diff --git a/.gitattributes b/.gitattributes index b9bebaea5b9f8ad2ee2201cbfa92677d3a12c840..83211371402d6ce6b019154a3d962e4280283eea 100644 --- a/.gitattributes +++ b/.gitattributes @@ -493,3 +493,36 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/sympy/stats/__pycache__/crv_types.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/sympy/stats/__pycache__/stochastic_process_types.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_continuous_rv.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/sympy/tensor/__pycache__/tensor.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/array_expressions.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/test_tensor.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/iterables.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_lambdify.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_wester.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/tests/__pycache__/test_python.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/__pycache__/_meta_registrations.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor_docs.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/__pycache__/_torch_docs.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/__pycache__/overrides.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/decompositions.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/convert_frame.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/eval_frame.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/guards.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/output_graph.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/symbolic_convert.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/trace_rules.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/utils.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/base.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/builder.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/builtin.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/functions.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/higher_order_ops.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/lists.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/misc.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/tensor.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/torch.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/user_defined.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/serialize.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/partitioners.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/runtime_wrappers.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/.venv/lib/python3.12/site-packages/sympy-1.14.0.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/sympy-1.14.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy-1.14.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/sympy-1.14.0.dist-info/METADATA b/.venv/lib/python3.12/site-packages/sympy-1.14.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..5883009e816c08a2672bc24096295aa8b3252a51 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy-1.14.0.dist-info/METADATA @@ -0,0 +1,319 @@ +Metadata-Version: 2.4 +Name: sympy +Version: 1.14.0 +Summary: Computer algebra system (CAS) in Python +Home-page: https://sympy.org +Author: SymPy development team +Author-email: sympy@googlegroups.com +License: BSD +Project-URL: Source, https://github.com/sympy/sympy +Keywords: Math CAS +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Scientific/Engineering :: Mathematics +Classifier: Topic :: Scientific/Engineering :: Physics +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +License-File: LICENSE +License-File: AUTHORS +Requires-Dist: mpmath<1.4,>=1.1.0 +Provides-Extra: dev +Requires-Dist: pytest>=7.1.0; extra == "dev" +Requires-Dist: hypothesis>=6.70.0; extra == "dev" +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 + +# SymPy + +[![pypi version](https://img.shields.io/pypi/v/sympy.svg)](https://pypi.python.org/pypi/sympy) +[![Join the chat at https://gitter.im/sympy/sympy](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/sympy/sympy?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +[![Zenodo Badge](https://zenodo.org/badge/18918/sympy/sympy.svg)](https://zenodo.org/badge/latestdoi/18918/sympy/sympy) +[![Downloads](https://pepy.tech/badge/sympy/month)](https://pepy.tech/project/sympy) +[![GitHub Issues](https://img.shields.io/badge/issue_tracking-github-blue.svg)](https://github.com/sympy/sympy/issues) +[![Git Tutorial](https://img.shields.io/badge/PR-Welcome-%23FF8300.svg?)](https://git-scm.com/book/en/v2/GitHub-Contributing-to-a-Project) +[![Powered by NumFocus](https://img.shields.io/badge/powered%20by-NumFOCUS-orange.svg?style=flat&colorA=E1523D&colorB=007D8A)](https://numfocus.org) +[![Commits since last release](https://img.shields.io/github/commits-since/sympy/sympy/latest.svg?longCache=true&style=flat-square&logo=git&logoColor=fff)](https://github.com/sympy/sympy/releases) + +[![SymPy Banner](https://github.com/sympy/sympy/raw/master/banner.svg)](https://sympy.org/) + + +See the [AUTHORS](AUTHORS) file for the list of authors. + +And many more people helped on the SymPy mailing list, reported bugs, +helped organize SymPy's participation in the Google Summer of Code, the +Google Highly Open Participation Contest, Google Code-In, wrote and +blogged about SymPy... + +License: New BSD License (see the [LICENSE](LICENSE) file for details) covers all +files in the sympy repository unless stated otherwise. + +Our mailing list is at +. + +We have a community chat at [Gitter](https://gitter.im/sympy/sympy). Feel +free to ask us anything there. We have a very welcoming and helpful +community. + +## Download + +The recommended installation method is through Anaconda, + + +You can also get the latest version of SymPy from + + +To get the git version do + + $ git clone https://github.com/sympy/sympy.git + +For other options (tarballs, debs, etc.), see +. + +## Documentation and Usage + +For in-depth instructions on installation and building the +documentation, see the [SymPy Documentation Style Guide](https://docs.sympy.org/dev/documentation-style-guide.html). + +Everything is at: + + + +You can generate everything at the above site in your local copy of +SymPy by: + + $ cd doc + $ make html + +Then the docs will be in \_build/html. If +you don't want to read that, here is a short usage: + +From this directory, start Python and: + +``` python +>>> from sympy import Symbol, cos +>>> x = Symbol('x') +>>> e = 1/cos(x) +>>> print(e.series(x, 0, 10)) +1 + x**2/2 + 5*x**4/24 + 61*x**6/720 + 277*x**8/8064 + O(x**10) +``` + +SymPy also comes with a console that is a simple wrapper around the +classic python console (or IPython when available) that loads the SymPy +namespace and executes some common commands for you. + +To start it, issue: + + $ bin/isympy + +from this directory, if SymPy is not installed or simply: + + $ isympy + +if SymPy is installed. + +## Installation + +To install SymPy using PyPI, run the following command: + + $ pip install sympy + +To install SymPy using Anaconda, run the following command: + + $ conda install -c anaconda sympy + +To install SymPy from GitHub source, first clone SymPy using `git`: + + $ git clone https://github.com/sympy/sympy.git + +Then, in the `sympy` repository that you cloned, simply run: + + $ pip install . + +See for more information. + +## Contributing + +We welcome contributions from anyone, even if you are new to open +source. Please read our [Introduction to Contributing](https://docs.sympy.org/dev/contributing/introduction-to-contributing.html) +page and the [SymPy Documentation Style Guide](https://docs.sympy.org/dev/documentation-style-guide.html). If you +are new and looking for some way to contribute, a good place to start is +to look at the issues tagged [Easy to Fix](https://github.com/sympy/sympy/issues?q=is%3Aopen+is%3Aissue+label%3A%22Easy+to+Fix%22). + +Please note that all participants in this project are expected to follow +our Code of Conduct. By participating in this project you agree to abide +by its terms. See [CODE\_OF\_CONDUCT.md](CODE_OF_CONDUCT.md). + +## Tests + +To execute all tests, run: + + $./setup.py test + +in the current directory. + +For the more fine-grained running of tests or doctests, use `bin/test` +or respectively `bin/doctest`. The master branch is automatically tested +by GitHub Actions. + +To test pull requests, use +[sympy-bot](https://github.com/sympy/sympy-bot). + +## Regenerate Experimental LaTeX Parser/Lexer + +The parser and lexer were generated with the [ANTLR4](http://antlr4.org) +toolchain in `sympy/parsing/latex/_antlr` and checked into the repo. +Presently, most users should not need to regenerate these files, but +if you plan to work on this feature, you will need the `antlr4` +command-line tool (and you must ensure that it is in your `PATH`). +One way to get it is: + + $ conda install -c conda-forge antlr=4.11.1 + +Alternatively, follow the instructions on the ANTLR website and download +the `antlr-4.11.1-complete.jar`. Then export the `CLASSPATH` as instructed +and instead of creating `antlr4` as an alias, make it an executable file +with the following contents: +``` bash +#!/bin/bash +java -jar /usr/local/lib/antlr-4.11.1-complete.jar "$@" +``` + +After making changes to `sympy/parsing/latex/LaTeX.g4`, run: + + $ ./setup.py antlr + +## Clean + +To clean everything (thus getting the same tree as in the repository): + + $ git clean -Xdf + +which will clear everything ignored by `.gitignore`, and: + + $ git clean -df + +to clear all untracked files. You can revert the most recent changes in +git with: + + $ git reset --hard + +WARNING: The above commands will all clear changes you may have made, +and you will lose them forever. Be sure to check things with `git +status`, `git diff`, `git clean -Xn`, and `git clean -n` before doing any +of those. + +## Bugs + +Our issue tracker is at . Please +report any bugs that you find. Or, even better, fork the repository on +GitHub and create a pull request. We welcome all changes, big or small, +and we will help you make the pull request if you are new to git (just +ask on our mailing list or Gitter Channel). If you further have any queries, you can find answers +on Stack Overflow using the [sympy](https://stackoverflow.com/questions/tagged/sympy) tag. + +## Brief History + +SymPy was started by Ondřej Čertík in 2005, he wrote some code during +the summer, then he wrote some more code during summer 2006. In February +2007, Fabian Pedregosa joined the project and helped fix many things, +contributed documentation, and made it alive again. 5 students (Mateusz +Paprocki, Brian Jorgensen, Jason Gedge, Robert Schwarz, and Chris Wu) +improved SymPy incredibly during summer 2007 as part of the Google +Summer of Code. Pearu Peterson joined the development during the summer +2007 and he has made SymPy much more competitive by rewriting the core +from scratch, which has made it from 10x to 100x faster. Jurjen N.E. Bos +has contributed pretty-printing and other patches. Fredrik Johansson has +written mpmath and contributed a lot of patches. + +SymPy has participated in every Google Summer of Code since 2007. You +can see for +full details. Each year has improved SymPy by bounds. Most of SymPy's +development has come from Google Summer of Code students. + +In 2011, Ondřej Čertík stepped down as lead developer, with Aaron +Meurer, who also started as a Google Summer of Code student, taking his +place. Ondřej Čertík is still active in the community but is too busy +with work and family to play a lead development role. + +Since then, a lot more people have joined the development and some +people have also left. You can see the full list in doc/src/aboutus.rst, +or online at: + + + +The git history goes back to 2007 when development moved from svn to hg. +To see the history before that point, look at +. + +You can use git to see the biggest developers. The command: + + $ git shortlog -ns + +will show each developer, sorted by commits to the project. The command: + + $ git shortlog -ns --since="1 year" + +will show the top developers from the last year. + +## Citation + +To cite SymPy in publications use + +> Meurer A, Smith CP, Paprocki M, Čertík O, Kirpichev SB, Rocklin M, +> Kumar A, Ivanov S, Moore JK, Singh S, Rathnayake T, Vig S, Granger BE, +> Muller RP, Bonazzi F, Gupta H, Vats S, Johansson F, Pedregosa F, Curry +> MJ, Terrel AR, Roučka Š, Saboo A, Fernando I, Kulal S, Cimrman R, +> Scopatz A. (2017) SymPy: symbolic computing in Python. *PeerJ Computer +> Science* 3:e103 + +A BibTeX entry for LaTeX users is + +``` bibtex +@article{10.7717/peerj-cs.103, + title = {SymPy: symbolic computing in Python}, + author = {Meurer, Aaron and Smith, Christopher P. and Paprocki, Mateusz and \v{C}ert\'{i}k, Ond\v{r}ej and Kirpichev, Sergey B. and Rocklin, Matthew and Kumar, Amit and Ivanov, Sergiu and Moore, Jason K. and Singh, Sartaj and Rathnayake, Thilina and Vig, Sean and Granger, Brian E. and Muller, Richard P. and Bonazzi, Francesco and Gupta, Harsh and Vats, Shivam and Johansson, Fredrik and Pedregosa, Fabian and Curry, Matthew J. and Terrel, Andy R. and Rou\v{c}ka, \v{S}t\v{e}p\'{a}n and Saboo, Ashutosh and Fernando, Isuru and Kulal, Sumith and Cimrman, Robert and Scopatz, Anthony}, + year = 2017, + month = Jan, + keywords = {Python, Computer algebra system, Symbolics}, + abstract = { + SymPy is an open-source computer algebra system written in pure Python. It is built with a focus on extensibility and ease of use, through both interactive and programmatic applications. These characteristics have led SymPy to become a popular symbolic library for the scientific Python ecosystem. This paper presents the architecture of SymPy, a description of its features, and a discussion of select submodules. The supplementary material provides additional examples and further outlines details of the architecture and features of SymPy. + }, + volume = 3, + pages = {e103}, + journal = {PeerJ Computer Science}, + issn = {2376-5992}, + url = {https://doi.org/10.7717/peerj-cs.103}, + doi = {10.7717/peerj-cs.103} +} +``` + +SymPy is BSD licensed, so you are free to use it whatever you like, be +it academic, commercial, creating forks or derivatives, as long as you +copy the BSD statement if you redistribute it (see the LICENSE file for +details). That said, although not required by the SymPy license, if it +is convenient for you, please cite SymPy when using it in your work and +also consider contributing all your changes back, so that we can +incorporate it and all of us will benefit in the end. diff --git a/.venv/lib/python3.12/site-packages/sympy-1.14.0.dist-info/RECORD b/.venv/lib/python3.12/site-packages/sympy-1.14.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..a31b1622a83ebdc80916d72478b306930e36bd5e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy-1.14.0.dist-info/RECORD @@ -0,0 +1,3105 @@ +../../../bin/isympy,sha256=M5AMTJqv7K9QGHtadgn4UEjCuxX_dVdwJ1MXAq8NAuA,237 +../../../share/man/man1/isympy.1,sha256=9DZdSOIQLikrATHlbkdDZ04LBQigZDUE0_oCXBDvdBs,6659 +__pycache__/isympy.cpython-312.pyc,, +isympy.py,sha256=haEArczb_Ny-LyjOCwx2FNGal_S0Mo4d0deiWL2g_Gc,11220 +sympy-1.14.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +sympy-1.14.0.dist-info/METADATA,sha256=t1bC-_1b4FrFvbDrymH1VhjzD2M-2S2IpWh0KTE6dZU,12816 +sympy-1.14.0.dist-info/RECORD,, +sympy-1.14.0.dist-info/WHEEL,sha256=SmOxYU7pzNKBqASvQJ7DjX3XGUF92lrGhMb3R6_iiqI,91 +sympy-1.14.0.dist-info/entry_points.txt,sha256=Sp-vLJom4PRlhGfY6RpUre7SjYm33JNq9NCwCGeW-fQ,39 +sympy-1.14.0.dist-info/licenses/AUTHORS,sha256=grEDhSGwaWxjyQsx7UoKLJxMFoccZIsVewfKRLbxj40,55779 +sympy-1.14.0.dist-info/licenses/LICENSE,sha256=B6XpgZ9ye0mGrSgpx6KaYyDUJXX3IOsk1xt_71c6AoY,7885 +sympy-1.14.0.dist-info/top_level.txt,sha256=elXb5xfjLdjgSSoQFk4_2Qu3lp2CIaglF9MQtfIoH7o,13 +sympy/__init__.py,sha256=TpR2NIuhBf6rKNgvW89s26Lj6E3m4Fm7_noTcowKSrA,29422 +sympy/__pycache__/__init__.cpython-312.pyc,, +sympy/__pycache__/abc.cpython-312.pyc,, +sympy/__pycache__/conftest.cpython-312.pyc,, +sympy/__pycache__/galgebra.cpython-312.pyc,, +sympy/__pycache__/release.cpython-312.pyc,, +sympy/__pycache__/this.cpython-312.pyc,, +sympy/abc.py,sha256=-RYLRKQ6SZMJGXDIAOP9UWPDAyvYH0zPbp9ZFg0YKBY,3764 +sympy/algebras/__init__.py,sha256=7PRGOW30nlMOTeUPR7iy8l5xGoE2yCBEfRbjqDKWOgU,62 +sympy/algebras/__pycache__/__init__.cpython-312.pyc,, +sympy/algebras/__pycache__/quaternion.cpython-312.pyc,, +sympy/algebras/quaternion.py,sha256=i2Fkvjj14vA6GtXgcSkpDwVmIYc7T5zT1hw49sb__tM,47483 +sympy/algebras/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/algebras/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/algebras/tests/__pycache__/test_quaternion.cpython-312.pyc,, +sympy/algebras/tests/test_quaternion.py,sha256=un4I6IKE2v6YEfUsFBSY5N6qaZ0agn1puX0LElb1k4E,16809 +sympy/assumptions/__init__.py,sha256=PFS8djTqiNbGVMjg7PaPjEfwmjyZVfioXiRVzqqA3E0,550 +sympy/assumptions/__pycache__/__init__.cpython-312.pyc,, +sympy/assumptions/__pycache__/ask.cpython-312.pyc,, +sympy/assumptions/__pycache__/ask_generated.cpython-312.pyc,, +sympy/assumptions/__pycache__/assume.cpython-312.pyc,, +sympy/assumptions/__pycache__/cnf.cpython-312.pyc,, +sympy/assumptions/__pycache__/facts.cpython-312.pyc,, +sympy/assumptions/__pycache__/lra_satask.cpython-312.pyc,, +sympy/assumptions/__pycache__/refine.cpython-312.pyc,, +sympy/assumptions/__pycache__/satask.cpython-312.pyc,, +sympy/assumptions/__pycache__/sathandlers.cpython-312.pyc,, +sympy/assumptions/__pycache__/wrapper.cpython-312.pyc,, +sympy/assumptions/ask.py,sha256=B2W8CW-9ynvYqfBX9_4qCLhCSwE0g_gUGqq7lM50wUk,19376 +sympy/assumptions/ask_generated.py,sha256=whNIU5tj2UkEGHPAfk-_89ahvVERs4npOB0JYVbIQJc,23558 +sympy/assumptions/assume.py,sha256=_gcFc4h_YGs9-tshoD0gmLl_RtPivDQWMWhWWLX9seo,14606 +sympy/assumptions/cnf.py,sha256=mfthFXL8Jhpn7Vgj1IfG5acFzfBgaV02xztQ7KpoLmg,12509 +sympy/assumptions/facts.py,sha256=fimPoHEyusSUr0uI4kiDb4mzxHjEBglvLQW0DGdNFAs,8391 +sympy/assumptions/handlers/__init__.py,sha256=lvjAfPdz0MDjTxjuzbBSGBco2OmpZRiGixSG0oaiZi0,330 +sympy/assumptions/handlers/__pycache__/__init__.cpython-312.pyc,, +sympy/assumptions/handlers/__pycache__/calculus.cpython-312.pyc,, +sympy/assumptions/handlers/__pycache__/common.cpython-312.pyc,, +sympy/assumptions/handlers/__pycache__/matrices.cpython-312.pyc,, +sympy/assumptions/handlers/__pycache__/ntheory.cpython-312.pyc,, +sympy/assumptions/handlers/__pycache__/order.cpython-312.pyc,, +sympy/assumptions/handlers/__pycache__/sets.cpython-312.pyc,, +sympy/assumptions/handlers/calculus.py,sha256=WF3gysxZa2frvd1kHxdDN7xd0PwYemER8dWutfDN-w8,7799 +sympy/assumptions/handlers/common.py,sha256=xgUR3xHPNgGFkLGyMqLV_nUIfMsQJLP8p6boy8Rc6JI,4314 +sympy/assumptions/handlers/matrices.py,sha256=Gdauk2xk1hKPRr4i6RpvOMHtDnyVD34x1OyhL-Oh8Hc,22321 +sympy/assumptions/handlers/ntheory.py,sha256=lRhW2ceJPK0gNqR00NAwkEq1FBjtRrxz1u6WevjRvjc,7660 +sympy/assumptions/handlers/order.py,sha256=-NCLn8ab7Fo_UzZLZi7m3UwtYGN-XiU1qvJDhi5z7ZQ,12280 +sympy/assumptions/handlers/sets.py,sha256=9P8X6ucARJIJA3jG_gj736L71ZQi5hfLCKL--0_ifrw,25841 +sympy/assumptions/lra_satask.py,sha256=FlmiLERsj6J9w6vygwEEEn7pyGPnD0JkPEFEdoE7bfM,9563 +sympy/assumptions/predicates/__init__.py,sha256=q1C7iWpvdDymEUZNyzJvZLsLtgwSkYtCixME-fYyIDw,110 +sympy/assumptions/predicates/__pycache__/__init__.cpython-312.pyc,, +sympy/assumptions/predicates/__pycache__/calculus.cpython-312.pyc,, +sympy/assumptions/predicates/__pycache__/common.cpython-312.pyc,, +sympy/assumptions/predicates/__pycache__/matrices.cpython-312.pyc,, +sympy/assumptions/predicates/__pycache__/ntheory.cpython-312.pyc,, +sympy/assumptions/predicates/__pycache__/order.cpython-312.pyc,, +sympy/assumptions/predicates/__pycache__/sets.cpython-312.pyc,, +sympy/assumptions/predicates/calculus.py,sha256=vFnlYVYZVd6D9OwA7-3bDK_Q0jf2iCZCZiMlWenw0Vg,1889 +sympy/assumptions/predicates/common.py,sha256=zpByACpa_tF0nVNB0J_rJehnXkHtkxhchn1DvkVVS-s,2279 +sympy/assumptions/predicates/matrices.py,sha256=X3vbkEf3zwJLyanEjf6ijYXuRfFfSv-yatl1tJ25wDk,12142 +sympy/assumptions/predicates/ntheory.py,sha256=wvFNFSf0S4egbY7REw0V0ANC03CuiRU9PLmdi16VfHo,2546 +sympy/assumptions/predicates/order.py,sha256=ez1UZ824KDtimLssUASCZHD_KEQmo8Pv-qofVLhZUrk,9511 +sympy/assumptions/predicates/sets.py,sha256=-bTVXa-X1-yfXlIKzMBW_JxIqueS5PdEwEzChzIne38,9238 +sympy/assumptions/refine.py,sha256=FNv5neAYJh-MgvnHDZ8-tjC9RIKcIxarVj5WiE4EnYg,11946 +sympy/assumptions/relation/__init__.py,sha256=t2tZNEIK7w-xXshRQIRL8tIyiNe1W5fMhN7QNRPnQFo,261 +sympy/assumptions/relation/__pycache__/__init__.cpython-312.pyc,, +sympy/assumptions/relation/__pycache__/binrel.cpython-312.pyc,, +sympy/assumptions/relation/__pycache__/equality.cpython-312.pyc,, +sympy/assumptions/relation/binrel.py,sha256=3iwnSEE53-vRsPv-bOnjydgOkCpbB12FTFR_sQ3CwvE,6313 +sympy/assumptions/relation/equality.py,sha256=ZBnSFpctNeroYy1nvam0kzSJCNpsUR3SlBeqFcAMM0U,7148 +sympy/assumptions/satask.py,sha256=P3iprPjuOyhT5Fwr0hX61xTOcD98M_bzXSAV-pXYhN4,11745 +sympy/assumptions/sathandlers.py,sha256=jx8B0u_N73fMoVoLKIfmXMdtSLz7-ZIKhJrxYl84AJk,9418 +sympy/assumptions/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/assumptions/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/assumptions/tests/__pycache__/test_assumptions_2.cpython-312.pyc,, +sympy/assumptions/tests/__pycache__/test_context.cpython-312.pyc,, +sympy/assumptions/tests/__pycache__/test_matrices.cpython-312.pyc,, +sympy/assumptions/tests/__pycache__/test_query.cpython-312.pyc,, +sympy/assumptions/tests/__pycache__/test_refine.cpython-312.pyc,, +sympy/assumptions/tests/__pycache__/test_rel_queries.cpython-312.pyc,, +sympy/assumptions/tests/__pycache__/test_satask.cpython-312.pyc,, +sympy/assumptions/tests/__pycache__/test_sathandlers.cpython-312.pyc,, +sympy/assumptions/tests/__pycache__/test_wrapper.cpython-312.pyc,, +sympy/assumptions/tests/test_assumptions_2.py,sha256=oNgIDOoW-GpBbXxbtw05SWnE8I7sGislYmB3MDogwB4,1070 +sympy/assumptions/tests/test_context.py,sha256=I5gES7AY9_vz1-CEaCchy4MXABtX85ncNkvoRuLskG8,1153 +sympy/assumptions/tests/test_matrices.py,sha256=nzSofuawc18hNe9Nj0dN_lTeDwa2KbPjt4K2rvb3xmw,12258 +sympy/assumptions/tests/test_query.py,sha256=ENB3XoNNi7j0p1_-j9Xd9C5YYpRbu1dcAQe46foV8cU,104495 +sympy/assumptions/tests/test_refine.py,sha256=bHxYUnCOEIzA1yPU3B2xbU9JZfhDv6RkmPm8esetisQ,8834 +sympy/assumptions/tests/test_rel_queries.py,sha256=fRn_IMMb942GfEH8CNk6z50YCyDlA_GMXv2xOVFdSdk,6677 +sympy/assumptions/tests/test_satask.py,sha256=IIqqIxzkLfANpTNBKEsCGCp3Bm8zmDnYd23woqKh9EE,15741 +sympy/assumptions/tests/test_sathandlers.py,sha256=jMCZQb3G6pVQ5MHaSTWV_0eULHaCF8Mowu12Ll72rgs,1842 +sympy/assumptions/tests/test_wrapper.py,sha256=iE32j83rrerCz85HHt2hTolgJkqb44KddfEpI3H1Fb8,1159 +sympy/assumptions/wrapper.py,sha256=7GXR39zPCCfV-pcs8ph9KRRwZF3i_T5Lzv156vKFf_I,5434 +sympy/benchmarks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/benchmarks/__pycache__/__init__.cpython-312.pyc,, +sympy/benchmarks/__pycache__/bench_discrete_log.cpython-312.pyc,, +sympy/benchmarks/__pycache__/bench_meijerint.cpython-312.pyc,, +sympy/benchmarks/__pycache__/bench_symbench.cpython-312.pyc,, +sympy/benchmarks/bench_discrete_log.py,sha256=CNchIJ5HFMPpNlVZh2vOU0GgQ3bse6hqyqDovpDHlKE,2473 +sympy/benchmarks/bench_meijerint.py,sha256=dSNdZhoc8a4h50wRtbOxLwpmgUiuMFpe6ytTLURcplY,11610 +sympy/benchmarks/bench_symbench.py,sha256=UMD3eYf_Poht0qxjdH2_axGwwON6cZo1Sp700Ci1M1M,2997 +sympy/calculus/__init__.py,sha256=IWDc6qPbEcWyTm9QM6V8vSAs-5OtGNijimykoWz3Clc,828 +sympy/calculus/__pycache__/__init__.cpython-312.pyc,, +sympy/calculus/__pycache__/accumulationbounds.cpython-312.pyc,, +sympy/calculus/__pycache__/euler.cpython-312.pyc,, +sympy/calculus/__pycache__/finite_diff.cpython-312.pyc,, +sympy/calculus/__pycache__/singularities.cpython-312.pyc,, +sympy/calculus/__pycache__/util.cpython-312.pyc,, +sympy/calculus/accumulationbounds.py,sha256=4nJD5JzBarlB5l6yPpVADX3iDamnHVwsor_nQJw9CAM,28682 +sympy/calculus/euler.py,sha256=0QrHD9TYKlSZuO8drnU3bUFJrSu8v5SncqtkRSWLjGM,3436 +sympy/calculus/finite_diff.py,sha256=X7qZJ5GmHlHKokUUMFoaQqrqX2jLRq4b7W2G5aWntzM,17053 +sympy/calculus/singularities.py,sha256=wBQ7WiJ1amuZStBJ-iMTiIHJexjzJHHwrc0tU2XVT10,12184 +sympy/calculus/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/calculus/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/calculus/tests/__pycache__/test_accumulationbounds.cpython-312.pyc,, +sympy/calculus/tests/__pycache__/test_euler.cpython-312.pyc,, +sympy/calculus/tests/__pycache__/test_finite_diff.cpython-312.pyc,, +sympy/calculus/tests/__pycache__/test_singularities.cpython-312.pyc,, +sympy/calculus/tests/__pycache__/test_util.cpython-312.pyc,, +sympy/calculus/tests/test_accumulationbounds.py,sha256=a_Ry2nKX5WbhSe1Bk2k0W6-VWOpVTg0FnA9u8rNSIV4,11195 +sympy/calculus/tests/test_euler.py,sha256=YWpts4pWSiYEwRsi5DLQ16JgC9109-9NKZIL_IO6_Aw,2683 +sympy/calculus/tests/test_finite_diff.py,sha256=9mIvXB8DaxJh2gzmhwi5eE3eBRYTFxyqYG5uIUpYg2w,7670 +sympy/calculus/tests/test_singularities.py,sha256=Zj4WPkT-KlXo7TF3Ir3ug3IkS_qhnFBS7VXAMnIuCso,5272 +sympy/calculus/tests/test_util.py,sha256=IJIhgudR9dym1VRAdu33G2tfSDoexNdWdz-Pgf-kh4o,18557 +sympy/calculus/util.py,sha256=qBDTlb5VP-xJPfh2Ndz37zNMVpseXW4d77hxBCLX5AA,28880 +sympy/categories/__init__.py,sha256=XiKBVC6pbDED-OVtNlSH-fGB8dB_jWLqwCEO7wBTAyA,984 +sympy/categories/__pycache__/__init__.cpython-312.pyc,, +sympy/categories/__pycache__/baseclasses.cpython-312.pyc,, +sympy/categories/__pycache__/diagram_drawing.cpython-312.pyc,, +sympy/categories/baseclasses.py,sha256=1Kn7PIegQCbF78s0rhf1Bx1mbxwfQcfQi6v-QqloSoE,31360 +sympy/categories/diagram_drawing.py,sha256=lfR29f6QX-rK-cCAom-2mRJ4xLyhi55ch91CyEPCXAQ,95173 +sympy/categories/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/categories/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/categories/tests/__pycache__/test_baseclasses.cpython-312.pyc,, +sympy/categories/tests/__pycache__/test_drawing.cpython-312.pyc,, +sympy/categories/tests/test_baseclasses.py,sha256=SwD6QsfSlrEdpD2dbkcN62CPVIRP5SadjCplLrMAoa8,5767 +sympy/categories/tests/test_drawing.py,sha256=IELPpadmnQyQ2x5a5qHC8ioq5kfT1UnAl4h1vO3gbqg,27848 +sympy/codegen/__init__.py,sha256=sQcJsyLyoRh9ccOPhv2eZ-wHjQrArByOON9ndj-MYgQ,974 +sympy/codegen/__pycache__/__init__.cpython-312.pyc,, +sympy/codegen/__pycache__/abstract_nodes.cpython-312.pyc,, +sympy/codegen/__pycache__/algorithms.cpython-312.pyc,, +sympy/codegen/__pycache__/approximations.cpython-312.pyc,, +sympy/codegen/__pycache__/ast.cpython-312.pyc,, +sympy/codegen/__pycache__/cfunctions.cpython-312.pyc,, +sympy/codegen/__pycache__/cnodes.cpython-312.pyc,, +sympy/codegen/__pycache__/cutils.cpython-312.pyc,, +sympy/codegen/__pycache__/cxxnodes.cpython-312.pyc,, +sympy/codegen/__pycache__/fnodes.cpython-312.pyc,, +sympy/codegen/__pycache__/futils.cpython-312.pyc,, +sympy/codegen/__pycache__/matrix_nodes.cpython-312.pyc,, +sympy/codegen/__pycache__/numpy_nodes.cpython-312.pyc,, +sympy/codegen/__pycache__/pynodes.cpython-312.pyc,, +sympy/codegen/__pycache__/pyutils.cpython-312.pyc,, +sympy/codegen/__pycache__/rewriting.cpython-312.pyc,, +sympy/codegen/__pycache__/scipy_nodes.cpython-312.pyc,, +sympy/codegen/abstract_nodes.py,sha256=TY4ecftqnym5viYInnb59zGPPFXdeSGQwi--xTz6Pvo,490 +sympy/codegen/algorithms.py,sha256=GEvnadOTZ3afVrbN5WE52OhCP8gzMII_AN4oHQxvEpo,6383 +sympy/codegen/approximations.py,sha256=r7zyShIWp40QngshFQwqKVKWcA5KmHmQcJarXVtOATQ,6448 +sympy/codegen/ast.py,sha256=R_JhC-uryx9NoJ1ISQU6fb3aV4aRL1SModmV_Dc2z2U,56788 +sympy/codegen/cfunctions.py,sha256=jrFWaRjrQnpHzu6-mwFtd6cRspK8Jo7B3RDo1AOoTLo,12331 +sympy/codegen/cnodes.py,sha256=lsqy-JeRvr9WCk2fwDiRqPhAMFk0snInF7WlAlk9-Zg,3409 +sympy/codegen/cutils.py,sha256=vlzMs8OkC5Bu4sIP-AF2mYf_tIo7Uo4r2DAI_LNhZzM,383 +sympy/codegen/cxxnodes.py,sha256=Om-EBfYduFF97tgXOF68rr8zYbngem9kBRm9SJiKLSM,342 +sympy/codegen/fnodes.py,sha256=mdOPkMVmjjNp22XfHscvx8uMtUxbUqTl66Wki7ORMa8,18936 +sympy/codegen/futils.py,sha256=k-mxMJKr_Q_afTy6NrKNl_N2XQLBmSdZAssO5hBonNY,1792 +sympy/codegen/matrix_nodes.py,sha256=0d3qXy2zaq3isyklE48lP7NP5LTF7SkLXMHMbweVGXU,2284 +sympy/codegen/numpy_nodes.py,sha256=H6FoBnarEuO7R1sbX8Qa9hK4jCju90R2qN66_-1N6Ug,4543 +sympy/codegen/pynodes.py,sha256=Neo1gFQ9kC31T-gH8TeeCaDDNaDe5deIP97MRZFgMHk,243 +sympy/codegen/pyutils.py,sha256=HfF6SP710Y7yExZcSesI0usVaDiWdEPEmMtyMD3JtOY,838 +sympy/codegen/rewriting.py,sha256=8JtiMFgv0sA7uGu2MUU7L3uzldGw5xG1ksuk4zh2ZDE,11585 +sympy/codegen/scipy_nodes.py,sha256=hYlxtGyTM0Z64Nazm1TeMZ3Y8dMsiD_HNhNvbU9eiQY,2508 +sympy/codegen/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/codegen/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/codegen/tests/__pycache__/test_abstract_nodes.cpython-312.pyc,, +sympy/codegen/tests/__pycache__/test_algorithms.cpython-312.pyc,, +sympy/codegen/tests/__pycache__/test_applications.cpython-312.pyc,, +sympy/codegen/tests/__pycache__/test_approximations.cpython-312.pyc,, +sympy/codegen/tests/__pycache__/test_ast.cpython-312.pyc,, +sympy/codegen/tests/__pycache__/test_cfunctions.cpython-312.pyc,, +sympy/codegen/tests/__pycache__/test_cnodes.cpython-312.pyc,, +sympy/codegen/tests/__pycache__/test_cxxnodes.cpython-312.pyc,, +sympy/codegen/tests/__pycache__/test_fnodes.cpython-312.pyc,, +sympy/codegen/tests/__pycache__/test_matrix_nodes.cpython-312.pyc,, +sympy/codegen/tests/__pycache__/test_numpy_nodes.cpython-312.pyc,, +sympy/codegen/tests/__pycache__/test_pynodes.cpython-312.pyc,, +sympy/codegen/tests/__pycache__/test_pyutils.cpython-312.pyc,, +sympy/codegen/tests/__pycache__/test_rewriting.cpython-312.pyc,, +sympy/codegen/tests/__pycache__/test_scipy_nodes.cpython-312.pyc,, +sympy/codegen/tests/test_abstract_nodes.py,sha256=a_GKf3FpeNN8zfMc-V8AaSrQtEI1oiLfJOco2VKiSKI,451 +sympy/codegen/tests/test_algorithms.py,sha256=lgl6w3d7WaT8LJrp716wWicxbgnR4hQk4alzBCdDrIw,6919 +sympy/codegen/tests/test_applications.py,sha256=RFWS7EoE3DytUrr4HzkPaXbOtnaStpzJalVKrY1rVRE,2277 +sympy/codegen/tests/test_approximations.py,sha256=SZpOUzahb_bJOceD0DLdmeiw-jN37OPmf5TRp1dyRgM,2035 +sympy/codegen/tests/test_ast.py,sha256=aAWk-yAVVNAmFMkyUlYBbVA8mPlTFqULOtmXMEi3LO8,21688 +sympy/codegen/tests/test_cfunctions.py,sha256=4jJM7dCLPbfEU3CB1ZUKGC1pRuRvjqZfDkFfYSkrzsY,5119 +sympy/codegen/tests/test_cnodes.py,sha256=FlI5XP39K3kC1QWKQ-QKkzNQw8TROjj5mKXJhK1UU2c,3039 +sympy/codegen/tests/test_cxxnodes.py,sha256=5OwN8D_ZtKN9z5uNeUwbUkyAGzNLrTgIKUlcRWmOSpE,366 +sympy/codegen/tests/test_fnodes.py,sha256=dKSw6w7i4Z8NHVDu_ug4V9Fa49CfnSX1FVahDIdNPgI,6650 +sympy/codegen/tests/test_matrix_nodes.py,sha256=CTMSwQkW0JHaMgHR9Lys8kDk5UgQidTl4VQhWI8gw7s,1896 +sympy/codegen/tests/test_numpy_nodes.py,sha256=tEeyF9vDmw-EyKnHV2dYM6MWGfA2I2fmf3kBsYxqad0,2199 +sympy/codegen/tests/test_pynodes.py,sha256=Gso18KKzSwA-1AHC55SgHPAfH1GrGUCGaN6QR7iuEO0,432 +sympy/codegen/tests/test_pyutils.py,sha256=yvqif7d6EpsnaBjP8XXjVo3wEENBxI6Vm01I1Wow-js,299 +sympy/codegen/tests/test_rewriting.py,sha256=ELPziNI3CsJ4VS7mUbk4QWyG_94FbgZCdBKieMN20Vc,15852 +sympy/codegen/tests/test_scipy_nodes.py,sha256=LBWpjTRfgWN5NLTchLZEp6m7IMtu7HbiKoztLc6KNGY,1495 +sympy/combinatorics/__init__.py,sha256=Dx9xakpHuTIgy4G8zVjAY6pTu8J9_K3d_jKPizRMdVo,1500 +sympy/combinatorics/__pycache__/__init__.cpython-312.pyc,, +sympy/combinatorics/__pycache__/coset_table.cpython-312.pyc,, +sympy/combinatorics/__pycache__/fp_groups.cpython-312.pyc,, +sympy/combinatorics/__pycache__/free_groups.cpython-312.pyc,, +sympy/combinatorics/__pycache__/galois.cpython-312.pyc,, +sympy/combinatorics/__pycache__/generators.cpython-312.pyc,, +sympy/combinatorics/__pycache__/graycode.cpython-312.pyc,, +sympy/combinatorics/__pycache__/group_constructs.cpython-312.pyc,, +sympy/combinatorics/__pycache__/group_numbers.cpython-312.pyc,, +sympy/combinatorics/__pycache__/homomorphisms.cpython-312.pyc,, +sympy/combinatorics/__pycache__/named_groups.cpython-312.pyc,, +sympy/combinatorics/__pycache__/partitions.cpython-312.pyc,, +sympy/combinatorics/__pycache__/pc_groups.cpython-312.pyc,, +sympy/combinatorics/__pycache__/perm_groups.cpython-312.pyc,, +sympy/combinatorics/__pycache__/permutations.cpython-312.pyc,, +sympy/combinatorics/__pycache__/polyhedron.cpython-312.pyc,, +sympy/combinatorics/__pycache__/prufer.cpython-312.pyc,, +sympy/combinatorics/__pycache__/rewritingsystem.cpython-312.pyc,, +sympy/combinatorics/__pycache__/rewritingsystem_fsm.cpython-312.pyc,, +sympy/combinatorics/__pycache__/schur_number.cpython-312.pyc,, +sympy/combinatorics/__pycache__/subsets.cpython-312.pyc,, +sympy/combinatorics/__pycache__/tensor_can.cpython-312.pyc,, +sympy/combinatorics/__pycache__/testutil.cpython-312.pyc,, +sympy/combinatorics/__pycache__/util.cpython-312.pyc,, +sympy/combinatorics/coset_table.py,sha256=soppBd8i6UV-sppdOzykfNE8evMeclU4l1TwfL5UlXI,43296 +sympy/combinatorics/fp_groups.py,sha256=0iLx7mtwxn1kjYFysgAzILAdtlS9e1VWPtWnszubhd8,47779 +sympy/combinatorics/free_groups.py,sha256=gt33RoIByKDZNaf661ay4pQMilPPMPY4hFNGIKi2ho0,39740 +sympy/combinatorics/galois.py,sha256=cpd2iHaSdim5-3-cqvk58YP-AuS6CvJeCdUWpiOdIZI,17867 +sympy/combinatorics/generators.py,sha256=UAdv0bvqtN6i9bfFgB873g-A-zssc0ZoiHckDOEI0M0,7479 +sympy/combinatorics/graycode.py,sha256=xbtr8AaFYb4SMmwUi7mf7913U87jH-XEYF_3pGZfj0o,11207 +sympy/combinatorics/group_constructs.py,sha256=IKx12_yWJqEQ7g-oBuAWd5VRLbCOWyL0LG4PQu43BS8,2021 +sympy/combinatorics/group_numbers.py,sha256=eOiK0RyVHewiGiPXHihfM7MIKlAlg7AhGnBL4f1D54M,9163 +sympy/combinatorics/homomorphisms.py,sha256=dCpmPM3V2ReRuYDdXDfdMTU3pt7zkjKBkYSF6X2MfE8,18844 +sympy/combinatorics/named_groups.py,sha256=zd_C9epKDrMG0drafGUcHuuJJkcMaDt1Nf2ik4NXNq8,8378 +sympy/combinatorics/partitions.py,sha256=ZXqVmVNjmauhMeiTWtCCqOP38b9MJg7UlBdZa-7aICQ,20841 +sympy/combinatorics/pc_groups.py,sha256=5AwEeYQCMdYcybhlEykvJZqEYtJQLgYbRxAnNQeajfE,21414 +sympy/combinatorics/perm_groups.py,sha256=sf0FfxmJ5uWCwlvzRD5m5HHduG5qqHzh3Y0n1Dax5Yo,184825 +sympy/combinatorics/permutations.py,sha256=nQoc4YgTeoT80eHkqetTBUxwAQQW40US2AnR2u4-E_k,87737 +sympy/combinatorics/polyhedron.py,sha256=-1y5GhorUK62_gJpn4tXTLye7BcG0hAup74waDQ8y2I,35928 +sympy/combinatorics/prufer.py,sha256=yN6d4w_ZVXNFhBoevA84gor4Xb5ttG529xbVgHxzKDo,12061 +sympy/combinatorics/rewritingsystem.py,sha256=cT1JrAuKj9rWI3IhaHekYYt0rdG56pwFLg32pcGC9aI,17095 +sympy/combinatorics/rewritingsystem_fsm.py,sha256=CKGhLqyvxY0mlmy8_Hb4WzkSdWYPUaU2yZYhz-0iZ5w,2433 +sympy/combinatorics/schur_number.py,sha256=YdsyA7n_z9tyfRTSRfIjEjtnGo5EuDGBMUS09AQ2MxU,4437 +sympy/combinatorics/subsets.py,sha256=oxuExuGyFnvunkmktl-vBYiLbiN66A2Q2MyzwWfy46A,16047 +sympy/combinatorics/tensor_can.py,sha256=JywytVypkN6aWdCpeEYletMW4vxyUvU29RfKq9-Lu0c,40738 +sympy/combinatorics/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/combinatorics/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/combinatorics/tests/__pycache__/test_coset_table.cpython-312.pyc,, +sympy/combinatorics/tests/__pycache__/test_fp_groups.cpython-312.pyc,, +sympy/combinatorics/tests/__pycache__/test_free_groups.cpython-312.pyc,, +sympy/combinatorics/tests/__pycache__/test_galois.cpython-312.pyc,, +sympy/combinatorics/tests/__pycache__/test_generators.cpython-312.pyc,, +sympy/combinatorics/tests/__pycache__/test_graycode.cpython-312.pyc,, +sympy/combinatorics/tests/__pycache__/test_group_constructs.cpython-312.pyc,, +sympy/combinatorics/tests/__pycache__/test_group_numbers.cpython-312.pyc,, +sympy/combinatorics/tests/__pycache__/test_homomorphisms.cpython-312.pyc,, +sympy/combinatorics/tests/__pycache__/test_named_groups.cpython-312.pyc,, +sympy/combinatorics/tests/__pycache__/test_partitions.cpython-312.pyc,, +sympy/combinatorics/tests/__pycache__/test_pc_groups.cpython-312.pyc,, +sympy/combinatorics/tests/__pycache__/test_perm_groups.cpython-312.pyc,, +sympy/combinatorics/tests/__pycache__/test_permutations.cpython-312.pyc,, +sympy/combinatorics/tests/__pycache__/test_polyhedron.cpython-312.pyc,, +sympy/combinatorics/tests/__pycache__/test_prufer.cpython-312.pyc,, +sympy/combinatorics/tests/__pycache__/test_rewriting.cpython-312.pyc,, +sympy/combinatorics/tests/__pycache__/test_schur_number.cpython-312.pyc,, +sympy/combinatorics/tests/__pycache__/test_subsets.cpython-312.pyc,, +sympy/combinatorics/tests/__pycache__/test_tensor_can.cpython-312.pyc,, +sympy/combinatorics/tests/__pycache__/test_testutil.cpython-312.pyc,, +sympy/combinatorics/tests/__pycache__/test_util.cpython-312.pyc,, +sympy/combinatorics/tests/test_coset_table.py,sha256=cEUF0OH6SNhN_kh069wMsq6h4eSVqbDLghrg2r9Ht48,28474 +sympy/combinatorics/tests/test_fp_groups.py,sha256=C4rWnSJyk7L6uZnI-kAYvtbfFXxba0o1XjpOTkWr97s,10203 +sympy/combinatorics/tests/test_free_groups.py,sha256=g47dnRsNXVG9lFcqppJyrGryGIUCw9dRASkcMa4QujA,6411 +sympy/combinatorics/tests/test_galois.py,sha256=w35JRx8lmlXCdzUBNdocgATPYWBOEZ6LH-tAxOPwCQ8,2763 +sympy/combinatorics/tests/test_generators.py,sha256=6YpOp0i5PRGtySPNZseQ8mjSXbwpfGfz0hDB4kfk40Q,3567 +sympy/combinatorics/tests/test_graycode.py,sha256=pI4e7Y615d5Bmmxui6fdEeyca6j6KSD0YmeychV6ORk,2800 +sympy/combinatorics/tests/test_group_constructs.py,sha256=jJLwMdhuUalKv4Aql9SzV2utK8Ex-IYdMecggr95pi8,450 +sympy/combinatorics/tests/test_group_numbers.py,sha256=spHwsvjzEDXsdAFxkrQYOnioTgtWoVF5K7k7FbgMvfg,4149 +sympy/combinatorics/tests/test_homomorphisms.py,sha256=UwBj5loCuZAiuvmqy5VAbwhCQTph8o6BzTaGrH0rzB4,3745 +sympy/combinatorics/tests/test_named_groups.py,sha256=tsuDVGv4iHGEZ0BVR87_ENhyAfZvFIl0M6Dv_HX1VoY,1931 +sympy/combinatorics/tests/test_partitions.py,sha256=oppszKJLLSpcEzHgespIveSmEC3fDZ0qkus1k7MBt4E,4097 +sympy/combinatorics/tests/test_pc_groups.py,sha256=wfkY_ilpG0XWrhaWMVK6r7yWMeXfM8WNTyti5oE9bdk,2728 +sympy/combinatorics/tests/test_perm_groups.py,sha256=70_AedMpr-YxiYDHHjw6fjvmYW7-YoznEGwUeGtJo0E,41195 +sympy/combinatorics/tests/test_permutations.py,sha256=E8J-WLCW2z9hTyTJcm1dsFgFXh8YAesIppYsXRu5pAs,20189 +sympy/combinatorics/tests/test_polyhedron.py,sha256=3SWkFQKeF-p1QWP4Iu9NIA1oTxAFo1BLRrrLerBFAhw,4180 +sympy/combinatorics/tests/test_prufer.py,sha256=OTJp0NxjiVswWkOuCIlnGFU2Gw4noRsrPpUJtp2XhEs,2649 +sympy/combinatorics/tests/test_rewriting.py,sha256=3COHq74k6knt2rqE7hfd4ZP_6whf0Kg14tYxFmTtYrI,1787 +sympy/combinatorics/tests/test_schur_number.py,sha256=wg13uTumFltWIGbVg_PEr6nhXIru19UWitsEZiakoRI,1727 +sympy/combinatorics/tests/test_subsets.py,sha256=6pyhLYV5HuXvx63r-gGVHr8LSrGRXcpDudhFn9fBqX8,2635 +sympy/combinatorics/tests/test_tensor_can.py,sha256=olH5D5wwTBOkZXjtqvLO6RKbvCG9KoMVK4__wDe95N4,24676 +sympy/combinatorics/tests/test_testutil.py,sha256=NYEI8X2qLWf7Gv1O7UthOHUSyWpbNCRrGmG_vdyEgF8,1733 +sympy/combinatorics/tests/test_util.py,sha256=sOYMWHxlbM0mqalqA7jNrYMm8DKcf_GwL5YBjs96_C4,4499 +sympy/combinatorics/testutil.py,sha256=GNnqy0mb6yPMa3zpGEzz2p6uxY7VtobPtwUialhfYEQ,11142 +sympy/combinatorics/util.py,sha256=lkOaITBImqB9yyLvN8DU0G-vraw27cSx2XaPdAPVBhg,16296 +sympy/concrete/__init__.py,sha256=2HDmg3VyLgM_ZPw3XsGpkOClGiQnyTlUNHSwVTtizA0,144 +sympy/concrete/__pycache__/__init__.cpython-312.pyc,, +sympy/concrete/__pycache__/delta.cpython-312.pyc,, +sympy/concrete/__pycache__/expr_with_intlimits.cpython-312.pyc,, +sympy/concrete/__pycache__/expr_with_limits.cpython-312.pyc,, +sympy/concrete/__pycache__/gosper.cpython-312.pyc,, +sympy/concrete/__pycache__/guess.cpython-312.pyc,, +sympy/concrete/__pycache__/products.cpython-312.pyc,, +sympy/concrete/__pycache__/summations.cpython-312.pyc,, +sympy/concrete/delta.py,sha256=38M0E24b6V-dn706WXnylM4DAvvyb6tFy7eRE4oR5Bo,9870 +sympy/concrete/expr_with_intlimits.py,sha256=vj4PjttB9xE5aUYu37R1A4_KtGgxcPa65jzjv8-krsc,11352 +sympy/concrete/expr_with_limits.py,sha256=dL5u-b_CzwghTWIhNsGc4md8jPWfhXOvna5Lig6XVr0,21834 +sympy/concrete/gosper.py,sha256=JUFbnOWSls8Xo0Zj198Xm4adopE-rAJjXv6M2q9x7us,5499 +sympy/concrete/guess.py,sha256=6EejdhNgqjMK7lVTXms8-_xGmmpI3vtliLW7-L2eaDM,17474 +sympy/concrete/products.py,sha256=I_aGMeKtSuFU07PGfZPHHTwS1WxDRNbnjedNC_m1k24,18456 +sympy/concrete/summations.py,sha256=D5n4x-fzqhgRwTIWpdN3Xun4I8u847tB7Dcex7lh7lI,55998 +sympy/concrete/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/concrete/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/concrete/tests/__pycache__/test_delta.cpython-312.pyc,, +sympy/concrete/tests/__pycache__/test_gosper.cpython-312.pyc,, +sympy/concrete/tests/__pycache__/test_guess.cpython-312.pyc,, +sympy/concrete/tests/__pycache__/test_products.cpython-312.pyc,, +sympy/concrete/tests/__pycache__/test_sums_products.cpython-312.pyc,, +sympy/concrete/tests/test_delta.py,sha256=uI7xjMx7JuVb3kkN7cLR6_pGsKS4Ulq22p-Z9oti5Jc,23869 +sympy/concrete/tests/test_gosper.py,sha256=ZHiZfYGCeCS9I-0oqN6sFbiYa-284GeFoGsNbhIWq4I,7987 +sympy/concrete/tests/test_guess.py,sha256=TPW6Hy11Po6VLZG_dx95x3sMBYl5kcQH8wjJ6TOtu-k,3370 +sympy/concrete/tests/test_products.py,sha256=caYc-xlEIrX9I_A-KPQdwp5oDprVJSbfcOaKg_qUnsM,14521 +sympy/concrete/tests/test_sums_products.py,sha256=rg0cSziPNgkvyehA0wCf-3jj8fSmNT7ECOOkiXWN64o,66390 +sympy/conftest.py,sha256=wvibr2FiWTlUcLTYAFEL8tSAKWPnv_Q6Cj4lARBCM0U,2775 +sympy/core/__init__.py,sha256=0L72TGngrIg2JknW3elaPSIDmkpPjWGNVfNk33wKXJ0,3123 +sympy/core/__pycache__/__init__.cpython-312.pyc,, +sympy/core/__pycache__/_print_helpers.cpython-312.pyc,, +sympy/core/__pycache__/add.cpython-312.pyc,, +sympy/core/__pycache__/alphabets.cpython-312.pyc,, +sympy/core/__pycache__/assumptions.cpython-312.pyc,, +sympy/core/__pycache__/assumptions_generated.cpython-312.pyc,, +sympy/core/__pycache__/backend.cpython-312.pyc,, +sympy/core/__pycache__/basic.cpython-312.pyc,, +sympy/core/__pycache__/cache.cpython-312.pyc,, +sympy/core/__pycache__/compatibility.cpython-312.pyc,, +sympy/core/__pycache__/containers.cpython-312.pyc,, +sympy/core/__pycache__/core.cpython-312.pyc,, +sympy/core/__pycache__/coreerrors.cpython-312.pyc,, +sympy/core/__pycache__/decorators.cpython-312.pyc,, +sympy/core/__pycache__/evalf.cpython-312.pyc,, +sympy/core/__pycache__/expr.cpython-312.pyc,, +sympy/core/__pycache__/exprtools.cpython-312.pyc,, +sympy/core/__pycache__/facts.cpython-312.pyc,, +sympy/core/__pycache__/function.cpython-312.pyc,, +sympy/core/__pycache__/intfunc.cpython-312.pyc,, +sympy/core/__pycache__/kind.cpython-312.pyc,, +sympy/core/__pycache__/logic.cpython-312.pyc,, +sympy/core/__pycache__/mod.cpython-312.pyc,, +sympy/core/__pycache__/mul.cpython-312.pyc,, +sympy/core/__pycache__/multidimensional.cpython-312.pyc,, +sympy/core/__pycache__/numbers.cpython-312.pyc,, +sympy/core/__pycache__/operations.cpython-312.pyc,, +sympy/core/__pycache__/parameters.cpython-312.pyc,, +sympy/core/__pycache__/power.cpython-312.pyc,, +sympy/core/__pycache__/random.cpython-312.pyc,, +sympy/core/__pycache__/relational.cpython-312.pyc,, +sympy/core/__pycache__/rules.cpython-312.pyc,, +sympy/core/__pycache__/singleton.cpython-312.pyc,, +sympy/core/__pycache__/sorting.cpython-312.pyc,, +sympy/core/__pycache__/symbol.cpython-312.pyc,, +sympy/core/__pycache__/sympify.cpython-312.pyc,, +sympy/core/__pycache__/trace.cpython-312.pyc,, +sympy/core/__pycache__/traversal.cpython-312.pyc,, +sympy/core/_print_helpers.py,sha256=GQo9dI_BvAJtYHVFFfmroNr0L8d71UeI-tU7SGJgctk,2388 +sympy/core/add.py,sha256=TddwsicZFR4yEtVTkZmkzFtn9ndAlhfad7vJiECr6o4,43407 +sympy/core/alphabets.py,sha256=vWBs2atOvfRK6Xfg6hc5IKiB7s_0sZIiVJpcCUJL0N4,266 +sympy/core/assumptions.py,sha256=8K9rhYtT-kqS7hmc9ltkYC-wujYT3pe0BaUJNrOr8fg,23595 +sympy/core/assumptions_generated.py,sha256=0TJKYIHSIFyQcVHZdIHZ19b7tqst_sY7iZwjKzcvZBM,42817 +sympy/core/backend.py,sha256=hF9cftjzB92QEcwimekj0gQ9CEMXTH-leH3l8QcguGo,5273 +sympy/core/basic.py,sha256=IzZvs7iIcMvV8_athdOBnIvBYJg38khuO2fAJtd7uTE,76789 +sympy/core/benchmarks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/core/benchmarks/__pycache__/__init__.cpython-312.pyc,, +sympy/core/benchmarks/__pycache__/bench_arit.cpython-312.pyc,, +sympy/core/benchmarks/__pycache__/bench_assumptions.cpython-312.pyc,, +sympy/core/benchmarks/__pycache__/bench_basic.cpython-312.pyc,, +sympy/core/benchmarks/__pycache__/bench_expand.cpython-312.pyc,, +sympy/core/benchmarks/__pycache__/bench_numbers.cpython-312.pyc,, +sympy/core/benchmarks/__pycache__/bench_sympify.cpython-312.pyc,, +sympy/core/benchmarks/bench_arit.py,sha256=gfrnvKSXLCaUoFFxMgJhnLUp7rG9Pa_YT7OKgOrPP8E,412 +sympy/core/benchmarks/bench_assumptions.py,sha256=evfZzTgOUUvvvlK0DRdDZQRqxIlGLfJYzKu8QDMxSks,177 +sympy/core/benchmarks/bench_basic.py,sha256=YF0tTJ_AN_Wz11qidzM4bIhlwEhEqVc-IGVGrUx6SaA,210 +sympy/core/benchmarks/bench_expand.py,sha256=xgQYQMwqgXJtKajM4JVhuL-7AW8TLY-vdBpO6uyMDoQ,427 +sympy/core/benchmarks/bench_numbers.py,sha256=_1yHSbYmxriiTTzKtxFh7kJm-rXPL6roGs8MW1E5-sg,1135 +sympy/core/benchmarks/bench_sympify.py,sha256=G5iGInhhbkkxSY2pS08BNG945m9m4eZlNT1aJutGt5M,138 +sympy/core/cache.py,sha256=AyG7kganyV0jVx-aNBEUFogqRLHQqqFn8xU3ZSfJoaM,6172 +sympy/core/compatibility.py,sha256=XQH7ezmRi6l3R23qMHN2wfA-YMRWbh2YYjPY7LRo3lo,1145 +sympy/core/containers.py,sha256=IA8PWQeCl78Pn_1WczoYUzOhBoT9X2hM3_hJ232gyKc,11411 +sympy/core/core.py,sha256=lX3Af31Qyff-gwPiAH-vijjuOzBFSuQtN06nUqIcSTQ,547 +sympy/core/coreerrors.py,sha256=imD9TCL-UEM5hrHcqGQbbfLeyZCSJMx6vB1NBQITQIQ,642 +sympy/core/decorators.py,sha256=NO3oe7yIO4q-6Vvy2vTpIAS8GGI-JHjEOEGeAv97voY,8759 +sympy/core/evalf.py,sha256=X0BinrUYeCKyHPHJQnu3FGASTUB8iz5dweVvqeArBrU,62089 +sympy/core/expr.py,sha256=HR_xzh6273FBmdfNbogGzkWoqaI_k_CeIOnpmyzwCrQ,143770 +sympy/core/exprtools.py,sha256=Ft7C1K2kD4_EdpRrGxii_WDub4pK_rYnLTdeVhlBoeo,51544 +sympy/core/facts.py,sha256=54pFKhJwEzU8LkO7rL25TwGjIb5y5CvZleHEy_TpD68,19546 +sympy/core/function.py,sha256=y0vEdXaUD8thP3XasZVkkogqXOGB0cs2JnfHEa4DNjQ,117102 +sympy/core/intfunc.py,sha256=TigJI9bvsb4aN0aZJgCzxIHlv_eh0rElWeTurier3yI,14219 +sympy/core/kind.py,sha256=9kQvtDxm-SSRGi-155XsBl_rs-oN_7dw7fNNT3mDu2Q,11540 +sympy/core/logic.py,sha256=Qbj2WUh5lS0GjxvtPaNmcQXz7mbWXuWj5ZNFZ-N-YPg,10827 +sympy/core/mod.py,sha256=XDfpth2r4AWc04oLqtDWwFuYRLzI0l0MhLMwGSMu99g,8363 +sympy/core/mul.py,sha256=rjCiyOqxMgUTWR8sAcmilRfQLup9wv8Ij7s7JIfUkVM,79201 +sympy/core/multidimensional.py,sha256=NWX1okybO_nZCl9IhIOE8QYalY1WoC0zlzsvBg_E1eE,4233 +sympy/core/numbers.py,sha256=WEkS1JJ9ov-n4hXvxwrH1NPikNlyBCjLN5v-jOZxvsw,136741 +sympy/core/operations.py,sha256=_wjhMX-MD6cyUNKCc9K_QxyxpeG4WQehdypo0Fp76GM,25828 +sympy/core/parameters.py,sha256=EoT2S3W1dS2-HoV6WN7szBexXvn5_w43e2JFouKuvkU,3854 +sympy/core/power.py,sha256=FJSYRf0S3pk1JGkVy3kdWWQENhmpVme-Pf9SS2Rc6SE,73244 +sympy/core/random.py,sha256=miFdVpNKfutbkpYiIOzG9kVNUm5GTk-_nnmQqUhVDZs,6647 +sympy/core/relational.py,sha256=htbGT0uvzoYD07Q6_hdT0iDDsns0NDI2aml0W8mtAgM,51896 +sympy/core/rules.py,sha256=AJuZztmYKZ_yUITLZB6rhZjDy6ROBCtajcYqPa50sjc,1496 +sympy/core/singleton.py,sha256=2Ueja8GJ-0-cvBzlqPwL9hB9eOtjrJFXV6mkDZO1Bp4,7115 +sympy/core/sorting.py,sha256=PoL2-MtVeuYTu-DISGlbvqW2mt787BmWfzrwV1ibavE,10827 +sympy/core/symbol.py,sha256=0xwgxT7ZfhPjq87glw2CQq5MtIEO-DOrAoXu7bHwWFo,29820 +sympy/core/sympify.py,sha256=1vWheH469HqICHrADMY_k4T4eDQlGORNjEh7Re4WbmE,20546 +sympy/core/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/core/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_args.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_arit.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_assumptions.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_basic.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_cache.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_compatibility.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_complex.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_constructor_postprocessor.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_containers.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_count_ops.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_diff.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_equal.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_eval.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_evalf.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_expand.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_expr.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_exprtools.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_facts.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_function.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_kind.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_logic.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_match.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_multidimensional.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_noncommutative.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_numbers.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_operations.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_parameters.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_power.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_priority.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_random.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_relational.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_rules.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_singleton.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_sorting.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_subs.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_symbol.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_sympify.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_traversal.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_truediv.cpython-312.pyc,, +sympy/core/tests/__pycache__/test_var.cpython-312.pyc,, +sympy/core/tests/test_args.py,sha256=gsvYkFoqSWM0G8sjwBkwwNpT_9jc-io1SyDcchI3fA4,184252 +sympy/core/tests/test_arit.py,sha256=TH4b9Z_sMGWlYqiU5MqpY5LmhzYRJSTHWtTNIrYv7fk,78611 +sympy/core/tests/test_assumptions.py,sha256=MjJdF_ymVL6mtgQx-aSr_rsNNxaTi2pHFLjyaPCBq5Q,41573 +sympy/core/tests/test_basic.py,sha256=skFOWZRNqDujmQ8GAskWH7OYcsrO0miBdM92Gy01k0U,10230 +sympy/core/tests/test_cache.py,sha256=p6Ci75a_T-bBXE_5HVxRKla62uSay_0Vuf57gUuH6sI,2001 +sympy/core/tests/test_compatibility.py,sha256=7pvNUEGIcRrfWl3doqHlm3AdNkGlcChO69gos3Fk09A,240 +sympy/core/tests/test_complex.py,sha256=koNGFMt6UMmzahJADSja_eD24gr-GG5gGCtyDgCRtPI,21906 +sympy/core/tests/test_constructor_postprocessor.py,sha256=0d7vbVuKi3GCm3PKLtiNqv_Au7v6RYt1rzRdHiD08tM,2441 +sympy/core/tests/test_containers.py,sha256=ijteBC6cjqzejfxXZZIELZJfMrgTQa1n6AlxHGCEQJs,7432 +sympy/core/tests/test_count_ops.py,sha256=eIA2WvCuWKXVBJEGfWoJrn6WfUshX_NXttrrfyLbNnI,5665 +sympy/core/tests/test_diff.py,sha256=6j4Vk9UCNRv8Oyx_4iv1ePjocwBg7_-3ftrSJ8u0cPo,5421 +sympy/core/tests/test_equal.py,sha256=RoOJuu4kMe4Rkk7eNyVOJov5S1770YHiVAiziNIKd2o,1678 +sympy/core/tests/test_eval.py,sha256=o0kZn3oaMidVYdNjeZYtx4uUKBoE3A2tWn2NS4hu72Q,2366 +sympy/core/tests/test_evalf.py,sha256=aIf2xMuFomr828s4qv6Q16xLHWNmBnDfC4FUv9g619M,28574 +sympy/core/tests/test_expand.py,sha256=jbIjBEmdsPPArsxJ9206YzMS7mPUVZo7j-7alM795eU,13886 +sympy/core/tests/test_expr.py,sha256=249jMUV5GnkjmVVcgPSkwWvzrT00ppWeygkK_9RO6kc,78428 +sympy/core/tests/test_exprtools.py,sha256=L7fi319z1EeFag6pH8myqDQYQ32H193QLKMdqlxACsY,19021 +sympy/core/tests/test_facts.py,sha256=YEZMZ-116VFnFqJ48h9bQsF2flhiB65trnZvJsRSh_o,11579 +sympy/core/tests/test_function.py,sha256=_YRRGTDthS85Bq4zoLo8bHMHNESPLUZW-4_VQaClCLs,51450 +sympy/core/tests/test_kind.py,sha256=NLJbwCpugzlNbaSyUlbb6NHoT_9dHuoXj023EDQMrNI,2048 +sympy/core/tests/test_logic.py,sha256=_YKSIod6Q0oIz9lDs78UQQrv9LU-uKaztd7w8LWwuwY,5634 +sympy/core/tests/test_match.py,sha256=yjVNccCLutvov8Ru_p38Hl_HDS0ltdsWierSi54m5Ts,22714 +sympy/core/tests/test_multidimensional.py,sha256=Fr-lagme3lwLrBpdaWP7O7oPezhIatn5X8fYYs-8bN8,848 +sympy/core/tests/test_noncommutative.py,sha256=IkGPcvLO4ACVj5LMT2IUgyj68F1RBvMKbm01iqTOK04,4436 +sympy/core/tests/test_numbers.py,sha256=SvTVZUpMWfeGvaqyJUp4e9FYIO8lFJLcbRcmBNWO8m0,78001 +sympy/core/tests/test_operations.py,sha256=mRxftKlrxxrn3zS3UPwqkF6Nr15l5Cv6j3c2RJX46s4,2859 +sympy/core/tests/test_parameters.py,sha256=wO9D-LcMMEyf5u5-EmDwVeQ02YzYbYwtFFR_o-M4ybQ,3560 +sympy/core/tests/test_power.py,sha256=H7SFxpWVnF4vgpF95ad-Fo5xHhIvKhtZJuGBg0J2SAk,24862 +sympy/core/tests/test_priority.py,sha256=6QlWz52qWwOU0CknBb4KErs4R87jp4wH3hVSQNAgdVI,3252 +sympy/core/tests/test_random.py,sha256=H58NfH5BYeQ3RIscbDct6SZkHQVRJjichVUSuSrhvAU,1233 +sympy/core/tests/test_relational.py,sha256=7ne7GIG_i0uVT8FfpCJ4ixnuIyQoVy-PwJm3kYNWbKI,43525 +sympy/core/tests/test_rules.py,sha256=iwmMX7hxC_73CuX9BizeAci-cO4JDq-y1sicKBXEGA4,349 +sympy/core/tests/test_singleton.py,sha256=xLJJgXwmkbKhsot_qTs-o4dniMjHUh3_va0xsA5h-KA,3036 +sympy/core/tests/test_sorting.py,sha256=6BZKYqUedAR-jeHcIgsJelJHFWuougml2c1NNilxGZg,902 +sympy/core/tests/test_subs.py,sha256=7ITJFDplgWBRImkcHfjRdnHqaKgjTxWb4j4WoRysvR8,30106 +sympy/core/tests/test_symbol.py,sha256=zYhPWsdyQp7_NiLVthpoCB1RyP9pmJcNlTdTN2kMdfY,13043 +sympy/core/tests/test_sympify.py,sha256=FEOsRduYX3EqE9EhMILwE9wu6jDj_o2WU9XEZHsXFUo,28195 +sympy/core/tests/test_traversal.py,sha256=cmgvMW8G-LZ20ZXy-wg5Vz5ogI_oq2p2bJSwMy9IMF0,4311 +sympy/core/tests/test_truediv.py,sha256=RYfJX39-mNhekRE3sj5TGFZXKra4ML9vGvObsRYuD3k,854 +sympy/core/tests/test_var.py,sha256=hexP-0q2nN9h_dyhKLCuvqFXgLC9e_Hroni8Ldb16Ko,1594 +sympy/core/trace.py,sha256=9WC8p3OpBL6TdHmZWMDK9jaCG-16f4uZV2VptduVH98,348 +sympy/core/traversal.py,sha256=PP4HUp-2gtsoCtGZwqxpbqZ33vtoRX-yYTbIqOQiaR0,8860 +sympy/crypto/__init__.py,sha256=i8GcbScXhIPbMEe7uuMgXqh_cU2mZm2f6hspIgmW5uM,2158 +sympy/crypto/__pycache__/__init__.cpython-312.pyc,, +sympy/crypto/__pycache__/crypto.cpython-312.pyc,, +sympy/crypto/crypto.py,sha256=iAERU5Qf9GizEUMUyxTgTUBI0U9QpSkbRir2nvKIKUA,89685 +sympy/crypto/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/crypto/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/crypto/tests/__pycache__/test_crypto.cpython-312.pyc,, +sympy/crypto/tests/test_crypto.py,sha256=gPsRBNNHwc4QDBjgT5tvWTCuC5IA5d4aZRTblxXjngk,19758 +sympy/diffgeom/__init__.py,sha256=cWj4N7AfNgrYcGIBexX-UrWxfd1bP9DTNqUmLWUJ9nA,991 +sympy/diffgeom/__pycache__/__init__.cpython-312.pyc,, +sympy/diffgeom/__pycache__/diffgeom.cpython-312.pyc,, +sympy/diffgeom/__pycache__/rn.cpython-312.pyc,, +sympy/diffgeom/diffgeom.py,sha256=DgxgxP9B7NT-M1Hb1-1AwHYHBvXZk_Y6_MqZcGPsmOg,72274 +sympy/diffgeom/rn.py,sha256=kvgth6rNJWt94kzVospZwiH53C-s4VSiorktQNmMobQ,6264 +sympy/diffgeom/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/diffgeom/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/diffgeom/tests/__pycache__/test_class_structure.cpython-312.pyc,, +sympy/diffgeom/tests/__pycache__/test_diffgeom.cpython-312.pyc,, +sympy/diffgeom/tests/__pycache__/test_function_diffgeom_book.cpython-312.pyc,, +sympy/diffgeom/tests/__pycache__/test_hyperbolic_space.cpython-312.pyc,, +sympy/diffgeom/tests/test_class_structure.py,sha256=LbRyxhhp-NnnfJ2gTn1SdlgCBQn2rhyB7xApOgcd_rM,1048 +sympy/diffgeom/tests/test_diffgeom.py,sha256=3BepCr6ned-4C_3me4zScu06HXG9Qx_dBBxIpiXAvy4,14145 +sympy/diffgeom/tests/test_function_diffgeom_book.py,sha256=GwhUAiAPtUv5I9oghdElMhtc6KX184tySgLSpVHhT0Q,5254 +sympy/diffgeom/tests/test_hyperbolic_space.py,sha256=c4xQJ_bBS4xrMj3pfx1Ms3oC2_LwuJuNYXNZxs-cVG8,2598 +sympy/discrete/__init__.py,sha256=A_Seud0IRr2gPYlz6JMQZa3sBhRL3O7gVqhIvMRRvE0,772 +sympy/discrete/__pycache__/__init__.cpython-312.pyc,, +sympy/discrete/__pycache__/convolutions.cpython-312.pyc,, +sympy/discrete/__pycache__/recurrences.cpython-312.pyc,, +sympy/discrete/__pycache__/transforms.cpython-312.pyc,, +sympy/discrete/convolutions.py,sha256=9L2d2Rrn6jqGfV2lBxCV6LmcTNBZUuOIqP_fuMIzPzk,18341 +sympy/discrete/recurrences.py,sha256=FqU5QG4qNNLSVBqcpL7HtKa7rQOlmHMXDQRzHZ_P_s0,5124 +sympy/discrete/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/discrete/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/discrete/tests/__pycache__/test_convolutions.cpython-312.pyc,, +sympy/discrete/tests/__pycache__/test_recurrences.cpython-312.pyc,, +sympy/discrete/tests/__pycache__/test_transforms.cpython-312.pyc,, +sympy/discrete/tests/test_convolutions.py,sha256=K4S9bA1E2tg0VcFQ8SYtlxjL6HB666RxD5rriTuAK4k,17856 +sympy/discrete/tests/test_recurrences.py,sha256=s5ZEZQ262gcnBLpCjJVmeKlTKQByRTQBrc-N9p_4W8c,3019 +sympy/discrete/tests/test_transforms.py,sha256=vEORFaPvxmPSsw0f4Z2hLEN1wD0FdyQOYHDEY9aVm5A,5546 +sympy/discrete/transforms.py,sha256=lf-n6IN881uCfTUAxPNjdUaSguiRbYW0omuR96vKNlE,11681 +sympy/external/__init__.py,sha256=C6s4654Elc_X-D9UgI2cUQWiQyGDt9LG3IKUc8qqzuo,578 +sympy/external/__pycache__/__init__.cpython-312.pyc,, +sympy/external/__pycache__/gmpy.cpython-312.pyc,, +sympy/external/__pycache__/importtools.cpython-312.pyc,, +sympy/external/__pycache__/ntheory.cpython-312.pyc,, +sympy/external/__pycache__/pythonmpq.cpython-312.pyc,, +sympy/external/gmpy.py,sha256=89vXc1KD5TiQCTwlL-98r01KdqsOsJpzc8XN1R7TwM4,9768 +sympy/external/importtools.py,sha256=Q7tS2cdGZ9a4NI_1sgGuoVcSDv_rIk-Av0BpFTa6EzA,7671 +sympy/external/ntheory.py,sha256=jnm13KGII1p6X42T-u2jVoBxiOCXZ8XGxjzhCuWXthE,16555 +sympy/external/pythonmpq.py,sha256=DBQYdZsCUajqIjV5ECYpzpCSbe4RR9qr4D1x_ZTuZaY,11259 +sympy/external/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/external/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/external/tests/__pycache__/test_autowrap.cpython-312.pyc,, +sympy/external/tests/__pycache__/test_codegen.cpython-312.pyc,, +sympy/external/tests/__pycache__/test_gmpy.cpython-312.pyc,, +sympy/external/tests/__pycache__/test_importtools.cpython-312.pyc,, +sympy/external/tests/__pycache__/test_ntheory.cpython-312.pyc,, +sympy/external/tests/__pycache__/test_numpy.cpython-312.pyc,, +sympy/external/tests/__pycache__/test_pythonmpq.cpython-312.pyc,, +sympy/external/tests/__pycache__/test_scipy.cpython-312.pyc,, +sympy/external/tests/test_autowrap.py,sha256=nUWYeQd1QF-Ou4A63iWypsn6pJMi0uMLyba8aRCOhnM,9759 +sympy/external/tests/test_codegen.py,sha256=t991vYFfQC6loodk7Vp1oKTCklBn8SwY7qLshVVou4w,12598 +sympy/external/tests/test_gmpy.py,sha256=8ITpuWYeitCymWwuQLpOOVBmRb3CJsO5sbqiZcVDulE,397 +sympy/external/tests/test_importtools.py,sha256=KrfontKYv11UvpazQ0vS1qyhxIvgZrCOXh1JFeACjeo,1394 +sympy/external/tests/test_ntheory.py,sha256=BJWirDnX7Y7McBoXreMomGQx33YlAjiuBTYQQLhobLU,8881 +sympy/external/tests/test_numpy.py,sha256=tuEji5l6GqbNjv74T6a3e8LDzI2zKUaLzvfluNXOFE0,10291 +sympy/external/tests/test_pythonmpq.py,sha256=L_FdZmmk5N-VEivE_O_qZa98BZhT1WSxRfdmG817bA0,5797 +sympy/external/tests/test_scipy.py,sha256=CVaw7D0-6DORgg78Q6b35SNKn05PlKwWJuqXOuU-qdY,1172 +sympy/functions/__init__.py,sha256=-u5IzcQAPk9emytXfMK22EVXqpXUtSau3pQtevZYmFo,5565 +sympy/functions/__pycache__/__init__.cpython-312.pyc,, +sympy/functions/combinatorial/__init__.py,sha256=WqXI3qU_TTJ7nJA8m3Z-7ZAYKoApT8f9Xs0u2bTwy_c,53 +sympy/functions/combinatorial/__pycache__/__init__.cpython-312.pyc,, +sympy/functions/combinatorial/__pycache__/factorials.cpython-312.pyc,, +sympy/functions/combinatorial/__pycache__/numbers.cpython-312.pyc,, +sympy/functions/combinatorial/factorials.py,sha256=cYMN1Bz76XninzSxzdLYxTN7-Mt1mzfUcSWIU-qpYAw,39184 +sympy/functions/combinatorial/numbers.py,sha256=PcW4rvWQ66POd1FcL8SJav2iUmGv2Ip_Vbbp_3qYIAY,101088 +sympy/functions/combinatorial/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/functions/combinatorial/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/functions/combinatorial/tests/__pycache__/test_comb_factorials.cpython-312.pyc,, +sympy/functions/combinatorial/tests/__pycache__/test_comb_numbers.cpython-312.pyc,, +sympy/functions/combinatorial/tests/test_comb_factorials.py,sha256=B59sfZxTUmKtnG62LW9sPn7HnRxFBP6x_rnbKqbaaZ0,26317 +sympy/functions/combinatorial/tests/test_comb_numbers.py,sha256=GWeIeb9zJo3WJr9NGW7VD-PmCIt13ce-VufICHs1-A8,47593 +sympy/functions/elementary/__init__.py,sha256=Fj8p5qE-Rr1lqAyHI0aSgC3RYX56O-gWwo6wu-eUQYA,50 +sympy/functions/elementary/__pycache__/__init__.cpython-312.pyc,, +sympy/functions/elementary/__pycache__/_trigonometric_special.cpython-312.pyc,, +sympy/functions/elementary/__pycache__/complexes.cpython-312.pyc,, +sympy/functions/elementary/__pycache__/exponential.cpython-312.pyc,, +sympy/functions/elementary/__pycache__/hyperbolic.cpython-312.pyc,, +sympy/functions/elementary/__pycache__/integers.cpython-312.pyc,, +sympy/functions/elementary/__pycache__/miscellaneous.cpython-312.pyc,, +sympy/functions/elementary/__pycache__/piecewise.cpython-312.pyc,, +sympy/functions/elementary/__pycache__/trigonometric.cpython-312.pyc,, +sympy/functions/elementary/_trigonometric_special.py,sha256=FvrgSXisxjXjyBC4-NLLya6q2YyTMNMAUqqYzuYl34g,7271 +sympy/functions/elementary/benchmarks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/functions/elementary/benchmarks/__pycache__/__init__.cpython-312.pyc,, +sympy/functions/elementary/benchmarks/__pycache__/bench_exp.cpython-312.pyc,, +sympy/functions/elementary/benchmarks/bench_exp.py,sha256=PFBYa9eMovH5XOFN5XTxWr1VDj1EBoKwn4mAtj-_DdM,185 +sympy/functions/elementary/complexes.py,sha256=HQm4ViBWN5OkCtJZQPdLdChTnmzbk4Cb2A--MUzTgUs,44168 +sympy/functions/elementary/exponential.py,sha256=GoDlUBPcmpRjYehRZOooF0bISSK_oxpJlkqaE_KNTeQ,42610 +sympy/functions/elementary/hyperbolic.py,sha256=zewRSHNzxyvSFD9sP9XBKX-evG6Rds4k9jAAcfmDbIk,69329 +sympy/functions/elementary/integers.py,sha256=Dc5Bq6ds85NJYWkfHJPJccUeVTxbhzVloTeMo5HGG98,22394 +sympy/functions/elementary/miscellaneous.py,sha256=cPpv71po3HCQGsWIHgcQEql6RNb4Y3RrL24ujgtdTIQ,27944 +sympy/functions/elementary/piecewise.py,sha256=Nv32I9lktMPHF3k0JpifbcgCgIz7CyQ8KwI_t1BaVsI,58285 +sympy/functions/elementary/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/functions/elementary/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/functions/elementary/tests/__pycache__/test_complexes.cpython-312.pyc,, +sympy/functions/elementary/tests/__pycache__/test_exponential.cpython-312.pyc,, +sympy/functions/elementary/tests/__pycache__/test_hyperbolic.cpython-312.pyc,, +sympy/functions/elementary/tests/__pycache__/test_integers.cpython-312.pyc,, +sympy/functions/elementary/tests/__pycache__/test_interface.cpython-312.pyc,, +sympy/functions/elementary/tests/__pycache__/test_miscellaneous.cpython-312.pyc,, +sympy/functions/elementary/tests/__pycache__/test_piecewise.cpython-312.pyc,, +sympy/functions/elementary/tests/__pycache__/test_trigonometric.cpython-312.pyc,, +sympy/functions/elementary/tests/test_complexes.py,sha256=BaPIrUSkoguP74x7uLSt9bA9kxmB58fJ4wgNtx5RnCg,34016 +sympy/functions/elementary/tests/test_exponential.py,sha256=ojjC0aafWaQegZVYV7bgxyvWAES_erpeYTb3R0m9V5I,29733 +sympy/functions/elementary/tests/test_hyperbolic.py,sha256=TBJZbiV-o9c2uVUqnkaRuHr5FdSGBOpqKK5_2bWg92s,56898 +sympy/functions/elementary/tests/test_integers.py,sha256=_QaECu3JQRQa9uPi10jXlu9AohvtLTKB4rSe920g0tY,23266 +sympy/functions/elementary/tests/test_interface.py,sha256=dW0aHvLR5UPyyXzBS-tgKrQIp-H6Vu8sKjlQrBQgtZ4,2513 +sympy/functions/elementary/tests/test_miscellaneous.py,sha256=eCL30UmsusBhjvqICQNmToa1aJTML8fXav1L1J6b7FU,17148 +sympy/functions/elementary/tests/test_piecewise.py,sha256=b1c0IMbXHDLjbi_ESs7fQhJiMaEro30GEu9XYreicYA,62876 +sympy/functions/elementary/tests/test_trigonometric.py,sha256=ebRorj-WThNp56qvZOAGkvgpvWFnIlB6kFZyV1gCii4,90340 +sympy/functions/elementary/trigonometric.py,sha256=b2mE2SpNj0LZM3AcipW0FrjturAi9ozijK3PhqyfCbM,115945 +sympy/functions/special/__init__.py,sha256=5pjIq_RVCMsuCe1b-FlwIty30KxoUowZYKLmpIT9KHQ,59 +sympy/functions/special/__pycache__/__init__.cpython-312.pyc,, +sympy/functions/special/__pycache__/bessel.cpython-312.pyc,, +sympy/functions/special/__pycache__/beta_functions.cpython-312.pyc,, +sympy/functions/special/__pycache__/bsplines.cpython-312.pyc,, +sympy/functions/special/__pycache__/delta_functions.cpython-312.pyc,, +sympy/functions/special/__pycache__/elliptic_integrals.cpython-312.pyc,, +sympy/functions/special/__pycache__/error_functions.cpython-312.pyc,, +sympy/functions/special/__pycache__/gamma_functions.cpython-312.pyc,, +sympy/functions/special/__pycache__/hyper.cpython-312.pyc,, +sympy/functions/special/__pycache__/mathieu_functions.cpython-312.pyc,, +sympy/functions/special/__pycache__/polynomials.cpython-312.pyc,, +sympy/functions/special/__pycache__/singularity_functions.cpython-312.pyc,, +sympy/functions/special/__pycache__/spherical_harmonics.cpython-312.pyc,, +sympy/functions/special/__pycache__/tensor_functions.cpython-312.pyc,, +sympy/functions/special/__pycache__/zeta_functions.cpython-312.pyc,, +sympy/functions/special/benchmarks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/functions/special/benchmarks/__pycache__/__init__.cpython-312.pyc,, +sympy/functions/special/benchmarks/__pycache__/bench_special.cpython-312.pyc,, +sympy/functions/special/benchmarks/bench_special.py,sha256=wzAoKTccuEaG4xrEYTlYfIJuLi3kUTMTEJ9iA113Wog,164 +sympy/functions/special/bessel.py,sha256=r-jJETBLp8a4JOKV9dW5EWr_yvERL0HMn0su328bug8,68656 +sympy/functions/special/beta_functions.py,sha256=de-ypTWZEjvFkq9RgPq3ghGOvFOfPmb9JfUDAPKQoXk,12777 +sympy/functions/special/bsplines.py,sha256=q7iZSeEMlRrx5gpXOzlk4uSTPIollduNZuGwMHB6fRM,10060 +sympy/functions/special/delta_functions.py,sha256=jopb1BX803pZtDAtLmKfFqRVjo3mySekyC80Lu-sJkM,19887 +sympy/functions/special/elliptic_integrals.py,sha256=YpCU-xyTvrmBxdO7Rj2pNYDbS2-bGfCvCaOHon9nSq0,14921 +sympy/functions/special/error_functions.py,sha256=GvKrm5fVMpat0Iierh9UsxsTeQknJyiHgMrWS-e7fhw,79556 +sympy/functions/special/gamma_functions.py,sha256=gkPQdMNR7k5uY1vSUu6zzyoJKMoQZfC90YjLRcyft5c,42943 +sympy/functions/special/hyper.py,sha256=oqeAhFALAN_H6eS0Fs_axdfL9jIYQ-aRFGGgQky2HYk,38829 +sympy/functions/special/mathieu_functions.py,sha256=kFmt0RUA70vhGphI7lhwUsOQ7KIy8Y95DU6gGkVQU5Y,6620 +sympy/functions/special/polynomials.py,sha256=IdxRf8D1iFA-oYfLyTcUmsSCeuWja4h2ExNb8UShwxg,46753 +sympy/functions/special/singularity_functions.py,sha256=ounzMgFQiOW-e1Rb5y_dCSopJGegXMdkj-EpjrP8tzU,8346 +sympy/functions/special/spherical_harmonics.py,sha256=MNAJ4ABTy_EIZe2XSK_MZ1SPnk1OeDnJAtrICAst4yw,11018 +sympy/functions/special/tensor_functions.py,sha256=UNoDpLu1EBR-2tX_dLoRpKhN0Yhm-z_hh8EtW50dNSE,12303 +sympy/functions/special/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/functions/special/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/functions/special/tests/__pycache__/test_bessel.cpython-312.pyc,, +sympy/functions/special/tests/__pycache__/test_beta_functions.cpython-312.pyc,, +sympy/functions/special/tests/__pycache__/test_bsplines.cpython-312.pyc,, +sympy/functions/special/tests/__pycache__/test_delta_functions.cpython-312.pyc,, +sympy/functions/special/tests/__pycache__/test_elliptic_integrals.cpython-312.pyc,, +sympy/functions/special/tests/__pycache__/test_error_functions.cpython-312.pyc,, +sympy/functions/special/tests/__pycache__/test_gamma_functions.cpython-312.pyc,, +sympy/functions/special/tests/__pycache__/test_hyper.cpython-312.pyc,, +sympy/functions/special/tests/__pycache__/test_mathieu.cpython-312.pyc,, +sympy/functions/special/tests/__pycache__/test_singularity_functions.cpython-312.pyc,, +sympy/functions/special/tests/__pycache__/test_spec_polynomials.cpython-312.pyc,, +sympy/functions/special/tests/__pycache__/test_spherical_harmonics.cpython-312.pyc,, +sympy/functions/special/tests/__pycache__/test_tensor_functions.cpython-312.pyc,, +sympy/functions/special/tests/__pycache__/test_zeta_functions.cpython-312.pyc,, +sympy/functions/special/tests/test_bessel.py,sha256=c6OKhj4MCjv4kpDG7udueaCOLykblsKHMOyP4CdFToA,37373 +sympy/functions/special/tests/test_beta_functions.py,sha256=yxfgu-wmNEeMfaFABiDHYmuZpZup9FTp0ZYerlc6hhc,3786 +sympy/functions/special/tests/test_bsplines.py,sha256=6UYg7IqXTi8fcSOut8TEzNVkxIA4ff-CyG22qJnbIYA,7145 +sympy/functions/special/tests/test_delta_functions.py,sha256=8xhSWG4SLL86z1QKFfLk_3b--bCrxjvCaxHlODBVToE,7138 +sympy/functions/special/tests/test_elliptic_integrals.py,sha256=scu7KemJ7Q2nsRcZtckQNruuthI-vla9M1sDVkLcbKM,6991 +sympy/functions/special/tests/test_error_functions.py,sha256=TkhkIKiuRZS78-F4ZTt5rvr3hfknp654IEhmHhRXT48,33565 +sympy/functions/special/tests/test_gamma_functions.py,sha256=aveGPdG1X9OdlC6xpdZbSsJ3S4M4DaG2osyOhm1fAYo,29908 +sympy/functions/special/tests/test_hyper.py,sha256=SEnQ9TtyO_dSQRc94AHrbQai6Q7-tmRfDIh40gNE3FE,16694 +sympy/functions/special/tests/test_mathieu.py,sha256=pqoFbnC84NDL6EQkigFtx5OQ1RFYppckTjzsm9XT0PY,1282 +sympy/functions/special/tests/test_singularity_functions.py,sha256=GEXzHHeR5F0swrZzhF7pEGR0tk9Vp3Ve2c-sE4WSpsY,6249 +sympy/functions/special/tests/test_spec_polynomials.py,sha256=wuiZaR_LwaM8SlNuGl3B1p4eOHC_-zZVSXMPNfzKRB4,19561 +sympy/functions/special/tests/test_spherical_harmonics.py,sha256=pUFtFpNPBnJTdnqou0jniSchijyh1rdzKv8H24RT9FU,3850 +sympy/functions/special/tests/test_tensor_functions.py,sha256=bblSDkPABZ6N1j1Rb2Bb5TZIzZoK1D8ks3fHizi69ZI,5546 +sympy/functions/special/tests/test_zeta_functions.py,sha256=2r59_aC0QOXQsBNXqxsHPr2PkJExusI6qvSydZBPbfw,10474 +sympy/functions/special/zeta_functions.py,sha256=QPRYVp0-WKs02CUSQiRIJUWD4N_3PmqrOsk1MGzBUfU,24091 +sympy/galgebra.py,sha256=yEosUPSnhLp9a1NWXvpCLoU20J6TQ58XNIvw07POkVk,123 +sympy/geometry/__init__.py,sha256=BU2MiKm8qJyZJ_hz1qC-3nFJTPEcuvx4hYd02jHjqSM,1240 +sympy/geometry/__pycache__/__init__.cpython-312.pyc,, +sympy/geometry/__pycache__/curve.cpython-312.pyc,, +sympy/geometry/__pycache__/ellipse.cpython-312.pyc,, +sympy/geometry/__pycache__/entity.cpython-312.pyc,, +sympy/geometry/__pycache__/exceptions.cpython-312.pyc,, +sympy/geometry/__pycache__/line.cpython-312.pyc,, +sympy/geometry/__pycache__/parabola.cpython-312.pyc,, +sympy/geometry/__pycache__/plane.cpython-312.pyc,, +sympy/geometry/__pycache__/point.cpython-312.pyc,, +sympy/geometry/__pycache__/polygon.cpython-312.pyc,, +sympy/geometry/__pycache__/util.cpython-312.pyc,, +sympy/geometry/curve.py,sha256=F7b6XrlhUZ0QWLDoZJVojWfC5LeyOU-69OTFnYAREg8,10170 +sympy/geometry/ellipse.py,sha256=So0gH9e-1Oh3HGzrXoLqANyP4lTTBfGHHVo5vCdbfdk,50305 +sympy/geometry/entity.py,sha256=fvHhtSb6RvE6v-8yMyCNvm0ekLPoO7EO9J8TEsGyQGU,20668 +sympy/geometry/exceptions.py,sha256=XtUMA44UTdrBWt771jegFC-TXsobhDiI-10TDH_WNFM,131 +sympy/geometry/line.py,sha256=Yw8ns_w8rn6FEak6MmfsdccgNNjMQHhodDik2UX7jJM,80397 +sympy/geometry/parabola.py,sha256=YhtQ9C5Yco_iSQ6ZYRs0lZBWHmDkcvKUr-Y8RghY3M8,10716 +sympy/geometry/plane.py,sha256=z3hjEf3ibO735DV0Mb4DVjvthYlDyiPfekCeePSCDMM,26770 +sympy/geometry/point.py,sha256=vQB40V1fvhZze3D_D54HlMSS8gXeMIWerd2hBozmPFA,36661 +sympy/geometry/polygon.py,sha256=aooJyJVwf6ZPuxStYgTc-2jNjVaM2YHSvpVY3XRjAuo,82027 +sympy/geometry/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/geometry/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/geometry/tests/__pycache__/test_curve.cpython-312.pyc,, +sympy/geometry/tests/__pycache__/test_ellipse.cpython-312.pyc,, +sympy/geometry/tests/__pycache__/test_entity.cpython-312.pyc,, +sympy/geometry/tests/__pycache__/test_geometrysets.cpython-312.pyc,, +sympy/geometry/tests/__pycache__/test_line.cpython-312.pyc,, +sympy/geometry/tests/__pycache__/test_parabola.cpython-312.pyc,, +sympy/geometry/tests/__pycache__/test_plane.cpython-312.pyc,, +sympy/geometry/tests/__pycache__/test_point.cpython-312.pyc,, +sympy/geometry/tests/__pycache__/test_polygon.cpython-312.pyc,, +sympy/geometry/tests/__pycache__/test_util.cpython-312.pyc,, +sympy/geometry/tests/test_curve.py,sha256=xL4uRWAal4mXZxuQhcs9QOhs6MheCbFNyH1asq_a2IQ,4479 +sympy/geometry/tests/test_ellipse.py,sha256=f-EorUkNl_cg63bDvm4Qrbe1PWrBaCCRg8jAmdIYBuU,26509 +sympy/geometry/tests/test_entity.py,sha256=KSsncs7afLpqUAYTs9b0VH1dt6FhPrX5rrj2rdLpBUo,3896 +sympy/geometry/tests/test_geometrysets.py,sha256=vvOWrFrJuNAFgbrVh1wPY94o-H-85FWlnIyyo2Kst9c,1911 +sympy/geometry/tests/test_line.py,sha256=fLWGfHQNC3YqjxtT7zQbP--Cu0mjcPwSBfji4DA7BP0,38054 +sympy/geometry/tests/test_parabola.py,sha256=kd0RU5sGOcfp6jgwgXMtvT2B6kG1-M3-iGOLnUJfZOw,6150 +sympy/geometry/tests/test_plane.py,sha256=QRcfoDsJtCtcvjFb18hBEHupycLgAT2OohF6GpNShyQ,12525 +sympy/geometry/tests/test_point.py,sha256=YKXQdlBTQWsIVf9l3G6iPMq0OqMTo8nZlibhJDsq_Ic,16410 +sympy/geometry/tests/test_polygon.py,sha256=4D0t98SELQF42dYR-CbFqDU5yJds0LAE2RE8xqEdqag,27602 +sympy/geometry/tests/test_util.py,sha256=sbh1QvkQG1OqvE-kt4fNNIkMWnOFi5EpaBmnZS3pzNc,7044 +sympy/geometry/util.py,sha256=zF6Xx0ciab6Rxm4ekK5RawWXPWAk5oug8eDvgfNKoRc,20671 +sympy/holonomic/__init__.py,sha256=BgHIokaSOo3nwJlGO_caJHz37n6yoA8GeM9Xjn4zMpc,784 +sympy/holonomic/__pycache__/__init__.cpython-312.pyc,, +sympy/holonomic/__pycache__/holonomic.cpython-312.pyc,, +sympy/holonomic/__pycache__/holonomicerrors.cpython-312.pyc,, +sympy/holonomic/__pycache__/numerical.cpython-312.pyc,, +sympy/holonomic/__pycache__/recurrence.cpython-312.pyc,, +sympy/holonomic/holonomic.py,sha256=vP5XabVIezsAURbK65p8P_QfPINQwhol0d62B7Br3s0,91887 +sympy/holonomic/holonomicerrors.py,sha256=qDyUoGbrRjPtVax4SeEEf_o6-264mASEZO_rZETXH5o,1193 +sympy/holonomic/numerical.py,sha256=MlP8xTBqjVQqM1-jwviS_yPICKj6tEVsa9f6wyMCSfo,2625 +sympy/holonomic/recurrence.py,sha256=HWSMokhjcdGTLW_oku0Xi8W8RHxWYS28bv8V7eubC58,10377 +sympy/holonomic/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/holonomic/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/holonomic/tests/__pycache__/test_holonomic.cpython-312.pyc,, +sympy/holonomic/tests/__pycache__/test_recurrence.cpython-312.pyc,, +sympy/holonomic/tests/test_holonomic.py,sha256=NuoJtJi3RlpMYhMU_bGH1tuFuFoOZZrrSdMpgdHGhf0,35333 +sympy/holonomic/tests/test_recurrence.py,sha256=qHv0kn1Q4-aCD7XmbDK2xIdkjF0XkeZUKD2yeLajiq0,1342 +sympy/integrals/__init__.py,sha256=pZ-C3tDP_8woKActNoS7IwyW-9AuB5PMHB5B0ohlpw8,1970 +sympy/integrals/__pycache__/__init__.cpython-312.pyc,, +sympy/integrals/__pycache__/deltafunctions.cpython-312.pyc,, +sympy/integrals/__pycache__/heurisch.cpython-312.pyc,, +sympy/integrals/__pycache__/integrals.cpython-312.pyc,, +sympy/integrals/__pycache__/intpoly.cpython-312.pyc,, +sympy/integrals/__pycache__/laplace.cpython-312.pyc,, +sympy/integrals/__pycache__/manualintegrate.cpython-312.pyc,, +sympy/integrals/__pycache__/meijerint.cpython-312.pyc,, +sympy/integrals/__pycache__/meijerint_doc.cpython-312.pyc,, +sympy/integrals/__pycache__/prde.cpython-312.pyc,, +sympy/integrals/__pycache__/quadrature.cpython-312.pyc,, +sympy/integrals/__pycache__/rationaltools.cpython-312.pyc,, +sympy/integrals/__pycache__/rde.cpython-312.pyc,, +sympy/integrals/__pycache__/risch.cpython-312.pyc,, +sympy/integrals/__pycache__/singularityfunctions.cpython-312.pyc,, +sympy/integrals/__pycache__/transforms.cpython-312.pyc,, +sympy/integrals/__pycache__/trigonometry.cpython-312.pyc,, +sympy/integrals/benchmarks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/integrals/benchmarks/__pycache__/__init__.cpython-312.pyc,, +sympy/integrals/benchmarks/__pycache__/bench_integrate.cpython-312.pyc,, +sympy/integrals/benchmarks/__pycache__/bench_trigintegrate.cpython-312.pyc,, +sympy/integrals/benchmarks/bench_integrate.py,sha256=vk6wAO1bqzFT9oW4qsW7nKGfc_gP0XaB5PMYKx5339Q,396 +sympy/integrals/benchmarks/bench_trigintegrate.py,sha256=8XU3uB3mcavigvzHQZA7H1sHI32zgT-9RkSnLa-Y3Vc,305 +sympy/integrals/deltafunctions.py,sha256=ysIQLdRBcG_YR-bVDoxt-sxEVU8TG77oSgM-J0gI0mE,7435 +sympy/integrals/heurisch.py,sha256=Huq3dBJEXvYGzkBboXnG6xFCGorc5Uftf5ssbiltyIs,26706 +sympy/integrals/integrals.py,sha256=DV_ditazAyVBpUCzsUFNiYvvQRqJfx3UGjnSEB2HKcg,64887 +sympy/integrals/intpoly.py,sha256=SXjd_f295YrYsvoQpzE2EQM5xaQnnj0zvHdYW5KEdn0,43266 +sympy/integrals/laplace.py,sha256=y5NxZ3_nNtc-NETYWw4iha7LTVM9Ok9NWPtmMUXtZwg,87038 +sympy/integrals/manualintegrate.py,sha256=sO_5-9pbeRKhZSuEwXm6okxpvRsbpQZerbLBdRdDtp4,75721 +sympy/integrals/meijerint.py,sha256=yOsrHJA7doo1uDsmsiTqK2Tly4JF30sA5RElT92lfec,80775 +sympy/integrals/meijerint_doc.py,sha256=Sis9bZvwciU2_BZzr3GCvXLkBcXVUhP9ycqGIDu99xU,1204 +sympy/integrals/prde.py,sha256=3VqBQOX7SZv_lETmhoVgb9gRjb1z8hiZAJ6vv5AgNEo,52073 +sympy/integrals/quadrature.py,sha256=6Bg3JmlIjIduIfaGfNVcwNfSrgEiLOszcN8WPzsXNqE,17064 +sympy/integrals/rationaltools.py,sha256=ZAizq9unSt-_wQkCIAhl_FaemzbQcfBcE9A3mDiU788,11694 +sympy/integrals/rde.py,sha256=EKXK6bf4m-2O0NZ-rtHq0Ye2a_o9LmUrkoV8gNxZKVk,27393 +sympy/integrals/risch.py,sha256=4UsTHizZtAMe3VUmRHugdOuPMilw8sKiVOlSUMWj9oE,67352 +sympy/integrals/singularityfunctions.py,sha256=ONI8x-ed-IcqOF4K2l0LVUvEUN2_dHztvL4auRsi67U,2235 +sympy/integrals/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/integrals/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/integrals/tests/__pycache__/test_deltafunctions.cpython-312.pyc,, +sympy/integrals/tests/__pycache__/test_failing_integrals.cpython-312.pyc,, +sympy/integrals/tests/__pycache__/test_heurisch.cpython-312.pyc,, +sympy/integrals/tests/__pycache__/test_integrals.cpython-312.pyc,, +sympy/integrals/tests/__pycache__/test_intpoly.cpython-312.pyc,, +sympy/integrals/tests/__pycache__/test_laplace.cpython-312.pyc,, +sympy/integrals/tests/__pycache__/test_lineintegrals.cpython-312.pyc,, +sympy/integrals/tests/__pycache__/test_manual.cpython-312.pyc,, +sympy/integrals/tests/__pycache__/test_meijerint.cpython-312.pyc,, +sympy/integrals/tests/__pycache__/test_prde.cpython-312.pyc,, +sympy/integrals/tests/__pycache__/test_quadrature.cpython-312.pyc,, +sympy/integrals/tests/__pycache__/test_rationaltools.cpython-312.pyc,, +sympy/integrals/tests/__pycache__/test_rde.cpython-312.pyc,, +sympy/integrals/tests/__pycache__/test_risch.cpython-312.pyc,, +sympy/integrals/tests/__pycache__/test_singularityfunctions.cpython-312.pyc,, +sympy/integrals/tests/__pycache__/test_transforms.cpython-312.pyc,, +sympy/integrals/tests/__pycache__/test_trigonometry.cpython-312.pyc,, +sympy/integrals/tests/test_deltafunctions.py,sha256=ivFjS-WlLQ4aMqjVS7ZzMChP2Mmw_JUPnwI9otiLnvs,3709 +sympy/integrals/tests/test_failing_integrals.py,sha256=HKMA6O26exCIRWQ43KyKugOvJL3gOei3r9JObcKo8p0,7438 +sympy/integrals/tests/test_heurisch.py,sha256=-btpZS_LI9EO-2EmA0eHV6l7xykQjkHIcpDU_GziTlo,14299 +sympy/integrals/tests/test_integrals.py,sha256=8bVIN4ztTwOvpLrlDIk1SURQMtiNXoqu-LLMkZp-Wrk,81192 +sympy/integrals/tests/test_intpoly.py,sha256=NzGhkR2pUMfd8lIU2cFR9bFa0J89RzpHs3zDggAWtXo,37445 +sympy/integrals/tests/test_laplace.py,sha256=pWn5UEm15gJv_hD35lvJh03Uuw4o79rbCQYvbXQS2xk,38186 +sympy/integrals/tests/test_lineintegrals.py,sha256=zcPJ2n7DYt9KsgAe38t0gq3ARApUlb-kBahLThuRcq8,450 +sympy/integrals/tests/test_manual.py,sha256=unQ6Ew81SCHvVMva_aAOndh7hWpLeDwBtXs6W-yC0jE,34551 +sympy/integrals/tests/test_meijerint.py,sha256=G22dppQGMFU3JGexHZs65nce8UAK9wTilZn0D1XvZu0,32594 +sympy/integrals/tests/test_prde.py,sha256=2BZmEDasdx_3l64-9hioArysDj6Nl520GpQN2xnEE_A,16360 +sympy/integrals/tests/test_quadrature.py,sha256=iFMdqck36gkL-yksLflawIOYmw-0PzO2tFj_qdK6Hjg,19919 +sympy/integrals/tests/test_rationaltools.py,sha256=7QiPnpBXl7lo32RmhXo7ED6FYj5I1gjEFOziJYlqPtI,5669 +sympy/integrals/tests/test_rde.py,sha256=4d3vJupa-hRN4yNDISY8IC3rSI_cZW5BbtxoZm14y-Y,9571 +sympy/integrals/tests/test_risch.py,sha256=HaWg0JnErdrNzNmVfyz2Zz4XAgZPVVpZPt6Map3sQ58,38630 +sympy/integrals/tests/test_singularityfunctions.py,sha256=CSrHie59_NjNZ9B2GaHzKPNsMzxm5Kh6GuxlYk8zTuI,1266 +sympy/integrals/tests/test_transforms.py,sha256=mLl5RfuENf11oenV1OXgg6TfWdQTEY23txiGl7grCyo,27152 +sympy/integrals/tests/test_trigonometry.py,sha256=moMYr_Prc7gaYPjBK0McLjRpTEes2veUlN0vGv9UyEA,3869 +sympy/integrals/transforms.py,sha256=_rwRkrOnV4zby27MZJ9dpJrtQFG4gTbL7naLpFLXKDo,51750 +sympy/integrals/trigonometry.py,sha256=iOoBDGFDZx8PNbgL3XeZEd80I8ro0WAizNuC4P-u8x0,11083 +sympy/interactive/__init__.py,sha256=yokwEO2HF3eN2Xu65JSpUUsN4iYmPvvU4m_64f3Q33o,251 +sympy/interactive/__pycache__/__init__.cpython-312.pyc,, +sympy/interactive/__pycache__/printing.cpython-312.pyc,, +sympy/interactive/__pycache__/session.cpython-312.pyc,, +sympy/interactive/__pycache__/traversal.cpython-312.pyc,, +sympy/interactive/printing.py,sha256=EZBO3YCga2dXBI1EfFHVDmUKBkF9UmrLMgwI76B0nyE,21562 +sympy/interactive/session.py,sha256=sG546e0mAtT0OrFkYNVM7QGvkWrDhAQZ5E1hfx03iBQ,15329 +sympy/interactive/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/interactive/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/interactive/tests/__pycache__/test_interactive.cpython-312.pyc,, +sympy/interactive/tests/__pycache__/test_ipython.cpython-312.pyc,, +sympy/interactive/tests/test_interactive.py,sha256=Pbopy9lODrd_P46_xxlWxLwqPfG6_4J3CWWC4IqfDL4,485 +sympy/interactive/tests/test_ipython.py,sha256=QZUvr77TxJHjdgQVNpihAuoglg1ghVHOTDFOVXJ9pcE,11797 +sympy/interactive/traversal.py,sha256=XbccdO6msNAvrG6FFJl2n4XmIiRISnvda4QflfEPg7U,3189 +sympy/liealgebras/__init__.py,sha256=K8tw7JqG33_y6mYl1LTr8ZNtKH5L21BqkjCHfLhP4aA,79 +sympy/liealgebras/__pycache__/__init__.cpython-312.pyc,, +sympy/liealgebras/__pycache__/cartan_matrix.cpython-312.pyc,, +sympy/liealgebras/__pycache__/cartan_type.cpython-312.pyc,, +sympy/liealgebras/__pycache__/dynkin_diagram.cpython-312.pyc,, +sympy/liealgebras/__pycache__/root_system.cpython-312.pyc,, +sympy/liealgebras/__pycache__/type_a.cpython-312.pyc,, +sympy/liealgebras/__pycache__/type_b.cpython-312.pyc,, +sympy/liealgebras/__pycache__/type_c.cpython-312.pyc,, +sympy/liealgebras/__pycache__/type_d.cpython-312.pyc,, +sympy/liealgebras/__pycache__/type_e.cpython-312.pyc,, +sympy/liealgebras/__pycache__/type_f.cpython-312.pyc,, +sympy/liealgebras/__pycache__/type_g.cpython-312.pyc,, +sympy/liealgebras/__pycache__/weyl_group.cpython-312.pyc,, +sympy/liealgebras/cartan_matrix.py,sha256=yr2LoZi_Gxmu-EMKgFuPOPNMYPOsxucLAS6oRpSYi2U,524 +sympy/liealgebras/cartan_type.py,sha256=xLklg8Y5s40je6sXwmLmG9iyYi9YEk9KoxTSFz1GtdI,1790 +sympy/liealgebras/dynkin_diagram.py,sha256=ZzGuBGNOJ3lPDdJDs4n8hvGbz6wLhC5mwb8zFkDmyPw,535 +sympy/liealgebras/root_system.py,sha256=n1TKAZyWDPSlUDmjAga9Sa2Cm9qeRXddYPbl2XKyFq4,6673 +sympy/liealgebras/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/liealgebras/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/liealgebras/tests/__pycache__/test_cartan_matrix.cpython-312.pyc,, +sympy/liealgebras/tests/__pycache__/test_cartan_type.cpython-312.pyc,, +sympy/liealgebras/tests/__pycache__/test_dynkin_diagram.cpython-312.pyc,, +sympy/liealgebras/tests/__pycache__/test_root_system.cpython-312.pyc,, +sympy/liealgebras/tests/__pycache__/test_type_A.cpython-312.pyc,, +sympy/liealgebras/tests/__pycache__/test_type_B.cpython-312.pyc,, +sympy/liealgebras/tests/__pycache__/test_type_C.cpython-312.pyc,, +sympy/liealgebras/tests/__pycache__/test_type_D.cpython-312.pyc,, +sympy/liealgebras/tests/__pycache__/test_type_E.cpython-312.pyc,, +sympy/liealgebras/tests/__pycache__/test_type_F.cpython-312.pyc,, +sympy/liealgebras/tests/__pycache__/test_type_G.cpython-312.pyc,, +sympy/liealgebras/tests/__pycache__/test_weyl_group.cpython-312.pyc,, +sympy/liealgebras/tests/test_cartan_matrix.py,sha256=KCsakn0fHKHRbIUcrUkHBIKkudl3_ISUdHrfJy-UOd4,303 +sympy/liealgebras/tests/test_cartan_type.py,sha256=t5PvYYDXbNIFL3CV59Je7SBIAeLLf-W3mOINPUoHK6E,339 +sympy/liealgebras/tests/test_dynkin_diagram.py,sha256=DSixbnt_yd0zrhKzXW_XqkXWXYe1Dk2MmXN-Rjb1dGg,260 +sympy/liealgebras/tests/test_root_system.py,sha256=YmGBdUeJ4PkLSfAfRgTF7GW62RCEd5nH27FSX9UaG5Q,927 +sympy/liealgebras/tests/test_type_A.py,sha256=x7QmpjxsGmXol-IYVtN1lmIOmM3HLYwpX1tSG5h6FMM,657 +sympy/liealgebras/tests/test_type_B.py,sha256=Gw0GP24wP2rPn38Wwla9W7BwWH4JtCGpaprZb5W6JVY,642 +sympy/liealgebras/tests/test_type_C.py,sha256=ysSy-vzE9lNwzAunrmvnFkLBoJwF7W2On7QpqS6RI1s,927 +sympy/liealgebras/tests/test_type_D.py,sha256=qrO4oCjrjkp1uDvrNtbgANVyaOExqOLNtIpIxD1uH0U,764 +sympy/liealgebras/tests/test_type_E.py,sha256=IQ46Bo75Kivz0O45mNKNvDO8jen7X2NwxVBTwvr5lQo,987 +sympy/liealgebras/tests/test_type_F.py,sha256=yUQJ7LzTemv4Cd1XW_dr3x7KEI07BahsWAyJfXLS1eA,1378 +sympy/liealgebras/tests/test_type_G.py,sha256=wVa6qcAHbdrc9dA63samexHL35cWWJS606pom-6mH2Q,548 +sympy/liealgebras/tests/test_weyl_group.py,sha256=HrzojRECbhNUsdLFQAXYnJEt8LfktOSJZuqVE45aRnc,1501 +sympy/liealgebras/type_a.py,sha256=Etn_aeyE5FdYrUXrGnjNiTL5k4r5-O_CysaO-_UKASA,4294 +sympy/liealgebras/type_b.py,sha256=ERH1aM38eHZUuTJYRsWLKFDm74G4y1MQtweSfkDFQYc,4547 +sympy/liealgebras/type_c.py,sha256=Al1pA5cw5IKjvBzx9LdMORd5-JZXgA0kaMv8aHhnYJ0,4426 +sympy/liealgebras/type_d.py,sha256=Cagn4GXrYuUP32W6jauIPnEv8IcD3H88sbn0fKS7pmU,4681 +sympy/liealgebras/type_e.py,sha256=KR84bp4Ga7d9itKRCsD3AYrarVewGiNNe7AHWNUfTAM,8280 +sympy/liealgebras/type_f.py,sha256=gIyk4zA04uIpwizcYdvKsZ_xkcpPLId6LIHR6tp38dk,4423 +sympy/liealgebras/type_g.py,sha256=Ife98dGPtarGd-ii8hJbXdB0SMsct4okDkSX2wLN8XI,2965 +sympy/liealgebras/weyl_group.py,sha256=5YFA8qC4GWDM0WLNR_6VgpuNFZDfyDA7fBFjBcZaLgA,14557 +sympy/logic/__init__.py,sha256=RfoXrq9MESnXdL7PkwpYEfWeaxH6wBPHiE4zCgLKvk0,456 +sympy/logic/__pycache__/__init__.cpython-312.pyc,, +sympy/logic/__pycache__/boolalg.cpython-312.pyc,, +sympy/logic/__pycache__/inference.cpython-312.pyc,, +sympy/logic/algorithms/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/logic/algorithms/__pycache__/__init__.cpython-312.pyc,, +sympy/logic/algorithms/__pycache__/dpll.cpython-312.pyc,, +sympy/logic/algorithms/__pycache__/dpll2.cpython-312.pyc,, +sympy/logic/algorithms/__pycache__/lra_theory.cpython-312.pyc,, +sympy/logic/algorithms/__pycache__/minisat22_wrapper.cpython-312.pyc,, +sympy/logic/algorithms/__pycache__/pycosat_wrapper.cpython-312.pyc,, +sympy/logic/algorithms/__pycache__/z3_wrapper.cpython-312.pyc,, +sympy/logic/algorithms/dpll.py,sha256=zqiZDm1oD5sNxFqm_0Hen6NjfILIDp5uRgEOad1vYXI,9188 +sympy/logic/algorithms/dpll2.py,sha256=PEVvFUrEf-IwTwfnTYtAFLPLPjjqA1nmm39nASgsM1I,21497 +sympy/logic/algorithms/lra_theory.py,sha256=6JZAZMJhhHSbUXZuc0ddYwp_x7efVuthIYV7Dc9eUyc,31769 +sympy/logic/algorithms/minisat22_wrapper.py,sha256=uINcvkIHGWYJb8u-Q0OgnSgaHfVUd9tYYFbBAVNiASo,1317 +sympy/logic/algorithms/pycosat_wrapper.py,sha256=0vNFTbu9-YhSfjwYTsZsP_Z4HM8WpL11-xujLBS1kYg,1207 +sympy/logic/algorithms/z3_wrapper.py,sha256=mFmf7DWDV0Zu7006EdFK4qEDTP7sfmcXrfGZkMK97vo,3747 +sympy/logic/boolalg.py,sha256=GqxLtqUangGoSjsncKDzlLEE7iYVe5qsMtPhztniI9c,114972 +sympy/logic/inference.py,sha256=J2D8t9iHCSdotzS9iq6g3EvLPsI2B10kiNbmHsIz_oY,8983 +sympy/logic/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/logic/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/logic/tests/__pycache__/test_boolalg.cpython-312.pyc,, +sympy/logic/tests/__pycache__/test_dimacs.cpython-312.pyc,, +sympy/logic/tests/__pycache__/test_inference.cpython-312.pyc,, +sympy/logic/tests/__pycache__/test_lra_theory.cpython-312.pyc,, +sympy/logic/tests/test_boolalg.py,sha256=0ZjG56WpIhIwFLedUzg5IC-c0VF_g9qoU9aAbFydPYU,49748 +sympy/logic/tests/test_dimacs.py,sha256=EK_mA_k9zBLcQLTOKTZVrGhnGuQNza5mwXDQD_f-X1c,3886 +sympy/logic/tests/test_inference.py,sha256=9BXfPbJs6sBEgx1nwkmg2HcLl82lcfFXngKJL_ByzUI,16116 +sympy/logic/tests/test_lra_theory.py,sha256=hNCH66hP_32x5ioyqM6ltd0DbEl72kdctCBu-H6egG0,16834 +sympy/logic/utilities/__init__.py,sha256=WTn2vBgHcmhONRWI79PdMYNk8UxYDzsxRlZWuc-wtNI,55 +sympy/logic/utilities/__pycache__/__init__.cpython-312.pyc,, +sympy/logic/utilities/__pycache__/dimacs.cpython-312.pyc,, +sympy/logic/utilities/dimacs.py,sha256=gfrGWQpn4F7gLJH1zHAnLB8-CMGa1XtXl9NCGhwAW9k,1671 +sympy/matrices/__init__.py,sha256=i2a37WlcCj8-AKG_Yy8BBdOHFgAuWois_2IcD_Ih00s,2634 +sympy/matrices/__pycache__/__init__.cpython-312.pyc,, +sympy/matrices/__pycache__/common.cpython-312.pyc,, +sympy/matrices/__pycache__/decompositions.cpython-312.pyc,, +sympy/matrices/__pycache__/dense.cpython-312.pyc,, +sympy/matrices/__pycache__/determinant.cpython-312.pyc,, +sympy/matrices/__pycache__/eigen.cpython-312.pyc,, +sympy/matrices/__pycache__/exceptions.cpython-312.pyc,, +sympy/matrices/__pycache__/graph.cpython-312.pyc,, +sympy/matrices/__pycache__/immutable.cpython-312.pyc,, +sympy/matrices/__pycache__/inverse.cpython-312.pyc,, +sympy/matrices/__pycache__/kind.cpython-312.pyc,, +sympy/matrices/__pycache__/matrices.cpython-312.pyc,, +sympy/matrices/__pycache__/matrixbase.cpython-312.pyc,, +sympy/matrices/__pycache__/normalforms.cpython-312.pyc,, +sympy/matrices/__pycache__/reductions.cpython-312.pyc,, +sympy/matrices/__pycache__/repmatrix.cpython-312.pyc,, +sympy/matrices/__pycache__/solvers.cpython-312.pyc,, +sympy/matrices/__pycache__/sparse.cpython-312.pyc,, +sympy/matrices/__pycache__/sparsetools.cpython-312.pyc,, +sympy/matrices/__pycache__/subspaces.cpython-312.pyc,, +sympy/matrices/__pycache__/utilities.cpython-312.pyc,, +sympy/matrices/benchmarks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/matrices/benchmarks/__pycache__/__init__.cpython-312.pyc,, +sympy/matrices/benchmarks/__pycache__/bench_matrix.cpython-312.pyc,, +sympy/matrices/benchmarks/bench_matrix.py,sha256=vGMlg-2il2cFeAWrf0NJ6pzPX3Yd3ZQMxFgQ4q5ILQE,306 +sympy/matrices/common.py,sha256=v_jMjH9t6mrHl7Z5QluhO-G07QUaJSdiioF2YC1xlhY,95395 +sympy/matrices/decompositions.py,sha256=5OjwFe5Z_eM2XoZPqrNFY9-Esq3cO_8yqFxT9QBPHgQ,47865 +sympy/matrices/dense.py,sha256=HTPNMKbi2M0W0nHImNtHib9JM5VC8si99ldL_FylKwQ,30461 +sympy/matrices/determinant.py,sha256=pDTDYCLBSWJov_j_B-ZZHdqH3-WQ_uwhZawrX3EDE9k,34550 +sympy/matrices/eigen.py,sha256=v09mqb2hZ0HqGbGzYpELOatIHnGTP5XADE-1RGcua-g,39811 +sympy/matrices/exceptions.py,sha256=8diN_ojMGC93XpqvZeS5ow4crlFxSkm6WqtnIK5j81E,503 +sympy/matrices/expressions/__init__.py,sha256=IMqXCSsPh0Vp_MC9HZTudA5DGM4WBq_yB-Bst0azyM8,1692 +sympy/matrices/expressions/__pycache__/__init__.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/_shape.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/adjoint.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/applyfunc.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/blockmatrix.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/companion.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/determinant.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/diagonal.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/dotproduct.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/factorizations.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/fourier.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/funcmatrix.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/hadamard.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/inverse.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/kronecker.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/matadd.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/matexpr.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/matmul.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/matpow.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/permutation.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/sets.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/slice.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/special.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/trace.cpython-312.pyc,, +sympy/matrices/expressions/__pycache__/transpose.cpython-312.pyc,, +sympy/matrices/expressions/_shape.py,sha256=TyQSwGx41aaMyAYs5Q7Er6atKVAdWK7DJ6YIVsiEAZg,3062 +sympy/matrices/expressions/adjoint.py,sha256=HV4OIWgmS2f_1_4PHRhQpgNmKJVCoX0eyHmrM6gfN5g,1515 +sympy/matrices/expressions/applyfunc.py,sha256=8scpWjZp7yzuvUNr0mxN03KgyTzLRa5NkGl9s81YPgY,6751 +sympy/matrices/expressions/blockmatrix.py,sha256=TPR1ZDTSzVGtT-Qo23XNzjnDVl1Js8NCi_2qV3fQA9U,31643 +sympy/matrices/expressions/companion.py,sha256=lXUJRbjQR6e1mdHQdJwNIJXMW80XmKbOVqNvUXjB57U,1705 +sympy/matrices/expressions/determinant.py,sha256=RyQXgUgqJkv_rvUPrn1_rOY45wzp5zYH6ZOf9S8NK8s,3281 +sympy/matrices/expressions/diagonal.py,sha256=XHWoT-Jv5QwJVsGNbfxHnNG2sygPy1CeR_t6zr8oUoM,6328 +sympy/matrices/expressions/dotproduct.py,sha256=sKdUhwVKTB3LEvd8xMwCDexNoQ1Dz43DCYsmm3UwFWw,1911 +sympy/matrices/expressions/factorizations.py,sha256=zFNjMBsJqhsIcDD8Me4W8-Q-TV89WptfG3Dd9yK_tPE,1456 +sympy/matrices/expressions/fourier.py,sha256=dvaftgB9jgkR_8ETyhzyVLtf1ZJu_wQC-ZbpTYMXZGE,2094 +sympy/matrices/expressions/funcmatrix.py,sha256=q6R75wLn0UdV4xJdVJUrNaofV1k1egXLLQdBeZcPtiY,3520 +sympy/matrices/expressions/hadamard.py,sha256=feXSZy0vbqxTzg0JeLmkSegiF4T2v5dOdcv0UQczK38,13920 +sympy/matrices/expressions/inverse.py,sha256=4UwgHWSIHgEoKOniObkClMYN9DrO2xNyvOSVToXSpj8,2963 +sympy/matrices/expressions/kronecker.py,sha256=kzCHqXDtcZGVQPln521lfN5redNwj6IjXJwjbv_Dkhg,13404 +sympy/matrices/expressions/matadd.py,sha256=0MSanal1HKVEuCBEpehKwfUX4fuM9UMy6Fg2H5noA0s,4773 +sympy/matrices/expressions/matexpr.py,sha256=nfV9MhDNBR9HkOP7zoXOtv9wWR4OFxNczprik4S3Uh8,27549 +sympy/matrices/expressions/matmul.py,sha256=n9LcrgYoEhEQuq2htALHuboIWN0p8P_3lZdKNo92Rf0,15509 +sympy/matrices/expressions/matpow.py,sha256=puuYB49wr1WzFxhT9DcTWtF2bGDFWcbJ7oh14ATQARs,5140 +sympy/matrices/expressions/permutation.py,sha256=Xe7yOx-EgeD6JrqWc4L-ApdN-3ZiV8XS_LQPmc1lhGw,8050 +sympy/matrices/expressions/sets.py,sha256=3zase_rDn2QdaXETX78BgkfKiWcRC7FmwVjjIU-WmdY,2033 +sympy/matrices/expressions/slice.py,sha256=aNdY1Ey4VJR-UCvoORX2kh2DmA6QjOp-waENvWg8WVE,3355 +sympy/matrices/expressions/special.py,sha256=hywkygOQjcJEGQn2fG4dF8oUqXL3N42U1TxbdJr4-6E,7499 +sympy/matrices/expressions/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/matrices/expressions/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_adjoint.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_applyfunc.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_blockmatrix.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_companion.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_derivatives.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_determinant.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_diagonal.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_dotproduct.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_factorizations.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_fourier.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_funcmatrix.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_hadamard.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_indexing.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_inverse.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_kronecker.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_matadd.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_matexpr.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_matmul.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_matpow.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_permutation.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_sets.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_slice.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_special.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_trace.cpython-312.pyc,, +sympy/matrices/expressions/tests/__pycache__/test_transpose.cpython-312.pyc,, +sympy/matrices/expressions/tests/test_adjoint.py,sha256=cxOc334yNSI9MazhG9HT8s1OCXjkDWr3Zj2JnyHS3Z4,1065 +sympy/matrices/expressions/tests/test_applyfunc.py,sha256=mxTJaoB4Ze50lk-2TgVopmrrbuQbEqUsZwc3K1H8w-Q,3522 +sympy/matrices/expressions/tests/test_blockmatrix.py,sha256=ANNR7e2eiGIvabMNezxRVzipmA8oUwmDTrBTz5ALMzU,16541 +sympy/matrices/expressions/tests/test_companion.py,sha256=Lam6r-cSOokjhSlJws55Kq-gL5_pHfeV_Xuvmn5PkRU,1657 +sympy/matrices/expressions/tests/test_derivatives.py,sha256=9mBeaAZDX7-JbYs6tMClNuGDygETVN_dCXSlHmyAhwg,15991 +sympy/matrices/expressions/tests/test_determinant.py,sha256=JSgptLz9KNC4_X27qnuFq-rscgHk6144s5TEUQpLxr0,2067 +sympy/matrices/expressions/tests/test_diagonal.py,sha256=3L6Vs_Yr36a8dgIqAeIcNEf0xcVyeyGhANNu0dlIpwI,4516 +sympy/matrices/expressions/tests/test_dotproduct.py,sha256=Zkv2N6oRPm0-sN4PFwsVFrM5Y_qv4x2gWqQQQD86hBY,1171 +sympy/matrices/expressions/tests/test_factorizations.py,sha256=6UPA_UhCL5JPbaQCOatMnxhGnQ-aIHmb3lXqbwrSoIE,786 +sympy/matrices/expressions/tests/test_fourier.py,sha256=0eD69faoHXBcuQ7g2Q31fqs-gyR_Xfe-gv-7DXhJh_c,1638 +sympy/matrices/expressions/tests/test_funcmatrix.py,sha256=uN9r0ECMIBqsIzOezg_n9uDYNs6ebYS8Yf5yexUjmAM,2230 +sympy/matrices/expressions/tests/test_hadamard.py,sha256=rR0l1howrI8SaJOnLb0fsCXS5cIx1rzahwFTfGldp3Y,4614 +sympy/matrices/expressions/tests/test_indexing.py,sha256=wwYQa7LNlzhBA5fU50gPyE8cqaJf0s3O70PUx4eNCEA,12038 +sympy/matrices/expressions/tests/test_inverse.py,sha256=n4gwv-GH0LPXZDVgzEB0lA_fk8MmNFK_BVNJb0FEUfY,2320 +sympy/matrices/expressions/tests/test_kronecker.py,sha256=e5H6av3ioOn8jkjyDBrT3NEmCkyHbN6ZEHOlyB9OYLk,5366 +sympy/matrices/expressions/tests/test_matadd.py,sha256=U1fL5YLP_cYEOsdi2uaGGrzm8qOsKcXn69BC1UV6RMM,1866 +sympy/matrices/expressions/tests/test_matexpr.py,sha256=pQkxhi8okFDbF6Uea-dbeRrjNfmlc6nzJdIXOJxAqUI,18441 +sympy/matrices/expressions/tests/test_matmul.py,sha256=2ofS4YHHIcI9DamZNU-8RhBQTnNogqGknKxqkyKXO8U,6187 +sympy/matrices/expressions/tests/test_matpow.py,sha256=dRbwvZ3vxwnqw09lnRqOu475f46xDPNo7V3oc1d_P2U,7308 +sympy/matrices/expressions/tests/test_permutation.py,sha256=93Cqjj2k3aoR3ayMJLdJUa5h1u87bRRxT3I8B4FQsvU,5607 +sympy/matrices/expressions/tests/test_sets.py,sha256=DfFGe6W1ppUs6bgo3vB3DSJvFemrT68s0F3QbyoIJiE,1408 +sympy/matrices/expressions/tests/test_slice.py,sha256=C7OGAQQTz0YZxZCa7g0m8_0Bqq8jaPRa22JHVSqK7tY,2027 +sympy/matrices/expressions/tests/test_special.py,sha256=Mhg71vnjjb4fm0jZgjDoWW8rAJMBeh8aDCM75gjEpKQ,6496 +sympy/matrices/expressions/tests/test_trace.py,sha256=fRlrw9CfdO3z3SI4TQb1fCUb_zVAndbtyOErEeCTCQ0,3383 +sympy/matrices/expressions/tests/test_transpose.py,sha256=P3wPPRywKnrAppX6gssgD66v0RIcolxqDkCaKGGPVcM,1987 +sympy/matrices/expressions/trace.py,sha256=skr53LvstLV5Yg9hkaRb0yWrTdxC9u95G-YzIc80aTs,5362 +sympy/matrices/expressions/transpose.py,sha256=QGQ1bgqvYmRNs6QiVolhtFlbluPYpwW3UNvkRZUqUHU,2645 +sympy/matrices/graph.py,sha256=4UBv9SI5Z8Xjc5jPJVOoPVGQDtfbyOmS8f0ENrPOuU8,9080 +sympy/matrices/immutable.py,sha256=okpJZ41FnaHp1PpwnPNCnB_o3afAU7DgRsr2NqBKtvg,5530 +sympy/matrices/inverse.py,sha256=aVjDn_SjZUfi-jdM_1uJ6u6lVItuvbnb3CppayHQ-Gs,13166 +sympy/matrices/kind.py,sha256=EJxDdD4gFgvVfC3lRex-bczhcGjwBhglf1hPDk2WzXE,2843 +sympy/matrices/matrices.py,sha256=iqgi7x7cjnLT6OuRp6TYjoObJtUtbcPpeGTOC-Enh9Q,23536 +sympy/matrices/matrixbase.py,sha256=snpv-ZBFi-CRtfMwY9lukSTPpELVXmJF16Gn8xPV3yI,165154 +sympy/matrices/normalforms.py,sha256=mX19wvJqQAirRiPY-WdSfEdljFOhst18LcDX4MvPM8A,4636 +sympy/matrices/reductions.py,sha256=MZ8LtryawSm1jXsWzRPsYBmir867lRUWX4LFNGVIHwI,12500 +sympy/matrices/repmatrix.py,sha256=d2vne9qNn1cu7dQbCdkftMPadA87evGMaoE7LkxaYXE,29914 +sympy/matrices/solvers.py,sha256=kWkUdy0XoWbn7RY4S1N0qNgxKAcUrHiTlicb25rR9z4,25163 +sympy/matrices/sparse.py,sha256=ER4tfnpvAMeockzWi10mKdKZJSYJNPISyoUL_m29UJ8,14673 +sympy/matrices/sparsetools.py,sha256=tzI541P8QW_v1eVJAXgOlo_KK1Xp6u1geawX_tdlBxY,9182 +sympy/matrices/subspaces.py,sha256=uLo4qnP0xvFcFo5hhf6g7pHSHiRbcQ1ATDKwGBxW7CE,3761 +sympy/matrices/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/matrices/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/matrices/tests/__pycache__/test_commonmatrix.cpython-312.pyc,, +sympy/matrices/tests/__pycache__/test_decompositions.cpython-312.pyc,, +sympy/matrices/tests/__pycache__/test_determinant.cpython-312.pyc,, +sympy/matrices/tests/__pycache__/test_domains.cpython-312.pyc,, +sympy/matrices/tests/__pycache__/test_eigen.cpython-312.pyc,, +sympy/matrices/tests/__pycache__/test_graph.cpython-312.pyc,, +sympy/matrices/tests/__pycache__/test_immutable.cpython-312.pyc,, +sympy/matrices/tests/__pycache__/test_interactions.cpython-312.pyc,, +sympy/matrices/tests/__pycache__/test_matrices.cpython-312.pyc,, +sympy/matrices/tests/__pycache__/test_matrixbase.cpython-312.pyc,, +sympy/matrices/tests/__pycache__/test_normalforms.cpython-312.pyc,, +sympy/matrices/tests/__pycache__/test_reductions.cpython-312.pyc,, +sympy/matrices/tests/__pycache__/test_repmatrix.cpython-312.pyc,, +sympy/matrices/tests/__pycache__/test_solvers.cpython-312.pyc,, +sympy/matrices/tests/__pycache__/test_sparse.cpython-312.pyc,, +sympy/matrices/tests/__pycache__/test_sparsetools.cpython-312.pyc,, +sympy/matrices/tests/__pycache__/test_subspaces.cpython-312.pyc,, +sympy/matrices/tests/test_commonmatrix.py,sha256=CEYYa5frGDGPAVz78uYVTBC3IHoQLG18VRnq289XtBQ,40772 +sympy/matrices/tests/test_decompositions.py,sha256=LTm3KjUHh0QkGmR8UA1CwGWzpFu8o-qcl4sv2VKBi8g,14419 +sympy/matrices/tests/test_determinant.py,sha256=FxbLYbiO1wj12YYfsbQPoEOcgWpRGVu1CzVKLx4e8oQ,9560 +sympy/matrices/tests/test_domains.py,sha256=gUnMLr_LeEsN5unFjIwHCZje0URC9uVBN_Q76JbX9f4,3276 +sympy/matrices/tests/test_eigen.py,sha256=Xm-Xe7qGACLpqwOx5W2mDjve2KyJf-q8PyEi40jMgAk,22722 +sympy/matrices/tests/test_graph.py,sha256=ckfGDCg2M6gluv9XFnfURga8gxd2HTL7aX281s6wy6c,3213 +sympy/matrices/tests/test_immutable.py,sha256=JSu6YlGtPP-5iialCeatCKbZ4ScLDUzhQ-TMGhsalp8,4616 +sympy/matrices/tests/test_interactions.py,sha256=6T6wkHyTW5v2fwg0rz2HULoDElfA_NttApU2t-pZFKI,2070 +sympy/matrices/tests/test_matrices.py,sha256=YrwrczVsTuLoPAAkh4dlZYbfUcVEUe88wyM53fmUOtw,163196 +sympy/matrices/tests/test_matrixbase.py,sha256=2EUoz0Dl3hPFNvWU--ls6RPGfllZJbVvZSsDA9D6jPo,168868 +sympy/matrices/tests/test_normalforms.py,sha256=leFZ2rJGrWKv8Zz8aMaHQiNrCEQWOG1RqQ87omvlqIk,3730 +sympy/matrices/tests/test_reductions.py,sha256=tKv_KufpVc6qwH-MDz8XLpgVS4z6snnlNdd1ECAQSXM,13385 +sympy/matrices/tests/test_repmatrix.py,sha256=enu29IYEPzvKvGFeN6Bi9KYKqcXdy0EucifN9fV420Q,2084 +sympy/matrices/tests/test_solvers.py,sha256=55Zmvp2KC6OpdXFHBkXZRBRls_8wHfYNWO2UOQh9AoE,22311 +sympy/matrices/tests/test_sparse.py,sha256=GvXN6kBVldjqoR8WN8I_PjblKhRmyRWvVuLUgZEgugY,23281 +sympy/matrices/tests/test_sparsetools.py,sha256=pjQR6UaEMR92NolB_IGZ9Umk6FPZjvI0vk1Fd4H_C5I,4877 +sympy/matrices/tests/test_subspaces.py,sha256=poY6k6l2LSL7OCixQNGzrauLZIYbrjDul7J-yEE02S8,3465 +sympy/matrices/utilities.py,sha256=mMnNsDTxGKqiG0JATsM4W9b5jglhacy-vmRw2aZojgY,2117 +sympy/multipledispatch/__init__.py,sha256=aV2NC2cO_KmD6QFiwy4oC1D8fm3pFuPbaiTMeWmNWak,259 +sympy/multipledispatch/__pycache__/__init__.cpython-312.pyc,, +sympy/multipledispatch/__pycache__/conflict.cpython-312.pyc,, +sympy/multipledispatch/__pycache__/core.cpython-312.pyc,, +sympy/multipledispatch/__pycache__/dispatcher.cpython-312.pyc,, +sympy/multipledispatch/__pycache__/utils.cpython-312.pyc,, +sympy/multipledispatch/conflict.py,sha256=rR6tKn58MfhMMKZ4ZrhVduylXd9f5PjT2TpzM9LMB6o,2117 +sympy/multipledispatch/core.py,sha256=I4WOnmu1VtlaCnn2oD9R2-xckkYLRZPNFEWtCOTAYfM,2261 +sympy/multipledispatch/dispatcher.py,sha256=A2I4upt4qNollXGpwzrqg7M0oKHJhZx1BUMIBnjRIow,12226 +sympy/multipledispatch/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/multipledispatch/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/multipledispatch/tests/__pycache__/test_conflict.cpython-312.pyc,, +sympy/multipledispatch/tests/__pycache__/test_core.cpython-312.pyc,, +sympy/multipledispatch/tests/__pycache__/test_dispatcher.cpython-312.pyc,, +sympy/multipledispatch/tests/test_conflict.py,sha256=msNVSiikuPOqsEm_MMGmjsNbA2CAR0F1FZaHskzzo04,1786 +sympy/multipledispatch/tests/test_core.py,sha256=UfH_7cyvZ6PHjdH8vmLG49CG7E30W8uxm3FthuMc1Jk,4048 +sympy/multipledispatch/tests/test_dispatcher.py,sha256=saJPpGXLpLOuRfw-ekzZGzY-Rys0NsS5ke0n33i9j0U,6228 +sympy/multipledispatch/utils.py,sha256=39wB9i8jNhlLFZyCTFnioLx5N_CNWv4r5VZwKrxswIE,3097 +sympy/ntheory/__init__.py,sha256=WpYPsusKb9OQ1xmXxZFla7kXacIWv4lNIpFIEVVzTLA,2810 +sympy/ntheory/__pycache__/__init__.cpython-312.pyc,, +sympy/ntheory/__pycache__/bbp_pi.cpython-312.pyc,, +sympy/ntheory/__pycache__/continued_fraction.cpython-312.pyc,, +sympy/ntheory/__pycache__/digits.cpython-312.pyc,, +sympy/ntheory/__pycache__/ecm.cpython-312.pyc,, +sympy/ntheory/__pycache__/egyptian_fraction.cpython-312.pyc,, +sympy/ntheory/__pycache__/elliptic_curve.cpython-312.pyc,, +sympy/ntheory/__pycache__/factor_.cpython-312.pyc,, +sympy/ntheory/__pycache__/generate.cpython-312.pyc,, +sympy/ntheory/__pycache__/modular.cpython-312.pyc,, +sympy/ntheory/__pycache__/multinomial.cpython-312.pyc,, +sympy/ntheory/__pycache__/partitions_.cpython-312.pyc,, +sympy/ntheory/__pycache__/primetest.cpython-312.pyc,, +sympy/ntheory/__pycache__/qs.cpython-312.pyc,, +sympy/ntheory/__pycache__/residue_ntheory.cpython-312.pyc,, +sympy/ntheory/bbp_pi.py,sha256=ILur1c9Ja-1F_blgnInUx-WopQ_WSvK-2OvNLEe2Zx8,5998 +sympy/ntheory/continued_fraction.py,sha256=bQW7PvdgDtWnbpCmkOwyz3mNYPOXh9_ehq3_ZpJO8Rw,10717 +sympy/ntheory/digits.py,sha256=ea3xSLy8RMaMHsekg8nq2gnVTug7SOvaDjw0lmB6NMU,3831 +sympy/ntheory/ecm.py,sha256=zg_GhL0XSyG5ZVSdGv3YceCguPZrFaS-hC-vXqOVOGQ,11793 +sympy/ntheory/egyptian_fraction.py,sha256=hW886hPWJtARqgZIrH1WjZFC0uvf9CHxMIn0X9MWZro,6923 +sympy/ntheory/elliptic_curve.py,sha256=ZT677EHi26BkZdRTLs1Tf4VSyMxDzJrwk1xECoMT7Qg,11544 +sympy/ntheory/factor_.py,sha256=MQQJSnjSpz-B9ex9fqMCnrrNTfqFOlhJV9RAWy3gJTw,83551 +sympy/ntheory/generate.py,sha256=B6LVkK627xWzQ1UE5XoeMxNM7Q1O8EwcP7fwKs5vkZk,33376 +sympy/ntheory/modular.py,sha256=wYNfNr5S8DqipQNBLVMR7cPUNg7twM25xcLhXBD14I4,8474 +sympy/ntheory/multinomial.py,sha256=rbm3STjgfRbNVbcPeH69qtWktthSCk0sC373NuDM6fU,5073 +sympy/ntheory/partitions_.py,sha256=S81zrWeTVHmYAphcP6yUGLz5CrlUwW_JFtkQRoeLlV4,8995 +sympy/ntheory/primetest.py,sha256=9EVL1yeBkOHDfa2phHiDwUnmidSJJrTl6Wzo0y1Sck0,25423 +sympy/ntheory/qs.py,sha256=8ZKxvqc-oGPqZNbEH-XcPsjXLy5-5aygVB5rR1BkSO8,14938 +sympy/ntheory/residue_ntheory.py,sha256=dDBaogSqroJHlyXRqnLmuzNVyXfy4rWB_hlhOCNQHpk,54359 +sympy/ntheory/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/ntheory/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/ntheory/tests/__pycache__/test_bbp_pi.cpython-312.pyc,, +sympy/ntheory/tests/__pycache__/test_continued_fraction.cpython-312.pyc,, +sympy/ntheory/tests/__pycache__/test_digits.cpython-312.pyc,, +sympy/ntheory/tests/__pycache__/test_ecm.cpython-312.pyc,, +sympy/ntheory/tests/__pycache__/test_egyptian_fraction.cpython-312.pyc,, +sympy/ntheory/tests/__pycache__/test_elliptic_curve.cpython-312.pyc,, +sympy/ntheory/tests/__pycache__/test_factor_.cpython-312.pyc,, +sympy/ntheory/tests/__pycache__/test_generate.cpython-312.pyc,, +sympy/ntheory/tests/__pycache__/test_hypothesis.cpython-312.pyc,, +sympy/ntheory/tests/__pycache__/test_modular.cpython-312.pyc,, +sympy/ntheory/tests/__pycache__/test_multinomial.cpython-312.pyc,, +sympy/ntheory/tests/__pycache__/test_partitions.cpython-312.pyc,, +sympy/ntheory/tests/__pycache__/test_primetest.cpython-312.pyc,, +sympy/ntheory/tests/__pycache__/test_qs.cpython-312.pyc,, +sympy/ntheory/tests/__pycache__/test_residue.cpython-312.pyc,, +sympy/ntheory/tests/test_bbp_pi.py,sha256=TgNpZOtKAfU-IVzO62Ko7Oy3LLNfdzEo9gWMTTDZL6c,9486 +sympy/ntheory/tests/test_continued_fraction.py,sha256=JJsyEXatgjNxYZTKkKubvymyVs0WDpLfbEiAY5SYk8g,3583 +sympy/ntheory/tests/test_digits.py,sha256=mrTfwboMCQkiOEpMgYg8Nrk12WE5pEtpmbQthRVt4Xc,1968 +sympy/ntheory/tests/test_ecm.py,sha256=yco77gknWe6co4VKTCoRNKHzd3jdqGKQWQFwuziYNWI,2290 +sympy/ntheory/tests/test_egyptian_fraction.py,sha256=tpHcwteuuQAahcPqvgBm4Mwq-efzcHOn8mldijynjlE,2378 +sympy/ntheory/tests/test_elliptic_curve.py,sha256=wc0EOsGo-qGpdevRq1o64htwTOT_YSUzUfyhJC-JVbg,624 +sympy/ntheory/tests/test_factor_.py,sha256=Z4B33C0blhcG9KuQzmJcDw7TtrTYJ6jAsWQd8Oi3YZw,26382 +sympy/ntheory/tests/test_generate.py,sha256=lhnJPjlz1TYrDHJ4Jq0F64P4KV8C7ngKmm3Jxtz7Wsk,9868 +sympy/ntheory/tests/test_hypothesis.py,sha256=Ztg-QoiBxpUp6euPy1RcPbF6yaLK_ij-Jcl637GGhNY,728 +sympy/ntheory/tests/test_modular.py,sha256=g73sUXtYNxzbDcq5UnMWT8NodAU8unwRj_E-PpvJqDs,1425 +sympy/ntheory/tests/test_multinomial.py,sha256=8uuj6XlatNyIILOpjJap13CMZmDwrCyGKn9LiIUiLV0,2344 +sympy/ntheory/tests/test_partitions.py,sha256=qkd-84AO0rpJv-MQW0lnXtIPtGTAfplFbu2ezKSfEQI,1088 +sympy/ntheory/tests/test_primetest.py,sha256=Lp4elAnnBDYSIPfVXENOUjZYuwAynsNQrE_CEiYDErU,9495 +sympy/ntheory/tests/test_qs.py,sha256=zbwQ1k5ywsUVNZzPewWul_yUnoqWxxvsSWOBAU5Albc,3956 +sympy/ntheory/tests/test_residue.py,sha256=7VGXsslZWVd3R7tAtIcLjYyh0TjZpb5BtG2GQehlAUY,16809 +sympy/parsing/__init__.py,sha256=KHuyDeHY1ifpVxT4aTOhomazCBYVIrKWd28jqp6YNJ8,125 +sympy/parsing/__pycache__/__init__.cpython-312.pyc,, +sympy/parsing/__pycache__/ast_parser.cpython-312.pyc,, +sympy/parsing/__pycache__/mathematica.cpython-312.pyc,, +sympy/parsing/__pycache__/maxima.cpython-312.pyc,, +sympy/parsing/__pycache__/sym_expr.cpython-312.pyc,, +sympy/parsing/__pycache__/sympy_parser.cpython-312.pyc,, +sympy/parsing/ast_parser.py,sha256=iJvr6bhm1RjM5rhWzZA4c4LGTH5lAFazN5zu8y8q-aY,2734 +sympy/parsing/autolev/Autolev.g4,sha256=980mo25mLWrQFmhRIg-aqIalUuwktYYaBGTXZ5_XZwA,4195 +sympy/parsing/autolev/__init__.py,sha256=sp5hzv5siVW3xUmhkp0S0iaA0Cz-PVB0HO1zC04pxYs,3611 +sympy/parsing/autolev/__pycache__/__init__.cpython-312.pyc,, +sympy/parsing/autolev/__pycache__/_build_autolev_antlr.cpython-312.pyc,, +sympy/parsing/autolev/__pycache__/_listener_autolev_antlr.cpython-312.pyc,, +sympy/parsing/autolev/__pycache__/_parse_autolev_antlr.cpython-312.pyc,, +sympy/parsing/autolev/_antlr/__init__.py,sha256=MQ4ZacpTuP-NmruFXKdWLQatoeVJQ8SaBQ2DnYvtyE8,203 +sympy/parsing/autolev/_antlr/__pycache__/__init__.cpython-312.pyc,, +sympy/parsing/autolev/_antlr/__pycache__/autolevlexer.cpython-312.pyc,, +sympy/parsing/autolev/_antlr/__pycache__/autolevlistener.cpython-312.pyc,, +sympy/parsing/autolev/_antlr/__pycache__/autolevparser.cpython-312.pyc,, +sympy/parsing/autolev/_antlr/autolevlexer.py,sha256=K7HF_-5dUyAIv1_7GkhTmxqSCanEhCpzJG8fayAEB3Q,13609 +sympy/parsing/autolev/_antlr/autolevlistener.py,sha256=EDb3XkH9Y7CLzxGM-tY-nGqxMGfBHVkqKdVCPxABgRE,12821 +sympy/parsing/autolev/_antlr/autolevparser.py,sha256=BZYJ7IkurRmm44S50pYp_9JHCjT8fr1w5HeksAEPjtg,106291 +sympy/parsing/autolev/_build_autolev_antlr.py,sha256=0oIrC3sWUDe18zydeNyRmQrGGwPtRYQzIul8YcmMpk4,2578 +sympy/parsing/autolev/_listener_autolev_antlr.py,sha256=jv1jYvmrGmom6F3fhYTHG1sqLK6FFCO1-jrvDW-nPEM,104760 +sympy/parsing/autolev/_parse_autolev_antlr.py,sha256=b9hIaluJUd1V2XIAp1erak6U-c-CwKyDLH1UkYQuvKE,1736 +sympy/parsing/autolev/test-examples/README.txt,sha256=0C4m_nLROeV5J8nMfm3RYEfYgQJqmlHZaCpVD24boQY,528 +sympy/parsing/autolev/test-examples/__pycache__/ruletest1.cpython-312.pyc,, +sympy/parsing/autolev/test-examples/__pycache__/ruletest10.cpython-312.pyc,, +sympy/parsing/autolev/test-examples/__pycache__/ruletest11.cpython-312.pyc,, +sympy/parsing/autolev/test-examples/__pycache__/ruletest12.cpython-312.pyc,, +sympy/parsing/autolev/test-examples/__pycache__/ruletest2.cpython-312.pyc,, +sympy/parsing/autolev/test-examples/__pycache__/ruletest3.cpython-312.pyc,, +sympy/parsing/autolev/test-examples/__pycache__/ruletest4.cpython-312.pyc,, +sympy/parsing/autolev/test-examples/__pycache__/ruletest5.cpython-312.pyc,, +sympy/parsing/autolev/test-examples/__pycache__/ruletest6.cpython-312.pyc,, +sympy/parsing/autolev/test-examples/__pycache__/ruletest7.cpython-312.pyc,, +sympy/parsing/autolev/test-examples/__pycache__/ruletest8.cpython-312.pyc,, +sympy/parsing/autolev/test-examples/__pycache__/ruletest9.cpython-312.pyc,, +sympy/parsing/autolev/test-examples/pydy-example-repo/__pycache__/chaos_pendulum.cpython-312.pyc,, +sympy/parsing/autolev/test-examples/pydy-example-repo/__pycache__/double_pendulum.cpython-312.pyc,, +sympy/parsing/autolev/test-examples/pydy-example-repo/__pycache__/mass_spring_damper.cpython-312.pyc,, +sympy/parsing/autolev/test-examples/pydy-example-repo/__pycache__/non_min_pendulum.cpython-312.pyc,, +sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.al,sha256=HpTcX2wXzLqmgpp8fcSqNweKjxljk43iYK0wQmBbCDI,690 +sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.py,sha256=FSu4TP2BDTQjzYhMkcpRhXbb3kAD27XCyO_EoL55Ack,2274 +sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.al,sha256=wjeeRdCS3Es6ldX9Ug5Du1uaijUTyoXpfTqmhL0uYfk,427 +sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.py,sha256=uU9azTUGrY15BSDtw5T_V-7gmjyhHbXslzkmwBvFjGk,1583 +sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.al,sha256=Gf7OhgRlwqUEXq7rkfbf89yWA23u4uIUJ-buXTyOuXM,505 +sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.py,sha256=9ReCAqcUH5HYBgHmop9h5Zx54mfScWZN5L5F6rCHk4w,1366 +sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.al,sha256=p5v40h1nVFrWNqnB0K7GiNQT0b-MqwayYjZxXOY4M8M,362 +sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.py,sha256=DdxcWrm3HMQuyyY3Pk6sKHb4RXhQEM_EKY3HYZCP8ec,1503 +sympy/parsing/autolev/test-examples/ruletest1.al,sha256=mDJ02Q1Qm-ShVmGoyjzSfgDJHUOuDrsUg3YMnkpKdUw,176 +sympy/parsing/autolev/test-examples/ruletest1.py,sha256=eIKEFzEwkCFhPF0GTmf6SLuxXT384GqdCJnhiL2U0BQ,555 +sympy/parsing/autolev/test-examples/ruletest10.al,sha256=jKpV8BgX91iQsQDLFOJyaS396AyE5YQlUMxih5o9RK0,781 +sympy/parsing/autolev/test-examples/ruletest10.py,sha256=I1tsQcSAW6wqIguF-7lwlj9D4YZ8kCZqPqTKPUHR9oI,2726 +sympy/parsing/autolev/test-examples/ruletest11.al,sha256=j_q7giq2KIuXVRLWwNlwIlpbhNO6SqBMnLGLcxIkzwk,188 +sympy/parsing/autolev/test-examples/ruletest11.py,sha256=dYTRtXvMDXHiKzXHD2Sh0fcEukob3wr_GbSeqaZrrO8,475 +sympy/parsing/autolev/test-examples/ruletest12.al,sha256=drr2NLrK1ewn4FjMppXycpAUNbZEQ0IAMsdVx8nxk6I,185 +sympy/parsing/autolev/test-examples/ruletest12.py,sha256=ZG36s3PnkT0aKBM9Nx6H0sdJrtoLwaebU9386YSUql8,472 +sympy/parsing/autolev/test-examples/ruletest2.al,sha256=d-QjPpW0lzugaGBg8F6pDl_5sZHOR_EDJ8EvWLcz4FY,237 +sympy/parsing/autolev/test-examples/ruletest2.py,sha256=jrJfb0Jk2FP4GS5pDa0UB5ph0ijEVd1X8meKeZrTVng,820 +sympy/parsing/autolev/test-examples/ruletest3.al,sha256=1TAaOe8GI8-yBWJddfIxwnvScHNmOjSzSaQn0RS_v5k,308 +sympy/parsing/autolev/test-examples/ruletest3.py,sha256=O3K3IQo-HCjAIOSkfz3bDlst7dVUiRwhOZ0q_3jb5LU,1574 +sympy/parsing/autolev/test-examples/ruletest4.al,sha256=qPGlPbdDRrzTDUBeWydAIa7mbjs2o3uX938QAsWJ7Qk,302 +sympy/parsing/autolev/test-examples/ruletest4.py,sha256=WHod5yzKF4TNbEf4Yfxmx9WnimA7NOXqtTjZXR8FsP0,682 +sympy/parsing/autolev/test-examples/ruletest5.al,sha256=VuiKjiFmLK3uEdho0m3pk-n0qm4SNLoLPMRJqjMJ4GY,516 +sympy/parsing/autolev/test-examples/ruletest5.py,sha256=WvUtno1D3BrmFNPYYIBKR_gOA-PaHoxLlSTNDX67dcQ,1991 +sympy/parsing/autolev/test-examples/ruletest6.al,sha256=-HwgTmh_6X3wHjo3PQi7378t8YdizRJClc5Eb5DmjhE,703 +sympy/parsing/autolev/test-examples/ruletest6.py,sha256=vEO0jMOD-KIevAcVexmpvac0MGjN7O_dNipOBJJNzF0,1473 +sympy/parsing/autolev/test-examples/ruletest7.al,sha256=wR9S9rTzO9fyKL6Ofgwzw8XCFCV_p2hBpYotC8TvADI,773 +sympy/parsing/autolev/test-examples/ruletest7.py,sha256=_XvMrMe5r9RLopTrIqMGLhaYvHL1qjteWz9CKcotCL8,1696 +sympy/parsing/autolev/test-examples/ruletest8.al,sha256=P7Nu3Pq2R1mKcuFRc9dRO5jJ1_e5fwWdtqYG8NHVVds,682 +sympy/parsing/autolev/test-examples/ruletest8.py,sha256=8tgbwJ-ir0wiOCsgIFCAu4uD8SieYRrLoLzEfae5YQY,2690 +sympy/parsing/autolev/test-examples/ruletest9.al,sha256=txtZ5RH2p1FvAe6etwetSCH8rLktnpk5z0W72sCOdAA,755 +sympy/parsing/autolev/test-examples/ruletest9.py,sha256=GtqV-Wq2GGJzfblMscAz-KXCzs0P_4XqvA3FIdlPe04,1965 +sympy/parsing/c/__init__.py,sha256=J9CvkNRY-qy6CA06GZYuwTuxdnqas6oUP2g0qLztGro,65 +sympy/parsing/c/__pycache__/__init__.cpython-312.pyc,, +sympy/parsing/c/__pycache__/c_parser.cpython-312.pyc,, +sympy/parsing/c/c_parser.py,sha256=fM1GGRIbjzrVQ7ErfkWz6Xzfjvym030BOoWlQLx37Oc,38124 +sympy/parsing/fortran/__init__.py,sha256=KraiVw2qxIgYeMRTFjs1vkMi-hqqDkxUBv8Rc2gwkCI,73 +sympy/parsing/fortran/__pycache__/__init__.cpython-312.pyc,, +sympy/parsing/fortran/__pycache__/fortran_parser.cpython-312.pyc,, +sympy/parsing/fortran/fortran_parser.py,sha256=RpNQR3eNx5vgfzdt0nEZDCB56kF__SnYMaqWN3zla00,11483 +sympy/parsing/latex/LICENSE.txt,sha256=AHvDClj6QKmW53IEcSDeTq8x9REOT5w7X5P8374urKE,1075 +sympy/parsing/latex/LaTeX.g4,sha256=fG0ZUQPwYQOIbcyaPDAkGvcfGs3ZwwMB8ZnKW5yHUDY,5821 +sympy/parsing/latex/__init__.py,sha256=CfRRwZZo2qMF2HksyjGer8qSwhx0T4wnXsa2HKxCvUE,8968 +sympy/parsing/latex/__pycache__/__init__.cpython-312.pyc,, +sympy/parsing/latex/__pycache__/_build_latex_antlr.cpython-312.pyc,, +sympy/parsing/latex/__pycache__/_parse_latex_antlr.cpython-312.pyc,, +sympy/parsing/latex/__pycache__/errors.cpython-312.pyc,, +sympy/parsing/latex/_antlr/__init__.py,sha256=TAb79senorEsoYLCLwUa8wg8AUCHzmmZ7tLdi0XGNaE,384 +sympy/parsing/latex/_antlr/__pycache__/__init__.cpython-312.pyc,, +sympy/parsing/latex/_antlr/__pycache__/latexlexer.cpython-312.pyc,, +sympy/parsing/latex/_antlr/__pycache__/latexparser.cpython-312.pyc,, +sympy/parsing/latex/_antlr/latexlexer.py,sha256=Y1hmY1VGL5FTSSlToTRQydPnyaLLNy1mDSWx76HaYwM,30502 +sympy/parsing/latex/_antlr/latexparser.py,sha256=ZvonpvTS3vLSOVpas88M3CfNnUhPUDsCCPPk4wBYUGE,123655 +sympy/parsing/latex/_build_latex_antlr.py,sha256=3Mwip9f_yXUNhiwwUTCG5Nk8l2uzAw8oZHU0HSl5gkE,2765 +sympy/parsing/latex/_parse_latex_antlr.py,sha256=sVaO04oSeHe_TaMeM-6toheCR88G_RmJYpUIx-Sef1g,20712 +sympy/parsing/latex/errors.py,sha256=adSpvQyWjTLsbN_2KHJ4HuXpY7_U9noeWiG0lskYLgE,45 +sympy/parsing/latex/lark/__init__.py,sha256=hhhvfKRGP3ON36wRJwVfxMWw_GA6rl0JKsIzjuaUX38,120 +sympy/parsing/latex/lark/__pycache__/__init__.cpython-312.pyc,, +sympy/parsing/latex/lark/__pycache__/latex_parser.cpython-312.pyc,, +sympy/parsing/latex/lark/__pycache__/transformer.cpython-312.pyc,, +sympy/parsing/latex/lark/grammar/greek_symbols.lark,sha256=-G8JGrBredhWAzCaurr1UmqgRMRrAJfs_pANub8kXyA,937 +sympy/parsing/latex/lark/grammar/latex.lark,sha256=yz3DXIHllvRDGHeBmpz49PzDCU92pKexg2RTKX4KhTE,13221 +sympy/parsing/latex/lark/latex_parser.py,sha256=lGFEo_RxSKXYmjVEb_E3DiZ-aXl5tAZyfHklzEuJ9VA,4430 +sympy/parsing/latex/lark/transformer.py,sha256=RuXe8enUnLrzUFC9ZfKQyQ1_IlgA-qPINNng6UnY1x4,25754 +sympy/parsing/mathematica.py,sha256=P2vWEgx_HXv4I_C-6vPE3RXtbpXNT2iIJQBrA6QfqkU,39614 +sympy/parsing/maxima.py,sha256=DhTnXRSAceijyA1OAm86c6TyW9-aeUVoZEELGu0oZtY,1835 +sympy/parsing/sym_expr.py,sha256=-hxarp961eyLtuwUhbg3D3qzy06HrEPZEYpGVcJzAv0,8895 +sympy/parsing/sympy_parser.py,sha256=PRRhNS_0LKBVcHFmg7LGygzxRyQt6-vyCSMisXkRhVE,43832 +sympy/parsing/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/parsing/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/parsing/tests/__pycache__/test_ast_parser.cpython-312.pyc,, +sympy/parsing/tests/__pycache__/test_autolev.cpython-312.pyc,, +sympy/parsing/tests/__pycache__/test_c_parser.cpython-312.pyc,, +sympy/parsing/tests/__pycache__/test_custom_latex.cpython-312.pyc,, +sympy/parsing/tests/__pycache__/test_fortran_parser.cpython-312.pyc,, +sympy/parsing/tests/__pycache__/test_implicit_multiplication_application.cpython-312.pyc,, +sympy/parsing/tests/__pycache__/test_latex.cpython-312.pyc,, +sympy/parsing/tests/__pycache__/test_latex_deps.cpython-312.pyc,, +sympy/parsing/tests/__pycache__/test_latex_lark.cpython-312.pyc,, +sympy/parsing/tests/__pycache__/test_mathematica.cpython-312.pyc,, +sympy/parsing/tests/__pycache__/test_maxima.cpython-312.pyc,, +sympy/parsing/tests/__pycache__/test_sym_expr.cpython-312.pyc,, +sympy/parsing/tests/__pycache__/test_sympy_parser.cpython-312.pyc,, +sympy/parsing/tests/test_ast_parser.py,sha256=lcT8w7mn6UEZ8T-xfA4TqG4Mt7JxY00oHhOW7JtHQfY,803 +sympy/parsing/tests/test_autolev.py,sha256=tQuUFa8YqVdsHPOcUhAwlMKB8Uk08HejDhDCda8lXs0,6647 +sympy/parsing/tests/test_c_parser.py,sha256=VYl3K4if_23iIS-Be8MBSG0OKZo-6xgxHiN22laeAyo,155354 +sympy/parsing/tests/test_custom_latex.py,sha256=vX5uVHw9-UgEcRl0XVNOMgrjBbb1sXDlPLL4D8AeOiQ,2060 +sympy/parsing/tests/test_fortran_parser.py,sha256=SGbawrJ4a780TJAFVMONc7Y3Y8VYgVqsIHxVGaicbxE,11828 +sympy/parsing/tests/test_implicit_multiplication_application.py,sha256=xUlc9TKH4HjimhnvWMwCtTabHAJcHCupFdsuiOsZhUs,7389 +sympy/parsing/tests/test_latex.py,sha256=WvKNJ5mtxfzl-rBiE9hc2aEz81b5BmI3SKO7sRZiNbI,11765 +sympy/parsing/tests/test_latex_deps.py,sha256=oe5vm2eIKn05ZiCcXUaO8X6HCcRmN1qCuTsz6tB7Qrk,426 +sympy/parsing/tests/test_latex_lark.py,sha256=kXmZP-gMLwa5XAcNsd-rF_zrPok0RZuJsa6Ny6zfoLw,36059 +sympy/parsing/tests/test_mathematica.py,sha256=vAxwquc8ArTQE9UNbsO21FqSa6J17sCF-A4vhTPXLY0,13395 +sympy/parsing/tests/test_maxima.py,sha256=iIwnFm0lYD0-JcraUIymogqEMN3ji0c-0JeNFFGTEDs,1987 +sympy/parsing/tests/test_sym_expr.py,sha256=-wNR7GwvJHVmPSZxSuAuoX1_FJk83O0tcDi09qYY6Jk,5668 +sympy/parsing/tests/test_sympy_parser.py,sha256=H_dDL89ASex3sI8F92ceXIJy5Qd137rxTa20Rj-9l2A,12946 +sympy/physics/__init__.py,sha256=F_yvUMCuBq3HR-3Ai6W4oktBsXRg8KdutFLwT9FFJlY,220 +sympy/physics/__pycache__/__init__.cpython-312.pyc,, +sympy/physics/__pycache__/hydrogen.cpython-312.pyc,, +sympy/physics/__pycache__/matrices.cpython-312.pyc,, +sympy/physics/__pycache__/paulialgebra.cpython-312.pyc,, +sympy/physics/__pycache__/pring.cpython-312.pyc,, +sympy/physics/__pycache__/qho_1d.cpython-312.pyc,, +sympy/physics/__pycache__/secondquant.cpython-312.pyc,, +sympy/physics/__pycache__/sho.cpython-312.pyc,, +sympy/physics/__pycache__/wigner.cpython-312.pyc,, +sympy/physics/biomechanics/__init__.py,sha256=dG1IoRAnmfXvSyPciqJVrPn5LLnuvbVnBt78hBG0maQ,1520 +sympy/physics/biomechanics/__pycache__/__init__.cpython-312.pyc,, +sympy/physics/biomechanics/__pycache__/_mixin.cpython-312.pyc,, +sympy/physics/biomechanics/__pycache__/activation.cpython-312.pyc,, +sympy/physics/biomechanics/__pycache__/curve.cpython-312.pyc,, +sympy/physics/biomechanics/__pycache__/musculotendon.cpython-312.pyc,, +sympy/physics/biomechanics/_mixin.py,sha256=0D3iBqlCRmR4HXKMxyC2LvYpKGHreOuZY5dXMJioQ4A,1493 +sympy/physics/biomechanics/activation.py,sha256=rUJegXrdO1LPHnzJpVRAYnA6DsvF46ndctkBt1JHDwI,25522 +sympy/physics/biomechanics/curve.py,sha256=PezKOUytiC15oLV11GC4M6u7ndXHpwtbilqdbIiqvgw,63154 +sympy/physics/biomechanics/musculotendon.py,sha256=LrYwFnwkShDWWZQtCgtSUqvc1H5IlTj_BNVKxfFNhE0,58274 +sympy/physics/biomechanics/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/physics/biomechanics/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/physics/biomechanics/tests/__pycache__/test_activation.cpython-312.pyc,, +sympy/physics/biomechanics/tests/__pycache__/test_curve.cpython-312.pyc,, +sympy/physics/biomechanics/tests/__pycache__/test_mixin.cpython-312.pyc,, +sympy/physics/biomechanics/tests/__pycache__/test_musculotendon.cpython-312.pyc,, +sympy/physics/biomechanics/tests/test_activation.py,sha256=hdnMsFBLjloJylu8-cLZ44oamORG3kSsI0q2-eLQ_-I,13395 +sympy/physics/biomechanics/tests/test_curve.py,sha256=3jbWEHr8ieZYCfVlwJ1KTA1WJ9dcTCyQ1p3r8G2jp1I,75800 +sympy/physics/biomechanics/tests/test_mixin.py,sha256=ds-EoUCvfiSjVGnC_mBwjn5mI7z5W5wi2UTZZ4-pIIQ,1322 +sympy/physics/biomechanics/tests/test_musculotendon.py,sha256=Ls59mtJQ83W0fdpDGFGNeTgtxL8yAZ6ODW96N9mvFtM,32906 +sympy/physics/continuum_mechanics/__init__.py,sha256=GzYypKq3so15xfvY4qFerHYCNGFzZthfQ1aOcgu8yCM,191 +sympy/physics/continuum_mechanics/__pycache__/__init__.cpython-312.pyc,, +sympy/physics/continuum_mechanics/__pycache__/arch.cpython-312.pyc,, +sympy/physics/continuum_mechanics/__pycache__/beam.cpython-312.pyc,, +sympy/physics/continuum_mechanics/__pycache__/cable.cpython-312.pyc,, +sympy/physics/continuum_mechanics/__pycache__/truss.cpython-312.pyc,, +sympy/physics/continuum_mechanics/arch.py,sha256=TKaoHk7-ToNP0n6ZGFF_cW6x965C-D3iENiqFo74ZJU,39243 +sympy/physics/continuum_mechanics/beam.py,sha256=Vq1xJHrjatQEUigMsxlAk8qoZSyp_Z_0GiJ5y5AIMIg,159946 +sympy/physics/continuum_mechanics/cable.py,sha256=1IOpa_eLYwdyixNkDhLXJQSg4fQhwOH7Ybm1jWR4aQA,31420 +sympy/physics/continuum_mechanics/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/physics/continuum_mechanics/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/physics/continuum_mechanics/tests/__pycache__/test_arch.cpython-312.pyc,, +sympy/physics/continuum_mechanics/tests/__pycache__/test_beam.cpython-312.pyc,, +sympy/physics/continuum_mechanics/tests/__pycache__/test_cable.cpython-312.pyc,, +sympy/physics/continuum_mechanics/tests/__pycache__/test_truss.cpython-312.pyc,, +sympy/physics/continuum_mechanics/tests/test_arch.py,sha256=t_V-Pt0fxoPqYDZl5LB6ehQ4hBBVlveRWLsEXdyo_3k,2571 +sympy/physics/continuum_mechanics/tests/test_beam.py,sha256=Wmi8BCju21H1RaomKDqFATvCUqsrca_43o5IyA5s4ok,42085 +sympy/physics/continuum_mechanics/tests/test_cable.py,sha256=aANZVJxfihRkjAauCvFPGkXKD_zxMcJFb7vXU443dsQ,3832 +sympy/physics/continuum_mechanics/tests/test_truss.py,sha256=wgtF1GbQX5hzx20UrBg2ZyEvplVpsio3DiU8CS_bAk8,3269 +sympy/physics/continuum_mechanics/truss.py,sha256=hkLLnXA9aRaE2YvA0ods7T40zJQXUc_jLI108NjhtTI,44962 +sympy/physics/control/__init__.py,sha256=U0BeOmFRXOw-cpZ_F-RzNuEh78Tqzx31nuvZMZW2Fo8,1334 +sympy/physics/control/__pycache__/__init__.cpython-312.pyc,, +sympy/physics/control/__pycache__/control_plots.cpython-312.pyc,, +sympy/physics/control/__pycache__/lti.cpython-312.pyc,, +sympy/physics/control/control_plots.py,sha256=lYa42ATTrSXMV44Q3POfEyYQCFSTV1W5Rb4UejYFdT8,37515 +sympy/physics/control/lti.py,sha256=o6n-qFXriBeETr4anCgOuYViUpQXDtBejckIdYdlxx0,177322 +sympy/physics/control/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/physics/control/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/physics/control/tests/__pycache__/test_control_plots.cpython-312.pyc,, +sympy/physics/control/tests/__pycache__/test_lti.cpython-312.pyc,, +sympy/physics/control/tests/test_control_plots.py,sha256=dsXkabVUMzU6b1FmptRz2sGgXfe6y_lu3Mm0KN8is90,16899 +sympy/physics/control/tests/test_lti.py,sha256=YAvwA11zSKRcHmgLPuCJhBJXbFrPfjUNytaQsnEsEr8,104043 +sympy/physics/hep/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/physics/hep/__pycache__/__init__.cpython-312.pyc,, +sympy/physics/hep/__pycache__/gamma_matrices.cpython-312.pyc,, +sympy/physics/hep/gamma_matrices.py,sha256=WlSHLUtMU7NrgLyKEvTntMSYxMZq1r_6o2kqUEAdPaA,24253 +sympy/physics/hep/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/physics/hep/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/physics/hep/tests/__pycache__/test_gamma_matrices.cpython-312.pyc,, +sympy/physics/hep/tests/test_gamma_matrices.py,sha256=iKqICj0bP7EK0sSuYFsPdPkDTbHGa6J_LMPZAzv1j4o,14722 +sympy/physics/hydrogen.py,sha256=R2wnNi1xB-WTQ8Z9aPUhX9Z8mQ8TdhCM1JAZIkyXgjw,7594 +sympy/physics/matrices.py,sha256=jHfbWkzL2myFt-39kodQo5wPubBxNZKXlljuSxZL4bE,3836 +sympy/physics/mechanics/__init__.py,sha256=7rgPJp1YItAMOc29gWqkRp68AKCdZLu4tFQG-CWgjOQ,2874 +sympy/physics/mechanics/__pycache__/__init__.cpython-312.pyc,, +sympy/physics/mechanics/__pycache__/actuator.cpython-312.pyc,, +sympy/physics/mechanics/__pycache__/body.cpython-312.pyc,, +sympy/physics/mechanics/__pycache__/body_base.cpython-312.pyc,, +sympy/physics/mechanics/__pycache__/functions.cpython-312.pyc,, +sympy/physics/mechanics/__pycache__/inertia.cpython-312.pyc,, +sympy/physics/mechanics/__pycache__/joint.cpython-312.pyc,, +sympy/physics/mechanics/__pycache__/jointsmethod.cpython-312.pyc,, +sympy/physics/mechanics/__pycache__/kane.cpython-312.pyc,, +sympy/physics/mechanics/__pycache__/lagrange.cpython-312.pyc,, +sympy/physics/mechanics/__pycache__/linearize.cpython-312.pyc,, +sympy/physics/mechanics/__pycache__/loads.cpython-312.pyc,, +sympy/physics/mechanics/__pycache__/method.cpython-312.pyc,, +sympy/physics/mechanics/__pycache__/models.cpython-312.pyc,, +sympy/physics/mechanics/__pycache__/particle.cpython-312.pyc,, +sympy/physics/mechanics/__pycache__/pathway.cpython-312.pyc,, +sympy/physics/mechanics/__pycache__/rigidbody.cpython-312.pyc,, +sympy/physics/mechanics/__pycache__/system.cpython-312.pyc,, +sympy/physics/mechanics/__pycache__/wrapping_geometry.cpython-312.pyc,, +sympy/physics/mechanics/actuator.py,sha256=d7Ffb9vo1Tmrcfiy71_g0r1btscfvvabE-vznku3Auk,43633 +sympy/physics/mechanics/body.py,sha256=Z9ZOReEab9FHEDsyv2RfIBQM4_ripXhFXmQtu1OmN_Y,24617 +sympy/physics/mechanics/body_base.py,sha256=bwP04lWmD0iY_T0Vsn6NWMbnWyzUMFFqkAoAyKsow_c,2491 +sympy/physics/mechanics/functions.py,sha256=KsX3z33rZdMCifwyVlyKIHVJh0Fve--zs5wd1rkGMl0,25190 +sympy/physics/mechanics/inertia.py,sha256=FKcEbpYPx_26LS9sSp8lcsJ83spqwSYIyxM5q_z1mYA,6172 +sympy/physics/mechanics/joint.py,sha256=o9SWJ9pXDO-sVh0gJ6VTI0LgY019gFB5w5FP1PN--UI,84621 +sympy/physics/mechanics/jointsmethod.py,sha256=nqkXawtuxeyP0D8DEAYURCJlDYS4Eka_vXx6UZP7y74,10415 +sympy/physics/mechanics/kane.py,sha256=XyvEDNF09i5DnHf-YlCecEHDdKK9j486N2P5YD8_XaM,37118 +sympy/physics/mechanics/lagrange.py,sha256=UTmClOP-PkY8S-LcPlcOAUmshndlq6mpmZailbvy4E4,20202 +sympy/physics/mechanics/linearize.py,sha256=YtAap6TzsZJd794cdDCEDJVlMOXd_wFAMaCZZacHwbE,17242 +sympy/physics/mechanics/loads.py,sha256=jnajZOg631Aqtd0-BplehohUL991C3Cji2OZZ3MVHdk,5406 +sympy/physics/mechanics/method.py,sha256=2vFRhA79ra4HR6AzVBHMr3oNncrcqgLLMRqdyif0DrI,660 +sympy/physics/mechanics/models.py,sha256=9q1g3I2xYpuTMi-v9geswEqxJWTP3RjcOquRfzMhHzM,6463 +sympy/physics/mechanics/particle.py,sha256=YKiEBkPLVRI9foXlEe8eu8Ys5W1GyQO1oOBf0T8fHFg,5985 +sympy/physics/mechanics/pathway.py,sha256=2T71x06X8CZ20NUyXkMnP83gKsx2wJJEbPJS-1gMXFA,26555 +sympy/physics/mechanics/rigidbody.py,sha256=s5b7ynsdcMsq9PN2nM1yozNcZd08RA-MgzMjcs7jnBI,10287 +sympy/physics/mechanics/system.py,sha256=VsPPQfJs0gBLKJYNQ2ZLmD98JWLd1IZy0QGRwI21_TM,59457 +sympy/physics/mechanics/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/physics/mechanics/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_actuator.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_body.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_functions.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_inertia.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_joint.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_jointsmethod.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_kane.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_kane2.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_kane3.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_kane4.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_kane5.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_lagrange.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_lagrange2.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_linearity_of_velocity_constraints.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_linearize.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_loads.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_method.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_models.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_particle.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_pathway.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_rigidbody.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_system.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_system_class.cpython-312.pyc,, +sympy/physics/mechanics/tests/__pycache__/test_wrapping_geometry.cpython-312.pyc,, +sympy/physics/mechanics/tests/test_actuator.py,sha256=WoTnD_IGhewVOzcL7ybJXf_mrK0_E71gDcnon-3Mayg,41081 +sympy/physics/mechanics/tests/test_body.py,sha256=ygHfWeL6-3LW9gqXHfzdvqQhJWxg2-U2KQIHKqGNqKQ,12067 +sympy/physics/mechanics/tests/test_functions.py,sha256=Cl1aT3qT-0Ik6vJgS6at6PUaeWRQfpEG88QvEIxz1Bk,10447 +sympy/physics/mechanics/tests/test_inertia.py,sha256=On4K78tmq4tyr_QFs3Uo01efdlVj5R6yfn6CVs7ksnE,2726 +sympy/physics/mechanics/tests/test_joint.py,sha256=ojhQdBsWN6nR7egEhpw-LAyDRdFIPfSEsDoFL1bhzqs,57922 +sympy/physics/mechanics/tests/test_jointsmethod.py,sha256=8IUO7ntLPsydDT4YgA1FPyO5TXNpo4CIWC7O_JdWg9Q,10226 +sympy/physics/mechanics/tests/test_kane.py,sha256=K1HOm7cuPzXeO9ZmW7oAHgu-jxOg1IFqyKB3YheAbus,21545 +sympy/physics/mechanics/tests/test_kane2.py,sha256=qNLkbSV6UYclQzMDoRi_TJrJEz0-MUi7yf1e7XW4ba4,19256 +sympy/physics/mechanics/tests/test_kane3.py,sha256=-9MbXLfYUDhA_9D2o4NrNLgDTOnKDLLsgryQW3AHacs,14959 +sympy/physics/mechanics/tests/test_kane4.py,sha256=qJYUfvnq1F5UN_AQqTu_3BT5XqGceqxnCyP3d2gE04A,4709 +sympy/physics/mechanics/tests/test_kane5.py,sha256=gZvAyxJ8fkkLtH60xHlb_Gxrbt9d7VmJTckXSGmF0j4,5693 +sympy/physics/mechanics/tests/test_lagrange.py,sha256=iuHomulBF8MafLeorKGaLHUEF8CvFhXcxEtN0hk1akM,10119 +sympy/physics/mechanics/tests/test_lagrange2.py,sha256=VBonbWg0uLduE4AwNUWCsGGa_2KmaDbg9jROZL3DTWE,1402 +sympy/physics/mechanics/tests/test_linearity_of_velocity_constraints.py,sha256=Y9JYoaob8yyL7PS-VN7g-DC8YEfCxBGdFSSkQAKlOBI,1341 +sympy/physics/mechanics/tests/test_linearize.py,sha256=6yFFGEhJW60fx9Ny1duc6eyvGDg6rtmJVo_V1mgHgGk,13273 +sympy/physics/mechanics/tests/test_loads.py,sha256=Kw94kP0tfwKsV-jCDHGTQsyc-1dKQl3ABJfqJtR8AJg,2698 +sympy/physics/mechanics/tests/test_method.py,sha256=L7CnsvbQC-U7ijbSZdu7DEr03p88OLj4IPvFJ_3kCDo,154 +sympy/physics/mechanics/tests/test_models.py,sha256=GcsfCm5G4PPYQXsHCiAKI1dEW42RaZOh-x6aEouTYo4,5078 +sympy/physics/mechanics/tests/test_particle.py,sha256=JL6QAA6T3POQkSutUnungrVkR3xt6ZVX-hp75-EufQw,2682 +sympy/physics/mechanics/tests/test_pathway.py,sha256=oGCxlUOviyNc1GBMvhk5sYVZfu8C4o7lJMbqatBie3A,24944 +sympy/physics/mechanics/tests/test_rigidbody.py,sha256=ezMW5BWt9cWdNeY1B9aYcL4NsPcVkaKZuUS1C7S1qPk,6188 +sympy/physics/mechanics/tests/test_system.py,sha256=Dihu77qM5_QkDQg-zavHbVhh_nvaGEVztXgPNl2_enk,8700 +sympy/physics/mechanics/tests/test_system_class.py,sha256=Xe4VLrxWaYL3oRwP2SBaanWf5DY46d2yPlwf9H1XJ4M,38219 +sympy/physics/mechanics/tests/test_wrapping_geometry.py,sha256=aXwuEaprstnSW7BwLr3OKUyxSagRPO58L-tUMaq3I9s,10502 +sympy/physics/mechanics/wrapping_geometry.py,sha256=XkI331oQcBme4jDmH0RqQDWh_pq49o38nbRsXwT9O5E,21599 +sympy/physics/optics/__init__.py,sha256=0UmqIt2-u8WwNkAqsnOVt9VlkB9K0CRIJYiQaltJ73w,1647 +sympy/physics/optics/__pycache__/__init__.cpython-312.pyc,, +sympy/physics/optics/__pycache__/gaussopt.cpython-312.pyc,, +sympy/physics/optics/__pycache__/medium.cpython-312.pyc,, +sympy/physics/optics/__pycache__/polarization.cpython-312.pyc,, +sympy/physics/optics/__pycache__/utils.cpython-312.pyc,, +sympy/physics/optics/__pycache__/waves.cpython-312.pyc,, +sympy/physics/optics/gaussopt.py,sha256=mVQ-JX7xmAp9XbNOYIlwsPAxkUukTw_QjbjIxuKWZW8,20898 +sympy/physics/optics/medium.py,sha256=cys0tWGi1VCPWMTZuKadcN_bToz_bqKsDHSEVzuV3CE,7124 +sympy/physics/optics/polarization.py,sha256=mIrZiOVXetGtKkLxl8Llaf2Z9coWenf6JKrClh4W8yU,21434 +sympy/physics/optics/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/physics/optics/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/physics/optics/tests/__pycache__/test_gaussopt.cpython-312.pyc,, +sympy/physics/optics/tests/__pycache__/test_medium.cpython-312.pyc,, +sympy/physics/optics/tests/__pycache__/test_polarization.cpython-312.pyc,, +sympy/physics/optics/tests/__pycache__/test_utils.cpython-312.pyc,, +sympy/physics/optics/tests/__pycache__/test_waves.cpython-312.pyc,, +sympy/physics/optics/tests/test_gaussopt.py,sha256=QMXJw_6mFCC3918b-pc_4b_zgO8Hsk7_SBvMupbEi5I,4222 +sympy/physics/optics/tests/test_medium.py,sha256=RxG7N3lzmCO_8hIoKyPnDKffmk8QFzA9yamu1_mr_dE,2194 +sympy/physics/optics/tests/test_polarization.py,sha256=81MzyA29HZckg_Ss-88-5o0g9augDqCr_LwcJIiXuA0,2605 +sympy/physics/optics/tests/test_utils.py,sha256=SjicjAptcZGwuX-ib_Lq7PlGONotvo2XJ4p3JA9iNVI,8553 +sympy/physics/optics/tests/test_waves.py,sha256=PeFfrl7MBkWBHdc796sDDYDuhGepat3DQk7PmyTXVnw,3397 +sympy/physics/optics/utils.py,sha256=BqfuvtrjO3PEcDQ1DecNyt2Th9Yps6xued1tEY4ysvk,22172 +sympy/physics/optics/waves.py,sha256=Iw-9gGksvWhPmQ_VepmI90ekKyzHdPlq6U41wdM4ikI,10042 +sympy/physics/paulialgebra.py,sha256=1r_qDBbVyl836qIXlVDdoF89Z9wedGvWIkHAbwQaK-4,6002 +sympy/physics/pring.py,sha256=SCMGGIcEhVoD7dwhY7_NWL1iKwo7OfgKdmm2Ok_9Xl0,2240 +sympy/physics/qho_1d.py,sha256=ZXemUsa_b0rLtPVTUkgAkZQ1Ecu2eIZxaiNSSXW0PDk,2005 +sympy/physics/quantum/__init__.py,sha256=vzWc2d2aXbMdZGJRx4tyS6FDCtjbtl7SqCJE7nSXN9A,1952 +sympy/physics/quantum/__pycache__/__init__.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/anticommutator.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/boson.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/cartesian.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/cg.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/circuitplot.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/circuitutils.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/commutator.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/constants.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/dagger.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/density.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/fermion.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/gate.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/grover.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/hilbert.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/identitysearch.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/innerproduct.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/kind.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/matrixcache.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/matrixutils.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/operator.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/operatorordering.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/operatorset.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/pauli.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/piab.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/qapply.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/qasm.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/qexpr.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/qft.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/qubit.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/represent.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/sho1d.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/shor.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/spin.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/state.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/tensorproduct.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/trace.cpython-312.pyc,, +sympy/physics/quantum/__pycache__/transforms.cpython-312.pyc,, +sympy/physics/quantum/anticommutator.py,sha256=kXr7DWZZy0Sqcnxx-QEeA58mUCRXTL_VHDzQBjNV0DI,5072 +sympy/physics/quantum/boson.py,sha256=Nn4TN917TQv4tdFNZddlT1eEGg7O1uybnU9K5NI6AyM,5834 +sympy/physics/quantum/cartesian.py,sha256=9R9VDYLV1Xe-GkA9TQbj8PVlBLaD0fF6KXfHJ1ze5as,9092 +sympy/physics/quantum/cg.py,sha256=WK7HkAIRFejQQLjRsCC7rH0L--0fmXAoeL1JdTHb3GA,23319 +sympy/physics/quantum/circuitplot.py,sha256=SacQMhPyDhizKmGRNEs1vtXph8lR6bMn5bVJI4rJiXg,11799 +sympy/physics/quantum/circuitutils.py,sha256=mrQNUDbwM3LV1NZ1EqVpXyOY2mOXCBVZW7cQTiCxUaM,13882 +sympy/physics/quantum/commutator.py,sha256=MKk8OqwIi8LCzxkD8URmKCFM9OthAAxS8xFNgP_i09U,8139 +sympy/physics/quantum/constants.py,sha256=20VRATCkSprSnGFR5ejvMEYlWwEcv1B-dE3RPqPTQ9k,1420 +sympy/physics/quantum/dagger.py,sha256=P58FL8fLFfMhtu79jGsG69oEMjLjutRDrXsLwBat-9U,2484 +sympy/physics/quantum/density.py,sha256=ie_NJO-YNJ3PydAMp3jlmhC5H8bN3ldhn2SiCKY5N0s,9546 +sympy/physics/quantum/fermion.py,sha256=1ipn3FItUJ_ruLnflpp9MN_6t5w8CgHAJRJCOsukGGI,4983 +sympy/physics/quantum/gate.py,sha256=Iv7-qhSCe_An9qaJcYRDgwr8ClNraP47E75UlS5fCoQ,42588 +sympy/physics/quantum/grover.py,sha256=17KC5MJR3cCavmzqRqi9dB5OFTOpsYjfrTZuv03HiuE,10452 +sympy/physics/quantum/hilbert.py,sha256=qrja92vF7BUeSyHOLKVX8-XKcPGT7QaQMWrqWXjRNus,19632 +sympy/physics/quantum/identitysearch.py,sha256=Zh_ji5J0YeAy2AezsQcHV9W2icWoaa3ZwTbfjCCQmJo,27607 +sympy/physics/quantum/innerproduct.py,sha256=NKlJufh068C3MeKBORJG8k7zdH_vGJeo7jlH67PqU7E,4303 +sympy/physics/quantum/kind.py,sha256=odJyriPZKyievddvlY-kks8iBCSi1yZ7JEsaLANHoe4,2831 +sympy/physics/quantum/matrixcache.py,sha256=S6fPkkYmfX8ELBOc9EST-8XnQ1gtpSOBfd2KwLGKdYo,3587 +sympy/physics/quantum/matrixutils.py,sha256=53VGeUNYNpU1eA1sNcYFaX1_45I9SVabCfpTyHUDFog,8214 +sympy/physics/quantum/operator.py,sha256=Q-uiUjAZgMOXHKoBFe2oW_qJsJSjC8fM246yzxMmZ0A,19657 +sympy/physics/quantum/operatorordering.py,sha256=byAyZCNKTCeFWIFThmNx0NgdI4u32O4ydodYSa6Wrr8,10296 +sympy/physics/quantum/operatorset.py,sha256=h8nkScpQcUzCO3zemqKpgQfJDWiBbfj33IJzcl4J2_4,9563 +sympy/physics/quantum/pauli.py,sha256=lzxWFHXqxKWRiYK99QCo9zuVG9eVXiB8vFya7TvrVxQ,17250 +sympy/physics/quantum/piab.py,sha256=Zjb2cRGniVDV6e35gjP4uEpI4w0C7YGQIEXReaq_z-E,1912 +sympy/physics/quantum/qapply.py,sha256=5vqWe__WRvJuD6sWC2NTDe1qEcToBGTGaye9lzirgf4,9494 +sympy/physics/quantum/qasm.py,sha256=UWpcUIBgkK55SmEBZlpmz-1KGHZvW7dNeSVG8tHr44A,6288 +sympy/physics/quantum/qexpr.py,sha256=N87sU5AqFbGEXgHJof-B7ua46rk4SeysK16abU1GfYI,13940 +sympy/physics/quantum/qft.py,sha256=ua4qBQAm-gi923lRRxOgAebTsTCoR93pz8ZHPXBdcus,6425 +sympy/physics/quantum/qubit.py,sha256=mE0xebz8zqeKEc4xww9-Iv7tZzxHjm9Klsr2WgUQcVM,25997 +sympy/physics/quantum/represent.py,sha256=dBY9RLD21V0WuIBbigagjaLSUCiloDzitv8Wl6fU9dE,18729 +sympy/physics/quantum/sho1d.py,sha256=ZroR_FjxmjOmDcd0Fm04vWKTGCpvLaEu4NiuplKm708,20867 +sympy/physics/quantum/shor.py,sha256=DVwPxLAPSr8t3F3aXJIPe4o5XSuQiE6a6eA6OYmdZFw,5504 +sympy/physics/quantum/spin.py,sha256=l6168fTEZEC4FeaMS8iLqo3b4YMvUlPTZvq9N8iSV08,72986 +sympy/physics/quantum/state.py,sha256=618YaDGAtpUeuWCVYs6lDuO3mD87_f8KIUGUXaN9L4s,29971 +sympy/physics/quantum/tensorproduct.py,sha256=PvpDSuLku1IdIV3T2dK3fVv6AdMNVcc5eR8n34AB3OQ,12599 +sympy/physics/quantum/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/physics/quantum/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_anticommutator.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_boson.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_cartesian.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_cg.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_circuitplot.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_circuitutils.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_commutator.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_constants.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_dagger.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_density.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_fermion.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_gate.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_grover.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_hilbert.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_identitysearch.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_innerproduct.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_kind.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_matrixutils.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_operator.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_operatorordering.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_operatorset.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_pauli.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_piab.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_printing.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_qapply.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_qasm.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_qexpr.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_qft.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_qubit.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_represent.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_sho1d.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_shor.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_spin.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_state.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_tensorproduct.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_trace.cpython-312.pyc,, +sympy/physics/quantum/tests/__pycache__/test_transforms.cpython-312.pyc,, +sympy/physics/quantum/tests/test_anticommutator.py,sha256=ckWHKwQFiAMWcDaYSa_26vi_GIsvs32_0O62I5lGsr8,1304 +sympy/physics/quantum/tests/test_boson.py,sha256=BZjdrZ-F1QhyhDqfK4Zc1VEFBJi1PeiPjMpfBcHekfo,1676 +sympy/physics/quantum/tests/test_cartesian.py,sha256=4szaB4w555oDUkhaRtBF8mOfIxiODNCqOlDHEVcUFOo,4417 +sympy/physics/quantum/tests/test_cg.py,sha256=BF-2ybLhoAYOb0wfWFlgnobMzH20zTYJvW5Z7v46SYI,9159 +sympy/physics/quantum/tests/test_circuitplot.py,sha256=c3v9wUzLHUH-eBVGj6_broVhHkioNwpaaApTDAJEflU,2096 +sympy/physics/quantum/tests/test_circuitutils.py,sha256=GrJAWRQVH_l8EIHrj1ve2jtxske72IriQ3lo94fqrVQ,13187 +sympy/physics/quantum/tests/test_commutator.py,sha256=keBstGDpNITFRr06uVFrka_Lje56g6oFoJQEpZXmnYw,2727 +sympy/physics/quantum/tests/test_constants.py,sha256=KBmYPIF49Sq34lbzbFCZRYWSyIdhnR3AK3q-VbU6grU,338 +sympy/physics/quantum/tests/test_dagger.py,sha256=pi2lhL5EaE8FuIuwM9gOce2NpDCP4S1JptqI-mx8FGM,2632 +sympy/physics/quantum/tests/test_density.py,sha256=EyxiEgyc0nDSweJwI0JUwta7gZ81TVHCl7YDEosTrvI,9718 +sympy/physics/quantum/tests/test_fermion.py,sha256=RK-J3nV1UO_9R5UyrBIp_qfWX-5iZ152aoyEllKWSIc,1636 +sympy/physics/quantum/tests/test_gate.py,sha256=7oBX1HoWnrYtHjABRoqv_wQDB9B829E99fdcJzaqawM,12496 +sympy/physics/quantum/tests/test_grover.py,sha256=uze62AG6H4x2MYJJA-EY3NtkqwvrDIQ2kONuvIRQiZ4,3640 +sympy/physics/quantum/tests/test_hilbert.py,sha256=IGP6rc2-b3we9dRDbpRniFAhQwp_TYtMfFzxusAprx0,2643 +sympy/physics/quantum/tests/test_identitysearch.py,sha256=3YGrXCsFLhLtN5MRyT5ZF8ELrSdkvDKTv6xKM4i2ims,17745 +sympy/physics/quantum/tests/test_innerproduct.py,sha256=37tT8p6MhHjAYeoay1Zyv7gCs-DeZQi4VdwUH2IffDE,1483 +sympy/physics/quantum/tests/test_kind.py,sha256=MCc0jobaf-fZmi99ir2VpZM1Lah5w9ZMxqygVQZfleU,2515 +sympy/physics/quantum/tests/test_matrixutils.py,sha256=wXc2jYLYaR07MgbVBpUU0cEsy2YQhQygbHV6M55u_ss,4115 +sympy/physics/quantum/tests/test_operator.py,sha256=kmNGQzjtdsko6PlUNcTT0kjOYX73LOMzHGuncS2SjSw,8417 +sympy/physics/quantum/tests/test_operatorordering.py,sha256=SFvJfrBxreMgMB3PEpXGcTvO_113Pi1O-Jco-A9_aVI,2003 +sympy/physics/quantum/tests/test_operatorset.py,sha256=DNfBeYBa_58kSG7PM5Ilo6xnzek8lSiAGX01uMFRYqI,2628 +sympy/physics/quantum/tests/test_pauli.py,sha256=Bhsx_gj5cpYv4BhVJRQohxlKk_rcp4jHtSRlTP-m_xs,4940 +sympy/physics/quantum/tests/test_piab.py,sha256=8ndnzyIsjF4AOu_9k6Yqap_1XUDTbiGnv7onJdrZBWA,1086 +sympy/physics/quantum/tests/test_printing.py,sha256=Qg34sHUAgKeh7DhHNp3KQX0_bhfdkMPCKJUvL08ufz8,30332 +sympy/physics/quantum/tests/test_qapply.py,sha256=ol5IJuuPand4r-P2cBv_Wycv2wnkMsW3dlJxDAp_PSs,6086 +sympy/physics/quantum/tests/test_qasm.py,sha256=ZvMjiheWBceSmIM9LHOL5fiFUl6HsUo8puqdzywrhkc,2976 +sympy/physics/quantum/tests/test_qexpr.py,sha256=0a80r2d31yxuJn11CcemrMn855o2ge5CH8j73ZCwuKI,1830 +sympy/physics/quantum/tests/test_qft.py,sha256=v-sGTaW9S-gcGTDAUPvjwd1kINF6rlI_u5Sf-Gso0r8,1931 +sympy/physics/quantum/tests/test_qubit.py,sha256=rj5RNjLWjZ8514fQwEsVp0wuUlI1SKAIomL0wZ-9PqA,9271 +sympy/physics/quantum/tests/test_represent.py,sha256=lEwzpL0fGxDGkojZ4_WoBAtCcA7aq2-S-i0Z0QrnTXg,5177 +sympy/physics/quantum/tests/test_sho1d.py,sha256=1QCoRXwhcK-P1oUrREgAroPHJPzPgWEBSrHomjS3meA,6893 +sympy/physics/quantum/tests/test_shor.py,sha256=3a3GCg6V5_mlJ2bltoXinGMGvlSxpq7GluapD_3SZaQ,666 +sympy/physics/quantum/tests/test_spin.py,sha256=p6F0cfQkPYwXlzE29mTL-dpsEYZmFU0EfAwm2MUA9xE,345698 +sympy/physics/quantum/tests/test_state.py,sha256=pjNwjEQN1zMXzC6NbL60ZLzpqBfZD5RscjuyiFuhTaE,6748 +sympy/physics/quantum/tests/test_tensorproduct.py,sha256=CL8xJyUl7plFU7TYsHHkLDYt9PtS4SM_H-SG4lKM5aE,5314 +sympy/physics/quantum/tests/test_trace.py,sha256=dbpTXcJArWRR_Hh5JTuy2GJIfgjVo6zS20o5mdVEGH4,3057 +sympy/physics/quantum/tests/test_transforms.py,sha256=w1fLTJO07CWPOQp5jFVU83MatsaoNBkxOI_YbM6I1w8,2346 +sympy/physics/quantum/trace.py,sha256=2ZqN9IEsz3LKHTLV8ZDwTK0sM5PfwL0p2sYet0N7Gis,6397 +sympy/physics/quantum/transforms.py,sha256=XLnWmyoWW8oXJ8I7dUIF7cMxFt9xr736HfNstD_tnK0,10929 +sympy/physics/secondquant.py,sha256=1XDsbnUpFC7zmJ4VC9DXEsK_smSqNMaDfsi6slIkws0,90974 +sympy/physics/sho.py,sha256=K8P9FAdZr6UfQKYZO9TlhDUqUd3YsMekXCsKy2HhaY0,2480 +sympy/physics/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/physics/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/physics/tests/__pycache__/test_clebsch_gordan.cpython-312.pyc,, +sympy/physics/tests/__pycache__/test_hydrogen.cpython-312.pyc,, +sympy/physics/tests/__pycache__/test_paulialgebra.cpython-312.pyc,, +sympy/physics/tests/__pycache__/test_physics_matrices.cpython-312.pyc,, +sympy/physics/tests/__pycache__/test_pring.cpython-312.pyc,, +sympy/physics/tests/__pycache__/test_qho_1d.cpython-312.pyc,, +sympy/physics/tests/__pycache__/test_secondquant.cpython-312.pyc,, +sympy/physics/tests/__pycache__/test_sho.cpython-312.pyc,, +sympy/physics/tests/test_clebsch_gordan.py,sha256=gHMZnYkigoVWeDV7bwD4YARplb_L1AOMppzcLxSmWnI,9921 +sympy/physics/tests/test_hydrogen.py,sha256=kohRIR6JojE_GWYnlzLsMMgdhoKd8whazs0mq7cCTQc,4987 +sympy/physics/tests/test_paulialgebra.py,sha256=tyshEMsLNPR4iYzoAbPGZRZ-e_8t7GDP_xyjRyhepeQ,1477 +sympy/physics/tests/test_physics_matrices.py,sha256=Dha8iQRhzxLcl7TKSA6QP0pnEcBoqtj_Ob6tx01SMwI,2948 +sympy/physics/tests/test_pring.py,sha256=XScQQO9RhRrlqSII_ZyyOUpE-zs-7wphSFCZq2OuFnE,1261 +sympy/physics/tests/test_qho_1d.py,sha256=LD9WU-Y5lW7bVM7MyCkSGW9MU2FZhVjMB5Zk848_q1M,1775 +sympy/physics/tests/test_secondquant.py,sha256=vI9EuCMd1PMYNbZH2bHW9xHPYS5DS92QOmAk1kC12cQ,49401 +sympy/physics/tests/test_sho.py,sha256=aIs1f3eo6hb4ErRU8xrr_h_yhTmRx-fQgv9n27SfsLM,693 +sympy/physics/units/__init__.py,sha256=DVvWy9qNRm742NFGcBpybFY20ZK3BU7DWNbLMTXYiFo,12386 +sympy/physics/units/__pycache__/__init__.cpython-312.pyc,, +sympy/physics/units/__pycache__/dimensions.cpython-312.pyc,, +sympy/physics/units/__pycache__/prefixes.cpython-312.pyc,, +sympy/physics/units/__pycache__/quantities.cpython-312.pyc,, +sympy/physics/units/__pycache__/unitsystem.cpython-312.pyc,, +sympy/physics/units/__pycache__/util.cpython-312.pyc,, +sympy/physics/units/definitions/__init__.py,sha256=F3RyZc1AjM2Ch5b27Tt-VYdZ1HAIWvhgtQQQTfMiN6w,7470 +sympy/physics/units/definitions/__pycache__/__init__.cpython-312.pyc,, +sympy/physics/units/definitions/__pycache__/dimension_definitions.cpython-312.pyc,, +sympy/physics/units/definitions/__pycache__/unit_definitions.cpython-312.pyc,, +sympy/physics/units/definitions/dimension_definitions.py,sha256=QmPLCy7GvLx1z_YEZ5KFl8QUXg4rcuu3PuNI5wLpPdY,1633 +sympy/physics/units/definitions/unit_definitions.py,sha256=05wpHmAtyQvuJBeuzWm3cDQ6UYviNtsi4kVc0hv8VHw,14680 +sympy/physics/units/dimensions.py,sha256=GMuoSF1vqKDs_e3JJ7Y0lpFrneXMZLZk_qIC5d6Q5UU,20899 +sympy/physics/units/prefixes.py,sha256=_q2f8gA-kckBG7TutTFQazTf15PCZqNnaTR1gKXRfsk,6260 +sympy/physics/units/quantities.py,sha256=r5E231CULmsSEM7Rh7zfcTPuR85_X0CwRCVU_nDsek0,4671 +sympy/physics/units/systems/__init__.py,sha256=jJuvdc15c83yl11IuvhyjijwOZ9m1JGgZOgKwKv2e2o,244 +sympy/physics/units/systems/__pycache__/__init__.cpython-312.pyc,, +sympy/physics/units/systems/__pycache__/cgs.cpython-312.pyc,, +sympy/physics/units/systems/__pycache__/length_weight_time.cpython-312.pyc,, +sympy/physics/units/systems/__pycache__/mks.cpython-312.pyc,, +sympy/physics/units/systems/__pycache__/mksa.cpython-312.pyc,, +sympy/physics/units/systems/__pycache__/natural.cpython-312.pyc,, +sympy/physics/units/systems/__pycache__/si.cpython-312.pyc,, +sympy/physics/units/systems/cgs.py,sha256=gXbX8uuZo7lcYIENA-CpAnyS9WVQy-vRisxlQm-198A,3702 +sympy/physics/units/systems/length_weight_time.py,sha256=DXIDSWdhjfxGLA0ldOziWhwQjzTAs7-VQTNCHzDvCgY,7004 +sympy/physics/units/systems/mks.py,sha256=Z3eX9yWK9BdvEosCROK2qRKtKFYOjtQ50Jk6vFT7AQY,1546 +sympy/physics/units/systems/mksa.py,sha256=U8cSI-maIuLJRvpKLBuZA8V19LDRYVc2I40Rao-wvjk,2002 +sympy/physics/units/systems/natural.py,sha256=43Odvmtxdpbz8UcW_xoRE9ArJVVdF7dgdAN2ByDAXx4,909 +sympy/physics/units/systems/si.py,sha256=YBPUuovW3-JBDZYuStXXRaC8cfzE3En3K5MjNy5pLJk,14478 +sympy/physics/units/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/physics/units/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/physics/units/tests/__pycache__/test_dimensions.cpython-312.pyc,, +sympy/physics/units/tests/__pycache__/test_dimensionsystem.cpython-312.pyc,, +sympy/physics/units/tests/__pycache__/test_prefixes.cpython-312.pyc,, +sympy/physics/units/tests/__pycache__/test_quantities.cpython-312.pyc,, +sympy/physics/units/tests/__pycache__/test_unit_system_cgs_gauss.cpython-312.pyc,, +sympy/physics/units/tests/__pycache__/test_unitsystem.cpython-312.pyc,, +sympy/physics/units/tests/__pycache__/test_util.cpython-312.pyc,, +sympy/physics/units/tests/test_dimensions.py,sha256=lzkgGfEXMHxB8Izv7nRTN2uOEPh65LXPYaG8Kr5H05o,6122 +sympy/physics/units/tests/test_dimensionsystem.py,sha256=s2_2RAJwOaPOTvyIiAO9SYap374ytZqWbatWkLCnbSU,2717 +sympy/physics/units/tests/test_prefixes.py,sha256=Y3vlIReWGu8bwwZTrNGZSVoWYjhzgUZC33CDeyIvw48,2238 +sympy/physics/units/tests/test_quantities.py,sha256=XPuM6ul7XrUHvQE7F8rvpoCaxT9N6TM2gX99qUM4gTA,19758 +sympy/physics/units/tests/test_unit_system_cgs_gauss.py,sha256=JepTWt8yGdtv5dQ2AKUKb9fxpuYqLWOp0oOmzov9vfY,3173 +sympy/physics/units/tests/test_unitsystem.py,sha256=1Xh78_8hbv-yP4ICWI_dUrOnk3cimlvP_VhO-EXOa7Q,3254 +sympy/physics/units/tests/test_util.py,sha256=76PaLp_Cd9BAiry6VcWUD4Hrr68D6lTOkScWcLyhmL0,9355 +sympy/physics/units/unitsystem.py,sha256=mLuXftt3003OLk3knUGdYb1XfGbQa6vp-pHcenL11-o,7593 +sympy/physics/units/util.py,sha256=GU43MjXBRl5fm0CrU1fhFsZi9Q7wPG0NSJVJb1Oc_Y8,9885 +sympy/physics/vector/__init__.py,sha256=jZmrNB6ZfY7NOP8nx8GWcfI2Ixb2mv7lXuGHn63kyOw,985 +sympy/physics/vector/__pycache__/__init__.cpython-312.pyc,, +sympy/physics/vector/__pycache__/dyadic.cpython-312.pyc,, +sympy/physics/vector/__pycache__/fieldfunctions.cpython-312.pyc,, +sympy/physics/vector/__pycache__/frame.cpython-312.pyc,, +sympy/physics/vector/__pycache__/functions.cpython-312.pyc,, +sympy/physics/vector/__pycache__/point.cpython-312.pyc,, +sympy/physics/vector/__pycache__/printing.cpython-312.pyc,, +sympy/physics/vector/__pycache__/vector.cpython-312.pyc,, +sympy/physics/vector/dyadic.py,sha256=CuAkSBgnatfnZQ2gBazZQC1DBVXbksiFWWqxu2w3C2U,18042 +sympy/physics/vector/fieldfunctions.py,sha256=H3S7oeLHaInZns9ko04BPOcSSOK2M5hBK71jB813ExY,8610 +sympy/physics/vector/frame.py,sha256=J1sY-qaAamcZFKP26x54Q9TWITXBgjmE3v5PiEaFri4,57260 +sympy/physics/vector/functions.py,sha256=b4dHZOxbvS77SMcSlCV2GTaOzWj0TQiUtDaO_dhj3Uw,24810 +sympy/physics/vector/point.py,sha256=W1H6Jd-ZAIHY8yKO3YWj-vdEp7qI2yoglzk5HuT-y2E,20569 +sympy/physics/vector/printing.py,sha256=a1N-wziCnt4gHtY9luqe-CDW9aAtpZ0FcvWwQ0hMEEo,11790 +sympy/physics/vector/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/physics/vector/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/physics/vector/tests/__pycache__/test_dyadic.cpython-312.pyc,, +sympy/physics/vector/tests/__pycache__/test_fieldfunctions.cpython-312.pyc,, +sympy/physics/vector/tests/__pycache__/test_frame.cpython-312.pyc,, +sympy/physics/vector/tests/__pycache__/test_functions.cpython-312.pyc,, +sympy/physics/vector/tests/__pycache__/test_output.cpython-312.pyc,, +sympy/physics/vector/tests/__pycache__/test_point.cpython-312.pyc,, +sympy/physics/vector/tests/__pycache__/test_printing.cpython-312.pyc,, +sympy/physics/vector/tests/__pycache__/test_vector.cpython-312.pyc,, +sympy/physics/vector/tests/test_dyadic.py,sha256=vCSLxo0pynrHrCCo7S4925lgRhoSm_Mr5YhIh_1bYcw,4265 +sympy/physics/vector/tests/test_fieldfunctions.py,sha256=FUjh18QzB6dXSau9iHutb36o28faSa7T9sB0icpja-M,5825 +sympy/physics/vector/tests/test_frame.py,sha256=S5xn5Q9dMj_ACIS9ff7ACTBS7sFFovi9DIov-crUsko,29683 +sympy/physics/vector/tests/test_functions.py,sha256=qHGT0RR-vkAp1oF30TFNgaeuOGvXdZnK2aKZuRgrZHg,21127 +sympy/physics/vector/tests/test_output.py,sha256=hgqlE-_zN_EPE_gIZ_v2uXB1y2auo39hReWpvFUm2QQ,2612 +sympy/physics/vector/tests/test_point.py,sha256=5CTzT3a-igd33auAra4uusm0PYUc_whPtV7KAoZ4g5w,12373 +sympy/physics/vector/tests/test_printing.py,sha256=qVBjz4f3TtDrduUYLNDrvlrzBVMBDqLo27JWsFHdX18,10967 +sympy/physics/vector/tests/test_vector.py,sha256=bqU1ltS6UGbSo74KXMtvP1mOpqKQ6XSV19Wjw2QoNFc,10259 +sympy/physics/vector/vector.py,sha256=R7P63QPZee0lfHHVDU7Uq91ZJs5ewjVK5HVj9HHNeQo,24874 +sympy/physics/wigner.py,sha256=L5QyzD4yH4SyTk7-WCCd07XK0_Pd9nz7sHwo2zOWV7I,39588 +sympy/plotting/__init__.py,sha256=hAdOjai8-laj79rLJ2HZbiW1okXlz0p1ck-CoeNU6m8,526 +sympy/plotting/__pycache__/__init__.cpython-312.pyc,, +sympy/plotting/__pycache__/experimental_lambdify.cpython-312.pyc,, +sympy/plotting/__pycache__/plot.cpython-312.pyc,, +sympy/plotting/__pycache__/plot_implicit.cpython-312.pyc,, +sympy/plotting/__pycache__/plotgrid.cpython-312.pyc,, +sympy/plotting/__pycache__/series.cpython-312.pyc,, +sympy/plotting/__pycache__/textplot.cpython-312.pyc,, +sympy/plotting/__pycache__/utils.cpython-312.pyc,, +sympy/plotting/backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/plotting/backends/__pycache__/__init__.cpython-312.pyc,, +sympy/plotting/backends/__pycache__/base_backend.cpython-312.pyc,, +sympy/plotting/backends/base_backend.py,sha256=aof5cs8mWG6fl87DadR5sZBjY8ssMelOwKFWi27-FO0,14911 +sympy/plotting/backends/matplotlibbackend/__init__.py,sha256=Mzsz43gkanid12G8qnOcwJNbbvqf6eGppn-IZyJCMto,162 +sympy/plotting/backends/matplotlibbackend/__pycache__/__init__.cpython-312.pyc,, +sympy/plotting/backends/matplotlibbackend/__pycache__/matplotlib.cpython-312.pyc,, +sympy/plotting/backends/matplotlibbackend/matplotlib.py,sha256=9efu7ST_D3M-_fepZCPTcy8TdYEIX0PCkyocDGVfbPE,12548 +sympy/plotting/backends/textbackend/__init__.py,sha256=nnV_C7JJ_kwGcQe2C-tpnK635W8vTuIf5Grvvmur0rQ,92 +sympy/plotting/backends/textbackend/__pycache__/__init__.cpython-312.pyc,, +sympy/plotting/backends/textbackend/__pycache__/text.cpython-312.pyc,, +sympy/plotting/backends/textbackend/text.py,sha256=1ukArjwwQWUED9SB-1dmkB6YL5EcJ2rUosUf_NcBpXs,803 +sympy/plotting/experimental_lambdify.py,sha256=xcBhlvZ2h20aI1MpUN6qAEpO075Dv132AWbQJ7l3Wzg,22828 +sympy/plotting/intervalmath/__init__.py,sha256=fQV7sLZ9NHpZO5XGl2ZfqX56x-mdq-sYhtWEKLngHlU,479 +sympy/plotting/intervalmath/__pycache__/__init__.cpython-312.pyc,, +sympy/plotting/intervalmath/__pycache__/interval_arithmetic.cpython-312.pyc,, +sympy/plotting/intervalmath/__pycache__/interval_membership.cpython-312.pyc,, +sympy/plotting/intervalmath/__pycache__/lib_interval.cpython-312.pyc,, +sympy/plotting/intervalmath/interval_arithmetic.py,sha256=jv5YolNs6pOawIhuSsTBVwgkgmdOFwPrGN_1KtjfcIs,15570 +sympy/plotting/intervalmath/interval_membership.py,sha256=1VpO1T7UjvPxcMySC5GhZl8-VM_DxIirSWC3ZGmxIAY,2385 +sympy/plotting/intervalmath/lib_interval.py,sha256=WY1qRtyub4MDJaZizw6cXQI5NMEIXBO9UEWPEI80aW8,14809 +sympy/plotting/intervalmath/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/plotting/intervalmath/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/plotting/intervalmath/tests/__pycache__/test_interval_functions.cpython-312.pyc,, +sympy/plotting/intervalmath/tests/__pycache__/test_interval_membership.cpython-312.pyc,, +sympy/plotting/intervalmath/tests/__pycache__/test_intervalmath.cpython-312.pyc,, +sympy/plotting/intervalmath/tests/test_interval_functions.py,sha256=gdIo5z54tIbG8hDaGd3I8rBDP67oetMZWWdM-uvt1ec,9862 +sympy/plotting/intervalmath/tests/test_interval_membership.py,sha256=D1KjcrLxAwOmDEUqA-8TCqkFWGtmeerR9KwmzS7tyjk,4216 +sympy/plotting/intervalmath/tests/test_intervalmath.py,sha256=ndBMczrs6xYMN5RGnyCL9yq7pNUxrXHTSU1mdUsp5tU,9034 +sympy/plotting/plot.py,sha256=umvG47eIqOdEUo5qki3jDkS6LYKnTWFTZ5qzxZZBgAw,40882 +sympy/plotting/plot_implicit.py,sha256=1xIIr4eV1gIU4SkQ2k54PBZGUgYMCgsPttY-9uZ2eZM,7330 +sympy/plotting/plotgrid.py,sha256=QZmbxY-fcgPuseYLnKVDFsoH6m57Cosvy4W7l4jIqWw,6115 +sympy/plotting/pygletplot/__init__.py,sha256=DM7GURQbdSfcddHz23MxOShatBFc26tP_sd3G8pGCQE,3732 +sympy/plotting/pygletplot/__pycache__/__init__.cpython-312.pyc,, +sympy/plotting/pygletplot/__pycache__/color_scheme.cpython-312.pyc,, +sympy/plotting/pygletplot/__pycache__/managed_window.cpython-312.pyc,, +sympy/plotting/pygletplot/__pycache__/plot.cpython-312.pyc,, +sympy/plotting/pygletplot/__pycache__/plot_axes.cpython-312.pyc,, +sympy/plotting/pygletplot/__pycache__/plot_camera.cpython-312.pyc,, +sympy/plotting/pygletplot/__pycache__/plot_controller.cpython-312.pyc,, +sympy/plotting/pygletplot/__pycache__/plot_curve.cpython-312.pyc,, +sympy/plotting/pygletplot/__pycache__/plot_interval.cpython-312.pyc,, +sympy/plotting/pygletplot/__pycache__/plot_mode.cpython-312.pyc,, +sympy/plotting/pygletplot/__pycache__/plot_mode_base.cpython-312.pyc,, +sympy/plotting/pygletplot/__pycache__/plot_modes.cpython-312.pyc,, +sympy/plotting/pygletplot/__pycache__/plot_object.cpython-312.pyc,, +sympy/plotting/pygletplot/__pycache__/plot_rotation.cpython-312.pyc,, +sympy/plotting/pygletplot/__pycache__/plot_surface.cpython-312.pyc,, +sympy/plotting/pygletplot/__pycache__/plot_window.cpython-312.pyc,, +sympy/plotting/pygletplot/__pycache__/util.cpython-312.pyc,, +sympy/plotting/pygletplot/color_scheme.py,sha256=NgPUamkldygfrIPj0LvC_1AzhscVtg18FSudElvFYB8,12522 +sympy/plotting/pygletplot/managed_window.py,sha256=N7AKtM7ELfIJLie6zvI-J6-OQRBnMZu6AL1USz7hFEk,3072 +sympy/plotting/pygletplot/plot.py,sha256=s-5AJB0KelHs9WGoFIVIdYrOoMXfdpnM5-G2cF8xzDQ,13352 +sympy/plotting/pygletplot/plot_axes.py,sha256=Q9YN8W0Hd1PeflHLvOvSZ-hxeLU4Kq3nUFLYDC0x0E8,8655 +sympy/plotting/pygletplot/plot_camera.py,sha256=myYtKbv1ov_ltgR34hf8BR76t3AwTSu4QFUY5YY-e1E,3928 +sympy/plotting/pygletplot/plot_controller.py,sha256=MroJJSPCbBDT8gGs_GdqpV_KHsllMNJpxx0MU3vKJV8,6941 +sympy/plotting/pygletplot/plot_curve.py,sha256=YwKA2lYC7IwCOQJaOVnww8AAG4P36cArgbC1iLV9OFI,2838 +sympy/plotting/pygletplot/plot_interval.py,sha256=doqr2wxnrED4MJDlkxQ07GFvaagX36HUb77ly_vIuKQ,5431 +sympy/plotting/pygletplot/plot_mode.py,sha256=Djq-ewVms_JoSriDpolDhhtttBJQdJO8BD4E0nyOWcQ,14156 +sympy/plotting/pygletplot/plot_mode_base.py,sha256=3z3WjeN7TTslHJevhr3X_7HRHPgUleYSngu6285lR6k,11502 +sympy/plotting/pygletplot/plot_modes.py,sha256=gKzJShz6OXa6EHKar8SuHWrELVznxg_s2d5IBQkkeYE,5352 +sympy/plotting/pygletplot/plot_object.py,sha256=qGtzcKup4It1CqZ2jxA7FnorCua4S9I-B_7I3SHBjcQ,330 +sympy/plotting/pygletplot/plot_rotation.py,sha256=KGMCTyaSh5_UQD9FKGCIpoI3-CbbOhXxTcjAc1o5-PU,1445 +sympy/plotting/pygletplot/plot_surface.py,sha256=C0q9tzDmxzC1IpWiNKY4llzcopx6dhotGOLpK1N9m3s,3803 +sympy/plotting/pygletplot/plot_window.py,sha256=5boC2Fkmk46-gWGqWzdTkPmTMNHHOpA0CnB9q946Hwc,4643 +sympy/plotting/pygletplot/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/plotting/pygletplot/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/plotting/pygletplot/tests/__pycache__/test_plotting.cpython-312.pyc,, +sympy/plotting/pygletplot/tests/test_plotting.py,sha256=NisjR-yuBRJfQvjcb20skTR3yid2U3MhKHW6sy8RE10,2720 +sympy/plotting/pygletplot/util.py,sha256=mzQQgDDbp04B03KyJrossLp8Yq72RJzjp-3ArfjbMH8,4621 +sympy/plotting/series.py,sha256=hPkMicAi29RjoJkFpMCt1CRn0xdBVYU1wLniigHgCaM,96568 +sympy/plotting/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/plotting/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/plotting/tests/__pycache__/test_experimental_lambdify.cpython-312.pyc,, +sympy/plotting/tests/__pycache__/test_plot.cpython-312.pyc,, +sympy/plotting/tests/__pycache__/test_plot_implicit.cpython-312.pyc,, +sympy/plotting/tests/__pycache__/test_series.cpython-312.pyc,, +sympy/plotting/tests/__pycache__/test_textplot.cpython-312.pyc,, +sympy/plotting/tests/__pycache__/test_utils.cpython-312.pyc,, +sympy/plotting/tests/test_experimental_lambdify.py,sha256=EYshdXA5tAGWolaDX-nHAolp7xIJN4Oqb1Uc1C1IhJI,3127 +sympy/plotting/tests/test_plot.py,sha256=mXiNdG-dHkK1iJ_moNlehZQU3i8mCtUKhVJdTxSxjdA,48217 +sympy/plotting/tests/test_plot_implicit.py,sha256=wurrO7ntsHb4tWYPVs5VogRrtcylevu0EceCSEwiWQg,5799 +sympy/plotting/tests/test_region_and.png,sha256=EV0Lm4HtQPk_6eIWtPY4TPcQk-O7tkpdZIuLmFjGRaA,6864 +sympy/plotting/tests/test_region_not.png,sha256=3O_9_nPW149FMULEcT5RqI2-k2H3nHELbfJADt2cO8k,7939 +sympy/plotting/tests/test_region_or.png,sha256=5Bug09vyog-Cu3mky7pbtFjew5bMvbpe0ZXWsgDKfy4,8809 +sympy/plotting/tests/test_region_xor.png,sha256=kucVWBA9A98OpcR4did5aLXUyoq4z0O4C3PM6dliBSw,10002 +sympy/plotting/tests/test_series.py,sha256=Nwa6__YMoWCiY0mYSlvJPPnlvtfOYLACHR1RbkopMc0,65638 +sympy/plotting/tests/test_textplot.py,sha256=VurTGeMjUfBLpLdoMqzJK9gbcShNb7f1OrAcRNyrtag,12761 +sympy/plotting/tests/test_utils.py,sha256=FkcYZAFT8TnHRIbkknx9NvA3-LgR0ua7WFyzQEPsVIE,3602 +sympy/plotting/textplot.py,sha256=Xc-bWvzVOq8QUn_BxDlJv9bryCpgzsgV73XoQQwVj0Q,5075 +sympy/plotting/utils.py,sha256=Cimno9MQGjcbe4rQ6TN86r4rM2t62CgARqPtgF0mhR8,12259 +sympy/polys/__init__.py,sha256=qXmDNr7noCUAtIs0rJJRHHFbHjy3uHIvXZDajcSePc4,5577 +sympy/polys/__pycache__/__init__.cpython-312.pyc,, +sympy/polys/__pycache__/appellseqs.cpython-312.pyc,, +sympy/polys/__pycache__/compatibility.cpython-312.pyc,, +sympy/polys/__pycache__/constructor.cpython-312.pyc,, +sympy/polys/__pycache__/densearith.cpython-312.pyc,, +sympy/polys/__pycache__/densebasic.cpython-312.pyc,, +sympy/polys/__pycache__/densetools.cpython-312.pyc,, +sympy/polys/__pycache__/dispersion.cpython-312.pyc,, +sympy/polys/__pycache__/distributedmodules.cpython-312.pyc,, +sympy/polys/__pycache__/domainmatrix.cpython-312.pyc,, +sympy/polys/__pycache__/euclidtools.cpython-312.pyc,, +sympy/polys/__pycache__/factortools.cpython-312.pyc,, +sympy/polys/__pycache__/fglmtools.cpython-312.pyc,, +sympy/polys/__pycache__/fields.cpython-312.pyc,, +sympy/polys/__pycache__/galoistools.cpython-312.pyc,, +sympy/polys/__pycache__/groebnertools.cpython-312.pyc,, +sympy/polys/__pycache__/heuristicgcd.cpython-312.pyc,, +sympy/polys/__pycache__/modulargcd.cpython-312.pyc,, +sympy/polys/__pycache__/monomials.cpython-312.pyc,, +sympy/polys/__pycache__/multivariate_resultants.cpython-312.pyc,, +sympy/polys/__pycache__/orderings.cpython-312.pyc,, +sympy/polys/__pycache__/orthopolys.cpython-312.pyc,, +sympy/polys/__pycache__/partfrac.cpython-312.pyc,, +sympy/polys/__pycache__/polyclasses.cpython-312.pyc,, +sympy/polys/__pycache__/polyconfig.cpython-312.pyc,, +sympy/polys/__pycache__/polyerrors.cpython-312.pyc,, +sympy/polys/__pycache__/polyfuncs.cpython-312.pyc,, +sympy/polys/__pycache__/polymatrix.cpython-312.pyc,, +sympy/polys/__pycache__/polyoptions.cpython-312.pyc,, +sympy/polys/__pycache__/polyquinticconst.cpython-312.pyc,, +sympy/polys/__pycache__/polyroots.cpython-312.pyc,, +sympy/polys/__pycache__/polytools.cpython-312.pyc,, +sympy/polys/__pycache__/polyutils.cpython-312.pyc,, +sympy/polys/__pycache__/puiseux.cpython-312.pyc,, +sympy/polys/__pycache__/rationaltools.cpython-312.pyc,, +sympy/polys/__pycache__/ring_series.cpython-312.pyc,, +sympy/polys/__pycache__/rings.cpython-312.pyc,, +sympy/polys/__pycache__/rootisolation.cpython-312.pyc,, +sympy/polys/__pycache__/rootoftools.cpython-312.pyc,, +sympy/polys/__pycache__/solvers.cpython-312.pyc,, +sympy/polys/__pycache__/specialpolys.cpython-312.pyc,, +sympy/polys/__pycache__/sqfreetools.cpython-312.pyc,, +sympy/polys/__pycache__/subresultants_qq_zz.cpython-312.pyc,, +sympy/polys/agca/__init__.py,sha256=fahpWoG_0LgoqOXBnDBJS16Jj1fE1_VKG7edM3qZ2HE,130 +sympy/polys/agca/__pycache__/__init__.cpython-312.pyc,, +sympy/polys/agca/__pycache__/extensions.cpython-312.pyc,, +sympy/polys/agca/__pycache__/homomorphisms.cpython-312.pyc,, +sympy/polys/agca/__pycache__/ideals.cpython-312.pyc,, +sympy/polys/agca/__pycache__/modules.cpython-312.pyc,, +sympy/polys/agca/extensions.py,sha256=YmtFs9C0s-4DNMXFtdX1hYVNlby18mAJzhJ5Aqickrw,9388 +sympy/polys/agca/homomorphisms.py,sha256=gaMNV96pKUuYHZ8Bd7QOs27J1IbbJgkEjyWcTLe8GFI,21937 +sympy/polys/agca/ideals.py,sha256=S6rBl3H-hdeI44ZbELwjjt1rKlrhK11AKb8Aas-OtCE,11073 +sympy/polys/agca/modules.py,sha256=PeA138FHsCfUn8vkdrjPa92xmzq7Qqk0PrdYwVoNqf0,47240 +sympy/polys/agca/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/polys/agca/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/polys/agca/tests/__pycache__/test_extensions.cpython-312.pyc,, +sympy/polys/agca/tests/__pycache__/test_homomorphisms.cpython-312.pyc,, +sympy/polys/agca/tests/__pycache__/test_ideals.cpython-312.pyc,, +sympy/polys/agca/tests/__pycache__/test_modules.cpython-312.pyc,, +sympy/polys/agca/tests/test_extensions.py,sha256=i3IHQNXQByFMCvjjyd_hwwJSCiUj0z1rRwS9WFK2AFc,6455 +sympy/polys/agca/tests/test_homomorphisms.py,sha256=m0hFmcTzvZ8sZbbnWeENwzKyufpE9zWwZR-WCI4kdpU,4224 +sympy/polys/agca/tests/test_ideals.py,sha256=w76qXO-_HN6LQbV7l3h7gJZsM-DZ2io2X-kPWiHYRNw,3788 +sympy/polys/agca/tests/test_modules.py,sha256=HdfmcxdEVucEbtfmzVq8i_1wGojT5b5DE5VIfbTMx3k,13552 +sympy/polys/appellseqs.py,sha256=hWeDKsKnJuAuPN_5IU6m1okurAq9xMt3LQgMehcvBKQ,8305 +sympy/polys/benchmarks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/polys/benchmarks/__pycache__/__init__.cpython-312.pyc,, +sympy/polys/benchmarks/__pycache__/bench_galoispolys.cpython-312.pyc,, +sympy/polys/benchmarks/__pycache__/bench_groebnertools.cpython-312.pyc,, +sympy/polys/benchmarks/__pycache__/bench_solvers.cpython-312.pyc,, +sympy/polys/benchmarks/bench_galoispolys.py,sha256=8RtN9ZQga2oxscVPPkMGB29Dz8UbskMS2szYtqZ69u0,1502 +sympy/polys/benchmarks/bench_groebnertools.py,sha256=YqGDCzewRszCye_GnneDXMRNB38ORSpVu_Jn0ELIySo,803 +sympy/polys/benchmarks/bench_solvers.py,sha256=gLrZguh6pE0E4_vM2GeOS5bHnrcSUQXqD0Qz9tItfmo,446778 +sympy/polys/compatibility.py,sha256=ti_gJSz8zB1sf-oIyfXAw4xkDGkQaZs_34RSC-6HldY,58373 +sympy/polys/constructor.py,sha256=rv8hQgE8-P9QXUtOQmlEiyA4XD-fb1Qzd8bvH3UHQls,11373 +sympy/polys/densearith.py,sha256=6wB6DJWKNB0RA7Tdg7jMgRIERjZdtAp32OQhIQ6wmV4,34114 +sympy/polys/densebasic.py,sha256=Kag6cqlxHhHUMYUXpr9GHLWh4E1Mnw2Esoh6zx9r14E,35954 +sympy/polys/densetools.py,sha256=A0Z1E16eVx577zw84m8KZgT5o6dbDXXonW8TqfISJZY,29746 +sympy/polys/dispersion.py,sha256=s6GIYnGA6U9jhGP7YXQQS8G3byG4-kPbr55BR6p-iz4,5740 +sympy/polys/distributedmodules.py,sha256=t8pLIgDQs_dMecGXwybVYoLavofEy2DXhFS8N5gj5SU,21827 +sympy/polys/domainmatrix.py,sha256=FmNqklNFQR1WrQYtP2r7jypw2IQadNKGP14EaUaxUqI,310 +sympy/polys/domains/__init__.py,sha256=T6qPNkU1EJ6D5BnvyJSXJv4zeJ5MUT5RLsovMkkXS9E,1872 +sympy/polys/domains/__pycache__/__init__.cpython-312.pyc,, +sympy/polys/domains/__pycache__/algebraicfield.cpython-312.pyc,, +sympy/polys/domains/__pycache__/characteristiczero.cpython-312.pyc,, +sympy/polys/domains/__pycache__/complexfield.cpython-312.pyc,, +sympy/polys/domains/__pycache__/compositedomain.cpython-312.pyc,, +sympy/polys/domains/__pycache__/domain.cpython-312.pyc,, +sympy/polys/domains/__pycache__/domainelement.cpython-312.pyc,, +sympy/polys/domains/__pycache__/expressiondomain.cpython-312.pyc,, +sympy/polys/domains/__pycache__/expressionrawdomain.cpython-312.pyc,, +sympy/polys/domains/__pycache__/field.cpython-312.pyc,, +sympy/polys/domains/__pycache__/finitefield.cpython-312.pyc,, +sympy/polys/domains/__pycache__/fractionfield.cpython-312.pyc,, +sympy/polys/domains/__pycache__/gaussiandomains.cpython-312.pyc,, +sympy/polys/domains/__pycache__/gmpyfinitefield.cpython-312.pyc,, +sympy/polys/domains/__pycache__/gmpyintegerring.cpython-312.pyc,, +sympy/polys/domains/__pycache__/gmpyrationalfield.cpython-312.pyc,, +sympy/polys/domains/__pycache__/groundtypes.cpython-312.pyc,, +sympy/polys/domains/__pycache__/integerring.cpython-312.pyc,, +sympy/polys/domains/__pycache__/modularinteger.cpython-312.pyc,, +sympy/polys/domains/__pycache__/mpelements.cpython-312.pyc,, +sympy/polys/domains/__pycache__/old_fractionfield.cpython-312.pyc,, +sympy/polys/domains/__pycache__/old_polynomialring.cpython-312.pyc,, +sympy/polys/domains/__pycache__/polynomialring.cpython-312.pyc,, +sympy/polys/domains/__pycache__/pythonfinitefield.cpython-312.pyc,, +sympy/polys/domains/__pycache__/pythonintegerring.cpython-312.pyc,, +sympy/polys/domains/__pycache__/pythonrational.cpython-312.pyc,, +sympy/polys/domains/__pycache__/pythonrationalfield.cpython-312.pyc,, +sympy/polys/domains/__pycache__/quotientring.cpython-312.pyc,, +sympy/polys/domains/__pycache__/rationalfield.cpython-312.pyc,, +sympy/polys/domains/__pycache__/realfield.cpython-312.pyc,, +sympy/polys/domains/__pycache__/ring.cpython-312.pyc,, +sympy/polys/domains/__pycache__/simpledomain.cpython-312.pyc,, +sympy/polys/domains/algebraicfield.py,sha256=JXK_o6BdQbYT_0gOLALNOLsmqgfV46DRFJb7cANJgAM,23051 +sympy/polys/domains/characteristiczero.py,sha256=vHYRUXPrfJzDF8wrd1KSFqG8WzwfITP_eweA-SHPVYA,382 +sympy/polys/domains/complexfield.py,sha256=VbhX6yigmU2OLhof8qEpPp1XZhzzkfXfcuZevx1LZsk,6159 +sympy/polys/domains/compositedomain.py,sha256=DAo2ISA9XdOnYzFu8azuPIQAT9fyVwSM8Pe425vmvww,1642 +sympy/polys/domains/domain.py,sha256=aj9HOp98G2m25wRzSDj4lWzoRLGyXDsuevzScdHjV6o,40850 +sympy/polys/domains/domainelement.py,sha256=IrG-Mzv_VlCAmE-hmJVH_d77TrsfyaGGfJVmU8FFvlY,860 +sympy/polys/domains/expressiondomain.py,sha256=AB7Mnd6kOLaS_yG4lMXZTpVPUuAHGcrd6RAjjFSVxNc,7593 +sympy/polys/domains/expressionrawdomain.py,sha256=cXarD2jXi97FGNiqNiDqQlX0g764EW2M1PEbrveImnY,1448 +sympy/polys/domains/field.py,sha256=fR0l6wZIv02UMJ5rioEP910jGUViVx38EdwtJuJX5vg,2959 +sympy/polys/domains/finitefield.py,sha256=1DHkfrCz08KXLEz7in4IK71B8udHPZZAWv50-jV5_vQ,10654 +sympy/polys/domains/fractionfield.py,sha256=BoqUCbVggwaoqGCVy_r42MIVHuAV-P3gONFVZIlWojU,5848 +sympy/polys/domains/gaussiandomains.py,sha256=YrcHg4QSPgIRW-Ft8J84q1zwmU-DVJuAscWXnVCQ9CI,19598 +sympy/polys/domains/gmpyfinitefield.py,sha256=WgSLnALNOVVKH931WpVT28ZWDilsrTDG8DyMee2xR94,437 +sympy/polys/domains/gmpyintegerring.py,sha256=qJ7w8K40cfzhztZtOuWlIL2DXa642xJcKIIxoAOlcSs,3037 +sympy/polys/domains/gmpyrationalfield.py,sha256=dZjrfcWaUA-BHUtutzLOWPlOSNLYzBqSFeukER6L_bA,3178 +sympy/polys/domains/groundtypes.py,sha256=hAla27w5ekoJR_8c-1Yo8vrEgIIggPc615tfe1udc9A,2102 +sympy/polys/domains/integerring.py,sha256=4oy49xTi8hV6qh8CWUAoBcgn2aJqgqwyh7bZBsjGfwI,7442 +sympy/polys/domains/modularinteger.py,sha256=k6gskb0eypXdrKJRxR3l_75mVjmICGnaOy7FdRMwG8E,6042 +sympy/polys/domains/mpelements.py,sha256=PREDWq_WA5er2zzftt5Lg0opnWzyFBsIkLKcyGXUVz0,5042 +sympy/polys/domains/old_fractionfield.py,sha256=TUVxyL2fS4QF3kgyW5EGfkl91ir3S1klu08UfZr3GuI,6226 +sympy/polys/domains/old_polynomialring.py,sha256=KQcH58oHnHzOpDdWojZiLlHDqrAiUd4OAaBIZigqpyc,15982 +sympy/polys/domains/polynomialring.py,sha256=OLPcwkyrbkt5pNZ342o3Ziv9TCrlpU3h18s9R-cxqXI,6223 +sympy/polys/domains/pythonfinitefield.py,sha256=lWp266ErnuUPuo7k8ju3z2S5IresFInpJAl4Ihsq0pI,453 +sympy/polys/domains/pythonintegerring.py,sha256=EH5s6nwaxmeaScLER_FfqPdhyuJnbjtBslHmgyOyEPs,2962 +sympy/polys/domains/pythonrational.py,sha256=M3VUGODh3MLElePjYtjt9b02ReMThw-XXpuQTkohgNs,548 +sympy/polys/domains/pythonrationalfield.py,sha256=x8BPkGKj0WPuwJzN2py5l9aAjHaY4djv65c4tzUTr3Y,2295 +sympy/polys/domains/quotientring.py,sha256=2NOUkkbFj4514qkDUszl6hl1EQuPikn3QEoQ1sDobGI,5911 +sympy/polys/domains/rationalfield.py,sha256=D-pA-iHDHbOi6fivqSrJnfmH2JTrheKJQ9ZFXXN5ftM,5982 +sympy/polys/domains/realfield.py,sha256=OdLfE_9OVxvQlnQiT4faJxuB6dZwnXdIt-o-5wGYroA,6456 +sympy/polys/domains/ring.py,sha256=p66U2X58acSHLHxOTU6aJZ0Umdcu1qiGIUDtV8iJCD0,3236 +sympy/polys/domains/simpledomain.py,sha256=_K-Zz8Opf505r3eHSrbPAlnGiGSjY_O4Cwa4OTeOSoY,369 +sympy/polys/domains/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/polys/domains/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/polys/domains/tests/__pycache__/test_domains.cpython-312.pyc,, +sympy/polys/domains/tests/__pycache__/test_polynomialring.cpython-312.pyc,, +sympy/polys/domains/tests/__pycache__/test_quotientring.cpython-312.pyc,, +sympy/polys/domains/tests/test_domains.py,sha256=XJwTGPM-8W4Rn76-cec99rpUIDDjP-7HTFs7AKGNrEw,51028 +sympy/polys/domains/tests/test_polynomialring.py,sha256=8nNFKuQeicwiBk6pnqPLNk0cnI61iK8Dpl-TZifvORc,2895 +sympy/polys/domains/tests/test_quotientring.py,sha256=BYoq1CqI76RDSm0xQdp1v7Dv1n5sdcmes-b_y_AfW-0,1459 +sympy/polys/euclidtools.py,sha256=hAsNupzfR-07fTwFvTF2yDabyKMm_PLgFC8KX9c2CAo,41808 +sympy/polys/factortools.py,sha256=CupycipegP1IGCYPY9eY2T8f_6h4gmr6qId1A4UDJvk,43034 +sympy/polys/fglmtools.py,sha256=Z3VS_IKsZu1o3g22KPTIH1feNL8cTpieaNWvLuILmK4,4298 +sympy/polys/fields.py,sha256=RdSDkOls6n87yvHG1KXFnGng0JS3SAcUAlz4tTb1RZE,21250 +sympy/polys/galoistools.py,sha256=Z3ed_A0Nohj9RzuM3kom7-ay4MnzIHppwgV2QpONuTo,57238 +sympy/polys/groebnertools.py,sha256=NhK-XcFR9e4chDDJJ-diXb7XYuw9zcixFA_riomThPM,23342 +sympy/polys/heuristicgcd.py,sha256=rD3intgKCtAAMH3sqlgqbJL1XSq9QjfeG_MYzwCOek0,3732 +sympy/polys/matrices/__init__.py,sha256=ZaPJMi8l22d3F3rudS4NqzSt0xwxbs3uwnQwlhhR91o,397 +sympy/polys/matrices/__pycache__/__init__.cpython-312.pyc,, +sympy/polys/matrices/__pycache__/_dfm.cpython-312.pyc,, +sympy/polys/matrices/__pycache__/_typing.cpython-312.pyc,, +sympy/polys/matrices/__pycache__/ddm.cpython-312.pyc,, +sympy/polys/matrices/__pycache__/dense.cpython-312.pyc,, +sympy/polys/matrices/__pycache__/dfm.cpython-312.pyc,, +sympy/polys/matrices/__pycache__/domainmatrix.cpython-312.pyc,, +sympy/polys/matrices/__pycache__/domainscalar.cpython-312.pyc,, +sympy/polys/matrices/__pycache__/eigen.cpython-312.pyc,, +sympy/polys/matrices/__pycache__/exceptions.cpython-312.pyc,, +sympy/polys/matrices/__pycache__/linsolve.cpython-312.pyc,, +sympy/polys/matrices/__pycache__/lll.cpython-312.pyc,, +sympy/polys/matrices/__pycache__/normalforms.cpython-312.pyc,, +sympy/polys/matrices/__pycache__/rref.cpython-312.pyc,, +sympy/polys/matrices/__pycache__/sdm.cpython-312.pyc,, +sympy/polys/matrices/_dfm.py,sha256=_3p5Hb9e86uBG_r__Ee6BAZxj4KiRhcf2uN3XnjHxwQ,32971 +sympy/polys/matrices/_typing.py,sha256=Egp2nMOaq-oJCW0bgNDxy1Bx6evTl8eMTpf4mzIw1s4,407 +sympy/polys/matrices/ddm.py,sha256=eMKUy8X1kQTEG1l7Fx_L4LG9Jqs9l0KEwlYQwlcl6Do,32362 +sympy/polys/matrices/dense.py,sha256=RYdogVHeWZoeO94Oal1mf1sJvj-JmyS_baRi8-d9Rms,23217 +sympy/polys/matrices/dfm.py,sha256=Fj_uF4FskrwcBDNuRSV--AozCP2cYkUz-BMitcMlkRE,1241 +sympy/polys/matrices/domainmatrix.py,sha256=MvjWRzQ4lKzX2rCl8mRtpiIXSe641_x6OMrTr8iscPA,115928 +sympy/polys/matrices/domainscalar.py,sha256=sPXC-it46yun2r_tJkun4MIuVQQyQMQTVsTedId8Rj4,3778 +sympy/polys/matrices/eigen.py,sha256=glArxs9_rTrE_ssz2fd2gKCTsguSyEHwoeQP82tmIcM,3015 +sympy/polys/matrices/exceptions.py,sha256=ay3Lv21X3QqszysBN71xdr9KGQuC5kDBl90a2Sjx6pM,1351 +sympy/polys/matrices/linsolve.py,sha256=p86jlJP9h3CxZX92xk2sh1WAvKBkB5_YD55k1oYpmGI,7534 +sympy/polys/matrices/lll.py,sha256=p5q_rb5QvAuHsGRZAzP2Jf_h2vdC_Be4Q62lkaYxW-c,3550 +sympy/polys/matrices/normalforms.py,sha256=6MJfVbiwlZuCk-0fYiyOMuqkPdVpyzTNdDP2s6jkRw0,17122 +sympy/polys/matrices/rref.py,sha256=5YK_phB382K9JFVIydlH2IYpziirEDUnKzyl5BfS2_o,15532 +sympy/polys/matrices/sdm.py,sha256=bb2fIO42KjyJuEuMBkiDFn_qLJVjD4gsRgWZ6GOmTHw,64293 +sympy/polys/matrices/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/polys/matrices/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/polys/matrices/tests/__pycache__/test_ddm.cpython-312.pyc,, +sympy/polys/matrices/tests/__pycache__/test_dense.cpython-312.pyc,, +sympy/polys/matrices/tests/__pycache__/test_domainmatrix.cpython-312.pyc,, +sympy/polys/matrices/tests/__pycache__/test_domainscalar.cpython-312.pyc,, +sympy/polys/matrices/tests/__pycache__/test_eigen.cpython-312.pyc,, +sympy/polys/matrices/tests/__pycache__/test_fflu.cpython-312.pyc,, +sympy/polys/matrices/tests/__pycache__/test_inverse.cpython-312.pyc,, +sympy/polys/matrices/tests/__pycache__/test_linsolve.cpython-312.pyc,, +sympy/polys/matrices/tests/__pycache__/test_lll.cpython-312.pyc,, +sympy/polys/matrices/tests/__pycache__/test_normalforms.cpython-312.pyc,, +sympy/polys/matrices/tests/__pycache__/test_nullspace.cpython-312.pyc,, +sympy/polys/matrices/tests/__pycache__/test_rref.cpython-312.pyc,, +sympy/polys/matrices/tests/__pycache__/test_sdm.cpython-312.pyc,, +sympy/polys/matrices/tests/__pycache__/test_xxm.cpython-312.pyc,, +sympy/polys/matrices/tests/test_ddm.py,sha256=BcnUntz3XR2Xyff02l4Mk2EsxwYlIBzM4lFSRo9oZT8,16699 +sympy/polys/matrices/tests/test_dense.py,sha256=ETC2h5yLKsPJ5GAgx_RUcWyR63iZx81pbtOZiWty1r0,9516 +sympy/polys/matrices/tests/test_domainmatrix.py,sha256=4QttFR5PYJg6Xn37VXdxmv1w9Xkm82fF-M-KRQIe0RU,50006 +sympy/polys/matrices/tests/test_domainscalar.py,sha256=HEFEKX5tP6SZ83_91nvLmFqgHxbVdpqOP4ZwzfFbHnc,3740 +sympy/polys/matrices/tests/test_eigen.py,sha256=T1lYZeW-0NwDxDOG6ZJLr-OICfxY2wa0fVHV2V6EXSk,3200 +sympy/polys/matrices/tests/test_fflu.py,sha256=7En_75QemdtHvR7lUyZrcHiV9Dv2rswBuuKVOPWi1pk,8542 +sympy/polys/matrices/tests/test_inverse.py,sha256=5DT5qvfS3MlrgNgeHnG8GLjgLnmhsxj94yR3cbtmEO8,5247 +sympy/polys/matrices/tests/test_linsolve.py,sha256=ur1BFzlIQyBrO_-aL71lXsLC67nfec9G5o-mzW_TFY4,3373 +sympy/polys/matrices/tests/test_lll.py,sha256=RGYTDGbLfFvAMTESv-S1kqSWzwtOIjmguqXO3yGCjH4,6624 +sympy/polys/matrices/tests/test_normalforms.py,sha256=x1-vkjXq3LGblUSJFz7z73IVmaxqZbVzWoGj9XS-yXw,5106 +sympy/polys/matrices/tests/test_nullspace.py,sha256=eAEDPlnVkKfFM9jn1gztOUQTos1Sm9qwH10C-t9uLUE,5418 +sympy/polys/matrices/tests/test_rref.py,sha256=mWTIfKAUP3vkGKhffCrPHuC_0DdF-iH41cchlSN8Pqc,25982 +sympy/polys/matrices/tests/test_sdm.py,sha256=fSE3bQlDU-atzTFTgp4AgAS3QL-7rvb_61stj3QGBnU,13415 +sympy/polys/matrices/tests/test_xxm.py,sha256=X9sP_VfPi4bUR7V1ZLq6ZHXPOBUA7tE5-gQULang_Ag,29778 +sympy/polys/modulargcd.py,sha256=gOwojISiV8IncaEHZJZMHOC1odN7xRKN5L1Ls4szROI,58729 +sympy/polys/monomials.py,sha256=6cDCTVNNPDeee5bt0RQnGuYnsO_fefioHA5mEDKHSuA,18458 +sympy/polys/multivariate_resultants.py,sha256=6bwdF-lcUqtKoVDrnOKhm_PyPfo8w0Yyy_GtESatQFw,15248 +sympy/polys/numberfields/__init__.py,sha256=ZfhC9MyfGfGUz_DT_rXasB-M_P2zUiZXOJUNh_Gtm8c,538 +sympy/polys/numberfields/__pycache__/__init__.cpython-312.pyc,, +sympy/polys/numberfields/__pycache__/basis.cpython-312.pyc,, +sympy/polys/numberfields/__pycache__/exceptions.cpython-312.pyc,, +sympy/polys/numberfields/__pycache__/galois_resolvents.cpython-312.pyc,, +sympy/polys/numberfields/__pycache__/galoisgroups.cpython-312.pyc,, +sympy/polys/numberfields/__pycache__/minpoly.cpython-312.pyc,, +sympy/polys/numberfields/__pycache__/modules.cpython-312.pyc,, +sympy/polys/numberfields/__pycache__/primes.cpython-312.pyc,, +sympy/polys/numberfields/__pycache__/resolvent_lookup.cpython-312.pyc,, +sympy/polys/numberfields/__pycache__/subfield.cpython-312.pyc,, +sympy/polys/numberfields/__pycache__/utilities.cpython-312.pyc,, +sympy/polys/numberfields/basis.py,sha256=IPA6cSwz-53ClQwo-wkmRzfx9pRX4iBhiggdLMVSgJ0,8261 +sympy/polys/numberfields/exceptions.py,sha256=kHb-aB4eBzG3SsIpYtL5wLExDSb8lIOpNq0tk3guFIA,1594 +sympy/polys/numberfields/galois_resolvents.py,sha256=OL3u-G6sCwvZuBuuYQO0QpL-wWxtjxFaBjVQhtiQ_Z8,25006 +sympy/polys/numberfields/galoisgroups.py,sha256=c4s6z_mEUkoWKezFrfjKiU2tZnEnxR4m1LYaagicVno,20671 +sympy/polys/numberfields/minpoly.py,sha256=0F7QVSOk8WqViD50jKtT-94C6kQyuXPBCyNZPTf0ScA,27791 +sympy/polys/numberfields/modules.py,sha256=4MJykT6gtT_LC033LWsHT_CM7nEydLISAdQ0yA_bhkQ,69243 +sympy/polys/numberfields/primes.py,sha256=UXOkuMdnamVvHPQZxwilCbhdwNNNS7zQ4bwSFc5xGgk,23984 +sympy/polys/numberfields/resolvent_lookup.py,sha256=qfLNKOz_WjtXwpVlfzy8EkD4gw12epx9npE9HsjyIdg,40411 +sympy/polys/numberfields/subfield.py,sha256=Huh9iq2CDQN8p0fs2bSe-yEoB_V1OVr8rH58rJT4crk,16668 +sympy/polys/numberfields/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/polys/numberfields/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/polys/numberfields/tests/__pycache__/test_basis.cpython-312.pyc,, +sympy/polys/numberfields/tests/__pycache__/test_galoisgroups.cpython-312.pyc,, +sympy/polys/numberfields/tests/__pycache__/test_minpoly.cpython-312.pyc,, +sympy/polys/numberfields/tests/__pycache__/test_modules.cpython-312.pyc,, +sympy/polys/numberfields/tests/__pycache__/test_numbers.cpython-312.pyc,, +sympy/polys/numberfields/tests/__pycache__/test_primes.cpython-312.pyc,, +sympy/polys/numberfields/tests/__pycache__/test_subfield.cpython-312.pyc,, +sympy/polys/numberfields/tests/__pycache__/test_utilities.cpython-312.pyc,, +sympy/polys/numberfields/tests/test_basis.py,sha256=96BJ7e4oPDKXyvlRrUkiQxmHyjRGpOkAC7R3ln-jgNE,4580 +sympy/polys/numberfields/tests/test_galoisgroups.py,sha256=3LFuMbV92VBFlqqEqjh37oQvmG8cgZ0pFxDCXUoYRL4,5036 +sympy/polys/numberfields/tests/test_minpoly.py,sha256=HjlmPWX90Cb-XK5G1H0-uirOiHdgTu7R8qpcG5ZI5iw,23115 +sympy/polys/numberfields/tests/test_modules.py,sha256=GU4166j_hMlB22uWxxIjV_ON8RsyvpaN7Ly3eK8_m8Y,22926 +sympy/polys/numberfields/tests/test_numbers.py,sha256=M0vZIBnjPBHV4vFUnPBILaqiR_cgSuU50kFB-v7l1gA,5988 +sympy/polys/numberfields/tests/test_primes.py,sha256=JhcAkaQMgjkOSziQ2jZApJ8b8oviil5cUy0hfFqNmZg,9779 +sympy/polys/numberfields/tests/test_subfield.py,sha256=EpBexToc17YwLB4-n6nE_HaleU8AcFGi5OpDReW7q0k,12776 +sympy/polys/numberfields/tests/test_utilities.py,sha256=rQGEJWctcfzjUtMwRuyCHerSqEsoP5C3z1bnddJA17o,3661 +sympy/polys/numberfields/utilities.py,sha256=IHKmfafE9tMGammfdtkyR4_IHb0mON-OBwitE0Ss1R0,13087 +sympy/polys/orderings.py,sha256=IFieyj4LkFa7NDiGTZD3VwUY7mSN3GEjThKk0z5WJ1s,8500 +sympy/polys/orthopolys.py,sha256=PIJg_Kml8MxmJs5QPCjGmRLjjlE_4QKhsWhU7-an7x0,10181 +sympy/polys/partfrac.py,sha256=ptYpXsp8dYyyeiPnLU-rdQ-uv3-GAvDnN79E81C68y8,14695 +sympy/polys/polyclasses.py,sha256=Zc9sjiwVxsM6wM8h9KCFP2Pjlfl4XA3MjC6NlguQzqM,96529 +sympy/polys/polyconfig.py,sha256=mgfFpp9SU159tA_PM2o04WZyzMoWfOtWZugRcHnP42c,1598 +sympy/polys/polyerrors.py,sha256=xByI-fqIHVYsYRm63NmHXlSSRCwSI9vZUoO-1Mf5Wlk,4744 +sympy/polys/polyfuncs.py,sha256=OEZpdYeHQADBJYqMw8JAyN4sw-jsJ6lzVH6m-CCoK8g,8547 +sympy/polys/polymatrix.py,sha256=iNa-EyIrzv7ZeXMaP_PjojgNd29AnIotZE3NeF2te44,9771 +sympy/polys/polyoptions.py,sha256=yG1k4ZPN2ufwpZ4lI4Sn8DSIHvd7EwDUHUaz64HxlUM,21806 +sympy/polys/polyquinticconst.py,sha256=mYLFWSBq3H3Y0I8cx76Z_xauLx1YeViC4xF6yWsSTPQ,96035 +sympy/polys/polyroots.py,sha256=bJToZlR6WZNl9fNxkIJxiPt3XoDQ_K6Pb3UOCBPfsKM,37025 +sympy/polys/polytools.py,sha256=BUwK8wJApazWeKQ3t27yg-HTMnwiv9ScPiavk2n02Rk,212876 +sympy/polys/polyutils.py,sha256=M8V-D4NkfMlsJe4LeAZzljrM4BKp10Qvuuutd8kmp3E,17248 +sympy/polys/puiseux.py,sha256=wc_5w5RyXHfAwC9Dde-6ecPm9y1z5DAmfthtSZ53CqA,26518 +sympy/polys/rationaltools.py,sha256=8vbkg3nuBxbd4ztR7lOj2jTF9taKUKTPah_fD38Ex6c,2838 +sympy/polys/ring_series.py,sha256=7DijmljyAaQrupWB0JmaNwGm3wNTstnEsBln-o1uX1M,59877 +sympy/polys/rings.py,sha256=KVdA3C04G2H3YN81rM-8ORsUHqmktIrz0S0tfwLwN4g,86080 +sympy/polys/rootisolation.py,sha256=QKCYgD4kMNBtSLYkUim8MXHa7louMtlO0riwKTiXRRI,64341 +sympy/polys/rootoftools.py,sha256=bMcVUcIwqaM643UU1WTCNmPmDFRepZEq9Xfdr9mm63Q,43092 +sympy/polys/solvers.py,sha256=FareKqDVVC6P2I4yjudi_3CS3kx0SbmAz3k7zHkETgE,13520 +sympy/polys/specialpolys.py,sha256=B2vijl75zgUKUTY1HCqjB9BTDFf3FM8ugwkKGTB83XA,11038 +sympy/polys/sqfreetools.py,sha256=oRFlOLhcXz5OKjc9SQtOuEhMvacvkHyTSEqhk6Snh1Y,19876 +sympy/polys/subresultants_qq_zz.py,sha256=VFKTAe3iGMCimLkc9GeuwG5o4SB0x2T5kRwxe4A5BDo,88241 +sympy/polys/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/polys/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_appellseqs.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_constructor.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_densearith.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_densebasic.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_densetools.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_dispersion.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_distributedmodules.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_euclidtools.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_factortools.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_fields.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_galoistools.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_groebnertools.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_heuristicgcd.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_hypothesis.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_injections.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_modulargcd.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_monomials.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_multivariate_resultants.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_orderings.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_orthopolys.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_partfrac.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_polyclasses.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_polyfuncs.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_polymatrix.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_polyoptions.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_polyroots.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_polytools.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_polyutils.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_puiseux.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_pythonrational.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_rationaltools.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_ring_series.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_rings.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_rootisolation.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_rootoftools.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_solvers.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_specialpolys.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_sqfreetools.cpython-312.pyc,, +sympy/polys/tests/__pycache__/test_subresultants_qq_zz.cpython-312.pyc,, +sympy/polys/tests/test_appellseqs.py,sha256=YTERuRr30QtfxYR0erXvJG8D-INe9RaMFAF0ZM-H4Ks,3820 +sympy/polys/tests/test_constructor.py,sha256=t6JpLbIdy2hcHF4_s_Xiav0kVc4OOsH5EFg6IXOiwmI,7220 +sympy/polys/tests/test_densearith.py,sha256=ptFGN7ovPH3dqT5khr6Wm8CR6a1WOR7Fi8dj8SuBvJs,40827 +sympy/polys/tests/test_densebasic.py,sha256=FcjAfZngYRQSWJ__BrBPITAUYjMNkS_pOtGyuJv_Bs0,21590 +sympy/polys/tests/test_densetools.py,sha256=o7HZfOw4Xn71RpCDhk98srNipA3zXfikAP_lV0gShlM,26241 +sympy/polys/tests/test_dispersion.py,sha256=S3diTgz7WKH88ulGNT3ijiQ8Y53Rpul6jATBJMGyQdw,3182 +sympy/polys/tests/test_distributedmodules.py,sha256=dXmjhozX5Yzb7DsrtbdFTqAxi9Z1UZNJvGxj-vHM7cM,7639 +sympy/polys/tests/test_euclidtools.py,sha256=vEyj48eIjm6-KRQtThNfI4ic_VDNB6l7jMouxJAF9HE,19482 +sympy/polys/tests/test_factortools.py,sha256=K5_R-01Muc_45XOtolk_tQswE2l6tGrlOJ9zA_aNVYE,24903 +sympy/polys/tests/test_fields.py,sha256=DUvcax7WGtydkLDXq0aQ9Ksc6PkdV67NPZCvqTYN2w8,9869 +sympy/polys/tests/test_galoistools.py,sha256=0oN3eSWvV99juZSXco6Ek9n6s6BFOmOE4UIEhyZnQQs,28532 +sympy/polys/tests/test_groebnertools.py,sha256=ZWHBcCCOVNwDxuJWg1WPo0krTHx1m1wTPi2cOYPsAT4,18584 +sympy/polys/tests/test_heuristicgcd.py,sha256=87Yc0on955VExFyOgJuxBZhsIMFz1Vq4vclIVkQ--cE,4297 +sympy/polys/tests/test_hypothesis.py,sha256=LdokFa3JrQ59_umY15x21QSScPjJoCl8RxHRfn1NUOc,1109 +sympy/polys/tests/test_injections.py,sha256=EONGggBUNWaVSwi817CzLBYJgkTehFq8-m-Qdqes984,1286 +sympy/polys/tests/test_modulargcd.py,sha256=2SjCEjCPkf1-u-Co5vuVg5sJmfBLSY3gkFLicLl4g6E,9043 +sympy/polys/tests/test_monomials.py,sha256=YcMBU1qe6g7EJojtV89dfJZmdXsXVTSly2J5cF6SD6o,11083 +sympy/polys/tests/test_multivariate_resultants.py,sha256=DJu8CcZ3xwx8njpjDeSOyhyxeqZYmhfb7dkSCU-ll7Y,9501 +sympy/polys/tests/test_orderings.py,sha256=bdsIsqJTFJCVyZNRMAGVDXVk79ldw9rmAGejS_lwKP0,4254 +sympy/polys/tests/test_orthopolys.py,sha256=Ob5Osxd8hwebEjK3dDMarZ2VDXzl3pdsEdz_-kMa80M,6560 +sympy/polys/tests/test_partfrac.py,sha256=VfWOx30fZu_avMbWqxtbLDcLi-9x6iuQmLfyatnFc3Y,7838 +sympy/polys/tests/test_polyclasses.py,sha256=EuoT3b9a9KRTQFe95MjGrQIqAhRgLG5qUo42FtkM-Js,14765 +sympy/polys/tests/test_polyfuncs.py,sha256=VbgCgCRE06dtSY9I9GSdPH9T52ETYYoxk4J3N1WBtd4,4520 +sympy/polys/tests/test_polymatrix.py,sha256=pl2VrN_d2XGOVHvvAnaNQzkdFTdQgjt9ePgo41soBRs,7353 +sympy/polys/tests/test_polyoptions.py,sha256=z9DUdt8K3lYkm4IyLH1Cv-TKe76HP-EyaRkZVsfWb6U,12416 +sympy/polys/tests/test_polyroots.py,sha256=m0rnjXMqX59XdFn9X4rRtZJjI39vBN-MAt9cpQszq-I,26803 +sympy/polys/tests/test_polytools.py,sha256=JfaZlcguRIh6ZVNpkIUc2sSRJX_Hq6aluW7HxjCDWO4,139212 +sympy/polys/tests/test_polyutils.py,sha256=Qs3QQl0WYmTnkYE2ovTxdLeu6DYnWO_OoUmLwNDZzSw,11547 +sympy/polys/tests/test_puiseux.py,sha256=4PnBdJuYDWku8l6Jg2Dsn7umg14ldYBdvHqtVaaELbE,7304 +sympy/polys/tests/test_pythonrational.py,sha256=vYMlOTuYvf-15P0nKTFm-uRrhUc-nCFEkqYFAPLxg08,4143 +sympy/polys/tests/test_rationaltools.py,sha256=wkvjzNP1IH-SdubNk5JJ7OWcY-zNF6z3t32kfp9Ncs0,2397 +sympy/polys/tests/test_ring_series.py,sha256=j88HGfiJ9ZL114UezdJtC5aWtox8RG0I2Qyq9gLnkCE,31697 +sympy/polys/tests/test_rings.py,sha256=q8A_CeerrzGqVf1Ol-O-Jc-R7q-2X119YSNMnds3Ccs,48735 +sympy/polys/tests/test_rootisolation.py,sha256=x-n-T-Con-8phelNa05BPszkC_UCW1C0yAOwz658I60,32724 +sympy/polys/tests/test_rootoftools.py,sha256=1cv7M6EQ3mK7NhcwKqbIvour1l_QYtW_zr6vyZ3rzs0,23414 +sympy/polys/tests/test_solvers.py,sha256=kKyEvmqt91HHuAV42DS26B8fPDFQ2Ghtb_Nf3-1eWyI,13644 +sympy/polys/tests/test_specialpolys.py,sha256=v1i0RMNlixxe2EbwqoE-UlV7a2KY-md4T7thhUhWSx0,5031 +sympy/polys/tests/test_sqfreetools.py,sha256=m8ipJE28YC9eOrsVVAqxduCsw4iOW-s_nw76y0E8wUs,4886 +sympy/polys/tests/test_subresultants_qq_zz.py,sha256=bSFOjbtyIClbJHLDvvzgmOgoZyC_5Vdpe7vtW9VGU_s,13219 +sympy/printing/__init__.py,sha256=Hh-z1idh92pk17XjdXkjYwb8cJ5coEr4ZJQGcpE3d9I,2215 +sympy/printing/__pycache__/__init__.cpython-312.pyc,, +sympy/printing/__pycache__/aesaracode.cpython-312.pyc,, +sympy/printing/__pycache__/c.cpython-312.pyc,, +sympy/printing/__pycache__/codeprinter.cpython-312.pyc,, +sympy/printing/__pycache__/conventions.cpython-312.pyc,, +sympy/printing/__pycache__/cxx.cpython-312.pyc,, +sympy/printing/__pycache__/defaults.cpython-312.pyc,, +sympy/printing/__pycache__/dot.cpython-312.pyc,, +sympy/printing/__pycache__/fortran.cpython-312.pyc,, +sympy/printing/__pycache__/glsl.cpython-312.pyc,, +sympy/printing/__pycache__/gtk.cpython-312.pyc,, +sympy/printing/__pycache__/jscode.cpython-312.pyc,, +sympy/printing/__pycache__/julia.cpython-312.pyc,, +sympy/printing/__pycache__/lambdarepr.cpython-312.pyc,, +sympy/printing/__pycache__/latex.cpython-312.pyc,, +sympy/printing/__pycache__/llvmjitcode.cpython-312.pyc,, +sympy/printing/__pycache__/maple.cpython-312.pyc,, +sympy/printing/__pycache__/mathematica.cpython-312.pyc,, +sympy/printing/__pycache__/mathml.cpython-312.pyc,, +sympy/printing/__pycache__/numpy.cpython-312.pyc,, +sympy/printing/__pycache__/octave.cpython-312.pyc,, +sympy/printing/__pycache__/precedence.cpython-312.pyc,, +sympy/printing/__pycache__/preview.cpython-312.pyc,, +sympy/printing/__pycache__/printer.cpython-312.pyc,, +sympy/printing/__pycache__/pycode.cpython-312.pyc,, +sympy/printing/__pycache__/python.cpython-312.pyc,, +sympy/printing/__pycache__/pytorch.cpython-312.pyc,, +sympy/printing/__pycache__/rcode.cpython-312.pyc,, +sympy/printing/__pycache__/repr.cpython-312.pyc,, +sympy/printing/__pycache__/rust.cpython-312.pyc,, +sympy/printing/__pycache__/smtlib.cpython-312.pyc,, +sympy/printing/__pycache__/str.cpython-312.pyc,, +sympy/printing/__pycache__/tableform.cpython-312.pyc,, +sympy/printing/__pycache__/tensorflow.cpython-312.pyc,, +sympy/printing/__pycache__/theanocode.cpython-312.pyc,, +sympy/printing/__pycache__/tree.cpython-312.pyc,, +sympy/printing/aesaracode.py,sha256=_iHvF9avR9MGiOnxLIwog2M5rUwhLRt-bdsbcJHeO_s,18921 +sympy/printing/c.py,sha256=qX8EkxVT5Z2Hncz8DJh8iar_jBuVcRDEiIt1d6jcerE,27011 +sympy/printing/codeprinter.py,sha256=QUAWM6H45YBkd7fX6jXXO3j-tfVaHhzxbXn7OnSm0Es,42371 +sympy/printing/conventions.py,sha256=hvN1VMZE5krMj8FL4AAuxAO0xCwhAugBFWrFQ0355AY,2586 +sympy/printing/cxx.py,sha256=vCQyzT-1eNLLDJy4NBwCp5X5OCoPOZ9icsx8YifaPsc,6123 +sympy/printing/defaults.py,sha256=YitLfIRfFH8ltNd18Y6YtBgq5H2te0wFKlHuIO4cvo8,135 +sympy/printing/dot.py,sha256=W0J798ZxBdlJercffBGnNDTp7J2tMdIYQkE_KIiyi3s,8274 +sympy/printing/fortran.py,sha256=zHVQMphFeeIGl-1x29Hw5Lekxi5NWou-V3Kn4O0oHQQ,28635 +sympy/printing/glsl.py,sha256=wsjPcpyzk92m4I2_re0cn3JwEjPmRlmlVWX9owhzM5w,20310 +sympy/printing/gtk.py,sha256=ptnwYxJr5ox3LG4TCDbRIgxsCikaVvEzWBaqIpITUXc,466 +sympy/printing/jscode.py,sha256=BORODo9Aio62FKh1HYlluG-IxtJC26_-IWrxAiEtmr8,11981 +sympy/printing/julia.py,sha256=V_Qbld0MOebIkT4VnmyP6VdIbgrPaqllgjkv7eSq8bk,23541 +sympy/printing/lambdarepr.py,sha256=BCx4eSdG8MQ8ZSUV1lWEd3CzbZ4IiMid-TTxPoV6FHU,8305 +sympy/printing/latex.py,sha256=jCqXe1XOWLNUcRNzsHOY3CMvbkPBKjf8tD4ii6PVKxU,123669 +sympy/printing/llvmjitcode.py,sha256=NjjHbgheH4j6SboFIDfrrIogkcrJRkW_kjlzM8DpDmQ,17127 +sympy/printing/maple.py,sha256=aG7t4RUEVojSFBVA14GDBzU702KtTcolTCelXozNiN0,10571 +sympy/printing/mathematica.py,sha256=to8LmNkhiP0ACh-Vun-hfaMnLFSEc0mF2OmZnQmihE8,12720 +sympy/printing/mathml.py,sha256=UT7g45oLTqvnrC1IUZeqywHTV6-LUClfuOF_U4AMlaI,76634 +sympy/printing/numpy.py,sha256=Kpq-ySkQSRKYCxtgQZEi_4lj3EmK7FgvbDJTzvB77Tc,21049 +sympy/printing/octave.py,sha256=1ofeBaIcoJfgzImezfPed9Z4dZ6Tk5gVbEQbr02TcLI,25469 +sympy/printing/precedence.py,sha256=hKIin20F4LJp2l5yhSQ-WAegTRHYQLhccABC1_ciI-U,5522 +sympy/printing/pretty/__init__.py,sha256=pJTe-DO4ctTlnjg1UvqyoeBY50B5znFjcGvivXRhM2U,344 +sympy/printing/pretty/__pycache__/__init__.cpython-312.pyc,, +sympy/printing/pretty/__pycache__/pretty.cpython-312.pyc,, +sympy/printing/pretty/__pycache__/pretty_symbology.cpython-312.pyc,, +sympy/printing/pretty/__pycache__/stringpict.cpython-312.pyc,, +sympy/printing/pretty/pretty.py,sha256=KmEXRb6XEtI5tiQYssueibKKrJVF1F1mwrF1uHGxmpM,105024 +sympy/printing/pretty/pretty_symbology.py,sha256=v4FyDz_03mbSGX7tGni8Zw2L2qKTRGvmCIL85ttXg0s,24112 +sympy/printing/pretty/stringpict.py,sha256=UbG55kC4ve8-Dby_v0cm8AXUdLcu4YDLXVnA8F_iV8Y,19158 +sympy/printing/pretty/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/printing/pretty/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/printing/pretty/tests/__pycache__/test_pretty.cpython-312.pyc,, +sympy/printing/pretty/tests/test_pretty.py,sha256=K2Xt--ptdxWLuUmtYJnuyh81ZrGIDRqNM_iOUADAdjA,187716 +sympy/printing/preview.py,sha256=3KacgHEch3KKJZeKc7kvD-L4pfftI8Gm62fx9-Vipak,14089 +sympy/printing/printer.py,sha256=z1phdIHrrcU2cyD-1GaBXREmhkcVl8bxeIWZrGAlczg,15868 +sympy/printing/pycode.py,sha256=LsDnREZEJVw0zsy_AjRSkYER-acomwQiDicrWBmnoW8,27048 +sympy/printing/python.py,sha256=oxGJhNQUXRKjHSEgqroGAyB-A4ZgJQqA_o7C8uXA1U8,3347 +sympy/printing/pytorch.py,sha256=HXEAoLbgbuE-SYj0hvDHeJ0zgzOVDBkK5qWErLCJhNo,10620 +sympy/printing/rcode.py,sha256=uBazXZwSRd95UUQjNoD6qLlpun7Xwlm8cfLG4qYhy3Y,14101 +sympy/printing/repr.py,sha256=GLO6WFOunZ8k0Om0g1VbGW2Y5uOP0IVEo_pIGO8HoNw,11545 +sympy/printing/rust.py,sha256=5Dh_zFxXZRVzbfHGowRQd9moUjzJZ7G2PXjxqsmBBw0,20831 +sympy/printing/smtlib.py,sha256=u2rVmprPITJdLq79FTYm7Fl-osteadr1JyXeQXlZW68,21752 +sympy/printing/str.py,sha256=dTK_CdT-Mm_zRoOL-Mwb4ocBA__h2wBFAAg6VvAiebQ,33239 +sympy/printing/tableform.py,sha256=pz4hXDLZ1IlqU8eOo0XBX1xaALYMqe4qHPUnEVq0mAE,11797 +sympy/printing/tensorflow.py,sha256=QmWoLUKpefBYJZ-J0Ei0NHHrU7Livp8Td4trWTDFzy8,8161 +sympy/printing/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/printing/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_aesaracode.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_c.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_codeprinter.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_conventions.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_cupy.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_cxx.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_dot.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_fortran.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_glsl.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_gtk.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_jax.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_jscode.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_julia.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_lambdarepr.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_latex.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_llvmjit.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_maple.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_mathematica.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_mathml.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_numpy.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_octave.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_precedence.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_preview.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_pycode.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_python.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_rcode.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_repr.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_rust.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_smtlib.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_str.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_tableform.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_tensorflow.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_theanocode.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_torch.cpython-312.pyc,, +sympy/printing/tests/__pycache__/test_tree.cpython-312.pyc,, +sympy/printing/tests/test_aesaracode.py,sha256=dX-SKJHfx9m91NSlt7pQ5Gul0x7fig3XZsHCt2kvtRc,21340 +sympy/printing/tests/test_c.py,sha256=etIEgJwlGWxtH6VRYg3Zkjyw_ktYRYj_-mvEMQehmjI,31227 +sympy/printing/tests/test_codeprinter.py,sha256=rVimgQTdJchy7PsjdZupQmXfqi6FBme2BPwnz7Z5WeQ,2142 +sympy/printing/tests/test_conventions.py,sha256=yqPpU3F0WcbxImPBBAHd3YEZpkFGfcq_TLK4WN_gtP4,5257 +sympy/printing/tests/test_cupy.py,sha256=E2T4a82XITbWAssmRZD4zCQdMCrpaZFCAjGXthUp8cY,1882 +sympy/printing/tests/test_cxx.py,sha256=0XQPQdtDCgEKVfpuelEB-79f7d2fe9QPgEKCCYVAI_w,3183 +sympy/printing/tests/test_dot.py,sha256=TSAtgGIgK_JbY-RMbQgUvnAI87SJqeJOqzcLjAobhKM,4648 +sympy/printing/tests/test_fortran.py,sha256=d5uy1zp0IgaBPupzXpNuk169YZYygnodPWhNRcvUtAQ,35456 +sympy/printing/tests/test_glsl.py,sha256=cfog9fp_EOFm_piJwqUcSvAIJ78bRwkFjecwr3ocCak,28421 +sympy/printing/tests/test_gtk.py,sha256=94gp1xRlPrFiALQGuqHnmh9xKrMxR52RQVkN0MXbUdA,500 +sympy/printing/tests/test_jax.py,sha256=5sOhmFNadFAKT2FumDuk5UqgOc0e0cYkRnJTczClnG8,11062 +sympy/printing/tests/test_jscode.py,sha256=ObahZne9lQbBiXyJZLohjQGdHsG2CnWCFOB8KbFOAqQ,11369 +sympy/printing/tests/test_julia.py,sha256=7KSmbPi_0J2ZSL2fI_xLWqoR9Gy73LfNtzFANHS8EiM,14014 +sympy/printing/tests/test_lambdarepr.py,sha256=DMoIfRNmUkF0KUXoNnJ_skNPU42tJ2xlEvqCT2GxwaA,6947 +sympy/printing/tests/test_latex.py,sha256=xHG_gSlEsD-QkOIiHUyWE4zb0brJxwgwGs1jJBvvOA0,138061 +sympy/printing/tests/test_llvmjit.py,sha256=EGPeRisM60_TIVgnk7PTLSm5F-Aod_88zLjHPZwfyZ8,5344 +sympy/printing/tests/test_maple.py,sha256=dhcz2bqapB_qMyBLMgsgnvVRIcHQ-HmxvAxC_Y0Z3q8,13078 +sympy/printing/tests/test_mathematica.py,sha256=oNNTHZzHviNi_ckua2issBb05IS7GaYyluBJiCjhGoM,10954 +sympy/printing/tests/test_mathml.py,sha256=yVIJYHlFNLbt1qtbKrqjxB2P88dsD6AtS9EVsDi_vEw,99434 +sympy/printing/tests/test_numpy.py,sha256=JZwyiFUS7Vfiwn3j1ogF31PJLJRzH57dtEHq_ujV9wQ,11715 +sympy/printing/tests/test_octave.py,sha256=WOJpsuGhMYLw2ikjwdTV6kVac6-I3xkjZ7qvUVheFbU,18545 +sympy/printing/tests/test_precedence.py,sha256=Za6JCTVvRGZhNY2dqiA8XpUpR5YGck7Op2cXiV78dZA,4067 +sympy/printing/tests/test_preview.py,sha256=dSVxiGqdNR6gbF40V4J2tGhQ-T4RDvSyGypHvYcPDYM,988 +sympy/printing/tests/test_pycode.py,sha256=txwQ1jKkQNZSOXoKw9w2n-_IeIdd-QUjh7WYvOgi1rA,18363 +sympy/printing/tests/test_python.py,sha256=HN7JkzQcKSnB6718i7kaEJZ5pYMqu56z1mSmHQGzY4k,8128 +sympy/printing/tests/test_rcode.py,sha256=TXyl449eCO4J-P3DQb3w9FWvMqOdXmfuiXgyBg_inQQ,13781 +sympy/printing/tests/test_repr.py,sha256=5XmDdIDlQlCWckWq8H95Fw82h-oDxrRpMWZePb6hHa4,12980 +sympy/printing/tests/test_rust.py,sha256=ClZ30PUmZj1ZoBWL2zSt4SsWQS0WB8FrFSQE-w3bxjU,11988 +sympy/printing/tests/test_smtlib.py,sha256=S-42OTOUGkZ-k17qCQ36DYgT-tyOeYqDCvtXzrL2Kzo,22553 +sympy/printing/tests/test_str.py,sha256=QhRuH-hwpXRcPTmKClxqBv8HQdlpNjR4dMXf_XJ3jCs,43523 +sympy/printing/tests/test_tableform.py,sha256=Ff5l1QL2HxN32WS_TdFhUAVqzop8YoWY3Uz1TThvVIM,5692 +sympy/printing/tests/test_tensorflow.py,sha256=-56L5IdYszZy9CGNxS8Ix8UaFStZudFuKQlyyz6Rzzs,17100 +sympy/printing/tests/test_theanocode.py,sha256=E36Fj72HxMK0e1pKTkoTpv9wI4UvwHdVufo-JA6dYq0,21394 +sympy/printing/tests/test_torch.py,sha256=yOtB4yl1DjbTbb8I_t2bdW8fAafVC5G8ubeIJpVLPus,16842 +sympy/printing/tests/test_tree.py,sha256=_8PGAhWMQ_A0f2DQLdDeMrpxY19889P5Ih9H41RZn8s,6080 +sympy/printing/theanocode.py,sha256=d1Aznwfqz6lFR680RGrIf5ht2AH0Ei7pz-7yGZt-CLY,19094 +sympy/printing/tree.py,sha256=tQNjLV3_c3QUUce068AbzAuCiUIJb47l_7F_TYxxFUQ,3868 +sympy/release.py,sha256=oitamisYLp3lrFI3uGv-5ZCJIeYOT9gZLcszUmVNhw8,23 +sympy/sandbox/__init__.py,sha256=IaEVOYHaZ97OHEuto1UGthFuO35c0uvAZFZU23YyEaU,189 +sympy/sandbox/__pycache__/__init__.cpython-312.pyc,, +sympy/sandbox/__pycache__/indexed_integrals.cpython-312.pyc,, +sympy/sandbox/indexed_integrals.py,sha256=svh4xDIa8nGpDeH4TeRb49gG8miMvXpCzEarbor58EE,2141 +sympy/sandbox/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/sandbox/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/sandbox/tests/__pycache__/test_indexed_integrals.cpython-312.pyc,, +sympy/sandbox/tests/test_indexed_integrals.py,sha256=UK2E2wg9EMwda4Vwpzyj3rmXs6ni33HqcbyaqAww6ww,1179 +sympy/series/__init__.py,sha256=DYG9oisjzYeS55dIUpQpbAFcoDz7Q81fZJw36PRGu14,766 +sympy/series/__pycache__/__init__.cpython-312.pyc,, +sympy/series/__pycache__/acceleration.cpython-312.pyc,, +sympy/series/__pycache__/approximants.cpython-312.pyc,, +sympy/series/__pycache__/aseries.cpython-312.pyc,, +sympy/series/__pycache__/formal.cpython-312.pyc,, +sympy/series/__pycache__/fourier.cpython-312.pyc,, +sympy/series/__pycache__/gruntz.cpython-312.pyc,, +sympy/series/__pycache__/kauers.cpython-312.pyc,, +sympy/series/__pycache__/limits.cpython-312.pyc,, +sympy/series/__pycache__/limitseq.cpython-312.pyc,, +sympy/series/__pycache__/order.cpython-312.pyc,, +sympy/series/__pycache__/residues.cpython-312.pyc,, +sympy/series/__pycache__/sequences.cpython-312.pyc,, +sympy/series/__pycache__/series.cpython-312.pyc,, +sympy/series/__pycache__/series_class.cpython-312.pyc,, +sympy/series/acceleration.py,sha256=Phe8jpZ4uiS4vYAzh8PiUoHKVUjyu5K9MoAnZX3pV_w,3365 +sympy/series/approximants.py,sha256=tE-hHuoW62QJHDA3WhRlXaTkokCAODs1vXgjirhOYiQ,3181 +sympy/series/aseries.py,sha256=cHVGRQaza4ayqI6ji6OHNkdQEMV7Bko4f4vug2buEQY,255 +sympy/series/benchmarks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/series/benchmarks/__pycache__/__init__.cpython-312.pyc,, +sympy/series/benchmarks/__pycache__/bench_limit.cpython-312.pyc,, +sympy/series/benchmarks/__pycache__/bench_order.cpython-312.pyc,, +sympy/series/benchmarks/bench_limit.py,sha256=2PtdeeJtD6qyEvt9HFNvyTnMM8phFZRjscgnb4fHndU,173 +sympy/series/benchmarks/bench_order.py,sha256=iC8sQJ0lLlTgiXltAyLzSCQ-3490cf-c6NFiIU44JSk,207 +sympy/series/formal.py,sha256=9HJp9fcNX-MxcIfTtMptdKEyAw6cQQ3LyyzMyEt-9aw,51668 +sympy/series/fourier.py,sha256=H3zDg_S5D0Qeewp-o87_t_30TIg3rad83bzAoz9yp_E,22941 +sympy/series/gruntz.py,sha256=fhHr8w8SeMd-6GKjHmlwajd4FUmzeYo97AA3C_q0lKg,23497 +sympy/series/kauers.py,sha256=PzD0MATMNjLjPi9GW5GQGL6Uqc2UT-uPwnzhi7TkJH8,1720 +sympy/series/limits.py,sha256=hoSFWORWR-DodSf6Po93uK_09JUePhNvI60YsH6V4CI,13307 +sympy/series/limitseq.py,sha256=WM1Lh3RXhSZM1gQaJrhWnUtYEgJunLujIEw1gmtVhYw,7752 +sympy/series/order.py,sha256=1JjdsH2zvP8X1rf75qpfIB-iI70fkcH9CmJsXsRqSxY,19558 +sympy/series/residues.py,sha256=k46s_fFfIHdJZqfst-B_-X1R-SAWs_rR9MQH7a9JLtg,2213 +sympy/series/sequences.py,sha256=WLubAZr5AevpllgI4b6WmIfXRX88QNVCpMGBofGkcqo,35543 +sympy/series/series.py,sha256=PveJ6LibsrDX-mymTbV7teNggnsX0cfaoGMLAP0KAIo,1863 +sympy/series/series_class.py,sha256=033NJ5Re8AS4eq-chmfct3-Lz2vBqdFqXtnrbxswTx0,2918 +sympy/series/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/series/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/series/tests/__pycache__/test_approximants.cpython-312.pyc,, +sympy/series/tests/__pycache__/test_aseries.cpython-312.pyc,, +sympy/series/tests/__pycache__/test_demidovich.cpython-312.pyc,, +sympy/series/tests/__pycache__/test_formal.cpython-312.pyc,, +sympy/series/tests/__pycache__/test_fourier.cpython-312.pyc,, +sympy/series/tests/__pycache__/test_gruntz.cpython-312.pyc,, +sympy/series/tests/__pycache__/test_kauers.cpython-312.pyc,, +sympy/series/tests/__pycache__/test_limits.cpython-312.pyc,, +sympy/series/tests/__pycache__/test_limitseq.cpython-312.pyc,, +sympy/series/tests/__pycache__/test_lseries.cpython-312.pyc,, +sympy/series/tests/__pycache__/test_nseries.cpython-312.pyc,, +sympy/series/tests/__pycache__/test_order.cpython-312.pyc,, +sympy/series/tests/__pycache__/test_residues.cpython-312.pyc,, +sympy/series/tests/__pycache__/test_sequences.cpython-312.pyc,, +sympy/series/tests/__pycache__/test_series.cpython-312.pyc,, +sympy/series/tests/test_approximants.py,sha256=KViHMW1dPXn7xaPYhtTQ9L_WtLLkoIic6yfFnwZ8Q70,1012 +sympy/series/tests/test_aseries.py,sha256=5yWntog5ogRZrmjF3ZhY4e-d2mHYC1Ocs7IXRRFQrtI,2377 +sympy/series/tests/test_demidovich.py,sha256=JGYacqJMEqHS6oT2AYs9d7iutIEb32PkJs9EJqOHxcQ,4947 +sympy/series/tests/test_formal.py,sha256=TpMws7tgQHaokLrzEKZdlOcn6f04WIZhUqreaOOJ0kU,22496 +sympy/series/tests/test_fourier.py,sha256=-RnlhZUZJuctdE3pEtVMeGzCfyWzR1TFeojDhpJqyWo,5908 +sympy/series/tests/test_gruntz.py,sha256=3yPq8ksMGM7x4VQIfsFkk3JIgHlj-g1kJJBwIL76uPg,16445 +sympy/series/tests/test_kauers.py,sha256=Z85FhfXOOVki0HNGeK5BEBZOpkuB6SnKK3FqfK1-aLQ,1102 +sympy/series/tests/test_limits.py,sha256=YuwcBy8Atf-UGP8Li2sFU0guV_ZsjHqx-IdPwI6M3EA,48638 +sympy/series/tests/test_limitseq.py,sha256=QjEF99sYEDqfY7ULz1qjQTo6e0lIRUCflEOBgiDYRVA,5691 +sympy/series/tests/test_lseries.py,sha256=GlQvlBlD9wh02PPBP6zU83wmhurvGUFTuCRp44B4uI4,1875 +sympy/series/tests/test_nseries.py,sha256=uzhzYswSOe9Gh_nWKeO69tvGPMLd-9tqk4HBYX8JIm4,18284 +sympy/series/tests/test_order.py,sha256=AUlRkYKCUIs4DyT6g94ZGmjzT2fqHutPXOUGhpz4mb0,17901 +sympy/series/tests/test_residues.py,sha256=pT9xzPqtmfKGSbLLAxgDVZLTSy3TOxyfq3thTJs2VLw,3178 +sympy/series/tests/test_sequences.py,sha256=Oyq32yQZnGNQDS2uJ3by3bZ-y4G9c9BFfdQTcVuW2RM,11161 +sympy/series/tests/test_series.py,sha256=yPqSIfTytdiIYlYR9yvK7uS4IwF1fctpDiiktEnwvec,17006 +sympy/sets/__init__.py,sha256=3vjCm4v2esbpsVPY0ROwTXMETxns_66bG4FCIFZ96oM,1026 +sympy/sets/__pycache__/__init__.cpython-312.pyc,, +sympy/sets/__pycache__/conditionset.cpython-312.pyc,, +sympy/sets/__pycache__/contains.cpython-312.pyc,, +sympy/sets/__pycache__/fancysets.cpython-312.pyc,, +sympy/sets/__pycache__/ordinals.cpython-312.pyc,, +sympy/sets/__pycache__/powerset.cpython-312.pyc,, +sympy/sets/__pycache__/setexpr.cpython-312.pyc,, +sympy/sets/__pycache__/sets.cpython-312.pyc,, +sympy/sets/conditionset.py,sha256=mhodBVrMqJ6W5H8CuaFhO3FO9VdJifOEPjjFmV9lT2I,7792 +sympy/sets/contains.py,sha256=AlsfOc_6V0TH_6G7XTPIXhDywgtg3ECdjCTfSOmPC-E,1829 +sympy/sets/fancysets.py,sha256=tZ4wVasc937Yr0VkQuLVHe75Falcr72Nrkhk89178QQ,48187 +sympy/sets/handlers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/sets/handlers/__pycache__/__init__.cpython-312.pyc,, +sympy/sets/handlers/__pycache__/add.cpython-312.pyc,, +sympy/sets/handlers/__pycache__/comparison.cpython-312.pyc,, +sympy/sets/handlers/__pycache__/functions.cpython-312.pyc,, +sympy/sets/handlers/__pycache__/intersection.cpython-312.pyc,, +sympy/sets/handlers/__pycache__/issubset.cpython-312.pyc,, +sympy/sets/handlers/__pycache__/mul.cpython-312.pyc,, +sympy/sets/handlers/__pycache__/power.cpython-312.pyc,, +sympy/sets/handlers/__pycache__/union.cpython-312.pyc,, +sympy/sets/handlers/add.py,sha256=_ucFvxuDv9wsmKxGkCDUERtYk3I_tQxjZjY3ZkroWs0,1863 +sympy/sets/handlers/comparison.py,sha256=WfT_vLrOkvPqRg2mf7gziVs_6cLg0kOTEFv-Nb1zIvo,1601 +sympy/sets/handlers/functions.py,sha256=jYSFqFNH6mXbKFPgvIAIGY8BhbLPo1dAvcNg4MxmCaI,8381 +sympy/sets/handlers/intersection.py,sha256=oYPmrx3FAkGLVWT3EjSimeMfsGqPsqVnpJm5UxQzuCM,17514 +sympy/sets/handlers/issubset.py,sha256=azka_5eOaUro3r3v72PmET0oY8-aaoJkzVEK7kuqXCA,4739 +sympy/sets/handlers/mul.py,sha256=XFbkOw4PDQumaOEUlHeQLvjhIom0f3iniSYv_Kau-xw,1842 +sympy/sets/handlers/power.py,sha256=84N3dIus7r09XV7PF_RiEpFRw1y5tOGD34WKzSM9F-4,3186 +sympy/sets/handlers/union.py,sha256=lrAdydqExnALUjM0dnoM-7JAZqtbgLb46Y2GGmFtQdw,4225 +sympy/sets/ordinals.py,sha256=GSyaBq7BHJC3pvgoCDoUKZQ0IE2VXyHtx6_g5OS64W4,7641 +sympy/sets/powerset.py,sha256=vIGnSYKngEPEt6V-6beDOXAOY9ugDLJ8fXOx5H9JJck,2913 +sympy/sets/setexpr.py,sha256=jMOQigDscLTrFPXvHqo1ODVRG9BqC4yn38Ej4m6WPa0,3019 +sympy/sets/sets.py,sha256=-iuLnPWLunCa0oOErHELO9EkLZXs6L2AFWQgkCFbJcA,81202 +sympy/sets/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/sets/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/sets/tests/__pycache__/test_conditionset.cpython-312.pyc,, +sympy/sets/tests/__pycache__/test_contains.cpython-312.pyc,, +sympy/sets/tests/__pycache__/test_fancysets.cpython-312.pyc,, +sympy/sets/tests/__pycache__/test_ordinals.cpython-312.pyc,, +sympy/sets/tests/__pycache__/test_powerset.cpython-312.pyc,, +sympy/sets/tests/__pycache__/test_setexpr.cpython-312.pyc,, +sympy/sets/tests/__pycache__/test_sets.cpython-312.pyc,, +sympy/sets/tests/test_conditionset.py,sha256=UeutWuBCT5PZicNkkl9E94pREnU5CvLGWUfmRS29PcU,11370 +sympy/sets/tests/test_contains.py,sha256=ec6WRzriwV9nurz3jS9IXEqtfL1pZedtJFp--fSsBvY,1561 +sympy/sets/tests/test_fancysets.py,sha256=oiuu5PKNrDeDO-NtgsE4CpkwQaS7JNgCYuSyc1ykKKE,51938 +sympy/sets/tests/test_ordinals.py,sha256=L4DYc6ByQMDwJGFzJC3YhfSrVk5auW7pf4QYpJ5xY7w,2637 +sympy/sets/tests/test_powerset.py,sha256=nFvDGlhAf0wG-pZnPkgJjfwDHrTwdro3MYIinwyxn94,4805 +sympy/sets/tests/test_setexpr.py,sha256=E--SjYVzrmau0EbD8g4NTqp6aLD8qHzIuI7sAfuWxpY,14797 +sympy/sets/tests/test_sets.py,sha256=oMtqcr9gr68itfWH4j18POID8tD0hAZUV8HCz7-KKj0,68544 +sympy/simplify/__init__.py,sha256=MH1vkwHq0J5tNm7ss8V6v-mjrDGUXwfOsariIwfi38c,1274 +sympy/simplify/__pycache__/__init__.cpython-312.pyc,, +sympy/simplify/__pycache__/_cse_diff.cpython-312.pyc,, +sympy/simplify/__pycache__/combsimp.cpython-312.pyc,, +sympy/simplify/__pycache__/cse_main.cpython-312.pyc,, +sympy/simplify/__pycache__/cse_opts.cpython-312.pyc,, +sympy/simplify/__pycache__/epathtools.cpython-312.pyc,, +sympy/simplify/__pycache__/fu.cpython-312.pyc,, +sympy/simplify/__pycache__/gammasimp.cpython-312.pyc,, +sympy/simplify/__pycache__/hyperexpand.cpython-312.pyc,, +sympy/simplify/__pycache__/hyperexpand_doc.cpython-312.pyc,, +sympy/simplify/__pycache__/powsimp.cpython-312.pyc,, +sympy/simplify/__pycache__/radsimp.cpython-312.pyc,, +sympy/simplify/__pycache__/ratsimp.cpython-312.pyc,, +sympy/simplify/__pycache__/simplify.cpython-312.pyc,, +sympy/simplify/__pycache__/sqrtdenest.cpython-312.pyc,, +sympy/simplify/__pycache__/traversaltools.cpython-312.pyc,, +sympy/simplify/__pycache__/trigsimp.cpython-312.pyc,, +sympy/simplify/_cse_diff.py,sha256=Nq1gXn27o1v83t__SQUuacnOohhywa39ucPaR2jD518,10479 +sympy/simplify/combsimp.py,sha256=UzgG6eC_eIzieMS3j0oQFJnS5XkZ1gxNqOSzBqJcIFQ,3604 +sympy/simplify/cse_main.py,sha256=tcUmXXFGIZyoX4PvBEmZ-YYm-CBLXoAyGLHverxP23o,31310 +sympy/simplify/cse_opts.py,sha256=ZTCaOdOrgtifWxQmFzyngrLq9uwzByBdiSS5mE-DDoE,1618 +sympy/simplify/epathtools.py,sha256=fV3oeD2J3LJRQ4YoTV6gq3yFT_NSZi-7xxKnrX-2KJA,10122 +sympy/simplify/fu.py,sha256=exevmk1p4YgEAO-MmTgh7cG7cyVMMF8p7vZ1ymwwKiI,62208 +sympy/simplify/gammasimp.py,sha256=yzfkD_q1Zxu1eMCZuprmA3VzZXhecX3K0xdZlUdYlcY,18485 +sympy/simplify/hyperexpand.py,sha256=sTWd1-VeLr0NTr-cm6nftjmO_gVPqa1P9ud_rvSZS54,84420 +sympy/simplify/hyperexpand_doc.py,sha256=E8AD0mj8ULtelDSUkmJKJY7kYm5fVfCL4QH_DX65qEw,521 +sympy/simplify/powsimp.py,sha256=aCkX2zxgOm1S9oWc260KrzhSwcJw8p3JEMZ-vkmUapM,26754 +sympy/simplify/radsimp.py,sha256=VP83Ufl_9DUtmeHCRXSmOHqdg9zDsPoQJ_7eUyCiwpI,41649 +sympy/simplify/ratsimp.py,sha256=vTu0t0k1FDFTofl4mwcK9NuTMNZ20IsL8fIyFJRFNkg,7682 +sympy/simplify/simplify.py,sha256=3rK7cCfkh1svliMVsCuTv9_aQDz3nmZvA_HRAvmNkSo,73330 +sympy/simplify/sqrtdenest.py,sha256=MsTyPUcEhiMf51fpk6e5grlqudU-LMAHOuatPCxo5uA,21600 +sympy/simplify/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/simplify/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/simplify/tests/__pycache__/test_combsimp.cpython-312.pyc,, +sympy/simplify/tests/__pycache__/test_cse.cpython-312.pyc,, +sympy/simplify/tests/__pycache__/test_cse_diff.cpython-312.pyc,, +sympy/simplify/tests/__pycache__/test_epathtools.cpython-312.pyc,, +sympy/simplify/tests/__pycache__/test_fu.cpython-312.pyc,, +sympy/simplify/tests/__pycache__/test_function.cpython-312.pyc,, +sympy/simplify/tests/__pycache__/test_gammasimp.cpython-312.pyc,, +sympy/simplify/tests/__pycache__/test_hyperexpand.cpython-312.pyc,, +sympy/simplify/tests/__pycache__/test_powsimp.cpython-312.pyc,, +sympy/simplify/tests/__pycache__/test_radsimp.cpython-312.pyc,, +sympy/simplify/tests/__pycache__/test_ratsimp.cpython-312.pyc,, +sympy/simplify/tests/__pycache__/test_rewrite.cpython-312.pyc,, +sympy/simplify/tests/__pycache__/test_simplify.cpython-312.pyc,, +sympy/simplify/tests/__pycache__/test_sqrtdenest.cpython-312.pyc,, +sympy/simplify/tests/__pycache__/test_trigsimp.cpython-312.pyc,, +sympy/simplify/tests/test_combsimp.py,sha256=O95WSxCvo2fDQs-UlarAcSf0_8M3PuTR76lhREDoNA8,2958 +sympy/simplify/tests/test_cse.py,sha256=JOjH5G6GPfeaKpKdeeKL1vvHgbt8TGxTkqmH2e1ovY8,25516 +sympy/simplify/tests/test_cse_diff.py,sha256=Y_zYZpldwjUoWiTTpFMlw4PXkqNp9r9Zwrw46gkmNoY,7275 +sympy/simplify/tests/test_epathtools.py,sha256=ugsQlfuK6POiixdeit63QovsVAlG5JyCaPlPp0j35LE,3525 +sympy/simplify/tests/test_fu.py,sha256=X2NNsynwefg2aH5GhyxQItL80fKPZ9md6nydMEedWbQ,19410 +sympy/simplify/tests/test_function.py,sha256=gzdcSFObuDzVFJDdAgmERtZJvG38WNSmclPAdG8OaPQ,2199 +sympy/simplify/tests/test_gammasimp.py,sha256=32cPRmtG-_Mz9g02lmmn-PWDD3J_Ku6sxLxIUU7WqxE,5320 +sympy/simplify/tests/test_hyperexpand.py,sha256=y3lxd97UZ1BkrrZe0r2l6MM8zNABTE_L4KtxFwmdzeQ,41043 +sympy/simplify/tests/test_powsimp.py,sha256=FWI_K8nozwYzhrhY1Q0CZkf6n88hFR0jjuYRvQnMius,14375 +sympy/simplify/tests/test_radsimp.py,sha256=Gf6Tf7-lb5G8gqF6hJA6kPrZNFES6fCz7_-ls7TFUfY,19128 +sympy/simplify/tests/test_ratsimp.py,sha256=bv-K60A7m2on-U9szzaeYO7Hlp1EK5P0HvBBO59oyas,2198 +sympy/simplify/tests/test_rewrite.py,sha256=LZj4V6a95GJj1o3NlKRoHMk7sWGPASFlw24nsm4z43k,1127 +sympy/simplify/tests/test_simplify.py,sha256=QkiaVVj0nqHXvu1lUUYZfYZ6_Ods6DfiBwFiqAJKSoo,41928 +sympy/simplify/tests/test_sqrtdenest.py,sha256=4zRtDQVGpKRRBYSAnEF5pSM0AR_fAMumONu2Ocb3tqg,7470 +sympy/simplify/tests/test_trigsimp.py,sha256=vG5PDTDNOuFypT7H9DSMjIollPqkKdNhWv5FBj6vFnE,19949 +sympy/simplify/traversaltools.py,sha256=pn_t9Yrk_SL1X0vl-zVR6yZaxkY25D4MwTBv4ywnD1Y,409 +sympy/simplify/trigsimp.py,sha256=t36QKVf_0yqVCNo1hUBlBp5locL0sMH1AlsAwQCzpLQ,46857 +sympy/solvers/__init__.py,sha256=nb1LceF2MwvULXsCN8VUq7X2tVgZOPsmWYHGFszIdW4,2333 +sympy/solvers/__pycache__/__init__.cpython-312.pyc,, +sympy/solvers/__pycache__/bivariate.cpython-312.pyc,, +sympy/solvers/__pycache__/decompogen.cpython-312.pyc,, +sympy/solvers/__pycache__/deutils.cpython-312.pyc,, +sympy/solvers/__pycache__/inequalities.cpython-312.pyc,, +sympy/solvers/__pycache__/pde.cpython-312.pyc,, +sympy/solvers/__pycache__/polysys.cpython-312.pyc,, +sympy/solvers/__pycache__/recurr.cpython-312.pyc,, +sympy/solvers/__pycache__/simplex.cpython-312.pyc,, +sympy/solvers/__pycache__/solvers.cpython-312.pyc,, +sympy/solvers/__pycache__/solveset.cpython-312.pyc,, +sympy/solvers/benchmarks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/solvers/benchmarks/__pycache__/__init__.cpython-312.pyc,, +sympy/solvers/benchmarks/__pycache__/bench_solvers.cpython-312.pyc,, +sympy/solvers/benchmarks/bench_solvers.py,sha256=ZVK2TIW0XjWRDBex054ymmVlSBQw-RIBhEL1wS2ZAmU,288 +sympy/solvers/bivariate.py,sha256=Ku4Ttid3yU3CIc4IPfJ7bedLtXVaGKvFOonEIlZrXXw,17870 +sympy/solvers/decompogen.py,sha256=dWQla7hp7A4RqI2a0qRNQLWNPEuur68lD3dVTyktdBU,3757 +sympy/solvers/deutils.py,sha256=jukqDw6JGZfl36HRFjZIX_A0_iarmTawI0Up7z5tQDc,10315 +sympy/solvers/diophantine/__init__.py,sha256=I1p3uj3kFQv20cbsZ34K5rNCx1_pDS7JwHUCFstpBgs,128 +sympy/solvers/diophantine/__pycache__/__init__.cpython-312.pyc,, +sympy/solvers/diophantine/__pycache__/diophantine.cpython-312.pyc,, +sympy/solvers/diophantine/diophantine.py,sha256=n74XrMIW6ZwrAfaVVks7nwB01GClI0SYdvTe5K90Jnc,122482 +sympy/solvers/diophantine/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/solvers/diophantine/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/solvers/diophantine/tests/__pycache__/test_diophantine.cpython-312.pyc,, +sympy/solvers/diophantine/tests/test_diophantine.py,sha256=N7ZCyNVfSV0JzAKbnc_8YbUFq5ZkiDLnO6MxxMxCG90,43335 +sympy/solvers/inequalities.py,sha256=kz6HzAytg4V2eqSKwGzbJuYyFfgj6bFSUgk1i15zVp0,33189 +sympy/solvers/ode/__init__.py,sha256=I7RKwCcaoerflUm5i3ZDJgBIOnkhBjb83BCHcVcFqfM,468 +sympy/solvers/ode/__pycache__/__init__.cpython-312.pyc,, +sympy/solvers/ode/__pycache__/hypergeometric.cpython-312.pyc,, +sympy/solvers/ode/__pycache__/lie_group.cpython-312.pyc,, +sympy/solvers/ode/__pycache__/nonhomogeneous.cpython-312.pyc,, +sympy/solvers/ode/__pycache__/ode.cpython-312.pyc,, +sympy/solvers/ode/__pycache__/riccati.cpython-312.pyc,, +sympy/solvers/ode/__pycache__/single.cpython-312.pyc,, +sympy/solvers/ode/__pycache__/subscheck.cpython-312.pyc,, +sympy/solvers/ode/__pycache__/systems.cpython-312.pyc,, +sympy/solvers/ode/hypergeometric.py,sha256=t9KN5AdB7yF-rRoatEBzUYBcrwvIrKm83KBDa5BJYqY,10048 +sympy/solvers/ode/lie_group.py,sha256=C2HoOVtDbIT2ryx4TzEvQU46Yqc8LurTBBtjv5m2-BQ,39175 +sympy/solvers/ode/nonhomogeneous.py,sha256=Wi6UxjYNAPcfJsEzKHNvIJ8zhJ7-ZOkqccCR93MpUuM,17875 +sympy/solvers/ode/ode.py,sha256=9UQ0bqcrFOsGuSxGfRJpd2CllIWfiUYZPC2-A7Crefo,145379 +sympy/solvers/ode/riccati.py,sha256=3ZrkCy3ufXCyCx8gJfAuxyCOgbOLEHtvTh2VgJhA7Mk,30736 +sympy/solvers/ode/single.py,sha256=yBpPVFK3LsCf07dDb9_x6tzhp5d4ln_xIpMZpP2Ryrc,109465 +sympy/solvers/ode/subscheck.py,sha256=CIPca_qTxL9z5oaD2e2NrgME0eVQgF9PabZndcVqHZM,16130 +sympy/solvers/ode/systems.py,sha256=Kok2AMO4YEKX38fi2LrxLm5zpTcNXz398b7OBvrUezU,71467 +sympy/solvers/ode/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/solvers/ode/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/solvers/ode/tests/__pycache__/test_lie_group.cpython-312.pyc,, +sympy/solvers/ode/tests/__pycache__/test_ode.cpython-312.pyc,, +sympy/solvers/ode/tests/__pycache__/test_riccati.cpython-312.pyc,, +sympy/solvers/ode/tests/__pycache__/test_single.cpython-312.pyc,, +sympy/solvers/ode/tests/__pycache__/test_subscheck.cpython-312.pyc,, +sympy/solvers/ode/tests/__pycache__/test_systems.cpython-312.pyc,, +sympy/solvers/ode/tests/test_lie_group.py,sha256=vg1yy_-a5x1Xm2IcVkEi5cD2uA5wE5gjqpfBwkV1vZc,5319 +sympy/solvers/ode/tests/test_ode.py,sha256=bEcTi9zA5TooKOE9duFtd6TAVRvLPrO92arX7fF85-Q,48508 +sympy/solvers/ode/tests/test_riccati.py,sha256=a2_pXzCFb9WDtT_kdxYkfLd-PG5xvs4rQn_vpFk-O9s,29348 +sympy/solvers/ode/tests/test_single.py,sha256=sEvhXws920Oe_IuvmBIYM5iPViR6I3njZNgJlc8sMC4,100200 +sympy/solvers/ode/tests/test_subscheck.py,sha256=Gzwc9h9n6zlNOhJ8Qh6fQDeB8ghaRmgv3ktBAfPJx-U,12468 +sympy/solvers/ode/tests/test_systems.py,sha256=PeIEHOx8-eZQNuqOfhjTvGEeFSVriLlHShPmy84mde4,129087 +sympy/solvers/pde.py,sha256=V2jxgmmepng2ofFFDVOsBHWqf-IUQCgIz4lXzhBUeyg,34913 +sympy/solvers/polysys.py,sha256=4CCK3FNhl-K6B4bYF_goSrAq1JOMubl6KsmaB_5R2f4,27168 +sympy/solvers/recurr.py,sha256=DyssZuOyemoC6J1cWq635O7zkg1WLHrR7KGoM-gNy0g,25389 +sympy/solvers/simplex.py,sha256=peRv44aDM30U_0wk8xZv3t6M_cpm_a9hBALiyr7zndY,35276 +sympy/solvers/solvers.py,sha256=xsSlQaj0XaunexmhfQZZI_uiRXHETmaUab9hgZrmmbU,138454 +sympy/solvers/solveset.py,sha256=6VxsiKcn4fwdJGYXA8k1si5zvYs6vNrSTtLcmSKpjMk,151683 +sympy/solvers/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/solvers/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/solvers/tests/__pycache__/test_constantsimp.cpython-312.pyc,, +sympy/solvers/tests/__pycache__/test_decompogen.cpython-312.pyc,, +sympy/solvers/tests/__pycache__/test_inequalities.cpython-312.pyc,, +sympy/solvers/tests/__pycache__/test_numeric.cpython-312.pyc,, +sympy/solvers/tests/__pycache__/test_pde.cpython-312.pyc,, +sympy/solvers/tests/__pycache__/test_polysys.cpython-312.pyc,, +sympy/solvers/tests/__pycache__/test_recurr.cpython-312.pyc,, +sympy/solvers/tests/__pycache__/test_simplex.cpython-312.pyc,, +sympy/solvers/tests/__pycache__/test_solvers.cpython-312.pyc,, +sympy/solvers/tests/__pycache__/test_solveset.cpython-312.pyc,, +sympy/solvers/tests/test_constantsimp.py,sha256=9Feugsg9jD2BwQiG4EFpb9fORyst6JdBmZqq2GaOgH8,8707 +sympy/solvers/tests/test_decompogen.py,sha256=7GUsDQQZtYbZIK0p0UxsOuNEJxEt4IHeOSsem_k-k0U,2943 +sympy/solvers/tests/test_inequalities.py,sha256=whg3vGXEYxeIHNQS4yBeB9VQpoYWnfw5NBS4xLiqDJ8,21025 +sympy/solvers/tests/test_numeric.py,sha256=pKLBJuf4lGCewf5DgBjvH5T9phf6ilkyW1gB2R-5SzA,4734 +sympy/solvers/tests/test_pde.py,sha256=UGP3uWjF8pKQgfPifmdfvS5URVmzSg6m2NkS7LGzmio,9257 +sympy/solvers/tests/test_polysys.py,sha256=bK2ckIhQvbJCc6_qsUOAuAEyTc5CR8J2yiqN4MFOgpM,15266 +sympy/solvers/tests/test_recurr.py,sha256=-OeghSg16GFN70y_RUXC6CF6VU_b7NXaKDbejtRSocg,11418 +sympy/solvers/tests/test_simplex.py,sha256=pG7j7KxXrlK8K_fF04XH_mvMzwEOopSBpJZiagKjyNs,9037 +sympy/solvers/tests/test_solvers.py,sha256=eXM6AT2upxlRC7S2l1YxUSS6jJNM42PxzYCTz4C4vmc,107765 +sympy/solvers/tests/test_solveset.py,sha256=lOQ4hG7Dg6yuDgFriKIlvWdzEumehgL08Srsh4JwDHY,148480 +sympy/stats/__init__.py,sha256=9pY3OMdvAIeJ_Q1ZqynOZ8hHWFFrrxOx0qBHKkGfHCg,8487 +sympy/stats/__pycache__/__init__.cpython-312.pyc,, +sympy/stats/__pycache__/compound_rv.cpython-312.pyc,, +sympy/stats/__pycache__/crv.cpython-312.pyc,, +sympy/stats/__pycache__/crv_types.cpython-312.pyc,, +sympy/stats/__pycache__/drv.cpython-312.pyc,, +sympy/stats/__pycache__/drv_types.cpython-312.pyc,, +sympy/stats/__pycache__/error_prop.cpython-312.pyc,, +sympy/stats/__pycache__/frv.cpython-312.pyc,, +sympy/stats/__pycache__/frv_types.cpython-312.pyc,, +sympy/stats/__pycache__/joint_rv.cpython-312.pyc,, +sympy/stats/__pycache__/joint_rv_types.cpython-312.pyc,, +sympy/stats/__pycache__/matrix_distributions.cpython-312.pyc,, +sympy/stats/__pycache__/random_matrix.cpython-312.pyc,, +sympy/stats/__pycache__/random_matrix_models.cpython-312.pyc,, +sympy/stats/__pycache__/rv.cpython-312.pyc,, +sympy/stats/__pycache__/rv_interface.cpython-312.pyc,, +sympy/stats/__pycache__/stochastic_process.cpython-312.pyc,, +sympy/stats/__pycache__/stochastic_process_types.cpython-312.pyc,, +sympy/stats/__pycache__/symbolic_multivariate_probability.cpython-312.pyc,, +sympy/stats/__pycache__/symbolic_probability.cpython-312.pyc,, +sympy/stats/compound_rv.py,sha256=SO1KXJ0aHGbD5y9QA8o6qOHbio3ua8wyO2Rsh0Hnw48,7965 +sympy/stats/crv.py,sha256=jd8iemE41aW-byXgFDYKaMv2VOOUnyUtiMx_QAXI-n4,21028 +sympy/stats/crv_types.py,sha256=qXYxtvJPg4ORJI7AxIkRhwnJ6lcz3sVBWf4toQy9vvA,122371 +sympy/stats/drv.py,sha256=Zu8IK9yt69XJFKt-ShoJfZbvZ-CGMwvrKNiXvi6q_n4,11994 +sympy/stats/drv_types.py,sha256=2jL6QYa9lAlbvTxvx9BXdfwU6PRt0uzV3CVXRIeZ5k0,19865 +sympy/stats/error_prop.py,sha256=a-H6GZEidsiP_4-iNw7nSD99AMyN6DNHsSl0IUZGIAs,3315 +sympy/stats/frv.py,sha256=vZROeD6DSVGX0kfOL_yOds3pZgjSiXFX-bMZtSUkVMA,16874 +sympy/stats/frv_types.py,sha256=Xkc3MU5dFLajPajIStW_lV4qiuiHg86rBo45zX_oGLk,23348 +sympy/stats/joint_rv.py,sha256=DcixlO2Ml4gnwMmZk2VTegiHVq88DkLdQlOTQ57SQtc,15963 +sympy/stats/joint_rv_types.py,sha256=PUatR4WcPHmAHadt8iRh5xYh5NJigzYh-EoAMR5blDw,30575 +sympy/stats/matrix_distributions.py,sha256=3OricwEMM_NU8b2lJxoiSTml7kvqrNQ6IUIn9Xy_DsY,21953 +sympy/stats/random_matrix.py,sha256=NmzLC5JMDWI2TvH8tY6go8lYyHmqcZ-B7sSIO7z7oAk,1028 +sympy/stats/random_matrix_models.py,sha256=7i5XAUYxt-ekmP5KDMaytUlmCvxglEspoWbswSf82tE,15328 +sympy/stats/rv.py,sha256=rmjdVpsvJrqtMgnreuT_7lU5S_V2nkvlrpUvA7zCWLM,54579 +sympy/stats/rv_interface.py,sha256=0ZSplwmkEtio_UTlh7bqSK_1aILgvk2JTfZ-CkOcfAc,13935 +sympy/stats/sampling/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/stats/sampling/__pycache__/__init__.cpython-312.pyc,, +sympy/stats/sampling/__pycache__/sample_numpy.cpython-312.pyc,, +sympy/stats/sampling/__pycache__/sample_pymc.cpython-312.pyc,, +sympy/stats/sampling/__pycache__/sample_scipy.cpython-312.pyc,, +sympy/stats/sampling/sample_numpy.py,sha256=B4ZC7ZBrSD6ICQT468rOy-xrOgQDuecsHa0zJesAeYE,4229 +sympy/stats/sampling/sample_pymc.py,sha256=9g-n04aXSFc6F7FJ5zTYtHHL6W8-26g1nrgtamJc3Hw,2995 +sympy/stats/sampling/sample_scipy.py,sha256=ysqpDy8bp1RMH0g5FFgMmp2SQuXGFkcSH7JDZEpiZ8w,6329 +sympy/stats/sampling/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/stats/sampling/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/stats/sampling/tests/__pycache__/test_sample_continuous_rv.cpython-312.pyc,, +sympy/stats/sampling/tests/__pycache__/test_sample_discrete_rv.cpython-312.pyc,, +sympy/stats/sampling/tests/__pycache__/test_sample_finite_rv.cpython-312.pyc,, +sympy/stats/sampling/tests/test_sample_continuous_rv.py,sha256=Gh8hFN1hFFsthEv9wP2ZdgghQfaEnE8n7HlmyXXhN1E,5708 +sympy/stats/sampling/tests/test_sample_discrete_rv.py,sha256=Z3hqjHEFaIoB0hrhpy7YYL_7Dtqzmy5YMWAYrlqPu38,3360 +sympy/stats/sampling/tests/test_sample_finite_rv.py,sha256=dWwrFePw8eX2rBheAXi1AVxr_gqBD63VZKfW81hNoQc,3061 +sympy/stats/stochastic_process.py,sha256=pDz0rbKXTiaNmMmmz70dP3F_KWL_XhoCKFHYBNt1QeU,2312 +sympy/stats/stochastic_process_types.py,sha256=YEUA-saTh8WF6Pn7GcgrcyclRCb_SC13YnpgOIpu7-Q,88553 +sympy/stats/symbolic_multivariate_probability.py,sha256=R6Co7XCcxLoOtTqC6ZSnGuylZNUBrC5AD0DrJr2jE1A,10450 +sympy/stats/symbolic_probability.py,sha256=HkWUiH9EM_DQ1aM1FxNmBm_8xtqeviIsyUpqFl2RYnI,23266 +sympy/stats/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/stats/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/stats/tests/__pycache__/test_compound_rv.cpython-312.pyc,, +sympy/stats/tests/__pycache__/test_continuous_rv.cpython-312.pyc,, +sympy/stats/tests/__pycache__/test_discrete_rv.cpython-312.pyc,, +sympy/stats/tests/__pycache__/test_error_prop.cpython-312.pyc,, +sympy/stats/tests/__pycache__/test_finite_rv.cpython-312.pyc,, +sympy/stats/tests/__pycache__/test_joint_rv.cpython-312.pyc,, +sympy/stats/tests/__pycache__/test_matrix_distributions.cpython-312.pyc,, +sympy/stats/tests/__pycache__/test_mix.cpython-312.pyc,, +sympy/stats/tests/__pycache__/test_random_matrix.cpython-312.pyc,, +sympy/stats/tests/__pycache__/test_rv.cpython-312.pyc,, +sympy/stats/tests/__pycache__/test_stochastic_process.cpython-312.pyc,, +sympy/stats/tests/__pycache__/test_symbolic_multivariate.cpython-312.pyc,, +sympy/stats/tests/__pycache__/test_symbolic_probability.cpython-312.pyc,, +sympy/stats/tests/test_compound_rv.py,sha256=2927chbHTThA34Ki-ji319QT7ajQ1ueC640Mga-18ZA,6263 +sympy/stats/tests/test_continuous_rv.py,sha256=BcBkiyX7e1QiwS6xnD-qLzXnijvqbsebTzXEn3IfGyE,56140 +sympy/stats/tests/test_discrete_rv.py,sha256=bLqMtKpH5fDjuP7uuRAtAjakbahuFz9x3dY-PPKFsGk,11230 +sympy/stats/tests/test_error_prop.py,sha256=xKAkw3F5XJ72xiDREI7PkyReWNVW_89CD_mjOY_diDY,1933 +sympy/stats/tests/test_finite_rv.py,sha256=JHYgY4snFF5t9qcnQfKaN5zaGsO7_SuNR7Tq234W4No,20413 +sympy/stats/tests/test_joint_rv.py,sha256=W28rCRYczv5Jax7k-bj7OveT-y-AP4q-kRR0-LNaWX0,18653 +sympy/stats/tests/test_matrix_distributions.py,sha256=9daJUiSGaLq34TeZfB-xPqC8xz6vECGrm0DdBZaQPyY,8857 +sympy/stats/tests/test_mix.py,sha256=Cplnw06Ki96Y_4fx6Bu7lUXjxoIfX7tNJasm9SOz5wQ,3991 +sympy/stats/tests/test_random_matrix.py,sha256=CiD1hV25MGHwTfHGaoaehGD3iJ4lqNYi-ZiwReO6CVk,5842 +sympy/stats/tests/test_rv.py,sha256=Bp7UwffIMO7oc8UnFV11yYGcXUjSa0NhsuOgQaNRMt8,12959 +sympy/stats/tests/test_stochastic_process.py,sha256=i-VCOZrjpJtvyTBm9xgniTCkk_iUYIuFnkiyxzkn6Ig,39323 +sympy/stats/tests/test_symbolic_multivariate.py,sha256=G3AgbRbt0DQ-p0DYXYDjbx4e4f5FIgd31F34e0NO2n8,5580 +sympy/stats/tests/test_symbolic_probability.py,sha256=k5trScMiwSgl9dzJt30BV-t0KuYcyD-s9HtT2-hVhQ0,9398 +sympy/strategies/__init__.py,sha256=XaTAPqDoi6527juvR8LLN1mv6ZcslDrGloTTBMjJzxA,1402 +sympy/strategies/__pycache__/__init__.cpython-312.pyc,, +sympy/strategies/__pycache__/core.cpython-312.pyc,, +sympy/strategies/__pycache__/rl.cpython-312.pyc,, +sympy/strategies/__pycache__/tools.cpython-312.pyc,, +sympy/strategies/__pycache__/traverse.cpython-312.pyc,, +sympy/strategies/__pycache__/tree.cpython-312.pyc,, +sympy/strategies/__pycache__/util.cpython-312.pyc,, +sympy/strategies/branch/__init__.py,sha256=xxbMwR2LzLcQWsH9ss8ddE99VHFJTY-cYiR6xhO3tj0,356 +sympy/strategies/branch/__pycache__/__init__.cpython-312.pyc,, +sympy/strategies/branch/__pycache__/core.cpython-312.pyc,, +sympy/strategies/branch/__pycache__/tools.cpython-312.pyc,, +sympy/strategies/branch/__pycache__/traverse.cpython-312.pyc,, +sympy/strategies/branch/core.py,sha256=QiXSa7uhvmUBTLyUwBQHrYkWlOceKh5p4kVD90VnCKM,2759 +sympy/strategies/branch/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/strategies/branch/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/strategies/branch/tests/__pycache__/test_core.cpython-312.pyc,, +sympy/strategies/branch/tests/__pycache__/test_tools.cpython-312.pyc,, +sympy/strategies/branch/tests/__pycache__/test_traverse.cpython-312.pyc,, +sympy/strategies/branch/tests/test_core.py,sha256=23KQWJxC_2T1arwMAkt9pY1ZtG59avlxTZcVTn81UPI,2246 +sympy/strategies/branch/tests/test_tools.py,sha256=4BDkqVqrTlsivQ0PldQr6PjVZsAikc39tSxGAQA3ir8,942 +sympy/strategies/branch/tests/test_traverse.py,sha256=6rikMnZdamSzww1sSiM-aQwqa4lQrpM-DpOU9XCbiOQ,1322 +sympy/strategies/branch/tools.py,sha256=tvv3IjmQGNYbo-slCbbDf_rylZd537wvLcpdBtT-bbY,357 +sympy/strategies/branch/traverse.py,sha256=7iBViQdNpKu-AHoFED7_C9KBSyYcQBfLGopEJQbNtvk,799 +sympy/strategies/core.py,sha256=nsH6LZgyc_aslv4Na5XvJMEizC6uSzscRlVW91k1pu4,3956 +sympy/strategies/rl.py,sha256=-M5lfrtcREkvbW4YfoiB19wfYyMLKz6SmL887ymKeoI,4404 +sympy/strategies/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/strategies/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/strategies/tests/__pycache__/test_core.cpython-312.pyc,, +sympy/strategies/tests/__pycache__/test_rl.cpython-312.pyc,, +sympy/strategies/tests/__pycache__/test_tools.cpython-312.pyc,, +sympy/strategies/tests/__pycache__/test_traverse.cpython-312.pyc,, +sympy/strategies/tests/__pycache__/test_tree.cpython-312.pyc,, +sympy/strategies/tests/test_core.py,sha256=42XHlv1hN1S1QPEf2r9pddZ2EQL6o4FEPQvfo-UmXcw,2152 +sympy/strategies/tests/test_rl.py,sha256=wm0L6pdvddBgRcwhpiSk-nCgyzVGickfnOCkmHWS0j4,1949 +sympy/strategies/tests/test_tools.py,sha256=UdMojFIn3f1b2x2iRGv1Wfnwdso-Kl57GTyjCU_DjzQ,875 +sympy/strategies/tests/test_traverse.py,sha256=jWuZhYEt-F18_rxEMhn6OgGQ1GNs-dM_GFZ2F5nHs2I,2082 +sympy/strategies/tests/test_tree.py,sha256=9NL948rt6i9tYU6CQz9VNxE6l1begQs-MxP2euzE3Sc,2400 +sympy/strategies/tools.py,sha256=ERASzEP2SP-EcJ8p-4XyREYB15q3t81x1cyamJ-M880,1368 +sympy/strategies/traverse.py,sha256=DhPnBJ5Rw_xzhGiBtSciTyV-H2zhlxgjYVjrNH-gLyk,1183 +sympy/strategies/tree.py,sha256=ggnP9l3NIpJsssBMVKr4-yM_m8uCkrkm191ZC6MfZjc,3770 +sympy/strategies/util.py,sha256=2fbR813IY4IYco5mBoGJLu5z88OhXmwuIxgOO9IvZO4,361 +sympy/tensor/__init__.py,sha256=VMNXCRSayigQT6a3cvf5M_M-wdV-KSil_JbAmHcuUQc,870 +sympy/tensor/__pycache__/__init__.cpython-312.pyc,, +sympy/tensor/__pycache__/functions.cpython-312.pyc,, +sympy/tensor/__pycache__/index_methods.cpython-312.pyc,, +sympy/tensor/__pycache__/indexed.cpython-312.pyc,, +sympy/tensor/__pycache__/tensor.cpython-312.pyc,, +sympy/tensor/__pycache__/toperators.cpython-312.pyc,, +sympy/tensor/array/__init__.py,sha256=lTT1EwV5tb3WAvmmS_mIjhCSWSLiB0NNPW4n9_3fu0k,8244 +sympy/tensor/array/__pycache__/__init__.cpython-312.pyc,, +sympy/tensor/array/__pycache__/array_comprehension.cpython-312.pyc,, +sympy/tensor/array/__pycache__/array_derivatives.cpython-312.pyc,, +sympy/tensor/array/__pycache__/arrayop.cpython-312.pyc,, +sympy/tensor/array/__pycache__/dense_ndim_array.cpython-312.pyc,, +sympy/tensor/array/__pycache__/mutable_ndim_array.cpython-312.pyc,, +sympy/tensor/array/__pycache__/ndim_array.cpython-312.pyc,, +sympy/tensor/array/__pycache__/sparse_ndim_array.cpython-312.pyc,, +sympy/tensor/array/array_comprehension.py,sha256=01PTIbkAGaq0CDcaI_2KsaMnYm1nxQ8sFAiHHcc__gw,12262 +sympy/tensor/array/array_derivatives.py,sha256=c-gYeA_qpXOY3aexyz7psSqmTVIGVBrcGDvSkW5dZV0,4796 +sympy/tensor/array/arrayop.py,sha256=KvFGYWcYvChWkThtVAotlaSrcfjHogAxvpxWvp6dSgo,18397 +sympy/tensor/array/dense_ndim_array.py,sha256=Ie8qVMJyp2Tsq7aVhmZpPX8X-KTlF9uaxkQfTzCZ9z8,6433 +sympy/tensor/array/expressions/__init__.py,sha256=OUMJjZY7HtWJL0ygqkdWC8LdCqibJZhHCfYeXu-eB4E,7045 +sympy/tensor/array/expressions/__pycache__/__init__.cpython-312.pyc,, +sympy/tensor/array/expressions/__pycache__/array_expressions.cpython-312.pyc,, +sympy/tensor/array/expressions/__pycache__/arrayexpr_derivatives.cpython-312.pyc,, +sympy/tensor/array/expressions/__pycache__/conv_array_to_indexed.cpython-312.pyc,, +sympy/tensor/array/expressions/__pycache__/conv_array_to_matrix.cpython-312.pyc,, +sympy/tensor/array/expressions/__pycache__/conv_indexed_to_array.cpython-312.pyc,, +sympy/tensor/array/expressions/__pycache__/conv_matrix_to_array.cpython-312.pyc,, +sympy/tensor/array/expressions/__pycache__/from_array_to_indexed.cpython-312.pyc,, +sympy/tensor/array/expressions/__pycache__/from_array_to_matrix.cpython-312.pyc,, +sympy/tensor/array/expressions/__pycache__/from_indexed_to_array.cpython-312.pyc,, +sympy/tensor/array/expressions/__pycache__/from_matrix_to_array.cpython-312.pyc,, +sympy/tensor/array/expressions/__pycache__/utils.cpython-312.pyc,, +sympy/tensor/array/expressions/array_expressions.py,sha256=28TI8cwwQ4Q-QCI9X_j6X-lG0kR6amjAe9-h9JKb5EU,76961 +sympy/tensor/array/expressions/arrayexpr_derivatives.py,sha256=W9-bY2LL83lLSNHXItzqjOgvf-HIDbUXPoVw8uOymcg,6249 +sympy/tensor/array/expressions/conv_array_to_indexed.py,sha256=BIwlQr7RKC8bZN3mR8ICC5TYOC9uasYcV0Zc1VNKmiE,445 +sympy/tensor/array/expressions/conv_array_to_matrix.py,sha256=85YZBTZI4o9dJtKDJXXug_lJVLG8dT_22AT7l7DKoyE,416 +sympy/tensor/array/expressions/conv_indexed_to_array.py,sha256=EyW52TplBxIx25mUDvI_5Tzc8LD6Mnp6XNW9wIw9pH4,254 +sympy/tensor/array/expressions/conv_matrix_to_array.py,sha256=XYyqt0NsQSrgNpEkr8xTGeUhR7ZYeNljVFfVEF1K7vA,250 +sympy/tensor/array/expressions/from_array_to_indexed.py,sha256=3YIcsAzWVWQRJYQS90uPvSl2dM7ZqLV_qt7E9-uYU28,3936 +sympy/tensor/array/expressions/from_array_to_matrix.py,sha256=4HUbCfR2BHd54Ijws9DCcSs6aAJ-k8RwT195NTQImis,41435 +sympy/tensor/array/expressions/from_indexed_to_array.py,sha256=RUcKemmrwuK5RFRr19YSPVMCOkZfLAWlbbB56u8Wi0g,11187 +sympy/tensor/array/expressions/from_matrix_to_array.py,sha256=yIY1RupF9-FVV3jZLsqWxZ1ckoE1-HkQyM8cQIm4_Gs,3929 +sympy/tensor/array/expressions/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/tensor/array/expressions/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/tensor/array/expressions/tests/__pycache__/test_array_expressions.cpython-312.pyc,, +sympy/tensor/array/expressions/tests/__pycache__/test_arrayexpr_derivatives.cpython-312.pyc,, +sympy/tensor/array/expressions/tests/__pycache__/test_as_explicit.cpython-312.pyc,, +sympy/tensor/array/expressions/tests/__pycache__/test_convert_array_to_indexed.cpython-312.pyc,, +sympy/tensor/array/expressions/tests/__pycache__/test_convert_array_to_matrix.cpython-312.pyc,, +sympy/tensor/array/expressions/tests/__pycache__/test_convert_indexed_to_array.cpython-312.pyc,, +sympy/tensor/array/expressions/tests/__pycache__/test_convert_matrix_to_array.cpython-312.pyc,, +sympy/tensor/array/expressions/tests/__pycache__/test_deprecated_conv_modules.cpython-312.pyc,, +sympy/tensor/array/expressions/tests/test_array_expressions.py,sha256=QUAdxQ9TvBpDEAZoJpLSWwbqjmuflPe3xBRP30lFZr0,31262 +sympy/tensor/array/expressions/tests/test_arrayexpr_derivatives.py,sha256=lpC4ly6MJLDRBcVt3GcP3H6ke9bI-o3VULw0xyF5QbY,2470 +sympy/tensor/array/expressions/tests/test_as_explicit.py,sha256=nOjFKXCqYNu2O7Szc1TD1x1bsUchPRAG3nGlNGEd1Yg,2568 +sympy/tensor/array/expressions/tests/test_convert_array_to_indexed.py,sha256=6yNxGXH6BX5607FTjMkwR2t9wNVlEhV8JMSh4UIWux8,2500 +sympy/tensor/array/expressions/tests/test_convert_array_to_matrix.py,sha256=2vkSep9CPKYrQQS0u8Ayn_sc7yek1zwzjjCWK5cfYe8,29311 +sympy/tensor/array/expressions/tests/test_convert_indexed_to_array.py,sha256=RVEG_qUsXiBH9gHtWp2-9pMC4J2aLc4iUdzBFM0QyTw,8615 +sympy/tensor/array/expressions/tests/test_convert_matrix_to_array.py,sha256=G2g5E0l-FABwYyQowbKKvLcEI8NViJXaYLW3eUEcvjw,4595 +sympy/tensor/array/expressions/tests/test_deprecated_conv_modules.py,sha256=DG8IoUtxCy2acWjUHUUKu4bRsTxXbeFLFjKMLA2GdLY,1216 +sympy/tensor/array/expressions/utils.py,sha256=Rn58boHHUEoBZFtinDpruLWFBkNBwgkVQ4c9m7Nym1o,3939 +sympy/tensor/array/mutable_ndim_array.py,sha256=M0PTt8IOIcVXqQPWe2N50sm4Eq2bodRXV4Vkd08crXk,277 +sympy/tensor/array/ndim_array.py,sha256=bZvA21fSTMc2sQLJN4AovQspddzmnINBWFPr-TeGmm0,19138 +sympy/tensor/array/sparse_ndim_array.py,sha256=4nD_Hg-JdC_1mYQTohmKFfL5M1Ugdq0fpnDUILkTtq8,6387 +sympy/tensor/array/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/tensor/array/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/tensor/array/tests/__pycache__/test_array_comprehension.cpython-312.pyc,, +sympy/tensor/array/tests/__pycache__/test_array_derivatives.cpython-312.pyc,, +sympy/tensor/array/tests/__pycache__/test_arrayop.cpython-312.pyc,, +sympy/tensor/array/tests/__pycache__/test_immutable_ndim_array.cpython-312.pyc,, +sympy/tensor/array/tests/__pycache__/test_mutable_ndim_array.cpython-312.pyc,, +sympy/tensor/array/tests/__pycache__/test_ndim_array.cpython-312.pyc,, +sympy/tensor/array/tests/__pycache__/test_ndim_array_conversions.cpython-312.pyc,, +sympy/tensor/array/tests/test_array_comprehension.py,sha256=e8MsWbvwmr-HxTfaM7i8HoIVofa8InLzF9PTCIVvzjU,4529 +sympy/tensor/array/tests/test_array_derivatives.py,sha256=hS10Bkb3F2kWoFoxk2ucr21p0r5DfwHDYPI8HcmAl0o,1601 +sympy/tensor/array/tests/test_arrayop.py,sha256=WahGcUnArsAo9eaMqGT7_AjKons0WgFzLOWTtNvnSEI,25844 +sympy/tensor/array/tests/test_immutable_ndim_array.py,sha256=9ji_14szn-qoL6DQ5muzIFNaXefT7n55PFigXoFwk50,15823 +sympy/tensor/array/tests/test_mutable_ndim_array.py,sha256=rFFa0o0AJYgPNnpqijl91Vb9EW2kgHGQc6cu9f1fIvY,13070 +sympy/tensor/array/tests/test_ndim_array.py,sha256=KH-9LAME3ldVIu5n7Vd_Xr36dN4frCdiF9qZdBWETu0,2232 +sympy/tensor/array/tests/test_ndim_array_conversions.py,sha256=CUGDCbCcslACy3Ngq-zoig9JnO4yHTw3IPcKy0FnRpw,648 +sympy/tensor/functions.py,sha256=FNZ2M0HGVaASJ_1AkPu1vF5NHNLmBXKLsj0Q5wKMX90,4168 +sympy/tensor/index_methods.py,sha256=dcX9kNKLHi_XXkFHBPS-fcM-PaeYKkX80jmzxC0siiQ,15434 +sympy/tensor/indexed.py,sha256=3qiQehMvXSDbr_RDXg6l_aEu6dHZXEfXrMoXCJj7Cqo,24515 +sympy/tensor/tensor.py,sha256=EQ9qJjtvij4gG101jB1eOuTtaSmvm1Da3IHVCBn1Flo,181094 +sympy/tensor/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/tensor/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/tensor/tests/__pycache__/test_functions.cpython-312.pyc,, +sympy/tensor/tests/__pycache__/test_index_methods.cpython-312.pyc,, +sympy/tensor/tests/__pycache__/test_indexed.cpython-312.pyc,, +sympy/tensor/tests/__pycache__/test_printing.cpython-312.pyc,, +sympy/tensor/tests/__pycache__/test_tensor.cpython-312.pyc,, +sympy/tensor/tests/__pycache__/test_tensor_element.cpython-312.pyc,, +sympy/tensor/tests/__pycache__/test_tensor_operators.cpython-312.pyc,, +sympy/tensor/tests/test_functions.py,sha256=rBBHjJIUA2oR83UgEJ_GIASDWfTZXDzOllmcO90XYDU,1552 +sympy/tensor/tests/test_index_methods.py,sha256=Pu951z4yYYMOXBKcNteH63hTAxmNX8702nSQH_pciFE,7112 +sympy/tensor/tests/test_indexed.py,sha256=EB2-t0gYkaTOvrCkhyW2cEL_MVi4xBUZxbf35NA-puI,16376 +sympy/tensor/tests/test_printing.py,sha256=sUx_rChNTWFKPNwVl296QXO-d4-yemDJnkEHFislsmc,424 +sympy/tensor/tests/test_tensor.py,sha256=XQiLkOtyLLFKX_lWEqpCr2lXxQ6LK_hShj0rz7RrWpk,81236 +sympy/tensor/tests/test_tensor_element.py,sha256=1dF96FtqUGaJzethw23vJIj3H5KdxsU1Xyd4DU54EB4,908 +sympy/tensor/tests/test_tensor_operators.py,sha256=n4md5Dv7QoVSMR4cHbkEKSFDxgTTpEyxMiCAqoqyJyk,17966 +sympy/tensor/toperators.py,sha256=fniTUpdYz0OvtNnFgrHINedX86FxVcxfKj9l_l1p9Rw,8840 +sympy/testing/__init__.py,sha256=IN9aHvoksdZywonAYE0cExFnuPQs9z1E4P742aYZNnE,169 +sympy/testing/__pycache__/__init__.cpython-312.pyc,, +sympy/testing/__pycache__/matrices.cpython-312.pyc,, +sympy/testing/__pycache__/pytest.cpython-312.pyc,, +sympy/testing/__pycache__/quality_unicode.cpython-312.pyc,, +sympy/testing/__pycache__/randtest.cpython-312.pyc,, +sympy/testing/__pycache__/runtests.cpython-312.pyc,, +sympy/testing/__pycache__/runtests_pytest.cpython-312.pyc,, +sympy/testing/__pycache__/tmpfiles.cpython-312.pyc,, +sympy/testing/matrices.py,sha256=VWBPdjIUYNHE7fdbYcmQwQTYcIWpOP9tFn9A0rGCBmE,216 +sympy/testing/pytest.py,sha256=xiKL67rD4sKYVZ1Xqci4arPJQzrm3xWfg-m6I7eWNBM,13363 +sympy/testing/quality_unicode.py,sha256=quKFUpEUPftVGNpsj71WpRoeKZUzc8sgLjODRmHPf-w,3482 +sympy/testing/randtest.py,sha256=IKDFAm8b72Z1OkT7vpgnZjaW5LsSU_wf6g35sCkq9I0,562 +sympy/testing/runtests.py,sha256=dD9_0xtvG0wMgQtdvxDi7ePc2CL2ybNRqHKgHjJomzE,89921 +sympy/testing/runtests_pytest.py,sha256=KSqhzaRis7sx2AwctWsP6VjCbDcg6C5UCApp_LUNRuc,17801 +sympy/testing/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/testing/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/testing/tests/__pycache__/diagnose_imports.cpython-312.pyc,, +sympy/testing/tests/__pycache__/test_code_quality.cpython-312.pyc,, +sympy/testing/tests/__pycache__/test_deprecated.cpython-312.pyc,, +sympy/testing/tests/__pycache__/test_module_imports.cpython-312.pyc,, +sympy/testing/tests/__pycache__/test_pytest.cpython-312.pyc,, +sympy/testing/tests/__pycache__/test_runtests_pytest.cpython-312.pyc,, +sympy/testing/tests/diagnose_imports.py,sha256=VQAc0WLHgQgksu6kcQLmEVW4O98v7YgjLMzCLNZ6JfE,9508 +sympy/testing/tests/test_code_quality.py,sha256=Yzb1CAIAGTO29Ay2fsPn0-OqstAoy9FMiAMIed6iVZE,19214 +sympy/testing/tests/test_deprecated.py,sha256=wQZHs4wDNuK4flaKKLsJW6XRMtrVjMv_5rUP3WspgPA,183 +sympy/testing/tests/test_module_imports.py,sha256=5w6F6JW6K7lgpbB4X9Tj0Vw8AcNVlfaSuvbwKXJKD6c,1459 +sympy/testing/tests/test_pytest.py,sha256=iKO10Tvua1Xem6a22IWH4SDrpFfr-bM-rXx039Ua7YA,6778 +sympy/testing/tests/test_runtests_pytest.py,sha256=C4bo-SOx8BsxvT4M_0OPUiwSEXShaMqpYRoedMmbR1g,6083 +sympy/testing/tmpfiles.py,sha256=bF8ktKC9lDhS65gahB9hOewsZ378UkhLgq3QHiqWYXU,1042 +sympy/this.py,sha256=XfOkN5EIM2RuDxSm_q6k_R_WtkIoSy6PXWKp3aAXvoc,550 +sympy/unify/__init__.py,sha256=Upa9h7SSr9W1PXo0WkNESsGsMZ85rcWkeruBtkAi3Fg,293 +sympy/unify/__pycache__/__init__.cpython-312.pyc,, +sympy/unify/__pycache__/core.cpython-312.pyc,, +sympy/unify/__pycache__/rewrite.cpython-312.pyc,, +sympy/unify/__pycache__/usympy.cpython-312.pyc,, +sympy/unify/core.py,sha256=-BCNPPMdfZuhhIWqyn9pYJoO8yFPGDX78Hn2551ABuE,7037 +sympy/unify/rewrite.py,sha256=Emr8Uoum3gxKpMDqFHJIjx3xChArUIN6XIy6NPfCS8I,1798 +sympy/unify/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/unify/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/unify/tests/__pycache__/test_rewrite.cpython-312.pyc,, +sympy/unify/tests/__pycache__/test_sympy.cpython-312.pyc,, +sympy/unify/tests/__pycache__/test_unify.cpython-312.pyc,, +sympy/unify/tests/test_rewrite.py,sha256=BgA8zmdz9Nw-Xbu4-w3UABeWypqLvmy9VzL744EmYtE,2002 +sympy/unify/tests/test_sympy.py,sha256=UCItZJNAx9dG5F7O27pyXUF1-e6aOwkZ-cVdB6SZFZc,5922 +sympy/unify/tests/test_unify.py,sha256=4TlgchV6NWuBekJx9RGlMjx3-UwonzgIYXDytb7sBRU,3029 +sympy/unify/usympy.py,sha256=6Kxx96FXSdqXimLseVK_FkYwy2vqWhNnxMVPMRShvy4,3964 +sympy/utilities/__init__.py,sha256=nbQhzII8dw5zd4hQJ2SUyriK5dOrqf-bbjy10XKQXPw,840 +sympy/utilities/__pycache__/__init__.cpython-312.pyc,, +sympy/utilities/__pycache__/autowrap.cpython-312.pyc,, +sympy/utilities/__pycache__/codegen.cpython-312.pyc,, +sympy/utilities/__pycache__/decorator.cpython-312.pyc,, +sympy/utilities/__pycache__/enumerative.cpython-312.pyc,, +sympy/utilities/__pycache__/exceptions.cpython-312.pyc,, +sympy/utilities/__pycache__/iterables.cpython-312.pyc,, +sympy/utilities/__pycache__/lambdify.cpython-312.pyc,, +sympy/utilities/__pycache__/magic.cpython-312.pyc,, +sympy/utilities/__pycache__/matchpy_connector.cpython-312.pyc,, +sympy/utilities/__pycache__/memoization.cpython-312.pyc,, +sympy/utilities/__pycache__/misc.cpython-312.pyc,, +sympy/utilities/__pycache__/pkgdata.cpython-312.pyc,, +sympy/utilities/__pycache__/pytest.cpython-312.pyc,, +sympy/utilities/__pycache__/randtest.cpython-312.pyc,, +sympy/utilities/__pycache__/runtests.cpython-312.pyc,, +sympy/utilities/__pycache__/source.cpython-312.pyc,, +sympy/utilities/__pycache__/timeutils.cpython-312.pyc,, +sympy/utilities/__pycache__/tmpfiles.cpython-312.pyc,, +sympy/utilities/_compilation/__init__.py,sha256=uYUDPbwrMTbGEMVuago32EN_ix8fsi5M0SvcLOtwMOk,751 +sympy/utilities/_compilation/__pycache__/__init__.cpython-312.pyc,, +sympy/utilities/_compilation/__pycache__/availability.cpython-312.pyc,, +sympy/utilities/_compilation/__pycache__/compilation.cpython-312.pyc,, +sympy/utilities/_compilation/__pycache__/runners.cpython-312.pyc,, +sympy/utilities/_compilation/__pycache__/util.cpython-312.pyc,, +sympy/utilities/_compilation/availability.py,sha256=ybxp3mboH5772JHTWKBN1D-cs6QxATQiaL4zJVV4RE0,2884 +sympy/utilities/_compilation/compilation.py,sha256=qkfDtSgSeRJ-97E5hN1asUqoDXS4nnNgYoHCA8WAmHA,22156 +sympy/utilities/_compilation/runners.py,sha256=KAinYF0m55dRdDFO5pvHBlvTxDY0ldoImqTOwX7VmL4,10237 +sympy/utilities/_compilation/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/utilities/_compilation/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/utilities/_compilation/tests/__pycache__/test_compilation.cpython-312.pyc,, +sympy/utilities/_compilation/tests/test_compilation.py,sha256=DmdxCPlWaqgtNZPWzMVPwqRuqqJcgWBWxXfOEMZ21D0,3189 +sympy/utilities/_compilation/util.py,sha256=otSIKhM5YSYzbUNYycagG2xSj6owlQVrwIVl0rv7Owc,8611 +sympy/utilities/autowrap.py,sha256=l8noWRKmA-B814S92RK3O64YWAkARnMfqY1AQqi2S8g,42561 +sympy/utilities/codegen.py,sha256=1ieFSlxGgd9utMSPzN5NraTfoSSzlUM9V_BnGYMuMc8,81670 +sympy/utilities/decorator.py,sha256=NaZBNCDdMhG4_3esEOLZCbVQcjltvi3lrMIRCqewfR4,11184 +sympy/utilities/enumerative.py,sha256=ah4Td5KhqGdPR7EQHcUDOsYLDH64Sh2z6xm5gDpJSFg,43585 +sympy/utilities/exceptions.py,sha256=RoKY7jDIq6OsZbNSCyneWbVQb1Cw2MtOuioJlCKmBec,10570 +sympy/utilities/iterables.py,sha256=noIMRQmdSPfbg1LorRPHreozS265u4IHUmDkOvMB2po,91103 +sympy/utilities/lambdify.py,sha256=lepieExI19QvZYPrGl_WZaFwta8YZBo6AgxDnwq01ow,57816 +sympy/utilities/magic.py,sha256=ofrwi1-xwMWb4VCQOEIwe4J1QAwxOscigDq26uSn3iY,400 +sympy/utilities/matchpy_connector.py,sha256=7dSDOPbN5Y_XW6bIGVNK3dJ-gVdTB_liJ8O5rIqd28c,11948 +sympy/utilities/mathml/__init__.py,sha256=74VhxNJlvCZTm2Jh3t69N8QZRklTQjqMvqFMLVwCKQk,3388 +sympy/utilities/mathml/__pycache__/__init__.cpython-312.pyc,, +sympy/utilities/mathml/data/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/utilities/mathml/data/__pycache__/__init__.cpython-312.pyc,, +sympy/utilities/mathml/data/mmlctop.xsl,sha256=fi3CTNyg-mSscOGYBXLJv8veE_ItR_YTFMJ4jmjp6aE,114444 +sympy/utilities/mathml/data/mmltex.xsl,sha256=haX7emZOfD6_nbn5BjK93F-C85mSS8KogAbIBsW1aBA,137304 +sympy/utilities/mathml/data/simple_mmlctop.xsl,sha256=OM-Vge1satH-MAYwWhraeXcorn1KGtuqBK-PDddaOrk,114433 +sympy/utilities/memoization.py,sha256=jD6RjVMZkGpNZYaJ9481vTiqvmwyu1IKDpsF5PYIvf4,1838 +sympy/utilities/misc.py,sha256=C6C3Em9YUjqg4gUhVdu97K0Wt_gRxuhNHS0TW6MlrxQ,16000 +sympy/utilities/pkgdata.py,sha256=BiBonyObCsS6EnLUII_1kDtchDN7Tur0T4GMzoUo06M,935 +sympy/utilities/pytest.py,sha256=ifo5fkOQ94HKXjy_U__mLFSohNRGP2ft8Z4P5gAi4yw,440 +sympy/utilities/randtest.py,sha256=Qlr4MMe0ade6jUH6pIEE0-v4g4qGswJhKpdaQFS_GDw,435 +sympy/utilities/runtests.py,sha256=Js3GGuzxQDZw5Tr5Kge0DCYx9gi3eya4DZxfwib6e3Y,451 +sympy/utilities/source.py,sha256=ShIXRNtplSEfZNi5VDYD3yi6305eRz4TmchEOEvcicw,1127 +sympy/utilities/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/utilities/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/utilities/tests/__pycache__/test_autowrap.cpython-312.pyc,, +sympy/utilities/tests/__pycache__/test_codegen.cpython-312.pyc,, +sympy/utilities/tests/__pycache__/test_codegen_julia.cpython-312.pyc,, +sympy/utilities/tests/__pycache__/test_codegen_octave.cpython-312.pyc,, +sympy/utilities/tests/__pycache__/test_codegen_rust.cpython-312.pyc,, +sympy/utilities/tests/__pycache__/test_decorator.cpython-312.pyc,, +sympy/utilities/tests/__pycache__/test_deprecated.cpython-312.pyc,, +sympy/utilities/tests/__pycache__/test_enumerative.cpython-312.pyc,, +sympy/utilities/tests/__pycache__/test_exceptions.cpython-312.pyc,, +sympy/utilities/tests/__pycache__/test_iterables.cpython-312.pyc,, +sympy/utilities/tests/__pycache__/test_lambdify.cpython-312.pyc,, +sympy/utilities/tests/__pycache__/test_matchpy_connector.cpython-312.pyc,, +sympy/utilities/tests/__pycache__/test_mathml.cpython-312.pyc,, +sympy/utilities/tests/__pycache__/test_misc.cpython-312.pyc,, +sympy/utilities/tests/__pycache__/test_pickling.cpython-312.pyc,, +sympy/utilities/tests/__pycache__/test_source.cpython-312.pyc,, +sympy/utilities/tests/__pycache__/test_timeutils.cpython-312.pyc,, +sympy/utilities/tests/__pycache__/test_wester.cpython-312.pyc,, +sympy/utilities/tests/__pycache__/test_xxe.cpython-312.pyc,, +sympy/utilities/tests/test_autowrap.py,sha256=PA6zaRVrIWyQHq6bGKezqNB6YWTfcnnB9VH2vzaEfaQ,14865 +sympy/utilities/tests/test_codegen.py,sha256=pjfhZTa5LI9gdrakDfLtBBrIxgWjWORR_NBDW9J8Cq8,56130 +sympy/utilities/tests/test_codegen_julia.py,sha256=QYqSluVhmxq_BAagEKBb6eJIseFFAweMjpuLgNPMUWI,18540 +sympy/utilities/tests/test_codegen_octave.py,sha256=GUQIj6YjsMsj8ZLmVngWa9ovoyqfwvikWXdeS7m_c7I,17830 +sympy/utilities/tests/test_codegen_rust.py,sha256=seq9o51dsa09MmcqwKRkGiurbWLs1uAIjaz7xGOKNE4,12326 +sympy/utilities/tests/test_decorator.py,sha256=VYUvzUrVI7I7MK0YZxLLEmEu4pV5dqaB1CLEJ8Ocav4,3705 +sympy/utilities/tests/test_deprecated.py,sha256=LRrZ2UxuXnK6Jwxl8vT0EdLT-q-7jLkTC69U9JjuYYU,489 +sympy/utilities/tests/test_enumerative.py,sha256=nw-1r0MgxbzYkScmxv7HUAIAQycg8pUVOH_slDRLg7E,6097 +sympy/utilities/tests/test_exceptions.py,sha256=OKRa2yuHMtnVcnisu-xcaedi2RKsH9QrgU9exgoOK30,716 +sympy/utilities/tests/test_iterables.py,sha256=xYWyoDtVkYfnIOdA-5yUYZsxo4iTsExaNpVmjMuwpTc,35288 +sympy/utilities/tests/test_lambdify.py,sha256=emTSDwHdGprENO3ugK86k1L6m8Y3IamPj1oUNIKaYrQ,73531 +sympy/utilities/tests/test_matchpy_connector.py,sha256=mBrAev2Hxe4jg_1ny3ZaGIfh2xvWbr6BDRVjB9owJFM,4850 +sympy/utilities/tests/test_mathml.py,sha256=-6z1MRYEH4eYQi2_wt8zmdjwtt5Cn483zqsvD-o_r70,836 +sympy/utilities/tests/test_misc.py,sha256=xZh6ux9o2iZpWvfX_ivp4lD3WgJVeP5k6ipppNGHDsw,4643 +sympy/utilities/tests/test_pickling.py,sha256=ZXGzB_gQ9juws_N_n2vf6QPVojdfP4Mbl7uqdtkPb0E,23600 +sympy/utilities/tests/test_source.py,sha256=ObjrJxZFVhLgXjVmFHUy7bti9UPPgOh5Cptw8lHW9mM,289 +sympy/utilities/tests/test_timeutils.py,sha256=sCRC6BCSho1e9n4clke3QXHx4a3qYLru-bddS_sEmFA,337 +sympy/utilities/tests/test_wester.py,sha256=S79UNsGhEW5z6hDriQB8OY_Vhaz1j0Q7yv31HynyDfk,94866 +sympy/utilities/tests/test_xxe.py,sha256=xk1j0Dd96wsGYKRNDzXTW0hTQejGCfiZcEhYcYiqojg,66 +sympy/utilities/timeutils.py,sha256=PNHyvuEM66UEXLF8ye6PMilcEDK75B9wab3ai8a9cyo,1941 +sympy/utilities/tmpfiles.py,sha256=tQP3g7LTrnXTGqUgGNoIZtjug6O6lq6EYLrKPJcUGEU,450 +sympy/vector/__init__.py,sha256=bgKutVqUPWuvHWBpiEm6XWE6iGfAPJw3pt19NRn2n10,1969 +sympy/vector/__pycache__/__init__.cpython-312.pyc,, +sympy/vector/__pycache__/basisdependent.cpython-312.pyc,, +sympy/vector/__pycache__/coordsysrect.cpython-312.pyc,, +sympy/vector/__pycache__/deloperator.cpython-312.pyc,, +sympy/vector/__pycache__/dyadic.cpython-312.pyc,, +sympy/vector/__pycache__/functions.cpython-312.pyc,, +sympy/vector/__pycache__/implicitregion.cpython-312.pyc,, +sympy/vector/__pycache__/integrals.cpython-312.pyc,, +sympy/vector/__pycache__/kind.cpython-312.pyc,, +sympy/vector/__pycache__/operators.cpython-312.pyc,, +sympy/vector/__pycache__/orienters.cpython-312.pyc,, +sympy/vector/__pycache__/parametricregion.cpython-312.pyc,, +sympy/vector/__pycache__/point.cpython-312.pyc,, +sympy/vector/__pycache__/scalar.cpython-312.pyc,, +sympy/vector/__pycache__/vector.cpython-312.pyc,, +sympy/vector/basisdependent.py,sha256=P7LogUck6NWjEzAOH3dYr4A8M5QCOPaCW75lmiQpBqU,11857 +sympy/vector/coordsysrect.py,sha256=0BKdr8AG8BUJnShIIyyCvkU5OVdjtZsKcBuGgdbvdHw,36833 +sympy/vector/deloperator.py,sha256=4BJNjmI342HkVRmeQkqauqvibKsf2HOuzknQTfQMkpg,3191 +sympy/vector/dyadic.py,sha256=IOyrgONyGDHPtG0RINcMgetAVMSOmYI5a99s-OwXBTA,8571 +sympy/vector/functions.py,sha256=rmEBaV0XpZLkCPcJFojHS9CNHirV55v5sDwNqTPwqGM,15454 +sympy/vector/implicitregion.py,sha256=4-M_-shL4EJ9nfjAZ_xg00IXZVQghcCZ3bv8QGbkopI,16158 +sympy/vector/integrals.py,sha256=x8DrvKXPznE05JgnZ7I3IWLWrvFl9SEghGaFmHrBaE4,6837 +sympy/vector/kind.py,sha256=U6qxciZY7-ACzBSpGM0iSTI5tqflpPBvm4_J9ujyxyE,1812 +sympy/vector/operators.py,sha256=dNC7mNXZb3KxX5GyjFNDTLTkzSnYjOohZtBXuQ1keZE,9579 +sympy/vector/orienters.py,sha256=EtWNWfOvAuy_wipam9SA7_muKSrsP-43UPRCCz56sb0,11798 +sympy/vector/parametricregion.py,sha256=gAarunY8q3D8WVvryZEbJQ4g-nlXo4FnO-CbyEpVUXc,5932 +sympy/vector/point.py,sha256=-JFOibsQclOKC2m2qZRiGGB4oK9ieVZRd2ll5g4k3bE,4488 +sympy/vector/scalar.py,sha256=WAb25BC0TEOZ-_bEtL1gdySuM1adJzK47kJYTrC4Y4w,2024 +sympy/vector/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +sympy/vector/tests/__pycache__/__init__.cpython-312.pyc,, +sympy/vector/tests/__pycache__/test_coordsysrect.cpython-312.pyc,, +sympy/vector/tests/__pycache__/test_dyadic.cpython-312.pyc,, +sympy/vector/tests/__pycache__/test_field_functions.cpython-312.pyc,, +sympy/vector/tests/__pycache__/test_functions.cpython-312.pyc,, +sympy/vector/tests/__pycache__/test_implicitregion.cpython-312.pyc,, +sympy/vector/tests/__pycache__/test_integrals.cpython-312.pyc,, +sympy/vector/tests/__pycache__/test_operators.cpython-312.pyc,, +sympy/vector/tests/__pycache__/test_parametricregion.cpython-312.pyc,, +sympy/vector/tests/__pycache__/test_printing.cpython-312.pyc,, +sympy/vector/tests/__pycache__/test_vector.cpython-312.pyc,, +sympy/vector/tests/test_coordsysrect.py,sha256=q9n9OIG_CpD4KQN20dzwRZIXoMv7VSgp8fHmVnkZfr0,19595 +sympy/vector/tests/test_dyadic.py,sha256=f1R-BL_63VBbc0XgEX_LYzV_3OupYd4hp5RzRk6dAbI,4949 +sympy/vector/tests/test_field_functions.py,sha256=v9l8Ex8K2MsPGxqAPhpEgu6WAo6wS6qvdWLKQMxgE4A,14094 +sympy/vector/tests/test_functions.py,sha256=Bs2sekdDJyw_wrUpG7vZQGH0y0S4C4AbxGSpeU_8C2s,8050 +sympy/vector/tests/test_implicitregion.py,sha256=wVilD5H-MhHiW58QT6P5U7uT79JdKHm9D7JgZoi6BE4,4028 +sympy/vector/tests/test_integrals.py,sha256=iDq3Wpr8I8EXAGkXqMpA-P9i1zEnV7lU8WR6xBOhEK0,5087 +sympy/vector/tests/test_operators.py,sha256=KexUWvc_Nwp2HWrEbhxiO7MeaFxYlckrp__Tkwg-wmU,1613 +sympy/vector/tests/test_parametricregion.py,sha256=OfKapF9A_g9X6JxgYc0UfxIhwXzRERzaj-EijQCJONw,4009 +sympy/vector/tests/test_printing.py,sha256=3BeW55iQ4qXdfDTFqptE2ufJPJIBOzdfIYVx84n_EwA,7708 +sympy/vector/tests/test_vector.py,sha256=rJpMlUWiezrY6drHUNdJc8_FDYMwGCG4lBy8zS4XSZk,10238 +sympy/vector/vector.py,sha256=aOSfyfRvkatzWHWuulY6n0_iqElI5mntAUjNPptpBiM,20322 diff --git a/.venv/lib/python3.12/site-packages/sympy-1.14.0.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/sympy-1.14.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..8acb95590701b87bf84eec079cf4e3989f63b098 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy-1.14.0.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/.venv/lib/python3.12/site-packages/sympy-1.14.0.dist-info/entry_points.txt b/.venv/lib/python3.12/site-packages/sympy-1.14.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..42a12f960335556fcee728e5754c346447d4e89c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy-1.14.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +isympy = isympy:main diff --git a/.venv/lib/python3.12/site-packages/sympy-1.14.0.dist-info/licenses/AUTHORS b/.venv/lib/python3.12/site-packages/sympy-1.14.0.dist-info/licenses/AUTHORS new file mode 100644 index 0000000000000000000000000000000000000000..1062f3bf743c0a37bcde05b1afc1ba5e98a95822 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy-1.14.0.dist-info/licenses/AUTHORS @@ -0,0 +1,1379 @@ +All people who contributed to SymPy by sending at least a patch or +more (in the order of the date of their first contribution), except +those who explicitly didn't want to be mentioned. People with a * next +to their names are not found in the metadata of the git history. This +file is generated automatically by running `./bin/authors_update.py`. + +There are a total of 1371 authors. + +Ondřej Čertík +Fabian Pedregosa +Jurjen N.E. Bos +Mateusz Paprocki +*Marc-Etienne M.Leveille +Brian Jorgensen +Jason Gedge +Robert Schwarz +Pearu Peterson +Fredrik Johansson +Chris Wu +*Ulrich Hecht +Goutham Lakshminarayan +David Lawrence +Jaroslaw Tworek +David Marek +Bernhard R. Link +Andrej Tokarčík +Or Dvory +Saroj Adhikari +Pauli Virtanen +Robert Kern +James Aspnes +Nimish Telang +Abderrahim Kitouni +Pan Peng +Friedrich Hagedorn +Elrond der Elbenfuerst +Rizgar Mella +Felix Kaiser +Roberto Nobrega +David Roberts +Sebastian Krämer +Vinzent Steinberg +Riccardo Gori +Case Van Horsen +Stepan Roucka +Ali Raza Syed +Stefano Maggiolo +Robert Cimrman +Bastian Weber +Sebastian Krause +Sebastian Kreft +*Dan +Alan Bromborsky +Boris Timokhin +Robert +Andy R. Terrel +Hubert Tsang +Konrad Meyer +Henrik Johansson +Priit Laes +Freddie Witherden +Brian E. Granger +Andrew Straw +Kaifeng Zhu +Ted Horst +Andrew Docherty +Akshay Srinivasan +Aaron Meurer +Barry Wardell +Tomasz Buchert +Vinay Kumar +Johann Cohen-Tanugi +Jochen Voss +Luke Peterson +Chris Smith +Thomas Sidoti +Florian Mickler +Nicolas Pourcelot +Ben Goodrich +Toon Verstraelen +Ronan Lamy +James Abbatiello +Ryan Krauss +Bill Flynn +Kevin Goodsell +Jorn Baayen +Eh Tan +Renato Coutinho +Oscar Benjamin +Øyvind Jensen +Julio Idichekop Filho +Łukasz Pankowski +*Chu-Ching Huang +Fernando Perez +Raffaele De Feo +Christian Muise +Matt Curry +Kazuo Thow +Christian Schubert +Jezreel Ng +James Pearson +Matthew Brett +Addison Cugini +Nicholas J.S. Kinar +Harold Erbin +Thomas Dixon +Cristóvão Sousa +Andre de Fortier Smit +Mark Dewing +Alexey U. Gudchenko +Gary Kerr +Sherjil Ozair +Oleksandr Gituliar +Sean Vig +Prafullkumar P. Tale +Vladimir Perić +Tom Bachmann +Yuri Karadzhov +Vladimir Lagunov +Matthew Rocklin +Saptarshi Mandal +Gilbert Gede +Anatolii Koval +Tomo Lazovich +Pavel Fedotov +Jack McCaffery +Jeremias Yehdegho +Kibeom Kim +Gregory Ksionda +Tomáš Bambas +Raymond Wong +Luca Weihs +Shai 'Deshe' Wyborski +Thomas Wiecki +Óscar Nájera +Mario Pernici +Benjamin McDonald +Sam Magura +Stefan Krastanov +Bradley Froehle +Min Ragan-Kelley +Emma Hogan +Nikhil Sarda +Julien Rioux +Roberto Colistete, Jr. +Raoul Bourquin +Gert-Ludwig Ingold +Srinivas Vasudevan +Jason Moore +Miha Marolt +Tim Lahey +Luis Garcia +Matt Rajca +David Li +Alexandr Gudulin +Bilal Akhtar +Grzegorz Świrski +Matt Habel +David Ju +Nichita Utiu +Nikolay Lazarov +Steve Anton +Imran Ahmed Manzoor +Ljubiša Moćić <3rdslasher@gmail.com> +Piotr Korgul +Jim Zhang +Sam Sleight +tborisova +Chancellor Arkantos +Stepan Simsa +Tobias Lenz +Siddhanathan Shanmugam +Tiffany Zhu +Tristan Hume +Alexey Subach +Joan Creus +Geoffry Song +Puneeth Chaganti +Marcin Kostrzewa <> +Natalia Nawara +vishal +Shruti Mangipudi +Davy Mao +Swapnil Agarwal +Dhia Kennouche +jerryma1121 +Joachim Durchholz +Martin Povišer +Siddhant Jain +Kevin Hunter +Michael Mayorov +Nathan Alison +Christian Bühler +Carsten Knoll +Bharath M R +Matthias Toews +Sergiu Ivanov +Jorge E. Cardona +Sanket Agarwal +Manoj Babu K. +Sai Nikhil +Aleksandar Makelov +Sachin Irukula +Raphael Michel +Ashwini Oruganti +Andreas Klöckner +Prateek Papriwal +Arpit Goyal +Angadh Nanjangud +Comer Duncan +Jens H. Nielsen +Joseph Dougherty +Elliot Marshall +Guru Devanla +George Waksman +Alexandr Popov +Tarun Gaba +Takafumi Arakaki +Saurabh Jha +Rom le Clair +Angus Griffith <16sn6uv@gmail.com> +Timothy Reluga +Brian Stephanik +Alexander Eberspächer +Sachin Joglekar +Tyler Pirtle +Vasily Povalyaev +Colleen Lee +Matthew Hoff +Niklas Thörne +Huijun Mai +Marek Šuppa +Ramana Venkata +Prasoon Shukla +Stefen Yin +Thomas Hisch +Madeleine Ball +Mary Clark +Rishabh Dixit +Manoj Kumar +Akshit Agarwal +CJ Carey +Patrick Lacasse +Ananya H +Tarang Patel +Christopher Dembia +Benjamin Fishbein +Sean Ge +Amit Jamadagni +Ankit Agrawal +Björn Dahlgren +Christophe Saint-Jean +Demian Wassermann +Khagesh Patel +Stephen Loo +hm +Patrick Poitras +Katja Sophie Hotz +Varun Joshi +Chetna Gupta +Thilina Rathnayake +Max Hutchinson +Shravas K Rao +Matthew Tadd +Alexander Hirzel +Randy Heydon +Oliver Lee +Seshagiri Prabhu +Pradyumna +Erik Welch +Eric Nelson +Roland Puntaier +Chris Conley +Tim Swast +Dmitry Batkovich +Francesco Bonazzi +Yuriy Demidov +Rick Muller +Manish Gill +Markus Müller +Amit Saha +Jeremy +QuaBoo +Stefan van der Walt +David Joyner +Lars Buitinck +Alkiviadis G. Akritas +Vinit Ravishankar +Michael Boyle +Heiner Kirchhoffer +Pablo Puente +James Fiedler +Harsh Gupta +Tuomas Airaksinen +Paul Strickland +James Goppert +rathmann +Avichal Dayal +Paul Scott +Shipra Banga +Pramod Ch +Akshay +Buck Shlegeris +Jonathan Miller +Edward Schembor +Rajath Shashidhara +Zamrath Nizam +Aditya Shah +Rajat Aggarwal +Sambuddha Basu +Zeel Shah +Abhinav Chanda +Jim Crist +Sudhanshu Mishra +Anurag Sharma +Soumya Dipta Biswas +Sushant Hiray +Ben Lucato +Kunal Arora +Henry Gebhardt +Dammina Sahabandu +Manish Shukla +Ralph Bean +richierichrawr +John Connor +Juan Luis Cano Rodríguez +Sahil Shekhawat +Kundan Kumar +Stas Kelvich +sevaader +Dhruvesh Vijay Parikh +Venkatesh Halli +Lennart Fricke +Vlad Seghete +Shashank Agarwal +carstimon +Pierre Haessig +Maciej Baranski +Benjamin Gudehus +Faisal Anees +Mark Shoulson +Robert Johansson +Kalevi Suominen +Kaushik Varanasi +Fawaz Alazemi +Ambar Mehrotra +David P. Sanders +Peter Brady +John V. Siratt +Sarwar Chahal +Nathan Woods +Colin B. Macdonald +Marcus Näslund +Clemens Novak +Mridul Seth +Craig A. Stoudt +Raj +Mihai A. Ionescu +immerrr +Chai Wah Wu +Leonid Blouvshtein +Peleg Michaeli +ck Lux +zsc347 +Hamish Dickson +Michael Gallaspy +Roman Inflianskas +Duane Nykamp +Ted Dokos +Sunny Aggarwal +Victor Brebenar +Akshat Jain +Shivam Vats +Longqi Wang +Juan Felipe Osorio +Ray Cathcart +Lukas Zorich +Eric Miller +Cody Herbst +Nishith Shah +Amit Kumar +Yury G. Kudryashov +Guillaume Gay +Mihir Wadwekar +Tuan Manh Lai +Asish Panda +Darshan Chaudhary +Alec Kalinin +Ralf Stephan +Aaditya Nair +Jayesh Lahori +Harshil Goel +Luv Agarwal +Jason Ly +Lokesh Sharma +Sartaj Singh +Chris Swierczewski +Konstantin Togoi +Param Singh +Sumith Kulal +Juha Remes +Philippe Bouafia +Peter Schmidt +Jiaxing Liang +Lucas Jones +Gregory Ashton +Jennifer White +Renato Orsino +Alistair Lynn +Govind Sahai +Adam Bloomston +Kyle McDaniel +Nguyen Truong Duy +Alex Lindsay +Mathew Chong +Jason Siefken +Gaurav Dhingra +Gao, Xiang +Kevin Ventullo +mao8 +Isuru Fernando +Shivam Tyagi +Richard Otis +Rich LaSota +dustyrockpyle +Anton Akhmerov +Michael Zingale +Chak-Pong Chung +David T +Phil Ruffwind +Sebastian Koslowski +Kumar Krishna Agrawal +Dustin Gadal +João Moura +Yu Kobayashi +Shashank Kumar +Timothy Cyrus +Devyani Kota +Keval Shah +Dzhelil Rufat +Pastafarianist +Sourav Singh +Jacob Garber +Vinay Singh +GolimarOurHero +Prashant Tyagi +Matthew Davis +Tschijnmo TSCHAU +Alexander Bentkamp +Jack Kemp +Kshitij Saraogi +Thomas Baruchel +Nicolás Guarín-Zapata +Jens Jørgen Mortensen +Sampad Kumar Saha +Eva Charlotte Mayer +Laura Domine +Justin Blythe +Meghana Madhyastha +Tanu Hari Dixit +Shekhar Prasad Rajak +Aqnouch Mohammed +Arafat Dad Khan +Boris Atamanovskiy +Sam Tygier +Jai Luthra +Guo Xingjian +Sandeep Veethu +Archit Verma +Shubham Tibra +Ashutosh Saboo +Michael S. Hansen +Anish Shah +Guillaume Jacquenot +Bhautik Mavani +Michał Radwański +Jerry Li +Pablo Zubieta +Shivam Agarwal +Chaitanya Sai Alaparthi +Arihant Parsoya +Ruslan Pisarev +Akash Trehan +Nishant Nikhil +Vladimir Poluhsin +Akshay Nagar +James Brandon Milam +Abhinav Agarwal +Rishabh Daal +Sanya Khurana +Aman Deep +Aravind Reddy +Abhishek Verma +Matthew Parnell +Thomas Hickman +Akshay Siramdas +YiDing Jiang +Jatin Yadav +Matthew Thomas +Rehas Sachdeva +Michael Mueller +Srajan Garg +Prabhjot Singh +Haruki Moriguchi +Tom Gijselinck +Nitin Chaudhary +Alex Argunov +Nathan Musoke +Abhishek Garg +Dana Jacobsen +Vasiliy Dommes +Phillip Berndt +Haimo Zhang +Anthony Scopatz +bluebrook +Leonid Kovalev +Josh Burkart +Dimitra Konomi +Christina Zografou +Fiach Antaw +Langston Barrett +Krit Karan +G. D. McBain +Prempal Singh +Gabriel Orisaka +Matthias Bussonnier +rahuldan +Colin Marquardt +Andrew Taber +Yash Reddy +Peter Stangl +elvis-sik +Nikos Karagiannakis +Jainul Vaghasia +Dennis Meckel +Harshil Meena +Micky +Nick Curtis +Michele Zaffalon +Martha Giannoudovardi +Devang Kulshreshtha +Steph Papanik +Mohammad Sadeq Dousti +Arif Ahmed +Abdullah Javed Nesar +Lakshya Agrawal +shruti +Rohit Rango +Hong Xu +Ivan Petuhov +Alsheh +Marcel Stimberg +Alexey Pakhocmhik +Tommy Olofsson +Zulfikar +Blair Azzopardi +Danny Hermes +Sergey Pestov +Mohit Chandra +Karthik Chintapalli +Marcin Briański +andreo +Flamy Owl +Yicong Guo +Varun Garg +Rishabh Madan +Aditya Kapoor +Karan Sharma +Vedant Rathore +Johan Blåbäck +Pranjal Tale +Jason Tokayer +Raghav Jajodia +Rajat Thakur +Dhruv Bhanushali +Anjul Kumar Tyagi +Barun Parruck +Bao Chau +Tanay Agrawal +Ranjith Kumar +Shikhar Makhija +Yathartha Joshi +Valeriia Gladkova +Sagar Bharadwaj +Daniel Mahler +Ka Yi +Rishat Iskhakov +Szymon Mieszczak +Sachin Agarwal +Priyank Patel +Satya Prakash Dwibedi +tools4origins +Nico Schlömer +Fermi Paradox +Ekansh Purohit +Vedarth Sharma +Peeyush Kushwaha +Jayjayyy +Christopher J. Wright +Jakub Wilk +Mauro Garavello +Chris Tefer +Shikhar Jaiswal +Chiu-Hsiang Hsu +Carlos Cordoba +Fabian Ball +Yerniyaz +Christiano Anderson +Robin Neatherway +Thomas Hunt +Theodore Han +Duc-Minh Phan +Lejla Metohajrova +Samyak Jain +Aditya Rohan +Vincent Delecroix +Michael Sparapany +Harsh Jain +Nathan Goldbaum +latot +Kenneth Lyons +Stan Schymanski +David Daly +Ayush Shridhar +Javed Nissar +Jiri Kuncar +vedantc98 +Rupesh Harode +Rob Zinkov +James Harrop +James Taylor +Ishan Joshi +Marco Mancini +Boris Ettinger +Micah Fitch +Daniel Wennberg +ylemkimon +Akash Vaish +Peter Enenkel +Waldir Pimenta +Jithin D. George +Lev Chelyadinov +Lucas Wiman +Rhea Parekh +James Cotton +Robert Pollak +anca-mc +Sourav Ghosh +Jonathan Allan +Nikhil Pappu +Ethan Ward +Cezary Marczak +dps7ud +Nilabja Bhattacharya +Itay4 <31018228+Itay4@users.noreply.github.com> +Poom Chiarawongse +Yang Yang +Cavendish McKay +Bradley Gannon +B McG +Rob Drynkin +Seth Ebner +Akash Kundu +Mark Jeromin +Roberto Díaz Pérez +Gleb Siroki +Segev Finer +Alex Lubbock +Ayodeji Ige +Matthew Wardrop +Hugo van Kemenade +Austin Palmer +der-blaue-elefant +Filip Gokstorp +Yuki Matsuda +Aaron Miller +Salil Vishnu Kapur +Atharva Khare +Shubham Maheshwari +Pavel Tkachenko +Ashish Kumar Gaurav +Rajeev Singh +Keno Goertz +Lucas Gallindo +Himanshu +David Menéndez Hurtado +Amit Manchanda +Rohit Jain +Jonathan A. Gross +Unknown +Sayan Goswami +Subhash Saurabh +Rastislav Rabatin +Vishal +Jeremey Gluck +Akshat Maheshwari +symbolique +Saloni Jain +Arighna Chakrabarty +Abhigyan Khaund +Jashanpreet Singh +Saurabh Agarwal +luzpaz +P. Sai Prasanth +Nirmal Sarswat +Cristian Di Pietrantonio +Ravi charan +Nityananda Gohain +Cédric Travelletti +Nicholas Bollweg +Himanshu Ladia +Adwait Baokar +Mihail Tarigradschi +Saketh +rushyam +sfoo +Rahil Hastu +Zach Raines +Sidhant Nagpal +Gagandeep Singh +Rishav Chakraborty +Malkhan Singh +Joaquim Monserrat +Mayank Singh +Rémy Léone +Maxence Mayrand <35958639+maxencemayrand@users.noreply.github.com> +Nikoleta Glynatsi +helo9 +Ken Wakita +Carl Sandrock +Fredrik Eriksson +Ian Swire +Bulat +Ehren Metcalfe +Dmitry Savransky +Kiyohito Yamazaki +Caley Finn +Zhi-Qiang Zhou +Alexander Pozdneev +Wes Turner <50891+westurner@users.noreply.github.com> +JMSS-Unknown <31131631+JMSS-Unknown@users.noreply.github.com> +Arshdeep Singh +cym1 <16437732+cym1@users.noreply.github.com> +Stewart Wadsworth +Jared Lumpe +Avi Shrivastava +ramvenkat98 +Bilal Ahmed +Dimas Abreu Archanjo Dutra +Yatna Verma +S.Y. Lee +Miro Hrončok +Sudarshan Kamath +Ayushman Koul +Robert Dougherty-Bliss +Andrey Grozin +Bavish Kulur +Arun Singh +sirnicolaf <43586954+sirnicolaf@users.noreply.github.com> +Zachariah Etienne +Prayush Dawda <35144226+iamprayush@users.noreply.github.com> +2torus +Faisal Riyaz +Martin Roelfs +SirJohnFranklin +Anthony Sottile +ViacheslavP +Safiya03 +Alexander Dunlap +Rohit Sharma <31184621+rohitx007@users.noreply.github.com> +Jonathan Warner +Mohit Balwani +Marduk Bolaños +amsuhane +Matthias Geier +klaasvanaarsen <44929042+klaasvanaarsen@users.noreply.github.com> +Shubham Kumar Jha +rationa-kunal +Animesh Sinha +Gaurang Tandon <1gaurangtandon@gmail.com> +Matthew Craven +Daniel Ingram +Jogi Miglani +Takumasa Nakamura +Ritu Raj Singh +Rajiv Ranjan Singh +Vera Lozhkina +adhoc-king <46354827+adhoc-king@users.noreply.github.com> +Mikel Rouco +Oscar Gustafsson +damianos +Supreet Agrawal +shiksha11 +Martin Ueding +sharma-kunal +Divyanshu Thakur +Susumu Ishizuka +Samnan Rahee +Fredrik Andersson +Bhavya Srivastava +Alpesh Jamgade +Shubham Abhang +Vishesh Mangla +Nicko van Someren +dandiez <47832466+dandiez@users.noreply.github.com> +Frédéric Chapoton +jhanwar +Noumbissi valere Gille Geovan +Salmista-94 +Shivani Kohli +Parker Berry +Pragyan Mehrotra +Nabanita Dash +Gaetano Guerriero +Ankit Raj Pandey +Ritesh Kumar +kangzhiq <709563092@qq.com> +Jun Lin +Petr Kungurtsev +Anway De +znxftw +Denis Ivanenko +Orestis Vaggelis +Nikhil Maan +Abhinav Anand +Qingsha Shi +Juan Barbosa +Prionti Nasir +Bharat Raghunathan +arooshiverma +Christoph Gohle +Charalampos Tsiagkalis +Daniel Sears +Megan Ly +Sean P. Cornelius +Erik R. Gomez +Riccardo Magliocchetti +Henry Metlov +pekochun +Bendik Samseth +Vighnesh Shenoy +Versus Void +Denys Rybalka +Mark Dickinson +Rimi +rimibis <33387803+rimibis@users.noreply.github.com> +Steven Lee +Gilles Schintgen +Abhi58 +Tomasz Pytel +Aadit Kamat +Samesh +Velibor Zeli +Gabriel Bernardino +Joseph Redfern +Evelyn King +Miguel Marco +David Hagen +Hannah Kari +Soniya Nayak +Harsh Agarwal +Enric Florit +Yogesh Mishra +Denis Rykov +Ivan Tkachenko +Kenneth Emeka Odoh +Stephan Seitz +Yeshwanth N +Oscar Gerardo Lazo Arjona +Srinivasa Arun Yeragudipati +Kirtan Mali +TitanSnow +Pengning Chao <8857165+PengningChao@users.noreply.github.com> +Louis Abraham +Morten Olsen Lysgaard +Akash Nagaraj (akasnaga) +Akash Nagaraj +Lauren Glattly +Hou-Rui +George Korepanov +dranknight09 +aditisingh2362 +Gina +gregmedlock +Georgios Giapitzakis Tzintanos +Eric Wieser +Bradley Dowling <34559056+btdow@users.noreply.github.com> +Maria Marginean <33810762+mmargin@users.noreply.github.com> +Akash Agrawall +jgulian +Sourav Goyal +Zlatan Vasović +Alex Meiburg +Smit Lunagariya +Naman Gera +Julien Palard +Dhruv Mendiratta +erdOne <36414270+erdOne@users.noreply.github.com> +risubaba +abhinav28071999 <41710346+abhinav28071999@users.noreply.github.com> +Jisoo Song +Jaime R <38530589+Jaime02@users.noreply.github.com> +Vikrant Malik +Hardik Saini <43683678+Guardianofgotham@users.noreply.github.com> +Abhishek +Johannes Hartung +Milan Jolly +faizan2700 +mohit <39158356+mohitacecode@users.noreply.github.com> +Mohit Gupta +Psycho-Pirate +Chanakya-Ekbote +Rashmi Shehana +Jonty16117 +Anubhav Gupta +Michal Grňo +vezeli <37907135+vezeli@users.noreply.github.com> +Tim Gates +Sandeep Murthy +Neil +V1krant <46847915+V1krant@users.noreply.github.com> +alejandro +Riyan Dhiman +sbt4104 +Seth Troisi +Bhaskar Gupta +Smit Gajjar +rbl +Ilya Pchelintsev +Omar Wagih +prshnt19 +Johan Guzman +Vasileios Kalos +BasileiosKal <61801875+BasileiosKal@users.noreply.github.com> +Shubham Thorat <37049710+sbt4104@users.noreply.github.com> +Arpan Chattopadhyay +Ashutosh Hathidara +Moses Paul R +Saanidhya vats +tnzl +Vatsal Srivastava +Jean-Luc Herren +Dhruv Kothari +seadavis <45022599+seadavis@users.noreply.github.com> +kamimura +slacker404 +Jaime Resano +Ebrahim Byagowi +wuyudi +Akira Kyle +Calvin Jay Ross +Martin Thoma +Thomas A Caswell +Lagaras Stelios +Jerry James +Jan Kruse +Nathan Taylor +Vaishnav Damani +Mohit Shah +Mathias Louboutin +Marijan Smetko +Dave Witte Morris +soumi7 +Zhongshi +Wes Galbraith +KaustubhDamania +w495 +Akhil Rajput +Markus Mohrhard +Benjamin Wolba +彭于斌 <1931127624@qq.com> +Rudr Tiwari +Aaryan Dewan +Benedikt Placke +Sneha Goddu +goddus <39923708+goddus@users.noreply.github.com> +Shivang Dubey +Michael Greminger +Peter Cock +Willem Melching +Elias Basler +Brandon David +Abhay_Dhiman +Tasha Kim +Ayush Malik +Devesh Sawant +Wolfgang Stöcher +Sudeep Sidhu +foice +Ben Payne +Muskan Kumar <31043527+muskanvk@users.noreply.github.com> +noam simcha finkelstein +Garrett Folbe +Islam Mansour +Sayandip Halder +Shubham Agrawal +numbermaniac <5206120+numbermaniac@users.noreply.github.com> +Sakirul Alam +Mohammed Bilal +Chris du Plessis +Coder-RG +Ansh Mishra +Alex Malins +Lorenzo Contento +Naveen Sai +Shital Mule +Amanda Dsouza +Nijso Beishuizen +Harry Zheng +Felix Yan +Constantin Mateescu +Eva Tiwari +Aditya Kumar Sinha +Soumi Bardhan <51290447+Soumi7@users.noreply.github.com> +Kaustubh Chaudhari +Kristian Brünn +Neel Gorasiya +Akshat Sood <68052998+akshatsood2249@users.noreply.github.com> +Jose M. Gomez +Stefan Petrea +Praveen Sahu +Mark Bell +AlexCQY +Fabian Froehlich +Nikhil Gopalam +Kartik Sethi +Muhammed Abdul Quadir Owais +Harshit Yadav +Sidharth Mundhra +Suryam Arnav Kalra +Prince Gupta +Kunal Singh +Mayank Raj +Achal Jain <2achaljain@gmail.com> +Mario Maio +Aaron Stiff <69512633+AaronStiff@users.noreply.github.com> +Wyatt Peak +Bhaskar Joshi +Aditya Jindal +Vaibhav Bhat +Priyansh Rathi +Saket Kumar Singh +Yukai Chou +Qijia Liu +Paul Mandel +Nisarg Chaudhari <54911392+Nisarg-Chaudhari@users.noreply.github.com> +Dominik Stańczak +Rodrigo Luger +Marco Antônio Habitzreuter +Ayush Bisht +Akshansh Bhatt +Brandon T. Willard +Thomas Aarholt +Hiren Chalodiya +Roland Dixon +dimasvq +Sagar231 +Michael Chu +Abby Ng +Angad Sandhu <55819847+angadsinghsandhu@users.noreply.github.com> +Alexander Cockburn +Yaser AlOsh +Davide Sandonà +Jonathan Gutow +Nihir Agarwal +Lee Johnston +Zach Carmichael <20629897+craymichael@users.noreply.github.com> +Vijairam Ganesh Moorthy +Hanspeter Schmid +Ben Oostendorp +Nikita +Aman +Shashank KS +Aman Sharma +Anup Parikh +Lucy Mountain +Miguel Torres Costa +Rikard Nordgren +Arun sanganal <74652697+ArunSanganal@users.noreply.github.com> +Kamlesh Joshi <72374645+kamleshjoshi8102@users.noreply.github.com> +Joseph Rance <56409230+Joseph-Rance@users.noreply.github.com> +Huangduirong +Nils Schulte <47043622+Schnilz@users.noreply.github.com> +Matt Bogosian +Elisha Hollander +Aditya Ravuri +Mamidi Ratna Praneeth +Jeffrey Ryan +Jonathan Daniel <36337649+jond01@users.noreply.github.com> +Robin Richard +Gautam Menghani +Remco de Boer <29308176+redeboer@users.noreply.github.com> +Sebastian East +Evani Balasubramanyam +Rahil Parikh +Jason Ross +Joannah Nanjekye +Ayush Kumar +Kshitij +Daniel Hyams +alijosephine +Matthias Köppe +mohajain +Anibal M. Medina-Mardones +Travis Ens +Evgenia Karunus +Risiraj Dey +lastcodestanding +Andrey Lekar +Abbas Mohammed <42001049+iam-abbas@users.noreply.github.com> +Anutosh Bhat +Steve Kieffer +Paul Spiering +Pieter Gijsbers +Wang Ran (汪然) +naelsondouglas +Aman Thakur +S. Hanko +Dennis Sweeney +Gurpartap Singh +Hampus Malmberg +scimax +Nikhil Date +Kuldeep Borkar Jr +AkuBrain <76952313+Franck2111@users.noreply.github.com> +Leo Battle +Advait Pote +Anurag Bhat +Jeremy Monat +Diane Tchuindjo +Tom Fryers <61272761+TomFryers@users.noreply.github.com> +Zouhair +zzj <29055749+zjzh@users.noreply.github.com> +shubhayu09 +Siddhant Jain +Tirthankar Mazumder <63574588+wermos@users.noreply.github.com> +Sumit Kumar +Shivam Sagar +Gaurav Jain +Andrii Oriekhov +Luis Talavera +Arie Bovenberg +Carson McManus +Jack Schmidt <1107865+jackschmidt@users.noreply.github.com> +Riley Britten +Georges Khaznadar +Donald Wilson +Timo Stienstra +dispasha +Saksham Alok +Varenyam Bhardwaj +oittaa <8972248+oittaa@users.noreply.github.com> +Omkaar <79257339+Pysics@users.noreply.github.com> +Islem BOUZENIA +extraymond +Alexander Behrens +user202729 <25191436+user202729@users.noreply.github.com> +Pieter Eendebak +Zaz Brown +ritikBhandari +viocha <66580331+viocha@users.noreply.github.com> +Arthur Ryman +Xiang Wu +tttc3 +Seth Poulsen +cocolato +Anton Golovanov +Gareth Ma +Clément M.T. Robert +Glenn Horton-Smith +Karan +Stefan Behnle <84378403+behnle@users.noreply.github.com> +Shreyash Mishra <72146041+Shreyash-cyber@users.noreply.github.com> +Arthur Milchior +NotWearingPants <26556598+NotWearingPants@users.noreply.github.com> +Ishan Pandhare +Carlos García Montoro +Parcly Taxel +Saicharan +Kunal Sheth +Biswadeep Purkayastha <98874428+metabiswadeep@users.noreply.github.com> +Jyn Spring 琴春 +Phil LeMaitre +Chris Kerr +José Senart +Uwe L. Korn +ForeverHaibara <69423537+ForeverHaibara@users.noreply.github.com> +Yves Tumushimire +wookie184 +Costor +Klaus Rettinghaus +Sam Brockie +Abhishek Patidar <1e9abhi1e10@gmail.com> +Eric Demer +Pontus von Brömssen +Victor Immanuel +Evandro Bernardes +Michele Ceccacci +Ayush Aryan +Kishore Gopalakrishnan +Jan-Philipp Hoffmann +Daiki Takahashi +Sayan Mitra +Aman Kumar Shukla +Zoufiné Lauer-Baré +Charles Harris +Tejaswini Sanapathi +Devansh +Aaron Gokaslan +Daan Koning (he/him) +Steven Burns +Jay Patankar +Vivek Soni +Le Cong Minh Hieu +Sam Ritchie +Maciej Skórski +Tilo Reneau-Cardoso +Laurence Warne +Lukas Molleman +Konstantinos Riganas +Grace Su +Pedro Rosa +Abhinav Cillanki +Baiyuan Qiu <1061688677@qq.com> +Liwei Cai +Daniel Weindl +Isidora Araya +Seb Tiburzio +Victory Omole +Abhishek Chaudhary +Alexander Zhura +Shuai Zhou +Martin Manns +John Möller +zzc <1378113190@qq.com> +Pablo Galindo Salgado +Johannes Kasimir +Theodore Dias +Kaustubh <90597818+kaustubh-765@users.noreply.github.com> +Idan Pazi +Bobby Palmer +Saikat Das +Suman mondal +Taylan Sahin +Fabio Luporini +Oriel Malihi +Geetika Vadali +Matthias Rettl +Mikhail Remnev +philwillnyc <56197213+philwillnyc@users.noreply.github.com> +Raphael Lehner +Harry Mountain +Bhavik Sachdev +袁野 (Yuan Ye) +fazledyn-or +mohammedouahman +K. Kraus +Zac Hatfield-Dodds +platypus +codecruisader +James Whitehead +atharvParlikar +Ivan Petukhov +Augusto Borges +Han Wei Ang +Congxu Yang +Saicharan <62512681+saicharan2804@users.noreply.github.com> +Arnab Nandi +Harrison Oates <48871176+HarrisonOates@users.noreply.github.com> +Corey Cerovsek +Harsh Kasat +omahs <73983677+omahs@users.noreply.github.com> +Pascal Gitz +Ravindu-Hirimuthugoda +Sophia Pustova +George Pittock +Warren Jacinto +Sachin Singh +Zedmat <104870914+harshkasat@users.noreply.github.com> +Soumendra Ganguly +Samith Karunathilake <55777141+samithkavishke@users.noreply.github.com> +Viraj Vekaria +Shishir Kushwaha +Ankit Kumar Singh +Abhishek Kumar +Mohak Malviya +Matthias Liesenfeld <116307294+maliesen@users.noreply.github.com> +dodo +Mohamed Rezk +Tommaso Vaccari <05-gesto-follemente@icloud.com> +Alexis Schotte +Lauren Yim <31467609+cherryblossom000@users.noreply.github.com> +Prey Patel +Riccardo Di Girolamo +Abhishek kumar +Sam Lubelsky +Henrique Soares +Vladimir Sereda +Hwayeon Kang +Raj Sapale +Gerald Teschl +Richard Samuel <98638849+samuelard7@users.noreply.github.com> +HeeJae Chang +Nick Harder +Ethan DeGuire +Lorenz Winkler +Richard Rodenbusch +Zhenxu Zhu +Mark van Gelder +Mark van Gelder +Ishan Pandhare <91841626+Ishanned@users.noreply.github.com> +James A. Preiss +Emile Fourcini +Alberto Jiménez Ruiz +João Bravo +Dean Price +Edward Z. Yang +James Titus +Zhuoyuan Li +Hugo Kerstens +Jan Jancar +Andrew Mosson +Marek Madejski +Gonzalo Tornaría +Peter Stahlecker +Jean-François B <2589111+jfbu@users.noreply.github.com> +Zexuan Zhou (Bruce) +George Frolov +Corbet Elkins +Håkon Kvernmoen +Muhammad Maaz +Shishir Kushwaha <138311586+shishir-11@users.noreply.github.com> +Matt Wang +bharatAmeria <21001019007@jcboseust.ac.in> +Amir Ebrahimi +Steven Esquea +Rishabh Kamboj <111004091+VectorNd@users.noreply.github.com> +Aasim Ali +Ivan A. Melnikov +Borek Saheli +Guido Roncarolo +Quek Zi Yao +Roelof Rietbroek +MostafaGalal1 +Au Huishan +Kris Katterjohn +Shiyao Guo +Rushabh Mehta +Temiloluwa Yusuf ytemiloluwa@gmail.com ytemiloluwa +Davi Laerte +Agriya Khetarpal <74401230+agriyakhetarpal@users.noreply.github.com> +Harshit Gupta +Praveen Perumal +Kevin McWhirter +Prayag V +Lucas Kletzander +Pratyksh Gupta +Leonardo Mangani +Karan Anand +Gagan Mishra +Krishnav Bajoria +Matt Ord +Jatin Bhardwaj +Prashant Tandon +Paramjit Singh +João Rodrigues +Alejandro García Prada <114813960+AlexGarciaPrada@users.noreply.github.com> +Matthew Treinish +Clayton Rabideau +Victoria Koval +Voaides Negustor Robert <134785947+voaidesr@users.noreply.github.com> +Ovsk Mendov +David Brooks +Nicholas Laustrup <124007393+nicklaustrup@users.noreply.github.com> +Harikrishna Srinivasan +Mathis Cros +Arnav Mummineni <45217840+RCoder01@users.noreply.github.com> +Thangaraju Sibiraj <85477603+t-sibiraj@users.noreply.github.com> +KJaybhaye diff --git a/.venv/lib/python3.12/site-packages/sympy-1.14.0.dist-info/licenses/LICENSE b/.venv/lib/python3.12/site-packages/sympy-1.14.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0744f229d697ca3ed1b1b257bfdb70e3eecf0b9e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy-1.14.0.dist-info/licenses/LICENSE @@ -0,0 +1,153 @@ +Copyright (c) 2006-2023 SymPy Development Team + +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 SymPy 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 REGENTS 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. + +-------------------------------------------------------------------------------- + +Patches that were taken from the Diofant project (https://github.com/diofant/diofant) +are licensed as: + +Copyright (c) 2006-2018 SymPy Development Team, + 2013-2023 Sergey B Kirpichev + +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 Diofant or SymPy 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 REGENTS 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. + +-------------------------------------------------------------------------------- + +Submodules taken from the multipledispatch project (https://github.com/mrocklin/multipledispatch) +are licensed as: + +Copyright (c) 2014 Matthew Rocklin + +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 multipledispatch 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 REGENTS 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. + +-------------------------------------------------------------------------------- + +The files under the directory sympy/parsing/autolev/tests/pydy-example-repo +are directly copied from PyDy project and are licensed as: + +Copyright (c) 2009-2023, PyDy Authors +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 this 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 PYDY AUTHORS 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. + +-------------------------------------------------------------------------------- + +The files under the directory sympy/parsing/latex +are directly copied from latex2sympy project and are licensed as: + +Copyright 2016, latex2sympy + +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/.venv/lib/python3.12/site-packages/sympy-1.14.0.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/sympy-1.14.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..0aa85c253508b68bb075f556be3c3f76dc4467ad --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy-1.14.0.dist-info/top_level.txt @@ -0,0 +1,2 @@ +isympy +sympy diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_discrete_rv.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_discrete_rv.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93ed0d40f9823d677f627378043b755d45b1968c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_discrete_rv.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_error_prop.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_error_prop.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..620e1a2317e7dc5a100bd8f40c9830c9c5cd00bb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_error_prop.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_finite_rv.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_finite_rv.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79a08296e394954cbece9a4892e1471563124bfd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_finite_rv.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_joint_rv.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_joint_rv.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbeb3ffc90b4098eae286e35f882a6ec61149acd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_joint_rv.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_matrix_distributions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_matrix_distributions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b09cf5558f77df9b91d7f6726ed2e5e5d8ce131 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_matrix_distributions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_mix.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_mix.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d05060e447db6e45339dd03f00ed9a3b8bc2460a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_mix.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_random_matrix.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_random_matrix.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cdc5fe95f79358691274890224c79f5d9a9f8aab Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_random_matrix.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_rv.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_rv.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..828fe163dea04c95aa23cab97a371d288bfed015 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_rv.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_stochastic_process.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_stochastic_process.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83d7418bb49f122ad0c51b03739b494ceaeed71b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_stochastic_process.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_symbolic_multivariate.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_symbolic_multivariate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9545524856cf2fcf3fd337f3015b7907e3956e3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_symbolic_multivariate.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_symbolic_probability.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_symbolic_probability.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57cb788c474b2bb6adc2b2a0b38d57797daa6282 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/stats/tests/__pycache__/test_symbolic_probability.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_compound_rv.py b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_compound_rv.py new file mode 100644 index 0000000000000000000000000000000000000000..573ba364b686738e56bb1c4615acd2a9bc8bf3ae --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_compound_rv.py @@ -0,0 +1,159 @@ +from sympy.concrete.summations import Sum +from sympy.core.numbers import (oo, pi) +from sympy.core.relational import Eq +from sympy.core.singleton import S +from sympy.core.symbol import symbols +from sympy.functions.combinatorial.factorials import factorial +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.special.beta_functions import beta +from sympy.functions.special.error_functions import erf +from sympy.functions.special.gamma_functions import gamma +from sympy.integrals.integrals import Integral +from sympy.sets.sets import Interval +from sympy.stats import (Normal, P, E, density, Gamma, Poisson, Rayleigh, + variance, Bernoulli, Beta, Uniform, cdf) +from sympy.stats.compound_rv import CompoundDistribution, CompoundPSpace +from sympy.stats.crv_types import NormalDistribution +from sympy.stats.drv_types import PoissonDistribution +from sympy.stats.frv_types import BernoulliDistribution +from sympy.testing.pytest import raises, ignore_warnings +from sympy.stats.joint_rv_types import MultivariateNormalDistribution + +from sympy.abc import x + + +# helpers for testing troublesome unevaluated expressions +flat = lambda s: ''.join(str(s).split()) +streq = lambda *a: len(set(map(flat, a))) == 1 +assert streq(x, x) +assert streq(x, 'x') +assert not streq(x, x + 1) + + +def test_normal_CompoundDist(): + X = Normal('X', 1, 2) + Y = Normal('X', X, 4) + assert density(Y)(x).simplify() == sqrt(10)*exp(-x**2/40 + x/20 - S(1)/40)/(20*sqrt(pi)) + assert E(Y) == 1 # it is always equal to mean of X + assert P(Y > 1) == S(1)/2 # as 1 is the mean + assert P(Y > 5).simplify() == S(1)/2 - erf(sqrt(10)/5)/2 + assert variance(Y) == variance(X) + 4**2 # 2**2 + 4**2 + # https://math.stackexchange.com/questions/1484451/ + # (Contains proof of E and variance computation) + + +def test_poisson_CompoundDist(): + k, t, y = symbols('k t y', positive=True, real=True) + G = Gamma('G', k, t) + D = Poisson('P', G) + assert density(D)(y).simplify() == t**y*(t + 1)**(-k - y)*gamma(k + y)/(gamma(k)*gamma(y + 1)) + # https://en.wikipedia.org/wiki/Negative_binomial_distribution#Gamma%E2%80%93Poisson_mixture + assert E(D).simplify() == k*t # mean of NegativeBinomialDistribution + + +def test_bernoulli_CompoundDist(): + X = Beta('X', 1, 2) + Y = Bernoulli('Y', X) + assert density(Y).dict == {0: S(2)/3, 1: S(1)/3} + assert E(Y) == P(Eq(Y, 1)) == S(1)/3 + assert variance(Y) == S(2)/9 + assert cdf(Y) == {0: S(2)/3, 1: 1} + + # test issue 8128 + a = Bernoulli('a', S(1)/2) + b = Bernoulli('b', a) + assert density(b).dict == {0: S(1)/2, 1: S(1)/2} + assert P(b > 0.5) == S(1)/2 + + X = Uniform('X', 0, 1) + Y = Bernoulli('Y', X) + assert E(Y) == S(1)/2 + assert P(Eq(Y, 1)) == E(Y) + + +def test_unevaluated_CompoundDist(): + # these tests need to be removed once they work with evaluation as they are currently not + # evaluated completely in sympy. + R = Rayleigh('R', 4) + X = Normal('X', 3, R) + ans = ''' + Piecewise(((-sqrt(pi)*sinh(x/4 - 3/4) + sqrt(pi)*cosh(x/4 - 3/4))/( + 8*sqrt(pi)), Abs(arg(x - 3)) <= pi/4), (Integral(sqrt(2)*exp(-(x - 3) + **2/(2*R**2))*exp(-R**2/32)/(32*sqrt(pi)), (R, 0, oo)), True))''' + assert streq(density(X)(x), ans) + + expre = ''' + Integral(X*Integral(sqrt(2)*exp(-(X-3)**2/(2*R**2))*exp(-R**2/32)/(32* + sqrt(pi)),(R,0,oo)),(X,-oo,oo))''' + with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed + assert streq(E(X, evaluate=False).rewrite(Integral), expre) + + X = Poisson('X', 1) + Y = Poisson('Y', X) + Z = Poisson('Z', Y) + exprd = Sum(exp(-Y)*Y**x*Sum(exp(-1)*exp(-X)*X**Y/(factorial(X)*factorial(Y) + ), (X, 0, oo))/factorial(x), (Y, 0, oo)) + assert density(Z)(x) == exprd + + N = Normal('N', 1, 2) + M = Normal('M', 3, 4) + D = Normal('D', M, N) + exprd = ''' + Integral(sqrt(2)*exp(-(N-1)**2/8)*Integral(exp(-(x-M)**2/(2*N**2))*exp + (-(M-3)**2/32)/(8*pi*N),(M,-oo,oo))/(4*sqrt(pi)),(N,-oo,oo))''' + assert streq(density(D, evaluate=False)(x), exprd) + + +def test_Compound_Distribution(): + X = Normal('X', 2, 4) + N = NormalDistribution(X, 4) + C = CompoundDistribution(N) + assert C.is_Continuous + assert C.set == Interval(-oo, oo) + assert C.pdf(x, evaluate=True).simplify() == exp(-x**2/64 + x/16 - S(1)/16)/(8*sqrt(pi)) + + assert not isinstance(CompoundDistribution(NormalDistribution(2, 3)), + CompoundDistribution) + M = MultivariateNormalDistribution([1, 2], [[2, 1], [1, 2]]) + raises(NotImplementedError, lambda: CompoundDistribution(M)) + + X = Beta('X', 2, 4) + B = BernoulliDistribution(X, 1, 0) + C = CompoundDistribution(B) + assert C.is_Finite + assert C.set == {0, 1} + y = symbols('y', negative=False, integer=True) + assert C.pdf(y, evaluate=True) == Piecewise((S(1)/(30*beta(2, 4)), Eq(y, 0)), + (S(1)/(60*beta(2, 4)), Eq(y, 1)), (0, True)) + + k, t, z = symbols('k t z', positive=True, real=True) + G = Gamma('G', k, t) + X = PoissonDistribution(G) + C = CompoundDistribution(X) + assert C.is_Discrete + assert C.set == S.Naturals0 + assert C.pdf(z, evaluate=True).simplify() == t**z*(t + 1)**(-k - z)*gamma(k \ + + z)/(gamma(k)*gamma(z + 1)) + + +def test_compound_pspace(): + X = Normal('X', 2, 4) + Y = Normal('Y', 3, 6) + assert not isinstance(Y.pspace, CompoundPSpace) + N = NormalDistribution(1, 2) + D = PoissonDistribution(3) + B = BernoulliDistribution(0.2, 1, 0) + pspace1 = CompoundPSpace('N', N) + pspace2 = CompoundPSpace('D', D) + pspace3 = CompoundPSpace('B', B) + assert not isinstance(pspace1, CompoundPSpace) + assert not isinstance(pspace2, CompoundPSpace) + assert not isinstance(pspace3, CompoundPSpace) + M = MultivariateNormalDistribution([1, 2], [[2, 1], [1, 2]]) + raises(ValueError, lambda: CompoundPSpace('M', M)) + Y = Normal('Y', X, 6) + assert isinstance(Y.pspace, CompoundPSpace) + assert Y.pspace.distribution == CompoundDistribution(NormalDistribution(X, 6)) + assert Y.pspace.domain.set == Interval(-oo, oo) diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_continuous_rv.py b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_continuous_rv.py new file mode 100644 index 0000000000000000000000000000000000000000..b2c4206b5c29ffd3194d1ae05e57c51c9c1b6d78 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_continuous_rv.py @@ -0,0 +1,1583 @@ +from sympy.concrete.summations import Sum +from sympy.core.function import (Lambda, diff, expand_func) +from sympy.core.mul import Mul +from sympy.core import EulerGamma +from sympy.core.numbers import (E as e, I, Rational, pi) +from sympy.core.relational import (Eq, Ne) +from sympy.core.singleton import S +from sympy.core.symbol import (Dummy, Symbol, symbols) +from sympy.functions.combinatorial.factorials import (binomial, factorial) +from sympy.functions.elementary.complexes import (Abs, im, re, sign) +from sympy.functions.elementary.exponential import (exp, log) +from sympy.functions.elementary.hyperbolic import (cosh, sinh) +from sympy.functions.elementary.integers import floor +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.elementary.trigonometric import (asin, atan, cos, sin, tan) +from sympy.functions.special.bessel import (besseli, besselj, besselk) +from sympy.functions.special.beta_functions import beta +from sympy.functions.special.error_functions import (erf, erfc, erfi, expint) +from sympy.functions.special.gamma_functions import (gamma, lowergamma, uppergamma) +from sympy.functions.special.zeta_functions import zeta +from sympy.functions.special.hyper import hyper +from sympy.integrals.integrals import Integral +from sympy.logic.boolalg import (And, Or) +from sympy.sets.sets import Interval +from sympy.simplify.simplify import simplify +from sympy.utilities.lambdify import lambdify +from sympy.functions.special.error_functions import erfinv +from sympy.functions.special.hyper import meijerg +from sympy.sets.sets import FiniteSet, Complement, Intersection +from sympy.stats import (P, E, where, density, variance, covariance, skewness, kurtosis, median, + given, pspace, cdf, characteristic_function, moment_generating_function, + ContinuousRV, Arcsin, Benini, Beta, BetaNoncentral, BetaPrime, + Cauchy, Chi, ChiSquared, ChiNoncentral, Dagum, Davis, Erlang, ExGaussian, + Exponential, ExponentialPower, FDistribution, FisherZ, Frechet, Gamma, + GammaInverse, Gompertz, Gumbel, Kumaraswamy, Laplace, Levy, Logistic, LogCauchy, + LogLogistic, LogitNormal, LogNormal, Maxwell, Moyal, Nakagami, Normal, GaussianInverse, + Pareto, PowerFunction, QuadraticU, RaisedCosine, Rayleigh, Reciprocal, ShiftedGompertz, StudentT, + Trapezoidal, Triangular, Uniform, UniformSum, VonMises, Weibull, coskewness, + WignerSemicircle, Wald, correlation, moment, cmoment, smoment, quantile, + Lomax, BoundedPareto) + +from sympy.stats.crv_types import NormalDistribution, ExponentialDistribution, ContinuousDistributionHandmade +from sympy.stats.joint_rv_types import MultivariateLaplaceDistribution, MultivariateNormalDistribution +from sympy.stats.crv import SingleContinuousPSpace, SingleContinuousDomain +from sympy.stats.compound_rv import CompoundPSpace +from sympy.stats.symbolic_probability import Probability +from sympy.testing.pytest import raises, XFAIL, slow, ignore_warnings +from sympy.core.random import verify_numerically as tn + +oo = S.Infinity + +x, y, z = map(Symbol, 'xyz') + +def test_single_normal(): + mu = Symbol('mu', real=True) + sigma = Symbol('sigma', positive=True) + X = Normal('x', 0, 1) + Y = X*sigma + mu + + assert E(Y) == mu + assert variance(Y) == sigma**2 + pdf = density(Y) + x = Symbol('x', real=True) + assert (pdf(x) == + 2**S.Half*exp(-(x - mu)**2/(2*sigma**2))/(2*pi**S.Half*sigma)) + + assert P(X**2 < 1) == erf(2**S.Half/2) + ans = quantile(Y)(x) + assert ans == Complement(Intersection(FiniteSet( + sqrt(2)*sigma*(sqrt(2)*mu/(2*sigma)+ erfinv(2*x - 1))), + Interval(-oo, oo)), FiniteSet(mu)) + assert E(X, Eq(X, mu)) == mu + + assert median(X) == FiniteSet(0) + # issue 8248 + assert X.pspace.compute_expectation(1).doit() == 1 + + +def test_conditional_1d(): + X = Normal('x', 0, 1) + Y = given(X, X >= 0) + z = Symbol('z') + + assert density(Y)(z) == 2 * density(X)(z) + + assert Y.pspace.domain.set == Interval(0, oo) + assert E(Y) == sqrt(2) / sqrt(pi) + + assert E(X**2) == E(Y**2) + + +def test_ContinuousDomain(): + X = Normal('x', 0, 1) + assert where(X**2 <= 1).set == Interval(-1, 1) + assert where(X**2 <= 1).symbol == X.symbol + assert where(And(X**2 <= 1, X >= 0)).set == Interval(0, 1) + raises(ValueError, lambda: where(sin(X) > 1)) + + Y = given(X, X >= 0) + + assert Y.pspace.domain.set == Interval(0, oo) + + +def test_multiple_normal(): + X, Y = Normal('x', 0, 1), Normal('y', 0, 1) + p = Symbol("p", positive=True) + + assert E(X + Y) == 0 + assert variance(X + Y) == 2 + assert variance(X + X) == 4 + assert covariance(X, Y) == 0 + assert covariance(2*X + Y, -X) == -2*variance(X) + assert skewness(X) == 0 + assert skewness(X + Y) == 0 + assert kurtosis(X) == 3 + assert kurtosis(X+Y) == 3 + assert correlation(X, Y) == 0 + assert correlation(X, X + Y) == correlation(X, X - Y) + assert moment(X, 2) == 1 + assert cmoment(X, 3) == 0 + assert moment(X + Y, 4) == 12 + assert cmoment(X, 2) == variance(X) + assert smoment(X*X, 2) == 1 + assert smoment(X + Y, 3) == skewness(X + Y) + assert smoment(X + Y, 4) == kurtosis(X + Y) + assert E(X, Eq(X + Y, 0)) == 0 + assert variance(X, Eq(X + Y, 0)) == S.Half + assert quantile(X)(p) == sqrt(2)*erfinv(2*p - S.One) + + +def test_symbolic(): + mu1, mu2 = symbols('mu1 mu2', real=True) + s1, s2 = symbols('sigma1 sigma2', positive=True) + rate = Symbol('lambda', positive=True) + X = Normal('x', mu1, s1) + Y = Normal('y', mu2, s2) + Z = Exponential('z', rate) + a, b, c = symbols('a b c', real=True) + + assert E(X) == mu1 + assert E(X + Y) == mu1 + mu2 + assert E(a*X + b) == a*E(X) + b + assert variance(X) == s1**2 + assert variance(X + a*Y + b) == variance(X) + a**2*variance(Y) + + assert E(Z) == 1/rate + assert E(a*Z + b) == a*E(Z) + b + assert E(X + a*Z + b) == mu1 + a/rate + b + assert median(X) == FiniteSet(mu1) + + +def test_cdf(): + X = Normal('x', 0, 1) + + d = cdf(X) + assert P(X < 1) == d(1).rewrite(erfc) + assert d(0) == S.Half + + d = cdf(X, X > 0) # given X>0 + assert d(0) == 0 + + Y = Exponential('y', 10) + d = cdf(Y) + assert d(-5) == 0 + assert P(Y > 3) == 1 - d(3) + + raises(ValueError, lambda: cdf(X + Y)) + + Z = Exponential('z', 1) + f = cdf(Z) + assert f(z) == Piecewise((1 - exp(-z), z >= 0), (0, True)) + + +def test_characteristic_function(): + X = Uniform('x', 0, 1) + + cf = characteristic_function(X) + assert cf(1) == -I*(-1 + exp(I)) + + Y = Normal('y', 1, 1) + cf = characteristic_function(Y) + assert cf(0) == 1 + assert cf(1) == exp(I - S.Half) + + Z = Exponential('z', 5) + cf = characteristic_function(Z) + assert cf(0) == 1 + assert cf(1).expand() == Rational(25, 26) + I*5/26 + + X = GaussianInverse('x', 1, 1) + cf = characteristic_function(X) + assert cf(0) == 1 + assert cf(1) == exp(1 - sqrt(1 - 2*I)) + + X = ExGaussian('x', 0, 1, 1) + cf = characteristic_function(X) + assert cf(0) == 1 + assert cf(1) == (1 + I)*exp(Rational(-1, 2))/2 + + L = Levy('x', 0, 1) + cf = characteristic_function(L) + assert cf(0) == 1 + assert cf(1) == exp(-sqrt(2)*sqrt(-I)) + + +def test_moment_generating_function(): + t = symbols('t', positive=True) + + # Symbolic tests + a, b, c = symbols('a b c') + + mgf = moment_generating_function(Beta('x', a, b))(t) + assert mgf == hyper((a,), (a + b,), t) + + mgf = moment_generating_function(Chi('x', a))(t) + assert mgf == sqrt(2)*t*gamma(a/2 + S.Half)*\ + hyper((a/2 + S.Half,), (Rational(3, 2),), t**2/2)/gamma(a/2) +\ + hyper((a/2,), (S.Half,), t**2/2) + + mgf = moment_generating_function(ChiSquared('x', a))(t) + assert mgf == (1 - 2*t)**(-a/2) + + mgf = moment_generating_function(Erlang('x', a, b))(t) + assert mgf == (1 - t/b)**(-a) + + mgf = moment_generating_function(ExGaussian("x", a, b, c))(t) + assert mgf == exp(a*t + b**2*t**2/2)/(1 - t/c) + + mgf = moment_generating_function(Exponential('x', a))(t) + assert mgf == a/(a - t) + + mgf = moment_generating_function(Gamma('x', a, b))(t) + assert mgf == (-b*t + 1)**(-a) + + mgf = moment_generating_function(Gumbel('x', a, b))(t) + assert mgf == exp(b*t)*gamma(-a*t + 1) + + mgf = moment_generating_function(Gompertz('x', a, b))(t) + assert mgf == b*exp(b)*expint(t/a, b) + + mgf = moment_generating_function(Laplace('x', a, b))(t) + assert mgf == exp(a*t)/(-b**2*t**2 + 1) + + mgf = moment_generating_function(Logistic('x', a, b))(t) + assert mgf == exp(a*t)*beta(-b*t + 1, b*t + 1) + + mgf = moment_generating_function(Normal('x', a, b))(t) + assert mgf == exp(a*t + b**2*t**2/2) + + mgf = moment_generating_function(Pareto('x', a, b))(t) + assert mgf == b*(-a*t)**b*uppergamma(-b, -a*t) + + mgf = moment_generating_function(QuadraticU('x', a, b))(t) + assert str(mgf) == ("(3*(t*(-4*b + (a + b)**2) + 4)*exp(b*t) - " + "3*(t*(a**2 + 2*a*(b - 2) + b**2) + 4)*exp(a*t))/(t**2*(a - b)**3)") + + mgf = moment_generating_function(RaisedCosine('x', a, b))(t) + assert mgf == pi**2*exp(a*t)*sinh(b*t)/(b*t*(b**2*t**2 + pi**2)) + + mgf = moment_generating_function(Rayleigh('x', a))(t) + assert mgf == sqrt(2)*sqrt(pi)*a*t*(erf(sqrt(2)*a*t/2) + 1)\ + *exp(a**2*t**2/2)/2 + 1 + + mgf = moment_generating_function(Triangular('x', a, b, c))(t) + assert str(mgf) == ("(-2*(-a + b)*exp(c*t) + 2*(-a + c)*exp(b*t) + " + "2*(b - c)*exp(a*t))/(t**2*(-a + b)*(-a + c)*(b - c))") + + mgf = moment_generating_function(Uniform('x', a, b))(t) + assert mgf == (-exp(a*t) + exp(b*t))/(t*(-a + b)) + + mgf = moment_generating_function(UniformSum('x', a))(t) + assert mgf == ((exp(t) - 1)/t)**a + + mgf = moment_generating_function(WignerSemicircle('x', a))(t) + assert mgf == 2*besseli(1, a*t)/(a*t) + + # Numeric tests + + mgf = moment_generating_function(Beta('x', 1, 1))(t) + assert mgf.diff(t).subs(t, 1) == hyper((2,), (3,), 1)/2 + + mgf = moment_generating_function(Chi('x', 1))(t) + assert mgf.diff(t).subs(t, 1) == sqrt(2)*hyper((1,), (Rational(3, 2),), S.Half + )/sqrt(pi) + hyper((Rational(3, 2),), (Rational(3, 2),), S.Half) + 2*sqrt(2)*hyper((2,), + (Rational(5, 2),), S.Half)/(3*sqrt(pi)) + + mgf = moment_generating_function(ChiSquared('x', 1))(t) + assert mgf.diff(t).subs(t, 1) == I + + mgf = moment_generating_function(Erlang('x', 1, 1))(t) + assert mgf.diff(t).subs(t, 0) == 1 + + mgf = moment_generating_function(ExGaussian("x", 0, 1, 1))(t) + assert mgf.diff(t).subs(t, 2) == -exp(2) + + mgf = moment_generating_function(Exponential('x', 1))(t) + assert mgf.diff(t).subs(t, 0) == 1 + + mgf = moment_generating_function(Gamma('x', 1, 1))(t) + assert mgf.diff(t).subs(t, 0) == 1 + + mgf = moment_generating_function(Gumbel('x', 1, 1))(t) + assert mgf.diff(t).subs(t, 0) == EulerGamma + 1 + + mgf = moment_generating_function(Gompertz('x', 1, 1))(t) + assert mgf.diff(t).subs(t, 1) == -e*meijerg(((), (1, 1)), + ((0, 0, 0), ()), 1) + + mgf = moment_generating_function(Laplace('x', 1, 1))(t) + assert mgf.diff(t).subs(t, 0) == 1 + + mgf = moment_generating_function(Logistic('x', 1, 1))(t) + assert mgf.diff(t).subs(t, 0) == beta(1, 1) + + mgf = moment_generating_function(Normal('x', 0, 1))(t) + assert mgf.diff(t).subs(t, 1) == exp(S.Half) + + mgf = moment_generating_function(Pareto('x', 1, 1))(t) + assert mgf.diff(t).subs(t, 0) == expint(1, 0) + + mgf = moment_generating_function(QuadraticU('x', 1, 2))(t) + assert mgf.diff(t).subs(t, 1) == -12*e - 3*exp(2) + + mgf = moment_generating_function(RaisedCosine('x', 1, 1))(t) + assert mgf.diff(t).subs(t, 1) == -2*e*pi**2*sinh(1)/\ + (1 + pi**2)**2 + e*pi**2*cosh(1)/(1 + pi**2) + + mgf = moment_generating_function(Rayleigh('x', 1))(t) + assert mgf.diff(t).subs(t, 0) == sqrt(2)*sqrt(pi)/2 + + mgf = moment_generating_function(Triangular('x', 1, 3, 2))(t) + assert mgf.diff(t).subs(t, 1) == -e + exp(3) + + mgf = moment_generating_function(Uniform('x', 0, 1))(t) + assert mgf.diff(t).subs(t, 1) == 1 + + mgf = moment_generating_function(UniformSum('x', 1))(t) + assert mgf.diff(t).subs(t, 1) == 1 + + mgf = moment_generating_function(WignerSemicircle('x', 1))(t) + assert mgf.diff(t).subs(t, 1) == -2*besseli(1, 1) + besseli(2, 1) +\ + besseli(0, 1) + + +def test_ContinuousRV(): + pdf = sqrt(2)*exp(-x**2/2)/(2*sqrt(pi)) # Normal distribution + # X and Y should be equivalent + X = ContinuousRV(x, pdf, check=True) + Y = Normal('y', 0, 1) + + assert variance(X) == variance(Y) + assert P(X > 0) == P(Y > 0) + Z = ContinuousRV(z, exp(-z), set=Interval(0, oo)) + assert Z.pspace.domain.set == Interval(0, oo) + assert E(Z) == 1 + assert P(Z > 5) == exp(-5) + raises(ValueError, lambda: ContinuousRV(z, exp(-z), set=Interval(0, 10), check=True)) + + # the correct pdf for Gamma(k, theta) but the integral in `check` + # integrates to something equivalent to 1 and not to 1 exactly + _x, k, theta = symbols("x k theta", positive=True) + pdf = 1/(gamma(k)*theta**k)*_x**(k-1)*exp(-_x/theta) + X = ContinuousRV(_x, pdf, set=Interval(0, oo)) + Y = Gamma('y', k, theta) + assert (E(X) - E(Y)).simplify() == 0 + assert (variance(X) - variance(Y)).simplify() == 0 + + +def test_arcsin(): + + a = Symbol("a", real=True) + b = Symbol("b", real=True) + + X = Arcsin('x', a, b) + assert density(X)(x) == 1/(pi*sqrt((-x + b)*(x - a))) + assert cdf(X)(x) == Piecewise((0, a > x), + (2*asin(sqrt((-a + x)/(-a + b)))/pi, b >= x), + (1, True)) + assert pspace(X).domain.set == Interval(a, b) + +def test_benini(): + alpha = Symbol("alpha", positive=True) + beta = Symbol("beta", positive=True) + sigma = Symbol("sigma", positive=True) + X = Benini('x', alpha, beta, sigma) + + assert density(X)(x) == ((alpha/x + 2*beta*log(x/sigma)/x) + *exp(-alpha*log(x/sigma) - beta*log(x/sigma)**2)) + + assert pspace(X).domain.set == Interval(sigma, oo) + raises(NotImplementedError, lambda: moment_generating_function(X)) + alpha = Symbol("alpha", nonpositive=True) + raises(ValueError, lambda: Benini('x', alpha, beta, sigma)) + + beta = Symbol("beta", nonpositive=True) + raises(ValueError, lambda: Benini('x', alpha, beta, sigma)) + + alpha = Symbol("alpha", positive=True) + raises(ValueError, lambda: Benini('x', alpha, beta, sigma)) + + beta = Symbol("beta", positive=True) + sigma = Symbol("sigma", nonpositive=True) + raises(ValueError, lambda: Benini('x', alpha, beta, sigma)) + +def test_beta(): + a, b = symbols('alpha beta', positive=True) + B = Beta('x', a, b) + + assert pspace(B).domain.set == Interval(0, 1) + assert characteristic_function(B)(x) == hyper((a,), (a + b,), I*x) + assert density(B)(x) == x**(a - 1)*(1 - x)**(b - 1)/beta(a, b) + + assert simplify(E(B)) == a / (a + b) + assert simplify(variance(B)) == a*b / (a**3 + 3*a**2*b + a**2 + 3*a*b**2 + 2*a*b + b**3 + b**2) + + # Full symbolic solution is too much, test with numeric version + a, b = 1, 2 + B = Beta('x', a, b) + assert expand_func(E(B)) == a / S(a + b) + assert expand_func(variance(B)) == (a*b) / S((a + b)**2 * (a + b + 1)) + assert median(B) == FiniteSet(1 - 1/sqrt(2)) + +def test_beta_noncentral(): + a, b = symbols('a b', positive=True) + c = Symbol('c', nonnegative=True) + _k = Dummy('k') + + X = BetaNoncentral('x', a, b, c) + + assert pspace(X).domain.set == Interval(0, 1) + + dens = density(X) + z = Symbol('z') + + res = Sum( z**(_k + a - 1)*(c/2)**_k*(1 - z)**(b - 1)*exp(-c/2)/ + (beta(_k + a, b)*factorial(_k)), (_k, 0, oo)) + assert dens(z).dummy_eq(res) + + # BetaCentral should not raise if the assumptions + # on the symbols can not be determined + a, b, c = symbols('a b c') + assert BetaNoncentral('x', a, b, c) + + a = Symbol('a', positive=False, real=True) + raises(ValueError, lambda: BetaNoncentral('x', a, b, c)) + + a = Symbol('a', positive=True) + b = Symbol('b', positive=False, real=True) + raises(ValueError, lambda: BetaNoncentral('x', a, b, c)) + + a = Symbol('a', positive=True) + b = Symbol('b', positive=True) + c = Symbol('c', nonnegative=False, real=True) + raises(ValueError, lambda: BetaNoncentral('x', a, b, c)) + +def test_betaprime(): + alpha = Symbol("alpha", positive=True) + + betap = Symbol("beta", positive=True) + + X = BetaPrime('x', alpha, betap) + assert density(X)(x) == x**(alpha - 1)*(x + 1)**(-alpha - betap)/beta(alpha, betap) + + alpha = Symbol("alpha", nonpositive=True) + raises(ValueError, lambda: BetaPrime('x', alpha, betap)) + + alpha = Symbol("alpha", positive=True) + betap = Symbol("beta", nonpositive=True) + raises(ValueError, lambda: BetaPrime('x', alpha, betap)) + X = BetaPrime('x', 1, 1) + assert median(X) == FiniteSet(1) + + +def test_BoundedPareto(): + L, H = symbols('L, H', negative=True) + raises(ValueError, lambda: BoundedPareto('X', 1, L, H)) + L, H = symbols('L, H', real=False) + raises(ValueError, lambda: BoundedPareto('X', 1, L, H)) + L, H = symbols('L, H', positive=True) + raises(ValueError, lambda: BoundedPareto('X', -1, L, H)) + + X = BoundedPareto('X', 2, L, H) + assert X.pspace.domain.set == Interval(L, H) + assert density(X)(x) == 2*L**2/(x**3*(1 - L**2/H**2)) + assert cdf(X)(x) == Piecewise((-H**2*L**2/(x**2*(H**2 - L**2)) \ + + H**2/(H**2 - L**2), L <= x), (0, True)) + assert E(X).simplify() == 2*H*L/(H + L) + X = BoundedPareto('X', 1, 2, 4) + assert E(X).simplify() == log(16) + assert median(X) == FiniteSet(Rational(8, 3)) + assert variance(X).simplify() == 8 - 16*log(2)**2 + + +def test_cauchy(): + x0 = Symbol("x0", real=True) + gamma = Symbol("gamma", positive=True) + p = Symbol("p", positive=True) + + X = Cauchy('x', x0, gamma) + # Tests the characteristic function + assert characteristic_function(X)(x) == exp(-gamma*Abs(x) + I*x*x0) + raises(NotImplementedError, lambda: moment_generating_function(X)) + assert density(X)(x) == 1/(pi*gamma*(1 + (x - x0)**2/gamma**2)) + assert diff(cdf(X)(x), x) == density(X)(x) + assert quantile(X)(p) == gamma*tan(pi*(p - S.Half)) + x0 + + x1 = Symbol("x1", real=False) + raises(ValueError, lambda: Cauchy('x', x1, gamma)) + gamma = Symbol("gamma", nonpositive=True) + raises(ValueError, lambda: Cauchy('x', x0, gamma)) + assert median(X) == FiniteSet(x0) + +def test_chi(): + from sympy.core.numbers import I + k = Symbol("k", integer=True) + + X = Chi('x', k) + assert density(X)(x) == 2**(-k/2 + 1)*x**(k - 1)*exp(-x**2/2)/gamma(k/2) + + # Tests the characteristic function + assert characteristic_function(X)(x) == sqrt(2)*I*x*gamma(k/2 + S(1)/2)*hyper((k/2 + S(1)/2,), + (S(3)/2,), -x**2/2)/gamma(k/2) + hyper((k/2,), (S(1)/2,), -x**2/2) + + # Tests the moment generating function + assert moment_generating_function(X)(x) == sqrt(2)*x*gamma(k/2 + S(1)/2)*hyper((k/2 + S(1)/2,), + (S(3)/2,), x**2/2)/gamma(k/2) + hyper((k/2,), (S(1)/2,), x**2/2) + + k = Symbol("k", integer=True, positive=False) + raises(ValueError, lambda: Chi('x', k)) + + k = Symbol("k", integer=False, positive=True) + raises(ValueError, lambda: Chi('x', k)) + +def test_chi_noncentral(): + k = Symbol("k", integer=True) + l = Symbol("l") + + X = ChiNoncentral("x", k, l) + assert density(X)(x) == (x**k*l*(x*l)**(-k/2)* + exp(-x**2/2 - l**2/2)*besseli(k/2 - 1, x*l)) + + k = Symbol("k", integer=True, positive=False) + raises(ValueError, lambda: ChiNoncentral('x', k, l)) + + k = Symbol("k", integer=True, positive=True) + l = Symbol("l", nonpositive=True) + raises(ValueError, lambda: ChiNoncentral('x', k, l)) + + k = Symbol("k", integer=False) + l = Symbol("l", positive=True) + raises(ValueError, lambda: ChiNoncentral('x', k, l)) + + +def test_chi_squared(): + k = Symbol("k", integer=True) + X = ChiSquared('x', k) + + # Tests the characteristic function + assert characteristic_function(X)(x) == ((-2*I*x + 1)**(-k/2)) + + assert density(X)(x) == 2**(-k/2)*x**(k/2 - 1)*exp(-x/2)/gamma(k/2) + assert cdf(X)(x) == Piecewise((lowergamma(k/2, x/2)/gamma(k/2), x >= 0), (0, True)) + assert E(X) == k + assert variance(X) == 2*k + + X = ChiSquared('x', 15) + assert cdf(X)(3) == -14873*sqrt(6)*exp(Rational(-3, 2))/(5005*sqrt(pi)) + erf(sqrt(6)/2) + + k = Symbol("k", integer=True, positive=False) + raises(ValueError, lambda: ChiSquared('x', k)) + + k = Symbol("k", integer=False, positive=True) + raises(ValueError, lambda: ChiSquared('x', k)) + + +def test_dagum(): + p = Symbol("p", positive=True) + b = Symbol("b", positive=True) + a = Symbol("a", positive=True) + + X = Dagum('x', p, a, b) + assert density(X)(x) == a*p*(x/b)**(a*p)*((x/b)**a + 1)**(-p - 1)/x + assert cdf(X)(x) == Piecewise(((1 + (x/b)**(-a))**(-p), x >= 0), + (0, True)) + + p = Symbol("p", nonpositive=True) + raises(ValueError, lambda: Dagum('x', p, a, b)) + + p = Symbol("p", positive=True) + b = Symbol("b", nonpositive=True) + raises(ValueError, lambda: Dagum('x', p, a, b)) + + b = Symbol("b", positive=True) + a = Symbol("a", nonpositive=True) + raises(ValueError, lambda: Dagum('x', p, a, b)) + X = Dagum('x', 1, 1, 1) + assert median(X) == FiniteSet(1) + +def test_davis(): + b = Symbol("b", positive=True) + n = Symbol("n", positive=True) + mu = Symbol("mu", positive=True) + + X = Davis('x', b, n, mu) + dividend = b**n*(x - mu)**(-1-n) + divisor = (exp(b/(x-mu))-1)*(gamma(n)*zeta(n)) + assert density(X)(x) == dividend/divisor + + +def test_erlang(): + k = Symbol("k", integer=True, positive=True) + l = Symbol("l", positive=True) + + X = Erlang("x", k, l) + assert density(X)(x) == x**(k - 1)*l**k*exp(-x*l)/gamma(k) + assert cdf(X)(x) == Piecewise((lowergamma(k, l*x)/gamma(k), x > 0), + (0, True)) + + +def test_exgaussian(): + m, z = symbols("m, z") + s, l = symbols("s, l", positive=True) + X = ExGaussian("x", m, s, l) + + assert density(X)(z) == l*exp(l*(l*s**2 + 2*m - 2*z)/2) *\ + erfc(sqrt(2)*(l*s**2 + m - z)/(2*s))/2 + + # Note: actual_output simplifies to expected_output. + # Ideally cdf(X)(z) would return expected_output + # expected_output = (erf(sqrt(2)*(l*s**2 + m - z)/(2*s)) - 1)*exp(l*(l*s**2 + 2*m - 2*z)/2)/2 - erf(sqrt(2)*(m - z)/(2*s))/2 + S.Half + u = l*(z - m) + v = l*s + GaussianCDF1 = cdf(Normal('x', 0, v))(u) + GaussianCDF2 = cdf(Normal('x', v**2, v))(u) + actual_output = GaussianCDF1 - exp(-u + (v**2/2) + log(GaussianCDF2)) + assert cdf(X)(z) == actual_output + # assert simplify(actual_output) == expected_output + + assert variance(X).expand() == s**2 + l**(-2) + + assert skewness(X).expand() == 2/(l**3*s**2*sqrt(s**2 + l**(-2)) + l * + sqrt(s**2 + l**(-2))) + + +@slow +def test_exponential(): + rate = Symbol('lambda', positive=True) + X = Exponential('x', rate) + p = Symbol("p", positive=True, real=True) + + assert E(X) == 1/rate + assert variance(X) == 1/rate**2 + assert skewness(X) == 2 + assert skewness(X) == smoment(X, 3) + assert kurtosis(X) == 9 + assert kurtosis(X) == smoment(X, 4) + assert smoment(2*X, 4) == smoment(X, 4) + assert moment(X, 3) == 3*2*1/rate**3 + assert P(X > 0) is S.One + assert P(X > 1) == exp(-rate) + assert P(X > 10) == exp(-10*rate) + assert quantile(X)(p) == -log(1-p)/rate + + assert where(X <= 1).set == Interval(0, 1) + Y = Exponential('y', 1) + assert median(Y) == FiniteSet(log(2)) + #Test issue 9970 + z = Dummy('z') + assert P(X > z) == exp(-z*rate) + assert P(X < z) == 0 + #Test issue 10076 (Distribution with interval(0,oo)) + x = Symbol('x') + _z = Dummy('_z') + b = SingleContinuousPSpace(x, ExponentialDistribution(2)) + + with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed + expected1 = Integral(2*exp(-2*_z), (_z, 3, oo)) + assert b.probability(x > 3, evaluate=False).rewrite(Integral).dummy_eq(expected1) + + expected2 = Integral(2*exp(-2*_z), (_z, 0, 4)) + assert b.probability(x < 4, evaluate=False).rewrite(Integral).dummy_eq(expected2) + Y = Exponential('y', 2*rate) + assert coskewness(X, X, X) == skewness(X) + assert coskewness(X, Y + rate*X, Y + 2*rate*X) == \ + 4/(sqrt(1 + 1/(4*rate**2))*sqrt(4 + 1/(4*rate**2))) + assert coskewness(X + 2*Y, Y + X, Y + 2*X, X > 3) == \ + sqrt(170)*Rational(9, 85) + +def test_exponential_power(): + mu = Symbol('mu') + z = Symbol('z') + alpha = Symbol('alpha', positive=True) + beta = Symbol('beta', positive=True) + + X = ExponentialPower('x', mu, alpha, beta) + + assert density(X)(z) == beta*exp(-(Abs(mu - z)/alpha) + ** beta)/(2*alpha*gamma(1/beta)) + assert cdf(X)(z) == S.Half + lowergamma(1/beta, + (Abs(mu - z)/alpha)**beta)*sign(-mu + z)/\ + (2*gamma(1/beta)) + + +def test_f_distribution(): + d1 = Symbol("d1", positive=True) + d2 = Symbol("d2", positive=True) + + X = FDistribution("x", d1, d2) + + assert density(X)(x) == (d2**(d2/2)*sqrt((d1*x)**d1*(d1*x + d2)**(-d1 - d2)) + /(x*beta(d1/2, d2/2))) + + raises(NotImplementedError, lambda: moment_generating_function(X)) + d1 = Symbol("d1", nonpositive=True) + raises(ValueError, lambda: FDistribution('x', d1, d1)) + + d1 = Symbol("d1", positive=True, integer=False) + raises(ValueError, lambda: FDistribution('x', d1, d1)) + + d1 = Symbol("d1", positive=True) + d2 = Symbol("d2", nonpositive=True) + raises(ValueError, lambda: FDistribution('x', d1, d2)) + + d2 = Symbol("d2", positive=True, integer=False) + raises(ValueError, lambda: FDistribution('x', d1, d2)) + + +def test_fisher_z(): + d1 = Symbol("d1", positive=True) + d2 = Symbol("d2", positive=True) + + X = FisherZ("x", d1, d2) + assert density(X)(x) == (2*d1**(d1/2)*d2**(d2/2)*(d1*exp(2*x) + d2) + **(-d1/2 - d2/2)*exp(d1*x)/beta(d1/2, d2/2)) + +def test_frechet(): + a = Symbol("a", positive=True) + s = Symbol("s", positive=True) + m = Symbol("m", real=True) + + X = Frechet("x", a, s=s, m=m) + assert density(X)(x) == a*((x - m)/s)**(-a - 1)*exp(-((x - m)/s)**(-a))/s + assert cdf(X)(x) == Piecewise((exp(-((-m + x)/s)**(-a)), m <= x), (0, True)) + +@slow +def test_gamma(): + k = Symbol("k", positive=True) + theta = Symbol("theta", positive=True) + + X = Gamma('x', k, theta) + + # Tests characteristic function + assert characteristic_function(X)(x) == ((-I*theta*x + 1)**(-k)) + + assert density(X)(x) == x**(k - 1)*theta**(-k)*exp(-x/theta)/gamma(k) + assert cdf(X, meijerg=True)(z) == Piecewise( + (-k*lowergamma(k, 0)/gamma(k + 1) + + k*lowergamma(k, z/theta)/gamma(k + 1), z >= 0), + (0, True)) + + # assert simplify(variance(X)) == k*theta**2 # handled numerically below + assert E(X) == moment(X, 1) + + k, theta = symbols('k theta', positive=True) + X = Gamma('x', k, theta) + assert E(X) == k*theta + assert variance(X) == k*theta**2 + assert skewness(X).expand() == 2/sqrt(k) + assert kurtosis(X).expand() == 3 + 6/k + + Y = Gamma('y', 2*k, 3*theta) + assert coskewness(X, theta*X + Y, k*X + Y).simplify() == \ + 2*531441**(-k)*sqrt(k)*theta*(3*3**(12*k) - 2*531441**k) \ + /(sqrt(k**2 + 18)*sqrt(theta**2 + 18)) + +def test_gamma_inverse(): + a = Symbol("a", positive=True) + b = Symbol("b", positive=True) + X = GammaInverse("x", a, b) + assert density(X)(x) == x**(-a - 1)*b**a*exp(-b/x)/gamma(a) + assert cdf(X)(x) == Piecewise((uppergamma(a, b/x)/gamma(a), x > 0), (0, True)) + assert characteristic_function(X)(x) == 2 * (-I*b*x)**(a/2) \ + * besselk(a, 2*sqrt(b)*sqrt(-I*x))/gamma(a) + raises(NotImplementedError, lambda: moment_generating_function(X)) + +def test_gompertz(): + b = Symbol("b", positive=True) + eta = Symbol("eta", positive=True) + + X = Gompertz("x", b, eta) + + assert density(X)(x) == b*eta*exp(eta)*exp(b*x)*exp(-eta*exp(b*x)) + assert cdf(X)(x) == 1 - exp(eta)*exp(-eta*exp(b*x)) + assert diff(cdf(X)(x), x) == density(X)(x) + + +def test_gumbel(): + beta = Symbol("beta", positive=True) + mu = Symbol("mu") + x = Symbol("x") + y = Symbol("y") + X = Gumbel("x", beta, mu) + Y = Gumbel("y", beta, mu, minimum=True) + assert density(X)(x).expand() == \ + exp(mu/beta)*exp(-x/beta)*exp(-exp(mu/beta)*exp(-x/beta))/beta + assert density(Y)(y).expand() == \ + exp(-mu/beta)*exp(y/beta)*exp(-exp(-mu/beta)*exp(y/beta))/beta + assert cdf(X)(x).expand() == \ + exp(-exp(mu/beta)*exp(-x/beta)) + assert characteristic_function(X)(x) == exp(I*mu*x)*gamma(-I*beta*x + 1) + +def test_kumaraswamy(): + a = Symbol("a", positive=True) + b = Symbol("b", positive=True) + + X = Kumaraswamy("x", a, b) + assert density(X)(x) == x**(a - 1)*a*b*(-x**a + 1)**(b - 1) + assert cdf(X)(x) == Piecewise((0, x < 0), + (-(-x**a + 1)**b + 1, x <= 1), + (1, True)) + + +def test_laplace(): + mu = Symbol("mu") + b = Symbol("b", positive=True) + + X = Laplace('x', mu, b) + + #Tests characteristic_function + assert characteristic_function(X)(x) == (exp(I*mu*x)/(b**2*x**2 + 1)) + + assert density(X)(x) == exp(-Abs(x - mu)/b)/(2*b) + assert cdf(X)(x) == Piecewise((exp((-mu + x)/b)/2, mu > x), + (-exp((mu - x)/b)/2 + 1, True)) + X = Laplace('x', [1, 2], [[1, 0], [0, 1]]) + assert isinstance(pspace(X).distribution, MultivariateLaplaceDistribution) + +def test_levy(): + mu = Symbol("mu", real=True) + c = Symbol("c", positive=True) + + X = Levy('x', mu, c) + assert X.pspace.domain.set == Interval(mu, oo) + assert density(X)(x) == sqrt(c/(2*pi))*exp(-c/(2*(x - mu)))/((x - mu)**(S.One + S.Half)) + assert cdf(X)(x) == erfc(sqrt(c/(2*(x - mu)))) + + raises(NotImplementedError, lambda: moment_generating_function(X)) + mu = Symbol("mu", real=False) + raises(ValueError, lambda: Levy('x',mu,c)) + + c = Symbol("c", nonpositive=True) + raises(ValueError, lambda: Levy('x',mu,c)) + + mu = Symbol("mu", real=True) + raises(ValueError, lambda: Levy('x',mu,c)) + +def test_logcauchy(): + mu = Symbol("mu", positive=True) + sigma = Symbol("sigma", positive=True) + + X = LogCauchy("x", mu, sigma) + + assert density(X)(x) == sigma/(x*pi*(sigma**2 + (-mu + log(x))**2)) + assert cdf(X)(x) == atan((log(x) - mu)/sigma)/pi + S.Half + + +def test_logistic(): + mu = Symbol("mu", real=True) + s = Symbol("s", positive=True) + p = Symbol("p", positive=True) + + X = Logistic('x', mu, s) + + #Tests characteristics_function + assert characteristic_function(X)(x) == \ + (Piecewise((pi*s*x*exp(I*mu*x)/sinh(pi*s*x), Ne(x, 0)), (1, True))) + + assert density(X)(x) == exp((-x + mu)/s)/(s*(exp((-x + mu)/s) + 1)**2) + assert cdf(X)(x) == 1/(exp((mu - x)/s) + 1) + assert quantile(X)(p) == mu - s*log(-S.One + 1/p) + +def test_loglogistic(): + a, b = symbols('a b') + assert LogLogistic('x', a, b) + + a = Symbol('a', negative=True) + b = Symbol('b', positive=True) + raises(ValueError, lambda: LogLogistic('x', a, b)) + + a = Symbol('a', positive=True) + b = Symbol('b', negative=True) + raises(ValueError, lambda: LogLogistic('x', a, b)) + + a, b, z, p = symbols('a b z p', positive=True) + X = LogLogistic('x', a, b) + assert density(X)(z) == b*(z/a)**(b - 1)/(a*((z/a)**b + 1)**2) + assert cdf(X)(z) == 1/(1 + (z/a)**(-b)) + assert quantile(X)(p) == a*(p/(1 - p))**(1/b) + + # Expectation + assert E(X) == Piecewise((S.NaN, b <= 1), (pi*a/(b*sin(pi/b)), True)) + b = symbols('b', prime=True) # b > 1 + X = LogLogistic('x', a, b) + assert E(X) == pi*a/(b*sin(pi/b)) + X = LogLogistic('x', 1, 2) + assert median(X) == FiniteSet(1) + +def test_logitnormal(): + mu = Symbol('mu', real=True) + s = Symbol('s', positive=True) + X = LogitNormal('x', mu, s) + x = Symbol('x') + + assert density(X)(x) == sqrt(2)*exp(-(-mu + log(x/(1 - x)))**2/(2*s**2))/(2*sqrt(pi)*s*x*(1 - x)) + assert cdf(X)(x) == erf(sqrt(2)*(-mu + log(x/(1 - x)))/(2*s))/2 + S(1)/2 + +def test_lognormal(): + mean = Symbol('mu', real=True) + std = Symbol('sigma', positive=True) + X = LogNormal('x', mean, std) + # The sympy integrator can't do this too well + #assert E(X) == exp(mean+std**2/2) + #assert variance(X) == (exp(std**2)-1) * exp(2*mean + std**2) + + # The sympy integrator can't do this too well + #assert E(X) == + raises(NotImplementedError, lambda: moment_generating_function(X)) + mu = Symbol("mu", real=True) + sigma = Symbol("sigma", positive=True) + + X = LogNormal('x', mu, sigma) + assert density(X)(x) == (sqrt(2)*exp(-(-mu + log(x))**2 + /(2*sigma**2))/(2*x*sqrt(pi)*sigma)) + # Tests cdf + assert cdf(X)(x) == Piecewise( + (erf(sqrt(2)*(-mu + log(x))/(2*sigma))/2 + + S(1)/2, x > 0), (0, True)) + + X = LogNormal('x', 0, 1) # Mean 0, standard deviation 1 + assert density(X)(x) == sqrt(2)*exp(-log(x)**2/2)/(2*x*sqrt(pi)) + + +def test_Lomax(): + a, l = symbols('a, l', negative=True) + raises(ValueError, lambda: Lomax('X', a, l)) + a, l = symbols('a, l', real=False) + raises(ValueError, lambda: Lomax('X', a, l)) + + a, l = symbols('a, l', positive=True) + X = Lomax('X', a, l) + assert X.pspace.domain.set == Interval(0, oo) + assert density(X)(x) == a*(1 + x/l)**(-a - 1)/l + assert cdf(X)(x) == Piecewise((1 - (1 + x/l)**(-a), x >= 0), (0, True)) + a = 3 + X = Lomax('X', a, l) + assert E(X) == l/2 + assert median(X) == FiniteSet(l*(-1 + 2**Rational(1, 3))) + assert variance(X) == 3*l**2/4 + + +def test_maxwell(): + a = Symbol("a", positive=True) + + X = Maxwell('x', a) + + assert density(X)(x) == (sqrt(2)*x**2*exp(-x**2/(2*a**2))/ + (sqrt(pi)*a**3)) + assert E(X) == 2*sqrt(2)*a/sqrt(pi) + assert variance(X) == -8*a**2/pi + 3*a**2 + assert cdf(X)(x) == erf(sqrt(2)*x/(2*a)) - sqrt(2)*x*exp(-x**2/(2*a**2))/(sqrt(pi)*a) + assert diff(cdf(X)(x), x) == density(X)(x) + + +@slow +def test_Moyal(): + mu = Symbol('mu',real=False) + sigma = Symbol('sigma', positive=True) + raises(ValueError, lambda: Moyal('M',mu, sigma)) + + mu = Symbol('mu', real=True) + sigma = Symbol('sigma', negative=True) + raises(ValueError, lambda: Moyal('M',mu, sigma)) + + sigma = Symbol('sigma', positive=True) + M = Moyal('M', mu, sigma) + assert density(M)(z) == sqrt(2)*exp(-exp((mu - z)/sigma)/2 + - (-mu + z)/(2*sigma))/(2*sqrt(pi)*sigma) + assert cdf(M)(z).simplify() == 1 - erf(sqrt(2)*exp((mu - z)/(2*sigma))/2) + assert characteristic_function(M)(z) == 2**(-I*sigma*z)*exp(I*mu*z) \ + *gamma(-I*sigma*z + Rational(1, 2))/sqrt(pi) + assert E(M) == mu + EulerGamma*sigma + sigma*log(2) + assert moment_generating_function(M)(z) == 2**(-sigma*z)*exp(mu*z) \ + *gamma(-sigma*z + Rational(1, 2))/sqrt(pi) + + +def test_nakagami(): + mu = Symbol("mu", positive=True) + omega = Symbol("omega", positive=True) + + X = Nakagami('x', mu, omega) + assert density(X)(x) == (2*x**(2*mu - 1)*mu**mu*omega**(-mu) + *exp(-x**2*mu/omega)/gamma(mu)) + assert simplify(E(X)) == (sqrt(mu)*sqrt(omega) + *gamma(mu + S.Half)/gamma(mu + 1)) + assert simplify(variance(X)) == ( + omega - omega*gamma(mu + S.Half)**2/(gamma(mu)*gamma(mu + 1))) + assert cdf(X)(x) == Piecewise( + (lowergamma(mu, mu*x**2/omega)/gamma(mu), x > 0), + (0, True)) + X = Nakagami('x', 1, 1) + assert median(X) == FiniteSet(sqrt(log(2))) + +def test_gaussian_inverse(): + # test for symbolic parameters + a, b = symbols('a b') + assert GaussianInverse('x', a, b) + + # Inverse Gaussian distribution is also known as Wald distribution + # `GaussianInverse` can also be referred by the name `Wald` + a, b, z = symbols('a b z') + X = Wald('x', a, b) + assert density(X)(z) == sqrt(2)*sqrt(b/z**3)*exp(-b*(-a + z)**2/(2*a**2*z))/(2*sqrt(pi)) + + a, b = symbols('a b', positive=True) + z = Symbol('z', positive=True) + + X = GaussianInverse('x', a, b) + assert density(X)(z) == sqrt(2)*sqrt(b)*sqrt(z**(-3))*exp(-b*(-a + z)**2/(2*a**2*z))/(2*sqrt(pi)) + assert E(X) == a + assert variance(X).expand() == a**3/b + assert cdf(X)(z) == (S.Half - erf(sqrt(2)*sqrt(b)*(1 + z/a)/(2*sqrt(z)))/2)*exp(2*b/a) +\ + erf(sqrt(2)*sqrt(b)*(-1 + z/a)/(2*sqrt(z)))/2 + S.Half + + a = symbols('a', nonpositive=True) + raises(ValueError, lambda: GaussianInverse('x', a, b)) + + a = symbols('a', positive=True) + b = symbols('b', nonpositive=True) + raises(ValueError, lambda: GaussianInverse('x', a, b)) + +def test_pareto(): + xm, beta = symbols('xm beta', positive=True) + alpha = beta + 5 + X = Pareto('x', xm, alpha) + + dens = density(X) + + #Tests cdf function + assert cdf(X)(x) == \ + Piecewise((-x**(-beta - 5)*xm**(beta + 5) + 1, x >= xm), (0, True)) + + #Tests characteristic_function + assert characteristic_function(X)(x) == \ + ((-I*x*xm)**(beta + 5)*(beta + 5)*uppergamma(-beta - 5, -I*x*xm)) + + assert dens(x) == x**(-(alpha + 1))*xm**(alpha)*(alpha) + + assert simplify(E(X)) == alpha*xm/(alpha-1) + + # computation of taylor series for MGF still too slow + #assert simplify(variance(X)) == xm**2*alpha / ((alpha-1)**2*(alpha-2)) + + +def test_pareto_numeric(): + xm, beta = 3, 2 + alpha = beta + 5 + X = Pareto('x', xm, alpha) + + assert E(X) == alpha*xm/S(alpha - 1) + assert variance(X) == xm**2*alpha / S((alpha - 1)**2*(alpha - 2)) + assert median(X) == FiniteSet(3*2**Rational(1, 7)) + # Skewness tests too slow. Try shortcutting function? + + +def test_PowerFunction(): + alpha = Symbol("alpha", nonpositive=True) + a, b = symbols('a, b', real=True) + raises (ValueError, lambda: PowerFunction('x', alpha, a, b)) + + a, b = symbols('a, b', real=False) + raises (ValueError, lambda: PowerFunction('x', alpha, a, b)) + + alpha = Symbol("alpha", positive=True) + a, b = symbols('a, b', real=True) + raises (ValueError, lambda: PowerFunction('x', alpha, 5, 2)) + + X = PowerFunction('X', 2, a, b) + assert density(X)(z) == (-2*a + 2*z)/(-a + b)**2 + assert cdf(X)(z) == Piecewise((a**2/(a**2 - 2*a*b + b**2) - + 2*a*z/(a**2 - 2*a*b + b**2) + z**2/(a**2 - 2*a*b + b**2), a <= z), (0, True)) + + X = PowerFunction('X', 2, 0, 1) + assert density(X)(z) == 2*z + assert cdf(X)(z) == Piecewise((z**2, z >= 0), (0,True)) + assert E(X) == Rational(2,3) + assert P(X < 0) == 0 + assert P(X < 1) == 1 + assert median(X) == FiniteSet(1/sqrt(2)) + +def test_raised_cosine(): + mu = Symbol("mu", real=True) + s = Symbol("s", positive=True) + + X = RaisedCosine("x", mu, s) + + assert pspace(X).domain.set == Interval(mu - s, mu + s) + #Tests characteristics_function + assert characteristic_function(X)(x) == \ + Piecewise((exp(-I*pi*mu/s)/2, Eq(x, -pi/s)), (exp(I*pi*mu/s)/2, Eq(x, pi/s)), (pi**2*exp(I*mu*x)*sin(s*x)/(s*x*(-s**2*x**2 + pi**2)), True)) + + assert density(X)(x) == (Piecewise(((cos(pi*(x - mu)/s) + 1)/(2*s), + And(x <= mu + s, mu - s <= x)), (0, True))) + + +def test_rayleigh(): + sigma = Symbol("sigma", positive=True) + + X = Rayleigh('x', sigma) + + #Tests characteristic_function + assert characteristic_function(X)(x) == (-sqrt(2)*sqrt(pi)*sigma*x*(erfi(sqrt(2)*sigma*x/2) - I)*exp(-sigma**2*x**2/2)/2 + 1) + + assert density(X)(x) == x*exp(-x**2/(2*sigma**2))/sigma**2 + assert E(X) == sqrt(2)*sqrt(pi)*sigma/2 + assert variance(X) == -pi*sigma**2/2 + 2*sigma**2 + assert cdf(X)(x) == 1 - exp(-x**2/(2*sigma**2)) + assert diff(cdf(X)(x), x) == density(X)(x) + +def test_reciprocal(): + a = Symbol("a", real=True) + b = Symbol("b", real=True) + + X = Reciprocal('x', a, b) + assert density(X)(x) == 1/(x*(-log(a) + log(b))) + assert cdf(X)(x) == Piecewise((log(a)/(log(a) - log(b)) - log(x)/(log(a) - log(b)), a <= x), (0, True)) + X = Reciprocal('x', 5, 30) + + assert E(X) == 25/(log(30) - log(5)) + assert P(X < 4) == S.Zero + assert P(X < 20) == log(20) / (log(30) - log(5)) - log(5) / (log(30) - log(5)) + assert cdf(X)(10) == log(10) / (log(30) - log(5)) - log(5) / (log(30) - log(5)) + + a = symbols('a', nonpositive=True) + raises(ValueError, lambda: Reciprocal('x', a, b)) + + a = symbols('a', positive=True) + b = symbols('b', positive=True) + raises(ValueError, lambda: Reciprocal('x', a + b, a)) + +def test_shiftedgompertz(): + b = Symbol("b", positive=True) + eta = Symbol("eta", positive=True) + X = ShiftedGompertz("x", b, eta) + assert density(X)(x) == b*(eta*(1 - exp(-b*x)) + 1)*exp(-b*x)*exp(-eta*exp(-b*x)) + + +def test_studentt(): + nu = Symbol("nu", positive=True) + + X = StudentT('x', nu) + assert density(X)(x) == (1 + x**2/nu)**(-nu/2 - S.Half)/(sqrt(nu)*beta(S.Half, nu/2)) + assert cdf(X)(x) == S.Half + x*gamma(nu/2 + S.Half)*hyper((S.Half, nu/2 + S.Half), + (Rational(3, 2),), -x**2/nu)/(sqrt(pi)*sqrt(nu)*gamma(nu/2)) + raises(NotImplementedError, lambda: moment_generating_function(X)) + +def test_trapezoidal(): + a = Symbol("a", real=True) + b = Symbol("b", real=True) + c = Symbol("c", real=True) + d = Symbol("d", real=True) + + X = Trapezoidal('x', a, b, c, d) + assert density(X)(x) == Piecewise(((-2*a + 2*x)/((-a + b)*(-a - b + c + d)), (a <= x) & (x < b)), + (2/(-a - b + c + d), (b <= x) & (x < c)), + ((2*d - 2*x)/((-c + d)*(-a - b + c + d)), (c <= x) & (x <= d)), + (0, True)) + + X = Trapezoidal('x', 0, 1, 2, 3) + assert E(X) == Rational(3, 2) + assert variance(X) == Rational(5, 12) + assert P(X < 2) == Rational(3, 4) + assert median(X) == FiniteSet(Rational(3, 2)) + +def test_triangular(): + a = Symbol("a") + b = Symbol("b") + c = Symbol("c") + + X = Triangular('x', a, b, c) + assert pspace(X).domain.set == Interval(a, b) + assert str(density(X)(x)) == ("Piecewise(((-2*a + 2*x)/((-a + b)*(-a + c)), (a <= x) & (c > x)), " + "(2/(-a + b), Eq(c, x)), ((2*b - 2*x)/((-a + b)*(b - c)), (b >= x) & (c < x)), (0, True))") + + #Tests moment_generating_function + assert moment_generating_function(X)(x).expand() == \ + ((-2*(-a + b)*exp(c*x) + 2*(-a + c)*exp(b*x) + 2*(b - c)*exp(a*x))/(x**2*(-a + b)*(-a + c)*(b - c))).expand() + assert str(characteristic_function(X)(x)) == \ + '(2*(-a + b)*exp(I*c*x) - 2*(-a + c)*exp(I*b*x) - 2*(b - c)*exp(I*a*x))/(x**2*(-a + b)*(-a + c)*(b - c))' + +def test_quadratic_u(): + a = Symbol("a", real=True) + b = Symbol("b", real=True) + + X = QuadraticU("x", a, b) + Y = QuadraticU("x", 1, 2) + + assert pspace(X).domain.set == Interval(a, b) + # Tests _moment_generating_function + assert moment_generating_function(Y)(1) == -15*exp(2) + 27*exp(1) + assert moment_generating_function(Y)(2) == -9*exp(4)/2 + 21*exp(2)/2 + + assert characteristic_function(Y)(1) == 3*I*(-1 + 4*I)*exp(I*exp(2*I)) + assert density(X)(x) == (Piecewise((12*(x - a/2 - b/2)**2/(-a + b)**3, + And(x <= b, a <= x)), (0, True))) + + +def test_uniform(): + l = Symbol('l', real=True) + w = Symbol('w', positive=True) + X = Uniform('x', l, l + w) + + assert E(X) == l + w/2 + assert variance(X).expand() == w**2/12 + + # With numbers all is well + X = Uniform('x', 3, 5) + assert P(X < 3) == 0 and P(X > 5) == 0 + assert P(X < 4) == P(X > 4) == S.Half + assert median(X) == FiniteSet(4) + + z = Symbol('z') + p = density(X)(z) + assert p.subs(z, 3.7) == S.Half + assert p.subs(z, -1) == 0 + assert p.subs(z, 6) == 0 + + c = cdf(X) + assert c(2) == 0 and c(3) == 0 + assert c(Rational(7, 2)) == Rational(1, 4) + assert c(5) == 1 and c(6) == 1 + + +@XFAIL +@slow +def test_uniform_P(): + """ This stopped working because SingleContinuousPSpace.compute_density no + longer calls integrate on a DiracDelta but rather just solves directly. + integrate used to call UniformDistribution.expectation which special-cased + subsed out the Min and Max terms that Uniform produces + + I decided to regress on this class for general cleanliness (and I suspect + speed) of the algorithm. + """ + l = Symbol('l', real=True) + w = Symbol('w', positive=True) + X = Uniform('x', l, l + w) + assert P(X < l) == 0 and P(X > l + w) == 0 + + +def test_uniformsum(): + n = Symbol("n", integer=True) + _k = Dummy("k") + x = Symbol("x") + + X = UniformSum('x', n) + res = Sum((-1)**_k*(-_k + x)**(n - 1)*binomial(n, _k), (_k, 0, floor(x)))/factorial(n - 1) + assert density(X)(x).dummy_eq(res) + + #Tests set functions + assert X.pspace.domain.set == Interval(0, n) + + #Tests the characteristic_function + assert characteristic_function(X)(x) == (-I*(exp(I*x) - 1)/x)**n + + #Tests the moment_generating_function + assert moment_generating_function(X)(x) == ((exp(x) - 1)/x)**n + + +def test_von_mises(): + mu = Symbol("mu") + k = Symbol("k", positive=True) + + X = VonMises("x", mu, k) + assert density(X)(x) == exp(k*cos(x - mu))/(2*pi*besseli(0, k)) + + +def test_weibull(): + a, b = symbols('a b', positive=True) + # FIXME: simplify(E(X)) seems to hang without extended_positive=True + # On a Linux machine this had a rapid memory leak... + # a, b = symbols('a b', positive=True) + X = Weibull('x', a, b) + + assert E(X).expand() == a * gamma(1 + 1/b) + assert variance(X).expand() == (a**2 * gamma(1 + 2/b) - E(X)**2).expand() + assert simplify(skewness(X)) == (2*gamma(1 + 1/b)**3 - 3*gamma(1 + 1/b)*gamma(1 + 2/b) + gamma(1 + 3/b))/(-gamma(1 + 1/b)**2 + gamma(1 + 2/b))**Rational(3, 2) + assert simplify(kurtosis(X)) == (-3*gamma(1 + 1/b)**4 +\ + 6*gamma(1 + 1/b)**2*gamma(1 + 2/b) - 4*gamma(1 + 1/b)*gamma(1 + 3/b) + gamma(1 + 4/b))/(gamma(1 + 1/b)**2 - gamma(1 + 2/b))**2 + +def test_weibull_numeric(): + # Test for integers and rationals + a = 1 + bvals = [S.Half, 1, Rational(3, 2), 5] + for b in bvals: + X = Weibull('x', a, b) + assert simplify(E(X)) == expand_func(a * gamma(1 + 1/S(b))) + assert simplify(variance(X)) == simplify( + a**2 * gamma(1 + 2/S(b)) - E(X)**2) + # Not testing Skew... it's slow with int/frac values > 3/2 + + +def test_wignersemicircle(): + R = Symbol("R", positive=True) + + X = WignerSemicircle('x', R) + assert pspace(X).domain.set == Interval(-R, R) + assert density(X)(x) == 2*sqrt(-x**2 + R**2)/(pi*R**2) + assert E(X) == 0 + + + #Tests ChiNoncentralDistribution + assert characteristic_function(X)(x) == \ + Piecewise((2*besselj(1, R*x)/(R*x), Ne(x, 0)), (1, True)) + + +def test_input_value_assertions(): + a, b = symbols('a b') + p, q = symbols('p q', positive=True) + m, n = symbols('m n', positive=False, real=True) + + raises(ValueError, lambda: Normal('x', 3, 0)) + raises(ValueError, lambda: Normal('x', m, n)) + Normal('X', a, p) # No error raised + raises(ValueError, lambda: Exponential('x', m)) + Exponential('Ex', p) # No error raised + for fn in [Pareto, Weibull, Beta, Gamma]: + raises(ValueError, lambda: fn('x', m, p)) + raises(ValueError, lambda: fn('x', p, n)) + fn('x', p, q) # No error raised + + +def test_unevaluated(): + X = Normal('x', 0, 1) + k = Dummy('k') + expr1 = Integral(sqrt(2)*k*exp(-k**2/2)/(2*sqrt(pi)), (k, -oo, oo)) + expr2 = Integral(sqrt(2)*exp(-k**2/2)/(2*sqrt(pi)), (k, 0, oo)) + with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed + assert E(X, evaluate=False).rewrite(Integral).dummy_eq(expr1) + assert E(X + 1, evaluate=False).rewrite(Integral).dummy_eq(expr1 + 1) + assert P(X > 0, evaluate=False).rewrite(Integral).dummy_eq(expr2) + + assert P(X > 0, X**2 < 1) == S.Half + + +def test_probability_unevaluated(): + T = Normal('T', 30, 3) + with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed + assert type(P(T > 33, evaluate=False)) == Probability + + +def test_density_unevaluated(): + X = Normal('X', 0, 1) + Y = Normal('Y', 0, 2) + assert isinstance(density(X+Y, evaluate=False)(z), Integral) + + +def test_NormalDistribution(): + nd = NormalDistribution(0, 1) + x = Symbol('x') + assert nd.cdf(x) == erf(sqrt(2)*x/2)/2 + S.Half + assert nd.expectation(1, x) == 1 + assert nd.expectation(x, x) == 0 + assert nd.expectation(x**2, x) == 1 + #Test issue 10076 + a = SingleContinuousPSpace(x, NormalDistribution(2, 4)) + _z = Dummy('_z') + + expected1 = Integral(sqrt(2)*exp(-(_z - 2)**2/32)/(8*sqrt(pi)),(_z, -oo, 1)) + assert a.probability(x < 1, evaluate=False).dummy_eq(expected1) is True + + expected2 = Integral(sqrt(2)*exp(-(_z - 2)**2/32)/(8*sqrt(pi)),(_z, 1, oo)) + assert a.probability(x > 1, evaluate=False).dummy_eq(expected2) is True + + b = SingleContinuousPSpace(x, NormalDistribution(1, 9)) + + expected3 = Integral(sqrt(2)*exp(-(_z - 1)**2/162)/(18*sqrt(pi)),(_z, 6, oo)) + assert b.probability(x > 6, evaluate=False).dummy_eq(expected3) is True + + expected4 = Integral(sqrt(2)*exp(-(_z - 1)**2/162)/(18*sqrt(pi)),(_z, -oo, 6)) + assert b.probability(x < 6, evaluate=False).dummy_eq(expected4) is True + + +def test_random_parameters(): + mu = Normal('mu', 2, 3) + meas = Normal('T', mu, 1) + assert density(meas, evaluate=False)(z) + assert isinstance(pspace(meas), CompoundPSpace) + X = Normal('x', [1, 2], [[1, 0], [0, 1]]) + assert isinstance(pspace(X).distribution, MultivariateNormalDistribution) + assert density(meas)(z).simplify() == sqrt(5)*exp(-z**2/20 + z/5 - S(1)/5)/(10*sqrt(pi)) + + +def test_random_parameters_given(): + mu = Normal('mu', 2, 3) + meas = Normal('T', mu, 1) + assert given(meas, Eq(mu, 5)) == Normal('T', 5, 1) + + +def test_conjugate_priors(): + mu = Normal('mu', 2, 3) + x = Normal('x', mu, 1) + assert isinstance(simplify(density(mu, Eq(x, y), evaluate=False)(z)), + Mul) + + +def test_difficult_univariate(): + """ Since using solve in place of deltaintegrate we're able to perform + substantially more complex density computations on single continuous random + variables """ + x = Normal('x', 0, 1) + assert density(x**3) + assert density(exp(x**2)) + assert density(log(x)) + + +def test_issue_10003(): + X = Exponential('x', 3) + G = Gamma('g', 1, 2) + assert P(X < -1) is S.Zero + assert P(G < -1) is S.Zero + + +def test_precomputed_cdf(): + x = symbols("x", real=True) + mu = symbols("mu", real=True) + sigma, xm, alpha = symbols("sigma xm alpha", positive=True) + n = symbols("n", integer=True, positive=True) + distribs = [ + Normal("X", mu, sigma), + Pareto("P", xm, alpha), + ChiSquared("C", n), + Exponential("E", sigma), + # LogNormal("L", mu, sigma), + ] + for X in distribs: + compdiff = cdf(X)(x) - simplify(X.pspace.density.compute_cdf()(x)) + compdiff = simplify(compdiff.rewrite(erfc)) + assert compdiff == 0 + + +@slow +def test_precomputed_characteristic_functions(): + import mpmath + + def test_cf(dist, support_lower_limit, support_upper_limit): + pdf = density(dist) + t = Symbol('t') + + # first function is the hardcoded CF of the distribution + cf1 = lambdify([t], characteristic_function(dist)(t), 'mpmath') + + # second function is the Fourier transform of the density function + f = lambdify([x, t], pdf(x)*exp(I*x*t), 'mpmath') + cf2 = lambda t: mpmath.quad(lambda x: f(x, t), [support_lower_limit, support_upper_limit], maxdegree=10) + + # compare the two functions at various points + for test_point in [2, 5, 8, 11]: + n1 = cf1(test_point) + n2 = cf2(test_point) + + assert abs(re(n1) - re(n2)) < 1e-12 + assert abs(im(n1) - im(n2)) < 1e-12 + + test_cf(Beta('b', 1, 2), 0, 1) + test_cf(Chi('c', 3), 0, mpmath.inf) + test_cf(ChiSquared('c', 2), 0, mpmath.inf) + test_cf(Exponential('e', 6), 0, mpmath.inf) + test_cf(Logistic('l', 1, 2), -mpmath.inf, mpmath.inf) + test_cf(Normal('n', -1, 5), -mpmath.inf, mpmath.inf) + test_cf(RaisedCosine('r', 3, 1), 2, 4) + test_cf(Rayleigh('r', 0.5), 0, mpmath.inf) + test_cf(Uniform('u', -1, 1), -1, 1) + test_cf(WignerSemicircle('w', 3), -3, 3) + + +def test_long_precomputed_cdf(): + x = symbols("x", real=True) + distribs = [ + Arcsin("A", -5, 9), + Dagum("D", 4, 10, 3), + Erlang("E", 14, 5), + Frechet("F", 2, 6, -3), + Gamma("G", 2, 7), + GammaInverse("GI", 3, 5), + Kumaraswamy("K", 6, 8), + Laplace("LA", -5, 4), + Logistic("L", -6, 7), + Nakagami("N", 2, 7), + StudentT("S", 4) + ] + for distr in distribs: + for _ in range(5): + assert tn(diff(cdf(distr)(x), x), density(distr)(x), x, a=0, b=0, c=1, d=0) + + US = UniformSum("US", 5) + pdf01 = density(US)(x).subs(floor(x), 0).doit() # pdf on (0, 1) + cdf01 = cdf(US, evaluate=False)(x).subs(floor(x), 0).doit() # cdf on (0, 1) + assert tn(diff(cdf01, x), pdf01, x, a=0, b=0, c=1, d=0) + + +def test_issue_13324(): + X = Uniform('X', 0, 1) + assert E(X, X > S.Half) == Rational(3, 4) + assert E(X, X > 0) == S.Half + +def test_issue_20756(): + X = Uniform('X', -1, +1) + Y = Uniform('Y', -1, +1) + assert E(X * Y) == S.Zero + assert E(X * ((Y + 1) - 1)) == S.Zero + assert E(Y * (X*(X + 1) - X*X)) == S.Zero + +def test_FiniteSet_prob(): + E = Exponential('E', 3) + N = Normal('N', 5, 7) + assert P(Eq(E, 1)) is S.Zero + assert P(Eq(N, 2)) is S.Zero + assert P(Eq(N, x)) is S.Zero + +def test_prob_neq(): + E = Exponential('E', 4) + X = ChiSquared('X', 4) + assert P(Ne(E, 2)) == 1 + assert P(Ne(X, 4)) == 1 + assert P(Ne(X, 4)) == 1 + assert P(Ne(X, 5)) == 1 + assert P(Ne(E, x)) == 1 + +def test_union(): + N = Normal('N', 3, 2) + assert simplify(P(N**2 - N > 2)) == \ + -erf(sqrt(2))/2 - erfc(sqrt(2)/4)/2 + Rational(3, 2) + assert simplify(P(N**2 - 4 > 0)) == \ + -erf(5*sqrt(2)/4)/2 - erfc(sqrt(2)/4)/2 + Rational(3, 2) + +def test_Or(): + N = Normal('N', 0, 1) + assert simplify(P(Or(N > 2, N < 1))) == \ + -erf(sqrt(2))/2 - erfc(sqrt(2)/2)/2 + Rational(3, 2) + assert P(Or(N < 0, N < 1)) == P(N < 1) + assert P(Or(N > 0, N < 0)) == 1 + + +def test_conditional_eq(): + E = Exponential('E', 1) + assert P(Eq(E, 1), Eq(E, 1)) == 1 + assert P(Eq(E, 1), Eq(E, 2)) == 0 + assert P(E > 1, Eq(E, 2)) == 1 + assert P(E < 1, Eq(E, 2)) == 0 + +def test_ContinuousDistributionHandmade(): + x = Symbol('x') + z = Dummy('z') + dens = Lambda(x, Piecewise((S.Half, (0<=x)&(x<1)), (0, (x>=1)&(x<2)), + (S.Half, (x>=2)&(x<3)), (0, True))) + dens = ContinuousDistributionHandmade(dens, set=Interval(0, 3)) + space = SingleContinuousPSpace(z, dens) + assert dens.pdf == Lambda(x, Piecewise((S(1)/2, (x >= 0) & (x < 1)), + (0, (x >= 1) & (x < 2)), (S(1)/2, (x >= 2) & (x < 3)), (0, True))) + assert median(space.value) == Interval(1, 2) + assert E(space.value) == Rational(3, 2) + assert variance(space.value) == Rational(13, 12) + + +def test_issue_16318(): + # test compute_expectation function of the SingleContinuousDomain + N = SingleContinuousDomain(x, Interval(0, 1)) + raises(ValueError, lambda: SingleContinuousDomain.compute_expectation(N, x+1, {x, y})) + +def test_compute_density(): + X = Normal('X', 0, Symbol("sigma")**2) + raises(ValueError, lambda: density(X**5 + X)) diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_discrete_rv.py b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_discrete_rv.py new file mode 100644 index 0000000000000000000000000000000000000000..39650a1a08e42840aaf8b06c1eb6e60c92a57f23 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_discrete_rv.py @@ -0,0 +1,312 @@ +from sympy.concrete.summations import Sum +from sympy.core.numbers import (I, Rational, oo, pi) +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.functions.elementary.complexes import (im, re) +from sympy.functions.elementary.exponential import log +from sympy.functions.elementary.integers import floor +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.special.bessel import besseli +from sympy.functions.special.beta_functions import beta +from sympy.functions.special.zeta_functions import zeta +from sympy.sets.sets import FiniteSet +from sympy.simplify.simplify import simplify +from sympy.utilities.lambdify import lambdify +from sympy.core.relational import Eq, Ne +from sympy.functions.elementary.exponential import exp +from sympy.logic.boolalg import Or +from sympy.sets.fancysets import Range +from sympy.stats import (P, E, variance, density, characteristic_function, + where, moment_generating_function, skewness, cdf, + kurtosis, coskewness) +from sympy.stats.drv_types import (PoissonDistribution, GeometricDistribution, + FlorySchulz, Poisson, Geometric, Hermite, Logarithmic, + NegativeBinomial, Skellam, YuleSimon, Zeta, + DiscreteRV) +from sympy.testing.pytest import slow, nocache_fail, raises, skip +from sympy.stats.symbolic_probability import Expectation +from sympy.functions.combinatorial.factorials import FallingFactorial + +x = Symbol('x') + + +def test_PoissonDistribution(): + l = 3 + p = PoissonDistribution(l) + assert abs(p.cdf(10).evalf() - 1) < .001 + assert abs(p.cdf(10.4).evalf() - 1) < .001 + assert p.expectation(x, x) == l + assert p.expectation(x**2, x) - p.expectation(x, x)**2 == l + + +def test_Poisson(): + l = 3 + x = Poisson('x', l) + assert E(x) == l + assert E(2*x) == 2*l + assert variance(x) == l + assert density(x) == PoissonDistribution(l) + assert isinstance(E(x, evaluate=False), Expectation) + assert isinstance(E(2*x, evaluate=False), Expectation) + # issue 8248 + assert x.pspace.compute_expectation(1) == 1 + # issue 27344 + try: + import numpy as np + except ImportError: + skip("numpy not installed") + y = Poisson('y', np.float64(4.72544290380919e-11)) + assert E(y) == 4.72544290380919e-11 + y = Poisson('y', np.float64(4.725442903809197e-11)) + assert E(y) == 4.725442903809197e-11 + l2 = 5 + z = Poisson('z', l2) + assert E(z) == l2 + assert E(FallingFactorial(z, 3)) == l2**3 + assert E(z**2) == l2 + l2**2 + + +def test_FlorySchulz(): + a = Symbol("a") + z = Symbol("z") + x = FlorySchulz('x', a) + assert E(x) == (2 - a)/a + assert (variance(x) - 2*(1 - a)/a**2).simplify() == S(0) + assert density(x)(z) == a**2*z*(1 - a)**(z - 1) + + +@slow +def test_GeometricDistribution(): + p = S.One / 5 + d = GeometricDistribution(p) + assert d.expectation(x, x) == 1/p + assert d.expectation(x**2, x) - d.expectation(x, x)**2 == (1-p)/p**2 + assert abs(d.cdf(20000).evalf() - 1) < .001 + assert abs(d.cdf(20000.8).evalf() - 1) < .001 + G = Geometric('G', p=S(1)/4) + assert cdf(G)(S(7)/2) == P(G <= S(7)/2) + + X = Geometric('X', Rational(1, 5)) + Y = Geometric('Y', Rational(3, 10)) + assert coskewness(X, X + Y, X + 2*Y).simplify() == sqrt(230)*Rational(81, 1150) + + +def test_Hermite(): + a1 = Symbol("a1", positive=True) + a2 = Symbol("a2", negative=True) + raises(ValueError, lambda: Hermite("H", a1, a2)) + + a1 = Symbol("a1", negative=True) + a2 = Symbol("a2", positive=True) + raises(ValueError, lambda: Hermite("H", a1, a2)) + + a1 = Symbol("a1", positive=True) + x = Symbol("x") + H = Hermite("H", a1, a2) + assert moment_generating_function(H)(x) == exp(a1*(exp(x) - 1) + + a2*(exp(2*x) - 1)) + assert characteristic_function(H)(x) == exp(a1*(exp(I*x) - 1) + + a2*(exp(2*I*x) - 1)) + assert E(H) == a1 + 2*a2 + + H = Hermite("H", a1=5, a2=4) + assert density(H)(2) == 33*exp(-9)/2 + assert E(H) == 13 + assert variance(H) == 21 + assert kurtosis(H) == Rational(464,147) + assert skewness(H) == 37*sqrt(21)/441 + +def test_Logarithmic(): + p = S.Half + x = Logarithmic('x', p) + assert E(x) == -p / ((1 - p) * log(1 - p)) + assert variance(x) == -1/log(2)**2 + 2/log(2) + assert E(2*x**2 + 3*x + 4) == 4 + 7 / log(2) + assert isinstance(E(x, evaluate=False), Expectation) + + +@nocache_fail +def test_negative_binomial(): + r = 5 + p = S.One / 3 + x = NegativeBinomial('x', r, p) + assert E(x) == r * (1 - p) / p + # This hangs when run with the cache disabled: + assert variance(x) == r * (1 - p) / p**2 + assert E(x**5 + 2*x + 3) == E(x**5) + 2*E(x) + 3 == Rational(796473, 1) + assert isinstance(E(x, evaluate=False), Expectation) + + +def test_skellam(): + mu1 = Symbol('mu1') + mu2 = Symbol('mu2') + z = Symbol('z') + X = Skellam('x', mu1, mu2) + + assert density(X)(z) == (mu1/mu2)**(z/2) * \ + exp(-mu1 - mu2)*besseli(z, 2*sqrt(mu1*mu2)) + assert skewness(X).expand() == mu1/(mu1*sqrt(mu1 + mu2) + mu2 * + sqrt(mu1 + mu2)) - mu2/(mu1*sqrt(mu1 + mu2) + mu2*sqrt(mu1 + mu2)) + assert variance(X).expand() == mu1 + mu2 + assert E(X) == mu1 - mu2 + assert characteristic_function(X)(z) == exp( + mu1*exp(I*z) - mu1 - mu2 + mu2*exp(-I*z)) + assert moment_generating_function(X)(z) == exp( + mu1*exp(z) - mu1 - mu2 + mu2*exp(-z)) + + +def test_yule_simon(): + from sympy.core.singleton import S + rho = S(3) + x = YuleSimon('x', rho) + assert simplify(E(x)) == rho / (rho - 1) + assert simplify(variance(x)) == rho**2 / ((rho - 1)**2 * (rho - 2)) + assert isinstance(E(x, evaluate=False), Expectation) + # To test the cdf function + assert cdf(x)(x) == Piecewise((-beta(floor(x), 4)*floor(x) + 1, x >= 1), (0, True)) + + +def test_zeta(): + s = S(5) + x = Zeta('x', s) + assert E(x) == zeta(s-1) / zeta(s) + assert simplify(variance(x)) == ( + zeta(s) * zeta(s-2) - zeta(s-1)**2) / zeta(s)**2 + + +def test_discrete_probability(): + X = Geometric('X', Rational(1, 5)) + Y = Poisson('Y', 4) + G = Geometric('e', x) + assert P(Eq(X, 3)) == Rational(16, 125) + assert P(X < 3) == Rational(9, 25) + assert P(X > 3) == Rational(64, 125) + assert P(X >= 3) == Rational(16, 25) + assert P(X <= 3) == Rational(61, 125) + assert P(Ne(X, 3)) == Rational(109, 125) + assert P(Eq(Y, 3)) == 32*exp(-4)/3 + assert P(Y < 3) == 13*exp(-4) + assert P(Y > 3).equals(32*(Rational(-71, 32) + 3*exp(4)/32)*exp(-4)/3) + assert P(Y >= 3).equals(32*(Rational(-39, 32) + 3*exp(4)/32)*exp(-4)/3) + assert P(Y <= 3) == 71*exp(-4)/3 + assert P(Ne(Y, 3)).equals( + 13*exp(-4) + 32*(Rational(-71, 32) + 3*exp(4)/32)*exp(-4)/3) + assert P(X < S.Infinity) is S.One + assert P(X > S.Infinity) is S.Zero + assert P(G < 3) == x*(2-x) + assert P(Eq(G, 3)) == x*(-x + 1)**2 + + +def test_DiscreteRV(): + p = S(1)/2 + x = Symbol('x', integer=True, positive=True) + pdf = p*(1 - p)**(x - 1) # pdf of Geometric Distribution + D = DiscreteRV(x, pdf, set=S.Naturals, check=True) + assert E(D) == E(Geometric('G', S(1)/2)) == 2 + assert P(D > 3) == S(1)/8 + assert D.pspace.domain.set == S.Naturals + raises(ValueError, lambda: DiscreteRV(x, x, FiniteSet(*range(4)), check=True)) + + # purposeful invalid pmf but it should not raise since check=False + # see test_drv_types.test_ContinuousRV for explanation + X = DiscreteRV(x, 1/x, S.Naturals) + assert P(X < 2) == 1 + assert E(X) == oo + +def test_precomputed_characteristic_functions(): + import mpmath + + def test_cf(dist, support_lower_limit, support_upper_limit): + pdf = density(dist) + t = S('t') + x = S('x') + + # first function is the hardcoded CF of the distribution + cf1 = lambdify([t], characteristic_function(dist)(t), 'mpmath') + + # second function is the Fourier transform of the density function + f = lambdify([x, t], pdf(x)*exp(I*x*t), 'mpmath') + cf2 = lambda t: mpmath.nsum(lambda x: f(x, t), [ + support_lower_limit, support_upper_limit], maxdegree=10) + + # compare the two functions at various points + for test_point in [2, 5, 8, 11]: + n1 = cf1(test_point) + n2 = cf2(test_point) + + assert abs(re(n1) - re(n2)) < 1e-12 + assert abs(im(n1) - im(n2)) < 1e-12 + + test_cf(Geometric('g', Rational(1, 3)), 1, mpmath.inf) + test_cf(Logarithmic('l', Rational(1, 5)), 1, mpmath.inf) + test_cf(NegativeBinomial('n', 5, Rational(1, 7)), 0, mpmath.inf) + test_cf(Poisson('p', 5), 0, mpmath.inf) + test_cf(YuleSimon('y', 5), 1, mpmath.inf) + test_cf(Zeta('z', 5), 1, mpmath.inf) + + +def test_moment_generating_functions(): + t = S('t') + + geometric_mgf = moment_generating_function(Geometric('g', S.Half))(t) + assert geometric_mgf.diff(t).subs(t, 0) == 2 + + logarithmic_mgf = moment_generating_function(Logarithmic('l', S.Half))(t) + assert logarithmic_mgf.diff(t).subs(t, 0) == 1/log(2) + + negative_binomial_mgf = moment_generating_function( + NegativeBinomial('n', 5, Rational(1, 3)))(t) + assert negative_binomial_mgf.diff(t).subs(t, 0) == Rational(10, 1) + + poisson_mgf = moment_generating_function(Poisson('p', 5))(t) + assert poisson_mgf.diff(t).subs(t, 0) == 5 + + skellam_mgf = moment_generating_function(Skellam('s', 1, 1))(t) + assert skellam_mgf.diff(t).subs( + t, 2) == (-exp(-2) + exp(2))*exp(-2 + exp(-2) + exp(2)) + + yule_simon_mgf = moment_generating_function(YuleSimon('y', 3))(t) + assert simplify(yule_simon_mgf.diff(t).subs(t, 0)) == Rational(3, 2) + + zeta_mgf = moment_generating_function(Zeta('z', 5))(t) + assert zeta_mgf.diff(t).subs(t, 0) == pi**4/(90*zeta(5)) + + +def test_Or(): + X = Geometric('X', S.Half) + assert P(Or(X < 3, X > 4)) == Rational(13, 16) + assert P(Or(X > 2, X > 1)) == P(X > 1) + assert P(Or(X >= 3, X < 3)) == 1 + + +def test_where(): + X = Geometric('X', Rational(1, 5)) + Y = Poisson('Y', 4) + assert where(X**2 > 4).set == Range(3, S.Infinity, 1) + assert where(X**2 >= 4).set == Range(2, S.Infinity, 1) + assert where(Y**2 < 9).set == Range(0, 3, 1) + assert where(Y**2 <= 9).set == Range(0, 4, 1) + + +def test_conditional(): + X = Geometric('X', Rational(2, 3)) + Y = Poisson('Y', 3) + assert P(X > 2, X > 3) == 1 + assert P(X > 3, X > 2) == Rational(1, 3) + assert P(Y > 2, Y < 2) == 0 + assert P(Eq(Y, 3), Y >= 0) == 9*exp(-3)/2 + assert P(Eq(Y, 3), Eq(Y, 2)) == 0 + assert P(X < 2, Eq(X, 2)) == 0 + assert P(X > 2, Eq(X, 3)) == 1 + + +def test_product_spaces(): + X1 = Geometric('X1', S.Half) + X2 = Geometric('X2', Rational(1, 3)) + assert str(P(X1 + X2 < 3).rewrite(Sum)) == ( + "Sum(Piecewise((1/(4*2**n), n >= -1), (0, True)), (n, -oo, -1))/3") + assert str(P(X1 + X2 > 3).rewrite(Sum)) == ( + 'Sum(Piecewise((2**(X2 - n - 2)*(2/3)**(X2 - 1)/6, ' + 'X2 - n <= 2), (0, True)), (X2, 1, oo), (n, 1, oo))') + assert P(Eq(X1 + X2, 3)) == Rational(1, 12) diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_error_prop.py b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_error_prop.py new file mode 100644 index 0000000000000000000000000000000000000000..483fb4c36e202d744faeb355606ff9803a516873 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_error_prop.py @@ -0,0 +1,60 @@ +from sympy.core.function import Function +from sympy.core.symbol import symbols +from sympy.functions.elementary.exponential import exp +from sympy.stats.error_prop import variance_prop +from sympy.stats.symbolic_probability import (RandomSymbol, Variance, + Covariance) + + +def test_variance_prop(): + x, y, z = symbols('x y z') + phi, t = consts = symbols('phi t') + a = RandomSymbol(x) + var_x = Variance(a) + var_y = Variance(RandomSymbol(y)) + var_z = Variance(RandomSymbol(z)) + f = Function('f')(x) + cases = { + x + y: var_x + var_y, + a + y: var_x + var_y, + x + y + z: var_x + var_y + var_z, + 2*x: 4*var_x, + x*y: var_x*y**2 + var_y*x**2, + 1/x: var_x/x**4, + x/y: (var_x*y**2 + var_y*x**2)/y**4, + exp(x): var_x*exp(2*x), + exp(2*x): 4*var_x*exp(4*x), + exp(-x*t): t**2*var_x*exp(-2*t*x), + f: Variance(f), + } + for inp, out in cases.items(): + obs = variance_prop(inp, consts=consts) + assert out == obs + +def test_variance_prop_with_covar(): + x, y, z = symbols('x y z') + phi, t = consts = symbols('phi t') + a = RandomSymbol(x) + var_x = Variance(a) + b = RandomSymbol(y) + var_y = Variance(b) + c = RandomSymbol(z) + var_z = Variance(c) + covar_x_y = Covariance(a, b) + covar_x_z = Covariance(a, c) + covar_y_z = Covariance(b, c) + cases = { + x + y: var_x + var_y + 2*covar_x_y, + a + y: var_x + var_y + 2*covar_x_y, + x + y + z: var_x + var_y + var_z + \ + 2*covar_x_y + 2*covar_x_z + 2*covar_y_z, + 2*x: 4*var_x, + x*y: var_x*y**2 + var_y*x**2 + 2*covar_x_y/(x*y), + 1/x: var_x/x**4, + exp(x): var_x*exp(2*x), + exp(2*x): 4*var_x*exp(4*x), + exp(-x*t): t**2*var_x*exp(-2*t*x), + } + for inp, out in cases.items(): + obs = variance_prop(inp, consts=consts, include_covar=True) + assert out == obs diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_finite_rv.py b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_finite_rv.py new file mode 100644 index 0000000000000000000000000000000000000000..93bf0211a26ecc32d7f18c7e2d8236859857e445 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_finite_rv.py @@ -0,0 +1,509 @@ +from sympy.concrete.summations import Sum +from sympy.core.containers import (Dict, Tuple) +from sympy.core.function import Function +from sympy.core.numbers import (I, Rational, nan) +from sympy.core.relational import Eq +from sympy.core.singleton import S +from sympy.core.symbol import (Dummy, Symbol, symbols) +from sympy.core.sympify import sympify +from sympy.functions.combinatorial.factorials import binomial +from sympy.functions.combinatorial.numbers import harmonic +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.elementary.trigonometric import cos +from sympy.functions.special.beta_functions import beta +from sympy.logic.boolalg import (And, Or) +from sympy.polys.polytools import cancel +from sympy.sets.sets import FiniteSet +from sympy.simplify.simplify import simplify +from sympy.matrices import Matrix +from sympy.stats import (DiscreteUniform, Die, Bernoulli, Coin, Binomial, BetaBinomial, + Hypergeometric, Rademacher, IdealSoliton, RobustSoliton, P, E, variance, + covariance, skewness, density, where, FiniteRV, pspace, cdf, + correlation, moment, cmoment, smoment, characteristic_function, + moment_generating_function, quantile, kurtosis, median, coskewness) +from sympy.stats.frv_types import DieDistribution, BinomialDistribution, \ + HypergeometricDistribution +from sympy.stats.rv import Density +from sympy.testing.pytest import raises + + +def BayesTest(A, B): + assert P(A, B) == P(And(A, B)) / P(B) + assert P(A, B) == P(B, A) * P(A) / P(B) + + +def test_discreteuniform(): + # Symbolic + a, b, c, t = symbols('a b c t') + X = DiscreteUniform('X', [a, b, c]) + + assert E(X) == (a + b + c)/3 + assert simplify(variance(X) + - ((a**2 + b**2 + c**2)/3 - (a/3 + b/3 + c/3)**2)) == 0 + assert P(Eq(X, a)) == P(Eq(X, b)) == P(Eq(X, c)) == S('1/3') + + Y = DiscreteUniform('Y', range(-5, 5)) + + # Numeric + assert E(Y) == S('-1/2') + assert variance(Y) == S('33/4') + assert median(Y) == FiniteSet(-1, 0) + + for x in range(-5, 5): + assert P(Eq(Y, x)) == S('1/10') + assert P(Y <= x) == S(x + 6)/10 + assert P(Y >= x) == S(5 - x)/10 + + assert dict(density(Die('D', 6)).items()) == \ + dict(density(DiscreteUniform('U', range(1, 7))).items()) + + assert characteristic_function(X)(t) == exp(I*a*t)/3 + exp(I*b*t)/3 + exp(I*c*t)/3 + assert moment_generating_function(X)(t) == exp(a*t)/3 + exp(b*t)/3 + exp(c*t)/3 + # issue 18611 + raises(ValueError, lambda: DiscreteUniform('Z', [a, a, a, b, b, c])) + +def test_dice(): + # TODO: Make iid method! + X, Y, Z = Die('X', 6), Die('Y', 6), Die('Z', 6) + a, b, t, p = symbols('a b t p') + + assert E(X) == 3 + S.Half + assert variance(X) == Rational(35, 12) + assert E(X + Y) == 7 + assert E(X + X) == 7 + assert E(a*X + b) == a*E(X) + b + assert variance(X + Y) == variance(X) + variance(Y) == cmoment(X + Y, 2) + assert variance(X + X) == 4 * variance(X) == cmoment(X + X, 2) + assert cmoment(X, 0) == 1 + assert cmoment(4*X, 3) == 64*cmoment(X, 3) + assert covariance(X, Y) is S.Zero + assert covariance(X, X + Y) == variance(X) + assert density(Eq(cos(X*S.Pi), 1))[True] == S.Half + assert correlation(X, Y) == 0 + assert correlation(X, Y) == correlation(Y, X) + assert smoment(X + Y, 3) == skewness(X + Y) + assert smoment(X + Y, 4) == kurtosis(X + Y) + assert smoment(X, 0) == 1 + assert P(X > 3) == S.Half + assert P(2*X > 6) == S.Half + assert P(X > Y) == Rational(5, 12) + assert P(Eq(X, Y)) == P(Eq(X, 1)) + + assert E(X, X > 3) == 5 == moment(X, 1, 0, X > 3) + assert E(X, Y > 3) == E(X) == moment(X, 1, 0, Y > 3) + assert E(X + Y, Eq(X, Y)) == E(2*X) + assert moment(X, 0) == 1 + assert moment(5*X, 2) == 25*moment(X, 2) + assert quantile(X)(p) == Piecewise((nan, (p > 1) | (p < 0)),\ + (S.One, p <= Rational(1, 6)), (S(2), p <= Rational(1, 3)), (S(3), p <= S.Half),\ + (S(4), p <= Rational(2, 3)), (S(5), p <= Rational(5, 6)), (S(6), p <= 1)) + + assert P(X > 3, X > 3) is S.One + assert P(X > Y, Eq(Y, 6)) is S.Zero + assert P(Eq(X + Y, 12)) == Rational(1, 36) + assert P(Eq(X + Y, 12), Eq(X, 6)) == Rational(1, 6) + + assert density(X + Y) == density(Y + Z) != density(X + X) + d = density(2*X + Y**Z) + assert d[S(22)] == Rational(1, 108) and d[S(4100)] == Rational(1, 216) and S(3130) not in d + + assert pspace(X).domain.as_boolean() == Or( + *[Eq(X.symbol, i) for i in [1, 2, 3, 4, 5, 6]]) + + assert where(X > 3).set == FiniteSet(4, 5, 6) + + assert characteristic_function(X)(t) == exp(6*I*t)/6 + exp(5*I*t)/6 + exp(4*I*t)/6 + exp(3*I*t)/6 + exp(2*I*t)/6 + exp(I*t)/6 + assert moment_generating_function(X)(t) == exp(6*t)/6 + exp(5*t)/6 + exp(4*t)/6 + exp(3*t)/6 + exp(2*t)/6 + exp(t)/6 + assert median(X) == FiniteSet(3, 4) + D = Die('D', 7) + assert median(D) == FiniteSet(4) + # Bayes test for die + BayesTest(X > 3, X + Y < 5) + BayesTest(Eq(X - Y, Z), Z > Y) + BayesTest(X > 3, X > 2) + + # arg test for die + raises(ValueError, lambda: Die('X', -1)) # issue 8105: negative sides. + raises(ValueError, lambda: Die('X', 0)) + raises(ValueError, lambda: Die('X', 1.5)) # issue 8103: non integer sides. + + # symbolic test for die + n, k = symbols('n, k', positive=True) + D = Die('D', n) + dens = density(D).dict + assert dens == Density(DieDistribution(n)) + assert set(dens.subs(n, 4).doit().keys()) == {1, 2, 3, 4} + assert set(dens.subs(n, 4).doit().values()) == {Rational(1, 4)} + k = Dummy('k', integer=True) + assert E(D).dummy_eq( + Sum(Piecewise((k/n, k <= n), (0, True)), (k, 1, n))) + assert variance(D).subs(n, 6).doit() == Rational(35, 12) + + ki = Dummy('ki') + cumuf = cdf(D)(k) + assert cumuf.dummy_eq( + Sum(Piecewise((1/n, (ki >= 1) & (ki <= n)), (0, True)), (ki, 1, k))) + assert cumuf.subs({n: 6, k: 2}).doit() == Rational(1, 3) + + t = Dummy('t') + cf = characteristic_function(D)(t) + assert cf.dummy_eq( + Sum(Piecewise((exp(ki*I*t)/n, (ki >= 1) & (ki <= n)), (0, True)), (ki, 1, n))) + assert cf.subs(n, 3).doit() == exp(3*I*t)/3 + exp(2*I*t)/3 + exp(I*t)/3 + mgf = moment_generating_function(D)(t) + assert mgf.dummy_eq( + Sum(Piecewise((exp(ki*t)/n, (ki >= 1) & (ki <= n)), (0, True)), (ki, 1, n))) + assert mgf.subs(n, 3).doit() == exp(3*t)/3 + exp(2*t)/3 + exp(t)/3 + +def test_given(): + X = Die('X', 6) + assert density(X, X > 5) == {S(6): S.One} + assert where(X > 2, X > 5).as_boolean() == Eq(X.symbol, 6) + + +def test_domains(): + X, Y = Die('x', 6), Die('y', 6) + x, y = X.symbol, Y.symbol + # Domains + d = where(X > Y) + assert d.condition == (x > y) + d = where(And(X > Y, Y > 3)) + assert d.as_boolean() == Or(And(Eq(x, 5), Eq(y, 4)), And(Eq(x, 6), + Eq(y, 5)), And(Eq(x, 6), Eq(y, 4))) + assert len(d.elements) == 3 + + assert len(pspace(X + Y).domain.elements) == 36 + + Z = Die('x', 4) + + raises(ValueError, lambda: P(X > Z)) # Two domains with same internal symbol + + assert pspace(X + Y).domain.set == FiniteSet(1, 2, 3, 4, 5, 6)**2 + + assert where(X > 3).set == FiniteSet(4, 5, 6) + assert X.pspace.domain.dict == FiniteSet( + *[Dict({X.symbol: i}) for i in range(1, 7)]) + + assert where(X > Y).dict == FiniteSet(*[Dict({X.symbol: i, Y.symbol: j}) + for i in range(1, 7) for j in range(1, 7) if i > j]) + +def test_bernoulli(): + p, a, b, t = symbols('p a b t') + X = Bernoulli('B', p, a, b) + + assert E(X) == a*p + b*(-p + 1) + assert density(X)[a] == p + assert density(X)[b] == 1 - p + assert characteristic_function(X)(t) == p * exp(I * a * t) + (-p + 1) * exp(I * b * t) + assert moment_generating_function(X)(t) == p * exp(a * t) + (-p + 1) * exp(b * t) + + X = Bernoulli('B', p, 1, 0) + z = Symbol("z") + + assert E(X) == p + assert simplify(variance(X)) == p*(1 - p) + assert E(a*X + b) == a*E(X) + b + assert simplify(variance(a*X + b)) == simplify(a**2 * variance(X)) + assert quantile(X)(z) == Piecewise((nan, (z > 1) | (z < 0)), (0, z <= 1 - p), (1, z <= 1)) + Y = Bernoulli('Y', Rational(1, 2)) + assert median(Y) == FiniteSet(0, 1) + Z = Bernoulli('Z', Rational(2, 3)) + assert median(Z) == FiniteSet(1) + raises(ValueError, lambda: Bernoulli('B', 1.5)) + raises(ValueError, lambda: Bernoulli('B', -0.5)) + + #issue 8248 + assert X.pspace.compute_expectation(1) == 1 + + p = Rational(1, 5) + X = Binomial('X', 5, p) + Y = Binomial('Y', 7, 2*p) + Z = Binomial('Z', 9, 3*p) + assert coskewness(Y + Z, X + Y, X + Z).simplify() == 0 + assert coskewness(Y + 2*X + Z, X + 2*Y + Z, X + 2*Z + Y).simplify() == \ + sqrt(1529)*Rational(12, 16819) + assert coskewness(Y + 2*X + Z, X + 2*Y + Z, X + 2*Z + Y, X < 2).simplify() \ + == -sqrt(357451121)*Rational(2812, 4646864573) + +def test_cdf(): + D = Die('D', 6) + o = S.One + + assert cdf( + D) == sympify({1: o/6, 2: o/3, 3: o/2, 4: 2*o/3, 5: 5*o/6, 6: o}) + + +def test_coins(): + C, D = Coin('C'), Coin('D') + H, T = symbols('H, T') + assert P(Eq(C, D)) == S.Half + assert density(Tuple(C, D)) == {(H, H): Rational(1, 4), (H, T): Rational(1, 4), + (T, H): Rational(1, 4), (T, T): Rational(1, 4)} + assert dict(density(C).items()) == {H: S.Half, T: S.Half} + + F = Coin('F', Rational(1, 10)) + assert P(Eq(F, H)) == Rational(1, 10) + + d = pspace(C).domain + + assert d.as_boolean() == Or(Eq(C.symbol, H), Eq(C.symbol, T)) + + raises(ValueError, lambda: P(C > D)) # Can't intelligently compare H to T + +def test_binomial_verify_parameters(): + raises(ValueError, lambda: Binomial('b', .2, .5)) + raises(ValueError, lambda: Binomial('b', 3, 1.5)) + +def test_binomial_numeric(): + nvals = range(5) + pvals = [0, Rational(1, 4), S.Half, Rational(3, 4), 1] + + for n in nvals: + for p in pvals: + X = Binomial('X', n, p) + assert E(X) == n*p + assert variance(X) == n*p*(1 - p) + if n > 0 and 0 < p < 1: + assert skewness(X) == (1 - 2*p)/sqrt(n*p*(1 - p)) + assert kurtosis(X) == 3 + (1 - 6*p*(1 - p))/(n*p*(1 - p)) + for k in range(n + 1): + assert P(Eq(X, k)) == binomial(n, k)*p**k*(1 - p)**(n - k) + +def test_binomial_quantile(): + X = Binomial('X', 50, S.Half) + assert quantile(X)(0.95) == S(31) + assert median(X) == FiniteSet(25) + + X = Binomial('X', 5, S.Half) + p = Symbol("p", positive=True) + assert quantile(X)(p) == Piecewise((nan, p > S.One), (S.Zero, p <= Rational(1, 32)),\ + (S.One, p <= Rational(3, 16)), (S(2), p <= S.Half), (S(3), p <= Rational(13, 16)),\ + (S(4), p <= Rational(31, 32)), (S(5), p <= S.One)) + assert median(X) == FiniteSet(2, 3) + + +def test_binomial_symbolic(): + n = 2 + p = symbols('p', positive=True) + X = Binomial('X', n, p) + t = Symbol('t') + + assert simplify(E(X)) == n*p == simplify(moment(X, 1)) + assert simplify(variance(X)) == n*p*(1 - p) == simplify(cmoment(X, 2)) + assert cancel(skewness(X) - (1 - 2*p)/sqrt(n*p*(1 - p))) == 0 + assert cancel((kurtosis(X)) - (3 + (1 - 6*p*(1 - p))/(n*p*(1 - p)))) == 0 + assert characteristic_function(X)(t) == p ** 2 * exp(2 * I * t) + 2 * p * (-p + 1) * exp(I * t) + (-p + 1) ** 2 + assert moment_generating_function(X)(t) == p ** 2 * exp(2 * t) + 2 * p * (-p + 1) * exp(t) + (-p + 1) ** 2 + + # Test ability to change success/failure winnings + H, T = symbols('H T') + Y = Binomial('Y', n, p, succ=H, fail=T) + assert simplify(E(Y) - (n*(H*p + T*(1 - p)))) == 0 + + # test symbolic dimensions + n = symbols('n') + B = Binomial('B', n, p) + raises(NotImplementedError, lambda: P(B > 2)) + assert density(B).dict == Density(BinomialDistribution(n, p, 1, 0)) + assert set(density(B).dict.subs(n, 4).doit().keys()) == \ + {S.Zero, S.One, S(2), S(3), S(4)} + assert set(density(B).dict.subs(n, 4).doit().values()) == \ + {(1 - p)**4, 4*p*(1 - p)**3, 6*p**2*(1 - p)**2, 4*p**3*(1 - p), p**4} + k = Dummy('k', integer=True) + assert E(B > 2).dummy_eq( + Sum(Piecewise((k*p**k*(1 - p)**(-k + n)*binomial(n, k), (k >= 0) + & (k <= n) & (k > 2)), (0, True)), (k, 0, n))) + +def test_beta_binomial(): + # verify parameters + raises(ValueError, lambda: BetaBinomial('b', .2, 1, 2)) + raises(ValueError, lambda: BetaBinomial('b', 2, -1, 2)) + raises(ValueError, lambda: BetaBinomial('b', 2, 1, -2)) + assert BetaBinomial('b', 2, 1, 1) + + # test numeric values + nvals = range(1,5) + alphavals = [Rational(1, 4), S.Half, Rational(3, 4), 1, 10] + betavals = [Rational(1, 4), S.Half, Rational(3, 4), 1, 10] + + for n in nvals: + for a in alphavals: + for b in betavals: + X = BetaBinomial('X', n, a, b) + assert E(X) == moment(X, 1) + assert variance(X) == cmoment(X, 2) + + # test symbolic + n, a, b = symbols('a b n') + assert BetaBinomial('x', n, a, b) + n = 2 # Because we're using for loops, can't do symbolic n + a, b = symbols('a b', positive=True) + X = BetaBinomial('X', n, a, b) + t = Symbol('t') + + assert E(X).expand() == moment(X, 1).expand() + assert variance(X).expand() == cmoment(X, 2).expand() + assert skewness(X) == smoment(X, 3) + assert characteristic_function(X)(t) == exp(2*I*t)*beta(a + 2, b)/beta(a, b) +\ + 2*exp(I*t)*beta(a + 1, b + 1)/beta(a, b) + beta(a, b + 2)/beta(a, b) + assert moment_generating_function(X)(t) == exp(2*t)*beta(a + 2, b)/beta(a, b) +\ + 2*exp(t)*beta(a + 1, b + 1)/beta(a, b) + beta(a, b + 2)/beta(a, b) + +def test_hypergeometric_numeric(): + for N in range(1, 5): + for m in range(0, N + 1): + for n in range(1, N + 1): + X = Hypergeometric('X', N, m, n) + N, m, n = map(sympify, (N, m, n)) + assert sum(density(X).values()) == 1 + assert E(X) == n * m / N + if N > 1: + assert variance(X) == n*(m/N)*(N - m)/N*(N - n)/(N - 1) + # Only test for skewness when defined + if N > 2 and 0 < m < N and n < N: + assert skewness(X) == simplify((N - 2*m)*sqrt(N - 1)*(N - 2*n) + / (sqrt(n*m*(N - m)*(N - n))*(N - 2))) + +def test_hypergeometric_symbolic(): + N, m, n = symbols('N, m, n') + H = Hypergeometric('H', N, m, n) + dens = density(H).dict + expec = E(H > 2) + assert dens == Density(HypergeometricDistribution(N, m, n)) + assert dens.subs(N, 5).doit() == Density(HypergeometricDistribution(5, m, n)) + assert set(dens.subs({N: 3, m: 2, n: 1}).doit().keys()) == {S.Zero, S.One} + assert set(dens.subs({N: 3, m: 2, n: 1}).doit().values()) == {Rational(1, 3), Rational(2, 3)} + k = Dummy('k', integer=True) + assert expec.dummy_eq( + Sum(Piecewise((k*binomial(m, k)*binomial(N - m, -k + n) + /binomial(N, n), k > 2), (0, True)), (k, 0, n))) + +def test_rademacher(): + X = Rademacher('X') + t = Symbol('t') + + assert E(X) == 0 + assert variance(X) == 1 + assert density(X)[-1] == S.Half + assert density(X)[1] == S.Half + assert characteristic_function(X)(t) == exp(I*t)/2 + exp(-I*t)/2 + assert moment_generating_function(X)(t) == exp(t) / 2 + exp(-t) / 2 + +def test_ideal_soliton(): + raises(ValueError, lambda : IdealSoliton('sol', -12)) + raises(ValueError, lambda : IdealSoliton('sol', 13.2)) + raises(ValueError, lambda : IdealSoliton('sol', 0)) + f = Function('f') + raises(ValueError, lambda : density(IdealSoliton('sol', 10)).pmf(f)) + + k = Symbol('k', integer=True, positive=True) + x = Symbol('x', integer=True, positive=True) + t = Symbol('t') + sol = IdealSoliton('sol', k) + assert density(sol).low == S.One + assert density(sol).high == k + assert density(sol).dict == Density(density(sol)) + assert density(sol).pmf(x) == Piecewise((1/k, Eq(x, 1)), (1/(x*(x - 1)), k >= x), (0, True)) + + k_vals = [5, 20, 50, 100, 1000] + for i in k_vals: + assert E(sol.subs(k, i)) == harmonic(i) == moment(sol.subs(k, i), 1) + assert variance(sol.subs(k, i)) == (i - 1) + harmonic(i) - harmonic(i)**2 == cmoment(sol.subs(k, i),2) + assert skewness(sol.subs(k, i)) == smoment(sol.subs(k, i), 3) + assert kurtosis(sol.subs(k, i)) == smoment(sol.subs(k, i), 4) + + assert exp(I*t)/10 + Sum(exp(I*t*x)/(x*x - x), (x, 2, k)).subs(k, 10).doit() == characteristic_function(sol.subs(k, 10))(t) + assert exp(t)/10 + Sum(exp(t*x)/(x*x - x), (x, 2, k)).subs(k, 10).doit() == moment_generating_function(sol.subs(k, 10))(t) + +def test_robust_soliton(): + raises(ValueError, lambda : RobustSoliton('robSol', -12, 0.1, 0.02)) + raises(ValueError, lambda : RobustSoliton('robSol', 13, 1.89, 0.1)) + raises(ValueError, lambda : RobustSoliton('robSol', 15, 0.6, -2.31)) + f = Function('f') + raises(ValueError, lambda : density(RobustSoliton('robSol', 15, 0.6, 0.1)).pmf(f)) + + k = Symbol('k', integer=True, positive=True) + delta = Symbol('delta', positive=True) + c = Symbol('c', positive=True) + robSol = RobustSoliton('robSol', k, delta, c) + assert density(robSol).low == 1 + assert density(robSol).high == k + + k_vals = [10, 20, 50] + delta_vals = [0.2, 0.4, 0.6] + c_vals = [0.01, 0.03, 0.05] + for x in k_vals: + for y in delta_vals: + for z in c_vals: + assert E(robSol.subs({k: x, delta: y, c: z})) == moment(robSol.subs({k: x, delta: y, c: z}), 1) + assert variance(robSol.subs({k: x, delta: y, c: z})) == cmoment(robSol.subs({k: x, delta: y, c: z}), 2) + assert skewness(robSol.subs({k: x, delta: y, c: z})) == smoment(robSol.subs({k: x, delta: y, c: z}), 3) + assert kurtosis(robSol.subs({k: x, delta: y, c: z})) == smoment(robSol.subs({k: x, delta: y, c: z}), 4) + +def test_FiniteRV(): + F = FiniteRV('F', {1: S.Half, 2: Rational(1, 4), 3: Rational(1, 4)}, check=True) + p = Symbol("p", positive=True) + + assert dict(density(F).items()) == {S.One: S.Half, S(2): Rational(1, 4), S(3): Rational(1, 4)} + assert P(F >= 2) == S.Half + assert quantile(F)(p) == Piecewise((nan, p > S.One), (S.One, p <= S.Half),\ + (S(2), p <= Rational(3, 4)),(S(3), True)) + + assert pspace(F).domain.as_boolean() == Or( + *[Eq(F.symbol, i) for i in [1, 2, 3]]) + + assert F.pspace.domain.set == FiniteSet(1, 2, 3) + raises(ValueError, lambda: FiniteRV('F', {1: S.Half, 2: S.Half, 3: S.Half}, check=True)) + raises(ValueError, lambda: FiniteRV('F', {1: S.Half, 2: Rational(-1, 2), 3: S.One}, check=True)) + raises(ValueError, lambda: FiniteRV('F', {1: S.One, 2: Rational(3, 2), 3: S.Zero,\ + 4: Rational(-1, 2), 5: Rational(-3, 4), 6: Rational(-1, 4)}, check=True)) + + # purposeful invalid pmf but it should not raise since check=False + # see test_drv_types.test_ContinuousRV for explanation + X = FiniteRV('X', {1: 1, 2: 2}) + assert E(X) == 5 + assert P(X <= 2) + P(X > 2) != 1 + +def test_density_call(): + from sympy.abc import p + x = Bernoulli('x', p) + d = density(x) + assert d(0) == 1 - p + assert d(S.Zero) == 1 - p + assert d(5) == 0 + + assert 0 in d + assert 5 not in d + assert d(S.Zero) == d[S.Zero] + + +def test_DieDistribution(): + from sympy.abc import x + X = DieDistribution(6) + assert X.pmf(S.Half) is S.Zero + assert X.pmf(x).subs({x: 1}).doit() == Rational(1, 6) + assert X.pmf(x).subs({x: 7}).doit() == 0 + assert X.pmf(x).subs({x: -1}).doit() == 0 + assert X.pmf(x).subs({x: Rational(1, 3)}).doit() == 0 + raises(ValueError, lambda: X.pmf(Matrix([0, 0]))) + raises(ValueError, lambda: X.pmf(x**2 - 1)) + +def test_FinitePSpace(): + X = Die('X', 6) + space = pspace(X) + assert space.density == DieDistribution(6) + +def test_symbolic_conditions(): + B = Bernoulli('B', Rational(1, 4)) + D = Die('D', 4) + b, n = symbols('b, n') + Y = P(Eq(B, b)) + Z = E(D > n) + assert Y == \ + Piecewise((Rational(1, 4), Eq(b, 1)), (0, True)) + \ + Piecewise((Rational(3, 4), Eq(b, 0)), (0, True)) + assert Z == \ + Piecewise((Rational(1, 4), n < 1), (0, True)) + Piecewise((S.Half, n < 2), (0, True)) + \ + Piecewise((Rational(3, 4), n < 3), (0, True)) + Piecewise((S.One, n < 4), (0, True)) diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_joint_rv.py b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_joint_rv.py new file mode 100644 index 0000000000000000000000000000000000000000..057fc313dfbb31826b07fd1315205d22b86a7f96 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_joint_rv.py @@ -0,0 +1,436 @@ +from sympy.concrete.products import Product +from sympy.concrete.summations import Sum +from sympy.core.numbers import (Rational, oo, pi) +from sympy.core.relational import Eq +from sympy.core.singleton import S +from sympy.core.symbol import symbols +from sympy.functions.combinatorial.factorials import (RisingFactorial, factorial) +from sympy.functions.elementary.complexes import polar_lift +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.special.bessel import besselk +from sympy.functions.special.gamma_functions import gamma +from sympy.matrices.dense import eye +from sympy.matrices.expressions.determinant import Determinant +from sympy.sets.fancysets import Range +from sympy.sets.sets import (Interval, ProductSet) +from sympy.simplify.simplify import simplify +from sympy.tensor.indexed import (Indexed, IndexedBase) +from sympy.core.numbers import comp +from sympy.integrals.integrals import integrate +from sympy.matrices import Matrix, MatrixSymbol +from sympy.matrices.expressions.matexpr import MatrixElement +from sympy.stats import density, median, marginal_distribution, Normal, Laplace, E, sample +from sympy.stats.joint_rv_types import (JointRV, MultivariateNormalDistribution, + JointDistributionHandmade, MultivariateT, NormalGamma, + GeneralizedMultivariateLogGammaOmega as GMVLGO, MultivariateBeta, + GeneralizedMultivariateLogGamma as GMVLG, MultivariateEwens, + Multinomial, NegativeMultinomial, MultivariateNormal, + MultivariateLaplace) +from sympy.testing.pytest import raises, XFAIL, skip, slow +from sympy.external import import_module + +from sympy.abc import x, y + + + +def test_Normal(): + m = Normal('A', [1, 2], [[1, 0], [0, 1]]) + A = MultivariateNormal('A', [1, 2], [[1, 0], [0, 1]]) + assert m == A + assert density(m)(1, 2) == 1/(2*pi) + assert m.pspace.distribution.set == ProductSet(S.Reals, S.Reals) + raises (ValueError, lambda:m[2]) + n = Normal('B', [1, 2, 3], [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) + p = Normal('C', Matrix([1, 2]), Matrix([[1, 0], [0, 1]])) + assert density(m)(x, y) == density(p)(x, y) + assert marginal_distribution(n, 0, 1)(1, 2) == 1/(2*pi) + raises(ValueError, lambda: marginal_distribution(m)) + assert integrate(density(m)(x, y), (x, -oo, oo), (y, -oo, oo)).evalf() == 1.0 + N = Normal('N', [1, 2], [[x, 0], [0, y]]) + assert density(N)(0, 0) == exp(-((4*x + y)/(2*x*y)))/(2*pi*sqrt(x*y)) + + raises (ValueError, lambda: Normal('M', [1, 2], [[1, 1], [1, -1]])) + # symbolic + n = symbols('n', integer=True, positive=True) + mu = MatrixSymbol('mu', n, 1) + sigma = MatrixSymbol('sigma', n, n) + X = Normal('X', mu, sigma) + assert density(X) == MultivariateNormalDistribution(mu, sigma) + raises (NotImplementedError, lambda: median(m)) + # Below tests should work after issue #17267 is resolved + # assert E(X) == mu + # assert variance(X) == sigma + + # test symbolic multivariate normal densities + n = 3 + + Sg = MatrixSymbol('Sg', n, n) + mu = MatrixSymbol('mu', n, 1) + obs = MatrixSymbol('obs', n, 1) + + X = MultivariateNormal('X', mu, Sg) + density_X = density(X) + + eval_a = density_X(obs).subs({Sg: eye(3), + mu: Matrix([0, 0, 0]), obs: Matrix([0, 0, 0])}).doit() + eval_b = density_X(0, 0, 0).subs({Sg: eye(3), mu: Matrix([0, 0, 0])}).doit() + + assert eval_a == sqrt(2)/(4*pi**Rational(3/2)) + assert eval_b == sqrt(2)/(4*pi**Rational(3/2)) + + n = symbols('n', integer=True, positive=True) + + Sg = MatrixSymbol('Sg', n, n) + mu = MatrixSymbol('mu', n, 1) + obs = MatrixSymbol('obs', n, 1) + + X = MultivariateNormal('X', mu, Sg) + density_X_at_obs = density(X)(obs) + + expected_density = MatrixElement( + exp((S(1)/2) * (mu.T - obs.T) * Sg**(-1) * (-mu + obs)) / \ + sqrt((2*pi)**n * Determinant(Sg)), 0, 0) + + assert density_X_at_obs == expected_density + + +def test_MultivariateTDist(): + t1 = MultivariateT('T', [0, 0], [[1, 0], [0, 1]], 2) + assert(density(t1))(1, 1) == 1/(8*pi) + assert t1.pspace.distribution.set == ProductSet(S.Reals, S.Reals) + assert integrate(density(t1)(x, y), (x, -oo, oo), \ + (y, -oo, oo)).evalf() == 1.0 + raises(ValueError, lambda: MultivariateT('T', [1, 2], [[1, 1], [1, -1]], 1)) + t2 = MultivariateT('t2', [1, 2], [[x, 0], [0, y]], 1) + assert density(t2)(1, 2) == 1/(2*pi*sqrt(x*y)) + + +def test_multivariate_laplace(): + raises(ValueError, lambda: Laplace('T', [1, 2], [[1, 2], [2, 1]])) + L = Laplace('L', [1, 0], [[1, 0], [0, 1]]) + L2 = MultivariateLaplace('L2', [1, 0], [[1, 0], [0, 1]]) + assert density(L)(2, 3) == exp(2)*besselk(0, sqrt(39))/pi + L1 = Laplace('L1', [1, 2], [[x, 0], [0, y]]) + assert density(L1)(0, 1) == \ + exp(2/y)*besselk(0, sqrt((2 + 4/y + 1/x)/y))/(pi*sqrt(x*y)) + assert L.pspace.distribution.set == ProductSet(S.Reals, S.Reals) + assert L.pspace.distribution == L2.pspace.distribution + + +def test_NormalGamma(): + ng = NormalGamma('G', 1, 2, 3, 4) + assert density(ng)(1, 1) == 32*exp(-4)/sqrt(pi) + assert ng.pspace.distribution.set == ProductSet(S.Reals, Interval(0, oo)) + raises(ValueError, lambda:NormalGamma('G', 1, 2, 3, -1)) + assert marginal_distribution(ng, 0)(1) == \ + 3*sqrt(10)*gamma(Rational(7, 4))/(10*sqrt(pi)*gamma(Rational(5, 4))) + assert marginal_distribution(ng, y)(1) == exp(Rational(-1, 4))/128 + assert marginal_distribution(ng,[0,1])(x) == x**2*exp(-x/4)/128 + + +def test_GeneralizedMultivariateLogGammaDistribution(): + h = S.Half + omega = Matrix([[1, h, h, h], + [h, 1, h, h], + [h, h, 1, h], + [h, h, h, 1]]) + v, l, mu = (4, [1, 2, 3, 4], [1, 2, 3, 4]) + y_1, y_2, y_3, y_4 = symbols('y_1:5', real=True) + delta = symbols('d', positive=True) + G = GMVLGO('G', omega, v, l, mu) + Gd = GMVLG('Gd', delta, v, l, mu) + dend = ("d**4*Sum(4*24**(-n - 4)*(1 - d)**n*exp((n + 4)*(y_1 + 2*y_2 + 3*y_3 " + "+ 4*y_4) - exp(y_1) - exp(2*y_2)/2 - exp(3*y_3)/3 - exp(4*y_4)/4)/" + "(gamma(n + 1)*gamma(n + 4)**3), (n, 0, oo))") + assert str(density(Gd)(y_1, y_2, y_3, y_4)) == dend + den = ("5*2**(2/3)*5**(1/3)*Sum(4*24**(-n - 4)*(-2**(2/3)*5**(1/3)/4 + 1)**n*" + "exp((n + 4)*(y_1 + 2*y_2 + 3*y_3 + 4*y_4) - exp(y_1) - exp(2*y_2)/2 - " + "exp(3*y_3)/3 - exp(4*y_4)/4)/(gamma(n + 1)*gamma(n + 4)**3), (n, 0, oo))/64") + assert str(density(G)(y_1, y_2, y_3, y_4)) == den + marg = ("5*2**(2/3)*5**(1/3)*exp(4*y_1)*exp(-exp(y_1))*Integral(exp(-exp(4*G[3])" + "/4)*exp(16*G[3])*Integral(exp(-exp(3*G[2])/3)*exp(12*G[2])*Integral(exp(" + "-exp(2*G[1])/2)*exp(8*G[1])*Sum((-1/4)**n*(-4 + 2**(2/3)*5**(1/3" + "))**n*exp(n*y_1)*exp(2*n*G[1])*exp(3*n*G[2])*exp(4*n*G[3])/(24**n*gamma(n + 1)" + "*gamma(n + 4)**3), (n, 0, oo)), (G[1], -oo, oo)), (G[2], -oo, oo)), (G[3]" + ", -oo, oo))/5308416") + assert str(marginal_distribution(G, G[0])(y_1)) == marg + omega_f1 = Matrix([[1, h, h]]) + omega_f2 = Matrix([[1, h, h, h], + [h, 1, 2, h], + [h, h, 1, h], + [h, h, h, 1]]) + omega_f3 = Matrix([[6, h, h, h], + [h, 1, 2, h], + [h, h, 1, h], + [h, h, h, 1]]) + v_f = symbols("v_f", positive=False, real=True) + l_f = [1, 2, v_f, 4] + m_f = [v_f, 2, 3, 4] + omega_f4 = Matrix([[1, h, h, h, h], + [h, 1, h, h, h], + [h, h, 1, h, h], + [h, h, h, 1, h], + [h, h, h, h, 1]]) + l_f1 = [1, 2, 3, 4, 5] + omega_f5 = Matrix([[1]]) + mu_f5 = l_f5 = [1] + + raises(ValueError, lambda: GMVLGO('G', omega_f1, v, l, mu)) + raises(ValueError, lambda: GMVLGO('G', omega_f2, v, l, mu)) + raises(ValueError, lambda: GMVLGO('G', omega_f3, v, l, mu)) + raises(ValueError, lambda: GMVLGO('G', omega, v_f, l, mu)) + raises(ValueError, lambda: GMVLGO('G', omega, v, l_f, mu)) + raises(ValueError, lambda: GMVLGO('G', omega, v, l, m_f)) + raises(ValueError, lambda: GMVLGO('G', omega_f4, v, l, mu)) + raises(ValueError, lambda: GMVLGO('G', omega, v, l_f1, mu)) + raises(ValueError, lambda: GMVLGO('G', omega_f5, v, l_f5, mu_f5)) + raises(ValueError, lambda: GMVLG('G', Rational(3, 2), v, l, mu)) + + +def test_MultivariateBeta(): + a1, a2 = symbols('a1, a2', positive=True) + a1_f, a2_f = symbols('a1, a2', positive=False, real=True) + mb = MultivariateBeta('B', [a1, a2]) + mb_c = MultivariateBeta('C', a1, a2) + assert density(mb)(1, 2) == S(2)**(a2 - 1)*gamma(a1 + a2)/\ + (gamma(a1)*gamma(a2)) + assert marginal_distribution(mb_c, 0)(3) == S(3)**(a1 - 1)*gamma(a1 + a2)/\ + (a2*gamma(a1)*gamma(a2)) + raises(ValueError, lambda: MultivariateBeta('b1', [a1_f, a2])) + raises(ValueError, lambda: MultivariateBeta('b2', [a1, a2_f])) + raises(ValueError, lambda: MultivariateBeta('b3', [0, 0])) + raises(ValueError, lambda: MultivariateBeta('b4', [a1_f, a2_f])) + assert mb.pspace.distribution.set == ProductSet(Interval(0, 1), Interval(0, 1)) + + +def test_MultivariateEwens(): + n, theta, i = symbols('n theta i', positive=True) + + # tests for integer dimensions + theta_f = symbols('t_f', negative=True) + a = symbols('a_1:4', positive = True, integer = True) + ed = MultivariateEwens('E', 3, theta) + assert density(ed)(a[0], a[1], a[2]) == Piecewise((6*2**(-a[1])*3**(-a[2])* + theta**a[0]*theta**a[1]*theta**a[2]/ + (theta*(theta + 1)*(theta + 2)* + factorial(a[0])*factorial(a[1])* + factorial(a[2])), Eq(a[0] + 2*a[1] + + 3*a[2], 3)), (0, True)) + assert marginal_distribution(ed, ed[1])(a[1]) == Piecewise((6*2**(-a[1])* + theta**a[1]/((theta + 1)* + (theta + 2)*factorial(a[1])), + Eq(2*a[1] + 1, 3)), (0, True)) + raises(ValueError, lambda: MultivariateEwens('e1', 5, theta_f)) + assert ed.pspace.distribution.set == ProductSet(Range(0, 4, 1), + Range(0, 2, 1), Range(0, 2, 1)) + + # tests for symbolic dimensions + eds = MultivariateEwens('E', n, theta) + a = IndexedBase('a') + j, k = symbols('j, k') + den = Piecewise((factorial(n)*Product(theta**a[j]*(j + 1)**(-a[j])/ + factorial(a[j]), (j, 0, n - 1))/RisingFactorial(theta, n), + Eq(n, Sum((k + 1)*a[k], (k, 0, n - 1)))), (0, True)) + assert density(eds)(a).dummy_eq(den) + + +def test_Multinomial(): + n, x1, x2, x3, x4 = symbols('n, x1, x2, x3, x4', nonnegative=True, integer=True) + p1, p2, p3, p4 = symbols('p1, p2, p3, p4', positive=True) + p1_f, n_f = symbols('p1_f, n_f', negative=True) + M = Multinomial('M', n, [p1, p2, p3, p4]) + C = Multinomial('C', 3, p1, p2, p3) + f = factorial + assert density(M)(x1, x2, x3, x4) == Piecewise((p1**x1*p2**x2*p3**x3*p4**x4* + f(n)/(f(x1)*f(x2)*f(x3)*f(x4)), + Eq(n, x1 + x2 + x3 + x4)), (0, True)) + assert marginal_distribution(C, C[0])(x1).subs(x1, 1) ==\ + 3*p1*p2**2 +\ + 6*p1*p2*p3 +\ + 3*p1*p3**2 + raises(ValueError, lambda: Multinomial('b1', 5, [p1, p2, p3, p1_f])) + raises(ValueError, lambda: Multinomial('b2', n_f, [p1, p2, p3, p4])) + raises(ValueError, lambda: Multinomial('b3', n, 0.5, 0.4, 0.3, 0.1)) + + +def test_NegativeMultinomial(): + k0, x1, x2, x3, x4 = symbols('k0, x1, x2, x3, x4', nonnegative=True, integer=True) + p1, p2, p3, p4 = symbols('p1, p2, p3, p4', positive=True) + p1_f = symbols('p1_f', negative=True) + N = NegativeMultinomial('N', 4, [p1, p2, p3, p4]) + C = NegativeMultinomial('C', 4, 0.1, 0.2, 0.3) + g = gamma + f = factorial + assert simplify(density(N)(x1, x2, x3, x4) - + p1**x1*p2**x2*p3**x3*p4**x4*(-p1 - p2 - p3 - p4 + 1)**4*g(x1 + x2 + + x3 + x4 + 4)/(6*f(x1)*f(x2)*f(x3)*f(x4))) is S.Zero + assert comp(marginal_distribution(C, C[0])(1).evalf(), 0.33, .01) + raises(ValueError, lambda: NegativeMultinomial('b1', 5, [p1, p2, p3, p1_f])) + raises(ValueError, lambda: NegativeMultinomial('b2', k0, 0.5, 0.4, 0.3, 0.4)) + assert N.pspace.distribution.set == ProductSet(Range(0, oo, 1), + Range(0, oo, 1), Range(0, oo, 1), Range(0, oo, 1)) + + +@slow +def test_JointPSpace_marginal_distribution(): + T = MultivariateT('T', [0, 0], [[1, 0], [0, 1]], 2) + got = marginal_distribution(T, T[1])(x) + ans = sqrt(2)*(x**2/2 + 1)/(4*polar_lift(x**2/2 + 1)**(S(5)/2)) + assert got == ans, got + assert integrate(marginal_distribution(T, 1)(x), (x, -oo, oo)) == 1 + + t = MultivariateT('T', [0, 0, 0], [[1, 0, 0], [0, 1, 0], [0, 0, 1]], 3) + assert comp(marginal_distribution(t, 0)(1).evalf(), 0.2, .01) + + +def test_JointRV(): + x1, x2 = (Indexed('x', i) for i in (1, 2)) + pdf = exp(-x1**2/2 + x1 - x2**2/2 - S.Half)/(2*pi) + X = JointRV('x', pdf) + assert density(X)(1, 2) == exp(-2)/(2*pi) + assert isinstance(X.pspace.distribution, JointDistributionHandmade) + assert marginal_distribution(X, 0)(2) == sqrt(2)*exp(Rational(-1, 2))/(2*sqrt(pi)) + + +def test_expectation(): + m = Normal('A', [x, y], [[1, 0], [0, 1]]) + assert simplify(E(m[1])) == y + + +@XFAIL +def test_joint_vector_expectation(): + m = Normal('A', [x, y], [[1, 0], [0, 1]]) + assert E(m) == (x, y) + + +def test_sample_numpy(): + distribs_numpy = [ + MultivariateNormal("M", [3, 4], [[2, 1], [1, 2]]), + MultivariateBeta("B", [0.4, 5, 15, 50, 203]), + Multinomial("N", 50, [0.3, 0.2, 0.1, 0.25, 0.15]) + ] + size = 3 + numpy = import_module('numpy') + if not numpy: + skip('Numpy is not installed. Abort tests for _sample_numpy.') + else: + for X in distribs_numpy: + samps = sample(X, size=size, library='numpy') + for sam in samps: + assert tuple(sam) in X.pspace.distribution.set + N_c = NegativeMultinomial('N', 3, 0.1, 0.1, 0.1) + raises(NotImplementedError, lambda: sample(N_c, library='numpy')) + + +def test_sample_scipy(): + distribs_scipy = [ + MultivariateNormal("M", [0, 0], [[0.1, 0.025], [0.025, 0.1]]), + MultivariateBeta("B", [0.4, 5, 15]), + Multinomial("N", 8, [0.3, 0.2, 0.1, 0.4]) + ] + + size = 3 + scipy = import_module('scipy') + if not scipy: + skip('Scipy not installed. Abort tests for _sample_scipy.') + else: + for X in distribs_scipy: + samps = sample(X, size=size) + samps2 = sample(X, size=(2, 2)) + for sam in samps: + assert tuple(sam) in X.pspace.distribution.set + for i in range(2): + for j in range(2): + assert tuple(samps2[i][j]) in X.pspace.distribution.set + N_c = NegativeMultinomial('N', 3, 0.1, 0.1, 0.1) + raises(NotImplementedError, lambda: sample(N_c)) + + +def test_sample_pymc(): + distribs_pymc = [ + MultivariateNormal("M", [5, 2], [[1, 0], [0, 1]]), + MultivariateBeta("B", [0.4, 5, 15]), + Multinomial("N", 4, [0.3, 0.2, 0.1, 0.4]) + ] + size = 3 + pymc = import_module('pymc') + if not pymc: + skip('PyMC is not installed. Abort tests for _sample_pymc.') + else: + for X in distribs_pymc: + samps = sample(X, size=size, library='pymc') + for sam in samps: + assert tuple(sam.flatten()) in X.pspace.distribution.set + N_c = NegativeMultinomial('N', 3, 0.1, 0.1, 0.1) + raises(NotImplementedError, lambda: sample(N_c, library='pymc')) + + +def test_sample_seed(): + x1, x2 = (Indexed('x', i) for i in (1, 2)) + pdf = exp(-x1**2/2 + x1 - x2**2/2 - S.Half)/(2*pi) + X = JointRV('x', pdf) + + libraries = ['scipy', 'numpy', 'pymc'] + for lib in libraries: + try: + imported_lib = import_module(lib) + if imported_lib: + s0, s1, s2 = [], [], [] + s0 = sample(X, size=10, library=lib, seed=0) + s1 = sample(X, size=10, library=lib, seed=0) + s2 = sample(X, size=10, library=lib, seed=1) + assert all(s0 == s1) + assert all(s1 != s2) + except NotImplementedError: + continue + +# +# XXX: This fails for pymc. Previously the test appeared to pass but that is +# just because the library argument was not passed so the test always used +# scipy. +# +def test_issue_21057(): + m = Normal("x", [0, 0], [[0, 0], [0, 0]]) + n = MultivariateNormal("x", [0, 0], [[0, 0], [0, 0]]) + p = Normal("x", [0, 0], [[0, 0], [0, 1]]) + assert m == n + libraries = ('scipy', 'numpy') # , 'pymc') # <-- pymc fails + for library in libraries: + try: + imported_lib = import_module(library) + if imported_lib: + s1 = sample(m, size=8, library=library) + s2 = sample(n, size=8, library=library) + s3 = sample(p, size=8, library=library) + assert tuple(s1.flatten()) == tuple(s2.flatten()) + for s in s3: + assert tuple(s.flatten()) in p.pspace.distribution.set + except NotImplementedError: + continue + + +# +# When this passes the pymc part can be uncommented in test_issue_21057 above +# and this can be deleted. +# +@XFAIL +def test_issue_21057_pymc(): + m = Normal("x", [0, 0], [[0, 0], [0, 0]]) + n = MultivariateNormal("x", [0, 0], [[0, 0], [0, 0]]) + p = Normal("x", [0, 0], [[0, 0], [0, 1]]) + assert m == n + libraries = ('pymc',) + for library in libraries: + try: + imported_lib = import_module(library) + if imported_lib: + s1 = sample(m, size=8, library=library) + s2 = sample(n, size=8, library=library) + s3 = sample(p, size=8, library=library) + assert tuple(s1.flatten()) == tuple(s2.flatten()) + for s in s3: + assert tuple(s.flatten()) in p.pspace.distribution.set + except NotImplementedError: + continue diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_matrix_distributions.py b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_matrix_distributions.py new file mode 100644 index 0000000000000000000000000000000000000000..a2a2dcdd853793d9f77e1a88adf63158ed68e3ba --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_matrix_distributions.py @@ -0,0 +1,186 @@ +from sympy.concrete.products import Product +from sympy.core.numbers import pi +from sympy.core.singleton import S +from sympy.core.symbol import (Dummy, symbols) +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.special.gamma_functions import gamma +from sympy.matrices import Determinant, Matrix, Trace, MatrixSymbol, MatrixSet +from sympy.stats import density, sample +from sympy.stats.matrix_distributions import (MatrixGammaDistribution, + MatrixGamma, MatrixPSpace, Wishart, MatrixNormal, MatrixStudentT) +from sympy.testing.pytest import raises, skip +from sympy.external import import_module + + +def test_MatrixPSpace(): + M = MatrixGammaDistribution(1, 2, [[2, 1], [1, 2]]) + MP = MatrixPSpace('M', M, 2, 2) + assert MP.distribution == M + raises(ValueError, lambda: MatrixPSpace('M', M, 1.2, 2)) + +def test_MatrixGamma(): + M = MatrixGamma('M', 1, 2, [[1, 0], [0, 1]]) + assert M.pspace.distribution.set == MatrixSet(2, 2, S.Reals) + assert isinstance(density(M), MatrixGammaDistribution) + X = MatrixSymbol('X', 2, 2) + num = exp(Trace(Matrix([[-S(1)/2, 0], [0, -S(1)/2]])*X)) + assert density(M)(X).doit() == num/(4*pi*sqrt(Determinant(X))) + assert density(M)([[2, 1], [1, 2]]).doit() == sqrt(3)*exp(-2)/(12*pi) + X = MatrixSymbol('X', 1, 2) + Y = MatrixSymbol('Y', 1, 2) + assert density(M)([X, Y]).doit() == exp(-X[0, 0]/2 - Y[0, 1]/2)/(4*pi*sqrt( + X[0, 0]*Y[0, 1] - X[0, 1]*Y[0, 0])) + # symbolic + a, b = symbols('a b', positive=True) + d = symbols('d', positive=True, integer=True) + Y = MatrixSymbol('Y', d, d) + Z = MatrixSymbol('Z', 2, 2) + SM = MatrixSymbol('SM', d, d) + M2 = MatrixGamma('M2', a, b, SM) + M3 = MatrixGamma('M3', 2, 3, [[2, 1], [1, 2]]) + k = Dummy('k') + exprd = pi**(-d*(d - 1)/4)*b**(-a*d)*exp(Trace((-1/b)*SM**(-1)*Y) + )*Determinant(SM)**(-a)*Determinant(Y)**(a - d/2 - S(1)/2)/Product( + gamma(-k/2 + a + S(1)/2), (k, 1, d)) + assert density(M2)(Y).dummy_eq(exprd) + raises(NotImplementedError, lambda: density(M3 + M)(Z)) + raises(ValueError, lambda: density(M)(1)) + raises(ValueError, lambda: MatrixGamma('M', -1, 2, [[1, 0], [0, 1]])) + raises(ValueError, lambda: MatrixGamma('M', -1, -2, [[1, 0], [0, 1]])) + raises(ValueError, lambda: MatrixGamma('M', -1, 2, [[1, 0], [2, 1]])) + raises(ValueError, lambda: MatrixGamma('M', -1, 2, [[1, 0], [0]])) + +def test_Wishart(): + W = Wishart('W', 5, [[1, 0], [0, 1]]) + assert W.pspace.distribution.set == MatrixSet(2, 2, S.Reals) + X = MatrixSymbol('X', 2, 2) + term1 = exp(Trace(Matrix([[-S(1)/2, 0], [0, -S(1)/2]])*X)) + assert density(W)(X).doit() == term1 * Determinant(X)/(24*pi) + assert density(W)([[2, 1], [1, 2]]).doit() == exp(-2)/(8*pi) + n = symbols('n', positive=True) + d = symbols('d', positive=True, integer=True) + Y = MatrixSymbol('Y', d, d) + SM = MatrixSymbol('SM', d, d) + W = Wishart('W', n, SM) + k = Dummy('k') + exprd = 2**(-d*n/2)*pi**(-d*(d - 1)/4)*exp(Trace(-(S(1)/2)*SM**(-1)*Y) + )*Determinant(SM)**(-n/2)*Determinant(Y)**( + -d/2 + n/2 - S(1)/2)/Product(gamma(-k/2 + n/2 + S(1)/2), (k, 1, d)) + assert density(W)(Y).dummy_eq(exprd) + raises(ValueError, lambda: density(W)(1)) + raises(ValueError, lambda: Wishart('W', -1, [[1, 0], [0, 1]])) + raises(ValueError, lambda: Wishart('W', -1, [[1, 0], [2, 1]])) + raises(ValueError, lambda: Wishart('W', 2, [[1, 0], [0]])) + +def test_MatrixNormal(): + M = MatrixNormal('M', [[5, 6]], [4], [[2, 1], [1, 2]]) + assert M.pspace.distribution.set == MatrixSet(1, 2, S.Reals) + X = MatrixSymbol('X', 1, 2) + term1 = exp(-Trace(Matrix([[ S(2)/3, -S(1)/3], [-S(1)/3, S(2)/3]])*( + Matrix([[-5], [-6]]) + X.T)*Matrix([[S(1)/4]])*(Matrix([[-5, -6]]) + X))/2) + assert density(M)(X).doit() == (sqrt(3)) * term1/(24*pi) + assert density(M)([[7, 8]]).doit() == sqrt(3)*exp(-S(1)/3)/(24*pi) + d, n = symbols('d n', positive=True, integer=True) + SM2 = MatrixSymbol('SM2', d, d) + SM1 = MatrixSymbol('SM1', n, n) + LM = MatrixSymbol('LM', n, d) + Y = MatrixSymbol('Y', n, d) + M = MatrixNormal('M', LM, SM1, SM2) + exprd = (2*pi)**(-d*n/2)*exp(-Trace(SM2**(-1)*(-LM.T + Y.T)*SM1**(-1)*(-LM + Y) + )/2)*Determinant(SM1)**(-d/2)*Determinant(SM2)**(-n/2) + assert density(M)(Y).doit() == exprd + raises(ValueError, lambda: density(M)(1)) + raises(ValueError, lambda: MatrixNormal('M', [1, 2], [[1, 0], [0, 1]], [[1, 0], [2, 1]])) + raises(ValueError, lambda: MatrixNormal('M', [1, 2], [[1, 0], [2, 1]], [[1, 0], [0, 1]])) + raises(ValueError, lambda: MatrixNormal('M', [1, 2], [[1, 0], [0, 1]], [[1, 0], [0, 1]])) + raises(ValueError, lambda: MatrixNormal('M', [1, 2], [[1, 0], [2]], [[1, 0], [0, 1]])) + raises(ValueError, lambda: MatrixNormal('M', [1, 2], [[1, 0], [2, 1]], [[1, 0], [0]])) + raises(ValueError, lambda: MatrixNormal('M', [[1, 2]], [[1, 0], [0, 1]], [[1, 0]])) + raises(ValueError, lambda: MatrixNormal('M', [[1, 2]], [1], [[1, 0]])) + +def test_MatrixStudentT(): + M = MatrixStudentT('M', 2, [[5, 6]], [[2, 1], [1, 2]], [4]) + assert M.pspace.distribution.set == MatrixSet(1, 2, S.Reals) + X = MatrixSymbol('X', 1, 2) + D = pi ** (-1.0) * Determinant(Matrix([[4]])) ** (-1.0) * Determinant(Matrix([[2, 1], [1, 2]])) \ + ** (-0.5) / Determinant(Matrix([[S(1) / 4]]) * (Matrix([[-5, -6]]) + X) + * Matrix([[S(2) / 3, -S(1) / 3], [-S(1) / 3, S(2) / 3]]) * ( + Matrix([[-5], [-6]]) + X.T) + Matrix([[1]])) ** 2 + assert density(M)(X) == D + + v = symbols('v', positive=True) + n, p = 1, 2 + Omega = MatrixSymbol('Omega', p, p) + Sigma = MatrixSymbol('Sigma', n, n) + Location = MatrixSymbol('Location', n, p) + Y = MatrixSymbol('Y', n, p) + M = MatrixStudentT('M', v, Location, Omega, Sigma) + + exprd = gamma(v/2 + 1)*Determinant(Matrix([[1]]) + Sigma**(-1)*(-Location + Y)*Omega**(-1)*(-Location.T + Y.T))**(-v/2 - 1) / \ + (pi*gamma(v/2)*sqrt(Determinant(Omega))*Determinant(Sigma)) + + assert density(M)(Y) == exprd + raises(ValueError, lambda: density(M)(1)) + raises(ValueError, lambda: MatrixStudentT('M', 1, [1, 2], [[1, 0], [0, 1]], [[1, 0], [2, 1]])) + raises(ValueError, lambda: MatrixStudentT('M', 1, [1, 2], [[1, 0], [2, 1]], [[1, 0], [0, 1]])) + raises(ValueError, lambda: MatrixStudentT('M', 1, [1, 2], [[1, 0], [0, 1]], [[1, 0], [0, 1]])) + raises(ValueError, lambda: MatrixStudentT('M', 1, [1, 2], [[1, 0], [2]], [[1, 0], [0, 1]])) + raises(ValueError, lambda: MatrixStudentT('M', 1, [1, 2], [[1, 0], [2, 1]], [[1], [2]])) + raises(ValueError, lambda: MatrixStudentT('M', 1, [[1, 2]], [[1, 0], [0, 1]], [[1, 0]])) + raises(ValueError, lambda: MatrixStudentT('M', 1, [[1, 2]], [1], [[1, 0]])) + raises(ValueError, lambda: MatrixStudentT('M', -1, [1, 2], [[1, 0], [0, 1]], [4])) + +def test_sample_scipy(): + distribs_scipy = [ + MatrixNormal('M', [[5, 6]], [4], [[2, 1], [1, 2]]), + Wishart('W', 5, [[1, 0], [0, 1]]) + ] + + size = 5 + scipy = import_module('scipy') + if not scipy: + skip('Scipy not installed. Abort tests for _sample_scipy.') + else: + for X in distribs_scipy: + samps = sample(X, size=size) + for sam in samps: + assert Matrix(sam) in X.pspace.distribution.set + M = MatrixGamma('M', 1, 2, [[1, 0], [0, 1]]) + raises(NotImplementedError, lambda: sample(M, size=3)) + +def test_sample_pymc(): + distribs_pymc = [ + MatrixNormal('M', [[5, 6], [3, 4]], [[1, 0], [0, 1]], [[2, 1], [1, 2]]), + Wishart('W', 7, [[2, 1], [1, 2]]) + ] + size = 3 + pymc = import_module('pymc') + if not pymc: + skip('PyMC is not installed. Abort tests for _sample_pymc.') + else: + for X in distribs_pymc: + samps = sample(X, size=size, library='pymc') + for sam in samps: + assert Matrix(sam) in X.pspace.distribution.set + M = MatrixGamma('M', 1, 2, [[1, 0], [0, 1]]) + raises(NotImplementedError, lambda: sample(M, size=3)) + +def test_sample_seed(): + X = MatrixNormal('M', [[5, 6], [3, 4]], [[1, 0], [0, 1]], [[2, 1], [1, 2]]) + + libraries = ['scipy', 'numpy', 'pymc'] + for lib in libraries: + try: + imported_lib = import_module(lib) + if imported_lib: + s0, s1, s2 = [], [], [] + s0 = sample(X, size=10, library=lib, seed=0) + s1 = sample(X, size=10, library=lib, seed=0) + s2 = sample(X, size=10, library=lib, seed=1) + for i in range(10): + assert (s0[i] == s1[i]).all() + assert (s1[i] != s2[i]).all() + + except NotImplementedError: + continue diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_mix.py b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_mix.py new file mode 100644 index 0000000000000000000000000000000000000000..4334d9b144a5ddaad938f195f0276e0e8993aa35 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_mix.py @@ -0,0 +1,82 @@ +from sympy.concrete.summations import Sum +from sympy.core.add import Add +from sympy.core.mul import Mul +from sympy.core.numbers import (Integer, oo, pi) +from sympy.core.power import Pow +from sympy.core.relational import (Eq, Ne) +from sympy.core.symbol import (Dummy, Symbol, symbols) +from sympy.functions.combinatorial.factorials import factorial +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.special.delta_functions import DiracDelta +from sympy.functions.special.gamma_functions import gamma +from sympy.integrals.integrals import Integral +from sympy.simplify.simplify import simplify +from sympy.tensor.indexed import (Indexed, IndexedBase) +from sympy.functions.elementary.piecewise import ExprCondPair +from sympy.stats import (Poisson, Beta, Exponential, P, + Multinomial, MultivariateBeta) +from sympy.stats.crv_types import Normal +from sympy.stats.drv_types import PoissonDistribution +from sympy.stats.compound_rv import CompoundPSpace, CompoundDistribution +from sympy.stats.joint_rv import MarginalDistribution +from sympy.stats.rv import pspace, density +from sympy.testing.pytest import ignore_warnings + +def test_density(): + x = Symbol('x') + l = Symbol('l', positive=True) + rate = Beta(l, 2, 3) + X = Poisson(x, rate) + assert isinstance(pspace(X), CompoundPSpace) + assert density(X, Eq(rate, rate.symbol)) == PoissonDistribution(l) + N1 = Normal('N1', 0, 1) + N2 = Normal('N2', N1, 2) + assert density(N2)(0).doit() == sqrt(10)/(10*sqrt(pi)) + assert simplify(density(N2, Eq(N1, 1))(x)) == \ + sqrt(2)*exp(-(x - 1)**2/8)/(4*sqrt(pi)) + assert simplify(density(N2)(x)) == sqrt(10)*exp(-x**2/10)/(10*sqrt(pi)) + +def test_MarginalDistribution(): + a1, p1, p2 = symbols('a1 p1 p2', positive=True) + C = Multinomial('C', 2, p1, p2) + B = MultivariateBeta('B', a1, C[0]) + MGR = MarginalDistribution(B, (C[0],)) + mgrc = Mul(Symbol('B'), Piecewise(ExprCondPair(Mul(Integer(2), + Pow(Symbol('p1', positive=True), Indexed(IndexedBase(Symbol('C')), + Integer(0))), Pow(Symbol('p2', positive=True), + Indexed(IndexedBase(Symbol('C')), Integer(1))), + Pow(factorial(Indexed(IndexedBase(Symbol('C')), Integer(0))), Integer(-1)), + Pow(factorial(Indexed(IndexedBase(Symbol('C')), Integer(1))), Integer(-1))), + Eq(Add(Indexed(IndexedBase(Symbol('C')), Integer(0)), + Indexed(IndexedBase(Symbol('C')), Integer(1))), Integer(2))), + ExprCondPair(Integer(0), True)), Pow(gamma(Symbol('a1', positive=True)), + Integer(-1)), gamma(Add(Symbol('a1', positive=True), + Indexed(IndexedBase(Symbol('C')), Integer(0)))), + Pow(gamma(Indexed(IndexedBase(Symbol('C')), Integer(0))), Integer(-1)), + Pow(Indexed(IndexedBase(Symbol('B')), Integer(0)), + Add(Symbol('a1', positive=True), Integer(-1))), + Pow(Indexed(IndexedBase(Symbol('B')), Integer(1)), + Add(Indexed(IndexedBase(Symbol('C')), Integer(0)), Integer(-1)))) + assert MGR(C) == mgrc + +def test_compound_distribution(): + Y = Poisson('Y', 1) + Z = Poisson('Z', Y) + assert isinstance(pspace(Z), CompoundPSpace) + assert isinstance(pspace(Z).distribution, CompoundDistribution) + assert Z.pspace.distribution.pdf(1).doit() == exp(-2)*exp(exp(-1)) + +def test_mix_expression(): + Y, E = Poisson('Y', 1), Exponential('E', 1) + k = Dummy('k') + expr1 = Integral(Sum(exp(-1)*Integral(exp(-k)*DiracDelta(k - 2), (k, 0, oo) + )/factorial(k), (k, 0, oo)), (k, -oo, 0)) + expr2 = Integral(Sum(exp(-1)*Integral(exp(-k)*DiracDelta(k - 2), (k, 0, oo) + )/factorial(k), (k, 0, oo)), (k, 0, oo)) + assert P(Eq(Y + E, 1)) == 0 + assert P(Ne(Y + E, 2)) == 1 + with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed + assert P(E + Y < 2, evaluate=False).rewrite(Integral).dummy_eq(expr1) + assert P(E + Y > 2, evaluate=False).rewrite(Integral).dummy_eq(expr2) diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_random_matrix.py b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_random_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..ba570a16bc42620d53bce19be71e7d125965ede1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_random_matrix.py @@ -0,0 +1,135 @@ +from sympy.concrete.products import Product +from sympy.core.function import Lambda +from sympy.core.numbers import (I, Rational, pi) +from sympy.core.singleton import S +from sympy.core.symbol import Dummy +from sympy.functions.elementary.complexes import Abs +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.integrals.integrals import Integral +from sympy.matrices.dense import Matrix +from sympy.matrices.expressions.matexpr import MatrixSymbol +from sympy.matrices.expressions.trace import Trace +from sympy.tensor.indexed import IndexedBase +from sympy.stats import (GaussianUnitaryEnsemble as GUE, density, + GaussianOrthogonalEnsemble as GOE, + GaussianSymplecticEnsemble as GSE, + joint_eigen_distribution, + CircularUnitaryEnsemble as CUE, + CircularOrthogonalEnsemble as COE, + CircularSymplecticEnsemble as CSE, + JointEigenDistribution, + level_spacing_distribution, + Normal, Beta) +from sympy.stats.joint_rv_types import JointDistributionHandmade +from sympy.stats.rv import RandomMatrixSymbol +from sympy.stats.random_matrix_models import GaussianEnsemble, RandomMatrixPSpace +from sympy.testing.pytest import raises + +def test_GaussianEnsemble(): + G = GaussianEnsemble('G', 3) + assert density(G) == G.pspace.model + raises(ValueError, lambda: GaussianEnsemble('G', 3.5)) + +def test_GaussianUnitaryEnsemble(): + H = RandomMatrixSymbol('H', 3, 3) + G = GUE('U', 3) + assert density(G)(H) == sqrt(2)*exp(-3*Trace(H**2)/2)/(4*pi**Rational(9, 2)) + i, j = (Dummy('i', integer=True, positive=True), + Dummy('j', integer=True, positive=True)) + l = IndexedBase('l') + assert joint_eigen_distribution(G).dummy_eq( + Lambda((l[1], l[2], l[3]), + 27*sqrt(6)*exp(-3*(l[1]**2)/2 - 3*(l[2]**2)/2 - 3*(l[3]**2)/2)* + Product(Abs(l[i] - l[j])**2, (j, i + 1, 3), (i, 1, 2))/(16*pi**Rational(3, 2)))) + s = Dummy('s') + assert level_spacing_distribution(G).dummy_eq(Lambda(s, 32*s**2*exp(-4*s**2/pi)/pi**2)) + + +def test_GaussianOrthogonalEnsemble(): + H = RandomMatrixSymbol('H', 3, 3) + _H = MatrixSymbol('_H', 3, 3) + G = GOE('O', 3) + assert density(G)(H) == exp(-3*Trace(H**2)/4)/Integral(exp(-3*Trace(_H**2)/4), _H) + i, j = (Dummy('i', integer=True, positive=True), + Dummy('j', integer=True, positive=True)) + l = IndexedBase('l') + assert joint_eigen_distribution(G).dummy_eq( + Lambda((l[1], l[2], l[3]), + 9*sqrt(2)*exp(-3*l[1]**2/2 - 3*l[2]**2/2 - 3*l[3]**2/2)* + Product(Abs(l[i] - l[j]), (j, i + 1, 3), (i, 1, 2))/(32*pi))) + s = Dummy('s') + assert level_spacing_distribution(G).dummy_eq(Lambda(s, s*pi*exp(-s**2*pi/4)/2)) + +def test_GaussianSymplecticEnsemble(): + H = RandomMatrixSymbol('H', 3, 3) + _H = MatrixSymbol('_H', 3, 3) + G = GSE('O', 3) + assert density(G)(H) == exp(-3*Trace(H**2))/Integral(exp(-3*Trace(_H**2)), _H) + i, j = (Dummy('i', integer=True, positive=True), + Dummy('j', integer=True, positive=True)) + l = IndexedBase('l') + assert joint_eigen_distribution(G).dummy_eq( + Lambda((l[1], l[2], l[3]), + 162*sqrt(3)*exp(-3*l[1]**2/2 - 3*l[2]**2/2 - 3*l[3]**2/2)* + Product(Abs(l[i] - l[j])**4, (j, i + 1, 3), (i, 1, 2))/(5*pi**Rational(3, 2)))) + s = Dummy('s') + assert level_spacing_distribution(G).dummy_eq(Lambda(s, S(262144)*s**4*exp(-64*s**2/(9*pi))/(729*pi**3))) + +def test_CircularUnitaryEnsemble(): + CU = CUE('U', 3) + j, k = (Dummy('j', integer=True, positive=True), + Dummy('k', integer=True, positive=True)) + t = IndexedBase('t') + assert joint_eigen_distribution(CU).dummy_eq( + Lambda((t[1], t[2], t[3]), + Product(Abs(exp(I*t[j]) - exp(I*t[k]))**2, + (j, k + 1, 3), (k, 1, 2))/(48*pi**3)) + ) + +def test_CircularOrthogonalEnsemble(): + CO = COE('U', 3) + j, k = (Dummy('j', integer=True, positive=True), + Dummy('k', integer=True, positive=True)) + t = IndexedBase('t') + assert joint_eigen_distribution(CO).dummy_eq( + Lambda((t[1], t[2], t[3]), + Product(Abs(exp(I*t[j]) - exp(I*t[k])), + (j, k + 1, 3), (k, 1, 2))/(48*pi**2)) + ) + +def test_CircularSymplecticEnsemble(): + CS = CSE('U', 3) + j, k = (Dummy('j', integer=True, positive=True), + Dummy('k', integer=True, positive=True)) + t = IndexedBase('t') + assert joint_eigen_distribution(CS).dummy_eq( + Lambda((t[1], t[2], t[3]), + Product(Abs(exp(I*t[j]) - exp(I*t[k]))**4, + (j, k + 1, 3), (k, 1, 2))/(720*pi**3)) + ) + +def test_JointEigenDistribution(): + A = Matrix([[Normal('A00', 0, 1), Normal('A01', 1, 1)], + [Beta('A10', 1, 1), Beta('A11', 1, 1)]]) + assert JointEigenDistribution(A) == \ + JointDistributionHandmade(-sqrt(A[0, 0]**2 - 2*A[0, 0]*A[1, 1] + 4*A[0, 1]*A[1, 0] + A[1, 1]**2)/2 + + A[0, 0]/2 + A[1, 1]/2, sqrt(A[0, 0]**2 - 2*A[0, 0]*A[1, 1] + 4*A[0, 1]*A[1, 0] + A[1, 1]**2)/2 + A[0, 0]/2 + A[1, 1]/2) + raises(ValueError, lambda: JointEigenDistribution(Matrix([[1, 0], [2, 1]]))) + +def test_issue_19841(): + G1 = GUE('U', 2) + G2 = G1.xreplace({2: 2}) + assert G1.args == G2.args + + X = MatrixSymbol('X', 2, 2) + G = GSE('U', 2) + h_pspace = RandomMatrixPSpace('P', model=density(G)) + H = RandomMatrixSymbol('H', 2, 2, pspace=h_pspace) + H2 = RandomMatrixSymbol('H', 2, 2, pspace=None) + assert H.doit() == H + + assert (2*H).xreplace({H: X}) == 2*X + assert (2*H).xreplace({H2: X}) == 2*H + assert (2*H2).xreplace({H: X}) == 2*H2 + assert (2*H2).xreplace({H2: X}) == 2*X diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_rv.py b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_rv.py new file mode 100644 index 0000000000000000000000000000000000000000..185756300556f2fe70b76c402113ec2bb2501ef4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_rv.py @@ -0,0 +1,441 @@ +from sympy.concrete.summations import Sum +from sympy.core.basic import Basic +from sympy.core.containers import Tuple +from sympy.core.function import Lambda +from sympy.core.numbers import (Rational, nan, oo, pi) +from sympy.core.relational import Eq +from sympy.core.singleton import S +from sympy.core.symbol import (Symbol, symbols) +from sympy.functions.combinatorial.factorials import (FallingFactorial, binomial) +from sympy.functions.elementary.exponential import (exp, log) +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.functions.special.delta_functions import DiracDelta +from sympy.integrals.integrals import integrate +from sympy.logic.boolalg import (And, Or) +from sympy.matrices.dense import Matrix +from sympy.sets.sets import Interval +from sympy.tensor.indexed import Indexed +from sympy.stats import (Die, Normal, Exponential, FiniteRV, P, E, H, variance, + density, given, independent, dependent, where, pspace, GaussianUnitaryEnsemble, + random_symbols, sample, Geometric, factorial_moment, Binomial, Hypergeometric, + DiscreteUniform, Poisson, characteristic_function, moment_generating_function, + BernoulliProcess, Variance, Expectation, Probability, Covariance, covariance, cmoment, + moment, median) +from sympy.stats.rv import (IndependentProductPSpace, rs_swap, Density, NamedArgsMixin, + RandomSymbol, sample_iter, PSpace, is_random, RandomIndexedSymbol, RandomMatrixSymbol) +from sympy.testing.pytest import raises, skip, XFAIL, warns_deprecated_sympy +from sympy.external import import_module +from sympy.core.numbers import comp +from sympy.stats.frv_types import BernoulliDistribution +from sympy.core.symbol import Dummy +from sympy.functions.elementary.piecewise import Piecewise + +def test_where(): + X, Y = Die('X'), Die('Y') + Z = Normal('Z', 0, 1) + + assert where(Z**2 <= 1).set == Interval(-1, 1) + assert where(Z**2 <= 1).as_boolean() == Interval(-1, 1).as_relational(Z.symbol) + assert where(And(X > Y, Y > 4)).as_boolean() == And( + Eq(X.symbol, 6), Eq(Y.symbol, 5)) + + assert len(where(X < 3).set) == 2 + assert 1 in where(X < 3).set + + X, Y = Normal('X', 0, 1), Normal('Y', 0, 1) + assert where(And(X**2 <= 1, X >= 0)).set == Interval(0, 1) + XX = given(X, And(X**2 <= 1, X >= 0)) + assert XX.pspace.domain.set == Interval(0, 1) + assert XX.pspace.domain.as_boolean() == \ + And(0 <= X.symbol, X.symbol**2 <= 1, -oo < X.symbol, X.symbol < oo) + + with raises(TypeError): + XX = given(X, X + 3) + + +def test_random_symbols(): + X, Y = Normal('X', 0, 1), Normal('Y', 0, 1) + + assert set(random_symbols(2*X + 1)) == {X} + assert set(random_symbols(2*X + Y)) == {X, Y} + assert set(random_symbols(2*X + Y.symbol)) == {X} + assert set(random_symbols(2)) == set() + + +def test_characteristic_function(): + # Imports I from sympy + from sympy.core.numbers import I + X = Normal('X',0,1) + Y = DiscreteUniform('Y', [1,2,7]) + Z = Poisson('Z', 2) + t = symbols('_t') + P = Lambda(t, exp(-t**2/2)) + Q = Lambda(t, exp(7*t*I)/3 + exp(2*t*I)/3 + exp(t*I)/3) + R = Lambda(t, exp(2 * exp(t*I) - 2)) + + + assert characteristic_function(X).dummy_eq(P) + assert characteristic_function(Y).dummy_eq(Q) + assert characteristic_function(Z).dummy_eq(R) + + +def test_moment_generating_function(): + + X = Normal('X',0,1) + Y = DiscreteUniform('Y', [1,2,7]) + Z = Poisson('Z', 2) + t = symbols('_t') + P = Lambda(t, exp(t**2/2)) + Q = Lambda(t, (exp(7*t)/3 + exp(2*t)/3 + exp(t)/3)) + R = Lambda(t, exp(2 * exp(t) - 2)) + + + assert moment_generating_function(X).dummy_eq(P) + assert moment_generating_function(Y).dummy_eq(Q) + assert moment_generating_function(Z).dummy_eq(R) + +def test_sample_iter(): + + X = Normal('X',0,1) + Y = DiscreteUniform('Y', [1, 2, 7]) + Z = Poisson('Z', 2) + + scipy = import_module('scipy') + if not scipy: + skip('Scipy is not installed. Abort tests') + expr = X**2 + 3 + iterator = sample_iter(expr) + + expr2 = Y**2 + 5*Y + 4 + iterator2 = sample_iter(expr2) + + expr3 = Z**3 + 4 + iterator3 = sample_iter(expr3) + + def is_iterator(obj): + if ( + hasattr(obj, '__iter__') and + (hasattr(obj, 'next') or + hasattr(obj, '__next__')) and + callable(obj.__iter__) and + obj.__iter__() is obj + ): + return True + else: + return False + assert is_iterator(iterator) + assert is_iterator(iterator2) + assert is_iterator(iterator3) + +def test_pspace(): + X, Y = Normal('X', 0, 1), Normal('Y', 0, 1) + x = Symbol('x') + + raises(ValueError, lambda: pspace(5 + 3)) + raises(ValueError, lambda: pspace(x < 1)) + assert pspace(X) == X.pspace + assert pspace(2*X + 1) == X.pspace + assert pspace(2*X + Y) == IndependentProductPSpace(Y.pspace, X.pspace) + +def test_rs_swap(): + X = Normal('x', 0, 1) + Y = Exponential('y', 1) + + XX = Normal('x', 0, 2) + YY = Normal('y', 0, 3) + + expr = 2*X + Y + assert expr.subs(rs_swap((X, Y), (YY, XX))) == 2*XX + YY + + +def test_RandomSymbol(): + + X = Normal('x', 0, 1) + Y = Normal('x', 0, 2) + assert X.symbol == Y.symbol + assert X != Y + + assert X.name == X.symbol.name + + X = Normal('lambda', 0, 1) # make sure we can use protected terms + X = Normal('Lambda', 0, 1) # make sure we can use SymPy terms + + +def test_RandomSymbol_diff(): + X = Normal('x', 0, 1) + assert (2*X).diff(X) + + +def test_random_symbol_no_pspace(): + x = RandomSymbol(Symbol('x')) + assert x.pspace == PSpace() + +def test_overlap(): + X = Normal('x', 0, 1) + Y = Normal('x', 0, 2) + + raises(ValueError, lambda: P(X > Y)) + + +def test_IndependentProductPSpace(): + X = Normal('X', 0, 1) + Y = Normal('Y', 0, 1) + px = X.pspace + py = Y.pspace + assert pspace(X + Y) == IndependentProductPSpace(px, py) + assert pspace(X + Y) == IndependentProductPSpace(py, px) + + +def test_E(): + assert E(5) == 5 + + +def test_H(): + X = Normal('X', 0, 1) + D = Die('D', sides = 4) + G = Geometric('G', 0.5) + assert H(X, X > 0) == -log(2)/2 + S.Half + log(pi)/2 + assert H(D, D > 2) == log(2) + assert comp(H(G).evalf().round(2), 1.39) + + +def test_Sample(): + X = Die('X', 6) + Y = Normal('Y', 0, 1) + z = Symbol('z', integer=True) + + scipy = import_module('scipy') + if not scipy: + skip('Scipy is not installed. Abort tests') + assert sample(X) in [1, 2, 3, 4, 5, 6] + assert isinstance(sample(X + Y), float) + + assert P(X + Y > 0, Y < 0, numsamples=10).is_number + assert E(X + Y, numsamples=10).is_number + assert E(X**2 + Y, numsamples=10).is_number + assert E((X + Y)**2, numsamples=10).is_number + assert variance(X + Y, numsamples=10).is_number + + raises(TypeError, lambda: P(Y > z, numsamples=5)) + + assert P(sin(Y) <= 1, numsamples=10) == 1.0 + assert P(sin(Y) <= 1, cos(Y) < 1, numsamples=10) == 1.0 + + assert all(i in range(1, 7) for i in density(X, numsamples=10)) + assert all(i in range(4, 7) for i in density(X, X>3, numsamples=10)) + + numpy = import_module('numpy') + if not numpy: + skip('Numpy is not installed. Abort tests') + #Test Issue #21563: Output of sample must be a float or array + assert isinstance(sample(X), (numpy.int32, numpy.int64)) + assert isinstance(sample(Y), numpy.float64) + assert isinstance(sample(X, size=2), numpy.ndarray) + + with warns_deprecated_sympy(): + sample(X, numsamples=2) + +@XFAIL +def test_samplingE(): + scipy = import_module('scipy') + if not scipy: + skip('Scipy is not installed. Abort tests') + Y = Normal('Y', 0, 1) + z = Symbol('z', integer=True) + assert E(Sum(1/z**Y, (z, 1, oo)), Y > 2, numsamples=3).is_number + + +def test_given(): + X = Normal('X', 0, 1) + Y = Normal('Y', 0, 1) + A = given(X, True) + B = given(X, Y > 2) + + assert X == A == B + + +def test_factorial_moment(): + X = Poisson('X', 2) + Y = Binomial('Y', 2, S.Half) + Z = Hypergeometric('Z', 4, 2, 2) + assert factorial_moment(X, 2) == 4 + assert factorial_moment(Y, 2) == S.Half + assert factorial_moment(Z, 2) == Rational(1, 3) + + x, y, z, l = symbols('x y z l') + Y = Binomial('Y', 2, y) + Z = Hypergeometric('Z', 10, 2, 3) + assert factorial_moment(Y, l) == y**2*FallingFactorial( + 2, l) + 2*y*(1 - y)*FallingFactorial(1, l) + (1 - y)**2*\ + FallingFactorial(0, l) + assert factorial_moment(Z, l) == 7*FallingFactorial(0, l)/\ + 15 + 7*FallingFactorial(1, l)/15 + FallingFactorial(2, l)/15 + + +def test_dependence(): + X, Y = Die('X'), Die('Y') + assert independent(X, 2*Y) + assert not dependent(X, 2*Y) + + X, Y = Normal('X', 0, 1), Normal('Y', 0, 1) + assert independent(X, Y) + assert dependent(X, 2*X) + + # Create a dependency + XX, YY = given(Tuple(X, Y), Eq(X + Y, 3)) + assert dependent(XX, YY) + +def test_dependent_finite(): + X, Y = Die('X'), Die('Y') + # Dependence testing requires symbolic conditions which currently break + # finite random variables + assert dependent(X, Y + X) + + XX, YY = given(Tuple(X, Y), X + Y > 5) # Create a dependency + assert dependent(XX, YY) + + +def test_normality(): + X, Y = Normal('X', 0, 1), Normal('Y', 0, 1) + x = Symbol('x', real=True) + z = Symbol('z', real=True) + dens = density(X - Y, Eq(X + Y, z)) + + assert integrate(dens(x), (x, -oo, oo)) == 1 + + +def test_Density(): + X = Die('X', 6) + d = Density(X) + assert d.doit() == density(X) + +def test_NamedArgsMixin(): + class Foo(Basic, NamedArgsMixin): + _argnames = 'foo', 'bar' + + a = Foo(S(1), S(2)) + + assert a.foo == 1 + assert a.bar == 2 + + raises(AttributeError, lambda: a.baz) + + class Bar(Basic, NamedArgsMixin): + pass + + raises(AttributeError, lambda: Bar(S(1), S(2)).foo) + +def test_density_constant(): + assert density(3)(2) == 0 + assert density(3)(3) == DiracDelta(0) + +def test_cmoment_constant(): + assert variance(3) == 0 + assert cmoment(3, 3) == 0 + assert cmoment(3, 4) == 0 + x = Symbol('x') + assert variance(x) == 0 + assert cmoment(x, 15) == 0 + assert cmoment(x, 0) == 1 + +def test_moment_constant(): + assert moment(3, 0) == 1 + assert moment(3, 1) == 3 + assert moment(3, 2) == 9 + x = Symbol('x') + assert moment(x, 2) == x**2 + +def test_median_constant(): + assert median(3) == 3 + x = Symbol('x') + assert median(x) == x + +def test_real(): + x = Normal('x', 0, 1) + assert x.is_real + + +def test_issue_10052(): + X = Exponential('X', 3) + assert P(X < oo) == 1 + assert P(X > oo) == 0 + assert P(X < 2, X > oo) == 0 + assert P(X < oo, X > oo) == 0 + assert P(X < oo, X > 2) == 1 + assert P(X < 3, X == 2) == 0 + raises(ValueError, lambda: P(1)) + raises(ValueError, lambda: P(X < 1, 2)) + +def test_issue_11934(): + density = {0: .5, 1: .5} + X = FiniteRV('X', density) + assert E(X) == 0.5 + assert P( X>= 2) == 0 + +def test_issue_8129(): + X = Exponential('X', 4) + assert P(X >= X) == 1 + assert P(X > X) == 0 + assert P(X > X+1) == 0 + +def test_issue_12237(): + X = Normal('X', 0, 1) + Y = Normal('Y', 0, 1) + U = P(X > 0, X) + V = P(Y < 0, X) + W = P(X + Y > 0, X) + assert W == P(X + Y > 0, X) + assert U == BernoulliDistribution(S.Half, S.Zero, S.One) + assert V == S.Half + +def test_is_random(): + X = Normal('X', 0, 1) + Y = Normal('Y', 0, 1) + a, b = symbols('a, b') + G = GaussianUnitaryEnsemble('U', 2) + B = BernoulliProcess('B', 0.9) + assert not is_random(a) + assert not is_random(a + b) + assert not is_random(a * b) + assert not is_random(Matrix([a**2, b**2])) + assert is_random(X) + assert is_random(X**2 + Y) + assert is_random(Y + b**2) + assert is_random(Y > 5) + assert is_random(B[3] < 1) + assert is_random(G) + assert is_random(X * Y * B[1]) + assert is_random(Matrix([[X, B[2]], [G, Y]])) + assert is_random(Eq(X, 4)) + +def test_issue_12283(): + x = symbols('x') + X = RandomSymbol(x) + Y = RandomSymbol('Y') + Z = RandomMatrixSymbol('Z', 2, 1) + W = RandomMatrixSymbol('W', 2, 1) + RI = RandomIndexedSymbol(Indexed('RI', 3)) + assert pspace(Z) == PSpace() + assert pspace(RI) == PSpace() + assert pspace(X) == PSpace() + assert E(X) == Expectation(X) + assert P(Y > 3) == Probability(Y > 3) + assert variance(X) == Variance(X) + assert variance(RI) == Variance(RI) + assert covariance(X, Y) == Covariance(X, Y) + assert covariance(W, Z) == Covariance(W, Z) + +def test_issue_6810(): + X = Die('X', 6) + Y = Normal('Y', 0, 1) + assert P(Eq(X, 2)) == S(1)/6 + assert P(Eq(Y, 0)) == 0 + assert P(Or(X > 2, X < 3)) == 1 + assert P(And(X > 3, X > 2)) == S(1)/2 + +def test_issue_20286(): + n, p = symbols('n p') + B = Binomial('B', n, p) + k = Dummy('k', integer = True) + eq = Sum(Piecewise((-p**k*(1 - p)**(-k + n)*log(p**k*(1 - p)**(-k + n)*binomial(n, k))*binomial(n, k), (k >= 0) & (k <= n)), (nan, True)), (k, 0, n)) + assert eq.dummy_eq(H(B)) diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_stochastic_process.py b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_stochastic_process.py new file mode 100644 index 0000000000000000000000000000000000000000..3e42ffc8632240b1d85a774467a057e9857c567c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_stochastic_process.py @@ -0,0 +1,763 @@ +from sympy.concrete.summations import Sum +from sympy.core.containers import Tuple +from sympy.core.function import Lambda +from sympy.core.numbers import (Float, Rational, oo, pi) +from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne) +from sympy.core.singleton import S +from sympy.core.symbol import (Symbol, symbols) +from sympy.functions.combinatorial.factorials import factorial +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.integers import ceiling +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.special.error_functions import erf +from sympy.functions.special.gamma_functions import (gamma, lowergamma) +from sympy.logic.boolalg import (And, Not) +from sympy.matrices.dense import Matrix +from sympy.matrices.expressions.matexpr import MatrixSymbol +from sympy.matrices.immutable import ImmutableMatrix +from sympy.sets.contains import Contains +from sympy.sets.fancysets import Range +from sympy.sets.sets import (FiniteSet, Interval) +from sympy.stats import (DiscreteMarkovChain, P, TransitionMatrixOf, E, + StochasticStateSpaceOf, variance, ContinuousMarkovChain, + BernoulliProcess, PoissonProcess, WienerProcess, + GammaProcess, sample_stochastic_process) +from sympy.stats.joint_rv import JointDistribution +from sympy.stats.joint_rv_types import JointDistributionHandmade +from sympy.stats.rv import RandomIndexedSymbol +from sympy.stats.symbolic_probability import Probability, Expectation +from sympy.testing.pytest import (raises, skip, ignore_warnings, + warns_deprecated_sympy) +from sympy.external import import_module +from sympy.stats.frv_types import BernoulliDistribution +from sympy.stats.drv_types import PoissonDistribution +from sympy.stats.crv_types import NormalDistribution, GammaDistribution +from sympy.core.symbol import Str + + +def test_DiscreteMarkovChain(): + + # pass only the name + X = DiscreteMarkovChain("X") + assert isinstance(X.state_space, Range) + assert X.index_set == S.Naturals0 + assert isinstance(X.transition_probabilities, MatrixSymbol) + t = symbols('t', positive=True, integer=True) + assert isinstance(X[t], RandomIndexedSymbol) + assert E(X[0]) == Expectation(X[0]) + raises(TypeError, lambda: DiscreteMarkovChain(1)) + raises(NotImplementedError, lambda: X(t)) + raises(NotImplementedError, lambda: X.communication_classes()) + raises(NotImplementedError, lambda: X.canonical_form()) + raises(NotImplementedError, lambda: X.decompose()) + + nz = Symbol('n', integer=True) + TZ = MatrixSymbol('M', nz, nz) + SZ = Range(nz) + YZ = DiscreteMarkovChain('Y', SZ, TZ) + assert P(Eq(YZ[2], 1), Eq(YZ[1], 0)) == TZ[0, 1] + + raises(ValueError, lambda: sample_stochastic_process(t)) + raises(ValueError, lambda: next(sample_stochastic_process(X))) + # pass name and state_space + # any hashable object should be a valid state + # states should be valid as a tuple/set/list/Tuple/Range + sym, rainy, cloudy, sunny = symbols('a Rainy Cloudy Sunny', real=True) + state_spaces = [(1, 2, 3), [Str('Hello'), sym, DiscreteMarkovChain("Y", (1,2,3))], + Tuple(S(1), exp(sym), Str('World'), sympify=False), Range(-1, 5, 2), + [rainy, cloudy, sunny]] + chains = [DiscreteMarkovChain("Y", state_space) for state_space in state_spaces] + + for i, Y in enumerate(chains): + assert isinstance(Y.transition_probabilities, MatrixSymbol) + assert Y.state_space == state_spaces[i] or Y.state_space == FiniteSet(*state_spaces[i]) + assert Y.number_of_states == 3 + + with ignore_warnings(UserWarning): # TODO: Restore tests once warnings are removed + assert P(Eq(Y[2], 1), Eq(Y[0], 2), evaluate=False) == Probability(Eq(Y[2], 1), Eq(Y[0], 2)) + assert E(Y[0]) == Expectation(Y[0]) + + raises(ValueError, lambda: next(sample_stochastic_process(Y))) + + raises(TypeError, lambda: DiscreteMarkovChain("Y", {1: 1})) + Y = DiscreteMarkovChain("Y", Range(1, t, 2)) + assert Y.number_of_states == ceiling((t-1)/2) + + # pass name and transition_probabilities + chains = [DiscreteMarkovChain("Y", trans_probs=Matrix([])), + DiscreteMarkovChain("Y", trans_probs=Matrix([[0, 1], [1, 0]])), + DiscreteMarkovChain("Y", trans_probs=Matrix([[pi, 1-pi], [sym, 1-sym]]))] + for Z in chains: + assert Z.number_of_states == Z.transition_probabilities.shape[0] + assert isinstance(Z.transition_probabilities, ImmutableMatrix) + + # pass name, state_space and transition_probabilities + T = Matrix([[0.5, 0.2, 0.3],[0.2, 0.5, 0.3],[0.2, 0.3, 0.5]]) + TS = MatrixSymbol('T', 3, 3) + Y = DiscreteMarkovChain("Y", [0, 1, 2], T) + YS = DiscreteMarkovChain("Y", ['One', 'Two', 3], TS) + assert Y.joint_distribution(1, Y[2], 3) == JointDistribution(Y[1], Y[2], Y[3]) + raises(ValueError, lambda: Y.joint_distribution(Y[1].symbol, Y[2].symbol)) + assert P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2) == Float(0.36, 2) + assert (P(Eq(YS[3], 2), Eq(YS[1], 1)) - + (TS[0, 2]*TS[1, 0] + TS[1, 1]*TS[1, 2] + TS[1, 2]*TS[2, 2])).simplify() == 0 + assert P(Eq(YS[1], 1), Eq(YS[2], 2)) == Probability(Eq(YS[1], 1)) + assert P(Eq(YS[3], 3), Eq(YS[1], 1)) == TS[0, 2]*TS[1, 0] + TS[1, 1]*TS[1, 2] + TS[1, 2]*TS[2, 2] + TO = Matrix([[0.25, 0.75, 0],[0, 0.25, 0.75],[0.75, 0, 0.25]]) + assert P(Eq(Y[3], 2), Eq(Y[1], 1) & TransitionMatrixOf(Y, TO)).round(3) == Float(0.375, 3) + with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed + assert E(Y[3], evaluate=False) == Expectation(Y[3]) + assert E(Y[3], Eq(Y[2], 1)).round(2) == Float(1.1, 3) + TSO = MatrixSymbol('T', 4, 4) + raises(ValueError, lambda: str(P(Eq(YS[3], 2), Eq(YS[1], 1) & TransitionMatrixOf(YS, TSO)))) + raises(TypeError, lambda: DiscreteMarkovChain("Z", [0, 1, 2], symbols('M'))) + raises(ValueError, lambda: DiscreteMarkovChain("Z", [0, 1, 2], MatrixSymbol('T', 3, 4))) + raises(ValueError, lambda: E(Y[3], Eq(Y[2], 6))) + raises(ValueError, lambda: E(Y[2], Eq(Y[3], 1))) + + + # extended tests for probability queries + TO1 = Matrix([[Rational(1, 4), Rational(3, 4), 0],[Rational(1, 3), Rational(1, 3), Rational(1, 3)],[0, Rational(1, 4), Rational(3, 4)]]) + assert P(And(Eq(Y[2], 1), Eq(Y[1], 1), Eq(Y[0], 0)), + Eq(Probability(Eq(Y[0], 0)), Rational(1, 4)) & TransitionMatrixOf(Y, TO1)) == Rational(1, 16) + assert P(And(Eq(Y[2], 1), Eq(Y[1], 1), Eq(Y[0], 0)), TransitionMatrixOf(Y, TO1)) == \ + Probability(Eq(Y[0], 0))/4 + assert P(Lt(X[1], 2) & Gt(X[1], 0), Eq(X[0], 2) & + StochasticStateSpaceOf(X, [0, 1, 2]) & TransitionMatrixOf(X, TO1)) == Rational(1, 4) + assert P(Lt(X[1], 2) & Gt(X[1], 0), Eq(X[0], 2) & + StochasticStateSpaceOf(X, [S(0), '0', 1]) & TransitionMatrixOf(X, TO1)) == Rational(1, 4) + assert P(Ne(X[1], 2) & Ne(X[1], 1), Eq(X[0], 2) & + StochasticStateSpaceOf(X, [0, 1, 2]) & TransitionMatrixOf(X, TO1)) is S.Zero + assert P(Ne(X[1], 2) & Ne(X[1], 1), Eq(X[0], 2) & + StochasticStateSpaceOf(X, [S(0), '0', 1]) & TransitionMatrixOf(X, TO1)) is S.Zero + assert P(And(Eq(Y[2], 1), Eq(Y[1], 1), Eq(Y[0], 0)), Eq(Y[1], 1)) == 0.1*Probability(Eq(Y[0], 0)) + + # testing properties of Markov chain + TO2 = Matrix([[S.One, 0, 0],[Rational(1, 3), Rational(1, 3), Rational(1, 3)],[0, Rational(1, 4), Rational(3, 4)]]) + TO3 = Matrix([[Rational(1, 4), Rational(3, 4), 0],[Rational(1, 3), Rational(1, 3), Rational(1, 3)], [0, Rational(1, 4), Rational(3, 4)]]) + Y2 = DiscreteMarkovChain('Y', trans_probs=TO2) + Y3 = DiscreteMarkovChain('Y', trans_probs=TO3) + assert Y3.fundamental_matrix() == ImmutableMatrix([[176, 81, -132], [36, 141, -52], [-44, -39, 208]])/125 + assert Y2.is_absorbing_chain() == True + assert Y3.is_absorbing_chain() == False + assert Y2.canonical_form() == ([0, 1, 2], TO2) + assert Y3.canonical_form() == ([0, 1, 2], TO3) + assert Y2.decompose() == ([0, 1, 2], TO2[0:1, 0:1], TO2[1:3, 0:1], TO2[1:3, 1:3]) + assert Y3.decompose() == ([0, 1, 2], TO3, Matrix(0, 3, []), Matrix(0, 0, [])) + TO4 = Matrix([[Rational(1, 5), Rational(2, 5), Rational(2, 5)], [Rational(1, 10), S.Half, Rational(2, 5)], [Rational(3, 5), Rational(3, 10), Rational(1, 10)]]) + Y4 = DiscreteMarkovChain('Y', trans_probs=TO4) + w = ImmutableMatrix([[Rational(11, 39), Rational(16, 39), Rational(4, 13)]]) + assert Y4.limiting_distribution == w + assert Y4.is_regular() == True + assert Y4.is_ergodic() == True + TS1 = MatrixSymbol('T', 3, 3) + Y5 = DiscreteMarkovChain('Y', trans_probs=TS1) + assert Y5.limiting_distribution(w, TO4).doit() == True + assert Y5.stationary_distribution(condition_set=True).subs(TS1, TO4).contains(w).doit() == S.true + TO6 = Matrix([[S.One, 0, 0, 0, 0],[S.Half, 0, S.Half, 0, 0],[0, S.Half, 0, S.Half, 0], [0, 0, S.Half, 0, S.Half], [0, 0, 0, 0, 1]]) + Y6 = DiscreteMarkovChain('Y', trans_probs=TO6) + assert Y6.fundamental_matrix() == ImmutableMatrix([[Rational(3, 2), S.One, S.Half], [S.One, S(2), S.One], [S.Half, S.One, Rational(3, 2)]]) + assert Y6.absorbing_probabilities() == ImmutableMatrix([[Rational(3, 4), Rational(1, 4)], [S.Half, S.Half], [Rational(1, 4), Rational(3, 4)]]) + with warns_deprecated_sympy(): + Y6.absorbing_probabilites() + TO7 = Matrix([[Rational(1, 2), Rational(1, 4), Rational(1, 4)], [Rational(1, 2), 0, Rational(1, 2)], [Rational(1, 4), Rational(1, 4), Rational(1, 2)]]) + Y7 = DiscreteMarkovChain('Y', trans_probs=TO7) + assert Y7.is_absorbing_chain() == False + assert Y7.fundamental_matrix() == ImmutableMatrix([[Rational(86, 75), Rational(1, 25), Rational(-14, 75)], + [Rational(2, 25), Rational(21, 25), Rational(2, 25)], + [Rational(-14, 75), Rational(1, 25), Rational(86, 75)]]) + + # test for zero-sized matrix functionality + X = DiscreteMarkovChain('X', trans_probs=Matrix([])) + assert X.number_of_states == 0 + assert X.stationary_distribution() == Matrix([[]]) + assert X.communication_classes() == [] + assert X.canonical_form() == ([], Matrix([])) + assert X.decompose() == ([], Matrix([]), Matrix([]), Matrix([])) + assert X.is_regular() == False + assert X.is_ergodic() == False + + # test communication_class + # see https://drive.google.com/drive/folders/1HbxLlwwn2b3U8Lj7eb_ASIUb5vYaNIjg?usp=sharing + # tutorial 2.pdf + TO7 = Matrix([[0, 5, 5, 0, 0], + [0, 0, 0, 10, 0], + [5, 0, 5, 0, 0], + [0, 10, 0, 0, 0], + [0, 3, 0, 3, 4]])/10 + Y7 = DiscreteMarkovChain('Y', trans_probs=TO7) + tuples = Y7.communication_classes() + classes, recurrence, periods = list(zip(*tuples)) + assert classes == ([1, 3], [0, 2], [4]) + assert recurrence == (True, False, False) + assert periods == (2, 1, 1) + + TO8 = Matrix([[0, 0, 0, 10, 0, 0], + [5, 0, 5, 0, 0, 0], + [0, 4, 0, 0, 0, 6], + [10, 0, 0, 0, 0, 0], + [0, 10, 0, 0, 0, 0], + [0, 0, 0, 5, 5, 0]])/10 + Y8 = DiscreteMarkovChain('Y', trans_probs=TO8) + tuples = Y8.communication_classes() + classes, recurrence, periods = list(zip(*tuples)) + assert classes == ([0, 3], [1, 2, 5, 4]) + assert recurrence == (True, False) + assert periods == (2, 2) + + TO9 = Matrix([[2, 0, 0, 3, 0, 0, 3, 2, 0, 0], + [0, 10, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 2, 2, 0, 0, 0, 0, 0, 3, 3], + [0, 0, 0, 3, 0, 0, 6, 1, 0, 0], + [0, 0, 0, 0, 5, 5, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 10, 0, 0, 0, 0], + [4, 0, 0, 5, 0, 0, 1, 0, 0, 0], + [2, 0, 0, 4, 0, 0, 2, 2, 0, 0], + [3, 0, 1, 0, 0, 0, 0, 0, 4, 2], + [0, 0, 4, 0, 0, 0, 0, 0, 3, 3]])/10 + Y9 = DiscreteMarkovChain('Y', trans_probs=TO9) + tuples = Y9.communication_classes() + classes, recurrence, periods = list(zip(*tuples)) + assert classes == ([0, 3, 6, 7], [1], [2, 8, 9], [5], [4]) + assert recurrence == (True, True, False, True, False) + assert periods == (1, 1, 1, 1, 1) + + # test canonical form + # see https://web.archive.org/web/20201230182007/https://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter11.pdf + # example 11.13 + T = Matrix([[1, 0, 0, 0, 0], + [S(1) / 2, 0, S(1) / 2, 0, 0], + [0, S(1) / 2, 0, S(1) / 2, 0], + [0, 0, S(1) / 2, 0, S(1) / 2], + [0, 0, 0, 0, S(1)]]) + DW = DiscreteMarkovChain('DW', [0, 1, 2, 3, 4], T) + states, A, B, C = DW.decompose() + assert states == [0, 4, 1, 2, 3] + assert A == Matrix([[1, 0], [0, 1]]) + assert B == Matrix([[S(1)/2, 0], [0, 0], [0, S(1)/2]]) + assert C == Matrix([[0, S(1)/2, 0], [S(1)/2, 0, S(1)/2], [0, S(1)/2, 0]]) + states, new_matrix = DW.canonical_form() + assert states == [0, 4, 1, 2, 3] + assert new_matrix == Matrix([[1, 0, 0, 0, 0], + [0, 1, 0, 0, 0], + [S(1)/2, 0, 0, S(1)/2, 0], + [0, 0, S(1)/2, 0, S(1)/2], + [0, S(1)/2, 0, S(1)/2, 0]]) + + # test regular and ergodic + # https://web.archive.org/web/20201230182007/https://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter11.pdf + T = Matrix([[0, 4, 0, 0, 0], + [1, 0, 3, 0, 0], + [0, 2, 0, 2, 0], + [0, 0, 3, 0, 1], + [0, 0, 0, 4, 0]])/4 + X = DiscreteMarkovChain('X', trans_probs=T) + assert not X.is_regular() + assert X.is_ergodic() + T = Matrix([[0, 1], [1, 0]]) + X = DiscreteMarkovChain('X', trans_probs=T) + assert not X.is_regular() + assert X.is_ergodic() + # http://www.math.wisc.edu/~valko/courses/331/MC2.pdf + T = Matrix([[2, 1, 1], + [2, 0, 2], + [1, 1, 2]])/4 + X = DiscreteMarkovChain('X', trans_probs=T) + assert X.is_regular() + assert X.is_ergodic() + # https://docs.ufpr.br/~lucambio/CE222/1S2014/Kemeny-Snell1976.pdf + T = Matrix([[1, 1], [1, 1]])/2 + X = DiscreteMarkovChain('X', trans_probs=T) + assert X.is_regular() + assert X.is_ergodic() + + # test is_absorbing_chain + T = Matrix([[0, 1, 0], + [1, 0, 0], + [0, 0, 1]]) + X = DiscreteMarkovChain('X', trans_probs=T) + assert not X.is_absorbing_chain() + # https://en.wikipedia.org/wiki/Absorbing_Markov_chain + T = Matrix([[1, 1, 0, 0], + [0, 1, 1, 0], + [1, 0, 0, 1], + [0, 0, 0, 2]])/2 + X = DiscreteMarkovChain('X', trans_probs=T) + assert X.is_absorbing_chain() + T = Matrix([[2, 0, 0, 0, 0], + [1, 0, 1, 0, 0], + [0, 1, 0, 1, 0], + [0, 0, 1, 0, 1], + [0, 0, 0, 0, 2]])/2 + X = DiscreteMarkovChain('X', trans_probs=T) + assert X.is_absorbing_chain() + + # test custom state space + Y10 = DiscreteMarkovChain('Y', [1, 2, 3], TO2) + tuples = Y10.communication_classes() + classes, recurrence, periods = list(zip(*tuples)) + assert classes == ([1], [2, 3]) + assert recurrence == (True, False) + assert periods == (1, 1) + assert Y10.canonical_form() == ([1, 2, 3], TO2) + assert Y10.decompose() == ([1, 2, 3], TO2[0:1, 0:1], TO2[1:3, 0:1], TO2[1:3, 1:3]) + + # testing miscellaneous queries + T = Matrix([[S.Half, Rational(1, 4), Rational(1, 4)], + [Rational(1, 3), 0, Rational(2, 3)], + [S.Half, S.Half, 0]]) + X = DiscreteMarkovChain('X', [0, 1, 2], T) + assert P(Eq(X[1], 2) & Eq(X[2], 1) & Eq(X[3], 0), + Eq(P(Eq(X[1], 0)), Rational(1, 4)) & Eq(P(Eq(X[1], 1)), Rational(1, 4))) == Rational(1, 12) + assert P(Eq(X[2], 1) | Eq(X[2], 2), Eq(X[1], 1)) == Rational(2, 3) + assert P(Eq(X[2], 1) & Eq(X[2], 2), Eq(X[1], 1)) is S.Zero + assert P(Ne(X[2], 2), Eq(X[1], 1)) == Rational(1, 3) + assert E(X[1]**2, Eq(X[0], 1)) == Rational(8, 3) + assert variance(X[1], Eq(X[0], 1)) == Rational(8, 9) + raises(ValueError, lambda: E(X[1], Eq(X[2], 1))) + raises(ValueError, lambda: DiscreteMarkovChain('X', [0, 1], T)) + + # testing miscellaneous queries with different state space + X = DiscreteMarkovChain('X', ['A', 'B', 'C'], T) + assert P(Eq(X[1], 2) & Eq(X[2], 1) & Eq(X[3], 0), + Eq(P(Eq(X[1], 0)), Rational(1, 4)) & Eq(P(Eq(X[1], 1)), Rational(1, 4))) == Rational(1, 12) + assert P(Eq(X[2], 1) | Eq(X[2], 2), Eq(X[1], 1)) == Rational(2, 3) + assert P(Eq(X[2], 1) & Eq(X[2], 2), Eq(X[1], 1)) is S.Zero + assert P(Ne(X[2], 2), Eq(X[1], 1)) == Rational(1, 3) + a = X.state_space.args[0] + c = X.state_space.args[2] + assert (E(X[1] ** 2, Eq(X[0], 1)) - (a**2/3 + 2*c**2/3)).simplify() == 0 + assert (variance(X[1], Eq(X[0], 1)) - (2*(-a/3 + c/3)**2/3 + (2*a/3 - 2*c/3)**2/3)).simplify() == 0 + raises(ValueError, lambda: E(X[1], Eq(X[2], 1))) + + #testing queries with multiple RandomIndexedSymbols + T = Matrix([[Rational(5, 10), Rational(3, 10), Rational(2, 10)], [Rational(2, 10), Rational(7, 10), Rational(1, 10)], [Rational(3, 10), Rational(3, 10), Rational(4, 10)]]) + Y = DiscreteMarkovChain("Y", [0, 1, 2], T) + assert P(Eq(Y[7], Y[5]), Eq(Y[2], 0)).round(5) == Float(0.44428, 5) + assert P(Gt(Y[3], Y[1]), Eq(Y[0], 0)).round(2) == Float(0.36, 2) + assert P(Le(Y[5], Y[10]), Eq(Y[4], 2)).round(6) == Float(0.583120, 6) + assert Float(P(Eq(Y[10], Y[5]), Eq(Y[4], 1)), 14) == Float(1 - P(Ne(Y[10], Y[5]), Eq(Y[4], 1)), 14) + assert Float(P(Gt(Y[8], Y[9]), Eq(Y[3], 2)), 14) == Float(1 - P(Le(Y[8], Y[9]), Eq(Y[3], 2)), 14) + assert Float(P(Lt(Y[1], Y[4]), Eq(Y[0], 0)), 14) == Float(1 - P(Ge(Y[1], Y[4]), Eq(Y[0], 0)), 14) + assert P(Eq(Y[5], Y[10]), Eq(Y[2], 1)) == P(Eq(Y[10], Y[5]), Eq(Y[2], 1)) + assert P(Gt(Y[1], Y[2]), Eq(Y[0], 1)) == P(Lt(Y[2], Y[1]), Eq(Y[0], 1)) + assert P(Ge(Y[7], Y[6]), Eq(Y[4], 1)) == P(Le(Y[6], Y[7]), Eq(Y[4], 1)) + + #test symbolic queries + a, b, c, d = symbols('a b c d') + T = Matrix([[Rational(1, 10), Rational(4, 10), Rational(5, 10)], [Rational(3, 10), Rational(4, 10), Rational(3, 10)], [Rational(7, 10), Rational(2, 10), Rational(1, 10)]]) + Y = DiscreteMarkovChain("Y", [0, 1, 2], T) + query = P(Eq(Y[a], b), Eq(Y[c], d)) + assert query.subs({a:10, b:2, c:5, d:1}).evalf().round(4) == P(Eq(Y[10], 2), Eq(Y[5], 1)).round(4) + assert query.subs({a:15, b:0, c:10, d:1}).evalf().round(4) == P(Eq(Y[15], 0), Eq(Y[10], 1)).round(4) + query_gt = P(Gt(Y[a], b), Eq(Y[c], d)) + query_le = P(Le(Y[a], b), Eq(Y[c], d)) + assert query_gt.subs({a:5, b:2, c:1, d:0}).evalf() + query_le.subs({a:5, b:2, c:1, d:0}).evalf() == 1.0 + query_ge = P(Ge(Y[a], b), Eq(Y[c], d)) + query_lt = P(Lt(Y[a], b), Eq(Y[c], d)) + assert query_ge.subs({a:4, b:1, c:0, d:2}).evalf() + query_lt.subs({a:4, b:1, c:0, d:2}).evalf() == 1.0 + + #test issue 20078 + assert (2*Y[1] + 3*Y[1]).simplify() == 5*Y[1] + assert (2*Y[1] - 3*Y[1]).simplify() == -Y[1] + assert (2*(0.25*Y[1])).simplify() == 0.5*Y[1] + assert ((2*Y[1]) * (0.25*Y[1])).simplify() == 0.5*Y[1]**2 + assert (Y[1]**2 + Y[1]**3).simplify() == (Y[1] + 1)*Y[1]**2 + +def test_sample_stochastic_process(): + if not import_module('scipy'): + skip('SciPy Not installed. Skip sampling tests') + import random + random.seed(0) + numpy = import_module('numpy') + if numpy: + numpy.random.seed(0) # scipy uses numpy to sample so to set its seed + T = Matrix([[0.5, 0.2, 0.3],[0.2, 0.5, 0.3],[0.2, 0.3, 0.5]]) + Y = DiscreteMarkovChain("Y", [0, 1, 2], T) + for samps in range(10): + assert next(sample_stochastic_process(Y)) in Y.state_space + Z = DiscreteMarkovChain("Z", ['1', 1, 0], T) + for samps in range(10): + assert next(sample_stochastic_process(Z)) in Z.state_space + + T = Matrix([[S.Half, Rational(1, 4), Rational(1, 4)], + [Rational(1, 3), 0, Rational(2, 3)], + [S.Half, S.Half, 0]]) + X = DiscreteMarkovChain('X', [0, 1, 2], T) + for samps in range(10): + assert next(sample_stochastic_process(X)) in X.state_space + W = DiscreteMarkovChain('W', [1, pi, oo], T) + for samps in range(10): + assert next(sample_stochastic_process(W)) in W.state_space + + +def test_ContinuousMarkovChain(): + T1 = Matrix([[S(-2), S(2), S.Zero], + [S.Zero, S.NegativeOne, S.One], + [Rational(3, 2), Rational(3, 2), S(-3)]]) + C1 = ContinuousMarkovChain('C', [0, 1, 2], T1) + assert C1.limiting_distribution() == ImmutableMatrix([[Rational(3, 19), Rational(12, 19), Rational(4, 19)]]) + + T2 = Matrix([[-S.One, S.One, S.Zero], [S.One, -S.One, S.Zero], [S.Zero, S.One, -S.One]]) + C2 = ContinuousMarkovChain('C', [0, 1, 2], T2) + A, t = C2.generator_matrix, symbols('t', positive=True) + assert C2.transition_probabilities(A)(t) == Matrix([[S.Half + exp(-2*t)/2, S.Half - exp(-2*t)/2, 0], + [S.Half - exp(-2*t)/2, S.Half + exp(-2*t)/2, 0], + [S.Half - exp(-t) + exp(-2*t)/2, S.Half - exp(-2*t)/2, exp(-t)]]) + with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed + assert P(Eq(C2(1), 1), Eq(C2(0), 1), evaluate=False) == Probability(Eq(C2(1), 1), Eq(C2(0), 1)) + assert P(Eq(C2(1), 1), Eq(C2(0), 1)) == exp(-2)/2 + S.Half + assert P(Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 1), + Eq(P(Eq(C2(1), 0)), S.Half)) == (Rational(1, 4) - exp(-2)/4)*(exp(-2)/2 + S.Half) + assert P(Not(Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2)) | + (Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2)), + Eq(P(Eq(C2(1), 0)), Rational(1, 4)) & Eq(P(Eq(C2(1), 1)), Rational(1, 4))) is S.One + assert E(C2(Rational(3, 2)), Eq(C2(0), 2)) == -exp(-3)/2 + 2*exp(Rational(-3, 2)) + S.Half + assert variance(C2(Rational(3, 2)), Eq(C2(0), 1)) == ((S.Half - exp(-3)/2)**2*(exp(-3)/2 + S.Half) + + (Rational(-1, 2) - exp(-3)/2)**2*(S.Half - exp(-3)/2)) + raises(KeyError, lambda: P(Eq(C2(1), 0), Eq(P(Eq(C2(1), 1)), S.Half))) + assert P(Eq(C2(1), 0), Eq(P(Eq(C2(5), 1)), S.Half)) == Probability(Eq(C2(1), 0)) + TS1 = MatrixSymbol('G', 3, 3) + CS1 = ContinuousMarkovChain('C', [0, 1, 2], TS1) + A = CS1.generator_matrix + assert CS1.transition_probabilities(A)(t) == exp(t*A) + + C3 = ContinuousMarkovChain('C', [Symbol('0'), Symbol('1'), Symbol('2')], T2) + assert P(Eq(C3(1), 1), Eq(C3(0), 1)) == exp(-2)/2 + S.Half + assert P(Eq(C3(1), Symbol('1')), Eq(C3(0), Symbol('1'))) == exp(-2)/2 + S.Half + + #test probability queries + G = Matrix([[-S(1), Rational(1, 10), Rational(9, 10)], [Rational(2, 5), -S(1), Rational(3, 5)], [Rational(1, 2), Rational(1, 2), -S(1)]]) + C = ContinuousMarkovChain('C', state_space=[0, 1, 2], gen_mat=G) + assert P(Eq(C(7.385), C(3.19)), Eq(C(0.862), 0)).round(5) == Float(0.35469, 5) + assert P(Gt(C(98.715), C(19.807)), Eq(C(11.314), 2)).round(5) == Float(0.32452, 5) + assert P(Le(C(5.9), C(10.112)), Eq(C(4), 1)).round(6) == Float(0.675214, 6) + assert Float(P(Eq(C(7.32), C(2.91)), Eq(C(2.63), 1)), 14) == Float(1 - P(Ne(C(7.32), C(2.91)), Eq(C(2.63), 1)), 14) + assert Float(P(Gt(C(3.36), C(1.101)), Eq(C(0.8), 2)), 14) == Float(1 - P(Le(C(3.36), C(1.101)), Eq(C(0.8), 2)), 14) + assert Float(P(Lt(C(4.9), C(2.79)), Eq(C(1.61), 0)), 14) == Float(1 - P(Ge(C(4.9), C(2.79)), Eq(C(1.61), 0)), 14) + assert P(Eq(C(5.243), C(10.912)), Eq(C(2.174), 1)) == P(Eq(C(10.912), C(5.243)), Eq(C(2.174), 1)) + assert P(Gt(C(2.344), C(9.9)), Eq(C(1.102), 1)) == P(Lt(C(9.9), C(2.344)), Eq(C(1.102), 1)) + assert P(Ge(C(7.87), C(1.008)), Eq(C(0.153), 1)) == P(Le(C(1.008), C(7.87)), Eq(C(0.153), 1)) + + #test symbolic queries + a, b, c, d = symbols('a b c d') + query = P(Eq(C(a), b), Eq(C(c), d)) + assert query.subs({a:3.65, b:2, c:1.78, d:1}).evalf().round(10) == P(Eq(C(3.65), 2), Eq(C(1.78), 1)).round(10) + query_gt = P(Gt(C(a), b), Eq(C(c), d)) + query_le = P(Le(C(a), b), Eq(C(c), d)) + assert query_gt.subs({a:13.2, b:0, c:3.29, d:2}).evalf() + query_le.subs({a:13.2, b:0, c:3.29, d:2}).evalf() == 1.0 + query_ge = P(Ge(C(a), b), Eq(C(c), d)) + query_lt = P(Lt(C(a), b), Eq(C(c), d)) + assert query_ge.subs({a:7.43, b:1, c:1.45, d:0}).evalf() + query_lt.subs({a:7.43, b:1, c:1.45, d:0}).evalf() == 1.0 + + #test issue 20078 + assert (2*C(1) + 3*C(1)).simplify() == 5*C(1) + assert (2*C(1) - 3*C(1)).simplify() == -C(1) + assert (2*(0.25*C(1))).simplify() == 0.5*C(1) + assert (2*C(1) * 0.25*C(1)).simplify() == 0.5*C(1)**2 + assert (C(1)**2 + C(1)**3).simplify() == (C(1) + 1)*C(1)**2 + +def test_BernoulliProcess(): + + B = BernoulliProcess("B", p=0.6, success=1, failure=0) + assert B.state_space == FiniteSet(0, 1) + assert B.index_set == S.Naturals0 + assert B.success == 1 + assert B.failure == 0 + + X = BernoulliProcess("X", p=Rational(1,3), success='H', failure='T') + assert X.state_space == FiniteSet('H', 'T') + H, T = symbols("H,T") + assert E(X[1]+X[2]*X[3]) == H**2/9 + 4*H*T/9 + H/3 + 4*T**2/9 + 2*T/3 + + t, x = symbols('t, x', positive=True, integer=True) + assert isinstance(B[t], RandomIndexedSymbol) + + raises(ValueError, lambda: BernoulliProcess("X", p=1.1, success=1, failure=0)) + raises(NotImplementedError, lambda: B(t)) + + raises(IndexError, lambda: B[-3]) + assert B.joint_distribution(B[3], B[9]) == JointDistributionHandmade(Lambda((B[3], B[9]), + Piecewise((0.6, Eq(B[3], 1)), (0.4, Eq(B[3], 0)), (0, True)) + *Piecewise((0.6, Eq(B[9], 1)), (0.4, Eq(B[9], 0)), (0, True)))) + + assert B.joint_distribution(2, B[4]) == JointDistributionHandmade(Lambda((B[2], B[4]), + Piecewise((0.6, Eq(B[2], 1)), (0.4, Eq(B[2], 0)), (0, True)) + *Piecewise((0.6, Eq(B[4], 1)), (0.4, Eq(B[4], 0)), (0, True)))) + + # Test for the sum distribution of Bernoulli Process RVs + Y = B[1] + B[2] + B[3] + assert P(Eq(Y, 0)).round(2) == Float(0.06, 1) + assert P(Eq(Y, 2)).round(2) == Float(0.43, 2) + assert P(Eq(Y, 4)).round(2) == 0 + assert P(Gt(Y, 1)).round(2) == Float(0.65, 2) + # Test for independency of each Random Indexed variable + assert P(Eq(B[1], 0) & Eq(B[2], 1) & Eq(B[3], 0) & Eq(B[4], 1)).round(2) == Float(0.06, 1) + + assert E(2 * B[1] + B[2]).round(2) == Float(1.80, 3) + assert E(2 * B[1] + B[2] + 5).round(2) == Float(6.80, 3) + assert E(B[2] * B[4] + B[10]).round(2) == Float(0.96, 2) + assert E(B[2] > 0, Eq(B[1],1) & Eq(B[2],1)).round(2) == Float(0.60,2) + assert E(B[1]) == 0.6 + assert P(B[1] > 0).round(2) == Float(0.60, 2) + assert P(B[1] < 1).round(2) == Float(0.40, 2) + assert P(B[1] > 0, B[2] <= 1).round(2) == Float(0.60, 2) + assert P(B[12] * B[5] > 0).round(2) == Float(0.36, 2) + assert P(B[12] * B[5] > 0, B[4] < 1).round(2) == Float(0.36, 2) + assert P(Eq(B[2], 1), B[2] > 0) == 1.0 + assert P(Eq(B[5], 3)) == 0 + assert P(Eq(B[1], 1), B[1] < 0) == 0 + assert P(B[2] > 0, Eq(B[2], 1)) == 1 + assert P(B[2] < 0, Eq(B[2], 1)) == 0 + assert P(B[2] > 0, B[2]==7) == 0 + assert P(B[5] > 0, B[5]) == BernoulliDistribution(0.6, 0, 1) + raises(ValueError, lambda: P(3)) + raises(ValueError, lambda: P(B[3] > 0, 3)) + + # test issue 19456 + expr = Sum(B[t], (t, 0, 4)) + expr2 = Sum(B[t], (t, 1, 3)) + expr3 = Sum(B[t]**2, (t, 1, 3)) + assert expr.doit() == B[0] + B[1] + B[2] + B[3] + B[4] + assert expr2.doit() == Y + assert expr3.doit() == B[1]**2 + B[2]**2 + B[3]**2 + assert B[2*t].free_symbols == {B[2*t], t} + assert B[4].free_symbols == {B[4]} + assert B[x*t].free_symbols == {B[x*t], x, t} + + #test issue 20078 + assert (2*B[t] + 3*B[t]).simplify() == 5*B[t] + assert (2*B[t] - 3*B[t]).simplify() == -B[t] + assert (2*(0.25*B[t])).simplify() == 0.5*B[t] + assert (2*B[t] * 0.25*B[t]).simplify() == 0.5*B[t]**2 + assert (B[t]**2 + B[t]**3).simplify() == (B[t] + 1)*B[t]**2 + +def test_PoissonProcess(): + X = PoissonProcess("X", 3) + assert X.state_space == S.Naturals0 + assert X.index_set == Interval(0, oo) + assert X.lamda == 3 + + t, d, x, y = symbols('t d x y', positive=True) + assert isinstance(X(t), RandomIndexedSymbol) + assert X.distribution(t) == PoissonDistribution(3*t) + with warns_deprecated_sympy(): + X.distribution(X(t)) + raises(ValueError, lambda: PoissonProcess("X", -1)) + raises(NotImplementedError, lambda: X[t]) + raises(IndexError, lambda: X(-5)) + + assert X.joint_distribution(X(2), X(3)) == JointDistributionHandmade(Lambda((X(2), X(3)), + 6**X(2)*9**X(3)*exp(-15)/(factorial(X(2))*factorial(X(3))))) + + assert X.joint_distribution(4, 6) == JointDistributionHandmade(Lambda((X(4), X(6)), + 12**X(4)*18**X(6)*exp(-30)/(factorial(X(4))*factorial(X(6))))) + + assert P(X(t) < 1) == exp(-3*t) + assert P(Eq(X(t), 0), Contains(t, Interval.Lopen(3, 5))) == exp(-6) # exp(-2*lamda) + res = P(Eq(X(t), 1), Contains(t, Interval.Lopen(3, 4))) + assert res == 3*exp(-3) + + # Equivalent to P(Eq(X(t), 1))**4 because of non-overlapping intervals + assert P(Eq(X(t), 1) & Eq(X(d), 1) & Eq(X(x), 1) & Eq(X(y), 1), Contains(t, Interval.Lopen(0, 1)) + & Contains(d, Interval.Lopen(1, 2)) & Contains(x, Interval.Lopen(2, 3)) + & Contains(y, Interval.Lopen(3, 4))) == res**4 + + # Return Probability because of overlapping intervals + assert P(Eq(X(t), 2) & Eq(X(d), 3), Contains(t, Interval.Lopen(0, 2)) + & Contains(d, Interval.Ropen(2, 4))) == \ + Probability(Eq(X(d), 3) & Eq(X(t), 2), Contains(t, Interval.Lopen(0, 2)) + & Contains(d, Interval.Ropen(2, 4))) + + raises(ValueError, lambda: P(Eq(X(t), 2) & Eq(X(d), 3), + Contains(t, Interval.Lopen(0, 4)) & Contains(d, Interval.Lopen(3, oo)))) # no bound on d + assert P(Eq(X(3), 2)) == 81*exp(-9)/2 + assert P(Eq(X(t), 2), Contains(t, Interval.Lopen(0, 5))) == 225*exp(-15)/2 + + # Check that probability works correctly by adding it to 1 + res1 = P(X(t) <= 3, Contains(t, Interval.Lopen(0, 5))) + res2 = P(X(t) > 3, Contains(t, Interval.Lopen(0, 5))) + assert res1 == 691*exp(-15) + assert (res1 + res2).simplify() == 1 + + # Check Not and Or + assert P(Not(Eq(X(t), 2) & (X(d) > 3)), Contains(t, Interval.Ropen(2, 4)) & \ + Contains(d, Interval.Lopen(7, 8))).simplify() == -18*exp(-6) + 234*exp(-9) + 1 + assert P(Eq(X(t), 2) | Ne(X(t), 4), Contains(t, Interval.Ropen(2, 4))) == 1 - 36*exp(-6) + raises(ValueError, lambda: P(X(t) > 2, X(t) + X(d))) + assert E(X(t)) == 3*t # property of the distribution at a given timestamp + assert E(X(t)**2 + X(d)*2 + X(y)**3, Contains(t, Interval.Lopen(0, 1)) + & Contains(d, Interval.Lopen(1, 2)) & Contains(y, Interval.Ropen(3, 4))) == 75 + assert E(X(t)**2, Contains(t, Interval.Lopen(0, 1))) == 12 + assert E(x*(X(t) + X(d))*(X(t)**2+X(d)**2), Contains(t, Interval.Lopen(0, 1)) + & Contains(d, Interval.Ropen(1, 2))) == \ + Expectation(x*(X(d) + X(t))*(X(d)**2 + X(t)**2), Contains(t, Interval.Lopen(0, 1)) + & Contains(d, Interval.Ropen(1, 2))) + + # Value Error because of infinite time bound + raises(ValueError, lambda: E(X(t)**3, Contains(t, Interval.Lopen(1, oo)))) + + # Equivalent to E(X(t)**2) - E(X(d)**2) == E(X(1)**2) - E(X(1)**2) == 0 + assert E((X(t) + X(d))*(X(t) - X(d)), Contains(t, Interval.Lopen(0, 1)) + & Contains(d, Interval.Lopen(1, 2))) == 0 + assert E(X(2) + x*E(X(5))) == 15*x + 6 + assert E(x*X(1) + y) == 3*x + y + assert P(Eq(X(1), 2) & Eq(X(t), 3), Contains(t, Interval.Lopen(1, 2))) == 81*exp(-6)/4 + Y = PoissonProcess("Y", 6) + Z = X + Y + assert Z.lamda == X.lamda + Y.lamda == 9 + raises(ValueError, lambda: X + 5) # should be added be only PoissonProcess instance + N, M = Z.split(4, 5) + assert N.lamda == 4 + assert M.lamda == 5 + raises(ValueError, lambda: Z.split(3, 2)) # 2+3 != 9 + + raises(ValueError, lambda :P(Eq(X(t), 0), Contains(t, Interval.Lopen(1, 3)) & Eq(X(1), 0))) + # check if it handles queries with two random variables in one args + res1 = P(Eq(N(3), N(5))) + assert res1 == P(Eq(N(t), 0), Contains(t, Interval(3, 5))) + res2 = P(N(3) > N(1)) + assert res2 == P((N(t) > 0), Contains(t, Interval(1, 3))) + assert P(N(3) < N(1)) == 0 # condition is not possible + res3 = P(N(3) <= N(1)) # holds only for Eq(N(3), N(1)) + assert res3 == P(Eq(N(t), 0), Contains(t, Interval(1, 3))) + + # tests from https://www.probabilitycourse.com/chapter11/11_1_2_basic_concepts_of_the_poisson_process.php + X = PoissonProcess('X', 10) # 11.1 + assert P(Eq(X(S(1)/3), 3) & Eq(X(1), 10)) == exp(-10)*Rational(8000000000, 11160261) + assert P(Eq(X(1), 1), Eq(X(S(1)/3), 3)) == 0 + assert P(Eq(X(1), 10), Eq(X(S(1)/3), 3)) == P(Eq(X(S(2)/3), 7)) + + X = PoissonProcess('X', 2) # 11.2 + assert P(X(S(1)/2) < 1) == exp(-1) + assert P(X(3) < 1, Eq(X(1), 0)) == exp(-4) + assert P(Eq(X(4), 3), Eq(X(2), 3)) == exp(-4) + + X = PoissonProcess('X', 3) + assert P(Eq(X(2), 5) & Eq(X(1), 2)) == Rational(81, 4)*exp(-6) + + # check few properties + assert P(X(2) <= 3, X(1)>=1) == 3*P(Eq(X(1), 0)) + 2*P(Eq(X(1), 1)) + P(Eq(X(1), 2)) + assert P(X(2) <= 3, X(1) > 1) == 2*P(Eq(X(1), 0)) + 1*P(Eq(X(1), 1)) + assert P(Eq(X(2), 5) & Eq(X(1), 2)) == P(Eq(X(1), 3))*P(Eq(X(1), 2)) + assert P(Eq(X(3), 4), Eq(X(1), 3)) == P(Eq(X(2), 1)) + + #test issue 20078 + assert (2*X(t) + 3*X(t)).simplify() == 5*X(t) + assert (2*X(t) - 3*X(t)).simplify() == -X(t) + assert (2*(0.25*X(t))).simplify() == 0.5*X(t) + assert (2*X(t) * 0.25*X(t)).simplify() == 0.5*X(t)**2 + assert (X(t)**2 + X(t)**3).simplify() == (X(t) + 1)*X(t)**2 + +def test_WienerProcess(): + X = WienerProcess("X") + assert X.state_space == S.Reals + assert X.index_set == Interval(0, oo) + + t, d, x, y = symbols('t d x y', positive=True) + assert isinstance(X(t), RandomIndexedSymbol) + assert X.distribution(t) == NormalDistribution(0, sqrt(t)) + with warns_deprecated_sympy(): + X.distribution(X(t)) + raises(ValueError, lambda: PoissonProcess("X", -1)) + raises(NotImplementedError, lambda: X[t]) + raises(IndexError, lambda: X(-2)) + + assert X.joint_distribution(X(2), X(3)) == JointDistributionHandmade( + Lambda((X(2), X(3)), sqrt(6)*exp(-X(2)**2/4)*exp(-X(3)**2/6)/(12*pi))) + assert X.joint_distribution(4, 6) == JointDistributionHandmade( + Lambda((X(4), X(6)), sqrt(6)*exp(-X(4)**2/8)*exp(-X(6)**2/12)/(24*pi))) + + assert P(X(t) < 3).simplify() == erf(3*sqrt(2)/(2*sqrt(t)))/2 + S(1)/2 + assert P(X(t) > 2, Contains(t, Interval.Lopen(3, 7))).simplify() == S(1)/2 -\ + erf(sqrt(2)/2)/2 + + # Equivalent to P(X(1)>1)**4 + assert P((X(t) > 4) & (X(d) > 3) & (X(x) > 2) & (X(y) > 1), + Contains(t, Interval.Lopen(0, 1)) & Contains(d, Interval.Lopen(1, 2)) + & Contains(x, Interval.Lopen(2, 3)) & Contains(y, Interval.Lopen(3, 4))).simplify() ==\ + (1 - erf(sqrt(2)/2))*(1 - erf(sqrt(2)))*(1 - erf(3*sqrt(2)/2))*(1 - erf(2*sqrt(2)))/16 + + # Contains an overlapping interval so, return Probability + assert P((X(t)< 2) & (X(d)> 3), Contains(t, Interval.Lopen(0, 2)) + & Contains(d, Interval.Ropen(2, 4))) == Probability((X(d) > 3) & (X(t) < 2), + Contains(d, Interval.Ropen(2, 4)) & Contains(t, Interval.Lopen(0, 2))) + + assert str(P(Not((X(t) < 5) & (X(d) > 3)), Contains(t, Interval.Ropen(2, 4)) & + Contains(d, Interval.Lopen(7, 8))).simplify()) == \ + '-(1 - erf(3*sqrt(2)/2))*(2 - erfc(5/2))/4 + 1' + # Distribution has mean 0 at each timestamp + assert E(X(t)) == 0 + assert E(x*(X(t) + X(d))*(X(t)**2+X(d)**2), Contains(t, Interval.Lopen(0, 1)) + & Contains(d, Interval.Ropen(1, 2))) == Expectation(x*(X(d) + X(t))*(X(d)**2 + X(t)**2), + Contains(d, Interval.Ropen(1, 2)) & Contains(t, Interval.Lopen(0, 1))) + assert E(X(t) + x*E(X(3))) == 0 + + #test issue 20078 + assert (2*X(t) + 3*X(t)).simplify() == 5*X(t) + assert (2*X(t) - 3*X(t)).simplify() == -X(t) + assert (2*(0.25*X(t))).simplify() == 0.5*X(t) + assert (2*X(t) * 0.25*X(t)).simplify() == 0.5*X(t)**2 + assert (X(t)**2 + X(t)**3).simplify() == (X(t) + 1)*X(t)**2 + + +def test_GammaProcess_symbolic(): + t, d, x, y, g, l = symbols('t d x y g l', positive=True) + X = GammaProcess("X", l, g) + + raises(NotImplementedError, lambda: X[t]) + raises(IndexError, lambda: X(-1)) + assert isinstance(X(t), RandomIndexedSymbol) + assert X.state_space == Interval(0, oo) + assert X.distribution(t) == GammaDistribution(g*t, 1/l) + with warns_deprecated_sympy(): + X.distribution(X(t)) + assert X.joint_distribution(5, X(3)) == JointDistributionHandmade(Lambda( + (X(5), X(3)), l**(8*g)*exp(-l*X(3))*exp(-l*X(5))*X(3)**(3*g - 1)*X(5)**(5*g + - 1)/(gamma(3*g)*gamma(5*g)))) + # property of the gamma process at any given timestamp + assert E(X(t)) == g*t/l + assert variance(X(t)).simplify() == g*t/l**2 + + # Equivalent to E(2*X(1)) + E(X(1)**2) + E(X(1)**3), where E(X(1)) == g/l + assert E(X(t)**2 + X(d)*2 + X(y)**3, Contains(t, Interval.Lopen(0, 1)) + & Contains(d, Interval.Lopen(1, 2)) & Contains(y, Interval.Ropen(3, 4))) == \ + 2*g/l + (g**2 + g)/l**2 + (g**3 + 3*g**2 + 2*g)/l**3 + + assert P(X(t) > 3, Contains(t, Interval.Lopen(3, 4))).simplify() == \ + 1 - lowergamma(g, 3*l)/gamma(g) # equivalent to P(X(1)>3) + + + #test issue 20078 + assert (2*X(t) + 3*X(t)).simplify() == 5*X(t) + assert (2*X(t) - 3*X(t)).simplify() == -X(t) + assert (2*(0.25*X(t))).simplify() == 0.5*X(t) + assert (2*X(t) * 0.25*X(t)).simplify() == 0.5*X(t)**2 + assert (X(t)**2 + X(t)**3).simplify() == (X(t) + 1)*X(t)**2 +def test_GammaProcess_numeric(): + t, d, x, y = symbols('t d x y', positive=True) + X = GammaProcess("X", 1, 2) + assert X.state_space == Interval(0, oo) + assert X.index_set == Interval(0, oo) + assert X.lamda == 1 + assert X.gamma == 2 + + raises(ValueError, lambda: GammaProcess("X", -1, 2)) + raises(ValueError, lambda: GammaProcess("X", 0, -2)) + raises(ValueError, lambda: GammaProcess("X", -1, -2)) + + # all are independent because of non-overlapping intervals + assert P((X(t) > 4) & (X(d) > 3) & (X(x) > 2) & (X(y) > 1), Contains(t, + Interval.Lopen(0, 1)) & Contains(d, Interval.Lopen(1, 2)) & Contains(x, + Interval.Lopen(2, 3)) & Contains(y, Interval.Lopen(3, 4))).simplify() == \ + 120*exp(-10) + + # Check working with Not and Or + assert P(Not((X(t) < 5) & (X(d) > 3)), Contains(t, Interval.Ropen(2, 4)) & + Contains(d, Interval.Lopen(7, 8))).simplify() == -4*exp(-3) + 472*exp(-8)/3 + 1 + assert P((X(t) > 2) | (X(t) < 4), Contains(t, Interval.Ropen(1, 4))).simplify() == \ + -643*exp(-4)/15 + 109*exp(-2)/15 + 1 + + assert E(X(t)) == 2*t # E(X(t)) == gamma*t/l + assert E(X(2) + x*E(X(5))) == 10*x + 4 diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_symbolic_multivariate.py b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_symbolic_multivariate.py new file mode 100644 index 0000000000000000000000000000000000000000..79979e20a6f10d2a2ddfe85ce4c8df145e98c3fd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_symbolic_multivariate.py @@ -0,0 +1,172 @@ +from sympy.stats import Expectation, Normal, Variance, Covariance +from sympy.testing.pytest import raises +from sympy.core.symbol import symbols +from sympy.matrices.exceptions import ShapeError +from sympy.matrices.dense import Matrix +from sympy.matrices.expressions.matexpr import MatrixSymbol +from sympy.matrices.expressions.special import ZeroMatrix +from sympy.stats.rv import RandomMatrixSymbol +from sympy.stats.symbolic_multivariate_probability import (ExpectationMatrix, + VarianceMatrix, CrossCovarianceMatrix) + +j, k = symbols("j,k") + +A = MatrixSymbol("A", k, k) +B = MatrixSymbol("B", k, k) +C = MatrixSymbol("C", k, k) +D = MatrixSymbol("D", k, k) + +a = MatrixSymbol("a", k, 1) +b = MatrixSymbol("b", k, 1) + +A2 = MatrixSymbol("A2", 2, 2) +B2 = MatrixSymbol("B2", 2, 2) + +X = RandomMatrixSymbol("X", k, 1) +Y = RandomMatrixSymbol("Y", k, 1) +Z = RandomMatrixSymbol("Z", k, 1) +W = RandomMatrixSymbol("W", k, 1) + +R = RandomMatrixSymbol("R", k, k) + +X2 = RandomMatrixSymbol("X2", 2, 1) + +normal = Normal("normal", 0, 1) + +m1 = Matrix([ + [1, j*Normal("normal2", 2, 1)], + [normal, 0] +]) + +def test_multivariate_expectation(): + expr = Expectation(a) + assert expr == Expectation(a) == ExpectationMatrix(a) + assert expr.expand() == a + + expr = Expectation(X) + assert expr == Expectation(X) == ExpectationMatrix(X) + assert expr.shape == (k, 1) + assert expr.rows == k + assert expr.cols == 1 + assert isinstance(expr, ExpectationMatrix) + + expr = Expectation(A*X + b) + assert expr == ExpectationMatrix(A*X + b) + assert expr.expand() == A*ExpectationMatrix(X) + b + assert isinstance(expr, ExpectationMatrix) + assert expr.shape == (k, 1) + + expr = Expectation(m1*X2) + assert expr.expand() == expr + + expr = Expectation(A2*m1*B2*X2) + assert expr.args[0].args == (A2, m1, B2, X2) + assert expr.expand() == A2*ExpectationMatrix(m1*B2*X2) + + expr = Expectation((X + Y)*(X - Y).T) + assert expr.expand() == ExpectationMatrix(X*X.T) - ExpectationMatrix(X*Y.T) +\ + ExpectationMatrix(Y*X.T) - ExpectationMatrix(Y*Y.T) + + expr = Expectation(A*X + B*Y) + assert expr.expand() == A*ExpectationMatrix(X) + B*ExpectationMatrix(Y) + + assert Expectation(m1).doit() == Matrix([[1, 2*j], [0, 0]]) + + x1 = Matrix([ + [Normal('N11', 11, 1), Normal('N12', 12, 1)], + [Normal('N21', 21, 1), Normal('N22', 22, 1)] + ]) + x2 = Matrix([ + [Normal('M11', 1, 1), Normal('M12', 2, 1)], + [Normal('M21', 3, 1), Normal('M22', 4, 1)] + ]) + + assert Expectation(Expectation(x1 + x2)).doit(deep=False) == ExpectationMatrix(x1 + x2) + assert Expectation(Expectation(x1 + x2)).doit() == Matrix([[12, 14], [24, 26]]) + + +def test_multivariate_variance(): + raises(ShapeError, lambda: Variance(A)) + + expr = Variance(a) + assert expr == Variance(a) == VarianceMatrix(a) + assert expr.expand() == ZeroMatrix(k, k) + expr = Variance(a.T) + assert expr == Variance(a.T) == VarianceMatrix(a.T) + assert expr.expand() == ZeroMatrix(k, k) + + expr = Variance(X) + assert expr == Variance(X) == VarianceMatrix(X) + assert expr.shape == (k, k) + assert expr.rows == k + assert expr.cols == k + assert isinstance(expr, VarianceMatrix) + + expr = Variance(A*X) + assert expr == VarianceMatrix(A*X) + assert expr.expand() == A*VarianceMatrix(X)*A.T + assert isinstance(expr, VarianceMatrix) + assert expr.shape == (k, k) + + expr = Variance(A*B*X) + assert expr.expand() == A*B*VarianceMatrix(X)*B.T*A.T + + expr = Variance(m1*X2) + assert expr.expand() == expr + + expr = Variance(A2*m1*B2*X2) + assert expr.args[0].args == (A2, m1, B2, X2) + assert expr.expand() == expr + + expr = Variance(A*X + B*Y) + assert expr.expand() == 2*A*CrossCovarianceMatrix(X, Y)*B.T +\ + A*VarianceMatrix(X)*A.T + B*VarianceMatrix(Y)*B.T + +def test_multivariate_crosscovariance(): + raises(ShapeError, lambda: Covariance(X, Y.T)) + raises(ShapeError, lambda: Covariance(X, A)) + + + expr = Covariance(a.T, b.T) + assert expr.shape == (1, 1) + assert expr.expand() == ZeroMatrix(1, 1) + + expr = Covariance(a, b) + assert expr == Covariance(a, b) == CrossCovarianceMatrix(a, b) + assert expr.expand() == ZeroMatrix(k, k) + assert expr.shape == (k, k) + assert expr.rows == k + assert expr.cols == k + assert isinstance(expr, CrossCovarianceMatrix) + + expr = Covariance(A*X + a, b) + assert expr.expand() == ZeroMatrix(k, k) + + expr = Covariance(X, Y) + assert isinstance(expr, CrossCovarianceMatrix) + assert expr.expand() == expr + + expr = Covariance(X, X) + assert isinstance(expr, CrossCovarianceMatrix) + assert expr.expand() == VarianceMatrix(X) + + expr = Covariance(X + Y, Z) + assert isinstance(expr, CrossCovarianceMatrix) + assert expr.expand() == CrossCovarianceMatrix(X, Z) + CrossCovarianceMatrix(Y, Z) + + expr = Covariance(A*X, Y) + assert isinstance(expr, CrossCovarianceMatrix) + assert expr.expand() == A*CrossCovarianceMatrix(X, Y) + + expr = Covariance(X, B*Y) + assert isinstance(expr, CrossCovarianceMatrix) + assert expr.expand() == CrossCovarianceMatrix(X, Y)*B.T + + expr = Covariance(A*X + a, B.T*Y + b) + assert isinstance(expr, CrossCovarianceMatrix) + assert expr.expand() == A*CrossCovarianceMatrix(X, Y)*B + + expr = Covariance(A*X + B*Y + a, C.T*Z + D.T*W + b) + assert isinstance(expr, CrossCovarianceMatrix) + assert expr.expand() == A*CrossCovarianceMatrix(X, W)*D + A*CrossCovarianceMatrix(X, Z)*C \ + + B*CrossCovarianceMatrix(Y, W)*D + B*CrossCovarianceMatrix(Y, Z)*C diff --git a/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_symbolic_probability.py b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_symbolic_probability.py new file mode 100644 index 0000000000000000000000000000000000000000..edac942ac081c0d44cafd31761b77bc577b6a3fd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/stats/tests/test_symbolic_probability.py @@ -0,0 +1,175 @@ +from sympy.concrete.summations import Sum +from sympy.core.mul import Mul +from sympy.core.numbers import (oo, pi) +from sympy.core.relational import Eq +from sympy.core.symbol import (Dummy, symbols) +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import sin +from sympy.integrals.integrals import Integral +from sympy.core.expr import unchanged +from sympy.stats import (Normal, Poisson, variance, Covariance, Variance, + Probability, Expectation, Moment, CentralMoment) +from sympy.stats.rv import probability, expectation + + +def test_literal_probability(): + X = Normal('X', 2, 3) + Y = Normal('Y', 3, 4) + Z = Poisson('Z', 4) + W = Poisson('W', 3) + x = symbols('x', real=True) + y, w, z = symbols('y, w, z') + + assert Probability(X > 0).evaluate_integral() == probability(X > 0) + assert Probability(X > x).evaluate_integral() == probability(X > x) + assert Probability(X > 0).rewrite(Integral).doit() == probability(X > 0) + assert Probability(X > x).rewrite(Integral).doit() == probability(X > x) + + assert Expectation(X).evaluate_integral() == expectation(X) + assert Expectation(X).rewrite(Integral).doit() == expectation(X) + assert Expectation(X**2).evaluate_integral() == expectation(X**2) + assert Expectation(x*X).args == (x*X,) + assert Expectation(x*X).expand() == x*Expectation(X) + assert Expectation(2*X + 3*Y + z*X*Y).expand() == 2*Expectation(X) + 3*Expectation(Y) + z*Expectation(X*Y) + assert Expectation(2*X + 3*Y + z*X*Y).args == (2*X + 3*Y + z*X*Y,) + assert Expectation(sin(X)) == Expectation(sin(X)).expand() + assert Expectation(2*x*sin(X)*Y + y*X**2 + z*X*Y).expand() == 2*x*Expectation(sin(X)*Y) \ + + y*Expectation(X**2) + z*Expectation(X*Y) + assert Expectation(X + Y).expand() == Expectation(X) + Expectation(Y) + assert Expectation((X + Y)*(X - Y)).expand() == Expectation(X**2) - Expectation(Y**2) + assert Expectation((X + Y)*(X - Y)).expand().doit() == -12 + assert Expectation(X + Y, evaluate=True).doit() == 5 + assert Expectation(X + Expectation(Y)).doit() == 5 + assert Expectation(X + Expectation(Y)).doit(deep=False) == 2 + Expectation(Expectation(Y)) + assert Expectation(X + Expectation(Y + Expectation(2*X))).doit(deep=False) == 2 \ + + Expectation(Expectation(Y + Expectation(2*X))) + assert Expectation(X + Expectation(Y + Expectation(2*X))).doit() == 9 + assert Expectation(Expectation(2*X)).doit() == 4 + assert Expectation(Expectation(2*X)).doit(deep=False) == Expectation(2*X) + assert Expectation(4*Expectation(2*X)).doit(deep=False) == 4*Expectation(2*X) + assert Expectation((X + Y)**3).expand() == 3*Expectation(X*Y**2) +\ + 3*Expectation(X**2*Y) + Expectation(X**3) + Expectation(Y**3) + assert Expectation((X - Y)**3).expand() == 3*Expectation(X*Y**2) -\ + 3*Expectation(X**2*Y) + Expectation(X**3) - Expectation(Y**3) + assert Expectation((X - Y)**2).expand() == -2*Expectation(X*Y) +\ + Expectation(X**2) + Expectation(Y**2) + + assert Variance(w).args == (w,) + assert Variance(w).expand() == 0 + assert Variance(X).evaluate_integral() == Variance(X).rewrite(Integral).doit() == variance(X) + assert Variance(X + z).args == (X + z,) + assert Variance(X + z).expand() == Variance(X) + assert Variance(X*Y).args == (Mul(X, Y),) + assert type(Variance(X*Y)) == Variance + assert Variance(z*X).expand() == z**2*Variance(X) + assert Variance(X + Y).expand() == Variance(X) + Variance(Y) + 2*Covariance(X, Y) + assert Variance(X + Y + Z + W).expand() == (Variance(X) + Variance(Y) + Variance(Z) + Variance(W) + + 2 * Covariance(X, Y) + 2 * Covariance(X, Z) + 2 * Covariance(X, W) + + 2 * Covariance(Y, Z) + 2 * Covariance(Y, W) + 2 * Covariance(W, Z)) + assert Variance(X**2).evaluate_integral() == variance(X**2) + assert unchanged(Variance, X**2) + assert Variance(x*X**2).expand() == x**2*Variance(X**2) + assert Variance(sin(X)).args == (sin(X),) + assert Variance(sin(X)).expand() == Variance(sin(X)) + assert Variance(x*sin(X)).expand() == x**2*Variance(sin(X)) + + assert Covariance(w, z).args == (w, z) + assert Covariance(w, z).expand() == 0 + assert Covariance(X, w).expand() == 0 + assert Covariance(w, X).expand() == 0 + assert Covariance(X, Y).args == (X, Y) + assert type(Covariance(X, Y)) == Covariance + assert Covariance(z*X + 3, Y).expand() == z*Covariance(X, Y) + assert Covariance(X, X).args == (X, X) + assert Covariance(X, X).expand() == Variance(X) + assert Covariance(z*X + 3, w*Y + 4).expand() == w*z*Covariance(X,Y) + assert Covariance(X, Y) == Covariance(Y, X) + assert Covariance(X + Y, Z + W).expand() == Covariance(W, X) + Covariance(W, Y) + Covariance(X, Z) + Covariance(Y, Z) + assert Covariance(x*X + y*Y, z*Z + w*W).expand() == (x*w*Covariance(W, X) + w*y*Covariance(W, Y) + + x*z*Covariance(X, Z) + y*z*Covariance(Y, Z)) + assert Covariance(x*X**2 + y*sin(Y), z*Y*Z**2 + w*W).expand() == (w*x*Covariance(W, X**2) + w*y*Covariance(sin(Y), W) + + x*z*Covariance(Y*Z**2, X**2) + y*z*Covariance(Y*Z**2, sin(Y))) + assert Covariance(X, X**2).expand() == Covariance(X, X**2) + assert Covariance(X, sin(X)).expand() == Covariance(sin(X), X) + assert Covariance(X**2, sin(X)*Y).expand() == Covariance(sin(X)*Y, X**2) + assert Covariance(w, X).evaluate_integral() == 0 + + +def test_probability_rewrite(): + X = Normal('X', 2, 3) + Y = Normal('Y', 3, 4) + Z = Poisson('Z', 4) + W = Poisson('W', 3) + x, y, w, z = symbols('x, y, w, z') + + assert Variance(w).rewrite(Expectation) == 0 + assert Variance(X).rewrite(Expectation) == Expectation(X ** 2) - Expectation(X) ** 2 + assert Variance(X, condition=Y).rewrite(Expectation) == Expectation(X ** 2, Y) - Expectation(X, Y) ** 2 + assert Variance(X, Y) != Expectation(X**2) - Expectation(X)**2 + assert Variance(X + z).rewrite(Expectation) == Expectation((X + z) ** 2) - Expectation(X + z) ** 2 + assert Variance(X * Y).rewrite(Expectation) == Expectation(X ** 2 * Y ** 2) - Expectation(X * Y) ** 2 + + assert Covariance(w, X).rewrite(Expectation) == -w*Expectation(X) + Expectation(w*X) + assert Covariance(X, Y).rewrite(Expectation) == Expectation(X*Y) - Expectation(X)*Expectation(Y) + assert Covariance(X, Y, condition=W).rewrite(Expectation) == Expectation(X * Y, W) - Expectation(X, W) * Expectation(Y, W) + + w, x, z = symbols("W, x, z") + px = Probability(Eq(X, x)) + pz = Probability(Eq(Z, z)) + + assert Expectation(X).rewrite(Probability) == Integral(x*px, (x, -oo, oo)) + assert Expectation(Z).rewrite(Probability) == Sum(z*pz, (z, 0, oo)) + assert Variance(X).rewrite(Probability) == Integral(x**2*px, (x, -oo, oo)) - Integral(x*px, (x, -oo, oo))**2 + assert Variance(Z).rewrite(Probability) == Sum(z**2*pz, (z, 0, oo)) - Sum(z*pz, (z, 0, oo))**2 + assert Covariance(w, X).rewrite(Probability) == \ + -w*Integral(x*Probability(Eq(X, x)), (x, -oo, oo)) + Integral(w*x*Probability(Eq(X, x)), (x, -oo, oo)) + + # To test rewrite as sum function + assert Variance(X).rewrite(Sum) == Variance(X).rewrite(Integral) + assert Expectation(X).rewrite(Sum) == Expectation(X).rewrite(Integral) + + assert Covariance(w, X).rewrite(Sum) == 0 + + assert Covariance(w, X).rewrite(Integral) == 0 + + assert Variance(X, condition=Y).rewrite(Probability) == Integral(x**2*Probability(Eq(X, x), Y), (x, -oo, oo)) - \ + Integral(x*Probability(Eq(X, x), Y), (x, -oo, oo))**2 + + +def test_symbolic_Moment(): + mu = symbols('mu', real=True) + sigma = symbols('sigma', positive=True) + x = symbols('x') + X = Normal('X', mu, sigma) + M = Moment(X, 4, 2) + assert M.rewrite(Expectation) == Expectation((X - 2)**4) + assert M.rewrite(Probability) == Integral((x - 2)**4*Probability(Eq(X, x)), + (x, -oo, oo)) + k = Dummy('k') + expri = Integral(sqrt(2)*(k - 2)**4*exp(-(k - \ + mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (k, -oo, oo)) + assert M.rewrite(Integral).dummy_eq(expri) + assert M.doit() == (mu**4 - 8*mu**3 + 6*mu**2*sigma**2 + \ + 24*mu**2 - 24*mu*sigma**2 - 32*mu + 3*sigma**4 + 24*sigma**2 + 16) + M = Moment(2, 5) + assert M.doit() == 2**5 + + +def test_symbolic_CentralMoment(): + mu = symbols('mu', real=True) + sigma = symbols('sigma', positive=True) + x = symbols('x') + X = Normal('X', mu, sigma) + CM = CentralMoment(X, 6) + assert CM.rewrite(Expectation) == Expectation((X - Expectation(X))**6) + assert CM.rewrite(Probability) == Integral((x - Integral(x*Probability(True), + (x, -oo, oo)))**6*Probability(Eq(X, x)), (x, -oo, oo)) + k = Dummy('k') + expri = Integral(sqrt(2)*(k - Integral(sqrt(2)*k*exp(-(k - \ + mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (k, -oo, oo)))**6*exp(-(k - \ + mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (k, -oo, oo)) + assert CM.rewrite(Integral).dummy_eq(expri) + assert CM.doit().simplify() == 15*sigma**6 + CM = Moment(5, 5) + assert CM.doit() == 5**5 diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/__init__.py b/.venv/lib/python3.12/site-packages/sympy/strategies/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bb4c5aa8afe6fd818e136ec0797b7429e2da76cf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/strategies/__init__.py @@ -0,0 +1,50 @@ +""" Rewrite Rules + +DISCLAIMER: This module is experimental. The interface is subject to change. + +A rule is a function that transforms one expression into another + + Rule :: Expr -> Expr + +A strategy is a function that says how a rule should be applied to a syntax +tree. In general strategies take rules and produce a new rule + + Strategy :: [Rules], Other-stuff -> Rule + +This allows developers to separate a mathematical transformation from the +algorithmic details of applying that transformation. The goal is to separate +the work of mathematical programming from algorithmic programming. + +Submodules + +strategies.rl - some fundamental rules +strategies.core - generic non-SymPy specific strategies +strategies.traverse - strategies that traverse a SymPy tree +strategies.tools - some conglomerate strategies that do depend on SymPy +""" + +from . import rl +from . import traverse +from .rl import rm_id, unpack, flatten, sort, glom, distribute, rebuild +from .util import new +from .core import ( + condition, debug, chain, null_safe, do_one, exhaust, minimize, tryit) +from .tools import canon, typed +from . import branch + +__all__ = [ + 'rl', + + 'traverse', + + 'rm_id', 'unpack', 'flatten', 'sort', 'glom', 'distribute', 'rebuild', + + 'new', + + 'condition', 'debug', 'chain', 'null_safe', 'do_one', 'exhaust', + 'minimize', 'tryit', + + 'canon', 'typed', + + 'branch', +] diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/strategies/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..240f48f7ab63c2ee9e5c9ca17d8c3a128dafa669 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/strategies/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/__pycache__/core.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/strategies/__pycache__/core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd666769ea83723482094ffdd0ae9ecc5d45d738 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/strategies/__pycache__/core.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/__pycache__/rl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/strategies/__pycache__/rl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07ee061006c339aaae900dca30d8437938fa374b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/strategies/__pycache__/rl.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/__pycache__/tools.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/strategies/__pycache__/tools.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77193a07eee9055bd9d47e0c3d43fe119ec556dd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/strategies/__pycache__/tools.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/__pycache__/traverse.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/strategies/__pycache__/traverse.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38f00e5a2bd4fd0f7f8ac5223d43d8d97e42eac9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/strategies/__pycache__/traverse.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/__pycache__/tree.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/strategies/__pycache__/tree.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56456543fe8a0998705a1ac2bb3893d5635ba84e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/strategies/__pycache__/tree.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/__pycache__/util.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/strategies/__pycache__/util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f13cc1ee1a1b0db3575e3fd87771a96395bd008f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/strategies/__pycache__/util.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/branch/__init__.py b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fec5afe84a58f3d887a8c762692a3673a2b6d4c8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/__init__.py @@ -0,0 +1,14 @@ +from . import traverse +from .core import ( + condition, debug, multiplex, exhaust, notempty, + chain, onaction, sfilter, yieldify, do_one, identity) +from .tools import canon + +__all__ = [ + 'traverse', + + 'condition', 'debug', 'multiplex', 'exhaust', 'notempty', 'chain', + 'onaction', 'sfilter', 'yieldify', 'do_one', 'identity', + + 'canon', +] diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/branch/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f77ace8355de9f13735d229bb335b9bbe36a0dfd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/branch/__pycache__/core.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/__pycache__/core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..220ad023d41e7d4fd53144ee88aef5ddb8febea6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/__pycache__/core.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/branch/__pycache__/tools.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/__pycache__/tools.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d96992a613d81ebb3474c417a68d2222f9145495 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/__pycache__/tools.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/branch/__pycache__/traverse.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/__pycache__/traverse.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58f0df8348297c6eb3f07d78e94beb58a5b44b05 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/__pycache__/traverse.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/branch/core.py b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/core.py new file mode 100644 index 0000000000000000000000000000000000000000..2dabaef69b60d994799f71414699223f84e1809b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/core.py @@ -0,0 +1,116 @@ +""" Generic SymPy-Independent Strategies """ + + +def identity(x): + yield x + + +def exhaust(brule): + """ Apply a branching rule repeatedly until it has no effect """ + def exhaust_brl(expr): + seen = {expr} + for nexpr in brule(expr): + if nexpr not in seen: + seen.add(nexpr) + yield from exhaust_brl(nexpr) + if seen == {expr}: + yield expr + return exhaust_brl + + +def onaction(brule, fn): + def onaction_brl(expr): + for result in brule(expr): + if result != expr: + fn(brule, expr, result) + yield result + return onaction_brl + + +def debug(brule, file=None): + """ Print the input and output expressions at each rule application """ + if not file: + from sys import stdout + file = stdout + + def write(brl, expr, result): + file.write("Rule: %s\n" % brl.__name__) + file.write("In: %s\nOut: %s\n\n" % (expr, result)) + + return onaction(brule, write) + + +def multiplex(*brules): + """ Multiplex many branching rules into one """ + def multiplex_brl(expr): + seen = set() + for brl in brules: + for nexpr in brl(expr): + if nexpr not in seen: + seen.add(nexpr) + yield nexpr + return multiplex_brl + + +def condition(cond, brule): + """ Only apply branching rule if condition is true """ + def conditioned_brl(expr): + if cond(expr): + yield from brule(expr) + else: + pass + return conditioned_brl + + +def sfilter(pred, brule): + """ Yield only those results which satisfy the predicate """ + def filtered_brl(expr): + yield from filter(pred, brule(expr)) + return filtered_brl + + +def notempty(brule): + def notempty_brl(expr): + yielded = False + for nexpr in brule(expr): + yielded = True + yield nexpr + if not yielded: + yield expr + return notempty_brl + + +def do_one(*brules): + """ Execute one of the branching rules """ + def do_one_brl(expr): + yielded = False + for brl in brules: + for nexpr in brl(expr): + yielded = True + yield nexpr + if yielded: + return + return do_one_brl + + +def chain(*brules): + """ + Compose a sequence of brules so that they apply to the expr sequentially + """ + def chain_brl(expr): + if not brules: + yield expr + return + + head, tail = brules[0], brules[1:] + for nexpr in head(expr): + yield from chain(*tail)(nexpr) + + return chain_brl + + +def yieldify(rl): + """ Turn a rule into a branching rule """ + def brl(expr): + yield rl(expr) + return brl diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tests/__init__.py b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tests/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddc76666438b5f176ae4f3d9c6a7806926cf3cd2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tests/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tests/__pycache__/test_core.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tests/__pycache__/test_core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac4205c6dd613aaf6d085fd6f3255693966bda69 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tests/__pycache__/test_core.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tests/__pycache__/test_tools.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tests/__pycache__/test_tools.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc6bcb03a4a0c673ea8e0af0a3dc81c93b100175 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tests/__pycache__/test_tools.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tests/__pycache__/test_traverse.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tests/__pycache__/test_traverse.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a6e137c9fcc5069f113755f572c6ca599585401 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tests/__pycache__/test_traverse.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tests/test_core.py b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tests/test_core.py new file mode 100644 index 0000000000000000000000000000000000000000..ac620b0afb6dbadc4d97b29ddbb341cd920b6588 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tests/test_core.py @@ -0,0 +1,117 @@ +from sympy.strategies.branch.core import ( + exhaust, debug, multiplex, condition, notempty, chain, onaction, sfilter, + yieldify, do_one, identity) + + +def posdec(x): + if x > 0: + yield x - 1 + else: + yield x + + +def branch5(x): + if 0 < x < 5: + yield x - 1 + elif 5 < x < 10: + yield x + 1 + elif x == 5: + yield x + 1 + yield x - 1 + else: + yield x + + +def even(x): + return x % 2 == 0 + + +def inc(x): + yield x + 1 + + +def one_to_n(n): + yield from range(n) + + +def test_exhaust(): + brl = exhaust(branch5) + assert set(brl(3)) == {0} + assert set(brl(7)) == {10} + assert set(brl(5)) == {0, 10} + + +def test_debug(): + from io import StringIO + file = StringIO() + rl = debug(posdec, file) + list(rl(5)) + log = file.getvalue() + file.close() + + assert posdec.__name__ in log + assert '5' in log + assert '4' in log + + +def test_multiplex(): + brl = multiplex(posdec, branch5) + assert set(brl(3)) == {2} + assert set(brl(7)) == {6, 8} + assert set(brl(5)) == {4, 6} + + +def test_condition(): + brl = condition(even, branch5) + assert set(brl(4)) == set(branch5(4)) + assert set(brl(5)) == set() + + +def test_sfilter(): + brl = sfilter(even, one_to_n) + assert set(brl(10)) == {0, 2, 4, 6, 8} + + +def test_notempty(): + def ident_if_even(x): + if even(x): + yield x + + brl = notempty(ident_if_even) + assert set(brl(4)) == {4} + assert set(brl(5)) == {5} + + +def test_chain(): + assert list(chain()(2)) == [2] # identity + assert list(chain(inc, inc)(2)) == [4] + assert list(chain(branch5, inc)(4)) == [4] + assert set(chain(branch5, inc)(5)) == {5, 7} + assert list(chain(inc, branch5)(5)) == [7] + + +def test_onaction(): + L = [] + + def record(fn, input, output): + L.append((input, output)) + + list(onaction(inc, record)(2)) + assert L == [(2, 3)] + + list(onaction(identity, record)(2)) + assert L == [(2, 3)] + + +def test_yieldify(): + yinc = yieldify(lambda x: x + 1) + assert list(yinc(3)) == [4] + + +def test_do_one(): + def bad(expr): + raise ValueError + + assert list(do_one(inc)(3)) == [4] + assert list(do_one(inc, bad)(3)) == [4] + assert list(do_one(inc, posdec)(3)) == [4] diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tests/test_tools.py b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tests/test_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..c2bd224030c337f0a000d94f6e7e65f3b8bd118f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tests/test_tools.py @@ -0,0 +1,42 @@ +from sympy.strategies.branch.tools import canon +from sympy.core.basic import Basic +from sympy.core.numbers import Integer +from sympy.core.singleton import S + + +def posdec(x): + if isinstance(x, Integer) and x > 0: + yield x - 1 + else: + yield x + + +def branch5(x): + if isinstance(x, Integer): + if 0 < x < 5: + yield x - 1 + elif 5 < x < 10: + yield x + 1 + elif x == 5: + yield x + 1 + yield x - 1 + else: + yield x + + +def test_zero_ints(): + expr = Basic(S(2), Basic(S(5), S(3)), S(8)) + expected = {Basic(S(0), Basic(S(0), S(0)), S(0))} + + brl = canon(posdec) + assert set(brl(expr)) == expected + + +def test_split5(): + expr = Basic(S(2), Basic(S(5), S(3)), S(8)) + expected = { + Basic(S(0), Basic(S(0), S(0)), S(10)), + Basic(S(0), Basic(S(10), S(0)), S(10))} + + brl = canon(branch5) + assert set(brl(expr)) == expected diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tests/test_traverse.py b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tests/test_traverse.py new file mode 100644 index 0000000000000000000000000000000000000000..e051928210981223004de28b8c617d0438e11ac6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tests/test_traverse.py @@ -0,0 +1,53 @@ +from sympy.core.basic import Basic +from sympy.core.numbers import Integer +from sympy.core.singleton import S +from sympy.strategies.branch.traverse import top_down, sall +from sympy.strategies.branch.core import do_one, identity + + +def inc(x): + if isinstance(x, Integer): + yield x + 1 + + +def test_top_down_easy(): + expr = Basic(S(1), S(2)) + expected = Basic(S(2), S(3)) + brl = top_down(inc) + + assert set(brl(expr)) == {expected} + + +def test_top_down_big_tree(): + expr = Basic(S(1), Basic(S(2)), Basic(S(3), Basic(S(4)), S(5))) + expected = Basic(S(2), Basic(S(3)), Basic(S(4), Basic(S(5)), S(6))) + brl = top_down(inc) + + assert set(brl(expr)) == {expected} + + +def test_top_down_harder_function(): + def split5(x): + if x == 5: + yield x - 1 + yield x + 1 + + expr = Basic(Basic(S(5), S(6)), S(1)) + expected = {Basic(Basic(S(4), S(6)), S(1)), Basic(Basic(S(6), S(6)), S(1))} + brl = top_down(split5) + + assert set(brl(expr)) == expected + + +def test_sall(): + expr = Basic(S(1), S(2)) + expected = Basic(S(2), S(3)) + brl = sall(inc) + + assert list(brl(expr)) == [expected] + + expr = Basic(S(1), S(2), Basic(S(3), S(4))) + expected = Basic(S(2), S(3), Basic(S(3), S(4))) + brl = sall(do_one(inc, identity)) + + assert list(brl(expr)) == [expected] diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tools.py b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tools.py new file mode 100644 index 0000000000000000000000000000000000000000..a6c9097323a7962080ae4497ead976818e386518 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/tools.py @@ -0,0 +1,12 @@ +from .core import exhaust, multiplex +from .traverse import top_down + + +def canon(*rules): + """ Strategy for canonicalization + + Apply each branching rule in a top-down fashion through the tree. + Multiplex through all branching rule traversals + Keep doing this until there is no change. + """ + return exhaust(multiplex(*map(top_down, rules))) diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/branch/traverse.py b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/traverse.py new file mode 100644 index 0000000000000000000000000000000000000000..28b7098dbda401fc0f0b6d27988d8c37e2f231ae --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/strategies/branch/traverse.py @@ -0,0 +1,25 @@ +""" Branching Strategies to Traverse a Tree """ +from itertools import product +from sympy.strategies.util import basic_fns +from .core import chain, identity, do_one + + +def top_down(brule, fns=basic_fns): + """ Apply a rule down a tree running it on the top nodes first """ + return chain(do_one(brule, identity), + lambda expr: sall(top_down(brule, fns), fns)(expr)) + + +def sall(brule, fns=basic_fns): + """ Strategic all - apply rule to args """ + op, new, children, leaf = map(fns.get, ('op', 'new', 'children', 'leaf')) + + def all_rl(expr): + if leaf(expr): + yield expr + else: + myop = op(expr) + argss = product(*map(brule, children(expr))) + for args in argss: + yield new(myop, *args) + return all_rl diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/core.py b/.venv/lib/python3.12/site-packages/sympy/strategies/core.py new file mode 100644 index 0000000000000000000000000000000000000000..75b75cb5f2e0693eea98a7b1c9b3e7f036ec26f6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/strategies/core.py @@ -0,0 +1,151 @@ +""" Generic SymPy-Independent Strategies """ +from __future__ import annotations +from collections.abc import Callable, Mapping +from typing import TypeVar +from sys import stdout + + +_S = TypeVar('_S') +_T = TypeVar('_T') + + +def identity(x: _T) -> _T: + return x + + +def exhaust(rule: Callable[[_T], _T]) -> Callable[[_T], _T]: + """ Apply a rule repeatedly until it has no effect """ + def exhaustive_rl(expr: _T) -> _T: + new, old = rule(expr), expr + while new != old: + new, old = rule(new), new + return new + return exhaustive_rl + + +def memoize(rule: Callable[[_S], _T]) -> Callable[[_S], _T]: + """Memoized version of a rule + + Notes + ===== + + This cache can grow infinitely, so it is not recommended to use this + than ``functools.lru_cache`` unless you need very heavy computation. + """ + cache: dict[_S, _T] = {} + + def memoized_rl(expr: _S) -> _T: + if expr in cache: + return cache[expr] + else: + result = rule(expr) + cache[expr] = result + return result + return memoized_rl + + +def condition( + cond: Callable[[_T], bool], rule: Callable[[_T], _T] +) -> Callable[[_T], _T]: + """ Only apply rule if condition is true """ + def conditioned_rl(expr: _T) -> _T: + if cond(expr): + return rule(expr) + return expr + return conditioned_rl + + +def chain(*rules: Callable[[_T], _T]) -> Callable[[_T], _T]: + """ + Compose a sequence of rules so that they apply to the expr sequentially + """ + def chain_rl(expr: _T) -> _T: + for rule in rules: + expr = rule(expr) + return expr + return chain_rl + + +def debug(rule, file=None): + """ Print out before and after expressions each time rule is used """ + if file is None: + file = stdout + + def debug_rl(*args, **kwargs): + expr = args[0] + result = rule(*args, **kwargs) + if result != expr: + file.write("Rule: %s\n" % rule.__name__) + file.write("In: %s\nOut: %s\n\n" % (expr, result)) + return result + return debug_rl + + +def null_safe(rule: Callable[[_T], _T | None]) -> Callable[[_T], _T]: + """ Return original expr if rule returns None """ + def null_safe_rl(expr: _T) -> _T: + result = rule(expr) + if result is None: + return expr + return result + return null_safe_rl + + +def tryit(rule: Callable[[_T], _T], exception) -> Callable[[_T], _T]: + """ Return original expr if rule raises exception """ + def try_rl(expr: _T) -> _T: + try: + return rule(expr) + except exception: + return expr + return try_rl + + +def do_one(*rules: Callable[[_T], _T]) -> Callable[[_T], _T]: + """ Try each of the rules until one works. Then stop. """ + def do_one_rl(expr: _T) -> _T: + for rl in rules: + result = rl(expr) + if result != expr: + return result + return expr + return do_one_rl + + +def switch( + key: Callable[[_S], _T], + ruledict: Mapping[_T, Callable[[_S], _S]] +) -> Callable[[_S], _S]: + """ Select a rule based on the result of key called on the function """ + def switch_rl(expr: _S) -> _S: + rl = ruledict.get(key(expr), identity) + return rl(expr) + return switch_rl + + +# XXX Untyped default argument for minimize function +# where python requires SupportsRichComparison type +def _identity(x): + return x + + +def minimize( + *rules: Callable[[_S], _T], + objective=_identity +) -> Callable[[_S], _T]: + """ Select result of rules that minimizes objective + + >>> from sympy.strategies import minimize + >>> inc = lambda x: x + 1 + >>> dec = lambda x: x - 1 + >>> rl = minimize(inc, dec) + >>> rl(4) + 3 + + >>> rl = minimize(inc, dec, objective=lambda x: -x) # maximize + >>> rl(4) + 5 + """ + def minrule(expr: _S) -> _T: + return min([rule(expr) for rule in rules], key=objective) + return minrule diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/rl.py b/.venv/lib/python3.12/site-packages/sympy/strategies/rl.py new file mode 100644 index 0000000000000000000000000000000000000000..e84ee90582fafcf36fd4205a58b05b650875a9a5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/strategies/rl.py @@ -0,0 +1,176 @@ +""" Generic Rules for SymPy + +This file assumes knowledge of Basic and little else. +""" +from sympy.utilities.iterables import sift +from .util import new + + +# Functions that create rules +def rm_id(isid, new=new): + """ Create a rule to remove identities. + + isid - fn :: x -> Bool --- whether or not this element is an identity. + + Examples + ======== + + >>> from sympy.strategies import rm_id + >>> from sympy import Basic, S + >>> remove_zeros = rm_id(lambda x: x==0) + >>> remove_zeros(Basic(S(1), S(0), S(2))) + Basic(1, 2) + >>> remove_zeros(Basic(S(0), S(0))) # If only identities then we keep one + Basic(0) + + See Also: + unpack + """ + def ident_remove(expr): + """ Remove identities """ + ids = list(map(isid, expr.args)) + if sum(ids) == 0: # No identities. Common case + return expr + elif sum(ids) != len(ids): # there is at least one non-identity + return new(expr.__class__, + *[arg for arg, x in zip(expr.args, ids) if not x]) + else: + return new(expr.__class__, expr.args[0]) + + return ident_remove + + +def glom(key, count, combine): + """ Create a rule to conglomerate identical args. + + Examples + ======== + + >>> from sympy.strategies import glom + >>> from sympy import Add + >>> from sympy.abc import x + + >>> key = lambda x: x.as_coeff_Mul()[1] + >>> count = lambda x: x.as_coeff_Mul()[0] + >>> combine = lambda cnt, arg: cnt * arg + >>> rl = glom(key, count, combine) + + >>> rl(Add(x, -x, 3*x, 2, 3, evaluate=False)) + 3*x + 5 + + Wait, how are key, count and combine supposed to work? + + >>> key(2*x) + x + >>> count(2*x) + 2 + >>> combine(2, x) + 2*x + """ + def conglomerate(expr): + """ Conglomerate together identical args x + x -> 2x """ + groups = sift(expr.args, key) + counts = {k: sum(map(count, args)) for k, args in groups.items()} + newargs = [combine(cnt, mat) for mat, cnt in counts.items()] + if set(newargs) != set(expr.args): + return new(type(expr), *newargs) + else: + return expr + + return conglomerate + + +def sort(key, new=new): + """ Create a rule to sort by a key function. + + Examples + ======== + + >>> from sympy.strategies import sort + >>> from sympy import Basic, S + >>> sort_rl = sort(str) + >>> sort_rl(Basic(S(3), S(1), S(2))) + Basic(1, 2, 3) + """ + + def sort_rl(expr): + return new(expr.__class__, *sorted(expr.args, key=key)) + return sort_rl + + +def distribute(A, B): + """ Turns an A containing Bs into a B of As + + where A, B are container types + + >>> from sympy.strategies import distribute + >>> from sympy import Add, Mul, symbols + >>> x, y = symbols('x,y') + >>> dist = distribute(Mul, Add) + >>> expr = Mul(2, x+y, evaluate=False) + >>> expr + 2*(x + y) + >>> dist(expr) + 2*x + 2*y + """ + + def distribute_rl(expr): + for i, arg in enumerate(expr.args): + if isinstance(arg, B): + first, b, tail = expr.args[:i], expr.args[i], expr.args[i + 1:] + return B(*[A(*(first + (arg,) + tail)) for arg in b.args]) + return expr + return distribute_rl + + +def subs(a, b): + """ Replace expressions exactly """ + def subs_rl(expr): + if expr == a: + return b + else: + return expr + return subs_rl + + +# Functions that are rules +def unpack(expr): + """ Rule to unpack singleton args + + >>> from sympy.strategies import unpack + >>> from sympy import Basic, S + >>> unpack(Basic(S(2))) + 2 + """ + if len(expr.args) == 1: + return expr.args[0] + else: + return expr + + +def flatten(expr, new=new): + """ Flatten T(a, b, T(c, d), T2(e)) to T(a, b, c, d, T2(e)) """ + cls = expr.__class__ + args = [] + for arg in expr.args: + if arg.__class__ == cls: + args.extend(arg.args) + else: + args.append(arg) + return new(expr.__class__, *args) + + +def rebuild(expr): + """ Rebuild a SymPy tree. + + Explanation + =========== + + This function recursively calls constructors in the expression tree. + This forces canonicalization and removes ugliness introduced by the use of + Basic.__new__ + """ + if expr.is_Atom: + return expr + else: + return expr.func(*list(map(rebuild, expr.args))) diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/tests/__init__.py b/.venv/lib/python3.12/site-packages/sympy/strategies/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/tests/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/strategies/tests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa3b29aa02f67982f40459d4e421a1f2e302a0dd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/strategies/tests/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/tests/__pycache__/test_core.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/strategies/tests/__pycache__/test_core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af3aeab09a2775ac1e760faad2b9d3058cc5434e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/strategies/tests/__pycache__/test_core.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/tests/__pycache__/test_rl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/strategies/tests/__pycache__/test_rl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a61965fd978fda3390cf7033988f45f072bc5633 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/strategies/tests/__pycache__/test_rl.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/tests/__pycache__/test_tools.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/strategies/tests/__pycache__/test_tools.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b20510ebfdf061064ae5b64a0f2fda6945fe04e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/strategies/tests/__pycache__/test_tools.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/tests/__pycache__/test_traverse.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/strategies/tests/__pycache__/test_traverse.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..889258eafa3b4317a4ff2c84cc7d0a9137abbb93 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/strategies/tests/__pycache__/test_traverse.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/tests/__pycache__/test_tree.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/strategies/tests/__pycache__/test_tree.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abc24b0c7f5c95c7944685d37a62c0856762f30c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/strategies/tests/__pycache__/test_tree.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/tests/test_core.py b/.venv/lib/python3.12/site-packages/sympy/strategies/tests/test_core.py new file mode 100644 index 0000000000000000000000000000000000000000..1e19bcab1940c476a8996b7ba92e7645a6230034 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/strategies/tests/test_core.py @@ -0,0 +1,118 @@ +from __future__ import annotations +from sympy.core.singleton import S +from sympy.core.basic import Basic +from sympy.strategies.core import ( + null_safe, exhaust, memoize, condition, + chain, tryit, do_one, debug, switch, minimize) +from io import StringIO + + +def posdec(x: int) -> int: + if x > 0: + return x - 1 + return x + + +def inc(x: int) -> int: + return x + 1 + + +def dec(x: int) -> int: + return x - 1 + + +def test_null_safe(): + def rl(expr: int) -> int | None: + if expr == 1: + return 2 + return None + + safe_rl = null_safe(rl) + assert rl(1) == safe_rl(1) + assert rl(3) is None + assert safe_rl(3) == 3 + + +def test_exhaust(): + sink = exhaust(posdec) + assert sink(5) == 0 + assert sink(10) == 0 + + +def test_memoize(): + rl = memoize(posdec) + assert rl(5) == posdec(5) + assert rl(5) == posdec(5) + assert rl(-2) == posdec(-2) + + +def test_condition(): + rl = condition(lambda x: x % 2 == 0, posdec) + assert rl(5) == 5 + assert rl(4) == 3 + + +def test_chain(): + rl = chain(posdec, posdec) + assert rl(5) == 3 + assert rl(1) == 0 + + +def test_tryit(): + def rl(expr: Basic) -> Basic: + assert False + + safe_rl = tryit(rl, AssertionError) + assert safe_rl(S(1)) == S(1) + + +def test_do_one(): + rl = do_one(posdec, posdec) + assert rl(5) == 4 + + def rl1(x: int) -> int: + if x == 1: + return 2 + return x + + def rl2(x: int) -> int: + if x == 2: + return 3 + return x + + rule = do_one(rl1, rl2) + assert rule(1) == 2 + assert rule(rule(1)) == 3 + + +def test_debug(): + file = StringIO() + rl = debug(posdec, file) + rl(5) + log = file.getvalue() + file.close() + + assert posdec.__name__ in log + assert '5' in log + assert '4' in log + + +def test_switch(): + def key(x: int) -> int: + return x % 3 + + rl = switch(key, {0: inc, 1: dec}) + assert rl(3) == 4 + assert rl(4) == 3 + assert rl(5) == 5 + + +def test_minimize(): + def key(x: int) -> int: + return -x + + rl = minimize(inc, dec) + assert rl(4) == 3 + + rl = minimize(inc, dec, objective=key) + assert rl(4) == 5 diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/tests/test_rl.py b/.venv/lib/python3.12/site-packages/sympy/strategies/tests/test_rl.py new file mode 100644 index 0000000000000000000000000000000000000000..8bfa90ad4d970b21396e0e1b6427b5a5c68fe381 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/strategies/tests/test_rl.py @@ -0,0 +1,78 @@ +from sympy.core.singleton import S +from sympy.strategies.rl import ( + rm_id, glom, flatten, unpack, sort, distribute, subs, rebuild) +from sympy.core.basic import Basic +from sympy.core.add import Add +from sympy.core.mul import Mul +from sympy.core.symbol import symbols +from sympy.abc import x + + +def test_rm_id(): + rmzeros = rm_id(lambda x: x == 0) + assert rmzeros(Basic(S(0), S(1))) == Basic(S(1)) + assert rmzeros(Basic(S(0), S(0))) == Basic(S(0)) + assert rmzeros(Basic(S(2), S(1))) == Basic(S(2), S(1)) + + +def test_glom(): + def key(x): + return x.as_coeff_Mul()[1] + + def count(x): + return x.as_coeff_Mul()[0] + + def newargs(cnt, arg): + return cnt * arg + + rl = glom(key, count, newargs) + + result = rl(Add(x, -x, 3 * x, 2, 3, evaluate=False)) + expected = Add(3 * x, 5) + assert set(result.args) == set(expected.args) + + +def test_flatten(): + assert flatten(Basic(S(1), S(2), Basic(S(3), S(4)))) == \ + Basic(S(1), S(2), S(3), S(4)) + + +def test_unpack(): + assert unpack(Basic(S(2))) == 2 + assert unpack(Basic(S(2), S(3))) == Basic(S(2), S(3)) + + +def test_sort(): + assert sort(str)(Basic(S(3), S(1), S(2))) == Basic(S(1), S(2), S(3)) + + +def test_distribute(): + class T1(Basic): + pass + + class T2(Basic): + pass + + distribute_t12 = distribute(T1, T2) + assert distribute_t12(T1(S(1), S(2), T2(S(3), S(4)), S(5))) == \ + T2(T1(S(1), S(2), S(3), S(5)), T1(S(1), S(2), S(4), S(5))) + assert distribute_t12(T1(S(1), S(2), S(3))) == T1(S(1), S(2), S(3)) + + +def test_distribute_add_mul(): + x, y = symbols('x, y') + expr = Mul(2, Add(x, y), evaluate=False) + expected = Add(Mul(2, x), Mul(2, y)) + distribute_mul = distribute(Mul, Add) + assert distribute_mul(expr) == expected + + +def test_subs(): + rl = subs(1, 2) + assert rl(1) == 2 + assert rl(3) == 3 + + +def test_rebuild(): + expr = Basic.__new__(Add, S(1), S(2)) + assert rebuild(expr) == 3 diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/tests/test_tools.py b/.venv/lib/python3.12/site-packages/sympy/strategies/tests/test_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..89774aeb92ead5781966e4f48ad32dc63e1bf7e2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/strategies/tests/test_tools.py @@ -0,0 +1,32 @@ +from sympy.strategies.tools import subs, typed +from sympy.strategies.rl import rm_id +from sympy.core.basic import Basic +from sympy.core.singleton import S + + +def test_subs(): + from sympy.core.symbol import symbols + a, b, c, d, e, f = symbols('a,b,c,d,e,f') + mapping = {a: d, d: a, Basic(e): Basic(f)} + expr = Basic(a, Basic(b, c), Basic(d, Basic(e))) + result = Basic(d, Basic(b, c), Basic(a, Basic(f))) + assert subs(mapping)(expr) == result + + +def test_subs_empty(): + assert subs({})(Basic(S(1), S(2))) == Basic(S(1), S(2)) + + +def test_typed(): + class A(Basic): + pass + + class B(Basic): + pass + + rmzeros = rm_id(lambda x: x == S(0)) + rmones = rm_id(lambda x: x == S(1)) + remove_something = typed({A: rmzeros, B: rmones}) + + assert remove_something(A(S(0), S(1))) == A(S(1)) + assert remove_something(B(S(0), S(1))) == B(S(0)) diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/tests/test_traverse.py b/.venv/lib/python3.12/site-packages/sympy/strategies/tests/test_traverse.py new file mode 100644 index 0000000000000000000000000000000000000000..ee2409616a8b4f750af8baea149b2ea52c56be9d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/strategies/tests/test_traverse.py @@ -0,0 +1,84 @@ +from sympy.strategies.traverse import ( + top_down, bottom_up, sall, top_down_once, bottom_up_once, basic_fns) +from sympy.strategies.rl import rebuild +from sympy.strategies.util import expr_fns +from sympy.core.add import Add +from sympy.core.basic import Basic +from sympy.core.numbers import Integer +from sympy.core.singleton import S +from sympy.core.symbol import Str, Symbol +from sympy.abc import x, y, z + + +def zero_symbols(expression): + return S.Zero if isinstance(expression, Symbol) else expression + + +def test_sall(): + zero_onelevel = sall(zero_symbols) + + assert zero_onelevel(Basic(x, y, Basic(x, z))) == \ + Basic(S(0), S(0), Basic(x, z)) + + +def test_bottom_up(): + _test_global_traversal(bottom_up) + _test_stop_on_non_basics(bottom_up) + + +def test_top_down(): + _test_global_traversal(top_down) + _test_stop_on_non_basics(top_down) + + +def _test_global_traversal(trav): + zero_all_symbols = trav(zero_symbols) + + assert zero_all_symbols(Basic(x, y, Basic(x, z))) == \ + Basic(S(0), S(0), Basic(S(0), S(0))) + + +def _test_stop_on_non_basics(trav): + def add_one_if_can(expr): + try: + return expr + 1 + except TypeError: + return expr + + expr = Basic(S(1), Str('a'), Basic(S(2), Str('b'))) + expected = Basic(S(2), Str('a'), Basic(S(3), Str('b'))) + rl = trav(add_one_if_can) + + assert rl(expr) == expected + + +class Basic2(Basic): + pass + + +def rl(x): + if x.args and not isinstance(x.args[0], Integer): + return Basic2(*x.args) + return x + + +def test_top_down_once(): + top_rl = top_down_once(rl) + + assert top_rl(Basic(S(1.0), S(2.0), Basic(S(3), S(4)))) == \ + Basic2(S(1.0), S(2.0), Basic(S(3), S(4))) + + +def test_bottom_up_once(): + bottom_rl = bottom_up_once(rl) + + assert bottom_rl(Basic(S(1), S(2), Basic(S(3.0), S(4.0)))) == \ + Basic(S(1), S(2), Basic2(S(3.0), S(4.0))) + + +def test_expr_fns(): + expr = x + y**3 + e = bottom_up(lambda v: v + 1, expr_fns)(expr) + b = bottom_up(lambda v: Basic.__new__(Add, v, S(1)), basic_fns)(expr) + + assert rebuild(b) == e diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/tests/test_tree.py b/.venv/lib/python3.12/site-packages/sympy/strategies/tests/test_tree.py new file mode 100644 index 0000000000000000000000000000000000000000..d5cdde747fe3ab90c8fd181701194403bc526067 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/strategies/tests/test_tree.py @@ -0,0 +1,92 @@ +from sympy.strategies.tree import treeapply, greedy, allresults, brute +from functools import partial, reduce + + +def inc(x): + return x + 1 + + +def dec(x): + return x - 1 + + +def double(x): + return 2 * x + + +def square(x): + return x**2 + + +def add(*args): + return sum(args) + + +def mul(*args): + return reduce(lambda a, b: a * b, args, 1) + + +def test_treeapply(): + tree = ([3, 3], [4, 1], 2) + assert treeapply(tree, {list: min, tuple: max}) == 3 + assert treeapply(tree, {list: add, tuple: mul}) == 60 + + +def test_treeapply_leaf(): + assert treeapply(3, {}, leaf=lambda x: x**2) == 9 + tree = ([3, 3], [4, 1], 2) + treep1 = ([4, 4], [5, 2], 3) + assert treeapply(tree, {list: min, tuple: max}, leaf=lambda x: x + 1) == \ + treeapply(treep1, {list: min, tuple: max}) + + +def test_treeapply_strategies(): + from sympy.strategies import chain, minimize + join = {list: chain, tuple: minimize} + + assert treeapply(inc, join) == inc + assert treeapply((inc, dec), join)(5) == minimize(inc, dec)(5) + assert treeapply([inc, dec], join)(5) == chain(inc, dec)(5) + tree = (inc, [dec, double]) # either inc or dec-then-double + assert treeapply(tree, join)(5) == 6 + assert treeapply(tree, join)(1) == 0 + + maximize = partial(minimize, objective=lambda x: -x) + join = {list: chain, tuple: maximize} + fn = treeapply(tree, join) + assert fn(4) == 6 # highest value comes from the dec then double + assert fn(1) == 2 # highest value comes from the inc + + +def test_greedy(): + tree = [inc, (dec, double)] # either inc or dec-then-double + + fn = greedy(tree, objective=lambda x: -x) + assert fn(4) == 6 # highest value comes from the dec then double + assert fn(1) == 2 # highest value comes from the inc + + tree = [inc, dec, [inc, dec, [(inc, inc), (dec, dec)]]] + lowest = greedy(tree) + assert lowest(10) == 8 + + highest = greedy(tree, objective=lambda x: -x) + assert highest(10) == 12 + + +def test_allresults(): + # square = lambda x: x**2 + + assert set(allresults(inc)(3)) == {inc(3)} + assert set(allresults([inc, dec])(3)) == {2, 4} + assert set(allresults((inc, dec))(3)) == {3} + assert set(allresults([inc, (dec, double)])(4)) == {5, 6} + + +def test_brute(): + tree = ([inc, dec], square) + fn = brute(tree, lambda x: -x) + + assert fn(2) == (2 + 1)**2 + assert fn(-2) == (-2 - 1)**2 + + assert brute(inc)(1) == 2 diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/tools.py b/.venv/lib/python3.12/site-packages/sympy/strategies/tools.py new file mode 100644 index 0000000000000000000000000000000000000000..e6a94c16db57206d7c83c8a5e13930c4cffdde47 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/strategies/tools.py @@ -0,0 +1,53 @@ +from . import rl +from .core import do_one, exhaust, switch +from .traverse import top_down + + +def subs(d, **kwargs): + """ Full simultaneous exact substitution. + + Examples + ======== + + >>> from sympy.strategies.tools import subs + >>> from sympy import Basic, S + >>> mapping = {S(1): S(4), S(4): S(1), Basic(S(5)): Basic(S(6), S(7))} + >>> expr = Basic(S(1), Basic(S(2), S(3)), Basic(S(4), Basic(S(5)))) + >>> subs(mapping)(expr) + Basic(4, Basic(2, 3), Basic(1, Basic(6, 7))) + """ + if d: + return top_down(do_one(*map(rl.subs, *zip(*d.items()))), **kwargs) + else: + return lambda x: x + + +def canon(*rules, **kwargs): + """ Strategy for canonicalization. + + Explanation + =========== + + Apply each rule in a bottom_up fashion through the tree. + Do each one in turn. + Keep doing this until there is no change. + """ + return exhaust(top_down(exhaust(do_one(*rules)), **kwargs)) + + +def typed(ruletypes): + """ Apply rules based on the expression type + + inputs: + ruletypes -- a dict mapping {Type: rule} + + Examples + ======== + + >>> from sympy.strategies import rm_id, typed + >>> from sympy import Add, Mul + >>> rm_zeros = rm_id(lambda x: x==0) + >>> rm_ones = rm_id(lambda x: x==1) + >>> remove_idents = typed({Add: rm_zeros, Mul: rm_ones}) + """ + return switch(type, ruletypes) diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/traverse.py b/.venv/lib/python3.12/site-packages/sympy/strategies/traverse.py new file mode 100644 index 0000000000000000000000000000000000000000..869361f443742b5b7346c9c970f103b955e8473e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/strategies/traverse.py @@ -0,0 +1,37 @@ +"""Strategies to Traverse a Tree.""" +from sympy.strategies.util import basic_fns +from sympy.strategies.core import chain, do_one + + +def top_down(rule, fns=basic_fns): + """Apply a rule down a tree running it on the top nodes first.""" + return chain(rule, lambda expr: sall(top_down(rule, fns), fns)(expr)) + + +def bottom_up(rule, fns=basic_fns): + """Apply a rule down a tree running it on the bottom nodes first.""" + return chain(lambda expr: sall(bottom_up(rule, fns), fns)(expr), rule) + + +def top_down_once(rule, fns=basic_fns): + """Apply a rule down a tree - stop on success.""" + return do_one(rule, lambda expr: sall(top_down(rule, fns), fns)(expr)) + + +def bottom_up_once(rule, fns=basic_fns): + """Apply a rule up a tree - stop on success.""" + return do_one(lambda expr: sall(bottom_up(rule, fns), fns)(expr), rule) + + +def sall(rule, fns=basic_fns): + """Strategic all - apply rule to args.""" + op, new, children, leaf = map(fns.get, ('op', 'new', 'children', 'leaf')) + + def all_rl(expr): + if leaf(expr): + return expr + else: + args = map(rule, children(expr)) + return new(op(expr), *args) + + return all_rl diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/tree.py b/.venv/lib/python3.12/site-packages/sympy/strategies/tree.py new file mode 100644 index 0000000000000000000000000000000000000000..c2006fde4fc5d09f3d38baae4d7335b4cbd971b7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/strategies/tree.py @@ -0,0 +1,139 @@ +from functools import partial +from sympy.strategies import chain, minimize +from sympy.strategies.core import identity +import sympy.strategies.branch as branch +from sympy.strategies.branch import yieldify + + +def treeapply(tree, join, leaf=identity): + """ Apply functions onto recursive containers (tree). + + Explanation + =========== + + join - a dictionary mapping container types to functions + e.g. ``{list: minimize, tuple: chain}`` + + Keys are containers/iterables. Values are functions [a] -> a. + + Examples + ======== + + >>> from sympy.strategies.tree import treeapply + >>> tree = [(3, 2), (4, 1)] + >>> treeapply(tree, {list: max, tuple: min}) + 2 + + >>> add = lambda *args: sum(args) + >>> def mul(*args): + ... total = 1 + ... for arg in args: + ... total *= arg + ... return total + >>> treeapply(tree, {list: mul, tuple: add}) + 25 + """ + for typ in join: + if isinstance(tree, typ): + return join[typ](*map(partial(treeapply, join=join, leaf=leaf), + tree)) + return leaf(tree) + + +def greedy(tree, objective=identity, **kwargs): + """ Execute a strategic tree. Select alternatives greedily + + Trees + ----- + + Nodes in a tree can be either + + function - a leaf + list - a selection among operations + tuple - a sequence of chained operations + + Textual examples + ---------------- + + Text: Run f, then run g, e.g. ``lambda x: g(f(x))`` + Code: ``(f, g)`` + + Text: Run either f or g, whichever minimizes the objective + Code: ``[f, g]`` + + Textx: Run either f or g, whichever is better, then run h + Code: ``([f, g], h)`` + + Text: Either expand then simplify or try factor then foosimp. Finally print + Code: ``([(expand, simplify), (factor, foosimp)], print)`` + + Objective + --------- + + "Better" is determined by the objective keyword. This function makes + choices to minimize the objective. It defaults to the identity. + + Examples + ======== + + >>> from sympy.strategies.tree import greedy + >>> inc = lambda x: x + 1 + >>> dec = lambda x: x - 1 + >>> double = lambda x: 2*x + + >>> tree = [inc, (dec, double)] # either inc or dec-then-double + >>> fn = greedy(tree) + >>> fn(4) # lowest value comes from the inc + 5 + >>> fn(1) # lowest value comes from dec then double + 0 + + This function selects between options in a tuple. The result is chosen + that minimizes the objective function. + + >>> fn = greedy(tree, objective=lambda x: -x) # maximize + >>> fn(4) # highest value comes from the dec then double + 6 + >>> fn(1) # highest value comes from the inc + 2 + + Greediness + ---------- + + This is a greedy algorithm. In the example: + + ([a, b], c) # do either a or b, then do c + + the choice between running ``a`` or ``b`` is made without foresight to c + """ + optimize = partial(minimize, objective=objective) + return treeapply(tree, {list: optimize, tuple: chain}, **kwargs) + + +def allresults(tree, leaf=yieldify): + """ Execute a strategic tree. Return all possibilities. + + Returns a lazy iterator of all possible results + + Exhaustiveness + -------------- + + This is an exhaustive algorithm. In the example + + ([a, b], [c, d]) + + All of the results from + + (a, c), (b, c), (a, d), (b, d) + + are returned. This can lead to combinatorial blowup. + + See sympy.strategies.greedy for details on input + """ + return treeapply(tree, {list: branch.multiplex, tuple: branch.chain}, + leaf=leaf) + + +def brute(tree, objective=identity, **kwargs): + return lambda expr: min(tuple(allresults(tree, **kwargs)(expr)), + key=objective) diff --git a/.venv/lib/python3.12/site-packages/sympy/strategies/util.py b/.venv/lib/python3.12/site-packages/sympy/strategies/util.py new file mode 100644 index 0000000000000000000000000000000000000000..13aab5f6a49650c5ded9cd913c23c6682f18d40a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/strategies/util.py @@ -0,0 +1,17 @@ +from sympy.core.basic import Basic + +new = Basic.__new__ + + +def assoc(d, k, v): + d = d.copy() + d[k] = v + return d + + +basic_fns = {'op': type, + 'new': Basic.__new__, + 'leaf': lambda x: not isinstance(x, Basic) or x.is_Atom, + 'children': lambda x: x.args} + +expr_fns = assoc(basic_fns, 'new', lambda op, *args: op(*args)) diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/__init__.py b/.venv/lib/python3.12/site-packages/sympy/tensor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a832614b1d48e26bf01e16f040f34dd412e8e32b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/__init__.py @@ -0,0 +1,23 @@ +"""A module to manipulate symbolic objects with indices including tensors + +""" +from .indexed import IndexedBase, Idx, Indexed +from .index_methods import get_contraction_structure, get_indices +from .functions import shape +from .array import (MutableDenseNDimArray, ImmutableDenseNDimArray, + MutableSparseNDimArray, ImmutableSparseNDimArray, NDimArray, tensorproduct, + tensorcontraction, tensordiagonal, derive_by_array, permutedims, Array, + DenseNDimArray, SparseNDimArray,) + +__all__ = [ + 'IndexedBase', 'Idx', 'Indexed', + + 'get_contraction_structure', 'get_indices', + + 'shape', + + 'MutableDenseNDimArray', 'ImmutableDenseNDimArray', + 'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'NDimArray', + 'tensorproduct', 'tensorcontraction', 'tensordiagonal', 'derive_by_array', 'permutedims', + 'Array', 'DenseNDimArray', 'SparseNDimArray', +] diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac4ceadb7d50bf7b663470e3351963b12388e4f7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/__pycache__/functions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/__pycache__/functions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b11bc758347e13d12087edd6791b29ff381f9f04 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/__pycache__/functions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/__pycache__/index_methods.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/__pycache__/index_methods.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6691574d19ed2ae49712f558b47fdbf95f5f95b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/__pycache__/index_methods.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/__pycache__/indexed.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/__pycache__/indexed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28bfe278392cedafb7bc2ef9395bf96ff6045dc9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/__pycache__/indexed.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/__pycache__/tensor.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/__pycache__/tensor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ba08fc1bf5b2a438664148723fb15e6f9b78024 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/__pycache__/tensor.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1c3c496acb117628f8de5c4ee6a63cf025f6b578eb99bea420db4149fe070314 +size 228647 diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/__pycache__/toperators.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/__pycache__/toperators.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5133fc95ea7f75dbb7660b436129cf2c7567f419 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/__pycache__/toperators.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/__init__.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eca2eb4c6c58cb113517b6e41737e9d97abbb84e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/__init__.py @@ -0,0 +1,271 @@ +r""" +N-dim array module for SymPy. + +Four classes are provided to handle N-dim arrays, given by the combinations +dense/sparse (i.e. whether to store all elements or only the non-zero ones in +memory) and mutable/immutable (immutable classes are SymPy objects, but cannot +change after they have been created). + +Examples +======== + +The following examples show the usage of ``Array``. This is an abbreviation for +``ImmutableDenseNDimArray``, that is an immutable and dense N-dim array, the +other classes are analogous. For mutable classes it is also possible to change +element values after the object has been constructed. + +Array construction can detect the shape of nested lists and tuples: + +>>> from sympy import Array +>>> a1 = Array([[1, 2], [3, 4], [5, 6]]) +>>> a1 +[[1, 2], [3, 4], [5, 6]] +>>> a1.shape +(3, 2) +>>> a1.rank() +2 +>>> from sympy.abc import x, y, z +>>> a2 = Array([[[x, y], [z, x*z]], [[1, x*y], [1/x, x/y]]]) +>>> a2 +[[[x, y], [z, x*z]], [[1, x*y], [1/x, x/y]]] +>>> a2.shape +(2, 2, 2) +>>> a2.rank() +3 + +Otherwise one could pass a 1-dim array followed by a shape tuple: + +>>> m1 = Array(range(12), (3, 4)) +>>> m1 +[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] +>>> m2 = Array(range(12), (3, 2, 2)) +>>> m2 +[[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]] +>>> m2[1,1,1] +7 +>>> m2.reshape(4, 3) +[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]] + +Slice support: + +>>> m2[:, 1, 1] +[3, 7, 11] + +Elementwise derivative: + +>>> from sympy.abc import x, y, z +>>> m3 = Array([x**3, x*y, z]) +>>> m3.diff(x) +[3*x**2, y, 0] +>>> m3.diff(z) +[0, 0, 1] + +Multiplication with other SymPy expressions is applied elementwisely: + +>>> (1+x)*m3 +[x**3*(x + 1), x*y*(x + 1), z*(x + 1)] + +To apply a function to each element of the N-dim array, use ``applyfunc``: + +>>> m3.applyfunc(lambda x: x/2) +[x**3/2, x*y/2, z/2] + +N-dim arrays can be converted to nested lists by the ``tolist()`` method: + +>>> m2.tolist() +[[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]] +>>> isinstance(m2.tolist(), list) +True + +If the rank is 2, it is possible to convert them to matrices with ``tomatrix()``: + +>>> m1.tomatrix() +Matrix([ +[0, 1, 2, 3], +[4, 5, 6, 7], +[8, 9, 10, 11]]) + +Products and contractions +------------------------- + +Tensor product between arrays `A_{i_1,\ldots,i_n}` and `B_{j_1,\ldots,j_m}` +creates the combined array `P = A \otimes B` defined as + +`P_{i_1,\ldots,i_n,j_1,\ldots,j_m} := A_{i_1,\ldots,i_n}\cdot B_{j_1,\ldots,j_m}.` + +It is available through ``tensorproduct(...)``: + +>>> from sympy import Array, tensorproduct +>>> from sympy.abc import x,y,z,t +>>> A = Array([x, y, z, t]) +>>> B = Array([1, 2, 3, 4]) +>>> tensorproduct(A, B) +[[x, 2*x, 3*x, 4*x], [y, 2*y, 3*y, 4*y], [z, 2*z, 3*z, 4*z], [t, 2*t, 3*t, 4*t]] + +In case you don't want to evaluate the tensor product immediately, you can use +``ArrayTensorProduct``, which creates an unevaluated tensor product expression: + +>>> from sympy.tensor.array.expressions import ArrayTensorProduct +>>> ArrayTensorProduct(A, B) +ArrayTensorProduct([x, y, z, t], [1, 2, 3, 4]) + +Calling ``.as_explicit()`` on ``ArrayTensorProduct`` is equivalent to just calling +``tensorproduct(...)``: + +>>> ArrayTensorProduct(A, B).as_explicit() +[[x, 2*x, 3*x, 4*x], [y, 2*y, 3*y, 4*y], [z, 2*z, 3*z, 4*z], [t, 2*t, 3*t, 4*t]] + +Tensor product between a rank-1 array and a matrix creates a rank-3 array: + +>>> from sympy import eye +>>> p1 = tensorproduct(A, eye(4)) +>>> p1 +[[[x, 0, 0, 0], [0, x, 0, 0], [0, 0, x, 0], [0, 0, 0, x]], [[y, 0, 0, 0], [0, y, 0, 0], [0, 0, y, 0], [0, 0, 0, y]], [[z, 0, 0, 0], [0, z, 0, 0], [0, 0, z, 0], [0, 0, 0, z]], [[t, 0, 0, 0], [0, t, 0, 0], [0, 0, t, 0], [0, 0, 0, t]]] + +Now, to get back `A_0 \otimes \mathbf{1}` one can access `p_{0,m,n}` by slicing: + +>>> p1[0,:,:] +[[x, 0, 0, 0], [0, x, 0, 0], [0, 0, x, 0], [0, 0, 0, x]] + +Tensor contraction sums over the specified axes, for example contracting +positions `a` and `b` means + +`A_{i_1,\ldots,i_a,\ldots,i_b,\ldots,i_n} \implies \sum_k A_{i_1,\ldots,k,\ldots,k,\ldots,i_n}` + +Remember that Python indexing is zero starting, to contract the a-th and b-th +axes it is therefore necessary to specify `a-1` and `b-1` + +>>> from sympy import tensorcontraction +>>> C = Array([[x, y], [z, t]]) + +The matrix trace is equivalent to the contraction of a rank-2 array: + +`A_{m,n} \implies \sum_k A_{k,k}` + +>>> tensorcontraction(C, (0, 1)) +t + x + +To create an expression representing a tensor contraction that does not get +evaluated immediately, use ``ArrayContraction``, which is equivalent to +``tensorcontraction(...)`` if it is followed by ``.as_explicit()``: + +>>> from sympy.tensor.array.expressions import ArrayContraction +>>> ArrayContraction(C, (0, 1)) +ArrayContraction([[x, y], [z, t]], (0, 1)) +>>> ArrayContraction(C, (0, 1)).as_explicit() +t + x + +Matrix product is equivalent to a tensor product of two rank-2 arrays, followed +by a contraction of the 2nd and 3rd axes (in Python indexing axes number 1, 2). + +`A_{m,n}\cdot B_{i,j} \implies \sum_k A_{m, k}\cdot B_{k, j}` + +>>> D = Array([[2, 1], [0, -1]]) +>>> tensorcontraction(tensorproduct(C, D), (1, 2)) +[[2*x, x - y], [2*z, -t + z]] + +One may verify that the matrix product is equivalent: + +>>> from sympy import Matrix +>>> Matrix([[x, y], [z, t]])*Matrix([[2, 1], [0, -1]]) +Matrix([ +[2*x, x - y], +[2*z, -t + z]]) + +or equivalently + +>>> C.tomatrix()*D.tomatrix() +Matrix([ +[2*x, x - y], +[2*z, -t + z]]) + +Diagonal operator +----------------- + +The ``tensordiagonal`` function acts in a similar manner as ``tensorcontraction``, +but the joined indices are not summed over, for example diagonalizing +positions `a` and `b` means + +`A_{i_1,\ldots,i_a,\ldots,i_b,\ldots,i_n} \implies A_{i_1,\ldots,k,\ldots,k,\ldots,i_n} +\implies \tilde{A}_{i_1,\ldots,i_{a-1},i_{a+1},\ldots,i_{b-1},i_{b+1},\ldots,i_n,k}` + +where `\tilde{A}` is the array equivalent to the diagonal of `A` at positions +`a` and `b` moved to the last index slot. + +Compare the difference between contraction and diagonal operators: + +>>> from sympy import tensordiagonal +>>> from sympy.abc import a, b, c, d +>>> m = Matrix([[a, b], [c, d]]) +>>> tensorcontraction(m, [0, 1]) +a + d +>>> tensordiagonal(m, [0, 1]) +[a, d] + +In short, no summation occurs with ``tensordiagonal``. + + +Derivatives by array +-------------------- + +The usual derivative operation may be extended to support derivation with +respect to arrays, provided that all elements in the that array are symbols or +expressions suitable for derivations. + +The definition of a derivative by an array is as follows: given the array +`A_{i_1, \ldots, i_N}` and the array `X_{j_1, \ldots, j_M}` +the derivative of arrays will return a new array `B` defined by + +`B_{j_1,\ldots,j_M,i_1,\ldots,i_N} := \frac{\partial A_{i_1,\ldots,i_N}}{\partial X_{j_1,\ldots,j_M}}` + +The function ``derive_by_array`` performs such an operation: + +>>> from sympy import derive_by_array +>>> from sympy.abc import x, y, z, t +>>> from sympy import sin, exp + +With scalars, it behaves exactly as the ordinary derivative: + +>>> derive_by_array(sin(x*y), x) +y*cos(x*y) + +Scalar derived by an array basis: + +>>> derive_by_array(sin(x*y), [x, y, z]) +[y*cos(x*y), x*cos(x*y), 0] + +Deriving array by an array basis: `B^{nm} := \frac{\partial A^m}{\partial x^n}` + +>>> basis = [x, y, z] +>>> ax = derive_by_array([exp(x), sin(y*z), t], basis) +>>> ax +[[exp(x), 0, 0], [0, z*cos(y*z), 0], [0, y*cos(y*z), 0]] + +Contraction of the resulting array: `\sum_m \frac{\partial A^m}{\partial x^m}` + +>>> tensorcontraction(ax, (0, 1)) +z*cos(y*z) + exp(x) + +""" + +from .dense_ndim_array import MutableDenseNDimArray, ImmutableDenseNDimArray, DenseNDimArray +from .sparse_ndim_array import MutableSparseNDimArray, ImmutableSparseNDimArray, SparseNDimArray +from .ndim_array import NDimArray, ArrayKind +from .arrayop import tensorproduct, tensorcontraction, tensordiagonal, derive_by_array, permutedims +from .array_comprehension import ArrayComprehension, ArrayComprehensionMap + +Array = ImmutableDenseNDimArray + +__all__ = [ + 'MutableDenseNDimArray', 'ImmutableDenseNDimArray', 'DenseNDimArray', + + 'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'SparseNDimArray', + + 'NDimArray', 'ArrayKind', + + 'tensorproduct', 'tensorcontraction', 'tensordiagonal', 'derive_by_array', + + 'permutedims', 'ArrayComprehension', 'ArrayComprehensionMap', + + 'Array', +] diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a407c01e50e66d374f966a57684f4504431d4ed Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/array_comprehension.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/array_comprehension.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eeb9363ce521efb0a0ceacacd1fd7c767dc2248e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/array_comprehension.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/array_derivatives.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/array_derivatives.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..272feca1c1077acd7c55329ed09e0e4527e21fb4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/array_derivatives.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/arrayop.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/arrayop.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..487671d3f03a3b46e639fe85b8c96ad0730caacf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/arrayop.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/dense_ndim_array.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/dense_ndim_array.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6d5f4d7173ef9e81756cd54214d80ef78350956 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/dense_ndim_array.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/mutable_ndim_array.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/mutable_ndim_array.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2719434e4f80c953a584be7051b2619ce8688f0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/mutable_ndim_array.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/ndim_array.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/ndim_array.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d59552a32232fba09c246c7679f2fed7af60cba4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/ndim_array.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/sparse_ndim_array.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/sparse_ndim_array.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c870c24c3a259fd268d7d07c79e598665c1d60d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/__pycache__/sparse_ndim_array.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/array_comprehension.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/array_comprehension.py new file mode 100644 index 0000000000000000000000000000000000000000..95702f499f3e40597fd0144929138ac1329962ee --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/array_comprehension.py @@ -0,0 +1,399 @@ +import functools, itertools +from sympy.core.sympify import _sympify, sympify +from sympy.core.expr import Expr +from sympy.core import Basic, Tuple +from sympy.tensor.array import ImmutableDenseNDimArray +from sympy.core.symbol import Symbol +from sympy.core.numbers import Integer + + +class ArrayComprehension(Basic): + """ + Generate a list comprehension. + + Explanation + =========== + + If there is a symbolic dimension, for example, say [i for i in range(1, N)] where + N is a Symbol, then the expression will not be expanded to an array. Otherwise, + calling the doit() function will launch the expansion. + + Examples + ======== + + >>> from sympy.tensor.array import ArrayComprehension + >>> from sympy import symbols + >>> i, j, k = symbols('i j k') + >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3)) + >>> a + ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3)) + >>> a.doit() + [[11, 12, 13], [21, 22, 23], [31, 32, 33], [41, 42, 43]] + >>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k)) + >>> b.doit() + ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k)) + """ + def __new__(cls, function, *symbols, **assumptions): + if any(len(l) != 3 or None for l in symbols): + raise ValueError('ArrayComprehension requires values lower and upper bound' + ' for the expression') + arglist = [sympify(function)] + arglist.extend(cls._check_limits_validity(function, symbols)) + obj = Basic.__new__(cls, *arglist, **assumptions) + obj._limits = obj._args[1:] + obj._shape = cls._calculate_shape_from_limits(obj._limits) + obj._rank = len(obj._shape) + obj._loop_size = cls._calculate_loop_size(obj._shape) + return obj + + @property + def function(self): + """The function applied across limits. + + Examples + ======== + + >>> from sympy.tensor.array import ArrayComprehension + >>> from sympy import symbols + >>> i, j = symbols('i j') + >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3)) + >>> a.function + 10*i + j + """ + return self._args[0] + + @property + def limits(self): + """ + The list of limits that will be applied while expanding the array. + + Examples + ======== + + >>> from sympy.tensor.array import ArrayComprehension + >>> from sympy import symbols + >>> i, j = symbols('i j') + >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3)) + >>> a.limits + ((i, 1, 4), (j, 1, 3)) + """ + return self._limits + + @property + def free_symbols(self): + """ + The set of the free_symbols in the array. + Variables appeared in the bounds are supposed to be excluded + from the free symbol set. + + Examples + ======== + + >>> from sympy.tensor.array import ArrayComprehension + >>> from sympy import symbols + >>> i, j, k = symbols('i j k') + >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3)) + >>> a.free_symbols + set() + >>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k+3)) + >>> b.free_symbols + {k} + """ + expr_free_sym = self.function.free_symbols + for var, inf, sup in self._limits: + expr_free_sym.discard(var) + curr_free_syms = inf.free_symbols.union(sup.free_symbols) + expr_free_sym = expr_free_sym.union(curr_free_syms) + return expr_free_sym + + @property + def variables(self): + """The tuples of the variables in the limits. + + Examples + ======== + + >>> from sympy.tensor.array import ArrayComprehension + >>> from sympy import symbols + >>> i, j, k = symbols('i j k') + >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3)) + >>> a.variables + [i, j] + """ + return [l[0] for l in self._limits] + + @property + def bound_symbols(self): + """The list of dummy variables. + + Note + ==== + + Note that all variables are dummy variables since a limit without + lower bound or upper bound is not accepted. + """ + return [l[0] for l in self._limits if len(l) != 1] + + @property + def shape(self): + """ + The shape of the expanded array, which may have symbols. + + Note + ==== + + Both the lower and the upper bounds are included while + calculating the shape. + + Examples + ======== + + >>> from sympy.tensor.array import ArrayComprehension + >>> from sympy import symbols + >>> i, j, k = symbols('i j k') + >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3)) + >>> a.shape + (4, 3) + >>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k+3)) + >>> b.shape + (4, k + 3) + """ + return self._shape + + @property + def is_shape_numeric(self): + """ + Test if the array is shape-numeric which means there is no symbolic + dimension. + + Examples + ======== + + >>> from sympy.tensor.array import ArrayComprehension + >>> from sympy import symbols + >>> i, j, k = symbols('i j k') + >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3)) + >>> a.is_shape_numeric + True + >>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k+3)) + >>> b.is_shape_numeric + False + """ + for _, inf, sup in self._limits: + if Basic(inf, sup).atoms(Symbol): + return False + return True + + def rank(self): + """The rank of the expanded array. + + Examples + ======== + + >>> from sympy.tensor.array import ArrayComprehension + >>> from sympy import symbols + >>> i, j, k = symbols('i j k') + >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3)) + >>> a.rank() + 2 + """ + return self._rank + + def __len__(self): + """ + The length of the expanded array which means the number + of elements in the array. + + Raises + ====== + + ValueError : When the length of the array is symbolic + + Examples + ======== + + >>> from sympy.tensor.array import ArrayComprehension + >>> from sympy import symbols + >>> i, j = symbols('i j') + >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3)) + >>> len(a) + 12 + """ + if self._loop_size.free_symbols: + raise ValueError('Symbolic length is not supported') + return self._loop_size + + @classmethod + def _check_limits_validity(cls, function, limits): + #limits = sympify(limits) + new_limits = [] + for var, inf, sup in limits: + var = _sympify(var) + inf = _sympify(inf) + #since this is stored as an argument, it should be + #a Tuple + if isinstance(sup, list): + sup = Tuple(*sup) + else: + sup = _sympify(sup) + new_limits.append(Tuple(var, inf, sup)) + if any((not isinstance(i, Expr)) or i.atoms(Symbol, Integer) != i.atoms() + for i in [inf, sup]): + raise TypeError('Bounds should be an Expression(combination of Integer and Symbol)') + if (inf > sup) == True: + raise ValueError('Lower bound should be inferior to upper bound') + if var in inf.free_symbols or var in sup.free_symbols: + raise ValueError('Variable should not be part of its bounds') + return new_limits + + @classmethod + def _calculate_shape_from_limits(cls, limits): + return tuple([sup - inf + 1 for _, inf, sup in limits]) + + @classmethod + def _calculate_loop_size(cls, shape): + if not shape: + return 0 + loop_size = 1 + for l in shape: + loop_size = loop_size * l + + return loop_size + + def doit(self, **hints): + if not self.is_shape_numeric: + return self + + return self._expand_array() + + def _expand_array(self): + res = [] + for values in itertools.product(*[range(inf, sup+1) + for var, inf, sup + in self._limits]): + res.append(self._get_element(values)) + + return ImmutableDenseNDimArray(res, self.shape) + + def _get_element(self, values): + temp = self.function + for var, val in zip(self.variables, values): + temp = temp.subs(var, val) + return temp + + def tolist(self): + """Transform the expanded array to a list. + + Raises + ====== + + ValueError : When there is a symbolic dimension + + Examples + ======== + + >>> from sympy.tensor.array import ArrayComprehension + >>> from sympy import symbols + >>> i, j = symbols('i j') + >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3)) + >>> a.tolist() + [[11, 12, 13], [21, 22, 23], [31, 32, 33], [41, 42, 43]] + """ + if self.is_shape_numeric: + return self._expand_array().tolist() + + raise ValueError("A symbolic array cannot be expanded to a list") + + def tomatrix(self): + """Transform the expanded array to a matrix. + + Raises + ====== + + ValueError : When there is a symbolic dimension + ValueError : When the rank of the expanded array is not equal to 2 + + Examples + ======== + + >>> from sympy.tensor.array import ArrayComprehension + >>> from sympy import symbols + >>> i, j = symbols('i j') + >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3)) + >>> a.tomatrix() + Matrix([ + [11, 12, 13], + [21, 22, 23], + [31, 32, 33], + [41, 42, 43]]) + """ + from sympy.matrices import Matrix + + if not self.is_shape_numeric: + raise ValueError("A symbolic array cannot be expanded to a matrix") + if self._rank != 2: + raise ValueError('Dimensions must be of size of 2') + + return Matrix(self._expand_array().tomatrix()) + + +def isLambda(v): + LAMBDA = lambda: 0 + return isinstance(v, type(LAMBDA)) and v.__name__ == LAMBDA.__name__ + +class ArrayComprehensionMap(ArrayComprehension): + ''' + A subclass of ArrayComprehension dedicated to map external function lambda. + + Notes + ===== + + Only the lambda function is considered. + At most one argument in lambda function is accepted in order to avoid ambiguity + in value assignment. + + Examples + ======== + + >>> from sympy.tensor.array import ArrayComprehensionMap + >>> from sympy import symbols + >>> i, j, k = symbols('i j k') + >>> a = ArrayComprehensionMap(lambda: 1, (i, 1, 4)) + >>> a.doit() + [1, 1, 1, 1] + >>> b = ArrayComprehensionMap(lambda a: a+1, (j, 1, 4)) + >>> b.doit() + [2, 3, 4, 5] + + ''' + def __new__(cls, function, *symbols, **assumptions): + if any(len(l) != 3 or None for l in symbols): + raise ValueError('ArrayComprehension requires values lower and upper bound' + ' for the expression') + + if not isLambda(function): + raise ValueError('Data type not supported') + + arglist = cls._check_limits_validity(function, symbols) + obj = Basic.__new__(cls, *arglist, **assumptions) + obj._limits = obj._args + obj._shape = cls._calculate_shape_from_limits(obj._limits) + obj._rank = len(obj._shape) + obj._loop_size = cls._calculate_loop_size(obj._shape) + obj._lambda = function + return obj + + @property + def func(self): + class _(ArrayComprehensionMap): + def __new__(cls, *args, **kwargs): + return ArrayComprehensionMap(self._lambda, *args, **kwargs) + return _ + + def _get_element(self, values): + temp = self._lambda + if self._lambda.__code__.co_argcount == 0: + temp = temp() + elif self._lambda.__code__.co_argcount == 1: + temp = temp(functools.reduce(lambda a, b: a*b, values)) + return temp diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/array_derivatives.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/array_derivatives.py new file mode 100644 index 0000000000000000000000000000000000000000..a38db6caefe256a8c7e1f3415b78351b3787fee9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/array_derivatives.py @@ -0,0 +1,129 @@ +from __future__ import annotations + +from sympy.core.expr import Expr +from sympy.core.function import Derivative +from sympy.core.numbers import Integer +from sympy.matrices.matrixbase import MatrixBase +from .ndim_array import NDimArray +from .arrayop import derive_by_array +from sympy.matrices.expressions.matexpr import MatrixExpr +from sympy.matrices.expressions.special import ZeroMatrix +from sympy.matrices.expressions.matexpr import _matrix_derivative + + +class ArrayDerivative(Derivative): + + is_scalar = False + + def __new__(cls, expr, *variables, **kwargs): + obj = super().__new__(cls, expr, *variables, **kwargs) + if isinstance(obj, ArrayDerivative): + obj._shape = obj._get_shape() + return obj + + def _get_shape(self): + shape = () + for v, count in self.variable_count: + if hasattr(v, "shape"): + for i in range(count): + shape += v.shape + if hasattr(self.expr, "shape"): + shape += self.expr.shape + return shape + + @property + def shape(self): + return self._shape + + @classmethod + def _get_zero_with_shape_like(cls, expr): + if isinstance(expr, (MatrixBase, NDimArray)): + return expr.zeros(*expr.shape) + elif isinstance(expr, MatrixExpr): + return ZeroMatrix(*expr.shape) + else: + raise RuntimeError("Unable to determine shape of array-derivative.") + + @staticmethod + def _call_derive_scalar_by_matrix(expr: Expr, v: MatrixBase) -> Expr: + return v.applyfunc(lambda x: expr.diff(x)) + + @staticmethod + def _call_derive_scalar_by_matexpr(expr: Expr, v: MatrixExpr) -> Expr: + if expr.has(v): + return _matrix_derivative(expr, v) + else: + return ZeroMatrix(*v.shape) + + @staticmethod + def _call_derive_scalar_by_array(expr: Expr, v: NDimArray) -> Expr: + return v.applyfunc(lambda x: expr.diff(x)) + + @staticmethod + def _call_derive_matrix_by_scalar(expr: MatrixBase, v: Expr) -> Expr: + return _matrix_derivative(expr, v) + + @staticmethod + def _call_derive_matexpr_by_scalar(expr: MatrixExpr, v: Expr) -> Expr: + return expr._eval_derivative(v) + + @staticmethod + def _call_derive_array_by_scalar(expr: NDimArray, v: Expr) -> Expr: + return expr.applyfunc(lambda x: x.diff(v)) + + @staticmethod + def _call_derive_default(expr: Expr, v: Expr) -> Expr | None: + if expr.has(v): + return _matrix_derivative(expr, v) + else: + return None + + @classmethod + def _dispatch_eval_derivative_n_times(cls, expr, v, count): + # Evaluate the derivative `n` times. If + # `_eval_derivative_n_times` is not overridden by the current + # object, the default in `Basic` will call a loop over + # `_eval_derivative`: + + if not isinstance(count, (int, Integer)) or ((count <= 0) == True): + return None + + # TODO: this could be done with multiple-dispatching: + if expr.is_scalar: + if isinstance(v, MatrixBase): + result = cls._call_derive_scalar_by_matrix(expr, v) + elif isinstance(v, MatrixExpr): + result = cls._call_derive_scalar_by_matexpr(expr, v) + elif isinstance(v, NDimArray): + result = cls._call_derive_scalar_by_array(expr, v) + elif v.is_scalar: + # scalar by scalar has a special + return super()._dispatch_eval_derivative_n_times(expr, v, count) + else: + return None + elif v.is_scalar: + if isinstance(expr, MatrixBase): + result = cls._call_derive_matrix_by_scalar(expr, v) + elif isinstance(expr, MatrixExpr): + result = cls._call_derive_matexpr_by_scalar(expr, v) + elif isinstance(expr, NDimArray): + result = cls._call_derive_array_by_scalar(expr, v) + else: + return None + else: + # Both `expr` and `v` are some array/matrix type: + if isinstance(expr, MatrixBase) or isinstance(v, MatrixBase): + result = derive_by_array(expr, v) + elif isinstance(expr, MatrixExpr) and isinstance(v, MatrixExpr): + result = cls._call_derive_default(expr, v) + elif isinstance(expr, MatrixExpr) or isinstance(v, MatrixExpr): + # if one expression is a symbolic matrix expression while the other isn't, don't evaluate: + return None + else: + result = derive_by_array(expr, v) + if result is None: + return None + if count == 1: + return result + else: + return cls._dispatch_eval_derivative_n_times(result, v, count - 1) diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/arrayop.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/arrayop.py new file mode 100644 index 0000000000000000000000000000000000000000..a81e6b381a8a93f0cd585278a4be0259b06406dd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/arrayop.py @@ -0,0 +1,528 @@ +import itertools +from collections.abc import Iterable + +from sympy.core._print_helpers import Printable +from sympy.core.containers import Tuple +from sympy.core.function import diff +from sympy.core.singleton import S +from sympy.core.sympify import _sympify + +from sympy.tensor.array.ndim_array import NDimArray +from sympy.tensor.array.dense_ndim_array import DenseNDimArray, ImmutableDenseNDimArray +from sympy.tensor.array.sparse_ndim_array import SparseNDimArray + + +def _arrayfy(a): + from sympy.matrices import MatrixBase + + if isinstance(a, NDimArray): + return a + if isinstance(a, (MatrixBase, list, tuple, Tuple)): + return ImmutableDenseNDimArray(a) + return a + + +def tensorproduct(*args): + """ + Tensor product among scalars or array-like objects. + + The equivalent operator for array expressions is ``ArrayTensorProduct``, + which can be used to keep the expression unevaluated. + + Examples + ======== + + >>> from sympy.tensor.array import tensorproduct, Array + >>> from sympy.abc import x, y, z, t + >>> A = Array([[1, 2], [3, 4]]) + >>> B = Array([x, y]) + >>> tensorproduct(A, B) + [[[x, y], [2*x, 2*y]], [[3*x, 3*y], [4*x, 4*y]]] + >>> tensorproduct(A, x) + [[x, 2*x], [3*x, 4*x]] + >>> tensorproduct(A, B, B) + [[[[x**2, x*y], [x*y, y**2]], [[2*x**2, 2*x*y], [2*x*y, 2*y**2]]], [[[3*x**2, 3*x*y], [3*x*y, 3*y**2]], [[4*x**2, 4*x*y], [4*x*y, 4*y**2]]]] + + Applying this function on two matrices will result in a rank 4 array. + + >>> from sympy import Matrix, eye + >>> m = Matrix([[x, y], [z, t]]) + >>> p = tensorproduct(eye(3), m) + >>> p + [[[[x, y], [z, t]], [[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[x, y], [z, t]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, 0], [0, 0]], [[x, y], [z, t]]]] + + See Also + ======== + + sympy.tensor.array.expressions.array_expressions.ArrayTensorProduct + + """ + from sympy.tensor.array import SparseNDimArray, ImmutableSparseNDimArray + + if len(args) == 0: + return S.One + if len(args) == 1: + return _arrayfy(args[0]) + from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract + from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct + from sympy.tensor.array.expressions.array_expressions import _ArrayExpr + from sympy.matrices.expressions.matexpr import MatrixSymbol + if any(isinstance(arg, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)) for arg in args): + return ArrayTensorProduct(*args) + if len(args) > 2: + return tensorproduct(tensorproduct(args[0], args[1]), *args[2:]) + + # length of args is 2: + a, b = map(_arrayfy, args) + + if not isinstance(a, NDimArray) or not isinstance(b, NDimArray): + return a*b + + if isinstance(a, SparseNDimArray) and isinstance(b, SparseNDimArray): + lp = len(b) + new_array = {k1*lp + k2: v1*v2 for k1, v1 in a._sparse_array.items() for k2, v2 in b._sparse_array.items()} + return ImmutableSparseNDimArray(new_array, a.shape + b.shape) + + product_list = [i*j for i in Flatten(a) for j in Flatten(b)] + return ImmutableDenseNDimArray(product_list, a.shape + b.shape) + + +def _util_contraction_diagonal(array, *contraction_or_diagonal_axes): + array = _arrayfy(array) + + # Verify contraction_axes: + taken_dims = set() + for axes_group in contraction_or_diagonal_axes: + if not isinstance(axes_group, Iterable): + raise ValueError("collections of contraction/diagonal axes expected") + + dim = array.shape[axes_group[0]] + + for d in axes_group: + if d in taken_dims: + raise ValueError("dimension specified more than once") + if dim != array.shape[d]: + raise ValueError("cannot contract or diagonalize between axes of different dimension") + taken_dims.add(d) + + rank = array.rank() + + remaining_shape = [dim for i, dim in enumerate(array.shape) if i not in taken_dims] + cum_shape = [0]*rank + _cumul = 1 + for i in range(rank): + cum_shape[rank - i - 1] = _cumul + _cumul *= int(array.shape[rank - i - 1]) + + # DEFINITION: by absolute position it is meant the position along the one + # dimensional array containing all the tensor components. + + # Possible future work on this module: move computation of absolute + # positions to a class method. + + # Determine absolute positions of the uncontracted indices: + remaining_indices = [[cum_shape[i]*j for j in range(array.shape[i])] + for i in range(rank) if i not in taken_dims] + + # Determine absolute positions of the contracted indices: + summed_deltas = [] + for axes_group in contraction_or_diagonal_axes: + lidx = [] + for js in range(array.shape[axes_group[0]]): + lidx.append(sum(cum_shape[ig] * js for ig in axes_group)) + summed_deltas.append(lidx) + + return array, remaining_indices, remaining_shape, summed_deltas + + +def tensorcontraction(array, *contraction_axes): + """ + Contraction of an array-like object on the specified axes. + + The equivalent operator for array expressions is ``ArrayContraction``, + which can be used to keep the expression unevaluated. + + Examples + ======== + + >>> from sympy import Array, tensorcontraction + >>> from sympy import Matrix, eye + >>> tensorcontraction(eye(3), (0, 1)) + 3 + >>> A = Array(range(18), (3, 2, 3)) + >>> A + [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]], [[12, 13, 14], [15, 16, 17]]] + >>> tensorcontraction(A, (0, 2)) + [21, 30] + + Matrix multiplication may be emulated with a proper combination of + ``tensorcontraction`` and ``tensorproduct`` + + >>> from sympy import tensorproduct + >>> from sympy.abc import a,b,c,d,e,f,g,h + >>> m1 = Matrix([[a, b], [c, d]]) + >>> m2 = Matrix([[e, f], [g, h]]) + >>> p = tensorproduct(m1, m2) + >>> p + [[[[a*e, a*f], [a*g, a*h]], [[b*e, b*f], [b*g, b*h]]], [[[c*e, c*f], [c*g, c*h]], [[d*e, d*f], [d*g, d*h]]]] + >>> tensorcontraction(p, (1, 2)) + [[a*e + b*g, a*f + b*h], [c*e + d*g, c*f + d*h]] + >>> m1*m2 + Matrix([ + [a*e + b*g, a*f + b*h], + [c*e + d*g, c*f + d*h]]) + + See Also + ======== + + sympy.tensor.array.expressions.array_expressions.ArrayContraction + + """ + from sympy.tensor.array.expressions.array_expressions import _array_contraction + from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract + from sympy.tensor.array.expressions.array_expressions import _ArrayExpr + from sympy.matrices.expressions.matexpr import MatrixSymbol + if isinstance(array, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)): + return _array_contraction(array, *contraction_axes) + + array, remaining_indices, remaining_shape, summed_deltas = _util_contraction_diagonal(array, *contraction_axes) + + # Compute the contracted array: + # + # 1. external for loops on all uncontracted indices. + # Uncontracted indices are determined by the combinatorial product of + # the absolute positions of the remaining indices. + # 2. internal loop on all contracted indices. + # It sums the values of the absolute contracted index and the absolute + # uncontracted index for the external loop. + contracted_array = [] + for icontrib in itertools.product(*remaining_indices): + index_base_position = sum(icontrib) + isum = S.Zero + for sum_to_index in itertools.product(*summed_deltas): + idx = array._get_tuple_index(index_base_position + sum(sum_to_index)) + isum += array[idx] + + contracted_array.append(isum) + + if len(remaining_indices) == 0: + assert len(contracted_array) == 1 + return contracted_array[0] + + return type(array)(contracted_array, remaining_shape) + + +def tensordiagonal(array, *diagonal_axes): + """ + Diagonalization of an array-like object on the specified axes. + + This is equivalent to multiplying the expression by Kronecker deltas + uniting the axes. + + The diagonal indices are put at the end of the axes. + + The equivalent operator for array expressions is ``ArrayDiagonal``, which + can be used to keep the expression unevaluated. + + Examples + ======== + + ``tensordiagonal`` acting on a 2-dimensional array by axes 0 and 1 is + equivalent to the diagonal of the matrix: + + >>> from sympy import Array, tensordiagonal + >>> from sympy import Matrix, eye + >>> tensordiagonal(eye(3), (0, 1)) + [1, 1, 1] + + >>> from sympy.abc import a,b,c,d + >>> m1 = Matrix([[a, b], [c, d]]) + >>> tensordiagonal(m1, [0, 1]) + [a, d] + + In case of higher dimensional arrays, the diagonalized out dimensions + are appended removed and appended as a single dimension at the end: + + >>> A = Array(range(18), (3, 2, 3)) + >>> A + [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]], [[12, 13, 14], [15, 16, 17]]] + >>> tensordiagonal(A, (0, 2)) + [[0, 7, 14], [3, 10, 17]] + >>> from sympy import permutedims + >>> tensordiagonal(A, (0, 2)) == permutedims(Array([A[0, :, 0], A[1, :, 1], A[2, :, 2]]), [1, 0]) + True + + See Also + ======== + + sympy.tensor.array.expressions.array_expressions.ArrayDiagonal + + """ + if any(len(i) <= 1 for i in diagonal_axes): + raise ValueError("need at least two axes to diagonalize") + + from sympy.tensor.array.expressions.array_expressions import _ArrayExpr + from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract + from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal, _array_diagonal + from sympy.matrices.expressions.matexpr import MatrixSymbol + if isinstance(array, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)): + return _array_diagonal(array, *diagonal_axes) + + ArrayDiagonal._validate(array, *diagonal_axes) + + array, remaining_indices, remaining_shape, diagonal_deltas = _util_contraction_diagonal(array, *diagonal_axes) + + # Compute the diagonalized array: + # + # 1. external for loops on all undiagonalized indices. + # Undiagonalized indices are determined by the combinatorial product of + # the absolute positions of the remaining indices. + # 2. internal loop on all diagonal indices. + # It appends the values of the absolute diagonalized index and the absolute + # undiagonalized index for the external loop. + diagonalized_array = [] + diagonal_shape = [len(i) for i in diagonal_deltas] + for icontrib in itertools.product(*remaining_indices): + index_base_position = sum(icontrib) + isum = [] + for sum_to_index in itertools.product(*diagonal_deltas): + idx = array._get_tuple_index(index_base_position + sum(sum_to_index)) + isum.append(array[idx]) + + isum = type(array)(isum).reshape(*diagonal_shape) + diagonalized_array.append(isum) + + return type(array)(diagonalized_array, remaining_shape + diagonal_shape) + + +def derive_by_array(expr, dx): + r""" + Derivative by arrays. Supports both arrays and scalars. + + The equivalent operator for array expressions is ``array_derive``. + + Explanation + =========== + + Given the array `A_{i_1, \ldots, i_N}` and the array `X_{j_1, \ldots, j_M}` + this function will return a new array `B` defined by + + `B_{j_1,\ldots,j_M,i_1,\ldots,i_N} := \frac{\partial A_{i_1,\ldots,i_N}}{\partial X_{j_1,\ldots,j_M}}` + + Examples + ======== + + >>> from sympy import derive_by_array + >>> from sympy.abc import x, y, z, t + >>> from sympy import cos + >>> derive_by_array(cos(x*t), x) + -t*sin(t*x) + >>> derive_by_array(cos(x*t), [x, y, z, t]) + [-t*sin(t*x), 0, 0, -x*sin(t*x)] + >>> derive_by_array([x, y**2*z], [[x, y], [z, t]]) + [[[1, 0], [0, 2*y*z]], [[0, y**2], [0, 0]]] + + """ + from sympy.matrices import MatrixBase + from sympy.tensor.array import SparseNDimArray + array_types = (Iterable, MatrixBase, NDimArray) + + if isinstance(dx, array_types): + dx = ImmutableDenseNDimArray(dx) + for i in dx: + if not i._diff_wrt: + raise ValueError("cannot derive by this array") + + if isinstance(expr, array_types): + if isinstance(expr, NDimArray): + expr = expr.as_immutable() + else: + expr = ImmutableDenseNDimArray(expr) + + if isinstance(dx, array_types): + if isinstance(expr, SparseNDimArray): + lp = len(expr) + new_array = {k + i*lp: v + for i, x in enumerate(Flatten(dx)) + for k, v in expr.diff(x)._sparse_array.items()} + else: + new_array = [[y.diff(x) for y in Flatten(expr)] for x in Flatten(dx)] + return type(expr)(new_array, dx.shape + expr.shape) + else: + return expr.diff(dx) + else: + expr = _sympify(expr) + if isinstance(dx, array_types): + return ImmutableDenseNDimArray([expr.diff(i) for i in Flatten(dx)], dx.shape) + else: + dx = _sympify(dx) + return diff(expr, dx) + + +def permutedims(expr, perm=None, index_order_old=None, index_order_new=None): + """ + Permutes the indices of an array. + + Parameter specifies the permutation of the indices. + + The equivalent operator for array expressions is ``PermuteDims``, which can + be used to keep the expression unevaluated. + + Examples + ======== + + >>> from sympy.abc import x, y, z, t + >>> from sympy import sin + >>> from sympy import Array, permutedims + >>> a = Array([[x, y, z], [t, sin(x), 0]]) + >>> a + [[x, y, z], [t, sin(x), 0]] + >>> permutedims(a, (1, 0)) + [[x, t], [y, sin(x)], [z, 0]] + + If the array is of second order, ``transpose`` can be used: + + >>> from sympy import transpose + >>> transpose(a) + [[x, t], [y, sin(x)], [z, 0]] + + Examples on higher dimensions: + + >>> b = Array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) + >>> permutedims(b, (2, 1, 0)) + [[[1, 5], [3, 7]], [[2, 6], [4, 8]]] + >>> permutedims(b, (1, 2, 0)) + [[[1, 5], [2, 6]], [[3, 7], [4, 8]]] + + An alternative way to specify the same permutations as in the previous + lines involves passing the *old* and *new* indices, either as a list or as + a string: + + >>> permutedims(b, index_order_old="cba", index_order_new="abc") + [[[1, 5], [3, 7]], [[2, 6], [4, 8]]] + >>> permutedims(b, index_order_old="cab", index_order_new="abc") + [[[1, 5], [2, 6]], [[3, 7], [4, 8]]] + + ``Permutation`` objects are also allowed: + + >>> from sympy.combinatorics import Permutation + >>> permutedims(b, Permutation([1, 2, 0])) + [[[1, 5], [2, 6]], [[3, 7], [4, 8]]] + + See Also + ======== + + sympy.tensor.array.expressions.array_expressions.PermuteDims + + """ + from sympy.tensor.array import SparseNDimArray + + from sympy.tensor.array.expressions.array_expressions import _ArrayExpr + from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract + from sympy.tensor.array.expressions.array_expressions import _permute_dims + from sympy.matrices.expressions.matexpr import MatrixSymbol + from sympy.tensor.array.expressions import PermuteDims + from sympy.tensor.array.expressions.array_expressions import get_rank + perm = PermuteDims._get_permutation_from_arguments(perm, index_order_old, index_order_new, get_rank(expr)) + if isinstance(expr, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)): + return _permute_dims(expr, perm) + + if not isinstance(expr, NDimArray): + expr = ImmutableDenseNDimArray(expr) + + from sympy.combinatorics import Permutation + if not isinstance(perm, Permutation): + perm = Permutation(list(perm)) + + if perm.size != expr.rank(): + raise ValueError("wrong permutation size") + + # Get the inverse permutation: + iperm = ~perm + new_shape = perm(expr.shape) + + if isinstance(expr, SparseNDimArray): + return type(expr)({tuple(perm(expr._get_tuple_index(k))): v + for k, v in expr._sparse_array.items()}, new_shape) + + indices_span = perm([range(i) for i in expr.shape]) + + new_array = [None]*len(expr) + for i, idx in enumerate(itertools.product(*indices_span)): + t = iperm(idx) + new_array[i] = expr[t] + + return type(expr)(new_array, new_shape) + + +class Flatten(Printable): + """ + Flatten an iterable object to a list in a lazy-evaluation way. + + Notes + ===== + + This class is an iterator with which the memory cost can be economised. + Optimisation has been considered to ameliorate the performance for some + specific data types like DenseNDimArray and SparseNDimArray. + + Examples + ======== + + >>> from sympy.tensor.array.arrayop import Flatten + >>> from sympy.tensor.array import Array + >>> A = Array(range(6)).reshape(2, 3) + >>> Flatten(A) + Flatten([[0, 1, 2], [3, 4, 5]]) + >>> [i for i in Flatten(A)] + [0, 1, 2, 3, 4, 5] + """ + def __init__(self, iterable): + from sympy.matrices.matrixbase import MatrixBase + from sympy.tensor.array import NDimArray + + if not isinstance(iterable, (Iterable, MatrixBase)): + raise NotImplementedError("Data type not yet supported") + + if isinstance(iterable, list): + iterable = NDimArray(iterable) + + self._iter = iterable + self._idx = 0 + + def __iter__(self): + return self + + def __next__(self): + from sympy.matrices.matrixbase import MatrixBase + + if len(self._iter) > self._idx: + if isinstance(self._iter, DenseNDimArray): + result = self._iter._array[self._idx] + + elif isinstance(self._iter, SparseNDimArray): + if self._idx in self._iter._sparse_array: + result = self._iter._sparse_array[self._idx] + else: + result = 0 + + elif isinstance(self._iter, MatrixBase): + result = self._iter[self._idx] + + elif hasattr(self._iter, '__next__'): + result = next(self._iter) + + else: + result = self._iter[self._idx] + + else: + raise StopIteration + + self._idx += 1 + return result + + def next(self): + return self.__next__() + + def _sympystr(self, printer): + return type(self).__name__ + '(' + printer._print(self._iter) + ')' diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/dense_ndim_array.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/dense_ndim_array.py new file mode 100644 index 0000000000000000000000000000000000000000..576e452c55d8d374ca1f72c553f3a64de7227d43 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/dense_ndim_array.py @@ -0,0 +1,206 @@ +import functools +from typing import List + +from sympy.core.basic import Basic +from sympy.core.containers import Tuple +from sympy.core.singleton import S +from sympy.core.sympify import _sympify +from sympy.tensor.array.mutable_ndim_array import MutableNDimArray +from sympy.tensor.array.ndim_array import NDimArray, ImmutableNDimArray, ArrayKind +from sympy.utilities.iterables import flatten + + +class DenseNDimArray(NDimArray): + + _array: List[Basic] + + def __new__(self, *args, **kwargs): + return ImmutableDenseNDimArray(*args, **kwargs) + + @property + def kind(self) -> ArrayKind: + return ArrayKind._union(self._array) + + def __getitem__(self, index): + """ + Allows to get items from N-dim array. + + Examples + ======== + + >>> from sympy import MutableDenseNDimArray + >>> a = MutableDenseNDimArray([0, 1, 2, 3], (2, 2)) + >>> a + [[0, 1], [2, 3]] + >>> a[0, 0] + 0 + >>> a[1, 1] + 3 + >>> a[0] + [0, 1] + >>> a[1] + [2, 3] + + + Symbolic index: + + >>> from sympy.abc import i, j + >>> a[i, j] + [[0, 1], [2, 3]][i, j] + + Replace `i` and `j` to get element `(1, 1)`: + + >>> a[i, j].subs({i: 1, j: 1}) + 3 + + """ + syindex = self._check_symbolic_index(index) + if syindex is not None: + return syindex + + index = self._check_index_for_getitem(index) + + if isinstance(index, tuple) and any(isinstance(i, slice) for i in index): + sl_factors, eindices = self._get_slice_data_for_array_access(index) + array = [self._array[self._parse_index(i)] for i in eindices] + nshape = [len(el) for i, el in enumerate(sl_factors) if isinstance(index[i], slice)] + return type(self)(array, nshape) + else: + index = self._parse_index(index) + return self._array[index] + + @classmethod + def zeros(cls, *shape): + list_length = functools.reduce(lambda x, y: x*y, shape, S.One) + return cls._new(([0]*list_length,), shape) + + def tomatrix(self): + """ + Converts MutableDenseNDimArray to Matrix. Can convert only 2-dim array, else will raise error. + + Examples + ======== + + >>> from sympy import MutableDenseNDimArray + >>> a = MutableDenseNDimArray([1 for i in range(9)], (3, 3)) + >>> b = a.tomatrix() + >>> b + Matrix([ + [1, 1, 1], + [1, 1, 1], + [1, 1, 1]]) + + """ + from sympy.matrices import Matrix + + if self.rank() != 2: + raise ValueError('Dimensions must be of size of 2') + + return Matrix(self.shape[0], self.shape[1], self._array) + + def reshape(self, *newshape): + """ + Returns MutableDenseNDimArray instance with new shape. Elements number + must be suitable to new shape. The only argument of method sets + new shape. + + Examples + ======== + + >>> from sympy import MutableDenseNDimArray + >>> a = MutableDenseNDimArray([1, 2, 3, 4, 5, 6], (2, 3)) + >>> a.shape + (2, 3) + >>> a + [[1, 2, 3], [4, 5, 6]] + >>> b = a.reshape(3, 2) + >>> b.shape + (3, 2) + >>> b + [[1, 2], [3, 4], [5, 6]] + + """ + new_total_size = functools.reduce(lambda x,y: x*y, newshape) + if new_total_size != self._loop_size: + raise ValueError('Expecting reshape size to %d but got prod(%s) = %d' % ( + self._loop_size, str(newshape), new_total_size)) + + # there is no `.func` as this class does not subtype `Basic`: + return type(self)(self._array, newshape) + + +class ImmutableDenseNDimArray(DenseNDimArray, ImmutableNDimArray): # type: ignore + def __new__(cls, iterable, shape=None, **kwargs): + return cls._new(iterable, shape, **kwargs) + + @classmethod + def _new(cls, iterable, shape, **kwargs): + shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs) + shape = Tuple(*map(_sympify, shape)) + cls._check_special_bounds(flat_list, shape) + flat_list = flatten(flat_list) + flat_list = Tuple(*flat_list) + self = Basic.__new__(cls, flat_list, shape, **kwargs) + self._shape = shape + self._array = list(flat_list) + self._rank = len(shape) + self._loop_size = functools.reduce(lambda x,y: x*y, shape, 1) + return self + + def __setitem__(self, index, value): + raise TypeError('immutable N-dim array') + + def as_mutable(self): + return MutableDenseNDimArray(self) + + def _eval_simplify(self, **kwargs): + from sympy.simplify.simplify import simplify + return self.applyfunc(simplify) + +class MutableDenseNDimArray(DenseNDimArray, MutableNDimArray): + + def __new__(cls, iterable=None, shape=None, **kwargs): + return cls._new(iterable, shape, **kwargs) + + @classmethod + def _new(cls, iterable, shape, **kwargs): + shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs) + flat_list = flatten(flat_list) + self = object.__new__(cls) + self._shape = shape + self._array = list(flat_list) + self._rank = len(shape) + self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else len(flat_list) + return self + + def __setitem__(self, index, value): + """Allows to set items to MutableDenseNDimArray. + + Examples + ======== + + >>> from sympy import MutableDenseNDimArray + >>> a = MutableDenseNDimArray.zeros(2, 2) + >>> a[0,0] = 1 + >>> a[1,1] = 1 + >>> a + [[1, 0], [0, 1]] + + """ + if isinstance(index, tuple) and any(isinstance(i, slice) for i in index): + value, eindices, slice_offsets = self._get_slice_data_for_array_assignment(index, value) + for i in eindices: + other_i = [ind - j for ind, j in zip(i, slice_offsets) if j is not None] + self._array[self._parse_index(i)] = value[other_i] + else: + index = self._parse_index(index) + self._setter_iterable_check(value) + value = _sympify(value) + self._array[index] = value + + def as_immutable(self): + return ImmutableDenseNDimArray(self) + + @property + def free_symbols(self): + return {i for j in self._array for i in j.free_symbols} diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__init__.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f1658241782cdf0e38a30c43a6d67f9811297f4c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__init__.py @@ -0,0 +1,178 @@ +r""" +Array expressions are expressions representing N-dimensional arrays, without +evaluating them. These expressions represent in a certain way abstract syntax +trees of operations on N-dimensional arrays. + +Every N-dimensional array operator has a corresponding array expression object. + +Table of correspondences: + +=============================== ============================= + Array operator Array expression operator +=============================== ============================= + tensorproduct ArrayTensorProduct + tensorcontraction ArrayContraction + tensordiagonal ArrayDiagonal + permutedims PermuteDims +=============================== ============================= + +Examples +======== + +``ArraySymbol`` objects are the N-dimensional equivalent of ``MatrixSymbol`` +objects in the matrix module: + +>>> from sympy.tensor.array.expressions import ArraySymbol +>>> from sympy.abc import i, j, k +>>> A = ArraySymbol("A", (3, 2, 4)) +>>> A.shape +(3, 2, 4) +>>> A[i, j, k] +A[i, j, k] +>>> A.as_explicit() +[[[A[0, 0, 0], A[0, 0, 1], A[0, 0, 2], A[0, 0, 3]], + [A[0, 1, 0], A[0, 1, 1], A[0, 1, 2], A[0, 1, 3]]], + [[A[1, 0, 0], A[1, 0, 1], A[1, 0, 2], A[1, 0, 3]], + [A[1, 1, 0], A[1, 1, 1], A[1, 1, 2], A[1, 1, 3]]], + [[A[2, 0, 0], A[2, 0, 1], A[2, 0, 2], A[2, 0, 3]], + [A[2, 1, 0], A[2, 1, 1], A[2, 1, 2], A[2, 1, 3]]]] + +Component-explicit arrays can be added inside array expressions: + +>>> from sympy import Array +>>> from sympy import tensorproduct +>>> from sympy.tensor.array.expressions import ArrayTensorProduct +>>> a = Array([1, 2, 3]) +>>> b = Array([i, j, k]) +>>> expr = ArrayTensorProduct(a, b, b) +>>> expr +ArrayTensorProduct([1, 2, 3], [i, j, k], [i, j, k]) +>>> expr.as_explicit() == tensorproduct(a, b, b) +True + +Constructing array expressions from index-explicit forms +-------------------------------------------------------- + +Array expressions are index-implicit. This means they do not use any indices to +represent array operations. The function ``convert_indexed_to_array( ... )`` +may be used to convert index-explicit expressions to array expressions. +It takes as input two parameters: the index-explicit expression and the order +of the indices: + +>>> from sympy.tensor.array.expressions import convert_indexed_to_array +>>> from sympy import Sum +>>> A = ArraySymbol("A", (3, 3)) +>>> B = ArraySymbol("B", (3, 3)) +>>> convert_indexed_to_array(A[i, j], [i, j]) +A +>>> convert_indexed_to_array(A[i, j], [j, i]) +PermuteDims(A, (0 1)) +>>> convert_indexed_to_array(A[i, j] + B[j, i], [i, j]) +ArrayAdd(A, PermuteDims(B, (0 1))) +>>> convert_indexed_to_array(Sum(A[i, j]*B[j, k], (j, 0, 2)), [i, k]) +ArrayContraction(ArrayTensorProduct(A, B), (1, 2)) + +The diagonal of a matrix in the array expression form: + +>>> convert_indexed_to_array(A[i, i], [i]) +ArrayDiagonal(A, (0, 1)) + +The trace of a matrix in the array expression form: + +>>> convert_indexed_to_array(Sum(A[i, i], (i, 0, 2)), [i]) +ArrayContraction(A, (0, 1)) + +Compatibility with matrices +--------------------------- + +Array expressions can be mixed with objects from the matrix module: + +>>> from sympy import MatrixSymbol +>>> from sympy.tensor.array.expressions import ArrayContraction +>>> M = MatrixSymbol("M", 3, 3) +>>> N = MatrixSymbol("N", 3, 3) + +Express the matrix product in the array expression form: + +>>> from sympy.tensor.array.expressions import convert_matrix_to_array +>>> expr = convert_matrix_to_array(M*N) +>>> expr +ArrayContraction(ArrayTensorProduct(M, N), (1, 2)) + +The expression can be converted back to matrix form: + +>>> from sympy.tensor.array.expressions import convert_array_to_matrix +>>> convert_array_to_matrix(expr) +M*N + +Add a second contraction on the remaining axes in order to get the trace of `M \cdot N`: + +>>> expr_tr = ArrayContraction(expr, (0, 1)) +>>> expr_tr +ArrayContraction(ArrayContraction(ArrayTensorProduct(M, N), (1, 2)), (0, 1)) + +Flatten the expression by calling ``.doit()`` and remove the nested array contraction operations: + +>>> expr_tr.doit() +ArrayContraction(ArrayTensorProduct(M, N), (0, 3), (1, 2)) + +Get the explicit form of the array expression: + +>>> expr.as_explicit() +[[M[0, 0]*N[0, 0] + M[0, 1]*N[1, 0] + M[0, 2]*N[2, 0], M[0, 0]*N[0, 1] + M[0, 1]*N[1, 1] + M[0, 2]*N[2, 1], M[0, 0]*N[0, 2] + M[0, 1]*N[1, 2] + M[0, 2]*N[2, 2]], + [M[1, 0]*N[0, 0] + M[1, 1]*N[1, 0] + M[1, 2]*N[2, 0], M[1, 0]*N[0, 1] + M[1, 1]*N[1, 1] + M[1, 2]*N[2, 1], M[1, 0]*N[0, 2] + M[1, 1]*N[1, 2] + M[1, 2]*N[2, 2]], + [M[2, 0]*N[0, 0] + M[2, 1]*N[1, 0] + M[2, 2]*N[2, 0], M[2, 0]*N[0, 1] + M[2, 1]*N[1, 1] + M[2, 2]*N[2, 1], M[2, 0]*N[0, 2] + M[2, 1]*N[1, 2] + M[2, 2]*N[2, 2]]] + +Express the trace of a matrix: + +>>> from sympy import Trace +>>> convert_matrix_to_array(Trace(M)) +ArrayContraction(M, (0, 1)) +>>> convert_matrix_to_array(Trace(M*N)) +ArrayContraction(ArrayTensorProduct(M, N), (0, 3), (1, 2)) + +Express the transposition of a matrix (will be expressed as a permutation of the axes: + +>>> convert_matrix_to_array(M.T) +PermuteDims(M, (0 1)) + +Compute the derivative array expressions: + +>>> from sympy.tensor.array.expressions import array_derive +>>> d = array_derive(M, M) +>>> d +PermuteDims(ArrayTensorProduct(I, I), (3)(1 2)) + +Verify that the derivative corresponds to the form computed with explicit matrices: + +>>> d.as_explicit() +[[[[1, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 1, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 1], [0, 0, 0], [0, 0, 0]]], [[[0, 0, 0], [1, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 1, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 1], [0, 0, 0]]], [[[0, 0, 0], [0, 0, 0], [1, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 1, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 1]]]] +>>> Me = M.as_explicit() +>>> Me.diff(Me) +[[[[1, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 1, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 1], [0, 0, 0], [0, 0, 0]]], [[[0, 0, 0], [1, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 1, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 1], [0, 0, 0]]], [[[0, 0, 0], [0, 0, 0], [1, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 1, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 1]]]] + +""" + +__all__ = [ + "ArraySymbol", "ArrayElement", "ZeroArray", "OneArray", + "ArrayTensorProduct", + "ArrayContraction", + "ArrayDiagonal", + "PermuteDims", + "ArrayAdd", + "ArrayElementwiseApplyFunc", + "Reshape", + "convert_array_to_matrix", + "convert_matrix_to_array", + "convert_array_to_indexed", + "convert_indexed_to_array", + "array_derive", +] + +from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayAdd, PermuteDims, ArrayDiagonal, \ + ArrayContraction, Reshape, ArraySymbol, ArrayElement, ZeroArray, OneArray, ArrayElementwiseApplyFunc +from sympy.tensor.array.expressions.arrayexpr_derivatives import array_derive +from sympy.tensor.array.expressions.from_array_to_indexed import convert_array_to_indexed +from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix +from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array +from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c836f905786be1d699e198f76d5595cec823349 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/array_expressions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/array_expressions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..857858a44d0554fc5cbbfeee0af1bbfeb0039198 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/array_expressions.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2800435ecbbc5dc1146544725b2a2e0f21d1d924d9a17ad8c138bacfaa78b7b8 +size 110687 diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/arrayexpr_derivatives.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/arrayexpr_derivatives.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34a66861d8470b1a276af735eaf9cbf4c38dc3d6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/arrayexpr_derivatives.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/conv_array_to_indexed.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/conv_array_to_indexed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d27d8c02ad6cbe4e4697cd48e392330bf009aabc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/conv_array_to_indexed.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/conv_array_to_matrix.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/conv_array_to_matrix.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..922f29b162eb2a1c427b7ad12dcf4e8a000f84bd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/conv_array_to_matrix.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/conv_indexed_to_array.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/conv_indexed_to_array.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29abeb9f19f63660d4a84fc87f987cff1235c146 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/conv_indexed_to_array.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/conv_matrix_to_array.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/conv_matrix_to_array.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a3e7a0db050ec1f3f6e7fa564acaedfd61380e3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/conv_matrix_to_array.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/from_array_to_indexed.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/from_array_to_indexed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a89708eac44e0a9027b17e31e2d0f5985de5b1c8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/from_array_to_indexed.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/from_array_to_matrix.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/from_array_to_matrix.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..490a19ed6088a14f555ee1faff685227c33d1c0c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/from_array_to_matrix.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/from_indexed_to_array.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/from_indexed_to_array.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a8df252f0191baa96fcdb153ec0358c155fae1e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/from_indexed_to_array.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/from_matrix_to_array.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/from_matrix_to_array.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e698e45ea5c1fa2883ab0a6019638e58ea49b6d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/from_matrix_to_array.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2105e609cc70918334dad63e6820d0f2d29ae85b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/array_expressions.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/array_expressions.py new file mode 100644 index 0000000000000000000000000000000000000000..f062e3de4c24987d62ba0b3a19fe474fb4687940 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/array_expressions.py @@ -0,0 +1,1969 @@ +from __future__ import annotations +import collections.abc +import operator +from collections import defaultdict, Counter +from functools import reduce +import itertools +from itertools import accumulate + +import typing + +from sympy.core.numbers import Integer +from sympy.core.relational import Equality +from sympy.functions.special.tensor_functions import KroneckerDelta +from sympy.core.basic import Basic +from sympy.core.containers import Tuple +from sympy.core.expr import Expr +from sympy.core.function import (Function, Lambda) +from sympy.core.mul import Mul +from sympy.core.singleton import S +from sympy.core.sorting import default_sort_key +from sympy.core.symbol import (Dummy, Symbol) +from sympy.matrices.matrixbase import MatrixBase +from sympy.matrices.expressions.diagonal import diagonalize_vector +from sympy.matrices.expressions.matexpr import MatrixExpr +from sympy.matrices.expressions.special import ZeroMatrix +from sympy.tensor.array.arrayop import (permutedims, tensorcontraction, tensordiagonal, tensorproduct) +from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray +from sympy.tensor.array.ndim_array import NDimArray +from sympy.tensor.indexed import (Indexed, IndexedBase) +from sympy.matrices.expressions.matexpr import MatrixElement +from sympy.tensor.array.expressions.utils import _apply_recursively_over_nested_lists, _sort_contraction_indices, \ + _get_mapping_from_subranks, _build_push_indices_up_func_transformation, _get_contraction_links, \ + _build_push_indices_down_func_transformation +from sympy.combinatorics import Permutation +from sympy.combinatorics.permutations import _af_invert +from sympy.core.sympify import _sympify + + +class _ArrayExpr(Expr): + shape: tuple[Expr, ...] + + def __getitem__(self, item): + if not isinstance(item, collections.abc.Iterable): + item = (item,) + ArrayElement._check_shape(self, item) + return self._get(item) + + def _get(self, item): + return _get_array_element_or_slice(self, item) + + +class ArraySymbol(_ArrayExpr): + """ + Symbol representing an array expression + """ + + _iterable = False + + def __new__(cls, symbol, shape: typing.Iterable) -> "ArraySymbol": + if isinstance(symbol, str): + symbol = Symbol(symbol) + # symbol = _sympify(symbol) + shape = Tuple(*map(_sympify, shape)) + obj = Expr.__new__(cls, symbol, shape) + return obj + + @property + def name(self): + return self._args[0] + + @property + def shape(self): + return self._args[1] + + def as_explicit(self): + if not all(i.is_Integer for i in self.shape): + raise ValueError("cannot express explicit array with symbolic shape") + data = [self[i] for i in itertools.product(*[range(j) for j in self.shape])] + return ImmutableDenseNDimArray(data).reshape(*self.shape) + + +class ArrayElement(Expr): + """ + An element of an array. + """ + + _diff_wrt = True + is_symbol = True + is_commutative = True + + def __new__(cls, name, indices): + if isinstance(name, str): + name = Symbol(name) + name = _sympify(name) + if not isinstance(indices, collections.abc.Iterable): + indices = (indices,) + indices = _sympify(tuple(indices)) + cls._check_shape(name, indices) + obj = Expr.__new__(cls, name, indices) + return obj + + @classmethod + def _check_shape(cls, name, indices): + indices = tuple(indices) + if hasattr(name, "shape"): + index_error = IndexError("number of indices does not match shape of the array") + if len(indices) != len(name.shape): + raise index_error + if any((i >= s) == True for i, s in zip(indices, name.shape)): + raise ValueError("shape is out of bounds") + if any((i < 0) == True for i in indices): + raise ValueError("shape contains negative values") + + @property + def name(self): + return self._args[0] + + @property + def indices(self): + return self._args[1] + + def _eval_derivative(self, s): + if not isinstance(s, ArrayElement): + return S.Zero + + if s == self: + return S.One + + if s.name != self.name: + return S.Zero + + return Mul.fromiter(KroneckerDelta(i, j) for i, j in zip(self.indices, s.indices)) + + +class ZeroArray(_ArrayExpr): + """ + Symbolic array of zeros. Equivalent to ``ZeroMatrix`` for matrices. + """ + + def __new__(cls, *shape): + if len(shape) == 0: + return S.Zero + shape = map(_sympify, shape) + obj = Expr.__new__(cls, *shape) + return obj + + @property + def shape(self): + return self._args + + def as_explicit(self): + if not all(i.is_Integer for i in self.shape): + raise ValueError("Cannot return explicit form for symbolic shape.") + return ImmutableDenseNDimArray.zeros(*self.shape) + + def _get(self, item): + return S.Zero + + +class OneArray(_ArrayExpr): + """ + Symbolic array of ones. + """ + + def __new__(cls, *shape): + if len(shape) == 0: + return S.One + shape = map(_sympify, shape) + obj = Expr.__new__(cls, *shape) + return obj + + @property + def shape(self): + return self._args + + def as_explicit(self): + if not all(i.is_Integer for i in self.shape): + raise ValueError("Cannot return explicit form for symbolic shape.") + return ImmutableDenseNDimArray([S.One for i in range(reduce(operator.mul, self.shape))]).reshape(*self.shape) + + def _get(self, item): + return S.One + + +class _CodegenArrayAbstract(Basic): + + @property + def subranks(self): + """ + Returns the ranks of the objects in the uppermost tensor product inside + the current object. In case no tensor products are contained, return + the atomic ranks. + + Examples + ======== + + >>> from sympy.tensor.array import tensorproduct, tensorcontraction + >>> from sympy import MatrixSymbol + >>> M = MatrixSymbol("M", 3, 3) + >>> N = MatrixSymbol("N", 3, 3) + >>> P = MatrixSymbol("P", 3, 3) + + Important: do not confuse the rank of the matrix with the rank of an array. + + >>> tp = tensorproduct(M, N, P) + >>> tp.subranks + [2, 2, 2] + + >>> co = tensorcontraction(tp, (1, 2), (3, 4)) + >>> co.subranks + [2, 2, 2] + """ + return self._subranks[:] + + def subrank(self): + """ + The sum of ``subranks``. + """ + return sum(self.subranks) + + @property + def shape(self): + return self._shape + + def doit(self, **hints): + deep = hints.get("deep", True) + if deep: + return self.func(*[arg.doit(**hints) for arg in self.args])._canonicalize() + else: + return self._canonicalize() + +class ArrayTensorProduct(_CodegenArrayAbstract): + r""" + Class to represent the tensor product of array-like objects. + """ + + def __new__(cls, *args, **kwargs): + args = [_sympify(arg) for arg in args] + + canonicalize = kwargs.pop("canonicalize", False) + + ranks = [get_rank(arg) for arg in args] + + obj = Basic.__new__(cls, *args) + obj._subranks = ranks + shapes = [get_shape(i) for i in args] + + if any(i is None for i in shapes): + obj._shape = None + else: + obj._shape = tuple(j for i in shapes for j in i) + if canonicalize: + return obj._canonicalize() + return obj + + def _canonicalize(self): + args = self.args + args = self._flatten(args) + + ranks = [get_rank(arg) for arg in args] + + # Check if there are nested permutation and lift them up: + permutation_cycles = [] + for i, arg in enumerate(args): + if not isinstance(arg, PermuteDims): + continue + permutation_cycles.extend([[k + sum(ranks[:i]) for k in j] for j in arg.permutation.cyclic_form]) + args[i] = arg.expr + if permutation_cycles: + return _permute_dims(_array_tensor_product(*args), Permutation(sum(ranks)-1)*Permutation(permutation_cycles)) + + if len(args) == 1: + return args[0] + + # If any object is a ZeroArray, return a ZeroArray: + if any(isinstance(arg, (ZeroArray, ZeroMatrix)) for arg in args): + shapes = reduce(operator.add, [get_shape(i) for i in args], ()) + return ZeroArray(*shapes) + + # If there are contraction objects inside, transform the whole + # expression into `ArrayContraction`: + contractions = {i: arg for i, arg in enumerate(args) if isinstance(arg, ArrayContraction)} + if contractions: + ranks = [_get_subrank(arg) if isinstance(arg, ArrayContraction) else get_rank(arg) for arg in args] + cumulative_ranks = list(accumulate([0] + ranks))[:-1] + tp = _array_tensor_product(*[arg.expr if isinstance(arg, ArrayContraction) else arg for arg in args]) + contraction_indices = [tuple(cumulative_ranks[i] + k for k in j) for i, arg in contractions.items() for j in arg.contraction_indices] + return _array_contraction(tp, *contraction_indices) + + diagonals = {i: arg for i, arg in enumerate(args) if isinstance(arg, ArrayDiagonal)} + if diagonals: + inverse_permutation = [] + last_perm = [] + ranks = [get_rank(arg) for arg in args] + cumulative_ranks = list(accumulate([0] + ranks))[:-1] + for i, arg in enumerate(args): + if isinstance(arg, ArrayDiagonal): + i1 = get_rank(arg) - len(arg.diagonal_indices) + i2 = len(arg.diagonal_indices) + inverse_permutation.extend([cumulative_ranks[i] + j for j in range(i1)]) + last_perm.extend([cumulative_ranks[i] + j for j in range(i1, i1 + i2)]) + else: + inverse_permutation.extend([cumulative_ranks[i] + j for j in range(get_rank(arg))]) + inverse_permutation.extend(last_perm) + tp = _array_tensor_product(*[arg.expr if isinstance(arg, ArrayDiagonal) else arg for arg in args]) + ranks2 = [_get_subrank(arg) if isinstance(arg, ArrayDiagonal) else get_rank(arg) for arg in args] + cumulative_ranks2 = list(accumulate([0] + ranks2))[:-1] + diagonal_indices = [tuple(cumulative_ranks2[i] + k for k in j) for i, arg in diagonals.items() for j in arg.diagonal_indices] + return _permute_dims(_array_diagonal(tp, *diagonal_indices), _af_invert(inverse_permutation)) + + return self.func(*args, canonicalize=False) + + @classmethod + def _flatten(cls, args): + args = [i for arg in args for i in (arg.args if isinstance(arg, cls) else [arg])] + return args + + def as_explicit(self): + return tensorproduct(*[arg.as_explicit() if hasattr(arg, "as_explicit") else arg for arg in self.args]) + + +class ArrayAdd(_CodegenArrayAbstract): + r""" + Class for elementwise array additions. + """ + + def __new__(cls, *args, **kwargs): + args = [_sympify(arg) for arg in args] + ranks = [get_rank(arg) for arg in args] + ranks = list(set(ranks)) + if len(ranks) != 1: + raise ValueError("summing arrays of different ranks") + shapes = [arg.shape for arg in args] + if len({i for i in shapes if i is not None}) > 1: + raise ValueError("mismatching shapes in addition") + + canonicalize = kwargs.pop("canonicalize", False) + + obj = Basic.__new__(cls, *args) + obj._subranks = ranks + if any(i is None for i in shapes): + obj._shape = None + else: + obj._shape = shapes[0] + if canonicalize: + return obj._canonicalize() + return obj + + def _canonicalize(self): + args = self.args + + # Flatten: + args = self._flatten_args(args) + + shapes = [get_shape(arg) for arg in args] + args = [arg for arg in args if not isinstance(arg, (ZeroArray, ZeroMatrix))] + if len(args) == 0: + if any(i for i in shapes if i is None): + raise NotImplementedError("cannot handle addition of ZeroMatrix/ZeroArray and undefined shape object") + return ZeroArray(*shapes[0]) + elif len(args) == 1: + return args[0] + return self.func(*args, canonicalize=False) + + @classmethod + def _flatten_args(cls, args): + new_args = [] + for arg in args: + if isinstance(arg, ArrayAdd): + new_args.extend(arg.args) + else: + new_args.append(arg) + return new_args + + def as_explicit(self): + return reduce( + operator.add, + [arg.as_explicit() if hasattr(arg, "as_explicit") else arg for arg in self.args]) + + +class PermuteDims(_CodegenArrayAbstract): + r""" + Class to represent permutation of axes of arrays. + + Examples + ======== + + >>> from sympy.tensor.array import permutedims + >>> from sympy import MatrixSymbol + >>> M = MatrixSymbol("M", 3, 3) + >>> cg = permutedims(M, [1, 0]) + + The object ``cg`` represents the transposition of ``M``, as the permutation + ``[1, 0]`` will act on its indices by switching them: + + `M_{ij} \Rightarrow M_{ji}` + + This is evident when transforming back to matrix form: + + >>> from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix + >>> convert_array_to_matrix(cg) + M.T + + >>> N = MatrixSymbol("N", 3, 2) + >>> cg = permutedims(N, [1, 0]) + >>> cg.shape + (2, 3) + + There are optional parameters that can be used as alternative to the permutation: + + >>> from sympy.tensor.array.expressions import ArraySymbol, PermuteDims + >>> M = ArraySymbol("M", (1, 2, 3, 4, 5)) + >>> expr = PermuteDims(M, index_order_old="ijklm", index_order_new="kijml") + >>> expr + PermuteDims(M, (0 2 1)(3 4)) + >>> expr.shape + (3, 1, 2, 5, 4) + + Permutations of tensor products are simplified in order to achieve a + standard form: + + >>> from sympy.tensor.array import tensorproduct + >>> M = MatrixSymbol("M", 4, 5) + >>> tp = tensorproduct(M, N) + >>> tp.shape + (4, 5, 3, 2) + >>> perm1 = permutedims(tp, [2, 3, 1, 0]) + + The args ``(M, N)`` have been sorted and the permutation has been + simplified, the expression is equivalent: + + >>> perm1.expr.args + (N, M) + >>> perm1.shape + (3, 2, 5, 4) + >>> perm1.permutation + (2 3) + + The permutation in its array form has been simplified from + ``[2, 3, 1, 0]`` to ``[0, 1, 3, 2]``, as the arguments of the tensor + product `M` and `N` have been switched: + + >>> perm1.permutation.array_form + [0, 1, 3, 2] + + We can nest a second permutation: + + >>> perm2 = permutedims(perm1, [1, 0, 2, 3]) + >>> perm2.shape + (2, 3, 5, 4) + >>> perm2.permutation.array_form + [1, 0, 3, 2] + """ + + def __new__(cls, expr, permutation=None, index_order_old=None, index_order_new=None, **kwargs): + from sympy.combinatorics import Permutation + expr = _sympify(expr) + expr_rank = get_rank(expr) + permutation = cls._get_permutation_from_arguments(permutation, index_order_old, index_order_new, expr_rank) + permutation = Permutation(permutation) + permutation_size = permutation.size + if permutation_size != expr_rank: + raise ValueError("Permutation size must be the length of the shape of expr") + + canonicalize = kwargs.pop("canonicalize", False) + + obj = Basic.__new__(cls, expr, permutation) + obj._subranks = [get_rank(expr)] + shape = get_shape(expr) + if shape is None: + obj._shape = None + else: + obj._shape = tuple(shape[permutation(i)] for i in range(len(shape))) + if canonicalize: + return obj._canonicalize() + return obj + + def _canonicalize(self): + expr = self.expr + permutation = self.permutation + if isinstance(expr, PermuteDims): + subexpr = expr.expr + subperm = expr.permutation + permutation = permutation * subperm + expr = subexpr + if isinstance(expr, ArrayContraction): + expr, permutation = self._PermuteDims_denestarg_ArrayContraction(expr, permutation) + if isinstance(expr, ArrayTensorProduct): + expr, permutation = self._PermuteDims_denestarg_ArrayTensorProduct(expr, permutation) + if isinstance(expr, (ZeroArray, ZeroMatrix)): + return ZeroArray(*[expr.shape[i] for i in permutation.array_form]) + plist = permutation.array_form + if plist == sorted(plist): + return expr + return self.func(expr, permutation, canonicalize=False) + + @property + def expr(self): + return self.args[0] + + @property + def permutation(self): + return self.args[1] + + @classmethod + def _PermuteDims_denestarg_ArrayTensorProduct(cls, expr, permutation): + # Get the permutation in its image-form: + perm_image_form = _af_invert(permutation.array_form) + args = list(expr.args) + # Starting index global position for every arg: + cumul = list(accumulate([0] + expr.subranks)) + # Split `perm_image_form` into a list of list corresponding to the indices + # of every argument: + perm_image_form_in_components = [perm_image_form[cumul[i]:cumul[i+1]] for i in range(len(args))] + # Create an index, target-position-key array: + ps = [(i, sorted(comp)) for i, comp in enumerate(perm_image_form_in_components)] + # Sort the array according to the target-position-key: + # In this way, we define a canonical way to sort the arguments according + # to the permutation. + ps.sort(key=lambda x: x[1]) + # Read the inverse-permutation (i.e. image-form) of the args: + perm_args_image_form = [i[0] for i in ps] + # Apply the args-permutation to the `args`: + args_sorted = [args[i] for i in perm_args_image_form] + # Apply the args-permutation to the array-form of the permutation of the axes (of `expr`): + perm_image_form_sorted_args = [perm_image_form_in_components[i] for i in perm_args_image_form] + new_permutation = Permutation(_af_invert([j for i in perm_image_form_sorted_args for j in i])) + return _array_tensor_product(*args_sorted), new_permutation + + @classmethod + def _PermuteDims_denestarg_ArrayContraction(cls, expr, permutation): + if not isinstance(expr, ArrayContraction): + return expr, permutation + if not isinstance(expr.expr, ArrayTensorProduct): + return expr, permutation + args = expr.expr.args + subranks = [get_rank(arg) for arg in expr.expr.args] + + contraction_indices = expr.contraction_indices + contraction_indices_flat = [j for i in contraction_indices for j in i] + cumul = list(accumulate([0] + subranks)) + + # Spread the permutation in its array form across the args in the corresponding + # tensor-product arguments with free indices: + permutation_array_blocks_up = [] + image_form = _af_invert(permutation.array_form) + counter = 0 + for i in range(len(subranks)): + current = [] + for j in range(cumul[i], cumul[i+1]): + if j in contraction_indices_flat: + continue + current.append(image_form[counter]) + counter += 1 + permutation_array_blocks_up.append(current) + + # Get the map of axis repositioning for every argument of tensor-product: + index_blocks = [list(range(cumul[i], cumul[i+1])) for i, e in enumerate(expr.subranks)] + index_blocks_up = expr._push_indices_up(expr.contraction_indices, index_blocks) + inverse_permutation = permutation**(-1) + index_blocks_up_permuted = [[inverse_permutation(j) for j in i if j is not None] for i in index_blocks_up] + + # Sorting key is a list of tuple, first element is the index of `args`, second element of + # the tuple is the sorting key to sort `args` of the tensor product: + sorting_keys = list(enumerate(index_blocks_up_permuted)) + sorting_keys.sort(key=lambda x: x[1]) + + # Now we can get the permutation acting on the args in its image-form: + new_perm_image_form = [i[0] for i in sorting_keys] + # Apply the args-level permutation to various elements: + new_index_blocks = [index_blocks[i] for i in new_perm_image_form] + new_index_perm_array_form = _af_invert([j for i in new_index_blocks for j in i]) + new_args = [args[i] for i in new_perm_image_form] + new_contraction_indices = [tuple(new_index_perm_array_form[j] for j in i) for i in contraction_indices] + new_expr = _array_contraction(_array_tensor_product(*new_args), *new_contraction_indices) + new_permutation = Permutation(_af_invert([j for i in [permutation_array_blocks_up[k] for k in new_perm_image_form] for j in i])) + return new_expr, new_permutation + + @classmethod + def _check_permutation_mapping(cls, expr, permutation): + subranks = expr.subranks + index2arg = [i for i, arg in enumerate(expr.args) for j in range(expr.subranks[i])] + permuted_indices = [permutation(i) for i in range(expr.subrank())] + new_args = list(expr.args) + arg_candidate_index = index2arg[permuted_indices[0]] + current_indices = [] + new_permutation = [] + inserted_arg_cand_indices = set() + for i, idx in enumerate(permuted_indices): + if index2arg[idx] != arg_candidate_index: + new_permutation.extend(current_indices) + current_indices = [] + arg_candidate_index = index2arg[idx] + current_indices.append(idx) + arg_candidate_rank = subranks[arg_candidate_index] + if len(current_indices) == arg_candidate_rank: + new_permutation.extend(sorted(current_indices)) + local_current_indices = [j - min(current_indices) for j in current_indices] + i1 = index2arg[i] + new_args[i1] = _permute_dims(new_args[i1], Permutation(local_current_indices)) + inserted_arg_cand_indices.add(arg_candidate_index) + current_indices = [] + new_permutation.extend(current_indices) + + # TODO: swap args positions in order to simplify the expression: + # TODO: this should be in a function + args_positions = list(range(len(new_args))) + # Get possible shifts: + maps = {} + cumulative_subranks = [0] + list(accumulate(subranks)) + for i in range(len(subranks)): + s = {index2arg[new_permutation[j]] for j in range(cumulative_subranks[i], cumulative_subranks[i+1])} + if len(s) != 1: + continue + elem = next(iter(s)) + if i != elem: + maps[i] = elem + + # Find cycles in the map: + lines = [] + current_line = [] + while maps: + if len(current_line) == 0: + k, v = maps.popitem() + current_line.append(k) + else: + k = current_line[-1] + if k not in maps: + current_line = [] + continue + v = maps.pop(k) + if v in current_line: + lines.append(current_line) + current_line = [] + continue + current_line.append(v) + for line in lines: + for i, e in enumerate(line): + args_positions[line[(i + 1) % len(line)]] = e + + # TODO: function in order to permute the args: + permutation_blocks = [[new_permutation[cumulative_subranks[i] + j] for j in range(e)] for i, e in enumerate(subranks)] + new_args = [new_args[i] for i in args_positions] + new_permutation_blocks = [permutation_blocks[i] for i in args_positions] + new_permutation2 = [j for i in new_permutation_blocks for j in i] + return _array_tensor_product(*new_args), Permutation(new_permutation2) # **(-1) + + @classmethod + def _check_if_there_are_closed_cycles(cls, expr, permutation): + args = list(expr.args) + subranks = expr.subranks + cyclic_form = permutation.cyclic_form + cumulative_subranks = [0] + list(accumulate(subranks)) + cyclic_min = [min(i) for i in cyclic_form] + cyclic_max = [max(i) for i in cyclic_form] + cyclic_keep = [] + for i, cycle in enumerate(cyclic_form): + flag = True + for j in range(len(cumulative_subranks) - 1): + if cyclic_min[i] >= cumulative_subranks[j] and cyclic_max[i] < cumulative_subranks[j+1]: + # Found a sinkable cycle. + args[j] = _permute_dims(args[j], Permutation([[k - cumulative_subranks[j] for k in cycle]])) + flag = False + break + if flag: + cyclic_keep.append(cycle) + return _array_tensor_product(*args), Permutation(cyclic_keep, size=permutation.size) + + def nest_permutation(self): + r""" + DEPRECATED. + """ + ret = self._nest_permutation(self.expr, self.permutation) + if ret is None: + return self + return ret + + @classmethod + def _nest_permutation(cls, expr, permutation): + if isinstance(expr, ArrayTensorProduct): + return _permute_dims(*cls._check_if_there_are_closed_cycles(expr, permutation)) + elif isinstance(expr, ArrayContraction): + # Invert tree hierarchy: put the contraction above. + cycles = permutation.cyclic_form + newcycles = ArrayContraction._convert_outer_indices_to_inner_indices(expr, *cycles) + newpermutation = Permutation(newcycles) + new_contr_indices = [tuple(newpermutation(j) for j in i) for i in expr.contraction_indices] + return _array_contraction(PermuteDims(expr.expr, newpermutation), *new_contr_indices) + elif isinstance(expr, ArrayAdd): + return _array_add(*[PermuteDims(arg, permutation) for arg in expr.args]) + return None + + def as_explicit(self): + expr = self.expr + if hasattr(expr, "as_explicit"): + expr = expr.as_explicit() + return permutedims(expr, self.permutation) + + @classmethod + def _get_permutation_from_arguments(cls, permutation, index_order_old, index_order_new, dim): + if permutation is None: + if index_order_new is None or index_order_old is None: + raise ValueError("Permutation not defined") + return PermuteDims._get_permutation_from_index_orders(index_order_old, index_order_new, dim) + else: + if index_order_new is not None: + raise ValueError("index_order_new cannot be defined with permutation") + if index_order_old is not None: + raise ValueError("index_order_old cannot be defined with permutation") + return permutation + + @classmethod + def _get_permutation_from_index_orders(cls, index_order_old, index_order_new, dim): + if len(set(index_order_new)) != dim: + raise ValueError("wrong number of indices in index_order_new") + if len(set(index_order_old)) != dim: + raise ValueError("wrong number of indices in index_order_old") + if len(set.symmetric_difference(set(index_order_new), set(index_order_old))) > 0: + raise ValueError("index_order_new and index_order_old must have the same indices") + permutation = [index_order_old.index(i) for i in index_order_new] + return permutation + + +class ArrayDiagonal(_CodegenArrayAbstract): + r""" + Class to represent the diagonal operator. + + Explanation + =========== + + In a 2-dimensional array it returns the diagonal, this looks like the + operation: + + `A_{ij} \rightarrow A_{ii}` + + The diagonal over axes 1 and 2 (the second and third) of the tensor product + of two 2-dimensional arrays `A \otimes B` is + + `\Big[ A_{ab} B_{cd} \Big]_{abcd} \rightarrow \Big[ A_{ai} B_{id} \Big]_{adi}` + + In this last example the array expression has been reduced from + 4-dimensional to 3-dimensional. Notice that no contraction has occurred, + rather there is a new index `i` for the diagonal, contraction would have + reduced the array to 2 dimensions. + + Notice that the diagonalized out dimensions are added as new dimensions at + the end of the indices. + """ + + def __new__(cls, expr, *diagonal_indices, **kwargs): + expr = _sympify(expr) + diagonal_indices = [Tuple(*sorted(i)) for i in diagonal_indices] + canonicalize = kwargs.get("canonicalize", False) + + shape = get_shape(expr) + if shape is not None: + cls._validate(expr, *diagonal_indices, **kwargs) + # Get new shape: + positions, shape = cls._get_positions_shape(shape, diagonal_indices) + else: + positions = None + if len(diagonal_indices) == 0: + return expr + obj = Basic.__new__(cls, expr, *diagonal_indices) + obj._positions = positions + obj._subranks = _get_subranks(expr) + obj._shape = shape + if canonicalize: + return obj._canonicalize() + return obj + + def _canonicalize(self): + expr = self.expr + diagonal_indices = self.diagonal_indices + trivial_diags = [i for i in diagonal_indices if len(i) == 1] + if len(trivial_diags) > 0: + trivial_pos = {e[0]: i for i, e in enumerate(diagonal_indices) if len(e) == 1} + diag_pos = {e: i for i, e in enumerate(diagonal_indices) if len(e) > 1} + diagonal_indices_short = [i for i in diagonal_indices if len(i) > 1] + rank1 = get_rank(self) + rank2 = len(diagonal_indices) + rank3 = rank1 - rank2 + inv_permutation = [] + counter1 = 0 + indices_down = ArrayDiagonal._push_indices_down(diagonal_indices_short, list(range(rank1)), get_rank(expr)) + for i in indices_down: + if i in trivial_pos: + inv_permutation.append(rank3 + trivial_pos[i]) + elif isinstance(i, (Integer, int)): + inv_permutation.append(counter1) + counter1 += 1 + else: + inv_permutation.append(rank3 + diag_pos[i]) + permutation = _af_invert(inv_permutation) + if len(diagonal_indices_short) > 0: + return _permute_dims(_array_diagonal(expr, *diagonal_indices_short), permutation) + else: + return _permute_dims(expr, permutation) + if isinstance(expr, ArrayAdd): + return self._ArrayDiagonal_denest_ArrayAdd(expr, *diagonal_indices) + if isinstance(expr, ArrayDiagonal): + return self._ArrayDiagonal_denest_ArrayDiagonal(expr, *diagonal_indices) + if isinstance(expr, PermuteDims): + return self._ArrayDiagonal_denest_PermuteDims(expr, *diagonal_indices) + if isinstance(expr, (ZeroArray, ZeroMatrix)): + positions, shape = self._get_positions_shape(expr.shape, diagonal_indices) + return ZeroArray(*shape) + return self.func(expr, *diagonal_indices, canonicalize=False) + + @staticmethod + def _validate(expr, *diagonal_indices, **kwargs): + # Check that no diagonalization happens on indices with mismatched + # dimensions: + shape = get_shape(expr) + for i in diagonal_indices: + if any(j >= len(shape) for j in i): + raise ValueError("index is larger than expression shape") + if len({shape[j] for j in i}) != 1: + raise ValueError("diagonalizing indices of different dimensions") + if not kwargs.get("allow_trivial_diags", False) and len(i) <= 1: + raise ValueError("need at least two axes to diagonalize") + if len(set(i)) != len(i): + raise ValueError("axis index cannot be repeated") + + @staticmethod + def _remove_trivial_dimensions(shape, *diagonal_indices): + return [tuple(j for j in i) for i in diagonal_indices if shape[i[0]] != 1] + + @property + def expr(self): + return self.args[0] + + @property + def diagonal_indices(self): + return self.args[1:] + + @staticmethod + def _flatten(expr, *outer_diagonal_indices): + inner_diagonal_indices = expr.diagonal_indices + all_inner = [j for i in inner_diagonal_indices for j in i] + all_inner.sort() + # TODO: add API for total rank and cumulative rank: + total_rank = _get_subrank(expr) + inner_rank = len(all_inner) + outer_rank = total_rank - inner_rank + shifts = [0 for i in range(outer_rank)] + counter = 0 + pointer = 0 + for i in range(outer_rank): + while pointer < inner_rank and counter >= all_inner[pointer]: + counter += 1 + pointer += 1 + shifts[i] += pointer + counter += 1 + outer_diagonal_indices = tuple(tuple(shifts[j] + j for j in i) for i in outer_diagonal_indices) + diagonal_indices = inner_diagonal_indices + outer_diagonal_indices + return _array_diagonal(expr.expr, *diagonal_indices) + + @classmethod + def _ArrayDiagonal_denest_ArrayAdd(cls, expr, *diagonal_indices): + return _array_add(*[_array_diagonal(arg, *diagonal_indices) for arg in expr.args]) + + @classmethod + def _ArrayDiagonal_denest_ArrayDiagonal(cls, expr, *diagonal_indices): + return cls._flatten(expr, *diagonal_indices) + + @classmethod + def _ArrayDiagonal_denest_PermuteDims(cls, expr: PermuteDims, *diagonal_indices): + back_diagonal_indices = [[expr.permutation(j) for j in i] for i in diagonal_indices] + nondiag = [i for i in range(get_rank(expr)) if not any(i in j for j in diagonal_indices)] + back_nondiag = [expr.permutation(i) for i in nondiag] + remap = {e: i for i, e in enumerate(sorted(back_nondiag))} + new_permutation1 = [remap[i] for i in back_nondiag] + shift = len(new_permutation1) + diag_block_perm = [i + shift for i in range(len(back_diagonal_indices))] + new_permutation = new_permutation1 + diag_block_perm + return _permute_dims( + _array_diagonal( + expr.expr, + *back_diagonal_indices + ), + new_permutation + ) + + def _push_indices_down_nonstatic(self, indices): + transform = lambda x: self._positions[x] if x < len(self._positions) else None + return _apply_recursively_over_nested_lists(transform, indices) + + def _push_indices_up_nonstatic(self, indices): + + def transform(x): + for i, e in enumerate(self._positions): + if (isinstance(e, int) and x == e) or (isinstance(e, tuple) and x in e): + return i + + return _apply_recursively_over_nested_lists(transform, indices) + + @classmethod + def _push_indices_down(cls, diagonal_indices, indices, rank): + positions, shape = cls._get_positions_shape(range(rank), diagonal_indices) + transform = lambda x: positions[x] if x < len(positions) else None + return _apply_recursively_over_nested_lists(transform, indices) + + @classmethod + def _push_indices_up(cls, diagonal_indices, indices, rank): + positions, shape = cls._get_positions_shape(range(rank), diagonal_indices) + + def transform(x): + for i, e in enumerate(positions): + if (isinstance(e, int) and x == e) or (isinstance(e, (tuple, Tuple)) and (x in e)): + return i + + return _apply_recursively_over_nested_lists(transform, indices) + + @classmethod + def _get_positions_shape(cls, shape, diagonal_indices): + data1 = tuple((i, shp) for i, shp in enumerate(shape) if not any(i in j for j in diagonal_indices)) + pos1, shp1 = zip(*data1) if data1 else ((), ()) + data2 = tuple((i, shape[i[0]]) for i in diagonal_indices) + pos2, shp2 = zip(*data2) if data2 else ((), ()) + positions = pos1 + pos2 + shape = shp1 + shp2 + return positions, shape + + def as_explicit(self): + expr = self.expr + if hasattr(expr, "as_explicit"): + expr = expr.as_explicit() + return tensordiagonal(expr, *self.diagonal_indices) + + +class ArrayElementwiseApplyFunc(_CodegenArrayAbstract): + + def __new__(cls, function, element): + + if not isinstance(function, Lambda): + d = Dummy('d') + function = Lambda(d, function(d)) + + obj = _CodegenArrayAbstract.__new__(cls, function, element) + obj._subranks = _get_subranks(element) + return obj + + @property + def function(self): + return self.args[0] + + @property + def expr(self): + return self.args[1] + + @property + def shape(self): + return self.expr.shape + + def _get_function_fdiff(self): + d = Dummy("d") + function = self.function(d) + fdiff = function.diff(d) + if isinstance(fdiff, Function): + fdiff = type(fdiff) + else: + fdiff = Lambda(d, fdiff) + return fdiff + + def as_explicit(self): + expr = self.expr + if hasattr(expr, "as_explicit"): + expr = expr.as_explicit() + return expr.applyfunc(self.function) + + +class ArrayContraction(_CodegenArrayAbstract): + r""" + This class is meant to represent contractions of arrays in a form easily + processable by the code printers. + """ + + def __new__(cls, expr, *contraction_indices, **kwargs): + contraction_indices = _sort_contraction_indices(contraction_indices) + expr = _sympify(expr) + + canonicalize = kwargs.get("canonicalize", False) + + obj = Basic.__new__(cls, expr, *contraction_indices) + obj._subranks = _get_subranks(expr) + obj._mapping = _get_mapping_from_subranks(obj._subranks) + + free_indices_to_position = {i: i for i in range(sum(obj._subranks)) if all(i not in cind for cind in contraction_indices)} + obj._free_indices_to_position = free_indices_to_position + + shape = get_shape(expr) + cls._validate(expr, *contraction_indices) + if shape: + shape = tuple(shp for i, shp in enumerate(shape) if not any(i in j for j in contraction_indices)) + obj._shape = shape + if canonicalize: + return obj._canonicalize() + return obj + + def _canonicalize(self): + expr = self.expr + contraction_indices = self.contraction_indices + + if len(contraction_indices) == 0: + return expr + + if isinstance(expr, ArrayContraction): + return self._ArrayContraction_denest_ArrayContraction(expr, *contraction_indices) + + if isinstance(expr, (ZeroArray, ZeroMatrix)): + return self._ArrayContraction_denest_ZeroArray(expr, *contraction_indices) + + if isinstance(expr, PermuteDims): + return self._ArrayContraction_denest_PermuteDims(expr, *contraction_indices) + + if isinstance(expr, ArrayTensorProduct): + expr, contraction_indices = self._sort_fully_contracted_args(expr, contraction_indices) + expr, contraction_indices = self._lower_contraction_to_addends(expr, contraction_indices) + if len(contraction_indices) == 0: + return expr + + if isinstance(expr, ArrayDiagonal): + return self._ArrayContraction_denest_ArrayDiagonal(expr, *contraction_indices) + + if isinstance(expr, ArrayAdd): + return self._ArrayContraction_denest_ArrayAdd(expr, *contraction_indices) + + # Check single index contractions on 1-dimensional axes: + contraction_indices = [i for i in contraction_indices if len(i) > 1 or get_shape(expr)[i[0]] != 1] + if len(contraction_indices) == 0: + return expr + + return self.func(expr, *contraction_indices, canonicalize=False) + + def __mul__(self, other): + if other == 1: + return self + else: + raise NotImplementedError("Product of N-dim arrays is not uniquely defined. Use another method.") + + def __rmul__(self, other): + if other == 1: + return self + else: + raise NotImplementedError("Product of N-dim arrays is not uniquely defined. Use another method.") + + @staticmethod + def _validate(expr, *contraction_indices): + shape = get_shape(expr) + if shape is None: + return + + # Check that no contraction happens when the shape is mismatched: + for i in contraction_indices: + if len({shape[j] for j in i if shape[j] != -1}) != 1: + raise ValueError("contracting indices of different dimensions") + + @classmethod + def _push_indices_down(cls, contraction_indices, indices): + flattened_contraction_indices = [j for i in contraction_indices for j in i] + flattened_contraction_indices.sort() + transform = _build_push_indices_down_func_transformation(flattened_contraction_indices) + return _apply_recursively_over_nested_lists(transform, indices) + + @classmethod + def _push_indices_up(cls, contraction_indices, indices): + flattened_contraction_indices = [j for i in contraction_indices for j in i] + flattened_contraction_indices.sort() + transform = _build_push_indices_up_func_transformation(flattened_contraction_indices) + return _apply_recursively_over_nested_lists(transform, indices) + + @classmethod + def _lower_contraction_to_addends(cls, expr, contraction_indices): + if isinstance(expr, ArrayAdd): + raise NotImplementedError() + if not isinstance(expr, ArrayTensorProduct): + return expr, contraction_indices + subranks = expr.subranks + cumranks = list(accumulate([0] + subranks)) + contraction_indices_remaining = [] + contraction_indices_args = [[] for i in expr.args] + backshift = set() + for contraction_group in contraction_indices: + for j in range(len(expr.args)): + if not isinstance(expr.args[j], ArrayAdd): + continue + if all(cumranks[j] <= k < cumranks[j+1] for k in contraction_group): + contraction_indices_args[j].append([k - cumranks[j] for k in contraction_group]) + backshift.update(contraction_group) + break + else: + contraction_indices_remaining.append(contraction_group) + if len(contraction_indices_remaining) == len(contraction_indices): + return expr, contraction_indices + total_rank = get_rank(expr) + shifts = list(accumulate([1 if i in backshift else 0 for i in range(total_rank)])) + contraction_indices_remaining = [Tuple.fromiter(j - shifts[j] for j in i) for i in contraction_indices_remaining] + ret = _array_tensor_product(*[ + _array_contraction(arg, *contr) for arg, contr in zip(expr.args, contraction_indices_args) + ]) + return ret, contraction_indices_remaining + + def split_multiple_contractions(self): + """ + Recognize multiple contractions and attempt at rewriting them as paired-contractions. + + This allows some contractions involving more than two indices to be + rewritten as multiple contractions involving two indices, thus allowing + the expression to be rewritten as a matrix multiplication line. + + Examples: + + * `A_ij b_j0 C_jk` ===> `A*DiagMatrix(b)*C` + + Care for: + - matrix being diagonalized (i.e. `A_ii`) + - vectors being diagonalized (i.e. `a_i0`) + + Multiple contractions can be split into matrix multiplications if + not more than two arguments are non-diagonals or non-vectors. + Vectors get diagonalized while diagonal matrices remain diagonal. + The non-diagonal matrices can be at the beginning or at the end + of the final matrix multiplication line. + """ + + editor = _EditArrayContraction(self) + + contraction_indices = self.contraction_indices + + onearray_insert = [] + + for indl, links in enumerate(contraction_indices): + if len(links) <= 2: + continue + + # Check multiple contractions: + # + # Examples: + # + # * `A_ij b_j0 C_jk` ===> `A*DiagMatrix(b)*C \otimes OneArray(1)` with permutation (1 2) + # + # Care for: + # - matrix being diagonalized (i.e. `A_ii`) + # - vectors being diagonalized (i.e. `a_i0`) + + # Multiple contractions can be split into matrix multiplications if + # not more than three arguments are non-diagonals or non-vectors. + # + # Vectors get diagonalized while diagonal matrices remain diagonal. + # The non-diagonal matrices can be at the beginning or at the end + # of the final matrix multiplication line. + + positions = editor.get_mapping_for_index(indl) + + # Also consider the case of diagonal matrices being contracted: + current_dimension = self.expr.shape[links[0]] + + not_vectors = [] + vectors = [] + for arg_ind, rel_ind in positions: + arg = editor.args_with_ind[arg_ind] + mat = arg.element + abs_arg_start, abs_arg_end = editor.get_absolute_range(arg) + other_arg_pos = 1-rel_ind + other_arg_abs = abs_arg_start + other_arg_pos + if ((1 not in mat.shape) or + ((current_dimension == 1) is True and mat.shape != (1, 1)) or + any(other_arg_abs in l for li, l in enumerate(contraction_indices) if li != indl) + ): + not_vectors.append((arg, rel_ind)) + else: + vectors.append((arg, rel_ind)) + if len(not_vectors) > 2: + # If more than two arguments in the multiple contraction are + # non-vectors and non-diagonal matrices, we cannot find a way + # to split this contraction into a matrix multiplication line: + continue + # Three cases to handle: + # - zero non-vectors + # - one non-vector + # - two non-vectors + for v, rel_ind in vectors: + v.element = diagonalize_vector(v.element) + vectors_to_loop = not_vectors[:1] + vectors + not_vectors[1:] + first_not_vector, rel_ind = vectors_to_loop[0] + new_index = first_not_vector.indices[rel_ind] + + for v, rel_ind in vectors_to_loop[1:-1]: + v.indices[rel_ind] = new_index + new_index = editor.get_new_contraction_index() + assert v.indices.index(None) == 1 - rel_ind + v.indices[v.indices.index(None)] = new_index + onearray_insert.append(v) + + last_vec, rel_ind = vectors_to_loop[-1] + last_vec.indices[rel_ind] = new_index + + for v in onearray_insert: + editor.insert_after(v, _ArgE(OneArray(1), [None])) + + return editor.to_array_contraction() + + def flatten_contraction_of_diagonal(self): + if not isinstance(self.expr, ArrayDiagonal): + return self + contraction_down = self.expr._push_indices_down(self.expr.diagonal_indices, self.contraction_indices) + new_contraction_indices = [] + diagonal_indices = self.expr.diagonal_indices[:] + for i in contraction_down: + contraction_group = list(i) + for j in i: + diagonal_with = [k for k in diagonal_indices if j in k] + contraction_group.extend([l for k in diagonal_with for l in k]) + diagonal_indices = [k for k in diagonal_indices if k not in diagonal_with] + new_contraction_indices.append(sorted(set(contraction_group))) + + new_contraction_indices = ArrayDiagonal._push_indices_up(diagonal_indices, new_contraction_indices) + return _array_contraction( + _array_diagonal( + self.expr.expr, + *diagonal_indices + ), + *new_contraction_indices + ) + + @staticmethod + def _get_free_indices_to_position_map(free_indices, contraction_indices): + free_indices_to_position = {} + flattened_contraction_indices = [j for i in contraction_indices for j in i] + counter = 0 + for ind in free_indices: + while counter in flattened_contraction_indices: + counter += 1 + free_indices_to_position[ind] = counter + counter += 1 + return free_indices_to_position + + @staticmethod + def _get_index_shifts(expr): + """ + Get the mapping of indices at the positions before the contraction + occurs. + + Examples + ======== + + >>> from sympy.tensor.array import tensorproduct, tensorcontraction + >>> from sympy import MatrixSymbol + >>> M = MatrixSymbol("M", 3, 3) + >>> N = MatrixSymbol("N", 3, 3) + >>> cg = tensorcontraction(tensorproduct(M, N), [1, 2]) + >>> cg._get_index_shifts(cg) + [0, 2] + + Indeed, ``cg`` after the contraction has two dimensions, 0 and 1. They + need to be shifted by 0 and 2 to get the corresponding positions before + the contraction (that is, 0 and 3). + """ + inner_contraction_indices = expr.contraction_indices + all_inner = [j for i in inner_contraction_indices for j in i] + all_inner.sort() + # TODO: add API for total rank and cumulative rank: + total_rank = _get_subrank(expr) + inner_rank = len(all_inner) + outer_rank = total_rank - inner_rank + shifts = [0 for i in range(outer_rank)] + counter = 0 + pointer = 0 + for i in range(outer_rank): + while pointer < inner_rank and counter >= all_inner[pointer]: + counter += 1 + pointer += 1 + shifts[i] += pointer + counter += 1 + return shifts + + @staticmethod + def _convert_outer_indices_to_inner_indices(expr, *outer_contraction_indices): + shifts = ArrayContraction._get_index_shifts(expr) + outer_contraction_indices = tuple(tuple(shifts[j] + j for j in i) for i in outer_contraction_indices) + return outer_contraction_indices + + @staticmethod + def _flatten(expr, *outer_contraction_indices): + inner_contraction_indices = expr.contraction_indices + outer_contraction_indices = ArrayContraction._convert_outer_indices_to_inner_indices(expr, *outer_contraction_indices) + contraction_indices = inner_contraction_indices + outer_contraction_indices + return _array_contraction(expr.expr, *contraction_indices) + + @classmethod + def _ArrayContraction_denest_ArrayContraction(cls, expr, *contraction_indices): + return cls._flatten(expr, *contraction_indices) + + @classmethod + def _ArrayContraction_denest_ZeroArray(cls, expr, *contraction_indices): + contraction_indices_flat = [j for i in contraction_indices for j in i] + shape = [e for i, e in enumerate(expr.shape) if i not in contraction_indices_flat] + return ZeroArray(*shape) + + @classmethod + def _ArrayContraction_denest_ArrayAdd(cls, expr, *contraction_indices): + return _array_add(*[_array_contraction(i, *contraction_indices) for i in expr.args]) + + @classmethod + def _ArrayContraction_denest_PermuteDims(cls, expr, *contraction_indices): + permutation = expr.permutation + plist = permutation.array_form + new_contraction_indices = [tuple(permutation(j) for j in i) for i in contraction_indices] + new_plist = [i for i in plist if not any(i in j for j in new_contraction_indices)] + new_plist = cls._push_indices_up(new_contraction_indices, new_plist) + return _permute_dims( + _array_contraction(expr.expr, *new_contraction_indices), + Permutation(new_plist) + ) + + @classmethod + def _ArrayContraction_denest_ArrayDiagonal(cls, expr: 'ArrayDiagonal', *contraction_indices): + diagonal_indices = list(expr.diagonal_indices) + down_contraction_indices = expr._push_indices_down(expr.diagonal_indices, contraction_indices, get_rank(expr.expr)) + # Flatten diagonally contracted indices: + down_contraction_indices = [[k for j in i for k in (j if isinstance(j, (tuple, Tuple)) else [j])] for i in down_contraction_indices] + new_contraction_indices = [] + for contr_indgrp in down_contraction_indices: + ind = contr_indgrp[:] + for j, diag_indgrp in enumerate(diagonal_indices): + if diag_indgrp is None: + continue + if any(i in diag_indgrp for i in contr_indgrp): + ind.extend(diag_indgrp) + diagonal_indices[j] = None + new_contraction_indices.append(sorted(set(ind))) + + new_diagonal_indices_down = [i for i in diagonal_indices if i is not None] + new_diagonal_indices = ArrayContraction._push_indices_up(new_contraction_indices, new_diagonal_indices_down) + return _array_diagonal( + _array_contraction(expr.expr, *new_contraction_indices), + *new_diagonal_indices + ) + + @classmethod + def _sort_fully_contracted_args(cls, expr, contraction_indices): + if expr.shape is None: + return expr, contraction_indices + cumul = list(accumulate([0] + expr.subranks)) + index_blocks = [list(range(cumul[i], cumul[i+1])) for i in range(len(expr.args))] + contraction_indices_flat = {j for i in contraction_indices for j in i} + fully_contracted = [all(j in contraction_indices_flat for j in range(cumul[i], cumul[i+1])) for i, arg in enumerate(expr.args)] + new_pos = sorted(range(len(expr.args)), key=lambda x: (0, default_sort_key(expr.args[x])) if fully_contracted[x] else (1,)) + new_args = [expr.args[i] for i in new_pos] + new_index_blocks_flat = [j for i in new_pos for j in index_blocks[i]] + index_permutation_array_form = _af_invert(new_index_blocks_flat) + new_contraction_indices = [tuple(index_permutation_array_form[j] for j in i) for i in contraction_indices] + new_contraction_indices = _sort_contraction_indices(new_contraction_indices) + return _array_tensor_product(*new_args), new_contraction_indices + + def _get_contraction_tuples(self): + r""" + Return tuples containing the argument index and position within the + argument of the index position. + + Examples + ======== + + >>> from sympy import MatrixSymbol + >>> from sympy.abc import N + >>> from sympy.tensor.array import tensorproduct, tensorcontraction + >>> A = MatrixSymbol("A", N, N) + >>> B = MatrixSymbol("B", N, N) + + >>> cg = tensorcontraction(tensorproduct(A, B), (1, 2)) + >>> cg._get_contraction_tuples() + [[(0, 1), (1, 0)]] + + Notes + ===== + + Here the contraction pair `(1, 2)` meaning that the 2nd and 3rd indices + of the tensor product `A\otimes B` are contracted, has been transformed + into `(0, 1)` and `(1, 0)`, identifying the same indices in a different + notation. `(0, 1)` is the second index (1) of the first argument (i.e. + 0 or `A`). `(1, 0)` is the first index (i.e. 0) of the second + argument (i.e. 1 or `B`). + """ + mapping = self._mapping + return [[mapping[j] for j in i] for i in self.contraction_indices] + + @staticmethod + def _contraction_tuples_to_contraction_indices(expr, contraction_tuples): + # TODO: check that `expr` has `.subranks`: + ranks = expr.subranks + cumulative_ranks = [0] + list(accumulate(ranks)) + return [tuple(cumulative_ranks[j]+k for j, k in i) for i in contraction_tuples] + + @property + def free_indices(self): + return self._free_indices[:] + + @property + def free_indices_to_position(self): + return dict(self._free_indices_to_position) + + @property + def expr(self): + return self.args[0] + + @property + def contraction_indices(self): + return self.args[1:] + + def _contraction_indices_to_components(self): + expr = self.expr + if not isinstance(expr, ArrayTensorProduct): + raise NotImplementedError("only for contractions of tensor products") + ranks = expr.subranks + mapping = {} + counter = 0 + for i, rank in enumerate(ranks): + for j in range(rank): + mapping[counter] = (i, j) + counter += 1 + return mapping + + def sort_args_by_name(self): + """ + Sort arguments in the tensor product so that their order is lexicographical. + + Examples + ======== + + >>> from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array + >>> from sympy import MatrixSymbol + >>> from sympy.abc import N + >>> A = MatrixSymbol("A", N, N) + >>> B = MatrixSymbol("B", N, N) + >>> C = MatrixSymbol("C", N, N) + >>> D = MatrixSymbol("D", N, N) + + >>> cg = convert_matrix_to_array(C*D*A*B) + >>> cg + ArrayContraction(ArrayTensorProduct(A, D, C, B), (0, 3), (1, 6), (2, 5)) + >>> cg.sort_args_by_name() + ArrayContraction(ArrayTensorProduct(A, D, B, C), (0, 3), (1, 4), (2, 7)) + """ + expr = self.expr + if not isinstance(expr, ArrayTensorProduct): + return self + args = expr.args + sorted_data = sorted(enumerate(args), key=lambda x: default_sort_key(x[1])) + pos_sorted, args_sorted = zip(*sorted_data) + reordering_map = {i: pos_sorted.index(i) for i, arg in enumerate(args)} + contraction_tuples = self._get_contraction_tuples() + contraction_tuples = [[(reordering_map[j], k) for j, k in i] for i in contraction_tuples] + c_tp = _array_tensor_product(*args_sorted) + new_contr_indices = self._contraction_tuples_to_contraction_indices( + c_tp, + contraction_tuples + ) + return _array_contraction(c_tp, *new_contr_indices) + + def _get_contraction_links(self): + r""" + Returns a dictionary of links between arguments in the tensor product + being contracted. + + See the example for an explanation of the values. + + Examples + ======== + + >>> from sympy import MatrixSymbol + >>> from sympy.abc import N + >>> from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array + >>> A = MatrixSymbol("A", N, N) + >>> B = MatrixSymbol("B", N, N) + >>> C = MatrixSymbol("C", N, N) + >>> D = MatrixSymbol("D", N, N) + + Matrix multiplications are pairwise contractions between neighboring + matrices: + + `A_{ij} B_{jk} C_{kl} D_{lm}` + + >>> cg = convert_matrix_to_array(A*B*C*D) + >>> cg + ArrayContraction(ArrayTensorProduct(B, C, A, D), (0, 5), (1, 2), (3, 6)) + + >>> cg._get_contraction_links() + {0: {0: (2, 1), 1: (1, 0)}, 1: {0: (0, 1), 1: (3, 0)}, 2: {1: (0, 0)}, 3: {0: (1, 1)}} + + This dictionary is interpreted as follows: argument in position 0 (i.e. + matrix `A`) has its second index (i.e. 1) contracted to `(1, 0)`, that + is argument in position 1 (matrix `B`) on the first index slot of `B`, + this is the contraction provided by the index `j` from `A`. + + The argument in position 1 (that is, matrix `B`) has two contractions, + the ones provided by the indices `j` and `k`, respectively the first + and second indices (0 and 1 in the sub-dict). The link `(0, 1)` and + `(2, 0)` respectively. `(0, 1)` is the index slot 1 (the 2nd) of + argument in position 0 (that is, `A_{\ldot j}`), and so on. + """ + args, dlinks = _get_contraction_links([self], self.subranks, *self.contraction_indices) + return dlinks + + def as_explicit(self): + expr = self.expr + if hasattr(expr, "as_explicit"): + expr = expr.as_explicit() + return tensorcontraction(expr, *self.contraction_indices) + + +class Reshape(_CodegenArrayAbstract): + """ + Reshape the dimensions of an array expression. + + Examples + ======== + + >>> from sympy.tensor.array.expressions import ArraySymbol, Reshape + >>> A = ArraySymbol("A", (6,)) + >>> A.shape + (6,) + >>> Reshape(A, (3, 2)).shape + (3, 2) + + Check the component-explicit forms: + + >>> A.as_explicit() + [A[0], A[1], A[2], A[3], A[4], A[5]] + >>> Reshape(A, (3, 2)).as_explicit() + [[A[0], A[1]], [A[2], A[3]], [A[4], A[5]]] + + """ + + def __new__(cls, expr, shape): + expr = _sympify(expr) + if not isinstance(shape, Tuple): + shape = Tuple(*shape) + if Equality(Mul.fromiter(expr.shape), Mul.fromiter(shape)) == False: + raise ValueError("shape mismatch") + obj = Expr.__new__(cls, expr, shape) + obj._shape = tuple(shape) + obj._expr = expr + return obj + + @property + def shape(self): + return self._shape + + @property + def expr(self): + return self._expr + + def doit(self, *args, **kwargs): + if kwargs.get("deep", True): + expr = self.expr.doit(*args, **kwargs) + else: + expr = self.expr + if isinstance(expr, (MatrixBase, NDimArray)): + return expr.reshape(*self.shape) + return Reshape(expr, self.shape) + + def as_explicit(self): + ee = self.expr + if hasattr(ee, "as_explicit"): + ee = ee.as_explicit() + if isinstance(ee, MatrixBase): + from sympy import Array + ee = Array(ee) + elif isinstance(ee, MatrixExpr): + return self + return ee.reshape(*self.shape) + + +class _ArgE: + """ + The ``_ArgE`` object contains references to the array expression + (``.element``) and a list containing the information about index + contractions (``.indices``). + + Index contractions are numbered and contracted indices show the number of + the contraction. Uncontracted indices have ``None`` value. + + For example: + ``_ArgE(M, [None, 3])`` + This object means that expression ``M`` is part of an array contraction + and has two indices, the first is not contracted (value ``None``), + the second index is contracted to the 4th (i.e. number ``3``) group of the + array contraction object. + """ + indices: list[int | None] + + def __init__(self, element, indices: list[int | None] | None = None): + self.element = element + if indices is None: + self.indices = [None for i in range(get_rank(element))] + else: + self.indices = indices + + def __str__(self): + return "_ArgE(%s, %s)" % (self.element, self.indices) + + __repr__ = __str__ + + +class _IndPos: + """ + Index position, requiring two integers in the constructor: + + - arg: the position of the argument in the tensor product, + - rel: the relative position of the index inside the argument. + """ + def __init__(self, arg: int, rel: int): + self.arg = arg + self.rel = rel + + def __str__(self): + return "_IndPos(%i, %i)" % (self.arg, self.rel) + + __repr__ = __str__ + + def __iter__(self): + yield from [self.arg, self.rel] + + +class _EditArrayContraction: + """ + Utility class to help manipulate array contraction objects. + + This class takes as input an ``ArrayContraction`` object and turns it into + an editable object. + + The field ``args_with_ind`` of this class is a list of ``_ArgE`` objects + which can be used to easily edit the contraction structure of the + expression. + + Once editing is finished, the ``ArrayContraction`` object may be recreated + by calling the ``.to_array_contraction()`` method. + """ + + def __init__(self, base_array: typing.Union[ArrayContraction, ArrayDiagonal, ArrayTensorProduct]): + + expr: Basic + diagonalized: tuple[tuple[int, ...], ...] + contraction_indices: list[tuple[int]] + if isinstance(base_array, ArrayContraction): + mapping = _get_mapping_from_subranks(base_array.subranks) + expr = base_array.expr + contraction_indices = base_array.contraction_indices + diagonalized = () + elif isinstance(base_array, ArrayDiagonal): + + if isinstance(base_array.expr, ArrayContraction): + mapping = _get_mapping_from_subranks(base_array.expr.subranks) + expr = base_array.expr.expr + diagonalized = ArrayContraction._push_indices_down(base_array.expr.contraction_indices, base_array.diagonal_indices) + contraction_indices = base_array.expr.contraction_indices + elif isinstance(base_array.expr, ArrayTensorProduct): + mapping = {} + expr = base_array.expr + diagonalized = base_array.diagonal_indices + contraction_indices = [] + else: + mapping = {} + expr = base_array.expr + diagonalized = base_array.diagonal_indices + contraction_indices = [] + + elif isinstance(base_array, ArrayTensorProduct): + expr = base_array + contraction_indices = [] + diagonalized = () + else: + raise NotImplementedError() + + if isinstance(expr, ArrayTensorProduct): + args = list(expr.args) + else: + args = [expr] + + args_with_ind: list[_ArgE] = [_ArgE(arg) for arg in args] + for i, contraction_tuple in enumerate(contraction_indices): + for j in contraction_tuple: + arg_pos, rel_pos = mapping[j] + args_with_ind[arg_pos].indices[rel_pos] = i + self.args_with_ind: list[_ArgE] = args_with_ind + self.number_of_contraction_indices: int = len(contraction_indices) + self._track_permutation: list[list[int]] | None = None + + mapping = _get_mapping_from_subranks(base_array.subranks) + + # Trick: add diagonalized indices as negative indices into the editor object: + for i, e in enumerate(diagonalized): + for j in e: + arg_pos, rel_pos = mapping[j] + self.args_with_ind[arg_pos].indices[rel_pos] = -1 - i + + def insert_after(self, arg: _ArgE, new_arg: _ArgE): + pos = self.args_with_ind.index(arg) + self.args_with_ind.insert(pos + 1, new_arg) + + def get_new_contraction_index(self): + self.number_of_contraction_indices += 1 + return self.number_of_contraction_indices - 1 + + def refresh_indices(self): + updates = {} + for arg_with_ind in self.args_with_ind: + updates.update({i: -1 for i in arg_with_ind.indices if i is not None}) + for i, e in enumerate(sorted(updates)): + updates[e] = i + self.number_of_contraction_indices = len(updates) + for arg_with_ind in self.args_with_ind: + arg_with_ind.indices = [updates.get(i, None) for i in arg_with_ind.indices] + + def merge_scalars(self): + scalars = [] + for arg_with_ind in self.args_with_ind: + if len(arg_with_ind.indices) == 0: + scalars.append(arg_with_ind) + for i in scalars: + self.args_with_ind.remove(i) + scalar = Mul.fromiter([i.element for i in scalars]) + if len(self.args_with_ind) == 0: + self.args_with_ind.append(_ArgE(scalar)) + else: + from sympy.tensor.array.expressions.from_array_to_matrix import _a2m_tensor_product + self.args_with_ind[0].element = _a2m_tensor_product(scalar, self.args_with_ind[0].element) + + def to_array_contraction(self): + + # Count the ranks of the arguments: + counter = 0 + # Create a collector for the new diagonal indices: + diag_indices = defaultdict(list) + + count_index_freq = Counter() + for arg_with_ind in self.args_with_ind: + count_index_freq.update(Counter(arg_with_ind.indices)) + + free_index_count = count_index_freq[None] + + # Construct the inverse permutation: + inv_perm1 = [] + inv_perm2 = [] + # Keep track of which diagonal indices have already been processed: + done = set() + + # Counter for the diagonal indices: + counter4 = 0 + + for arg_with_ind in self.args_with_ind: + # If some diagonalization axes have been removed, they should be + # permuted in order to keep the permutation. + # Add permutation here + counter2 = 0 # counter for the indices + for i in arg_with_ind.indices: + if i is None: + inv_perm1.append(counter4) + counter2 += 1 + counter4 += 1 + continue + if i >= 0: + continue + # Reconstruct the diagonal indices: + diag_indices[-1 - i].append(counter + counter2) + if count_index_freq[i] == 1 and i not in done: + inv_perm1.append(free_index_count - 1 - i) + done.add(i) + elif i not in done: + inv_perm2.append(free_index_count - 1 - i) + done.add(i) + counter2 += 1 + # Remove negative indices to restore a proper editor object: + arg_with_ind.indices = [i if i is not None and i >= 0 else None for i in arg_with_ind.indices] + counter += len([i for i in arg_with_ind.indices if i is None or i < 0]) + + inverse_permutation = inv_perm1 + inv_perm2 + permutation = _af_invert(inverse_permutation) + + # Get the diagonal indices after the detection of HadamardProduct in the expression: + diag_indices_filtered = [tuple(v) for v in diag_indices.values() if len(v) > 1] + + self.merge_scalars() + self.refresh_indices() + args = [arg.element for arg in self.args_with_ind] + contraction_indices = self.get_contraction_indices() + expr = _array_contraction(_array_tensor_product(*args), *contraction_indices) + expr2 = _array_diagonal(expr, *diag_indices_filtered) + if self._track_permutation is not None: + permutation2 = _af_invert([j for i in self._track_permutation for j in i]) + expr2 = _permute_dims(expr2, permutation2) + + expr3 = _permute_dims(expr2, permutation) + return expr3 + + def get_contraction_indices(self) -> list[list[int]]: + contraction_indices: list[list[int]] = [[] for i in range(self.number_of_contraction_indices)] + current_position: int = 0 + for arg_with_ind in self.args_with_ind: + for j in arg_with_ind.indices: + if j is not None: + contraction_indices[j].append(current_position) + current_position += 1 + return contraction_indices + + def get_mapping_for_index(self, ind) -> list[_IndPos]: + if ind >= self.number_of_contraction_indices: + raise ValueError("index value exceeding the index range") + positions: list[_IndPos] = [] + for i, arg_with_ind in enumerate(self.args_with_ind): + for j, arg_ind in enumerate(arg_with_ind.indices): + if ind == arg_ind: + positions.append(_IndPos(i, j)) + return positions + + def get_contraction_indices_to_ind_rel_pos(self) -> list[list[_IndPos]]: + contraction_indices: list[list[_IndPos]] = [[] for i in range(self.number_of_contraction_indices)] + for i, arg_with_ind in enumerate(self.args_with_ind): + for j, ind in enumerate(arg_with_ind.indices): + if ind is not None: + contraction_indices[ind].append(_IndPos(i, j)) + return contraction_indices + + def count_args_with_index(self, index: int) -> int: + """ + Count the number of arguments that have the given index. + """ + counter: int = 0 + for arg_with_ind in self.args_with_ind: + if index in arg_with_ind.indices: + counter += 1 + return counter + + def get_args_with_index(self, index: int) -> list[_ArgE]: + """ + Get a list of arguments having the given index. + """ + ret: list[_ArgE] = [i for i in self.args_with_ind if index in i.indices] + return ret + + @property + def number_of_diagonal_indices(self): + data = set() + for arg in self.args_with_ind: + data.update({i for i in arg.indices if i is not None and i < 0}) + return len(data) + + def track_permutation_start(self): + permutation = [] + perm_diag = [] + counter = 0 + counter2 = -1 + for arg_with_ind in self.args_with_ind: + perm = [] + for i in arg_with_ind.indices: + if i is not None: + if i < 0: + perm_diag.append(counter2) + counter2 -= 1 + continue + perm.append(counter) + counter += 1 + permutation.append(perm) + max_ind = max(max(i) if i else -1 for i in permutation) if permutation else -1 + perm_diag = [max_ind - i for i in perm_diag] + self._track_permutation = permutation + [perm_diag] + + def track_permutation_merge(self, destination: _ArgE, from_element: _ArgE): + index_destination = self.args_with_ind.index(destination) + index_element = self.args_with_ind.index(from_element) + self._track_permutation[index_destination].extend(self._track_permutation[index_element]) # type: ignore + self._track_permutation.pop(index_element) # type: ignore + + def get_absolute_free_range(self, arg: _ArgE) -> typing.Tuple[int, int]: + """ + Return the range of the free indices of the arg as absolute positions + among all free indices. + """ + counter = 0 + for arg_with_ind in self.args_with_ind: + number_free_indices = len([i for i in arg_with_ind.indices if i is None]) + if arg_with_ind == arg: + return counter, counter + number_free_indices + counter += number_free_indices + raise IndexError("argument not found") + + def get_absolute_range(self, arg: _ArgE) -> typing.Tuple[int, int]: + """ + Return the absolute range of indices for arg, disregarding dummy + indices. + """ + counter = 0 + for arg_with_ind in self.args_with_ind: + number_indices = len(arg_with_ind.indices) + if arg_with_ind == arg: + return counter, counter + number_indices + counter += number_indices + raise IndexError("argument not found") + + +def get_rank(expr): + if isinstance(expr, (MatrixExpr, MatrixElement)): + return 2 + if isinstance(expr, _CodegenArrayAbstract): + return len(expr.shape) + if isinstance(expr, NDimArray): + return expr.rank() + if isinstance(expr, Indexed): + return expr.rank + if isinstance(expr, IndexedBase): + shape = expr.shape + if shape is None: + return -1 + else: + return len(shape) + if hasattr(expr, "shape"): + return len(expr.shape) + return 0 + + +def _get_subrank(expr): + if isinstance(expr, _CodegenArrayAbstract): + return expr.subrank() + return get_rank(expr) + + +def _get_subranks(expr): + if isinstance(expr, _CodegenArrayAbstract): + return expr.subranks + else: + return [get_rank(expr)] + + +def get_shape(expr): + if hasattr(expr, "shape"): + return expr.shape + return () + + +def nest_permutation(expr): + if isinstance(expr, PermuteDims): + return expr.nest_permutation() + else: + return expr + + +def _array_tensor_product(*args, **kwargs): + return ArrayTensorProduct(*args, canonicalize=True, **kwargs) + + +def _array_contraction(expr, *contraction_indices, **kwargs): + return ArrayContraction(expr, *contraction_indices, canonicalize=True, **kwargs) + + +def _array_diagonal(expr, *diagonal_indices, **kwargs): + return ArrayDiagonal(expr, *diagonal_indices, canonicalize=True, **kwargs) + + +def _permute_dims(expr, permutation, **kwargs): + return PermuteDims(expr, permutation, canonicalize=True, **kwargs) + + +def _array_add(*args, **kwargs): + return ArrayAdd(*args, canonicalize=True, **kwargs) + + +def _get_array_element_or_slice(expr, indices): + return ArrayElement(expr, indices) diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/arrayexpr_derivatives.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/arrayexpr_derivatives.py new file mode 100644 index 0000000000000000000000000000000000000000..ab44a6fbf715ac7f2b8c287dcc84a49289f2dd76 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/arrayexpr_derivatives.py @@ -0,0 +1,194 @@ +import operator +from functools import reduce, singledispatch + +from sympy.core.expr import Expr +from sympy.core.singleton import S +from sympy.matrices.expressions.hadamard import HadamardProduct +from sympy.matrices.expressions.inverse import Inverse +from sympy.matrices.expressions.matexpr import (MatrixExpr, MatrixSymbol) +from sympy.matrices.expressions.special import Identity, OneMatrix +from sympy.matrices.expressions.transpose import Transpose +from sympy.combinatorics.permutations import _af_invert +from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction +from sympy.tensor.array.expressions.array_expressions import ( + _ArrayExpr, ZeroArray, ArraySymbol, ArrayTensorProduct, ArrayAdd, + PermuteDims, ArrayDiagonal, ArrayElementwiseApplyFunc, get_rank, + get_shape, ArrayContraction, _array_tensor_product, _array_contraction, + _array_diagonal, _array_add, _permute_dims, Reshape) +from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array + + +@singledispatch +def array_derive(expr, x): + """ + Derivatives (gradients) for array expressions. + """ + raise NotImplementedError(f"not implemented for type {type(expr)}") + + +@array_derive.register(Expr) +def _(expr: Expr, x: _ArrayExpr): + return ZeroArray(*x.shape) + + +@array_derive.register(ArrayTensorProduct) +def _(expr: ArrayTensorProduct, x: Expr): + args = expr.args + addend_list = [] + for i, arg in enumerate(expr.args): + darg = array_derive(arg, x) + if darg == 0: + continue + args_prev = args[:i] + args_succ = args[i+1:] + shape_prev = reduce(operator.add, map(get_shape, args_prev), ()) + shape_succ = reduce(operator.add, map(get_shape, args_succ), ()) + addend = _array_tensor_product(*args_prev, darg, *args_succ) + tot1 = len(get_shape(x)) + tot2 = tot1 + len(shape_prev) + tot3 = tot2 + len(get_shape(arg)) + tot4 = tot3 + len(shape_succ) + perm = list(range(tot1, tot2)) + \ + list(range(tot1)) + list(range(tot2, tot3)) + \ + list(range(tot3, tot4)) + addend = _permute_dims(addend, _af_invert(perm)) + addend_list.append(addend) + if len(addend_list) == 1: + return addend_list[0] + elif len(addend_list) == 0: + return S.Zero + else: + return _array_add(*addend_list) + + +@array_derive.register(ArraySymbol) +def _(expr: ArraySymbol, x: _ArrayExpr): + if expr == x: + return _permute_dims( + ArrayTensorProduct.fromiter(Identity(i) for i in expr.shape), + [2*i for i in range(len(expr.shape))] + [2*i+1 for i in range(len(expr.shape))] + ) + return ZeroArray(*(x.shape + expr.shape)) + + +@array_derive.register(MatrixSymbol) +def _(expr: MatrixSymbol, x: _ArrayExpr): + m, n = expr.shape + if expr == x: + return _permute_dims( + _array_tensor_product(Identity(m), Identity(n)), + [0, 2, 1, 3] + ) + return ZeroArray(*(x.shape + expr.shape)) + + +@array_derive.register(Identity) +def _(expr: Identity, x: _ArrayExpr): + return ZeroArray(*(x.shape + expr.shape)) + + +@array_derive.register(OneMatrix) +def _(expr: OneMatrix, x: _ArrayExpr): + return ZeroArray(*(x.shape + expr.shape)) + + +@array_derive.register(Transpose) +def _(expr: Transpose, x: Expr): + # D(A.T, A) ==> (m,n,i,j) ==> D(A_ji, A_mn) = d_mj d_ni + # D(B.T, A) ==> (m,n,i,j) ==> D(B_ji, A_mn) + fd = array_derive(expr.arg, x) + return _permute_dims(fd, [0, 1, 3, 2]) + + +@array_derive.register(Inverse) +def _(expr: Inverse, x: Expr): + mat = expr.I + dexpr = array_derive(mat, x) + tp = _array_tensor_product(-expr, dexpr, expr) + mp = _array_contraction(tp, (1, 4), (5, 6)) + pp = _permute_dims(mp, [1, 2, 0, 3]) + return pp + + +@array_derive.register(ElementwiseApplyFunction) +def _(expr: ElementwiseApplyFunction, x: Expr): + assert get_rank(expr) == 2 + assert get_rank(x) == 2 + fdiff = expr._get_function_fdiff() + dexpr = array_derive(expr.expr, x) + tp = _array_tensor_product( + ElementwiseApplyFunction(fdiff, expr.expr), + dexpr + ) + td = _array_diagonal( + tp, (0, 4), (1, 5) + ) + return td + + +@array_derive.register(ArrayElementwiseApplyFunc) +def _(expr: ArrayElementwiseApplyFunc, x: Expr): + fdiff = expr._get_function_fdiff() + subexpr = expr.expr + dsubexpr = array_derive(subexpr, x) + tp = _array_tensor_product( + dsubexpr, + ArrayElementwiseApplyFunc(fdiff, subexpr) + ) + b = get_rank(x) + c = get_rank(expr) + diag_indices = [(b + i, b + c + i) for i in range(c)] + return _array_diagonal(tp, *diag_indices) + + +@array_derive.register(MatrixExpr) +def _(expr: MatrixExpr, x: Expr): + cg = convert_matrix_to_array(expr) + return array_derive(cg, x) + + +@array_derive.register(HadamardProduct) +def _(expr: HadamardProduct, x: Expr): + raise NotImplementedError() + + +@array_derive.register(ArrayContraction) +def _(expr: ArrayContraction, x: Expr): + fd = array_derive(expr.expr, x) + rank_x = len(get_shape(x)) + contraction_indices = expr.contraction_indices + new_contraction_indices = [tuple(j + rank_x for j in i) for i in contraction_indices] + return _array_contraction(fd, *new_contraction_indices) + + +@array_derive.register(ArrayDiagonal) +def _(expr: ArrayDiagonal, x: Expr): + dsubexpr = array_derive(expr.expr, x) + rank_x = len(get_shape(x)) + diag_indices = [[j + rank_x for j in i] for i in expr.diagonal_indices] + return _array_diagonal(dsubexpr, *diag_indices) + + +@array_derive.register(ArrayAdd) +def _(expr: ArrayAdd, x: Expr): + return _array_add(*[array_derive(arg, x) for arg in expr.args]) + + +@array_derive.register(PermuteDims) +def _(expr: PermuteDims, x: Expr): + de = array_derive(expr.expr, x) + perm = [0, 1] + [i + 2 for i in expr.permutation.array_form] + return _permute_dims(de, perm) + + +@array_derive.register(Reshape) +def _(expr: Reshape, x: Expr): + de = array_derive(expr.expr, x) + return Reshape(de, get_shape(x) + expr.shape) + + +def matrix_derive(expr, x): + from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix + ce = convert_matrix_to_array(expr) + dce = array_derive(ce, x) + return convert_array_to_matrix(dce).doit() diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/conv_array_to_indexed.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/conv_array_to_indexed.py new file mode 100644 index 0000000000000000000000000000000000000000..1929c3401e131cca0a83080131ead9198b37bcbb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/conv_array_to_indexed.py @@ -0,0 +1,12 @@ +from sympy.tensor.array.expressions import from_array_to_indexed +from sympy.utilities.decorator import deprecated + + +_conv_to_from_decorator = deprecated( + "module has been renamed by replacing 'conv_' with 'from_' in its name", + deprecated_since_version="1.11", + active_deprecations_target="deprecated-conv-array-expr-module-names", +) + + +convert_array_to_indexed = _conv_to_from_decorator(from_array_to_indexed.convert_array_to_indexed) diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/conv_array_to_matrix.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/conv_array_to_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..2708e74aaa98d6ee38eae46d97d4483a546e0776 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/conv_array_to_matrix.py @@ -0,0 +1,6 @@ +from sympy.tensor.array.expressions import from_array_to_matrix +from sympy.tensor.array.expressions.conv_array_to_indexed import _conv_to_from_decorator + +convert_array_to_matrix = _conv_to_from_decorator(from_array_to_matrix.convert_array_to_matrix) +_array2matrix = _conv_to_from_decorator(from_array_to_matrix._array2matrix) +_remove_trivial_dims = _conv_to_from_decorator(from_array_to_matrix._remove_trivial_dims) diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/conv_indexed_to_array.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/conv_indexed_to_array.py new file mode 100644 index 0000000000000000000000000000000000000000..6058b31f20778834ea23a01553d594b7965eb6bb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/conv_indexed_to_array.py @@ -0,0 +1,4 @@ +from sympy.tensor.array.expressions import from_indexed_to_array +from sympy.tensor.array.expressions.conv_array_to_indexed import _conv_to_from_decorator + +convert_indexed_to_array = _conv_to_from_decorator(from_indexed_to_array.convert_indexed_to_array) diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/conv_matrix_to_array.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/conv_matrix_to_array.py new file mode 100644 index 0000000000000000000000000000000000000000..46469df60703c237527c0b2834235309640afe7c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/conv_matrix_to_array.py @@ -0,0 +1,4 @@ +from sympy.tensor.array.expressions import from_matrix_to_array +from sympy.tensor.array.expressions.conv_array_to_indexed import _conv_to_from_decorator + +convert_matrix_to_array = _conv_to_from_decorator(from_matrix_to_array.convert_matrix_to_array) diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/from_array_to_indexed.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/from_array_to_indexed.py new file mode 100644 index 0000000000000000000000000000000000000000..9eb86e7cfbe31ebfe7c9649803d9cb5e34b98276 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/from_array_to_indexed.py @@ -0,0 +1,84 @@ +import collections.abc +import operator +from itertools import accumulate + +from sympy import Mul, Sum, Dummy, Add +from sympy.tensor.array.expressions import PermuteDims, ArrayAdd, ArrayElementwiseApplyFunc, Reshape +from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, get_rank, ArrayContraction, \ + ArrayDiagonal, get_shape, _get_array_element_or_slice, _ArrayExpr +from sympy.tensor.array.expressions.utils import _apply_permutation_to_list + + +def convert_array_to_indexed(expr, indices): + return _ConvertArrayToIndexed().do_convert(expr, indices) + + +class _ConvertArrayToIndexed: + + def __init__(self): + self.count_dummies = 0 + + def do_convert(self, expr, indices): + if isinstance(expr, ArrayTensorProduct): + cumul = list(accumulate([0] + [get_rank(arg) for arg in expr.args])) + indices_grp = [indices[cumul[i]:cumul[i+1]] for i in range(len(expr.args))] + return Mul.fromiter(self.do_convert(arg, ind) for arg, ind in zip(expr.args, indices_grp)) + if isinstance(expr, ArrayContraction): + new_indices = [None for i in range(get_rank(expr.expr))] + limits = [] + bottom_shape = get_shape(expr.expr) + for contraction_index_grp in expr.contraction_indices: + d = Dummy(f"d{self.count_dummies}") + self.count_dummies += 1 + dim = bottom_shape[contraction_index_grp[0]] + limits.append((d, 0, dim-1)) + for i in contraction_index_grp: + new_indices[i] = d + j = 0 + for i in range(len(new_indices)): + if new_indices[i] is None: + new_indices[i] = indices[j] + j += 1 + newexpr = self.do_convert(expr.expr, new_indices) + return Sum(newexpr, *limits) + if isinstance(expr, ArrayDiagonal): + new_indices = [None for i in range(get_rank(expr.expr))] + ind_pos = expr._push_indices_down(expr.diagonal_indices, list(range(len(indices))), get_rank(expr)) + for i, index in zip(ind_pos, indices): + if isinstance(i, collections.abc.Iterable): + for j in i: + new_indices[j] = index + else: + new_indices[i] = index + newexpr = self.do_convert(expr.expr, new_indices) + return newexpr + if isinstance(expr, PermuteDims): + permuted_indices = _apply_permutation_to_list(expr.permutation, indices) + return self.do_convert(expr.expr, permuted_indices) + if isinstance(expr, ArrayAdd): + return Add.fromiter(self.do_convert(arg, indices) for arg in expr.args) + if isinstance(expr, _ArrayExpr): + return expr.__getitem__(tuple(indices)) + if isinstance(expr, ArrayElementwiseApplyFunc): + return expr.function(self.do_convert(expr.expr, indices)) + if isinstance(expr, Reshape): + shape_up = expr.shape + shape_down = get_shape(expr.expr) + cumul = list(accumulate([1] + list(reversed(shape_up)), operator.mul)) + one_index = Add.fromiter(i*s for i, s in zip(reversed(indices), cumul)) + dest_indices = [None for _ in shape_down] + c = 1 + for i, e in enumerate(reversed(shape_down)): + if c == 1: + if i == len(shape_down) - 1: + dest_indices[i] = one_index + else: + dest_indices[i] = one_index % e + elif i == len(shape_down) - 1: + dest_indices[i] = one_index // c + else: + dest_indices[i] = one_index // c % e + c *= e + dest_indices.reverse() + return self.do_convert(expr.expr, dest_indices) + return _get_array_element_or_slice(expr, indices) diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/from_array_to_matrix.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/from_array_to_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..debfdd7eb5c4533996b3d72b55d679be3daf3afe --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/from_array_to_matrix.py @@ -0,0 +1,1004 @@ +from __future__ import annotations +import itertools +from collections import defaultdict +from typing import FrozenSet +from functools import singledispatch +from itertools import accumulate + +from sympy import MatMul, Basic, Wild, KroneckerProduct +from sympy.assumptions.ask import (Q, ask) +from sympy.core.mul import Mul +from sympy.core.singleton import S +from sympy.matrices.expressions.diagonal import DiagMatrix +from sympy.matrices.expressions.hadamard import hadamard_product, HadamardPower +from sympy.matrices.expressions.matexpr import MatrixExpr +from sympy.matrices.expressions.special import (Identity, ZeroMatrix, OneMatrix) +from sympy.matrices.expressions.trace import Trace +from sympy.matrices.expressions.transpose import Transpose +from sympy.combinatorics.permutations import _af_invert, Permutation +from sympy.matrices.matrixbase import MatrixBase +from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction +from sympy.matrices.expressions.matexpr import MatrixElement +from sympy.tensor.array.expressions.array_expressions import PermuteDims, ArrayDiagonal, \ + ArrayTensorProduct, OneArray, get_rank, _get_subrank, ZeroArray, ArrayContraction, \ + ArrayAdd, _CodegenArrayAbstract, get_shape, ArrayElementwiseApplyFunc, _ArrayExpr, _EditArrayContraction, _ArgE, \ + ArrayElement, _array_tensor_product, _array_contraction, _array_diagonal, _array_add, _permute_dims +from sympy.tensor.array.expressions.utils import _get_mapping_from_subranks + + +def _get_candidate_for_matmul_from_contraction(scan_indices: list[int | None], remaining_args: list[_ArgE]) -> tuple[_ArgE | None, bool, int]: + + scan_indices_int: list[int] = [i for i in scan_indices if i is not None] + if len(scan_indices_int) == 0: + return None, False, -1 + + transpose: bool = False + candidate: _ArgE | None = None + candidate_index: int = -1 + for arg_with_ind2 in remaining_args: + if not isinstance(arg_with_ind2.element, MatrixExpr): + continue + for index in scan_indices_int: + if candidate_index != -1 and candidate_index != index: + # A candidate index has already been selected, check + # repetitions only for that index: + continue + if index in arg_with_ind2.indices: + if set(arg_with_ind2.indices) == {index}: + # Index repeated twice in arg_with_ind2 + candidate = None + break + if candidate is None: + candidate = arg_with_ind2 + candidate_index = index + transpose = (index == arg_with_ind2.indices[1]) + else: + # Index repeated more than twice, break + candidate = None + break + return candidate, transpose, candidate_index + + +def _insert_candidate_into_editor(editor: _EditArrayContraction, arg_with_ind: _ArgE, candidate: _ArgE, transpose1: bool, transpose2: bool): + other = candidate.element + other_index: int | None + if transpose2: + other = Transpose(other) + other_index = candidate.indices[0] + else: + other_index = candidate.indices[1] + new_element = (Transpose(arg_with_ind.element) if transpose1 else arg_with_ind.element) * other + editor.args_with_ind.remove(candidate) + new_arge = _ArgE(new_element) + return new_arge, other_index + + +def _support_function_tp1_recognize(contraction_indices, args): + if len(contraction_indices) == 0: + return _a2m_tensor_product(*args) + + ac = _array_contraction(_array_tensor_product(*args), *contraction_indices) + editor = _EditArrayContraction(ac) + editor.track_permutation_start() + + while True: + flag_stop = True + for i, arg_with_ind in enumerate(editor.args_with_ind): + if not isinstance(arg_with_ind.element, MatrixExpr): + continue + + first_index = arg_with_ind.indices[0] + second_index = arg_with_ind.indices[1] + + first_frequency = editor.count_args_with_index(first_index) + second_frequency = editor.count_args_with_index(second_index) + + if first_index is not None and first_frequency == 1 and first_index == second_index: + flag_stop = False + arg_with_ind.element = Trace(arg_with_ind.element)._normalize() + arg_with_ind.indices = [] + break + + scan_indices = [] + if first_frequency == 2: + scan_indices.append(first_index) + if second_frequency == 2: + scan_indices.append(second_index) + + candidate, transpose, found_index = _get_candidate_for_matmul_from_contraction(scan_indices, editor.args_with_ind[i+1:]) + if candidate is not None: + flag_stop = False + editor.track_permutation_merge(arg_with_ind, candidate) + transpose1 = found_index == first_index + new_arge, other_index = _insert_candidate_into_editor(editor, arg_with_ind, candidate, transpose1, transpose) + if found_index == first_index: + new_arge.indices = [second_index, other_index] + else: + new_arge.indices = [first_index, other_index] + set_indices = set(new_arge.indices) + if len(set_indices) == 1 and set_indices != {None}: + # This is a trace: + new_arge.element = Trace(new_arge.element)._normalize() + new_arge.indices = [] + editor.args_with_ind[i] = new_arge + # TODO: is this break necessary? + break + + if flag_stop: + break + + editor.refresh_indices() + return editor.to_array_contraction() + + +def _find_trivial_matrices_rewrite(expr: ArrayTensorProduct): + # If there are matrices of trivial shape in the tensor product (i.e. shape + # (1, 1)), try to check if there is a suitable non-trivial MatMul where the + # expression can be inserted. + + # For example, if "a" has shape (1, 1) and "b" has shape (k, 1), the + # expressions "_array_tensor_product(a, b*b.T)" can be rewritten as + # "b*a*b.T" + + trivial_matrices = [] + pos: int | None = None # must be initialized else causes UnboundLocalError + first: MatrixExpr | None = None # may cause UnboundLocalError if not initialized + second: MatrixExpr | None = None # may cause UnboundLocalError if not initialized + removed: list[int] = [] + counter: int = 0 + args: list[Basic | None] = list(expr.args) + for i, arg in enumerate(expr.args): + if isinstance(arg, MatrixExpr): + if arg.shape == (1, 1): + trivial_matrices.append(arg) + args[i] = None + removed.extend([counter, counter+1]) + elif pos is None and isinstance(arg, MatMul): + margs = arg.args + for j, e in enumerate(margs): + if isinstance(e, MatrixExpr) and e.shape[1] == 1: + pos = i + first = MatMul.fromiter(margs[:j+1]) + second = MatMul.fromiter(margs[j+1:]) + break + counter += get_rank(arg) + if pos is None: + return expr, [] + args[pos] = (first*MatMul.fromiter(i for i in trivial_matrices)*second).doit() + return _array_tensor_product(*[i for i in args if i is not None]), removed + + +def _find_trivial_kronecker_products_broadcast(expr: ArrayTensorProduct): + newargs: list[Basic] = [] + removed = [] + count_dims = 0 + for arg in expr.args: + count_dims += get_rank(arg) + shape = get_shape(arg) + current_range = [count_dims-i for i in range(len(shape), 0, -1)] + if (shape == (1, 1) and len(newargs) > 0 and 1 not in get_shape(newargs[-1]) and + isinstance(newargs[-1], MatrixExpr) and isinstance(arg, MatrixExpr)): + # KroneckerProduct object allows the trick of broadcasting: + newargs[-1] = KroneckerProduct(newargs[-1], arg) + removed.extend(current_range) + elif 1 not in shape and len(newargs) > 0 and get_shape(newargs[-1]) == (1, 1): + # Broadcast: + newargs[-1] = KroneckerProduct(newargs[-1], arg) + prev_range = [i for i in range(min(current_range)) if i not in removed] + removed.extend(prev_range[-2:]) + else: + newargs.append(arg) + return _array_tensor_product(*newargs), removed + + +@singledispatch +def _array2matrix(expr): + return expr + + +@_array2matrix.register(ZeroArray) +def _(expr: ZeroArray): + if get_rank(expr) == 2: + return ZeroMatrix(*expr.shape) + else: + return expr + + +@_array2matrix.register(ArrayTensorProduct) +def _(expr: ArrayTensorProduct): + return _a2m_tensor_product(*[_array2matrix(arg) for arg in expr.args]) + + +@_array2matrix.register(ArrayContraction) +def _(expr: ArrayContraction): + expr = expr.flatten_contraction_of_diagonal() + expr = identify_removable_identity_matrices(expr) + expr = expr.split_multiple_contractions() + expr = identify_hadamard_products(expr) + if not isinstance(expr, ArrayContraction): + return _array2matrix(expr) + subexpr = expr.expr + contraction_indices: tuple[tuple[int]] = expr.contraction_indices + if contraction_indices == ((0,), (1,)) or ( + contraction_indices == ((0,),) and subexpr.shape[1] == 1 + ) or ( + contraction_indices == ((1,),) and subexpr.shape[0] == 1 + ): + shape = subexpr.shape + subexpr = _array2matrix(subexpr) + if isinstance(subexpr, MatrixExpr): + return OneMatrix(1, shape[0])*subexpr*OneMatrix(shape[1], 1) + if isinstance(subexpr, ArrayTensorProduct): + newexpr = _array_contraction(_array2matrix(subexpr), *contraction_indices) + contraction_indices = newexpr.contraction_indices + if any(i > 2 for i in newexpr.subranks): + addends = _array_add(*[_a2m_tensor_product(*j) for j in itertools.product(*[i.args if isinstance(i, + ArrayAdd) else [i] for i in expr.expr.args])]) + newexpr = _array_contraction(addends, *contraction_indices) + if isinstance(newexpr, ArrayAdd): + ret = _array2matrix(newexpr) + return ret + assert isinstance(newexpr, ArrayContraction) + ret = _support_function_tp1_recognize(contraction_indices, list(newexpr.expr.args)) + return ret + elif not isinstance(subexpr, _CodegenArrayAbstract): + ret = _array2matrix(subexpr) + if isinstance(ret, MatrixExpr): + assert expr.contraction_indices == ((0, 1),) + return _a2m_trace(ret) + else: + return _array_contraction(ret, *expr.contraction_indices) + + +@_array2matrix.register(ArrayDiagonal) +def _(expr: ArrayDiagonal): + pexpr = _array_diagonal(_array2matrix(expr.expr), *expr.diagonal_indices) + pexpr = identify_hadamard_products(pexpr) + if isinstance(pexpr, ArrayDiagonal): + pexpr = _array_diag2contr_diagmatrix(pexpr) + if expr == pexpr: + return expr + return _array2matrix(pexpr) + + +@_array2matrix.register(PermuteDims) +def _(expr: PermuteDims): + if expr.permutation.array_form == [1, 0]: + return _a2m_transpose(_array2matrix(expr.expr)) + elif isinstance(expr.expr, ArrayTensorProduct): + ranks = expr.expr.subranks + inv_permutation = expr.permutation**(-1) + newrange = [inv_permutation(i) for i in range(sum(ranks))] + newpos = [] + counter = 0 + for rank in ranks: + newpos.append(newrange[counter:counter+rank]) + counter += rank + newargs = [] + newperm = [] + scalars = [] + for pos, arg in zip(newpos, expr.expr.args): + if len(pos) == 0: + scalars.append(_array2matrix(arg)) + elif pos == sorted(pos): + newargs.append((_array2matrix(arg), pos[0])) + newperm.extend(pos) + elif len(pos) == 2: + newargs.append((_a2m_transpose(_array2matrix(arg)), pos[0])) + newperm.extend(reversed(pos)) + else: + raise NotImplementedError() + newargs = [i[0] for i in newargs] + return _permute_dims(_a2m_tensor_product(*scalars, *newargs), _af_invert(newperm)) + elif isinstance(expr.expr, ArrayContraction): + mat_mul_lines = _array2matrix(expr.expr) + if not isinstance(mat_mul_lines, ArrayTensorProduct): + return _permute_dims(mat_mul_lines, expr.permutation) + # TODO: this assumes that all arguments are matrices, it may not be the case: + permutation = Permutation(2*len(mat_mul_lines.args)-1)*expr.permutation + permuted = [permutation(i) for i in range(2*len(mat_mul_lines.args))] + args_array = [None for i in mat_mul_lines.args] + for i in range(len(mat_mul_lines.args)): + p1 = permuted[2*i] + p2 = permuted[2*i+1] + if p1 // 2 != p2 // 2: + return _permute_dims(mat_mul_lines, permutation) + if p1 > p2: + args_array[i] = _a2m_transpose(mat_mul_lines.args[p1 // 2]) + else: + args_array[i] = mat_mul_lines.args[p1 // 2] + return _a2m_tensor_product(*args_array) + else: + return expr + + +@_array2matrix.register(ArrayAdd) +def _(expr: ArrayAdd): + addends = [_array2matrix(arg) for arg in expr.args] + return _a2m_add(*addends) + + +@_array2matrix.register(ArrayElementwiseApplyFunc) +def _(expr: ArrayElementwiseApplyFunc): + subexpr = _array2matrix(expr.expr) + if isinstance(subexpr, MatrixExpr): + if subexpr.shape != (1, 1): + d = expr.function.bound_symbols[0] + w = Wild("w", exclude=[d]) + p = Wild("p", exclude=[d]) + m = expr.function.expr.match(w*d**p) + if m is not None: + return m[w]*HadamardPower(subexpr, m[p]) + return ElementwiseApplyFunction(expr.function, subexpr) + else: + return ArrayElementwiseApplyFunc(expr.function, subexpr) + + +@_array2matrix.register(ArrayElement) +def _(expr: ArrayElement): + ret = _array2matrix(expr.name) + if isinstance(ret, MatrixExpr): + return MatrixElement(ret, *expr.indices) + return ArrayElement(ret, expr.indices) + + +@singledispatch +def _remove_trivial_dims(expr): + return expr, [] + + +@_remove_trivial_dims.register(ArrayTensorProduct) +def _(expr: ArrayTensorProduct): + # Recognize expressions like [x, y] with shape (k, 1, k, 1) as `x*y.T`. + # The matrix expression has to be equivalent to the tensor product of the + # matrices, with trivial dimensions (i.e. dim=1) dropped. + # That is, add contractions over trivial dimensions: + + removed = [] + newargs = [] + cumul = list(accumulate([0] + [get_rank(arg) for arg in expr.args])) + pending = None + prev_i = None + for i, arg in enumerate(expr.args): + current_range = list(range(cumul[i], cumul[i+1])) + if isinstance(arg, OneArray): + removed.extend(current_range) + continue + if not isinstance(arg, (MatrixExpr, MatrixBase)): + rarg, rem = _remove_trivial_dims(arg) + removed.extend(rem) + newargs.append(rarg) + continue + elif getattr(arg, "is_Identity", False) and arg.shape == (1, 1): + if arg.shape == (1, 1): + # Ignore identity matrices of shape (1, 1) - they are equivalent to scalar 1. + removed.extend(current_range) + continue + elif arg.shape == (1, 1): + arg, _ = _remove_trivial_dims(arg) + # Matrix is equivalent to scalar: + if len(newargs) == 0: + newargs.append(arg) + elif 1 in get_shape(newargs[-1]): + if newargs[-1].shape[1] == 1: + newargs[-1] = newargs[-1]*arg + else: + newargs[-1] = arg*newargs[-1] + removed.extend(current_range) + else: + newargs.append(arg) + elif 1 in arg.shape: + k = [i for i in arg.shape if i != 1][0] + if pending is None: + pending = k + prev_i = i + newargs.append(arg) + elif pending == k: + prev = newargs[-1] + if prev.shape[0] == 1: + d1 = cumul[prev_i] # type: ignore + prev = _a2m_transpose(prev) + else: + d1 = cumul[prev_i] + 1 # type: ignore + if arg.shape[1] == 1: + d2 = cumul[i] + 1 + arg = _a2m_transpose(arg) + else: + d2 = cumul[i] + newargs[-1] = prev*arg + pending = None + removed.extend([d1, d2]) + else: + newargs.append(arg) + pending = k + prev_i = i + else: + newargs.append(arg) + pending = None + newexpr, newremoved = _a2m_tensor_product(*newargs), sorted(removed) + if isinstance(newexpr, ArrayTensorProduct): + newexpr, newremoved2 = _find_trivial_matrices_rewrite(newexpr) + newremoved = _combine_removed(-1, newremoved, newremoved2) + if isinstance(newexpr, ArrayTensorProduct): + newexpr, newremoved2 = _find_trivial_kronecker_products_broadcast(newexpr) + newremoved = _combine_removed(-1, newremoved, newremoved2) + return newexpr, newremoved + + +@_remove_trivial_dims.register(ArrayAdd) +def _(expr: ArrayAdd): + rec = [_remove_trivial_dims(arg) for arg in expr.args] + newargs, removed = zip(*rec) + if len({get_shape(i) for i in newargs}) > 1: + return expr, [] + if len(removed) == 0: + return expr, removed + removed1 = removed[0] + return _a2m_add(*newargs), removed1 + + +@_remove_trivial_dims.register(PermuteDims) +def _(expr: PermuteDims): + subexpr, subremoved = _remove_trivial_dims(expr.expr) + p = expr.permutation.array_form + pinv = _af_invert(expr.permutation.array_form) + shift = list(accumulate([1 if i in subremoved else 0 for i in range(len(p))])) + premoved = [pinv[i] for i in subremoved] + p2 = [e - shift[e] for e in p if e not in subremoved] + # TODO: check if subremoved should be permuted as well... + newexpr = _permute_dims(subexpr, p2) + premoved = sorted(premoved) + if newexpr != expr: + newexpr, removed2 = _remove_trivial_dims(_array2matrix(newexpr)) + premoved = _combine_removed(-1, premoved, removed2) + return newexpr, premoved + + +@_remove_trivial_dims.register(ArrayContraction) +def _(expr: ArrayContraction): + new_expr, removed0 = _array_contraction_to_diagonal_multiple_identity(expr) + if new_expr != expr: + new_expr2, removed1 = _remove_trivial_dims(_array2matrix(new_expr)) + removed = _combine_removed(-1, removed0, removed1) + return new_expr2, removed + rank1 = get_rank(expr) + expr, removed1 = remove_identity_matrices(expr) + if not isinstance(expr, ArrayContraction): + expr2, removed2 = _remove_trivial_dims(expr) + return expr2, _combine_removed(rank1, removed1, removed2) + newexpr, removed2 = _remove_trivial_dims(expr.expr) + shifts = list(accumulate([1 if i in removed2 else 0 for i in range(get_rank(expr.expr))])) + new_contraction_indices = [tuple(j for j in i if j not in removed2) for i in expr.contraction_indices] + # Remove possible empty tuples "()": + new_contraction_indices = [i for i in new_contraction_indices if len(i) > 0] + contraction_indices_flat = [j for i in expr.contraction_indices for j in i] + removed2 = [i for i in removed2 if i not in contraction_indices_flat] + new_contraction_indices = [tuple(j - shifts[j] for j in i) for i in new_contraction_indices] + # Shift removed2: + removed2 = ArrayContraction._push_indices_up(expr.contraction_indices, removed2) + removed = _combine_removed(rank1, removed1, removed2) + return _array_contraction(newexpr, *new_contraction_indices), list(removed) + + +def _remove_diagonalized_identity_matrices(expr: ArrayDiagonal): + assert isinstance(expr, ArrayDiagonal) + editor = _EditArrayContraction(expr) + mapping = {i: {j for j in editor.args_with_ind if i in j.indices} for i in range(-1, -1-editor.number_of_diagonal_indices, -1)} + removed = [] + counter: int = 0 + for i, arg_with_ind in enumerate(editor.args_with_ind): + counter += len(arg_with_ind.indices) + if isinstance(arg_with_ind.element, Identity): + if None in arg_with_ind.indices and any(i is not None and (i < 0) == True for i in arg_with_ind.indices): + diag_ind = [j for j in arg_with_ind.indices if j is not None][0] + other = [j for j in mapping[diag_ind] if j != arg_with_ind][0] + if not isinstance(other.element, MatrixExpr): + continue + if 1 not in other.element.shape: + continue + if None not in other.indices: + continue + editor.args_with_ind[i].element = None + none_index = other.indices.index(None) + other.element = DiagMatrix(other.element) + other_range = editor.get_absolute_range(other) + removed.extend([other_range[0] + none_index]) + editor.args_with_ind = [i for i in editor.args_with_ind if i.element is not None] + removed = ArrayDiagonal._push_indices_up(expr.diagonal_indices, removed, get_rank(expr.expr)) + return editor.to_array_contraction(), removed + + +@_remove_trivial_dims.register(ArrayDiagonal) +def _(expr: ArrayDiagonal): + newexpr, removed = _remove_trivial_dims(expr.expr) + shifts = list(accumulate([0] + [1 if i in removed else 0 for i in range(get_rank(expr.expr))])) + new_diag_indices_map = {i: tuple(j for j in i if j not in removed) for i in expr.diagonal_indices} + for old_diag_tuple, new_diag_tuple in new_diag_indices_map.items(): + if len(new_diag_tuple) == 1: + removed = [i for i in removed if i not in old_diag_tuple] + new_diag_indices = [tuple(j - shifts[j] for j in i) for i in new_diag_indices_map.values()] + rank = get_rank(expr.expr) + removed = ArrayDiagonal._push_indices_up(expr.diagonal_indices, removed, rank) + removed = sorted(set(removed)) + # If there are single axes to diagonalize remaining, it means that their + # corresponding dimension has been removed, they no longer need diagonalization: + new_diag_indices = [i for i in new_diag_indices if len(i) > 0] + if len(new_diag_indices) > 0: + newexpr2 = _array_diagonal(newexpr, *new_diag_indices, allow_trivial_diags=True) + else: + newexpr2 = newexpr + if isinstance(newexpr2, ArrayDiagonal): + newexpr3, removed2 = _remove_diagonalized_identity_matrices(newexpr2) + removed = _combine_removed(-1, removed, removed2) + return newexpr3, removed + else: + return newexpr2, removed + + +@_remove_trivial_dims.register(ElementwiseApplyFunction) +def _(expr: ElementwiseApplyFunction): + subexpr, removed = _remove_trivial_dims(expr.expr) + if subexpr.shape == (1, 1): + # TODO: move this to ElementwiseApplyFunction + return expr.function(subexpr), removed + [0, 1] + return ElementwiseApplyFunction(expr.function, subexpr), [] + + +@_remove_trivial_dims.register(ArrayElementwiseApplyFunc) +def _(expr: ArrayElementwiseApplyFunc): + subexpr, removed = _remove_trivial_dims(expr.expr) + return ArrayElementwiseApplyFunc(expr.function, subexpr), removed + + +def convert_array_to_matrix(expr): + r""" + Recognize matrix expressions in codegen objects. + + If more than one matrix multiplication line have been detected, return a + list with the matrix expressions. + + Examples + ======== + + >>> from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array + >>> from sympy.tensor.array import tensorcontraction, tensorproduct + >>> from sympy import MatrixSymbol, Sum + >>> from sympy.abc import i, j, k, l, N + >>> from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array + >>> from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix + >>> A = MatrixSymbol("A", N, N) + >>> B = MatrixSymbol("B", N, N) + >>> C = MatrixSymbol("C", N, N) + >>> D = MatrixSymbol("D", N, N) + + >>> expr = Sum(A[i, j]*B[j, k], (j, 0, N-1)) + >>> cg = convert_indexed_to_array(expr) + >>> convert_array_to_matrix(cg) + A*B + >>> cg = convert_indexed_to_array(expr, first_indices=[k]) + >>> convert_array_to_matrix(cg) + B.T*A.T + + Transposition is detected: + + >>> expr = Sum(A[j, i]*B[j, k], (j, 0, N-1)) + >>> cg = convert_indexed_to_array(expr) + >>> convert_array_to_matrix(cg) + A.T*B + >>> cg = convert_indexed_to_array(expr, first_indices=[k]) + >>> convert_array_to_matrix(cg) + B.T*A + + Detect the trace: + + >>> expr = Sum(A[i, i], (i, 0, N-1)) + >>> cg = convert_indexed_to_array(expr) + >>> convert_array_to_matrix(cg) + Trace(A) + + Recognize some more complex traces: + + >>> expr = Sum(A[i, j]*B[j, i], (i, 0, N-1), (j, 0, N-1)) + >>> cg = convert_indexed_to_array(expr) + >>> convert_array_to_matrix(cg) + Trace(A*B) + + More complicated expressions: + + >>> expr = Sum(A[i, j]*B[k, j]*A[l, k], (j, 0, N-1), (k, 0, N-1)) + >>> cg = convert_indexed_to_array(expr) + >>> convert_array_to_matrix(cg) + A*B.T*A.T + + Expressions constructed from matrix expressions do not contain literal + indices, the positions of free indices are returned instead: + + >>> expr = A*B + >>> cg = convert_matrix_to_array(expr) + >>> convert_array_to_matrix(cg) + A*B + + If more than one line of matrix multiplications is detected, return + separate matrix multiplication factors embedded in a tensor product object: + + >>> cg = tensorcontraction(tensorproduct(A, B, C, D), (1, 2), (5, 6)) + >>> convert_array_to_matrix(cg) + ArrayTensorProduct(A*B, C*D) + + The two lines have free indices at axes 0, 3 and 4, 7, respectively. + """ + rec = _array2matrix(expr) + rec, removed = _remove_trivial_dims(rec) + return rec + + +def _array_diag2contr_diagmatrix(expr: ArrayDiagonal): + if isinstance(expr.expr, ArrayTensorProduct): + args = list(expr.expr.args) + diag_indices = list(expr.diagonal_indices) + mapping = _get_mapping_from_subranks([_get_subrank(arg) for arg in args]) + tuple_links = [[mapping[j] for j in i] for i in diag_indices] + contr_indices = [] + total_rank = get_rank(expr) + replaced = [False for arg in args] + for i, (abs_pos, rel_pos) in enumerate(zip(diag_indices, tuple_links)): + if len(abs_pos) != 2: + continue + (pos1_outer, pos1_inner), (pos2_outer, pos2_inner) = rel_pos + arg1 = args[pos1_outer] + arg2 = args[pos2_outer] + if get_rank(arg1) != 2 or get_rank(arg2) != 2: + if replaced[pos1_outer]: + diag_indices[i] = None + if replaced[pos2_outer]: + diag_indices[i] = None + continue + pos1_in2 = 1 - pos1_inner + pos2_in2 = 1 - pos2_inner + if arg1.shape[pos1_in2] == 1: + if arg1.shape[pos1_inner] != 1: + darg1 = DiagMatrix(arg1) + else: + darg1 = arg1 + args.append(darg1) + contr_indices.append(((pos2_outer, pos2_inner), (len(args)-1, pos1_inner))) + total_rank += 1 + diag_indices[i] = None + args[pos1_outer] = OneArray(arg1.shape[pos1_in2]) + replaced[pos1_outer] = True + elif arg2.shape[pos2_in2] == 1: + if arg2.shape[pos2_inner] != 1: + darg2 = DiagMatrix(arg2) + else: + darg2 = arg2 + args.append(darg2) + contr_indices.append(((pos1_outer, pos1_inner), (len(args)-1, pos2_inner))) + total_rank += 1 + diag_indices[i] = None + args[pos2_outer] = OneArray(arg2.shape[pos2_in2]) + replaced[pos2_outer] = True + diag_indices_new = [i for i in diag_indices if i is not None] + cumul = list(accumulate([0] + [get_rank(arg) for arg in args])) + contr_indices2 = [tuple(cumul[a] + b for a, b in i) for i in contr_indices] + tc = _array_contraction( + _array_tensor_product(*args), *contr_indices2 + ) + td = _array_diagonal(tc, *diag_indices_new) + return td + return expr + + +def _a2m_mul(*args): + if not any(isinstance(i, _CodegenArrayAbstract) for i in args): + from sympy.matrices.expressions.matmul import MatMul + return MatMul(*args).doit() + else: + return _array_contraction( + _array_tensor_product(*args), + *[(2*i-1, 2*i) for i in range(1, len(args))] + ) + + +def _a2m_tensor_product(*args): + scalars = [] + arrays = [] + for arg in args: + if isinstance(arg, (MatrixExpr, _ArrayExpr, _CodegenArrayAbstract)): + arrays.append(arg) + else: + scalars.append(arg) + scalar = Mul.fromiter(scalars) + if len(arrays) == 0: + return scalar + if scalar != 1: + if isinstance(arrays[0], _CodegenArrayAbstract): + arrays = [scalar] + arrays + else: + arrays[0] *= scalar + return _array_tensor_product(*arrays) + + +def _a2m_add(*args): + if not any(isinstance(i, _CodegenArrayAbstract) for i in args): + from sympy.matrices.expressions.matadd import MatAdd + return MatAdd(*args).doit() + else: + return _array_add(*args) + + +def _a2m_trace(arg): + if isinstance(arg, _CodegenArrayAbstract): + return _array_contraction(arg, (0, 1)) + else: + from sympy.matrices.expressions.trace import Trace + return Trace(arg) + + +def _a2m_transpose(arg): + if isinstance(arg, _CodegenArrayAbstract): + return _permute_dims(arg, [1, 0]) + else: + from sympy.matrices.expressions.transpose import Transpose + return Transpose(arg).doit() + + +def identify_hadamard_products(expr: ArrayContraction | ArrayDiagonal): + + editor: _EditArrayContraction = _EditArrayContraction(expr) + + map_contr_to_args: dict[FrozenSet, list[_ArgE]] = defaultdict(list) + map_ind_to_inds: dict[int | None, int] = defaultdict(int) + for arg_with_ind in editor.args_with_ind: + for ind in arg_with_ind.indices: + map_ind_to_inds[ind] += 1 + if None in arg_with_ind.indices: + continue + map_contr_to_args[frozenset(arg_with_ind.indices)].append(arg_with_ind) + + k: FrozenSet[int] + v: list[_ArgE] + for k, v in map_contr_to_args.items(): + make_trace: bool = False + if len(k) == 1 and next(iter(k)) >= 0 and sum(next(iter(k)) in i for i in map_contr_to_args) == 1: + # This is a trace: the arguments are fully contracted with only one + # index, and the index isn't used anywhere else: + make_trace = True + first_element = S.One + elif len(k) != 2: + # Hadamard product only defined for matrices: + continue + if len(v) == 1: + # Hadamard product with a single argument makes no sense: + continue + for ind in k: + if map_ind_to_inds[ind] <= 2: + # There is no other contraction, skip: + continue + + def check_transpose(x): + x = [i if i >= 0 else -1-i for i in x] + return x == sorted(x) + + # Check if expression is a trace: + if all(map_ind_to_inds[j] == len(v) and j >= 0 for j in k) and all(j >= 0 for j in k): + # This is a trace + make_trace = True + first_element = v[0].element + if not check_transpose(v[0].indices): + first_element = first_element.T # type: ignore + hadamard_factors = v[1:] + else: + hadamard_factors = v + + # This is a Hadamard product: + + hp = hadamard_product(*[i.element if check_transpose(i.indices) else Transpose(i.element) for i in hadamard_factors]) + hp_indices = v[0].indices + if not check_transpose(hadamard_factors[0].indices): + hp_indices = list(reversed(hp_indices)) + if make_trace: + hp = Trace(first_element*hp.T)._normalize() + hp_indices = [] + editor.insert_after(v[0], _ArgE(hp, hp_indices)) + for i in v: + editor.args_with_ind.remove(i) + + return editor.to_array_contraction() + + +def identify_removable_identity_matrices(expr): + editor = _EditArrayContraction(expr) + + flag = True + while flag: + flag = False + for arg_with_ind in editor.args_with_ind: + if isinstance(arg_with_ind.element, Identity): + k = arg_with_ind.element.shape[0] + # Candidate for removal: + if arg_with_ind.indices == [None, None]: + # Free identity matrix, will be cleared by _remove_trivial_dims: + continue + elif None in arg_with_ind.indices: + ind = [j for j in arg_with_ind.indices if j is not None][0] + counted = editor.count_args_with_index(ind) + if counted == 1: + # Identity matrix contracted only on one index with itself, + # transform to a OneArray(k) element: + editor.insert_after(arg_with_ind, OneArray(k)) + editor.args_with_ind.remove(arg_with_ind) + flag = True + break + elif counted > 2: + # Case counted = 2 is a matrix multiplication by identity matrix, skip it. + # Case counted > 2 is a multiple contraction, + # this is a case where the contraction becomes a diagonalization if the + # identity matrix is dropped. + continue + elif arg_with_ind.indices[0] == arg_with_ind.indices[1]: + ind = arg_with_ind.indices[0] + counted = editor.count_args_with_index(ind) + if counted > 1: + editor.args_with_ind.remove(arg_with_ind) + flag = True + break + else: + # This is a trace, skip it as it will be recognized somewhere else: + pass + elif ask(Q.diagonal(arg_with_ind.element)): + if arg_with_ind.indices == [None, None]: + continue + elif None in arg_with_ind.indices: + pass + elif arg_with_ind.indices[0] == arg_with_ind.indices[1]: + ind = arg_with_ind.indices[0] + counted = editor.count_args_with_index(ind) + if counted == 3: + # A_ai B_bi D_ii ==> A_ai D_ij B_bj + ind_new = editor.get_new_contraction_index() + other_args = [j for j in editor.args_with_ind if j != arg_with_ind] + other_args[1].indices = [ind_new if j == ind else j for j in other_args[1].indices] + arg_with_ind.indices = [ind, ind_new] + flag = True + break + + return editor.to_array_contraction() + + +def remove_identity_matrices(expr: ArrayContraction): + editor = _EditArrayContraction(expr) + removed: list[int] = [] + + permutation_map = {} + + free_indices = list(accumulate([0] + [sum(i is None for i in arg.indices) for arg in editor.args_with_ind])) + free_map = dict(zip(editor.args_with_ind, free_indices[:-1])) + + update_pairs = {} + + for ind in range(editor.number_of_contraction_indices): + args = editor.get_args_with_index(ind) + identity_matrices = [i for i in args if isinstance(i.element, Identity)] + number_identity_matrices = len(identity_matrices) + # If the contraction involves a non-identity matrix and multiple identity matrices: + if number_identity_matrices != len(args) - 1 or number_identity_matrices == 0: + continue + # Get the non-identity element: + non_identity = [i for i in args if not isinstance(i.element, Identity)][0] + # Check that all identity matrices have at least one free index + # (otherwise they would be contractions to some other elements) + if any(None not in i.indices for i in identity_matrices): + continue + # Mark the identity matrices for removal: + for i in identity_matrices: + i.element = None + removed.extend(range(free_map[i], free_map[i] + len([j for j in i.indices if j is None]))) + last_removed = removed.pop(-1) + update_pairs[last_removed, ind] = non_identity.indices[:] + # Remove the indices from the non-identity matrix, as the contraction + # no longer exists: + non_identity.indices = [None if i == ind else i for i in non_identity.indices] + + removed.sort() + + shifts = list(accumulate([1 if i in removed else 0 for i in range(get_rank(expr))])) + for (last_removed, ind), non_identity_indices in update_pairs.items(): + pos = [free_map[non_identity] + i for i, e in enumerate(non_identity_indices) if e == ind] + assert len(pos) == 1 + for j in pos: + permutation_map[j] = last_removed + + editor.args_with_ind = [i for i in editor.args_with_ind if i.element is not None] + ret_expr = editor.to_array_contraction() + permutation = [] + counter = 0 + counter2 = 0 + for j in range(get_rank(expr)): + if j in removed: + continue + if counter2 in permutation_map: + target = permutation_map[counter2] + permutation.append(target - shifts[target]) + counter2 += 1 + else: + while counter in permutation_map.values(): + counter += 1 + permutation.append(counter) + counter += 1 + counter2 += 1 + ret_expr2 = _permute_dims(ret_expr, _af_invert(permutation)) + return ret_expr2, removed + + +def _combine_removed(dim: int, removed1: list[int], removed2: list[int]) -> list[int]: + # Concatenate two axis removal operations as performed by + # _remove_trivial_dims, + removed1 = sorted(removed1) + removed2 = sorted(removed2) + i = 0 + j = 0 + removed = [] + while True: + if j >= len(removed2): + while i < len(removed1): + removed.append(removed1[i]) + i += 1 + break + elif i < len(removed1) and removed1[i] <= i + removed2[j]: + removed.append(removed1[i]) + i += 1 + else: + removed.append(i + removed2[j]) + j += 1 + return removed + + +def _array_contraction_to_diagonal_multiple_identity(expr: ArrayContraction): + editor = _EditArrayContraction(expr) + editor.track_permutation_start() + removed: list[int] = [] + diag_index_counter: int = 0 + for i in range(editor.number_of_contraction_indices): + identities = [] + args = [] + for j, arg in enumerate(editor.args_with_ind): + if i not in arg.indices: + continue + if isinstance(arg.element, Identity): + identities.append(arg) + else: + args.append(arg) + if len(identities) == 0: + continue + if len(args) + len(identities) < 3: + continue + new_diag_ind = -1 - diag_index_counter + diag_index_counter += 1 + # Variable "flag" to control whether to skip this contraction set: + flag: bool = True + for i1, id1 in enumerate(identities): + if None not in id1.indices: + flag = True + break + free_pos = list(range(*editor.get_absolute_free_range(id1)))[0] + editor._track_permutation[-1].append(free_pos) # type: ignore + id1.element = None + flag = False + break + if flag: + continue + for arg in identities[:i1] + identities[i1+1:]: + arg.element = None + removed.extend(range(*editor.get_absolute_free_range(arg))) + for arg in args: + arg.indices = [new_diag_ind if j == i else j for j in arg.indices] + for j, e in enumerate(editor.args_with_ind): + if e.element is None: + editor._track_permutation[j] = None # type: ignore + editor._track_permutation = [i for i in editor._track_permutation if i is not None] # type: ignore + # Renumber permutation array form in order to deal with deleted positions: + remap = {e: i for i, e in enumerate(sorted({k for j in editor._track_permutation for k in j}))} + editor._track_permutation = [[remap[j] for j in i] for i in editor._track_permutation] + editor.args_with_ind = [i for i in editor.args_with_ind if i.element is not None] + new_expr = editor.to_array_contraction() + return new_expr, removed diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/from_indexed_to_array.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/from_indexed_to_array.py new file mode 100644 index 0000000000000000000000000000000000000000..c219a205c4305bd7070e5117978146224521c58c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/from_indexed_to_array.py @@ -0,0 +1,257 @@ +from collections import defaultdict + +from sympy import Function +from sympy.combinatorics.permutations import _af_invert +from sympy.concrete.summations import Sum +from sympy.core.add import Add +from sympy.core.mul import Mul +from sympy.core.numbers import Integer +from sympy.core.power import Pow +from sympy.core.sorting import default_sort_key +from sympy.functions.special.tensor_functions import KroneckerDelta +from sympy.tensor.array.expressions import ArrayElementwiseApplyFunc +from sympy.tensor.indexed import (Indexed, IndexedBase) +from sympy.combinatorics import Permutation +from sympy.matrices.expressions.matexpr import MatrixElement +from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal, \ + get_shape, ArrayElement, _array_tensor_product, _array_diagonal, _array_contraction, _array_add, \ + _permute_dims, OneArray, ArrayAdd +from sympy.tensor.array.expressions.utils import _get_argindex, _get_diagonal_indices + + +def convert_indexed_to_array(expr, first_indices=None): + r""" + Parse indexed expression into a form useful for code generation. + + Examples + ======== + + >>> from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array + >>> from sympy import MatrixSymbol, Sum, symbols + + >>> i, j, k, d = symbols("i j k d") + >>> M = MatrixSymbol("M", d, d) + >>> N = MatrixSymbol("N", d, d) + + Recognize the trace in summation form: + + >>> expr = Sum(M[i, i], (i, 0, d-1)) + >>> convert_indexed_to_array(expr) + ArrayContraction(M, (0, 1)) + + Recognize the extraction of the diagonal by using the same index `i` on + both axes of the matrix: + + >>> expr = M[i, i] + >>> convert_indexed_to_array(expr) + ArrayDiagonal(M, (0, 1)) + + This function can help perform the transformation expressed in two + different mathematical notations as: + + `\sum_{j=0}^{N-1} A_{i,j} B_{j,k} \Longrightarrow \mathbf{A}\cdot \mathbf{B}` + + Recognize the matrix multiplication in summation form: + + >>> expr = Sum(M[i, j]*N[j, k], (j, 0, d-1)) + >>> convert_indexed_to_array(expr) + ArrayContraction(ArrayTensorProduct(M, N), (1, 2)) + + Specify that ``k`` has to be the starting index: + + >>> convert_indexed_to_array(expr, first_indices=[k]) + ArrayContraction(ArrayTensorProduct(N, M), (0, 3)) + """ + + result, indices = _convert_indexed_to_array(expr) + + if any(isinstance(i, (int, Integer)) for i in indices): + result = ArrayElement(result, indices) + indices = [] + + if not first_indices: + return result + + def _check_is_in(elem, indices): + if elem in indices: + return True + if any(elem in i for i in indices if isinstance(i, frozenset)): + return True + return False + + repl = {j: i for i in indices if isinstance(i, frozenset) for j in i} + first_indices = [repl.get(i, i) for i in first_indices] + for i in first_indices: + if not _check_is_in(i, indices): + first_indices.remove(i) + first_indices.extend([i for i in indices if not _check_is_in(i, first_indices)]) + + def _get_pos(elem, indices): + if elem in indices: + return indices.index(elem) + for i, e in enumerate(indices): + if not isinstance(e, frozenset): + continue + if elem in e: + return i + raise ValueError("not found") + + permutation = _af_invert([_get_pos(i, first_indices) for i in indices]) + if isinstance(result, ArrayAdd): + return _array_add(*[_permute_dims(arg, permutation) for arg in result.args]) + else: + return _permute_dims(result, permutation) + + +def _convert_indexed_to_array(expr): + if isinstance(expr, Sum): + function = expr.function + summation_indices = expr.variables + subexpr, subindices = _convert_indexed_to_array(function) + subindicessets = {j: i for i in subindices if isinstance(i, frozenset) for j in i} + summation_indices = sorted({subindicessets.get(i, i) for i in summation_indices}, key=default_sort_key) + # TODO: check that Kronecker delta is only contracted to one other element: + kronecker_indices = set() + if isinstance(function, Mul): + for arg in function.args: + if not isinstance(arg, KroneckerDelta): + continue + arg_indices = sorted(set(arg.indices), key=default_sort_key) + if len(arg_indices) == 2: + kronecker_indices.update(arg_indices) + kronecker_indices = sorted(kronecker_indices, key=default_sort_key) + # Check dimensional consistency: + shape = get_shape(subexpr) + if shape: + for ind, istart, iend in expr.limits: + i = _get_argindex(subindices, ind) + if istart != 0 or iend+1 != shape[i]: + raise ValueError("summation index and array dimension mismatch: %s" % ind) + contraction_indices = [] + subindices = list(subindices) + if isinstance(subexpr, ArrayDiagonal): + diagonal_indices = list(subexpr.diagonal_indices) + dindices = subindices[-len(diagonal_indices):] + subindices = subindices[:-len(diagonal_indices)] + for index in summation_indices: + if index in dindices: + position = dindices.index(index) + contraction_indices.append(diagonal_indices[position]) + diagonal_indices[position] = None + diagonal_indices = [i for i in diagonal_indices if i is not None] + for i, ind in enumerate(subindices): + if ind in summation_indices: + pass + if diagonal_indices: + subexpr = _array_diagonal(subexpr.expr, *diagonal_indices) + else: + subexpr = subexpr.expr + + axes_contraction = defaultdict(list) + for i, ind in enumerate(subindices): + include = all(j not in kronecker_indices for j in ind) if isinstance(ind, frozenset) else ind not in kronecker_indices + if ind in summation_indices and include: + axes_contraction[ind].append(i) + subindices[i] = None + for k, v in axes_contraction.items(): + if any(i in kronecker_indices for i in k) if isinstance(k, frozenset) else k in kronecker_indices: + continue + contraction_indices.append(tuple(v)) + free_indices = [i for i in subindices if i is not None] + indices_ret = list(free_indices) + indices_ret.sort(key=lambda x: free_indices.index(x)) + return _array_contraction( + subexpr, + *contraction_indices, + free_indices=free_indices + ), tuple(indices_ret) + if isinstance(expr, Mul): + args, indices = zip(*[_convert_indexed_to_array(arg) for arg in expr.args]) + # Check if there are KroneckerDelta objects: + kronecker_delta_repl = {} + for arg in args: + if not isinstance(arg, KroneckerDelta): + continue + # Diagonalize two indices: + i, j = arg.indices + kindices = set(arg.indices) + if i in kronecker_delta_repl: + kindices.update(kronecker_delta_repl[i]) + if j in kronecker_delta_repl: + kindices.update(kronecker_delta_repl[j]) + kindices = frozenset(kindices) + for index in kindices: + kronecker_delta_repl[index] = kindices + # Remove KroneckerDelta objects, their relations should be handled by + # ArrayDiagonal: + newargs = [] + newindices = [] + for arg, loc_indices in zip(args, indices): + if isinstance(arg, KroneckerDelta): + continue + newargs.append(arg) + newindices.append(loc_indices) + flattened_indices = [kronecker_delta_repl.get(j, j) for i in newindices for j in i] + diagonal_indices, ret_indices = _get_diagonal_indices(flattened_indices) + tp = _array_tensor_product(*newargs) + if diagonal_indices: + return _array_diagonal(tp, *diagonal_indices), ret_indices + else: + return tp, ret_indices + if isinstance(expr, MatrixElement): + indices = expr.args[1:] + diagonal_indices, ret_indices = _get_diagonal_indices(indices) + if diagonal_indices: + return _array_diagonal(expr.args[0], *diagonal_indices), ret_indices + else: + return expr.args[0], ret_indices + if isinstance(expr, ArrayElement): + indices = expr.indices + diagonal_indices, ret_indices = _get_diagonal_indices(indices) + if diagonal_indices: + return _array_diagonal(expr.name, *diagonal_indices), ret_indices + else: + return expr.name, ret_indices + if isinstance(expr, Indexed): + indices = expr.indices + diagonal_indices, ret_indices = _get_diagonal_indices(indices) + if diagonal_indices: + return _array_diagonal(expr.base, *diagonal_indices), ret_indices + else: + return expr.args[0], ret_indices + if isinstance(expr, IndexedBase): + raise NotImplementedError + if isinstance(expr, KroneckerDelta): + return expr, expr.indices + if isinstance(expr, Add): + args, indices = zip(*[_convert_indexed_to_array(arg) for arg in expr.args]) + args = list(args) + # Check if all indices are compatible. Otherwise expand the dimensions: + index0 = [] + shape0 = [] + for arg, arg_indices in zip(args, indices): + arg_indices_set = set(arg_indices) + arg_indices_missing = arg_indices_set.difference(index0) + index0.extend([i for i in arg_indices if i in arg_indices_missing]) + arg_shape = get_shape(arg) + shape0.extend([arg_shape[i] for i, e in enumerate(arg_indices) if e in arg_indices_missing]) + for i, (arg, arg_indices) in enumerate(zip(args, indices)): + if len(arg_indices) < len(index0): + missing_indices_pos = [i for i, e in enumerate(index0) if e not in arg_indices] + missing_shape = [shape0[i] for i in missing_indices_pos] + arg_indices = tuple(index0[j] for j in missing_indices_pos) + arg_indices + args[i] = _array_tensor_product(OneArray(*missing_shape), args[i]) + permutation = Permutation([arg_indices.index(j) for j in index0]) + # Perform index permutations: + args[i] = _permute_dims(args[i], permutation) + return _array_add(*args), tuple(index0) + if isinstance(expr, Pow): + subexpr, subindices = _convert_indexed_to_array(expr.base) + if isinstance(expr.exp, (int, Integer)): + diags = zip(*[(2*i, 2*i + 1) for i in range(expr.exp)]) + arr = _array_diagonal(_array_tensor_product(*[subexpr for i in range(expr.exp)]), *diags) + return arr, subindices + if isinstance(expr, Function): + subexpr, subindices = _convert_indexed_to_array(expr.args[0]) + return ArrayElementwiseApplyFunc(type(expr), subexpr), subindices + return expr, () diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/from_matrix_to_array.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/from_matrix_to_array.py new file mode 100644 index 0000000000000000000000000000000000000000..8f66961727f6338318d65876a7768802773e4f2d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/from_matrix_to_array.py @@ -0,0 +1,87 @@ +from sympy import KroneckerProduct +from sympy.core.basic import Basic +from sympy.core.function import Lambda +from sympy.core.mul import Mul +from sympy.core.numbers import Integer +from sympy.core.power import Pow +from sympy.core.singleton import S +from sympy.core.symbol import (Dummy, symbols) +from sympy.matrices.expressions.hadamard import (HadamardPower, HadamardProduct) +from sympy.matrices.expressions.matadd import MatAdd +from sympy.matrices.expressions.matmul import MatMul +from sympy.matrices.expressions.matpow import MatPow +from sympy.matrices.expressions.trace import Trace +from sympy.matrices.expressions.transpose import Transpose +from sympy.matrices.expressions.matexpr import MatrixExpr +from sympy.tensor.array.expressions.array_expressions import \ + ArrayElementwiseApplyFunc, _array_tensor_product, _array_contraction, \ + _array_diagonal, _array_add, _permute_dims, Reshape + + +def convert_matrix_to_array(expr: Basic) -> Basic: + if isinstance(expr, MatMul): + args_nonmat = [] + args = [] + for arg in expr.args: + if isinstance(arg, MatrixExpr): + args.append(arg) + else: + args_nonmat.append(convert_matrix_to_array(arg)) + contractions = [(2*i+1, 2*i+2) for i in range(len(args)-1)] + scalar = _array_tensor_product(*args_nonmat) if args_nonmat else S.One + if scalar == 1: + tprod = _array_tensor_product( + *[convert_matrix_to_array(arg) for arg in args]) + else: + tprod = _array_tensor_product( + scalar, + *[convert_matrix_to_array(arg) for arg in args]) + return _array_contraction( + tprod, + *contractions + ) + elif isinstance(expr, MatAdd): + return _array_add( + *[convert_matrix_to_array(arg) for arg in expr.args] + ) + elif isinstance(expr, Transpose): + return _permute_dims( + convert_matrix_to_array(expr.args[0]), [1, 0] + ) + elif isinstance(expr, Trace): + inner_expr: MatrixExpr = convert_matrix_to_array(expr.arg) # type: ignore + return _array_contraction(inner_expr, (0, len(inner_expr.shape) - 1)) + elif isinstance(expr, Mul): + return _array_tensor_product(*[convert_matrix_to_array(i) for i in expr.args]) + elif isinstance(expr, Pow): + base = convert_matrix_to_array(expr.base) + if (expr.exp > 0) == True: + return _array_tensor_product(*[base for i in range(expr.exp)]) + else: + return expr + elif isinstance(expr, MatPow): + base = convert_matrix_to_array(expr.base) + if expr.exp.is_Integer != True: + b = symbols("b", cls=Dummy) + return ArrayElementwiseApplyFunc(Lambda(b, b**expr.exp), convert_matrix_to_array(base)) + elif (expr.exp > 0) == True: + return convert_matrix_to_array(MatMul.fromiter(base for i in range(expr.exp))) + else: + return expr + elif isinstance(expr, HadamardProduct): + tp = _array_tensor_product(*[convert_matrix_to_array(arg) for arg in expr.args]) + diag = [[2*i for i in range(len(expr.args))], [2*i+1 for i in range(len(expr.args))]] + return _array_diagonal(tp, *diag) + elif isinstance(expr, HadamardPower): + base, exp = expr.args + if isinstance(exp, Integer) and exp > 0: + return convert_matrix_to_array(HadamardProduct.fromiter(base for i in range(exp))) + else: + d = Dummy("d") + return ArrayElementwiseApplyFunc(Lambda(d, d**exp), base) + elif isinstance(expr, KroneckerProduct): + kp_args = [convert_matrix_to_array(arg) for arg in expr.args] + permutation = [2*i for i in range(len(kp_args))] + [2*i + 1 for i in range(len(kp_args))] + return Reshape(_permute_dims(_array_tensor_product(*kp_args), permutation), expr.shape) + else: + return expr diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__init__.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58783a9437b88491786b17ce5dc02d87d9d3dd14 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_array_expressions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_array_expressions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d19532a566f5525f397962a27df0bad536c77d6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_array_expressions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_arrayexpr_derivatives.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_arrayexpr_derivatives.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..386fa1b54ab91ac6907b81b68bd3064cc8c61a53 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_arrayexpr_derivatives.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_as_explicit.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_as_explicit.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4e2676368bfb9549aa8406c6c4e3e669833cd6c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_as_explicit.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_convert_array_to_indexed.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_convert_array_to_indexed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b8605a2abdf7bc7ece98e0e88baf877825cc392 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_convert_array_to_indexed.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_convert_array_to_matrix.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_convert_array_to_matrix.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9dc75f71c2281c701e4c4c67a18a84fa3daf02f0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_convert_array_to_matrix.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_convert_indexed_to_array.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_convert_indexed_to_array.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94785c1d69ac55375d7aaf7134b72dd849a38e9a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_convert_indexed_to_array.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_convert_matrix_to_array.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_convert_matrix_to_array.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e97e9f78e1a59cfc61ee651f1d33b24c96e62b00 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_convert_matrix_to_array.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_deprecated_conv_modules.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_deprecated_conv_modules.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b1419ee16132cdccd6444c0547c1d3e05b97cdc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/__pycache__/test_deprecated_conv_modules.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_array_expressions.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_array_expressions.py new file mode 100644 index 0000000000000000000000000000000000000000..63fb79ab7ced7bff5ecb55b1764f43e29f98609d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_array_expressions.py @@ -0,0 +1,808 @@ +import random + +from sympy import tensordiagonal, eye, KroneckerDelta, Array +from sympy.core.symbol import symbols +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.matrices.expressions.diagonal import DiagMatrix +from sympy.matrices.expressions.matexpr import MatrixSymbol +from sympy.matrices.expressions.special import ZeroMatrix +from sympy.tensor.array.arrayop import (permutedims, tensorcontraction, tensorproduct) +from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray +from sympy.combinatorics import Permutation +from sympy.tensor.array.expressions.array_expressions import ZeroArray, OneArray, ArraySymbol, ArrayElement, \ + PermuteDims, ArrayContraction, ArrayTensorProduct, ArrayDiagonal, \ + ArrayAdd, nest_permutation, ArrayElementwiseApplyFunc, _EditArrayContraction, _ArgE, _array_tensor_product, \ + _array_contraction, _array_diagonal, _array_add, _permute_dims, Reshape +from sympy.testing.pytest import raises + +i, j, k, l, m, n = symbols("i j k l m n") + + +M = ArraySymbol("M", (k, k)) +N = ArraySymbol("N", (k, k)) +P = ArraySymbol("P", (k, k)) +Q = ArraySymbol("Q", (k, k)) + +A = ArraySymbol("A", (k, k)) +B = ArraySymbol("B", (k, k)) +C = ArraySymbol("C", (k, k)) +D = ArraySymbol("D", (k, k)) + +X = ArraySymbol("X", (k, k)) +Y = ArraySymbol("Y", (k, k)) + +a = ArraySymbol("a", (k, 1)) +b = ArraySymbol("b", (k, 1)) +c = ArraySymbol("c", (k, 1)) +d = ArraySymbol("d", (k, 1)) + + +def test_array_symbol_and_element(): + A = ArraySymbol("A", (2,)) + A0 = ArrayElement(A, (0,)) + A1 = ArrayElement(A, (1,)) + assert A[0] == A0 + assert A[1] != A0 + assert A.as_explicit() == ImmutableDenseNDimArray([A0, A1]) + + A2 = tensorproduct(A, A) + assert A2.shape == (2, 2) + # TODO: not yet supported: + # assert A2.as_explicit() == Array([[A[0]*A[0], A[1]*A[0]], [A[0]*A[1], A[1]*A[1]]]) + A3 = tensorcontraction(A2, (0, 1)) + assert A3.shape == () + # TODO: not yet supported: + # assert A3.as_explicit() == Array([]) + + A = ArraySymbol("A", (2, 3, 4)) + Ae = A.as_explicit() + assert Ae == ImmutableDenseNDimArray( + [[[ArrayElement(A, (i, j, k)) for k in range(4)] for j in range(3)] for i in range(2)]) + + p = _permute_dims(A, Permutation(0, 2, 1)) + assert isinstance(p, PermuteDims) + + A = ArraySymbol("A", (2,)) + raises(IndexError, lambda: A[()]) + raises(IndexError, lambda: A[0, 1]) + raises(ValueError, lambda: A[-1]) + raises(ValueError, lambda: A[2]) + + O = OneArray(3, 4) + Z = ZeroArray(m, n) + + raises(IndexError, lambda: O[()]) + raises(IndexError, lambda: O[1, 2, 3]) + raises(ValueError, lambda: O[3, 0]) + raises(ValueError, lambda: O[0, 4]) + + assert O[1, 2] == 1 + assert Z[1, 2] == 0 + + +def test_zero_array(): + assert ZeroArray() == 0 + assert ZeroArray().is_Integer + + za = ZeroArray(3, 2, 4) + assert za.shape == (3, 2, 4) + za_e = za.as_explicit() + assert za_e.shape == (3, 2, 4) + + m, n, k = symbols("m n k") + za = ZeroArray(m, n, k, 2) + assert za.shape == (m, n, k, 2) + raises(ValueError, lambda: za.as_explicit()) + + +def test_one_array(): + assert OneArray() == 1 + assert OneArray().is_Integer + + oa = OneArray(3, 2, 4) + assert oa.shape == (3, 2, 4) + oa_e = oa.as_explicit() + assert oa_e.shape == (3, 2, 4) + + m, n, k = symbols("m n k") + oa = OneArray(m, n, k, 2) + assert oa.shape == (m, n, k, 2) + raises(ValueError, lambda: oa.as_explicit()) + + +def test_arrayexpr_contraction_construction(): + + cg = _array_contraction(A) + assert cg == A + + cg = _array_contraction(_array_tensor_product(A, B), (1, 0)) + assert cg == _array_contraction(_array_tensor_product(A, B), (0, 1)) + + cg = _array_contraction(_array_tensor_product(M, N), (0, 1)) + indtup = cg._get_contraction_tuples() + assert indtup == [[(0, 0), (0, 1)]] + assert cg._contraction_tuples_to_contraction_indices(cg.expr, indtup) == [(0, 1)] + + cg = _array_contraction(_array_tensor_product(M, N), (1, 2)) + indtup = cg._get_contraction_tuples() + assert indtup == [[(0, 1), (1, 0)]] + assert cg._contraction_tuples_to_contraction_indices(cg.expr, indtup) == [(1, 2)] + + cg = _array_contraction(_array_tensor_product(M, M, N), (1, 4), (2, 5)) + indtup = cg._get_contraction_tuples() + assert indtup == [[(0, 0), (1, 1)], [(0, 1), (2, 0)]] + assert cg._contraction_tuples_to_contraction_indices(cg.expr, indtup) == [(0, 3), (1, 4)] + + # Test removal of trivial contraction: + assert _array_contraction(a, (1,)) == a + assert _array_contraction( + _array_tensor_product(a, b), (0, 2), (1,), (3,)) == _array_contraction( + _array_tensor_product(a, b), (0, 2)) + + +def test_arrayexpr_array_flatten(): + + # Flatten nested ArrayTensorProduct objects: + expr1 = _array_tensor_product(M, N) + expr2 = _array_tensor_product(P, Q) + expr = _array_tensor_product(expr1, expr2) + assert expr == _array_tensor_product(M, N, P, Q) + assert expr.args == (M, N, P, Q) + + # Flatten mixed ArrayTensorProduct and ArrayContraction objects: + cg1 = _array_contraction(expr1, (1, 2)) + cg2 = _array_contraction(expr2, (0, 3)) + + expr = _array_tensor_product(cg1, cg2) + assert expr == _array_contraction(_array_tensor_product(M, N, P, Q), (1, 2), (4, 7)) + + expr = _array_tensor_product(M, cg1) + assert expr == _array_contraction(_array_tensor_product(M, M, N), (3, 4)) + + # Flatten nested ArrayContraction objects: + cgnested = _array_contraction(cg1, (0, 1)) + assert cgnested == _array_contraction(_array_tensor_product(M, N), (0, 3), (1, 2)) + + cgnested = _array_contraction(_array_tensor_product(cg1, cg2), (0, 3)) + assert cgnested == _array_contraction(_array_tensor_product(M, N, P, Q), (0, 6), (1, 2), (4, 7)) + + cg3 = _array_contraction(_array_tensor_product(M, N, P, Q), (1, 3), (2, 4)) + cgnested = _array_contraction(cg3, (0, 1)) + assert cgnested == _array_contraction(_array_tensor_product(M, N, P, Q), (0, 5), (1, 3), (2, 4)) + + cgnested = _array_contraction(cg3, (0, 3), (1, 2)) + assert cgnested == _array_contraction(_array_tensor_product(M, N, P, Q), (0, 7), (1, 3), (2, 4), (5, 6)) + + cg4 = _array_contraction(_array_tensor_product(M, N, P, Q), (1, 5), (3, 7)) + cgnested = _array_contraction(cg4, (0, 1)) + assert cgnested == _array_contraction(_array_tensor_product(M, N, P, Q), (0, 2), (1, 5), (3, 7)) + + cgnested = _array_contraction(cg4, (0, 1), (2, 3)) + assert cgnested == _array_contraction(_array_tensor_product(M, N, P, Q), (0, 2), (1, 5), (3, 7), (4, 6)) + + cg = _array_diagonal(cg4) + assert cg == cg4 + assert isinstance(cg, type(cg4)) + + # Flatten nested ArrayDiagonal objects: + cg1 = _array_diagonal(expr1, (1, 2)) + cg2 = _array_diagonal(expr2, (0, 3)) + cg3 = _array_diagonal(_array_tensor_product(M, N, P, Q), (1, 3), (2, 4)) + cg4 = _array_diagonal(_array_tensor_product(M, N, P, Q), (1, 5), (3, 7)) + + cgnested = _array_diagonal(cg1, (0, 1)) + assert cgnested == _array_diagonal(_array_tensor_product(M, N), (1, 2), (0, 3)) + + cgnested = _array_diagonal(cg3, (1, 2)) + assert cgnested == _array_diagonal(_array_tensor_product(M, N, P, Q), (1, 3), (2, 4), (5, 6)) + + cgnested = _array_diagonal(cg4, (1, 2)) + assert cgnested == _array_diagonal(_array_tensor_product(M, N, P, Q), (1, 5), (3, 7), (2, 4)) + + cg = _array_add(M, N) + cg2 = _array_add(cg, P) + assert isinstance(cg2, ArrayAdd) + assert cg2.args == (M, N, P) + assert cg2.shape == (k, k) + + expr = _array_tensor_product(_array_diagonal(X, (0, 1)), _array_diagonal(A, (0, 1))) + assert expr == _array_diagonal(_array_tensor_product(X, A), (0, 1), (2, 3)) + + expr1 = _array_diagonal(_array_tensor_product(X, A), (1, 2)) + expr2 = _array_tensor_product(expr1, a) + assert expr2 == _permute_dims(_array_diagonal(_array_tensor_product(X, A, a), (1, 2)), [0, 1, 4, 2, 3]) + + expr1 = _array_contraction(_array_tensor_product(X, A), (1, 2)) + expr2 = _array_tensor_product(expr1, a) + assert isinstance(expr2, ArrayContraction) + assert isinstance(expr2.expr, ArrayTensorProduct) + + cg = _array_tensor_product(_array_diagonal(_array_tensor_product(A, X, Y), (0, 3), (1, 5)), a, b) + assert cg == _permute_dims(_array_diagonal(_array_tensor_product(A, X, Y, a, b), (0, 3), (1, 5)), [0, 1, 6, 7, 2, 3, 4, 5]) + + +def test_arrayexpr_array_diagonal(): + cg = _array_diagonal(M, (1, 0)) + assert cg == _array_diagonal(M, (0, 1)) + + cg = _array_diagonal(_array_tensor_product(M, N, P), (4, 1), (2, 0)) + assert cg == _array_diagonal(_array_tensor_product(M, N, P), (1, 4), (0, 2)) + + cg = _array_diagonal(_array_tensor_product(M, N), (1, 2), (3,), allow_trivial_diags=True) + assert cg == _permute_dims(_array_diagonal(_array_tensor_product(M, N), (1, 2)), [0, 2, 1]) + + Ax = ArraySymbol("Ax", shape=(1, 2, 3, 4, 3, 5, 6, 2, 7)) + cg = _array_diagonal(Ax, (1, 7), (3,), (2, 4), (6,), allow_trivial_diags=True) + assert cg == _permute_dims(_array_diagonal(Ax, (1, 7), (2, 4)), [0, 2, 4, 5, 1, 6, 3]) + + cg = _array_diagonal(M, (0,), allow_trivial_diags=True) + assert cg == _permute_dims(M, [1, 0]) + + raises(ValueError, lambda: _array_diagonal(M, (0, 0))) + + +def test_arrayexpr_array_shape(): + expr = _array_tensor_product(M, N, P, Q) + assert expr.shape == (k, k, k, k, k, k, k, k) + Z = MatrixSymbol("Z", m, n) + expr = _array_tensor_product(M, Z) + assert expr.shape == (k, k, m, n) + expr2 = _array_contraction(expr, (0, 1)) + assert expr2.shape == (m, n) + expr2 = _array_diagonal(expr, (0, 1)) + assert expr2.shape == (m, n, k) + exprp = _permute_dims(expr, [2, 1, 3, 0]) + assert exprp.shape == (m, k, n, k) + expr3 = _array_tensor_product(N, Z) + expr2 = _array_add(expr, expr3) + assert expr2.shape == (k, k, m, n) + + # Contraction along axes with discordant dimensions: + raises(ValueError, lambda: _array_contraction(expr, (1, 2))) + # Also diagonal needs the same dimensions: + raises(ValueError, lambda: _array_diagonal(expr, (1, 2))) + # Diagonal requires at least to axes to compute the diagonal: + raises(ValueError, lambda: _array_diagonal(expr, (1,))) + + +def test_arrayexpr_permutedims_sink(): + + cg = _permute_dims(_array_tensor_product(M, N), [0, 1, 3, 2], nest_permutation=False) + sunk = nest_permutation(cg) + assert sunk == _array_tensor_product(M, _permute_dims(N, [1, 0])) + + cg = _permute_dims(_array_tensor_product(M, N), [1, 0, 3, 2], nest_permutation=False) + sunk = nest_permutation(cg) + assert sunk == _array_tensor_product(_permute_dims(M, [1, 0]), _permute_dims(N, [1, 0])) + + cg = _permute_dims(_array_tensor_product(M, N), [3, 2, 1, 0], nest_permutation=False) + sunk = nest_permutation(cg) + assert sunk == _array_tensor_product(_permute_dims(N, [1, 0]), _permute_dims(M, [1, 0])) + + cg = _permute_dims(_array_contraction(_array_tensor_product(M, N), (1, 2)), [1, 0], nest_permutation=False) + sunk = nest_permutation(cg) + assert sunk == _array_contraction(_permute_dims(_array_tensor_product(M, N), [[0, 3]]), (1, 2)) + + cg = _permute_dims(_array_tensor_product(M, N), [1, 0, 3, 2], nest_permutation=False) + sunk = nest_permutation(cg) + assert sunk == _array_tensor_product(_permute_dims(M, [1, 0]), _permute_dims(N, [1, 0])) + + cg = _permute_dims(_array_contraction(_array_tensor_product(M, N, P), (1, 2), (3, 4)), [1, 0], nest_permutation=False) + sunk = nest_permutation(cg) + assert sunk == _array_contraction(_permute_dims(_array_tensor_product(M, N, P), [[0, 5]]), (1, 2), (3, 4)) + + +def test_arrayexpr_push_indices_up_and_down(): + + indices = list(range(12)) + + contr_diag_indices = [(0, 6), (2, 8)] + assert ArrayContraction._push_indices_down(contr_diag_indices, indices) == (1, 3, 4, 5, 7, 9, 10, 11, 12, 13, 14, 15) + assert ArrayContraction._push_indices_up(contr_diag_indices, indices) == (None, 0, None, 1, 2, 3, None, 4, None, 5, 6, 7) + + assert ArrayDiagonal._push_indices_down(contr_diag_indices, indices, 10) == (1, 3, 4, 5, 7, 9, (0, 6), (2, 8), None, None, None, None) + assert ArrayDiagonal._push_indices_up(contr_diag_indices, indices, 10) == (6, 0, 7, 1, 2, 3, 6, 4, 7, 5, None, None) + + contr_diag_indices = [(1, 2), (7, 8)] + assert ArrayContraction._push_indices_down(contr_diag_indices, indices) == (0, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15) + assert ArrayContraction._push_indices_up(contr_diag_indices, indices) == (0, None, None, 1, 2, 3, 4, None, None, 5, 6, 7) + + assert ArrayDiagonal._push_indices_down(contr_diag_indices, indices, 10) == (0, 3, 4, 5, 6, 9, (1, 2), (7, 8), None, None, None, None) + assert ArrayDiagonal._push_indices_up(contr_diag_indices, indices, 10) == (0, 6, 6, 1, 2, 3, 4, 7, 7, 5, None, None) + + +def test_arrayexpr_split_multiple_contractions(): + a = MatrixSymbol("a", k, 1) + b = MatrixSymbol("b", k, 1) + A = MatrixSymbol("A", k, k) + B = MatrixSymbol("B", k, k) + C = MatrixSymbol("C", k, k) + X = MatrixSymbol("X", k, k) + + cg = _array_contraction(_array_tensor_product(A.T, a, b, b.T, (A*X*b).applyfunc(cos)), (1, 2, 8), (5, 6, 9)) + expected = _array_contraction(_array_tensor_product(A.T, DiagMatrix(a), OneArray(1), b, b.T, (A*X*b).applyfunc(cos)), (1, 3), (2, 9), (6, 7, 10)) + assert cg.split_multiple_contractions().dummy_eq(expected) + + # Check no overlap of lines: + + cg = _array_contraction(_array_tensor_product(A, a, C, a, B), (1, 2, 4), (5, 6, 8), (3, 7)) + assert cg.split_multiple_contractions() == cg + + cg = _array_contraction(_array_tensor_product(a, b, A), (0, 2, 4), (1, 3)) + assert cg.split_multiple_contractions() == cg + + +def test_arrayexpr_nested_permutations(): + + cg = _permute_dims(_permute_dims(M, (1, 0)), (1, 0)) + assert cg == M + + times = 3 + plist1 = [list(range(6)) for i in range(times)] + plist2 = [list(range(6)) for i in range(times)] + + for i in range(times): + random.shuffle(plist1[i]) + random.shuffle(plist2[i]) + + plist1.append([2, 5, 4, 1, 0, 3]) + plist2.append([3, 5, 0, 4, 1, 2]) + + plist1.append([2, 5, 4, 0, 3, 1]) + plist2.append([3, 0, 5, 1, 2, 4]) + + plist1.append([5, 4, 2, 0, 3, 1]) + plist2.append([4, 5, 0, 2, 3, 1]) + + Me = M.subs(k, 3).as_explicit() + Ne = N.subs(k, 3).as_explicit() + Pe = P.subs(k, 3).as_explicit() + cge = tensorproduct(Me, Ne, Pe) + + for permutation_array1, permutation_array2 in zip(plist1, plist2): + p1 = Permutation(permutation_array1) + p2 = Permutation(permutation_array2) + + cg = _permute_dims( + _permute_dims( + _array_tensor_product(M, N, P), + p1), + p2 + ) + result = _permute_dims( + _array_tensor_product(M, N, P), + p2*p1 + ) + assert cg == result + + # Check that `permutedims` behaves the same way with explicit-component arrays: + result1 = _permute_dims(_permute_dims(cge, p1), p2) + result2 = _permute_dims(cge, p2*p1) + assert result1 == result2 + + +def test_arrayexpr_contraction_permutation_mix(): + + Me = M.subs(k, 3).as_explicit() + Ne = N.subs(k, 3).as_explicit() + + cg1 = _array_contraction(PermuteDims(_array_tensor_product(M, N), Permutation([0, 2, 1, 3])), (2, 3)) + cg2 = _array_contraction(_array_tensor_product(M, N), (1, 3)) + assert cg1 == cg2 + cge1 = tensorcontraction(permutedims(tensorproduct(Me, Ne), Permutation([0, 2, 1, 3])), (2, 3)) + cge2 = tensorcontraction(tensorproduct(Me, Ne), (1, 3)) + assert cge1 == cge2 + + cg1 = _permute_dims(_array_tensor_product(M, N), Permutation([0, 1, 3, 2])) + cg2 = _array_tensor_product(M, _permute_dims(N, Permutation([1, 0]))) + assert cg1 == cg2 + + cg1 = _array_contraction( + _permute_dims( + _array_tensor_product(M, N, P, Q), Permutation([0, 2, 3, 1, 4, 5, 7, 6])), + (1, 2), (3, 5) + ) + cg2 = _array_contraction( + _array_tensor_product(M, N, P, _permute_dims(Q, Permutation([1, 0]))), + (1, 5), (2, 3) + ) + assert cg1 == cg2 + + cg1 = _array_contraction( + _permute_dims( + _array_tensor_product(M, N, P, Q), Permutation([1, 0, 4, 6, 2, 7, 5, 3])), + (0, 1), (2, 6), (3, 7) + ) + cg2 = _permute_dims( + _array_contraction( + _array_tensor_product(M, P, Q, N), + (0, 1), (2, 3), (4, 7)), + [1, 0] + ) + assert cg1 == cg2 + + cg1 = _array_contraction( + _permute_dims( + _array_tensor_product(M, N, P, Q), Permutation([1, 0, 4, 6, 7, 2, 5, 3])), + (0, 1), (2, 6), (3, 7) + ) + cg2 = _permute_dims( + _array_contraction( + _array_tensor_product(_permute_dims(M, [1, 0]), N, P, Q), + (0, 1), (3, 6), (4, 5) + ), + Permutation([1, 0]) + ) + assert cg1 == cg2 + + +def test_arrayexpr_permute_tensor_product(): + cg1 = _permute_dims(_array_tensor_product(M, N, P, Q), Permutation([2, 3, 1, 0, 5, 4, 6, 7])) + cg2 = _array_tensor_product(N, _permute_dims(M, [1, 0]), + _permute_dims(P, [1, 0]), Q) + assert cg1 == cg2 + + # TODO: reverse operation starting with `PermuteDims` and getting down to `bb`... + cg1 = _permute_dims(_array_tensor_product(M, N, P, Q), Permutation([2, 3, 4, 5, 0, 1, 6, 7])) + cg2 = _array_tensor_product(N, P, M, Q) + assert cg1 == cg2 + + cg1 = _permute_dims(_array_tensor_product(M, N, P, Q), Permutation([2, 3, 4, 6, 5, 7, 0, 1])) + assert cg1.expr == _array_tensor_product(N, P, Q, M) + assert cg1.permutation == Permutation([0, 1, 2, 4, 3, 5, 6, 7]) + + cg1 = _array_contraction( + _permute_dims( + _array_tensor_product(N, Q, Q, M), + [2, 1, 5, 4, 0, 3, 6, 7]), + [1, 2, 6]) + cg2 = _permute_dims(_array_contraction(_array_tensor_product(Q, Q, N, M), (3, 5, 6)), [0, 2, 3, 1, 4]) + assert cg1 == cg2 + + cg1 = _array_contraction( + _array_contraction( + _array_contraction( + _array_contraction( + _permute_dims( + _array_tensor_product(N, Q, Q, M), + [2, 1, 5, 4, 0, 3, 6, 7]), + [1, 2, 6]), + [1, 3, 4]), + [1]), + [0]) + cg2 = _array_contraction(_array_tensor_product(M, N, Q, Q), (0, 3, 5), (1, 4, 7), (2,), (6,)) + assert cg1 == cg2 + + +def test_arrayexpr_canonicalize_diagonal__permute_dims(): + tp = _array_tensor_product(M, Q, N, P) + expr = _array_diagonal( + _permute_dims(tp, [0, 1, 2, 4, 7, 6, 3, 5]), (2, 4, 5), (6, 7), + (0, 3)) + result = _array_diagonal(tp, (2, 6, 7), (3, 5), (0, 4)) + assert expr == result + + tp = _array_tensor_product(M, N, P, Q) + expr = _array_diagonal(_permute_dims(tp, [0, 5, 2, 4, 1, 6, 3, 7]), (1, 2, 6), (3, 4)) + result = _array_diagonal(_array_tensor_product(M, P, N, Q), (3, 4, 5), (1, 2)) + assert expr == result + + +def test_arrayexpr_canonicalize_diagonal_contraction(): + tp = _array_tensor_product(M, N, P, Q) + expr = _array_contraction(_array_diagonal(tp, (1, 3, 4)), (0, 3)) + result = _array_diagonal(_array_contraction(_array_tensor_product(M, N, P, Q), (0, 6)), (0, 2, 3)) + assert expr == result + + expr = _array_contraction(_array_diagonal(tp, (0, 1, 2, 3, 7)), (1, 2, 3)) + result = _array_contraction(_array_tensor_product(M, N, P, Q), (0, 1, 2, 3, 5, 6, 7)) + assert expr == result + + expr = _array_contraction(_array_diagonal(tp, (0, 2, 6, 7)), (1, 2, 3)) + result = _array_diagonal(_array_contraction(tp, (3, 4, 5)), (0, 2, 3, 4)) + assert expr == result + + td = _array_diagonal(_array_tensor_product(M, N, P, Q), (0, 3)) + expr = _array_contraction(td, (2, 1), (0, 4, 6, 5, 3)) + result = _array_contraction(_array_tensor_product(M, N, P, Q), (0, 1, 3, 5, 6, 7), (2, 4)) + assert expr == result + + +def test_arrayexpr_array_wrong_permutation_size(): + cg = _array_tensor_product(M, N) + raises(ValueError, lambda: _permute_dims(cg, [1, 0])) + raises(ValueError, lambda: _permute_dims(cg, [1, 0, 2, 3, 5, 4])) + + +def test_arrayexpr_nested_array_elementwise_add(): + cg = _array_contraction(_array_add( + _array_tensor_product(M, N), + _array_tensor_product(N, M) + ), (1, 2)) + result = _array_add( + _array_contraction(_array_tensor_product(M, N), (1, 2)), + _array_contraction(_array_tensor_product(N, M), (1, 2)) + ) + assert cg == result + + cg = _array_diagonal(_array_add( + _array_tensor_product(M, N), + _array_tensor_product(N, M) + ), (1, 2)) + result = _array_add( + _array_diagonal(_array_tensor_product(M, N), (1, 2)), + _array_diagonal(_array_tensor_product(N, M), (1, 2)) + ) + assert cg == result + + +def test_arrayexpr_array_expr_zero_array(): + za1 = ZeroArray(k, l, m, n) + zm1 = ZeroMatrix(m, n) + + za2 = ZeroArray(k, m, m, n) + zm2 = ZeroMatrix(m, m) + zm3 = ZeroMatrix(k, k) + + assert _array_tensor_product(M, N, za1) == ZeroArray(k, k, k, k, k, l, m, n) + assert _array_tensor_product(M, N, zm1) == ZeroArray(k, k, k, k, m, n) + + assert _array_contraction(za1, (3,)) == ZeroArray(k, l, m) + assert _array_contraction(zm1, (1,)) == ZeroArray(m) + assert _array_contraction(za2, (1, 2)) == ZeroArray(k, n) + assert _array_contraction(zm2, (0, 1)) == 0 + + assert _array_diagonal(za2, (1, 2)) == ZeroArray(k, n, m) + assert _array_diagonal(zm2, (0, 1)) == ZeroArray(m) + + assert _permute_dims(za1, [2, 1, 3, 0]) == ZeroArray(m, l, n, k) + assert _permute_dims(zm1, [1, 0]) == ZeroArray(n, m) + + assert _array_add(za1) == za1 + assert _array_add(zm1) == ZeroArray(m, n) + tp1 = _array_tensor_product(MatrixSymbol("A", k, l), MatrixSymbol("B", m, n)) + assert _array_add(tp1, za1) == tp1 + tp2 = _array_tensor_product(MatrixSymbol("C", k, l), MatrixSymbol("D", m, n)) + assert _array_add(tp1, za1, tp2) == _array_add(tp1, tp2) + assert _array_add(M, zm3) == M + assert _array_add(M, N, zm3) == _array_add(M, N) + + +def test_arrayexpr_array_expr_applyfunc(): + + A = ArraySymbol("A", (3, k, 2)) + aaf = ArrayElementwiseApplyFunc(sin, A) + assert aaf.shape == (3, k, 2) + + +def test_edit_array_contraction(): + cg = _array_contraction(_array_tensor_product(A, B, C, D), (1, 2, 5)) + ecg = _EditArrayContraction(cg) + assert ecg.to_array_contraction() == cg + + ecg.args_with_ind[1], ecg.args_with_ind[2] = ecg.args_with_ind[2], ecg.args_with_ind[1] + assert ecg.to_array_contraction() == _array_contraction(_array_tensor_product(A, C, B, D), (1, 3, 4)) + + ci = ecg.get_new_contraction_index() + new_arg = _ArgE(X) + new_arg.indices = [ci, ci] + ecg.args_with_ind.insert(2, new_arg) + assert ecg.to_array_contraction() == _array_contraction(_array_tensor_product(A, C, X, B, D), (1, 3, 6), (4, 5)) + + assert ecg.get_contraction_indices() == [[1, 3, 6], [4, 5]] + assert [[tuple(j) for j in i] for i in ecg.get_contraction_indices_to_ind_rel_pos()] == [[(0, 1), (1, 1), (3, 0)], [(2, 0), (2, 1)]] + assert [list(i) for i in ecg.get_mapping_for_index(0)] == [[0, 1], [1, 1], [3, 0]] + assert [list(i) for i in ecg.get_mapping_for_index(1)] == [[2, 0], [2, 1]] + raises(ValueError, lambda: ecg.get_mapping_for_index(2)) + + ecg.args_with_ind.pop(1) + assert ecg.to_array_contraction() == _array_contraction(_array_tensor_product(A, X, B, D), (1, 4), (2, 3)) + + ecg.args_with_ind[0].indices[1] = ecg.args_with_ind[1].indices[0] + ecg.args_with_ind[1].indices[1] = ecg.args_with_ind[2].indices[0] + assert ecg.to_array_contraction() == _array_contraction(_array_tensor_product(A, X, B, D), (1, 2), (3, 4)) + + ecg.insert_after(ecg.args_with_ind[1], _ArgE(C)) + assert ecg.to_array_contraction() == _array_contraction(_array_tensor_product(A, X, C, B, D), (1, 2), (3, 6)) + + +def test_array_expressions_no_canonicalization(): + + tp = _array_tensor_product(M, N, P) + + # ArrayTensorProduct: + + expr = ArrayTensorProduct(tp, N) + assert str(expr) == "ArrayTensorProduct(ArrayTensorProduct(M, N, P), N)" + assert expr.doit() == ArrayTensorProduct(M, N, P, N) + + expr = ArrayTensorProduct(ArrayContraction(M, (0, 1)), N) + assert str(expr) == "ArrayTensorProduct(ArrayContraction(M, (0, 1)), N)" + assert expr.doit() == ArrayContraction(ArrayTensorProduct(M, N), (0, 1)) + + expr = ArrayTensorProduct(ArrayDiagonal(M, (0, 1)), N) + assert str(expr) == "ArrayTensorProduct(ArrayDiagonal(M, (0, 1)), N)" + assert expr.doit() == PermuteDims(ArrayDiagonal(ArrayTensorProduct(M, N), (0, 1)), [2, 0, 1]) + + expr = ArrayTensorProduct(PermuteDims(M, [1, 0]), N) + assert str(expr) == "ArrayTensorProduct(PermuteDims(M, (0 1)), N)" + assert expr.doit() == PermuteDims(ArrayTensorProduct(M, N), [1, 0, 2, 3]) + + # ArrayContraction: + + expr = ArrayContraction(_array_contraction(tp, (0, 2)), (0, 1)) + assert isinstance(expr, ArrayContraction) + assert isinstance(expr.expr, ArrayContraction) + assert str(expr) == "ArrayContraction(ArrayContraction(ArrayTensorProduct(M, N, P), (0, 2)), (0, 1))" + assert expr.doit() == ArrayContraction(tp, (0, 2), (1, 3)) + + expr = ArrayContraction(ArrayContraction(ArrayContraction(tp, (0, 1)), (0, 1)), (0, 1)) + assert expr.doit() == ArrayContraction(tp, (0, 1), (2, 3), (4, 5)) + # assert expr._canonicalize() == ArrayContraction(ArrayContraction(tp, (0, 1)), (0, 1), (2, 3)) + + expr = ArrayContraction(ArrayDiagonal(tp, (0, 1)), (0, 1)) + assert str(expr) == "ArrayContraction(ArrayDiagonal(ArrayTensorProduct(M, N, P), (0, 1)), (0, 1))" + assert expr.doit() == ArrayDiagonal(ArrayContraction(ArrayTensorProduct(N, M, P), (0, 1)), (0, 1)) + + expr = ArrayContraction(PermuteDims(M, [1, 0]), (0, 1)) + assert str(expr) == "ArrayContraction(PermuteDims(M, (0 1)), (0, 1))" + assert expr.doit() == ArrayContraction(M, (0, 1)) + + # ArrayDiagonal: + + expr = ArrayDiagonal(ArrayDiagonal(tp, (0, 2)), (0, 1)) + assert str(expr) == "ArrayDiagonal(ArrayDiagonal(ArrayTensorProduct(M, N, P), (0, 2)), (0, 1))" + assert expr.doit() == ArrayDiagonal(tp, (0, 2), (1, 3)) + + expr = ArrayDiagonal(ArrayDiagonal(ArrayDiagonal(tp, (0, 1)), (0, 1)), (0, 1)) + assert expr.doit() == ArrayDiagonal(tp, (0, 1), (2, 3), (4, 5)) + assert expr._canonicalize() == expr.doit() + + expr = ArrayDiagonal(ArrayContraction(tp, (0, 1)), (0, 1)) + assert str(expr) == "ArrayDiagonal(ArrayContraction(ArrayTensorProduct(M, N, P), (0, 1)), (0, 1))" + assert expr.doit() == expr + + expr = ArrayDiagonal(PermuteDims(M, [1, 0]), (0, 1)) + assert str(expr) == "ArrayDiagonal(PermuteDims(M, (0 1)), (0, 1))" + assert expr.doit() == ArrayDiagonal(M, (0, 1)) + + # ArrayAdd: + + expr = ArrayAdd(M) + assert isinstance(expr, ArrayAdd) + assert expr.doit() == M + + expr = ArrayAdd(ArrayAdd(M, N), P) + assert str(expr) == "ArrayAdd(ArrayAdd(M, N), P)" + assert expr.doit() == ArrayAdd(M, N, P) + + expr = ArrayAdd(M, ArrayAdd(N, ArrayAdd(P, M))) + assert expr.doit() == ArrayAdd(M, N, P, M) + assert expr._canonicalize() == ArrayAdd(M, N, ArrayAdd(P, M)) + + expr = ArrayAdd(M, ZeroArray(k, k), N) + assert str(expr) == "ArrayAdd(M, ZeroArray(k, k), N)" + assert expr.doit() == ArrayAdd(M, N) + + # PermuteDims: + + expr = PermuteDims(PermuteDims(M, [1, 0]), [1, 0]) + assert str(expr) == "PermuteDims(PermuteDims(M, (0 1)), (0 1))" + assert expr.doit() == M + + expr = PermuteDims(PermuteDims(PermuteDims(M, [1, 0]), [1, 0]), [1, 0]) + assert expr.doit() == PermuteDims(M, [1, 0]) + assert expr._canonicalize() == expr.doit() + + # Reshape + + expr = Reshape(A, (k**2,)) + assert expr.shape == (k**2,) + assert isinstance(expr, Reshape) + + +def test_array_expr_construction_with_functions(): + + tp = tensorproduct(M, N) + assert tp == ArrayTensorProduct(M, N) + + expr = tensorproduct(A, eye(2)) + assert expr == ArrayTensorProduct(A, eye(2)) + + # Contraction: + + expr = tensorcontraction(M, (0, 1)) + assert expr == ArrayContraction(M, (0, 1)) + + expr = tensorcontraction(tp, (1, 2)) + assert expr == ArrayContraction(tp, (1, 2)) + + expr = tensorcontraction(tensorcontraction(tp, (1, 2)), (0, 1)) + assert expr == ArrayContraction(tp, (0, 3), (1, 2)) + + # Diagonalization: + + expr = tensordiagonal(M, (0, 1)) + assert expr == ArrayDiagonal(M, (0, 1)) + + expr = tensordiagonal(tensordiagonal(tp, (0, 1)), (0, 1)) + assert expr == ArrayDiagonal(tp, (0, 1), (2, 3)) + + # Permutation of dimensions: + + expr = permutedims(M, [1, 0]) + assert expr == PermuteDims(M, [1, 0]) + + expr = permutedims(PermuteDims(tp, [1, 0, 2, 3]), [0, 1, 3, 2]) + assert expr == PermuteDims(tp, [1, 0, 3, 2]) + + expr = PermuteDims(tp, index_order_new=["a", "b", "c", "d"], index_order_old=["d", "c", "b", "a"]) + assert expr == PermuteDims(tp, [3, 2, 1, 0]) + + arr = Array(range(32)).reshape(2, 2, 2, 2, 2) + expr = PermuteDims(arr, index_order_new=["a", "b", "c", "d", "e"], index_order_old=['b', 'e', 'a', 'd', 'c']) + assert expr == PermuteDims(arr, [2, 0, 4, 3, 1]) + assert expr.as_explicit() == permutedims(arr, index_order_new=["a", "b", "c", "d", "e"], index_order_old=['b', 'e', 'a', 'd', 'c']) + + +def test_array_element_expressions(): + # Check commutative property: + assert M[0, 0]*N[0, 0] == N[0, 0]*M[0, 0] + + # Check derivatives: + assert M[0, 0].diff(M[0, 0]) == 1 + assert M[0, 0].diff(M[1, 0]) == 0 + assert M[0, 0].diff(N[0, 0]) == 0 + assert M[0, 1].diff(M[i, j]) == KroneckerDelta(i, 0)*KroneckerDelta(j, 1) + assert M[0, 1].diff(N[i, j]) == 0 + + K4 = ArraySymbol("K4", shape=(k, k, k, k)) + + assert K4[i, j, k, l].diff(K4[1, 2, 3, 4]) == ( + KroneckerDelta(i, 1)*KroneckerDelta(j, 2)*KroneckerDelta(k, 3)*KroneckerDelta(l, 4) + ) + + +def test_array_expr_reshape(): + + A = MatrixSymbol("A", 2, 2) + B = ArraySymbol("B", (2, 2, 2)) + C = Array([1, 2, 3, 4]) + + expr = Reshape(A, (4,)) + assert expr.expr == A + assert expr.shape == (4,) + assert expr.as_explicit() == Array([A[0, 0], A[0, 1], A[1, 0], A[1, 1]]) + + expr = Reshape(B, (2, 4)) + assert expr.expr == B + assert expr.shape == (2, 4) + ee = expr.as_explicit() + assert isinstance(ee, ImmutableDenseNDimArray) + assert ee.shape == (2, 4) + assert ee == Array([[B[0, 0, 0], B[0, 0, 1], B[0, 1, 0], B[0, 1, 1]], [B[1, 0, 0], B[1, 0, 1], B[1, 1, 0], B[1, 1, 1]]]) + + expr = Reshape(A, (k, 2)) + assert expr.shape == (k, 2) + + raises(ValueError, lambda: Reshape(A, (2, 3))) + raises(ValueError, lambda: Reshape(A, (3,))) + + expr = Reshape(C, (2, 2)) + assert expr.expr == C + assert expr.shape == (2, 2) + assert expr.doit() == Array([[1, 2], [3, 4]]) + + +def test_array_expr_as_explicit_with_explicit_component_arrays(): + # Test if .as_explicit() works with explicit-component arrays + # nested in array expressions: + from sympy.abc import x, y, z, t + A = Array([[x, y], [z, t]]) + assert ArrayTensorProduct(A, A).as_explicit() == tensorproduct(A, A) + assert ArrayDiagonal(A, (0, 1)).as_explicit() == tensordiagonal(A, (0, 1)) + assert ArrayContraction(A, (0, 1)).as_explicit() == tensorcontraction(A, (0, 1)) + assert ArrayAdd(A, A).as_explicit() == A + A + assert ArrayElementwiseApplyFunc(sin, A).as_explicit() == A.applyfunc(sin) + assert PermuteDims(A, [1, 0]).as_explicit() == permutedims(A, [1, 0]) + assert Reshape(A, [4]).as_explicit() == A.reshape(4) diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_arrayexpr_derivatives.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_arrayexpr_derivatives.py new file mode 100644 index 0000000000000000000000000000000000000000..bc0fcf63f2607b23feb38758e4f0994de4f0384b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_arrayexpr_derivatives.py @@ -0,0 +1,78 @@ +from sympy.core.symbol import symbols +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.matrices.expressions.matexpr import MatrixSymbol +from sympy.matrices.expressions.special import Identity +from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction +from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayTensorProduct, \ + PermuteDims, ArrayDiagonal, ArrayElementwiseApplyFunc, ArrayContraction, _permute_dims, Reshape +from sympy.tensor.array.expressions.arrayexpr_derivatives import array_derive + +k = symbols("k") + +I = Identity(k) +X = MatrixSymbol("X", k, k) +x = MatrixSymbol("x", k, 1) + +A = MatrixSymbol("A", k, k) +B = MatrixSymbol("B", k, k) +C = MatrixSymbol("C", k, k) +D = MatrixSymbol("D", k, k) + +A1 = ArraySymbol("A", (3, 2, k)) + + +def test_arrayexpr_derivatives1(): + + res = array_derive(X, X) + assert res == PermuteDims(ArrayTensorProduct(I, I), [0, 2, 1, 3]) + + cg = ArrayTensorProduct(A, X, B) + res = array_derive(cg, X) + assert res == _permute_dims( + ArrayTensorProduct(I, A, I, B), + [0, 4, 2, 3, 1, 5, 6, 7]) + + cg = ArrayContraction(X, (0, 1)) + res = array_derive(cg, X) + assert res == ArrayContraction(ArrayTensorProduct(I, I), (1, 3)) + + cg = ArrayDiagonal(X, (0, 1)) + res = array_derive(cg, X) + assert res == ArrayDiagonal(ArrayTensorProduct(I, I), (1, 3)) + + cg = ElementwiseApplyFunction(sin, X) + res = array_derive(cg, X) + assert res.dummy_eq(ArrayDiagonal( + ArrayTensorProduct( + ElementwiseApplyFunction(cos, X), + I, + I + ), (0, 3), (1, 5))) + + cg = ArrayElementwiseApplyFunc(sin, X) + res = array_derive(cg, X) + assert res.dummy_eq(ArrayDiagonal( + ArrayTensorProduct( + I, + I, + ArrayElementwiseApplyFunc(cos, X) + ), (1, 4), (3, 5))) + + res = array_derive(A1, A1) + assert res == PermuteDims( + ArrayTensorProduct(Identity(3), Identity(2), Identity(k)), + [0, 2, 4, 1, 3, 5] + ) + + cg = ArrayElementwiseApplyFunc(sin, A1) + res = array_derive(cg, A1) + assert res.dummy_eq(ArrayDiagonal( + ArrayTensorProduct( + Identity(3), Identity(2), Identity(k), + ArrayElementwiseApplyFunc(cos, A1) + ), (1, 6), (3, 7), (5, 8) + )) + + cg = Reshape(A, (k**2,)) + res = array_derive(cg, A) + assert res == Reshape(PermuteDims(ArrayTensorProduct(I, I), [0, 2, 1, 3]), (k, k, k**2)) diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_as_explicit.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_as_explicit.py new file mode 100644 index 0000000000000000000000000000000000000000..30cc61b1ee651ca032e165cd67926fa33c71354f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_as_explicit.py @@ -0,0 +1,63 @@ +from sympy.core.symbol import Symbol +from sympy.matrices.expressions.matexpr import MatrixSymbol +from sympy.tensor.array.arrayop import (permutedims, tensorcontraction, tensordiagonal, tensorproduct) +from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray +from sympy.tensor.array.expressions.array_expressions import ZeroArray, OneArray, ArraySymbol, \ + ArrayTensorProduct, PermuteDims, ArrayDiagonal, ArrayContraction, ArrayAdd +from sympy.testing.pytest import raises + + +def test_array_as_explicit_call(): + + assert ZeroArray(3, 2, 4).as_explicit() == ImmutableDenseNDimArray.zeros(3, 2, 4) + assert OneArray(3, 2, 4).as_explicit() == ImmutableDenseNDimArray([1 for i in range(3*2*4)]).reshape(3, 2, 4) + + k = Symbol("k") + X = ArraySymbol("X", (k, 3, 2)) + raises(ValueError, lambda: X.as_explicit()) + raises(ValueError, lambda: ZeroArray(k, 2, 3).as_explicit()) + raises(ValueError, lambda: OneArray(2, k, 2).as_explicit()) + + A = ArraySymbol("A", (3, 3)) + B = ArraySymbol("B", (3, 3)) + + texpr = tensorproduct(A, B) + assert isinstance(texpr, ArrayTensorProduct) + assert texpr.as_explicit() == tensorproduct(A.as_explicit(), B.as_explicit()) + + texpr = tensorcontraction(A, (0, 1)) + assert isinstance(texpr, ArrayContraction) + assert texpr.as_explicit() == A[0, 0] + A[1, 1] + A[2, 2] + + texpr = tensordiagonal(A, (0, 1)) + assert isinstance(texpr, ArrayDiagonal) + assert texpr.as_explicit() == ImmutableDenseNDimArray([A[0, 0], A[1, 1], A[2, 2]]) + + texpr = permutedims(A, [1, 0]) + assert isinstance(texpr, PermuteDims) + assert texpr.as_explicit() == permutedims(A.as_explicit(), [1, 0]) + + +def test_array_as_explicit_matrix_symbol(): + + A = MatrixSymbol("A", 3, 3) + B = MatrixSymbol("B", 3, 3) + + texpr = tensorproduct(A, B) + assert isinstance(texpr, ArrayTensorProduct) + assert texpr.as_explicit() == tensorproduct(A.as_explicit(), B.as_explicit()) + + texpr = tensorcontraction(A, (0, 1)) + assert isinstance(texpr, ArrayContraction) + assert texpr.as_explicit() == A[0, 0] + A[1, 1] + A[2, 2] + + texpr = tensordiagonal(A, (0, 1)) + assert isinstance(texpr, ArrayDiagonal) + assert texpr.as_explicit() == ImmutableDenseNDimArray([A[0, 0], A[1, 1], A[2, 2]]) + + texpr = permutedims(A, [1, 0]) + assert isinstance(texpr, PermuteDims) + assert texpr.as_explicit() == permutedims(A.as_explicit(), [1, 0]) + + expr = ArrayAdd(ArrayTensorProduct(A, B), ArrayTensorProduct(B, A)) + assert expr.as_explicit() == expr.args[0].as_explicit() + expr.args[1].as_explicit() diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_convert_array_to_indexed.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_convert_array_to_indexed.py new file mode 100644 index 0000000000000000000000000000000000000000..a6b713fbec94ab7808c5a8a778b3313402d9d0c7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_convert_array_to_indexed.py @@ -0,0 +1,61 @@ +from sympy import Sum, Dummy, sin +from sympy.tensor.array.expressions import ArraySymbol, ArrayTensorProduct, ArrayContraction, PermuteDims, \ + ArrayDiagonal, ArrayAdd, OneArray, ZeroArray, convert_indexed_to_array, ArrayElementwiseApplyFunc, Reshape +from sympy.tensor.array.expressions.from_array_to_indexed import convert_array_to_indexed + +from sympy.abc import i, j, k, l, m, n, o + + +def test_convert_array_to_indexed_main(): + A = ArraySymbol("A", (3, 3, 3)) + B = ArraySymbol("B", (3, 3)) + C = ArraySymbol("C", (3, 3)) + + d_ = Dummy("d_") + + assert convert_array_to_indexed(A, [i, j, k]) == A[i, j, k] + + expr = ArrayTensorProduct(A, B, C) + conv = convert_array_to_indexed(expr, [i,j,k,l,m,n,o]) + assert conv == A[i,j,k]*B[l,m]*C[n,o] + assert convert_indexed_to_array(conv, [i,j,k,l,m,n,o]) == expr + + expr = ArrayContraction(A, (0, 2)) + assert convert_array_to_indexed(expr, [i]).dummy_eq(Sum(A[d_, i, d_], (d_, 0, 2))) + + expr = ArrayDiagonal(A, (0, 2)) + assert convert_array_to_indexed(expr, [i, j]) == A[j, i, j] + + expr = PermuteDims(A, [1, 2, 0]) + conv = convert_array_to_indexed(expr, [i, j, k]) + assert conv == A[k, i, j] + assert convert_indexed_to_array(conv, [i, j, k]) == expr + + expr = ArrayAdd(B, C, PermuteDims(C, [1, 0])) + conv = convert_array_to_indexed(expr, [i, j]) + assert conv == B[i, j] + C[i, j] + C[j, i] + assert convert_indexed_to_array(conv, [i, j]) == expr + + expr = ArrayElementwiseApplyFunc(sin, A) + conv = convert_array_to_indexed(expr, [i, j, k]) + assert conv == sin(A[i, j, k]) + assert convert_indexed_to_array(conv, [i, j, k]).dummy_eq(expr) + + assert convert_array_to_indexed(OneArray(3, 3), [i, j]) == 1 + assert convert_array_to_indexed(ZeroArray(3, 3), [i, j]) == 0 + + expr = Reshape(A, (27,)) + assert convert_array_to_indexed(expr, [i]) == A[i // 9, i // 3 % 3, i % 3] + + X = ArraySymbol("X", (2, 3, 4, 5, 6)) + expr = Reshape(X, (2*3*4*5*6,)) + assert convert_array_to_indexed(expr, [i]) == X[i // 360, i // 120 % 3, i // 30 % 4, i // 6 % 5, i % 6] + + expr = Reshape(X, (4, 9, 2, 2, 5)) + one_index = 180*i + 20*j + 10*k + 5*l + m + expected = X[one_index // (3*4*5*6), one_index // (4*5*6) % 3, one_index // (5*6) % 4, one_index // 6 % 5, one_index % 6] + assert convert_array_to_indexed(expr, [i, j, k, l, m]) == expected + + X = ArraySymbol("X", (2*3*5,)) + expr = Reshape(X, (2, 3, 5)) + assert convert_array_to_indexed(expr, [i, j, k]) == X[15*i + 5*j + k] diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_convert_array_to_matrix.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_convert_array_to_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..26839d5e7cec0554948c6b726482f9d8ca250b1c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_convert_array_to_matrix.py @@ -0,0 +1,689 @@ +from sympy import Lambda, S, Dummy, KroneckerProduct +from sympy.core.symbol import symbols +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import cos, sin +from sympy.matrices.expressions.hadamard import HadamardProduct, HadamardPower +from sympy.matrices.expressions.special import (Identity, OneMatrix, ZeroMatrix) +from sympy.matrices.expressions.matexpr import MatrixElement +from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array +from sympy.tensor.array.expressions.from_array_to_matrix import _support_function_tp1_recognize, \ + _array_diag2contr_diagmatrix, convert_array_to_matrix, _remove_trivial_dims, _array2matrix, \ + _combine_removed, identify_removable_identity_matrices, _array_contraction_to_diagonal_multiple_identity +from sympy.matrices.expressions.matexpr import MatrixSymbol +from sympy.combinatorics import Permutation +from sympy.matrices.expressions.diagonal import DiagMatrix, DiagonalMatrix +from sympy.matrices import Trace, MatMul, Transpose +from sympy.tensor.array.expressions.array_expressions import ZeroArray, OneArray, \ + ArrayElement, ArraySymbol, ArrayElementwiseApplyFunc, _array_tensor_product, _array_contraction, \ + _array_diagonal, _permute_dims, PermuteDims, ArrayAdd, ArrayDiagonal, ArrayContraction, ArrayTensorProduct +from sympy.testing.pytest import raises + + +i, j, k, l, m, n = symbols("i j k l m n") + +I = Identity(k) +I1 = Identity(1) + +M = MatrixSymbol("M", k, k) +N = MatrixSymbol("N", k, k) +P = MatrixSymbol("P", k, k) +Q = MatrixSymbol("Q", k, k) + +A = MatrixSymbol("A", k, k) +B = MatrixSymbol("B", k, k) +C = MatrixSymbol("C", k, k) +D = MatrixSymbol("D", k, k) + +X = MatrixSymbol("X", k, k) +Y = MatrixSymbol("Y", k, k) + +a = MatrixSymbol("a", k, 1) +b = MatrixSymbol("b", k, 1) +c = MatrixSymbol("c", k, 1) +d = MatrixSymbol("d", k, 1) + +x = MatrixSymbol("x", k, 1) +y = MatrixSymbol("y", k, 1) + + +def test_arrayexpr_convert_array_to_matrix(): + + cg = _array_contraction(_array_tensor_product(M), (0, 1)) + assert convert_array_to_matrix(cg) == Trace(M) + + cg = _array_contraction(_array_tensor_product(M, N), (0, 1), (2, 3)) + assert convert_array_to_matrix(cg) == Trace(M) * Trace(N) + + cg = _array_contraction(_array_tensor_product(M, N), (0, 3), (1, 2)) + assert convert_array_to_matrix(cg) == Trace(M * N) + + cg = _array_contraction(_array_tensor_product(M, N), (0, 2), (1, 3)) + assert convert_array_to_matrix(cg) == Trace(M * N.T) + + cg = convert_matrix_to_array(M * N * P) + assert convert_array_to_matrix(cg) == M * N * P + + cg = convert_matrix_to_array(M * N.T * P) + assert convert_array_to_matrix(cg) == M * N.T * P + + cg = _array_contraction(_array_tensor_product(M,N,P,Q), (1, 2), (5, 6)) + assert convert_array_to_matrix(cg) == _array_tensor_product(M * N, P * Q) + + cg = _array_contraction(_array_tensor_product(-2, M, N), (1, 2)) + assert convert_array_to_matrix(cg) == -2 * M * N + + a = MatrixSymbol("a", k, 1) + b = MatrixSymbol("b", k, 1) + c = MatrixSymbol("c", k, 1) + cg = PermuteDims( + _array_contraction( + _array_tensor_product( + a, + ArrayAdd( + _array_tensor_product(b, c), + _array_tensor_product(c, b), + ) + ), (2, 4)), [0, 1, 3, 2]) + assert convert_array_to_matrix(cg) == a * (b.T * c + c.T * b) + + za = ZeroArray(m, n) + assert convert_array_to_matrix(za) == ZeroMatrix(m, n) + + cg = _array_tensor_product(3, M) + assert convert_array_to_matrix(cg) == 3 * M + + # Partial conversion to matrix multiplication: + expr = _array_contraction(_array_tensor_product(M, N, P, Q), (0, 2), (1, 4, 6)) + assert convert_array_to_matrix(expr) == _array_contraction(_array_tensor_product(M.T*N, P, Q), (0, 2, 4)) + + x = MatrixSymbol("x", k, 1) + cg = PermuteDims( + _array_contraction(_array_tensor_product(OneArray(1), x, OneArray(1), DiagMatrix(Identity(1))), + (0, 5)), Permutation(1, 2, 3)) + assert convert_array_to_matrix(cg) == x + + expr = ArrayAdd(M, PermuteDims(M, [1, 0])) + assert convert_array_to_matrix(expr) == M + Transpose(M) + + +def test_arrayexpr_convert_array_to_matrix2(): + cg = _array_contraction(_array_tensor_product(M, N), (1, 3)) + assert convert_array_to_matrix(cg) == M * N.T + + cg = PermuteDims(_array_tensor_product(M, N), Permutation([0, 1, 3, 2])) + assert convert_array_to_matrix(cg) == _array_tensor_product(M, N.T) + + cg = _array_tensor_product(M, PermuteDims(N, Permutation([1, 0]))) + assert convert_array_to_matrix(cg) == _array_tensor_product(M, N.T) + + cg = _array_contraction( + PermuteDims( + _array_tensor_product(M, N, P, Q), Permutation([0, 2, 3, 1, 4, 5, 7, 6])), + (1, 2), (3, 5) + ) + assert convert_array_to_matrix(cg) == _array_tensor_product(M * P.T * Trace(N), Q.T) + + cg = _array_contraction( + _array_tensor_product(M, N, P, PermuteDims(Q, Permutation([1, 0]))), + (1, 5), (2, 3) + ) + assert convert_array_to_matrix(cg) == _array_tensor_product(M * P.T * Trace(N), Q.T) + + cg = _array_tensor_product(M, PermuteDims(N, [1, 0])) + assert convert_array_to_matrix(cg) == _array_tensor_product(M, N.T) + + cg = _array_tensor_product(PermuteDims(M, [1, 0]), PermuteDims(N, [1, 0])) + assert convert_array_to_matrix(cg) == _array_tensor_product(M.T, N.T) + + cg = _array_tensor_product(PermuteDims(N, [1, 0]), PermuteDims(M, [1, 0])) + assert convert_array_to_matrix(cg) == _array_tensor_product(N.T, M.T) + + cg = _array_contraction(M, (0,), (1,)) + assert convert_array_to_matrix(cg) == OneMatrix(1, k)*M*OneMatrix(k, 1) + + cg = _array_contraction(x, (0,), (1,)) + assert convert_array_to_matrix(cg) == OneMatrix(1, k)*x + + Xm = MatrixSymbol("Xm", m, n) + cg = _array_contraction(Xm, (0,), (1,)) + assert convert_array_to_matrix(cg) == OneMatrix(1, m)*Xm*OneMatrix(n, 1) + + +def test_arrayexpr_convert_array_to_diagonalized_vector(): + + # Check matrix recognition over trivial dimensions: + + cg = _array_tensor_product(a, b) + assert convert_array_to_matrix(cg) == a * b.T + + cg = _array_tensor_product(I1, a, b) + assert convert_array_to_matrix(cg) == a * b.T + + # Recognize trace inside a tensor product: + + cg = _array_contraction(_array_tensor_product(A, B, C), (0, 3), (1, 2)) + assert convert_array_to_matrix(cg) == Trace(A * B) * C + + # Transform diagonal operator to contraction: + + cg = _array_diagonal(_array_tensor_product(A, a), (1, 2)) + assert _array_diag2contr_diagmatrix(cg) == _array_contraction(_array_tensor_product(A, OneArray(1), DiagMatrix(a)), (1, 3)) + assert convert_array_to_matrix(cg) == A * DiagMatrix(a) + + cg = _array_diagonal(_array_tensor_product(a, b), (0, 2)) + assert _array_diag2contr_diagmatrix(cg) == _permute_dims( + _array_contraction(_array_tensor_product(DiagMatrix(a), OneArray(1), b), (0, 3)), [1, 2, 0] + ) + assert convert_array_to_matrix(cg) == b.T * DiagMatrix(a) + + cg = _array_diagonal(_array_tensor_product(A, a), (0, 2)) + assert _array_diag2contr_diagmatrix(cg) == _array_contraction(_array_tensor_product(A, OneArray(1), DiagMatrix(a)), (0, 3)) + assert convert_array_to_matrix(cg) == A.T * DiagMatrix(a) + + cg = _array_diagonal(_array_tensor_product(I, x, I1), (0, 2), (3, 5)) + assert _array_diag2contr_diagmatrix(cg) == _array_contraction(_array_tensor_product(I, OneArray(1), I1, DiagMatrix(x)), (0, 5)) + assert convert_array_to_matrix(cg) == DiagMatrix(x) + + cg = _array_diagonal(_array_tensor_product(I, x, A, B), (1, 2), (5, 6)) + assert _array_diag2contr_diagmatrix(cg) == _array_diagonal(_array_contraction(_array_tensor_product(I, OneArray(1), A, B, DiagMatrix(x)), (1, 7)), (5, 6)) + # TODO: this is returning a wrong result: + # convert_array_to_matrix(cg) + + cg = _array_diagonal(_array_tensor_product(I1, a, b), (1, 3, 5)) + assert convert_array_to_matrix(cg) == a*b.T + + cg = _array_diagonal(_array_tensor_product(I1, a, b), (1, 3)) + assert _array_diag2contr_diagmatrix(cg) == _array_contraction(_array_tensor_product(OneArray(1), a, b, I1), (2, 6)) + assert convert_array_to_matrix(cg) == a*b.T + + cg = _array_diagonal(_array_tensor_product(x, I1), (1, 2)) + assert isinstance(cg, ArrayDiagonal) + assert cg.diagonal_indices == ((1, 2),) + assert convert_array_to_matrix(cg) == x + + cg = _array_diagonal(_array_tensor_product(x, I), (0, 2)) + assert _array_diag2contr_diagmatrix(cg) == _array_contraction(_array_tensor_product(OneArray(1), I, DiagMatrix(x)), (1, 3)) + assert convert_array_to_matrix(cg).doit() == DiagMatrix(x) + + raises(ValueError, lambda: _array_diagonal(x, (1,))) + + # Ignore identity matrices with contractions: + + cg = _array_contraction(_array_tensor_product(I, A, I, I), (0, 2), (1, 3), (5, 7)) + assert cg.split_multiple_contractions() == cg + assert convert_array_to_matrix(cg) == Trace(A) * I + + cg = _array_contraction(_array_tensor_product(Trace(A) * I, I, I), (1, 5), (3, 4)) + assert cg.split_multiple_contractions() == cg + assert convert_array_to_matrix(cg).doit() == Trace(A) * I + + # Add DiagMatrix when required: + + cg = _array_contraction(_array_tensor_product(A, a), (1, 2)) + assert cg.split_multiple_contractions() == cg + assert convert_array_to_matrix(cg) == A * a + + cg = _array_contraction(_array_tensor_product(A, a, B), (1, 2, 4)) + assert cg.split_multiple_contractions() == _array_contraction(_array_tensor_product(A, DiagMatrix(a), OneArray(1), B), (1, 2), (3, 5)) + assert convert_array_to_matrix(cg) == A * DiagMatrix(a) * B + + cg = _array_contraction(_array_tensor_product(A, a, B), (0, 2, 4)) + assert cg.split_multiple_contractions() == _array_contraction(_array_tensor_product(A, DiagMatrix(a), OneArray(1), B), (0, 2), (3, 5)) + assert convert_array_to_matrix(cg) == A.T * DiagMatrix(a) * B + + cg = _array_contraction(_array_tensor_product(A, a, b, a.T, B), (0, 2, 4, 7, 9)) + assert cg.split_multiple_contractions() == _array_contraction(_array_tensor_product(A, DiagMatrix(a), OneArray(1), + DiagMatrix(b), OneArray(1), DiagMatrix(a), OneArray(1), B), + (0, 2), (3, 5), (6, 9), (8, 12)) + assert convert_array_to_matrix(cg) == A.T * DiagMatrix(a) * DiagMatrix(b) * DiagMatrix(a) * B.T + + cg = _array_contraction(_array_tensor_product(I1, I1, I1), (1, 2, 4)) + assert cg.split_multiple_contractions() == _array_contraction(_array_tensor_product(I1, I1, OneArray(1), I1), (1, 2), (3, 5)) + assert convert_array_to_matrix(cg) == 1 + + cg = _array_contraction(_array_tensor_product(I, I, I, I, A), (1, 2, 8), (5, 6, 9)) + assert convert_array_to_matrix(cg.split_multiple_contractions()).doit() == A + + cg = _array_contraction(_array_tensor_product(A, a, C, a, B), (1, 2, 4), (5, 6, 8)) + expected = _array_contraction(_array_tensor_product(A, DiagMatrix(a), OneArray(1), C, DiagMatrix(a), OneArray(1), B), (1, 3), (2, 5), (6, 7), (8, 10)) + assert cg.split_multiple_contractions() == expected + assert convert_array_to_matrix(cg) == A * DiagMatrix(a) * C * DiagMatrix(a) * B + + cg = _array_contraction(_array_tensor_product(a, I1, b, I1, (a.T*b).applyfunc(cos)), (1, 2, 8), (5, 6, 9)) + expected = _array_contraction(_array_tensor_product(a, I1, OneArray(1), b, I1, OneArray(1), (a.T*b).applyfunc(cos)), + (1, 3), (2, 10), (6, 8), (7, 11)) + assert cg.split_multiple_contractions().dummy_eq(expected) + assert convert_array_to_matrix(cg).doit().dummy_eq(MatMul(a, (a.T * b).applyfunc(cos), b.T)) + + +def test_arrayexpr_convert_array_contraction_tp_additions(): + a = ArrayAdd( + _array_tensor_product(M, N), + _array_tensor_product(N, M) + ) + tp = _array_tensor_product(P, a, Q) + expr = _array_contraction(tp, (3, 4)) + expected = _array_tensor_product( + P, + ArrayAdd( + _array_contraction(_array_tensor_product(M, N), (1, 2)), + _array_contraction(_array_tensor_product(N, M), (1, 2)), + ), + Q + ) + assert expr == expected + assert convert_array_to_matrix(expr) == _array_tensor_product(P, M * N + N * M, Q) + + expr = _array_contraction(tp, (1, 2), (3, 4), (5, 6)) + result = _array_contraction( + _array_tensor_product( + P, + ArrayAdd( + _array_contraction(_array_tensor_product(M, N), (1, 2)), + _array_contraction(_array_tensor_product(N, M), (1, 2)), + ), + Q + ), (1, 2), (3, 4)) + assert expr == result + assert convert_array_to_matrix(expr) == P * (M * N + N * M) * Q + + +def test_arrayexpr_convert_array_to_implicit_matmul(): + # Trivial dimensions are suppressed, so the result can be expressed in matrix form: + + cg = _array_tensor_product(a, b) + assert convert_array_to_matrix(cg) == a * b.T + + cg = _array_tensor_product(a, b, I) + assert convert_array_to_matrix(cg) == _array_tensor_product(a*b.T, I) + + cg = _array_tensor_product(I, a, b) + assert convert_array_to_matrix(cg) == _array_tensor_product(I, a*b.T) + + cg = _array_tensor_product(a, I, b) + assert convert_array_to_matrix(cg) == _array_tensor_product(a, I, b) + + cg = _array_contraction(_array_tensor_product(I, I), (1, 2)) + assert convert_array_to_matrix(cg) == I + + cg = PermuteDims(_array_tensor_product(I, Identity(1)), [0, 2, 1, 3]) + assert convert_array_to_matrix(cg) == I + + +def test_arrayexpr_convert_array_to_matrix_remove_trivial_dims(): + + # Tensor Product: + assert _remove_trivial_dims(_array_tensor_product(a, b)) == (a * b.T, [1, 3]) + assert _remove_trivial_dims(_array_tensor_product(a.T, b)) == (a * b.T, [0, 3]) + assert _remove_trivial_dims(_array_tensor_product(a, b.T)) == (a * b.T, [1, 2]) + assert _remove_trivial_dims(_array_tensor_product(a.T, b.T)) == (a * b.T, [0, 2]) + + assert _remove_trivial_dims(_array_tensor_product(I, a.T, b.T)) == (_array_tensor_product(I, a * b.T), [2, 4]) + assert _remove_trivial_dims(_array_tensor_product(a.T, I, b.T)) == (_array_tensor_product(a.T, I, b.T), []) + + assert _remove_trivial_dims(_array_tensor_product(a, I)) == (_array_tensor_product(a, I), []) + assert _remove_trivial_dims(_array_tensor_product(I, a)) == (_array_tensor_product(I, a), []) + + assert _remove_trivial_dims(_array_tensor_product(a.T, b.T, c, d)) == ( + _array_tensor_product(a * b.T, c * d.T), [0, 2, 5, 7]) + assert _remove_trivial_dims(_array_tensor_product(a.T, I, b.T, c, d, I)) == ( + _array_tensor_product(a.T, I, b*c.T, d, I), [4, 7]) + + # Addition: + + cg = ArrayAdd(_array_tensor_product(a, b), _array_tensor_product(c, d)) + assert _remove_trivial_dims(cg) == (a * b.T + c * d.T, [1, 3]) + + # Permute Dims: + + cg = PermuteDims(_array_tensor_product(a, b), Permutation(3)(1, 2)) + assert _remove_trivial_dims(cg) == (a * b.T, [2, 3]) + + cg = PermuteDims(_array_tensor_product(a, I, b), Permutation(5)(1, 2, 3, 4)) + assert _remove_trivial_dims(cg) == (cg, []) + + cg = PermuteDims(_array_tensor_product(I, b, a), Permutation(5)(1, 2, 4, 5, 3)) + assert _remove_trivial_dims(cg) == (PermuteDims(_array_tensor_product(I, b * a.T), [0, 2, 3, 1]), [4, 5]) + + # Diagonal: + + cg = _array_diagonal(_array_tensor_product(M, a), (1, 2)) + assert _remove_trivial_dims(cg) == (cg, []) + + # Contraction: + + cg = _array_contraction(_array_tensor_product(M, a), (1, 2)) + assert _remove_trivial_dims(cg) == (cg, []) + + # A few more cases to test the removal and shift of nested removed axes + # with array contractions and array diagonals: + tp = _array_tensor_product( + OneMatrix(1, 1), + M, + x, + OneMatrix(1, 1), + Identity(1), + ) + + expr = _array_contraction(tp, (1, 8)) + rexpr, removed = _remove_trivial_dims(expr) + assert removed == [0, 5, 6, 7] + + expr = _array_contraction(tp, (1, 8), (3, 4)) + rexpr, removed = _remove_trivial_dims(expr) + assert removed == [0, 3, 4, 5] + + expr = _array_diagonal(tp, (1, 8)) + rexpr, removed = _remove_trivial_dims(expr) + assert removed == [0, 5, 6, 7, 8] + + expr = _array_diagonal(tp, (1, 8), (3, 4)) + rexpr, removed = _remove_trivial_dims(expr) + assert removed == [0, 3, 4, 5, 6] + + expr = _array_diagonal(_array_contraction(_array_tensor_product(A, x, I, I1), (1, 2, 5)), (1, 4)) + rexpr, removed = _remove_trivial_dims(expr) + assert removed == [2, 3] + + cg = _array_diagonal(_array_tensor_product(PermuteDims(_array_tensor_product(x, I1), Permutation(1, 2, 3)), (x.T*x).applyfunc(sqrt)), (2, 4), (3, 5)) + rexpr, removed = _remove_trivial_dims(cg) + assert removed == [1, 2] + + # Contractions with identity matrices need to be followed by a permutation + # in order + cg = _array_contraction(_array_tensor_product(A, B, C, M, I), (1, 8)) + ret, removed = _remove_trivial_dims(cg) + assert ret == PermuteDims(_array_tensor_product(A, B, C, M), [0, 2, 3, 4, 5, 6, 7, 1]) + assert removed == [] + + cg = _array_contraction(_array_tensor_product(A, B, C, M, I), (1, 8), (3, 4)) + ret, removed = _remove_trivial_dims(cg) + assert ret == PermuteDims(_array_contraction(_array_tensor_product(A, B, C, M), (3, 4)), [0, 2, 3, 4, 5, 1]) + assert removed == [] + + # Trivial matrices are sometimes inserted into MatMul expressions: + + cg = _array_tensor_product(b*b.T, a.T*a) + ret, removed = _remove_trivial_dims(cg) + assert ret == b*a.T*a*b.T + assert removed == [2, 3] + + Xs = ArraySymbol("X", (3, 2, k)) + cg = _array_tensor_product(M, Xs, b.T*c, a*a.T, b*b.T, c.T*d) + ret, removed = _remove_trivial_dims(cg) + assert ret == _array_tensor_product(M, Xs, a*b.T*c*c.T*d*a.T, b*b.T) + assert removed == [5, 6, 11, 12] + + cg = _array_diagonal(_array_tensor_product(I, I1, x), (1, 4), (3, 5)) + assert _remove_trivial_dims(cg) == (PermuteDims(_array_diagonal(_array_tensor_product(I, x), (1, 2)), Permutation(1, 2)), [1]) + + expr = _array_diagonal(_array_tensor_product(x, I, y), (0, 2)) + assert _remove_trivial_dims(expr) == (PermuteDims(_array_tensor_product(DiagMatrix(x), y), [1, 2, 3, 0]), [0]) + + expr = _array_diagonal(_array_tensor_product(x, I, y), (0, 2), (3, 4)) + assert _remove_trivial_dims(expr) == (expr, []) + + +def test_arrayexpr_convert_array_to_matrix_diag2contraction_diagmatrix(): + cg = _array_diagonal(_array_tensor_product(M, a), (1, 2)) + res = _array_diag2contr_diagmatrix(cg) + assert res.shape == cg.shape + assert res == _array_contraction(_array_tensor_product(M, OneArray(1), DiagMatrix(a)), (1, 3)) + + raises(ValueError, lambda: _array_diagonal(_array_tensor_product(a, M), (1, 2))) + + cg = _array_diagonal(_array_tensor_product(a.T, M), (1, 2)) + res = _array_diag2contr_diagmatrix(cg) + assert res.shape == cg.shape + assert res == _array_contraction(_array_tensor_product(OneArray(1), M, DiagMatrix(a.T)), (1, 4)) + + cg = _array_diagonal(_array_tensor_product(a.T, M, N, b.T), (1, 2), (4, 7)) + res = _array_diag2contr_diagmatrix(cg) + assert res.shape == cg.shape + assert res == _array_contraction( + _array_tensor_product(OneArray(1), M, N, OneArray(1), DiagMatrix(a.T), DiagMatrix(b.T)), (1, 7), (3, 9)) + + cg = _array_diagonal(_array_tensor_product(a, M, N, b.T), (0, 2), (4, 7)) + res = _array_diag2contr_diagmatrix(cg) + assert res.shape == cg.shape + assert res == _array_contraction( + _array_tensor_product(OneArray(1), M, N, OneArray(1), DiagMatrix(a), DiagMatrix(b.T)), (1, 6), (3, 9)) + + cg = _array_diagonal(_array_tensor_product(a, M, N, b.T), (0, 4), (3, 7)) + res = _array_diag2contr_diagmatrix(cg) + assert res.shape == cg.shape + assert res == _array_contraction( + _array_tensor_product(OneArray(1), M, N, OneArray(1), DiagMatrix(a), DiagMatrix(b.T)), (3, 6), (2, 9)) + + I1 = Identity(1) + x = MatrixSymbol("x", k, 1) + A = MatrixSymbol("A", k, k) + cg = _array_diagonal(_array_tensor_product(x, A.T, I1), (0, 2)) + assert _array_diag2contr_diagmatrix(cg).shape == cg.shape + assert _array2matrix(cg).shape == cg.shape + + +def test_arrayexpr_convert_array_to_matrix_support_function(): + + assert _support_function_tp1_recognize([], [2 * k]) == 2 * k + + assert _support_function_tp1_recognize([(1, 2)], [A, 2 * k, B, 3]) == 6 * k * A * B + + assert _support_function_tp1_recognize([(0, 3), (1, 2)], [A, B]) == Trace(A * B) + + assert _support_function_tp1_recognize([(1, 2)], [A, B]) == A * B + assert _support_function_tp1_recognize([(0, 2)], [A, B]) == A.T * B + assert _support_function_tp1_recognize([(1, 3)], [A, B]) == A * B.T + assert _support_function_tp1_recognize([(0, 3)], [A, B]) == A.T * B.T + + assert _support_function_tp1_recognize([(1, 2), (5, 6)], [A, B, C, D]) == _array_tensor_product(A * B, C * D) + assert _support_function_tp1_recognize([(1, 4), (3, 6)], [A, B, C, D]) == PermuteDims( + _array_tensor_product(A * C, B * D), [0, 2, 1, 3]) + + assert _support_function_tp1_recognize([(0, 3), (1, 4)], [A, B, C]) == B * A * C + + assert _support_function_tp1_recognize([(9, 10), (1, 2), (5, 6), (3, 4), (7, 8)], + [X, Y, A, B, C, D]) == X * Y * A * B * C * D + + assert _support_function_tp1_recognize([(9, 10), (1, 2), (5, 6), (3, 4)], + [X, Y, A, B, C, D]) == _array_tensor_product(X * Y * A * B, C * D) + + assert _support_function_tp1_recognize([(1, 7), (3, 8), (4, 11)], [X, Y, A, B, C, D]) == PermuteDims( + _array_tensor_product(X * B.T, Y * C, A.T * D.T), [0, 2, 4, 1, 3, 5] + ) + + assert _support_function_tp1_recognize([(0, 1), (3, 6), (5, 8)], [X, A, B, C, D]) == PermuteDims( + _array_tensor_product(Trace(X) * A * C, B * D), [0, 2, 1, 3]) + + assert _support_function_tp1_recognize([(1, 2), (3, 4), (5, 6), (7, 8)], [A, A, B, C, D]) == A ** 2 * B * C * D + assert _support_function_tp1_recognize([(1, 2), (3, 4), (5, 6), (7, 8)], [X, A, B, C, D]) == X * A * B * C * D + + assert _support_function_tp1_recognize([(1, 6), (3, 8), (5, 10)], [X, Y, A, B, C, D]) == PermuteDims( + _array_tensor_product(X * B, Y * C, A * D), [0, 2, 4, 1, 3, 5] + ) + + assert _support_function_tp1_recognize([(1, 4), (3, 6)], [A, B, C, D]) == PermuteDims( + _array_tensor_product(A * C, B * D), [0, 2, 1, 3]) + + assert _support_function_tp1_recognize([(0, 4), (1, 7), (2, 5), (3, 8)], [X, A, B, C, D]) == C*X.T*B*A*D + + assert _support_function_tp1_recognize([(0, 4), (1, 7), (2, 5), (3, 8)], [X, A, B, C, D]) == C*X.T*B*A*D + + +def test_convert_array_to_hadamard_products(): + + expr = HadamardProduct(M, N) + cg = convert_matrix_to_array(expr) + ret = convert_array_to_matrix(cg) + assert ret == expr + + expr = HadamardProduct(M, N)*P + cg = convert_matrix_to_array(expr) + ret = convert_array_to_matrix(cg) + assert ret == expr + + expr = Q*HadamardProduct(M, N)*P + cg = convert_matrix_to_array(expr) + ret = convert_array_to_matrix(cg) + assert ret == expr + + expr = Q*HadamardProduct(M, N.T)*P + cg = convert_matrix_to_array(expr) + ret = convert_array_to_matrix(cg) + assert ret == expr + + expr = HadamardProduct(M, N)*HadamardProduct(Q, P) + cg = convert_matrix_to_array(expr) + ret = convert_array_to_matrix(cg) + assert expr == ret + + expr = P.T*HadamardProduct(M, N)*HadamardProduct(Q, P) + cg = convert_matrix_to_array(expr) + ret = convert_array_to_matrix(cg) + assert expr == ret + + # ArrayDiagonal should be converted + cg = _array_diagonal(_array_tensor_product(M, N, Q), (1, 3), (0, 2, 4)) + ret = convert_array_to_matrix(cg) + expected = PermuteDims(_array_diagonal(_array_tensor_product(HadamardProduct(M.T, N.T), Q), (1, 2)), [1, 0, 2]) + assert expected == ret + + # Special case that should return the same expression: + cg = _array_diagonal(_array_tensor_product(HadamardProduct(M, N), Q), (0, 2)) + ret = convert_array_to_matrix(cg) + assert ret == cg + + # Hadamard products with traces: + + expr = Trace(HadamardProduct(M, N)) + cg = convert_matrix_to_array(expr) + ret = convert_array_to_matrix(cg) + assert ret == Trace(HadamardProduct(M.T, N.T)) + + expr = Trace(A*HadamardProduct(M, N)) + cg = convert_matrix_to_array(expr) + ret = convert_array_to_matrix(cg) + assert ret == Trace(HadamardProduct(M, N)*A) + + expr = Trace(HadamardProduct(A, M)*N) + cg = convert_matrix_to_array(expr) + ret = convert_array_to_matrix(cg) + assert ret == Trace(HadamardProduct(M.T, N)*A) + + # These should not be converted into Hadamard products: + + cg = _array_diagonal(_array_tensor_product(M, N), (0, 1, 2, 3)) + ret = convert_array_to_matrix(cg) + assert ret == cg + + cg = _array_diagonal(_array_tensor_product(A), (0, 1)) + ret = convert_array_to_matrix(cg) + assert ret == cg + + cg = _array_diagonal(_array_tensor_product(M, N, P), (0, 2, 4), (1, 3, 5)) + assert convert_array_to_matrix(cg) == HadamardProduct(M, N, P) + + cg = _array_diagonal(_array_tensor_product(M, N, P), (0, 3, 4), (1, 2, 5)) + assert convert_array_to_matrix(cg) == HadamardProduct(M, P, N.T) + + cg = _array_diagonal(_array_tensor_product(I, I1, x), (1, 4), (3, 5)) + assert convert_array_to_matrix(cg) == DiagMatrix(x) + + +def test_identify_removable_identity_matrices(): + + D = DiagonalMatrix(MatrixSymbol("D", k, k)) + + cg = _array_contraction(_array_tensor_product(A, B, I), (1, 2, 4, 5)) + expected = _array_contraction(_array_tensor_product(A, B), (1, 2)) + assert identify_removable_identity_matrices(cg) == expected + + cg = _array_contraction(_array_tensor_product(A, B, C, I), (1, 3, 5, 6, 7)) + expected = _array_contraction(_array_tensor_product(A, B, C), (1, 3, 5)) + assert identify_removable_identity_matrices(cg) == expected + + # Tests with diagonal matrices: + + cg = _array_contraction(_array_tensor_product(A, B, D), (1, 2, 4, 5)) + ret = identify_removable_identity_matrices(cg) + expected = _array_contraction(_array_tensor_product(A, B, D), (1, 4), (2, 5)) + assert ret == expected + + cg = _array_contraction(_array_tensor_product(A, B, D, M, N), (1, 2, 4, 5, 6, 8)) + ret = identify_removable_identity_matrices(cg) + assert ret == cg + + +def test_combine_removed(): + + assert _combine_removed(6, [0, 1, 2], [0, 1, 2]) == [0, 1, 2, 3, 4, 5] + assert _combine_removed(8, [2, 5], [1, 3, 4]) == [1, 2, 4, 5, 6] + assert _combine_removed(8, [7], []) == [7] + + +def test_array_contraction_to_diagonal_multiple_identities(): + + expr = _array_contraction(_array_tensor_product(A, B, I, C), (1, 2, 4), (5, 6)) + assert _array_contraction_to_diagonal_multiple_identity(expr) == (expr, []) + assert convert_array_to_matrix(expr) == _array_contraction(_array_tensor_product(A, B, C), (1, 2, 4)) + + expr = _array_contraction(_array_tensor_product(A, I, I), (1, 2, 4)) + assert _array_contraction_to_diagonal_multiple_identity(expr) == (A, [2]) + assert convert_array_to_matrix(expr) == A + + expr = _array_contraction(_array_tensor_product(A, I, I, B), (1, 2, 4), (3, 6)) + assert _array_contraction_to_diagonal_multiple_identity(expr) == (expr, []) + + expr = _array_contraction(_array_tensor_product(A, I, I, B), (1, 2, 3, 4, 6)) + assert _array_contraction_to_diagonal_multiple_identity(expr) == (expr, []) + + +def test_convert_array_element_to_matrix(): + + expr = ArrayElement(M, (i, j)) + assert convert_array_to_matrix(expr) == MatrixElement(M, i, j) + + expr = ArrayElement(_array_contraction(_array_tensor_product(M, N), (1, 3)), (i, j)) + assert convert_array_to_matrix(expr) == MatrixElement(M*N.T, i, j) + + expr = ArrayElement(_array_tensor_product(M, N), (i, j, m, n)) + assert convert_array_to_matrix(expr) == expr + + +def test_convert_array_elementwise_function_to_matrix(): + + d = Dummy("d") + + expr = ArrayElementwiseApplyFunc(Lambda(d, sin(d)), x.T*y) + assert convert_array_to_matrix(expr) == sin(x.T*y) + + expr = ArrayElementwiseApplyFunc(Lambda(d, d**2), x.T*y) + assert convert_array_to_matrix(expr) == (x.T*y)**2 + + expr = ArrayElementwiseApplyFunc(Lambda(d, sin(d)), x) + assert convert_array_to_matrix(expr).dummy_eq(x.applyfunc(sin)) + + expr = ArrayElementwiseApplyFunc(Lambda(d, 1 / (2 * sqrt(d))), x) + assert convert_array_to_matrix(expr) == S.Half * HadamardPower(x, -S.Half) + + +def test_array2matrix(): + # See issue https://github.com/sympy/sympy/pull/22877 + expr = PermuteDims(ArrayContraction(ArrayTensorProduct(x, I, I1, x), (0, 3), (1, 7)), Permutation(2, 3)) + expected = PermuteDims(ArrayTensorProduct(x*x.T, I1), Permutation(3)(1, 2)) + assert _array2matrix(expr) == expected + + +def test_recognize_broadcasting(): + expr = ArrayTensorProduct(x.T*x, A) + assert _remove_trivial_dims(expr) == (KroneckerProduct(x.T*x, A), [0, 1]) + + expr = ArrayTensorProduct(A, x.T*x) + assert _remove_trivial_dims(expr) == (KroneckerProduct(A, x.T*x), [2, 3]) + + expr = ArrayTensorProduct(A, B, x.T*x, C) + assert _remove_trivial_dims(expr) == (ArrayTensorProduct(A, KroneckerProduct(B, x.T*x), C), [4, 5]) + + # Always prefer matrix multiplication to Kronecker product, if possible: + expr = ArrayTensorProduct(a, b, x.T*x) + assert _remove_trivial_dims(expr) == (a*x.T*x*b.T, [1, 3, 4, 5]) diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_convert_indexed_to_array.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_convert_indexed_to_array.py new file mode 100644 index 0000000000000000000000000000000000000000..258062eadeca041ae3c864dabeefd5165f1cef11 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_convert_indexed_to_array.py @@ -0,0 +1,205 @@ +from sympy import tanh +from sympy.concrete.summations import Sum +from sympy.core.symbol import symbols +from sympy.functions.special.tensor_functions import KroneckerDelta +from sympy.matrices.expressions.matexpr import MatrixSymbol +from sympy.matrices.expressions.special import Identity +from sympy.tensor.array.expressions import ArrayElementwiseApplyFunc +from sympy.tensor.indexed import IndexedBase +from sympy.combinatorics import Permutation +from sympy.tensor.array.expressions.array_expressions import ArrayContraction, ArrayTensorProduct, \ + ArrayDiagonal, ArrayAdd, PermuteDims, ArrayElement, _array_tensor_product, _array_contraction, _array_diagonal, \ + _array_add, _permute_dims, ArraySymbol, OneArray +from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix +from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array, _convert_indexed_to_array +from sympy.testing.pytest import raises + + +A, B = symbols("A B", cls=IndexedBase) +i, j, k, l, m, n = symbols("i j k l m n") +d0, d1, d2, d3 = symbols("d0:4") + +I = Identity(k) + +M = MatrixSymbol("M", k, k) +N = MatrixSymbol("N", k, k) +P = MatrixSymbol("P", k, k) +Q = MatrixSymbol("Q", k, k) + +a = MatrixSymbol("a", k, 1) +b = MatrixSymbol("b", k, 1) +c = MatrixSymbol("c", k, 1) +d = MatrixSymbol("d", k, 1) + + +def test_arrayexpr_convert_index_to_array_support_function(): + expr = M[i, j] + assert _convert_indexed_to_array(expr) == (M, (i, j)) + expr = M[i, j]*N[k, l] + assert _convert_indexed_to_array(expr) == (ArrayTensorProduct(M, N), (i, j, k, l)) + expr = M[i, j]*N[j, k] + assert _convert_indexed_to_array(expr) == (ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2)), (i, k, j)) + expr = Sum(M[i, j]*N[j, k], (j, 0, k-1)) + assert _convert_indexed_to_array(expr) == (ArrayContraction(ArrayTensorProduct(M, N), (1, 2)), (i, k)) + expr = M[i, j] + N[i, j] + assert _convert_indexed_to_array(expr) == (ArrayAdd(M, N), (i, j)) + expr = M[i, j] + N[j, i] + assert _convert_indexed_to_array(expr) == (ArrayAdd(M, PermuteDims(N, Permutation([1, 0]))), (i, j)) + expr = M[i, j] + M[j, i] + assert _convert_indexed_to_array(expr) == (ArrayAdd(M, PermuteDims(M, Permutation([1, 0]))), (i, j)) + expr = (M*N*P)[i, j] + assert _convert_indexed_to_array(expr) == (_array_contraction(ArrayTensorProduct(M, N, P), (1, 2), (3, 4)), (i, j)) + expr = expr.function # Disregard summation in previous expression + ret1, ret2 = _convert_indexed_to_array(expr) + assert ret1 == ArrayDiagonal(ArrayTensorProduct(M, N, P), (1, 2), (3, 4)) + assert str(ret2) == "(i, j, _i_1, _i_2)" + expr = KroneckerDelta(i, j)*M[i, k] + assert _convert_indexed_to_array(expr) == (M, ({i, j}, k)) + expr = KroneckerDelta(i, j)*KroneckerDelta(j, k)*M[i, l] + assert _convert_indexed_to_array(expr) == (M, ({i, j, k}, l)) + expr = KroneckerDelta(j, k)*(M[i, j]*N[k, l] + N[i, j]*M[k, l]) + assert _convert_indexed_to_array(expr) == (_array_diagonal(_array_add( + ArrayTensorProduct(M, N), + _permute_dims(ArrayTensorProduct(M, N), Permutation(0, 2)(1, 3)) + ), (1, 2)), (i, l, frozenset({j, k}))) + expr = KroneckerDelta(j, m)*KroneckerDelta(m, k)*(M[i, j]*N[k, l] + N[i, j]*M[k, l]) + assert _convert_indexed_to_array(expr) == (_array_diagonal(_array_add( + ArrayTensorProduct(M, N), + _permute_dims(ArrayTensorProduct(M, N), Permutation(0, 2)(1, 3)) + ), (1, 2)), (i, l, frozenset({j, m, k}))) + expr = KroneckerDelta(i, j)*KroneckerDelta(j, k)*KroneckerDelta(k,m)*M[i, 0]*KroneckerDelta(m, n) + assert _convert_indexed_to_array(expr) == (M, ({i, j, k, m, n}, 0)) + expr = M[i, i] + assert _convert_indexed_to_array(expr) == (ArrayDiagonal(M, (0, 1)), (i,)) + + +def test_arrayexpr_convert_indexed_to_array_expression(): + + s = Sum(A[i]*B[i], (i, 0, 3)) + cg = convert_indexed_to_array(s) + assert cg == ArrayContraction(ArrayTensorProduct(A, B), (0, 1)) + + expr = M*N + result = ArrayContraction(ArrayTensorProduct(M, N), (1, 2)) + elem = expr[i, j] + assert convert_indexed_to_array(elem) == result + + expr = M*N*M + elem = expr[i, j] + result = _array_contraction(_array_tensor_product(M, M, N), (1, 4), (2, 5)) + cg = convert_indexed_to_array(elem) + assert cg == result + + cg = convert_indexed_to_array((M * N * P)[i, j]) + assert cg == _array_contraction(ArrayTensorProduct(M, N, P), (1, 2), (3, 4)) + + cg = convert_indexed_to_array((M * N.T * P)[i, j]) + assert cg == _array_contraction(ArrayTensorProduct(M, N, P), (1, 3), (2, 4)) + + expr = -2*M*N + elem = expr[i, j] + cg = convert_indexed_to_array(elem) + assert cg == ArrayContraction(ArrayTensorProduct(-2, M, N), (1, 2)) + + +def test_arrayexpr_convert_array_element_to_array_expression(): + A = ArraySymbol("A", (k,)) + B = ArraySymbol("B", (k,)) + + s = Sum(A[i]*B[i], (i, 0, k-1)) + cg = convert_indexed_to_array(s) + assert cg == ArrayContraction(ArrayTensorProduct(A, B), (0, 1)) + + s = A[i]*B[i] + cg = convert_indexed_to_array(s) + assert cg == ArrayDiagonal(ArrayTensorProduct(A, B), (0, 1)) + + s = A[i]*B[j] + cg = convert_indexed_to_array(s, [i, j]) + assert cg == ArrayTensorProduct(A, B) + cg = convert_indexed_to_array(s, [j, i]) + assert cg == ArrayTensorProduct(B, A) + + s = tanh(A[i]*B[j]) + cg = convert_indexed_to_array(s, [i, j]) + assert cg.dummy_eq(ArrayElementwiseApplyFunc(tanh, ArrayTensorProduct(A, B))) + + +def test_arrayexpr_convert_indexed_to_array_and_back_to_matrix(): + + expr = a.T*b + elem = expr[0, 0] + cg = convert_indexed_to_array(elem) + assert cg == ArrayElement(ArrayContraction(ArrayTensorProduct(a, b), (0, 2)), [0, 0]) + + expr = M[i,j] + N[i,j] + p1, p2 = _convert_indexed_to_array(expr) + assert convert_array_to_matrix(p1) == M + N + + expr = M[i,j] + N[j,i] + p1, p2 = _convert_indexed_to_array(expr) + assert convert_array_to_matrix(p1) == M + N.T + + expr = M[i,j]*N[k,l] + N[i,j]*M[k,l] + p1, p2 = _convert_indexed_to_array(expr) + assert convert_array_to_matrix(p1) == ArrayAdd( + ArrayTensorProduct(M, N), + ArrayTensorProduct(N, M)) + + expr = (M*N*P)[i, j] + p1, p2 = _convert_indexed_to_array(expr) + assert convert_array_to_matrix(p1) == M * N * P + + expr = Sum(M[i,j]*(N*P)[j,m], (j, 0, k-1)) + p1, p2 = _convert_indexed_to_array(expr) + assert convert_array_to_matrix(p1) == M * N * P + + expr = Sum((P[j, m] + P[m, j])*(M[i,j]*N[m,n] + N[i,j]*M[m,n]), (j, 0, k-1), (m, 0, k-1)) + p1, p2 = _convert_indexed_to_array(expr) + assert convert_array_to_matrix(p1) == M * P * N + M * P.T * N + N * P * M + N * P.T * M + + +def test_arrayexpr_convert_indexed_to_array_out_of_bounds(): + + expr = Sum(M[i, i], (i, 0, 4)) + raises(ValueError, lambda: convert_indexed_to_array(expr)) + expr = Sum(M[i, i], (i, 0, k)) + raises(ValueError, lambda: convert_indexed_to_array(expr)) + expr = Sum(M[i, i], (i, 1, k-1)) + raises(ValueError, lambda: convert_indexed_to_array(expr)) + + expr = Sum(M[i, j]*N[j,m], (j, 0, 4)) + raises(ValueError, lambda: convert_indexed_to_array(expr)) + expr = Sum(M[i, j]*N[j,m], (j, 0, k)) + raises(ValueError, lambda: convert_indexed_to_array(expr)) + expr = Sum(M[i, j]*N[j,m], (j, 1, k-1)) + raises(ValueError, lambda: convert_indexed_to_array(expr)) + + +def test_arrayexpr_convert_indexed_to_array_broadcast(): + A = ArraySymbol("A", (3, 3)) + B = ArraySymbol("B", (3, 3)) + + expr = A[i, j] + B[k, l] + O2 = OneArray(3, 3) + expected = ArrayAdd(ArrayTensorProduct(A, O2), ArrayTensorProduct(O2, B)) + assert convert_indexed_to_array(expr) == expected + assert convert_indexed_to_array(expr, [i, j, k, l]) == expected + assert convert_indexed_to_array(expr, [l, k, i, j]) == ArrayAdd(PermuteDims(ArrayTensorProduct(O2, A), [1, 0, 2, 3]), PermuteDims(ArrayTensorProduct(B, O2), [1, 0, 2, 3])) + + expr = A[i, j] + B[j, k] + O1 = OneArray(3) + assert convert_indexed_to_array(expr, [i, j, k]) == ArrayAdd(ArrayTensorProduct(A, O1), ArrayTensorProduct(O1, B)) + + C = ArraySymbol("C", (d0, d1)) + D = ArraySymbol("D", (d3, d1)) + + expr = C[i, j] + D[k, j] + assert convert_indexed_to_array(expr, [i, j, k]) == ArrayAdd(ArrayTensorProduct(C, OneArray(d3)), PermuteDims(ArrayTensorProduct(OneArray(d0), D), [0, 2, 1])) + + X = ArraySymbol("X", (5, 3)) + + expr = X[i, n] - X[j, n] + assert convert_indexed_to_array(expr, [i, j, n]) == ArrayAdd(ArrayTensorProduct(-1, OneArray(5), X), PermuteDims(ArrayTensorProduct(X, OneArray(5)), [0, 2, 1])) + + raises(ValueError, lambda: convert_indexed_to_array(C[i, j] + D[i, j])) diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_convert_matrix_to_array.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_convert_matrix_to_array.py new file mode 100644 index 0000000000000000000000000000000000000000..142585882588df6aa0e4648d9d8881ea755f42a0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_convert_matrix_to_array.py @@ -0,0 +1,128 @@ +from sympy import Lambda, KroneckerProduct +from sympy.core.symbol import symbols, Dummy +from sympy.matrices.expressions.hadamard import (HadamardPower, HadamardProduct) +from sympy.matrices.expressions.inverse import Inverse +from sympy.matrices.expressions.matexpr import MatrixSymbol +from sympy.matrices.expressions.matpow import MatPow +from sympy.matrices.expressions.special import Identity +from sympy.matrices.expressions.trace import Trace +from sympy.matrices.expressions.transpose import Transpose +from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayContraction, \ + PermuteDims, ArrayDiagonal, ArrayElementwiseApplyFunc, _array_contraction, _array_tensor_product, Reshape +from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix +from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array + +i, j, k, l, m, n = symbols("i j k l m n") + +I = Identity(k) + +M = MatrixSymbol("M", k, k) +N = MatrixSymbol("N", k, k) +P = MatrixSymbol("P", k, k) +Q = MatrixSymbol("Q", k, k) + +A = MatrixSymbol("A", k, k) +B = MatrixSymbol("B", k, k) +C = MatrixSymbol("C", k, k) +D = MatrixSymbol("D", k, k) + +X = MatrixSymbol("X", k, k) +Y = MatrixSymbol("Y", k, k) + +a = MatrixSymbol("a", k, 1) +b = MatrixSymbol("b", k, 1) +c = MatrixSymbol("c", k, 1) +d = MatrixSymbol("d", k, 1) + + +def test_arrayexpr_convert_matrix_to_array(): + + expr = M*N + result = ArrayContraction(ArrayTensorProduct(M, N), (1, 2)) + assert convert_matrix_to_array(expr) == result + + expr = M*N*M + result = _array_contraction(ArrayTensorProduct(M, N, M), (1, 2), (3, 4)) + assert convert_matrix_to_array(expr) == result + + expr = Transpose(M) + assert convert_matrix_to_array(expr) == PermuteDims(M, [1, 0]) + + expr = M*Transpose(N) + assert convert_matrix_to_array(expr) == _array_contraction(_array_tensor_product(M, PermuteDims(N, [1, 0])), (1, 2)) + + expr = 3*M*N + res = convert_matrix_to_array(expr) + rexpr = convert_array_to_matrix(res) + assert expr == rexpr + + expr = 3*M + N*M.T*M + 4*k*N + res = convert_matrix_to_array(expr) + rexpr = convert_array_to_matrix(res) + assert expr == rexpr + + expr = Inverse(M)*N + rexpr = convert_array_to_matrix(convert_matrix_to_array(expr)) + assert expr == rexpr + + expr = M**2 + rexpr = convert_array_to_matrix(convert_matrix_to_array(expr)) + assert expr == rexpr + + expr = M*(2*N + 3*M) + res = convert_matrix_to_array(expr) + rexpr = convert_array_to_matrix(res) + assert expr == rexpr + + expr = Trace(M) + result = ArrayContraction(M, (0, 1)) + assert convert_matrix_to_array(expr) == result + + expr = 3*Trace(M) + result = ArrayContraction(ArrayTensorProduct(3, M), (0, 1)) + assert convert_matrix_to_array(expr) == result + + expr = 3*Trace(Trace(M) * M) + result = ArrayContraction(ArrayTensorProduct(3, M, M), (0, 1), (2, 3)) + assert convert_matrix_to_array(expr) == result + + expr = 3*Trace(M)**2 + result = ArrayContraction(ArrayTensorProduct(3, M, M), (0, 1), (2, 3)) + assert convert_matrix_to_array(expr) == result + + expr = HadamardProduct(M, N) + result = ArrayDiagonal(ArrayTensorProduct(M, N), (0, 2), (1, 3)) + assert convert_matrix_to_array(expr) == result + + expr = HadamardProduct(M*N, N*M) + result = ArrayDiagonal(ArrayContraction(ArrayTensorProduct(M, N, N, M), (1, 2), (5, 6)), (0, 2), (1, 3)) + assert convert_matrix_to_array(expr) == result + + expr = HadamardPower(M, 2) + result = ArrayDiagonal(ArrayTensorProduct(M, M), (0, 2), (1, 3)) + assert convert_matrix_to_array(expr) == result + + expr = HadamardPower(M*N, 2) + result = ArrayDiagonal(ArrayContraction(ArrayTensorProduct(M, N, M, N), (1, 2), (5, 6)), (0, 2), (1, 3)) + assert convert_matrix_to_array(expr) == result + + expr = HadamardPower(M, n) + d0 = Dummy("d0") + result = ArrayElementwiseApplyFunc(Lambda(d0, d0**n), M) + assert convert_matrix_to_array(expr).dummy_eq(result) + + expr = M**2 + assert isinstance(expr, MatPow) + assert convert_matrix_to_array(expr) == ArrayContraction(ArrayTensorProduct(M, M), (1, 2)) + + expr = a.T*b + cg = convert_matrix_to_array(expr) + assert cg == ArrayContraction(ArrayTensorProduct(a, b), (0, 2)) + + expr = KroneckerProduct(A, B) + cg = convert_matrix_to_array(expr) + assert cg == Reshape(PermuteDims(ArrayTensorProduct(A, B), [0, 2, 1, 3]), (k**2, k**2)) + + expr = KroneckerProduct(A, B, C, D) + cg = convert_matrix_to_array(expr) + assert cg == Reshape(PermuteDims(ArrayTensorProduct(A, B, C, D), [0, 2, 4, 6, 1, 3, 5, 7]), (k**4, k**4)) diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_deprecated_conv_modules.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_deprecated_conv_modules.py new file mode 100644 index 0000000000000000000000000000000000000000..b41b6105410a308e7774fce760b235497d0303bb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/tests/test_deprecated_conv_modules.py @@ -0,0 +1,22 @@ +from sympy import MatrixSymbol, symbols, Sum +from sympy.tensor.array.expressions import conv_array_to_indexed, from_array_to_indexed, ArrayTensorProduct, \ + ArrayContraction, conv_array_to_matrix, from_array_to_matrix, conv_matrix_to_array, from_matrix_to_array, \ + conv_indexed_to_array, from_indexed_to_array +from sympy.testing.pytest import warns +from sympy.utilities.exceptions import SymPyDeprecationWarning + + +def test_deprecated_conv_module_results(): + + M = MatrixSymbol("M", 3, 3) + N = MatrixSymbol("N", 3, 3) + i, j, d = symbols("i j d") + + x = ArrayContraction(ArrayTensorProduct(M, N), (1, 2)) + y = Sum(M[i, d]*N[d, j], (d, 0, 2)) + + with warns(SymPyDeprecationWarning, test_stacklevel=False): + assert conv_array_to_indexed.convert_array_to_indexed(x, [i, j]).dummy_eq(from_array_to_indexed.convert_array_to_indexed(x, [i, j])) + assert conv_array_to_matrix.convert_array_to_matrix(x) == from_array_to_matrix.convert_array_to_matrix(x) + assert conv_matrix_to_array.convert_matrix_to_array(M*N) == from_matrix_to_array.convert_matrix_to_array(M*N) + assert conv_indexed_to_array.convert_indexed_to_array(y) == from_indexed_to_array.convert_indexed_to_array(y) diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/utils.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e55c0e6ed47cdc9ff1c24cc92f006998aeb86822 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/expressions/utils.py @@ -0,0 +1,123 @@ +import bisect +from collections import defaultdict + +from sympy.combinatorics import Permutation +from sympy.core.containers import Tuple +from sympy.core.numbers import Integer + + +def _get_mapping_from_subranks(subranks): + mapping = {} + counter = 0 + for i, rank in enumerate(subranks): + for j in range(rank): + mapping[counter] = (i, j) + counter += 1 + return mapping + + +def _get_contraction_links(args, subranks, *contraction_indices): + mapping = _get_mapping_from_subranks(subranks) + contraction_tuples = [[mapping[j] for j in i] for i in contraction_indices] + dlinks = defaultdict(dict) + for links in contraction_tuples: + if len(links) == 2: + (arg1, pos1), (arg2, pos2) = links + dlinks[arg1][pos1] = (arg2, pos2) + dlinks[arg2][pos2] = (arg1, pos1) + continue + + return args, dict(dlinks) + + +def _sort_contraction_indices(pairing_indices): + pairing_indices = [Tuple(*sorted(i)) for i in pairing_indices] + pairing_indices.sort(key=lambda x: min(x)) + return pairing_indices + + +def _get_diagonal_indices(flattened_indices): + axes_contraction = defaultdict(list) + for i, ind in enumerate(flattened_indices): + if isinstance(ind, (int, Integer)): + # If the indices is a number, there can be no diagonal operation: + continue + axes_contraction[ind].append(i) + axes_contraction = {k: v for k, v in axes_contraction.items() if len(v) > 1} + # Put the diagonalized indices at the end: + ret_indices = [i for i in flattened_indices if i not in axes_contraction] + diag_indices = list(axes_contraction) + diag_indices.sort(key=lambda x: flattened_indices.index(x)) + diagonal_indices = [tuple(axes_contraction[i]) for i in diag_indices] + ret_indices += diag_indices + ret_indices = tuple(ret_indices) + return diagonal_indices, ret_indices + + +def _get_argindex(subindices, ind): + for i, sind in enumerate(subindices): + if ind == sind: + return i + if isinstance(sind, (set, frozenset)) and ind in sind: + return i + raise IndexError("%s not found in %s" % (ind, subindices)) + + +def _apply_recursively_over_nested_lists(func, arr): + if isinstance(arr, (tuple, list, Tuple)): + return tuple(_apply_recursively_over_nested_lists(func, i) for i in arr) + elif isinstance(arr, Tuple): + return Tuple.fromiter(_apply_recursively_over_nested_lists(func, i) for i in arr) + else: + return func(arr) + + +def _build_push_indices_up_func_transformation(flattened_contraction_indices): + shifts = {0: 0} + i = 0 + cumulative = 0 + while i < len(flattened_contraction_indices): + j = 1 + while i+j < len(flattened_contraction_indices): + if flattened_contraction_indices[i] + j != flattened_contraction_indices[i+j]: + break + j += 1 + cumulative += j + shifts[flattened_contraction_indices[i]] = cumulative + i += j + shift_keys = sorted(shifts.keys()) + + def func(idx): + return shifts[shift_keys[bisect.bisect_right(shift_keys, idx)-1]] + + def transform(j): + if j in flattened_contraction_indices: + return None + else: + return j - func(j) + + return transform + + +def _build_push_indices_down_func_transformation(flattened_contraction_indices): + N = flattened_contraction_indices[-1]+2 + + shifts = [i for i in range(N) if i not in flattened_contraction_indices] + + def transform(j): + if j < len(shifts): + return shifts[j] + else: + return j + shifts[-1] - len(shifts) + 1 + + return transform + + +def _apply_permutation_to_list(perm: Permutation, target_list: list): + """ + Permute a list according to the given permutation. + """ + new_list = [None for i in range(perm.size)] + for i, e in enumerate(target_list): + new_list[perm(i)] = e + return new_list diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/mutable_ndim_array.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/mutable_ndim_array.py new file mode 100644 index 0000000000000000000000000000000000000000..e1eaaf7241bc3b4a48234178d18da3aa5736e189 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/mutable_ndim_array.py @@ -0,0 +1,13 @@ +from sympy.tensor.array.ndim_array import NDimArray + + +class MutableNDimArray(NDimArray): + + def as_immutable(self): + raise NotImplementedError("abstract method") + + def as_mutable(self): + return self + + def _sympy_(self): + return self.as_immutable() diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/ndim_array.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/ndim_array.py new file mode 100644 index 0000000000000000000000000000000000000000..2b9a857b8cfd9ee46646c46f274636d6b9962b6e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/ndim_array.py @@ -0,0 +1,601 @@ +from sympy.core.basic import Basic +from sympy.core.containers import (Dict, Tuple) +from sympy.core.expr import Expr +from sympy.core.kind import Kind, NumberKind, UndefinedKind +from sympy.core.numbers import Integer +from sympy.core.singleton import S +from sympy.core.sympify import sympify +from sympy.external.gmpy import SYMPY_INTS +from sympy.printing.defaults import Printable + +import itertools +from collections.abc import Iterable + + +class ArrayKind(Kind): + """ + Kind for N-dimensional array in SymPy. + + This kind represents the multidimensional array that algebraic + operations are defined. Basic class for this kind is ``NDimArray``, + but any expression representing the array can have this. + + Parameters + ========== + + element_kind : Kind + Kind of the element. Default is :obj:NumberKind ``, + which means that the array contains only numbers. + + Examples + ======== + + Any instance of array class has ``ArrayKind``. + + >>> from sympy import NDimArray + >>> NDimArray([1,2,3]).kind + ArrayKind(NumberKind) + + Although expressions representing an array may be not instance of + array class, it will have ``ArrayKind`` as well. + + >>> from sympy import Integral + >>> from sympy.tensor.array import NDimArray + >>> from sympy.abc import x + >>> intA = Integral(NDimArray([1,2,3]), x) + >>> isinstance(intA, NDimArray) + False + >>> intA.kind + ArrayKind(NumberKind) + + Use ``isinstance()`` to check for ``ArrayKind` without specifying + the element kind. Use ``is`` with specifying the element kind. + + >>> from sympy.tensor.array import ArrayKind + >>> from sympy.core import NumberKind + >>> boolA = NDimArray([True, False]) + >>> isinstance(boolA.kind, ArrayKind) + True + >>> boolA.kind is ArrayKind(NumberKind) + False + + See Also + ======== + + shape : Function to return the shape of objects with ``MatrixKind``. + + """ + def __new__(cls, element_kind=NumberKind): + obj = super().__new__(cls, element_kind) + obj.element_kind = element_kind + return obj + + def __repr__(self): + return "ArrayKind(%s)" % self.element_kind + + @classmethod + def _union(cls, kinds) -> 'ArrayKind': + elem_kinds = {e.kind for e in kinds} + if len(elem_kinds) == 1: + elemkind, = elem_kinds + else: + elemkind = UndefinedKind + return ArrayKind(elemkind) + + +class NDimArray(Printable): + """N-dimensional array. + + Examples + ======== + + Create an N-dim array of zeros: + + >>> from sympy import MutableDenseNDimArray + >>> a = MutableDenseNDimArray.zeros(2, 3, 4) + >>> a + [[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]] + + Create an N-dim array from a list; + + >>> a = MutableDenseNDimArray([[2, 3], [4, 5]]) + >>> a + [[2, 3], [4, 5]] + + >>> b = MutableDenseNDimArray([[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]]) + >>> b + [[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]] + + Create an N-dim array from a flat list with dimension shape: + + >>> a = MutableDenseNDimArray([1, 2, 3, 4, 5, 6], (2, 3)) + >>> a + [[1, 2, 3], [4, 5, 6]] + + Create an N-dim array from a matrix: + + >>> from sympy import Matrix + >>> a = Matrix([[1,2],[3,4]]) + >>> a + Matrix([ + [1, 2], + [3, 4]]) + >>> b = MutableDenseNDimArray(a) + >>> b + [[1, 2], [3, 4]] + + Arithmetic operations on N-dim arrays + + >>> a = MutableDenseNDimArray([1, 1, 1, 1], (2, 2)) + >>> b = MutableDenseNDimArray([4, 4, 4, 4], (2, 2)) + >>> c = a + b + >>> c + [[5, 5], [5, 5]] + >>> a - b + [[-3, -3], [-3, -3]] + + """ + + _diff_wrt = True + is_scalar = False + + def __new__(cls, iterable, shape=None, **kwargs): + from sympy.tensor.array import ImmutableDenseNDimArray + return ImmutableDenseNDimArray(iterable, shape, **kwargs) + + def __getitem__(self, index): + raise NotImplementedError("A subclass of NDimArray should implement __getitem__") + + def _parse_index(self, index): + if isinstance(index, (SYMPY_INTS, Integer)): + if index >= self._loop_size: + raise ValueError("Only a tuple index is accepted") + return index + + if self._loop_size == 0: + raise ValueError("Index not valid with an empty array") + + if len(index) != self._rank: + raise ValueError('Wrong number of array axes') + + real_index = 0 + # check if input index can exist in current indexing + for i in range(self._rank): + if (index[i] >= self.shape[i]) or (index[i] < -self.shape[i]): + raise ValueError('Index ' + str(index) + ' out of border') + if index[i] < 0: + real_index += 1 + real_index = real_index*self.shape[i] + index[i] + + return real_index + + def _get_tuple_index(self, integer_index): + index = [] + for sh in reversed(self.shape): + index.append(integer_index % sh) + integer_index //= sh + index.reverse() + return tuple(index) + + def _check_symbolic_index(self, index): + # Check if any index is symbolic: + tuple_index = (index if isinstance(index, tuple) else (index,)) + if any((isinstance(i, Expr) and (not i.is_number)) for i in tuple_index): + for i, nth_dim in zip(tuple_index, self.shape): + if ((i < 0) == True) or ((i >= nth_dim) == True): + raise ValueError("index out of range") + from sympy.tensor import Indexed + return Indexed(self, *tuple_index) + return None + + def _setter_iterable_check(self, value): + from sympy.matrices.matrixbase import MatrixBase + if isinstance(value, (Iterable, MatrixBase, NDimArray)): + raise NotImplementedError + + @classmethod + def _scan_iterable_shape(cls, iterable): + def f(pointer): + if not isinstance(pointer, Iterable): + return [pointer], () + + if len(pointer) == 0: + return [], (0,) + + result = [] + elems, shapes = zip(*[f(i) for i in pointer]) + if len(set(shapes)) != 1: + raise ValueError("could not determine shape unambiguously") + for i in elems: + result.extend(i) + return result, (len(shapes),)+shapes[0] + + return f(iterable) + + @classmethod + def _handle_ndarray_creation_inputs(cls, iterable=None, shape=None, **kwargs): + from sympy.matrices.matrixbase import MatrixBase + from sympy.tensor.array import SparseNDimArray + + if shape is None: + if iterable is None: + shape = () + iterable = () + # Construction of a sparse array from a sparse array + elif isinstance(iterable, SparseNDimArray): + return iterable._shape, iterable._sparse_array + + # Construct N-dim array from another N-dim array: + elif isinstance(iterable, NDimArray): + shape = iterable.shape + + # Construct N-dim array from an iterable (numpy arrays included): + elif isinstance(iterable, Iterable): + iterable, shape = cls._scan_iterable_shape(iterable) + + # Construct N-dim array from a Matrix: + elif isinstance(iterable, MatrixBase): + shape = iterable.shape + + else: + shape = () + iterable = (iterable,) + + if isinstance(iterable, (Dict, dict)) and shape is not None: + new_dict = iterable.copy() + for k in new_dict: + if isinstance(k, (tuple, Tuple)): + new_key = 0 + for i, idx in enumerate(k): + new_key = new_key * shape[i] + idx + iterable[new_key] = iterable[k] + del iterable[k] + + if isinstance(shape, (SYMPY_INTS, Integer)): + shape = (shape,) + + if not all(isinstance(dim, (SYMPY_INTS, Integer)) for dim in shape): + raise TypeError("Shape should contain integers only.") + + return tuple(shape), iterable + + def __len__(self): + """Overload common function len(). Returns number of elements in array. + + Examples + ======== + + >>> from sympy import MutableDenseNDimArray + >>> a = MutableDenseNDimArray.zeros(3, 3) + >>> a + [[0, 0, 0], [0, 0, 0], [0, 0, 0]] + >>> len(a) + 9 + + """ + return self._loop_size + + @property + def shape(self): + """ + Returns array shape (dimension). + + Examples + ======== + + >>> from sympy import MutableDenseNDimArray + >>> a = MutableDenseNDimArray.zeros(3, 3) + >>> a.shape + (3, 3) + + """ + return self._shape + + def rank(self): + """ + Returns rank of array. + + Examples + ======== + + >>> from sympy import MutableDenseNDimArray + >>> a = MutableDenseNDimArray.zeros(3,4,5,6,3) + >>> a.rank() + 5 + + """ + return self._rank + + def diff(self, *args, **kwargs): + """ + Calculate the derivative of each element in the array. + + Examples + ======== + + >>> from sympy import ImmutableDenseNDimArray + >>> from sympy.abc import x, y + >>> M = ImmutableDenseNDimArray([[x, y], [1, x*y]]) + >>> M.diff(x) + [[1, 0], [0, y]] + + """ + from sympy.tensor.array.array_derivatives import ArrayDerivative + kwargs.setdefault('evaluate', True) + return ArrayDerivative(self.as_immutable(), *args, **kwargs) + + def _eval_derivative(self, base): + # Types are (base: scalar, self: array) + return self.applyfunc(lambda x: base.diff(x)) + + def _eval_derivative_n_times(self, s, n): + return Basic._eval_derivative_n_times(self, s, n) + + def applyfunc(self, f): + """Apply a function to each element of the N-dim array. + + Examples + ======== + + >>> from sympy import ImmutableDenseNDimArray + >>> m = ImmutableDenseNDimArray([i*2+j for i in range(2) for j in range(2)], (2, 2)) + >>> m + [[0, 1], [2, 3]] + >>> m.applyfunc(lambda i: 2*i) + [[0, 2], [4, 6]] + """ + from sympy.tensor.array import SparseNDimArray + from sympy.tensor.array.arrayop import Flatten + + if isinstance(self, SparseNDimArray) and f(S.Zero) == 0: + return type(self)({k: f(v) for k, v in self._sparse_array.items() if f(v) != 0}, self.shape) + + return type(self)(map(f, Flatten(self)), self.shape) + + def _sympystr(self, printer): + def f(sh, shape_left, i, j): + if len(shape_left) == 1: + return "["+", ".join([printer._print(self[self._get_tuple_index(e)]) for e in range(i, j)])+"]" + + sh //= shape_left[0] + return "[" + ", ".join([f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh) for e in range(shape_left[0])]) + "]" # + "\n"*len(shape_left) + + if self.rank() == 0: + return printer._print(self[()]) + if 0 in self.shape: + return f"{self.__class__.__name__}([], {self.shape})" + return f(self._loop_size, self.shape, 0, self._loop_size) + + def tolist(self): + """ + Converting MutableDenseNDimArray to one-dim list + + Examples + ======== + + >>> from sympy import MutableDenseNDimArray + >>> a = MutableDenseNDimArray([1, 2, 3, 4], (2, 2)) + >>> a + [[1, 2], [3, 4]] + >>> b = a.tolist() + >>> b + [[1, 2], [3, 4]] + """ + + def f(sh, shape_left, i, j): + if len(shape_left) == 1: + return [self[self._get_tuple_index(e)] for e in range(i, j)] + result = [] + sh //= shape_left[0] + for e in range(shape_left[0]): + result.append(f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh)) + return result + + return f(self._loop_size, self.shape, 0, self._loop_size) + + def __add__(self, other): + from sympy.tensor.array.arrayop import Flatten + + if not isinstance(other, NDimArray): + return NotImplemented + + if self.shape != other.shape: + raise ValueError("array shape mismatch") + result_list = [i+j for i,j in zip(Flatten(self), Flatten(other))] + + return type(self)(result_list, self.shape) + + def __sub__(self, other): + from sympy.tensor.array.arrayop import Flatten + + if not isinstance(other, NDimArray): + return NotImplemented + + if self.shape != other.shape: + raise ValueError("array shape mismatch") + result_list = [i-j for i,j in zip(Flatten(self), Flatten(other))] + + return type(self)(result_list, self.shape) + + def __mul__(self, other): + from sympy.matrices.matrixbase import MatrixBase + from sympy.tensor.array import SparseNDimArray + from sympy.tensor.array.arrayop import Flatten + + if isinstance(other, (Iterable, NDimArray, MatrixBase)): + raise ValueError("scalar expected, use tensorproduct(...) for tensorial product") + + other = sympify(other) + if isinstance(self, SparseNDimArray): + if other.is_zero: + return type(self)({}, self.shape) + return type(self)({k: other*v for (k, v) in self._sparse_array.items()}, self.shape) + + result_list = [i*other for i in Flatten(self)] + return type(self)(result_list, self.shape) + + def __rmul__(self, other): + from sympy.matrices.matrixbase import MatrixBase + from sympy.tensor.array import SparseNDimArray + from sympy.tensor.array.arrayop import Flatten + + if isinstance(other, (Iterable, NDimArray, MatrixBase)): + raise ValueError("scalar expected, use tensorproduct(...) for tensorial product") + + other = sympify(other) + if isinstance(self, SparseNDimArray): + if other.is_zero: + return type(self)({}, self.shape) + return type(self)({k: other*v for (k, v) in self._sparse_array.items()}, self.shape) + + result_list = [other*i for i in Flatten(self)] + return type(self)(result_list, self.shape) + + def __truediv__(self, other): + from sympy.matrices.matrixbase import MatrixBase + from sympy.tensor.array import SparseNDimArray + from sympy.tensor.array.arrayop import Flatten + + if isinstance(other, (Iterable, NDimArray, MatrixBase)): + raise ValueError("scalar expected") + + other = sympify(other) + if isinstance(self, SparseNDimArray) and other != S.Zero: + return type(self)({k: v/other for (k, v) in self._sparse_array.items()}, self.shape) + + result_list = [i/other for i in Flatten(self)] + return type(self)(result_list, self.shape) + + def __rtruediv__(self, other): + raise NotImplementedError('unsupported operation on NDimArray') + + def __neg__(self): + from sympy.tensor.array import SparseNDimArray + from sympy.tensor.array.arrayop import Flatten + + if isinstance(self, SparseNDimArray): + return type(self)({k: -v for (k, v) in self._sparse_array.items()}, self.shape) + + result_list = [-i for i in Flatten(self)] + return type(self)(result_list, self.shape) + + def __iter__(self): + def iterator(): + if self._shape: + for i in range(self._shape[0]): + yield self[i] + else: + yield self[()] + + return iterator() + + def __eq__(self, other): + """ + NDimArray instances can be compared to each other. + Instances equal if they have same shape and data. + + Examples + ======== + + >>> from sympy import MutableDenseNDimArray + >>> a = MutableDenseNDimArray.zeros(2, 3) + >>> b = MutableDenseNDimArray.zeros(2, 3) + >>> a == b + True + >>> c = a.reshape(3, 2) + >>> c == b + False + >>> a[0,0] = 1 + >>> b[0,0] = 2 + >>> a == b + False + """ + from sympy.tensor.array import SparseNDimArray + if not isinstance(other, NDimArray): + return False + + if not self.shape == other.shape: + return False + + if isinstance(self, SparseNDimArray) and isinstance(other, SparseNDimArray): + return dict(self._sparse_array) == dict(other._sparse_array) + + return list(self) == list(other) + + def __ne__(self, other): + return not self == other + + def _eval_transpose(self): + if self.rank() != 2: + raise ValueError("array rank not 2") + from .arrayop import permutedims + return permutedims(self, (1, 0)) + + def transpose(self): + return self._eval_transpose() + + def _eval_conjugate(self): + from sympy.tensor.array.arrayop import Flatten + + return self.func([i.conjugate() for i in Flatten(self)], self.shape) + + def conjugate(self): + return self._eval_conjugate() + + def _eval_adjoint(self): + return self.transpose().conjugate() + + def adjoint(self): + return self._eval_adjoint() + + def _slice_expand(self, s, dim): + if not isinstance(s, slice): + return (s,) + start, stop, step = s.indices(dim) + return [start + i*step for i in range((stop-start)//step)] + + def _get_slice_data_for_array_access(self, index): + sl_factors = [self._slice_expand(i, dim) for (i, dim) in zip(index, self.shape)] + eindices = itertools.product(*sl_factors) + return sl_factors, eindices + + def _get_slice_data_for_array_assignment(self, index, value): + if not isinstance(value, NDimArray): + value = type(self)(value) + sl_factors, eindices = self._get_slice_data_for_array_access(index) + slice_offsets = [min(i) if isinstance(i, list) else None for i in sl_factors] + # TODO: add checks for dimensions for `value`? + return value, eindices, slice_offsets + + @classmethod + def _check_special_bounds(cls, flat_list, shape): + if shape == () and len(flat_list) != 1: + raise ValueError("arrays without shape need one scalar value") + if shape == (0,) and len(flat_list) > 0: + raise ValueError("if array shape is (0,) there cannot be elements") + + def _check_index_for_getitem(self, index): + if isinstance(index, (SYMPY_INTS, Integer, slice)): + index = (index,) + + if len(index) < self.rank(): + index = tuple(index) + \ + tuple(slice(None) for i in range(len(index), self.rank())) + + if len(index) > self.rank(): + raise ValueError('Dimension of index greater than rank of array') + + return index + + +class ImmutableNDimArray(NDimArray, Basic): + _op_priority = 11.0 + + def __hash__(self): + return Basic.__hash__(self) + + def as_immutable(self): + return self + + def as_mutable(self): + raise NotImplementedError("abstract method") diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/sparse_ndim_array.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/sparse_ndim_array.py new file mode 100644 index 0000000000000000000000000000000000000000..f11aa95be8ec9d10a9104d48fb28f406fe43845e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/sparse_ndim_array.py @@ -0,0 +1,196 @@ +from sympy.core.basic import Basic +from sympy.core.containers import (Dict, Tuple) +from sympy.core.singleton import S +from sympy.core.sympify import _sympify +from sympy.tensor.array.mutable_ndim_array import MutableNDimArray +from sympy.tensor.array.ndim_array import NDimArray, ImmutableNDimArray +from sympy.utilities.iterables import flatten + +import functools + +class SparseNDimArray(NDimArray): + + def __new__(self, *args, **kwargs): + return ImmutableSparseNDimArray(*args, **kwargs) + + def __getitem__(self, index): + """ + Get an element from a sparse N-dim array. + + Examples + ======== + + >>> from sympy import MutableSparseNDimArray + >>> a = MutableSparseNDimArray(range(4), (2, 2)) + >>> a + [[0, 1], [2, 3]] + >>> a[0, 0] + 0 + >>> a[1, 1] + 3 + >>> a[0] + [0, 1] + >>> a[1] + [2, 3] + + Symbolic indexing: + + >>> from sympy.abc import i, j + >>> a[i, j] + [[0, 1], [2, 3]][i, j] + + Replace `i` and `j` to get element `(0, 0)`: + + >>> a[i, j].subs({i: 0, j: 0}) + 0 + + """ + syindex = self._check_symbolic_index(index) + if syindex is not None: + return syindex + + index = self._check_index_for_getitem(index) + + # `index` is a tuple with one or more slices: + if isinstance(index, tuple) and any(isinstance(i, slice) for i in index): + sl_factors, eindices = self._get_slice_data_for_array_access(index) + array = [self._sparse_array.get(self._parse_index(i), S.Zero) for i in eindices] + nshape = [len(el) for i, el in enumerate(sl_factors) if isinstance(index[i], slice)] + return type(self)(array, nshape) + else: + index = self._parse_index(index) + return self._sparse_array.get(index, S.Zero) + + @classmethod + def zeros(cls, *shape): + """ + Return a sparse N-dim array of zeros. + """ + return cls({}, shape) + + def tomatrix(self): + """ + Converts MutableDenseNDimArray to Matrix. Can convert only 2-dim array, else will raise error. + + Examples + ======== + + >>> from sympy import MutableSparseNDimArray + >>> a = MutableSparseNDimArray([1 for i in range(9)], (3, 3)) + >>> b = a.tomatrix() + >>> b + Matrix([ + [1, 1, 1], + [1, 1, 1], + [1, 1, 1]]) + """ + from sympy.matrices import SparseMatrix + if self.rank() != 2: + raise ValueError('Dimensions must be of size of 2') + + mat_sparse = {} + for key, value in self._sparse_array.items(): + mat_sparse[self._get_tuple_index(key)] = value + + return SparseMatrix(self.shape[0], self.shape[1], mat_sparse) + + def reshape(self, *newshape): + new_total_size = functools.reduce(lambda x,y: x*y, newshape) + if new_total_size != self._loop_size: + raise ValueError("Invalid reshape parameters " + newshape) + + return type(self)(self._sparse_array, newshape) + +class ImmutableSparseNDimArray(SparseNDimArray, ImmutableNDimArray): # type: ignore + + def __new__(cls, iterable=None, shape=None, **kwargs): + shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs) + shape = Tuple(*map(_sympify, shape)) + cls._check_special_bounds(flat_list, shape) + loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else len(flat_list) + + # Sparse array: + if isinstance(flat_list, (dict, Dict)): + sparse_array = Dict(flat_list) + else: + sparse_array = {} + for i, el in enumerate(flatten(flat_list)): + if el != 0: + sparse_array[i] = _sympify(el) + + sparse_array = Dict(sparse_array) + + self = Basic.__new__(cls, sparse_array, shape, **kwargs) + self._shape = shape + self._rank = len(shape) + self._loop_size = loop_size + self._sparse_array = sparse_array + + return self + + def __setitem__(self, index, value): + raise TypeError("immutable N-dim array") + + def as_mutable(self): + return MutableSparseNDimArray(self) + + +class MutableSparseNDimArray(MutableNDimArray, SparseNDimArray): + + def __new__(cls, iterable=None, shape=None, **kwargs): + shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs) + self = object.__new__(cls) + self._shape = shape + self._rank = len(shape) + self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else len(flat_list) + + # Sparse array: + if isinstance(flat_list, (dict, Dict)): + self._sparse_array = dict(flat_list) + return self + + self._sparse_array = {} + + for i, el in enumerate(flatten(flat_list)): + if el != 0: + self._sparse_array[i] = _sympify(el) + + return self + + def __setitem__(self, index, value): + """Allows to set items to MutableDenseNDimArray. + + Examples + ======== + + >>> from sympy import MutableSparseNDimArray + >>> a = MutableSparseNDimArray.zeros(2, 2) + >>> a[0, 0] = 1 + >>> a[1, 1] = 1 + >>> a + [[1, 0], [0, 1]] + """ + if isinstance(index, tuple) and any(isinstance(i, slice) for i in index): + value, eindices, slice_offsets = self._get_slice_data_for_array_assignment(index, value) + for i in eindices: + other_i = [ind - j for ind, j in zip(i, slice_offsets) if j is not None] + other_value = value[other_i] + complete_index = self._parse_index(i) + if other_value != 0: + self._sparse_array[complete_index] = other_value + elif complete_index in self._sparse_array: + self._sparse_array.pop(complete_index) + else: + index = self._parse_index(index) + value = _sympify(value) + if value == 0 and index in self._sparse_array: + self._sparse_array.pop(index) + else: + self._sparse_array[index] = value + + def as_immutable(self): + return ImmutableSparseNDimArray(self) + + @property + def free_symbols(self): + return {i for j in self._sparse_array.values() for i in j.free_symbols} diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__init__.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ef755e589d2662146437a189b9a66404a3c6796 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/test_array_comprehension.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/test_array_comprehension.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35a058505da008c2d670b645ca277343cb08f466 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/test_array_comprehension.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/test_array_derivatives.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/test_array_derivatives.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d5536c973ece83f311bed7a8be20f0290e2ac4e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/test_array_derivatives.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/test_arrayop.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/test_arrayop.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38a3212618392c8a1f0e716d70758c60f4490b80 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/test_arrayop.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/test_immutable_ndim_array.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/test_immutable_ndim_array.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..346e4e32d6eb378b745ef833df6d0796b7c563a4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/test_immutable_ndim_array.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/test_mutable_ndim_array.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/test_mutable_ndim_array.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bed3e582bdd96b32c4dad417762b6ab7470d777a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/test_mutable_ndim_array.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/test_ndim_array.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/test_ndim_array.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f19839f73595c70ca568ea61b39716b1307ee54 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/test_ndim_array.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/test_ndim_array_conversions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/test_ndim_array_conversions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6cb96bb0ecb30999fd1a5acf610d7b39d774ccdb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/__pycache__/test_ndim_array_conversions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/test_array_comprehension.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/test_array_comprehension.py new file mode 100644 index 0000000000000000000000000000000000000000..510e068f287fa04419712e5e9a16a314e522a62d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/test_array_comprehension.py @@ -0,0 +1,78 @@ +from sympy.tensor.array.array_comprehension import ArrayComprehension, ArrayComprehensionMap +from sympy.tensor.array import ImmutableDenseNDimArray +from sympy.abc import i, j, k, l +from sympy.testing.pytest import raises +from sympy.matrices import Matrix + + +def test_array_comprehension(): + a = ArrayComprehension(i*j, (i, 1, 3), (j, 2, 4)) + b = ArrayComprehension(i, (i, 1, j+1)) + c = ArrayComprehension(i+j+k+l, (i, 1, 2), (j, 1, 3), (k, 1, 4), (l, 1, 5)) + d = ArrayComprehension(k, (i, 1, 5)) + e = ArrayComprehension(i, (j, k+1, k+5)) + assert a.doit().tolist() == [[2, 3, 4], [4, 6, 8], [6, 9, 12]] + assert a.shape == (3, 3) + assert a.is_shape_numeric == True + assert a.tolist() == [[2, 3, 4], [4, 6, 8], [6, 9, 12]] + assert a.tomatrix() == Matrix([ + [2, 3, 4], + [4, 6, 8], + [6, 9, 12]]) + assert len(a) == 9 + assert isinstance(b.doit(), ArrayComprehension) + assert isinstance(a.doit(), ImmutableDenseNDimArray) + assert b.subs(j, 3) == ArrayComprehension(i, (i, 1, 4)) + assert b.free_symbols == {j} + assert b.shape == (j + 1,) + assert b.rank() == 1 + assert b.is_shape_numeric == False + assert c.free_symbols == set() + assert c.function == i + j + k + l + assert c.limits == ((i, 1, 2), (j, 1, 3), (k, 1, 4), (l, 1, 5)) + assert c.doit().tolist() == [[[[4, 5, 6, 7, 8], [5, 6, 7, 8, 9], [6, 7, 8, 9, 10], [7, 8, 9, 10, 11]], + [[5, 6, 7, 8, 9], [6, 7, 8, 9, 10], [7, 8, 9, 10, 11], [8, 9, 10, 11, 12]], + [[6, 7, 8, 9, 10], [7, 8, 9, 10, 11], [8, 9, 10, 11, 12], [9, 10, 11, 12, 13]]], + [[[5, 6, 7, 8, 9], [6, 7, 8, 9, 10], [7, 8, 9, 10, 11], [8, 9, 10, 11, 12]], + [[6, 7, 8, 9, 10], [7, 8, 9, 10, 11], [8, 9, 10, 11, 12], [9, 10, 11, 12, 13]], + [[7, 8, 9, 10, 11], [8, 9, 10, 11, 12], [9, 10, 11, 12, 13], [10, 11, 12, 13, 14]]]] + assert c.free_symbols == set() + assert c.variables == [i, j, k, l] + assert c.bound_symbols == [i, j, k, l] + assert d.doit().tolist() == [k, k, k, k, k] + assert len(e) == 5 + raises(TypeError, lambda: ArrayComprehension(i*j, (i, 1, 3), (j, 2, [1, 3, 2]))) + raises(ValueError, lambda: ArrayComprehension(i*j, (i, 1, 3), (j, 2, 1))) + raises(ValueError, lambda: ArrayComprehension(i*j, (i, 1, 3), (j, 2, j+1))) + raises(ValueError, lambda: len(ArrayComprehension(i*j, (i, 1, 3), (j, 2, j+4)))) + raises(TypeError, lambda: ArrayComprehension(i*j, (i, 0, i + 1.5), (j, 0, 2))) + raises(ValueError, lambda: b.tolist()) + raises(ValueError, lambda: b.tomatrix()) + raises(ValueError, lambda: c.tomatrix()) + +def test_arraycomprehensionmap(): + a = ArrayComprehensionMap(lambda i: i+1, (i, 1, 5)) + assert a.doit().tolist() == [2, 3, 4, 5, 6] + assert a.shape == (5,) + assert a.is_shape_numeric + assert a.tolist() == [2, 3, 4, 5, 6] + assert len(a) == 5 + assert isinstance(a.doit(), ImmutableDenseNDimArray) + expr = ArrayComprehensionMap(lambda i: i+1, (i, 1, k)) + assert expr.doit() == expr + assert expr.subs(k, 4) == ArrayComprehensionMap(lambda i: i+1, (i, 1, 4)) + assert expr.subs(k, 4).doit() == ImmutableDenseNDimArray([2, 3, 4, 5]) + b = ArrayComprehensionMap(lambda i: i+1, (i, 1, 2), (i, 1, 3), (i, 1, 4), (i, 1, 5)) + assert b.doit().tolist() == [[[[2, 3, 4, 5, 6], [3, 5, 7, 9, 11], [4, 7, 10, 13, 16], [5, 9, 13, 17, 21]], + [[3, 5, 7, 9, 11], [5, 9, 13, 17, 21], [7, 13, 19, 25, 31], [9, 17, 25, 33, 41]], + [[4, 7, 10, 13, 16], [7, 13, 19, 25, 31], [10, 19, 28, 37, 46], [13, 25, 37, 49, 61]]], + [[[3, 5, 7, 9, 11], [5, 9, 13, 17, 21], [7, 13, 19, 25, 31], [9, 17, 25, 33, 41]], + [[5, 9, 13, 17, 21], [9, 17, 25, 33, 41], [13, 25, 37, 49, 61], [17, 33, 49, 65, 81]], + [[7, 13, 19, 25, 31], [13, 25, 37, 49, 61], [19, 37, 55, 73, 91], [25, 49, 73, 97, 121]]]] + + # tests about lambda expression + assert ArrayComprehensionMap(lambda: 3, (i, 1, 5)).doit().tolist() == [3, 3, 3, 3, 3] + assert ArrayComprehensionMap(lambda i: i+1, (i, 1, 5)).doit().tolist() == [2, 3, 4, 5, 6] + raises(ValueError, lambda: ArrayComprehensionMap(i*j, (i, 1, 3), (j, 2, 4))) + a = ArrayComprehensionMap(lambda i, j: i+j, (i, 1, 5)) + raises(ValueError, lambda: a.doit()) diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/test_array_derivatives.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/test_array_derivatives.py new file mode 100644 index 0000000000000000000000000000000000000000..7f6c777c55a9170704f309bf74387d140bf2ec32 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/test_array_derivatives.py @@ -0,0 +1,52 @@ +from sympy.core.symbol import symbols +from sympy.matrices.dense import Matrix +from sympy.matrices.expressions.matexpr import MatrixSymbol +from sympy.tensor.array.ndim_array import NDimArray +from sympy.matrices.matrixbase import MatrixBase +from sympy.tensor.array.array_derivatives import ArrayDerivative + +x, y, z, t = symbols("x y z t") + +m = Matrix([[x, y], [z, t]]) + +M = MatrixSymbol("M", 3, 2) +N = MatrixSymbol("N", 4, 3) + + +def test_array_derivative_construction(): + + d = ArrayDerivative(x, m, evaluate=False) + assert d.shape == (2, 2) + expr = d.doit() + assert isinstance(expr, MatrixBase) + assert expr.shape == (2, 2) + + d = ArrayDerivative(m, m, evaluate=False) + assert d.shape == (2, 2, 2, 2) + expr = d.doit() + assert isinstance(expr, NDimArray) + assert expr.shape == (2, 2, 2, 2) + + d = ArrayDerivative(m, x, evaluate=False) + assert d.shape == (2, 2) + expr = d.doit() + assert isinstance(expr, MatrixBase) + assert expr.shape == (2, 2) + + d = ArrayDerivative(M, N, evaluate=False) + assert d.shape == (4, 3, 3, 2) + expr = d.doit() + assert isinstance(expr, ArrayDerivative) + assert expr.shape == (4, 3, 3, 2) + + d = ArrayDerivative(M, (N, 2), evaluate=False) + assert d.shape == (4, 3, 4, 3, 3, 2) + expr = d.doit() + assert isinstance(expr, ArrayDerivative) + assert expr.shape == (4, 3, 4, 3, 3, 2) + + d = ArrayDerivative(M.as_explicit(), (N.as_explicit(), 2), evaluate=False) + assert d.doit().shape == (4, 3, 4, 3, 3, 2) + expr = d.doit() + assert isinstance(expr, NDimArray) + assert expr.shape == (4, 3, 4, 3, 3, 2) diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/test_arrayop.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/test_arrayop.py new file mode 100644 index 0000000000000000000000000000000000000000..de56e81e0064f1e303a7a58e41932d15f2d0b41e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/test_arrayop.py @@ -0,0 +1,361 @@ +import itertools +import random + +from sympy.combinatorics import Permutation +from sympy.combinatorics.permutations import _af_invert +from sympy.testing.pytest import raises + +from sympy.core.function import diff +from sympy.core.symbol import symbols +from sympy.functions.elementary.complexes import (adjoint, conjugate, transpose) +from sympy.functions.elementary.exponential import (exp, log) +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.tensor.array import Array, ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableSparseNDimArray + +from sympy.tensor.array.arrayop import tensorproduct, tensorcontraction, derive_by_array, permutedims, Flatten, \ + tensordiagonal + + +def test_import_NDimArray(): + from sympy.tensor.array import NDimArray + del NDimArray + + +def test_tensorproduct(): + x,y,z,t = symbols('x y z t') + from sympy.abc import a,b,c,d + assert tensorproduct() == 1 + assert tensorproduct([x]) == Array([x]) + assert tensorproduct([x], [y]) == Array([[x*y]]) + assert tensorproduct([x], [y], [z]) == Array([[[x*y*z]]]) + assert tensorproduct([x], [y], [z], [t]) == Array([[[[x*y*z*t]]]]) + + assert tensorproduct(x) == x + assert tensorproduct(x, y) == x*y + assert tensorproduct(x, y, z) == x*y*z + assert tensorproduct(x, y, z, t) == x*y*z*t + + for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]: + A = ArrayType([x, y]) + B = ArrayType([1, 2, 3]) + C = ArrayType([a, b, c, d]) + + assert tensorproduct(A, B, C) == ArrayType([[[a*x, b*x, c*x, d*x], [2*a*x, 2*b*x, 2*c*x, 2*d*x], [3*a*x, 3*b*x, 3*c*x, 3*d*x]], + [[a*y, b*y, c*y, d*y], [2*a*y, 2*b*y, 2*c*y, 2*d*y], [3*a*y, 3*b*y, 3*c*y, 3*d*y]]]) + + assert tensorproduct([x, y], [1, 2, 3]) == tensorproduct(A, B) + + assert tensorproduct(A, 2) == ArrayType([2*x, 2*y]) + assert tensorproduct(A, [2]) == ArrayType([[2*x], [2*y]]) + assert tensorproduct([2], A) == ArrayType([[2*x, 2*y]]) + assert tensorproduct(a, A) == ArrayType([a*x, a*y]) + assert tensorproduct(a, A, B) == ArrayType([[a*x, 2*a*x, 3*a*x], [a*y, 2*a*y, 3*a*y]]) + assert tensorproduct(A, B, a) == ArrayType([[a*x, 2*a*x, 3*a*x], [a*y, 2*a*y, 3*a*y]]) + assert tensorproduct(B, a, A) == ArrayType([[a*x, a*y], [2*a*x, 2*a*y], [3*a*x, 3*a*y]]) + + # tests for large scale sparse array + for SparseArrayType in [ImmutableSparseNDimArray, MutableSparseNDimArray]: + a = SparseArrayType({1:2, 3:4},(1000, 2000)) + b = SparseArrayType({1:2, 3:4},(1000, 2000)) + assert tensorproduct(a, b) == ImmutableSparseNDimArray({2000001: 4, 2000003: 8, 6000001: 8, 6000003: 16}, (1000, 2000, 1000, 2000)) + + +def test_tensorcontraction(): + from sympy.abc import a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x + B = Array(range(18), (2, 3, 3)) + assert tensorcontraction(B, (1, 2)) == Array([12, 39]) + C1 = Array([a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x], (2, 3, 2, 2)) + + assert tensorcontraction(C1, (0, 2)) == Array([[a + o, b + p], [e + s, f + t], [i + w, j + x]]) + assert tensorcontraction(C1, (0, 2, 3)) == Array([a + p, e + t, i + x]) + assert tensorcontraction(C1, (2, 3)) == Array([[a + d, e + h, i + l], [m + p, q + t, u + x]]) + + +def test_derivative_by_array(): + from sympy.abc import i, j, t, x, y, z + + bexpr = x*y**2*exp(z)*log(t) + sexpr = sin(bexpr) + cexpr = cos(bexpr) + + a = Array([sexpr]) + + assert derive_by_array(sexpr, t) == x*y**2*exp(z)*cos(x*y**2*exp(z)*log(t))/t + assert derive_by_array(sexpr, [x, y, z]) == Array([bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr, bexpr*cexpr]) + assert derive_by_array(a, [x, y, z]) == Array([[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr], [bexpr*cexpr]]) + + assert derive_by_array(sexpr, [[x, y], [z, t]]) == Array([[bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr], [bexpr*cexpr, bexpr/log(t)/t*cexpr]]) + assert derive_by_array(a, [[x, y], [z, t]]) == Array([[[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr]], [[bexpr*cexpr], [bexpr/log(t)/t*cexpr]]]) + assert derive_by_array([[x, y], [z, t]], [x, y]) == Array([[[1, 0], [0, 0]], [[0, 1], [0, 0]]]) + assert derive_by_array([[x, y], [z, t]], [[x, y], [z, t]]) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], + [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]]) + + assert diff(sexpr, t) == x*y**2*exp(z)*cos(x*y**2*exp(z)*log(t))/t + assert diff(sexpr, Array([x, y, z])) == Array([bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr, bexpr*cexpr]) + assert diff(a, Array([x, y, z])) == Array([[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr], [bexpr*cexpr]]) + + assert diff(sexpr, Array([[x, y], [z, t]])) == Array([[bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr], [bexpr*cexpr, bexpr/log(t)/t*cexpr]]) + assert diff(a, Array([[x, y], [z, t]])) == Array([[[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr]], [[bexpr*cexpr], [bexpr/log(t)/t*cexpr]]]) + assert diff(Array([[x, y], [z, t]]), Array([x, y])) == Array([[[1, 0], [0, 0]], [[0, 1], [0, 0]]]) + assert diff(Array([[x, y], [z, t]]), Array([[x, y], [z, t]])) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], + [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]]) + + # test for large scale sparse array + for SparseArrayType in [ImmutableSparseNDimArray, MutableSparseNDimArray]: + b = MutableSparseNDimArray({0:i, 1:j}, (10000, 20000)) + assert derive_by_array(b, i) == ImmutableSparseNDimArray({0: 1}, (10000, 20000)) + assert derive_by_array(b, (i, j)) == ImmutableSparseNDimArray({0: 1, 200000001: 1}, (2, 10000, 20000)) + + #https://github.com/sympy/sympy/issues/20655 + U = Array([x, y, z]) + E = 2 + assert derive_by_array(E, U) == ImmutableDenseNDimArray([0, 0, 0]) + + +def test_issue_emerged_while_discussing_10972(): + ua = Array([-1,0]) + Fa = Array([[0, 1], [-1, 0]]) + po = tensorproduct(Fa, ua, Fa, ua) + assert tensorcontraction(po, (1, 2), (4, 5)) == Array([[0, 0], [0, 1]]) + + sa = symbols('a0:144') + po = Array(sa, [2, 2, 3, 3, 2, 2]) + assert tensorcontraction(po, (0, 1), (2, 3), (4, 5)) == sa[0] + sa[108] + sa[111] + sa[124] + sa[127] + sa[140] + sa[143] + sa[16] + sa[19] + sa[3] + sa[32] + sa[35] + assert tensorcontraction(po, (0, 1, 4, 5), (2, 3)) == sa[0] + sa[111] + sa[127] + sa[143] + sa[16] + sa[32] + assert tensorcontraction(po, (0, 1), (4, 5)) == Array([[sa[0] + sa[108] + sa[111] + sa[3], sa[112] + sa[115] + sa[4] + sa[7], + sa[11] + sa[116] + sa[119] + sa[8]], [sa[12] + sa[120] + sa[123] + sa[15], + sa[124] + sa[127] + sa[16] + sa[19], sa[128] + sa[131] + sa[20] + sa[23]], + [sa[132] + sa[135] + sa[24] + sa[27], sa[136] + sa[139] + sa[28] + sa[31], + sa[140] + sa[143] + sa[32] + sa[35]]]) + assert tensorcontraction(po, (0, 1), (2, 3)) == Array([[sa[0] + sa[108] + sa[124] + sa[140] + sa[16] + sa[32], sa[1] + sa[109] + sa[125] + sa[141] + sa[17] + sa[33]], + [sa[110] + sa[126] + sa[142] + sa[18] + sa[2] + sa[34], sa[111] + sa[127] + sa[143] + sa[19] + sa[3] + sa[35]]]) + + +def test_array_permutedims(): + sa = symbols('a0:144') + + for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]: + m1 = ArrayType(sa[:6], (2, 3)) + assert permutedims(m1, (1, 0)) == transpose(m1) + assert m1.tomatrix().T == permutedims(m1, (1, 0)).tomatrix() + + assert m1.tomatrix().T == transpose(m1).tomatrix() + assert m1.tomatrix().C == conjugate(m1).tomatrix() + assert m1.tomatrix().H == adjoint(m1).tomatrix() + + assert m1.tomatrix().T == m1.transpose().tomatrix() + assert m1.tomatrix().C == m1.conjugate().tomatrix() + assert m1.tomatrix().H == m1.adjoint().tomatrix() + + raises(ValueError, lambda: permutedims(m1, (0,))) + raises(ValueError, lambda: permutedims(m1, (0, 0))) + raises(ValueError, lambda: permutedims(m1, (1, 2, 0))) + + # Some tests with random arrays: + dims = 6 + shape = [random.randint(1,5) for i in range(dims)] + elems = [random.random() for i in range(tensorproduct(*shape))] + ra = ArrayType(elems, shape) + perm = list(range(dims)) + # Randomize the permutation: + random.shuffle(perm) + # Test inverse permutation: + assert permutedims(permutedims(ra, perm), _af_invert(perm)) == ra + # Test that permuted shape corresponds to action by `Permutation`: + assert permutedims(ra, perm).shape == tuple(Permutation(perm)(shape)) + + z = ArrayType.zeros(4,5,6,7) + + assert permutedims(z, (2, 3, 1, 0)).shape == (6, 7, 5, 4) + assert permutedims(z, [2, 3, 1, 0]).shape == (6, 7, 5, 4) + assert permutedims(z, Permutation([2, 3, 1, 0])).shape == (6, 7, 5, 4) + + po = ArrayType(sa, [2, 2, 3, 3, 2, 2]) + + raises(ValueError, lambda: permutedims(po, (1, 1))) + raises(ValueError, lambda: po.transpose()) + raises(ValueError, lambda: po.adjoint()) + + assert permutedims(po, reversed(range(po.rank()))) == ArrayType( + [[[[[[sa[0], sa[72]], [sa[36], sa[108]]], [[sa[12], sa[84]], [sa[48], sa[120]]], [[sa[24], + sa[96]], [sa[60], sa[132]]]], + [[[sa[4], sa[76]], [sa[40], sa[112]]], [[sa[16], + sa[88]], [sa[52], sa[124]]], + [[sa[28], sa[100]], [sa[64], sa[136]]]], + [[[sa[8], + sa[80]], [sa[44], sa[116]]], [[sa[20], sa[92]], [sa[56], sa[128]]], [[sa[32], + sa[104]], [sa[68], sa[140]]]]], + [[[[sa[2], sa[74]], [sa[38], sa[110]]], [[sa[14], + sa[86]], [sa[50], sa[122]]], [[sa[26], sa[98]], [sa[62], sa[134]]]], + [[[sa[6], + sa[78]], [sa[42], sa[114]]], [[sa[18], sa[90]], [sa[54], sa[126]]], [[sa[30], + sa[102]], [sa[66], sa[138]]]], + [[[sa[10], sa[82]], [sa[46], sa[118]]], [[sa[22], + sa[94]], [sa[58], sa[130]]], + [[sa[34], sa[106]], [sa[70], sa[142]]]]]], + [[[[[sa[1], + sa[73]], [sa[37], sa[109]]], [[sa[13], sa[85]], [sa[49], sa[121]]], [[sa[25], + sa[97]], [sa[61], sa[133]]]], + [[[sa[5], sa[77]], [sa[41], sa[113]]], [[sa[17], + sa[89]], [sa[53], sa[125]]], + [[sa[29], sa[101]], [sa[65], sa[137]]]], + [[[sa[9], + sa[81]], [sa[45], sa[117]]], [[sa[21], sa[93]], [sa[57], sa[129]]], [[sa[33], + sa[105]], [sa[69], sa[141]]]]], + [[[[sa[3], sa[75]], [sa[39], sa[111]]], [[sa[15], + sa[87]], [sa[51], sa[123]]], [[sa[27], sa[99]], [sa[63], sa[135]]]], + [[[sa[7], + sa[79]], [sa[43], sa[115]]], [[sa[19], sa[91]], [sa[55], sa[127]]], [[sa[31], + sa[103]], [sa[67], sa[139]]]], + [[[sa[11], sa[83]], [sa[47], sa[119]]], [[sa[23], + sa[95]], [sa[59], sa[131]]], + [[sa[35], sa[107]], [sa[71], sa[143]]]]]]]) + + assert permutedims(po, (1, 0, 2, 3, 4, 5)) == ArrayType( + [[[[[[sa[0], sa[1]], [sa[2], sa[3]]], [[sa[4], sa[5]], [sa[6], sa[7]]], [[sa[8], sa[9]], [sa[10], + sa[11]]]], + [[[sa[12], sa[13]], [sa[14], sa[15]]], [[sa[16], sa[17]], [sa[18], + sa[19]]], [[sa[20], sa[21]], [sa[22], sa[23]]]], + [[[sa[24], sa[25]], [sa[26], + sa[27]]], [[sa[28], sa[29]], [sa[30], sa[31]]], [[sa[32], sa[33]], [sa[34], + sa[35]]]]], + [[[[sa[72], sa[73]], [sa[74], sa[75]]], [[sa[76], sa[77]], [sa[78], + sa[79]]], [[sa[80], sa[81]], [sa[82], sa[83]]]], + [[[sa[84], sa[85]], [sa[86], + sa[87]]], [[sa[88], sa[89]], [sa[90], sa[91]]], [[sa[92], sa[93]], [sa[94], + sa[95]]]], + [[[sa[96], sa[97]], [sa[98], sa[99]]], [[sa[100], sa[101]], [sa[102], + sa[103]]], + [[sa[104], sa[105]], [sa[106], sa[107]]]]]], [[[[[sa[36], sa[37]], [sa[38], + sa[39]]], + [[sa[40], sa[41]], [sa[42], sa[43]]], + [[sa[44], sa[45]], [sa[46], + sa[47]]]], + [[[sa[48], sa[49]], [sa[50], sa[51]]], + [[sa[52], sa[53]], [sa[54], + sa[55]]], + [[sa[56], sa[57]], [sa[58], sa[59]]]], + [[[sa[60], sa[61]], [sa[62], + sa[63]]], + [[sa[64], sa[65]], [sa[66], sa[67]]], + [[sa[68], sa[69]], [sa[70], + sa[71]]]]], [ + [[[sa[108], sa[109]], [sa[110], sa[111]]], + [[sa[112], sa[113]], [sa[114], + sa[115]]], + [[sa[116], sa[117]], [sa[118], sa[119]]]], + [[[sa[120], sa[121]], [sa[122], + sa[123]]], + [[sa[124], sa[125]], [sa[126], sa[127]]], + [[sa[128], sa[129]], [sa[130], + sa[131]]]], + [[[sa[132], sa[133]], [sa[134], sa[135]]], + [[sa[136], sa[137]], [sa[138], + sa[139]]], + [[sa[140], sa[141]], [sa[142], sa[143]]]]]]]) + + assert permutedims(po, (0, 2, 1, 4, 3, 5)) == ArrayType( + [[[[[[sa[0], sa[1]], [sa[4], sa[5]], [sa[8], sa[9]]], [[sa[2], sa[3]], [sa[6], sa[7]], [sa[10], + sa[11]]]], + [[[sa[36], sa[37]], [sa[40], sa[41]], [sa[44], sa[45]]], [[sa[38], + sa[39]], [sa[42], sa[43]], [sa[46], sa[47]]]]], + [[[[sa[12], sa[13]], [sa[16], + sa[17]], [sa[20], sa[21]]], [[sa[14], sa[15]], [sa[18], sa[19]], [sa[22], + sa[23]]]], + [[[sa[48], sa[49]], [sa[52], sa[53]], [sa[56], sa[57]]], [[sa[50], + sa[51]], [sa[54], sa[55]], [sa[58], sa[59]]]]], + [[[[sa[24], sa[25]], [sa[28], + sa[29]], [sa[32], sa[33]]], [[sa[26], sa[27]], [sa[30], sa[31]], [sa[34], + sa[35]]]], + [[[sa[60], sa[61]], [sa[64], sa[65]], [sa[68], sa[69]]], [[sa[62], + sa[63]], [sa[66], sa[67]], [sa[70], sa[71]]]]]], + [[[[[sa[72], sa[73]], [sa[76], + sa[77]], [sa[80], sa[81]]], [[sa[74], sa[75]], [sa[78], sa[79]], [sa[82], + sa[83]]]], + [[[sa[108], sa[109]], [sa[112], sa[113]], [sa[116], sa[117]]], [[sa[110], + sa[111]], [sa[114], sa[115]], + [sa[118], sa[119]]]]], + [[[[sa[84], sa[85]], [sa[88], + sa[89]], [sa[92], sa[93]]], [[sa[86], sa[87]], [sa[90], sa[91]], [sa[94], + sa[95]]]], + [[[sa[120], sa[121]], [sa[124], sa[125]], [sa[128], sa[129]]], [[sa[122], + sa[123]], [sa[126], sa[127]], + [sa[130], sa[131]]]]], + [[[[sa[96], sa[97]], [sa[100], + sa[101]], [sa[104], sa[105]]], [[sa[98], sa[99]], [sa[102], sa[103]], [sa[106], + sa[107]]]], + [[[sa[132], sa[133]], [sa[136], sa[137]], [sa[140], sa[141]]], [[sa[134], + sa[135]], [sa[138], sa[139]], + [sa[142], sa[143]]]]]]]) + + po2 = po.reshape(4, 9, 2, 2) + assert po2 == ArrayType([[[[sa[0], sa[1]], [sa[2], sa[3]]], [[sa[4], sa[5]], [sa[6], sa[7]]], [[sa[8], sa[9]], [sa[10], sa[11]]], [[sa[12], sa[13]], [sa[14], sa[15]]], [[sa[16], sa[17]], [sa[18], sa[19]]], [[sa[20], sa[21]], [sa[22], sa[23]]], [[sa[24], sa[25]], [sa[26], sa[27]]], [[sa[28], sa[29]], [sa[30], sa[31]]], [[sa[32], sa[33]], [sa[34], sa[35]]]], [[[sa[36], sa[37]], [sa[38], sa[39]]], [[sa[40], sa[41]], [sa[42], sa[43]]], [[sa[44], sa[45]], [sa[46], sa[47]]], [[sa[48], sa[49]], [sa[50], sa[51]]], [[sa[52], sa[53]], [sa[54], sa[55]]], [[sa[56], sa[57]], [sa[58], sa[59]]], [[sa[60], sa[61]], [sa[62], sa[63]]], [[sa[64], sa[65]], [sa[66], sa[67]]], [[sa[68], sa[69]], [sa[70], sa[71]]]], [[[sa[72], sa[73]], [sa[74], sa[75]]], [[sa[76], sa[77]], [sa[78], sa[79]]], [[sa[80], sa[81]], [sa[82], sa[83]]], [[sa[84], sa[85]], [sa[86], sa[87]]], [[sa[88], sa[89]], [sa[90], sa[91]]], [[sa[92], sa[93]], [sa[94], sa[95]]], [[sa[96], sa[97]], [sa[98], sa[99]]], [[sa[100], sa[101]], [sa[102], sa[103]]], [[sa[104], sa[105]], [sa[106], sa[107]]]], [[[sa[108], sa[109]], [sa[110], sa[111]]], [[sa[112], sa[113]], [sa[114], sa[115]]], [[sa[116], sa[117]], [sa[118], sa[119]]], [[sa[120], sa[121]], [sa[122], sa[123]]], [[sa[124], sa[125]], [sa[126], sa[127]]], [[sa[128], sa[129]], [sa[130], sa[131]]], [[sa[132], sa[133]], [sa[134], sa[135]]], [[sa[136], sa[137]], [sa[138], sa[139]]], [[sa[140], sa[141]], [sa[142], sa[143]]]]]) + + assert permutedims(po2, (3, 2, 0, 1)) == ArrayType([[[[sa[0], sa[4], sa[8], sa[12], sa[16], sa[20], sa[24], sa[28], sa[32]], [sa[36], sa[40], sa[44], sa[48], sa[52], sa[56], sa[60], sa[64], sa[68]], [sa[72], sa[76], sa[80], sa[84], sa[88], sa[92], sa[96], sa[100], sa[104]], [sa[108], sa[112], sa[116], sa[120], sa[124], sa[128], sa[132], sa[136], sa[140]]], [[sa[2], sa[6], sa[10], sa[14], sa[18], sa[22], sa[26], sa[30], sa[34]], [sa[38], sa[42], sa[46], sa[50], sa[54], sa[58], sa[62], sa[66], sa[70]], [sa[74], sa[78], sa[82], sa[86], sa[90], sa[94], sa[98], sa[102], sa[106]], [sa[110], sa[114], sa[118], sa[122], sa[126], sa[130], sa[134], sa[138], sa[142]]]], [[[sa[1], sa[5], sa[9], sa[13], sa[17], sa[21], sa[25], sa[29], sa[33]], [sa[37], sa[41], sa[45], sa[49], sa[53], sa[57], sa[61], sa[65], sa[69]], [sa[73], sa[77], sa[81], sa[85], sa[89], sa[93], sa[97], sa[101], sa[105]], [sa[109], sa[113], sa[117], sa[121], sa[125], sa[129], sa[133], sa[137], sa[141]]], [[sa[3], sa[7], sa[11], sa[15], sa[19], sa[23], sa[27], sa[31], sa[35]], [sa[39], sa[43], sa[47], sa[51], sa[55], sa[59], sa[63], sa[67], sa[71]], [sa[75], sa[79], sa[83], sa[87], sa[91], sa[95], sa[99], sa[103], sa[107]], [sa[111], sa[115], sa[119], sa[123], sa[127], sa[131], sa[135], sa[139], sa[143]]]]]) + + # test for large scale sparse array + for SparseArrayType in [ImmutableSparseNDimArray, MutableSparseNDimArray]: + A = SparseArrayType({1:1, 10000:2}, (10000, 20000, 10000)) + assert permutedims(A, (0, 1, 2)) == A + assert permutedims(A, (1, 0, 2)) == SparseArrayType({1: 1, 100000000: 2}, (20000, 10000, 10000)) + B = SparseArrayType({1:1, 20000:2}, (10000, 20000)) + assert B.transpose() == SparseArrayType({10000: 1, 1: 2}, (20000, 10000)) + + +def test_permutedims_with_indices(): + A = Array(range(32)).reshape(2, 2, 2, 2, 2) + indices_new = list("abcde") + indices_old = list("ebdac") + new_A = permutedims(A, index_order_new=indices_new, index_order_old=indices_old) + for a, b, c, d, e in itertools.product(range(2), range(2), range(2), range(2), range(2)): + assert new_A[a, b, c, d, e] == A[e, b, d, a, c] + indices_old = list("cabed") + new_A = permutedims(A, index_order_new=indices_new, index_order_old=indices_old) + for a, b, c, d, e in itertools.product(range(2), range(2), range(2), range(2), range(2)): + assert new_A[a, b, c, d, e] == A[c, a, b, e, d] + raises(ValueError, lambda: permutedims(A, index_order_old=list("aacde"), index_order_new=list("abcde"))) + raises(ValueError, lambda: permutedims(A, index_order_old=list("abcde"), index_order_new=list("abcce"))) + raises(ValueError, lambda: permutedims(A, index_order_old=list("abcde"), index_order_new=list("abce"))) + raises(ValueError, lambda: permutedims(A, index_order_old=list("abce"), index_order_new=list("abce"))) + raises(ValueError, lambda: permutedims(A, [2, 1, 0, 3, 4], index_order_old=list("abcde"))) + raises(ValueError, lambda: permutedims(A, [2, 1, 0, 3, 4], index_order_new=list("abcde"))) + + +def test_flatten(): + from sympy.matrices.dense import Matrix + for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray, Matrix]: + A = ArrayType(range(24)).reshape(4, 6) + assert list(Flatten(A)) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23] + + for i, v in enumerate(Flatten(A)): + assert i == v + + +def test_tensordiagonal(): + from sympy.matrices.dense import eye + expr = Array(range(9)).reshape(3, 3) + raises(ValueError, lambda: tensordiagonal(expr, [0], [1])) + raises(ValueError, lambda: tensordiagonal(expr, [0, 0])) + assert tensordiagonal(eye(3), [0, 1]) == Array([1, 1, 1]) + assert tensordiagonal(expr, [0, 1]) == Array([0, 4, 8]) + x, y, z = symbols("x y z") + expr2 = tensorproduct([x, y, z], expr) + assert tensordiagonal(expr2, [1, 2]) == Array([[0, 4*x, 8*x], [0, 4*y, 8*y], [0, 4*z, 8*z]]) + assert tensordiagonal(expr2, [0, 1]) == Array([[0, 3*y, 6*z], [x, 4*y, 7*z], [2*x, 5*y, 8*z]]) + assert tensordiagonal(expr2, [0, 1, 2]) == Array([0, 4*y, 8*z]) + # assert tensordiagonal(expr2, [0]) == permutedims(expr2, [1, 2, 0]) + # assert tensordiagonal(expr2, [1]) == permutedims(expr2, [0, 2, 1]) + # assert tensordiagonal(expr2, [2]) == expr2 + # assert tensordiagonal(expr2, [1], [2]) == expr2 + # assert tensordiagonal(expr2, [0], [1]) == permutedims(expr2, [2, 0, 1]) + + a, b, c, X, Y, Z = symbols("a b c X Y Z") + expr3 = tensorproduct([x, y, z], [1, 2, 3], [a, b, c], [X, Y, Z]) + assert tensordiagonal(expr3, [0, 1, 2, 3]) == Array([x*a*X, 2*y*b*Y, 3*z*c*Z]) + assert tensordiagonal(expr3, [0, 1], [2, 3]) == tensorproduct([x, 2*y, 3*z], [a*X, b*Y, c*Z]) + + # assert tensordiagonal(expr3, [0], [1, 2], [3]) == tensorproduct([x, y, z], [a, 2*b, 3*c], [X, Y, Z]) + assert tensordiagonal(tensordiagonal(expr3, [2, 3]), [0, 1]) == tensorproduct([a*X, b*Y, c*Z], [x, 2*y, 3*z]) + + raises(ValueError, lambda: tensordiagonal([[1, 2, 3], [4, 5, 6]], [0, 1])) + raises(ValueError, lambda: tensordiagonal(expr3.reshape(3, 3, 9), [1, 2])) diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/test_immutable_ndim_array.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/test_immutable_ndim_array.py new file mode 100644 index 0000000000000000000000000000000000000000..c6bed4b605c424284b4752592b03b13a9178aac8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/test_immutable_ndim_array.py @@ -0,0 +1,452 @@ +from copy import copy + +from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray +from sympy.core.containers import Dict +from sympy.core.function import diff +from sympy.core.numbers import Rational +from sympy.core.singleton import S +from sympy.core.symbol import (Symbol, symbols) +from sympy.matrices import SparseMatrix +from sympy.tensor.indexed import (Indexed, IndexedBase) +from sympy.matrices import Matrix +from sympy.tensor.array.sparse_ndim_array import ImmutableSparseNDimArray +from sympy.testing.pytest import raises + + +def test_ndim_array_initiation(): + arr_with_no_elements = ImmutableDenseNDimArray([], shape=(0,)) + assert len(arr_with_no_elements) == 0 + assert arr_with_no_elements.rank() == 1 + + raises(ValueError, lambda: ImmutableDenseNDimArray([0], shape=(0,))) + raises(ValueError, lambda: ImmutableDenseNDimArray([1, 2, 3], shape=(0,))) + raises(ValueError, lambda: ImmutableDenseNDimArray([], shape=())) + + raises(ValueError, lambda: ImmutableSparseNDimArray([0], shape=(0,))) + raises(ValueError, lambda: ImmutableSparseNDimArray([1, 2, 3], shape=(0,))) + raises(ValueError, lambda: ImmutableSparseNDimArray([], shape=())) + + arr_with_one_element = ImmutableDenseNDimArray([23]) + assert len(arr_with_one_element) == 1 + assert arr_with_one_element[0] == 23 + assert arr_with_one_element[:] == ImmutableDenseNDimArray([23]) + assert arr_with_one_element.rank() == 1 + + arr_with_symbol_element = ImmutableDenseNDimArray([Symbol('x')]) + assert len(arr_with_symbol_element) == 1 + assert arr_with_symbol_element[0] == Symbol('x') + assert arr_with_symbol_element[:] == ImmutableDenseNDimArray([Symbol('x')]) + assert arr_with_symbol_element.rank() == 1 + + number5 = 5 + vector = ImmutableDenseNDimArray.zeros(number5) + assert len(vector) == number5 + assert vector.shape == (number5,) + assert vector.rank() == 1 + + vector = ImmutableSparseNDimArray.zeros(number5) + assert len(vector) == number5 + assert vector.shape == (number5,) + assert vector._sparse_array == Dict() + assert vector.rank() == 1 + + n_dim_array = ImmutableDenseNDimArray(range(3**4), (3, 3, 3, 3,)) + assert len(n_dim_array) == 3 * 3 * 3 * 3 + assert n_dim_array.shape == (3, 3, 3, 3) + assert n_dim_array.rank() == 4 + + array_shape = (3, 3, 3, 3) + sparse_array = ImmutableSparseNDimArray.zeros(*array_shape) + assert len(sparse_array._sparse_array) == 0 + assert len(sparse_array) == 3 * 3 * 3 * 3 + assert n_dim_array.shape == array_shape + assert n_dim_array.rank() == 4 + + one_dim_array = ImmutableDenseNDimArray([2, 3, 1]) + assert len(one_dim_array) == 3 + assert one_dim_array.shape == (3,) + assert one_dim_array.rank() == 1 + assert one_dim_array.tolist() == [2, 3, 1] + + shape = (3, 3) + array_with_many_args = ImmutableSparseNDimArray.zeros(*shape) + assert len(array_with_many_args) == 3 * 3 + assert array_with_many_args.shape == shape + assert array_with_many_args[0, 0] == 0 + assert array_with_many_args.rank() == 2 + + shape = (int(3), int(3)) + array_with_long_shape = ImmutableSparseNDimArray.zeros(*shape) + assert len(array_with_long_shape) == 3 * 3 + assert array_with_long_shape.shape == shape + assert array_with_long_shape[int(0), int(0)] == 0 + assert array_with_long_shape.rank() == 2 + + vector_with_long_shape = ImmutableDenseNDimArray(range(5), int(5)) + assert len(vector_with_long_shape) == 5 + assert vector_with_long_shape.shape == (int(5),) + assert vector_with_long_shape.rank() == 1 + raises(ValueError, lambda: vector_with_long_shape[int(5)]) + + from sympy.abc import x + for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]: + rank_zero_array = ArrayType(x) + assert len(rank_zero_array) == 1 + assert rank_zero_array.shape == () + assert rank_zero_array.rank() == 0 + assert rank_zero_array[()] == x + raises(ValueError, lambda: rank_zero_array[0]) + + +def test_reshape(): + array = ImmutableDenseNDimArray(range(50), 50) + assert array.shape == (50,) + assert array.rank() == 1 + + array = array.reshape(5, 5, 2) + assert array.shape == (5, 5, 2) + assert array.rank() == 3 + assert len(array) == 50 + + +def test_getitem(): + for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]: + array = ArrayType(range(24)).reshape(2, 3, 4) + assert array.tolist() == [[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]] + assert array[0] == ArrayType([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]) + assert array[0, 0] == ArrayType([0, 1, 2, 3]) + value = 0 + for i in range(2): + for j in range(3): + for k in range(4): + assert array[i, j, k] == value + value += 1 + + raises(ValueError, lambda: array[3, 4, 5]) + raises(ValueError, lambda: array[3, 4, 5, 6]) + raises(ValueError, lambda: array[3, 4, 5, 3:4]) + + +def test_iterator(): + array = ImmutableDenseNDimArray(range(4), (2, 2)) + assert array[0] == ImmutableDenseNDimArray([0, 1]) + assert array[1] == ImmutableDenseNDimArray([2, 3]) + + array = array.reshape(4) + j = 0 + for i in array: + assert i == j + j += 1 + + +def test_sparse(): + sparse_array = ImmutableSparseNDimArray([0, 0, 0, 1], (2, 2)) + assert len(sparse_array) == 2 * 2 + # dictionary where all data is, only non-zero entries are actually stored: + assert len(sparse_array._sparse_array) == 1 + + assert sparse_array.tolist() == [[0, 0], [0, 1]] + + for i, j in zip(sparse_array, [[0, 0], [0, 1]]): + assert i == ImmutableSparseNDimArray(j) + + def sparse_assignment(): + sparse_array[0, 0] = 123 + + assert len(sparse_array._sparse_array) == 1 + raises(TypeError, sparse_assignment) + assert len(sparse_array._sparse_array) == 1 + assert sparse_array[0, 0] == 0 + assert sparse_array/0 == ImmutableSparseNDimArray([[S.NaN, S.NaN], [S.NaN, S.ComplexInfinity]], (2, 2)) + + # test for large scale sparse array + # equality test + assert ImmutableSparseNDimArray.zeros(100000, 200000) == ImmutableSparseNDimArray.zeros(100000, 200000) + + # __mul__ and __rmul__ + a = ImmutableSparseNDimArray({200001: 1}, (100000, 200000)) + assert a * 3 == ImmutableSparseNDimArray({200001: 3}, (100000, 200000)) + assert 3 * a == ImmutableSparseNDimArray({200001: 3}, (100000, 200000)) + assert a * 0 == ImmutableSparseNDimArray({}, (100000, 200000)) + assert 0 * a == ImmutableSparseNDimArray({}, (100000, 200000)) + + # __truediv__ + assert a/3 == ImmutableSparseNDimArray({200001: Rational(1, 3)}, (100000, 200000)) + + # __neg__ + assert -a == ImmutableSparseNDimArray({200001: -1}, (100000, 200000)) + + +def test_calculation(): + + a = ImmutableDenseNDimArray([1]*9, (3, 3)) + b = ImmutableDenseNDimArray([9]*9, (3, 3)) + + c = a + b + for i in c: + assert i == ImmutableDenseNDimArray([10, 10, 10]) + + assert c == ImmutableDenseNDimArray([10]*9, (3, 3)) + assert c == ImmutableSparseNDimArray([10]*9, (3, 3)) + + c = b - a + for i in c: + assert i == ImmutableDenseNDimArray([8, 8, 8]) + + assert c == ImmutableDenseNDimArray([8]*9, (3, 3)) + assert c == ImmutableSparseNDimArray([8]*9, (3, 3)) + + +def test_ndim_array_converting(): + dense_array = ImmutableDenseNDimArray([1, 2, 3, 4], (2, 2)) + alist = dense_array.tolist() + + assert alist == [[1, 2], [3, 4]] + + matrix = dense_array.tomatrix() + assert (isinstance(matrix, Matrix)) + + for i in range(len(dense_array)): + assert dense_array[dense_array._get_tuple_index(i)] == matrix[i] + assert matrix.shape == dense_array.shape + + assert ImmutableDenseNDimArray(matrix) == dense_array + assert ImmutableDenseNDimArray(matrix.as_immutable()) == dense_array + assert ImmutableDenseNDimArray(matrix.as_mutable()) == dense_array + + sparse_array = ImmutableSparseNDimArray([1, 2, 3, 4], (2, 2)) + alist = sparse_array.tolist() + + assert alist == [[1, 2], [3, 4]] + + matrix = sparse_array.tomatrix() + assert(isinstance(matrix, SparseMatrix)) + + for i in range(len(sparse_array)): + assert sparse_array[sparse_array._get_tuple_index(i)] == matrix[i] + assert matrix.shape == sparse_array.shape + + assert ImmutableSparseNDimArray(matrix) == sparse_array + assert ImmutableSparseNDimArray(matrix.as_immutable()) == sparse_array + assert ImmutableSparseNDimArray(matrix.as_mutable()) == sparse_array + + +def test_converting_functions(): + arr_list = [1, 2, 3, 4] + arr_matrix = Matrix(((1, 2), (3, 4))) + + # list + arr_ndim_array = ImmutableDenseNDimArray(arr_list, (2, 2)) + assert (isinstance(arr_ndim_array, ImmutableDenseNDimArray)) + assert arr_matrix.tolist() == arr_ndim_array.tolist() + + # Matrix + arr_ndim_array = ImmutableDenseNDimArray(arr_matrix) + assert (isinstance(arr_ndim_array, ImmutableDenseNDimArray)) + assert arr_matrix.tolist() == arr_ndim_array.tolist() + assert arr_matrix.shape == arr_ndim_array.shape + + +def test_equality(): + first_list = [1, 2, 3, 4] + second_list = [1, 2, 3, 4] + third_list = [4, 3, 2, 1] + assert first_list == second_list + assert first_list != third_list + + first_ndim_array = ImmutableDenseNDimArray(first_list, (2, 2)) + second_ndim_array = ImmutableDenseNDimArray(second_list, (2, 2)) + fourth_ndim_array = ImmutableDenseNDimArray(first_list, (2, 2)) + + assert first_ndim_array == second_ndim_array + + def assignment_attempt(a): + a[0, 0] = 0 + + raises(TypeError, lambda: assignment_attempt(second_ndim_array)) + assert first_ndim_array == second_ndim_array + assert first_ndim_array == fourth_ndim_array + + +def test_arithmetic(): + a = ImmutableDenseNDimArray([3 for i in range(9)], (3, 3)) + b = ImmutableDenseNDimArray([7 for i in range(9)], (3, 3)) + + c1 = a + b + c2 = b + a + assert c1 == c2 + + d1 = a - b + d2 = b - a + assert d1 == d2 * (-1) + + e1 = a * 5 + e2 = 5 * a + e3 = copy(a) + e3 *= 5 + assert e1 == e2 == e3 + + f1 = a / 5 + f2 = copy(a) + f2 /= 5 + assert f1 == f2 + assert f1[0, 0] == f1[0, 1] == f1[0, 2] == f1[1, 0] == f1[1, 1] == \ + f1[1, 2] == f1[2, 0] == f1[2, 1] == f1[2, 2] == Rational(3, 5) + + assert type(a) == type(b) == type(c1) == type(c2) == type(d1) == type(d2) \ + == type(e1) == type(e2) == type(e3) == type(f1) + + z0 = -a + assert z0 == ImmutableDenseNDimArray([-3 for i in range(9)], (3, 3)) + + +def test_higher_dimenions(): + m3 = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4)) + + assert m3.tolist() == [[[10, 11, 12, 13], + [14, 15, 16, 17], + [18, 19, 20, 21]], + + [[22, 23, 24, 25], + [26, 27, 28, 29], + [30, 31, 32, 33]]] + + assert m3._get_tuple_index(0) == (0, 0, 0) + assert m3._get_tuple_index(1) == (0, 0, 1) + assert m3._get_tuple_index(4) == (0, 1, 0) + assert m3._get_tuple_index(12) == (1, 0, 0) + + assert str(m3) == '[[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]]' + + m3_rebuilt = ImmutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]]) + assert m3 == m3_rebuilt + + m3_other = ImmutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]], (2, 3, 4)) + + assert m3 == m3_other + + +def test_rebuild_immutable_arrays(): + sparr = ImmutableSparseNDimArray(range(10, 34), (2, 3, 4)) + densarr = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4)) + + assert sparr == sparr.func(*sparr.args) + assert densarr == densarr.func(*densarr.args) + + +def test_slices(): + md = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4)) + + assert md[:] == ImmutableDenseNDimArray(range(10, 34), (2, 3, 4)) + assert md[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]]) + assert md[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]]) + assert md[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]]) + assert md[:, :, :] == md + + sd = ImmutableSparseNDimArray(range(10, 34), (2, 3, 4)) + assert sd == ImmutableSparseNDimArray(md) + + assert sd[:] == ImmutableSparseNDimArray(range(10, 34), (2, 3, 4)) + assert sd[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]]) + assert sd[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]]) + assert sd[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]]) + assert sd[:, :, :] == sd + + +def test_diff_and_applyfunc(): + from sympy.abc import x, y, z + md = ImmutableDenseNDimArray([[x, y], [x*z, x*y*z]]) + assert md.diff(x) == ImmutableDenseNDimArray([[1, 0], [z, y*z]]) + assert diff(md, x) == ImmutableDenseNDimArray([[1, 0], [z, y*z]]) + + sd = ImmutableSparseNDimArray(md) + assert sd == ImmutableSparseNDimArray([x, y, x*z, x*y*z], (2, 2)) + assert sd.diff(x) == ImmutableSparseNDimArray([[1, 0], [z, y*z]]) + assert diff(sd, x) == ImmutableSparseNDimArray([[1, 0], [z, y*z]]) + + mdn = md.applyfunc(lambda x: x*3) + assert mdn == ImmutableDenseNDimArray([[3*x, 3*y], [3*x*z, 3*x*y*z]]) + assert md != mdn + + sdn = sd.applyfunc(lambda x: x/2) + assert sdn == ImmutableSparseNDimArray([[x/2, y/2], [x*z/2, x*y*z/2]]) + assert sd != sdn + + sdp = sd.applyfunc(lambda x: x+1) + assert sdp == ImmutableSparseNDimArray([[x + 1, y + 1], [x*z + 1, x*y*z + 1]]) + assert sd != sdp + + +def test_op_priority(): + from sympy.abc import x + md = ImmutableDenseNDimArray([1, 2, 3]) + e1 = (1+x)*md + e2 = md*(1+x) + assert e1 == ImmutableDenseNDimArray([1+x, 2+2*x, 3+3*x]) + assert e1 == e2 + + sd = ImmutableSparseNDimArray([1, 2, 3]) + e3 = (1+x)*sd + e4 = sd*(1+x) + assert e3 == ImmutableDenseNDimArray([1+x, 2+2*x, 3+3*x]) + assert e3 == e4 + + +def test_symbolic_indexing(): + x, y, z, w = symbols("x y z w") + M = ImmutableDenseNDimArray([[x, y], [z, w]]) + i, j = symbols("i, j") + Mij = M[i, j] + assert isinstance(Mij, Indexed) + Ms = ImmutableSparseNDimArray([[2, 3*x], [4, 5]]) + msij = Ms[i, j] + assert isinstance(msij, Indexed) + for oi, oj in [(0, 0), (0, 1), (1, 0), (1, 1)]: + assert Mij.subs({i: oi, j: oj}) == M[oi, oj] + assert msij.subs({i: oi, j: oj}) == Ms[oi, oj] + A = IndexedBase("A", (0, 2)) + assert A[0, 0].subs(A, M) == x + assert A[i, j].subs(A, M) == M[i, j] + assert M[i, j].subs(M, A) == A[i, j] + + assert isinstance(M[3 * i - 2, j], Indexed) + assert M[3 * i - 2, j].subs({i: 1, j: 0}) == M[1, 0] + assert isinstance(M[i, 0], Indexed) + assert M[i, 0].subs(i, 0) == M[0, 0] + assert M[0, i].subs(i, 1) == M[0, 1] + + assert M[i, j].diff(x) == ImmutableDenseNDimArray([[1, 0], [0, 0]])[i, j] + assert Ms[i, j].diff(x) == ImmutableSparseNDimArray([[0, 3], [0, 0]])[i, j] + + Mo = ImmutableDenseNDimArray([1, 2, 3]) + assert Mo[i].subs(i, 1) == 2 + Mos = ImmutableSparseNDimArray([1, 2, 3]) + assert Mos[i].subs(i, 1) == 2 + + raises(ValueError, lambda: M[i, 2]) + raises(ValueError, lambda: M[i, -1]) + raises(ValueError, lambda: M[2, i]) + raises(ValueError, lambda: M[-1, i]) + + raises(ValueError, lambda: Ms[i, 2]) + raises(ValueError, lambda: Ms[i, -1]) + raises(ValueError, lambda: Ms[2, i]) + raises(ValueError, lambda: Ms[-1, i]) + + +def test_issue_12665(): + # Testing Python 3 hash of immutable arrays: + arr = ImmutableDenseNDimArray([1, 2, 3]) + # This should NOT raise an exception: + hash(arr) + + +def test_zeros_without_shape(): + arr = ImmutableDenseNDimArray.zeros() + assert arr == ImmutableDenseNDimArray(0) + +def test_issue_21870(): + a0 = ImmutableDenseNDimArray(0) + assert a0.rank() == 0 + a1 = ImmutableDenseNDimArray(a0) + assert a1.rank() == 0 diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/test_mutable_ndim_array.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/test_mutable_ndim_array.py new file mode 100644 index 0000000000000000000000000000000000000000..9a232f399bbc0639d326217975fb0a12e645a984 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/test_mutable_ndim_array.py @@ -0,0 +1,374 @@ +from copy import copy + +from sympy.tensor.array.dense_ndim_array import MutableDenseNDimArray +from sympy.core.function import diff +from sympy.core.numbers import Rational +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.core.sympify import sympify +from sympy.matrices import SparseMatrix +from sympy.matrices import Matrix +from sympy.tensor.array.sparse_ndim_array import MutableSparseNDimArray +from sympy.testing.pytest import raises + + +def test_ndim_array_initiation(): + arr_with_one_element = MutableDenseNDimArray([23]) + assert len(arr_with_one_element) == 1 + assert arr_with_one_element[0] == 23 + assert arr_with_one_element.rank() == 1 + raises(ValueError, lambda: arr_with_one_element[1]) + + arr_with_symbol_element = MutableDenseNDimArray([Symbol('x')]) + assert len(arr_with_symbol_element) == 1 + assert arr_with_symbol_element[0] == Symbol('x') + assert arr_with_symbol_element.rank() == 1 + + number5 = 5 + vector = MutableDenseNDimArray.zeros(number5) + assert len(vector) == number5 + assert vector.shape == (number5,) + assert vector.rank() == 1 + raises(ValueError, lambda: arr_with_one_element[5]) + + vector = MutableSparseNDimArray.zeros(number5) + assert len(vector) == number5 + assert vector.shape == (number5,) + assert vector._sparse_array == {} + assert vector.rank() == 1 + + n_dim_array = MutableDenseNDimArray(range(3**4), (3, 3, 3, 3,)) + assert len(n_dim_array) == 3 * 3 * 3 * 3 + assert n_dim_array.shape == (3, 3, 3, 3) + assert n_dim_array.rank() == 4 + raises(ValueError, lambda: n_dim_array[0, 0, 0, 3]) + raises(ValueError, lambda: n_dim_array[3, 0, 0, 0]) + raises(ValueError, lambda: n_dim_array[3**4]) + + array_shape = (3, 3, 3, 3) + sparse_array = MutableSparseNDimArray.zeros(*array_shape) + assert len(sparse_array._sparse_array) == 0 + assert len(sparse_array) == 3 * 3 * 3 * 3 + assert n_dim_array.shape == array_shape + assert n_dim_array.rank() == 4 + + one_dim_array = MutableDenseNDimArray([2, 3, 1]) + assert len(one_dim_array) == 3 + assert one_dim_array.shape == (3,) + assert one_dim_array.rank() == 1 + assert one_dim_array.tolist() == [2, 3, 1] + + shape = (3, 3) + array_with_many_args = MutableSparseNDimArray.zeros(*shape) + assert len(array_with_many_args) == 3 * 3 + assert array_with_many_args.shape == shape + assert array_with_many_args[0, 0] == 0 + assert array_with_many_args.rank() == 2 + + shape = (int(3), int(3)) + array_with_long_shape = MutableSparseNDimArray.zeros(*shape) + assert len(array_with_long_shape) == 3 * 3 + assert array_with_long_shape.shape == shape + assert array_with_long_shape[int(0), int(0)] == 0 + assert array_with_long_shape.rank() == 2 + + vector_with_long_shape = MutableDenseNDimArray(range(5), int(5)) + assert len(vector_with_long_shape) == 5 + assert vector_with_long_shape.shape == (int(5),) + assert vector_with_long_shape.rank() == 1 + raises(ValueError, lambda: vector_with_long_shape[int(5)]) + + from sympy.abc import x + for ArrayType in [MutableDenseNDimArray, MutableSparseNDimArray]: + rank_zero_array = ArrayType(x) + assert len(rank_zero_array) == 1 + assert rank_zero_array.shape == () + assert rank_zero_array.rank() == 0 + assert rank_zero_array[()] == x + raises(ValueError, lambda: rank_zero_array[0]) + +def test_sympify(): + from sympy.abc import x, y, z, t + arr = MutableDenseNDimArray([[x, y], [1, z*t]]) + arr_other = sympify(arr) + assert arr_other.shape == (2, 2) + assert arr_other == arr + + +def test_reshape(): + array = MutableDenseNDimArray(range(50), 50) + assert array.shape == (50,) + assert array.rank() == 1 + + array = array.reshape(5, 5, 2) + assert array.shape == (5, 5, 2) + assert array.rank() == 3 + assert len(array) == 50 + + +def test_iterator(): + array = MutableDenseNDimArray(range(4), (2, 2)) + assert array[0] == MutableDenseNDimArray([0, 1]) + assert array[1] == MutableDenseNDimArray([2, 3]) + + array = array.reshape(4) + j = 0 + for i in array: + assert i == j + j += 1 + + +def test_getitem(): + for ArrayType in [MutableDenseNDimArray, MutableSparseNDimArray]: + array = ArrayType(range(24)).reshape(2, 3, 4) + assert array.tolist() == [[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]] + assert array[0] == ArrayType([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]) + assert array[0, 0] == ArrayType([0, 1, 2, 3]) + value = 0 + for i in range(2): + for j in range(3): + for k in range(4): + assert array[i, j, k] == value + value += 1 + + raises(ValueError, lambda: array[3, 4, 5]) + raises(ValueError, lambda: array[3, 4, 5, 6]) + raises(ValueError, lambda: array[3, 4, 5, 3:4]) + + +def test_sparse(): + sparse_array = MutableSparseNDimArray([0, 0, 0, 1], (2, 2)) + assert len(sparse_array) == 2 * 2 + # dictionary where all data is, only non-zero entries are actually stored: + assert len(sparse_array._sparse_array) == 1 + + assert sparse_array.tolist() == [[0, 0], [0, 1]] + + for i, j in zip(sparse_array, [[0, 0], [0, 1]]): + assert i == MutableSparseNDimArray(j) + + sparse_array[0, 0] = 123 + assert len(sparse_array._sparse_array) == 2 + assert sparse_array[0, 0] == 123 + assert sparse_array/0 == MutableSparseNDimArray([[S.ComplexInfinity, S.NaN], [S.NaN, S.ComplexInfinity]], (2, 2)) + + # when element in sparse array become zero it will disappear from + # dictionary + sparse_array[0, 0] = 0 + assert len(sparse_array._sparse_array) == 1 + sparse_array[1, 1] = 0 + assert len(sparse_array._sparse_array) == 0 + assert sparse_array[0, 0] == 0 + + # test for large scale sparse array + # equality test + a = MutableSparseNDimArray.zeros(100000, 200000) + b = MutableSparseNDimArray.zeros(100000, 200000) + assert a == b + a[1, 1] = 1 + b[1, 1] = 2 + assert a != b + + # __mul__ and __rmul__ + assert a * 3 == MutableSparseNDimArray({200001: 3}, (100000, 200000)) + assert 3 * a == MutableSparseNDimArray({200001: 3}, (100000, 200000)) + assert a * 0 == MutableSparseNDimArray({}, (100000, 200000)) + assert 0 * a == MutableSparseNDimArray({}, (100000, 200000)) + + # __truediv__ + assert a/3 == MutableSparseNDimArray({200001: Rational(1, 3)}, (100000, 200000)) + + # __neg__ + assert -a == MutableSparseNDimArray({200001: -1}, (100000, 200000)) + + +def test_calculation(): + + a = MutableDenseNDimArray([1]*9, (3, 3)) + b = MutableDenseNDimArray([9]*9, (3, 3)) + + c = a + b + for i in c: + assert i == MutableDenseNDimArray([10, 10, 10]) + + assert c == MutableDenseNDimArray([10]*9, (3, 3)) + assert c == MutableSparseNDimArray([10]*9, (3, 3)) + + c = b - a + for i in c: + assert i == MutableSparseNDimArray([8, 8, 8]) + + assert c == MutableDenseNDimArray([8]*9, (3, 3)) + assert c == MutableSparseNDimArray([8]*9, (3, 3)) + + +def test_ndim_array_converting(): + dense_array = MutableDenseNDimArray([1, 2, 3, 4], (2, 2)) + alist = dense_array.tolist() + + assert alist == [[1, 2], [3, 4]] + + matrix = dense_array.tomatrix() + assert (isinstance(matrix, Matrix)) + + for i in range(len(dense_array)): + assert dense_array[dense_array._get_tuple_index(i)] == matrix[i] + assert matrix.shape == dense_array.shape + + assert MutableDenseNDimArray(matrix) == dense_array + assert MutableDenseNDimArray(matrix.as_immutable()) == dense_array + assert MutableDenseNDimArray(matrix.as_mutable()) == dense_array + + sparse_array = MutableSparseNDimArray([1, 2, 3, 4], (2, 2)) + alist = sparse_array.tolist() + + assert alist == [[1, 2], [3, 4]] + + matrix = sparse_array.tomatrix() + assert(isinstance(matrix, SparseMatrix)) + + for i in range(len(sparse_array)): + assert sparse_array[sparse_array._get_tuple_index(i)] == matrix[i] + assert matrix.shape == sparse_array.shape + + assert MutableSparseNDimArray(matrix) == sparse_array + assert MutableSparseNDimArray(matrix.as_immutable()) == sparse_array + assert MutableSparseNDimArray(matrix.as_mutable()) == sparse_array + + +def test_converting_functions(): + arr_list = [1, 2, 3, 4] + arr_matrix = Matrix(((1, 2), (3, 4))) + + # list + arr_ndim_array = MutableDenseNDimArray(arr_list, (2, 2)) + assert (isinstance(arr_ndim_array, MutableDenseNDimArray)) + assert arr_matrix.tolist() == arr_ndim_array.tolist() + + # Matrix + arr_ndim_array = MutableDenseNDimArray(arr_matrix) + assert (isinstance(arr_ndim_array, MutableDenseNDimArray)) + assert arr_matrix.tolist() == arr_ndim_array.tolist() + assert arr_matrix.shape == arr_ndim_array.shape + + +def test_equality(): + first_list = [1, 2, 3, 4] + second_list = [1, 2, 3, 4] + third_list = [4, 3, 2, 1] + assert first_list == second_list + assert first_list != third_list + + first_ndim_array = MutableDenseNDimArray(first_list, (2, 2)) + second_ndim_array = MutableDenseNDimArray(second_list, (2, 2)) + third_ndim_array = MutableDenseNDimArray(third_list, (2, 2)) + fourth_ndim_array = MutableDenseNDimArray(first_list, (2, 2)) + + assert first_ndim_array == second_ndim_array + second_ndim_array[0, 0] = 0 + assert first_ndim_array != second_ndim_array + assert first_ndim_array != third_ndim_array + assert first_ndim_array == fourth_ndim_array + + +def test_arithmetic(): + a = MutableDenseNDimArray([3 for i in range(9)], (3, 3)) + b = MutableDenseNDimArray([7 for i in range(9)], (3, 3)) + + c1 = a + b + c2 = b + a + assert c1 == c2 + + d1 = a - b + d2 = b - a + assert d1 == d2 * (-1) + + e1 = a * 5 + e2 = 5 * a + e3 = copy(a) + e3 *= 5 + assert e1 == e2 == e3 + + f1 = a / 5 + f2 = copy(a) + f2 /= 5 + assert f1 == f2 + assert f1[0, 0] == f1[0, 1] == f1[0, 2] == f1[1, 0] == f1[1, 1] == \ + f1[1, 2] == f1[2, 0] == f1[2, 1] == f1[2, 2] == Rational(3, 5) + + assert type(a) == type(b) == type(c1) == type(c2) == type(d1) == type(d2) \ + == type(e1) == type(e2) == type(e3) == type(f1) + + z0 = -a + assert z0 == MutableDenseNDimArray([-3 for i in range(9)], (3, 3)) + + +def test_higher_dimenions(): + m3 = MutableDenseNDimArray(range(10, 34), (2, 3, 4)) + + assert m3.tolist() == [[[10, 11, 12, 13], + [14, 15, 16, 17], + [18, 19, 20, 21]], + + [[22, 23, 24, 25], + [26, 27, 28, 29], + [30, 31, 32, 33]]] + + assert m3._get_tuple_index(0) == (0, 0, 0) + assert m3._get_tuple_index(1) == (0, 0, 1) + assert m3._get_tuple_index(4) == (0, 1, 0) + assert m3._get_tuple_index(12) == (1, 0, 0) + + assert str(m3) == '[[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]]' + + m3_rebuilt = MutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]]) + assert m3 == m3_rebuilt + + m3_other = MutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]], (2, 3, 4)) + + assert m3 == m3_other + + +def test_slices(): + md = MutableDenseNDimArray(range(10, 34), (2, 3, 4)) + + assert md[:] == MutableDenseNDimArray(range(10, 34), (2, 3, 4)) + assert md[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]]) + assert md[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]]) + assert md[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]]) + assert md[:, :, :] == md + + sd = MutableSparseNDimArray(range(10, 34), (2, 3, 4)) + assert sd == MutableSparseNDimArray(md) + + assert sd[:] == MutableSparseNDimArray(range(10, 34), (2, 3, 4)) + assert sd[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]]) + assert sd[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]]) + assert sd[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]]) + assert sd[:, :, :] == sd + + +def test_slices_assign(): + a = MutableDenseNDimArray(range(12), shape=(4, 3)) + b = MutableSparseNDimArray(range(12), shape=(4, 3)) + + for i in [a, b]: + assert i.tolist() == [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]] + i[0, :] = [2, 2, 2] + assert i.tolist() == [[2, 2, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]] + i[0, 1:] = [8, 8] + assert i.tolist() == [[2, 8, 8], [3, 4, 5], [6, 7, 8], [9, 10, 11]] + i[1:3, 1] = [20, 44] + assert i.tolist() == [[2, 8, 8], [3, 20, 5], [6, 44, 8], [9, 10, 11]] + + +def test_diff(): + from sympy.abc import x, y, z + md = MutableDenseNDimArray([[x, y], [x*z, x*y*z]]) + assert md.diff(x) == MutableDenseNDimArray([[1, 0], [z, y*z]]) + assert diff(md, x) == MutableDenseNDimArray([[1, 0], [z, y*z]]) + + sd = MutableSparseNDimArray(md) + assert sd == MutableSparseNDimArray([x, y, x*z, x*y*z], (2, 2)) + assert sd.diff(x) == MutableSparseNDimArray([[1, 0], [z, y*z]]) + assert diff(sd, x) == MutableSparseNDimArray([[1, 0], [z, y*z]]) diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/test_ndim_array.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/test_ndim_array.py new file mode 100644 index 0000000000000000000000000000000000000000..7ff9b032631c01272c00478e4cdf0dcbc6997990 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/test_ndim_array.py @@ -0,0 +1,73 @@ +from sympy.testing.pytest import raises +from sympy.functions.elementary.trigonometric import sin, cos +from sympy.matrices.dense import Matrix +from sympy.simplify import simplify +from sympy.tensor.array import Array +from sympy.tensor.array.dense_ndim_array import ( + ImmutableDenseNDimArray, MutableDenseNDimArray) +from sympy.tensor.array.sparse_ndim_array import ( + ImmutableSparseNDimArray, MutableSparseNDimArray) + +from sympy.abc import x, y + +mutable_array_types = [ + MutableDenseNDimArray, + MutableSparseNDimArray +] + +array_types = [ + ImmutableDenseNDimArray, + ImmutableSparseNDimArray, + MutableDenseNDimArray, + MutableSparseNDimArray +] + + +def test_array_negative_indices(): + for ArrayType in array_types: + test_array = ArrayType([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) + assert test_array[:, -1] == Array([5, 10]) + assert test_array[:, -2] == Array([4, 9]) + assert test_array[:, -3] == Array([3, 8]) + assert test_array[:, -4] == Array([2, 7]) + assert test_array[:, -5] == Array([1, 6]) + assert test_array[:, 0] == Array([1, 6]) + assert test_array[:, 1] == Array([2, 7]) + assert test_array[:, 2] == Array([3, 8]) + assert test_array[:, 3] == Array([4, 9]) + assert test_array[:, 4] == Array([5, 10]) + + raises(ValueError, lambda: test_array[:, -6]) + raises(ValueError, lambda: test_array[-3, :]) + + assert test_array[-1, -1] == 10 + + +def test_issue_18361(): + A = Array([sin(2 * x) - 2 * sin(x) * cos(x)]) + B = Array([sin(x)**2 + cos(x)**2, 0]) + C = Array([(x + x**2)/(x*sin(y)**2 + x*cos(y)**2), 2*sin(x)*cos(x)]) + assert simplify(A) == Array([0]) + assert simplify(B) == Array([1, 0]) + assert simplify(C) == Array([x + 1, sin(2*x)]) + + +def test_issue_20222(): + A = Array([[1, 2], [3, 4]]) + B = Matrix([[1,2],[3,4]]) + raises(TypeError, lambda: A - B) + + +def test_issue_17851(): + for array_type in array_types: + A = array_type([]) + assert isinstance(A, array_type) + assert A.shape == (0,) + assert list(A) == [] + + +def test_issue_and_18715(): + for array_type in mutable_array_types: + A = array_type([0, 1, 2]) + A[0] += 5 + assert A[0] == 5 diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/test_ndim_array_conversions.py b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/test_ndim_array_conversions.py new file mode 100644 index 0000000000000000000000000000000000000000..f43260ccc636ac461ba0c06dbfcf3fe3a8d5338d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/array/tests/test_ndim_array_conversions.py @@ -0,0 +1,22 @@ +from sympy.tensor.array import (ImmutableDenseNDimArray, + ImmutableSparseNDimArray, MutableDenseNDimArray, MutableSparseNDimArray) +from sympy.abc import x, y, z + + +def test_NDim_array_conv(): + MD = MutableDenseNDimArray([x, y, z]) + MS = MutableSparseNDimArray([x, y, z]) + ID = ImmutableDenseNDimArray([x, y, z]) + IS = ImmutableSparseNDimArray([x, y, z]) + + assert MD.as_immutable() == ID + assert MD.as_mutable() == MD + + assert MS.as_immutable() == IS + assert MS.as_mutable() == MS + + assert ID.as_immutable() == ID + assert ID.as_mutable() == MD + + assert IS.as_immutable() == IS + assert IS.as_mutable() == MS diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/functions.py b/.venv/lib/python3.12/site-packages/sympy/tensor/functions.py new file mode 100644 index 0000000000000000000000000000000000000000..f14599d69152db1713f21c9dd785683901c5eeb9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/functions.py @@ -0,0 +1,154 @@ +from collections.abc import Iterable +from functools import singledispatch + +from sympy.core.expr import Expr +from sympy.core.mul import Mul +from sympy.core.singleton import S +from sympy.core.sympify import sympify +from sympy.core.parameters import global_parameters + + +class TensorProduct(Expr): + """ + Generic class for tensor products. + """ + is_number = False + + def __new__(cls, *args, **kwargs): + from sympy.tensor.array import NDimArray, tensorproduct, Array + from sympy.matrices.expressions.matexpr import MatrixExpr + from sympy.matrices.matrixbase import MatrixBase + from sympy.strategies import flatten + + args = [sympify(arg) for arg in args] + evaluate = kwargs.get("evaluate", global_parameters.evaluate) + + if not evaluate: + obj = Expr.__new__(cls, *args) + return obj + + arrays = [] + other = [] + scalar = S.One + for arg in args: + if isinstance(arg, (Iterable, MatrixBase, NDimArray)): + arrays.append(Array(arg)) + elif isinstance(arg, (MatrixExpr,)): + other.append(arg) + else: + scalar *= arg + + coeff = scalar*tensorproduct(*arrays) + if len(other) == 0: + return coeff + if coeff != 1: + newargs = [coeff] + other + else: + newargs = other + obj = Expr.__new__(cls, *newargs, **kwargs) + return flatten(obj) + + def rank(self): + return len(self.shape) + + def _get_args_shapes(self): + from sympy.tensor.array import Array + return [i.shape if hasattr(i, "shape") else Array(i).shape for i in self.args] + + @property + def shape(self): + shape_list = self._get_args_shapes() + return sum(shape_list, ()) + + def __getitem__(self, index): + index = iter(index) + return Mul.fromiter( + arg.__getitem__(tuple(next(index) for i in shp)) + for arg, shp in zip(self.args, self._get_args_shapes()) + ) + + +@singledispatch +def shape(expr): + """ + Return the shape of the *expr* as a tuple. *expr* should represent + suitable object such as matrix or array. + + Parameters + ========== + + expr : SymPy object having ``MatrixKind`` or ``ArrayKind``. + + Raises + ====== + + NoShapeError : Raised when object with wrong kind is passed. + + Examples + ======== + + This function returns the shape of any object representing matrix or array. + + >>> from sympy import shape, Array, ImmutableDenseMatrix, Integral + >>> from sympy.abc import x + >>> A = Array([1, 2]) + >>> shape(A) + (2,) + >>> shape(Integral(A, x)) + (2,) + >>> M = ImmutableDenseMatrix([1, 2]) + >>> shape(M) + (2, 1) + >>> shape(Integral(M, x)) + (2, 1) + + You can support new type by dispatching. + + >>> from sympy import Expr + >>> class NewExpr(Expr): + ... pass + >>> @shape.register(NewExpr) + ... def _(expr): + ... return shape(expr.args[0]) + >>> shape(NewExpr(M)) + (2, 1) + + If unsuitable expression is passed, ``NoShapeError()`` will be raised. + + >>> shape(Integral(x, x)) + Traceback (most recent call last): + ... + sympy.tensor.functions.NoShapeError: shape() called on non-array object: Integral(x, x) + + Notes + ===== + + Array-like classes (such as ``Matrix`` or ``NDimArray``) has ``shape`` + property which returns its shape, but it cannot be used for non-array + classes containing array. This function returns the shape of any + registered object representing array. + + """ + if hasattr(expr, "shape"): + return expr.shape + raise NoShapeError( + "%s does not have shape, or its type is not registered to shape()." % expr) + + +class NoShapeError(Exception): + """ + Raised when ``shape()`` is called on non-array object. + + This error can be imported from ``sympy.tensor.functions``. + + Examples + ======== + + >>> from sympy import shape + >>> from sympy.abc import x + >>> shape(x) + Traceback (most recent call last): + ... + sympy.tensor.functions.NoShapeError: shape() called on non-array object: x + """ + pass diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/index_methods.py b/.venv/lib/python3.12/site-packages/sympy/tensor/index_methods.py new file mode 100644 index 0000000000000000000000000000000000000000..12f707b60b4ad0bcadc35a222d9abe0cc5e033fc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/index_methods.py @@ -0,0 +1,469 @@ +"""Module with functions operating on IndexedBase, Indexed and Idx objects + + - Check shape conformance + - Determine indices in resulting expression + + etc. + + Methods in this module could be implemented by calling methods on Expr + objects instead. When things stabilize this could be a useful + refactoring. +""" + +from functools import reduce + +from sympy.core.function import Function +from sympy.functions import exp, Piecewise +from sympy.tensor.indexed import Idx, Indexed +from sympy.utilities import sift + +from collections import OrderedDict + +class IndexConformanceException(Exception): + pass + +def _unique_and_repeated(inds): + """ + Returns the unique and repeated indices. Also note, from the examples given below + that the order of indices is maintained as given in the input. + + Examples + ======== + + >>> from sympy.tensor.index_methods import _unique_and_repeated + >>> _unique_and_repeated([2, 3, 1, 3, 0, 4, 0]) + ([2, 1, 4], [3, 0]) + """ + uniq = OrderedDict() + for i in inds: + if i in uniq: + uniq[i] = 0 + else: + uniq[i] = 1 + return sift(uniq, lambda x: uniq[x], binary=True) + +def _remove_repeated(inds): + """ + Removes repeated objects from sequences + + Returns a set of the unique objects and a tuple of all that have been + removed. + + Examples + ======== + + >>> from sympy.tensor.index_methods import _remove_repeated + >>> l1 = [1, 2, 3, 2] + >>> _remove_repeated(l1) + ({1, 3}, (2,)) + + """ + u, r = _unique_and_repeated(inds) + return set(u), tuple(r) + + +def _get_indices_Mul(expr, return_dummies=False): + """Determine the outer indices of a Mul object. + + Examples + ======== + + >>> from sympy.tensor.index_methods import _get_indices_Mul + >>> from sympy.tensor.indexed import IndexedBase, Idx + >>> i, j, k = map(Idx, ['i', 'j', 'k']) + >>> x = IndexedBase('x') + >>> y = IndexedBase('y') + >>> _get_indices_Mul(x[i, k]*y[j, k]) + ({i, j}, {}) + >>> _get_indices_Mul(x[i, k]*y[j, k], return_dummies=True) + ({i, j}, {}, (k,)) + + """ + + inds = list(map(get_indices, expr.args)) + inds, syms = list(zip(*inds)) + + inds = list(map(list, inds)) + inds = list(reduce(lambda x, y: x + y, inds)) + inds, dummies = _remove_repeated(inds) + + symmetry = {} + for s in syms: + for pair in s: + if pair in symmetry: + symmetry[pair] *= s[pair] + else: + symmetry[pair] = s[pair] + + if return_dummies: + return inds, symmetry, dummies + else: + return inds, symmetry + + +def _get_indices_Pow(expr): + """Determine outer indices of a power or an exponential. + + A power is considered a universal function, so that the indices of a Pow is + just the collection of indices present in the expression. This may be + viewed as a bit inconsistent in the special case: + + x[i]**2 = x[i]*x[i] (1) + + The above expression could have been interpreted as the contraction of x[i] + with itself, but we choose instead to interpret it as a function + + lambda y: y**2 + + applied to each element of x (a universal function in numpy terms). In + order to allow an interpretation of (1) as a contraction, we need + contravariant and covariant Idx subclasses. (FIXME: this is not yet + implemented) + + Expressions in the base or exponent are subject to contraction as usual, + but an index that is present in the exponent, will not be considered + contractable with its own base. Note however, that indices in the same + exponent can be contracted with each other. + + Examples + ======== + + >>> from sympy.tensor.index_methods import _get_indices_Pow + >>> from sympy import Pow, exp, IndexedBase, Idx + >>> A = IndexedBase('A') + >>> x = IndexedBase('x') + >>> i, j, k = map(Idx, ['i', 'j', 'k']) + >>> _get_indices_Pow(exp(A[i, j]*x[j])) + ({i}, {}) + >>> _get_indices_Pow(Pow(x[i], x[i])) + ({i}, {}) + >>> _get_indices_Pow(Pow(A[i, j]*x[j], x[i])) + ({i}, {}) + + """ + base, exp = expr.as_base_exp() + binds, bsyms = get_indices(base) + einds, esyms = get_indices(exp) + + inds = binds | einds + + # FIXME: symmetries from power needs to check special cases, else nothing + symmetries = {} + + return inds, symmetries + + +def _get_indices_Add(expr): + """Determine outer indices of an Add object. + + In a sum, each term must have the same set of outer indices. A valid + expression could be + + x(i)*y(j) - x(j)*y(i) + + But we do not allow expressions like: + + x(i)*y(j) - z(j)*z(j) + + FIXME: Add support for Numpy broadcasting + + Examples + ======== + + >>> from sympy.tensor.index_methods import _get_indices_Add + >>> from sympy.tensor.indexed import IndexedBase, Idx + >>> i, j, k = map(Idx, ['i', 'j', 'k']) + >>> x = IndexedBase('x') + >>> y = IndexedBase('y') + >>> _get_indices_Add(x[i] + x[k]*y[i, k]) + ({i}, {}) + + """ + + inds = list(map(get_indices, expr.args)) + inds, syms = list(zip(*inds)) + + # allow broadcast of scalars + non_scalars = [x for x in inds if x != set()] + if not non_scalars: + return set(), {} + + if not all(x == non_scalars[0] for x in non_scalars[1:]): + raise IndexConformanceException("Indices are not consistent: %s" % expr) + if not reduce(lambda x, y: x != y or y, syms): + symmetries = syms[0] + else: + # FIXME: search for symmetries + symmetries = {} + + return non_scalars[0], symmetries + + +def get_indices(expr): + """Determine the outer indices of expression ``expr`` + + By *outer* we mean indices that are not summation indices. Returns a set + and a dict. The set contains outer indices and the dict contains + information about index symmetries. + + Examples + ======== + + >>> from sympy.tensor.index_methods import get_indices + >>> from sympy import symbols + >>> from sympy.tensor import IndexedBase + >>> x, y, A = map(IndexedBase, ['x', 'y', 'A']) + >>> i, j, a, z = symbols('i j a z', integer=True) + + The indices of the total expression is determined, Repeated indices imply a + summation, for instance the trace of a matrix A: + + >>> get_indices(A[i, i]) + (set(), {}) + + In the case of many terms, the terms are required to have identical + outer indices. Else an IndexConformanceException is raised. + + >>> get_indices(x[i] + A[i, j]*y[j]) + ({i}, {}) + + :Exceptions: + + An IndexConformanceException means that the terms ar not compatible, e.g. + + >>> get_indices(x[i] + y[j]) #doctest: +SKIP + (...) + IndexConformanceException: Indices are not consistent: x(i) + y(j) + + .. warning:: + The concept of *outer* indices applies recursively, starting on the deepest + level. This implies that dummies inside parenthesis are assumed to be + summed first, so that the following expression is handled gracefully: + + >>> get_indices((x[i] + A[i, j]*y[j])*x[j]) + ({i, j}, {}) + + This is correct and may appear convenient, but you need to be careful + with this as SymPy will happily .expand() the product, if requested. The + resulting expression would mix the outer ``j`` with the dummies inside + the parenthesis, which makes it a different expression. To be on the + safe side, it is best to avoid such ambiguities by using unique indices + for all contractions that should be held separate. + + """ + # We call ourself recursively to determine indices of sub expressions. + + # break recursion + if isinstance(expr, Indexed): + c = expr.indices + inds, dummies = _remove_repeated(c) + return inds, {} + elif expr is None: + return set(), {} + elif isinstance(expr, Idx): + return {expr}, {} + elif expr.is_Atom: + return set(), {} + + + # recurse via specialized functions + else: + if expr.is_Mul: + return _get_indices_Mul(expr) + elif expr.is_Add: + return _get_indices_Add(expr) + elif expr.is_Pow or isinstance(expr, exp): + return _get_indices_Pow(expr) + + elif isinstance(expr, Piecewise): + # FIXME: No support for Piecewise yet + return set(), {} + elif isinstance(expr, Function): + # Support ufunc like behaviour by returning indices from arguments. + # Functions do not interpret repeated indices across arguments + # as summation + ind0 = set() + for arg in expr.args: + ind, sym = get_indices(arg) + ind0 |= ind + return ind0, sym + + # this test is expensive, so it should be at the end + elif not expr.has(Indexed): + return set(), {} + raise NotImplementedError( + "FIXME: No specialized handling of type %s" % type(expr)) + + +def get_contraction_structure(expr): + """Determine dummy indices of ``expr`` and describe its structure + + By *dummy* we mean indices that are summation indices. + + The structure of the expression is determined and described as follows: + + 1) A conforming summation of Indexed objects is described with a dict where + the keys are summation indices and the corresponding values are sets + containing all terms for which the summation applies. All Add objects + in the SymPy expression tree are described like this. + + 2) For all nodes in the SymPy expression tree that are *not* of type Add, the + following applies: + + If a node discovers contractions in one of its arguments, the node + itself will be stored as a key in the dict. For that key, the + corresponding value is a list of dicts, each of which is the result of a + recursive call to get_contraction_structure(). The list contains only + dicts for the non-trivial deeper contractions, omitting dicts with None + as the one and only key. + + .. Note:: The presence of expressions among the dictionary keys indicates + multiple levels of index contractions. A nested dict displays nested + contractions and may itself contain dicts from a deeper level. In + practical calculations the summation in the deepest nested level must be + calculated first so that the outer expression can access the resulting + indexed object. + + Examples + ======== + + >>> from sympy.tensor.index_methods import get_contraction_structure + >>> from sympy import default_sort_key + >>> from sympy.tensor import IndexedBase, Idx + >>> x, y, A = map(IndexedBase, ['x', 'y', 'A']) + >>> i, j, k, l = map(Idx, ['i', 'j', 'k', 'l']) + >>> get_contraction_structure(x[i]*y[i] + A[j, j]) + {(i,): {x[i]*y[i]}, (j,): {A[j, j]}} + >>> get_contraction_structure(x[i]*y[j]) + {None: {x[i]*y[j]}} + + A multiplication of contracted factors results in nested dicts representing + the internal contractions. + + >>> d = get_contraction_structure(x[i, i]*y[j, j]) + >>> sorted(d.keys(), key=default_sort_key) + [None, x[i, i]*y[j, j]] + + In this case, the product has no contractions: + + >>> d[None] + {x[i, i]*y[j, j]} + + Factors are contracted "first": + + >>> sorted(d[x[i, i]*y[j, j]], key=default_sort_key) + [{(i,): {x[i, i]}}, {(j,): {y[j, j]}}] + + A parenthesized Add object is also returned as a nested dictionary. The + term containing the parenthesis is a Mul with a contraction among the + arguments, so it will be found as a key in the result. It stores the + dictionary resulting from a recursive call on the Add expression. + + >>> d = get_contraction_structure(x[i]*(y[i] + A[i, j]*x[j])) + >>> sorted(d.keys(), key=default_sort_key) + [(A[i, j]*x[j] + y[i])*x[i], (i,)] + >>> d[(i,)] + {(A[i, j]*x[j] + y[i])*x[i]} + >>> d[x[i]*(A[i, j]*x[j] + y[i])] + [{None: {y[i]}, (j,): {A[i, j]*x[j]}}] + + Powers with contractions in either base or exponent will also be found as + keys in the dictionary, mapping to a list of results from recursive calls: + + >>> d = get_contraction_structure(A[j, j]**A[i, i]) + >>> d[None] + {A[j, j]**A[i, i]} + >>> nested_contractions = d[A[j, j]**A[i, i]] + >>> nested_contractions[0] + {(j,): {A[j, j]}} + >>> nested_contractions[1] + {(i,): {A[i, i]}} + + The description of the contraction structure may appear complicated when + represented with a string in the above examples, but it is easy to iterate + over: + + >>> from sympy import Expr + >>> for key in d: + ... if isinstance(key, Expr): + ... continue + ... for term in d[key]: + ... if term in d: + ... # treat deepest contraction first + ... pass + ... # treat outermost contactions here + + """ + + # We call ourself recursively to inspect sub expressions. + + if isinstance(expr, Indexed): + junk, key = _remove_repeated(expr.indices) + return {key or None: {expr}} + elif expr.is_Atom: + return {None: {expr}} + elif expr.is_Mul: + junk, junk, key = _get_indices_Mul(expr, return_dummies=True) + result = {key or None: {expr}} + # recurse on every factor + nested = [] + for fac in expr.args: + facd = get_contraction_structure(fac) + if not (None in facd and len(facd) == 1): + nested.append(facd) + if nested: + result[expr] = nested + return result + elif expr.is_Pow or isinstance(expr, exp): + # recurse in base and exp separately. If either has internal + # contractions we must include ourselves as a key in the returned dict + b, e = expr.as_base_exp() + dbase = get_contraction_structure(b) + dexp = get_contraction_structure(e) + + dicts = [] + for d in dbase, dexp: + if not (None in d and len(d) == 1): + dicts.append(d) + result = {None: {expr}} + if dicts: + result[expr] = dicts + return result + elif expr.is_Add: + # Note: we just collect all terms with identical summation indices, We + # do nothing to identify equivalent terms here, as this would require + # substitutions or pattern matching in expressions of unknown + # complexity. + result = {} + for term in expr.args: + # recurse on every term + d = get_contraction_structure(term) + for key in d: + if key in result: + result[key] |= d[key] + else: + result[key] = d[key] + return result + + elif isinstance(expr, Piecewise): + # FIXME: No support for Piecewise yet + return {None: expr} + elif isinstance(expr, Function): + # Collect non-trivial contraction structures in each argument + # We do not report repeated indices in separate arguments as a + # contraction + deeplist = [] + for arg in expr.args: + deep = get_contraction_structure(arg) + if not (None in deep and len(deep) == 1): + deeplist.append(deep) + d = {None: {expr}} + if deeplist: + d[expr] = deeplist + return d + + # this test is expensive, so it should be at the end + elif not expr.has(Indexed): + return {None: {expr}} + raise NotImplementedError( + "FIXME: No specialized handling of type %s" % type(expr)) diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/indexed.py b/.venv/lib/python3.12/site-packages/sympy/tensor/indexed.py new file mode 100644 index 0000000000000000000000000000000000000000..feddad21e52bbab2e1243beafdb11f30b2eded4d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/indexed.py @@ -0,0 +1,793 @@ +r"""Module that defines indexed objects. + +The classes ``IndexedBase``, ``Indexed``, and ``Idx`` represent a +matrix element ``M[i, j]`` as in the following diagram:: + + 1) The Indexed class represents the entire indexed object. + | + ___|___ + ' ' + M[i, j] + / \__\______ + | | + | | + | 2) The Idx class represents indices; each Idx can + | optionally contain information about its range. + | + 3) IndexedBase represents the 'stem' of an indexed object, here `M`. + The stem used by itself is usually taken to represent the entire + array. + +There can be any number of indices on an Indexed object. No +transformation properties are implemented in these Base objects, but +implicit contraction of repeated indices is supported. + +Note that the support for complicated (i.e. non-atomic) integer +expressions as indices is limited. (This should be improved in +future releases.) + +Examples +======== + +To express the above matrix element example you would write: + +>>> from sympy import symbols, IndexedBase, Idx +>>> M = IndexedBase('M') +>>> i, j = symbols('i j', cls=Idx) +>>> M[i, j] +M[i, j] + +Repeated indices in a product implies a summation, so to express a +matrix-vector product in terms of Indexed objects: + +>>> x = IndexedBase('x') +>>> M[i, j]*x[j] +M[i, j]*x[j] + +If the indexed objects will be converted to component based arrays, e.g. +with the code printers or the autowrap framework, you also need to provide +(symbolic or numerical) dimensions. This can be done by passing an +optional shape parameter to IndexedBase upon construction: + +>>> dim1, dim2 = symbols('dim1 dim2', integer=True) +>>> A = IndexedBase('A', shape=(dim1, 2*dim1, dim2)) +>>> A.shape +(dim1, 2*dim1, dim2) +>>> A[i, j, 3].shape +(dim1, 2*dim1, dim2) + +If an IndexedBase object has no shape information, it is assumed that the +array is as large as the ranges of its indices: + +>>> n, m = symbols('n m', integer=True) +>>> i = Idx('i', m) +>>> j = Idx('j', n) +>>> M[i, j].shape +(m, n) +>>> M[i, j].ranges +[(0, m - 1), (0, n - 1)] + +The above can be compared with the following: + +>>> A[i, 2, j].shape +(dim1, 2*dim1, dim2) +>>> A[i, 2, j].ranges +[(0, m - 1), None, (0, n - 1)] + +To analyze the structure of indexed expressions, you can use the methods +get_indices() and get_contraction_structure(): + +>>> from sympy.tensor import get_indices, get_contraction_structure +>>> get_indices(A[i, j, j]) +({i}, {}) +>>> get_contraction_structure(A[i, j, j]) +{(j,): {A[i, j, j]}} + +See the appropriate docstrings for a detailed explanation of the output. +""" + +# TODO: (some ideas for improvement) +# +# o test and guarantee numpy compatibility +# - implement full support for broadcasting +# - strided arrays +# +# o more functions to analyze indexed expressions +# - identify standard constructs, e.g matrix-vector product in a subexpression +# +# o functions to generate component based arrays (numpy and sympy.Matrix) +# - generate a single array directly from Indexed +# - convert simple sub-expressions +# +# o sophisticated indexing (possibly in subclasses to preserve simplicity) +# - Idx with range smaller than dimension of Indexed +# - Idx with stepsize != 1 +# - Idx with step determined by function call +from collections.abc import Iterable + +from sympy.core.numbers import Number +from sympy.core.assumptions import StdFactKB +from sympy.core import Expr, Tuple, sympify, S +from sympy.core.symbol import _filter_assumptions, Symbol +from sympy.core.logic import fuzzy_bool, fuzzy_not +from sympy.core.sympify import _sympify +from sympy.functions.special.tensor_functions import KroneckerDelta +from sympy.multipledispatch import dispatch +from sympy.utilities.iterables import is_sequence, NotIterable +from sympy.utilities.misc import filldedent + + +class IndexException(Exception): + pass + + +class Indexed(Expr): + """Represents a mathematical object with indices. + + >>> from sympy import Indexed, IndexedBase, Idx, symbols + >>> i, j = symbols('i j', cls=Idx) + >>> Indexed('A', i, j) + A[i, j] + + It is recommended that ``Indexed`` objects be created by indexing ``IndexedBase``: + ``IndexedBase('A')[i, j]`` instead of ``Indexed(IndexedBase('A'), i, j)``. + + >>> A = IndexedBase('A') + >>> a_ij = A[i, j] # Prefer this, + >>> b_ij = Indexed(A, i, j) # over this. + >>> a_ij == b_ij + True + + """ + is_Indexed = True + is_symbol = True + is_Atom = True + + def __new__(cls, base, *args, **kw_args): + from sympy.tensor.array.ndim_array import NDimArray + from sympy.matrices.matrixbase import MatrixBase + + if not args: + raise IndexException("Indexed needs at least one index.") + if isinstance(base, (str, Symbol)): + base = IndexedBase(base) + elif not hasattr(base, '__getitem__') and not isinstance(base, IndexedBase): + raise TypeError(filldedent(""" + The base can only be replaced with a string, Symbol, + IndexedBase or an object with a method for getting + items (i.e. an object with a `__getitem__` method). + """)) + args = list(map(sympify, args)) + if isinstance(base, (NDimArray, Iterable, Tuple, MatrixBase)) and all(i.is_number for i in args): + if len(args) == 1: + return base[args[0]] + else: + return base[args] + + base = _sympify(base) + + obj = Expr.__new__(cls, base, *args, **kw_args) + + IndexedBase._set_assumptions(obj, base.assumptions0) + + return obj + + def _hashable_content(self): + return super()._hashable_content() + tuple(sorted(self.assumptions0.items())) + + @property + def name(self): + return str(self) + + @property + def _diff_wrt(self): + """Allow derivatives with respect to an ``Indexed`` object.""" + return True + + def _eval_derivative(self, wrt): + from sympy.tensor.array.ndim_array import NDimArray + + if isinstance(wrt, Indexed) and wrt.base == self.base: + if len(self.indices) != len(wrt.indices): + msg = "Different # of indices: d({!s})/d({!s})".format(self, + wrt) + raise IndexException(msg) + result = S.One + for index1, index2 in zip(self.indices, wrt.indices): + result *= KroneckerDelta(index1, index2) + return result + elif isinstance(self.base, NDimArray): + from sympy.tensor.array import derive_by_array + return Indexed(derive_by_array(self.base, wrt), *self.args[1:]) + else: + if Tuple(self.indices).has(wrt): + return S.NaN + return S.Zero + + @property + def assumptions0(self): + return {k: v for k, v in self._assumptions.items() if v is not None} + + @property + def base(self): + """Returns the ``IndexedBase`` of the ``Indexed`` object. + + Examples + ======== + + >>> from sympy import Indexed, IndexedBase, Idx, symbols + >>> i, j = symbols('i j', cls=Idx) + >>> Indexed('A', i, j).base + A + >>> B = IndexedBase('B') + >>> B == B[i, j].base + True + + """ + return self.args[0] + + @property + def indices(self): + """ + Returns the indices of the ``Indexed`` object. + + Examples + ======== + + >>> from sympy import Indexed, Idx, symbols + >>> i, j = symbols('i j', cls=Idx) + >>> Indexed('A', i, j).indices + (i, j) + + """ + return self.args[1:] + + @property + def rank(self): + """ + Returns the rank of the ``Indexed`` object. + + Examples + ======== + + >>> from sympy import Indexed, Idx, symbols + >>> i, j, k, l, m = symbols('i:m', cls=Idx) + >>> Indexed('A', i, j).rank + 2 + >>> q = Indexed('A', i, j, k, l, m) + >>> q.rank + 5 + >>> q.rank == len(q.indices) + True + + """ + return len(self.args) - 1 + + @property + def shape(self): + """Returns a list with dimensions of each index. + + Dimensions is a property of the array, not of the indices. Still, if + the ``IndexedBase`` does not define a shape attribute, it is assumed + that the ranges of the indices correspond to the shape of the array. + + >>> from sympy import IndexedBase, Idx, symbols + >>> n, m = symbols('n m', integer=True) + >>> i = Idx('i', m) + >>> j = Idx('j', m) + >>> A = IndexedBase('A', shape=(n, n)) + >>> B = IndexedBase('B') + >>> A[i, j].shape + (n, n) + >>> B[i, j].shape + (m, m) + """ + + if self.base.shape: + return self.base.shape + sizes = [] + for i in self.indices: + upper = getattr(i, 'upper', None) + lower = getattr(i, 'lower', None) + if None in (upper, lower): + raise IndexException(filldedent(""" + Range is not defined for all indices in: %s""" % self)) + try: + size = upper - lower + 1 + except TypeError: + raise IndexException(filldedent(""" + Shape cannot be inferred from Idx with + undefined range: %s""" % self)) + sizes.append(size) + return Tuple(*sizes) + + @property + def ranges(self): + """Returns a list of tuples with lower and upper range of each index. + + If an index does not define the data members upper and lower, the + corresponding slot in the list contains ``None`` instead of a tuple. + + Examples + ======== + + >>> from sympy import Indexed,Idx, symbols + >>> Indexed('A', Idx('i', 2), Idx('j', 4), Idx('k', 8)).ranges + [(0, 1), (0, 3), (0, 7)] + >>> Indexed('A', Idx('i', 3), Idx('j', 3), Idx('k', 3)).ranges + [(0, 2), (0, 2), (0, 2)] + >>> x, y, z = symbols('x y z', integer=True) + >>> Indexed('A', x, y, z).ranges + [None, None, None] + + """ + ranges = [] + sentinel = object() + for i in self.indices: + upper = getattr(i, 'upper', sentinel) + lower = getattr(i, 'lower', sentinel) + if sentinel not in (upper, lower): + ranges.append((lower, upper)) + else: + ranges.append(None) + return ranges + + def _sympystr(self, p): + indices = list(map(p.doprint, self.indices)) + return "%s[%s]" % (p.doprint(self.base), ", ".join(indices)) + + @property + def free_symbols(self): + base_free_symbols = self.base.free_symbols + indices_free_symbols = { + fs for i in self.indices for fs in i.free_symbols} + if base_free_symbols: + return {self} | base_free_symbols | indices_free_symbols + else: + return indices_free_symbols + + @property + def expr_free_symbols(self): + from sympy.utilities.exceptions import sympy_deprecation_warning + sympy_deprecation_warning(""" + The expr_free_symbols property is deprecated. Use free_symbols to get + the free symbols of an expression. + """, + deprecated_since_version="1.9", + active_deprecations_target="deprecated-expr-free-symbols") + + return {self} + + +class IndexedBase(Expr, NotIterable): + """Represent the base or stem of an indexed object + + The IndexedBase class represent an array that contains elements. The main purpose + of this class is to allow the convenient creation of objects of the Indexed + class. The __getitem__ method of IndexedBase returns an instance of + Indexed. Alone, without indices, the IndexedBase class can be used as a + notation for e.g. matrix equations, resembling what you could do with the + Symbol class. But, the IndexedBase class adds functionality that is not + available for Symbol instances: + + - An IndexedBase object can optionally store shape information. This can + be used in to check array conformance and conditions for numpy + broadcasting. (TODO) + - An IndexedBase object implements syntactic sugar that allows easy symbolic + representation of array operations, using implicit summation of + repeated indices. + - The IndexedBase object symbolizes a mathematical structure equivalent + to arrays, and is recognized as such for code generation and automatic + compilation and wrapping. + + >>> from sympy.tensor import IndexedBase, Idx + >>> from sympy import symbols + >>> A = IndexedBase('A'); A + A + >>> type(A) + + + When an IndexedBase object receives indices, it returns an array with named + axes, represented by an Indexed object: + + >>> i, j = symbols('i j', integer=True) + >>> A[i, j, 2] + A[i, j, 2] + >>> type(A[i, j, 2]) + + + The IndexedBase constructor takes an optional shape argument. If given, + it overrides any shape information in the indices. (But not the index + ranges!) + + >>> m, n, o, p = symbols('m n o p', integer=True) + >>> i = Idx('i', m) + >>> j = Idx('j', n) + >>> A[i, j].shape + (m, n) + >>> B = IndexedBase('B', shape=(o, p)) + >>> B[i, j].shape + (o, p) + + Assumptions can be specified with keyword arguments the same way as for Symbol: + + >>> A_real = IndexedBase('A', real=True) + >>> A_real.is_real + True + >>> A != A_real + True + + Assumptions can also be inherited if a Symbol is used to initialize the IndexedBase: + + >>> I = symbols('I', integer=True) + >>> C_inherit = IndexedBase(I) + >>> C_explicit = IndexedBase('I', integer=True) + >>> C_inherit == C_explicit + True + """ + is_symbol = True + is_Atom = True + + @staticmethod + def _set_assumptions(obj, assumptions): + """Set assumptions on obj, making sure to apply consistent values.""" + tmp_asm_copy = assumptions.copy() + is_commutative = fuzzy_bool(assumptions.get('commutative', True)) + assumptions['commutative'] = is_commutative + obj._assumptions = StdFactKB(assumptions) + obj._assumptions._generator = tmp_asm_copy # Issue #8873 + + def __new__(cls, label, shape=None, *, offset=S.Zero, strides=None, **kw_args): + from sympy.matrices.matrixbase import MatrixBase + from sympy.tensor.array.ndim_array import NDimArray + + assumptions, kw_args = _filter_assumptions(kw_args) + if isinstance(label, str): + label = Symbol(label, **assumptions) + elif isinstance(label, Symbol): + assumptions = label._merge(assumptions) + elif isinstance(label, (MatrixBase, NDimArray)): + return label + elif isinstance(label, Iterable): + return _sympify(label) + else: + label = _sympify(label) + + if is_sequence(shape): + shape = Tuple(*shape) + elif shape is not None: + shape = Tuple(shape) + + if shape is not None: + obj = Expr.__new__(cls, label, shape) + else: + obj = Expr.__new__(cls, label) + obj._shape = shape + obj._offset = offset + obj._strides = strides + obj._name = str(label) + + IndexedBase._set_assumptions(obj, assumptions) + return obj + + @property + def name(self): + return self._name + + def _hashable_content(self): + return super()._hashable_content() + tuple(sorted(self.assumptions0.items())) + + @property + def assumptions0(self): + return {k: v for k, v in self._assumptions.items() if v is not None} + + def __getitem__(self, indices, **kw_args): + if is_sequence(indices): + # Special case needed because M[*my_tuple] is a syntax error. + if self.shape and len(self.shape) != len(indices): + raise IndexException("Rank mismatch.") + return Indexed(self, *indices, **kw_args) + else: + if self.shape and len(self.shape) != 1: + raise IndexException("Rank mismatch.") + return Indexed(self, indices, **kw_args) + + @property + def shape(self): + """Returns the shape of the ``IndexedBase`` object. + + Examples + ======== + + >>> from sympy import IndexedBase, Idx + >>> from sympy.abc import x, y + >>> IndexedBase('A', shape=(x, y)).shape + (x, y) + + Note: If the shape of the ``IndexedBase`` is specified, it will override + any shape information given by the indices. + + >>> A = IndexedBase('A', shape=(x, y)) + >>> B = IndexedBase('B') + >>> i = Idx('i', 2) + >>> j = Idx('j', 1) + >>> A[i, j].shape + (x, y) + >>> B[i, j].shape + (2, 1) + + """ + return self._shape + + @property + def strides(self): + """Returns the strided scheme for the ``IndexedBase`` object. + + Normally this is a tuple denoting the number of + steps to take in the respective dimension when traversing + an array. For code generation purposes strides='C' and + strides='F' can also be used. + + strides='C' would mean that code printer would unroll + in row-major order and 'F' means unroll in column major + order. + + """ + + return self._strides + + @property + def offset(self): + """Returns the offset for the ``IndexedBase`` object. + + This is the value added to the resulting index when the + 2D Indexed object is unrolled to a 1D form. Used in code + generation. + + Examples + ========== + >>> from sympy.printing import ccode + >>> from sympy.tensor import IndexedBase, Idx + >>> from sympy import symbols + >>> l, m, n, o = symbols('l m n o', integer=True) + >>> A = IndexedBase('A', strides=(l, m, n), offset=o) + >>> i, j, k = map(Idx, 'ijk') + >>> ccode(A[i, j, k]) + 'A[l*i + m*j + n*k + o]' + + """ + return self._offset + + @property + def label(self): + """Returns the label of the ``IndexedBase`` object. + + Examples + ======== + + >>> from sympy import IndexedBase + >>> from sympy.abc import x, y + >>> IndexedBase('A', shape=(x, y)).label + A + + """ + return self.args[0] + + def _sympystr(self, p): + return p.doprint(self.label) + + +class Idx(Expr): + """Represents an integer index as an ``Integer`` or integer expression. + + There are a number of ways to create an ``Idx`` object. The constructor + takes two arguments: + + ``label`` + An integer or a symbol that labels the index. + ``range`` + Optionally you can specify a range as either + + * ``Symbol`` or integer: This is interpreted as a dimension. Lower and + upper bounds are set to ``0`` and ``range - 1``, respectively. + * ``tuple``: The two elements are interpreted as the lower and upper + bounds of the range, respectively. + + Note: bounds of the range are assumed to be either integer or infinite (oo + and -oo are allowed to specify an unbounded range). If ``n`` is given as a + bound, then ``n.is_integer`` must not return false. + + For convenience, if the label is given as a string it is automatically + converted to an integer symbol. (Note: this conversion is not done for + range or dimension arguments.) + + Examples + ======== + + >>> from sympy import Idx, symbols, oo + >>> n, i, L, U = symbols('n i L U', integer=True) + + If a string is given for the label an integer ``Symbol`` is created and the + bounds are both ``None``: + + >>> idx = Idx('qwerty'); idx + qwerty + >>> idx.lower, idx.upper + (None, None) + + Both upper and lower bounds can be specified: + + >>> idx = Idx(i, (L, U)); idx + i + >>> idx.lower, idx.upper + (L, U) + + When only a single bound is given it is interpreted as the dimension + and the lower bound defaults to 0: + + >>> idx = Idx(i, n); idx.lower, idx.upper + (0, n - 1) + >>> idx = Idx(i, 4); idx.lower, idx.upper + (0, 3) + >>> idx = Idx(i, oo); idx.lower, idx.upper + (0, oo) + + """ + + is_integer = True + is_finite = True + is_real = True + is_symbol = True + is_Atom = True + _diff_wrt = True + + def __new__(cls, label, range=None, **kw_args): + + if isinstance(label, str): + label = Symbol(label, integer=True) + label, range = list(map(sympify, (label, range))) + + if label.is_Number: + if not label.is_integer: + raise TypeError("Index is not an integer number.") + return label + + if not label.is_integer: + raise TypeError("Idx object requires an integer label.") + + elif is_sequence(range): + if len(range) != 2: + raise ValueError(filldedent(""" + Idx range tuple must have length 2, but got %s""" % len(range))) + for bound in range: + if (bound.is_integer is False and bound is not S.Infinity + and bound is not S.NegativeInfinity): + raise TypeError("Idx object requires integer bounds.") + args = label, Tuple(*range) + elif isinstance(range, Expr): + if range is not S.Infinity and fuzzy_not(range.is_integer): + raise TypeError("Idx object requires an integer dimension.") + args = label, Tuple(0, range - 1) + elif range: + raise TypeError(filldedent(""" + The range must be an ordered iterable or + integer SymPy expression.""")) + else: + args = label, + + obj = Expr.__new__(cls, *args, **kw_args) + obj._assumptions["finite"] = True + obj._assumptions["real"] = True + return obj + + @property + def label(self): + """Returns the label (Integer or integer expression) of the Idx object. + + Examples + ======== + + >>> from sympy import Idx, Symbol + >>> x = Symbol('x', integer=True) + >>> Idx(x).label + x + >>> j = Symbol('j', integer=True) + >>> Idx(j).label + j + >>> Idx(j + 1).label + j + 1 + + """ + return self.args[0] + + @property + def lower(self): + """Returns the lower bound of the ``Idx``. + + Examples + ======== + + >>> from sympy import Idx + >>> Idx('j', 2).lower + 0 + >>> Idx('j', 5).lower + 0 + >>> Idx('j').lower is None + True + + """ + try: + return self.args[1][0] + except IndexError: + return + + @property + def upper(self): + """Returns the upper bound of the ``Idx``. + + Examples + ======== + + >>> from sympy import Idx + >>> Idx('j', 2).upper + 1 + >>> Idx('j', 5).upper + 4 + >>> Idx('j').upper is None + True + + """ + try: + return self.args[1][1] + except IndexError: + return + + def _sympystr(self, p): + return p.doprint(self.label) + + @property + def name(self): + return self.label.name if self.label.is_Symbol else str(self.label) + + @property + def free_symbols(self): + return {self} + + +@dispatch(Idx, Idx) +def _eval_is_ge(lhs, rhs): # noqa:F811 + + other_upper = rhs if rhs.upper is None else rhs.upper + other_lower = rhs if rhs.lower is None else rhs.lower + + if lhs.lower is not None and (lhs.lower >= other_upper) == True: + return True + if lhs.upper is not None and (lhs.upper < other_lower) == True: + return False + return None + + +@dispatch(Idx, Number) # type:ignore +def _eval_is_ge(lhs, rhs): # noqa:F811 + + other_upper = rhs + other_lower = rhs + + if lhs.lower is not None and (lhs.lower >= other_upper) == True: + return True + if lhs.upper is not None and (lhs.upper < other_lower) == True: + return False + return None + + +@dispatch(Number, Idx) # type:ignore +def _eval_is_ge(lhs, rhs): # noqa:F811 + + other_upper = lhs + other_lower = lhs + + if rhs.upper is not None and (rhs.upper <= other_lower) == True: + return True + if rhs.lower is not None and (rhs.lower > other_upper) == True: + return False + return None diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/tensor.py b/.venv/lib/python3.12/site-packages/sympy/tensor/tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..579e7c7a86c2a1f18ab889af32ce0053a729ff5f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/tensor.py @@ -0,0 +1,5265 @@ +""" +This module defines tensors with abstract index notation. + +The abstract index notation has been first formalized by Penrose. + +Tensor indices are formal objects, with a tensor type; there is no +notion of index range, it is only possible to assign the dimension, +used to trace the Kronecker delta; the dimension can be a Symbol. + +The Einstein summation convention is used. +The covariant indices are indicated with a minus sign in front of the index. + +For instance the tensor ``t = p(a)*A(b,c)*q(-c)`` has the index ``c`` +contracted. + +A tensor expression ``t`` can be called; called with its +indices in sorted order it is equal to itself: +in the above example ``t(a, b) == t``; +one can call ``t`` with different indices; ``t(c, d) == p(c)*A(d,a)*q(-a)``. + +The contracted indices are dummy indices, internally they have no name, +the indices being represented by a graph-like structure. + +Tensors are put in canonical form using ``canon_bp``, which uses +the Butler-Portugal algorithm for canonicalization using the monoterm +symmetries of the tensors. + +If there is a (anti)symmetric metric, the indices can be raised and +lowered when the tensor is put in canonical form. +""" + +from __future__ import annotations +from typing import Any +from functools import reduce +from math import prod + +from abc import abstractmethod, ABC +from collections import defaultdict +import operator +import itertools + +from sympy.core.numbers import (Integer, Rational) +from sympy.combinatorics import Permutation +from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, \ + bsgs_direct_product, canonicalize, riemann_bsgs +from sympy.core import Basic, Expr, sympify, Add, Mul, S +from sympy.core.cache import clear_cache +from sympy.core.containers import Tuple, Dict +from sympy.core.function import WildFunction +from sympy.core.sorting import default_sort_key +from sympy.core.symbol import Symbol, symbols, Wild +from sympy.core.sympify import CantSympify, _sympify +from sympy.core.operations import AssocOp +from sympy.external.gmpy import SYMPY_INTS +from sympy.matrices import eye +from sympy.utilities.exceptions import (sympy_deprecation_warning, + SymPyDeprecationWarning, + ignore_warnings) +from sympy.utilities.decorator import memoize_property, deprecated +from sympy.utilities.iterables import sift + + +def deprecate_data(): + sympy_deprecation_warning( + """ + The data attribute of TensorIndexType is deprecated. Use The + replace_with_arrays() method instead. + """, + deprecated_since_version="1.4", + active_deprecations_target="deprecated-tensorindextype-attrs", + stacklevel=4, + ) + +def deprecate_fun_eval(): + sympy_deprecation_warning( + """ + The Tensor.fun_eval() method is deprecated. Use + Tensor.substitute_indices() instead. + """, + deprecated_since_version="1.5", + active_deprecations_target="deprecated-tensor-fun-eval", + stacklevel=4, + ) + + +def deprecate_call(): + sympy_deprecation_warning( + """ + Calling a tensor like Tensor(*indices) is deprecated. Use + Tensor.substitute_indices() instead. + """, + deprecated_since_version="1.5", + active_deprecations_target="deprecated-tensor-fun-eval", + stacklevel=4, + ) + + +class _IndexStructure(CantSympify): + """ + This class handles the indices (free and dummy ones). It contains the + algorithms to manage the dummy indices replacements and contractions of + free indices under multiplications of tensor expressions, as well as stuff + related to canonicalization sorting, getting the permutation of the + expression and so on. It also includes tools to get the ``TensorIndex`` + objects corresponding to the given index structure. + """ + + def __init__(self, free, dum, index_types, indices, canon_bp=False): + self.free = free + self.dum = dum + self.index_types = index_types + self.indices = indices + self._ext_rank = len(self.free) + 2*len(self.dum) + self.dum.sort(key=lambda x: x[0]) + + @staticmethod + def from_indices(*indices): + """ + Create a new ``_IndexStructure`` object from a list of ``indices``. + + Explanation + =========== + + ``indices`` ``TensorIndex`` objects, the indices. Contractions are + detected upon construction. + + Examples + ======== + + >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, _IndexStructure + >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') + >>> m0, m1, m2, m3 = tensor_indices('m0,m1,m2,m3', Lorentz) + >>> _IndexStructure.from_indices(m0, m1, -m1, m3) + _IndexStructure([(m0, 0), (m3, 3)], [(1, 2)], [Lorentz, Lorentz, Lorentz, Lorentz]) + """ + + free, dum = _IndexStructure._free_dum_from_indices(*indices) + index_types = [i.tensor_index_type for i in indices] + indices = _IndexStructure._replace_dummy_names(indices, free, dum) + return _IndexStructure(free, dum, index_types, indices) + + @staticmethod + def from_components_free_dum(components, free, dum): + index_types = [] + for component in components: + index_types.extend(component.index_types) + indices = _IndexStructure.generate_indices_from_free_dum_index_types(free, dum, index_types) + return _IndexStructure(free, dum, index_types, indices) + + @staticmethod + def _free_dum_from_indices(*indices): + """ + Convert ``indices`` into ``free``, ``dum`` for single component tensor. + + Explanation + =========== + + ``free`` list of tuples ``(index, pos, 0)``, + where ``pos`` is the position of index in + the list of indices formed by the component tensors + + ``dum`` list of tuples ``(pos_contr, pos_cov, 0, 0)`` + + Examples + ======== + + >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, \ + _IndexStructure + >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') + >>> m0, m1, m2, m3 = tensor_indices('m0,m1,m2,m3', Lorentz) + >>> _IndexStructure._free_dum_from_indices(m0, m1, -m1, m3) + ([(m0, 0), (m3, 3)], [(1, 2)]) + """ + n = len(indices) + if n == 1: + return [(indices[0], 0)], [] + + # find the positions of the free indices and of the dummy indices + free = [True]*len(indices) + index_dict = {} + dum = [] + for i, index in enumerate(indices): + name = index.name + typ = index.tensor_index_type + contr = index.is_up + if (name, typ) in index_dict: + # found a pair of dummy indices + is_contr, pos = index_dict[(name, typ)] + # check consistency and update free + if is_contr: + if contr: + raise ValueError('two equal contravariant indices in slots %d and %d' %(pos, i)) + else: + free[pos] = False + free[i] = False + else: + if contr: + free[pos] = False + free[i] = False + else: + raise ValueError('two equal covariant indices in slots %d and %d' %(pos, i)) + if contr: + dum.append((i, pos)) + else: + dum.append((pos, i)) + else: + index_dict[(name, typ)] = index.is_up, i + + free = [(index, i) for i, index in enumerate(indices) if free[i]] + free.sort() + return free, dum + + def get_indices(self): + """ + Get a list of indices, creating new tensor indices to complete dummy indices. + """ + return self.indices[:] + + @staticmethod + def generate_indices_from_free_dum_index_types(free, dum, index_types): + indices = [None]*(len(free)+2*len(dum)) + for idx, pos in free: + indices[pos] = idx + + generate_dummy_name = _IndexStructure._get_generator_for_dummy_indices(free) + for pos1, pos2 in dum: + typ1 = index_types[pos1] + indname = generate_dummy_name(typ1) + indices[pos1] = TensorIndex(indname, typ1, True) + indices[pos2] = TensorIndex(indname, typ1, False) + + return _IndexStructure._replace_dummy_names(indices, free, dum) + + @staticmethod + def _get_generator_for_dummy_indices(free): + cdt = defaultdict(int) + # if the free indices have names with dummy_name, start with an + # index higher than those for the dummy indices + # to avoid name collisions + for indx, ipos in free: + if indx.name.split('_')[0] == indx.tensor_index_type.dummy_name: + cdt[indx.tensor_index_type] = max(cdt[indx.tensor_index_type], int(indx.name.split('_')[1]) + 1) + + def dummy_name_gen(tensor_index_type): + nd = str(cdt[tensor_index_type]) + cdt[tensor_index_type] += 1 + return tensor_index_type.dummy_name + '_' + nd + + return dummy_name_gen + + @staticmethod + def _replace_dummy_names(indices, free, dum): + dum.sort(key=lambda x: x[0]) + new_indices = list(indices) + assert len(indices) == len(free) + 2*len(dum) + generate_dummy_name = _IndexStructure._get_generator_for_dummy_indices(free) + for ipos1, ipos2 in dum: + typ1 = new_indices[ipos1].tensor_index_type + indname = generate_dummy_name(typ1) + new_indices[ipos1] = TensorIndex(indname, typ1, True) + new_indices[ipos2] = TensorIndex(indname, typ1, False) + return new_indices + + def get_free_indices(self) -> list[TensorIndex]: + """ + Get a list of free indices. + """ + # get sorted indices according to their position: + free = sorted(self.free, key=lambda x: x[1]) + return [i[0] for i in free] + + def __str__(self): + return "_IndexStructure({}, {}, {})".format(self.free, self.dum, self.index_types) + + def __repr__(self): + return self.__str__() + + def _get_sorted_free_indices_for_canon(self): + sorted_free = self.free[:] + sorted_free.sort(key=lambda x: x[0]) + return sorted_free + + def _get_sorted_dum_indices_for_canon(self): + return sorted(self.dum, key=lambda x: x[0]) + + def _get_lexicographically_sorted_index_types(self): + permutation = self.indices_canon_args()[0] + index_types = [None]*self._ext_rank + for i, it in enumerate(self.index_types): + index_types[permutation(i)] = it + return index_types + + def _get_lexicographically_sorted_indices(self): + permutation = self.indices_canon_args()[0] + indices = [None]*self._ext_rank + for i, it in enumerate(self.indices): + indices[permutation(i)] = it + return indices + + def perm2tensor(self, g, is_canon_bp=False): + """ + Returns a ``_IndexStructure`` instance corresponding to the permutation ``g``. + + Explanation + =========== + + ``g`` permutation corresponding to the tensor in the representation + used in canonicalization + + ``is_canon_bp`` if True, then ``g`` is the permutation + corresponding to the canonical form of the tensor + """ + sorted_free = [i[0] for i in self._get_sorted_free_indices_for_canon()] + lex_index_types = self._get_lexicographically_sorted_index_types() + lex_indices = self._get_lexicographically_sorted_indices() + nfree = len(sorted_free) + rank = self._ext_rank + dum = [[None]*2 for i in range((rank - nfree)//2)] + free = [] + + index_types = [None]*rank + indices = [None]*rank + for i in range(rank): + gi = g[i] + index_types[i] = lex_index_types[gi] + indices[i] = lex_indices[gi] + if gi < nfree: + ind = sorted_free[gi] + assert index_types[i] == sorted_free[gi].tensor_index_type + free.append((ind, i)) + else: + j = gi - nfree + idum, cov = divmod(j, 2) + if cov: + dum[idum][1] = i + else: + dum[idum][0] = i + dum = [tuple(x) for x in dum] + + return _IndexStructure(free, dum, index_types, indices) + + def indices_canon_args(self): + """ + Returns ``(g, dummies, msym, v)``, the entries of ``canonicalize`` + + See ``canonicalize`` in ``tensor_can.py`` in combinatorics module. + """ + # to be called after sorted_components + from sympy.combinatorics.permutations import _af_new + n = self._ext_rank + g = [None]*n + [n, n+1] + + # Converts the symmetry of the metric into msym from .canonicalize() + # method in the combinatorics module + def metric_symmetry_to_msym(metric): + if metric is None: + return None + sym = metric.symmetry + if sym == TensorSymmetry.fully_symmetric(2): + return 0 + if sym == TensorSymmetry.fully_symmetric(-2): + return 1 + return None + + # ordered indices: first the free indices, ordered by types + # then the dummy indices, ordered by types and contravariant before + # covariant + # g[position in tensor] = position in ordered indices + for i, (indx, ipos) in enumerate(self._get_sorted_free_indices_for_canon()): + g[ipos] = i + pos = len(self.free) + j = len(self.free) + dummies = [] + prev = None + a = [] + msym = [] + for ipos1, ipos2 in self._get_sorted_dum_indices_for_canon(): + g[ipos1] = j + g[ipos2] = j + 1 + j += 2 + typ = self.index_types[ipos1] + if typ != prev: + if a: + dummies.append(a) + a = [pos, pos + 1] + prev = typ + msym.append(metric_symmetry_to_msym(typ.metric)) + else: + a.extend([pos, pos + 1]) + pos += 2 + if a: + dummies.append(a) + + return _af_new(g), dummies, msym + + +def components_canon_args(components): + numtyp = [] + prev = None + for t in components: + if t == prev: + numtyp[-1][1] += 1 + else: + prev = t + numtyp.append([prev, 1]) + v = [] + for h, n in numtyp: + if h.comm in (0, 1): + comm = h.comm + else: + comm = TensorManager.get_comm(h.comm, h.comm) + v.append((h.symmetry.base, h.symmetry.generators, n, comm)) + return v + + +class _TensorDataLazyEvaluator(CantSympify): + """ + EXPERIMENTAL: do not rely on this class, it may change without deprecation + warnings in future versions of SymPy. + + Explanation + =========== + + This object contains the logic to associate components data to a tensor + expression. Components data are set via the ``.data`` property of tensor + expressions, is stored inside this class as a mapping between the tensor + expression and the ``ndarray``. + + Computations are executed lazily: whereas the tensor expressions can have + contractions, tensor products, and additions, components data are not + computed until they are accessed by reading the ``.data`` property + associated to the tensor expression. + """ + _substitutions_dict: dict[Any, Any] = {} + _substitutions_dict_tensmul: dict[Any, Any] = {} + + def __getitem__(self, key): + dat = self._get(key) + if dat is None: + return None + + from .array import NDimArray + if not isinstance(dat, NDimArray): + return dat + + if dat.rank() == 0: + return dat[()] + elif dat.rank() == 1 and len(dat) == 1: + return dat[0] + return dat + + def _get(self, key): + """ + Retrieve ``data`` associated with ``key``. + + Explanation + =========== + + This algorithm looks into ``self._substitutions_dict`` for all + ``TensorHead`` in the ``TensExpr`` (or just ``TensorHead`` if key is a + TensorHead instance). It reconstructs the components data that the + tensor expression should have by performing on components data the + operations that correspond to the abstract tensor operations applied. + + Metric tensor is handled in a different manner: it is pre-computed in + ``self._substitutions_dict_tensmul``. + """ + if key in self._substitutions_dict: + return self._substitutions_dict[key] + + if isinstance(key, TensorHead): + return None + + if isinstance(key, Tensor): + # special case to handle metrics. Metric tensors cannot be + # constructed through contraction by the metric, their + # components show if they are a matrix or its inverse. + signature = tuple([i.is_up for i in key.get_indices()]) + srch = (key.component,) + signature + if srch in self._substitutions_dict_tensmul: + return self._substitutions_dict_tensmul[srch] + array_list = [self.data_from_tensor(key)] + return self.data_contract_dum(array_list, key.dum, key.ext_rank) + + if isinstance(key, TensMul): + tensmul_args = key.args + if len(tensmul_args) == 1 and len(tensmul_args[0].components) == 1: + # special case to handle metrics. Metric tensors cannot be + # constructed through contraction by the metric, their + # components show if they are a matrix or its inverse. + signature = tuple([i.is_up for i in tensmul_args[0].get_indices()]) + srch = (tensmul_args[0].components[0],) + signature + if srch in self._substitutions_dict_tensmul: + return self._substitutions_dict_tensmul[srch] + #data_list = [self.data_from_tensor(i) for i in tensmul_args if isinstance(i, TensExpr)] + data_list = [self.data_from_tensor(i) if isinstance(i, Tensor) else i.data for i in tensmul_args if isinstance(i, TensExpr)] + coeff = prod([i for i in tensmul_args if not isinstance(i, TensExpr)]) + if all(i is None for i in data_list): + return None + if any(i is None for i in data_list): + raise ValueError("Mixing tensors with associated components "\ + "data with tensors without components data") + data_result = self.data_contract_dum(data_list, key.dum, key.ext_rank) + return coeff*data_result + + if isinstance(key, TensAdd): + data_list = [] + free_args_list = [] + for arg in key.args: + if isinstance(arg, TensExpr): + data_list.append(arg.data) + free_args_list.append([x[0] for x in arg.free]) + else: + data_list.append(arg) + free_args_list.append([]) + if all(i is None for i in data_list): + return None + if any(i is None for i in data_list): + raise ValueError("Mixing tensors with associated components "\ + "data with tensors without components data") + + sum_list = [] + from .array import permutedims + for data, free_args in zip(data_list, free_args_list): + if len(free_args) < 2: + sum_list.append(data) + else: + free_args_pos = {y: x for x, y in enumerate(free_args)} + axes = [free_args_pos[arg] for arg in key.free_args] + sum_list.append(permutedims(data, axes)) + return reduce(lambda x, y: x+y, sum_list) + + return None + + @staticmethod + def data_contract_dum(ndarray_list, dum, ext_rank): + from .array import tensorproduct, tensorcontraction, MutableDenseNDimArray + arrays = list(map(MutableDenseNDimArray, ndarray_list)) + prodarr = tensorproduct(*arrays) + return tensorcontraction(prodarr, *dum) + + def data_tensorhead_from_tensmul(self, data, tensmul, tensorhead): + """ + This method is used when assigning components data to a ``TensMul`` + object, it converts components data to a fully contravariant ndarray, + which is then stored according to the ``TensorHead`` key. + """ + if data is None: + return None + + return self._correct_signature_from_indices( + data, + tensmul.get_indices(), + tensmul.free, + tensmul.dum, + True) + + def data_from_tensor(self, tensor): + """ + This method corrects the components data to the right signature + (covariant/contravariant) using the metric associated with each + ``TensorIndexType``. + """ + tensorhead = tensor.component + + if tensorhead.data is None: + return None + + return self._correct_signature_from_indices( + tensorhead.data, + tensor.get_indices(), + tensor.free, + tensor.dum) + + def _assign_data_to_tensor_expr(self, key, data): + if isinstance(key, TensAdd): + raise ValueError('cannot assign data to TensAdd') + # here it is assumed that `key` is a `TensMul` instance. + if len(key.components) != 1: + raise ValueError('cannot assign data to TensMul with multiple components') + tensorhead = key.components[0] + newdata = self.data_tensorhead_from_tensmul(data, key, tensorhead) + return tensorhead, newdata + + def _check_permutations_on_data(self, tens, data): + from .array import permutedims + from .array.arrayop import Flatten + + if isinstance(tens, TensorHead): + rank = tens.rank + generators = tens.symmetry.generators + elif isinstance(tens, Tensor): + rank = tens.rank + generators = tens.components[0].symmetry.generators + elif isinstance(tens, TensorIndexType): + rank = tens.metric.rank + generators = tens.metric.symmetry.generators + + # Every generator is a permutation, check that by permuting the array + # by that permutation, the array will be the same, except for a + # possible sign change if the permutation admits it. + for gener in generators: + sign_change = +1 if (gener(rank) == rank) else -1 + data_swapped = data + last_data = data + permute_axes = list(map(gener, range(rank))) + # the order of a permutation is the number of times to get the + # identity by applying that permutation. + for i in range(gener.order()-1): + data_swapped = permutedims(data_swapped, permute_axes) + # if any value in the difference array is non-zero, raise an error: + if any(Flatten(last_data - sign_change*data_swapped)): + raise ValueError("Component data symmetry structure error") + last_data = data_swapped + + def __setitem__(self, key, value): + """ + Set the components data of a tensor object/expression. + + Explanation + =========== + + Components data are transformed to the all-contravariant form and stored + with the corresponding ``TensorHead`` object. If a ``TensorHead`` object + cannot be uniquely identified, it will raise an error. + """ + data = _TensorDataLazyEvaluator.parse_data(value) + self._check_permutations_on_data(key, data) + + # TensorHead and TensorIndexType can be assigned data directly, while + # TensMul must first convert data to a fully contravariant form, and + # assign it to its corresponding TensorHead single component. + if not isinstance(key, (TensorHead, TensorIndexType)): + key, data = self._assign_data_to_tensor_expr(key, data) + + if isinstance(key, TensorHead): + for dim, indextype in zip(data.shape, key.index_types): + if indextype.data is None: + raise ValueError("index type {} has no components data"\ + " associated (needed to raise/lower index)".format(indextype)) + if not indextype.dim.is_number: + continue + if dim != indextype.dim: + raise ValueError("wrong dimension of ndarray") + self._substitutions_dict[key] = data + + def __delitem__(self, key): + del self._substitutions_dict[key] + + def __contains__(self, key): + return key in self._substitutions_dict + + def add_metric_data(self, metric, data): + """ + Assign data to the ``metric`` tensor. The metric tensor behaves in an + anomalous way when raising and lowering indices. + + Explanation + =========== + + A fully covariant metric is the inverse transpose of the fully + contravariant metric (it is meant matrix inverse). If the metric is + symmetric, the transpose is not necessary and mixed + covariant/contravariant metrics are Kronecker deltas. + """ + # hard assignment, data should not be added to `TensorHead` for metric: + # the problem with `TensorHead` is that the metric is anomalous, i.e. + # raising and lowering the index means considering the metric or its + # inverse, this is not the case for other tensors. + self._substitutions_dict_tensmul[metric, True, True] = data + inverse_transpose = self.inverse_transpose_matrix(data) + # in symmetric spaces, the transpose is the same as the original matrix, + # the full covariant metric tensor is the inverse transpose, so this + # code will be able to handle non-symmetric metrics. + self._substitutions_dict_tensmul[metric, False, False] = inverse_transpose + # now mixed cases, these are identical to the unit matrix if the metric + # is symmetric. + m = data.tomatrix() + invt = inverse_transpose.tomatrix() + self._substitutions_dict_tensmul[metric, True, False] = m * invt + self._substitutions_dict_tensmul[metric, False, True] = invt * m + + @staticmethod + def _flip_index_by_metric(data, metric, pos): + from .array import tensorproduct, tensorcontraction + + mdim = metric.rank() + ddim = data.rank() + + if pos == 0: + data = tensorcontraction( + tensorproduct( + metric, + data + ), + (1, mdim+pos) + ) + else: + data = tensorcontraction( + tensorproduct( + data, + metric + ), + (pos, ddim) + ) + return data + + @staticmethod + def inverse_matrix(ndarray): + m = ndarray.tomatrix().inv() + return _TensorDataLazyEvaluator.parse_data(m) + + @staticmethod + def inverse_transpose_matrix(ndarray): + m = ndarray.tomatrix().inv().T + return _TensorDataLazyEvaluator.parse_data(m) + + @staticmethod + def _correct_signature_from_indices(data, indices, free, dum, inverse=False): + """ + Utility function to correct the values inside the components data + ndarray according to whether indices are covariant or contravariant. + + It uses the metric matrix to lower values of covariant indices. + """ + # change the ndarray values according covariantness/contravariantness of the indices + # use the metric + for i, indx in enumerate(indices): + if not indx.is_up and not inverse: + data = _TensorDataLazyEvaluator._flip_index_by_metric(data, indx.tensor_index_type.data, i) + elif not indx.is_up and inverse: + data = _TensorDataLazyEvaluator._flip_index_by_metric( + data, + _TensorDataLazyEvaluator.inverse_matrix(indx.tensor_index_type.data), + i + ) + return data + + @staticmethod + def _sort_data_axes(old, new): + from .array import permutedims + + new_data = old.data.copy() + + old_free = [i[0] for i in old.free] + new_free = [i[0] for i in new.free] + + for i in range(len(new_free)): + for j in range(i, len(old_free)): + if old_free[j] == new_free[i]: + old_free[i], old_free[j] = old_free[j], old_free[i] + new_data = permutedims(new_data, (i, j)) + break + return new_data + + @staticmethod + def add_rearrange_tensmul_parts(new_tensmul, old_tensmul): + def sorted_compo(): + return _TensorDataLazyEvaluator._sort_data_axes(old_tensmul, new_tensmul) + + _TensorDataLazyEvaluator._substitutions_dict[new_tensmul] = sorted_compo() + + @staticmethod + def parse_data(data): + """ + Transform ``data`` to array. The parameter ``data`` may + contain data in various formats, e.g. nested lists, SymPy ``Matrix``, + and so on. + + Examples + ======== + + >>> from sympy.tensor.tensor import _TensorDataLazyEvaluator + >>> _TensorDataLazyEvaluator.parse_data([1, 3, -6, 12]) + [1, 3, -6, 12] + + >>> _TensorDataLazyEvaluator.parse_data([[1, 2], [4, 7]]) + [[1, 2], [4, 7]] + """ + from .array import MutableDenseNDimArray + + if not isinstance(data, MutableDenseNDimArray): + if len(data) == 2 and hasattr(data[0], '__call__'): + data = MutableDenseNDimArray(data[0], data[1]) + else: + data = MutableDenseNDimArray(data) + return data + +_tensor_data_substitution_dict = _TensorDataLazyEvaluator() + + +class _TensorManager: + """ + Class to manage tensor properties. + + Notes + ===== + + Tensors belong to tensor commutation groups; each group has a label + ``comm``; there are predefined labels: + + ``0`` tensors commuting with any other tensor + + ``1`` tensors anticommuting among themselves + + ``2`` tensors not commuting, apart with those with ``comm=0`` + + Other groups can be defined using ``set_comm``; tensors in those + groups commute with those with ``comm=0``; by default they + do not commute with any other group. + """ + def __init__(self): + self._comm_init() + + def _comm_init(self): + self._comm = [{} for i in range(3)] + for i in range(3): + self._comm[0][i] = 0 + self._comm[i][0] = 0 + self._comm[1][1] = 1 + self._comm[2][1] = None + self._comm[1][2] = None + self._comm_symbols2i = {0:0, 1:1, 2:2} + self._comm_i2symbol = {0:0, 1:1, 2:2} + + @property + def comm(self): + return self._comm + + def comm_symbols2i(self, i): + """ + Get the commutation group number corresponding to ``i``. + + ``i`` can be a symbol or a number or a string. + + If ``i`` is not already defined its commutation group number + is set. + """ + if i not in self._comm_symbols2i: + n = len(self._comm) + self._comm.append({}) + self._comm[n][0] = 0 + self._comm[0][n] = 0 + self._comm_symbols2i[i] = n + self._comm_i2symbol[n] = i + return n + return self._comm_symbols2i[i] + + def comm_i2symbol(self, i): + """ + Returns the symbol corresponding to the commutation group number. + """ + return self._comm_i2symbol[i] + + def set_comm(self, i, j, c): + """ + Set the commutation parameter ``c`` for commutation groups ``i, j``. + + Parameters + ========== + + i, j : symbols representing commutation groups + + c : group commutation number + + Notes + ===== + + ``i, j`` can be symbols, strings or numbers, + apart from ``0, 1`` and ``2`` which are reserved respectively + for commuting, anticommuting tensors and tensors not commuting + with any other group apart with the commuting tensors. + For the remaining cases, use this method to set the commutation rules; + by default ``c=None``. + + The group commutation number ``c`` is assigned in correspondence + to the group commutation symbols; it can be + + 0 commuting + + 1 anticommuting + + None no commutation property + + Examples + ======== + + ``G`` and ``GH`` do not commute with themselves and commute with + each other; A is commuting. + + >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, TensorManager, TensorSymmetry + >>> Lorentz = TensorIndexType('Lorentz') + >>> i0,i1,i2,i3,i4 = tensor_indices('i0:5', Lorentz) + >>> A = TensorHead('A', [Lorentz]) + >>> G = TensorHead('G', [Lorentz], TensorSymmetry.no_symmetry(1), 'Gcomm') + >>> GH = TensorHead('GH', [Lorentz], TensorSymmetry.no_symmetry(1), 'GHcomm') + >>> TensorManager.set_comm('Gcomm', 'GHcomm', 0) + >>> (GH(i1)*G(i0)).canon_bp() + G(i0)*GH(i1) + >>> (G(i1)*G(i0)).canon_bp() + G(i1)*G(i0) + >>> (G(i1)*A(i0)).canon_bp() + A(i0)*G(i1) + """ + if c not in (0, 1, None): + raise ValueError('`c` can assume only the values 0, 1 or None') + + i = sympify(i) + j = sympify(j) + + if i not in self._comm_symbols2i: + n = len(self._comm) + self._comm.append({}) + self._comm[n][0] = 0 + self._comm[0][n] = 0 + self._comm_symbols2i[i] = n + self._comm_i2symbol[n] = i + if j not in self._comm_symbols2i: + n = len(self._comm) + self._comm.append({}) + self._comm[0][n] = 0 + self._comm[n][0] = 0 + self._comm_symbols2i[j] = n + self._comm_i2symbol[n] = j + ni = self._comm_symbols2i[i] + nj = self._comm_symbols2i[j] + self._comm[ni][nj] = c + self._comm[nj][ni] = c + + """ + Cached sympy functions (e.g. expand) may have cached the results of + expressions involving tensors, but those results may not be valid after + changing the commutation properties. To stay on the safe side, we clear + the cache of all functions. + """ + clear_cache() + + def set_comms(self, *args): + """ + Set the commutation group numbers ``c`` for symbols ``i, j``. + + Parameters + ========== + + args : sequence of ``(i, j, c)`` + """ + for i, j, c in args: + self.set_comm(i, j, c) + + def get_comm(self, i, j): + """ + Return the commutation parameter for commutation group numbers ``i, j`` + + see ``_TensorManager.set_comm`` + """ + return self._comm[i].get(j, 0 if i == 0 or j == 0 else None) + + def clear(self): + """ + Clear the TensorManager. + """ + self._comm_init() + + +TensorManager = _TensorManager() + + +class TensorIndexType(Basic): + """ + A TensorIndexType is characterized by its name and its metric. + + Parameters + ========== + + name : name of the tensor type + dummy_name : name of the head of dummy indices + dim : dimension, it can be a symbol or an integer or ``None`` + eps_dim : dimension of the epsilon tensor + metric_symmetry : integer that denotes metric symmetry or ``None`` for no metric + metric_name : string with the name of the metric tensor + + Attributes + ========== + + ``metric`` : the metric tensor + ``delta`` : ``Kronecker delta`` + ``epsilon`` : the ``Levi-Civita epsilon`` tensor + ``data`` : (deprecated) a property to add ``ndarray`` values, to work in a specified basis. + + Notes + ===== + + The possible values of the ``metric_symmetry`` parameter are: + + ``1`` : metric tensor is fully symmetric + ``0`` : metric tensor possesses no index symmetry + ``-1`` : metric tensor is fully antisymmetric + ``None``: there is no metric tensor (metric equals to ``None``) + + The metric is assumed to be symmetric by default. It can also be set + to a custom tensor by the ``.set_metric()`` method. + + If there is a metric the metric is used to raise and lower indices. + + In the case of non-symmetric metric, the following raising and + lowering conventions will be adopted: + + ``psi(a) = g(a, b)*psi(-b); chi(-a) = chi(b)*g(-b, -a)`` + + From these it is easy to find: + + ``g(-a, b) = delta(-a, b)`` + + where ``delta(-a, b) = delta(b, -a)`` is the ``Kronecker delta`` + (see ``TensorIndex`` for the conventions on indices). + For antisymmetric metrics there is also the following equality: + + ``g(a, -b) = -delta(a, -b)`` + + If there is no metric it is not possible to raise or lower indices; + e.g. the index of the defining representation of ``SU(N)`` + is 'covariant' and the conjugate representation is + 'contravariant'; for ``N > 2`` they are linearly independent. + + ``eps_dim`` is by default equal to ``dim``, if the latter is an integer; + else it can be assigned (for use in naive dimensional regularization); + if ``eps_dim`` is not an integer ``epsilon`` is ``None``. + + Examples + ======== + + >>> from sympy.tensor.tensor import TensorIndexType + >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') + >>> Lorentz.metric + metric(Lorentz,Lorentz) + """ + + def __new__(cls, name, dummy_name=None, dim=None, eps_dim=None, + metric_symmetry=1, metric_name='metric', **kwargs): + if 'dummy_fmt' in kwargs: + dummy_fmt = kwargs['dummy_fmt'] + sympy_deprecation_warning( + f""" + The dummy_fmt keyword to TensorIndexType is deprecated. Use + dummy_name={dummy_fmt} instead. + """, + deprecated_since_version="1.5", + active_deprecations_target="deprecated-tensorindextype-dummy-fmt", + ) + dummy_name = dummy_fmt + + if isinstance(name, str): + name = Symbol(name) + + if dummy_name is None: + dummy_name = str(name)[0] + if isinstance(dummy_name, str): + dummy_name = Symbol(dummy_name) + + if dim is None: + dim = Symbol("dim_" + dummy_name.name) + else: + dim = sympify(dim) + + if eps_dim is None: + eps_dim = dim + else: + eps_dim = sympify(eps_dim) + + metric_symmetry = sympify(metric_symmetry) + + if isinstance(metric_name, str): + metric_name = Symbol(metric_name) + + if 'metric' in kwargs: + SymPyDeprecationWarning( + """ + The 'metric' keyword argument to TensorIndexType is + deprecated. Use the 'metric_symmetry' keyword argument or the + TensorIndexType.set_metric() method instead. + """, + deprecated_since_version="1.5", + active_deprecations_target="deprecated-tensorindextype-metric", + ) + metric = kwargs.get('metric') + if metric is not None: + if metric in (True, False, 0, 1): + metric_name = 'metric' + #metric_antisym = metric + else: + metric_name = metric.name + #metric_antisym = metric.antisym + + if metric: + metric_symmetry = -1 + else: + metric_symmetry = 1 + + obj = Basic.__new__(cls, name, dummy_name, dim, eps_dim, + metric_symmetry, metric_name) + + obj._autogenerated = [] + return obj + + @property + def name(self): + return self.args[0].name + + @property + def dummy_name(self): + return self.args[1].name + + @property + def dim(self): + return self.args[2] + + @property + def eps_dim(self): + return self.args[3] + + @memoize_property + def metric(self): + metric_symmetry = self.args[4] + metric_name = self.args[5] + if metric_symmetry is None: + return None + + if metric_symmetry == 0: + symmetry = TensorSymmetry.no_symmetry(2) + elif metric_symmetry == 1: + symmetry = TensorSymmetry.fully_symmetric(2) + elif metric_symmetry == -1: + symmetry = TensorSymmetry.fully_symmetric(-2) + + return TensorHead(metric_name, [self]*2, symmetry) + + @memoize_property + def delta(self): + return TensorHead('KD', [self]*2, TensorSymmetry.fully_symmetric(2)) + + @memoize_property + def epsilon(self): + if not isinstance(self.eps_dim, (SYMPY_INTS, Integer)): + return None + symmetry = TensorSymmetry.fully_symmetric(-self.eps_dim) + return TensorHead('Eps', [self]*self.eps_dim, symmetry) + + def set_metric(self, tensor): + self._metric = tensor + + def __lt__(self, other): + return self.name < other.name + + def __str__(self): + return self.name + + __repr__ = __str__ + + # Everything below this line is deprecated + + @property + def data(self): + deprecate_data() + with ignore_warnings(SymPyDeprecationWarning): + return _tensor_data_substitution_dict[self] + + @data.setter + def data(self, data): + deprecate_data() + # This assignment is a bit controversial, should metric components be assigned + # to the metric only or also to the TensorIndexType object? The advantage here + # is the ability to assign a 1D array and transform it to a 2D diagonal array. + from .array import MutableDenseNDimArray + + data = _TensorDataLazyEvaluator.parse_data(data) + if data.rank() > 2: + raise ValueError("data have to be of rank 1 (diagonal metric) or 2.") + if data.rank() == 1: + if self.dim.is_number: + nda_dim = data.shape[0] + if nda_dim != self.dim: + raise ValueError("Dimension mismatch") + + dim = data.shape[0] + newndarray = MutableDenseNDimArray.zeros(dim, dim) + for i, val in enumerate(data): + newndarray[i, i] = val + data = newndarray + dim1, dim2 = data.shape + if dim1 != dim2: + raise ValueError("Non-square matrix tensor.") + if self.dim.is_number: + if self.dim != dim1: + raise ValueError("Dimension mismatch") + _tensor_data_substitution_dict[self] = data + _tensor_data_substitution_dict.add_metric_data(self.metric, data) + with ignore_warnings(SymPyDeprecationWarning): + delta = self.get_kronecker_delta() + i1 = TensorIndex('i1', self) + i2 = TensorIndex('i2', self) + with ignore_warnings(SymPyDeprecationWarning): + delta(i1, -i2).data = _TensorDataLazyEvaluator.parse_data(eye(dim1)) + + @data.deleter + def data(self): + deprecate_data() + with ignore_warnings(SymPyDeprecationWarning): + if self in _tensor_data_substitution_dict: + del _tensor_data_substitution_dict[self] + if self.metric in _tensor_data_substitution_dict: + del _tensor_data_substitution_dict[self.metric] + + @deprecated( + """ + The TensorIndexType.get_kronecker_delta() method is deprecated. Use + the TensorIndexType.delta attribute instead. + """, + deprecated_since_version="1.5", + active_deprecations_target="deprecated-tensorindextype-methods", + ) + def get_kronecker_delta(self): + sym2 = TensorSymmetry(get_symmetric_group_sgs(2)) + delta = TensorHead('KD', [self]*2, sym2) + return delta + + @deprecated( + """ + The TensorIndexType.get_epsilon() method is deprecated. Use + the TensorIndexType.epsilon attribute instead. + """, + deprecated_since_version="1.5", + active_deprecations_target="deprecated-tensorindextype-methods", + ) + def get_epsilon(self): + if not isinstance(self._eps_dim, (SYMPY_INTS, Integer)): + return None + sym = TensorSymmetry(get_symmetric_group_sgs(self._eps_dim, 1)) + epsilon = TensorHead('Eps', [self]*self._eps_dim, sym) + return epsilon + + def _components_data_full_destroy(self): + """ + EXPERIMENTAL: do not rely on this API method. + + This destroys components data associated to the ``TensorIndexType``, if + any, specifically: + + * metric tensor data + * Kronecker tensor data + """ + if self in _tensor_data_substitution_dict: + del _tensor_data_substitution_dict[self] + + def delete_tensmul_data(key): + if key in _tensor_data_substitution_dict._substitutions_dict_tensmul: + del _tensor_data_substitution_dict._substitutions_dict_tensmul[key] + + # delete metric data: + delete_tensmul_data((self.metric, True, True)) + delete_tensmul_data((self.metric, True, False)) + delete_tensmul_data((self.metric, False, True)) + delete_tensmul_data((self.metric, False, False)) + + # delete delta tensor data: + delta = self.get_kronecker_delta() + if delta in _tensor_data_substitution_dict: + del _tensor_data_substitution_dict[delta] + + +class TensorIndex(Basic): + """ + Represents a tensor index + + Parameters + ========== + + name : name of the index, or ``True`` if you want it to be automatically assigned + tensor_index_type : ``TensorIndexType`` of the index + is_up : flag for contravariant index (is_up=True by default) + + Attributes + ========== + + ``name`` + ``tensor_index_type`` + ``is_up`` + + Notes + ===== + + Tensor indices are contracted with the Einstein summation convention. + + An index can be in contravariant or in covariant form; in the latter + case it is represented prepending a ``-`` to the index name. Adding + ``-`` to a covariant (is_up=False) index makes it contravariant. + + Dummy indices have a name with head given by + ``tensor_inde_type.dummy_name`` with underscore and a number. + + Similar to ``symbols`` multiple contravariant indices can be created + at once using ``tensor_indices(s, typ)``, where ``s`` is a string + of names. + + + Examples + ======== + + >>> from sympy.tensor.tensor import TensorIndexType, TensorIndex, TensorHead, tensor_indices + >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') + >>> mu = TensorIndex('mu', Lorentz, is_up=False) + >>> nu, rho = tensor_indices('nu, rho', Lorentz) + >>> A = TensorHead('A', [Lorentz, Lorentz]) + >>> A(mu, nu) + A(-mu, nu) + >>> A(-mu, -rho) + A(mu, -rho) + >>> A(mu, -mu) + A(-L_0, L_0) + """ + def __new__(cls, name, tensor_index_type, is_up=True): + if isinstance(name, str): + name_symbol = Symbol(name) + elif isinstance(name, Symbol): + name_symbol = name + elif name is True: + name = "_i{}".format(len(tensor_index_type._autogenerated)) + name_symbol = Symbol(name) + tensor_index_type._autogenerated.append(name_symbol) + else: + raise ValueError("invalid name") + + is_up = sympify(is_up) + return Basic.__new__(cls, name_symbol, tensor_index_type, is_up) + + @property + def name(self): + return self.args[0].name + + @property + def tensor_index_type(self): + return self.args[1] + + @property + def is_up(self): + return self.args[2] + + def _print(self): + s = self.name + if not self.is_up: + s = '-%s' % s + return s + + def __lt__(self, other): + return ((self.tensor_index_type, self.name) < + (other.tensor_index_type, other.name)) + + def __neg__(self): + t1 = TensorIndex(self.name, self.tensor_index_type, + (not self.is_up)) + return t1 + + +def tensor_indices(s, typ): + """ + Returns list of tensor indices given their names and their types. + + Parameters + ========== + + s : string of comma separated names of indices + + typ : ``TensorIndexType`` of the indices + + Examples + ======== + + >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices + >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') + >>> a, b, c, d = tensor_indices('a,b,c,d', Lorentz) + """ + if isinstance(s, str): + a = [x.name for x in symbols(s, seq=True)] + else: + raise ValueError('expecting a string') + + tilist = [TensorIndex(i, typ) for i in a] + if len(tilist) == 1: + return tilist[0] + return tilist + + +class TensorSymmetry(Basic): + """ + Monoterm symmetry of a tensor (i.e. any symmetric or anti-symmetric + index permutation). For the relevant terminology see ``tensor_can.py`` + section of the combinatorics module. + + Parameters + ========== + + bsgs : tuple ``(base, sgs)`` BSGS of the symmetry of the tensor + + Attributes + ========== + + ``base`` : base of the BSGS + ``generators`` : generators of the BSGS + ``rank`` : rank of the tensor + + Notes + ===== + + A tensor can have an arbitrary monoterm symmetry provided by its BSGS. + Multiterm symmetries, like the cyclic symmetry of the Riemann tensor + (i.e., Bianchi identity), are not covered. See combinatorics module for + information on how to generate BSGS for a general index permutation group. + Simple symmetries can be generated using built-in methods. + + See Also + ======== + + sympy.combinatorics.tensor_can.get_symmetric_group_sgs + + Examples + ======== + + Define a symmetric tensor of rank 2 + + >>> from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, TensorHead + >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') + >>> sym = TensorSymmetry(get_symmetric_group_sgs(2)) + >>> T = TensorHead('T', [Lorentz]*2, sym) + + Note, that the same can also be done using built-in TensorSymmetry methods + + >>> sym2 = TensorSymmetry.fully_symmetric(2) + >>> sym == sym2 + True + """ + def __new__(cls, *args, **kw_args): + if len(args) == 1: + base, generators = args[0] + elif len(args) == 2: + base, generators = args + else: + raise TypeError("bsgs required, either two separate parameters or one tuple") + + if not isinstance(base, Tuple): + base = Tuple(*base) + if not isinstance(generators, Tuple): + generators = Tuple(*generators) + + return Basic.__new__(cls, base, generators, **kw_args) + + @property + def base(self): + return self.args[0] + + @property + def generators(self): + return self.args[1] + + @property + def rank(self): + return self.generators[0].size - 2 + + @classmethod + def fully_symmetric(cls, rank): + """ + Returns a fully symmetric (antisymmetric if ``rank``<0) + TensorSymmetry object for ``abs(rank)`` indices. + """ + if rank > 0: + bsgs = get_symmetric_group_sgs(rank, False) + elif rank < 0: + bsgs = get_symmetric_group_sgs(-rank, True) + elif rank == 0: + bsgs = ([], [Permutation(1)]) + return TensorSymmetry(bsgs) + + @classmethod + def direct_product(cls, *args): + """ + Returns a TensorSymmetry object that is being a direct product of + fully (anti-)symmetric index permutation groups. + + Notes + ===== + + Some examples for different values of ``(*args)``: + ``(1)`` vector, equivalent to ``TensorSymmetry.fully_symmetric(1)`` + ``(2)`` tensor with 2 symmetric indices, equivalent to ``.fully_symmetric(2)`` + ``(-2)`` tensor with 2 antisymmetric indices, equivalent to ``.fully_symmetric(-2)`` + ``(2, -2)`` tensor with the first 2 indices commuting and the last 2 anticommuting + ``(1, 1, 1)`` tensor with 3 indices without any symmetry + """ + base, sgs = [], [Permutation(1)] + for arg in args: + if arg > 0: + bsgs2 = get_symmetric_group_sgs(arg, False) + elif arg < 0: + bsgs2 = get_symmetric_group_sgs(-arg, True) + else: + continue + base, sgs = bsgs_direct_product(base, sgs, *bsgs2) + + return TensorSymmetry(base, sgs) + + @classmethod + def riemann(cls): + """ + Returns a monotorem symmetry of the Riemann tensor + """ + return TensorSymmetry(riemann_bsgs) + + @classmethod + def no_symmetry(cls, rank): + """ + TensorSymmetry object for ``rank`` indices with no symmetry + """ + return TensorSymmetry([], [Permutation(rank+1)]) + + +@deprecated( + """ + The tensorsymmetry() function is deprecated. Use the TensorSymmetry + constructor instead. + """, + deprecated_since_version="1.5", + active_deprecations_target="deprecated-tensorsymmetry", +) +def tensorsymmetry(*args): + """ + Returns a ``TensorSymmetry`` object. This method is deprecated, use + ``TensorSymmetry.direct_product()`` or ``.riemann()`` instead. + + Explanation + =========== + + One can represent a tensor with any monoterm slot symmetry group + using a BSGS. + + ``args`` can be a BSGS + ``args[0]`` base + ``args[1]`` sgs + + Usually tensors are in (direct products of) representations + of the symmetric group; + ``args`` can be a list of lists representing the shapes of Young tableaux + + Notes + ===== + + For instance: + ``[[1]]`` vector + ``[[1]*n]`` symmetric tensor of rank ``n`` + ``[[n]]`` antisymmetric tensor of rank ``n`` + ``[[2, 2]]`` monoterm slot symmetry of the Riemann tensor + ``[[1],[1]]`` vector*vector + ``[[2],[1],[1]`` (antisymmetric tensor)*vector*vector + + Notice that with the shape ``[2, 2]`` we associate only the monoterm + symmetries of the Riemann tensor; this is an abuse of notation, + since the shape ``[2, 2]`` corresponds usually to the irreducible + representation characterized by the monoterm symmetries and by the + cyclic symmetry. + """ + from sympy.combinatorics import Permutation + + def tableau2bsgs(a): + if len(a) == 1: + # antisymmetric vector + n = a[0] + bsgs = get_symmetric_group_sgs(n, 1) + else: + if all(x == 1 for x in a): + # symmetric vector + n = len(a) + bsgs = get_symmetric_group_sgs(n) + elif a == [2, 2]: + bsgs = riemann_bsgs + else: + raise NotImplementedError + return bsgs + + if not args: + return TensorSymmetry(Tuple(), Tuple(Permutation(1))) + + if len(args) == 2 and isinstance(args[1][0], Permutation): + return TensorSymmetry(args) + base, sgs = tableau2bsgs(args[0]) + for a in args[1:]: + basex, sgsx = tableau2bsgs(a) + base, sgs = bsgs_direct_product(base, sgs, basex, sgsx) + return TensorSymmetry(Tuple(base, sgs)) + +@deprecated( + "TensorType is deprecated. Use tensor_heads() instead.", + deprecated_since_version="1.5", + active_deprecations_target="deprecated-tensortype", +) +class TensorType(Basic): + """ + Class of tensor types. Deprecated, use tensor_heads() instead. + + Parameters + ========== + + index_types : list of ``TensorIndexType`` of the tensor indices + symmetry : ``TensorSymmetry`` of the tensor + + Attributes + ========== + + ``index_types`` + ``symmetry`` + ``types`` : list of ``TensorIndexType`` without repetitions + """ + is_commutative = False + + def __new__(cls, index_types, symmetry, **kw_args): + assert symmetry.rank == len(index_types) + obj = Basic.__new__(cls, Tuple(*index_types), symmetry, **kw_args) + return obj + + @property + def index_types(self): + return self.args[0] + + @property + def symmetry(self): + return self.args[1] + + @property + def types(self): + return sorted(set(self.index_types), key=lambda x: x.name) + + def __str__(self): + return 'TensorType(%s)' % ([str(x) for x in self.index_types]) + + def __call__(self, s, comm=0): + """ + Return a TensorHead object or a list of TensorHead objects. + + Parameters + ========== + + s : name or string of names. + + comm : Commutation group. + + see ``_TensorManager.set_comm`` + """ + if isinstance(s, str): + names = [x.name for x in symbols(s, seq=True)] + else: + raise ValueError('expecting a string') + if len(names) == 1: + return TensorHead(names[0], self.index_types, self.symmetry, comm) + else: + return [TensorHead(name, self.index_types, self.symmetry, comm) for name in names] + + +@deprecated( + """ + The tensorhead() function is deprecated. Use tensor_heads() instead. + """, + deprecated_since_version="1.5", + active_deprecations_target="deprecated-tensorhead", +) +def tensorhead(name, typ, sym=None, comm=0): + """ + Function generating tensorhead(s). This method is deprecated, + use TensorHead constructor or tensor_heads() instead. + + Parameters + ========== + + name : name or sequence of names (as in ``symbols``) + + typ : index types + + sym : same as ``*args`` in ``tensorsymmetry`` + + comm : commutation group number + see ``_TensorManager.set_comm`` + """ + if sym is None: + sym = [[1] for i in range(len(typ))] + with ignore_warnings(SymPyDeprecationWarning): + sym = tensorsymmetry(*sym) + return TensorHead(name, typ, sym, comm) + + +class TensorHead(Basic): + """ + Tensor head of the tensor. + + Parameters + ========== + + name : name of the tensor + index_types : list of TensorIndexType + symmetry : TensorSymmetry of the tensor + comm : commutation group number + + Attributes + ========== + + ``name`` + ``index_types`` + ``rank`` : total number of indices + ``symmetry`` + ``comm`` : commutation group + + Notes + ===== + + Similar to ``symbols`` multiple TensorHeads can be created using + ``tensorhead(s, typ, sym=None, comm=0)`` function, where ``s`` + is the string of names and ``sym`` is the monoterm tensor symmetry + (see ``tensorsymmetry``). + + A ``TensorHead`` belongs to a commutation group, defined by a + symbol on number ``comm`` (see ``_TensorManager.set_comm``); + tensors in a commutation group have the same commutation properties; + by default ``comm`` is ``0``, the group of the commuting tensors. + + Examples + ======== + + Define a fully antisymmetric tensor of rank 2: + + >>> from sympy.tensor.tensor import TensorIndexType, TensorHead, TensorSymmetry + >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') + >>> asym2 = TensorSymmetry.fully_symmetric(-2) + >>> A = TensorHead('A', [Lorentz, Lorentz], asym2) + + Examples with ndarray values, the components data assigned to the + ``TensorHead`` object are assumed to be in a fully-contravariant + representation. In case it is necessary to assign components data which + represents the values of a non-fully covariant tensor, see the other + examples. + + >>> from sympy.tensor.tensor import tensor_indices + >>> from sympy import diag + >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') + >>> i0, i1 = tensor_indices('i0:2', Lorentz) + + Specify a replacement dictionary to keep track of the arrays to use for + replacements in the tensorial expression. The ``TensorIndexType`` is + associated to the metric used for contractions (in fully covariant form): + + >>> repl = {Lorentz: diag(1, -1, -1, -1)} + + Let's see some examples of working with components with the electromagnetic + tensor: + + >>> from sympy import symbols + >>> Ex, Ey, Ez, Bx, By, Bz = symbols('E_x E_y E_z B_x B_y B_z') + >>> c = symbols('c', positive=True) + + Let's define `F`, an antisymmetric tensor: + + >>> F = TensorHead('F', [Lorentz, Lorentz], asym2) + + Let's update the dictionary to contain the matrix to use in the + replacements: + + >>> repl.update({F(-i0, -i1): [ + ... [0, Ex/c, Ey/c, Ez/c], + ... [-Ex/c, 0, -Bz, By], + ... [-Ey/c, Bz, 0, -Bx], + ... [-Ez/c, -By, Bx, 0]]}) + + Now it is possible to retrieve the contravariant form of the Electromagnetic + tensor: + + >>> F(i0, i1).replace_with_arrays(repl, [i0, i1]) + [[0, -E_x/c, -E_y/c, -E_z/c], [E_x/c, 0, -B_z, B_y], [E_y/c, B_z, 0, -B_x], [E_z/c, -B_y, B_x, 0]] + + and the mixed contravariant-covariant form: + + >>> F(i0, -i1).replace_with_arrays(repl, [i0, -i1]) + [[0, E_x/c, E_y/c, E_z/c], [E_x/c, 0, B_z, -B_y], [E_y/c, -B_z, 0, B_x], [E_z/c, B_y, -B_x, 0]] + + Energy-momentum of a particle may be represented as: + + >>> from sympy import symbols + >>> P = TensorHead('P', [Lorentz], TensorSymmetry.no_symmetry(1)) + >>> E, px, py, pz = symbols('E p_x p_y p_z', positive=True) + >>> repl.update({P(i0): [E, px, py, pz]}) + + The contravariant and covariant components are, respectively: + + >>> P(i0).replace_with_arrays(repl, [i0]) + [E, p_x, p_y, p_z] + >>> P(-i0).replace_with_arrays(repl, [-i0]) + [E, -p_x, -p_y, -p_z] + + The contraction of a 1-index tensor by itself: + + >>> expr = P(i0)*P(-i0) + >>> expr.replace_with_arrays(repl, []) + E**2 - p_x**2 - p_y**2 - p_z**2 + """ + is_commutative = False + + def __new__(cls, name, index_types, symmetry=None, comm=0): + if isinstance(name, str): + name_symbol = Symbol(name) + elif isinstance(name, Symbol): + name_symbol = name + else: + raise ValueError("invalid name") + + if symmetry is None: + symmetry = TensorSymmetry.no_symmetry(len(index_types)) + else: + assert symmetry.rank == len(index_types) + + obj = Basic.__new__(cls, name_symbol, Tuple(*index_types), symmetry, sympify(comm)) + return obj + + @property + def name(self): + return self.args[0].name + + @property + def index_types(self): + return list(self.args[1]) + + @property + def symmetry(self): + return self.args[2] + + @property + def comm(self): + return TensorManager.comm_symbols2i(self.args[3]) + + @property + def rank(self): + return len(self.index_types) + + def __lt__(self, other): + return (self.name, self.index_types) < (other.name, other.index_types) + + def commutes_with(self, other): + """ + Returns ``0`` if ``self`` and ``other`` commute, ``1`` if they anticommute. + + Returns ``None`` if ``self`` and ``other`` neither commute nor anticommute. + """ + r = TensorManager.get_comm(self.comm, other.comm) + return r + + def _print(self): + return '%s(%s)' %(self.name, ','.join([str(x) for x in self.index_types])) + + def __call__(self, *indices, **kw_args): + """ + Returns a tensor with indices. + + Explanation + =========== + + There is a special behavior in case of indices denoted by ``True``, + they are considered auto-matrix indices, their slots are automatically + filled, and confer to the tensor the behavior of a matrix or vector + upon multiplication with another tensor containing auto-matrix indices + of the same ``TensorIndexType``. This means indices get summed over the + same way as in matrix multiplication. For matrix behavior, define two + auto-matrix indices, for vector behavior define just one. + + Indices can also be strings, in which case the attribute + ``index_types`` is used to convert them to proper ``TensorIndex``. + + Examples + ======== + + >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorSymmetry, TensorHead + >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') + >>> a, b = tensor_indices('a,b', Lorentz) + >>> A = TensorHead('A', [Lorentz]*2, TensorSymmetry.no_symmetry(2)) + >>> t = A(a, -b) + >>> t + A(a, -b) + + """ + + updated_indices = [] + for idx, typ in zip(indices, self.index_types): + if isinstance(idx, str): + idx = idx.strip().replace(" ", "") + if idx.startswith('-'): + updated_indices.append(TensorIndex(idx[1:], typ, + is_up=False)) + else: + updated_indices.append(TensorIndex(idx, typ)) + else: + updated_indices.append(idx) + + updated_indices += indices[len(updated_indices):] + + tensor = Tensor(self, updated_indices, **kw_args) + return tensor.doit() + + # Everything below this line is deprecated + + def __pow__(self, other): + deprecate_data() + with ignore_warnings(SymPyDeprecationWarning): + if self.data is None: + raise ValueError("No power on abstract tensors.") + from .array import tensorproduct, tensorcontraction + metrics = [_.data for _ in self.index_types] + + marray = self.data + marraydim = marray.rank() + for metric in metrics: + marray = tensorproduct(marray, metric, marray) + marray = tensorcontraction(marray, (0, marraydim), (marraydim+1, marraydim+2)) + + return marray ** (other * S.Half) + + @property + def data(self): + deprecate_data() + with ignore_warnings(SymPyDeprecationWarning): + return _tensor_data_substitution_dict[self] + + @data.setter + def data(self, data): + deprecate_data() + with ignore_warnings(SymPyDeprecationWarning): + _tensor_data_substitution_dict[self] = data + + @data.deleter + def data(self): + deprecate_data() + if self in _tensor_data_substitution_dict: + del _tensor_data_substitution_dict[self] + + def __iter__(self): + deprecate_data() + with ignore_warnings(SymPyDeprecationWarning): + return self.data.__iter__() + + def _components_data_full_destroy(self): + """ + EXPERIMENTAL: do not rely on this API method. + + Destroy components data associated to the ``TensorHead`` object, this + checks for attached components data, and destroys components data too. + """ + # do not garbage collect Kronecker tensor (it should be done by + # ``TensorIndexType`` garbage collection) + deprecate_data() + if self.name == "KD": + return + + # the data attached to a tensor must be deleted only by the TensorHead + # destructor. If the TensorHead is deleted, it means that there are no + # more instances of that tensor anywhere. + if self in _tensor_data_substitution_dict: + del _tensor_data_substitution_dict[self] + + +def tensor_heads(s, index_types, symmetry=None, comm=0): + """ + Returns a sequence of TensorHeads from a string `s` + """ + if isinstance(s, str): + names = [x.name for x in symbols(s, seq=True)] + else: + raise ValueError('expecting a string') + + thlist = [TensorHead(name, index_types, symmetry, comm) for name in names] + if len(thlist) == 1: + return thlist[0] + return thlist + + +class TensExpr(Expr, ABC): + """ + Abstract base class for tensor expressions + + Notes + ===== + + A tensor expression is an expression formed by tensors; + currently the sums of tensors are distributed. + + A ``TensExpr`` can be a ``TensAdd`` or a ``TensMul``. + + ``TensMul`` objects are formed by products of component tensors, + and include a coefficient, which is a SymPy expression. + + + In the internal representation contracted indices are represented + by ``(ipos1, ipos2, icomp1, icomp2)``, where ``icomp1`` is the position + of the component tensor with contravariant index, ``ipos1`` is the + slot which the index occupies in that component tensor. + + Contracted indices are therefore nameless in the internal representation. + """ + + _op_priority = 12.0 + is_commutative = False + + def __neg__(self): + return self*S.NegativeOne + + def __abs__(self): + raise NotImplementedError + + def __add__(self, other): + return TensAdd(self, other).doit(deep=False) + + def __radd__(self, other): + return TensAdd(other, self).doit(deep=False) + + def __sub__(self, other): + return TensAdd(self, -other).doit(deep=False) + + def __rsub__(self, other): + return TensAdd(other, -self).doit(deep=False) + + def __mul__(self, other): + """ + Multiply two tensors using Einstein summation convention. + + Explanation + =========== + + If the two tensors have an index in common, one contravariant + and the other covariant, in their product the indices are summed + + Examples + ======== + + >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads + >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') + >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz) + >>> g = Lorentz.metric + >>> p, q = tensor_heads('p,q', [Lorentz]) + >>> t1 = p(m0) + >>> t2 = q(-m0) + >>> t1*t2 + p(L_0)*q(-L_0) + """ + return TensMul(self, other).doit(deep=False) + + def __rmul__(self, other): + return TensMul(other, self).doit(deep=False) + + def __truediv__(self, other): + other = _sympify(other) + if isinstance(other, TensExpr): + raise ValueError('cannot divide by a tensor') + return TensMul(self, S.One/other).doit(deep=False) + + def __rtruediv__(self, other): + raise ValueError('cannot divide by a tensor') + + def __pow__(self, other): + deprecate_data() + with ignore_warnings(SymPyDeprecationWarning): + if self.data is None: + raise ValueError("No power without ndarray data.") + from .array import tensorproduct, tensorcontraction + free = self.free + marray = self.data + mdim = marray.rank() + for metric in free: + marray = tensorcontraction( + tensorproduct( + marray, + metric[0].tensor_index_type.data, + marray), + (0, mdim), (mdim+1, mdim+2) + ) + return marray ** (other * S.Half) + + def __rpow__(self, other): + raise NotImplementedError + + @property + @abstractmethod + def nocoeff(self): + raise NotImplementedError("abstract method") + + @property + @abstractmethod + def coeff(self): + raise NotImplementedError("abstract method") + + @abstractmethod + def get_indices(self): + raise NotImplementedError("abstract method") + + @abstractmethod + def get_free_indices(self) -> list[TensorIndex]: + raise NotImplementedError("abstract method") + + @abstractmethod + def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr: + raise NotImplementedError("abstract method") + + def fun_eval(self, *index_tuples): + deprecate_fun_eval() + return self.substitute_indices(*index_tuples) + + def get_matrix(self): + """ + DEPRECATED: do not use. + + Returns ndarray components data as a matrix, if components data are + available and ndarray dimension does not exceed 2. + """ + from sympy.matrices.dense import Matrix + deprecate_data() + with ignore_warnings(SymPyDeprecationWarning): + if 0 < self.rank <= 2: + rows = self.data.shape[0] + columns = self.data.shape[1] if self.rank == 2 else 1 + if self.rank == 2: + mat_list = [] * rows + for i in range(rows): + mat_list.append([]) + for j in range(columns): + mat_list[i].append(self[i, j]) + else: + mat_list = [None] * rows + for i in range(rows): + mat_list[i] = self[i] + return Matrix(mat_list) + else: + raise NotImplementedError( + "missing multidimensional reduction to matrix.") + + @staticmethod + def _get_indices_permutation(indices1, indices2): + return [indices1.index(i) for i in indices2] + + def _get_free_indices_set(self): + indset = set() + for arg in self.args: + if isinstance(arg, TensExpr): + indset.update(arg._get_free_indices_set()) + return indset + + def _get_dummy_indices_set(self): + indset = set() + for arg in self.args: + if isinstance(arg, TensExpr): + indset.update(arg._get_dummy_indices_set()) + return indset + + def _get_indices_set(self): + indset = set() + for arg in self.args: + if isinstance(arg, TensExpr): + indset.update(arg._get_indices_set()) + return indset + + @property + def _iterate_dummy_indices(self): + dummy_set = self._get_dummy_indices_set() + + def recursor(expr, pos): + if isinstance(expr, TensorIndex): + if expr in dummy_set: + yield (expr, pos) + elif isinstance(expr, (Tuple, TensExpr)): + for p, arg in enumerate(expr.args): + yield from recursor(arg, pos+(p,)) + + return recursor(self, ()) + + @property + def _iterate_free_indices(self): + free_set = self._get_free_indices_set() + + def recursor(expr, pos): + if isinstance(expr, TensorIndex): + if expr in free_set: + yield (expr, pos) + elif isinstance(expr, (Tuple, TensExpr)): + for p, arg in enumerate(expr.args): + yield from recursor(arg, pos+(p,)) + + return recursor(self, ()) + + @property + def _iterate_indices(self): + def recursor(expr, pos): + if isinstance(expr, TensorIndex): + yield (expr, pos) + elif isinstance(expr, (Tuple, TensExpr)): + for p, arg in enumerate(expr.args): + yield from recursor(arg, pos+(p,)) + + return recursor(self, ()) + + @staticmethod + def _contract_and_permute_with_metric(metric, array, pos, dim): + # TODO: add possibility of metric after (spinors) + from .array import tensorcontraction, tensorproduct, permutedims + + array = tensorcontraction(tensorproduct(metric, array), (1, 2+pos)) + permu = list(range(dim)) + permu[0], permu[pos] = permu[pos], permu[0] + return permutedims(array, permu) + + @staticmethod + def _match_indices_with_other_tensor(array, free_ind1, free_ind2, replacement_dict): + from .array import permutedims + + index_types1 = [i.tensor_index_type for i in free_ind1] + + # Check if variance of indices needs to be fixed: + pos2up = [] + pos2down = [] + free2remaining = free_ind2[:] + for pos1, index1 in enumerate(free_ind1): + if index1 in free2remaining: + pos2 = free2remaining.index(index1) + free2remaining[pos2] = None + continue + if -index1 in free2remaining: + pos2 = free2remaining.index(-index1) + free2remaining[pos2] = None + free_ind2[pos2] = index1 + if index1.is_up: + pos2up.append(pos2) + else: + pos2down.append(pos2) + else: + index2 = free2remaining[pos1] + if index2 is None: + raise ValueError("incompatible indices: %s and %s" % (free_ind1, free_ind2)) + free2remaining[pos1] = None + free_ind2[pos1] = index1 + if index1.is_up ^ index2.is_up: + if index1.is_up: + pos2up.append(pos1) + else: + pos2down.append(pos1) + + if len(set(free_ind1) & set(free_ind2)) < len(free_ind1): + raise ValueError("incompatible indices: %s and %s" % (free_ind1, free_ind2)) + + # Raise indices: + for pos in pos2up: + index_type_pos = index_types1[pos] + if index_type_pos not in replacement_dict: + raise ValueError("No metric provided to lower index") + metric = replacement_dict[index_type_pos] + metric_inverse = _TensorDataLazyEvaluator.inverse_matrix(metric) + array = TensExpr._contract_and_permute_with_metric(metric_inverse, array, pos, len(free_ind1)) + # Lower indices: + for pos in pos2down: + index_type_pos = index_types1[pos] + if index_type_pos not in replacement_dict: + raise ValueError("No metric provided to lower index") + metric = replacement_dict[index_type_pos] + array = TensExpr._contract_and_permute_with_metric(metric, array, pos, len(free_ind1)) + + if free_ind1: + permutation = TensExpr._get_indices_permutation(free_ind2, free_ind1) + array = permutedims(array, permutation) + + if hasattr(array, "rank") and array.rank() == 0: + array = array[()] + + return free_ind2, array + + def replace_with_arrays(self, replacement_dict, indices=None): + """ + Replace the tensorial expressions with arrays. The final array will + correspond to the N-dimensional array with indices arranged according + to ``indices``. + + Parameters + ========== + + replacement_dict + dictionary containing the replacement rules for tensors. + indices + the index order with respect to which the array is read. The + original index order will be used if no value is passed. + + Examples + ======== + + >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices + >>> from sympy.tensor.tensor import TensorHead + >>> from sympy import symbols, diag + + >>> L = TensorIndexType("L") + >>> i, j = tensor_indices("i j", L) + >>> A = TensorHead("A", [L]) + >>> A(i).replace_with_arrays({A(i): [1, 2]}, [i]) + [1, 2] + + Since 'indices' is optional, we can also call replace_with_arrays by + this way if no specific index order is needed: + + >>> A(i).replace_with_arrays({A(i): [1, 2]}) + [1, 2] + + >>> expr = A(i)*A(j) + >>> expr.replace_with_arrays({A(i): [1, 2]}) + [[1, 2], [2, 4]] + + For contractions, specify the metric of the ``TensorIndexType``, which + in this case is ``L``, in its covariant form: + + >>> expr = A(i)*A(-i) + >>> expr.replace_with_arrays({A(i): [1, 2], L: diag(1, -1)}) + -3 + + Symmetrization of an array: + + >>> H = TensorHead("H", [L, L]) + >>> a, b, c, d = symbols("a b c d") + >>> expr = H(i, j)/2 + H(j, i)/2 + >>> expr.replace_with_arrays({H(i, j): [[a, b], [c, d]]}) + [[a, b/2 + c/2], [b/2 + c/2, d]] + + Anti-symmetrization of an array: + + >>> expr = H(i, j)/2 - H(j, i)/2 + >>> repl = {H(i, j): [[a, b], [c, d]]} + >>> expr.replace_with_arrays(repl) + [[0, b/2 - c/2], [-b/2 + c/2, 0]] + + The same expression can be read as the transpose by inverting ``i`` and + ``j``: + + >>> expr.replace_with_arrays(repl, [j, i]) + [[0, -b/2 + c/2], [b/2 - c/2, 0]] + """ + from .array import Array + + indices = indices or [] + remap = {k.args[0] if k.is_up else -k.args[0]: k for k in self.get_free_indices()} + for i, index in enumerate(indices): + if isinstance(index, (Symbol, Mul)): + if index in remap: + indices[i] = remap[index] + else: + indices[i] = -remap[-index] + + replacement_dict = {tensor: Array(array) for tensor, array in replacement_dict.items()} + + # Check dimensions of replaced arrays: + for tensor, array in replacement_dict.items(): + if isinstance(tensor, TensorIndexType): + expected_shape = [tensor.dim for i in range(2)] + else: + expected_shape = [index_type.dim for index_type in tensor.index_types] + if len(expected_shape) != array.rank() or (not all(dim1 == dim2 if + dim1.is_number else True for dim1, dim2 in zip(expected_shape, + array.shape))): + raise ValueError("shapes for tensor %s expected to be %s, "\ + "replacement array shape is %s" % (tensor, expected_shape, + array.shape)) + + ret_indices, array = self._extract_data(replacement_dict) + + last_indices, array = self._match_indices_with_other_tensor(array, indices, ret_indices, replacement_dict) + return array + + def _check_add_Sum(self, expr, index_symbols): + from sympy.concrete.summations import Sum + indices = self.get_indices() + dum = self.dum + sum_indices = [ (index_symbols[i], 0, + indices[i].tensor_index_type.dim-1) for i, j in dum] + if sum_indices: + expr = Sum(expr, *sum_indices) + return expr + + def _expand_partial_derivative(self): + # simply delegate the _expand_partial_derivative() to + # its arguments to expand a possibly found PartialDerivative + return self.func(*[ + a._expand_partial_derivative() + if isinstance(a, TensExpr) else a + for a in self.args]) + + def _matches_simple(self, expr, repl_dict=None, old=False): + """ + Matches assuming there are no wild objects in self. + """ + if repl_dict is None: + repl_dict = {} + else: + repl_dict = repl_dict.copy() + + if not isinstance(expr, TensExpr): + if len(self.get_free_indices()) > 0: + #self has indices, but expr does not. + return None + elif set(self.get_free_indices()) != set(expr.get_free_indices()): + #If there are no wilds and the free indices are not the same, they cannot match. + return None + + if canon_bp(self - expr) == S.Zero: + return repl_dict + else: + return None + + +class TensAdd(TensExpr, AssocOp): + """ + Sum of tensors. + + Parameters + ========== + + free_args : list of the free indices + + Attributes + ========== + + ``args`` : tuple of addends + ``rank`` : rank of the tensor + ``free_args`` : list of the free indices in sorted order + + Examples + ======== + + >>> from sympy.tensor.tensor import TensorIndexType, tensor_heads, tensor_indices + >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') + >>> a, b = tensor_indices('a,b', Lorentz) + >>> p, q = tensor_heads('p,q', [Lorentz]) + >>> t = p(a) + q(a); t + p(a) + q(a) + + Examples with components data added to the tensor expression: + + >>> from sympy import symbols, diag + >>> x, y, z, t = symbols("x y z t") + >>> repl = {} + >>> repl[Lorentz] = diag(1, -1, -1, -1) + >>> repl[p(a)] = [1, 2, 3, 4] + >>> repl[q(a)] = [x, y, z, t] + + The following are: 2**2 - 3**2 - 2**2 - 7**2 ==> -58 + + >>> expr = p(a) + q(a) + >>> expr.replace_with_arrays(repl, [a]) + [x + 1, y + 2, z + 3, t + 4] + """ + + def __new__(cls, *args, **kw_args): + args = [_sympify(x) for x in args if x] + args = TensAdd._tensAdd_flatten(args) + args.sort(key=default_sort_key) + if not args: + return S.Zero + if len(args) == 1: + return args[0] + + return Basic.__new__(cls, *args, **kw_args) + + @property + def coeff(self): + return S.One + + @property + def nocoeff(self): + return self + + def get_free_indices(self) -> list[TensorIndex]: + return self.free_indices + + def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr: + newargs = [arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg for arg in self.args] + return self.func(*newargs) + + @memoize_property + def rank(self): + if isinstance(self.args[0], TensExpr): + return self.args[0].rank + else: + return 0 + + @memoize_property + def free_args(self): + if isinstance(self.args[0], TensExpr): + return self.args[0].free_args + else: + return [] + + @memoize_property + def free_indices(self): + if isinstance(self.args[0], TensExpr): + return self.args[0].get_free_indices() + else: + return set() + + def doit(self, **hints) -> Expr: + deep = hints.get('deep', True) + if deep: + args = [arg.doit(**hints) for arg in self.args] + else: + args = self.args # type: ignore + + # if any of the args are zero (after doit), drop them. Otherwise, _tensAdd_check will complain about non-matching indices, even though the TensAdd is correctly formed. + args = [arg for arg in args if arg != S.Zero] + + if len(args) == 0: + return S.Zero + elif len(args) == 1: + return args[0] + + # now check that all addends have the same indices: + TensAdd._tensAdd_check(args) + + # Collect terms appearing more than once, differing by their coefficients: + args = TensAdd._tensAdd_collect_terms(args) + + # collect canonicalized terms + def sort_key(t): + if not isinstance(t, TensExpr): + return [], [], [] + if hasattr(t, "_index_structure") and hasattr(t, "components"): + x = get_index_structure(t) + return t.components, x.free, x.dum + return [], [], [] + args.sort(key=sort_key) + + if not args: + return S.Zero + # it there is only a component tensor return it + if len(args) == 1: + return args[0] + + obj = self.func(*args) + return obj + + @staticmethod + def _tensAdd_flatten(args): + # flatten TensAdd, coerce terms which are not tensors to tensors + a = [] + for x in args: + if isinstance(x, (Add, TensAdd)): + a.extend(list(x.args)) + else: + a.append(x) + args = [x for x in a if x.coeff] + return args + + @staticmethod + def _tensAdd_check(args): + # check that all addends have the same free indices + + def get_indices_set(x: Expr) -> set[TensorIndex]: + if isinstance(x, TensExpr): + return set(x.get_free_indices()) + return set() + + indices0 = get_indices_set(args[0]) + list_indices = [get_indices_set(arg) for arg in args[1:]] + if not all(x == indices0 for x in list_indices): + raise ValueError('all tensors must have the same indices') + + @staticmethod + def _tensAdd_collect_terms(args): + # collect TensMul terms differing at most by their coefficient + terms_dict = defaultdict(list) + scalars = S.Zero + if isinstance(args[0], TensExpr): + free_indices = set(args[0].get_free_indices()) + else: + free_indices = set() + + for arg in args: + if not isinstance(arg, TensExpr): + if free_indices != set(): + raise ValueError("wrong valence") + scalars += arg + continue + if free_indices != set(arg.get_free_indices()): + raise ValueError("wrong valence") + # TODO: what is the part which is not a coeff? + # needs an implementation similar to .as_coeff_Mul() + terms_dict[arg.nocoeff].append(arg.coeff) + + new_args = [TensMul(Add(*coeff), t).doit(deep=False) for t, coeff in terms_dict.items() if Add(*coeff) != 0] + if isinstance(scalars, Add): + new_args = list(scalars.args) + new_args + elif scalars != 0: + new_args = [scalars] + new_args + return new_args + + def get_indices(self): + indices = [] + for arg in self.args: + indices.extend([i for i in get_indices(arg) if i not in indices]) + return indices + + + def __call__(self, *indices): + deprecate_call() + free_args = self.free_args + indices = list(indices) + if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]: + raise ValueError('incompatible types') + if indices == free_args: + return self + index_tuples = list(zip(free_args, indices)) + a = [x.func(*x.substitute_indices(*index_tuples).args) for x in self.args] + res = TensAdd(*a).doit(deep=False) + return res + + def canon_bp(self): + """ + Canonicalize using the Butler-Portugal algorithm for canonicalization + under monoterm symmetries. + """ + expr = self.expand() + if isinstance(expr, self.func): + args = [canon_bp(x) for x in expr.args] + res = TensAdd(*args).doit(deep=False) + return res + else: + return canon_bp(expr) + + def equals(self, other): + other = _sympify(other) + if isinstance(other, TensMul) and other.coeff == 0: + return all(x.coeff == 0 for x in self.args) + if isinstance(other, TensExpr): + if self.rank != other.rank: + return False + if isinstance(other, TensAdd): + if set(self.args) != set(other.args): + return False + else: + return True + t = self - other + if not isinstance(t, TensExpr): + return t == 0 + else: + if isinstance(t, TensMul): + return t.coeff == 0 + else: + return all(x.coeff == 0 for x in t.args) + + def __getitem__(self, item): + deprecate_data() + with ignore_warnings(SymPyDeprecationWarning): + return self.data[item] + + def contract_delta(self, delta): + args = [x.contract_delta(delta) if isinstance(x, TensExpr) else x for x in self.args] + t = TensAdd(*args).doit(deep=False) + return canon_bp(t) + + def contract_metric(self, g): + """ + Raise or lower indices with the metric ``g``. + + Parameters + ========== + + g : metric + + contract_all : if True, eliminate all ``g`` which are contracted + + Notes + ===== + + see the ``TensorIndexType`` docstring for the contraction conventions + """ + + args = [contract_metric(x, g) for x in self.args] + t = TensAdd(*args).doit(deep=False) + return canon_bp(t) + + def substitute_indices(self, *index_tuples): + new_args = [] + for arg in self.args: + if isinstance(arg, TensExpr): + arg = arg.substitute_indices(*index_tuples) + new_args.append(arg) + return TensAdd(*new_args).doit(deep=False) + + def _print(self): + a = [] + args = self.args + for x in args: + a.append(str(x)) + s = ' + '.join(a) + s = s.replace('+ -', '- ') + return s + + def _extract_data(self, replacement_dict): + from sympy.tensor.array import Array, permutedims + args_indices, arrays = zip(*[ + arg._extract_data(replacement_dict) if + isinstance(arg, TensExpr) else ([], arg) for arg in self.args + ]) + arrays = [Array(i) for i in arrays] + ref_indices = args_indices[0] + for i in range(1, len(args_indices)): + indices = args_indices[i] + array = arrays[i] + permutation = TensMul._get_indices_permutation(indices, ref_indices) + arrays[i] = permutedims(array, permutation) + return ref_indices, sum(arrays, Array.zeros(*array.shape)) + + @property + def data(self): + deprecate_data() + with ignore_warnings(SymPyDeprecationWarning): + return _tensor_data_substitution_dict[self.expand()] + + @data.setter + def data(self, data): + deprecate_data() + with ignore_warnings(SymPyDeprecationWarning): + _tensor_data_substitution_dict[self] = data + + @data.deleter + def data(self): + deprecate_data() + with ignore_warnings(SymPyDeprecationWarning): + if self in _tensor_data_substitution_dict: + del _tensor_data_substitution_dict[self] + + def __iter__(self): + deprecate_data() + if not self.data: + raise ValueError("No iteration on abstract tensors") + return self.data.flatten().__iter__() + + def _eval_rewrite_as_Indexed(self, *args, **kwargs): + return Add.fromiter(args) + + def _eval_partial_derivative(self, s): + # Evaluation like Add + list_addends = [] + for a in self.args: + if isinstance(a, TensExpr): + list_addends.append(a._eval_partial_derivative(s)) + # do not call diff if s is no symbol + elif s._diff_wrt: + list_addends.append(a._eval_derivative(s)) + + return self.func(*list_addends).doit(deep=False) + + def matches(self, expr, repl_dict=None, old=False): + expr = sympify(expr) + + if repl_dict is None: + repl_dict = {} + else: + repl_dict = repl_dict.copy() + + if not isinstance(expr, TensAdd): + return None + + if len(_get_wilds(self)) == 0: + return self._matches_simple(expr, repl_dict, old) + + def siftkey(arg): + wildatoms = _get_wilds(arg) + wildatom_types = sift(wildatoms, type) + if len(wildatoms) == 0: + return "nonwild" + elif WildTensor in wildatom_types.keys(): + for w in wildatom_types["WildTensor"]: + if len(w.get_indices()) == 0: + return "indexless_wildtensor" + return "wildtensor" + else: + return "otherwild" + + query_sifted = sift(self.args, siftkey) + expr_sifted = sift(expr.args, siftkey) + + #First try to match the terms without WildTensors + matched_e_tensors = [] #Used to make sure that the same tensor in expr is not matched with more than one tensor in self. + for q_tensor in query_sifted["nonwild"]: + matched_this_q = False + for e_tensor in expr_sifted["nonwild"]: + if e_tensor in matched_e_tensors: + continue + + m = q_tensor.matches(e_tensor, repl_dict=repl_dict, old=old) + if m is None: + continue + else: + matched_this_q = True + repl_dict.update(m) + matched_e_tensors.append(e_tensor) + break + + if not matched_this_q: + return None + + remaining_e_tensors = [t for t in expr_sifted["nonwild"] if t not in matched_e_tensors] + for w in query_sifted["otherwild"]: + for e in remaining_e_tensors: + m = w.matches(e) + if m is not None: + matched_e_tensors.append(e) + if w in repl_dict.keys(): + repl_dict[w] += m.pop(w) + repl_dict.update(m) + + remaining_e_tensors = [t for t in expr_sifted["nonwild"] if t not in matched_e_tensors] + for w in query_sifted["wildtensor"]: + for e in remaining_e_tensors: + m = w.matches(e) + if m is not None: + matched_e_tensors.append(e) + if w.component in repl_dict.keys(): + repl_dict[w.component] += m.pop(w.component) + repl_dict.update(m) + + remaining_e_tensors = [t for t in expr_sifted["nonwild"] if t not in matched_e_tensors] + for w in query_sifted["indexless_wildtensor"]: + for e in remaining_e_tensors: + m = w.matches(e) + if m is not None: + matched_e_tensors.append(e) + if w.component in repl_dict.keys(): + repl_dict[w.component] += m.pop(w.component) + repl_dict.update(m) + + remaining_e_tensors = [t for t in expr_sifted["nonwild"] if t not in matched_e_tensors] + if len(remaining_e_tensors) > 0: + return None + else: + return repl_dict + + +class Tensor(TensExpr): + """ + Base tensor class, i.e. this represents a tensor, the single unit to be + put into an expression. + + Explanation + =========== + + This object is usually created from a ``TensorHead``, by attaching indices + to it. Indices preceded by a minus sign are considered contravariant, + otherwise covariant. + + Examples + ======== + + >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead + >>> Lorentz = TensorIndexType("Lorentz", dummy_name="L") + >>> mu, nu = tensor_indices('mu nu', Lorentz) + >>> A = TensorHead("A", [Lorentz, Lorentz]) + >>> A(mu, -nu) + A(mu, -nu) + >>> A(mu, -mu) + A(L_0, -L_0) + + It is also possible to use symbols instead of inidices (appropriate indices + are then generated automatically). + + >>> from sympy import Symbol + >>> x = Symbol('x') + >>> A(x, mu) + A(x, mu) + >>> A(x, -x) + A(L_0, -L_0) + + """ + + is_commutative = False + + _index_structure: _IndexStructure + args: tuple[TensorHead, Tuple] + + def __new__(cls, tensor_head, indices, *, is_canon_bp=False, **kw_args): + indices = cls._parse_indices(tensor_head, indices) + obj = Basic.__new__(cls, tensor_head, Tuple(*indices), **kw_args) + obj._index_structure = _IndexStructure.from_indices(*indices) + obj._free = obj._index_structure.free[:] + obj._dum = obj._index_structure.dum[:] + obj._ext_rank = obj._index_structure._ext_rank + obj._coeff = S.One + obj._nocoeff = obj + obj._component = tensor_head + obj._components = [tensor_head] + if tensor_head.rank != len(indices): + raise ValueError("wrong number of indices") + obj.is_canon_bp = is_canon_bp + obj._index_map = Tensor._build_index_map(indices, obj._index_structure) + return obj + + @property + def free(self): + return self._free + + @property + def dum(self): + return self._dum + + @property + def ext_rank(self): + return self._ext_rank + + @property + def coeff(self): + return self._coeff + + @property + def nocoeff(self): + return self._nocoeff + + @property + def component(self): + return self._component + + @property + def components(self): + return self._components + + @property + def head(self): + return self.args[0] + + @property + def indices(self): + return self.args[1] + + @property + def free_indices(self): + return set(self._index_structure.get_free_indices()) + + @property + def index_types(self): + return self.head.index_types + + @property + def rank(self): + return len(self.free_indices) + + @staticmethod + def _build_index_map(indices, index_structure): + index_map = {} + for idx in indices: + index_map[idx] = (indices.index(idx),) + return index_map + + def doit(self, **hints): + args, indices, free, dum = TensMul._tensMul_contract_indices([self]) + return args[0] + + @staticmethod + def _parse_indices(tensor_head, indices): + if not isinstance(indices, (tuple, list, Tuple)): + raise TypeError("indices should be an array, got %s" % type(indices)) + indices = list(indices) + for i, index in enumerate(indices): + if isinstance(index, Symbol): + indices[i] = TensorIndex(index, tensor_head.index_types[i], True) + elif isinstance(index, Mul): + c, e = index.as_coeff_Mul() + if c == -1 and isinstance(e, Symbol): + indices[i] = TensorIndex(e, tensor_head.index_types[i], False) + else: + raise ValueError("index not understood: %s" % index) + elif not isinstance(index, TensorIndex): + raise TypeError("wrong type for index: %s is %s" % (index, type(index))) + return indices + + def _set_new_index_structure(self, im, is_canon_bp=False): + indices = im.get_indices() + return self._set_indices(*indices, is_canon_bp=is_canon_bp) + + def _set_indices(self, *indices, is_canon_bp=False, **kw_args): + if len(indices) != self.ext_rank: + raise ValueError("indices length mismatch") + return self.func(self.args[0], indices, is_canon_bp=is_canon_bp).doit() + + def _get_free_indices_set(self): + return {i[0] for i in self._index_structure.free} + + def _get_dummy_indices_set(self): + dummy_pos = set(itertools.chain(*self._index_structure.dum)) + return {idx for i, idx in enumerate(self.args[1]) if i in dummy_pos} + + def _get_indices_set(self): + return set(self.args[1].args) + + @property + def free_in_args(self): + return [(ind, pos, 0) for ind, pos in self.free] + + @property + def dum_in_args(self): + return [(p1, p2, 0, 0) for p1, p2 in self.dum] + + @property + def free_args(self): + return sorted([x[0] for x in self.free]) + + def commutes_with(self, other): + """ + :param other: + :return: + 0 commute + 1 anticommute + None neither commute nor anticommute + """ + if not isinstance(other, TensExpr): + return 0 + elif isinstance(other, Tensor): + return self.component.commutes_with(other.component) + return NotImplementedError + + def perm2tensor(self, g, is_canon_bp=False): + """ + Returns the tensor corresponding to the permutation ``g``. + + For further details, see the method in ``TIDS`` with the same name. + """ + return perm2tensor(self, g, is_canon_bp) + + def canon_bp(self): + if self.is_canon_bp: + return self + expr = self.expand() + g, dummies, msym = expr._index_structure.indices_canon_args() + v = components_canon_args([expr.component]) + can = canonicalize(g, dummies, msym, *v) + if can == 0: + return S.Zero + tensor = self.perm2tensor(can, True) + return tensor + + def split(self): + return [self] + + def sorted_components(self): + return self + + def get_indices(self) -> list[TensorIndex]: + """ + Get a list of indices, corresponding to those of the tensor. + """ + return list(self.args[1]) + + def get_free_indices(self) -> list[TensorIndex]: + """ + Get a list of free indices, corresponding to those of the tensor. + """ + return self._index_structure.get_free_indices() + + def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr: + # TODO: this could be optimized by only swapping the indices + # instead of visiting the whole expression tree: + return self.xreplace(repl) + + def as_base_exp(self): + return self, S.One + + def substitute_indices(self, *index_tuples): + """ + Return a tensor with free indices substituted according to ``index_tuples``. + + ``index_types`` list of tuples ``(old_index, new_index)``. + + Examples + ======== + + >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads, TensorSymmetry + >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') + >>> i, j, k, l = tensor_indices('i,j,k,l', Lorentz) + >>> A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) + >>> t = A(i, k)*B(-k, -j); t + A(i, L_0)*B(-L_0, -j) + >>> t.substitute_indices((i, k),(-j, l)) + A(k, L_0)*B(-L_0, l) + """ + indices = [] + for index in self.indices: + for ind_old, ind_new in index_tuples: + if (index.name == ind_old.name and index.tensor_index_type == + ind_old.tensor_index_type): + if index.is_up == ind_old.is_up: + indices.append(ind_new) + else: + indices.append(-ind_new) + break + else: + indices.append(index) + return self.head(*indices) + + def _get_symmetrized_forms(self): + """ + Return a list giving all possible permutations of self that are allowed by its symmetries. + """ + comp = self.component + gens = comp.symmetry.generators + rank = comp.rank + + old_perms = None + new_perms = {self} + while new_perms != old_perms: + old_perms = new_perms.copy() + for tens in old_perms: + for gen in gens: + inds = tens.get_indices() + per = [gen.apply(i) for i in range(0,rank)] + sign = (-1)**(gen.apply(rank) - rank) + ind_map = dict(zip(inds, [inds[i] for i in per])) + new_perms.add( sign * tens._replace_indices(ind_map) ) + + return new_perms + + def matches(self, expr, repl_dict=None, old=False): + expr = sympify(expr) + + if repl_dict is None: + repl_dict = {} + else: + repl_dict = repl_dict.copy() + + #simple checks + if self == expr: + return repl_dict + if not isinstance(expr, Tensor): + return None + if self.head != expr.head: + return None + + #Now consider all index symmetries of expr, and see if any of them allow a match. + for new_expr in expr._get_symmetrized_forms(): + m = self._matches(new_expr, repl_dict, old=old) + if m is not None: + repl_dict.update(m) + return repl_dict + + return None + + def _matches(self, expr, repl_dict=None, old=False): + """ + This does not account for index symmetries of expr + """ + expr = sympify(expr) + + if repl_dict is None: + repl_dict = {} + else: + repl_dict = repl_dict.copy() + + #simple checks + if self == expr: + return repl_dict + if not isinstance(expr, Tensor): + return None + if self.head != expr.head: + return None + + s_indices = self.get_indices() + e_indices = expr.get_indices() + + if len(s_indices) != len(e_indices): + return None + + for i in range(len(s_indices)): + s_ind = s_indices[i] + m = s_ind.matches(e_indices[i]) + if m is None: + return None + elif -s_ind in repl_dict.keys() and -repl_dict[-s_ind] != m[s_ind]: + return None + else: + repl_dict.update(m) + + return repl_dict + + def __call__(self, *indices): + deprecate_call() + free_args = self.free_args + indices = list(indices) + if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]: + raise ValueError('incompatible types') + if indices == free_args: + return self + t = self.substitute_indices(*list(zip(free_args, indices))) + + # object is rebuilt in order to make sure that all contracted indices + # get recognized as dummies, but only if there are contracted indices. + if len({i if i.is_up else -i for i in indices}) != len(indices): + return t.func(*t.args) + return t + + # TODO: put this into TensExpr? + def __iter__(self): + deprecate_data() + with ignore_warnings(SymPyDeprecationWarning): + return self.data.__iter__() + + # TODO: put this into TensExpr? + def __getitem__(self, item): + deprecate_data() + with ignore_warnings(SymPyDeprecationWarning): + return self.data[item] + + def _extract_data(self, replacement_dict): + from .array import Array + for k, v in replacement_dict.items(): + if isinstance(k, Tensor) and k.args[0] == self.args[0]: + other = k + array = v + break + else: + raise ValueError("%s not found in %s" % (self, replacement_dict)) + + # TODO: inefficient, this should be done at root level only: + replacement_dict = {k: Array(v) for k, v in replacement_dict.items()} + array = Array(array) + + dum1 = self.dum + dum2 = other.dum + + if len(dum2) > 0: + for pair in dum2: + # allow `dum2` if the contained values are also in `dum1`. + if pair not in dum1: + raise NotImplementedError("%s with contractions is not implemented" % other) + # Remove elements in `dum2` from `dum1`: + dum1 = [pair for pair in dum1 if pair not in dum2] + if len(dum1) > 0: + indices1 = self.get_indices() + indices2 = other.get_indices() + repl = {} + for p1, p2 in dum1: + repl[indices2[p2]] = -indices2[p1] + for pos in (p1, p2): + if indices1[pos].is_up ^ indices2[pos].is_up: + metric = replacement_dict[indices1[pos].tensor_index_type] + if indices1[pos].is_up: + metric = _TensorDataLazyEvaluator.inverse_matrix(metric) + array = self._contract_and_permute_with_metric(metric, array, pos, len(indices2)) + other = other.xreplace(repl).doit() + array = _TensorDataLazyEvaluator.data_contract_dum([array], dum1, len(indices2)) + + free_ind1 = self.get_free_indices() + free_ind2 = other.get_free_indices() + + return self._match_indices_with_other_tensor(array, free_ind1, free_ind2, replacement_dict) + + @property + def data(self): + deprecate_data() + with ignore_warnings(SymPyDeprecationWarning): + return _tensor_data_substitution_dict[self] + + @data.setter + def data(self, data): + deprecate_data() + # TODO: check data compatibility with properties of tensor. + with ignore_warnings(SymPyDeprecationWarning): + _tensor_data_substitution_dict[self] = data + + @data.deleter + def data(self): + deprecate_data() + with ignore_warnings(SymPyDeprecationWarning): + if self in _tensor_data_substitution_dict: + del _tensor_data_substitution_dict[self] + if self.metric in _tensor_data_substitution_dict: + del _tensor_data_substitution_dict[self.metric] + + def _print(self): + indices = [str(ind) for ind in self.indices] + component = self.component + if component.rank > 0: + return ('%s(%s)' % (component.name, ', '.join(indices))) + else: + return ('%s' % component.name) + + def equals(self, other): + if other == 0: + return self.coeff == 0 + other = _sympify(other) + if not isinstance(other, TensExpr): + assert not self.components + return S.One == other + + def _get_compar_comp(self): + t = self.canon_bp() + r = (t.coeff, tuple(t.components), \ + tuple(sorted(t.free)), tuple(sorted(t.dum))) + return r + + return _get_compar_comp(self) == _get_compar_comp(other) + + def contract_metric(self, g): + # if metric is not the same, ignore this step: + if self.component != g: + return self + # in case there are free components, do not perform anything: + if len(self.free) != 0: + return self + + #antisym = g.index_types[0].metric_antisym + if g.symmetry == TensorSymmetry.fully_symmetric(-2): + antisym = 1 + elif g.symmetry == TensorSymmetry.fully_symmetric(2): + antisym = 0 + elif g.symmetry == TensorSymmetry.no_symmetry(2): + antisym = None + else: + raise NotImplementedError + sign = S.One + typ = g.index_types[0] + + if not antisym: + # g(i, -i) + sign = sign*typ.dim + else: + # g(i, -i) + sign = sign*typ.dim + + dp0, dp1 = self.dum[0] + if dp0 < dp1: + # g(i, -i) = -D with antisymmetric metric + sign = -sign + + return sign + + def contract_delta(self, metric): + return self.contract_metric(metric) + + def _eval_rewrite_as_Indexed(self, tens, indices, **kwargs): + from sympy.tensor.indexed import Indexed + # TODO: replace .args[0] with .name: + index_symbols = [i.args[0] for i in self.get_indices()] + expr = Indexed(tens.args[0], *index_symbols) + return self._check_add_Sum(expr, index_symbols) + + def _eval_partial_derivative(self, s: Tensor) -> Expr: + + if not isinstance(s, Tensor): + return S.Zero + else: + + # @a_i/@a_k = delta_i^k + # @a_i/@a^k = g_ij delta^j_k + # @a^i/@a^k = delta^i_k + # @a^i/@a_k = g^ij delta_j^k + # TODO: if there is no metric present, the derivative should be zero? + + if self.head != s.head: + return S.Zero + + # if heads are the same, provide delta and/or metric products + # for every free index pair in the appropriate tensor + # assumed that the free indices are in proper order + # A contravariante index in the derivative becomes covariant + # after performing the derivative and vice versa + + kronecker_delta_list = [1] + + # not guarantee a correct index order + + for (count, (iself, iother)) in enumerate(zip(self.get_free_indices(), s.get_free_indices())): + if iself.tensor_index_type != iother.tensor_index_type: + raise ValueError("index types not compatible") + else: + tensor_index_type = iself.tensor_index_type + tensor_metric = tensor_index_type.metric + dummy = TensorIndex("d_" + str(count), tensor_index_type, + is_up=iself.is_up) + if iself.is_up == iother.is_up: + kroneckerdelta = tensor_index_type.delta(iself, -iother) + else: + kroneckerdelta = ( + TensMul(tensor_metric(iself, dummy), + tensor_index_type.delta(-dummy, -iother)) + ) + kronecker_delta_list.append(kroneckerdelta) + return TensMul.fromiter(kronecker_delta_list).doit(deep=False) + # doit necessary to rename dummy indices accordingly + + +class TensMul(TensExpr, AssocOp): + """ + Product of tensors. + + Parameters + ========== + + coeff : SymPy coefficient of the tensor + args + + Attributes + ========== + + ``components`` : list of ``TensorHead`` of the component tensors + ``types`` : list of nonrepeated ``TensorIndexType`` + ``free`` : list of ``(ind, ipos, icomp)``, see Notes + ``dum`` : list of ``(ipos1, ipos2, icomp1, icomp2)``, see Notes + ``ext_rank`` : rank of the tensor counting the dummy indices + ``rank`` : rank of the tensor + ``coeff`` : SymPy coefficient of the tensor + ``free_args`` : list of the free indices in sorted order + ``is_canon_bp`` : ``True`` if the tensor in in canonical form + + Notes + ===== + + ``args[0]`` list of ``TensorHead`` of the component tensors. + + ``args[1]`` list of ``(ind, ipos, icomp)`` + where ``ind`` is a free index, ``ipos`` is the slot position + of ``ind`` in the ``icomp``-th component tensor. + + ``args[2]`` list of tuples representing dummy indices. + ``(ipos1, ipos2, icomp1, icomp2)`` indicates that the contravariant + dummy index is the ``ipos1``-th slot position in the ``icomp1``-th + component tensor; the corresponding covariant index is + in the ``ipos2`` slot position in the ``icomp2``-th component tensor. + + """ + identity = S.One + + _index_structure: _IndexStructure + + def __new__(cls, *args, **kw_args): + is_canon_bp = kw_args.get('is_canon_bp', False) + args = list(map(_sympify, args)) + + """ + If the internal dummy indices in one arg conflict with the free indices + of the remaining args, we need to rename those internal dummy indices. + """ + free = [get_free_indices(arg) for arg in args] + free = set(itertools.chain(*free)) #flatten free + newargs = [] + for arg in args: + dum_this = set(get_dummy_indices(arg)) + dum_other = [get_dummy_indices(a) for a in newargs] + dum_other = set(itertools.chain(*dum_other)) #flatten dum_other + free_this = set(get_free_indices(arg)) + if len(dum_this.intersection(free)) > 0: + exclude = free_this.union(free, dum_other) + newarg = TensMul._dedupe_indices(arg, exclude) + else: + newarg = arg + newargs.append(newarg) + + args = newargs + + # Flatten: + args = [i for arg in args for i in (arg.args if isinstance(arg, (TensMul, Mul)) else [arg])] + + args, indices, free, dum = TensMul._tensMul_contract_indices(args, replace_indices=False) + + # Data for indices: + index_types = [i.tensor_index_type for i in indices] + index_structure = _IndexStructure(free, dum, index_types, indices, canon_bp=is_canon_bp) + + obj = TensExpr.__new__(cls, *args) + obj._indices = indices + obj._index_types = index_types.copy() + obj._index_structure = index_structure + obj._free = index_structure.free[:] + obj._dum = index_structure.dum[:] + obj._free_indices = {x[0] for x in obj.free} + obj._rank = len(obj.free) + obj._ext_rank = len(obj._index_structure.free) + 2*len(obj._index_structure.dum) + obj._coeff = S.One + obj._is_canon_bp = is_canon_bp + return obj + + index_types = property(lambda self: self._index_types) + free = property(lambda self: self._free) + dum = property(lambda self: self._dum) + free_indices = property(lambda self: self._free_indices) + rank = property(lambda self: self._rank) + ext_rank = property(lambda self: self._ext_rank) + + @staticmethod + def _indices_to_free_dum(args_indices): + free2pos1 = {} + free2pos2 = {} + dummy_data = [] + indices = [] + + # Notation for positions (to better understand the code): + # `pos1`: position in the `args`. + # `pos2`: position in the indices. + + # Example: + # A(i, j)*B(k, m, n)*C(p) + # `pos1` of `n` is 1 because it's in `B` (second `args` of TensMul). + # `pos2` of `n` is 4 because it's the fifth overall index. + + # Counter for the index position wrt the whole expression: + pos2 = 0 + + for pos1, arg_indices in enumerate(args_indices): + + for index in arg_indices: + if not isinstance(index, TensorIndex): + raise TypeError("expected TensorIndex") + if -index in free2pos1: + # Dummy index detected: + other_pos1 = free2pos1.pop(-index) + other_pos2 = free2pos2.pop(-index) + if index.is_up: + dummy_data.append((index, pos1, other_pos1, pos2, other_pos2)) + else: + dummy_data.append((-index, other_pos1, pos1, other_pos2, pos2)) + indices.append(index) + elif index in free2pos1: + raise ValueError("Repeated index: %s" % index) + else: + free2pos1[index] = pos1 + free2pos2[index] = pos2 + indices.append(index) + pos2 += 1 + + free = list(free2pos2.items()) + free_names = [i.name for i in free2pos2.keys()] + + dummy_data.sort(key=lambda x: x[3]) + return indices, free, free_names, dummy_data + + @staticmethod + def _dummy_data_to_dum(dummy_data): + return [(p2a, p2b) for (i, p1a, p1b, p2a, p2b) in dummy_data] + + @staticmethod + def _tensMul_contract_indices(args, replace_indices=True): + replacements = [{} for _ in args] + + #_index_order = all(_has_index_order(arg) for arg in args) + + args_indices = [get_indices(arg) for arg in args] + indices, free, free_names, dummy_data = TensMul._indices_to_free_dum(args_indices) + + cdt = defaultdict(int) + + def dummy_name_gen(tensor_index_type): + nd = str(cdt[tensor_index_type]) + cdt[tensor_index_type] += 1 + return tensor_index_type.dummy_name + '_' + nd + + if replace_indices: + for old_index, pos1cov, pos1contra, pos2cov, pos2contra in dummy_data: + index_type = old_index.tensor_index_type + while True: + dummy_name = dummy_name_gen(index_type) + if dummy_name not in free_names: + break + dummy = old_index.func(dummy_name, index_type, *old_index.args[2:]) + replacements[pos1cov][old_index] = dummy + replacements[pos1contra][-old_index] = -dummy + indices[pos2cov] = dummy + indices[pos2contra] = -dummy + args = [ + arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg + for arg, repl in zip(args, replacements)] + + """ + The order of indices might've changed due to the replacements (e.g. if one of the args is a TensAdd, replacing an index can change the sort order of the terms, thus changing the order of indices returned by its get_indices() method). + To stay on the safe side, we calculate these quantities again. + """ + args_indices = [get_indices(arg) for arg in args] + indices, free, free_names, dummy_data = TensMul._indices_to_free_dum(args_indices) + + dum = TensMul._dummy_data_to_dum(dummy_data) + return args, indices, free, dum + + @staticmethod + def _get_components_from_args(args): + """ + Get a list of ``Tensor`` objects having the same ``TIDS`` if multiplied + by one another. + """ + components = [] + for arg in args: + if not isinstance(arg, TensExpr): + continue + if isinstance(arg, TensAdd): + continue + components.extend(arg.components) + return components + + @staticmethod + def _rebuild_tensors_list(args, index_structure): + indices = index_structure.get_indices() + #tensors = [None for i in components] # pre-allocate list + ind_pos = 0 + for i, arg in enumerate(args): + if not isinstance(arg, TensExpr): + continue + prev_pos = ind_pos + ind_pos += arg.ext_rank + args[i] = Tensor(arg.component, indices[prev_pos:ind_pos]) + + def doit(self, **hints): + is_canon_bp = self._is_canon_bp + deep = hints.get('deep', True) + if deep: + args = [arg.doit(**hints) for arg in self.args] + + """ + There may now be conflicts between dummy indices of different args + (each arg's doit method does not have any information about which + dummy indices are already used in the other args), so we + deduplicate them. + """ + rule = dict(zip(self.args, args)) + rule = self._dedupe_indices_in_rule(rule) + args = [rule[a] for a in self.args] + + else: + args = self.args + + args = [arg for arg in args if arg != self.identity] + + # Extract non-tensor coefficients: + coeff = reduce(lambda a, b: a*b, [arg for arg in args if not isinstance(arg, TensExpr)], S.One) + args = [arg for arg in args if isinstance(arg, TensExpr)] + + if len(args) == 0: + return coeff + + if coeff != self.identity: + args = [coeff] + args + if coeff == 0: + return S.Zero + + if len(args) == 1: + return args[0] + + args, indices, free, dum = TensMul._tensMul_contract_indices(args) + + # Data for indices: + index_types = [i.tensor_index_type for i in indices] + index_structure = _IndexStructure(free, dum, index_types, indices, canon_bp=is_canon_bp) + + obj = self.func(*args) + obj._index_types = index_types + obj._index_structure = index_structure + obj._ext_rank = len(obj._index_structure.free) + 2*len(obj._index_structure.dum) + obj._coeff = coeff + obj._is_canon_bp = is_canon_bp + return obj + + # TODO: this method should be private + # TODO: should this method be renamed _from_components_free_dum ? + @staticmethod + def from_data(coeff, components, free, dum, **kw_args): + return TensMul(coeff, *TensMul._get_tensors_from_components_free_dum(components, free, dum), **kw_args).doit(deep=False) + + @staticmethod + def _get_tensors_from_components_free_dum(components, free, dum): + """ + Get a list of ``Tensor`` objects by distributing ``free`` and ``dum`` indices on the ``components``. + """ + index_structure = _IndexStructure.from_components_free_dum(components, free, dum) + indices = index_structure.get_indices() + tensors = [None for i in components] # pre-allocate list + + # distribute indices on components to build a list of tensors: + ind_pos = 0 + for i, component in enumerate(components): + prev_pos = ind_pos + ind_pos += component.rank + tensors[i] = Tensor(component, indices[prev_pos:ind_pos]) + return tensors + + def _get_free_indices_set(self): + return {i[0] for i in self.free} + + def _get_dummy_indices_set(self): + dummy_pos = set(itertools.chain(*self.dum)) + return {idx for i, idx in enumerate(self._index_structure.get_indices()) if i in dummy_pos} + + def _get_position_offset_for_indices(self): + arg_offset = [None for i in range(self.ext_rank)] + counter = 0 + for arg in self.args: + if not isinstance(arg, TensExpr): + continue + for j in range(arg.ext_rank): + arg_offset[j + counter] = counter + counter += arg.ext_rank + return arg_offset + + @property + def free_args(self): + return sorted([x[0] for x in self.free]) + + @property + def components(self): + return self._get_components_from_args(self.args) + + @property + def free_in_args(self): + arg_offset = self._get_position_offset_for_indices() + argpos = self._get_indices_to_args_pos() + return [(ind, pos-arg_offset[pos], argpos[pos]) for (ind, pos) in self.free] + + @property + def coeff(self): + # return Mul.fromiter([c for c in self.args if not isinstance(c, TensExpr)]) + return self._coeff + + @property + def nocoeff(self): + return self.func(*self.args, 1/self.coeff).doit(deep=False) + + @property + def dum_in_args(self): + arg_offset = self._get_position_offset_for_indices() + argpos = self._get_indices_to_args_pos() + return [(p1-arg_offset[p1], p2-arg_offset[p2], argpos[p1], argpos[p2]) for p1, p2 in self.dum] + + def equals(self, other): + if other == 0: + return self.coeff == 0 + other = _sympify(other) + if not isinstance(other, TensExpr): + assert not self.components + return self.coeff == other + + return self.canon_bp() == other.canon_bp() + + def get_indices(self): + """ + Returns the list of indices of the tensor. + + Explanation + =========== + + The indices are listed in the order in which they appear in the + component tensors. + The dummy indices are given a name which does not collide with + the names of the free indices. + + Examples + ======== + + >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads + >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') + >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz) + >>> g = Lorentz.metric + >>> p, q = tensor_heads('p,q', [Lorentz]) + >>> t = p(m1)*g(m0,m2) + >>> t.get_indices() + [m1, m0, m2] + >>> t2 = p(m1)*g(-m1, m2) + >>> t2.get_indices() + [L_0, -L_0, m2] + """ + return self._indices + + def get_free_indices(self) -> list[TensorIndex]: + """ + Returns the list of free indices of the tensor. + + Explanation + =========== + + The indices are listed in the order in which they appear in the + component tensors. + + Examples + ======== + + >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads + >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') + >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz) + >>> g = Lorentz.metric + >>> p, q = tensor_heads('p,q', [Lorentz]) + >>> t = p(m1)*g(m0,m2) + >>> t.get_free_indices() + [m1, m0, m2] + >>> t2 = p(m1)*g(-m1, m2) + >>> t2.get_free_indices() + [m2] + """ + return self._index_structure.get_free_indices() + + def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr: + return self.func(*[arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg for arg in self.args]) + + def split(self): + """ + Returns a list of tensors, whose product is ``self``. + + Explanation + =========== + + Dummy indices contracted among different tensor components + become free indices with the same name as the one used to + represent the dummy indices. + + Examples + ======== + + >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads, TensorSymmetry + >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') + >>> a, b, c, d = tensor_indices('a,b,c,d', Lorentz) + >>> A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) + >>> t = A(a,b)*B(-b,c) + >>> t + A(a, L_0)*B(-L_0, c) + >>> t.split() + [A(a, L_0), B(-L_0, c)] + """ + if self.args == (): + return [self] + splitp = [] + res = 1 + for arg in self.args: + if isinstance(arg, Tensor): + splitp.append(res*arg) + res = 1 + else: + res *= arg + return splitp + + def _eval_expand_mul(self, **hints): + args1 = [arg.args if isinstance(arg, (Add, TensAdd)) else (arg,) for arg in self.args] + return TensAdd(*[ + TensMul(*i).doit(deep=False) for i in itertools.product(*args1)] + ) + + def __neg__(self): + return TensMul(S.NegativeOne, self, is_canon_bp=self._is_canon_bp).doit(deep=False) + + def __getitem__(self, item): + deprecate_data() + with ignore_warnings(SymPyDeprecationWarning): + return self.data[item] + + def _get_args_for_traditional_printer(self): + args = list(self.args) + if self.coeff.could_extract_minus_sign(): + # expressions like "-A(a)" + sign = "-" + if args[0] == S.NegativeOne: + args = args[1:] + else: + args[0] = -args[0] + else: + sign = "" + return sign, args + + def _sort_args_for_sorted_components(self): + """ + Returns the ``args`` sorted according to the components commutation + properties. + + Explanation + =========== + + The sorting is done taking into account the commutation group + of the component tensors. + """ + cv = [arg for arg in self.args if isinstance(arg, TensExpr)] + sign = 1 + n = len(cv) - 1 + for i in range(n): + for j in range(n, i, -1): + c = cv[j-1].commutes_with(cv[j]) + # if `c` is `None`, it does neither commute nor anticommute, skip: + if c not in (0, 1): + continue + typ1 = sorted(set(cv[j-1].component.index_types), key=lambda x: x.name) + typ2 = sorted(set(cv[j].component.index_types), key=lambda x: x.name) + if (typ1, cv[j-1].component.name) > (typ2, cv[j].component.name): + cv[j-1], cv[j] = cv[j], cv[j-1] + # if `c` is 1, the anticommute, so change sign: + if c: + sign = -sign + + coeff = sign * self.coeff + if coeff != 1: + return [coeff] + cv + return cv + + def sorted_components(self): + """ + Returns a tensor product with sorted components. + """ + return TensMul(*self._sort_args_for_sorted_components()).doit(deep=False) + + def perm2tensor(self, g, is_canon_bp=False): + """ + Returns the tensor corresponding to the permutation ``g`` + + For further details, see the method in ``TIDS`` with the same name. + """ + return perm2tensor(self, g, is_canon_bp=is_canon_bp) + + def canon_bp(self): + """ + Canonicalize using the Butler-Portugal algorithm for canonicalization + under monoterm symmetries. + + Examples + ======== + + >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, TensorSymmetry + >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') + >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz) + >>> A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2)) + >>> t = A(m0,-m1)*A(m1,-m0) + >>> t.canon_bp() + -A(L_0, L_1)*A(-L_0, -L_1) + >>> t = A(m0,-m1)*A(m1,-m2)*A(m2,-m0) + >>> t.canon_bp() + 0 + """ + if self._is_canon_bp: + return self + expr = self.expand() + if isinstance(expr, TensAdd): + return expr.canon_bp() + if not expr.components: + return expr + expr = expr.doit(deep=False) #make sure self.coeff is populated correctly + t = expr.sorted_components() + g, dummies, msym = t._index_structure.indices_canon_args() + v = components_canon_args(t.components) + can = canonicalize(g, dummies, msym, *v) + if can == 0: + return S.Zero + tmul = t.perm2tensor(can, True) + return tmul + + def contract_delta(self, delta): + t = self.contract_metric(delta) + return t + + def _get_indices_to_args_pos(self): + """ + Get a dict mapping the index position to TensMul's argument number. + """ + pos_map = {} + pos_counter = 0 + for arg_i, arg in enumerate(self.args): + if not isinstance(arg, TensExpr): + continue + assert isinstance(arg, Tensor) + for i in range(arg.ext_rank): + pos_map[pos_counter] = arg_i + pos_counter += 1 + return pos_map + + def contract_metric(self, g): + """ + Raise or lower indices with the metric ``g``. + + Parameters + ========== + + g : metric + + Notes + ===== + + See the ``TensorIndexType`` docstring for the contraction conventions. + + Examples + ======== + + >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads + >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') + >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz) + >>> g = Lorentz.metric + >>> p, q = tensor_heads('p,q', [Lorentz]) + >>> t = p(m0)*q(m1)*g(-m0, -m1) + >>> t.canon_bp() + metric(L_0, L_1)*p(-L_0)*q(-L_1) + >>> t.contract_metric(g).canon_bp() + p(L_0)*q(-L_0) + """ + expr = self.expand().doit(deep=False) + if self != expr: + expr = canon_bp(expr) + return contract_metric(expr, g) + pos_map = self._get_indices_to_args_pos() + args = list(self.args) + + #antisym = g.index_types[0].metric_antisym + if g.symmetry == TensorSymmetry.fully_symmetric(-2): + antisym = 1 + elif g.symmetry == TensorSymmetry.fully_symmetric(2): + antisym = 0 + elif g.symmetry == TensorSymmetry.no_symmetry(2): + antisym = None + else: + raise NotImplementedError + + # list of positions of the metric ``g`` inside ``args`` + gpos = [i for i, x in enumerate(self.args) if isinstance(x, Tensor) and x.component == g] + if not gpos: + return self + + # Sign is either 1 or -1, to correct the sign after metric contraction + # (for spinor indices). + sign = 1 + dum = self.dum[:] + free = self.free[:] + elim = set() + for gposx in gpos: + if gposx in elim: + continue + free1 = [x for x in free if pos_map[x[1]] == gposx] + dum1 = [x for x in dum if pos_map[x[0]] == gposx or pos_map[x[1]] == gposx] + if not dum1: + continue + elim.add(gposx) + # subs with the multiplication neutral element, that is, remove it: + args[gposx] = 1 + if len(dum1) == 2: + if not antisym: + dum10, dum11 = dum1 + if pos_map[dum10[1]] == gposx: + # the index with pos p0 contravariant + p0 = dum10[0] + else: + # the index with pos p0 is covariant + p0 = dum10[1] + if pos_map[dum11[1]] == gposx: + # the index with pos p1 is contravariant + p1 = dum11[0] + else: + # the index with pos p1 is covariant + p1 = dum11[1] + + dum.append((p0, p1)) + else: + dum10, dum11 = dum1 + # change the sign to bring the indices of the metric to contravariant + # form; change the sign if dum10 has the metric index in position 0 + if pos_map[dum10[1]] == gposx: + # the index with pos p0 is contravariant + p0 = dum10[0] + if dum10[1] == 1: + sign = -sign + else: + # the index with pos p0 is covariant + p0 = dum10[1] + if dum10[0] == 0: + sign = -sign + if pos_map[dum11[1]] == gposx: + # the index with pos p1 is contravariant + p1 = dum11[0] + sign = -sign + else: + # the index with pos p1 is covariant + p1 = dum11[1] + + dum.append((p0, p1)) + + elif len(dum1) == 1: + if not antisym: + dp0, dp1 = dum1[0] + if pos_map[dp0] == pos_map[dp1]: + # g(i, -i) + typ = g.index_types[0] + sign = sign*typ.dim + + else: + # g(i0, i1)*p(-i1) + if pos_map[dp0] == gposx: + p1 = dp1 + else: + p1 = dp0 + + ind, p = free1[0] + free.append((ind, p1)) + else: + dp0, dp1 = dum1[0] + if pos_map[dp0] == pos_map[dp1]: + # g(i, -i) + typ = g.index_types[0] + sign = sign*typ.dim + + if dp0 < dp1: + # g(i, -i) = -D with antisymmetric metric + sign = -sign + else: + # g(i0, i1)*p(-i1) + if pos_map[dp0] == gposx: + p1 = dp1 + if dp0 == 0: + sign = -sign + else: + p1 = dp0 + ind, p = free1[0] + free.append((ind, p1)) + dum = [x for x in dum if x not in dum1] + free = [x for x in free if x not in free1] + + # shift positions: + shift = 0 + shifts = [0]*len(args) + for i in range(len(args)): + if i in elim: + shift += 2 + continue + shifts[i] = shift + free = [(ind, p - shifts[pos_map[p]]) for (ind, p) in free if pos_map[p] not in elim] + dum = [(p0 - shifts[pos_map[p0]], p1 - shifts[pos_map[p1]]) for p0, p1 in dum if pos_map[p0] not in elim and pos_map[p1] not in elim] + + res = ( sign*TensMul(*args) ).doit(deep=False) + if not isinstance(res, TensExpr): + return res + im = _IndexStructure.from_components_free_dum(res.components, free, dum) + return res._set_new_index_structure(im) + + def _set_new_index_structure(self, im, is_canon_bp=False): + indices = im.get_indices() + return self._set_indices(*indices, is_canon_bp=is_canon_bp) + + def _set_indices(self, *indices, is_canon_bp=False, **kw_args): + if len(indices) != self.ext_rank: + raise ValueError("indices length mismatch") + args = list(self.args) + pos = 0 + for i, arg in enumerate(args): + if not isinstance(arg, TensExpr): + continue + assert isinstance(arg, Tensor) + ext_rank = arg.ext_rank + args[i] = arg._set_indices(*indices[pos:pos+ext_rank]) + pos += ext_rank + return TensMul(*args, is_canon_bp=is_canon_bp).doit(deep=False) + + @staticmethod + def _index_replacement_for_contract_metric(args, free, dum): + for arg in args: + if not isinstance(arg, TensExpr): + continue + assert isinstance(arg, Tensor) + + def substitute_indices(self, *index_tuples): + new_args = [] + for arg in self.args: + if isinstance(arg, TensExpr): + arg = arg.substitute_indices(*index_tuples) + new_args.append(arg) + return TensMul(*new_args).doit(deep=False) + + def __call__(self, *indices): + deprecate_call() + free_args = self.free_args + indices = list(indices) + if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]: + raise ValueError('incompatible types') + if indices == free_args: + return self + t = self.substitute_indices(*list(zip(free_args, indices))) + + # object is rebuilt in order to make sure that all contracted indices + # get recognized as dummies, but only if there are contracted indices. + if len({i if i.is_up else -i for i in indices}) != len(indices): + return t.func(*t.args) + return t + + def _extract_data(self, replacement_dict): + args_indices, arrays = zip(*[arg._extract_data(replacement_dict) for arg in self.args if isinstance(arg, TensExpr)]) + coeff = reduce(operator.mul, [a for a in self.args if not isinstance(a, TensExpr)], S.One) + indices, free, free_names, dummy_data = TensMul._indices_to_free_dum(args_indices) + dum = TensMul._dummy_data_to_dum(dummy_data) + ext_rank = self.ext_rank + free.sort(key=lambda x: x[1]) + free_indices = [i[0] for i in free] + return free_indices, coeff*_TensorDataLazyEvaluator.data_contract_dum(arrays, dum, ext_rank) + + @property + def data(self): + deprecate_data() + with ignore_warnings(SymPyDeprecationWarning): + dat = _tensor_data_substitution_dict[self.expand()] + return dat + + @data.setter + def data(self, data): + deprecate_data() + raise ValueError("Not possible to set component data to a tensor expression") + + @data.deleter + def data(self): + deprecate_data() + raise ValueError("Not possible to delete component data to a tensor expression") + + def __iter__(self): + deprecate_data() + with ignore_warnings(SymPyDeprecationWarning): + if self.data is None: + raise ValueError("No iteration on abstract tensors") + return self.data.__iter__() + + @staticmethod + def _dedupe_indices(new, exclude): + """ + exclude: set + new: TensExpr + + If ``new`` has any dummy indices that are in ``exclude``, return a version + of new with those indices replaced. If no replacements are needed, + return None + + """ + exclude = set(exclude) + dums_new = set(get_dummy_indices(new)) + free_new = set(get_free_indices(new)) + + conflicts = dums_new.intersection(exclude) + if len(conflicts) == 0: + return None + + """ + ``exclude_for_gen`` is to be passed to ``_IndexStructure._get_generator_for_dummy_indices()``. + Since the latter does not use the index position for anything, we just + set it as ``None`` here. + """ + exclude.update(dums_new) + exclude.update(free_new) + exclude_for_gen = [(i, None) for i in exclude] + gen = _IndexStructure._get_generator_for_dummy_indices(exclude_for_gen) + repl = {} + for d in conflicts: + if -d in repl.keys(): + continue + newname = gen(d.tensor_index_type) + new_d = d.func(newname, *d.args[1:]) + repl[d] = new_d + repl[-d] = -new_d + + if len(repl) == 0: + return None + + new_renamed = new._replace_indices(repl) + return new_renamed + + def _dedupe_indices_in_rule(self, rule): + """ + rule: dict + + This applies TensMul._dedupe_indices on all values of rule. + + """ + index_rules = {k:v for k,v in rule.items() if isinstance(k, TensorIndex)} + other_rules = {k:v for k,v in rule.items() if k not in index_rules.keys()} + exclude = set(self.get_indices()) + + newrule = {} + newrule.update(index_rules) + exclude.update(index_rules.keys()) + exclude.update(index_rules.values()) + for old, new in other_rules.items(): + new_renamed = TensMul._dedupe_indices(new, exclude) + if old == new or new_renamed is None: + newrule[old] = new + else: + newrule[old] = new_renamed + exclude.update(get_indices(new_renamed)) + return newrule + + def _eval_subs(self, old, new): + """ + If new is an index which is already present in self as a dummy, the dummies in self should be renamed. + """ + + if not isinstance(new, TensorIndex): + return None + + exclude = {new} + self_renamed = self._dedupe_indices(self, exclude) + if self_renamed is None: + return None + else: + return self_renamed._subs(old, new).doit(deep=False) + + def _eval_rewrite_as_Indexed(self, *args, **kwargs): + from sympy.concrete.summations import Sum + index_symbols = [i.args[0] for i in self.get_indices()] + args = [arg.args[0] if isinstance(arg, Sum) else arg for arg in args] + expr = Mul.fromiter(args) + return self._check_add_Sum(expr, index_symbols) + + def _eval_partial_derivative(self, s): + # Evaluation like Mul + terms = [] + for i, arg in enumerate(self.args): + # checking whether some tensor instance is differentiated + # or some other thing is necessary, but ugly + if isinstance(arg, TensExpr): + d = arg._eval_partial_derivative(s) + else: + # do not call diff is s is no symbol + if s._diff_wrt: + d = arg._eval_derivative(s) + else: + d = S.Zero + if d: + terms.append(TensMul.fromiter(self.args[:i] + (d,) + self.args[i + 1:]).doit(deep=False)) + return TensAdd.fromiter(terms).doit(deep=False) + + + def _matches_commutative(self, expr, repl_dict=None, old=False): + """ + Match assuming all tensors commute. But note that we are not assuming anything about their symmetry under index permutations. + """ + #Take care of the various possible types for expr. + if not isinstance(expr, TensMul): + if isinstance(expr, (TensExpr, Expr)): + expr = TensMul(expr) + else: + return None + + #The code that follows assumes expr is a TensMul + + if repl_dict is None: + repl_dict = {} + else: + repl_dict = repl_dict.copy() + + #Make sure that none of the dummy indices in self, expr conflict with the values already present in repl_dict. This may happen due to automatic index relabelling when rem_query and rem_expr are formed later on in this function (it calls itself recursively). + indices = [k for k in repl_dict.values() if isinstance(k ,TensorIndex)] + + def dedupe(expr): + renamed = TensMul._dedupe_indices(expr, indices) + if renamed is not None: + return renamed + else: + return expr + + self = dedupe(self) + expr = dedupe(expr) + + #Find the non-tensor part of expr. This need not be the same as expr.coeff when expr.doit() has not been called. + expr_coeff = reduce(lambda a, b: a*b, [arg for arg in expr.args if not isinstance(arg, TensExpr)], S.One) + + # handle simple patterns + if self == expr: + return repl_dict + + if len(_get_wilds(self)) == 0: + return self._matches_simple(expr, repl_dict, old) + + def siftkey(arg): + if isinstance(arg, WildTensor): + return "WildTensor" + elif isinstance(arg, (Tensor, TensExpr)): + return "Tensor" + else: + return "coeff" + + query_sifted = sift(self.args, siftkey) + expr_sifted = sift(expr.args, siftkey) + + #Sanity checks + if "coeff" in query_sifted.keys(): + if TensMul(*query_sifted["coeff"]).doit(deep=False) != self.coeff: + raise NotImplementedError(f"Found something that we do not know to handle: {query_sifted['coeff']}") + if "coeff" in expr_sifted.keys(): + if TensMul(*expr_sifted["coeff"]).doit(deep=False) != expr_coeff: + raise NotImplementedError(f"Found something that we do not know to handle: {expr_sifted['coeff']}") + + query_tens_heads = {tuple(getattr(x, "components", [])) for x in query_sifted["Tensor"]} #We use getattr because, e.g. TensAdd does not have the 'components' attribute. + expr_tens_heads = {tuple(getattr(x, "components", [])) for x in expr_sifted["Tensor"]} + if not query_tens_heads.issubset(expr_tens_heads): + #Some tensorheads in self are not present in the expr + return None + + #Try to match all non-wild tensors of self with tensors that compose expr + if len(query_sifted["Tensor"]) > 0: + q_tensor = query_sifted["Tensor"][0] + """ + We need to iterate over all possible symmetrized forms of q_tensor since the matches given by some of them may map dummy indices to free indices; the information about which indices are dummy/free will only be available later, when we are doing rem_q.matches(rem_e) + """ + for q_tens in q_tensor._get_symmetrized_forms(): + for e in expr_sifted["Tensor"]: + if isinstance(q_tens, TensMul): + #q_tensor got a minus sign due to this permutation. + sign = -1 + else: + sign = 1 + + """ + _matches is used here since we are already iterating over index permutations of q_tensor. Also note that the sign is removed from q_tensor, and will later be put into rem_q. + """ + m = (sign*q_tens)._matches(e) + if m is None: + continue + + rem_query = self.func(sign, *[a for a in self.args if a != q_tensor]).doit(deep=False) + rem_expr = expr.func(*[a for a in expr.args if a != e]).doit(deep=False) + tmp_repl = {} + tmp_repl.update(repl_dict) + tmp_repl.update(m) + rem_m = rem_query.matches(rem_expr, repl_dict=tmp_repl) + if rem_m is not None: + #Check that contracted indices are not mapped to different indices. + internally_consistent = True + for k in rem_m.keys(): + if isinstance(k,TensorIndex): + if -k in rem_m.keys() and rem_m[-k] != -rem_m[k]: + internally_consistent = False + break + if internally_consistent: + repl_dict.update(rem_m) + return repl_dict + + return None + + #Try to match WildTensor instances which have indices + matched_e_tensors = [] + remaining_e_tensors = expr_sifted["Tensor"] + indexless_wilds, wilds = sift(query_sifted["WildTensor"], lambda x: len(x.get_free_indices()) == 0, binary=True) + + for w in wilds: + free_this_wild = set(w.get_free_indices()) + tensors_to_try = [] + for t in remaining_e_tensors: + free = t.get_free_indices() + shares_indices_with_wild = True + for i in free: + if all(j.matches(i) is None for j in free_this_wild): + #The index i matches none of the indices in free_this_wild + shares_indices_with_wild = False + if shares_indices_with_wild: + tensors_to_try.append(t) + + m = w.matches(TensMul(*tensors_to_try).doit(deep=False) ) + if m is None: + return None + else: + for tens in tensors_to_try: + matched_e_tensors.append(tens) + repl_dict.update(m) + + #Try to match indexless WildTensor instances + remaining_e_tensors = [t for t in expr_sifted["Tensor"] if t not in matched_e_tensors] + if len(indexless_wilds) > 0: + #If there are any remaining tensors, match them with the indexless WildTensor + m = indexless_wilds[0].matches( TensMul(1,*remaining_e_tensors).doit(deep=False) ) + if m is None: + return None + else: + repl_dict.update(m) + elif len(remaining_e_tensors) > 0: + return None + + #Try to match the non-tensorial coefficient + m = self.coeff.matches(expr_coeff, old=old) + if m is None: + return None + else: + repl_dict.update(m) + + return repl_dict + + def matches(self, expr, repl_dict=None, old=False): + expr = sympify(expr) + + if repl_dict is None: + repl_dict = {} + else: + repl_dict = repl_dict.copy() + + commute = all(arg.component.comm == 0 for arg in expr.args if isinstance(arg, Tensor)) + if commute: + return self._matches_commutative(expr, repl_dict, old) + else: + raise NotImplementedError("Tensor matching not implemented for non-commuting tensors") + +class TensorElement(TensExpr): + """ + Tensor with evaluated components. + + Examples + ======== + + >>> from sympy.tensor.tensor import TensorIndexType, TensorHead, TensorSymmetry + >>> from sympy import symbols + >>> L = TensorIndexType("L") + >>> i, j, k = symbols("i j k") + >>> A = TensorHead("A", [L, L], TensorSymmetry.fully_symmetric(2)) + >>> A(i, j).get_free_indices() + [i, j] + + If we want to set component ``i`` to a specific value, use the + ``TensorElement`` class: + + >>> from sympy.tensor.tensor import TensorElement + >>> te = TensorElement(A(i, j), {i: 2}) + + As index ``i`` has been accessed (``{i: 2}`` is the evaluation of its 3rd + element), the free indices will only contain ``j``: + + >>> te.get_free_indices() + [j] + """ + + def __new__(cls, expr, index_map): + if not isinstance(expr, Tensor): + # remap + if not isinstance(expr, TensExpr): + raise TypeError("%s is not a tensor expression" % expr) + return expr.func(*[TensorElement(arg, index_map) for arg in expr.args]) + expr_free_indices = expr.get_free_indices() + name_translation = {i.args[0]: i for i in expr_free_indices} + index_map = {name_translation.get(index, index): value for index, value in index_map.items()} + index_map = {index: value for index, value in index_map.items() if index in expr_free_indices} + if len(index_map) == 0: + return expr + free_indices = [i for i in expr_free_indices if i not in index_map.keys()] + index_map = Dict(index_map) + obj = TensExpr.__new__(cls, expr, index_map) + obj._free_indices = free_indices + return obj + + @property + def free(self): + return [(index, i) for i, index in enumerate(self.get_free_indices())] + + @property + def dum(self): + # TODO: inherit dummies from expr + return [] + + @property + def expr(self): + return self._args[0] + + @property + def index_map(self): + return self._args[1] + + @property + def coeff(self): + return S.One + + @property + def nocoeff(self): + return self + + def get_free_indices(self): + return self._free_indices + + def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr: + # TODO: can be improved: + return self.xreplace(repl) + + def get_indices(self): + return self.get_free_indices() + + def _extract_data(self, replacement_dict): + ret_indices, array = self.expr._extract_data(replacement_dict) + index_map = self.index_map + slice_tuple = tuple(index_map.get(i, slice(None)) for i in ret_indices) + ret_indices = [i for i in ret_indices if i not in index_map] + array = array.__getitem__(slice_tuple) + return ret_indices, array + + +class WildTensorHead(TensorHead): + """ + A wild object that is used to create ``WildTensor`` instances + + Explanation + =========== + + Examples + ======== + >>> from sympy.tensor.tensor import TensorHead, TensorIndex, WildTensorHead, TensorIndexType + >>> R3 = TensorIndexType('R3', dim=3) + >>> p = TensorIndex('p', R3) + >>> q = TensorIndex('q', R3) + + A WildTensorHead can be created without specifying a ``TensorIndexType`` + + >>> W = WildTensorHead("W") + + Calling it with a ``TensorIndex`` creates a ``WildTensor`` instance. + + >>> type(W(p)) + + + The ``TensorIndexType`` is automatically detected from the index that is passed + + >>> W(p).component + W(R3) + + Calling it with no indices returns an object that can match tensors with any number of indices. + + >>> K = TensorHead('K', [R3]) + >>> Q = TensorHead('Q', [R3, R3]) + >>> W().matches(K(p)) + {W: K(p)} + >>> W().matches(Q(p,q)) + {W: Q(p, q)} + + If you want to ignore the order of indices while matching, pass ``unordered_indices=True``. + + >>> U = WildTensorHead("U", unordered_indices=True) + >>> W(p,q).matches(Q(q,p)) + >>> U(p,q).matches(Q(q,p)) + {U(R3,R3): _WildTensExpr(Q(q, p))} + + Parameters + ========== + name : name of the tensor + unordered_indices : whether the order of the indices matters for matching + (default: False) + + See also + ======== + ``WildTensor`` + ``TensorHead`` + + """ + def __new__(cls, name, index_types=None, symmetry=None, comm=0, unordered_indices=False): + if isinstance(name, str): + name_symbol = Symbol(name) + elif isinstance(name, Symbol): + name_symbol = name + else: + raise ValueError("invalid name") + + if index_types is None: + index_types = [] + + if symmetry is None: + symmetry = TensorSymmetry.no_symmetry(len(index_types)) + else: + assert symmetry.rank == len(index_types) + + if symmetry != TensorSymmetry.no_symmetry(len(index_types)): + raise NotImplementedError("Wild matching based on symmetry is not implemented.") + + obj = Basic.__new__(cls, name_symbol, Tuple(*index_types), sympify(symmetry), sympify(comm), sympify(unordered_indices)) + + return obj + + @property + def unordered_indices(self): + return self.args[4] + + def __call__(self, *indices, **kwargs): + tensor = WildTensor(self, indices, **kwargs) + return tensor.doit() + + +class WildTensor(Tensor): + """ + A wild object which matches ``Tensor`` instances + + Explanation + =========== + This is instantiated by attaching indices to a ``WildTensorHead`` instance. + + Examples + ======== + >>> from sympy.tensor.tensor import TensorHead, TensorIndex, WildTensorHead, TensorIndexType + >>> W = WildTensorHead("W") + >>> R3 = TensorIndexType('R3', dim=3) + >>> p = TensorIndex('p', R3) + >>> q = TensorIndex('q', R3) + >>> K = TensorHead('K', [R3]) + >>> Q = TensorHead('Q', [R3, R3]) + + Matching also takes the indices into account + >>> W(p).matches(K(p)) + {W(R3): _WildTensExpr(K(p))} + >>> W(p).matches(K(q)) + >>> W(p).matches(K(-p)) + + If you want to match objects with any number of indices, just use a ``WildTensor`` with no indices. + >>> W().matches(K(p)) + {W: K(p)} + >>> W().matches(Q(p,q)) + {W: Q(p, q)} + + See Also + ======== + ``WildTensorHead`` + ``Tensor`` + + """ + def __new__(cls, tensor_head, indices, **kw_args): + is_canon_bp = kw_args.pop("is_canon_bp", False) + + if tensor_head.func == TensorHead: + """ + If someone tried to call WildTensor by supplying a TensorHead (not a WildTensorHead), return a normal tensor instead. This is helpful when using subs on an expression to replace occurrences of a WildTensorHead with a TensorHead. + """ + return Tensor(tensor_head, indices, is_canon_bp=is_canon_bp, **kw_args) + elif tensor_head.func == _WildTensExpr: + return tensor_head(*indices) + + indices = cls._parse_indices(tensor_head, indices) + index_types = [ind.tensor_index_type for ind in indices] + tensor_head = tensor_head.func( + tensor_head.name, + index_types, + symmetry=None, + comm=tensor_head.comm, + unordered_indices=tensor_head.unordered_indices, + ) + + obj = Basic.__new__(cls, tensor_head, Tuple(*indices)) + obj.name = tensor_head.name + obj._index_structure = _IndexStructure.from_indices(*indices) + obj._free = obj._index_structure.free[:] + obj._dum = obj._index_structure.dum[:] + obj._ext_rank = obj._index_structure._ext_rank + obj._coeff = S.One + obj._nocoeff = obj + obj._component = tensor_head + obj._components = [tensor_head] + if tensor_head.rank != len(indices): + raise ValueError("wrong number of indices") + obj.is_canon_bp = is_canon_bp + obj._index_map = obj._build_index_map(indices, obj._index_structure) + + return obj + + + def matches(self, expr, repl_dict=None, old=False): + if not isinstance(expr, TensExpr) and expr != S(1): + return None + + if repl_dict is None: + repl_dict = {} + else: + repl_dict = repl_dict.copy() + + if len(self.indices) > 0: + if not hasattr(expr, "get_free_indices"): + return None + expr_indices = expr.get_free_indices() + if len(expr_indices) != len(self.indices): + return None + if self._component.unordered_indices: + m = self._match_indices_ignoring_order(expr) + if m is None: + return None + else: + repl_dict.update(m) + else: + for i in range(len(expr_indices)): + m = self.indices[i].matches(expr_indices[i]) + if m is None: + return None + else: + repl_dict.update(m) + + repl_dict[self.component] = _WildTensExpr(expr) + else: + #If no indices were passed to the WildTensor, it may match tensors with any number of indices. + repl_dict[self] = expr + + return repl_dict + + def _match_indices_ignoring_order(self, expr, repl_dict=None, old=False): + """ + Helper method for matches. Checks if the indices of self and expr + match disregarding index ordering. + """ + if repl_dict is None: + repl_dict = {} + else: + repl_dict = repl_dict.copy() + + def siftkey(ind): + if isinstance(ind, WildTensorIndex): + if ind.ignore_updown: + return "wild, updown" + else: + return "wild" + else: + return "nonwild" + + indices_sifted = sift(self.indices, siftkey) + + matched_indices = [] + expr_indices_remaining = expr.get_indices() + for ind in indices_sifted["nonwild"]: + matched_this_ind = False + for e_ind in expr_indices_remaining: + if e_ind in matched_indices: + continue + m = ind.matches(e_ind) + if m is not None: + matched_this_ind = True + repl_dict.update(m) + matched_indices.append(e_ind) + break + if not matched_this_ind: + return None + + expr_indices_remaining = [i for i in expr_indices_remaining if i not in matched_indices] + for ind in indices_sifted["wild"]: + matched_this_ind = False + for e_ind in expr_indices_remaining: + m = ind.matches(e_ind) + if m is not None: + if -ind in repl_dict.keys() and -repl_dict[-ind] != m[ind]: + return None + matched_this_ind = True + repl_dict.update(m) + matched_indices.append(e_ind) + break + if not matched_this_ind: + return None + + expr_indices_remaining = [i for i in expr_indices_remaining if i not in matched_indices] + for ind in indices_sifted["wild, updown"]: + matched_this_ind = False + for e_ind in expr_indices_remaining: + m = ind.matches(e_ind) + if m is not None: + if -ind in repl_dict.keys() and -repl_dict[-ind] != m[ind]: + return None + matched_this_ind = True + repl_dict.update(m) + matched_indices.append(e_ind) + break + if not matched_this_ind: + return None + + if len(matched_indices) < len(self.indices): + return None + else: + return repl_dict + +class WildTensorIndex(TensorIndex): + """ + A wild object that matches TensorIndex instances. + + Examples + ======== + >>> from sympy.tensor.tensor import TensorIndex, TensorIndexType, WildTensorIndex + >>> R3 = TensorIndexType('R3', dim=3) + >>> p = TensorIndex("p", R3) + + By default, covariant indices only match with covariant indices (and + similarly for contravariant) + + >>> q = WildTensorIndex("q", R3) + >>> (q).matches(p) + {q: p} + >>> (q).matches(-p) + + If you want matching to ignore whether the index is co/contra-variant, set + ignore_updown=True + + >>> r = WildTensorIndex("r", R3, ignore_updown=True) + >>> (r).matches(-p) + {r: -p} + >>> (r).matches(p) + {r: p} + + Parameters + ========== + name : name of the index (string), or ``True`` if you want it to be + automatically assigned + tensor_index_type : ``TensorIndexType`` of the index + is_up : flag for contravariant index (is_up=True by default) + ignore_updown : bool, Whether this should match both co- and contra-variant + indices (default:False) + """ + def __new__(cls, name, tensor_index_type, is_up=True, ignore_updown=False): + if isinstance(name, str): + name_symbol = Symbol(name) + elif isinstance(name, Symbol): + name_symbol = name + elif name is True: + name = "_i{}".format(len(tensor_index_type._autogenerated)) + name_symbol = Symbol(name) + tensor_index_type._autogenerated.append(name_symbol) + else: + raise ValueError("invalid name") + + is_up = sympify(is_up) + ignore_updown = sympify(ignore_updown) + return Basic.__new__(cls, name_symbol, tensor_index_type, is_up, ignore_updown) + + @property + def ignore_updown(self): + return self.args[3] + + def __neg__(self): + t1 = WildTensorIndex(self.name, self.tensor_index_type, + (not self.is_up), self.ignore_updown) + return t1 + + def matches(self, expr, repl_dict=None, old=False): + if not isinstance(expr, TensorIndex): + return None + if self.tensor_index_type != expr.tensor_index_type: + return None + if not self.ignore_updown: + if self.is_up != expr.is_up: + return None + + if repl_dict is None: + repl_dict = {} + else: + repl_dict = repl_dict.copy() + + repl_dict[self] = expr + return repl_dict + + +class _WildTensExpr(Basic): + """ + INTERNAL USE ONLY + + This is an object that helps with replacement of WildTensors in expressions. + When this object is set as the tensor_head of a WildTensor, it replaces the + WildTensor by a TensExpr (passed when initializing this object). + + Examples + ======== + >>> from sympy.tensor.tensor import WildTensorHead, TensorIndex, TensorHead, TensorIndexType + >>> W = WildTensorHead("W") + >>> R3 = TensorIndexType('R3', dim=3) + >>> p = TensorIndex('p', R3) + >>> q = TensorIndex('q', R3) + >>> K = TensorHead('K', [R3]) + >>> print( ( K(p) ).replace( W(p), W(q)*W(-q)*W(p) ) ) + K(R_0)*K(-R_0)*K(p) + + """ + def __init__(self, expr): + if not isinstance(expr, TensExpr): + raise TypeError("_WildTensExpr expects a TensExpr as argument") + self.expr = expr + + def __call__(self, *indices): + return self.expr._replace_indices(dict(zip(self.expr.get_free_indices(), indices))) + + def __neg__(self): + return self.func(self.expr*S.NegativeOne) + + def __abs__(self): + raise NotImplementedError + + def __add__(self, other): + if other.func != self.func: + raise TypeError(f"Cannot add {self.func} to {other.func}") + return self.func(self.expr+other.expr) + + def __radd__(self, other): + if other.func != self.func: + raise TypeError(f"Cannot add {self.func} to {other.func}") + return self.func(other.expr+self.expr) + + def __sub__(self, other): + return self + (-other) + + def __rsub__(self, other): + return other + (-self) + + def __mul__(self, other): + raise NotImplementedError + + def __rmul__(self, other): + raise NotImplementedError + + def __truediv__(self, other): + raise NotImplementedError + + def __rtruediv__(self, other): + raise NotImplementedError + + def __pow__(self, other): + raise NotImplementedError + + def __rpow__(self, other): + raise NotImplementedError + + +def canon_bp(p): + """ + Butler-Portugal canonicalization. See ``tensor_can.py`` from the + combinatorics module for the details. + """ + if isinstance(p, TensExpr): + return p.canon_bp() + return p + + +def tensor_mul(*a): + """ + product of tensors + """ + if not a: + return TensMul.from_data(S.One, [], [], []) + t = a[0] + for tx in a[1:]: + t = t*tx + return t + + +def riemann_cyclic_replace(t_r): + """ + replace Riemann tensor with an equivalent expression + + ``R(m,n,p,q) -> 2/3*R(m,n,p,q) - 1/3*R(m,q,n,p) + 1/3*R(m,p,n,q)`` + + """ + free = sorted(t_r.free, key=lambda x: x[1]) + m, n, p, q = [x[0] for x in free] + t0 = t_r*Rational(2, 3) + t1 = -t_r.substitute_indices((m,m),(n,q),(p,n),(q,p))*Rational(1, 3) + t2 = t_r.substitute_indices((m,m),(n,p),(p,n),(q,q))*Rational(1, 3) + t3 = t0 + t1 + t2 + return t3 + +def riemann_cyclic(t2): + """ + Replace each Riemann tensor with an equivalent expression + satisfying the cyclic identity. + + This trick is discussed in the reference guide to Cadabra. + + Examples + ======== + + >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, riemann_cyclic, TensorSymmetry + >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') + >>> i, j, k, l = tensor_indices('i,j,k,l', Lorentz) + >>> R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann()) + >>> t = R(i,j,k,l)*(R(-i,-j,-k,-l) - 2*R(-i,-k,-j,-l)) + >>> riemann_cyclic(t) + 0 + """ + t2 = t2.expand() + if isinstance(t2, (TensMul, Tensor)): + args = [t2] + else: + args = t2.args + a1 = [x.split() for x in args] + a2 = [[riemann_cyclic_replace(tx) for tx in y] for y in a1] + a3 = [tensor_mul(*v) for v in a2] + t3 = TensAdd(*a3).doit(deep=False) + if not t3: + return t3 + else: + return canon_bp(t3) + + +def get_lines(ex, index_type): + """ + Returns ``(lines, traces, rest)`` for an index type, + where ``lines`` is the list of list of positions of a matrix line, + ``traces`` is the list of list of traced matrix lines, + ``rest`` is the rest of the elements of the tensor. + """ + def _join_lines(a): + i = 0 + while i < len(a): + x = a[i] + xend = x[-1] + xstart = x[0] + hit = True + while hit: + hit = False + for j in range(i + 1, len(a)): + if j >= len(a): + break + if a[j][0] == xend: + hit = True + x.extend(a[j][1:]) + xend = x[-1] + a.pop(j) + continue + if a[j][0] == xstart: + hit = True + a[i] = reversed(a[j][1:]) + x + x = a[i] + xstart = a[i][0] + a.pop(j) + continue + if a[j][-1] == xend: + hit = True + x.extend(reversed(a[j][:-1])) + xend = x[-1] + a.pop(j) + continue + if a[j][-1] == xstart: + hit = True + a[i] = a[j][:-1] + x + x = a[i] + xstart = x[0] + a.pop(j) + continue + i += 1 + return a + + arguments = ex.args + dt = {} + for c in ex.args: + if not isinstance(c, TensExpr): + continue + if c in dt: + continue + index_types = c.index_types + a = [] + for i in range(len(index_types)): + if index_types[i] is index_type: + a.append(i) + if len(a) > 2: + raise ValueError('at most two indices of type %s allowed' % index_type) + if len(a) == 2: + dt[c] = a + #dum = ex.dum + lines = [] + traces = [] + traces1 = [] + #indices_to_args_pos = ex._get_indices_to_args_pos() + # TODO: add a dum_to_components_map ? + for p0, p1, c0, c1 in ex.dum_in_args: + if arguments[c0] not in dt: + continue + if c0 == c1: + traces.append([c0]) + continue + ta0 = dt[arguments[c0]] + ta1 = dt[arguments[c1]] + if p0 not in ta0: + continue + if ta0.index(p0) == ta1.index(p1): + # case gamma(i,s0,-s1) in c0, gamma(j,-s0,s2) in c1; + # to deal with this case one could add to the position + # a flag for transposition; + # one could write [(c0, False), (c1, True)] + raise NotImplementedError + # if p0 == ta0[1] then G in pos c0 is mult on the right by G in c1 + # if p0 == ta0[0] then G in pos c1 is mult on the right by G in c0 + ta0 = dt[arguments[c0]] + b0, b1 = (c0, c1) if p0 == ta0[1] else (c1, c0) + lines1 = lines.copy() + for line in lines: + if line[-1] == b0: + if line[0] == b1: + n = line.index(min(line)) + traces1.append(line) + traces.append(line[n:] + line[:n]) + else: + line.append(b1) + break + elif line[0] == b1: + line.insert(0, b0) + break + else: + lines1.append([b0, b1]) + + lines = [x for x in lines1 if x not in traces1] + lines = _join_lines(lines) + rest = [] + for line in lines: + for y in line: + rest.append(y) + for line in traces: + for y in line: + rest.append(y) + rest = [x for x in range(len(arguments)) if x not in rest] + + return lines, traces, rest + + +def get_free_indices(t): + if not isinstance(t, TensExpr): + return () + return t.get_free_indices() + + +def get_indices(t): + if not isinstance(t, TensExpr): + return () + return t.get_indices() + +def get_dummy_indices(t): + if not isinstance(t, TensExpr): + return () + inds = t.get_indices() + free = t.get_free_indices() + return [i for i in inds if i not in free] + +def get_index_structure(t): + if isinstance(t, TensExpr): + return t._index_structure + return _IndexStructure([], [], [], []) + + +def get_coeff(t): + if isinstance(t, Tensor): + return S.One + if isinstance(t, TensMul): + return t.coeff + if isinstance(t, TensExpr): + raise ValueError("no coefficient associated to this tensor expression") + return t + +def contract_metric(t, g): + if isinstance(t, TensExpr): + return t.contract_metric(g) + return t + +def perm2tensor(t, g, is_canon_bp=False): + """ + Returns the tensor corresponding to the permutation ``g`` + + For further details, see the method in ``TIDS`` with the same name. + """ + if not isinstance(t, TensExpr): + return t + elif isinstance(t, (Tensor, TensMul)): + nim = get_index_structure(t).perm2tensor(g, is_canon_bp=is_canon_bp) + res = t._set_new_index_structure(nim, is_canon_bp=is_canon_bp) + if g[-1] != len(g) - 1: + return -res + + return res + raise NotImplementedError() + + +def substitute_indices(t, *index_tuples): + if not isinstance(t, TensExpr): + return t + return t.substitute_indices(*index_tuples) + + +def _get_wilds(expr): + return list(expr.atoms(Wild, WildFunction, WildTensor, WildTensorIndex, WildTensorHead)) + + +def get_postprocessor(cls): + def _postprocessor(expr): + tens_class = {Mul: TensMul, Add: TensAdd}[cls] + if any(isinstance(a, TensExpr) for a in expr.args): + return tens_class(*expr.args) + else: + return expr + + return _postprocessor + +Basic._constructor_postprocessor_mapping[TensExpr] = { + "Mul": [get_postprocessor(Mul)], +} diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__init__.py b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0a99daefbd826cda07bb6e7d083f399e05ad193 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/test_functions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/test_functions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77bf39e7074e1a7dd554bed8c431405a2b2d1897 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/test_functions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/test_index_methods.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/test_index_methods.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97412d3156134de6ffcac57ea27c5ed63a82a4fe Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/test_index_methods.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/test_indexed.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/test_indexed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5b95e36301cb46145be3abeb6bc969c4dbf1c85 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/test_indexed.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/test_printing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/test_printing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5197e05c4d2c1d98755d35699ca502565354c70 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/test_printing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/test_tensor.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/test_tensor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33707e0efb8133dc67de07bcec95910d6d21cf87 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/test_tensor.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f85fd0bf44137f1f81a3cf4d62b043f8e705c7cde8db76c4b1ba0fc5800ca967 +size 145213 diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/test_tensor_element.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/test_tensor_element.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b77d4e16da4290fd0d549d6f9fb638b000b5eb80 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/test_tensor_element.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/test_tensor_operators.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/test_tensor_operators.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d383643e300cb97f8c5c313473c94e41552dd0b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/__pycache__/test_tensor_operators.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/tests/test_functions.py b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/test_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..ae40865d1bddffaa976dc3d94ae1ef1b6c97ca35 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/test_functions.py @@ -0,0 +1,57 @@ +from sympy.tensor.functions import TensorProduct +from sympy.matrices.dense import Matrix +from sympy.matrices.expressions.matexpr import MatrixSymbol +from sympy.tensor.array import Array +from sympy.abc import x, y, z +from sympy.abc import i, j, k, l + + +A = MatrixSymbol("A", 3, 3) +B = MatrixSymbol("B", 3, 3) +C = MatrixSymbol("C", 3, 3) + + +def test_TensorProduct_construction(): + assert TensorProduct(3, 4) == 12 + assert isinstance(TensorProduct(A, A), TensorProduct) + + expr = TensorProduct(TensorProduct(x, y), z) + assert expr == x*y*z + + expr = TensorProduct(TensorProduct(A, B), C) + assert expr == TensorProduct(A, B, C) + + expr = TensorProduct(Matrix.eye(2), Array([[0, -1], [1, 0]])) + assert expr == Array([ + [ + [[0, -1], [1, 0]], + [[0, 0], [0, 0]] + ], + [ + [[0, 0], [0, 0]], + [[0, -1], [1, 0]] + ] + ]) + + +def test_TensorProduct_shape(): + + expr = TensorProduct(3, 4, evaluate=False) + assert expr.shape == () + assert expr.rank() == 0 + + expr = TensorProduct(Array([1, 2]), Array([x, y]), evaluate=False) + assert expr.shape == (2, 2) + assert expr.rank() == 2 + expr = TensorProduct(expr, expr, evaluate=False) + assert expr.shape == (2, 2, 2, 2) + assert expr.rank() == 4 + + expr = TensorProduct(Matrix.eye(2), Array([[0, -1], [1, 0]]), evaluate=False) + assert expr.shape == (2, 2, 2, 2) + assert expr.rank() == 4 + + +def test_TensorProduct_getitem(): + expr = TensorProduct(A, B) + assert expr[i, j, k, l] == A[i, j]*B[k, l] diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/tests/test_index_methods.py b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/test_index_methods.py new file mode 100644 index 0000000000000000000000000000000000000000..df20f7e7c1ab392321e8350b95dd07c5639c1865 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/test_index_methods.py @@ -0,0 +1,227 @@ +from sympy.core import symbols, S, Pow, Function +from sympy.functions import exp +from sympy.testing.pytest import raises +from sympy.tensor.indexed import Idx, IndexedBase +from sympy.tensor.index_methods import IndexConformanceException + +from sympy.tensor.index_methods import (get_contraction_structure, get_indices) + + +def test_trivial_indices(): + x, y = symbols('x y') + assert get_indices(x) == (set(), {}) + assert get_indices(x*y) == (set(), {}) + assert get_indices(x + y) == (set(), {}) + assert get_indices(x**y) == (set(), {}) + + +def test_get_indices_Indexed(): + x = IndexedBase('x') + i, j = Idx('i'), Idx('j') + assert get_indices(x[i, j]) == ({i, j}, {}) + assert get_indices(x[j, i]) == ({j, i}, {}) + + +def test_get_indices_Idx(): + f = Function('f') + i, j = Idx('i'), Idx('j') + assert get_indices(f(i)*j) == ({i, j}, {}) + assert get_indices(f(j, i)) == ({j, i}, {}) + assert get_indices(f(i)*i) == (set(), {}) + + +def test_get_indices_mul(): + x = IndexedBase('x') + y = IndexedBase('y') + i, j = Idx('i'), Idx('j') + assert get_indices(x[j]*y[i]) == ({i, j}, {}) + assert get_indices(x[i]*y[j]) == ({i, j}, {}) + + +def test_get_indices_exceptions(): + x = IndexedBase('x') + y = IndexedBase('y') + i, j = Idx('i'), Idx('j') + raises(IndexConformanceException, lambda: get_indices(x[i] + y[j])) + + +def test_scalar_broadcast(): + x = IndexedBase('x') + y = IndexedBase('y') + i, j = Idx('i'), Idx('j') + assert get_indices(x[i] + y[i, i]) == ({i}, {}) + assert get_indices(x[i] + y[j, j]) == ({i}, {}) + + +def test_get_indices_add(): + x = IndexedBase('x') + y = IndexedBase('y') + A = IndexedBase('A') + i, j, k = Idx('i'), Idx('j'), Idx('k') + assert get_indices(x[i] + 2*y[i]) == ({i}, {}) + assert get_indices(y[i] + 2*A[i, j]*x[j]) == ({i}, {}) + assert get_indices(y[i] + 2*(x[i] + A[i, j]*x[j])) == ({i}, {}) + assert get_indices(y[i] + x[i]*(A[j, j] + 1)) == ({i}, {}) + assert get_indices( + y[i] + x[i]*x[j]*(y[j] + A[j, k]*x[k])) == ({i}, {}) + + +def test_get_indices_Pow(): + x = IndexedBase('x') + y = IndexedBase('y') + A = IndexedBase('A') + i, j, k = Idx('i'), Idx('j'), Idx('k') + assert get_indices(Pow(x[i], y[j])) == ({i, j}, {}) + assert get_indices(Pow(x[i, k], y[j, k])) == ({i, j, k}, {}) + assert get_indices(Pow(A[i, k], y[k] + A[k, j]*x[j])) == ({i, k}, {}) + assert get_indices(Pow(2, x[i])) == get_indices(exp(x[i])) + + # test of a design decision, this may change: + assert get_indices(Pow(x[i], 2)) == ({i}, {}) + + +def test_get_contraction_structure_basic(): + x = IndexedBase('x') + y = IndexedBase('y') + i, j = Idx('i'), Idx('j') + assert get_contraction_structure(x[i]*y[j]) == {None: {x[i]*y[j]}} + assert get_contraction_structure(x[i] + y[j]) == {None: {x[i], y[j]}} + assert get_contraction_structure(x[i]*y[i]) == {(i,): {x[i]*y[i]}} + assert get_contraction_structure( + 1 + x[i]*y[i]) == {None: {S.One}, (i,): {x[i]*y[i]}} + assert get_contraction_structure(x[i]**y[i]) == {None: {x[i]**y[i]}} + + +def test_get_contraction_structure_complex(): + x = IndexedBase('x') + y = IndexedBase('y') + A = IndexedBase('A') + i, j, k = Idx('i'), Idx('j'), Idx('k') + expr1 = y[i] + A[i, j]*x[j] + d1 = {None: {y[i]}, (j,): {A[i, j]*x[j]}} + assert get_contraction_structure(expr1) == d1 + expr2 = expr1*A[k, i] + x[k] + d2 = {None: {x[k]}, (i,): {expr1*A[k, i]}, expr1*A[k, i]: [d1]} + assert get_contraction_structure(expr2) == d2 + + +def test_contraction_structure_simple_Pow(): + x = IndexedBase('x') + y = IndexedBase('y') + i, j, k = Idx('i'), Idx('j'), Idx('k') + ii_jj = x[i, i]**y[j, j] + assert get_contraction_structure(ii_jj) == { + None: {ii_jj}, + ii_jj: [ + {(i,): {x[i, i]}}, + {(j,): {y[j, j]}} + ] + } + + ii_jk = x[i, i]**y[j, k] + assert get_contraction_structure(ii_jk) == { + None: {x[i, i]**y[j, k]}, + x[i, i]**y[j, k]: [ + {(i,): {x[i, i]}} + ] + } + + +def test_contraction_structure_Mul_and_Pow(): + x = IndexedBase('x') + y = IndexedBase('y') + i, j, k = Idx('i'), Idx('j'), Idx('k') + + i_ji = x[i]**(y[j]*x[i]) + assert get_contraction_structure(i_ji) == {None: {i_ji}} + ij_i = (x[i]*y[j])**(y[i]) + assert get_contraction_structure(ij_i) == {None: {ij_i}} + j_ij_i = x[j]*(x[i]*y[j])**(y[i]) + assert get_contraction_structure(j_ij_i) == {(j,): {j_ij_i}} + j_i_ji = x[j]*x[i]**(y[j]*x[i]) + assert get_contraction_structure(j_i_ji) == {(j,): {j_i_ji}} + ij_exp_kki = x[i]*y[j]*exp(y[i]*y[k, k]) + result = get_contraction_structure(ij_exp_kki) + expected = { + (i,): {ij_exp_kki}, + ij_exp_kki: [{ + None: {exp(y[i]*y[k, k])}, + exp(y[i]*y[k, k]): [{ + None: {y[i]*y[k, k]}, + y[i]*y[k, k]: [{(k,): {y[k, k]}}] + }]} + ] + } + assert result == expected + + +def test_contraction_structure_Add_in_Pow(): + x = IndexedBase('x') + y = IndexedBase('y') + i, j, k = Idx('i'), Idx('j'), Idx('k') + s_ii_jj_s = (1 + x[i, i])**(1 + y[j, j]) + expected = { + None: {s_ii_jj_s}, + s_ii_jj_s: [ + {None: {S.One}, (i,): {x[i, i]}}, + {None: {S.One}, (j,): {y[j, j]}} + ] + } + result = get_contraction_structure(s_ii_jj_s) + assert result == expected + + s_ii_jk_s = (1 + x[i, i]) ** (1 + y[j, k]) + expected_2 = { + None: {(x[i, i] + 1)**(y[j, k] + 1)}, + s_ii_jk_s: [ + {None: {S.One}, (i,): {x[i, i]}} + ] + } + result_2 = get_contraction_structure(s_ii_jk_s) + assert result_2 == expected_2 + + +def test_contraction_structure_Pow_in_Pow(): + x = IndexedBase('x') + y = IndexedBase('y') + z = IndexedBase('z') + i, j, k = Idx('i'), Idx('j'), Idx('k') + ii_jj_kk = x[i, i]**y[j, j]**z[k, k] + expected = { + None: {ii_jj_kk}, + ii_jj_kk: [ + {(i,): {x[i, i]}}, + { + None: {y[j, j]**z[k, k]}, + y[j, j]**z[k, k]: [ + {(j,): {y[j, j]}}, + {(k,): {z[k, k]}} + ] + } + ] + } + assert get_contraction_structure(ii_jj_kk) == expected + + +def test_ufunc_support(): + f = Function('f') + g = Function('g') + x = IndexedBase('x') + y = IndexedBase('y') + i, j = Idx('i'), Idx('j') + a = symbols('a') + + assert get_indices(f(x[i])) == ({i}, {}) + assert get_indices(f(x[i], y[j])) == ({i, j}, {}) + assert get_indices(f(y[i])*g(x[i])) == (set(), {}) + assert get_indices(f(a, x[i])) == ({i}, {}) + assert get_indices(f(a, y[i], x[j])*g(x[i])) == ({j}, {}) + assert get_indices(g(f(x[i]))) == ({i}, {}) + + assert get_contraction_structure(f(x[i])) == {None: {f(x[i])}} + assert get_contraction_structure( + f(y[i])*g(x[i])) == {(i,): {f(y[i])*g(x[i])}} + assert get_contraction_structure( + f(y[i])*g(f(x[i]))) == {(i,): {f(y[i])*g(f(x[i]))}} + assert get_contraction_structure( + f(x[j], y[i])*g(x[i])) == {(i,): {f(x[j], y[i])*g(x[i])}} diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/tests/test_indexed.py b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/test_indexed.py new file mode 100644 index 0000000000000000000000000000000000000000..689ec932c8fcefe0a24de289dd2ffd6820c63f19 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/test_indexed.py @@ -0,0 +1,511 @@ +from sympy.core import symbols, Symbol, Tuple, oo, Dummy +from sympy.tensor.indexed import IndexException +from sympy.testing.pytest import raises +from sympy.utilities.iterables import iterable + +# import test: +from sympy.concrete.summations import Sum +from sympy.core.function import Function, Subs, Derivative +from sympy.core.relational import (StrictLessThan, GreaterThan, + StrictGreaterThan, LessThan) +from sympy.core.singleton import S +from sympy.functions.elementary.exponential import exp, log +from sympy.functions.elementary.trigonometric import cos, sin +from sympy.functions.special.tensor_functions import KroneckerDelta +from sympy.series.order import Order +from sympy.sets.fancysets import Range +from sympy.tensor.indexed import IndexedBase, Idx, Indexed + + +def test_Idx_construction(): + i, a, b = symbols('i a b', integer=True) + assert Idx(i) != Idx(i, 1) + assert Idx(i, a) == Idx(i, (0, a - 1)) + assert Idx(i, oo) == Idx(i, (0, oo)) + + x = symbols('x', integer=False) + raises(TypeError, lambda: Idx(x)) + raises(TypeError, lambda: Idx(0.5)) + raises(TypeError, lambda: Idx(i, x)) + raises(TypeError, lambda: Idx(i, 0.5)) + raises(TypeError, lambda: Idx(i, (x, 5))) + raises(TypeError, lambda: Idx(i, (2, x))) + raises(TypeError, lambda: Idx(i, (2, 3.5))) + + +def test_Idx_properties(): + i, a, b = symbols('i a b', integer=True) + assert Idx(i).is_integer + assert Idx(i).name == 'i' + assert Idx(i + 2).name == 'i + 2' + assert Idx('foo').name == 'foo' + + +def test_Idx_bounds(): + i, a, b = symbols('i a b', integer=True) + assert Idx(i).lower is None + assert Idx(i).upper is None + assert Idx(i, a).lower == 0 + assert Idx(i, a).upper == a - 1 + assert Idx(i, 5).lower == 0 + assert Idx(i, 5).upper == 4 + assert Idx(i, oo).lower == 0 + assert Idx(i, oo).upper is oo + assert Idx(i, (a, b)).lower == a + assert Idx(i, (a, b)).upper == b + assert Idx(i, (1, 5)).lower == 1 + assert Idx(i, (1, 5)).upper == 5 + assert Idx(i, (-oo, oo)).lower is -oo + assert Idx(i, (-oo, oo)).upper is oo + + +def test_Idx_fixed_bounds(): + i, a, b, x = symbols('i a b x', integer=True) + assert Idx(x).lower is None + assert Idx(x).upper is None + assert Idx(x, a).lower == 0 + assert Idx(x, a).upper == a - 1 + assert Idx(x, 5).lower == 0 + assert Idx(x, 5).upper == 4 + assert Idx(x, oo).lower == 0 + assert Idx(x, oo).upper is oo + assert Idx(x, (a, b)).lower == a + assert Idx(x, (a, b)).upper == b + assert Idx(x, (1, 5)).lower == 1 + assert Idx(x, (1, 5)).upper == 5 + assert Idx(x, (-oo, oo)).lower is -oo + assert Idx(x, (-oo, oo)).upper is oo + + +def test_Idx_inequalities(): + i14 = Idx("i14", (1, 4)) + i79 = Idx("i79", (7, 9)) + i46 = Idx("i46", (4, 6)) + i35 = Idx("i35", (3, 5)) + + assert i14 <= 5 + assert i14 < 5 + assert not (i14 >= 5) + assert not (i14 > 5) + + assert 5 >= i14 + assert 5 > i14 + assert not (5 <= i14) + assert not (5 < i14) + + assert LessThan(i14, 5) + assert StrictLessThan(i14, 5) + assert not GreaterThan(i14, 5) + assert not StrictGreaterThan(i14, 5) + + assert i14 <= 4 + assert isinstance(i14 < 4, StrictLessThan) + assert isinstance(i14 >= 4, GreaterThan) + assert not (i14 > 4) + + assert isinstance(i14 <= 1, LessThan) + assert not (i14 < 1) + assert i14 >= 1 + assert isinstance(i14 > 1, StrictGreaterThan) + + assert not (i14 <= 0) + assert not (i14 < 0) + assert i14 >= 0 + assert i14 > 0 + + from sympy.abc import x + + assert isinstance(i14 < x, StrictLessThan) + assert isinstance(i14 > x, StrictGreaterThan) + assert isinstance(i14 <= x, LessThan) + assert isinstance(i14 >= x, GreaterThan) + + assert i14 < i79 + assert i14 <= i79 + assert not (i14 > i79) + assert not (i14 >= i79) + + assert i14 <= i46 + assert isinstance(i14 < i46, StrictLessThan) + assert isinstance(i14 >= i46, GreaterThan) + assert not (i14 > i46) + + assert isinstance(i14 < i35, StrictLessThan) + assert isinstance(i14 > i35, StrictGreaterThan) + assert isinstance(i14 <= i35, LessThan) + assert isinstance(i14 >= i35, GreaterThan) + + iNone1 = Idx("iNone1") + iNone2 = Idx("iNone2") + + assert isinstance(iNone1 < iNone2, StrictLessThan) + assert isinstance(iNone1 > iNone2, StrictGreaterThan) + assert isinstance(iNone1 <= iNone2, LessThan) + assert isinstance(iNone1 >= iNone2, GreaterThan) + + +def test_Idx_inequalities_current_fails(): + i14 = Idx("i14", (1, 4)) + + assert S(5) >= i14 + assert S(5) > i14 + assert not (S(5) <= i14) + assert not (S(5) < i14) + + +def test_Idx_func_args(): + i, a, b = symbols('i a b', integer=True) + ii = Idx(i) + assert ii.func(*ii.args) == ii + ii = Idx(i, a) + assert ii.func(*ii.args) == ii + ii = Idx(i, (a, b)) + assert ii.func(*ii.args) == ii + + +def test_Idx_subs(): + i, a, b = symbols('i a b', integer=True) + assert Idx(i, a).subs(a, b) == Idx(i, b) + assert Idx(i, a).subs(i, b) == Idx(b, a) + + assert Idx(i).subs(i, 2) == Idx(2) + assert Idx(i, a).subs(a, 2) == Idx(i, 2) + assert Idx(i, (a, b)).subs(i, 2) == Idx(2, (a, b)) + + +def test_IndexedBase_sugar(): + i, j = symbols('i j', integer=True) + a = symbols('a') + A1 = Indexed(a, i, j) + A2 = IndexedBase(a) + assert A1 == A2[i, j] + assert A1 == A2[(i, j)] + assert A1 == A2[[i, j]] + assert A1 == A2[Tuple(i, j)] + assert all(a.is_Integer for a in A2[1, 0].args[1:]) + + +def test_IndexedBase_subs(): + i = symbols('i', integer=True) + a, b = symbols('a b') + A = IndexedBase(a) + B = IndexedBase(b) + assert A[i] == B[i].subs(b, a) + C = {1: 2} + assert C[1] == A[1].subs(A, C) + + +def test_IndexedBase_shape(): + i, j, m, n = symbols('i j m n', integer=True) + a = IndexedBase('a', shape=(m, m)) + b = IndexedBase('a', shape=(m, n)) + assert b.shape == Tuple(m, n) + assert a[i, j] != b[i, j] + assert a[i, j] == b[i, j].subs(n, m) + assert b.func(*b.args) == b + assert b[i, j].func(*b[i, j].args) == b[i, j] + raises(IndexException, lambda: b[i]) + raises(IndexException, lambda: b[i, i, j]) + F = IndexedBase("F", shape=m) + assert F.shape == Tuple(m) + assert F[i].subs(i, j) == F[j] + raises(IndexException, lambda: F[i, j]) + + +def test_IndexedBase_assumptions(): + i = Symbol('i', integer=True) + a = Symbol('a') + A = IndexedBase(a, positive=True) + for c in (A, A[i]): + assert c.is_real + assert c.is_complex + assert not c.is_imaginary + assert c.is_nonnegative + assert c.is_nonzero + assert c.is_commutative + assert log(exp(c)) == c + + assert A != IndexedBase(a) + assert A == IndexedBase(a, positive=True, real=True) + assert A[i] != Indexed(a, i) + + +def test_IndexedBase_assumptions_inheritance(): + I = Symbol('I', integer=True) + I_inherit = IndexedBase(I) + I_explicit = IndexedBase('I', integer=True) + + assert I_inherit.is_integer + assert I_explicit.is_integer + assert I_inherit.label.is_integer + assert I_explicit.label.is_integer + assert I_inherit == I_explicit + + +def test_issue_17652(): + """Regression test issue #17652. + + IndexedBase.label should not upcast subclasses of Symbol + """ + class SubClass(Symbol): + pass + + x = SubClass('X') + assert type(x) == SubClass + base = IndexedBase(x) + assert type(x) == SubClass + assert type(base.label) == SubClass + + +def test_Indexed_constructor(): + i, j = symbols('i j', integer=True) + A = Indexed('A', i, j) + assert A == Indexed(Symbol('A'), i, j) + assert A == Indexed(IndexedBase('A'), i, j) + raises(TypeError, lambda: Indexed(A, i, j)) + raises(IndexException, lambda: Indexed("A")) + assert A.free_symbols == {A, A.base.label, i, j} + + +def test_Indexed_func_args(): + i, j = symbols('i j', integer=True) + a = symbols('a') + A = Indexed(a, i, j) + assert A == A.func(*A.args) + + +def test_Indexed_subs(): + i, j, k = symbols('i j k', integer=True) + a, b = symbols('a b') + A = IndexedBase(a) + B = IndexedBase(b) + assert A[i, j] == B[i, j].subs(b, a) + assert A[i, j] == A[i, k].subs(k, j) + + +def test_Indexed_properties(): + i, j = symbols('i j', integer=True) + A = Indexed('A', i, j) + assert A.name == 'A[i, j]' + assert A.rank == 2 + assert A.indices == (i, j) + assert A.base == IndexedBase('A') + assert A.ranges == [None, None] + raises(IndexException, lambda: A.shape) + + n, m = symbols('n m', integer=True) + assert Indexed('A', Idx( + i, m), Idx(j, n)).ranges == [Tuple(0, m - 1), Tuple(0, n - 1)] + assert Indexed('A', Idx(i, m), Idx(j, n)).shape == Tuple(m, n) + raises(IndexException, lambda: Indexed("A", Idx(i, m), Idx(j)).shape) + + +def test_Indexed_shape_precedence(): + i, j = symbols('i j', integer=True) + o, p = symbols('o p', integer=True) + n, m = symbols('n m', integer=True) + a = IndexedBase('a', shape=(o, p)) + assert a.shape == Tuple(o, p) + assert Indexed( + a, Idx(i, m), Idx(j, n)).ranges == [Tuple(0, m - 1), Tuple(0, n - 1)] + assert Indexed(a, Idx(i, m), Idx(j, n)).shape == Tuple(o, p) + assert Indexed( + a, Idx(i, m), Idx(j)).ranges == [Tuple(0, m - 1), (None, None)] + assert Indexed(a, Idx(i, m), Idx(j)).shape == Tuple(o, p) + + +def test_complex_indices(): + i, j = symbols('i j', integer=True) + A = Indexed('A', i, i + j) + assert A.rank == 2 + assert A.indices == (i, i + j) + + +def test_not_interable(): + i, j = symbols('i j', integer=True) + A = Indexed('A', i, i + j) + assert not iterable(A) + + +def test_Indexed_coeff(): + N = Symbol('N', integer=True) + len_y = N + i = Idx('i', len_y-1) + y = IndexedBase('y', shape=(len_y,)) + a = (1/y[i+1]*y[i]).coeff(y[i]) + b = (y[i]/y[i+1]).coeff(y[i]) + assert a == b + + +def test_differentiation(): + from sympy.functions.special.tensor_functions import KroneckerDelta + i, j, k, l = symbols('i j k l', cls=Idx) + a = symbols('a') + m, n = symbols("m, n", integer=True, finite=True) + assert m.is_real + h, L = symbols('h L', cls=IndexedBase) + hi, hj = h[i], h[j] + + expr = hi + assert expr.diff(hj) == KroneckerDelta(i, j) + assert expr.diff(hi) == KroneckerDelta(i, i) + + expr = S(2) * hi + assert expr.diff(hj) == S(2) * KroneckerDelta(i, j) + assert expr.diff(hi) == S(2) * KroneckerDelta(i, i) + assert expr.diff(a) is S.Zero + + assert Sum(expr, (i, -oo, oo)).diff(hj) == Sum(2*KroneckerDelta(i, j), (i, -oo, oo)) + assert Sum(expr.diff(hj), (i, -oo, oo)) == Sum(2*KroneckerDelta(i, j), (i, -oo, oo)) + assert Sum(expr, (i, -oo, oo)).diff(hj).doit() == 2 + + assert Sum(expr.diff(hi), (i, -oo, oo)).doit() == Sum(2, (i, -oo, oo)).doit() + assert Sum(expr, (i, -oo, oo)).diff(hi).doit() is oo + + expr = a * hj * hj / S(2) + assert expr.diff(hi) == a * h[j] * KroneckerDelta(i, j) + assert expr.diff(a) == hj * hj / S(2) + assert expr.diff(a, 2) is S.Zero + + assert Sum(expr, (i, -oo, oo)).diff(hi) == Sum(a*KroneckerDelta(i, j)*h[j], (i, -oo, oo)) + assert Sum(expr.diff(hi), (i, -oo, oo)) == Sum(a*KroneckerDelta(i, j)*h[j], (i, -oo, oo)) + assert Sum(expr, (i, -oo, oo)).diff(hi).doit() == a*h[j] + + assert Sum(expr, (j, -oo, oo)).diff(hi) == Sum(a*KroneckerDelta(i, j)*h[j], (j, -oo, oo)) + assert Sum(expr.diff(hi), (j, -oo, oo)) == Sum(a*KroneckerDelta(i, j)*h[j], (j, -oo, oo)) + assert Sum(expr, (j, -oo, oo)).diff(hi).doit() == a*h[i] + + expr = a * sin(hj * hj) + assert expr.diff(hi) == 2*a*cos(hj * hj) * hj * KroneckerDelta(i, j) + assert expr.diff(hj) == 2*a*cos(hj * hj) * hj + + expr = a * L[i, j] * h[j] + assert expr.diff(hi) == a*L[i, j]*KroneckerDelta(i, j) + assert expr.diff(hj) == a*L[i, j] + assert expr.diff(L[i, j]) == a*h[j] + assert expr.diff(L[k, l]) == a*KroneckerDelta(i, k)*KroneckerDelta(j, l)*h[j] + assert expr.diff(L[i, l]) == a*KroneckerDelta(j, l)*h[j] + + assert Sum(expr, (j, -oo, oo)).diff(L[k, l]) == Sum(a * KroneckerDelta(i, k) * KroneckerDelta(j, l) * h[j], (j, -oo, oo)) + assert Sum(expr, (j, -oo, oo)).diff(L[k, l]).doit() == a * KroneckerDelta(i, k) * h[l] + + assert h[m].diff(h[m]) == 1 + assert h[m].diff(h[n]) == KroneckerDelta(m, n) + assert Sum(a*h[m], (m, -oo, oo)).diff(h[n]) == Sum(a*KroneckerDelta(m, n), (m, -oo, oo)) + assert Sum(a*h[m], (m, -oo, oo)).diff(h[n]).doit() == a + assert Sum(a*h[m], (n, -oo, oo)).diff(h[n]) == Sum(a*KroneckerDelta(m, n), (n, -oo, oo)) + assert Sum(a*h[m], (m, -oo, oo)).diff(h[m]).doit() == oo*a + + +def test_indexed_series(): + A = IndexedBase("A") + i = symbols("i", integer=True) + assert sin(A[i]).series(A[i]) == A[i] - A[i]**3/6 + A[i]**5/120 + Order(A[i]**6, A[i]) + + +def test_indexed_is_constant(): + A = IndexedBase("A") + i, j, k = symbols("i,j,k") + assert not A[i].is_constant() + assert A[i].is_constant(j) + assert not A[1+2*i, k].is_constant() + assert not A[1+2*i, k].is_constant(i) + assert A[1+2*i, k].is_constant(j) + assert not A[1+2*i, k].is_constant(k) + + +def test_issue_12533(): + d = IndexedBase('d') + assert IndexedBase(range(5)) == Range(0, 5, 1) + assert d[0].subs(Symbol("d"), range(5)) == 0 + assert d[0].subs(d, range(5)) == 0 + assert d[1].subs(d, range(5)) == 1 + assert Indexed(Range(5), 2) == 2 + + +def test_issue_12780(): + n = symbols("n") + i = Idx("i", (0, n)) + raises(TypeError, lambda: i.subs(n, 1.5)) + + +def test_issue_18604(): + m = symbols("m") + assert Idx("i", m).name == 'i' + assert Idx("i", m).lower == 0 + assert Idx("i", m).upper == m - 1 + m = symbols("m", real=False) + raises(TypeError, lambda: Idx("i", m)) + +def test_Subs_with_Indexed(): + A = IndexedBase("A") + i, j, k = symbols("i,j,k") + x, y, z = symbols("x,y,z") + f = Function("f") + + assert Subs(A[i], A[i], A[j]).diff(A[j]) == 1 + assert Subs(A[i], A[i], x).diff(A[i]) == 0 + assert Subs(A[i], A[i], x).diff(A[j]) == 0 + assert Subs(A[i], A[i], x).diff(x) == 1 + assert Subs(A[i], A[i], x).diff(y) == 0 + assert Subs(A[i], A[i], A[j]).diff(A[k]) == KroneckerDelta(j, k) + assert Subs(x, x, A[i]).diff(A[j]) == KroneckerDelta(i, j) + assert Subs(f(A[i]), A[i], x).diff(A[j]) == 0 + assert Subs(f(A[i]), A[i], A[k]).diff(A[j]) == Derivative(f(A[k]), A[k])*KroneckerDelta(j, k) + assert Subs(x, x, A[i]**2).diff(A[j]) == 2*KroneckerDelta(i, j)*A[i] + assert Subs(A[i], A[i], A[j]**2).diff(A[k]) == 2*KroneckerDelta(j, k)*A[j] + + assert Subs(A[i]*x, x, A[i]).diff(A[i]) == 2*A[i] + assert Subs(A[i]*x, x, A[i]).diff(A[j]) == 2*A[i]*KroneckerDelta(i, j) + assert Subs(A[i]*x, x, A[j]).diff(A[i]) == A[j] + A[i]*KroneckerDelta(i, j) + assert Subs(A[i]*x, x, A[j]).diff(A[j]) == A[i] + A[j]*KroneckerDelta(i, j) + assert Subs(A[i]*x, x, A[i]).diff(A[k]) == 2*A[i]*KroneckerDelta(i, k) + assert Subs(A[i]*x, x, A[j]).diff(A[k]) == KroneckerDelta(i, k)*A[j] + KroneckerDelta(j, k)*A[i] + + assert Subs(A[i]*x, A[i], x).diff(A[i]) == 0 + assert Subs(A[i]*x, A[i], x).diff(A[j]) == 0 + assert Subs(A[i]*x, A[j], x).diff(A[i]) == x + assert Subs(A[i]*x, A[j], x).diff(A[j]) == x*KroneckerDelta(i, j) + assert Subs(A[i]*x, A[i], x).diff(A[k]) == 0 + assert Subs(A[i]*x, A[j], x).diff(A[k]) == x*KroneckerDelta(i, k) + + +def test_complicated_derivative_with_Indexed(): + x, y = symbols("x,y", cls=IndexedBase) + sigma = symbols("sigma") + i, j, k = symbols("i,j,k") + m0,m1,m2,m3,m4,m5 = symbols("m0:6") + f = Function("f") + + expr = f((x[i] - y[i])**2/sigma) + _xi_1 = symbols("xi_1", cls=Dummy) + assert expr.diff(x[m0]).dummy_eq( + (x[i] - y[i])*KroneckerDelta(i, m0)*\ + 2*Subs( + Derivative(f(_xi_1), _xi_1), + (_xi_1,), + ((x[i] - y[i])**2/sigma,) + )/sigma + ) + assert expr.diff(x[m0]).diff(x[m1]).dummy_eq( + 2*KroneckerDelta(i, m0)*\ + KroneckerDelta(i, m1)*Subs( + Derivative(f(_xi_1), _xi_1), + (_xi_1,), + ((x[i] - y[i])**2/sigma,) + )/sigma + \ + 4*(x[i] - y[i])**2*KroneckerDelta(i, m0)*KroneckerDelta(i, m1)*\ + Subs( + Derivative(f(_xi_1), _xi_1, _xi_1), + (_xi_1,), + ((x[i] - y[i])**2/sigma,) + )/sigma**2 + ) + + +def test_IndexedBase_commutative(): + t = IndexedBase('t', commutative=False) + u = IndexedBase('u', commutative=False) + v = IndexedBase('v') + assert t[0]*v[0] == v[0]*t[0] + assert t[0]*u[0] != u[0]*t[0] diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/tests/test_printing.py b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/test_printing.py new file mode 100644 index 0000000000000000000000000000000000000000..9f3cf7f0591a7012c93354ab7b8d7e010def38bb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/test_printing.py @@ -0,0 +1,13 @@ +from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead +from sympy import I + +def test_printing_TensMul(): + R3 = TensorIndexType('R3', dim=3) + p, q = tensor_indices("p q", R3) + K = TensorHead("K", [R3]) + + assert repr(2*K(p)) == "2*K(p)" + assert repr(-K(p)) == "-K(p)" + assert repr(-2*K(p)*K(q)) == "-2*K(p)*K(q)" + assert repr(-I*K(p)) == "-I*K(p)" + assert repr(I*K(p)) == "I*K(p)" diff --git a/.venv/lib/python3.12/site-packages/sympy/tensor/tests/test_tensor.py b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/test_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..3113f5be9bcd32224f3525b5d831b6d7476c39e3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/tensor/tests/test_tensor.py @@ -0,0 +1,2218 @@ +from sympy.concrete.summations import Sum +from sympy.core.function import expand +from sympy.core.numbers import Integer +from sympy.matrices.dense import (Matrix, eye) +from sympy.tensor.indexed import Indexed +from sympy.combinatorics import Permutation +from sympy.core import S, Rational, Symbol, Basic, Add, Wild, Function +from sympy.core.containers import Tuple +from sympy.core.symbol import symbols +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.integrals import integrate +from sympy.tensor.array import Array +from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorSymmetry, \ + get_symmetric_group_sgs, TensorIndex, tensor_mul, TensAdd, \ + riemann_cyclic_replace, riemann_cyclic, TensMul, tensor_heads, \ + TensorManager, TensExpr, TensorHead, canon_bp, \ + tensorhead, tensorsymmetry, TensorType, substitute_indices, \ + WildTensorIndex, WildTensorHead, _WildTensExpr +from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy +from sympy.matrices import diag + +def _is_equal(arg1, arg2): + if isinstance(arg1, TensExpr): + return arg1.equals(arg2) + elif isinstance(arg2, TensExpr): + return arg2.equals(arg1) + return arg1 == arg2 + + +#################### Tests from tensor_can.py ####################### +def test_canonicalize_no_slot_sym(): + # A_d0 * B^d0; T_c = A^d0*B_d0 + Lorentz = TensorIndexType('Lorentz', dummy_name='L') + a, b, d0, d1 = tensor_indices('a,b,d0,d1', Lorentz) + A, B = tensor_heads('A,B', [Lorentz], TensorSymmetry.no_symmetry(1)) + t = A(-d0)*B(d0) + tc = t.canon_bp() + assert str(tc) == 'A(L_0)*B(-L_0)' + + # A^a * B^b; T_c = T + t = A(a)*B(b) + tc = t.canon_bp() + assert tc == t + # B^b * A^a + t1 = B(b)*A(a) + tc = t1.canon_bp() + assert str(tc) == 'A(a)*B(b)' + + # A symmetric + # A^{b}_{d0}*A^{d0, a}; T_c = A^{a d0}*A{b}_{d0} + A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) + t = A(b, -d0)*A(d0, a) + tc = t.canon_bp() + assert str(tc) == 'A(a, L_0)*A(b, -L_0)' + + # A^{d1}_{d0}*B^d0*C_d1 + # T_c = A^{d0 d1}*B_d0*C_d1 + B, C = tensor_heads('B,C', [Lorentz], TensorSymmetry.no_symmetry(1)) + t = A(d1, -d0)*B(d0)*C(-d1) + tc = t.canon_bp() + assert str(tc) == 'A(L_0, L_1)*B(-L_0)*C(-L_1)' + + # A without symmetry + # A^{d1}_{d0}*B^d0*C_d1 ord=[d0,-d0,d1,-d1]; g = [2,1,0,3,4,5] + # T_c = A^{d0 d1}*B_d1*C_d0; can = [0,2,3,1,4,5] + A = TensorHead('A', [Lorentz]*2, TensorSymmetry.no_symmetry(2)) + t = A(d1, -d0)*B(d0)*C(-d1) + tc = t.canon_bp() + assert str(tc) == 'A(L_0, L_1)*B(-L_1)*C(-L_0)' + + # A, B without symmetry + # A^{d1}_{d0}*B_{d1}^{d0} + # T_c = A^{d0 d1}*B_{d0 d1} + B = TensorHead('B', [Lorentz]*2, TensorSymmetry.no_symmetry(2)) + t = A(d1, -d0)*B(-d1, d0) + tc = t.canon_bp() + assert str(tc) == 'A(L_0, L_1)*B(-L_0, -L_1)' + # A_{d0}^{d1}*B_{d1}^{d0} + # T_c = A^{d0 d1}*B_{d1 d0} + t = A(-d0, d1)*B(-d1, d0) + tc = t.canon_bp() + assert str(tc) == 'A(L_0, L_1)*B(-L_1, -L_0)' + + # A, B, C without symmetry + # A^{d1 d0}*B_{a d0}*C_{d1 b} + # T_c=A^{d0 d1}*B_{a d1}*C_{d0 b} + C = TensorHead('C', [Lorentz]*2, TensorSymmetry.no_symmetry(2)) + t = A(d1, d0)*B(-a, -d0)*C(-d1, -b) + tc = t.canon_bp() + assert str(tc) == 'A(L_0, L_1)*B(-a, -L_1)*C(-L_0, -b)' + + # A symmetric, B and C without symmetry + # A^{d1 d0}*B_{a d0}*C_{d1 b} + # T_c = A^{d0 d1}*B_{a d0}*C_{d1 b} + A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) + t = A(d1, d0)*B(-a, -d0)*C(-d1, -b) + tc = t.canon_bp() + assert str(tc) == 'A(L_0, L_1)*B(-a, -L_0)*C(-L_1, -b)' + + # A and C symmetric, B without symmetry + # A^{d1 d0}*B_{a d0}*C_{d1 b} ord=[a,b,d0,-d0,d1,-d1] + # T_c = A^{d0 d1}*B_{a d0}*C_{b d1} + C = TensorHead('C', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) + t = A(d1, d0)*B(-a, -d0)*C(-d1, -b) + tc = t.canon_bp() + assert str(tc) == 'A(L_0, L_1)*B(-a, -L_0)*C(-b, -L_1)' + +def test_canonicalize_no_dummies(): + Lorentz = TensorIndexType('Lorentz', dummy_name='L') + a, b, c, d = tensor_indices('a, b, c, d', Lorentz) + + # A commuting + # A^c A^b A^a + # T_c = A^a A^b A^c + A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1)) + t = A(c)*A(b)*A(a) + tc = t.canon_bp() + assert str(tc) == 'A(a)*A(b)*A(c)' + + # A anticommuting + # A^c A^b A^a + # T_c = -A^a A^b A^c + A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1), 1) + t = A(c)*A(b)*A(a) + tc = t.canon_bp() + assert str(tc) == '-A(a)*A(b)*A(c)' + + # A commuting and symmetric + # A^{b,d}*A^{c,a} + # T_c = A^{a c}*A^{b d} + A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) + t = A(b, d)*A(c, a) + tc = t.canon_bp() + assert str(tc) == 'A(a, c)*A(b, d)' + + # A anticommuting and symmetric + # A^{b,d}*A^{c,a} + # T_c = -A^{a c}*A^{b d} + A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2), 1) + t = A(b, d)*A(c, a) + tc = t.canon_bp() + assert str(tc) == '-A(a, c)*A(b, d)' + + # A^{c,a}*A^{b,d} + # T_c = A^{a c}*A^{b d} + t = A(c, a)*A(b, d) + tc = t.canon_bp() + assert str(tc) == 'A(a, c)*A(b, d)' + +def test_tensorhead_construction_without_symmetry(): + L = TensorIndexType('Lorentz') + A1 = TensorHead('A', [L, L]) + A2 = TensorHead('A', [L, L], TensorSymmetry.no_symmetry(2)) + assert A1 == A2 + A3 = TensorHead('A', [L, L], TensorSymmetry.fully_symmetric(2)) # Symmetric + assert A1 != A3 + +def test_no_metric_symmetry(): + # no metric symmetry; A no symmetry + # A^d1_d0 * A^d0_d1 + # T_c = A^d0_d1 * A^d1_d0 + Lorentz = TensorIndexType('Lorentz', dummy_name='L', metric_symmetry=0) + d0, d1, d2, d3 = tensor_indices('d:4', Lorentz) + A = TensorHead('A', [Lorentz]*2, TensorSymmetry.no_symmetry(2)) + t = A(d1, -d0)*A(d0, -d1) + tc = t.canon_bp() + assert str(tc) == 'A(L_0, -L_1)*A(L_1, -L_0)' + + # A^d1_d2 * A^d0_d3 * A^d2_d1 * A^d3_d0 + # T_c = A^d0_d1 * A^d1_d0 * A^d2_d3 * A^d3_d2 + t = A(d1, -d2)*A(d0, -d3)*A(d2, -d1)*A(d3, -d0) + tc = t.canon_bp() + assert str(tc) == 'A(L_0, -L_1)*A(L_1, -L_0)*A(L_2, -L_3)*A(L_3, -L_2)' + + # A^d0_d2 * A^d1_d3 * A^d3_d0 * A^d2_d1 + # T_c = A^d0_d1 * A^d1_d2 * A^d2_d3 * A^d3_d0 + t = A(d0, -d1)*A(d1, -d2)*A(d2, -d3)*A(d3, -d0) + tc = t.canon_bp() + assert str(tc) == 'A(L_0, -L_1)*A(L_1, -L_2)*A(L_2, -L_3)*A(L_3, -L_0)' + +def test_canonicalize1(): + Lorentz = TensorIndexType('Lorentz', dummy_name='L') + a, a0, a1, a2, a3, b, d0, d1, d2, d3 = \ + tensor_indices('a,a0,a1,a2,a3,b,d0,d1,d2,d3', Lorentz) + + # A_d0*A^d0; ord = [d0,-d0] + # T_c = A^d0*A_d0 + A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1)) + t = A(-d0)*A(d0) + tc = t.canon_bp() + assert str(tc) == 'A(L_0)*A(-L_0)' + + # A commuting + # A_d0*A_d1*A_d2*A^d2*A^d1*A^d0 + # T_c = A^d0*A_d0*A^d1*A_d1*A^d2*A_d2 + t = A(-d0)*A(-d1)*A(-d2)*A(d2)*A(d1)*A(d0) + tc = t.canon_bp() + assert str(tc) == 'A(L_0)*A(-L_0)*A(L_1)*A(-L_1)*A(L_2)*A(-L_2)' + + # A anticommuting + # A_d0*A_d1*A_d2*A^d2*A^d1*A^d0 + # T_c 0 + A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1), 1) + t = A(-d0)*A(-d1)*A(-d2)*A(d2)*A(d1)*A(d0) + tc = t.canon_bp() + assert tc == 0 + + # A commuting symmetric + # A^{d0 b}*A^a_d1*A^d1_d0 + # T_c = A^{a d0}*A^{b d1}*A_{d0 d1} + A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) + t = A(d0, b)*A(a, -d1)*A(d1, -d0) + tc = t.canon_bp() + assert str(tc) == 'A(a, L_0)*A(b, L_1)*A(-L_0, -L_1)' + + # A, B commuting symmetric + # A^{d0 b}*A^d1_d0*B^a_d1 + # T_c = A^{b d0}*A_d0^d1*B^a_d1 + B = TensorHead('B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) + t = A(d0, b)*A(d1, -d0)*B(a, -d1) + tc = t.canon_bp() + assert str(tc) == 'A(b, L_0)*A(-L_0, L_1)*B(a, -L_1)' + + # A commuting symmetric + # A^{d1 d0 b}*A^{a}_{d1 d0}; ord=[a,b, d0,-d0,d1,-d1] + # T_c = A^{a d0 d1}*A^{b}_{d0 d1} + A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(3)) + t = A(d1, d0, b)*A(a, -d1, -d0) + tc = t.canon_bp() + assert str(tc) == 'A(a, L_0, L_1)*A(b, -L_0, -L_1)' + + # A^{d3 d0 d2}*A^a0_{d1 d2}*A^d1_d3^a1*A^{a2 a3}_d0 + # T_c = A^{a0 d0 d1}*A^a1_d0^d2*A^{a2 a3 d3}*A_{d1 d2 d3} + t = A(d3, d0, d2)*A(a0, -d1, -d2)*A(d1, -d3, a1)*A(a2, a3, -d0) + tc = t.canon_bp() + assert str(tc) == 'A(a0, L_0, L_1)*A(a1, -L_0, L_2)*A(a2, a3, L_3)*A(-L_1, -L_2, -L_3)' + + # A commuting symmetric, B antisymmetric + # A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3 + # in this esxample and in the next three, + # renaming dummy indices and using symmetry of A, + # T = A^{d0 d1 d2} * A_{d0 d1 d3} * B_d2^d3 + # can = 0 + A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(3)) + B = TensorHead('B', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2)) + t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3) + tc = t.canon_bp() + assert tc == 0 + + # A anticommuting symmetric, B antisymmetric + # A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3 + # T_c = A^{d0 d1 d2} * A_{d0 d1}^d3 * B_{d2 d3} + A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(3), 1) + B = TensorHead('B', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2)) + t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3) + tc = t.canon_bp() + assert str(tc) == 'A(L_0, L_1, L_2)*A(-L_0, -L_1, L_3)*B(-L_2, -L_3)' + + # A anticommuting symmetric, B antisymmetric commuting, antisymmetric metric + # A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3 + # T_c = -A^{d0 d1 d2} * A_{d0 d1}^d3 * B_{d2 d3} + Spinor = TensorIndexType('Spinor', dummy_name='S', metric_symmetry=-1) + a, a0, a1, a2, a3, b, d0, d1, d2, d3 = \ + tensor_indices('a,a0,a1,a2,a3,b,d0,d1,d2,d3', Spinor) + A = TensorHead('A', [Spinor]*3, TensorSymmetry.fully_symmetric(3), 1) + B = TensorHead('B', [Spinor]*2, TensorSymmetry.fully_symmetric(-2)) + t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3) + tc = t.canon_bp() + assert str(tc) == '-A(S_0, S_1, S_2)*A(-S_0, -S_1, S_3)*B(-S_2, -S_3)' + + # A anticommuting symmetric, B antisymmetric anticommuting, + # no metric symmetry + # A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3 + # T_c = A^{d0 d1 d2} * A_{d0 d1 d3} * B_d2^d3 + Mat = TensorIndexType('Mat', metric_symmetry=0, dummy_name='M') + a, a0, a1, a2, a3, b, d0, d1, d2, d3 = \ + tensor_indices('a,a0,a1,a2,a3,b,d0,d1,d2,d3', Mat) + A = TensorHead('A', [Mat]*3, TensorSymmetry.fully_symmetric(3), 1) + B = TensorHead('B', [Mat]*2, TensorSymmetry.fully_symmetric(-2)) + t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3) + tc = t.canon_bp() + assert str(tc) == 'A(M_0, M_1, M_2)*A(-M_0, -M_1, -M_3)*B(-M_2, M_3)' + + # Gamma anticommuting + # Gamma_{mu nu} * gamma^rho * Gamma^{nu mu alpha} + # T_c = -Gamma^{mu nu} * gamma^rho * Gamma_{alpha mu nu} + alpha, beta, gamma, mu, nu, rho = \ + tensor_indices('alpha,beta,gamma,mu,nu,rho', Lorentz) + Gamma = TensorHead('Gamma', [Lorentz], + TensorSymmetry.fully_symmetric(1), 2) + Gamma2 = TensorHead('Gamma', [Lorentz]*2, + TensorSymmetry.fully_symmetric(-2), 2) + Gamma3 = TensorHead('Gamma', [Lorentz]*3, + TensorSymmetry.fully_symmetric(-3), 2) + t = Gamma2(-mu, -nu)*Gamma(rho)*Gamma3(nu, mu, alpha) + tc = t.canon_bp() + assert str(tc) == '-Gamma(L_0, L_1)*Gamma(rho)*Gamma(alpha, -L_0, -L_1)' + + # Gamma_{mu nu} * Gamma^{gamma beta} * gamma_rho * Gamma^{nu mu alpha} + # T_c = Gamma^{mu nu} * Gamma^{beta gamma} * gamma_rho * Gamma^alpha_{mu nu} + t = Gamma2(mu, nu)*Gamma2(beta, gamma)*Gamma(-rho)*Gamma3(alpha, -mu, -nu) + tc = t.canon_bp() + assert str(tc) == 'Gamma(L_0, L_1)*Gamma(beta, gamma)*Gamma(-rho)*Gamma(alpha, -L_0, -L_1)' + + # f^a_{b,c} antisymmetric in b,c; A_mu^a no symmetry + # f^c_{d a} * f_{c e b} * A_mu^d * A_nu^a * A^{nu e} * A^{mu b} + # g = [8,11,5, 9,13,7, 1,10, 3,4, 2,12, 0,6, 14,15] + # T_c = -f^{a b c} * f_a^{d e} * A^mu_b * A_{mu d} * A^nu_c * A_{nu e} + Flavor = TensorIndexType('Flavor', dummy_name='F') + a, b, c, d, e, ff = tensor_indices('a,b,c,d,e,f', Flavor) + mu, nu = tensor_indices('mu,nu', Lorentz) + f = TensorHead('f', [Flavor]*3, TensorSymmetry.direct_product(1, -2)) + A = TensorHead('A', [Lorentz, Flavor], TensorSymmetry.no_symmetry(2)) + t = f(c, -d, -a)*f(-c, -e, -b)*A(-mu, d)*A(-nu, a)*A(nu, e)*A(mu, b) + tc = t.canon_bp() + assert str(tc) == '-f(F_0, F_1, F_2)*f(-F_0, F_3, F_4)*A(L_0, -F_1)*A(-L_0, -F_3)*A(L_1, -F_2)*A(-L_1, -F_4)' + + +def test_bug_correction_tensor_indices(): + # to make sure that tensor_indices does not return a list if creating + # only one index: + A = TensorIndexType("A") + i = tensor_indices('i', A) + assert not isinstance(i, (tuple, list)) + assert isinstance(i, TensorIndex) + + +def test_riemann_invariants(): + Lorentz = TensorIndexType('Lorentz', dummy_name='L') + d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11 = \ + tensor_indices('d0:12', Lorentz) + # R^{d0 d1}_{d1 d0}; ord = [d0,-d0,d1,-d1] + # T_c = -R^{d0 d1}_{d0 d1} + R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann()) + t = R(d0, d1, -d1, -d0) + tc = t.canon_bp() + assert str(tc) == '-R(L_0, L_1, -L_0, -L_1)' + + # R_d11^d1_d0^d5 * R^{d6 d4 d0}_d5 * R_{d7 d2 d8 d9} * + # R_{d10 d3 d6 d4} * R^{d2 d7 d11}_d1 * R^{d8 d9 d3 d10} + # can = [0,2,4,6, 1,3,8,10, 5,7,12,14, 9,11,16,18, 13,15,20,22, + # 17,19,21>> from sympy.tensor.tensor import TensorIndexType, TensorHead + >>> from sympy.tensor.toperators import PartialDerivative + >>> from sympy import symbols + >>> L = TensorIndexType("L") + >>> A = TensorHead("A", [L]) + >>> B = TensorHead("B", [L]) + >>> i, j, k = symbols("i j k") + + >>> expr = PartialDerivative(A(i), A(j)) + >>> expr + PartialDerivative(A(i), A(j)) + + The ``PartialDerivative`` object behaves like a tensorial expression: + + >>> expr.get_indices() + [i, -j] + + Notice that the deriving variables have opposite valence than the + printed one: ``A(j)`` is printed as covariant, but the index of the + derivative is actually contravariant, i.e. ``-j``. + + Indices can be contracted: + + >>> expr = PartialDerivative(A(i), A(i)) + >>> expr + PartialDerivative(A(L_0), A(L_0)) + >>> expr.get_indices() + [L_0, -L_0] + + The method ``.get_indices()`` always returns all indices (even the + contracted ones). If only uncontracted indices are needed, call + ``.get_free_indices()``: + + >>> expr.get_free_indices() + [] + + Nested partial derivatives are flattened: + + >>> expr = PartialDerivative(PartialDerivative(A(i), A(j)), A(k)) + >>> expr + PartialDerivative(A(i), A(j), A(k)) + >>> expr.get_indices() + [i, -j, -k] + + Replace a derivative with array values: + + >>> from sympy.abc import x, y + >>> from sympy import sin, log + >>> compA = [sin(x), log(x)*y**3] + >>> compB = [x, y] + >>> expr = PartialDerivative(A(i), B(j)) + >>> expr.replace_with_arrays({A(i): compA, B(i): compB}) + [[cos(x), 0], [y**3/x, 3*y**2*log(x)]] + + The returned array is indexed by `(i, -j)`. + + Be careful that other SymPy modules put the indices of the deriving + variables before the indices of the derivand in the derivative result. + For example: + + >>> expr.get_free_indices() + [i, -j] + + >>> from sympy import Matrix, Array + >>> Matrix(compA).diff(Matrix(compB)).reshape(2, 2) + [[cos(x), y**3/x], [0, 3*y**2*log(x)]] + >>> Array(compA).diff(Array(compB)) + [[cos(x), y**3/x], [0, 3*y**2*log(x)]] + + These are the transpose of the result of ``PartialDerivative``, + as the matrix and the array modules put the index `-j` before `i` in the + derivative result. An array read with index order `(-j, i)` is indeed the + transpose of the same array read with index order `(i, -j)`. By specifying + the index order to ``.replace_with_arrays`` one can get a compatible + expression: + + >>> expr.replace_with_arrays({A(i): compA, B(i): compB}, [-j, i]) + [[cos(x), y**3/x], [0, 3*y**2*log(x)]] + """ + + def __new__(cls, expr, *variables): + + # Flatten: + if isinstance(expr, PartialDerivative): + variables = expr.variables + variables + expr = expr.expr + + args, indices, free, dum = cls._contract_indices_for_derivative( + S(expr), variables) + + obj = TensExpr.__new__(cls, *args) + + obj._indices = indices + obj._free = free + obj._dum = dum + return obj + + @property + def coeff(self): + return S.One + + @property + def nocoeff(self): + return self + + @classmethod + def _contract_indices_for_derivative(cls, expr, variables): + variables_opposite_valence = [] + + for i in variables: + if isinstance(i, Tensor): + i_free_indices = i.get_free_indices() + variables_opposite_valence.append( + i.xreplace({k: -k for k in i_free_indices})) + elif isinstance(i, Symbol): + variables_opposite_valence.append(i) + + args, indices, free, dum = TensMul._tensMul_contract_indices( + [expr] + variables_opposite_valence, replace_indices=True) + + for i in range(1, len(args)): + args_i = args[i] + if isinstance(args_i, Tensor): + i_indices = args[i].get_free_indices() + args[i] = args[i].xreplace({k: -k for k in i_indices}) + + return args, indices, free, dum + + def doit(self, **hints): + args, indices, free, dum = self._contract_indices_for_derivative(self.expr, self.variables) + + obj = self.func(*args) + obj._indices = indices + obj._free = free + obj._dum = dum + + return obj + + def _expand_partial_derivative(self): + args, indices, free, dum = self._contract_indices_for_derivative(self.expr, self.variables) + + obj = self.func(*args) + obj._indices = indices + obj._free = free + obj._dum = dum + + result = obj + + if not args[0].free_symbols: + return S.Zero + elif isinstance(obj.expr, TensAdd): + # take care of sums of multi PDs + result = obj.expr.func(*[ + self.func(a, *obj.variables)._expand_partial_derivative() + for a in result.expr.args]) + elif isinstance(obj.expr, TensMul): + # take care of products of multi PDs + if len(obj.variables) == 1: + # derivative with respect to single variable + terms = [] + mulargs = list(obj.expr.args) + for ind in range(len(mulargs)): + if not isinstance(sympify(mulargs[ind]), Number): + # a number coefficient is not considered for + # expansion of PartialDerivative + d = self.func(mulargs[ind], *obj.variables)._expand_partial_derivative() + terms.append(TensMul(*(mulargs[:ind] + + [d] + + mulargs[(ind + 1):]))) + result = TensAdd.fromiter(terms) + else: + # derivative with respect to multiple variables + # decompose: + # partial(expr, (u, v)) + # = partial(partial(expr, u).doit(), v).doit() + result = obj.expr # init with expr + for v in obj.variables: + result = self.func(result, v)._expand_partial_derivative() + # then throw PD on it + + return result + + def _perform_derivative(self): + result = self.expr + for v in self.variables: + if isinstance(result, TensExpr): + result = result._eval_partial_derivative(v) + else: + if v._diff_wrt: + result = result._eval_derivative(v) + else: + result = S.Zero + return result + + def get_indices(self): + return self._indices + + def get_free_indices(self): + free = sorted(self._free, key=lambda x: x[1]) + return [i[0] for i in free] + + def _replace_indices(self, repl): + expr = self.expr.xreplace(repl) + mirrored = {-k: -v for k, v in repl.items()} + variables = [i.xreplace(mirrored) for i in self.variables] + return self.func(expr, *variables) + + @property + def expr(self): + return self.args[0] + + @property + def variables(self): + return self.args[1:] + + def _extract_data(self, replacement_dict): + from .array import derive_by_array, tensorcontraction + indices, array = self.expr._extract_data(replacement_dict) + for variable in self.variables: + var_indices, var_array = variable._extract_data(replacement_dict) + var_indices = [-i for i in var_indices] + coeff_array, var_array = zip(*[i.as_coeff_Mul() for i in var_array]) + dim_before = len(array.shape) + array = derive_by_array(array, var_array) + dim_after = len(array.shape) + dim_increase = dim_after - dim_before + array = permutedims(array, [i + dim_increase for i in range(dim_before)] + list(range(dim_increase))) + array = array.as_mutable() + varindex = var_indices[0] + # Remove coefficients of base vector: + coeff_index = [0] + [slice(None) for i in range(len(indices))] + for i, coeff in enumerate(coeff_array): + coeff_index[0] = i + array[tuple(coeff_index)] /= coeff + if -varindex in indices: + pos = indices.index(-varindex) + array = tensorcontraction(array, (0, pos+1)) + indices.pop(pos) + else: + indices.append(varindex) + return indices, array diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/__init__.py b/.venv/lib/python3.12/site-packages/sympy/testing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..aa66402955e7d5d2b27cccc6627b42d33f4cd855 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/testing/__init__.py @@ -0,0 +1,10 @@ +"""This module contains code for running the tests in SymPy.""" + + +from .runtests import doctest +from .runtests_pytest import test + + +__all__ = [ + 'test', 'doctest', +] diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59cd8b764e76e2bd95f0a4cba5677ec7c6250751 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/matrices.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/matrices.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..271353a795c132f22703806c0e68249bdc586114 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/matrices.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/pytest.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/pytest.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4adedbdbf04d9667f4b6865ceff00a6bfbc255d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/pytest.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/quality_unicode.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/quality_unicode.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffc7dfe447e7dc0c30bf5880552aeeae51085b83 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/quality_unicode.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/randtest.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/randtest.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e56610c7cfd3ca6c36fc3c535f681a38f635994 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/randtest.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/runtests.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/runtests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ab56fb004b355f82a866ddebd988f12e4ba368e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/runtests.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/runtests_pytest.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/runtests_pytest.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d0e314d5f28f669ec32d5893f576bfb2851094f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/runtests_pytest.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/tmpfiles.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/tmpfiles.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7a98998529c65ccaf3b2801b97d2c3e4ae52217 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/testing/__pycache__/tmpfiles.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/matrices.py b/.venv/lib/python3.12/site-packages/sympy/testing/matrices.py new file mode 100644 index 0000000000000000000000000000000000000000..236a384366df7f69d0d92f43f7e007e95c12388c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/testing/matrices.py @@ -0,0 +1,8 @@ +def allclose(A, B, rtol=1e-05, atol=1e-08): + if len(A) != len(B): + return False + + for x, y in zip(A, B): + if abs(x-y) > atol + rtol * max(abs(x), abs(y)): + return False + return True diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/pytest.py b/.venv/lib/python3.12/site-packages/sympy/testing/pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..498515a2d3c0a167a5f7067753736898cfa64799 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/testing/pytest.py @@ -0,0 +1,392 @@ +"""py.test hacks to support XFAIL/XPASS""" + +import platform +import sys +import re +import functools +import os +import contextlib +import warnings +import inspect +import pathlib +from typing import Any, Callable + +from sympy.utilities.exceptions import SymPyDeprecationWarning +# Imported here for backwards compatibility. Note: do not import this from +# here in library code (importing sympy.pytest in library code will break the +# pytest integration). +from sympy.utilities.exceptions import ignore_warnings # noqa:F401 + +ON_CI = os.getenv('CI', None) == "true" + +try: + import pytest + USE_PYTEST = getattr(sys, '_running_pytest', False) +except ImportError: + USE_PYTEST = False + +IS_WASM: bool = sys.platform == 'emscripten' or platform.machine() in ["wasm32", "wasm64"] + +raises: Callable[[Any, Any], Any] +XFAIL: Callable[[Any], Any] +skip: Callable[[Any], Any] +SKIP: Callable[[Any], Any] +slow: Callable[[Any], Any] +tooslow: Callable[[Any], Any] +nocache_fail: Callable[[Any], Any] + + +if USE_PYTEST: + raises = pytest.raises + skip = pytest.skip + XFAIL = pytest.mark.xfail + SKIP = pytest.mark.skip + slow = pytest.mark.slow + tooslow = pytest.mark.tooslow + nocache_fail = pytest.mark.nocache_fail + from _pytest.outcomes import Failed + +else: + # Not using pytest so define the things that would have been imported from + # there. + + # _pytest._code.code.ExceptionInfo + class ExceptionInfo: + def __init__(self, value): + self.value = value + + def __repr__(self): + return "".format(self.value) + + + def raises(expectedException, code=None): + """ + Tests that ``code`` raises the exception ``expectedException``. + + ``code`` may be a callable, such as a lambda expression or function + name. + + If ``code`` is not given or None, ``raises`` will return a context + manager for use in ``with`` statements; the code to execute then + comes from the scope of the ``with``. + + ``raises()`` does nothing if the callable raises the expected exception, + otherwise it raises an AssertionError. + + Examples + ======== + + >>> from sympy.testing.pytest import raises + + >>> raises(ZeroDivisionError, lambda: 1/0) + + >>> raises(ZeroDivisionError, lambda: 1/2) + Traceback (most recent call last): + ... + Failed: DID NOT RAISE + + >>> with raises(ZeroDivisionError): + ... n = 1/0 + >>> with raises(ZeroDivisionError): + ... n = 1/2 + Traceback (most recent call last): + ... + Failed: DID NOT RAISE + + Note that you cannot test multiple statements via + ``with raises``: + + >>> with raises(ZeroDivisionError): + ... n = 1/0 # will execute and raise, aborting the ``with`` + ... n = 9999/0 # never executed + + This is just what ``with`` is supposed to do: abort the + contained statement sequence at the first exception and let + the context manager deal with the exception. + + To test multiple statements, you'll need a separate ``with`` + for each: + + >>> with raises(ZeroDivisionError): + ... n = 1/0 # will execute and raise + >>> with raises(ZeroDivisionError): + ... n = 9999/0 # will also execute and raise + + """ + if code is None: + return RaisesContext(expectedException) + elif callable(code): + try: + code() + except expectedException as e: + return ExceptionInfo(e) + raise Failed("DID NOT RAISE") + elif isinstance(code, str): + raise TypeError( + '\'raises(xxx, "code")\' has been phased out; ' + 'change \'raises(xxx, "expression")\' ' + 'to \'raises(xxx, lambda: expression)\', ' + '\'raises(xxx, "statement")\' ' + 'to \'with raises(xxx): statement\'') + else: + raise TypeError( + 'raises() expects a callable for the 2nd argument.') + + class RaisesContext: + def __init__(self, expectedException): + self.expectedException = expectedException + + def __enter__(self): + return None + + def __exit__(self, exc_type, exc_value, traceback): + if exc_type is None: + raise Failed("DID NOT RAISE") + return issubclass(exc_type, self.expectedException) + + class XFail(Exception): + pass + + class XPass(Exception): + pass + + class Skipped(Exception): + pass + + class Failed(Exception): # type: ignore + pass + + def XFAIL(func): + def wrapper(): + try: + func() + except Exception as e: + message = str(e) + if message != "Timeout": + raise XFail(func.__name__) + else: + raise Skipped("Timeout") + raise XPass(func.__name__) + + wrapper = functools.update_wrapper(wrapper, func) + return wrapper + + def skip(str): + raise Skipped(str) + + def SKIP(reason): + """Similar to ``skip()``, but this is a decorator. """ + def wrapper(func): + def func_wrapper(): + raise Skipped(reason) + + func_wrapper = functools.update_wrapper(func_wrapper, func) + return func_wrapper + + return wrapper + + def slow(func): + func._slow = True + + def func_wrapper(): + func() + + func_wrapper = functools.update_wrapper(func_wrapper, func) + func_wrapper.__wrapped__ = func + return func_wrapper + + def tooslow(func): + func._slow = True + func._tooslow = True + + def func_wrapper(): + skip("Too slow") + + func_wrapper = functools.update_wrapper(func_wrapper, func) + func_wrapper.__wrapped__ = func + return func_wrapper + + def nocache_fail(func): + "Dummy decorator for marking tests that fail when cache is disabled" + return func + +@contextlib.contextmanager +def warns(warningcls, *, match='', test_stacklevel=True): + ''' + Like raises but tests that warnings are emitted. + + >>> from sympy.testing.pytest import warns + >>> import warnings + + >>> with warns(UserWarning): + ... warnings.warn('deprecated', UserWarning, stacklevel=2) + + >>> with warns(UserWarning): + ... pass + Traceback (most recent call last): + ... + Failed: DID NOT WARN. No warnings of type UserWarning\ + was emitted. The list of emitted warnings is: []. + + ``test_stacklevel`` makes it check that the ``stacklevel`` parameter to + ``warn()`` is set so that the warning shows the user line of code (the + code under the warns() context manager). Set this to False if this is + ambiguous or if the context manager does not test the direct user code + that emits the warning. + + If the warning is a ``SymPyDeprecationWarning``, this additionally tests + that the ``active_deprecations_target`` is a real target in the + ``active-deprecations.md`` file. + + ''' + # Absorbs all warnings in warnrec + with warnings.catch_warnings(record=True) as warnrec: + # Any warning other than the one we are looking for is an error + warnings.simplefilter("error") + warnings.filterwarnings("always", category=warningcls) + # Now run the test + yield warnrec + + # Raise if expected warning not found + if not any(issubclass(w.category, warningcls) for w in warnrec): + msg = ('Failed: DID NOT WARN.' + ' No warnings of type %s was emitted.' + ' The list of emitted warnings is: %s.' + ) % (warningcls, [w.message for w in warnrec]) + raise Failed(msg) + + # We don't include the match in the filter above because it would then + # fall to the error filter, so we instead manually check that it matches + # here + for w in warnrec: + # Should always be true due to the filters above + assert issubclass(w.category, warningcls) + if not re.compile(match, re.IGNORECASE).match(str(w.message)): + raise Failed(f"Failed: WRONG MESSAGE. A warning with of the correct category ({warningcls.__name__}) was issued, but it did not match the given match regex ({match!r})") + + if test_stacklevel: + for f in inspect.stack(): + thisfile = f.filename + file = os.path.split(thisfile)[1] + if file.startswith('test_'): + break + elif file == 'doctest.py': + # skip the stacklevel testing in the doctests of this + # function + return + else: + raise RuntimeError("Could not find the file for the given warning to test the stacklevel") + for w in warnrec: + if w.filename != thisfile: + msg = f'''\ +Failed: Warning has the wrong stacklevel. The warning stacklevel needs to be +set so that the line of code shown in the warning message is user code that +calls the deprecated code (the current stacklevel is showing code from +{w.filename} (line {w.lineno}), expected {thisfile})'''.replace('\n', ' ') + raise Failed(msg) + + if warningcls == SymPyDeprecationWarning: + this_file = pathlib.Path(__file__) + active_deprecations_file = (this_file.parent.parent.parent / 'doc' / + 'src' / 'explanation' / + 'active-deprecations.md') + if not active_deprecations_file.exists(): + # We can only test that the active_deprecations_target works if we are + # in the git repo. + return + targets = [] + for w in warnrec: + targets.append(w.message.active_deprecations_target) + text = pathlib.Path(active_deprecations_file).read_text(encoding="utf-8") + for target in targets: + if f'({target})=' not in text: + raise Failed(f"The active deprecations target {target!r} does not appear to be a valid target in the active-deprecations.md file ({active_deprecations_file}).") + +def _both_exp_pow(func): + """ + Decorator used to run the test twice: the first time `e^x` is represented + as ``Pow(E, x)``, the second time as ``exp(x)`` (exponential object is not + a power). + + This is a temporary trick helping to manage the elimination of the class + ``exp`` in favor of a replacement by ``Pow(E, ...)``. + """ + from sympy.core.parameters import _exp_is_pow + + def func_wrap(): + with _exp_is_pow(True): + func() + with _exp_is_pow(False): + func() + + wrapper = functools.update_wrapper(func_wrap, func) + return wrapper + + +@contextlib.contextmanager +def warns_deprecated_sympy(): + ''' + Shorthand for ``warns(SymPyDeprecationWarning)`` + + This is the recommended way to test that ``SymPyDeprecationWarning`` is + emitted for deprecated features in SymPy. To test for other warnings use + ``warns``. To suppress warnings without asserting that they are emitted + use ``ignore_warnings``. + + .. note:: + + ``warns_deprecated_sympy()`` is only intended for internal use in the + SymPy test suite to test that a deprecation warning triggers properly. + All other code in the SymPy codebase, including documentation examples, + should not use deprecated behavior. + + If you are a user of SymPy and you want to disable + SymPyDeprecationWarnings, use ``warnings`` filters (see + :ref:`silencing-sympy-deprecation-warnings`). + + >>> from sympy.testing.pytest import warns_deprecated_sympy + >>> from sympy.utilities.exceptions import sympy_deprecation_warning + >>> with warns_deprecated_sympy(): + ... sympy_deprecation_warning("Don't use", + ... deprecated_since_version="1.0", + ... active_deprecations_target="active-deprecations") + + >>> with warns_deprecated_sympy(): + ... pass + Traceback (most recent call last): + ... + Failed: DID NOT WARN. No warnings of type \ + SymPyDeprecationWarning was emitted. The list of emitted warnings is: []. + + .. note:: + + Sometimes the stacklevel test will fail because the same warning is + emitted multiple times. In this case, you can use + :func:`sympy.utilities.exceptions.ignore_warnings` in the code to + prevent the ``SymPyDeprecationWarning`` from being emitted again + recursively. In rare cases it is impossible to have a consistent + ``stacklevel`` for deprecation warnings because different ways of + calling a function will produce different call stacks.. In those cases, + use ``warns(SymPyDeprecationWarning)`` instead. + + See Also + ======== + sympy.utilities.exceptions.SymPyDeprecationWarning + sympy.utilities.exceptions.sympy_deprecation_warning + sympy.utilities.decorator.deprecated + + ''' + with warns(SymPyDeprecationWarning): + yield + + +def skip_under_pyodide(message): + """Decorator to skip a test if running under Pyodide/WASM.""" + def decorator(test_func): + @functools.wraps(test_func) + def test_wrapper(): + if IS_WASM: + skip(message) + return test_func() + return test_wrapper + return decorator diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/quality_unicode.py b/.venv/lib/python3.12/site-packages/sympy/testing/quality_unicode.py new file mode 100644 index 0000000000000000000000000000000000000000..d43623ff5112610e377347f50c6a40a15810644b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/testing/quality_unicode.py @@ -0,0 +1,102 @@ +import re +import fnmatch + + +message_unicode_B = \ + "File contains a unicode character : %s, line %s. " \ + "But not in the whitelist. " \ + "Add the file to the whitelist in " + __file__ +message_unicode_D = \ + "File does not contain a unicode character : %s." \ + "but is in the whitelist. " \ + "Remove the file from the whitelist in " + __file__ + + +encoding_header_re = re.compile( + r'^[ \t\f]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)') + +# Whitelist pattern for files which can have unicode. +unicode_whitelist = [ + # Author names can include non-ASCII characters + r'*/bin/authors_update.py', + r'*/bin/mailmap_check.py', + + # These files have functions and test functions for unicode input and + # output. + r'*/sympy/testing/tests/test_code_quality.py', + r'*/sympy/physics/vector/tests/test_printing.py', + r'*/physics/quantum/tests/test_printing.py', + r'*/sympy/vector/tests/test_printing.py', + r'*/sympy/parsing/tests/test_sympy_parser.py', + r'*/sympy/printing/pretty/stringpict.py', + r'*/sympy/printing/pretty/tests/test_pretty.py', + r'*/sympy/printing/tests/test_conventions.py', + r'*/sympy/printing/tests/test_preview.py', + r'*/liealgebras/type_g.py', + r'*/liealgebras/weyl_group.py', + r'*/liealgebras/tests/test_type_G.py', + + # wigner.py and polarization.py have unicode doctests. These probably + # don't need to be there but some of the examples that are there are + # pretty ugly without use_unicode (matrices need to be wrapped across + # multiple lines etc) + r'*/sympy/physics/wigner.py', + r'*/sympy/physics/optics/polarization.py', + + # joint.py uses some unicode for variable names in the docstrings + r'*/sympy/physics/mechanics/joint.py', + + # lll method has unicode in docstring references and author name + r'*/sympy/polys/matrices/domainmatrix.py', + r'*/sympy/matrices/repmatrix.py', + + # Explanation of symbols uses greek letters + r'*/sympy/core/symbol.py', +] + +unicode_strict_whitelist = [ + r'*/sympy/parsing/latex/_antlr/__init__.py', + # test_mathematica.py uses some unicode for testing Greek characters are working #24055 + r'*/sympy/parsing/tests/test_mathematica.py', +] + + +def _test_this_file_encoding( + fname, test_file, + unicode_whitelist=unicode_whitelist, + unicode_strict_whitelist=unicode_strict_whitelist): + """Test helper function for unicode test + + The test may have to operate on filewise manner, so it had moved + to a separate process. + """ + has_unicode = False + + is_in_whitelist = False + is_in_strict_whitelist = False + for patt in unicode_whitelist: + if fnmatch.fnmatch(fname, patt): + is_in_whitelist = True + break + for patt in unicode_strict_whitelist: + if fnmatch.fnmatch(fname, patt): + is_in_strict_whitelist = True + is_in_whitelist = True + break + + if is_in_whitelist: + for idx, line in enumerate(test_file): + try: + line.encode(encoding='ascii') + except (UnicodeEncodeError, UnicodeDecodeError): + has_unicode = True + + if not has_unicode and not is_in_strict_whitelist: + assert False, message_unicode_D % fname + + else: + for idx, line in enumerate(test_file): + try: + line.encode(encoding='ascii') + except (UnicodeEncodeError, UnicodeDecodeError): + assert False, message_unicode_B % (fname, idx + 1) diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/randtest.py b/.venv/lib/python3.12/site-packages/sympy/testing/randtest.py new file mode 100644 index 0000000000000000000000000000000000000000..3ce2c8c031eec1c886532daba32c96d83e9cf85c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/testing/randtest.py @@ -0,0 +1,19 @@ +""" +.. deprecated:: 1.10 + + ``sympy.testing.randtest`` functions have been moved to + :mod:`sympy.core.random`. + +""" +from sympy.utilities.exceptions import sympy_deprecation_warning + +sympy_deprecation_warning("The sympy.testing.randtest submodule is deprecated. Use sympy.core.random instead.", + deprecated_since_version="1.10", + active_deprecations_target="deprecated-sympy-testing-randtest") + +from sympy.core.random import ( # noqa:F401 + random_complex_number, + verify_numerically, + test_derivative_numerically, + _randrange, + _randint) diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/runtests.py b/.venv/lib/python3.12/site-packages/sympy/testing/runtests.py new file mode 100644 index 0000000000000000000000000000000000000000..e2650e4e6dabaaa07fc25c76cce3d9d28723b0d5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/testing/runtests.py @@ -0,0 +1,2409 @@ +""" +This is our testing framework. + +Goals: + +* it should be compatible with py.test and operate very similarly + (or identically) +* does not require any external dependencies +* preferably all the functionality should be in this file only +* no magic, just import the test file and execute the test functions, that's it +* portable + +""" + +import os +import sys +import platform +import inspect +import traceback +import pdb +import re +import linecache +import time +from fnmatch import fnmatch +from timeit import default_timer as clock +import doctest as pdoctest # avoid clashing with our doctest() function +from doctest import DocTestFinder, DocTestRunner +import random +import subprocess +import shutil +import signal +import stat +import tempfile +import warnings +from contextlib import contextmanager +from inspect import unwrap +from pathlib import Path + +from sympy.core.cache import clear_cache +from sympy.external import import_module +from sympy.external.gmpy import GROUND_TYPES + +IS_WINDOWS = (os.name == 'nt') +ON_CI = os.getenv('CI', None) + +# empirically generated list of the proportion of time spent running +# an even split of tests. This should periodically be regenerated. +# A list of [.6, .1, .3] would mean that if the tests are evenly split +# into '1/3', '2/3', '3/3', the first split would take 60% of the time, +# the second 10% and the third 30%. These lists are normalized to sum +# to 1, so [60, 10, 30] has the same behavior as [6, 1, 3] or [.6, .1, .3]. +# +# This list can be generated with the code: +# from time import time +# import sympy +# import os +# os.environ["CI"] = 'true' # Mock CI to get more correct densities +# delays, num_splits = [], 30 +# for i in range(1, num_splits + 1): +# tic = time() +# sympy.test(split='{}/{}'.format(i, num_splits), time_balance=False) # Add slow=True for slow tests +# delays.append(time() - tic) +# tot = sum(delays) +# print([round(x / tot, 4) for x in delays]) +SPLIT_DENSITY = [ + 0.0059, 0.0027, 0.0068, 0.0011, 0.0006, + 0.0058, 0.0047, 0.0046, 0.004, 0.0257, + 0.0017, 0.0026, 0.004, 0.0032, 0.0016, + 0.0015, 0.0004, 0.0011, 0.0016, 0.0014, + 0.0077, 0.0137, 0.0217, 0.0074, 0.0043, + 0.0067, 0.0236, 0.0004, 0.1189, 0.0142, + 0.0234, 0.0003, 0.0003, 0.0047, 0.0006, + 0.0013, 0.0004, 0.0008, 0.0007, 0.0006, + 0.0139, 0.0013, 0.0007, 0.0051, 0.002, + 0.0004, 0.0005, 0.0213, 0.0048, 0.0016, + 0.0012, 0.0014, 0.0024, 0.0015, 0.0004, + 0.0005, 0.0007, 0.011, 0.0062, 0.0015, + 0.0021, 0.0049, 0.0006, 0.0006, 0.0011, + 0.0006, 0.0019, 0.003, 0.0044, 0.0054, + 0.0057, 0.0049, 0.0016, 0.0006, 0.0009, + 0.0006, 0.0012, 0.0006, 0.0149, 0.0532, + 0.0076, 0.0041, 0.0024, 0.0135, 0.0081, + 0.2209, 0.0459, 0.0438, 0.0488, 0.0137, + 0.002, 0.0003, 0.0008, 0.0039, 0.0024, + 0.0005, 0.0004, 0.003, 0.056, 0.0026] +SPLIT_DENSITY_SLOW = [0.0086, 0.0004, 0.0568, 0.0003, 0.0032, 0.0005, 0.0004, 0.0013, 0.0016, 0.0648, 0.0198, 0.1285, 0.098, 0.0005, 0.0064, 0.0003, 0.0004, 0.0026, 0.0007, 0.0051, 0.0089, 0.0024, 0.0033, 0.0057, 0.0005, 0.0003, 0.001, 0.0045, 0.0091, 0.0006, 0.0005, 0.0321, 0.0059, 0.1105, 0.216, 0.1489, 0.0004, 0.0003, 0.0006, 0.0483] + +class Skipped(Exception): + pass + +class TimeOutError(Exception): + pass + +class DependencyError(Exception): + pass + + +def _indent(s, indent=4): + """ + Add the given number of space characters to the beginning of + every non-blank line in ``s``, and return the result. + If the string ``s`` is Unicode, it is encoded using the stdout + encoding and the ``backslashreplace`` error handler. + """ + # This regexp matches the start of non-blank lines: + return re.sub('(?m)^(?!$)', indent*' ', s) + + +pdoctest._indent = _indent # type: ignore + +# override reporter to maintain windows and python3 + + +def _report_failure(self, out, test, example, got): + """ + Report that the given example failed. + """ + s = self._checker.output_difference(example, got, self.optionflags) + s = s.encode('raw_unicode_escape').decode('utf8', 'ignore') + out(self._failure_header(test, example) + s) + + +if IS_WINDOWS: + DocTestRunner.report_failure = _report_failure # type: ignore + + +def convert_to_native_paths(lst): + """ + Converts a list of '/' separated paths into a list of + native (os.sep separated) paths and converts to lowercase + if the system is case insensitive. + """ + newlst = [] + for rv in lst: + rv = os.path.join(*rv.split("/")) + # on windows the slash after the colon is dropped + if sys.platform == "win32": + pos = rv.find(':') + if pos != -1: + if rv[pos + 1] != '\\': + rv = rv[:pos + 1] + '\\' + rv[pos + 1:] + newlst.append(os.path.normcase(rv)) + return newlst + + +def get_sympy_dir(): + """ + Returns the root SymPy directory and set the global value + indicating whether the system is case sensitive or not. + """ + this_file = os.path.abspath(__file__) + sympy_dir = os.path.join(os.path.dirname(this_file), "..", "..") + sympy_dir = os.path.normpath(sympy_dir) + return os.path.normcase(sympy_dir) + + +def setup_pprint(disable_line_wrap=True): + from sympy.interactive.printing import init_printing + from sympy.printing.pretty.pretty import pprint_use_unicode + import sympy.interactive.printing as interactive_printing + from sympy.printing.pretty import stringpict + + # Prevent init_printing() in doctests from affecting other doctests + interactive_printing.NO_GLOBAL = True + + # force pprint to be in ascii mode in doctests + use_unicode_prev = pprint_use_unicode(False) + + # disable line wrapping for pprint() outputs + wrap_line_prev = stringpict._GLOBAL_WRAP_LINE + if disable_line_wrap: + stringpict._GLOBAL_WRAP_LINE = False + + # hook our nice, hash-stable strprinter + init_printing(pretty_print=False) + + return use_unicode_prev, wrap_line_prev + + +@contextmanager +def raise_on_deprecated(): + """Context manager to make DeprecationWarning raise an error + + This is to catch SymPyDeprecationWarning from library code while running + tests and doctests. It is important to use this context manager around + each individual test/doctest in case some tests modify the warning + filters. + """ + with warnings.catch_warnings(): + warnings.filterwarnings('error', '.*', DeprecationWarning, module='sympy.*') + yield + + +def run_in_subprocess_with_hash_randomization( + function, function_args=(), + function_kwargs=None, command=sys.executable, + module='sympy.testing.runtests', force=False): + """ + Run a function in a Python subprocess with hash randomization enabled. + + If hash randomization is not supported by the version of Python given, it + returns False. Otherwise, it returns the exit value of the command. The + function is passed to sys.exit(), so the return value of the function will + be the return value. + + The environment variable PYTHONHASHSEED is used to seed Python's hash + randomization. If it is set, this function will return False, because + starting a new subprocess is unnecessary in that case. If it is not set, + one is set at random, and the tests are run. Note that if this + environment variable is set when Python starts, hash randomization is + automatically enabled. To force a subprocess to be created even if + PYTHONHASHSEED is set, pass ``force=True``. This flag will not force a + subprocess in Python versions that do not support hash randomization (see + below), because those versions of Python do not support the ``-R`` flag. + + ``function`` should be a string name of a function that is importable from + the module ``module``, like "_test". The default for ``module`` is + "sympy.testing.runtests". ``function_args`` and ``function_kwargs`` + should be a repr-able tuple and dict, respectively. The default Python + command is sys.executable, which is the currently running Python command. + + This function is necessary because the seed for hash randomization must be + set by the environment variable before Python starts. Hence, in order to + use a predetermined seed for tests, we must start Python in a separate + subprocess. + + Hash randomization was added in the minor Python versions 2.6.8, 2.7.3, + 3.1.5, and 3.2.3, and is enabled by default in all Python versions after + and including 3.3.0. + + Examples + ======== + + >>> from sympy.testing.runtests import ( + ... run_in_subprocess_with_hash_randomization) + >>> # run the core tests in verbose mode + >>> run_in_subprocess_with_hash_randomization("_test", + ... function_args=("core",), + ... function_kwargs={'verbose': True}) # doctest: +SKIP + # Will return 0 if sys.executable supports hash randomization and tests + # pass, 1 if they fail, and False if it does not support hash + # randomization. + + """ + cwd = get_sympy_dir() + # Note, we must return False everywhere, not None, as subprocess.call will + # sometimes return None. + + # First check if the Python version supports hash randomization + # If it does not have this support, it won't recognize the -R flag + p = subprocess.Popen([command, "-RV"], stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, cwd=cwd) + p.communicate() + if p.returncode != 0: + return False + + hash_seed = os.getenv("PYTHONHASHSEED") + if not hash_seed: + os.environ["PYTHONHASHSEED"] = str(random.randrange(2**32)) + else: + if not force: + return False + + function_kwargs = function_kwargs or {} + + # Now run the command + commandstring = ("import sys; from %s import %s;sys.exit(%s(*%s, **%s))" % + (module, function, function, repr(function_args), + repr(function_kwargs))) + + try: + p = subprocess.Popen([command, "-R", "-c", commandstring], cwd=cwd) + p.communicate() + except KeyboardInterrupt: + p.wait() + finally: + # Put the environment variable back, so that it reads correctly for + # the current Python process. + if hash_seed is None: + del os.environ["PYTHONHASHSEED"] + else: + os.environ["PYTHONHASHSEED"] = hash_seed + return p.returncode + + +def run_all_tests(test_args=(), test_kwargs=None, + doctest_args=(), doctest_kwargs=None, + examples_args=(), examples_kwargs=None): + """ + Run all tests. + + Right now, this runs the regular tests (bin/test), the doctests + (bin/doctest), and the examples (examples/all.py). + + This is what ``setup.py test`` uses. + + You can pass arguments and keyword arguments to the test functions that + support them (for now, test, doctest, and the examples). See the + docstrings of those functions for a description of the available options. + + For example, to run the solvers tests with colors turned off: + + >>> from sympy.testing.runtests import run_all_tests + >>> run_all_tests(test_args=("solvers",), + ... test_kwargs={"colors:False"}) # doctest: +SKIP + + """ + tests_successful = True + + test_kwargs = test_kwargs or {} + doctest_kwargs = doctest_kwargs or {} + examples_kwargs = examples_kwargs or {'quiet': True} + + try: + # Regular tests + if not test(*test_args, **test_kwargs): + # some regular test fails, so set the tests_successful + # flag to false and continue running the doctests + tests_successful = False + + # Doctests + print() + if not doctest(*doctest_args, **doctest_kwargs): + tests_successful = False + + # Examples + print() + sys.path.append("examples") # examples/all.py + from all import run_examples # type: ignore + if not run_examples(*examples_args, **examples_kwargs): + tests_successful = False + + if tests_successful: + return + else: + # Return nonzero exit code + sys.exit(1) + except KeyboardInterrupt: + print() + print("DO *NOT* COMMIT!") + sys.exit(1) + + +def test(*paths, subprocess=True, rerun=0, **kwargs): + """ + Run tests in the specified test_*.py files. + + Tests in a particular test_*.py file are run if any of the given strings + in ``paths`` matches a part of the test file's path. If ``paths=[]``, + tests in all test_*.py files are run. + + Notes: + + - If sort=False, tests are run in random order (not default). + - Paths can be entered in native system format or in unix, + forward-slash format. + - Files that are on the blacklist can be tested by providing + their path; they are only excluded if no paths are given. + + **Explanation of test results** + + ====== =============================================================== + Output Meaning + ====== =============================================================== + . passed + F failed + X XPassed (expected to fail but passed) + f XFAILed (expected to fail and indeed failed) + s skipped + w slow + T timeout (e.g., when ``--timeout`` is used) + K KeyboardInterrupt (when running the slow tests with ``--slow``, + you can interrupt one of them without killing the test runner) + ====== =============================================================== + + + Colors have no additional meaning and are used just to facilitate + interpreting the output. + + Examples + ======== + + >>> import sympy + + Run all tests: + + >>> sympy.test() # doctest: +SKIP + + Run one file: + + >>> sympy.test("sympy/core/tests/test_basic.py") # doctest: +SKIP + >>> sympy.test("_basic") # doctest: +SKIP + + Run all tests in sympy/functions/ and some particular file: + + >>> sympy.test("sympy/core/tests/test_basic.py", + ... "sympy/functions") # doctest: +SKIP + + Run all tests in sympy/core and sympy/utilities: + + >>> sympy.test("/core", "/util") # doctest: +SKIP + + Run specific test from a file: + + >>> sympy.test("sympy/core/tests/test_basic.py", + ... kw="test_equality") # doctest: +SKIP + + Run specific test from any file: + + >>> sympy.test(kw="subs") # doctest: +SKIP + + Run the tests with verbose mode on: + + >>> sympy.test(verbose=True) # doctest: +SKIP + + Do not sort the test output: + + >>> sympy.test(sort=False) # doctest: +SKIP + + Turn on post-mortem pdb: + + >>> sympy.test(pdb=True) # doctest: +SKIP + + Turn off colors: + + >>> sympy.test(colors=False) # doctest: +SKIP + + Force colors, even when the output is not to a terminal (this is useful, + e.g., if you are piping to ``less -r`` and you still want colors) + + >>> sympy.test(force_colors=False) # doctest: +SKIP + + The traceback verboseness can be set to "short" or "no" (default is + "short") + + >>> sympy.test(tb='no') # doctest: +SKIP + + The ``split`` option can be passed to split the test run into parts. The + split currently only splits the test files, though this may change in the + future. ``split`` should be a string of the form 'a/b', which will run + part ``a`` of ``b``. For instance, to run the first half of the test suite: + + >>> sympy.test(split='1/2') # doctest: +SKIP + + The ``time_balance`` option can be passed in conjunction with ``split``. + If ``time_balance=True`` (the default for ``sympy.test``), SymPy will attempt + to split the tests such that each split takes equal time. This heuristic + for balancing is based on pre-recorded test data. + + >>> sympy.test(split='1/2', time_balance=True) # doctest: +SKIP + + You can disable running the tests in a separate subprocess using + ``subprocess=False``. This is done to support seeding hash randomization, + which is enabled by default in the Python versions where it is supported. + If subprocess=False, hash randomization is enabled/disabled according to + whether it has been enabled or not in the calling Python process. + However, even if it is enabled, the seed cannot be printed unless it is + called from a new Python process. + + Hash randomization was added in the minor Python versions 2.6.8, 2.7.3, + 3.1.5, and 3.2.3, and is enabled by default in all Python versions after + and including 3.3.0. + + If hash randomization is not supported ``subprocess=False`` is used + automatically. + + >>> sympy.test(subprocess=False) # doctest: +SKIP + + To set the hash randomization seed, set the environment variable + ``PYTHONHASHSEED`` before running the tests. This can be done from within + Python using + + >>> import os + >>> os.environ['PYTHONHASHSEED'] = '42' # doctest: +SKIP + + Or from the command line using + + $ PYTHONHASHSEED=42 ./bin/test + + If the seed is not set, a random seed will be chosen. + + Note that to reproduce the same hash values, you must use both the same seed + as well as the same architecture (32-bit vs. 64-bit). + + """ + # count up from 0, do not print 0 + print_counter = lambda i : (print("rerun %d" % (rerun-i)) + if rerun-i else None) + + if subprocess: + # loop backwards so last i is 0 + for i in range(rerun, -1, -1): + print_counter(i) + ret = run_in_subprocess_with_hash_randomization("_test", + function_args=paths, function_kwargs=kwargs) + if ret is False: + break + val = not bool(ret) + # exit on the first failure or if done + if not val or i == 0: + return val + + # rerun even if hash randomization is not supported + for i in range(rerun, -1, -1): + print_counter(i) + val = not bool(_test(*paths, **kwargs)) + if not val or i == 0: + return val + + +def _test(*paths, + verbose=False, tb="short", kw=None, pdb=False, colors=True, + force_colors=False, sort=True, seed=None, timeout=False, + fail_on_timeout=False, slow=False, enhance_asserts=False, split=None, + time_balance=True, blacklist=(), + fast_threshold=None, slow_threshold=None): + """ + Internal function that actually runs the tests. + + All keyword arguments from ``test()`` are passed to this function except for + ``subprocess``. + + Returns 0 if tests passed and 1 if they failed. See the docstring of + ``test()`` for more information. + """ + kw = kw or () + # ensure that kw is a tuple + if isinstance(kw, str): + kw = (kw,) + post_mortem = pdb + if seed is None: + seed = random.randrange(100000000) + if ON_CI and timeout is False: + timeout = 595 + fail_on_timeout = True + if ON_CI: + blacklist = list(blacklist) + ['sympy/plotting/pygletplot/tests'] + blacklist = convert_to_native_paths(blacklist) + r = PyTestReporter(verbose=verbose, tb=tb, colors=colors, + force_colors=force_colors, split=split) + # This won't strictly run the test for the corresponding file, but it is + # good enough for copying and pasting the failing test. + _paths = [] + for path in paths: + if '::' in path: + path, _kw = path.split('::', 1) + kw += (_kw,) + _paths.append(path) + paths = _paths + + t = SymPyTests(r, kw, post_mortem, seed, + fast_threshold=fast_threshold, + slow_threshold=slow_threshold) + + test_files = t.get_test_files('sympy') + + not_blacklisted = [f for f in test_files + if not any(b in f for b in blacklist)] + + if len(paths) == 0: + matched = not_blacklisted + else: + paths = convert_to_native_paths(paths) + matched = [] + for f in not_blacklisted: + basename = os.path.basename(f) + for p in paths: + if p in f or fnmatch(basename, p): + matched.append(f) + break + + density = None + if time_balance: + if slow: + density = SPLIT_DENSITY_SLOW + else: + density = SPLIT_DENSITY + + if split: + matched = split_list(matched, split, density=density) + + t._testfiles.extend(matched) + + return int(not t.test(sort=sort, timeout=timeout, slow=slow, + enhance_asserts=enhance_asserts, fail_on_timeout=fail_on_timeout)) + + +def doctest(*paths, subprocess=True, rerun=0, **kwargs): + r""" + Runs doctests in all \*.py files in the SymPy directory which match + any of the given strings in ``paths`` or all tests if paths=[]. + + Notes: + + - Paths can be entered in native system format or in unix, + forward-slash format. + - Files that are on the blacklist can be tested by providing + their path; they are only excluded if no paths are given. + + Examples + ======== + + >>> import sympy + + Run all tests: + + >>> sympy.doctest() # doctest: +SKIP + + Run one file: + + >>> sympy.doctest("sympy/core/basic.py") # doctest: +SKIP + >>> sympy.doctest("polynomial.rst") # doctest: +SKIP + + Run all tests in sympy/functions/ and some particular file: + + >>> sympy.doctest("/functions", "basic.py") # doctest: +SKIP + + Run any file having polynomial in its name, doc/src/modules/polynomial.rst, + sympy/functions/special/polynomials.py, and sympy/polys/polynomial.py: + + >>> sympy.doctest("polynomial") # doctest: +SKIP + + The ``split`` option can be passed to split the test run into parts. The + split currently only splits the test files, though this may change in the + future. ``split`` should be a string of the form 'a/b', which will run + part ``a`` of ``b``. Note that the regular doctests and the Sphinx + doctests are split independently. For instance, to run the first half of + the test suite: + + >>> sympy.doctest(split='1/2') # doctest: +SKIP + + The ``subprocess`` and ``verbose`` options are the same as with the function + ``test()`` (see the docstring of that function for more information) except + that ``verbose`` may also be set equal to ``2`` in order to print + individual doctest lines, as they are being tested. + """ + # count up from 0, do not print 0 + print_counter = lambda i : (print("rerun %d" % (rerun-i)) + if rerun-i else None) + + if subprocess: + # loop backwards so last i is 0 + for i in range(rerun, -1, -1): + print_counter(i) + ret = run_in_subprocess_with_hash_randomization("_doctest", + function_args=paths, function_kwargs=kwargs) + if ret is False: + break + val = not bool(ret) + # exit on the first failure or if done + if not val or i == 0: + return val + + # rerun even if hash randomization is not supported + for i in range(rerun, -1, -1): + print_counter(i) + val = not bool(_doctest(*paths, **kwargs)) + if not val or i == 0: + return val + + +def _get_doctest_blacklist(): + '''Get the default blacklist for the doctests''' + blacklist = [] + + blacklist.extend([ + "doc/src/modules/plotting.rst", # generates live plots + "doc/src/modules/physics/mechanics/autolev_parser.rst", + "sympy/codegen/array_utils.py", # raises deprecation warning + "sympy/core/compatibility.py", # backwards compatibility shim, importing it triggers a deprecation warning + "sympy/core/trace.py", # backwards compatibility shim, importing it triggers a deprecation warning + "sympy/galgebra.py", # no longer part of SymPy + "sympy/parsing/autolev/_antlr/autolevlexer.py", # generated code + "sympy/parsing/autolev/_antlr/autolevlistener.py", # generated code + "sympy/parsing/autolev/_antlr/autolevparser.py", # generated code + "sympy/parsing/latex/_antlr/latexlexer.py", # generated code + "sympy/parsing/latex/_antlr/latexparser.py", # generated code + "sympy/plotting/pygletplot/__init__.py", # crashes on some systems + "sympy/plotting/pygletplot/plot.py", # crashes on some systems + "sympy/printing/ccode.py", # backwards compatibility shim, importing it breaks the codegen doctests + "sympy/printing/cxxcode.py", # backwards compatibility shim, importing it breaks the codegen doctests + "sympy/printing/fcode.py", # backwards compatibility shim, importing it breaks the codegen doctests + "sympy/testing/randtest.py", # backwards compatibility shim, importing it triggers a deprecation warning + "sympy/this.py", # prints text + ]) + # autolev parser tests + num = 12 + for i in range (1, num+1): + blacklist.append("sympy/parsing/autolev/test-examples/ruletest" + str(i) + ".py") + blacklist.extend(["sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.py", + "sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.py", + "sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.py", + "sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.py"]) + + if import_module('numpy') is None: + blacklist.extend([ + "sympy/plotting/experimental_lambdify.py", + "sympy/plotting/plot_implicit.py", + "examples/advanced/autowrap_integrators.py", + "examples/advanced/autowrap_ufuncify.py", + "examples/intermediate/sample.py", + "examples/intermediate/mplot2d.py", + "examples/intermediate/mplot3d.py", + "doc/src/modules/numeric-computation.rst", + "doc/src/explanation/best-practices.md", + "doc/src/tutorials/physics/biomechanics/biomechanical-model-example.rst", + "doc/src/tutorials/physics/biomechanics/biomechanics.rst", + ]) + else: + if import_module('matplotlib') is None: + blacklist.extend([ + "examples/intermediate/mplot2d.py", + "examples/intermediate/mplot3d.py" + ]) + else: + # Use a non-windowed backend, so that the tests work on CI + import matplotlib + matplotlib.use('Agg') + + if ON_CI or import_module('pyglet') is None: + blacklist.extend(["sympy/plotting/pygletplot"]) + + if import_module('aesara') is None: + blacklist.extend([ + "sympy/printing/aesaracode.py", + "doc/src/modules/numeric-computation.rst", + ]) + + if import_module('cupy') is None: + blacklist.extend([ + "doc/src/modules/numeric-computation.rst", + ]) + + if import_module('jax') is None: + blacklist.extend([ + "doc/src/modules/numeric-computation.rst", + ]) + + if import_module('antlr4') is None: + blacklist.extend([ + "sympy/parsing/autolev/__init__.py", + "sympy/parsing/latex/_parse_latex_antlr.py", + ]) + + if import_module('lfortran') is None: + #throws ImportError when lfortran not installed + blacklist.extend([ + "sympy/parsing/sym_expr.py", + ]) + + if import_module("scipy") is None: + # throws ModuleNotFoundError when scipy not installed + blacklist.extend([ + "doc/src/guides/solving/solve-numerically.md", + "doc/src/guides/solving/solve-ode.md", + ]) + + if import_module("numpy") is None: + # throws ModuleNotFoundError when numpy not installed + blacklist.extend([ + "doc/src/guides/solving/solve-ode.md", + "doc/src/guides/solving/solve-numerically.md", + ]) + + # disabled because of doctest failures in asmeurer's bot + blacklist.extend([ + "sympy/utilities/autowrap.py", + "examples/advanced/autowrap_integrators.py", + "examples/advanced/autowrap_ufuncify.py" + ]) + + blacklist.extend([ + "sympy/conftest.py", # Depends on pytest + ]) + + # These are deprecated stubs to be removed: + blacklist.extend([ + "sympy/utilities/tmpfiles.py", + "sympy/utilities/pytest.py", + "sympy/utilities/runtests.py", + "sympy/utilities/quality_unicode.py", + "sympy/utilities/randtest.py", + ]) + + blacklist = convert_to_native_paths(blacklist) + return blacklist + + +def _doctest(*paths, **kwargs): + """ + Internal function that actually runs the doctests. + + All keyword arguments from ``doctest()`` are passed to this function + except for ``subprocess``. + + Returns 0 if tests passed and 1 if they failed. See the docstrings of + ``doctest()`` and ``test()`` for more information. + """ + from sympy.printing.pretty.pretty import pprint_use_unicode + from sympy.printing.pretty import stringpict + + normal = kwargs.get("normal", False) + verbose = kwargs.get("verbose", False) + colors = kwargs.get("colors", True) + force_colors = kwargs.get("force_colors", False) + blacklist = kwargs.get("blacklist", []) + split = kwargs.get('split', None) + + blacklist.extend(_get_doctest_blacklist()) + + # Use a non-windowed backend, so that the tests work on CI + if import_module('matplotlib') is not None: + import matplotlib + matplotlib.use('Agg') + + # Disable warnings for external modules + import sympy.external + sympy.external.importtools.WARN_OLD_VERSION = False + sympy.external.importtools.WARN_NOT_INSTALLED = False + + # Disable showing up of plots + from sympy.plotting.plot import unset_show + unset_show() + + r = PyTestReporter(verbose, split=split, colors=colors,\ + force_colors=force_colors) + t = SymPyDocTests(r, normal) + + test_files = t.get_test_files('sympy') + test_files.extend(t.get_test_files('examples', init_only=False)) + + not_blacklisted = [f for f in test_files + if not any(b in f for b in blacklist)] + if len(paths) == 0: + matched = not_blacklisted + else: + # take only what was requested...but not blacklisted items + # and allow for partial match anywhere or fnmatch of name + paths = convert_to_native_paths(paths) + matched = [] + for f in not_blacklisted: + basename = os.path.basename(f) + for p in paths: + if p in f or fnmatch(basename, p): + matched.append(f) + break + + matched.sort() + + if split: + matched = split_list(matched, split) + + t._testfiles.extend(matched) + + # run the tests and record the result for this *py portion of the tests + if t._testfiles: + failed = not t.test() + else: + failed = False + + # N.B. + # -------------------------------------------------------------------- + # Here we test *.rst and *.md files at or below doc/src. Code from these + # must be self supporting in terms of imports since there is no importing + # of necessary modules by doctest.testfile. If you try to pass *.py files + # through this they might fail because they will lack the needed imports + # and smarter parsing that can be done with source code. + # + test_files_rst = t.get_test_files('doc/src', '*.rst', init_only=False) + test_files_md = t.get_test_files('doc/src', '*.md', init_only=False) + test_files = test_files_rst + test_files_md + test_files.sort() + + not_blacklisted = [f for f in test_files + if not any(b in f for b in blacklist)] + + if len(paths) == 0: + matched = not_blacklisted + else: + # Take only what was requested as long as it's not on the blacklist. + # Paths were already made native in *py tests so don't repeat here. + # There's no chance of having a *py file slip through since we + # only have *rst files in test_files. + matched = [] + for f in not_blacklisted: + basename = os.path.basename(f) + for p in paths: + if p in f or fnmatch(basename, p): + matched.append(f) + break + + if split: + matched = split_list(matched, split) + + first_report = True + for rst_file in matched: + if not os.path.isfile(rst_file): + continue + old_displayhook = sys.displayhook + try: + use_unicode_prev, wrap_line_prev = setup_pprint() + out = sympytestfile( + rst_file, module_relative=False, encoding='utf-8', + optionflags=pdoctest.ELLIPSIS | pdoctest.NORMALIZE_WHITESPACE | + pdoctest.IGNORE_EXCEPTION_DETAIL) + finally: + # make sure we return to the original displayhook in case some + # doctest has changed that + sys.displayhook = old_displayhook + # The NO_GLOBAL flag overrides the no_global flag to init_printing + # if True + import sympy.interactive.printing as interactive_printing + interactive_printing.NO_GLOBAL = False + pprint_use_unicode(use_unicode_prev) + stringpict._GLOBAL_WRAP_LINE = wrap_line_prev + + rstfailed, tested = out + if tested: + failed = rstfailed or failed + if first_report: + first_report = False + msg = 'rst/md doctests start' + if not t._testfiles: + r.start(msg=msg) + else: + r.write_center(msg) + print() + # use as the id, everything past the first 'sympy' + file_id = rst_file[rst_file.find('sympy') + len('sympy') + 1:] + print(file_id, end=" ") + # get at least the name out so it is know who is being tested + wid = r.terminal_width - len(file_id) - 1 # update width + test_file = '[%s]' % (tested) + report = '[%s]' % (rstfailed or 'OK') + print(''.join( + [test_file, ' '*(wid - len(test_file) - len(report)), report]) + ) + + # the doctests for *py will have printed this message already if there was + # a failure, so now only print it if there was intervening reporting by + # testing the *rst as evidenced by first_report no longer being True. + if not first_report and failed: + print() + print("DO *NOT* COMMIT!") + + return int(failed) + +sp = re.compile(r'([0-9]+)/([1-9][0-9]*)') + +def split_list(l, split, density=None): + """ + Splits a list into part a of b + + split should be a string of the form 'a/b'. For instance, '1/3' would give + the split one of three. + + If the length of the list is not divisible by the number of splits, the + last split will have more items. + + `density` may be specified as a list. If specified, + tests will be balanced so that each split has as equal-as-possible + amount of mass according to `density`. + + >>> from sympy.testing.runtests import split_list + >>> a = list(range(10)) + >>> split_list(a, '1/3') + [0, 1, 2] + >>> split_list(a, '2/3') + [3, 4, 5] + >>> split_list(a, '3/3') + [6, 7, 8, 9] + """ + m = sp.match(split) + if not m: + raise ValueError("split must be a string of the form a/b where a and b are ints") + i, t = map(int, m.groups()) + + if not density: + return l[(i - 1)*len(l)//t : i*len(l)//t] + + # normalize density + tot = sum(density) + density = [x / tot for x in density] + + def density_inv(x): + """Interpolate the inverse to the cumulative + distribution function given by density""" + if x <= 0: + return 0 + if x >= sum(density): + return 1 + + # find the first time the cumulative sum surpasses x + # and linearly interpolate + cumm = 0 + for i, d in enumerate(density): + cumm += d + if cumm >= x: + break + frac = (d - (cumm - x)) / d + return (i + frac) / len(density) + + lower_frac = density_inv((i - 1) / t) + higher_frac = density_inv(i / t) + return l[int(lower_frac*len(l)) : int(higher_frac*len(l))] + +from collections import namedtuple +SymPyTestResults = namedtuple('SymPyTestResults', 'failed attempted') + +def sympytestfile(filename, module_relative=True, name=None, package=None, + globs=None, verbose=None, report=True, optionflags=0, + extraglobs=None, raise_on_error=False, + parser=pdoctest.DocTestParser(), encoding=None): + + """ + Test examples in the given file. Return (#failures, #tests). + + Optional keyword arg ``module_relative`` specifies how filenames + should be interpreted: + + - If ``module_relative`` is True (the default), then ``filename`` + specifies a module-relative path. By default, this path is + relative to the calling module's directory; but if the + ``package`` argument is specified, then it is relative to that + package. To ensure os-independence, ``filename`` should use + "/" characters to separate path segments, and should not + be an absolute path (i.e., it may not begin with "/"). + + - If ``module_relative`` is False, then ``filename`` specifies an + os-specific path. The path may be absolute or relative (to + the current working directory). + + Optional keyword arg ``name`` gives the name of the test; by default + use the file's basename. + + Optional keyword argument ``package`` is a Python package or the + name of a Python package whose directory should be used as the + base directory for a module relative filename. If no package is + specified, then the calling module's directory is used as the base + directory for module relative filenames. It is an error to + specify ``package`` if ``module_relative`` is False. + + Optional keyword arg ``globs`` gives a dict to be used as the globals + when executing examples; by default, use {}. A copy of this dict + is actually used for each docstring, so that each docstring's + examples start with a clean slate. + + Optional keyword arg ``extraglobs`` gives a dictionary that should be + merged into the globals that are used to execute examples. By + default, no extra globals are used. + + Optional keyword arg ``verbose`` prints lots of stuff if true, prints + only failures if false; by default, it's true iff "-v" is in sys.argv. + + Optional keyword arg ``report`` prints a summary at the end when true, + else prints nothing at the end. In verbose mode, the summary is + detailed, else very brief (in fact, empty if all tests passed). + + Optional keyword arg ``optionflags`` or's together module constants, + and defaults to 0. Possible values (see the docs for details): + + - DONT_ACCEPT_TRUE_FOR_1 + - DONT_ACCEPT_BLANKLINE + - NORMALIZE_WHITESPACE + - ELLIPSIS + - SKIP + - IGNORE_EXCEPTION_DETAIL + - REPORT_UDIFF + - REPORT_CDIFF + - REPORT_NDIFF + - REPORT_ONLY_FIRST_FAILURE + + Optional keyword arg ``raise_on_error`` raises an exception on the + first unexpected exception or failure. This allows failures to be + post-mortem debugged. + + Optional keyword arg ``parser`` specifies a DocTestParser (or + subclass) that should be used to extract tests from the files. + + Optional keyword arg ``encoding`` specifies an encoding that should + be used to convert the file to unicode. + + Advanced tomfoolery: testmod runs methods of a local instance of + class doctest.Tester, then merges the results into (or creates) + global Tester instance doctest.master. Methods of doctest.master + can be called directly too, if you want to do something unusual. + Passing report=0 to testmod is especially useful then, to delay + displaying a summary. Invoke doctest.master.summarize(verbose) + when you're done fiddling. + """ + if package and not module_relative: + raise ValueError("Package may only be specified for module-" + "relative paths.") + + # Relativize the path + text, filename = pdoctest._load_testfile( + filename, package, module_relative, encoding) + + # If no name was given, then use the file's name. + if name is None: + name = os.path.basename(filename) + + # Assemble the globals. + if globs is None: + globs = {} + else: + globs = globs.copy() + if extraglobs is not None: + globs.update(extraglobs) + if '__name__' not in globs: + globs['__name__'] = '__main__' + + if raise_on_error: + runner = pdoctest.DebugRunner(verbose=verbose, optionflags=optionflags) + else: + runner = SymPyDocTestRunner(verbose=verbose, optionflags=optionflags) + runner._checker = SymPyOutputChecker() + + # Read the file, convert it to a test, and run it. + test = parser.get_doctest(text, globs, name, filename, 0) + runner.run(test) + + if report: + runner.summarize() + + if pdoctest.master is None: + pdoctest.master = runner + else: + pdoctest.master.merge(runner) + + return SymPyTestResults(runner.failures, runner.tries) + + +class SymPyTests: + + def __init__(self, reporter, kw="", post_mortem=False, + seed=None, fast_threshold=None, slow_threshold=None): + self._post_mortem = post_mortem + self._kw = kw + self._count = 0 + self._root_dir = get_sympy_dir() + self._reporter = reporter + self._reporter.root_dir(self._root_dir) + self._testfiles = [] + self._seed = seed if seed is not None else random.random() + + # Defaults in seconds, from human / UX design limits + # http://www.nngroup.com/articles/response-times-3-important-limits/ + # + # These defaults are *NOT* set in stone as we are measuring different + # things, so others feel free to come up with a better yardstick :) + if fast_threshold: + self._fast_threshold = float(fast_threshold) + else: + self._fast_threshold = 8 + if slow_threshold: + self._slow_threshold = float(slow_threshold) + else: + self._slow_threshold = 10 + + def test(self, sort=False, timeout=False, slow=False, + enhance_asserts=False, fail_on_timeout=False): + """ + Runs the tests returning True if all tests pass, otherwise False. + + If sort=False run tests in random order. + """ + if sort: + self._testfiles.sort() + elif slow: + pass + else: + random.seed(self._seed) + random.shuffle(self._testfiles) + self._reporter.start(self._seed) + for f in self._testfiles: + try: + self.test_file(f, sort, timeout, slow, + enhance_asserts, fail_on_timeout) + except KeyboardInterrupt: + print(" interrupted by user") + self._reporter.finish() + raise + return self._reporter.finish() + + def _enhance_asserts(self, source): + from ast import (NodeTransformer, Compare, Name, Store, Load, Tuple, + Assign, BinOp, Str, Mod, Assert, parse, fix_missing_locations) + + ops = {"Eq": '==', "NotEq": '!=', "Lt": '<', "LtE": '<=', + "Gt": '>', "GtE": '>=', "Is": 'is', "IsNot": 'is not', + "In": 'in', "NotIn": 'not in'} + + class Transform(NodeTransformer): + def visit_Assert(self, stmt): + if isinstance(stmt.test, Compare): + compare = stmt.test + values = [compare.left] + compare.comparators + names = [ "_%s" % i for i, _ in enumerate(values) ] + names_store = [ Name(n, Store()) for n in names ] + names_load = [ Name(n, Load()) for n in names ] + target = Tuple(names_store, Store()) + value = Tuple(values, Load()) + assign = Assign([target], value) + new_compare = Compare(names_load[0], compare.ops, names_load[1:]) + msg_format = "\n%s " + "\n%s ".join([ ops[op.__class__.__name__] for op in compare.ops ]) + "\n%s" + msg = BinOp(Str(msg_format), Mod(), Tuple(names_load, Load())) + test = Assert(new_compare, msg, lineno=stmt.lineno, col_offset=stmt.col_offset) + return [assign, test] + else: + return stmt + + tree = parse(source) + new_tree = Transform().visit(tree) + return fix_missing_locations(new_tree) + + def test_file(self, filename, sort=True, timeout=False, slow=False, + enhance_asserts=False, fail_on_timeout=False): + reporter = self._reporter + funcs = [] + try: + gl = {'__file__': filename} + try: + open_file = lambda: open(filename, encoding="utf8") + + with open_file() as f: + source = f.read() + if self._kw: + for l in source.splitlines(): + if l.lstrip().startswith('def '): + if any(l.lower().find(k.lower()) != -1 for k in self._kw): + break + else: + return + + if enhance_asserts: + try: + source = self._enhance_asserts(source) + except ImportError: + pass + + code = compile(source, filename, "exec", flags=0, dont_inherit=True) + exec(code, gl) + except (SystemExit, KeyboardInterrupt): + raise + except ImportError: + reporter.import_error(filename, sys.exc_info()) + return + except Exception: + reporter.test_exception(sys.exc_info()) + + clear_cache() + self._count += 1 + random.seed(self._seed) + disabled = gl.get("disabled", False) + if not disabled: + # we need to filter only those functions that begin with 'test_' + # We have to be careful about decorated functions. As long as + # the decorator uses functools.wraps, we can detect it. + funcs = [] + for f in gl: + if (f.startswith("test_") and (inspect.isfunction(gl[f]) + or inspect.ismethod(gl[f]))): + func = gl[f] + # Handle multiple decorators + while hasattr(func, '__wrapped__'): + func = func.__wrapped__ + + if inspect.getsourcefile(func) == filename: + funcs.append(gl[f]) + if slow: + funcs = [f for f in funcs if getattr(f, '_slow', False)] + # Sorting of XFAILed functions isn't fixed yet :-( + funcs.sort(key=lambda x: inspect.getsourcelines(x)[1]) + i = 0 + while i < len(funcs): + if inspect.isgeneratorfunction(funcs[i]): + # some tests can be generators, that return the actual + # test functions. We unpack it below: + f = funcs.pop(i) + for fg in f(): + func = fg[0] + args = fg[1:] + fgw = lambda: func(*args) + funcs.insert(i, fgw) + i += 1 + else: + i += 1 + # drop functions that are not selected with the keyword expression: + funcs = [x for x in funcs if self.matches(x)] + + if not funcs: + return + except Exception: + reporter.entering_filename(filename, len(funcs)) + raise + + reporter.entering_filename(filename, len(funcs)) + if not sort: + random.shuffle(funcs) + + for f in funcs: + start = time.time() + reporter.entering_test(f) + try: + if getattr(f, '_slow', False) and not slow: + raise Skipped("Slow") + with raise_on_deprecated(): + if timeout: + self._timeout(f, timeout, fail_on_timeout) + else: + random.seed(self._seed) + f() + except KeyboardInterrupt: + if getattr(f, '_slow', False): + reporter.test_skip("KeyboardInterrupt") + else: + raise + except Exception: + if timeout: + signal.alarm(0) # Disable the alarm. It could not be handled before. + t, v, tr = sys.exc_info() + if t is AssertionError: + reporter.test_fail((t, v, tr)) + if self._post_mortem: + pdb.post_mortem(tr) + elif t.__name__ == "Skipped": + reporter.test_skip(v) + elif t.__name__ == "XFail": + reporter.test_xfail() + elif t.__name__ == "XPass": + reporter.test_xpass(v) + else: + reporter.test_exception((t, v, tr)) + if self._post_mortem: + pdb.post_mortem(tr) + else: + reporter.test_pass() + taken = time.time() - start + if taken > self._slow_threshold: + filename = os.path.relpath(filename, reporter._root_dir) + reporter.slow_test_functions.append( + (filename + "::" + f.__name__, taken)) + if getattr(f, '_slow', False) and slow: + if taken < self._fast_threshold: + filename = os.path.relpath(filename, reporter._root_dir) + reporter.fast_test_functions.append( + (filename + "::" + f.__name__, taken)) + reporter.leaving_filename() + + def _timeout(self, function, timeout, fail_on_timeout): + def callback(x, y): + signal.alarm(0) + if fail_on_timeout: + raise TimeOutError("Timed out after %d seconds" % timeout) + else: + raise Skipped("Timeout") + signal.signal(signal.SIGALRM, callback) + signal.alarm(timeout) # Set an alarm with a given timeout + function() + signal.alarm(0) # Disable the alarm + + def matches(self, x): + """ + Does the keyword expression self._kw match "x"? Returns True/False. + + Always returns True if self._kw is "". + """ + if not self._kw: + return True + for kw in self._kw: + if x.__name__.lower().find(kw.lower()) != -1: + return True + return False + + def get_test_files(self, dir, pat='test_*.py'): + """ + Returns the list of test_*.py (default) files at or below directory + ``dir`` relative to the SymPy home directory. + """ + dir = os.path.join(self._root_dir, convert_to_native_paths([dir])[0]) + + g = [] + for path, folders, files in os.walk(dir): + g.extend([os.path.join(path, f) for f in files if fnmatch(f, pat)]) + + return sorted([os.path.normcase(gi) for gi in g]) + + +class SymPyDocTests: + + def __init__(self, reporter, normal): + self._count = 0 + self._root_dir = get_sympy_dir() + self._reporter = reporter + self._reporter.root_dir(self._root_dir) + self._normal = normal + + self._testfiles = [] + + def test(self): + """ + Runs the tests and returns True if all tests pass, otherwise False. + """ + self._reporter.start() + for f in self._testfiles: + try: + self.test_file(f) + except KeyboardInterrupt: + print(" interrupted by user") + self._reporter.finish() + raise + return self._reporter.finish() + + def test_file(self, filename): + clear_cache() + + from io import StringIO + import sympy.interactive.printing as interactive_printing + from sympy.printing.pretty.pretty import pprint_use_unicode + from sympy.printing.pretty import stringpict + + rel_name = filename[len(self._root_dir) + 1:] + dirname, file = os.path.split(filename) + module = rel_name.replace(os.sep, '.')[:-3] + + if rel_name.startswith("examples"): + # Examples files do not have __init__.py files, + # So we have to temporarily extend sys.path to import them + sys.path.insert(0, dirname) + module = file[:-3] # remove ".py" + try: + module = pdoctest._normalize_module(module) + tests = SymPyDocTestFinder().find(module) + except (SystemExit, KeyboardInterrupt): + raise + except ImportError: + self._reporter.import_error(filename, sys.exc_info()) + return + finally: + if rel_name.startswith("examples"): + del sys.path[0] + + tests = [test for test in tests if len(test.examples) > 0] + # By default tests are sorted by alphabetical order by function name. + # We sort by line number so one can edit the file sequentially from + # bottom to top. However, if there are decorated functions, their line + # numbers will be too large and for now one must just search for these + # by text and function name. + tests.sort(key=lambda x: -x.lineno) + + if not tests: + return + self._reporter.entering_filename(filename, len(tests)) + for test in tests: + assert len(test.examples) != 0 + + if self._reporter._verbose: + self._reporter.write("\n{} ".format(test.name)) + + # check if there are external dependencies which need to be met + if '_doctest_depends_on' in test.globs: + try: + self._check_dependencies(**test.globs['_doctest_depends_on']) + except DependencyError as e: + self._reporter.test_skip(v=str(e)) + continue + + runner = SymPyDocTestRunner(verbose=self._reporter._verbose==2, + optionflags=pdoctest.ELLIPSIS | + pdoctest.NORMALIZE_WHITESPACE | + pdoctest.IGNORE_EXCEPTION_DETAIL) + runner._checker = SymPyOutputChecker() + old = sys.stdout + new = old if self._reporter._verbose==2 else StringIO() + sys.stdout = new + # If the testing is normal, the doctests get importing magic to + # provide the global namespace. If not normal (the default) then + # then must run on their own; all imports must be explicit within + # a function's docstring. Once imported that import will be + # available to the rest of the tests in a given function's + # docstring (unless clear_globs=True below). + if not self._normal: + test.globs = {} + # if this is uncommented then all the test would get is what + # comes by default with a "from sympy import *" + #exec('from sympy import *') in test.globs + old_displayhook = sys.displayhook + use_unicode_prev, wrap_line_prev = setup_pprint() + + try: + f, t = runner.run(test, + out=new.write, clear_globs=False) + except KeyboardInterrupt: + raise + finally: + sys.stdout = old + if f > 0: + self._reporter.doctest_fail(test.name, new.getvalue()) + else: + self._reporter.test_pass() + sys.displayhook = old_displayhook + interactive_printing.NO_GLOBAL = False + pprint_use_unicode(use_unicode_prev) + stringpict._GLOBAL_WRAP_LINE = wrap_line_prev + + self._reporter.leaving_filename() + + def get_test_files(self, dir, pat='*.py', init_only=True): + r""" + Returns the list of \*.py files (default) from which docstrings + will be tested which are at or below directory ``dir``. By default, + only those that have an __init__.py in their parent directory + and do not start with ``test_`` will be included. + """ + def importable(x): + """ + Checks if given pathname x is an importable module by checking for + __init__.py file. + + Returns True/False. + + Currently we only test if the __init__.py file exists in the + directory with the file "x" (in theory we should also test all the + parent dirs). + """ + init_py = os.path.join(os.path.dirname(x), "__init__.py") + return os.path.exists(init_py) + + dir = os.path.join(self._root_dir, convert_to_native_paths([dir])[0]) + + g = [] + for path, folders, files in os.walk(dir): + g.extend([os.path.join(path, f) for f in files + if not f.startswith('test_') and fnmatch(f, pat)]) + if init_only: + # skip files that are not importable (i.e. missing __init__.py) + g = [x for x in g if importable(x)] + + return [os.path.normcase(gi) for gi in g] + + def _check_dependencies(self, + executables=(), + modules=(), + disable_viewers=(), + python_version=(3, 5), + ground_types=None): + """ + Checks if the dependencies for the test are installed. + + Raises ``DependencyError`` it at least one dependency is not installed. + """ + + for executable in executables: + if not shutil.which(executable): + raise DependencyError("Could not find %s" % executable) + + for module in modules: + if module == 'matplotlib': + matplotlib = import_module( + 'matplotlib', + import_kwargs={'fromlist': + ['pyplot', 'cm', 'collections']}, + min_module_version='1.0.0', catch=(RuntimeError,)) + if matplotlib is None: + raise DependencyError("Could not import matplotlib") + else: + if not import_module(module): + raise DependencyError("Could not import %s" % module) + + if disable_viewers: + tempdir = tempfile.mkdtemp() + os.environ['PATH'] = '%s:%s' % (tempdir, os.environ['PATH']) + + vw = ('#!/usr/bin/env python3\n' + 'import sys\n' + 'if len(sys.argv) <= 1:\n' + ' exit("wrong number of args")\n') + + for viewer in disable_viewers: + Path(os.path.join(tempdir, viewer)).write_text(vw) + + # make the file executable + os.chmod(os.path.join(tempdir, viewer), + stat.S_IREAD | stat.S_IWRITE | stat.S_IXUSR) + + if python_version: + if sys.version_info < python_version: + raise DependencyError("Requires Python >= " + '.'.join(map(str, python_version))) + + if ground_types is not None: + if GROUND_TYPES not in ground_types: + raise DependencyError("Requires ground_types in " + str(ground_types)) + + if 'pyglet' in modules: + # monkey-patch pyglet s.t. it does not open a window during + # doctesting + import pyglet + class DummyWindow: + def __init__(self, *args, **kwargs): + self.has_exit = True + self.width = 600 + self.height = 400 + + def set_vsync(self, x): + pass + + def switch_to(self): + pass + + def push_handlers(self, x): + pass + + def close(self): + pass + + pyglet.window.Window = DummyWindow + + +class SymPyDocTestFinder(DocTestFinder): + """ + A class used to extract the DocTests that are relevant to a given + object, from its docstring and the docstrings of its contained + objects. Doctests can currently be extracted from the following + object types: modules, functions, classes, methods, staticmethods, + classmethods, and properties. + + Modified from doctest's version to look harder for code that + appears comes from a different module. For example, the @vectorize + decorator makes it look like functions come from multidimensional.py + even though their code exists elsewhere. + """ + + def _find(self, tests, obj, name, module, source_lines, globs, seen): + """ + Find tests for the given object and any contained objects, and + add them to ``tests``. + """ + if self._verbose: + print('Finding tests in %s' % name) + + # If we've already processed this object, then ignore it. + if id(obj) in seen: + return + seen[id(obj)] = 1 + + # Make sure we don't run doctests for classes outside of sympy, such + # as in numpy or scipy. + if inspect.isclass(obj): + if obj.__module__.split('.')[0] != 'sympy': + return + + # Find a test for this object, and add it to the list of tests. + test = self._get_test(obj, name, module, globs, source_lines) + if test is not None: + tests.append(test) + + if not self._recurse: + return + + # Look for tests in a module's contained objects. + if inspect.ismodule(obj): + for rawname, val in obj.__dict__.items(): + # Recurse to functions & classes. + if inspect.isfunction(val) or inspect.isclass(val): + # Make sure we don't run doctests functions or classes + # from different modules + if val.__module__ != module.__name__: + continue + + assert self._from_module(module, val), \ + "%s is not in module %s (rawname %s)" % (val, module, rawname) + + try: + valname = '%s.%s' % (name, rawname) + self._find(tests, val, valname, module, + source_lines, globs, seen) + except KeyboardInterrupt: + raise + + # Look for tests in a module's __test__ dictionary. + for valname, val in getattr(obj, '__test__', {}).items(): + if not isinstance(valname, str): + raise ValueError("SymPyDocTestFinder.find: __test__ keys " + "must be strings: %r" % + (type(valname),)) + if not (inspect.isfunction(val) or inspect.isclass(val) or + inspect.ismethod(val) or inspect.ismodule(val) or + isinstance(val, str)): + raise ValueError("SymPyDocTestFinder.find: __test__ values " + "must be strings, functions, methods, " + "classes, or modules: %r" % + (type(val),)) + valname = '%s.__test__.%s' % (name, valname) + self._find(tests, val, valname, module, source_lines, + globs, seen) + + + # Look for tests in a class's contained objects. + if inspect.isclass(obj): + for valname, val in obj.__dict__.items(): + # Special handling for staticmethod/classmethod. + if isinstance(val, staticmethod): + val = getattr(obj, valname) + if isinstance(val, classmethod): + val = getattr(obj, valname).__func__ + + + # Recurse to methods, properties, and nested classes. + if ((inspect.isfunction(unwrap(val)) or + inspect.isclass(val) or + isinstance(val, property)) and + self._from_module(module, val)): + # Make sure we don't run doctests functions or classes + # from different modules + if isinstance(val, property): + if hasattr(val.fget, '__module__'): + if val.fget.__module__ != module.__name__: + continue + else: + if val.__module__ != module.__name__: + continue + + assert self._from_module(module, val), \ + "%s is not in module %s (valname %s)" % ( + val, module, valname) + + valname = '%s.%s' % (name, valname) + self._find(tests, val, valname, module, source_lines, + globs, seen) + + def _get_test(self, obj, name, module, globs, source_lines): + """ + Return a DocTest for the given object, if it defines a docstring; + otherwise, return None. + """ + + lineno = None + + # Extract the object's docstring. If it does not have one, + # then return None (no test for this object). + if isinstance(obj, str): + # obj is a string in the case for objects in the polys package. + # Note that source_lines is a binary string (compiled polys + # modules), which can't be handled by _find_lineno so determine + # the line number here. + + docstring = obj + + matches = re.findall(r"line \d+", name) + assert len(matches) == 1, \ + "string '%s' does not contain lineno " % name + + # NOTE: this is not the exact linenumber but its better than no + # lineno ;) + lineno = int(matches[0][5:]) + + else: + docstring = getattr(obj, '__doc__', '') + if docstring is None: + docstring = '' + if not isinstance(docstring, str): + docstring = str(docstring) + + # Don't bother if the docstring is empty. + if self._exclude_empty and not docstring: + return None + + # check that properties have a docstring because _find_lineno + # assumes it + if isinstance(obj, property): + if obj.fget.__doc__ is None: + return None + + # Find the docstring's location in the file. + if lineno is None: + obj = unwrap(obj) + # handling of properties is not implemented in _find_lineno so do + # it here + if hasattr(obj, 'func_closure') and obj.func_closure is not None: + tobj = obj.func_closure[0].cell_contents + elif isinstance(obj, property): + tobj = obj.fget + else: + tobj = obj + lineno = self._find_lineno(tobj, source_lines) + + if lineno is None: + return None + + # Return a DocTest for this object. + if module is None: + filename = None + else: + filename = getattr(module, '__file__', module.__name__) + if filename[-4:] in (".pyc", ".pyo"): + filename = filename[:-1] + + globs['_doctest_depends_on'] = getattr(obj, '_doctest_depends_on', {}) + + return self._parser.get_doctest(docstring, globs, name, + filename, lineno) + + +class SymPyDocTestRunner(DocTestRunner): + """ + A class used to run DocTest test cases, and accumulate statistics. + The ``run`` method is used to process a single DocTest case. It + returns a tuple ``(f, t)``, where ``t`` is the number of test cases + tried, and ``f`` is the number of test cases that failed. + + Modified from the doctest version to not reset the sys.displayhook (see + issue 5140). + + See the docstring of the original DocTestRunner for more information. + """ + + def run(self, test, compileflags=None, out=None, clear_globs=True): + """ + Run the examples in ``test``, and display the results using the + writer function ``out``. + + The examples are run in the namespace ``test.globs``. If + ``clear_globs`` is true (the default), then this namespace will + be cleared after the test runs, to help with garbage + collection. If you would like to examine the namespace after + the test completes, then use ``clear_globs=False``. + + ``compileflags`` gives the set of flags that should be used by + the Python compiler when running the examples. If not + specified, then it will default to the set of future-import + flags that apply to ``globs``. + + The output of each example is checked using + ``SymPyDocTestRunner.check_output``, and the results are + formatted by the ``SymPyDocTestRunner.report_*`` methods. + """ + self.test = test + + # Remove ``` from the end of example, which may appear in Markdown + # files + for example in test.examples: + example.want = example.want.replace('```\n', '') + example.exc_msg = example.exc_msg and example.exc_msg.replace('```\n', '') + + + if compileflags is None: + compileflags = pdoctest._extract_future_flags(test.globs) + + save_stdout = sys.stdout + if out is None: + out = save_stdout.write + sys.stdout = self._fakeout + + # Patch pdb.set_trace to restore sys.stdout during interactive + # debugging (so it's not still redirected to self._fakeout). + # Note that the interactive output will go to *our* + # save_stdout, even if that's not the real sys.stdout; this + # allows us to write test cases for the set_trace behavior. + save_set_trace = pdb.set_trace + self.debugger = pdoctest._OutputRedirectingPdb(save_stdout) + self.debugger.reset() + pdb.set_trace = self.debugger.set_trace + + # Patch linecache.getlines, so we can see the example's source + # when we're inside the debugger. + self.save_linecache_getlines = pdoctest.linecache.getlines + linecache.getlines = self.__patched_linecache_getlines + + # Fail for deprecation warnings + with raise_on_deprecated(): + try: + return self.__run(test, compileflags, out) + finally: + sys.stdout = save_stdout + pdb.set_trace = save_set_trace + linecache.getlines = self.save_linecache_getlines + if clear_globs: + test.globs.clear() + + +# We have to override the name mangled methods. +monkeypatched_methods = [ + 'patched_linecache_getlines', + 'run', + 'record_outcome' +] +for method in monkeypatched_methods: + oldname = '_DocTestRunner__' + method + newname = '_SymPyDocTestRunner__' + method + setattr(SymPyDocTestRunner, newname, getattr(DocTestRunner, oldname)) + + +class SymPyOutputChecker(pdoctest.OutputChecker): + """ + Compared to the OutputChecker from the stdlib our OutputChecker class + supports numerical comparison of floats occurring in the output of the + doctest examples + """ + + def __init__(self): + # NOTE OutputChecker is an old-style class with no __init__ method, + # so we can't call the base class version of __init__ here + + got_floats = r'(\d+\.\d*|\.\d+)' + + # floats in the 'want' string may contain ellipses + want_floats = got_floats + r'(\.{3})?' + + front_sep = r'\s|\+|\-|\*|,' + back_sep = front_sep + r'|j|e' + + fbeg = r'^%s(?=%s|$)' % (got_floats, back_sep) + fmidend = r'(?<=%s)%s(?=%s|$)' % (front_sep, got_floats, back_sep) + self.num_got_rgx = re.compile(r'(%s|%s)' %(fbeg, fmidend)) + + fbeg = r'^%s(?=%s|$)' % (want_floats, back_sep) + fmidend = r'(?<=%s)%s(?=%s|$)' % (front_sep, want_floats, back_sep) + self.num_want_rgx = re.compile(r'(%s|%s)' %(fbeg, fmidend)) + + def check_output(self, want, got, optionflags): + """ + Return True iff the actual output from an example (`got`) + matches the expected output (`want`). These strings are + always considered to match if they are identical; but + depending on what option flags the test runner is using, + several non-exact match types are also possible. See the + documentation for `TestRunner` for more information about + option flags. + """ + # Handle the common case first, for efficiency: + # if they're string-identical, always return true. + if got == want: + return True + + # TODO parse integers as well ? + # Parse floats and compare them. If some of the parsed floats contain + # ellipses, skip the comparison. + matches = self.num_got_rgx.finditer(got) + numbers_got = [match.group(1) for match in matches] # list of strs + matches = self.num_want_rgx.finditer(want) + numbers_want = [match.group(1) for match in matches] # list of strs + if len(numbers_got) != len(numbers_want): + return False + + if len(numbers_got) > 0: + nw_ = [] + for ng, nw in zip(numbers_got, numbers_want): + if '...' in nw: + nw_.append(ng) + continue + else: + nw_.append(nw) + + if abs(float(ng)-float(nw)) > 1e-5: + return False + + got = self.num_got_rgx.sub(r'%s', got) + got = got % tuple(nw_) + + # can be used as a special sequence to signify a + # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used. + if not (optionflags & pdoctest.DONT_ACCEPT_BLANKLINE): + # Replace in want with a blank line. + want = re.sub(r'(?m)^%s\s*?$' % re.escape(pdoctest.BLANKLINE_MARKER), + '', want) + # If a line in got contains only spaces, then remove the + # spaces. + got = re.sub(r'(?m)^\s*?$', '', got) + if got == want: + return True + + # This flag causes doctest to ignore any differences in the + # contents of whitespace strings. Note that this can be used + # in conjunction with the ELLIPSIS flag. + if optionflags & pdoctest.NORMALIZE_WHITESPACE: + got = ' '.join(got.split()) + want = ' '.join(want.split()) + if got == want: + return True + + # The ELLIPSIS flag says to let the sequence "..." in `want` + # match any substring in `got`. + if optionflags & pdoctest.ELLIPSIS: + if pdoctest._ellipsis_match(want, got): + return True + + # We didn't find any match; return false. + return False + + +class Reporter: + """ + Parent class for all reporters. + """ + pass + + +class PyTestReporter(Reporter): + """ + Py.test like reporter. Should produce output identical to py.test. + """ + + def __init__(self, verbose=False, tb="short", colors=True, + force_colors=False, split=None): + self._verbose = verbose + self._tb_style = tb + self._colors = colors + self._force_colors = force_colors + self._xfailed = 0 + self._xpassed = [] + self._failed = [] + self._failed_doctest = [] + self._passed = 0 + self._skipped = 0 + self._exceptions = [] + self._terminal_width = None + self._default_width = 80 + self._split = split + self._active_file = '' + self._active_f = None + + # TODO: Should these be protected? + self.slow_test_functions = [] + self.fast_test_functions = [] + + # this tracks the x-position of the cursor (useful for positioning + # things on the screen), without the need for any readline library: + self._write_pos = 0 + self._line_wrap = False + + def root_dir(self, dir): + self._root_dir = dir + + @property + def terminal_width(self): + if self._terminal_width is not None: + return self._terminal_width + + def findout_terminal_width(): + if sys.platform == "win32": + # Windows support is based on: + # + # http://code.activestate.com/recipes/ + # 440694-determine-size-of-console-window-on-windows/ + + from ctypes import windll, create_string_buffer + + h = windll.kernel32.GetStdHandle(-12) + csbi = create_string_buffer(22) + res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) + + if res: + import struct + (_, _, _, _, _, left, _, right, _, _, _) = \ + struct.unpack("hhhhHhhhhhh", csbi.raw) + return right - left + else: + return self._default_width + + if hasattr(sys.stdout, 'isatty') and not sys.stdout.isatty(): + return self._default_width # leave PIPEs alone + + try: + process = subprocess.Popen(['stty', '-a'], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + stdout, stderr = process.communicate() + stdout = stdout.decode("utf-8") + except OSError: + pass + else: + # We support the following output formats from stty: + # + # 1) Linux -> columns 80 + # 2) OS X -> 80 columns + # 3) Solaris -> columns = 80 + + re_linux = r"columns\s+(?P\d+);" + re_osx = r"(?P\d+)\s*columns;" + re_solaris = r"columns\s+=\s+(?P\d+);" + + for regex in (re_linux, re_osx, re_solaris): + match = re.search(regex, stdout) + + if match is not None: + columns = match.group('columns') + + try: + width = int(columns) + except ValueError: + pass + if width != 0: + return width + + return self._default_width + + width = findout_terminal_width() + self._terminal_width = width + + return width + + def write(self, text, color="", align="left", width=None, + force_colors=False): + """ + Prints a text on the screen. + + It uses sys.stdout.write(), so no readline library is necessary. + + Parameters + ========== + + color : choose from the colors below, "" means default color + align : "left"/"right", "left" is a normal print, "right" is aligned on + the right-hand side of the screen, filled with spaces if + necessary + width : the screen width + + """ + color_templates = ( + ("Black", "0;30"), + ("Red", "0;31"), + ("Green", "0;32"), + ("Brown", "0;33"), + ("Blue", "0;34"), + ("Purple", "0;35"), + ("Cyan", "0;36"), + ("LightGray", "0;37"), + ("DarkGray", "1;30"), + ("LightRed", "1;31"), + ("LightGreen", "1;32"), + ("Yellow", "1;33"), + ("LightBlue", "1;34"), + ("LightPurple", "1;35"), + ("LightCyan", "1;36"), + ("White", "1;37"), + ) + + colors = {} + + for name, value in color_templates: + colors[name] = value + c_normal = '\033[0m' + c_color = '\033[%sm' + + if width is None: + width = self.terminal_width + + if align == "right": + if self._write_pos + len(text) > width: + # we don't fit on the current line, create a new line + self.write("\n") + self.write(" "*(width - self._write_pos - len(text))) + + if not self._force_colors and hasattr(sys.stdout, 'isatty') and not \ + sys.stdout.isatty(): + # the stdout is not a terminal, this for example happens if the + # output is piped to less, e.g. "bin/test | less". In this case, + # the terminal control sequences would be printed verbatim, so + # don't use any colors. + color = "" + elif sys.platform == "win32": + # Windows consoles don't support ANSI escape sequences + color = "" + elif not self._colors: + color = "" + + if self._line_wrap: + if text[0] != "\n": + sys.stdout.write("\n") + + # Avoid UnicodeEncodeError when printing out test failures + if IS_WINDOWS: + text = text.encode('raw_unicode_escape').decode('utf8', 'ignore') + elif not sys.stdout.encoding.lower().startswith('utf'): + text = text.encode(sys.stdout.encoding, 'backslashreplace' + ).decode(sys.stdout.encoding) + + if color == "": + sys.stdout.write(text) + else: + sys.stdout.write("%s%s%s" % + (c_color % colors[color], text, c_normal)) + sys.stdout.flush() + l = text.rfind("\n") + if l == -1: + self._write_pos += len(text) + else: + self._write_pos = len(text) - l - 1 + self._line_wrap = self._write_pos >= width + self._write_pos %= width + + def write_center(self, text, delim="="): + width = self.terminal_width + if text != "": + text = " %s " % text + idx = (width - len(text)) // 2 + t = delim*idx + text + delim*(width - idx - len(text)) + self.write(t + "\n") + + def write_exception(self, e, val, tb): + # remove the first item, as that is always runtests.py + tb = tb.tb_next + t = traceback.format_exception(e, val, tb) + self.write("".join(t)) + + def start(self, seed=None, msg="test process starts"): + self.write_center(msg) + executable = sys.executable + v = tuple(sys.version_info) + python_version = "%s.%s.%s-%s-%s" % v + implementation = platform.python_implementation() + if implementation == 'PyPy': + implementation += " %s.%s.%s-%s-%s" % sys.pypy_version_info + self.write("executable: %s (%s) [%s]\n" % + (executable, python_version, implementation)) + from sympy.utilities.misc import ARCH + self.write("architecture: %s\n" % ARCH) + from sympy.core.cache import USE_CACHE + self.write("cache: %s\n" % USE_CACHE) + version = '' + if GROUND_TYPES =='gmpy': + import gmpy2 as gmpy + version = gmpy.version() + self.write("ground types: %s %s\n" % (GROUND_TYPES, version)) + numpy = import_module('numpy') + self.write("numpy: %s\n" % (None if not numpy else numpy.__version__)) + if seed is not None: + self.write("random seed: %d\n" % seed) + from sympy.utilities.misc import HASH_RANDOMIZATION + self.write("hash randomization: ") + hash_seed = os.getenv("PYTHONHASHSEED") or '0' + if HASH_RANDOMIZATION and (hash_seed == "random" or int(hash_seed)): + self.write("on (PYTHONHASHSEED=%s)\n" % hash_seed) + else: + self.write("off\n") + if self._split: + self.write("split: %s\n" % self._split) + self.write('\n') + self._t_start = clock() + + def finish(self): + self._t_end = clock() + self.write("\n") + global text, linelen + text = "tests finished: %d passed, " % self._passed + linelen = len(text) + + def add_text(mytext): + global text, linelen + """Break new text if too long.""" + if linelen + len(mytext) > self.terminal_width: + text += '\n' + linelen = 0 + text += mytext + linelen += len(mytext) + + if len(self._failed) > 0: + add_text("%d failed, " % len(self._failed)) + if len(self._failed_doctest) > 0: + add_text("%d failed, " % len(self._failed_doctest)) + if self._skipped > 0: + add_text("%d skipped, " % self._skipped) + if self._xfailed > 0: + add_text("%d expected to fail, " % self._xfailed) + if len(self._xpassed) > 0: + add_text("%d expected to fail but passed, " % len(self._xpassed)) + if len(self._exceptions) > 0: + add_text("%d exceptions, " % len(self._exceptions)) + add_text("in %.2f seconds" % (self._t_end - self._t_start)) + + if self.slow_test_functions: + self.write_center('slowest tests', '_') + sorted_slow = sorted(self.slow_test_functions, key=lambda r: r[1]) + for slow_func_name, taken in sorted_slow: + print('%s - Took %.3f seconds' % (slow_func_name, taken)) + + if self.fast_test_functions: + self.write_center('unexpectedly fast tests', '_') + sorted_fast = sorted(self.fast_test_functions, + key=lambda r: r[1]) + for fast_func_name, taken in sorted_fast: + print('%s - Took %.3f seconds' % (fast_func_name, taken)) + + if len(self._xpassed) > 0: + self.write_center("xpassed tests", "_") + for e in self._xpassed: + self.write("%s: %s\n" % (e[0], e[1])) + self.write("\n") + + if self._tb_style != "no" and len(self._exceptions) > 0: + for e in self._exceptions: + filename, f, (t, val, tb) = e + self.write_center("", "_") + if f is None: + s = "%s" % filename + else: + s = "%s:%s" % (filename, f.__name__) + self.write_center(s, "_") + self.write_exception(t, val, tb) + self.write("\n") + + if self._tb_style != "no" and len(self._failed) > 0: + for e in self._failed: + filename, f, (t, val, tb) = e + self.write_center("", "_") + self.write_center("%s::%s" % (filename, f.__name__), "_") + self.write_exception(t, val, tb) + self.write("\n") + + if self._tb_style != "no" and len(self._failed_doctest) > 0: + for e in self._failed_doctest: + filename, msg = e + self.write_center("", "_") + self.write_center("%s" % filename, "_") + self.write(msg) + self.write("\n") + + self.write_center(text) + ok = len(self._failed) == 0 and len(self._exceptions) == 0 and \ + len(self._failed_doctest) == 0 + if not ok: + self.write("DO *NOT* COMMIT!\n") + return ok + + def entering_filename(self, filename, n): + rel_name = filename[len(self._root_dir) + 1:] + self._active_file = rel_name + self._active_file_error = False + self.write(rel_name) + self.write("[%d] " % n) + + def leaving_filename(self): + self.write(" ") + if self._active_file_error: + self.write("[FAIL]", "Red", align="right") + else: + self.write("[OK]", "Green", align="right") + self.write("\n") + if self._verbose: + self.write("\n") + + def entering_test(self, f): + self._active_f = f + if self._verbose: + self.write("\n" + f.__name__ + " ") + + def test_xfail(self): + self._xfailed += 1 + self.write("f", "Green") + + def test_xpass(self, v): + message = str(v) + self._xpassed.append((self._active_file, message)) + self.write("X", "Green") + + def test_fail(self, exc_info): + self._failed.append((self._active_file, self._active_f, exc_info)) + self.write("F", "Red") + self._active_file_error = True + + def doctest_fail(self, name, error_msg): + # the first line contains "******", remove it: + error_msg = "\n".join(error_msg.split("\n")[1:]) + self._failed_doctest.append((name, error_msg)) + self.write("F", "Red") + self._active_file_error = True + + def test_pass(self, char="."): + self._passed += 1 + if self._verbose: + self.write("ok", "Green") + else: + self.write(char, "Green") + + def test_skip(self, v=None): + char = "s" + self._skipped += 1 + if v is not None: + message = str(v) + if message == "KeyboardInterrupt": + char = "K" + elif message == "Timeout": + char = "T" + elif message == "Slow": + char = "w" + if self._verbose: + if v is not None: + self.write(message + ' ', "Blue") + else: + self.write(" - ", "Blue") + self.write(char, "Blue") + + def test_exception(self, exc_info): + self._exceptions.append((self._active_file, self._active_f, exc_info)) + if exc_info[0] is TimeOutError: + self.write("T", "Red") + else: + self.write("E", "Red") + self._active_file_error = True + + def import_error(self, filename, exc_info): + self._exceptions.append((filename, None, exc_info)) + rel_name = filename[len(self._root_dir) + 1:] + self.write(rel_name) + self.write("[?] Failed to import", "Red") + self.write(" ") + self.write("[FAIL]", "Red", align="right") + self.write("\n") diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/runtests_pytest.py b/.venv/lib/python3.12/site-packages/sympy/testing/runtests_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..635f27864ca86571128e6c9a055199dfbde1ed63 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/testing/runtests_pytest.py @@ -0,0 +1,461 @@ +"""Backwards compatible functions for running tests from SymPy using pytest. + +SymPy historically had its own testing framework that aimed to: +- be compatible with pytest; +- operate similarly (or identically) to pytest; +- not require any external dependencies; +- have all the functionality in one file only; +- have no magic, just import the test file and execute the test functions; and +- be portable. + +To reduce the maintenance burden of developing an independent testing framework +and to leverage the benefits of existing Python testing infrastructure, SymPy +now uses pytest (and various of its plugins) to run the test suite. + +To maintain backwards compatibility with the legacy testing interface of SymPy, +which implemented functions that allowed users to run the tests on their +installed version of SymPy, the functions in this module are implemented to +match the existing API while thinly wrapping pytest. + +These two key functions are `test` and `doctest`. + +""" + +import functools +import importlib.util +import os +import pathlib +import re +from fnmatch import fnmatch +from typing import List, Optional, Tuple + +try: + import pytest +except ImportError: + + class NoPytestError(Exception): + """Raise when an internal test helper function is called with pytest.""" + + class pytest: # type: ignore + """Shadow to support pytest features when pytest can't be imported.""" + + @staticmethod + def main(*args, **kwargs): + msg = 'pytest must be installed to run tests via this function' + raise NoPytestError(msg) + +from sympy.testing.runtests import test as test_sympy + + +TESTPATHS_DEFAULT = ( + pathlib.Path('sympy'), + pathlib.Path('doc', 'src'), +) +BLACKLIST_DEFAULT = ( + 'sympy/integrals/rubi/rubi_tests/tests', +) + + +class PytestPluginManager: + """Module names for pytest plugins used by SymPy.""" + PYTEST: str = 'pytest' + RANDOMLY: str = 'pytest_randomly' + SPLIT: str = 'pytest_split' + TIMEOUT: str = 'pytest_timeout' + XDIST: str = 'xdist' + + @functools.cached_property + def has_pytest(self) -> bool: + return bool(importlib.util.find_spec(self.PYTEST)) + + @functools.cached_property + def has_randomly(self) -> bool: + return bool(importlib.util.find_spec(self.RANDOMLY)) + + @functools.cached_property + def has_split(self) -> bool: + return bool(importlib.util.find_spec(self.SPLIT)) + + @functools.cached_property + def has_timeout(self) -> bool: + return bool(importlib.util.find_spec(self.TIMEOUT)) + + @functools.cached_property + def has_xdist(self) -> bool: + return bool(importlib.util.find_spec(self.XDIST)) + + +split_pattern = re.compile(r'([1-9][0-9]*)/([1-9][0-9]*)') + + +@functools.lru_cache +def sympy_dir() -> pathlib.Path: + """Returns the root SymPy directory.""" + return pathlib.Path(__file__).parents[2] + + +def update_args_with_paths( + paths: List[str], + keywords: Optional[Tuple[str]], + args: List[str], +) -> List[str]: + """Appends valid paths and flags to the args `list` passed to `pytest.main`. + + The are three different types of "path" that a user may pass to the `paths` + positional arguments, all of which need to be handled slightly differently: + + 1. Nothing is passed + The paths to the `testpaths` defined in `pytest.ini` need to be appended + to the arguments list. + 2. Full, valid paths are passed + These paths need to be validated but can then be directly appended to + the arguments list. + 3. Partial paths are passed. + The `testpaths` defined in `pytest.ini` need to be recursed and any + matches be appended to the arguments list. + + """ + + def find_paths_matching_partial(partial_paths): + partial_path_file_patterns = [] + for partial_path in partial_paths: + if len(partial_path) >= 4: + has_test_prefix = partial_path[:4] == 'test' + has_py_suffix = partial_path[-3:] == '.py' + elif len(partial_path) >= 3: + has_test_prefix = False + has_py_suffix = partial_path[-3:] == '.py' + else: + has_test_prefix = False + has_py_suffix = False + if has_test_prefix and has_py_suffix: + partial_path_file_patterns.append(partial_path) + elif has_test_prefix: + partial_path_file_patterns.append(f'{partial_path}*.py') + elif has_py_suffix: + partial_path_file_patterns.append(f'test*{partial_path}') + else: + partial_path_file_patterns.append(f'test*{partial_path}*.py') + matches = [] + for testpath in valid_testpaths_default: + for path, dirs, files in os.walk(testpath, topdown=True): + zipped = zip(partial_paths, partial_path_file_patterns) + for (partial_path, partial_path_file) in zipped: + if fnmatch(path, f'*{partial_path}*'): + matches.append(str(pathlib.Path(path))) + dirs[:] = [] + else: + for file in files: + if fnmatch(file, partial_path_file): + matches.append(str(pathlib.Path(path, file))) + return matches + + def is_tests_file(filepath: str) -> bool: + path = pathlib.Path(filepath) + if not path.is_file(): + return False + if not path.parts[-1].startswith('test_'): + return False + if not path.suffix == '.py': + return False + return True + + def find_tests_matching_keywords(keywords, filepath): + matches = [] + source = pathlib.Path(filepath).read_text(encoding='utf-8') + for line in source.splitlines(): + if line.lstrip().startswith('def '): + for kw in keywords: + if line.lower().find(kw.lower()) != -1: + test_name = line.split(' ')[1].split('(')[0] + full_test_path = filepath + '::' + test_name + matches.append(full_test_path) + return matches + + valid_testpaths_default = [] + for testpath in TESTPATHS_DEFAULT: + absolute_testpath = pathlib.Path(sympy_dir(), testpath) + if absolute_testpath.exists(): + valid_testpaths_default.append(str(absolute_testpath)) + + candidate_paths = [] + if paths: + full_paths = [] + partial_paths = [] + for path in paths: + if pathlib.Path(path).exists(): + full_paths.append(str(pathlib.Path(sympy_dir(), path))) + else: + partial_paths.append(path) + matched_paths = find_paths_matching_partial(partial_paths) + candidate_paths.extend(full_paths) + candidate_paths.extend(matched_paths) + else: + candidate_paths.extend(valid_testpaths_default) + + if keywords is not None and keywords != (): + matches = [] + for path in candidate_paths: + if is_tests_file(path): + test_matches = find_tests_matching_keywords(keywords, path) + matches.extend(test_matches) + else: + for root, dirnames, filenames in os.walk(path): + for filename in filenames: + absolute_filepath = str(pathlib.Path(root, filename)) + if is_tests_file(absolute_filepath): + test_matches = find_tests_matching_keywords( + keywords, + absolute_filepath, + ) + matches.extend(test_matches) + args.extend(matches) + else: + args.extend(candidate_paths) + + return args + + +def make_absolute_path(partial_path: str) -> str: + """Convert a partial path to an absolute path. + + A path such a `sympy/core` might be needed. However, absolute paths should + be used in the arguments to pytest in all cases as it avoids errors that + arise from nonexistent paths. + + This function assumes that partial_paths will be passed in such that they + begin with the explicit `sympy` directory, i.e. `sympy/...`. + + """ + + def is_valid_partial_path(partial_path: str) -> bool: + """Assumption that partial paths are defined from the `sympy` root.""" + return pathlib.Path(partial_path).parts[0] == 'sympy' + + if not is_valid_partial_path(partial_path): + msg = ( + f'Partial path {dir(partial_path)} is invalid, partial paths are ' + f'expected to be defined with the `sympy` directory as the root.' + ) + raise ValueError(msg) + + absolute_path = str(pathlib.Path(sympy_dir(), partial_path)) + return absolute_path + + +def test(*paths, subprocess=True, rerun=0, **kwargs): + """Interface to run tests via pytest compatible with SymPy's test runner. + + Explanation + =========== + + Note that a `pytest.ExitCode`, which is an `enum`, is returned. This is + different to the legacy SymPy test runner which would return a `bool`. If + all tests successfully pass the `pytest.ExitCode.OK` with value `0` is + returned, whereas the legacy SymPy test runner would return `True`. In any + other scenario, a non-zero `enum` value is returned, whereas the legacy + SymPy test runner would return `False`. Users need to, therefore, be careful + if treating the pytest exit codes as booleans because + `bool(pytest.ExitCode.OK)` evaluates to `False`, the opposite of legacy + behaviour. + + Examples + ======== + + >>> import sympy # doctest: +SKIP + + Run one file: + + >>> sympy.test('sympy/core/tests/test_basic.py') # doctest: +SKIP + >>> sympy.test('_basic') # doctest: +SKIP + + Run all tests in sympy/functions/ and some particular file: + + >>> sympy.test("sympy/core/tests/test_basic.py", + ... "sympy/functions") # doctest: +SKIP + + Run all tests in sympy/core and sympy/utilities: + + >>> sympy.test("/core", "/util") # doctest: +SKIP + + Run specific test from a file: + + >>> sympy.test("sympy/core/tests/test_basic.py", + ... kw="test_equality") # doctest: +SKIP + + Run specific test from any file: + + >>> sympy.test(kw="subs") # doctest: +SKIP + + Run the tests using the legacy SymPy runner: + + >>> sympy.test(use_sympy_runner=True) # doctest: +SKIP + + Note that this option is slated for deprecation in the near future and is + only currently provided to ensure users have an alternative option while the + pytest-based runner receives real-world testing. + + Parameters + ========== + paths : first n positional arguments of strings + Paths, both partial and absolute, describing which subset(s) of the test + suite are to be run. + subprocess : bool, default is True + Legacy option, is currently ignored. + rerun : int, default is 0 + Legacy option, is ignored. + use_sympy_runner : bool or None, default is None + Temporary option to invoke the legacy SymPy test runner instead of + `pytest.main`. Will be removed in the near future. + verbose : bool, default is False + Sets the verbosity of the pytest output. Using `True` will add the + `--verbose` option to the pytest call. + tb : str, 'auto', 'long', 'short', 'line', 'native', or 'no' + Sets the traceback print mode of pytest using the `--tb` option. + kw : str + Only run tests which match the given substring expression. An expression + is a Python evaluatable expression where all names are substring-matched + against test names and their parent classes. Example: -k 'test_method or + test_other' matches all test functions and classes whose name contains + 'test_method' or 'test_other', while -k 'not test_method' matches those + that don't contain 'test_method' in their names. -k 'not test_method and + not test_other' will eliminate the matches. Additionally keywords are + matched to classes and functions containing extra names in their + 'extra_keyword_matches' set, as well as functions which have names + assigned directly to them. The matching is case-insensitive. + pdb : bool, default is False + Start the interactive Python debugger on errors or `KeyboardInterrupt`. + colors : bool, default is True + Color terminal output. + force_colors : bool, default is False + Legacy option, is ignored. + sort : bool, default is True + Run the tests in sorted order. pytest uses a sorted test order by + default. Requires pytest-randomly. + seed : int + Seed to use for random number generation. Requires pytest-randomly. + timeout : int, default is 0 + Timeout in seconds before dumping the stacks. 0 means no timeout. + Requires pytest-timeout. + fail_on_timeout : bool, default is False + Legacy option, is currently ignored. + slow : bool, default is False + Run the subset of tests marked as `slow`. + enhance_asserts : bool, default is False + Legacy option, is currently ignored. + split : string in form `/` or None, default is None + Used to split the tests up. As an example, if `split='2/3' is used then + only the middle third of tests are run. Requires pytest-split. + time_balance : bool, default is True + Legacy option, is currently ignored. + blacklist : iterable of test paths as strings, default is BLACKLIST_DEFAULT + Blacklisted test paths are ignored using the `--ignore` option. Paths + may be partial or absolute. If partial then they are matched against + all paths in the pytest tests path. + parallel : bool, default is False + Parallelize the test running using pytest-xdist. If `True` then pytest + will automatically detect the number of CPU cores available and use them + all. Requires pytest-xdist. + store_durations : bool, False + Store test durations into the file `.test_durations`. The is used by + `pytest-split` to help determine more even splits when more than one + test group is being used. Requires pytest-split. + + """ + # NOTE: to be removed alongside SymPy test runner + if kwargs.get('use_sympy_runner', False): + kwargs.pop('parallel', False) + kwargs.pop('store_durations', False) + kwargs.pop('use_sympy_runner', True) + if kwargs.get('slow') is None: + kwargs['slow'] = False + return test_sympy(*paths, subprocess=True, rerun=0, **kwargs) + + pytest_plugin_manager = PytestPluginManager() + if not pytest_plugin_manager.has_pytest: + pytest.main() + + args = [] + + if kwargs.get('verbose', False): + args.append('--verbose') + + if tb := kwargs.get('tb'): + args.extend(['--tb', tb]) + + if kwargs.get('pdb'): + args.append('--pdb') + + if not kwargs.get('colors', True): + args.extend(['--color', 'no']) + + if seed := kwargs.get('seed'): + if not pytest_plugin_manager.has_randomly: + msg = '`pytest-randomly` plugin required to control random seed.' + raise ModuleNotFoundError(msg) + args.extend(['--randomly-seed', str(seed)]) + + if kwargs.get('sort', True) and pytest_plugin_manager.has_randomly: + args.append('--randomly-dont-reorganize') + elif not kwargs.get('sort', True) and not pytest_plugin_manager.has_randomly: + msg = '`pytest-randomly` plugin required to randomize test order.' + raise ModuleNotFoundError(msg) + + if timeout := kwargs.get('timeout', None): + if not pytest_plugin_manager.has_timeout: + msg = '`pytest-timeout` plugin required to apply timeout to tests.' + raise ModuleNotFoundError(msg) + args.extend(['--timeout', str(int(timeout))]) + + # Skip slow tests by default and always skip tooslow tests + if kwargs.get('slow', False): + args.extend(['-m', 'slow and not tooslow']) + else: + args.extend(['-m', 'not slow and not tooslow']) + + if (split := kwargs.get('split')) is not None: + if not pytest_plugin_manager.has_split: + msg = '`pytest-split` plugin required to run tests as groups.' + raise ModuleNotFoundError(msg) + match = split_pattern.match(split) + if not match: + msg = ('split must be a string of the form a/b where a and b are ' + 'positive nonzero ints') + raise ValueError(msg) + group, splits = map(str, match.groups()) + args.extend(['--group', group, '--splits', splits]) + if group > splits: + msg = (f'cannot have a group number {group} with only {splits} ' + 'splits') + raise ValueError(msg) + + if blacklist := kwargs.get('blacklist', BLACKLIST_DEFAULT): + for path in blacklist: + args.extend(['--ignore', make_absolute_path(path)]) + + if kwargs.get('parallel', False): + if not pytest_plugin_manager.has_xdist: + msg = '`pytest-xdist` plugin required to run tests in parallel.' + raise ModuleNotFoundError(msg) + args.extend(['-n', 'auto']) + + if kwargs.get('store_durations', False): + if not pytest_plugin_manager.has_split: + msg = '`pytest-split` plugin required to store test durations.' + raise ModuleNotFoundError(msg) + args.append('--store-durations') + + if (keywords := kwargs.get('kw')) is not None: + keywords = tuple(str(kw) for kw in keywords) + else: + keywords = () + + args = update_args_with_paths(paths, keywords, args) + exit_code = pytest.main(args) + return exit_code + + +def doctest(): + """Interface to run doctests via pytest compatible with SymPy's test runner. + """ + raise NotImplementedError diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/tests/__init__.py b/.venv/lib/python3.12/site-packages/sympy/testing/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/tests/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/testing/tests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ef62361c2b651ccfa028760c86d6f6f6f256c74 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/testing/tests/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/tests/__pycache__/diagnose_imports.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/testing/tests/__pycache__/diagnose_imports.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3d0f79a7118c9d141010b19978ce6fc5b5a0a01 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/testing/tests/__pycache__/diagnose_imports.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/tests/__pycache__/test_code_quality.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/testing/tests/__pycache__/test_code_quality.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d899674dea3ad0cb2985920b1666c2f5d12c2bff Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/testing/tests/__pycache__/test_code_quality.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/tests/__pycache__/test_deprecated.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/testing/tests/__pycache__/test_deprecated.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d655983e420d309d23b510a33d84750249ca1ed Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/testing/tests/__pycache__/test_deprecated.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/tests/__pycache__/test_module_imports.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/testing/tests/__pycache__/test_module_imports.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f463b9d3cb96887bb5d9dad2de6367e8a977d8eb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/testing/tests/__pycache__/test_module_imports.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/tests/__pycache__/test_pytest.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/testing/tests/__pycache__/test_pytest.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91e5eaebbeb0fd20fe1927e9a272bf34fc474713 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/testing/tests/__pycache__/test_pytest.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/tests/__pycache__/test_runtests_pytest.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/testing/tests/__pycache__/test_runtests_pytest.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c421b7748b4fe1d5fa45da1424fdc092a6106456 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/testing/tests/__pycache__/test_runtests_pytest.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/tests/diagnose_imports.py b/.venv/lib/python3.12/site-packages/sympy/testing/tests/diagnose_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..a31b66c66690c082800ae36eee37dad6927e0b37 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/testing/tests/diagnose_imports.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python + +""" +Import diagnostics. Run bin/diagnose_imports.py --help for details. +""" + +from __future__ import annotations + +if __name__ == "__main__": + + import sys + import inspect + import builtins + + import optparse + + from os.path import abspath, dirname, join, normpath + this_file = abspath(__file__) + sympy_dir = join(dirname(this_file), '..', '..', '..') + sympy_dir = normpath(sympy_dir) + sys.path.insert(0, sympy_dir) + + option_parser = optparse.OptionParser( + usage= + "Usage: %prog option [options]\n" + "\n" + "Import analysis for imports between SymPy modules.") + option_group = optparse.OptionGroup( + option_parser, + 'Analysis options', + 'Options that define what to do. Exactly one of these must be given.') + option_group.add_option( + '--problems', + help= + 'Print all import problems, that is: ' + 'If an import pulls in a package instead of a module ' + '(e.g. sympy.core instead of sympy.core.add); ' # see ##PACKAGE## + 'if it imports a symbol that is already present; ' # see ##DUPLICATE## + 'if it imports a symbol ' + 'from somewhere other than the defining module.', # see ##ORIGIN## + action='count') + option_group.add_option( + '--origins', + help= + 'For each imported symbol in each module, ' + 'print the module that defined it. ' + '(This is useful for import refactoring.)', + action='count') + option_parser.add_option_group(option_group) + option_group = optparse.OptionGroup( + option_parser, + 'Sort options', + 'These options define the sort order for output lines. ' + 'At most one of these options is allowed. ' + 'Unsorted output will reflect the order in which imports happened.') + option_group.add_option( + '--by-importer', + help='Sort output lines by name of importing module.', + action='count') + option_group.add_option( + '--by-origin', + help='Sort output lines by name of imported module.', + action='count') + option_parser.add_option_group(option_group) + (options, args) = option_parser.parse_args() + if args: + option_parser.error( + 'Unexpected arguments %s (try %s --help)' % (args, sys.argv[0])) + if options.problems > 1: + option_parser.error('--problems must not be given more than once.') + if options.origins > 1: + option_parser.error('--origins must not be given more than once.') + if options.by_importer > 1: + option_parser.error('--by-importer must not be given more than once.') + if options.by_origin > 1: + option_parser.error('--by-origin must not be given more than once.') + options.problems = options.problems == 1 + options.origins = options.origins == 1 + options.by_importer = options.by_importer == 1 + options.by_origin = options.by_origin == 1 + if not options.problems and not options.origins: + option_parser.error( + 'At least one of --problems and --origins is required') + if options.problems and options.origins: + option_parser.error( + 'At most one of --problems and --origins is allowed') + if options.by_importer and options.by_origin: + option_parser.error( + 'At most one of --by-importer and --by-origin is allowed') + options.by_process = not options.by_importer and not options.by_origin + + builtin_import = builtins.__import__ + + class Definition: + """Information about a symbol's definition.""" + def __init__(self, name, value, definer): + self.name = name + self.value = value + self.definer = definer + def __hash__(self): + return hash(self.name) + def __eq__(self, other): + return self.name == other.name and self.value == other.value + def __ne__(self, other): + return not (self == other) + def __repr__(self): + return 'Definition(%s, ..., %s)' % ( + repr(self.name), repr(self.definer)) + + # Maps each function/variable to name of module to define it + symbol_definers: dict[Definition, str] = {} + + def in_module(a, b): + """Is a the same module as or a submodule of b?""" + return a == b or a != None and b != None and a.startswith(b + '.') + + def relevant(module): + """Is module relevant for import checking? + + Only imports between relevant modules will be checked.""" + return in_module(module, 'sympy') + + sorted_messages = [] + + def msg(msg, *args): + if options.by_process: + print(msg % args) + else: + sorted_messages.append(msg % args) + + def tracking_import(module, globals=globals(), locals=[], fromlist=None, level=-1): + """__import__ wrapper - does not change imports at all, but tracks them. + + Default order is implemented by doing output directly. + All other orders are implemented by collecting output information into + a sorted list that will be emitted after all imports are processed. + + Indirect imports can only occur after the requested symbol has been + imported directly (because the indirect import would not have a module + to pick the symbol up from). + So this code detects indirect imports by checking whether the symbol in + question was already imported. + + Keeps the semantics of __import__ unchanged.""" + caller_frame = inspect.getframeinfo(sys._getframe(1)) + importer_filename = caller_frame.filename + importer_module = globals['__name__'] + if importer_filename == caller_frame.filename: + importer_reference = '%s line %s' % ( + importer_filename, str(caller_frame.lineno)) + else: + importer_reference = importer_filename + result = builtin_import(module, globals, locals, fromlist, level) + importee_module = result.__name__ + # We're only interested if importer and importee are in SymPy + if relevant(importer_module) and relevant(importee_module): + for symbol in result.__dict__.iterkeys(): + definition = Definition( + symbol, result.__dict__[symbol], importer_module) + if definition not in symbol_definers: + symbol_definers[definition] = importee_module + if hasattr(result, '__path__'): + ##PACKAGE## + # The existence of __path__ is documented in the tutorial on modules. + # Python 3.3 documents this in http://docs.python.org/3.3/reference/import.html + if options.by_origin: + msg('Error: %s (a package) is imported by %s', + module, importer_reference) + else: + msg('Error: %s contains package import %s', + importer_reference, module) + if fromlist != None: + symbol_list = fromlist + if '*' in symbol_list: + if (importer_filename.endswith(("__init__.py", "__init__.pyc", "__init__.pyo"))): + # We do not check starred imports inside __init__ + # That's the normal "please copy over its imports to my namespace" + symbol_list = [] + else: + symbol_list = result.__dict__.iterkeys() + for symbol in symbol_list: + if symbol not in result.__dict__: + if options.by_origin: + msg('Error: %s.%s is not defined (yet), but %s tries to import it', + importee_module, symbol, importer_reference) + else: + msg('Error: %s tries to import %s.%s, which did not define it (yet)', + importer_reference, importee_module, symbol) + else: + definition = Definition( + symbol, result.__dict__[symbol], importer_module) + symbol_definer = symbol_definers[definition] + if symbol_definer == importee_module: + ##DUPLICATE## + if options.by_origin: + msg('Error: %s.%s is imported again into %s', + importee_module, symbol, importer_reference) + else: + msg('Error: %s imports %s.%s again', + importer_reference, importee_module, symbol) + else: + ##ORIGIN## + if options.by_origin: + msg('Error: %s.%s is imported by %s, which should import %s.%s instead', + importee_module, symbol, importer_reference, symbol_definer, symbol) + else: + msg('Error: %s imports %s.%s but should import %s.%s instead', + importer_reference, importee_module, symbol, symbol_definer, symbol) + return result + + builtins.__import__ = tracking_import + __import__('sympy') + + sorted_messages.sort() + for message in sorted_messages: + print(message) diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/tests/test_code_quality.py b/.venv/lib/python3.12/site-packages/sympy/testing/tests/test_code_quality.py new file mode 100644 index 0000000000000000000000000000000000000000..9a9f363f0b9a802553f8643186b7d858d1ad0694 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/testing/tests/test_code_quality.py @@ -0,0 +1,510 @@ +# coding=utf-8 +from os import walk, sep, pardir +from os.path import split, join, abspath, exists, isfile +from glob import glob +import re +import random +import ast + +from sympy.testing.pytest import raises +from sympy.testing.quality_unicode import _test_this_file_encoding + +# System path separator (usually slash or backslash) to be +# used with excluded files, e.g. +# exclude = set([ +# "%(sep)smpmath%(sep)s" % sepd, +# ]) +sepd = {"sep": sep} + +# path and sympy_path +SYMPY_PATH = abspath(join(split(__file__)[0], pardir, pardir)) # go to sympy/ +assert exists(SYMPY_PATH) + +TOP_PATH = abspath(join(SYMPY_PATH, pardir)) +BIN_PATH = join(TOP_PATH, "bin") +EXAMPLES_PATH = join(TOP_PATH, "examples") + +# Error messages +message_space = "File contains trailing whitespace: %s, line %s." +message_implicit = "File contains an implicit import: %s, line %s." +message_tabs = "File contains tabs instead of spaces: %s, line %s." +message_carriage = "File contains carriage returns at end of line: %s, line %s" +message_str_raise = "File contains string exception: %s, line %s" +message_gen_raise = "File contains generic exception: %s, line %s" +message_old_raise = "File contains old-style raise statement: %s, line %s, \"%s\"" +message_eof = "File does not end with a newline: %s, line %s" +message_multi_eof = "File ends with more than 1 newline: %s, line %s" +message_test_suite_def = "Function should start with 'test_' or '_': %s, line %s" +message_duplicate_test = "This is a duplicate test function: %s, line %s" +message_self_assignments = "File contains assignments to self/cls: %s, line %s." +message_func_is = "File contains '.func is': %s, line %s." +message_bare_expr = "File contains bare expression: %s, line %s." + +implicit_test_re = re.compile(r'^\s*(>>> )?(\.\.\. )?from .* import .*\*') +str_raise_re = re.compile( + r'^\s*(>>> )?(\.\.\. )?raise(\s+(\'|\")|\s*(\(\s*)+(\'|\"))') +gen_raise_re = re.compile( + r'^\s*(>>> )?(\.\.\. )?raise(\s+Exception|\s*(\(\s*)+Exception)') +old_raise_re = re.compile(r'^\s*(>>> )?(\.\.\. )?raise((\s*\(\s*)|\s+)\w+\s*,') +test_suite_def_re = re.compile(r'^def\s+(?!(_|test))[^(]*\(\s*\)\s*:$') +test_ok_def_re = re.compile(r'^def\s+test_.*:$') +test_file_re = re.compile(r'.*[/\\]test_.*\.py$') +func_is_re = re.compile(r'\.\s*func\s+is') + + +def tab_in_leading(s): + """Returns True if there are tabs in the leading whitespace of a line, + including the whitespace of docstring code samples.""" + n = len(s) - len(s.lstrip()) + if not s[n:n + 3] in ['...', '>>>']: + check = s[:n] + else: + smore = s[n + 3:] + check = s[:n] + smore[:len(smore) - len(smore.lstrip())] + return not (check.expandtabs() == check) + + +def find_self_assignments(s): + """Returns a list of "bad" assignments: if there are instances + of assigning to the first argument of the class method (except + for staticmethod's). + """ + t = [n for n in ast.parse(s).body if isinstance(n, ast.ClassDef)] + + bad = [] + for c in t: + for n in c.body: + if not isinstance(n, ast.FunctionDef): + continue + if any(d.id == 'staticmethod' + for d in n.decorator_list if isinstance(d, ast.Name)): + continue + if n.name == '__new__': + continue + if not n.args.args: + continue + first_arg = n.args.args[0].arg + + for m in ast.walk(n): + if isinstance(m, ast.Assign): + for a in m.targets: + if isinstance(a, ast.Name) and a.id == first_arg: + bad.append(m) + elif (isinstance(a, ast.Tuple) and + any(q.id == first_arg for q in a.elts + if isinstance(q, ast.Name))): + bad.append(m) + + return bad + + +def check_directory_tree(base_path, file_check, exclusions=set(), pattern="*.py"): + """ + Checks all files in the directory tree (with base_path as starting point) + with the file_check function provided, skipping files that contain + any of the strings in the set provided by exclusions. + """ + if not base_path: + return + for root, dirs, files in walk(base_path): + check_files(glob(join(root, pattern)), file_check, exclusions) + + +def check_files(files, file_check, exclusions=set(), pattern=None): + """ + Checks all files with the file_check function provided, skipping files + that contain any of the strings in the set provided by exclusions. + """ + if not files: + return + for fname in files: + if not exists(fname) or not isfile(fname): + continue + if any(ex in fname for ex in exclusions): + continue + if pattern is None or re.match(pattern, fname): + file_check(fname) + + +class _Visit(ast.NodeVisitor): + """return the line number corresponding to the + line on which a bare expression appears if it is a binary op + or a comparison that is not in a with block. + + EXAMPLES + ======== + + >>> import ast + >>> class _Visit(ast.NodeVisitor): + ... def visit_Expr(self, node): + ... if isinstance(node.value, (ast.BinOp, ast.Compare)): + ... print(node.lineno) + ... def visit_With(self, node): + ... pass # no checking there + ... + >>> code='''x = 1 # line 1 + ... for i in range(3): + ... x == 2 # <-- 3 + ... if x == 2: + ... x == 3 # <-- 5 + ... x + 1 # <-- 6 + ... x = 1 + ... if x == 1: + ... print(1) + ... while x != 1: + ... x == 1 # <-- 11 + ... with raises(TypeError): + ... c == 1 + ... raise TypeError + ... assert x == 1 + ... ''' + >>> _Visit().visit(ast.parse(code)) + 3 + 5 + 6 + 11 + """ + def visit_Expr(self, node): + if isinstance(node.value, (ast.BinOp, ast.Compare)): + assert None, message_bare_expr % ('', node.lineno) + def visit_With(self, node): + pass + + +BareExpr = _Visit() + + +def line_with_bare_expr(code): + """return None or else 0-based line number of code on which + a bare expression appeared. + """ + tree = ast.parse(code) + try: + BareExpr.visit(tree) + except AssertionError as msg: + assert msg.args + msg = msg.args[0] + assert msg.startswith(message_bare_expr.split(':', 1)[0]) + return int(msg.rsplit(' ', 1)[1].rstrip('.')) # the line number + + +def test_files(): + """ + This test tests all files in SymPy and checks that: + o no lines contains a trailing whitespace + o no lines end with \r\n + o no line uses tabs instead of spaces + o that the file ends with a single newline + o there are no general or string exceptions + o there are no old style raise statements + o name of arg-less test suite functions start with _ or test_ + o no duplicate function names that start with test_ + o no assignments to self variable in class methods + o no lines contain ".func is" except in the test suite + o there is no do-nothing expression like `a == b` or `x + 1` + """ + + def test(fname): + with open(fname, encoding="utf8") as test_file: + test_this_file(fname, test_file) + with open(fname, encoding='utf8') as test_file: + _test_this_file_encoding(fname, test_file) + + def test_this_file(fname, test_file): + idx = None + code = test_file.read() + test_file.seek(0) # restore reader to head + py = fname if sep not in fname else fname.rsplit(sep, 1)[-1] + if py.startswith('test_'): + idx = line_with_bare_expr(code) + if idx is not None: + assert False, message_bare_expr % (fname, idx + 1) + + line = None # to flag the case where there were no lines in file + tests = 0 + test_set = set() + for idx, line in enumerate(test_file): + if test_file_re.match(fname): + if test_suite_def_re.match(line): + assert False, message_test_suite_def % (fname, idx + 1) + if test_ok_def_re.match(line): + tests += 1 + test_set.add(line[3:].split('(')[0].strip()) + if len(test_set) != tests: + assert False, message_duplicate_test % (fname, idx + 1) + if line.endswith((" \n", "\t\n")): + assert False, message_space % (fname, idx + 1) + if line.endswith("\r\n"): + assert False, message_carriage % (fname, idx + 1) + if tab_in_leading(line): + assert False, message_tabs % (fname, idx + 1) + if str_raise_re.search(line): + assert False, message_str_raise % (fname, idx + 1) + if gen_raise_re.search(line): + assert False, message_gen_raise % (fname, idx + 1) + if (implicit_test_re.search(line) and + not list(filter(lambda ex: ex in fname, import_exclude))): + assert False, message_implicit % (fname, idx + 1) + if func_is_re.search(line) and not test_file_re.search(fname): + assert False, message_func_is % (fname, idx + 1) + + result = old_raise_re.search(line) + + if result is not None: + assert False, message_old_raise % ( + fname, idx + 1, result.group(2)) + + if line is not None: + if line == '\n' and idx > 0: + assert False, message_multi_eof % (fname, idx + 1) + elif not line.endswith('\n'): + # eof newline check + assert False, message_eof % (fname, idx + 1) + + + # Files to test at top level + top_level_files = [join(TOP_PATH, file) for file in [ + "isympy.py", + "build.py", + "setup.py", + ]] + # Files to exclude from all tests + exclude = { + "%(sep)ssympy%(sep)sparsing%(sep)sautolev%(sep)s_antlr%(sep)sautolevparser.py" % sepd, + "%(sep)ssympy%(sep)sparsing%(sep)sautolev%(sep)s_antlr%(sep)sautolevlexer.py" % sepd, + "%(sep)ssympy%(sep)sparsing%(sep)sautolev%(sep)s_antlr%(sep)sautolevlistener.py" % sepd, + "%(sep)ssympy%(sep)sparsing%(sep)slatex%(sep)s_antlr%(sep)slatexparser.py" % sepd, + "%(sep)ssympy%(sep)sparsing%(sep)slatex%(sep)s_antlr%(sep)slatexlexer.py" % sepd, + } + # Files to exclude from the implicit import test + import_exclude = { + # glob imports are allowed in top-level __init__.py: + "%(sep)ssympy%(sep)s__init__.py" % sepd, + # these __init__.py should be fixed: + # XXX: not really, they use useful import pattern (DRY) + "%(sep)svector%(sep)s__init__.py" % sepd, + "%(sep)smechanics%(sep)s__init__.py" % sepd, + "%(sep)squantum%(sep)s__init__.py" % sepd, + "%(sep)spolys%(sep)s__init__.py" % sepd, + "%(sep)spolys%(sep)sdomains%(sep)s__init__.py" % sepd, + # interactive SymPy executes ``from sympy import *``: + "%(sep)sinteractive%(sep)ssession.py" % sepd, + # isympy.py executes ``from sympy import *``: + "%(sep)sisympy.py" % sepd, + # these two are import timing tests: + "%(sep)sbin%(sep)ssympy_time.py" % sepd, + "%(sep)sbin%(sep)ssympy_time_cache.py" % sepd, + # Taken from Python stdlib: + "%(sep)sparsing%(sep)ssympy_tokenize.py" % sepd, + # this one should be fixed: + "%(sep)splotting%(sep)spygletplot%(sep)s" % sepd, + # False positive in the docstring + "%(sep)sbin%(sep)stest_external_imports.py" % sepd, + "%(sep)sbin%(sep)stest_submodule_imports.py" % sepd, + # These are deprecated stubs that can be removed at some point: + "%(sep)sutilities%(sep)sruntests.py" % sepd, + "%(sep)sutilities%(sep)spytest.py" % sepd, + "%(sep)sutilities%(sep)srandtest.py" % sepd, + "%(sep)sutilities%(sep)stmpfiles.py" % sepd, + "%(sep)sutilities%(sep)squality_unicode.py" % sepd, + } + check_files(top_level_files, test) + check_directory_tree(BIN_PATH, test, {"~", ".pyc", ".sh"}, "*") + check_directory_tree(SYMPY_PATH, test, exclude) + check_directory_tree(EXAMPLES_PATH, test, exclude) + + +def _with_space(c): + # return c with a random amount of leading space + return random.randint(0, 10)*' ' + c + + +def test_raise_statement_regular_expression(): + candidates_ok = [ + "some text # raise Exception, 'text'", + "raise ValueError('text') # raise Exception, 'text'", + "raise ValueError('text')", + "raise ValueError", + "raise ValueError('text')", + "raise ValueError('text') #,", + # Talking about an exception in a docstring + ''''"""This function will raise ValueError, except when it doesn't"""''', + "raise (ValueError('text')", + ] + str_candidates_fail = [ + "raise 'exception'", + "raise 'Exception'", + 'raise "exception"', + 'raise "Exception"', + "raise 'ValueError'", + ] + gen_candidates_fail = [ + "raise Exception('text') # raise Exception, 'text'", + "raise Exception('text')", + "raise Exception", + "raise Exception('text')", + "raise Exception('text') #,", + "raise Exception, 'text'", + "raise Exception, 'text' # raise Exception('text')", + "raise Exception, 'text' # raise Exception, 'text'", + ">>> raise Exception, 'text'", + ">>> raise Exception, 'text' # raise Exception('text')", + ">>> raise Exception, 'text' # raise Exception, 'text'", + ] + old_candidates_fail = [ + "raise Exception, 'text'", + "raise Exception, 'text' # raise Exception('text')", + "raise Exception, 'text' # raise Exception, 'text'", + ">>> raise Exception, 'text'", + ">>> raise Exception, 'text' # raise Exception('text')", + ">>> raise Exception, 'text' # raise Exception, 'text'", + "raise ValueError, 'text'", + "raise ValueError, 'text' # raise Exception('text')", + "raise ValueError, 'text' # raise Exception, 'text'", + ">>> raise ValueError, 'text'", + ">>> raise ValueError, 'text' # raise Exception('text')", + ">>> raise ValueError, 'text' # raise Exception, 'text'", + "raise(ValueError,", + "raise (ValueError,", + "raise( ValueError,", + "raise ( ValueError,", + "raise(ValueError ,", + "raise (ValueError ,", + "raise( ValueError ,", + "raise ( ValueError ,", + ] + + for c in candidates_ok: + assert str_raise_re.search(_with_space(c)) is None, c + assert gen_raise_re.search(_with_space(c)) is None, c + assert old_raise_re.search(_with_space(c)) is None, c + for c in str_candidates_fail: + assert str_raise_re.search(_with_space(c)) is not None, c + for c in gen_candidates_fail: + assert gen_raise_re.search(_with_space(c)) is not None, c + for c in old_candidates_fail: + assert old_raise_re.search(_with_space(c)) is not None, c + + +def test_implicit_imports_regular_expression(): + candidates_ok = [ + "from sympy import something", + ">>> from sympy import something", + "from sympy.somewhere import something", + ">>> from sympy.somewhere import something", + "import sympy", + ">>> import sympy", + "import sympy.something.something", + "... import sympy", + "... import sympy.something.something", + "... from sympy import something", + "... from sympy.somewhere import something", + ">> from sympy import *", # To allow 'fake' docstrings + "# from sympy import *", + "some text # from sympy import *", + ] + candidates_fail = [ + "from sympy import *", + ">>> from sympy import *", + "from sympy.somewhere import *", + ">>> from sympy.somewhere import *", + "... from sympy import *", + "... from sympy.somewhere import *", + ] + for c in candidates_ok: + assert implicit_test_re.search(_with_space(c)) is None, c + for c in candidates_fail: + assert implicit_test_re.search(_with_space(c)) is not None, c + + +def test_test_suite_defs(): + candidates_ok = [ + " def foo():\n", + "def foo(arg):\n", + "def _foo():\n", + "def test_foo():\n", + ] + candidates_fail = [ + "def foo():\n", + "def foo() :\n", + "def foo( ):\n", + "def foo():\n", + ] + for c in candidates_ok: + assert test_suite_def_re.search(c) is None, c + for c in candidates_fail: + assert test_suite_def_re.search(c) is not None, c + + +def test_test_duplicate_defs(): + candidates_ok = [ + "def foo():\ndef foo():\n", + "def test():\ndef test_():\n", + "def test_():\ndef test__():\n", + ] + candidates_fail = [ + "def test_():\ndef test_ ():\n", + "def test_1():\ndef test_1():\n", + ] + ok = (None, 'check') + def check(file): + tests = 0 + test_set = set() + for idx, line in enumerate(file.splitlines()): + if test_ok_def_re.match(line): + tests += 1 + test_set.add(line[3:].split('(')[0].strip()) + if len(test_set) != tests: + return False, message_duplicate_test % ('check', idx + 1) + return None, 'check' + for c in candidates_ok: + assert check(c) == ok + for c in candidates_fail: + assert check(c) != ok + + +def test_find_self_assignments(): + candidates_ok = [ + "class A(object):\n def foo(self, arg): arg = self\n", + "class A(object):\n def foo(self, arg): self.prop = arg\n", + "class A(object):\n def foo(self, arg): obj, obj2 = arg, self\n", + "class A(object):\n @classmethod\n def bar(cls, arg): arg = cls\n", + "class A(object):\n def foo(var, arg): arg = var\n", + ] + candidates_fail = [ + "class A(object):\n def foo(self, arg): self = arg\n", + "class A(object):\n def foo(self, arg): obj, self = arg, arg\n", + "class A(object):\n def foo(self, arg):\n if arg: self = arg", + "class A(object):\n @classmethod\n def foo(cls, arg): cls = arg\n", + "class A(object):\n def foo(var, arg): var = arg\n", + ] + + for c in candidates_ok: + assert find_self_assignments(c) == [] + for c in candidates_fail: + assert find_self_assignments(c) != [] + + +def test_test_unicode_encoding(): + unicode_whitelist = ['foo'] + unicode_strict_whitelist = ['bar'] + + fname = 'abc' + test_file = ['α'] + raises(AssertionError, lambda: _test_this_file_encoding( + fname, test_file, unicode_whitelist, unicode_strict_whitelist)) + + fname = 'abc' + test_file = ['abc'] + _test_this_file_encoding( + fname, test_file, unicode_whitelist, unicode_strict_whitelist) + + fname = 'foo' + test_file = ['abc'] + raises(AssertionError, lambda: _test_this_file_encoding( + fname, test_file, unicode_whitelist, unicode_strict_whitelist)) + + fname = 'bar' + test_file = ['abc'] + _test_this_file_encoding( + fname, test_file, unicode_whitelist, unicode_strict_whitelist) diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/tests/test_deprecated.py b/.venv/lib/python3.12/site-packages/sympy/testing/tests/test_deprecated.py new file mode 100644 index 0000000000000000000000000000000000000000..696933d96d6232ea869da1002ec9ebee5309724d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/testing/tests/test_deprecated.py @@ -0,0 +1,5 @@ +from sympy.testing.pytest import warns_deprecated_sympy + +def test_deprecated_testing_randtest(): + with warns_deprecated_sympy(): + import sympy.testing.randtest # noqa:F401 diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/tests/test_module_imports.py b/.venv/lib/python3.12/site-packages/sympy/testing/tests/test_module_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..d16dbaa98156c287c18b46ff07c0ede5d26e069a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/testing/tests/test_module_imports.py @@ -0,0 +1,42 @@ +""" +Checks that SymPy does not contain indirect imports. + +An indirect import is importing a symbol from a module that itself imported the +symbol from elsewhere. Such a constellation makes it harder to diagnose +inter-module dependencies and import order problems, and is therefore strongly +discouraged. + +(Indirect imports from end-user code is fine and in fact a best practice.) + +Implementation note: Forcing Python into actually unloading already-imported +submodules is a tricky and partly undocumented process. To avoid these issues, +the actual diagnostic code is in bin/diagnose_imports, which is run as a +separate, pristine Python process. +""" + +import subprocess +import sys +from os.path import abspath, dirname, join, normpath +import inspect + +from sympy.testing.pytest import XFAIL + +@XFAIL +def test_module_imports_are_direct(): + my_filename = abspath(inspect.getfile(inspect.currentframe())) + my_dirname = dirname(my_filename) + diagnose_imports_filename = join(my_dirname, 'diagnose_imports.py') + diagnose_imports_filename = normpath(diagnose_imports_filename) + + process = subprocess.Popen( + [ + sys.executable, + normpath(diagnose_imports_filename), + '--problems', + '--by-importer' + ], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + bufsize=-1) + output, _ = process.communicate() + assert output == '', "There are import problems:\n" + output.decode() diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/tests/test_pytest.py b/.venv/lib/python3.12/site-packages/sympy/testing/tests/test_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7080a4ed4602707a3efb4d9025e8e9cbe23a5ef8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/testing/tests/test_pytest.py @@ -0,0 +1,211 @@ +import warnings + +from sympy.testing.pytest import (raises, warns, ignore_warnings, + warns_deprecated_sympy, Failed) +from sympy.utilities.exceptions import sympy_deprecation_warning + + + +# Test callables + + +def test_expected_exception_is_silent_callable(): + def f(): + raise ValueError() + raises(ValueError, f) + + +# Under pytest raises will raise Failed rather than AssertionError +def test_lack_of_exception_triggers_AssertionError_callable(): + try: + raises(Exception, lambda: 1 + 1) + assert False + except Failed as e: + assert "DID NOT RAISE" in str(e) + + +def test_unexpected_exception_is_passed_through_callable(): + def f(): + raise ValueError("some error message") + try: + raises(TypeError, f) + assert False + except ValueError as e: + assert str(e) == "some error message" + +# Test with statement + +def test_expected_exception_is_silent_with(): + with raises(ValueError): + raise ValueError() + + +def test_lack_of_exception_triggers_AssertionError_with(): + try: + with raises(Exception): + 1 + 1 + assert False + except Failed as e: + assert "DID NOT RAISE" in str(e) + + +def test_unexpected_exception_is_passed_through_with(): + try: + with raises(TypeError): + raise ValueError("some error message") + assert False + except ValueError as e: + assert str(e) == "some error message" + +# Now we can use raises() instead of try/catch +# to test that a specific exception class is raised + + +def test_second_argument_should_be_callable_or_string(): + raises(TypeError, lambda: raises("irrelevant", 42)) + + +def test_warns_catches_warning(): + with warnings.catch_warnings(record=True) as w: + with warns(UserWarning): + warnings.warn('this is the warning message') + assert len(w) == 0 + + +def test_warns_raises_without_warning(): + with raises(Failed): + with warns(UserWarning): + pass + + +def test_warns_hides_other_warnings(): + with raises(RuntimeWarning): + with warns(UserWarning): + warnings.warn('this is the warning message', UserWarning) + warnings.warn('this is the other message', RuntimeWarning) + + +def test_warns_continues_after_warning(): + with warnings.catch_warnings(record=True) as w: + finished = False + with warns(UserWarning): + warnings.warn('this is the warning message') + finished = True + assert finished + assert len(w) == 0 + + +def test_warns_many_warnings(): + with warns(UserWarning): + warnings.warn('this is the warning message', UserWarning) + warnings.warn('this is the other warning message', UserWarning) + + +def test_warns_match_matching(): + with warnings.catch_warnings(record=True) as w: + with warns(UserWarning, match='this is the warning message'): + warnings.warn('this is the warning message', UserWarning) + assert len(w) == 0 + + +def test_warns_match_non_matching(): + with warnings.catch_warnings(record=True) as w: + with raises(Failed): + with warns(UserWarning, match='this is the warning message'): + warnings.warn('this is not the expected warning message', UserWarning) + assert len(w) == 0 + +def _warn_sympy_deprecation(stacklevel=3): + sympy_deprecation_warning( + "feature", + active_deprecations_target="active-deprecations", + deprecated_since_version="0.0.0", + stacklevel=stacklevel, + ) + +def test_warns_deprecated_sympy_catches_warning(): + with warnings.catch_warnings(record=True) as w: + with warns_deprecated_sympy(): + _warn_sympy_deprecation() + assert len(w) == 0 + + +def test_warns_deprecated_sympy_raises_without_warning(): + with raises(Failed): + with warns_deprecated_sympy(): + pass + +def test_warns_deprecated_sympy_wrong_stacklevel(): + with raises(Failed): + with warns_deprecated_sympy(): + _warn_sympy_deprecation(stacklevel=1) + +def test_warns_deprecated_sympy_doesnt_hide_other_warnings(): + # Unlike pytest's deprecated_call, we should not hide other warnings. + with raises(RuntimeWarning): + with warns_deprecated_sympy(): + _warn_sympy_deprecation() + warnings.warn('this is the other message', RuntimeWarning) + + +def test_warns_deprecated_sympy_continues_after_warning(): + with warnings.catch_warnings(record=True) as w: + finished = False + with warns_deprecated_sympy(): + _warn_sympy_deprecation() + finished = True + assert finished + assert len(w) == 0 + +def test_ignore_ignores_warning(): + with warnings.catch_warnings(record=True) as w: + with ignore_warnings(UserWarning): + warnings.warn('this is the warning message') + assert len(w) == 0 + + +def test_ignore_does_not_raise_without_warning(): + with warnings.catch_warnings(record=True) as w: + with ignore_warnings(UserWarning): + pass + assert len(w) == 0 + + +def test_ignore_allows_other_warnings(): + with warnings.catch_warnings(record=True) as w: + # This is needed when pytest is run as -Werror + # the setting is reverted at the end of the catch_Warnings block. + warnings.simplefilter("always") + with ignore_warnings(UserWarning): + warnings.warn('this is the warning message', UserWarning) + warnings.warn('this is the other message', RuntimeWarning) + assert len(w) == 1 + assert isinstance(w[0].message, RuntimeWarning) + assert str(w[0].message) == 'this is the other message' + + +def test_ignore_continues_after_warning(): + with warnings.catch_warnings(record=True) as w: + finished = False + with ignore_warnings(UserWarning): + warnings.warn('this is the warning message') + finished = True + assert finished + assert len(w) == 0 + + +def test_ignore_many_warnings(): + with warnings.catch_warnings(record=True) as w: + # This is needed when pytest is run as -Werror + # the setting is reverted at the end of the catch_Warnings block. + warnings.simplefilter("always") + with ignore_warnings(UserWarning): + warnings.warn('this is the warning message', UserWarning) + warnings.warn('this is the other message', RuntimeWarning) + warnings.warn('this is the warning message', UserWarning) + warnings.warn('this is the other message', RuntimeWarning) + warnings.warn('this is the other message', RuntimeWarning) + assert len(w) == 3 + for wi in w: + assert isinstance(wi.message, RuntimeWarning) + assert str(wi.message) == 'this is the other message' diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/tests/test_runtests_pytest.py b/.venv/lib/python3.12/site-packages/sympy/testing/tests/test_runtests_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..cd56d831f3618c9dbb8a1dffe63d95a0befc6adf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/testing/tests/test_runtests_pytest.py @@ -0,0 +1,171 @@ +import pathlib +from typing import List + +import pytest + +from sympy.testing.runtests_pytest import ( + make_absolute_path, + sympy_dir, + update_args_with_paths, +) + + +class TestMakeAbsolutePath: + + @staticmethod + @pytest.mark.parametrize( + 'partial_path', ['sympy', 'sympy/core', 'sympy/nonexistant_directory'], + ) + def test_valid_partial_path(partial_path: str): + """Paths that start with `sympy` are valid.""" + _ = make_absolute_path(partial_path) + + @staticmethod + @pytest.mark.parametrize( + 'partial_path', ['not_sympy', 'also/not/sympy'], + ) + def test_invalid_partial_path_raises_value_error(partial_path: str): + """A `ValueError` is raises on paths that don't start with `sympy`.""" + with pytest.raises(ValueError): + _ = make_absolute_path(partial_path) + + +class TestUpdateArgsWithPaths: + + @staticmethod + def test_no_paths(): + """If no paths are passed, only `sympy` and `doc/src` are appended. + + `sympy` and `doc/src` are the `testpaths` stated in `pytest.ini`. They + need to be manually added as if any path-related arguments are passed + to `pytest.main` then the settings in `pytest.ini` may be ignored. + + """ + paths = [] + args = update_args_with_paths(paths=paths, keywords=None, args=[]) + expected = [ + str(pathlib.Path(sympy_dir(), 'sympy')), + str(pathlib.Path(sympy_dir(), 'doc/src')), + ] + assert args == expected + + @staticmethod + @pytest.mark.parametrize( + 'path', + ['sympy/core/tests/test_basic.py', '_basic'] + ) + def test_one_file(path: str): + """Single files/paths, full or partial, are matched correctly.""" + args = update_args_with_paths(paths=[path], keywords=None, args=[]) + expected = [ + str(pathlib.Path(sympy_dir(), 'sympy/core/tests/test_basic.py')), + ] + assert args == expected + + @staticmethod + def test_partial_path_from_root(): + """Partial paths from the root directly are matched correctly.""" + args = update_args_with_paths(paths=['sympy/functions'], keywords=None, args=[]) + expected = [str(pathlib.Path(sympy_dir(), 'sympy/functions'))] + assert args == expected + + @staticmethod + def test_multiple_paths_from_root(): + """Multiple paths, partial or full, are matched correctly.""" + paths = ['sympy/core/tests/test_basic.py', 'sympy/functions'] + args = update_args_with_paths(paths=paths, keywords=None, args=[]) + expected = [ + str(pathlib.Path(sympy_dir(), 'sympy/core/tests/test_basic.py')), + str(pathlib.Path(sympy_dir(), 'sympy/functions')), + ] + assert args == expected + + @staticmethod + @pytest.mark.parametrize( + 'paths, expected_paths', + [ + ( + ['/core', '/util'], + [ + 'doc/src/modules/utilities', + 'doc/src/reference/public/utilities', + 'sympy/core', + 'sympy/logic/utilities', + 'sympy/utilities', + ] + ), + ] + ) + def test_multiple_paths_from_non_root(paths: List[str], expected_paths: List[str]): + """Multiple partial paths are matched correctly.""" + args = update_args_with_paths(paths=paths, keywords=None, args=[]) + assert len(args) == len(expected_paths) + for arg, expected in zip(sorted(args), expected_paths): + assert expected in arg + + @staticmethod + @pytest.mark.parametrize( + 'paths', + [ + + [], + ['sympy/physics'], + ['sympy/physics/mechanics'], + ['sympy/physics/mechanics/tests'], + ['sympy/physics/mechanics/tests/test_kane3.py'], + ] + ) + def test_string_as_keyword(paths: List[str]): + """String keywords are matched correctly.""" + keywords = ('bicycle', ) + args = update_args_with_paths(paths=paths, keywords=keywords, args=[]) + expected_args = ['sympy/physics/mechanics/tests/test_kane3.py::test_bicycle'] + assert len(args) == len(expected_args) + for arg, expected in zip(sorted(args), expected_args): + assert expected in arg + + @staticmethod + @pytest.mark.parametrize( + 'paths', + [ + + [], + ['sympy/core'], + ['sympy/core/tests'], + ['sympy/core/tests/test_sympify.py'], + ] + ) + def test_integer_as_keyword(paths: List[str]): + """Integer keywords are matched correctly.""" + keywords = ('3538', ) + args = update_args_with_paths(paths=paths, keywords=keywords, args=[]) + expected_args = ['sympy/core/tests/test_sympify.py::test_issue_3538'] + assert len(args) == len(expected_args) + for arg, expected in zip(sorted(args), expected_args): + assert expected in arg + + @staticmethod + def test_multiple_keywords(): + """Multiple keywords are matched correctly.""" + keywords = ('bicycle', '3538') + args = update_args_with_paths(paths=[], keywords=keywords, args=[]) + expected_args = [ + 'sympy/core/tests/test_sympify.py::test_issue_3538', + 'sympy/physics/mechanics/tests/test_kane3.py::test_bicycle', + ] + assert len(args) == len(expected_args) + for arg, expected in zip(sorted(args), expected_args): + assert expected in arg + + @staticmethod + def test_keyword_match_in_multiple_files(): + """Keywords are matched across multiple files.""" + keywords = ('1130', ) + args = update_args_with_paths(paths=[], keywords=keywords, args=[]) + expected_args = [ + 'sympy/integrals/tests/test_heurisch.py::test_heurisch_symbolic_coeffs_1130', + 'sympy/utilities/tests/test_lambdify.py::test_python_div_zero_issue_11306', + ] + assert len(args) == len(expected_args) + for arg, expected in zip(sorted(args), expected_args): + assert expected in arg diff --git a/.venv/lib/python3.12/site-packages/sympy/testing/tmpfiles.py b/.venv/lib/python3.12/site-packages/sympy/testing/tmpfiles.py new file mode 100644 index 0000000000000000000000000000000000000000..1d5c69cb58aa11f77679855f3df21f03a10d3b2b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/testing/tmpfiles.py @@ -0,0 +1,46 @@ +""" +This module adds context manager for temporary files generated by the tests. +""" + +import shutil +import os + + +class TmpFileManager: + """ + A class to track record of every temporary files created by the tests. + """ + tmp_files = set('') + tmp_folders = set('') + + @classmethod + def tmp_file(cls, name=''): + cls.tmp_files.add(name) + return name + + @classmethod + def tmp_folder(cls, name=''): + cls.tmp_folders.add(name) + return name + + @classmethod + def cleanup(cls): + while cls.tmp_files: + file = cls.tmp_files.pop() + if os.path.isfile(file): + os.remove(file) + while cls.tmp_folders: + folder = cls.tmp_folders.pop() + shutil.rmtree(folder) + +def cleanup_tmp_files(test_func): + """ + A decorator to help test codes remove temporary files after the tests. + """ + def wrapper_function(): + try: + test_func() + finally: + TmpFileManager.cleanup() + + return wrapper_function diff --git a/.venv/lib/python3.12/site-packages/sympy/this.py b/.venv/lib/python3.12/site-packages/sympy/this.py new file mode 100644 index 0000000000000000000000000000000000000000..c2a5504ac42c7d57790d65524b066a6df86ab539 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/this.py @@ -0,0 +1,21 @@ +""" +The Zen of SymPy. +""" + +s = """The Zen of SymPy + +Unevaluated is better than evaluated. +The user interface matters. +Printing matters. +Pure Python can be fast enough. +If it's too slow, it's (probably) your fault. +Documentation matters. +Correctness is more important than speed. +Push it in now and improve upon it later. +Coverage by testing matters. +Smart tests are better than random tests. +But random tests sometimes find what your smartest test missed. +The Python way is probably the right way. +Community is more important than code.""" + +print(s) diff --git a/.venv/lib/python3.12/site-packages/sympy/unify/__init__.py b/.venv/lib/python3.12/site-packages/sympy/unify/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5c166f9163785f4aa5744324eb817bef79b33525 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/unify/__init__.py @@ -0,0 +1,15 @@ +""" Unification in SymPy + +See sympy.unify.core docstring for algorithmic details + +See http://matthewrocklin.com/blog/work/2012/11/01/Unification/ for discussion +""" + +from .usympy import unify, rebuild +from .rewrite import rewriterule + +__all__ = [ + 'unify', 'rebuild', + + 'rewriterule', +] diff --git a/.venv/lib/python3.12/site-packages/sympy/unify/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/unify/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90198261e30d02cc4652ebf36833642a468c928f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/unify/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/unify/__pycache__/core.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/unify/__pycache__/core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c78ae82054fb2815cb9075dd24bb1eecf9c341a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/unify/__pycache__/core.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/unify/__pycache__/rewrite.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/unify/__pycache__/rewrite.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ec255b9e3697c9b97f42b9f5e0189724963e1a0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/unify/__pycache__/rewrite.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/unify/__pycache__/usympy.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/unify/__pycache__/usympy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e315488c80538d88f4d8085d5be5606adfd4d8d7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/unify/__pycache__/usympy.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/unify/core.py b/.venv/lib/python3.12/site-packages/sympy/unify/core.py new file mode 100644 index 0000000000000000000000000000000000000000..5359d0bbd376e9fa9efacff1d90c0bf51414cebf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/unify/core.py @@ -0,0 +1,234 @@ +""" Generic Unification algorithm for expression trees with lists of children + +This implementation is a direct translation of + +Artificial Intelligence: A Modern Approach by Stuart Russel and Peter Norvig +Second edition, section 9.2, page 276 + +It is modified in the following ways: + +1. We allow associative and commutative Compound expressions. This results in + combinatorial blowup. +2. We explore the tree lazily. +3. We provide generic interfaces to symbolic algebra libraries in Python. + +A more traditional version can be found here +http://aima.cs.berkeley.edu/python/logic.html +""" + +from sympy.utilities.iterables import kbins + +class Compound: + """ A little class to represent an interior node in the tree + + This is analogous to SymPy.Basic for non-Atoms + """ + def __init__(self, op, args): + self.op = op + self.args = args + + def __eq__(self, other): + return (type(self) is type(other) and self.op == other.op and + self.args == other.args) + + def __hash__(self): + return hash((type(self), self.op, self.args)) + + def __str__(self): + return "%s[%s]" % (str(self.op), ', '.join(map(str, self.args))) + +class Variable: + """ A Wild token """ + def __init__(self, arg): + self.arg = arg + + def __eq__(self, other): + return type(self) is type(other) and self.arg == other.arg + + def __hash__(self): + return hash((type(self), self.arg)) + + def __str__(self): + return "Variable(%s)" % str(self.arg) + +class CondVariable: + """ A wild token that matches conditionally. + + arg - a wild token. + valid - an additional constraining function on a match. + """ + def __init__(self, arg, valid): + self.arg = arg + self.valid = valid + + def __eq__(self, other): + return (type(self) is type(other) and + self.arg == other.arg and + self.valid == other.valid) + + def __hash__(self): + return hash((type(self), self.arg, self.valid)) + + def __str__(self): + return "CondVariable(%s)" % str(self.arg) + +def unify(x, y, s=None, **fns): + """ Unify two expressions. + + Parameters + ========== + + x, y - expression trees containing leaves, Compounds and Variables. + s - a mapping of variables to subtrees. + + Returns + ======= + + lazy sequence of mappings {Variable: subtree} + + Examples + ======== + + >>> from sympy.unify.core import unify, Compound, Variable + >>> expr = Compound("Add", ("x", "y")) + >>> pattern = Compound("Add", ("x", Variable("a"))) + >>> next(unify(expr, pattern, {})) + {Variable(a): 'y'} + """ + s = s or {} + + if x == y: + yield s + elif isinstance(x, (Variable, CondVariable)): + yield from unify_var(x, y, s, **fns) + elif isinstance(y, (Variable, CondVariable)): + yield from unify_var(y, x, s, **fns) + elif isinstance(x, Compound) and isinstance(y, Compound): + is_commutative = fns.get('is_commutative', lambda x: False) + is_associative = fns.get('is_associative', lambda x: False) + for sop in unify(x.op, y.op, s, **fns): + if is_associative(x) and is_associative(y): + a, b = (x, y) if len(x.args) < len(y.args) else (y, x) + if is_commutative(x) and is_commutative(y): + combs = allcombinations(a.args, b.args, 'commutative') + else: + combs = allcombinations(a.args, b.args, 'associative') + for aaargs, bbargs in combs: + aa = [unpack(Compound(a.op, arg)) for arg in aaargs] + bb = [unpack(Compound(b.op, arg)) for arg in bbargs] + yield from unify(aa, bb, sop, **fns) + elif len(x.args) == len(y.args): + yield from unify(x.args, y.args, sop, **fns) + + elif is_args(x) and is_args(y) and len(x) == len(y): + if len(x) == 0: + yield s + else: + for shead in unify(x[0], y[0], s, **fns): + yield from unify(x[1:], y[1:], shead, **fns) + +def unify_var(var, x, s, **fns): + if var in s: + yield from unify(s[var], x, s, **fns) + elif occur_check(var, x): + pass + elif isinstance(var, CondVariable) and var.valid(x): + yield assoc(s, var, x) + elif isinstance(var, Variable): + yield assoc(s, var, x) + +def occur_check(var, x): + """ var occurs in subtree owned by x? """ + if var == x: + return True + elif isinstance(x, Compound): + return occur_check(var, x.args) + elif is_args(x): + if any(occur_check(var, xi) for xi in x): return True + return False + +def assoc(d, key, val): + """ Return copy of d with key associated to val """ + d = d.copy() + d[key] = val + return d + +def is_args(x): + """ Is x a traditional iterable? """ + return type(x) in (tuple, list, set) + +def unpack(x): + if isinstance(x, Compound) and len(x.args) == 1: + return x.args[0] + else: + return x + +def allcombinations(A, B, ordered): + """ + Restructure A and B to have the same number of elements. + + Parameters + ========== + + ordered must be either 'commutative' or 'associative'. + + A and B can be rearranged so that the larger of the two lists is + reorganized into smaller sublists. + + Examples + ======== + + >>> from sympy.unify.core import allcombinations + >>> for x in allcombinations((1, 2, 3), (5, 6), 'associative'): print(x) + (((1,), (2, 3)), ((5,), (6,))) + (((1, 2), (3,)), ((5,), (6,))) + + >>> for x in allcombinations((1, 2, 3), (5, 6), 'commutative'): print(x) + (((1,), (2, 3)), ((5,), (6,))) + (((1, 2), (3,)), ((5,), (6,))) + (((1,), (3, 2)), ((5,), (6,))) + (((1, 3), (2,)), ((5,), (6,))) + (((2,), (1, 3)), ((5,), (6,))) + (((2, 1), (3,)), ((5,), (6,))) + (((2,), (3, 1)), ((5,), (6,))) + (((2, 3), (1,)), ((5,), (6,))) + (((3,), (1, 2)), ((5,), (6,))) + (((3, 1), (2,)), ((5,), (6,))) + (((3,), (2, 1)), ((5,), (6,))) + (((3, 2), (1,)), ((5,), (6,))) + """ + + if ordered == "commutative": + ordered = 11 + if ordered == "associative": + ordered = None + sm, bg = (A, B) if len(A) < len(B) else (B, A) + for part in kbins(list(range(len(bg))), len(sm), ordered=ordered): + if bg == B: + yield tuple((a,) for a in A), partition(B, part) + else: + yield partition(A, part), tuple((b,) for b in B) + +def partition(it, part): + """ Partition a tuple/list into pieces defined by indices. + + Examples + ======== + + >>> from sympy.unify.core import partition + >>> partition((10, 20, 30, 40), [[0, 1, 2], [3]]) + ((10, 20, 30), (40,)) + """ + return type(it)([index(it, ind) for ind in part]) + +def index(it, ind): + """ Fancy indexing into an indexable iterable (tuple, list). + + Examples + ======== + + >>> from sympy.unify.core import index + >>> index([10, 20, 30], (1, 2, 0)) + [20, 30, 10] + """ + return type(it)([it[i] for i in ind]) diff --git a/.venv/lib/python3.12/site-packages/sympy/unify/rewrite.py b/.venv/lib/python3.12/site-packages/sympy/unify/rewrite.py new file mode 100644 index 0000000000000000000000000000000000000000..95a6fa5ffd6a3fde94d17ee845c03bb2b44cf009 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/unify/rewrite.py @@ -0,0 +1,55 @@ +""" Functions to support rewriting of SymPy expressions """ + +from sympy.core.expr import Expr +from sympy.assumptions import ask +from sympy.strategies.tools import subs +from sympy.unify.usympy import rebuild, unify + +def rewriterule(source, target, variables=(), condition=None, assume=None): + """ Rewrite rule. + + Transform expressions that match source into expressions that match target + treating all ``variables`` as wilds. + + Examples + ======== + + >>> from sympy.abc import w, x, y, z + >>> from sympy.unify.rewrite import rewriterule + >>> from sympy import default_sort_key + >>> rl = rewriterule(x + y, x**y, [x, y]) + >>> sorted(rl(z + 3), key=default_sort_key) + [3**z, z**3] + + Use ``condition`` to specify additional requirements. Inputs are taken in + the same order as is found in variables. + + >>> rl = rewriterule(x + y, x**y, [x, y], lambda x, y: x.is_integer) + >>> list(rl(z + 3)) + [3**z] + + Use ``assume`` to specify additional requirements using new assumptions. + + >>> from sympy.assumptions import Q + >>> rl = rewriterule(x + y, x**y, [x, y], assume=Q.integer(x)) + >>> list(rl(z + 3)) + [3**z] + + Assumptions for the local context are provided at rule runtime + + >>> list(rl(w + z, Q.integer(z))) + [z**w] + """ + + def rewrite_rl(expr, assumptions=True): + for match in unify(source, expr, {}, variables=variables): + if (condition and + not condition(*[match.get(var, var) for var in variables])): + continue + if (assume and not ask(assume.xreplace(match), assumptions)): + continue + expr2 = subs(match)(target) + if isinstance(expr2, Expr): + expr2 = rebuild(expr2) + yield expr2 + return rewrite_rl diff --git a/.venv/lib/python3.12/site-packages/sympy/unify/tests/__init__.py b/.venv/lib/python3.12/site-packages/sympy/unify/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/sympy/unify/tests/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/unify/tests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8df19fbfe9f9551f98250e674c4b6a595cdaee69 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/unify/tests/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/unify/tests/__pycache__/test_rewrite.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/unify/tests/__pycache__/test_rewrite.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..467f7c1fc9a9606539b99b827dabde55a0d63b91 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/unify/tests/__pycache__/test_rewrite.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/unify/tests/__pycache__/test_sympy.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/unify/tests/__pycache__/test_sympy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e4357fe493fabd44feb3d163ae6baf3b33585bf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/unify/tests/__pycache__/test_sympy.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/unify/tests/__pycache__/test_unify.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/unify/tests/__pycache__/test_unify.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2237911c6bd594cb1633419d40c3d166075b3c4b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/unify/tests/__pycache__/test_unify.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/unify/tests/test_rewrite.py b/.venv/lib/python3.12/site-packages/sympy/unify/tests/test_rewrite.py new file mode 100644 index 0000000000000000000000000000000000000000..7b73e2856d5f6380c576220fa2780324df98091a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/unify/tests/test_rewrite.py @@ -0,0 +1,74 @@ +from sympy.unify.rewrite import rewriterule +from sympy.core.basic import Basic +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.functions.elementary.trigonometric import sin +from sympy.abc import x, y +from sympy.strategies.rl import rebuild +from sympy.assumptions import Q + +p, q = Symbol('p'), Symbol('q') + +def test_simple(): + rl = rewriterule(Basic(p, S(1)), Basic(p, S(2)), variables=(p,)) + assert list(rl(Basic(S(3), S(1)))) == [Basic(S(3), S(2))] + + p1 = p**2 + p2 = p**3 + rl = rewriterule(p1, p2, variables=(p,)) + + expr = x**2 + assert list(rl(expr)) == [x**3] + +def test_simple_variables(): + rl = rewriterule(Basic(x, S(1)), Basic(x, S(2)), variables=(x,)) + assert list(rl(Basic(S(3), S(1)))) == [Basic(S(3), S(2))] + + rl = rewriterule(x**2, x**3, variables=(x,)) + assert list(rl(y**2)) == [y**3] + +def test_moderate(): + p1 = p**2 + q**3 + p2 = (p*q)**4 + rl = rewriterule(p1, p2, (p, q)) + + expr = x**2 + y**3 + assert list(rl(expr)) == [(x*y)**4] + +def test_sincos(): + p1 = sin(p)**2 + sin(p)**2 + p2 = 1 + rl = rewriterule(p1, p2, (p, q)) + + assert list(rl(sin(x)**2 + sin(x)**2)) == [1] + assert list(rl(sin(y)**2 + sin(y)**2)) == [1] + +def test_Exprs_ok(): + rl = rewriterule(p+q, q+p, (p, q)) + next(rl(x+y)).is_commutative + str(next(rl(x+y))) + +def test_condition_simple(): + rl = rewriterule(x, x+1, [x], lambda x: x < 10) + assert not list(rl(S(15))) + assert rebuild(next(rl(S(5)))) == 6 + + +def test_condition_multiple(): + rl = rewriterule(x + y, x**y, [x,y], lambda x, y: x.is_integer) + + a = Symbol('a') + b = Symbol('b', integer=True) + expr = a + b + assert list(rl(expr)) == [b**a] + + c = Symbol('c', integer=True) + d = Symbol('d', integer=True) + assert set(rl(c + d)) == {c**d, d**c} + +def test_assumptions(): + rl = rewriterule(x + y, x**y, [x, y], assume=Q.integer(x)) + + a, b = map(Symbol, 'ab') + expr = a + b + assert list(rl(expr, Q.integer(b))) == [b**a] diff --git a/.venv/lib/python3.12/site-packages/sympy/unify/tests/test_sympy.py b/.venv/lib/python3.12/site-packages/sympy/unify/tests/test_sympy.py new file mode 100644 index 0000000000000000000000000000000000000000..eca3933a91abfabdbad96f626e4da761a41b3fd2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/unify/tests/test_sympy.py @@ -0,0 +1,162 @@ +from sympy.core.add import Add +from sympy.core.basic import Basic +from sympy.core.containers import Tuple +from sympy.core.singleton import S +from sympy.core.symbol import (Symbol, symbols) +from sympy.logic.boolalg import And +from sympy.core.symbol import Str +from sympy.unify.core import Compound, Variable +from sympy.unify.usympy import (deconstruct, construct, unify, is_associative, + is_commutative) +from sympy.abc import x, y, z, n + +def test_deconstruct(): + expr = Basic(S(1), S(2), S(3)) + expected = Compound(Basic, (1, 2, 3)) + assert deconstruct(expr) == expected + + assert deconstruct(1) == 1 + assert deconstruct(x) == x + assert deconstruct(x, variables=(x,)) == Variable(x) + assert deconstruct(Add(1, x, evaluate=False)) == Compound(Add, (1, x)) + assert deconstruct(Add(1, x, evaluate=False), variables=(x,)) == \ + Compound(Add, (1, Variable(x))) + +def test_construct(): + expr = Compound(Basic, (S(1), S(2), S(3))) + expected = Basic(S(1), S(2), S(3)) + assert construct(expr) == expected + +def test_nested(): + expr = Basic(S(1), Basic(S(2)), S(3)) + cmpd = Compound(Basic, (S(1), Compound(Basic, Tuple(2)), S(3))) + assert deconstruct(expr) == cmpd + assert construct(cmpd) == expr + +def test_unify(): + expr = Basic(S(1), S(2), S(3)) + a, b, c = map(Symbol, 'abc') + pattern = Basic(a, b, c) + assert list(unify(expr, pattern, {}, (a, b, c))) == [{a: 1, b: 2, c: 3}] + assert list(unify(expr, pattern, variables=(a, b, c))) == \ + [{a: 1, b: 2, c: 3}] + +def test_unify_variables(): + assert list(unify(Basic(S(1), S(2)), Basic(S(1), x), {}, variables=(x,))) == [{x: 2}] + +def test_s_input(): + expr = Basic(S(1), S(2)) + a, b = map(Symbol, 'ab') + pattern = Basic(a, b) + assert list(unify(expr, pattern, {}, (a, b))) == [{a: 1, b: 2}] + assert list(unify(expr, pattern, {a: 5}, (a, b))) == [] + +def iterdicteq(a, b): + a = tuple(a) + b = tuple(b) + return len(a) == len(b) and all(x in b for x in a) + +def test_unify_commutative(): + expr = Add(1, 2, 3, evaluate=False) + a, b, c = map(Symbol, 'abc') + pattern = Add(a, b, c, evaluate=False) + + result = tuple(unify(expr, pattern, {}, (a, b, c))) + expected = ({a: 1, b: 2, c: 3}, + {a: 1, b: 3, c: 2}, + {a: 2, b: 1, c: 3}, + {a: 2, b: 3, c: 1}, + {a: 3, b: 1, c: 2}, + {a: 3, b: 2, c: 1}) + + assert iterdicteq(result, expected) + +def test_unify_iter(): + expr = Add(1, 2, 3, evaluate=False) + a, b, c = map(Symbol, 'abc') + pattern = Add(a, c, evaluate=False) + assert is_associative(deconstruct(pattern)) + assert is_commutative(deconstruct(pattern)) + + result = list(unify(expr, pattern, {}, (a, c))) + expected = [{a: 1, c: Add(2, 3, evaluate=False)}, + {a: 1, c: Add(3, 2, evaluate=False)}, + {a: 2, c: Add(1, 3, evaluate=False)}, + {a: 2, c: Add(3, 1, evaluate=False)}, + {a: 3, c: Add(1, 2, evaluate=False)}, + {a: 3, c: Add(2, 1, evaluate=False)}, + {a: Add(1, 2, evaluate=False), c: 3}, + {a: Add(2, 1, evaluate=False), c: 3}, + {a: Add(1, 3, evaluate=False), c: 2}, + {a: Add(3, 1, evaluate=False), c: 2}, + {a: Add(2, 3, evaluate=False), c: 1}, + {a: Add(3, 2, evaluate=False), c: 1}] + + assert iterdicteq(result, expected) + +def test_hard_match(): + from sympy.functions.elementary.trigonometric import (cos, sin) + expr = sin(x) + cos(x)**2 + p, q = map(Symbol, 'pq') + pattern = sin(p) + cos(p)**2 + assert list(unify(expr, pattern, {}, (p, q))) == [{p: x}] + +def test_matrix(): + from sympy.matrices.expressions.matexpr import MatrixSymbol + X = MatrixSymbol('X', n, n) + Y = MatrixSymbol('Y', 2, 2) + Z = MatrixSymbol('Z', 2, 3) + assert list(unify(X, Y, {}, variables=[n, Str('X')])) == [{Str('X'): Str('Y'), n: 2}] + assert list(unify(X, Z, {}, variables=[n, Str('X')])) == [] + +def test_non_frankenAdds(): + # the is_commutative property used to fail because of Basic.__new__ + # This caused is_commutative and str calls to fail + expr = x+y*2 + rebuilt = construct(deconstruct(expr)) + # Ensure that we can run these commands without causing an error + str(rebuilt) + rebuilt.is_commutative + +def test_FiniteSet_commutivity(): + from sympy.sets.sets import FiniteSet + a, b, c, x, y = symbols('a,b,c,x,y') + s = FiniteSet(a, b, c) + t = FiniteSet(x, y) + variables = (x, y) + assert {x: FiniteSet(a, c), y: b} in tuple(unify(s, t, variables=variables)) + +def test_FiniteSet_complex(): + from sympy.sets.sets import FiniteSet + a, b, c, x, y, z = symbols('a,b,c,x,y,z') + expr = FiniteSet(Basic(S(1), x), y, Basic(x, z)) + pattern = FiniteSet(a, Basic(x, b)) + variables = a, b + expected = ({b: 1, a: FiniteSet(y, Basic(x, z))}, + {b: z, a: FiniteSet(y, Basic(S(1), x))}) + assert iterdicteq(unify(expr, pattern, variables=variables), expected) + + +def test_and(): + variables = x, y + expected = ({x: z > 0, y: n < 3},) + assert iterdicteq(unify((z>0) & (n<3), And(x, y), variables=variables), + expected) + +def test_Union(): + from sympy.sets.sets import Interval + assert list(unify(Interval(0, 1) + Interval(10, 11), + Interval(0, 1) + Interval(12, 13), + variables=(Interval(12, 13),))) + +def test_is_commutative(): + assert is_commutative(deconstruct(x+y)) + assert is_commutative(deconstruct(x*y)) + assert not is_commutative(deconstruct(x**y)) + +def test_commutative_in_commutative(): + from sympy.abc import a,b,c,d + from sympy.functions.elementary.trigonometric import (cos, sin) + eq = sin(3)*sin(4)*sin(5) + 4*cos(3)*cos(4) + pat = a*cos(b)*cos(c) + d*sin(b)*sin(c) + assert next(unify(eq, pat, variables=(a,b,c,d))) diff --git a/.venv/lib/python3.12/site-packages/sympy/unify/tests/test_unify.py b/.venv/lib/python3.12/site-packages/sympy/unify/tests/test_unify.py new file mode 100644 index 0000000000000000000000000000000000000000..31153242576e1ff55dd3097efbc985aced5d574a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/unify/tests/test_unify.py @@ -0,0 +1,88 @@ +from sympy.unify.core import Compound, Variable, CondVariable, allcombinations +from sympy.unify import core + +a,b,c = 'a', 'b', 'c' +w,x,y,z = map(Variable, 'wxyz') + +C = Compound + +def is_associative(x): + return isinstance(x, Compound) and (x.op in ('Add', 'Mul', 'CAdd', 'CMul')) +def is_commutative(x): + return isinstance(x, Compound) and (x.op in ('CAdd', 'CMul')) + + +def unify(a, b, s={}): + return core.unify(a, b, s=s, is_associative=is_associative, + is_commutative=is_commutative) + +def test_basic(): + assert list(unify(a, x, {})) == [{x: a}] + assert list(unify(a, x, {x: 10})) == [] + assert list(unify(1, x, {})) == [{x: 1}] + assert list(unify(a, a, {})) == [{}] + assert list(unify((w, x), (y, z), {})) == [{w: y, x: z}] + assert list(unify(x, (a, b), {})) == [{x: (a, b)}] + + assert list(unify((a, b), (x, x), {})) == [] + assert list(unify((y, z), (x, x), {}))!= [] + assert list(unify((a, (b, c)), (a, (x, y)), {})) == [{x: b, y: c}] + +def test_ops(): + assert list(unify(C('Add', (a,b,c)), C('Add', (a,x,y)), {})) == \ + [{x:b, y:c}] + assert list(unify(C('Add', (C('Mul', (1,2)), b,c)), C('Add', (x,y,c)), {})) == \ + [{x: C('Mul', (1,2)), y:b}] + +def test_associative(): + c1 = C('Add', (1,2,3)) + c2 = C('Add', (x,y)) + assert tuple(unify(c1, c2, {})) == ({x: 1, y: C('Add', (2, 3))}, + {x: C('Add', (1, 2)), y: 3}) + +def test_commutative(): + c1 = C('CAdd', (1,2,3)) + c2 = C('CAdd', (x,y)) + result = list(unify(c1, c2, {})) + assert {x: 1, y: C('CAdd', (2, 3))} in result + assert ({x: 2, y: C('CAdd', (1, 3))} in result or + {x: 2, y: C('CAdd', (3, 1))} in result) + +def _test_combinations_assoc(): + assert set(allcombinations((1,2,3), (a,b), True)) == \ + {(((1, 2), (3,)), (a, b)), (((1,), (2, 3)), (a, b))} + +def _test_combinations_comm(): + assert set(allcombinations((1,2,3), (a,b), None)) == \ + {(((1,), (2, 3)), ('a', 'b')), (((2,), (3, 1)), ('a', 'b')), + (((3,), (1, 2)), ('a', 'b')), (((1, 2), (3,)), ('a', 'b')), + (((2, 3), (1,)), ('a', 'b')), (((3, 1), (2,)), ('a', 'b'))} + +def test_allcombinations(): + assert set(allcombinations((1,2), (1,2), 'commutative')) ==\ + {(((1,),(2,)), ((1,),(2,))), (((1,),(2,)), ((2,),(1,)))} + + +def test_commutativity(): + c1 = Compound('CAdd', (a, b)) + c2 = Compound('CAdd', (x, y)) + assert is_commutative(c1) and is_commutative(c2) + assert len(list(unify(c1, c2, {}))) == 2 + + +def test_CondVariable(): + expr = C('CAdd', (1, 2)) + x = Variable('x') + y = CondVariable('y', lambda a: a % 2 == 0) + z = CondVariable('z', lambda a: a > 3) + pattern = C('CAdd', (x, y)) + assert list(unify(expr, pattern, {})) == \ + [{x: 1, y: 2}] + + z = CondVariable('z', lambda a: a > 3) + pattern = C('CAdd', (z, y)) + + assert list(unify(expr, pattern, {})) == [] + +def test_defaultdict(): + assert next(unify(Variable('x'), 'foo')) == {Variable('x'): 'foo'} diff --git a/.venv/lib/python3.12/site-packages/sympy/unify/usympy.py b/.venv/lib/python3.12/site-packages/sympy/unify/usympy.py new file mode 100644 index 0000000000000000000000000000000000000000..3942b35ec549e5dbd08a3cf1cad2b2ecea733c7a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/unify/usympy.py @@ -0,0 +1,124 @@ +""" SymPy interface to Unification engine + +See sympy.unify for module level docstring +See sympy.unify.core for algorithmic docstring """ + +from sympy.core import Basic, Add, Mul, Pow +from sympy.core.operations import AssocOp, LatticeOp +from sympy.matrices import MatAdd, MatMul, MatrixExpr +from sympy.sets.sets import Union, Intersection, FiniteSet +from sympy.unify.core import Compound, Variable, CondVariable +from sympy.unify import core + +basic_new_legal = [MatrixExpr] +eval_false_legal = [AssocOp, Pow, FiniteSet] +illegal = [LatticeOp] + +def sympy_associative(op): + assoc_ops = (AssocOp, MatAdd, MatMul, Union, Intersection, FiniteSet) + return any(issubclass(op, aop) for aop in assoc_ops) + +def sympy_commutative(op): + comm_ops = (Add, MatAdd, Union, Intersection, FiniteSet) + return any(issubclass(op, cop) for cop in comm_ops) + +def is_associative(x): + return isinstance(x, Compound) and sympy_associative(x.op) + +def is_commutative(x): + if not isinstance(x, Compound): + return False + if sympy_commutative(x.op): + return True + if issubclass(x.op, Mul): + return all(construct(arg).is_commutative for arg in x.args) + +def mk_matchtype(typ): + def matchtype(x): + return (isinstance(x, typ) or + isinstance(x, Compound) and issubclass(x.op, typ)) + return matchtype + +def deconstruct(s, variables=()): + """ Turn a SymPy object into a Compound """ + if s in variables: + return Variable(s) + if isinstance(s, (Variable, CondVariable)): + return s + if not isinstance(s, Basic) or s.is_Atom: + return s + return Compound(s.__class__, + tuple(deconstruct(arg, variables) for arg in s.args)) + +def construct(t): + """ Turn a Compound into a SymPy object """ + if isinstance(t, (Variable, CondVariable)): + return t.arg + if not isinstance(t, Compound): + return t + if any(issubclass(t.op, cls) for cls in eval_false_legal): + return t.op(*map(construct, t.args), evaluate=False) + elif any(issubclass(t.op, cls) for cls in basic_new_legal): + return Basic.__new__(t.op, *map(construct, t.args)) + else: + return t.op(*map(construct, t.args)) + +def rebuild(s): + """ Rebuild a SymPy expression. + + This removes harm caused by Expr-Rules interactions. + """ + return construct(deconstruct(s)) + +def unify(x, y, s=None, variables=(), **kwargs): + """ Structural unification of two expressions/patterns. + + Examples + ======== + + >>> from sympy.unify.usympy import unify + >>> from sympy import Basic, S + >>> from sympy.abc import x, y, z, p, q + + >>> next(unify(Basic(S(1), S(2)), Basic(S(1), x), variables=[x])) + {x: 2} + + >>> expr = 2*x + y + z + >>> pattern = 2*p + q + >>> next(unify(expr, pattern, {}, variables=(p, q))) + {p: x, q: y + z} + + Unification supports commutative and associative matching + + >>> expr = x + y + z + >>> pattern = p + q + >>> len(list(unify(expr, pattern, {}, variables=(p, q)))) + 12 + + Symbols not indicated to be variables are treated as literal, + else they are wild-like and match anything in a sub-expression. + + >>> expr = x*y*z + 3 + >>> pattern = x*y + 3 + >>> next(unify(expr, pattern, {}, variables=[x, y])) + {x: y, y: x*z} + + The x and y of the pattern above were in a Mul and matched factors + in the Mul of expr. Here, a single symbol matches an entire term: + + >>> expr = x*y + 3 + >>> pattern = p + 3 + >>> next(unify(expr, pattern, {}, variables=[p])) + {p: x*y} + + """ + decons = lambda x: deconstruct(x, variables) + s = s or {} + s = {decons(k): decons(v) for k, v in s.items()} + + ds = core.unify(decons(x), decons(y), s, + is_associative=is_associative, + is_commutative=is_commutative, + **kwargs) + for d in ds: + yield {construct(k): construct(v) for k, v in d.items()} diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/__init__.py b/.venv/lib/python3.12/site-packages/sympy/utilities/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8f35da4a84396618a33a12c3c6b5cf58e9d4742c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/__init__.py @@ -0,0 +1,30 @@ +"""This module contains some general purpose utilities that are used across +SymPy. +""" +from .iterables import (flatten, group, take, subsets, + variations, numbered_symbols, cartes, capture, dict_merge, + prefixes, postfixes, sift, topological_sort, unflatten, + has_dups, has_variety, reshape, rotations) + +from .misc import filldedent + +from .lambdify import lambdify + +from .decorator import threaded, xthreaded, public, memoize_property + +from .timeutils import timed + +__all__ = [ + 'flatten', 'group', 'take', 'subsets', 'variations', 'numbered_symbols', + 'cartes', 'capture', 'dict_merge', 'prefixes', 'postfixes', 'sift', + 'topological_sort', 'unflatten', 'has_dups', 'has_variety', 'reshape', + 'rotations', + + 'filldedent', + + 'lambdify', + + 'threaded', 'xthreaded', 'public', 'memoize_property', + + 'timed', +] diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..827af5a5dd33b83e37dfac35ed3c3dbedf2810c8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/autowrap.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/autowrap.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec1b3a6269b24001aa000fd16688f3a972379204 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/autowrap.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/codegen.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/codegen.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c65a9f6609e7b2f325bb48fe102e44943a97fe5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/codegen.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/decorator.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/decorator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33413807ee647a29963cb57843788fcc0918196d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/decorator.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/enumerative.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/enumerative.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3c018e70626fcd59830ae9ed1b32a9f90d23b24 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/enumerative.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/exceptions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b0ecab9131f511288f42faaec7539ac9d518fdb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/exceptions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/iterables.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/iterables.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83993292adcf376dc49c4fddf5f4ba3439c19970 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/iterables.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d5a76d019af2f53b25f3271dbf85db84ff49d320304884aa0470f00c2c3fecd9 +size 105782 diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/lambdify.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/lambdify.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f9958f7bd9395b39e2a4cd05993252c304fb4c1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/lambdify.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/magic.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/magic.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3681b05ee4dbfa4462045adba313434ea141cc0c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/magic.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/matchpy_connector.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/matchpy_connector.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7190704dd1a4ab940fd1bb756dad6263c314d6f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/matchpy_connector.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/memoization.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/memoization.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d55de9a5ef16cfb87b6daa27a934f8959baa5f2b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/memoization.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/misc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/misc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f2711973689ac7ad3699895da0b8784dbf4a5b9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/misc.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/pkgdata.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/pkgdata.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d095c33cdc642dd4f3d561365298015d02c72fa6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/pkgdata.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/pytest.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/pytest.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4442c800540c87569118759e8fb21b49461fd55c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/pytest.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/randtest.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/randtest.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dde40470880e05d4b95969773b8264e7c11e5458 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/randtest.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/runtests.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/runtests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1321c2d537eafd9fb20c7dff1235ae1b7d048b48 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/runtests.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/source.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/source.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27cff68b54f2f06aa1d2d63d515c427f48560c14 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/source.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/timeutils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/timeutils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..262770cc60d8b1f1ede50c569de926da95c26d4b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/timeutils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/tmpfiles.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/tmpfiles.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49ca83bdaf8da3bcf5efd09613fe70e7e3ee59f1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/__pycache__/tmpfiles.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/__init__.py b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d2c05ad48a93493bb5434256c88dfd614ac47b2d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/__init__.py @@ -0,0 +1,22 @@ +""" This sub-module is private, i.e. external code should not depend on it. + +These functions are used by tests run as part of continuous integration. +Once the implementation is mature (it should support the major +platforms: Windows, OS X & Linux) it may become official API which + may be relied upon by downstream libraries. Until then API may break +without prior notice. + +TODO: +- (optionally) clean up after tempfile.mkdtemp() +- cross-platform testing +- caching of compiler choice and intermediate files + +""" + +from .compilation import compile_link_import_strings, compile_run_strings +from .availability import has_fortran, has_c, has_cxx + +__all__ = [ + 'compile_link_import_strings', 'compile_run_strings', + 'has_fortran', 'has_c', 'has_cxx', +] diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37ef40ac6b40059e0b085f9fc9550310f828a07d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/__pycache__/availability.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/__pycache__/availability.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b813dde4d3f586f86ced07b878e97426d5a9fc8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/__pycache__/availability.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/__pycache__/compilation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/__pycache__/compilation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac41c79be337452b763a1c38460ff29349568730 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/__pycache__/compilation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/__pycache__/runners.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/__pycache__/runners.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfd0b505c13f4f984c39d0e87621ef7a73646de9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/__pycache__/runners.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/__pycache__/util.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/__pycache__/util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5267322b6315b54fcea4425ff5f33076545fe67a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/__pycache__/util.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/availability.py b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/availability.py new file mode 100644 index 0000000000000000000000000000000000000000..dc97b3e7b8c7e7307c6c21352ed4035d977aabb3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/availability.py @@ -0,0 +1,77 @@ +import os +from .compilation import compile_run_strings +from .util import CompilerNotFoundError + +def has_fortran(): + if not hasattr(has_fortran, 'result'): + try: + (stdout, stderr), info = compile_run_strings( + [('main.f90', ( + 'program foo\n' + 'print *, "hello world"\n' + 'end program' + ))], clean=True + ) + except CompilerNotFoundError: + has_fortran.result = False + if os.environ.get('SYMPY_STRICT_COMPILER_CHECKS', '0') == '1': + raise + else: + if info['exit_status'] != os.EX_OK or 'hello world' not in stdout: + if os.environ.get('SYMPY_STRICT_COMPILER_CHECKS', '0') == '1': + raise ValueError("Failed to compile test program:\n%s\n%s\n" % (stdout, stderr)) + has_fortran.result = False + else: + has_fortran.result = True + return has_fortran.result + + +def has_c(): + if not hasattr(has_c, 'result'): + try: + (stdout, stderr), info = compile_run_strings( + [('main.c', ( + '#include \n' + 'int main(){\n' + 'printf("hello world\\n");\n' + 'return 0;\n' + '}' + ))], clean=True + ) + except CompilerNotFoundError: + has_c.result = False + if os.environ.get('SYMPY_STRICT_COMPILER_CHECKS', '0') == '1': + raise + else: + if info['exit_status'] != os.EX_OK or 'hello world' not in stdout: + if os.environ.get('SYMPY_STRICT_COMPILER_CHECKS', '0') == '1': + raise ValueError("Failed to compile test program:\n%s\n%s\n" % (stdout, stderr)) + has_c.result = False + else: + has_c.result = True + return has_c.result + + +def has_cxx(): + if not hasattr(has_cxx, 'result'): + try: + (stdout, stderr), info = compile_run_strings( + [('main.cxx', ( + '#include \n' + 'int main(){\n' + 'std::cout << "hello world" << std::endl;\n' + '}' + ))], clean=True + ) + except CompilerNotFoundError: + has_cxx.result = False + if os.environ.get('SYMPY_STRICT_COMPILER_CHECKS', '0') == '1': + raise + else: + if info['exit_status'] != os.EX_OK or 'hello world' not in stdout: + if os.environ.get('SYMPY_STRICT_COMPILER_CHECKS', '0') == '1': + raise ValueError("Failed to compile test program:\n%s\n%s\n" % (stdout, stderr)) + has_cxx.result = False + else: + has_cxx.result = True + return has_cxx.result diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/compilation.py b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/compilation.py new file mode 100644 index 0000000000000000000000000000000000000000..2d50a20467c08086d6cb5fb5b0d478e7a953d720 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/compilation.py @@ -0,0 +1,657 @@ +import glob +import os +import shutil +import subprocess +import sys +import tempfile +import warnings +from pathlib import Path +from sysconfig import get_config_var, get_config_vars, get_path + +from .runners import ( + CCompilerRunner, + CppCompilerRunner, + FortranCompilerRunner +) +from .util import ( + get_abspath, make_dirs, copy, Glob, ArbitraryDepthGlob, + glob_at_depth, import_module_from_file, pyx_is_cplus, + sha256_of_string, sha256_of_file, CompileError +) + +if os.name == 'posix': + objext = '.o' +elif os.name == 'nt': + objext = '.obj' +else: + warnings.warn("Unknown os.name: {}".format(os.name)) + objext = '.o' + + +def compile_sources(files, Runner=None, destdir=None, cwd=None, keep_dir_struct=False, + per_file_kwargs=None, **kwargs): + """ Compile source code files to object files. + + Parameters + ========== + + files : iterable of str + Paths to source files, if ``cwd`` is given, the paths are taken as relative. + Runner: CompilerRunner subclass (optional) + Could be e.g. ``FortranCompilerRunner``. Will be inferred from filename + extensions if missing. + destdir: str + Output directory, if cwd is given, the path is taken as relative. + cwd: str + Working directory. Specify to have compiler run in other directory. + also used as root of relative paths. + keep_dir_struct: bool + Reproduce directory structure in `destdir`. default: ``False`` + per_file_kwargs: dict + Dict mapping instances in ``files`` to keyword arguments. + \\*\\*kwargs: dict + Default keyword arguments to pass to ``Runner``. + + Returns + ======= + List of strings (paths of object files). + """ + _per_file_kwargs = {} + + if per_file_kwargs is not None: + for k, v in per_file_kwargs.items(): + if isinstance(k, Glob): + for path in glob.glob(k.pathname): + _per_file_kwargs[path] = v + elif isinstance(k, ArbitraryDepthGlob): + for path in glob_at_depth(k.filename, cwd): + _per_file_kwargs[path] = v + else: + _per_file_kwargs[k] = v + + # Set up destination directory + destdir = destdir or '.' + if not os.path.isdir(destdir): + if os.path.exists(destdir): + raise OSError("{} is not a directory".format(destdir)) + else: + make_dirs(destdir) + if cwd is None: + cwd = '.' + for f in files: + copy(f, destdir, only_update=True, dest_is_dir=True) + + # Compile files and return list of paths to the objects + dstpaths = [] + for f in files: + if keep_dir_struct: + name, ext = os.path.splitext(f) + else: + name, ext = os.path.splitext(os.path.basename(f)) + file_kwargs = kwargs.copy() + file_kwargs.update(_per_file_kwargs.get(f, {})) + dstpaths.append(src2obj(f, Runner, cwd=cwd, **file_kwargs)) + return dstpaths + + +def get_mixed_fort_c_linker(vendor=None, cplus=False, cwd=None): + vendor = vendor or os.environ.get('SYMPY_COMPILER_VENDOR', 'gnu') + + if vendor.lower() == 'intel': + if cplus: + return (FortranCompilerRunner, + {'flags': ['-nofor_main', '-cxxlib']}, vendor) + else: + return (FortranCompilerRunner, + {'flags': ['-nofor_main']}, vendor) + elif vendor.lower() == 'gnu' or 'llvm': + if cplus: + return (CppCompilerRunner, + {'lib_options': ['fortran']}, vendor) + else: + return (FortranCompilerRunner, + {}, vendor) + else: + raise ValueError("No vendor found.") + + +def link(obj_files, out_file=None, shared=False, Runner=None, + cwd=None, cplus=False, fort=False, extra_objs=None, **kwargs): + """ Link object files. + + Parameters + ========== + + obj_files: iterable of str + Paths to object files. + out_file: str (optional) + Path to executable/shared library, if ``None`` it will be + deduced from the last item in obj_files. + shared: bool + Generate a shared library? + Runner: CompilerRunner subclass (optional) + If not given the ``cplus`` and ``fort`` flags will be inspected + (fallback is the C compiler). + cwd: str + Path to the root of relative paths and working directory for compiler. + cplus: bool + C++ objects? default: ``False``. + fort: bool + Fortran objects? default: ``False``. + extra_objs: list + List of paths to extra object files / static libraries. + \\*\\*kwargs: dict + Keyword arguments passed to ``Runner``. + + Returns + ======= + + The absolute path to the generated shared object / executable. + + """ + if out_file is None: + out_file, ext = os.path.splitext(os.path.basename(obj_files[-1])) + if shared: + out_file += get_config_var('EXT_SUFFIX') + + if not Runner: + if fort: + Runner, extra_kwargs, vendor = \ + get_mixed_fort_c_linker( + vendor=kwargs.get('vendor', None), + cplus=cplus, + cwd=cwd, + ) + for k, v in extra_kwargs.items(): + if k in kwargs: + kwargs[k].expand(v) + else: + kwargs[k] = v + else: + if cplus: + Runner = CppCompilerRunner + else: + Runner = CCompilerRunner + + flags = kwargs.pop('flags', []) + if shared: + if '-shared' not in flags: + flags.append('-shared') + run_linker = kwargs.pop('run_linker', True) + if not run_linker: + raise ValueError("run_linker was set to False (nonsensical).") + + out_file = get_abspath(out_file, cwd=cwd) + runner = Runner(obj_files+(extra_objs or []), out_file, flags, cwd=cwd, **kwargs) + runner.run() + return out_file + + +def link_py_so(obj_files, so_file=None, cwd=None, libraries=None, + cplus=False, fort=False, extra_objs=None, **kwargs): + """ Link Python extension module (shared object) for importing + + Parameters + ========== + + obj_files: iterable of str + Paths to object files to be linked. + so_file: str + Name (path) of shared object file to create. If not specified it will + have the basname of the last object file in `obj_files` but with the + extension '.so' (Unix). + cwd: path string + Root of relative paths and working directory of linker. + libraries: iterable of strings + Libraries to link against, e.g. ['m']. + cplus: bool + Any C++ objects? default: ``False``. + fort: bool + Any Fortran objects? default: ``False``. + extra_objs: list + List of paths of extra object files / static libraries to link against. + kwargs**: dict + Keyword arguments passed to ``link(...)``. + + Returns + ======= + + Absolute path to the generate shared object. + """ + libraries = libraries or [] + + include_dirs = kwargs.pop('include_dirs', []) + library_dirs = kwargs.pop('library_dirs', []) + + # Add Python include and library directories + # PY_LDFLAGS does not available on all python implementations + # e.g. when with pypy, so it's LDFLAGS we need to use + if sys.platform == "win32": + warnings.warn("Windows not yet supported.") + elif sys.platform == 'darwin': + cfgDict = get_config_vars() + kwargs['linkline'] = kwargs.get('linkline', []) + [cfgDict['LDFLAGS']] + library_dirs += [cfgDict['LIBDIR']] + + # In macOS, linker needs to compile frameworks + # e.g. "-framework CoreFoundation" + is_framework = False + for opt in cfgDict['LIBS'].split(): + if is_framework: + kwargs['linkline'] = kwargs.get('linkline', []) + ['-framework', opt] + is_framework = False + elif opt.startswith('-l'): + libraries.append(opt[2:]) + elif opt.startswith('-framework'): + is_framework = True + # The python library is not included in LIBS + libfile = cfgDict['LIBRARY'] + libname = ".".join(libfile.split('.')[:-1])[3:] + libraries.append(libname) + + elif sys.platform[:3] == 'aix': + # Don't use the default code below + pass + else: + if get_config_var('Py_ENABLE_SHARED'): + cfgDict = get_config_vars() + kwargs['linkline'] = kwargs.get('linkline', []) + [cfgDict['LDFLAGS']] + library_dirs += [cfgDict['LIBDIR']] + for opt in cfgDict['BLDLIBRARY'].split(): + if opt.startswith('-l'): + libraries += [opt[2:]] + else: + pass + + flags = kwargs.pop('flags', []) + needed_flags = ('-pthread',) + for flag in needed_flags: + if flag not in flags: + flags.append(flag) + + return link(obj_files, shared=True, flags=flags, cwd=cwd, cplus=cplus, fort=fort, + include_dirs=include_dirs, libraries=libraries, + library_dirs=library_dirs, extra_objs=extra_objs, **kwargs) + + +def simple_cythonize(src, destdir=None, cwd=None, **cy_kwargs): + """ Generates a C file from a Cython source file. + + Parameters + ========== + + src: str + Path to Cython source. + destdir: str (optional) + Path to output directory (default: '.'). + cwd: path string (optional) + Root of relative paths (default: '.'). + **cy_kwargs: + Second argument passed to cy_compile. Generates a .cpp file if ``cplus=True`` in ``cy_kwargs``, + else a .c file. + """ + from Cython.Compiler.Main import ( + default_options, CompilationOptions + ) + from Cython.Compiler.Main import compile as cy_compile + + assert src.lower().endswith('.pyx') or src.lower().endswith('.py') + cwd = cwd or '.' + destdir = destdir or '.' + + ext = '.cpp' if cy_kwargs.get('cplus', False) else '.c' + c_name = os.path.splitext(os.path.basename(src))[0] + ext + + dstfile = os.path.join(destdir, c_name) + + if cwd: + ori_dir = os.getcwd() + else: + ori_dir = '.' + os.chdir(cwd) + try: + cy_options = CompilationOptions(default_options) + cy_options.__dict__.update(cy_kwargs) + # Set language_level if not set by cy_kwargs + # as not setting it is deprecated + if 'language_level' not in cy_kwargs: + cy_options.__dict__['language_level'] = 3 + cy_result = cy_compile([src], cy_options) + if cy_result.num_errors > 0: + raise ValueError("Cython compilation failed.") + + # Move generated C file to destination + # In macOS, the generated C file is in the same directory as the source + # but the /var is a symlink to /private/var, so we need to use realpath + if os.path.realpath(os.path.dirname(src)) != os.path.realpath(destdir): + if os.path.exists(dstfile): + os.unlink(dstfile) + shutil.move(os.path.join(os.path.dirname(src), c_name), destdir) + finally: + os.chdir(ori_dir) + return dstfile + + +extension_mapping = { + '.c': (CCompilerRunner, None), + '.cpp': (CppCompilerRunner, None), + '.cxx': (CppCompilerRunner, None), + '.f': (FortranCompilerRunner, None), + '.for': (FortranCompilerRunner, None), + '.ftn': (FortranCompilerRunner, None), + '.f90': (FortranCompilerRunner, None), # ifort only knows about .f90 + '.f95': (FortranCompilerRunner, 'f95'), + '.f03': (FortranCompilerRunner, 'f2003'), + '.f08': (FortranCompilerRunner, 'f2008'), +} + + +def src2obj(srcpath, Runner=None, objpath=None, cwd=None, inc_py=False, **kwargs): + """ Compiles a source code file to an object file. + + Files ending with '.pyx' assumed to be cython files and + are dispatched to pyx2obj. + + Parameters + ========== + + srcpath: str + Path to source file. + Runner: CompilerRunner subclass (optional) + If ``None``: deduced from extension of srcpath. + objpath : str (optional) + Path to generated object. If ``None``: deduced from ``srcpath``. + cwd: str (optional) + Working directory and root of relative paths. If ``None``: current dir. + inc_py: bool + Add Python include path to kwarg "include_dirs". Default: False + \\*\\*kwargs: dict + keyword arguments passed to Runner or pyx2obj + + """ + name, ext = os.path.splitext(os.path.basename(srcpath)) + if objpath is None: + if os.path.isabs(srcpath): + objpath = '.' + else: + objpath = os.path.dirname(srcpath) + objpath = objpath or '.' # avoid objpath == '' + + if os.path.isdir(objpath): + objpath = os.path.join(objpath, name + objext) + + include_dirs = kwargs.pop('include_dirs', []) + if inc_py: + py_inc_dir = get_path('include') + if py_inc_dir not in include_dirs: + include_dirs.append(py_inc_dir) + + if ext.lower() == '.pyx': + return pyx2obj(srcpath, objpath=objpath, include_dirs=include_dirs, cwd=cwd, + **kwargs) + + if Runner is None: + Runner, std = extension_mapping[ext.lower()] + if 'std' not in kwargs: + kwargs['std'] = std + + flags = kwargs.pop('flags', []) + needed_flags = ('-fPIC',) + for flag in needed_flags: + if flag not in flags: + flags.append(flag) + + # src2obj implies not running the linker... + run_linker = kwargs.pop('run_linker', False) + if run_linker: + raise CompileError("src2obj called with run_linker=True") + + runner = Runner([srcpath], objpath, include_dirs=include_dirs, + run_linker=run_linker, cwd=cwd, flags=flags, **kwargs) + runner.run() + return objpath + + +def pyx2obj(pyxpath, objpath=None, destdir=None, cwd=None, + include_dirs=None, cy_kwargs=None, cplus=None, **kwargs): + """ + Convenience function + + If cwd is specified, pyxpath and dst are taken to be relative + If only_update is set to `True` the modification time is checked + and compilation is only run if the source is newer than the + destination + + Parameters + ========== + + pyxpath: str + Path to Cython source file. + objpath: str (optional) + Path to object file to generate. + destdir: str (optional) + Directory to put generated C file. When ``None``: directory of ``objpath``. + cwd: str (optional) + Working directory and root of relative paths. + include_dirs: iterable of path strings (optional) + Passed onto src2obj and via cy_kwargs['include_path'] + to simple_cythonize. + cy_kwargs: dict (optional) + Keyword arguments passed onto `simple_cythonize` + cplus: bool (optional) + Indicate whether C++ is used. default: auto-detect using ``.util.pyx_is_cplus``. + compile_kwargs: dict + keyword arguments passed onto src2obj + + Returns + ======= + + Absolute path of generated object file. + + """ + assert pyxpath.endswith('.pyx') + cwd = cwd or '.' + objpath = objpath or '.' + destdir = destdir or os.path.dirname(objpath) + + abs_objpath = get_abspath(objpath, cwd=cwd) + + if os.path.isdir(abs_objpath): + pyx_fname = os.path.basename(pyxpath) + name, ext = os.path.splitext(pyx_fname) + objpath = os.path.join(objpath, name + objext) + + cy_kwargs = cy_kwargs or {} + cy_kwargs['output_dir'] = cwd + if cplus is None: + cplus = pyx_is_cplus(pyxpath) + cy_kwargs['cplus'] = cplus + + interm_c_file = simple_cythonize(pyxpath, destdir=destdir, cwd=cwd, **cy_kwargs) + + include_dirs = include_dirs or [] + flags = kwargs.pop('flags', []) + needed_flags = ('-fwrapv', '-pthread', '-fPIC') + for flag in needed_flags: + if flag not in flags: + flags.append(flag) + + options = kwargs.pop('options', []) + + if kwargs.pop('strict_aliasing', False): + raise CompileError("Cython requires strict aliasing to be disabled.") + + # Let's be explicit about standard + if cplus: + std = kwargs.pop('std', 'c++98') + else: + std = kwargs.pop('std', 'c99') + + return src2obj(interm_c_file, objpath=objpath, cwd=cwd, + include_dirs=include_dirs, flags=flags, std=std, + options=options, inc_py=True, strict_aliasing=False, + **kwargs) + + +def _any_X(srcs, cls): + for src in srcs: + name, ext = os.path.splitext(src) + key = ext.lower() + if key in extension_mapping: + if extension_mapping[key][0] == cls: + return True + return False + + +def any_fortran_src(srcs): + return _any_X(srcs, FortranCompilerRunner) + + +def any_cplus_src(srcs): + return _any_X(srcs, CppCompilerRunner) + + +def compile_link_import_py_ext(sources, extname=None, build_dir='.', compile_kwargs=None, + link_kwargs=None, extra_objs=None): + """ Compiles sources to a shared object (Python extension) and imports it + + Sources in ``sources`` which is imported. If shared object is newer than the sources, they + are not recompiled but instead it is imported. + + Parameters + ========== + + sources : list of strings + List of paths to sources. + extname : string + Name of extension (default: ``None``). + If ``None``: taken from the last file in ``sources`` without extension. + build_dir: str + Path to directory in which objects files etc. are generated. + compile_kwargs: dict + keyword arguments passed to ``compile_sources`` + link_kwargs: dict + keyword arguments passed to ``link_py_so`` + extra_objs: list + List of paths to (prebuilt) object files / static libraries to link against. + + Returns + ======= + + The imported module from of the Python extension. + """ + if extname is None: + extname = os.path.splitext(os.path.basename(sources[-1]))[0] + + compile_kwargs = compile_kwargs or {} + link_kwargs = link_kwargs or {} + + try: + mod = import_module_from_file(os.path.join(build_dir, extname), sources) + except ImportError: + objs = compile_sources(list(map(get_abspath, sources)), destdir=build_dir, + cwd=build_dir, **compile_kwargs) + so = link_py_so(objs, cwd=build_dir, fort=any_fortran_src(sources), + cplus=any_cplus_src(sources), extra_objs=extra_objs, **link_kwargs) + mod = import_module_from_file(so) + return mod + + +def _write_sources_to_build_dir(sources, build_dir): + build_dir = build_dir or tempfile.mkdtemp() + if not os.path.isdir(build_dir): + raise OSError("Non-existent directory: ", build_dir) + + source_files = [] + for name, src in sources: + dest = os.path.join(build_dir, name) + differs = True + sha256_in_mem = sha256_of_string(src.encode('utf-8')).hexdigest() + if os.path.exists(dest): + if os.path.exists(dest + '.sha256'): + sha256_on_disk = Path(dest + '.sha256').read_text() + else: + sha256_on_disk = sha256_of_file(dest).hexdigest() + + differs = sha256_on_disk != sha256_in_mem + if differs: + with open(dest, 'wt') as fh: + fh.write(src) + with open(dest + '.sha256', 'wt') as fh: + fh.write(sha256_in_mem) + source_files.append(dest) + return source_files, build_dir + + +def compile_link_import_strings(sources, build_dir=None, **kwargs): + """ Compiles, links and imports extension module from source. + + Parameters + ========== + + sources : iterable of name/source pair tuples + build_dir : string (default: None) + Path. ``None`` implies use a temporary directory. + **kwargs: + Keyword arguments passed onto `compile_link_import_py_ext`. + + Returns + ======= + + mod : module + The compiled and imported extension module. + info : dict + Containing ``build_dir`` as 'build_dir'. + + """ + source_files, build_dir = _write_sources_to_build_dir(sources, build_dir) + mod = compile_link_import_py_ext(source_files, build_dir=build_dir, **kwargs) + info = {"build_dir": build_dir} + return mod, info + + +def compile_run_strings(sources, build_dir=None, clean=False, compile_kwargs=None, link_kwargs=None): + """ Compiles, links and runs a program built from sources. + + Parameters + ========== + + sources : iterable of name/source pair tuples + build_dir : string (default: None) + Path. ``None`` implies use a temporary directory. + clean : bool + Whether to remove build_dir after use. This will only have an + effect if ``build_dir`` is ``None`` (which creates a temporary directory). + Passing ``clean == True`` and ``build_dir != None`` raises a ``ValueError``. + This will also set ``build_dir`` in returned info dictionary to ``None``. + compile_kwargs: dict + Keyword arguments passed onto ``compile_sources`` + link_kwargs: dict + Keyword arguments passed onto ``link`` + + Returns + ======= + + (stdout, stderr): pair of strings + info: dict + Containing exit status as 'exit_status' and ``build_dir`` as 'build_dir' + + """ + if clean and build_dir is not None: + raise ValueError("Automatic removal of build_dir is only available for temporary directory.") + try: + source_files, build_dir = _write_sources_to_build_dir(sources, build_dir) + objs = compile_sources(list(map(get_abspath, source_files)), destdir=build_dir, + cwd=build_dir, **(compile_kwargs or {})) + prog = link(objs, cwd=build_dir, + fort=any_fortran_src(source_files), + cplus=any_cplus_src(source_files), **(link_kwargs or {})) + p = subprocess.Popen([prog], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + exit_status = p.wait() + stdout, stderr = [txt.decode('utf-8') for txt in p.communicate()] + finally: + if clean and os.path.isdir(build_dir): + shutil.rmtree(build_dir) + build_dir = None + info = {"exit_status": exit_status, "build_dir": build_dir} + return (stdout, stderr), info diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/runners.py b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/runners.py new file mode 100644 index 0000000000000000000000000000000000000000..1f37d6cf8ac47807da7f3f00dfc5cd847c03fa8d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/runners.py @@ -0,0 +1,301 @@ +from __future__ import annotations +from typing import Callable, Optional + +from collections import OrderedDict +import os +import re +import subprocess +import warnings + +from .util import ( + find_binary_of_command, unique_list, CompileError +) + + +class CompilerRunner: + """ CompilerRunner base class. + + Parameters + ========== + + sources : list of str + Paths to sources. + out : str + flags : iterable of str + Compiler flags. + run_linker : bool + compiler_name_exe : (str, str) tuple + Tuple of compiler name & command to call. + cwd : str + Path of root of relative paths. + include_dirs : list of str + Include directories. + libraries : list of str + Libraries to link against. + library_dirs : list of str + Paths to search for shared libraries. + std : str + Standard string, e.g. ``'c++11'``, ``'c99'``, ``'f2003'``. + define: iterable of strings + macros to define + undef : iterable of strings + macros to undefine + preferred_vendor : string + name of preferred vendor e.g. 'gnu' or 'intel' + + Methods + ======= + + run(): + Invoke compilation as a subprocess. + + """ + + environ_key_compiler: str # e.g. 'CC', 'CXX', ... + environ_key_flags: str # e.g. 'CFLAGS', 'CXXFLAGS', ... + environ_key_ldflags: str = "LDFLAGS" # typically 'LDFLAGS' + + # Subclass to vendor/binary dict + compiler_dict: dict[str, str] + + # Standards should be a tuple of supported standards + # (first one will be the default) + standards: tuple[None | str, ...] + + # Subclass to dict of binary/formater-callback + std_formater: dict[str, Callable[[Optional[str]], str]] + + # subclass to be e.g. {'gcc': 'gnu', ...} + compiler_name_vendor_mapping: dict[str, str] + + def __init__(self, sources, out, flags=None, run_linker=True, compiler=None, cwd='.', + include_dirs=None, libraries=None, library_dirs=None, std=None, define=None, + undef=None, strict_aliasing=None, preferred_vendor=None, linkline=None, **kwargs): + if isinstance(sources, str): + raise ValueError("Expected argument sources to be a list of strings.") + self.sources = list(sources) + self.out = out + self.flags = flags or [] + if os.environ.get(self.environ_key_flags): + self.flags += os.environ[self.environ_key_flags].split() + self.cwd = cwd + if compiler: + self.compiler_name, self.compiler_binary = compiler + elif os.environ.get(self.environ_key_compiler): + self.compiler_binary = os.environ[self.environ_key_compiler] + for k, v in self.compiler_dict.items(): + if k in self.compiler_binary: + self.compiler_vendor = k + self.compiler_name = v + break + else: + self.compiler_vendor, self.compiler_name = list(self.compiler_dict.items())[0] + warnings.warn("failed to determine what kind of compiler %s is, assuming %s" % + (self.compiler_binary, self.compiler_name)) + else: + # Find a compiler + if preferred_vendor is None: + preferred_vendor = os.environ.get('SYMPY_COMPILER_VENDOR', None) + self.compiler_name, self.compiler_binary, self.compiler_vendor = self.find_compiler(preferred_vendor) + if self.compiler_binary is None: + raise ValueError("No compiler found (searched: {})".format(', '.join(self.compiler_dict.values()))) + self.define = define or [] + self.undef = undef or [] + self.include_dirs = include_dirs or [] + self.libraries = libraries or [] + self.library_dirs = library_dirs or [] + self.std = std or self.standards[0] + self.run_linker = run_linker + if self.run_linker: + # both gnu and intel compilers use '-c' for disabling linker + self.flags = list(filter(lambda x: x != '-c', self.flags)) + else: + if '-c' not in self.flags: + self.flags.append('-c') + + if self.std: + self.flags.append(self.std_formater[ + self.compiler_name](self.std)) + + self.linkline = (linkline or []) + [lf for lf in map( + str.strip, os.environ.get(self.environ_key_ldflags, "").split() + ) if lf != ""] + + if strict_aliasing is not None: + nsa_re = re.compile("no-strict-aliasing$") + sa_re = re.compile("strict-aliasing$") + if strict_aliasing is True: + if any(map(nsa_re.match, flags)): + raise CompileError("Strict aliasing cannot be both enforced and disabled") + elif any(map(sa_re.match, flags)): + pass # already enforced + else: + flags.append('-fstrict-aliasing') + elif strict_aliasing is False: + if any(map(nsa_re.match, flags)): + pass # already disabled + else: + if any(map(sa_re.match, flags)): + raise CompileError("Strict aliasing cannot be both enforced and disabled") + else: + flags.append('-fno-strict-aliasing') + else: + msg = "Expected argument strict_aliasing to be True/False, got {}" + raise ValueError(msg.format(strict_aliasing)) + + @classmethod + def find_compiler(cls, preferred_vendor=None): + """ Identify a suitable C/fortran/other compiler. """ + candidates = list(cls.compiler_dict.keys()) + if preferred_vendor: + if preferred_vendor in candidates: + candidates = [preferred_vendor]+candidates + else: + raise ValueError("Unknown vendor {}".format(preferred_vendor)) + name, path = find_binary_of_command([cls.compiler_dict[x] for x in candidates]) + return name, path, cls.compiler_name_vendor_mapping[name] + + def cmd(self): + """ List of arguments (str) to be passed to e.g. ``subprocess.Popen``. """ + cmd = ( + [self.compiler_binary] + + self.flags + + ['-U'+x for x in self.undef] + + ['-D'+x for x in self.define] + + ['-I'+x for x in self.include_dirs] + + self.sources + ) + if self.run_linker: + cmd += (['-L'+x for x in self.library_dirs] + + ['-l'+x for x in self.libraries] + + self.linkline) + counted = [] + for envvar in re.findall(r'\$\{(\w+)\}', ' '.join(cmd)): + if os.getenv(envvar) is None: + if envvar not in counted: + counted.append(envvar) + msg = "Environment variable '{}' undefined.".format(envvar) + raise CompileError(msg) + return cmd + + def run(self): + self.flags = unique_list(self.flags) + + # Append output flag and name to tail of flags + self.flags.extend(['-o', self.out]) + env = os.environ.copy() + env['PWD'] = self.cwd + + # NOTE: intel compilers seems to need shell=True + p = subprocess.Popen(' '.join(self.cmd()), + shell=True, + cwd=self.cwd, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + env=env) + comm = p.communicate() + try: + self.cmd_outerr = comm[0].decode('utf-8') + except UnicodeDecodeError: + self.cmd_outerr = comm[0].decode('iso-8859-1') # win32 + self.cmd_returncode = p.returncode + + # Error handling + if self.cmd_returncode != 0: + msg = "Error executing '{}' in {} (exited status {}):\n {}\n".format( + ' '.join(self.cmd()), self.cwd, str(self.cmd_returncode), self.cmd_outerr + ) + raise CompileError(msg) + + return self.cmd_outerr, self.cmd_returncode + + +class CCompilerRunner(CompilerRunner): + + environ_key_compiler = 'CC' + environ_key_flags = 'CFLAGS' + + compiler_dict = OrderedDict([ + ('gnu', 'gcc'), + ('intel', 'icc'), + ('llvm', 'clang'), + ]) + + standards = ('c89', 'c90', 'c99', 'c11') # First is default + + std_formater = { + 'gcc': '-std={}'.format, + 'icc': '-std={}'.format, + 'clang': '-std={}'.format, + } + + compiler_name_vendor_mapping = { + 'gcc': 'gnu', + 'icc': 'intel', + 'clang': 'llvm' + } + + +def _mk_flag_filter(cmplr_name): # helper for class initialization + not_welcome = {'g++': ("Wimplicit-interface",)} # "Wstrict-prototypes",)} + if cmplr_name in not_welcome: + def fltr(x): + for nw in not_welcome[cmplr_name]: + if nw in x: + return False + return True + else: + def fltr(x): + return True + return fltr + + +class CppCompilerRunner(CompilerRunner): + + environ_key_compiler = 'CXX' + environ_key_flags = 'CXXFLAGS' + + compiler_dict = OrderedDict([ + ('gnu', 'g++'), + ('intel', 'icpc'), + ('llvm', 'clang++'), + ]) + + # First is the default, c++0x == c++11 + standards = ('c++98', 'c++0x') + + std_formater = { + 'g++': '-std={}'.format, + 'icpc': '-std={}'.format, + 'clang++': '-std={}'.format, + } + + compiler_name_vendor_mapping = { + 'g++': 'gnu', + 'icpc': 'intel', + 'clang++': 'llvm' + } + + +class FortranCompilerRunner(CompilerRunner): + + environ_key_compiler = 'FC' + environ_key_flags = 'FFLAGS' + + standards = (None, 'f77', 'f95', 'f2003', 'f2008') + + std_formater = { + 'gfortran': lambda x: '-std=gnu' if x is None else '-std=legacy' if x == 'f77' else '-std={}'.format(x), + 'ifort': lambda x: '-stand f08' if x is None else '-stand f{}'.format(x[-2:]), # f2008 => f08 + } + + compiler_dict = OrderedDict([ + ('gnu', 'gfortran'), + ('intel', 'ifort'), + ]) + + compiler_name_vendor_mapping = { + 'gfortran': 'gnu', + 'ifort': 'intel', + } diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/tests/__init__.py b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/tests/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/tests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9afb2067ee0a1222ed2f7b5172b7a25b37433eae Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/tests/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/tests/__pycache__/test_compilation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/tests/__pycache__/test_compilation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4063cd300fdee537a094984d5ce2b1d6928f3de Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/tests/__pycache__/test_compilation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/tests/test_compilation.py b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/tests/test_compilation.py new file mode 100644 index 0000000000000000000000000000000000000000..ff7cf86644a9645665e62b49cfc4e7ea73b2c1ab --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/_compilation/tests/test_compilation.py @@ -0,0 +1,104 @@ +import shutil +import os +import subprocess +import tempfile +from sympy.external import import_module +from sympy.testing.pytest import skip, skip_under_pyodide + +from sympy.utilities._compilation.compilation import compile_link_import_py_ext, compile_link_import_strings, compile_sources, get_abspath + +numpy = import_module('numpy') +cython = import_module('cython') + +_sources1 = [ + ('sigmoid.c', r""" +#include + +void sigmoid(int n, const double * const restrict in, + double * const restrict out, double lim){ + for (int i=0; i 0: + if not os.path.exists(parent): + make_dirs(parent) + + if not os.path.exists(path): + os.mkdir(path, 0o777) + else: + assert os.path.isdir(path) + +def missing_or_other_newer(path, other_path, cwd=None): + """ + Investigate if path is non-existent or older than provided reference + path. + + Parameters + ========== + path: string + path to path which might be missing or too old + other_path: string + reference path + cwd: string + working directory (root of relative paths) + + Returns + ======= + True if path is older or missing. + """ + cwd = cwd or '.' + path = get_abspath(path, cwd=cwd) + other_path = get_abspath(other_path, cwd=cwd) + if not os.path.exists(path): + return True + if os.path.getmtime(other_path) - 1e-6 >= os.path.getmtime(path): + # 1e-6 is needed because http://stackoverflow.com/questions/17086426/ + return True + return False + +def copy(src, dst, only_update=False, copystat=True, cwd=None, + dest_is_dir=False, create_dest_dirs=False): + """ Variation of ``shutil.copy`` with extra options. + + Parameters + ========== + + src : str + Path to source file. + dst : str + Path to destination. + only_update : bool + Only copy if source is newer than destination + (returns None if it was newer), default: ``False``. + copystat : bool + See ``shutil.copystat``. default: ``True``. + cwd : str + Path to working directory (root of relative paths). + dest_is_dir : bool + Ensures that dst is treated as a directory. default: ``False`` + create_dest_dirs : bool + Creates directories if needed. + + Returns + ======= + + Path to the copied file. + + """ + if cwd: # Handle working directory + if not os.path.isabs(src): + src = os.path.join(cwd, src) + if not os.path.isabs(dst): + dst = os.path.join(cwd, dst) + + if not os.path.exists(src): # Make sure source file exists + raise FileNotFoundError("Source: `{}` does not exist".format(src)) + + # We accept both (re)naming destination file _or_ + # passing a (possible non-existent) destination directory + if dest_is_dir: + if not dst[-1] == '/': + dst = dst+'/' + else: + if os.path.exists(dst) and os.path.isdir(dst): + dest_is_dir = True + + if dest_is_dir: + dest_dir = dst + dest_fname = os.path.basename(src) + dst = os.path.join(dest_dir, dest_fname) + else: + dest_dir = os.path.dirname(dst) + + if not os.path.exists(dest_dir): + if create_dest_dirs: + make_dirs(dest_dir) + else: + raise FileNotFoundError("You must create directory first.") + + if only_update: + if not missing_or_other_newer(dst, src): + return + + if os.path.islink(dst): + dst = os.path.abspath(os.path.realpath(dst), cwd=cwd) + + shutil.copy(src, dst) + if copystat: + shutil.copystat(src, dst) + + return dst + +Glob = namedtuple('Glob', 'pathname') +ArbitraryDepthGlob = namedtuple('ArbitraryDepthGlob', 'filename') + +def glob_at_depth(filename_glob, cwd=None): + if cwd is not None: + cwd = '.' + globbed = [] + for root, dirs, filenames in os.walk(cwd): + for fn in filenames: + # This is not tested: + if fnmatch.fnmatch(fn, filename_glob): + globbed.append(os.path.join(root, fn)) + return globbed + +def sha256_of_file(path, nblocks=128): + """ Computes the SHA256 hash of a file. + + Parameters + ========== + + path : string + Path to file to compute hash of. + nblocks : int + Number of blocks to read per iteration. + + Returns + ======= + + hashlib sha256 hash object. Use ``.digest()`` or ``.hexdigest()`` + on returned object to get binary or hex encoded string. + """ + sh = sha256() + with open(path, 'rb') as f: + for chunk in iter(lambda: f.read(nblocks*sh.block_size), b''): + sh.update(chunk) + return sh + + +def sha256_of_string(string): + """ Computes the SHA256 hash of a string. """ + sh = sha256() + sh.update(string) + return sh + + +def pyx_is_cplus(path): + """ + Inspect a Cython source file (.pyx) and look for comment line like: + + # distutils: language = c++ + + Returns True if such a file is present in the file, else False. + """ + with open(path) as fh: + for line in fh: + if line.startswith('#') and '=' in line: + splitted = line.split('=') + if len(splitted) != 2: + continue + lhs, rhs = splitted + if lhs.strip().split()[-1].lower() == 'language' and \ + rhs.strip().split()[0].lower() == 'c++': + return True + return False + +def import_module_from_file(filename, only_if_newer_than=None): + """ Imports Python extension (from shared object file) + + Provide a list of paths in `only_if_newer_than` to check + timestamps of dependencies. import_ raises an ImportError + if any is newer. + + Word of warning: The OS may cache shared objects which makes + reimporting same path of an shared object file very problematic. + + It will not detect the new time stamp, nor new checksum, but will + instead silently use old module. Use unique names for this reason. + + Parameters + ========== + + filename : str + Path to shared object. + only_if_newer_than : iterable of strings + Paths to dependencies of the shared object. + + Raises + ====== + + ``ImportError`` if any of the files specified in ``only_if_newer_than`` are newer + than the file given by filename. + """ + path, name = os.path.split(filename) + name, ext = os.path.splitext(name) + name = name.split('.')[0] + if sys.version_info[0] == 2: + from imp import find_module, load_module + fobj, filename, data = find_module(name, [path]) + if only_if_newer_than: + for dep in only_if_newer_than: + if os.path.getmtime(filename) < os.path.getmtime(dep): + raise ImportError("{} is newer than {}".format(dep, filename)) + mod = load_module(name, fobj, filename, data) + else: + import importlib.util + spec = importlib.util.spec_from_file_location(name, filename) + if spec is None: + raise ImportError("Failed to import: '%s'" % filename) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def find_binary_of_command(candidates): + """ Finds binary first matching name among candidates. + + Calls ``which`` from shutils for provided candidates and returns + first hit. + + Parameters + ========== + + candidates : iterable of str + Names of candidate commands + + Raises + ====== + + CompilerNotFoundError if no candidates match. + """ + from shutil import which + for c in candidates: + binary_path = which(c) + if c and binary_path: + return c, binary_path + + raise CompilerNotFoundError('No binary located for candidates: {}'.format(candidates)) + + +def unique_list(l): + """ Uniquify a list (skip duplicate items). """ + result = [] + for x in l: + if x not in result: + result.append(x) + return result diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/autowrap.py b/.venv/lib/python3.12/site-packages/sympy/utilities/autowrap.py new file mode 100644 index 0000000000000000000000000000000000000000..b6c33b2f0f72f89b5680f910929618a821e924c3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/autowrap.py @@ -0,0 +1,1178 @@ +"""Module for compiling codegen output, and wrap the binary for use in +python. + +.. note:: To use the autowrap module it must first be imported + + >>> from sympy.utilities.autowrap import autowrap + +This module provides a common interface for different external backends, such +as f2py, fwrap, Cython, SWIG(?) etc. (Currently only f2py and Cython are +implemented) The goal is to provide access to compiled binaries of acceptable +performance with a one-button user interface, e.g., + + >>> from sympy.abc import x,y + >>> expr = (x - y)**25 + >>> flat = expr.expand() + >>> binary_callable = autowrap(flat) + >>> binary_callable(2, 3) + -1.0 + +Although a SymPy user might primarily be interested in working with +mathematical expressions and not in the details of wrapping tools +needed to evaluate such expressions efficiently in numerical form, +the user cannot do so without some understanding of the +limits in the target language. For example, the expanded expression +contains large coefficients which result in loss of precision when +computing the expression: + + >>> binary_callable(3, 2) + 0.0 + >>> binary_callable(4, 5), binary_callable(5, 4) + (-22925376.0, 25165824.0) + +Wrapping the unexpanded expression gives the expected behavior: + + >>> e = autowrap(expr) + >>> e(4, 5), e(5, 4) + (-1.0, 1.0) + +The callable returned from autowrap() is a binary Python function, not a +SymPy object. If it is desired to use the compiled function in symbolic +expressions, it is better to use binary_function() which returns a SymPy +Function object. The binary callable is attached as the _imp_ attribute and +invoked when a numerical evaluation is requested with evalf(), or with +lambdify(). + + >>> from sympy.utilities.autowrap import binary_function + >>> f = binary_function('f', expr) + >>> 2*f(x, y) + y + y + 2*f(x, y) + >>> (2*f(x, y) + y).evalf(2, subs={x: 1, y:2}) + 0.e-110 + +When is this useful? + + 1) For computations on large arrays, Python iterations may be too slow, + and depending on the mathematical expression, it may be difficult to + exploit the advanced index operations provided by NumPy. + + 2) For *really* long expressions that will be called repeatedly, the + compiled binary should be significantly faster than SymPy's .evalf() + + 3) If you are generating code with the codegen utility in order to use + it in another project, the automatic Python wrappers let you test the + binaries immediately from within SymPy. + + 4) To create customized ufuncs for use with numpy arrays. + See *ufuncify*. + +When is this module NOT the best approach? + + 1) If you are really concerned about speed or memory optimizations, + you will probably get better results by working directly with the + wrapper tools and the low level code. However, the files generated + by this utility may provide a useful starting point and reference + code. Temporary files will be left intact if you supply the keyword + tempdir="path/to/files/". + + 2) If the array computation can be handled easily by numpy, and you + do not need the binaries for another project. + +""" + +import sys +import os +import shutil +import tempfile +from pathlib import Path +from subprocess import STDOUT, CalledProcessError, check_output +from string import Template +from warnings import warn + +from sympy.core.cache import cacheit +from sympy.core.function import Lambda +from sympy.core.relational import Eq +from sympy.core.symbol import Dummy, Symbol +from sympy.tensor.indexed import Idx, IndexedBase +from sympy.utilities.codegen import (make_routine, get_code_generator, + OutputArgument, InOutArgument, + InputArgument, CodeGenArgumentListError, + Result, ResultBase, C99CodeGen) +from sympy.utilities.iterables import iterable +from sympy.utilities.lambdify import implemented_function +from sympy.utilities.decorator import doctest_depends_on + +_doctest_depends_on = {'exe': ('f2py', 'gfortran', 'gcc'), + 'modules': ('numpy',)} + + +class CodeWrapError(Exception): + pass + + +class CodeWrapper: + """Base Class for code wrappers""" + _filename = "wrapped_code" + _module_basename = "wrapper_module" + _module_counter = 0 + + @property + def filename(self): + return "%s_%s" % (self._filename, CodeWrapper._module_counter) + + @property + def module_name(self): + return "%s_%s" % (self._module_basename, CodeWrapper._module_counter) + + def __init__(self, generator, filepath=None, flags=[], verbose=False): + """ + generator -- the code generator to use + """ + self.generator = generator + self.filepath = filepath + self.flags = flags + self.quiet = not verbose + + @property + def include_header(self): + return bool(self.filepath) + + @property + def include_empty(self): + return bool(self.filepath) + + def _generate_code(self, main_routine, routines): + routines.append(main_routine) + self.generator.write( + routines, self.filename, True, self.include_header, + self.include_empty) + + def wrap_code(self, routine, helpers=None): + helpers = helpers or [] + if self.filepath: + workdir = os.path.abspath(self.filepath) + else: + workdir = tempfile.mkdtemp("_sympy_compile") + if not os.access(workdir, os.F_OK): + os.mkdir(workdir) + oldwork = os.getcwd() + os.chdir(workdir) + try: + sys.path.append(workdir) + self._generate_code(routine, helpers) + self._prepare_files(routine) + self._process_files(routine) + mod = __import__(self.module_name) + finally: + sys.path.remove(workdir) + CodeWrapper._module_counter += 1 + os.chdir(oldwork) + if not self.filepath: + try: + shutil.rmtree(workdir) + except OSError: + # Could be some issues on Windows + pass + + return self._get_wrapped_function(mod, routine.name) + + def _process_files(self, routine): + command = self.command + command.extend(self.flags) + try: + retoutput = check_output(command, stderr=STDOUT) + except CalledProcessError as e: + raise CodeWrapError( + "Error while executing command: %s. Command output is:\n%s" % ( + " ".join(command), e.output.decode('utf-8'))) + if not self.quiet: + print(retoutput) + + +class DummyWrapper(CodeWrapper): + """Class used for testing independent of backends """ + + template = """# dummy module for testing of SymPy +def %(name)s(): + return "%(expr)s" +%(name)s.args = "%(args)s" +%(name)s.returns = "%(retvals)s" +""" + + def _prepare_files(self, routine): + return + + def _generate_code(self, routine, helpers): + with open('%s.py' % self.module_name, 'w') as f: + printed = ", ".join( + [str(res.expr) for res in routine.result_variables]) + # convert OutputArguments to return value like f2py + args = filter(lambda x: not isinstance( + x, OutputArgument), routine.arguments) + retvals = [] + for val in routine.result_variables: + if isinstance(val, Result): + retvals.append('nameless') + else: + retvals.append(val.result_var) + + print(DummyWrapper.template % { + 'name': routine.name, + 'expr': printed, + 'args': ", ".join([str(a.name) for a in args]), + 'retvals': ", ".join([str(val) for val in retvals]) + }, end="", file=f) + + def _process_files(self, routine): + return + + @classmethod + def _get_wrapped_function(cls, mod, name): + return getattr(mod, name) + + +class CythonCodeWrapper(CodeWrapper): + """Wrapper that uses Cython""" + + setup_template = """\ +from setuptools import setup +from setuptools import Extension +from Cython.Build import cythonize +cy_opts = {cythonize_options} +{np_import} +ext_mods = [Extension( + {ext_args}, + include_dirs={include_dirs}, + library_dirs={library_dirs}, + libraries={libraries}, + extra_compile_args={extra_compile_args}, + extra_link_args={extra_link_args} +)] +setup(ext_modules=cythonize(ext_mods, **cy_opts)) +""" + + _cythonize_options = {'compiler_directives':{'language_level' : "3"}} + + pyx_imports = ( + "import numpy as np\n" + "cimport numpy as np\n\n") + + pyx_header = ( + "cdef extern from '{header_file}.h':\n" + " {prototype}\n\n") + + pyx_func = ( + "def {name}_c({arg_string}):\n" + "\n" + "{declarations}" + "{body}") + + std_compile_flag = '-std=c99' + + def __init__(self, *args, **kwargs): + """Instantiates a Cython code wrapper. + + The following optional parameters get passed to ``setuptools.Extension`` + for building the Python extension module. Read its documentation to + learn more. + + Parameters + ========== + include_dirs : [list of strings] + A list of directories to search for C/C++ header files (in Unix + form for portability). + library_dirs : [list of strings] + A list of directories to search for C/C++ libraries at link time. + libraries : [list of strings] + A list of library names (not filenames or paths) to link against. + extra_compile_args : [list of strings] + 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. Note that the attribute ``std_compile_flag`` will be + appended to this list. + extra_link_args : [list of strings] + 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'. + cythonize_options : [dictionary] + Keyword arguments passed on to cythonize. + + """ + + self._include_dirs = kwargs.pop('include_dirs', []) + self._library_dirs = kwargs.pop('library_dirs', []) + self._libraries = kwargs.pop('libraries', []) + self._extra_compile_args = kwargs.pop('extra_compile_args', []) + self._extra_compile_args.append(self.std_compile_flag) + self._extra_link_args = kwargs.pop('extra_link_args', []) + self._cythonize_options = kwargs.pop('cythonize_options', self._cythonize_options) + + self._need_numpy = False + + super().__init__(*args, **kwargs) + + @property + def command(self): + command = [sys.executable, "setup.py", "build_ext", "--inplace"] + return command + + def _prepare_files(self, routine, build_dir=os.curdir): + # NOTE : build_dir is used for testing purposes. + pyxfilename = self.module_name + '.pyx' + codefilename = "%s.%s" % (self.filename, self.generator.code_extension) + + # pyx + with open(os.path.join(build_dir, pyxfilename), 'w') as f: + self.dump_pyx([routine], f, self.filename) + + # setup.py + ext_args = [repr(self.module_name), repr([pyxfilename, codefilename])] + if self._need_numpy: + np_import = 'import numpy as np\n' + self._include_dirs.append('np.get_include()') + else: + np_import = '' + + includes = str(self._include_dirs).replace("'np.get_include()'", + 'np.get_include()') + code = self.setup_template.format( + ext_args=", ".join(ext_args), + np_import=np_import, + include_dirs=includes, + library_dirs=self._library_dirs, + libraries=self._libraries, + extra_compile_args=self._extra_compile_args, + extra_link_args=self._extra_link_args, + cythonize_options=self._cythonize_options) + Path(os.path.join(build_dir, 'setup.py')).write_text(code) + + @classmethod + def _get_wrapped_function(cls, mod, name): + return getattr(mod, name + '_c') + + def dump_pyx(self, routines, f, prefix): + """Write a Cython file with Python wrappers + + This file contains all the definitions of the routines in c code and + refers to the header file. + + Arguments + --------- + routines + List of Routine instances + f + File-like object to write the file to + prefix + The filename prefix, used to refer to the proper header file. + Only the basename of the prefix is used. + """ + headers = [] + functions = [] + for routine in routines: + prototype = self.generator.get_prototype(routine) + + # C Function Header Import + headers.append(self.pyx_header.format(header_file=prefix, + prototype=prototype)) + + # Partition the C function arguments into categories + py_rets, py_args, py_loc, py_inf = self._partition_args(routine.arguments) + + # Function prototype + name = routine.name + arg_string = ", ".join(self._prototype_arg(arg) for arg in py_args) + + # Local Declarations + local_decs = [] + for arg, val in py_inf.items(): + proto = self._prototype_arg(arg) + mat, ind = [self._string_var(v) for v in val] + local_decs.append(" cdef {} = {}.shape[{}]".format(proto, mat, ind)) + local_decs.extend([" cdef {}".format(self._declare_arg(a)) for a in py_loc]) + declarations = "\n".join(local_decs) + if declarations: + declarations = declarations + "\n" + + # Function Body + args_c = ", ".join([self._call_arg(a) for a in routine.arguments]) + rets = ", ".join([self._string_var(r.name) for r in py_rets]) + if routine.results: + body = ' return %s(%s)' % (routine.name, args_c) + if rets: + body = body + ', ' + rets + else: + body = ' %s(%s)\n' % (routine.name, args_c) + body = body + ' return ' + rets + + functions.append(self.pyx_func.format(name=name, arg_string=arg_string, + declarations=declarations, body=body)) + + # Write text to file + if self._need_numpy: + # Only import numpy if required + f.write(self.pyx_imports) + f.write('\n'.join(headers)) + f.write('\n'.join(functions)) + + def _partition_args(self, args): + """Group function arguments into categories.""" + py_args = [] + py_returns = [] + py_locals = [] + py_inferred = {} + for arg in args: + if isinstance(arg, OutputArgument): + py_returns.append(arg) + py_locals.append(arg) + elif isinstance(arg, InOutArgument): + py_returns.append(arg) + py_args.append(arg) + else: + py_args.append(arg) + # Find arguments that are array dimensions. These can be inferred + # locally in the Cython code. + if isinstance(arg, (InputArgument, InOutArgument)) and arg.dimensions: + dims = [d[1] + 1 for d in arg.dimensions] + sym_dims = [(i, d) for (i, d) in enumerate(dims) if + isinstance(d, Symbol)] + for (i, d) in sym_dims: + py_inferred[d] = (arg.name, i) + for arg in args: + if arg.name in py_inferred: + py_inferred[arg] = py_inferred.pop(arg.name) + # Filter inferred arguments from py_args + py_args = [a for a in py_args if a not in py_inferred] + return py_returns, py_args, py_locals, py_inferred + + def _prototype_arg(self, arg): + mat_dec = "np.ndarray[{mtype}, ndim={ndim}] {name}" + np_types = {'double': 'np.double_t', + 'int': 'np.int_t'} + t = arg.get_datatype('c') + if arg.dimensions: + self._need_numpy = True + ndim = len(arg.dimensions) + mtype = np_types[t] + return mat_dec.format(mtype=mtype, ndim=ndim, name=self._string_var(arg.name)) + else: + return "%s %s" % (t, self._string_var(arg.name)) + + def _declare_arg(self, arg): + proto = self._prototype_arg(arg) + if arg.dimensions: + shape = '(' + ','.join(self._string_var(i[1] + 1) for i in arg.dimensions) + ')' + return proto + " = np.empty({shape})".format(shape=shape) + else: + return proto + " = 0" + + def _call_arg(self, arg): + if arg.dimensions: + t = arg.get_datatype('c') + return "<{}*> {}.data".format(t, self._string_var(arg.name)) + elif isinstance(arg, ResultBase): + return "&{}".format(self._string_var(arg.name)) + else: + return self._string_var(arg.name) + + def _string_var(self, var): + printer = self.generator.printer.doprint + return printer(var) + + +class F2PyCodeWrapper(CodeWrapper): + """Wrapper that uses f2py""" + + def __init__(self, *args, **kwargs): + + ext_keys = ['include_dirs', 'library_dirs', 'libraries', + 'extra_compile_args', 'extra_link_args'] + msg = ('The compilation option kwarg {} is not supported with the f2py ' + 'backend.') + + for k in ext_keys: + if k in kwargs.keys(): + warn(msg.format(k)) + kwargs.pop(k, None) + + super().__init__(*args, **kwargs) + + @property + def command(self): + filename = self.filename + '.' + self.generator.code_extension + args = ['-c', '-m', self.module_name, filename] + command = [sys.executable, "-c", "import numpy.f2py as f2py2e;f2py2e.main()"]+args + return command + + def _prepare_files(self, routine): + pass + + @classmethod + def _get_wrapped_function(cls, mod, name): + return getattr(mod, name) + + +# Here we define a lookup of backends -> tuples of languages. For now, each +# tuple is of length 1, but if a backend supports more than one language, +# the most preferable language is listed first. +_lang_lookup = {'CYTHON': ('C99', 'C89', 'C'), + 'F2PY': ('F95',), + 'NUMPY': ('C99', 'C89', 'C'), + 'DUMMY': ('F95',)} # Dummy here just for testing + + +def _infer_language(backend): + """For a given backend, return the top choice of language""" + langs = _lang_lookup.get(backend.upper(), False) + if not langs: + raise ValueError("Unrecognized backend: " + backend) + return langs[0] + + +def _validate_backend_language(backend, language): + """Throws error if backend and language are incompatible""" + langs = _lang_lookup.get(backend.upper(), False) + if not langs: + raise ValueError("Unrecognized backend: " + backend) + if language.upper() not in langs: + raise ValueError(("Backend {} and language {} are " + "incompatible").format(backend, language)) + + +@cacheit +@doctest_depends_on(exe=('f2py', 'gfortran'), modules=('numpy',)) +def autowrap(expr, language=None, backend='f2py', tempdir=None, args=None, + flags=None, verbose=False, helpers=None, code_gen=None, **kwargs): + """Generates Python callable binaries based on the math expression. + + Parameters + ========== + + expr + The SymPy expression that should be wrapped as a binary routine. + language : string, optional + If supplied, (options: 'C' or 'F95'), specifies the language of the + generated code. If ``None`` [default], the language is inferred based + upon the specified backend. + backend : string, optional + Backend used to wrap the generated code. Either 'f2py' [default], + or 'cython'. + tempdir : string, optional + Path to directory for temporary files. If this argument is supplied, + the generated code and the wrapper input files are left intact in the + specified path. + args : iterable, optional + An ordered iterable of symbols. Specifies the argument sequence for the + function. + flags : iterable, optional + Additional option flags that will be passed to the backend. + verbose : bool, optional + If True, autowrap will not mute the command line backends. This can be + helpful for debugging. + helpers : 3-tuple or iterable of 3-tuples, optional + Used to define auxiliary functions needed for the main expression. + Each tuple should be of the form (name, expr, args) where: + + - name : str, the function name + - expr : sympy expression, the function + - args : iterable, the function arguments (can be any iterable of symbols) + + code_gen : CodeGen instance + An instance of a CodeGen subclass. Overrides ``language``. + include_dirs : [string] + A list of directories to search for C/C++ header files (in Unix form + for portability). + library_dirs : [string] + A list of directories to search for C/C++ libraries at link time. + libraries : [string] + A list of library names (not filenames or paths) to link against. + extra_compile_args : [string] + 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. + extra_link_args : [string] + 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'. + + Examples + ======== + + Basic usage: + + >>> from sympy.abc import x, y, z + >>> from sympy.utilities.autowrap import autowrap + >>> expr = ((x - y + z)**(13)).expand() + >>> binary_func = autowrap(expr) + >>> binary_func(1, 4, 2) + -1.0 + + Using helper functions: + + >>> from sympy.abc import x, t + >>> from sympy import Function + >>> helper_func = Function('helper_func') # Define symbolic function + >>> expr = 3*x + helper_func(t) # Main expression using helper function + >>> # Define helper_func(x) = 4*x using f2py backend + >>> binary_func = autowrap(expr, args=[x, t], + ... helpers=('helper_func', 4*x, [x])) + >>> binary_func(2, 5) # 3*2 + helper_func(5) = 6 + 20 + 26.0 + >>> # Same example using cython backend + >>> binary_func = autowrap(expr, args=[x, t], backend='cython', + ... helpers=[('helper_func', 4*x, [x])]) + >>> binary_func(2, 5) # 3*2 + helper_func(5) = 6 + 20 + 26.0 + + Type handling example: + + >>> import numpy as np + >>> expr = x + y + >>> f_cython = autowrap(expr, backend='cython') + >>> f_cython(1, 2) # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + TypeError: Argument '_x' has incorrect type (expected numpy.ndarray, got int) + >>> f_cython(np.array([1.0]), np.array([2.0])) + array([ 3.]) + + """ + if language: + if not isinstance(language, type): + _validate_backend_language(backend, language) + else: + language = _infer_language(backend) + + # two cases 1) helpers is an iterable of 3-tuples and 2) helpers is a + # 3-tuple + if iterable(helpers) and len(helpers) != 0 and iterable(helpers[0]): + helpers = helpers if helpers else () + else: + helpers = [helpers] if helpers else () + args = list(args) if iterable(args, exclude=set) else args + + if code_gen is None: + code_gen = get_code_generator(language, "autowrap") + + CodeWrapperClass = { + 'F2PY': F2PyCodeWrapper, + 'CYTHON': CythonCodeWrapper, + 'DUMMY': DummyWrapper + }[backend.upper()] + code_wrapper = CodeWrapperClass(code_gen, tempdir, flags if flags else (), + verbose, **kwargs) + + helps = [] + for name_h, expr_h, args_h in helpers: + helps.append(code_gen.routine(name_h, expr_h, args_h)) + + for name_h, expr_h, args_h in helpers: + if expr.has(expr_h): + name_h = binary_function(name_h, expr_h, backend='dummy') + expr = expr.subs(expr_h, name_h(*args_h)) + try: + routine = code_gen.routine('autofunc', expr, args) + except CodeGenArgumentListError as e: + # if all missing arguments are for pure output, we simply attach them + # at the end and try again, because the wrappers will silently convert + # them to return values anyway. + new_args = [] + for missing in e.missing_args: + if not isinstance(missing, OutputArgument): + raise + new_args.append(missing.name) + routine = code_gen.routine('autofunc', expr, args + new_args) + + return code_wrapper.wrap_code(routine, helpers=helps) + + +@doctest_depends_on(exe=('f2py', 'gfortran'), modules=('numpy',)) +def binary_function(symfunc, expr, **kwargs): + """Returns a SymPy function with expr as binary implementation + + This is a convenience function that automates the steps needed to + autowrap the SymPy expression and attaching it to a Function object + with implemented_function(). + + Parameters + ========== + + symfunc : SymPy Function + The function to bind the callable to. + expr : SymPy Expression + The expression used to generate the function. + kwargs : dict + Any kwargs accepted by autowrap. + + Examples + ======== + + >>> from sympy.abc import x, y + >>> from sympy.utilities.autowrap import binary_function + >>> expr = ((x - y)**(25)).expand() + >>> f = binary_function('f', expr) + >>> type(f) + + >>> 2*f(x, y) + 2*f(x, y) + >>> f(x, y).evalf(2, subs={x: 1, y: 2}) + -1.0 + + """ + binary = autowrap(expr, **kwargs) + return implemented_function(symfunc, binary) + +################################################################# +# UFUNCIFY # +################################################################# + +_ufunc_top = Template("""\ +#include "Python.h" +#include "math.h" +#include "numpy/ndarraytypes.h" +#include "numpy/ufuncobject.h" +#include "numpy/halffloat.h" +#include ${include_file} + +static PyMethodDef ${module}Methods[] = { + {NULL, NULL, 0, NULL} +};""") + +_ufunc_outcalls = Template("*((double *)out${outnum}) = ${funcname}(${call_args});") + +_ufunc_body = Template("""\ +#ifdef NPY_1_19_API_VERSION +static void ${funcname}_ufunc(char **args, const npy_intp *dimensions, const npy_intp* steps, void* data) +#else +static void ${funcname}_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data) +#endif +{ + npy_intp i; + npy_intp n = dimensions[0]; + ${declare_args} + ${declare_steps} + for (i = 0; i < n; i++) { + ${outcalls} + ${step_increments} + } +} +PyUFuncGenericFunction ${funcname}_funcs[1] = {&${funcname}_ufunc}; +static char ${funcname}_types[${n_types}] = ${types} +static void *${funcname}_data[1] = {NULL};""") + +_ufunc_bottom = Template("""\ +#if PY_VERSION_HEX >= 0x03000000 +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "${module}", + NULL, + -1, + ${module}Methods, + NULL, + NULL, + NULL, + NULL +}; + +PyMODINIT_FUNC PyInit_${module}(void) +{ + PyObject *m, *d; + ${function_creation} + m = PyModule_Create(&moduledef); + if (!m) { + return NULL; + } + import_array(); + import_umath(); + d = PyModule_GetDict(m); + ${ufunc_init} + return m; +} +#else +PyMODINIT_FUNC init${module}(void) +{ + PyObject *m, *d; + ${function_creation} + m = Py_InitModule("${module}", ${module}Methods); + if (m == NULL) { + return; + } + import_array(); + import_umath(); + d = PyModule_GetDict(m); + ${ufunc_init} +} +#endif\ +""") + +_ufunc_init_form = Template("""\ +ufunc${ind} = PyUFunc_FromFuncAndData(${funcname}_funcs, ${funcname}_data, ${funcname}_types, 1, ${n_in}, ${n_out}, + PyUFunc_None, "${module}", ${docstring}, 0); + PyDict_SetItemString(d, "${funcname}", ufunc${ind}); + Py_DECREF(ufunc${ind});""") + +_ufunc_setup = Template("""\ +from setuptools.extension import Extension +from setuptools import setup + +from numpy import get_include + +if __name__ == "__main__": + setup(ext_modules=[ + Extension('${module}', + sources=['${module}.c', '${filename}.c'], + include_dirs=[get_include()])]) +""") + + +class UfuncifyCodeWrapper(CodeWrapper): + """Wrapper for Ufuncify""" + + def __init__(self, *args, **kwargs): + + ext_keys = ['include_dirs', 'library_dirs', 'libraries', + 'extra_compile_args', 'extra_link_args'] + msg = ('The compilation option kwarg {} is not supported with the numpy' + ' backend.') + + for k in ext_keys: + if k in kwargs.keys(): + warn(msg.format(k)) + kwargs.pop(k, None) + + super().__init__(*args, **kwargs) + + @property + def command(self): + command = [sys.executable, "setup.py", "build_ext", "--inplace"] + return command + + def wrap_code(self, routines, helpers=None): + # This routine overrides CodeWrapper because we can't assume funcname == routines[0].name + # Therefore we have to break the CodeWrapper private API. + # There isn't an obvious way to extend multi-expr support to + # the other autowrap backends, so we limit this change to ufuncify. + helpers = helpers if helpers is not None else [] + # We just need a consistent name + funcname = 'wrapped_' + str(id(routines) + id(helpers)) + + workdir = self.filepath or tempfile.mkdtemp("_sympy_compile") + if not os.access(workdir, os.F_OK): + os.mkdir(workdir) + oldwork = os.getcwd() + os.chdir(workdir) + try: + sys.path.append(workdir) + self._generate_code(routines, helpers) + self._prepare_files(routines, funcname) + self._process_files(routines) + mod = __import__(self.module_name) + finally: + sys.path.remove(workdir) + CodeWrapper._module_counter += 1 + os.chdir(oldwork) + if not self.filepath: + try: + shutil.rmtree(workdir) + except OSError: + # Could be some issues on Windows + pass + + return self._get_wrapped_function(mod, funcname) + + def _generate_code(self, main_routines, helper_routines): + all_routines = main_routines + helper_routines + self.generator.write( + all_routines, self.filename, True, self.include_header, + self.include_empty) + + def _prepare_files(self, routines, funcname): + + # C + codefilename = self.module_name + '.c' + with open(codefilename, 'w') as f: + self.dump_c(routines, f, self.filename, funcname=funcname) + + # setup.py + with open('setup.py', 'w') as f: + self.dump_setup(f) + + @classmethod + def _get_wrapped_function(cls, mod, name): + return getattr(mod, name) + + def dump_setup(self, f): + setup = _ufunc_setup.substitute(module=self.module_name, + filename=self.filename) + f.write(setup) + + def dump_c(self, routines, f, prefix, funcname=None): + """Write a C file with Python wrappers + + This file contains all the definitions of the routines in c code. + + Arguments + --------- + routines + List of Routine instances + f + File-like object to write the file to + prefix + The filename prefix, used to name the imported module. + funcname + Name of the main function to be returned. + """ + if funcname is None: + if len(routines) == 1: + funcname = routines[0].name + else: + msg = 'funcname must be specified for multiple output routines' + raise ValueError(msg) + functions = [] + function_creation = [] + ufunc_init = [] + module = self.module_name + include_file = "\"{}.h\"".format(prefix) + top = _ufunc_top.substitute(include_file=include_file, module=module) + + name = funcname + + # Partition the C function arguments into categories + # Here we assume all routines accept the same arguments + r_index = 0 + py_in, _ = self._partition_args(routines[0].arguments) + n_in = len(py_in) + n_out = len(routines) + + # Declare Args + form = "char *{0}{1} = args[{2}];" + arg_decs = [form.format('in', i, i) for i in range(n_in)] + arg_decs.extend([form.format('out', i, i+n_in) for i in range(n_out)]) + declare_args = '\n '.join(arg_decs) + + # Declare Steps + form = "npy_intp {0}{1}_step = steps[{2}];" + step_decs = [form.format('in', i, i) for i in range(n_in)] + step_decs.extend([form.format('out', i, i+n_in) for i in range(n_out)]) + declare_steps = '\n '.join(step_decs) + + # Call Args + form = "*(double *)in{0}" + call_args = ', '.join([form.format(a) for a in range(n_in)]) + + # Step Increments + form = "{0}{1} += {0}{1}_step;" + step_incs = [form.format('in', i) for i in range(n_in)] + step_incs.extend([form.format('out', i, i) for i in range(n_out)]) + step_increments = '\n '.join(step_incs) + + # Types + n_types = n_in + n_out + types = "{" + ', '.join(["NPY_DOUBLE"]*n_types) + "};" + + # Docstring + docstring = '"Created in SymPy with Ufuncify"' + + # Function Creation + function_creation.append("PyObject *ufunc{};".format(r_index)) + + # Ufunc initialization + init_form = _ufunc_init_form.substitute(module=module, + funcname=name, + docstring=docstring, + n_in=n_in, n_out=n_out, + ind=r_index) + ufunc_init.append(init_form) + + outcalls = [_ufunc_outcalls.substitute( + outnum=i, call_args=call_args, funcname=routines[i].name) for i in + range(n_out)] + + body = _ufunc_body.substitute(module=module, funcname=name, + declare_args=declare_args, + declare_steps=declare_steps, + call_args=call_args, + step_increments=step_increments, + n_types=n_types, types=types, + outcalls='\n '.join(outcalls)) + functions.append(body) + + body = '\n\n'.join(functions) + ufunc_init = '\n '.join(ufunc_init) + function_creation = '\n '.join(function_creation) + bottom = _ufunc_bottom.substitute(module=module, + ufunc_init=ufunc_init, + function_creation=function_creation) + text = [top, body, bottom] + f.write('\n\n'.join(text)) + + def _partition_args(self, args): + """Group function arguments into categories.""" + py_in = [] + py_out = [] + for arg in args: + if isinstance(arg, OutputArgument): + py_out.append(arg) + elif isinstance(arg, InOutArgument): + raise ValueError("Ufuncify doesn't support InOutArguments") + else: + py_in.append(arg) + return py_in, py_out + + +@cacheit +@doctest_depends_on(exe=('f2py', 'gfortran', 'gcc'), modules=('numpy',)) +def ufuncify(args, expr, language=None, backend='numpy', tempdir=None, + flags=None, verbose=False, helpers=None, **kwargs): + """Generates a binary function that supports broadcasting on numpy arrays. + + Parameters + ========== + + args : iterable + Either a Symbol or an iterable of symbols. Specifies the argument + sequence for the function. + expr + A SymPy expression that defines the element wise operation. + language : string, optional + If supplied, (options: 'C' or 'F95'), specifies the language of the + generated code. If ``None`` [default], the language is inferred based + upon the specified backend. + backend : string, optional + Backend used to wrap the generated code. Either 'numpy' [default], + 'cython', or 'f2py'. + tempdir : string, optional + Path to directory for temporary files. If this argument is supplied, + the generated code and the wrapper input files are left intact in + the specified path. + flags : iterable, optional + Additional option flags that will be passed to the backend. + verbose : bool, optional + If True, autowrap will not mute the command line backends. This can + be helpful for debugging. + helpers : 3-tuple or iterable of 3-tuples, optional + Used to define auxiliary functions needed for the main expression. + Each tuple should be of the form (name, expr, args) where: + + - name : str, the function name + - expr : sympy expression, the function + - args : iterable, the function arguments (can be any iterable of symbols) + + kwargs : dict + These kwargs will be passed to autowrap if the `f2py` or `cython` + backend is used and ignored if the `numpy` backend is used. + + Notes + ===== + + The default backend ('numpy') will create actual instances of + ``numpy.ufunc``. These support ndimensional broadcasting, and implicit type + conversion. Use of the other backends will result in a "ufunc-like" + function, which requires equal length 1-dimensional arrays for all + arguments, and will not perform any type conversions. + + References + ========== + + .. [1] https://numpy.org/doc/stable/reference/ufuncs.html + + Examples + ======== + + Basic usage: + + >>> from sympy.utilities.autowrap import ufuncify + >>> from sympy.abc import x, y + >>> import numpy as np + >>> f = ufuncify((x, y), y + x**2) + >>> type(f) + + >>> f([1, 2, 3], 2) + array([ 3., 6., 11.]) + >>> f(np.arange(5), 3) + array([ 3., 4., 7., 12., 19.]) + + Using helper functions: + + >>> from sympy import Function + >>> helper_func = Function('helper_func') # Define symbolic function + >>> expr = x**2 + y*helper_func(x) # Main expression using helper function + >>> # Define helper_func(x) = x**3 + >>> f = ufuncify((x, y), expr, helpers=[('helper_func', x**3, [x])]) + >>> f([1, 2], [3, 4]) + array([ 4., 36.]) + + Type handling with different backends: + + For the 'f2py' and 'cython' backends, inputs are required to be equal length + 1-dimensional arrays. The 'f2py' backend will perform type conversion, but + the Cython backend will error if the inputs are not of the expected type. + + >>> f_fortran = ufuncify((x, y), y + x**2, backend='f2py') + >>> f_fortran(1, 2) + array([ 3.]) + >>> f_fortran(np.array([1, 2, 3]), np.array([1.0, 2.0, 3.0])) + array([ 2., 6., 12.]) + >>> f_cython = ufuncify((x, y), y + x**2, backend='Cython') + >>> f_cython(1, 2) # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + TypeError: Argument '_x' has incorrect type (expected numpy.ndarray, got int) + >>> f_cython(np.array([1.0]), np.array([2.0])) + array([ 3.]) + + """ + + if isinstance(args, Symbol): + args = (args,) + else: + args = tuple(args) + + if language: + _validate_backend_language(backend, language) + else: + language = _infer_language(backend) + + helpers = helpers if helpers else () + flags = flags if flags else () + + if backend.upper() == 'NUMPY': + # maxargs is set by numpy compile-time constant NPY_MAXARGS + # If a future version of numpy modifies or removes this restriction + # this variable should be changed or removed + maxargs = 32 + helps = [] + for name, expr, args in helpers: + helps.append(make_routine(name, expr, args)) + code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify"), tempdir, + flags, verbose) + if not isinstance(expr, (list, tuple)): + expr = [expr] + if len(expr) == 0: + raise ValueError('Expression iterable has zero length') + if len(expr) + len(args) > maxargs: + msg = ('Cannot create ufunc with more than {0} total arguments: ' + 'got {1} in, {2} out') + raise ValueError(msg.format(maxargs, len(args), len(expr))) + routines = [make_routine('autofunc{}'.format(idx), exprx, args) for + idx, exprx in enumerate(expr)] + return code_wrapper.wrap_code(routines, helpers=helps) + else: + # Dummies are used for all added expressions to prevent name clashes + # within the original expression. + y = IndexedBase(Dummy('y')) + m = Dummy('m', integer=True) + i = Idx(Dummy('i', integer=True), m) + f_dummy = Dummy('f') + f = implemented_function('%s_%d' % (f_dummy.name, f_dummy.dummy_index), Lambda(args, expr)) + # For each of the args create an indexed version. + indexed_args = [IndexedBase(Dummy(str(a))) for a in args] + # Order the arguments (out, args, dim) + args = [y] + indexed_args + [m] + args_with_indices = [a[i] for a in indexed_args] + return autowrap(Eq(y[i], f(*args_with_indices)), language, backend, + tempdir, args, flags, verbose, helpers, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/codegen.py b/.venv/lib/python3.12/site-packages/sympy/utilities/codegen.py new file mode 100644 index 0000000000000000000000000000000000000000..9ac8772fc000d707ae33c67eaa44b4c281157ab0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/codegen.py @@ -0,0 +1,2237 @@ +""" +module for generating C, C++, Fortran77, Fortran90, Julia, Rust +and Octave/Matlab routines that evaluate SymPy expressions. +This module is work in progress. +Only the milestones with a '+' character in the list below have been completed. + +--- How is sympy.utilities.codegen different from sympy.printing.ccode? --- + +We considered the idea to extend the printing routines for SymPy functions in +such a way that it prints complete compilable code, but this leads to a few +unsurmountable issues that can only be tackled with dedicated code generator: + +- For C, one needs both a code and a header file, while the printing routines + generate just one string. This code generator can be extended to support + .pyf files for f2py. + +- SymPy functions are not concerned with programming-technical issues, such + as input, output and input-output arguments. Other examples are contiguous + or non-contiguous arrays, including headers of other libraries such as gsl + or others. + +- It is highly interesting to evaluate several SymPy functions in one C + routine, eventually sharing common intermediate results with the help + of the cse routine. This is more than just printing. + +- From the programming perspective, expressions with constants should be + evaluated in the code generator as much as possible. This is different + for printing. + +--- Basic assumptions --- + +* A generic Routine data structure describes the routine that must be + translated into C/Fortran/... code. This data structure covers all + features present in one or more of the supported languages. + +* Descendants from the CodeGen class transform multiple Routine instances + into compilable code. Each derived class translates into a specific + language. + +* In many cases, one wants a simple workflow. The friendly functions in the + last part are a simple api on top of the Routine/CodeGen stuff. They are + easier to use, but are less powerful. + +--- Milestones --- + ++ First working version with scalar input arguments, generating C code, + tests ++ Friendly functions that are easier to use than the rigorous + Routine/CodeGen workflow. ++ Integer and Real numbers as input and output ++ Output arguments ++ InputOutput arguments ++ Sort input/output arguments properly ++ Contiguous array arguments (numpy matrices) ++ Also generate .pyf code for f2py (in autowrap module) ++ Isolate constants and evaluate them beforehand in double precision ++ Fortran 90 ++ Octave/Matlab + +- Common Subexpression Elimination +- User defined comments in the generated code +- Optional extra include lines for libraries/objects that can eval special + functions +- Test other C compilers and libraries: gcc, tcc, libtcc, gcc+gsl, ... +- Contiguous array arguments (SymPy matrices) +- Non-contiguous array arguments (SymPy matrices) +- ccode must raise an error when it encounters something that cannot be + translated into c. ccode(integrate(sin(x)/x, x)) does not make sense. +- Complex numbers as input and output +- A default complex datatype +- Include extra information in the header: date, user, hostname, sha1 + hash, ... +- Fortran 77 +- C++ +- Python +- Julia +- Rust +- ... + +""" + +import os +import textwrap +from io import StringIO + +from sympy import __version__ as sympy_version +from sympy.core import Symbol, S, Tuple, Equality, Function, Basic +from sympy.printing.c import c_code_printers +from sympy.printing.codeprinter import AssignmentError +from sympy.printing.fortran import FCodePrinter +from sympy.printing.julia import JuliaCodePrinter +from sympy.printing.octave import OctaveCodePrinter +from sympy.printing.rust import RustCodePrinter +from sympy.tensor import Idx, Indexed, IndexedBase +from sympy.matrices import (MatrixSymbol, ImmutableMatrix, MatrixBase, + MatrixExpr, MatrixSlice) +from sympy.utilities.iterables import is_sequence + + +__all__ = [ + # description of routines + "Routine", "DataType", "default_datatypes", "get_default_datatype", + "Argument", "InputArgument", "OutputArgument", "Result", + # routines -> code + "CodeGen", "CCodeGen", "FCodeGen", "JuliaCodeGen", "OctaveCodeGen", + "RustCodeGen", + # friendly functions + "codegen", "make_routine", +] + + +# +# Description of routines +# + + +class Routine: + """Generic description of evaluation routine for set of expressions. + + A CodeGen class can translate instances of this class into code in a + particular language. The routine specification covers all the features + present in these languages. The CodeGen part must raise an exception + when certain features are not present in the target language. For + example, multiple return values are possible in Python, but not in C or + Fortran. Another example: Fortran and Python support complex numbers, + while C does not. + + """ + + def __init__(self, name, arguments, results, local_vars, global_vars): + """Initialize a Routine instance. + + Parameters + ========== + + name : string + Name of the routine. + + arguments : list of Arguments + These are things that appear in arguments of a routine, often + appearing on the right-hand side of a function call. These are + commonly InputArguments but in some languages, they can also be + OutputArguments or InOutArguments (e.g., pass-by-reference in C + code). + + results : list of Results + These are the return values of the routine, often appearing on + the left-hand side of a function call. The difference between + Results and OutputArguments and when you should use each is + language-specific. + + local_vars : list of Results + These are variables that will be defined at the beginning of the + function. + + global_vars : list of Symbols + Variables which will not be passed into the function. + + """ + + # extract all input symbols and all symbols appearing in an expression + input_symbols = set() + symbols = set() + for arg in arguments: + if isinstance(arg, OutputArgument): + symbols.update(arg.expr.free_symbols - arg.expr.atoms(Indexed)) + elif isinstance(arg, InputArgument): + input_symbols.add(arg.name) + elif isinstance(arg, InOutArgument): + input_symbols.add(arg.name) + symbols.update(arg.expr.free_symbols - arg.expr.atoms(Indexed)) + else: + raise ValueError("Unknown Routine argument: %s" % arg) + + for r in results: + if not isinstance(r, Result): + raise ValueError("Unknown Routine result: %s" % r) + symbols.update(r.expr.free_symbols - r.expr.atoms(Indexed)) + + local_symbols = set() + for r in local_vars: + if isinstance(r, Result): + symbols.update(r.expr.free_symbols - r.expr.atoms(Indexed)) + local_symbols.add(r.name) + else: + local_symbols.add(r) + + symbols = {s.label if isinstance(s, Idx) else s for s in symbols} + + # Check that all symbols in the expressions are covered by + # InputArguments/InOutArguments---subset because user could + # specify additional (unused) InputArguments or local_vars. + notcovered = symbols.difference( + input_symbols.union(local_symbols).union(global_vars)) + if notcovered != set(): + raise ValueError("Symbols needed for output are not in input " + + ", ".join([str(x) for x in notcovered])) + + self.name = name + self.arguments = arguments + self.results = results + self.local_vars = local_vars + self.global_vars = global_vars + + def __str__(self): + return self.__class__.__name__ + "({name!r}, {arguments}, {results}, {local_vars}, {global_vars})".format(**self.__dict__) + + __repr__ = __str__ + + @property + def variables(self): + """Returns a set of all variables possibly used in the routine. + + For routines with unnamed return values, the dummies that may or + may not be used will be included in the set. + + """ + v = set(self.local_vars) + v.update(arg.name for arg in self.arguments) + v.update(res.result_var for res in self.results) + return v + + @property + def result_variables(self): + """Returns a list of OutputArgument, InOutArgument and Result. + + If return values are present, they are at the end of the list. + """ + args = [arg for arg in self.arguments if isinstance( + arg, (OutputArgument, InOutArgument))] + args.extend(self.results) + return args + + +class DataType: + """Holds strings for a certain datatype in different languages.""" + def __init__(self, cname, fname, pyname, jlname, octname, rsname): + self.cname = cname + self.fname = fname + self.pyname = pyname + self.jlname = jlname + self.octname = octname + self.rsname = rsname + + +default_datatypes = { + "int": DataType("int", "INTEGER*4", "int", "", "", "i32"), + "float": DataType("double", "REAL*8", "float", "", "", "f64"), + "complex": DataType("double", "COMPLEX*16", "complex", "", "", "float") #FIXME: + # complex is only supported in fortran, python, julia, and octave. + # So to not break c or rust code generation, we stick with double or + # float, respectively (but actually should raise an exception for + # explicitly complex variables (x.is_complex==True)) +} + + +COMPLEX_ALLOWED = False +def get_default_datatype(expr, complex_allowed=None): + """Derives an appropriate datatype based on the expression.""" + if complex_allowed is None: + complex_allowed = COMPLEX_ALLOWED + if complex_allowed: + final_dtype = "complex" + else: + final_dtype = "float" + if expr.is_integer: + return default_datatypes["int"] + elif expr.is_real: + return default_datatypes["float"] + elif isinstance(expr, MatrixBase): + #check all entries + dt = "int" + for element in expr: + if dt == "int" and not element.is_integer: + dt = "float" + if dt == "float" and not element.is_real: + return default_datatypes[final_dtype] + return default_datatypes[dt] + else: + return default_datatypes[final_dtype] + + +class Variable: + """Represents a typed variable.""" + + def __init__(self, name, datatype=None, dimensions=None, precision=None): + """Return a new variable. + + Parameters + ========== + + name : Symbol or MatrixSymbol + + datatype : optional + When not given, the data type will be guessed based on the + assumptions on the symbol argument. + + dimensions : sequence containing tuples, optional + If present, the argument is interpreted as an array, where this + sequence of tuples specifies (lower, upper) bounds for each + index of the array. + + precision : int, optional + Controls the precision of floating point constants. + + """ + if not isinstance(name, (Symbol, MatrixSymbol)): + raise TypeError("The first argument must be a SymPy symbol.") + if datatype is None: + datatype = get_default_datatype(name) + elif not isinstance(datatype, DataType): + raise TypeError("The (optional) `datatype' argument must be an " + "instance of the DataType class.") + if dimensions and not isinstance(dimensions, (tuple, list)): + raise TypeError( + "The dimensions argument must be a sequence of tuples") + + self._name = name + self._datatype = { + 'C': datatype.cname, + 'FORTRAN': datatype.fname, + 'JULIA': datatype.jlname, + 'OCTAVE': datatype.octname, + 'PYTHON': datatype.pyname, + 'RUST': datatype.rsname, + } + self.dimensions = dimensions + self.precision = precision + + def __str__(self): + return "%s(%r)" % (self.__class__.__name__, self.name) + + __repr__ = __str__ + + @property + def name(self): + return self._name + + def get_datatype(self, language): + """Returns the datatype string for the requested language. + + Examples + ======== + + >>> from sympy import Symbol + >>> from sympy.utilities.codegen import Variable + >>> x = Variable(Symbol('x')) + >>> x.get_datatype('c') + 'double' + >>> x.get_datatype('fortran') + 'REAL*8' + + """ + try: + return self._datatype[language.upper()] + except KeyError: + raise CodeGenError("Has datatypes for languages: %s" % + ", ".join(self._datatype)) + + +class Argument(Variable): + """An abstract Argument data structure: a name and a data type. + + This structure is refined in the descendants below. + + """ + pass + + +class InputArgument(Argument): + pass + + +class ResultBase: + """Base class for all "outgoing" information from a routine. + + Objects of this class stores a SymPy expression, and a SymPy object + representing a result variable that will be used in the generated code + only if necessary. + + """ + def __init__(self, expr, result_var): + self.expr = expr + self.result_var = result_var + + def __str__(self): + return "%s(%r, %r)" % (self.__class__.__name__, self.expr, + self.result_var) + + __repr__ = __str__ + + +class OutputArgument(Argument, ResultBase): + """OutputArgument are always initialized in the routine.""" + + def __init__(self, name, result_var, expr, datatype=None, dimensions=None, precision=None): + """Return a new variable. + + Parameters + ========== + + name : Symbol, MatrixSymbol + The name of this variable. When used for code generation, this + might appear, for example, in the prototype of function in the + argument list. + + result_var : Symbol, Indexed + Something that can be used to assign a value to this variable. + Typically the same as `name` but for Indexed this should be e.g., + "y[i]" whereas `name` should be the Symbol "y". + + expr : object + The expression that should be output, typically a SymPy + expression. + + datatype : optional + When not given, the data type will be guessed based on the + assumptions on the symbol argument. + + dimensions : sequence containing tuples, optional + If present, the argument is interpreted as an array, where this + sequence of tuples specifies (lower, upper) bounds for each + index of the array. + + precision : int, optional + Controls the precision of floating point constants. + + """ + + Argument.__init__(self, name, datatype, dimensions, precision) + ResultBase.__init__(self, expr, result_var) + + def __str__(self): + return "%s(%r, %r, %r)" % (self.__class__.__name__, self.name, self.result_var, self.expr) + + __repr__ = __str__ + + +class InOutArgument(Argument, ResultBase): + """InOutArgument are never initialized in the routine.""" + + def __init__(self, name, result_var, expr, datatype=None, dimensions=None, precision=None): + if not datatype: + datatype = get_default_datatype(expr) + Argument.__init__(self, name, datatype, dimensions, precision) + ResultBase.__init__(self, expr, result_var) + __init__.__doc__ = OutputArgument.__init__.__doc__ + + + def __str__(self): + return "%s(%r, %r, %r)" % (self.__class__.__name__, self.name, self.expr, + self.result_var) + + __repr__ = __str__ + + +class Result(Variable, ResultBase): + """An expression for a return value. + + The name result is used to avoid conflicts with the reserved word + "return" in the Python language. It is also shorter than ReturnValue. + + These may or may not need a name in the destination (e.g., "return(x*y)" + might return a value without ever naming it). + + """ + + def __init__(self, expr, name=None, result_var=None, datatype=None, + dimensions=None, precision=None): + """Initialize a return value. + + Parameters + ========== + + expr : SymPy expression + + name : Symbol, MatrixSymbol, optional + The name of this return variable. When used for code generation, + this might appear, for example, in the prototype of function in a + list of return values. A dummy name is generated if omitted. + + result_var : Symbol, Indexed, optional + Something that can be used to assign a value to this variable. + Typically the same as `name` but for Indexed this should be e.g., + "y[i]" whereas `name` should be the Symbol "y". Defaults to + `name` if omitted. + + datatype : optional + When not given, the data type will be guessed based on the + assumptions on the expr argument. + + dimensions : sequence containing tuples, optional + If present, this variable is interpreted as an array, + where this sequence of tuples specifies (lower, upper) + bounds for each index of the array. + + precision : int, optional + Controls the precision of floating point constants. + + """ + # Basic because it is the base class for all types of expressions + if not isinstance(expr, (Basic, MatrixBase)): + raise TypeError("The first argument must be a SymPy expression.") + + if name is None: + name = 'result_%d' % abs(hash(expr)) + + if datatype is None: + #try to infer data type from the expression + datatype = get_default_datatype(expr) + + if isinstance(name, str): + if isinstance(expr, (MatrixBase, MatrixExpr)): + name = MatrixSymbol(name, *expr.shape) + else: + name = Symbol(name) + + if result_var is None: + result_var = name + + Variable.__init__(self, name, datatype=datatype, + dimensions=dimensions, precision=precision) + ResultBase.__init__(self, expr, result_var) + + def __str__(self): + return "%s(%r, %r, %r)" % (self.__class__.__name__, self.expr, self.name, + self.result_var) + + __repr__ = __str__ + + +# +# Transformation of routine objects into code +# + +class CodeGen: + """Abstract class for the code generators.""" + + printer = None # will be set to an instance of a CodePrinter subclass + + def _indent_code(self, codelines): + return self.printer.indent_code(codelines) + + def _printer_method_with_settings(self, method, settings=None, *args, **kwargs): + settings = settings or {} + ori = {k: self.printer._settings[k] for k in settings} + for k, v in settings.items(): + self.printer._settings[k] = v + result = getattr(self.printer, method)(*args, **kwargs) + for k, v in ori.items(): + self.printer._settings[k] = v + return result + + def _get_symbol(self, s): + """Returns the symbol as fcode prints it.""" + if self.printer._settings['human']: + expr_str = self.printer.doprint(s) + else: + constants, not_supported, expr_str = self.printer.doprint(s) + if constants or not_supported: + raise ValueError("Failed to print %s" % str(s)) + return expr_str.strip() + + def __init__(self, project="project", cse=False): + """Initialize a code generator. + + Derived classes will offer more options that affect the generated + code. + + """ + self.project = project + self.cse = cse + + def routine(self, name, expr, argument_sequence=None, global_vars=None): + """Creates an Routine object that is appropriate for this language. + + This implementation is appropriate for at least C/Fortran. Subclasses + can override this if necessary. + + Here, we assume at most one return value (the l-value) which must be + scalar. Additional outputs are OutputArguments (e.g., pointers on + right-hand-side or pass-by-reference). Matrices are always returned + via OutputArguments. If ``argument_sequence`` is None, arguments will + be ordered alphabetically, but with all InputArguments first, and then + OutputArgument and InOutArguments. + + """ + + if self.cse: + from sympy.simplify.cse_main import cse + + if is_sequence(expr) and not isinstance(expr, (MatrixBase, MatrixExpr)): + if not expr: + raise ValueError("No expression given") + for e in expr: + if not e.is_Equality: + raise CodeGenError("Lists of expressions must all be Equalities. {} is not.".format(e)) + + # create a list of right hand sides and simplify them + rhs = [e.rhs for e in expr] + common, simplified = cse(rhs) + + # pack the simplified expressions back up with their left hand sides + expr = [Equality(e.lhs, rhs) for e, rhs in zip(expr, simplified)] + else: + if isinstance(expr, Equality): + common, simplified = cse(expr.rhs) #, ignore=in_out_args) + expr = Equality(expr.lhs, simplified[0]) + else: + common, simplified = cse(expr) + expr = simplified + + local_vars = [Result(b,a) for a,b in common] + local_symbols = {a for a,_ in common} + local_expressions = Tuple(*[b for _,b in common]) + else: + local_expressions = Tuple() + + if is_sequence(expr) and not isinstance(expr, (MatrixBase, MatrixExpr)): + if not expr: + raise ValueError("No expression given") + expressions = Tuple(*expr) + else: + expressions = Tuple(expr) + + if self.cse: + if {i.label for i in expressions.atoms(Idx)} != set(): + raise CodeGenError("CSE and Indexed expressions do not play well together yet") + else: + # local variables for indexed expressions + local_vars = {i.label for i in expressions.atoms(Idx)} + local_symbols = local_vars + + # global variables + global_vars = set() if global_vars is None else set(global_vars) + + # symbols that should be arguments + symbols = (expressions.free_symbols | local_expressions.free_symbols) - local_symbols - global_vars + new_symbols = set() + new_symbols.update(symbols) + + for symbol in symbols: + if isinstance(symbol, Idx): + new_symbols.remove(symbol) + new_symbols.update(symbol.args[1].free_symbols) + if isinstance(symbol, Indexed): + new_symbols.remove(symbol) + symbols = new_symbols + + # Decide whether to use output argument or return value + return_val = [] + output_args = [] + for expr in expressions: + if isinstance(expr, Equality): + out_arg = expr.lhs + expr = expr.rhs + if isinstance(out_arg, Indexed): + dims = tuple([ (S.Zero, dim - 1) for dim in out_arg.shape]) + symbol = out_arg.base.label + elif isinstance(out_arg, Symbol): + dims = [] + symbol = out_arg + elif isinstance(out_arg, MatrixSymbol): + dims = tuple([ (S.Zero, dim - 1) for dim in out_arg.shape]) + symbol = out_arg + else: + raise CodeGenError("Only Indexed, Symbol, or MatrixSymbol " + "can define output arguments.") + + if expr.has(symbol): + output_args.append( + InOutArgument(symbol, out_arg, expr, dimensions=dims)) + else: + output_args.append( + OutputArgument(symbol, out_arg, expr, dimensions=dims)) + + # remove duplicate arguments when they are not local variables + if symbol not in local_vars: + # avoid duplicate arguments + symbols.remove(symbol) + elif isinstance(expr, (ImmutableMatrix, MatrixSlice)): + # Create a "dummy" MatrixSymbol to use as the Output arg + out_arg = MatrixSymbol('out_%s' % abs(hash(expr)), *expr.shape) + dims = tuple([(S.Zero, dim - 1) for dim in out_arg.shape]) + output_args.append( + OutputArgument(out_arg, out_arg, expr, dimensions=dims)) + else: + return_val.append(Result(expr)) + + arg_list = [] + + # setup input argument list + + # helper to get dimensions for data for array-like args + def dimensions(s): + return [(S.Zero, dim - 1) for dim in s.shape] + + array_symbols = {} + for array in expressions.atoms(Indexed) | local_expressions.atoms(Indexed): + array_symbols[array.base.label] = array + for array in expressions.atoms(MatrixSymbol) | local_expressions.atoms(MatrixSymbol): + array_symbols[array] = array + + for symbol in sorted(symbols, key=str): + if symbol in array_symbols: + array = array_symbols[symbol] + metadata = {'dimensions': dimensions(array)} + else: + metadata = {} + + arg_list.append(InputArgument(symbol, **metadata)) + + output_args.sort(key=lambda x: str(x.name)) + arg_list.extend(output_args) + + if argument_sequence is not None: + # if the user has supplied IndexedBase instances, we'll accept that + new_sequence = [] + for arg in argument_sequence: + if isinstance(arg, IndexedBase): + new_sequence.append(arg.label) + else: + new_sequence.append(arg) + argument_sequence = new_sequence + + missing = [x for x in arg_list if x.name not in argument_sequence] + if missing: + msg = "Argument list didn't specify: {0} " + msg = msg.format(", ".join([str(m.name) for m in missing])) + raise CodeGenArgumentListError(msg, missing) + + # create redundant arguments to produce the requested sequence + name_arg_dict = {x.name: x for x in arg_list} + new_args = [] + for symbol in argument_sequence: + try: + new_args.append(name_arg_dict[symbol]) + except KeyError: + if isinstance(symbol, (IndexedBase, MatrixSymbol)): + metadata = {'dimensions': dimensions(symbol)} + else: + metadata = {} + new_args.append(InputArgument(symbol, **metadata)) + arg_list = new_args + + return Routine(name, arg_list, return_val, local_vars, global_vars) + + def write(self, routines, prefix, to_files=False, header=True, empty=True): + """Writes all the source code files for the given routines. + + The generated source is returned as a list of (filename, contents) + tuples, or is written to files (see below). Each filename consists + of the given prefix, appended with an appropriate extension. + + Parameters + ========== + + routines : list + A list of Routine instances to be written + + prefix : string + The prefix for the output files + + to_files : bool, optional + When True, the output is written to files. Otherwise, a list + of (filename, contents) tuples is returned. [default: False] + + header : bool, optional + When True, a header comment is included on top of each source + file. [default: True] + + empty : bool, optional + When True, empty lines are included to structure the source + files. [default: True] + + """ + if to_files: + for dump_fn in self.dump_fns: + filename = "%s.%s" % (prefix, dump_fn.extension) + with open(filename, "w") as f: + dump_fn(self, routines, f, prefix, header, empty) + else: + result = [] + for dump_fn in self.dump_fns: + filename = "%s.%s" % (prefix, dump_fn.extension) + contents = StringIO() + dump_fn(self, routines, contents, prefix, header, empty) + result.append((filename, contents.getvalue())) + return result + + def dump_code(self, routines, f, prefix, header=True, empty=True): + """Write the code by calling language specific methods. + + The generated file contains all the definitions of the routines in + low-level code and refers to the header file if appropriate. + + Parameters + ========== + + routines : list + A list of Routine instances. + + f : file-like + Where to write the file. + + prefix : string + The filename prefix, used to refer to the proper header file. + Only the basename of the prefix is used. + + header : bool, optional + When True, a header comment is included on top of each source + file. [default : True] + + empty : bool, optional + When True, empty lines are included to structure the source + files. [default : True] + + """ + + code_lines = self._preprocessor_statements(prefix) + + for routine in routines: + if empty: + code_lines.append("\n") + code_lines.extend(self._get_routine_opening(routine)) + code_lines.extend(self._declare_arguments(routine)) + code_lines.extend(self._declare_globals(routine)) + code_lines.extend(self._declare_locals(routine)) + if empty: + code_lines.append("\n") + code_lines.extend(self._call_printer(routine)) + if empty: + code_lines.append("\n") + code_lines.extend(self._get_routine_ending(routine)) + + code_lines = self._indent_code(''.join(code_lines)) + + if header: + code_lines = ''.join(self._get_header() + [code_lines]) + + if code_lines: + f.write(code_lines) + + +class CodeGenError(Exception): + pass + + +class CodeGenArgumentListError(Exception): + @property + def missing_args(self): + return self.args[1] + + +header_comment = """Code generated with SymPy %(version)s + +See http://www.sympy.org/ for more information. + +This file is part of '%(project)s' +""" + + +class CCodeGen(CodeGen): + """Generator for C code. + + The .write() method inherited from CodeGen will output a code file and + an interface file, .c and .h respectively. + + """ + + code_extension = "c" + interface_extension = "h" + standard = 'c99' + + def __init__(self, project="project", printer=None, + preprocessor_statements=None, cse=False): + super().__init__(project=project, cse=cse) + self.printer = printer or c_code_printers[self.standard.lower()]() + + self.preprocessor_statements = preprocessor_statements + if preprocessor_statements is None: + self.preprocessor_statements = ['#include '] + + def _get_header(self): + """Writes a common header for the generated files.""" + code_lines = [] + code_lines.append("/" + "*"*78 + '\n') + tmp = header_comment % {"version": sympy_version, + "project": self.project} + for line in tmp.splitlines(): + code_lines.append(" *%s*\n" % line.center(76)) + code_lines.append(" " + "*"*78 + "/\n") + return code_lines + + def get_prototype(self, routine): + """Returns a string for the function prototype of the routine. + + If the routine has multiple result objects, an CodeGenError is + raised. + + See: https://en.wikipedia.org/wiki/Function_prototype + + """ + if len(routine.results) > 1: + raise CodeGenError("C only supports a single or no return value.") + elif len(routine.results) == 1: + ctype = routine.results[0].get_datatype('C') + else: + ctype = "void" + + type_args = [] + for arg in routine.arguments: + name = self.printer.doprint(arg.name) + if arg.dimensions or isinstance(arg, ResultBase): + type_args.append((arg.get_datatype('C'), "*%s" % name)) + else: + type_args.append((arg.get_datatype('C'), name)) + arguments = ", ".join([ "%s %s" % t for t in type_args]) + return "%s %s(%s)" % (ctype, routine.name, arguments) + + def _preprocessor_statements(self, prefix): + code_lines = [] + code_lines.append('#include "{}.h"'.format(os.path.basename(prefix))) + code_lines.extend(self.preprocessor_statements) + code_lines = ['{}\n'.format(l) for l in code_lines] + return code_lines + + def _get_routine_opening(self, routine): + prototype = self.get_prototype(routine) + return ["%s {\n" % prototype] + + def _declare_arguments(self, routine): + # arguments are declared in prototype + return [] + + def _declare_globals(self, routine): + # global variables are not explicitly declared within C functions + return [] + + def _declare_locals(self, routine): + + # Compose a list of symbols to be dereferenced in the function + # body. These are the arguments that were passed by a reference + # pointer, excluding arrays. + dereference = [] + for arg in routine.arguments: + if isinstance(arg, ResultBase) and not arg.dimensions: + dereference.append(arg.name) + + code_lines = [] + for result in routine.local_vars: + + # local variables that are simple symbols such as those used as indices into + # for loops are defined declared elsewhere. + if not isinstance(result, Result): + continue + + if result.name != result.result_var: + raise CodeGen("Result variable and name should match: {}".format(result)) + assign_to = result.name + t = result.get_datatype('c') + if isinstance(result.expr, (MatrixBase, MatrixExpr)): + dims = result.expr.shape + code_lines.append("{} {}[{}];\n".format(t, str(assign_to), dims[0]*dims[1])) + prefix = "" + else: + prefix = "const {} ".format(t) + + constants, not_c, c_expr = self._printer_method_with_settings( + 'doprint', {"human": False, "dereference": dereference, "strict": False}, + result.expr, assign_to=assign_to) + + for name, value in sorted(constants, key=str): + code_lines.append("double const %s = %s;\n" % (name, value)) + + code_lines.append("{}{}\n".format(prefix, c_expr)) + + return code_lines + + def _call_printer(self, routine): + code_lines = [] + + # Compose a list of symbols to be dereferenced in the function + # body. These are the arguments that were passed by a reference + # pointer, excluding arrays. + dereference = [] + for arg in routine.arguments: + if isinstance(arg, ResultBase) and not arg.dimensions: + dereference.append(arg.name) + + return_val = None + for result in routine.result_variables: + if isinstance(result, Result): + assign_to = routine.name + "_result" + t = result.get_datatype('c') + code_lines.append("{} {};\n".format(t, str(assign_to))) + return_val = assign_to + else: + assign_to = result.result_var + + try: + constants, not_c, c_expr = self._printer_method_with_settings( + 'doprint', {"human": False, "dereference": dereference, "strict": False}, + result.expr, assign_to=assign_to) + except AssignmentError: + assign_to = result.result_var + code_lines.append( + "%s %s;\n" % (result.get_datatype('c'), str(assign_to))) + constants, not_c, c_expr = self._printer_method_with_settings( + 'doprint', {"human": False, "dereference": dereference, "strict": False}, + result.expr, assign_to=assign_to) + + for name, value in sorted(constants, key=str): + code_lines.append("double const %s = %s;\n" % (name, value)) + code_lines.append("%s\n" % c_expr) + + if return_val: + code_lines.append(" return %s;\n" % return_val) + return code_lines + + def _get_routine_ending(self, routine): + return ["}\n"] + + def dump_c(self, routines, f, prefix, header=True, empty=True): + self.dump_code(routines, f, prefix, header, empty) + dump_c.extension = code_extension # type: ignore + dump_c.__doc__ = CodeGen.dump_code.__doc__ + + def dump_h(self, routines, f, prefix, header=True, empty=True): + """Writes the C header file. + + This file contains all the function declarations. + + Parameters + ========== + + routines : list + A list of Routine instances. + + f : file-like + Where to write the file. + + prefix : string + The filename prefix, used to construct the include guards. + Only the basename of the prefix is used. + + header : bool, optional + When True, a header comment is included on top of each source + file. [default : True] + + empty : bool, optional + When True, empty lines are included to structure the source + files. [default : True] + + """ + if header: + print(''.join(self._get_header()), file=f) + guard_name = "%s__%s__H" % (self.project.replace( + " ", "_").upper(), prefix.replace("/", "_").upper()) + # include guards + if empty: + print(file=f) + print("#ifndef %s" % guard_name, file=f) + print("#define %s" % guard_name, file=f) + if empty: + print(file=f) + # declaration of the function prototypes + for routine in routines: + prototype = self.get_prototype(routine) + print("%s;" % prototype, file=f) + # end if include guards + if empty: + print(file=f) + print("#endif", file=f) + if empty: + print(file=f) + dump_h.extension = interface_extension # type: ignore + + # This list of dump functions is used by CodeGen.write to know which dump + # functions it has to call. + dump_fns = [dump_c, dump_h] + +class C89CodeGen(CCodeGen): + standard = 'C89' + +class C99CodeGen(CCodeGen): + standard = 'C99' + +class FCodeGen(CodeGen): + """Generator for Fortran 95 code + + The .write() method inherited from CodeGen will output a code file and + an interface file, .f90 and .h respectively. + + """ + + code_extension = "f90" + interface_extension = "h" + + def __init__(self, project='project', printer=None): + super().__init__(project) + self.printer = printer or FCodePrinter() + + def _get_header(self): + """Writes a common header for the generated files.""" + code_lines = [] + code_lines.append("!" + "*"*78 + '\n') + tmp = header_comment % {"version": sympy_version, + "project": self.project} + for line in tmp.splitlines(): + code_lines.append("!*%s*\n" % line.center(76)) + code_lines.append("!" + "*"*78 + '\n') + return code_lines + + def _preprocessor_statements(self, prefix): + return [] + + def _get_routine_opening(self, routine): + """Returns the opening statements of the fortran routine.""" + code_list = [] + if len(routine.results) > 1: + raise CodeGenError( + "Fortran only supports a single or no return value.") + elif len(routine.results) == 1: + result = routine.results[0] + code_list.append(result.get_datatype('fortran')) + code_list.append("function") + else: + code_list.append("subroutine") + + args = ", ".join("%s" % self._get_symbol(arg.name) + for arg in routine.arguments) + + call_sig = "{}({})\n".format(routine.name, args) + # Fortran 95 requires all lines be less than 132 characters, so wrap + # this line before appending. + call_sig = ' &\n'.join(textwrap.wrap(call_sig, + width=60, + break_long_words=False)) + '\n' + code_list.append(call_sig) + code_list = [' '.join(code_list)] + code_list.append('implicit none\n') + return code_list + + def _declare_arguments(self, routine): + # argument type declarations + code_list = [] + array_list = [] + scalar_list = [] + for arg in routine.arguments: + + if isinstance(arg, InputArgument): + typeinfo = "%s, intent(in)" % arg.get_datatype('fortran') + elif isinstance(arg, InOutArgument): + typeinfo = "%s, intent(inout)" % arg.get_datatype('fortran') + elif isinstance(arg, OutputArgument): + typeinfo = "%s, intent(out)" % arg.get_datatype('fortran') + else: + raise CodeGenError("Unknown Argument type: %s" % type(arg)) + + fprint = self._get_symbol + + if arg.dimensions: + # fortran arrays start at 1 + dimstr = ", ".join(["%s:%s" % ( + fprint(dim[0] + 1), fprint(dim[1] + 1)) + for dim in arg.dimensions]) + typeinfo += ", dimension(%s)" % dimstr + array_list.append("%s :: %s\n" % (typeinfo, fprint(arg.name))) + else: + scalar_list.append("%s :: %s\n" % (typeinfo, fprint(arg.name))) + + # scalars first, because they can be used in array declarations + code_list.extend(scalar_list) + code_list.extend(array_list) + + return code_list + + def _declare_globals(self, routine): + # Global variables not explicitly declared within Fortran 90 functions. + # Note: a future F77 mode may need to generate "common" blocks. + return [] + + def _declare_locals(self, routine): + code_list = [] + for var in sorted(routine.local_vars, key=str): + typeinfo = get_default_datatype(var) + code_list.append("%s :: %s\n" % ( + typeinfo.fname, self._get_symbol(var))) + return code_list + + def _get_routine_ending(self, routine): + """Returns the closing statements of the fortran routine.""" + if len(routine.results) == 1: + return ["end function\n"] + else: + return ["end subroutine\n"] + + def get_interface(self, routine): + """Returns a string for the function interface. + + The routine should have a single result object, which can be None. + If the routine has multiple result objects, a CodeGenError is + raised. + + See: https://en.wikipedia.org/wiki/Function_prototype + + """ + prototype = [ "interface\n" ] + prototype.extend(self._get_routine_opening(routine)) + prototype.extend(self._declare_arguments(routine)) + prototype.extend(self._get_routine_ending(routine)) + prototype.append("end interface\n") + + return "".join(prototype) + + def _call_printer(self, routine): + declarations = [] + code_lines = [] + for result in routine.result_variables: + if isinstance(result, Result): + assign_to = routine.name + elif isinstance(result, (OutputArgument, InOutArgument)): + assign_to = result.result_var + + constants, not_fortran, f_expr = self._printer_method_with_settings( + 'doprint', {"human": False, "source_format": 'free', "standard": 95, "strict": False}, + result.expr, assign_to=assign_to) + + for obj, v in sorted(constants, key=str): + t = get_default_datatype(obj) + declarations.append( + "%s, parameter :: %s = %s\n" % (t.fname, obj, v)) + for obj in sorted(not_fortran, key=str): + t = get_default_datatype(obj) + if isinstance(obj, Function): + name = obj.func + else: + name = obj + declarations.append("%s :: %s\n" % (t.fname, name)) + + code_lines.append("%s\n" % f_expr) + return declarations + code_lines + + def _indent_code(self, codelines): + return self._printer_method_with_settings( + 'indent_code', {"human": False, "source_format": 'free', "strict": False}, codelines) + + def dump_f95(self, routines, f, prefix, header=True, empty=True): + # check that symbols are unique with ignorecase + for r in routines: + lowercase = {str(x).lower() for x in r.variables} + orig_case = {str(x) for x in r.variables} + if len(lowercase) < len(orig_case): + raise CodeGenError("Fortran ignores case. Got symbols: %s" % + (", ".join([str(var) for var in r.variables]))) + self.dump_code(routines, f, prefix, header, empty) + dump_f95.extension = code_extension # type: ignore + dump_f95.__doc__ = CodeGen.dump_code.__doc__ + + def dump_h(self, routines, f, prefix, header=True, empty=True): + """Writes the interface to a header file. + + This file contains all the function declarations. + + Parameters + ========== + + routines : list + A list of Routine instances. + + f : file-like + Where to write the file. + + prefix : string + The filename prefix. + + header : bool, optional + When True, a header comment is included on top of each source + file. [default : True] + + empty : bool, optional + When True, empty lines are included to structure the source + files. [default : True] + + """ + if header: + print(''.join(self._get_header()), file=f) + if empty: + print(file=f) + # declaration of the function prototypes + for routine in routines: + prototype = self.get_interface(routine) + f.write(prototype) + if empty: + print(file=f) + dump_h.extension = interface_extension # type: ignore + + # This list of dump functions is used by CodeGen.write to know which dump + # functions it has to call. + dump_fns = [dump_f95, dump_h] + + +class JuliaCodeGen(CodeGen): + """Generator for Julia code. + + The .write() method inherited from CodeGen will output a code file + .jl. + + """ + + code_extension = "jl" + + def __init__(self, project='project', printer=None): + super().__init__(project) + self.printer = printer or JuliaCodePrinter() + + def routine(self, name, expr, argument_sequence, global_vars): + """Specialized Routine creation for Julia.""" + + if is_sequence(expr) and not isinstance(expr, (MatrixBase, MatrixExpr)): + if not expr: + raise ValueError("No expression given") + expressions = Tuple(*expr) + else: + expressions = Tuple(expr) + + # local variables + local_vars = {i.label for i in expressions.atoms(Idx)} + + # global variables + global_vars = set() if global_vars is None else set(global_vars) + + # symbols that should be arguments + old_symbols = expressions.free_symbols - local_vars - global_vars + symbols = set() + for s in old_symbols: + if isinstance(s, Idx): + symbols.update(s.args[1].free_symbols) + elif not isinstance(s, Indexed): + symbols.add(s) + + # Julia supports multiple return values + return_vals = [] + output_args = [] + for (i, expr) in enumerate(expressions): + if isinstance(expr, Equality): + out_arg = expr.lhs + expr = expr.rhs + symbol = out_arg + if isinstance(out_arg, Indexed): + dims = tuple([ (S.One, dim) for dim in out_arg.shape]) + symbol = out_arg.base.label + output_args.append(InOutArgument(symbol, out_arg, expr, dimensions=dims)) + if not isinstance(out_arg, (Indexed, Symbol, MatrixSymbol)): + raise CodeGenError("Only Indexed, Symbol, or MatrixSymbol " + "can define output arguments.") + + return_vals.append(Result(expr, name=symbol, result_var=out_arg)) + if not expr.has(symbol): + # this is a pure output: remove from the symbols list, so + # it doesn't become an input. + symbols.remove(symbol) + + else: + # we have no name for this output + return_vals.append(Result(expr, name='out%d' % (i+1))) + + # setup input argument list + output_args.sort(key=lambda x: str(x.name)) + arg_list = list(output_args) + array_symbols = {} + for array in expressions.atoms(Indexed): + array_symbols[array.base.label] = array + for array in expressions.atoms(MatrixSymbol): + array_symbols[array] = array + + for symbol in sorted(symbols, key=str): + arg_list.append(InputArgument(symbol)) + + if argument_sequence is not None: + # if the user has supplied IndexedBase instances, we'll accept that + new_sequence = [] + for arg in argument_sequence: + if isinstance(arg, IndexedBase): + new_sequence.append(arg.label) + else: + new_sequence.append(arg) + argument_sequence = new_sequence + + missing = [x for x in arg_list if x.name not in argument_sequence] + if missing: + msg = "Argument list didn't specify: {0} " + msg = msg.format(", ".join([str(m.name) for m in missing])) + raise CodeGenArgumentListError(msg, missing) + + # create redundant arguments to produce the requested sequence + name_arg_dict = {x.name: x for x in arg_list} + new_args = [] + for symbol in argument_sequence: + try: + new_args.append(name_arg_dict[symbol]) + except KeyError: + new_args.append(InputArgument(symbol)) + arg_list = new_args + + return Routine(name, arg_list, return_vals, local_vars, global_vars) + + def _get_header(self): + """Writes a common header for the generated files.""" + code_lines = [] + tmp = header_comment % {"version": sympy_version, + "project": self.project} + for line in tmp.splitlines(): + if line == '': + code_lines.append("#\n") + else: + code_lines.append("# %s\n" % line) + return code_lines + + def _preprocessor_statements(self, prefix): + return [] + + def _get_routine_opening(self, routine): + """Returns the opening statements of the routine.""" + code_list = [] + code_list.append("function ") + + # Inputs + args = [] + for arg in routine.arguments: + if isinstance(arg, OutputArgument): + raise CodeGenError("Julia: invalid argument of type %s" % + str(type(arg))) + if isinstance(arg, (InputArgument, InOutArgument)): + args.append("%s" % self._get_symbol(arg.name)) + args = ", ".join(args) + code_list.append("%s(%s)\n" % (routine.name, args)) + code_list = [ "".join(code_list) ] + + return code_list + + def _declare_arguments(self, routine): + return [] + + def _declare_globals(self, routine): + return [] + + def _declare_locals(self, routine): + return [] + + def _get_routine_ending(self, routine): + outs = [] + for result in routine.results: + if isinstance(result, Result): + # Note: name not result_var; want `y` not `y[i]` for Indexed + s = self._get_symbol(result.name) + else: + raise CodeGenError("unexpected object in Routine results") + outs.append(s) + return ["return " + ", ".join(outs) + "\nend\n"] + + def _call_printer(self, routine): + declarations = [] + code_lines = [] + for result in routine.results: + if isinstance(result, Result): + assign_to = result.result_var + else: + raise CodeGenError("unexpected object in Routine results") + + constants, not_supported, jl_expr = self._printer_method_with_settings( + 'doprint', {"human": False, "strict": False}, result.expr, assign_to=assign_to) + + for obj, v in sorted(constants, key=str): + declarations.append( + "%s = %s\n" % (obj, v)) + for obj in sorted(not_supported, key=str): + if isinstance(obj, Function): + name = obj.func + else: + name = obj + declarations.append( + "# unsupported: %s\n" % (name)) + code_lines.append("%s\n" % (jl_expr)) + return declarations + code_lines + + def _indent_code(self, codelines): + # Note that indenting seems to happen twice, first + # statement-by-statement by JuliaPrinter then again here. + p = JuliaCodePrinter({'human': False, "strict": False}) + return p.indent_code(codelines) + + def dump_jl(self, routines, f, prefix, header=True, empty=True): + self.dump_code(routines, f, prefix, header, empty) + + dump_jl.extension = code_extension # type: ignore + dump_jl.__doc__ = CodeGen.dump_code.__doc__ + + # This list of dump functions is used by CodeGen.write to know which dump + # functions it has to call. + dump_fns = [dump_jl] + + +class OctaveCodeGen(CodeGen): + """Generator for Octave code. + + The .write() method inherited from CodeGen will output a code file + .m. + + Octave .m files usually contain one function. That function name should + match the filename (``prefix``). If you pass multiple ``name_expr`` pairs, + the latter ones are presumed to be private functions accessed by the + primary function. + + You should only pass inputs to ``argument_sequence``: outputs are ordered + according to their order in ``name_expr``. + + """ + + code_extension = "m" + + def __init__(self, project='project', printer=None): + super().__init__(project) + self.printer = printer or OctaveCodePrinter() + + def routine(self, name, expr, argument_sequence, global_vars): + """Specialized Routine creation for Octave.""" + + # FIXME: this is probably general enough for other high-level + # languages, perhaps its the C/Fortran one that is specialized! + + if is_sequence(expr) and not isinstance(expr, (MatrixBase, MatrixExpr)): + if not expr: + raise ValueError("No expression given") + expressions = Tuple(*expr) + else: + expressions = Tuple(expr) + + # local variables + local_vars = {i.label for i in expressions.atoms(Idx)} + + # global variables + global_vars = set() if global_vars is None else set(global_vars) + + # symbols that should be arguments + old_symbols = expressions.free_symbols - local_vars - global_vars + symbols = set() + for s in old_symbols: + if isinstance(s, Idx): + symbols.update(s.args[1].free_symbols) + elif not isinstance(s, Indexed): + symbols.add(s) + + # Octave supports multiple return values + return_vals = [] + for (i, expr) in enumerate(expressions): + if isinstance(expr, Equality): + out_arg = expr.lhs + expr = expr.rhs + symbol = out_arg + if isinstance(out_arg, Indexed): + symbol = out_arg.base.label + if not isinstance(out_arg, (Indexed, Symbol, MatrixSymbol)): + raise CodeGenError("Only Indexed, Symbol, or MatrixSymbol " + "can define output arguments.") + + return_vals.append(Result(expr, name=symbol, result_var=out_arg)) + if not expr.has(symbol): + # this is a pure output: remove from the symbols list, so + # it doesn't become an input. + symbols.remove(symbol) + + else: + # we have no name for this output + return_vals.append(Result(expr, name='out%d' % (i+1))) + + # setup input argument list + arg_list = [] + array_symbols = {} + for array in expressions.atoms(Indexed): + array_symbols[array.base.label] = array + for array in expressions.atoms(MatrixSymbol): + array_symbols[array] = array + + for symbol in sorted(symbols, key=str): + arg_list.append(InputArgument(symbol)) + + if argument_sequence is not None: + # if the user has supplied IndexedBase instances, we'll accept that + new_sequence = [] + for arg in argument_sequence: + if isinstance(arg, IndexedBase): + new_sequence.append(arg.label) + else: + new_sequence.append(arg) + argument_sequence = new_sequence + + missing = [x for x in arg_list if x.name not in argument_sequence] + if missing: + msg = "Argument list didn't specify: {0} " + msg = msg.format(", ".join([str(m.name) for m in missing])) + raise CodeGenArgumentListError(msg, missing) + + # create redundant arguments to produce the requested sequence + name_arg_dict = {x.name: x for x in arg_list} + new_args = [] + for symbol in argument_sequence: + try: + new_args.append(name_arg_dict[symbol]) + except KeyError: + new_args.append(InputArgument(symbol)) + arg_list = new_args + + return Routine(name, arg_list, return_vals, local_vars, global_vars) + + def _get_header(self): + """Writes a common header for the generated files.""" + code_lines = [] + tmp = header_comment % {"version": sympy_version, + "project": self.project} + for line in tmp.splitlines(): + if line == '': + code_lines.append("%\n") + else: + code_lines.append("%% %s\n" % line) + return code_lines + + def _preprocessor_statements(self, prefix): + return [] + + def _get_routine_opening(self, routine): + """Returns the opening statements of the routine.""" + code_list = [] + code_list.append("function ") + + # Outputs + outs = [] + for result in routine.results: + if isinstance(result, Result): + # Note: name not result_var; want `y` not `y(i)` for Indexed + s = self._get_symbol(result.name) + else: + raise CodeGenError("unexpected object in Routine results") + outs.append(s) + if len(outs) > 1: + code_list.append("[" + (", ".join(outs)) + "]") + else: + code_list.append("".join(outs)) + code_list.append(" = ") + + # Inputs + args = [] + for arg in routine.arguments: + if isinstance(arg, (OutputArgument, InOutArgument)): + raise CodeGenError("Octave: invalid argument of type %s" % + str(type(arg))) + if isinstance(arg, InputArgument): + args.append("%s" % self._get_symbol(arg.name)) + args = ", ".join(args) + code_list.append("%s(%s)\n" % (routine.name, args)) + code_list = [ "".join(code_list) ] + + return code_list + + def _declare_arguments(self, routine): + return [] + + def _declare_globals(self, routine): + if not routine.global_vars: + return [] + s = " ".join(sorted([self._get_symbol(g) for g in routine.global_vars])) + return ["global " + s + "\n"] + + def _declare_locals(self, routine): + return [] + + def _get_routine_ending(self, routine): + return ["end\n"] + + def _call_printer(self, routine): + declarations = [] + code_lines = [] + for result in routine.results: + if isinstance(result, Result): + assign_to = result.result_var + else: + raise CodeGenError("unexpected object in Routine results") + + constants, not_supported, oct_expr = self._printer_method_with_settings( + 'doprint', {"human": False, "strict": False}, result.expr, assign_to=assign_to) + + for obj, v in sorted(constants, key=str): + declarations.append( + " %s = %s; %% constant\n" % (obj, v)) + for obj in sorted(not_supported, key=str): + if isinstance(obj, Function): + name = obj.func + else: + name = obj + declarations.append( + " %% unsupported: %s\n" % (name)) + code_lines.append("%s\n" % (oct_expr)) + return declarations + code_lines + + def _indent_code(self, codelines): + return self._printer_method_with_settings( + 'indent_code', {"human": False, "strict": False}, codelines) + + def dump_m(self, routines, f, prefix, header=True, empty=True, inline=True): + # Note used to call self.dump_code() but we need more control for header + + code_lines = self._preprocessor_statements(prefix) + + for i, routine in enumerate(routines): + if i > 0: + if empty: + code_lines.append("\n") + code_lines.extend(self._get_routine_opening(routine)) + if i == 0: + if routine.name != prefix: + raise ValueError('Octave function name should match prefix') + if header: + code_lines.append("%" + prefix.upper() + + " Autogenerated by SymPy\n") + code_lines.append(''.join(self._get_header())) + code_lines.extend(self._declare_arguments(routine)) + code_lines.extend(self._declare_globals(routine)) + code_lines.extend(self._declare_locals(routine)) + if empty: + code_lines.append("\n") + code_lines.extend(self._call_printer(routine)) + if empty: + code_lines.append("\n") + code_lines.extend(self._get_routine_ending(routine)) + + code_lines = self._indent_code(''.join(code_lines)) + + if code_lines: + f.write(code_lines) + + dump_m.extension = code_extension # type: ignore + dump_m.__doc__ = CodeGen.dump_code.__doc__ + + # This list of dump functions is used by CodeGen.write to know which dump + # functions it has to call. + dump_fns = [dump_m] + +class RustCodeGen(CodeGen): + """Generator for Rust code. + + The .write() method inherited from CodeGen will output a code file + .rs + + """ + + code_extension = "rs" + + def __init__(self, project="project", printer=None): + super().__init__(project=project) + self.printer = printer or RustCodePrinter() + + def routine(self, name, expr, argument_sequence, global_vars): + """Specialized Routine creation for Rust.""" + + if is_sequence(expr) and not isinstance(expr, (MatrixBase, MatrixExpr)): + if not expr: + raise ValueError("No expression given") + expressions = Tuple(*expr) + else: + expressions = Tuple(expr) + + # local variables + local_vars = {i.label for i in expressions.atoms(Idx)} + + # global variables + global_vars = set() if global_vars is None else set(global_vars) + + # symbols that should be arguments + symbols = expressions.free_symbols - local_vars - global_vars - expressions.atoms(Indexed) + + # Rust supports multiple return values + return_vals = [] + output_args = [] + for (i, expr) in enumerate(expressions): + if isinstance(expr, Equality): + out_arg = expr.lhs + expr = expr.rhs + symbol = out_arg + if isinstance(out_arg, Indexed): + dims = tuple([ (S.One, dim) for dim in out_arg.shape]) + symbol = out_arg.base.label + output_args.append(InOutArgument(symbol, out_arg, expr, dimensions=dims)) + if not isinstance(out_arg, (Indexed, Symbol, MatrixSymbol)): + raise CodeGenError("Only Indexed, Symbol, or MatrixSymbol " + "can define output arguments.") + + return_vals.append(Result(expr, name=symbol, result_var=out_arg)) + if not expr.has(symbol): + # this is a pure output: remove from the symbols list, so + # it doesn't become an input. + symbols.remove(symbol) + + else: + # we have no name for this output + return_vals.append(Result(expr, name='out%d' % (i+1))) + + # setup input argument list + output_args.sort(key=lambda x: str(x.name)) + arg_list = list(output_args) + array_symbols = {} + for array in expressions.atoms(Indexed): + array_symbols[array.base.label] = array + for array in expressions.atoms(MatrixSymbol): + array_symbols[array] = array + + for symbol in sorted(symbols, key=str): + arg_list.append(InputArgument(symbol)) + + if argument_sequence is not None: + # if the user has supplied IndexedBase instances, we'll accept that + new_sequence = [] + for arg in argument_sequence: + if isinstance(arg, IndexedBase): + new_sequence.append(arg.label) + else: + new_sequence.append(arg) + argument_sequence = new_sequence + + missing = [x for x in arg_list if x.name not in argument_sequence] + if missing: + msg = "Argument list didn't specify: {0} " + msg = msg.format(", ".join([str(m.name) for m in missing])) + raise CodeGenArgumentListError(msg, missing) + + # create redundant arguments to produce the requested sequence + name_arg_dict = {x.name: x for x in arg_list} + new_args = [] + for symbol in argument_sequence: + try: + new_args.append(name_arg_dict[symbol]) + except KeyError: + new_args.append(InputArgument(symbol)) + arg_list = new_args + + return Routine(name, arg_list, return_vals, local_vars, global_vars) + + + def _get_header(self): + """Writes a common header for the generated files.""" + code_lines = [] + code_lines.append("/*\n") + tmp = header_comment % {"version": sympy_version, + "project": self.project} + for line in tmp.splitlines(): + code_lines.append((" *%s" % line.center(76)).rstrip() + "\n") + code_lines.append(" */\n") + return code_lines + + def get_prototype(self, routine): + """Returns a string for the function prototype of the routine. + + If the routine has multiple result objects, an CodeGenError is + raised. + + See: https://en.wikipedia.org/wiki/Function_prototype + + """ + results = [i.get_datatype('Rust') for i in routine.results] + + if len(results) == 1: + rstype = " -> " + results[0] + elif len(routine.results) > 1: + rstype = " -> (" + ", ".join(results) + ")" + else: + rstype = "" + + type_args = [] + for arg in routine.arguments: + name = self.printer.doprint(arg.name) + if arg.dimensions or isinstance(arg, ResultBase): + type_args.append(("*%s" % name, arg.get_datatype('Rust'))) + else: + type_args.append((name, arg.get_datatype('Rust'))) + arguments = ", ".join([ "%s: %s" % t for t in type_args]) + return "fn %s(%s)%s" % (routine.name, arguments, rstype) + + def _preprocessor_statements(self, prefix): + code_lines = [] + # code_lines.append("use std::f64::consts::*;\n") + return code_lines + + def _get_routine_opening(self, routine): + prototype = self.get_prototype(routine) + return ["%s {\n" % prototype] + + def _declare_arguments(self, routine): + # arguments are declared in prototype + return [] + + def _declare_globals(self, routine): + # global variables are not explicitly declared within C functions + return [] + + def _declare_locals(self, routine): + # loop variables are declared in loop statement + return [] + + def _call_printer(self, routine): + + code_lines = [] + declarations = [] + returns = [] + + # Compose a list of symbols to be dereferenced in the function + # body. These are the arguments that were passed by a reference + # pointer, excluding arrays. + dereference = [] + for arg in routine.arguments: + if isinstance(arg, ResultBase) and not arg.dimensions: + dereference.append(arg.name) + + for result in routine.results: + if isinstance(result, Result): + assign_to = result.result_var + returns.append(str(result.result_var)) + else: + raise CodeGenError("unexpected object in Routine results") + + constants, not_supported, rs_expr = self._printer_method_with_settings( + 'doprint', {"human": False, "strict": False}, result.expr, assign_to=assign_to) + + for name, value in sorted(constants, key=str): + declarations.append("const %s: f64 = %s;\n" % (name, value)) + + for obj in sorted(not_supported, key=str): + if isinstance(obj, Function): + name = obj.func + else: + name = obj + declarations.append("// unsupported: %s\n" % (name)) + + code_lines.append("let %s\n" % rs_expr) + + if len(returns) > 1: + returns = ['(' + ', '.join(returns) + ')'] + + returns.append('\n') + + return declarations + code_lines + returns + + def _get_routine_ending(self, routine): + return ["}\n"] + + def dump_rs(self, routines, f, prefix, header=True, empty=True): + self.dump_code(routines, f, prefix, header, empty) + + dump_rs.extension = code_extension # type: ignore + dump_rs.__doc__ = CodeGen.dump_code.__doc__ + + # This list of dump functions is used by CodeGen.write to know which dump + # functions it has to call. + dump_fns = [dump_rs] + + + + +def get_code_generator(language, project=None, standard=None, printer = None): + if language == 'C': + if standard is None: + pass + elif standard.lower() == 'c89': + language = 'C89' + elif standard.lower() == 'c99': + language = 'C99' + CodeGenClass = {"C": CCodeGen, "C89": C89CodeGen, "C99": C99CodeGen, + "F95": FCodeGen, "JULIA": JuliaCodeGen, + "OCTAVE": OctaveCodeGen, + "RUST": RustCodeGen}.get(language.upper()) + if CodeGenClass is None: + raise ValueError("Language '%s' is not supported." % language) + return CodeGenClass(project, printer) + + +# +# Friendly functions +# + + +def codegen(name_expr, language=None, prefix=None, project="project", + to_files=False, header=True, empty=True, argument_sequence=None, + global_vars=None, standard=None, code_gen=None, printer=None): + """Generate source code for expressions in a given language. + + Parameters + ========== + + name_expr : tuple, or list of tuples + A single (name, expression) tuple or a list of (name, expression) + tuples. Each tuple corresponds to a routine. If the expression is + an equality (an instance of class Equality) the left hand side is + considered an output argument. If expression is an iterable, then + the routine will have multiple outputs. + + language : string, + A string that indicates the source code language. This is case + insensitive. Currently, 'C', 'F95' and 'Octave' are supported. + 'Octave' generates code compatible with both Octave and Matlab. + + prefix : string, optional + A prefix for the names of the files that contain the source code. + Language-dependent suffixes will be appended. If omitted, the name + of the first name_expr tuple is used. + + project : string, optional + A project name, used for making unique preprocessor instructions. + [default: "project"] + + to_files : bool, optional + When True, the code will be written to one or more files with the + given prefix, otherwise strings with the names and contents of + these files are returned. [default: False] + + header : bool, optional + When True, a header is written on top of each source file. + [default: True] + + empty : bool, optional + When True, empty lines are used to structure the code. + [default: True] + + argument_sequence : iterable, optional + Sequence of arguments for the routine in a preferred order. A + CodeGenError is raised if required arguments are missing. + Redundant arguments are used without warning. If omitted, + arguments will be ordered alphabetically, but with all input + arguments first, and then output or in-out arguments. + + global_vars : iterable, optional + Sequence of global variables used by the routine. Variables + listed here will not show up as function arguments. + + standard : string, optional + + code_gen : CodeGen instance, optional + An instance of a CodeGen subclass. Overrides ``language``. + + printer : Printer instance, optional + An instance of a Printer subclass. + + Examples + ======== + + >>> from sympy.utilities.codegen import codegen + >>> from sympy.abc import x, y, z + >>> [(c_name, c_code), (h_name, c_header)] = codegen( + ... ("f", x+y*z), "C89", "test", header=False, empty=False) + >>> print(c_name) + test.c + >>> print(c_code) + #include "test.h" + #include + double f(double x, double y, double z) { + double f_result; + f_result = x + y*z; + return f_result; + } + + >>> print(h_name) + test.h + >>> print(c_header) + #ifndef PROJECT__TEST__H + #define PROJECT__TEST__H + double f(double x, double y, double z); + #endif + + + Another example using Equality objects to give named outputs. Here the + filename (prefix) is taken from the first (name, expr) pair. + + >>> from sympy.abc import f, g + >>> from sympy import Eq + >>> [(c_name, c_code), (h_name, c_header)] = codegen( + ... [("myfcn", x + y), ("fcn2", [Eq(f, 2*x), Eq(g, y)])], + ... "C99", header=False, empty=False) + >>> print(c_name) + myfcn.c + >>> print(c_code) + #include "myfcn.h" + #include + double myfcn(double x, double y) { + double myfcn_result; + myfcn_result = x + y; + return myfcn_result; + } + void fcn2(double x, double y, double *f, double *g) { + (*f) = 2*x; + (*g) = y; + } + + + If the generated function(s) will be part of a larger project where various + global variables have been defined, the 'global_vars' option can be used + to remove the specified variables from the function signature + + >>> from sympy.utilities.codegen import codegen + >>> from sympy.abc import x, y, z + >>> [(f_name, f_code), header] = codegen( + ... ("f", x+y*z), "F95", header=False, empty=False, + ... argument_sequence=(x, y), global_vars=(z,)) + >>> print(f_code) + REAL*8 function f(x, y) + implicit none + REAL*8, intent(in) :: x + REAL*8, intent(in) :: y + f = x + y*z + end function + + + """ + + # Initialize the code generator. + if language is None: + if code_gen is None: + raise ValueError("Need either language or code_gen") + else: + if code_gen is not None: + raise ValueError("You cannot specify both language and code_gen.") + code_gen = get_code_generator(language, project, standard, printer) + + if isinstance(name_expr[0], str): + # single tuple is given, turn it into a singleton list with a tuple. + name_expr = [name_expr] + + if prefix is None: + prefix = name_expr[0][0] + + # Construct Routines appropriate for this code_gen from (name, expr) pairs. + routines = [] + for name, expr in name_expr: + routines.append(code_gen.routine(name, expr, argument_sequence, + global_vars)) + + # Write the code. + return code_gen.write(routines, prefix, to_files, header, empty) + + +def make_routine(name, expr, argument_sequence=None, + global_vars=None, language="F95"): + """A factory that makes an appropriate Routine from an expression. + + Parameters + ========== + + name : string + The name of this routine in the generated code. + + expr : expression or list/tuple of expressions + A SymPy expression that the Routine instance will represent. If + given a list or tuple of expressions, the routine will be + considered to have multiple return values and/or output arguments. + + argument_sequence : list or tuple, optional + List arguments for the routine in a preferred order. If omitted, + the results are language dependent, for example, alphabetical order + or in the same order as the given expressions. + + global_vars : iterable, optional + Sequence of global variables used by the routine. Variables + listed here will not show up as function arguments. + + language : string, optional + Specify a target language. The Routine itself should be + language-agnostic but the precise way one is created, error + checking, etc depend on the language. [default: "F95"]. + + Notes + ===== + + A decision about whether to use output arguments or return values is made + depending on both the language and the particular mathematical expressions. + For an expression of type Equality, the left hand side is typically made + into an OutputArgument (or perhaps an InOutArgument if appropriate). + Otherwise, typically, the calculated expression is made a return values of + the routine. + + Examples + ======== + + >>> from sympy.utilities.codegen import make_routine + >>> from sympy.abc import x, y, f, g + >>> from sympy import Eq + >>> r = make_routine('test', [Eq(f, 2*x), Eq(g, x + y)]) + >>> [arg.result_var for arg in r.results] + [] + >>> [arg.name for arg in r.arguments] + [x, y, f, g] + >>> [arg.name for arg in r.result_variables] + [f, g] + >>> r.local_vars + set() + + Another more complicated example with a mixture of specified and + automatically-assigned names. Also has Matrix output. + + >>> from sympy import Matrix + >>> r = make_routine('fcn', [x*y, Eq(f, 1), Eq(g, x + g), Matrix([[x, 2]])]) + >>> [arg.result_var for arg in r.results] # doctest: +SKIP + [result_5397460570204848505] + >>> [arg.expr for arg in r.results] + [x*y] + >>> [arg.name for arg in r.arguments] # doctest: +SKIP + [x, y, f, g, out_8598435338387848786] + + We can examine the various arguments more closely: + + >>> from sympy.utilities.codegen import (InputArgument, OutputArgument, + ... InOutArgument) + >>> [a.name for a in r.arguments if isinstance(a, InputArgument)] + [x, y] + + >>> [a.name for a in r.arguments if isinstance(a, OutputArgument)] # doctest: +SKIP + [f, out_8598435338387848786] + >>> [a.expr for a in r.arguments if isinstance(a, OutputArgument)] + [1, Matrix([[x, 2]])] + + >>> [a.name for a in r.arguments if isinstance(a, InOutArgument)] + [g] + >>> [a.expr for a in r.arguments if isinstance(a, InOutArgument)] + [g + x] + + """ + + # initialize a new code generator + code_gen = get_code_generator(language) + + return code_gen.routine(name, expr, argument_sequence, global_vars) diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/decorator.py b/.venv/lib/python3.12/site-packages/sympy/utilities/decorator.py new file mode 100644 index 0000000000000000000000000000000000000000..82636c35e9f235a1d23aa7df5182418db3ef6b4f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/decorator.py @@ -0,0 +1,339 @@ +"""Useful utility decorators. """ + +from typing import TypeVar +import sys +import types +import inspect +from functools import wraps, update_wrapper + +from sympy.utilities.exceptions import sympy_deprecation_warning + + +T = TypeVar('T') +"""A generic type""" + + +def threaded_factory(func, use_add): + """A factory for ``threaded`` decorators. """ + from sympy.core import sympify + from sympy.matrices import MatrixBase + from sympy.utilities.iterables import iterable + + @wraps(func) + def threaded_func(expr, *args, **kwargs): + if isinstance(expr, MatrixBase): + return expr.applyfunc(lambda f: func(f, *args, **kwargs)) + elif iterable(expr): + try: + return expr.__class__([func(f, *args, **kwargs) for f in expr]) + except TypeError: + return expr + else: + expr = sympify(expr) + + if use_add and expr.is_Add: + return expr.__class__(*[ func(f, *args, **kwargs) for f in expr.args ]) + elif expr.is_Relational: + return expr.__class__(func(expr.lhs, *args, **kwargs), + func(expr.rhs, *args, **kwargs)) + else: + return func(expr, *args, **kwargs) + + return threaded_func + + +def threaded(func): + """Apply ``func`` to sub--elements of an object, including :class:`~.Add`. + + This decorator is intended to make it uniformly possible to apply a + function to all elements of composite objects, e.g. matrices, lists, tuples + and other iterable containers, or just expressions. + + This version of :func:`threaded` decorator allows threading over + elements of :class:`~.Add` class. If this behavior is not desirable + use :func:`xthreaded` decorator. + + Functions using this decorator must have the following signature:: + + @threaded + def function(expr, *args, **kwargs): + + """ + return threaded_factory(func, True) + + +def xthreaded(func): + """Apply ``func`` to sub--elements of an object, excluding :class:`~.Add`. + + This decorator is intended to make it uniformly possible to apply a + function to all elements of composite objects, e.g. matrices, lists, tuples + and other iterable containers, or just expressions. + + This version of :func:`threaded` decorator disallows threading over + elements of :class:`~.Add` class. If this behavior is not desirable + use :func:`threaded` decorator. + + Functions using this decorator must have the following signature:: + + @xthreaded + def function(expr, *args, **kwargs): + + """ + return threaded_factory(func, False) + + +def conserve_mpmath_dps(func): + """After the function finishes, resets the value of ``mpmath.mp.dps`` to + the value it had before the function was run.""" + import mpmath + + def func_wrapper(*args, **kwargs): + dps = mpmath.mp.dps + try: + return func(*args, **kwargs) + finally: + mpmath.mp.dps = dps + + func_wrapper = update_wrapper(func_wrapper, func) + return func_wrapper + + +class no_attrs_in_subclass: + """Don't 'inherit' certain attributes from a base class + + >>> from sympy.utilities.decorator import no_attrs_in_subclass + + >>> class A(object): + ... x = 'test' + + >>> A.x = no_attrs_in_subclass(A, A.x) + + >>> class B(A): + ... pass + + >>> hasattr(A, 'x') + True + >>> hasattr(B, 'x') + False + + """ + def __init__(self, cls, f): + self.cls = cls + self.f = f + + def __get__(self, instance, owner=None): + if owner == self.cls: + if hasattr(self.f, '__get__'): + return self.f.__get__(instance, owner) + return self.f + raise AttributeError + + +def doctest_depends_on(exe=None, modules=None, disable_viewers=None, + python_version=None, ground_types=None): + """ + Adds metadata about the dependencies which need to be met for doctesting + the docstrings of the decorated objects. + + ``exe`` should be a list of executables + + ``modules`` should be a list of modules + + ``disable_viewers`` should be a list of viewers for :func:`~sympy.printing.preview.preview` to disable + + ``python_version`` should be the minimum Python version required, as a tuple + (like ``(3, 0)``) + """ + dependencies = {} + if exe is not None: + dependencies['executables'] = exe + if modules is not None: + dependencies['modules'] = modules + if disable_viewers is not None: + dependencies['disable_viewers'] = disable_viewers + if python_version is not None: + dependencies['python_version'] = python_version + if ground_types is not None: + dependencies['ground_types'] = ground_types + + def skiptests(): + from sympy.testing.runtests import DependencyError, SymPyDocTests, PyTestReporter # lazy import + r = PyTestReporter() + t = SymPyDocTests(r, None) + try: + t._check_dependencies(**dependencies) + except DependencyError: + return True # Skip doctests + else: + return False # Run doctests + + def depends_on_deco(fn): + fn._doctest_depends_on = dependencies + fn.__doctest_skip__ = skiptests + + if inspect.isclass(fn): + fn._doctest_depdends_on = no_attrs_in_subclass( + fn, fn._doctest_depends_on) + fn.__doctest_skip__ = no_attrs_in_subclass( + fn, fn.__doctest_skip__) + return fn + + return depends_on_deco + + +def public(obj: T) -> T: + """ + Append ``obj``'s name to global ``__all__`` variable (call site). + + By using this decorator on functions or classes you achieve the same goal + as by filling ``__all__`` variables manually, you just do not have to repeat + yourself (object's name). You also know if object is public at definition + site, not at some random location (where ``__all__`` was set). + + Note that in multiple decorator setup (in almost all cases) ``@public`` + decorator must be applied before any other decorators, because it relies + on the pointer to object's global namespace. If you apply other decorators + first, ``@public`` may end up modifying the wrong namespace. + + Examples + ======== + + >>> from sympy.utilities.decorator import public + + >>> __all__ # noqa: F821 + Traceback (most recent call last): + ... + NameError: name '__all__' is not defined + + >>> @public + ... def some_function(): + ... pass + + >>> __all__ # noqa: F821 + ['some_function'] + + """ + if isinstance(obj, types.FunctionType): + ns = obj.__globals__ + name = obj.__name__ + elif isinstance(obj, (type(type), type)): + ns = sys.modules[obj.__module__].__dict__ + name = obj.__name__ + else: + raise TypeError("expected a function or a class, got %s" % obj) + + if "__all__" not in ns: + ns["__all__"] = [name] + else: + ns["__all__"].append(name) + + return obj + + +def memoize_property(propfunc): + """Property decorator that caches the value of potentially expensive + ``propfunc`` after the first evaluation. The cached value is stored in + the corresponding property name with an attached underscore.""" + attrname = '_' + propfunc.__name__ + sentinel = object() + + @wraps(propfunc) + def accessor(self): + val = getattr(self, attrname, sentinel) + if val is sentinel: + val = propfunc(self) + setattr(self, attrname, val) + return val + + return property(accessor) + + +def deprecated(message, *, deprecated_since_version, + active_deprecations_target, stacklevel=3): + ''' + Mark a function as deprecated. + + This decorator should be used if an entire function or class is + deprecated. If only a certain functionality is deprecated, you should use + :func:`~.warns_deprecated_sympy` directly. This decorator is just a + convenience. There is no functional difference between using this + decorator and calling ``warns_deprecated_sympy()`` at the top of the + function. + + The decorator takes the same arguments as + :func:`~.warns_deprecated_sympy`. See its + documentation for details on what the keywords to this decorator do. + + See the :ref:`deprecation-policy` document for details on when and how + things should be deprecated in SymPy. + + Examples + ======== + + >>> from sympy.utilities.decorator import deprecated + >>> from sympy import simplify + >>> @deprecated("""\ + ... The simplify_this(expr) function is deprecated. Use simplify(expr) + ... instead.""", deprecated_since_version="1.1", + ... active_deprecations_target='simplify-this-deprecation') + ... def simplify_this(expr): + ... """ + ... Simplify ``expr``. + ... + ... .. deprecated:: 1.1 + ... + ... The ``simplify_this`` function is deprecated. Use :func:`simplify` + ... instead. See its documentation for more information. See + ... :ref:`simplify-this-deprecation` for details. + ... + ... """ + ... return simplify(expr) + >>> from sympy.abc import x + >>> simplify_this(x*(x + 1) - x**2) # doctest: +SKIP + :1: SymPyDeprecationWarning: + + The simplify_this(expr) function is deprecated. Use simplify(expr) + instead. + + See https://docs.sympy.org/latest/explanation/active-deprecations.html#simplify-this-deprecation + for details. + + This has been deprecated since SymPy version 1.1. It + will be removed in a future version of SymPy. + + simplify_this(x) + x + + See Also + ======== + sympy.utilities.exceptions.SymPyDeprecationWarning + sympy.utilities.exceptions.sympy_deprecation_warning + sympy.utilities.exceptions.ignore_warnings + sympy.testing.pytest.warns_deprecated_sympy + + ''' + decorator_kwargs = {"deprecated_since_version": deprecated_since_version, + "active_deprecations_target": active_deprecations_target} + def deprecated_decorator(wrapped): + if hasattr(wrapped, '__mro__'): # wrapped is actually a class + class wrapper(wrapped): + __doc__ = wrapped.__doc__ + __module__ = wrapped.__module__ + _sympy_deprecated_func = wrapped + if '__new__' in wrapped.__dict__: + def __new__(cls, *args, **kwargs): + sympy_deprecation_warning(message, **decorator_kwargs, stacklevel=stacklevel) + return super().__new__(cls, *args, **kwargs) + else: + def __init__(self, *args, **kwargs): + sympy_deprecation_warning(message, **decorator_kwargs, stacklevel=stacklevel) + super().__init__(*args, **kwargs) + wrapper.__name__ = wrapped.__name__ + else: + @wraps(wrapped) + def wrapper(*args, **kwargs): + sympy_deprecation_warning(message, **decorator_kwargs, stacklevel=stacklevel) + return wrapped(*args, **kwargs) + wrapper._sympy_deprecated_func = wrapped + return wrapper + return deprecated_decorator diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/enumerative.py b/.venv/lib/python3.12/site-packages/sympy/utilities/enumerative.py new file mode 100644 index 0000000000000000000000000000000000000000..dcdabf064ad6291282b5905e7aed0ba9eb412d1a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/enumerative.py @@ -0,0 +1,1155 @@ +""" +Algorithms and classes to support enumerative combinatorics. + +Currently just multiset partitions, but more could be added. + +Terminology (following Knuth, algorithm 7.1.2.5M TAOCP) +*multiset* aaabbcccc has a *partition* aaabc | bccc + +The submultisets, aaabc and bccc of the partition are called +*parts*, or sometimes *vectors*. (Knuth notes that multiset +partitions can be thought of as partitions of vectors of integers, +where the ith element of the vector gives the multiplicity of +element i.) + +The values a, b and c are *components* of the multiset. These +correspond to elements of a set, but in a multiset can be present +with a multiplicity greater than 1. + +The algorithm deserves some explanation. + +Think of the part aaabc from the multiset above. If we impose an +ordering on the components of the multiset, we can represent a part +with a vector, in which the value of the first element of the vector +corresponds to the multiplicity of the first component in that +part. Thus, aaabc can be represented by the vector [3, 1, 1]. We +can also define an ordering on parts, based on the lexicographic +ordering of the vector (leftmost vector element, i.e., the element +with the smallest component number, is the most significant), so +that [3, 1, 1] > [3, 1, 0] and [3, 1, 1] > [2, 1, 4]. The ordering +on parts can be extended to an ordering on partitions: First, sort +the parts in each partition, left-to-right in decreasing order. Then +partition A is greater than partition B if A's leftmost/greatest +part is greater than B's leftmost part. If the leftmost parts are +equal, compare the second parts, and so on. + +In this ordering, the greatest partition of a given multiset has only +one part. The least partition is the one in which the components +are spread out, one per part. + +The enumeration algorithms in this file yield the partitions of the +argument multiset in decreasing order. The main data structure is a +stack of parts, corresponding to the current partition. An +important invariant is that the parts on the stack are themselves in +decreasing order. This data structure is decremented to find the +next smaller partition. Most often, decrementing the partition will +only involve adjustments to the smallest parts at the top of the +stack, much as adjacent integers *usually* differ only in their last +few digits. + +Knuth's algorithm uses two main operations on parts: + +Decrement - change the part so that it is smaller in the + (vector) lexicographic order, but reduced by the smallest amount possible. + For example, if the multiset has vector [5, + 3, 1], and the bottom/greatest part is [4, 2, 1], this part would + decrement to [4, 2, 0], while [4, 0, 0] would decrement to [3, 3, + 1]. A singleton part is never decremented -- [1, 0, 0] is not + decremented to [0, 3, 1]. Instead, the decrement operator needs + to fail for this case. In Knuth's pseudocode, the decrement + operator is step m5. + +Spread unallocated multiplicity - Once a part has been decremented, + it cannot be the rightmost part in the partition. There is some + multiplicity that has not been allocated, and new parts must be + created above it in the stack to use up this multiplicity. To + maintain the invariant that the parts on the stack are in + decreasing order, these new parts must be less than or equal to + the decremented part. + For example, if the multiset is [5, 3, 1], and its most + significant part has just been decremented to [5, 3, 0], the + spread operation will add a new part so that the stack becomes + [[5, 3, 0], [0, 0, 1]]. If the most significant part (for the + same multiset) has been decremented to [2, 0, 0] the stack becomes + [[2, 0, 0], [2, 0, 0], [1, 3, 1]]. In the pseudocode, the spread + operation for one part is step m2. The complete spread operation + is a loop of steps m2 and m3. + +In order to facilitate the spread operation, Knuth stores, for each +component of each part, not just the multiplicity of that component +in the part, but also the total multiplicity available for this +component in this part or any lesser part above it on the stack. + +One added twist is that Knuth does not represent the part vectors as +arrays. Instead, he uses a sparse representation, in which a +component of a part is represented as a component number (c), plus +the multiplicity of the component in that part (v) as well as the +total multiplicity available for that component (u). This saves +time that would be spent skipping over zeros. + +""" + +class PartComponent: + """Internal class used in support of the multiset partitions + enumerators and the associated visitor functions. + + Represents one component of one part of the current partition. + + A stack of these, plus an auxiliary frame array, f, represents a + partition of the multiset. + + Knuth's pseudocode makes c, u, and v separate arrays. + """ + + __slots__ = ('c', 'u', 'v') + + def __init__(self): + self.c = 0 # Component number + self.u = 0 # The as yet unpartitioned amount in component c + # *before* it is allocated by this triple + self.v = 0 # Amount of c component in the current part + # (v<=u). An invariant of the representation is + # that the next higher triple for this component + # (if there is one) will have a value of u-v in + # its u attribute. + + def __repr__(self): + "for debug/algorithm animation purposes" + return 'c:%d u:%d v:%d' % (self.c, self.u, self.v) + + def __eq__(self, other): + """Define value oriented equality, which is useful for testers""" + return (isinstance(other, self.__class__) and + self.c == other.c and + self.u == other.u and + self.v == other.v) + + def __ne__(self, other): + """Defined for consistency with __eq__""" + return not self == other + + +# This function tries to be a faithful implementation of algorithm +# 7.1.2.5M in Volume 4A, Combinatoral Algorithms, Part 1, of The Art +# of Computer Programming, by Donald Knuth. This includes using +# (mostly) the same variable names, etc. This makes for rather +# low-level Python. + +# Changes from Knuth's pseudocode include +# - use PartComponent struct/object instead of 3 arrays +# - make the function a generator +# - map (with some difficulty) the GOTOs to Python control structures. +# - Knuth uses 1-based numbering for components, this code is 0-based +# - renamed variable l to lpart. +# - flag variable x takes on values True/False instead of 1/0 +# +def multiset_partitions_taocp(multiplicities): + """Enumerates partitions of a multiset. + + Parameters + ========== + + multiplicities + list of integer multiplicities of the components of the multiset. + + Yields + ====== + + state + Internal data structure which encodes a particular partition. + This output is then usually processed by a visitor function + which combines the information from this data structure with + the components themselves to produce an actual partition. + + Unless they wish to create their own visitor function, users will + have little need to look inside this data structure. But, for + reference, it is a 3-element list with components: + + f + is a frame array, which is used to divide pstack into parts. + + lpart + points to the base of the topmost part. + + pstack + is an array of PartComponent objects. + + The ``state`` output offers a peek into the internal data + structures of the enumeration function. The client should + treat this as read-only; any modification of the data + structure will cause unpredictable (and almost certainly + incorrect) results. Also, the components of ``state`` are + modified in place at each iteration. Hence, the visitor must + be called at each loop iteration. Accumulating the ``state`` + instances and processing them later will not work. + + Examples + ======== + + >>> from sympy.utilities.enumerative import list_visitor + >>> from sympy.utilities.enumerative import multiset_partitions_taocp + >>> # variables components and multiplicities represent the multiset 'abb' + >>> components = 'ab' + >>> multiplicities = [1, 2] + >>> states = multiset_partitions_taocp(multiplicities) + >>> list(list_visitor(state, components) for state in states) + [[['a', 'b', 'b']], + [['a', 'b'], ['b']], + [['a'], ['b', 'b']], + [['a'], ['b'], ['b']]] + + See Also + ======== + + sympy.utilities.iterables.multiset_partitions: Takes a multiset + as input and directly yields multiset partitions. It + dispatches to a number of functions, including this one, for + implementation. Most users will find it more convenient to + use than multiset_partitions_taocp. + + """ + + # Important variables. + # m is the number of components, i.e., number of distinct elements + m = len(multiplicities) + # n is the cardinality, total number of elements whether or not distinct + n = sum(multiplicities) + + # The main data structure, f segments pstack into parts. See + # list_visitor() for example code indicating how this internal + # state corresponds to a partition. + + # Note: allocation of space for stack is conservative. Knuth's + # exercise 7.2.1.5.68 gives some indication of how to tighten this + # bound, but this is not implemented. + pstack = [PartComponent() for i in range(n * m + 1)] + f = [0] * (n + 1) + + # Step M1 in Knuth (Initialize) + # Initial state - entire multiset in one part. + for j in range(m): + ps = pstack[j] + ps.c = j + ps.u = multiplicities[j] + ps.v = multiplicities[j] + + # Other variables + f[0] = 0 + a = 0 + lpart = 0 + f[1] = m + b = m # in general, current stack frame is from a to b - 1 + + while True: + while True: + # Step M2 (Subtract v from u) + k = b + x = False + for j in range(a, b): + pstack[k].u = pstack[j].u - pstack[j].v + if pstack[k].u == 0: + x = True + elif not x: + pstack[k].c = pstack[j].c + pstack[k].v = min(pstack[j].v, pstack[k].u) + x = pstack[k].u < pstack[j].v + k = k + 1 + else: # x is True + pstack[k].c = pstack[j].c + pstack[k].v = pstack[k].u + k = k + 1 + # Note: x is True iff v has changed + + # Step M3 (Push if nonzero.) + if k > b: + a = b + b = k + lpart = lpart + 1 + f[lpart + 1] = b + # Return to M2 + else: + break # Continue to M4 + + # M4 Visit a partition + state = [f, lpart, pstack] + yield state + + # M5 (Decrease v) + while True: + j = b-1 + while (pstack[j].v == 0): + j = j - 1 + if j == a and pstack[j].v == 1: + # M6 (Backtrack) + if lpart == 0: + return + lpart = lpart - 1 + b = a + a = f[lpart] + # Return to M5 + else: + pstack[j].v = pstack[j].v - 1 + for k in range(j + 1, b): + pstack[k].v = pstack[k].u + break # GOTO M2 + +# --------------- Visitor functions for multiset partitions --------------- +# A visitor takes the partition state generated by +# multiset_partitions_taocp or other enumerator, and produces useful +# output (such as the actual partition). + + +def factoring_visitor(state, primes): + """Use with multiset_partitions_taocp to enumerate the ways a + number can be expressed as a product of factors. For this usage, + the exponents of the prime factors of a number are arguments to + the partition enumerator, while the corresponding prime factors + are input here. + + Examples + ======== + + To enumerate the factorings of a number we can think of the elements of the + partition as being the prime factors and the multiplicities as being their + exponents. + + >>> from sympy.utilities.enumerative import factoring_visitor + >>> from sympy.utilities.enumerative import multiset_partitions_taocp + >>> from sympy import factorint + >>> primes, multiplicities = zip(*factorint(24).items()) + >>> primes + (2, 3) + >>> multiplicities + (3, 1) + >>> states = multiset_partitions_taocp(multiplicities) + >>> list(factoring_visitor(state, primes) for state in states) + [[24], [8, 3], [12, 2], [4, 6], [4, 2, 3], [6, 2, 2], [2, 2, 2, 3]] + """ + f, lpart, pstack = state + factoring = [] + for i in range(lpart + 1): + factor = 1 + for ps in pstack[f[i]: f[i + 1]]: + if ps.v > 0: + factor *= primes[ps.c] ** ps.v + factoring.append(factor) + return factoring + + +def list_visitor(state, components): + """Return a list of lists to represent the partition. + + Examples + ======== + + >>> from sympy.utilities.enumerative import list_visitor + >>> from sympy.utilities.enumerative import multiset_partitions_taocp + >>> states = multiset_partitions_taocp([1, 2, 1]) + >>> s = next(states) + >>> list_visitor(s, 'abc') # for multiset 'a b b c' + [['a', 'b', 'b', 'c']] + >>> s = next(states) + >>> list_visitor(s, [1, 2, 3]) # for multiset '1 2 2 3 + [[1, 2, 2], [3]] + """ + f, lpart, pstack = state + + partition = [] + for i in range(lpart+1): + part = [] + for ps in pstack[f[i]:f[i+1]]: + if ps.v > 0: + part.extend([components[ps.c]] * ps.v) + partition.append(part) + + return partition + + +class MultisetPartitionTraverser(): + """ + Has methods to ``enumerate`` and ``count`` the partitions of a multiset. + + This implements a refactored and extended version of Knuth's algorithm + 7.1.2.5M [AOCP]_." + + The enumeration methods of this class are generators and return + data structures which can be interpreted by the same visitor + functions used for the output of ``multiset_partitions_taocp``. + + Examples + ======== + + >>> from sympy.utilities.enumerative import MultisetPartitionTraverser + >>> m = MultisetPartitionTraverser() + >>> m.count_partitions([4,4,4,2]) + 127750 + >>> m.count_partitions([3,3,3]) + 686 + + See Also + ======== + + multiset_partitions_taocp + sympy.utilities.iterables.multiset_partitions + + References + ========== + + .. [AOCP] Algorithm 7.1.2.5M in Volume 4A, Combinatoral Algorithms, + Part 1, of The Art of Computer Programming, by Donald Knuth. + + .. [Factorisatio] On a Problem of Oppenheim concerning + "Factorisatio Numerorum" E. R. Canfield, Paul Erdos, Carl + Pomerance, JOURNAL OF NUMBER THEORY, Vol. 17, No. 1. August + 1983. See section 7 for a description of an algorithm + similar to Knuth's. + + .. [Yorgey] Generating Multiset Partitions, Brent Yorgey, The + Monad.Reader, Issue 8, September 2007. + + """ + + def __init__(self): + self.debug = False + # TRACING variables. These are useful for gathering + # statistics on the algorithm itself, but have no particular + # benefit to a user of the code. + self.k1 = 0 + self.k2 = 0 + self.p1 = 0 + self.pstack = None + self.f = None + self.lpart = 0 + self.discarded = 0 + # dp_stack is list of lists of (part_key, start_count) pairs + self.dp_stack = [] + + # dp_map is map part_key-> count, where count represents the + # number of multiset which are descendants of a part with this + # key, **or any of its decrements** + + # Thus, when we find a part in the map, we add its count + # value to the running total, cut off the enumeration, and + # backtrack + + if not hasattr(self, 'dp_map'): + self.dp_map = {} + + def db_trace(self, msg): + """Useful for understanding/debugging the algorithms. Not + generally activated in end-user code.""" + if self.debug: + # XXX: animation_visitor is undefined... Clearly this does not + # work and was not tested. Previous code in comments below. + raise RuntimeError + #letters = 'abcdefghijklmnopqrstuvwxyz' + #state = [self.f, self.lpart, self.pstack] + #print("DBG:", msg, + # ["".join(part) for part in list_visitor(state, letters)], + # animation_visitor(state)) + + # + # Helper methods for enumeration + # + def _initialize_enumeration(self, multiplicities): + """Allocates and initializes the partition stack. + + This is called from the enumeration/counting routines, so + there is no need to call it separately.""" + + num_components = len(multiplicities) + # cardinality is the total number of elements, whether or not distinct + cardinality = sum(multiplicities) + + # pstack is the partition stack, which is segmented by + # f into parts. + self.pstack = [PartComponent() for i in + range(num_components * cardinality + 1)] + self.f = [0] * (cardinality + 1) + + # Initial state - entire multiset in one part. + for j in range(num_components): + ps = self.pstack[j] + ps.c = j + ps.u = multiplicities[j] + ps.v = multiplicities[j] + + self.f[0] = 0 + self.f[1] = num_components + self.lpart = 0 + + # The decrement_part() method corresponds to step M5 in Knuth's + # algorithm. This is the base version for enum_all(). Modified + # versions of this method are needed if we want to restrict + # sizes of the partitions produced. + def decrement_part(self, part): + """Decrements part (a subrange of pstack), if possible, returning + True iff the part was successfully decremented. + + If you think of the v values in the part as a multi-digit + integer (least significant digit on the right) this is + basically decrementing that integer, but with the extra + constraint that the leftmost digit cannot be decremented to 0. + + Parameters + ========== + + part + The part, represented as a list of PartComponent objects, + which is to be decremented. + + """ + plen = len(part) + for j in range(plen - 1, -1, -1): + if j == 0 and part[j].v > 1 or j > 0 and part[j].v > 0: + # found val to decrement + part[j].v -= 1 + # Reset trailing parts back to maximum + for k in range(j + 1, plen): + part[k].v = part[k].u + return True + return False + + # Version to allow number of parts to be bounded from above. + # Corresponds to (a modified) step M5. + def decrement_part_small(self, part, ub): + """Decrements part (a subrange of pstack), if possible, returning + True iff the part was successfully decremented. + + Parameters + ========== + + part + part to be decremented (topmost part on the stack) + + ub + the maximum number of parts allowed in a partition + returned by the calling traversal. + + Notes + ===== + + The goal of this modification of the ordinary decrement method + is to fail (meaning that the subtree rooted at this part is to + be skipped) when it can be proved that this part can only have + child partitions which are larger than allowed by ``ub``. If a + decision is made to fail, it must be accurate, otherwise the + enumeration will miss some partitions. But, it is OK not to + capture all the possible failures -- if a part is passed that + should not be, the resulting too-large partitions are filtered + by the enumeration one level up. However, as is usual in + constrained enumerations, failing early is advantageous. + + The tests used by this method catch the most common cases, + although this implementation is by no means the last word on + this problem. The tests include: + + 1) ``lpart`` must be less than ``ub`` by at least 2. This is because + once a part has been decremented, the partition + will gain at least one child in the spread step. + + 2) If the leading component of the part is about to be + decremented, check for how many parts will be added in + order to use up the unallocated multiplicity in that + leading component, and fail if this number is greater than + allowed by ``ub``. (See code for the exact expression.) This + test is given in the answer to Knuth's problem 7.2.1.5.69. + + 3) If there is *exactly* enough room to expand the leading + component by the above test, check the next component (if + it exists) once decrementing has finished. If this has + ``v == 0``, this next component will push the expansion over the + limit by 1, so fail. + """ + if self.lpart >= ub - 1: + self.p1 += 1 # increment to keep track of usefulness of tests + return False + plen = len(part) + for j in range(plen - 1, -1, -1): + # Knuth's mod, (answer to problem 7.2.1.5.69) + if j == 0 and (part[0].v - 1)*(ub - self.lpart) < part[0].u: + self.k1 += 1 + return False + + if j == 0 and part[j].v > 1 or j > 0 and part[j].v > 0: + # found val to decrement + part[j].v -= 1 + # Reset trailing parts back to maximum + for k in range(j + 1, plen): + part[k].v = part[k].u + + # Have now decremented part, but are we doomed to + # failure when it is expanded? Check one oddball case + # that turns out to be surprisingly common - exactly + # enough room to expand the leading component, but no + # room for the second component, which has v=0. + if (plen > 1 and part[1].v == 0 and + (part[0].u - part[0].v) == + ((ub - self.lpart - 1) * part[0].v)): + self.k2 += 1 + self.db_trace("Decrement fails test 3") + return False + return True + return False + + def decrement_part_large(self, part, amt, lb): + """Decrements part, while respecting size constraint. + + A part can have no children which are of sufficient size (as + indicated by ``lb``) unless that part has sufficient + unallocated multiplicity. When enforcing the size constraint, + this method will decrement the part (if necessary) by an + amount needed to ensure sufficient unallocated multiplicity. + + Returns True iff the part was successfully decremented. + + Parameters + ========== + + part + part to be decremented (topmost part on the stack) + + amt + Can only take values 0 or 1. A value of 1 means that the + part must be decremented, and then the size constraint is + enforced. A value of 0 means just to enforce the ``lb`` + size constraint. + + lb + The partitions produced by the calling enumeration must + have more parts than this value. + + """ + + if amt == 1: + # In this case we always need to decrement, *before* + # enforcing the "sufficient unallocated multiplicity" + # constraint. Easiest for this is just to call the + # regular decrement method. + if not self.decrement_part(part): + return False + + # Next, perform any needed additional decrementing to respect + # "sufficient unallocated multiplicity" (or fail if this is + # not possible). + min_unalloc = lb - self.lpart + if min_unalloc <= 0: + return True + total_mult = sum(pc.u for pc in part) + total_alloc = sum(pc.v for pc in part) + if total_mult <= min_unalloc: + return False + + deficit = min_unalloc - (total_mult - total_alloc) + if deficit <= 0: + return True + + for i in range(len(part) - 1, -1, -1): + if i == 0: + if part[0].v > deficit: + part[0].v -= deficit + return True + else: + return False # This shouldn't happen, due to above check + else: + if part[i].v >= deficit: + part[i].v -= deficit + return True + else: + deficit -= part[i].v + part[i].v = 0 + + def decrement_part_range(self, part, lb, ub): + """Decrements part (a subrange of pstack), if possible, returning + True iff the part was successfully decremented. + + Parameters + ========== + + part + part to be decremented (topmost part on the stack) + + ub + the maximum number of parts allowed in a partition + returned by the calling traversal. + + lb + The partitions produced by the calling enumeration must + have more parts than this value. + + Notes + ===== + + Combines the constraints of _small and _large decrement + methods. If returns success, part has been decremented at + least once, but perhaps by quite a bit more if needed to meet + the lb constraint. + """ + + # Constraint in the range case is just enforcing both the + # constraints from _small and _large cases. Note the 0 as the + # second argument to the _large call -- this is the signal to + # decrement only as needed to for constraint enforcement. The + # short circuiting and left-to-right order of the 'and' + # operator is important for this to work correctly. + return self.decrement_part_small(part, ub) and \ + self.decrement_part_large(part, 0, lb) + + def spread_part_multiplicity(self): + """Returns True if a new part has been created, and + adjusts pstack, f and lpart as needed. + + Notes + ===== + + Spreads unallocated multiplicity from the current top part + into a new part created above the current on the stack. This + new part is constrained to be less than or equal to the old in + terms of the part ordering. + + This call does nothing (and returns False) if the current top + part has no unallocated multiplicity. + + """ + j = self.f[self.lpart] # base of current top part + k = self.f[self.lpart + 1] # ub of current; potential base of next + base = k # save for later comparison + + changed = False # Set to true when the new part (so far) is + # strictly less than (as opposed to less than + # or equal) to the old. + for j in range(self.f[self.lpart], self.f[self.lpart + 1]): + self.pstack[k].u = self.pstack[j].u - self.pstack[j].v + if self.pstack[k].u == 0: + changed = True + else: + self.pstack[k].c = self.pstack[j].c + if changed: # Put all available multiplicity in this part + self.pstack[k].v = self.pstack[k].u + else: # Still maintaining ordering constraint + if self.pstack[k].u < self.pstack[j].v: + self.pstack[k].v = self.pstack[k].u + changed = True + else: + self.pstack[k].v = self.pstack[j].v + k = k + 1 + if k > base: + # Adjust for the new part on stack + self.lpart = self.lpart + 1 + self.f[self.lpart + 1] = k + return True + return False + + def top_part(self): + """Return current top part on the stack, as a slice of pstack. + + """ + return self.pstack[self.f[self.lpart]:self.f[self.lpart + 1]] + + # Same interface and functionality as multiset_partitions_taocp(), + # but some might find this refactored version easier to follow. + def enum_all(self, multiplicities): + """Enumerate the partitions of a multiset. + + Examples + ======== + + >>> from sympy.utilities.enumerative import list_visitor + >>> from sympy.utilities.enumerative import MultisetPartitionTraverser + >>> m = MultisetPartitionTraverser() + >>> states = m.enum_all([2,2]) + >>> list(list_visitor(state, 'ab') for state in states) + [[['a', 'a', 'b', 'b']], + [['a', 'a', 'b'], ['b']], + [['a', 'a'], ['b', 'b']], + [['a', 'a'], ['b'], ['b']], + [['a', 'b', 'b'], ['a']], + [['a', 'b'], ['a', 'b']], + [['a', 'b'], ['a'], ['b']], + [['a'], ['a'], ['b', 'b']], + [['a'], ['a'], ['b'], ['b']]] + + See Also + ======== + + multiset_partitions_taocp: + which provides the same result as this method, but is + about twice as fast. Hence, enum_all is primarily useful + for testing. Also see the function for a discussion of + states and visitors. + + """ + self._initialize_enumeration(multiplicities) + while True: + while self.spread_part_multiplicity(): + pass + + # M4 Visit a partition + state = [self.f, self.lpart, self.pstack] + yield state + + # M5 (Decrease v) + while not self.decrement_part(self.top_part()): + # M6 (Backtrack) + if self.lpart == 0: + return + self.lpart -= 1 + + def enum_small(self, multiplicities, ub): + """Enumerate multiset partitions with no more than ``ub`` parts. + + Equivalent to enum_range(multiplicities, 0, ub) + + Parameters + ========== + + multiplicities + list of multiplicities of the components of the multiset. + + ub + Maximum number of parts + + Examples + ======== + + >>> from sympy.utilities.enumerative import list_visitor + >>> from sympy.utilities.enumerative import MultisetPartitionTraverser + >>> m = MultisetPartitionTraverser() + >>> states = m.enum_small([2,2], 2) + >>> list(list_visitor(state, 'ab') for state in states) + [[['a', 'a', 'b', 'b']], + [['a', 'a', 'b'], ['b']], + [['a', 'a'], ['b', 'b']], + [['a', 'b', 'b'], ['a']], + [['a', 'b'], ['a', 'b']]] + + The implementation is based, in part, on the answer given to + exercise 69, in Knuth [AOCP]_. + + See Also + ======== + + enum_all, enum_large, enum_range + + """ + + # Keep track of iterations which do not yield a partition. + # Clearly, we would like to keep this number small. + self.discarded = 0 + if ub <= 0: + return + self._initialize_enumeration(multiplicities) + while True: + while self.spread_part_multiplicity(): + self.db_trace('spread 1') + if self.lpart >= ub: + self.discarded += 1 + self.db_trace(' Discarding') + self.lpart = ub - 2 + break + else: + # M4 Visit a partition + state = [self.f, self.lpart, self.pstack] + yield state + + # M5 (Decrease v) + while not self.decrement_part_small(self.top_part(), ub): + self.db_trace("Failed decrement, going to backtrack") + # M6 (Backtrack) + if self.lpart == 0: + return + self.lpart -= 1 + self.db_trace("Backtracked to") + self.db_trace("decrement ok, about to expand") + + def enum_large(self, multiplicities, lb): + """Enumerate the partitions of a multiset with lb < num(parts) + + Equivalent to enum_range(multiplicities, lb, sum(multiplicities)) + + Parameters + ========== + + multiplicities + list of multiplicities of the components of the multiset. + + lb + Number of parts in the partition must be greater than + this lower bound. + + + Examples + ======== + + >>> from sympy.utilities.enumerative import list_visitor + >>> from sympy.utilities.enumerative import MultisetPartitionTraverser + >>> m = MultisetPartitionTraverser() + >>> states = m.enum_large([2,2], 2) + >>> list(list_visitor(state, 'ab') for state in states) + [[['a', 'a'], ['b'], ['b']], + [['a', 'b'], ['a'], ['b']], + [['a'], ['a'], ['b', 'b']], + [['a'], ['a'], ['b'], ['b']]] + + See Also + ======== + + enum_all, enum_small, enum_range + + """ + self.discarded = 0 + if lb >= sum(multiplicities): + return + self._initialize_enumeration(multiplicities) + self.decrement_part_large(self.top_part(), 0, lb) + while True: + good_partition = True + while self.spread_part_multiplicity(): + if not self.decrement_part_large(self.top_part(), 0, lb): + # Failure here should be rare/impossible + self.discarded += 1 + good_partition = False + break + + # M4 Visit a partition + if good_partition: + state = [self.f, self.lpart, self.pstack] + yield state + + # M5 (Decrease v) + while not self.decrement_part_large(self.top_part(), 1, lb): + # M6 (Backtrack) + if self.lpart == 0: + return + self.lpart -= 1 + + def enum_range(self, multiplicities, lb, ub): + + """Enumerate the partitions of a multiset with + ``lb < num(parts) <= ub``. + + In particular, if partitions with exactly ``k`` parts are + desired, call with ``(multiplicities, k - 1, k)``. This + method generalizes enum_all, enum_small, and enum_large. + + Examples + ======== + + >>> from sympy.utilities.enumerative import list_visitor + >>> from sympy.utilities.enumerative import MultisetPartitionTraverser + >>> m = MultisetPartitionTraverser() + >>> states = m.enum_range([2,2], 1, 2) + >>> list(list_visitor(state, 'ab') for state in states) + [[['a', 'a', 'b'], ['b']], + [['a', 'a'], ['b', 'b']], + [['a', 'b', 'b'], ['a']], + [['a', 'b'], ['a', 'b']]] + + """ + # combine the constraints of the _large and _small + # enumerations. + self.discarded = 0 + if ub <= 0 or lb >= sum(multiplicities): + return + self._initialize_enumeration(multiplicities) + self.decrement_part_large(self.top_part(), 0, lb) + while True: + good_partition = True + while self.spread_part_multiplicity(): + self.db_trace("spread 1") + if not self.decrement_part_large(self.top_part(), 0, lb): + # Failure here - possible in range case? + self.db_trace(" Discarding (large cons)") + self.discarded += 1 + good_partition = False + break + elif self.lpart >= ub: + self.discarded += 1 + good_partition = False + self.db_trace(" Discarding small cons") + self.lpart = ub - 2 + break + + # M4 Visit a partition + if good_partition: + state = [self.f, self.lpart, self.pstack] + yield state + + # M5 (Decrease v) + while not self.decrement_part_range(self.top_part(), lb, ub): + self.db_trace("Failed decrement, going to backtrack") + # M6 (Backtrack) + if self.lpart == 0: + return + self.lpart -= 1 + self.db_trace("Backtracked to") + self.db_trace("decrement ok, about to expand") + + def count_partitions_slow(self, multiplicities): + """Returns the number of partitions of a multiset whose elements + have the multiplicities given in ``multiplicities``. + + Primarily for comparison purposes. It follows the same path as + enumerate, and counts, rather than generates, the partitions. + + See Also + ======== + + count_partitions + Has the same calling interface, but is much faster. + + """ + # number of partitions so far in the enumeration + self.pcount = 0 + self._initialize_enumeration(multiplicities) + while True: + while self.spread_part_multiplicity(): + pass + + # M4 Visit (count) a partition + self.pcount += 1 + + # M5 (Decrease v) + while not self.decrement_part(self.top_part()): + # M6 (Backtrack) + if self.lpart == 0: + return self.pcount + self.lpart -= 1 + + def count_partitions(self, multiplicities): + """Returns the number of partitions of a multiset whose components + have the multiplicities given in ``multiplicities``. + + For larger counts, this method is much faster than calling one + of the enumerators and counting the result. Uses dynamic + programming to cut down on the number of nodes actually + explored. The dictionary used in order to accelerate the + counting process is stored in the ``MultisetPartitionTraverser`` + object and persists across calls. If the user does not + expect to call ``count_partitions`` for any additional + multisets, the object should be cleared to save memory. On + the other hand, the cache built up from one count run can + significantly speed up subsequent calls to ``count_partitions``, + so it may be advantageous not to clear the object. + + Examples + ======== + + >>> from sympy.utilities.enumerative import MultisetPartitionTraverser + >>> m = MultisetPartitionTraverser() + >>> m.count_partitions([9,8,2]) + 288716 + >>> m.count_partitions([2,2]) + 9 + >>> del m + + Notes + ===== + + If one looks at the workings of Knuth's algorithm M [AOCP]_, it + can be viewed as a traversal of a binary tree of parts. A + part has (up to) two children, the left child resulting from + the spread operation, and the right child from the decrement + operation. The ordinary enumeration of multiset partitions is + an in-order traversal of this tree, and with the partitions + corresponding to paths from the root to the leaves. The + mapping from paths to partitions is a little complicated, + since the partition would contain only those parts which are + leaves or the parents of a spread link, not those which are + parents of a decrement link. + + For counting purposes, it is sufficient to count leaves, and + this can be done with a recursive in-order traversal. The + number of leaves of a subtree rooted at a particular part is a + function only of that part itself, so memoizing has the + potential to speed up the counting dramatically. + + This method follows a computational approach which is similar + to the hypothetical memoized recursive function, but with two + differences: + + 1) This method is iterative, borrowing its structure from the + other enumerations and maintaining an explicit stack of + parts which are in the process of being counted. (There + may be multisets which can be counted reasonably quickly by + this implementation, but which would overflow the default + Python recursion limit with a recursive implementation.) + + 2) Instead of using the part data structure directly, a more + compact key is constructed. This saves space, but more + importantly coalesces some parts which would remain + separate with physical keys. + + Unlike the enumeration functions, there is currently no _range + version of count_partitions. If someone wants to stretch + their brain, it should be possible to construct one by + memoizing with a histogram of counts rather than a single + count, and combining the histograms. + """ + # number of partitions so far in the enumeration + self.pcount = 0 + + # dp_stack is list of lists of (part_key, start_count) pairs + self.dp_stack = [] + + self._initialize_enumeration(multiplicities) + pkey = part_key(self.top_part()) + self.dp_stack.append([(pkey, 0), ]) + while True: + while self.spread_part_multiplicity(): + pkey = part_key(self.top_part()) + if pkey in self.dp_map: + # Already have a cached value for the count of the + # subtree rooted at this part. Add it to the + # running counter, and break out of the spread + # loop. The -1 below is to compensate for the + # leaf that this code path would otherwise find, + # and which gets incremented for below. + + self.pcount += (self.dp_map[pkey] - 1) + self.lpart -= 1 + break + else: + self.dp_stack.append([(pkey, self.pcount), ]) + + # M4 count a leaf partition + self.pcount += 1 + + # M5 (Decrease v) + while not self.decrement_part(self.top_part()): + # M6 (Backtrack) + for key, oldcount in self.dp_stack.pop(): + self.dp_map[key] = self.pcount - oldcount + if self.lpart == 0: + return self.pcount + self.lpart -= 1 + + # At this point have successfully decremented the part on + # the stack and it does not appear in the cache. It needs + # to be added to the list at the top of dp_stack + pkey = part_key(self.top_part()) + self.dp_stack[-1].append((pkey, self.pcount),) + + +def part_key(part): + """Helper for MultisetPartitionTraverser.count_partitions that + creates a key for ``part``, that only includes information which can + affect the count for that part. (Any irrelevant information just + reduces the effectiveness of dynamic programming.) + + Notes + ===== + + This member function is a candidate for future exploration. There + are likely symmetries that can be exploited to coalesce some + ``part_key`` values, and thereby save space and improve + performance. + + """ + # The component number is irrelevant for counting partitions, so + # leave it out of the memo key. + rval = [] + for ps in part: + rval.append(ps.u) + rval.append(ps.v) + return tuple(rval) diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/exceptions.py b/.venv/lib/python3.12/site-packages/sympy/utilities/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..f764a31371ed109d69102777bd9ec0dfb3d75380 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/exceptions.py @@ -0,0 +1,271 @@ +""" +General SymPy exceptions and warnings. +""" + +import warnings +import contextlib + +from textwrap import dedent + + +class SymPyDeprecationWarning(DeprecationWarning): + r""" + A warning for deprecated features of SymPy. + + See the :ref:`deprecation-policy` document for details on when and how + things should be deprecated in SymPy. + + Note that simply constructing this class will not cause a warning to be + issued. To do that, you must call the :func`sympy_deprecation_warning` + function. For this reason, it is not recommended to ever construct this + class directly. + + Explanation + =========== + + The ``SymPyDeprecationWarning`` class is a subclass of + ``DeprecationWarning`` that is used for all deprecations in SymPy. A + special subclass is used so that we can automatically augment the warning + message with additional metadata about the version the deprecation was + introduced in and a link to the documentation. This also allows users to + explicitly filter deprecation warnings from SymPy using ``warnings`` + filters (see :ref:`silencing-sympy-deprecation-warnings`). + + Additionally, ``SymPyDeprecationWarning`` is enabled to be shown by + default, unlike normal ``DeprecationWarning``\s, which are only shown by + default in interactive sessions. This ensures that deprecation warnings in + SymPy will actually be seen by users. + + See the documentation of :func:`sympy_deprecation_warning` for a + description of the parameters to this function. + + To mark a function as deprecated, you can use the :func:`@deprecated + ` decorator. + + See Also + ======== + sympy.utilities.exceptions.sympy_deprecation_warning + sympy.utilities.exceptions.ignore_warnings + sympy.utilities.decorator.deprecated + sympy.testing.pytest.warns_deprecated_sympy + + """ + def __init__(self, message, *, deprecated_since_version, active_deprecations_target): + + super().__init__(message, deprecated_since_version, + active_deprecations_target) + self.message = message + if not isinstance(deprecated_since_version, str): + raise TypeError(f"'deprecated_since_version' should be a string, got {deprecated_since_version!r}") + self.deprecated_since_version = deprecated_since_version + self.active_deprecations_target = active_deprecations_target + if any(i in active_deprecations_target for i in '()='): + raise ValueError("active_deprecations_target be the part inside of the '(...)='") + + self.full_message = f""" + +{dedent(message).strip()} + +See https://docs.sympy.org/latest/explanation/active-deprecations.html#{active_deprecations_target} +for details. + +This has been deprecated since SymPy version {deprecated_since_version}. It +will be removed in a future version of SymPy. +""" + + def __str__(self): + return self.full_message + + def __repr__(self): + return f"{self.__class__.__name__}({self.message!r}, deprecated_since_version={self.deprecated_since_version!r}, active_deprecations_target={self.active_deprecations_target!r})" + + def __eq__(self, other): + return isinstance(other, SymPyDeprecationWarning) and self.args == other.args + + # Make pickling work. The by default, it tries to recreate the expression + # from its args, but this doesn't work because of our keyword-only + # arguments. + @classmethod + def _new(cls, message, deprecated_since_version, + active_deprecations_target): + return cls(message, deprecated_since_version=deprecated_since_version, active_deprecations_target=active_deprecations_target) + + def __reduce__(self): + return (self._new, (self.message, self.deprecated_since_version, self.active_deprecations_target)) + +# Python by default hides DeprecationWarnings, which we do not want. +warnings.simplefilter("once", SymPyDeprecationWarning) + +def sympy_deprecation_warning(message, *, deprecated_since_version, + active_deprecations_target, stacklevel=3): + r''' + Warn that a feature is deprecated in SymPy. + + See the :ref:`deprecation-policy` document for details on when and how + things should be deprecated in SymPy. + + To mark an entire function or class as deprecated, you can use the + :func:`@deprecated ` decorator. + + Parameters + ========== + + message : str + The deprecation message. This may span multiple lines and contain + code examples. Messages should be wrapped to 80 characters. The + message is automatically dedented and leading and trailing whitespace + stripped. Messages may include dynamic content based on the user + input, but avoid using ``str(expression)`` if an expression can be + arbitrary, as it might be huge and make the warning message + unreadable. + + deprecated_since_version : str + The version of SymPy the feature has been deprecated since. For new + deprecations, this should be the version in `sympy/release.py + `_ + without the ``.dev``. If the next SymPy version ends up being + different from this, the release manager will need to update any + ``SymPyDeprecationWarning``\s using the incorrect version. This + argument is required and must be passed as a keyword argument. + (example: ``deprecated_since_version="1.10"``). + + active_deprecations_target : str + The Sphinx target corresponding to the section for the deprecation in + the :ref:`active-deprecations` document (see + ``doc/src/explanation/active-deprecations.md``). This is used to + automatically generate a URL to the page in the warning message. This + argument is required and must be passed as a keyword argument. + (example: ``active_deprecations_target="deprecated-feature-abc"``) + + stacklevel : int, default: 3 + The ``stacklevel`` parameter that is passed to ``warnings.warn``. If + you create a wrapper that calls this function, this should be + increased so that the warning message shows the user line of code that + produced the warning. Note that in some cases there will be multiple + possible different user code paths that could result in the warning. + In that case, just choose the smallest common stacklevel. + + Examples + ======== + + >>> from sympy.utilities.exceptions import sympy_deprecation_warning + >>> def is_this_zero(x, y=0): + ... """ + ... Determine if x = 0. + ... + ... Parameters + ... ========== + ... + ... x : Expr + ... The expression to check. + ... + ... y : Expr, optional + ... If provided, check if x = y. + ... + ... .. deprecated:: 1.1 + ... + ... The ``y`` argument to ``is_this_zero`` is deprecated. Use + ... ``is_this_zero(x - y)`` instead. + ... + ... """ + ... from sympy import simplify + ... + ... if y != 0: + ... sympy_deprecation_warning(""" + ... The y argument to is_zero() is deprecated. Use is_zero(x - y) instead.""", + ... deprecated_since_version="1.1", + ... active_deprecations_target='is-this-zero-y-deprecation') + ... return simplify(x - y) == 0 + >>> is_this_zero(0) + True + >>> is_this_zero(1, 1) # doctest: +SKIP + :1: SymPyDeprecationWarning: + + The y argument to is_zero() is deprecated. Use is_zero(x - y) instead. + + See https://docs.sympy.org/latest/explanation/active-deprecations.html#is-this-zero-y-deprecation + for details. + + This has been deprecated since SymPy version 1.1. It + will be removed in a future version of SymPy. + + is_this_zero(1, 1) + True + + See Also + ======== + + sympy.utilities.exceptions.SymPyDeprecationWarning + sympy.utilities.exceptions.ignore_warnings + sympy.utilities.decorator.deprecated + sympy.testing.pytest.warns_deprecated_sympy + + ''' + w = SymPyDeprecationWarning(message, + deprecated_since_version=deprecated_since_version, + active_deprecations_target=active_deprecations_target) + warnings.warn(w, stacklevel=stacklevel) + + +@contextlib.contextmanager +def ignore_warnings(warningcls): + ''' + Context manager to suppress warnings during tests. + + .. note:: + + Do not use this with SymPyDeprecationWarning in the tests. + warns_deprecated_sympy() should be used instead. + + This function is useful for suppressing warnings during tests. The warns + function should be used to assert that a warning is raised. The + ignore_warnings function is useful in situation when the warning is not + guaranteed to be raised (e.g. on importing a module) or if the warning + comes from third-party code. + + This function is also useful to prevent the same or similar warnings from + being issue twice due to recursive calls. + + When the warning is coming (reliably) from SymPy the warns function should + be preferred to ignore_warnings. + + >>> from sympy.utilities.exceptions import ignore_warnings + >>> import warnings + + Here's a warning: + + >>> with warnings.catch_warnings(): # reset warnings in doctest + ... warnings.simplefilter('error') + ... warnings.warn('deprecated', UserWarning) + Traceback (most recent call last): + ... + UserWarning: deprecated + + Let's suppress it with ignore_warnings: + + >>> with warnings.catch_warnings(): # reset warnings in doctest + ... warnings.simplefilter('error') + ... with ignore_warnings(UserWarning): + ... warnings.warn('deprecated', UserWarning) + + (No warning emitted) + + See Also + ======== + sympy.utilities.exceptions.SymPyDeprecationWarning + sympy.utilities.exceptions.sympy_deprecation_warning + sympy.utilities.decorator.deprecated + sympy.testing.pytest.warns_deprecated_sympy + + ''' + # Absorbs all warnings in warnrec + with warnings.catch_warnings(record=True) as warnrec: + # Make sure our warning doesn't get filtered + warnings.simplefilter("always", warningcls) + # Now run the test + yield + + # Reissue any warnings that we aren't testing for + for w in warnrec: + if not issubclass(w.category, warningcls): + warnings.warn_explicit(w.message, w.category, w.filename, w.lineno) diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/iterables.py b/.venv/lib/python3.12/site-packages/sympy/utilities/iterables.py new file mode 100644 index 0000000000000000000000000000000000000000..cc5c1152f03b10f62f9dd04c842b6fc74b0b9242 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/iterables.py @@ -0,0 +1,3179 @@ +from collections import Counter, defaultdict, OrderedDict +from itertools import ( + chain, combinations, combinations_with_replacement, cycle, islice, + permutations, product, groupby +) +# For backwards compatibility +from itertools import product as cartes # noqa: F401 +from operator import gt + + + +# this is the logical location of these functions +from sympy.utilities.enumerative import ( + multiset_partitions_taocp, list_visitor, MultisetPartitionTraverser) + +from sympy.utilities.misc import as_int +from sympy.utilities.decorator import deprecated + + +def is_palindromic(s, i=0, j=None): + """ + Return True if the sequence is the same from left to right as it + is from right to left in the whole sequence (default) or in the + Python slice ``s[i: j]``; else False. + + Examples + ======== + + >>> from sympy.utilities.iterables import is_palindromic + >>> is_palindromic([1, 0, 1]) + True + >>> is_palindromic('abcbb') + False + >>> is_palindromic('abcbb', 1) + False + + Normal Python slicing is performed in place so there is no need to + create a slice of the sequence for testing: + + >>> is_palindromic('abcbb', 1, -1) + True + >>> is_palindromic('abcbb', -4, -1) + True + + See Also + ======== + + sympy.ntheory.digits.is_palindromic: tests integers + + """ + i, j, _ = slice(i, j).indices(len(s)) + m = (j - i)//2 + # if length is odd, middle element will be ignored + return all(s[i + k] == s[j - 1 - k] for k in range(m)) + + +def flatten(iterable, levels=None, cls=None): # noqa: F811 + """ + Recursively denest iterable containers. + + >>> from sympy import flatten + + >>> flatten([1, 2, 3]) + [1, 2, 3] + >>> flatten([1, 2, [3]]) + [1, 2, 3] + >>> flatten([1, [2, 3], [4, 5]]) + [1, 2, 3, 4, 5] + >>> flatten([1.0, 2, (1, None)]) + [1.0, 2, 1, None] + + If you want to denest only a specified number of levels of + nested containers, then set ``levels`` flag to the desired + number of levels:: + + >>> ls = [[(-2, -1), (1, 2)], [(0, 0)]] + + >>> flatten(ls, levels=1) + [(-2, -1), (1, 2), (0, 0)] + + If cls argument is specified, it will only flatten instances of that + class, for example: + + >>> from sympy import Basic, S + >>> class MyOp(Basic): + ... pass + ... + >>> flatten([MyOp(S(1), MyOp(S(2), S(3)))], cls=MyOp) + [1, 2, 3] + + adapted from https://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks + """ + from sympy.tensor.array import NDimArray + if levels is not None: + if not levels: + return iterable + elif levels > 0: + levels -= 1 + else: + raise ValueError( + "expected non-negative number of levels, got %s" % levels) + + if cls is None: + def reducible(x): + return is_sequence(x, set) + else: + def reducible(x): + return isinstance(x, cls) + + result = [] + + for el in iterable: + if reducible(el): + if hasattr(el, 'args') and not isinstance(el, NDimArray): + el = el.args + result.extend(flatten(el, levels=levels, cls=cls)) + else: + result.append(el) + + return result + + +def unflatten(iter, n=2): + """Group ``iter`` into tuples of length ``n``. Raise an error if + the length of ``iter`` is not a multiple of ``n``. + """ + if n < 1 or len(iter) % n: + raise ValueError('iter length is not a multiple of %i' % n) + return list(zip(*(iter[i::n] for i in range(n)))) + + +def reshape(seq, how): + """Reshape the sequence according to the template in ``how``. + + Examples + ======== + + >>> from sympy.utilities import reshape + >>> seq = list(range(1, 9)) + + >>> reshape(seq, [4]) # lists of 4 + [[1, 2, 3, 4], [5, 6, 7, 8]] + + >>> reshape(seq, (4,)) # tuples of 4 + [(1, 2, 3, 4), (5, 6, 7, 8)] + + >>> reshape(seq, (2, 2)) # tuples of 4 + [(1, 2, 3, 4), (5, 6, 7, 8)] + + >>> reshape(seq, (2, [2])) # (i, i, [i, i]) + [(1, 2, [3, 4]), (5, 6, [7, 8])] + + >>> reshape(seq, ((2,), [2])) # etc.... + [((1, 2), [3, 4]), ((5, 6), [7, 8])] + + >>> reshape(seq, (1, [2], 1)) + [(1, [2, 3], 4), (5, [6, 7], 8)] + + >>> reshape(tuple(seq), ([[1], 1, (2,)],)) + (([[1], 2, (3, 4)],), ([[5], 6, (7, 8)],)) + + >>> reshape(tuple(seq), ([1], 1, (2,))) + (([1], 2, (3, 4)), ([5], 6, (7, 8))) + + >>> reshape(list(range(12)), [2, [3], {2}, (1, (3,), 1)]) + [[0, 1, [2, 3, 4], {5, 6}, (7, (8, 9, 10), 11)]] + + """ + m = sum(flatten(how)) + n, rem = divmod(len(seq), m) + if m < 0 or rem: + raise ValueError('template must sum to positive number ' + 'that divides the length of the sequence') + i = 0 + container = type(how) + rv = [None]*n + for k in range(len(rv)): + _rv = [] + for hi in how: + if isinstance(hi, int): + _rv.extend(seq[i: i + hi]) + i += hi + else: + n = sum(flatten(hi)) + hi_type = type(hi) + _rv.append(hi_type(reshape(seq[i: i + n], hi)[0])) + i += n + rv[k] = container(_rv) + return type(seq)(rv) + + +def group(seq, multiple=True): + """ + Splits a sequence into a list of lists of equal, adjacent elements. + + Examples + ======== + + >>> from sympy import group + + >>> group([1, 1, 1, 2, 2, 3]) + [[1, 1, 1], [2, 2], [3]] + >>> group([1, 1, 1, 2, 2, 3], multiple=False) + [(1, 3), (2, 2), (3, 1)] + >>> group([1, 1, 3, 2, 2, 1], multiple=False) + [(1, 2), (3, 1), (2, 2), (1, 1)] + + See Also + ======== + + multiset + + """ + if multiple: + return [(list(g)) for _, g in groupby(seq)] + return [(k, len(list(g))) for k, g in groupby(seq)] + + +def _iproduct2(iterable1, iterable2): + '''Cartesian product of two possibly infinite iterables''' + + it1 = iter(iterable1) + it2 = iter(iterable2) + + elems1 = [] + elems2 = [] + + sentinel = object() + def append(it, elems): + e = next(it, sentinel) + if e is not sentinel: + elems.append(e) + + n = 0 + append(it1, elems1) + append(it2, elems2) + + while n <= len(elems1) + len(elems2): + for m in range(n-len(elems1)+1, len(elems2)): + yield (elems1[n-m], elems2[m]) + n += 1 + append(it1, elems1) + append(it2, elems2) + + +def iproduct(*iterables): + ''' + Cartesian product of iterables. + + Generator of the Cartesian product of iterables. This is analogous to + itertools.product except that it works with infinite iterables and will + yield any item from the infinite product eventually. + + Examples + ======== + + >>> from sympy.utilities.iterables import iproduct + >>> sorted(iproduct([1,2], [3,4])) + [(1, 3), (1, 4), (2, 3), (2, 4)] + + With an infinite iterator: + + >>> from sympy import S + >>> (3,) in iproduct(S.Integers) + True + >>> (3, 4) in iproduct(S.Integers, S.Integers) + True + + .. seealso:: + + `itertools.product + `_ + ''' + if len(iterables) == 0: + yield () + return + elif len(iterables) == 1: + for e in iterables[0]: + yield (e,) + elif len(iterables) == 2: + yield from _iproduct2(*iterables) + else: + first, others = iterables[0], iterables[1:] + for ef, eo in _iproduct2(first, iproduct(*others)): + yield (ef,) + eo + + +def multiset(seq): + """Return the hashable sequence in multiset form with values being the + multiplicity of the item in the sequence. + + Examples + ======== + + >>> from sympy.utilities.iterables import multiset + >>> multiset('mississippi') + {'i': 4, 'm': 1, 'p': 2, 's': 4} + + See Also + ======== + + group + + """ + return dict(Counter(seq).items()) + + + + +def ibin(n, bits=None, str=False): + """Return a list of length ``bits`` corresponding to the binary value + of ``n`` with small bits to the right (last). If bits is omitted, the + length will be the number required to represent ``n``. If the bits are + desired in reversed order, use the ``[::-1]`` slice of the returned list. + + If a sequence of all bits-length lists starting from ``[0, 0,..., 0]`` + through ``[1, 1, ..., 1]`` are desired, pass a non-integer for bits, e.g. + ``'all'``. + + If the bit *string* is desired pass ``str=True``. + + Examples + ======== + + >>> from sympy.utilities.iterables import ibin + >>> ibin(2) + [1, 0] + >>> ibin(2, 4) + [0, 0, 1, 0] + + If all lists corresponding to 0 to 2**n - 1, pass a non-integer + for bits: + + >>> bits = 2 + >>> for i in ibin(2, 'all'): + ... print(i) + (0, 0) + (0, 1) + (1, 0) + (1, 1) + + If a bit string is desired of a given length, use str=True: + + >>> n = 123 + >>> bits = 10 + >>> ibin(n, bits, str=True) + '0001111011' + >>> ibin(n, bits, str=True)[::-1] # small bits left + '1101111000' + >>> list(ibin(3, 'all', str=True)) + ['000', '001', '010', '011', '100', '101', '110', '111'] + + """ + if n < 0: + raise ValueError("negative numbers are not allowed") + n = as_int(n) + + if bits is None: + bits = 0 + else: + try: + bits = as_int(bits) + except ValueError: + bits = -1 + else: + if n.bit_length() > bits: + raise ValueError( + "`bits` must be >= {}".format(n.bit_length())) + + if not str: + if bits >= 0: + return [1 if i == "1" else 0 for i in bin(n)[2:].rjust(bits, "0")] + else: + return variations(range(2), n, repetition=True) + else: + if bits >= 0: + return bin(n)[2:].rjust(bits, "0") + else: + return (bin(i)[2:].rjust(n, "0") for i in range(2**n)) + + +def variations(seq, n, repetition=False): + r"""Returns an iterator over the n-sized variations of ``seq`` (size N). + ``repetition`` controls whether items in ``seq`` can appear more than once; + + Examples + ======== + + ``variations(seq, n)`` will return `\frac{N!}{(N - n)!}` permutations without + repetition of ``seq``'s elements: + + >>> from sympy import variations + >>> list(variations([1, 2], 2)) + [(1, 2), (2, 1)] + + ``variations(seq, n, True)`` will return the `N^n` permutations obtained + by allowing repetition of elements: + + >>> list(variations([1, 2], 2, repetition=True)) + [(1, 1), (1, 2), (2, 1), (2, 2)] + + If you ask for more items than are in the set you get the empty set unless + you allow repetitions: + + >>> list(variations([0, 1], 3, repetition=False)) + [] + >>> list(variations([0, 1], 3, repetition=True))[:4] + [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1)] + + .. seealso:: + + `itertools.permutations + `_, + `itertools.product + `_ + """ + if not repetition: + seq = tuple(seq) + if len(seq) < n: + return iter(()) # 0 length iterator + return permutations(seq, n) + else: + if n == 0: + return iter(((),)) # yields 1 empty tuple + else: + return product(seq, repeat=n) + + +def subsets(seq, k=None, repetition=False): + r"""Generates all `k`-subsets (combinations) from an `n`-element set, ``seq``. + + A `k`-subset of an `n`-element set is any subset of length exactly `k`. The + number of `k`-subsets of an `n`-element set is given by ``binomial(n, k)``, + whereas there are `2^n` subsets all together. If `k` is ``None`` then all + `2^n` subsets will be returned from shortest to longest. + + Examples + ======== + + >>> from sympy import subsets + + ``subsets(seq, k)`` will return the + `\frac{n!}{k!(n - k)!}` `k`-subsets (combinations) + without repetition, i.e. once an item has been removed, it can no + longer be "taken": + + >>> list(subsets([1, 2], 2)) + [(1, 2)] + >>> list(subsets([1, 2])) + [(), (1,), (2,), (1, 2)] + >>> list(subsets([1, 2, 3], 2)) + [(1, 2), (1, 3), (2, 3)] + + + ``subsets(seq, k, repetition=True)`` will return the + `\frac{(n - 1 + k)!}{k!(n - 1)!}` + combinations *with* repetition: + + >>> list(subsets([1, 2], 2, repetition=True)) + [(1, 1), (1, 2), (2, 2)] + + If you ask for more items than are in the set you get the empty set unless + you allow repetitions: + + >>> list(subsets([0, 1], 3, repetition=False)) + [] + >>> list(subsets([0, 1], 3, repetition=True)) + [(0, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1)] + + """ + if k is None: + if not repetition: + return chain.from_iterable((combinations(seq, k) + for k in range(len(seq) + 1))) + else: + return chain.from_iterable((combinations_with_replacement(seq, k) + for k in range(len(seq) + 1))) + else: + if not repetition: + return combinations(seq, k) + else: + return combinations_with_replacement(seq, k) + + +def filter_symbols(iterator, exclude): + """ + Only yield elements from `iterator` that do not occur in `exclude`. + + Parameters + ========== + + iterator : iterable + iterator to take elements from + + exclude : iterable + elements to exclude + + Returns + ======= + + iterator : iterator + filtered iterator + """ + exclude = set(exclude) + for s in iterator: + if s not in exclude: + yield s + +def numbered_symbols(prefix='x', cls=None, start=0, exclude=(), *args, **assumptions): + """ + Generate an infinite stream of Symbols consisting of a prefix and + increasing subscripts provided that they do not occur in ``exclude``. + + Parameters + ========== + + prefix : str, optional + The prefix to use. By default, this function will generate symbols of + the form "x0", "x1", etc. + + cls : class, optional + The class to use. By default, it uses ``Symbol``, but you can also use ``Wild`` + or ``Dummy``. + + start : int, optional + The start number. By default, it is 0. + + exclude : list, tuple, set of cls, optional + Symbols to be excluded. + + *args, **kwargs + Additional positional and keyword arguments are passed to the *cls* class. + + Returns + ======= + + sym : Symbol + The subscripted symbols. + """ + exclude = set(exclude or []) + if cls is None: + # We can't just make the default cls=Symbol because it isn't + # imported yet. + from sympy.core import Symbol + cls = Symbol + + while True: + name = '%s%s' % (prefix, start) + s = cls(name, *args, **assumptions) + if s not in exclude: + yield s + start += 1 + + +def capture(func): + """Return the printed output of func(). + + ``func`` should be a function without arguments that produces output with + print statements. + + >>> from sympy.utilities.iterables import capture + >>> from sympy import pprint + >>> from sympy.abc import x + >>> def foo(): + ... print('hello world!') + ... + >>> 'hello' in capture(foo) # foo, not foo() + True + >>> capture(lambda: pprint(2/x)) + '2\\n-\\nx\\n' + + """ + from io import StringIO + import sys + + stdout = sys.stdout + sys.stdout = file = StringIO() + try: + func() + finally: + sys.stdout = stdout + return file.getvalue() + + +def sift(seq, keyfunc, binary=False): + """ + Sift the sequence, ``seq`` according to ``keyfunc``. + + Returns + ======= + + When ``binary`` is ``False`` (default), the output is a dictionary + where elements of ``seq`` are stored in a list keyed to the value + of keyfunc for that element. If ``binary`` is True then a tuple + with lists ``T`` and ``F`` are returned where ``T`` is a list + containing elements of seq for which ``keyfunc`` was ``True`` and + ``F`` containing those elements for which ``keyfunc`` was ``False``; + a ValueError is raised if the ``keyfunc`` is not binary. + + Examples + ======== + + >>> from sympy.utilities import sift + >>> from sympy.abc import x, y + >>> from sympy import sqrt, exp, pi, Tuple + + >>> sift(range(5), lambda x: x % 2) + {0: [0, 2, 4], 1: [1, 3]} + + sift() returns a defaultdict() object, so any key that has no matches will + give []. + + >>> sift([x], lambda x: x.is_commutative) + {True: [x]} + >>> _[False] + [] + + Sometimes you will not know how many keys you will get: + + >>> sift([sqrt(x), exp(x), (y**x)**2], + ... lambda x: x.as_base_exp()[0]) + {E: [exp(x)], x: [sqrt(x)], y: [y**(2*x)]} + + Sometimes you expect the results to be binary; the + results can be unpacked by setting ``binary`` to True: + + >>> sift(range(4), lambda x: x % 2, binary=True) + ([1, 3], [0, 2]) + >>> sift(Tuple(1, pi), lambda x: x.is_rational, binary=True) + ([1], [pi]) + + A ValueError is raised if the predicate was not actually binary + (which is a good test for the logic where sifting is used and + binary results were expected): + + >>> unknown = exp(1) - pi # the rationality of this is unknown + >>> args = Tuple(1, pi, unknown) + >>> sift(args, lambda x: x.is_rational, binary=True) + Traceback (most recent call last): + ... + ValueError: keyfunc gave non-binary output + + The non-binary sifting shows that there were 3 keys generated: + + >>> set(sift(args, lambda x: x.is_rational).keys()) + {None, False, True} + + If you need to sort the sifted items it might be better to use + ``ordered`` which can economically apply multiple sort keys + to a sequence while sorting. + + See Also + ======== + + ordered + + """ + if not binary: + m = defaultdict(list) + for i in seq: + m[keyfunc(i)].append(i) + return m + sift = F, T = [], [] + for i in seq: + try: + sift[keyfunc(i)].append(i) + except (IndexError, TypeError): + raise ValueError('keyfunc gave non-binary output') + return T, F + + +def take(iter, n): + """Return ``n`` items from ``iter`` iterator. """ + return [ value for _, value in zip(range(n), iter) ] + + +def dict_merge(*dicts): + """Merge dictionaries into a single dictionary. """ + merged = {} + + for dict in dicts: + merged.update(dict) + + return merged + + +def common_prefix(*seqs): + """Return the subsequence that is a common start of sequences in ``seqs``. + + >>> from sympy.utilities.iterables import common_prefix + >>> common_prefix(list(range(3))) + [0, 1, 2] + >>> common_prefix(list(range(3)), list(range(4))) + [0, 1, 2] + >>> common_prefix([1, 2, 3], [1, 2, 5]) + [1, 2] + >>> common_prefix([1, 2, 3], [1, 3, 5]) + [1] + """ + if not all(seqs): + return [] + elif len(seqs) == 1: + return seqs[0] + i = 0 + for i in range(min(len(s) for s in seqs)): + if not all(seqs[j][i] == seqs[0][i] for j in range(len(seqs))): + break + else: + i += 1 + return seqs[0][:i] + + +def common_suffix(*seqs): + """Return the subsequence that is a common ending of sequences in ``seqs``. + + >>> from sympy.utilities.iterables import common_suffix + >>> common_suffix(list(range(3))) + [0, 1, 2] + >>> common_suffix(list(range(3)), list(range(4))) + [] + >>> common_suffix([1, 2, 3], [9, 2, 3]) + [2, 3] + >>> common_suffix([1, 2, 3], [9, 7, 3]) + [3] + """ + + if not all(seqs): + return [] + elif len(seqs) == 1: + return seqs[0] + i = 0 + for i in range(-1, -min(len(s) for s in seqs) - 1, -1): + if not all(seqs[j][i] == seqs[0][i] for j in range(len(seqs))): + break + else: + i -= 1 + if i == -1: + return [] + else: + return seqs[0][i + 1:] + + +def prefixes(seq): + """ + Generate all prefixes of a sequence. + + Examples + ======== + + >>> from sympy.utilities.iterables import prefixes + + >>> list(prefixes([1,2,3,4])) + [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]] + + """ + n = len(seq) + + for i in range(n): + yield seq[:i + 1] + + +def postfixes(seq): + """ + Generate all postfixes of a sequence. + + Examples + ======== + + >>> from sympy.utilities.iterables import postfixes + + >>> list(postfixes([1,2,3,4])) + [[4], [3, 4], [2, 3, 4], [1, 2, 3, 4]] + + """ + n = len(seq) + + for i in range(n): + yield seq[n - i - 1:] + + +def topological_sort(graph, key=None): + r""" + Topological sort of graph's vertices. + + Parameters + ========== + + graph : tuple[list, list[tuple[T, T]] + A tuple consisting of a list of vertices and a list of edges of + a graph to be sorted topologically. + + key : callable[T] (optional) + Ordering key for vertices on the same level. By default the natural + (e.g. lexicographic) ordering is used (in this case the base type + must implement ordering relations). + + Examples + ======== + + Consider a graph:: + + +---+ +---+ +---+ + | 7 |\ | 5 | | 3 | + +---+ \ +---+ +---+ + | _\___/ ____ _/ | + | / \___/ \ / | + V V V V | + +----+ +---+ | + | 11 | | 8 | | + +----+ +---+ | + | | \____ ___/ _ | + | \ \ / / \ | + V \ V V / V V + +---+ \ +---+ | +----+ + | 2 | | | 9 | | | 10 | + +---+ | +---+ | +----+ + \________/ + + where vertices are integers. This graph can be encoded using + elementary Python's data structures as follows:: + + >>> V = [2, 3, 5, 7, 8, 9, 10, 11] + >>> E = [(7, 11), (7, 8), (5, 11), (3, 8), (3, 10), + ... (11, 2), (11, 9), (11, 10), (8, 9)] + + To compute a topological sort for graph ``(V, E)`` issue:: + + >>> from sympy.utilities.iterables import topological_sort + + >>> topological_sort((V, E)) + [3, 5, 7, 8, 11, 2, 9, 10] + + If specific tie breaking approach is needed, use ``key`` parameter:: + + >>> topological_sort((V, E), key=lambda v: -v) + [7, 5, 11, 3, 10, 8, 9, 2] + + Only acyclic graphs can be sorted. If the input graph has a cycle, + then ``ValueError`` will be raised:: + + >>> topological_sort((V, E + [(10, 7)])) + Traceback (most recent call last): + ... + ValueError: cycle detected + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Topological_sorting + + """ + V, E = graph + + L = [] + S = set(V) + E = list(E) + + S.difference_update(u for v, u in E) + + if key is None: + def key(value): + return value + + S = sorted(S, key=key, reverse=True) + + while S: + node = S.pop() + L.append(node) + + for u, v in list(E): + if u == node: + E.remove((u, v)) + + for _u, _v in E: + if v == _v: + break + else: + kv = key(v) + + for i, s in enumerate(S): + ks = key(s) + + if kv > ks: + S.insert(i, v) + break + else: + S.append(v) + + if E: + raise ValueError("cycle detected") + else: + return L + + +def strongly_connected_components(G): + r""" + Strongly connected components of a directed graph in reverse topological + order. + + + Parameters + ========== + + G : tuple[list, list[tuple[T, T]] + A tuple consisting of a list of vertices and a list of edges of + a graph whose strongly connected components are to be found. + + + Examples + ======== + + Consider a directed graph (in dot notation):: + + digraph { + A -> B + A -> C + B -> C + C -> B + B -> D + } + + .. graphviz:: + + digraph { + A -> B + A -> C + B -> C + C -> B + B -> D + } + + where vertices are the letters A, B, C and D. This graph can be encoded + using Python's elementary data structures as follows:: + + >>> V = ['A', 'B', 'C', 'D'] + >>> E = [('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'B'), ('B', 'D')] + + The strongly connected components of this graph can be computed as + + >>> from sympy.utilities.iterables import strongly_connected_components + + >>> strongly_connected_components((V, E)) + [['D'], ['B', 'C'], ['A']] + + This also gives the components in reverse topological order. + + Since the subgraph containing B and C has a cycle they must be together in + a strongly connected component. A and D are connected to the rest of the + graph but not in a cyclic manner so they appear as their own strongly + connected components. + + + Notes + ===== + + The vertices of the graph must be hashable for the data structures used. + If the vertices are unhashable replace them with integer indices. + + This function uses Tarjan's algorithm to compute the strongly connected + components in `O(|V|+|E|)` (linear) time. + + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Strongly_connected_component + .. [2] https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm + + + See Also + ======== + + sympy.utilities.iterables.connected_components + + """ + # Map from a vertex to its neighbours + V, E = G + Gmap = {vi: [] for vi in V} + for v1, v2 in E: + Gmap[v1].append(v2) + return _strongly_connected_components(V, Gmap) + + +def _strongly_connected_components(V, Gmap): + """More efficient internal routine for strongly_connected_components""" + # + # Here V is an iterable of vertices and Gmap is a dict mapping each vertex + # to a list of neighbours e.g.: + # + # V = [0, 1, 2, 3] + # Gmap = {0: [2, 3], 1: [0]} + # + # For a large graph these data structures can often be created more + # efficiently then those expected by strongly_connected_components() which + # in this case would be + # + # V = [0, 1, 2, 3] + # Gmap = [(0, 2), (0, 3), (1, 0)] + # + # XXX: Maybe this should be the recommended function to use instead... + # + + # Non-recursive Tarjan's algorithm: + lowlink = {} + indices = {} + stack = OrderedDict() + callstack = [] + components = [] + nomore = object() + + def start(v): + index = len(stack) + indices[v] = lowlink[v] = index + stack[v] = None + callstack.append((v, iter(Gmap[v]))) + + def finish(v1): + # Finished a component? + if lowlink[v1] == indices[v1]: + component = [stack.popitem()[0]] + while component[-1] is not v1: + component.append(stack.popitem()[0]) + components.append(component[::-1]) + v2, _ = callstack.pop() + if callstack: + v1, _ = callstack[-1] + lowlink[v1] = min(lowlink[v1], lowlink[v2]) + + for v in V: + if v in indices: + continue + start(v) + while callstack: + v1, it1 = callstack[-1] + v2 = next(it1, nomore) + # Finished children of v1? + if v2 is nomore: + finish(v1) + # Recurse on v2 + elif v2 not in indices: + start(v2) + elif v2 in stack: + lowlink[v1] = min(lowlink[v1], indices[v2]) + + # Reverse topological sort order: + return components + + +def connected_components(G): + r""" + Connected components of an undirected graph or weakly connected components + of a directed graph. + + + Parameters + ========== + + G : tuple[list, list[tuple[T, T]] + A tuple consisting of a list of vertices and a list of edges of + a graph whose connected components are to be found. + + + Examples + ======== + + + Given an undirected graph:: + + graph { + A -- B + C -- D + } + + .. graphviz:: + + graph { + A -- B + C -- D + } + + We can find the connected components using this function if we include + each edge in both directions:: + + >>> from sympy.utilities.iterables import connected_components + + >>> V = ['A', 'B', 'C', 'D'] + >>> E = [('A', 'B'), ('B', 'A'), ('C', 'D'), ('D', 'C')] + >>> connected_components((V, E)) + [['A', 'B'], ['C', 'D']] + + The weakly connected components of a directed graph can found the same + way. + + + Notes + ===== + + The vertices of the graph must be hashable for the data structures used. + If the vertices are unhashable replace them with integer indices. + + This function uses Tarjan's algorithm to compute the connected components + in `O(|V|+|E|)` (linear) time. + + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Component_%28graph_theory%29 + .. [2] https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm + + + See Also + ======== + + sympy.utilities.iterables.strongly_connected_components + + """ + # Duplicate edges both ways so that the graph is effectively undirected + # and return the strongly connected components: + V, E = G + E_undirected = [] + for v1, v2 in E: + E_undirected.extend([(v1, v2), (v2, v1)]) + return strongly_connected_components((V, E_undirected)) + + +def rotate_left(x, y): + """ + Left rotates a list x by the number of steps specified + in y. + + Examples + ======== + + >>> from sympy.utilities.iterables import rotate_left + >>> a = [0, 1, 2] + >>> rotate_left(a, 1) + [1, 2, 0] + """ + if len(x) == 0: + return [] + y = y % len(x) + return x[y:] + x[:y] + + +def rotate_right(x, y): + """ + Right rotates a list x by the number of steps specified + in y. + + Examples + ======== + + >>> from sympy.utilities.iterables import rotate_right + >>> a = [0, 1, 2] + >>> rotate_right(a, 1) + [2, 0, 1] + """ + if len(x) == 0: + return [] + y = len(x) - y % len(x) + return x[y:] + x[:y] + + +def least_rotation(x, key=None): + ''' + Returns the number of steps of left rotation required to + obtain lexicographically minimal string/list/tuple, etc. + + Examples + ======== + + >>> from sympy.utilities.iterables import least_rotation, rotate_left + >>> a = [3, 1, 5, 1, 2] + >>> least_rotation(a) + 3 + >>> rotate_left(a, _) + [1, 2, 3, 1, 5] + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Lexicographically_minimal_string_rotation + + ''' + from sympy.functions.elementary.miscellaneous import Id + if key is None: key = Id + S = x + x # Concatenate string to it self to avoid modular arithmetic + f = [-1] * len(S) # Failure function + k = 0 # Least rotation of string found so far + for j in range(1,len(S)): + sj = S[j] + i = f[j-k-1] + while i != -1 and sj != S[k+i+1]: + if key(sj) < key(S[k+i+1]): + k = j-i-1 + i = f[i] + if sj != S[k+i+1]: + if key(sj) < key(S[k]): + k = j + f[j-k] = -1 + else: + f[j-k] = i+1 + return k + + +def multiset_combinations(m, n, g=None): + """ + Return the unique combinations of size ``n`` from multiset ``m``. + + Examples + ======== + + >>> from sympy.utilities.iterables import multiset_combinations + >>> from itertools import combinations + >>> [''.join(i) for i in multiset_combinations('baby', 3)] + ['abb', 'aby', 'bby'] + + >>> def count(f, s): return len(list(f(s, 3))) + + The number of combinations depends on the number of letters; the + number of unique combinations depends on how the letters are + repeated. + + >>> s1 = 'abracadabra' + >>> s2 = 'banana tree' + >>> count(combinations, s1), count(multiset_combinations, s1) + (165, 23) + >>> count(combinations, s2), count(multiset_combinations, s2) + (165, 54) + + """ + from sympy.core.sorting import ordered + if g is None: + if isinstance(m, dict): + if any(as_int(v) < 0 for v in m.values()): + raise ValueError('counts cannot be negative') + N = sum(m.values()) + if n > N: + return + g = [[k, m[k]] for k in ordered(m)] + else: + m = list(m) + N = len(m) + if n > N: + return + try: + m = multiset(m) + g = [(k, m[k]) for k in ordered(m)] + except TypeError: + m = list(ordered(m)) + g = [list(i) for i in group(m, multiple=False)] + del m + else: + # not checking counts since g is intended for internal use + N = sum(v for k, v in g) + if n > N or not n: + yield [] + else: + for i, (k, v) in enumerate(g): + if v >= n: + yield [k]*n + v = n - 1 + for v in range(min(n, v), 0, -1): + for j in multiset_combinations(None, n - v, g[i + 1:]): + rv = [k]*v + j + if len(rv) == n: + yield rv + +def multiset_permutations(m, size=None, g=None): + """ + Return the unique permutations of multiset ``m``. + + Examples + ======== + + >>> from sympy.utilities.iterables import multiset_permutations + >>> from sympy import factorial + >>> [''.join(i) for i in multiset_permutations('aab')] + ['aab', 'aba', 'baa'] + >>> factorial(len('banana')) + 720 + >>> len(list(multiset_permutations('banana'))) + 60 + """ + from sympy.core.sorting import ordered + if g is None: + if isinstance(m, dict): + if any(as_int(v) < 0 for v in m.values()): + raise ValueError('counts cannot be negative') + g = [[k, m[k]] for k in ordered(m)] + else: + m = list(ordered(m)) + g = [list(i) for i in group(m, multiple=False)] + del m + do = [gi for gi in g if gi[1] > 0] + SUM = sum(gi[1] for gi in do) + if not do or size is not None and (size > SUM or size < 1): + if not do and size is None or size == 0: + yield [] + return + elif size == 1: + for k, v in do: + yield [k] + elif len(do) == 1: + k, v = do[0] + v = v if size is None else (size if size <= v else 0) + yield [k for i in range(v)] + elif all(v == 1 for k, v in do): + for p in permutations([k for k, v in do], size): + yield list(p) + else: + size = size if size is not None else SUM + for i, (k, v) in enumerate(do): + do[i][1] -= 1 + for j in multiset_permutations(None, size - 1, do): + if j: + yield [k] + j + do[i][1] += 1 + + +def _partition(seq, vector, m=None): + """ + Return the partition of seq as specified by the partition vector. + + Examples + ======== + + >>> from sympy.utilities.iterables import _partition + >>> _partition('abcde', [1, 0, 1, 2, 0]) + [['b', 'e'], ['a', 'c'], ['d']] + + Specifying the number of bins in the partition is optional: + + >>> _partition('abcde', [1, 0, 1, 2, 0], 3) + [['b', 'e'], ['a', 'c'], ['d']] + + The output of _set_partitions can be passed as follows: + + >>> output = (3, [1, 0, 1, 2, 0]) + >>> _partition('abcde', *output) + [['b', 'e'], ['a', 'c'], ['d']] + + See Also + ======== + + combinatorics.partitions.Partition.from_rgs + + """ + if m is None: + m = max(vector) + 1 + elif isinstance(vector, int): # entered as m, vector + vector, m = m, vector + p = [[] for i in range(m)] + for i, v in enumerate(vector): + p[v].append(seq[i]) + return p + + +def _set_partitions(n): + """Cycle through all partitions of n elements, yielding the + current number of partitions, ``m``, and a mutable list, ``q`` + such that ``element[i]`` is in part ``q[i]`` of the partition. + + NOTE: ``q`` is modified in place and generally should not be changed + between function calls. + + Examples + ======== + + >>> from sympy.utilities.iterables import _set_partitions, _partition + >>> for m, q in _set_partitions(3): + ... print('%s %s %s' % (m, q, _partition('abc', q, m))) + 1 [0, 0, 0] [['a', 'b', 'c']] + 2 [0, 0, 1] [['a', 'b'], ['c']] + 2 [0, 1, 0] [['a', 'c'], ['b']] + 2 [0, 1, 1] [['a'], ['b', 'c']] + 3 [0, 1, 2] [['a'], ['b'], ['c']] + + Notes + ===== + + This algorithm is similar to, and solves the same problem as, + Algorithm 7.2.1.5H, from volume 4A of Knuth's The Art of Computer + Programming. Knuth uses the term "restricted growth string" where + this code refers to a "partition vector". In each case, the meaning is + the same: the value in the ith element of the vector specifies to + which part the ith set element is to be assigned. + + At the lowest level, this code implements an n-digit big-endian + counter (stored in the array q) which is incremented (with carries) to + get the next partition in the sequence. A special twist is that a + digit is constrained to be at most one greater than the maximum of all + the digits to the left of it. The array p maintains this maximum, so + that the code can efficiently decide when a digit can be incremented + in place or whether it needs to be reset to 0 and trigger a carry to + the next digit. The enumeration starts with all the digits 0 (which + corresponds to all the set elements being assigned to the same 0th + part), and ends with 0123...n, which corresponds to each set element + being assigned to a different, singleton, part. + + This routine was rewritten to use 0-based lists while trying to + preserve the beauty and efficiency of the original algorithm. + + References + ========== + + .. [1] Nijenhuis, Albert and Wilf, Herbert. (1978) Combinatorial Algorithms, + 2nd Ed, p 91, algorithm "nexequ". Available online from + https://www.math.upenn.edu/~wilf/website/CombAlgDownld.html (viewed + November 17, 2012). + + """ + p = [0]*n + q = [0]*n + nc = 1 + yield nc, q + while nc != n: + m = n + while 1: + m -= 1 + i = q[m] + if p[i] != 1: + break + q[m] = 0 + i += 1 + q[m] = i + m += 1 + nc += m - n + p[0] += n - m + if i == nc: + p[nc] = 0 + nc += 1 + p[i - 1] -= 1 + p[i] += 1 + yield nc, q + + +def multiset_partitions(multiset, m=None): + """ + Return unique partitions of the given multiset (in list form). + If ``m`` is None, all multisets will be returned, otherwise only + partitions with ``m`` parts will be returned. + + If ``multiset`` is an integer, a range [0, 1, ..., multiset - 1] + will be supplied. + + Examples + ======== + + >>> from sympy.utilities.iterables import multiset_partitions + >>> list(multiset_partitions([1, 2, 3, 4], 2)) + [[[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 2], [3, 4]], + [[1, 3, 4], [2]], [[1, 3], [2, 4]], [[1, 4], [2, 3]], + [[1], [2, 3, 4]]] + >>> list(multiset_partitions([1, 2, 3, 4], 1)) + [[[1, 2, 3, 4]]] + + Only unique partitions are returned and these will be returned in a + canonical order regardless of the order of the input: + + >>> a = [1, 2, 2, 1] + >>> ans = list(multiset_partitions(a, 2)) + >>> a.sort() + >>> list(multiset_partitions(a, 2)) == ans + True + >>> a = range(3, 1, -1) + >>> (list(multiset_partitions(a)) == + ... list(multiset_partitions(sorted(a)))) + True + + If m is omitted then all partitions will be returned: + + >>> list(multiset_partitions([1, 1, 2])) + [[[1, 1, 2]], [[1, 1], [2]], [[1, 2], [1]], [[1], [1], [2]]] + >>> list(multiset_partitions([1]*3)) + [[[1, 1, 1]], [[1], [1, 1]], [[1], [1], [1]]] + + Counting + ======== + + The number of partitions of a set is given by the bell number: + + >>> from sympy import bell + >>> len(list(multiset_partitions(5))) == bell(5) == 52 + True + + The number of partitions of length k from a set of size n is given by the + Stirling Number of the 2nd kind: + + >>> from sympy.functions.combinatorial.numbers import stirling + >>> stirling(5, 2) == len(list(multiset_partitions(5, 2))) == 15 + True + + These comments on counting apply to *sets*, not multisets. + + Notes + ===== + + When all the elements are the same in the multiset, the order + of the returned partitions is determined by the ``partitions`` + routine. If one is counting partitions then it is better to use + the ``nT`` function. + + See Also + ======== + + partitions + sympy.combinatorics.partitions.Partition + sympy.combinatorics.partitions.IntegerPartition + sympy.functions.combinatorial.numbers.nT + + """ + # This function looks at the supplied input and dispatches to + # several special-case routines as they apply. + if isinstance(multiset, int): + n = multiset + if m and m > n: + return + multiset = list(range(n)) + if m == 1: + yield [multiset[:]] + return + + # If m is not None, it can sometimes be faster to use + # MultisetPartitionTraverser.enum_range() even for inputs + # which are sets. Since the _set_partitions code is quite + # fast, this is only advantageous when the overall set + # partitions outnumber those with the desired number of parts + # by a large factor. (At least 60.) Such a switch is not + # currently implemented. + for nc, q in _set_partitions(n): + if m is None or nc == m: + rv = [[] for i in range(nc)] + for i in range(n): + rv[q[i]].append(multiset[i]) + yield rv + return + + if len(multiset) == 1 and isinstance(multiset, str): + multiset = [multiset] + + if not has_variety(multiset): + # Only one component, repeated n times. The resulting + # partitions correspond to partitions of integer n. + n = len(multiset) + if m and m > n: + return + if m == 1: + yield [multiset[:]] + return + x = multiset[:1] + for size, p in partitions(n, m, size=True): + if m is None or size == m: + rv = [] + for k in sorted(p): + rv.extend([x*k]*p[k]) + yield rv + else: + from sympy.core.sorting import ordered + multiset = list(ordered(multiset)) + n = len(multiset) + if m and m > n: + return + if m == 1: + yield [multiset[:]] + return + + # Split the information of the multiset into two lists - + # one of the elements themselves, and one (of the same length) + # giving the number of repeats for the corresponding element. + elements, multiplicities = zip(*group(multiset, False)) + + if len(elements) < len(multiset): + # General case - multiset with more than one distinct element + # and at least one element repeated more than once. + if m: + mpt = MultisetPartitionTraverser() + for state in mpt.enum_range(multiplicities, m-1, m): + yield list_visitor(state, elements) + else: + for state in multiset_partitions_taocp(multiplicities): + yield list_visitor(state, elements) + else: + # Set partitions case - no repeated elements. Pretty much + # same as int argument case above, with same possible, but + # currently unimplemented optimization for some cases when + # m is not None + for nc, q in _set_partitions(n): + if m is None or nc == m: + rv = [[] for i in range(nc)] + for i in range(n): + rv[q[i]].append(i) + yield [[multiset[j] for j in i] for i in rv] + + +def partitions(n, m=None, k=None, size=False): + """Generate all partitions of positive integer, n. + + Each partition is represented as a dictionary, mapping an integer + to the number of copies of that integer in the partition. For example, + the first partition of 4 returned is {4: 1}, "4: one of them". + + Parameters + ========== + n : int + m : int, optional + limits number of parts in partition (mnemonic: m, maximum parts) + k : int, optional + limits the numbers that are kept in the partition (mnemonic: k, keys) + size : bool, default: False + If ``True``, (M, P) is returned where M is the sum of the + multiplicities and P is the generated partition. + If ``False``, only the generated partition is returned. + + Examples + ======== + + >>> from sympy.utilities.iterables import partitions + + The numbers appearing in the partition (the key of the returned dict) + are limited with k: + + >>> for p in partitions(6, k=2): # doctest: +SKIP + ... print(p) + {2: 3} + {1: 2, 2: 2} + {1: 4, 2: 1} + {1: 6} + + The maximum number of parts in the partition (the sum of the values in + the returned dict) are limited with m (default value, None, gives + partitions from 1 through n): + + >>> for p in partitions(6, m=2): # doctest: +SKIP + ... print(p) + ... + {6: 1} + {1: 1, 5: 1} + {2: 1, 4: 1} + {3: 2} + + References + ========== + + .. [1] modified from Tim Peter's version to allow for k and m values: + https://code.activestate.com/recipes/218332-generator-for-integer-partitions/ + + See Also + ======== + + sympy.combinatorics.partitions.Partition + sympy.combinatorics.partitions.IntegerPartition + + """ + if (n <= 0 or + m is not None and m < 1 or + k is not None and k < 1 or + m and k and m*k < n): + # the empty set is the only way to handle these inputs + # and returning {} to represent it is consistent with + # the counting convention, e.g. nT(0) == 1. + if size: + yield 0, {} + else: + yield {} + return + + if m is None: + m = n + else: + m = min(m, n) + k = min(k or n, n) + + n, m, k = as_int(n), as_int(m), as_int(k) + q, r = divmod(n, k) + ms = {k: q} + keys = [k] # ms.keys(), from largest to smallest + if r: + ms[r] = 1 + keys.append(r) + room = m - q - bool(r) + if size: + yield sum(ms.values()), ms.copy() + else: + yield ms.copy() + + while keys != [1]: + # Reuse any 1's. + if keys[-1] == 1: + del keys[-1] + reuse = ms.pop(1) + room += reuse + else: + reuse = 0 + + while 1: + # Let i be the smallest key larger than 1. Reuse one + # instance of i. + i = keys[-1] + newcount = ms[i] = ms[i] - 1 + reuse += i + if newcount == 0: + del keys[-1], ms[i] + room += 1 + + # Break the remainder into pieces of size i-1. + i -= 1 + q, r = divmod(reuse, i) + need = q + bool(r) + if need > room: + if not keys: + return + continue + + ms[i] = q + keys.append(i) + if r: + ms[r] = 1 + keys.append(r) + break + room -= need + if size: + yield sum(ms.values()), ms.copy() + else: + yield ms.copy() + + +def ordered_partitions(n, m=None, sort=True): + """Generates ordered partitions of integer *n*. + + Parameters + ========== + n : int + m : int, optional + The default value gives partitions of all sizes else only + those with size m. In addition, if *m* is not None then + partitions are generated *in place* (see examples). + sort : bool, default: True + Controls whether partitions are + returned in sorted order when *m* is not None; when False, + the partitions are returned as fast as possible with elements + sorted, but when m|n the partitions will not be in + ascending lexicographical order. + + Examples + ======== + + >>> from sympy.utilities.iterables import ordered_partitions + + All partitions of 5 in ascending lexicographical: + + >>> for p in ordered_partitions(5): + ... print(p) + [1, 1, 1, 1, 1] + [1, 1, 1, 2] + [1, 1, 3] + [1, 2, 2] + [1, 4] + [2, 3] + [5] + + Only partitions of 5 with two parts: + + >>> for p in ordered_partitions(5, 2): + ... print(p) + [1, 4] + [2, 3] + + When ``m`` is given, a given list objects will be used more than + once for speed reasons so you will not see the correct partitions + unless you make a copy of each as it is generated: + + >>> [p for p in ordered_partitions(7, 3)] + [[1, 1, 1], [1, 1, 1], [1, 1, 1], [2, 2, 2]] + >>> [list(p) for p in ordered_partitions(7, 3)] + [[1, 1, 5], [1, 2, 4], [1, 3, 3], [2, 2, 3]] + + When ``n`` is a multiple of ``m``, the elements are still sorted + but the partitions themselves will be *unordered* if sort is False; + the default is to return them in ascending lexicographical order. + + >>> for p in ordered_partitions(6, 2): + ... print(p) + [1, 5] + [2, 4] + [3, 3] + + But if speed is more important than ordering, sort can be set to + False: + + >>> for p in ordered_partitions(6, 2, sort=False): + ... print(p) + [1, 5] + [3, 3] + [2, 4] + + References + ========== + + .. [1] Generating Integer Partitions, [online], + Available: https://jeromekelleher.net/generating-integer-partitions.html + .. [2] Jerome Kelleher and Barry O'Sullivan, "Generating All + Partitions: A Comparison Of Two Encodings", [online], + Available: https://arxiv.org/pdf/0909.2331v2.pdf + """ + if n < 1 or m is not None and m < 1: + # the empty set is the only way to handle these inputs + # and returning {} to represent it is consistent with + # the counting convention, e.g. nT(0) == 1. + yield [] + return + + if m is None: + # The list `a`'s leading elements contain the partition in which + # y is the biggest element and x is either the same as y or the + # 2nd largest element; v and w are adjacent element indices + # to which x and y are being assigned, respectively. + a = [1]*n + y = -1 + v = n + while v > 0: + v -= 1 + x = a[v] + 1 + while y >= 2 * x: + a[v] = x + y -= x + v += 1 + w = v + 1 + while x <= y: + a[v] = x + a[w] = y + yield a[:w + 1] + x += 1 + y -= 1 + a[v] = x + y + y = a[v] - 1 + yield a[:w] + elif m == 1: + yield [n] + elif n == m: + yield [1]*n + else: + # recursively generate partitions of size m + for b in range(1, n//m + 1): + a = [b]*m + x = n - b*m + if not x: + if sort: + yield a + elif not sort and x <= m: + for ax in ordered_partitions(x, sort=False): + mi = len(ax) + a[-mi:] = [i + b for i in ax] + yield a + a[-mi:] = [b]*mi + else: + for mi in range(1, m): + for ax in ordered_partitions(x, mi, sort=True): + a[-mi:] = [i + b for i in ax] + yield a + a[-mi:] = [b]*mi + + +def binary_partitions(n): + """ + Generates the binary partition of *n*. + + A binary partition consists only of numbers that are + powers of two. Each step reduces a `2^{k+1}` to `2^k` and + `2^k`. Thus 16 is converted to 8 and 8. + + Examples + ======== + + >>> from sympy.utilities.iterables import binary_partitions + >>> for i in binary_partitions(5): + ... print(i) + ... + [4, 1] + [2, 2, 1] + [2, 1, 1, 1] + [1, 1, 1, 1, 1] + + References + ========== + + .. [1] TAOCP 4, section 7.2.1.5, problem 64 + + """ + from math import ceil, log2 + power = int(2**(ceil(log2(n)))) + acc = 0 + partition = [] + while power: + if acc + power <= n: + partition.append(power) + acc += power + power >>= 1 + + last_num = len(partition) - 1 - (n & 1) + while last_num >= 0: + yield partition + if partition[last_num] == 2: + partition[last_num] = 1 + partition.append(1) + last_num -= 1 + continue + partition.append(1) + partition[last_num] >>= 1 + x = partition[last_num + 1] = partition[last_num] + last_num += 1 + while x > 1: + if x <= len(partition) - last_num - 1: + del partition[-x + 1:] + last_num += 1 + partition[last_num] = x + else: + x >>= 1 + yield [1]*n + + +def has_dups(seq): + """Return True if there are any duplicate elements in ``seq``. + + Examples + ======== + + >>> from sympy import has_dups, Dict, Set + >>> has_dups((1, 2, 1)) + True + >>> has_dups(range(3)) + False + >>> all(has_dups(c) is False for c in (set(), Set(), dict(), Dict())) + True + """ + from sympy.core.containers import Dict + from sympy.sets.sets import Set + if isinstance(seq, (dict, set, Dict, Set)): + return False + unique = set() + try: + return any(True for s in seq if s in unique or unique.add(s)) + except TypeError: + return len(seq) != len(list(uniq(seq))) + + +def has_variety(seq): + """Return True if there are any different elements in ``seq``. + + Examples + ======== + + >>> from sympy import has_variety + + >>> has_variety((1, 2, 1)) + True + >>> has_variety((1, 1, 1)) + False + """ + for i, s in enumerate(seq): + if i == 0: + sentinel = s + else: + if s != sentinel: + return True + return False + + +def uniq(seq, result=None): + """ + Yield unique elements from ``seq`` as an iterator. The second + parameter ``result`` is used internally; it is not necessary + to pass anything for this. + + Note: changing the sequence during iteration will raise a + RuntimeError if the size of the sequence is known; if you pass + an iterator and advance the iterator you will change the + output of this routine but there will be no warning. + + Examples + ======== + + >>> from sympy.utilities.iterables import uniq + >>> dat = [1, 4, 1, 5, 4, 2, 1, 2] + >>> type(uniq(dat)) in (list, tuple) + False + + >>> list(uniq(dat)) + [1, 4, 5, 2] + >>> list(uniq(x for x in dat)) + [1, 4, 5, 2] + >>> list(uniq([[1], [2, 1], [1]])) + [[1], [2, 1]] + """ + try: + n = len(seq) + except TypeError: + n = None + def check(): + # check that size of seq did not change during iteration; + # if n == None the object won't support size changing, e.g. + # an iterator can't be changed + if n is not None and len(seq) != n: + raise RuntimeError('sequence changed size during iteration') + try: + seen = set() + result = result or [] + for i, s in enumerate(seq): + if not (s in seen or seen.add(s)): + yield s + check() + except TypeError: + if s not in result: + yield s + check() + result.append(s) + if hasattr(seq, '__getitem__'): + yield from uniq(seq[i + 1:], result) + else: + yield from uniq(seq, result) + + +def generate_bell(n): + """Return permutations of [0, 1, ..., n - 1] such that each permutation + differs from the last by the exchange of a single pair of neighbors. + The ``n!`` permutations are returned as an iterator. In order to obtain + the next permutation from a random starting permutation, use the + ``next_trotterjohnson`` method of the Permutation class (which generates + the same sequence in a different manner). + + Examples + ======== + + >>> from itertools import permutations + >>> from sympy.utilities.iterables import generate_bell + >>> from sympy import zeros, Matrix + + This is the sort of permutation used in the ringing of physical bells, + and does not produce permutations in lexicographical order. Rather, the + permutations differ from each other by exactly one inversion, and the + position at which the swapping occurs varies periodically in a simple + fashion. Consider the first few permutations of 4 elements generated + by ``permutations`` and ``generate_bell``: + + >>> list(permutations(range(4)))[:5] + [(0, 1, 2, 3), (0, 1, 3, 2), (0, 2, 1, 3), (0, 2, 3, 1), (0, 3, 1, 2)] + >>> list(generate_bell(4))[:5] + [(0, 1, 2, 3), (0, 1, 3, 2), (0, 3, 1, 2), (3, 0, 1, 2), (3, 0, 2, 1)] + + Notice how the 2nd and 3rd lexicographical permutations have 3 elements + out of place whereas each "bell" permutation always has only two + elements out of place relative to the previous permutation (and so the + signature (+/-1) of a permutation is opposite of the signature of the + previous permutation). + + How the position of inversion varies across the elements can be seen + by tracing out where the largest number appears in the permutations: + + >>> m = zeros(4, 24) + >>> for i, p in enumerate(generate_bell(4)): + ... m[:, i] = Matrix([j - 3 for j in list(p)]) # make largest zero + >>> m.print_nonzero('X') + [XXX XXXXXX XXXXXX XXX] + [XX XX XXXX XX XXXX XX XX] + [X XXXX XX XXXX XX XXXX X] + [ XXXXXX XXXXXX XXXXXX ] + + See Also + ======== + + sympy.combinatorics.permutations.Permutation.next_trotterjohnson + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Method_ringing + + .. [2] https://stackoverflow.com/questions/4856615/recursive-permutation/4857018 + + .. [3] https://web.archive.org/web/20160313023044/http://programminggeeks.com/bell-algorithm-for-permutation/ + + .. [4] https://en.wikipedia.org/wiki/Steinhaus%E2%80%93Johnson%E2%80%93Trotter_algorithm + + .. [5] Generating involutions, derangements, and relatives by ECO + Vincent Vajnovszki, DMTCS vol 1 issue 12, 2010 + + """ + n = as_int(n) + if n < 1: + raise ValueError('n must be a positive integer') + if n == 1: + yield (0,) + elif n == 2: + yield (0, 1) + yield (1, 0) + elif n == 3: + yield from [(0, 1, 2), (0, 2, 1), (2, 0, 1), (2, 1, 0), (1, 2, 0), (1, 0, 2)] + else: + m = n - 1 + op = [0] + [-1]*m + l = list(range(n)) + while True: + yield tuple(l) + # find biggest element with op + big = None, -1 # idx, value + for i in range(n): + if op[i] and l[i] > big[1]: + big = i, l[i] + i, _ = big + if i is None: + break # there are no ops left + # swap it with neighbor in the indicated direction + j = i + op[i] + l[i], l[j] = l[j], l[i] + op[i], op[j] = op[j], op[i] + # if it landed at the end or if the neighbor in the same + # direction is bigger then turn off op + if j == 0 or j == m or l[j + op[j]] > l[j]: + op[j] = 0 + # any element bigger to the left gets +1 op + for i in range(j): + if l[i] > l[j]: + op[i] = 1 + # any element bigger to the right gets -1 op + for i in range(j + 1, n): + if l[i] > l[j]: + op[i] = -1 + + +def generate_involutions(n): + """ + Generates involutions. + + An involution is a permutation that when multiplied + by itself equals the identity permutation. In this + implementation the involutions are generated using + Fixed Points. + + Alternatively, an involution can be considered as + a permutation that does not contain any cycles with + a length that is greater than two. + + Examples + ======== + + >>> from sympy.utilities.iterables import generate_involutions + >>> list(generate_involutions(3)) + [(0, 1, 2), (0, 2, 1), (1, 0, 2), (2, 1, 0)] + >>> len(list(generate_involutions(4))) + 10 + + References + ========== + + .. [1] https://mathworld.wolfram.com/PermutationInvolution.html + + """ + idx = list(range(n)) + for p in permutations(idx): + for i in idx: + if p[p[i]] != i: + break + else: + yield p + + +def multiset_derangements(s): + """Generate derangements of the elements of s *in place*. + + Examples + ======== + + >>> from sympy.utilities.iterables import multiset_derangements, uniq + + Because the derangements of multisets (not sets) are generated + in place, copies of the return value must be made if a collection + of derangements is desired or else all values will be the same: + + >>> list(uniq([i for i in multiset_derangements('1233')])) + [[None, None, None, None]] + >>> [i.copy() for i in multiset_derangements('1233')] + [['3', '3', '1', '2'], ['3', '3', '2', '1']] + >>> [''.join(i) for i in multiset_derangements('1233')] + ['3312', '3321'] + """ + from sympy.core.sorting import ordered + # create multiset dictionary of hashable elements or else + # remap elements to integers + try: + ms = multiset(s) + except TypeError: + # give each element a canonical integer value + key = dict(enumerate(ordered(uniq(s)))) + h = [] + for si in s: + for k in key: + if key[k] == si: + h.append(k) + break + for i in multiset_derangements(h): + yield [key[j] for j in i] + return + + mx = max(ms.values()) # max repetition of any element + n = len(s) # the number of elements + + ## special cases + + # 1) one element has more than half the total cardinality of s: no + # derangements are possible. + if mx*2 > n: + return + + # 2) all elements appear once: singletons + if len(ms) == n: + yield from _set_derangements(s) + return + + # find the first element that is repeated the most to place + # in the following two special cases where the selection + # is unambiguous: either there are two elements with multiplicity + # of mx or else there is only one with multiplicity mx + for M in ms: + if ms[M] == mx: + break + + inonM = [i for i in range(n) if s[i] != M] # location of non-M + iM = [i for i in range(n) if s[i] == M] # locations of M + rv = [None]*n + + # 3) half are the same + if 2*mx == n: + # M goes into non-M locations + for i in inonM: + rv[i] = M + # permutations of non-M go to M locations + for p in multiset_permutations([s[i] for i in inonM]): + for i, pi in zip(iM, p): + rv[i] = pi + yield rv + # clean-up (and encourages proper use of routine) + rv[:] = [None]*n + return + + # 4) single repeat covers all but 1 of the non-repeats: + # if there is one repeat then the multiset of the values + # of ms would be {mx: 1, 1: n - mx}, i.e. there would + # be n - mx + 1 values with the condition that n - 2*mx = 1 + if n - 2*mx == 1 and len(ms.values()) == n - mx + 1: + for i, i1 in enumerate(inonM): + ifill = inonM[:i] + inonM[i+1:] + for j in ifill: + rv[j] = M + for p in permutations([s[j] for j in ifill]): + rv[i1] = s[i1] + for j, pi in zip(iM, p): + rv[j] = pi + k = i1 + for j in iM: + rv[j], rv[k] = rv[k], rv[j] + yield rv + k = j + # clean-up (and encourages proper use of routine) + rv[:] = [None]*n + return + + ## general case is handled with 3 helpers: + # 1) `finish_derangements` will place the last two elements + # which have arbitrary multiplicities, e.g. for multiset + # {c: 3, a: 2, b: 2}, the last two elements are a and b + # 2) `iopen` will tell where a given element can be placed + # 3) `do` will recursively place elements into subsets of + # valid locations + + def finish_derangements(): + """Place the last two elements into the partially completed + derangement, and yield the results. + """ + + a = take[1][0] # penultimate element + a_ct = take[1][1] + b = take[0][0] # last element to be placed + b_ct = take[0][1] + + # split the indexes of the not-already-assigned elements of rv into + # three categories + forced_a = [] # positions which must have an a + forced_b = [] # positions which must have a b + open_free = [] # positions which could take either + for i in range(len(s)): + if rv[i] is None: + if s[i] == a: + forced_b.append(i) + elif s[i] == b: + forced_a.append(i) + else: + open_free.append(i) + + if len(forced_a) > a_ct or len(forced_b) > b_ct: + # No derangement possible + return + + for i in forced_a: + rv[i] = a + for i in forced_b: + rv[i] = b + for a_place in combinations(open_free, a_ct - len(forced_a)): + for a_pos in a_place: + rv[a_pos] = a + for i in open_free: + if rv[i] is None: # anything not in the subset is set to b + rv[i] = b + yield rv + # Clean up/undo the final placements + for i in open_free: + rv[i] = None + + # additional cleanup - clear forced_a, forced_b + for i in forced_a: + rv[i] = None + for i in forced_b: + rv[i] = None + + def iopen(v): + # return indices at which element v can be placed in rv: + # locations which are not already occupied if that location + # does not already contain v in the same location of s + return [i for i in range(n) if rv[i] is None and s[i] != v] + + def do(j): + if j == 1: + # handle the last two elements (regardless of multiplicity) + # with a special method + yield from finish_derangements() + else: + # place the mx elements of M into a subset of places + # into which it can be replaced + M, mx = take[j] + for i in combinations(iopen(M), mx): + # place M + for ii in i: + rv[ii] = M + # recursively place the next element + yield from do(j - 1) + # mark positions where M was placed as once again + # open for placement of other elements + for ii in i: + rv[ii] = None + + # process elements in order of canonically decreasing multiplicity + take = sorted(ms.items(), key=lambda x:(x[1], x[0])) + yield from do(len(take) - 1) + rv[:] = [None]*n + + +def random_derangement(t, choice=None, strict=True): + """Return a list of elements in which none are in the same positions + as they were originally. If an element fills more than half of the positions + then an error will be raised since no derangement is possible. To obtain + a derangement of as many items as possible--with some of the most numerous + remaining in their original positions--pass `strict=False`. To produce a + pseudorandom derangment, pass a pseudorandom selector like `choice` (see + below). + + Examples + ======== + + >>> from sympy.utilities.iterables import random_derangement + >>> t = 'SymPy: a CAS in pure Python' + >>> d = random_derangement(t) + >>> all(i != j for i, j in zip(d, t)) + True + + A predictable result can be obtained by using a pseudorandom + generator for the choice: + + >>> from sympy.core.random import seed, choice as c + >>> seed(1) + >>> d = [''.join(random_derangement(t, c)) for i in range(5)] + >>> assert len(set(d)) != 1 # we got different values + + By reseeding, the same sequence can be obtained: + + >>> seed(1) + >>> d2 = [''.join(random_derangement(t, c)) for i in range(5)] + >>> assert d == d2 + """ + if choice is None: + import secrets + choice = secrets.choice + def shuffle(rv): + '''Knuth shuffle''' + for i in range(len(rv) - 1, 0, -1): + x = choice(rv[:i + 1]) + j = rv.index(x) + rv[i], rv[j] = rv[j], rv[i] + def pick(rv, n): + '''shuffle rv and return the first n values + ''' + shuffle(rv) + return rv[:n] + ms = multiset(t) + tot = len(t) + ms = sorted(ms.items(), key=lambda x: x[1]) + # if there are not enough spaces for the most + # plentiful element to move to then some of them + # will have to stay in place + M, mx = ms[-1] + n = len(t) + xs = 2*mx - tot + if xs > 0: + if strict: + raise ValueError('no derangement possible') + opts = [i for (i, c) in enumerate(t) if c == ms[-1][0]] + pick(opts, xs) + stay = sorted(opts[:xs]) + rv = list(t) + for i in reversed(stay): + rv.pop(i) + rv = random_derangement(rv, choice) + for i in stay: + rv.insert(i, ms[-1][0]) + return ''.join(rv) if type(t) is str else rv + # the normal derangement calculated from here + if n == len(ms): + # approx 1/3 will succeed + rv = list(t) + while True: + shuffle(rv) + if all(i != j for i,j in zip(rv, t)): + break + else: + # general case + rv = [None]*n + while True: + j = 0 + while j > -len(ms): # do most numerous first + j -= 1 + e, c = ms[j] + opts = [i for i in range(n) if rv[i] is None and t[i] != e] + if len(opts) < c: + for i in range(n): + rv[i] = None + break # try again + pick(opts, c) + for i in range(c): + rv[opts[i]] = e + else: + return rv + return rv + + +def _set_derangements(s): + """ + yield derangements of items in ``s`` which are assumed to contain + no repeated elements + """ + if len(s) < 2: + return + if len(s) == 2: + yield [s[1], s[0]] + return + if len(s) == 3: + yield [s[1], s[2], s[0]] + yield [s[2], s[0], s[1]] + return + for p in permutations(s): + if not any(i == j for i, j in zip(p, s)): + yield list(p) + + +def generate_derangements(s): + """ + Return unique derangements of the elements of iterable ``s``. + + Examples + ======== + + >>> from sympy.utilities.iterables import generate_derangements + >>> list(generate_derangements([0, 1, 2])) + [[1, 2, 0], [2, 0, 1]] + >>> list(generate_derangements([0, 1, 2, 2])) + [[2, 2, 0, 1], [2, 2, 1, 0]] + >>> list(generate_derangements([0, 1, 1])) + [] + + See Also + ======== + + sympy.functions.combinatorial.factorials.subfactorial + + """ + if not has_dups(s): + yield from _set_derangements(s) + else: + for p in multiset_derangements(s): + yield list(p) + + +def necklaces(n, k, free=False): + """ + A routine to generate necklaces that may (free=True) or may not + (free=False) be turned over to be viewed. The "necklaces" returned + are comprised of ``n`` integers (beads) with ``k`` different + values (colors). Only unique necklaces are returned. + + Examples + ======== + + >>> from sympy.utilities.iterables import necklaces, bracelets + >>> def show(s, i): + ... return ''.join(s[j] for j in i) + + The "unrestricted necklace" is sometimes also referred to as a + "bracelet" (an object that can be turned over, a sequence that can + be reversed) and the term "necklace" is used to imply a sequence + that cannot be reversed. So ACB == ABC for a bracelet (rotate and + reverse) while the two are different for a necklace since rotation + alone cannot make the two sequences the same. + + (mnemonic: Bracelets can be viewed Backwards, but Not Necklaces.) + + >>> B = [show('ABC', i) for i in bracelets(3, 3)] + >>> N = [show('ABC', i) for i in necklaces(3, 3)] + >>> set(N) - set(B) + {'ACB'} + + >>> list(necklaces(4, 2)) + [(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 1), + (0, 1, 0, 1), (0, 1, 1, 1), (1, 1, 1, 1)] + + >>> [show('.o', i) for i in bracelets(4, 2)] + ['....', '...o', '..oo', '.o.o', '.ooo', 'oooo'] + + References + ========== + + .. [1] https://mathworld.wolfram.com/Necklace.html + + .. [2] Frank Ruskey, Carla Savage, and Terry Min Yih Wang, + Generating necklaces, Journal of Algorithms 13 (1992), 414-430; + https://doi.org/10.1016/0196-6774(92)90047-G + + """ + # The FKM algorithm + if k == 0 and n > 0: + return + a = [0]*n + yield tuple(a) + if n == 0: + return + while True: + i = n - 1 + while a[i] == k - 1: + i -= 1 + if i == -1: + return + a[i] += 1 + for j in range(n - i - 1): + a[j + i + 1] = a[j] + if n % (i + 1) == 0 and (not free or all(a <= a[j::-1] + a[-1:j:-1] for j in range(n - 1))): + # No need to test j = n - 1. + yield tuple(a) + + +def bracelets(n, k): + """Wrapper to necklaces to return a free (unrestricted) necklace.""" + return necklaces(n, k, free=True) + + +def generate_oriented_forest(n): + """ + This algorithm generates oriented forests. + + An oriented graph is a directed graph having no symmetric pair of directed + edges. A forest is an acyclic graph, i.e., it has no cycles. A forest can + also be described as a disjoint union of trees, which are graphs in which + any two vertices are connected by exactly one simple path. + + Examples + ======== + + >>> from sympy.utilities.iterables import generate_oriented_forest + >>> list(generate_oriented_forest(4)) + [[0, 1, 2, 3], [0, 1, 2, 2], [0, 1, 2, 1], [0, 1, 2, 0], \ + [0, 1, 1, 1], [0, 1, 1, 0], [0, 1, 0, 1], [0, 1, 0, 0], [0, 0, 0, 0]] + + References + ========== + + .. [1] T. Beyer and S.M. Hedetniemi: constant time generation of + rooted trees, SIAM J. Computing Vol. 9, No. 4, November 1980 + + .. [2] https://stackoverflow.com/questions/1633833/oriented-forest-taocp-algorithm-in-python + + """ + P = list(range(-1, n)) + while True: + yield P[1:] + if P[n] > 0: + P[n] = P[P[n]] + else: + for p in range(n - 1, 0, -1): + if P[p] != 0: + target = P[p] - 1 + for q in range(p - 1, 0, -1): + if P[q] == target: + break + offset = p - q + for i in range(p, n + 1): + P[i] = P[i - offset] + break + else: + break + + +def minlex(seq, directed=True, key=None): + r""" + Return the rotation of the sequence in which the lexically smallest + elements appear first, e.g. `cba \rightarrow acb`. + + The sequence returned is a tuple, unless the input sequence is a string + in which case a string is returned. + + If ``directed`` is False then the smaller of the sequence and the + reversed sequence is returned, e.g. `cba \rightarrow abc`. + + If ``key`` is not None then it is used to extract a comparison key from each element in iterable. + + Examples + ======== + + >>> from sympy.combinatorics.polyhedron import minlex + >>> minlex((1, 2, 0)) + (0, 1, 2) + >>> minlex((1, 0, 2)) + (0, 2, 1) + >>> minlex((1, 0, 2), directed=False) + (0, 1, 2) + + >>> minlex('11010011000', directed=True) + '00011010011' + >>> minlex('11010011000', directed=False) + '00011001011' + + >>> minlex(('bb', 'aaa', 'c', 'a')) + ('a', 'bb', 'aaa', 'c') + >>> minlex(('bb', 'aaa', 'c', 'a'), key=len) + ('c', 'a', 'bb', 'aaa') + + """ + from sympy.functions.elementary.miscellaneous import Id + if key is None: key = Id + best = rotate_left(seq, least_rotation(seq, key=key)) + if not directed: + rseq = seq[::-1] + rbest = rotate_left(rseq, least_rotation(rseq, key=key)) + best = min(best, rbest, key=key) + + # Convert to tuple, unless we started with a string. + return tuple(best) if not isinstance(seq, str) else best + + +def runs(seq, op=gt): + """Group the sequence into lists in which successive elements + all compare the same with the comparison operator, ``op``: + op(seq[i + 1], seq[i]) is True from all elements in a run. + + Examples + ======== + + >>> from sympy.utilities.iterables import runs + >>> from operator import ge + >>> runs([0, 1, 2, 2, 1, 4, 3, 2, 2]) + [[0, 1, 2], [2], [1, 4], [3], [2], [2]] + >>> runs([0, 1, 2, 2, 1, 4, 3, 2, 2], op=ge) + [[0, 1, 2, 2], [1, 4], [3], [2, 2]] + """ + cycles = [] + seq = iter(seq) + try: + run = [next(seq)] + except StopIteration: + return [] + while True: + try: + ei = next(seq) + except StopIteration: + break + if op(ei, run[-1]): + run.append(ei) + continue + else: + cycles.append(run) + run = [ei] + if run: + cycles.append(run) + return cycles + + +def sequence_partitions(l, n, /): + r"""Returns the partition of sequence $l$ into $n$ bins + + Explanation + =========== + + Given the sequence $l_1 \cdots l_m \in V^+$ where + $V^+$ is the Kleene plus of $V$ + + The set of $n$ partitions of $l$ is defined as: + + .. math:: + \{(s_1, \cdots, s_n) | s_1 \in V^+, \cdots, s_n \in V^+, + s_1 \cdots s_n = l_1 \cdots l_m\} + + Parameters + ========== + + l : Sequence[T] + A nonempty sequence of any Python objects + + n : int + A positive integer + + Yields + ====== + + out : list[Sequence[T]] + A list of sequences with concatenation equals $l$. + This should conform with the type of $l$. + + Examples + ======== + + >>> from sympy.utilities.iterables import sequence_partitions + >>> for out in sequence_partitions([1, 2, 3, 4], 2): + ... print(out) + [[1], [2, 3, 4]] + [[1, 2], [3, 4]] + [[1, 2, 3], [4]] + + Notes + ===== + + This is modified version of EnricoGiampieri's partition generator + from https://stackoverflow.com/questions/13131491/partition-n-items-into-k-bins-in-python-lazily + + See Also + ======== + + sequence_partitions_empty + """ + # Asserting l is nonempty is done only for sanity check + if n == 1 and l: + yield [l] + return + for i in range(1, len(l)): + for part in sequence_partitions(l[i:], n - 1): + yield [l[:i]] + part + + +def sequence_partitions_empty(l, n, /): + r"""Returns the partition of sequence $l$ into $n$ bins with + empty sequence + + Explanation + =========== + + Given the sequence $l_1 \cdots l_m \in V^*$ where + $V^*$ is the Kleene star of $V$ + + The set of $n$ partitions of $l$ is defined as: + + .. math:: + \{(s_1, \cdots, s_n) | s_1 \in V^*, \cdots, s_n \in V^*, + s_1 \cdots s_n = l_1 \cdots l_m\} + + There are more combinations than :func:`sequence_partitions` because + empty sequence can fill everywhere, so we try to provide different + utility for this. + + Parameters + ========== + + l : Sequence[T] + A sequence of any Python objects (can be possibly empty) + + n : int + A positive integer + + Yields + ====== + + out : list[Sequence[T]] + A list of sequences with concatenation equals $l$. + This should conform with the type of $l$. + + Examples + ======== + + >>> from sympy.utilities.iterables import sequence_partitions_empty + >>> for out in sequence_partitions_empty([1, 2, 3, 4], 2): + ... print(out) + [[], [1, 2, 3, 4]] + [[1], [2, 3, 4]] + [[1, 2], [3, 4]] + [[1, 2, 3], [4]] + [[1, 2, 3, 4], []] + + See Also + ======== + + sequence_partitions + """ + if n < 1: + return + if n == 1: + yield [l] + return + for i in range(0, len(l) + 1): + for part in sequence_partitions_empty(l[i:], n - 1): + yield [l[:i]] + part + + +def kbins(l, k, ordered=None): + """ + Return sequence ``l`` partitioned into ``k`` bins. + + Examples + ======== + + The default is to give the items in the same order, but grouped + into k partitions without any reordering: + + >>> from sympy.utilities.iterables import kbins + >>> for p in kbins(list(range(5)), 2): + ... print(p) + ... + [[0], [1, 2, 3, 4]] + [[0, 1], [2, 3, 4]] + [[0, 1, 2], [3, 4]] + [[0, 1, 2, 3], [4]] + + The ``ordered`` flag is either None (to give the simple partition + of the elements) or is a 2 digit integer indicating whether the order of + the bins and the order of the items in the bins matters. Given:: + + A = [[0], [1, 2]] + B = [[1, 2], [0]] + C = [[2, 1], [0]] + D = [[0], [2, 1]] + + the following values for ``ordered`` have the shown meanings:: + + 00 means A == B == C == D + 01 means A == B + 10 means A == D + 11 means A == A + + >>> for ordered_flag in [None, 0, 1, 10, 11]: + ... print('ordered = %s' % ordered_flag) + ... for p in kbins(list(range(3)), 2, ordered=ordered_flag): + ... print(' %s' % p) + ... + ordered = None + [[0], [1, 2]] + [[0, 1], [2]] + ordered = 0 + [[0, 1], [2]] + [[0, 2], [1]] + [[0], [1, 2]] + ordered = 1 + [[0], [1, 2]] + [[0], [2, 1]] + [[1], [0, 2]] + [[1], [2, 0]] + [[2], [0, 1]] + [[2], [1, 0]] + ordered = 10 + [[0, 1], [2]] + [[2], [0, 1]] + [[0, 2], [1]] + [[1], [0, 2]] + [[0], [1, 2]] + [[1, 2], [0]] + ordered = 11 + [[0], [1, 2]] + [[0, 1], [2]] + [[0], [2, 1]] + [[0, 2], [1]] + [[1], [0, 2]] + [[1, 0], [2]] + [[1], [2, 0]] + [[1, 2], [0]] + [[2], [0, 1]] + [[2, 0], [1]] + [[2], [1, 0]] + [[2, 1], [0]] + + See Also + ======== + + partitions, multiset_partitions + + """ + if ordered is None: + yield from sequence_partitions(l, k) + elif ordered == 11: + for pl in multiset_permutations(l): + pl = list(pl) + yield from sequence_partitions(pl, k) + elif ordered == 00: + yield from multiset_partitions(l, k) + elif ordered == 10: + for p in multiset_partitions(l, k): + for perm in permutations(p): + yield list(perm) + elif ordered == 1: + for kgot, p in partitions(len(l), k, size=True): + if kgot != k: + continue + for li in multiset_permutations(l): + rv = [] + i = j = 0 + li = list(li) + for size, multiplicity in sorted(p.items()): + for m in range(multiplicity): + j = i + size + rv.append(li[i: j]) + i = j + yield rv + else: + raise ValueError( + 'ordered must be one of 00, 01, 10 or 11, not %s' % ordered) + + +def permute_signs(t): + """Return iterator in which the signs of non-zero elements + of t are permuted. + + Examples + ======== + + >>> from sympy.utilities.iterables import permute_signs + >>> list(permute_signs((0, 1, 2))) + [(0, 1, 2), (0, -1, 2), (0, 1, -2), (0, -1, -2)] + """ + for signs in product(*[(1, -1)]*(len(t) - t.count(0))): + signs = list(signs) + yield type(t)([i*signs.pop() if i else i for i in t]) + + +def signed_permutations(t): + """Return iterator in which the signs of non-zero elements + of t and the order of the elements are permuted and all + returned values are unique. + + Examples + ======== + + >>> from sympy.utilities.iterables import signed_permutations + >>> list(signed_permutations((0, 1, 2))) + [(0, 1, 2), (0, -1, 2), (0, 1, -2), (0, -1, -2), (0, 2, 1), + (0, -2, 1), (0, 2, -1), (0, -2, -1), (1, 0, 2), (-1, 0, 2), + (1, 0, -2), (-1, 0, -2), (1, 2, 0), (-1, 2, 0), (1, -2, 0), + (-1, -2, 0), (2, 0, 1), (-2, 0, 1), (2, 0, -1), (-2, 0, -1), + (2, 1, 0), (-2, 1, 0), (2, -1, 0), (-2, -1, 0)] + """ + return (type(t)(i) for j in multiset_permutations(t) + for i in permute_signs(j)) + + +def rotations(s, dir=1): + """Return a generator giving the items in s as list where + each subsequent list has the items rotated to the left (default) + or right (``dir=-1``) relative to the previous list. + + Examples + ======== + + >>> from sympy import rotations + >>> list(rotations([1,2,3])) + [[1, 2, 3], [2, 3, 1], [3, 1, 2]] + >>> list(rotations([1,2,3], -1)) + [[1, 2, 3], [3, 1, 2], [2, 3, 1]] + """ + seq = list(s) + for i in range(len(seq)): + yield seq + seq = rotate_left(seq, dir) + + +def roundrobin(*iterables): + """roundrobin recipe taken from itertools documentation: + https://docs.python.org/3/library/itertools.html#itertools-recipes + + roundrobin('ABC', 'D', 'EF') --> A D E B F C + + Recipe credited to George Sakkis + """ + nexts = cycle(iter(it).__next__ for it in iterables) + + pending = len(iterables) + while pending: + try: + for nxt in nexts: + yield nxt() + except StopIteration: + pending -= 1 + nexts = cycle(islice(nexts, pending)) + + + +class NotIterable: + """ + Use this as mixin when creating a class which is not supposed to + return true when iterable() is called on its instances because + calling list() on the instance, for example, would result in + an infinite loop. + """ + pass + + +def iterable(i, exclude=(str, dict, NotIterable)): + """ + Return a boolean indicating whether ``i`` is SymPy iterable. + True also indicates that the iterator is finite, e.g. you can + call list(...) on the instance. + + When SymPy is working with iterables, it is almost always assuming + that the iterable is not a string or a mapping, so those are excluded + by default. If you want a pure Python definition, make exclude=None. To + exclude multiple items, pass them as a tuple. + + You can also set the _iterable attribute to True or False on your class, + which will override the checks here, including the exclude test. + + As a rule of thumb, some SymPy functions use this to check if they should + recursively map over an object. If an object is technically iterable in + the Python sense but does not desire this behavior (e.g., because its + iteration is not finite, or because iteration might induce an unwanted + computation), it should disable it by setting the _iterable attribute to False. + + See also: is_sequence + + Examples + ======== + + >>> from sympy.utilities.iterables import iterable + >>> from sympy import Tuple + >>> things = [[1], (1,), set([1]), Tuple(1), (j for j in [1, 2]), {1:2}, '1', 1] + >>> for i in things: + ... print('%s %s' % (iterable(i), type(i))) + True <... 'list'> + True <... 'tuple'> + True <... 'set'> + True + True <... 'generator'> + False <... 'dict'> + False <... 'str'> + False <... 'int'> + + >>> iterable({}, exclude=None) + True + >>> iterable({}, exclude=str) + True + >>> iterable("no", exclude=str) + False + + """ + if hasattr(i, '_iterable'): + return i._iterable + try: + iter(i) + except TypeError: + return False + if exclude: + return not isinstance(i, exclude) + return True + + +def is_sequence(i, include=None): + """ + Return a boolean indicating whether ``i`` is a sequence in the SymPy + sense. If anything that fails the test below should be included as + being a sequence for your application, set 'include' to that object's + type; multiple types should be passed as a tuple of types. + + Note: although generators can generate a sequence, they often need special + handling to make sure their elements are captured before the generator is + exhausted, so these are not included by default in the definition of a + sequence. + + See also: iterable + + Examples + ======== + + >>> from sympy.utilities.iterables import is_sequence + >>> from types import GeneratorType + >>> is_sequence([]) + True + >>> is_sequence(set()) + False + >>> is_sequence('abc') + False + >>> is_sequence('abc', include=str) + True + >>> generator = (c for c in 'abc') + >>> is_sequence(generator) + False + >>> is_sequence(generator, include=(str, GeneratorType)) + True + + """ + return (hasattr(i, '__getitem__') and + iterable(i) or + bool(include) and + isinstance(i, include)) + + +@deprecated( + """ + Using postorder_traversal from the sympy.utilities.iterables submodule is + deprecated. + + Instead, use postorder_traversal from the top-level sympy namespace, like + + sympy.postorder_traversal + """, + deprecated_since_version="1.10", + active_deprecations_target="deprecated-traversal-functions-moved") +def postorder_traversal(node, keys=None): + from sympy.core.traversal import postorder_traversal as _postorder_traversal + return _postorder_traversal(node, keys=keys) + + +@deprecated( + """ + Using interactive_traversal from the sympy.utilities.iterables submodule + is deprecated. + + Instead, use interactive_traversal from the top-level sympy namespace, + like + + sympy.interactive_traversal + """, + deprecated_since_version="1.10", + active_deprecations_target="deprecated-traversal-functions-moved") +def interactive_traversal(expr): + from sympy.interactive.traversal import interactive_traversal as _interactive_traversal + return _interactive_traversal(expr) + + +@deprecated( + """ + Importing default_sort_key from sympy.utilities.iterables is deprecated. + Use from sympy import default_sort_key instead. + """, + deprecated_since_version="1.10", +active_deprecations_target="deprecated-sympy-core-compatibility", +) +def default_sort_key(*args, **kwargs): + from sympy import default_sort_key as _default_sort_key + return _default_sort_key(*args, **kwargs) + + +@deprecated( + """ + Importing default_sort_key from sympy.utilities.iterables is deprecated. + Use from sympy import default_sort_key instead. + """, + deprecated_since_version="1.10", +active_deprecations_target="deprecated-sympy-core-compatibility", +) +def ordered(*args, **kwargs): + from sympy import ordered as _ordered + return _ordered(*args, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/lambdify.py b/.venv/lib/python3.12/site-packages/sympy/utilities/lambdify.py new file mode 100644 index 0000000000000000000000000000000000000000..6807fdaec10963a60ba88d6e1ec6b2951c19241e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/lambdify.py @@ -0,0 +1,1592 @@ +""" +This module provides convenient functions to transform SymPy expressions to +lambda functions which can be used to calculate numerical values very fast. +""" + +from __future__ import annotations +from typing import Any + +import builtins +import inspect +import keyword +import textwrap +import linecache +import weakref + +# Required despite static analysis claiming it is not used +from sympy.external import import_module # noqa:F401 +from sympy.utilities.exceptions import sympy_deprecation_warning +from sympy.utilities.decorator import doctest_depends_on +from sympy.utilities.iterables import (is_sequence, iterable, + NotIterable, flatten) +from sympy.utilities.misc import filldedent + + +__doctest_requires__ = {('lambdify',): ['numpy', 'tensorflow']} + + +# Default namespaces, letting us define translations that can't be defined +# by simple variable maps, like I => 1j +MATH_DEFAULT: dict[str, Any] = {} +CMATH_DEFAULT: dict[str,Any] = {} +MPMATH_DEFAULT: dict[str, Any] = {} +NUMPY_DEFAULT: dict[str, Any] = {"I": 1j} +SCIPY_DEFAULT: dict[str, Any] = {"I": 1j} +CUPY_DEFAULT: dict[str, Any] = {"I": 1j} +JAX_DEFAULT: dict[str, Any] = {"I": 1j} +TENSORFLOW_DEFAULT: dict[str, Any] = {} +TORCH_DEFAULT: dict[str, Any] = {"I": 1j} +SYMPY_DEFAULT: dict[str, Any] = {} +NUMEXPR_DEFAULT: dict[str, Any] = {} + +# These are the namespaces the lambda functions will use. +# These are separate from the names above because they are modified +# throughout this file, whereas the defaults should remain unmodified. + +MATH = MATH_DEFAULT.copy() +CMATH = CMATH_DEFAULT.copy() +MPMATH = MPMATH_DEFAULT.copy() +NUMPY = NUMPY_DEFAULT.copy() +SCIPY = SCIPY_DEFAULT.copy() +CUPY = CUPY_DEFAULT.copy() +JAX = JAX_DEFAULT.copy() +TENSORFLOW = TENSORFLOW_DEFAULT.copy() +TORCH = TORCH_DEFAULT.copy() +SYMPY = SYMPY_DEFAULT.copy() +NUMEXPR = NUMEXPR_DEFAULT.copy() + + +# Mappings between SymPy and other modules function names. +MATH_TRANSLATIONS = { + "ceiling": "ceil", + "E": "e", + "ln": "log", +} + +CMATH_TRANSLATIONS: dict[str, str] = {} + +# NOTE: This dictionary is reused in Function._eval_evalf to allow subclasses +# of Function to automatically evalf. +MPMATH_TRANSLATIONS = { + "Abs": "fabs", + "elliptic_k": "ellipk", + "elliptic_f": "ellipf", + "elliptic_e": "ellipe", + "elliptic_pi": "ellippi", + "ceiling": "ceil", + "chebyshevt": "chebyt", + "chebyshevu": "chebyu", + "assoc_legendre": "legenp", + "E": "e", + "I": "j", + "ln": "log", + #"lowergamma":"lower_gamma", + "oo": "inf", + #"uppergamma":"upper_gamma", + "LambertW": "lambertw", + "MutableDenseMatrix": "matrix", + "ImmutableDenseMatrix": "matrix", + "conjugate": "conj", + "dirichlet_eta": "altzeta", + "Ei": "ei", + "Shi": "shi", + "Chi": "chi", + "Si": "si", + "Ci": "ci", + "RisingFactorial": "rf", + "FallingFactorial": "ff", + "betainc_regularized": "betainc", +} + +NUMPY_TRANSLATIONS: dict[str, str] = { + "Heaviside": "heaviside", +} +SCIPY_TRANSLATIONS: dict[str, str] = { + "jn" : "spherical_jn", + "yn" : "spherical_yn" +} +CUPY_TRANSLATIONS: dict[str, str] = {} +JAX_TRANSLATIONS: dict[str, str] = {} + +TENSORFLOW_TRANSLATIONS: dict[str, str] = {} +TORCH_TRANSLATIONS: dict[str, str] = {} + +NUMEXPR_TRANSLATIONS: dict[str, str] = {} + +# Available modules: +MODULES = { + "math": (MATH, MATH_DEFAULT, MATH_TRANSLATIONS, ("from math import *",)), + "cmath": (CMATH, CMATH_DEFAULT, CMATH_TRANSLATIONS, ("import cmath; from cmath import *",)), + "mpmath": (MPMATH, MPMATH_DEFAULT, MPMATH_TRANSLATIONS, ("from mpmath import *",)), + "numpy": (NUMPY, NUMPY_DEFAULT, NUMPY_TRANSLATIONS, ("import numpy; from numpy import *; from numpy.linalg import *",)), + "scipy": (SCIPY, SCIPY_DEFAULT, SCIPY_TRANSLATIONS, ("import scipy; import numpy; from scipy.special import *",)), + "cupy": (CUPY, CUPY_DEFAULT, CUPY_TRANSLATIONS, ("import cupy",)), + "jax": (JAX, JAX_DEFAULT, JAX_TRANSLATIONS, ("import jax",)), + "tensorflow": (TENSORFLOW, TENSORFLOW_DEFAULT, TENSORFLOW_TRANSLATIONS, ("import tensorflow",)), + "torch": (TORCH, TORCH_DEFAULT, TORCH_TRANSLATIONS, ("import torch",)), + "sympy": (SYMPY, SYMPY_DEFAULT, {}, ( + "from sympy.functions import *", + "from sympy.matrices import *", + "from sympy import Integral, pi, oo, nan, zoo, E, I",)), + "numexpr" : (NUMEXPR, NUMEXPR_DEFAULT, NUMEXPR_TRANSLATIONS, + ("import_module('numexpr')", )), +} + + +def _import(module, reload=False): + """ + Creates a global translation dictionary for module. + + The argument module has to be one of the following strings: "math","cmath" + "mpmath", "numpy", "sympy", "tensorflow", "jax". + These dictionaries map names of Python functions to their equivalent in + other modules. + """ + try: + namespace, namespace_default, translations, import_commands = MODULES[ + module] + except KeyError: + raise NameError( + "'%s' module cannot be used for lambdification" % module) + + # Clear namespace or exit + if namespace != namespace_default: + # The namespace was already generated, don't do it again if not forced. + if reload: + namespace.clear() + namespace.update(namespace_default) + else: + return + + for import_command in import_commands: + if import_command.startswith('import_module'): + module = eval(import_command) + + if module is not None: + namespace.update(module.__dict__) + continue + else: + try: + exec(import_command, {}, namespace) + continue + except ImportError: + pass + + raise ImportError( + "Cannot import '%s' with '%s' command" % (module, import_command)) + + # Add translated names to namespace + for sympyname, translation in translations.items(): + namespace[sympyname] = namespace[translation] + + # For computing the modulus of a SymPy expression we use the builtin abs + # function, instead of the previously used fabs function for all + # translation modules. This is because the fabs function in the math + # module does not accept complex valued arguments. (see issue 9474). The + # only exception, where we don't use the builtin abs function is the + # mpmath translation module, because mpmath.fabs returns mpf objects in + # contrast to abs(). + if 'Abs' not in namespace: + namespace['Abs'] = abs + +# Used for dynamically generated filenames that are inserted into the +# linecache. +_lambdify_generated_counter = 1 + + +@doctest_depends_on(modules=('numpy', 'scipy', 'tensorflow',), python_version=(3,)) +def lambdify(args, expr, modules=None, printer=None, use_imps=True, + dummify=False, cse=False, docstring_limit=1000): + """Convert a SymPy expression into a function that allows for fast + numeric evaluation. + + .. warning:: + This function uses ``exec``, and thus should not be used on + unsanitized input. + + .. deprecated:: 1.7 + Passing a set for the *args* parameter is deprecated as sets are + unordered. Use an ordered iterable such as a list or tuple. + + Explanation + =========== + + For example, to convert the SymPy expression ``sin(x) + cos(x)`` to an + equivalent NumPy function that numerically evaluates it: + + >>> from sympy import sin, cos, symbols, lambdify + >>> import numpy as np + >>> x = symbols('x') + >>> expr = sin(x) + cos(x) + >>> expr + sin(x) + cos(x) + >>> f = lambdify(x, expr, 'numpy') + >>> a = np.array([1, 2]) + >>> f(a) + [1.38177329 0.49315059] + + The primary purpose of this function is to provide a bridge from SymPy + expressions to numerical libraries such as NumPy, SciPy, NumExpr, mpmath, + and tensorflow. In general, SymPy functions do not work with objects from + other libraries, such as NumPy arrays, and functions from numeric + libraries like NumPy or mpmath do not work on SymPy expressions. + ``lambdify`` bridges the two by converting a SymPy expression to an + equivalent numeric function. + + The basic workflow with ``lambdify`` is to first create a SymPy expression + representing whatever mathematical function you wish to evaluate. This + should be done using only SymPy functions and expressions. Then, use + ``lambdify`` to convert this to an equivalent function for numerical + evaluation. For instance, above we created ``expr`` using the SymPy symbol + ``x`` and SymPy functions ``sin`` and ``cos``, then converted it to an + equivalent NumPy function ``f``, and called it on a NumPy array ``a``. + + Parameters + ========== + + args : List[Symbol] + A variable or a list of variables whose nesting represents the + nesting of the arguments that will be passed to the function. + + Variables can be symbols, undefined functions, or matrix symbols. + + >>> from sympy import Eq + >>> from sympy.abc import x, y, z + + The list of variables should match the structure of how the + arguments will be passed to the function. Simply enclose the + parameters as they will be passed in a list. + + To call a function like ``f(x)`` then ``[x]`` + should be the first argument to ``lambdify``; for this + case a single ``x`` can also be used: + + >>> f = lambdify(x, x + 1) + >>> f(1) + 2 + >>> f = lambdify([x], x + 1) + >>> f(1) + 2 + + To call a function like ``f(x, y)`` then ``[x, y]`` will + be the first argument of the ``lambdify``: + + >>> f = lambdify([x, y], x + y) + >>> f(1, 1) + 2 + + To call a function with a single 3-element tuple like + ``f((x, y, z))`` then ``[(x, y, z)]`` will be the first + argument of the ``lambdify``: + + >>> f = lambdify([(x, y, z)], Eq(z**2, x**2 + y**2)) + >>> f((3, 4, 5)) + True + + If two args will be passed and the first is a scalar but + the second is a tuple with two arguments then the items + in the list should match that structure: + + >>> f = lambdify([x, (y, z)], x + y + z) + >>> f(1, (2, 3)) + 6 + + expr : Expr + An expression, list of expressions, or matrix to be evaluated. + + Lists may be nested. + If the expression is a list, the output will also be a list. + + >>> f = lambdify(x, [x, [x + 1, x + 2]]) + >>> f(1) + [1, [2, 3]] + + If it is a matrix, an array will be returned (for the NumPy module). + + >>> from sympy import Matrix + >>> f = lambdify(x, Matrix([x, x + 1])) + >>> f(1) + [[1] + [2]] + + Note that the argument order here (variables then expression) is used + to emulate the Python ``lambda`` keyword. ``lambdify(x, expr)`` works + (roughly) like ``lambda x: expr`` + (see :ref:`lambdify-how-it-works` below). + + modules : str, optional + Specifies the numeric library to use. + + If not specified, *modules* defaults to: + + - ``["scipy", "numpy"]`` if SciPy is installed + - ``["numpy"]`` if only NumPy is installed + - ``["math","cmath", "mpmath", "sympy"]`` if neither is installed. + + That is, SymPy functions are replaced as far as possible by + either ``scipy`` or ``numpy`` functions if available, and Python's + standard library ``math`` and ``cmath``, or ``mpmath`` functions otherwise. + + *modules* can be one of the following types: + + - The strings ``"math"``, ``"cmath"``, ``"mpmath"``, ``"numpy"``, ``"numexpr"``, + ``"scipy"``, ``"sympy"``, or ``"tensorflow"`` or ``"jax"``. This uses the + corresponding printer and namespace mapping for that module. + - A module (e.g., ``math``). This uses the global namespace of the + module. If the module is one of the above known modules, it will + also use the corresponding printer and namespace mapping + (i.e., ``modules=numpy`` is equivalent to ``modules="numpy"``). + - A dictionary that maps names of SymPy functions to arbitrary + functions + (e.g., ``{'sin': custom_sin}``). + - A list that contains a mix of the arguments above, with higher + priority given to entries appearing first + (e.g., to use the NumPy module but override the ``sin`` function + with a custom version, you can use + ``[{'sin': custom_sin}, 'numpy']``). + + dummify : bool, optional + Whether or not the variables in the provided expression that are not + valid Python identifiers are substituted with dummy symbols. + + This allows for undefined functions like ``Function('f')(t)`` to be + supplied as arguments. By default, the variables are only dummified + if they are not valid Python identifiers. + + Set ``dummify=True`` to replace all arguments with dummy symbols + (if ``args`` is not a string) - for example, to ensure that the + arguments do not redefine any built-in names. + + cse : bool, or callable, optional + Large expressions can be computed more efficiently when + common subexpressions are identified and precomputed before + being used multiple time. Finding the subexpressions will make + creation of the 'lambdify' function slower, however. + + When ``True``, ``sympy.simplify.cse`` is used, otherwise (the default) + the user may pass a function matching the ``cse`` signature. + + docstring_limit : int or None + When lambdifying large expressions, a significant proportion of the time + spent inside ``lambdify`` is spent producing a string representation of + the expression for use in the automatically generated docstring of the + returned function. For expressions containing hundreds or more nodes the + resulting docstring often becomes so long and dense that it is difficult + to read. To reduce the runtime of lambdify, the rendering of the full + expression inside the docstring can be disabled. + + When ``None``, the full expression is rendered in the docstring. When + ``0`` or a negative ``int``, an ellipsis is rendering in the docstring + instead of the expression. When a strictly positive ``int``, if the + number of nodes in the expression exceeds ``docstring_limit`` an + ellipsis is rendered in the docstring, otherwise a string representation + of the expression is rendered as normal. The default is ``1000``. + + Examples + ======== + + >>> from sympy.utilities.lambdify import implemented_function + >>> from sympy import sqrt, sin, Matrix + >>> from sympy import Function + >>> from sympy.abc import w, x, y, z + + >>> f = lambdify(x, x**2) + >>> f(2) + 4 + >>> f = lambdify((x, y, z), [z, y, x]) + >>> f(1,2,3) + [3, 2, 1] + >>> f = lambdify(x, sqrt(x)) + >>> f(4) + 2.0 + >>> f = lambdify((x, y), sin(x*y)**2) + >>> f(0, 5) + 0.0 + >>> row = lambdify((x, y), Matrix((x, x + y)).T, modules='sympy') + >>> row(1, 2) + Matrix([[1, 3]]) + + ``lambdify`` can be used to translate SymPy expressions into mpmath + functions. This may be preferable to using ``evalf`` (which uses mpmath on + the backend) in some cases. + + >>> f = lambdify(x, sin(x), 'mpmath') + >>> f(1) + 0.8414709848078965 + + Tuple arguments are handled and the lambdified function should + be called with the same type of arguments as were used to create + the function: + + >>> f = lambdify((x, (y, z)), x + y) + >>> f(1, (2, 4)) + 3 + + The ``flatten`` function can be used to always work with flattened + arguments: + + >>> from sympy.utilities.iterables import flatten + >>> args = w, (x, (y, z)) + >>> vals = 1, (2, (3, 4)) + >>> f = lambdify(flatten(args), w + x + y + z) + >>> f(*flatten(vals)) + 10 + + Functions present in ``expr`` can also carry their own numerical + implementations, in a callable attached to the ``_imp_`` attribute. This + can be used with undefined functions using the ``implemented_function`` + factory: + + >>> f = implemented_function(Function('f'), lambda x: x+1) + >>> func = lambdify(x, f(x)) + >>> func(4) + 5 + + ``lambdify`` always prefers ``_imp_`` implementations to implementations + in other namespaces, unless the ``use_imps`` input parameter is False. + + Usage with Tensorflow: + + >>> import tensorflow as tf + >>> from sympy import Max, sin, lambdify + >>> from sympy.abc import x + + >>> f = Max(x, sin(x)) + >>> func = lambdify(x, f, 'tensorflow') + + After tensorflow v2, eager execution is enabled by default. + If you want to get the compatible result across tensorflow v1 and v2 + as same as this tutorial, run this line. + + >>> tf.compat.v1.enable_eager_execution() + + If you have eager execution enabled, you can get the result out + immediately as you can use numpy. + + If you pass tensorflow objects, you may get an ``EagerTensor`` + object instead of value. + + >>> result = func(tf.constant(1.0)) + >>> print(result) + tf.Tensor(1.0, shape=(), dtype=float32) + >>> print(result.__class__) + + + You can use ``.numpy()`` to get the numpy value of the tensor. + + >>> result.numpy() + 1.0 + + >>> var = tf.Variable(2.0) + >>> result = func(var) # also works for tf.Variable and tf.Placeholder + >>> result.numpy() + 2.0 + + And it works with any shape array. + + >>> tensor = tf.constant([[1.0, 2.0], [3.0, 4.0]]) + >>> result = func(tensor) + >>> result.numpy() + [[1. 2.] + [3. 4.]] + + Notes + ===== + + - For functions involving large array calculations, numexpr can provide a + significant speedup over numpy. Please note that the available functions + for numexpr are more limited than numpy but can be expanded with + ``implemented_function`` and user defined subclasses of Function. If + specified, numexpr may be the only option in modules. The official list + of numexpr functions can be found at: + https://numexpr.readthedocs.io/en/latest/user_guide.html#supported-functions + + - In the above examples, the generated functions can accept scalar + values or numpy arrays as arguments. However, in some cases + the generated function relies on the input being a numpy array: + + >>> import numpy + >>> from sympy import Piecewise + >>> from sympy.testing.pytest import ignore_warnings + >>> f = lambdify(x, Piecewise((x, x <= 1), (1/x, x > 1)), "numpy") + + >>> with ignore_warnings(RuntimeWarning): + ... f(numpy.array([-1, 0, 1, 2])) + [-1. 0. 1. 0.5] + + >>> f(0) + Traceback (most recent call last): + ... + ZeroDivisionError: division by zero + + In such cases, the input should be wrapped in a numpy array: + + >>> with ignore_warnings(RuntimeWarning): + ... float(f(numpy.array([0]))) + 0.0 + + Or if numpy functionality is not required another module can be used: + + >>> f = lambdify(x, Piecewise((x, x <= 1), (1/x, x > 1)), "math") + >>> f(0) + 0 + + .. _lambdify-how-it-works: + + How it works + ============ + + When using this function, it helps a great deal to have an idea of what it + is doing. At its core, lambdify is nothing more than a namespace + translation, on top of a special printer that makes some corner cases work + properly. + + To understand lambdify, first we must properly understand how Python + namespaces work. Say we had two files. One called ``sin_cos_sympy.py``, + with + + .. code:: python + + # sin_cos_sympy.py + + from sympy.functions.elementary.trigonometric import (cos, sin) + + def sin_cos(x): + return sin(x) + cos(x) + + + and one called ``sin_cos_numpy.py`` with + + .. code:: python + + # sin_cos_numpy.py + + from numpy import sin, cos + + def sin_cos(x): + return sin(x) + cos(x) + + The two files define an identical function ``sin_cos``. However, in the + first file, ``sin`` and ``cos`` are defined as the SymPy ``sin`` and + ``cos``. In the second, they are defined as the NumPy versions. + + If we were to import the first file and use the ``sin_cos`` function, we + would get something like + + >>> from sin_cos_sympy import sin_cos # doctest: +SKIP + >>> sin_cos(1) # doctest: +SKIP + cos(1) + sin(1) + + On the other hand, if we imported ``sin_cos`` from the second file, we + would get + + >>> from sin_cos_numpy import sin_cos # doctest: +SKIP + >>> sin_cos(1) # doctest: +SKIP + 1.38177329068 + + In the first case we got a symbolic output, because it used the symbolic + ``sin`` and ``cos`` functions from SymPy. In the second, we got a numeric + result, because ``sin_cos`` used the numeric ``sin`` and ``cos`` functions + from NumPy. But notice that the versions of ``sin`` and ``cos`` that were + used was not inherent to the ``sin_cos`` function definition. Both + ``sin_cos`` definitions are exactly the same. Rather, it was based on the + names defined at the module where the ``sin_cos`` function was defined. + + The key point here is that when function in Python references a name that + is not defined in the function, that name is looked up in the "global" + namespace of the module where that function is defined. + + Now, in Python, we can emulate this behavior without actually writing a + file to disk using the ``exec`` function. ``exec`` takes a string + containing a block of Python code, and a dictionary that should contain + the global variables of the module. It then executes the code "in" that + dictionary, as if it were the module globals. The following is equivalent + to the ``sin_cos`` defined in ``sin_cos_sympy.py``: + + >>> import sympy + >>> module_dictionary = {'sin': sympy.sin, 'cos': sympy.cos} + >>> exec(''' + ... def sin_cos(x): + ... return sin(x) + cos(x) + ... ''', module_dictionary) + >>> sin_cos = module_dictionary['sin_cos'] + >>> sin_cos(1) + cos(1) + sin(1) + + and similarly with ``sin_cos_numpy``: + + >>> import numpy + >>> module_dictionary = {'sin': numpy.sin, 'cos': numpy.cos} + >>> exec(''' + ... def sin_cos(x): + ... return sin(x) + cos(x) + ... ''', module_dictionary) + >>> sin_cos = module_dictionary['sin_cos'] + >>> sin_cos(1) + 1.38177329068 + + So now we can get an idea of how ``lambdify`` works. The name "lambdify" + comes from the fact that we can think of something like ``lambdify(x, + sin(x) + cos(x), 'numpy')`` as ``lambda x: sin(x) + cos(x)``, where + ``sin`` and ``cos`` come from the ``numpy`` namespace. This is also why + the symbols argument is first in ``lambdify``, as opposed to most SymPy + functions where it comes after the expression: to better mimic the + ``lambda`` keyword. + + ``lambdify`` takes the input expression (like ``sin(x) + cos(x)``) and + + 1. Converts it to a string + 2. Creates a module globals dictionary based on the modules that are + passed in (by default, it uses the NumPy module) + 3. Creates the string ``"def func({vars}): return {expr}"``, where ``{vars}`` is the + list of variables separated by commas, and ``{expr}`` is the string + created in step 1., then ``exec``s that string with the module globals + namespace and returns ``func``. + + In fact, functions returned by ``lambdify`` support inspection. So you can + see exactly how they are defined by using ``inspect.getsource``, or ``??`` if you + are using IPython or the Jupyter notebook. + + >>> f = lambdify(x, sin(x) + cos(x)) + >>> import inspect + >>> print(inspect.getsource(f)) + def _lambdifygenerated(x): + return sin(x) + cos(x) + + This shows us the source code of the function, but not the namespace it + was defined in. We can inspect that by looking at the ``__globals__`` + attribute of ``f``: + + >>> f.__globals__['sin'] + + >>> f.__globals__['cos'] + + >>> f.__globals__['sin'] is numpy.sin + True + + This shows us that ``sin`` and ``cos`` in the namespace of ``f`` will be + ``numpy.sin`` and ``numpy.cos``. + + Note that there are some convenience layers in each of these steps, but at + the core, this is how ``lambdify`` works. Step 1 is done using the + ``LambdaPrinter`` printers defined in the printing module (see + :mod:`sympy.printing.lambdarepr`). This allows different SymPy expressions + to define how they should be converted to a string for different modules. + You can change which printer ``lambdify`` uses by passing a custom printer + in to the ``printer`` argument. + + Step 2 is augmented by certain translations. There are default + translations for each module, but you can provide your own by passing a + list to the ``modules`` argument. For instance, + + >>> def mysin(x): + ... print('taking the sin of', x) + ... return numpy.sin(x) + ... + >>> f = lambdify(x, sin(x), [{'sin': mysin}, 'numpy']) + >>> f(1) + taking the sin of 1 + 0.8414709848078965 + + The globals dictionary is generated from the list by merging the + dictionary ``{'sin': mysin}`` and the module dictionary for NumPy. The + merging is done so that earlier items take precedence, which is why + ``mysin`` is used above instead of ``numpy.sin``. + + If you want to modify the way ``lambdify`` works for a given function, it + is usually easiest to do so by modifying the globals dictionary as such. + In more complicated cases, it may be necessary to create and pass in a + custom printer. + + Finally, step 3 is augmented with certain convenience operations, such as + the addition of a docstring. + + Understanding how ``lambdify`` works can make it easier to avoid certain + gotchas when using it. For instance, a common mistake is to create a + lambdified function for one module (say, NumPy), and pass it objects from + another (say, a SymPy expression). + + For instance, say we create + + >>> from sympy.abc import x + >>> f = lambdify(x, x + 1, 'numpy') + + Now if we pass in a NumPy array, we get that array plus 1 + + >>> import numpy + >>> a = numpy.array([1, 2]) + >>> f(a) + [2 3] + + But what happens if you make the mistake of passing in a SymPy expression + instead of a NumPy array: + + >>> f(x + 1) + x + 2 + + This worked, but it was only by accident. Now take a different lambdified + function: + + >>> from sympy import sin + >>> g = lambdify(x, x + sin(x), 'numpy') + + This works as expected on NumPy arrays: + + >>> g(a) + [1.84147098 2.90929743] + + But if we try to pass in a SymPy expression, it fails + + >>> g(x + 1) + Traceback (most recent call last): + ... + TypeError: loop of ufunc does not support argument 0 of type Add which has + no callable sin method + + Now, let's look at what happened. The reason this fails is that ``g`` + calls ``numpy.sin`` on the input expression, and ``numpy.sin`` does not + know how to operate on a SymPy object. **As a general rule, NumPy + functions do not know how to operate on SymPy expressions, and SymPy + functions do not know how to operate on NumPy arrays. This is why lambdify + exists: to provide a bridge between SymPy and NumPy.** + + However, why is it that ``f`` did work? That's because ``f`` does not call + any functions, it only adds 1. So the resulting function that is created, + ``def _lambdifygenerated(x): return x + 1`` does not depend on the globals + namespace it is defined in. Thus it works, but only by accident. A future + version of ``lambdify`` may remove this behavior. + + Be aware that certain implementation details described here may change in + future versions of SymPy. The API of passing in custom modules and + printers will not change, but the details of how a lambda function is + created may change. However, the basic idea will remain the same, and + understanding it will be helpful to understanding the behavior of + lambdify. + + **In general: you should create lambdified functions for one module (say, + NumPy), and only pass it input types that are compatible with that module + (say, NumPy arrays).** Remember that by default, if the ``module`` + argument is not provided, ``lambdify`` creates functions using the NumPy + and SciPy namespaces. + """ + from sympy.core.symbol import Symbol + from sympy.core.expr import Expr + + # If the user hasn't specified any modules, use what is available. + if modules is None: + try: + _import("scipy") + except ImportError: + try: + _import("numpy") + except ImportError: + # Use either numpy (if available) or python.math where possible. + # XXX: This leads to different behaviour on different systems and + # might be the reason for irreproducible errors. + modules = ["math", "mpmath", "sympy"] + else: + modules = ["numpy"] + else: + modules = ["numpy", "scipy"] + + # Get the needed namespaces. + namespaces = [] + # First find any function implementations + if use_imps: + namespaces.append(_imp_namespace(expr)) + # Check for dict before iterating + if isinstance(modules, (dict, str)) or not hasattr(modules, '__iter__'): + namespaces.append(modules) + else: + # consistency check + if _module_present('numexpr', modules) and len(modules) > 1: + raise TypeError("numexpr must be the only item in 'modules'") + namespaces += list(modules) + # fill namespace with first having highest priority + namespace = {} + for m in namespaces[::-1]: + buf = _get_namespace(m) + namespace.update(buf) + + if hasattr(expr, "atoms"): + #Try if you can extract symbols from the expression. + #Move on if expr.atoms in not implemented. + syms = expr.atoms(Symbol) + for term in syms: + namespace.update({str(term): term}) + + if printer is None: + if _module_present('mpmath', namespaces): + from sympy.printing.pycode import MpmathPrinter as Printer # type: ignore + elif _module_present('scipy', namespaces): + from sympy.printing.numpy import SciPyPrinter as Printer # type: ignore + elif _module_present('numpy', namespaces): + from sympy.printing.numpy import NumPyPrinter as Printer # type: ignore + elif _module_present('cupy', namespaces): + from sympy.printing.numpy import CuPyPrinter as Printer # type: ignore + elif _module_present('jax', namespaces): + from sympy.printing.numpy import JaxPrinter as Printer # type: ignore + elif _module_present('numexpr', namespaces): + from sympy.printing.lambdarepr import NumExprPrinter as Printer # type: ignore + elif _module_present('tensorflow', namespaces): + from sympy.printing.tensorflow import TensorflowPrinter as Printer # type: ignore + elif _module_present('torch', namespaces): + from sympy.printing.pytorch import TorchPrinter as Printer # type: ignore + elif _module_present('sympy', namespaces): + from sympy.printing.pycode import SymPyPrinter as Printer # type: ignore + elif _module_present('cmath', namespaces): + from sympy.printing.pycode import CmathPrinter as Printer # type: ignore + else: + from sympy.printing.pycode import PythonCodePrinter as Printer # type: ignore + user_functions = {} + for m in namespaces[::-1]: + if isinstance(m, dict): + for k in m: + user_functions[k] = k + printer = Printer({'fully_qualified_modules': False, 'inline': True, + 'allow_unknown_functions': True, + 'user_functions': user_functions}) + + if isinstance(args, set): + sympy_deprecation_warning( + """ +Passing the function arguments to lambdify() as a set is deprecated. This +leads to unpredictable results since sets are unordered. Instead, use a list +or tuple for the function arguments. + """, + deprecated_since_version="1.6.3", + active_deprecations_target="deprecated-lambdify-arguments-set", + ) + + # Get the names of the args, for creating a docstring + iterable_args = (args,) if isinstance(args, Expr) else args + names = [] + + # Grab the callers frame, for getting the names by inspection (if needed) + callers_local_vars = inspect.currentframe().f_back.f_locals.items() # type: ignore + for n, var in enumerate(iterable_args): + if hasattr(var, 'name'): + names.append(var.name) + else: + # It's an iterable. Try to get name by inspection of calling frame. + name_list = [var_name for var_name, var_val in callers_local_vars + if var_val is var] + if len(name_list) == 1: + names.append(name_list[0]) + else: + # Cannot infer name with certainty. arg_# will have to do. + names.append('arg_' + str(n)) + + # Create the function definition code and execute it + funcname = '_lambdifygenerated' + if _module_present('tensorflow', namespaces): + funcprinter = _TensorflowEvaluatorPrinter(printer, dummify) + else: + funcprinter = _EvaluatorPrinter(printer, dummify) + + if cse == True: + from sympy.simplify.cse_main import cse as _cse + cses, _expr = _cse(expr, list=False) + elif callable(cse): + cses, _expr = cse(expr) + else: + cses, _expr = (), expr + funcstr = funcprinter.doprint(funcname, iterable_args, _expr, cses=cses) + + # Collect the module imports from the code printers. + imp_mod_lines = [] + for mod, keys in (getattr(printer, 'module_imports', None) or {}).items(): + for k in keys: + if k not in namespace: + ln = "from %s import %s" % (mod, k) + try: + exec(ln, {}, namespace) + except ImportError: + # Tensorflow 2.0 has issues with importing a specific + # function from its submodule. + # https://github.com/tensorflow/tensorflow/issues/33022 + ln = "%s = %s.%s" % (k, mod, k) + exec(ln, {}, namespace) + imp_mod_lines.append(ln) + + # Provide lambda expression with builtins, and compatible implementation of range + namespace.update({'builtins':builtins, 'range':range}) + + funclocals = {} + global _lambdify_generated_counter + filename = '' % _lambdify_generated_counter + _lambdify_generated_counter += 1 + c = compile(funcstr, filename, 'exec') + exec(c, namespace, funclocals) + # mtime has to be None or else linecache.checkcache will remove it + linecache.cache[filename] = (len(funcstr), None, funcstr.splitlines(True), filename) # type: ignore + + # Remove the entry from the linecache when the object is garbage collected + def cleanup_linecache(filename): + def _cleanup(): + if filename in linecache.cache: + del linecache.cache[filename] + return _cleanup + + func = funclocals[funcname] + + weakref.finalize(func, cleanup_linecache(filename)) + + # Apply the docstring + sig = "func({})".format(", ".join(str(i) for i in names)) + sig = textwrap.fill(sig, subsequent_indent=' '*8) + if _too_large_for_docstring(expr, docstring_limit): + expr_str = "EXPRESSION REDACTED DUE TO LENGTH, (see lambdify's `docstring_limit`)" + src_str = "SOURCE CODE REDACTED DUE TO LENGTH, (see lambdify's `docstring_limit`)" + else: + expr_str = str(expr) + if len(expr_str) > 78: + expr_str = textwrap.wrap(expr_str, 75)[0] + '...' + src_str = funcstr + func.__doc__ = ( + "Created with lambdify. Signature:\n\n" + "{sig}\n\n" + "Expression:\n\n" + "{expr}\n\n" + "Source code:\n\n" + "{src}\n\n" + "Imported modules:\n\n" + "{imp_mods}" + ).format(sig=sig, expr=expr_str, src=src_str, imp_mods='\n'.join(imp_mod_lines)) + return func + +def _module_present(modname, modlist): + if modname in modlist: + return True + for m in modlist: + if hasattr(m, '__name__') and m.__name__ == modname: + return True + return False + +def _get_namespace(m): + """ + This is used by _lambdify to parse its arguments. + """ + if isinstance(m, str): + _import(m) + return MODULES[m][0] + elif isinstance(m, dict): + return m + elif hasattr(m, "__dict__"): + return m.__dict__ + else: + raise TypeError("Argument must be either a string, dict or module but it is: %s" % m) + + +def _recursive_to_string(doprint, arg): + """Functions in lambdify accept both SymPy types and non-SymPy types such as python + lists and tuples. This method ensures that we only call the doprint method of the + printer with SymPy types (so that the printer safely can use SymPy-methods).""" + from sympy.matrices.matrixbase import MatrixBase + from sympy.core.basic import Basic + + if isinstance(arg, (Basic, MatrixBase)): + return doprint(arg) + elif iterable(arg): + if isinstance(arg, list): + left, right = "[", "]" + elif isinstance(arg, tuple): + left, right = "(", ",)" + if not arg: + return "()" + else: + raise NotImplementedError("unhandled type: %s, %s" % (type(arg), arg)) + return left +', '.join(_recursive_to_string(doprint, e) for e in arg) + right + elif isinstance(arg, str): + return arg + else: + return doprint(arg) + + +def lambdastr(args, expr, printer=None, dummify=None): + """ + Returns a string that can be evaluated to a lambda function. + + Examples + ======== + + >>> from sympy.abc import x, y, z + >>> from sympy.utilities.lambdify import lambdastr + >>> lambdastr(x, x**2) + 'lambda x: (x**2)' + >>> lambdastr((x,y,z), [z,y,x]) + 'lambda x,y,z: ([z, y, x])' + + Although tuples may not appear as arguments to lambda in Python 3, + lambdastr will create a lambda function that will unpack the original + arguments so that nested arguments can be handled: + + >>> lambdastr((x, (y, z)), x + y) + 'lambda _0,_1: (lambda x,y,z: (x + y))(_0,_1[0],_1[1])' + """ + # Transforming everything to strings. + from sympy.matrices import DeferredVector + from sympy.core.basic import Basic + from sympy.core.function import (Derivative, Function) + from sympy.core.symbol import (Dummy, Symbol) + from sympy.core.sympify import sympify + + if printer is not None: + if inspect.isfunction(printer): + lambdarepr = printer + else: + if inspect.isclass(printer): + lambdarepr = lambda expr: printer().doprint(expr) + else: + lambdarepr = lambda expr: printer.doprint(expr) + else: + #XXX: This has to be done here because of circular imports + from sympy.printing.lambdarepr import lambdarepr + + def sub_args(args, dummies_dict): + if isinstance(args, str): + return args + elif isinstance(args, DeferredVector): + return str(args) + elif iterable(args): + dummies = flatten([sub_args(a, dummies_dict) for a in args]) + return ",".join(str(a) for a in dummies) + else: + # replace these with Dummy symbols + if isinstance(args, (Function, Symbol, Derivative)): + dummies = Dummy() + dummies_dict.update({args : dummies}) + return str(dummies) + else: + return str(args) + + def sub_expr(expr, dummies_dict): + expr = sympify(expr) + # dict/tuple are sympified to Basic + if isinstance(expr, Basic): + expr = expr.xreplace(dummies_dict) + # list is not sympified to Basic + elif isinstance(expr, list): + expr = [sub_expr(a, dummies_dict) for a in expr] + return expr + + # Transform args + def isiter(l): + return iterable(l, exclude=(str, DeferredVector, NotIterable)) + + def flat_indexes(iterable): + n = 0 + + for el in iterable: + if isiter(el): + for ndeep in flat_indexes(el): + yield (n,) + ndeep + else: + yield (n,) + + n += 1 + + if dummify is None: + dummify = any(isinstance(a, Basic) and + a.atoms(Function, Derivative) for a in ( + args if isiter(args) else [args])) + + if isiter(args) and any(isiter(i) for i in args): + dum_args = [str(Dummy(str(i))) for i in range(len(args))] + + indexed_args = ','.join([ + dum_args[ind[0]] + ''.join(["[%s]" % k for k in ind[1:]]) + for ind in flat_indexes(args)]) + + lstr = lambdastr(flatten(args), expr, printer=printer, dummify=dummify) + + return 'lambda %s: (%s)(%s)' % (','.join(dum_args), lstr, indexed_args) + + dummies_dict = {} + if dummify: + args = sub_args(args, dummies_dict) + else: + if isinstance(args, str): + pass + elif iterable(args, exclude=DeferredVector): + args = ",".join(str(a) for a in args) + + # Transform expr + if dummify: + if isinstance(expr, str): + pass + else: + expr = sub_expr(expr, dummies_dict) + expr = _recursive_to_string(lambdarepr, expr) + return "lambda %s: (%s)" % (args, expr) + +class _EvaluatorPrinter: + def __init__(self, printer=None, dummify=False): + self._dummify = dummify + + #XXX: This has to be done here because of circular imports + from sympy.printing.lambdarepr import LambdaPrinter + + if printer is None: + printer = LambdaPrinter() + + if inspect.isfunction(printer): + self._exprrepr = printer + else: + if inspect.isclass(printer): + printer = printer() + + self._exprrepr = printer.doprint + + #if hasattr(printer, '_print_Symbol'): + # symbolrepr = printer._print_Symbol + + #if hasattr(printer, '_print_Dummy'): + # dummyrepr = printer._print_Dummy + + # Used to print the generated function arguments in a standard way + self._argrepr = LambdaPrinter().doprint + + def doprint(self, funcname, args, expr, *, cses=()): + """ + Returns the function definition code as a string. + """ + from sympy.core.symbol import Dummy + + funcbody = [] + + if not iterable(args): + args = [args] + + if cses: + cses = list(cses) + subvars, subexprs = zip(*cses) + exprs = [expr] + list(subexprs) + argstrs, exprs = self._preprocess(args, exprs, cses=cses) + expr, subexprs = exprs[0], exprs[1:] + cses = zip(subvars, subexprs) + else: + argstrs, expr = self._preprocess(args, expr) + + # Generate argument unpacking and final argument list + funcargs = [] + unpackings = [] + + for argstr in argstrs: + if iterable(argstr): + funcargs.append(self._argrepr(Dummy())) + unpackings.extend(self._print_unpacking(argstr, funcargs[-1])) + else: + funcargs.append(argstr) + + funcsig = 'def {}({}):'.format(funcname, ', '.join(funcargs)) + + # Wrap input arguments before unpacking + funcbody.extend(self._print_funcargwrapping(funcargs)) + + funcbody.extend(unpackings) + + for s, e in cses: + if e is None: + funcbody.append('del {}'.format(self._exprrepr(s))) + else: + funcbody.append('{} = {}'.format(self._exprrepr(s), self._exprrepr(e))) + + # Subs may appear in expressions generated by .diff() + subs_assignments = [] + expr = self._handle_Subs(expr, out=subs_assignments) + for lhs, rhs in subs_assignments: + funcbody.append('{} = {}'.format(self._exprrepr(lhs), self._exprrepr(rhs))) + + str_expr = _recursive_to_string(self._exprrepr, expr) + + if '\n' in str_expr: + str_expr = '({})'.format(str_expr) + funcbody.append('return {}'.format(str_expr)) + + funclines = [funcsig] + funclines.extend([' ' + line for line in funcbody]) + + return '\n'.join(funclines) + '\n' + + @classmethod + def _is_safe_ident(cls, ident): + return isinstance(ident, str) and ident.isidentifier() \ + and not keyword.iskeyword(ident) + + def _preprocess(self, args, expr, cses=(), _dummies_dict=None): + """Preprocess args, expr to replace arguments that do not map + to valid Python identifiers. + + Returns string form of args, and updated expr. + """ + from sympy.core.basic import Basic + from sympy.core.sorting import ordered + from sympy.core.function import (Derivative, Function) + from sympy.core.symbol import Dummy, uniquely_named_symbol + from sympy.matrices import DeferredVector + from sympy.core.expr import Expr + + # Args of type Dummy can cause name collisions with args + # of type Symbol. Force dummify of everything in this + # situation. + dummify = self._dummify or any( + isinstance(arg, Dummy) for arg in flatten(args)) + + argstrs = [None]*len(args) + if _dummies_dict is None: + _dummies_dict = {} + + def update_dummies(arg, dummy): + _dummies_dict[arg] = dummy + for repl, sub in cses: + arg = arg.xreplace({sub: repl}) + _dummies_dict[arg] = dummy + + for arg, i in reversed(list(ordered(zip(args, range(len(args)))))): + if iterable(arg): + s, expr = self._preprocess(arg, expr, cses=cses, _dummies_dict=_dummies_dict) + elif isinstance(arg, DeferredVector): + s = str(arg) + elif isinstance(arg, Basic) and arg.is_symbol: + s = str(arg) + if dummify or not self._is_safe_ident(s): + dummy = Dummy() + if isinstance(expr, Expr): + dummy = uniquely_named_symbol( + dummy.name, expr, modify=lambda s: '_' + s) + s = self._argrepr(dummy) + update_dummies(arg, dummy) + expr = self._subexpr(expr, _dummies_dict) + elif dummify or isinstance(arg, (Function, Derivative)): + dummy = Dummy() + s = self._argrepr(dummy) + update_dummies(arg, dummy) + expr = self._subexpr(expr, _dummies_dict) + else: + s = str(arg) + argstrs[i] = s + return argstrs, expr + + def _subexpr(self, expr, dummies_dict): + from sympy.matrices import DeferredVector + from sympy.core.sympify import sympify + + expr = sympify(expr) + xreplace = getattr(expr, 'xreplace', None) + if xreplace is not None: + expr = xreplace(dummies_dict) + else: + if isinstance(expr, DeferredVector): + pass + elif isinstance(expr, dict): + k = [self._subexpr(sympify(a), dummies_dict) for a in expr.keys()] + v = [self._subexpr(sympify(a), dummies_dict) for a in expr.values()] + expr = dict(zip(k, v)) + elif isinstance(expr, tuple): + expr = tuple(self._subexpr(sympify(a), dummies_dict) for a in expr) + elif isinstance(expr, list): + expr = [self._subexpr(sympify(a), dummies_dict) for a in expr] + return expr + + def _print_funcargwrapping(self, args): + """Generate argument wrapping code. + + args is the argument list of the generated function (strings). + + Return value is a list of lines of code that will be inserted at + the beginning of the function definition. + """ + return [] + + def _print_unpacking(self, unpackto, arg): + """Generate argument unpacking code. + + arg is the function argument to be unpacked (a string), and + unpackto is a list or nested lists of the variable names (strings) to + unpack to. + """ + def unpack_lhs(lvalues): + return '[{}]'.format(', '.join( + unpack_lhs(val) if iterable(val) else val for val in lvalues)) + + return ['{} = {}'.format(unpack_lhs(unpackto), arg)] + + def _handle_Subs(self, expr, out): + """Any instance of Subs is extracted and returned as assignment pairs.""" + from sympy.core.basic import Basic + from sympy.core.function import Subs + from sympy.core.symbol import Dummy + from sympy.matrices.matrixbase import MatrixBase + + def _replace(ex, variables, point): + safe = {} + for lhs, rhs in zip(variables, point): + dummy = Dummy() + safe[lhs] = dummy + out.append((dummy, rhs)) + return ex.xreplace(safe) + + if isinstance(expr, (Basic, MatrixBase)): + expr = expr.replace(Subs, _replace) + elif iterable(expr): + expr = type(expr)([self._handle_Subs(e, out) for e in expr]) + return expr + +class _TensorflowEvaluatorPrinter(_EvaluatorPrinter): + def _print_unpacking(self, lvalues, rvalue): + """Generate argument unpacking code. + + This method is used when the input value is not iterable, + but can be indexed (see issue #14655). + """ + + def flat_indexes(elems): + n = 0 + + for el in elems: + if iterable(el): + for ndeep in flat_indexes(el): + yield (n,) + ndeep + else: + yield (n,) + + n += 1 + + indexed = ', '.join('{}[{}]'.format(rvalue, ']['.join(map(str, ind))) + for ind in flat_indexes(lvalues)) + + return ['[{}] = [{}]'.format(', '.join(flatten(lvalues)), indexed)] + +def _imp_namespace(expr, namespace=None): + """ Return namespace dict with function implementations + + We need to search for functions in anything that can be thrown at + us - that is - anything that could be passed as ``expr``. Examples + include SymPy expressions, as well as tuples, lists and dicts that may + contain SymPy expressions. + + Parameters + ---------- + expr : object + Something passed to lambdify, that will generate valid code from + ``str(expr)``. + namespace : None or mapping + Namespace to fill. None results in new empty dict + + Returns + ------- + namespace : dict + dict with keys of implemented function names within ``expr`` and + corresponding values being the numerical implementation of + function + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy.utilities.lambdify import implemented_function, _imp_namespace + >>> from sympy import Function + >>> f = implemented_function(Function('f'), lambda x: x+1) + >>> g = implemented_function(Function('g'), lambda x: x*10) + >>> namespace = _imp_namespace(f(g(x))) + >>> sorted(namespace.keys()) + ['f', 'g'] + """ + # Delayed import to avoid circular imports + from sympy.core.function import FunctionClass + if namespace is None: + namespace = {} + # tuples, lists, dicts are valid expressions + if is_sequence(expr): + for arg in expr: + _imp_namespace(arg, namespace) + return namespace + elif isinstance(expr, dict): + for key, val in expr.items(): + # functions can be in dictionary keys + _imp_namespace(key, namespace) + _imp_namespace(val, namespace) + return namespace + # SymPy expressions may be Functions themselves + func = getattr(expr, 'func', None) + if isinstance(func, FunctionClass): + imp = getattr(func, '_imp_', None) + if imp is not None: + name = expr.func.__name__ + if name in namespace and namespace[name] != imp: + raise ValueError('We found more than one ' + 'implementation with name ' + '"%s"' % name) + namespace[name] = imp + # and / or they may take Functions as arguments + if hasattr(expr, 'args'): + for arg in expr.args: + _imp_namespace(arg, namespace) + return namespace + + +def implemented_function(symfunc, implementation): + """ Add numerical ``implementation`` to function ``symfunc``. + + ``symfunc`` can be an ``UndefinedFunction`` instance, or a name string. + In the latter case we create an ``UndefinedFunction`` instance with that + name. + + Be aware that this is a quick workaround, not a general method to create + special symbolic functions. If you want to create a symbolic function to be + used by all the machinery of SymPy you should subclass the ``Function`` + class. + + Parameters + ---------- + symfunc : ``str`` or ``UndefinedFunction`` instance + If ``str``, then create new ``UndefinedFunction`` with this as + name. If ``symfunc`` is an Undefined function, create a new function + with the same name and the implemented function attached. + implementation : callable + numerical implementation to be called by ``evalf()`` or ``lambdify`` + + Returns + ------- + afunc : sympy.FunctionClass instance + function with attached implementation + + Examples + ======== + + >>> from sympy.abc import x + >>> from sympy.utilities.lambdify import implemented_function + >>> from sympy import lambdify + >>> f = implemented_function('f', lambda x: x+1) + >>> lam_f = lambdify(x, f(x)) + >>> lam_f(4) + 5 + """ + # Delayed import to avoid circular imports + from sympy.core.function import UndefinedFunction + # if name, create function to hold implementation + kwargs = {} + if isinstance(symfunc, UndefinedFunction): + kwargs = symfunc._kwargs + symfunc = symfunc.__name__ + if isinstance(symfunc, str): + # Keyword arguments to UndefinedFunction are added as attributes to + # the created class. + symfunc = UndefinedFunction( + symfunc, _imp_=staticmethod(implementation), **kwargs) + elif not isinstance(symfunc, UndefinedFunction): + raise ValueError(filldedent(''' + symfunc should be either a string or + an UndefinedFunction instance.''')) + return symfunc + + +def _too_large_for_docstring(expr, limit): + """Decide whether an ``Expr`` is too large to be fully rendered in a + ``lambdify`` docstring. + + This is a fast alternative to ``count_ops``, which can become prohibitively + slow for large expressions, because in this instance we only care whether + ``limit`` is exceeded rather than counting the exact number of nodes in the + expression. + + Parameters + ========== + expr : ``Expr``, (nested) ``list`` of ``Expr``, or ``Matrix`` + The same objects that can be passed to the ``expr`` argument of + ``lambdify``. + limit : ``int`` or ``None`` + The threshold above which an expression contains too many nodes to be + usefully rendered in the docstring. If ``None`` then there is no limit. + + Returns + ======= + bool + ``True`` if the number of nodes in the expression exceeds the limit, + ``False`` otherwise. + + Examples + ======== + + >>> from sympy.abc import x, y, z + >>> from sympy.utilities.lambdify import _too_large_for_docstring + >>> expr = x + >>> _too_large_for_docstring(expr, None) + False + >>> _too_large_for_docstring(expr, 100) + False + >>> _too_large_for_docstring(expr, 1) + False + >>> _too_large_for_docstring(expr, 0) + True + >>> _too_large_for_docstring(expr, -1) + True + + Does this split it? + + >>> expr = [x, y, z] + >>> _too_large_for_docstring(expr, None) + False + >>> _too_large_for_docstring(expr, 100) + False + >>> _too_large_for_docstring(expr, 1) + True + >>> _too_large_for_docstring(expr, 0) + True + >>> _too_large_for_docstring(expr, -1) + True + + >>> expr = [x, [y], z, [[x+y], [x*y*z, [x+y+z]]]] + >>> _too_large_for_docstring(expr, None) + False + >>> _too_large_for_docstring(expr, 100) + False + >>> _too_large_for_docstring(expr, 1) + True + >>> _too_large_for_docstring(expr, 0) + True + >>> _too_large_for_docstring(expr, -1) + True + + >>> expr = ((x + y + z)**5).expand() + >>> _too_large_for_docstring(expr, None) + False + >>> _too_large_for_docstring(expr, 100) + True + >>> _too_large_for_docstring(expr, 1) + True + >>> _too_large_for_docstring(expr, 0) + True + >>> _too_large_for_docstring(expr, -1) + True + + >>> from sympy import Matrix + >>> expr = Matrix([[(x + y + z), ((x + y + z)**2).expand(), + ... ((x + y + z)**3).expand(), ((x + y + z)**4).expand()]]) + >>> _too_large_for_docstring(expr, None) + False + >>> _too_large_for_docstring(expr, 1000) + False + >>> _too_large_for_docstring(expr, 100) + True + >>> _too_large_for_docstring(expr, 1) + True + >>> _too_large_for_docstring(expr, 0) + True + >>> _too_large_for_docstring(expr, -1) + True + + """ + # Must be imported here to avoid a circular import error + from sympy.core.traversal import postorder_traversal + + if limit is None: + return False + + i = 0 + for _ in postorder_traversal(expr): + i += 1 + if i > limit: + return True + return False diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/magic.py b/.venv/lib/python3.12/site-packages/sympy/utilities/magic.py new file mode 100644 index 0000000000000000000000000000000000000000..e853a0ad9a85bc252dcb24e8a1ecbfca422ac3fd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/magic.py @@ -0,0 +1,12 @@ +"""Functions that involve magic. """ + +def pollute(names, objects): + """Pollute the global namespace with symbols -> objects mapping. """ + from inspect import currentframe + frame = currentframe().f_back.f_back + + try: + for name, obj in zip(names, objects): + frame.f_globals[name] = obj + finally: + del frame # break cyclic dependencies as stated in inspect docs diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/matchpy_connector.py b/.venv/lib/python3.12/site-packages/sympy/utilities/matchpy_connector.py new file mode 100644 index 0000000000000000000000000000000000000000..35aa013294b93bbcfe4a1bf4ec96b629ea5a468f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/matchpy_connector.py @@ -0,0 +1,340 @@ +""" +The objects in this module allow the usage of the MatchPy pattern matching +library on SymPy expressions. +""" +import re +from typing import List, Callable, NamedTuple, Any, Dict + +from sympy.core.sympify import _sympify +from sympy.external import import_module +from sympy.functions import (log, sin, cos, tan, cot, csc, sec, erf, gamma, uppergamma) +from sympy.functions.elementary.hyperbolic import acosh, asinh, atanh, acoth, acsch, asech, cosh, sinh, tanh, coth, sech, csch +from sympy.functions.elementary.trigonometric import atan, acsc, asin, acot, acos, asec +from sympy.functions.special.error_functions import fresnelc, fresnels, erfc, erfi, Ei +from sympy.core.add import Add +from sympy.core.basic import Basic +from sympy.core.expr import Expr +from sympy.core.mul import Mul +from sympy.core.power import Pow +from sympy.core.relational import (Equality, Unequality) +from sympy.core.symbol import Symbol +from sympy.functions.elementary.exponential import exp +from sympy.integrals.integrals import Integral +from sympy.printing.repr import srepr +from sympy.utilities.decorator import doctest_depends_on + + +matchpy = import_module("matchpy") + + +__doctest_requires__ = {('*',): ['matchpy']} + + +if matchpy: + from matchpy import Operation, CommutativeOperation, AssociativeOperation, OneIdentityOperation + from matchpy.expressions.functions import op_iter, create_operation_expression, op_len + + Operation.register(Integral) + Operation.register(Pow) + OneIdentityOperation.register(Pow) + + Operation.register(Add) + OneIdentityOperation.register(Add) + CommutativeOperation.register(Add) + AssociativeOperation.register(Add) + + Operation.register(Mul) + OneIdentityOperation.register(Mul) + CommutativeOperation.register(Mul) + AssociativeOperation.register(Mul) + + Operation.register(Equality) + CommutativeOperation.register(Equality) + Operation.register(Unequality) + CommutativeOperation.register(Unequality) + + Operation.register(exp) + Operation.register(log) + Operation.register(gamma) + Operation.register(uppergamma) + Operation.register(fresnels) + Operation.register(fresnelc) + Operation.register(erf) + Operation.register(Ei) + Operation.register(erfc) + Operation.register(erfi) + Operation.register(sin) + Operation.register(cos) + Operation.register(tan) + Operation.register(cot) + Operation.register(csc) + Operation.register(sec) + Operation.register(sinh) + Operation.register(cosh) + Operation.register(tanh) + Operation.register(coth) + Operation.register(csch) + Operation.register(sech) + Operation.register(asin) + Operation.register(acos) + Operation.register(atan) + Operation.register(acot) + Operation.register(acsc) + Operation.register(asec) + Operation.register(asinh) + Operation.register(acosh) + Operation.register(atanh) + Operation.register(acoth) + Operation.register(acsch) + Operation.register(asech) + + @op_iter.register(Integral) # type: ignore + def _(operation): + return iter((operation._args[0],) + operation._args[1]) + + @op_iter.register(Basic) # type: ignore + def _(operation): + return iter(operation._args) + + @op_len.register(Integral) # type: ignore + def _(operation): + return 1 + len(operation._args[1]) + + @op_len.register(Basic) # type: ignore + def _(operation): + return len(operation._args) + + @create_operation_expression.register(Basic) + def sympy_op_factory(old_operation, new_operands, variable_name=True): + return type(old_operation)(*new_operands) + + +if matchpy: + from matchpy import Wildcard +else: + class Wildcard: # type: ignore + def __init__(self, min_length, fixed_size, variable_name, optional): + self.min_count = min_length + self.fixed_size = fixed_size + self.variable_name = variable_name + self.optional = optional + + +@doctest_depends_on(modules=('matchpy',)) +class _WildAbstract(Wildcard, Symbol): + min_length: int # abstract field required in subclasses + fixed_size: bool # abstract field required in subclasses + + def __init__(self, variable_name=None, optional=None, **assumptions): + min_length = self.min_length + fixed_size = self.fixed_size + if optional is not None: + optional = _sympify(optional) + Wildcard.__init__(self, min_length, fixed_size, str(variable_name), optional) + + def __getstate__(self): + return { + "min_length": self.min_length, + "fixed_size": self.fixed_size, + "min_count": self.min_count, + "variable_name": self.variable_name, + "optional": self.optional, + } + + def __new__(cls, variable_name=None, optional=None, **assumptions): + cls._sanitize(assumptions, cls) + return _WildAbstract.__xnew__(cls, variable_name, optional, **assumptions) + + def __getnewargs__(self): + return self.variable_name, self.optional + + @staticmethod + def __xnew__(cls, variable_name=None, optional=None, **assumptions): + obj = Symbol.__xnew__(cls, variable_name, **assumptions) + return obj + + def _hashable_content(self): + if self.optional: + return super()._hashable_content() + (self.min_count, self.fixed_size, self.variable_name, self.optional) + else: + return super()._hashable_content() + (self.min_count, self.fixed_size, self.variable_name) + + def __copy__(self) -> '_WildAbstract': + return type(self)(variable_name=self.variable_name, optional=self.optional) + + def __repr__(self): + return str(self) + + def __str__(self): + return self.name + + +@doctest_depends_on(modules=('matchpy',)) +class WildDot(_WildAbstract): + min_length = 1 + fixed_size = True + + +@doctest_depends_on(modules=('matchpy',)) +class WildPlus(_WildAbstract): + min_length = 1 + fixed_size = False + + +@doctest_depends_on(modules=('matchpy',)) +class WildStar(_WildAbstract): + min_length = 0 + fixed_size = False + + +def _get_srepr(expr): + s = srepr(expr) + s = re.sub(r"WildDot\('(\w+)'\)", r"\1", s) + s = re.sub(r"WildPlus\('(\w+)'\)", r"*\1", s) + s = re.sub(r"WildStar\('(\w+)'\)", r"*\1", s) + return s + + +class ReplacementInfo(NamedTuple): + replacement: Any + info: Any + + +@doctest_depends_on(modules=('matchpy',)) +class Replacer: + """ + Replacer object to perform multiple pattern matching and subexpression + replacements in SymPy expressions. + + Examples + ======== + + Example to construct a simple first degree equation solver: + + >>> from sympy.utilities.matchpy_connector import WildDot, Replacer + >>> from sympy import Equality, Symbol + >>> x = Symbol("x") + >>> a_ = WildDot("a_", optional=1) + >>> b_ = WildDot("b_", optional=0) + + The lines above have defined two wildcards, ``a_`` and ``b_``, the + coefficients of the equation `a x + b = 0`. The optional values specified + indicate which expression to return in case no match is found, they are + necessary in equations like `a x = 0` and `x + b = 0`. + + Create two constraints to make sure that ``a_`` and ``b_`` will not match + any expression containing ``x``: + + >>> from matchpy import CustomConstraint + >>> free_x_a = CustomConstraint(lambda a_: not a_.has(x)) + >>> free_x_b = CustomConstraint(lambda b_: not b_.has(x)) + + Now create the rule replacer with the constraints: + + >>> replacer = Replacer(common_constraints=[free_x_a, free_x_b]) + + Add the matching rule: + + >>> replacer.add(Equality(a_*x + b_, 0), -b_/a_) + + Let's try it: + + >>> replacer.replace(Equality(3*x + 4, 0)) + -4/3 + + Notice that it will not match equations expressed with other patterns: + + >>> eq = Equality(3*x, 4) + >>> replacer.replace(eq) + Eq(3*x, 4) + + In order to extend the matching patterns, define another one (we also need + to clear the cache, because the previous result has already been memorized + and the pattern matcher will not iterate again if given the same expression) + + >>> replacer.add(Equality(a_*x, b_), b_/a_) + >>> replacer._matcher.clear() + >>> replacer.replace(eq) + 4/3 + """ + + def __init__(self, common_constraints: list = [], lambdify: bool = False, info: bool = False): + self._matcher = matchpy.ManyToOneMatcher() + self._common_constraint = common_constraints + self._lambdify = lambdify + self._info = info + self._wildcards: Dict[str, Wildcard] = {} + + def _get_lambda(self, lambda_str: str) -> Callable[..., Expr]: + exec("from sympy import *") + return eval(lambda_str, locals()) + + def _get_custom_constraint(self, constraint_expr: Expr, condition_template: str) -> Callable[..., Expr]: + wilds = [x.name for x in constraint_expr.atoms(_WildAbstract)] + lambdaargs = ', '.join(wilds) + fullexpr = _get_srepr(constraint_expr) + condition = condition_template.format(fullexpr) + return matchpy.CustomConstraint( + self._get_lambda(f"lambda {lambdaargs}: ({condition})")) + + def _get_custom_constraint_nonfalse(self, constraint_expr: Expr) -> Callable[..., Expr]: + return self._get_custom_constraint(constraint_expr, "({}) != False") + + def _get_custom_constraint_true(self, constraint_expr: Expr) -> Callable[..., Expr]: + return self._get_custom_constraint(constraint_expr, "({}) == True") + + def add(self, expr: Expr, replacement, conditions_true: List[Expr] = [], + conditions_nonfalse: List[Expr] = [], info: Any = None) -> None: + expr = _sympify(expr) + replacement = _sympify(replacement) + constraints = self._common_constraint[:] + constraint_conditions_true = [ + self._get_custom_constraint_true(cond) for cond in conditions_true] + constraint_conditions_nonfalse = [ + self._get_custom_constraint_nonfalse(cond) for cond in conditions_nonfalse] + constraints.extend(constraint_conditions_true) + constraints.extend(constraint_conditions_nonfalse) + pattern = matchpy.Pattern(expr, *constraints) + if self._lambdify: + lambda_str = f"lambda {', '.join((x.name for x in expr.atoms(_WildAbstract)))}: {_get_srepr(replacement)}" + lambda_expr = self._get_lambda(lambda_str) + replacement = lambda_expr + else: + self._wildcards.update({str(i): i for i in expr.atoms(Wildcard)}) + if self._info: + replacement = ReplacementInfo(replacement, info) + self._matcher.add(pattern, replacement) + + def replace(self, expression, max_count: int = -1): + # This method partly rewrites the .replace method of ManyToOneReplacer + # in MatchPy. + # License: https://github.com/HPAC/matchpy/blob/master/LICENSE + infos = [] + replaced = True + replace_count = 0 + while replaced and (max_count < 0 or replace_count < max_count): + replaced = False + for subexpr, pos in matchpy.preorder_iter_with_position(expression): + try: + replacement_data, subst = next(iter(self._matcher.match(subexpr))) + if self._info: + replacement = replacement_data.replacement + infos.append(replacement_data.info) + else: + replacement = replacement_data + + if self._lambdify: + result = replacement(**subst) + else: + result = replacement.xreplace({self._wildcards[k]: v for k, v in subst.items()}) + + expression = matchpy.functions.replace(expression, pos, result) + replaced = True + break + except StopIteration: + pass + replace_count += 1 + if self._info: + return expression, infos + else: + return expression diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/mathml/__init__.py b/.venv/lib/python3.12/site-packages/sympy/utilities/mathml/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eded44ee3c0f34ad1324765ba06ee9d6eb5e9899 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/mathml/__init__.py @@ -0,0 +1,122 @@ +"""Module with some functions for MathML, like transforming MathML +content in MathML presentation. + +To use this module, you will need lxml. +""" + +from pathlib import Path + +from sympy.utilities.decorator import doctest_depends_on + + +__doctest_requires__ = {('apply_xsl', 'c2p'): ['lxml']} + + +def add_mathml_headers(s): + return """""" + s + "" + + +def _read_binary(pkgname, filename): + import sys + + if sys.version_info >= (3, 10): + # files was added in Python 3.9 but only seems to work here in 3.10+ + from importlib.resources import files + return files(pkgname).joinpath(filename).read_bytes() + else: + # read_binary was deprecated in Python 3.11 + from importlib.resources import read_binary + return read_binary(pkgname, filename) + + +def _read_xsl(xsl): + # Previously these values were allowed: + if xsl == 'mathml/data/simple_mmlctop.xsl': + xsl = 'simple_mmlctop.xsl' + elif xsl == 'mathml/data/mmlctop.xsl': + xsl = 'mmlctop.xsl' + elif xsl == 'mathml/data/mmltex.xsl': + xsl = 'mmltex.xsl' + + if xsl in ['simple_mmlctop.xsl', 'mmlctop.xsl', 'mmltex.xsl']: + xslbytes = _read_binary('sympy.utilities.mathml.data', xsl) + else: + xslbytes = Path(xsl).read_bytes() + + return xslbytes + + +@doctest_depends_on(modules=('lxml',)) +def apply_xsl(mml, xsl): + """Apply a xsl to a MathML string. + + Parameters + ========== + + mml + A string with MathML code. + xsl + A string giving the name of an xsl (xml stylesheet) file which can be + found in sympy/utilities/mathml/data. The following files are supplied + with SymPy: + + - mmlctop.xsl + - mmltex.xsl + - simple_mmlctop.xsl + + Alternatively, a full path to an xsl file can be given. + + Examples + ======== + + >>> from sympy.utilities.mathml import apply_xsl + >>> xsl = 'simple_mmlctop.xsl' + >>> mml = ' a b ' + >>> res = apply_xsl(mml,xsl) + >>> print(res) + + + a + + + b + + """ + from lxml import etree + + parser = etree.XMLParser(resolve_entities=False) + ac = etree.XSLTAccessControl.DENY_ALL + + s = etree.XML(_read_xsl(xsl), parser=parser) + transform = etree.XSLT(s, access_control=ac) + doc = etree.XML(mml, parser=parser) + result = transform(doc) + s = str(result) + return s + + +@doctest_depends_on(modules=('lxml',)) +def c2p(mml, simple=False): + """Transforms a document in MathML content (like the one that sympy produces) + in one document in MathML presentation, more suitable for printing, and more + widely accepted + + Examples + ======== + + >>> from sympy.utilities.mathml import c2p + >>> mml = ' 2 ' + >>> c2p(mml,simple=True) != c2p(mml,simple=False) + True + + """ + + if not mml.startswith(' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + e + + + + + + + + + + + + + - + + + + + + + + &#x2062; + &#x2148; + + + + + + + + + + + + + - + + + + + + + + &#x2062; + &#x2148; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Polar + &#x2062; + + + + + + + + + + + + + + + Polar + &#x2062; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + [ + + + ] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x03BB; + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2218; + + + + + + + + + + + + + + + + + + &#x2218; + + + + + + + + + + + + + + + + id + + + id + + + + + + + + + + + + + + domain + + + codomain + + + image + + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + + + + + { + + + + + + + + if + + + + + + + + + + + otherwise + + + + + + + + + + + + + + + + + + + + + + + &#x230A; + + + + + + + + + + + + + + + + + + + &#x230B; + + + + + + + + + + + + &#x2147; + + + + + + + + + + + + + + + + + ! + + + + + + + + + + + + + + + + max + + + min + + + + + + + max + + + min + + + + + + + + + + + + + | + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2062; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + gcd + + + lcm + + + + + + gcd + + + lcm + + + + + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2227; + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2228; + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x22BB; + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + &#x00AC; + &#x2061; + + + + + + + + + + + + + + + &#x00AC; + &#x2061; + + + + + + + + + + + + + + + + + + + &#x2200; + + + + + + + + + + + + : + + + + , + + + + + + + + + + + + + + &#x2203; + + + + + + + + + + + + : + + + + , + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x00AF; + + + + + + + + + + + + + + + + + &#x211C; + + + &#x2111; + + + &#x2061; + + + + + + + + + + + + + + + + + &#x230A; + + + &#x2308; + + + + + + &#x230B; + + + &#x2309; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2260; + + + &#x2248; + + + &#x2223; + + + + + &#x2198; + + + &#x2197; + + + &#x2192; + + + + + &#x21D2; + + + &#x2208; + + + &#x2209; + + + &#x2284; + + + &#x2288; + + + + + + + + + + &#x2286; + + + &#x2282; + + + + + + + + + + + + &#x2265; + + + &#x2264; + + + &#x2261; + + + + + + + + + + + + + + + + + + + + + + ln + + + + + ln + + + + + + + + + + + + + + + + + + + + + + log + + + + + + log + + + + + + + + log + + + + log + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2146; + + &#x2146; + + + + + + + + &#x2146; + + + + &#x2146; + + + + + + + + + + + + + + + + + + &#x2032; + + + + + + + + + + + + + + + + + &#x2145; + + + + + + + + &#x2202; + + + + + &#x2202; + + + + + + + + + + + + + + + + + + + &#x2202; + + + + &#x2202; + + + + + + + + + + &#x2202; + + &#x2202; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2207; + 2 + + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + | + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x222A; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2229; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x00D7; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2211; + + + &#x220F; + + + + + = + + + + + + + + + + + &#x2211; + + + &#x220F; + + + + + + + + + + + &#x2211; + + + &#x220F; + + + + + + + + + + + + + + + + + + + + + + + + &#x222B; + + + + + + &#x222B; + + + + + + &#x222B; + + + + + + + + + + + + &#x222B; + + + + + + + + + &#x222B; + + + + + + + + + &#x2146; + + + + + + + + + + + + + + + + lim + + + + &#x2192; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x03C3; + + + + + + + + + + + + + + + + + &#x03C3; + + + + + + + 2 + + + + + + + + + + + + + median + + + + + + + + + + + + + + + + + mode + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + det + + + + + + + + + + + + + + + T + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x00D7; + + + &#x22C5; + + + &#x2297; + + + + + + + + + + + + &#x2124; + + + + &#x211D; + + + + &#x211A; + + + + &#x2115; + + + + &#x2102; + + + + &#x2119; + + + + &#x2147; + + + + &#x2148; + + + + NaN + + + + true + + + + false + + + + &#x2205; + + + + &#x03C0; + + + + &#x213D; + + + + &#x221E; + + + diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/mathml/data/mmltex.xsl b/.venv/lib/python3.12/site-packages/sympy/utilities/mathml/data/mmltex.xsl new file mode 100644 index 0000000000000000000000000000000000000000..5e6b85e02efd5196fe76b6ce4e10def27b9a8497 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/mathml/data/mmltex.xsl @@ -0,0 +1,2360 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + $ + + $ + + + + + + + + + + + + + + + + i + + + + + / + + + + + + _{} + + + + + e^{i + + } + + + + + E + + + + + + + + \mathrm{} + + + + + + + + + + + + + ( + + + , + + ) + + + + + () + + + + + + + \left( + + \left[ + + + , + + + + \right) + + \right] + + + + + \left\{\right\} + + + + + ^{(-1)} + + + + + + + + \mathrm{lambda}\: + + .\: + + + + + + + + + + \circ + + + + +\mathrm{id} + + + + \mathop{\mathrm{ + + }} + + + + + + + + \begin{cases} + + + \end{cases} + + + + + & \text{if $ + + $} + \\ + + + + + & \text{otherwise} + + + + + \left\lfloor\frac{ + + }{ + + }\right\rfloor + + + + + + + + ! + + + + + + + \left( + \frac{ + + + }{ + + + } + \right) + + + + + \ + + \{ + + + + , + + + + + + , + + + + \} + + + + + - + + + + + + + + + - + + + + + + + + + + ( + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + ) + + + + + + + + + ^{ + + + + } + + + + + + + \mod + + + + + + + + + + ( + + + + \times + + + + + + + + + + ) + + + + + \sqrt + + [ + + ] + + { + + } + + + +\gcd + + + + + + + + \land + + + + + + + + + + \lor + + + + + + + + + + \mathop{\mathrm{xor}} + + + + + + \neg + + + + + + + + + + \implies + + + + + + + + \ + + + + + , + + + \colon + + + + + + + \left| + + \right| + + + + + \overline{} + + + +\Re + + +\Im + + + + \left\lfloor + + \right\rfloor + + + + + \left\lceil + + \right\rceil + + + + + + + + + = + + + + + + + + + + \neq + + + + + + + + + + > + + + + + + + + + + < + + + + + + + + + + \ge + + + + + + + + + + \le + + + + + + + + + + \equiv + + + + + + + + + + \approx + + + + + + + + | + + + + + + + + \int + + _{ + + } + + + ^{ + + } + + + + \,d + + + + + + + ^\prime + + + + \frac{ + + + d^{ + + } + + }{d + + ^{ + + } + + + d + + }{d + + } + + + } + + + + + D_{ + + + , + + } + + + + + \frac{\partial^{ + + + + + + + + + + + + + + + + + + + + + } + + }{ + + \partial + + + ^{ + + } + + + } + + + + + + + + + , + + + +\mathop{\mathrm{div}} + + +\nabla^2 + + + + \{\} + + + + + \left[\right] + + + + + + + \colon + + + + + + , + + + + + + + + + + + + \cup + + + + + + + + + + \cap + + + + + + + + \in + + + + + + + + + + \notin + + + + + + + + + + + + \subseteq + + + + + + + + + + \subset + + + + + + + + + + \nsubseteq + + + + + + + + + + \not\subset + + + + + + + + + + \setminus + + + + + + | + + | + + + + + + + + + \times + + + + + + + + ^{ + + } + + + + + \sum + + + + + \prod + + + + + _{ + + + = + + + } + + + ^{ + + } + + + + + + + + \lim_{ + + } + + + + + + \to + + + + + + + + + + + + \searrow + \nearrow + \rightarrow + \to + + + + + + + + \ + + + + + + + + + \ + + + + + + \mathrm{ + + \,} + + + + + + + \mathrm{ + + } + + + + + e^{} + + + + + \lg + + + + + + + \log_{ + + } + + + + + + + + \left\langle + + + , + + \right\rangle + + + +\sigma + + + + \sigma( + + )^2 + + + + + \left\langle + + ^{ + + }\right\rangle + + _{ + + } + + + + + + + \left(\begin{array}{c} + + + \\ + + \end{array}\right) + + + + + \begin{pmatrix} + + \end{pmatrix} + + + + + + + & + + \\ + + + + + \det + + + + + + + \begin{vmatrix} + + \end{vmatrix} + + + + + + + + ^T + + + + + + + + _{ + + + , + + } + + + + + + + + + \dot + + + + + + + + + + + +\mathbb{Z} + + +\mathbb{R} + + +\mathbb{Q} + + +\mathbb{N} + + +\mathbb{C} + + +\mathbb{P} + + +e + + +i + + +NaN + + +\mbox{true} + + +\mbox{false} + + +\emptyset + + +\pi + + +\gamma + + +\infty + + + + + + + ( + + + + + + + + + ) + + + + + + + ( + + + + + + + + ) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \multicolumn{ + + }{c}{ + + } + + & + + + + + + + \hfill + + + + \hfill + + + + & + + + + + + + \\ + + + + + \begin{array}{ + + | + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + | + + } + + \hline + + + + \\ \hline + + \end{array} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \overline{ + + + + + } + + + \overbrace{ + + + + + } + + + \underline{ + + + + + + } + + + \underbrace{ + + + + + + } + + + + + _{ + + }^{ + + } + + + \underset{ + + }{\overset{ + + }{ + + }} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \overline{ + + } + + + \overbrace{ + + } + + + + + ^{ + + } + + + \stackrel{ + + }{ + + } + + + + + + + + + + + \underline{ + + } + + + \underbrace{ + + } + + + + + _{ + + } + + + \underset{ + + }{ + + } + + + + + + { + + }_{ + + }^{ + + } + + + + { + + }^{ + + } + + + + { + + }_{ + + } + + + + + + {}_{ + + } + + + {}^{ + + } + + + + + + {} + + + _{ + + } + + + ^{ + + } + + + + + + + + + + + + + + {} + + + _{ + + } + + + ^{ + + } + + + + + + + + + + + + + + + + + + \genfrac{}{}{ + + + + ex + + + .05ex + + + + .2ex + + + + + + }{}{ + + + \frac{ + + + + \hfill + + + + \hfill + + }{ + + \hfill + + + + \hfill + + } + + + + + + \sqrt[ + + ]{ + + } + + + + exception 25: + \text{exception 25:} + + + + + + \sqrt{ + + } + + + + + + + \left + + + \ + + + + \left( + + + + + + + + + + + , + + + + + + + + + + + + + + + + + + + + + + + + \right + + + \ + + + + \right) + + + + + \phantom{ + + } + + + + + + \overline{ + + \hspace{.2em}|} + + + \sqrt{ + + } + + + \overline{) + + } + + + + + + + + + + + \colorbox[rgb]{ + + + + }{$ + + + \textcolor[rgb]{ + + + + }{ + + + + } + + + $} + + + + + + + + + + + + + + + + + + + + + \mathrm{ + + } + + + + + + + + + + + + + + + + + + + + + + \text{ + + } + + + + \phantom{\rule + + [- + + ] + + { + + 0ex + + + }{ + + 0ex + + + }} + + + + + + " + + + " + + + + + + \colorbox[rgb]{ + + + + }{$ + + + \textcolor[rgb]{ + + + + }{ + + + + + \mathrm{ + + + \mathbf{ + + + \mathit{ + + + \mathbit{ + + + \mathbb{ + + + { + + + \mathcal{ + + + \mathsc{ + + + \mathfrak{ + + + \mathsf{ + + + \mathbsf{ + + + \mathsfit{ + + + \mathbsfit{ + + + \mathtt{ + + + { + + + + + + } + + + } + + + $} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + , + + + + + + , + + + + + + + + + + + + + + + + + + + , + + + + + + + + + + + , + + + + + + + + + + + + + + 0,1,1 + 0,0,0 + 0,0,1 + 1,0,1 + .5,.5,.5 + 0,.5,0 + 0,1,0 + .5,0,0 + 0,0,.5 + .5,.5,0 + .5,0,.5 + 1,0,0 + .75,.75,.75 + 0,.5,.5 + 1,1,1 + 1,1,0 + + Exception at color template + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Exception at Hex2Decimal template + + + + + + + + + + + diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/mathml/data/simple_mmlctop.xsl b/.venv/lib/python3.12/site-packages/sympy/utilities/mathml/data/simple_mmlctop.xsl new file mode 100644 index 0000000000000000000000000000000000000000..0cd73bccc24c963ed9c6c4121cc410997b94261c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/mathml/data/simple_mmlctop.xsl @@ -0,0 +1,3166 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + e + + + + + + + + + + + + + - + + + + + + + + &#x2062; + &#x2148; + + + + + + + + + + + + + - + + + + + + + + &#x2062; + &#x2148; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Polar + &#x2062; + + + + + + + + + + + + + + + Polar + &#x2062; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + [ + + + ] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x03BB; + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2218; + + + + + + + + + + + + + + + + + + &#x2218; + + + + + + + + + + + + + + + + id + + + id + + + + + + + + + + + + + + domain + + + codomain + + + image + + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + + + + + { + + + + + + + + if + + + + + + + + + + + otherwise + + + + + + + + + + + + + + + + + + + + + + + &#x230A; + + + + + + + + + + + + + + + + + + + &#x230B; + + + + + + + + + + + + e + + + + + + + + + + + + + + + + + ! + + + + + + + + + + + + + + + + max + + + min + + + + + + + max + + + min + + + + + + + + + + + + + | + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2062; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + gcd + + + lcm + + + + + + gcd + + + lcm + + + + + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2227; + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2228; + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x22BB; + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + &#x00AC; + &#x2061; + + + + + + + + + + + + + + + &#x00AC; + &#x2061; + + + + + + + + + + + + + + + + + + + &#x2200; + + + + + + + + + + + + : + + + + , + + + + + + + + + + + + + + &#x2203; + + + + + + + + + + + + : + + + + , + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x00AF; + + + + + + + + + + + + + + + + + &#x211C; + + + &#x2111; + + + &#x2061; + + + + + + + + + + + + + + + + + &#x230A; + + + &#x2308; + + + + + + &#x230B; + + + &#x2309; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2260; + + + &#x2248; + + + &#x2223; + + + + + &#x2198; + + + &#x2197; + + + &#x2192; + + + + + &#x21D2; + + + &#x2208; + + + &#x2209; + + + &#x2284; + + + &#x2288; + + + + + + + + + + &#x2286; + + + &#x2282; + + + + + + + + + + + + &#x2265; + + + &#x2264; + + + &#x2261; + + + + + + + + + + + + + + + + + + + + + + ln + + + + + ln + + + + + + + + + + + + + + + + + + + + + + log + + + + + + log + + + + + + + + log + + + + log + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + d + + d + + + + + + + + d + + + + d + + + + + + + + + + + + + + + + + + &#x2032; + + + + + + + + + + + + + + + + + &#x2145; + + + + + + + + &#x2202; + + + + + &#x2202; + + + + + + + + + + + + + + + + + + + &#x2202; + + + + &#x2202; + + + + + + + + + + &#x2202; + + &#x2202; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2207; + 2 + + &#x2061; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + | + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x222A; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2229; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x00D7; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x2211; + + + &#x220F; + + + + + = + + + + + + + + + + + &#x2211; + + + &#x220F; + + + + + + + + + + + &#x2211; + + + &#x220F; + + + + + + + + + + + + + + + + + + + + + + + + &#x222B; + + + + + + &#x222B; + + + + + + &#x222B; + + + + + + + + + + + + &#x222B; + + + + + + + + + &#x222B; + + + + + + + + + d + + + + + + + + + + + + + + + + lim + + + + &#x2192; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x03C3; + + + + + + + + + + + + + + + + + &#x03C3; + + + + + + + 2 + + + + + + + + + + + + + median + + + + + + + + + + + + + + + + + mode + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + det + + + + + + + + + + + + + + + T + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &#x00D7; + + + &#x22C5; + + + &#x2297; + + + + + + + + + + + + &#x2124; + + + + &#x211D; + + + + &#x211A; + + + + &#x2115; + + + + &#x2102; + + + + &#x2119; + + + + e + + + + &#x2148; + + + + NaN + + + + true + + + + false + + + + &#x2205; + + + + &#x03C0; + + + + &#x213D; + + + + &#x221E; + + + diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/memoization.py b/.venv/lib/python3.12/site-packages/sympy/utilities/memoization.py new file mode 100644 index 0000000000000000000000000000000000000000..b638dfe244628096108ea689b664782f6538b7b8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/memoization.py @@ -0,0 +1,76 @@ +from functools import wraps + + +def recurrence_memo(initial): + """ + Memo decorator for sequences defined by recurrence + + Examples + ======== + + >>> from sympy.utilities.memoization import recurrence_memo + >>> @recurrence_memo([1]) # 0! = 1 + ... def factorial(n, prev): + ... return n * prev[-1] + >>> factorial(4) + 24 + >>> factorial(3) # use cache values + 6 + >>> factorial.cache_length() # cache length can be obtained + 5 + >>> factorial.fetch_item(slice(2, 4)) + [2, 6] + + """ + cache = initial + + def decorator(f): + @wraps(f) + def g(n): + L = len(cache) + if n < L: + return cache[n] + for i in range(L, n + 1): + cache.append(f(i, cache)) + return cache[-1] + g.cache_length = lambda: len(cache) + g.fetch_item = lambda x: cache[x] + return g + return decorator + + +def assoc_recurrence_memo(base_seq): + """ + Memo decorator for associated sequences defined by recurrence starting from base + + base_seq(n) -- callable to get base sequence elements + + XXX works only for Pn0 = base_seq(0) cases + XXX works only for m <= n cases + """ + + cache = [] + + def decorator(f): + @wraps(f) + def g(n, m): + L = len(cache) + if n < L: + return cache[n][m] + + for i in range(L, n + 1): + # get base sequence + F_i0 = base_seq(i) + F_i_cache = [F_i0] + cache.append(F_i_cache) + + # XXX only works for m <= n cases + # generate assoc sequence + for j in range(1, i + 1): + F_ij = f(i, j, cache) + F_i_cache.append(F_ij) + + return cache[n][m] + + return g + return decorator diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/misc.py b/.venv/lib/python3.12/site-packages/sympy/utilities/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..741b983f03272890b22f2545f67b141767507634 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/misc.py @@ -0,0 +1,564 @@ +"""Miscellaneous stuff that does not really fit anywhere else.""" + +from __future__ import annotations + +import operator +import sys +import os +import re as _re +import struct +from textwrap import fill, dedent + + +class Undecidable(ValueError): + # an error to be raised when a decision cannot be made definitively + # where a definitive answer is needed + pass + + +def filldedent(s, w=70, **kwargs): + """ + Strips leading and trailing empty lines from a copy of ``s``, then dedents, + fills and returns it. + + Empty line stripping serves to deal with docstrings like this one that + start with a newline after the initial triple quote, inserting an empty + line at the beginning of the string. + + Additional keyword arguments will be passed to ``textwrap.fill()``. + + See Also + ======== + strlines, rawlines + + """ + return '\n' + fill(dedent(str(s)).strip('\n'), width=w, **kwargs) + + +def strlines(s, c=64, short=False): + """Return a cut-and-pastable string that, when printed, is + equivalent to the input. The lines will be surrounded by + parentheses and no line will be longer than c (default 64) + characters. If the line contains newlines characters, the + `rawlines` result will be returned. If ``short`` is True + (default is False) then if there is one line it will be + returned without bounding parentheses. + + Examples + ======== + + >>> from sympy.utilities.misc import strlines + >>> q = 'this is a long string that should be broken into shorter lines' + >>> print(strlines(q, 40)) + ( + 'this is a long string that should be b' + 'roken into shorter lines' + ) + >>> q == ( + ... 'this is a long string that should be b' + ... 'roken into shorter lines' + ... ) + True + + See Also + ======== + filldedent, rawlines + """ + if not isinstance(s, str): + raise ValueError('expecting string input') + if '\n' in s: + return rawlines(s) + q = '"' if repr(s).startswith('"') else "'" + q = (q,)*2 + if '\\' in s: # use r-string + m = '(\nr%s%%s%s\n)' % q + j = '%s\nr%s' % q + c -= 3 + else: + m = '(\n%s%%s%s\n)' % q + j = '%s\n%s' % q + c -= 2 + out = [] + while s: + out.append(s[:c]) + s=s[c:] + if short and len(out) == 1: + return (m % out[0]).splitlines()[1] # strip bounding (\n...\n) + return m % j.join(out) + + +def rawlines(s): + """Return a cut-and-pastable string that, when printed, is equivalent + to the input. Use this when there is more than one line in the + string. The string returned is formatted so it can be indented + nicely within tests; in some cases it is wrapped in the dedent + function which has to be imported from textwrap. + + Examples + ======== + + Note: because there are characters in the examples below that need + to be escaped because they are themselves within a triple quoted + docstring, expressions below look more complicated than they would + be if they were printed in an interpreter window. + + >>> from sympy.utilities.misc import rawlines + >>> from sympy import TableForm + >>> s = str(TableForm([[1, 10]], headings=(None, ['a', 'bee']))) + >>> print(rawlines(s)) + ( + 'a bee\\n' + '-----\\n' + '1 10 ' + ) + >>> print(rawlines('''this + ... that''')) + dedent('''\\ + this + that''') + + >>> print(rawlines('''this + ... that + ... ''')) + dedent('''\\ + this + that + ''') + + >>> s = \"\"\"this + ... is a triple ''' + ... \"\"\" + >>> print(rawlines(s)) + dedent(\"\"\"\\ + this + is a triple ''' + \"\"\") + + >>> print(rawlines('''this + ... that + ... ''')) + ( + 'this\\n' + 'that\\n' + ' ' + ) + + See Also + ======== + filldedent, strlines + """ + lines = s.split('\n') + if len(lines) == 1: + return repr(lines[0]) + triple = ["'''" in s, '"""' in s] + if any(li.endswith(' ') for li in lines) or '\\' in s or all(triple): + rv = [] + # add on the newlines + trailing = s.endswith('\n') + last = len(lines) - 1 + for i, li in enumerate(lines): + if i != last or trailing: + rv.append(repr(li + '\n')) + else: + rv.append(repr(li)) + return '(\n %s\n)' % '\n '.join(rv) + else: + rv = '\n '.join(lines) + if triple[0]: + return 'dedent("""\\\n %s""")' % rv + else: + return "dedent('''\\\n %s''')" % rv + +ARCH = str(struct.calcsize('P') * 8) + "-bit" + + +# XXX: PyPy does not support hash randomization +HASH_RANDOMIZATION = getattr(sys.flags, 'hash_randomization', False) + +_debug_tmp: list[str] = [] +_debug_iter = 0 + +def debug_decorator(func): + """If SYMPY_DEBUG is True, it will print a nice execution tree with + arguments and results of all decorated functions, else do nothing. + """ + from sympy import SYMPY_DEBUG + + if not SYMPY_DEBUG: + return func + + def maketree(f, *args, **kw): + global _debug_tmp, _debug_iter + oldtmp = _debug_tmp + _debug_tmp = [] + _debug_iter += 1 + + def tree(subtrees): + def indent(s, variant=1): + x = s.split("\n") + r = "+-%s\n" % x[0] + for a in x[1:]: + if a == "": + continue + if variant == 1: + r += "| %s\n" % a + else: + r += " %s\n" % a + return r + if len(subtrees) == 0: + return "" + f = [] + for a in subtrees[:-1]: + f.append(indent(a)) + f.append(indent(subtrees[-1], 2)) + return ''.join(f) + + # If there is a bug and the algorithm enters an infinite loop, enable the + # following lines. It will print the names and parameters of all major functions + # that are called, *before* they are called + #from functools import reduce + #print("%s%s %s%s" % (_debug_iter, reduce(lambda x, y: x + y, \ + # map(lambda x: '-', range(1, 2 + _debug_iter))), f.__name__, args)) + + r = f(*args, **kw) + + _debug_iter -= 1 + s = "%s%s = %s\n" % (f.__name__, args, r) + if _debug_tmp != []: + s += tree(_debug_tmp) + _debug_tmp = oldtmp + _debug_tmp.append(s) + if _debug_iter == 0: + print(_debug_tmp[0]) + _debug_tmp = [] + return r + + def decorated(*args, **kwargs): + return maketree(func, *args, **kwargs) + + return decorated + + +def debug(*args): + """ + Print ``*args`` if SYMPY_DEBUG is True, else do nothing. + """ + from sympy import SYMPY_DEBUG + if SYMPY_DEBUG: + print(*args, file=sys.stderr) + + +def debugf(string, args): + """ + Print ``string%args`` if SYMPY_DEBUG is True, else do nothing. This is + intended for debug messages using formatted strings. + """ + from sympy import SYMPY_DEBUG + if SYMPY_DEBUG: + print(string%args, file=sys.stderr) + + +def find_executable(executable, path=None): + """Try to find 'executable' in the directories listed in 'path' (a + string listing directories separated by 'os.pathsep'; defaults to + os.environ['PATH']). Returns the complete filename or None if not + found + """ + from .exceptions import sympy_deprecation_warning + sympy_deprecation_warning( + """ + sympy.utilities.misc.find_executable() is deprecated. Use the standard + library shutil.which() function instead. + """, + deprecated_since_version="1.7", + active_deprecations_target="deprecated-find-executable", + ) + if path is None: + path = os.environ['PATH'] + paths = path.split(os.pathsep) + extlist = [''] + if os.name == 'os2': + (base, ext) = os.path.splitext(executable) + # executable files on OS/2 can have an arbitrary extension, but + # .exe is automatically appended if no dot is present in the name + if not ext: + executable = executable + ".exe" + elif sys.platform == 'win32': + pathext = os.environ['PATHEXT'].lower().split(os.pathsep) + (base, ext) = os.path.splitext(executable) + if ext.lower() not in pathext: + extlist = pathext + for ext in extlist: + execname = executable + ext + if os.path.isfile(execname): + return execname + else: + for p in paths: + f = os.path.join(p, execname) + if os.path.isfile(f): + return f + + return None + + +def func_name(x, short=False): + """Return function name of `x` (if defined) else the `type(x)`. + If short is True and there is a shorter alias for the result, + return the alias. + + Examples + ======== + + >>> from sympy.utilities.misc import func_name + >>> from sympy import Matrix + >>> from sympy.abc import x + >>> func_name(Matrix.eye(3)) + 'MutableDenseMatrix' + >>> func_name(x < 1) + 'StrictLessThan' + >>> func_name(x < 1, short=True) + 'Lt' + """ + alias = { + 'GreaterThan': 'Ge', + 'StrictGreaterThan': 'Gt', + 'LessThan': 'Le', + 'StrictLessThan': 'Lt', + 'Equality': 'Eq', + 'Unequality': 'Ne', + } + typ = type(x) + if str(typ).startswith(">> from sympy.utilities.misc import _replace + >>> f = _replace(dict(foo='bar', d='t')) + >>> f('food') + 'bart' + >>> f = _replace({}) + >>> f('food') + 'food' + """ + if not reps: + return lambda x: x + D = lambda match: reps[match.group(0)] + pattern = _re.compile("|".join( + [_re.escape(k) for k, v in reps.items()]), _re.MULTILINE) + return lambda string: pattern.sub(D, string) + + +def replace(string, *reps): + """Return ``string`` with all keys in ``reps`` replaced with + their corresponding values, longer strings first, irrespective + of the order they are given. ``reps`` may be passed as tuples + or a single mapping. + + Examples + ======== + + >>> from sympy.utilities.misc import replace + >>> replace('foo', {'oo': 'ar', 'f': 'b'}) + 'bar' + >>> replace("spamham sha", ("spam", "eggs"), ("sha","md5")) + 'eggsham md5' + + There is no guarantee that a unique answer will be + obtained if keys in a mapping overlap (i.e. are the same + length and have some identical sequence at the + beginning/end): + + >>> reps = [ + ... ('ab', 'x'), + ... ('bc', 'y')] + >>> replace('abc', *reps) in ('xc', 'ay') + True + + References + ========== + + .. [1] https://stackoverflow.com/questions/6116978/how-to-replace-multiple-substrings-of-a-string + """ + if len(reps) == 1: + kv = reps[0] + if isinstance(kv, dict): + reps = kv + else: + return string.replace(*kv) + else: + reps = dict(reps) + return _replace(reps)(string) + + +def translate(s, a, b=None, c=None): + """Return ``s`` where characters have been replaced or deleted. + + SYNTAX + ====== + + translate(s, None, deletechars): + all characters in ``deletechars`` are deleted + translate(s, map [,deletechars]): + all characters in ``deletechars`` (if provided) are deleted + then the replacements defined by map are made; if the keys + of map are strings then the longer ones are handled first. + Multicharacter deletions should have a value of ''. + translate(s, oldchars, newchars, deletechars) + all characters in ``deletechars`` are deleted + then each character in ``oldchars`` is replaced with the + corresponding character in ``newchars`` + + Examples + ======== + + >>> from sympy.utilities.misc import translate + >>> abc = 'abc' + >>> translate(abc, None, 'a') + 'bc' + >>> translate(abc, {'a': 'x'}, 'c') + 'xb' + >>> translate(abc, {'abc': 'x', 'a': 'y'}) + 'x' + + >>> translate('abcd', 'ac', 'AC', 'd') + 'AbC' + + There is no guarantee that a unique answer will be + obtained if keys in a mapping overlap are the same + length and have some identical sequences at the + beginning/end: + + >>> translate(abc, {'ab': 'x', 'bc': 'y'}) in ('xc', 'ay') + True + """ + + mr = {} + if a is None: + if c is not None: + raise ValueError('c should be None when a=None is passed, instead got %s' % c) + if b is None: + return s + c = b + a = b = '' + else: + if isinstance(a, dict): + short = {} + for k in list(a.keys()): + if len(k) == 1 and len(a[k]) == 1: + short[k] = a.pop(k) + mr = a + c = b + if short: + a, b = [''.join(i) for i in list(zip(*short.items()))] + else: + a = b = '' + elif len(a) != len(b): + raise ValueError('oldchars and newchars have different lengths') + + if c: + val = str.maketrans('', '', c) + s = s.translate(val) + s = replace(s, mr) + n = str.maketrans(a, b) + return s.translate(n) + + +def ordinal(num): + """Return ordinal number string of num, e.g. 1 becomes 1st. + """ + # modified from https://codereview.stackexchange.com/questions/41298/producing-ordinal-numbers + n = as_int(num) + k = abs(n) % 100 + if 11 <= k <= 13: + suffix = 'th' + elif k % 10 == 1: + suffix = 'st' + elif k % 10 == 2: + suffix = 'nd' + elif k % 10 == 3: + suffix = 'rd' + else: + suffix = 'th' + return str(n) + suffix + + +def as_int(n, strict=True): + """ + Convert the argument to a builtin integer. + + The return value is guaranteed to be equal to the input. ValueError is + raised if the input has a non-integral value. When ``strict`` is True, this + uses `__index__ `_ + and when it is False it uses ``int``. + + + Examples + ======== + + >>> from sympy.utilities.misc import as_int + >>> from sympy import sqrt, S + + The function is primarily concerned with sanitizing input for + functions that need to work with builtin integers, so anything that + is unambiguously an integer should be returned as an int: + + >>> as_int(S(3)) + 3 + + Floats, being of limited precision, are not assumed to be exact and + will raise an error unless the ``strict`` flag is False. This + precision issue becomes apparent for large floating point numbers: + + >>> big = 1e23 + >>> type(big) is float + True + >>> big == int(big) + True + >>> as_int(big) + Traceback (most recent call last): + ... + ValueError: ... is not an integer + >>> as_int(big, strict=False) + 99999999999999991611392 + + Input that might be a complex representation of an integer value is + also rejected by default: + + >>> one = sqrt(3 + 2*sqrt(2)) - sqrt(2) + >>> int(one) == 1 + True + >>> as_int(one) + Traceback (most recent call last): + ... + ValueError: ... is not an integer + """ + if strict: + try: + if isinstance(n, bool): + raise TypeError + return operator.index(n) + except TypeError: + raise ValueError('%s is not an integer' % (n,)) + else: + try: + result = int(n) + except TypeError: + raise ValueError('%s is not an integer' % (n,)) + if n - result: + raise ValueError('%s is not an integer' % (n,)) + return result diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/pkgdata.py b/.venv/lib/python3.12/site-packages/sympy/utilities/pkgdata.py new file mode 100644 index 0000000000000000000000000000000000000000..8bf2065759362ee09a252d4736bd612b8d271e72 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/pkgdata.py @@ -0,0 +1,33 @@ +# This module is deprecated and will be removed. + +import sys +import os +from io import StringIO + +from sympy.utilities.decorator import deprecated + + +@deprecated( + """ + The sympy.utilities.pkgdata module and its get_resource function are + deprecated. Use the stdlib importlib.resources module instead. + """, + deprecated_since_version="1.12", + active_deprecations_target="pkgdata", +) +def get_resource(identifier, pkgname=__name__): + + mod = sys.modules[pkgname] + fn = getattr(mod, '__file__', None) + if fn is None: + raise OSError("%r has no __file__!") + path = os.path.join(os.path.dirname(fn), identifier) + loader = getattr(mod, '__loader__', None) + if loader is not None: + try: + data = loader.get_data(path) + except (OSError, AttributeError): + pass + else: + return StringIO(data.decode('utf-8')) + return open(os.path.normpath(path), 'rb') diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/pytest.py b/.venv/lib/python3.12/site-packages/sympy/utilities/pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..75494c8e987c7b89bddf18febe09fdc3df2b194e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/pytest.py @@ -0,0 +1,12 @@ +""" +.. deprecated:: 1.6 + + sympy.utilities.pytest has been renamed to sympy.testing.pytest. +""" +from sympy.utilities.exceptions import sympy_deprecation_warning + +sympy_deprecation_warning("The sympy.utilities.pytest submodule is deprecated. Use sympy.testing.pytest instead.", + deprecated_since_version="1.6", + active_deprecations_target="deprecated-sympy-utilities-submodules") + +from sympy.testing.pytest import * # noqa:F401,F403 diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/randtest.py b/.venv/lib/python3.12/site-packages/sympy/utilities/randtest.py new file mode 100644 index 0000000000000000000000000000000000000000..1bd3472ed8a89198d9e78e125f16dae1a56f6bad --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/randtest.py @@ -0,0 +1,12 @@ +""" +.. deprecated:: 1.6 + + sympy.utilities.randtest has been renamed to sympy.core.random. +""" +from sympy.utilities.exceptions import sympy_deprecation_warning + +sympy_deprecation_warning("The sympy.utilities.randtest submodule is deprecated. Use sympy.core.random instead.", + deprecated_since_version="1.6", + active_deprecations_target="deprecated-sympy-utilities-submodules") + +from sympy.core.random import * # noqa:F401,F403 diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/runtests.py b/.venv/lib/python3.12/site-packages/sympy/utilities/runtests.py new file mode 100644 index 0000000000000000000000000000000000000000..bb9f760f070be528e8cd51ab38e00bc944dda9ac --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/runtests.py @@ -0,0 +1,13 @@ +""" +.. deprecated:: 1.6 + + sympy.utilities.runtests has been renamed to sympy.testing.runtests. +""" + +from sympy.utilities.exceptions import sympy_deprecation_warning + +sympy_deprecation_warning("The sympy.utilities.runtests submodule is deprecated. Use sympy.testing.runtests instead.", + deprecated_since_version="1.6", + active_deprecations_target="deprecated-sympy-utilities-submodules") + +from sympy.testing.runtests import * # noqa: F401,F403 diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/source.py b/.venv/lib/python3.12/site-packages/sympy/utilities/source.py new file mode 100644 index 0000000000000000000000000000000000000000..71692b4aaad07df70b63d7e1eaa86c402ad03c4f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/source.py @@ -0,0 +1,40 @@ +""" +This module adds several functions for interactive source code inspection. +""" + + +def get_class(lookup_view): + """ + Convert a string version of a class name to the object. + + For example, get_class('sympy.core.Basic') will return + class Basic located in module sympy.core + """ + if isinstance(lookup_view, str): + mod_name, func_name = get_mod_func(lookup_view) + if func_name != '': + lookup_view = getattr( + __import__(mod_name, {}, {}, ['*']), func_name) + if not callable(lookup_view): + raise AttributeError( + "'%s.%s' is not a callable." % (mod_name, func_name)) + return lookup_view + + +def get_mod_func(callback): + """ + splits the string path to a class into a string path to the module + and the name of the class. + + Examples + ======== + + >>> from sympy.utilities.source import get_mod_func + >>> get_mod_func('sympy.core.basic.Basic') + ('sympy.core.basic', 'Basic') + + """ + dot = callback.rfind('.') + if dot == -1: + return callback, '' + return callback[:dot], callback[dot + 1:] diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__init__.py b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92d48d7b2b943bee2985038e2a519f6cd6db739e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_autowrap.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_autowrap.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6ec226043b347a3b0f32c18698ac8bcef9767e8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_autowrap.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_codegen.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_codegen.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5249b8e25622ff8e4862cb5ded2d1068ad3d0f61 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_codegen.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_codegen_julia.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_codegen_julia.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..247a7cb760e12d8f230e427b645c06759371b2d7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_codegen_julia.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_codegen_octave.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_codegen_octave.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68f7f3fc50e5e41ad59a20f7157a655918ac451e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_codegen_octave.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_codegen_rust.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_codegen_rust.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abb037564e65b1329920aedfe93aa3b1bbad7523 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_codegen_rust.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_decorator.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_decorator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bed954f888aa06e83affd5acb82cdc3b55a828ba Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_decorator.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_deprecated.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_deprecated.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cce6c6acd598082bc164170a37f31b854a1e871 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_deprecated.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_enumerative.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_enumerative.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d36d5fbbf3223dfcfb06c5894408f511c7eb1d0f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_enumerative.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_exceptions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97f8ee75f3e272f34791cba4035ad501f2ea4d13 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_exceptions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_iterables.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_iterables.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07f71bfc102c4f479960860504bed8897fb00422 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_iterables.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_lambdify.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_lambdify.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f1ca2ebc7ce497731455b9f0c8aecdc07170d3b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_lambdify.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43faa5e868f2cf3e3bb1abca9456094d5d854941c8025bd49244ac1dc136a034 +size 141614 diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_matchpy_connector.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_matchpy_connector.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f66c6691f684a3f3dbded0ccace87bc7bb43d72 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_matchpy_connector.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_mathml.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_mathml.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9528340584d4347d92dac60edf3d42eebb2fd25e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_mathml.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_misc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_misc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..158d190a1a254c253c4618d3bee6158eccdac5e3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_misc.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_pickling.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_pickling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80b41ff25741f39dc3ba15bd0de577868c36b0e1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_pickling.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_source.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_source.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e90646ca88f0ccd0350bbcad10cafd50685f698 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_source.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_timeutils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_timeutils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d7d76647bb54aa7c04d8ce8add9bbcb02f6264f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_timeutils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_wester.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_wester.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ecadb9380040c5d5d471094e75696eb58311a9b8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_wester.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f06907937831d8d85a46ad0fad6999e29a653f3f650f3d75d3b1d7795c1583c5 +size 205475 diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_xxe.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_xxe.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..289e482b2f83a61ffb4fe832edbe8eed4250c1f1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/__pycache__/test_xxe.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_autowrap.py b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_autowrap.py new file mode 100644 index 0000000000000000000000000000000000000000..b5a33d77adb46710cfa3cfeb1ea39402e35c76cf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_autowrap.py @@ -0,0 +1,467 @@ +# Tests that require installed backends go into +# sympy/test_external/test_autowrap + +import os +import tempfile +import shutil +from io import StringIO +from pathlib import Path + +from sympy.core import symbols, Eq +from sympy.utilities.autowrap import (autowrap, binary_function, + CythonCodeWrapper, UfuncifyCodeWrapper, CodeWrapper) +from sympy.utilities.codegen import ( + CCodeGen, C99CodeGen, CodeGenArgumentListError, make_routine +) +from sympy.testing.pytest import raises +from sympy.testing.tmpfiles import TmpFileManager + + +def get_string(dump_fn, routines, prefix="file", **kwargs): + """Wrapper for dump_fn. dump_fn writes its results to a stream object and + this wrapper returns the contents of that stream as a string. This + auxiliary function is used by many tests below. + + The header and the empty lines are not generator to facilitate the + testing of the output. + """ + output = StringIO() + dump_fn(routines, output, prefix, **kwargs) + source = output.getvalue() + output.close() + return source + + +def test_cython_wrapper_scalar_function(): + x, y, z = symbols('x,y,z') + expr = (x + y)*z + routine = make_routine("test", expr) + code_gen = CythonCodeWrapper(CCodeGen()) + source = get_string(code_gen.dump_pyx, [routine]) + + expected = ( + "cdef extern from 'file.h':\n" + " double test(double x, double y, double z)\n" + "\n" + "def test_c(double x, double y, double z):\n" + "\n" + " return test(x, y, z)") + assert source == expected + + +def test_cython_wrapper_outarg(): + from sympy.core.relational import Equality + x, y, z = symbols('x,y,z') + code_gen = CythonCodeWrapper(C99CodeGen()) + + routine = make_routine("test", Equality(z, x + y)) + source = get_string(code_gen.dump_pyx, [routine]) + expected = ( + "cdef extern from 'file.h':\n" + " void test(double x, double y, double *z)\n" + "\n" + "def test_c(double x, double y):\n" + "\n" + " cdef double z = 0\n" + " test(x, y, &z)\n" + " return z") + assert source == expected + + +def test_cython_wrapper_inoutarg(): + from sympy.core.relational import Equality + x, y, z = symbols('x,y,z') + code_gen = CythonCodeWrapper(C99CodeGen()) + routine = make_routine("test", Equality(z, x + y + z)) + source = get_string(code_gen.dump_pyx, [routine]) + expected = ( + "cdef extern from 'file.h':\n" + " void test(double x, double y, double *z)\n" + "\n" + "def test_c(double x, double y, double z):\n" + "\n" + " test(x, y, &z)\n" + " return z") + assert source == expected + + +def test_cython_wrapper_compile_flags(): + from sympy.core.relational import Equality + x, y, z = symbols('x,y,z') + routine = make_routine("test", Equality(z, x + y)) + + code_gen = CythonCodeWrapper(CCodeGen()) + + expected = """\ +from setuptools import setup +from setuptools import Extension +from Cython.Build import cythonize +cy_opts = {'compiler_directives': {'language_level': '3'}} + +ext_mods = [Extension( + 'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'], + include_dirs=[], + library_dirs=[], + libraries=[], + extra_compile_args=['-std=c99'], + extra_link_args=[] +)] +setup(ext_modules=cythonize(ext_mods, **cy_opts)) +""" % {'num': CodeWrapper._module_counter} + + temp_dir = tempfile.mkdtemp() + TmpFileManager.tmp_folder(temp_dir) + setup_file_path = os.path.join(temp_dir, 'setup.py') + + code_gen._prepare_files(routine, build_dir=temp_dir) + setup_text = Path(setup_file_path).read_text() + assert setup_text == expected + + code_gen = CythonCodeWrapper(CCodeGen(), + include_dirs=['/usr/local/include', '/opt/booger/include'], + library_dirs=['/user/local/lib'], + libraries=['thelib', 'nilib'], + extra_compile_args=['-slow-math'], + extra_link_args=['-lswamp', '-ltrident'], + cythonize_options={'compiler_directives': {'boundscheck': False}} + ) + expected = """\ +from setuptools import setup +from setuptools import Extension +from Cython.Build import cythonize +cy_opts = {'compiler_directives': {'boundscheck': False}} + +ext_mods = [Extension( + 'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'], + include_dirs=['/usr/local/include', '/opt/booger/include'], + library_dirs=['/user/local/lib'], + libraries=['thelib', 'nilib'], + extra_compile_args=['-slow-math', '-std=c99'], + extra_link_args=['-lswamp', '-ltrident'] +)] +setup(ext_modules=cythonize(ext_mods, **cy_opts)) +""" % {'num': CodeWrapper._module_counter} + + code_gen._prepare_files(routine, build_dir=temp_dir) + setup_text = Path(setup_file_path).read_text() + assert setup_text == expected + + expected = """\ +from setuptools import setup +from setuptools import Extension +from Cython.Build import cythonize +cy_opts = {'compiler_directives': {'boundscheck': False}} +import numpy as np + +ext_mods = [Extension( + 'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'], + include_dirs=['/usr/local/include', '/opt/booger/include', np.get_include()], + library_dirs=['/user/local/lib'], + libraries=['thelib', 'nilib'], + extra_compile_args=['-slow-math', '-std=c99'], + extra_link_args=['-lswamp', '-ltrident'] +)] +setup(ext_modules=cythonize(ext_mods, **cy_opts)) +""" % {'num': CodeWrapper._module_counter} + + code_gen._need_numpy = True + code_gen._prepare_files(routine, build_dir=temp_dir) + setup_text = Path(setup_file_path).read_text() + assert setup_text == expected + + TmpFileManager.cleanup() + +def test_cython_wrapper_unique_dummyvars(): + from sympy.core.relational import Equality + from sympy.core.symbol import Dummy + x, y, z = Dummy('x'), Dummy('y'), Dummy('z') + x_id, y_id, z_id = [str(d.dummy_index) for d in [x, y, z]] + expr = Equality(z, x + y) + routine = make_routine("test", expr) + code_gen = CythonCodeWrapper(CCodeGen()) + source = get_string(code_gen.dump_pyx, [routine]) + expected_template = ( + "cdef extern from 'file.h':\n" + " void test(double x_{x_id}, double y_{y_id}, double *z_{z_id})\n" + "\n" + "def test_c(double x_{x_id}, double y_{y_id}):\n" + "\n" + " cdef double z_{z_id} = 0\n" + " test(x_{x_id}, y_{y_id}, &z_{z_id})\n" + " return z_{z_id}") + expected = expected_template.format(x_id=x_id, y_id=y_id, z_id=z_id) + assert source == expected + +def test_autowrap_dummy(): + x, y, z = symbols('x y z') + + # Uses DummyWrapper to test that codegen works as expected + + f = autowrap(x + y, backend='dummy') + assert f() == str(x + y) + assert f.args == "x, y" + assert f.returns == "nameless" + f = autowrap(Eq(z, x + y), backend='dummy') + assert f() == str(x + y) + assert f.args == "x, y" + assert f.returns == "z" + f = autowrap(Eq(z, x + y + z), backend='dummy') + assert f() == str(x + y + z) + assert f.args == "x, y, z" + assert f.returns == "z" + + +def test_autowrap_args(): + x, y, z = symbols('x y z') + + raises(CodeGenArgumentListError, lambda: autowrap(Eq(z, x + y), + backend='dummy', args=[x])) + f = autowrap(Eq(z, x + y), backend='dummy', args=[y, x]) + assert f() == str(x + y) + assert f.args == "y, x" + assert f.returns == "z" + + raises(CodeGenArgumentListError, lambda: autowrap(Eq(z, x + y + z), + backend='dummy', args=[x, y])) + f = autowrap(Eq(z, x + y + z), backend='dummy', args=[y, x, z]) + assert f() == str(x + y + z) + assert f.args == "y, x, z" + assert f.returns == "z" + + f = autowrap(Eq(z, x + y + z), backend='dummy', args=(y, x, z)) + assert f() == str(x + y + z) + assert f.args == "y, x, z" + assert f.returns == "z" + +def test_autowrap_store_files(): + x, y = symbols('x y') + tmp = tempfile.mkdtemp() + TmpFileManager.tmp_folder(tmp) + + f = autowrap(x + y, backend='dummy', tempdir=tmp) + assert f() == str(x + y) + assert os.access(tmp, os.F_OK) + + TmpFileManager.cleanup() + +def test_autowrap_store_files_issue_gh12939(): + x, y = symbols('x y') + tmp = './tmp' + saved_cwd = os.getcwd() + temp_cwd = tempfile.mkdtemp() + try: + os.chdir(temp_cwd) + f = autowrap(x + y, backend='dummy', tempdir=tmp) + assert f() == str(x + y) + assert os.access(tmp, os.F_OK) + finally: + os.chdir(saved_cwd) + shutil.rmtree(temp_cwd) + + +def test_binary_function(): + x, y = symbols('x y') + f = binary_function('f', x + y, backend='dummy') + assert f._imp_() == str(x + y) + + +def test_ufuncify_source(): + x, y, z = symbols('x,y,z') + code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify")) + routine = make_routine("test", x + y + z) + source = get_string(code_wrapper.dump_c, [routine]) + expected = """\ +#include "Python.h" +#include "math.h" +#include "numpy/ndarraytypes.h" +#include "numpy/ufuncobject.h" +#include "numpy/halffloat.h" +#include "file.h" + +static PyMethodDef wrapper_module_%(num)sMethods[] = { + {NULL, NULL, 0, NULL} +}; + +#ifdef NPY_1_19_API_VERSION +static void test_ufunc(char **args, const npy_intp *dimensions, const npy_intp* steps, void* data) +#else +static void test_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data) +#endif +{ + npy_intp i; + npy_intp n = dimensions[0]; + char *in0 = args[0]; + char *in1 = args[1]; + char *in2 = args[2]; + char *out0 = args[3]; + npy_intp in0_step = steps[0]; + npy_intp in1_step = steps[1]; + npy_intp in2_step = steps[2]; + npy_intp out0_step = steps[3]; + for (i = 0; i < n; i++) { + *((double *)out0) = test(*(double *)in0, *(double *)in1, *(double *)in2); + in0 += in0_step; + in1 += in1_step; + in2 += in2_step; + out0 += out0_step; + } +} +PyUFuncGenericFunction test_funcs[1] = {&test_ufunc}; +static char test_types[4] = {NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE}; +static void *test_data[1] = {NULL}; + +#if PY_VERSION_HEX >= 0x03000000 +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "wrapper_module_%(num)s", + NULL, + -1, + wrapper_module_%(num)sMethods, + NULL, + NULL, + NULL, + NULL +}; + +PyMODINIT_FUNC PyInit_wrapper_module_%(num)s(void) +{ + PyObject *m, *d; + PyObject *ufunc0; + m = PyModule_Create(&moduledef); + if (!m) { + return NULL; + } + import_array(); + import_umath(); + d = PyModule_GetDict(m); + ufunc0 = PyUFunc_FromFuncAndData(test_funcs, test_data, test_types, 1, 3, 1, + PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); + PyDict_SetItemString(d, "test", ufunc0); + Py_DECREF(ufunc0); + return m; +} +#else +PyMODINIT_FUNC initwrapper_module_%(num)s(void) +{ + PyObject *m, *d; + PyObject *ufunc0; + m = Py_InitModule("wrapper_module_%(num)s", wrapper_module_%(num)sMethods); + if (m == NULL) { + return; + } + import_array(); + import_umath(); + d = PyModule_GetDict(m); + ufunc0 = PyUFunc_FromFuncAndData(test_funcs, test_data, test_types, 1, 3, 1, + PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); + PyDict_SetItemString(d, "test", ufunc0); + Py_DECREF(ufunc0); +} +#endif""" % {'num': CodeWrapper._module_counter} + assert source == expected + + +def test_ufuncify_source_multioutput(): + x, y, z = symbols('x,y,z') + var_symbols = (x, y, z) + expr = x + y**3 + 10*z**2 + code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify")) + routines = [make_routine("func{}".format(i), expr.diff(var_symbols[i]), var_symbols) for i in range(len(var_symbols))] + source = get_string(code_wrapper.dump_c, routines, funcname='multitest') + expected = """\ +#include "Python.h" +#include "math.h" +#include "numpy/ndarraytypes.h" +#include "numpy/ufuncobject.h" +#include "numpy/halffloat.h" +#include "file.h" + +static PyMethodDef wrapper_module_%(num)sMethods[] = { + {NULL, NULL, 0, NULL} +}; + +#ifdef NPY_1_19_API_VERSION +static void multitest_ufunc(char **args, const npy_intp *dimensions, const npy_intp* steps, void* data) +#else +static void multitest_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data) +#endif +{ + npy_intp i; + npy_intp n = dimensions[0]; + char *in0 = args[0]; + char *in1 = args[1]; + char *in2 = args[2]; + char *out0 = args[3]; + char *out1 = args[4]; + char *out2 = args[5]; + npy_intp in0_step = steps[0]; + npy_intp in1_step = steps[1]; + npy_intp in2_step = steps[2]; + npy_intp out0_step = steps[3]; + npy_intp out1_step = steps[4]; + npy_intp out2_step = steps[5]; + for (i = 0; i < n; i++) { + *((double *)out0) = func0(*(double *)in0, *(double *)in1, *(double *)in2); + *((double *)out1) = func1(*(double *)in0, *(double *)in1, *(double *)in2); + *((double *)out2) = func2(*(double *)in0, *(double *)in1, *(double *)in2); + in0 += in0_step; + in1 += in1_step; + in2 += in2_step; + out0 += out0_step; + out1 += out1_step; + out2 += out2_step; + } +} +PyUFuncGenericFunction multitest_funcs[1] = {&multitest_ufunc}; +static char multitest_types[6] = {NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE}; +static void *multitest_data[1] = {NULL}; + +#if PY_VERSION_HEX >= 0x03000000 +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "wrapper_module_%(num)s", + NULL, + -1, + wrapper_module_%(num)sMethods, + NULL, + NULL, + NULL, + NULL +}; + +PyMODINIT_FUNC PyInit_wrapper_module_%(num)s(void) +{ + PyObject *m, *d; + PyObject *ufunc0; + m = PyModule_Create(&moduledef); + if (!m) { + return NULL; + } + import_array(); + import_umath(); + d = PyModule_GetDict(m); + ufunc0 = PyUFunc_FromFuncAndData(multitest_funcs, multitest_data, multitest_types, 1, 3, 3, + PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); + PyDict_SetItemString(d, "multitest", ufunc0); + Py_DECREF(ufunc0); + return m; +} +#else +PyMODINIT_FUNC initwrapper_module_%(num)s(void) +{ + PyObject *m, *d; + PyObject *ufunc0; + m = Py_InitModule("wrapper_module_%(num)s", wrapper_module_%(num)sMethods); + if (m == NULL) { + return; + } + import_array(); + import_umath(); + d = PyModule_GetDict(m); + ufunc0 = PyUFunc_FromFuncAndData(multitest_funcs, multitest_data, multitest_types, 1, 3, 3, + PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); + PyDict_SetItemString(d, "multitest", ufunc0); + Py_DECREF(ufunc0); +} +#endif""" % {'num': CodeWrapper._module_counter} + assert source == expected diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_codegen.py b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_codegen.py new file mode 100644 index 0000000000000000000000000000000000000000..4ccc6f9a90fb0a0bec39cea22420da8091ede740 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_codegen.py @@ -0,0 +1,1632 @@ +from io import StringIO + +from sympy.core import symbols, Eq, pi, Catalan, Lambda, Dummy +from sympy.core.relational import Equality +from sympy.core.symbol import Symbol +from sympy.functions.special.error_functions import erf +from sympy.integrals.integrals import Integral +from sympy.matrices import Matrix, MatrixSymbol +from sympy.utilities.codegen import ( + codegen, make_routine, CCodeGen, C89CodeGen, C99CodeGen, InputArgument, + CodeGenError, FCodeGen, CodeGenArgumentListError, OutputArgument, + InOutArgument) +from sympy.testing.pytest import raises +from sympy.utilities.lambdify import implemented_function + +#FIXME: Fails due to circular import in with core +# from sympy import codegen + + +def get_string(dump_fn, routines, prefix="file", header=False, empty=False): + """Wrapper for dump_fn. dump_fn writes its results to a stream object and + this wrapper returns the contents of that stream as a string. This + auxiliary function is used by many tests below. + + The header and the empty lines are not generated to facilitate the + testing of the output. + """ + output = StringIO() + dump_fn(routines, output, prefix, header, empty) + source = output.getvalue() + output.close() + return source + + +def test_Routine_argument_order(): + a, x, y, z = symbols('a x y z') + expr = (x + y)*z + raises(CodeGenArgumentListError, lambda: make_routine("test", expr, + argument_sequence=[z, x])) + raises(CodeGenArgumentListError, lambda: make_routine("test", Eq(a, + expr), argument_sequence=[z, x, y])) + r = make_routine('test', Eq(a, expr), argument_sequence=[z, x, a, y]) + assert [ arg.name for arg in r.arguments ] == [z, x, a, y] + assert [ type(arg) for arg in r.arguments ] == [ + InputArgument, InputArgument, OutputArgument, InputArgument ] + r = make_routine('test', Eq(z, expr), argument_sequence=[z, x, y]) + assert [ type(arg) for arg in r.arguments ] == [ + InOutArgument, InputArgument, InputArgument ] + + from sympy.tensor import IndexedBase, Idx + A, B = map(IndexedBase, ['A', 'B']) + m = symbols('m', integer=True) + i = Idx('i', m) + r = make_routine('test', Eq(A[i], B[i]), argument_sequence=[B, A, m]) + assert [ arg.name for arg in r.arguments ] == [B.label, A.label, m] + + expr = Integral(x*y*z, (x, 1, 2), (y, 1, 3)) + r = make_routine('test', Eq(a, expr), argument_sequence=[z, x, a, y]) + assert [ arg.name for arg in r.arguments ] == [z, x, a, y] + + +def test_empty_c_code(): + code_gen = C89CodeGen() + source = get_string(code_gen.dump_c, []) + assert source == "#include \"file.h\"\n#include \n" + + +def test_empty_c_code_with_comment(): + code_gen = C89CodeGen() + source = get_string(code_gen.dump_c, [], header=True) + assert source[:82] == ( + "/******************************************************************************\n *" + ) + # " Code generated with SymPy 0.7.2-git " + assert source[158:] == ( "*\n" + " * *\n" + " * See http://www.sympy.org/ for more information. *\n" + " * *\n" + " * This file is part of 'project' *\n" + " ******************************************************************************/\n" + "#include \"file.h\"\n" + "#include \n" + ) + + +def test_empty_c_header(): + code_gen = C99CodeGen() + source = get_string(code_gen.dump_h, []) + assert source == "#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n#endif\n" + + +def test_simple_c_code(): + x, y, z = symbols('x,y,z') + expr = (x + y)*z + routine = make_routine("test", expr) + code_gen = C89CodeGen() + source = get_string(code_gen.dump_c, [routine]) + expected = ( + "#include \"file.h\"\n" + "#include \n" + "double test(double x, double y, double z) {\n" + " double test_result;\n" + " test_result = z*(x + y);\n" + " return test_result;\n" + "}\n" + ) + assert source == expected + + +def test_c_code_reserved_words(): + x, y, z = symbols('if, typedef, while') + expr = (x + y) * z + routine = make_routine("test", expr) + code_gen = C99CodeGen() + source = get_string(code_gen.dump_c, [routine]) + expected = ( + "#include \"file.h\"\n" + "#include \n" + "double test(double if_, double typedef_, double while_) {\n" + " double test_result;\n" + " test_result = while_*(if_ + typedef_);\n" + " return test_result;\n" + "}\n" + ) + assert source == expected + + +def test_numbersymbol_c_code(): + routine = make_routine("test", pi**Catalan) + code_gen = C89CodeGen() + source = get_string(code_gen.dump_c, [routine]) + expected = ( + "#include \"file.h\"\n" + "#include \n" + "double test() {\n" + " double test_result;\n" + " double const Catalan = %s;\n" + " test_result = pow(M_PI, Catalan);\n" + " return test_result;\n" + "}\n" + ) % Catalan.evalf(17) + assert source == expected + + +def test_c_code_argument_order(): + x, y, z = symbols('x,y,z') + expr = x + y + routine = make_routine("test", expr, argument_sequence=[z, x, y]) + code_gen = C89CodeGen() + source = get_string(code_gen.dump_c, [routine]) + expected = ( + "#include \"file.h\"\n" + "#include \n" + "double test(double z, double x, double y) {\n" + " double test_result;\n" + " test_result = x + y;\n" + " return test_result;\n" + "}\n" + ) + assert source == expected + + +def test_simple_c_header(): + x, y, z = symbols('x,y,z') + expr = (x + y)*z + routine = make_routine("test", expr) + code_gen = C89CodeGen() + source = get_string(code_gen.dump_h, [routine]) + expected = ( + "#ifndef PROJECT__FILE__H\n" + "#define PROJECT__FILE__H\n" + "double test(double x, double y, double z);\n" + "#endif\n" + ) + assert source == expected + + +def test_simple_c_codegen(): + x, y, z = symbols('x,y,z') + expr = (x + y)*z + expected = [ + ("file.c", + "#include \"file.h\"\n" + "#include \n" + "double test(double x, double y, double z) {\n" + " double test_result;\n" + " test_result = z*(x + y);\n" + " return test_result;\n" + "}\n"), + ("file.h", + "#ifndef PROJECT__FILE__H\n" + "#define PROJECT__FILE__H\n" + "double test(double x, double y, double z);\n" + "#endif\n") + ] + result = codegen(("test", expr), "C", "file", header=False, empty=False) + assert result == expected + + +def test_multiple_results_c(): + x, y, z = symbols('x,y,z') + expr1 = (x + y)*z + expr2 = (x - y)*z + routine = make_routine( + "test", + [expr1, expr2] + ) + code_gen = C99CodeGen() + raises(CodeGenError, lambda: get_string(code_gen.dump_h, [routine])) + + +def test_no_results_c(): + raises(ValueError, lambda: make_routine("test", [])) + + +def test_ansi_math1_codegen(): + # not included: log10 + from sympy.functions.elementary.complexes import Abs + from sympy.functions.elementary.exponential import log + from sympy.functions.elementary.hyperbolic import (cosh, sinh, tanh) + from sympy.functions.elementary.integers import (ceiling, floor) + from sympy.functions.elementary.miscellaneous import sqrt + from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, tan) + x = symbols('x') + name_expr = [ + ("test_fabs", Abs(x)), + ("test_acos", acos(x)), + ("test_asin", asin(x)), + ("test_atan", atan(x)), + ("test_ceil", ceiling(x)), + ("test_cos", cos(x)), + ("test_cosh", cosh(x)), + ("test_floor", floor(x)), + ("test_log", log(x)), + ("test_ln", log(x)), + ("test_sin", sin(x)), + ("test_sinh", sinh(x)), + ("test_sqrt", sqrt(x)), + ("test_tan", tan(x)), + ("test_tanh", tanh(x)), + ] + result = codegen(name_expr, "C89", "file", header=False, empty=False) + assert result[0][0] == "file.c" + assert result[0][1] == ( + '#include "file.h"\n#include \n' + 'double test_fabs(double x) {\n double test_fabs_result;\n test_fabs_result = fabs(x);\n return test_fabs_result;\n}\n' + 'double test_acos(double x) {\n double test_acos_result;\n test_acos_result = acos(x);\n return test_acos_result;\n}\n' + 'double test_asin(double x) {\n double test_asin_result;\n test_asin_result = asin(x);\n return test_asin_result;\n}\n' + 'double test_atan(double x) {\n double test_atan_result;\n test_atan_result = atan(x);\n return test_atan_result;\n}\n' + 'double test_ceil(double x) {\n double test_ceil_result;\n test_ceil_result = ceil(x);\n return test_ceil_result;\n}\n' + 'double test_cos(double x) {\n double test_cos_result;\n test_cos_result = cos(x);\n return test_cos_result;\n}\n' + 'double test_cosh(double x) {\n double test_cosh_result;\n test_cosh_result = cosh(x);\n return test_cosh_result;\n}\n' + 'double test_floor(double x) {\n double test_floor_result;\n test_floor_result = floor(x);\n return test_floor_result;\n}\n' + 'double test_log(double x) {\n double test_log_result;\n test_log_result = log(x);\n return test_log_result;\n}\n' + 'double test_ln(double x) {\n double test_ln_result;\n test_ln_result = log(x);\n return test_ln_result;\n}\n' + 'double test_sin(double x) {\n double test_sin_result;\n test_sin_result = sin(x);\n return test_sin_result;\n}\n' + 'double test_sinh(double x) {\n double test_sinh_result;\n test_sinh_result = sinh(x);\n return test_sinh_result;\n}\n' + 'double test_sqrt(double x) {\n double test_sqrt_result;\n test_sqrt_result = sqrt(x);\n return test_sqrt_result;\n}\n' + 'double test_tan(double x) {\n double test_tan_result;\n test_tan_result = tan(x);\n return test_tan_result;\n}\n' + 'double test_tanh(double x) {\n double test_tanh_result;\n test_tanh_result = tanh(x);\n return test_tanh_result;\n}\n' + ) + assert result[1][0] == "file.h" + assert result[1][1] == ( + '#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n' + 'double test_fabs(double x);\ndouble test_acos(double x);\n' + 'double test_asin(double x);\ndouble test_atan(double x);\n' + 'double test_ceil(double x);\ndouble test_cos(double x);\n' + 'double test_cosh(double x);\ndouble test_floor(double x);\n' + 'double test_log(double x);\ndouble test_ln(double x);\n' + 'double test_sin(double x);\ndouble test_sinh(double x);\n' + 'double test_sqrt(double x);\ndouble test_tan(double x);\n' + 'double test_tanh(double x);\n#endif\n' + ) + + +def test_ansi_math2_codegen(): + # not included: frexp, ldexp, modf, fmod + from sympy.functions.elementary.trigonometric import atan2 + x, y = symbols('x,y') + name_expr = [ + ("test_atan2", atan2(x, y)), + ("test_pow", x**y), + ] + result = codegen(name_expr, "C89", "file", header=False, empty=False) + assert result[0][0] == "file.c" + assert result[0][1] == ( + '#include "file.h"\n#include \n' + 'double test_atan2(double x, double y) {\n double test_atan2_result;\n test_atan2_result = atan2(x, y);\n return test_atan2_result;\n}\n' + 'double test_pow(double x, double y) {\n double test_pow_result;\n test_pow_result = pow(x, y);\n return test_pow_result;\n}\n' + ) + assert result[1][0] == "file.h" + assert result[1][1] == ( + '#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n' + 'double test_atan2(double x, double y);\n' + 'double test_pow(double x, double y);\n' + '#endif\n' + ) + + +def test_complicated_codegen(): + from sympy.functions.elementary.trigonometric import (cos, sin, tan) + x, y, z = symbols('x,y,z') + name_expr = [ + ("test1", ((sin(x) + cos(y) + tan(z))**7).expand()), + ("test2", cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))), + ] + result = codegen(name_expr, "C89", "file", header=False, empty=False) + assert result[0][0] == "file.c" + assert result[0][1] == ( + '#include "file.h"\n#include \n' + 'double test1(double x, double y, double z) {\n' + ' double test1_result;\n' + ' test1_result = ' + 'pow(sin(x), 7) + ' + '7*pow(sin(x), 6)*cos(y) + ' + '7*pow(sin(x), 6)*tan(z) + ' + '21*pow(sin(x), 5)*pow(cos(y), 2) + ' + '42*pow(sin(x), 5)*cos(y)*tan(z) + ' + '21*pow(sin(x), 5)*pow(tan(z), 2) + ' + '35*pow(sin(x), 4)*pow(cos(y), 3) + ' + '105*pow(sin(x), 4)*pow(cos(y), 2)*tan(z) + ' + '105*pow(sin(x), 4)*cos(y)*pow(tan(z), 2) + ' + '35*pow(sin(x), 4)*pow(tan(z), 3) + ' + '35*pow(sin(x), 3)*pow(cos(y), 4) + ' + '140*pow(sin(x), 3)*pow(cos(y), 3)*tan(z) + ' + '210*pow(sin(x), 3)*pow(cos(y), 2)*pow(tan(z), 2) + ' + '140*pow(sin(x), 3)*cos(y)*pow(tan(z), 3) + ' + '35*pow(sin(x), 3)*pow(tan(z), 4) + ' + '21*pow(sin(x), 2)*pow(cos(y), 5) + ' + '105*pow(sin(x), 2)*pow(cos(y), 4)*tan(z) + ' + '210*pow(sin(x), 2)*pow(cos(y), 3)*pow(tan(z), 2) + ' + '210*pow(sin(x), 2)*pow(cos(y), 2)*pow(tan(z), 3) + ' + '105*pow(sin(x), 2)*cos(y)*pow(tan(z), 4) + ' + '21*pow(sin(x), 2)*pow(tan(z), 5) + ' + '7*sin(x)*pow(cos(y), 6) + ' + '42*sin(x)*pow(cos(y), 5)*tan(z) + ' + '105*sin(x)*pow(cos(y), 4)*pow(tan(z), 2) + ' + '140*sin(x)*pow(cos(y), 3)*pow(tan(z), 3) + ' + '105*sin(x)*pow(cos(y), 2)*pow(tan(z), 4) + ' + '42*sin(x)*cos(y)*pow(tan(z), 5) + ' + '7*sin(x)*pow(tan(z), 6) + ' + 'pow(cos(y), 7) + ' + '7*pow(cos(y), 6)*tan(z) + ' + '21*pow(cos(y), 5)*pow(tan(z), 2) + ' + '35*pow(cos(y), 4)*pow(tan(z), 3) + ' + '35*pow(cos(y), 3)*pow(tan(z), 4) + ' + '21*pow(cos(y), 2)*pow(tan(z), 5) + ' + '7*cos(y)*pow(tan(z), 6) + ' + 'pow(tan(z), 7);\n' + ' return test1_result;\n' + '}\n' + 'double test2(double x, double y, double z) {\n' + ' double test2_result;\n' + ' test2_result = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))));\n' + ' return test2_result;\n' + '}\n' + ) + assert result[1][0] == "file.h" + assert result[1][1] == ( + '#ifndef PROJECT__FILE__H\n' + '#define PROJECT__FILE__H\n' + 'double test1(double x, double y, double z);\n' + 'double test2(double x, double y, double z);\n' + '#endif\n' + ) + + +def test_loops_c(): + from sympy.tensor import IndexedBase, Idx + from sympy.core.symbol import symbols + n, m = symbols('n m', integer=True) + A = IndexedBase('A') + x = IndexedBase('x') + y = IndexedBase('y') + i = Idx('i', m) + j = Idx('j', n) + + (f1, code), (f2, interface) = codegen( + ('matrix_vector', Eq(y[i], A[i, j]*x[j])), "C99", "file", header=False, empty=False) + + assert f1 == 'file.c' + expected = ( + '#include "file.h"\n' + '#include \n' + 'void matrix_vector(double *A, int m, int n, double *x, double *y) {\n' + ' for (int i=0; i\n' + 'void test_dummies(int m_%(mno)i, double *x, double *y) {\n' + ' for (int i_%(ino)i=0; i_%(ino)i\n' + 'void matrix_vector(double *A, int m, int n, int o, int p, double *x, double *y) {\n' + ' for (int i=o; i<%(upperi)s; i++){\n' + ' y[i] = 0;\n' + ' }\n' + ' for (int i=o; i<%(upperi)s; i++){\n' + ' for (int j=0; j\n' + 'double foo(double x, double *y) {\n' + ' (*y) = sin(x);\n' + ' double foo_result;\n' + ' foo_result = cos(x);\n' + ' return foo_result;\n' + '}\n' + ) + assert result[0][1] == expected + + +def test_output_arg_c_reserved_words(): + from sympy.core.relational import Equality + from sympy.functions.elementary.trigonometric import (cos, sin) + x, y, z = symbols("if, while, z") + r = make_routine("foo", [Equality(y, sin(x)), cos(x)]) + c = C89CodeGen() + result = c.write([r], "test", header=False, empty=False) + assert result[0][0] == "test.c" + expected = ( + '#include "test.h"\n' + '#include \n' + 'double foo(double if_, double *while_) {\n' + ' (*while_) = sin(if_);\n' + ' double foo_result;\n' + ' foo_result = cos(if_);\n' + ' return foo_result;\n' + '}\n' + ) + assert result[0][1] == expected + + +def test_multidim_c_argument_cse(): + A_sym = MatrixSymbol('A', 3, 3) + b_sym = MatrixSymbol('b', 3, 1) + A = Matrix(A_sym) + b = Matrix(b_sym) + c = A*b + cgen = CCodeGen(project="test", cse=True) + r = cgen.routine("c", c) + r.arguments[-1].result_var = "out" + r.arguments[-1]._name = "out" + code = get_string(cgen.dump_c, [r], prefix="test") + expected = ( + '#include "test.h"\n' + "#include \n" + "void c(double *A, double *b, double *out) {\n" + " out[0] = A[0]*b[0] + A[1]*b[1] + A[2]*b[2];\n" + " out[1] = A[3]*b[0] + A[4]*b[1] + A[5]*b[2];\n" + " out[2] = A[6]*b[0] + A[7]*b[1] + A[8]*b[2];\n" + "}\n" + ) + assert code == expected + + +def test_ccode_results_named_ordered(): + x, y, z = symbols('x,y,z') + B, C = symbols('B,C') + A = MatrixSymbol('A', 1, 3) + expr1 = Equality(A, Matrix([[1, 2, x]])) + expr2 = Equality(C, (x + y)*z) + expr3 = Equality(B, 2*x) + name_expr = ("test", [expr1, expr2, expr3]) + expected = ( + '#include "test.h"\n' + '#include \n' + 'void test(double x, double *C, double z, double y, double *A, double *B) {\n' + ' (*C) = z*(x + y);\n' + ' A[0] = 1;\n' + ' A[1] = 2;\n' + ' A[2] = x;\n' + ' (*B) = 2*x;\n' + '}\n' + ) + + result = codegen(name_expr, "c", "test", header=False, empty=False, + argument_sequence=(x, C, z, y, A, B)) + source = result[0][1] + assert source == expected + + +def test_ccode_matrixsymbol_slice(): + A = MatrixSymbol('A', 5, 3) + B = MatrixSymbol('B', 1, 3) + C = MatrixSymbol('C', 1, 3) + D = MatrixSymbol('D', 5, 1) + name_expr = ("test", [Equality(B, A[0, :]), + Equality(C, A[1, :]), + Equality(D, A[:, 2])]) + result = codegen(name_expr, "c99", "test", header=False, empty=False) + source = result[0][1] + expected = ( + '#include "test.h"\n' + '#include \n' + 'void test(double *A, double *B, double *C, double *D) {\n' + ' B[0] = A[0];\n' + ' B[1] = A[1];\n' + ' B[2] = A[2];\n' + ' C[0] = A[3];\n' + ' C[1] = A[4];\n' + ' C[2] = A[5];\n' + ' D[0] = A[2];\n' + ' D[1] = A[5];\n' + ' D[2] = A[8];\n' + ' D[3] = A[11];\n' + ' D[4] = A[14];\n' + '}\n' + ) + assert source == expected + +def test_ccode_cse(): + a, b, c, d = symbols('a b c d') + e = MatrixSymbol('e', 3, 1) + name_expr = ("test", [Equality(e, Matrix([[a*b], [a*b + c*d], [a*b*c*d]]))]) + generator = CCodeGen(cse=True) + result = codegen(name_expr, code_gen=generator, header=False, empty=False) + source = result[0][1] + expected = ( + '#include "test.h"\n' + '#include \n' + 'void test(double a, double b, double c, double d, double *e) {\n' + ' const double x0 = a*b;\n' + ' const double x1 = c*d;\n' + ' e[0] = x0;\n' + ' e[1] = x0 + x1;\n' + ' e[2] = x0*x1;\n' + '}\n' + ) + assert source == expected + +def test_ccode_unused_array_arg(): + x = MatrixSymbol('x', 2, 1) + # x does not appear in output + name_expr = ("test", 1.0) + generator = CCodeGen() + result = codegen(name_expr, code_gen=generator, header=False, empty=False, argument_sequence=(x,)) + source = result[0][1] + # note: x should appear as (double *) + expected = ( + '#include "test.h"\n' + '#include \n' + 'double test(double *x) {\n' + ' double test_result;\n' + ' test_result = 1.0;\n' + ' return test_result;\n' + '}\n' + ) + assert source == expected + +def test_ccode_unused_array_arg_func(): + # issue 16689 + X = MatrixSymbol('X',3,1) + Y = MatrixSymbol('Y',3,1) + z = symbols('z',integer = True) + name_expr = ('testBug', X[0] + X[1]) + result = codegen(name_expr, language='C', header=False, empty=False, argument_sequence=(X, Y, z)) + source = result[0][1] + expected = ( + '#include "testBug.h"\n' + '#include \n' + 'double testBug(double *X, double *Y, int z) {\n' + ' double testBug_result;\n' + ' testBug_result = X[0] + X[1];\n' + ' return testBug_result;\n' + '}\n' + ) + assert source == expected + +def test_empty_f_code(): + code_gen = FCodeGen() + source = get_string(code_gen.dump_f95, []) + assert source == "" + + +def test_empty_f_code_with_header(): + code_gen = FCodeGen() + source = get_string(code_gen.dump_f95, [], header=True) + assert source[:82] == ( + "!******************************************************************************\n!*" + ) + # " Code generated with SymPy 0.7.2-git " + assert source[158:] == ( "*\n" + "!* *\n" + "!* See http://www.sympy.org/ for more information. *\n" + "!* *\n" + "!* This file is part of 'project' *\n" + "!******************************************************************************\n" + ) + + +def test_empty_f_header(): + code_gen = FCodeGen() + source = get_string(code_gen.dump_h, []) + assert source == "" + + +def test_simple_f_code(): + x, y, z = symbols('x,y,z') + expr = (x + y)*z + routine = make_routine("test", expr) + code_gen = FCodeGen() + source = get_string(code_gen.dump_f95, [routine]) + expected = ( + "REAL*8 function test(x, y, z)\n" + "implicit none\n" + "REAL*8, intent(in) :: x\n" + "REAL*8, intent(in) :: y\n" + "REAL*8, intent(in) :: z\n" + "test = z*(x + y)\n" + "end function\n" + ) + assert source == expected + + +def test_numbersymbol_f_code(): + routine = make_routine("test", pi**Catalan) + code_gen = FCodeGen() + source = get_string(code_gen.dump_f95, [routine]) + expected = ( + "REAL*8 function test()\n" + "implicit none\n" + "REAL*8, parameter :: Catalan = %sd0\n" + "REAL*8, parameter :: pi = %sd0\n" + "test = pi**Catalan\n" + "end function\n" + ) % (Catalan.evalf(17), pi.evalf(17)) + assert source == expected + +def test_erf_f_code(): + x = symbols('x') + routine = make_routine("test", erf(x) - erf(-2 * x)) + code_gen = FCodeGen() + source = get_string(code_gen.dump_f95, [routine]) + expected = ( + "REAL*8 function test(x)\n" + "implicit none\n" + "REAL*8, intent(in) :: x\n" + "test = erf(x) + erf(2.0d0*x)\n" + "end function\n" + ) + assert source == expected, source + +def test_f_code_argument_order(): + x, y, z = symbols('x,y,z') + expr = x + y + routine = make_routine("test", expr, argument_sequence=[z, x, y]) + code_gen = FCodeGen() + source = get_string(code_gen.dump_f95, [routine]) + expected = ( + "REAL*8 function test(z, x, y)\n" + "implicit none\n" + "REAL*8, intent(in) :: z\n" + "REAL*8, intent(in) :: x\n" + "REAL*8, intent(in) :: y\n" + "test = x + y\n" + "end function\n" + ) + assert source == expected + + +def test_simple_f_header(): + x, y, z = symbols('x,y,z') + expr = (x + y)*z + routine = make_routine("test", expr) + code_gen = FCodeGen() + source = get_string(code_gen.dump_h, [routine]) + expected = ( + "interface\n" + "REAL*8 function test(x, y, z)\n" + "implicit none\n" + "REAL*8, intent(in) :: x\n" + "REAL*8, intent(in) :: y\n" + "REAL*8, intent(in) :: z\n" + "end function\n" + "end interface\n" + ) + assert source == expected + + +def test_simple_f_codegen(): + x, y, z = symbols('x,y,z') + expr = (x + y)*z + result = codegen( + ("test", expr), "F95", "file", header=False, empty=False) + expected = [ + ("file.f90", + "REAL*8 function test(x, y, z)\n" + "implicit none\n" + "REAL*8, intent(in) :: x\n" + "REAL*8, intent(in) :: y\n" + "REAL*8, intent(in) :: z\n" + "test = z*(x + y)\n" + "end function\n"), + ("file.h", + "interface\n" + "REAL*8 function test(x, y, z)\n" + "implicit none\n" + "REAL*8, intent(in) :: x\n" + "REAL*8, intent(in) :: y\n" + "REAL*8, intent(in) :: z\n" + "end function\n" + "end interface\n") + ] + assert result == expected + + +def test_multiple_results_f(): + x, y, z = symbols('x,y,z') + expr1 = (x + y)*z + expr2 = (x - y)*z + routine = make_routine( + "test", + [expr1, expr2] + ) + code_gen = FCodeGen() + raises(CodeGenError, lambda: get_string(code_gen.dump_h, [routine])) + + +def test_no_results_f(): + raises(ValueError, lambda: make_routine("test", [])) + + +def test_intrinsic_math_codegen(): + # not included: log10 + from sympy.functions.elementary.complexes import Abs + from sympy.functions.elementary.exponential import log + from sympy.functions.elementary.hyperbolic import (cosh, sinh, tanh) + from sympy.functions.elementary.miscellaneous import sqrt + from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, tan) + x = symbols('x') + name_expr = [ + ("test_abs", Abs(x)), + ("test_acos", acos(x)), + ("test_asin", asin(x)), + ("test_atan", atan(x)), + ("test_cos", cos(x)), + ("test_cosh", cosh(x)), + ("test_log", log(x)), + ("test_ln", log(x)), + ("test_sin", sin(x)), + ("test_sinh", sinh(x)), + ("test_sqrt", sqrt(x)), + ("test_tan", tan(x)), + ("test_tanh", tanh(x)), + ] + result = codegen(name_expr, "F95", "file", header=False, empty=False) + assert result[0][0] == "file.f90" + expected = ( + 'REAL*8 function test_abs(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_abs = abs(x)\n' + 'end function\n' + 'REAL*8 function test_acos(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_acos = acos(x)\n' + 'end function\n' + 'REAL*8 function test_asin(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_asin = asin(x)\n' + 'end function\n' + 'REAL*8 function test_atan(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_atan = atan(x)\n' + 'end function\n' + 'REAL*8 function test_cos(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_cos = cos(x)\n' + 'end function\n' + 'REAL*8 function test_cosh(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_cosh = cosh(x)\n' + 'end function\n' + 'REAL*8 function test_log(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_log = log(x)\n' + 'end function\n' + 'REAL*8 function test_ln(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_ln = log(x)\n' + 'end function\n' + 'REAL*8 function test_sin(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_sin = sin(x)\n' + 'end function\n' + 'REAL*8 function test_sinh(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_sinh = sinh(x)\n' + 'end function\n' + 'REAL*8 function test_sqrt(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_sqrt = sqrt(x)\n' + 'end function\n' + 'REAL*8 function test_tan(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_tan = tan(x)\n' + 'end function\n' + 'REAL*8 function test_tanh(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'test_tanh = tanh(x)\n' + 'end function\n' + ) + assert result[0][1] == expected + + assert result[1][0] == "file.h" + expected = ( + 'interface\n' + 'REAL*8 function test_abs(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_acos(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_asin(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_atan(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_cos(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_cosh(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_log(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_ln(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_sin(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_sinh(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_sqrt(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_tan(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_tanh(x)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'end function\n' + 'end interface\n' + ) + assert result[1][1] == expected + + +def test_intrinsic_math2_codegen(): + # not included: frexp, ldexp, modf, fmod + from sympy.functions.elementary.trigonometric import atan2 + x, y = symbols('x,y') + name_expr = [ + ("test_atan2", atan2(x, y)), + ("test_pow", x**y), + ] + result = codegen(name_expr, "F95", "file", header=False, empty=False) + assert result[0][0] == "file.f90" + expected = ( + 'REAL*8 function test_atan2(x, y)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'REAL*8, intent(in) :: y\n' + 'test_atan2 = atan2(x, y)\n' + 'end function\n' + 'REAL*8 function test_pow(x, y)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'REAL*8, intent(in) :: y\n' + 'test_pow = x**y\n' + 'end function\n' + ) + assert result[0][1] == expected + + assert result[1][0] == "file.h" + expected = ( + 'interface\n' + 'REAL*8 function test_atan2(x, y)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'REAL*8, intent(in) :: y\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test_pow(x, y)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'REAL*8, intent(in) :: y\n' + 'end function\n' + 'end interface\n' + ) + assert result[1][1] == expected + + +def test_complicated_codegen_f95(): + from sympy.functions.elementary.trigonometric import (cos, sin, tan) + x, y, z = symbols('x,y,z') + name_expr = [ + ("test1", ((sin(x) + cos(y) + tan(z))**7).expand()), + ("test2", cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))), + ] + result = codegen(name_expr, "F95", "file", header=False, empty=False) + assert result[0][0] == "file.f90" + expected = ( + 'REAL*8 function test1(x, y, z)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'REAL*8, intent(in) :: y\n' + 'REAL*8, intent(in) :: z\n' + 'test1 = sin(x)**7 + 7*sin(x)**6*cos(y) + 7*sin(x)**6*tan(z) + 21*sin(x) &\n' + ' **5*cos(y)**2 + 42*sin(x)**5*cos(y)*tan(z) + 21*sin(x)**5*tan(z) &\n' + ' **2 + 35*sin(x)**4*cos(y)**3 + 105*sin(x)**4*cos(y)**2*tan(z) + &\n' + ' 105*sin(x)**4*cos(y)*tan(z)**2 + 35*sin(x)**4*tan(z)**3 + 35*sin( &\n' + ' x)**3*cos(y)**4 + 140*sin(x)**3*cos(y)**3*tan(z) + 210*sin(x)**3* &\n' + ' cos(y)**2*tan(z)**2 + 140*sin(x)**3*cos(y)*tan(z)**3 + 35*sin(x) &\n' + ' **3*tan(z)**4 + 21*sin(x)**2*cos(y)**5 + 105*sin(x)**2*cos(y)**4* &\n' + ' tan(z) + 210*sin(x)**2*cos(y)**3*tan(z)**2 + 210*sin(x)**2*cos(y) &\n' + ' **2*tan(z)**3 + 105*sin(x)**2*cos(y)*tan(z)**4 + 21*sin(x)**2*tan &\n' + ' (z)**5 + 7*sin(x)*cos(y)**6 + 42*sin(x)*cos(y)**5*tan(z) + 105* &\n' + ' sin(x)*cos(y)**4*tan(z)**2 + 140*sin(x)*cos(y)**3*tan(z)**3 + 105 &\n' + ' *sin(x)*cos(y)**2*tan(z)**4 + 42*sin(x)*cos(y)*tan(z)**5 + 7*sin( &\n' + ' x)*tan(z)**6 + cos(y)**7 + 7*cos(y)**6*tan(z) + 21*cos(y)**5*tan( &\n' + ' z)**2 + 35*cos(y)**4*tan(z)**3 + 35*cos(y)**3*tan(z)**4 + 21*cos( &\n' + ' y)**2*tan(z)**5 + 7*cos(y)*tan(z)**6 + tan(z)**7\n' + 'end function\n' + 'REAL*8 function test2(x, y, z)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'REAL*8, intent(in) :: y\n' + 'REAL*8, intent(in) :: z\n' + 'test2 = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))\n' + 'end function\n' + ) + assert result[0][1] == expected + assert result[1][0] == "file.h" + expected = ( + 'interface\n' + 'REAL*8 function test1(x, y, z)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'REAL*8, intent(in) :: y\n' + 'REAL*8, intent(in) :: z\n' + 'end function\n' + 'end interface\n' + 'interface\n' + 'REAL*8 function test2(x, y, z)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'REAL*8, intent(in) :: y\n' + 'REAL*8, intent(in) :: z\n' + 'end function\n' + 'end interface\n' + ) + assert result[1][1] == expected + + +def test_loops(): + from sympy.tensor import IndexedBase, Idx + from sympy.core.symbol import symbols + + n, m = symbols('n,m', integer=True) + A, x, y = map(IndexedBase, 'Axy') + i = Idx('i', m) + j = Idx('j', n) + + (f1, code), (f2, interface) = codegen( + ('matrix_vector', Eq(y[i], A[i, j]*x[j])), "F95", "file", header=False, empty=False) + + assert f1 == 'file.f90' + expected = ( + 'subroutine matrix_vector(A, m, n, x, y)\n' + 'implicit none\n' + 'INTEGER*4, intent(in) :: m\n' + 'INTEGER*4, intent(in) :: n\n' + 'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n' + 'REAL*8, intent(in), dimension(1:n) :: x\n' + 'REAL*8, intent(out), dimension(1:m) :: y\n' + 'INTEGER*4 :: i\n' + 'INTEGER*4 :: j\n' + 'do i = 1, m\n' + ' y(i) = 0\n' + 'end do\n' + 'do i = 1, m\n' + ' do j = 1, n\n' + ' y(i) = %(rhs)s + y(i)\n' + ' end do\n' + 'end do\n' + 'end subroutine\n' + ) + + assert code == expected % {'rhs': 'A(i, j)*x(j)'} or\ + code == expected % {'rhs': 'x(j)*A(i, j)'} + assert f2 == 'file.h' + assert interface == ( + 'interface\n' + 'subroutine matrix_vector(A, m, n, x, y)\n' + 'implicit none\n' + 'INTEGER*4, intent(in) :: m\n' + 'INTEGER*4, intent(in) :: n\n' + 'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n' + 'REAL*8, intent(in), dimension(1:n) :: x\n' + 'REAL*8, intent(out), dimension(1:m) :: y\n' + 'end subroutine\n' + 'end interface\n' + ) + + +def test_dummy_loops_f95(): + from sympy.tensor import IndexedBase, Idx + i, m = symbols('i m', integer=True, cls=Dummy) + x = IndexedBase('x') + y = IndexedBase('y') + i = Idx(i, m) + expected = ( + 'subroutine test_dummies(m_%(mcount)i, x, y)\n' + 'implicit none\n' + 'INTEGER*4, intent(in) :: m_%(mcount)i\n' + 'REAL*8, intent(in), dimension(1:m_%(mcount)i) :: x\n' + 'REAL*8, intent(out), dimension(1:m_%(mcount)i) :: y\n' + 'INTEGER*4 :: i_%(icount)i\n' + 'do i_%(icount)i = 1, m_%(mcount)i\n' + ' y(i_%(icount)i) = x(i_%(icount)i)\n' + 'end do\n' + 'end subroutine\n' + ) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index} + r = make_routine('test_dummies', Eq(y[i], x[i])) + c = FCodeGen() + code = get_string(c.dump_f95, [r]) + assert code == expected + + +def test_loops_InOut(): + from sympy.tensor import IndexedBase, Idx + from sympy.core.symbol import symbols + + i, j, n, m = symbols('i,j,n,m', integer=True) + A, x, y = symbols('A,x,y') + A = IndexedBase(A)[Idx(i, m), Idx(j, n)] + x = IndexedBase(x)[Idx(j, n)] + y = IndexedBase(y)[Idx(i, m)] + + (f1, code), (f2, interface) = codegen( + ('matrix_vector', Eq(y, y + A*x)), "F95", "file", header=False, empty=False) + + assert f1 == 'file.f90' + expected = ( + 'subroutine matrix_vector(A, m, n, x, y)\n' + 'implicit none\n' + 'INTEGER*4, intent(in) :: m\n' + 'INTEGER*4, intent(in) :: n\n' + 'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n' + 'REAL*8, intent(in), dimension(1:n) :: x\n' + 'REAL*8, intent(inout), dimension(1:m) :: y\n' + 'INTEGER*4 :: i\n' + 'INTEGER*4 :: j\n' + 'do i = 1, m\n' + ' do j = 1, n\n' + ' y(i) = %(rhs)s + y(i)\n' + ' end do\n' + 'end do\n' + 'end subroutine\n' + ) + + assert (code == expected % {'rhs': 'A(i, j)*x(j)'} or + code == expected % {'rhs': 'x(j)*A(i, j)'}) + assert f2 == 'file.h' + assert interface == ( + 'interface\n' + 'subroutine matrix_vector(A, m, n, x, y)\n' + 'implicit none\n' + 'INTEGER*4, intent(in) :: m\n' + 'INTEGER*4, intent(in) :: n\n' + 'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n' + 'REAL*8, intent(in), dimension(1:n) :: x\n' + 'REAL*8, intent(inout), dimension(1:m) :: y\n' + 'end subroutine\n' + 'end interface\n' + ) + + +def test_partial_loops_f(): + # check that loop boundaries are determined by Idx, and array strides + # determined by shape of IndexedBase object. + from sympy.tensor import IndexedBase, Idx + from sympy.core.symbol import symbols + n, m, o, p = symbols('n m o p', integer=True) + A = IndexedBase('A', shape=(m, p)) + x = IndexedBase('x') + y = IndexedBase('y') + i = Idx('i', (o, m - 5)) # Note: bounds are inclusive + j = Idx('j', n) # dimension n corresponds to bounds (0, n - 1) + + (f1, code), (f2, interface) = codegen( + ('matrix_vector', Eq(y[i], A[i, j]*x[j])), "F95", "file", header=False, empty=False) + + expected = ( + 'subroutine matrix_vector(A, m, n, o, p, x, y)\n' + 'implicit none\n' + 'INTEGER*4, intent(in) :: m\n' + 'INTEGER*4, intent(in) :: n\n' + 'INTEGER*4, intent(in) :: o\n' + 'INTEGER*4, intent(in) :: p\n' + 'REAL*8, intent(in), dimension(1:m, 1:p) :: A\n' + 'REAL*8, intent(in), dimension(1:n) :: x\n' + 'REAL*8, intent(out), dimension(1:%(iup-ilow)s) :: y\n' + 'INTEGER*4 :: i\n' + 'INTEGER*4 :: j\n' + 'do i = %(ilow)s, %(iup)s\n' + ' y(i) = 0\n' + 'end do\n' + 'do i = %(ilow)s, %(iup)s\n' + ' do j = 1, n\n' + ' y(i) = %(rhs)s + y(i)\n' + ' end do\n' + 'end do\n' + 'end subroutine\n' + ) % { + 'rhs': '%(rhs)s', + 'iup': str(m - 4), + 'ilow': str(1 + o), + 'iup-ilow': str(m - 4 - o) + } + + assert code == expected % {'rhs': 'A(i, j)*x(j)'} or\ + code == expected % {'rhs': 'x(j)*A(i, j)'} + + +def test_output_arg_f(): + from sympy.core.relational import Equality + from sympy.functions.elementary.trigonometric import (cos, sin) + x, y, z = symbols("x,y,z") + r = make_routine("foo", [Equality(y, sin(x)), cos(x)]) + c = FCodeGen() + result = c.write([r], "test", header=False, empty=False) + assert result[0][0] == "test.f90" + assert result[0][1] == ( + 'REAL*8 function foo(x, y)\n' + 'implicit none\n' + 'REAL*8, intent(in) :: x\n' + 'REAL*8, intent(out) :: y\n' + 'y = sin(x)\n' + 'foo = cos(x)\n' + 'end function\n' + ) + + +def test_inline_function(): + from sympy.tensor import IndexedBase, Idx + from sympy.core.symbol import symbols + n, m = symbols('n m', integer=True) + A, x, y = map(IndexedBase, 'Axy') + i = Idx('i', m) + p = FCodeGen() + func = implemented_function('func', Lambda(n, n*(n + 1))) + routine = make_routine('test_inline', Eq(y[i], func(x[i]))) + code = get_string(p.dump_f95, [routine]) + expected = ( + 'subroutine test_inline(m, x, y)\n' + 'implicit none\n' + 'INTEGER*4, intent(in) :: m\n' + 'REAL*8, intent(in), dimension(1:m) :: x\n' + 'REAL*8, intent(out), dimension(1:m) :: y\n' + 'INTEGER*4 :: i\n' + 'do i = 1, m\n' + ' y(i) = %s*%s\n' + 'end do\n' + 'end subroutine\n' + ) + args = ('x(i)', '(x(i) + 1)') + assert code == expected % args or\ + code == expected % args[::-1] + + +def test_f_code_call_signature_wrap(): + # Issue #7934 + x = symbols('x:20') + expr = 0 + for sym in x: + expr += sym + routine = make_routine("test", expr) + code_gen = FCodeGen() + source = get_string(code_gen.dump_f95, [routine]) + expected = """\ +REAL*8 function test(x0, x1, x10, x11, x12, x13, x14, x15, x16, x17, x18, & + x19, x2, x3, x4, x5, x6, x7, x8, x9) +implicit none +REAL*8, intent(in) :: x0 +REAL*8, intent(in) :: x1 +REAL*8, intent(in) :: x10 +REAL*8, intent(in) :: x11 +REAL*8, intent(in) :: x12 +REAL*8, intent(in) :: x13 +REAL*8, intent(in) :: x14 +REAL*8, intent(in) :: x15 +REAL*8, intent(in) :: x16 +REAL*8, intent(in) :: x17 +REAL*8, intent(in) :: x18 +REAL*8, intent(in) :: x19 +REAL*8, intent(in) :: x2 +REAL*8, intent(in) :: x3 +REAL*8, intent(in) :: x4 +REAL*8, intent(in) :: x5 +REAL*8, intent(in) :: x6 +REAL*8, intent(in) :: x7 +REAL*8, intent(in) :: x8 +REAL*8, intent(in) :: x9 +test = x0 + x1 + x10 + x11 + x12 + x13 + x14 + x15 + x16 + x17 + x18 + & + x19 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 +end function +""" + assert source == expected + + +def test_check_case(): + x, X = symbols('x,X') + raises(CodeGenError, lambda: codegen(('test', x*X), 'f95', 'prefix')) + + +def test_check_case_false_positive(): + # The upper case/lower case exception should not be triggered by SymPy + # objects that differ only because of assumptions. (It may be useful to + # have a check for that as well, but here we only want to test against + # false positives with respect to case checking.) + x1 = symbols('x') + x2 = symbols('x', my_assumption=True) + try: + codegen(('test', x1*x2), 'f95', 'prefix') + except CodeGenError as e: + if e.args[0].startswith("Fortran ignores case."): + raise AssertionError("This exception should not be raised!") + + +def test_c_fortran_omit_routine_name(): + x, y = symbols("x,y") + name_expr = [("foo", 2*x)] + result = codegen(name_expr, "F95", header=False, empty=False) + expresult = codegen(name_expr, "F95", "foo", header=False, empty=False) + assert result[0][1] == expresult[0][1] + + name_expr = ("foo", x*y) + result = codegen(name_expr, "F95", header=False, empty=False) + expresult = codegen(name_expr, "F95", "foo", header=False, empty=False) + assert result[0][1] == expresult[0][1] + + name_expr = ("foo", Matrix([[x, y], [x+y, x-y]])) + result = codegen(name_expr, "C89", header=False, empty=False) + expresult = codegen(name_expr, "C89", "foo", header=False, empty=False) + assert result[0][1] == expresult[0][1] + + +def test_fcode_matrix_output(): + x, y, z = symbols('x,y,z') + e1 = x + y + e2 = Matrix([[x, y], [z, 16]]) + name_expr = ("test", (e1, e2)) + result = codegen(name_expr, "f95", "test", header=False, empty=False) + source = result[0][1] + expected = ( + "REAL*8 function test(x, y, z, out_%(hash)s)\n" + "implicit none\n" + "REAL*8, intent(in) :: x\n" + "REAL*8, intent(in) :: y\n" + "REAL*8, intent(in) :: z\n" + "REAL*8, intent(out), dimension(1:2, 1:2) :: out_%(hash)s\n" + "out_%(hash)s(1, 1) = x\n" + "out_%(hash)s(2, 1) = z\n" + "out_%(hash)s(1, 2) = y\n" + "out_%(hash)s(2, 2) = 16\n" + "test = x + y\n" + "end function\n" + ) + # look for the magic number + a = source.splitlines()[5] + b = a.split('_') + out = b[1] + expected = expected % {'hash': out} + assert source == expected + + +def test_fcode_results_named_ordered(): + x, y, z = symbols('x,y,z') + B, C = symbols('B,C') + A = MatrixSymbol('A', 1, 3) + expr1 = Equality(A, Matrix([[1, 2, x]])) + expr2 = Equality(C, (x + y)*z) + expr3 = Equality(B, 2*x) + name_expr = ("test", [expr1, expr2, expr3]) + result = codegen(name_expr, "f95", "test", header=False, empty=False, + argument_sequence=(x, z, y, C, A, B)) + source = result[0][1] + expected = ( + "subroutine test(x, z, y, C, A, B)\n" + "implicit none\n" + "REAL*8, intent(in) :: x\n" + "REAL*8, intent(in) :: z\n" + "REAL*8, intent(in) :: y\n" + "REAL*8, intent(out) :: C\n" + "REAL*8, intent(out) :: B\n" + "REAL*8, intent(out), dimension(1:1, 1:3) :: A\n" + "C = z*(x + y)\n" + "A(1, 1) = 1\n" + "A(1, 2) = 2\n" + "A(1, 3) = x\n" + "B = 2*x\n" + "end subroutine\n" + ) + assert source == expected + + +def test_fcode_matrixsymbol_slice(): + A = MatrixSymbol('A', 2, 3) + B = MatrixSymbol('B', 1, 3) + C = MatrixSymbol('C', 1, 3) + D = MatrixSymbol('D', 2, 1) + name_expr = ("test", [Equality(B, A[0, :]), + Equality(C, A[1, :]), + Equality(D, A[:, 2])]) + result = codegen(name_expr, "f95", "test", header=False, empty=False) + source = result[0][1] + expected = ( + "subroutine test(A, B, C, D)\n" + "implicit none\n" + "REAL*8, intent(in), dimension(1:2, 1:3) :: A\n" + "REAL*8, intent(out), dimension(1:1, 1:3) :: B\n" + "REAL*8, intent(out), dimension(1:1, 1:3) :: C\n" + "REAL*8, intent(out), dimension(1:2, 1:1) :: D\n" + "B(1, 1) = A(1, 1)\n" + "B(1, 2) = A(1, 2)\n" + "B(1, 3) = A(1, 3)\n" + "C(1, 1) = A(2, 1)\n" + "C(1, 2) = A(2, 2)\n" + "C(1, 3) = A(2, 3)\n" + "D(1, 1) = A(1, 3)\n" + "D(2, 1) = A(2, 3)\n" + "end subroutine\n" + ) + assert source == expected + + +def test_fcode_matrixsymbol_slice_autoname(): + # see issue #8093 + A = MatrixSymbol('A', 2, 3) + name_expr = ("test", A[:, 1]) + result = codegen(name_expr, "f95", "test", header=False, empty=False) + source = result[0][1] + expected = ( + "subroutine test(A, out_%(hash)s)\n" + "implicit none\n" + "REAL*8, intent(in), dimension(1:2, 1:3) :: A\n" + "REAL*8, intent(out), dimension(1:2, 1:1) :: out_%(hash)s\n" + "out_%(hash)s(1, 1) = A(1, 2)\n" + "out_%(hash)s(2, 1) = A(2, 2)\n" + "end subroutine\n" + ) + # look for the magic number + a = source.splitlines()[3] + b = a.split('_') + out = b[1] + expected = expected % {'hash': out} + assert source == expected + + +def test_global_vars(): + x, y, z, t = symbols("x y z t") + result = codegen(('f', x*y), "F95", header=False, empty=False, + global_vars=(y,)) + source = result[0][1] + expected = ( + "REAL*8 function f(x)\n" + "implicit none\n" + "REAL*8, intent(in) :: x\n" + "f = x*y\n" + "end function\n" + ) + assert source == expected + + expected = ( + '#include "f.h"\n' + '#include \n' + 'double f(double x, double y) {\n' + ' double f_result;\n' + ' f_result = x*y + z;\n' + ' return f_result;\n' + '}\n' + ) + result = codegen(('f', x*y+z), "C", header=False, empty=False, + global_vars=(z, t)) + source = result[0][1] + assert source == expected + +def test_custom_codegen(): + from sympy.printing.c import C99CodePrinter + from sympy.functions.elementary.exponential import exp + + printer = C99CodePrinter(settings={'user_functions': {'exp': 'fastexp'}}) + + x, y = symbols('x y') + expr = exp(x + y) + + # replace math.h with a different header + gen = C99CodeGen(printer=printer, + preprocessor_statements=['#include "fastexp.h"']) + + expected = ( + '#include "expr.h"\n' + '#include "fastexp.h"\n' + 'double expr(double x, double y) {\n' + ' double expr_result;\n' + ' expr_result = fastexp(x + y);\n' + ' return expr_result;\n' + '}\n' + ) + + result = codegen(('expr', expr), header=False, empty=False, code_gen=gen) + source = result[0][1] + assert source == expected + + # use both math.h and an external header + gen = C99CodeGen(printer=printer) + gen.preprocessor_statements.append('#include "fastexp.h"') + + expected = ( + '#include "expr.h"\n' + '#include \n' + '#include "fastexp.h"\n' + 'double expr(double x, double y) {\n' + ' double expr_result;\n' + ' expr_result = fastexp(x + y);\n' + ' return expr_result;\n' + '}\n' + ) + + result = codegen(('expr', expr), header=False, empty=False, code_gen=gen) + source = result[0][1] + assert source == expected + +def test_c_with_printer(): + # issue 13586 + from sympy.printing.c import C99CodePrinter + class CustomPrinter(C99CodePrinter): + def _print_Pow(self, expr): + return "fastpow({}, {})".format(self._print(expr.base), + self._print(expr.exp)) + + x = symbols('x') + expr = x**3 + expected =[ + ("file.c", + "#include \"file.h\"\n" + "#include \n" + "double test(double x) {\n" + " double test_result;\n" + " test_result = fastpow(x, 3);\n" + " return test_result;\n" + "}\n"), + ("file.h", + "#ifndef PROJECT__FILE__H\n" + "#define PROJECT__FILE__H\n" + "double test(double x);\n" + "#endif\n") + ] + result = codegen(("test", expr), "C","file", header=False, empty=False, printer = CustomPrinter()) + assert result == expected + + +def test_fcode_complex(): + import sympy.utilities.codegen + sympy.utilities.codegen.COMPLEX_ALLOWED = True + x = Symbol('x', real=True) + y = Symbol('y',real=True) + result = codegen(('test',x+y), 'f95', 'test', header=False, empty=False) + source = (result[0][1]) + expected = ( + "REAL*8 function test(x, y)\n" + "implicit none\n" + "REAL*8, intent(in) :: x\n" + "REAL*8, intent(in) :: y\n" + "test = x + y\n" + "end function\n") + assert source == expected + x = Symbol('x') + y = Symbol('y',real=True) + result = codegen(('test',x+y), 'f95', 'test', header=False, empty=False) + source = (result[0][1]) + expected = ( + "COMPLEX*16 function test(x, y)\n" + "implicit none\n" + "COMPLEX*16, intent(in) :: x\n" + "REAL*8, intent(in) :: y\n" + "test = x + y\n" + "end function\n" + ) + assert source==expected + sympy.utilities.codegen.COMPLEX_ALLOWED = False diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_codegen_julia.py b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_codegen_julia.py new file mode 100644 index 0000000000000000000000000000000000000000..12841cb7d476107e3866d91b998bed1f997f3901 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_codegen_julia.py @@ -0,0 +1,620 @@ +from io import StringIO + +from sympy.core import S, symbols, Eq, pi, Catalan, EulerGamma, Function +from sympy.core.relational import Equality +from sympy.functions.elementary.piecewise import Piecewise +from sympy.matrices import Matrix, MatrixSymbol +from sympy.utilities.codegen import JuliaCodeGen, codegen, make_routine +from sympy.testing.pytest import XFAIL +import sympy + + +x, y, z = symbols('x,y,z') + + +def test_empty_jl_code(): + code_gen = JuliaCodeGen() + output = StringIO() + code_gen.dump_jl([], output, "file", header=False, empty=False) + source = output.getvalue() + assert source == "" + + +def test_jl_simple_code(): + name_expr = ("test", (x + y)*z) + result, = codegen(name_expr, "Julia", header=False, empty=False) + assert result[0] == "test.jl" + source = result[1] + expected = ( + "function test(x, y, z)\n" + " out1 = z .* (x + y)\n" + " return out1\n" + "end\n" + ) + assert source == expected + + +def test_jl_simple_code_with_header(): + name_expr = ("test", (x + y)*z) + result, = codegen(name_expr, "Julia", header=True, empty=False) + assert result[0] == "test.jl" + source = result[1] + expected = ( + "# Code generated with SymPy " + sympy.__version__ + "\n" + "#\n" + "# See http://www.sympy.org/ for more information.\n" + "#\n" + "# This file is part of 'project'\n" + "function test(x, y, z)\n" + " out1 = z .* (x + y)\n" + " return out1\n" + "end\n" + ) + assert source == expected + + +def test_jl_simple_code_nameout(): + expr = Equality(z, (x + y)) + name_expr = ("test", expr) + result, = codegen(name_expr, "Julia", header=False, empty=False) + source = result[1] + expected = ( + "function test(x, y)\n" + " z = x + y\n" + " return z\n" + "end\n" + ) + assert source == expected + + +def test_jl_numbersymbol(): + name_expr = ("test", pi**Catalan) + result, = codegen(name_expr, "Julia", header=False, empty=False) + source = result[1] + expected = ( + "function test()\n" + " out1 = pi ^ catalan\n" + " return out1\n" + "end\n" + ) + assert source == expected + + +@XFAIL +def test_jl_numbersymbol_no_inline(): + # FIXME: how to pass inline=False to the JuliaCodePrinter? + name_expr = ("test", [pi**Catalan, EulerGamma]) + result, = codegen(name_expr, "Julia", header=False, + empty=False, inline=False) + source = result[1] + expected = ( + "function test()\n" + " Catalan = 0.915965594177219\n" + " EulerGamma = 0.5772156649015329\n" + " out1 = pi ^ Catalan\n" + " out2 = EulerGamma\n" + " return out1, out2\n" + "end\n" + ) + assert source == expected + + +def test_jl_code_argument_order(): + expr = x + y + routine = make_routine("test", expr, argument_sequence=[z, x, y], language="julia") + code_gen = JuliaCodeGen() + output = StringIO() + code_gen.dump_jl([routine], output, "test", header=False, empty=False) + source = output.getvalue() + expected = ( + "function test(z, x, y)\n" + " out1 = x + y\n" + " return out1\n" + "end\n" + ) + assert source == expected + + +def test_multiple_results_m(): + # Here the output order is the input order + expr1 = (x + y)*z + expr2 = (x - y)*z + name_expr = ("test", [expr1, expr2]) + result, = codegen(name_expr, "Julia", header=False, empty=False) + source = result[1] + expected = ( + "function test(x, y, z)\n" + " out1 = z .* (x + y)\n" + " out2 = z .* (x - y)\n" + " return out1, out2\n" + "end\n" + ) + assert source == expected + + +def test_results_named_unordered(): + # Here output order is based on name_expr + A, B, C = symbols('A,B,C') + expr1 = Equality(C, (x + y)*z) + expr2 = Equality(A, (x - y)*z) + expr3 = Equality(B, 2*x) + name_expr = ("test", [expr1, expr2, expr3]) + result, = codegen(name_expr, "Julia", header=False, empty=False) + source = result[1] + expected = ( + "function test(x, y, z)\n" + " C = z .* (x + y)\n" + " A = z .* (x - y)\n" + " B = 2 * x\n" + " return C, A, B\n" + "end\n" + ) + assert source == expected + + +def test_results_named_ordered(): + A, B, C = symbols('A,B,C') + expr1 = Equality(C, (x + y)*z) + expr2 = Equality(A, (x - y)*z) + expr3 = Equality(B, 2*x) + name_expr = ("test", [expr1, expr2, expr3]) + result = codegen(name_expr, "Julia", header=False, empty=False, + argument_sequence=(x, z, y)) + assert result[0][0] == "test.jl" + source = result[0][1] + expected = ( + "function test(x, z, y)\n" + " C = z .* (x + y)\n" + " A = z .* (x - y)\n" + " B = 2 * x\n" + " return C, A, B\n" + "end\n" + ) + assert source == expected + + +def test_complicated_jl_codegen(): + from sympy.functions.elementary.trigonometric import (cos, sin, tan) + name_expr = ("testlong", + [ ((sin(x) + cos(y) + tan(z))**3).expand(), + cos(cos(cos(cos(cos(cos(cos(cos(x + y + z)))))))) + ]) + result = codegen(name_expr, "Julia", header=False, empty=False) + assert result[0][0] == "testlong.jl" + source = result[0][1] + expected = ( + "function testlong(x, y, z)\n" + " out1 = sin(x) .^ 3 + 3 * sin(x) .^ 2 .* cos(y) + 3 * sin(x) .^ 2 .* tan(z)" + " + 3 * sin(x) .* cos(y) .^ 2 + 6 * sin(x) .* cos(y) .* tan(z) + 3 * sin(x) .* tan(z) .^ 2" + " + cos(y) .^ 3 + 3 * cos(y) .^ 2 .* tan(z) + 3 * cos(y) .* tan(z) .^ 2 + tan(z) .^ 3\n" + " out2 = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))\n" + " return out1, out2\n" + "end\n" + ) + assert source == expected + + +def test_jl_output_arg_mixed_unordered(): + # named outputs are alphabetical, unnamed output appear in the given order + from sympy.functions.elementary.trigonometric import (cos, sin) + a = symbols("a") + name_expr = ("foo", [cos(2*x), Equality(y, sin(x)), cos(x), Equality(a, sin(2*x))]) + result, = codegen(name_expr, "Julia", header=False, empty=False) + assert result[0] == "foo.jl" + source = result[1] + expected = ( + 'function foo(x)\n' + ' out1 = cos(2 * x)\n' + ' y = sin(x)\n' + ' out3 = cos(x)\n' + ' a = sin(2 * x)\n' + ' return out1, y, out3, a\n' + 'end\n' + ) + assert source == expected + + +def test_jl_piecewise_(): + pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True), evaluate=False) + name_expr = ("pwtest", pw) + result, = codegen(name_expr, "Julia", header=False, empty=False) + source = result[1] + expected = ( + "function pwtest(x)\n" + " out1 = ((x < -1) ? (0) :\n" + " (x <= 1) ? (x .^ 2) :\n" + " (x > 1) ? (2 - x) : (1))\n" + " return out1\n" + "end\n" + ) + assert source == expected + + +@XFAIL +def test_jl_piecewise_no_inline(): + # FIXME: how to pass inline=False to the JuliaCodePrinter? + pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True)) + name_expr = ("pwtest", pw) + result, = codegen(name_expr, "Julia", header=False, empty=False, + inline=False) + source = result[1] + expected = ( + "function pwtest(x)\n" + " if (x < -1)\n" + " out1 = 0\n" + " elseif (x <= 1)\n" + " out1 = x .^ 2\n" + " elseif (x > 1)\n" + " out1 = -x + 2\n" + " else\n" + " out1 = 1\n" + " end\n" + " return out1\n" + "end\n" + ) + assert source == expected + + +def test_jl_multifcns_per_file(): + name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] + result = codegen(name_expr, "Julia", header=False, empty=False) + assert result[0][0] == "foo.jl" + source = result[0][1] + expected = ( + "function foo(x, y)\n" + " out1 = 2 * x\n" + " out2 = 3 * y\n" + " return out1, out2\n" + "end\n" + "function bar(y)\n" + " out1 = y .^ 2\n" + " out2 = 4 * y\n" + " return out1, out2\n" + "end\n" + ) + assert source == expected + + +def test_jl_multifcns_per_file_w_header(): + name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] + result = codegen(name_expr, "Julia", header=True, empty=False) + assert result[0][0] == "foo.jl" + source = result[0][1] + expected = ( + "# Code generated with SymPy " + sympy.__version__ + "\n" + "#\n" + "# See http://www.sympy.org/ for more information.\n" + "#\n" + "# This file is part of 'project'\n" + "function foo(x, y)\n" + " out1 = 2 * x\n" + " out2 = 3 * y\n" + " return out1, out2\n" + "end\n" + "function bar(y)\n" + " out1 = y .^ 2\n" + " out2 = 4 * y\n" + " return out1, out2\n" + "end\n" + ) + assert source == expected + + +def test_jl_filename_match_prefix(): + name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] + result, = codegen(name_expr, "Julia", prefix="baz", header=False, + empty=False) + assert result[0] == "baz.jl" + + +def test_jl_matrix_named(): + e2 = Matrix([[x, 2*y, pi*z]]) + name_expr = ("test", Equality(MatrixSymbol('myout1', 1, 3), e2)) + result = codegen(name_expr, "Julia", header=False, empty=False) + assert result[0][0] == "test.jl" + source = result[0][1] + expected = ( + "function test(x, y, z)\n" + " myout1 = [x 2 * y pi * z]\n" + " return myout1\n" + "end\n" + ) + assert source == expected + + +def test_jl_matrix_named_matsym(): + myout1 = MatrixSymbol('myout1', 1, 3) + e2 = Matrix([[x, 2*y, pi*z]]) + name_expr = ("test", Equality(myout1, e2, evaluate=False)) + result, = codegen(name_expr, "Julia", header=False, empty=False) + source = result[1] + expected = ( + "function test(x, y, z)\n" + " myout1 = [x 2 * y pi * z]\n" + " return myout1\n" + "end\n" + ) + assert source == expected + + +def test_jl_matrix_output_autoname(): + expr = Matrix([[x, x+y, 3]]) + name_expr = ("test", expr) + result, = codegen(name_expr, "Julia", header=False, empty=False) + source = result[1] + expected = ( + "function test(x, y)\n" + " out1 = [x x + y 3]\n" + " return out1\n" + "end\n" + ) + assert source == expected + + +def test_jl_matrix_output_autoname_2(): + e1 = (x + y) + e2 = Matrix([[2*x, 2*y, 2*z]]) + e3 = Matrix([[x], [y], [z]]) + e4 = Matrix([[x, y], [z, 16]]) + name_expr = ("test", (e1, e2, e3, e4)) + result, = codegen(name_expr, "Julia", header=False, empty=False) + source = result[1] + expected = ( + "function test(x, y, z)\n" + " out1 = x + y\n" + " out2 = [2 * x 2 * y 2 * z]\n" + " out3 = [x, y, z]\n" + " out4 = [x y;\n" + " z 16]\n" + " return out1, out2, out3, out4\n" + "end\n" + ) + assert source == expected + + +def test_jl_results_matrix_named_ordered(): + B, C = symbols('B,C') + A = MatrixSymbol('A', 1, 3) + expr1 = Equality(C, (x + y)*z) + expr2 = Equality(A, Matrix([[1, 2, x]])) + expr3 = Equality(B, 2*x) + name_expr = ("test", [expr1, expr2, expr3]) + result, = codegen(name_expr, "Julia", header=False, empty=False, + argument_sequence=(x, z, y)) + source = result[1] + expected = ( + "function test(x, z, y)\n" + " C = z .* (x + y)\n" + " A = [1 2 x]\n" + " B = 2 * x\n" + " return C, A, B\n" + "end\n" + ) + assert source == expected + + +def test_jl_matrixsymbol_slice(): + A = MatrixSymbol('A', 2, 3) + B = MatrixSymbol('B', 1, 3) + C = MatrixSymbol('C', 1, 3) + D = MatrixSymbol('D', 2, 1) + name_expr = ("test", [Equality(B, A[0, :]), + Equality(C, A[1, :]), + Equality(D, A[:, 2])]) + result, = codegen(name_expr, "Julia", header=False, empty=False) + source = result[1] + expected = ( + "function test(A)\n" + " B = A[1,:]\n" + " C = A[2,:]\n" + " D = A[:,3]\n" + " return B, C, D\n" + "end\n" + ) + assert source == expected + + +def test_jl_matrixsymbol_slice2(): + A = MatrixSymbol('A', 3, 4) + B = MatrixSymbol('B', 2, 2) + C = MatrixSymbol('C', 2, 2) + name_expr = ("test", [Equality(B, A[0:2, 0:2]), + Equality(C, A[0:2, 1:3])]) + result, = codegen(name_expr, "Julia", header=False, empty=False) + source = result[1] + expected = ( + "function test(A)\n" + " B = A[1:2,1:2]\n" + " C = A[1:2,2:3]\n" + " return B, C\n" + "end\n" + ) + assert source == expected + + +def test_jl_matrixsymbol_slice3(): + A = MatrixSymbol('A', 8, 7) + B = MatrixSymbol('B', 2, 2) + C = MatrixSymbol('C', 4, 2) + name_expr = ("test", [Equality(B, A[6:, 1::3]), + Equality(C, A[::2, ::3])]) + result, = codegen(name_expr, "Julia", header=False, empty=False) + source = result[1] + expected = ( + "function test(A)\n" + " B = A[7:end,2:3:end]\n" + " C = A[1:2:end,1:3:end]\n" + " return B, C\n" + "end\n" + ) + assert source == expected + + +def test_jl_matrixsymbol_slice_autoname(): + A = MatrixSymbol('A', 2, 3) + B = MatrixSymbol('B', 1, 3) + name_expr = ("test", [Equality(B, A[0,:]), A[1,:], A[:,0], A[:,1]]) + result, = codegen(name_expr, "Julia", header=False, empty=False) + source = result[1] + expected = ( + "function test(A)\n" + " B = A[1,:]\n" + " out2 = A[2,:]\n" + " out3 = A[:,1]\n" + " out4 = A[:,2]\n" + " return B, out2, out3, out4\n" + "end\n" + ) + assert source == expected + + +def test_jl_loops(): + # Note: an Julia programmer would probably vectorize this across one or + # more dimensions. Also, size(A) would be used rather than passing in m + # and n. Perhaps users would expect us to vectorize automatically here? + # Or is it possible to represent such things using IndexedBase? + from sympy.tensor import IndexedBase, Idx + from sympy.core.symbol import symbols + n, m = symbols('n m', integer=True) + A = IndexedBase('A') + x = IndexedBase('x') + y = IndexedBase('y') + i = Idx('i', m) + j = Idx('j', n) + result, = codegen(('mat_vec_mult', Eq(y[i], A[i, j]*x[j])), "Julia", + header=False, empty=False) + source = result[1] + expected = ( + 'function mat_vec_mult(y, A, m, n, x)\n' + ' for i = 1:m\n' + ' y[i] = 0\n' + ' end\n' + ' for i = 1:m\n' + ' for j = 1:n\n' + ' y[i] = %(rhs)s + y[i]\n' + ' end\n' + ' end\n' + ' return y\n' + 'end\n' + ) + assert (source == expected % {'rhs': 'A[%s,%s] .* x[j]' % (i, j)} or + source == expected % {'rhs': 'x[j] .* A[%s,%s]' % (i, j)}) + + +def test_jl_tensor_loops_multiple_contractions(): + # see comments in previous test about vectorizing + from sympy.tensor import IndexedBase, Idx + from sympy.core.symbol import symbols + n, m, o, p = symbols('n m o p', integer=True) + A = IndexedBase('A') + B = IndexedBase('B') + y = IndexedBase('y') + i = Idx('i', m) + j = Idx('j', n) + k = Idx('k', o) + l = Idx('l', p) + result, = codegen(('tensorthing', Eq(y[i], B[j, k, l]*A[i, j, k, l])), + "Julia", header=False, empty=False) + source = result[1] + expected = ( + 'function tensorthing(y, A, B, m, n, o, p)\n' + ' for i = 1:m\n' + ' y[i] = 0\n' + ' end\n' + ' for i = 1:m\n' + ' for j = 1:n\n' + ' for k = 1:o\n' + ' for l = 1:p\n' + ' y[i] = A[i,j,k,l] .* B[j,k,l] + y[i]\n' + ' end\n' + ' end\n' + ' end\n' + ' end\n' + ' return y\n' + 'end\n' + ) + assert source == expected + + +def test_jl_InOutArgument(): + expr = Equality(x, x**2) + name_expr = ("mysqr", expr) + result, = codegen(name_expr, "Julia", header=False, empty=False) + source = result[1] + expected = ( + "function mysqr(x)\n" + " x = x .^ 2\n" + " return x\n" + "end\n" + ) + assert source == expected + + +def test_jl_InOutArgument_order(): + # can specify the order as (x, y) + expr = Equality(x, x**2 + y) + name_expr = ("test", expr) + result, = codegen(name_expr, "Julia", header=False, + empty=False, argument_sequence=(x,y)) + source = result[1] + expected = ( + "function test(x, y)\n" + " x = x .^ 2 + y\n" + " return x\n" + "end\n" + ) + assert source == expected + # make sure it gives (x, y) not (y, x) + expr = Equality(x, x**2 + y) + name_expr = ("test", expr) + result, = codegen(name_expr, "Julia", header=False, empty=False) + source = result[1] + expected = ( + "function test(x, y)\n" + " x = x .^ 2 + y\n" + " return x\n" + "end\n" + ) + assert source == expected + + +def test_jl_not_supported(): + f = Function('f') + name_expr = ("test", [f(x).diff(x), S.ComplexInfinity]) + result, = codegen(name_expr, "Julia", header=False, empty=False) + source = result[1] + expected = ( + "function test(x)\n" + " # unsupported: Derivative(f(x), x)\n" + " # unsupported: zoo\n" + " out1 = Derivative(f(x), x)\n" + " out2 = zoo\n" + " return out1, out2\n" + "end\n" + ) + assert source == expected + + +def test_global_vars_octave(): + x, y, z, t = symbols("x y z t") + result = codegen(('f', x*y), "Julia", header=False, empty=False, + global_vars=(y,)) + source = result[0][1] + expected = ( + "function f(x)\n" + " out1 = x .* y\n" + " return out1\n" + "end\n" + ) + assert source == expected + + result = codegen(('f', x*y+z), "Julia", header=False, empty=False, + argument_sequence=(x, y), global_vars=(z, t)) + source = result[0][1] + expected = ( + "function f(x, y)\n" + " out1 = x .* y + z\n" + " return out1\n" + "end\n" + ) + assert source == expected diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_codegen_octave.py b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_codegen_octave.py new file mode 100644 index 0000000000000000000000000000000000000000..77aaef7dd0d81d6855024e49fbb3d6d4c09f3384 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_codegen_octave.py @@ -0,0 +1,589 @@ +from io import StringIO + +from sympy.core import S, symbols, Eq, pi, Catalan, EulerGamma, Function +from sympy.core.relational import Equality +from sympy.functions.elementary.piecewise import Piecewise +from sympy.matrices import Matrix, MatrixSymbol +from sympy.utilities.codegen import OctaveCodeGen, codegen, make_routine +from sympy.testing.pytest import raises +from sympy.testing.pytest import XFAIL +import sympy + + +x, y, z = symbols('x,y,z') + + +def test_empty_m_code(): + code_gen = OctaveCodeGen() + output = StringIO() + code_gen.dump_m([], output, "file", header=False, empty=False) + source = output.getvalue() + assert source == "" + + +def test_m_simple_code(): + name_expr = ("test", (x + y)*z) + result, = codegen(name_expr, "Octave", header=False, empty=False) + assert result[0] == "test.m" + source = result[1] + expected = ( + "function out1 = test(x, y, z)\n" + " out1 = z.*(x + y);\n" + "end\n" + ) + assert source == expected + + +def test_m_simple_code_with_header(): + name_expr = ("test", (x + y)*z) + result, = codegen(name_expr, "Octave", header=True, empty=False) + assert result[0] == "test.m" + source = result[1] + expected = ( + "function out1 = test(x, y, z)\n" + " %TEST Autogenerated by SymPy\n" + " % Code generated with SymPy " + sympy.__version__ + "\n" + " %\n" + " % See http://www.sympy.org/ for more information.\n" + " %\n" + " % This file is part of 'project'\n" + " out1 = z.*(x + y);\n" + "end\n" + ) + assert source == expected + + +def test_m_simple_code_nameout(): + expr = Equality(z, (x + y)) + name_expr = ("test", expr) + result, = codegen(name_expr, "Octave", header=False, empty=False) + source = result[1] + expected = ( + "function z = test(x, y)\n" + " z = x + y;\n" + "end\n" + ) + assert source == expected + + +def test_m_numbersymbol(): + name_expr = ("test", pi**Catalan) + result, = codegen(name_expr, "Octave", header=False, empty=False) + source = result[1] + expected = ( + "function out1 = test()\n" + " out1 = pi^%s;\n" + "end\n" + ) % Catalan.evalf(17) + assert source == expected + + +@XFAIL +def test_m_numbersymbol_no_inline(): + # FIXME: how to pass inline=False to the OctaveCodePrinter? + name_expr = ("test", [pi**Catalan, EulerGamma]) + result, = codegen(name_expr, "Octave", header=False, + empty=False, inline=False) + source = result[1] + expected = ( + "function [out1, out2] = test()\n" + " Catalan = 0.915965594177219; % constant\n" + " EulerGamma = 0.5772156649015329; % constant\n" + " out1 = pi^Catalan;\n" + " out2 = EulerGamma;\n" + "end\n" + ) + assert source == expected + + +def test_m_code_argument_order(): + expr = x + y + routine = make_routine("test", expr, argument_sequence=[z, x, y], language="octave") + code_gen = OctaveCodeGen() + output = StringIO() + code_gen.dump_m([routine], output, "test", header=False, empty=False) + source = output.getvalue() + expected = ( + "function out1 = test(z, x, y)\n" + " out1 = x + y;\n" + "end\n" + ) + assert source == expected + + +def test_multiple_results_m(): + # Here the output order is the input order + expr1 = (x + y)*z + expr2 = (x - y)*z + name_expr = ("test", [expr1, expr2]) + result, = codegen(name_expr, "Octave", header=False, empty=False) + source = result[1] + expected = ( + "function [out1, out2] = test(x, y, z)\n" + " out1 = z.*(x + y);\n" + " out2 = z.*(x - y);\n" + "end\n" + ) + assert source == expected + + +def test_results_named_unordered(): + # Here output order is based on name_expr + A, B, C = symbols('A,B,C') + expr1 = Equality(C, (x + y)*z) + expr2 = Equality(A, (x - y)*z) + expr3 = Equality(B, 2*x) + name_expr = ("test", [expr1, expr2, expr3]) + result, = codegen(name_expr, "Octave", header=False, empty=False) + source = result[1] + expected = ( + "function [C, A, B] = test(x, y, z)\n" + " C = z.*(x + y);\n" + " A = z.*(x - y);\n" + " B = 2*x;\n" + "end\n" + ) + assert source == expected + + +def test_results_named_ordered(): + A, B, C = symbols('A,B,C') + expr1 = Equality(C, (x + y)*z) + expr2 = Equality(A, (x - y)*z) + expr3 = Equality(B, 2*x) + name_expr = ("test", [expr1, expr2, expr3]) + result = codegen(name_expr, "Octave", header=False, empty=False, + argument_sequence=(x, z, y)) + assert result[0][0] == "test.m" + source = result[0][1] + expected = ( + "function [C, A, B] = test(x, z, y)\n" + " C = z.*(x + y);\n" + " A = z.*(x - y);\n" + " B = 2*x;\n" + "end\n" + ) + assert source == expected + + +def test_complicated_m_codegen(): + from sympy.functions.elementary.trigonometric import (cos, sin, tan) + name_expr = ("testlong", + [ ((sin(x) + cos(y) + tan(z))**3).expand(), + cos(cos(cos(cos(cos(cos(cos(cos(x + y + z)))))))) + ]) + result = codegen(name_expr, "Octave", header=False, empty=False) + assert result[0][0] == "testlong.m" + source = result[0][1] + expected = ( + "function [out1, out2] = testlong(x, y, z)\n" + " out1 = sin(x).^3 + 3*sin(x).^2.*cos(y) + 3*sin(x).^2.*tan(z)" + " + 3*sin(x).*cos(y).^2 + 6*sin(x).*cos(y).*tan(z) + 3*sin(x).*tan(z).^2" + " + cos(y).^3 + 3*cos(y).^2.*tan(z) + 3*cos(y).*tan(z).^2 + tan(z).^3;\n" + " out2 = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))));\n" + "end\n" + ) + assert source == expected + + +def test_m_output_arg_mixed_unordered(): + # named outputs are alphabetical, unnamed output appear in the given order + from sympy.functions.elementary.trigonometric import (cos, sin) + a = symbols("a") + name_expr = ("foo", [cos(2*x), Equality(y, sin(x)), cos(x), Equality(a, sin(2*x))]) + result, = codegen(name_expr, "Octave", header=False, empty=False) + assert result[0] == "foo.m" + source = result[1] + expected = ( + 'function [out1, y, out3, a] = foo(x)\n' + ' out1 = cos(2*x);\n' + ' y = sin(x);\n' + ' out3 = cos(x);\n' + ' a = sin(2*x);\n' + 'end\n' + ) + assert source == expected + + +def test_m_piecewise_(): + pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True), evaluate=False) + name_expr = ("pwtest", pw) + result, = codegen(name_expr, "Octave", header=False, empty=False) + source = result[1] + expected = ( + "function out1 = pwtest(x)\n" + " out1 = ((x < -1).*(0) + (~(x < -1)).*( ...\n" + " (x <= 1).*(x.^2) + (~(x <= 1)).*( ...\n" + " (x > 1).*(2 - x) + (~(x > 1)).*(1))));\n" + "end\n" + ) + assert source == expected + + +@XFAIL +def test_m_piecewise_no_inline(): + # FIXME: how to pass inline=False to the OctaveCodePrinter? + pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True)) + name_expr = ("pwtest", pw) + result, = codegen(name_expr, "Octave", header=False, empty=False, + inline=False) + source = result[1] + expected = ( + "function out1 = pwtest(x)\n" + " if (x < -1)\n" + " out1 = 0;\n" + " elseif (x <= 1)\n" + " out1 = x.^2;\n" + " elseif (x > 1)\n" + " out1 = -x + 2;\n" + " else\n" + " out1 = 1;\n" + " end\n" + "end\n" + ) + assert source == expected + + +def test_m_multifcns_per_file(): + name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] + result = codegen(name_expr, "Octave", header=False, empty=False) + assert result[0][0] == "foo.m" + source = result[0][1] + expected = ( + "function [out1, out2] = foo(x, y)\n" + " out1 = 2*x;\n" + " out2 = 3*y;\n" + "end\n" + "function [out1, out2] = bar(y)\n" + " out1 = y.^2;\n" + " out2 = 4*y;\n" + "end\n" + ) + assert source == expected + + +def test_m_multifcns_per_file_w_header(): + name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] + result = codegen(name_expr, "Octave", header=True, empty=False) + assert result[0][0] == "foo.m" + source = result[0][1] + expected = ( + "function [out1, out2] = foo(x, y)\n" + " %FOO Autogenerated by SymPy\n" + " % Code generated with SymPy " + sympy.__version__ + "\n" + " %\n" + " % See http://www.sympy.org/ for more information.\n" + " %\n" + " % This file is part of 'project'\n" + " out1 = 2*x;\n" + " out2 = 3*y;\n" + "end\n" + "function [out1, out2] = bar(y)\n" + " out1 = y.^2;\n" + " out2 = 4*y;\n" + "end\n" + ) + assert source == expected + + +def test_m_filename_match_first_fcn(): + name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] + raises(ValueError, lambda: codegen(name_expr, + "Octave", prefix="bar", header=False, empty=False)) + + +def test_m_matrix_named(): + e2 = Matrix([[x, 2*y, pi*z]]) + name_expr = ("test", Equality(MatrixSymbol('myout1', 1, 3), e2)) + result = codegen(name_expr, "Octave", header=False, empty=False) + assert result[0][0] == "test.m" + source = result[0][1] + expected = ( + "function myout1 = test(x, y, z)\n" + " myout1 = [x 2*y pi*z];\n" + "end\n" + ) + assert source == expected + + +def test_m_matrix_named_matsym(): + myout1 = MatrixSymbol('myout1', 1, 3) + e2 = Matrix([[x, 2*y, pi*z]]) + name_expr = ("test", Equality(myout1, e2, evaluate=False)) + result, = codegen(name_expr, "Octave", header=False, empty=False) + source = result[1] + expected = ( + "function myout1 = test(x, y, z)\n" + " myout1 = [x 2*y pi*z];\n" + "end\n" + ) + assert source == expected + + +def test_m_matrix_output_autoname(): + expr = Matrix([[x, x+y, 3]]) + name_expr = ("test", expr) + result, = codegen(name_expr, "Octave", header=False, empty=False) + source = result[1] + expected = ( + "function out1 = test(x, y)\n" + " out1 = [x x + y 3];\n" + "end\n" + ) + assert source == expected + + +def test_m_matrix_output_autoname_2(): + e1 = (x + y) + e2 = Matrix([[2*x, 2*y, 2*z]]) + e3 = Matrix([[x], [y], [z]]) + e4 = Matrix([[x, y], [z, 16]]) + name_expr = ("test", (e1, e2, e3, e4)) + result, = codegen(name_expr, "Octave", header=False, empty=False) + source = result[1] + expected = ( + "function [out1, out2, out3, out4] = test(x, y, z)\n" + " out1 = x + y;\n" + " out2 = [2*x 2*y 2*z];\n" + " out3 = [x; y; z];\n" + " out4 = [x y; z 16];\n" + "end\n" + ) + assert source == expected + + +def test_m_results_matrix_named_ordered(): + B, C = symbols('B,C') + A = MatrixSymbol('A', 1, 3) + expr1 = Equality(C, (x + y)*z) + expr2 = Equality(A, Matrix([[1, 2, x]])) + expr3 = Equality(B, 2*x) + name_expr = ("test", [expr1, expr2, expr3]) + result, = codegen(name_expr, "Octave", header=False, empty=False, + argument_sequence=(x, z, y)) + source = result[1] + expected = ( + "function [C, A, B] = test(x, z, y)\n" + " C = z.*(x + y);\n" + " A = [1 2 x];\n" + " B = 2*x;\n" + "end\n" + ) + assert source == expected + + +def test_m_matrixsymbol_slice(): + A = MatrixSymbol('A', 2, 3) + B = MatrixSymbol('B', 1, 3) + C = MatrixSymbol('C', 1, 3) + D = MatrixSymbol('D', 2, 1) + name_expr = ("test", [Equality(B, A[0, :]), + Equality(C, A[1, :]), + Equality(D, A[:, 2])]) + result, = codegen(name_expr, "Octave", header=False, empty=False) + source = result[1] + expected = ( + "function [B, C, D] = test(A)\n" + " B = A(1, :);\n" + " C = A(2, :);\n" + " D = A(:, 3);\n" + "end\n" + ) + assert source == expected + + +def test_m_matrixsymbol_slice2(): + A = MatrixSymbol('A', 3, 4) + B = MatrixSymbol('B', 2, 2) + C = MatrixSymbol('C', 2, 2) + name_expr = ("test", [Equality(B, A[0:2, 0:2]), + Equality(C, A[0:2, 1:3])]) + result, = codegen(name_expr, "Octave", header=False, empty=False) + source = result[1] + expected = ( + "function [B, C] = test(A)\n" + " B = A(1:2, 1:2);\n" + " C = A(1:2, 2:3);\n" + "end\n" + ) + assert source == expected + + +def test_m_matrixsymbol_slice3(): + A = MatrixSymbol('A', 8, 7) + B = MatrixSymbol('B', 2, 2) + C = MatrixSymbol('C', 4, 2) + name_expr = ("test", [Equality(B, A[6:, 1::3]), + Equality(C, A[::2, ::3])]) + result, = codegen(name_expr, "Octave", header=False, empty=False) + source = result[1] + expected = ( + "function [B, C] = test(A)\n" + " B = A(7:end, 2:3:end);\n" + " C = A(1:2:end, 1:3:end);\n" + "end\n" + ) + assert source == expected + + +def test_m_matrixsymbol_slice_autoname(): + A = MatrixSymbol('A', 2, 3) + B = MatrixSymbol('B', 1, 3) + name_expr = ("test", [Equality(B, A[0,:]), A[1,:], A[:,0], A[:,1]]) + result, = codegen(name_expr, "Octave", header=False, empty=False) + source = result[1] + expected = ( + "function [B, out2, out3, out4] = test(A)\n" + " B = A(1, :);\n" + " out2 = A(2, :);\n" + " out3 = A(:, 1);\n" + " out4 = A(:, 2);\n" + "end\n" + ) + assert source == expected + + +def test_m_loops(): + # Note: an Octave programmer would probably vectorize this across one or + # more dimensions. Also, size(A) would be used rather than passing in m + # and n. Perhaps users would expect us to vectorize automatically here? + # Or is it possible to represent such things using IndexedBase? + from sympy.tensor import IndexedBase, Idx + from sympy.core.symbol import symbols + n, m = symbols('n m', integer=True) + A = IndexedBase('A') + x = IndexedBase('x') + y = IndexedBase('y') + i = Idx('i', m) + j = Idx('j', n) + result, = codegen(('mat_vec_mult', Eq(y[i], A[i, j]*x[j])), "Octave", + header=False, empty=False) + source = result[1] + expected = ( + 'function y = mat_vec_mult(A, m, n, x)\n' + ' for i = 1:m\n' + ' y(i) = 0;\n' + ' end\n' + ' for i = 1:m\n' + ' for j = 1:n\n' + ' y(i) = %(rhs)s + y(i);\n' + ' end\n' + ' end\n' + 'end\n' + ) + assert (source == expected % {'rhs': 'A(%s, %s).*x(j)' % (i, j)} or + source == expected % {'rhs': 'x(j).*A(%s, %s)' % (i, j)}) + + +def test_m_tensor_loops_multiple_contractions(): + # see comments in previous test about vectorizing + from sympy.tensor import IndexedBase, Idx + from sympy.core.symbol import symbols + n, m, o, p = symbols('n m o p', integer=True) + A = IndexedBase('A') + B = IndexedBase('B') + y = IndexedBase('y') + i = Idx('i', m) + j = Idx('j', n) + k = Idx('k', o) + l = Idx('l', p) + result, = codegen(('tensorthing', Eq(y[i], B[j, k, l]*A[i, j, k, l])), + "Octave", header=False, empty=False) + source = result[1] + expected = ( + 'function y = tensorthing(A, B, m, n, o, p)\n' + ' for i = 1:m\n' + ' y(i) = 0;\n' + ' end\n' + ' for i = 1:m\n' + ' for j = 1:n\n' + ' for k = 1:o\n' + ' for l = 1:p\n' + ' y(i) = A(i, j, k, l).*B(j, k, l) + y(i);\n' + ' end\n' + ' end\n' + ' end\n' + ' end\n' + 'end\n' + ) + assert source == expected + + +def test_m_InOutArgument(): + expr = Equality(x, x**2) + name_expr = ("mysqr", expr) + result, = codegen(name_expr, "Octave", header=False, empty=False) + source = result[1] + expected = ( + "function x = mysqr(x)\n" + " x = x.^2;\n" + "end\n" + ) + assert source == expected + + +def test_m_InOutArgument_order(): + # can specify the order as (x, y) + expr = Equality(x, x**2 + y) + name_expr = ("test", expr) + result, = codegen(name_expr, "Octave", header=False, + empty=False, argument_sequence=(x,y)) + source = result[1] + expected = ( + "function x = test(x, y)\n" + " x = x.^2 + y;\n" + "end\n" + ) + assert source == expected + # make sure it gives (x, y) not (y, x) + expr = Equality(x, x**2 + y) + name_expr = ("test", expr) + result, = codegen(name_expr, "Octave", header=False, empty=False) + source = result[1] + expected = ( + "function x = test(x, y)\n" + " x = x.^2 + y;\n" + "end\n" + ) + assert source == expected + + +def test_m_not_supported(): + f = Function('f') + name_expr = ("test", [f(x).diff(x), S.ComplexInfinity]) + result, = codegen(name_expr, "Octave", header=False, empty=False) + source = result[1] + expected = ( + "function [out1, out2] = test(x)\n" + " % unsupported: Derivative(f(x), x)\n" + " % unsupported: zoo\n" + " out1 = Derivative(f(x), x);\n" + " out2 = zoo;\n" + "end\n" + ) + assert source == expected + + +def test_global_vars_octave(): + x, y, z, t = symbols("x y z t") + result = codegen(('f', x*y), "Octave", header=False, empty=False, + global_vars=(y,)) + source = result[0][1] + expected = ( + "function out1 = f(x)\n" + " global y\n" + " out1 = x.*y;\n" + "end\n" + ) + assert source == expected + + result = codegen(('f', x*y+z), "Octave", header=False, empty=False, + argument_sequence=(x, y), global_vars=(z, t)) + source = result[0][1] + expected = ( + "function out1 = f(x, y)\n" + " global t z\n" + " out1 = x.*y + z;\n" + "end\n" + ) + assert source == expected diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_codegen_rust.py b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_codegen_rust.py new file mode 100644 index 0000000000000000000000000000000000000000..bc7f82158ae8fa7dfe34bf909aa695b119fb9526 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_codegen_rust.py @@ -0,0 +1,401 @@ +from io import StringIO + +from sympy.core import S, symbols, pi, Catalan, EulerGamma, Function +from sympy.core.relational import Equality +from sympy.functions.elementary.piecewise import Piecewise +from sympy.utilities.codegen import RustCodeGen, codegen, make_routine +from sympy.testing.pytest import XFAIL +import sympy + + +x, y, z = symbols('x,y,z') + + +def test_empty_rust_code(): + code_gen = RustCodeGen() + output = StringIO() + code_gen.dump_rs([], output, "file", header=False, empty=False) + source = output.getvalue() + assert source == "" + + +def test_simple_rust_code(): + name_expr = ("test", (x + y)*z) + result, = codegen(name_expr, "Rust", header=False, empty=False) + assert result[0] == "test.rs" + source = result[1] + expected = ( + "fn test(x: f64, y: f64, z: f64) -> f64 {\n" + " let out1 = z*(x + y);\n" + " out1\n" + "}\n" + ) + assert source == expected + + +def test_simple_code_with_header(): + name_expr = ("test", (x + y)*z) + result, = codegen(name_expr, "Rust", header=True, empty=False) + assert result[0] == "test.rs" + source = result[1] + version_str = "Code generated with SymPy %s" % sympy.__version__ + version_line = version_str.center(76).rstrip() + expected = ( + "/*\n" + " *%(version_line)s\n" + " *\n" + " * See http://www.sympy.org/ for more information.\n" + " *\n" + " * This file is part of 'project'\n" + " */\n" + "fn test(x: f64, y: f64, z: f64) -> f64 {\n" + " let out1 = z*(x + y);\n" + " out1\n" + "}\n" + ) % {'version_line': version_line} + assert source == expected + + +def test_simple_code_nameout(): + expr = Equality(z, (x + y)) + name_expr = ("test", expr) + result, = codegen(name_expr, "Rust", header=False, empty=False) + source = result[1] + expected = ( + "fn test(x: f64, y: f64) -> f64 {\n" + " let z = x + y;\n" + " z\n" + "}\n" + ) + assert source == expected + + +def test_numbersymbol(): + name_expr = ("test", pi**Catalan) + result, = codegen(name_expr, "Rust", header=False, empty=False) + source = result[1] + expected = ( + "fn test() -> f64 {\n" + " const Catalan: f64 = %s;\n" + " let out1 = PI.powf(Catalan);\n" + " out1\n" + "}\n" + ) % Catalan.evalf(17) + assert source == expected + + +@XFAIL +def test_numbersymbol_inline(): + # FIXME: how to pass inline to the RustCodePrinter? + name_expr = ("test", [pi**Catalan, EulerGamma]) + result, = codegen(name_expr, "Rust", header=False, + empty=False, inline=True) + source = result[1] + expected = ( + "fn test() -> (f64, f64) {\n" + " const Catalan: f64 = %s;\n" + " const EulerGamma: f64 = %s;\n" + " let out1 = PI.powf(Catalan);\n" + " let out2 = EulerGamma);\n" + " (out1, out2)\n" + "}\n" + ) % (Catalan.evalf(17), EulerGamma.evalf(17)) + assert source == expected + + +def test_argument_order(): + expr = x + y + routine = make_routine("test", expr, argument_sequence=[z, x, y], language="rust") + code_gen = RustCodeGen() + output = StringIO() + code_gen.dump_rs([routine], output, "test", header=False, empty=False) + source = output.getvalue() + expected = ( + "fn test(z: f64, x: f64, y: f64) -> f64 {\n" + " let out1 = x + y;\n" + " out1\n" + "}\n" + ) + assert source == expected + + +def test_multiple_results_rust(): + # Here the output order is the input order + expr1 = (x + y)*z + expr2 = (x - y)*z + name_expr = ("test", [expr1, expr2]) + result, = codegen(name_expr, "Rust", header=False, empty=False) + source = result[1] + expected = ( + "fn test(x: f64, y: f64, z: f64) -> (f64, f64) {\n" + " let out1 = z*(x + y);\n" + " let out2 = z*(x - y);\n" + " (out1, out2)\n" + "}\n" + ) + assert source == expected + + +def test_results_named_unordered(): + # Here output order is based on name_expr + A, B, C = symbols('A,B,C') + expr1 = Equality(C, (x + y)*z) + expr2 = Equality(A, (x - y)*z) + expr3 = Equality(B, 2*x) + name_expr = ("test", [expr1, expr2, expr3]) + result, = codegen(name_expr, "Rust", header=False, empty=False) + source = result[1] + expected = ( + "fn test(x: f64, y: f64, z: f64) -> (f64, f64, f64) {\n" + " let C = z*(x + y);\n" + " let A = z*(x - y);\n" + " let B = 2*x;\n" + " (C, A, B)\n" + "}\n" + ) + assert source == expected + + +def test_results_named_ordered(): + A, B, C = symbols('A,B,C') + expr1 = Equality(C, (x + y)*z) + expr2 = Equality(A, (x - y)*z) + expr3 = Equality(B, 2*x) + name_expr = ("test", [expr1, expr2, expr3]) + result = codegen(name_expr, "Rust", header=False, empty=False, + argument_sequence=(x, z, y)) + assert result[0][0] == "test.rs" + source = result[0][1] + expected = ( + "fn test(x: f64, z: f64, y: f64) -> (f64, f64, f64) {\n" + " let C = z*(x + y);\n" + " let A = z*(x - y);\n" + " let B = 2*x;\n" + " (C, A, B)\n" + "}\n" + ) + assert source == expected + + +def test_complicated_rs_codegen(): + from sympy.functions.elementary.trigonometric import (cos, sin, tan) + name_expr = ("testlong", + [ ((sin(x) + cos(y) + tan(z))**3).expand(), + cos(cos(cos(cos(cos(cos(cos(cos(x + y + z)))))))) + ]) + result = codegen(name_expr, "Rust", header=False, empty=False) + assert result[0][0] == "testlong.rs" + source = result[0][1] + expected = ( + "fn testlong(x: f64, y: f64, z: f64) -> (f64, f64) {\n" + " let out1 = x.sin().powi(3) + 3*x.sin().powi(2)*y.cos()" + " + 3*x.sin().powi(2)*z.tan() + 3*x.sin()*y.cos().powi(2)" + " + 6*x.sin()*y.cos()*z.tan() + 3*x.sin()*z.tan().powi(2)" + " + y.cos().powi(3) + 3*y.cos().powi(2)*z.tan()" + " + 3*y.cos()*z.tan().powi(2) + z.tan().powi(3);\n" + " let out2 = (x + y + z).cos().cos().cos().cos()" + ".cos().cos().cos().cos();\n" + " (out1, out2)\n" + "}\n" + ) + assert source == expected + + +def test_output_arg_mixed_unordered(): + # named outputs are alphabetical, unnamed output appear in the given order + from sympy.functions.elementary.trigonometric import (cos, sin) + a = symbols("a") + name_expr = ("foo", [cos(2*x), Equality(y, sin(x)), cos(x), Equality(a, sin(2*x))]) + result, = codegen(name_expr, "Rust", header=False, empty=False) + assert result[0] == "foo.rs" + source = result[1] + expected = ( + "fn foo(x: f64) -> (f64, f64, f64, f64) {\n" + " let out1 = (2*x).cos();\n" + " let y = x.sin();\n" + " let out3 = x.cos();\n" + " let a = (2*x).sin();\n" + " (out1, y, out3, a)\n" + "}\n" + ) + assert source == expected + + +def test_piecewise_(): + pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True), evaluate=False) + name_expr = ("pwtest", pw) + result, = codegen(name_expr, "Rust", header=False, empty=False) + source = result[1] + expected = ( + "fn pwtest(x: f64) -> f64 {\n" + " let out1 = if (x < -1.0) {\n" + " 0\n" + " } else if (x <= 1.0) {\n" + " x.powi(2)\n" + " } else if (x > 1.0) {\n" + " 2 - x\n" + " } else {\n" + " 1\n" + " };\n" + " out1\n" + "}\n" + ) + assert source == expected + + +@XFAIL +def test_piecewise_inline(): + # FIXME: how to pass inline to the RustCodePrinter? + pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True)) + name_expr = ("pwtest", pw) + result, = codegen(name_expr, "Rust", header=False, empty=False, + inline=True) + source = result[1] + expected = ( + "fn pwtest(x: f64) -> f64 {\n" + " let out1 = if (x < -1) { 0 } else if (x <= 1) { x.powi(2) }" + " else if (x > 1) { -x + 2 } else { 1 };\n" + " out1\n" + "}\n" + ) + assert source == expected + + +def test_multifcns_per_file(): + name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] + result = codegen(name_expr, "Rust", header=False, empty=False) + assert result[0][0] == "foo.rs" + source = result[0][1] + expected = ( + "fn foo(x: f64, y: f64) -> (f64, f64) {\n" + " let out1 = 2*x;\n" + " let out2 = 3*y;\n" + " (out1, out2)\n" + "}\n" + "fn bar(y: f64) -> (f64, f64) {\n" + " let out1 = y.powi(2);\n" + " let out2 = 4*y;\n" + " (out1, out2)\n" + "}\n" + ) + assert source == expected + + +def test_multifcns_per_file_w_header(): + name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] + result = codegen(name_expr, "Rust", header=True, empty=False) + assert result[0][0] == "foo.rs" + source = result[0][1] + version_str = "Code generated with SymPy %s" % sympy.__version__ + version_line = version_str.center(76).rstrip() + expected = ( + "/*\n" + " *%(version_line)s\n" + " *\n" + " * See http://www.sympy.org/ for more information.\n" + " *\n" + " * This file is part of 'project'\n" + " */\n" + "fn foo(x: f64, y: f64) -> (f64, f64) {\n" + " let out1 = 2*x;\n" + " let out2 = 3*y;\n" + " (out1, out2)\n" + "}\n" + "fn bar(y: f64) -> (f64, f64) {\n" + " let out1 = y.powi(2);\n" + " let out2 = 4*y;\n" + " (out1, out2)\n" + "}\n" + ) % {'version_line': version_line} + assert source == expected + + +def test_filename_match_prefix(): + name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] + result, = codegen(name_expr, "Rust", prefix="baz", header=False, + empty=False) + assert result[0] == "baz.rs" + + +def test_InOutArgument(): + expr = Equality(x, x**2) + name_expr = ("mysqr", expr) + result, = codegen(name_expr, "Rust", header=False, empty=False) + source = result[1] + expected = ( + "fn mysqr(x: f64) -> f64 {\n" + " let x = x.powi(2);\n" + " x\n" + "}\n" + ) + assert source == expected + + +def test_InOutArgument_order(): + # can specify the order as (x, y) + expr = Equality(x, x**2 + y) + name_expr = ("test", expr) + result, = codegen(name_expr, "Rust", header=False, + empty=False, argument_sequence=(x,y)) + source = result[1] + expected = ( + "fn test(x: f64, y: f64) -> f64 {\n" + " let x = x.powi(2) + y;\n" + " x\n" + "}\n" + ) + assert source == expected + # make sure it gives (x, y) not (y, x) + expr = Equality(x, x**2 + y) + name_expr = ("test", expr) + result, = codegen(name_expr, "Rust", header=False, empty=False) + source = result[1] + expected = ( + "fn test(x: f64, y: f64) -> f64 {\n" + " let x = x.powi(2) + y;\n" + " x\n" + "}\n" + ) + assert source == expected + + +def test_not_supported(): + f = Function('f') + name_expr = ("test", [f(x).diff(x), S.ComplexInfinity]) + result, = codegen(name_expr, "Rust", header=False, empty=False) + source = result[1] + expected = ( + "fn test(x: f64) -> (f64, f64) {\n" + " // unsupported: Derivative(f(x), x)\n" + " // unsupported: zoo\n" + " let out1 = Derivative(f(x), x);\n" + " let out2 = zoo;\n" + " (out1, out2)\n" + "}\n" + ) + assert source == expected + + +def test_global_vars_rust(): + x, y, z, t = symbols("x y z t") + result = codegen(('f', x*y), "Rust", header=False, empty=False, + global_vars=(y,)) + source = result[0][1] + expected = ( + "fn f(x: f64) -> f64 {\n" + " let out1 = x*y;\n" + " out1\n" + "}\n" + ) + assert source == expected + + result = codegen(('f', x*y+z), "Rust", header=False, empty=False, + argument_sequence=(x, y), global_vars=(z, t)) + source = result[0][1] + expected = ( + "fn f(x: f64, y: f64) -> f64 {\n" + " let out1 = x*y + z;\n" + " out1\n" + "}\n" + ) + assert source == expected diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_decorator.py b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_decorator.py new file mode 100644 index 0000000000000000000000000000000000000000..b1870d4db8f719fdabfeab14120bfb3ce10131a9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_decorator.py @@ -0,0 +1,129 @@ +from functools import wraps + +from sympy.utilities.decorator import threaded, xthreaded, memoize_property, deprecated +from sympy.testing.pytest import warns_deprecated_sympy + +from sympy.core.basic import Basic +from sympy.core.relational import Eq +from sympy.matrices.dense import Matrix + +from sympy.abc import x, y + + +def test_threaded(): + @threaded + def function(expr, *args): + return 2*expr + sum(args) + + assert function(Matrix([[x, y], [1, x]]), 1, 2) == \ + Matrix([[2*x + 3, 2*y + 3], [5, 2*x + 3]]) + + assert function(Eq(x, y), 1, 2) == Eq(2*x + 3, 2*y + 3) + + assert function([x, y], 1, 2) == [2*x + 3, 2*y + 3] + assert function((x, y), 1, 2) == (2*x + 3, 2*y + 3) + + assert function({x, y}, 1, 2) == {2*x + 3, 2*y + 3} + + @threaded + def function(expr, n): + return expr**n + + assert function(x + y, 2) == x**2 + y**2 + assert function(x, 2) == x**2 + + +def test_xthreaded(): + @xthreaded + def function(expr, n): + return expr**n + + assert function(x + y, 2) == (x + y)**2 + + +def test_wraps(): + def my_func(x): + """My function. """ + + my_func.is_my_func = True + + new_my_func = threaded(my_func) + new_my_func = wraps(my_func)(new_my_func) + + assert new_my_func.__name__ == 'my_func' + assert new_my_func.__doc__ == 'My function. ' + assert hasattr(new_my_func, 'is_my_func') + assert new_my_func.is_my_func is True + + +def test_memoize_property(): + class TestMemoize(Basic): + @memoize_property + def prop(self): + return Basic() + + member = TestMemoize() + obj1 = member.prop + obj2 = member.prop + assert obj1 is obj2 + +def test_deprecated(): + @deprecated('deprecated_function is deprecated', + deprecated_since_version='1.10', + # This is the target at the top of the file, which will never + # go away. + active_deprecations_target='active-deprecations') + def deprecated_function(x): + return x + + with warns_deprecated_sympy(): + assert deprecated_function(1) == 1 + + @deprecated('deprecated_class is deprecated', + deprecated_since_version='1.10', + active_deprecations_target='active-deprecations') + class deprecated_class: + pass + + with warns_deprecated_sympy(): + assert isinstance(deprecated_class(), deprecated_class) + + # Ensure the class decorator works even when the class never returns + # itself + @deprecated('deprecated_class_new is deprecated', + deprecated_since_version='1.10', + active_deprecations_target='active-deprecations') + class deprecated_class_new: + def __new__(cls, arg): + return arg + + with warns_deprecated_sympy(): + assert deprecated_class_new(1) == 1 + + @deprecated('deprecated_class_init is deprecated', + deprecated_since_version='1.10', + active_deprecations_target='active-deprecations') + class deprecated_class_init: + def __init__(self, arg): + self.arg = 1 + + with warns_deprecated_sympy(): + assert deprecated_class_init(1).arg == 1 + + @deprecated('deprecated_class_new_init is deprecated', + deprecated_since_version='1.10', + active_deprecations_target='active-deprecations') + class deprecated_class_new_init: + def __new__(cls, arg): + if arg == 0: + return arg + return object.__new__(cls) + + def __init__(self, arg): + self.arg = 1 + + with warns_deprecated_sympy(): + assert deprecated_class_new_init(0) == 0 + + with warns_deprecated_sympy(): + assert deprecated_class_new_init(1).arg == 1 diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_deprecated.py b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_deprecated.py new file mode 100644 index 0000000000000000000000000000000000000000..dd4534ef1abc38ff368011b3ef9d11c497f3675b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_deprecated.py @@ -0,0 +1,13 @@ +from sympy.testing.pytest import warns_deprecated_sympy + +# See https://github.com/sympy/sympy/pull/18095 + +def test_deprecated_utilities(): + with warns_deprecated_sympy(): + import sympy.utilities.pytest # noqa:F401 + with warns_deprecated_sympy(): + import sympy.utilities.runtests # noqa:F401 + with warns_deprecated_sympy(): + import sympy.utilities.randtest # noqa:F401 + with warns_deprecated_sympy(): + import sympy.utilities.tmpfiles # noqa:F401 diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_enumerative.py b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_enumerative.py new file mode 100644 index 0000000000000000000000000000000000000000..357499d5fd400b14e2bcad067f3015b74b0e9003 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_enumerative.py @@ -0,0 +1,179 @@ +import string +from itertools import zip_longest + +from sympy.utilities.enumerative import ( + list_visitor, + MultisetPartitionTraverser, + multiset_partitions_taocp + ) +from sympy.utilities.iterables import _set_partitions + +# first some functions only useful as test scaffolding - these provide +# straightforward, but slow reference implementations against which to +# compare the real versions, and also a comparison to verify that +# different versions are giving identical results. + +def part_range_filter(partition_iterator, lb, ub): + """ + Filters (on the number of parts) a multiset partition enumeration + + Arguments + ========= + + lb, and ub are a range (in the Python slice sense) on the lpart + variable returned from a multiset partition enumeration. Recall + that lpart is 0-based (it points to the topmost part on the part + stack), so if you want to return parts of sizes 2,3,4,5 you would + use lb=1 and ub=5. + """ + for state in partition_iterator: + f, lpart, pstack = state + if lpart >= lb and lpart < ub: + yield state + +def multiset_partitions_baseline(multiplicities, components): + """Enumerates partitions of a multiset + + Parameters + ========== + + multiplicities + list of integer multiplicities of the components of the multiset. + + components + the components (elements) themselves + + Returns + ======= + + Set of partitions. Each partition is tuple of parts, and each + part is a tuple of components (with repeats to indicate + multiplicity) + + Notes + ===== + + Multiset partitions can be created as equivalence classes of set + partitions, and this function does just that. This approach is + slow and memory intensive compared to the more advanced algorithms + available, but the code is simple and easy to understand. Hence + this routine is strictly for testing -- to provide a + straightforward baseline against which to regress the production + versions. (This code is a simplified version of an earlier + production implementation.) + """ + + canon = [] # list of components with repeats + for ct, elem in zip(multiplicities, components): + canon.extend([elem]*ct) + + # accumulate the multiset partitions in a set to eliminate dups + cache = set() + n = len(canon) + for nc, q in _set_partitions(n): + rv = [[] for i in range(nc)] + for i in range(n): + rv[q[i]].append(canon[i]) + canonical = tuple( + sorted([tuple(p) for p in rv])) + cache.add(canonical) + return cache + + +def compare_multiset_w_baseline(multiplicities): + """ + Enumerates the partitions of multiset with AOCP algorithm and + baseline implementation, and compare the results. + + """ + letters = string.ascii_lowercase + bl_partitions = multiset_partitions_baseline(multiplicities, letters) + + # The partitions returned by the different algorithms may have + # their parts in different orders. Also, they generate partitions + # in different orders. Hence the sorting, and set comparison. + + aocp_partitions = set() + for state in multiset_partitions_taocp(multiplicities): + p1 = tuple(sorted( + [tuple(p) for p in list_visitor(state, letters)])) + aocp_partitions.add(p1) + + assert bl_partitions == aocp_partitions + +def compare_multiset_states(s1, s2): + """compare for equality two instances of multiset partition states + + This is useful for comparing different versions of the algorithm + to verify correctness.""" + # Comparison is physical, the only use of semantics is to ignore + # trash off the top of the stack. + f1, lpart1, pstack1 = s1 + f2, lpart2, pstack2 = s2 + + if (lpart1 == lpart2) and (f1[0:lpart1+1] == f2[0:lpart2+1]): + if pstack1[0:f1[lpart1+1]] == pstack2[0:f2[lpart2+1]]: + return True + return False + +def test_multiset_partitions_taocp(): + """Compares the output of multiset_partitions_taocp with a baseline + (set partition based) implementation.""" + + # Test cases should not be too large, since the baseline + # implementation is fairly slow. + multiplicities = [2,2] + compare_multiset_w_baseline(multiplicities) + + multiplicities = [4,3,1] + compare_multiset_w_baseline(multiplicities) + +def test_multiset_partitions_versions(): + """Compares Knuth-based versions of multiset_partitions""" + multiplicities = [5,2,2,1] + m = MultisetPartitionTraverser() + for s1, s2 in zip_longest(m.enum_all(multiplicities), + multiset_partitions_taocp(multiplicities)): + assert compare_multiset_states(s1, s2) + +def subrange_exercise(mult, lb, ub): + """Compare filter-based and more optimized subrange implementations + + Helper for tests, called with both small and larger multisets. + """ + m = MultisetPartitionTraverser() + assert m.count_partitions(mult) == \ + m.count_partitions_slow(mult) + + # Note - multiple traversals from the same + # MultisetPartitionTraverser object cannot execute at the same + # time, hence make several instances here. + ma = MultisetPartitionTraverser() + mc = MultisetPartitionTraverser() + md = MultisetPartitionTraverser() + + # Several paths to compute just the size two partitions + a_it = ma.enum_range(mult, lb, ub) + b_it = part_range_filter(multiset_partitions_taocp(mult), lb, ub) + c_it = part_range_filter(mc.enum_small(mult, ub), lb, sum(mult)) + d_it = part_range_filter(md.enum_large(mult, lb), 0, ub) + + for sa, sb, sc, sd in zip_longest(a_it, b_it, c_it, d_it): + assert compare_multiset_states(sa, sb) + assert compare_multiset_states(sa, sc) + assert compare_multiset_states(sa, sd) + +def test_subrange(): + # Quick, but doesn't hit some of the corner cases + mult = [4,4,2,1] # mississippi + lb = 1 + ub = 2 + subrange_exercise(mult, lb, ub) + + +def test_subrange_large(): + # takes a second or so, depending on cpu, Python version, etc. + mult = [6,3,2,1] + lb = 4 + ub = 7 + subrange_exercise(mult, lb, ub) diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_exceptions.py b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..d91e55e95d0ae4ac57cdd1989e0b3d39a55cd07d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_exceptions.py @@ -0,0 +1,12 @@ +from sympy.testing.pytest import raises +from sympy.utilities.exceptions import sympy_deprecation_warning + +# Only test exceptions here because the other cases are tested in the +# warns_deprecated_sympy tests +def test_sympy_deprecation_warning(): + raises(TypeError, lambda: sympy_deprecation_warning('test', + deprecated_since_version=1.10, + active_deprecations_target='active-deprecations')) + + raises(ValueError, lambda: sympy_deprecation_warning('test', + deprecated_since_version="1.10", active_deprecations_target='(active-deprecations)=')) diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_iterables.py b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_iterables.py new file mode 100644 index 0000000000000000000000000000000000000000..1003522bcd556c6f63e04de7da57b43498575fee --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_iterables.py @@ -0,0 +1,945 @@ +from textwrap import dedent +from itertools import islice, product + +from sympy.core.basic import Basic +from sympy.core.numbers import Integer +from sympy.core.sorting import ordered +from sympy.core.symbol import (Dummy, symbols) +from sympy.functions.combinatorial.factorials import factorial +from sympy.matrices.dense import Matrix +from sympy.combinatorics import RGS_enum, RGS_unrank, Permutation +from sympy.utilities.iterables import ( + _partition, _set_partitions, binary_partitions, bracelets, capture, + cartes, common_prefix, common_suffix, connected_components, dict_merge, + filter_symbols, flatten, generate_bell, generate_derangements, + generate_involutions, generate_oriented_forest, group, has_dups, ibin, + iproduct, kbins, minlex, multiset, multiset_combinations, + multiset_partitions, multiset_permutations, necklaces, numbered_symbols, + partitions, permutations, postfixes, + prefixes, reshape, rotate_left, rotate_right, runs, sift, + strongly_connected_components, subsets, take, topological_sort, unflatten, + uniq, variations, ordered_partitions, rotations, is_palindromic, iterable, + NotIterable, multiset_derangements, signed_permutations, + sequence_partitions, sequence_partitions_empty) +from sympy.utilities.enumerative import ( + factoring_visitor, multiset_partitions_taocp ) + +from sympy.core.singleton import S +from sympy.testing.pytest import raises, warns_deprecated_sympy + +w, x, y, z = symbols('w,x,y,z') + + +def test_deprecated_iterables(): + from sympy.utilities.iterables import default_sort_key, ordered + with warns_deprecated_sympy(): + assert list(ordered([y, x])) == [x, y] + with warns_deprecated_sympy(): + assert sorted([y, x], key=default_sort_key) == [x, y] + + +def test_is_palindromic(): + assert is_palindromic('') + assert is_palindromic('x') + assert is_palindromic('xx') + assert is_palindromic('xyx') + assert not is_palindromic('xy') + assert not is_palindromic('xyzx') + assert is_palindromic('xxyzzyx', 1) + assert not is_palindromic('xxyzzyx', 2) + assert is_palindromic('xxyzzyx', 2, -1) + assert is_palindromic('xxyzzyx', 2, 6) + assert is_palindromic('xxyzyx', 1) + assert not is_palindromic('xxyzyx', 2) + assert is_palindromic('xxyzyx', 2, 2 + 3) + + +def test_flatten(): + assert flatten((1, (1,))) == [1, 1] + assert flatten((x, (x,))) == [x, x] + + ls = [[(-2, -1), (1, 2)], [(0, 0)]] + + assert flatten(ls, levels=0) == ls + assert flatten(ls, levels=1) == [(-2, -1), (1, 2), (0, 0)] + assert flatten(ls, levels=2) == [-2, -1, 1, 2, 0, 0] + assert flatten(ls, levels=3) == [-2, -1, 1, 2, 0, 0] + + raises(ValueError, lambda: flatten(ls, levels=-1)) + + class MyOp(Basic): + pass + + assert flatten([MyOp(x, y), z]) == [MyOp(x, y), z] + assert flatten([MyOp(x, y), z], cls=MyOp) == [x, y, z] + + assert flatten({1, 11, 2}) == list({1, 11, 2}) + + +def test_iproduct(): + assert list(iproduct()) == [()] + assert list(iproduct([])) == [] + assert list(iproduct([1,2,3])) == [(1,),(2,),(3,)] + assert sorted(iproduct([1, 2], [3, 4, 5])) == [ + (1,3),(1,4),(1,5),(2,3),(2,4),(2,5)] + assert sorted(iproduct([0,1],[0,1],[0,1])) == [ + (0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)] + assert iterable(iproduct(S.Integers)) is True + assert iterable(iproduct(S.Integers, S.Integers)) is True + assert (3,) in iproduct(S.Integers) + assert (4, 5) in iproduct(S.Integers, S.Integers) + assert (1, 2, 3) in iproduct(S.Integers, S.Integers, S.Integers) + triples = set(islice(iproduct(S.Integers, S.Integers, S.Integers), 1000)) + for n1, n2, n3 in triples: + assert isinstance(n1, Integer) + assert isinstance(n2, Integer) + assert isinstance(n3, Integer) + for t in set(product(*([range(-2, 3)]*3))): + assert t in iproduct(S.Integers, S.Integers, S.Integers) + + +def test_group(): + assert group([]) == [] + assert group([], multiple=False) == [] + + assert group([1]) == [[1]] + assert group([1], multiple=False) == [(1, 1)] + + assert group([1, 1]) == [[1, 1]] + assert group([1, 1], multiple=False) == [(1, 2)] + + assert group([1, 1, 1]) == [[1, 1, 1]] + assert group([1, 1, 1], multiple=False) == [(1, 3)] + + assert group([1, 2, 1]) == [[1], [2], [1]] + assert group([1, 2, 1], multiple=False) == [(1, 1), (2, 1), (1, 1)] + + assert group([1, 1, 2, 2, 2, 1, 3, 3]) == [[1, 1], [2, 2, 2], [1], [3, 3]] + assert group([1, 1, 2, 2, 2, 1, 3, 3], multiple=False) == [(1, 2), + (2, 3), (1, 1), (3, 2)] + + +def test_subsets(): + # combinations + assert list(subsets([1, 2, 3], 0)) == [()] + assert list(subsets([1, 2, 3], 1)) == [(1,), (2,), (3,)] + assert list(subsets([1, 2, 3], 2)) == [(1, 2), (1, 3), (2, 3)] + assert list(subsets([1, 2, 3], 3)) == [(1, 2, 3)] + l = list(range(4)) + assert list(subsets(l, 0, repetition=True)) == [()] + assert list(subsets(l, 1, repetition=True)) == [(0,), (1,), (2,), (3,)] + assert list(subsets(l, 2, repetition=True)) == [(0, 0), (0, 1), (0, 2), + (0, 3), (1, 1), (1, 2), + (1, 3), (2, 2), (2, 3), + (3, 3)] + assert list(subsets(l, 3, repetition=True)) == [(0, 0, 0), (0, 0, 1), + (0, 0, 2), (0, 0, 3), + (0, 1, 1), (0, 1, 2), + (0, 1, 3), (0, 2, 2), + (0, 2, 3), (0, 3, 3), + (1, 1, 1), (1, 1, 2), + (1, 1, 3), (1, 2, 2), + (1, 2, 3), (1, 3, 3), + (2, 2, 2), (2, 2, 3), + (2, 3, 3), (3, 3, 3)] + assert len(list(subsets(l, 4, repetition=True))) == 35 + + assert list(subsets(l[:2], 3, repetition=False)) == [] + assert list(subsets(l[:2], 3, repetition=True)) == [(0, 0, 0), + (0, 0, 1), + (0, 1, 1), + (1, 1, 1)] + assert list(subsets([1, 2], repetition=True)) == \ + [(), (1,), (2,), (1, 1), (1, 2), (2, 2)] + assert list(subsets([1, 2], repetition=False)) == \ + [(), (1,), (2,), (1, 2)] + assert list(subsets([1, 2, 3], 2)) == \ + [(1, 2), (1, 3), (2, 3)] + assert list(subsets([1, 2, 3], 2, repetition=True)) == \ + [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)] + + +def test_variations(): + # permutations + l = list(range(4)) + assert list(variations(l, 0, repetition=False)) == [()] + assert list(variations(l, 1, repetition=False)) == [(0,), (1,), (2,), (3,)] + assert list(variations(l, 2, repetition=False)) == [(0, 1), (0, 2), (0, 3), (1, 0), (1, 2), (1, 3), (2, 0), (2, 1), (2, 3), (3, 0), (3, 1), (3, 2)] + assert list(variations(l, 3, repetition=False)) == [(0, 1, 2), (0, 1, 3), (0, 2, 1), (0, 2, 3), (0, 3, 1), (0, 3, 2), (1, 0, 2), (1, 0, 3), (1, 2, 0), (1, 2, 3), (1, 3, 0), (1, 3, 2), (2, 0, 1), (2, 0, 3), (2, 1, 0), (2, 1, 3), (2, 3, 0), (2, 3, 1), (3, 0, 1), (3, 0, 2), (3, 1, 0), (3, 1, 2), (3, 2, 0), (3, 2, 1)] + assert list(variations(l, 0, repetition=True)) == [()] + assert list(variations(l, 1, repetition=True)) == [(0,), (1,), (2,), (3,)] + assert list(variations(l, 2, repetition=True)) == [(0, 0), (0, 1), (0, 2), + (0, 3), (1, 0), (1, 1), + (1, 2), (1, 3), (2, 0), + (2, 1), (2, 2), (2, 3), + (3, 0), (3, 1), (3, 2), + (3, 3)] + assert len(list(variations(l, 3, repetition=True))) == 64 + assert len(list(variations(l, 4, repetition=True))) == 256 + assert list(variations(l[:2], 3, repetition=False)) == [] + assert list(variations(l[:2], 3, repetition=True)) == [ + (0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), + (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1) + ] + + +def test_cartes(): + assert list(cartes([1, 2], [3, 4, 5])) == \ + [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)] + assert list(cartes()) == [()] + assert list(cartes('a')) == [('a',)] + assert list(cartes('a', repeat=2)) == [('a', 'a')] + assert list(cartes(list(range(2)))) == [(0,), (1,)] + + +def test_filter_symbols(): + s = numbered_symbols() + filtered = filter_symbols(s, symbols("x0 x2 x3")) + assert take(filtered, 3) == list(symbols("x1 x4 x5")) + + +def test_numbered_symbols(): + s = numbered_symbols(cls=Dummy) + assert isinstance(next(s), Dummy) + assert next(numbered_symbols('C', start=1, exclude=[symbols('C1')])) == \ + symbols('C2') + + +def test_sift(): + assert sift(list(range(5)), lambda _: _ % 2) == {1: [1, 3], 0: [0, 2, 4]} + assert sift([x, y], lambda _: _.has(x)) == {False: [y], True: [x]} + assert sift([S.One], lambda _: _.has(x)) == {False: [1]} + assert sift([0, 1, 2, 3], lambda x: x % 2, binary=True) == ( + [1, 3], [0, 2]) + assert sift([0, 1, 2, 3], lambda x: x % 3 == 1, binary=True) == ( + [1], [0, 2, 3]) + raises(ValueError, lambda: + sift([0, 1, 2, 3], lambda x: x % 3, binary=True)) + + +def test_take(): + X = numbered_symbols() + + assert take(X, 5) == list(symbols('x0:5')) + assert take(X, 5) == list(symbols('x5:10')) + + assert take([1, 2, 3, 4, 5], 5) == [1, 2, 3, 4, 5] + + +def test_dict_merge(): + assert dict_merge({}, {1: x, y: z}) == {1: x, y: z} + assert dict_merge({1: x, y: z}, {}) == {1: x, y: z} + + assert dict_merge({2: z}, {1: x, y: z}) == {1: x, 2: z, y: z} + assert dict_merge({1: x, y: z}, {2: z}) == {1: x, 2: z, y: z} + + assert dict_merge({1: y, 2: z}, {1: x, y: z}) == {1: x, 2: z, y: z} + assert dict_merge({1: x, y: z}, {1: y, 2: z}) == {1: y, 2: z, y: z} + + +def test_prefixes(): + assert list(prefixes([])) == [] + assert list(prefixes([1])) == [[1]] + assert list(prefixes([1, 2])) == [[1], [1, 2]] + + assert list(prefixes([1, 2, 3, 4, 5])) == \ + [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]] + + +def test_postfixes(): + assert list(postfixes([])) == [] + assert list(postfixes([1])) == [[1]] + assert list(postfixes([1, 2])) == [[2], [1, 2]] + + assert list(postfixes([1, 2, 3, 4, 5])) == \ + [[5], [4, 5], [3, 4, 5], [2, 3, 4, 5], [1, 2, 3, 4, 5]] + + +def test_topological_sort(): + V = [2, 3, 5, 7, 8, 9, 10, 11] + E = [(7, 11), (7, 8), (5, 11), + (3, 8), (3, 10), (11, 2), + (11, 9), (11, 10), (8, 9)] + + assert topological_sort((V, E)) == [3, 5, 7, 8, 11, 2, 9, 10] + assert topological_sort((V, E), key=lambda v: -v) == \ + [7, 5, 11, 3, 10, 8, 9, 2] + + raises(ValueError, lambda: topological_sort((V, E + [(10, 7)]))) + + +def test_strongly_connected_components(): + assert strongly_connected_components(([], [])) == [] + assert strongly_connected_components(([1, 2, 3], [])) == [[1], [2], [3]] + + V = [1, 2, 3] + E = [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1)] + assert strongly_connected_components((V, E)) == [[1, 2, 3]] + + V = [1, 2, 3, 4] + E = [(1, 2), (2, 3), (3, 2), (3, 4)] + assert strongly_connected_components((V, E)) == [[4], [2, 3], [1]] + + V = [1, 2, 3, 4] + E = [(1, 2), (2, 1), (3, 4), (4, 3)] + assert strongly_connected_components((V, E)) == [[1, 2], [3, 4]] + + +def test_connected_components(): + assert connected_components(([], [])) == [] + assert connected_components(([1, 2, 3], [])) == [[1], [2], [3]] + + V = [1, 2, 3] + E = [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1)] + assert connected_components((V, E)) == [[1, 2, 3]] + + V = [1, 2, 3, 4] + E = [(1, 2), (2, 3), (3, 2), (3, 4)] + assert connected_components((V, E)) == [[1, 2, 3, 4]] + + V = [1, 2, 3, 4] + E = [(1, 2), (3, 4)] + assert connected_components((V, E)) == [[1, 2], [3, 4]] + + +def test_rotate(): + A = [0, 1, 2, 3, 4] + + assert rotate_left(A, 2) == [2, 3, 4, 0, 1] + assert rotate_right(A, 1) == [4, 0, 1, 2, 3] + A = [] + B = rotate_right(A, 1) + assert B == [] + B.append(1) + assert A == [] + B = rotate_left(A, 1) + assert B == [] + B.append(1) + assert A == [] + + +def test_multiset_partitions(): + A = [0, 1, 2, 3, 4] + + assert list(multiset_partitions(A, 5)) == [[[0], [1], [2], [3], [4]]] + assert len(list(multiset_partitions(A, 4))) == 10 + assert len(list(multiset_partitions(A, 3))) == 25 + + assert list(multiset_partitions([1, 1, 1, 2, 2], 2)) == [ + [[1, 1, 1, 2], [2]], [[1, 1, 1], [2, 2]], [[1, 1, 2, 2], [1]], + [[1, 1, 2], [1, 2]], [[1, 1], [1, 2, 2]]] + + assert list(multiset_partitions([1, 1, 2, 2], 2)) == [ + [[1, 1, 2], [2]], [[1, 1], [2, 2]], [[1, 2, 2], [1]], + [[1, 2], [1, 2]]] + + assert list(multiset_partitions([1, 2, 3, 4], 2)) == [ + [[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 2], [3, 4]], + [[1, 3, 4], [2]], [[1, 3], [2, 4]], [[1, 4], [2, 3]], + [[1], [2, 3, 4]]] + + assert list(multiset_partitions([1, 2, 2], 2)) == [ + [[1, 2], [2]], [[1], [2, 2]]] + + assert list(multiset_partitions(3)) == [ + [[0, 1, 2]], [[0, 1], [2]], [[0, 2], [1]], [[0], [1, 2]], + [[0], [1], [2]]] + assert list(multiset_partitions(3, 2)) == [ + [[0, 1], [2]], [[0, 2], [1]], [[0], [1, 2]]] + assert list(multiset_partitions([1] * 3, 2)) == [[[1], [1, 1]]] + assert list(multiset_partitions([1] * 3)) == [ + [[1, 1, 1]], [[1], [1, 1]], [[1], [1], [1]]] + a = [3, 2, 1] + assert list(multiset_partitions(a)) == \ + list(multiset_partitions(sorted(a))) + assert list(multiset_partitions(a, 5)) == [] + assert list(multiset_partitions(a, 1)) == [[[1, 2, 3]]] + assert list(multiset_partitions(a + [4], 5)) == [] + assert list(multiset_partitions(a + [4], 1)) == [[[1, 2, 3, 4]]] + assert list(multiset_partitions(2, 5)) == [] + assert list(multiset_partitions(2, 1)) == [[[0, 1]]] + assert list(multiset_partitions('a')) == [[['a']]] + assert list(multiset_partitions('a', 2)) == [] + assert list(multiset_partitions('ab')) == [[['a', 'b']], [['a'], ['b']]] + assert list(multiset_partitions('ab', 1)) == [[['a', 'b']]] + assert list(multiset_partitions('aaa', 1)) == [['aaa']] + assert list(multiset_partitions([1, 1], 1)) == [[[1, 1]]] + ans = [('mpsyy',), ('mpsy', 'y'), ('mps', 'yy'), ('mps', 'y', 'y'), + ('mpyy', 's'), ('mpy', 'sy'), ('mpy', 's', 'y'), ('mp', 'syy'), + ('mp', 'sy', 'y'), ('mp', 's', 'yy'), ('mp', 's', 'y', 'y'), + ('msyy', 'p'), ('msy', 'py'), ('msy', 'p', 'y'), ('ms', 'pyy'), + ('ms', 'py', 'y'), ('ms', 'p', 'yy'), ('ms', 'p', 'y', 'y'), + ('myy', 'ps'), ('myy', 'p', 's'), ('my', 'psy'), ('my', 'ps', 'y'), + ('my', 'py', 's'), ('my', 'p', 'sy'), ('my', 'p', 's', 'y'), + ('m', 'psyy'), ('m', 'psy', 'y'), ('m', 'ps', 'yy'), + ('m', 'ps', 'y', 'y'), ('m', 'pyy', 's'), ('m', 'py', 'sy'), + ('m', 'py', 's', 'y'), ('m', 'p', 'syy'), + ('m', 'p', 'sy', 'y'), ('m', 'p', 's', 'yy'), + ('m', 'p', 's', 'y', 'y')] + assert [tuple("".join(part) for part in p) + for p in multiset_partitions('sympy')] == ans + factorings = [[24], [8, 3], [12, 2], [4, 6], [4, 2, 3], + [6, 2, 2], [2, 2, 2, 3]] + assert [factoring_visitor(p, [2,3]) for + p in multiset_partitions_taocp([3, 1])] == factorings + + +def test_multiset_combinations(): + ans = ['iii', 'iim', 'iip', 'iis', 'imp', 'ims', 'ipp', 'ips', + 'iss', 'mpp', 'mps', 'mss', 'pps', 'pss', 'sss'] + assert [''.join(i) for i in + list(multiset_combinations('mississippi', 3))] == ans + M = multiset('mississippi') + assert [''.join(i) for i in + list(multiset_combinations(M, 3))] == ans + assert [''.join(i) for i in multiset_combinations(M, 30)] == [] + assert list(multiset_combinations([[1], [2, 3]], 2)) == [[[1], [2, 3]]] + assert len(list(multiset_combinations('a', 3))) == 0 + assert len(list(multiset_combinations('a', 0))) == 1 + assert list(multiset_combinations('abc', 1)) == [['a'], ['b'], ['c']] + raises(ValueError, lambda: list(multiset_combinations({0: 3, 1: -1}, 2))) + + +def test_multiset_permutations(): + ans = ['abby', 'abyb', 'aybb', 'baby', 'bayb', 'bbay', 'bbya', 'byab', + 'byba', 'yabb', 'ybab', 'ybba'] + assert [''.join(i) for i in multiset_permutations('baby')] == ans + assert [''.join(i) for i in multiset_permutations(multiset('baby'))] == ans + assert list(multiset_permutations([0, 0, 0], 2)) == [[0, 0]] + assert list(multiset_permutations([0, 2, 1], 2)) == [ + [0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1]] + assert len(list(multiset_permutations('a', 0))) == 1 + assert len(list(multiset_permutations('a', 3))) == 0 + for nul in ([], {}, ''): + assert list(multiset_permutations(nul)) == [[]] + assert list(multiset_permutations(nul, 0)) == [[]] + # impossible requests give no result + assert list(multiset_permutations(nul, 1)) == [] + assert list(multiset_permutations(nul, -1)) == [] + + def test(): + for i in range(1, 7): + print(i) + for p in multiset_permutations([0, 0, 1, 0, 1], i): + print(p) + assert capture(lambda: test()) == dedent('''\ + 1 + [0] + [1] + 2 + [0, 0] + [0, 1] + [1, 0] + [1, 1] + 3 + [0, 0, 0] + [0, 0, 1] + [0, 1, 0] + [0, 1, 1] + [1, 0, 0] + [1, 0, 1] + [1, 1, 0] + 4 + [0, 0, 0, 1] + [0, 0, 1, 0] + [0, 0, 1, 1] + [0, 1, 0, 0] + [0, 1, 0, 1] + [0, 1, 1, 0] + [1, 0, 0, 0] + [1, 0, 0, 1] + [1, 0, 1, 0] + [1, 1, 0, 0] + 5 + [0, 0, 0, 1, 1] + [0, 0, 1, 0, 1] + [0, 0, 1, 1, 0] + [0, 1, 0, 0, 1] + [0, 1, 0, 1, 0] + [0, 1, 1, 0, 0] + [1, 0, 0, 0, 1] + [1, 0, 0, 1, 0] + [1, 0, 1, 0, 0] + [1, 1, 0, 0, 0] + 6\n''') + raises(ValueError, lambda: list(multiset_permutations({0: 3, 1: -1}))) + + +def test_partitions(): + ans = [[{}], [(0, {})]] + for i in range(2): + assert list(partitions(0, size=i)) == ans[i] + assert list(partitions(1, 0, size=i)) == ans[i] + assert list(partitions(6, 2, 2, size=i)) == ans[i] + assert list(partitions(6, 2, None, size=i)) != ans[i] + assert list(partitions(6, None, 2, size=i)) != ans[i] + assert list(partitions(6, 2, 0, size=i)) == ans[i] + + assert list(partitions(6, k=2)) == [ + {2: 3}, {1: 2, 2: 2}, {1: 4, 2: 1}, {1: 6}] + + assert list(partitions(6, k=3)) == [ + {3: 2}, {1: 1, 2: 1, 3: 1}, {1: 3, 3: 1}, {2: 3}, {1: 2, 2: 2}, + {1: 4, 2: 1}, {1: 6}] + + assert list(partitions(8, k=4, m=3)) == [ + {4: 2}, {1: 1, 3: 1, 4: 1}, {2: 2, 4: 1}, {2: 1, 3: 2}] == [ + i for i in partitions(8, k=4, m=3) if all(k <= 4 for k in i) + and sum(i.values()) <=3] + + assert list(partitions(S(3), m=2)) == [ + {3: 1}, {1: 1, 2: 1}] + + assert list(partitions(4, k=3)) == [ + {1: 1, 3: 1}, {2: 2}, {1: 2, 2: 1}, {1: 4}] == [ + i for i in partitions(4) if all(k <= 3 for k in i)] + + + # Consistency check on output of _partitions and RGS_unrank. + # This provides a sanity test on both routines. Also verifies that + # the total number of partitions is the same in each case. + # (from pkrathmann2) + + for n in range(2, 6): + i = 0 + for m, q in _set_partitions(n): + assert q == RGS_unrank(i, n) + i += 1 + assert i == RGS_enum(n) + + +def test_binary_partitions(): + assert [i[:] for i in binary_partitions(10)] == [[8, 2], [8, 1, 1], + [4, 4, 2], [4, 4, 1, 1], [4, 2, 2, 2], [4, 2, 2, 1, 1], + [4, 2, 1, 1, 1, 1], [4, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2], + [2, 2, 2, 2, 1, 1], [2, 2, 2, 1, 1, 1, 1], [2, 2, 1, 1, 1, 1, 1, 1], + [2, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] + + assert len([j[:] for j in binary_partitions(16)]) == 36 + + +def test_bell_perm(): + assert [len(set(generate_bell(i))) for i in range(1, 7)] == [ + factorial(i) for i in range(1, 7)] + assert list(generate_bell(3)) == [ + (0, 1, 2), (0, 2, 1), (2, 0, 1), (2, 1, 0), (1, 2, 0), (1, 0, 2)] + # generate_bell and trotterjohnson are advertised to return the same + # permutations; this is not technically necessary so this test could + # be removed + for n in range(1, 5): + p = Permutation(range(n)) + b = generate_bell(n) + for bi in b: + assert bi == tuple(p.array_form) + p = p.next_trotterjohnson() + raises(ValueError, lambda: list(generate_bell(0))) # XXX is this consistent with other permutation algorithms? + + +def test_involutions(): + lengths = [1, 2, 4, 10, 26, 76] + for n, N in enumerate(lengths): + i = list(generate_involutions(n + 1)) + assert len(i) == N + assert len({Permutation(j)**2 for j in i}) == 1 + + +def test_derangements(): + assert len(list(generate_derangements(list(range(6))))) == 265 + assert ''.join(''.join(i) for i in generate_derangements('abcde')) == ( + 'badecbaecdbcaedbcdeabceadbdaecbdeacbdecabeacdbedacbedcacabedcadebcaebd' + 'cdaebcdbeacdeabcdebaceabdcebadcedabcedbadabecdaebcdaecbdcaebdcbeadceab' + 'dcebadeabcdeacbdebacdebcaeabcdeadbceadcbecabdecbadecdabecdbaedabcedacb' + 'edbacedbca') + assert list(generate_derangements([0, 1, 2, 3])) == [ + [1, 0, 3, 2], [1, 2, 3, 0], [1, 3, 0, 2], [2, 0, 3, 1], + [2, 3, 0, 1], [2, 3, 1, 0], [3, 0, 1, 2], [3, 2, 0, 1], [3, 2, 1, 0]] + assert list(generate_derangements([0, 1, 2, 2])) == [ + [2, 2, 0, 1], [2, 2, 1, 0]] + assert list(generate_derangements('ba')) == [list('ab')] + # multiset_derangements + D = multiset_derangements + assert list(D('abb')) == [] + assert [''.join(i) for i in D('ab')] == ['ba'] + assert [''.join(i) for i in D('abc')] == ['bca', 'cab'] + assert [''.join(i) for i in D('aabb')] == ['bbaa'] + assert [''.join(i) for i in D('aabbcccc')] == [ + 'ccccaabb', 'ccccabab', 'ccccabba', 'ccccbaab', 'ccccbaba', + 'ccccbbaa'] + assert [''.join(i) for i in D('aabbccc')] == [ + 'cccabba', 'cccabab', 'cccaabb', 'ccacbba', 'ccacbab', + 'ccacabb', 'cbccbaa', 'cbccaba', 'cbccaab', 'bcccbaa', + 'bcccaba', 'bcccaab'] + assert [''.join(i) for i in D('books')] == ['kbsoo', 'ksboo', + 'sbkoo', 'skboo', 'oksbo', 'oskbo', 'okbso', 'obkso', 'oskob', + 'oksob', 'osbok', 'obsok'] + assert list(generate_derangements([[3], [2], [2], [1]])) == [ + [[2], [1], [3], [2]], [[2], [3], [1], [2]]] + + +def test_necklaces(): + def count(n, k, f): + return len(list(necklaces(n, k, f))) + m = [] + for i in range(1, 8): + m.append(( + i, count(i, 2, 0), count(i, 2, 1), count(i, 3, 1))) + assert Matrix(m) == Matrix([ + [1, 2, 2, 3], + [2, 3, 3, 6], + [3, 4, 4, 10], + [4, 6, 6, 21], + [5, 8, 8, 39], + [6, 14, 13, 92], + [7, 20, 18, 198]]) + + +def test_bracelets(): + bc = list(bracelets(2, 4)) + assert Matrix(bc) == Matrix([ + [0, 0], + [0, 1], + [0, 2], + [0, 3], + [1, 1], + [1, 2], + [1, 3], + [2, 2], + [2, 3], + [3, 3] + ]) + bc = list(bracelets(4, 2)) + assert Matrix(bc) == Matrix([ + [0, 0, 0, 0], + [0, 0, 0, 1], + [0, 0, 1, 1], + [0, 1, 0, 1], + [0, 1, 1, 1], + [1, 1, 1, 1] + ]) + + +def test_generate_oriented_forest(): + assert list(generate_oriented_forest(5)) == [[0, 1, 2, 3, 4], + [0, 1, 2, 3, 3], [0, 1, 2, 3, 2], [0, 1, 2, 3, 1], [0, 1, 2, 3, 0], + [0, 1, 2, 2, 2], [0, 1, 2, 2, 1], [0, 1, 2, 2, 0], [0, 1, 2, 1, 2], + [0, 1, 2, 1, 1], [0, 1, 2, 1, 0], [0, 1, 2, 0, 1], [0, 1, 2, 0, 0], + [0, 1, 1, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 0, 1], [0, 1, 1, 0, 0], + [0, 1, 0, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 0]] + assert len(list(generate_oriented_forest(10))) == 1842 + + +def test_unflatten(): + r = list(range(10)) + assert unflatten(r) == list(zip(r[::2], r[1::2])) + assert unflatten(r, 5) == [tuple(r[:5]), tuple(r[5:])] + raises(ValueError, lambda: unflatten(list(range(10)), 3)) + raises(ValueError, lambda: unflatten(list(range(10)), -2)) + + +def test_common_prefix_suffix(): + assert common_prefix([], [1]) == [] + assert common_prefix(list(range(3))) == [0, 1, 2] + assert common_prefix(list(range(3)), list(range(4))) == [0, 1, 2] + assert common_prefix([1, 2, 3], [1, 2, 5]) == [1, 2] + assert common_prefix([1, 2, 3], [1, 3, 5]) == [1] + + assert common_suffix([], [1]) == [] + assert common_suffix(list(range(3))) == [0, 1, 2] + assert common_suffix(list(range(3)), list(range(3))) == [0, 1, 2] + assert common_suffix(list(range(3)), list(range(4))) == [] + assert common_suffix([1, 2, 3], [9, 2, 3]) == [2, 3] + assert common_suffix([1, 2, 3], [9, 7, 3]) == [3] + + +def test_minlex(): + assert minlex([1, 2, 0]) == (0, 1, 2) + assert minlex((1, 2, 0)) == (0, 1, 2) + assert minlex((1, 0, 2)) == (0, 2, 1) + assert minlex((1, 0, 2), directed=False) == (0, 1, 2) + assert minlex('aba') == 'aab' + assert minlex(('bb', 'aaa', 'c', 'a'), key=len) == ('c', 'a', 'bb', 'aaa') + + +def test_ordered(): + assert list(ordered((x, y), hash, default=False)) in [[x, y], [y, x]] + assert list(ordered((x, y), hash, default=False)) == \ + list(ordered((y, x), hash, default=False)) + assert list(ordered((x, y))) == [x, y] + + seq, keys = [[[1, 2, 1], [0, 3, 1], [1, 1, 3], [2], [1]], + (lambda x: len(x), lambda x: sum(x))] + assert list(ordered(seq, keys, default=False, warn=False)) == \ + [[1], [2], [1, 2, 1], [0, 3, 1], [1, 1, 3]] + raises(ValueError, lambda: + list(ordered(seq, keys, default=False, warn=True))) + + +def test_runs(): + assert runs([]) == [] + assert runs([1]) == [[1]] + assert runs([1, 1]) == [[1], [1]] + assert runs([1, 1, 2]) == [[1], [1, 2]] + assert runs([1, 2, 1]) == [[1, 2], [1]] + assert runs([2, 1, 1]) == [[2], [1], [1]] + from operator import lt + assert runs([2, 1, 1], lt) == [[2, 1], [1]] + + +def test_reshape(): + seq = list(range(1, 9)) + assert reshape(seq, [4]) == \ + [[1, 2, 3, 4], [5, 6, 7, 8]] + assert reshape(seq, (4,)) == \ + [(1, 2, 3, 4), (5, 6, 7, 8)] + assert reshape(seq, (2, 2)) == \ + [(1, 2, 3, 4), (5, 6, 7, 8)] + assert reshape(seq, (2, [2])) == \ + [(1, 2, [3, 4]), (5, 6, [7, 8])] + assert reshape(seq, ((2,), [2])) == \ + [((1, 2), [3, 4]), ((5, 6), [7, 8])] + assert reshape(seq, (1, [2], 1)) == \ + [(1, [2, 3], 4), (5, [6, 7], 8)] + assert reshape(tuple(seq), ([[1], 1, (2,)],)) == \ + (([[1], 2, (3, 4)],), ([[5], 6, (7, 8)],)) + assert reshape(tuple(seq), ([1], 1, (2,))) == \ + (([1], 2, (3, 4)), ([5], 6, (7, 8))) + assert reshape(list(range(12)), [2, [3], {2}, (1, (3,), 1)]) == \ + [[0, 1, [2, 3, 4], {5, 6}, (7, (8, 9, 10), 11)]] + raises(ValueError, lambda: reshape([0, 1], [-1])) + raises(ValueError, lambda: reshape([0, 1], [3])) + + +def test_uniq(): + assert list(uniq(p for p in partitions(4))) == \ + [{4: 1}, {1: 1, 3: 1}, {2: 2}, {1: 2, 2: 1}, {1: 4}] + assert list(uniq(x % 2 for x in range(5))) == [0, 1] + assert list(uniq('a')) == ['a'] + assert list(uniq('ababc')) == list('abc') + assert list(uniq([[1], [2, 1], [1]])) == [[1], [2, 1]] + assert list(uniq(permutations(i for i in [[1], 2, 2]))) == \ + [([1], 2, 2), (2, [1], 2), (2, 2, [1])] + assert list(uniq([2, 3, 2, 4, [2], [1], [2], [3], [1]])) == \ + [2, 3, 4, [2], [1], [3]] + f = [1] + raises(RuntimeError, lambda: [f.remove(i) for i in uniq(f)]) + f = [[1]] + raises(RuntimeError, lambda: [f.remove(i) for i in uniq(f)]) + + +def test_kbins(): + assert len(list(kbins('1123', 2, ordered=1))) == 24 + assert len(list(kbins('1123', 2, ordered=11))) == 36 + assert len(list(kbins('1123', 2, ordered=10))) == 10 + assert len(list(kbins('1123', 2, ordered=0))) == 5 + assert len(list(kbins('1123', 2, ordered=None))) == 3 + + def test1(): + for orderedval in [None, 0, 1, 10, 11]: + print('ordered =', orderedval) + for p in kbins([0, 0, 1], 2, ordered=orderedval): + print(' ', p) + assert capture(lambda : test1()) == dedent('''\ + ordered = None + [[0], [0, 1]] + [[0, 0], [1]] + ordered = 0 + [[0, 0], [1]] + [[0, 1], [0]] + ordered = 1 + [[0], [0, 1]] + [[0], [1, 0]] + [[1], [0, 0]] + ordered = 10 + [[0, 0], [1]] + [[1], [0, 0]] + [[0, 1], [0]] + [[0], [0, 1]] + ordered = 11 + [[0], [0, 1]] + [[0, 0], [1]] + [[0], [1, 0]] + [[0, 1], [0]] + [[1], [0, 0]] + [[1, 0], [0]]\n''') + + def test2(): + for orderedval in [None, 0, 1, 10, 11]: + print('ordered =', orderedval) + for p in kbins(list(range(3)), 2, ordered=orderedval): + print(' ', p) + assert capture(lambda : test2()) == dedent('''\ + ordered = None + [[0], [1, 2]] + [[0, 1], [2]] + ordered = 0 + [[0, 1], [2]] + [[0, 2], [1]] + [[0], [1, 2]] + ordered = 1 + [[0], [1, 2]] + [[0], [2, 1]] + [[1], [0, 2]] + [[1], [2, 0]] + [[2], [0, 1]] + [[2], [1, 0]] + ordered = 10 + [[0, 1], [2]] + [[2], [0, 1]] + [[0, 2], [1]] + [[1], [0, 2]] + [[0], [1, 2]] + [[1, 2], [0]] + ordered = 11 + [[0], [1, 2]] + [[0, 1], [2]] + [[0], [2, 1]] + [[0, 2], [1]] + [[1], [0, 2]] + [[1, 0], [2]] + [[1], [2, 0]] + [[1, 2], [0]] + [[2], [0, 1]] + [[2, 0], [1]] + [[2], [1, 0]] + [[2, 1], [0]]\n''') + + +def test_has_dups(): + assert has_dups(set()) is False + assert has_dups(list(range(3))) is False + assert has_dups([1, 2, 1]) is True + assert has_dups([[1], [1]]) is True + assert has_dups([[1], [2]]) is False + + +def test__partition(): + assert _partition('abcde', [1, 0, 1, 2, 0]) == [ + ['b', 'e'], ['a', 'c'], ['d']] + assert _partition('abcde', [1, 0, 1, 2, 0], 3) == [ + ['b', 'e'], ['a', 'c'], ['d']] + output = (3, [1, 0, 1, 2, 0]) + assert _partition('abcde', *output) == [['b', 'e'], ['a', 'c'], ['d']] + + +def test_ordered_partitions(): + from sympy.functions.combinatorial.numbers import nT + f = ordered_partitions + assert list(f(0, 1)) == [[]] + assert list(f(1, 0)) == [[]] + for i in range(1, 7): + for j in [None] + list(range(1, i)): + assert ( + sum(1 for p in f(i, j, 1)) == + sum(1 for p in f(i, j, 0)) == + nT(i, j)) + + +def test_rotations(): + assert list(rotations('ab')) == [['a', 'b'], ['b', 'a']] + assert list(rotations(range(3))) == [[0, 1, 2], [1, 2, 0], [2, 0, 1]] + assert list(rotations(range(3), dir=-1)) == [[0, 1, 2], [2, 0, 1], [1, 2, 0]] + + +def test_ibin(): + assert ibin(3) == [1, 1] + assert ibin(3, 3) == [0, 1, 1] + assert ibin(3, str=True) == '11' + assert ibin(3, 3, str=True) == '011' + assert list(ibin(2, 'all')) == [(0, 0), (0, 1), (1, 0), (1, 1)] + assert list(ibin(2, '', str=True)) == ['00', '01', '10', '11'] + raises(ValueError, lambda: ibin(-.5)) + raises(ValueError, lambda: ibin(2, 1)) + + +def test_iterable(): + assert iterable(0) is False + assert iterable(1) is False + assert iterable(None) is False + + class Test1(NotIterable): + pass + + assert iterable(Test1()) is False + + class Test2(NotIterable): + _iterable = True + + assert iterable(Test2()) is True + + class Test3: + pass + + assert iterable(Test3()) is False + + class Test4: + _iterable = True + + assert iterable(Test4()) is True + + class Test5: + def __iter__(self): + yield 1 + + assert iterable(Test5()) is True + + class Test6(Test5): + _iterable = False + + assert iterable(Test6()) is False + + +def test_sequence_partitions(): + assert list(sequence_partitions([1], 1)) == [[[1]]] + assert list(sequence_partitions([1, 2], 1)) == [[[1, 2]]] + assert list(sequence_partitions([1, 2], 2)) == [[[1], [2]]] + assert list(sequence_partitions([1, 2, 3], 1)) == [[[1, 2, 3]]] + assert list(sequence_partitions([1, 2, 3], 2)) == \ + [[[1], [2, 3]], [[1, 2], [3]]] + assert list(sequence_partitions([1, 2, 3], 3)) == [[[1], [2], [3]]] + + # Exceptional cases + assert list(sequence_partitions([], 0)) == [] + assert list(sequence_partitions([], 1)) == [] + assert list(sequence_partitions([1, 2], 0)) == [] + assert list(sequence_partitions([1, 2], 3)) == [] + + +def test_sequence_partitions_empty(): + assert list(sequence_partitions_empty([], 1)) == [[[]]] + assert list(sequence_partitions_empty([], 2)) == [[[], []]] + assert list(sequence_partitions_empty([], 3)) == [[[], [], []]] + assert list(sequence_partitions_empty([1], 1)) == [[[1]]] + assert list(sequence_partitions_empty([1], 2)) == [[[], [1]], [[1], []]] + assert list(sequence_partitions_empty([1], 3)) == \ + [[[], [], [1]], [[], [1], []], [[1], [], []]] + assert list(sequence_partitions_empty([1, 2], 1)) == [[[1, 2]]] + assert list(sequence_partitions_empty([1, 2], 2)) == \ + [[[], [1, 2]], [[1], [2]], [[1, 2], []]] + assert list(sequence_partitions_empty([1, 2], 3)) == [ + [[], [], [1, 2]], [[], [1], [2]], [[], [1, 2], []], + [[1], [], [2]], [[1], [2], []], [[1, 2], [], []] + ] + assert list(sequence_partitions_empty([1, 2, 3], 1)) == [[[1, 2, 3]]] + assert list(sequence_partitions_empty([1, 2, 3], 2)) == \ + [[[], [1, 2, 3]], [[1], [2, 3]], [[1, 2], [3]], [[1, 2, 3], []]] + assert list(sequence_partitions_empty([1, 2, 3], 3)) == [ + [[], [], [1, 2, 3]], [[], [1], [2, 3]], + [[], [1, 2], [3]], [[], [1, 2, 3], []], + [[1], [], [2, 3]], [[1], [2], [3]], + [[1], [2, 3], []], [[1, 2], [], [3]], + [[1, 2], [3], []], [[1, 2, 3], [], []] + ] + + # Exceptional cases + assert list(sequence_partitions([], 0)) == [] + assert list(sequence_partitions([1], 0)) == [] + assert list(sequence_partitions([1, 2], 0)) == [] + + +def test_signed_permutations(): + ans = [(0, 1, 1), (0, -1, 1), (0, 1, -1), (0, -1, -1), + (1, 0, 1), (-1, 0, 1), (1, 0, -1), (-1, 0, -1), + (1, 1, 0), (-1, 1, 0), (1, -1, 0), (-1, -1, 0)] + assert list(signed_permutations((0, 1, 1))) == ans + assert list(signed_permutations((1, 0, 1))) == ans + assert list(signed_permutations((1, 1, 0))) == ans diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_lambdify.py b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_lambdify.py new file mode 100644 index 0000000000000000000000000000000000000000..b094c67d39f09c24bcb9abc1e755cb5328e143e7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_lambdify.py @@ -0,0 +1,2263 @@ +from itertools import product +import math +import inspect +import linecache +import gc + +import mpmath +import cmath + +from sympy.testing.pytest import raises, warns_deprecated_sympy +from sympy.concrete.summations import Sum +from sympy.core.function import (Function, Lambda, diff) +from sympy.core.numbers import (E, Float, I, Rational, all_close, oo, pi) +from sympy.core.relational import Eq +from sympy.core.singleton import S +from sympy.core.symbol import (Dummy, symbols) +from sympy.functions.combinatorial.factorials import (RisingFactorial, factorial) +from sympy.functions.combinatorial.numbers import bernoulli, harmonic +from sympy.functions.elementary.complexes import Abs, sign +from sympy.functions.elementary.exponential import exp, log +from sympy.functions.elementary.hyperbolic import asinh,acosh,atanh +from sympy.functions.elementary.integers import floor +from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt) +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.elementary.trigonometric import (asin, acos, atan, cos, cot, sin, + sinc, tan) +from sympy.functions import sinh,cosh,tanh +from sympy.functions.special.bessel import (besseli, besselj, besselk, bessely, jn, yn) +from sympy.functions.special.beta_functions import (beta, betainc, betainc_regularized) +from sympy.functions.special.delta_functions import (Heaviside) +from sympy.functions.special.error_functions import (Ei, erf, erfc, fresnelc, fresnels, Si, Ci) +from sympy.functions.special.gamma_functions import (digamma, gamma, loggamma, polygamma) +from sympy.functions.special.zeta_functions import zeta +from sympy.integrals.integrals import Integral +from sympy.logic.boolalg import (And, false, ITE, Not, Or, true) +from sympy.matrices.expressions.dotproduct import DotProduct +from sympy.simplify.cse_main import cse +from sympy.tensor.array import derive_by_array, Array +from sympy.tensor.array.expressions import ArraySymbol +from sympy.tensor.indexed import IndexedBase, Idx +from sympy.utilities.lambdify import lambdify +from sympy.utilities.iterables import numbered_symbols +from sympy.vector import CoordSys3D +from sympy.core.expr import UnevaluatedExpr +from sympy.codegen.cfunctions import expm1, log1p, exp2, log2, log10, hypot, isnan, isinf +from sympy.codegen.numpy_nodes import logaddexp, logaddexp2, amin, amax, minimum, maximum +from sympy.codegen.scipy_nodes import cosm1, powm1 +from sympy.functions.elementary.complexes import re, im, arg +from sympy.functions.special.polynomials import \ + chebyshevt, chebyshevu, legendre, hermite, laguerre, gegenbauer, \ + assoc_legendre, assoc_laguerre, jacobi +from sympy.matrices import Matrix, MatrixSymbol, SparseMatrix +from sympy.printing.codeprinter import PrintMethodNotImplementedError +from sympy.printing.lambdarepr import LambdaPrinter +from sympy.printing.numpy import NumPyPrinter +from sympy.utilities.lambdify import implemented_function, lambdastr +from sympy.testing.pytest import skip +from sympy.utilities.decorator import conserve_mpmath_dps +from sympy.utilities.exceptions import ignore_warnings +from sympy.external import import_module +from sympy.functions.special.gamma_functions import uppergamma, lowergamma + + +import sympy + + +MutableDenseMatrix = Matrix + +numpy = import_module('numpy') +scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']}) +numexpr = import_module('numexpr') +tensorflow = import_module('tensorflow') +cupy = import_module('cupy') +jax = import_module('jax') +numba = import_module('numba') + +if tensorflow: + # Hide Tensorflow warnings + import os + os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' + +w, x, y, z = symbols('w,x,y,z') + +#================== Test different arguments ======================= + + +def test_no_args(): + f = lambdify([], 1) + raises(TypeError, lambda: f(-1)) + assert f() == 1 + + +def test_single_arg(): + f = lambdify(x, 2*x) + assert f(1) == 2 + + +def test_list_args(): + f = lambdify([x, y], x + y) + assert f(1, 2) == 3 + + +def test_nested_args(): + f1 = lambdify([[w, x]], [w, x]) + assert f1([91, 2]) == [91, 2] + raises(TypeError, lambda: f1(1, 2)) + + f2 = lambdify([(w, x), (y, z)], [w, x, y, z]) + assert f2((18, 12), (73, 4)) == [18, 12, 73, 4] + raises(TypeError, lambda: f2(3, 4)) + + f3 = lambdify([w, [[[x]], y], z], [w, x, y, z]) + assert f3(10, [[[52]], 31], 44) == [10, 52, 31, 44] + + +def test_str_args(): + f = lambdify('x,y,z', 'z,y,x') + assert f(3, 2, 1) == (1, 2, 3) + assert f(1.0, 2.0, 3.0) == (3.0, 2.0, 1.0) + # make sure correct number of args required + raises(TypeError, lambda: f(0)) + + +def test_own_namespace_1(): + myfunc = lambda x: 1 + f = lambdify(x, sin(x), {"sin": myfunc}) + assert f(0.1) == 1 + assert f(100) == 1 + + +def test_own_namespace_2(): + def myfunc(x): + return 1 + f = lambdify(x, sin(x), {'sin': myfunc}) + assert f(0.1) == 1 + assert f(100) == 1 + + +def test_own_module(): + f = lambdify(x, sin(x), math) + assert f(0) == 0.0 + + p, q, r = symbols("p q r", real=True) + ae = abs(exp(p+UnevaluatedExpr(q+r))) + f = lambdify([p, q, r], [ae, ae], modules=math) + results = f(1.0, 1e18, -1e18) + refvals = [math.exp(1.0)]*2 + for res, ref in zip(results, refvals): + assert abs((res-ref)/ref) < 1e-15 + + +def test_bad_args(): + # no vargs given + raises(TypeError, lambda: lambdify(1)) + # same with vector exprs + raises(TypeError, lambda: lambdify([1, 2])) + + +def test_atoms(): + # Non-Symbol atoms should not be pulled out from the expression namespace + f = lambdify(x, pi + x, {"pi": 3.14}) + assert f(0) == 3.14 + f = lambdify(x, I + x, {"I": 1j}) + assert f(1) == 1 + 1j + +#================== Test different modules ========================= + +# high precision output of sin(0.2*pi) is used to detect if precision is lost unwanted + + +@conserve_mpmath_dps +def test_sympy_lambda(): + mpmath.mp.dps = 50 + sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020") + f = lambdify(x, sin(x), "sympy") + assert f(x) == sin(x) + prec = 1e-15 + assert -prec < f(Rational(1, 5)).evalf() - Float(str(sin02)) < prec + # arctan is in numpy module and should not be available + # The arctan below gives NameError. What is this supposed to test? + # raises(NameError, lambda: lambdify(x, arctan(x), "sympy")) + + +@conserve_mpmath_dps +def test_math_lambda(): + mpmath.mp.dps = 50 + sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020") + f = lambdify(x, sin(x), "math") + prec = 1e-15 + assert -prec < f(0.2) - sin02 < prec + raises(TypeError, lambda: f(x)) + # if this succeeds, it can't be a Python math function + + +@conserve_mpmath_dps +def test_mpmath_lambda(): + mpmath.mp.dps = 50 + sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020") + f = lambdify(x, sin(x), "mpmath") + prec = 1e-49 # mpmath precision is around 50 decimal places + assert -prec < f(mpmath.mpf("0.2")) - sin02 < prec + raises(TypeError, lambda: f(x)) + # if this succeeds, it can't be a mpmath function + + ref2 = (mpmath.mpf("1e-30") + - mpmath.mpf("1e-45")/2 + + 5*mpmath.mpf("1e-60")/6 + - 3*mpmath.mpf("1e-75")/4 + + 33*mpmath.mpf("1e-90")/40 + ) + f2a = lambdify((x, y), x**y - 1, "mpmath") + f2b = lambdify((x, y), powm1(x, y), "mpmath") + f2c = lambdify((x,), expm1(x*log1p(x)), "mpmath") + ans2a = f2a(mpmath.mpf("1")+mpmath.mpf("1e-15"), mpmath.mpf("1e-15")) + ans2b = f2b(mpmath.mpf("1")+mpmath.mpf("1e-15"), mpmath.mpf("1e-15")) + ans2c = f2c(mpmath.mpf("1e-15")) + assert abs(ans2a - ref2) < 1e-51 + assert abs(ans2b - ref2) < 1e-67 + assert abs(ans2c - ref2) < 1e-80 + + +@conserve_mpmath_dps +def test_number_precision(): + mpmath.mp.dps = 50 + sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020") + f = lambdify(x, sin02, "mpmath") + prec = 1e-49 # mpmath precision is around 50 decimal places + assert -prec < f(0) - sin02 < prec + +@conserve_mpmath_dps +def test_mpmath_precision(): + mpmath.mp.dps = 100 + assert str(lambdify((), pi.evalf(100), 'mpmath')()) == str(pi.evalf(100)) + +#================== Test Translations ============================== +# We can only check if all translated functions are valid. It has to be checked +# by hand if they are complete. + + +def test_math_transl(): + from sympy.utilities.lambdify import MATH_TRANSLATIONS + for sym, mat in MATH_TRANSLATIONS.items(): + assert sym in sympy.__dict__ + assert mat in math.__dict__ + + +def test_mpmath_transl(): + from sympy.utilities.lambdify import MPMATH_TRANSLATIONS + for sym, mat in MPMATH_TRANSLATIONS.items(): + assert sym in sympy.__dict__ or sym == 'Matrix' + assert mat in mpmath.__dict__ + + +def test_numpy_transl(): + if not numpy: + skip("numpy not installed.") + + from sympy.utilities.lambdify import NUMPY_TRANSLATIONS + for sym, nump in NUMPY_TRANSLATIONS.items(): + assert sym in sympy.__dict__ + assert nump in numpy.__dict__ + + +def test_scipy_transl(): + if not scipy: + skip("scipy not installed.") + + from sympy.utilities.lambdify import SCIPY_TRANSLATIONS + for sym, scip in SCIPY_TRANSLATIONS.items(): + assert sym in sympy.__dict__ + assert scip in scipy.__dict__ or scip in scipy.special.__dict__ + + +def test_numpy_translation_abs(): + if not numpy: + skip("numpy not installed.") + + f = lambdify(x, Abs(x), "numpy") + assert f(-1) == 1 + assert f(1) == 1 + + +def test_numexpr_printer(): + if not numexpr: + skip("numexpr not installed.") + + # if translation/printing is done incorrectly then evaluating + # a lambdified numexpr expression will throw an exception + from sympy.printing.lambdarepr import NumExprPrinter + + blacklist = ('where', 'complex', 'contains') + arg_tuple = (x, y, z) # some functions take more than one argument + for sym in NumExprPrinter._numexpr_functions.keys(): + if sym in blacklist: + continue + ssym = S(sym) + if hasattr(ssym, '_nargs'): + nargs = ssym._nargs[0] + else: + nargs = 1 + args = arg_tuple[:nargs] + f = lambdify(args, ssym(*args), modules='numexpr') + assert f(*(1, )*nargs) is not None + + +def test_cmath_sqrt(): + f = lambdify(x, sqrt(x), "cmath") + assert f(0) == 0 + assert f(1) == 1 + assert f(4) == 2 + assert abs(f(2) - 1.414) < 0.001 + assert f(-1) == 1j + assert f(-4) == 2j + + +def test_cmath_log(): + f = lambdify(x, log(x), "cmath") + assert abs(f(1) - 0) < 1e-15 + assert abs(f(cmath.e) - 1) < 1e-15 + assert abs(f(-1) - cmath.log(-1)) < 1e-15 + + +def test_cmath_sinh(): + f = lambdify(x, sinh(x), "cmath") + assert abs(f(0) - cmath.sinh(0)) < 1e-15 + assert abs(f(pi) - cmath.sinh(pi)) < 1e-15 + assert abs(f(-pi) - cmath.sinh(-pi)) < 1e-15 + assert abs(f(1j) - cmath.sinh(1j)) < 1e-15 + + +def test_cmath_cosh(): + f = lambdify(x, cosh(x), "cmath") + assert abs(f(0) - cmath.cosh(0)) < 1e-15 + assert abs(f(pi) - cmath.cosh(pi)) < 1e-15 + assert abs(f(-pi) - cmath.cosh(-pi)) < 1e-15 + assert abs(f(1j) - cmath.cosh(1j)) < 1e-15 + + +def test_cmath_tanh(): + f = lambdify(x, tanh(x), "cmath") + assert abs(f(0) - cmath.tanh(0)) < 1e-15 + assert abs(f(pi) - cmath.tanh(pi)) < 1e-15 + assert abs(f(-pi) - cmath.tanh(-pi)) < 1e-15 + assert abs(f(1j) - cmath.tanh(1j)) < 1e-15 + + +def test_cmath_sin(): + f = lambdify(x, sin(x), "cmath") + assert abs(f(0) - cmath.sin(0)) < 1e-15 + assert abs(f(pi) - cmath.sin(pi)) < 1e-15 + assert abs(f(-pi) - cmath.sin(-pi)) < 1e-15 + assert abs(f(1j) - cmath.sin(1j)) < 1e-15 + + +def test_cmath_cos(): + f = lambdify(x, cos(x), "cmath") + assert abs(f(0) - cmath.cos(0)) < 1e-15 + assert abs(f(pi) - cmath.cos(pi)) < 1e-15 + assert abs(f(-pi) - cmath.cos(-pi)) < 1e-15 + assert abs(f(1j) - cmath.cos(1j)) < 1e-15 + + +def test_cmath_tan(): + f = lambdify(x, tan(x), "cmath") + assert abs(f(0) - cmath.tan(0)) < 1e-15 + assert abs(f(1j) - cmath.tan(1j)) < 1e-15 + + +def test_cmath_asin(): + f = lambdify(x, asin(x), "cmath") + assert abs(f(0) - cmath.asin(0)) < 1e-15 + assert abs(f(1) - cmath.asin(1)) < 1e-15 + assert abs(f(-1) - cmath.asin(-1)) < 1e-15 + assert abs(f(2) - cmath.asin(2)) < 1e-15 + assert abs(f(1j) - cmath.asin(1j)) < 1e-15 + + +def test_cmath_acos(): + f = lambdify(x, acos(x), "cmath") + assert abs(f(1) - cmath.acos(1)) < 1e-15 + assert abs(f(-1) - cmath.acos(-1)) < 1e-15 + assert abs(f(2) - cmath.acos(2)) < 1e-15 + assert abs(f(1j) - cmath.acos(1j)) < 1e-15 + + +def test_cmath_atan(): + f = lambdify(x, atan(x), "cmath") + assert abs(f(0) - cmath.atan(0)) < 1e-15 + assert abs(f(1) - cmath.atan(1)) < 1e-15 + assert abs(f(-1) - cmath.atan(-1)) < 1e-15 + assert abs(f(2) - cmath.atan(2)) < 1e-15 + assert abs(f(2j) - cmath.atan(2j)) < 1e-15 + + +def test_cmath_asinh(): + f = lambdify(x, asinh(x), "cmath") + assert abs(f(0) - cmath.asinh(0)) < 1e-15 + assert abs(f(1) - cmath.asinh(1)) < 1e-15 + assert abs(f(-1) - cmath.asinh(-1)) < 1e-15 + assert abs(f(2) - cmath.asinh(2)) < 1e-15 + assert abs(f(2j) - cmath.asinh(2j)) < 1e-15 + + +def test_cmath_acosh(): + f = lambdify(x, acosh(x), "cmath") + assert abs(f(1) - cmath.acosh(1)) < 1e-15 + assert abs(f(2) - cmath.acosh(2)) < 1e-15 + assert abs(f(-1) - cmath.acosh(-1)) < 1e-15 + assert abs(f(2j) - cmath.acosh(2j)) < 1e-15 + + +def test_cmath_atanh(): + f = lambdify(x, atanh(x), "cmath") + assert abs(f(0) - cmath.atanh(0)) < 1e-15 + assert abs(f(0.5) - cmath.atanh(0.5)) < 1e-15 + assert abs(f(-0.5) - cmath.atanh(-0.5)) < 1e-15 + assert abs(f(2) - cmath.atanh(2)) < 1e-15 + assert abs(f(-2) - cmath.atanh(-2)) < 1e-15 + assert abs(f(2j) - cmath.atanh(2j)) < 1e-15 + + +def test_cmath_complex_identities(): + # Define symbol + z = symbols('z') + + # Trigonometric identity using re(z) and im(z) + expr = cos(z) - cos(re(z)) * cosh(im(z)) + I * sin(re(z)) * sinh(im(z)) + func = lambdify([z], expr, modules=["cmath", "math"]) + hpi = math.pi / 2 + assert abs(func(hpi + 1j * hpi)) < 4e-16 + + # Euler's Formula: e^(i*z) = cos(z) + i*sin(z) + func = lambdify([z], exp(I * z) - (cos(z) + I * sin(z)), modules=["cmath", "math"]) + assert abs(func(hpi)) < 4e-16 + + # Exponential Identity: e^z = e^(Re(z)) * (cos(Im(z)) + i*sin(Im(z))) + func_exp = lambdify([z], exp(z) - exp(re(z)) * (cos(im(z)) + I * sin(im(z))), + modules=["cmath", "math"]) + assert abs(func_exp(hpi + 1j * hpi)) < 4e-16 + + # Complex Cosine Identity: cos(z) = cos(Re(z)) * cosh(Im(z)) - i*sin(Re(z)) * sinh(Im(z)) + func_cos = lambdify([z], cos(z) - (cos(re(z)) * cosh(im(z)) - I * sin(re(z)) * sinh(im(z))), + modules=["cmath", "math"]) + assert abs(func_cos(hpi + 1j * hpi)) < 4e-16 + + # Complex Sine Identity: sin(z) = sin(Re(z)) * cosh(Im(z)) + i*cos(Re(z)) * sinh(Im(z)) + func_sin = lambdify([z], sin(z) - (sin(re(z)) * cosh(im(z)) + I * cos(re(z)) * sinh(im(z))), + modules=["cmath", "math"]) + assert abs(func_sin(hpi + 1j * hpi)) < 4e-16 + + # Complex Hyperbolic Cosine Identity: cosh(z) = cosh(Re(z)) * cos(Im(z)) + i*sinh(Re(z)) * sin(Im(z)) + func_cosh_1 = lambdify([z], cosh(z) - (cosh(re(z)) * cos(im(z)) + I * sinh(re(z)) * sin(im(z))), + modules=["cmath", "math"]) + assert abs(func_cosh_1(hpi + 1j * hpi)) < 4e-16 + + # Complex Hyperbolic Sine Identity: sinh(z) = sinh(Re(z)) * cos(Im(z)) + i*cosh(Re(z)) * sin(Im(z)) + func_sinh = lambdify([z], sinh(z) - (sinh(re(z)) * cos(im(z)) + I * cosh(re(z)) * sin(im(z))), + modules=["cmath", "math"]) + assert abs(func_sinh(hpi + 1j * hpi)) < 4e-16 + + # cosh(z) = (e^z + e^(-z)) / 2 + func_cosh_2 = lambdify([z], cosh(z) - (exp(z) + exp(-z)) / 2, modules=["cmath", "math"]) + assert abs(func_cosh_2(hpi)) < 4e-16 + + # Additional expressions testing log and exp with real and imaginary parts + expr1 = log(re(z)) + log(im(z)) - log(re(z) * im(z)) + expr2 = exp(re(z)) * exp(im(z) * I) - exp(z) + expr3 = log(exp(re(z))) - re(z) + expr4 = exp(log(re(z))) - re(z) + expr5 = log(exp(re(z) + im(z))) - (re(z) + im(z)) + expr6 = exp(log(re(z) + im(z))) - (re(z) + im(z)) + func1 = lambdify([z], expr1, modules=["cmath", "math"]) + func2 = lambdify([z], expr2, modules=["cmath", "math"]) + func3 = lambdify([z], expr3, modules=["cmath", "math"]) + func4 = lambdify([z], expr4, modules=["cmath", "math"]) + func5 = lambdify([z], expr5, modules=["cmath", "math"]) + func6 = lambdify([z], expr6, modules=["cmath", "math"]) + test_value = 3 + 4j + assert abs(func1(test_value)) < 4e-16 + assert abs(func2(test_value)) < 4e-16 + assert abs(func3(test_value)) < 4e-16 + assert abs(func4(test_value)) < 4e-16 + assert abs(func5(test_value)) < 4e-16 + assert abs(func6(test_value)) < 4e-16 + + +def test_issue_9334(): + if not numexpr: + skip("numexpr not installed.") + if not numpy: + skip("numpy not installed.") + expr = S('b*a - sqrt(a**2)') + a, b = sorted(expr.free_symbols, key=lambda s: s.name) + func_numexpr = lambdify((a,b), expr, modules=[numexpr], dummify=False) + foo, bar = numpy.random.random((2, 4)) + func_numexpr(foo, bar) + + +def test_issue_12984(): + if not numexpr: + skip("numexpr not installed.") + func_numexpr = lambdify((x,y,z), Piecewise((y, x >= 0), (z, x > -1)), numexpr) + with ignore_warnings(RuntimeWarning): + assert func_numexpr(1, 24, 42) == 24 + assert str(func_numexpr(-1, 24, 42)) == 'nan' + + +def test_empty_modules(): + x, y = symbols('x y') + expr = -(x % y) + + no_modules = lambdify([x, y], expr) + empty_modules = lambdify([x, y], expr, modules=[]) + assert no_modules(3, 7) == empty_modules(3, 7) + assert no_modules(3, 7) == -3 + + +def test_exponentiation(): + f = lambdify(x, x**2) + assert f(-1) == 1 + assert f(0) == 0 + assert f(1) == 1 + assert f(-2) == 4 + assert f(2) == 4 + assert f(2.5) == 6.25 + + +def test_sqrt(): + f = lambdify(x, sqrt(x)) + assert f(0) == 0.0 + assert f(1) == 1.0 + assert f(4) == 2.0 + assert abs(f(2) - 1.414) < 0.001 + assert f(6.25) == 2.5 + + +def test_trig(): + f = lambdify([x], [cos(x), sin(x)], 'math') + d = f(pi) + prec = 1e-11 + assert -prec < d[0] + 1 < prec + assert -prec < d[1] < prec + d = f(3.14159) + prec = 1e-5 + assert -prec < d[0] + 1 < prec + assert -prec < d[1] < prec + + +def test_integral(): + if numpy and not scipy: + skip("scipy not installed.") + f = Lambda(x, exp(-x**2)) + l = lambdify(y, Integral(f(x), (x, y, oo))) + d = l(-oo) + assert 1.77245385 < d < 1.772453851 + + +def test_double_integral(): + if numpy and not scipy: + skip("scipy not installed.") + # example from http://mpmath.org/doc/current/calculus/integration.html + i = Integral(1/(1 - x**2*y**2), (x, 0, 1), (y, 0, z)) + l = lambdify([z], i) + d = l(1) + assert 1.23370055 < d < 1.233700551 + +def test_spherical_bessel(): + if numpy and not scipy: + skip("scipy not installed.") + test_point = 4.2 #randomly selected + x = symbols("x") + jtest = jn(2, x) + assert abs(lambdify(x,jtest)(test_point) - + jtest.subs(x,test_point).evalf()) < 1e-8 + ytest = yn(2, x) + assert abs(lambdify(x,ytest)(test_point) - + ytest.subs(x,test_point).evalf()) < 1e-8 + + +#================== Test vectors =================================== + + +def test_vector_simple(): + f = lambdify((x, y, z), (z, y, x)) + assert f(3, 2, 1) == (1, 2, 3) + assert f(1.0, 2.0, 3.0) == (3.0, 2.0, 1.0) + # make sure correct number of args required + raises(TypeError, lambda: f(0)) + + +def test_vector_discontinuous(): + f = lambdify(x, (-1/x, 1/x)) + raises(ZeroDivisionError, lambda: f(0)) + assert f(1) == (-1.0, 1.0) + assert f(2) == (-0.5, 0.5) + assert f(-2) == (0.5, -0.5) + + +def test_trig_symbolic(): + f = lambdify([x], [cos(x), sin(x)], 'math') + d = f(pi) + assert abs(d[0] + 1) < 0.0001 + assert abs(d[1] - 0) < 0.0001 + + +def test_trig_float(): + f = lambdify([x], [cos(x), sin(x)]) + d = f(3.14159) + assert abs(d[0] + 1) < 0.0001 + assert abs(d[1] - 0) < 0.0001 + + +def test_docs(): + f = lambdify(x, x**2) + assert f(2) == 4 + f = lambdify([x, y, z], [z, y, x]) + assert f(1, 2, 3) == [3, 2, 1] + f = lambdify(x, sqrt(x)) + assert f(4) == 2.0 + f = lambdify((x, y), sin(x*y)**2) + assert f(0, 5) == 0 + + +def test_math(): + f = lambdify((x, y), sin(x), modules="math") + assert f(0, 5) == 0 + + +def test_sin(): + f = lambdify(x, sin(x)**2) + assert isinstance(f(2), float) + f = lambdify(x, sin(x)**2, modules="math") + assert isinstance(f(2), float) + + +def test_matrix(): + A = Matrix([[x, x*y], [sin(z) + 4, x**z]]) + sol = Matrix([[1, 2], [sin(3) + 4, 1]]) + f = lambdify((x, y, z), A, modules="sympy") + assert f(1, 2, 3) == sol + f = lambdify((x, y, z), (A, [A]), modules="sympy") + assert f(1, 2, 3) == (sol, [sol]) + J = Matrix((x, x + y)).jacobian((x, y)) + v = Matrix((x, y)) + sol = Matrix([[1, 0], [1, 1]]) + assert lambdify(v, J, modules='sympy')(1, 2) == sol + assert lambdify(v.T, J, modules='sympy')(1, 2) == sol + + +def test_numpy_matrix(): + if not numpy: + skip("numpy not installed.") + A = Matrix([[x, x*y], [sin(z) + 4, x**z]]) + sol_arr = numpy.array([[1, 2], [numpy.sin(3) + 4, 1]]) + #Lambdify array first, to ensure return to array as default + f = lambdify((x, y, z), A, ['numpy']) + numpy.testing.assert_allclose(f(1, 2, 3), sol_arr) + #Check that the types are arrays and matrices + assert isinstance(f(1, 2, 3), numpy.ndarray) + + # gh-15071 + class dot(Function): + pass + x_dot_mtx = dot(x, Matrix([[2], [1], [0]])) + f_dot1 = lambdify(x, x_dot_mtx) + inp = numpy.zeros((17, 3)) + assert numpy.all(f_dot1(inp) == 0) + + strict_kw = {"allow_unknown_functions": False, "inline": True, "fully_qualified_modules": False} + p2 = NumPyPrinter(dict(user_functions={'dot': 'dot'}, **strict_kw)) + f_dot2 = lambdify(x, x_dot_mtx, printer=p2) + assert numpy.all(f_dot2(inp) == 0) + + p3 = NumPyPrinter(strict_kw) + # The line below should probably fail upon construction (before calling with "(inp)"): + raises(Exception, lambda: lambdify(x, x_dot_mtx, printer=p3)(inp)) + + +def test_numpy_transpose(): + if not numpy: + skip("numpy not installed.") + A = Matrix([[1, x], [0, 1]]) + f = lambdify((x), A.T, modules="numpy") + numpy.testing.assert_array_equal(f(2), numpy.array([[1, 0], [2, 1]])) + + +def test_numpy_dotproduct(): + if not numpy: + skip("numpy not installed") + A = Matrix([x, y, z]) + f1 = lambdify([x, y, z], DotProduct(A, A), modules='numpy') + f2 = lambdify([x, y, z], DotProduct(A, A.T), modules='numpy') + f3 = lambdify([x, y, z], DotProduct(A.T, A), modules='numpy') + f4 = lambdify([x, y, z], DotProduct(A, A.T), modules='numpy') + + assert f1(1, 2, 3) == \ + f2(1, 2, 3) == \ + f3(1, 2, 3) == \ + f4(1, 2, 3) == \ + numpy.array([14]) + + +def test_numpy_inverse(): + if not numpy: + skip("numpy not installed.") + A = Matrix([[1, x], [0, 1]]) + f = lambdify((x), A**-1, modules="numpy") + numpy.testing.assert_array_equal(f(2), numpy.array([[1, -2], [0, 1]])) + + +def test_numpy_old_matrix(): + if not numpy: + skip("numpy not installed.") + A = Matrix([[x, x*y], [sin(z) + 4, x**z]]) + sol_arr = numpy.array([[1, 2], [numpy.sin(3) + 4, 1]]) + f = lambdify((x, y, z), A, [{'ImmutableDenseMatrix': numpy.matrix}, 'numpy']) + with ignore_warnings(PendingDeprecationWarning): + numpy.testing.assert_allclose(f(1, 2, 3), sol_arr) + assert isinstance(f(1, 2, 3), numpy.matrix) + + +def test_scipy_sparse_matrix(): + if not scipy: + skip("scipy not installed.") + A = SparseMatrix([[x, 0], [0, y]]) + f = lambdify((x, y), A, modules="scipy") + B = f(1, 2) + assert isinstance(B, scipy.sparse.coo_matrix) + + +def test_python_div_zero_issue_11306(): + if not numpy: + skip("numpy not installed.") + p = Piecewise((1 / x, y < -1), (x, y < 1), (1 / x, True)) + f = lambdify([x, y], p, modules='numpy') + with numpy.errstate(divide='ignore'): + assert float(f(numpy.array(0), numpy.array(0.5))) == 0 + assert float(f(numpy.array(0), numpy.array(1))) == float('inf') + + +def test_issue9474(): + mods = [None, 'math'] + if numpy: + mods.append('numpy') + if mpmath: + mods.append('mpmath') + for mod in mods: + f = lambdify(x, S.One/x, modules=mod) + assert f(2) == 0.5 + f = lambdify(x, floor(S.One/x), modules=mod) + assert f(2) == 0 + + for absfunc, modules in product([Abs, abs], mods): + f = lambdify(x, absfunc(x), modules=modules) + assert f(-1) == 1 + assert f(1) == 1 + assert f(3+4j) == 5 + + +def test_issue_9871(): + if not numexpr: + skip("numexpr not installed.") + if not numpy: + skip("numpy not installed.") + + r = sqrt(x**2 + y**2) + expr = diff(1/r, x) + + xn = yn = numpy.linspace(1, 10, 16) + # expr(xn, xn) = -xn/(sqrt(2)*xn)^3 + fv_exact = -numpy.sqrt(2.)**-3 * xn**-2 + + fv_numpy = lambdify((x, y), expr, modules='numpy')(xn, yn) + fv_numexpr = lambdify((x, y), expr, modules='numexpr')(xn, yn) + numpy.testing.assert_allclose(fv_numpy, fv_exact, rtol=1e-10) + numpy.testing.assert_allclose(fv_numexpr, fv_exact, rtol=1e-10) + + +def test_numpy_piecewise(): + if not numpy: + skip("numpy not installed.") + pieces = Piecewise((x, x < 3), (x**2, x > 5), (0, True)) + f = lambdify(x, pieces, modules="numpy") + numpy.testing.assert_array_equal(f(numpy.arange(10)), + numpy.array([0, 1, 2, 0, 0, 0, 36, 49, 64, 81])) + # If we evaluate somewhere all conditions are False, we should get back NaN + nodef_func = lambdify(x, Piecewise((x, x > 0), (-x, x < 0))) + numpy.testing.assert_array_equal(nodef_func(numpy.array([-1, 0, 1])), + numpy.array([1, numpy.nan, 1])) + + +def test_numpy_logical_ops(): + if not numpy: + skip("numpy not installed.") + and_func = lambdify((x, y), And(x, y), modules="numpy") + and_func_3 = lambdify((x, y, z), And(x, y, z), modules="numpy") + or_func = lambdify((x, y), Or(x, y), modules="numpy") + or_func_3 = lambdify((x, y, z), Or(x, y, z), modules="numpy") + not_func = lambdify((x), Not(x), modules="numpy") + arr1 = numpy.array([True, True]) + arr2 = numpy.array([False, True]) + arr3 = numpy.array([True, False]) + numpy.testing.assert_array_equal(and_func(arr1, arr2), numpy.array([False, True])) + numpy.testing.assert_array_equal(and_func_3(arr1, arr2, arr3), numpy.array([False, False])) + numpy.testing.assert_array_equal(or_func(arr1, arr2), numpy.array([True, True])) + numpy.testing.assert_array_equal(or_func_3(arr1, arr2, arr3), numpy.array([True, True])) + numpy.testing.assert_array_equal(not_func(arr2), numpy.array([True, False])) + + +def test_numpy_matmul(): + if not numpy: + skip("numpy not installed.") + xmat = Matrix([[x, y], [z, 1+z]]) + ymat = Matrix([[x**2], [Abs(x)]]) + mat_func = lambdify((x, y, z), xmat*ymat, modules="numpy") + numpy.testing.assert_array_equal(mat_func(0.5, 3, 4), numpy.array([[1.625], [3.5]])) + numpy.testing.assert_array_equal(mat_func(-0.5, 3, 4), numpy.array([[1.375], [3.5]])) + # Multiple matrices chained together in multiplication + f = lambdify((x, y, z), xmat*xmat*xmat, modules="numpy") + numpy.testing.assert_array_equal(f(0.5, 3, 4), numpy.array([[72.125, 119.25], + [159, 251]])) + + +def test_numpy_numexpr(): + if not numpy: + skip("numpy not installed.") + if not numexpr: + skip("numexpr not installed.") + a, b, c = numpy.random.randn(3, 128, 128) + # ensure that numpy and numexpr return same value for complicated expression + expr = sin(x) + cos(y) + tan(z)**2 + Abs(z-y)*acos(sin(y*z)) + \ + Abs(y-z)*acosh(2+exp(y-x))- sqrt(x**2+I*y**2) + npfunc = lambdify((x, y, z), expr, modules='numpy') + nefunc = lambdify((x, y, z), expr, modules='numexpr') + assert numpy.allclose(npfunc(a, b, c), nefunc(a, b, c)) + + +def test_numexpr_userfunctions(): + if not numpy: + skip("numpy not installed.") + if not numexpr: + skip("numexpr not installed.") + a, b = numpy.random.randn(2, 10) + uf = type('uf', (Function, ), + {'eval' : classmethod(lambda x, y : y**2+1)}) + func = lambdify(x, 1-uf(x), modules='numexpr') + assert numpy.allclose(func(a), -(a**2)) + + uf = implemented_function(Function('uf'), lambda x, y : 2*x*y+1) + func = lambdify((x, y), uf(x, y), modules='numexpr') + assert numpy.allclose(func(a, b), 2*a*b+1) + + +def test_tensorflow_basic_math(): + if not tensorflow: + skip("tensorflow not installed.") + expr = Max(sin(x), Abs(1/(x+2))) + func = lambdify(x, expr, modules="tensorflow") + + with tensorflow.compat.v1.Session() as s: + a = tensorflow.constant(0, dtype=tensorflow.float32) + assert func(a).eval(session=s) == 0.5 + + +def test_tensorflow_placeholders(): + if not tensorflow: + skip("tensorflow not installed.") + expr = Max(sin(x), Abs(1/(x+2))) + func = lambdify(x, expr, modules="tensorflow") + + with tensorflow.compat.v1.Session() as s: + a = tensorflow.compat.v1.placeholder(dtype=tensorflow.float32) + assert func(a).eval(session=s, feed_dict={a: 0}) == 0.5 + + +def test_tensorflow_variables(): + if not tensorflow: + skip("tensorflow not installed.") + expr = Max(sin(x), Abs(1/(x+2))) + func = lambdify(x, expr, modules="tensorflow") + + with tensorflow.compat.v1.Session() as s: + a = tensorflow.Variable(0, dtype=tensorflow.float32) + s.run(a.initializer) + assert func(a).eval(session=s, feed_dict={a: 0}) == 0.5 + + +def test_tensorflow_logical_operations(): + if not tensorflow: + skip("tensorflow not installed.") + expr = Not(And(Or(x, y), y)) + func = lambdify([x, y], expr, modules="tensorflow") + + with tensorflow.compat.v1.Session() as s: + assert func(False, True).eval(session=s) == False + + +def test_tensorflow_piecewise(): + if not tensorflow: + skip("tensorflow not installed.") + expr = Piecewise((0, Eq(x,0)), (-1, x < 0), (1, x > 0)) + func = lambdify(x, expr, modules="tensorflow") + + with tensorflow.compat.v1.Session() as s: + assert func(-1).eval(session=s) == -1 + assert func(0).eval(session=s) == 0 + assert func(1).eval(session=s) == 1 + + +def test_tensorflow_multi_max(): + if not tensorflow: + skip("tensorflow not installed.") + expr = Max(x, -x, x**2) + func = lambdify(x, expr, modules="tensorflow") + + with tensorflow.compat.v1.Session() as s: + assert func(-2).eval(session=s) == 4 + + +def test_tensorflow_multi_min(): + if not tensorflow: + skip("tensorflow not installed.") + expr = Min(x, -x, x**2) + func = lambdify(x, expr, modules="tensorflow") + + with tensorflow.compat.v1.Session() as s: + assert func(-2).eval(session=s) == -2 + + +def test_tensorflow_relational(): + if not tensorflow: + skip("tensorflow not installed.") + expr = x >= 0 + func = lambdify(x, expr, modules="tensorflow") + + with tensorflow.compat.v1.Session() as s: + assert func(1).eval(session=s) == True + + +def test_tensorflow_complexes(): + if not tensorflow: + skip("tensorflow not installed") + + func1 = lambdify(x, re(x), modules="tensorflow") + func2 = lambdify(x, im(x), modules="tensorflow") + func3 = lambdify(x, Abs(x), modules="tensorflow") + func4 = lambdify(x, arg(x), modules="tensorflow") + + with tensorflow.compat.v1.Session() as s: + # For versions before + # https://github.com/tensorflow/tensorflow/issues/30029 + # resolved, using Python numeric types may not work + a = tensorflow.constant(1+2j) + assert func1(a).eval(session=s) == 1 + assert func2(a).eval(session=s) == 2 + + tensorflow_result = func3(a).eval(session=s) + sympy_result = Abs(1 + 2j).evalf() + assert abs(tensorflow_result-sympy_result) < 10**-6 + + tensorflow_result = func4(a).eval(session=s) + sympy_result = arg(1 + 2j).evalf() + assert abs(tensorflow_result-sympy_result) < 10**-6 + + +def test_tensorflow_array_arg(): + # Test for issue 14655 (tensorflow part) + if not tensorflow: + skip("tensorflow not installed.") + + f = lambdify([[x, y]], x*x + y, 'tensorflow') + + with tensorflow.compat.v1.Session() as s: + fcall = f(tensorflow.constant([2.0, 1.0])) + assert fcall.eval(session=s) == 5.0 + + +#================== Test symbolic ================================== + + +def test_sym_single_arg(): + f = lambdify(x, x * y) + assert f(z) == z * y + + +def test_sym_list_args(): + f = lambdify([x, y], x + y + z) + assert f(1, 2) == 3 + z + + +def test_sym_integral(): + f = Lambda(x, exp(-x**2)) + l = lambdify(x, Integral(f(x), (x, -oo, oo)), modules="sympy") + assert l(y) == Integral(exp(-y**2), (y, -oo, oo)) + assert l(y).doit() == sqrt(pi) + + +def test_namespace_order(): + # lambdify had a bug, such that module dictionaries or cached module + # dictionaries would pull earlier namespaces into themselves. + # Because the module dictionaries form the namespace of the + # generated lambda, this meant that the behavior of a previously + # generated lambda function could change as a result of later calls + # to lambdify. + n1 = {'f': lambda x: 'first f'} + n2 = {'f': lambda x: 'second f', + 'g': lambda x: 'function g'} + f = sympy.Function('f') + g = sympy.Function('g') + if1 = lambdify(x, f(x), modules=(n1, "sympy")) + assert if1(1) == 'first f' + if2 = lambdify(x, g(x), modules=(n2, "sympy")) + # previously gave 'second f' + assert if1(1) == 'first f' + + assert if2(1) == 'function g' + + +def test_imps(): + # Here we check if the default returned functions are anonymous - in + # the sense that we can have more than one function with the same name + f = implemented_function('f', lambda x: 2*x) + g = implemented_function('f', lambda x: math.sqrt(x)) + l1 = lambdify(x, f(x)) + l2 = lambdify(x, g(x)) + assert str(f(x)) == str(g(x)) + assert l1(3) == 6 + assert l2(3) == math.sqrt(3) + # check that we can pass in a Function as input + func = sympy.Function('myfunc') + assert not hasattr(func, '_imp_') + my_f = implemented_function(func, lambda x: 2*x) + assert hasattr(my_f, '_imp_') + # Error for functions with same name and different implementation + f2 = implemented_function("f", lambda x: x + 101) + raises(ValueError, lambda: lambdify(x, f(f2(x)))) + + +def test_imps_errors(): + # Test errors that implemented functions can return, and still be able to + # form expressions. + # See: https://github.com/sympy/sympy/issues/10810 + # + # XXX: Removed AttributeError here. This test was added due to issue 10810 + # but that issue was about ValueError. It doesn't seem reasonable to + # "support" catching AttributeError in the same context... + for val, error_class in product((0, 0., 2, 2.0), (TypeError, ValueError)): + + def myfunc(a): + if a == 0: + raise error_class + return 1 + + f = implemented_function('f', myfunc) + expr = f(val) + assert expr == f(val) + + +def test_imps_wrong_args(): + raises(ValueError, lambda: implemented_function(sin, lambda x: x)) + + +def test_lambdify_imps(): + # Test lambdify with implemented functions + # first test basic (sympy) lambdify + f = sympy.cos + assert lambdify(x, f(x))(0) == 1 + assert lambdify(x, 1 + f(x))(0) == 2 + assert lambdify((x, y), y + f(x))(0, 1) == 2 + # make an implemented function and test + f = implemented_function("f", lambda x: x + 100) + assert lambdify(x, f(x))(0) == 100 + assert lambdify(x, 1 + f(x))(0) == 101 + assert lambdify((x, y), y + f(x))(0, 1) == 101 + # Can also handle tuples, lists, dicts as expressions + lam = lambdify(x, (f(x), x)) + assert lam(3) == (103, 3) + lam = lambdify(x, [f(x), x]) + assert lam(3) == [103, 3] + lam = lambdify(x, [f(x), (f(x), x)]) + assert lam(3) == [103, (103, 3)] + lam = lambdify(x, {f(x): x}) + assert lam(3) == {103: 3} + lam = lambdify(x, {f(x): x}) + assert lam(3) == {103: 3} + lam = lambdify(x, {x: f(x)}) + assert lam(3) == {3: 103} + # Check that imp preferred to other namespaces by default + d = {'f': lambda x: x + 99} + lam = lambdify(x, f(x), d) + assert lam(3) == 103 + # Unless flag passed + lam = lambdify(x, f(x), d, use_imps=False) + assert lam(3) == 102 + + +def test_dummification(): + t = symbols('t') + F = Function('F') + G = Function('G') + #"\alpha" is not a valid Python variable name + #lambdify should sub in a dummy for it, and return + #without a syntax error + alpha = symbols(r'\alpha') + some_expr = 2 * F(t)**2 / G(t) + lam = lambdify((F(t), G(t)), some_expr) + assert lam(3, 9) == 2 + lam = lambdify(sin(t), 2 * sin(t)**2) + assert lam(F(t)) == 2 * F(t)**2 + #Test that \alpha was properly dummified + lam = lambdify((alpha, t), 2*alpha + t) + assert lam(2, 1) == 5 + raises(SyntaxError, lambda: lambdify(F(t) * G(t), F(t) * G(t) + 5)) + raises(SyntaxError, lambda: lambdify(2 * F(t), 2 * F(t) + 5)) + raises(SyntaxError, lambda: lambdify(2 * F(t), 4 * F(t) + 5)) + + +def test_lambdify__arguments_with_invalid_python_identifiers(): + # see sympy/sympy#26690 + N = CoordSys3D('N') + xn, yn, zn = N.base_scalars() + expr = xn + yn + f = lambdify([xn, yn], expr) + res = f(0.2, 0.3) + ref = 0.2 + 0.3 + assert abs(res-ref) < 1e-15 + + +def test_curly_matrix_symbol(): + # Issue #15009 + curlyv = sympy.MatrixSymbol("{v}", 2, 1) + lam = lambdify(curlyv, curlyv) + assert lam(1)==1 + lam = lambdify(curlyv, curlyv, dummify=True) + assert lam(1)==1 + + +def test_python_keywords(): + # Test for issue 7452. The automatic dummification should ensure use of + # Python reserved keywords as symbol names will create valid lambda + # functions. This is an additional regression test. + python_if = symbols('if') + expr = python_if / 2 + f = lambdify(python_if, expr) + assert f(4.0) == 2.0 + + +def test_lambdify_docstring(): + func = lambdify((w, x, y, z), w + x + y + z) + ref = ( + "Created with lambdify. Signature:\n\n" + "func(w, x, y, z)\n\n" + "Expression:\n\n" + "w + x + y + z" + ).splitlines() + assert func.__doc__.splitlines()[:len(ref)] == ref + syms = symbols('a1:26') + func = lambdify(syms, sum(syms)) + ref = ( + "Created with lambdify. Signature:\n\n" + "func(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15,\n" + " a16, a17, a18, a19, a20, a21, a22, a23, a24, a25)\n\n" + "Expression:\n\n" + "a1 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 + a2 + a20 +..." + ).splitlines() + assert func.__doc__.splitlines()[:len(ref)] == ref + + +def test_lambdify_linecache(): + func = lambdify(x, x + 1) + source = 'def _lambdifygenerated(x):\n return x + 1\n' + assert inspect.getsource(func) == source + filename = inspect.getsourcefile(func) + assert filename.startswith('= (1, 10) + + if have_scipy_1_10plus: + cm2 = lambdify((x, y), powm1(x, y), modules='scipy') + assert abs(cm2(1.2, 1e-9) - 1.82321557e-10) < 1e-17 + + +def test_scipy_bernoulli(): + if not scipy: + skip("scipy not installed") + + bern = lambdify((x,), bernoulli(x), modules='scipy') + assert bern(1) == 0.5 + + +def test_scipy_harmonic(): + if not scipy: + skip("scipy not installed") + + hn = lambdify((x,), harmonic(x), modules='scipy') + assert hn(2) == 1.5 + hnm = lambdify((x, y), harmonic(x, y), modules='scipy') + assert hnm(2, 2) == 1.25 + + +def test_cupy_array_arg(): + if not cupy: + skip("CuPy not installed") + + f = lambdify([[x, y]], x*x + y, 'cupy') + result = f(cupy.array([2.0, 1.0])) + assert result == 5 + assert "cupy" in str(type(result)) + + +def test_cupy_array_arg_using_numpy(): + # numpy functions can be run on cupy arrays + # unclear if we can "officially" support this, + # depends on numpy __array_function__ support + if not cupy: + skip("CuPy not installed") + + f = lambdify([[x, y]], x*x + y, 'numpy') + result = f(cupy.array([2.0, 1.0])) + assert result == 5 + assert "cupy" in str(type(result)) + +def test_cupy_dotproduct(): + if not cupy: + skip("CuPy not installed") + + A = Matrix([x, y, z]) + f1 = lambdify([x, y, z], DotProduct(A, A), modules='cupy') + f2 = lambdify([x, y, z], DotProduct(A, A.T), modules='cupy') + f3 = lambdify([x, y, z], DotProduct(A.T, A), modules='cupy') + f4 = lambdify([x, y, z], DotProduct(A, A.T), modules='cupy') + + assert f1(1, 2, 3) == \ + f2(1, 2, 3) == \ + f3(1, 2, 3) == \ + f4(1, 2, 3) == \ + cupy.array([14]) + + +def test_jax_array_arg(): + if not jax: + skip("JAX not installed") + + f = lambdify([[x, y]], x*x + y, 'jax') + result = f(jax.numpy.array([2.0, 1.0])) + assert result == 5 + assert "jax" in str(type(result)) + + +def test_jax_array_arg_using_numpy(): + if not jax: + skip("JAX not installed") + + f = lambdify([[x, y]], x*x + y, 'numpy') + result = f(jax.numpy.array([2.0, 1.0])) + assert result == 5 + assert "jax" in str(type(result)) + + +def test_jax_dotproduct(): + if not jax: + skip("JAX not installed") + + A = Matrix([x, y, z]) + f1 = lambdify([x, y, z], DotProduct(A, A), modules='jax') + f2 = lambdify([x, y, z], DotProduct(A, A.T), modules='jax') + f3 = lambdify([x, y, z], DotProduct(A.T, A), modules='jax') + f4 = lambdify([x, y, z], DotProduct(A, A.T), modules='jax') + + assert f1(1, 2, 3) == \ + f2(1, 2, 3) == \ + f3(1, 2, 3) == \ + f4(1, 2, 3) == \ + jax.numpy.array([14]) + + +def test_lambdify_cse(): + def no_op_cse(exprs): + return (), exprs + + def dummy_cse(exprs): + from sympy.simplify.cse_main import cse + return cse(exprs, symbols=numbered_symbols(cls=Dummy)) + + def minmem(exprs): + from sympy.simplify.cse_main import cse_release_variables, cse + return cse(exprs, postprocess=cse_release_variables) + + class Case: + def __init__(self, *, args, exprs, num_args, requires_numpy=False): + self.args = args + self.exprs = exprs + self.num_args = num_args + subs_dict = dict(zip(self.args, self.num_args)) + self.ref = [e.subs(subs_dict).evalf() for e in exprs] + self.requires_numpy = requires_numpy + + def lambdify(self, *, cse): + return lambdify(self.args, self.exprs, cse=cse) + + def assertAllClose(self, result, *, abstol=1e-15, reltol=1e-15): + if self.requires_numpy: + assert all(numpy.allclose(result[i], numpy.asarray(r, dtype=float), + rtol=reltol, atol=abstol) + for i, r in enumerate(self.ref)) + return + + for i, r in enumerate(self.ref): + abs_err = abs(result[i] - r) + if r == 0: + assert abs_err < abstol + else: + assert abs_err/abs(r) < reltol + + cases = [ + Case( + args=(x, y, z), + exprs=[ + x + y + z, + x + y - z, + 2*x + 2*y - z, + (x+y)**2 + (y+z)**2, + ], + num_args=(2., 3., 4.) + ), + Case( + args=(x, y, z), + exprs=[ + x + sympy.Heaviside(x), + y + sympy.Heaviside(x), + z + sympy.Heaviside(x, 1), + z/sympy.Heaviside(x, 1) + ], + num_args=(0., 3., 4.) + ), + Case( + args=(x, y, z), + exprs=[ + x + sinc(y), + y + sinc(y), + z - sinc(y) + ], + num_args=(0.1, 0.2, 0.3) + ), + Case( + args=(x, y, z), + exprs=[ + Matrix([[x, x*y], [sin(z) + 4, x**z]]), + x*y+sin(z)-x**z, + Matrix([x*x, sin(z), x**z]) + ], + num_args=(1.,2.,3.), + requires_numpy=True + ), + Case( + args=(x, y), + exprs=[(x + y - 1)**2, x, x + y, + (x + y)/(2*x + 1) + (x + y - 1)**2, (2*x + 1)**(x + y)], + num_args=(1,2) + ) + ] + for case in cases: + if not numpy and case.requires_numpy: + continue + for _cse in [False, True, minmem, no_op_cse, dummy_cse]: + f = case.lambdify(cse=_cse) + result = f(*case.num_args) + case.assertAllClose(result) + +def test_issue_25288(): + syms = numbered_symbols(cls=Dummy) + ok = lambdify(x, [x**2, sin(x**2)], cse=lambda e: cse(e, symbols=syms))(2) + assert ok + + +def test_deprecated_set(): + with warns_deprecated_sympy(): + lambdify({x, y}, x + y) + +def test_issue_13881(): + if not numpy: + skip("numpy not installed.") + + X = MatrixSymbol('X', 3, 1) + + f = lambdify(X, X.T*X, 'numpy') + assert f(numpy.array([1, 2, 3])) == 14 + assert f(numpy.array([3, 2, 1])) == 14 + + f = lambdify(X, X*X.T, 'numpy') + assert f(numpy.array([1, 2, 3])) == 14 + assert f(numpy.array([3, 2, 1])) == 14 + + f = lambdify(X, (X*X.T)*X, 'numpy') + arr1 = numpy.array([[1], [2], [3]]) + arr2 = numpy.array([[14],[28],[42]]) + + assert numpy.array_equal(f(arr1), arr2) + + +def test_23536_lambdify_cse_dummy(): + + f = Function('x')(y) + g = Function('w')(y) + expr = z + (f**4 + g**5)*(f**3 + (g*f)**3) + expr = expr.expand() + eval_expr = lambdify(((f, g), z), expr, cse=True) + ans = eval_expr((1.0, 2.0), 3.0) # shouldn't raise NameError + assert ans == 300.0 # not a list and value is 300 + + +class LambdifyDocstringTestCase: + SIGNATURE = None + EXPR = None + SRC = None + + def __init__(self, docstring_limit, expected_redacted): + self.docstring_limit = docstring_limit + self.expected_redacted = expected_redacted + + @property + def expected_expr(self): + expr_redacted_msg = "EXPRESSION REDACTED DUE TO LENGTH, (see lambdify's `docstring_limit`)" + return self.EXPR if not self.expected_redacted else expr_redacted_msg + + @property + def expected_src(self): + src_redacted_msg = "SOURCE CODE REDACTED DUE TO LENGTH, (see lambdify's `docstring_limit`)" + return self.SRC if not self.expected_redacted else src_redacted_msg + + @property + def expected_docstring(self): + expected_docstring = ( + f'Created with lambdify. Signature:\n\n' + f'func({self.SIGNATURE})\n\n' + f'Expression:\n\n' + f'{self.expected_expr}\n\n' + f'Source code:\n\n' + f'{self.expected_src}\n\n' + f'Imported modules:\n\n' + ) + return expected_docstring + + def __len__(self): + return len(self.expected_docstring) + + def __repr__(self): + return ( + f'{self.__class__.__name__}(' + f'docstring_limit={self.docstring_limit}, ' + f'expected_redacted={self.expected_redacted})' + ) + + +def test_lambdify_docstring_size_limit_simple_symbol(): + + class SimpleSymbolTestCase(LambdifyDocstringTestCase): + SIGNATURE = 'x' + EXPR = 'x' + SRC = ( + 'def _lambdifygenerated(x):\n' + ' return x\n' + ) + + x = symbols('x') + + test_cases = ( + SimpleSymbolTestCase(docstring_limit=None, expected_redacted=False), + SimpleSymbolTestCase(docstring_limit=100, expected_redacted=False), + SimpleSymbolTestCase(docstring_limit=1, expected_redacted=False), + SimpleSymbolTestCase(docstring_limit=0, expected_redacted=True), + SimpleSymbolTestCase(docstring_limit=-1, expected_redacted=True), + ) + for test_case in test_cases: + lambdified_expr = lambdify( + [x], + x, + 'sympy', + docstring_limit=test_case.docstring_limit, + ) + assert lambdified_expr.__doc__ == test_case.expected_docstring + + +def test_lambdify_docstring_size_limit_nested_expr(): + + class ExprListTestCase(LambdifyDocstringTestCase): + SIGNATURE = 'x, y, z' + EXPR = ( + '[x, [y], z, x**3 + 3*x**2*y + 3*x**2*z + 3*x*y**2 + 6*x*y*z ' + '+ 3*x*z**2 +...' + ) + SRC = ( + 'def _lambdifygenerated(x, y, z):\n' + ' return [x, [y], z, x**3 + 3*x**2*y + 3*x**2*z + 3*x*y**2 ' + '+ 6*x*y*z + 3*x*z**2 + y**3 + 3*y**2*z + 3*y*z**2 + z**3]\n' + ) + + x, y, z = symbols('x, y, z') + expr = [x, [y], z, ((x + y + z)**3).expand()] + + test_cases = ( + ExprListTestCase(docstring_limit=None, expected_redacted=False), + ExprListTestCase(docstring_limit=200, expected_redacted=False), + ExprListTestCase(docstring_limit=50, expected_redacted=True), + ExprListTestCase(docstring_limit=0, expected_redacted=True), + ExprListTestCase(docstring_limit=-1, expected_redacted=True), + ) + for test_case in test_cases: + lambdified_expr = lambdify( + [x, y, z], + expr, + 'sympy', + docstring_limit=test_case.docstring_limit, + ) + assert lambdified_expr.__doc__ == test_case.expected_docstring + + +def test_lambdify_docstring_size_limit_matrix(): + + class MatrixTestCase(LambdifyDocstringTestCase): + SIGNATURE = 'x, y, z' + EXPR = ( + 'Matrix([[0, x], [x + y + z, x**3 + 3*x**2*y + 3*x**2*z + 3*x*y**2 ' + '+ 6*x*y*z...' + ) + SRC = ( + 'def _lambdifygenerated(x, y, z):\n' + ' return ImmutableDenseMatrix([[0, x], [x + y + z, x**3 ' + '+ 3*x**2*y + 3*x**2*z + 3*x*y**2 + 6*x*y*z + 3*x*z**2 + y**3 ' + '+ 3*y**2*z + 3*y*z**2 + z**3]])\n' + ) + + x, y, z = symbols('x, y, z') + expr = Matrix([[S.Zero, x], [x + y + z, ((x + y + z)**3).expand()]]) + + test_cases = ( + MatrixTestCase(docstring_limit=None, expected_redacted=False), + MatrixTestCase(docstring_limit=200, expected_redacted=False), + MatrixTestCase(docstring_limit=50, expected_redacted=True), + MatrixTestCase(docstring_limit=0, expected_redacted=True), + MatrixTestCase(docstring_limit=-1, expected_redacted=True), + ) + for test_case in test_cases: + lambdified_expr = lambdify( + [x, y, z], + expr, + 'sympy', + docstring_limit=test_case.docstring_limit, + ) + assert lambdified_expr.__doc__ == test_case.expected_docstring + + +def test_lambdify_empty_tuple(): + a = symbols("a") + expr = ((), (a,)) + f = lambdify(a, expr) + result = f(1) + assert result == ((), (1,)), "Lambdify did not handle the empty tuple correctly." + + +def test_assoc_legendre_numerical_evaluation(): + + tol = 1e-10 + + sympy_result_integer = assoc_legendre(1, 1/2, 0.1).evalf() + sympy_result_complex = assoc_legendre(2, 1, 3).evalf() + mpmath_result_integer = -0.474572528387641 + mpmath_result_complex = -25.45584412271571*I + + assert all_close(sympy_result_integer, mpmath_result_integer, tol) + assert all_close(sympy_result_complex, mpmath_result_complex, tol) + + +def test_Piecewise(): + + modules = [math] + if numpy: + modules.append('numpy') + + for mod in modules: + # test isinf + f = lambdify(x, Piecewise((7.0, isinf(x)), (3.0, True)), mod) + assert f(+float('inf')) == +7.0 + assert f(-float('inf')) == +7.0 + assert f(42.) == 3.0 + + f2 = lambdify(x, Piecewise((7.0*sign(x), isinf(x)), (3.0, True)), mod) + assert f2(+float('inf')) == +7.0 + assert f2(-float('inf')) == -7.0 + assert f2(42.) == 3.0 + + # test isnan (gh-26784) + g = lambdify(x, Piecewise((7.0, isnan(x)), (3.0, True)), mod) + assert g(float('nan')) == 7.0 + assert g(42.) == 3.0 + + +def test_array_symbol(): + if not numpy: + skip("numpy not installed.") + a = ArraySymbol('a', (3,)) + f = lambdify((a), a) + assert numpy.all(f(numpy.array([1,2,3])) == numpy.array([1,2,3])) diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_matchpy_connector.py b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_matchpy_connector.py new file mode 100644 index 0000000000000000000000000000000000000000..3648bd49f9e56ca20fbf428ed46c01429dbe8b15 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_matchpy_connector.py @@ -0,0 +1,164 @@ +import pickle + +from sympy.core.relational import (Eq, Ne) +from sympy.core.singleton import S +from sympy.core.symbol import symbols +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.external import import_module +from sympy.testing.pytest import skip +from sympy.utilities.matchpy_connector import WildDot, WildPlus, WildStar, Replacer + +matchpy = import_module("matchpy") + +x, y, z = symbols("x y z") + + +def _get_first_match(expr, pattern): + from matchpy import ManyToOneMatcher, Pattern + + matcher = ManyToOneMatcher() + matcher.add(Pattern(pattern)) + return next(iter(matcher.match(expr))) + + +def test_matchpy_connector(): + if matchpy is None: + skip("matchpy not installed") + + from multiset import Multiset + from matchpy import Pattern, Substitution + + w_ = WildDot("w_") + w__ = WildPlus("w__") + w___ = WildStar("w___") + + expr = x + y + pattern = x + w_ + p, subst = _get_first_match(expr, pattern) + assert p == Pattern(pattern) + assert subst == Substitution({'w_': y}) + + expr = x + y + z + pattern = x + w__ + p, subst = _get_first_match(expr, pattern) + assert p == Pattern(pattern) + assert subst == Substitution({'w__': Multiset([y, z])}) + + expr = x + y + z + pattern = x + y + z + w___ + p, subst = _get_first_match(expr, pattern) + assert p == Pattern(pattern) + assert subst == Substitution({'w___': Multiset()}) + + +def test_matchpy_optional(): + if matchpy is None: + skip("matchpy not installed") + + from matchpy import Pattern, Substitution + from matchpy import ManyToOneReplacer, ReplacementRule + + p = WildDot("p", optional=1) + q = WildDot("q", optional=0) + + pattern = p*x + q + + expr1 = 2*x + pa, subst = _get_first_match(expr1, pattern) + assert pa == Pattern(pattern) + assert subst == Substitution({'p': 2, 'q': 0}) + + expr2 = x + 3 + pa, subst = _get_first_match(expr2, pattern) + assert pa == Pattern(pattern) + assert subst == Substitution({'p': 1, 'q': 3}) + + expr3 = x + pa, subst = _get_first_match(expr3, pattern) + assert pa == Pattern(pattern) + assert subst == Substitution({'p': 1, 'q': 0}) + + expr4 = x*y + z + pa, subst = _get_first_match(expr4, pattern) + assert pa == Pattern(pattern) + assert subst == Substitution({'p': y, 'q': z}) + + replacer = ManyToOneReplacer() + replacer.add(ReplacementRule(Pattern(pattern), lambda p, q: sin(p)*cos(q))) + assert replacer.replace(expr1) == sin(2)*cos(0) + assert replacer.replace(expr2) == sin(1)*cos(3) + assert replacer.replace(expr3) == sin(1)*cos(0) + assert replacer.replace(expr4) == sin(y)*cos(z) + + +def test_replacer(): + if matchpy is None: + skip("matchpy not installed") + + for info in [True, False]: + for lambdify in [True, False]: + _perform_test_replacer(info, lambdify) + + +def _perform_test_replacer(info, lambdify): + + x1_ = WildDot("x1_") + x2_ = WildDot("x2_") + + a_ = WildDot("a_", optional=S.One) + b_ = WildDot("b_", optional=S.One) + c_ = WildDot("c_", optional=S.Zero) + + replacer = Replacer(common_constraints=[ + matchpy.CustomConstraint(lambda a_: not a_.has(x)), + matchpy.CustomConstraint(lambda b_: not b_.has(x)), + matchpy.CustomConstraint(lambda c_: not c_.has(x)), + ], lambdify=lambdify, info=info) + + # Rewrite the equation into implicit form, unless it's already solved: + replacer.add(Eq(x1_, x2_), Eq(x1_ - x2_, 0), conditions_nonfalse=[Ne(x2_, 0), Ne(x1_, 0), Ne(x1_, x), Ne(x2_, x)], info=1) + + # Simple equation solver for real numbers: + replacer.add(Eq(a_*x + b_, 0), Eq(x, -b_/a_), info=2) + disc = b_**2 - 4*a_*c_ + replacer.add( + Eq(a_*x**2 + b_*x + c_, 0), + Eq(x, (-b_ - sqrt(disc))/(2*a_)) | Eq(x, (-b_ + sqrt(disc))/(2*a_)), + conditions_nonfalse=[disc >= 0], + info=3 + ) + replacer.add( + Eq(a_*x**2 + c_, 0), + Eq(x, sqrt(-c_/a_)) | Eq(x, -sqrt(-c_/a_)), + conditions_nonfalse=[-c_*a_ > 0], + info=4 + ) + + g = lambda expr, infos: (expr, infos) if info else expr + + assert replacer.replace(Eq(3*x, y)) == g(Eq(x, y/3), [1, 2]) + assert replacer.replace(Eq(x**2 + 1, 0)) == g(Eq(x**2 + 1, 0), []) + assert replacer.replace(Eq(x**2, 4)) == g((Eq(x, 2) | Eq(x, -2)), [1, 4]) + assert replacer.replace(Eq(x**2 + 4*y*x + 4*y**2, 0)) == g(Eq(x, -2*y), [3]) + + +def test_matchpy_object_pickle(): + if matchpy is None: + return + + a1 = WildDot("a") + a2 = pickle.loads(pickle.dumps(a1)) + assert a1 == a2 + + a1 = WildDot("a", S(1)) + a2 = pickle.loads(pickle.dumps(a1)) + assert a1 == a2 + + a1 = WildPlus("a", S(1)) + a2 = pickle.loads(pickle.dumps(a1)) + assert a1 == a2 + + a1 = WildStar("a", S(1)) + a2 = pickle.loads(pickle.dumps(a1)) + assert a1 == a2 diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_mathml.py b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_mathml.py new file mode 100644 index 0000000000000000000000000000000000000000..e4a7598f175be34f8bb34c0bd9c003d1c0238c7b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_mathml.py @@ -0,0 +1,33 @@ +import os +from textwrap import dedent +from sympy.external import import_module +from sympy.testing.pytest import skip +from sympy.utilities.mathml import apply_xsl + + + +lxml = import_module('lxml') + +path = os.path.abspath(os.path.join(os.path.dirname(__file__), "test_xxe.py")) + + +def test_xxe(): + assert os.path.isfile(path) + if not lxml: + skip("lxml not installed.") + + mml = dedent( + rf""" + + ]> + + John + &ent; + + """ + ) + xsl = 'mathml/data/simple_mmlctop.xsl' + + res = apply_xsl(mml, xsl) + assert res == \ + '\n\nJohn\n\n\n' diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_misc.py b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..0a3e059419303c33cbd7b770679b5efc1b03486d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_misc.py @@ -0,0 +1,148 @@ +from textwrap import dedent +import sys +from subprocess import Popen, PIPE +import os + +from sympy.core.singleton import S +from sympy.testing.pytest import (raises, warns_deprecated_sympy, + skip_under_pyodide) +from sympy.utilities.misc import (translate, replace, ordinal, rawlines, + strlines, as_int, find_executable) + + +def test_translate(): + abc = 'abc' + assert translate(abc, None, 'a') == 'bc' + assert translate(abc, None, '') == 'abc' + assert translate(abc, {'a': 'x'}, 'c') == 'xb' + assert translate(abc, {'a': 'bc'}, 'c') == 'bcb' + assert translate(abc, {'ab': 'x'}, 'c') == 'x' + assert translate(abc, {'ab': ''}, 'c') == '' + assert translate(abc, {'bc': 'x'}, 'c') == 'ab' + assert translate(abc, {'abc': 'x', 'a': 'y'}) == 'x' + u = chr(4096) + assert translate(abc, 'a', 'x', u) == 'xbc' + assert (u in translate(abc, 'a', u, u)) is True + + +def test_replace(): + assert replace('abc', ('a', 'b')) == 'bbc' + assert replace('abc', {'a': 'Aa'}) == 'Aabc' + assert replace('abc', ('a', 'b'), ('c', 'C')) == 'bbC' + + +def test_ordinal(): + assert ordinal(-1) == '-1st' + assert ordinal(0) == '0th' + assert ordinal(1) == '1st' + assert ordinal(2) == '2nd' + assert ordinal(3) == '3rd' + assert all(ordinal(i).endswith('th') for i in range(4, 21)) + assert ordinal(100) == '100th' + assert ordinal(101) == '101st' + assert ordinal(102) == '102nd' + assert ordinal(103) == '103rd' + assert ordinal(104) == '104th' + assert ordinal(200) == '200th' + assert all(ordinal(i) == str(i) + 'th' for i in range(-220, -203)) + + +def test_rawlines(): + assert rawlines('a a\na') == "dedent('''\\\n a a\n a''')" + assert rawlines('a a') == "'a a'" + assert rawlines(strlines('\\le"ft')) == ( + '(\n' + " '(\\n'\n" + ' \'r\\\'\\\\le"ft\\\'\\n\'\n' + " ')'\n" + ')') + + +def test_strlines(): + q = 'this quote (") is in the middle' + # the following assert rhs was prepared with + # print(rawlines(strlines(q, 10))) + assert strlines(q, 10) == dedent('''\ + ( + 'this quo' + 'te (") i' + 's in the' + ' middle' + )''') + assert q == ( + 'this quo' + 'te (") i' + 's in the' + ' middle' + ) + q = "this quote (') is in the middle" + assert strlines(q, 20) == dedent('''\ + ( + "this quote (') is " + "in the middle" + )''') + assert strlines('\\left') == ( + '(\n' + "r'\\left'\n" + ')') + assert strlines('\\left', short=True) == r"r'\left'" + assert strlines('\\le"ft') == ( + '(\n' + 'r\'\\le"ft\'\n' + ')') + q = 'this\nother line' + assert strlines(q) == rawlines(q) + + +def test_translate_args(): + try: + translate(None, None, None, 'not_none') + except ValueError: + pass # Exception raised successfully + else: + assert False + + assert translate('s', None, None, None) == 's' + + try: + translate('s', 'a', 'bc') + except ValueError: + pass # Exception raised successfully + else: + assert False + + +@skip_under_pyodide("Cannot create subprocess under pyodide.") +def test_debug_output(): + env = os.environ.copy() + env['SYMPY_DEBUG'] = 'True' + cmd = 'from sympy import *; x = Symbol("x"); print(integrate((1-cos(x))/x, x))' + cmdline = [sys.executable, '-c', cmd] + proc = Popen(cmdline, env=env, stdout=PIPE, stderr=PIPE) + out, err = proc.communicate() + out = out.decode('ascii') # utf-8? + err = err.decode('ascii') + expected = 'substituted: -x*(1 - cos(x)), u: 1/x, u_var: _u' + assert expected in err, err + + +def test_as_int(): + raises(ValueError, lambda : as_int(True)) + raises(ValueError, lambda : as_int(1.1)) + raises(ValueError, lambda : as_int([])) + raises(ValueError, lambda : as_int(S.NaN)) + raises(ValueError, lambda : as_int(S.Infinity)) + raises(ValueError, lambda : as_int(S.NegativeInfinity)) + raises(ValueError, lambda : as_int(S.ComplexInfinity)) + # for the following, limited precision makes int(arg) == arg + # but the int value is not necessarily what a user might have + # expected; Q.prime is more nuanced in its response for + # expressions which might be complex representations of an + # integer. This is not -- by design -- as_ints role. + raises(ValueError, lambda : as_int(1e23)) + raises(ValueError, lambda : as_int(S('1.'+'0'*20+'1'))) + assert as_int(True, strict=False) == 1 + +def test_deprecated_find_executable(): + with warns_deprecated_sympy(): + find_executable('python') diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_pickling.py b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_pickling.py new file mode 100644 index 0000000000000000000000000000000000000000..7ea2d062286cbcf802eb0f42f2d7d130123599af --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_pickling.py @@ -0,0 +1,723 @@ +import inspect +import copy +import pickle + +from sympy.physics.units import meter + +from sympy.testing.pytest import XFAIL, raises, ignore_warnings + +from sympy.core.basic import Atom, Basic +from sympy.core.singleton import SingletonRegistry +from sympy.core.symbol import Str, Dummy, Symbol, Wild +from sympy.core.numbers import (E, I, pi, oo, zoo, nan, Integer, + Rational, Float, AlgebraicNumber) +from sympy.core.relational import (Equality, GreaterThan, LessThan, Relational, + StrictGreaterThan, StrictLessThan, Unequality) +from sympy.core.add import Add +from sympy.core.mul import Mul +from sympy.core.power import Pow +from sympy.core.function import Derivative, Function, FunctionClass, Lambda, \ + WildFunction +from sympy.sets.sets import Interval +from sympy.core.multidimensional import vectorize + +from sympy.external.gmpy import gmpy as _gmpy +from sympy.utilities.exceptions import SymPyDeprecationWarning + +from sympy.core.singleton import S +from sympy.core.symbol import symbols + +from sympy.external import import_module +cloudpickle = import_module('cloudpickle') + + +not_equal_attrs = { + '_assumptions', # This is a local cache that isn't automatically filled on creation + '_mhash', # Cached after __hash__ is called but set to None after creation +} + + +deprecated_attrs = { + 'is_EmptySet', # Deprecated from SymPy 1.5. This can be removed when is_EmptySet is removed. + 'expr_free_symbols', # Deprecated from SymPy 1.9. This can be removed when exr_free_symbols is removed. +} + +dont_check_attrs = { + '_sage_', # Fails because Sage is not installed +} + + +def check(a, exclude=[], check_attr=True, deprecated=()): + """ Check that pickling and copying round-trips. + """ + # Pickling with protocols 0 and 1 is disabled for Basic instances: + if isinstance(a, Basic): + for protocol in [0, 1]: + raises(NotImplementedError, lambda: pickle.dumps(a, protocol)) + + protocols = [2, copy.copy, copy.deepcopy, 3, 4] + if cloudpickle: + protocols.extend([cloudpickle]) + + for protocol in protocols: + if protocol in exclude: + continue + + if callable(protocol): + if isinstance(a, type): + # Classes can't be copied, but that's okay. + continue + b = protocol(a) + elif inspect.ismodule(protocol): + b = protocol.loads(protocol.dumps(a)) + else: + b = pickle.loads(pickle.dumps(a, protocol)) + + d1 = dir(a) + d2 = dir(b) + assert set(d1) == set(d2) + + if not check_attr: + continue + + def c(a, b, d): + for i in d: + if i in dont_check_attrs: + continue + elif i in not_equal_attrs: + if hasattr(a, i): + assert hasattr(b, i), i + elif i in deprecated_attrs or i in deprecated: + with ignore_warnings(SymPyDeprecationWarning): + assert getattr(a, i) == getattr(b, i), i + elif not hasattr(a, i): + continue + else: + attr = getattr(a, i) + if not hasattr(attr, "__call__"): + assert hasattr(b, i), i + assert getattr(b, i) == attr, "%s != %s, protocol: %s" % (getattr(b, i), attr, protocol) + + c(a, b, d1) + c(b, a, d2) + + + +#================== core ========================= + + +def test_core_basic(): + for c in (Atom, Atom(), Basic, Basic(), SingletonRegistry, S): + check(c) + +def test_core_Str(): + check(Str('x')) + +def test_core_symbol(): + # make the Symbol a unique name that doesn't class with any other + # testing variable in this file since after this test the symbol + # having the same name will be cached as noncommutative + for c in (Dummy, Dummy("x", commutative=False), Symbol, + Symbol("_issue_3130", commutative=False), Wild, Wild("x")): + check(c) + + +def test_core_numbers(): + for c in (Integer(2), Rational(2, 3), Float("1.2")): + check(c) + for c in (AlgebraicNumber, AlgebraicNumber(sqrt(3))): + check(c, check_attr=False) + + +def test_core_float_copy(): + # See gh-7457 + y = Symbol("x") + 1.0 + check(y) # does not raise TypeError ("argument is not an mpz") + + +def test_core_relational(): + x = Symbol("x") + y = Symbol("y") + for c in (Equality, Equality(x, y), GreaterThan, GreaterThan(x, y), + LessThan, LessThan(x, y), Relational, Relational(x, y), + StrictGreaterThan, StrictGreaterThan(x, y), StrictLessThan, + StrictLessThan(x, y), Unequality, Unequality(x, y)): + check(c) + + +def test_core_add(): + x = Symbol("x") + for c in (Add, Add(x, 4)): + check(c) + + +def test_core_mul(): + x = Symbol("x") + for c in (Mul, Mul(x, 4)): + check(c) + + +def test_core_power(): + x = Symbol("x") + for c in (Pow, Pow(x, 4)): + check(c) + + +def test_core_function(): + x = Symbol("x") + for f in (Derivative, Derivative(x), Function, FunctionClass, Lambda, + WildFunction): + check(f) + + +def test_core_undefinedfunctions(): + f = Function("f") + check(f) + + +def test_core_appliedundef(): + x = Symbol("_long_unique_name_1") + f = Function("_long_unique_name_2") + check(f(x)) + + +def test_core_interval(): + for c in (Interval, Interval(0, 2)): + check(c) + + +def test_core_multidimensional(): + for c in (vectorize, vectorize(0)): + check(c) + + +def test_Singletons(): + protocols = [0, 1, 2, 3, 4] + copiers = [copy.copy, copy.deepcopy] + copiers += [lambda x: pickle.loads(pickle.dumps(x, proto)) + for proto in protocols] + if cloudpickle: + copiers += [lambda x: cloudpickle.loads(cloudpickle.dumps(x))] + + for obj in (Integer(-1), Integer(0), Integer(1), Rational(1, 2), pi, E, I, + oo, -oo, zoo, nan, S.GoldenRatio, S.TribonacciConstant, + S.EulerGamma, S.Catalan, S.EmptySet, S.IdentityFunction): + for func in copiers: + assert func(obj) is obj + +#================== combinatorics =================== +from sympy.combinatorics.free_groups import FreeGroup + +def test_free_group(): + check(FreeGroup("x, y, z"), check_attr=False) + +#================== functions =================== +from sympy.functions import (Piecewise, lowergamma, acosh, chebyshevu, + chebyshevt, ln, chebyshevt_root, legendre, Heaviside, bernoulli, coth, + tanh, assoc_legendre, sign, arg, asin, DiracDelta, re, rf, Abs, + uppergamma, binomial, sinh, cos, cot, acos, acot, gamma, bell, + hermite, harmonic, LambertW, zeta, log, factorial, asinh, acoth, cosh, + dirichlet_eta, Eijk, loggamma, erf, ceiling, im, fibonacci, + tribonacci, conjugate, tan, chebyshevu_root, floor, atanh, sqrt, sin, + atan, ff, lucas, atan2, polygamma, exp) + + +def test_functions(): + one_var = (acosh, ln, Heaviside, factorial, bernoulli, coth, tanh, + sign, arg, asin, DiracDelta, re, Abs, sinh, cos, cot, acos, acot, + gamma, bell, harmonic, LambertW, zeta, log, factorial, asinh, + acoth, cosh, dirichlet_eta, loggamma, erf, ceiling, im, fibonacci, + tribonacci, conjugate, tan, floor, atanh, sin, atan, lucas, exp) + two_var = (rf, ff, lowergamma, chebyshevu, chebyshevt, binomial, + atan2, polygamma, hermite, legendre, uppergamma) + x, y, z = symbols("x,y,z") + others = (chebyshevt_root, chebyshevu_root, Eijk(x, y, z), + Piecewise( (0, x < -1), (x**2, x <= 1), (x**3, True)), + assoc_legendre) + for cls in one_var: + check(cls) + c = cls(x) + check(c) + for cls in two_var: + check(cls) + c = cls(x, y) + check(c) + for cls in others: + check(cls) + +#================== geometry ==================== +from sympy.geometry.entity import GeometryEntity +from sympy.geometry.point import Point +from sympy.geometry.ellipse import Circle, Ellipse +from sympy.geometry.line import Line, LinearEntity, Ray, Segment +from sympy.geometry.polygon import Polygon, RegularPolygon, Triangle + + +def test_geometry(): + p1 = Point(1, 2) + p2 = Point(2, 3) + p3 = Point(0, 0) + p4 = Point(0, 1) + for c in ( + GeometryEntity, GeometryEntity(), Point, p1, Circle, Circle(p1, 2), + Ellipse, Ellipse(p1, 3, 4), Line, Line(p1, p2), LinearEntity, + LinearEntity(p1, p2), Ray, Ray(p1, p2), Segment, Segment(p1, p2), + Polygon, Polygon(p1, p2, p3, p4), RegularPolygon, + RegularPolygon(p1, 4, 5), Triangle, Triangle(p1, p2, p3)): + check(c, check_attr=False) + +#================== integrals ==================== +from sympy.integrals.integrals import Integral + + +def test_integrals(): + x = Symbol("x") + for c in (Integral, Integral(x)): + check(c) + +#==================== logic ===================== +from sympy.core.logic import Logic + + +def test_logic(): + for c in (Logic, Logic(1)): + check(c) + +#================== matrices ==================== +from sympy.matrices import Matrix, SparseMatrix + + +def test_matrices(): + for c in (Matrix, Matrix([1, 2, 3]), SparseMatrix, SparseMatrix([[1, 2], [3, 4]])): + check(c, deprecated=['_smat', '_mat']) + +#================== ntheory ===================== +from sympy.ntheory.generate import Sieve + + +def test_ntheory(): + for c in (Sieve, Sieve()): + check(c) + +#================== physics ===================== +from sympy.physics.paulialgebra import Pauli +from sympy.physics.units import Unit + + +def test_physics(): + for c in (Unit, meter, Pauli, Pauli(1)): + check(c) + +#================== plotting ==================== +# XXX: These tests are not complete, so XFAIL them + + +@XFAIL +def test_plotting(): + from sympy.plotting.pygletplot.color_scheme import ColorGradient, ColorScheme + from sympy.plotting.pygletplot.managed_window import ManagedWindow + from sympy.plotting.plot import Plot, ScreenShot + from sympy.plotting.pygletplot.plot_axes import PlotAxes, PlotAxesBase, PlotAxesFrame, PlotAxesOrdinate + from sympy.plotting.pygletplot.plot_camera import PlotCamera + from sympy.plotting.pygletplot.plot_controller import PlotController + from sympy.plotting.pygletplot.plot_curve import PlotCurve + from sympy.plotting.pygletplot.plot_interval import PlotInterval + from sympy.plotting.pygletplot.plot_mode import PlotMode + from sympy.plotting.pygletplot.plot_modes import Cartesian2D, Cartesian3D, Cylindrical, \ + ParametricCurve2D, ParametricCurve3D, ParametricSurface, Polar, Spherical + from sympy.plotting.pygletplot.plot_object import PlotObject + from sympy.plotting.pygletplot.plot_surface import PlotSurface + from sympy.plotting.pygletplot.plot_window import PlotWindow + for c in ( + ColorGradient, ColorGradient(0.2, 0.4), ColorScheme, ManagedWindow, + ManagedWindow, Plot, ScreenShot, PlotAxes, PlotAxesBase, + PlotAxesFrame, PlotAxesOrdinate, PlotCamera, PlotController, + PlotCurve, PlotInterval, PlotMode, Cartesian2D, Cartesian3D, + Cylindrical, ParametricCurve2D, ParametricCurve3D, + ParametricSurface, Polar, Spherical, PlotObject, PlotSurface, + PlotWindow): + check(c) + + +@XFAIL +def test_plotting2(): + #from sympy.plotting.color_scheme import ColorGradient + from sympy.plotting.pygletplot.color_scheme import ColorScheme + #from sympy.plotting.managed_window import ManagedWindow + from sympy.plotting.plot import Plot + #from sympy.plotting.plot import ScreenShot + from sympy.plotting.pygletplot.plot_axes import PlotAxes + #from sympy.plotting.plot_axes import PlotAxesBase, PlotAxesFrame, PlotAxesOrdinate + #from sympy.plotting.plot_camera import PlotCamera + #from sympy.plotting.plot_controller import PlotController + #from sympy.plotting.plot_curve import PlotCurve + #from sympy.plotting.plot_interval import PlotInterval + #from sympy.plotting.plot_mode import PlotMode + #from sympy.plotting.plot_modes import Cartesian2D, Cartesian3D, Cylindrical, \ + # ParametricCurve2D, ParametricCurve3D, ParametricSurface, Polar, Spherical + #from sympy.plotting.plot_object import PlotObject + #from sympy.plotting.plot_surface import PlotSurface + # from sympy.plotting.plot_window import PlotWindow + check(ColorScheme("rainbow")) + check(Plot(1, visible=False)) + check(PlotAxes()) + +#================== polys ======================= +from sympy.polys.domains.integerring import ZZ +from sympy.polys.domains.rationalfield import QQ +from sympy.polys.orderings import lex +from sympy.polys.polytools import Poly + +def test_pickling_polys_polytools(): + from sympy.polys.polytools import PurePoly + # from sympy.polys.polytools import GroebnerBasis + x = Symbol('x') + + for c in (Poly, Poly(x, x)): + check(c) + + for c in (PurePoly, PurePoly(x)): + check(c) + + # TODO: fix pickling of Options class (see GroebnerBasis._options) + # for c in (GroebnerBasis, GroebnerBasis([x**2 - 1], x, order=lex)): + # check(c) + +def test_pickling_polys_polyclasses(): + from sympy.polys.polyclasses import DMP, DMF, ANP + + for c in (DMP, DMP([[ZZ(1)], [ZZ(2)], [ZZ(3)]], ZZ)): + check(c, deprecated=['rep']) + for c in (DMF, DMF(([ZZ(1), ZZ(2)], [ZZ(1), ZZ(3)]), ZZ)): + check(c) + for c in (ANP, ANP([QQ(1), QQ(2)], [QQ(1), QQ(2), QQ(3)], QQ)): + check(c) + +@XFAIL +def test_pickling_polys_rings(): + # NOTE: can't use protocols < 2 because we have to execute __new__ to + # make sure caching of rings works properly. + + from sympy.polys.rings import PolyRing + + ring = PolyRing("x,y,z", ZZ, lex) + + for c in (PolyRing, ring): + check(c, exclude=[0, 1]) + + for c in (ring.dtype, ring.one): + check(c, exclude=[0, 1], check_attr=False) # TODO: Py3k + +def test_pickling_polys_fields(): + pass + # NOTE: can't use protocols < 2 because we have to execute __new__ to + # make sure caching of fields works properly. + + # from sympy.polys.fields import FracField + + # field = FracField("x,y,z", ZZ, lex) + + # TODO: AssertionError: assert id(obj) not in self.memo + # for c in (FracField, field): + # check(c, exclude=[0, 1]) + + # TODO: AssertionError: assert id(obj) not in self.memo + # for c in (field.dtype, field.one): + # check(c, exclude=[0, 1]) + +def test_pickling_polys_elements(): + from sympy.polys.domains.pythonrational import PythonRational + #from sympy.polys.domains.pythonfinitefield import PythonFiniteField + #from sympy.polys.domains.mpelements import MPContext + + for c in (PythonRational, PythonRational(1, 7)): + check(c) + + #gf = PythonFiniteField(17) + + # TODO: fix pickling of ModularInteger + # for c in (gf.dtype, gf(5)): + # check(c) + + #mp = MPContext() + + # TODO: fix pickling of RealElement + # for c in (mp.mpf, mp.mpf(1.0)): + # check(c) + + # TODO: fix pickling of ComplexElement + # for c in (mp.mpc, mp.mpc(1.0, -1.5)): + # check(c) + +def test_pickling_polys_domains(): + # from sympy.polys.domains.pythonfinitefield import PythonFiniteField + from sympy.polys.domains.pythonintegerring import PythonIntegerRing + from sympy.polys.domains.pythonrationalfield import PythonRationalField + + # TODO: fix pickling of ModularInteger + # for c in (PythonFiniteField, PythonFiniteField(17)): + # check(c) + + for c in (PythonIntegerRing, PythonIntegerRing()): + check(c, check_attr=False) + + for c in (PythonRationalField, PythonRationalField()): + check(c, check_attr=False) + + if _gmpy is not None: + # from sympy.polys.domains.gmpyfinitefield import GMPYFiniteField + from sympy.polys.domains.gmpyintegerring import GMPYIntegerRing + from sympy.polys.domains.gmpyrationalfield import GMPYRationalField + + # TODO: fix pickling of ModularInteger + # for c in (GMPYFiniteField, GMPYFiniteField(17)): + # check(c) + + for c in (GMPYIntegerRing, GMPYIntegerRing()): + check(c, check_attr=False) + + for c in (GMPYRationalField, GMPYRationalField()): + check(c, check_attr=False) + + #from sympy.polys.domains.realfield import RealField + #from sympy.polys.domains.complexfield import ComplexField + from sympy.polys.domains.algebraicfield import AlgebraicField + #from sympy.polys.domains.polynomialring import PolynomialRing + #from sympy.polys.domains.fractionfield import FractionField + from sympy.polys.domains.expressiondomain import ExpressionDomain + + # TODO: fix pickling of RealElement + # for c in (RealField, RealField(100)): + # check(c) + + # TODO: fix pickling of ComplexElement + # for c in (ComplexField, ComplexField(100)): + # check(c) + + for c in (AlgebraicField, AlgebraicField(QQ, sqrt(3))): + check(c, check_attr=False) + + # TODO: AssertionError + # for c in (PolynomialRing, PolynomialRing(ZZ, "x,y,z")): + # check(c) + + # TODO: AttributeError: 'PolyElement' object has no attribute 'ring' + # for c in (FractionField, FractionField(ZZ, "x,y,z")): + # check(c) + + for c in (ExpressionDomain, ExpressionDomain()): + check(c, check_attr=False) + + +def test_pickling_polys_orderings(): + from sympy.polys.orderings import (LexOrder, GradedLexOrder, + ReversedGradedLexOrder, InverseOrder) + # from sympy.polys.orderings import ProductOrder + + for c in (LexOrder, LexOrder()): + check(c) + + for c in (GradedLexOrder, GradedLexOrder()): + check(c) + + for c in (ReversedGradedLexOrder, ReversedGradedLexOrder()): + check(c) + + # TODO: Argh, Python is so naive. No lambdas nor inner function support in + # pickling module. Maybe someone could figure out what to do with this. + # + # for c in (ProductOrder, ProductOrder((LexOrder(), lambda m: m[:2]), + # (GradedLexOrder(), lambda m: m[2:]))): + # check(c) + + for c in (InverseOrder, InverseOrder(LexOrder())): + check(c) + +def test_pickling_polys_monomials(): + from sympy.polys.monomials import MonomialOps, Monomial + x, y, z = symbols("x,y,z") + + for c in (MonomialOps, MonomialOps(3)): + check(c) + + for c in (Monomial, Monomial((1, 2, 3), (x, y, z))): + check(c) + +def test_pickling_polys_errors(): + from sympy.polys.polyerrors import (HeuristicGCDFailed, + HomomorphismFailed, IsomorphismFailed, ExtraneousFactors, + EvaluationFailed, RefinementFailed, CoercionFailed, NotInvertible, + NotReversible, NotAlgebraic, DomainError, PolynomialError, + UnificationFailed, GeneratorsError, GeneratorsNeeded, + UnivariatePolynomialError, MultivariatePolynomialError, OptionError, + FlagError) + # from sympy.polys.polyerrors import (ExactQuotientFailed, + # OperationNotSupported, ComputationFailed, PolificationFailed) + + # x = Symbol('x') + + # TODO: TypeError: __init__() takes at least 3 arguments (1 given) + # for c in (ExactQuotientFailed, ExactQuotientFailed(x, 3*x, ZZ)): + # check(c) + + # TODO: TypeError: can't pickle instancemethod objects + # for c in (OperationNotSupported, OperationNotSupported(Poly(x), Poly.gcd)): + # check(c) + + for c in (HeuristicGCDFailed, HeuristicGCDFailed()): + check(c) + + for c in (HomomorphismFailed, HomomorphismFailed()): + check(c) + + for c in (IsomorphismFailed, IsomorphismFailed()): + check(c) + + for c in (ExtraneousFactors, ExtraneousFactors()): + check(c) + + for c in (EvaluationFailed, EvaluationFailed()): + check(c) + + for c in (RefinementFailed, RefinementFailed()): + check(c) + + for c in (CoercionFailed, CoercionFailed()): + check(c) + + for c in (NotInvertible, NotInvertible()): + check(c) + + for c in (NotReversible, NotReversible()): + check(c) + + for c in (NotAlgebraic, NotAlgebraic()): + check(c) + + for c in (DomainError, DomainError()): + check(c) + + for c in (PolynomialError, PolynomialError()): + check(c) + + for c in (UnificationFailed, UnificationFailed()): + check(c) + + for c in (GeneratorsError, GeneratorsError()): + check(c) + + for c in (GeneratorsNeeded, GeneratorsNeeded()): + check(c) + + # TODO: PicklingError: Can't pickle at 0x38578c0>: it's not found as __main__. + # for c in (ComputationFailed, ComputationFailed(lambda t: t, 3, None)): + # check(c) + + for c in (UnivariatePolynomialError, UnivariatePolynomialError()): + check(c) + + for c in (MultivariatePolynomialError, MultivariatePolynomialError()): + check(c) + + # TODO: TypeError: __init__() takes at least 3 arguments (1 given) + # for c in (PolificationFailed, PolificationFailed({}, x, x, False)): + # check(c) + + for c in (OptionError, OptionError()): + check(c) + + for c in (FlagError, FlagError()): + check(c) + +#def test_pickling_polys_options(): + #from sympy.polys.polyoptions import Options + + # TODO: fix pickling of `symbols' flag + # for c in (Options, Options((), dict(domain='ZZ', polys=False))): + # check(c) + +# TODO: def test_pickling_polys_rootisolation(): +# RealInterval +# ComplexInterval + +def test_pickling_polys_rootoftools(): + from sympy.polys.rootoftools import CRootOf, RootSum + + x = Symbol('x') + f = x**3 + x + 3 + + for c in (CRootOf, CRootOf(f, 0)): + check(c) + + for c in (RootSum, RootSum(f, exp)): + check(c) + +#================== printing ==================== +from sympy.printing.latex import LatexPrinter +from sympy.printing.mathml import MathMLContentPrinter, MathMLPresentationPrinter +from sympy.printing.pretty.pretty import PrettyPrinter +from sympy.printing.pretty.stringpict import prettyForm, stringPict +from sympy.printing.printer import Printer +from sympy.printing.python import PythonPrinter + + +def test_printing(): + for c in (LatexPrinter, LatexPrinter(), MathMLContentPrinter, + MathMLPresentationPrinter, PrettyPrinter, prettyForm, stringPict, + stringPict("a"), Printer, Printer(), PythonPrinter, + PythonPrinter()): + check(c) + + +@XFAIL +def test_printing1(): + check(MathMLContentPrinter()) + + +@XFAIL +def test_printing2(): + check(MathMLPresentationPrinter()) + + +@XFAIL +def test_printing3(): + check(PrettyPrinter()) + +#================== series ====================== +from sympy.series.limits import Limit +from sympy.series.order import Order + + +def test_series(): + e = Symbol("e") + x = Symbol("x") + for c in (Limit, Limit(e, x, 1), Order, Order(e)): + check(c) + +#================== concrete ================== +from sympy.concrete.products import Product +from sympy.concrete.summations import Sum + + +def test_concrete(): + x = Symbol("x") + for c in (Product, Product(x, (x, 2, 4)), Sum, Sum(x, (x, 2, 4))): + check(c) + +def test_deprecation_warning(): + w = SymPyDeprecationWarning("message", deprecated_since_version='1.0', active_deprecations_target="active-deprecations") + check(w) + +def test_issue_18438(): + assert pickle.loads(pickle.dumps(S.Half)) == S.Half + + +#================= old pickles ================= +def test_unpickle_from_older_versions(): + data = ( + b'\x80\x04\x95^\x00\x00\x00\x00\x00\x00\x00\x8c\x10sympy.core.power' + b'\x94\x8c\x03Pow\x94\x93\x94\x8c\x12sympy.core.numbers\x94\x8c' + b'\x07Integer\x94\x93\x94K\x02\x85\x94R\x94}\x94bh\x03\x8c\x04Half' + b'\x94\x93\x94)R\x94}\x94b\x86\x94R\x94}\x94b.' + ) + assert pickle.loads(data) == sqrt(2) diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_source.py b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_source.py new file mode 100644 index 0000000000000000000000000000000000000000..468185bc579fc325aee21024dfa15ebf14287b5f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_source.py @@ -0,0 +1,11 @@ +from sympy.utilities.source import get_mod_func, get_class + + +def test_get_mod_func(): + assert get_mod_func( + 'sympy.core.basic.Basic') == ('sympy.core.basic', 'Basic') + + +def test_get_class(): + _basic = get_class('sympy.core.basic.Basic') + assert _basic.__name__ == 'Basic' diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_timeutils.py b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_timeutils.py new file mode 100644 index 0000000000000000000000000000000000000000..14edfd089c7315ee9f39a4298af0289f8919da6b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_timeutils.py @@ -0,0 +1,10 @@ +"""Tests for simple tools for timing functions' execution. """ + +from sympy.utilities.timeutils import timed + +def test_timed(): + result = timed(lambda: 1 + 1, limit=100000) + assert result[0] == 100000 and result[3] == "ns", str(result) + + result = timed("1 + 1", limit=100000) + assert result[0] == 100000 and result[3] == "ns" diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_wester.py b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_wester.py new file mode 100644 index 0000000000000000000000000000000000000000..c5699a4eb0824e507967ecd4ff8f7a5f32cc9a54 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_wester.py @@ -0,0 +1,3104 @@ +""" Tests from Michael Wester's 1999 paper "Review of CAS mathematical +capabilities". + +http://www.math.unm.edu/~wester/cas/book/Wester.pdf +See also http://math.unm.edu/~wester/cas_review.html for detailed output of +each tested system. +""" + +from sympy.assumptions.ask import Q, ask +from sympy.assumptions.refine import refine +from sympy.concrete.products import product +from sympy.core import EulerGamma +from sympy.core.evalf import N +from sympy.core.function import (Derivative, Function, Lambda, Subs, + diff, expand, expand_func) +from sympy.core.mul import Mul +from sympy.core.intfunc import igcd +from sympy.core.numbers import (AlgebraicNumber, E, I, Rational, + nan, oo, pi, zoo) +from sympy.core.relational import Eq, Lt +from sympy.core.singleton import S +from sympy.core.symbol import Dummy, Symbol, symbols +from sympy.functions.combinatorial.factorials import (rf, binomial, + factorial, factorial2) +from sympy.functions.combinatorial.numbers import bernoulli, fibonacci, totient, partition +from sympy.functions.elementary.complexes import (conjugate, im, re, + sign) +from sympy.functions.elementary.exponential import LambertW, exp, log +from sympy.functions.elementary.hyperbolic import (asinh, cosh, sinh, + tanh) +from sympy.functions.elementary.integers import ceiling, floor +from sympy.functions.elementary.miscellaneous import Max, Min, sqrt +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.elementary.trigonometric import (acos, acot, asin, + atan, cos, cot, csc, sec, sin, tan) +from sympy.functions.special.bessel import besselj +from sympy.functions.special.delta_functions import DiracDelta +from sympy.functions.special.elliptic_integrals import (elliptic_e, + elliptic_f) +from sympy.functions.special.gamma_functions import gamma, polygamma +from sympy.functions.special.hyper import hyper +from sympy.functions.special.polynomials import (assoc_legendre, + chebyshevt) +from sympy.functions.special.zeta_functions import polylog +from sympy.geometry.util import idiff +from sympy.logic.boolalg import And +from sympy.matrices.dense import hessian, wronskian +from sympy.matrices.expressions.matmul import MatMul +from sympy.ntheory.continued_fraction import ( + continued_fraction_convergents as cf_c, + continued_fraction_iterator as cf_i, continued_fraction_periodic as + cf_p, continued_fraction_reduce as cf_r) +from sympy.ntheory.factor_ import factorint +from sympy.ntheory.generate import primerange +from sympy.polys.domains.integerring import ZZ +from sympy.polys.orthopolys import legendre_poly +from sympy.polys.partfrac import apart +from sympy.polys.polytools import Poly, factor, gcd, resultant +from sympy.series.limits import limit +from sympy.series.order import O +from sympy.series.residues import residue +from sympy.series.series import series +from sympy.sets.fancysets import ImageSet +from sympy.sets.sets import FiniteSet, Intersection, Interval, Union +from sympy.simplify.combsimp import combsimp +from sympy.simplify.hyperexpand import hyperexpand +from sympy.simplify.powsimp import powdenest, powsimp +from sympy.simplify.radsimp import radsimp +from sympy.simplify.simplify import logcombine, simplify +from sympy.simplify.sqrtdenest import sqrtdenest +from sympy.simplify.trigsimp import trigsimp +from sympy.solvers.solvers import solve + +import mpmath +from sympy.functions.combinatorial.numbers import stirling +from sympy.functions.special.delta_functions import Heaviside +from sympy.functions.special.error_functions import Ci, Si, erf +from sympy.functions.special.zeta_functions import zeta +from sympy.testing.pytest import (XFAIL, slow, SKIP, tooslow, raises) +from sympy.utilities.iterables import partitions +from mpmath import mpi, mpc +from sympy.matrices import Matrix, GramSchmidt, eye +from sympy.matrices.expressions.blockmatrix import BlockMatrix, block_collapse +from sympy.matrices.expressions import MatrixSymbol, ZeroMatrix +from sympy.physics.quantum import Commutator +from sympy.polys.rings import PolyRing +from sympy.polys.fields import FracField +from sympy.polys.solvers import solve_lin_sys +from sympy.concrete import Sum +from sympy.concrete.products import Product +from sympy.integrals import integrate +from sympy.integrals.transforms import laplace_transform,\ + inverse_laplace_transform, LaplaceTransform, fourier_transform,\ + mellin_transform, laplace_correspondence, laplace_initial_conds +from sympy.solvers.recurr import rsolve +from sympy.solvers.solveset import solveset, solveset_real, linsolve +from sympy.solvers.ode import dsolve +from sympy.core.relational import Equality +from itertools import islice, takewhile +from sympy.series.formal import fps +from sympy.series.fourier import fourier_series +from sympy.calculus.util import minimum + + +EmptySet = S.EmptySet +R = Rational +x, y, z = symbols('x y z') +i, j, k, l, m, n = symbols('i j k l m n', integer=True) +f = Function('f') +g = Function('g') + +# A. Boolean Logic and Quantifier Elimination +# Not implemented. + +# B. Set Theory + + +def test_B1(): + assert (FiniteSet(i, j, j, k, k, k) | FiniteSet(l, k, j) | + FiniteSet(j, m, j)) == FiniteSet(i, j, k, l, m) + + +def test_B2(): + assert (FiniteSet(i, j, j, k, k, k) & FiniteSet(l, k, j) & + FiniteSet(j, m, j)) == Intersection({j, m}, {i, j, k}, {j, k, l}) + # Previous output below. Not sure why that should be the expected output. + # There should probably be a way to rewrite Intersections that way but I + # don't see why an Intersection should evaluate like that: + # + # == Union({j}, Intersection({m}, Union({j, k}, Intersection({i}, {l})))) + + +def test_B3(): + assert (FiniteSet(i, j, k, l, m) - FiniteSet(j) == + FiniteSet(i, k, l, m)) + + +def test_B4(): + assert (FiniteSet(*(FiniteSet(i, j)*FiniteSet(k, l))) == + FiniteSet((i, k), (i, l), (j, k), (j, l))) + + +# C. Numbers + + +def test_C1(): + assert (factorial(50) == + 30414093201713378043612608166064768844377641568960512000000000000) + + +def test_C2(): + assert (factorint(factorial(50)) == {2: 47, 3: 22, 5: 12, 7: 8, + 11: 4, 13: 3, 17: 2, 19: 2, 23: 2, 29: 1, 31: 1, 37: 1, + 41: 1, 43: 1, 47: 1}) + + +def test_C3(): + assert (factorial2(10), factorial2(9)) == (3840, 945) + + +# Base conversions; not really implemented by SymPy +# Whatever. Take credit! +def test_C4(): + assert 0xABC == 2748 + + +def test_C5(): + assert 123 == int('234', 7) + + +def test_C6(): + assert int('677', 8) == int('1BF', 16) == 447 + + +def test_C7(): + assert log(32768, 8) == 5 + + +def test_C8(): + # Modular multiplicative inverse. Would be nice if divmod could do this. + assert ZZ.invert(5, 7) == 3 + assert ZZ.invert(5, 6) == 5 + + +def test_C9(): + assert igcd(igcd(1776, 1554), 5698) == 74 + + +def test_C10(): + x = 0 + for n in range(2, 11): + x += R(1, n) + assert x == R(4861, 2520) + + +def test_C11(): + assert R(1, 7) == S('0.[142857]') + + +def test_C12(): + assert R(7, 11) * R(22, 7) == 2 + + +def test_C13(): + test = R(10, 7) * (1 + R(29, 1000)) ** R(1, 3) + good = 3 ** R(1, 3) + assert test == good + + +def test_C14(): + assert sqrtdenest(sqrt(2*sqrt(3) + 4)) == 1 + sqrt(3) + + +def test_C15(): + test = sqrtdenest(sqrt(14 + 3*sqrt(3 + 2*sqrt(5 - 12*sqrt(3 - 2*sqrt(2)))))) + good = sqrt(2) + 3 + assert test == good + + +def test_C16(): + test = sqrtdenest(sqrt(10 + 2*sqrt(6) + 2*sqrt(10) + 2*sqrt(15))) + good = sqrt(2) + sqrt(3) + sqrt(5) + assert test == good + + +def test_C17(): + test = radsimp((sqrt(3) + sqrt(2)) / (sqrt(3) - sqrt(2))) + good = 5 + 2*sqrt(6) + assert test == good + + +def test_C18(): + assert simplify((sqrt(-2 + sqrt(-5)) * sqrt(-2 - sqrt(-5))).expand(complex=True)) == 3 + + +@XFAIL +def test_C19(): + assert radsimp(simplify((90 + 34*sqrt(7)) ** R(1, 3))) == 3 + sqrt(7) + + +def test_C20(): + inside = (135 + 78*sqrt(3)) + test = AlgebraicNumber((inside**R(2, 3) + 3) * sqrt(3) / inside**R(1, 3)) + assert simplify(test) == AlgebraicNumber(12) + + +def test_C21(): + assert simplify(AlgebraicNumber((41 + 29*sqrt(2)) ** R(1, 5))) == \ + AlgebraicNumber(1 + sqrt(2)) + + +@XFAIL +def test_C22(): + test = simplify(((6 - 4*sqrt(2))*log(3 - 2*sqrt(2)) + (3 - 2*sqrt(2))*log(17 + - 12*sqrt(2)) + 32 - 24*sqrt(2)) / (48*sqrt(2) - 72)) + good = sqrt(2)/3 - log(sqrt(2) - 1)/3 + assert test == good + + +def test_C23(): + assert 2 * oo - 3 is oo + + +@XFAIL +def test_C24(): + raise NotImplementedError("2**aleph_null == aleph_1") + +# D. Numerical Analysis + + +def test_D1(): + assert 0.0 / sqrt(2) == 0 + + +def test_D2(): + assert str(exp(-1000000).evalf()) == '3.29683147808856e-434295' + + +def test_D3(): + assert exp(pi*sqrt(163)).evalf(50).num.ae(262537412640768744) + + +def test_D4(): + assert floor(R(-5, 3)) == -2 + assert ceiling(R(-5, 3)) == -1 + + +@XFAIL +def test_D5(): + raise NotImplementedError("cubic_spline([1, 2, 4, 5], [1, 4, 2, 3], x)(3) == 27/8") + + +@XFAIL +def test_D6(): + raise NotImplementedError("translate sum(a[i]*x**i, (i,1,n)) to FORTRAN") + + +@XFAIL +def test_D7(): + raise NotImplementedError("translate sum(a[i]*x**i, (i,1,n)) to C") + + +@XFAIL +def test_D8(): + # One way is to cheat by converting the sum to a string, + # and replacing the '[' and ']' with ''. + # E.g., horner(S(str(_).replace('[','').replace(']',''))) + raise NotImplementedError("apply Horner's rule to sum(a[i]*x**i, (i,1,5))") + + +@XFAIL +def test_D9(): + raise NotImplementedError("translate D8 to FORTRAN") + + +@XFAIL +def test_D10(): + raise NotImplementedError("translate D8 to C") + + +@XFAIL +def test_D11(): + #Is there a way to use count_ops? + raise NotImplementedError("flops(sum(product(f[i][k], (i,1,k)), (k,1,n)))") + + +@XFAIL +def test_D12(): + assert (mpi(-4, 2) * x + mpi(1, 3)) ** 2 == mpi(-8, 16)*x**2 + mpi(-24, 12)*x + mpi(1, 9) + + +@XFAIL +def test_D13(): + raise NotImplementedError("discretize a PDE: diff(f(x,t),t) == diff(diff(f(x,t),x),x)") + +# E. Statistics +# See scipy; all of this is numerical. + +# F. Combinatorial Theory. + + +def test_F1(): + assert rf(x, 3) == x*(1 + x)*(2 + x) + + +def test_F2(): + assert expand_func(binomial(n, 3)) == n*(n - 1)*(n - 2)/6 + + +@XFAIL +def test_F3(): + assert combsimp(2**n * factorial(n) * factorial2(2*n - 1)) == factorial(2*n) + + +@XFAIL +def test_F4(): + assert combsimp(2**n * factorial(n) * product(2*k - 1, (k, 1, n))) == factorial(2*n) + + +@XFAIL +def test_F5(): + assert gamma(n + R(1, 2)) / sqrt(pi) / factorial(n) == factorial(2*n)/2**(2*n)/factorial(n)**2 + + +def test_F6(): + partTest = [p.copy() for p in partitions(4)] + partDesired = [{4: 1}, {1: 1, 3: 1}, {2: 2}, {1: 2, 2:1}, {1: 4}] + assert partTest == partDesired + + +def test_F7(): + assert partition(4) == 5 + + +def test_F8(): + assert stirling(5, 2, signed=True) == -50 # if signed, then kind=1 + + +def test_F9(): + assert totient(1776) == 576 + +# G. Number Theory + + +def test_G1(): + assert list(primerange(999983, 1000004)) == [999983, 1000003] + + +@XFAIL +def test_G2(): + raise NotImplementedError("find the primitive root of 191 == 19") + + +@XFAIL +def test_G3(): + raise NotImplementedError("(a+b)**p mod p == a**p + b**p mod p; p prime") + +# ... G14 Modular equations are not implemented. + +def test_G15(): + assert Rational(sqrt(3).evalf()).limit_denominator(15) == R(26, 15) + assert list(takewhile(lambda x: x.q <= 15, cf_c(cf_i(sqrt(3)))))[-1] == \ + R(26, 15) + + +def test_G16(): + assert list(islice(cf_i(pi),10)) == [3, 7, 15, 1, 292, 1, 1, 1, 2, 1] + + +def test_G17(): + assert cf_p(0, 1, 23) == [4, [1, 3, 1, 8]] + + +def test_G18(): + assert cf_p(1, 2, 5) == [[1]] + assert cf_r([[1]]).expand() == S.Half + sqrt(5)/2 + + +@XFAIL +def test_G19(): + s = symbols('s', integer=True, positive=True) + it = cf_i((exp(1/s) - 1)/(exp(1/s) + 1)) + assert list(islice(it, 5)) == [0, 2*s, 6*s, 10*s, 14*s] + + +def test_G20(): + s = symbols('s', integer=True, positive=True) + # Wester erroneously has this as -s + sqrt(s**2 + 1) + assert cf_r([[2*s]]) == s + sqrt(s**2 + 1) + + +@XFAIL +def test_G20b(): + s = symbols('s', integer=True, positive=True) + assert cf_p(s, 1, s**2 + 1) == [[2*s]] + + +# H. Algebra + + +def test_H1(): + assert simplify(2*2**n) == simplify(2**(n + 1)) + assert powdenest(2*2**n) == simplify(2**(n + 1)) + + +def test_H2(): + assert powsimp(4 * 2**n) == 2**(n + 2) + + +def test_H3(): + assert (-1)**(n*(n + 1)) == 1 + + +def test_H4(): + expr = factor(6*x - 10) + assert type(expr) is Mul + assert expr.args[0] == 2 + assert expr.args[1] == 3*x - 5 + +p1 = 64*x**34 - 21*x**47 - 126*x**8 - 46*x**5 - 16*x**60 - 81 +p2 = 72*x**60 - 25*x**25 - 19*x**23 - 22*x**39 - 83*x**52 + 54*x**10 + 81 +q = 34*x**19 - 25*x**16 + 70*x**7 + 20*x**3 - 91*x - 86 + + +def test_H5(): + assert gcd(p1, p2, x) == 1 + + +def test_H6(): + assert gcd(expand(p1 * q), expand(p2 * q)) == q + + +def test_H7(): + p1 = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5 + p2 = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z + assert gcd(p1, p2, x, y, z) == 1 + + +def test_H8(): + p1 = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5 + p2 = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z + q = 11*x**12*y**7*z**13 - 23*x**2*y**8*z**10 + 47*x**17*y**5*z**8 + assert gcd(p1 * q, p2 * q, x, y, z) == q + + +def test_H9(): + x = Symbol('x', zero=False) + p1 = 2*x**(n + 4) - x**(n + 2) + p2 = 4*x**(n + 1) + 3*x**n + assert gcd(p1, p2) == x**n + + +def test_H10(): + p1 = 3*x**4 + 3*x**3 + x**2 - x - 2 + p2 = x**3 - 3*x**2 + x + 5 + assert resultant(p1, p2, x) == 0 + + +def test_H11(): + assert resultant(p1 * q, p2 * q, x) == 0 + + +def test_H12(): + num = x**2 - 4 + den = x**2 + 4*x + 4 + assert simplify(num/den) == (x - 2)/(x + 2) + + +@XFAIL +def test_H13(): + assert simplify((exp(x) - 1) / (exp(x/2) + 1)) == exp(x/2) - 1 + + +def test_H14(): + p = (x + 1) ** 20 + ep = expand(p) + assert ep == (1 + 20*x + 190*x**2 + 1140*x**3 + 4845*x**4 + 15504*x**5 + + 38760*x**6 + 77520*x**7 + 125970*x**8 + 167960*x**9 + 184756*x**10 + + 167960*x**11 + 125970*x**12 + 77520*x**13 + 38760*x**14 + 15504*x**15 + + 4845*x**16 + 1140*x**17 + 190*x**18 + 20*x**19 + x**20) + dep = diff(ep, x) + assert dep == (20 + 380*x + 3420*x**2 + 19380*x**3 + 77520*x**4 + + 232560*x**5 + 542640*x**6 + 1007760*x**7 + 1511640*x**8 + 1847560*x**9 + + 1847560*x**10 + 1511640*x**11 + 1007760*x**12 + 542640*x**13 + + 232560*x**14 + 77520*x**15 + 19380*x**16 + 3420*x**17 + 380*x**18 + + 20*x**19) + assert factor(dep) == 20*(1 + x)**19 + + +def test_H15(): + assert simplify(Mul(*[x - r for r in solveset(x**3 + x**2 - 7)])) == x**3 + x**2 - 7 + + +def test_H16(): + assert factor(x**100 - 1) == ((x - 1)*(x + 1)*(x**2 + 1)*(x**4 - x**3 + + x**2 - x + 1)*(x**4 + x**3 + x**2 + x + 1)*(x**8 - x**6 + x**4 + - x**2 + 1)*(x**20 - x**15 + x**10 - x**5 + 1)*(x**20 + x**15 + x**10 + + x**5 + 1)*(x**40 - x**30 + x**20 - x**10 + 1)) + + +def test_H17(): + assert simplify(factor(expand(p1 * p2)) - p1*p2) == 0 + + +@XFAIL +def test_H18(): + # Factor over complex rationals. + test = factor(4*x**4 + 8*x**3 + 77*x**2 + 18*x + 153) + good = (2*x + 3*I)*(2*x - 3*I)*(x + 1 - 4*I)*(x + 1 + 4*I) + assert test == good + + +def test_H19(): + a = symbols('a') + # The idea is to let a**2 == 2, then solve 1/(a-1). Answer is a+1") + assert Poly(a - 1).invert(Poly(a**2 - 2)) == a + 1 + + +@XFAIL +def test_H20(): + raise NotImplementedError("let a**2==2; (x**3 + (a-2)*x**2 - " + + "(2*a+3)*x - 3*a) / (x**2-2) = (x**2 - 2*x - 3) / (x-a)") + + +@XFAIL +def test_H21(): + raise NotImplementedError("evaluate (b+c)**4 assuming b**3==2, c**2==3. \ + Answer is 2*b + 8*c + 18*b**2 + 12*b*c + 9") + + +def test_H22(): + assert factor(x**4 - 3*x**2 + 1, modulus=5) == (x - 2)**2 * (x + 2)**2 + + +def test_H23(): + f = x**11 + x + 1 + g = (x**2 + x + 1) * (x**9 - x**8 + x**6 - x**5 + x**3 - x**2 + 1) + assert factor(f, modulus=65537) == g + + +def test_H24(): + phi = AlgebraicNumber(S.GoldenRatio.expand(func=True), alias='phi') + assert factor(x**4 - 3*x**2 + 1, extension=phi) == \ + (x - phi)*(x + 1 - phi)*(x - 1 + phi)*(x + phi) + + +def test_H25(): + e = (x - 2*y**2 + 3*z**3) ** 20 + assert factor(expand(e)) == e + + +def test_H26(): + g = expand((sin(x) - 2*cos(y)**2 + 3*tan(z)**3)**20) + assert factor(g, expand=False) == (-sin(x) + 2*cos(y)**2 - 3*tan(z)**3)**20 + + +def test_H27(): + f = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5 + g = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z + h = -2*z*y**7 \ + *(6*x**9*y**9*z**3 + 10*x**7*z**6 + 17*y*x**5*z**12 + 40*y**7) \ + *(3*x**22 + 47*x**17*y**5*z**8 - 6*x**15*y**9*z**2 - 24*x*y**19*z**8 - 5) + assert factor(expand(f*g)) == h + + +@XFAIL +def test_H28(): + raise NotImplementedError("expand ((1 - c**2)**5 * (1 - s**2)**5 * " + + "(c**2 + s**2)**10) with c**2 + s**2 = 1. Answer is c**10*s**10.") + + +@XFAIL +def test_H29(): + assert factor(4*x**2 - 21*x*y + 20*y**2, modulus=3) == (x + y)*(x - y) + + +def test_H30(): + test = factor(x**3 + y**3, extension=sqrt(-3)) + answer = (x + y)*(x + y*(-R(1, 2) - sqrt(3)/2*I))*(x + y*(-R(1, 2) + sqrt(3)/2*I)) + assert answer == test + + +def test_H31(): + f = (x**2 + 2*x + 3)/(x**3 + 4*x**2 + 5*x + 2) + g = 2 / (x + 1)**2 - 2 / (x + 1) + 3 / (x + 2) + assert apart(f) == g + + +@XFAIL +def test_H32(): # issue 6558 + raise NotImplementedError("[A*B*C - (A*B*C)**(-1)]*A*C*B (product \ + of a non-commuting product and its inverse)") + + +def test_H33(): + A, B, C = symbols('A, B, C', commutative=False) + assert (Commutator(A, Commutator(B, C)) + + Commutator(B, Commutator(C, A)) + + Commutator(C, Commutator(A, B))).doit().expand() == 0 + + +# I. Trigonometry + +def test_I1(): + assert tan(pi*R(7, 10)) == -sqrt(1 + 2/sqrt(5)) + + +@XFAIL +def test_I2(): + assert sqrt((1 + cos(6))/2) == -cos(3) + + +def test_I3(): + assert cos(n*pi) + sin((4*n - 1)*pi/2) == (-1)**n - 1 + + +def test_I4(): + assert refine(cos(pi*cos(n*pi)) + sin(pi/2*cos(n*pi)), Q.integer(n)) == (-1)**n - 1 + + +@XFAIL +def test_I5(): + assert sin((n**5/5 + n**4/2 + n**3/3 - n/30) * pi) == 0 + + +@XFAIL +def test_I6(): + raise NotImplementedError("assuming -3*pi pi**E) + + +@XFAIL +def test_N2(): + x = symbols('x', real=True) + assert ask(x**4 - x + 1 > 0) is True + assert ask(x**4 - x + 1 > 1) is False + + +@XFAIL +def test_N3(): + x = symbols('x', real=True) + assert ask(And(Lt(-1, x), Lt(x, 1)), abs(x) < 1 ) + +@XFAIL +def test_N4(): + x, y = symbols('x y', real=True) + assert ask(2*x**2 > 2*y**2, (x > y) & (y > 0)) is True + + +@XFAIL +def test_N5(): + x, y, k = symbols('x y k', real=True) + assert ask(k*x**2 > k*y**2, (x > y) & (y > 0) & (k > 0)) is True + + +@slow +@XFAIL +def test_N6(): + x, y, k, n = symbols('x y k n', real=True) + assert ask(k*x**n > k*y**n, (x > y) & (y > 0) & (k > 0) & (n > 0)) is True + + +@XFAIL +def test_N7(): + x, y = symbols('x y', real=True) + assert ask(y > 0, (x > 1) & (y >= x - 1)) is True + + +@XFAIL +@slow +def test_N8(): + x, y, z = symbols('x y z', real=True) + assert ask(Eq(x, y) & Eq(y, z), + (x >= y) & (y >= z) & (z >= x)) + + +def test_N9(): + x = Symbol('x') + assert solveset(abs(x - 1) > 2, domain=S.Reals) == Union(Interval(-oo, -1, False, True), + Interval(3, oo, True)) + + +def test_N10(): + x = Symbol('x') + p = (x - 1)*(x - 2)*(x - 3)*(x - 4)*(x - 5) + assert solveset(expand(p) < 0, domain=S.Reals) == Union(Interval(-oo, 1, True, True), + Interval(2, 3, True, True), + Interval(4, 5, True, True)) + + +def test_N11(): + x = Symbol('x') + assert solveset(6/(x - 3) <= 3, domain=S.Reals) == Union(Interval(-oo, 3, True, True), Interval(5, oo)) + + +def test_N12(): + x = Symbol('x') + assert solveset(sqrt(x) < 2, domain=S.Reals) == Interval(0, 4, False, True) + + +def test_N13(): + x = Symbol('x') + assert solveset(sin(x) < 2, domain=S.Reals) == S.Reals + + +@XFAIL +def test_N14(): + x = Symbol('x') + # Gives 'Union(Interval(Integer(0), Mul(Rational(1, 2), pi), false, true), + # Interval(Mul(Rational(1, 2), pi), Mul(Integer(2), pi), true, false))' + # which is not the correct answer, but the provided also seems wrong. + assert solveset(sin(x) < 1, x, domain=S.Reals) == Union(Interval(-oo, pi/2, True, True), + Interval(pi/2, oo, True, True)) + + +def test_N15(): + r, t = symbols('r t') + # raises NotImplementedError: only univariate inequalities are supported + solveset(abs(2*r*(cos(t) - 1) + 1) <= 1, r, S.Reals) + + +def test_N16(): + r, t = symbols('r t') + solveset((r**2)*((cos(t) - 4)**2)*sin(t)**2 < 9, r, S.Reals) + + +@XFAIL +def test_N17(): + # currently only univariate inequalities are supported + assert solveset((x + y > 0, x - y < 0), (x, y)) == (abs(x) < y) + + +def test_O1(): + M = Matrix((1 + I, -2, 3*I)) + assert sqrt(expand(M.dot(M.H))) == sqrt(15) + + +def test_O2(): + assert Matrix((2, 2, -3)).cross(Matrix((1, 3, 1))) == Matrix([[11], + [-5], + [4]]) + +# The vector module has no way of representing vectors symbolically (without +# respect to a basis) +@XFAIL +def test_O3(): + # assert (va ^ vb) | (vc ^ vd) == -(va | vc)*(vb | vd) + (va | vd)*(vb | vc) + raise NotImplementedError("""The vector module has no way of representing + vectors symbolically (without respect to a basis)""") + +def test_O4(): + from sympy.vector import CoordSys3D, Del + N = CoordSys3D("N") + delop = Del() + i, j, k = N.base_vectors() + x, y, z = N.base_scalars() + F = i*(x*y*z) + j*((x*y*z)**2) + k*((y**2)*(z**3)) + assert delop.cross(F).doit() == (-2*x**2*y**2*z + 2*y*z**3)*i + x*y*j + (2*x*y**2*z**2 - x*z)*k + +@XFAIL +def test_O5(): + #assert grad|(f^g)-g|(grad^f)+f|(grad^g) == 0 + raise NotImplementedError("""The vector module has no way of representing + vectors symbolically (without respect to a basis)""") + +#testO8-O9 MISSING!! + + +def test_O10(): + L = [Matrix([2, 3, 5]), Matrix([3, 6, 2]), Matrix([8, 3, 6])] + assert GramSchmidt(L) == [Matrix([ + [2], + [3], + [5]]), + Matrix([ + [R(23, 19)], + [R(63, 19)], + [R(-47, 19)]]), + Matrix([ + [R(1692, 353)], + [R(-1551, 706)], + [R(-423, 706)]])] + + +def test_P1(): + assert Matrix(3, 3, lambda i, j: j - i).diagonal(-1) == Matrix( + 1, 2, [-1, -1]) + + +def test_P2(): + M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + M.row_del(1) + M.col_del(2) + assert M == Matrix([[1, 2], + [7, 8]]) + + +def test_P3(): + A = Matrix([ + [11, 12, 13, 14], + [21, 22, 23, 24], + [31, 32, 33, 34], + [41, 42, 43, 44]]) + + A11 = A[0:3, 1:4] + A12 = A[(0, 1, 3), (2, 0, 3)] + A21 = A + A221 = -A[0:2, 2:4] + A222 = -A[(3, 0), (2, 1)] + A22 = BlockMatrix([[A221, A222]]).T + rows = [[-A11, A12], [A21, A22]] + raises(ValueError, lambda: BlockMatrix(rows)) + B = Matrix(rows) + assert B == Matrix([ + [-12, -13, -14, 13, 11, 14], + [-22, -23, -24, 23, 21, 24], + [-32, -33, -34, 43, 41, 44], + [11, 12, 13, 14, -13, -23], + [21, 22, 23, 24, -14, -24], + [31, 32, 33, 34, -43, -13], + [41, 42, 43, 44, -42, -12]]) + + +@XFAIL +def test_P4(): + raise NotImplementedError("Block matrix diagonalization not supported") + + +def test_P5(): + M = Matrix([[7, 11], + [3, 8]]) + assert M % 2 == Matrix([[1, 1], + [1, 0]]) + + +def test_P6(): + M = Matrix([[cos(x), sin(x)], + [-sin(x), cos(x)]]) + assert M.diff(x, 2) == Matrix([[-cos(x), -sin(x)], + [sin(x), -cos(x)]]) + + +def test_P7(): + M = Matrix([[x, y]])*( + z*Matrix([[1, 3, 5], + [2, 4, 6]]) + Matrix([[7, -9, 11], + [-8, 10, -12]])) + assert M == Matrix([[x*(z + 7) + y*(2*z - 8), x*(3*z - 9) + y*(4*z + 10), + x*(5*z + 11) + y*(6*z - 12)]]) + + +def test_P8(): + M = Matrix([[1, -2*I], + [-3*I, 4]]) + assert M.norm(ord=S.Infinity) == 7 + + +def test_P9(): + a, b, c = symbols('a b c', nonzero=True) + M = Matrix([[a/(b*c), 1/c, 1/b], + [1/c, b/(a*c), 1/a], + [1/b, 1/a, c/(a*b)]]) + assert factor(M.norm('fro')) == (a**2 + b**2 + c**2)/(abs(a)*abs(b)*abs(c)) + + +@XFAIL +def test_P10(): + M = Matrix([[1, 2 + 3*I], + [f(4 - 5*I), 6]]) + # conjugate(f(4 - 5*i)) is not simplified to f(4+5*I) + assert M.H == Matrix([[1, f(4 + 5*I)], + [2 + 3*I, 6]]) + + +@XFAIL +def test_P11(): + # raises NotImplementedError("Matrix([[x,y],[1,x*y]]).inv() + # not simplifying to extract common factor") + assert Matrix([[x, y], + [1, x*y]]).inv() == (1/(x**2 - 1))*Matrix([[x, -1], + [-1/y, x/y]]) + + +def test_P11_workaround(): + # This test was changed to inverse method ADJ because it depended on the + # specific form of inverse returned from the 'GE' method which has changed. + M = Matrix([[x, y], [1, x*y]]).inv('ADJ') + c = gcd(tuple(M)) + assert MatMul(c, M/c, evaluate=False) == MatMul(c, Matrix([ + [x*y, -y], + [ -1, x]]), evaluate=False) + + +def test_P12(): + A11 = MatrixSymbol('A11', n, n) + A12 = MatrixSymbol('A12', n, n) + A22 = MatrixSymbol('A22', n, n) + B = BlockMatrix([[A11, A12], + [ZeroMatrix(n, n), A22]]) + assert block_collapse(B.I) == BlockMatrix([[A11.I, (-1)*A11.I*A12*A22.I], + [ZeroMatrix(n, n), A22.I]]) + + +def test_P13(): + M = Matrix([[1, x - 2, x - 3], + [x - 1, x**2 - 3*x + 6, x**2 - 3*x - 2], + [x - 2, x**2 - 8, 2*(x**2) - 12*x + 14]]) + L, U, _ = M.LUdecomposition() + assert simplify(L) == Matrix([[1, 0, 0], + [x - 1, 1, 0], + [x - 2, x - 3, 1]]) + assert simplify(U) == Matrix([[1, x - 2, x - 3], + [0, 4, x - 5], + [0, 0, x - 7]]) + + +def test_P14(): + M = Matrix([[1, 2, 3, 1, 3], + [3, 2, 1, 1, 7], + [0, 2, 4, 1, 1], + [1, 1, 1, 1, 4]]) + R, _ = M.rref() + assert R == Matrix([[1, 0, -1, 0, 2], + [0, 1, 2, 0, -1], + [0, 0, 0, 1, 3], + [0, 0, 0, 0, 0]]) + + +def test_P15(): + M = Matrix([[-1, 3, 7, -5], + [4, -2, 1, 3], + [2, 4, 15, -7]]) + assert M.rank() == 2 + + +def test_P16(): + M = Matrix([[2*sqrt(2), 8], + [6*sqrt(6), 24*sqrt(3)]]) + assert M.rank() == 1 + + +def test_P17(): + t = symbols('t', real=True) + M=Matrix([ + [sin(2*t), cos(2*t)], + [2*(1 - (cos(t)**2))*cos(t), (1 - 2*(sin(t)**2))*sin(t)]]) + assert M.rank() == 1 + + +def test_P18(): + M = Matrix([[1, 0, -2, 0], + [-2, 1, 0, 3], + [-1, 2, -6, 6]]) + assert M.nullspace() == [Matrix([[2], + [4], + [1], + [0]]), + Matrix([[0], + [-3], + [0], + [1]])] + + +def test_P19(): + w = symbols('w') + M = Matrix([[1, 1, 1, 1], + [w, x, y, z], + [w**2, x**2, y**2, z**2], + [w**3, x**3, y**3, z**3]]) + assert M.det() == (w**3*x**2*y - w**3*x**2*z - w**3*x*y**2 + w**3*x*z**2 + + w**3*y**2*z - w**3*y*z**2 - w**2*x**3*y + w**2*x**3*z + + w**2*x*y**3 - w**2*x*z**3 - w**2*y**3*z + w**2*y*z**3 + + w*x**3*y**2 - w*x**3*z**2 - w*x**2*y**3 + w*x**2*z**3 + + w*y**3*z**2 - w*y**2*z**3 - x**3*y**2*z + x**3*y*z**2 + + x**2*y**3*z - x**2*y*z**3 - x*y**3*z**2 + x*y**2*z**3 + ) + + +@XFAIL +def test_P20(): + raise NotImplementedError("Matrix minimal polynomial not supported") + + +def test_P21(): + M = Matrix([[5, -3, -7], + [-2, 1, 2], + [2, -3, -4]]) + assert M.charpoly(x).as_expr() == x**3 - 2*x**2 - 5*x + 6 + + +def test_P22(): + d = 100 + M = (2 - x)*eye(d) + assert M.eigenvals() == {-x + 2: d} + + +def test_P23(): + M = Matrix([ + [2, 1, 0, 0, 0], + [1, 2, 1, 0, 0], + [0, 1, 2, 1, 0], + [0, 0, 1, 2, 1], + [0, 0, 0, 1, 2]]) + assert M.eigenvals() == { + S('1'): 1, + S('2'): 1, + S('3'): 1, + S('sqrt(3) + 2'): 1, + S('-sqrt(3) + 2'): 1} + + +def test_P24(): + M = Matrix([[611, 196, -192, 407, -8, -52, -49, 29], + [196, 899, 113, -192, -71, -43, -8, -44], + [-192, 113, 899, 196, 61, 49, 8, 52], + [ 407, -192, 196, 611, 8, 44, 59, -23], + [ -8, -71, 61, 8, 411, -599, 208, 208], + [ -52, -43, 49, 44, -599, 411, 208, 208], + [ -49, -8, 8, 59, 208, 208, 99, -911], + [ 29, -44, 52, -23, 208, 208, -911, 99]]) + assert M.eigenvals() == { + S('0'): 1, + S('10*sqrt(10405)'): 1, + S('100*sqrt(26) + 510'): 1, + S('1000'): 2, + S('-100*sqrt(26) + 510'): 1, + S('-10*sqrt(10405)'): 1, + S('1020'): 1} + + +def test_P25(): + MF = N(Matrix([[ 611, 196, -192, 407, -8, -52, -49, 29], + [ 196, 899, 113, -192, -71, -43, -8, -44], + [-192, 113, 899, 196, 61, 49, 8, 52], + [ 407, -192, 196, 611, 8, 44, 59, -23], + [ -8, -71, 61, 8, 411, -599, 208, 208], + [ -52, -43, 49, 44, -599, 411, 208, 208], + [ -49, -8, 8, 59, 208, 208, 99, -911], + [ 29, -44, 52, -23, 208, 208, -911, 99]])) + + ev_1 = sorted(MF.eigenvals(multiple=True)) + ev_2 = sorted( + [-1020.0490184299969, 0.0, 0.09804864072151699, 1000.0, 1000.0, + 1019.9019513592784, 1020.0, 1020.0490184299969]) + + for x, y in zip(ev_1, ev_2): + assert abs(x - y) < 1e-12 + + +def test_P26(): + a0, a1, a2, a3, a4 = symbols('a0 a1 a2 a3 a4') + M = Matrix([[-a4, -a3, -a2, -a1, -a0, 0, 0, 0, 0], + [ 1, 0, 0, 0, 0, 0, 0, 0, 0], + [ 0, 1, 0, 0, 0, 0, 0, 0, 0], + [ 0, 0, 1, 0, 0, 0, 0, 0, 0], + [ 0, 0, 0, 1, 0, 0, 0, 0, 0], + [ 0, 0, 0, 0, 0, -1, -1, 0, 0], + [ 0, 0, 0, 0, 0, 1, 0, 0, 0], + [ 0, 0, 0, 0, 0, 0, 1, -1, -1], + [ 0, 0, 0, 0, 0, 0, 0, 1, 0]]) + assert M.eigenvals(error_when_incomplete=False) == { + S('-1/2 - sqrt(3)*I/2'): 2, + S('-1/2 + sqrt(3)*I/2'): 2} + + +def test_P27(): + a = symbols('a') + M = Matrix([[a, 0, 0, 0, 0], + [0, 0, 0, 0, 1], + [0, 0, a, 0, 0], + [0, 0, 0, a, 0], + [0, -2, 0, 0, 2]]) + + assert M.eigenvects() == [ + (a, 3, [ + Matrix([1, 0, 0, 0, 0]), + Matrix([0, 0, 1, 0, 0]), + Matrix([0, 0, 0, 1, 0]) + ]), + (1 - I, 1, [ + Matrix([0, (1 + I)/2, 0, 0, 1]) + ]), + (1 + I, 1, [ + Matrix([0, (1 - I)/2, 0, 0, 1]) + ]), + ] + + +@XFAIL +def test_P28(): + raise NotImplementedError("Generalized eigenvectors not supported \ +https://github.com/sympy/sympy/issues/5293") + + +@XFAIL +def test_P29(): + raise NotImplementedError("Generalized eigenvectors not supported \ +https://github.com/sympy/sympy/issues/5293") + + +def test_P30(): + M = Matrix([[1, 0, 0, 1, -1], + [0, 1, -2, 3, -3], + [0, 0, -1, 2, -2], + [1, -1, 1, 0, 1], + [1, -1, 1, -1, 2]]) + _, J = M.jordan_form() + assert J == Matrix([[-1, 0, 0, 0, 0], + [0, 1, 1, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 1, 1], + [0, 0, 0, 0, 1]]) + + +@XFAIL +def test_P31(): + raise NotImplementedError("Smith normal form not implemented") + + +def test_P32(): + M = Matrix([[1, -2], + [2, 1]]) + assert exp(M).rewrite(cos).simplify() == Matrix([[E*cos(2), -E*sin(2)], + [E*sin(2), E*cos(2)]]) + + +def test_P33(): + w, t = symbols('w t') + M = Matrix([[0, 1, 0, 0], + [0, 0, 0, 2*w], + [0, 0, 0, 1], + [0, -2*w, 3*w**2, 0]]) + assert exp(M*t).rewrite(cos).expand() == Matrix([ + [1, -3*t + 4*sin(t*w)/w, 6*t*w - 6*sin(t*w), -2*cos(t*w)/w + 2/w], + [0, 4*cos(t*w) - 3, -6*w*cos(t*w) + 6*w, 2*sin(t*w)], + [0, 2*cos(t*w)/w - 2/w, -3*cos(t*w) + 4, sin(t*w)/w], + [0, -2*sin(t*w), 3*w*sin(t*w), cos(t*w)]]) + + +@XFAIL +def test_P34(): + a, b, c = symbols('a b c', real=True) + M = Matrix([[a, 1, 0, 0, 0, 0], + [0, a, 0, 0, 0, 0], + [0, 0, b, 0, 0, 0], + [0, 0, 0, c, 1, 0], + [0, 0, 0, 0, c, 1], + [0, 0, 0, 0, 0, c]]) + # raises exception, sin(M) not supported. exp(M*I) also not supported + # https://github.com/sympy/sympy/issues/6218 + assert sin(M) == Matrix([[sin(a), cos(a), 0, 0, 0, 0], + [0, sin(a), 0, 0, 0, 0], + [0, 0, sin(b), 0, 0, 0], + [0, 0, 0, sin(c), cos(c), -sin(c)/2], + [0, 0, 0, 0, sin(c), cos(c)], + [0, 0, 0, 0, 0, sin(c)]]) + + +@XFAIL +def test_P35(): + M = pi/2*Matrix([[2, 1, 1], + [2, 3, 2], + [1, 1, 2]]) + # raises exception, sin(M) not supported. exp(M*I) also not supported + # https://github.com/sympy/sympy/issues/6218 + assert sin(M) == eye(3) + + +@XFAIL +def test_P36(): + M = Matrix([[10, 7], + [7, 17]]) + assert sqrt(M) == Matrix([[3, 1], + [1, 4]]) + + +def test_P37(): + M = Matrix([[1, 1, 0], + [0, 1, 0], + [0, 0, 1]]) + assert M**S.Half == Matrix([[1, R(1, 2), 0], + [0, 1, 0], + [0, 0, 1]]) + + +@XFAIL +def test_P38(): + M=Matrix([[0, 1, 0], + [0, 0, 0], + [0, 0, 0]]) + + with raises(AssertionError): + # raises ValueError: Matrix det == 0; not invertible + M**S.Half + # if it doesn't raise then this assertion will be + # raised and the test will be flagged as not XFAILing + assert None + +@XFAIL +def test_P39(): + """ + M=Matrix([ + [1, 1], + [2, 2], + [3, 3]]) + M.SVD() + """ + raise NotImplementedError("Singular value decomposition not implemented") + + +def test_P40(): + r, t = symbols('r t', real=True) + M = Matrix([r*cos(t), r*sin(t)]) + assert M.jacobian(Matrix([r, t])) == Matrix([[cos(t), -r*sin(t)], + [sin(t), r*cos(t)]]) + + +def test_P41(): + r, t = symbols('r t', real=True) + assert hessian(r**2*sin(t),(r,t)) == Matrix([[ 2*sin(t), 2*r*cos(t)], + [2*r*cos(t), -r**2*sin(t)]]) + + +def test_P42(): + assert wronskian([cos(x), sin(x)], x).simplify() == 1 + + +def test_P43(): + def __my_jacobian(M, Y): + return Matrix([M.diff(v).T for v in Y]).T + r, t = symbols('r t', real=True) + M = Matrix([r*cos(t), r*sin(t)]) + assert __my_jacobian(M,[r,t]) == Matrix([[cos(t), -r*sin(t)], + [sin(t), r*cos(t)]]) + + +def test_P44(): + def __my_hessian(f, Y): + V = Matrix([diff(f, v) for v in Y]) + return Matrix([V.T.diff(v) for v in Y]) + r, t = symbols('r t', real=True) + assert __my_hessian(r**2*sin(t), (r, t)) == Matrix([ + [ 2*sin(t), 2*r*cos(t)], + [2*r*cos(t), -r**2*sin(t)]]) + + +def test_P45(): + def __my_wronskian(Y, v): + M = Matrix([Matrix(Y).T.diff(x, n) for n in range(0, len(Y))]) + return M.det() + assert __my_wronskian([cos(x), sin(x)], x).simplify() == 1 + +# Q1-Q6 Tensor tests missing + + +@XFAIL +def test_R1(): + i, j, n = symbols('i j n', integer=True, positive=True) + xn = MatrixSymbol('xn', n, 1) + Sm = Sum((xn[i, 0] - Sum(xn[j, 0], (j, 0, n - 1))/n)**2, (i, 0, n - 1)) + # sum does not calculate + # Unknown result + Sm.doit() + raise NotImplementedError('Unknown result') + +@XFAIL +def test_R2(): + m, b = symbols('m b') + i, n = symbols('i n', integer=True, positive=True) + xn = MatrixSymbol('xn', n, 1) + yn = MatrixSymbol('yn', n, 1) + f = Sum((yn[i, 0] - m*xn[i, 0] - b)**2, (i, 0, n - 1)) + f1 = diff(f, m) + f2 = diff(f, b) + # raises TypeError: solveset() takes at most 2 arguments (3 given) + solveset((f1, f2), (m, b), domain=S.Reals) + + +@XFAIL +def test_R3(): + n, k = symbols('n k', integer=True, positive=True) + sk = ((-1)**k) * (binomial(2*n, k))**2 + Sm = Sum(sk, (k, 1, oo)) + T = Sm.doit() + T2 = T.combsimp() + # returns -((-1)**n*factorial(2*n) + # - (factorial(n))**2)*exp_polar(-I*pi)/(factorial(n))**2 + assert T2 == (-1)**n*binomial(2*n, n) + + +@XFAIL +def test_R4(): +# Macsyma indefinite sum test case: +#(c15) /* Check whether the full Gosper algorithm is implemented +# => 1/2^(n + 1) binomial(n, k - 1) */ +#closedform(indefsum(binomial(n, k)/2^n - binomial(n + 1, k)/2^(n + 1), k)); +#Time= 2690 msecs +# (- n + k - 1) binomial(n + 1, k) +#(d15) - -------------------------------- +# n +# 2 2 (n + 1) +# +#(c16) factcomb(makefact(%)); +#Time= 220 msecs +# n! +#(d16) ---------------- +# n +# 2 k! 2 (n - k)! +# Might be possible after fixing https://github.com/sympy/sympy/pull/1879 + raise NotImplementedError("Indefinite sum not supported") + + +@XFAIL +def test_R5(): + a, b, c, n, k = symbols('a b c n k', integer=True, positive=True) + sk = ((-1)**k)*(binomial(a + b, a + k) + *binomial(b + c, b + k)*binomial(c + a, c + k)) + Sm = Sum(sk, (k, 1, oo)) + T = Sm.doit() # hypergeometric series not calculated + assert T == factorial(a+b+c)/(factorial(a)*factorial(b)*factorial(c)) + + +def test_R6(): + n, k = symbols('n k', integer=True, positive=True) + gn = MatrixSymbol('gn', n + 2, 1) + Sm = Sum(gn[k, 0] - gn[k - 1, 0], (k, 1, n + 1)) + assert Sm.doit() == -gn[0, 0] + gn[n + 1, 0] + + +def test_R7(): + n, k = symbols('n k', integer=True, positive=True) + T = Sum(k**3,(k,1,n)).doit() + assert T.factor() == n**2*(n + 1)**2/4 + +@XFAIL +def test_R8(): + n, k = symbols('n k', integer=True, positive=True) + Sm = Sum(k**2*binomial(n, k), (k, 1, n)) + T = Sm.doit() #returns Piecewise function + assert T.combsimp() == n*(n + 1)*2**(n - 2) + + +def test_R9(): + n, k = symbols('n k', integer=True, positive=True) + Sm = Sum(binomial(n, k - 1)/k, (k, 1, n + 1)) + assert Sm.doit().simplify() == (2**(n + 1) - 1)/(n + 1) + + +@XFAIL +def test_R10(): + n, m, r, k = symbols('n m r k', integer=True, positive=True) + Sm = Sum(binomial(n, k)*binomial(m, r - k), (k, 0, r)) + T = Sm.doit() + T2 = T.combsimp().rewrite(factorial) + assert T2 == factorial(m + n)/(factorial(r)*factorial(m + n - r)) + assert T2 == binomial(m + n, r).rewrite(factorial) + # rewrite(binomial) is not working. + # https://github.com/sympy/sympy/issues/7135 + T3 = T2.rewrite(binomial) + assert T3 == binomial(m + n, r) + + +@XFAIL +def test_R11(): + n, k = symbols('n k', integer=True, positive=True) + sk = binomial(n, k)*fibonacci(k) + Sm = Sum(sk, (k, 0, n)) + T = Sm.doit() + # Fibonacci simplification not implemented + # https://github.com/sympy/sympy/issues/7134 + assert T == fibonacci(2*n) + + +@XFAIL +def test_R12(): + n, k = symbols('n k', integer=True, positive=True) + Sm = Sum(fibonacci(k)**2, (k, 0, n)) + T = Sm.doit() + assert T == fibonacci(n)*fibonacci(n + 1) + + +@XFAIL +def test_R13(): + n, k = symbols('n k', integer=True, positive=True) + Sm = Sum(sin(k*x), (k, 1, n)) + T = Sm.doit() # Sum is not calculated + assert T.simplify() == cot(x/2)/2 - cos(x*(2*n + 1)/2)/(2*sin(x/2)) + + +@XFAIL +def test_R14(): + n, k = symbols('n k', integer=True, positive=True) + Sm = Sum(sin((2*k - 1)*x), (k, 1, n)) + T = Sm.doit() # Sum is not calculated + assert T.simplify() == sin(n*x)**2/sin(x) + + +@XFAIL +def test_R15(): + n, k = symbols('n k', integer=True, positive=True) + Sm = Sum(binomial(n - k, k), (k, 0, floor(n/2))) + T = Sm.doit() # Sum is not calculated + assert T.simplify() == fibonacci(n + 1) + + +def test_R16(): + k = symbols('k', integer=True, positive=True) + Sm = Sum(1/k**2 + 1/k**3, (k, 1, oo)) + assert Sm.doit() == zeta(3) + pi**2/6 + + +def test_R17(): + k = symbols('k', integer=True, positive=True) + assert abs(float(Sum(1/k**2 + 1/k**3, (k, 1, oo))) + - 2.8469909700078206) < 1e-15 + + +def test_R18(): + k = symbols('k', integer=True, positive=True) + Sm = Sum(1/(2**k*k**2), (k, 1, oo)) + T = Sm.doit() + assert T.simplify() == -log(2)**2/2 + pi**2/12 + + +@slow +@XFAIL +def test_R19(): + k = symbols('k', integer=True, positive=True) + Sm = Sum(1/((3*k + 1)*(3*k + 2)*(3*k + 3)), (k, 0, oo)) + T = Sm.doit() + # assert fails, T not simplified + assert T.simplify() == -log(3)/4 + sqrt(3)*pi/12 + + +@XFAIL +def test_R20(): + n, k = symbols('n k', integer=True, positive=True) + Sm = Sum(binomial(n, 4*k), (k, 0, oo)) + T = Sm.doit() + # assert fails, T not simplified + assert T.simplify() == 2**(n/2)*cos(pi*n/4)/2 + 2**(n - 1)/2 + + +@XFAIL +def test_R21(): + k = symbols('k', integer=True, positive=True) + Sm = Sum(1/(sqrt(k*(k + 1)) * (sqrt(k) + sqrt(k + 1))), (k, 1, oo)) + T = Sm.doit() # Sum not calculated + assert T.simplify() == 1 + + +# test_R22 answer not available in Wester samples +# Sum(Sum(binomial(n, k)*binomial(n - k, n - 2*k)*x**n*y**(n - 2*k), +# (k, 0, floor(n/2))), (n, 0, oo)) with abs(x*y)<1? + + +@XFAIL +def test_R23(): + n, k = symbols('n k', integer=True, positive=True) + Sm = Sum(Sum((factorial(n)/(factorial(k)**2*factorial(n - 2*k)))* + (x/y)**k*(x*y)**(n - k), (n, 2*k, oo)), (k, 0, oo)) + # Missing how to express constraint abs(x*y)<1? + T = Sm.doit() # Sum not calculated + assert T == -1/sqrt(x**2*y**2 - 4*x**2 - 2*x*y + 1) + + +def test_R24(): + m, k = symbols('m k', integer=True, positive=True) + Sm = Sum(Product(k/(2*k - 1), (k, 1, m)), (m, 2, oo)) + assert Sm.doit() == pi/2 + + +def test_S1(): + k = symbols('k', integer=True, positive=True) + Pr = Product(gamma(k/3), (k, 1, 8)) + assert Pr.doit().simplify() == 640*sqrt(3)*pi**3/6561 + + +def test_S2(): + n, k = symbols('n k', integer=True, positive=True) + assert Product(k, (k, 1, n)).doit() == factorial(n) + + +def test_S3(): + n, k = symbols('n k', integer=True, positive=True) + assert Product(x**k, (k, 1, n)).doit().simplify() == x**(n*(n + 1)/2) + + +def test_S4(): + n, k = symbols('n k', integer=True, positive=True) + assert Product(1 + 1/k, (k, 1, n -1)).doit().simplify() == n + + +def test_S5(): + n, k = symbols('n k', integer=True, positive=True) + assert (Product((2*k - 1)/(2*k), (k, 1, n)).doit().gammasimp() == + gamma(n + S.Half)/(sqrt(pi)*gamma(n + 1))) + + +@XFAIL +def test_S6(): + n, k = symbols('n k', integer=True, positive=True) + # Product does not evaluate + assert (Product(x**2 -2*x*cos(k*pi/n) + 1, (k, 1, n - 1)).doit().simplify() + == (x**(2*n) - 1)/(x**2 - 1)) + + +@XFAIL +def test_S7(): + k = symbols('k', integer=True, positive=True) + Pr = Product((k**3 - 1)/(k**3 + 1), (k, 2, oo)) + T = Pr.doit() # Product does not evaluate + assert T.simplify() == R(2, 3) + + +@XFAIL +def test_S8(): + k = symbols('k', integer=True, positive=True) + Pr = Product(1 - 1/(2*k)**2, (k, 1, oo)) + T = Pr.doit() + # Product does not evaluate + assert T.simplify() == 2/pi + + +@XFAIL +def test_S9(): + k = symbols('k', integer=True, positive=True) + Pr = Product(1 + (-1)**(k + 1)/(2*k - 1), (k, 1, oo)) + T = Pr.doit() + # Product produces 0 + # https://github.com/sympy/sympy/issues/7133 + assert T.simplify() == sqrt(2) + + +@XFAIL +def test_S10(): + k = symbols('k', integer=True, positive=True) + Pr = Product((k*(k + 1) + 1 + I)/(k*(k + 1) + 1 - I), (k, 0, oo)) + T = Pr.doit() + # Product does not evaluate + assert T.simplify() == -1 + + +def test_T1(): + assert limit((1 + 1/n)**n, n, oo) == E + assert limit((1 - cos(x))/x**2, x, 0) == S.Half + + +def test_T2(): + assert limit((3**x + 5**x)**(1/x), x, oo) == 5 + + +def test_T3(): + assert limit(log(x)/(log(x) + sin(x)), x, oo) == 1 + + +def test_T4(): + assert limit((exp(x*exp(-x)/(exp(-x) + exp(-2*x**2/(x + 1)))) + - exp(x))/x, x, oo) == -exp(2) + + +def test_T5(): + assert limit(x*log(x)*log(x*exp(x) - x**2)**2/log(log(x**2 + + 2*exp(exp(3*x**3*log(x))))), x, oo) == R(1, 3) + + +def test_T6(): + assert limit(1/n * factorial(n)**(1/n), n, oo) == exp(-1) + + +def test_T7(): + limit(1/n * gamma(n + 1)**(1/n), n, oo) + + +def test_T8(): + a, z = symbols('a z', positive=True) + assert limit(gamma(z + a)/gamma(z)*exp(-a*log(z)), z, oo) == 1 + + +@XFAIL +def test_T9(): + z, k = symbols('z k', positive=True) + # raises NotImplementedError: + # Don't know how to calculate the mrv of '(1, k)' + assert limit(hyper((1, k), (1,), z/k), k, oo) == exp(z) + + +@XFAIL +def test_T10(): + # No longer raises PoleError, but should return euler-mascheroni constant + assert limit(zeta(x) - 1/(x - 1), x, 1) == integrate(-1/x + 1/floor(x), (x, 1, oo)) + +@XFAIL +def test_T11(): + n, k = symbols('n k', integer=True, positive=True) + # evaluates to 0 + assert limit(n**x/(x*product((1 + x/k), (k, 1, n))), n, oo) == gamma(x) + + +def test_T12(): + x, t = symbols('x t', real=True) + # Does not evaluate the limit but returns an expression with erf + assert limit(x * integrate(exp(-t**2), (t, 0, x))/(1 - exp(-x**2)), + x, 0) == 1 + + +def test_T13(): + x = symbols('x', real=True) + assert [limit(x/abs(x), x, 0, dir='-'), + limit(x/abs(x), x, 0, dir='+')] == [-1, 1] + + +def test_T14(): + x = symbols('x', real=True) + assert limit(atan(-log(x)), x, 0, dir='+') == pi/2 + + +def test_U1(): + x = symbols('x', real=True) + assert diff(abs(x), x) == sign(x) + + +def test_U2(): + f = Lambda(x, Piecewise((-x, x < 0), (x, x >= 0))) + assert diff(f(x), x) == Piecewise((-1, x < 0), (1, x >= 0)) + + +def test_U3(): + f = Lambda(x, Piecewise((x**2 - 1, x == 1), (x**3, x != 1))) + f1 = Lambda(x, diff(f(x), x)) + assert f1(x) == 3*x**2 + assert f1(1) == 3 + + +@XFAIL +def test_U4(): + n = symbols('n', integer=True, positive=True) + x = symbols('x', real=True) + d = diff(x**n, x, n) + assert d.rewrite(factorial) == factorial(n) + + +def test_U5(): + # issue 6681 + t = symbols('t') + ans = ( + Derivative(f(g(t)), g(t))*Derivative(g(t), (t, 2)) + + Derivative(f(g(t)), (g(t), 2))*Derivative(g(t), t)**2) + assert f(g(t)).diff(t, 2) == ans + assert ans.doit() == ans + + +def test_U6(): + h = Function('h') + T = integrate(f(y), (y, h(x), g(x))) + assert T.diff(x) == ( + f(g(x))*Derivative(g(x), x) - f(h(x))*Derivative(h(x), x)) + + +@XFAIL +def test_U7(): + p, t = symbols('p t', real=True) + # Exact differential => d(V(P, T)) => dV/dP DP + dV/dT DT + # raises ValueError: Since there is more than one variable in the + # expression, the variable(s) of differentiation must be supplied to + # differentiate f(p,t) + diff(f(p, t)) + + +def test_U8(): + x, y = symbols('x y', real=True) + eq = cos(x*y) + x + # If SymPy had implicit_diff() function this hack could be avoided + # TODO: Replace solve with solveset, current test fails for solveset + assert idiff(y - eq, y, x) == (-y*sin(x*y) + 1)/(x*sin(x*y) + 1) + + +def test_U9(): + # Wester sample case for Maple: + # O29 := diff(f(x, y), x) + diff(f(x, y), y); + # /d \ /d \ + # |-- f(x, y)| + |-- f(x, y)| + # \dx / \dy / + # + # O30 := factor(subs(f(x, y) = g(x^2 + y^2), %)); + # 2 2 + # 2 D(g)(x + y ) (x + y) + x, y = symbols('x y', real=True) + su = diff(f(x, y), x) + diff(f(x, y), y) + s2 = su.subs(f(x, y), g(x**2 + y**2)) + s3 = s2.doit().factor() + # Subs not performed, s3 = 2*(x + y)*Subs(Derivative( + # g(_xi_1), _xi_1), _xi_1, x**2 + y**2) + # Derivative(g(x*2 + y**2), x**2 + y**2) is not valid in SymPy, + # and probably will remain that way. You can take derivatives with respect + # to other expressions only if they are atomic, like a symbol or a + # function. + # D operator should be added to SymPy + # See https://github.com/sympy/sympy/issues/4719. + assert s3 == (x + y)*Subs(Derivative(g(x), x), x, x**2 + y**2)*2 + + +def test_U10(): + # see issue 2519: + assert residue((z**3 + 5)/((z**4 - 1)*(z + 1)), z, -1) == R(-9, 4) + +@XFAIL +def test_U11(): + # assert (2*dx + dz) ^ (3*dx + dy + dz) ^ (dx + dy + 4*dz) == 8*dx ^ dy ^dz + raise NotImplementedError + + +@XFAIL +def test_U12(): + # Wester sample case: + # (c41) /* d(3 x^5 dy /\ dz + 5 x y^2 dz /\ dx + 8 z dx /\ dy) + # => (15 x^4 + 10 x y + 8) dx /\ dy /\ dz */ + # factor(ext_diff(3*x^5 * dy ~ dz + 5*x*y^2 * dz ~ dx + 8*z * dx ~ dy)); + # 4 + # (d41) (10 x y + 15 x + 8) dx dy dz + raise NotImplementedError( + "External diff of differential form not supported") + + +def test_U13(): + assert minimum(x**4 - x + 1, x) == -3*2**R(1,3)/8 + 1 + + +@XFAIL +def test_U14(): + #f = 1/(x**2 + y**2 + 1) + #assert [minimize(f), maximize(f)] == [0,1] + raise NotImplementedError("minimize(), maximize() not supported") + + +@XFAIL +def test_U15(): + raise NotImplementedError("minimize() not supported and also solve does \ +not support multivariate inequalities") + + +@XFAIL +def test_U16(): + raise NotImplementedError("minimize() not supported in SymPy and also \ +solve does not support multivariate inequalities") + + +@XFAIL +def test_U17(): + raise NotImplementedError("Linear programming, symbolic simplex not \ +supported in SymPy") + + +def test_V1(): + x = symbols('x', real=True) + assert integrate(abs(x), x) == Piecewise((-x**2/2, x <= 0), (x**2/2, True)) + + +def test_V2(): + assert integrate(Piecewise((-x, x < 0), (x, x >= 0)), x + ) == Piecewise((-x**2/2, x < 0), (x**2/2, True)) + + +def test_V3(): + assert integrate(1/(x**3 + 2),x).diff().simplify() == 1/(x**3 + 2) + + +def test_V4(): + assert integrate(2**x/sqrt(1 + 4**x), x) == asinh(2**x)/log(2) + + +@XFAIL +def test_V5(): + # Returns (-45*x**2 + 80*x - 41)/(5*sqrt(2*x - 1)*(4*x**2 - 4*x + 1)) + assert (integrate((3*x - 5)**2/(2*x - 1)**R(7, 2), x).simplify() == + (-41 + 80*x - 45*x**2)/(5*(2*x - 1)**R(5, 2))) + + +@XFAIL +def test_V6(): + # returns RootSum(40*_z**2 - 1, Lambda(_i, _i*log(-4*_i + exp(-m*x))))/m + assert (integrate(1/(2*exp(m*x) - 5*exp(-m*x)), x) == sqrt(10)*( + log(2*exp(m*x) - sqrt(10)) - log(2*exp(m*x) + sqrt(10)))/(20*m)) + + +def test_V7(): + r1 = integrate(sinh(x)**4/cosh(x)**2) + assert r1.simplify() == x*R(-3, 2) + sinh(x)**3/(2*cosh(x)) + 3*tanh(x)/2 + + +@XFAIL +def test_V8_V9(): +#Macsyma test case: +#(c27) /* This example involves several symbolic parameters +# => 1/sqrt(b^2 - a^2) log([sqrt(b^2 - a^2) tan(x/2) + a + b]/ +# [sqrt(b^2 - a^2) tan(x/2) - a - b]) (a^2 < b^2) +# [Gradshteyn and Ryzhik 2.553(3)] */ +#assume(b^2 > a^2)$ +#(c28) integrate(1/(a + b*cos(x)), x); +#(c29) trigsimp(ratsimp(diff(%, x))); +# 1 +#(d29) ------------ +# b cos(x) + a + raise NotImplementedError( + "Integrate with assumption not supported") + + +def test_V10(): + assert integrate(1/(3 + 3*cos(x) + 4*sin(x)), x) == log(4*tan(x/2) + 3)/4 + + +def test_V11(): + r1 = integrate(1/(4 + 3*cos(x) + 4*sin(x)), x) + r2 = factor(r1) + assert (logcombine(r2, force=True) == + log(((tan(x/2) + 1)/(tan(x/2) + 7))**R(1, 3))) + + +def test_V12(): + r1 = integrate(1/(5 + 3*cos(x) + 4*sin(x)), x) + assert r1 == -1/(tan(x/2) + 2) + + +@XFAIL +def test_V13(): + r1 = integrate(1/(6 + 3*cos(x) + 4*sin(x)), x) + # expression not simplified, returns: -sqrt(11)*I*log(tan(x/2) + 4/3 + # - sqrt(11)*I/3)/11 + sqrt(11)*I*log(tan(x/2) + 4/3 + sqrt(11)*I/3)/11 + assert r1.simplify() == 2*sqrt(11)*atan(sqrt(11)*(3*tan(x/2) + 4)/11)/11 + + +@slow +@XFAIL +def test_V14(): + r1 = integrate(log(abs(x**2 - y**2)), x) + # Piecewise result does not simplify to the desired result. + assert (r1.simplify() == x*log(abs(x**2 - y**2)) + + y*log(x + y) - y*log(x - y) - 2*x) + + +def test_V15(): + r1 = integrate(x*acot(x/y), x) + assert simplify(r1 - (x*y + (x**2 + y**2)*acot(x/y))/2) == 0 + + +@XFAIL +def test_V16(): + # Integral not calculated + assert integrate(cos(5*x)*Ci(2*x), x) == Ci(2*x)*sin(5*x)/5 - (Si(3*x) + Si(7*x))/10 + +@XFAIL +def test_V17(): + r1 = integrate((diff(f(x), x)*g(x) + - f(x)*diff(g(x), x))/(f(x)**2 - g(x)**2), x) + # integral not calculated + assert simplify(r1 - (f(x) - g(x))/(f(x) + g(x))/2) == 0 + + +@XFAIL +def test_W1(): + # The function has a pole at y. + # The integral has a Cauchy principal value of zero but SymPy returns -I*pi + # https://github.com/sympy/sympy/issues/7159 + assert integrate(1/(x - y), (x, y - 1, y + 1)) == 0 + + +@XFAIL +def test_W2(): + # The function has a pole at y. + # The integral is divergent but SymPy returns -2 + # https://github.com/sympy/sympy/issues/7160 + # Test case in Macsyma: + # (c6) errcatch(integrate(1/(x - a)^2, x, a - 1, a + 1)); + # Integral is divergent + assert integrate(1/(x - y)**2, (x, y - 1, y + 1)) is zoo + + +@XFAIL +@slow +def test_W3(): + # integral is not calculated + # https://github.com/sympy/sympy/issues/7161 + assert integrate(sqrt(x + 1/x - 2), (x, 0, 1)) == R(4, 3) + + +@XFAIL +@slow +def test_W4(): + # integral is not calculated + assert integrate(sqrt(x + 1/x - 2), (x, 1, 2)) == -2*sqrt(2)/3 + R(4, 3) + + +@XFAIL +@slow +def test_W5(): + # integral is not calculated + assert integrate(sqrt(x + 1/x - 2), (x, 0, 2)) == -2*sqrt(2)/3 + R(8, 3) + + +@XFAIL +@slow +def test_W6(): + # integral is not calculated + assert integrate(sqrt(2 - 2*cos(2*x))/2, (x, pi*R(-3, 4), -pi/4)) == sqrt(2) + + +def test_W7(): + a = symbols('a', positive=True) + r1 = integrate(cos(x)/(x**2 + a**2), (x, -oo, oo)) + assert r1.simplify() == pi*exp(-a)/a + + +@XFAIL +def test_W8(): + # Test case in Mathematica: + # In[19]:= Integrate[t^(a - 1)/(1 + t), {t, 0, Infinity}, + # Assumptions -> 0 < a < 1] + # Out[19]= Pi Csc[a Pi] + raise NotImplementedError( + "Integrate with assumption 0 < a < 1 not supported") + + +@XFAIL +@slow +def test_W9(): + # Integrand with a residue at infinity => -2 pi [sin(pi/5) + sin(2pi/5)] + # (principal value) [Levinson and Redheffer, p. 234] *) + r1 = integrate(5*x**3/(1 + x + x**2 + x**3 + x**4), (x, -oo, oo)) + r2 = r1.doit() + assert r2 == -2*pi*(sqrt(-sqrt(5)/8 + 5/8) + sqrt(sqrt(5)/8 + 5/8)) + + +@XFAIL +def test_W10(): + # integrate(1/[1 + x + x^2 + ... + x^(2 n)], x = -infinity..infinity) = + # 2 pi/(2 n + 1) [1 + cos(pi/[2 n + 1])] csc(2 pi/[2 n + 1]) + # [Levinson and Redheffer, p. 255] => 2 pi/5 [1 + cos(pi/5)] csc(2 pi/5) */ + r1 = integrate(x/(1 + x + x**2 + x**4), (x, -oo, oo)) + r2 = r1.doit() + assert r2 == 2*pi*(sqrt(5)/4 + 5/4)*csc(pi*R(2, 5))/5 + + +@XFAIL +def test_W11(): + # integral not calculated + assert (integrate(sqrt(1 - x**2)/(1 + x**2), (x, -1, 1)) == + pi*(-1 + sqrt(2))) + + +def test_W12(): + p = symbols('p', positive=True) + q = symbols('q', real=True) + r1 = integrate(x*exp(-p*x**2 + 2*q*x), (x, -oo, oo)) + assert r1.simplify() == sqrt(pi)*q*exp(q**2/p)/p**R(3, 2) + + +@XFAIL +def test_W13(): + # Integral not calculated. Expected result is 2*(Euler_mascheroni_constant) + r1 = integrate(1/log(x) + 1/(1 - x) - log(log(1/x)), (x, 0, 1)) + assert r1 == 2*EulerGamma + + +def test_W14(): + assert integrate(sin(x)/x*exp(2*I*x), (x, -oo, oo)) == 0 + + +@XFAIL +def test_W15(): + # integral not calculated + assert integrate(log(gamma(x))*cos(6*pi*x), (x, 0, 1)) == R(1, 12) + + +def test_W16(): + assert integrate((1 + x)**3*legendre_poly(1, x)*legendre_poly(2, x), + (x, -1, 1)) == R(36, 35) + + +def test_W17(): + a, b = symbols('a b', positive=True) + assert integrate(exp(-a*x)*besselj(0, b*x), + (x, 0, oo)) == 1/(b*sqrt(a**2/b**2 + 1)) + + +def test_W18(): + assert integrate((besselj(1, x)/x)**2, (x, 0, oo)) == 4/(3*pi) + + +@XFAIL +def test_W19(): + # Integral not calculated + # Expected result is (cos 7 - 1)/7 [Gradshteyn and Ryzhik 6.782(3)] + assert integrate(Ci(x)*besselj(0, 2*sqrt(7*x)), (x, 0, oo)) == (cos(7) - 1)/7 + + +@XFAIL +def test_W20(): + # integral not calculated + assert (integrate(x**2*polylog(3, 1/(x + 1)), (x, 0, 1)) == + -pi**2/36 - R(17, 108) + zeta(3)/4 + + (-pi**2/2 - 4*log(2) + log(2)**2 + 35/3)*log(2)/9) + + +def test_W21(): + assert abs(N(integrate(x**2*polylog(3, 1/(x + 1)), (x, 0, 1))) + - 0.210882859565594) < 1e-15 + + +def test_W22(): + t, u = symbols('t u', real=True) + s = Lambda(x, Piecewise((1, And(x >= 1, x <= 2)), (0, True))) + assert integrate(s(t)*cos(t), (t, 0, u)) == Piecewise( + (0, u < 0), + (-sin(Min(1, u)) + sin(Min(2, u)), True)) + + +@slow +def test_W23(): + a, b = symbols('a b', positive=True) + r1 = integrate(integrate(x/(x**2 + y**2), (x, a, b)), (y, -oo, oo)) + assert r1.collect(pi).cancel() == -pi*a + pi*b + + +def test_W23b(): + # like W23 but limits are reversed + a, b = symbols('a b', positive=True) + r2 = integrate(integrate(x/(x**2 + y**2), (y, -oo, oo)), (x, a, b)) + assert r2.collect(pi) == pi*(-a + b) + + +@XFAIL +@tooslow +def test_W24(): + # Not that slow, but does not fully evaluate so simplify is slow. + # Maybe also require doit() + x, y = symbols('x y', real=True) + r1 = integrate(integrate(sqrt(x**2 + y**2), (x, 0, 1)), (y, 0, 1)) + assert (r1 - (sqrt(2) + asinh(1))/3).simplify() == 0 + + +@XFAIL +@tooslow +def test_W25(): + a, x, y = symbols('a x y', real=True) + i1 = integrate( + sin(a)*sin(y)/sqrt(1 - sin(a)**2*sin(x)**2*sin(y)**2), + (x, 0, pi/2)) + i2 = integrate(i1, (y, 0, pi/2)) + assert (i2 - pi*a/2).simplify() == 0 + + +def test_W26(): + x, y = symbols('x y', real=True) + assert integrate(integrate(abs(y - x**2), (y, 0, 2)), + (x, -1, 1)) == R(46, 15) + + +def test_W27(): + a, b, c = symbols('a b c') + assert integrate(integrate(integrate(1, (z, 0, c*(1 - x/a - y/b))), + (y, 0, b*(1 - x/a))), + (x, 0, a)) == a*b*c/6 + + +def test_X1(): + v, c = symbols('v c', real=True) + assert (series(1/sqrt(1 - (v/c)**2), v, x0=0, n=8) == + 5*v**6/(16*c**6) + 3*v**4/(8*c**4) + v**2/(2*c**2) + 1 + O(v**8)) + + +def test_X2(): + v, c = symbols('v c', real=True) + s1 = series(1/sqrt(1 - (v/c)**2), v, x0=0, n=8) + assert (1/s1**2).series(v, x0=0, n=8) == -v**2/c**2 + 1 + O(v**8) + + +def test_X3(): + s1 = (sin(x).series()/cos(x).series()).series() + s2 = tan(x).series() + assert s2 == x + x**3/3 + 2*x**5/15 + O(x**6) + assert s1 == s2 + + +def test_X4(): + s1 = log(sin(x)/x).series() + assert s1 == -x**2/6 - x**4/180 + O(x**6) + assert log(series(sin(x)/x)).series() == s1 + + +@XFAIL +def test_X5(): + # test case in Mathematica syntax: + # In[21]:= (* => [a f'(a d) + g(b d) + integrate(h(c y), y = 0..d)] + # + [a^2 f''(a d) + b g'(b d) + h(c d)] (x - d) *) + # In[22]:= D[f[a*x], x] + g[b*x] + Integrate[h[c*y], {y, 0, x}] + # Out[22]= g[b x] + Integrate[h[c y], {y, 0, x}] + a f'[a x] + # In[23]:= Series[%, {x, d, 1}] + # Out[23]= (g[b d] + Integrate[h[c y], {y, 0, d}] + a f'[a d]) + + # 2 2 + # (h[c d] + b g'[b d] + a f''[a d]) (-d + x) + O[-d + x] + h = Function('h') + a, b, c, d = symbols('a b c d', real=True) + # series() raises NotImplementedError: + # The _eval_nseries method should be added to to give terms up to O(x**n) at x=0 + series(diff(f(a*x), x) + g(b*x) + integrate(h(c*y), (y, 0, x)), + x, x0=d, n=2) + # assert missing, until exception is removed + + +def test_X6(): + # Taylor series of nonscalar objects (noncommutative multiplication) + # expected result => (B A - A B) t^2/2 + O(t^3) [Stanly Steinberg] + a, b = symbols('a b', commutative=False, scalar=False) + assert (series(exp((a + b)*x) - exp(a*x) * exp(b*x), x, x0=0, n=3) == + x**2*(-a*b/2 + b*a/2) + O(x**3)) + + +def test_X7(): + # => sum( Bernoulli[k]/k! x^(k - 2), k = 1..infinity ) + # = 1/x^2 - 1/(2 x) + 1/12 - x^2/720 + x^4/30240 + O(x^6) + # [Levinson and Redheffer, p. 173] + assert (series(1/(x*(exp(x) - 1)), x, 0, 7) == x**(-2) - 1/(2*x) + + R(1, 12) - x**2/720 + x**4/30240 - x**6/1209600 + O(x**7)) + + +def test_X8(): + # Puiseux series (terms with fractional degree): + # => 1/sqrt(x - 3/2 pi) + (x - 3/2 pi)^(3/2) / 12 + O([x - 3/2 pi]^(7/2)) + + # see issue 7167: + x = symbols('x', real=True) + assert (series(sqrt(sec(x)), x, x0=pi*3/2, n=4) == + 1/sqrt(x - pi*R(3, 2)) + (x - pi*R(3, 2))**R(3, 2)/12 + + (x - pi*R(3, 2))**R(7, 2)/160 + O((x - pi*R(3, 2))**4, (x, pi*R(3, 2)))) + + +def test_X9(): + assert (series(x**x, x, x0=0, n=4) == 1 + x*log(x) + x**2*log(x)**2/2 + + x**3*log(x)**3/6 + O(x**4*log(x)**4)) + + +def test_X10(): + z, w = symbols('z w') + assert (series(log(sinh(z)) + log(cosh(z + w)), z, x0=0, n=2) == + log(cosh(w)) + log(z) + z*sinh(w)/cosh(w) + O(z**2)) + + +def test_X11(): + z, w = symbols('z w') + assert (series(log(sinh(z) * cosh(z + w)), z, x0=0, n=2) == + log(cosh(w)) + log(z) + z*sinh(w)/cosh(w) + O(z**2)) + + +@XFAIL +def test_X12(): + # Look at the generalized Taylor series around x = 1 + # Result => (x - 1)^a/e^b [1 - (a + 2 b) (x - 1) / 2 + O((x - 1)^2)] + a, b, x = symbols('a b x', real=True) + # series returns O(log(x-1)**2) + # https://github.com/sympy/sympy/issues/7168 + assert (series(log(x)**a*exp(-b*x), x, x0=1, n=2) == + (x - 1)**a/exp(b)*(1 - (a + 2*b)*(x - 1)/2 + O((x - 1)**2))) + + +def test_X13(): + assert series(sqrt(2*x**2 + 1), x, x0=oo, n=1) == sqrt(2)*x + O(1/x, (x, oo)) + + +@XFAIL +def test_X14(): + # Wallis' product => 1/sqrt(pi n) + ... [Knopp, p. 385] + assert series(1/2**(2*n)*binomial(2*n, n), + n, x==oo, n=1) == 1/(sqrt(pi)*sqrt(n)) + O(1/x, (x, oo)) + + +@SKIP("https://github.com/sympy/sympy/issues/7164") +def test_X15(): + # => 0!/x - 1!/x^2 + 2!/x^3 - 3!/x^4 + O(1/x^5) [Knopp, p. 544] + x, t = symbols('x t', real=True) + # raises RuntimeError: maximum recursion depth exceeded + # https://github.com/sympy/sympy/issues/7164 + # 2019-02-17: Raises + # PoleError: + # Asymptotic expansion of Ei around [-oo] is not implemented. + e1 = integrate(exp(-t)/t, (t, x, oo)) + assert (series(e1, x, x0=oo, n=5) == + 6/x**4 + 2/x**3 - 1/x**2 + 1/x + O(x**(-5), (x, oo))) + + +def test_X16(): + # Multivariate Taylor series expansion => 1 - (x^2 + 2 x y + y^2)/2 + O(x^4) + assert (series(cos(x + y), x + y, x0=0, n=4) == 1 - (x + y)**2/2 + + O(x**4 + x**3*y + x**2*y**2 + x*y**3 + y**4, x, y)) + + +@XFAIL +def test_X17(): + # Power series (compute the general formula) + # (c41) powerseries(log(sin(x)/x), x, 0); + # /aquarius/data2/opt/local/macsyma_422/library1/trgred.so being loaded. + # inf + # ==== i1 2 i1 2 i1 + # \ (- 1) 2 bern(2 i1) x + # (d41) > ------------------------------ + # / 2 i1 (2 i1)! + # ==== + # i1 = 1 + # fps does not calculate + assert fps(log(sin(x)/x)) == \ + Sum((-1)**k*2**(2*k - 1)*bernoulli(2*k)*x**(2*k)/(k*factorial(2*k)), (k, 1, oo)) + + +@XFAIL +def test_X18(): + # Power series (compute the general formula). Maple FPS: + # > FormalPowerSeries(exp(-x)*sin(x), x = 0); + # infinity + # ----- (1/2 k) k + # \ 2 sin(3/4 k Pi) x + # ) ------------------------- + # / k! + # ----- + # + # Now, SymPy returns + # oo + # _____ + # \ ` + # \ / k k\ + # \ k |I*(-1 - I) I*(-1 + I) | + # \ x *|----------- - -----------| + # / \ 2 2 / + # / ------------------------------ + # / k! + # /____, + # k = 0 + k = Dummy('k') + assert fps(exp(-x)*sin(x)) == \ + Sum(2**(S.Half*k)*sin(R(3, 4)*k*pi)*x**k/factorial(k), (k, 0, oo)) + + +@XFAIL +def test_X19(): + # (c45) /* Derive an explicit Taylor series solution of y as a function of + # x from the following implicit relation: + # y = x - 1 + (x - 1)^2/2 + 2/3 (x - 1)^3 + (x - 1)^4 + + # 17/10 (x - 1)^5 + ... + # */ + # x = sin(y) + cos(y); + # Time= 0 msecs + # (d45) x = sin(y) + cos(y) + # + # (c46) taylor_revert(%, y, 7); + raise NotImplementedError("Solve using series not supported. \ +Inverse Taylor series expansion also not supported") + + +@XFAIL +def test_X20(): + # Pade (rational function) approximation => (2 - x)/(2 + x) + # > numapprox[pade](exp(-x), x = 0, [1, 1]); + # bytes used=9019816, alloc=3669344, time=13.12 + # 1 - 1/2 x + # --------- + # 1 + 1/2 x + # mpmath support numeric Pade approximant but there is + # no symbolic implementation in SymPy + # https://en.wikipedia.org/wiki/Pad%C3%A9_approximant + raise NotImplementedError("Symbolic Pade approximant not supported") + + +def test_X21(): + """ + Test whether `fourier_series` of x periodical on the [-p, p] interval equals + `- (2 p / pi) sum( (-1)^n / n sin(n pi x / p), n = 1..infinity )`. + """ + p = symbols('p', positive=True) + n = symbols('n', positive=True, integer=True) + s = fourier_series(x, (x, -p, p)) + + # All cosine coefficients are equal to 0 + assert s.an.formula == 0 + + # Check for sine coefficients + assert s.bn.formula.subs(s.bn.variables[0], 0) == 0 + assert s.bn.formula.subs(s.bn.variables[0], n) == \ + -2*p/pi * (-1)**n / n * sin(n*pi*x/p) + + +@XFAIL +def test_X22(): + # (c52) /* => p / 2 + # - (2 p / pi^2) sum( [1 - (-1)^n] cos(n pi x / p) / n^2, + # n = 1..infinity ) */ + # fourier_series(abs(x), x, p); + # p + # (e52) a = - + # 0 2 + # + # %nn + # (2 (- 1) - 2) p + # (e53) a = ------------------ + # %nn 2 2 + # %pi %nn + # + # (e54) b = 0 + # %nn + # + # Time= 5290 msecs + # inf %nn %pi %nn x + # ==== (2 (- 1) - 2) cos(---------) + # \ p + # p > ------------------------------- + # / 2 + # ==== %nn + # %nn = 1 p + # (d54) ----------------------------------------- + - + # 2 2 + # %pi + raise NotImplementedError("Fourier series not supported") + + +def test_Y1(): + t = symbols('t', positive=True) + w = symbols('w', real=True) + s = symbols('s') + F, _, _ = laplace_transform(cos((w - 1)*t), t, s) + assert F == s/(s**2 + (w - 1)**2) + + +def test_Y2(): + t = symbols('t', positive=True) + w = symbols('w', real=True) + s = symbols('s') + f = inverse_laplace_transform(s/(s**2 + (w - 1)**2), s, t, simplify=True) + assert f == cos(t*(w - 1)) + + +def test_Y3(): + t = symbols('t', positive=True) + w = symbols('w', real=True) + s = symbols('s') + F, _, _ = laplace_transform(sinh(w*t)*cosh(w*t), t, s, simplify=True) + assert F == w/(s**2 - 4*w**2) + + +def test_Y4(): + t = symbols('t', positive=True) + s = symbols('s') + F, _, _ = laplace_transform(erf(3/sqrt(t)), t, s, simplify=True) + assert F == 1/s - exp(-6*sqrt(s))/s + + +def test_Y5_Y6(): +# Solve y'' + y = 4 [H(t - 1) - H(t - 2)], y(0) = 1, y'(0) = 0 where H is the +# Heaviside (unit step) function (the RHS describes a pulse of magnitude 4 and +# duration 1). See David A. Sanchez, Richard C. Allen, Jr. and Walter T. +# Kyner, _Differential Equations: An Introduction_, Addison-Wesley Publishing +# Company, 1983, p. 211. First, take the Laplace transform of the ODE +# => s^2 Y(s) - s + Y(s) = 4/s [e^(-s) - e^(-2 s)] +# where Y(s) is the Laplace transform of y(t) + t = symbols('t', real=True) + s = symbols('s') + y = Function('y') + Y = Function('Y') + F = laplace_correspondence(laplace_transform(diff(y(t), t, 2) + y(t) + - 4*(Heaviside(t - 1) - Heaviside(t - 2)), + t, s, noconds=True), {y: Y}) + D = ( + -F + s**2*Y(s) - s*y(0) + Y(s) - Subs(Derivative(y(t), t), t, 0) - + 4*exp(-s)/s + 4*exp(-2*s)/s) + assert D == 0 +# Now, solve for Y(s) and then take the inverse Laplace transform +# => Y(s) = s/(s^2 + 1) + 4 [1/s - s/(s^2 + 1)] [e^(-s) - e^(-2 s)] +# => y(t) = cos t + 4 {[1 - cos(t - 1)] H(t - 1) - [1 - cos(t - 2)] H(t - 2)} + Yf = solve(F, Y(s))[0] + Yf = laplace_initial_conds(Yf, t, {y: [1, 0]}) + assert Yf == (s**2*exp(2*s) + 4*exp(s) - 4)*exp(-2*s)/(s*(s**2 + 1)) + yf = inverse_laplace_transform(Yf, s, t) + yf = yf.collect(Heaviside(t-1)).collect(Heaviside(t-2)) + assert yf == ( + (4 - 4*cos(t - 1))*Heaviside(t - 1) + + (4*cos(t - 2) - 4)*Heaviside(t - 2) + + cos(t)*Heaviside(t)) + + +@XFAIL +def test_Y7(): + # What is the Laplace transform of an infinite square wave? + # => 1/s + 2 sum( (-1)^n e^(- s n a)/s, n = 1..infinity ) + # [Sanchez, Allen and Kyner, p. 213] + t = symbols('t', positive=True) + a = symbols('a', real=True) + s = symbols('s') + F, _, _ = laplace_transform(1 + 2*Sum((-1)**n*Heaviside(t - n*a), + (n, 1, oo)), t, s) + # returns 2*LaplaceTransform(Sum((-1)**n*Heaviside(-a*n + t), + # (n, 1, oo)), t, s) + 1/s + # https://github.com/sympy/sympy/issues/7177 + assert F == 2*Sum((-1)**n*exp(-a*n*s)/s, (n, 1, oo)) + 1/s + + +@XFAIL +def test_Y8(): + assert fourier_transform(1, x, z) == DiracDelta(z) + + +def test_Y9(): + assert (fourier_transform(exp(-9*x**2), x, z) == + sqrt(pi)*exp(-pi**2*z**2/9)/3) + + +def test_Y10(): + assert (fourier_transform(abs(x)*exp(-3*abs(x)), x, z).cancel() == + (-8*pi**2*z**2 + 18)/(16*pi**4*z**4 + 72*pi**2*z**2 + 81)) + + +@SKIP("https://github.com/sympy/sympy/issues/7181") +@slow +def test_Y11(): + # => pi cot(pi s) (0 < Re s < 1) [Gradshteyn and Ryzhik 17.43(5)] + x, s = symbols('x s') + # raises RuntimeError: maximum recursion depth exceeded + # https://github.com/sympy/sympy/issues/7181 + # Update 2019-02-17 raises: + # TypeError: cannot unpack non-iterable MellinTransform object + F, _, _ = mellin_transform(1/(1 - x), x, s) + assert F == pi*cot(pi*s) + + +@XFAIL +def test_Y12(): + # => 2^(s - 4) gamma(s/2)/gamma(4 - s/2) (0 < Re s < 1) + # [Gradshteyn and Ryzhik 17.43(16)] + x, s = symbols('x s') + # returns Wrong value -2**(s - 4)*gamma(s/2 - 3)/gamma(-s/2 + 1) + # https://github.com/sympy/sympy/issues/7182 + F, _, _ = mellin_transform(besselj(3, x)/x**3, x, s) + assert F == -2**(s - 4)*gamma(s/2)/gamma(-s/2 + 4) + + +@XFAIL +def test_Y13(): +# Z[H(t - m T)] => z/[z^m (z - 1)] (H is the Heaviside (unit step) function) z + raise NotImplementedError("z-transform not supported") + + +@XFAIL +def test_Y14(): +# Z[H(t - m T)] => z/[z^m (z - 1)] (H is the Heaviside (unit step) function) + raise NotImplementedError("z-transform not supported") + + +def test_Z1(): + r = Function('r') + assert (rsolve(r(n + 2) - 2*r(n + 1) + r(n) - 2, r(n), + {r(0): 1, r(1): m}).simplify() == n**2 + n*(m - 2) + 1) + + +def test_Z2(): + r = Function('r') + assert (rsolve(r(n) - (5*r(n - 1) - 6*r(n - 2)), r(n), {r(0): 0, r(1): 1}) + == -2**n + 3**n) + + +def test_Z3(): + # => r(n) = Fibonacci[n + 1] [Cohen, p. 83] + r = Function('r') + # recurrence solution is correct, Wester expects it to be simplified to + # fibonacci(n+1), but that is quite hard + expected = ((S(1)/2 - sqrt(5)/2)**n*(S(1)/2 - sqrt(5)/10) + + (S(1)/2 + sqrt(5)/2)**n*(sqrt(5)/10 + S(1)/2)) + sol = rsolve(r(n) - (r(n - 1) + r(n - 2)), r(n), {r(1): 1, r(2): 2}) + assert sol == expected + + +@XFAIL +def test_Z4(): +# => [c^(n+1) [c^(n+1) - 2 c - 2] + (n+1) c^2 + 2 c - n] / [(c-1)^3 (c+1)] +# [Joan Z. Yu and Robert Israel in sci.math.symbolic] + r = Function('r') + c = symbols('c') + # raises ValueError: Polynomial or rational function expected, + # got '(c**2 - c**n)/(c - c**n) + s = rsolve(r(n) - ((1 + c - c**(n-1) - c**(n+1))/(1 - c**n)*r(n - 1) + - c*(1 - c**(n-2))/(1 - c**(n-1))*r(n - 2) + 1), + r(n), {r(1): 1, r(2): (2 + 2*c + c**2)/(1 + c)}) + assert (s - (c*(n + 1)*(c*(n + 1) - 2*c - 2) + + (n + 1)*c**2 + 2*c - n)/((c-1)**3*(c+1)) == 0) + + +@XFAIL +def test_Z5(): + # Second order ODE with initial conditions---solve directly + # transform: f(t) = sin(2 t)/8 - t cos(2 t)/4 + C1, C2 = symbols('C1 C2') + # initial conditions not supported, this is a manual workaround + # https://github.com/sympy/sympy/issues/4720 + eq = Derivative(f(x), x, 2) + 4*f(x) - sin(2*x) + sol = dsolve(eq, f(x)) + f0 = Lambda(x, sol.rhs) + assert f0(x) == C2*sin(2*x) + (C1 - x/4)*cos(2*x) + f1 = Lambda(x, diff(f0(x), x)) + # TODO: Replace solve with solveset, when it works for solveset + const_dict = solve((f0(0), f1(0))) + result = f0(x).subs(C1, const_dict[C1]).subs(C2, const_dict[C2]) + assert result == -x*cos(2*x)/4 + sin(2*x)/8 + # Result is OK, but ODE solving with initial conditions should be + # supported without all this manual work + raise NotImplementedError('ODE solving with initial conditions \ +not supported') + + +@XFAIL +def test_Z6(): + # Second order ODE with initial conditions---solve using Laplace + # transform: f(t) = sin(2 t)/8 - t cos(2 t)/4 + t = symbols('t', positive=True) + s = symbols('s') + eq = Derivative(f(t), t, 2) + 4*f(t) - sin(2*t) + F, _, _ = laplace_transform(eq, t, s) + # Laplace transform for diff() not calculated + # https://github.com/sympy/sympy/issues/7176 + assert (F == s**2*LaplaceTransform(f(t), t, s) + + 4*LaplaceTransform(f(t), t, s) - 2/(s**2 + 4)) + # rest of test case not implemented diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_xxe.py b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_xxe.py new file mode 100644 index 0000000000000000000000000000000000000000..3936e8aa135dde5f22c71548e2f90ed58ac25cb8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/tests/test_xxe.py @@ -0,0 +1,3 @@ +# A test file for XXE injection +# Username: Test +# Password: Test diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/timeutils.py b/.venv/lib/python3.12/site-packages/sympy/utilities/timeutils.py new file mode 100644 index 0000000000000000000000000000000000000000..1caae825103335f3e8afedeaf741cff2b0414fb2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/timeutils.py @@ -0,0 +1,75 @@ +"""Simple tools for timing functions' execution, when IPython is not available. """ + + +import timeit +import math + + +_scales = [1e0, 1e3, 1e6, 1e9] +_units = ['s', 'ms', '\N{GREEK SMALL LETTER MU}s', 'ns'] + + +def timed(func, setup="pass", limit=None): + """Adaptively measure execution time of a function. """ + timer = timeit.Timer(func, setup=setup) + repeat, number = 3, 1 + + for i in range(1, 10): + if timer.timeit(number) >= 0.2: + break + elif limit is not None and number >= limit: + break + else: + number *= 10 + + time = min(timer.repeat(repeat, number)) / number + + if time > 0.0: + order = min(-int(math.floor(math.log10(time)) // 3), 3) + else: + order = 3 + + return (number, time, time*_scales[order], _units[order]) + + +# Code for doing inline timings of recursive algorithms. + +def __do_timings(): + import os + res = os.getenv('SYMPY_TIMINGS', '') + res = [x.strip() for x in res.split(',')] + return set(res) + +_do_timings = __do_timings() +_timestack = None + + +def _print_timestack(stack, level=1): + print('-'*level, '%.2f %s%s' % (stack[2], stack[0], stack[3])) + for s in stack[1]: + _print_timestack(s, level + 1) + + +def timethis(name): + def decorator(func): + if name not in _do_timings: + return func + + def wrapper(*args, **kwargs): + from time import time + global _timestack + oldtimestack = _timestack + _timestack = [func.func_name, [], 0, args] + t1 = time() + r = func(*args, **kwargs) + t2 = time() + _timestack[2] = t2 - t1 + if oldtimestack is not None: + oldtimestack[1].append(_timestack) + _timestack = oldtimestack + else: + _print_timestack(_timestack) + _timestack = None + return r + return wrapper + return decorator diff --git a/.venv/lib/python3.12/site-packages/sympy/utilities/tmpfiles.py b/.venv/lib/python3.12/site-packages/sympy/utilities/tmpfiles.py new file mode 100644 index 0000000000000000000000000000000000000000..81c97efbf9d67cc20f25ff251abc94c2f5bafe06 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/utilities/tmpfiles.py @@ -0,0 +1,12 @@ +""" +.. deprecated:: 1.6 + + sympy.utilities.tmpfiles has been renamed to sympy.testing.tmpfiles. +""" +from sympy.utilities.exceptions import sympy_deprecation_warning + +sympy_deprecation_warning("The sympy.utilities.tmpfiles submodule is deprecated. Use sympy.testing.tmpfiles instead.", + deprecated_since_version="1.6", + active_deprecations_target="deprecated-sympy-utilities-submodules") + +from sympy.testing.tmpfiles import * # noqa:F401,F403 diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/__init__.py b/.venv/lib/python3.12/site-packages/sympy/vector/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f6757bbeb35022481b1cf183373ecccd19779faa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/__init__.py @@ -0,0 +1,50 @@ +from sympy.vector.coordsysrect import CoordSys3D +from sympy.vector.vector import (Vector, VectorAdd, VectorMul, + BaseVector, VectorZero, Cross, Dot, cross, dot) +from sympy.vector.dyadic import (Dyadic, DyadicAdd, DyadicMul, + BaseDyadic, DyadicZero) +from sympy.vector.scalar import BaseScalar +from sympy.vector.deloperator import Del +from sympy.vector.functions import (express, matrix_to_vector, + laplacian, is_conservative, + is_solenoidal, scalar_potential, + directional_derivative, + scalar_potential_difference) +from sympy.vector.point import Point +from sympy.vector.orienters import (AxisOrienter, BodyOrienter, + SpaceOrienter, QuaternionOrienter) +from sympy.vector.operators import Gradient, Divergence, Curl, Laplacian, gradient, curl, divergence +from sympy.vector.implicitregion import ImplicitRegion +from sympy.vector.parametricregion import (ParametricRegion, parametric_region_list) +from sympy.vector.integrals import (ParametricIntegral, vector_integrate) +from sympy.vector.kind import VectorKind + +__all__ = [ + 'Vector', 'VectorAdd', 'VectorMul', 'BaseVector', 'VectorZero', 'Cross', + 'Dot', 'cross', 'dot', + + 'VectorKind', + + 'Dyadic', 'DyadicAdd', 'DyadicMul', 'BaseDyadic', 'DyadicZero', + + 'BaseScalar', + + 'Del', + + 'CoordSys3D', + + 'express', 'matrix_to_vector', 'laplacian', 'is_conservative', + 'is_solenoidal', 'scalar_potential', 'directional_derivative', + 'scalar_potential_difference', + + 'Point', + + 'AxisOrienter', 'BodyOrienter', 'SpaceOrienter', 'QuaternionOrienter', + + 'Gradient', 'Divergence', 'Curl', 'Laplacian', 'gradient', 'curl', + 'divergence', + + 'ParametricRegion', 'parametric_region_list', 'ImplicitRegion', + + 'ParametricIntegral', 'vector_integrate', +] diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac0e92fc2c9c6cc3e8fdc914a995c7ae94f17cd4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/basisdependent.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/basisdependent.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2015f26682f66dd125b105801917656cc392fee2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/basisdependent.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/coordsysrect.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/coordsysrect.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6eac0593e96d7a951886e8690fed09a8ad9312af Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/coordsysrect.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/deloperator.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/deloperator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff6ca31962bb70dd464bb83ab292693fe9631b53 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/deloperator.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/dyadic.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/dyadic.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a6da6652e4e2475dafa7083ad9842ea2029e3a1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/dyadic.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/functions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/functions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c8b76a2d878cab110f40787f746f197e8c7602a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/functions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/implicitregion.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/implicitregion.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..857b15cbe503fbfbb96fa0e86a0c79eed2d411cd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/implicitregion.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/integrals.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/integrals.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b43b98404ba657b7334e0600d3347d12350af81 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/integrals.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/kind.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/kind.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99d835d9b5d84fb8701f25683886cb560416a5ac Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/kind.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/operators.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/operators.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c1b7842dd2887ed366a1b0540627692a9f1126e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/operators.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/orienters.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/orienters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73dd04569382167ca8b2ccce655737b6e2f7ef30 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/orienters.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/parametricregion.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/parametricregion.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6171b3d2684c69901d0a7c338e97a057114183cf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/parametricregion.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/point.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/point.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a38c0d1e5075ea957abd5fc0e3816eabfb2ceba7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/point.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/scalar.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/scalar.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b827a2f10e3400b1fc914287cded5eee4167f23 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/scalar.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/vector.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/vector.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49aa31383823212eaebc91d32f4ba9a07d2e0b88 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/__pycache__/vector.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/basisdependent.py b/.venv/lib/python3.12/site-packages/sympy/vector/basisdependent.py new file mode 100644 index 0000000000000000000000000000000000000000..53e4efc0bf839fb5a5de2d1af1487683fabd8cf1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/basisdependent.py @@ -0,0 +1,374 @@ +from __future__ import annotations +from typing import TYPE_CHECKING + +from sympy.simplify import simplify as simp, trigsimp as tsimp # type: ignore +from sympy.core.decorators import call_highest_priority, _sympifyit +from sympy.core.assumptions import StdFactKB +from sympy.core.function import diff as df +from sympy.integrals.integrals import Integral +from sympy.polys.polytools import factor as fctr +from sympy.core import S, Add, Mul +from sympy.core.expr import Expr + +if TYPE_CHECKING: + from sympy.vector.vector import BaseVector + + +class BasisDependent(Expr): + """ + Super class containing functionality common to vectors and + dyadics. + Named so because the representation of these quantities in + sympy.vector is dependent on the basis they are expressed in. + """ + + zero: BasisDependentZero + + @call_highest_priority('__radd__') + def __add__(self, other): + return self._add_func(self, other) + + @call_highest_priority('__add__') + def __radd__(self, other): + return self._add_func(other, self) + + @call_highest_priority('__rsub__') + def __sub__(self, other): + return self._add_func(self, -other) + + @call_highest_priority('__sub__') + def __rsub__(self, other): + return self._add_func(other, -self) + + @_sympifyit('other', NotImplemented) + @call_highest_priority('__rmul__') + def __mul__(self, other): + return self._mul_func(self, other) + + @_sympifyit('other', NotImplemented) + @call_highest_priority('__mul__') + def __rmul__(self, other): + return self._mul_func(other, self) + + def __neg__(self): + return self._mul_func(S.NegativeOne, self) + + @_sympifyit('other', NotImplemented) + @call_highest_priority('__rtruediv__') + def __truediv__(self, other): + return self._div_helper(other) + + @call_highest_priority('__truediv__') + def __rtruediv__(self, other): + return TypeError("Invalid divisor for division") + + def evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False): + """ + Implements the SymPy evalf routine for this quantity. + + evalf's documentation + ===================== + + """ + options = {'subs':subs, 'maxn':maxn, 'chop':chop, 'strict':strict, + 'quad':quad, 'verbose':verbose} + vec = self.zero + for k, v in self.components.items(): + vec += v.evalf(n, **options) * k + return vec + + evalf.__doc__ += Expr.evalf.__doc__ # type: ignore + + n = evalf # type: ignore + + def simplify(self, **kwargs): + """ + Implements the SymPy simplify routine for this quantity. + + simplify's documentation + ======================== + + """ + simp_components = [simp(v, **kwargs) * k for + k, v in self.components.items()] + return self._add_func(*simp_components) + + simplify.__doc__ += simp.__doc__ # type: ignore + + def trigsimp(self, **opts): + """ + Implements the SymPy trigsimp routine, for this quantity. + + trigsimp's documentation + ======================== + + """ + trig_components = [tsimp(v, **opts) * k for + k, v in self.components.items()] + return self._add_func(*trig_components) + + trigsimp.__doc__ += tsimp.__doc__ # type: ignore + + def _eval_simplify(self, **kwargs): + return self.simplify(**kwargs) + + def _eval_trigsimp(self, **opts): + return self.trigsimp(**opts) + + def _eval_derivative(self, wrt): + return self.diff(wrt) + + def _eval_Integral(self, *symbols, **assumptions): + integral_components = [Integral(v, *symbols, **assumptions) * k + for k, v in self.components.items()] + return self._add_func(*integral_components) + + def as_numer_denom(self): + """ + Returns the expression as a tuple wrt the following + transformation - + + expression -> a/b -> a, b + + """ + return self, S.One + + def factor(self, *args, **kwargs): + """ + Implements the SymPy factor routine, on the scalar parts + of a basis-dependent expression. + + factor's documentation + ======================== + + """ + fctr_components = [fctr(v, *args, **kwargs) * k for + k, v in self.components.items()] + return self._add_func(*fctr_components) + + factor.__doc__ += fctr.__doc__ # type: ignore + + def as_coeff_Mul(self, rational=False): + """Efficiently extract the coefficient of a product.""" + return (S.One, self) + + def as_coeff_add(self, *deps): + """Efficiently extract the coefficient of a summation.""" + return 0, tuple(x * self.components[x] for x in self.components) + + def diff(self, *args, **kwargs): + """ + Implements the SymPy diff routine, for vectors. + + diff's documentation + ======================== + + """ + for x in args: + if isinstance(x, BasisDependent): + raise TypeError("Invalid arg for differentiation") + diff_components = [df(v, *args, **kwargs) * k for + k, v in self.components.items()] + return self._add_func(*diff_components) + + diff.__doc__ += df.__doc__ # type: ignore + + def doit(self, **hints): + """Calls .doit() on each term in the Dyadic""" + doit_components = [self.components[x].doit(**hints) * x + for x in self.components] + return self._add_func(*doit_components) + + +class BasisDependentAdd(BasisDependent, Add): + """ + Denotes sum of basis dependent quantities such that they cannot + be expressed as base or Mul instances. + """ + + def __new__(cls, *args, **options): + components = {} + + # Check each arg and simultaneously learn the components + for arg in args: + if not isinstance(arg, cls._expr_type): + if isinstance(arg, Mul): + arg = cls._mul_func(*(arg.args)) + elif isinstance(arg, Add): + arg = cls._add_func(*(arg.args)) + else: + raise TypeError(str(arg) + + " cannot be interpreted correctly") + # If argument is zero, ignore + if arg == cls.zero: + continue + # Else, update components accordingly + for x in arg.components: + components[x] = components.get(x, 0) + arg.components[x] + + temp = list(components.keys()) + for x in temp: + if components[x] == 0: + del components[x] + + # Handle case of zero vector + if len(components) == 0: + return cls.zero + + # Build object + newargs = [x * components[x] for x in components] + obj = super().__new__(cls, *newargs, **options) + if isinstance(obj, Mul): + return cls._mul_func(*obj.args) + assumptions = {'commutative': True} + obj._assumptions = StdFactKB(assumptions) + obj._components = components + obj._sys = (list(components.keys()))[0]._sys + + return obj + + +class BasisDependentMul(BasisDependent, Mul): + """ + Denotes product of base- basis dependent quantity with a scalar. + """ + + def __new__(cls, *args, **options): + obj = cls._new(*args, **options) + return obj + + def _new_rawargs(self, *args): + # XXX: This is needed because Add.flatten() uses it but the default + # implementation does not work for Vectors because they assign + # attributes outside of .args. + return type(self)(*args) + + @classmethod + def _new(cls, *args, **options): + from sympy.vector import Cross, Dot, Curl, Gradient + count = 0 + measure_number = S.One + zeroflag = False + extra_args = [] + + # Determine the component and check arguments + # Also keep a count to ensure two vectors aren't + # being multiplied + for arg in args: + if isinstance(arg, cls._zero_func): + count += 1 + zeroflag = True + elif arg == S.Zero: + zeroflag = True + elif isinstance(arg, (cls._base_func, cls._mul_func)): + count += 1 + expr = arg._base_instance + measure_number *= arg._measure_number + elif isinstance(arg, cls._add_func): + count += 1 + expr = arg + elif isinstance(arg, (Cross, Dot, Curl, Gradient)): + extra_args.append(arg) + else: + measure_number *= arg + # Make sure incompatible types weren't multiplied + if count > 1: + raise ValueError("Invalid multiplication") + elif count == 0: + return Mul(*args, **options) + # Handle zero vector case + if zeroflag: + return cls.zero + + # If one of the args was a VectorAdd, return an + # appropriate VectorAdd instance + if isinstance(expr, cls._add_func): + newargs = [cls._mul_func(measure_number, x) for + x in expr.args] + return cls._add_func(*newargs) + + obj = super().__new__(cls, measure_number, + expr._base_instance, + *extra_args, + **options) + if isinstance(obj, Add): + return cls._add_func(*obj.args) + obj._base_instance = expr._base_instance + obj._measure_number = measure_number + assumptions = {'commutative': True} + obj._assumptions = StdFactKB(assumptions) + obj._components = {expr._base_instance: measure_number} + obj._sys = expr._base_instance._sys + + return obj + + def _sympystr(self, printer): + measure_str = printer._print(self._measure_number) + if ('(' in measure_str or '-' in measure_str or + '+' in measure_str): + measure_str = '(' + measure_str + ')' + return measure_str + '*' + printer._print(self._base_instance) + + +class BasisDependentZero(BasisDependent): + """ + Class to denote a zero basis dependent instance. + """ + components: dict['BaseVector', Expr] = {} + _latex_form: str + + def __new__(cls): + obj = super().__new__(cls) + # Pre-compute a specific hash value for the zero vector + # Use the same one always + obj._hash = (S.Zero, cls).__hash__() + return obj + + def __hash__(self): + return self._hash + + @call_highest_priority('__req__') + def __eq__(self, other): + return isinstance(other, self._zero_func) + + __req__ = __eq__ + + @call_highest_priority('__radd__') + def __add__(self, other): + if isinstance(other, self._expr_type): + return other + else: + raise TypeError("Invalid argument types for addition") + + @call_highest_priority('__add__') + def __radd__(self, other): + if isinstance(other, self._expr_type): + return other + else: + raise TypeError("Invalid argument types for addition") + + @call_highest_priority('__rsub__') + def __sub__(self, other): + if isinstance(other, self._expr_type): + return -other + else: + raise TypeError("Invalid argument types for subtraction") + + @call_highest_priority('__sub__') + def __rsub__(self, other): + if isinstance(other, self._expr_type): + return other + else: + raise TypeError("Invalid argument types for subtraction") + + def __neg__(self): + return self + + def normalize(self): + """ + Returns the normalized version of this vector. + """ + return self + + def _sympystr(self, printer): + return '0' diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/coordsysrect.py b/.venv/lib/python3.12/site-packages/sympy/vector/coordsysrect.py new file mode 100644 index 0000000000000000000000000000000000000000..55539fb19dc4221de69437111f44d6a6cc70b3e4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/coordsysrect.py @@ -0,0 +1,1031 @@ +from collections.abc import Callable + +from sympy.core.basic import Basic +from sympy.core.cache import cacheit +from sympy.core import S, Dummy, Lambda +from sympy.core.symbol import Str +from sympy.core.symbol import symbols +from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix +from sympy.matrices.matrixbase import MatrixBase +from sympy.solvers import solve +from sympy.vector.scalar import BaseScalar +from sympy.core.containers import Tuple +from sympy.core.function import diff +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (acos, atan2, cos, sin) +from sympy.matrices.dense import eye +from sympy.matrices.immutable import ImmutableDenseMatrix +from sympy.simplify.simplify import simplify +from sympy.simplify.trigsimp import trigsimp +import sympy.vector +from sympy.vector.orienters import (Orienter, AxisOrienter, BodyOrienter, + SpaceOrienter, QuaternionOrienter) + + +class CoordSys3D(Basic): + """ + Represents a coordinate system in 3-D space. + """ + + def __new__(cls, name, transformation=None, parent=None, location=None, + rotation_matrix=None, vector_names=None, variable_names=None): + """ + The orientation/location parameters are necessary if this system + is being defined at a certain orientation or location wrt another. + + Parameters + ========== + + name : str + The name of the new CoordSys3D instance. + + transformation : Lambda, Tuple, str + Transformation defined by transformation equations or chosen + from predefined ones. + + location : Vector + The position vector of the new system's origin wrt the parent + instance. + + rotation_matrix : SymPy ImmutableMatrix + The rotation matrix of the new coordinate system with respect + to the parent. In other words, the output of + new_system.rotation_matrix(parent). + + parent : CoordSys3D + The coordinate system wrt which the orientation/location + (or both) is being defined. + + vector_names, variable_names : iterable(optional) + Iterables of 3 strings each, with custom names for base + vectors and base scalars of the new system respectively. + Used for simple str printing. + + """ + + name = str(name) + Vector = sympy.vector.Vector + Point = sympy.vector.Point + + if not isinstance(name, str): + raise TypeError("name should be a string") + + if transformation is not None: + if (location is not None) or (rotation_matrix is not None): + raise ValueError("specify either `transformation` or " + "`location`/`rotation_matrix`") + if isinstance(transformation, (Tuple, tuple, list)): + if isinstance(transformation[0], MatrixBase): + rotation_matrix = transformation[0] + location = transformation[1] + else: + transformation = Lambda(transformation[0], + transformation[1]) + elif isinstance(transformation, Callable): + x1, x2, x3 = symbols('x1 x2 x3', cls=Dummy) + transformation = Lambda((x1, x2, x3), + transformation(x1, x2, x3)) + elif isinstance(transformation, str): + transformation = Str(transformation) + elif isinstance(transformation, (Str, Lambda)): + pass + else: + raise TypeError("transformation: " + "wrong type {}".format(type(transformation))) + + # If orientation information has been provided, store + # the rotation matrix accordingly + if rotation_matrix is None: + rotation_matrix = ImmutableDenseMatrix(eye(3)) + else: + if not isinstance(rotation_matrix, MatrixBase): + raise TypeError("rotation_matrix should be an Immutable" + + "Matrix instance") + rotation_matrix = rotation_matrix.as_immutable() + + # If location information is not given, adjust the default + # location as Vector.zero + if parent is not None: + if not isinstance(parent, CoordSys3D): + raise TypeError("parent should be a " + + "CoordSys3D/None") + if location is None: + location = Vector.zero + else: + if not isinstance(location, Vector): + raise TypeError("location should be a Vector") + # Check that location does not contain base + # scalars + for x in location.free_symbols: + if isinstance(x, BaseScalar): + raise ValueError("location should not contain" + + " BaseScalars") + origin = parent.origin.locate_new(name + '.origin', + location) + else: + location = Vector.zero + origin = Point(name + '.origin') + + if transformation is None: + transformation = Tuple(rotation_matrix, location) + + if isinstance(transformation, Tuple): + lambda_transformation = CoordSys3D._compose_rotation_and_translation( + transformation[0], + transformation[1], + parent + ) + r, l = transformation + l = l._projections + lambda_lame = CoordSys3D._get_lame_coeff('cartesian') + lambda_inverse = lambda x, y, z: r.inv()*Matrix( + [x-l[0], y-l[1], z-l[2]]) + elif isinstance(transformation, Str): + trname = transformation.name + lambda_transformation = CoordSys3D._get_transformation_lambdas(trname) + if parent is not None: + if parent.lame_coefficients() != (S.One, S.One, S.One): + raise ValueError('Parent for pre-defined coordinate ' + 'system should be Cartesian.') + lambda_lame = CoordSys3D._get_lame_coeff(trname) + lambda_inverse = CoordSys3D._set_inv_trans_equations(trname) + elif isinstance(transformation, Lambda): + if not CoordSys3D._check_orthogonality(transformation): + raise ValueError("The transformation equation does not " + "create orthogonal coordinate system") + lambda_transformation = transformation + lambda_lame = CoordSys3D._calculate_lame_coeff(lambda_transformation) + lambda_inverse = None + else: + lambda_transformation = lambda x, y, z: transformation(x, y, z) + lambda_lame = CoordSys3D._get_lame_coeff(transformation) + lambda_inverse = None + + if variable_names is None: + if isinstance(transformation, Lambda): + variable_names = ["x1", "x2", "x3"] + elif isinstance(transformation, Str): + if transformation.name == 'spherical': + variable_names = ["r", "theta", "phi"] + elif transformation.name == 'cylindrical': + variable_names = ["r", "theta", "z"] + else: + variable_names = ["x", "y", "z"] + else: + variable_names = ["x", "y", "z"] + if vector_names is None: + vector_names = ["i", "j", "k"] + + # All systems that are defined as 'roots' are unequal, unless + # they have the same name. + # Systems defined at same orientation/position wrt the same + # 'parent' are equal, irrespective of the name. + # This is true even if the same orientation is provided via + # different methods like Axis/Body/Space/Quaternion. + # However, coincident systems may be seen as unequal if + # positioned/oriented wrt different parents, even though + # they may actually be 'coincident' wrt the root system. + if parent is not None: + obj = super().__new__( + cls, Str(name), transformation, parent) + else: + obj = super().__new__( + cls, Str(name), transformation) + obj._name = name + # Initialize the base vectors + + _check_strings('vector_names', vector_names) + vector_names = list(vector_names) + latex_vects = [(r'\mathbf{\hat{%s}_{%s}}' % (x, name)) for + x in vector_names] + pretty_vects = ['%s_%s' % (x, name) for x in vector_names] + + obj._vector_names = vector_names + + v1 = BaseVector(0, obj, pretty_vects[0], latex_vects[0]) + v2 = BaseVector(1, obj, pretty_vects[1], latex_vects[1]) + v3 = BaseVector(2, obj, pretty_vects[2], latex_vects[2]) + + obj._base_vectors = (v1, v2, v3) + + # Initialize the base scalars + + _check_strings('variable_names', vector_names) + variable_names = list(variable_names) + latex_scalars = [(r"\mathbf{{%s}_{%s}}" % (x, name)) for + x in variable_names] + pretty_scalars = ['%s_%s' % (x, name) for x in variable_names] + + obj._variable_names = variable_names + obj._vector_names = vector_names + + x1 = BaseScalar(0, obj, pretty_scalars[0], latex_scalars[0]) + x2 = BaseScalar(1, obj, pretty_scalars[1], latex_scalars[1]) + x3 = BaseScalar(2, obj, pretty_scalars[2], latex_scalars[2]) + + obj._base_scalars = (x1, x2, x3) + + obj._transformation = transformation + obj._transformation_lambda = lambda_transformation + obj._lame_coefficients = lambda_lame(x1, x2, x3) + obj._transformation_from_parent_lambda = lambda_inverse + + setattr(obj, variable_names[0], x1) + setattr(obj, variable_names[1], x2) + setattr(obj, variable_names[2], x3) + + setattr(obj, vector_names[0], v1) + setattr(obj, vector_names[1], v2) + setattr(obj, vector_names[2], v3) + + # Assign params + obj._parent = parent + if obj._parent is not None: + obj._root = obj._parent._root + else: + obj._root = obj + + obj._parent_rotation_matrix = rotation_matrix + obj._origin = origin + + # Return the instance + return obj + + def _sympystr(self, printer): + return self._name + + def __iter__(self): + return iter(self.base_vectors()) + + @staticmethod + def _check_orthogonality(equations): + """ + Helper method for _connect_to_cartesian. It checks if + set of transformation equations create orthogonal curvilinear + coordinate system + + Parameters + ========== + + equations : Lambda + Lambda of transformation equations + + """ + + x1, x2, x3 = symbols("x1, x2, x3", cls=Dummy) + equations = equations(x1, x2, x3) + v1 = Matrix([diff(equations[0], x1), + diff(equations[1], x1), diff(equations[2], x1)]) + + v2 = Matrix([diff(equations[0], x2), + diff(equations[1], x2), diff(equations[2], x2)]) + + v3 = Matrix([diff(equations[0], x3), + diff(equations[1], x3), diff(equations[2], x3)]) + + if any(simplify(i[0] + i[1] + i[2]) == 0 for i in (v1, v2, v3)): + return False + else: + if simplify(v1.dot(v2)) == 0 and simplify(v2.dot(v3)) == 0 \ + and simplify(v3.dot(v1)) == 0: + return True + else: + return False + + @staticmethod + def _set_inv_trans_equations(curv_coord_name): + """ + Store information about inverse transformation equations for + pre-defined coordinate systems. + + Parameters + ========== + + curv_coord_name : str + Name of coordinate system + + """ + if curv_coord_name == 'cartesian': + return lambda x, y, z: (x, y, z) + + if curv_coord_name == 'spherical': + return lambda x, y, z: ( + sqrt(x**2 + y**2 + z**2), + acos(z/sqrt(x**2 + y**2 + z**2)), + atan2(y, x) + ) + if curv_coord_name == 'cylindrical': + return lambda x, y, z: ( + sqrt(x**2 + y**2), + atan2(y, x), + z + ) + raise ValueError('Wrong set of parameters.' + 'Type of coordinate system is defined') + + def _calculate_inv_trans_equations(self): + """ + Helper method for set_coordinate_type. It calculates inverse + transformation equations for given transformations equations. + + """ + x1, x2, x3 = symbols("x1, x2, x3", cls=Dummy, reals=True) + x, y, z = symbols("x, y, z", cls=Dummy) + + equations = self._transformation(x1, x2, x3) + + solved = solve([equations[0] - x, + equations[1] - y, + equations[2] - z], (x1, x2, x3), dict=True)[0] + solved = solved[x1], solved[x2], solved[x3] + self._transformation_from_parent_lambda = \ + lambda x1, x2, x3: tuple(i.subs(list(zip((x, y, z), (x1, x2, x3)))) for i in solved) + + @staticmethod + def _get_lame_coeff(curv_coord_name): + """ + Store information about Lame coefficients for pre-defined + coordinate systems. + + Parameters + ========== + + curv_coord_name : str + Name of coordinate system + + """ + if isinstance(curv_coord_name, str): + if curv_coord_name == 'cartesian': + return lambda x, y, z: (S.One, S.One, S.One) + if curv_coord_name == 'spherical': + return lambda r, theta, phi: (S.One, r, r*sin(theta)) + if curv_coord_name == 'cylindrical': + return lambda r, theta, h: (S.One, r, S.One) + raise ValueError('Wrong set of parameters.' + ' Type of coordinate system is not defined') + return CoordSys3D._calculate_lame_coefficients(curv_coord_name) + + @staticmethod + def _calculate_lame_coeff(equations): + """ + It calculates Lame coefficients + for given transformations equations. + + Parameters + ========== + + equations : Lambda + Lambda of transformation equations. + + """ + return lambda x1, x2, x3: ( + sqrt(diff(equations(x1, x2, x3)[0], x1)**2 + + diff(equations(x1, x2, x3)[1], x1)**2 + + diff(equations(x1, x2, x3)[2], x1)**2), + sqrt(diff(equations(x1, x2, x3)[0], x2)**2 + + diff(equations(x1, x2, x3)[1], x2)**2 + + diff(equations(x1, x2, x3)[2], x2)**2), + sqrt(diff(equations(x1, x2, x3)[0], x3)**2 + + diff(equations(x1, x2, x3)[1], x3)**2 + + diff(equations(x1, x2, x3)[2], x3)**2) + ) + + def _inverse_rotation_matrix(self): + """ + Returns inverse rotation matrix. + """ + return simplify(self._parent_rotation_matrix**-1) + + @staticmethod + def _get_transformation_lambdas(curv_coord_name): + """ + Store information about transformation equations for pre-defined + coordinate systems. + + Parameters + ========== + + curv_coord_name : str + Name of coordinate system + + """ + if isinstance(curv_coord_name, str): + if curv_coord_name == 'cartesian': + return lambda x, y, z: (x, y, z) + if curv_coord_name == 'spherical': + return lambda r, theta, phi: ( + r*sin(theta)*cos(phi), + r*sin(theta)*sin(phi), + r*cos(theta) + ) + if curv_coord_name == 'cylindrical': + return lambda r, theta, h: ( + r*cos(theta), + r*sin(theta), + h + ) + raise ValueError('Wrong set of parameters.' + 'Type of coordinate system is defined') + + @classmethod + def _rotation_trans_equations(cls, matrix, equations): + """ + Returns the transformation equations obtained from rotation matrix. + + Parameters + ========== + + matrix : Matrix + Rotation matrix + + equations : tuple + Transformation equations + + """ + return tuple(matrix * Matrix(equations)) + + @property + def origin(self): + return self._origin + + def base_vectors(self): + return self._base_vectors + + def base_scalars(self): + return self._base_scalars + + def lame_coefficients(self): + return self._lame_coefficients + + def transformation_to_parent(self): + return self._transformation_lambda(*self.base_scalars()) + + def transformation_from_parent(self): + if self._parent is None: + raise ValueError("no parent coordinate system, use " + "`transformation_from_parent_function()`") + return self._transformation_from_parent_lambda( + *self._parent.base_scalars()) + + def transformation_from_parent_function(self): + return self._transformation_from_parent_lambda + + def rotation_matrix(self, other): + """ + Returns the direction cosine matrix(DCM), also known as the + 'rotation matrix' of this coordinate system with respect to + another system. + + If v_a is a vector defined in system 'A' (in matrix format) + and v_b is the same vector defined in system 'B', then + v_a = A.rotation_matrix(B) * v_b. + + A SymPy Matrix is returned. + + Parameters + ========== + + other : CoordSys3D + The system which the DCM is generated to. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> from sympy import symbols + >>> q1 = symbols('q1') + >>> N = CoordSys3D('N') + >>> A = N.orient_new_axis('A', q1, N.i) + >>> N.rotation_matrix(A) + Matrix([ + [1, 0, 0], + [0, cos(q1), -sin(q1)], + [0, sin(q1), cos(q1)]]) + + """ + from sympy.vector.functions import _path + if not isinstance(other, CoordSys3D): + raise TypeError(str(other) + + " is not a CoordSys3D") + # Handle special cases + if other == self: + return eye(3) + elif other == self._parent: + return self._parent_rotation_matrix + elif other._parent == self: + return other._parent_rotation_matrix.T + # Else, use tree to calculate position + rootindex, path = _path(self, other) + result = eye(3) + for i in range(rootindex): + result *= path[i]._parent_rotation_matrix + for i in range(rootindex + 1, len(path)): + result *= path[i]._parent_rotation_matrix.T + return result + + @cacheit + def position_wrt(self, other): + """ + Returns the position vector of the origin of this coordinate + system with respect to another Point/CoordSys3D. + + Parameters + ========== + + other : Point/CoordSys3D + If other is a Point, the position of this system's origin + wrt it is returned. If its an instance of CoordSyRect, + the position wrt its origin is returned. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> N = CoordSys3D('N') + >>> N1 = N.locate_new('N1', 10 * N.i) + >>> N.position_wrt(N1) + (-10)*N.i + + """ + return self.origin.position_wrt(other) + + def scalar_map(self, other): + """ + Returns a dictionary which expresses the coordinate variables + (base scalars) of this frame in terms of the variables of + otherframe. + + Parameters + ========== + + otherframe : CoordSys3D + The other system to map the variables to. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> from sympy import Symbol + >>> A = CoordSys3D('A') + >>> q = Symbol('q') + >>> B = A.orient_new_axis('B', q, A.k) + >>> A.scalar_map(B) + {A.x: B.x*cos(q) - B.y*sin(q), A.y: B.x*sin(q) + B.y*cos(q), A.z: B.z} + + """ + + origin_coords = tuple(self.position_wrt(other).to_matrix(other)) + relocated_scalars = [x - origin_coords[i] + for i, x in enumerate(other.base_scalars())] + + vars_matrix = (self.rotation_matrix(other) * + Matrix(relocated_scalars)) + return {x: trigsimp(vars_matrix[i]) + for i, x in enumerate(self.base_scalars())} + + def locate_new(self, name, position, vector_names=None, + variable_names=None): + """ + Returns a CoordSys3D with its origin located at the given + position wrt this coordinate system's origin. + + Parameters + ========== + + name : str + The name of the new CoordSys3D instance. + + position : Vector + The position vector of the new system's origin wrt this + one. + + vector_names, variable_names : iterable(optional) + Iterables of 3 strings each, with custom names for base + vectors and base scalars of the new system respectively. + Used for simple str printing. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> A = CoordSys3D('A') + >>> B = A.locate_new('B', 10 * A.i) + >>> B.origin.position_wrt(A.origin) + 10*A.i + + """ + if variable_names is None: + variable_names = self._variable_names + if vector_names is None: + vector_names = self._vector_names + + return CoordSys3D(name, location=position, + vector_names=vector_names, + variable_names=variable_names, + parent=self) + + def orient_new(self, name, orienters, location=None, + vector_names=None, variable_names=None): + """ + Creates a new CoordSys3D oriented in the user-specified way + with respect to this system. + + Please refer to the documentation of the orienter classes + for more information about the orientation procedure. + + Parameters + ========== + + name : str + The name of the new CoordSys3D instance. + + orienters : iterable/Orienter + An Orienter or an iterable of Orienters for orienting the + new coordinate system. + If an Orienter is provided, it is applied to get the new + system. + If an iterable is provided, the orienters will be applied + in the order in which they appear in the iterable. + + location : Vector(optional) + The location of the new coordinate system's origin wrt this + system's origin. If not specified, the origins are taken to + be coincident. + + vector_names, variable_names : iterable(optional) + Iterables of 3 strings each, with custom names for base + vectors and base scalars of the new system respectively. + Used for simple str printing. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> from sympy import symbols + >>> q0, q1, q2, q3 = symbols('q0 q1 q2 q3') + >>> N = CoordSys3D('N') + + Using an AxisOrienter + + >>> from sympy.vector import AxisOrienter + >>> axis_orienter = AxisOrienter(q1, N.i + 2 * N.j) + >>> A = N.orient_new('A', (axis_orienter, )) + + Using a BodyOrienter + + >>> from sympy.vector import BodyOrienter + >>> body_orienter = BodyOrienter(q1, q2, q3, '123') + >>> B = N.orient_new('B', (body_orienter, )) + + Using a SpaceOrienter + + >>> from sympy.vector import SpaceOrienter + >>> space_orienter = SpaceOrienter(q1, q2, q3, '312') + >>> C = N.orient_new('C', (space_orienter, )) + + Using a QuaternionOrienter + + >>> from sympy.vector import QuaternionOrienter + >>> q_orienter = QuaternionOrienter(q0, q1, q2, q3) + >>> D = N.orient_new('D', (q_orienter, )) + """ + if variable_names is None: + variable_names = self._variable_names + if vector_names is None: + vector_names = self._vector_names + + if isinstance(orienters, Orienter): + if isinstance(orienters, AxisOrienter): + final_matrix = orienters.rotation_matrix(self) + else: + final_matrix = orienters.rotation_matrix() + # TODO: trigsimp is needed here so that the matrix becomes + # canonical (scalar_map also calls trigsimp; without this, you can + # end up with the same CoordinateSystem that compares differently + # due to a differently formatted matrix). However, this is + # probably not so good for performance. + final_matrix = trigsimp(final_matrix) + else: + final_matrix = Matrix(eye(3)) + for orienter in orienters: + if isinstance(orienter, AxisOrienter): + final_matrix *= orienter.rotation_matrix(self) + else: + final_matrix *= orienter.rotation_matrix() + + return CoordSys3D(name, rotation_matrix=final_matrix, + vector_names=vector_names, + variable_names=variable_names, + location=location, + parent=self) + + def orient_new_axis(self, name, angle, axis, location=None, + vector_names=None, variable_names=None): + """ + Axis rotation is a rotation about an arbitrary axis by + some angle. The angle is supplied as a SymPy expr scalar, and + the axis is supplied as a Vector. + + Parameters + ========== + + name : string + The name of the new coordinate system + + angle : Expr + The angle by which the new system is to be rotated + + axis : Vector + The axis around which the rotation has to be performed + + location : Vector(optional) + The location of the new coordinate system's origin wrt this + system's origin. If not specified, the origins are taken to + be coincident. + + vector_names, variable_names : iterable(optional) + Iterables of 3 strings each, with custom names for base + vectors and base scalars of the new system respectively. + Used for simple str printing. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> from sympy import symbols + >>> q1 = symbols('q1') + >>> N = CoordSys3D('N') + >>> B = N.orient_new_axis('B', q1, N.i + 2 * N.j) + + """ + if variable_names is None: + variable_names = self._variable_names + if vector_names is None: + vector_names = self._vector_names + + orienter = AxisOrienter(angle, axis) + return self.orient_new(name, orienter, + location=location, + vector_names=vector_names, + variable_names=variable_names) + + def orient_new_body(self, name, angle1, angle2, angle3, + rotation_order, location=None, + vector_names=None, variable_names=None): + """ + Body orientation takes this coordinate system through three + successive simple rotations. + + Body fixed rotations include both Euler Angles and + Tait-Bryan Angles, see https://en.wikipedia.org/wiki/Euler_angles. + + Parameters + ========== + + name : string + The name of the new coordinate system + + angle1, angle2, angle3 : Expr + Three successive angles to rotate the coordinate system by + + rotation_order : string + String defining the order of axes for rotation + + location : Vector(optional) + The location of the new coordinate system's origin wrt this + system's origin. If not specified, the origins are taken to + be coincident. + + vector_names, variable_names : iterable(optional) + Iterables of 3 strings each, with custom names for base + vectors and base scalars of the new system respectively. + Used for simple str printing. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> from sympy import symbols + >>> q1, q2, q3 = symbols('q1 q2 q3') + >>> N = CoordSys3D('N') + + A 'Body' fixed rotation is described by three angles and + three body-fixed rotation axes. To orient a coordinate system D + with respect to N, each sequential rotation is always about + the orthogonal unit vectors fixed to D. For example, a '123' + rotation will specify rotations about N.i, then D.j, then + D.k. (Initially, D.i is same as N.i) + Therefore, + + >>> D = N.orient_new_body('D', q1, q2, q3, '123') + + is same as + + >>> D = N.orient_new_axis('D', q1, N.i) + >>> D = D.orient_new_axis('D', q2, D.j) + >>> D = D.orient_new_axis('D', q3, D.k) + + Acceptable rotation orders are of length 3, expressed in XYZ or + 123, and cannot have a rotation about about an axis twice in a row. + + >>> B = N.orient_new_body('B', q1, q2, q3, '123') + >>> B = N.orient_new_body('B', q1, q2, 0, 'ZXZ') + >>> B = N.orient_new_body('B', 0, 0, 0, 'XYX') + + """ + + orienter = BodyOrienter(angle1, angle2, angle3, rotation_order) + return self.orient_new(name, orienter, + location=location, + vector_names=vector_names, + variable_names=variable_names) + + def orient_new_space(self, name, angle1, angle2, angle3, + rotation_order, location=None, + vector_names=None, variable_names=None): + """ + Space rotation is similar to Body rotation, but the rotations + are applied in the opposite order. + + Parameters + ========== + + name : string + The name of the new coordinate system + + angle1, angle2, angle3 : Expr + Three successive angles to rotate the coordinate system by + + rotation_order : string + String defining the order of axes for rotation + + location : Vector(optional) + The location of the new coordinate system's origin wrt this + system's origin. If not specified, the origins are taken to + be coincident. + + vector_names, variable_names : iterable(optional) + Iterables of 3 strings each, with custom names for base + vectors and base scalars of the new system respectively. + Used for simple str printing. + + See Also + ======== + + CoordSys3D.orient_new_body : method to orient via Euler + angles + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> from sympy import symbols + >>> q1, q2, q3 = symbols('q1 q2 q3') + >>> N = CoordSys3D('N') + + To orient a coordinate system D with respect to N, each + sequential rotation is always about N's orthogonal unit vectors. + For example, a '123' rotation will specify rotations about + N.i, then N.j, then N.k. + Therefore, + + >>> D = N.orient_new_space('D', q1, q2, q3, '312') + + is same as + + >>> B = N.orient_new_axis('B', q1, N.i) + >>> C = B.orient_new_axis('C', q2, N.j) + >>> D = C.orient_new_axis('D', q3, N.k) + + """ + + orienter = SpaceOrienter(angle1, angle2, angle3, rotation_order) + return self.orient_new(name, orienter, + location=location, + vector_names=vector_names, + variable_names=variable_names) + + def orient_new_quaternion(self, name, q0, q1, q2, q3, location=None, + vector_names=None, variable_names=None): + """ + Quaternion orientation orients the new CoordSys3D with + Quaternions, defined as a finite rotation about lambda, a unit + vector, by some amount theta. + + This orientation is described by four parameters: + + q0 = cos(theta/2) + + q1 = lambda_x sin(theta/2) + + q2 = lambda_y sin(theta/2) + + q3 = lambda_z sin(theta/2) + + Quaternion does not take in a rotation order. + + Parameters + ========== + + name : string + The name of the new coordinate system + + q0, q1, q2, q3 : Expr + The quaternions to rotate the coordinate system by + + location : Vector(optional) + The location of the new coordinate system's origin wrt this + system's origin. If not specified, the origins are taken to + be coincident. + + vector_names, variable_names : iterable(optional) + Iterables of 3 strings each, with custom names for base + vectors and base scalars of the new system respectively. + Used for simple str printing. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> from sympy import symbols + >>> q0, q1, q2, q3 = symbols('q0 q1 q2 q3') + >>> N = CoordSys3D('N') + >>> B = N.orient_new_quaternion('B', q0, q1, q2, q3) + + """ + + orienter = QuaternionOrienter(q0, q1, q2, q3) + return self.orient_new(name, orienter, + location=location, + vector_names=vector_names, + variable_names=variable_names) + + def create_new(self, name, transformation, variable_names=None, vector_names=None): + """ + Returns a CoordSys3D which is connected to self by transformation. + + Parameters + ========== + + name : str + The name of the new CoordSys3D instance. + + transformation : Lambda, Tuple, str + Transformation defined by transformation equations or chosen + from predefined ones. + + vector_names, variable_names : iterable(optional) + Iterables of 3 strings each, with custom names for base + vectors and base scalars of the new system respectively. + Used for simple str printing. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> a = CoordSys3D('a') + >>> b = a.create_new('b', transformation='spherical') + >>> b.transformation_to_parent() + (b.r*sin(b.theta)*cos(b.phi), b.r*sin(b.phi)*sin(b.theta), b.r*cos(b.theta)) + >>> b.transformation_from_parent() + (sqrt(a.x**2 + a.y**2 + a.z**2), acos(a.z/sqrt(a.x**2 + a.y**2 + a.z**2)), atan2(a.y, a.x)) + + """ + return CoordSys3D(name, parent=self, transformation=transformation, + variable_names=variable_names, vector_names=vector_names) + + def __init__(self, name, location=None, rotation_matrix=None, + parent=None, vector_names=None, variable_names=None, + latex_vects=None, pretty_vects=None, latex_scalars=None, + pretty_scalars=None, transformation=None): + # Dummy initializer for setting docstring + pass + + __init__.__doc__ = __new__.__doc__ + + @staticmethod + def _compose_rotation_and_translation(rot, translation, parent): + r = lambda x, y, z: CoordSys3D._rotation_trans_equations(rot, (x, y, z)) + if parent is None: + return r + + dx, dy, dz = [translation.dot(i) for i in parent.base_vectors()] + t = lambda x, y, z: ( + x + dx, + y + dy, + z + dz, + ) + return lambda x, y, z: t(*r(x, y, z)) + + +def _check_strings(arg_name, arg): + errorstr = arg_name + " must be an iterable of 3 string-types" + if len(arg) != 3: + raise ValueError(errorstr) + for s in arg: + if not isinstance(s, str): + raise TypeError(errorstr) + + +# Delayed import to avoid cyclic import problems: +from sympy.vector.vector import BaseVector diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/deloperator.py b/.venv/lib/python3.12/site-packages/sympy/vector/deloperator.py new file mode 100644 index 0000000000000000000000000000000000000000..51c3c0caf42b5e5d372bd65907d8bae2bd563562 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/deloperator.py @@ -0,0 +1,121 @@ +from sympy.core import Basic +from sympy.vector.operators import gradient, divergence, curl + + +class Del(Basic): + """ + Represents the vector differential operator, usually represented in + mathematical expressions as the 'nabla' symbol. + """ + + def __new__(cls): + obj = super().__new__(cls) + obj._name = "delop" + return obj + + def gradient(self, scalar_field, doit=False): + """ + Returns the gradient of the given scalar field, as a + Vector instance. + + Parameters + ========== + + scalar_field : SymPy expression + The scalar field to calculate the gradient of. + + doit : bool + If True, the result is returned after calling .doit() on + each component. Else, the returned expression contains + Derivative instances + + Examples + ======== + + >>> from sympy.vector import CoordSys3D, Del + >>> C = CoordSys3D('C') + >>> delop = Del() + >>> delop.gradient(9) + 0 + >>> delop(C.x*C.y*C.z).doit() + C.y*C.z*C.i + C.x*C.z*C.j + C.x*C.y*C.k + + """ + + return gradient(scalar_field, doit=doit) + + __call__ = gradient + __call__.__doc__ = gradient.__doc__ + + def dot(self, vect, doit=False): + """ + Represents the dot product between this operator and a given + vector - equal to the divergence of the vector field. + + Parameters + ========== + + vect : Vector + The vector whose divergence is to be calculated. + + doit : bool + If True, the result is returned after calling .doit() on + each component. Else, the returned expression contains + Derivative instances + + Examples + ======== + + >>> from sympy.vector import CoordSys3D, Del + >>> delop = Del() + >>> C = CoordSys3D('C') + >>> delop.dot(C.x*C.i) + Derivative(C.x, C.x) + >>> v = C.x*C.y*C.z * (C.i + C.j + C.k) + >>> (delop & v).doit() + C.x*C.y + C.x*C.z + C.y*C.z + + """ + return divergence(vect, doit=doit) + + __and__ = dot + __and__.__doc__ = dot.__doc__ + + def cross(self, vect, doit=False): + """ + Represents the cross product between this operator and a given + vector - equal to the curl of the vector field. + + Parameters + ========== + + vect : Vector + The vector whose curl is to be calculated. + + doit : bool + If True, the result is returned after calling .doit() on + each component. Else, the returned expression contains + Derivative instances + + Examples + ======== + + >>> from sympy.vector import CoordSys3D, Del + >>> C = CoordSys3D('C') + >>> delop = Del() + >>> v = C.x*C.y*C.z * (C.i + C.j + C.k) + >>> delop.cross(v, doit = True) + (-C.x*C.y + C.x*C.z)*C.i + (C.x*C.y - C.y*C.z)*C.j + + (-C.x*C.z + C.y*C.z)*C.k + >>> (delop ^ C.i).doit() + 0 + + """ + + return curl(vect, doit=doit) + + __xor__ = cross + __xor__.__doc__ = cross.__doc__ + + def _sympystr(self, printer): + return self._name diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/dyadic.py b/.venv/lib/python3.12/site-packages/sympy/vector/dyadic.py new file mode 100644 index 0000000000000000000000000000000000000000..980c6e6dad90ac095b7bd6d4228f507a7831b39f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/dyadic.py @@ -0,0 +1,285 @@ +from __future__ import annotations + +from sympy.vector.basisdependent import (BasisDependent, BasisDependentAdd, + BasisDependentMul, BasisDependentZero) +from sympy.core import S, Pow +from sympy.core.expr import AtomicExpr +from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix +import sympy.vector + + +class Dyadic(BasisDependent): + """ + Super class for all Dyadic-classes. + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Dyadic_tensor + .. [2] Kane, T., Levinson, D. Dynamics Theory and Applications. 1985 + McGraw-Hill + + """ + + _op_priority = 13.0 + + _expr_type: type[Dyadic] + _mul_func: type[Dyadic] + _add_func: type[Dyadic] + _zero_func: type[Dyadic] + _base_func: type[Dyadic] + zero: DyadicZero + + @property + def components(self): + """ + Returns the components of this dyadic in the form of a + Python dictionary mapping BaseDyadic instances to the + corresponding measure numbers. + + """ + # The '_components' attribute is defined according to the + # subclass of Dyadic the instance belongs to. + return self._components + + def dot(self, other): + """ + Returns the dot product(also called inner product) of this + Dyadic, with another Dyadic or Vector. + If 'other' is a Dyadic, this returns a Dyadic. Else, it returns + a Vector (unless an error is encountered). + + Parameters + ========== + + other : Dyadic/Vector + The other Dyadic or Vector to take the inner product with + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> N = CoordSys3D('N') + >>> D1 = N.i.outer(N.j) + >>> D2 = N.j.outer(N.j) + >>> D1.dot(D2) + (N.i|N.j) + >>> D1.dot(N.j) + N.i + + """ + + Vector = sympy.vector.Vector + if isinstance(other, BasisDependentZero): + return Vector.zero + elif isinstance(other, Vector): + outvec = Vector.zero + for k, v in self.components.items(): + vect_dot = k.args[1].dot(other) + outvec += vect_dot * v * k.args[0] + return outvec + elif isinstance(other, Dyadic): + outdyad = Dyadic.zero + for k1, v1 in self.components.items(): + for k2, v2 in other.components.items(): + vect_dot = k1.args[1].dot(k2.args[0]) + outer_product = k1.args[0].outer(k2.args[1]) + outdyad += vect_dot * v1 * v2 * outer_product + return outdyad + else: + raise TypeError("Inner product is not defined for " + + str(type(other)) + " and Dyadics.") + + def __and__(self, other): + return self.dot(other) + + __and__.__doc__ = dot.__doc__ + + def cross(self, other): + """ + Returns the cross product between this Dyadic, and a Vector, as a + Vector instance. + + Parameters + ========== + + other : Vector + The Vector that we are crossing this Dyadic with + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> N = CoordSys3D('N') + >>> d = N.i.outer(N.i) + >>> d.cross(N.j) + (N.i|N.k) + + """ + + Vector = sympy.vector.Vector + if other == Vector.zero: + return Dyadic.zero + elif isinstance(other, Vector): + outdyad = Dyadic.zero + for k, v in self.components.items(): + cross_product = k.args[1].cross(other) + outer = k.args[0].outer(cross_product) + outdyad += v * outer + return outdyad + else: + raise TypeError(str(type(other)) + " not supported for " + + "cross with dyadics") + + def __xor__(self, other): + return self.cross(other) + + __xor__.__doc__ = cross.__doc__ + + def to_matrix(self, system, second_system=None): + """ + Returns the matrix form of the dyadic with respect to one or two + coordinate systems. + + Parameters + ========== + + system : CoordSys3D + The coordinate system that the rows and columns of the matrix + correspond to. If a second system is provided, this + only corresponds to the rows of the matrix. + second_system : CoordSys3D, optional, default=None + The coordinate system that the columns of the matrix correspond + to. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> N = CoordSys3D('N') + >>> v = N.i + 2*N.j + >>> d = v.outer(N.i) + >>> d.to_matrix(N) + Matrix([ + [1, 0, 0], + [2, 0, 0], + [0, 0, 0]]) + >>> from sympy import Symbol + >>> q = Symbol('q') + >>> P = N.orient_new_axis('P', q, N.k) + >>> d.to_matrix(N, P) + Matrix([ + [ cos(q), -sin(q), 0], + [2*cos(q), -2*sin(q), 0], + [ 0, 0, 0]]) + + """ + + if second_system is None: + second_system = system + + return Matrix([i.dot(self).dot(j) for i in system for j in + second_system]).reshape(3, 3) + + def _div_helper(one, other): + """ Helper for division involving dyadics """ + if isinstance(one, Dyadic) and isinstance(other, Dyadic): + raise TypeError("Cannot divide two dyadics") + elif isinstance(one, Dyadic): + return DyadicMul(one, Pow(other, S.NegativeOne)) + else: + raise TypeError("Cannot divide by a dyadic") + + +class BaseDyadic(Dyadic, AtomicExpr): + """ + Class to denote a base dyadic tensor component. + """ + + def __new__(cls, vector1, vector2): + Vector = sympy.vector.Vector + BaseVector = sympy.vector.BaseVector + VectorZero = sympy.vector.VectorZero + # Verify arguments + if not isinstance(vector1, (BaseVector, VectorZero)) or \ + not isinstance(vector2, (BaseVector, VectorZero)): + raise TypeError("BaseDyadic cannot be composed of non-base " + + "vectors") + # Handle special case of zero vector + elif vector1 == Vector.zero or vector2 == Vector.zero: + return Dyadic.zero + # Initialize instance + obj = super().__new__(cls, vector1, vector2) + obj._base_instance = obj + obj._measure_number = 1 + obj._components = {obj: S.One} + obj._sys = vector1._sys + obj._pretty_form = ('(' + vector1._pretty_form + '|' + + vector2._pretty_form + ')') + obj._latex_form = (r'\left(' + vector1._latex_form + r"{\middle|}" + + vector2._latex_form + r'\right)') + + return obj + + def _sympystr(self, printer): + return "({}|{})".format( + printer._print(self.args[0]), printer._print(self.args[1])) + + def _sympyrepr(self, printer): + return "BaseDyadic({}, {})".format( + printer._print(self.args[0]), printer._print(self.args[1])) + + +class DyadicMul(BasisDependentMul, Dyadic): + """ Products of scalars and BaseDyadics """ + + def __new__(cls, *args, **options): + obj = BasisDependentMul.__new__(cls, *args, **options) + return obj + + @property + def base_dyadic(self): + """ The BaseDyadic involved in the product. """ + return self._base_instance + + @property + def measure_number(self): + """ The scalar expression involved in the definition of + this DyadicMul. + """ + return self._measure_number + + +class DyadicAdd(BasisDependentAdd, Dyadic): + """ Class to hold dyadic sums """ + + def __new__(cls, *args, **options): + obj = BasisDependentAdd.__new__(cls, *args, **options) + return obj + + def _sympystr(self, printer): + items = list(self.components.items()) + items.sort(key=lambda x: x[0].__str__()) + return " + ".join(printer._print(k * v) for k, v in items) + + +class DyadicZero(BasisDependentZero, Dyadic): + """ + Class to denote a zero dyadic + """ + + _op_priority = 13.1 + _pretty_form = '(0|0)' + _latex_form = r'(\mathbf{\hat{0}}|\mathbf{\hat{0}})' + + def __new__(cls): + obj = BasisDependentZero.__new__(cls) + return obj + + +Dyadic._expr_type = Dyadic +Dyadic._mul_func = DyadicMul +Dyadic._add_func = DyadicAdd +Dyadic._zero_func = DyadicZero +Dyadic._base_func = BaseDyadic +Dyadic.zero = DyadicZero() diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/functions.py b/.venv/lib/python3.12/site-packages/sympy/vector/functions.py new file mode 100644 index 0000000000000000000000000000000000000000..b78df8ae2e182f3e571ca7fa8bfabd39bf99d26e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/functions.py @@ -0,0 +1,513 @@ +from sympy.vector.coordsysrect import CoordSys3D +from sympy.vector.deloperator import Del +from sympy.vector.scalar import BaseScalar +from sympy.vector.vector import Vector, BaseVector +from sympy.vector.operators import gradient, curl, divergence +from sympy.core.function import diff +from sympy.core.singleton import S +from sympy.integrals.integrals import integrate +from sympy.core import sympify +from sympy.vector.dyadic import Dyadic + + +def express(expr, system, system2=None, variables=False): + """ + Global function for 'express' functionality. + + Re-expresses a Vector, Dyadic or scalar(sympyfiable) in the given + coordinate system. + + If 'variables' is True, then the coordinate variables (base scalars) + of other coordinate systems present in the vector/scalar field or + dyadic are also substituted in terms of the base scalars of the + given system. + + Parameters + ========== + + expr : Vector/Dyadic/scalar(sympyfiable) + The expression to re-express in CoordSys3D 'system' + + system: CoordSys3D + The coordinate system the expr is to be expressed in + + system2: CoordSys3D + The other coordinate system required for re-expression + (only for a Dyadic Expr) + + variables : boolean + Specifies whether to substitute the coordinate variables present + in expr, in terms of those of parameter system + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> from sympy import Symbol, cos, sin + >>> N = CoordSys3D('N') + >>> q = Symbol('q') + >>> B = N.orient_new_axis('B', q, N.k) + >>> from sympy.vector import express + >>> express(B.i, N) + (cos(q))*N.i + (sin(q))*N.j + >>> express(N.x, B, variables=True) + B.x*cos(q) - B.y*sin(q) + >>> d = N.i.outer(N.i) + >>> express(d, B, N) == (cos(q))*(B.i|N.i) + (-sin(q))*(B.j|N.i) + True + + """ + + if expr in (0, Vector.zero): + return expr + + if not isinstance(system, CoordSys3D): + raise TypeError("system should be a CoordSys3D \ + instance") + + if isinstance(expr, Vector): + if system2 is not None: + raise ValueError("system2 should not be provided for \ + Vectors") + # Given expr is a Vector + if variables: + # If variables attribute is True, substitute + # the coordinate variables in the Vector + system_list = {x.system for x in expr.atoms(BaseScalar, BaseVector)} - {system} + subs_dict = {} + for f in system_list: + subs_dict.update(f.scalar_map(system)) + expr = expr.subs(subs_dict) + # Re-express in this coordinate system + outvec = Vector.zero + parts = expr.separate() + for x in parts: + if x != system: + temp = system.rotation_matrix(x) * parts[x].to_matrix(x) + outvec += matrix_to_vector(temp, system) + else: + outvec += parts[x] + return outvec + + elif isinstance(expr, Dyadic): + if system2 is None: + system2 = system + if not isinstance(system2, CoordSys3D): + raise TypeError("system2 should be a CoordSys3D \ + instance") + outdyad = Dyadic.zero + var = variables + for k, v in expr.components.items(): + outdyad += (express(v, system, variables=var) * + (express(k.args[0], system, variables=var) | + express(k.args[1], system2, variables=var))) + + return outdyad + + else: + if system2 is not None: + raise ValueError("system2 should not be provided for \ + Vectors") + if variables: + # Given expr is a scalar field + system_set = set() + expr = sympify(expr) + # Substitute all the coordinate variables + for x in expr.atoms(BaseScalar): + if x.system != system: + system_set.add(x.system) + subs_dict = {} + for f in system_set: + subs_dict.update(f.scalar_map(system)) + return expr.subs(subs_dict) + return expr + + +def directional_derivative(field, direction_vector): + """ + Returns the directional derivative of a scalar or vector field computed + along a given vector in coordinate system which parameters are expressed. + + Parameters + ========== + + field : Vector or Scalar + The scalar or vector field to compute the directional derivative of + + direction_vector : Vector + The vector to calculated directional derivative along them. + + + Examples + ======== + + >>> from sympy.vector import CoordSys3D, directional_derivative + >>> R = CoordSys3D('R') + >>> f1 = R.x*R.y*R.z + >>> v1 = 3*R.i + 4*R.j + R.k + >>> directional_derivative(f1, v1) + R.x*R.y + 4*R.x*R.z + 3*R.y*R.z + >>> f2 = 5*R.x**2*R.z + >>> directional_derivative(f2, v1) + 5*R.x**2 + 30*R.x*R.z + + """ + from sympy.vector.operators import _get_coord_systems + coord_sys = _get_coord_systems(field) + if len(coord_sys) > 0: + # TODO: This gets a random coordinate system in case of multiple ones: + coord_sys = next(iter(coord_sys)) + field = express(field, coord_sys, variables=True) + i, j, k = coord_sys.base_vectors() + x, y, z = coord_sys.base_scalars() + out = Vector.dot(direction_vector, i) * diff(field, x) + out += Vector.dot(direction_vector, j) * diff(field, y) + out += Vector.dot(direction_vector, k) * diff(field, z) + if out == 0 and isinstance(field, Vector): + out = Vector.zero + return out + elif isinstance(field, Vector): + return Vector.zero + else: + return S.Zero + + +def laplacian(expr): + """ + Return the laplacian of the given field computed in terms of + the base scalars of the given coordinate system. + + Parameters + ========== + + expr : SymPy Expr or Vector + expr denotes a scalar or vector field. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D, laplacian + >>> R = CoordSys3D('R') + >>> f = R.x**2*R.y**5*R.z + >>> laplacian(f) + 20*R.x**2*R.y**3*R.z + 2*R.y**5*R.z + >>> f = R.x**2*R.i + R.y**3*R.j + R.z**4*R.k + >>> laplacian(f) + 2*R.i + 6*R.y*R.j + 12*R.z**2*R.k + + """ + + delop = Del() + if expr.is_Vector: + return (gradient(divergence(expr)) - curl(curl(expr))).doit() + return delop.dot(delop(expr)).doit() + + +def is_conservative(field): + """ + Checks if a field is conservative. + + Parameters + ========== + + field : Vector + The field to check for conservative property + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> from sympy.vector import is_conservative + >>> R = CoordSys3D('R') + >>> is_conservative(R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k) + True + >>> is_conservative(R.z*R.j) + False + + """ + + # Field is conservative irrespective of system + # Take the first coordinate system in the result of the + # separate method of Vector + if not isinstance(field, Vector): + raise TypeError("field should be a Vector") + if field == Vector.zero: + return True + return curl(field).simplify() == Vector.zero + + +def is_solenoidal(field): + """ + Checks if a field is solenoidal. + + Parameters + ========== + + field : Vector + The field to check for solenoidal property + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> from sympy.vector import is_solenoidal + >>> R = CoordSys3D('R') + >>> is_solenoidal(R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k) + True + >>> is_solenoidal(R.y * R.j) + False + + """ + + # Field is solenoidal irrespective of system + # Take the first coordinate system in the result of the + # separate method in Vector + if not isinstance(field, Vector): + raise TypeError("field should be a Vector") + if field == Vector.zero: + return True + return divergence(field).simplify() is S.Zero + + +def scalar_potential(field, coord_sys): + """ + Returns the scalar potential function of a field in a given + coordinate system (without the added integration constant). + + Parameters + ========== + + field : Vector + The vector field whose scalar potential function is to be + calculated + + coord_sys : CoordSys3D + The coordinate system to do the calculation in + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> from sympy.vector import scalar_potential, gradient + >>> R = CoordSys3D('R') + >>> scalar_potential(R.k, R) == R.z + True + >>> scalar_field = 2*R.x**2*R.y*R.z + >>> grad_field = gradient(scalar_field) + >>> scalar_potential(grad_field, R) + 2*R.x**2*R.y*R.z + + """ + + # Check whether field is conservative + if not is_conservative(field): + raise ValueError("Field is not conservative") + if field == Vector.zero: + return S.Zero + # Express the field exntirely in coord_sys + # Substitute coordinate variables also + if not isinstance(coord_sys, CoordSys3D): + raise TypeError("coord_sys must be a CoordSys3D") + field = express(field, coord_sys, variables=True) + dimensions = coord_sys.base_vectors() + scalars = coord_sys.base_scalars() + # Calculate scalar potential function + temp_function = integrate(field.dot(dimensions[0]), scalars[0]) + for i, dim in enumerate(dimensions[1:]): + partial_diff = diff(temp_function, scalars[i + 1]) + partial_diff = field.dot(dim) - partial_diff + temp_function += integrate(partial_diff, scalars[i + 1]) + return temp_function + + +def scalar_potential_difference(field, coord_sys, point1, point2): + """ + Returns the scalar potential difference between two points in a + certain coordinate system, wrt a given field. + + If a scalar field is provided, its values at the two points are + considered. If a conservative vector field is provided, the values + of its scalar potential function at the two points are used. + + Returns (potential at point2) - (potential at point1) + + The position vectors of the two Points are calculated wrt the + origin of the coordinate system provided. + + Parameters + ========== + + field : Vector/Expr + The field to calculate wrt + + coord_sys : CoordSys3D + The coordinate system to do the calculations in + + point1 : Point + The initial Point in given coordinate system + + position2 : Point + The second Point in the given coordinate system + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> from sympy.vector import scalar_potential_difference + >>> R = CoordSys3D('R') + >>> P = R.origin.locate_new('P', R.x*R.i + R.y*R.j + R.z*R.k) + >>> vectfield = 4*R.x*R.y*R.i + 2*R.x**2*R.j + >>> scalar_potential_difference(vectfield, R, R.origin, P) + 2*R.x**2*R.y + >>> Q = R.origin.locate_new('O', 3*R.i + R.j + 2*R.k) + >>> scalar_potential_difference(vectfield, R, P, Q) + -2*R.x**2*R.y + 18 + + """ + + if not isinstance(coord_sys, CoordSys3D): + raise TypeError("coord_sys must be a CoordSys3D") + if isinstance(field, Vector): + # Get the scalar potential function + scalar_fn = scalar_potential(field, coord_sys) + else: + # Field is a scalar + scalar_fn = field + # Express positions in required coordinate system + origin = coord_sys.origin + position1 = express(point1.position_wrt(origin), coord_sys, + variables=True) + position2 = express(point2.position_wrt(origin), coord_sys, + variables=True) + # Get the two positions as substitution dicts for coordinate variables + subs_dict1 = {} + subs_dict2 = {} + scalars = coord_sys.base_scalars() + for i, x in enumerate(coord_sys.base_vectors()): + subs_dict1[scalars[i]] = x.dot(position1) + subs_dict2[scalars[i]] = x.dot(position2) + return scalar_fn.subs(subs_dict2) - scalar_fn.subs(subs_dict1) + + +def matrix_to_vector(matrix, system): + """ + Converts a vector in matrix form to a Vector instance. + + It is assumed that the elements of the Matrix represent the + measure numbers of the components of the vector along basis + vectors of 'system'. + + Parameters + ========== + + matrix : SymPy Matrix, Dimensions: (3, 1) + The matrix to be converted to a vector + + system : CoordSys3D + The coordinate system the vector is to be defined in + + Examples + ======== + + >>> from sympy import ImmutableMatrix as Matrix + >>> m = Matrix([1, 2, 3]) + >>> from sympy.vector import CoordSys3D, matrix_to_vector + >>> C = CoordSys3D('C') + >>> v = matrix_to_vector(m, C) + >>> v + C.i + 2*C.j + 3*C.k + >>> v.to_matrix(C) == m + True + + """ + + outvec = Vector.zero + vects = system.base_vectors() + for i, x in enumerate(matrix): + outvec += x * vects[i] + return outvec + + +def _path(from_object, to_object): + """ + Calculates the 'path' of objects starting from 'from_object' + to 'to_object', along with the index of the first common + ancestor in the tree. + + Returns (index, list) tuple. + """ + + if from_object._root != to_object._root: + raise ValueError("No connecting path found between " + + str(from_object) + " and " + str(to_object)) + + other_path = [] + obj = to_object + while obj._parent is not None: + other_path.append(obj) + obj = obj._parent + other_path.append(obj) + object_set = set(other_path) + from_path = [] + obj = from_object + while obj not in object_set: + from_path.append(obj) + obj = obj._parent + index = len(from_path) + from_path.extend(other_path[other_path.index(obj)::-1]) + return index, from_path + + +def orthogonalize(*vlist, orthonormal=False): + """ + Takes a sequence of independent vectors and orthogonalizes them + using the Gram - Schmidt process. Returns a list of + orthogonal or orthonormal vectors. + + Parameters + ========== + + vlist : sequence of independent vectors to be made orthogonal. + + orthonormal : Optional parameter + Set to True if the vectors returned should be + orthonormal. + Default: False + + Examples + ======== + + >>> from sympy.vector.coordsysrect import CoordSys3D + >>> from sympy.vector.functions import orthogonalize + >>> C = CoordSys3D('C') + >>> i, j, k = C.base_vectors() + >>> v1 = i + 2*j + >>> v2 = 2*i + 3*j + >>> orthogonalize(v1, v2) + [C.i + 2*C.j, 2/5*C.i + (-1/5)*C.j] + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Gram-Schmidt_process + + """ + + if not all(isinstance(vec, Vector) for vec in vlist): + raise TypeError('Each element must be of Type Vector') + + ortho_vlist = [] + for i, term in enumerate(vlist): + for j in range(i): + term -= ortho_vlist[j].projection(vlist[i]) + # TODO : The following line introduces a performance issue + # and needs to be changed once a good solution for issue #10279 is + # found. + if term.equals(Vector.zero): + raise ValueError("Vector set not linearly independent") + ortho_vlist.append(term) + + if orthonormal: + ortho_vlist = [vec.normalize() for vec in ortho_vlist] + + return ortho_vlist diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/implicitregion.py b/.venv/lib/python3.12/site-packages/sympy/vector/implicitregion.py new file mode 100644 index 0000000000000000000000000000000000000000..ed2d55a1be8b1eaca71d08b632a94886a2b0269c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/implicitregion.py @@ -0,0 +1,506 @@ +from sympy.core.numbers import Rational +from sympy.core.singleton import S +from sympy.core.symbol import symbols +from sympy.functions.elementary.complexes import sign +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.polys.polytools import gcd +from sympy.sets.sets import Complement +from sympy.core import Basic, Tuple, diff, expand, Eq, Integer +from sympy.core.sorting import ordered +from sympy.core.symbol import _symbol +from sympy.solvers import solveset, nonlinsolve, diophantine +from sympy.polys import total_degree +from sympy.geometry import Point +from sympy.ntheory.factor_ import core + + +class ImplicitRegion(Basic): + """ + Represents an implicit region in space. + + Examples + ======== + + >>> from sympy import Eq + >>> from sympy.abc import x, y, z, t + >>> from sympy.vector import ImplicitRegion + + >>> ImplicitRegion((x, y), x**2 + y**2 - 4) + ImplicitRegion((x, y), x**2 + y**2 - 4) + >>> ImplicitRegion((x, y), Eq(y*x, 1)) + ImplicitRegion((x, y), x*y - 1) + + >>> parabola = ImplicitRegion((x, y), y**2 - 4*x) + >>> parabola.degree + 2 + >>> parabola.equation + -4*x + y**2 + >>> parabola.rational_parametrization(t) + (4/t**2, 4/t) + + >>> r = ImplicitRegion((x, y, z), Eq(z, x**2 + y**2)) + >>> r.variables + (x, y, z) + >>> r.singular_points() + EmptySet + >>> r.regular_point() + (-10, -10, 200) + + Parameters + ========== + + variables : tuple to map variables in implicit equation to base scalars. + + equation : An expression or Eq denoting the implicit equation of the region. + + """ + def __new__(cls, variables, equation): + if not isinstance(variables, Tuple): + variables = Tuple(*variables) + + if isinstance(equation, Eq): + equation = equation.lhs - equation.rhs + + return super().__new__(cls, variables, equation) + + @property + def variables(self): + return self.args[0] + + @property + def equation(self): + return self.args[1] + + @property + def degree(self): + return total_degree(self.equation) + + def regular_point(self): + """ + Returns a point on the implicit region. + + Examples + ======== + + >>> from sympy.abc import x, y, z + >>> from sympy.vector import ImplicitRegion + >>> circle = ImplicitRegion((x, y), (x + 2)**2 + (y - 3)**2 - 16) + >>> circle.regular_point() + (-2, -1) + >>> parabola = ImplicitRegion((x, y), x**2 - 4*y) + >>> parabola.regular_point() + (0, 0) + >>> r = ImplicitRegion((x, y, z), (x + y + z)**4) + >>> r.regular_point() + (-10, -10, 20) + + References + ========== + + - Erik Hillgarter, "Rational Points on Conics", Diploma Thesis, RISC-Linz, + J. Kepler Universitat Linz, 1996. Available: + https://www3.risc.jku.at/publications/download/risc_1355/Rational%20Points%20on%20Conics.pdf + + """ + equation = self.equation + + if len(self.variables) == 1: + return (list(solveset(equation, self.variables[0], domain=S.Reals))[0],) + elif len(self.variables) == 2: + + if self.degree == 2: + coeffs = a, b, c, d, e, f = conic_coeff(self.variables, equation) + + if b**2 == 4*a*c: + x_reg, y_reg = self._regular_point_parabola(*coeffs) + else: + x_reg, y_reg = self._regular_point_ellipse(*coeffs) + return x_reg, y_reg + + if len(self.variables) == 3: + x, y, z = self.variables + + for x_reg in range(-10, 10): + for y_reg in range(-10, 10): + if not solveset(equation.subs({x: x_reg, y: y_reg}), self.variables[2], domain=S.Reals).is_empty: + return (x_reg, y_reg, list(solveset(equation.subs({x: x_reg, y: y_reg})))[0]) + + if len(self.singular_points()) != 0: + return list[self.singular_points()][0] + + raise NotImplementedError() + + def _regular_point_parabola(self, a, b, c, d, e, f): + ok = (a, d) != (0, 0) and (c, e) != (0, 0) and b**2 == 4*a*c and (a, c) != (0, 0) + + if not ok: + raise ValueError("Rational Point on the conic does not exist") + + if a != 0: + d_dash, f_dash = (4*a*e - 2*b*d, 4*a*f - d**2) + if d_dash != 0: + y_reg = -f_dash/d_dash + x_reg = -(d + b*y_reg)/(2*a) + else: + ok = False + elif c != 0: + d_dash, f_dash = (4*c*d - 2*b*e, 4*c*f - e**2) + if d_dash != 0: + x_reg = -f_dash/d_dash + y_reg = -(e + b*x_reg)/(2*c) + else: + ok = False + + if ok: + return x_reg, y_reg + else: + raise ValueError("Rational Point on the conic does not exist") + + def _regular_point_ellipse(self, a, b, c, d, e, f): + D = 4*a*c - b**2 + ok = D + + if not ok: + raise ValueError("Rational Point on the conic does not exist") + + if a == 0 and c == 0: + K = -1 + L = 4*(d*e - b*f) + elif c != 0: + K = D + L = 4*c**2*d**2 - 4*b*c*d*e + 4*a*c*e**2 + 4*b**2*c*f - 16*a*c**2*f + else: + K = D + L = 4*a**2*e**2 - 4*b*a*d*e + 4*b**2*a*f + + ok = L != 0 and not(K > 0 and L < 0) + if not ok: + raise ValueError("Rational Point on the conic does not exist") + + K = Rational(K).limit_denominator(10**12) + L = Rational(L).limit_denominator(10**12) + + k1, k2 = K.p, K.q + l1, l2 = L.p, L.q + g = gcd(k2, l2) + + a1 = (l2*k2)/g + b1 = (k1*l2)/g + c1 = -(l1*k2)/g + a2 = sign(a1)*core(abs(a1), 2) + r1 = sqrt(a1/a2) + b2 = sign(b1)*core(abs(b1), 2) + r2 = sqrt(b1/b2) + c2 = sign(c1)*core(abs(c1), 2) + r3 = sqrt(c1/c2) + + g = gcd(gcd(a2, b2), c2) + a2 = a2/g + b2 = b2/g + c2 = c2/g + + g1 = gcd(a2, b2) + a2 = a2/g1 + b2 = b2/g1 + c2 = c2*g1 + + g2 = gcd(a2,c2) + a2 = a2/g2 + b2 = b2*g2 + c2 = c2/g2 + + g3 = gcd(b2, c2) + a2 = a2*g3 + b2 = b2/g3 + c2 = c2/g3 + + x, y, z = symbols("x y z") + eq = a2*x**2 + b2*y**2 + c2*z**2 + + solutions = diophantine(eq) + + if len(solutions) == 0: + raise ValueError("Rational Point on the conic does not exist") + + flag = False + for sol in solutions: + syms = Tuple(*sol).free_symbols + rep = dict.fromkeys(syms, 3) + sol_z = sol[2] + + if sol_z == 0: + flag = True + continue + + if not isinstance(sol_z, (int, Integer)): + syms_z = sol_z.free_symbols + + if len(syms_z) == 1: + p = next(iter(syms_z)) + p_values = Complement(S.Integers, solveset(Eq(sol_z, 0), p, S.Integers)) + rep[p] = next(iter(p_values)) + + if len(syms_z) == 2: + p, q = list(ordered(syms_z)) + + for i in S.Integers: + subs_sol_z = sol_z.subs(p, i) + q_values = Complement(S.Integers, solveset(Eq(subs_sol_z, 0), q, S.Integers)) + + if not q_values.is_empty: + rep[p] = i + rep[q] = next(iter(q_values)) + break + + if len(syms) != 0: + x, y, z = tuple(s.subs(rep) for s in sol) + else: + x, y, z = sol + flag = False + break + + if flag: + raise ValueError("Rational Point on the conic does not exist") + + x = (x*g3)/r1 + y = (y*g2)/r2 + z = (z*g1)/r3 + x = x/z + y = y/z + + if a == 0 and c == 0: + x_reg = (x + y - 2*e)/(2*b) + y_reg = (x - y - 2*d)/(2*b) + elif c != 0: + x_reg = (x - 2*d*c + b*e)/K + y_reg = (y - b*x_reg - e)/(2*c) + else: + y_reg = (x - 2*e*a + b*d)/K + x_reg = (y - b*y_reg - d)/(2*a) + + return x_reg, y_reg + + def singular_points(self): + """ + Returns a set of singular points of the region. + + The singular points are those points on the region + where all partial derivatives vanish. + + Examples + ======== + + >>> from sympy.abc import x, y + >>> from sympy.vector import ImplicitRegion + >>> I = ImplicitRegion((x, y), (y-1)**2 -x**3 + 2*x**2 -x) + >>> I.singular_points() + {(1, 1)} + + """ + eq_list = [self.equation] + for var in self.variables: + eq_list += [diff(self.equation, var)] + + return nonlinsolve(eq_list, list(self.variables)) + + def multiplicity(self, point): + """ + Returns the multiplicity of a singular point on the region. + + A singular point (x,y) of region is said to be of multiplicity m + if all the partial derivatives off to order m - 1 vanish there. + + Examples + ======== + + >>> from sympy.abc import x, y, z + >>> from sympy.vector import ImplicitRegion + >>> I = ImplicitRegion((x, y, z), x**2 + y**3 - z**4) + >>> I.singular_points() + {(0, 0, 0)} + >>> I.multiplicity((0, 0, 0)) + 2 + + """ + if isinstance(point, Point): + point = point.args + + modified_eq = self.equation + + for i, var in enumerate(self.variables): + modified_eq = modified_eq.subs(var, var + point[i]) + modified_eq = expand(modified_eq) + + if len(modified_eq.args) != 0: + terms = modified_eq.args + m = min(total_degree(term) for term in terms) + else: + terms = modified_eq + m = total_degree(terms) + + return m + + def rational_parametrization(self, parameters=('t', 's'), reg_point=None): + """ + Returns the rational parametrization of implicit region. + + Examples + ======== + + >>> from sympy import Eq + >>> from sympy.abc import x, y, z, s, t + >>> from sympy.vector import ImplicitRegion + + >>> parabola = ImplicitRegion((x, y), y**2 - 4*x) + >>> parabola.rational_parametrization() + (4/t**2, 4/t) + + >>> circle = ImplicitRegion((x, y), Eq(x**2 + y**2, 4)) + >>> circle.rational_parametrization() + (4*t/(t**2 + 1), 4*t**2/(t**2 + 1) - 2) + + >>> I = ImplicitRegion((x, y), x**3 + x**2 - y**2) + >>> I.rational_parametrization() + (t**2 - 1, t*(t**2 - 1)) + + >>> cubic_curve = ImplicitRegion((x, y), x**3 + x**2 - y**2) + >>> cubic_curve.rational_parametrization(parameters=(t)) + (t**2 - 1, t*(t**2 - 1)) + + >>> sphere = ImplicitRegion((x, y, z), x**2 + y**2 + z**2 - 4) + >>> sphere.rational_parametrization(parameters=(t, s)) + (-2 + 4/(s**2 + t**2 + 1), 4*s/(s**2 + t**2 + 1), 4*t/(s**2 + t**2 + 1)) + + For some conics, regular_points() is unable to find a point on curve. + To calulcate the parametric representation in such cases, user need + to determine a point on the region and pass it using reg_point. + + >>> c = ImplicitRegion((x, y), (x - 1/2)**2 + (y)**2 - (1/4)**2) + >>> c.rational_parametrization(reg_point=(3/4, 0)) + (0.75 - 0.5/(t**2 + 1), -0.5*t/(t**2 + 1)) + + References + ========== + + - Christoph M. Hoffmann, "Conversion Methods between Parametric and + Implicit Curves and Surfaces", Purdue e-Pubs, 1990. Available: + https://docs.lib.purdue.edu/cgi/viewcontent.cgi?article=1827&context=cstech + + """ + equation = self.equation + degree = self.degree + + if degree == 1: + if len(self.variables) == 1: + return (equation,) + elif len(self.variables) == 2: + x, y = self.variables + y_par = list(solveset(equation, y))[0] + return x, y_par + else: + raise NotImplementedError() + + point = () + + # Finding the (n - 1) fold point of the monoid of degree + if degree == 2: + # For degree 2 curves, either a regular point or a singular point can be used. + if reg_point is not None: + # Using point provided by the user as regular point + point = reg_point + else: + if len(self.singular_points()) != 0: + point = list(self.singular_points())[0] + else: + point = self.regular_point() + + if len(self.singular_points()) != 0: + singular_points = self.singular_points() + for spoint in singular_points: + syms = Tuple(*spoint).free_symbols + rep = dict.fromkeys(syms, 2) + + if len(syms) != 0: + spoint = tuple(s.subs(rep) for s in spoint) + + if self.multiplicity(spoint) == degree - 1: + point = spoint + break + + if len(point) == 0: + # The region in not a monoid + raise NotImplementedError() + + modified_eq = equation + + # Shifting the region such that fold point moves to origin + for i, var in enumerate(self.variables): + modified_eq = modified_eq.subs(var, var + point[i]) + modified_eq = expand(modified_eq) + + hn = hn_1 = 0 + for term in modified_eq.args: + if total_degree(term) == degree: + hn += term + else: + hn_1 += term + + hn_1 = -1*hn_1 + + if not isinstance(parameters, tuple): + parameters = (parameters,) + + if len(self.variables) == 2: + + parameter1 = parameters[0] + if parameter1 == 's': + # To avoid name conflict between parameters + s = _symbol('s_', real=True) + else: + s = _symbol('s', real=True) + t = _symbol(parameter1, real=True) + + hn = hn.subs({self.variables[0]: s, self.variables[1]: t}) + hn_1 = hn_1.subs({self.variables[0]: s, self.variables[1]: t}) + + x_par = (s*(hn_1/hn)).subs(s, 1) + point[0] + y_par = (t*(hn_1/hn)).subs(s, 1) + point[1] + + return x_par, y_par + + elif len(self.variables) == 3: + + parameter1, parameter2 = parameters + if 'r' in parameters: + # To avoid name conflict between parameters + r = _symbol('r_', real=True) + else: + r = _symbol('r', real=True) + s = _symbol(parameter2, real=True) + t = _symbol(parameter1, real=True) + + hn = hn.subs({self.variables[0]: r, self.variables[1]: s, self.variables[2]: t}) + hn_1 = hn_1.subs({self.variables[0]: r, self.variables[1]: s, self.variables[2]: t}) + + x_par = (r*(hn_1/hn)).subs(r, 1) + point[0] + y_par = (s*(hn_1/hn)).subs(r, 1) + point[1] + z_par = (t*(hn_1/hn)).subs(r, 1) + point[2] + + return x_par, y_par, z_par + + raise NotImplementedError() + +def conic_coeff(variables, equation): + if total_degree(equation) != 2: + raise ValueError() + x = variables[0] + y = variables[1] + + equation = expand(equation) + a = equation.coeff(x**2) + b = equation.coeff(x*y) + c = equation.coeff(y**2) + d = equation.coeff(x, 1).coeff(y, 0) + e = equation.coeff(y, 1).coeff(x, 0) + f = equation.coeff(x, 0).coeff(y, 0) + return a, b, c, d, e, f diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/integrals.py b/.venv/lib/python3.12/site-packages/sympy/vector/integrals.py new file mode 100644 index 0000000000000000000000000000000000000000..a6451c182f214b20b1105eb0a4dc243455c9d126 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/integrals.py @@ -0,0 +1,206 @@ +from sympy.core import Basic, diff +from sympy.core.singleton import S +from sympy.core.sorting import default_sort_key +from sympy.matrices import Matrix +from sympy.integrals import Integral, integrate +from sympy.geometry.entity import GeometryEntity +from sympy.simplify.simplify import simplify +from sympy.utilities.iterables import topological_sort +from sympy.vector import (CoordSys3D, Vector, ParametricRegion, + parametric_region_list, ImplicitRegion) +from sympy.vector.operators import _get_coord_systems + + +class ParametricIntegral(Basic): + """ + Represents integral of a scalar or vector field + over a Parametric Region + + Examples + ======== + + >>> from sympy import cos, sin, pi + >>> from sympy.vector import CoordSys3D, ParametricRegion, ParametricIntegral + >>> from sympy.abc import r, t, theta, phi + + >>> C = CoordSys3D('C') + >>> curve = ParametricRegion((3*t - 2, t + 1), (t, 1, 2)) + >>> ParametricIntegral(C.x, curve) + 5*sqrt(10)/2 + >>> length = ParametricIntegral(1, curve) + >>> length + sqrt(10) + >>> semisphere = ParametricRegion((2*sin(phi)*cos(theta), 2*sin(phi)*sin(theta), 2*cos(phi)),\ + (theta, 0, 2*pi), (phi, 0, pi/2)) + >>> ParametricIntegral(C.z, semisphere) + 8*pi + + >>> ParametricIntegral(C.j + C.k, ParametricRegion((r*cos(theta), r*sin(theta)), r, theta)) + 0 + + """ + + def __new__(cls, field, parametricregion): + + coord_set = _get_coord_systems(field) + + if len(coord_set) == 0: + coord_sys = CoordSys3D('C') + elif len(coord_set) > 1: + raise ValueError + else: + coord_sys = next(iter(coord_set)) + + if parametricregion.dimensions == 0: + return S.Zero + + base_vectors = coord_sys.base_vectors() + base_scalars = coord_sys.base_scalars() + + parametricfield = field + + r = Vector.zero + for i in range(len(parametricregion.definition)): + r += base_vectors[i]*parametricregion.definition[i] + + if len(coord_set) != 0: + for i in range(len(parametricregion.definition)): + parametricfield = parametricfield.subs(base_scalars[i], parametricregion.definition[i]) + + if parametricregion.dimensions == 1: + parameter = parametricregion.parameters[0] + + r_diff = diff(r, parameter) + lower, upper = parametricregion.limits[parameter][0], parametricregion.limits[parameter][1] + + if isinstance(parametricfield, Vector): + integrand = simplify(r_diff.dot(parametricfield)) + else: + integrand = simplify(r_diff.magnitude()*parametricfield) + + result = integrate(integrand, (parameter, lower, upper)) + + elif parametricregion.dimensions == 2: + u, v = cls._bounds_case(parametricregion.parameters, parametricregion.limits) + + r_u = diff(r, u) + r_v = diff(r, v) + normal_vector = simplify(r_u.cross(r_v)) + + if isinstance(parametricfield, Vector): + integrand = parametricfield.dot(normal_vector) + else: + integrand = parametricfield*normal_vector.magnitude() + + integrand = simplify(integrand) + + lower_u, upper_u = parametricregion.limits[u][0], parametricregion.limits[u][1] + lower_v, upper_v = parametricregion.limits[v][0], parametricregion.limits[v][1] + + result = integrate(integrand, (u, lower_u, upper_u), (v, lower_v, upper_v)) + + else: + variables = cls._bounds_case(parametricregion.parameters, parametricregion.limits) + coeff = Matrix(parametricregion.definition).jacobian(variables).det() + integrand = simplify(parametricfield*coeff) + + l = [(var, parametricregion.limits[var][0], parametricregion.limits[var][1]) for var in variables] + result = integrate(integrand, *l) + + if not isinstance(result, Integral): + return result + else: + return super().__new__(cls, field, parametricregion) + + @classmethod + def _bounds_case(cls, parameters, limits): + + V = list(limits.keys()) + E = [] + + for p in V: + lower_p = limits[p][0] + upper_p = limits[p][1] + + lower_p = lower_p.atoms() + upper_p = upper_p.atoms() + E.extend((p, q) for q in V if p != q and + (lower_p.issuperset({q}) or upper_p.issuperset({q}))) + + if not E: + return parameters + else: + return topological_sort((V, E), key=default_sort_key) + + @property + def field(self): + return self.args[0] + + @property + def parametricregion(self): + return self.args[1] + + +def vector_integrate(field, *region): + """ + Compute the integral of a vector/scalar field + over a a region or a set of parameters. + + Examples + ======== + >>> from sympy.vector import CoordSys3D, ParametricRegion, vector_integrate + >>> from sympy.abc import x, y, t + >>> C = CoordSys3D('C') + + >>> region = ParametricRegion((t, t**2), (t, 1, 5)) + >>> vector_integrate(C.x*C.i, region) + 12 + + Integrals over some objects of geometry module can also be calculated. + + >>> from sympy.geometry import Point, Circle, Triangle + >>> c = Circle(Point(0, 2), 5) + >>> vector_integrate(C.x**2 + C.y**2, c) + 290*pi + >>> triangle = Triangle(Point(-2, 3), Point(2, 3), Point(0, 5)) + >>> vector_integrate(3*C.x**2*C.y*C.i + C.j, triangle) + -8 + + Integrals over some simple implicit regions can be computed. But in most cases, + it takes too long to compute over them. This is due to the expressions of parametric + representation becoming large. + + >>> from sympy.vector import ImplicitRegion + >>> c2 = ImplicitRegion((x, y), (x - 2)**2 + (y - 1)**2 - 9) + >>> vector_integrate(1, c2) + 6*pi + + Integral of fields with respect to base scalars: + + >>> vector_integrate(12*C.y**3, (C.y, 1, 3)) + 240 + >>> vector_integrate(C.x**2*C.z, C.x) + C.x**3*C.z/3 + >>> vector_integrate(C.x*C.i - C.y*C.k, C.x) + (Integral(C.x, C.x))*C.i + (Integral(-C.y, C.x))*C.k + >>> _.doit() + C.x**2/2*C.i + (-C.x*C.y)*C.k + + """ + if len(region) == 1: + if isinstance(region[0], ParametricRegion): + return ParametricIntegral(field, region[0]) + + if isinstance(region[0], ImplicitRegion): + region = parametric_region_list(region[0])[0] + return vector_integrate(field, region) + + if isinstance(region[0], GeometryEntity): + regions_list = parametric_region_list(region[0]) + + result = 0 + for reg in regions_list: + result += vector_integrate(field, reg) + return result + + return integrate(field, *region) diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/kind.py b/.venv/lib/python3.12/site-packages/sympy/vector/kind.py new file mode 100644 index 0000000000000000000000000000000000000000..c6c04896b34c9c92c3fb340d94985df859e5877d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/kind.py @@ -0,0 +1,67 @@ +#sympy.vector.kind + +from sympy.core.kind import Kind, _NumberKind, NumberKind +from sympy.core.mul import Mul + +class VectorKind(Kind): + """ + Kind for all vector objects in SymPy. + + Parameters + ========== + + element_kind : Kind + Kind of the element. Default is + :class:`sympy.core.kind.NumberKind`, + which means that the vector contains only numbers. + + Examples + ======== + + Any instance of Vector class has kind ``VectorKind``: + + >>> from sympy.vector.coordsysrect import CoordSys3D + >>> Sys = CoordSys3D('Sys') + >>> Sys.i.kind + VectorKind(NumberKind) + + Operations between instances of Vector keep also have the kind ``VectorKind``: + + >>> from sympy.core.add import Add + >>> v1 = Sys.i * 2 + Sys.j * 3 + Sys.k * 4 + >>> v2 = Sys.i * Sys.x + Sys.j * Sys.y + Sys.k * Sys.z + >>> v1.kind + VectorKind(NumberKind) + >>> v2.kind + VectorKind(NumberKind) + >>> Add(v1, v2).kind + VectorKind(NumberKind) + + Subclasses of Vector also have the kind ``VectorKind``, such as + Cross, VectorAdd, VectorMul or VectorZero. + + See Also + ======== + + sympy.core.kind.Kind + sympy.matrices.kind.MatrixKind + + """ + def __new__(cls, element_kind=NumberKind): + obj = super().__new__(cls, element_kind) + obj.element_kind = element_kind + return obj + + def __repr__(self): + return "VectorKind(%s)" % self.element_kind + +@Mul._kind_dispatcher.register(_NumberKind, VectorKind) +def num_vec_mul(k1, k2): + """ + The result of a multiplication between a number and a Vector should be of VectorKind. + The element kind is selected by recursive dispatching. + """ + if not isinstance(k2, VectorKind): + k1, k2 = k2, k1 + elemk = Mul._kind_dispatcher(k1, k2.element_kind) + return VectorKind(elemk) diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/operators.py b/.venv/lib/python3.12/site-packages/sympy/vector/operators.py new file mode 100644 index 0000000000000000000000000000000000000000..3ca42d20302f972cef66e0b4a35ac75606b2da94 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/operators.py @@ -0,0 +1,335 @@ +import collections +from sympy.core.expr import Expr +from sympy.core import sympify, S, preorder_traversal +from sympy.vector.coordsysrect import CoordSys3D +from sympy.vector.vector import Vector, VectorMul, VectorAdd, Cross, Dot +from sympy.core.function import Derivative +from sympy.core.add import Add +from sympy.core.mul import Mul + + +def _get_coord_systems(expr): + g = preorder_traversal(expr) + ret = set() + for i in g: + if isinstance(i, CoordSys3D): + ret.add(i) + g.skip() + return frozenset(ret) + + +def _split_mul_args_wrt_coordsys(expr): + d = collections.defaultdict(lambda: S.One) + for i in expr.args: + d[_get_coord_systems(i)] *= i + return list(d.values()) + + +class Gradient(Expr): + """ + Represents unevaluated Gradient. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D, Gradient + >>> R = CoordSys3D('R') + >>> s = R.x*R.y*R.z + >>> Gradient(s) + Gradient(R.x*R.y*R.z) + + """ + + def __new__(cls, expr): + expr = sympify(expr) + obj = Expr.__new__(cls, expr) + obj._expr = expr + return obj + + def doit(self, **hints): + return gradient(self._expr, doit=True) + + +class Divergence(Expr): + """ + Represents unevaluated Divergence. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D, Divergence + >>> R = CoordSys3D('R') + >>> v = R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k + >>> Divergence(v) + Divergence(R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k) + + """ + + def __new__(cls, expr): + expr = sympify(expr) + obj = Expr.__new__(cls, expr) + obj._expr = expr + return obj + + def doit(self, **hints): + return divergence(self._expr, doit=True) + + +class Curl(Expr): + """ + Represents unevaluated Curl. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D, Curl + >>> R = CoordSys3D('R') + >>> v = R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k + >>> Curl(v) + Curl(R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k) + + """ + + def __new__(cls, expr): + expr = sympify(expr) + obj = Expr.__new__(cls, expr) + obj._expr = expr + return obj + + def doit(self, **hints): + return curl(self._expr, doit=True) + + +def curl(vect, doit=True): + """ + Returns the curl of a vector field computed wrt the base scalars + of the given coordinate system. + + Parameters + ========== + + vect : Vector + The vector operand + + doit : bool + If True, the result is returned after calling .doit() on + each component. Else, the returned expression contains + Derivative instances + + Examples + ======== + + >>> from sympy.vector import CoordSys3D, curl + >>> R = CoordSys3D('R') + >>> v1 = R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k + >>> curl(v1) + 0 + >>> v2 = R.x*R.y*R.z*R.i + >>> curl(v2) + R.x*R.y*R.j + (-R.x*R.z)*R.k + + """ + + coord_sys = _get_coord_systems(vect) + + if len(coord_sys) == 0: + return Vector.zero + elif len(coord_sys) == 1: + coord_sys = next(iter(coord_sys)) + i, j, k = coord_sys.base_vectors() + x, y, z = coord_sys.base_scalars() + h1, h2, h3 = coord_sys.lame_coefficients() + vectx = vect.dot(i) + vecty = vect.dot(j) + vectz = vect.dot(k) + outvec = Vector.zero + outvec += (Derivative(vectz * h3, y) - + Derivative(vecty * h2, z)) * i / (h2 * h3) + outvec += (Derivative(vectx * h1, z) - + Derivative(vectz * h3, x)) * j / (h1 * h3) + outvec += (Derivative(vecty * h2, x) - + Derivative(vectx * h1, y)) * k / (h2 * h1) + + if doit: + return outvec.doit() + return outvec + else: + if isinstance(vect, (Add, VectorAdd)): + from sympy.vector import express + try: + cs = next(iter(coord_sys)) + args = [express(i, cs, variables=True) for i in vect.args] + except ValueError: + args = vect.args + return VectorAdd.fromiter(curl(i, doit=doit) for i in args) + elif isinstance(vect, (Mul, VectorMul)): + vector = [i for i in vect.args if isinstance(i, (Vector, Cross, Gradient))][0] + scalar = Mul.fromiter(i for i in vect.args if not isinstance(i, (Vector, Cross, Gradient))) + res = Cross(gradient(scalar), vector).doit() + scalar*curl(vector, doit=doit) + if doit: + return res.doit() + return res + elif isinstance(vect, (Cross, Curl, Gradient)): + return Curl(vect) + else: + raise ValueError("Invalid argument for curl") + + +def divergence(vect, doit=True): + """ + Returns the divergence of a vector field computed wrt the base + scalars of the given coordinate system. + + Parameters + ========== + + vector : Vector + The vector operand + + doit : bool + If True, the result is returned after calling .doit() on + each component. Else, the returned expression contains + Derivative instances + + Examples + ======== + + >>> from sympy.vector import CoordSys3D, divergence + >>> R = CoordSys3D('R') + >>> v1 = R.x*R.y*R.z * (R.i+R.j+R.k) + + >>> divergence(v1) + R.x*R.y + R.x*R.z + R.y*R.z + >>> v2 = 2*R.y*R.z*R.j + >>> divergence(v2) + 2*R.z + + """ + coord_sys = _get_coord_systems(vect) + if len(coord_sys) == 0: + return S.Zero + elif len(coord_sys) == 1: + if isinstance(vect, (Cross, Curl, Gradient)): + return Divergence(vect) + # TODO: is case of many coord systems, this gets a random one: + coord_sys = next(iter(coord_sys)) + i, j, k = coord_sys.base_vectors() + x, y, z = coord_sys.base_scalars() + h1, h2, h3 = coord_sys.lame_coefficients() + vx = _diff_conditional(vect.dot(i), x, h2, h3) \ + / (h1 * h2 * h3) + vy = _diff_conditional(vect.dot(j), y, h3, h1) \ + / (h1 * h2 * h3) + vz = _diff_conditional(vect.dot(k), z, h1, h2) \ + / (h1 * h2 * h3) + res = vx + vy + vz + if doit: + return res.doit() + return res + else: + if isinstance(vect, (Add, VectorAdd)): + return Add.fromiter(divergence(i, doit=doit) for i in vect.args) + elif isinstance(vect, (Mul, VectorMul)): + vector = [i for i in vect.args if isinstance(i, (Vector, Cross, Gradient))][0] + scalar = Mul.fromiter(i for i in vect.args if not isinstance(i, (Vector, Cross, Gradient))) + res = Dot(vector, gradient(scalar)) + scalar*divergence(vector, doit=doit) + if doit: + return res.doit() + return res + elif isinstance(vect, (Cross, Curl, Gradient)): + return Divergence(vect) + else: + raise ValueError("Invalid argument for divergence") + + +def gradient(scalar_field, doit=True): + """ + Returns the vector gradient of a scalar field computed wrt the + base scalars of the given coordinate system. + + Parameters + ========== + + scalar_field : SymPy Expr + The scalar field to compute the gradient of + + doit : bool + If True, the result is returned after calling .doit() on + each component. Else, the returned expression contains + Derivative instances + + Examples + ======== + + >>> from sympy.vector import CoordSys3D, gradient + >>> R = CoordSys3D('R') + >>> s1 = R.x*R.y*R.z + >>> gradient(s1) + R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k + >>> s2 = 5*R.x**2*R.z + >>> gradient(s2) + 10*R.x*R.z*R.i + 5*R.x**2*R.k + + """ + coord_sys = _get_coord_systems(scalar_field) + + if len(coord_sys) == 0: + return Vector.zero + elif len(coord_sys) == 1: + coord_sys = next(iter(coord_sys)) + h1, h2, h3 = coord_sys.lame_coefficients() + i, j, k = coord_sys.base_vectors() + x, y, z = coord_sys.base_scalars() + vx = Derivative(scalar_field, x) / h1 + vy = Derivative(scalar_field, y) / h2 + vz = Derivative(scalar_field, z) / h3 + + if doit: + return (vx * i + vy * j + vz * k).doit() + return vx * i + vy * j + vz * k + else: + if isinstance(scalar_field, (Add, VectorAdd)): + return VectorAdd.fromiter(gradient(i) for i in scalar_field.args) + if isinstance(scalar_field, (Mul, VectorMul)): + s = _split_mul_args_wrt_coordsys(scalar_field) + return VectorAdd.fromiter(scalar_field / i * gradient(i) for i in s) + return Gradient(scalar_field) + + +class Laplacian(Expr): + """ + Represents unevaluated Laplacian. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D, Laplacian + >>> R = CoordSys3D('R') + >>> v = 3*R.x**3*R.y**2*R.z**3 + >>> Laplacian(v) + Laplacian(3*R.x**3*R.y**2*R.z**3) + + """ + + def __new__(cls, expr): + expr = sympify(expr) + obj = Expr.__new__(cls, expr) + obj._expr = expr + return obj + + def doit(self, **hints): + from sympy.vector.functions import laplacian + return laplacian(self._expr) + + +def _diff_conditional(expr, base_scalar, coeff_1, coeff_2): + """ + First re-expresses expr in the system that base_scalar belongs to. + If base_scalar appears in the re-expressed form, differentiates + it wrt base_scalar. + Else, returns 0 + """ + from sympy.vector.functions import express + new_expr = express(expr, base_scalar.system, variables=True) + arg = coeff_1 * coeff_2 * new_expr + return Derivative(arg, base_scalar) if arg else S.Zero diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/orienters.py b/.venv/lib/python3.12/site-packages/sympy/vector/orienters.py new file mode 100644 index 0000000000000000000000000000000000000000..0c22089e568bc817c943c1beecebde0fea46b6ae --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/orienters.py @@ -0,0 +1,398 @@ +from sympy.core.basic import Basic +from sympy.core.sympify import sympify +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.matrices.dense import (eye, rot_axis1, rot_axis2, rot_axis3) +from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix +from sympy.core.cache import cacheit +from sympy.core.symbol import Str +import sympy.vector + + +class Orienter(Basic): + """ + Super-class for all orienter classes. + """ + + def rotation_matrix(self): + """ + The rotation matrix corresponding to this orienter + instance. + """ + return self._parent_orient + + +class AxisOrienter(Orienter): + """ + Class to denote an axis orienter. + """ + + def __new__(cls, angle, axis): + if not isinstance(axis, sympy.vector.Vector): + raise TypeError("axis should be a Vector") + angle = sympify(angle) + + obj = super().__new__(cls, angle, axis) + obj._angle = angle + obj._axis = axis + + return obj + + def __init__(self, angle, axis): + """ + Axis rotation is a rotation about an arbitrary axis by + some angle. The angle is supplied as a SymPy expr scalar, and + the axis is supplied as a Vector. + + Parameters + ========== + + angle : Expr + The angle by which the new system is to be rotated + + axis : Vector + The axis around which the rotation has to be performed + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> from sympy import symbols + >>> q1 = symbols('q1') + >>> N = CoordSys3D('N') + >>> from sympy.vector import AxisOrienter + >>> orienter = AxisOrienter(q1, N.i + 2 * N.j) + >>> B = N.orient_new('B', (orienter, )) + + """ + # Dummy initializer for docstrings + pass + + @cacheit + def rotation_matrix(self, system): + """ + The rotation matrix corresponding to this orienter + instance. + + Parameters + ========== + + system : CoordSys3D + The coordinate system wrt which the rotation matrix + is to be computed + """ + + axis = sympy.vector.express(self.axis, system).normalize() + axis = axis.to_matrix(system) + theta = self.angle + parent_orient = ((eye(3) - axis * axis.T) * cos(theta) + + Matrix([[0, -axis[2], axis[1]], + [axis[2], 0, -axis[0]], + [-axis[1], axis[0], 0]]) * sin(theta) + + axis * axis.T) + parent_orient = parent_orient.T + return parent_orient + + @property + def angle(self): + return self._angle + + @property + def axis(self): + return self._axis + + +class ThreeAngleOrienter(Orienter): + """ + Super-class for Body and Space orienters. + """ + + def __new__(cls, angle1, angle2, angle3, rot_order): + if isinstance(rot_order, Str): + rot_order = rot_order.name + + approved_orders = ('123', '231', '312', '132', '213', + '321', '121', '131', '212', '232', + '313', '323', '') + original_rot_order = rot_order + rot_order = str(rot_order).upper() + if not (len(rot_order) == 3): + raise TypeError('rot_order should be a str of length 3') + rot_order = [i.replace('X', '1') for i in rot_order] + rot_order = [i.replace('Y', '2') for i in rot_order] + rot_order = [i.replace('Z', '3') for i in rot_order] + rot_order = ''.join(rot_order) + if rot_order not in approved_orders: + raise TypeError('Invalid rot_type parameter') + a1 = int(rot_order[0]) + a2 = int(rot_order[1]) + a3 = int(rot_order[2]) + angle1 = sympify(angle1) + angle2 = sympify(angle2) + angle3 = sympify(angle3) + if cls._in_order: + parent_orient = (_rot(a1, angle1) * + _rot(a2, angle2) * + _rot(a3, angle3)) + else: + parent_orient = (_rot(a3, angle3) * + _rot(a2, angle2) * + _rot(a1, angle1)) + parent_orient = parent_orient.T + + obj = super().__new__( + cls, angle1, angle2, angle3, Str(rot_order)) + obj._angle1 = angle1 + obj._angle2 = angle2 + obj._angle3 = angle3 + obj._rot_order = original_rot_order + obj._parent_orient = parent_orient + + return obj + + @property + def angle1(self): + return self._angle1 + + @property + def angle2(self): + return self._angle2 + + @property + def angle3(self): + return self._angle3 + + @property + def rot_order(self): + return self._rot_order + + +class BodyOrienter(ThreeAngleOrienter): + """ + Class to denote a body-orienter. + """ + + _in_order = True + + def __new__(cls, angle1, angle2, angle3, rot_order): + obj = ThreeAngleOrienter.__new__(cls, angle1, angle2, angle3, + rot_order) + return obj + + def __init__(self, angle1, angle2, angle3, rot_order): + """ + Body orientation takes this coordinate system through three + successive simple rotations. + + Body fixed rotations include both Euler Angles and + Tait-Bryan Angles, see https://en.wikipedia.org/wiki/Euler_angles. + + Parameters + ========== + + angle1, angle2, angle3 : Expr + Three successive angles to rotate the coordinate system by + + rotation_order : string + String defining the order of axes for rotation + + Examples + ======== + + >>> from sympy.vector import CoordSys3D, BodyOrienter + >>> from sympy import symbols + >>> q1, q2, q3 = symbols('q1 q2 q3') + >>> N = CoordSys3D('N') + + A 'Body' fixed rotation is described by three angles and + three body-fixed rotation axes. To orient a coordinate system D + with respect to N, each sequential rotation is always about + the orthogonal unit vectors fixed to D. For example, a '123' + rotation will specify rotations about N.i, then D.j, then + D.k. (Initially, D.i is same as N.i) + Therefore, + + >>> body_orienter = BodyOrienter(q1, q2, q3, '123') + >>> D = N.orient_new('D', (body_orienter, )) + + is same as + + >>> from sympy.vector import AxisOrienter + >>> axis_orienter1 = AxisOrienter(q1, N.i) + >>> D = N.orient_new('D', (axis_orienter1, )) + >>> axis_orienter2 = AxisOrienter(q2, D.j) + >>> D = D.orient_new('D', (axis_orienter2, )) + >>> axis_orienter3 = AxisOrienter(q3, D.k) + >>> D = D.orient_new('D', (axis_orienter3, )) + + Acceptable rotation orders are of length 3, expressed in XYZ or + 123, and cannot have a rotation about about an axis twice in a row. + + >>> body_orienter1 = BodyOrienter(q1, q2, q3, '123') + >>> body_orienter2 = BodyOrienter(q1, q2, 0, 'ZXZ') + >>> body_orienter3 = BodyOrienter(0, 0, 0, 'XYX') + + """ + # Dummy initializer for docstrings + pass + + +class SpaceOrienter(ThreeAngleOrienter): + """ + Class to denote a space-orienter. + """ + + _in_order = False + + def __new__(cls, angle1, angle2, angle3, rot_order): + obj = ThreeAngleOrienter.__new__(cls, angle1, angle2, angle3, + rot_order) + return obj + + def __init__(self, angle1, angle2, angle3, rot_order): + """ + Space rotation is similar to Body rotation, but the rotations + are applied in the opposite order. + + Parameters + ========== + + angle1, angle2, angle3 : Expr + Three successive angles to rotate the coordinate system by + + rotation_order : string + String defining the order of axes for rotation + + See Also + ======== + + BodyOrienter : Orienter to orient systems wrt Euler angles. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D, SpaceOrienter + >>> from sympy import symbols + >>> q1, q2, q3 = symbols('q1 q2 q3') + >>> N = CoordSys3D('N') + + To orient a coordinate system D with respect to N, each + sequential rotation is always about N's orthogonal unit vectors. + For example, a '123' rotation will specify rotations about + N.i, then N.j, then N.k. + Therefore, + + >>> space_orienter = SpaceOrienter(q1, q2, q3, '312') + >>> D = N.orient_new('D', (space_orienter, )) + + is same as + + >>> from sympy.vector import AxisOrienter + >>> axis_orienter1 = AxisOrienter(q1, N.i) + >>> B = N.orient_new('B', (axis_orienter1, )) + >>> axis_orienter2 = AxisOrienter(q2, N.j) + >>> C = B.orient_new('C', (axis_orienter2, )) + >>> axis_orienter3 = AxisOrienter(q3, N.k) + >>> D = C.orient_new('C', (axis_orienter3, )) + + """ + # Dummy initializer for docstrings + pass + + +class QuaternionOrienter(Orienter): + """ + Class to denote a quaternion-orienter. + """ + + def __new__(cls, q0, q1, q2, q3): + q0 = sympify(q0) + q1 = sympify(q1) + q2 = sympify(q2) + q3 = sympify(q3) + parent_orient = (Matrix([[q0 ** 2 + q1 ** 2 - q2 ** 2 - + q3 ** 2, + 2 * (q1 * q2 - q0 * q3), + 2 * (q0 * q2 + q1 * q3)], + [2 * (q1 * q2 + q0 * q3), + q0 ** 2 - q1 ** 2 + + q2 ** 2 - q3 ** 2, + 2 * (q2 * q3 - q0 * q1)], + [2 * (q1 * q3 - q0 * q2), + 2 * (q0 * q1 + q2 * q3), + q0 ** 2 - q1 ** 2 - + q2 ** 2 + q3 ** 2]])) + parent_orient = parent_orient.T + + obj = super().__new__(cls, q0, q1, q2, q3) + obj._q0 = q0 + obj._q1 = q1 + obj._q2 = q2 + obj._q3 = q3 + obj._parent_orient = parent_orient + + return obj + + def __init__(self, angle1, angle2, angle3, rot_order): + """ + Quaternion orientation orients the new CoordSys3D with + Quaternions, defined as a finite rotation about lambda, a unit + vector, by some amount theta. + + This orientation is described by four parameters: + + q0 = cos(theta/2) + + q1 = lambda_x sin(theta/2) + + q2 = lambda_y sin(theta/2) + + q3 = lambda_z sin(theta/2) + + Quaternion does not take in a rotation order. + + Parameters + ========== + + q0, q1, q2, q3 : Expr + The quaternions to rotate the coordinate system by + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> from sympy import symbols + >>> q0, q1, q2, q3 = symbols('q0 q1 q2 q3') + >>> N = CoordSys3D('N') + >>> from sympy.vector import QuaternionOrienter + >>> q_orienter = QuaternionOrienter(q0, q1, q2, q3) + >>> B = N.orient_new('B', (q_orienter, )) + + """ + # Dummy initializer for docstrings + pass + + @property + def q0(self): + return self._q0 + + @property + def q1(self): + return self._q1 + + @property + def q2(self): + return self._q2 + + @property + def q3(self): + return self._q3 + + +def _rot(axis, angle): + """DCM for simple axis 1, 2 or 3 rotations. """ + if axis == 1: + return Matrix(rot_axis1(angle).T) + elif axis == 2: + return Matrix(rot_axis2(angle).T) + elif axis == 3: + return Matrix(rot_axis3(angle).T) diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/parametricregion.py b/.venv/lib/python3.12/site-packages/sympy/vector/parametricregion.py new file mode 100644 index 0000000000000000000000000000000000000000..5246769dabe208fe630f7c33b2da3ef4e11b3f67 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/parametricregion.py @@ -0,0 +1,189 @@ +from functools import singledispatch +from sympy.core.numbers import pi +from sympy.functions.elementary.trigonometric import tan +from sympy.simplify import trigsimp +from sympy.core import Basic, Tuple +from sympy.core.symbol import _symbol +from sympy.solvers import solve +from sympy.geometry import Point, Segment, Curve, Ellipse, Polygon +from sympy.vector import ImplicitRegion + + +class ParametricRegion(Basic): + """ + Represents a parametric region in space. + + Examples + ======== + + >>> from sympy import cos, sin, pi + >>> from sympy.abc import r, theta, t, a, b, x, y + >>> from sympy.vector import ParametricRegion + + >>> ParametricRegion((t, t**2), (t, -1, 2)) + ParametricRegion((t, t**2), (t, -1, 2)) + >>> ParametricRegion((x, y), (x, 3, 4), (y, 5, 6)) + ParametricRegion((x, y), (x, 3, 4), (y, 5, 6)) + >>> ParametricRegion((r*cos(theta), r*sin(theta)), (r, -2, 2), (theta, 0, pi)) + ParametricRegion((r*cos(theta), r*sin(theta)), (r, -2, 2), (theta, 0, pi)) + >>> ParametricRegion((a*cos(t), b*sin(t)), t) + ParametricRegion((a*cos(t), b*sin(t)), t) + + >>> circle = ParametricRegion((r*cos(theta), r*sin(theta)), r, (theta, 0, pi)) + >>> circle.parameters + (r, theta) + >>> circle.definition + (r*cos(theta), r*sin(theta)) + >>> circle.limits + {theta: (0, pi)} + + Dimension of a parametric region determines whether a region is a curve, surface + or volume region. It does not represent its dimensions in space. + + >>> circle.dimensions + 1 + + Parameters + ========== + + definition : tuple to define base scalars in terms of parameters. + + bounds : Parameter or a tuple of length 3 to define parameter and corresponding lower and upper bound. + + """ + def __new__(cls, definition, *bounds): + parameters = () + limits = {} + + if not isinstance(bounds, Tuple): + bounds = Tuple(*bounds) + + for bound in bounds: + if isinstance(bound, (tuple, Tuple)): + if len(bound) != 3: + raise ValueError("Tuple should be in the form (parameter, lowerbound, upperbound)") + parameters += (bound[0],) + limits[bound[0]] = (bound[1], bound[2]) + else: + parameters += (bound,) + + if not isinstance(definition, (tuple, Tuple)): + definition = (definition,) + + obj = super().__new__(cls, Tuple(*definition), *bounds) + obj._parameters = parameters + obj._limits = limits + + return obj + + @property + def definition(self): + return self.args[0] + + @property + def limits(self): + return self._limits + + @property + def parameters(self): + return self._parameters + + @property + def dimensions(self): + return len(self.limits) + + +@singledispatch +def parametric_region_list(reg): + """ + Returns a list of ParametricRegion objects representing the geometric region. + + Examples + ======== + + >>> from sympy.abc import t + >>> from sympy.vector import parametric_region_list + >>> from sympy.geometry import Point, Curve, Ellipse, Segment, Polygon + + >>> p = Point(2, 5) + >>> parametric_region_list(p) + [ParametricRegion((2, 5))] + + >>> c = Curve((t**3, 4*t), (t, -3, 4)) + >>> parametric_region_list(c) + [ParametricRegion((t**3, 4*t), (t, -3, 4))] + + >>> e = Ellipse(Point(1, 3), 2, 3) + >>> parametric_region_list(e) + [ParametricRegion((2*cos(t) + 1, 3*sin(t) + 3), (t, 0, 2*pi))] + + >>> s = Segment(Point(1, 3), Point(2, 6)) + >>> parametric_region_list(s) + [ParametricRegion((t + 1, 3*t + 3), (t, 0, 1))] + + >>> p1, p2, p3, p4 = [(0, 1), (2, -3), (5, 3), (-2, 3)] + >>> poly = Polygon(p1, p2, p3, p4) + >>> parametric_region_list(poly) + [ParametricRegion((2*t, 1 - 4*t), (t, 0, 1)), ParametricRegion((3*t + 2, 6*t - 3), (t, 0, 1)),\ + ParametricRegion((5 - 7*t, 3), (t, 0, 1)), ParametricRegion((2*t - 2, 3 - 2*t), (t, 0, 1))] + + """ + raise ValueError("SymPy cannot determine parametric representation of the region.") + + +@parametric_region_list.register(Point) +def _(obj): + return [ParametricRegion(obj.args)] + + +@parametric_region_list.register(Curve) # type: ignore +def _(obj): + definition = obj.arbitrary_point(obj.parameter).args + bounds = obj.limits + return [ParametricRegion(definition, bounds)] + + +@parametric_region_list.register(Ellipse) # type: ignore +def _(obj, parameter='t'): + definition = obj.arbitrary_point(parameter).args + t = _symbol(parameter, real=True) + bounds = (t, 0, 2*pi) + return [ParametricRegion(definition, bounds)] + + +@parametric_region_list.register(Segment) # type: ignore +def _(obj, parameter='t'): + t = _symbol(parameter, real=True) + definition = obj.arbitrary_point(t).args + + for i in range(0, 3): + lower_bound = solve(definition[i] - obj.points[0].args[i], t) + upper_bound = solve(definition[i] - obj.points[1].args[i], t) + + if len(lower_bound) == 1 and len(upper_bound) == 1: + bounds = t, lower_bound[0], upper_bound[0] + break + + definition_tuple = obj.arbitrary_point(parameter).args + return [ParametricRegion(definition_tuple, bounds)] + + +@parametric_region_list.register(Polygon) # type: ignore +def _(obj, parameter='t'): + l = [parametric_region_list(side, parameter)[0] for side in obj.sides] + return l + + +@parametric_region_list.register(ImplicitRegion) # type: ignore +def _(obj, parameters=('t', 's')): + definition = obj.rational_parametrization(parameters) + bounds = [] + + for i in range(len(obj.variables) - 1): + # Each parameter is replaced by its tangent to simplify integration + parameter = _symbol(parameters[i], real=True) + definition = [trigsimp(elem.subs(parameter, tan(parameter/2))) for elem in definition] + bounds.append((parameter, 0, 2*pi),) + + definition = Tuple(*definition) + return [ParametricRegion(definition, *bounds)] diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/point.py b/.venv/lib/python3.12/site-packages/sympy/vector/point.py new file mode 100644 index 0000000000000000000000000000000000000000..442ea4e8edc0e33c4f83f774ea3f11a01725ac3a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/point.py @@ -0,0 +1,148 @@ +from sympy.core.basic import Basic +from sympy.core.symbol import Str +from sympy.vector.vector import Vector +from sympy.vector.coordsysrect import CoordSys3D +from sympy.vector.functions import _path +from sympy.core.cache import cacheit + + +class Point(Basic): + """ + Represents a point in 3-D space. + """ + + def __new__(cls, name, position=Vector.zero, parent_point=None): + name = str(name) + # Check the args first + if not isinstance(position, Vector): + raise TypeError( + "position should be an instance of Vector, not %s" % type( + position)) + if (not isinstance(parent_point, Point) and + parent_point is not None): + raise TypeError( + "parent_point should be an instance of Point, not %s" % type( + parent_point)) + # Super class construction + if parent_point is None: + obj = super().__new__(cls, Str(name), position) + else: + obj = super().__new__(cls, Str(name), position, parent_point) + # Decide the object parameters + obj._name = name + obj._pos = position + if parent_point is None: + obj._parent = None + obj._root = obj + else: + obj._parent = parent_point + obj._root = parent_point._root + # Return object + return obj + + @cacheit + def position_wrt(self, other): + """ + Returns the position vector of this Point with respect to + another Point/CoordSys3D. + + Parameters + ========== + + other : Point/CoordSys3D + If other is a Point, the position of this Point wrt it is + returned. If its an instance of CoordSyRect, the position + wrt its origin is returned. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> N = CoordSys3D('N') + >>> p1 = N.origin.locate_new('p1', 10 * N.i) + >>> N.origin.position_wrt(p1) + (-10)*N.i + + """ + + if (not isinstance(other, Point) and + not isinstance(other, CoordSys3D)): + raise TypeError(str(other) + + "is not a Point or CoordSys3D") + if isinstance(other, CoordSys3D): + other = other.origin + # Handle special cases + if other == self: + return Vector.zero + elif other == self._parent: + return self._pos + elif other._parent == self: + return -1 * other._pos + # Else, use point tree to calculate position + rootindex, path = _path(self, other) + result = Vector.zero + for i in range(rootindex): + result += path[i]._pos + for i in range(rootindex + 1, len(path)): + result -= path[i]._pos + return result + + def locate_new(self, name, position): + """ + Returns a new Point located at the given position wrt this + Point. + Thus, the position vector of the new Point wrt this one will + be equal to the given 'position' parameter. + + Parameters + ========== + + name : str + Name of the new point + + position : Vector + The position vector of the new Point wrt this one + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> N = CoordSys3D('N') + >>> p1 = N.origin.locate_new('p1', 10 * N.i) + >>> p1.position_wrt(N.origin) + 10*N.i + + """ + return Point(name, position, self) + + def express_coordinates(self, coordinate_system): + """ + Returns the Cartesian/rectangular coordinates of this point + wrt the origin of the given CoordSys3D instance. + + Parameters + ========== + + coordinate_system : CoordSys3D + The coordinate system to express the coordinates of this + Point in. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> N = CoordSys3D('N') + >>> p1 = N.origin.locate_new('p1', 10 * N.i) + >>> p2 = p1.locate_new('p2', 5 * N.j) + >>> p2.express_coordinates(N) + (10, 5, 0) + + """ + + # Determine the position vector + pos_vect = self.position_wrt(coordinate_system.origin) + # Express it in the given coordinate system + return tuple(pos_vect.to_matrix(coordinate_system)) + + def _sympystr(self, printer): + return self._name diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/scalar.py b/.venv/lib/python3.12/site-packages/sympy/vector/scalar.py new file mode 100644 index 0000000000000000000000000000000000000000..bcfb56cf177b9378a24f81ca1e6524fe048a5f94 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/scalar.py @@ -0,0 +1,72 @@ +from sympy.core import AtomicExpr, Symbol, S +from sympy.core.sympify import _sympify +from sympy.printing.pretty.stringpict import prettyForm +from sympy.printing.precedence import PRECEDENCE +from sympy.core.kind import NumberKind + + +class BaseScalar(AtomicExpr): + """ + A coordinate symbol/base scalar. + + Ideally, users should not instantiate this class. + + """ + + kind = NumberKind + + def __new__(cls, index, system, pretty_str=None, latex_str=None): + from sympy.vector.coordsysrect import CoordSys3D + if pretty_str is None: + pretty_str = "x{}".format(index) + elif isinstance(pretty_str, Symbol): + pretty_str = pretty_str.name + if latex_str is None: + latex_str = "x_{}".format(index) + elif isinstance(latex_str, Symbol): + latex_str = latex_str.name + + index = _sympify(index) + system = _sympify(system) + obj = super().__new__(cls, index, system) + if not isinstance(system, CoordSys3D): + raise TypeError("system should be a CoordSys3D") + if index not in range(0, 3): + raise ValueError("Invalid index specified.") + # The _id is used for equating purposes, and for hashing + obj._id = (index, system) + obj._name = obj.name = system._name + '.' + system._variable_names[index] + obj._pretty_form = '' + pretty_str + obj._latex_form = latex_str + obj._system = system + + return obj + + is_commutative = True + is_symbol = True + + @property + def free_symbols(self): + return {self} + + _diff_wrt = True + + def _eval_derivative(self, s): + if self == s: + return S.One + return S.Zero + + def _latex(self, printer=None): + return self._latex_form + + def _pretty(self, printer=None): + return prettyForm(self._pretty_form) + + precedence = PRECEDENCE['Atom'] + + @property + def system(self): + return self._system + + def _sympystr(self, printer): + return self._name diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/tests/__init__.py b/.venv/lib/python3.12/site-packages/sympy/vector/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8bc5f63db28bd59f16340dbbe937e38f150d200e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_coordsysrect.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_coordsysrect.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b5c7dcb6ef141766025e145fe598832e0da37f8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_coordsysrect.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_dyadic.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_dyadic.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8975f11af138ab8ef0f6eea44ebc3b08cf1e9b98 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_dyadic.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_field_functions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_field_functions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce2b787765e06670f5c1bc6e0c81543d2aeef1e6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_field_functions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_functions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_functions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3ed91fd22327302429687f032263faf449bee45 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_functions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_implicitregion.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_implicitregion.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2efaf43efebd987dcf5baa278eae3177da57d640 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_implicitregion.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_integrals.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_integrals.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04596ed0b177c216e8fed80bdd31a26752327bd0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_integrals.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_operators.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_operators.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb0735ffc8bfda110ae960c4dad7a118a211c606 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_operators.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_parametricregion.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_parametricregion.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..181af35f254b15bb1e771b765ad654876888d186 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_parametricregion.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_printing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_printing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09cd1e77485231203ce9fd0739fd1d47ac390ab6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_printing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_vector.cpython-312.pyc b/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_vector.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdfba65e84bab763db57bb3d72cd8b8e8842c586 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/sympy/vector/tests/__pycache__/test_vector.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_coordsysrect.py b/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_coordsysrect.py new file mode 100644 index 0000000000000000000000000000000000000000..53eb8c89ec1643a71800efe3e370acff3cb6f9c0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_coordsysrect.py @@ -0,0 +1,464 @@ +from sympy.testing.pytest import raises +from sympy.vector.coordsysrect import CoordSys3D +from sympy.vector.scalar import BaseScalar +from sympy.core.function import expand +from sympy.core.numbers import pi +from sympy.core.symbol import symbols +from sympy.functions.elementary.hyperbolic import (cosh, sinh) +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (acos, atan2, cos, sin) +from sympy.matrices.dense import zeros +from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix +from sympy.simplify.simplify import simplify +from sympy.vector.functions import express +from sympy.vector.point import Point +from sympy.vector.vector import Vector +from sympy.vector.orienters import (AxisOrienter, BodyOrienter, + SpaceOrienter, QuaternionOrienter) + + +x, y, z = symbols('x y z') +a, b, c, q = symbols('a b c q') +q1, q2, q3, q4 = symbols('q1 q2 q3 q4') + + +def test_func_args(): + A = CoordSys3D('A') + assert A.x.func(*A.x.args) == A.x + expr = 3*A.x + 4*A.y + assert expr.func(*expr.args) == expr + assert A.i.func(*A.i.args) == A.i + v = A.x*A.i + A.y*A.j + A.z*A.k + assert v.func(*v.args) == v + assert A.origin.func(*A.origin.args) == A.origin + + +def test_coordsys3d_equivalence(): + A = CoordSys3D('A') + A1 = CoordSys3D('A') + assert A1 == A + B = CoordSys3D('B') + assert A != B + + +def test_orienters(): + A = CoordSys3D('A') + axis_orienter = AxisOrienter(a, A.k) + body_orienter = BodyOrienter(a, b, c, '123') + space_orienter = SpaceOrienter(a, b, c, '123') + q_orienter = QuaternionOrienter(q1, q2, q3, q4) + assert axis_orienter.rotation_matrix(A) == Matrix([ + [ cos(a), sin(a), 0], + [-sin(a), cos(a), 0], + [ 0, 0, 1]]) + assert body_orienter.rotation_matrix() == Matrix([ + [ cos(b)*cos(c), sin(a)*sin(b)*cos(c) + sin(c)*cos(a), + sin(a)*sin(c) - sin(b)*cos(a)*cos(c)], + [-sin(c)*cos(b), -sin(a)*sin(b)*sin(c) + cos(a)*cos(c), + sin(a)*cos(c) + sin(b)*sin(c)*cos(a)], + [ sin(b), -sin(a)*cos(b), + cos(a)*cos(b)]]) + assert space_orienter.rotation_matrix() == Matrix([ + [cos(b)*cos(c), sin(c)*cos(b), -sin(b)], + [sin(a)*sin(b)*cos(c) - sin(c)*cos(a), + sin(a)*sin(b)*sin(c) + cos(a)*cos(c), sin(a)*cos(b)], + [sin(a)*sin(c) + sin(b)*cos(a)*cos(c), -sin(a)*cos(c) + + sin(b)*sin(c)*cos(a), cos(a)*cos(b)]]) + assert q_orienter.rotation_matrix() == Matrix([ + [q1**2 + q2**2 - q3**2 - q4**2, 2*q1*q4 + 2*q2*q3, + -2*q1*q3 + 2*q2*q4], + [-2*q1*q4 + 2*q2*q3, q1**2 - q2**2 + q3**2 - q4**2, + 2*q1*q2 + 2*q3*q4], + [2*q1*q3 + 2*q2*q4, + -2*q1*q2 + 2*q3*q4, q1**2 - q2**2 - q3**2 + q4**2]]) + + +def test_coordinate_vars(): + """ + Tests the coordinate variables functionality with respect to + reorientation of coordinate systems. + """ + A = CoordSys3D('A') + # Note that the name given on the lhs is different from A.x._name + assert BaseScalar(0, A, 'A_x', r'\mathbf{{x}_{A}}') == A.x + assert BaseScalar(1, A, 'A_y', r'\mathbf{{y}_{A}}') == A.y + assert BaseScalar(2, A, 'A_z', r'\mathbf{{z}_{A}}') == A.z + assert BaseScalar(0, A, 'A_x', r'\mathbf{{x}_{A}}').__hash__() == A.x.__hash__() + assert isinstance(A.x, BaseScalar) and \ + isinstance(A.y, BaseScalar) and \ + isinstance(A.z, BaseScalar) + assert A.x*A.y == A.y*A.x + assert A.scalar_map(A) == {A.x: A.x, A.y: A.y, A.z: A.z} + assert A.x.system == A + assert A.x.diff(A.x) == 1 + B = A.orient_new_axis('B', q, A.k) + assert B.scalar_map(A) == {B.z: A.z, B.y: -A.x*sin(q) + A.y*cos(q), + B.x: A.x*cos(q) + A.y*sin(q)} + assert A.scalar_map(B) == {A.x: B.x*cos(q) - B.y*sin(q), + A.y: B.x*sin(q) + B.y*cos(q), A.z: B.z} + assert express(B.x, A, variables=True) == A.x*cos(q) + A.y*sin(q) + assert express(B.y, A, variables=True) == -A.x*sin(q) + A.y*cos(q) + assert express(B.z, A, variables=True) == A.z + assert expand(express(B.x*B.y*B.z, A, variables=True)) == \ + expand(A.z*(-A.x*sin(q) + A.y*cos(q))*(A.x*cos(q) + A.y*sin(q))) + assert express(B.x*B.i + B.y*B.j + B.z*B.k, A) == \ + (B.x*cos(q) - B.y*sin(q))*A.i + (B.x*sin(q) + \ + B.y*cos(q))*A.j + B.z*A.k + assert simplify(express(B.x*B.i + B.y*B.j + B.z*B.k, A, \ + variables=True)) == \ + A.x*A.i + A.y*A.j + A.z*A.k + assert express(A.x*A.i + A.y*A.j + A.z*A.k, B) == \ + (A.x*cos(q) + A.y*sin(q))*B.i + \ + (-A.x*sin(q) + A.y*cos(q))*B.j + A.z*B.k + assert simplify(express(A.x*A.i + A.y*A.j + A.z*A.k, B, \ + variables=True)) == \ + B.x*B.i + B.y*B.j + B.z*B.k + N = B.orient_new_axis('N', -q, B.k) + assert N.scalar_map(A) == \ + {N.x: A.x, N.z: A.z, N.y: A.y} + C = A.orient_new_axis('C', q, A.i + A.j + A.k) + mapping = A.scalar_map(C) + assert mapping[A.x].equals(C.x*(2*cos(q) + 1)/3 + + C.y*(-2*sin(q + pi/6) + 1)/3 + + C.z*(-2*cos(q + pi/3) + 1)/3) + assert mapping[A.y].equals(C.x*(-2*cos(q + pi/3) + 1)/3 + + C.y*(2*cos(q) + 1)/3 + + C.z*(-2*sin(q + pi/6) + 1)/3) + assert mapping[A.z].equals(C.x*(-2*sin(q + pi/6) + 1)/3 + + C.y*(-2*cos(q + pi/3) + 1)/3 + + C.z*(2*cos(q) + 1)/3) + D = A.locate_new('D', a*A.i + b*A.j + c*A.k) + assert D.scalar_map(A) == {D.z: A.z - c, D.x: A.x - a, D.y: A.y - b} + E = A.orient_new_axis('E', a, A.k, a*A.i + b*A.j + c*A.k) + assert A.scalar_map(E) == {A.z: E.z + c, + A.x: E.x*cos(a) - E.y*sin(a) + a, + A.y: E.x*sin(a) + E.y*cos(a) + b} + assert E.scalar_map(A) == {E.x: (A.x - a)*cos(a) + (A.y - b)*sin(a), + E.y: (-A.x + a)*sin(a) + (A.y - b)*cos(a), + E.z: A.z - c} + F = A.locate_new('F', Vector.zero) + assert A.scalar_map(F) == {A.z: F.z, A.x: F.x, A.y: F.y} + + +def test_rotation_matrix(): + N = CoordSys3D('N') + A = N.orient_new_axis('A', q1, N.k) + B = A.orient_new_axis('B', q2, A.i) + C = B.orient_new_axis('C', q3, B.j) + D = N.orient_new_axis('D', q4, N.j) + E = N.orient_new_space('E', q1, q2, q3, '123') + F = N.orient_new_quaternion('F', q1, q2, q3, q4) + G = N.orient_new_body('G', q1, q2, q3, '123') + assert N.rotation_matrix(C) == Matrix([ + [- sin(q1) * sin(q2) * sin(q3) + cos(q1) * cos(q3), - sin(q1) * + cos(q2), sin(q1) * sin(q2) * cos(q3) + sin(q3) * cos(q1)], \ + [sin(q1) * cos(q3) + sin(q2) * sin(q3) * cos(q1), \ + cos(q1) * cos(q2), sin(q1) * sin(q3) - sin(q2) * cos(q1) * \ + cos(q3)], [- sin(q3) * cos(q2), sin(q2), cos(q2) * cos(q3)]]) + test_mat = D.rotation_matrix(C) - Matrix( + [[cos(q1) * cos(q3) * cos(q4) - sin(q3) * (- sin(q4) * cos(q2) + + sin(q1) * sin(q2) * cos(q4)), - sin(q2) * sin(q4) - sin(q1) * + cos(q2) * cos(q4), sin(q3) * cos(q1) * cos(q4) + cos(q3) * \ + (- sin(q4) * cos(q2) + sin(q1) * sin(q2) * cos(q4))], \ + [sin(q1) * cos(q3) + sin(q2) * sin(q3) * cos(q1), cos(q1) * \ + cos(q2), sin(q1) * sin(q3) - sin(q2) * cos(q1) * cos(q3)], \ + [sin(q4) * cos(q1) * cos(q3) - sin(q3) * (cos(q2) * cos(q4) + \ + sin(q1) * sin(q2) * \ + sin(q4)), sin(q2) * + cos(q4) - sin(q1) * sin(q4) * cos(q2), sin(q3) * \ + sin(q4) * cos(q1) + cos(q3) * (cos(q2) * cos(q4) + \ + sin(q1) * sin(q2) * sin(q4))]]) + assert test_mat.expand() == zeros(3, 3) + assert E.rotation_matrix(N) == Matrix( + [[cos(q2)*cos(q3), sin(q3)*cos(q2), -sin(q2)], + [sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1), \ + sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q2)], \ + [sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3), - \ + sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1), cos(q1)*cos(q2)]]) + assert F.rotation_matrix(N) == Matrix([[ + q1**2 + q2**2 - q3**2 - q4**2, + 2*q1*q4 + 2*q2*q3, -2*q1*q3 + 2*q2*q4],[ -2*q1*q4 + 2*q2*q3, + q1**2 - q2**2 + q3**2 - q4**2, 2*q1*q2 + 2*q3*q4], + [2*q1*q3 + 2*q2*q4, + -2*q1*q2 + 2*q3*q4, + q1**2 - q2**2 - q3**2 + q4**2]]) + assert G.rotation_matrix(N) == Matrix([[ + cos(q2)*cos(q3), sin(q1)*sin(q2)*cos(q3) + sin(q3)*cos(q1), + sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3)], [ + -sin(q3)*cos(q2), -sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), + sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1)],[ + sin(q2), -sin(q1)*cos(q2), cos(q1)*cos(q2)]]) + + +def test_vector_with_orientation(): + """ + Tests the effects of orientation of coordinate systems on + basic vector operations. + """ + N = CoordSys3D('N') + A = N.orient_new_axis('A', q1, N.k) + B = A.orient_new_axis('B', q2, A.i) + C = B.orient_new_axis('C', q3, B.j) + + # Test to_matrix + v1 = a*N.i + b*N.j + c*N.k + assert v1.to_matrix(A) == Matrix([[ a*cos(q1) + b*sin(q1)], + [-a*sin(q1) + b*cos(q1)], + [ c]]) + + # Test dot + assert N.i.dot(A.i) == cos(q1) + assert N.i.dot(A.j) == -sin(q1) + assert N.i.dot(A.k) == 0 + assert N.j.dot(A.i) == sin(q1) + assert N.j.dot(A.j) == cos(q1) + assert N.j.dot(A.k) == 0 + assert N.k.dot(A.i) == 0 + assert N.k.dot(A.j) == 0 + assert N.k.dot(A.k) == 1 + + assert N.i.dot(A.i + A.j) == -sin(q1) + cos(q1) == \ + (A.i + A.j).dot(N.i) + + assert A.i.dot(C.i) == cos(q3) + assert A.i.dot(C.j) == 0 + assert A.i.dot(C.k) == sin(q3) + assert A.j.dot(C.i) == sin(q2)*sin(q3) + assert A.j.dot(C.j) == cos(q2) + assert A.j.dot(C.k) == -sin(q2)*cos(q3) + assert A.k.dot(C.i) == -cos(q2)*sin(q3) + assert A.k.dot(C.j) == sin(q2) + assert A.k.dot(C.k) == cos(q2)*cos(q3) + + # Test cross + assert N.i.cross(A.i) == sin(q1)*A.k + assert N.i.cross(A.j) == cos(q1)*A.k + assert N.i.cross(A.k) == -sin(q1)*A.i - cos(q1)*A.j + assert N.j.cross(A.i) == -cos(q1)*A.k + assert N.j.cross(A.j) == sin(q1)*A.k + assert N.j.cross(A.k) == cos(q1)*A.i - sin(q1)*A.j + assert N.k.cross(A.i) == A.j + assert N.k.cross(A.j) == -A.i + assert N.k.cross(A.k) == Vector.zero + + assert N.i.cross(A.i) == sin(q1)*A.k + assert N.i.cross(A.j) == cos(q1)*A.k + assert N.i.cross(A.i + A.j) == sin(q1)*A.k + cos(q1)*A.k + assert (A.i + A.j).cross(N.i) == (-sin(q1) - cos(q1))*N.k + + assert A.i.cross(C.i) == sin(q3)*C.j + assert A.i.cross(C.j) == -sin(q3)*C.i + cos(q3)*C.k + assert A.i.cross(C.k) == -cos(q3)*C.j + assert C.i.cross(A.i) == (-sin(q3)*cos(q2))*A.j + \ + (-sin(q2)*sin(q3))*A.k + assert C.j.cross(A.i) == (sin(q2))*A.j + (-cos(q2))*A.k + assert express(C.k.cross(A.i), C).trigsimp() == cos(q3)*C.j + + +def test_orient_new_methods(): + N = CoordSys3D('N') + orienter1 = AxisOrienter(q4, N.j) + orienter2 = SpaceOrienter(q1, q2, q3, '123') + orienter3 = QuaternionOrienter(q1, q2, q3, q4) + orienter4 = BodyOrienter(q1, q2, q3, '123') + D = N.orient_new('D', (orienter1, )) + E = N.orient_new('E', (orienter2, )) + F = N.orient_new('F', (orienter3, )) + G = N.orient_new('G', (orienter4, )) + assert D == N.orient_new_axis('D', q4, N.j) + assert E == N.orient_new_space('E', q1, q2, q3, '123') + assert F == N.orient_new_quaternion('F', q1, q2, q3, q4) + assert G == N.orient_new_body('G', q1, q2, q3, '123') + + +def test_locatenew_point(): + """ + Tests Point class, and locate_new method in CoordSys3D. + """ + A = CoordSys3D('A') + assert isinstance(A.origin, Point) + v = a*A.i + b*A.j + c*A.k + C = A.locate_new('C', v) + assert C.origin.position_wrt(A) == \ + C.position_wrt(A) == \ + C.origin.position_wrt(A.origin) == v + assert A.origin.position_wrt(C) == \ + A.position_wrt(C) == \ + A.origin.position_wrt(C.origin) == -v + assert A.origin.express_coordinates(C) == (-a, -b, -c) + p = A.origin.locate_new('p', -v) + assert p.express_coordinates(A) == (-a, -b, -c) + assert p.position_wrt(C.origin) == p.position_wrt(C) == \ + -2 * v + p1 = p.locate_new('p1', 2*v) + assert p1.position_wrt(C.origin) == Vector.zero + assert p1.express_coordinates(C) == (0, 0, 0) + p2 = p.locate_new('p2', A.i) + assert p1.position_wrt(p2) == 2*v - A.i + assert p2.express_coordinates(C) == (-2*a + 1, -2*b, -2*c) + + +def test_create_new(): + a = CoordSys3D('a') + c = a.create_new('c', transformation='spherical') + assert c._parent == a + assert c.transformation_to_parent() == \ + (c.r*sin(c.theta)*cos(c.phi), c.r*sin(c.theta)*sin(c.phi), c.r*cos(c.theta)) + assert c.transformation_from_parent() == \ + (sqrt(a.x**2 + a.y**2 + a.z**2), acos(a.z/sqrt(a.x**2 + a.y**2 + a.z**2)), atan2(a.y, a.x)) + + +def test_evalf(): + A = CoordSys3D('A') + v = 3*A.i + 4*A.j + a*A.k + assert v.n() == v.evalf() + assert v.evalf(subs={a:1}) == v.subs(a, 1).evalf() + + +def test_lame_coefficients(): + a = CoordSys3D('a', 'spherical') + assert a.lame_coefficients() == (1, a.r, sin(a.theta)*a.r) + a = CoordSys3D('a') + assert a.lame_coefficients() == (1, 1, 1) + a = CoordSys3D('a', 'cartesian') + assert a.lame_coefficients() == (1, 1, 1) + a = CoordSys3D('a', 'cylindrical') + assert a.lame_coefficients() == (1, a.r, 1) + + +def test_transformation_equations(): + + x, y, z = symbols('x y z') + # Str + a = CoordSys3D('a', transformation='spherical', + variable_names=["r", "theta", "phi"]) + r, theta, phi = a.base_scalars() + + assert r == a.r + assert theta == a.theta + assert phi == a.phi + + raises(AttributeError, lambda: a.x) + raises(AttributeError, lambda: a.y) + raises(AttributeError, lambda: a.z) + + assert a.transformation_to_parent() == ( + r*sin(theta)*cos(phi), + r*sin(theta)*sin(phi), + r*cos(theta) + ) + assert a.lame_coefficients() == (1, r, r*sin(theta)) + assert a.transformation_from_parent_function()(x, y, z) == ( + sqrt(x ** 2 + y ** 2 + z ** 2), + acos((z) / sqrt(x**2 + y**2 + z**2)), + atan2(y, x) + ) + a = CoordSys3D('a', transformation='cylindrical', + variable_names=["r", "theta", "z"]) + r, theta, z = a.base_scalars() + assert a.transformation_to_parent() == ( + r*cos(theta), + r*sin(theta), + z + ) + assert a.lame_coefficients() == (1, a.r, 1) + assert a.transformation_from_parent_function()(x, y, z) == (sqrt(x**2 + y**2), + atan2(y, x), z) + + a = CoordSys3D('a', 'cartesian') + assert a.transformation_to_parent() == (a.x, a.y, a.z) + assert a.lame_coefficients() == (1, 1, 1) + assert a.transformation_from_parent_function()(x, y, z) == (x, y, z) + + # Variables and expressions + + # Cartesian with equation tuple: + x, y, z = symbols('x y z') + a = CoordSys3D('a', ((x, y, z), (x, y, z))) + a._calculate_inv_trans_equations() + assert a.transformation_to_parent() == (a.x1, a.x2, a.x3) + assert a.lame_coefficients() == (1, 1, 1) + assert a.transformation_from_parent_function()(x, y, z) == (x, y, z) + r, theta, z = symbols("r theta z") + + # Cylindrical with equation tuple: + a = CoordSys3D('a', [(r, theta, z), (r*cos(theta), r*sin(theta), z)], + variable_names=["r", "theta", "z"]) + r, theta, z = a.base_scalars() + assert a.transformation_to_parent() == ( + r*cos(theta), r*sin(theta), z + ) + assert a.lame_coefficients() == ( + sqrt(sin(theta)**2 + cos(theta)**2), + sqrt(r**2*sin(theta)**2 + r**2*cos(theta)**2), + 1 + ) # ==> this should simplify to (1, r, 1), tests are too slow with `simplify`. + + # Definitions with `lambda`: + + # Cartesian with `lambda` + a = CoordSys3D('a', lambda x, y, z: (x, y, z)) + assert a.transformation_to_parent() == (a.x1, a.x2, a.x3) + assert a.lame_coefficients() == (1, 1, 1) + a._calculate_inv_trans_equations() + assert a.transformation_from_parent_function()(x, y, z) == (x, y, z) + + # Spherical with `lambda` + a = CoordSys3D('a', lambda r, theta, phi: (r*sin(theta)*cos(phi), r*sin(theta)*sin(phi), r*cos(theta)), + variable_names=["r", "theta", "phi"]) + r, theta, phi = a.base_scalars() + assert a.transformation_to_parent() == ( + r*sin(theta)*cos(phi), r*sin(phi)*sin(theta), r*cos(theta) + ) + assert a.lame_coefficients() == ( + sqrt(sin(phi)**2*sin(theta)**2 + sin(theta)**2*cos(phi)**2 + cos(theta)**2), + sqrt(r**2*sin(phi)**2*cos(theta)**2 + r**2*sin(theta)**2 + r**2*cos(phi)**2*cos(theta)**2), + sqrt(r**2*sin(phi)**2*sin(theta)**2 + r**2*sin(theta)**2*cos(phi)**2) + ) # ==> this should simplify to (1, r, sin(theta)*r), `simplify` is too slow. + + # Cylindrical with `lambda` + a = CoordSys3D('a', lambda r, theta, z: + (r*cos(theta), r*sin(theta), z), + variable_names=["r", "theta", "z"] + ) + r, theta, z = a.base_scalars() + assert a.transformation_to_parent() == (r*cos(theta), r*sin(theta), z) + assert a.lame_coefficients() == ( + sqrt(sin(theta)**2 + cos(theta)**2), + sqrt(r**2*sin(theta)**2 + r**2*cos(theta)**2), + 1 + ) # ==> this should simplify to (1, a.x, 1) + + raises(TypeError, lambda: CoordSys3D('a', transformation={ + x: x*sin(y)*cos(z), y:x*sin(y)*sin(z), z: x*cos(y)})) + + +def test_check_orthogonality(): + x, y, z = symbols('x y z') + u,v = symbols('u, v') + a = CoordSys3D('a', transformation=((x, y, z), (x*sin(y)*cos(z), x*sin(y)*sin(z), x*cos(y)))) + assert a._check_orthogonality(a._transformation) is True + a = CoordSys3D('a', transformation=((x, y, z), (x * cos(y), x * sin(y), z))) + assert a._check_orthogonality(a._transformation) is True + a = CoordSys3D('a', transformation=((u, v, z), (cosh(u) * cos(v), sinh(u) * sin(v), z))) + assert a._check_orthogonality(a._transformation) is True + + raises(ValueError, lambda: CoordSys3D('a', transformation=((x, y, z), (x, x, z)))) + raises(ValueError, lambda: CoordSys3D('a', transformation=( + (x, y, z), (x*sin(y/2)*cos(z), x*sin(y)*sin(z), x*cos(y))))) + + +def test_rotation_trans_equations(): + a = CoordSys3D('a') + from sympy.core.symbol import symbols + q0 = symbols('q0') + assert a._rotation_trans_equations(a._parent_rotation_matrix, a.base_scalars()) == (a.x, a.y, a.z) + assert a._rotation_trans_equations(a._inverse_rotation_matrix(), a.base_scalars()) == (a.x, a.y, a.z) + b = a.orient_new_axis('b', 0, -a.k) + assert b._rotation_trans_equations(b._parent_rotation_matrix, b.base_scalars()) == (b.x, b.y, b.z) + assert b._rotation_trans_equations(b._inverse_rotation_matrix(), b.base_scalars()) == (b.x, b.y, b.z) + c = a.orient_new_axis('c', q0, -a.k) + assert c._rotation_trans_equations(c._parent_rotation_matrix, c.base_scalars()) == \ + (-sin(q0) * c.y + cos(q0) * c.x, sin(q0) * c.x + cos(q0) * c.y, c.z) + assert c._rotation_trans_equations(c._inverse_rotation_matrix(), c.base_scalars()) == \ + (sin(q0) * c.y + cos(q0) * c.x, -sin(q0) * c.x + cos(q0) * c.y, c.z) diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_dyadic.py b/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_dyadic.py new file mode 100644 index 0000000000000000000000000000000000000000..2e396fcf2a81af897b59c0065f6b15f5c6933222 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_dyadic.py @@ -0,0 +1,134 @@ +from sympy.core.numbers import pi +from sympy.core.symbol import symbols +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix +from sympy.simplify.simplify import simplify +from sympy.vector import (CoordSys3D, Vector, Dyadic, + DyadicAdd, DyadicMul, DyadicZero, + BaseDyadic, express) + + +A = CoordSys3D('A') + + +def test_dyadic(): + a, b = symbols('a, b') + assert Dyadic.zero != 0 + assert isinstance(Dyadic.zero, DyadicZero) + assert BaseDyadic(A.i, A.j) != BaseDyadic(A.j, A.i) + assert (BaseDyadic(Vector.zero, A.i) == + BaseDyadic(A.i, Vector.zero) == Dyadic.zero) + + d1 = A.i | A.i + d2 = A.j | A.j + d3 = A.i | A.j + + assert isinstance(d1, BaseDyadic) + d_mul = a*d1 + assert isinstance(d_mul, DyadicMul) + assert d_mul.base_dyadic == d1 + assert d_mul.measure_number == a + assert isinstance(a*d1 + b*d3, DyadicAdd) + assert d1 == A.i.outer(A.i) + assert d3 == A.i.outer(A.j) + v1 = a*A.i - A.k + v2 = A.i + b*A.j + assert v1 | v2 == v1.outer(v2) == a * (A.i|A.i) + (a*b) * (A.i|A.j) +\ + - (A.k|A.i) - b * (A.k|A.j) + assert d1 * 0 == Dyadic.zero + assert d1 != Dyadic.zero + assert d1 * 2 == 2 * (A.i | A.i) + assert d1 / 2. == 0.5 * d1 + + assert d1.dot(0 * d1) == Vector.zero + assert d1 & d2 == Dyadic.zero + assert d1.dot(A.i) == A.i == d1 & A.i + + assert d1.cross(Vector.zero) == Dyadic.zero + assert d1.cross(A.i) == Dyadic.zero + assert d1 ^ A.j == d1.cross(A.j) + assert d1.cross(A.k) == - A.i | A.j + assert d2.cross(A.i) == - A.j | A.k == d2 ^ A.i + + assert A.i ^ d1 == Dyadic.zero + assert A.j.cross(d1) == - A.k | A.i == A.j ^ d1 + assert Vector.zero.cross(d1) == Dyadic.zero + assert A.k ^ d1 == A.j | A.i + assert A.i.dot(d1) == A.i & d1 == A.i + assert A.j.dot(d1) == Vector.zero + assert Vector.zero.dot(d1) == Vector.zero + assert A.j & d2 == A.j + + assert d1.dot(d3) == d1 & d3 == A.i | A.j == d3 + assert d3 & d1 == Dyadic.zero + + q = symbols('q') + B = A.orient_new_axis('B', q, A.k) + assert express(d1, B) == express(d1, B, B) + + expr1 = ((cos(q)**2) * (B.i | B.i) + (-sin(q) * cos(q)) * + (B.i | B.j) + (-sin(q) * cos(q)) * (B.j | B.i) + (sin(q)**2) * + (B.j | B.j)) + assert (express(d1, B) - expr1).simplify() == Dyadic.zero + + expr2 = (cos(q)) * (B.i | A.i) + (-sin(q)) * (B.j | A.i) + assert (express(d1, B, A) - expr2).simplify() == Dyadic.zero + + expr3 = (cos(q)) * (A.i | B.i) + (-sin(q)) * (A.i | B.j) + assert (express(d1, A, B) - expr3).simplify() == Dyadic.zero + + assert d1.to_matrix(A) == Matrix([[1, 0, 0], [0, 0, 0], [0, 0, 0]]) + assert d1.to_matrix(A, B) == Matrix([[cos(q), -sin(q), 0], + [0, 0, 0], + [0, 0, 0]]) + assert d3.to_matrix(A) == Matrix([[0, 1, 0], [0, 0, 0], [0, 0, 0]]) + a, b, c, d, e, f = symbols('a, b, c, d, e, f') + v1 = a * A.i + b * A.j + c * A.k + v2 = d * A.i + e * A.j + f * A.k + d4 = v1.outer(v2) + assert d4.to_matrix(A) == Matrix([[a * d, a * e, a * f], + [b * d, b * e, b * f], + [c * d, c * e, c * f]]) + d5 = v1.outer(v1) + C = A.orient_new_axis('C', q, A.i) + for expected, actual in zip(C.rotation_matrix(A) * d5.to_matrix(A) * \ + C.rotation_matrix(A).T, d5.to_matrix(C)): + assert (expected - actual).simplify() == 0 + + +def test_dyadic_simplify(): + x, y, z, k, n, m, w, f, s, A = symbols('x, y, z, k, n, m, w, f, s, A') + N = CoordSys3D('N') + + dy = N.i | N.i + test1 = (1 / x + 1 / y) * dy + assert (N.i & test1 & N.i) != (x + y) / (x * y) + test1 = test1.simplify() + assert test1.simplify() == simplify(test1) + assert (N.i & test1 & N.i) == (x + y) / (x * y) + + test2 = (A**2 * s**4 / (4 * pi * k * m**3)) * dy + test2 = test2.simplify() + assert (N.i & test2 & N.i) == (A**2 * s**4 / (4 * pi * k * m**3)) + + test3 = ((4 + 4 * x - 2 * (2 + 2 * x)) / (2 + 2 * x)) * dy + test3 = test3.simplify() + assert (N.i & test3 & N.i) == 0 + + test4 = ((-4 * x * y**2 - 2 * y**3 - 2 * x**2 * y) / (x + y)**2) * dy + test4 = test4.simplify() + assert (N.i & test4 & N.i) == -2 * y + + +def test_dyadic_srepr(): + from sympy.printing.repr import srepr + N = CoordSys3D('N') + + dy = N.i | N.j + res = "BaseDyadic(CoordSys3D(Str('N'), Tuple(ImmutableDenseMatrix([["\ + "Integer(1), Integer(0), Integer(0)], [Integer(0), Integer(1), "\ + "Integer(0)], [Integer(0), Integer(0), Integer(1)]]), "\ + "VectorZero())).i, CoordSys3D(Str('N'), Tuple(ImmutableDenseMatrix("\ + "[[Integer(1), Integer(0), Integer(0)], [Integer(0), Integer(1), "\ + "Integer(0)], [Integer(0), Integer(0), Integer(1)]]), VectorZero())).j)" + assert srepr(dy) == res diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_field_functions.py b/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_field_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..035c2ce0234b81069c5ad8dcb1c74f4de0164a8f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_field_functions.py @@ -0,0 +1,321 @@ +from sympy.core.function import Derivative +from sympy.vector.vector import Vector +from sympy.vector.coordsysrect import CoordSys3D +from sympy.simplify import simplify +from sympy.core.symbol import symbols +from sympy.core import S +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.vector.vector import Dot +from sympy.vector.operators import curl, divergence, gradient, Gradient, Divergence, Cross +from sympy.vector.deloperator import Del +from sympy.vector.functions import (is_conservative, is_solenoidal, + scalar_potential, directional_derivative, + laplacian, scalar_potential_difference) +from sympy.testing.pytest import raises + +C = CoordSys3D('C') +i, j, k = C.base_vectors() +x, y, z = C.base_scalars() +delop = Del() +a, b, c, q = symbols('a b c q') + + +def test_del_operator(): + # Tests for curl + + assert delop ^ Vector.zero == Vector.zero + assert ((delop ^ Vector.zero).doit() == Vector.zero == + curl(Vector.zero)) + assert delop.cross(Vector.zero) == delop ^ Vector.zero + assert (delop ^ i).doit() == Vector.zero + assert delop.cross(2*y**2*j, doit=True) == Vector.zero + assert delop.cross(2*y**2*j) == delop ^ 2*y**2*j + v = x*y*z * (i + j + k) + assert ((delop ^ v).doit() == + (-x*y + x*z)*i + (x*y - y*z)*j + (-x*z + y*z)*k == + curl(v)) + assert delop ^ v == delop.cross(v) + assert (delop.cross(2*x**2*j) == + (Derivative(0, C.y) - Derivative(2*C.x**2, C.z))*C.i + + (-Derivative(0, C.x) + Derivative(0, C.z))*C.j + + (-Derivative(0, C.y) + Derivative(2*C.x**2, C.x))*C.k) + assert (delop.cross(2*x**2*j, doit=True) == 4*x*k == + curl(2*x**2*j)) + + #Tests for divergence + assert delop & Vector.zero is S.Zero == divergence(Vector.zero) + assert (delop & Vector.zero).doit() is S.Zero + assert delop.dot(Vector.zero) == delop & Vector.zero + assert (delop & i).doit() is S.Zero + assert (delop & x**2*i).doit() == 2*x == divergence(x**2*i) + assert (delop.dot(v, doit=True) == x*y + y*z + z*x == + divergence(v)) + assert delop & v == delop.dot(v) + assert delop.dot(1/(x*y*z) * (i + j + k), doit=True) == \ + - 1 / (x*y*z**2) - 1 / (x*y**2*z) - 1 / (x**2*y*z) + v = x*i + y*j + z*k + assert (delop & v == Derivative(C.x, C.x) + + Derivative(C.y, C.y) + Derivative(C.z, C.z)) + assert delop.dot(v, doit=True) == 3 == divergence(v) + assert delop & v == delop.dot(v) + assert simplify((delop & v).doit()) == 3 + + #Tests for gradient + assert (delop.gradient(0, doit=True) == Vector.zero == + gradient(0)) + assert delop.gradient(0) == delop(0) + assert (delop(S.Zero)).doit() == Vector.zero + assert (delop(x) == (Derivative(C.x, C.x))*C.i + + (Derivative(C.x, C.y))*C.j + (Derivative(C.x, C.z))*C.k) + assert (delop(x)).doit() == i == gradient(x) + assert (delop(x*y*z) == + (Derivative(C.x*C.y*C.z, C.x))*C.i + + (Derivative(C.x*C.y*C.z, C.y))*C.j + + (Derivative(C.x*C.y*C.z, C.z))*C.k) + assert (delop.gradient(x*y*z, doit=True) == + y*z*i + z*x*j + x*y*k == + gradient(x*y*z)) + assert delop(x*y*z) == delop.gradient(x*y*z) + assert (delop(2*x**2)).doit() == 4*x*i + assert ((delop(a*sin(y) / x)).doit() == + -a*sin(y)/x**2 * i + a*cos(y)/x * j) + + #Tests for directional derivative + assert (Vector.zero & delop)(a) is S.Zero + assert ((Vector.zero & delop)(a)).doit() is S.Zero + assert ((v & delop)(Vector.zero)).doit() == Vector.zero + assert ((v & delop)(S.Zero)).doit() is S.Zero + assert ((i & delop)(x)).doit() == 1 + assert ((j & delop)(y)).doit() == 1 + assert ((k & delop)(z)).doit() == 1 + assert ((i & delop)(x*y*z)).doit() == y*z + assert ((v & delop)(x)).doit() == x + assert ((v & delop)(x*y*z)).doit() == 3*x*y*z + assert (v & delop)(x + y + z) == C.x + C.y + C.z + assert ((v & delop)(x + y + z)).doit() == x + y + z + assert ((v & delop)(v)).doit() == v + assert ((i & delop)(v)).doit() == i + assert ((j & delop)(v)).doit() == j + assert ((k & delop)(v)).doit() == k + assert ((v & delop)(Vector.zero)).doit() == Vector.zero + + # Tests for laplacian on scalar fields + assert laplacian(x*y*z) is S.Zero + assert laplacian(x**2) == S(2) + assert laplacian(x**2*y**2*z**2) == \ + 2*y**2*z**2 + 2*x**2*z**2 + 2*x**2*y**2 + A = CoordSys3D('A', transformation="spherical", variable_names=["r", "theta", "phi"]) + B = CoordSys3D('B', transformation='cylindrical', variable_names=["r", "theta", "z"]) + assert laplacian(A.r + A.theta + A.phi) == 2/A.r + cos(A.theta)/(A.r**2*sin(A.theta)) + assert laplacian(B.r + B.theta + B.z) == 1/B.r + + # Tests for laplacian on vector fields + assert laplacian(x*y*z*(i + j + k)) == Vector.zero + assert laplacian(x*y**2*z*(i + j + k)) == \ + 2*x*z*i + 2*x*z*j + 2*x*z*k + + +def test_product_rules(): + """ + Tests the six product rules defined with respect to the Del + operator + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Del + + """ + + #Define the scalar and vector functions + f = 2*x*y*z + g = x*y + y*z + z*x + u = x**2*i + 4*j - y**2*z*k + v = 4*i + x*y*z*k + + # First product rule + lhs = delop(f * g, doit=True) + rhs = (f * delop(g) + g * delop(f)).doit() + assert simplify(lhs) == simplify(rhs) + + # Second product rule + lhs = delop(u & v).doit() + rhs = ((u ^ (delop ^ v)) + (v ^ (delop ^ u)) + \ + ((u & delop)(v)) + ((v & delop)(u))).doit() + assert simplify(lhs) == simplify(rhs) + + # Third product rule + lhs = (delop & (f*v)).doit() + rhs = ((f * (delop & v)) + (v & (delop(f)))).doit() + assert simplify(lhs) == simplify(rhs) + + # Fourth product rule + lhs = (delop & (u ^ v)).doit() + rhs = ((v & (delop ^ u)) - (u & (delop ^ v))).doit() + assert simplify(lhs) == simplify(rhs) + + # Fifth product rule + lhs = (delop ^ (f * v)).doit() + rhs = (((delop(f)) ^ v) + (f * (delop ^ v))).doit() + assert simplify(lhs) == simplify(rhs) + + # Sixth product rule + lhs = (delop ^ (u ^ v)).doit() + rhs = (u * (delop & v) - v * (delop & u) + + (v & delop)(u) - (u & delop)(v)).doit() + assert simplify(lhs) == simplify(rhs) + + +P = C.orient_new_axis('P', q, C.k) # type: ignore +scalar_field = 2*x**2*y*z +grad_field = gradient(scalar_field) +vector_field = y**2*i + 3*x*j + 5*y*z*k +curl_field = curl(vector_field) + + +def test_conservative(): + assert is_conservative(Vector.zero) is True + assert is_conservative(i) is True + assert is_conservative(2 * i + 3 * j + 4 * k) is True + assert (is_conservative(y*z*i + x*z*j + x*y*k) is + True) + assert is_conservative(x * j) is False + assert is_conservative(grad_field) is True + assert is_conservative(curl_field) is False + assert (is_conservative(4*x*y*z*i + 2*x**2*z*j) is + False) + assert is_conservative(z*P.i + P.x*k) is True + + +def test_solenoidal(): + assert is_solenoidal(Vector.zero) is True + assert is_solenoidal(i) is True + assert is_solenoidal(2 * i + 3 * j + 4 * k) is True + assert (is_solenoidal(y*z*i + x*z*j + x*y*k) is + True) + assert is_solenoidal(y * j) is False + assert is_solenoidal(grad_field) is False + assert is_solenoidal(curl_field) is True + assert is_solenoidal((-2*y + 3)*k) is True + assert is_solenoidal(cos(q)*i + sin(q)*j + cos(q)*P.k) is True + assert is_solenoidal(z*P.i + P.x*k) is True + + +def test_directional_derivative(): + assert directional_derivative(C.x*C.y*C.z, 3*C.i + 4*C.j + C.k) == C.x*C.y + 4*C.x*C.z + 3*C.y*C.z + assert directional_derivative(5*C.x**2*C.z, 3*C.i + 4*C.j + C.k) == 5*C.x**2 + 30*C.x*C.z + assert directional_derivative(5*C.x**2*C.z, 4*C.j) is S.Zero + + D = CoordSys3D("D", "spherical", variable_names=["r", "theta", "phi"], + vector_names=["e_r", "e_theta", "e_phi"]) + r, theta, phi = D.base_scalars() + e_r, e_theta, e_phi = D.base_vectors() + assert directional_derivative(r**2*e_r, e_r) == 2*r*e_r + assert directional_derivative(5*r**2*phi, 3*e_r + 4*e_theta + e_phi) == 5*r**2 + 30*r*phi + + +def test_scalar_potential(): + assert scalar_potential(Vector.zero, C) == 0 + assert scalar_potential(i, C) == x + assert scalar_potential(j, C) == y + assert scalar_potential(k, C) == z + assert scalar_potential(y*z*i + x*z*j + x*y*k, C) == x*y*z + assert scalar_potential(grad_field, C) == scalar_field + assert scalar_potential(z*P.i + P.x*k, C) == x*z*cos(q) + y*z*sin(q) + assert scalar_potential(z*P.i + P.x*k, P) == P.x*P.z + raises(ValueError, lambda: scalar_potential(x*j, C)) + + +def test_scalar_potential_difference(): + point1 = C.origin.locate_new('P1', 1*i + 2*j + 3*k) + point2 = C.origin.locate_new('P2', 4*i + 5*j + 6*k) + genericpointC = C.origin.locate_new('RP', x*i + y*j + z*k) + genericpointP = P.origin.locate_new('PP', P.x*P.i + P.y*P.j + P.z*P.k) + assert scalar_potential_difference(S.Zero, C, point1, point2) == 0 + assert (scalar_potential_difference(scalar_field, C, C.origin, + genericpointC) == + scalar_field) + assert (scalar_potential_difference(grad_field, C, C.origin, + genericpointC) == + scalar_field) + assert scalar_potential_difference(grad_field, C, point1, point2) == 948 + assert (scalar_potential_difference(y*z*i + x*z*j + + x*y*k, C, point1, + genericpointC) == + x*y*z - 6) + potential_diff_P = (2*P.z*(P.x*sin(q) + P.y*cos(q))* + (P.x*cos(q) - P.y*sin(q))**2) + assert (scalar_potential_difference(grad_field, P, P.origin, + genericpointP).simplify() == + potential_diff_P.simplify()) + + +def test_differential_operators_curvilinear_system(): + A = CoordSys3D('A', transformation="spherical", variable_names=["r", "theta", "phi"]) + B = CoordSys3D('B', transformation='cylindrical', variable_names=["r", "theta", "z"]) + # Test for spherical coordinate system and gradient + assert gradient(3*A.r + 4*A.theta) == 3*A.i + 4/A.r*A.j + assert gradient(3*A.r*A.phi + 4*A.theta) == 3*A.phi*A.i + 4/A.r*A.j + (3/sin(A.theta))*A.k + assert gradient(0*A.r + 0*A.theta+0*A.phi) == Vector.zero + assert gradient(A.r*A.theta*A.phi) == A.theta*A.phi*A.i + A.phi*A.j + (A.theta/sin(A.theta))*A.k + # Test for spherical coordinate system and divergence + assert divergence(A.r * A.i + A.theta * A.j + A.phi * A.k) == \ + (sin(A.theta)*A.r + cos(A.theta)*A.r*A.theta)/(sin(A.theta)*A.r**2) + 3 + 1/(sin(A.theta)*A.r) + assert divergence(3*A.r*A.phi*A.i + A.theta*A.j + A.r*A.theta*A.phi*A.k) == \ + (sin(A.theta)*A.r + cos(A.theta)*A.r*A.theta)/(sin(A.theta)*A.r**2) + 9*A.phi + A.theta/sin(A.theta) + assert divergence(Vector.zero) == 0 + assert divergence(0*A.i + 0*A.j + 0*A.k) == 0 + # Test for spherical coordinate system and curl + assert curl(A.r*A.i + A.theta*A.j + A.phi*A.k) == \ + (cos(A.theta)*A.phi/(sin(A.theta)*A.r))*A.i + (-A.phi/A.r)*A.j + A.theta/A.r*A.k + assert curl(A.r*A.j + A.phi*A.k) == (cos(A.theta)*A.phi/(sin(A.theta)*A.r))*A.i + (-A.phi/A.r)*A.j + 2*A.k + + # Test for cylindrical coordinate system and gradient + assert gradient(0*B.r + 0*B.theta+0*B.z) == Vector.zero + assert gradient(B.r*B.theta*B.z) == B.theta*B.z*B.i + B.z*B.j + B.r*B.theta*B.k + assert gradient(3*B.r) == 3*B.i + assert gradient(2*B.theta) == 2/B.r * B.j + assert gradient(4*B.z) == 4*B.k + # Test for cylindrical coordinate system and divergence + assert divergence(B.r*B.i + B.theta*B.j + B.z*B.k) == 3 + 1/B.r + assert divergence(B.r*B.j + B.z*B.k) == 1 + # Test for cylindrical coordinate system and curl + assert curl(B.r*B.j + B.z*B.k) == 2*B.k + assert curl(3*B.i + 2/B.r*B.j + 4*B.k) == Vector.zero + +def test_mixed_coordinates(): + # gradient + a = CoordSys3D('a') + b = CoordSys3D('b') + c = CoordSys3D('c') + assert gradient(a.x*b.y) == b.y*a.i + a.x*b.j + assert gradient(3*cos(q)*a.x*b.x+a.y*(a.x+(cos(q)+b.x))) ==\ + (a.y + 3*b.x*cos(q))*a.i + (a.x + b.x + cos(q))*a.j + (3*a.x*cos(q) + a.y)*b.i + # Some tests need further work: + # assert gradient(a.x*(cos(a.x+b.x))) == (cos(a.x + b.x))*a.i + a.x*Gradient(cos(a.x + b.x)) + # assert gradient(cos(a.x + b.x)*cos(a.x + b.z)) == Gradient(cos(a.x + b.x)*cos(a.x + b.z)) + assert gradient(a.x**b.y) == Gradient(a.x**b.y) + # assert gradient(cos(a.x+b.y)*a.z) == None + assert gradient(cos(a.x*b.y)) == Gradient(cos(a.x*b.y)) + assert gradient(3*cos(q)*a.x*b.x*a.z*a.y+ b.y*b.z + cos(a.x+a.y)*b.z) == \ + (3*a.y*a.z*b.x*cos(q) - b.z*sin(a.x + a.y))*a.i + \ + (3*a.x*a.z*b.x*cos(q) - b.z*sin(a.x + a.y))*a.j + (3*a.x*a.y*b.x*cos(q))*a.k + \ + (3*a.x*a.y*a.z*cos(q))*b.i + b.z*b.j + (b.y + cos(a.x + a.y))*b.k + # divergence + assert divergence(a.i*a.x+a.j*a.y+a.z*a.k + b.i*b.x+b.j*b.y+b.z*b.k + c.i*c.x+c.j*c.y+c.z*c.k) == S(9) + # assert divergence(3*a.i*a.x*cos(a.x+b.z) + a.j*b.x*c.z) == None + assert divergence(3*a.i*a.x*a.z + b.j*b.x*c.z + 3*a.j*a.z*a.y) == \ + 6*a.z + b.x*Dot(b.j, c.k) + assert divergence(3*cos(q)*a.x*b.x*b.i*c.x) == \ + 3*a.x*b.x*cos(q)*Dot(b.i, c.i) + 3*a.x*c.x*cos(q) + 3*b.x*c.x*cos(q)*Dot(b.i, a.i) + assert divergence(a.x*b.x*c.x*Cross(a.x*a.i, a.y*b.j)) ==\ + a.x*b.x*c.x*Divergence(Cross(a.x*a.i, a.y*b.j)) + \ + b.x*c.x*Dot(Cross(a.x*a.i, a.y*b.j), a.i) + \ + a.x*c.x*Dot(Cross(a.x*a.i, a.y*b.j), b.i) + \ + a.x*b.x*Dot(Cross(a.x*a.i, a.y*b.j), c.i) + assert divergence(a.x*b.x*c.x*(a.x*a.i + b.x*b.i)) == \ + 4*a.x*b.x*c.x +\ + a.x**2*c.x*Dot(a.i, b.i) +\ + a.x**2*b.x*Dot(a.i, c.i) +\ + b.x**2*c.x*Dot(b.i, a.i) +\ + a.x*b.x**2*Dot(b.i, c.i) diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_functions.py b/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..dfdf9821b6c853755ce12d0cbdfa599bd4f312e4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_functions.py @@ -0,0 +1,184 @@ +from sympy.vector.vector import Vector +from sympy.vector.coordsysrect import CoordSys3D +from sympy.vector.functions import express, matrix_to_vector, orthogonalize +from sympy.core.numbers import Rational +from sympy.core.singleton import S +from sympy.core.symbol import symbols +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix +from sympy.testing.pytest import raises + +N = CoordSys3D('N') +q1, q2, q3, q4, q5 = symbols('q1 q2 q3 q4 q5') +A = N.orient_new_axis('A', q1, N.k) # type: ignore +B = A.orient_new_axis('B', q2, A.i) +C = B.orient_new_axis('C', q3, B.j) + + +def test_express(): + assert express(Vector.zero, N) == Vector.zero + assert express(S.Zero, N) is S.Zero + assert express(A.i, C) == cos(q3)*C.i + sin(q3)*C.k + assert express(A.j, C) == sin(q2)*sin(q3)*C.i + cos(q2)*C.j - \ + sin(q2)*cos(q3)*C.k + assert express(A.k, C) == -sin(q3)*cos(q2)*C.i + sin(q2)*C.j + \ + cos(q2)*cos(q3)*C.k + assert express(A.i, N) == cos(q1)*N.i + sin(q1)*N.j + assert express(A.j, N) == -sin(q1)*N.i + cos(q1)*N.j + assert express(A.k, N) == N.k + assert express(A.i, A) == A.i + assert express(A.j, A) == A.j + assert express(A.k, A) == A.k + assert express(A.i, B) == B.i + assert express(A.j, B) == cos(q2)*B.j - sin(q2)*B.k + assert express(A.k, B) == sin(q2)*B.j + cos(q2)*B.k + assert express(A.i, C) == cos(q3)*C.i + sin(q3)*C.k + assert express(A.j, C) == sin(q2)*sin(q3)*C.i + cos(q2)*C.j - \ + sin(q2)*cos(q3)*C.k + assert express(A.k, C) == -sin(q3)*cos(q2)*C.i + sin(q2)*C.j + \ + cos(q2)*cos(q3)*C.k + # Check to make sure UnitVectors get converted properly + assert express(N.i, N) == N.i + assert express(N.j, N) == N.j + assert express(N.k, N) == N.k + assert express(N.i, A) == (cos(q1)*A.i - sin(q1)*A.j) + assert express(N.j, A) == (sin(q1)*A.i + cos(q1)*A.j) + assert express(N.k, A) == A.k + assert express(N.i, B) == (cos(q1)*B.i - sin(q1)*cos(q2)*B.j + + sin(q1)*sin(q2)*B.k) + assert express(N.j, B) == (sin(q1)*B.i + cos(q1)*cos(q2)*B.j - + sin(q2)*cos(q1)*B.k) + assert express(N.k, B) == (sin(q2)*B.j + cos(q2)*B.k) + assert express(N.i, C) == ( + (cos(q1)*cos(q3) - sin(q1)*sin(q2)*sin(q3))*C.i - + sin(q1)*cos(q2)*C.j + + (sin(q3)*cos(q1) + sin(q1)*sin(q2)*cos(q3))*C.k) + assert express(N.j, C) == ( + (sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1))*C.i + + cos(q1)*cos(q2)*C.j + + (sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3))*C.k) + assert express(N.k, C) == (-sin(q3)*cos(q2)*C.i + sin(q2)*C.j + + cos(q2)*cos(q3)*C.k) + + assert express(A.i, N) == (cos(q1)*N.i + sin(q1)*N.j) + assert express(A.j, N) == (-sin(q1)*N.i + cos(q1)*N.j) + assert express(A.k, N) == N.k + assert express(A.i, A) == A.i + assert express(A.j, A) == A.j + assert express(A.k, A) == A.k + assert express(A.i, B) == B.i + assert express(A.j, B) == (cos(q2)*B.j - sin(q2)*B.k) + assert express(A.k, B) == (sin(q2)*B.j + cos(q2)*B.k) + assert express(A.i, C) == (cos(q3)*C.i + sin(q3)*C.k) + assert express(A.j, C) == (sin(q2)*sin(q3)*C.i + cos(q2)*C.j - + sin(q2)*cos(q3)*C.k) + assert express(A.k, C) == (-sin(q3)*cos(q2)*C.i + sin(q2)*C.j + + cos(q2)*cos(q3)*C.k) + + assert express(B.i, N) == (cos(q1)*N.i + sin(q1)*N.j) + assert express(B.j, N) == (-sin(q1)*cos(q2)*N.i + + cos(q1)*cos(q2)*N.j + sin(q2)*N.k) + assert express(B.k, N) == (sin(q1)*sin(q2)*N.i - + sin(q2)*cos(q1)*N.j + cos(q2)*N.k) + assert express(B.i, A) == A.i + assert express(B.j, A) == (cos(q2)*A.j + sin(q2)*A.k) + assert express(B.k, A) == (-sin(q2)*A.j + cos(q2)*A.k) + assert express(B.i, B) == B.i + assert express(B.j, B) == B.j + assert express(B.k, B) == B.k + assert express(B.i, C) == (cos(q3)*C.i + sin(q3)*C.k) + assert express(B.j, C) == C.j + assert express(B.k, C) == (-sin(q3)*C.i + cos(q3)*C.k) + + assert express(C.i, N) == ( + (cos(q1)*cos(q3) - sin(q1)*sin(q2)*sin(q3))*N.i + + (sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1))*N.j - + sin(q3)*cos(q2)*N.k) + assert express(C.j, N) == ( + -sin(q1)*cos(q2)*N.i + cos(q1)*cos(q2)*N.j + sin(q2)*N.k) + assert express(C.k, N) == ( + (sin(q3)*cos(q1) + sin(q1)*sin(q2)*cos(q3))*N.i + + (sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3))*N.j + + cos(q2)*cos(q3)*N.k) + assert express(C.i, A) == (cos(q3)*A.i + sin(q2)*sin(q3)*A.j - + sin(q3)*cos(q2)*A.k) + assert express(C.j, A) == (cos(q2)*A.j + sin(q2)*A.k) + assert express(C.k, A) == (sin(q3)*A.i - sin(q2)*cos(q3)*A.j + + cos(q2)*cos(q3)*A.k) + assert express(C.i, B) == (cos(q3)*B.i - sin(q3)*B.k) + assert express(C.j, B) == B.j + assert express(C.k, B) == (sin(q3)*B.i + cos(q3)*B.k) + assert express(C.i, C) == C.i + assert express(C.j, C) == C.j + assert express(C.k, C) == C.k == (C.k) + + # Check to make sure Vectors get converted back to UnitVectors + assert N.i == express((cos(q1)*A.i - sin(q1)*A.j), N).simplify() + assert N.j == express((sin(q1)*A.i + cos(q1)*A.j), N).simplify() + assert N.i == express((cos(q1)*B.i - sin(q1)*cos(q2)*B.j + + sin(q1)*sin(q2)*B.k), N).simplify() + assert N.j == express((sin(q1)*B.i + cos(q1)*cos(q2)*B.j - + sin(q2)*cos(q1)*B.k), N).simplify() + assert N.k == express((sin(q2)*B.j + cos(q2)*B.k), N).simplify() + + + assert A.i == express((cos(q1)*N.i + sin(q1)*N.j), A).simplify() + assert A.j == express((-sin(q1)*N.i + cos(q1)*N.j), A).simplify() + + assert A.j == express((cos(q2)*B.j - sin(q2)*B.k), A).simplify() + assert A.k == express((sin(q2)*B.j + cos(q2)*B.k), A).simplify() + + assert A.i == express((cos(q3)*C.i + sin(q3)*C.k), A).simplify() + assert A.j == express((sin(q2)*sin(q3)*C.i + cos(q2)*C.j - + sin(q2)*cos(q3)*C.k), A).simplify() + + assert A.k == express((-sin(q3)*cos(q2)*C.i + sin(q2)*C.j + + cos(q2)*cos(q3)*C.k), A).simplify() + assert B.i == express((cos(q1)*N.i + sin(q1)*N.j), B).simplify() + assert B.j == express((-sin(q1)*cos(q2)*N.i + + cos(q1)*cos(q2)*N.j + sin(q2)*N.k), B).simplify() + + assert B.k == express((sin(q1)*sin(q2)*N.i - + sin(q2)*cos(q1)*N.j + cos(q2)*N.k), B).simplify() + + assert B.j == express((cos(q2)*A.j + sin(q2)*A.k), B).simplify() + assert B.k == express((-sin(q2)*A.j + cos(q2)*A.k), B).simplify() + assert B.i == express((cos(q3)*C.i + sin(q3)*C.k), B).simplify() + assert B.k == express((-sin(q3)*C.i + cos(q3)*C.k), B).simplify() + assert C.i == express((cos(q3)*A.i + sin(q2)*sin(q3)*A.j - + sin(q3)*cos(q2)*A.k), C).simplify() + assert C.j == express((cos(q2)*A.j + sin(q2)*A.k), C).simplify() + assert C.k == express((sin(q3)*A.i - sin(q2)*cos(q3)*A.j + + cos(q2)*cos(q3)*A.k), C).simplify() + assert C.i == express((cos(q3)*B.i - sin(q3)*B.k), C).simplify() + assert C.k == express((sin(q3)*B.i + cos(q3)*B.k), C).simplify() + + +def test_matrix_to_vector(): + m = Matrix([[1], [2], [3]]) + assert matrix_to_vector(m, C) == C.i + 2*C.j + 3*C.k + m = Matrix([[0], [0], [0]]) + assert matrix_to_vector(m, N) == matrix_to_vector(m, C) == \ + Vector.zero + m = Matrix([[q1], [q2], [q3]]) + assert matrix_to_vector(m, N) == q1*N.i + q2*N.j + q3*N.k + + +def test_orthogonalize(): + C = CoordSys3D('C') + a, b = symbols('a b', integer=True) + i, j, k = C.base_vectors() + v1 = i + 2*j + v2 = 2*i + 3*j + v3 = 3*i + 5*j + v4 = 3*i + j + v5 = 2*i + 2*j + v6 = a*i + b*j + v7 = 4*a*i + 4*b*j + assert orthogonalize(v1, v2) == [C.i + 2*C.j, C.i*Rational(2, 5) + -C.j/5] + # from wikipedia + assert orthogonalize(v4, v5, orthonormal=True) == \ + [(3*sqrt(10))*C.i/10 + (sqrt(10))*C.j/10, (-sqrt(10))*C.i/10 + (3*sqrt(10))*C.j/10] + raises(ValueError, lambda: orthogonalize(v1, v2, v3)) + raises(ValueError, lambda: orthogonalize(v6, v7)) diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_implicitregion.py b/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_implicitregion.py new file mode 100644 index 0000000000000000000000000000000000000000..3686d847a7f165cb5ba9aeb813e5922aaa17e1e0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_implicitregion.py @@ -0,0 +1,90 @@ +from sympy.core.relational import Eq +from sympy.core.singleton import S +from sympy.abc import x, y, z, s, t +from sympy.sets import FiniteSet, EmptySet +from sympy.geometry import Point +from sympy.vector import ImplicitRegion +from sympy.testing.pytest import raises + + +def test_ImplicitRegion(): + ellipse = ImplicitRegion((x, y), (x**2/4 + y**2/16 - 1)) + assert ellipse.equation == x**2/4 + y**2/16 - 1 + assert ellipse.variables == (x, y) + assert ellipse.degree == 2 + r = ImplicitRegion((x, y, z), Eq(x**4 + y**2 - x*y, 6)) + assert r.equation == x**4 + y**2 - x*y - 6 + assert r.variables == (x, y, z) + assert r.degree == 4 + + +def test_regular_point(): + r1 = ImplicitRegion((x,), x**2 - 16) + assert r1.regular_point() == (-4,) + c1 = ImplicitRegion((x, y), x**2 + y**2 - 4) + assert c1.regular_point() == (0, -2) + c2 = ImplicitRegion((x, y), (x - S(5)/2)**2 + y**2 - (S(1)/4)**2) + assert c2.regular_point() == (S(5)/2, -S(1)/4) + c3 = ImplicitRegion((x, y), (y - 5)**2 - 16*(x - 5)) + assert c3.regular_point() == (5, 5) + r2 = ImplicitRegion((x, y), x**2 - 4*x*y - 3*y**2 + 4*x + 8*y - 5) + assert r2.regular_point() == (S(4)/7, S(9)/7) + r3 = ImplicitRegion((x, y), x**2 - 2*x*y + 3*y**2 - 2*x - 5*y + 3/2) + raises(ValueError, lambda: r3.regular_point()) + + +def test_singular_points_and_multiplicty(): + r1 = ImplicitRegion((x, y, z), Eq(x + y + z, 0)) + assert r1.singular_points() == EmptySet + r2 = ImplicitRegion((x, y, z), x*y*z + y**4 -x**2*z**2) + assert r2.singular_points() == FiniteSet((0, 0, z), (x, 0, 0)) + assert r2.multiplicity((0, 0, 0)) == 3 + assert r2.multiplicity((0, 0, 6)) == 2 + r3 = ImplicitRegion((x, y, z), z**2 - x**2 - y**2) + assert r3.singular_points() == FiniteSet((0, 0, 0)) + assert r3.multiplicity((0, 0, 0)) == 2 + r4 = ImplicitRegion((x, y), x**2 + y**2 - 2*x) + assert r4.singular_points() == EmptySet + assert r4.multiplicity(Point(1, 3)) == 0 + + +def test_rational_parametrization(): + p = ImplicitRegion((x,), x - 2) + assert p.rational_parametrization() == (x - 2,) + + line = ImplicitRegion((x, y), Eq(y, 3*x + 2)) + assert line.rational_parametrization() == (x, 3*x + 2) + + circle1 = ImplicitRegion((x, y), (x-2)**2 + (y+3)**2 - 4) + assert circle1.rational_parametrization(parameters=t) == (4*t/(t**2 + 1) + 2, 4*t**2/(t**2 + 1) - 5) + circle2 = ImplicitRegion((x, y), (x - S.Half)**2 + y**2 - (S(1)/2)**2) + + assert circle2.rational_parametrization(parameters=t) == (t/(t**2 + 1) + S(1)/2, t**2/(t**2 + 1) - S(1)/2) + circle3 = ImplicitRegion((x, y), Eq(x**2 + y**2, 2*x)) + assert circle3.rational_parametrization(parameters=(t,)) == (2*t/(t**2 + 1) + 1, 2*t**2/(t**2 + 1) - 1) + + parabola = ImplicitRegion((x, y), (y - 3)**2 - 4*(x + 6)) + assert parabola.rational_parametrization(t) == (-6 + 4/t**2, 3 + 4/t) + + rect_hyperbola = ImplicitRegion((x, y), x*y - 1) + assert rect_hyperbola.rational_parametrization(t) == (-1 + (t + 1)/t, t) + + cubic_curve = ImplicitRegion((x, y), x**3 + x**2 - y**2) + assert cubic_curve.rational_parametrization(parameters=(t)) == (t**2 - 1, t*(t**2 - 1)) + cuspidal = ImplicitRegion((x, y), (x**3 - y**2)) + assert cuspidal.rational_parametrization(t) == (t**2, t**3) + + I = ImplicitRegion((x, y), x**3 + x**2 - y**2) + assert I.rational_parametrization(t) == (t**2 - 1, t*(t**2 - 1)) + + sphere = ImplicitRegion((x, y, z), Eq(x**2 + y**2 + z**2, 2*x)) + assert sphere.rational_parametrization(parameters=(s, t)) == (2/(s**2 + t**2 + 1), 2*t/(s**2 + t**2 + 1), 2*s/(s**2 + t**2 + 1)) + + conic = ImplicitRegion((x, y), Eq(x**2 + 4*x*y + 3*y**2 + x - y + 10, 0)) + assert conic.rational_parametrization(t) == ( + S(17)/2 + 4/(3*t**2 + 4*t + 1), 4*t/(3*t**2 + 4*t + 1) - S(11)/2) + + r1 = ImplicitRegion((x, y), y**2 - x**3 + x) + raises(NotImplementedError, lambda: r1.rational_parametrization()) + r2 = ImplicitRegion((x, y), y**2 - x**3 - x**2 + 1) + raises(NotImplementedError, lambda: r2.rational_parametrization()) diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_integrals.py b/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_integrals.py new file mode 100644 index 0000000000000000000000000000000000000000..84c900d038e214df1ea59a8cd8fb2929005c3674 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_integrals.py @@ -0,0 +1,106 @@ +from sympy.core.numbers import pi +from sympy.core.singleton import S +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.testing.pytest import raises +from sympy.vector.coordsysrect import CoordSys3D +from sympy.vector.integrals import ParametricIntegral, vector_integrate +from sympy.vector.parametricregion import ParametricRegion +from sympy.vector.implicitregion import ImplicitRegion +from sympy.abc import x, y, z, u, v, r, t, theta, phi +from sympy.geometry import Point, Segment, Curve, Circle, Polygon, Plane + +C = CoordSys3D('C') + +def test_parametric_lineintegrals(): + halfcircle = ParametricRegion((4*cos(theta), 4*sin(theta)), (theta, -pi/2, pi/2)) + assert ParametricIntegral(C.x*C.y**4, halfcircle) == S(8192)/5 + + curve = ParametricRegion((t, t**2, t**3), (t, 0, 1)) + field1 = 8*C.x**2*C.y*C.z*C.i + 5*C.z*C.j - 4*C.x*C.y*C.k + assert ParametricIntegral(field1, curve) == 1 + line = ParametricRegion((4*t - 1, 2 - 2*t, t), (t, 0, 1)) + assert ParametricIntegral(C.x*C.z*C.i - C.y*C.z*C.k, line) == 3 + + assert ParametricIntegral(4*C.x**3, ParametricRegion((1, t), (t, 0, 2))) == 8 + + helix = ParametricRegion((cos(t), sin(t), 3*t), (t, 0, 4*pi)) + assert ParametricIntegral(C.x*C.y*C.z, helix) == -3*sqrt(10)*pi + + field2 = C.y*C.i + C.z*C.j + C.z*C.k + assert ParametricIntegral(field2, ParametricRegion((cos(t), sin(t), t**2), (t, 0, pi))) == -5*pi/2 + pi**4/2 + +def test_parametric_surfaceintegrals(): + + semisphere = ParametricRegion((2*sin(phi)*cos(theta), 2*sin(phi)*sin(theta), 2*cos(phi)),\ + (theta, 0, 2*pi), (phi, 0, pi/2)) + assert ParametricIntegral(C.z, semisphere) == 8*pi + + cylinder = ParametricRegion((sqrt(3)*cos(theta), sqrt(3)*sin(theta), z), (z, 0, 6), (theta, 0, 2*pi)) + assert ParametricIntegral(C.y, cylinder) == 0 + + cone = ParametricRegion((v*cos(u), v*sin(u), v), (u, 0, 2*pi), (v, 0, 1)) + assert ParametricIntegral(C.x*C.i + C.y*C.j + C.z**4*C.k, cone) == pi/3 + + triangle1 = ParametricRegion((x, y), (x, 0, 2), (y, 0, 10 - 5*x)) + triangle2 = ParametricRegion((x, y), (y, 0, 10 - 5*x), (x, 0, 2)) + assert ParametricIntegral(-15.6*C.y*C.k, triangle1) == ParametricIntegral(-15.6*C.y*C.k, triangle2) + assert ParametricIntegral(C.z, triangle1) == 10*C.z + +def test_parametric_volumeintegrals(): + + cube = ParametricRegion((x, y, z), (x, 0, 1), (y, 0, 1), (z, 0, 1)) + assert ParametricIntegral(1, cube) == 1 + + solidsphere1 = ParametricRegion((r*sin(phi)*cos(theta), r*sin(phi)*sin(theta), r*cos(phi)),\ + (r, 0, 2), (theta, 0, 2*pi), (phi, 0, pi)) + solidsphere2 = ParametricRegion((r*sin(phi)*cos(theta), r*sin(phi)*sin(theta), r*cos(phi)),\ + (r, 0, 2), (phi, 0, pi), (theta, 0, 2*pi)) + assert ParametricIntegral(C.x**2 + C.y**2, solidsphere1) == -256*pi/15 + assert ParametricIntegral(C.x**2 + C.y**2, solidsphere2) == 256*pi/15 + + region_under_plane1 = ParametricRegion((x, y, z), (x, 0, 3), (y, 0, -2*x/3 + 2),\ + (z, 0, 6 - 2*x - 3*y)) + region_under_plane2 = ParametricRegion((x, y, z), (x, 0, 3), (z, 0, 6 - 2*x - 3*y),\ + (y, 0, -2*x/3 + 2)) + + assert ParametricIntegral(C.x*C.i + C.j - 100*C.k, region_under_plane1) == \ + ParametricIntegral(C.x*C.i + C.j - 100*C.k, region_under_plane2) + assert ParametricIntegral(2*C.x, region_under_plane2) == -9 + +def test_vector_integrate(): + halfdisc = ParametricRegion((r*cos(theta), r* sin(theta)), (r, -2, 2), (theta, 0, pi)) + assert vector_integrate(C.x**2, halfdisc) == 4*pi + assert vector_integrate(C.x, ParametricRegion((t, t**2), (t, 2, 3))) == -17*sqrt(17)/12 + 37*sqrt(37)/12 + + assert vector_integrate(C.y**3*C.z, (C.x, 0, 3), (C.y, -1, 4)) == 765*C.z/4 + + s1 = Segment(Point(0, 0), Point(0, 1)) + assert vector_integrate(-15*C.y, s1) == S(-15)/2 + s2 = Segment(Point(4, 3, 9), Point(1, 1, 7)) + assert vector_integrate(C.y*C.i, s2) == -6 + + curve = Curve((sin(t), cos(t)), (t, 0, 2)) + assert vector_integrate(5*C.z, curve) == 10*C.z + + c1 = Circle(Point(2, 3), 6) + assert vector_integrate(C.x*C.y, c1) == 72*pi + c2 = Circle(Point(0, 0), Point(1, 1), Point(1, 0)) + assert vector_integrate(1, c2) == c2.circumference + + triangle = Polygon((0, 0), (1, 0), (1, 1)) + assert vector_integrate(C.x*C.i - 14*C.y*C.j, triangle) == 0 + p1, p2, p3, p4 = [(0, 0), (1, 0), (5, 1), (0, 1)] + poly = Polygon(p1, p2, p3, p4) + assert vector_integrate(-23*C.z, poly) == -161*C.z - 23*sqrt(17)*C.z + + point = Point(2, 3) + assert vector_integrate(C.i*C.y, point) == ParametricIntegral(C.y*C.i, ParametricRegion((2, 3))) + + c3 = ImplicitRegion((x, y), x**2 + y**2 - 4) + assert vector_integrate(45, c3) == 180*pi + c4 = ImplicitRegion((x, y), (x - 3)**2 + (y - 4)**2 - 9) + assert vector_integrate(1, c4) == 6*pi + + pl = Plane(Point(1, 1, 1), Point(2, 3, 4), Point(2, 2, 2)) + raises(ValueError, lambda: vector_integrate(C.x*C.z*C.i + C.k, pl)) diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_operators.py b/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_operators.py new file mode 100644 index 0000000000000000000000000000000000000000..5734edadd00547c67d6f864b50afd966ad8392a6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_operators.py @@ -0,0 +1,43 @@ +from sympy.vector import CoordSys3D, Gradient, Divergence, Curl, VectorZero, Laplacian +from sympy.printing.repr import srepr + +R = CoordSys3D('R') +s1 = R.x*R.y*R.z # type: ignore +s2 = R.x + 3*R.y**2 # type: ignore +s3 = R.x**2 + R.y**2 + R.z**2 # type: ignore +v1 = R.x*R.i + R.z*R.z*R.j # type: ignore +v2 = R.x*R.i + R.y*R.j + R.z*R.k # type: ignore +v3 = R.x**2*R.i + R.y**2*R.j + R.z**2*R.k # type: ignore + + +def test_Gradient(): + assert Gradient(s1) == Gradient(R.x*R.y*R.z) + assert Gradient(s2) == Gradient(R.x + 3*R.y**2) + assert Gradient(s1).doit() == R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k + assert Gradient(s2).doit() == R.i + 6*R.y*R.j + + +def test_Divergence(): + assert Divergence(v1) == Divergence(R.x*R.i + R.z*R.z*R.j) + assert Divergence(v2) == Divergence(R.x*R.i + R.y*R.j + R.z*R.k) + assert Divergence(v1).doit() == 1 + assert Divergence(v2).doit() == 3 + # issue 22384 + Rc = CoordSys3D('R', transformation='cylindrical') + assert Divergence(Rc.i).doit() == 1/Rc.r + + +def test_Curl(): + assert Curl(v1) == Curl(R.x*R.i + R.z*R.z*R.j) + assert Curl(v2) == Curl(R.x*R.i + R.y*R.j + R.z*R.k) + assert Curl(v1).doit() == (-2*R.z)*R.i + assert Curl(v2).doit() == VectorZero() + + +def test_Laplacian(): + assert Laplacian(s3) == Laplacian(R.x**2 + R.y**2 + R.z**2) + assert Laplacian(v3) == Laplacian(R.x**2*R.i + R.y**2*R.j + R.z**2*R.k) + assert Laplacian(s3).doit() == 6 + assert Laplacian(v3).doit() == 2*R.i + 2*R.j + 2*R.k + assert srepr(Laplacian(s3)) == \ + 'Laplacian(Add(Pow(R.x, Integer(2)), Pow(R.y, Integer(2)), Pow(R.z, Integer(2))))' diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_parametricregion.py b/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_parametricregion.py new file mode 100644 index 0000000000000000000000000000000000000000..e785b96744f9e2c39e91b997fcb70f8a921256bd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_parametricregion.py @@ -0,0 +1,97 @@ +from sympy.core.numbers import pi +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.vector.coordsysrect import CoordSys3D +from sympy.vector.parametricregion import ParametricRegion, parametric_region_list +from sympy.geometry import Point, Segment, Curve, Ellipse, Line, Parabola, Polygon +from sympy.testing.pytest import raises +from sympy.abc import a, b, r, t, x, y, z, theta, phi + + +C = CoordSys3D('C') + +def test_ParametricRegion(): + + point = ParametricRegion((3, 4)) + assert point.definition == (3, 4) + assert point.parameters == () + assert point.limits == {} + assert point.dimensions == 0 + + # line x = y + line_xy = ParametricRegion((y, y), (y, 1, 5)) + assert line_xy .definition == (y, y) + assert line_xy.parameters == (y,) + assert line_xy.dimensions == 1 + + # line y = z + line_yz = ParametricRegion((x,t,t), x, (t, 1, 2)) + assert line_yz.definition == (x,t,t) + assert line_yz.parameters == (x, t) + assert line_yz.limits == {t: (1, 2)} + assert line_yz.dimensions == 1 + + p1 = ParametricRegion((9*a, -16*b), (a, 0, 2), (b, -1, 5)) + assert p1.definition == (9*a, -16*b) + assert p1.parameters == (a, b) + assert p1.limits == {a: (0, 2), b: (-1, 5)} + assert p1.dimensions == 2 + + p2 = ParametricRegion((t, t**3), t) + assert p2.parameters == (t,) + assert p2.limits == {} + assert p2.dimensions == 0 + + circle = ParametricRegion((r*cos(theta), r*sin(theta)), r, (theta, 0, 2*pi)) + assert circle.definition == (r*cos(theta), r*sin(theta)) + assert circle.dimensions == 1 + + halfdisc = ParametricRegion((r*cos(theta), r*sin(theta)), (r, -2, 2), (theta, 0, pi)) + assert halfdisc.definition == (r*cos(theta), r*sin(theta)) + assert halfdisc.parameters == (r, theta) + assert halfdisc.limits == {r: (-2, 2), theta: (0, pi)} + assert halfdisc.dimensions == 2 + + ellipse = ParametricRegion((a*cos(t), b*sin(t)), (t, 0, 8)) + assert ellipse.parameters == (t,) + assert ellipse.limits == {t: (0, 8)} + assert ellipse.dimensions == 1 + + cylinder = ParametricRegion((r*cos(theta), r*sin(theta), z), (r, 0, 1), (theta, 0, 2*pi), (z, 0, 4)) + assert cylinder.parameters == (r, theta, z) + assert cylinder.dimensions == 3 + + sphere = ParametricRegion((r*sin(phi)*cos(theta),r*sin(phi)*sin(theta), r*cos(phi)), + r, (theta, 0, 2*pi), (phi, 0, pi)) + assert sphere.definition == (r*sin(phi)*cos(theta),r*sin(phi)*sin(theta), r*cos(phi)) + assert sphere.parameters == (r, theta, phi) + assert sphere.dimensions == 2 + + raises(ValueError, lambda: ParametricRegion((a*t**2, 2*a*t), (a, -2))) + raises(ValueError, lambda: ParametricRegion((a, b), (a**2, sin(b)), (a, 2, 4, 6))) + + +def test_parametric_region_list(): + + point = Point(-5, 12) + assert parametric_region_list(point) == [ParametricRegion((-5, 12))] + + e = Ellipse(Point(2, 8), 2, 6) + assert parametric_region_list(e, t) == [ParametricRegion((2*cos(t) + 2, 6*sin(t) + 8), (t, 0, 2*pi))] + + c = Curve((t, t**3), (t, 5, 3)) + assert parametric_region_list(c) == [ParametricRegion((t, t**3), (t, 5, 3))] + + s = Segment(Point(2, 11, -6), Point(0, 2, 5)) + assert parametric_region_list(s, t) == [ParametricRegion((2 - 2*t, 11 - 9*t, 11*t - 6), (t, 0, 1))] + s1 = Segment(Point(0, 0), (1, 0)) + assert parametric_region_list(s1, t) == [ParametricRegion((t, 0), (t, 0, 1))] + s2 = Segment(Point(1, 2, 3), Point(1, 2, 5)) + assert parametric_region_list(s2, t) == [ParametricRegion((1, 2, 2*t + 3), (t, 0, 1))] + s3 = Segment(Point(12, 56), Point(12, 56)) + assert parametric_region_list(s3) == [ParametricRegion((12, 56))] + + poly = Polygon((1,3), (-3, 8), (2, 4)) + assert parametric_region_list(poly, t) == [ParametricRegion((1 - 4*t, 5*t + 3), (t, 0, 1)), ParametricRegion((5*t - 3, 8 - 4*t), (t, 0, 1)), ParametricRegion((2 - t, 4 - t), (t, 0, 1))] + + p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7,8))) + raises(ValueError, lambda: parametric_region_list(p1)) diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_printing.py b/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_printing.py new file mode 100644 index 0000000000000000000000000000000000000000..ae76905e967bdf93485f135c6a69f968e1208986 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_printing.py @@ -0,0 +1,221 @@ +# -*- coding: utf-8 -*- +from sympy.core.function import Function +from sympy.integrals.integrals import Integral +from sympy.printing.latex import latex +from sympy.printing.pretty import pretty as xpretty +from sympy.vector import CoordSys3D, Del, Vector, express +from sympy.abc import a, b, c +from sympy.testing.pytest import XFAIL + + +def pretty(expr): + """ASCII pretty-printing""" + return xpretty(expr, use_unicode=False, wrap_line=False) + + +def upretty(expr): + """Unicode pretty-printing""" + return xpretty(expr, use_unicode=True, wrap_line=False) + + +# Initialize the basic and tedious vector/dyadic expressions +# needed for testing. +# Some of the pretty forms shown denote how the expressions just +# above them should look with pretty printing. +N = CoordSys3D('N') +C = N.orient_new_axis('C', a, N.k) # type: ignore +v = [] +d = [] +v.append(Vector.zero) +v.append(N.i) # type: ignore +v.append(-N.i) # type: ignore +v.append(N.i + N.j) # type: ignore +v.append(a*N.i) # type: ignore +v.append(a*N.i - b*N.j) # type: ignore +v.append((a**2 + N.x)*N.i + N.k) # type: ignore +v.append((a**2 + b)*N.i + 3*(C.y - c)*N.k) # type: ignore +f = Function('f') +v.append(N.j - (Integral(f(b)) - C.x**2)*N.k) # type: ignore +upretty_v_8 = """\ + ⎛ 2 ⌠ ⎞ \n\ +j_N + ⎜x_C - ⎮ f(b) db⎟ k_N\n\ + ⎝ ⌡ ⎠ \ +""" +pretty_v_8 = """\ +j_N + / / \\\n\ + | 2 | |\n\ + |x_C - | f(b) db|\n\ + | | |\n\ + \\ / / \ +""" + +v.append(N.i + C.k) # type: ignore +v.append(express(N.i, C)) # type: ignore +v.append((a**2 + b)*N.i + (Integral(f(b)))*N.k) # type: ignore +upretty_v_11 = """\ +⎛ 2 ⎞ ⎛⌠ ⎞ \n\ +⎝a + b⎠ i_N + ⎜⎮ f(b) db⎟ k_N\n\ + ⎝⌡ ⎠ \ +""" +pretty_v_11 = """\ +/ 2 \\ + / / \\\n\ +\\a + b/ i_N| | |\n\ + | | f(b) db|\n\ + | | |\n\ + \\/ / \ +""" + +for x in v: + d.append(x | N.k) # type: ignore +s = 3*N.x**2*C.y # type: ignore +upretty_s = """\ + 2\n\ +3⋅y_C⋅x_N \ +""" +pretty_s = """\ + 2\n\ +3*y_C*x_N \ +""" + +# This is the pretty form for ((a**2 + b)*N.i + 3*(C.y - c)*N.k) | N.k +upretty_d_7 = """\ +⎛ 2 ⎞ \n\ +⎝a + b⎠ (i_N|k_N) + (3⋅y_C - 3⋅c) (k_N|k_N)\ +""" +pretty_d_7 = """\ +/ 2 \\ (i_N|k_N) + (3*y_C - 3*c) (k_N|k_N)\n\ +\\a + b/ \ +""" + + +def test_str_printing(): + assert str(v[0]) == '0' + assert str(v[1]) == 'N.i' + assert str(v[2]) == '(-1)*N.i' + assert str(v[3]) == 'N.i + N.j' + assert str(v[8]) == 'N.j + (C.x**2 - Integral(f(b), b))*N.k' + assert str(v[9]) == 'C.k + N.i' + assert str(s) == '3*C.y*N.x**2' + assert str(d[0]) == '0' + assert str(d[1]) == '(N.i|N.k)' + assert str(d[4]) == 'a*(N.i|N.k)' + assert str(d[5]) == 'a*(N.i|N.k) + (-b)*(N.j|N.k)' + assert str(d[8]) == ('(N.j|N.k) + (C.x**2 - ' + + 'Integral(f(b), b))*(N.k|N.k)') + + +@XFAIL +def test_pretty_printing_ascii(): + assert pretty(v[0]) == '0' + assert pretty(v[1]) == 'i_N' + assert pretty(v[5]) == '(a) i_N + (-b) j_N' + assert pretty(v[8]) == pretty_v_8 + assert pretty(v[2]) == '(-1) i_N' + assert pretty(v[11]) == pretty_v_11 + assert pretty(s) == pretty_s + assert pretty(d[0]) == '(0|0)' + assert pretty(d[5]) == '(a) (i_N|k_N) + (-b) (j_N|k_N)' + assert pretty(d[7]) == pretty_d_7 + assert pretty(d[10]) == '(cos(a)) (i_C|k_N) + (-sin(a)) (j_C|k_N)' + + +def test_pretty_print_unicode_v(): + assert upretty(v[0]) == '0' + assert upretty(v[1]) == 'i_N' + assert upretty(v[5]) == '(a) i_N + (-b) j_N' + # Make sure the printing works in other objects + assert upretty(v[5].args) == '((a) i_N, (-b) j_N)' + assert upretty(v[8]) == upretty_v_8 + assert upretty(v[2]) == '(-1) i_N' + assert upretty(v[11]) == upretty_v_11 + assert upretty(s) == upretty_s + assert upretty(d[0]) == '(0|0)' + assert upretty(d[5]) == '(a) (i_N|k_N) + (-b) (j_N|k_N)' + assert upretty(d[7]) == upretty_d_7 + assert upretty(d[10]) == '(cos(a)) (i_C|k_N) + (-sin(a)) (j_C|k_N)' + + +def test_latex_printing(): + assert latex(v[0]) == '\\mathbf{\\hat{0}}' + assert latex(v[1]) == '\\mathbf{\\hat{i}_{N}}' + assert latex(v[2]) == '- \\mathbf{\\hat{i}_{N}}' + assert latex(v[5]) == ('\\left(a\\right)\\mathbf{\\hat{i}_{N}} + ' + + '\\left(- b\\right)\\mathbf{\\hat{j}_{N}}') + assert latex(v[6]) == ('\\left(\\mathbf{{x}_{N}} + a^{2}\\right)\\mathbf{\\hat{i}_' + + '{N}} + \\mathbf{\\hat{k}_{N}}') + assert latex(v[8]) == ('\\mathbf{\\hat{j}_{N}} + \\left(\\mathbf{{x}_' + + '{C}}^{2} - \\int f{\\left(b \\right)}\\,' + + ' db\\right)\\mathbf{\\hat{k}_{N}}') + assert latex(s) == '3 \\mathbf{{y}_{C}} \\mathbf{{x}_{N}}^{2}' + assert latex(d[0]) == '(\\mathbf{\\hat{0}}|\\mathbf{\\hat{0}})' + assert latex(d[4]) == ('\\left(a\\right)\\left(\\mathbf{\\hat{i}_{N}}{\\middle|}' + + '\\mathbf{\\hat{k}_{N}}\\right)') + assert latex(d[9]) == ('\\left(\\mathbf{\\hat{k}_{C}}{\\middle|}' + + '\\mathbf{\\hat{k}_{N}}\\right) + \\left(' + + '\\mathbf{\\hat{i}_{N}}{\\middle|}\\mathbf{' + + '\\hat{k}_{N}}\\right)') + assert latex(d[11]) == ('\\left(a^{2} + b\\right)\\left(\\mathbf{\\hat{i}_{N}}' + + '{\\middle|}\\mathbf{\\hat{k}_{N}}\\right) + ' + + '\\left(\\int f{\\left(b \\right)}\\, db\\right)\\left(' + + '\\mathbf{\\hat{k}_{N}}{\\middle|}\\mathbf{' + + '\\hat{k}_{N}}\\right)') + +def test_issue_23058(): + from sympy import symbols, sin, cos, pi, UnevaluatedExpr + + delop = Del() + CC_ = CoordSys3D("C") + y = CC_.y + xhat = CC_.i + + t = symbols("t") + ten = symbols("10", positive=True) + eps, mu = 4*pi*ten**(-11), ten**(-5) + + Bx = 2 * ten**(-4) * cos(ten**5 * t) * sin(ten**(-3) * y) + vecB = Bx * xhat + vecE = (1/eps) * Integral(delop.cross(vecB/mu).doit(), t) + vecE = vecE.doit() + + vecB_str = """\ +⎛ ⎛y_C⎞ ⎛ 5 ⎞⎞ \n\ +⎜2⋅sin⎜───⎟⋅cos⎝10 ⋅t⎠⎟ i_C\n\ +⎜ ⎜ 3⎟ ⎟ \n\ +⎜ ⎝10 ⎠ ⎟ \n\ +⎜─────────────────────⎟ \n\ +⎜ 4 ⎟ \n\ +⎝ 10 ⎠ \ +""" + vecE_str = """\ +⎛ 4 ⎛ 5 ⎞ ⎛y_C⎞ ⎞ \n\ +⎜-10 ⋅sin⎝10 ⋅t⎠⋅cos⎜───⎟ ⎟ k_C\n\ +⎜ ⎜ 3⎟ ⎟ \n\ +⎜ ⎝10 ⎠ ⎟ \n\ +⎜─────────────────────────⎟ \n\ +⎝ 2⋅π ⎠ \ +""" + + assert upretty(vecB) == vecB_str + assert upretty(vecE) == vecE_str + + ten = UnevaluatedExpr(10) + eps, mu = 4*pi*ten**(-11), ten**(-5) + + Bx = 2 * ten**(-4) * cos(ten**5 * t) * sin(ten**(-3) * y) + vecB = Bx * xhat + + vecB_str = """\ +⎛ -4 ⎛ 5⎞ ⎛ -3⎞⎞ \n\ +⎝2⋅10 ⋅cos⎝t⋅10 ⎠⋅sin⎝y_C⋅10 ⎠⎠ i_C \ +""" + assert upretty(vecB) == vecB_str + +def test_custom_names(): + A = CoordSys3D('A', vector_names=['x', 'y', 'z'], + variable_names=['i', 'j', 'k']) + assert A.i.__str__() == 'A.i' + assert A.x.__str__() == 'A.x' + assert A.i._pretty_form == 'i_A' + assert A.x._pretty_form == 'x_A' + assert A.i._latex_form == r'\mathbf{{i}_{A}}' + assert A.x._latex_form == r"\mathbf{\hat{x}_{A}}" diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_vector.py b/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_vector.py new file mode 100644 index 0000000000000000000000000000000000000000..daba6d6a02c87b41a8bf801eee9b9045897d0003 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/tests/test_vector.py @@ -0,0 +1,342 @@ +from sympy.core import Rational, S, Add, Mul, I +from sympy.simplify import simplify, trigsimp +from sympy.core.function import (Derivative, Function, diff) +from sympy.core.numbers import pi +from sympy.core.symbol import symbols +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.integrals.integrals import Integral +from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix +from sympy.vector.vector import Vector, BaseVector, VectorAdd, \ + VectorMul, VectorZero +from sympy.vector.coordsysrect import CoordSys3D +from sympy.vector.vector import Cross, Dot, cross +from sympy.testing.pytest import raises +from sympy.vector.kind import VectorKind +from sympy.core.kind import NumberKind +from sympy.testing.pytest import XFAIL + + +C = CoordSys3D('C') + +i, j, k = C.base_vectors() +a, b, c = symbols('a b c') + + +def test_cross(): + v1 = C.x * i + C.z * C.z * j + v2 = C.x * i + C.y * j + C.z * k + assert Cross(v1, v2) == Cross(C.x*C.i + C.z**2*C.j, C.x*C.i + C.y*C.j + C.z*C.k) + assert Cross(v1, v2).doit() == C.z**3*C.i + (-C.x*C.z)*C.j + (C.x*C.y - C.x*C.z**2)*C.k + assert cross(v1, v2) == C.z**3*C.i + (-C.x*C.z)*C.j + (C.x*C.y - C.x*C.z**2)*C.k + assert Cross(v1, v2) == -Cross(v2, v1) + # XXX: Cannot use Cross here. See XFAIL test below: + assert cross(v1, v2) + cross(v2, v1) == Vector.zero + + +@XFAIL +def test_cross_xfail(): + v1 = C.x * i + C.z * C.z * j + v2 = C.x * i + C.y * j + C.z * k + assert Cross(v1, v2) + Cross(v2, v1) == Vector.zero + + +def test_dot(): + v1 = C.x * i + C.z * C.z * j + v2 = C.x * i + C.y * j + C.z * k + assert Dot(v1, v2) == Dot(C.x*C.i + C.z**2*C.j, C.x*C.i + C.y*C.j + C.z*C.k) + assert Dot(v1, v2).doit() == C.x**2 + C.y*C.z**2 + assert Dot(v2, v1).doit() == C.x**2 + C.y*C.z**2 + assert Dot(v1, v2) == Dot(v2, v1) + + +def test_vector_sympy(): + """ + Test whether the Vector framework confirms to the hashing + and equality testing properties of SymPy. + """ + v1 = 3*j + assert v1 == j*3 + assert v1.components == {j: 3} + v2 = 3*i + 4*j + 5*k + v3 = 2*i + 4*j + i + 4*k + k + assert v3 == v2 + assert v3.__hash__() == v2.__hash__() + + +def test_kind(): + assert C.i.kind is VectorKind(NumberKind) + assert C.j.kind is VectorKind(NumberKind) + assert C.k.kind is VectorKind(NumberKind) + + assert C.x.kind is NumberKind + assert C.y.kind is NumberKind + assert C.z.kind is NumberKind + + assert Mul._kind_dispatcher(NumberKind, VectorKind(NumberKind)) is VectorKind(NumberKind) + assert Mul(2, C.i).kind is VectorKind(NumberKind) + + v1 = C.x * i + C.z * C.z * j + v2 = C.x * i + C.y * j + C.z * k + assert v1.kind is VectorKind(NumberKind) + assert v2.kind is VectorKind(NumberKind) + + assert (v1 + v2).kind is VectorKind(NumberKind) + assert Add(v1, v2).kind is VectorKind(NumberKind) + assert Cross(v1, v2).doit().kind is VectorKind(NumberKind) + assert VectorAdd(v1, v2).kind is VectorKind(NumberKind) + assert VectorMul(2, v1).kind is VectorKind(NumberKind) + assert VectorZero().kind is VectorKind(NumberKind) + + assert v1.projection(v2).kind is VectorKind(NumberKind) + assert v2.projection(v1).kind is VectorKind(NumberKind) + + +def test_vectoradd(): + assert isinstance(Add(C.i, C.j), VectorAdd) + v1 = C.x * i + C.z * C.z * j + v2 = C.x * i + C.y * j + C.z * k + assert isinstance(Add(v1, v2), VectorAdd) + + # https://github.com/sympy/sympy/issues/26121 + + E = Matrix([C.i, C.j, C.k]).T + a = Matrix([1, 2, 3]) + av = E*a + + assert av[0].kind == VectorKind() + assert isinstance(av[0], VectorAdd) + + +def test_vector(): + assert isinstance(i, BaseVector) + assert i != j + assert j != k + assert k != i + assert i - i == Vector.zero + assert i + Vector.zero == i + assert i - Vector.zero == i + assert Vector.zero != 0 + assert -Vector.zero == Vector.zero + + v1 = a*i + b*j + c*k + v2 = a**2*i + b**2*j + c**2*k + v3 = v1 + v2 + v4 = 2 * v1 + v5 = a * i + + assert isinstance(v1, VectorAdd) + assert v1 - v1 == Vector.zero + assert v1 + Vector.zero == v1 + assert v1.dot(i) == a + assert v1.dot(j) == b + assert v1.dot(k) == c + assert i.dot(v2) == a**2 + assert j.dot(v2) == b**2 + assert k.dot(v2) == c**2 + assert v3.dot(i) == a**2 + a + assert v3.dot(j) == b**2 + b + assert v3.dot(k) == c**2 + c + + assert v1 + v2 == v2 + v1 + assert v1 - v2 == -1 * (v2 - v1) + assert a * v1 == v1 * a + + assert isinstance(v5, VectorMul) + assert v5.base_vector == i + assert v5.measure_number == a + assert isinstance(v4, Vector) + assert isinstance(v4, VectorAdd) + assert isinstance(v4, Vector) + assert isinstance(Vector.zero, VectorZero) + assert isinstance(Vector.zero, Vector) + assert isinstance(v1 * 0, VectorZero) + + assert v1.to_matrix(C) == Matrix([[a], [b], [c]]) + + assert i.components == {i: 1} + assert v5.components == {i: a} + assert v1.components == {i: a, j: b, k: c} + + assert VectorAdd(v1, Vector.zero) == v1 + assert VectorMul(a, v1) == v1*a + assert VectorMul(1, i) == i + assert VectorAdd(v1, Vector.zero) == v1 + assert VectorMul(0, Vector.zero) == Vector.zero + raises(TypeError, lambda: v1.outer(1)) + raises(TypeError, lambda: v1.dot(1)) + + +def test_vector_magnitude_normalize(): + assert Vector.zero.magnitude() == 0 + assert Vector.zero.normalize() == Vector.zero + + assert i.magnitude() == 1 + assert j.magnitude() == 1 + assert k.magnitude() == 1 + assert i.normalize() == i + assert j.normalize() == j + assert k.normalize() == k + + v1 = a * i + assert v1.normalize() == (a/sqrt(a**2))*i + assert v1.magnitude() == sqrt(a**2) + + v2 = a*i + b*j + c*k + assert v2.magnitude() == sqrt(a**2 + b**2 + c**2) + assert v2.normalize() == v2 / v2.magnitude() + + v3 = i + j + assert v3.normalize() == (sqrt(2)/2)*C.i + (sqrt(2)/2)*C.j + + +def test_vector_simplify(): + A, s, k, m = symbols('A, s, k, m') + + test1 = (1 / a + 1 / b) * i + assert (test1 & i) != (a + b) / (a * b) + test1 = simplify(test1) + assert (test1 & i) == (a + b) / (a * b) + assert test1.simplify() == simplify(test1) + + test2 = (A**2 * s**4 / (4 * pi * k * m**3)) * i + test2 = simplify(test2) + assert (test2 & i) == (A**2 * s**4 / (4 * pi * k * m**3)) + + test3 = ((4 + 4 * a - 2 * (2 + 2 * a)) / (2 + 2 * a)) * i + test3 = simplify(test3) + assert (test3 & i) == 0 + + test4 = ((-4 * a * b**2 - 2 * b**3 - 2 * a**2 * b) / (a + b)**2) * i + test4 = simplify(test4) + assert (test4 & i) == -2 * b + + v = (sin(a)+cos(a))**2*i - j + assert trigsimp(v) == (2*sin(a + pi/4)**2)*i + (-1)*j + assert trigsimp(v) == v.trigsimp() + + assert simplify(Vector.zero) == Vector.zero + + +def test_vector_equals(): + assert (2*i).equals(j) is False + assert i.equals(i) is True + + # https://github.com/sympy/sympy/issues/25915 + A = (sqrt(2) + sqrt(6)) / sqrt(sqrt(3) + 2) + assert (A*i).equals(2*i) is True + assert (A*i).equals(3*i) is False + + # Test comparing vectors in different coordinate systems + D = C.orient_new_axis('D', pi/2, C.k) + assert (D.i).equals(C.j) is True + assert (D.i).equals(C.i) is False + + +def test_vector_conjugate(): + # https://github.com/sympy/sympy/issues/27094 + assert (I*i + (1 + I)*j + 2*k).conjugate() == -I*i + (1 - I)*j + 2*k + + +def test_vector_dot(): + assert i.dot(Vector.zero) == 0 + assert Vector.zero.dot(i) == 0 + assert i & Vector.zero == 0 + + assert i.dot(i) == 1 + assert i.dot(j) == 0 + assert i.dot(k) == 0 + assert i & i == 1 + assert i & j == 0 + assert i & k == 0 + + assert j.dot(i) == 0 + assert j.dot(j) == 1 + assert j.dot(k) == 0 + assert j & i == 0 + assert j & j == 1 + assert j & k == 0 + + assert k.dot(i) == 0 + assert k.dot(j) == 0 + assert k.dot(k) == 1 + assert k & i == 0 + assert k & j == 0 + assert k & k == 1 + + raises(TypeError, lambda: k.dot(1)) + + +def test_vector_cross(): + assert i.cross(Vector.zero) == Vector.zero + assert Vector.zero.cross(i) == Vector.zero + + assert i.cross(i) == Vector.zero + assert i.cross(j) == k + assert i.cross(k) == -j + assert i ^ i == Vector.zero + assert i ^ j == k + assert i ^ k == -j + + assert j.cross(i) == -k + assert j.cross(j) == Vector.zero + assert j.cross(k) == i + assert j ^ i == -k + assert j ^ j == Vector.zero + assert j ^ k == i + + assert k.cross(i) == j + assert k.cross(j) == -i + assert k.cross(k) == Vector.zero + assert k ^ i == j + assert k ^ j == -i + assert k ^ k == Vector.zero + + assert k.cross(1) == Cross(k, 1) + + +def test_projection(): + v1 = i + j + k + v2 = 3*i + 4*j + v3 = 0*i + 0*j + assert v1.projection(v1) == i + j + k + assert v1.projection(v2) == Rational(7, 3)*C.i + Rational(7, 3)*C.j + Rational(7, 3)*C.k + assert v1.projection(v1, scalar=True) == S.One + assert v1.projection(v2, scalar=True) == Rational(7, 3) + assert v3.projection(v1) == Vector.zero + assert v3.projection(v1, scalar=True) == S.Zero + + +def test_vector_diff_integrate(): + f = Function('f') + v = f(a)*C.i + a**2*C.j - C.k + assert Derivative(v, a) == Derivative((f(a))*C.i + + a**2*C.j + (-1)*C.k, a) + assert (diff(v, a) == v.diff(a) == Derivative(v, a).doit() == + (Derivative(f(a), a))*C.i + 2*a*C.j) + assert (Integral(v, a) == (Integral(f(a), a))*C.i + + (Integral(a**2, a))*C.j + (Integral(-1, a))*C.k) + + +def test_vector_args(): + raises(ValueError, lambda: BaseVector(3, C)) + raises(TypeError, lambda: BaseVector(0, Vector.zero)) + + +def test_srepr(): + from sympy.printing.repr import srepr + res = "CoordSys3D(Str('C'), Tuple(ImmutableDenseMatrix([[Integer(1), "\ + "Integer(0), Integer(0)], [Integer(0), Integer(1), Integer(0)], "\ + "[Integer(0), Integer(0), Integer(1)]]), VectorZero())).i" + assert srepr(C.i) == res + + +def test_scalar(): + from sympy.vector import CoordSys3D + C = CoordSys3D('C') + v1 = 3*C.i + 4*C.j + 5*C.k + v2 = 3*C.i - 4*C.j + 5*C.k + assert v1.is_Vector is True + assert v1.is_scalar is False + assert (v1.dot(v2)).is_scalar is True + assert (v1.cross(v2)).is_scalar is False diff --git a/.venv/lib/python3.12/site-packages/sympy/vector/vector.py b/.venv/lib/python3.12/site-packages/sympy/vector/vector.py new file mode 100644 index 0000000000000000000000000000000000000000..c035ef48d2edd511f6cdbca19e965d99a2c8c66e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/sympy/vector/vector.py @@ -0,0 +1,714 @@ +from __future__ import annotations +from itertools import product + +from sympy.core import Add, Basic +from sympy.core.assumptions import StdFactKB +from sympy.core.expr import AtomicExpr, Expr +from sympy.core.power import Pow +from sympy.core.singleton import S +from sympy.core.sorting import default_sort_key +from sympy.core.sympify import sympify +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix +from sympy.vector.basisdependent import (BasisDependentZero, + BasisDependent, BasisDependentMul, BasisDependentAdd) +from sympy.vector.coordsysrect import CoordSys3D +from sympy.vector.dyadic import Dyadic, BaseDyadic, DyadicAdd +from sympy.vector.kind import VectorKind + + +class Vector(BasisDependent): + """ + Super class for all Vector classes. + Ideally, neither this class nor any of its subclasses should be + instantiated by the user. + """ + + is_scalar = False + is_Vector = True + _op_priority = 12.0 + + _expr_type: type[Vector] + _mul_func: type[Vector] + _add_func: type[Vector] + _zero_func: type[Vector] + _base_func: type[Vector] + zero: VectorZero + + kind: VectorKind = VectorKind() + + @property + def components(self): + """ + Returns the components of this vector in the form of a + Python dictionary mapping BaseVector instances to the + corresponding measure numbers. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> C = CoordSys3D('C') + >>> v = 3*C.i + 4*C.j + 5*C.k + >>> v.components + {C.i: 3, C.j: 4, C.k: 5} + + """ + # The '_components' attribute is defined according to the + # subclass of Vector the instance belongs to. + return self._components + + def magnitude(self): + """ + Returns the magnitude of this vector. + """ + return sqrt(self & self) + + def normalize(self): + """ + Returns the normalized version of this vector. + """ + return self / self.magnitude() + + def equals(self, other): + """ + Check if ``self`` and ``other`` are identically equal vectors. + + Explanation + =========== + + Checks if two vector expressions are equal for all possible values of + the symbols present in the expressions. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> from sympy.abc import x, y + >>> from sympy import pi + >>> C = CoordSys3D('C') + + Compare vectors that are equal or not: + + >>> C.i.equals(C.j) + False + >>> C.i.equals(C.i) + True + + These two vectors are equal if `x = y` but are not identically equal + as expressions since for some values of `x` and `y` they are unequal: + + >>> v1 = x*C.i + C.j + >>> v2 = y*C.i + C.j + >>> v1.equals(v1) + True + >>> v1.equals(v2) + False + + Vectors from different coordinate systems can be compared: + + >>> D = C.orient_new_axis('D', pi/2, C.i) + >>> D.j.equals(C.j) + False + >>> D.j.equals(C.k) + True + + Parameters + ========== + + other: Vector + The other vector expression to compare with. + + Returns + ======= + + ``True``, ``False`` or ``None``. A return value of ``True`` indicates + that the two vectors are identically equal. A return value of ``False`` + indicates that they are not. In some cases it is not possible to + determine if the two vectors are identically equal and ``None`` is + returned. + + See Also + ======== + + sympy.core.expr.Expr.equals + """ + diff = self - other + diff_mag2 = diff.dot(diff) + return diff_mag2.equals(0) + + def dot(self, other): + """ + Returns the dot product of this Vector, either with another + Vector, or a Dyadic, or a Del operator. + If 'other' is a Vector, returns the dot product scalar (SymPy + expression). + If 'other' is a Dyadic, the dot product is returned as a Vector. + If 'other' is an instance of Del, returns the directional + derivative operator as a Python function. If this function is + applied to a scalar expression, it returns the directional + derivative of the scalar field wrt this Vector. + + Parameters + ========== + + other: Vector/Dyadic/Del + The Vector or Dyadic we are dotting with, or a Del operator . + + Examples + ======== + + >>> from sympy.vector import CoordSys3D, Del + >>> C = CoordSys3D('C') + >>> delop = Del() + >>> C.i.dot(C.j) + 0 + >>> C.i & C.i + 1 + >>> v = 3*C.i + 4*C.j + 5*C.k + >>> v.dot(C.k) + 5 + >>> (C.i & delop)(C.x*C.y*C.z) + C.y*C.z + >>> d = C.i.outer(C.i) + >>> C.i.dot(d) + C.i + + """ + + # Check special cases + if isinstance(other, Dyadic): + if isinstance(self, VectorZero): + return Vector.zero + outvec = Vector.zero + for k, v in other.components.items(): + vect_dot = k.args[0].dot(self) + outvec += vect_dot * v * k.args[1] + return outvec + from sympy.vector.deloperator import Del + if not isinstance(other, (Del, Vector)): + raise TypeError(str(other) + " is not a vector, dyadic or " + + "del operator") + + # Check if the other is a del operator + if isinstance(other, Del): + def directional_derivative(field): + from sympy.vector.functions import directional_derivative + return directional_derivative(field, self) + return directional_derivative + + return dot(self, other) + + def __and__(self, other): + return self.dot(other) + + __and__.__doc__ = dot.__doc__ + + def cross(self, other): + """ + Returns the cross product of this Vector with another Vector or + Dyadic instance. + The cross product is a Vector, if 'other' is a Vector. If 'other' + is a Dyadic, this returns a Dyadic instance. + + Parameters + ========== + + other: Vector/Dyadic + The Vector or Dyadic we are crossing with. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> C = CoordSys3D('C') + >>> C.i.cross(C.j) + C.k + >>> C.i ^ C.i + 0 + >>> v = 3*C.i + 4*C.j + 5*C.k + >>> v ^ C.i + 5*C.j + (-4)*C.k + >>> d = C.i.outer(C.i) + >>> C.j.cross(d) + (-1)*(C.k|C.i) + + """ + + # Check special cases + if isinstance(other, Dyadic): + if isinstance(self, VectorZero): + return Dyadic.zero + outdyad = Dyadic.zero + for k, v in other.components.items(): + cross_product = self.cross(k.args[0]) + outer = cross_product.outer(k.args[1]) + outdyad += v * outer + return outdyad + + return cross(self, other) + + def __xor__(self, other): + return self.cross(other) + + __xor__.__doc__ = cross.__doc__ + + def outer(self, other): + """ + Returns the outer product of this vector with another, in the + form of a Dyadic instance. + + Parameters + ========== + + other : Vector + The Vector with respect to which the outer product is to + be computed. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> N = CoordSys3D('N') + >>> N.i.outer(N.j) + (N.i|N.j) + + """ + + # Handle the special cases + if not isinstance(other, Vector): + raise TypeError("Invalid operand for outer product") + elif (isinstance(self, VectorZero) or + isinstance(other, VectorZero)): + return Dyadic.zero + + # Iterate over components of both the vectors to generate + # the required Dyadic instance + args = [(v1 * v2) * BaseDyadic(k1, k2) for (k1, v1), (k2, v2) + in product(self.components.items(), other.components.items())] + + return DyadicAdd(*args) + + def projection(self, other, scalar=False): + """ + Returns the vector or scalar projection of the 'other' on 'self'. + + Examples + ======== + + >>> from sympy.vector.coordsysrect import CoordSys3D + >>> C = CoordSys3D('C') + >>> i, j, k = C.base_vectors() + >>> v1 = i + j + k + >>> v2 = 3*i + 4*j + >>> v1.projection(v2) + 7/3*C.i + 7/3*C.j + 7/3*C.k + >>> v1.projection(v2, scalar=True) + 7/3 + + """ + if self.equals(Vector.zero): + return S.Zero if scalar else Vector.zero + + if scalar: + return self.dot(other) / self.dot(self) + else: + return self.dot(other) / self.dot(self) * self + + @property + def _projections(self): + """ + Returns the components of this vector but the output includes + also zero values components. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D, Vector + >>> C = CoordSys3D('C') + >>> v1 = 3*C.i + 4*C.j + 5*C.k + >>> v1._projections + (3, 4, 5) + >>> v2 = C.x*C.y*C.z*C.i + >>> v2._projections + (C.x*C.y*C.z, 0, 0) + >>> v3 = Vector.zero + >>> v3._projections + (0, 0, 0) + """ + + from sympy.vector.operators import _get_coord_systems + if isinstance(self, VectorZero): + return (S.Zero, S.Zero, S.Zero) + base_vec = next(iter(_get_coord_systems(self))).base_vectors() + return tuple([self.dot(i) for i in base_vec]) + + def __or__(self, other): + return self.outer(other) + + __or__.__doc__ = outer.__doc__ + + def to_matrix(self, system): + """ + Returns the matrix form of this vector with respect to the + specified coordinate system. + + Parameters + ========== + + system : CoordSys3D + The system wrt which the matrix form is to be computed + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> C = CoordSys3D('C') + >>> from sympy.abc import a, b, c + >>> v = a*C.i + b*C.j + c*C.k + >>> v.to_matrix(C) + Matrix([ + [a], + [b], + [c]]) + + """ + + return Matrix([self.dot(unit_vec) for unit_vec in + system.base_vectors()]) + + def separate(self): + """ + The constituents of this vector in different coordinate systems, + as per its definition. + + Returns a dict mapping each CoordSys3D to the corresponding + constituent Vector. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> R1 = CoordSys3D('R1') + >>> R2 = CoordSys3D('R2') + >>> v = R1.i + R2.i + >>> v.separate() == {R1: R1.i, R2: R2.i} + True + + """ + + parts = {} + for vect, measure in self.components.items(): + parts[vect.system] = (parts.get(vect.system, Vector.zero) + + vect * measure) + return parts + + def _div_helper(one, other): + """ Helper for division involving vectors. """ + if isinstance(one, Vector) and isinstance(other, Vector): + raise TypeError("Cannot divide two vectors") + elif isinstance(one, Vector): + if other == S.Zero: + raise ValueError("Cannot divide a vector by zero") + return VectorMul(one, Pow(other, S.NegativeOne)) + else: + raise TypeError("Invalid division involving a vector") + +# The following is adapted from the matrices.expressions.matexpr file + +def get_postprocessor(cls): + def _postprocessor(expr): + vec_class = {Add: VectorAdd}[cls] + vectors = [] + for term in expr.args: + if isinstance(term.kind, VectorKind): + vectors.append(term) + + if vec_class == VectorAdd: + return VectorAdd(*vectors).doit(deep=False) + return _postprocessor + + +Basic._constructor_postprocessor_mapping[Vector] = { + "Add": [get_postprocessor(Add)], +} + +class BaseVector(Vector, AtomicExpr): + """ + Class to denote a base vector. + + """ + + def __new__(cls, index, system, pretty_str=None, latex_str=None): + if pretty_str is None: + pretty_str = "x{}".format(index) + if latex_str is None: + latex_str = "x_{}".format(index) + pretty_str = str(pretty_str) + latex_str = str(latex_str) + # Verify arguments + if index not in range(0, 3): + raise ValueError("index must be 0, 1 or 2") + if not isinstance(system, CoordSys3D): + raise TypeError("system should be a CoordSys3D") + name = system._vector_names[index] + # Initialize an object + obj = super().__new__(cls, S(index), system) + # Assign important attributes + obj._base_instance = obj + obj._components = {obj: S.One} + obj._measure_number = S.One + obj._name = system._name + '.' + name + obj._pretty_form = '' + pretty_str + obj._latex_form = latex_str + obj._system = system + # The _id is used for printing purposes + obj._id = (index, system) + assumptions = {'commutative': True} + obj._assumptions = StdFactKB(assumptions) + + # This attr is used for re-expression to one of the systems + # involved in the definition of the Vector. Applies to + # VectorMul and VectorAdd too. + obj._sys = system + + return obj + + @property + def system(self): + return self._system + + def _sympystr(self, printer): + return self._name + + def _sympyrepr(self, printer): + index, system = self._id + return printer._print(system) + '.' + system._vector_names[index] + + @property + def free_symbols(self): + return {self} + + def _eval_conjugate(self): + return self + + +class VectorAdd(BasisDependentAdd, Vector): + """ + Class to denote sum of Vector instances. + """ + + def __new__(cls, *args, **options): + obj = BasisDependentAdd.__new__(cls, *args, **options) + return obj + + def _sympystr(self, printer): + ret_str = '' + items = list(self.separate().items()) + items.sort(key=lambda x: x[0].__str__()) + for system, vect in items: + base_vects = system.base_vectors() + for x in base_vects: + if x in vect.components: + temp_vect = self.components[x] * x + ret_str += printer._print(temp_vect) + " + " + return ret_str[:-3] + + +class VectorMul(BasisDependentMul, Vector): + """ + Class to denote products of scalars and BaseVectors. + """ + + def __new__(cls, *args, **options): + obj = BasisDependentMul.__new__(cls, *args, **options) + return obj + + @property + def base_vector(self): + """ The BaseVector involved in the product. """ + return self._base_instance + + @property + def measure_number(self): + """ The scalar expression involved in the definition of + this VectorMul. + """ + return self._measure_number + + +class VectorZero(BasisDependentZero, Vector): + """ + Class to denote a zero vector + """ + + _op_priority = 12.1 + _pretty_form = '0' + _latex_form = r'\mathbf{\hat{0}}' + + def __new__(cls): + obj = BasisDependentZero.__new__(cls) + return obj + + +class Cross(Vector): + """ + Represents unevaluated Cross product. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D, Cross + >>> R = CoordSys3D('R') + >>> v1 = R.i + R.j + R.k + >>> v2 = R.x * R.i + R.y * R.j + R.z * R.k + >>> Cross(v1, v2) + Cross(R.i + R.j + R.k, R.x*R.i + R.y*R.j + R.z*R.k) + >>> Cross(v1, v2).doit() + (-R.y + R.z)*R.i + (R.x - R.z)*R.j + (-R.x + R.y)*R.k + + """ + + def __new__(cls, expr1, expr2): + expr1 = sympify(expr1) + expr2 = sympify(expr2) + if default_sort_key(expr1) > default_sort_key(expr2): + return -Cross(expr2, expr1) + obj = Expr.__new__(cls, expr1, expr2) + obj._expr1 = expr1 + obj._expr2 = expr2 + return obj + + def doit(self, **hints): + return cross(self._expr1, self._expr2) + + +class Dot(Expr): + """ + Represents unevaluated Dot product. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D, Dot + >>> from sympy import symbols + >>> R = CoordSys3D('R') + >>> a, b, c = symbols('a b c') + >>> v1 = R.i + R.j + R.k + >>> v2 = a * R.i + b * R.j + c * R.k + >>> Dot(v1, v2) + Dot(R.i + R.j + R.k, a*R.i + b*R.j + c*R.k) + >>> Dot(v1, v2).doit() + a + b + c + + """ + + def __new__(cls, expr1, expr2): + expr1 = sympify(expr1) + expr2 = sympify(expr2) + expr1, expr2 = sorted([expr1, expr2], key=default_sort_key) + obj = Expr.__new__(cls, expr1, expr2) + obj._expr1 = expr1 + obj._expr2 = expr2 + return obj + + def doit(self, **hints): + return dot(self._expr1, self._expr2) + + +def cross(vect1, vect2): + """ + Returns cross product of two vectors. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> from sympy.vector.vector import cross + >>> R = CoordSys3D('R') + >>> v1 = R.i + R.j + R.k + >>> v2 = R.x * R.i + R.y * R.j + R.z * R.k + >>> cross(v1, v2) + (-R.y + R.z)*R.i + (R.x - R.z)*R.j + (-R.x + R.y)*R.k + + """ + if isinstance(vect1, Add): + return VectorAdd.fromiter(cross(i, vect2) for i in vect1.args) + if isinstance(vect2, Add): + return VectorAdd.fromiter(cross(vect1, i) for i in vect2.args) + if isinstance(vect1, BaseVector) and isinstance(vect2, BaseVector): + if vect1._sys == vect2._sys: + n1 = vect1.args[0] + n2 = vect2.args[0] + if n1 == n2: + return Vector.zero + n3 = ({0,1,2}.difference({n1, n2})).pop() + sign = 1 if ((n1 + 1) % 3 == n2) else -1 + return sign*vect1._sys.base_vectors()[n3] + from .functions import express + try: + v = express(vect1, vect2._sys) + except ValueError: + return Cross(vect1, vect2) + else: + return cross(v, vect2) + if isinstance(vect1, VectorZero) or isinstance(vect2, VectorZero): + return Vector.zero + if isinstance(vect1, VectorMul): + v1, m1 = next(iter(vect1.components.items())) + return m1*cross(v1, vect2) + if isinstance(vect2, VectorMul): + v2, m2 = next(iter(vect2.components.items())) + return m2*cross(vect1, v2) + + return Cross(vect1, vect2) + + +def dot(vect1, vect2): + """ + Returns dot product of two vectors. + + Examples + ======== + + >>> from sympy.vector import CoordSys3D + >>> from sympy.vector.vector import dot + >>> R = CoordSys3D('R') + >>> v1 = R.i + R.j + R.k + >>> v2 = R.x * R.i + R.y * R.j + R.z * R.k + >>> dot(v1, v2) + R.x + R.y + R.z + + """ + if isinstance(vect1, Add): + return Add.fromiter(dot(i, vect2) for i in vect1.args) + if isinstance(vect2, Add): + return Add.fromiter(dot(vect1, i) for i in vect2.args) + if isinstance(vect1, BaseVector) and isinstance(vect2, BaseVector): + if vect1._sys == vect2._sys: + return S.One if vect1 == vect2 else S.Zero + from .functions import express + try: + v = express(vect2, vect1._sys) + except ValueError: + return Dot(vect1, vect2) + else: + return dot(vect1, v) + if isinstance(vect1, VectorZero) or isinstance(vect2, VectorZero): + return S.Zero + if isinstance(vect1, VectorMul): + v1, m1 = next(iter(vect1.components.items())) + return m1*dot(v1, vect2) + if isinstance(vect2, VectorMul): + v2, m2 = next(iter(vect2.components.items())) + return m2*dot(vect1, v2) + + return Dot(vect1, vect2) + + +Vector._expr_type = Vector +Vector._mul_func = VectorMul +Vector._add_func = VectorAdd +Vector._zero_func = VectorZero +Vector._base_func = BaseVector +Vector.zero = VectorZero() diff --git a/.venv/lib/python3.12/site-packages/tests/__init__.py b/.venv/lib/python3.12/site-packages/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5209db4e3f0e28d8529d3f62e84533faec3b9c38 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tests/__init__.py @@ -0,0 +1,38 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from ultralytics.cfg import TASK2DATA, TASK2MODEL, TASKS +from ultralytics.utils import ASSETS, WEIGHTS_DIR, checks + +# Shared test constants for model, config, data source, and environment info +MODEL = WEIGHTS_DIR / "path with spaces" / "yolo26n.pt" # path with spaces to test path handling +CFG = "yolo26n.yaml" +SOURCE = ASSETS / "bus.jpg" +SOURCES_LIST = [ASSETS / "bus.jpg", ASSETS, ASSETS / "*", ASSETS / "**/*.jpg"] # file, dir, and glob patterns +CUDA_IS_AVAILABLE = checks.cuda_is_available() +CUDA_DEVICE_COUNT = checks.cuda_device_count() +TASK_MODEL_DATA = sorted( + [(task, WEIGHTS_DIR / TASK2MODEL[task], TASK2DATA[task]) for task in TASKS] +) # (task, model, data) tuples +MODELS = sorted([*list(TASK2MODEL.values()), "yolo11n-grayscale.pt"]) # task models plus grayscale variant +SOLUTION_ASSETS = { + "boats": "boats.jpg", + "demo_video": "solutions_ci_demo.mp4", + "crop_video": "decelera_landscape_min.mov", + "pose_video": "solution_ci_pose_demo.mp4", + "parking_video": "solution_ci_parking_demo.mp4", + "vertical_video": "solution_vertical_demo.mp4", + "track_video": "decelera_portrait_min.mov", + "parking_areas": "solution_ci_parking_areas.json", + "parking_model": "solutions_ci_parking_model.pt", + "similarity_images": "4-imgs-similaritysearch.zip", +} + +__all__ = ( + "CFG", + "CUDA_DEVICE_COUNT", + "CUDA_IS_AVAILABLE", + "MODEL", + "SOLUTION_ASSETS", + "SOURCE", + "SOURCES_LIST", +) diff --git a/.venv/lib/python3.12/site-packages/tests/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/tests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2751e63083fe6c867267fe8bac4ed8bda7ca684 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/tests/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/tests/__pycache__/cache_test_assets.cpython-312.pyc b/.venv/lib/python3.12/site-packages/tests/__pycache__/cache_test_assets.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31a189d040ccdd78a88820ae38ae1ecd148af143 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/tests/__pycache__/cache_test_assets.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/tests/__pycache__/conftest.cpython-312.pyc b/.venv/lib/python3.12/site-packages/tests/__pycache__/conftest.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..835f7bc87d792de854c53a4d9cbe7e31d6f10ff2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/tests/__pycache__/conftest.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/tests/__pycache__/test_cli.cpython-312.pyc b/.venv/lib/python3.12/site-packages/tests/__pycache__/test_cli.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c91e322cf3448b9000a02c260f06ede95fa017fb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/tests/__pycache__/test_cli.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/tests/__pycache__/test_cuda.cpython-312.pyc b/.venv/lib/python3.12/site-packages/tests/__pycache__/test_cuda.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9edcbd89332be64b7614cb5c681f4e136a34663 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/tests/__pycache__/test_cuda.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/tests/__pycache__/test_engine.cpython-312.pyc b/.venv/lib/python3.12/site-packages/tests/__pycache__/test_engine.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f97aa4a508634c0c78c692c8fbb84712a8cf57d4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/tests/__pycache__/test_engine.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/tests/__pycache__/test_exports.cpython-312.pyc b/.venv/lib/python3.12/site-packages/tests/__pycache__/test_exports.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4ce44ccb46e7f9c4ef9e1ec7e399b6dba99c9f9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/tests/__pycache__/test_exports.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/tests/__pycache__/test_integrations.cpython-312.pyc b/.venv/lib/python3.12/site-packages/tests/__pycache__/test_integrations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d26d5e241dd662e0c771debda733f1319c28937d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/tests/__pycache__/test_integrations.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/tests/__pycache__/test_ndjson_converter.cpython-312.pyc b/.venv/lib/python3.12/site-packages/tests/__pycache__/test_ndjson_converter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f017d5a7058f71f8ec15f932fb018084c7a1e639 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/tests/__pycache__/test_ndjson_converter.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/tests/__pycache__/test_python.cpython-312.pyc b/.venv/lib/python3.12/site-packages/tests/__pycache__/test_python.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7816c74cd83c9fc2b3eacb988da96cc9fdc72f70 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tests/__pycache__/test_python.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa8028774e6a24a9bed8e0122192e9556c763b487a6dad89a5dd6f2049d56d68 +size 160295 diff --git a/.venv/lib/python3.12/site-packages/tests/__pycache__/test_solutions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/tests/__pycache__/test_solutions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..073ca5fd7f4f7fca61a6fa7844a465dda854a48c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/tests/__pycache__/test_solutions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/tests/cache_test_assets.py b/.venv/lib/python3.12/site-packages/tests/cache_test_assets.py new file mode 100644 index 0000000000000000000000000000000000000000..0ab0980c2d53599404ce7c21e891408035798e28 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tests/cache_test_assets.py @@ -0,0 +1,120 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Pre-download shared test assets to avoid race conditions under pytest-xdist. + +Run this script once before `pytest -n auto` to ensure all model weights, +datasets, and solution assets are already cached locally. Each xdist worker +can then reuse existing files instead of competing to download the same remote resources. +""" + +import shutil +import sys +from argparse import ArgumentParser +from pathlib import Path + +import torch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from tests import MODEL, SOLUTION_ASSETS +from ultralytics.cfg import TASK2CALIBRATIONDATA, TASK2DATA, TASK2MODEL +from ultralytics.data.utils import check_cls_dataset, check_det_dataset +from ultralytics.utils import ARM64, ASSETS_URL, DATASETS_DIR, IS_RASPBERRYPI, LINUX, LOGGER, WEIGHTS_DIR, checks +from ultralytics.utils.downloads import attempt_download_asset, safe_download + +COMMON_WEIGHTS = [ + *TASK2MODEL.values(), + "yolo11n-grayscale.pt", + "rtdetr-l.pt", + "FastSAM-s.pt", + "mobile_sam.pt", + "mobileclip_blt.ts", + "yolov8s-world.pt", + "yolov8s-worldv2.pt", + "yoloe-11s-seg.pt", + "yoloe-11s-seg-pf.pt", + "yolo26s.pt", + "yolo26s-seg.pt", + "yolo26s-pose.pt", + "yolo26s-obb.pt", +] + +SLOW_WEIGHTS = [ + "sam2.1_b.pt", +] + +DATASETS = [ + *TASK2DATA.values(), + *TASK2CALIBRATIONDATA.values(), + "coco8-grayscale.yaml", + "coco8-multispectral.yaml", + "coco12-formats.yaml", +] + + +def cache_weights(slow: bool = False) -> None: + """Download all model weights used by tests.""" + LOGGER.info("[cache] Downloading model weights ...") + weights = COMMON_WEIGHTS + (SLOW_WEIGHTS if slow else []) + for w in weights: + attempt_download_asset(WEIGHTS_DIR / w) + if not MODEL.exists(): + MODEL.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(WEIGHTS_DIR / "yolo26n.pt", MODEL) + LOGGER.info("[cache] Weights done.") + + +def cache_datasets() -> None: + """Download / extract all datasets used by tests.""" + LOGGER.info("[cache] Downloading datasets ...") + for ds in DATASETS: + if ds.startswith("imagenet"): + check_cls_dataset(ds) + else: + check_det_dataset(ds, autodownload=True) + safe_download(f"{ASSETS_URL}/instances_val2017.json", dir=DATASETS_DIR / "annotations") + LOGGER.info("[cache] Datasets done.") + + +def cache_solution_assets() -> None: + """Download solution test assets (videos, parking json, etc.).""" + LOGGER.info("[cache] Downloading solution assets ...") + cache_dir = WEIGHTS_DIR / "solution_assets" + cache_dir.mkdir(parents=True, exist_ok=True) + for asset in SOLUTION_ASSETS.values(): + dst = cache_dir / asset + if not dst.exists(): + safe_download(url=f"{ASSETS_URL}/{asset}", dir=cache_dir) + LOGGER.info("[cache] Solution assets done.") + + +def cache_clip_model() -> None: + """Download the CLIP text encoder before xdist workers can race on the shared cache file.""" + if IS_RASPBERRYPI or (checks.IS_PYTHON_3_8 and LINUX and ARM64): + return + + LOGGER.info("[cache] Downloading CLIP text encoder ...") + from ultralytics.nn.text_model import CLIP + + model = CLIP("ViT-B/32", device=torch.device("cpu")) + del model + LOGGER.info("[cache] CLIP text encoder done.") + + +def parse_args() -> bool: + """Parse command-line arguments.""" + parser = ArgumentParser(description="Pre-download test assets.") + parser.add_argument("--slow", action="store_true", help="Include assets used only by slow tests.") + return parser.parse_args().slow + + +def main() -> None: + """Main function to orchestrate caching of all test assets.""" + slow = parse_args() + cache_weights(slow=slow) + cache_datasets() + cache_solution_assets() + cache_clip_model() + LOGGER.info("[cache] All test assets are ready.") + + +if __name__ == "__main__": + main() diff --git a/.venv/lib/python3.12/site-packages/tests/conftest.py b/.venv/lib/python3.12/site-packages/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..cae861945b8e465d1dd2a66b0c1ec1bf069d01e9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tests/conftest.py @@ -0,0 +1,140 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import shutil +from pathlib import Path + +import numpy.testing # noqa: F401 # Pre-import before any test can corrupt numpy via in-place upgrade +import pytest + + +@pytest.fixture(scope="session") +def solution_assets(): + """Return cached solution asset paths by name.""" + from tests import SOLUTION_ASSETS + from ultralytics.utils import ASSETS_URL, WEIGHTS_DIR + from ultralytics.utils.downloads import safe_download + + cache_dir = WEIGHTS_DIR / "solution_assets" + cache_dir.mkdir(parents=True, exist_ok=True) + + def get_asset(name): + asset_path = cache_dir / SOLUTION_ASSETS[name] + if not asset_path.exists(): + safe_download(url=f"{ASSETS_URL}/{asset_path.name}", dir=cache_dir) + return asset_path + + return get_asset + + +def pytest_addoption(parser): + """Add custom command-line options to pytest.""" + parser.addoption("--slow", action="store_true", default=False, help="Run slow tests") + parser.addoption( + "--export-env", + default=None, + help="Run only export tests assigned to this export environment id.", + ) + + +def _export_format_from_item(item, formats): + """Infer the export format covered by a tests/test_exports.py item.""" + if Path(str(item.fspath)).name != "test_exports.py": + return None + name = getattr(item, "originalname", None) or item.name.split("[", 1)[0] + if name == "test_torch2onnx_serializes_concurrent_exports": + return "onnx" + if not name.startswith("test_export_"): + return None + + suffix = name[len("test_export_") :] + return next( + (fmt for fmt in sorted(formats, key=len, reverse=True) if suffix == fmt or suffix.startswith(f"{fmt}_")), None + ) + + +def pytest_collection_modifyitems(config, items): + """Modify the list of test items to exclude tests marked as slow if the --slow option is not specified. + + Args: + config: The pytest configuration object that provides access to command-line options. + items (list): The list of collected pytest item objects to be modified based on the presence of --slow option. + """ + if not config.getoption("--slow"): + # Remove the item entirely from the list of test items if it's marked as 'slow' + items[:] = [item for item in items if "slow" not in item.keywords] + + export_env = config.getoption("--export-env") + if not export_env: + return + + from ultralytics.engine.exporter import export_formats + + env_by_format = dict(zip(export_formats()["Argument"], export_formats()["Env"])) + for item in items: + fmt = _export_format_from_item(item, env_by_format) + if fmt and env_by_format.get(fmt) != export_env: + item.add_marker(pytest.mark.skip(reason=f"export format '{fmt}' belongs to env '{env_by_format[fmt]}'")) + + +def isolated_model_path(tmp_path, model): + """Copy a model to a per-test path to prevent export file races under pytest-xdist.""" + model = Path(model) + if not model.exists(): + from ultralytics.utils.downloads import attempt_download_asset + + model.parent.mkdir(parents=True, exist_ok=True) + shutil.copy(attempt_download_asset(model.name), model) + + dst = tmp_path / model.name + shutil.copy(model, dst) + return str(dst) + + +def pytest_sessionstart(session): + """Initialize session configurations for pytest. + + This function is automatically called by pytest after the 'Session' object has been created but before performing + test collection. It sets the initial seeds for the test session. + + Args: + session: The pytest session object. + """ + from ultralytics.utils.torch_utils import init_seeds + + init_seeds() + + +@pytest.fixture +def isolated_model(tmp_path): + """Provide an isolated copy of the test model to prevent export file races under pytest-xdist. + + When multiple xdist workers run export tests simultaneously, they derive output filenames from the model path (e.g., + model.onnx, model.torchscript). Using the same MODEL path causes workers to overwrite each other's + intermediate/export files. This fixture copies the shared model to a per-test temporary directory so each test + exports to a unique path. + """ + from tests import MODEL + + return isolated_model_path(tmp_path, MODEL) + + +def pytest_sessionfinish(session, exitstatus): + """Cleanup operations after pytest session. + + Runs only on the pytest controller (or serial run), skipping xdist workers to avoid race conditions where one worker + deletes shared assets while another is still reading them. + """ + # Skip on xdist workers - only the controller should clean up shared resources + if hasattr(session.config, "workerinput"): + return + + from ultralytics.utils import WEIGHTS_DIR + + # Remove files + models = [path for x in ("*.onnx", "*.torchscript") for path in WEIGHTS_DIR.rglob(x)] + for file in ["bus.jpg", "yolo26n.onnx", "yolo26n.torchscript", *models]: + Path(file).unlink(missing_ok=True) + + # Remove directories + for directory in [path for x in ("*.mlpackage", "*_openvino_model") for path in WEIGHTS_DIR.rglob(x)]: + shutil.rmtree(directory, ignore_errors=True) diff --git a/.venv/lib/python3.12/site-packages/tests/test_cli.py b/.venv/lib/python3.12/site-packages/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..c5f2e324ef8c54d019a1b6668f55a505b48eece9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tests/test_cli.py @@ -0,0 +1,200 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import json +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest +from PIL import Image + +from tests import CUDA_DEVICE_COUNT, CUDA_IS_AVAILABLE, MODELS, TASK_MODEL_DATA +from ultralytics.utils import ARM64, ASSETS, DATASETS_DIR, IS_RASPBERRYPI, LINUX, WEIGHTS_DIR, checks +from ultralytics.utils.torch_utils import TORCH_1_11, TORCH_VERSION + + +def run(cmd: str) -> None: + """Execute a shell command using subprocess.""" + subprocess.run(cmd.split(), check=True) + + +def test_special_modes() -> None: + """Test various special command-line modes for YOLO functionality.""" + run("yolo help") + run("yolo checks") + run("yolo version") + run("yolo settings reset") + run(f"yolo settings weights_dir={WEIGHTS_DIR} datasets_dir={DATASETS_DIR}") + run("yolo cfg") + + +@pytest.mark.parametrize("api_key", ["legacy_api_key", "ul_" + "a" * 40]) +def test_settings_migration(tmp_path: Path, api_key: str) -> None: + """Verify schema migration preserves user settings and only retains Platform API keys.""" + from ultralytics.utils import SettingsManager + + settings_file = tmp_path / "settings.json" + settings_file.write_text( + json.dumps( + { + "settings_version": "0.0.7", + "runs_dir": "/custom/runs", + "api_key": api_key, + "hub": True, + "neptune": True, + } + ) + ) + settings = SettingsManager(settings_file) + + assert settings["runs_dir"] == "/custom/runs" + assert settings["api_key"] == (api_key if api_key.startswith("ul_") else "") + assert settings["settings_version"] == "0.0.8" + assert "hub" not in settings + assert "neptune" not in settings + + +def test_cli_imports_defer_torchvision() -> None: + """Verify startup imports do not load torchvision or SAM3 geometry.""" + code = ( + "import sys; " + "from ultralytics import YOLO; " + "from ultralytics.models.sam import Predictor; " + "assert 'torchvision' not in sys.modules; " + "assert 'ultralytics.models.sam.sam3.geometry_encoders' not in sys.modules" + ) + subprocess.run([sys.executable, "-c", code], check=True) + + +@pytest.mark.parametrize("task,model,data", TASK_MODEL_DATA) +@pytest.mark.skipif(IS_RASPBERRYPI, reason="Edge devices not intended for training") +def test_train(task: str, model: str, data: str) -> None: + """Test YOLO training for different tasks, models, and datasets.""" + run(f"yolo train {task} model={model} data={data} imgsz=32 epochs=1 cache=disk") + + +@pytest.mark.parametrize("task,model,data", TASK_MODEL_DATA) +def test_val(task: str, model: str, data: str) -> None: + """Test YOLO validation process for specified task, model, and data using a shell command.""" + for nms in (None, False): + run(f"yolo val {task} model={model} data={data} imgsz=32 nms={nms} max_det=100 agnostic_nms") + + +@pytest.mark.parametrize("task,model,data", TASK_MODEL_DATA) +def test_predict(task: str, model: str, data: str) -> None: + """Test YOLO prediction on provided sample assets for specified task and model.""" + for nms in (None, False): + run(f"yolo {task} predict model={model} source={ASSETS} imgsz=32 save nms={nms} max_det=100") + + +@pytest.mark.parametrize("model", MODELS) +def test_export(model: str, tmp_path: Path) -> None: + """Test exporting a YOLO model to TorchScript format.""" + from ultralytics.utils.downloads import attempt_download_asset + + isolated = tmp_path / model + shutil.copy(Path(attempt_download_asset(model)), isolated) + for nms in (None, False): + run(f"yolo export model={isolated} format=torchscript imgsz=32 nms={nms} max_det=100") + + +@pytest.mark.parametrize( + "task,data,student,teacher", + [ + ("detect", "coco8.yaml", "yolo26n.yaml", WEIGHTS_DIR / "yolo26s.pt"), + ("segment", "coco8-seg.yaml", "yolo26n-seg.yaml", WEIGHTS_DIR / "yolo26s-seg.pt"), + ("pose", "coco8-pose.yaml", "yolo26n-pose.yaml", WEIGHTS_DIR / "yolo26s-pose.pt"), + ("obb", "dota8.yaml", "yolo26n-obb.yaml", WEIGHTS_DIR / "yolo26s-obb.pt"), + ], +) +def test_distill(task: str, data: str, student: str, teacher: Path) -> None: + """Test YOLO knowledge distillation training via CLI for supported tasks.""" + run(f"yolo train {task} model={student} distill_model={teacher} data={data} imgsz=32 epochs=1") + + +@pytest.mark.skipif(not TORCH_1_11, reason="RTDETR requires torch>=1.11") +@pytest.mark.skipif( + LINUX and ARM64 and checks.IS_PYTHON_3_8 and "2.1.0a0" in TORCH_VERSION, + reason="RTDETR CPU training produces NaN losses with JetPack 5 torch 2.1.0a0", +) +def test_rtdetr(task: str = "detect", model: Path = WEIGHTS_DIR / "rtdetr-l.pt", data: str = "coco8.yaml") -> None: + """Test the RTDETR functionality within Ultralytics for detection tasks using specified model and data.""" + # Add comma and spaces to test CLI arg cleanup. + run(f"yolo predict {task} model={model} source={ASSETS / 'bus.jpg'} imgsz=160 save") + run(f"yolo train {task} model={model} data={data} --imgsz= 160 epochs =1, cache = disk") + + +@pytest.mark.skipif(IS_RASPBERRYPI, reason="Edge devices not intended for heavy FastSAM tests") +@pytest.mark.skipif(checks.IS_PYTHON_3_12, reason="MobileSAM with CLIP is not supported in Python 3.12") +@pytest.mark.skipif( + checks.IS_PYTHON_3_8 and LINUX and ARM64, + reason="MobileSAM with CLIP is not supported in Python 3.8 and aarch64 Linux", +) +def test_fastsam( + task: str = "segment", model: str = WEIGHTS_DIR / "FastSAM-s.pt", data: str = "coco8-seg.yaml" +) -> None: + """Test FastSAM model for segmenting objects in images using various prompts within Ultralytics.""" + source = ASSETS / "bus.jpg" + + run(f"yolo segment val {task} model={model} data={data} imgsz=32") + run(f"yolo segment predict model={model} source={source} imgsz=32 save") + + from ultralytics import FastSAM + from ultralytics.models.sam import Predictor + + # Create a FastSAM model + sam_model = FastSAM(model) # or FastSAM-x.pt + + # Run inference on an image + for s in (source, Image.open(source)): + everything_results = sam_model(s, device="cpu", retina_masks=True, imgsz=160, conf=0.4, iou=0.9) + + # Remove small regions + _new_masks, _ = Predictor.remove_small_regions(everything_results[0].masks.data, min_area=20) + + # Run inference with bboxes and points and texts prompt at the same time + sam_model(source, bboxes=[439, 437, 524, 709], points=[[200, 200]], labels=[1], texts="a photo of a dog") + + +def test_mobilesam() -> None: + """Test MobileSAM segmentation with point and box prompts using Ultralytics.""" + from ultralytics import SAM + + # Load the model + model = SAM(WEIGHTS_DIR / "mobile_sam.pt") + + # Source + source = ASSETS / "zidane.jpg" + + # Predict a segment based on a 1D point prompt and 1D labels. + model.predict(source, points=[900, 370], labels=[1]) + + # Predict a segment based on 3D points and 2D labels (multiple points per object). + model.predict(source, points=[[[900, 370], [1000, 100]]], labels=[[1, 1]]) + + # Predict a segment based on a box prompt + model.predict(source, bboxes=[439, 437, 524, 709], save=True) + + # Predict all + # model(source) + + +# Slow Tests ----------------------------------------------------------------------------------------------------------- +@pytest.mark.slow +@pytest.mark.parametrize("task,model,data", TASK_MODEL_DATA) +@pytest.mark.skipif(not CUDA_IS_AVAILABLE, reason="CUDA is not available") +@pytest.mark.skipif(CUDA_DEVICE_COUNT < 2, reason="DDP is not available") +def test_train_gpu(task: str, model: str, data: str) -> None: + """Test YOLO training on GPU(s) for various tasks and models.""" + run(f"yolo train {task} model={model} data={data} imgsz=32 epochs=1 device=0") # single GPU + run(f"yolo train {task} model={model} data={data} imgsz=32 epochs=1 device=0,1") # multi GPU + + +@pytest.mark.parametrize( + "solution", + ["count", "blur", "workout", "heatmap", "isegment", "visioneye", "speed", "queue", "analytics", "trackzone"], +) +def test_solutions(solution: str) -> None: + """Test yolo solutions command-line modes.""" + run(f"yolo solutions {solution} verbose=False") diff --git a/.venv/lib/python3.12/site-packages/tests/test_cuda.py b/.venv/lib/python3.12/site-packages/tests/test_cuda.py new file mode 100644 index 0000000000000000000000000000000000000000..cd517e6936a8a74437d42c28c80354b735125ea6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tests/test_cuda.py @@ -0,0 +1,275 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import os +from itertools import product +from pathlib import Path + +import pytest +import torch + +from tests import CUDA_DEVICE_COUNT, CUDA_IS_AVAILABLE, MODEL, SOURCE +from ultralytics import YOLO +from ultralytics.cfg import TASK2DATA, TASK2MODEL, TASKS +from ultralytics.utils import ASSETS, IS_JETSON, WEIGHTS_DIR +from ultralytics.utils.autodevice import GPUInfo +from ultralytics.utils.checks import check_amp, check_tensorrt +from ultralytics.utils.torch_utils import TORCH_1_13, parse_device + +# Try to find idle devices if CUDA is available +DEVICES = [] +if CUDA_IS_AVAILABLE: + if IS_JETSON: + DEVICES = [0] # NVIDIA Jetson only has one GPU and does not fully support pynvml library + else: + gpu_info = GPUInfo() + gpu_info.print_status() + autodevice_fraction = __import__("os").environ.get("YOLO_AUTODEVICE_FRACTION_FREE", 0.3) + if idle_gpus := gpu_info.select_idle_gpu( + count=2, + min_memory_fraction=autodevice_fraction, + min_util_fraction=autodevice_fraction, + ): + DEVICES = idle_gpus + + +def test_checks(): + """Validate CUDA settings against torch CUDA functions.""" + assert torch.cuda.is_available() == CUDA_IS_AVAILABLE + assert torch.cuda.device_count() == CUDA_DEVICE_COUNT + + +@pytest.mark.skipif(not DEVICES, reason="No CUDA devices available") +def test_amp(): + """Test AMP training checks.""" + model = YOLO("yolo26n.pt").model.to(f"cuda:{DEVICES[0]}") + assert check_amp(model) + + +@pytest.mark.slow +@pytest.mark.skipif(not DEVICES, reason="No CUDA devices available") +@pytest.mark.parametrize( + "task, dynamic, batch, simplify, nms", + [ # generate all combinations except for exclusion cases + (task, dynamic, batch, simplify, nms) + for task, dynamic, batch, simplify, nms in product( + sorted(TASKS), [True, False], [1, 2], [True, False], [None, True, False] + ) + if not ( + (task == "classify" and nms is True) or (task == "obb" and nms is True and (not TORCH_1_13 or IS_JETSON)) + ) + ], +) +def test_export_onnx_matrix(task, dynamic, batch, simplify, nms): + """Test YOLO exports to ONNX format with various configurations and parameters.""" + file = YOLO(TASK2MODEL[task]).export( + format="onnx", + imgsz=32, + dynamic=dynamic, + batch=batch, + simplify=simplify, + nms=nms, + device=DEVICES[0], + ) + YOLO(file)([SOURCE] * batch, imgsz=64 if dynamic else 32, device=DEVICES[0]) # exported model inference + Path(file).unlink() # cleanup + + +@pytest.mark.slow +@pytest.mark.skipif(not DEVICES, reason="No CUDA devices available") +@pytest.mark.parametrize( + "task, dynamic, quantize, batch", + [ + (task, dynamic, quantize, batch) + # Limit Jetson task coverage for slow CI speed; full task coverage remains on GPU CI. + # for task, dynamic, quantize, batch in product(TASKS, [True, False], [8, 16], [1, 2]) + for task, dynamic, quantize, batch in product(["detect"] if IS_JETSON else sorted(TASKS), [True], [8, 16], [2]) + ] + + [("detect", False, 8, 2)], # exercise TensorRT 7-10 implicit INT8 quantization on GPU CI +) +def test_export_engine_matrix(task, dynamic, quantize, batch): + """Test YOLO model export to TensorRT format for various configurations and run inference.""" + check_tensorrt() + import tensorrt as trt + + is_trt11 = int(trt.__version__.split(".", 1)[0]) >= 11 + if not is_trt11 and quantize == 8 and dynamic: + # TensorRT 7-10 calibrator path cannot quantize dynamic-shape models; TensorRT 11 uses ModelOpt explicit Q/DQ + pytest.skip("INT8 + dynamic export requires explicit quantization, available on TensorRT 11+") + + file = YOLO(TASK2MODEL[task]).export( + format="engine", + imgsz=32, + dynamic=dynamic, + quantize=quantize, + batch=batch, + data=TASK2DATA[task], # use the smallest task datasets for fast INT8 calibration + workspace=1, # reduce workspace GB for less resource utilization during testing + simplify=True, + device=DEVICES[0], + ) + model = YOLO(file) + model([SOURCE] * batch, imgsz=64 if dynamic else 32, device=DEVICES[0]) # exported model inference + model.val(data=TASK2DATA[task], imgsz=32, device=DEVICES[0], batch=batch) # exported model validation + Path(file).unlink() # cleanup + if quantize == 8: + Path(file).with_suffix(".cache").unlink(missing_ok=True) # cleanup TensorRT 7-10 INT8 calibration cache + Path(file).with_suffix(".int8.onnx").unlink(missing_ok=True) # cleanup TensorRT 11 ModelOpt INT8 ONNX + if quantize == 16: + Path(file).with_suffix(".fp16.onnx").unlink(missing_ok=True) # cleanup TensorRT 11 ModelOpt FP16 ONNX + + +@pytest.mark.skipif(not DEVICES, reason="No CUDA devices available") +@pytest.mark.parametrize("nc", [1, 3]) +def test_semantic_loss_all_ignore_amp(nc): + """All-ignore guard must stay finite with large fp16 logits, where sum() overflows to inf (AMP is a GPU path).""" + from ultralytics.cfg import get_cfg + from ultralytics.nn.tasks import SemanticSegmentationModel + from ultralytics.utils.loss import SemanticSegmentationLoss + + model = SemanticSegmentationModel(cfg="yolo26-sem.yaml", nc=nc, verbose=False) + model.args = get_cfg() + loss_fn = SemanticSegmentationLoss(model) + preds = (torch.randn(1, nc, 64, 64, device=f"cuda:{DEVICES[0]}") + 50).half().requires_grad_() + loss, items = loss_fn(preds, {"semantic_mask": torch.full((1, 64, 64), 255, dtype=torch.long)}) + assert torch.isfinite(loss).all() and all(torch.isfinite(x).all() for x in items.values()) + loss.backward() + assert preds.grad is not None + + +@pytest.mark.skipif(not DEVICES, reason="No CUDA devices available") +@pytest.mark.skipif(IS_JETSON, reason="Edge devices not intended for training") +def test_train(): + """Test model training on a minimal dataset using available CUDA devices.""" + device = tuple(DEVICES) if len(DEVICES) > 1 else DEVICES[0] + expected = parse_device(device) # canonical torch indices, e.g. physical ids translate under external CVD + visible = os.environ.get("CUDA_VISIBLE_DEVICES") + results = YOLO(MODEL).train(data="coco8-grayscale.yaml", imgsz=64, epochs=1, device=DEVICES[0], batch=-1) + model = YOLO(MODEL) + results = model.train(data="coco8.yaml", imgsz=64, epochs=1, device=device, batch=15, compile=True) + assert model.trainer.args.device == expected, "trained on wrong GPUs" + assert model.trainer.device.index == int(expected.split(",")[0]), "trained on wrong GPU" + assert os.environ.get("CUDA_VISIBLE_DEVICES") == visible, "CUDA_VISIBLE_DEVICES must never be mutated" + results = YOLO(MODEL).train(data="coco128.yaml", imgsz=64, epochs=1, device=device, batch=15, val=False) + # Both single-GPU and DDP return metrics (recovered from the saved checkpoint under DDP) + assert results is not None + + +@pytest.mark.skipif(not DEVICES or max(DEVICES) == 0, reason="requires an idle CUDA device with nonzero index") +@pytest.mark.skipif(IS_JETSON, reason="Edge devices not intended for training") +def test_train_cold_process_nonzero_device(): + """Train on a nonzero GPU index in a fresh process with cold CUDA state, reproducing real CLI usage. + + A warm pytest process has CUDA initialized, so a subprocess without CUDA_VISIBLE_DEVICES is the only way to + reproduce cold-start device selection as on production pods (e.g. Ultralytics Platform). + """ + import subprocess + + env = {k: v for k, v in os.environ.items() if k != "CUDA_VISIBLE_DEVICES"} + cmd = ["yolo", "train", f"model={MODEL}", "data=coco8.yaml", "imgsz=32", "epochs=1", f"device={max(DEVICES)}"] + subprocess.run(cmd, check=True, env=env) + + +@pytest.mark.slow +@pytest.mark.skipif(not DEVICES, reason="No CUDA devices available") +def test_predict_multiple_devices(): + """Validate model prediction consistency across CPU and CUDA devices.""" + model = YOLO("yolo26n.pt") + + # Test CPU + model = model.cpu() + assert str(model.device) == "cpu" + _ = model(SOURCE) + assert str(model.device) == "cpu" + + # Test CUDA + cuda_device = f"cuda:{DEVICES[0]}" + model = model.to(cuda_device) + assert str(model.device) == cuda_device + _ = model(SOURCE) + assert str(model.device) == cuda_device + + # Test CPU again + model = model.cpu() + assert str(model.device) == "cpu" + _ = model(SOURCE) + assert str(model.device) == "cpu" + + # Test CUDA again + model = model.to(cuda_device) + assert str(model.device) == cuda_device + _ = model(SOURCE) + assert str(model.device) == cuda_device + + +@pytest.mark.skipif(not DEVICES, reason="No CUDA devices available") +def test_track_exported_model(): + """Track with an exported model on GPU; exported backends return raw preds as a single Tensor.""" + file = YOLO(MODEL).export(format="torchscript", imgsz=160, device=DEVICES[0]) + results = YOLO(file).track(SOURCE, imgsz=160, device=DEVICES[0]) + assert len(results[0].boxes) + Path(file).unlink() # cleanup + + +@pytest.mark.skipif(not DEVICES, reason="No CUDA devices available") +def test_autobatch(): + """Check optimal batch size for YOLO model training using autobatch utility.""" + from ultralytics.utils.autobatch import check_train_batch_size + + # imgsz < 2 * stride fails the batch-1 probe in train-mode BatchNorm, which is not a memory ceiling + assert check_train_batch_size(YOLO(MODEL).model.to(f"cuda:{DEVICES[0]}"), imgsz=32, amp=True) > 1 + + +@pytest.mark.slow +@pytest.mark.skipif(not DEVICES, reason="No CUDA devices available") +def test_utils_benchmarks(isolated_model): + """Profile YOLO models for performance benchmarks.""" + from ultralytics.utils.benchmarks import ProfileModels + + # Pre-export a dynamic engine model to use dynamic inference + YOLO(isolated_model).export(format="engine", imgsz=32, dynamic=True, batch=1, device=DEVICES[0]) + ProfileModels( + [isolated_model], + imgsz=32, + quantize=32, + min_time=1, + num_timed_runs=3, + num_warmup_runs=1, + device=DEVICES[0], + ).run() + + +@pytest.mark.slow +@pytest.mark.skipif(not DEVICES, reason="No CUDA devices available") +def test_predict_sam(): + """Test SAM model predictions using different prompts.""" + from ultralytics import SAM + from ultralytics.models.sam import Predictor as SAMPredictor + + model = SAM(WEIGHTS_DIR / "sam2.1_b.pt") + model.info() + + # Run inference with various prompts + model(SOURCE, device=DEVICES[0]) + model(SOURCE, bboxes=[439, 437, 524, 709], device=DEVICES[0]) + model(ASSETS / "zidane.jpg", points=[900, 370], device=DEVICES[0]) + model(ASSETS / "zidane.jpg", points=[900, 370], labels=[1], device=DEVICES[0]) + model(ASSETS / "zidane.jpg", points=[[900, 370]], labels=[1], device=DEVICES[0]) + model(ASSETS / "zidane.jpg", points=[[400, 370], [900, 370]], labels=[1, 1], device=DEVICES[0]) + model(ASSETS / "zidane.jpg", points=[[[900, 370], [1000, 100]]], labels=[[1, 1]], device=DEVICES[0]) + + # Test predictor + predictor = SAMPredictor( + overrides={ + "conf": 0.25, + "task": "segment", + "mode": "predict", + "imgsz": 1024, + "model": WEIGHTS_DIR / "mobile_sam.pt", + "device": DEVICES[0], + "quantize": 16, + } + ) + predictor.set_image(ASSETS / "zidane.jpg") + # predictor(bboxes=[439, 437, 524, 709]) + # predictor(points=[900, 370], labels=[1]) + predictor.reset_image() diff --git a/.venv/lib/python3.12/site-packages/tests/test_engine.py b/.venv/lib/python3.12/site-packages/tests/test_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..7f66d2e5d0df3b3251983f3bc2548d824017da8a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tests/test_engine.py @@ -0,0 +1,395 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import sys +from collections import OrderedDict +from pathlib import Path +from types import SimpleNamespace +from unittest import mock + +import pytest +import torch + +from tests import MODEL, SOURCE, TASK_MODEL_DATA +from ultralytics import YOLO +from ultralytics.cfg import get_cfg +from ultralytics.engine.exporter import Exporter +from ultralytics.engine.trainer import BaseTrainer +from ultralytics.models.yolo import classify, depth, detect, obb, pose, segment, semantic +from ultralytics.nn.distill_model import DistillationModel +from ultralytics.nn.tasks import DetectionModel, load_checkpoint +from ultralytics.utils import ASSETS, DEFAULT_CFG, IS_RASPBERRYPI, WEIGHTS_DIR +from ultralytics.utils.torch_utils import unwrap_model + + +def test_func(*args, **kwargs): + """Test function used as a callback stub to verify callback registration.""" + print("callback test passed") + + +def test_export(monkeypatch, tmp_path): + """Test model exporting functionality by adding a callback and verifying its execution.""" + monkeypatch.chdir(tmp_path) + exporter = Exporter() + exporter.add_callback("on_export_start", test_func) + assert test_func in exporter.callbacks["on_export_start"], "on_export_start callback not registered" + f = exporter(model=YOLO("yolo26n.yaml").model) + YOLO(f)(SOURCE) # exported model inference + + +@pytest.mark.parametrize( + "trainer_cls,validator_cls,predictor_cls,data,model,weights", + [ + ( + detect.DetectionTrainer, + detect.DetectionValidator, + detect.DetectionPredictor, + "coco8.yaml", + "yolo26n.yaml", + MODEL, + ), + ( + segment.SegmentationTrainer, + segment.SegmentationValidator, + segment.SegmentationPredictor, + "coco8-seg.yaml", + "yolo26n-seg.yaml", + WEIGHTS_DIR / "yolo26n-seg.pt", + ), + ( + classify.ClassificationTrainer, + classify.ClassificationValidator, + classify.ClassificationPredictor, + "imagenet10", + "yolo26n-cls.yaml", + None, + ), + (obb.OBBTrainer, obb.OBBValidator, obb.OBBPredictor, "dota8.yaml", "yolo26n-obb.yaml", None), + (pose.PoseTrainer, pose.PoseValidator, pose.PosePredictor, "coco8-pose.yaml", "yolo26n-pose.yaml", None), + ( + semantic.SemanticSegmentationTrainer, + semantic.SemanticSegmentationValidator, + semantic.SemanticSegmentationPredictor, + "cityscapes8.yaml", + "yolo26n-sem.yaml", + None, + ), + (depth.DepthTrainer, depth.DepthValidator, depth.DepthPredictor, "depth8.yaml", "yolo26-depth.yaml", None), + ], +) +@pytest.mark.skipif(IS_RASPBERRYPI, reason="Edge devices not intended for training") +def test_task(trainer_cls, validator_cls, predictor_cls, data, model, weights): + """Test YOLO training, validation, and prediction for various tasks.""" + overrides = { + "data": data, + "model": model, + "imgsz": 32, + "epochs": 1, + "save": False, + "mask_ratio": 1, + "overlap_mask": False, + } + + # Trainer + trainer = trainer_cls(overrides=overrides) + trainer.add_callback("on_train_start", test_func) + assert test_func in trainer.callbacks["on_train_start"], "on_train_start callback not registered" + trainer.train() + + # Validator + cfg = get_cfg(DEFAULT_CFG) + cfg.data = data + cfg.imgsz = 32 + val = validator_cls(args=cfg) + val.add_callback("on_val_start", test_func) + assert test_func in val.callbacks["on_val_start"], "on_val_start callback not registered" + val(model=trainer.best) + + # Predictor + pred = predictor_cls(overrides={"imgsz": [64, 64]}) + pred.add_callback("on_predict_start", test_func) + assert test_func in pred.callbacks["on_predict_start"], "on_predict_start callback not registered" + + # Determine model path for prediction + model_path = weights if weights else trainer.best + if model == "yolo26n.yaml": # only for detection + # Confirm there is no issue with sys.argv being empty + with mock.patch.object(sys, "argv", []): + result = pred(source=ASSETS, model=model_path) + assert len(result) > 0, f"Predictor returned no results for {model}" + else: + result = pred(source=ASSETS, model=model_path) + assert len(result) > 0, f"Predictor returned no results for {model}" + + # Test resume functionality + with pytest.raises(AssertionError): + trainer_cls(overrides={**overrides, "resume": trainer.last}).train() + + +def test_semantic_polygon_val_background(): + """Test standalone semantic val adds the polygon background class instead of mislabeling it as the last class.""" + from ultralytics.data.utils import check_det_dataset + + cfg = get_cfg(DEFAULT_CFG) + cfg.data = "coco8-seg.yaml" + cfg.imgsz = 64 + validator = semantic.SemanticSegmentationValidator(args=cfg) + validator.data = check_det_dataset(cfg.data) # standalone val dataset setup (engine/validator.py) + validator.stride = 32 # normally set from the model during validation + validator.device = torch.device("cpu") # normally set from the model during validation + dataset = validator.get_dataloader(validator.data["val"], 4).dataset + assert dataset.bg_class_idx == 80, "background class missing on standalone polygon val" + assert (dataset[0]["semantic_mask"] == 80).any(), "background pixels mislabeled on standalone polygon val" + + +@pytest.mark.parametrize("task,weight,data", TASK_MODEL_DATA) +def test_resume_incomplete(task, weight, data, tmp_path): + """Test training resumes from an incomplete checkpoint.""" + train_args = { + "data": data, + "epochs": 2, + "save": True, + "plots": False, + "workers": 0, + "project": tmp_path, + "name": task, + "imgsz": 32, + "exist_ok": True, + } + + def stop_after_first_epoch(trainer): + if trainer.epoch == 0: + trainer.stop = True + + def disable_final_eval(trainer): + trainer.final_eval = lambda: None + + model = YOLO(weight) + model.add_callback("on_train_start", disable_final_eval) + model.add_callback("on_train_epoch_end", stop_after_first_epoch) + model.train(**train_args) + last_path = model.trainer.last + _, ckpt = load_checkpoint(last_path) + assert ckpt["epoch"] == 0, "checkpoint should be resumable" + + # Resume training using the checkpoint + resume_model = YOLO(last_path) + resume_model.train(resume=True, **train_args) + assert resume_model.trainer.start_epoch == resume_model.trainer.epoch == 1, "resume test failed" + + +def test_resume_invalid_checkpoint_args(tmp_path): + """Test resuming a checkpoint with invalid train args raises the real error, not a missing-checkpoint error.""" + _, ckpt = load_checkpoint(MODEL) + ckpt["train_args"]["epochs"] = 0 # ultralytics <= 8.4.154 stored epochs < 1 without validating it + torch.save(ckpt, last := tmp_path / "last.pt") + with pytest.raises(ValueError, match="epochs"): + detect.DetectionTrainer(overrides={"model": MODEL, "data": "coco8.yaml", "resume": str(last)}) + + +def test_distill_resume(tmp_path: Path): + """Test knowledge distillation resumes from an incomplete checkpoint.""" + overrides = { + "data": "coco8.yaml", + "model": "yolo26n.yaml", + "distill_model": WEIGHTS_DIR / "yolo26s.pt", + "imgsz": 32, + "multi_scale": 0.5, # vary per-batch image size to exercise dynamic distillation score splitting + "epochs": 2, + "save": True, + "plots": False, + "workers": 0, + "project": tmp_path, + "name": "distill", + "exist_ok": True, + } + + # Train for one epoch then interrupt to produce a resumable checkpoint + trainer = detect.DetectionTrainer(overrides=overrides) + + def stop_after_first_epoch(trainer): + if trainer.epoch == 0: + trainer.stop = True + + trainer.final_eval = lambda: None + trainer.add_callback("on_train_epoch_end", stop_after_first_epoch) + trainer.train() + _, ckpt = load_checkpoint(trainer.last) + assert ckpt["epoch"] == 0, "checkpoint should be resumable" + assert isinstance(ckpt["ema"], DistillationModel), "distillation EMA wraps the student model" + assert ckpt["ema"].teacher_model is None, "teacher should be stripped from the EMA/checkpoint" + assert ckpt["ema"].projector is not None, "the distillation projector should be persisted in the EMA checkpoint" + + overrides["resume"] = trainer.last + trainer = detect.DetectionTrainer(overrides=overrides) + trainer.final_eval = lambda: None + trainer.train() + model = unwrap_model(trainer.model) + assert isinstance(model, DistillationModel), "resume should rebuild the DistillationModel" + assert model.teacher_model is not None, "resume should rebuild the teacher from the distill_model path" + assert trainer.start_epoch == trainer.epoch == 1, "resume test failed" + + +def test_distill_grayscale(tmp_path: Path): + """Test knowledge distillation on a single-channel dataset (https://github.com/ultralytics/ultralytics/issues/25066).""" + teacher = DetectionModel("yolo26n.yaml", ch=3, nc=80, verbose=False) + teacher_path = tmp_path / "teacher.pt" + torch.save({"model": teacher}, teacher_path) + student = DetectionModel("yolo26n.yaml", ch=1, nc=80, verbose=False) + student.args = SimpleNamespace(imgsz=32, dis=1.0) + model = DistillationModel(teacher_model=teacher_path, student_model=student) + assert isinstance(model, DistillationModel) + assert model.teacher_model.yaml["channels"] == 1 + + +@pytest.mark.parametrize( + "ckpt", + [ + {"model": OrderedDict([("a", torch.zeros(1))])}, # state_dict saved under the "model" key + {"model": {"a": torch.zeros(1)}}, # plain-dict "model" value + OrderedDict([("a", torch.zeros(1))]), # bare state_dict, no "model" key + ], +) +def test_load_checkpoint_state_dict_rejected(ckpt, tmp_path): + """Test a state_dict checkpoint raises a clear TypeError instead of a cryptic AttributeError/KeyError.""" + weight = tmp_path / "bad.pt" + torch.save(ckpt, weight) + with pytest.raises(TypeError, match="supported Ultralytics checkpoint format"): + load_checkpoint(weight) + + +def test_nan_recovery(): + """Test NaN loss detection and recovery during training.""" + nan_injected = [False] + + def inject_nan(trainer): + """Inject NaN into loss during batch processing to test recovery mechanism.""" + if trainer.epoch == 1 and trainer.tloss is not None and not nan_injected[0]: + trainer.tloss[next(iter(trainer.tloss))] *= float("nan") + nan_injected[0] = True + + overrides = {"data": "coco8.yaml", "model": "yolo26n.yaml", "imgsz": 32, "epochs": 3} + trainer = detect.DetectionTrainer(overrides=overrides) + trainer.add_callback("on_train_batch_end", inject_nan) + trainer.train() + assert nan_injected[0], "NaN injection failed" + + +def test_checkpoint_fp16_overflow(): + """Test a finite model whose weights overflow fp16 is still checkpointed (clamped) instead of skipped.""" + + def inflate_ema(trainer): + """Push an EMA weight above the fp16 max (65504) so its fp16 snapshot would otherwise become Inf.""" + if trainer.ema is not None: + next(iter(trainer.ema.ema.parameters())).data[0] = 1.0e5 + + overrides = {"data": "coco8.yaml", "model": "yolo26n.yaml", "imgsz": 32, "epochs": 2} + trainer = detect.DetectionTrainer(overrides=overrides) + trainer.add_callback("on_train_epoch_end", inflate_ema) + trainer.train() + assert trainer.last.exists(), "checkpoint not saved for a finite model with fp16-overflowing weights" + model, _ = load_checkpoint(trainer.last) + assert all(torch.isfinite(v).all() for v in model.state_dict().values() if isinstance(v, torch.Tensor)), ( + "saved checkpoint contains NaN/Inf" + ) + # Validation must leave the live EMA fp32 and unchanged; checkpoint serialization may clamp its fp16 copy. + ema_param = next(iter(trainer.ema.ema.parameters())) + assert ema_param.dtype == torch.float32 and torch.isfinite(ema_param).all() and ema_param.flatten()[0] == 1.0e5, ( + "validation corrupted the live EMA" + ) + + +def test_checkpoint_nonfinite_ema_resync(): + """Test a non-finite EMA on a finite model is resynced (not skipped) so the run still produces a checkpoint.""" + + def poison_ema(trainer): + """Make the live fp32 EMA genuinely non-finite while the model stays finite (sticky-NaN on a finite-loss run).""" + if trainer.ema is not None: + next(iter(trainer.ema.ema.parameters())).data[0] = float("inf") + + overrides = {"data": "coco8.yaml", "model": "yolo26n.yaml", "imgsz": 32, "epochs": 2} + trainer = detect.DetectionTrainer(overrides=overrides) + trainer.add_callback("on_train_epoch_end", poison_ema) + trainer.train() + assert trainer.last.exists(), "no checkpoint saved when the EMA went non-finite on a finite model" + model, _ = load_checkpoint(trainer.last) + assert all(torch.isfinite(v).all() for v in model.state_dict().values() if isinstance(v, torch.Tensor)), ( + "saved checkpoint contains NaN/Inf" + ) + + +def test_checkpoint_nonfinite_ema_and_model_sanitized(): + """Test a tensor non-finite in both EMA and model is sanitized (not skipped) so the run still produces a checkpoint.""" + + def poison_ema_and_model(trainer): + """Force the first parameter non-finite in both the live EMA and the model (finite-loss sticky-NaN).""" + if trainer.ema is not None: + next(iter(trainer.ema.ema.parameters())).data[0] = float("inf") + next(iter(unwrap_model(trainer.model).parameters())).data[0] = float("nan") + + overrides = {"data": "coco8.yaml", "model": "yolo26n.yaml", "imgsz": 32, "epochs": 1} + trainer = detect.DetectionTrainer(overrides=overrides) + trainer.add_callback("on_train_epoch_end", poison_ema_and_model) + trainer.train() + assert trainer.last.exists(), "no checkpoint saved when a tensor went non-finite in both EMA and model" + model, _ = load_checkpoint(trainer.last) + assert all(torch.isfinite(v).all() for v in model.state_dict().values() if isinstance(v, torch.Tensor)), ( + "saved checkpoint contains NaN/Inf" + ) + + +def test_train_multi_custom_trainer_metrics_and_failure_keys(monkeypatch, tmp_path): + """Test custom multi-dataset runs keep memory metrics and unique failure keys.""" + model = YOLO(MODEL) + calls = 0 + + class FakeTrainer: + def __init__(self, overrides=None, _callbacks=None): + pass + + def get_model(self, cfg=None, weights=None, verbose=True): + return model.model + + def train(self): + nonlocal calls + calls += 1 + if calls == 2: + raise RuntimeError("failed repeated dataset") + self.validator = SimpleNamespace(metrics=SimpleNamespace(results_dict={"fitness": 1.0})) + + monkeypatch.setattr("ultralytics.engine.model.checks.check_pip_update_available", lambda: None) + results = model.train( + data=["coco8.yaml", "coco8.yaml"], + project=tmp_path, + plots=False, + save=False, + trainer=FakeTrainer, + ) + + assert model.trainer.trainer is FakeTrainer + assert results == {"coco8": {"fitness": 1.0}, "coco8-2": None} + + +@pytest.mark.parametrize("pretrained,uses_weights", [(True, True), (False, False), (MODEL, True)]) +def test_setup_model_respects_pretrained_arg_for_pt_models(monkeypatch, pretrained, uses_weights): + """Test .pt models use checkpoint config while respecting the pretrained argument.""" + captured = {} + checkpoint_model = SimpleNamespace(yaml={"nc": 80}) + trainer = object.__new__(BaseTrainer) + trainer.model = "yolo26n.pt" + trainer.args = SimpleNamespace(pretrained=pretrained) + trainer.resume = False + + def fake_get_model(cfg=None, weights=None, verbose=True): + captured["cfg"] = cfg + captured["weights"] = weights + return SimpleNamespace() + + trainer.get_model = fake_get_model + monkeypatch.setattr( + "ultralytics.engine.trainer.load_checkpoint", lambda path: (checkpoint_model, {"checkpoint": True}) + ) + + trainer.setup_model() + + assert captured["cfg"] == checkpoint_model.yaml, "Checkpoint config was not used" + assert captured["weights"] is (checkpoint_model if uses_weights else None), "Unexpected weights loaded" diff --git a/.venv/lib/python3.12/site-packages/tests/test_exports.py b/.venv/lib/python3.12/site-packages/tests/test_exports.py new file mode 100644 index 0000000000000000000000000000000000000000..5e3a1a1e20b8c726e768ce694696ab5063a60abf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tests/test_exports.py @@ -0,0 +1,688 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import io +import shutil +import sys +import threading +import time +from contextlib import redirect_stderr, redirect_stdout +from itertools import product +from pathlib import Path +from types import SimpleNamespace + +import pytest +import torch + +from tests import MODEL, SOURCE +from tests.conftest import isolated_model_path +from ultralytics import YOLO +from ultralytics.cfg import TASK2DATA, TASK2MODEL, TASKS, _handle_deprecation, get_cfg +from ultralytics.engine.exporter import EXPORT_ENVS, Exporter, export_formats, validate_args +from ultralytics.utils import ( + ARM64, + IS_RASPBERRYPI, + LINUX, + MACOS, + MACOS_VERSION, + WEIGHTS_DIR, + WINDOWS, + checks, +) +from ultralytics.utils.export.engine import modelopt_quantize_onnx, torch2onnx +from ultralytics.utils.torch_utils import ( + TORCH_1_10, + TORCH_1_11, + TORCH_1_13, + TORCH_2_0, + TORCH_2_1, + TORCH_2_9, +) + + +def skip_rpi_semantic(task): + """Skip semantic segmentation export tests on Raspberry Pi due to memory constraints.""" + if IS_RASPBERRYPI and task == "semantic": + pytest.skip("Semantic segmentation export tests are skipped on Raspberry Pi due to memory constraints.") + + +@pytest.mark.parametrize("nms", [None, False]) +def test_export_torchscript(nms, isolated_model): + """Test YOLO model export to TorchScript format for compatibility and correctness.""" + file = YOLO(isolated_model).export(format="torchscript", imgsz=32, nms=nms) + model = YOLO(file) + model(SOURCE, imgsz=32) # exported model inference + model(SOURCE, imgsz=64) # predictor reuse must keep the fixed export imgsz + assert model.predictor.imgsz == [32, 32] + + +@pytest.mark.parametrize(("model_name", "nc"), [("yolo26n.yaml", 80), ("yolo26n-cls.yaml", 1000)]) +def test_export_torchscript_missing_names(model_name, nc, tmp_path): + """Test TorchScript export reconstructs missing class names from the model head's class count.""" + model = YOLO(model_name) + model.model.names = None # legacy and foreign checkpoints reach the exporter without names + model.model.pt_path = str(tmp_path / Path(model_name).with_suffix(".pt").name) + + names = YOLO(model.export(format="torchscript", imgsz=32)).names + + assert len(names) == nc # a 999-name fallback would leave names[999] missing on a 1000-class head + assert names[nc - 1] == f"class{nc - 1}" + + +@pytest.mark.parametrize("nms", [None, False]) +def test_export_onnx(nms, isolated_model): + """Test YOLO model export to ONNX format with dynamic axes.""" + file = YOLO(isolated_model).export(format="onnx", dynamic=True, imgsz=32, nms=nms) + YOLO(file)(SOURCE, imgsz=32) # exported model inference + + +@pytest.mark.skipif(not TORCH_1_13, reason="ONNX export with NMS requires torch>=1.13") +def test_export_onnx_nms_conf(isolated_model): + """Bake explicit zero confidence into the NMS graph instead of the 0.25 default.""" + import onnx + from onnx import numpy_helper + + path = YOLO(isolated_model).export(format="onnx", imgsz=32, nms=True, conf=0.0) + model = onnx.load(path) + initializers = {i.name: numpy_helper.to_array(i) for i in model.graph.initializer} + thresholds = { + initializers[n.input[1]].item() + for n in model.graph.node + if n.op_type == "Greater" and n.input[1] in initializers + } + assert 0.0 in thresholds + + +@pytest.mark.slow +@pytest.mark.parametrize("precision", [{"int8": True}, {"quantize": 8}]) +def test_export_onnx_int8(isolated_model, precision): + """Test INT8 ONNX export via both the legacy int8 alias and the unified quantize arg.""" + file = YOLO(isolated_model).export(format="onnx", data=Path("coco8.yaml"), fraction=0.25, imgsz=32, **precision) + assert Path(file).name.endswith("_int8.onnx") + YOLO(file)(SOURCE, imgsz=32) # exported model inference + Path(file).unlink() # cleanup + + +def test_onnx_int8_quantize_excludes_non_weighted_ops(monkeypatch): + """Check ONNX INT8 keeps only weighted ops quantized while preserving the string return contract.""" + import onnx + import onnxruntime.quantization as ort_quantization + + from ultralytics.utils.export.onnx import onnx_int8_quantize + + calls = {} + graph = SimpleNamespace( + node=[ + SimpleNamespace(name="conv", op_type="Conv"), + SimpleNamespace(name="pool", op_type="MaxPool"), + SimpleNamespace(name="sigmoid", op_type="Sigmoid"), + ] + ) + + monkeypatch.setattr(onnx, "load", lambda _: SimpleNamespace(graph=graph)) + monkeypatch.setattr(ort_quantization, "quantize_static", lambda *args, **kwargs: calls.update(kwargs)) + result = onnx_int8_quantize(Path("model.onnx"), Path("model_int8.onnx"), [], lambda x: x) + assert result == "model_int8.onnx" + assert calls["nodes_to_exclude"] == ["pool", "sigmoid"] + + +def test_quantize_canonicalization(): + """Quantize accepts 8/16/32 (int or str) and w-notation, canonicalizing to the int form (unset stays None).""" + for value, expected in [ + (8, 8), + (16, 16), + (32, 32), + ("8", 8), + ("int8", 8), + ("INT8", 8), + ("w8a8", 8), + ("W8A8", 8), + ("fp16", 16), + ("Fp16", 16), + ("w16a16", 16), + ("fp32", 32), + ("fP32", 32), + ("w8a16", "w8a16"), + ("W8a16", "w8a16"), + ("w8a32", "w8a32"), + ("W8A32", "w8a32"), + ]: + assert get_cfg(overrides={"quantize": value}).quantize == expected + assert get_cfg().quantize is None # unset default is FP32 + with pytest.raises(ValueError, match="quantize"): + get_cfg(overrides={"quantize": "x4"}) + with pytest.raises(ValueError, match="quantize"): + get_cfg(overrides={"quantize": "a8w8"}) + + +def test_quantize_deprecation(): + """Legacy half/int8 forward to the unified quantize arg in all modes; int8 wins on conflict.""" + assert _handle_deprecation({"int8": True})["quantize"] == 8 + assert _handle_deprecation({"half": True})["quantize"] == 16 + assert _handle_deprecation({"half": True, "int8": True})["quantize"] == 8 # int8 wins + assert "half" not in _handle_deprecation({"half": True}) # legacy flag is removed after forwarding + assert _handle_deprecation({"half": True, "quantize": None})["quantize"] is None # explicit quantize wins + assert _handle_deprecation({"half": True, "quantize": 8})["quantize"] == 8 # explicit quantize still wins + + +def test_benchmark_forwards_legacy_precision(monkeypatch): + """model.benchmark(half=True) must reach the benchmark call as quantize=16, not silently run FP32.""" + import ultralytics.utils.benchmarks as bm + + captured = {} + monkeypatch.setattr(bm, "benchmark", lambda **kw: captured.update(kw) or {}) + YOLO(MODEL).benchmark(half=True, format="onnx", data="coco8.yaml") + assert captured["quantize"] == 16, f"legacy half was dropped: quantize={captured.get('quantize')}" + + +def test_qnn_quantize_requires_w8a16(): + """QNN exports are W8A16; explicit INT8 activation quantization is not supported.""" + valid_args = ["batch", "data", "dynamic", "fraction", "keras", "nms"] + validate_args("qnn", SimpleNamespace(quantize="w8a16"), valid_args) + with pytest.raises(AssertionError, match=r"quantize=8 \(INT8\) is not supported"): + validate_args("qnn", SimpleNamespace(quantize=8), valid_args) + + +def test_modelopt_quantize_onnx_requires_int8_dataset(): + """Check INT8 ModelOpt quantization fails early without calibration data.""" + with pytest.raises(ValueError, match="requires a calibration dataset"): + modelopt_quantize_onnx("model.onnx", quantize=8) + + +def test_int8_calibration_validates_split(): + """Check INT8 calibration rejects dataset splits that do not exist.""" + exporter = object.__new__(Exporter) + exporter.model = SimpleNamespace(task="obb") + exporter.args = SimpleNamespace(data="coco8.yaml", split="trainval") + exporter.imgsz = [32] + with pytest.raises(FileNotFoundError, match="trainval"): + exporter.get_int8_calibration_dataloader() + + +@pytest.mark.parametrize("task", ["classify", "detect"]) +@pytest.mark.parametrize(("fraction", "expected"), [(2, 2), ([1, 3, 0], 3)]) +def test_int8_calibration_fraction(task, fraction, expected, tmp_path): + """Check scalar and list fractions select the requested calibration split size for classification and detection.""" + data = "coco8.yaml" + if task == "classify": + for split, count in (("train", 2), ("val", 4)): + (split_dir := tmp_path / split / "0").mkdir(parents=True) + for i in range(count): + shutil.copy(SOURCE, split_dir / f"{i}.jpg") + data = str(tmp_path) + exporter = object.__new__(Exporter) + exporter.model = SimpleNamespace(task=task) + exporter.args = get_cfg(overrides={"data": data, "split": "val", "fraction": fraction, "batch": 1}) + exporter.imgsz = [32] + assert len(exporter.get_int8_calibration_dataloader().dataset) == expected + + +def test_export_rknn_batch_expansion(monkeypatch, tmp_path): + """Check RKNN calibrates batch 1 before Toolkit expands to the requested batch.""" + calls = {} + monkeypatch.setattr( + "ultralytics.utils.export.rknn.onnx2rknn", lambda **kwargs: calls.update(kwargs) or kwargs["output_dir"] + ) + monkeypatch.setattr("ultralytics.engine.exporter.file_size", lambda _: 1) + + image = tmp_path / "image.jpg" + exporter = SimpleNamespace( + args=SimpleNamespace(opset=None, quantize=8, name="rk3588", batch=8), + im=torch.zeros(8, 3, 32, 32), + file=tmp_path / "model.pt", + metadata={}, + get_int8_calibration_dataloader=lambda prefix: SimpleNamespace(dataset=SimpleNamespace(im_files=[image])), + ) + exporter.export_onnx = lambda: calls.update(onnx_batch=len(exporter.im)) or tmp_path / "model.onnx" + Exporter.export_rknn(exporter) + assert calls["onnx_batch"] == 1 + assert calls["batch"] == 8 + + +def test_torch2onnx_serializes_concurrent_exports(monkeypatch, tmp_path): + """Ensure ONNX exports do not overlap across worker threads.""" + active = 0 + max_active = 0 + errors = [] + state_lock = threading.Lock() + + def fake_export(*args, **kwargs): + nonlocal active, max_active + with state_lock: + active += 1 + max_active = max(max_active, active) + time.sleep(0.05) + with state_lock: + active -= 1 + + monkeypatch.setattr(torch.onnx, "export", fake_export) + + def export_model(index: int): + try: + torch2onnx(torch.nn.Identity(), torch.zeros(1, 3, 8, 8), str(tmp_path / f"export-{index}.onnx")) + except Exception as error: # pragma: no cover - assertion handled below + errors.append(error) + + threads = [threading.Thread(target=export_model, args=(i,)) for i in range(4)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + assert not errors, f"Concurrent export errors: {errors}" + assert max_active == 1, f"Expected max 1 concurrent export, got {max_active}" + + +@pytest.mark.skipif(not TORCH_2_1, reason="OpenVINO requires torch>=2.1") +@pytest.mark.parametrize("nms", [None, False]) +def test_export_openvino(nms, isolated_model): + """Test YOLO export to OpenVINO format for model inference compatibility.""" + file = YOLO(isolated_model).export(format="openvino", imgsz=32, nms=nms) + YOLO(file)(SOURCE, imgsz=32) # exported model inference + + +@pytest.mark.slow +@pytest.mark.skipif(not TORCH_2_1, reason="OpenVINO requires torch>=2.1") +@pytest.mark.parametrize( + "task, dynamic, quantize, batch, nms", + [ # generate all combinations except for exclusion cases + (task, dynamic, quantize, batch, nms) + for task, dynamic, quantize, batch, nms in product(TASKS, [True, False], [8, 16], [1, 2], [False]) + ], +) +# Keep one-to-many INT8 cases disabled until OpenVINO runner OOM is resolved. +def test_export_openvino_matrix(task, dynamic, quantize, batch, nms): + """Test YOLO model export to OpenVINO under various configuration matrix conditions.""" + skip_rpi_semantic(task) + file = YOLO(TASK2MODEL[task]).export( + format="openvino", + imgsz=32, + dynamic=dynamic, + quantize=quantize, + batch=batch, + data=TASK2DATA[task], # use the smallest task datasets for fast INT8 calibration + nms=nms, + ) + YOLO(file)([SOURCE] * batch, imgsz=64 if dynamic else 32, batch=batch) # exported model inference + shutil.rmtree(file, ignore_errors=True) # retry in case of potential lingering multi-threaded file usage errors + + +@pytest.mark.slow +@pytest.mark.parametrize( + "task, dynamic, batch, simplify, nms", + [ # generate all combinations except for exclusion cases + (task, dynamic, batch, simplify, nms) + for task, dynamic, batch, simplify, nms in product( + TASKS, [True, False], [1, 2], [True, False], [None, True, False] + ) + if not (nms is True and (task == "classify" or not TORCH_1_13)) + ], +) +def test_export_onnx_matrix(task, dynamic, batch, simplify, nms): + """Test YOLO export to ONNX format with various configurations and parameters.""" + skip_rpi_semantic(task) + file = YOLO(TASK2MODEL[task]).export( + format="onnx", + imgsz=32, + dynamic=dynamic, + batch=batch, + simplify=simplify, + nms=nms, + ) + r = YOLO(file)([SOURCE] * batch, imgsz=64 if dynamic else 32) # exported model inference + if task == "semantic": + assert r[0].semantic_mask is not None + assert r[0].semantic_mask.data.dtype in {torch.uint8, torch.int32} + Path(file).unlink() # cleanup + + +def test_export_onnx_semantic_dnn(): + """Test semantic ONNX class-map output with OpenCV DNN.""" + skip_rpi_semantic("semantic") + file = YOLO(TASK2MODEL["semantic"]).export(format="onnx", imgsz=32) + r = YOLO(file).predict(SOURCE, imgsz=32, dnn=True) + assert r[0].semantic_mask is not None + Path(file).unlink() + + +@pytest.mark.slow +@pytest.mark.parametrize( + "task, dynamic, batch, nms", + [ # generate all combinations except for exclusion cases + (task, dynamic, batch, nms) + for task, dynamic, batch, nms in product(TASKS, [False, True], [1, 2], [None, True, False]) + if not (task == "classify" and nms is True) + ], +) +def test_export_torchscript_matrix(task, dynamic, batch, nms, tmp_path): + """Test YOLO model export to TorchScript format under varied configurations.""" + skip_rpi_semantic(task) + file = YOLO(isolated_model_path(tmp_path, WEIGHTS_DIR / TASK2MODEL[task])).export( + format="torchscript", imgsz=32, dynamic=dynamic, batch=batch, nms=nms + ) + YOLO(file)([SOURCE] * batch, imgsz=64 if dynamic else 32) # exported model inference + Path(file).unlink() # cleanup + + +@pytest.mark.slow +@pytest.mark.skipif(not MACOS, reason="CoreML inference only supported on macOS") +@pytest.mark.skipif(not TORCH_1_11, reason="CoreML export requires torch>=1.11") +@pytest.mark.skipif( + MACOS and MACOS_VERSION and MACOS_VERSION >= "15", reason="CoreML YOLO26 matrix test crashes on macOS 15+" +) +@pytest.mark.parametrize( + "task, dynamic, quantize, nms, batch", + [ # generate all combinations except for exclusion cases + (task, dynamic, quantize, nms, batch) + for task, dynamic, quantize, nms, batch in product(TASKS, [True, False], [8, 16], [None, True, False], [1]) + if not (task not in {"detect", "segment", "pose"} and nms is True) + and not (dynamic and nms is True) + and not (task == "classify" and dynamic) + ], +) +def test_export_coreml_matrix(task, dynamic, quantize, nms, batch): + """Test YOLO export to CoreML format with various parameter configurations.""" + skip_rpi_semantic(task) + file = YOLO(TASK2MODEL[task]).export( + format="coreml", + imgsz=32, + dynamic=dynamic, + quantize=quantize, + batch=batch, + nms=nms, + ) + YOLO(file)([SOURCE] * batch, imgsz=32) # exported model inference + shutil.rmtree(file) # cleanup + + +@pytest.mark.skipif(not TORCH_1_11, reason="CoreML export requires torch>=1.11") +@pytest.mark.skipif(WINDOWS, reason="CoreML not supported on Windows") # RuntimeError: BlobWriter not loaded +@pytest.mark.skipif(LINUX and ARM64, reason="CoreML not supported on aarch64 Linux") +@pytest.mark.skipif( + MACOS and checks.IS_PYTHON_MINIMUM_3_13, + reason="coremltools deadlocks after OpenVINO on macOS Python 3.13 (conflicting OpenMP runtimes)", +) +@pytest.mark.parametrize("format", ["coreml", "mlmodel"]) +def test_export_coreml(isolated_model, format, monkeypatch, tmp_path): + """Test YOLO export to CoreML format and check for errors.""" + from ultralytics.utils.export import coreml + + quantize, torch2coreml = [], coreml.torch2coreml + + def capture_quantize(*args, **kwargs): + quantize.append(kwargs["quantize"]) + return torch2coreml(*args, **kwargs) + + monkeypatch.setattr(coreml, "torch2coreml", capture_quantize) + # Capture stdout and stderr + stdout, stderr = io.StringIO(), io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + file = YOLO(isolated_model_path(tmp_path, WEIGHTS_DIR / "yolo11n.pt")).export( + format=format, nms=True, imgsz=32, iou=0.42, conf=0.24 + ) + import coremltools as ct + + spec = ct.utils.load_spec(str(file)) + metadata = spec.description.metadata + assert metadata.author and metadata.shortDescription and metadata.license and metadata.versionString + assert metadata.userDefined["IoU threshold"] == "0.42" + assert metadata.userDefined["Confidence threshold"] == "0.24" + assert all(key in metadata.userDefined for key in ("names", "stride", "task")) + assert next(iter(spec.pipeline.models[1].nonMaximumSuppression.stringClassLabels.vector)) == "person" + assert [output.name for output in spec.description.output] == ["confidence", "coordinates"] + if MACOS: + file = YOLO(isolated_model).export(format="coreml", imgsz=32) + YOLO(file)(SOURCE, imgsz=32) # model prediction only supported on macOS for raw-output models + + # Check captured output for errors + output = stdout.getvalue() + stderr.getvalue() + assert quantize[0] == (16 if format == "coreml" else None) + assert "Error" not in output, f"CoreML export produced errors: {output}" + assert "You will not be able to run predict()" not in output, "CoreML export has predict() error" + + +@pytest.mark.skipif(not TORCH_1_11, reason="RTDETR CoreML export requires torch>=1.11") +@pytest.mark.skipif(WINDOWS, reason="CoreML not supported on Windows") +@pytest.mark.skipif(LINUX and ARM64, reason="CoreML not supported on aarch64 Linux") +@pytest.mark.skipif( + MACOS and checks.IS_PYTHON_MINIMUM_3_13, + reason="coremltools deadlocks after OpenVINO on macOS Python 3.13 (conflicting OpenMP runtimes)", +) +def test_export_coreml_rtdetr(): + """Test RT-DETR export to CoreML format and check for errors.""" + stdout, stderr = io.StringIO(), io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + file = YOLO(WEIGHTS_DIR / "rtdetr-l.pt").export(format="coreml", imgsz=160) + import coremltools as ct + + shape = ct.models.MLModel(str(file)).get_spec().description.output[0].type.multiArrayType.shape + assert shape[-2] == 300 + if MACOS: + YOLO(file)(SOURCE, imgsz=160) + + output = stdout.getvalue() + stderr.getvalue() + assert "Error" not in output, f"RTDETR CoreML export produced errors: {output}" + assert "You will not be able to run predict()" not in output, "RTDETR CoreML export has predict() error" + + +@pytest.mark.skipif(True, reason="Test disabled") +@pytest.mark.skipif(not LINUX, reason="TF suffers from install conflicts on Windows and macOS") +def test_export_pb(isolated_model): + """Test YOLO export to TensorFlow's Protobuf (*.pb) format.""" + model = YOLO(isolated_model) + file = model.export(format="pb", imgsz=32) + YOLO(file)(SOURCE, imgsz=32) + + +@pytest.mark.skipif(True, reason="Test disabled as Paddle protobuf and ONNX protobuf requirements conflict.") +def test_export_paddle(isolated_model): + """Test YOLO export to Paddle format, noting protobuf conflicts with ONNX.""" + YOLO(isolated_model).export(format="paddle", imgsz=32) + + +@pytest.mark.skipif(not TORCH_1_10, reason="MNN export requires torch>=1.10") +@pytest.mark.skipif( + LINUX and checks.IS_PYTHON_MINIMUM_3_13, + reason="MNN ONNX-parser protobuf conflicts with TensorFlow protobuf>=6.31.1 loaded earlier in the shared Python 3.13 test process", +) +def test_export_mnn(isolated_model): + """Test YOLO export to MNN format (WARNING: MNN test must precede NCNN test or CI error on Windows).""" + file = YOLO(isolated_model).export(format="mnn", imgsz=32) + YOLO(file)(SOURCE, imgsz=32) # exported model inference + + +@pytest.mark.parametrize( + "model,kwargs,error", + [ + ("yolo11n.yaml", {"batch": 2, "dynamic": True, "nms": True}, "combining"), + ("yolo11n-seg.yaml", {"nms": True}, "only supports detect and pose"), + ("yolo11n-obb.yaml", {"nms": True}, "only supports detect and pose"), + ], +) +def test_export_mnn_rejects_unsupported_nms(model, kwargs, error): + """Test MNN rejects NMS combinations that fail or lose task outputs at runtime.""" + with pytest.raises(ValueError, match=error): + YOLO(model).export(format="mnn", imgsz=32, **kwargs) + + +@pytest.mark.slow +@pytest.mark.parametrize( + "model,task,kwargs", + [ + ("yolo11n.yaml", "detect", {"batch": 2, "dynamic": True}), + ("yolo11n.yaml", "detect", {"nms": True}), + ("yolo11n-pose.yaml", "pose", {"nms": True}), + ], +) +def test_export_mnn_options(model, task, kwargs): + """Test MNN dynamic shapes and supported embedded NMS tasks through inference.""" + batch = kwargs.get("batch", 1) + file = YOLO(model).export(format="mnn", imgsz=32, **kwargs) + assert len(YOLO(file, task=task)([SOURCE] * batch, imgsz=64 if kwargs.get("dynamic") else 32)) == batch + Path(file).unlink() + + +@pytest.mark.slow +@pytest.mark.skipif(not TORCH_1_10, reason="MNN export requires torch>=1.10") +@pytest.mark.parametrize( + "task, quantize, batch, nms", + [ # generate all combinations except for exclusion cases + (task, quantize, batch, nms) for task, quantize, batch, nms in product(TASKS, [8, 16], [1, 2], [None, False]) + ], +) +def test_export_mnn_matrix(task, quantize, batch, nms): + """Test YOLO export to MNN format considering various export configurations.""" + skip_rpi_semantic(task) + file = YOLO(TASK2MODEL[task]).export(format="mnn", imgsz=32, quantize=quantize, batch=batch, nms=nms) + YOLO(file)([SOURCE] * batch, imgsz=32) # exported model inference + Path(file).unlink() # cleanup + + +@pytest.mark.skipif(not TORCH_2_0, reason="NCNN inference causes segfault on PyTorch<2.0") +def test_export_ncnn(isolated_model): + """Test YOLO export to NCNN format.""" + file = YOLO(isolated_model).export(format="ncnn", imgsz=32) + YOLO(file)(SOURCE, imgsz=32) # exported model inference + + +@pytest.mark.slow +@pytest.mark.skipif(not TORCH_2_0, reason="NCNN inference causes segfault on PyTorch<2.0") +@pytest.mark.parametrize("task, quantize, batch", list(product(sorted(TASKS), [16], [1]))) +def test_export_ncnn_matrix(task, quantize, batch): + """Test YOLO export to NCNN format considering various export configurations.""" + skip_rpi_semantic(task) + file = YOLO(TASK2MODEL[task]).export(format="ncnn", imgsz=32, quantize=quantize, batch=batch) + YOLO(file)([SOURCE] * batch, imgsz=32) # exported model inference + shutil.rmtree(file, ignore_errors=True) # retry in case of potential lingering multi-threaded file usage errors + + +@pytest.mark.skipif(not TORCH_2_9, reason="IMX export requires torch>=2.9.0") +@pytest.mark.skipif(not checks.IS_PYTHON_MINIMUM_3_9, reason="IMX export requires Python>=3.9") +@pytest.mark.skipif(not LINUX, reason="IMX export only supported on Linux") +@pytest.mark.skipif( + IS_RASPBERRYPI, reason="Test disabled as IMX export suffers from OOM (Out of Memory) on Raspberry Pi 5 16GB" +) +@pytest.mark.parametrize("conf,expected", [(0.0, 0.0), (None, 0.25)]) +def test_export_imx(tmp_path, conf, expected): + """Test IMX export and inference, preserving zero confidence and the public export default.""" + import onnx + + model = YOLO(isolated_model_path(tmp_path, WEIGHTS_DIR / "yolo11n.pt")) + output_dir = model.export(format="imx", imgsz=32, data="coco8.yaml", conf=conf) + nodes = [ + n + for n in onnx.load(str(Path(output_dir) / "model_imx.onnx")).graph.node + if n.op_type == "MultiClassNMSWithIndices" + ] + assert len(nodes) == 1, "MultiClassNMSWithIndices node missing from the exported ONNX" + attrs = {a.name: a.f for a in nodes[0].attribute} + assert attrs["score_threshold"] == pytest.approx(expected) + YOLO(output_dir)(SOURCE, imgsz=32) + + +@pytest.mark.slow +@pytest.mark.skipif(not LINUX or ARM64, reason="RKNN export only supported on non-aarch64 Linux") +@pytest.mark.parametrize("quantize,batch", [(8, 8), (16, 1)]) +def test_export_rknn(isolated_model, quantize, batch): + """Test YOLO export to RKNN format.""" + file = YOLO(isolated_model).export(format="rknn", imgsz=32, quantize=quantize, batch=batch, data="coco8.yaml") + assert next(Path(file).rglob("*.rknn"), None), f"RKNN export failed, no RKNN model found in: {file}" + shutil.rmtree(file, ignore_errors=True) + + +# @pytest.mark.skipif(True, reason="Disabled for debugging ruamel.yaml installation required by executorch") +@pytest.mark.skipif(not checks.IS_PYTHON_MINIMUM_3_10 or not TORCH_2_9, reason="Requires Python>=3.10 and Torch>=2.9.0") +@pytest.mark.skipif(WINDOWS, reason="Skipping test on Windows") +def test_export_executorch(isolated_model): + """Test YOLO model export to ExecuTorch format.""" + file = YOLO(isolated_model).export(format="executorch", imgsz=32) + assert Path(file).exists(), f"ExecuTorch export failed, directory not found: {file}" + # Check that .pte file exists in the exported directory + pte_file = Path(file) / "model.pte" + assert pte_file.exists(), f"ExecuTorch .pte file not found: {pte_file}" + # Check that metadata.yaml exists + metadata_file = Path(file) / "metadata.yaml" + assert metadata_file.exists(), f"ExecuTorch metadata.yaml not found: {metadata_file}" + # Note: Inference testing skipped as ExecuTorch requires special runtime setup + shutil.rmtree(file, ignore_errors=True) # cleanup + + +@pytest.mark.slow +@pytest.mark.skipif(not (MACOS or (LINUX and not ARM64)), reason="LiteRT export only supported on Linux x86 and macOS") +@pytest.mark.skipif(not checks.IS_PYTHON_MINIMUM_3_10, reason="litert-torch requires Python>=3.10") +@pytest.mark.parametrize( + "task, quantize", + [(task, quantize) for task in sorted(TASKS) for quantize in (None, 8, "w8a16", "w8a32")], +) +def test_export_litert_matrix(task, quantize): + """Test YOLO export to LiteRT format (FP32, static INT8, static w8a16, and dynamic w8a32) for various tasks.""" + file = Path(YOLO(TASK2MODEL[task]).export(format="litert", imgsz=32, quantize=quantize)) + assert file.is_file() and file.suffix == ".tflite", f"LiteRT export is not a single .tflite for '{task}': {file}" + # Contract: exports keep float32 graph I/O (int8/int16 stays internal) so downstream runtimes feed/read floats + # without boundary (de)quantization; an int8/int16 I/O regression would silently break on-device consumers. + import numpy as np + from ai_edge_litert.interpreter import Interpreter + + interpreter = Interpreter(model_path=str(file)) + interpreter.allocate_tensors() + io_details = interpreter.get_input_details() + interpreter.get_output_details() + assert all(d["dtype"] == np.float32 for d in io_details), ( + f"LiteRT '{task}' quantize={quantize} must keep float32 I/O, got {[d['dtype'] for d in io_details]}" + ) + YOLO(file)(SOURCE, imgsz=32) # exported model inference (also exercises the embedded metadata) + file.unlink() # cleanup + + +@pytest.mark.slow +@pytest.mark.skipif(not checks.IS_PYTHON_MINIMUM_3_10 or not TORCH_2_9, reason="Requires Python>=3.10 and Torch>=2.9.0") +@pytest.mark.skipif(WINDOWS, reason="Skipping test on Windows") +@pytest.mark.parametrize("task", sorted(TASKS)) +def test_export_executorch_matrix(task): + """Test YOLO export to ExecuTorch format for various task types.""" + skip_rpi_semantic(task) + file = YOLO(TASK2MODEL[task]).export(format="executorch", imgsz=32) + assert Path(file).exists(), f"ExecuTorch export failed for task '{task}', directory not found: {file}" + # Check that .pte file exists in the exported directory + pte_file = Path(file) / "model.pte" + assert pte_file.exists(), f"ExecuTorch .pte file not found for task '{task}': {pte_file}" + # Check that metadata.yaml exists + metadata_file = Path(file) / "metadata.yaml" + assert metadata_file.exists(), f"ExecuTorch metadata.yaml not found for task '{task}': {metadata_file}" + # Note: Inference testing skipped as ExecuTorch requires special runtime setup + shutil.rmtree(file, ignore_errors=True) # cleanup + + +@pytest.mark.skipif( + not (WINDOWS or LINUX) or sys.version_info < (3, 11), + reason="onnxruntime-qnn ships prebuilt wheels only for Windows and Linux on Python>=3.11", +) +def test_export_qnn(isolated_model): + """Test YOLO export to Qualcomm QNN format via the ONNX Runtime QNN Execution Provider.""" + import importlib.util + + # QNN EP ships either as the 'onnxruntime_qnn' plugin module or as a provider library bundled in onnxruntime/capi. + has_qnn = importlib.util.find_spec("onnxruntime_qnn") is not None + if not has_qnn and importlib.util.find_spec("onnxruntime") is not None: + import onnxruntime + + capi = Path(onnxruntime.__file__).parent / "capi" + has_qnn = (capi / "libonnxruntime_providers_qnn.so").exists() or ( + capi / "onnxruntime_providers_qnn.dll" + ).exists() + if not has_qnn: + pytest.skip("onnxruntime-qnn / QNN Execution Provider not available") + file = YOLO(isolated_model).export(format="qnn", imgsz=32) + assert Path(file).is_file() and file.endswith("_qnn.onnx"), f"QNN export failed, no context binary found: {file}" + # Note: on-device inference is not exercised here as it requires Qualcomm Snapdragon hardware + Path(file).unlink(missing_ok=True) # cleanup + + +@pytest.mark.parametrize("env", [k for k, v in EXPORT_ENVS.items() if k != "base" or v["smoke"]]) +def test_export_env_has_smoke(env): + """Ensure every non-base export environment declares a build-time smoke export.""" + assert EXPORT_ENVS[env]["smoke"], f"export env '{env}' has no smoke command" + + +def test_every_format_env_is_registered(): + """Ensure every export format points at a registered export environment.""" + for fmt, env in zip(export_formats()["Argument"], export_formats()["Env"]): + assert env in EXPORT_ENVS, f"format '{fmt}' references unknown env '{env}'" diff --git a/.venv/lib/python3.12/site-packages/tests/test_integrations.py b/.venv/lib/python3.12/site-packages/tests/test_integrations.py new file mode 100644 index 0000000000000000000000000000000000000000..71568a0e4160400aa7e47801e9e32ba1222efb54 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tests/test_integrations.py @@ -0,0 +1,155 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import contextlib +import subprocess +import time +from pathlib import Path + +import pytest + +from tests import SOURCE +from ultralytics import YOLO, download +from ultralytics.utils import ASSETS_URL, DATASETS_DIR, SETTINGS +from ultralytics.utils.checks import check_requirements + + +@pytest.mark.slow +def test_tensorboard(): + """Test training with TensorBoard logging enabled.""" + SETTINGS["tensorboard"] = True + YOLO("yolo26n-cls.yaml").train(data="imagenet10", imgsz=32, epochs=3, plots=False, device="cpu") + SETTINGS["tensorboard"] = False + + +@pytest.mark.skipif(not check_requirements("ray", install=False), reason="ray[tune] not installed") +def test_model_ray_tune(): + """Tune YOLO model using Ray for hyperparameter optimization.""" + YOLO("yolo26n-cls.yaml").tune( + use_ray=True, data="imagenet10", grace_period=1, iterations=1, imgsz=32, epochs=1, plots=False, device="cpu" + ) + + +@pytest.mark.skipif(not check_requirements("mlflow", install=False), reason="mlflow not installed") +def test_mlflow(tmp_path, monkeypatch): + """Test training with MLflow tracking enabled.""" + import mlflow + + monkeypatch.setenv("MLFLOW_TRACKING_URI", f"sqlite:///{(tmp_path / 'mlflow.db').as_posix()}") + monkeypatch.setenv("MLFLOW_EXPERIMENT_NAME", "test_mlflow") + monkeypatch.setitem(SETTINGS, "mlflow", True) + try: + YOLO("yolo26n-cls.yaml").train(data="imagenet10", imgsz=32, epochs=3, plots=False, device="cpu") + finally: + mlflow.autolog(disable=True) + mlflow.end_run() + + +@pytest.mark.skipif(not check_requirements("mlflow", install=False), reason="mlflow not installed") +def test_mlflow_keep_run_active(tmp_path, monkeypatch): + """Ensure MLFLOW_KEEP_RUN_ACTIVE controls whether new MLflow runs remain active.""" + import mlflow + + monkeypatch.setenv("MLFLOW_TRACKING_URI", f"sqlite:///{(tmp_path / 'mlflow.db').as_posix()}") + monkeypatch.setenv("MLFLOW_EXPERIMENT_NAME", "keep_run_active") + monkeypatch.setenv("MLFLOW_RUN", "Test Run") + monkeypatch.setitem(SETTINGS, "mlflow", True) + try: + monkeypatch.setenv("MLFLOW_KEEP_RUN_ACTIVE", "True") + YOLO("yolo26n-cls.yaml").train(data="imagenet10", imgsz=32, epochs=1, plots=False, device="cpu") + active = mlflow.active_run() + assert active is not None and active.info.status == "RUNNING", ( + "MLflow run should be active when MLFLOW_KEEP_RUN_ACTIVE=True" + ) + mlflow.end_run() + + monkeypatch.setenv("MLFLOW_KEEP_RUN_ACTIVE", "False") + YOLO("yolo26n-cls.yaml").train(data="imagenet10", imgsz=32, epochs=1, plots=False, device="cpu") + assert mlflow.active_run() is None, "MLflow run should be ended when MLFLOW_KEEP_RUN_ACTIVE=False" + + monkeypatch.delenv("MLFLOW_KEEP_RUN_ACTIVE", raising=False) + YOLO("yolo26n-cls.yaml").train(data="imagenet10", imgsz=32, epochs=1, plots=False, device="cpu") + assert mlflow.active_run() is None, "MLflow run should be ended by default when MLFLOW_KEEP_RUN_ACTIVE is unset" + finally: + mlflow.autolog(disable=True) + mlflow.end_run() + + +@pytest.mark.skipif(not check_requirements("tritonclient", install=False), reason="tritonclient[all] not installed") +def test_triton(tmp_path, isolated_model): + """Test NVIDIA Triton Server functionalities with YOLO model.""" + check_requirements("tritonclient[all]") + from tritonclient.http import InferenceServerClient + + # Create variables + model_name = "yolo" + triton_repo = tmp_path / "triton_repo" # Triton repo path + triton_model = triton_repo / model_name # Triton model path + + # Export model to ONNX + f = YOLO(isolated_model).export(format="onnx", dynamic=True) + + # Prepare Triton repo + (triton_model / "1").mkdir(parents=True, exist_ok=True) + Path(f).rename(triton_model / "1" / "model.onnx") + (triton_model / "config.pbtxt").touch() + + # Define image https://catalog.ngc.nvidia.com/orgs/nvidia/containers/tritonserver + tag = "nvcr.io/nvidia/tritonserver:23.09-py3" # 6.4 GB + + # Pull the image + subprocess.call(f"docker pull {tag}", shell=True) + + # Run the Triton server and capture the container ID + container_id = ( + subprocess.check_output( + f"docker run -d --rm -v {triton_repo}:/models -p 8000:8000 {tag} tritonserver --model-repository=/models", + shell=True, + ) + .decode("utf-8") + .strip() + ) + + # Wait for the Triton server to start + triton_client = InferenceServerClient(url="localhost:8000", verbose=False, ssl=False) + + # Wait until model is ready + for _ in range(10): + with contextlib.suppress(Exception): + assert triton_client.is_model_ready(model_name) + break + time.sleep(1) + + # Check Triton inference + YOLO(f"http://localhost:8000/{model_name}", "detect")(SOURCE) # exported model inference + + # Kill and remove the container at the end of the test + subprocess.call(f"docker kill {container_id}", shell=True) + + +@pytest.mark.skipif(not check_requirements("faster-coco-eval", install=False), reason="faster-coco-eval not installed") +def test_faster_coco_eval(): + """Validate YOLO model predictions on COCO dataset using faster-coco-eval.""" + from ultralytics.models.yolo.detect import DetectionValidator + from ultralytics.models.yolo.pose import PoseValidator + from ultralytics.models.yolo.segment import SegmentationValidator + + args = {"model": "yolo26n.pt", "data": "coco8.yaml", "save_json": True, "imgsz": 64} + validator = DetectionValidator(args=args) + validator() + validator.is_coco = True + download(f"{ASSETS_URL}/instances_val2017.json", dir=DATASETS_DIR / "coco8/annotations") + _ = validator.eval_json(validator.stats) + + args = {"model": "yolo26n-seg.pt", "data": "coco8-seg.yaml", "save_json": True, "imgsz": 64} + validator = SegmentationValidator(args=args) + validator() + validator.is_coco = True + download(f"{ASSETS_URL}/instances_val2017.json", dir=DATASETS_DIR / "coco8-seg/annotations") + _ = validator.eval_json(validator.stats) + + args = {"model": "yolo26n-pose.pt", "data": "coco8-pose.yaml", "save_json": True, "imgsz": 64} + validator = PoseValidator(args=args) + validator() + validator.is_coco = True + download(f"{ASSETS_URL}/person_keypoints_val2017.json", dir=DATASETS_DIR / "coco8-pose/annotations") + _ = validator.eval_json(validator.stats) diff --git a/.venv/lib/python3.12/site-packages/tests/test_ndjson_converter.py b/.venv/lib/python3.12/site-packages/tests/test_ndjson_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..33de853f6eac479de12687ec06c96009b06e503e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tests/test_ndjson_converter.py @@ -0,0 +1,195 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import asyncio +import json +import threading +from functools import partial +from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer + +import cv2 +import numpy as np +import pytest + +from ultralytics.data.converter import convert_ndjson_to_yolo +from ultralytics.data.utils import load_depth, save_depth_png +from ultralytics.utils import YAML + + +class _QuietHandler(SimpleHTTPRequestHandler): + """Serve converter fixtures without writing requests to the test log.""" + + def log_message(self, _format, *args): + pass + + +def _write_manifest(path, base_url, *, missing_depth=False, depth_scale=None): + records = [ + {"type": "dataset", "task": "depth", **({"depth_scale": depth_scale} if depth_scale else {})}, + { + "type": "image", + "file": "camera/train.jpg", + "url": f"{base_url}/train.jpg?signature=image", + "split": "train", + "depth": { + "url": f"{base_url}/train.png?signature=depth", + "hash": "depth-train", + "shape": [3, 4], + }, + }, + { + "type": "image", + "file": "val.jpg", + "url": f"{base_url}/test.jpg?signature=image", + "split": "val", + "depth": { + "url": f"{base_url}/missing.png" if missing_depth else f"{base_url}/test.png?signature=depth", + "hash": "depth-test", + "shape": [3, 4], + }, + }, + ] + path.write_text("\n".join(json.dumps(record) for record in records)) + + +@pytest.fixture +def depth_server(tmp_path): + """Serve paired image and depth fixtures over HTTP.""" + source = tmp_path / "source" + source.mkdir() + depth = np.arange(12, dtype=np.float32).reshape(3, 4) + for split, value in (("train", 0), ("test", 255)): + cv2.imwrite(str(source / f"{split}.jpg"), np.full((3, 4, 3), value, dtype=np.uint8)) + save_depth_png(source / f"{split}.png", depth) + server = ThreadingHTTPServer(("127.0.0.1", 0), partial(_QuietHandler, directory=source)) + server.daemon_threads = True + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield f"http://127.0.0.1:{server.server_port}", depth + finally: + server.shutdown() + server.server_close() + thread.join() + + +def test_convert_depth_ndjson_downloads_image_target_pairs(tmp_path, depth_server): + """Download depth targets beside images using matching indexed stems and the default scale.""" + base_url, depth = depth_server + manifest = tmp_path / "depth.ndjson" + _write_manifest(manifest, base_url) + + yaml_path = asyncio.run(convert_ndjson_to_yolo(manifest, tmp_path / "datasets")) + + data = YAML.load(yaml_path) + assert data["task"] == "depth" + assert data["nc"] == 1 + assert data["names"] == {0: "depth"} + assert data["depth_scale"] == 1000 + assert data["train"] == "images/train" + assert data["val"] == "images/val" + assert not (yaml_path.parent / "labels").exists() + for index, split in enumerate(("train", "val"), 1): + assert (yaml_path.parent / "images" / split / f"{index}.jpg").is_file() + np.testing.assert_allclose(load_depth(yaml_path.parent / "depth" / split / f"{index}.png"), depth, atol=1e-3) + + +def test_convert_depth_ndjson_preserves_scale(tmp_path, depth_server): + """Copy a dataset-level PNG scale into the generated training YAML.""" + base_url, _ = depth_server + manifest = tmp_path / "depth.ndjson" + _write_manifest(manifest, base_url, depth_scale=256) + + data = YAML.load(asyncio.run(convert_ndjson_to_yolo(manifest, tmp_path / "datasets"))) + + assert data["depth_scale"] == 256 + + +def test_convert_depth_ndjson_reuses_existing_conversion(tmp_path, depth_server, monkeypatch): + """Reuse a complete subset and reconvert when its completion marker is invalidated.""" + base_url, _ = depth_server + manifest = tmp_path / "depth.ndjson" + _write_manifest(manifest, base_url) + yaml_path = asyncio.run(convert_ndjson_to_yolo(manifest, tmp_path / "datasets", fraction=[1, 1])) + + monkeypatch.setattr(YAML, "save", lambda *_args, **_kwargs: pytest.fail("cache missed")) + assert asyncio.run(convert_ndjson_to_yolo(manifest, tmp_path / "datasets", fraction=[1.0, 1.0])) == yaml_path + + monkeypatch.undo() + depth_path = yaml_path.parent / "depth" / "val" / "2.png" + depth_path.unlink() + data = YAML.load(yaml_path) + data.pop("complete") + YAML.save(yaml_path, data) + assert asyncio.run(convert_ndjson_to_yolo(manifest, tmp_path / "datasets", fraction=[1, 1])) == yaml_path + assert depth_path.is_file() + + +def test_convert_depth_ndjson_removes_incomplete_pair(tmp_path, depth_server): + """Fail depth conversion without leaving an image whose paired target failed to download.""" + base_url, _ = depth_server + manifest = tmp_path / "incomplete.ndjson" + _write_manifest(manifest, base_url, missing_depth=True) + + with pytest.raises(RuntimeError, match=r"Downloaded 1/2 images"): + asyncio.run(convert_ndjson_to_yolo(manifest, tmp_path / "datasets")) + + dataset_dir = next(p for p in (tmp_path / "datasets").iterdir() if p.is_dir()) + assert not (dataset_dir / "images" / "val" / "2.jpg").exists() + assert not (dataset_dir / "depth" / "val" / "2.png").exists() + assert not (dataset_dir / "data.yaml").exists() + + +def test_convert_depth_ndjson_rejects_missing_url(tmp_path): + """Reject a missing depth URL before issuing downloads.""" + manifest = tmp_path / "invalid.ndjson" + records = [ + {"type": "dataset", "task": "depth"}, + { + "type": "image", + "file": "train.jpg", + "url": "http://127.0.0.1:1/train.jpg", + "split": "train", + "depth": {}, + }, + ] + manifest.write_text("\n".join(json.dumps(record) for record in records)) + + with pytest.raises(ValueError, match=r"missing depth\.url"): + asyncio.run(convert_ndjson_to_yolo(manifest, tmp_path / "datasets")) + + +def test_convert_ndjson_selects_split_fractions(tmp_path, depth_server): + """Select requested splits while preserving full metadata and two-item list behavior.""" + base_url, _ = depth_server + records = [ + {"type": "dataset", "task": "detect"}, + *[ + { + "type": "image", + "file": f"{index}.jpg", + "url": f"{base_url}/train.jpg?signature={index}", + "split": "test" if index == 9 else "train", + "annotations": {"boxes": [[2 if index == 9 else 0, 0.5, 0.5, 1, 1]]}, + } + for index in range(10) + ], + ] + manifest = tmp_path / "detect.ndjson" + manifest.write_text("\n".join(json.dumps(record) for record in records)) + + for fraction, split, expected_test in ( + ([0.25, 1], None, {"10.jpg"}), + ([0.25, 1, 0], None, set()), + ([0.25, 1], "val", set()), + ([0.25, 1], "test", {"10.jpg"}), + ): + yaml_path = asyncio.run(convert_ndjson_to_yolo(manifest, tmp_path / "datasets", fraction=fraction, split=split)) + files = [ + {p.name for p in (yaml_path.parent / "images" / split).glob("*")} for split in ("train", "val", "test") + ] + assert files == [{"1.jpg", "9.jpg"}, {"8.jpg"}, expected_test] + assert YAML.load(yaml_path)["nc"] == 3 + + yaml_path = asyncio.run(convert_ndjson_to_yolo(manifest, tmp_path / "datasets", fraction=0.05)) + train = {p.name for p in (yaml_path.parent / "images" / "train").glob("*")} + assert train == {"1.jpg"} # round(9 * 0.05) == 0, yet a nonzero fraction must never write an empty split diff --git a/.venv/lib/python3.12/site-packages/tests/test_python.py b/.venv/lib/python3.12/site-packages/tests/test_python.py new file mode 100644 index 0000000000000000000000000000000000000000..ea656a48f647f24551b771c16fc98a4c2529ca64 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tests/test_python.py @@ -0,0 +1,2295 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import contextlib +import csv +import os +import platform +import shutil +import tarfile +import urllib +import zipfile +from copy import copy +from pathlib import Path + +import cv2 +import numpy as np +import pytest +import torch +from PIL import Image + +import ultralytics.data.build as data_build +from tests import CFG, MODEL, MODELS, SOURCE, SOURCES_LIST, TASK_MODEL_DATA +from ultralytics import RTDETR, YOLO +from ultralytics.cfg import get_cfg +from ultralytics.data.build import build_dataloader, load_inference_source +from ultralytics.data.utils import check_cls_dataset, check_det_dataset, get_split_fraction +from ultralytics.utils import ( + ARM64, + ASSETS, + ASSETS_URL, + DATASETS_DIR, + DEFAULT_CFG, + DEFAULT_CFG_PATH, + IS_JETSON, + IS_RASPBERRYPI, + LINUX, + LOGGER, + ONLINE, + ROOT, + WEIGHTS_DIR, + WINDOWS, + YAML, + checks, + is_github_action_running, +) +from ultralytics.utils.downloads import download, safe_download +from ultralytics.utils.torch_utils import TORCH_1_10, TORCH_1_11, TORCH_1_13, TORCH_2_0 + + +def test_dataloader_caps_workers_to_batches(): + """Test tiny datasets do not spawn persistent workers beyond useful batch count.""" + single_batch = build_dataloader(range(4), batch=4, workers=8) + drop_last_single_batch = build_dataloader(range(5), batch=4, workers=8, drop_last=True) + two_batches = build_dataloader(range(8), batch=4, workers=8) + try: + assert single_batch.num_workers == 0 + assert drop_last_single_batch.num_workers == 0 + assert two_batches.num_workers <= 2 + finally: + single_batch.close() + drop_last_single_batch.close() + two_batches.close() + + +def test_dataloader_cap_preserves_distributed_drop_last(monkeypatch): + """Test worker cap follows distributed sampler size without changing global drop_last behavior.""" + sampler_cls = data_build.distributed.DistributedSampler + + def distributed_sampler(dataset, shuffle, seed): + return sampler_cls(dataset, num_replicas=3, rank=2, shuffle=shuffle, seed=seed) + + monkeypatch.setattr(data_build.distributed, "DistributedSampler", distributed_sampler) + monkeypatch.setattr(data_build, "RANK", 2) # Simulate the second node with global rank 2 and local rank 0 + expected_seed = torch.initial_seed() - 3 + loader = build_dataloader(range(8), batch=4, workers=8, rank=0, drop_last=True) + try: + assert len(loader) == 1 + assert loader.num_workers == 0 + assert loader.sampler.seed == expected_seed + finally: + loader.close() + + +def test_dataloader_seed_varies_sampling_order(): + """Test the run seed reaches the loader RNG instead of every run replaying one fixed order.""" + with torch.random.fork_rng(): + loaders = [] + for seed in (0, 0, 1): + torch.manual_seed(seed) + loaders.append(build_dataloader(range(64), batch=4, workers=0)) + try: + first, repeat, other = (torch.cat(list(loader)).tolist() for loader in loaders) + assert first == repeat # same seed stays reproducible + assert first != other # different seeds must not share one order + finally: + for loader in loaders: + loader.close() + + +def test_dataloader_empty_dataset_uses_dataloader_validation(): + """Test empty datasets fail through DataLoader validation instead of worker-cap math.""" + with pytest.raises(ValueError, match="positive integer"): + build_dataloader([], batch=4, workers=2) + + +def test_image_cache_shared_with_spawned_workers(): + """Test the RAM image cache reaches spawned DataLoader workers as one shared buffer with intact contents.""" + from ultralytics.data.base import BaseDataset + + images = [np.full((8, 8, 3), i, dtype=np.uint8) for i in range(8)] + cache = BaseDataset._ImageCache(list(images)) + loader = torch.utils.data.DataLoader( + cache, batch_size=4, sampler=range(8), num_workers=2, multiprocessing_context="spawn" + ) + assert torch.equal(torch.cat(list(loader)), torch.from_numpy(np.stack(images))) + assert cache.buffer.is_shared() + + +def test_build_yolo_dataset_hyp_isolated(): + """Test dataset construction never mutates hyperparameters on the shared cfg it was built from.""" + data = check_det_dataset("coco8.yaml") + cfg = get_cfg(overrides={"data": "coco8.yaml", "imgsz": 32, "rect": True}) # rect zeroes mosaic on the hyp used + data_build.build_yolo_dataset(cfg, data["train"], batch=2, data=data, mode="train") + assert cfg.mosaic == DEFAULT_CFG.mosaic + + +def test_cfg_rejects_fuzzed_values(): + """Test invalid overrides fail in config validation.""" + with pytest.raises(TypeError, match="degrees"): + get_cfg(overrides={"degrees": None}) + with pytest.raises(ValueError, match="cls_pw"): + get_cfg(overrides={"cls_pw": 10}) + for key, value in ( + ("split", []), + ("split", -0.0), + ("epochs", 0), + ("epochs", -1), + ("optimizer", []), + ("copy_paste_mode", {}), + ("optimizer", None), + ("split", None), + ("copy_paste_mode", None), + ("patience", -1), + ): + with pytest.raises((TypeError, ValueError), match=key): + get_cfg(overrides={key: value}) + assert get_cfg(overrides={"fraction": 1}).fraction == 1.0 + assert get_cfg(overrides={"fraction": [1000, 1, 0]}).fraction == [1000, 1.0, 0.0] + assert type(get_split_fraction([1, 1, 0], "train")) is float + assert type(get_split_fraction([1, 1, 0], "test")) is float + with pytest.raises(ValueError, match="val fraction"): + get_split_fraction([1, 0], "val") + with pytest.raises(TypeError, match="fraction"): + get_cfg(overrides={"fraction": True}) + assert get_cfg(overrides={"auto_augment": None}).auto_augment is None + assert get_cfg(overrides={"end2end": True, "nms": True}).nms is False + assert get_cfg(overrides={"end2end": False, "nms": False}).nms is None + assert get_cfg(overrides={"end2end": False, "nms": True}).nms is True + + +def skip_rpi_semantic(): + """Skip semantic segmentation tests on Raspberry Pi due to memory constraints.""" + if IS_RASPBERRYPI: + pytest.skip("Semantic segmentation tests are skipped on Raspberry Pi due to memory constraints.") + + +def test_select_device(monkeypatch): + """The same device string must resolve to the same GPU on every call, and the environment is never mutated.""" + from ultralytics.utils import torch_utils + + set_calls = [] + monkeypatch.setattr(torch_utils.torch.cuda, "is_available", lambda: True) + monkeypatch.setattr(torch_utils.torch.cuda, "device_count", lambda: 2) + monkeypatch.setattr(torch_utils.torch.cuda, "current_device", lambda: 0) + monkeypatch.setattr(torch_utils.torch.cuda, "set_device", set_calls.append) + monkeypatch.setattr(torch_utils, "get_gpu_info", lambda i: f"Mock GPU {i}, 1MiB") + monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising=False) + assert str(torch_utils.select_device("", verbose=False)) == "cuda:0" + assert not set_calls # default '' request must never move the current device, e.g. diagnostics like check_yolo() + for _ in range(2): # repeated calls are idempotent, e.g. Trainer.__init__ then final_eval, or predict() twice + assert str(torch_utils.select_device("1", verbose=False)) == "cuda:1" + with pytest.raises(ValueError): + torch_utils.select_device("3", verbose=False) + assert os.environ.get("CUDA_VISIBLE_DEVICES") is None # CUDA_VISIBLE_DEVICES never written + assert set_calls == [1, 1] # explicit single-GPU requests set the default device for indexless 'cuda' operations + assert str(torch_utils.select_device("0,1", verbose=False)) == "cuda:0" + assert set_calls == [1, 1] # multi-GPU requests never move the current device; DDP ranks pin theirs in _setup_ddp + monkeypatch.setattr(torch_utils.torch.cuda, "current_device", lambda: 1) + assert str(torch_utils.select_device("", verbose=False)) == "cuda:1" # default '' resolves to the current device + assert str(torch_utils.select_device(torch.device("cuda", 1), verbose=False)) == "cuda:1" + with pytest.raises(ValueError): # torch.device inputs are validated like strings, no raw CUDA errors + torch_utils.select_device(torch.device("cuda", 3), verbose=False) + set_calls.clear() + assert str(torch_utils.select_device(torch.device("cuda"), verbose=False)) == "cuda:1" + assert not set_calls # indexless torch.device('cuda') means the current device and never moves it + assert torch_utils.parse_device([0, 1]) == "0,1" + assert torch_utils.parse_device("00,01") == "0,1" # leading zeros stripped for valid torch device strings + assert torch_utils.parse_device(torch.device("cuda")) == "" # indexless 'cuda' stays the '' default request + # Physical GPU ids under an external CUDA_VISIBLE_DEVICES restriction translate to torch indices + monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "2,3") + assert str(torch_utils.select_device("3", verbose=False)) == "cuda:1" + monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "3") + monkeypatch.setattr(torch_utils.torch.cuda, "device_count", lambda: 1) + assert str(torch_utils.select_device("3", verbose=False)) == "cuda:0" # e.g. pods launched with CVD preset + assert torch_utils.parse_device(torch_utils.parse_device("3")) == "0" # idempotent: trainer + select_device parse + # '-1' idle-GPU auto-selection searches only externally visible GPUs and translates physical ids to torch indices + from ultralytics.utils import autodevice + + monkeypatch.setattr(autodevice.GPUInfo, "__init__", lambda self: self.__dict__.update(nvml_available=False)) + monkeypatch.setattr( + autodevice.GPUInfo, + "select_idle_gpu", + lambda self, count=1, indices=None, **kw: [i for i in (0, 1, 3) if i in indices][:count], + ) + monkeypatch.setattr(torch_utils.torch.cuda, "device_count", lambda: 2) + monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "1,3") + assert torch_utils.parse_device("-1") == "0" # idle physical GPU 1 is torch index 0 under CVD='1,3'; 0 is hidden + assert torch_utils.parse_device("1") == "1" # in-range ids are torch indices, so repeated parses are stable + assert torch_utils.parse_device("-1,3") == "0,1" # mixed: idle physical GPU 1 + physical GPU 3 as torch indices + assert torch_utils.parse_device("0,1") == "0,1" # already-translated outputs re-parse unchanged (idempotent) + monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "3,2,9,1") # malformed: CUDA stops at the invalid id 9, 2 usable GPUs + assert torch_utils.parse_device("9") == "9" # unusable id is not translated, so select_device rejects it + assert torch_utils.parse_device("2") == "1" # physical GPU 2 is torch index 1 of the usable prefix + monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "01,03") # leading zeros are valid for CUDA's atoi-style parsing + assert torch_utils.parse_device("3") == "1" # visible ids normalize like requested ids + assert torch_utils.parse_device("-1") == "0" # idle physical GPU 1 found via normalized visible ids + + +def test_autobackend_memory_format(tmp_path): + """Check backend memory formats on the real host platform without mocked platform state.""" + from ultralytics.nn.autobackend import AutoBackend + + cpu_supported = ( + TORCH_1_13 + and platform.machine() in {"AMD64", "x86_64"} + and torch.backends.mkldnn.is_available() + and torch.backends.mkldnn.enabled + ) + for channels_last in (None, False, True): + model = torch.nn.Sequential(torch.nn.Conv2d(3, 4, 3)) + backend = AutoBackend(model=model, device=torch.device("cpu"), channels_last=channels_last) + expected = cpu_supported and (channels_last is True or (channels_last is None and (LINUX or WINDOWS))) + assert model[0].weight.is_contiguous(memory_format=torch.channels_last) is expected + assert backend(torch.zeros(1, 3, 32, 32)).shape == (1, 4, 30, 30) + if hasattr(torch, "inference_mode"): + with torch.inference_mode(): + model = torch.nn.Sequential(torch.nn.Conv2d(3, 4, 3)) + backend = AutoBackend(model=model, device=torch.device("cpu")) + if TORCH_1_10: + assert not backend.model[0].weight.is_inference() + + model = YOLO(MODEL) + model.ckpt["ema"] = model.model # raw training checkpoints prefer EMA when reloaded + model.model.to(memory_format=torch.channels_last) + model.save(tmp_path / "model.pt") + assert all(x.is_contiguous() for x in YOLO(tmp_path / "model.pt").model.parameters()) + + +def test_restricted_load_threaded(): + """Concurrent restricted loads share one process-wide allow-list and must not strip each other's entries.""" + import pathlib + from concurrent.futures import ThreadPoolExecutor + + from ultralytics.nn.tasks import torch_safe_load + + windows_path = pathlib.WindowsPath + with ThreadPoolExecutor(8) as pool: + list(pool.map(lambda _: torch_safe_load(MODEL, safe_only=True), range(32))) + assert pathlib.WindowsPath is windows_path + + +@pytest.mark.parametrize("fused", [False, True]) +def test_restricted_load_criterion(tmp_path, fused): + """Legacy criterion metadata and fused forward bindings survive restricted checkpoint round trips.""" + from ultralytics.nn.tasks import DetectionModel, torch_safe_load + from ultralytics.utils import DEFAULT_CFG + + model = DetectionModel(CFG, verbose=False) + model.args = DEFAULT_CFG + model.criterion = model.init_criterion() + model.eval() + if fused: + model.fuse(verbose=False) + image = torch.zeros(1, 3, 64, 64) + with torch.no_grad(): + expected = model(image)[0] + torch.save({"model": model, "best_fitness": np.float64(0.5)}, tmp_path / "legacy.pt") + checkpoint = torch_safe_load(tmp_path / "legacy.pt", safe_only=True)[0] + assert checkpoint["model"].criterion is not None + assert checkpoint["best_fitness"] == 0.5 + with torch.no_grad(): + assert torch.allclose(checkpoint["model"](image)[0], expected) + + +@pytest.mark.parametrize("cfg", [CFG, "yolov8n.yaml", "yolov10n.yaml", "yolo11n.yaml", "yolo26n-p6.yaml"]) +def test_model_forward(cfg): + """Test the forward pass of the YOLO model.""" + from ultralytics.nn.modules import SPPF + + model = YOLO(cfg) + sppf = next(m for m in model.model.modules() if isinstance(m, SPPF)) + assert isinstance(sppf.cv1.act, torch.nn.Identity) == ("26" in str(cfg)) + assert isinstance(SPPF(64, 64).cv1.act, torch.nn.Identity) + model(source=None, imgsz=32, augment=True) # also test no source and augment + + +def test_model_methods(): + """Test various methods and properties of the YOLO model to ensure correct functionality.""" + model = YOLO(MODEL) + + # Model methods + model.info(verbose=True, detailed=True) + model = model.reset_weights() + model = model.load(MODEL) + model.to("cpu") + model.fuse() + model.clear_callback("on_train_start") + model.reset_callbacks() + + # Model properties + _ = model.names + _ = model.device + _ = model.transforms + _ = model.task_map + + +def test_model_load_remaps_cls_head_by_names(): + """Test class-name remap is limited to closed-set class-logit heads.""" + from types import SimpleNamespace + + from ultralytics.models.yolo.detect.train import DetectionTrainer + from ultralytics.models.yolo.obb.train import OBBTrainer + from ultralytics.models.yolo.pose.train import PoseTrainer + from ultralytics.models.yolo.segment.train import SegmentationTrainer + from ultralytics.nn.tasks import DetectionModel, OBBModel, PoseModel, SegmentationModel, YOLOEModel + + src = DetectionModel("yolo26n.yaml", nc=3, verbose=False) + tgt = DetectionModel("yolo26n.yaml", nc=2, verbose=False) + src.names, tgt.names = {0: "cat", 1: "dog", 2: "car"}, {0: "dog", 1: "cat"} + for seq in src.model[-1].cv3: + seq[-1].bias.data.copy_(torch.tensor([10.0, 20.0, 30.0])) + tgt.load(src, verbose=False) + assert all(seq[-1].bias.tolist() == [20.0, 10.0] for seq in tgt.model[-1].cv3) + + src = YOLOEModel("yoloe-26n.yaml", nc=3, verbose=False) + tgt = YOLOEModel("yoloe-26n.yaml", nc=2, verbose=False) + src.names, tgt.names = {0: "cat", 1: "dog", 2: "car"}, {0: "dog", 1: "cat"} + tgt.load(src, verbose=False) # YOLOE cv3 outputs embeddings, not class rows + + names = {0: "dog", 1: "cat"} + for trainer_cls, model in ( + (DetectionTrainer, DetectionModel("yolo26n.yaml", nc=2, verbose=False)), + (SegmentationTrainer, SegmentationModel("yolo26n-seg.yaml", nc=2, verbose=False)), + (PoseTrainer, PoseModel("yolo26n-pose.yaml", nc=2, data_kpt_shape=[17, 3], verbose=False)), + (OBBTrainer, OBBModel("yolo26n-obb.yaml", nc=2, verbose=False)), + ): + trainer = object.__new__(trainer_cls) + trainer.args = SimpleNamespace(cls_remap=True) + trainer.data = {"names": names} + assert trainer.set_model_names_for_load(model).names == names + + +def test_model_profile(): + """Test profiling of the YOLO model with `profile=True` to assess performance and resource usage.""" + from ultralytics.nn.tasks import DetectionModel + + model = DetectionModel() # build model + im = torch.randn(1, 3, 64, 64) # requires min imgsz=64 + _ = model.predict(im, profile=True) + + +def test_predict_txt(tmp_path): + """Test YOLO predictions with file, directory, and pattern sources listed in a text file.""" + file = tmp_path / "sources_multi_row.txt" + with open(file, "w") as f: + f.writelines(f"{src}\n" for src in SOURCES_LIST) + results = YOLO(MODEL)(source=file, imgsz=32) + assert len(results) == 7, f"Expected 7 results from source list, got {len(results)}" + + +@pytest.mark.skipif(True, reason="disabled for testing") +def test_predict_csv_multi_row(tmp_path): + """Test YOLO predictions with sources listed in multiple rows of a CSV file.""" + file = tmp_path / "sources_multi_row.csv" + with open(file, "w", newline="") as f: + writer = csv.writer(f) + writer.writerow(["source"]) + writer.writerows([[src] for src in SOURCES_LIST]) + results = YOLO(MODEL)(source=file, imgsz=32) + assert len(results) == 7, f"Expected 7 results from multi-row CSV, got {len(results)}" + + +@pytest.mark.skipif(True, reason="disabled for testing") +def test_predict_csv_single_row(tmp_path): + """Test YOLO predictions with sources listed in a single row of a CSV file.""" + file = tmp_path / "sources_single_row.csv" + with open(file, "w", newline="") as f: + writer = csv.writer(f) + writer.writerow(SOURCES_LIST) + results = YOLO(MODEL)(source=file, imgsz=32) + assert len(results) == 7, f"Expected 7 results from single-row CSV, got {len(results)}" + + +@pytest.mark.parametrize("model_name", MODELS) +def test_predict_img(model_name): + """Test YOLO model predictions on various image input types.""" + if IS_RASPBERRYPI and model_name == "yolo26n-sem.pt": + skip_rpi_semantic() + channels = 1 if model_name == "yolo11n-grayscale.pt" else 3 + model = YOLO(WEIGHTS_DIR / model_name) + im = cv2.imread(str(SOURCE), flags=cv2.IMREAD_GRAYSCALE if channels == 1 else cv2.IMREAD_COLOR) # uint8 NumPy array + assert len(model(source=Image.open(SOURCE), save=True, verbose=True, imgsz=32)) == 1 # PIL + assert len(model(source=im, save=True, save_txt=True, imgsz=32)) == 1 # ndarray + assert len(model(torch.rand((2, channels, 32, 32)), imgsz=32)) == 2 # batch-size 2 Tensor, FP32 0.0-1.0 RGB order + assert len(model(source=[im, im], save=True, save_txt=True, imgsz=32)) == 2 # batch + assert len(list(model(source=[im, im], save=True, stream=True, imgsz=32))) == 2 # stream + assert len(model(torch.zeros(320, 640, channels).numpy().astype(np.uint8), imgsz=32)) == 1 # tensor to numpy + batch = [ + str(SOURCE), # filename + Path(SOURCE), # Path + im, # OpenCV + Image.open(SOURCE), # PIL + np.zeros((320, 640, channels), dtype=np.uint8), # numpy + ] + assert len(model(batch, imgsz=32, classes=0)) == len(batch) # multiple sources in a batch + + +@pytest.mark.parametrize(("model_name", "bgr"), [("yolo11n.pt", [0, 127, 255]), ("yolo11n-grayscale.pt", [127])]) +def test_preprocess_values(model_name, bgr): + """Check predictor channel order and normalization with known pixel values.""" + model = YOLO(WEIGHTS_DIR / model_name) + im = np.full((32, 32, len(bgr)), bgr, dtype=np.uint8) + model(im, imgsz=32, verbose=False) # build predictor through the public path + out = model.predictor.preprocess([im]) + expected = torch.tensor([bgr[::-1]], device=out.device, dtype=out.dtype) / 255 + assert out.shape == (1, len(bgr), 32, 32) and out.is_contiguous() + assert torch.equal(out[:, :, 0, 0], expected) + + +@pytest.mark.parametrize("model_name", ["yolo26n.pt", "yolo11n.pt"]) +@pytest.mark.parametrize("nms", [None, False]) +def test_predict_classes_with_max_det(model_name, nms): + """Test classes-before-max_det and reset reused-call filters for end2end and NMS-based models.""" + boxes = YOLO(WEIGHTS_DIR / model_name)(SOURCE, classes=[0], max_det=300, nms=nms, verbose=False)[0].boxes + assert len(boxes) > 1 # bus.jpg contains multiple persons + top1_model = YOLO(WEIGHTS_DIR / model_name) + top1 = top1_model(SOURCE, classes=[0], max_det=1, nms=nms, verbose=False)[0].boxes + assert len(top1) == 1 and int(top1.cls) == 0 + assert float(top1.conf) == pytest.approx(float(boxes.conf.max())) # best person kept, not an arbitrary one + + reused = top1_model(SOURCE, verbose=False)[0].boxes # SAME model, no kwargs at all this time + assert len(reused) > 1 # classes=[0]/max_det=1 from the previous call must not leak into this one + + +@pytest.mark.parametrize("model", MODELS) +def test_predict_visualize(model): + """Test model prediction methods with 'visualize=True' to generate prediction visualizations.""" + if IS_RASPBERRYPI and model == "yolo26n-sem.pt": + skip_rpi_semantic() + YOLO(WEIGHTS_DIR / model)(SOURCE, imgsz=32, visualize=True) + + +def test_load_tensor_uint8(): + """Test that tensor normalization supports uint8 while preserving floating-point epsilon tolerance.""" + from ultralytics.data.loaders import LoadTensor + + loaded = LoadTensor(torch.full((1, 3, 32, 32), 255, dtype=torch.uint8)).im0 + assert loaded.dtype == torch.float32 and loaded.max() == 1 + normalized = torch.ones((1, 3, 32, 32), dtype=torch.float32) + normalized[..., 0, 0] += torch.finfo(normalized.dtype).eps + assert LoadTensor(normalized).im0.max() > 1 + + +def test_predict_gray_and_4ch(tmp_path): + """Test YOLO prediction on SOURCE converted to grayscale and 4-channel images with various filenames.""" + im = Image.open(SOURCE) + + source_grayscale = tmp_path / "grayscale.jpg" + source_rgba = tmp_path / "4ch.png" + source_non_utf = tmp_path / "non_UTF_测试文件_tést_image.jpg" + source_spaces = tmp_path / "image with spaces.jpg" + + im.convert("L").save(source_grayscale) # grayscale + im.convert("RGBA").save(source_rgba) # 4-ch PNG with alpha + im.save(source_non_utf) # non-UTF characters in filename + im.save(source_spaces) # spaces in filename + + # Inference + model = YOLO(MODEL) + for f in source_rgba, source_grayscale, source_non_utf, source_spaces: + for source in Image.open(f), cv2.imread(str(f)), f: + results = model(source, save=True, verbose=True, imgsz=32) + assert len(results) == 1, f"Expected 1 result for {f.name}, got {len(results)}" + f.unlink() # cleanup + + +def test_predict_ndarray_channels(): + """Test NumPy channel normalization for grayscale and color models.""" + from ultralytics.data.loaders import LoadPilAndNumpy + + model = YOLO(MODEL) # default 3-channel model + gray = np.asarray(Image.open(SOURCE).convert("L")) # genuine 2D (H, W) uint8 array + assert gray.ndim == 2, "Expected a 2D grayscale array for this test" + assert len(model(source=gray, imgsz=32, verbose=False)) == 1 # 2D ndarray auto-expanded to 3 channels + assert len(model(source=gray.astype("float64"), imgsz=32, verbose=False)) == 1 # non-OpenCV dtype also works + bgra = np.zeros((8, 8, 4), dtype="float64") + assert LoadPilAndNumpy(bgra, channels=3).im0[0].shape == (8, 8, 3) # non-OpenCV dtype also falls back for BGRA + for source_channels, model_channels in ((1, 3), (2, 1), (2, 3), (3, 1), (4, 1), (4, 3)): + im = np.zeros((8, 8, source_channels), dtype=np.uint8) + assert LoadPilAndNumpy(im, channels=model_channels).im0[0].shape == (8, 8, model_channels) + + +def test_single_check_channel_order_and_contiguity(): + """Test LoadPilAndNumpy._single_check() keeps BGR order and C-contiguous output through cv2 conversions.""" + from ultralytics.data.loaders import LoadPilAndNumpy + + check = LoadPilAndNumpy._single_check + rgb = Image.fromarray(np.full((2, 2, 3), (10, 20, 30), dtype=np.uint8)) # PIL is R, G, B + bgra = np.full((2, 2, 4), (10, 20, 30, 255), dtype=np.uint8) # ndarray is already B, G, R, A + gray = np.full((2, 2, 1), 42, dtype=np.uint8) + for im, expected in ((check(rgb, 3), (30, 20, 10)), (check(bgra, 3), (10, 20, 30)), (check(gray, 3), (42, 42, 42))): + assert tuple(im[0, 0].tolist()) == expected + assert im.flags["C_CONTIGUOUS"] + + +@pytest.mark.slow +@pytest.mark.skipif(not ONLINE, reason="environment is offline") +def test_predict_all_image_formats(): + """Predict on the 12 image format extensions in COCO12-Formats (AVIF, BMP, DNG, HEIC, JP2, JPEG, JPG, MPO, PNG, TIF, + TIFF, WebP). + """ + # Download dataset if needed + data = check_det_dataset("coco12-formats.yaml") + dataset_path = Path(data["path"]) + + # Collect all images from train and val + expected = {"avif", "bmp", "dng", "heic", "jp2", "jpeg", "jpg", "mpo", "png", "tif", "tiff", "webp"} + images = [im for im in (dataset_path / "images" / "train").glob("*.*") if im.suffix.lower().lstrip(".") in expected] + images += [im for im in (dataset_path / "images" / "val").glob("*.*") if im.suffix.lower().lstrip(".") in expected] + assert len(images) == 12, f"Expected 12 images, found {len(images)}" + + # Verify all format extensions are represented + extensions = {img.suffix.lower().lstrip(".") for img in images} + assert extensions == expected, f"Missing formats: {expected - extensions}" + + # Run inference on all images + model = YOLO(MODEL) + results = model(images, imgsz=32) + assert len(results) == 12, f"Expected 12 results, got {len(results)}" + + +@pytest.mark.slow +@pytest.mark.skipif(not ONLINE, reason="environment is offline") +@pytest.mark.skipif(is_github_action_running(), reason="No auth https://github.com/JuanBindez/pytubefix/issues/166") +def test_youtube(): + """Test YOLO model on a YouTube video stream, handling potential network-related errors.""" + model = YOLO(MODEL) + try: + model.predict("https://youtu.be/G17sBkb38XQ", imgsz=32, save=True) + # Handle internet connection errors and 'urllib.error.HTTPError: HTTP Error 429: Too Many Requests' + except (urllib.error.HTTPError, ConnectionError) as e: + LOGGER.error(f"YouTube Test Error: {e}") + + +def test_track_second_association_indices(): + """Low-confidence detections matched in second association keep full detection-set indices.""" + from ultralytics.engine.results import Boxes + from ultralytics.trackers.byte_tracker import BYTETracker + from ultralytics.utils import ROOT, YAML, IterableSimpleNamespace + + args = IterableSimpleNamespace(**{**YAML.load(ROOT / "cfg/trackers/bytetrack.yaml"), "fuse_score": False}) + tracker = BYTETracker(args) + boxes = [[10, 10, 50, 50], [200, 200, 260, 260], [400, 400, 480, 480]] + for confs in ([0.9, 0.9, 0.9], [0.9, 0.9, 0.2]): # third detection drops to low confidence on frame 2 + data = torch.tensor([[*b, c, 0] for b, c in zip(boxes, confs)], dtype=torch.float32) + tracks = tracker.update(Boxes(data, (640, 640))) + low = tracks[np.isclose(tracks[:, 5], 0.2)] # columns are [x1, y1, x2, y2, id, score, cls, idx] + assert len(low) == 1 and int(low[0, -1]) == 2, f"second-association idx not preserved:\n{tracks}" + + +def test_track_split_detections_degenerate_boxes(): + """`_split_detections` must drop zero/negative-dimension boxes from both confidence partitions while keeping every + valid detection's index into the full detection-set space (later assigned to `track.idx`). + """ + from ultralytics.engine.results import Boxes + from ultralytics.trackers.byte_tracker import BYTETracker + from ultralytics.utils import ROOT, YAML, IterableSimpleNamespace + + args = IterableSimpleNamespace(**YAML.load(ROOT / "cfg/trackers/bytetrack.yaml")) + tracker = BYTETracker(args) + boxes = [ + [10, 10, 50, 50, 0.9, 0], # idx 0: valid, high-confidence partition + [300, 480, 350, 480, 0.9, 0], # idx 1: degenerate, zero height, high-confidence partition + [100, 100, 150, 150, 0.15, 0], # idx 2: valid, low-confidence partition + [300, 490, 350, 480, 0.15, 0], # idx 3: degenerate, negative height, low-confidence partition + [150, 100, 100, 150, 0.9, 0], # idx 4: degenerate, negative width, high-confidence partition + ] + results = Boxes(torch.tensor(boxes, dtype=torch.float32), (640, 640)) + high, low, mask_high, mask_low = tracker._split_detections(results) + assert np.flatnonzero(mask_high).tolist() == [0] and len(high) == 1, f"degenerate box leaked high band: {mask_high}" + assert np.flatnonzero(mask_low).tolist() == [2] and len(low) == 1, f"degenerate box leaked low band: {mask_low}" + + +@pytest.mark.parametrize("tracker_type", ["bytetrack", "fasttrack"]) +def test_track_second_association_low_conf_keeps_id(tracker_type): + """Low-confidence detection is recovered by the second association under the default fuse_score=True.""" + from ultralytics.engine.results import Boxes + from ultralytics.trackers.track import TRACKER_MAP + from ultralytics.utils import ROOT, YAML, IterableSimpleNamespace + + args = IterableSimpleNamespace(**YAML.load(ROOT / f"cfg/trackers/{tracker_type}.yaml")) # default fuse_score=True + tracker = TRACKER_MAP[tracker_type](args) + box = [100, 100, 200, 200] # same box on both frames, so IoU is 1.0 + # frame 1: high score starts the track; frame 2: score drops into the low band (track_low_thresh < 0.15 < track_high_thresh) + frame1 = tracker.update(Boxes(torch.tensor([[*box, 0.9, 0]], dtype=torch.float32), (640, 640))) + frame2 = tracker.update(Boxes(torch.tensor([[*box, 0.15, 0]], dtype=torch.float32), (640, 640))) + assert len(frame1) == 1, f"expected one track on frame 1:\n{frame1}" + tid = int(frame1[0, 4]) + # the low-score box must be kept and mapped to the same id via the second association + assert len(frame2) == 1, f"low-confidence detection lost by second association:\n{frame2}" + assert int(frame2[0, 4]) == tid, f"id switched on low-confidence frame: {tid} -> {int(frame2[0, 4])}\n{frame2}" + + +def test_tracktrack_new_lifecycle(): + """TrackTrack predicts New tracks and confirms them once their history reaches min_track_len.""" + from ultralytics.engine.results import Boxes + from ultralytics.trackers.track import TRACKER_MAP + from ultralytics.utils import ROOT, YAML, IterableSimpleNamespace + + cfg = {**YAML.load(ROOT / "cfg/trackers/tracktrack.yaml"), "gmc_method": "none", "min_track_len": 4} + tracker = TRACKER_MAP["tracktrack"](IterableSimpleNamespace(**cfg)) + tracker.update(Boxes(torch.empty((0, 6)), (640, 640))) # avoid first-frame auto-activation + outputs = [] + for center_x in (100, 135, 170, 205): + box = torch.tensor([[center_x - 50, 50, center_x + 50, 150, 0.9, 0]], dtype=torch.float32) + outputs.append(tracker.update(Boxes(box, (640, 640)))) + assert [len(output) for output in outputs] == [0, 0, 0, 1] + for min_track_len in (0, 1): + cfg["min_track_len"] = min_track_len + tracker = TRACKER_MAP["tracktrack"](IterableSimpleNamespace(**cfg)) + tracker.update(Boxes(torch.empty((0, 6)), (640, 640))) + assert len(tracker.update(Boxes(box, (640, 640)))) == 1 + + from ultralytics.trackers.basetrack import TrackState + + cfg["min_track_len"] = 4 + tracker = TRACKER_MAP["tracktrack"](IterableSimpleNamespace(**cfg)) + for center_x in (100, 135, 170, 205): # frame_id == 1 carries a real detection, not an empty warm-up frame + box = torch.tensor([[center_x - 50, 50, center_x + 50, 150, 0.9, 0]], dtype=torch.float32) + tracker.update(Boxes(box, (640, 640))) + if tracker.frame_id == 2: + assert tracker.tracked_stracks[0].state != TrackState.Tracked, "frame_id==1 track confirmed after 2 hits" + assert tracker.tracked_stracks[0].state == TrackState.Tracked + + +@pytest.mark.parametrize("tracker_type", ["botsort", "deepocsort", "tracktrack"]) +def test_track_reid_auto_user_detections(tracker_type): + """Native ReID (model='auto') must degrade to motion-only with user-supplied detections, not encode the raw frame.""" + from ultralytics.engine.results import Boxes + from ultralytics.trackers.track import TRACKER_MAP + from ultralytics.utils import ROOT, YAML, IterableSimpleNamespace + + cfg = {**YAML.load(ROOT / f"cfg/trackers/{tracker_type}.yaml"), "with_reid": True, "model": "auto"} + tracker = TRACKER_MAP[tracker_type](IterableSimpleNamespace(**cfg)) + img = np.full((640, 640, 3), 128, dtype=np.uint8) # nonzero so bogus frame-derived features would not be dropped + data = torch.tensor([[10, 10, 50, 50, 0.9, 0], [200, 200, 260, 260, 0.9, 0]], dtype=torch.float32) + for _ in range(3): # frame 2 used to crash in embedding_distance after storing image rows as track features + tracks = tracker.update(Boxes(data, (640, 640)), img) + assert len(tracks) == 2, f"native-ReID tracker must keep tracking without feats:\n{tracks}" + + +@pytest.mark.parametrize("fuse_score", [True, False]) +def test_deepocsort_ocr_proximity_gate(fuse_score): + """DeepOCSORT OCR rejects a zero-IoU pair even when its appearance is identical, under both fuse_score settings.""" + from types import SimpleNamespace + + from ultralytics.trackers.basetrack import TrackState + from ultralytics.trackers.deep_oc_sort import DeepOCSORT + + tracker = object.__new__(DeepOCSORT) + tracker.args = SimpleNamespace(fuse_score=fuse_score, match_thresh=0.8) + tracker.encoder, tracker.appearance_thresh, tracker.proximity_thresh, tracker.frame_id = object(), 0.9, 0.5, 2 + track = SimpleNamespace( + angle=None, + last_observation=np.array([0, 0, 10, 10]), + smooth_feat=np.array([1.0, 0.0]), + state=TrackState.Tracked, + update=lambda *_: None, + ) + detection = SimpleNamespace(xyxy=np.array([20, 20, 30, 30]), curr_feat=np.array([1.0, 0.0]), score=1.0) + # proves appearance is active and would override (ungated) this exact pair, so the OCR result below is caused by + # the proximity gate, not by appearance being unavailable + assert tracker._fuse_appearance(np.array([[1.0]]), [track], [detection]) == 0.0 + assert tracker._ocr_associate([track], [detection], [], []) == ([0], [0]) + + +def test_reid_invalid_crops(): + """Test ReID skips out-of-bounds detection crops while preserving feature alignment.""" + from types import SimpleNamespace + + from ultralytics.trackers.utils.reid import ReID + + encoder = ReID.__new__(ReID) + encoder.is_pt = True + encoder.model = SimpleNamespace(predictor=lambda crops: [torch.ones(4) for _ in crops]) + img = np.full((640, 640, 3), 128, dtype=np.uint8) + feats = encoder(img, np.array([[30, 30, 40, 40], [1100, 1100, 200, 200]], dtype=np.float32)) + assert feats[0] is not None and feats[1] is None + + +@pytest.mark.skipif(not ONLINE, reason="environment is offline") +@pytest.mark.parametrize("model", MODELS) +def test_track_stream(model, tmp_path, solution_assets): + """Test streaming tracking on a short video with all built-in trackers and various GMC/ReID configurations. + + Note imgsz=160 required for tracking for higher confidence and better matches. + """ + if model in { + "yolo26n-cls.pt", + "yolo26n-sem.pt", + "yolo26n-depth.pt", + }: # classification, semantic, and depth not supported + return + from ultralytics.trackers.track import TRACKER_MAP + + video_url = solution_assets("track_video") + model = YOLO(model) + + # Default end-to-end run for all built-in trackers + for tracker_type in TRACKER_MAP: + kwargs = {"save_frames": True} if tracker_type == "botsort" else {} + model.track(video_url, imgsz=160, tracker=f"{tracker_type}.yaml", **kwargs) + + # Test Global Motion Compensation (GMC) methods and ReID on botsort + for gmc, reidm in zip(["orb", "sift", "ecc"], ["auto", "auto", "yolo26n-cls.pt"]): + default_args = YAML.load(ROOT / "cfg/trackers/botsort.yaml") + custom_yaml = tmp_path / f"botsort-{gmc}.yaml" + YAML.save(custom_yaml, {**default_args, "gmc_method": gmc, "with_reid": True, "model": reidm}) + model.track(video_url, imgsz=160, tracker=custom_yaml) + + # Test ONNX ReID encoder auto-download + if model == "yolo26n.pt": + default_args = YAML.load(ROOT / "cfg/trackers/botsort.yaml") + custom_yaml = tmp_path / "botsort-reid-onnx.yaml" + YAML.save(custom_yaml, {**default_args, "with_reid": True, "model": "yolo26n-reid.onnx"}) + model.track(video_url, imgsz=160, tracker=custom_yaml) + + +@pytest.mark.parametrize("task,weight,data", TASK_MODEL_DATA) +def test_val(task: str, weight: str, data: str) -> None: + """Test the validation mode of the YOLO model.""" + if IS_RASPBERRYPI and task == "semantic": + skip_rpi_semantic() + model = YOLO(weight) + for plots in (True, False): # Test both cases i.e. plots=True and plots=False + metrics = model.val(data=data, imgsz=32, plots=plots) + metrics.to_df() + metrics.to_csv() + metrics.to_json() + if task != "depth": # depth is dense regression: no classes, no confusion matrix + metrics.confusion_matrix.to_df() + metrics.confusion_matrix.to_csv() + metrics.confusion_matrix.to_json() + cm = metrics.confusion_matrix + expected = cm.nc if task in {"classify", "semantic"} else cm.nc + 1 # background for detection tasks + assert cm.matrix.shape == (expected, expected), f"{task} confusion matrix is {cm.matrix.shape}" + assert len(cm.tp_fp()[0]) == cm.nc # per-class TP/FP never include background + + +def test_val_save_txt_pose(tmp_path): + """Test that pose keypoints saved by val(save_txt=True) and val(save_json=True) are in the original image space.""" + model = YOLO(WEIGHTS_DIR / "yolo26n-pose.pt") + # imgsz=640 (not the imgsz=32 used elsewhere): coco8-pose images are non-square, so the letterbox offset is only + # large enough to push mis-scaled keypoints outside [0, 1] at full resolution; at small imgsz they would stay in + # range and hide the regression. save_json=True also exercises pred_to_json, the other consumer of the scaled key. + metrics = model.val( + data="coco8-pose.yaml", imgsz=640, conf=0.25, save_txt=True, save_json=True, project=tmp_path, name="val" + ) + txt_files = list((Path(metrics.save_dir) / "labels").glob("*.txt")) + assert txt_files, "val(save_txt=True) saved no label files" + assert (Path(metrics.save_dir) / "predictions.json").exists(), "val(save_json=True) saved no predictions.json" + for txt_file in txt_files: + for line in txt_file.read_text().splitlines(): + values = [float(v) for v in line.split()] + x, y, w, h = values[1:5] # normalized xywh box + kpts = torch.tensor(values[5:]).view(-1, 3) # (17, 3) of normalized (x, y, conf) keypoints + assert ((kpts[:, :2] >= 0) & (kpts[:, :2] <= 1)).all(), f"keypoints not in [0, 1] in {txt_file.name}" + # Keypoints scaled into the wrong (letterbox) space also land off the person, so check that visible + # keypoints cluster on the box; the 0.05 margin allows joints (wrists, ankles) just outside a tight box. + visible = kpts[kpts[:, 2] > 0.5, :2] + if len(visible): + cx, cy = visible.mean(0) + assert abs(cx - x) < w / 2 + 0.05 and abs(cy - y) < h / 2 + 0.05, "keypoints misaligned with box" + + +def test_pose_metrics_curves(): + """Test that pose curve labels contain four unique box and pose series.""" + from ultralytics.utils.metrics import PoseMetrics + + curves = PoseMetrics().curves + assert len(curves) == len(set(curves)) == 8 + + +@pytest.mark.skipif(not ONLINE, reason="environment is offline") +@pytest.mark.skipif(IS_JETSON or IS_RASPBERRYPI, reason="Edge devices not intended for training") +def test_train_multi(): + """Test fine-tuning a base model across a dataset collection, which triggers MultiTrainer for list/tuple data.""" + model = YOLO(MODEL) + results = model.train(data=["coco8.yaml", "coco8.yaml"], epochs=1, imgsz=32) + assert isinstance(results, dict) and len(results) == 2 # one entry per run (coco8, coco8-2), no duplicate collapse + assert all(m and "fitness" in m for m in results.values()) # checkpoint train metrics per run + assert len(model.trainer.trainers) == 2 # both list entries fine-tuned in series + sweep_dir = model.trainer.save_dir + assert sweep_dir.name.startswith("multitrain") # all runs grouped under one sweep directory + assert (sweep_dir / "multitrain_results.json").exists() # results JSON for post-processing + assert (sweep_dir / "multitrain_results.png").exists() # cross-dataset results plot + + +def test_normalize_platform_uri(): + """Test Platform web URLs are rewritten to ul:// URIs so datasets/models load directly from a pasted URL.""" + from ultralytics.utils.checks import normalize_platform_uri + + base = "https://platform.ultralytics.com/glenn-jocher" + assert normalize_platform_uri(f"{base}/datasets/coco8") == "ul://glenn-jocher/datasets/coco8" + assert normalize_platform_uri(f"{base}/project/model/") == "ul://glenn-jocher/project/model" + assert normalize_platform_uri("coco8.yaml") == "coco8.yaml" # non-Platform inputs unchanged + + +def test_convert_signed_ndjson(monkeypatch): + """Test signed NDJSON URLs are converted before dataset YAML validation.""" + from ultralytics.data import converter, utils + + captured = [] + + async def convert(path, fraction, split): + captured.append((path, fraction)) + return "dataset.ndjson.yaml" + + monkeypatch.setattr(converter, "convert_ndjson_to_yolo", convert) + url = "https://storage.googleapis.com/bucket/dataset-v1.ndjson?X-Goog-Signature=abc" + assert utils.convert_ndjson_to_yolo_if_needed(url) == "dataset.ndjson.yaml" + assert captured == [(url, 1.0)] + + +@pytest.mark.parametrize("task", ["detect", "classify"]) +def test_ndjson_conversion_concurrency_and_resume(monkeypatch, tmp_path, task): + """Test concurrent conversions share work and interrupted conversions resume before publishing completion.""" + import asyncio + import json + import threading + from concurrent.futures import ThreadPoolExecutor + + import aiohttp + + from ultralytics.data import converter + + counts, failures, conversions, count_lock = {}, set(), 0, threading.Lock() + + class Response: + def __init__(self, url): + self.url = url + + async def __aenter__(self): + return self + + async def __aexit__(self, *_): + pass + + def raise_for_status(self): + pass + + async def read(self): + await asyncio.sleep(0.01) + with count_lock: + counts[self.url] = counts.get(self.url, 0) + 1 + fail = self.url in failures + failures.discard(self.url) + if fail: + raise OSError("interrupted") + return image_bytes + + class Session: + def __init__(self, **_): + pass + + async def __aenter__(self): + return self + + async def __aexit__(self, *_): + pass + + def get(self, url, **_): + return Response(url) + + ok, image = cv2.imencode(".jpg", np.zeros((16, 16, 3), dtype=np.uint8)) + assert ok + image_bytes = image.tobytes() + monkeypatch.setattr(aiohttp, "ClientSession", Session) + original_convert = converter._convert_ndjson_to_yolo + + async def track_conversion(*args): + nonlocal conversions + with count_lock: + conversions += 1 + return await original_convert(*args) + + monkeypatch.setattr(converter, "_convert_ndjson_to_yolo", track_conversion) + annotations = {"classification": [7]} if task == "classify" else {"boxes": [[0, 0.5, 0.5, 1, 1]]} + + def write_ndjson(name): + path = tmp_path / f"{name}.ndjson" + records = [ + {"type": "dataset", "task": task, "class_names": {"7": "item", "8": "rare"}}, + { + "file": "train.jpg", + "url": f"https://example.com/{name}-train.jpg", + "split": "train", + "annotations": annotations, + }, + { + "file": "val.jpg", + "url": f"https://example.com/{name}-val.jpg", + "split": "val", + "annotations": {"classification": [8]} if task == "classify" else annotations, + }, + ] + path.write_text("\n".join(json.dumps(record) for record in records)) + return path + + concurrent = write_ndjson("concurrent") + jobs = 2 + barrier = threading.Barrier(jobs) + + def convert(path): + barrier.wait() + return asyncio.run(converter.convert_ndjson_to_yolo(path, tmp_path)) + + with ThreadPoolExecutor(max_workers=jobs) as pool: + results = list(pool.map(convert, [concurrent] * jobs)) + assert len(set(results)) == 1 + assert conversions == 1 + assert sum(counts.values()) == 2 + if task == "classify": + assert check_cls_dataset(results[0])["nc"] == 2 + from ultralytics.data import dataset as dataset_module + + monkeypatch.setattr(dataset_module, "TORCHVISION_0_18", False) + args = copy(DEFAULT_CFG) + train = dataset_module.ClassificationDataset(results[0] / "train", args) + val = dataset_module.ClassificationDataset(results[0] / "val", args) + assert train.samples[0][1] == 0 + assert val.samples[0][1] == 1 + assert dataset_module.ClassificationDataset(results[0] / "val", args).samples[0][1] == 1 + + resume = write_ndjson("resume") + failed_url = "https://example.com/resume-val.jpg" + failures.add(failed_url) + with ThreadPoolExecutor(max_workers=jobs) as pool: + futures = [pool.submit(convert, resume) for _ in range(jobs)] + errors, results = [], [] + for future in futures: + try: + results.append(future.result()) + except RuntimeError as error: + errors.append(str(error)) + assert len(errors) == len(results) == 1 and "Downloaded 1/2 images" in errors[0] + result = results[0] + marker = result / ".ndjson.yaml" if task == "classify" else result + assert YAML.load(marker)["complete"] is True + assert counts["https://example.com/resume-train.jpg"] == 1 + assert counts[failed_url] == 2 + request_count = sum(counts.values()) + asyncio.run(converter.convert_ndjson_to_yolo(resume, tmp_path)) + assert conversions == 4 + assert sum(counts.values()) == request_count + + +@pytest.mark.skipif(not ONLINE, reason="environment is offline") +@pytest.mark.skipif(IS_JETSON or IS_RASPBERRYPI, reason="Edge devices not intended for training") +def test_train_scratch(): + """Test training the YOLO model from scratch on 12 different image types in the COCO12-Formats dataset.""" + model = YOLO(CFG) + model.train(data="coco12-formats.yaml", epochs=2, imgsz=32, cache="disk", batch=-1, close_mosaic=1, name="model") + head = model.trainer.model.model[-1] + assert head.cv2 is not None and head.one2one_cv2 is not None # both heads remain trained + assert hasattr(model.trainer.model.criterion, "one2many") and hasattr(model.trainer.model.criterion, "one2one") + assert not model.trainer.ema.ema.end2end # epoch validation selects one-to-many by default + model(SOURCE) + + +@pytest.mark.skipif(not ONLINE, reason="environment is offline") +@pytest.mark.skipif(IS_RASPBERRYPI, reason="Edge devices not intended for training") +def test_train_ndjson(): + """Test training the YOLO model using NDJSON format dataset.""" + model = YOLO(WEIGHTS_DIR / "yolo26n.pt") + model.train(data=f"{ASSETS_URL}/coco8-ndjson.ndjson", epochs=1, imgsz=32) + + +@pytest.mark.parametrize("scls", [False, True]) +@pytest.mark.skipif(IS_RASPBERRYPI, reason="Edge devices not intended for training") +def test_train_pretrained(scls): + """Test training of the YOLO model starting from a pre-trained checkpoint.""" + model = YOLO(WEIGHTS_DIR / "yolo26n-seg.pt") + model.train( + data="coco8-seg.yaml", epochs=1, imgsz=32, cache="ram", copy_paste=0.5, mixup=0.5, name=0, single_cls=scls + ) + model(SOURCE) + + +def test_all_model_yamls(): + """Test YOLO model creation for all available YAML configurations in the `cfg/models` directory.""" + for m in (ROOT / "cfg" / "models").rglob("*.yaml"): + if "rtdetr" in m.name: + if TORCH_1_11: + _ = RTDETR(m.name)(SOURCE, imgsz=160) + else: + YOLO(m.name) + + +@pytest.mark.skipif(WINDOWS, reason="Windows slow CI export bug https://github.com/ultralytics/ultralytics/pull/16003") +def test_workflow(isolated_model): + """Test the complete workflow including training, validation, prediction, and exporting.""" + model = YOLO(isolated_model) + model.train(data="coco8.yaml", epochs=1, imgsz=32, optimizer="SGD") + model.val(imgsz=32) + model.predict(SOURCE, imgsz=32) + model.export(format="torchscript") # WARNING: Windows slow CI export bug + + +def test_predict_callback_and_setup(): + """Test callback functionality during YOLO prediction setup and execution.""" + + def on_predict_batch_end(predictor): + """Callback function that handles operations at the end of a prediction batch.""" + path, im0s, _ = predictor.batch + im0s = im0s if isinstance(im0s, list) else [im0s] + bs = [predictor.dataset.bs for _ in range(len(path))] + predictor.results = zip(predictor.results, im0s, bs) # results is list[batch_size] + + model = YOLO(MODEL) + model.add_callback("on_predict_batch_end", on_predict_batch_end) + + dataset = load_inference_source(source=SOURCE) + bs = dataset.bs # access predictor properties + results = model.predict(dataset, stream=True, imgsz=32) # source already setup + for r, im0, bs in results: + print("test_callback", im0.shape) + print("test_callback", bs) + boxes = r.boxes # Boxes object for bbox outputs + print(boxes) + + +@pytest.mark.parametrize("model", MODELS) +def test_results(model: str, tmp_path, solution_assets): + """Test YOLO model results processing and output in various formats.""" + if IS_RASPBERRYPI and model == "yolo26n-sem.pt": + skip_rpi_semantic() + im = solution_assets("boats") if model == "yolo26n-obb.pt" else SOURCE + is_semantic = "semantic" in model or "-sem" in model + results = YOLO(WEIGHTS_DIR / model)([im, im], imgsz=32 if is_semantic else 160) + for r in results: + if is_semantic: + assert r.semantic_mask is not None and r.semantic_mask.shape == r.orig_shape, ( + f"'{model}' semantic_mask should match the original image shape!" + ) + assert r.semantic_mask.data.dtype == torch.uint8, f"'{model}' semantic_mask should use compact class IDs!" + else: + assert len(r), f"'{model}' results should not be empty!" + r = r.cpu().numpy() + print(r, len(r), r.path) # print numpy attributes + r = r.to(device="cpu", dtype=torch.float32) + r.save_txt(txt_file=tmp_path / "runs/tests/label.txt", save_conf=True) + r.save_crop(save_dir=tmp_path / "runs/tests/crops/") + r.to_df(decimals=3) # Align to_ methods: https://docs.ultralytics.com/modes/predict#working-with-results + r.to_csv() + r.to_json(normalize=True) + r.plot(pil=True, save=True, filename=tmp_path / "results_plot_save.jpg") + r.plot(conf=True, boxes=True) + print(r, len(r), r.path) # print after methods + + +def test_results_plot_without_boxes(): + """Test that plotting a masks-only Results (boxes=None) does not raise an AttributeError.""" + from ultralytics.engine.results import Results + + orig_img = np.zeros((640, 640, 3), dtype=np.uint8) + masks = torch.zeros((2, 640, 640), dtype=torch.float32) + r = Results(orig_img, path="image.jpg", names={0: "a", 1: "b"}, masks=masks) + assert r.boxes is None + for color_mode in ("class", "instance"): + assert r.plot(color_mode=color_mode).shape == orig_img.shape + + +def test_results_depth_field(): + """A depth array becomes a DepthMap that survives the .cpu().numpy() chain.""" + from ultralytics.engine.results import DepthMap, Results + + img = np.zeros((20, 24, 3), dtype=np.uint8) + depth = np.random.rand(20, 24).astype(np.float32) + r = Results(orig_img=img, path="x.jpg", names={0: "depth"}, depth=depth) + assert isinstance(r.depth, DepthMap) + assert r.depth.data.shape == (20, 24) + rc = r.cpu().numpy() # exercises BaseTensor _keys plumbing (.cpu()/.numpy()) + assert rc.depth is not None + assert rc.depth.data.shape == (20, 24) # shape survives the .cpu().numpy() chain + + +def test_results_depth_none_summary_len_and_update(): + """Depth-only Results: None passthrough, empty summary, __len__ counts the map, update() wraps arrays.""" + from ultralytics.engine.results import DepthMap, Results + + img = np.zeros((8, 8, 3), dtype=np.uint8) + assert Results(orig_img=img, path="x.jpg", names={}, depth=None).depth is None + r = Results(orig_img=img, path="x.jpg", names={0: "depth"}, depth=np.ones((8, 8), dtype=np.float32)) + assert r.summary() == [] # depth-only Results has no per-instance summary + assert len(r) == 1 # __len__ returns the depth map count + r = Results(orig_img=img, path="x.jpg", names={0: "depth"}) + r.update(depth=np.ones((8, 8), dtype=np.float32)) + assert isinstance(r.depth, DepthMap) + + +def test_results_plot_with_depth(): + """Results.plot() with a depth map blends the colorized depth heatmap over the image.""" + from ultralytics.engine.results import Results + + img = np.zeros((24, 24, 3), dtype=np.uint8) + depth = np.random.rand(24, 24).astype(np.float32) + r = Results(orig_img=img, path="x.jpg", names={0: "depth"}, depth=depth) + out = r.plot() # must not raise; returns an annotated image (masks=True by default) + assert out.shape[:2] == (24, 24) # heatmap overlaid, same size as input + + +def test_annotator_depth_map(): + """Annotator.depth_map colorizes a depth array, including the all-zero (no valid pixels) case.""" + from ultralytics.utils.plotting import Annotator + + ann = Annotator(np.zeros((32, 32, 3), dtype=np.uint8)) + ann.depth_map(np.random.rand(32, 32).astype(np.float32)) + assert ann.result().shape == (32, 32, 3) + ann = Annotator(np.zeros((16, 16, 3), dtype=np.uint8)) + ann.depth_map(np.zeros((16, 16), dtype=np.float32)) # no valid pixels → must not divide-by-zero + assert ann.result().shape == (16, 16, 3) + + +def test_dense_result_tensor_indexing(): + """Valid indices keep the intact map on SemanticMask/DepthMap; out-of-range raises; empty selections zero len.""" + from ultralytics.engine.results import DepthMap, SemanticMask + + data = torch.arange(20, dtype=torch.float32).reshape(4, 5) + valid = (0, -1, [0], np.array([0]), torch.tensor(0), torch.tensor([0]), [True], torch.tensor([True]), slice(0, 1)) + invalid = (1, -2, [1], torch.tensor(1)) + empty = ([False], torch.tensor([False]), slice(1, None), slice(0, 0)) + for cls in (SemanticMask, DepthMap): + dense = cls(data, orig_shape=(4, 5)) + for idx in valid: + sel = dense[idx] + assert len(sel) == 1 and torch.equal(torch.as_tensor(sel.data), data), f"{cls.__name__}[{idx!r}]" + for idx in invalid: + with pytest.raises(IndexError): + dense[idx] + for idx in empty: + assert len(dense[idx]) == 0, f"{cls.__name__}[{idx!r}] should be empty" + + +def test_results_plot_empty_dense_selection(): + """result[1:].plot() on a one-result dense (semantic/depth) Results returns the plain image, no overlay.""" + from ultralytics.engine.results import Results + + img = np.zeros((16, 16, 3), dtype=np.uint8) + dense_map = np.ones((16, 16), dtype=np.float32) + plain = Results(orig_img=img, path="x.jpg", names={}).plot() + for kwargs in ({"semantic_mask": dense_map.astype(np.uint8)}, {"depth": dense_map}): + r = Results(orig_img=img, path="x.jpg", names={0: "a"}, **kwargs) + assert len(r[1:]) == 0 + np.testing.assert_array_equal(r[1:].plot(), plain) + with pytest.raises(IndexError): + r[1] + + +def test_annotator_tensor_image(): + """Annotator accepts tensor images and matches Results.plot compositing pixels.""" + from ultralytics.engine.results import Results + from ultralytics.utils.plotting import Annotator + + image = torch.zeros((16, 16, 3), dtype=torch.uint8) + masks = torch.ones((1, 16, 16), dtype=torch.bool) + ann = Annotator(image) + ann.masks(masks, [[255, 0, 0]]) + assert ann.result()[0, 0].tolist() == [127, 0, 0] + result = Results(np.zeros((16, 16, 3), dtype=np.uint8), path="image.jpg", names={}, masks=masks) + expected = result.plot(img=np.zeros((16, 16, 3), dtype=np.uint8), boxes=False) + np.testing.assert_array_equal(result.plot(img=torch.zeros_like(image), boxes=False), expected) + + +def test_results_update_probs(): + """Test that Results.update(probs=...) wraps the tensor in Probs like the sibling attributes.""" + from ultralytics.engine.results import Probs, Results + + orig_img = np.zeros((32, 32, 3), dtype=np.uint8) + r = Results(orig_img, path="image.jpg", names={i: f"c{i}" for i in range(5)}, probs=torch.rand(5)) + r.update(probs=torch.rand(5)) + assert isinstance(r.probs, Probs), "update(probs=) should wrap the tensor in Probs, not store a raw Tensor" + assert r.verbose() and r.summary(), "verbose()/summary() raise AttributeError on a raw Tensor probs" + + +def test_labels_and_crops(tmp_path): + """Test output from prediction args for saving YOLO detection labels and crops.""" + imgs = [SOURCE, ASSETS / "zidane.jpg"] + model = YOLO(WEIGHTS_DIR / "yolo26n.pt") + results = model(imgs, imgsz=160, save_txt=True, save_crop=True) + save_path = Path(results[0].save_dir) + for r in results: + im_name = Path(r.path).stem + cls_idxs = r.boxes.cls.int().tolist() + # Check that detections are made (at least 2 detections per image expected) + assert len(cls_idxs) >= 2, f"Expected at least 2 detections, got {len(cls_idxs)}" + # Check label path + labels = save_path / f"labels/{im_name}.txt" + assert labels.exists(), f"Label file {labels} does not exist" + # Check detections match label count + label_count = len([line for line in labels.read_text().splitlines() if line]) + assert len(r.boxes.data) == label_count, f"Box count {len(r.boxes.data)} != label count {label_count}" + # Check crops path and files + crop_dirs = list((save_path / "crops").iterdir()) + crop_files = [f for p in crop_dirs for f in p.glob("*")] + # Crop directories match detections + crop_dir_names = {d.name for d in crop_dirs} + assert all(r.names.get(c) in crop_dir_names for c in cls_idxs), ( + f"Crop dirs {crop_dir_names} don't match classes {cls_idxs}" + ) + # Same number of crops as detections + crop_count = len([f for f in crop_files if im_name in f.name]) + assert crop_count == len(r.boxes.data), f"Crop count {crop_count} != detection count {len(r.boxes.data)}" + + model(SOURCE, imgsz=160, save_crop=True, verbose=False, project=tmp_path, name="crop", exist_ok=True) + assert any((tmp_path / "crop/crops").rglob("*.jpg")), "save_crop=True alone must write crop files" + + +def test_data_utils(tmp_path): + """Test data utility functions including auto-splitting and zip archiving.""" + from ultralytics.data.split import autosplit + from ultralytics.utils.downloads import zip_directory + + images_dir = tmp_path / "coco8/images/val" + images_dir.mkdir(parents=True) + Image.new("RGB", (8, 8)).save(images_dir / "test.jpg") + metadata_dir = images_dir / "__MACOSX" + metadata_dir.mkdir() + nested_metadata_dir = metadata_dir / "nested/__MACOSX" + nested_metadata_dir.mkdir(parents=True) + metadata_file = images_dir / ".DS_Store" + metadata_file.write_bytes(b"metadata") + (metadata_dir / "._test.jpg").write_bytes(b"metadata") + (nested_metadata_dir / "._nested.jpg").write_bytes(b"metadata") + + autosplit(tmp_path / "coco8/images") + assert any((tmp_path / "coco8").glob("autosplit_*.txt")) + assert zip_directory(images_dir).is_file() + assert not metadata_dir.exists() + assert not metadata_file.exists() + with pytest.raises(ValueError, match="split"): + check_cls_dataset("imagenet10", split="invalid") + with pytest.raises(FileNotFoundError, match="'test:' images not found"): + check_det_dataset("coco8.yaml", split="test") + data_yaml = tmp_path / "coco8.yaml" + data_yaml.write_text("train: images/train\nval: images/val\ntest: images/test\nnames: [item]\n") + with pytest.raises(FileNotFoundError, match="images not found"): + check_det_dataset(data_yaml, split="test") + + # polygons2masks_overlap must not overflow uint8 on the transient `masks + mask` sum (reaches 2 * i + 1): + # with more than 128 overlapping instances every instance must keep a distinct index in the overlap mask + from ultralytics.data.utils import polygons2masks_overlap + + segments = [ + np.array([[150 - s, 150 - s], [150 + s, 150 - s], [150 + s, 150 + s], [150 - s, 150 + s]], dtype=np.float32) + for s in range(140, 10, -1) # 130 concentric squares, all overlapping the center + ] + overlap, _ = polygons2masks_overlap((300, 300), segments) + assert len(np.unique(overlap)) == len(segments) + 1 # background + 130 instances, no uint8 wraparound + + +def test_safe_download_unzips_local_path_archive(tmp_path): + """Test safe_download() unzips local zip and tar paths to the archive's single top-level directory.""" + dataset_dir = tmp_path / "coco8 local" + archive = tmp_path / "coco8 local.zip" + (dataset_dir / "images" / "train").mkdir(parents=True) + (dataset_dir / "images" / "val").mkdir(parents=True) + (dataset_dir / "labels" / "train").mkdir(parents=True) + (dataset_dir / "labels" / "val").mkdir(parents=True) + (dataset_dir / "data.yaml").write_text("path: .\ntrain: images/train\nval: images/val\nnames:\n 0: item\n") + + with zipfile.ZipFile(archive, "w") as zf: + for path in dataset_dir.rglob("*"): + zf.write(path, arcname=path.relative_to(tmp_path)) + + extracted = safe_download(archive, dir=tmp_path / "datasets", unzip=True, progress=False) + expected_path = tmp_path / "datasets" / dataset_dir.name + assert extracted == expected_path, f"Extracted path {extracted} != expected {expected_path}" + assert (extracted / "data.yaml").is_file(), f"data.yaml not found in {extracted}" + assert (extracted / "images" / "val").is_dir(), f"images/val not found in {extracted}" + + with tarfile.open(tar_archive := tmp_path / "coco8 local.tar", "w") as tar: + tar.add(dataset_dir, arcname=dataset_dir.name) + tar_extracted = safe_download(tar_archive, dir=tmp_path / "datasets2", unzip=True, progress=False) + assert tar_extracted == tmp_path / "datasets2" / dataset_dir.name, f"tar returned {tar_extracted}" + + mislabeled = tmp_path / "corrupt.zip" # an HTML error page served with a .zip name + mislabeled.write_bytes(b"not an archive\n") + assert safe_download(mislabeled, dir=tmp_path / "datasets3", unzip=True, progress=False) == mislabeled + + +def test_safe_download_skips_unsafe_archive_members(tmp_path): + """Test safe_download() skips archive members that would extract outside the target directory.""" + archive = tmp_path / "unsafe.zip" + with zipfile.ZipFile(archive, "w") as zf: + zf.writestr("../unsafe.txt", "bad") + zf.writestr("safe/file.txt", "ok") + + extracted = safe_download(archive, dir=tmp_path / "datasets", unzip=True, progress=False) + + assert not (tmp_path / "unsafe.txt").exists() + assert (extracted / "safe/file.txt").is_file() + + +def test_safe_download_skips_unsafe_tar_members(tmp_path): + """Test safe_download() skips tar members that would extract outside the target directory.""" + source = tmp_path / "safe.txt" + source.write_text("ok") + archive = tmp_path / "unsafe.tar" + with tarfile.open(archive, "w") as tar: + tar.add(source, arcname="../unsafe.txt") + tar.add(source, arcname="safe.txt") + + extracted = safe_download(archive, dir=tmp_path / "datasets", unzip=True, progress=False) + + assert not (tmp_path / "unsafe.txt").exists() + assert (extracted / "safe.txt").is_file() + + +@pytest.mark.skipif(not ONLINE, reason="environment is offline") +def test_data_converter(tmp_path): + """Test dataset conversion functions from COCO to YOLO format and class mappings.""" + from ultralytics.data.converter import coco80_to_coco91_class, convert_coco + + cached_file = DATASETS_DIR / "annotations" / "instances_val2017.json" + if cached_file.exists(): + shutil.copy2(cached_file, tmp_path / cached_file.name) + else: + download(f"{ASSETS_URL}/instances_val2017.json", dir=tmp_path) + convert_coco( + labels_dir=tmp_path, save_dir=tmp_path / "yolo_labels", use_segments=True, use_keypoints=False, cls91to80=True + ) + coco80_to_coco91_class() + + +def test_data_annotator(tmp_path): + """Test automatic annotation of data using detection and segmentation models.""" + from ultralytics.data.annotator import auto_annotate + + auto_annotate( + ASSETS, + det_model=WEIGHTS_DIR / "yolo26n.pt", + sam_model=WEIGHTS_DIR / "mobile_sam.pt", + output_dir=tmp_path / "auto_annotate_labels", + ) + + +def test_events(): + """Test event sending functionality.""" + from ultralytics.utils.events import Events + + events = Events() + events.enabled = True + cfg = copy(DEFAULT_CFG) # does not require deepcopy + cfg.mode = "test" + events(cfg) + + +def test_cfg_init(): + """Test configuration initialization utilities from the 'ultralytics.cfg' module.""" + from ultralytics.cfg import check_dict_alignment, copy_default_cfg, smart_value + + with contextlib.suppress(SyntaxError): + check_dict_alignment({"a": 1}, {"b": 2}) + copy_default_cfg() + (Path.cwd() / DEFAULT_CFG_PATH.name.replace(".yaml", "_copy.yaml")).unlink(missing_ok=False) + + # Test smart_value() with comprehensive cases + # Test None conversion + assert smart_value("none") is None + assert smart_value("None") is None + assert smart_value("NONE") is None + + # Test boolean conversion + assert smart_value("true") is True + assert smart_value("True") is True + assert smart_value("TRUE") is True + assert smart_value("false") is False + assert smart_value("False") is False + assert smart_value("FALSE") is False + + # Test numeric conversion (ast.literal_eval) + assert smart_value("42") == 42 + assert smart_value("-42") == -42 + assert smart_value("3.14") == 3.14 + assert smart_value("-3.14") == -3.14 + assert smart_value("1e-3") == 0.001 + + # Test list/tuple conversion (ast.literal_eval) + assert smart_value("[1, 2, 3]") == [1, 2, 3] + assert smart_value("(1, 2, 3)") == (1, 2, 3) + assert smart_value("[640, 640]") == [640, 640] + + # Test dict conversion (ast.literal_eval) + assert smart_value("{'a': 1, 'b': 2}") == {"a": 1, "b": 2} + + # Test string fallback (when ast.literal_eval fails) + assert smart_value("some_string") == "some_string" + assert smart_value("path/to/file") == "path/to/file" + assert smart_value("hello world") == "hello world" + + # Test that code injection is prevented (ast.literal_eval safety) + # These should return strings, not execute code + assert smart_value("__import__('os').system('ls')") == "__import__('os').system('ls')" + assert smart_value("eval('1+1')") == "eval('1+1')" + assert smart_value("exec('x=1')") == "exec('x=1')" + + assert smart_value("zipfile.ZIP_DEFLATED") == zipfile.ZIP_DEFLATED + assert smart_value("zipfile.Path") == "zipfile.Path" + + +def test_depth_calibration_checkpoint_provenance(tmp_path): + """Depth calibration persists the selected transform and sample count with the checkpoint.""" + from copy import deepcopy + + from ultralytics.models.yolo.depth.calibrate import _depth_head, calibrate_checkpoint + from ultralytics.nn.tasks import DepthModel + from ultralytics.utils.patches import torch_load + + torch.manual_seed(0) + model = DepthModel("yolo26n-depth.yaml", verbose=False) + batches = [ + {"img": (torch.rand(2, 3, 64, 64) * 255).to(torch.uint8), "depth": torch.rand(2, 64, 64) * 5 + 0.5} + for _ in range(4) + ] + path = tmp_path / "depth.pt" + torch.save({"model": deepcopy(model).half()}, path) + + provenance = calibrate_checkpoint( + path, batches, device="cpu", dataset_hash="manifest-sha256", validation_split="images/val" + ) + checkpoint = torch_load(path) + head = _depth_head(checkpoint["model"]) + + assert provenance == checkpoint["depth_calibration"] + assert provenance["candidate"] in {"identity", "scale-only"} + assert provenance["images"] == 8 + assert provenance["status"] == "selected" + assert provenance["dataset_hash"] == "manifest-sha256" + assert provenance["validation_split"] == "images/val" + assert provenance["strategy"] == "two-fold-held-out-delta1" + assert set(provenance["scores"]) == {"identity", "scale-only"} + assert float(head.cal_a) == provenance["a"] + assert float(head.cal_b) == provenance["b"] + + +@pytest.mark.parametrize("external", [False, True]) +def test_depth_trainer_records_portable_calibration_split(tmp_path, monkeypatch, external): + """Calibration provenance records local splits without rejecting external validation paths.""" + from ultralytics.models.yolo import detect + from ultralytics.models.yolo.depth import calibrate + from ultralytics.models.yolo.depth.train import DepthTrainer + + dataset_root = tmp_path / "private" / "dataset" + validation_path = (tmp_path / "shared" if external else dataset_root) / "images" / "val" + validation_path.mkdir(parents=True) + checkpoint = tmp_path / "best.pt" + checkpoint.touch() + captured = {} + monkeypatch.setattr(detect.DetectionTrainer, "final_eval", lambda _self: None) + monkeypatch.setattr( + calibrate, + "calibrate_checkpoint", + lambda *_args, **kwargs: captured.update(kwargs) or {"status": "selected"}, + ) + trainer = DepthTrainer.__new__(DepthTrainer) + trainer.best = checkpoint + trainer.last = tmp_path / "last.pt" + trainer.save_dir = tmp_path + trainer.args = get_cfg(overrides={"plots": False}) + trainer.test_loader = [] + trainer.device = "cpu" + trainer.data = {"path": dataset_root, "val": str(validation_path), "hash": "manifest-sha256"} + + trainer.final_eval() + + assert captured["validation_split"] == (None if external else "images/val") + if captured["validation_split"] is not None: + assert str(tmp_path) not in captured["validation_split"] + + +def test_depth_dataset_ignores_unreadable_targets(tmp_path): + """Drop unreadable depth maps and accept single-class mode with empty class labels.""" + from ultralytics.data.dataset import DepthDataset + from ultralytics.data.utils import save_depth_png + from ultralytics.utils import DEFAULT_CFG + + images, depth = tmp_path / "images" / "train", tmp_path / "depth" / "train" + images.mkdir(parents=True) + depth.mkdir(parents=True) + for name in ("valid", "scaled", "legacy", "aspect", "corrupt", "missing"): + cv2.imwrite(str(images / f"{name}.jpg"), np.zeros((32, 32, 3), np.uint8)) + save_depth_png(depth / "valid.png", np.ones((32, 32), dtype=np.float32), scale=100) + with Image.open(depth / "valid.png") as image: + assert not image.info + assert np.asarray(image).max() == 100 + cv2.imwrite(str(depth / "scaled.png"), np.full((32, 32), 150, np.uint16)) + legacy = np.full((32, 32), 2.0, np.float32) + legacy[0, :3] = np.nan, np.inf, -np.inf + np.save(depth / "legacy.npy", legacy) + cv2.imwrite(str(depth / "aspect.png"), np.ones((16, 32), np.uint16)) + (depth / "corrupt.png").write_text("not a png file") + + data = {"names": {0: "depth"}, "nc": 1, "channels": 3, "depth_scale": 100} + hyp = copy(DEFAULT_CFG) + hyp.mosaic = 1.0 # pin the value the unsupported-argument zeroing must not reach, regardless of ambient state + ds = DepthDataset(img_path=str(images), imgsz=32, data=data, augment=False, single_cls=True, batch_size=1, hyp=hyp) + assert hyp.mosaic == 1.0 # construction must never mutate the caller's hyp namespace + assert {Path(f).stem for f in ds.im_files} == {"valid", "scaled", "legacy"} + assert sorted(ds._load_depth(i).max() for i in range(len(ds))) == [1.0, 1.5, 2.0] + legacy_index = next(i for i, path in enumerate(ds.im_files) if Path(path).stem == "legacy") + assert not ds._load_depth(legacy_index)[0, :3].any() + assert (depth.parent / "train.cache").exists() # scan results cached next to the depth maps + + +def test_utils_init(): + """Test initialization utilities in the Ultralytics library.""" + from ultralytics.utils import get_ubuntu_version, is_github_action_running + + get_ubuntu_version() + is_github_action_running() + + +def test_utils_checks(monkeypatch): + """Test various utility checks for filenames, requirements, image sizes, display capabilities, and versions.""" + + def package_version(name): + if name == "v2": + return "1.0" + raise checks.metadata.PackageNotFoundError + + checks.check_yolov5u_filename("yolov5n.pt") + checks.check_requirements("numpy") # check requirements.txt + checks.check_imgsz([600, 600], max_dim=1) + with pytest.raises(ValueError): + checks.check_imgsz("640x480") # malformed imgsz string raises a helpful ValueError, not a raw SyntaxError + checks.check_imshow(warn=True) + checks.check_suffix("https://example.com/model.pt?token=abc", ".pt") + checks.check_version("ultralytics", "8.0.0") + # parse_version must pad to at least 3 components and keep all segments so any version pair compares correctly + assert checks.parse_version("2") == (2, 0, 0) + assert checks.parse_version("4.13.0.92") == (4, 13, 0, 92) + assert checks.parse_version("2.0.1+cu118") == (2, 0, 1) # numeric local/build suffixes are not release segments + assert checks.parse_version("1.0.0rc1") == (1, 0, 0) + assert checks.parse_version("v2.1") == (2, 1, 0) + assert checks.parse_version("1.0rc1") == (1, 0, 0) # documented non-PEP-440 tradeoff: pre-releases equal the final + monkeypatch.setattr(checks.metadata, "version", package_version) + monkeypatch.setattr(checks, "ARM64", True) + monkeypatch.setattr(checks, "AUTOINSTALL", True) + monkeypatch.setattr(checks, "ONLINE", True) + commands = [] + monkeypatch.setattr(checks.subprocess, "check_output", lambda command, **kwargs: commands.append(command) or "") + requirements = ["ray[tune]", "nvidia-modelopt[onnx]>=0.44", "$(touch /tmp/pwned)/missing"] + assert checks.check_requirements(requirements) + assert commands[0][5:] == requirements # requirements remain individual argv entries, never shell source + assert not checks.check_version("v2", ">=2.0") # installed version-shaped package keeps metadata precedence + versions = ("v2.1-rc.1", "v2.1-beta1", "v2.1rev1", "v2.1-dev1", "v2.1+cu118") + assert all(checks.check_version(v, ">=2.0") for v in versions) + with pytest.raises(ModuleNotFoundError): + checks.check_version("v2-missing", ">=2.0", hard=True) + assert checks.check_version("10.3.0.30", ">=10.3.0,<10.4.0") # Jetson TensorRT family pin + assert checks.check_version("6.0", ">=6.0.0") # 2-component current must satisfy 3-component requirement + assert checks.check_version("2.1", "==2.1.0") + assert checks.check_version("4.13.0.92", "!=4.13.0.90") # 4-segment pins must not be truncated + assert not checks.check_version("4.13.0.90", "!=4.13.0.90") + assert checks.check_version("2.0.1", "<2.0.1.5") + checks.print_args() + + +@pytest.mark.skipif(WINDOWS, reason="Windows profiling is extremely slow (cause unknown)") +def test_utils_benchmarks(): + """Benchmark model performance using 'ProfileModels' from 'ultralytics.utils.benchmarks'.""" + from ultralytics.utils.benchmarks import ProfileModels + + ProfileModels(["yolo26n.yaml"], imgsz=32, min_time=1, num_timed_runs=3, num_warmup_runs=1).run() + + +def test_utils_torchutils(): + """Test Torch utility functions including profiling and FLOP calculations.""" + from ultralytics.nn.modules.conv import Conv + from ultralytics.utils.torch_utils import profile_ops, time_sync + + x = torch.randn(1, 64, 20, 20) + m = Conv(64, 64, k=1, s=2) + + profile_ops(x, [m], n=3) + time_sync() + + +def test_rtdetr_remap_cls_by_names(): + """Test RT-DETR decoder cls-head remap (direct-name match, unmatched, denoising partial transfer).""" + from types import SimpleNamespace + + from ultralytics.nn.tasks import RTDETRDetectionModel + + # Source has 2 classes (person, bird), target has 3 (person, bird, airplane). Target 'airplane' has no source. + dst_state = { + "score_head.weight": torch.full((3, 1), -1.0), + "score_head.bias": torch.full((3,), -1.0), + "decoder.denoising_class_embed.weight": torch.full((3, 4), -1.0), + } + csd = { + "score_head.weight": torch.tensor([[1.0], [2.0]]), + "score_head.bias": torch.tensor([10.0, 20.0]), + "decoder.denoising_class_embed.weight": torch.full((2, 4), 9.0), + } + tgt = SimpleNamespace(names={0: "person", 1: "bird", 2: "airplane"}, state_dict=lambda: dst_state) + src = SimpleNamespace(names={0: "bird", 1: "person"}) # inverted order to exercise the row-index mapping + n = RTDETRDetectionModel._remap_cls_by_names(tgt, csd, src, verbose=False) + assert n == 3 # score_head.weight + score_head.bias + denoising_class_embed remapped + assert dst_state["score_head.weight"][0, 0].item() == 2.0 # 'person' <- src[1] + assert dst_state["score_head.weight"][1, 0].item() == 1.0 # 'bird' <- src[0] + assert dst_state["score_head.weight"][2, 0].item() == -1.0 # 'airplane' unmatched -> dst init kept + assert dst_state["score_head.bias"].tolist() == [20.0, 10.0, -1.0] + dn = dst_state["decoder.denoising_class_embed.weight"] # row-per-class embedding transfers like score_head + assert dn[0].eq(9.0).all() and dn[1].eq(9.0).all() and dn[2].eq(-1.0).all() + assert "decoder.denoising_class_embed.weight" not in csd # popped so intersect_dicts skips it + + +@pytest.mark.parametrize("nc", [1, 3]) +def test_semantic_loss_all_ignore(nc): + """SemanticSegmentationLoss must stay finite when the whole batch is ignore (255), e.g. unlabeled/void frames.""" + from ultralytics.cfg import get_cfg + from ultralytics.nn.tasks import SemanticSegmentationModel + from ultralytics.utils.loss import SemanticSegmentationLoss + + model = SemanticSegmentationModel(cfg="yolo26-sem.yaml", nc=nc, verbose=False) + model.args = get_cfg() + loss_fn = SemanticSegmentationLoss(model) + preds = torch.randn(1, nc, 64, 64, requires_grad=True) + aux = torch.randn(1, nc, 32, 32, requires_grad=True) + loss, items = loss_fn((preds, aux), {"semantic_mask": torch.full((1, 64, 64), 255, dtype=torch.long)}) + assert torch.isfinite(loss).all() and all(torch.isfinite(x).all() for x in items.values()) + loss.backward() + assert preds.grad is not None and aux.grad is not None + + +def test_semantic_confusion_matrix_large_counts(): + """SemanticMetrics must keep counting past float32's 2**24, where accumulating 1.0 at a time would saturate.""" + from ultralytics.utils.metrics import SemanticMetrics + + metrics = SemanticMetrics(names={0: "a", 1: "b"}) + metrics.matrix = torch.full((2, 2), float(2**24)) # counts already accumulated from a large val set + zeros = torch.zeros((1, 10, 10), dtype=torch.int32) + metrics.update_stats(zeros, zeros) + assert metrics.matrix[0, 0].item() == 2**24 + 100, f"confusion matrix saturated at {metrics.matrix[0, 0].item()}" + + +class _DepthLossModel(torch.nn.Module): + """Tiny stub mirroring the model surface DepthLoss26 reads: .parameters() for device and .args for hyps.""" + + def __init__(self, **over): + super().__init__() + from types import SimpleNamespace + + self.p = torch.nn.Parameter(torch.zeros(1)) + hyp = {"dlog": 1.0, "dgrad": 0.5, "dlam": 1.0} + hyp.update(over) + self.args = SimpleNamespace(**hyp) + + +def _depth_loss_for_scaled_pred(lam, scale): + """Return the SILog-only depth loss for a prediction with perfect structure but wrong global scale.""" + from ultralytics.utils.loss import DepthLoss26 + + crit = DepthLoss26(_DepthLossModel(dlam=lam, dgrad=0.0)) # SILog only + gt = torch.rand(2, 1, 16, 16) * 5 + 1.0 + pred = (gt * scale).clone().requires_grad_(True) + total, _ = crit({"depth": pred}, {"depth": gt}) + return float(total.sum().detach()) + + +def test_v26_depth_loss_lower_lambda_penalizes_scale_error_more(): + """A globally scale-shifted prediction is ~free under scale-invariant SILog (dlam=1) but must be heavily penalized + as dlam drops (loss becomes scale-dependent). + """ + loss_invariant = _depth_loss_for_scaled_pred(lam=1.0, scale=2.0) + loss_anchored = _depth_loss_for_scaled_pred(lam=0.15, scale=2.0) + assert loss_invariant < 0.05 + assert loss_anchored > 5 * max(loss_invariant, 1e-6) + + +def test_utils_ops(): + """Test utility operations for coordinate transformations and normalizations.""" + from ultralytics.utils.ops import ( + ltwh2xywh, + ltwh2xyxy, + make_divisible, + segment2box, + xywh2ltwh, + xywh2xyxy, + xywhn2xyxy, + xywhr2xyxyxyxy, + xyxy2ltwh, + xyxy2xywh, + xyxy2xywhn, + xyxyxyxy2xywhr, + ) + + make_divisible(17, torch.tensor([8])) + + boxes = torch.rand(10, 4) # xywh + torch.allclose(boxes, xyxy2xywh(xywh2xyxy(boxes))) + torch.allclose(boxes, xyxy2xywhn(xywhn2xyxy(boxes))) + torch.allclose(boxes, ltwh2xywh(xywh2ltwh(boxes))) + torch.allclose(boxes, xyxy2ltwh(ltwh2xyxy(boxes))) + + boxes = torch.rand(10, 5) # xywhr for OBB + boxes[:, 4] = torch.randn(10) * 30 + torch.allclose(boxes, xyxyxyxy2xywhr(xywhr2xyxyxyxy(boxes)), rtol=1e-3) + + # segment2box must not drop a polygon lying on the left image edge (all x == 0) to a zero box + assert segment2box(np.array([[0, 100], [0, 150], [0, 200]]), 640, 640).tolist() == [0, 100, 0, 200] + + # segment2box must keep the visible extent when edge points shift out of frame after augmentation (issue #24935) + seg = np.array([[550.0, 100.0], [690.0, 100.0], [690.0, 200.0], [550.0, 200.0]]) + assert segment2box(seg, 640, 640).tolist() == [550, 100, 640, 200] + seg = np.array([[-10.0, 100.0], [650.0, 100.0], [650.0, 200.0], [-10.0, 200.0]]) + assert segment2box(seg, 640, 640).tolist() == [0, 100, 640, 200] + assert segment2box(np.array([[100.0, 100.0], [200.0, 100.0], [700.0, -100.0]]), 640, 640).tolist() == [ + 100, + 0, + 450, + 100, + ] + assert segment2box(np.array([[700.0, 100.0], [750.0, 150.0]]), 640, 640).tolist() == [0, 0, 0, 0] + assert segment2box(np.empty((0, 2)), 640, 640).tolist() == [0, 0, 0, 0] + seg = np.array([[-100.0, -100.0], [740.0, -100.0], [740.0, 740.0], [-100.0, 740.0]]) # surrounds the image + assert segment2box(seg, 640, 640).tolist() == [0, 0, 640, 640] + + +def test_scale_coords_nonuniform_letterbox(): + """Coordinate scaling must invert independent height and width gains from stretched preprocessing.""" + from ultralytics.data.augment import LetterBox + from ultralytics.utils import ops + + labels = {"img": np.zeros((320, 640, 3), dtype=np.uint8), "ratio_pad": (3.2, 3.2)} + ratio_pad = LetterBox((640, 640), scale_fill=True)(labels)["ratio_pad"] + boxes = np.array([[32.0, 64.0, 320.0, 384.0]]) + coords = torch.tensor([[160.0, 128.0]]) + assert ratio_pad == ((6.4, 3.2), (0, 0)) + assert np.allclose(ops.scale_boxes((640, 640), boxes, (100, 200), ratio_pad), [[10, 10, 100, 60]]) + assert torch.allclose(ops.scale_coords((640, 640), coords, (100, 200), ratio_pad), coords.new_tensor([[50, 20]])) + + boxes = np.array([[32.0, 192.0, 320.0, 352.0]]) + coords = torch.tensor([[160.0, 224.0]]) + assert np.allclose(ops.scale_boxes((640, 640), boxes, (100, 200)), [[10, 10, 100, 60]]) + assert torch.allclose(ops.scale_coords((640, 640), coords, (100, 200)), coords.new_tensor([[50, 20]])) + + +def test_nms_end2end_classes_before_max_det(): + """The end-to-end NMS branch must filter classes before truncating to max_det, like the NMS-based branch.""" + from ultralytics.utils.nms import non_max_suppression + + # (2, 4, 6) end2end predictions sorted by descending confidence: [x1, y1, x2, y2, conf, cls] + pred = torch.tensor( + [ + [[0, 0, 9, 9, 0.9, 5], [1, 1, 9, 9, 0.8, 0], [2, 2, 9, 9, 0.7, 0], [3, 3, 9, 9, 0.6, 0]], + [[0, 0, 9, 9, 0.9, 0], [1, 1, 9, 9, 0.8, 5], [2, 2, 9, 9, 0.7, 5], [3, 3, 9, 9, 0.6, 0]], + ], + dtype=torch.float32, + ) + outputs, indices = non_max_suppression(pred, conf_thres=0.25, classes=[0], max_det=2, return_idxs=True) + for out, idx, confs, expected in zip(outputs, indices, ([0.8, 0.7], [0.9, 0.6]), ([1, 2], [0, 3])): + assert out.shape[0] == 2 and (out[:, 5] == 0).all() # top-2 class-0 boxes kept, not truncated away + assert torch.allclose(out[:, 4], torch.tensor(confs)) + assert idx.tolist() == expected + out = non_max_suppression(pred, conf_thres=0.25, max_det=2)[0] # without classes, top-2 overall unchanged + assert torch.allclose(out[:, 4], torch.tensor([0.9, 0.8])) + + +def test_process_mask_empty(): + """Process_mask/process_mask_native/scale_masks must handle 0 detections without crashing.""" + from ultralytics.utils import ops + + protos, coeffs, bboxes = torch.rand(32, 160, 160), torch.zeros(0, 32), torch.zeros(0, 4) + assert ops.process_mask(protos, coeffs, bboxes, (640, 640), upsample=True).shape == (0, 640, 640) + assert ops.process_mask(protos, coeffs, bboxes, (640, 640)).shape == (0, 160, 160) # prototype res when no upsample + assert ops.process_mask_native(protos, coeffs, bboxes, (640, 640)).shape == (0, 640, 640) + assert ops.scale_masks(torch.zeros(1, 0, 160, 160), (640, 640)).shape == (1, 0, 640, 640) + + +def test_utils_files(tmp_path): + """Test file handling utilities including file age, date, and paths with spaces.""" + from ultralytics.utils.files import file_age, file_date, get_latest_run, increment_path, spaces_in_path + + file_age(SOURCE) + file_date(SOURCE) + get_latest_run(ROOT / "runs") + + path = tmp_path / "path/with spaces" + path.mkdir(parents=True, exist_ok=True) + with spaces_in_path(path) as new_path: + print(new_path) + + exp_dir = tmp_path / "runs" / "exp" + exp_dir.mkdir(parents=True) + assert increment_path(exp_dir) == tmp_path / "runs" / "exp-2" + + results_file = exp_dir / "results.txt" + results_file.touch() + assert increment_path(results_file) == exp_dir / "results-2.txt" + + +@pytest.mark.slow +def test_utils_patches_torch_save(tmp_path): + """Test torch_save backoff when _torch_save raises RuntimeError.""" + from unittest.mock import MagicMock, patch + + from ultralytics.utils.patches import torch_save + + mock = MagicMock(side_effect=RuntimeError) + + with patch("ultralytics.utils.patches._torch_save", new=mock), pytest.raises(RuntimeError): + torch_save(torch.zeros(1), tmp_path / "test.pt") + + assert mock.call_count == 4, "torch_save was not attempted the expected number of times" + + +def test_nn_modules_conv(): + """Test Convolutional Neural Network modules including CBAM, Conv2, and ConvTranspose.""" + from ultralytics.nn.modules.conv import CBAM, Conv2, ConvTranspose, DWConvTranspose2d, Focus + + c1, c2 = 8, 16 # input and output channels + x = torch.zeros(4, c1, 10, 10) # BCHW + + # Run all modules not otherwise covered in tests + DWConvTranspose2d(c1, c2)(x) + ConvTranspose(c1, c2)(x) + Focus(c1, c2)(x) + CBAM(c1)(x) + + # Fuse ops + m = Conv2(c1, c2) + m.fuse_convs() + m(x) + + +def test_nn_modules_block(): + """Test various neural network block modules.""" + from ultralytics.nn.modules.block import C1, C3TR, BottleneckCSP, C3Ghost, C3x + + c1, c2 = 8, 16 # input and output channels + x = torch.zeros(4, c1, 10, 10) # BCHW + + # Run all modules not otherwise covered in tests + C1(c1, c2)(x) + C3x(c1, c2)(x) + C3TR(c1, c2)(x) + C3Ghost(c1, c2)(x) + BottleneckCSP(c1, c2)(x) + + +def test_nn_detect_head_export_clamps_max_det(): + """Detect export postprocess should not request more candidates than available anchors.""" + from ultralytics.nn.modules.head import Detect + + head = Detect(nc=2, ch=(16,)) + head.export = True + head.format = "onnx" + anchors = 21 + assert head.postprocess(torch.rand(1, anchors, 4 + head.nc)).shape == (1, anchors, 6) + + +def _depth_head_feats(): + """Return a small Depth head constructor kwargs-matched P3/P4/P5 feature pyramid.""" + return [torch.randn(1, 32, 32, 32), torch.randn(1, 64, 16, 16), torch.randn(1, 128, 8, 8)] + + +def test_nn_depth_head_export_upsamples_to_input(): + """Depth export upsamples x4 to input resolution; inference returns native head resolution.""" + from ultralytics.nn.modules.head import Depth + + head = Depth(c_mid=32, ch=(32, 64, 128)).eval() + for fmt in ("onnx", "coreml"): + head.export, head.format = True, fmt + assert head(_depth_head_feats()).shape[-2:] == (256, 256) + head.export = False + assert head(_depth_head_feats()).shape[-2:] != (256, 256) # inference returns native head resolution + + +def test_nn_depth_head_no_dead_parameters(): + """Every head parameter receives gradient — DDP then needs no find_unused_parameters.""" + from ultralytics.nn.modules.head import Depth + + head = Depth(c_mid=32, ch=(32, 64, 128)).train() + head(_depth_head_feats())["depth"].sum().backward() + unused = [n for n, p in head.named_parameters() if p.grad is None] + assert not unused, f"parameters with no gradient: {unused}" + + +def test_classification_fraction_samples_across_classes(tmp_path): + """Sample classification fractions across the class-major ImageFolder ordering.""" + from ultralytics.data.dataset import ClassificationDataset + + for class_index in range(3): + class_dir = tmp_path / str(class_index) + class_dir.mkdir() + for image_index in range(4): + cv2.imwrite(str(class_dir / f"{image_index}.jpg"), np.full((16, 16, 3), class_index, dtype=np.uint8)) + args = copy(DEFAULT_CFG) + args.fraction = 0.5 + samples = ClassificationDataset(tmp_path, args, augment=True).samples + + assert np.bincount([sample[1] for sample in samples]).tolist() == [2, 2, 2] + + +def test_classification_split_class_alignment(tmp_path): + """Align a split's class folders to the model's class order by name and drop classes the model lacks.""" + from ultralytics.data.dataset import ClassificationDataset + + for name in ("b", "c", "d"): # the split lacks the model's first class and adds one it does not have + (tmp_path / name).mkdir() + cv2.imwrite(str(tmp_path / name / "0.jpg"), np.zeros((16, 16, 3), dtype=np.uint8)) + samples = ClassificationDataset(tmp_path, DEFAULT_CFG, names={0: "a", 1: "b", 2: "c"}).samples + assert sorted(sample[1] for sample in samples) == [1, 2] + + +@pytest.fixture +def image(): + """Load and return an image from a predefined source (OpenCV BGR).""" + return cv2.imread(str(SOURCE)) + + +@pytest.mark.parametrize( + "auto_augment, erasing, force_color_jitter", + [ + (None, 0.0, False), + ("randaugment", 0.5, True), + ("augmix", 0.2, False), + ("autoaugment", 0.0, True), + ], +) +def test_classify_transforms_train(image, auto_augment, erasing, force_color_jitter): + """Test classification transforms during training with various augmentations.""" + from ultralytics.data.augment import classify_augmentations + + transform = classify_augmentations( + size=224, + mean=(0.5, 0.5, 0.5), + std=(0.5, 0.5, 0.5), + scale=(0.08, 1.0), + ratio=(3.0 / 4.0, 4.0 / 3.0), + hflip=0.5, + vflip=0.5, + auto_augment=auto_augment, + hsv_h=0.015, + hsv_s=0.4, + hsv_v=0.4, + force_color_jitter=force_color_jitter, + erasing=erasing, + ) + + transformed_image = transform(Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))) + + assert transformed_image.shape == (3, 224, 224) + assert torch.is_tensor(transformed_image) + assert transformed_image.dtype == torch.float32 + + +@pytest.mark.slow +@pytest.mark.skipif(IS_RASPBERRYPI or IS_JETSON, reason="Edge devices not intended for tuning") +@pytest.mark.skipif(not ONLINE, reason="environment is offline") +def test_model_tune(): + """Tune YOLO model for performance improvement.""" + YOLO("yolo26n.pt").tune( + data=["coco8.yaml", "coco8-grayscale.yaml"], plots=False, imgsz=32, epochs=1, iterations=2, device="cpu" + ) + YOLO("yolo26n-pose.pt").tune(data="coco8-pose.yaml", plots=False, imgsz=32, epochs=1, iterations=2, device="cpu") + YOLO("yolo26n-cls.pt").tune(data="imagenet10", plots=False, imgsz=32, epochs=1, iterations=2, device="cpu") + + +@pytest.mark.slow +@pytest.mark.skipif(IS_RASPBERRYPI or IS_JETSON, reason="Edge devices not intended for tuning") +@pytest.mark.skipif(not ONLINE or not checks.IS_PYTHON_MINIMUM_3_10, reason="environment is offline") +@pytest.mark.skipif(not checks.check_requirements("ray", install=False), reason="ray[tune] not installed") +def test_model_tune_ray(): + """Tune YOLO model for performance improvement.""" + YOLO("yolo26n-cls.pt").tune( + data="imagenet10", + use_ray=True, + plots=False, + imgsz=32, + epochs=1, + iterations=2, + search_alg="random", + device="cpu", + ) + + +def test_model_embeddings(): + """Test YOLO model embeddings extraction functionality.""" + model_detect = YOLO(MODEL) + model_segment = YOLO(WEIGHTS_DIR / "yolo26n-seg.pt") + + for batch in [SOURCE], [SOURCE, SOURCE]: # test batch size 1 and 2 + assert len(model_detect.embed(source=batch, imgsz=32)) == len(batch) + assert len(model_segment.embed(source=batch, imgsz=32)) == len(batch) + + model_classify = YOLO(WEIGHTS_DIR / "yolo26n-cls.pt") + assert model_classify.predict(SOURCE, imgsz=32)[0].probs is not None + assert isinstance(model_classify.embed(SOURCE, imgsz=32)[0], torch.Tensor) + assert model_classify.predict(SOURCE, imgsz=32)[0].probs is not None + assert isinstance(model_classify.predict(SOURCE, imgsz=32, embed=[-2])[0], torch.Tensor) + assert model_classify.predict(SOURCE, imgsz=32)[0].probs is not None + + +def test_process_mask_native_chunked(): + """Chunked native upsampling is identical to upsampling all masks at once.""" + from ultralytics.utils import ops + + torch.manual_seed(0) + protos, masks_in = torch.randn(32, 160, 160), torch.randn(70, 32) + bboxes = torch.rand(70, 4) * 900 + 5 # fractional boxes exercise the crop edge handling + bboxes[:, 2:] += bboxes[:, :2] + out = ops.process_mask_native(protos, masks_in, bboxes, (1000, 1000)) # large shape forces multiple chunks + ref = ops.scale_masks((masks_in @ protos.float().view(32, -1)).view(-1, 160, 160)[None], (1000, 1000))[0] + ref = ops.crop_mask(ref, bboxes).gt_(0.0).byte() # single-shot upsample-crop-threshold + assert torch.equal(out, ref) + + +@pytest.mark.skipif(IS_RASPBERRYPI, reason="Edge devices not intended for CLIP-based models") +@pytest.mark.skipif( + checks.IS_PYTHON_3_8 and LINUX and ARM64, + reason="YOLOWorld with CLIP is not supported in Python 3.8 and aarch64 Linux", +) +def test_yolo_world(): + """Test YOLO world models with CLIP support.""" + model = YOLO(WEIGHTS_DIR / "yolov8s-world.pt") # no YOLO11n-world model yet + model.set_classes(["tree", "window"]) + model(SOURCE, conf=0.01) + + model = YOLO(WEIGHTS_DIR / "yolov8s-worldv2.pt") # no YOLO11n-world model yet + # Training from a pretrained model. Eval is included at the final stage of training. + # Use dota8.yaml which has fewer categories to reduce the inference time of CLIP model + model.train( + data="dota8.yaml", + epochs=1, + imgsz=32, + cache="disk", + close_mosaic=1, + ) + + # test WorWorldTrainerFromScratch + from ultralytics.models.yolo.world.train_world import WorldTrainerFromScratch + + model = YOLO("yolov8s-worldv2.yaml") # no YOLO11n-world model yet + model.train( + data={"train": {"yolo_data": ["dota8.yaml"]}, "val": {"yolo_data": ["dota8.yaml"]}}, + epochs=1, + imgsz=32, + cache="disk", + close_mosaic=1, + trainer=WorldTrainerFromScratch, + ) + + +@pytest.mark.skipif(IS_RASPBERRYPI, reason="Edge devices not intended for heavy CLIP-based models") +@pytest.mark.skipif(not TORCH_1_13, reason="YOLOE with CLIP requires torch>=1.13") +@pytest.mark.skipif( + checks.IS_PYTHON_3_8 and LINUX and ARM64, + reason="YOLOE with CLIP is not supported in Python 3.8 and aarch64 Linux", +) +def test_yoloe(tmp_path): + """Test YOLOE models with MobileCLIP support.""" + # Predict + # text-prompts + model = YOLO(WEIGHTS_DIR / "yoloe-11s-seg.pt") + model.set_classes(["person", "bus"]) + model.set_classes(["bus", "person"]) + assert list(model.names.values()) == ["bus", "person"] + model(SOURCE, conf=0.01) + + from ultralytics import YOLOE + from ultralytics.models.yolo.yoloe import YOLOEVPSegPredictor + + # visual-prompts + visuals = { + "bboxes": np.array([[221.52, 405.8, 344.98, 857.54], [120, 425, 160, 445]]), + "cls": np.array([0, 1]), + } + model.predict( + SOURCE, + visual_prompts=visuals, + predictor=YOLOEVPSegPredictor, + ) + + # Val + model = YOLOE(WEIGHTS_DIR / "yoloe-11s-seg.pt") + # text prompts + model.val(data="coco128-seg.yaml", imgsz=32) + # visual prompts + model.val(data="coco128-seg.yaml", load_vp=True, imgsz=32) + + # Train, fine-tune + from ultralytics.models.yolo.yoloe import YOLOEPEFreeTrainer, YOLOEPESegTrainer, YOLOESegTrainerFromScratch + + model = YOLOE("yoloe-11s-seg.pt") + model.train( + data="coco128-seg.yaml", + epochs=1, + close_mosaic=1, + trainer=YOLOEPESegTrainer, + imgsz=32, + ) + # Train, from scratch + data_dict = {"train": {"yolo_data": ["coco128-seg.yaml"]}, "val": {"yolo_data": ["coco128-seg.yaml"]}} + data_yaml = tmp_path / "yoloe-data.yaml" + YAML.save(data=data_dict, file=data_yaml) + for data in [data_dict, data_yaml]: + model = YOLOE("yoloe-11s-seg.yaml") + model.train( + data=data, + epochs=1, + close_mosaic=1, + trainer=YOLOESegTrainerFromScratch, + imgsz=32, + ) + + # prompt-free + # predict + model = YOLOE(WEIGHTS_DIR / "yoloe-11s-seg-pf.pt") + model.predict(SOURCE) + # val + model = YOLOE("yoloe-11s-seg.pt") # or select yoloe-m/l-seg.pt for different sizes + model.val(data="coco128-seg.yaml", imgsz=32) + # train, freezing everything but the classification branch + model = YOLOE("yoloe-11s-seg.pt") + head = len(model.model.model) - 1 + freeze = [str(i) for i in range(head)] + freeze += [f"{head}.{name}" for name, _ in model.model.model[-1].named_children() if "cv3" not in name] + freeze += [f"{head}.cv3.{i}.{j}" for i in range(3) for j in (0, 1)] + model.train( + data={"train": {"yolo_data": ["coco128-seg.yaml"]}, "val": {"yolo_data": ["coco128-seg.yaml"]}}, + epochs=1, + close_mosaic=1, + trainer=YOLOEPEFreeTrainer, + imgsz=32, + freeze=freeze, + single_cls=True, + ) + assert "seg_loss" in model.trainer.loss_names # segmentation criterion, not the detection one + assert Path(model.trainer.best).exists() # end-of-training validation ran and weights were saved + + +@pytest.mark.skipif(IS_RASPBERRYPI, reason="Edge devices not intended for heavy CLIP-based models") +@pytest.mark.skipif(not TORCH_2_0, reason="MobileCLIP2 uses scaled_dot_product_attention (torch>=2.0)") +def test_yoloe_vocab_head_switch(): + """Keep prompt-free inference on the branch that its vocabulary reparameterized.""" + model = YOLO(WEIGHTS_DIR / "yoloe-26n-seg.pt") + model.model.args["imgsz"] = 32 + names = ["person", "bus"] + vocab = model.get_vocab(names) # one-to-many branch + model.set_vocab(vocab, names) + for nms in (None, False): + model(SOURCE, imgsz=32, nms=nms) + + dual = YOLO(WEIGHTS_DIR / "yoloe-26n-seg.pt") # one head per branch, as the yoloe-26*-seg-pf.pt weights carry + dual.model.args["imgsz"] = 32 + dual.model.end2end = True + dual.set_vocab(vocab, names, one2one_vocab=dual.get_vocab(names)) + for nms in (None, False): + dual(SOURCE, imgsz=32, nms=nms) + + +def test_yoloe_visual_prompt_verbose_false(capfd): + """Verify that YOLOE visual prompting respects verbose=False.""" + model = YOLO(WEIGHTS_DIR / "yoloe-11s-seg.pt") + + from ultralytics.models.yolo.yoloe import YOLOEVPSegPredictor + + visuals = { + "bboxes": np.array([[221.52, 405.8, 344.98, 857.54]]), + "cls": np.array([0]), + } + + # Ignore any output produced while loading the model + capfd.readouterr() + + model.predict( + SOURCE, + refer_image=SOURCE, + visual_prompts=visuals, + predictor=YOLOEVPSegPredictor, + verbose=False, + ) + + captured = capfd.readouterr() + output = captured.out + captured.err + + assert "Ultralytics" not in output + + +def test_yolov10(): + """Test YOLOv10 model training, validation, and prediction functionality.""" + model = YOLO("yolov10n.yaml") + # train/val/predict + model.train(data="coco8.yaml", epochs=1, imgsz=32, close_mosaic=1, cache="disk") + model.val(data="coco8.yaml", imgsz=32) + model.predict(imgsz=32, save_txt=True, save_crop=True, augment=True) + model(SOURCE) + + +@pytest.mark.parametrize("grayscale_tiff", (False, True)) +def test_multichannel(tmp_path, grayscale_tiff): + """Test training, validation, prediction, and export with multispectral and grayscale TIFF datasets.""" + data = "coco8-multispectral.yaml" + if grayscale_tiff: + dataset = check_det_dataset(data) + root = shutil.copytree(dataset["path"], tmp_path / "dataset", ignore=shutil.ignore_patterns("*.npy", "*.cache")) + for path in Path(root).rglob("*.tiff"): + with Image.open(path) as image: + frame = image.copy() # Retain only the first grayscale page. + frame.save(path) + data = tmp_path / "data.yaml" + YAML.save(data, {"path": str(root), "train": "images/train", "val": "images/val", "names": dataset["names"]}) + + model = YOLO("yolo26n.pt") + model.train(data=data, epochs=1, imgsz=32, close_mosaic=1, cache="disk") + model.val(data=data) + im = np.zeros((32, 32, 3 if grayscale_tiff else 10), dtype=np.uint8) + model.predict(source=im, imgsz=32, save_txt=True, save_crop=True, augment=True) + model.export(format="onnx") + + +@pytest.mark.parametrize("task,model,data", TASK_MODEL_DATA) +def test_grayscale(task: str, model: str, data: str, tmp_path) -> None: + """Test YOLO model grayscale training, validation, and prediction functionality.""" + if IS_RASPBERRYPI and task == "semantic": + skip_rpi_semantic() + if task in {"classify", "depth"}: # grayscale not supported for classification or depth tasks + return + grayscale_data = tmp_path / f"{Path(data).stem}-grayscale.yaml" + data = check_det_dataset(data) + data["channels"] = 1 # add additional channels key for grayscale + YAML.save(data=data, file=grayscale_data) + # remove npy files in train/val splits if exists, might be created by previous tests + for split in ("train", "val"): + for npy_file in (Path(data["path"]) / data[split]).glob("*.npy"): + npy_file.unlink() + + model = YOLO(model) + model.train(data=grayscale_data, epochs=1, imgsz=32, close_mosaic=1, cache="ram") + model.val(data=grayscale_data) + im = np.zeros((32, 32, 1), dtype=np.uint8) + model.predict(source=im, imgsz=32, save_txt=True, save_crop=True, augment=True) + export_model = model.export(format="onnx") + + model = YOLO(export_model, task=task) + model.predict(source=im, imgsz=32) + + +def test_semantic_polygon_data(): + """Test YOLO semantic segmentation model with polygon data.""" + skip_rpi_semantic() + model = YOLO("yolo26n-sem.pt") + model.train(data="coco8-seg.yaml", epochs=1, imgsz=32, close_mosaic=1) + model.val(data="coco8-seg.yaml") + + +def test_semantic_cache_nc_edit_1bit_masks(tmp_path): + """Test a yaml-only nc 2->1 edit still loads 1-bit masks as {0, 1} from a cache scanned at nc=2.""" + from ultralytics.data.dataset import SemanticDataset + + images, masks = tmp_path / "images" / "train", tmp_path / "masks" / "train" + images.mkdir(parents=True) + masks.mkdir(parents=True) + foreground = np.zeros((32, 32), dtype=np.uint8) + foreground[8:24, 8:24] = 255 + cv2.imwrite(str(images / "a.jpg"), np.zeros((32, 32, 3), dtype=np.uint8)) + Image.fromarray(foreground).convert("1").save(masks / "a.png") # cv2 later reads this as 0/255 + + data = {"names": {0: "bg", 1: "fg"}, "nc": 2} + SemanticDataset(img_path=str(images), imgsz=32, data=data) # scan and cache at nc=2 + dataset = SemanticDataset(img_path=str(images), imgsz=32, data={**data, "nc": 1}) # yaml-only nc edit + assert set(np.unique(dataset.load_mask(0))) == {0, 1} # 1-bit foreground remapped from 255 diff --git a/.venv/lib/python3.12/site-packages/tests/test_solutions.py b/.venv/lib/python3.12/site-packages/tests/test_solutions.py new file mode 100644 index 0000000000000000000000000000000000000000..e9813c5da92c536a4c9374a8cebb19aced6e644e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tests/test_solutions.py @@ -0,0 +1,467 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +# Tests Ultralytics Solutions: https://docs.ultralytics.com/solutions, +# Includes all solutions except DistanceCalculation and the Security Alarm System. + +import os +from unittest.mock import patch + +import cv2 +import numpy as np +import pytest +import torch + +from tests import MODEL +from ultralytics import solutions +from ultralytics.utils import IS_RASPBERRYPI, TORCH_VERSION, checks +from ultralytics.utils.downloads import safe_download +from ultralytics.utils.torch_utils import TORCH_2_4 + +# Predefined argument values +SHOW = False +REGION = [(10, 200), (540, 200), (540, 180), (10, 180)] # for object counting, speed estimation and queue management +HORIZONTAL_LINE = [(10, 200), (540, 200)] # for object counting +VERTICAL_LINE = [(320, 0), (320, 400)] # for object counting + + +def process_video(solution, video_path: str, needs_frame_count: bool = False): + """Process video with solution, feeding frames and optional frame count to the solution instance.""" + cap = cv2.VideoCapture(video_path) + assert cap.isOpened(), f"Error reading video file {video_path}" + + frame_count = 0 + while cap.isOpened(): + success, im0 = cap.read() + if not success: + break + frame_count += 1 + im_copy = im0.copy() + args = [im_copy, frame_count] if needs_frame_count else [im_copy] + _ = solution(*args) + + cap.release() + + +@pytest.mark.skipif(IS_RASPBERRYPI, reason="Disabled for testing due to --slow test errors after YOLOE PR.") +@pytest.mark.parametrize( + "name, solution_class, needs_frame_count, video_key, kwargs_update", + [ + ( + "ObjectCounter", + solutions.ObjectCounter, + False, + "demo_video", + {"region": REGION, "model": MODEL, "show": SHOW}, + ), + ( + "ObjectCounter", + solutions.ObjectCounter, + False, + "demo_video", + {"region": HORIZONTAL_LINE, "model": MODEL, "show": SHOW}, + ), + ( + "ObjectCounterVertical", + solutions.ObjectCounter, + False, + "vertical_video", + {"region": VERTICAL_LINE, "model": MODEL, "show": SHOW}, + ), + ( + "ObjectCounterwithOBB", + solutions.ObjectCounter, + False, + "parking_video", # yolo26n-obb.pt yields no tracks on demo_video, so it would not exercise the OBB path + {"region": REGION, "model": "yolo26n-obb.pt", "show": SHOW}, + ), + ( + "Heatmap", + solutions.Heatmap, + False, + "demo_video", + {"colormap": cv2.COLORMAP_PARULA, "model": MODEL, "show": SHOW, "region": None}, + ), + ( + "HeatmapWithRegion", + solutions.Heatmap, + False, + "demo_video", + {"colormap": cv2.COLORMAP_PARULA, "region": REGION, "model": MODEL, "show": SHOW}, + ), + ( + "SpeedEstimator", + solutions.SpeedEstimator, + False, + "demo_video", + {"region": REGION, "model": MODEL, "show": SHOW}, + ), + ( + "QueueManager", + solutions.QueueManager, + False, + "demo_video", + {"region": REGION, "model": MODEL, "show": SHOW}, + ), + ( + "LineAnalytics", + solutions.Analytics, + True, + "demo_video", + {"analytics_type": "line", "model": MODEL, "show": SHOW, "figsize": (6.4, 3.2)}, + ), + ( + "PieAnalytics", + solutions.Analytics, + True, + "demo_video", + {"analytics_type": "pie", "model": MODEL, "show": SHOW, "figsize": (6.4, 3.2)}, + ), + ( + "BarAnalytics", + solutions.Analytics, + True, + "demo_video", + {"analytics_type": "bar", "model": MODEL, "show": SHOW, "figsize": (6.4, 3.2)}, + ), + ( + "AreaAnalytics", + solutions.Analytics, + True, + "demo_video", + {"analytics_type": "area", "model": MODEL, "show": SHOW, "figsize": (6.4, 3.2)}, + ), + ("TrackZone", solutions.TrackZone, False, "demo_video", {"region": REGION, "model": MODEL, "show": SHOW}), + ( + "ObjectCropper", + solutions.ObjectCropper, + False, + "crop_video", + {"temp_crop_dir": "cropped-detections", "model": MODEL, "show": SHOW}, + ), + ( + "ObjectBlurrer", + solutions.ObjectBlurrer, + False, + "demo_video", + {"blur_ratio": 0.02, "model": MODEL, "show": SHOW}, + ), + ( + "InstanceSegmentation", + solutions.InstanceSegmentation, + False, + "demo_video", + {"model": "yolo26n-seg.pt", "show": SHOW}, + ), + ("VisionEye", solutions.VisionEye, False, "demo_video", {"model": MODEL, "show": SHOW}), + ( + "RegionCounter", + solutions.RegionCounter, + False, + "demo_video", + {"region": REGION, "model": MODEL, "show": SHOW}, + ), + ("AIGym", solutions.AIGym, False, "pose_video", {"kpts": [6, 8, 10], "show": SHOW}), + ( + "ParkingManager", + solutions.ParkingManagement, + False, + "parking_video", + {"model": "parking_model", "show": SHOW, "json_file": "parking_areas"}, + ), + ( + "StreamlitInference", + solutions.Inference, + False, + None, # streamlit application doesn't require video file + {}, # streamlit application doesn't accept arguments + ), + ], +) +def test_solution(name, solution_class, needs_frame_count, video_key, kwargs_update, tmp_path, solution_assets): + """Test individual Ultralytics solution with video processing and parameter validation.""" + video_path = str(solution_assets(video_key)) if video_key else None + + kwargs = {} + for key, value in kwargs_update.items(): + if key.startswith("temp_"): + kwargs[key.replace("temp_", "")] = str(tmp_path / value) + elif value == "parking_model": + kwargs[key] = str(solution_assets("parking_model")) + elif value == "parking_areas": + kwargs[key] = str(solution_assets("parking_areas")) + else: + kwargs[key] = value + kwargs.setdefault("imgsz", 320) + + if name == "StreamlitInference": + if checks.check_imshow(): # do not merge with elif above + solution_class(**kwargs).inference() # requires interactive GUI environment + return + + process_video( + solution=solution_class(**kwargs), + video_path=video_path, + needs_frame_count=needs_frame_count, + ) + + +@pytest.mark.parametrize( + "region", + [[(220, 140), (420, 140), (420, 340), (220, 340)], [(20, 360), (1080, 360), (1080, 400), (20, 400)]], + ids=["square-zone", "wide-band"], +) +@pytest.mark.parametrize( + "step, expected", + [((8, 0), "IN"), ((-8, 0), "OUT"), ((0, 8), "IN"), ((0, -8), "OUT")], + ids=["left-to-right", "right-to-left", "downward", "upward"], +) +def test_object_counter_polygon_direction(region, step, expected): + """Polygonal counting must follow the object's motion axis regardless of the region's aspect ratio.""" + counter = solutions.ObjectCounter(region=region, show=False) + counter.initialize_region() + cx = sum(p[0] for p in region) / 4 + cy = sum(p[1] for p in region) / 4 + track = [(cx + (i - 5) * step[0], cy + (i - 5) * step[1]) for i in range(6)] # ends at region center + counter.track_history[1] = track + counter.count_objects(track[-1], 1, track[-2], 0) + counts = {"IN": counter.in_count, "OUT": counter.out_count} + assert counts[expected] == 1 and counts["IN" if expected == "OUT" else "OUT"] == 0, ( + f"step {step} into {region} expected {expected}, got in={counter.in_count} out={counter.out_count}" + ) + + +def test_object_counter_polygon_reversal_at_entry(): + """A track that backs away, turns around and then enters must be counted by its crossing motion.""" + counter = solutions.ObjectCounter(region=[(220, 140), (420, 140), (420, 340), (220, 340)], show=False) + counter.initialize_region() + # outside the right edge moving away (rightward), then reversing and entering leftward + xs = [428, 436, 444, 436, 428, 420, 412] # turn at x=444, entry at x=412 + track = [(float(x), 240.0) for x in xs] + for i in range(2, len(track) + 1): + counter.track_history[1] = track[:i] + counter.count_objects(track[i - 1], 1, track[i - 2], 0) + assert (counter.in_count, counter.out_count) == (0, 1), ( + f"entered moving left, expected OUT, got in={counter.in_count} out={counter.out_count}" + ) + + +def test_object_counter_polygon_reentry_after_inside_spawn(): + """A track spawning inside (uncounted first frame), exiting and re-entering counts by its crossing motion.""" + counter = solutions.ObjectCounter(region=[(220, 140), (420, 140), (420, 340), (220, 340)], show=False) + counter.initialize_region() + track = [(230.0, 240.0), (210.0, 240.0), (230.0, 240.0)] # inside -> out the left edge -> re-enter rightward + for i in range(1, len(track) + 1): + counter.track_history[1] = track[:i] + counter.count_objects(track[i - 1], 1, track[i - 2] if i > 1 else None, 0) + assert (counter.in_count, counter.out_count) == (1, 0), ( + f"re-entered moving right, expected IN, got in={counter.in_count} out={counter.out_count}" + ) + + +def test_left_click_selection(): + """Test distance calculation left click selection functionality.""" + dc = solutions.DistanceCalculation() + dc.boxes, dc.track_ids = [[10, 10, 50, 50]], [1] + dc.mouse_event_for_distance(cv2.EVENT_LBUTTONDOWN, 30, 30, None, None) + assert 1 in dc.selected_boxes, f"Expected track_id 1 in selected_boxes, got {dc.selected_boxes}" + + +def test_left_click_selection_obb(): + """Test distance calculation left click selection with (4, 2) OBB corner boxes.""" + dc = solutions.DistanceCalculation() + dc.boxes = [torch.tensor([[30.0, 10.0], [50.0, 30.0], [30.0, 50.0], [10.0, 30.0]])] # rotated box corners + dc.track_ids = [1] + dc.mouse_event_for_distance(cv2.EVENT_LBUTTONDOWN, 30, 30, None, None) + assert 1 in dc.selected_boxes, f"Expected track_id 1 in selected_boxes, got {dc.selected_boxes}" + + +@pytest.mark.skipif(IS_RASPBERRYPI, reason="Disabled for testing due to --slow test errors after YOLOE PR.") +@pytest.mark.parametrize( + "solution_class, extra_kwargs", + [ + (solutions.Heatmap, {"colormap": cv2.COLORMAP_PARULA, "region": None}), + (solutions.ObjectBlurrer, {"blur_ratio": 0.02}), + (solutions.VisionEye, {}), + (solutions.RegionCounter, {"region": REGION}), + (solutions.ParkingManagement, {"json_file": "parking_areas"}), + ], + ids=["Heatmap", "ObjectBlurrer", "VisionEye", "RegionCounter", "ParkingManagement"], +) +def test_solution_obb_boxes(solution_class, extra_kwargs, solution_assets): + """Regression: solutions consuming self.boxes must handle (4, 2) OBB corner boxes without crashing. + + OBB models fill self.boxes with (4, 2) corner points instead of xyxy scalars, and get_enclosing_box normalizes + them. A single parking_video frame already yields OBB tracks, so one frame exercises each crash site without + processing the whole video. Reuses the parking_video and yolo26n-obb.pt assets already in the test matrix. + """ + kwargs = {"model": "yolo26n-obb.pt", "show": SHOW, "imgsz": 320, **extra_kwargs} + if kwargs.get("json_file") == "parking_areas": + kwargs["json_file"] = str(solution_assets("parking_areas")) + cap = cv2.VideoCapture(str(solution_assets("parking_video"))) + success, im0 = cap.read() + cap.release() + assert success, "Failed to read first frame of parking_video" + results = solution_class(**kwargs)(im0) + assert results.plot_im is not None, f"{solution_class.__name__} returned no plot_im on OBB input" + + +def test_object_blurrer_obb_outside_frame(): + """An OBB box that clips fully outside the frame produces an empty ROI and must be skipped before cv2.blur.""" + blurrer = solutions.ObjectBlurrer() + frame = np.zeros((480, 640, 3), dtype=np.uint8) + inside = torch.tensor([[100.0, 100], [200, 100], [200, 200], [100, 200]]) # (4, 2) OBB, in frame + outside = torch.tensor([[700.0, 100], [760, 100], [760, 200], [700, 200]]) # (4, 2) OBB, fully off the right edge + blurrer.boxes, blurrer.clss, blurrer.confs, blurrer.track_ids = [inside, outside], [0, 0], [0.9, 0.9], [1, 2] + with patch.object(blurrer, "extract_tracks"), patch.object(blurrer, "display_output"): + results = blurrer.process(frame) + assert results.plot_im is not None + + +def test_right_click_reset(): + """Test distance calculation right click reset functionality.""" + dc = solutions.DistanceCalculation() + dc.selected_boxes, dc.left_mouse_count = {1: [10, 10, 50, 50]}, 1 + dc.mouse_event_for_distance(cv2.EVENT_RBUTTONDOWN, 0, 0, None, None) + assert not dc.selected_boxes, f"Expected empty selected_boxes after reset, got {dc.selected_boxes}" + assert dc.left_mouse_count == 0, f"Expected left_mouse_count=0 after reset, got {dc.left_mouse_count}" + + +def test_parking_json_none(): + """Test that ParkingManagement handles missing JSON gracefully.""" + im0 = np.zeros((640, 480, 3), dtype=np.uint8) + try: + parkingmanager = solutions.ParkingManagement(json_path=None) + parkingmanager(im0) + except ValueError: + pytest.skip("Skipping test due to missing JSON.") + + +def test_analytics_graph_not_supported(): + """Test that unsupported analytics type raises ValueError.""" + try: + analytics = solutions.Analytics(analytics_type="test") # 'test' is unsupported + analytics.process(im0=np.zeros((640, 480, 3), dtype=np.uint8), frame_number=0) + assert False, "Expected ValueError for unsupported chart type" + except ValueError as e: + assert "Unsupported analytics_type" in str(e), f"Expected 'Unsupported analytics_type' in error, got: {e}" + + +def test_area_chart_padding(): + """Test area chart graph update with dynamic class padding logic.""" + analytics = solutions.Analytics(analytics_type="area") + analytics.update_graph(frame_number=1, count_dict={"car": 2}, plot="area") + plot_im = analytics.update_graph(frame_number=2, count_dict={"car": 3, "person": 1}, plot="area") + assert plot_im is not None, "Area chart plot returned None" + + +def test_config_update_method_with_invalid_argument(): + """Test that update() raises ValueError for invalid config keys.""" + obj = solutions.config.SolutionConfig() + try: + obj.update(invalid_key=123) + assert False, "Expected ValueError for invalid update argument" + except ValueError as e: + assert "is not a valid solution argument" in str(e), f"Expected validation error message, got: {e}" + + +def test_plot_with_no_masks(): + """Test that instance segmentation handles cases with no masks.""" + im0 = np.zeros((640, 480, 3), dtype=np.uint8) + isegment = solutions.InstanceSegmentation(model="yolo26n-seg.pt") + results = isegment(im0) + assert results.plot_im is not None, "Instance segmentation plot returned None" + + +def test_streamlit_handle_video_upload_creates_file(tmp_path): + """Test Streamlit video upload logic saves file correctly.""" + import io + + fake_file = io.BytesIO(b"fake video content") + fake_file.read = fake_file.getvalue + if fake_file is not None: + g = io.BytesIO(fake_file.read()) + with open(tmp_path / "ultralytics.mp4", "wb") as out: + out.write(g.read()) + output_path = str(tmp_path / "ultralytics.mp4") + else: + output_path = None + assert output_path == str(tmp_path / "ultralytics.mp4"), ( + f"Expected output_path '{tmp_path / 'ultralytics.mp4'}', got {output_path}" + ) + assert os.path.exists(tmp_path / "ultralytics.mp4"), "ultralytics.mp4 file not created" + with open(tmp_path / "ultralytics.mp4", "rb") as f: + content = f.read() + assert content == b"fake video content", f"File content mismatch: {content}" + + +@pytest.mark.skipif(not TORCH_2_4, reason=f"VisualAISearch requires torch>=2.4 (found torch=={TORCH_VERSION})") +@pytest.mark.skipif(IS_RASPBERRYPI, reason="Disabled due to slow performance on Raspberry Pi.") +def test_similarity_search(tmp_path, solution_assets): + """Test similarity search solution with sample images and text query.""" + safe_download(solution_assets("similarity_images"), dir=tmp_path) # 4 dog images for testing in a zip file + searcher = solutions.VisualAISearch(data=str(tmp_path / "4-imgs-similaritysearch")) + _ = searcher("a dog sitting on a bench") # Returns the results in format "- img name | similarity score" + + +@pytest.mark.skipif(not TORCH_2_4, reason=f"VisualAISearch requires torch>=2.4 (found torch=={TORCH_VERSION})") +@pytest.mark.skipif(IS_RASPBERRYPI, reason="Disabled due to slow performance on Raspberry Pi.") +def test_similarity_search_app_init(): + """Test SearchApp initializes with required attributes.""" + app = solutions.SearchApp(device="cpu") + assert hasattr(app, "searcher") + assert hasattr(app, "run") + + +@pytest.mark.skipif(not TORCH_2_4, reason=f"VisualAISearch requires torch>=2.4 (found torch=={TORCH_VERSION})") +@pytest.mark.skipif(IS_RASPBERRYPI, reason="Disabled due to slow performance on Raspberry Pi.") +def test_similarity_search_complete(tmp_path): + """Test VisualAISearch end-to-end with sample images and query.""" + from PIL import Image + + image_dir = tmp_path / "images" + os.makedirs(image_dir, exist_ok=True) + for i in range(2): + img = Image.fromarray(np.uint8(np.random.rand(224, 224, 3) * 255)) + img.save(image_dir / f"test_image_{i}.jpg") + searcher = solutions.VisualAISearch(data=str(image_dir)) + results = searcher("a red and white object") + assert results, "Similarity search returned empty results" + + +def test_distance_calculation_process_method(): + """Test DistanceCalculation.process() computes distance between selected boxes.""" + from ultralytics.solutions.solutions import SolutionResults + + dc = solutions.DistanceCalculation() + dc.boxes, dc.track_ids, dc.clss, dc.confs = ( + [[100, 100, 200, 200], [300, 300, 400, 400]], + [1, 2], + [0, 0], + [0.9, 0.95], + ) + dc.selected_boxes = {1: dc.boxes[0], 2: dc.boxes[1]} + frame = np.zeros((480, 640, 3), dtype=np.uint8) + with patch.object(dc, "extract_tracks"), patch.object(dc, "display_output"), patch("cv2.setMouseCallback"): + result = dc.process(frame) + assert isinstance(result, SolutionResults), f"Expected SolutionResults, got {type(result)}" + assert result.total_tracks == 2, f"Expected 2 tracks, got {result.total_tracks}" + assert result.pixels_distance > 0, f"Expected positive distance, got {result.pixels_distance}" + + +def test_object_crop_with_show_True(): + """Test ObjectCropper init with show=True to cover display warning.""" + solutions.ObjectCropper(show=True) + + +def test_display_output_method(): + """Test that display_output triggers imshow, waitKey, and destroyAllWindows when enabled.""" + counter = solutions.ObjectCounter(show=True) + counter.env_check = True + frame = np.zeros((100, 100, 3), dtype=np.uint8) + with patch("cv2.imshow") as mock_imshow, patch("cv2.waitKey", return_value=ord("q")) as mock_wait, patch( + "cv2.destroyAllWindows" + ) as mock_destroy: + counter.display_output(frame) + mock_imshow.assert_called_once() + mock_wait.assert_called_once() + mock_destroy.assert_called_once() diff --git a/.venv/lib/python3.12/site-packages/thop/__init__.py b/.venv/lib/python3.12/site-packages/thop/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..628884467696ace9ccea9730a028904f563fcb8f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/thop/__init__.py @@ -0,0 +1,12 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +__version__ = "2.1.6" + +import torch + +from .profile import profile, profile_origin +from .utils import clever_format + +default_dtype = torch.float64 + +__all__ = ["clever_format", "default_dtype", "profile", "profile_origin"] diff --git a/.venv/lib/python3.12/site-packages/thop/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/thop/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d77127bc860b3798f924af51559d54ecfd06a254 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/thop/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/thop/__pycache__/profile.cpython-312.pyc b/.venv/lib/python3.12/site-packages/thop/__pycache__/profile.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..712655c8b46716fc1e2fe6ec710433d3b2fa130a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/thop/__pycache__/profile.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/thop/__pycache__/rnn_hooks.cpython-312.pyc b/.venv/lib/python3.12/site-packages/thop/__pycache__/rnn_hooks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6162f2212e56460b4571d70ce542a70f1c555708 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/thop/__pycache__/rnn_hooks.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/thop/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/thop/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b29be3b5380965d41b9a482933fa1e12ac119921 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/thop/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/thop/profile.py b/.venv/lib/python3.12/site-packages/thop/profile.py new file mode 100644 index 0000000000000000000000000000000000000000..1d622be05a5a51bd7d869ef000362aae6963a269 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/thop/profile.py @@ -0,0 +1,441 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import inspect + +from thop.rnn_hooks import ( + count_gru, + count_gru_cell, + count_lstm, + count_lstm_cell, + count_rnn, + count_rnn_cell, + torch, +) +from thop.vision.basic_hooks import ( + count_adap_avgpool, + count_avgpool, + count_bilinear, + count_convNd, + count_convtNd, + count_embedding, + count_linear, + count_multihead_attention, + count_normalization, + count_prelu, + count_softmax, + count_upsample, + logging, + nn, + zero_ops, +) + +from .utils import prRed +from .vision.calc_func import calculate_parameters + +default_dtype = torch.float64 + +# torch>=2.0 +_HOOK_TAKES_KWARGS = "with_kwargs" in inspect.signature(nn.Module.register_forward_hook).parameters + +register_hooks = { + # the padding and dropout families through the private base each shares, as the norm families below + # need for the same reason: naming the two concrete classes left their 10 siblings rule-less, so + # report_missing warned about layers that have nothing to count and taught the reader to ignore it + nn.modules.padding._ConstantPadNd: zero_ops, # padding does not involve any multiplication + nn.modules.padding._ReflectionPadNd: zero_ops, + nn.modules.padding._ReplicationPadNd: zero_ops, + nn.modules.dropout._DropoutNd: zero_ops, + nn.Conv1d: count_convNd, + nn.Conv2d: count_convNd, + nn.Conv3d: count_convNd, + nn.ConvTranspose1d: count_convtNd, + nn.ConvTranspose2d: count_convtNd, + nn.ConvTranspose3d: count_convtNd, + # the batch- and instance-norm families through the base they share, which count_normalization is + # already annotated for. A lazy norm needs the base: LazyBatchNorm2d derives from _BatchNorm, not + # from BatchNorm2d, so its concrete counterpart is a sibling and never appears in its MRO. + nn.modules.batchnorm._NormBase: count_normalization, + nn.LayerNorm: count_normalization, + nn.GroupNorm: count_normalization, + nn.PReLU: count_prelu, + # The softmax family shares no base, so each member is registered explicitly. + nn.Softmax: count_softmax, + nn.LogSoftmax: count_softmax, + nn.Softmin: count_softmax, + nn.Softmax2d: count_softmax, + nn.ReLU: zero_ops, + nn.ReLU6: zero_ops, + nn.LeakyReLU: zero_ops, + nn.MaxPool1d: zero_ops, + nn.MaxPool2d: zero_ops, + nn.MaxPool3d: zero_ops, + nn.AdaptiveMaxPool1d: zero_ops, + nn.AdaptiveMaxPool2d: zero_ops, + nn.AdaptiveMaxPool3d: zero_ops, + nn.FractionalMaxPool2d: zero_ops, # a max pool that picks its windows randomly still only selects + nn.FractionalMaxPool3d: zero_ops, + nn.modules.pooling._MaxUnpoolNd: zero_ops, # scattering into a larger zero tensor adds nothing + nn.AvgPool1d: count_avgpool, + nn.AvgPool2d: count_avgpool, + nn.AvgPool3d: count_avgpool, + nn.AdaptiveAvgPool1d: count_adap_avgpool, + nn.AdaptiveAvgPool2d: count_adap_avgpool, + nn.AdaptiveAvgPool3d: count_adap_avgpool, + nn.Linear: count_linear, + nn.Bilinear: count_bilinear, + nn.Upsample: count_upsample, + nn.UpsamplingBilinear2d: count_upsample, + nn.UpsamplingNearest2d: count_upsample, + nn.RNNCell: count_rnn_cell, + nn.GRUCell: count_gru_cell, + nn.LSTMCell: count_lstm_cell, + nn.RNN: count_rnn, + nn.GRU: count_gru, + nn.LSTM: count_lstm, + # containers hold children and compute nothing themselves; they share no base but nn.Module. + nn.Sequential: zero_ops, + nn.ModuleList: zero_ops, + nn.ModuleDict: zero_ops, + nn.ParameterList: zero_ops, + nn.ParameterDict: zero_ops, + # layers that only move elements around: a view, a re-index or a permutation reads and writes each + # element once and multiplies nothing. The elementwise activations that also reach no rule are left + # warned about on purpose, because registering one asserts it is free and SiLU, Mish, GELU, GLU and + # Hardswish each multiply per element, so they want formulas rather than a blanket entry. nn.Fold is + # out because it sums OVERLAPPING blocks, and an addition per input over a window is the work + # count_adap_avgpool charges rather than something a view does. + nn.Identity: zero_ops, + nn.Flatten: zero_ops, + nn.Unflatten: zero_ops, + nn.Unfold: zero_ops, + nn.PixelShuffle: zero_ops, + nn.PixelUnshuffle: zero_ops, + nn.ChannelShuffle: zero_ops, + # a gather, so it belongs with the block above, but max_norm keeps it out of a blanket zero: that rescale is + # real work and count_embedding warns rather than assert it away, the way count_upsample does for a mode it has + # no cost for. nn.EmbeddingBag stays unregistered, since it really does reduce each bag and how many adds that + # takes is not a function of shape either: padding_idx entries drop out and repeated offsets make empty bags. + nn.Embedding: count_embedding, +} + +if _HOOK_TAKES_KWARGS: + register_hooks[nn.MultiheadAttention] = count_multihead_attention + +if hasattr(nn, "RMSNorm"): # torch>=2.4, and its elementwise_affine flag is one count_normalization already reads + register_hooks[nn.RMSNorm] = count_normalization + +if hasattr(nn.modules.padding, "_CircularPadNd"): # torch>=2.1, which is where the CircularPad classes start + register_hooks[nn.modules.padding._CircularPadNd] = zero_ops + + +def _resolve_rule(m_type, custom_ops, types_collection, verbose, report_missing): + """Return the counting rule for a module type, or None when no ancestor of it carries one. + + The whole MRO is walked, most derived first, so a subclass of a supported type is counted by that type's rule + instead of being skipped, and a lazy module resolves through the class it derives from. custom_ops is consulted + ahead of the built-ins at every level, so a caller's own rule still wins. + """ + first_seen = m_type not in types_collection + for t in m_type.__mro__: + if t in custom_ops: # if defined in both op maps, custom_ops overwrites + fn = custom_ops[t] + if first_seen and verbose: + print(f"[INFO] Customize rule {getattr(fn, '__qualname__', fn)}() {m_type}.") + return fn + if t in register_hooks: + fn = register_hooks[t] + if first_seen and verbose: + print(f"[INFO] Register {getattr(fn, '__qualname__', fn)}() for {m_type}.") + return fn + if first_seen and report_missing: + prRed(f"[WARN] Cannot find rule for {m_type}. Treat it as zero Macs.") + return None + + +def _register_counter(m, fn, keep_result): + """Register a counting hook that receives positional and keyword arguments.""" + if _HOOK_TAKES_KWARGS: + + def counter(m, args, kwargs, y, fn=fn): + """Apply the counting rule to the arguments the module was called with.""" + result = fn(m, _positional(m, args, kwargs) if kwargs else args, y) + return result if keep_result else None + + return m.register_forward_hook(counter, with_kwargs=True) + + def counter(m, args, y, fn=fn): + """Apply the counting rule; this torch delivers no keyword arguments for it to be given.""" + result = fn(m, args, y) + return result if keep_result else None + + return m.register_forward_hook(counter) + + +def _positional(m, args, kwargs): + """Return supplied arguments in the order m.forward declares them.""" + try: + bound = inspect.signature(m.forward).bind(*args, **kwargs) + except (TypeError, ValueError): + return () + values = [] + for name, value in bound.arguments.items(): + kind = bound.signature.parameters[name].kind + if kind == inspect.Parameter.VAR_POSITIONAL: + values.extend(value) + elif kind != inspect.Parameter.VAR_KEYWORD: + values.append(value) + return tuple(values) + + +def _parents_first(roots): + """List reachable modules with every parent before its children.""" + order, seen = [], set() + + def visit(m): + seen.add(m) + for c in m.children(): + if c not in seen: + visit(c) + order.append(m) + + for root in roots: + if root not in seen: + visit(root) + order.reverse() + return order + + +def _displace_total_ops(m): + """Temporarily remove a caller-owned `total_ops` buffer or attribute; reject a name thop cannot borrow.""" + kind = None + if any(hasattr(vars(c).get("total_ops"), "__set__") for c in type(m).__mro__): + kind = "data descriptor" # no per-instance value to displace, and the hook's writes never reach the total + elif "total_ops" in m._parameters: + kind = "parameter" # displacing it would come back as a smaller parameter count + elif "total_ops" in m._modules: + kind = "child module" # displacing it would come back as a dropped subtree + if kind: + raise TypeError(f"{m!s} owns total_ops as a {kind}; thop needs that name to profile it.") + displaced = [(store, store["total_ops"]) for store in (m._buffers, m.__dict__) if "total_ops" in store] + if displaced: + logging.warning(f"{m!s} already has a .total_ops; it is shadowed while profiling and restored after.") + for store, _ in displaced: + del store["total_ops"] + return displaced + + +def _restore_modes(prev_training): + """Restore recorded modes without changing modules attached during forward.""" + order = _parents_first(prev_training) + modes = {m: prev_training.get(m, m.training) for m in order} # read before the first train() call moves any + for m, was_training in modes.items(): + if m.training != was_training: + m.train(was_training) + for m, was_training in modes.items(): + m.training = was_training + + +def profile_origin(model, inputs, custom_ops=None, verbose=True, report_missing=False): + """Profile a model with the legacy per-leaf-module traversal, returning total operations and parameters.""" + handler_collection = {} + displaced_collection = {} + types_collection = set() + if custom_ops is None: + custom_ops = {} + if report_missing: + verbose = True + + def add_hooks(m): + m_type = type(m) + has_own_rule = any(t in custom_ops or t in register_hooks for t in m_type.__mro__) + if (list(m.children()) and not has_own_rule) or m in handler_collection: + return + + fn = _resolve_rule(m_type, custom_ops, types_collection, verbose, report_missing) + + displaced = _displace_total_ops(m) + if displaced: + displaced_collection[m] = displaced + # register_buffer discards this flag; restore it without requiring the newer persistent= argument. + non_persistent = "total_ops" in m._non_persistent_buffers_set + m.register_buffer("total_ops", torch.zeros(1, dtype=default_dtype)) + if non_persistent: + m._non_persistent_buffers_set.add("total_ops") + handler_collection[m] = None + if fn is not None and fn is not zero_ops: + handler_collection[m] = _register_counter(m, fn, keep_result=True) # as profile_origin always has + types_collection.add(m_type) + + prev_training = {m: m.training for m in model.modules()} + + try: + model.eval() + model.apply(add_hooks) + + with torch.no_grad(): + model(*inputs) + + total_ops = 0 + for m in handler_collection: + total_ops += m.total_ops + + total_ops = total_ops.item() + total_params = float(calculate_parameters(model.parameters())) + finally: # no failure, at any stage, may leave behind the hooks or the buffers this call created + for handler in filter(None, handler_collection.values()): + handler.remove() + for m in handler_collection: + m._buffers.pop("total_ops", None) + for m, displaced in displaced_collection.items(): + for store, value in displaced: + store["total_ops"] = value + _restore_modes(prev_training) # last: it calls train(), which is the caller's code and may raise + + return total_ops, total_params + + +def profile( + model: nn.Module, + inputs, + custom_ops=None, + verbose=True, + ret_layer_info=False, + report_missing=False, + stride=None, +): + """Profiles a PyTorch model, optionally estimating target-image MACs from smaller stride-aligned inputs.""" + handler_collection = {} + displaced_collection = {} + types_collection = set() + if custom_ops is None: + custom_ops = {} + if report_missing: + # overwrite `verbose` option when enable report_missing + verbose = True + + def add_hooks(m: nn.Module): + """Registers a hook on a neural network module to track its total operations.""" + if m in handler_collection: # model.apply() revisits modules shared by several parents, e.g. a common act + return + + m_type = type(m) + fn = _resolve_rule(m_type, custom_ops, types_collection, verbose, report_missing) + + displaced = _displace_total_ops(m) + if displaced: + displaced_collection[m] = displaced + # a plain int attribute, not a float64 buffer: buffer reads go through nn.Module.__getattr__ and every + # hook would allocate a tensor per call, which dominates profiling cost on module-heavy models. + # Written straight into __dict__ (mirroring the teardown below) to skip nn.Module.__setattr__. + m.__dict__["total_ops"] = 0 + + handler_collection[m] = None + if fn is not None and fn is not zero_ops: + handler_collection[m] = _register_counter(m, fn, keep_result=False) # never the module output + types_collection.add(m_type) + + counted = set() + + def dfs_count(module: nn.Module, prefix="\t") -> (float, dict): + """Build layer details from the module tree left after forward.""" + total_ops = float(module.__dict__.get("total_ops", 0)) if module in handler_collection else 0.0 + ret_dict = {} + for n, m in module.named_children(): + # every child is walked, whether or not it carries a rule of its own: a rule accounts for its + # module's own arithmetic, not for its subtree's, so the two are added rather than one replacing + # the other. This is what the root of the traversal has always done with its own total_ops above + m_ops, next_dict = dfs_count(m, prefix=prefix + "\t") + if ret_layer_info: # the per-layer tree is the caller's opt-in, so it is not built when discarded + ret_dict[n] = (m_ops, float(calculate_parameters(m.parameters())), next_dict) + if m in counted: # a module reached through several parents already accumulated all of its calls + continue + counted.add(m) + total_ops += m_ops + # print(prefix, module._get_name(), total_ops) + return total_ops, ret_dict + + prev_training = {m: m.training for m in model.modules()} # per module: model.eval() below recurses + + try: + model.eval() + model.apply(add_hooks) + + def run(input_values): + """Profile one set of inputs while reusing the registered hooks.""" + counted.clear() + for m in handler_collection: + m.__dict__["total_ops"] = 0 + with torch.no_grad(): + model(*input_values) + # Count the executed hook record; build the surviving tree only when requested. + total = sum(float(m.__dict__.get("total_ops", 0)) for m in handler_collection) + return total, dfs_count(model)[1] if ret_layer_info else {} + + if stride is None or ret_layer_info: + total_ops, ret_dict = run(inputs) + else: + if len(inputs) != 1 or not isinstance(inputs[0], torch.Tensor) or inputs[0].ndim != 4: + raise ValueError("stride requires inputs to contain one BCHW image tensor") + stride = (stride, stride) if isinstance(stride, int) else tuple(stride) + if len(stride) != 2 or min(stride) < 1: + raise ValueError("stride must be a positive integer or a pair of positive integers") + + image = inputs[0] + target_height, target_width = image.shape[-2:] + fixed_ops = ( + nn.Linear, + nn.AdaptiveAvgPool1d, + nn.AdaptiveAvgPool2d, + nn.AdaptiveAvgPool3d, + nn.RNNBase, + nn.RNNCell, + nn.GRUCell, + nn.LSTMCell, + ) + required_samples = 2 if any(isinstance(m, fixed_ops) for m in model.modules()) else 1 + samples = [] + proxy_area = stride[0] * stride[1] + if ( + # two small samples can only fit a cost that is affine in image area. Attention is quadratic in it, + # and a caller's own rule may be anything at all, so a model carrying either is measured directly. + not any( + isinstance(m, nn.MultiheadAttention) or any(t in custom_ops for t in type(m).__mro__) + for m in model.modules() + ) + and target_height % stride[0] == target_width % stride[1] == 0 + and proxy_area < target_height * target_width + ): + try: + for width in (stride[1], stride[1] * 2)[:required_samples]: + ops, _ = run((image.new_empty((*image.shape[:-2], stride[0], width)),)) + samples.append((stride[0] * width, ops)) + except Exception: + samples.clear() + + if len(samples) == 2: + (area1, ops1), (area2, ops2) = samples + slope = (ops2 - ops1) / (area2 - area1) + total_ops = slope * target_height * target_width + ops1 - slope * area1 + ret_dict = {} + elif len(samples) == 1 and required_samples == 1: + area, ops = samples[0] + total_ops = ops * target_height * target_width / area + ret_dict = {} + else: + total_ops, ret_dict = run(inputs) + # Parameters belong to the module tree, not to the traced call. parameters() deduplicates shared tensors + # and includes unsupported or unexecuted modules. + total_params = float(calculate_parameters(model.parameters())) + finally: # no failure, at any stage, may leave behind hooks or temporary attributes + for handler in filter(None, handler_collection.values()): + handler.remove() + for m in handler_collection: + m.__dict__.pop("total_ops", None) + for m, displaced in displaced_collection.items(): + for store, value in displaced: + store["total_ops"] = value + _restore_modes(prev_training) # last: it calls train(), which is the caller's code and may raise + + if ret_layer_info: + return total_ops, total_params, ret_dict + return total_ops, total_params diff --git a/.venv/lib/python3.12/site-packages/thop/rnn_hooks.py b/.venv/lib/python3.12/site-packages/thop/rnn_hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..9e3cb67c859aa159293a8bb1456f5b7c9e3b40e9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/thop/rnn_hooks.py @@ -0,0 +1,179 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import torch +from torch import nn +from torch.nn.utils.rnn import PackedSequence + + +def _cell_evaluations(x): + """Return how many cell evaluations a recurrent layer's input asks for.""" + if isinstance(x, PackedSequence): + return int(x.batch_sizes.sum()) # the padded rectangle is the work packing exists to avoid + return x.size(0) if x.dim() == 2 else x.size(0) * x.size(1) # unbatched (L, H_in) carries no batch axis + + +def _count_rnn_cell(input_size, hidden_size, bias=True): + """Calculate the total operations for an RNN cell given input size, hidden size, and optional bias.""" + total_ops = hidden_size * (input_size + hidden_size) + hidden_size + if bias: + total_ops += hidden_size * 2 + + return total_ops + + +def count_rnn_cell(m: nn.RNNCell, x: torch.Tensor, y: torch.Tensor): + """Counts the total RNN cell operations based on input tensor, hidden size, bias, and batch size.""" + total_ops = _count_rnn_cell(m.input_size, m.hidden_size, m.bias) + + # a cell takes one vector per batch entry, so a 1-dimensional input is a single unbatched sample + total_ops *= x[0].size(0) if x[0].dim() == 2 else 1 + + m.total_ops += int(total_ops) + + +def _count_gru_cell(input_size, hidden_size, bias=True): + """Counts the total operations for a GRU cell based on input size, hidden size, and bias configuration.""" + total_ops = 0 + # r = \sigma(W_{ir} x + b_{ir} + W_{hr} h + b_{hr}) \\ + # z = \sigma(W_{iz} x + b_{iz} + W_{hz} h + b_{hz}) \\ + state_ops = (hidden_size + input_size) * hidden_size + hidden_size + if bias: + state_ops += hidden_size * 2 + total_ops += state_ops * 2 + + # n = \tanh(W_{in} x + b_{in} + r * (W_{hn} h + b_{hn})) \\ + total_ops += (hidden_size + input_size) * hidden_size + hidden_size + if bias: + total_ops += hidden_size * 2 + # r hadamard : r * (~) + total_ops += hidden_size + + # h' = (1 - z) * n + z * h + # hadamard hadamard add + total_ops += hidden_size * 3 + + return total_ops + + +def count_gru_cell(m: nn.GRUCell, x: torch.Tensor, y: torch.Tensor): + """Calculates and updates the total operations for a GRU cell in a mini-batch during inference.""" + total_ops = _count_gru_cell(m.input_size, m.hidden_size, m.bias) + + # a cell takes one vector per batch entry, so a 1-dimensional input is a single unbatched sample + total_ops *= x[0].size(0) if x[0].dim() == 2 else 1 + + m.total_ops += int(total_ops) + + +def _count_lstm_cell(input_size, hidden_size, bias=True, proj_size=0): + """Counts LSTM cell operations during inference based on input size, hidden size, and bias configuration.""" + total_ops = 0 + real_hidden_size = proj_size or hidden_size # what the recurrent matmuls read, torch's own name for it + + # i = \sigma(W_{ii} x + b_{ii} + W_{hi} h + b_{hi}) \\ + # f = \sigma(W_{if} x + b_{if} + W_{hf} h + b_{hf}) \\ + # o = \sigma(W_{io} x + b_{io} + W_{ho} h + b_{ho}) \\ + # g = \tanh(W_{ig} x + b_{ig} + W_{hg} h + b_{hg}) \\ + state_ops = (input_size + real_hidden_size) * hidden_size + hidden_size + if bias: + state_ops += hidden_size * 2 + total_ops += state_ops * 4 + + # c' = f * c + i * g \\ + # hadamard hadamard add + total_ops += hidden_size * 3 + + # h' = W_{hr} (o * \tanh(c')) \\ + total_ops += hidden_size + hidden_size * proj_size + + return total_ops + + +def count_lstm_cell(m: nn.LSTMCell, x: torch.Tensor, y: torch.Tensor): + """Counts and updates the total operations for an LSTM cell in a mini-batch during inference.""" + total_ops = _count_lstm_cell(m.input_size, m.hidden_size, m.bias) + + # a cell takes one vector per batch entry, so a 1-dimensional input is a single unbatched sample + total_ops *= x[0].size(0) if x[0].dim() == 2 else 1 + + m.total_ops += int(total_ops) + + +def count_rnn(m: nn.RNN, x, y): + """Calculate and update the total number of operations for each RNN cell in a given batch.""" + bias = m.bias + input_size = m.input_size + hidden_size = m.hidden_size + num_layers = m.num_layers + + evaluations = _cell_evaluations(x[0]) + + total_ops = 0 + if m.bidirectional: + total_ops += _count_rnn_cell(input_size, hidden_size, bias) * 2 + else: + total_ops += _count_rnn_cell(input_size, hidden_size, bias) + + for _ in range(num_layers - 1): + total_ops += ( + _count_rnn_cell(hidden_size * 2, hidden_size, bias) * 2 + if m.bidirectional + else _count_rnn_cell(hidden_size, hidden_size, bias) + ) + total_ops *= evaluations + + m.total_ops += int(total_ops) + + +def count_gru(m: nn.GRU, x, y): + """Calculates total operations for a GRU layer, updating the model's operation count based on batch size.""" + bias = m.bias + input_size = m.input_size + hidden_size = m.hidden_size + num_layers = m.num_layers + + evaluations = _cell_evaluations(x[0]) + + total_ops = 0 + if m.bidirectional: + total_ops += _count_gru_cell(input_size, hidden_size, bias) * 2 + else: + total_ops += _count_gru_cell(input_size, hidden_size, bias) + + for _ in range(num_layers - 1): + total_ops += ( + _count_gru_cell(hidden_size * 2, hidden_size, bias) * 2 + if m.bidirectional + else _count_gru_cell(hidden_size, hidden_size, bias) + ) + total_ops *= evaluations + + m.total_ops += int(total_ops) + + +def count_lstm(m: nn.LSTM, x, y): + """Calculate total operations for LSTM layers, including bidirectional, updating model's total operations.""" + bias = m.bias + input_size = m.input_size + hidden_size = m.hidden_size + num_layers = m.num_layers + proj_size = m.proj_size + stacked_size = proj_size or hidden_size # the width a projected layer hands the next one + + evaluations = _cell_evaluations(x[0]) + + total_ops = 0 + if m.bidirectional: + total_ops += _count_lstm_cell(input_size, hidden_size, bias, proj_size) * 2 + else: + total_ops += _count_lstm_cell(input_size, hidden_size, bias, proj_size) + + for _ in range(num_layers - 1): + total_ops += ( + _count_lstm_cell(stacked_size * 2, hidden_size, bias, proj_size) * 2 + if m.bidirectional + else _count_lstm_cell(stacked_size, hidden_size, bias, proj_size) + ) + total_ops *= evaluations + + m.total_ops += int(total_ops) diff --git a/.venv/lib/python3.12/site-packages/thop/utils.py b/.venv/lib/python3.12/site-packages/thop/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..76765359664ea976ad1479c38921816eaa1bf7f3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/thop/utils.py @@ -0,0 +1,48 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from collections.abc import Iterable + +COLOR_RED = "91m" +COLOR_GREEN = "92m" +COLOR_YELLOW = "93m" + + +def colorful_print(fn_print, color=COLOR_RED): + """A decorator to print text in the specified terminal color by wrapping the given print function.""" + + def actual_call(*args, **kwargs): + print(f"\033[{color}", end="") + fn_print(*args, **kwargs) + print("\033[00m", end="") + + return actual_call + + +prRed = colorful_print(print, color=COLOR_RED) +prGreen = colorful_print(print, color=COLOR_GREEN) +prYellow = colorful_print(print, color=COLOR_YELLOW) + + +def clever_format(nums, format="%.2f"): + """Formats numbers into human-readable strings with units (K for thousand, M for million, etc.).""" + if not isinstance(nums, Iterable): + nums = [nums] + clever_nums = [] + + for num in nums: + for unit, scale in (("T", 1e12), ("G", 1e9), ("M", 1e6), ("K", 1e3)): + # abs() and >=, not the value against >: a negative satisfied no comparison and came out unscaled, + # and an exact power of 1000 belongs to the unit it is one of rather than to the one below it + if abs(num) >= scale: + clever_nums.append(format % (num / scale) + unit) + break + else: + clever_nums.append(format % num + "B") + + return clever_nums[0] if len(clever_nums) == 1 else (*clever_nums,) + + +if __name__ == "__main__": + prRed("hello", "world") + prGreen("hello", "world") + prYellow("hello", "world") diff --git a/.venv/lib/python3.12/site-packages/thop/vision/__init__.py b/.venv/lib/python3.12/site-packages/thop/vision/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..77a19dcf0f8093de419453747db2e7e719f96349 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/thop/vision/__init__.py @@ -0,0 +1 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license diff --git a/.venv/lib/python3.12/site-packages/thop/vision/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/thop/vision/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc20e444d727e37526110e5b512909d524571597 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/thop/vision/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/thop/vision/__pycache__/basic_hooks.cpython-312.pyc b/.venv/lib/python3.12/site-packages/thop/vision/__pycache__/basic_hooks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..395ef19efb21eb60c6f8e2bb0b94a7a1f585eee4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/thop/vision/__pycache__/basic_hooks.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/thop/vision/__pycache__/calc_func.cpython-312.pyc b/.venv/lib/python3.12/site-packages/thop/vision/__pycache__/calc_func.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a2a6af241a34d700c3f0bec4fcad2d093376b7c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/thop/vision/__pycache__/calc_func.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/thop/vision/basic_hooks.py b/.venv/lib/python3.12/site-packages/thop/vision/basic_hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..0d8b0f2943b81e7cf242e6377531bd2735561315 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/thop/vision/basic_hooks.py @@ -0,0 +1,205 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +import logging + +import torch +from torch import nn +from torch.nn.modules.conv import _ConvNd + +from thop.vision.calc_func import ( + calculate_conv2d_flops, + calculate_linear, + calculate_norm, + calculate_softmax, + calculate_zero_ops, + l_prod, +) + +multiply_adds = 1 + + +def zero_ops(m, x, y): + """Incrementally add zero operations to the model's total operations count.""" + m.total_ops += calculate_zero_ops() + + +def count_embedding(m, x, y): + """Charge nothing for an embedding gather, warning when max_norm makes that incomplete.""" + if m.max_norm is not None: # it renormalizes only the rows the indices push over the limit, so data decides + logging.getLogger(__name__).warning("max_norm renormalization is not counted") + + +def count_convNd(m: _ConvNd, x, y: torch.Tensor): + """Calculate and add the number of convolutional operations (FLOPs) for a ConvNd layer to the model's total ops.""" + x = x[0] + + m.total_ops += calculate_conv2d_flops( + input_size=list(x.shape), + output_size=list(y.shape), + kernel_size=list(m.weight.shape), + groups=m.groups, + bias=m.bias, + transpose=False, + ) + # N x Cout x H x W x (Cin x Kw x Kh + bias) + # m.total_ops += calculate_conv( + # bias_ops, + # torch.zeros(m.weight.size()[2:]).numel(), + # y.nelement(), + # m.in_channels, + # m.groups, + # ) + + +def count_convtNd(m: _ConvNd, x, y: torch.Tensor): + """Calculate and add the number of convolutional operations (FLOPs) for a ConvNd layer to the model's total ops.""" + x = x[0] + + m.total_ops += calculate_conv2d_flops( + input_size=list(x.shape), + output_size=list(y.shape), + kernel_size=list(m.weight.shape), + groups=m.groups, + bias=m.bias, + transpose=True, + ) + + +def count_normalization(m: nn.modules.batchnorm._BatchNorm, x, y): + """Calculate and add the FLOPs for a batch normalization layer, including elementwise and affine operations.""" + # https://github.com/Lyken17/pytorch-OpCounter/issues/124 + # y = (x - mean) / sqrt(eps + var) * weight + bias + x = x[0] + # bn is by default fused in inference + flops = calculate_norm(x.numel()) + if getattr(m, "affine", False) or getattr(m, "elementwise_affine", False): + flops *= 2 + m.total_ops += flops + + +# def count_layer_norm(m, x, y): +# x = x[0] +# m.total_ops += calculate_norm(x.numel()) + + +# def count_instance_norm(m, x, y): +# x = x[0] +# m.total_ops += calculate_norm(x.numel()) + + +def count_prelu(m, x, y): + """Calculate and update the total operation counts for a PReLU layer using input element number.""" + x = x[0] + + if not m.training: + m.total_ops += x.numel() + + +def count_softmax(m, x, y): + """Calculate and update the total operation counts for a Softmax layer in a PyTorch model.""" + x = x[0] + # Softmax2d always normalizes channels, with or without a batch dimension. + dim = -3 if isinstance(m, nn.Softmax2d) else m.dim + if dim is None: + # Match torch's deprecated implicit dimension. + dim = 0 if x.dim() in {0, 1, 3} else 1 + # a scalar normalizes over itself, which no shape entry can say: torch returns 1.0 for it, so the cost is + # the one exponential and the one division that produce that, and indexing the empty shape only raises + nfeatures = x.size()[dim] if x.dim() else 1 + batch_size = x.numel() // nfeatures if nfeatures else 0 + + m.total_ops += calculate_softmax(batch_size, nfeatures) + if isinstance(m, nn.Softmin): + m.total_ops += x.numel() + elif isinstance(m, nn.LogSoftmax): + m.total_ops += batch_size + + +def count_avgpool(m, x, y): + """Calculate and update the total operation count for an AvgPool layer.""" + kernel = m.kernel_size + if isinstance(kernel, int): # only AvgPool2d and AvgPool3d keep it as passed, AvgPool1d normalizes to a tuple + kernel = (kernel,) * (3 if isinstance(m, nn.AvgPool3d) else 2) + dims = len(kernel) + stride = (m.stride,) * dims if isinstance(m.stride, int) else m.stride + padding = (m.padding,) * dims if isinstance(m.padding, int) else m.padding + windows = 1 + for size, output, k, s, p in zip(x[0].shape[-dims:], y.shape[-dims:], kernel, stride, padding): + lower, upper = (-p, size + p) if m.count_include_pad else (0, size) + windows *= sum(max(min(i * s - p + k, upper) - max(i * s - p, lower), 0) for i in range(output)) + m.total_ops += l_prod(x[0].shape[:-dims]) * windows + y.numel() # one add per input, one divide per output + + +def count_adap_avgpool(m, x, y): + """Calculate and update the total operation counts for an AdaptiveAvgPool layer from the windows it pools.""" + # the windows nn.AdaptiveAvgPool* actually slices, per dimension: output j spans + # [j * I // O, ceil((j + 1) * I / O)), so their sizes are integral and unequal whenever O does not divide I. + # The input-over-output ratio this replaced was a float, which made total_ops fractional, and it was also + # smaller than the window it stood for. + # Every axis is walked, not only the pooled ones: an axis the layer leaves alone has one input per output, so + # it contributes its own length and the batch and channel counts fall out of the same product. That is what + # the pooled-axes slice had to multiply back by hand, and it needs no batch axis to be there to slice off. + m.total_ops += ( + l_prod( + o if i == o else sum(-(-(j + 1) * i // o) - j * i // o for j in range(o)) + for i, o in zip(x[0].shape, y.shape) + ) + + y.numel() + ) # one add per pooled input, one divide per output + + +# TODO: verify the accuracy +def count_upsample(m, x, y): + """Update total operations counter for upsampling layers based on the mode used.""" + ops_per_element = { + "nearest": 0, + "nearest-exact": 0, + "linear": 5, + "bilinear": 11, + "bicubic": 259, + "trilinear": 31, + }.get(m.mode) + if ops_per_element is None: # one lookup owns both the cost and whether the mode has one at all + logging.getLogger(__name__).warning(f"mode {m.mode} is not implemented yet, take it a zero op") + ops_per_element = 0 + m.total_ops += ops_per_element * y.nelement() + + +# nn.Linear +def count_linear(m, x, y): + """Counts total operations for nn.Linear layers using input and output element dimensions.""" + total_mul = m.in_features + # total_add = m.in_features - 1 + # total_add += 1 if m.bias is not None else 0 + num_elements = y.numel() + + m.total_ops += calculate_linear(total_mul, num_elements) + + +def count_bilinear(m, x, y): + """Count both contractions of each bilinear output.""" + m.total_ops += calculate_linear((m.in1_features + 1) * m.in2_features, y.numel()) + + +def count_multihead_attention(m: nn.MultiheadAttention, x, y): + """Count projections, attention matrix products, and softmax. + + MultiheadAttention calls its projection weights functionally, so none of this work reaches a child-module hook. + Returned weights reveal appended key positions; calls that suppress them fall back to the key input. + """ + out, weights = y if isinstance(y, tuple) else (y, None) + batch_first = getattr(m, "batch_first", False) # added in torch 1.9; before it the layout is always (L, N, E) + tgt_len = out.shape[-2] if batch_first or out.dim() == 2 else out.shape[0] + batch_size = 1 if out.dim() == 2 else out.shape[0 if batch_first else 1] + appended = (m.bias_k is not None) + m.add_zero_attn # each adds one key position, after the projections have run + if weights is not None: + attended = weights.shape[-1] + else: + key = x[1] + attended = (key.shape[-2] if batch_first or key.dim() == 2 else key.shape[0]) + appended + + # Heads sum to embed_dim across both attention matrix products, so num_heads only multiplies the softmax rows. + projections = m.embed_dim * (2 * tgt_len * m.embed_dim + (attended - appended) * (m.kdim + m.vdim)) + attention = 2 * tgt_len * attended * m.embed_dim + softmax = calculate_softmax(batch_size * m.num_heads * tgt_len, attended) + m.total_ops += batch_size * (projections + attention) + softmax diff --git a/.venv/lib/python3.12/site-packages/thop/vision/calc_func.py b/.venv/lib/python3.12/site-packages/thop/vision/calc_func.py new file mode 100644 index 0000000000000000000000000000000000000000..01fbe7100f688fc81e95a990ca5857278239d56b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/thop/vision/calc_func.py @@ -0,0 +1,53 @@ +# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license + +from torch.nn.parameter import UninitializedParameter + + +def l_prod(in_list): + """Compute the product of all elements in the input list.""" + res = 1 + for _ in in_list: + res *= _ + return res + + +def calculate_parameters(param_list): + """Sum the element counts of an iterable of parameters, skipping any a lazy module has not created yet.""" + # a lazy module's parameters hold no elements until its first forward pass, and asking one for its + # element count raises rather than answering 0, so they are skipped instead of being counted. + # isinstance rather than torch.nn.parameter.is_lazy: that helper only exists from torch 1.9 on + return sum(p.nelement() for p in param_list if not isinstance(p, UninitializedParameter)) + + +def calculate_zero_ops(): + """Return the zero operation count.""" + return 0 + + +def calculate_conv2d_flops( + input_size: list, output_size: list, kernel_size: list, groups: int, bias: bool = False, transpose: bool = False +): + """Calculate FLOPs for a ConvNd layer using input/output sizes, kernel size, groups, and the bias flag.""" + # A transpose scatters rather than gathers, so it walks the input and takes its channel from the output. + volume, channels = (input_size, output_size) if transpose else (output_size, input_size) + # The channel axis is counted from the trailing end, so unbatched input lands on it too. + return l_prod(volume) * (channels[-(len(kernel_size) - 1)] // groups) * l_prod(kernel_size[2:]) + + +def calculate_norm(input_size): + """Compute the L2 norm of a tensor or array based on its input size.""" + return 2 * input_size + + +def calculate_softmax(batch_size, nfeatures): + """Compute FLOPs for a softmax activation given batch size and feature count.""" + total_exp = nfeatures + total_add = max(nfeatures - 1, 0) # normalizing an empty axis costs nothing, rather than one negative addition + total_div = nfeatures + total_ops = batch_size * (total_exp + total_add + total_div) + return int(total_ops) + + +def calculate_linear(in_feature, num_elements): + """Calculate the linear operation count for given input feature and number of elements.""" + return int(in_feature * num_elements) diff --git a/.venv/lib/python3.12/site-packages/torch/_C.cpython-312-x86_64-linux-gnu.so b/.venv/lib/python3.12/site-packages/torch/_C.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..a30c4bf779868837477b3834d4028da56406760d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_C.cpython-312-x86_64-linux-gnu.so differ diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_VariableFunctions.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_VariableFunctions.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2206a7e4093629d183276c42bfb015b061af3536 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_VariableFunctions.pyi @@ -0,0 +1,31270 @@ +# @generated by tools/pyi/gen_pyi.py from torch/_C/_VariableFunctions.pyi.in +# mypy: disable-error-code="type-arg" +# mypy: allow-untyped-defs +# ruff: noqa: F401,PYI054 + +from collections.abc import Callable, Sequence +from types import EllipsisType +from typing import Any, Literal, overload, TypeVar + +import torch +from torch import ( + contiguous_format, + Generator, + inf, + memory_format, + strided, + SymInt, + Tensor, +) +from torch._prims_common import DeviceLikeType +from torch.types import ( + _bool, + _complex, + _device, + _dtype, + _float, + _int, + _layout, + _qscheme, + _size, + Device, + Number, + PySymType, +) + +__all__ = [ + "__and__", + "__lshift__", + "__or__", + "__rshift__", + "__xor__", + "_adaptive_avg_pool2d", + "_adaptive_avg_pool3d", + "_add_batch_dim", + "_add_relu", + "_add_relu_", + "_addmm_activation", + "_aminmax", + "_amp_foreach_non_finite_check_and_unscale_", + "_amp_update_scale_", + "_assert_async", + "_assert_scalar", + "_assert_tensor_metadata", + "_batch_norm_impl_index", + "_cast_Byte", + "_cast_Char", + "_cast_Double", + "_cast_Float", + "_cast_Half", + "_cast_Int", + "_cast_Long", + "_cast_Short", + "_choose_qparams_per_tensor", + "_chunk_cat", + "_coalesce", + "_compute_linear_combination", + "_conj", + "_conj_copy", + "_conj_physical", + "_convert_indices_from_coo_to_csr", + "_convert_indices_from_csr_to_coo", + "_convert_weight_to_int4pack", + "_convert_weight_to_int4pack_for_cpu", + "_convolution", + "_convolution_mode", + "_copy_from", + "_copy_from_and_resize", + "_cslt_compress", + "_cslt_sparse_mm", + "_cslt_sparse_mm_search", + "_ctc_loss", + "_cudnn_ctc_loss", + "_cudnn_init_dropout_state", + "_cudnn_rnn", + "_cudnn_rnn_flatten_weight", + "_cufft_clear_plan_cache", + "_cufft_get_plan_cache_max_size", + "_cufft_get_plan_cache_size", + "_cufft_set_plan_cache_max_size", + "_cummax_helper", + "_cummin_helper", + "_debug_has_internal_overlap", + "_dim_arange", + "_dirichlet_grad", + "_disable_functionalization", + "_dyn_quant_matmul_4bit", + "_dyn_quant_pack_4bit_weight", + "_efficientzerotensor", + "_embedding_bag", + "_embedding_bag_forward_only", + "_empty_affine_quantized", + "_empty_per_channel_affine_quantized", + "_enable_functionalization", + "_euclidean_dist", + "_fake_quantize_learnable_per_channel_affine", + "_fake_quantize_learnable_per_tensor_affine", + "_fake_quantize_per_tensor_affine_cachemask_tensor_qparams", + "_fft_c2c", + "_fft_c2r", + "_fft_r2c", + "_fill_mem_eff_dropout_mask_", + "_flash_attention_forward_no_dropout_inplace", + "_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_clone", + "_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_mm", + "_foreach_mul", + "_foreach_mul_", + "_foreach_neg", + "_foreach_neg_", + "_foreach_norm", + "_foreach_pow", + "_foreach_pow_", + "_foreach_powsum", + "_foreach_reciprocal", + "_foreach_reciprocal_", + "_foreach_round", + "_foreach_round_", + "_foreach_rsqrt", + "_foreach_rsqrt_", + "_foreach_sigmoid", + "_foreach_sigmoid_", + "_foreach_sign", + "_foreach_sign_", + "_foreach_sin", + "_foreach_sin_", + "_foreach_sinh", + "_foreach_sinh_", + "_foreach_sqrt", + "_foreach_sqrt_", + "_foreach_sub", + "_foreach_sub_", + "_foreach_tan", + "_foreach_tan_", + "_foreach_tanh", + "_foreach_tanh_", + "_foreach_trunc", + "_foreach_trunc_", + "_foreach_zero_", + "_from_functional_tensor", + "_functional_assert_async", + "_functional_assert_scalar", + "_functional_sym_constrain_range", + "_functional_sym_constrain_range_for_size", + "_functionalize_apply_view_metas", + "_functionalize_are_all_mutations_hidden_from_autograd", + "_functionalize_are_all_mutations_under_no_grad_or_inference_mode", + "_functionalize_commit_update", + "_functionalize_has_metadata_mutation", + "_functionalize_inductor_storage_resized_counter", + "_functionalize_is_symbolic", + "_functionalize_mark_mutation_hidden_from_autograd", + "_functionalize_mark_storage_changed", + "_functionalize_mutation_counter", + "_functionalize_replace", + "_functionalize_storage_changed_counter", + "_functionalize_sync", + "_functionalize_unsafe_set", + "_functionalize_was_inductor_storage_resized", + "_functionalize_was_storage_changed", + "_fused_adagrad_", + "_fused_adam_", + "_fused_adamw_", + "_fused_dropout", + "_fused_moving_avg_obs_fq_helper", + "_fused_rms_norm", + "_fused_sdp_choice", + "_fused_sgd_", + "_fw_primal_copy", + "_grid_sampler_2d_cpu_fallback", + "_grouped_mm", + "_has_compatible_shallow_copy_type", + "_histogramdd_bin_edges", + "_histogramdd_from_bin_cts", + "_histogramdd_from_bin_tensors", + "_index_put_impl_", + "_indices_copy", + "_int_mm", + "_is_all_true", + "_is_any_true", + "_is_functional_tensor", + "_is_functional_tensor_base", + "_is_zerotensor", + "_lazy_clone", + "_linalg_check_errors", + "_linalg_det", + "_linalg_eigh", + "_linalg_slogdet", + "_linalg_solve_ex", + "_linalg_svd", + "_log_softmax", + "_log_softmax_backward_data", + "_logcumsumexp", + "_lstm_mps", + "_lu_with_info", + "_make_dep_token", + "_make_dual", + "_make_dual_copy", + "_make_per_channel_quantized_tensor", + "_make_per_tensor_quantized_tensor", + "_masked_scale", + "_masked_softmax", + "_mixed_dtypes_linear", + "_mkldnn_reshape", + "_mkldnn_transpose", + "_mkldnn_transpose_", + "_mps_convolution", + "_mps_convolution_transpose", + "_native_batch_norm_legit", + "_native_batch_norm_legit_no_training", + "_native_multi_head_attention", + "_neg_view", + "_neg_view_copy", + "_nested_compute_contiguous_strides_offsets", + "_nested_from_padded", + "_nested_from_padded_and_nested_example", + "_nested_from_padded_tensor", + "_nested_get_jagged_dummy", + "_nested_get_lengths", + "_nested_get_max_seqlen", + "_nested_get_min_seqlen", + "_nested_get_offsets", + "_nested_get_ragged_idx", + "_nested_get_values", + "_nested_get_values_copy", + "_nested_tensor_from_mask", + "_nested_tensor_from_mask_left_aligned", + "_nested_tensor_from_tensor_list", + "_nested_tensor_softmax_with_shape", + "_nested_view_from_buffer", + "_nested_view_from_buffer_copy", + "_nested_view_from_jagged", + "_nested_view_from_jagged_copy", + "_nnpack_available", + "_nnpack_spatial_convolution", + "_pack_padded_sequence", + "_pad_packed_sequence", + "_philox_key_fold_in", + "_philox_key_split", + "_philox_normal_", + "_philox_uniform_", + "_pin_memory", + "_prelu_kernel", + "_print", + "_propagate_xla_data", + "_remove_batch_dim", + "_reshape_alias_copy", + "_reshape_from_tensor", + "_resize_output_", + "_rowwise_prune", + "_safe_softmax", + "_sample_dirichlet", + "_saturate_weight_to_fp16", + "_scaled_dot_product_attention_math", + "_scaled_dot_product_attention_math_for_mps", + "_scaled_dot_product_cudnn_attention", + "_scaled_dot_product_efficient_attention", + "_scaled_dot_product_flash_attention", + "_scaled_dot_product_flash_attention_for_cpu", + "_scaled_grouped_mm", + "_scaled_grouped_mm_v2", + "_scaled_mm", + "_scaled_mm_v2", + "_shape_as_tensor", + "_sobol_engine_draw", + "_sobol_engine_ff_", + "_sobol_engine_initialize_state_", + "_sobol_engine_scramble_", + "_softmax", + "_softmax_backward_data", + "_sparse_broadcast_to", + "_sparse_broadcast_to_copy", + "_sparse_csr_prod", + "_sparse_csr_sum", + "_sparse_log_softmax_backward_data", + "_sparse_semi_structured_addmm", + "_sparse_semi_structured_apply", + "_sparse_semi_structured_apply_dense", + "_sparse_semi_structured_linear", + "_sparse_semi_structured_mm", + "_sparse_semi_structured_tile", + "_sparse_softmax_backward_data", + "_sparse_sparse_matmul", + "_sparse_sum", + "_stack", + "_standard_gamma", + "_standard_gamma_grad", + "_sync", + "_test_autograd_multiple_dispatch", + "_test_autograd_multiple_dispatch_view", + "_test_autograd_multiple_dispatch_view_copy", + "_test_check_tensor", + "_test_functorch_fallback", + "_test_parallel_materialize", + "_test_serialization_subcmul", + "_to_cpu", + "_to_functional_tensor", + "_to_sparse_semi_structured", + "_transform_bias_rescale_qkv", + "_transformer_encoder_layer_fwd", + "_trilinear", + "_triton_multi_head_attention", + "_triton_scaled_dot_attention", + "_unique", + "_unique2", + "_unpack_dual", + "_unsafe_index", + "_unsafe_index_put", + "_unsafe_masked_index", + "_unsafe_masked_index_put_accumulate", + "_use_cudnn_ctc_loss", + "_use_cudnn_rnn_flatten_weight", + "_use_miopen_ctc_loss", + "_validate_compressed_sparse_indices", + "_validate_sparse_bsc_tensor_args", + "_validate_sparse_bsr_tensor_args", + "_validate_sparse_compressed_tensor_args", + "_validate_sparse_coo_tensor_args", + "_validate_sparse_csc_tensor_args", + "_validate_sparse_csr_tensor_args", + "_values_copy", + "_weight_int4pack_mm", + "_weight_int4pack_mm_for_cpu", + "_weight_int4pack_mm_with_scales_and_zeros", + "_weight_int8pack_mm", + "_weight_norm", + "_weight_norm_interface", + "_wrapped_linear_prepack", + "_wrapped_quantized_linear_prepacked", + "abs", + "abs_", + "absolute", + "acos", + "acos_", + "acosh", + "acosh_", + "adaptive_avg_pool1d", + "adaptive_max_pool1d", + "add", + "addbmm", + "addcdiv", + "addcmul", + "addmm", + "addmv", + "addmv_", + "addr", + "adjoint", + "affine_grid_generator", + "alias_copy", + "all", + "allclose", + "alpha_dropout", + "alpha_dropout_", + "amax", + "amin", + "aminmax", + "angle", + "any", + "arange", + "arccos", + "arccos_", + "arccosh", + "arccosh_", + "arcsin", + "arcsin_", + "arcsinh", + "arcsinh_", + "arctan", + "arctan2", + "arctan_", + "arctanh", + "arctanh_", + "argmax", + "argmin", + "argsort", + "argwhere", + "as_strided", + "as_strided_", + "as_strided_copy", + "as_strided_scatter", + "as_tensor", + "asarray", + "asin", + "asin_", + "asinh", + "asinh_", + "atan", + "atan2", + "atan_", + "atanh", + "atanh_", + "avg_pool1d", + "baddbmm", + "bartlett_window", + "batch_norm", + "batch_norm_backward_elemt", + "batch_norm_backward_reduce", + "batch_norm_elemt", + "batch_norm_gather_stats", + "batch_norm_gather_stats_with_counts", + "batch_norm_stats", + "batch_norm_update_stats", + "bernoulli", + "bilinear", + "binary_cross_entropy_with_logits", + "bincount", + "binomial", + "bitwise_and", + "bitwise_left_shift", + "bitwise_not", + "bitwise_or", + "bitwise_right_shift", + "bitwise_xor", + "blackman_window", + "bmm", + "broadcast_to", + "bucketize", + "can_cast", + "cat", + "ccol_indices_copy", + "ceil", + "ceil_", + "celu", + "celu_", + "channel_shuffle", + "cholesky_inverse", + "cholesky_solve", + "choose_qparams_optimized", + "chunk", + "clamp", + "clamp_", + "clamp_max", + "clamp_max_", + "clamp_min", + "clamp_min_", + "clip", + "clip_", + "clone", + "col_indices_copy", + "column_stack", + "combinations", + "complex", + "concat", + "concatenate", + "conj", + "conj_physical", + "conj_physical_", + "constant_pad_nd", + "conv1d", + "conv2d", + "conv3d", + "conv_tbc", + "conv_transpose1d", + "conv_transpose2d", + "conv_transpose3d", + "convolution", + "copysign", + "corrcoef", + "cos", + "cos_", + "cosh", + "cosh_", + "cosine_embedding_loss", + "cosine_similarity", + "count_nonzero", + "cov", + "cross", + "crow_indices_copy", + "ctc_loss", + "cudnn_affine_grid_generator", + "cudnn_batch_norm", + "cudnn_convolution", + "cudnn_convolution_add_relu", + "cudnn_convolution_relu", + "cudnn_convolution_transpose", + "cudnn_grid_sampler", + "cudnn_is_acceptable", + "cummax", + "cummin", + "cumprod", + "cumsum", + "cumulative_trapezoid", + "deg2rad", + "deg2rad_", + "dequantize", + "det", + "detach", + "detach_", + "detach_copy", + "diag", + "diag_embed", + "diagflat", + "diagonal", + "diagonal_copy", + "diagonal_scatter", + "diff", + "digamma", + "dist", + "div", + "divide", + "dot", + "dropout", + "dropout_", + "dsmm", + "dsplit", + "dstack", + "embedding", + "embedding_bag", + "embedding_renorm_", + "empty", + "empty_like", + "empty_permuted", + "empty_quantized", + "empty_strided", + "eq", + "equal", + "erf", + "erf_", + "erfc", + "erfc_", + "erfinv", + "exp", + "exp2", + "exp2_", + "exp_", + "expand_copy", + "expm1", + "expm1_", + "eye", + "fake_quantize_per_channel_affine", + "fake_quantize_per_tensor_affine", + "fbgemm_linear_fp16_weight", + "fbgemm_linear_fp16_weight_fp32_activation", + "fbgemm_linear_int8_weight", + "fbgemm_linear_int8_weight_fp32_activation", + "fbgemm_linear_quantize_weight", + "fbgemm_pack_gemm_matrix_fp16", + "fbgemm_pack_quantized_matrix", + "feature_alpha_dropout", + "feature_alpha_dropout_", + "feature_dropout", + "feature_dropout_", + "fill", + "fill_", + "fix", + "fix_", + "flatten", + "flip", + "fliplr", + "flipud", + "float_power", + "floor", + "floor_", + "floor_divide", + "fmax", + "fmin", + "fmod", + "frac", + "frac_", + "frexp", + "frobenius_norm", + "from_file", + "from_numpy", + "frombuffer", + "full", + "full_like", + "fused_moving_avg_obs_fake_quant", + "gather", + "gcd", + "gcd_", + "ge", + "geqrf", + "ger", + "get_default_dtype", + "get_num_interop_threads", + "get_num_threads", + "gradient", + "greater", + "greater_equal", + "grid_sampler", + "grid_sampler_2d", + "grid_sampler_3d", + "group_norm", + "gru", + "gru_cell", + "gt", + "hamming_window", + "hann_window", + "hardshrink", + "hash_tensor", + "heaviside", + "hinge_embedding_loss", + "histc", + "histogram", + "histogramdd", + "hsmm", + "hsplit", + "hspmm", + "hstack", + "hypot", + "i0", + "i0_", + "igamma", + "igammac", + "imag", + "index_add", + "index_copy", + "index_fill", + "index_put", + "index_put_", + "index_reduce", + "index_select", + "indices_copy", + "init_num_threads", + "inner", + "instance_norm", + "int_repr", + "inverse", + "is_complex", + "is_conj", + "is_distributed", + "is_floating_point", + "is_grad_enabled", + "is_inference", + "is_inference_mode_enabled", + "is_neg", + "is_nonzero", + "is_same_size", + "is_signed", + "is_vulkan_available", + "isclose", + "isfinite", + "isin", + "isinf", + "isnan", + "isneginf", + "isposinf", + "isreal", + "istft", + "kaiser_window", + "kl_div", + "kron", + "kthvalue", + "layer_norm", + "lcm", + "lcm_", + "ldexp", + "ldexp_", + "le", + "lerp", + "less", + "less_equal", + "lgamma", + "linspace", + "log", + "log10", + "log10_", + "log1p", + "log1p_", + "log2", + "log2_", + "log_", + "log_softmax", + "logaddexp", + "logaddexp2", + "logcumsumexp", + "logdet", + "logical_and", + "logical_not", + "logical_or", + "logical_xor", + "logit", + "logit_", + "logspace", + "logsumexp", + "lstm", + "lstm_cell", + "lt", + "lu_solve", + "lu_unpack", + "margin_ranking_loss", + "masked_fill", + "masked_scatter", + "masked_select", + "matmul", + "matrix_exp", + "matrix_power", + "max", + "max_pool1d", + "max_pool1d_with_indices", + "max_pool2d", + "max_pool3d", + "maximum", + "mean", + "median", + "min", + "minimum", + "miopen_batch_norm", + "miopen_convolution", + "miopen_convolution_add_relu", + "miopen_convolution_relu", + "miopen_convolution_transpose", + "miopen_ctc_loss", + "miopen_depthwise_convolution", + "miopen_rnn", + "mkldnn_adaptive_avg_pool2d", + "mkldnn_convolution", + "mkldnn_linear_backward_weights", + "mkldnn_max_pool2d", + "mkldnn_max_pool3d", + "mkldnn_rnn_layer", + "mm", + "mode", + "moveaxis", + "movedim", + "msort", + "mul", + "multinomial", + "multiply", + "mv", + "mvlgamma", + "nan_to_num", + "nan_to_num_", + "nanmean", + "nanmedian", + "nanquantile", + "nansum", + "narrow", + "narrow_copy", + "native_batch_norm", + "native_channel_shuffle", + "native_dropout", + "native_group_norm", + "native_layer_norm", + "native_norm", + "ne", + "neg", + "neg_", + "negative", + "negative_", + "nextafter", + "nonzero", + "nonzero_static", + "norm_except_dim", + "normal", + "not_equal", + "nuclear_norm", + "numel", + "ones", + "ones_like", + "orgqr", + "ormqr", + "outer", + "pairwise_distance", + "pdist", + "permute", + "permute_copy", + "pinverse", + "pixel_shuffle", + "pixel_unshuffle", + "poisson", + "poisson_nll_loss", + "polar", + "polygamma", + "positive", + "pow", + "prelu", + "prod", + "promote_types", + "put", + "q_per_channel_axis", + "q_per_channel_scales", + "q_per_channel_zero_points", + "q_scale", + "q_zero_point", + "quantile", + "quantize_per_channel", + "quantize_per_tensor", + "quantize_per_tensor_dynamic", + "quantized_batch_norm", + "quantized_gru_cell", + "quantized_lstm_cell", + "quantized_max_pool1d", + "quantized_max_pool2d", + "quantized_max_pool3d", + "quantized_rnn_relu_cell", + "quantized_rnn_tanh_cell", + "rad2deg", + "rad2deg_", + "rand", + "rand_like", + "randint", + "randint_like", + "randn", + "randn_like", + "randperm", + "range", + "ravel", + "real", + "reciprocal", + "reciprocal_", + "relu", + "relu_", + "remainder", + "renorm", + "repeat_interleave", + "reshape", + "resize_as_", + "resize_as_sparse_", + "resolve_conj", + "resolve_neg", + "result_type", + "rms_norm", + "rnn_relu", + "rnn_relu_cell", + "rnn_tanh", + "rnn_tanh_cell", + "roll", + "rot90", + "round", + "round_", + "row_indices_copy", + "row_stack", + "rrelu", + "rrelu_", + "rsqrt", + "rsqrt_", + "rsub", + "saddmm", + "scalar_tensor", + "scatter", + "scatter_add", + "scatter_reduce", + "searchsorted", + "segment_reduce", + "select", + "select_copy", + "select_scatter", + "selu", + "selu_", + "set_flush_denormal", + "set_num_interop_threads", + "set_num_threads", + "sgn", + "sigmoid", + "sigmoid_", + "sign", + "signbit", + "sin", + "sin_", + "sinc", + "sinc_", + "sinh", + "sinh_", + "slice_copy", + "slice_inverse", + "slice_scatter", + "slogdet", + "smm", + "softmax", + "sort", + "sparse_bsc_tensor", + "sparse_bsr_tensor", + "sparse_compressed_tensor", + "sparse_coo_tensor", + "sparse_csc_tensor", + "sparse_csr_tensor", + "split_copy", + "split_with_sizes", + "split_with_sizes_copy", + "spmm", + "sqrt", + "sqrt_", + "square", + "square_", + "squeeze", + "squeeze_copy", + "sspaddmm", + "stack", + "std", + "std_mean", + "sub", + "subtract", + "sum", + "svd", + "swapaxes", + "swapdims", + "sym_constrain_range", + "sym_constrain_range_for_size", + "t", + "t_copy", + "take", + "take_along_dim", + "tan", + "tan_", + "tanh", + "tanh_", + "tensor", + "tensor_split", + "threshold", + "threshold_", + "tile", + "topk", + "trace", + "transpose", + "transpose_copy", + "trapezoid", + "trapz", + "triangular_solve", + "tril", + "tril_indices", + "triplet_margin_loss", + "triu", + "triu_indices", + "true_divide", + "trunc", + "trunc_", + "unbind", + "unbind_copy", + "unflatten", + "unfold_copy", + "unique_dim", + "unsafe_chunk", + "unsafe_split", + "unsafe_split_with_sizes", + "unsqueeze", + "unsqueeze_copy", + "values_copy", + "vander", + "var", + "var_mean", + "vdot", + "view_as_complex", + "view_as_complex_copy", + "view_as_real", + "view_as_real_copy", + "view_copy", + "vsplit", + "vstack", + "where", + "xlogy", + "xlogy_", + "zero_", + "zeros", + "zeros_like", +] + +@overload +def __and__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __and__(input: Tensor, other: Number | _complex | PySymType) -> Tensor: ... +@overload +def __lshift__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __lshift__( + input: Tensor, + other: Number | _complex | PySymType, +) -> Tensor: ... +@overload +def __or__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __or__(input: Tensor, other: Number | _complex | PySymType) -> Tensor: ... +@overload +def __rshift__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __rshift__( + input: Tensor, + other: Number | _complex | PySymType, +) -> Tensor: ... +@overload +def __xor__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __xor__(input: Tensor, other: Number | _complex | PySymType) -> 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 | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def _add_relu( + input: Tensor, + other: Number | _complex | PySymType, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: ... +@overload +def _add_relu_( + input: Tensor, + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: ... +@overload +def _add_relu_( + input: Tensor, + other: Number | _complex | PySymType, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: ... +def _addmm_activation( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 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], + 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 | PySymType, + 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], + 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], + 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], + 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 _flash_attention_forward_no_dropout_inplace( + out: Tensor | None, + query: Tensor, + key: Tensor, + value: Tensor, + cum_seq_q: Tensor | None, + cum_seq_k: Tensor | None, + max_q: _int | SymInt, + max_k: _int | SymInt, + dropout_p: _float, + is_causal: _bool, + return_debug_mask: _bool, + *, + scale: _float | None = None, + window_size_left: _int | SymInt | None = None, + window_size_right: _int | SymInt | None = None, + seqused_k: Tensor | None = None, + alibi_slopes: Tensor | None = None, + block_table: Tensor | None = None, + num_splits: _int | None = None, +) -> Tensor: ... +def _foobar( + input: Tensor, + arg1: _bool = True, + arg2: _bool = True, + *, + arg3: _bool = True, +) -> Tensor: ... +def _foreach_abs( + self: tuple[Tensor, ...] | list[Tensor], +) -> 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: + 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], +) -> 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: + 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], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], + *, + alpha: Number | _complex | PySymType = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], + *, + alpha: Number | _complex | PySymType = 1, +) -> None: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, +) -> None: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_addcdiv( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcdiv( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcdiv( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + value: Number | _complex | PySymType = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcdiv_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_addcdiv_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Tensor, +) -> None: ... +@overload +def _foreach_addcdiv_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + value: Number | _complex | PySymType = 1, +) -> None: ... +@overload +def _foreach_addcmul( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcmul( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcmul( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + value: Number | _complex | PySymType = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcmul_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_addcmul_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Tensor, +) -> None: ... +@overload +def _foreach_addcmul_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + value: Number | _complex | PySymType = 1, +) -> None: ... +def _foreach_asin( + self: tuple[Tensor, ...] | list[Tensor], +) -> 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: + 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], +) -> 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: + 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], +) -> 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: + 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], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_max( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_max( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_max_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_clamp_max_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_clamp_max_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +@overload +def _foreach_clamp_min( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_min( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_min( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_min_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_clamp_min_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_clamp_min_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_clone( + self: tuple[Tensor, ...] | list[Tensor], + *, + memory_format: memory_format | None = None, +) -> tuple[Tensor, ...]: ... +def _foreach_copy_( + self: tuple[Tensor, ...] | list[Tensor], + src: tuple[Tensor, ...] | list[Tensor], + non_blocking: _bool = False, +) -> None: ... +def _foreach_cos( + self: tuple[Tensor, ...] | list[Tensor], +) -> 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: + 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], +) -> 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: + 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], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, +) -> None: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_erf( + self: tuple[Tensor, ...] | list[Tensor], +) -> 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: + 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], +) -> 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: + 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], +) -> 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: + 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], +) -> 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: + 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], +) -> 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: + 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], +) -> 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: + 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], + tensors1: tuple[Tensor, ...] | list[Tensor], + weight: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_lerp( + self: tuple[Tensor, ...] | list[Tensor], + tensors1: tuple[Tensor, ...] | list[Tensor], + weight: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_lerp( + self: tuple[Tensor, ...] | list[Tensor], + tensors1: tuple[Tensor, ...] | list[Tensor], + weights: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_lerp_( + self: tuple[Tensor, ...] | list[Tensor], + tensors1: tuple[Tensor, ...] | list[Tensor], + weight: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_lerp_( + self: tuple[Tensor, ...] | list[Tensor], + tensors1: tuple[Tensor, ...] | list[Tensor], + weight: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_lerp_( + self: tuple[Tensor, ...] | list[Tensor], + tensors1: tuple[Tensor, ...] | list[Tensor], + weights: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_lgamma( + self: tuple[Tensor, ...] | list[Tensor], +) -> 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: + 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], +) -> 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], +) -> 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: + 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], +) -> 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: + 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], +) -> 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: + 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: + 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], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_maximum_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_maximum_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +@overload +def _foreach_minimum( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_minimum( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_minimum( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_minimum_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_minimum_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_minimum_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_mm( + self: tuple[Tensor, ...] | list[Tensor], + mat2: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, +) -> None: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_neg( + self: tuple[Tensor, ...] | list[Tensor], +) -> 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: + 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], + ord: Number | _complex | PySymType = 2, + dtype: _dtype | None = None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: tuple[Tensor, ...] | list[Tensor], + exponent: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: tuple[Tensor, ...] | list[Tensor], + exponent: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: tuple[Tensor, ...] | list[Tensor], + exponent: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: Number | _complex | PySymType, + exponent: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow_( + self: tuple[Tensor, ...] | list[Tensor], + exponent: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_pow_( + self: tuple[Tensor, ...] | list[Tensor], + exponent: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_pow_( + self: tuple[Tensor, ...] | list[Tensor], + exponent: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_powsum( + self: tuple[Tensor, ...] | list[Tensor], + ord: Number | _complex | PySymType = 2, + dtype: _dtype | None = None, +) -> tuple[Tensor, ...]: ... +def _foreach_reciprocal( + self: tuple[Tensor, ...] | list[Tensor], +) -> 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: + 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], +) -> 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: + 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], +) -> tuple[Tensor, ...]: ... +def _foreach_rsqrt_(self: tuple[Tensor, ...] | list[Tensor]) -> None: ... +def _foreach_sigmoid( + self: tuple[Tensor, ...] | list[Tensor], +) -> 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: + 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], +) -> tuple[Tensor, ...]: ... +def _foreach_sign_(self: tuple[Tensor, ...] | list[Tensor]) -> None: ... +def _foreach_sin( + self: tuple[Tensor, ...] | list[Tensor], +) -> 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: + 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], +) -> 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: + 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], +) -> 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: + 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], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_sub( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], + *, + alpha: Number | _complex | PySymType = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_sub( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_sub_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_sub_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], + *, + alpha: Number | _complex | PySymType = 1, +) -> None: ... +@overload +def _foreach_sub_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +def _foreach_tan( + self: tuple[Tensor, ...] | list[Tensor], +) -> 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: + 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], +) -> 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: + 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], +) -> 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: + 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: + 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 | PySymType, + assert_msg: str, + dep_token: Tensor, +) -> Tensor: ... +def _functional_sym_constrain_range( + size: Number | _complex | PySymType, + min: _int | None, + max: _int | None, + dep_token: Tensor, +) -> Tensor: ... +def _functional_sym_constrain_range_for_size( + size: Number | _complex | PySymType, + min: _int | None, + max: _int | None, + dep_token: Tensor, +) -> Tensor: ... +def _functionalize_apply_view_metas(tensor: Tensor, base: Tensor) -> Tensor: ... +def _functionalize_are_all_mutations_hidden_from_autograd( + t: Tensor, +) -> _bool: ... +def _functionalize_are_all_mutations_under_no_grad_or_inference_mode( + t: Tensor, +) -> _bool: ... +def _functionalize_commit_update(t: Tensor) -> None: ... +def _functionalize_has_metadata_mutation(tensor: Tensor) -> _bool: ... +def _functionalize_inductor_storage_resized_counter(t: Tensor) -> _int: ... +def _functionalize_is_symbolic(tensor: Tensor) -> _bool: ... +def _functionalize_mark_mutation_hidden_from_autograd(t: Tensor) -> None: ... +def _functionalize_mark_storage_changed(tensor: Tensor) -> _bool: ... +def _functionalize_mutation_counter(t: Tensor) -> _int: ... +def _functionalize_replace(self_: Tensor, other: Tensor) -> None: ... +def _functionalize_storage_changed_counter(t: Tensor) -> _int: ... +def _functionalize_sync(t: Tensor) -> None: ... +def _functionalize_unsafe_set(dst: Tensor, src: Tensor) -> None: ... +def _functionalize_was_inductor_storage_resized(t: Tensor) -> _bool: ... +def _functionalize_was_storage_changed(tensor: Tensor) -> _bool: ... +@overload +def _fused_adagrad_( + self: tuple[Tensor, ...] | list[Tensor], + grads: tuple[Tensor, ...] | list[Tensor], + state_sums: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + 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], + grads: tuple[Tensor, ...] | list[Tensor], + state_sums: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + 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], + grads: tuple[Tensor, ...] | list[Tensor], + exp_avgs: tuple[Tensor, ...] | list[Tensor], + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + 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], + grads: tuple[Tensor, ...] | list[Tensor], + exp_avgs: tuple[Tensor, ...] | list[Tensor], + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + 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], + grads: tuple[Tensor, ...] | list[Tensor], + exp_avgs: tuple[Tensor, ...] | list[Tensor], + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + 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], + grads: tuple[Tensor, ...] | list[Tensor], + exp_avgs: tuple[Tensor, ...] | list[Tensor], + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + lr: _float, + beta1: _float, + beta2: _float, + weight_decay: _float, + eps: _float, + amsgrad: _bool, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +def _fused_dropout( + input: Tensor, + p: _float, + generator: Generator | None = None, +) -> tuple[Tensor, Tensor]: ... +def _fused_moving_avg_obs_fq_helper( + input: Tensor, + observer_on: Tensor, + fake_quant_on: Tensor, + running_min: Tensor, + running_max: Tensor, + scale: Tensor, + zero_point: Tensor, + averaging_const: _float, + quant_min: _int, + quant_max: _int, + ch_axis: _int, + per_row_fake_quant: _bool = False, + symmetric_quant: _bool = False, +) -> torch.return_types._fused_moving_avg_obs_fq_helper: ... +def _fused_rms_norm( + input: Tensor, + normalized_shape: _size, + weight: Tensor | None, + eps: _float | None, +) -> tuple[Tensor, Tensor]: ... +def _fused_sdp_choice( + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Tensor | None = None, + dropout_p: _float = 0.0, + is_causal: _bool = False, + *, + scale: _float | None = None, + enable_gqa: _bool = False, +) -> _int: ... +@overload +def _fused_sgd_( + self: tuple[Tensor, ...] | list[Tensor], + grads: tuple[Tensor, ...] | list[Tensor], + momentum_buffer_list: tuple[Tensor, ...] | list[Tensor], + *, + 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], + grads: tuple[Tensor, ...] | list[Tensor], + momentum_buffer_list: tuple[Tensor, ...] | list[Tensor], + *, + 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], + *, + weight: Tensor | None = None, + density: _bool = False, +) -> Tensor: ... +def _index_put_impl_( + input: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | 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], + params: tuple[Tensor, ...] | list[Tensor], + 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], + 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 | PySymType, + total_length: _int, +) -> tuple[Tensor, Tensor]: ... +@overload +def _philox_key_fold_in(key: Tensor, data: Tensor) -> Tensor: ... +@overload +def _philox_key_fold_in(key: Tensor, data: _int) -> Tensor: ... +def _philox_key_split(key: Tensor, num_splits: _int) -> Tensor: ... +def _philox_normal_( + input: Tensor, + key: Tensor, + mean: _float = 0, + std: _float = 1, +) -> Tensor: ... +def _philox_uniform_( + input: Tensor, + key: Tensor, + low: _float = 0, + high: _float = 1, +) -> 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, + enable_gqa: _bool = False, +) -> 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: ... +@overload +def _scaled_dot_product_flash_attention( + query: Tensor, + key: Tensor, + value: Tensor, + q_descale: Tensor | None, + k_descale: Tensor | None, + v_descale: Tensor | None, + 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: ... +@overload +def _scaled_dot_product_flash_attention( + query: Tensor, + key: Tensor, + value: Tensor, + dropout_p: _float = 0.0, + is_causal: _bool = False, + return_debug_mask: _bool = False, + *, + scale: _float | None = None, +) -> torch.return_types._scaled_dot_product_flash_attention: ... +def _scaled_dot_product_flash_attention_for_cpu( + query: Tensor, + key: Tensor, + value: Tensor, + dropout_p: _float = 0.0, + is_causal: _bool = False, + *, + attn_mask: Tensor | None = None, + scale: _float | None = None, +) -> torch.return_types._scaled_dot_product_flash_attention_for_cpu: ... +def _scaled_grouped_mm( + input: Tensor, + mat2: Tensor, + scale_a: Tensor, + scale_b: Tensor, + offs: Tensor | None = None, + bias: Tensor | None = None, + scale_result: Tensor | None = None, + out_dtype: _dtype | None = None, + use_fast_accum: _bool = False, +) -> Tensor: ... +def _scaled_grouped_mm_v2( + input: Tensor, + mat2: Tensor, + scale_a: tuple[Tensor, ...] | list[Tensor], + recipe_a: _size, + swizzle_a: _size, + scale_b: tuple[Tensor, ...] | list[Tensor], + recipe_b: _size, + swizzle_b: _size, + offs: Tensor | None = None, + bias: Tensor | None = None, + out_dtype: _dtype | None = None, + contraction_dim: _size = (), + use_fast_accum: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _scaled_mm( + input: Tensor, + mat2: Tensor, + scale_a: Tensor, + scale_b: Tensor, + bias: Tensor | None = None, + scale_result: Tensor | None = None, + out_dtype: _dtype | None = None, + use_fast_accum: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _scaled_mm_v2( + input: Tensor, + mat2: Tensor, + scale_a: tuple[Tensor, ...] | list[Tensor], + recipe_a: _size, + swizzle_a: _size, + scale_b: tuple[Tensor, ...] | list[Tensor], + recipe_b: _size, + swizzle_b: _size, + bias: Tensor | None, + out_dtype: _dtype | None, + contraction_dim: _size = (), + use_fast_accum: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _shape_as_tensor(input: Tensor) -> Tensor: ... +def _sobol_engine_draw( + quasi: Tensor, + n: _int, + sobolstate: Tensor, + dimension: _int, + num_generated: _int, + dtype: _dtype | None, +) -> tuple[Tensor, Tensor]: ... +def _sobol_engine_ff_( + input: Tensor, + n: _int, + sobolstate: Tensor, + dimension: _int, + num_generated: _int, +) -> Tensor: ... +def _sobol_engine_initialize_state_( + input: Tensor, + dimension: _int, +) -> Tensor: ... +def _sobol_engine_scramble_( + input: Tensor, + ltm: Tensor, + dimension: _int, +) -> Tensor: ... +def _softmax( + input: Tensor, + dim: _int, + half_to_float: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _softmax_backward_data( + grad_output: Tensor, + output: Tensor, + dim: _int, + input_dtype: _dtype, + *, + grad_input: Tensor | None = None, +) -> Tensor: ... +def _sparse_broadcast_to(input: Tensor, size: _size) -> Tensor: ... +def _sparse_broadcast_to_copy( + input: Tensor, + size: _size, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _sparse_csr_prod( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_csr_sum( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_log_softmax_backward_data( + grad_output: Tensor, + output: Tensor, + dim: _int, + input: Tensor, +) -> Tensor: ... +def _sparse_semi_structured_addmm( + input: Tensor, + mat1: Tensor, + mat1_meta: Tensor, + mat2: Tensor, + *, + alpha: Number | _complex | PySymType = 1, + beta: Number | _complex | PySymType = 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], + 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 | PySymType = 1, +) -> Tensor: ... +def _to_cpu( + tensors: tuple[Tensor, ...] | list[Tensor], +) -> 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 | None, ...] | list[Tensor | None] | None, +) -> Tensor: ... +def _unsafe_index_put( + input: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, + values: Tensor, + accumulate: _bool = False, +) -> Tensor: ... +def _unsafe_masked_index( + input: Tensor, + mask: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, + fill: Number | _complex | PySymType, +) -> Tensor: ... +def _unsafe_masked_index_put_accumulate( + input: Tensor, + mask: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | 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: ... +@overload +def _use_miopen_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int, +) -> _bool: ... +@overload +def _use_miopen_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int, +) -> _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: + r""" + abs_(input) -> Tensor + + In-place version of :func:`torch.abs` + """ + +def absolute(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + absolute(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.abs` + """ + +def acos(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + acos(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the arccosine (in radians) of each element in :attr:`input`. + + .. math:: + \text{out}_{i} = \cos^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.3348, -0.5889, 0.2005, -0.1584]) + >>> torch.acos(a) + tensor([ 1.2294, 2.2004, 1.3690, 1.7298]) + """ + +def acos_(input: Tensor) -> Tensor: + r""" + acos_(input) -> Tensor + + In-place version of :func:`torch.acos` + """ + +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: + r""" + acosh_(input) -> Tensor + + In-place version of :func:`torch.acosh` + """ + +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 | PySymType, + 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 | PySymType, + 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 | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + 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 | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + 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 | PySymType = 1, + alpha: Number | _complex | PySymType = 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 | PySymType, + 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 | PySymType, + 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 | PySymType, + 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 | PySymType, + 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 | PySymType = 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 | PySymType, + 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 | PySymType, + 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 | PySymType = 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 | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + mat1: Tensor, + mat2: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, 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 + + 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]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@overload +def addmm( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + mat1: Tensor, + mat2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, 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 + + 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]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@overload +def addmm( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, 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 + + 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]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@overload +def addmm( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + out_dtype: _dtype, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, 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 + + 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]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@overload +def addmm( + beta: Number | _complex | PySymType, + self: Tensor, + mat1: Tensor, + mat2: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, 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 + + 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]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@overload +def addmm( + beta: Number | _complex | PySymType, + self: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, 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 + + 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]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@overload +def addmv( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + 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 | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + 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 | PySymType = 1, + alpha: Number | _complex | PySymType = 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 | PySymType, + 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 | PySymType, + 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 | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + mat: Tensor, + vec: Tensor, +) -> Tensor: + r""" + addmv_(input, mat, vec, *, beta=1, alpha=1) -> Tensor + + In-place version of :func:`torch.addmv` + """ + +@overload +def addmv_( + input: Tensor, + mat: Tensor, + vec: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: + r""" + addmv_(input, mat, vec, *, beta=1, alpha=1) -> Tensor + + In-place version of :func:`torch.addmv` + """ + +@overload +def addmv_( + beta: Number | _complex | PySymType, + self: Tensor, + mat: Tensor, + vec: Tensor, +) -> Tensor: + r""" + addmv_(input, mat, vec, *, beta=1, alpha=1) -> Tensor + + In-place version of :func:`torch.addmv` + """ + +@overload +def addr( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + 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 | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + 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 | PySymType = 1, + alpha: Number | _complex | PySymType = 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 | PySymType, + 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 | PySymType, + 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) + """ + +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: + r""" + alpha_dropout_(input, p, train) -> Tensor + + In-place version of :func:`torch.alpha_dropout` + """ + +def amax( + input: Tensor, + dim: _int | _size = (), + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + amax(input, dim=None, keepdim=False, *, out=None) -> Tensor + + Returns the maximum value of each slice of the :attr:`input` tensor in the given + dimension(s) :attr:`dim`. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.8177, 1.4878, -0.2491, 0.9130], + [-0.7158, 1.1775, 2.0992, 0.4817], + [-0.0053, 0.0164, -1.3738, -0.0507], + [ 1.9700, 1.1106, -1.0318, -1.0816]]) + >>> torch.amax(a, 1) + tensor([1.4878, 2.0992, 0.0164, 1.9700]) + """ + +def amin( + input: Tensor, + dim: _int | _size = (), + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + amin(input, dim=None, keepdim=False, *, out=None) -> Tensor + + Returns the minimum value of each slice of the :attr:`input` tensor in the given + dimension(s) :attr:`dim`. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.6451, -0.4866, 0.2987, -1.3312], + [-0.5744, 1.2980, 1.8397, -0.2713], + [ 0.9128, 0.9214, -1.7268, -0.2995], + [ 0.9023, 0.4853, 0.9075, -1.6165]]) + >>> torch.amin(a, 1) + tensor([-1.3312, -0.5744, -1.7268, -1.6165]) + """ + +def aminmax( + input: Tensor, + *, + dim: _int | None = None, + keepdim: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.aminmax: + r""" + aminmax(input, *, dim=None, keepdim=False, out=None) -> (Tensor min, Tensor max) + + Computes the minimum and maximum values of the :attr:`input` tensor. + + Args: + input (Tensor): + The input tensor + + Keyword Args: + dim (Optional[int]): + The dimension along which to compute the values. If `None`, + computes the values over the entire :attr:`input` tensor. + Default is `None`. + keepdim (bool): + If `True`, the reduced dimensions will be kept in the output + tensor as dimensions with size 1 for broadcasting, otherwise + they will be removed, as if calling (:func:`torch.squeeze`). + Default is `False`. + out (Optional[Tuple[Tensor, Tensor]]): + Optional tensors on which to write the result. Must have the same + shape and dtype as the expected output. + Default is `None`. + + Returns: + A named tuple `(min, max)` containing the minimum and maximum values. + + Raises: + RuntimeError + If any of the dimensions to compute the values over has size 0. + + .. note:: + NaN values are propagated to the output if at least one value is NaN. + + .. seealso:: + :func:`torch.amin` computes just the minimum value + :func:`torch.amax` computes just the maximum value + + Example:: + + >>> torch.aminmax(torch.tensor([1, -3, 5])) + torch.return_types.aminmax( + min=tensor(-3), + max=tensor(5)) + + >>> # aminmax propagates NaNs + >>> torch.aminmax(torch.tensor([1, -3, 5, torch.nan])) + torch.return_types.aminmax( + min=tensor(nan), + max=tensor(nan)) + + >>> t = torch.arange(10).view(2, 5) + >>> t + tensor([[0, 1, 2, 3, 4], + [5, 6, 7, 8, 9]]) + >>> t.aminmax(dim=0, keepdim=True) + torch.return_types.aminmax( + min=tensor([[0, 1, 2, 3, 4]]), + max=tensor([[5, 6, 7, 8, 9]])) + """ + +def angle(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + angle(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the element-wise angle (in radians) of the given :attr:`input` tensor. + + .. math:: + \text{out}_{i} = angle(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + .. note:: Starting in PyTorch 1.8, angle returns pi for negative real numbers, + zero for non-negative real numbers, and propagates NaNs. Previously + the function would return zero for all real numbers and not propagate + floating-point NaNs. + + Example:: + + >>> torch.angle(torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]))*180/3.14159 + tensor([ 135., 135, -45]) + """ + +@overload +def any(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + any(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Tests if any element in :attr:`input` evaluates to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.any(a) + tensor(True, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.any(a) + tensor(True) + + .. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if any element in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 2) < 0 + >>> a + tensor([[ True, True], + [False, True], + [ True, True], + [False, False]]) + >>> torch.any(a, 1) + tensor([ True, True, True, False]) + >>> torch.any(a, 0) + tensor([True, True]) + """ + +@overload +def any( + input: Tensor, + dim: _size | None = None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + any(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Tests if any element in :attr:`input` evaluates to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.any(a) + tensor(True, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.any(a) + tensor(True) + + .. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if any element in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 2) < 0 + >>> a + tensor([[ True, True], + [False, True], + [ True, True], + [False, False]]) + >>> torch.any(a, 1) + tensor([ True, True, True, False]) + >>> torch.any(a, 0) + tensor([True, True]) + """ + +@overload +def any( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + any(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Tests if any element in :attr:`input` evaluates to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.any(a) + tensor(True, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.any(a) + tensor(True) + + .. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if any element in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 2) < 0 + >>> a + tensor([[ True, True], + [False, True], + [ True, True], + [False, False]]) + >>> torch.any(a, 1) + tensor([ True, True, True, False]) + >>> torch.any(a, 0) + tensor([True, True]) + """ + +@overload +def 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 `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.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 `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.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 `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.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 | PySymType, + *, + 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 `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.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 | PySymType, + end: Number | _complex | PySymType, + *, + 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 `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.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 | PySymType, + end: Number | _complex | PySymType, + step: Number | _complex | PySymType = 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 `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.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: + r""" + arccos_(input) -> Tensor + + In-place version of :func:`torch.arccos` + """ + +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: + r""" + arccosh_(input) -> Tensor + + In-place version of :func:`torch.arccosh` + """ + +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: + r""" + arcsin_(input) -> Tensor + + In-place version of :func:`torch.arcsin` + """ + +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: + r""" + arcsinh_(input) -> Tensor + + In-place version of :func:`torch.arcsinh` + """ + +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: + r""" + arctan_(input) -> Tensor + + In-place version of :func:`torch.arctan` + """ + +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: + r""" + arctanh_(input) -> Tensor + + In-place version of :func:`torch.arctanh` + """ + +def argmax( + input: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + argmax(input) -> LongTensor + + Returns the indices of the maximum value of all elements in the :attr:`input` tensor. + + This is the second value returned by :meth:`torch.max`. See its + documentation for the exact semantics of this method. + + .. note:: If there are multiple maximal values then the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 1.3398, 0.2663, -0.2686, 0.2450], + [-0.7401, -0.8805, -0.3402, -1.1936], + [ 0.4907, -1.3948, -1.0691, -0.3132], + [-1.6092, 0.5419, -0.2993, 0.3195]]) + >>> torch.argmax(a) + tensor(0) + + .. function:: argmax(input, dim, keepdim=False) -> LongTensor + :noindex: + + Returns the indices of the maximum values of a tensor across a dimension. + + This is the second value returned by :meth:`torch.max`. See its + documentation for the exact semantics of this method. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, the argmax of the flattened input is returned. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 1.3398, 0.2663, -0.2686, 0.2450], + [-0.7401, -0.8805, -0.3402, -1.1936], + [ 0.4907, -1.3948, -1.0691, -0.3132], + [-1.6092, 0.5419, -0.2993, 0.3195]]) + >>> torch.argmax(a, dim=1) + tensor([ 0, 2, 0, 1]) + """ + +def argmin( + input: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + argmin(input, dim=None, keepdim=False) -> LongTensor + + Returns the indices of the minimum value(s) of the flattened tensor or along a dimension + + This is the second value returned by :meth:`torch.min`. See its + documentation for the exact semantics of this method. + + .. note:: If there are multiple minimal values then the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, the argmin of the flattened input is returned. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.1139, 0.2254, -0.1381, 0.3687], + [ 1.0100, -1.1975, -0.0102, -0.4732], + [-0.9240, 0.1207, -0.7506, -1.0213], + [ 1.7809, -1.2960, 0.9384, 0.1438]]) + >>> torch.argmin(a) + tensor(13) + >>> torch.argmin(a, dim=1) + tensor([ 2, 1, 3, 1]) + >>> torch.argmin(a, dim=1, keepdim=True) + tensor([[2], + [1], + [3], + [1]]) + """ + +@overload +def argsort( + input: Tensor, + *, + stable: _bool, + dim: _int = -1, + descending: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + argsort(input, dim=-1, descending=False, *, stable=False) -> Tensor + + Returns the indices that sort a tensor along a given dimension in ascending + order by value. + + This is the second value returned by :meth:`torch.sort`. See its documentation + for the exact semantics of this method. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. If ``False``, the relative order of values + which compare equal is not guaranteed. ``True`` is slower. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): controls the relative order of equivalent elements + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0785, 1.5267, -0.8521, 0.4065], + [ 0.1598, 0.0788, -0.0745, -1.2700], + [ 1.2208, 1.0722, -0.7064, 1.2564], + [ 0.0669, -0.2318, -0.8229, -0.9280]]) + + + >>> torch.argsort(a, dim=1) + tensor([[2, 0, 3, 1], + [3, 2, 1, 0], + [2, 1, 0, 3], + [3, 2, 1, 0]]) + """ + +@overload +def argsort( + input: Tensor, + dim: _int = -1, + descending: _bool = False, +) -> Tensor: + r""" + argsort(input, dim=-1, descending=False, *, stable=False) -> Tensor + + Returns the indices that sort a tensor along a given dimension in ascending + order by value. + + This is the second value returned by :meth:`torch.sort`. See its documentation + for the exact semantics of this method. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. If ``False``, the relative order of values + which compare equal is not guaranteed. ``True`` is slower. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): controls the relative order of equivalent elements + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0785, 1.5267, -0.8521, 0.4065], + [ 0.1598, 0.0788, -0.0745, -1.2700], + [ 1.2208, 1.0722, -0.7064, 1.2564], + [ 0.0669, -0.2318, -0.8229, -0.9280]]) + + + >>> torch.argsort(a, dim=1) + tensor([[2, 0, 3, 1], + [3, 2, 1, 0], + [2, 1, 0, 3], + [3, 2, 1, 0]]) + """ + +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: + r""" + as_strided_(input, size, stride, storage_offset=None) -> Tensor + + In-place version of :func:`torch.as_strided` + """ + +def as_strided_copy( + input: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.as_strided`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def as_strided_scatter( + input: Tensor, + src: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, +) -> Tensor: + r""" + as_strided_scatter(input, src, size, stride, storage_offset=None) -> Tensor + + Embeds the values of the :attr:`src` tensor into :attr:`input` along + the elements corresponding to the result of calling + input.as_strided(size, stride, storage_offset). + + This function returns a tensor with fresh storage; it does not + return a view. + + Args: + input (Tensor): the input tensor. + size (tuple or ints): the shape of the output tensor + stride (tuple or ints): the stride of the output tensor + storage_offset (int, optional): the offset in the underlying storage of the output tensor + + .. note:: + + :attr:`src` must be of the proper size in order to be embedded + into :attr:`input`. Specifically, it should have the same shape as + `torch.as_strided(input, size, stride, storage_offset)` + + Example:: + + >>> a = torch.arange(4).reshape(2, 2) + 1 + >>> a + tensor([[1, 2], + [3, 4]]) + >>> b = torch.zeros(3, 3) + >>> b + tensor([[0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]) + >>> torch.as_strided_scatter(b, a, (2, 2), (1, 2)) + tensor([[1., 3., 2.], + [4., 0., 0.], + [0., 0., 0.]]) + """ + +def as_tensor( + data: Any, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, +) -> Tensor: + r""" + as_tensor(data: Any, *, dtype: Optional[dtype] = None, device: Optional[DeviceLikeType]) -> Tensor + + Converts :attr:`data` into a tensor, sharing data and preserving autograd + history if possible. + + If :attr:`data` is already a tensor with the requested dtype and device + then :attr:`data` itself is returned, but if :attr:`data` is a + tensor with a different dtype or device then it's copied as if using + `data.to(dtype=dtype, device=device)`. + + If :attr:`data` is a NumPy array (an ndarray) with the same dtype and device then a + tensor is constructed using :func:`torch.from_numpy`. + + If :attr:`data` is a CuPy array, the returned tensor will be located on the same device as the CuPy array unless + specifically overwritten by :attr:`device` or a default device. The device of the CuPy array is inferred from the + pointer of the array using `cudaPointerGetAttributes` unless :attr:`device` is provided with an explicit device index. + + .. seealso:: + + :func:`torch.tensor` never shares its data and creates a new "leaf tensor" (see :doc:`/notes/autograd`). + + + Args: + data (array_like): Initial data for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, infers data type from :attr:`data`. + device (:class:`torch.device`, optional): the device of the constructed tensor. If None and data is a tensor + then the device of data is used. If None and data is not a tensor then + the result tensor is constructed on the current device. + + + Example:: + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.as_tensor(a) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([-1, 2, 3]) + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.as_tensor(a, device=torch.device('cuda')) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([1, 2, 3]) + """ + +def asarray( + obj: Any, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + copy: _bool | None = None, + requires_grad: _bool | None = None, +) -> Tensor: + r""" + asarray(obj: Any, *, dtype: Optional[dtype], device: Optional[DeviceLikeType], copy: Optional[bool] = None, requires_grad: Optional[bool] = None) -> 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, have the same requires_grad as :attr:`obj` (defaulting to False), have the + same datatype, 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`` (or ``None``, and + :attr:`obj` was a tensor with requires_grad set), 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: ``None``, which causes requires_grad for the returned tensor to be + inferred from :attr:`obj`. 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, requires_grad=False) + >>> 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=) + >>> # Shares memory with tensor 'b', retaining autograd history + >>> e = torch.asarray(b) + >>> e + tensor([3., 4., 5.], grad_fn=) + + >>> array = numpy.array([1, 2, 3]) + >>> # Shares memory with array 'array' + >>> t1 = torch.asarray(array) + >>> array.__array_interface__['data'][0] == t1.data_ptr() + True + >>> # Copies memory due to dtype mismatch + >>> t2 = torch.asarray(array, dtype=torch.float32) + >>> array.__array_interface__['data'][0] == t2.data_ptr() + False + + >>> scalar = numpy.float64(0.5) + >>> torch.asarray(scalar) + tensor(0.5000, dtype=torch.float64) + """ + +def asin(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + asin(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the arcsine of the elements (in radians) in the :attr:`input` tensor. + + .. math:: + \text{out}_{i} = \sin^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.5962, 1.4985, -0.4396, 1.4525]) + >>> torch.asin(a) + tensor([-0.6387, nan, -0.4552, nan]) + """ + +def asin_(input: Tensor) -> Tensor: + r""" + asin_(input) -> Tensor + + In-place version of :func:`torch.asin` + """ + +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: + r""" + asinh_(input) -> Tensor + + In-place version of :func:`torch.asinh` + """ + +def atan(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + atan(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the arctangent of the elements (in radians) in the :attr:`input` tensor. + + .. math:: + \text{out}_{i} = \tan^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.2341, 0.2539, -0.6256, -0.6448]) + >>> torch.atan(a) + tensor([ 0.2299, 0.2487, -0.5591, -0.5727]) + """ + +def atan2( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + atan2(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + + Element-wise arctangent of :math:`\text{input}_{i} / \text{other}_{i}` + with consideration of the quadrant. Returns a new tensor with the signed angles + in radians between vector :math:`(\text{other}_{i}, \text{input}_{i})` + and vector :math:`(1, 0)`. (Note that :math:`\text{other}_{i}`, the second + parameter, is the x-coordinate, while :math:`\text{input}_{i}`, the first + parameter, is the y-coordinate.) + + The shapes of ``input`` and ``other`` must be + :ref:`broadcastable `. + + Args: + input (Tensor): the first input tensor + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.9041, 0.0196, -0.3108, -2.4423]) + >>> torch.atan2(a, torch.randn(4)) + tensor([ 0.9833, 0.0811, -1.9743, -1.4151]) + """ + +def atan_(input: Tensor) -> Tensor: + r""" + atan_(input) -> Tensor + + In-place version of :func:`torch.atan` + """ + +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: + r""" + atanh_(input) -> Tensor + + In-place version of :func:`torch.atanh` + """ + +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 | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + batch1: Tensor, + batch2: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, 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 + + 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]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@overload +def baddbmm( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + batch1: Tensor, + batch2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, 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 + + 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]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@overload +def baddbmm( + input: Tensor, + batch1: Tensor, + batch2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, 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 + + 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]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@overload +def baddbmm( + input: Tensor, + batch1: Tensor, + batch2: Tensor, + out_dtype: _dtype, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, 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 + + 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]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@overload +def baddbmm( + beta: Number | _complex | PySymType, + self: Tensor, + batch1: Tensor, + batch2: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, 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 + + 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]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@overload +def baddbmm( + beta: Number | _complex | PySymType, + self: Tensor, + batch1: Tensor, + batch2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, 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 + + 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]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@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 | PySymType, + 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 | PySymType, + *, + 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 | PySymType, + 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 | PySymType, + *, + 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 | PySymType, + 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 | PySymType, + *, + 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 | PySymType, + 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 | PySymType, + *, + 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 | PySymType, + 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 | PySymType, + *, + 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=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 + + 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]) + + .. function:: bmm(input, mat2, out_dtype, *, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the first batch of matrices to be multiplied + mat2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword Args: + out (Tensor, optional): the output tensor. + """ + +@overload +def bmm( + input: Tensor, + mat2: Tensor, + out_dtype: _dtype, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bmm(input, mat2, *, 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 + + 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]) + + .. function:: bmm(input, mat2, out_dtype, *, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the first batch of matrices to be multiplied + mat2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword Args: + out (Tensor, optional): the output tensor. + """ + +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 | PySymType, + 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 + """ + +def cat( + tensors: tuple[Tensor, ...] | list[Tensor], + 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]]) + """ + +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: + r""" + ceil_(input) -> Tensor + + In-place version of :func:`torch.ceil` + """ + +def celu( + input: Tensor, + alpha: Number | _complex | PySymType = 1.0, +) -> Tensor: ... +def celu_( + input: Tensor, + alpha: Number | _complex | PySymType = 1.0, +) -> Tensor: ... +def channel_shuffle(input: Tensor, groups: _int | SymInt) -> Tensor: ... +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 | PySymType | None = None, + max: Number | _complex | PySymType | 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: + r""" + clamp_(input, min=None, max=None) -> Tensor + + In-place version of :func:`torch.clamp` + """ + +@overload +def clamp_( + input: Tensor, + min: Number | _complex | PySymType | None = None, + max: Number | _complex | PySymType | None = None, +) -> Tensor: + r""" + clamp_(input, min=None, max=None) -> Tensor + + In-place version of :func:`torch.clamp` + """ + +@overload +def clamp_max( + input: Tensor, + max: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_max( + input: Tensor, + max: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_max_(input: Tensor, max: Tensor) -> Tensor: ... +@overload +def clamp_max_(input: Tensor, max: Number | _complex | PySymType) -> Tensor: ... +@overload +def clamp_min( + input: Tensor, + min: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_min( + input: Tensor, + min: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_min_(input: Tensor, min: Tensor) -> Tensor: ... +@overload +def clamp_min_(input: Tensor, min: Number | _complex | PySymType) -> 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 | PySymType | None = None, + max: Number | _complex | PySymType | 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: + r""" + clip_(input, min=None, max=None) -> Tensor + + In-place version of :func:`torch.clip` + """ + +@overload +def clip_( + input: Tensor, + min: Number | _complex | PySymType | None = None, + max: Number | _complex | PySymType | None = None, +) -> Tensor: + r""" + clip_(input, min=None, max=None) -> Tensor + + In-place version of :func:`torch.clip` + """ + +def clone( + input: Tensor, + *, + memory_format: memory_format | None = None, +) -> Tensor: + r""" + clone(input, *, memory_format=torch.preserve_format) -> Tensor + + Returns a copy of :attr:`input`. + + .. note:: + + This function is differentiable, so gradients will flow back from the + result of this operation to :attr:`input`. To create a tensor without an + autograd relationship to :attr:`input` see :meth:`~Tensor.detach`. + + In addition, when ``torch.preserve_format`` is used: + If the input tensor is dense (i.e., non-overlapping strided), + its memory format (including strides) is retained. + Otherwise (e.g., a non-dense view like a stepped slice), + the output is converted to the dense (contiguous) format. + + Args: + input (Tensor): the input tensor. + + Keyword args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned tensor. Default: ``torch.preserve_format``. + """ + +def col_indices_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.col_indices`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def column_stack( + tensors: tuple[Tensor, ...] | list[Tensor], + *, + 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 + """ + +def concat( + tensors: tuple[Tensor, ...] | list[Tensor], + dim: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + concat(tensors, dim=0, *, out=None) -> Tensor + + Alias of :func:`torch.cat`. + """ + +def concatenate( + tensors: tuple[Tensor, ...] | list[Tensor], + dim: _int = 0, + *, + 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: + r""" + conj_physical_(input) -> Tensor + + In-place version of :func:`torch.conj_physical` + """ + +def constant_pad_nd( + input: Tensor, + pad: Sequence[_int | SymInt], + value: Number | _complex | PySymType = 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 | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + copysign(input, other, *, out=None) -> Tensor + + Create a new floating-point tensor with the magnitude of :attr:`input` and the sign of :attr:`other`, elementwise. + + .. math:: + \text{out}_{i} = \begin{cases} + -|\text{input}_{i}| & \text{if } \text{other}_{i} \leq -0.0 \\ + |\text{input}_{i}| & \text{if } \text{other}_{i} \geq 0.0 \\ + \end{cases} + + + Supports :ref:`broadcasting to a common shape `, + and integer and float inputs. + + Args: + input (Tensor): magnitudes. + other (Tensor or Number): contains value(s) whose signbit(s) are + applied to the magnitudes in :attr:`input`. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(5) + >>> a + tensor([-1.2557, -0.0026, -0.5387, 0.4740, -0.9244]) + >>> torch.copysign(a, 1) + tensor([1.2557, 0.0026, 0.5387, 0.4740, 0.9244]) + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.7079, 0.2778, -1.0249, 0.5719], + [-0.0059, -0.2600, -0.4475, -1.3948], + [ 0.3667, -0.9567, -2.5757, -0.1751], + [ 0.2046, -0.0742, 0.2998, -0.1054]]) + >>> b = torch.randn(4) + tensor([ 0.2373, 0.3120, 0.3190, -1.1128]) + >>> torch.copysign(a, b) + tensor([[ 0.7079, 0.2778, 1.0249, -0.5719], + [ 0.0059, 0.2600, 0.4475, -1.3948], + [ 0.3667, 0.9567, 2.5757, -0.1751], + [ 0.2046, 0.0742, 0.2998, -0.1054]]) + >>> a = torch.tensor([1.]) + >>> b = torch.tensor([-0.]) + >>> torch.copysign(a, b) + tensor([-1.]) + + .. note:: + copysign handles signed zeros. If the other argument has a negative zero (-0), + the corresponding output value will be negative. + """ + +def corrcoef(input: Tensor) -> Tensor: + r""" + corrcoef(input) -> Tensor + + Estimates the Pearson product-moment correlation coefficient matrix of the variables given by the :attr:`input` matrix, + where rows are the variables and columns are the observations. + + .. note:: + + The correlation coefficient matrix R is computed using the covariance matrix C as given by + :math:`R_{ij} = \frac{ C_{ij} } { \sqrt{ C_{ii} * C_{jj} } }` + + .. note:: + + Due to floating point rounding, the resulting array may not be Hermitian and its diagonal elements may not be 1. + The real and imaginary values are clipped to the interval [-1, 1] in an attempt to improve this situation. + + Args: + input (Tensor): A 2D matrix containing multiple variables and observations, or a + Scalar or 1D vector representing a single variable. + + Returns: + (Tensor) The correlation coefficient matrix of the variables. + + .. seealso:: + + :func:`torch.cov` covariance matrix. + + Example:: + + >>> x = torch.tensor([[0, 1, 2], [2, 1, 0]]) + >>> torch.corrcoef(x) + tensor([[ 1., -1.], + [-1., 1.]]) + >>> x = torch.randn(2, 4) + >>> x + tensor([[-0.2678, -0.0908, -0.3766, 0.2780], + [-0.5812, 0.1535, 0.2387, 0.2350]]) + >>> torch.corrcoef(x) + tensor([[1.0000, 0.3582], + [0.3582, 1.0000]]) + >>> torch.corrcoef(x[0]) + tensor(1.) + """ + +def cos(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + cos(input, *, out=None) -> Tensor + + Returns a new tensor with the cosine of the elements of :attr:`input` given in radians. + + .. math:: + \text{out}_{i} = \cos(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 1.4309, 1.2706, -0.8562, 0.9796]) + >>> torch.cos(a) + tensor([ 0.1395, 0.2957, 0.6553, 0.5574]) + """ + +def cos_(input: Tensor) -> Tensor: + r""" + cos_(input) -> Tensor + + In-place version of :func:`torch.cos` + """ + +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]) + """ + +def cosh_(input: Tensor) -> Tensor: + r""" + cosh_(input) -> Tensor + + In-place version of :func:`torch.cosh` + """ + +def cosine_embedding_loss( + input1: Tensor, + input2: Tensor, + target: Tensor, + margin: _float = 0.0, + reduction: _int = 1, +) -> Tensor: ... +def cosine_similarity( + x1: Tensor, + x2: Tensor, + dim: _int = 1, + eps: _float = 1e-08, +) -> Tensor: ... +@overload +def count_nonzero(input: Tensor, dim: _int | None = None) -> Tensor: + r""" + count_nonzero(input, dim=None) -> Tensor + + Counts the number of non-zero values in the tensor :attr:`input` along the given :attr:`dim`. + If no dim is specified then all non-zeros in the tensor are counted. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): Dim or tuple of dims along which to count non-zeros. + + Example:: + + >>> x = torch.zeros(3,3) + >>> x[torch.randn(3,3) > 0.5] = 1 + >>> x + tensor([[0., 1., 1.], + [0., 0., 0.], + [0., 0., 1.]]) + >>> torch.count_nonzero(x) + tensor(3) + >>> torch.count_nonzero(x, dim=0) + tensor([0, 1, 2]) + """ + +@overload +def count_nonzero(input: Tensor, dim: _size) -> Tensor: + r""" + count_nonzero(input, dim=None) -> Tensor + + Counts the number of non-zero values in the tensor :attr:`input` along the given :attr:`dim`. + If no dim is specified then all non-zeros in the tensor are counted. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): Dim or tuple of dims along which to count non-zeros. + + Example:: + + >>> x = torch.zeros(3,3) + >>> x[torch.randn(3,3) > 0.5] = 1 + >>> x + tensor([[0., 1., 1.], + [0., 0., 0.], + [0., 0., 1.]]) + >>> torch.count_nonzero(x) + tensor(3) + >>> torch.count_nonzero(x, dim=0) + tensor([0, 1, 2]) + """ + +def cov( + input: Tensor, + *, + correction: _int = 1, + fweights: Tensor | None = None, + aweights: Tensor | None = None, +) -> Tensor: + r""" + cov(input, *, correction=1, fweights=None, aweights=None) -> Tensor + + Estimates the covariance matrix of the variables given by the :attr:`input` matrix, where rows are + the variables and columns are the observations. + + A covariance matrix is a square matrix giving the covariance of each pair of variables. The diagonal contains + the variance of each variable (covariance of a variable with itself). By definition, if :attr:`input` represents + a single variable (Scalar or 1D) then its variance is returned. + + The sample covariance of the variables :math:`x` and :math:`y` is given by: + + .. math:: + \text{cov}(x,y) = \frac{\sum^{N}_{i = 1}(x_{i} - \bar{x})(y_{i} - \bar{y})}{\max(0,~N~-~\delta N)} + + where :math:`\bar{x}` and :math:`\bar{y}` are the simple means of the :math:`x` and :math:`y` respectively, and + :math:`\delta N` is the :attr:`correction`. + + If :attr:`fweights` and/or :attr:`aweights` are provided, the weighted covariance + is calculated, which is given by: + + .. math:: + \text{cov}_w(x,y) = \frac{\sum^{N}_{i = 1}w_i(x_{i} - \mu_x^*)(y_{i} - \mu_y^*)} + {\max(0,~\sum^{N}_{i = 1}w_i~-~\frac{\sum^{N}_{i = 1}w_ia_i}{\sum^{N}_{i = 1}w_i}~\delta N)} + + where :math:`w` denotes :attr:`fweights` or :attr:`aweights` (``f`` and ``a`` for brevity) based on whichever is + provided, or :math:`w = f \times a` if both are provided, and + :math:`\mu_x^* = \frac{\sum^{N}_{i = 1}w_ix_{i} }{\sum^{N}_{i = 1}w_i}` is the weighted mean of the variable. If not + provided, ``f`` and/or ``a`` can be seen as a :math:`\mathbb{1}` vector of appropriate size. + + Args: + input (Tensor): A 2D matrix containing multiple variables and observations, or a + Scalar or 1D vector representing a single variable. + + Keyword Args: + correction (int, optional): difference between the sample size and sample degrees of freedom. + Defaults to Bessel's correction, ``correction = 1`` which returns the unbiased estimate, + even if both :attr:`fweights` and :attr:`aweights` are specified. ``correction = 0`` + will return the simple average. Defaults to ``1``. + fweights (tensor, optional): A Scalar or 1D tensor of observation vector frequencies representing the number of + times each observation should be repeated. Its numel must equal the number of columns of :attr:`input`. + Must have integral dtype. Ignored if ``None``. Defaults to ``None``. + aweights (tensor, optional): A Scalar or 1D array of observation vector weights. + These relative weights are typically large for observations considered "important" and smaller for + observations considered less "important". Its numel must equal the number of columns of :attr:`input`. + Must have floating point dtype. Ignored if ``None``. Defaults to ``None``. + + Returns: + (Tensor) The covariance matrix of the variables. + + .. seealso:: + + :func:`torch.corrcoef` normalized covariance matrix. + + Example:: + + >>> x = torch.tensor([[0, 2], [1, 1], [2, 0]]).T + >>> x + tensor([[0, 1, 2], + [2, 1, 0]]) + >>> torch.cov(x) + tensor([[ 1., -1.], + [-1., 1.]]) + >>> torch.cov(x, correction=0) + tensor([[ 0.6667, -0.6667], + [-0.6667, 0.6667]]) + >>> fw = torch.randint(1, 10, (3,)) + >>> fw + tensor([1, 6, 9]) + >>> aw = torch.rand(3) + >>> aw + tensor([0.4282, 0.0255, 0.4144]) + >>> torch.cov(x, fweights=fw, aweights=aw) + tensor([[ 0.4169, -0.4169], + [-0.4169, 0.4169]]) + """ + +def cross( + input: Tensor, + other: Tensor, + dim: _int | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + cross(input, other, dim=None, *, out=None) -> Tensor + + + Returns the cross product of vectors in dimension :attr:`dim` of :attr:`input` + and :attr:`other`. + + Supports input of float, double, cfloat and cdouble dtypes. Also supports batches + of vectors, for which it computes the product along the dimension :attr:`dim`. + In this case, the output has the same batch dimensions as the inputs. + + .. warning:: + If :attr:`dim` is not given, it defaults to the first dimension found + with the size 3. Note that this might be unexpected. + + This behavior is deprecated and will be changed to match that of :func:`torch.linalg.cross` + in a future release. + + .. seealso:: + :func:`torch.linalg.cross` which has dim=-1 as default. + + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + dim (int, optional): the dimension to take the cross-product in. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 3) + >>> a + tensor([[-0.3956, 1.1455, 1.6895], + [-0.5849, 1.3672, 0.3599], + [-1.1626, 0.7180, -0.0521], + [-0.1339, 0.9902, -2.0225]]) + >>> b = torch.randn(4, 3) + >>> b + tensor([[-0.0257, -1.4725, -1.2251], + [-1.1479, -0.7005, -1.9757], + [-1.3904, 0.3726, -1.1836], + [-0.9688, -0.7153, 0.2159]]) + >>> torch.cross(a, b, dim=1) + tensor([[ 1.0844, -0.5281, 0.6120], + [-2.4490, -1.5687, 1.9792], + [-0.8304, -1.3037, 0.5650], + [-1.2329, 1.9883, 1.0551]]) + >>> torch.cross(a, b) + tensor([[ 1.0844, -0.5281, 0.6120], + [-2.4490, -1.5687, 1.9792], + [-0.8304, -1.3037, 0.5650], + [-1.2329, 1.9883, 1.0551]]) + """ + +def crow_indices_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.crow_indices`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int = 0, + reduction: _int = 1, + zero_infinity: _bool = False, +) -> Tensor: ... +@overload +def ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int = 0, + reduction: _int = 1, + zero_infinity: _bool = False, +) -> Tensor: ... +def cudnn_affine_grid_generator( + theta: Tensor, + N: _int, + C: _int, + H: _int, + W: _int, +) -> Tensor: ... +def cudnn_batch_norm( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: _bool, + exponential_average_factor: _float, + epsilon: _float, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +def cudnn_convolution( + input: Tensor, + weight: Tensor, + padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, + allow_tf32: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def cudnn_convolution_add_relu( + input: Tensor, + weight: Tensor, + z: Tensor, + alpha: Number | _complex | PySymType | 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: ... +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])) + """ + +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])) + """ + +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]) + """ + +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 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 | PySymType = 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: + r""" + deg2rad_(input) -> Tensor + + In-place version of :func:`torch.deg2rad` + """ + +@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], +) -> 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: + r""" + detach_(input) -> Tensor + + In-place version of :func:`torch.detach` + """ + +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]]) + """ + +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]]]) + """ + +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 | PySymType = 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 | PySymType, + *, + 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 | PySymType) -> 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], + *, + 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]]) + """ + +def empty_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns an uninitialized tensor with the same size as :attr:`input`. + ``torch.empty_like(input)`` is equivalent to + ``torch.empty(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + When ``torch.preserve_format`` is used: + If the input tensor is dense (i.e., non-overlapping strided), + its memory format (including strides) is retained. + Otherwise (e.g., a non-dense view like a stepped slice), + the output is converted to the dense format. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + Example:: + + >>> a=torch.empty((2,3), dtype=torch.int32, device = 'cuda') + >>> torch.empty_like(a) + tensor([[0, 0, 0], + [0, 0, 0]], device='cuda:0', dtype=torch.int32) + """ + +def empty_permuted( + size: Sequence[_int | SymInt], + physical_layout: _size, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty_permuted(size, physical_layout, *, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Creates an uninitialized, non-overlapping and dense tensor with the + specified :attr:`size`, with :attr:`physical_layout` specifying how the + dimensions are physically laid out in memory (each logical dimension is listed + from outermost to innermost). :attr:`physical_layout` is a generalization + of NCHW/NHWC notation: if each dimension is assigned a number according to + what order they occur in size (N=0, C=1, H=2, W=3), then NCHW is ``(0, 1, 2, 3)`` + while NHWC is ``(0, 2, 3, 1)``. Equivalently, the strides of the output + tensor ``t`` are such that ``t.stride(physical_layout[i]) == contiguous_strides[i]`` + (notably, this function is *not* equivalent to ``torch.empty(size).permute(physical_layout)``). + + Unlike :func:`torch.empty_strided`, this is guaranteed to produce a dense + tensor with no overlaps. If possible, prefer using this function over + :func:`torch.empty_strided` or manual use of :func:`torch.as_strided`. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (tuple of int): the shape of the output tensor + physical_layout (tuple of int): the ordering of dimensions physically in memory + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Examples: + + >>> torch.empty((2, 3, 5, 7)).stride() + (105, 35, 7, 1) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 1, 2, 3)).stride() + (105, 35, 7, 1) + >>> torch.empty((2, 3, 5, 7), memory_format=torch.channels_last).stride() + (105, 1, 21, 3) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 2, 3, 1)).stride() + (105, 1, 21, 3) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 2, 3, 1)).dim_order() + (0, 2, 3, 1) + """ + +def empty_quantized( + size: _size, + qtensor: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +def empty_strided( + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty_strided(size, stride, *, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Creates a tensor with the specified :attr:`size` and :attr:`stride` and filled with undefined data. + + .. warning:: + If the constructed tensor is "overlapped" (with multiple indices referring to the same element + in memory) its behavior is undefined. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (tuple of int): the shape of the output tensor + stride (tuple of int): the strides of the output tensor + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> a = torch.empty_strided((2, 3), (1, 2)) + >>> a + tensor([[8.9683e-44, 4.4842e-44, 5.1239e+07], + [0.0000e+00, 0.0000e+00, 3.0705e-41]]) + >>> a.stride() + (1, 2) + >>> a.size() + torch.Size([2, 3]) + """ + +@overload +def eq( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + eq(input, other, *, out=None) -> Tensor + + Computes element-wise equality + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.eq(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[ True, False], + [False, True]]) + """ + +@overload +def eq( + input: Tensor, + other: Number | _complex | PySymType, + *, + 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: + r""" + erf_(input) -> Tensor + + In-place version of :func:`torch.erf` + """ + +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: + r""" + erfc_(input) -> Tensor + + In-place version of :func:`torch.erfc` + """ + +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: + r""" + exp2_(input) -> Tensor + + In-place version of :func:`torch.exp2` + """ + +def exp_(input: Tensor) -> Tensor: + r""" + exp_(input) -> Tensor + + In-place version of :func:`torch.exp` + """ + +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: + r""" + expm1_(input) -> Tensor + + In-place version of :func:`torch.expm1` + """ + +@overload +def eye( + n: _int | SymInt, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + eye(n, m=None, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 2-D tensor with ones on the diagonal and zeros elsewhere. + + Args: + n (int): the number of rows + m (int, optional): the number of columns with default being :attr:`n` + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 2-D tensor with ones on the diagonal and zeros elsewhere + + Example:: + + >>> torch.eye(3) + tensor([[ 1., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 1.]]) + """ + +@overload +def eye( + n: _int | SymInt, + m: _int | SymInt, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + eye(n, m=None, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 2-D tensor with ones on the diagonal and zeros elsewhere. + + Args: + n (int): the number of rows + m (int, optional): the number of columns with default being :attr:`n` + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 2-D tensor with ones on the diagonal and zeros elsewhere + + Example:: + + >>> torch.eye(3) + tensor([[ 1., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 1.]]) + """ + +def fake_quantize_per_channel_affine( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + axis: _int, + quant_min: _int, + quant_max: _int, +) -> Tensor: + r""" + fake_quantize_per_channel_affine(input, scale, zero_point, axis, quant_min, quant_max) -> Tensor + + Returns a new tensor with the data in :attr:`input` fake quantized per channel using :attr:`scale`, + :attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`, across the channel specified by :attr:`axis`. + + .. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + + Args: + input (Tensor): the input value(s), in ``torch.float32`` + scale (Tensor): quantization scale, per channel in ``torch.float32`` + zero_point (Tensor): quantization zero_point, per channel in ``torch.int32`` or ``torch.half`` or ``torch.float32`` + axis (int32): channel axis + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + + Returns: + Tensor: A newly fake_quantized per channel ``torch.float32`` tensor + + Example:: + + >>> x = torch.randn(2, 2, 2) + >>> x + tensor([[[-0.2525, -0.0466], + [ 0.3491, -0.2168]], + + [[-0.5906, 1.6258], + [ 0.6444, -0.0542]]]) + >>> scales = (torch.randn(2) + 1) * 0.05 + >>> scales + tensor([0.0475, 0.0486]) + >>> zero_points = torch.zeros(2).to(torch.int32) + >>> zero_points + tensor([0, 0]) + >>> torch.fake_quantize_per_channel_affine(x, scales, zero_points, 1, 0, 255) + tensor([[[0.0000, 0.0000], + [0.3405, 0.0000]], + + [[0.0000, 1.6134], + [0.6323, 0.0000]]]) + """ + +@overload +def fake_quantize_per_tensor_affine( + input: Tensor, + scale: _float, + zero_point: _int, + quant_min: _int, + quant_max: _int, +) -> Tensor: + r""" + fake_quantize_per_tensor_affine(input, scale, zero_point, quant_min, quant_max) -> Tensor + + Returns a new tensor with the data in :attr:`input` fake quantized using :attr:`scale`, + :attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`. + + .. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + + Args: + input (Tensor): the input value(s), ``torch.float32`` tensor + scale (double scalar or ``float32`` Tensor): quantization scale + zero_point (int64 scalar or ``int32`` Tensor): quantization zero_point + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + + Returns: + Tensor: A newly fake_quantized ``torch.float32`` tensor + + Example:: + + >>> x = torch.randn(4) + >>> x + tensor([ 0.0552, 0.9730, 0.3973, -1.0780]) + >>> torch.fake_quantize_per_tensor_affine(x, 0.1, 0, 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + >>> torch.fake_quantize_per_tensor_affine(x, torch.tensor(0.1), torch.tensor(0), 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + """ + +@overload +def fake_quantize_per_tensor_affine( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + quant_min: _int, + quant_max: _int, +) -> Tensor: + r""" + fake_quantize_per_tensor_affine(input, scale, zero_point, quant_min, quant_max) -> Tensor + + Returns a new tensor with the data in :attr:`input` fake quantized using :attr:`scale`, + :attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`. + + .. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + + Args: + input (Tensor): the input value(s), ``torch.float32`` tensor + scale (double scalar or ``float32`` Tensor): quantization scale + zero_point (int64 scalar or ``int32`` Tensor): quantization zero_point + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + + Returns: + Tensor: A newly fake_quantized ``torch.float32`` tensor + + Example:: + + >>> x = torch.randn(4) + >>> x + tensor([ 0.0552, 0.9730, 0.3973, -1.0780]) + >>> torch.fake_quantize_per_tensor_affine(x, 0.1, 0, 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + >>> torch.fake_quantize_per_tensor_affine(x, torch.tensor(0.1), torch.tensor(0), 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + """ + +@overload +def fbgemm_linear_fp16_weight( + input: Tensor, + packed_weight: Tensor, + bias: Tensor, +) -> Tensor: ... +@overload +def fbgemm_linear_fp16_weight( + input: Tensor, + packed_weight: Tensor, + bias: Tensor, + output: Tensor, +) -> Tensor: ... +@overload +def fbgemm_linear_fp16_weight_fp32_activation( + input: Tensor, + packed_weight: Tensor, + bias: Tensor | None, +) -> Tensor: ... +@overload +def fbgemm_linear_fp16_weight_fp32_activation( + input: Tensor, + packed_weight: Tensor, + bias: Tensor | None, + output: Tensor, +) -> Tensor: ... +def fbgemm_linear_int8_weight( + input: Tensor, + weight: Tensor, + packed: Tensor, + col_offsets: Tensor, + weight_scale: Number | _complex | PySymType, + weight_zero_point: Number | _complex | PySymType, + bias: Tensor, +) -> Tensor: ... +def fbgemm_linear_int8_weight_fp32_activation( + input: Tensor, + weight: Tensor, + packed: Tensor, + col_offsets: Tensor, + weight_scale: Number | _complex | PySymType, + weight_zero_point: Number | _complex | PySymType, + 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: + r""" + feature_alpha_dropout_(input, p, train) -> Tensor + + In-place version of :func:`torch.feature_alpha_dropout` + """ + +def feature_dropout(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def feature_dropout_(input: Tensor, p: _float, train: _bool) -> Tensor: + r""" + feature_dropout_(input, p, train) -> Tensor + + In-place version of :func:`torch.feature_dropout` + """ + +@overload +def fill(input: Tensor, value: Tensor) -> Tensor: ... +@overload +def fill(input: Tensor, value: Number | _complex | PySymType) -> Tensor: ... +@overload +def fill_(input: Tensor, value: Tensor) -> Tensor: + r""" + fill_(input, value) -> Tensor + + In-place version of :func:`torch.fill` + """ + +@overload +def fill_(input: Tensor, value: Number | _complex | PySymType) -> Tensor: + r""" + fill_(input, value) -> Tensor + + In-place version of :func:`torch.fill` + """ + +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: + r""" + fix_(input) -> Tensor + + In-place version of :func:`torch.fix` + """ + +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]]) + """ + +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 | PySymType, + 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 | PySymType, + *, + 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: + r""" + floor_(input) -> Tensor + + In-place version of :func:`torch.floor` + """ + +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 | PySymType, + *, + 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: + r""" + frac_(input) -> Tensor + + In-place version of :func:`torch.frac` + """ + +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 | PySymType, + *, + 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]]) + """ + +def full_like( + input: Tensor, + fill_value: Number | _complex | PySymType, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + full_like(input, fill_value, \*, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` filled with :attr:`fill_value`. + ``torch.full_like(input, fill_value)`` is equivalent to + ``torch.full(input.size(), fill_value, dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + fill_value: the number to fill the output tensor with. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + Example:: + + >>> x = torch.ones(2, 3) + >>> torch.full_like(x, 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) + >>> torch.full_like(x, 7) + tensor([[7., 7., 7.], + [7., 7., 7.]]) + >>> torch.full_like(x, 0.5, dtype=torch.int32) + tensor([[0, 0, 0], + [0, 0, 0]], dtype=torch.int32) + >>> y = torch.randn(3, 4, dtype=torch.float64) + >>> torch.full_like(y, -1.0) + tensor([[-1., -1., -1., -1.], + [-1., -1., -1., -1.], + [-1., -1., -1., -1.]], dtype=torch.float64) + """ + +def fused_moving_avg_obs_fake_quant( + input: Tensor, + observer_on: Tensor, + fake_quant_on: Tensor, + running_min: Tensor, + running_max: Tensor, + scale: Tensor, + zero_point: Tensor, + averaging_const: _float, + quant_min: _int, + quant_max: _int, + ch_axis: _int, + per_row_fake_quant: _bool = False, + symmetric_quant: _bool = False, +) -> Tensor: ... +def gather( + input: Tensor, + dim: _int, + index: Tensor, + *, + sparse_grad: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + gather(input, dim, index, *, sparse_grad=False, out=None) -> Tensor + + Gathers values along an axis specified by `dim`. + + For a 3-D tensor the output is specified by:: + + out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0 + out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1 + out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2 + + :attr:`input` and :attr:`index` must have the same number of dimensions. + It is also required that ``index.size(d) <= input.size(d)`` for all + dimensions ``d != dim``. :attr:`out` will have the same shape as :attr:`index`. + Note that ``input`` and ``index`` do not broadcast against each other. + When :attr:`index` is empty, we always return an empty output with the same shape + without further error checking. + + Args: + input (Tensor): the source tensor + dim (int): the axis along which to index + index (LongTensor): the indices of elements to gather + + Keyword arguments: + sparse_grad (bool, optional): If ``True``, gradient w.r.t. :attr:`input` will be a sparse tensor. + out (Tensor, optional): the destination tensor + + Example:: + + >>> t = torch.tensor([[1, 2], [3, 4]]) + >>> torch.gather(t, 1, torch.tensor([[0, 0], [1, 0]])) + tensor([[ 1, 1], + [ 4, 3]]) + """ + +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: + r""" + gcd_(input, other) -> Tensor + + In-place version of :func:`torch.gcd` + """ + +@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 | PySymType, + *, + 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 | PySymType | None = None, + dim: _int | None = None, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: Sequence[Number | _complex | PySymType], + dim: _int | None = None, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: Sequence[Number | _complex | PySymType], + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: tuple[Tensor, ...] | list[Tensor], + dim: _int | None = None, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: Number | _complex | PySymType, + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: tuple[Tensor, ...] | list[Tensor], + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def greater( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + greater(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.gt`. + """ + +@overload +def greater( + input: Tensor, + other: Number | _complex | PySymType, + *, + 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 | PySymType, + *, + 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], + 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], + 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 | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + gt(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} > \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is greater than :attr:`other` and False elsewhere + + Example:: + + >>> torch.gt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [False, False]]) + """ + +@overload +def hamming_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hamming_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hamming_window( + window_length: _int, + periodic: _bool, + alpha: _float, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hamming_window( + window_length: _int, + periodic: _bool, + alpha: _float, + beta: _float, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hann_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hann_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Hann window function. + + .. math:: + w[n] = \frac{1}{2}\ \left[1 - \cos \left( \frac{2 \pi n}{N - 1} \right)\right] = + \sin^2 \left( \frac{\pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hann_window(L, periodic=True)`` equal to + ``torch.hann_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +@overload +def hann_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hann_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Hann window function. + + .. math:: + w[n] = \frac{1}{2}\ \left[1 - \cos \left( \frac{2 \pi n}{N - 1} \right)\right] = + \sin^2 \left( \frac{\pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hann_window(L, periodic=True)`` equal to + ``torch.hann_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +def hardshrink( + input: Tensor, + lambd: Number | _complex | PySymType = 0.5, + *, + out: Tensor | None = None, +) -> Tensor: ... +def hash_tensor( + input: Tensor, + dim: _int | _size = (), + *, + keepdim: _bool = False, + mode: _int = 0, + out: Tensor | None = None, +) -> Tensor: + r""" + hash_tensor(input, *, mode=0) -> Tensor + + Returns a hash of all elements in the :attr:`input` tensor. + + Currently only mode=0 (reduction via xor) is supported. The output will always + be of type ``torch.uint64``. The elements of ``input`` are upcasted to their + 64 bit float / integer equivalent and bitcasted to ``torch.uint64`` before + reduction via xor. + + Args: + input (Tensor): the input tensor. + + Keyword Args: + mode (int) : The hash to use. Default: 0 (xor_reduction) + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 1.1918, -1.1813, 0.3373]]) + >>> torch.hash_tensor(a) + tensor(13822780554648485888, dtype=torch.uint64) + + .. function:: hash_tensor(input, dim, *, keepdim=False, mode=0) -> Tensor + :noindex: + + Returns the hash of each row of the :attr:`input` tensor in the given + dimension :attr:`dim` given by mode. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword Args: + mode (int) : The hash to use. Default: 0 (xor_reduction) + + Example:: + + >>> a = torch.randn(2, 4) + >>> a + tensor([[ 0.1317, -0.5554, -1.4724, -1.1391], + [ 0.0778, -0.6070, 0.6375, 0.1798]]) + >>> torch.hash_tensor(a, 1) + tensor([9233691267014066176, 9255993250844508160], dtype=torch.uint64) + """ + +def heaviside( + input: Tensor, + values: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + heaviside(input, values, *, out=None) -> Tensor + + Computes the Heaviside step function for each element in :attr:`input`. + The Heaviside step function is defined as: + + .. math:: + \text{{heaviside}}(input, values) = \begin{cases} + 0, & \text{if input < 0}\\ + values, & \text{if input == 0}\\ + 1, & \text{if input > 0} + \end{cases} + + + Args: + input (Tensor): the input tensor. + values (Tensor): The values to use where :attr:`input` is zero. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> input = torch.tensor([-1.5, 0, 2.0]) + >>> values = torch.tensor([0.5]) + >>> torch.heaviside(input, values) + tensor([0.0000, 0.5000, 1.0000]) + >>> values = torch.tensor([1.2, -2.0, 3.5]) + >>> torch.heaviside(input, values) + tensor([0., -2., 1.]) + """ + +def hinge_embedding_loss( + input: Tensor, + target: Tensor, + margin: _float = 1.0, + reduction: _int = 1, +) -> Tensor: ... +def histc( + input: Tensor, + bins: _int = 100, + min: Number | _complex | PySymType = 0, + max: Number | _complex | PySymType = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + histc(input, bins=100, min=0, max=0, *, out=None) -> Tensor + + Computes the histogram of a tensor. + + The elements are sorted into equal width bins between :attr:`min` and + :attr:`max`. If :attr:`min` and :attr:`max` are both zero, the minimum and + maximum values of the data are used. + + Elements lower than min and higher than max and ``NaN`` elements are ignored. + + Args: + input (Tensor): the input tensor. + bins (int): number of histogram bins + min (Scalar): lower end of the range (inclusive) + max (Scalar): upper end of the range (inclusive) + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: Histogram represented as a tensor + + Example:: + + >>> torch.histc(torch.tensor([1., 2, 1]), bins=4, min=0, max=3) + tensor([ 0., 2., 1., 0.]) + """ + +@overload +def histogram( + input: Tensor, + bins: Tensor, + *, + weight: Tensor | None = None, + density: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.histogram: + r""" + histogram(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor) + + Computes a histogram of the values in a tensor. + + :attr:`bins` can be an integer or a 1D tensor. + + If :attr:`bins` is an int, it specifies the number of equal-width bins. + By default, the lower and upper range of the bins is determined by the + minimum and maximum elements of the input tensor. The :attr:`range` + argument can be provided to specify a range for the bins. + + If :attr:`bins` is a 1D tensor, it specifies the sequence of bin edges + including the rightmost edge. It should contain at least 2 elements + and its elements should be increasing. + + Args: + input (Tensor): the input tensor. + bins: int or 1D Tensor. If int, defines the number of equal-width bins. If tensor, + defines the sequence of bin edges including the rightmost edge. + + Keyword args: + range (tuple of float): Defines the range of the bins. + weight (Tensor): If provided, weight should have the same shape as input. Each value in + input contributes its associated weight towards its bin's result. + density (bool): If False, the result will contain the count (or total weight) in each bin. + If True, the result is the value of the probability density function over the bins, + normalized such that the integral over the range of the bins is 1. + out (Tensor, optional): the output tensor. (tuple, optional): The result tuple of two output tensors (hist, bin_edges). + + Returns: + hist (Tensor): 1D Tensor containing the values of the histogram. + bin_edges(Tensor): 1D Tensor containing the edges of the histogram bins. + + Example:: + + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.])) + (tensor([ 0., 5., 2., 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.]), density=True) + (tensor([ 0., 0.9524, 0.3810, 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + """ + +@overload +def histogram( + input: Tensor, + bins: _int = 100, + *, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.histogram: + r""" + histogram(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor) + + Computes a histogram of the values in a tensor. + + :attr:`bins` can be an integer or a 1D tensor. + + If :attr:`bins` is an int, it specifies the number of equal-width bins. + By default, the lower and upper range of the bins is determined by the + minimum and maximum elements of the input tensor. The :attr:`range` + argument can be provided to specify a range for the bins. + + If :attr:`bins` is a 1D tensor, it specifies the sequence of bin edges + including the rightmost edge. It should contain at least 2 elements + and its elements should be increasing. + + Args: + input (Tensor): the input tensor. + bins: int or 1D Tensor. If int, defines the number of equal-width bins. If tensor, + defines the sequence of bin edges including the rightmost edge. + + Keyword args: + range (tuple of float): Defines the range of the bins. + weight (Tensor): If provided, weight should have the same shape as input. Each value in + input contributes its associated weight towards its bin's result. + density (bool): If False, the result will contain the count (or total weight) in each bin. + If True, the result is the value of the probability density function over the bins, + normalized such that the integral over the range of the bins is 1. + out (Tensor, optional): the output tensor. (tuple, optional): The result tuple of two output tensors (hist, bin_edges). + + Returns: + hist (Tensor): 1D Tensor containing the values of the histogram. + bin_edges(Tensor): 1D Tensor containing the edges of the histogram bins. + + Example:: + + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.])) + (tensor([ 0., 5., 2., 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.]), density=True) + (tensor([ 0., 0.9524, 0.3810, 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + """ + +@overload +def histogramdd( + input: Tensor, + bins: _int, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> torch.return_types.histogramdd: + r""" + histogramdd(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor[]) + + Computes a multi-dimensional histogram of the values in a tensor. + + Interprets the elements of an input tensor whose innermost dimension has size N + as a collection of N-dimensional points. Maps each of the points into a set of + N-dimensional bins and returns the number of points (or total weight) in each bin. + + :attr:`input` must be a tensor with at least 2 dimensions. + If input has shape (M, N), each of its M rows defines a point in N-dimensional space. + If input has three or more dimensions, all but the last dimension are flattened. + + Each dimension is independently associated with its own strictly increasing sequence + of bin edges. Bin edges may be specified explicitly by passing a sequence of 1D + tensors. Alternatively, bin edges may be constructed automatically by passing a + sequence of integers specifying the number of equal-width bins in each dimension. + + For each N-dimensional point in input: + - Each of its coordinates is binned independently among the bin edges + corresponding to its dimension + - Binning results are combined to identify the N-dimensional bin (if any) + into which the point falls + - If the point falls into a bin, the bin's count (or total weight) is incremented + - Points which do not fall into any bin do not contribute to the output + + :attr:`bins` can be a sequence of N 1D tensors, a sequence of N ints, or a single int. + + If :attr:`bins` is a sequence of N 1D tensors, it explicitly specifies the N sequences + of bin edges. Each 1D tensor should contain a strictly increasing sequence with at + least one element. A sequence of K bin edges defines K-1 bins, explicitly specifying + the left and right edges of all bins. Every bin is inclusive of its left edge. Only + the rightmost bin is inclusive of its right edge. + + If :attr:`bins` is a sequence of N ints, it specifies the number of equal-width bins + in each dimension. By default, the leftmost and rightmost bin edges in each dimension + are determined by the minimum and maximum elements of the input tensor in the + corresponding dimension. The :attr:`range` argument can be provided to manually + specify the leftmost and rightmost bin edges in each dimension. + + If :attr:`bins` is an int, it specifies the number of equal-width bins for all dimensions. + + .. note:: + See also :func:`torch.histogram`, which specifically computes 1D histograms. + While :func:`torch.histogramdd` infers the dimensionality of its bins and + binned values from the shape of :attr:`input`, :func:`torch.histogram` + accepts and flattens :attr:`input` of any shape. + + Args: + input (Tensor): the input tensor. + bins: Tensor[], int[], or int. + If Tensor[], defines the sequences of bin edges. + If int[], defines the number of equal-width bins in each dimension. + If int, defines the number of equal-width bins for all dimensions. + Keyword args: + range (sequence of float): Defines the leftmost and rightmost bin edges + in each dimension. + weight (Tensor): By default, each value in the input has weight 1. If a weight + tensor is passed, each N-dimensional coordinate in input + contributes its associated weight towards its bin's result. + The weight tensor should have the same shape as the :attr:`input` + tensor excluding its innermost dimension N. + density (bool): If False (default), the result will contain the count (or total weight) + in each bin. If True, each count (weight) is divided by the total count + (total weight), then divided by the volume of its associated bin. + Returns: + hist (Tensor): N-dimensional Tensor containing the values of the histogram. + bin_edges(Tensor[]): sequence of N 1D Tensors containing the bin edges. + + Example:: + + >>> torch.histogramdd(torch.tensor([[0., 1.], [1., 0.], [2., 0.], [2., 2.]]), bins=[3, 3], + ... weight=torch.tensor([1., 2., 4., 8.])) + torch.return_types.histogramdd( + hist=tensor([[0., 1., 0.], + [2., 0., 0.], + [4., 0., 8.]]), + bin_edges=(tensor([0.0000, 0.6667, 1.3333, 2.0000]), + tensor([0.0000, 0.6667, 1.3333, 2.0000]))) + + >>> torch.histogramdd(torch.tensor([[0., 0.], [1., 1.], [2., 2.]]), bins=[2, 2], + ... range=[0., 1., 0., 1.], density=True) + torch.return_types.histogramdd( + hist=tensor([[2., 0.], + [0., 2.]]), + bin_edges=(tensor([0.0000, 0.5000, 1.0000]), + tensor([0.0000, 0.5000, 1.0000]))) + """ + +@overload +def histogramdd( + input: Tensor, + bins: _size, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> torch.return_types.histogramdd: + r""" + histogramdd(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor[]) + + Computes a multi-dimensional histogram of the values in a tensor. + + Interprets the elements of an input tensor whose innermost dimension has size N + as a collection of N-dimensional points. Maps each of the points into a set of + N-dimensional bins and returns the number of points (or total weight) in each bin. + + :attr:`input` must be a tensor with at least 2 dimensions. + If input has shape (M, N), each of its M rows defines a point in N-dimensional space. + If input has three or more dimensions, all but the last dimension are flattened. + + Each dimension is independently associated with its own strictly increasing sequence + of bin edges. Bin edges may be specified explicitly by passing a sequence of 1D + tensors. Alternatively, bin edges may be constructed automatically by passing a + sequence of integers specifying the number of equal-width bins in each dimension. + + For each N-dimensional point in input: + - Each of its coordinates is binned independently among the bin edges + corresponding to its dimension + - Binning results are combined to identify the N-dimensional bin (if any) + into which the point falls + - If the point falls into a bin, the bin's count (or total weight) is incremented + - Points which do not fall into any bin do not contribute to the output + + :attr:`bins` can be a sequence of N 1D tensors, a sequence of N ints, or a single int. + + If :attr:`bins` is a sequence of N 1D tensors, it explicitly specifies the N sequences + of bin edges. Each 1D tensor should contain a strictly increasing sequence with at + least one element. A sequence of K bin edges defines K-1 bins, explicitly specifying + the left and right edges of all bins. Every bin is inclusive of its left edge. Only + the rightmost bin is inclusive of its right edge. + + If :attr:`bins` is a sequence of N ints, it specifies the number of equal-width bins + in each dimension. By default, the leftmost and rightmost bin edges in each dimension + are determined by the minimum and maximum elements of the input tensor in the + corresponding dimension. The :attr:`range` argument can be provided to manually + specify the leftmost and rightmost bin edges in each dimension. + + If :attr:`bins` is an int, it specifies the number of equal-width bins for all dimensions. + + .. note:: + See also :func:`torch.histogram`, which specifically computes 1D histograms. + While :func:`torch.histogramdd` infers the dimensionality of its bins and + binned values from the shape of :attr:`input`, :func:`torch.histogram` + accepts and flattens :attr:`input` of any shape. + + Args: + input (Tensor): the input tensor. + bins: Tensor[], int[], or int. + If Tensor[], defines the sequences of bin edges. + If int[], defines the number of equal-width bins in each dimension. + If int, defines the number of equal-width bins for all dimensions. + Keyword args: + range (sequence of float): Defines the leftmost and rightmost bin edges + in each dimension. + weight (Tensor): By default, each value in the input has weight 1. If a weight + tensor is passed, each N-dimensional coordinate in input + contributes its associated weight towards its bin's result. + The weight tensor should have the same shape as the :attr:`input` + tensor excluding its innermost dimension N. + density (bool): If False (default), the result will contain the count (or total weight) + in each bin. If True, each count (weight) is divided by the total count + (total weight), then divided by the volume of its associated bin. + Returns: + hist (Tensor): N-dimensional Tensor containing the values of the histogram. + bin_edges(Tensor[]): sequence of N 1D Tensors containing the bin edges. + + Example:: + + >>> torch.histogramdd(torch.tensor([[0., 1.], [1., 0.], [2., 0.], [2., 2.]]), bins=[3, 3], + ... weight=torch.tensor([1., 2., 4., 8.])) + torch.return_types.histogramdd( + hist=tensor([[0., 1., 0.], + [2., 0., 0.], + [4., 0., 8.]]), + bin_edges=(tensor([0.0000, 0.6667, 1.3333, 2.0000]), + tensor([0.0000, 0.6667, 1.3333, 2.0000]))) + + >>> torch.histogramdd(torch.tensor([[0., 0.], [1., 1.], [2., 2.]]), bins=[2, 2], + ... range=[0., 1., 0., 1.], density=True) + torch.return_types.histogramdd( + hist=tensor([[2., 0.], + [0., 2.]]), + bin_edges=(tensor([0.0000, 0.5000, 1.0000]), + tensor([0.0000, 0.5000, 1.0000]))) + """ + +@overload +def histogramdd( + input: Tensor, + bins: tuple[Tensor, ...] | list[Tensor], + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> torch.return_types.histogramdd: + r""" + histogramdd(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor[]) + + Computes a multi-dimensional histogram of the values in a tensor. + + Interprets the elements of an input tensor whose innermost dimension has size N + as a collection of N-dimensional points. Maps each of the points into a set of + N-dimensional bins and returns the number of points (or total weight) in each bin. + + :attr:`input` must be a tensor with at least 2 dimensions. + If input has shape (M, N), each of its M rows defines a point in N-dimensional space. + If input has three or more dimensions, all but the last dimension are flattened. + + Each dimension is independently associated with its own strictly increasing sequence + of bin edges. Bin edges may be specified explicitly by passing a sequence of 1D + tensors. Alternatively, bin edges may be constructed automatically by passing a + sequence of integers specifying the number of equal-width bins in each dimension. + + For each N-dimensional point in input: + - Each of its coordinates is binned independently among the bin edges + corresponding to its dimension + - Binning results are combined to identify the N-dimensional bin (if any) + into which the point falls + - If the point falls into a bin, the bin's count (or total weight) is incremented + - Points which do not fall into any bin do not contribute to the output + + :attr:`bins` can be a sequence of N 1D tensors, a sequence of N ints, or a single int. + + If :attr:`bins` is a sequence of N 1D tensors, it explicitly specifies the N sequences + of bin edges. Each 1D tensor should contain a strictly increasing sequence with at + least one element. A sequence of K bin edges defines K-1 bins, explicitly specifying + the left and right edges of all bins. Every bin is inclusive of its left edge. Only + the rightmost bin is inclusive of its right edge. + + If :attr:`bins` is a sequence of N ints, it specifies the number of equal-width bins + in each dimension. By default, the leftmost and rightmost bin edges in each dimension + are determined by the minimum and maximum elements of the input tensor in the + corresponding dimension. The :attr:`range` argument can be provided to manually + specify the leftmost and rightmost bin edges in each dimension. + + If :attr:`bins` is an int, it specifies the number of equal-width bins for all dimensions. + + .. note:: + See also :func:`torch.histogram`, which specifically computes 1D histograms. + While :func:`torch.histogramdd` infers the dimensionality of its bins and + binned values from the shape of :attr:`input`, :func:`torch.histogram` + accepts and flattens :attr:`input` of any shape. + + Args: + input (Tensor): the input tensor. + bins: Tensor[], int[], or int. + If Tensor[], defines the sequences of bin edges. + If int[], defines the number of equal-width bins in each dimension. + If int, defines the number of equal-width bins for all dimensions. + Keyword args: + range (sequence of float): Defines the leftmost and rightmost bin edges + in each dimension. + weight (Tensor): By default, each value in the input has weight 1. If a weight + tensor is passed, each N-dimensional coordinate in input + contributes its associated weight towards its bin's result. + The weight tensor should have the same shape as the :attr:`input` + tensor excluding its innermost dimension N. + density (bool): If False (default), the result will contain the count (or total weight) + in each bin. If True, each count (weight) is divided by the total count + (total weight), then divided by the volume of its associated bin. + Returns: + hist (Tensor): N-dimensional Tensor containing the values of the histogram. + bin_edges(Tensor[]): sequence of N 1D Tensors containing the bin edges. + + Example:: + + >>> torch.histogramdd(torch.tensor([[0., 1.], [1., 0.], [2., 0.], [2., 2.]]), bins=[3, 3], + ... weight=torch.tensor([1., 2., 4., 8.])) + torch.return_types.histogramdd( + hist=tensor([[0., 1., 0.], + [2., 0., 0.], + [4., 0., 8.]]), + bin_edges=(tensor([0.0000, 0.6667, 1.3333, 2.0000]), + tensor([0.0000, 0.6667, 1.3333, 2.0000]))) + + >>> torch.histogramdd(torch.tensor([[0., 0.], [1., 1.], [2., 2.]]), bins=[2, 2], + ... range=[0., 1., 0., 1.], density=True) + torch.return_types.histogramdd( + hist=tensor([[2., 0.], + [0., 2.]]), + bin_edges=(tensor([0.0000, 0.5000, 1.0000]), + tensor([0.0000, 0.5000, 1.0000]))) + """ + +def hsmm(input: Tensor, mat2: Tensor) -> Tensor: ... +@overload +def hsplit(input: Tensor, sections: _int) -> tuple[Tensor, ...]: + r""" + hsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with one or more dimensions, into multiple tensors + horizontally according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + If :attr:`input` is one dimensional this is equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=0) (the split dimension is + zero), and if :attr:`input` has two or more dimensions it's equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=1) (the split dimension is 1), + except that if :attr:`indices_or_sections` is an integer it must evenly divide + the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.hsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.hsplit(t, 2) + (tensor([[ 0., 1.], + [ 4., 5.], + [ 8., 9.], + [12., 13.]]), + tensor([[ 2., 3.], + [ 6., 7.], + [10., 11.], + [14., 15.]])) + >>> torch.hsplit(t, [3, 6]) + (tensor([[ 0., 1., 2.], + [ 4., 5., 6.], + [ 8., 9., 10.], + [12., 13., 14.]]), + tensor([[ 3.], + [ 7.], + [11.], + [15.]]), + tensor([], size=(4, 0))) + """ + +@overload +def hsplit(input: Tensor, indices: _size) -> tuple[Tensor, ...]: + r""" + hsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with one or more dimensions, into multiple tensors + horizontally according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + If :attr:`input` is one dimensional this is equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=0) (the split dimension is + zero), and if :attr:`input` has two or more dimensions it's equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=1) (the split dimension is 1), + except that if :attr:`indices_or_sections` is an integer it must evenly divide + the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.hsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.hsplit(t, 2) + (tensor([[ 0., 1.], + [ 4., 5.], + [ 8., 9.], + [12., 13.]]), + tensor([[ 2., 3.], + [ 6., 7.], + [10., 11.], + [14., 15.]])) + >>> torch.hsplit(t, [3, 6]) + (tensor([[ 0., 1., 2.], + [ 4., 5., 6.], + [ 8., 9., 10.], + [12., 13., 14.]]), + tensor([[ 3.], + [ 7.], + [11.], + [15.]]), + tensor([], size=(4, 0))) + """ + +def hspmm( + mat1: Tensor, + mat2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + hspmm(mat1, mat2, *, out=None) -> Tensor + + Performs a matrix multiplication of a :ref:`sparse COO matrix + ` :attr:`mat1` and a strided matrix :attr:`mat2`. The + result is a (1 + 1)-dimensional :ref:`hybrid COO matrix + `. + + Args: + mat1 (Tensor): the first sparse matrix to be matrix multiplied + mat2 (Tensor): the second strided matrix to be matrix multiplied + + Keyword args: + out (Tensor, optional): the output tensor. + """ + +def hstack( + tensors: tuple[Tensor, ...] | list[Tensor], + *, + 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: + r""" + i0_(input) -> Tensor + + In-place version of :func:`torch.i0` + """ + +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]) + """ + +def index_add( + input: Tensor, + dim: _int, + index: Tensor, + source: Tensor, + *, + alpha: Number | _complex | PySymType = 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. + """ + +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_copy_` for function description. + """ + +@overload +def index_fill( + input: Tensor, + dim: _int, + index: Tensor, + value: Tensor, +) -> Tensor: ... +@overload +def index_fill( + input: Tensor, + dim: _int, + index: Tensor, + value: Number | _complex | PySymType, +) -> Tensor: ... +def index_put( + input: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, + values: Tensor, + accumulate: _bool = False, +) -> Tensor: ... +def index_put_( + input: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | 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. + """ + +def index_select( + input: Tensor, + dim: _int, + index: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + index_select(input, dim, index, *, out=None) -> Tensor + + Returns a new tensor which indexes the :attr:`input` tensor along dimension + :attr:`dim` using the entries in :attr:`index`. + + The returned tensor has the same number of dimensions as the original tensor + (:attr:`input`). The :attr:`dim`\ th dimension has the same size as the length + of :attr:`index`; other dimensions have the same size as in the original tensor. + + .. note:: The returned tensor does **not** use the same storage as the original + tensor. If :attr:`out` has a different shape than expected, we + silently change it to the correct shape, reallocating the underlying + storage if necessary. + + Args: + input (Tensor): the input tensor. + dim (int): the dimension in which we index + index (IntTensor or LongTensor): the 1-D tensor containing the indices to index + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(3, 4) + >>> x + tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], + [-0.4664, 0.2647, -0.1228, -1.1068], + [-1.1734, -0.6571, 0.7230, -0.6004]]) + >>> indices = torch.tensor([0, 2]) + >>> torch.index_select(x, 0, indices) + tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], + [-1.1734, -0.6571, 0.7230, -0.6004]]) + >>> torch.index_select(x, 1, indices) + tensor([[ 0.1427, -0.5414], + [-0.4664, -0.1228], + [-1.1734, 0.7230]]) + """ + +def indices_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.indices`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def init_num_threads() -> None: ... +def inner( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + inner(input, other, *, out=None) -> Tensor + + Computes the dot product for 1D tensors. For higher dimensions, sums the product + of elements from :attr:`input` and :attr:`other` along their last dimension. + + .. note:: + + If either :attr:`input` or :attr:`other` is a scalar, the result is equivalent + to `torch.mul(input, other)`. + + If both :attr:`input` and :attr:`other` are non-scalars, the size of their last + dimension must match and the result is equivalent to `torch.tensordot(input, + other, dims=([-1], [-1]))` + + Args: + input (Tensor): First input tensor + other (Tensor): Second input tensor + + Keyword args: + out (Tensor, optional): Optional output tensor to write result into. The output + shape is `input.shape[:-1] + other.shape[:-1]`. + + Example:: + + # Dot product + >>> torch.inner(torch.tensor([1, 2, 3]), torch.tensor([0, 2, 1])) + tensor(7) + + # Multidimensional input tensors + >>> a = torch.randn(2, 3) + >>> a + tensor([[0.8173, 1.0874, 1.1784], + [0.3279, 0.1234, 2.7894]]) + >>> b = torch.randn(2, 4, 3) + >>> b + tensor([[[-0.4682, -0.7159, 0.1506], + [ 0.4034, -0.3657, 1.0387], + [ 0.9892, -0.6684, 0.1774], + [ 0.9482, 1.3261, 0.3917]], + + [[ 0.4537, 0.7493, 1.1724], + [ 0.2291, 0.5749, -0.2267], + [-0.7920, 0.3607, -0.3701], + [ 1.3666, -0.5850, -1.7242]]]) + >>> torch.inner(a, b) + tensor([[[-0.9837, 1.1560, 0.2907, 2.6785], + [ 2.5671, 0.5452, -0.6912, -1.5509]], + + [[ 0.1782, 2.9843, 0.7366, 1.5672], + [ 3.5115, -0.4864, -1.2476, -4.4337]]]) + + # Scalar input + >>> torch.inner(a, torch.tensor(2)) + tensor([[1.6347, 2.1748, 2.3567], + [0.6558, 0.2469, 5.5787]]) + """ + +def instance_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + use_input_stats: _bool, + momentum: _float, + eps: _float, + cudnn_enabled: _bool, +) -> Tensor: ... +def int_repr(input: Tensor) -> Tensor: ... +def inverse(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + inverse(input, *, out=None) -> Tensor + + Alias for :func:`torch.linalg.inv` + """ + +def is_complex(input: Tensor) -> _bool: + r""" + is_complex(input: Tensor) -> bool + + Returns True if the data type of :attr:`input` is a complex data type i.e., + one of ``torch.complex64``, and ``torch.complex128``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.complex64)) + True + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.complex128)) + True + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.int32)) + False + >>> torch.is_complex(torch.tensor([1.0, 2.0, 3.0], dtype=torch.float16)) + False + """ + +def is_conj(input: Tensor) -> _bool: + r""" + is_conj(input) -> (bool) + + Returns True if the :attr:`input` is a conjugated tensor, i.e. its conjugate bit is set to `True`. + + Args: + input (Tensor): the input tensor. + """ + +def is_distributed(input: Tensor) -> _bool: ... +def is_floating_point(input: Tensor) -> _bool: + r""" + is_floating_point(input: Tensor) -> bool + + Returns True if the data type of :attr:`input` is a floating point data type i.e., + one of ``torch.float64``, ``torch.float32``, ``torch.float16``, and ``torch.bfloat16``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> torch.is_floating_point(torch.tensor([1.0, 2.0, 3.0])) + True + >>> torch.is_floating_point(torch.tensor([1, 2, 3], dtype=torch.int32)) + False + >>> torch.is_floating_point(torch.tensor([1.0, 2.0, 3.0], dtype=torch.float16)) + True + >>> torch.is_floating_point(torch.tensor([1, 2, 3], dtype=torch.complex64)) + False + """ + +def is_grad_enabled() -> _bool: + r""" + is_grad_enabled() -> (bool) + + Returns True if grad mode is currently enabled. + """ + +def is_inference(input: Tensor) -> _bool: + r""" + is_inference(input) -> (bool) + + Returns True if :attr:`input` is an inference tensor. + + A non-view tensor is an inference tensor if and only if it was + allocated during inference mode. A view tensor is an inference + tensor if and only if the tensor it is a view of is an inference tensor. + + For details on inference mode please see + `Inference Mode `_. + + Args: + input (Tensor): the input tensor. + """ + +def is_inference_mode_enabled() -> _bool: + r""" + is_inference_mode_enabled() -> (bool) + + Returns True if inference mode is currently enabled. + """ + +def is_neg(input: Tensor) -> _bool: ... +def is_nonzero(input: Tensor) -> _bool: + r""" + is_nonzero(input) -> (bool) + + Returns True if the :attr:`input` is a single element tensor which is not equal to zero + after type conversions. + i.e. not equal to ``torch.tensor([0.])`` or ``torch.tensor([0])`` or + ``torch.tensor([False])``. + Throws a ``RuntimeError`` if ``torch.numel() != 1`` (even in case + of sparse tensors). + + Args: + input (Tensor): the input tensor. + + Examples:: + + >>> torch.is_nonzero(torch.tensor([0.])) + False + >>> torch.is_nonzero(torch.tensor([1.5])) + True + >>> torch.is_nonzero(torch.tensor([False])) + False + >>> torch.is_nonzero(torch.tensor([3])) + True + >>> torch.is_nonzero(torch.tensor([1, 3, 5])) + Traceback (most recent call last): + ... + RuntimeError: Boolean value of Tensor with more than one value is ambiguous + >>> torch.is_nonzero(torch.tensor([])) + Traceback (most recent call last): + ... + RuntimeError: Boolean value of Tensor with no values is ambiguous + """ + +def is_same_size(input: Tensor, other: Tensor) -> _bool: ... +def is_signed(input: Tensor) -> _bool: ... +def is_vulkan_available() -> _bool: ... +def isclose( + input: Tensor, + other: Tensor, + rtol: _float = 1e-05, + atol: _float = 1e-08, + equal_nan: _bool = False, +) -> Tensor: + r""" + isclose(input, other, rtol=1e-05, atol=1e-08, equal_nan=False) -> Tensor + + Returns a new tensor with boolean elements representing if each element of + :attr:`input` is "close" to the corresponding element of :attr:`other`. + Closeness is defined as: + + .. math:: + \lvert \text{input}_i - \text{other}_i \rvert \leq \texttt{rtol} \times \lvert \text{other}_i \rvert + \texttt{atol} + + + where :attr:`input` and :attr:`other` are finite. Where :attr:`input` + and/or :attr:`other` are nonfinite they are close if and only if + they are equal, with NaNs being considered equal to each other when + :attr:`equal_nan` is True. + + Args: + input (Tensor): first tensor to compare + other (Tensor): second tensor to compare + rtol (float, optional): relative tolerance. Default: 1e-05 + atol (float, optional): absolute tolerance. Default: 1e-08 + equal_nan (bool, optional): if ``True``, then two ``NaN`` s will be considered equal. Default: ``False`` + + Examples:: + + >>> torch.isclose(torch.tensor((1., 2, 3)), torch.tensor((1 + 1e-10, 3, 4))) + tensor([ True, False, False]) + >>> torch.isclose(torch.tensor((float('inf'), 4)), torch.tensor((float('inf'), 6)), rtol=.5) + tensor([True, True]) + """ + +def isfinite(input: Tensor) -> Tensor: + r""" + isfinite(input) -> Tensor + + Returns a new tensor with boolean elements representing if each element is `finite` or not. + + Real values are finite when they are not NaN, negative infinity, or infinity. + Complex values are finite when both their real and imaginary parts are finite. + + Args: + input (Tensor): the input tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is finite and False elsewhere + + Example:: + + >>> torch.isfinite(torch.tensor([1, float('inf'), 2, float('-inf'), float('nan')])) + tensor([True, False, True, False, False]) + """ + +@overload +def isin( + elements: Tensor, + test_elements: Tensor, + *, + assume_unique: _bool = False, + invert: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + isin(elements, test_elements, *, assume_unique=False, invert=False) -> Tensor + + Tests if each element of :attr:`elements` is in :attr:`test_elements`. Returns + a boolean tensor of the same shape as :attr:`elements` that is True for elements + in :attr:`test_elements` and False otherwise. + + .. note:: + One of :attr:`elements` or :attr:`test_elements` can be a scalar, but not both. + + Args: + elements (Tensor or Scalar): Input elements + test_elements (Tensor or Scalar): Values against which to test for each input element + assume_unique (bool, optional): If True, assumes both :attr:`elements` and + :attr:`test_elements` contain unique elements, which can speed up the + calculation. Default: False + invert (bool, optional): If True, inverts the boolean return tensor, resulting in True + values for elements *not* in :attr:`test_elements`. Default: False + + Returns: + A boolean tensor of the same shape as :attr:`elements` that is True for elements in + :attr:`test_elements` and False otherwise + + Example: + >>> torch.isin(torch.tensor([[1, 2], [3, 4]]), torch.tensor([2, 3])) + tensor([[False, True], + [ True, False]]) + """ + +@overload +def isin( + element: Number | _complex | PySymType, + 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 | PySymType, + *, + 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.]]) + """ + +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]])) + """ + +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: + r""" + lcm_(input, other) -> Tensor + + In-place version of :func:`torch.lcm` + """ + +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: + r""" + ldexp_(input, other) -> Tensor + + In-place version of :func:`torch.ldexp` + """ + +@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 | PySymType, + *, + 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 | PySymType, + *, + 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 | PySymType, + *, + 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 | PySymType, + *, + 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 | PySymType, + 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 | PySymType, + 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 | PySymType, + end: Number | _complex | PySymType, + 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: + r""" + log10_(input) -> Tensor + + In-place version of :func:`torch.log10` + """ + +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: + r""" + log1p_(input) -> Tensor + + In-place version of :func:`torch.log1p` + """ + +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: + r""" + log2_(input) -> Tensor + + In-place version of :func:`torch.log2` + """ + +def log_(input: Tensor) -> Tensor: + r""" + log_(input) -> Tensor + + In-place version of :func:`torch.log` + """ + +def log_softmax( + input: Tensor, + dim: _int, + dtype: _dtype | None = None, + *, + out: Tensor | 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. + """ + +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])) + """ + +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: + r""" + logit_(input, eps=None) -> Tensor + + In-place version of :func:`torch.logit` + """ + +@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 | PySymType, + 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 | PySymType, + 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 | PySymType, + end: Number | _complex | PySymType, + 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]) + """ + +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 lstm( + data: Tensor, + batch_sizes: Tensor, + hx: tuple[Tensor, ...] | list[Tensor], + params: tuple[Tensor, ...] | list[Tensor], + 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], + params: tuple[Tensor, ...] | list[Tensor], + 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], + 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 | PySymType, + *, + 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 | PySymType, +) -> Tensor: ... +def masked_scatter(input: Tensor, mask: Tensor, source: Tensor) -> Tensor: ... +def masked_select( + input: Tensor, + mask: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + masked_select(input, mask, *, out=None) -> Tensor + + Returns a new 1-D tensor which indexes the :attr:`input` tensor according to + the boolean mask :attr:`mask` which is a `BoolTensor`. + + The shapes of the :attr:`mask` tensor and the :attr:`input` tensor don't need + to match, but they must be :ref:`broadcastable `. + + .. note:: The returned tensor does **not** use the same storage + as the original tensor + + Args: + input (Tensor): the input tensor. + mask (BoolTensor): the tensor containing the binary mask to index with + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(3, 4) + >>> x + tensor([[ 0.3552, -2.3825, -0.8297, 0.3477], + [-1.2035, 1.2252, 0.5002, 0.6248], + [ 0.1307, -2.0608, 0.1244, 2.0139]]) + >>> mask = x.ge(0.5) + >>> mask + tensor([[False, False, False, False], + [False, True, True, True], + [False, False, False, True]]) + >>> torch.masked_select(x, mask) + tensor([ 1.2252, 0.5002, 0.6248, 2.0139]) + """ + +def matmul( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + matmul(input, other, *, out=None) -> Tensor + + Matrix product of two tensors. + + The behavior depends on the dimensionality of the tensors as follows: + + - If both tensors are 1-dimensional, the dot product (scalar) is returned. + - If both arguments are 2-dimensional, the matrix-matrix product is returned. + - If the first argument is 1-dimensional and the second argument is 2-dimensional, + a 1 is prepended to its dimension for the purpose of the matrix multiply. + After the matrix multiply, the prepended dimension is removed. + - If the first argument is 2-dimensional and the second argument is 1-dimensional, + the matrix-vector product is returned. + - If both arguments are at least 1-dimensional and at least one argument is + N-dimensional (where N > 2), then a batched matrix multiply is returned. If the first + argument is 1-dimensional, a 1 is prepended to its dimension for the purpose of the + batched matrix multiply and removed after. If the second argument is 1-dimensional, a + 1 is appended to its dimension for the purpose of the batched matrix multiply and removed after. + + The first N-2 dimensions of each argument, the batch dimensions, are + :ref:`broadcast ` (and thus must be broadcastable). + The last 2, the matrix dimensions, are handled as in the matrix-matrix product. + + For example, if :attr:`input` is a + :math:`(j \times 1 \times n \times m)` tensor and :attr:`other` is a :math:`(k \times m \times p)` + tensor, the batch dimensions are :math:`(j \times 1)` and :math:`(k)`, + and the matrix dimensions are :math:`(n \times m)` and :math:`(m \times p)`. + :attr:`out` will be a :math:`(j \times k \times n \times p)` tensor. + + This operation has support for arguments with :ref:`sparse layouts`. In particular the + matrix-matrix (both arguments 2-dimensional) supports sparse arguments with the same restrictions + as :func:`torch.mm` + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + .. note:: + + The 1-dimensional dot product version of this function does not support an :attr:`out` parameter. + + Arguments: + input (Tensor): the first tensor to be multiplied + other (Tensor): the second tensor to be multiplied + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> # vector x vector + >>> tensor1 = torch.randn(3) + >>> tensor2 = torch.randn(3) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([]) + >>> # matrix x vector + >>> tensor1 = torch.randn(3, 4) + >>> tensor2 = torch.randn(4) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([3]) + >>> # batched matrix x broadcasted vector + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(4) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3]) + >>> # batched matrix x batched matrix + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(10, 4, 5) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3, 5]) + >>> # batched matrix x broadcasted matrix + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(4, 5) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3, 5]) + """ + +def matrix_exp(input: Tensor) -> Tensor: + r""" + matrix_exp(A) -> Tensor + + Alias for :func:`torch.linalg.matrix_exp`. + """ + +def matrix_power( + input: Tensor, + n: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + matrix_power(input, n, *, out=None) -> Tensor + + Alias for :func:`torch.linalg.matrix_power` + """ + +@overload +def max(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + max(input, *, out=None) -> Tensor + + Returns the maximum value of all elements in the ``input`` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6763, 0.7445, -2.2369]]) + >>> torch.max(a) + tensor(0.7445) + + .. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each maximum value found + (argmax). + + If ``keepdim`` is ``True``, the output tensors are of the same size + as ``input`` except in the dimension ``dim`` where they are of size 1. + Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than ``input``. + + .. note:: If there are multiple maximal values in a reduced row then + the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (max, max_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-1.2360, -0.2942, -0.1222, 0.8475], + [ 1.1949, -1.1127, -2.2379, -0.6702], + [ 1.5717, -0.9207, 0.1297, -1.8768], + [-0.6172, 1.0036, -0.6060, -0.2432]]) + >>> torch.max(a, 1) + torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1])) + >>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + >>> a.max(dim=1, keepdim=True) + torch.return_types.max( + values=tensor([[2.], [4.]]), + indices=tensor([[1], [1]])) + >>> a.max(dim=1, keepdim=False) + torch.return_types.max( + values=tensor([2., 4.]), + indices=tensor([1, 1])) + + .. function:: max(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.maximum`. + """ + +@overload +def max( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + max(input, *, out=None) -> Tensor + + Returns the maximum value of all elements in the ``input`` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6763, 0.7445, -2.2369]]) + >>> torch.max(a) + tensor(0.7445) + + .. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each maximum value found + (argmax). + + If ``keepdim`` is ``True``, the output tensors are of the same size + as ``input`` except in the dimension ``dim`` where they are of size 1. + Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than ``input``. + + .. note:: If there are multiple maximal values in a reduced row then + the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (max, max_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-1.2360, -0.2942, -0.1222, 0.8475], + [ 1.1949, -1.1127, -2.2379, -0.6702], + [ 1.5717, -0.9207, 0.1297, -1.8768], + [-0.6172, 1.0036, -0.6060, -0.2432]]) + >>> torch.max(a, 1) + torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1])) + >>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + >>> a.max(dim=1, keepdim=True) + torch.return_types.max( + values=tensor([[2.], [4.]]), + indices=tensor([[1], [1]])) + >>> a.max(dim=1, keepdim=False) + torch.return_types.max( + values=tensor([2., 4.]), + indices=tensor([1, 1])) + + .. function:: max(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.maximum`. + """ + +@overload +def max( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.max: + r""" + max(input, *, out=None) -> Tensor + + Returns the maximum value of all elements in the ``input`` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6763, 0.7445, -2.2369]]) + >>> torch.max(a) + tensor(0.7445) + + .. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each maximum value found + (argmax). + + If ``keepdim`` is ``True``, the output tensors are of the same size + as ``input`` except in the dimension ``dim`` where they are of size 1. + Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than ``input``. + + .. note:: If there are multiple maximal values in a reduced row then + the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (max, max_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-1.2360, -0.2942, -0.1222, 0.8475], + [ 1.1949, -1.1127, -2.2379, -0.6702], + [ 1.5717, -0.9207, 0.1297, -1.8768], + [-0.6172, 1.0036, -0.6060, -0.2432]]) + >>> torch.max(a, 1) + torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1])) + >>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + >>> a.max(dim=1, keepdim=True) + torch.return_types.max( + values=tensor([[2.], [4.]]), + indices=tensor([[1], [1]])) + >>> a.max(dim=1, keepdim=False) + torch.return_types.max( + values=tensor([2., 4.]), + indices=tensor([1, 1])) + + .. function:: max(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.maximum`. + """ + +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 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 min(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + min(input, *, out=None) -> Tensor + + Returns the minimum value of all elements in the :attr:`input` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6750, 1.0857, 1.7197]]) + >>> torch.min(a) + tensor(0.6750) + + .. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each minimum value found + (argmin). + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensors having 1 fewer dimension than :attr:`input`. + + .. note:: If there are multiple minimal values in a reduced row then + the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the tuple of two output tensors (min, min_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.6248, 1.1334, -1.1899, -0.2803], + [-1.4644, -0.2635, -0.3651, 0.6134], + [ 0.2457, 0.0384, 1.0128, 0.7015], + [-0.1153, 2.9849, 2.1458, 0.5788]]) + >>> torch.min(a, 1) + torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0])) + + .. function:: min(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.minimum`. + """ + +@overload +def min( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + min(input, *, out=None) -> Tensor + + Returns the minimum value of all elements in the :attr:`input` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6750, 1.0857, 1.7197]]) + >>> torch.min(a) + tensor(0.6750) + + .. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each minimum value found + (argmin). + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensors having 1 fewer dimension than :attr:`input`. + + .. note:: If there are multiple minimal values in a reduced row then + the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the tuple of two output tensors (min, min_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.6248, 1.1334, -1.1899, -0.2803], + [-1.4644, -0.2635, -0.3651, 0.6134], + [ 0.2457, 0.0384, 1.0128, 0.7015], + [-0.1153, 2.9849, 2.1458, 0.5788]]) + >>> torch.min(a, 1) + torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0])) + + .. function:: min(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.minimum`. + """ + +@overload +def min( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.min: + r""" + min(input, *, out=None) -> Tensor + + Returns the minimum value of all elements in the :attr:`input` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6750, 1.0857, 1.7197]]) + >>> torch.min(a) + tensor(0.6750) + + .. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each minimum value found + (argmin). + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensors having 1 fewer dimension than :attr:`input`. + + .. note:: If there are multiple minimal values in a reduced row then + the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the tuple of two output tensors (min, min_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.6248, 1.1334, -1.1899, -0.2803], + [-1.4644, -0.2635, -0.3651, 0.6134], + [ 0.2457, 0.0384, 1.0128, 0.7015], + [-0.1153, 2.9849, 2.1458, 0.5788]]) + >>> torch.min(a, 1) + torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0])) + + .. function:: min(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.minimum`. + """ + +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 | PySymType | 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: ... +@overload +def miopen_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 miopen_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int, + deterministic: _bool, + zero_infinity: _bool, +) -> tuple[Tensor, 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], + 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=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 + + 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]]) + + .. function:: mm(input, mat2, out_dtype, *, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + out (Tensor, optional): the output tensor. + """ + +@overload +def mm( + input: Tensor, + mat2: Tensor, + out_dtype: _dtype, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + mm(input, mat2, *, 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 + + 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]]) + + .. function:: mm(input, mat2, out_dtype, *, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + out (Tensor, optional): the output tensor. + """ + +def mode( + input: Tensor, + dim: _int = -1, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.mode: + r""" + mode(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + + Returns a namedtuple ``(values, indices)`` where ``values`` is the mode + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`, i.e. a value which appears most often + in that row, and ``indices`` is the index location of each mode value found. + + By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than :attr:`input`. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + + Example:: + + >>> b = torch.tensor([[0, 0, 0, 2, 0, 0, 2], + ... [0, 3, 0, 0, 2, 0, 1], + ... [2, 2, 2, 0, 0, 0, 3], + ... [2, 2, 3, 0, 1, 1, 0], + ... [1, 1, 0, 0, 2, 0, 2]]) + >>> torch.mode(b, 0) + torch.return_types.mode( + values=tensor([0, 2, 0, 0, 0, 0, 2]), + indices=tensor([1, 3, 4, 4, 2, 4, 4])) + """ + +@overload +def 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 | PySymType) -> 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: + r""" + nan_to_num_(input, nan=0.0, posinf=None, neginf=None) -> Tensor + + In-place version of :func:`torch.nan_to_num` + """ + +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 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 | PySymType | None, + dim: _int | _size, + keepdim: _bool, + dtype: _dtype | None, +) -> Tensor: ... +@overload +def native_norm( + input: Tensor, + p: Number | _complex | PySymType = 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 | PySymType, + *, + 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: + r""" + neg_(input) -> Tensor + + In-place version of :func:`torch.neg` + """ + +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: + r""" + negative_(input) -> Tensor + + In-place version of :func:`torch.negative` + """ + +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: + 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. + + Keyword args: + size (int): the size of non-zero elements expected to be included in the out + tensor. Pad the out tensor with `fill_value` if the `size` is larger + than total number of non-zero elements, truncate out tensor if `size` + is smaller. The size must be a non-negative integer. + fill_value (int, optional): the value to fill the output tensor with when `size` is larger + than the total number of non-zero elements. Default is `-1` to represent + invalid index. + + Example:: + + # Example 1: Padding + >>> input_tensor = torch.tensor([[1, 0], [3, 2]]) + >>> static_size = 4 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([[ 0, 0], + [ 1, 0], + [ 1, 1], + [ -1, -1]], dtype=torch.int64) + + # Example 2: Truncating + >>> input_tensor = torch.tensor([[1, 0], [3, 2]]) + >>> static_size = 2 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([[ 0, 0], + [ 1, 0]], dtype=torch.int64) + + # Example 3: 0 size + >>> input_tensor = torch.tensor([10]) + >>> static_size = 0 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([], size=(0, 1), dtype=torch.int64) + + # Example 4: 0 rank input + >>> input_tensor = torch.tensor(10) + >>> static_size = 2 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([], size=(2, 0), dtype=torch.int64) + """ + +def 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 (float or Tensor): per-element mean(s). Only floating point types are supported. + std (float or Tensor): per-element standard deviation(s). Only floating point types are supported. + + 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, *, generator=None, out=None, dtype=None, \ + layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> 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: + 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.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 (float or Tensor): per-element mean(s). Only floating point types are supported. + std (float or Tensor): per-element standard deviation(s). Only floating point types are supported. + + 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, *, generator=None, out=None, dtype=None, \ + layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> 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: + 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.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 (float or Tensor): per-element mean(s). Only floating point types are supported. + std (float or Tensor): per-element standard deviation(s). Only floating point types are supported. + + 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, *, generator=None, out=None, dtype=None, \ + layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> 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: + 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.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 (float or Tensor): per-element mean(s). Only floating point types are supported. + std (float or Tensor): per-element standard deviation(s). Only floating point types are supported. + + 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, *, generator=None, out=None, dtype=None, \ + layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> 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: + 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.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 | PySymType, + *, + 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.]) + """ + +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 (torch.Size, tuple of int or list 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 | PySymType, + 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 | PySymType, + *, + 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]) + """ + +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: ... +@overload +def quantile( + input: Tensor, + q: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + out: Tensor | None = None, +) -> Tensor: + r""" + quantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + + Computes the q-th quantiles of each row of the :attr:`input` tensor along the dimension :attr:`dim`. + + To compute the quantile, we map q in [0, 1] to the range of indices [0, n] to find the location + of the quantile in the sorted input. If the quantile lies between two data points ``a < b`` with + indices ``i`` and ``j`` in the sorted order, result is computed according to the given + :attr:`interpolation` method as follows: + + - ``linear``: ``a + (b - a) * fraction``, where ``fraction`` is the fractional part of the computed quantile index. + - ``lower``: ``a``. + - ``higher``: ``b``. + - ``nearest``: ``a`` or ``b``, whichever's index is closer to the computed quantile index (follows :func:`torch.round`). + - ``midpoint``: ``(a + b) / 2``. + + If :attr:`q` is a 1D tensor, the first dimension of the output represents the quantiles and has size + equal to the size of :attr:`q`, the remaining dimensions are what remains from the reduction. + + .. note:: + By default :attr:`dim` is ``None`` resulting in the :attr:`input` tensor being flattened before computation. + + Args: + input (Tensor): the input tensor. + q (float or Tensor): a scalar or 1D tensor of values in the range [0, 1]. + + dim (int, optional): the dimension to reduce. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword arguments: + interpolation (str, optional): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(2, 3) + >>> a + tensor([[ 0.0795, -1.2117, 0.9765], + [ 1.1707, 0.6706, 0.4884]]) + >>> q = torch.tensor([0.25, 0.5, 0.75]) + >>> torch.quantile(a, q, dim=1, keepdim=True) + tensor([[[-0.5661], + [ 0.5795]], + + [[ 0.0795], + [ 0.6706]], + + [[ 0.5280], + [ 0.9206]]]) + >>> torch.quantile(a, q, dim=1, keepdim=True).shape + torch.Size([3, 2, 1]) + >>> a = torch.arange(4.) + >>> a + tensor([0., 1., 2., 3.]) + >>> torch.quantile(a, 0.6, interpolation='linear') + tensor(1.8000) + >>> torch.quantile(a, 0.6, interpolation='lower') + tensor(1.) + >>> torch.quantile(a, 0.6, interpolation='higher') + tensor(2.) + >>> torch.quantile(a, 0.6, interpolation='midpoint') + tensor(1.5000) + >>> torch.quantile(a, 0.6, interpolation='nearest') + tensor(2.) + >>> torch.quantile(a, 0.4, interpolation='nearest') + tensor(1.) + """ + +@overload +def quantile( + input: Tensor, + q: _float, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + out: Tensor | None = None, +) -> Tensor: + r""" + quantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + + Computes the q-th quantiles of each row of the :attr:`input` tensor along the dimension :attr:`dim`. + + To compute the quantile, we map q in [0, 1] to the range of indices [0, n] to find the location + of the quantile in the sorted input. If the quantile lies between two data points ``a < b`` with + indices ``i`` and ``j`` in the sorted order, result is computed according to the given + :attr:`interpolation` method as follows: + + - ``linear``: ``a + (b - a) * fraction``, where ``fraction`` is the fractional part of the computed quantile index. + - ``lower``: ``a``. + - ``higher``: ``b``. + - ``nearest``: ``a`` or ``b``, whichever's index is closer to the computed quantile index (follows :func:`torch.round`). + - ``midpoint``: ``(a + b) / 2``. + + If :attr:`q` is a 1D tensor, the first dimension of the output represents the quantiles and has size + equal to the size of :attr:`q`, the remaining dimensions are what remains from the reduction. + + .. note:: + By default :attr:`dim` is ``None`` resulting in the :attr:`input` tensor being flattened before computation. + + Args: + input (Tensor): the input tensor. + q (float or Tensor): a scalar or 1D tensor of values in the range [0, 1]. + + dim (int, optional): the dimension to reduce. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword arguments: + interpolation (str, optional): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(2, 3) + >>> a + tensor([[ 0.0795, -1.2117, 0.9765], + [ 1.1707, 0.6706, 0.4884]]) + >>> q = torch.tensor([0.25, 0.5, 0.75]) + >>> torch.quantile(a, q, dim=1, keepdim=True) + tensor([[[-0.5661], + [ 0.5795]], + + [[ 0.0795], + [ 0.6706]], + + [[ 0.5280], + [ 0.9206]]]) + >>> torch.quantile(a, q, dim=1, keepdim=True).shape + torch.Size([3, 2, 1]) + >>> a = torch.arange(4.) + >>> a + tensor([0., 1., 2., 3.]) + >>> torch.quantile(a, 0.6, interpolation='linear') + tensor(1.8000) + >>> torch.quantile(a, 0.6, interpolation='lower') + tensor(1.) + >>> torch.quantile(a, 0.6, interpolation='higher') + tensor(2.) + >>> torch.quantile(a, 0.6, interpolation='midpoint') + tensor(1.5000) + >>> torch.quantile(a, 0.6, interpolation='nearest') + tensor(2.) + >>> torch.quantile(a, 0.4, interpolation='nearest') + tensor(1.) + """ + +def quantize_per_channel( + input: Tensor, + scales: Tensor, + zero_points: Tensor, + axis: _int, + dtype: _dtype, +) -> Tensor: + r""" + quantize_per_channel(input, scales, zero_points, axis, dtype) -> Tensor + + Converts a float tensor to a per-channel quantized tensor with given scales and zero points. + + Arguments: + input (Tensor): float tensor to quantize + scales (Tensor): float 1D tensor of scales to use, size should match ``input.size(axis)`` + zero_points (int): integer 1D tensor of offset to use, size should match ``input.size(axis)`` + axis (int): dimension on which apply per-channel quantization + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + + Returns: + Tensor: A newly quantized tensor + + Example:: + + >>> x = torch.tensor([[-1.0, 0.0], [1.0, 2.0]]) + >>> torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8) + tensor([[-1., 0.], + [ 1., 2.]], size=(2, 2), dtype=torch.quint8, + quantization_scheme=torch.per_channel_affine, + scale=tensor([0.1000, 0.0100], dtype=torch.float64), + zero_point=tensor([10, 0]), axis=0) + >>> torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8).int_repr() + tensor([[ 0, 10], + [100, 200]], dtype=torch.uint8) + """ + +@overload +def quantize_per_tensor( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + dtype: _dtype, +) -> Tensor: + r""" + quantize_per_tensor(input, scale, zero_point, dtype) -> Tensor + + Converts a float tensor to a quantized tensor with given scale and zero point. + + Arguments: + input (Tensor): float tensor or list of tensors to quantize + scale (float or Tensor): scale to apply in quantization formula + zero_point (int or Tensor): offset in integer value that maps to float zero + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + + Returns: + Tensor: A newly quantized tensor or list of quantized tensors. + + Example:: + + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8).int_repr() + tensor([ 0, 10, 20, 30], dtype=torch.uint8) + >>> torch.quantize_per_tensor([torch.tensor([-1.0, 0.0]), torch.tensor([-2.0, 2.0])], + >>> torch.tensor([0.1, 0.2]), torch.tensor([10, 20]), torch.quint8) + (tensor([-1., 0.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10), + tensor([-2., 2.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=20)) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.tensor(0.1), torch.tensor(10), torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.10, zero_point=10) + """ + +@overload +def quantize_per_tensor( + input: Tensor, + scale: _float, + zero_point: _int, + dtype: _dtype, +) -> Tensor: + r""" + quantize_per_tensor(input, scale, zero_point, dtype) -> Tensor + + Converts a float tensor to a quantized tensor with given scale and zero point. + + Arguments: + input (Tensor): float tensor or list of tensors to quantize + scale (float or Tensor): scale to apply in quantization formula + zero_point (int or Tensor): offset in integer value that maps to float zero + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + + Returns: + Tensor: A newly quantized tensor or list of quantized tensors. + + Example:: + + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8).int_repr() + tensor([ 0, 10, 20, 30], dtype=torch.uint8) + >>> torch.quantize_per_tensor([torch.tensor([-1.0, 0.0]), torch.tensor([-2.0, 2.0])], + >>> torch.tensor([0.1, 0.2]), torch.tensor([10, 20]), torch.quint8) + (tensor([-1., 0.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10), + tensor([-2., 2.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=20)) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.tensor(0.1), torch.tensor(10), torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.10, zero_point=10) + """ + +@overload +def quantize_per_tensor( + tensors: tuple[Tensor, ...] | list[Tensor], + 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 | PySymType, + scale_hh: Number | _complex | PySymType, + zero_point_ih: Number | _complex | PySymType, + zero_point_hh: Number | _complex | PySymType, +) -> Tensor: ... +def quantized_lstm_cell( + input: Tensor, + hx: tuple[Tensor, ...] | list[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 | PySymType, + scale_hh: Number | _complex | PySymType, + zero_point_ih: Number | _complex | PySymType, + zero_point_hh: Number | _complex | PySymType, +) -> 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 | PySymType, + scale_hh: Number | _complex | PySymType, + zero_point_ih: Number | _complex | PySymType, + zero_point_hh: Number | _complex | PySymType, +) -> 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 | PySymType, + scale_hh: Number | _complex | PySymType, + zero_point_ih: Number | _complex | PySymType, + zero_point_hh: Number | _complex | PySymType, +) -> 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: + r""" + rad2deg_(input) -> Tensor + + In-place version of :func:`torch.rad2deg` + """ + +@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_like( + input: Tensor, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a uniform distribution on the interval :math:`[0, 1)`. + ``torch.rand_like(input)`` is equivalent to + ``torch.rand(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def rand_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a uniform distribution on the interval :math:`[0, 1)`. + ``torch.rand_like(input)`` is equivalent to + ``torch.rand(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint( + low: _int, + high: _int, + size: _size, + *, + generator: Generator | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + high: _int, + size: _size, + *, + generator: Generator | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + low: _int | SymInt, + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + low: _int | SymInt, + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint_like( + input: Tensor, + low: _int | SymInt, + high: _int | SymInt, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + low: _int | SymInt, + high: _int | SymInt, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: Tensor, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: _int | SymInt, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: _int | SymInt, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randn( + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + 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_like( + input: Tensor, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a normal distribution with mean 0 and variance 1. Please refer to :func:`torch.randn` for the + sampling process of complex dtypes. ``torch.randn_like(input)`` is equivalent to + ``torch.randn(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randn_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a normal distribution with mean 0 and variance 1. Please refer to :func:`torch.randn` for the + sampling process of complex dtypes. ``torch.randn_like(input)`` is equivalent to + ``torch.randn(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randperm( + n: _int | SymInt, + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randperm(n, *, generator=None, out=None, dtype=torch.int64,layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a random permutation of integers from ``0`` to ``n - 1``. + + Args: + n (int): the upper bound (exclusive) + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randperm(4) + tensor([2, 1, 0, 3]) + """ + +@overload +def randperm( + n: _int | SymInt, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randperm(n, *, generator=None, out=None, dtype=torch.int64,layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a random permutation of integers from ``0`` to ``n - 1``. + + Args: + n (int): the upper bound (exclusive) + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randperm(4) + tensor([2, 1, 0, 3]) + """ + +def range( + start: Number, + end: Number, + step: Number = 1, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + range(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lfloor \frac{\text{end} - \text{start}}{\text{step}} \right\rfloor + 1` + with values from :attr:`start` to :attr:`end` with step :attr:`step`. Step is + the gap between two values in the tensor. + + .. math:: + \text{out}_{i+1} = \text{out}_i + \text{step}. + + .. warning:: + This function is deprecated and will be removed in a future release because its behavior is inconsistent with + Python's range builtin. Instead, use :func:`torch.arange`, which produces values in [start, end). + + Args: + start (float, optional): the starting value for the set of points. Default: ``0``. + end (float): the ending value for the set of points + step (float, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `step` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.range(1, 4) + tensor([ 1., 2., 3., 4.]) + >>> torch.range(1, 4, 0.5) + tensor([ 1.0000, 1.5000, 2.0000, 2.5000, 3.0000, 3.5000, 4.0000]) + """ + +def ravel(input: Tensor) -> Tensor: + r""" + ravel(input) -> Tensor + + Return a contiguous flattened tensor. A copy is made only if needed. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> t = torch.tensor([[[1, 2], + ... [3, 4]], + ... [[5, 6], + ... [7, 8]]]) + >>> torch.ravel(t) + tensor([1, 2, 3, 4, 5, 6, 7, 8]) + """ + +def real(input: Tensor) -> Tensor: + r""" + real(input) -> Tensor + + Returns a new tensor containing real values of the :attr:`self` tensor. + The returned tensor and :attr:`self` share the same underlying storage. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)]) + >>> x.real + tensor([ 0.3100, -0.5445, -1.6492, -0.0638]) + """ + +def reciprocal(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + reciprocal(input, *, out=None) -> Tensor + + Returns a new tensor with the reciprocal of the elements of :attr:`input` + + .. math:: + \text{out}_{i} = \frac{1}{\text{input}_{i}} + + .. note:: + Unlike NumPy's reciprocal, torch.reciprocal supports integral inputs. Integral + inputs to reciprocal are automatically :ref:`promoted ` to + the default scalar type. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.4595, -2.1219, -1.4314, 0.7298]) + >>> torch.reciprocal(a) + tensor([-2.1763, -0.4713, -0.6986, 1.3702]) + """ + +def reciprocal_(input: Tensor) -> Tensor: + r""" + reciprocal_(input) -> Tensor + + In-place version of :func:`torch.reciprocal` + """ + +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 | PySymType, 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 | PySymType, + *, + 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 | PySymType, + dim: _int, + maxnorm: Number | _complex | PySymType, + *, + 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 | PySymType, + 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 | PySymType, +) -> _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 | PySymType, + scalar2: Number | _complex | PySymType, +) -> _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], + 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], + 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], + 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], + 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 + >>> # 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 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 + >>> # 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 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: + r""" + round_(input, *, decimals=0) -> Tensor + + In-place version of :func:`torch.round` + """ + +@overload +def round_(input: Tensor, *, decimals: _int) -> Tensor: + r""" + round_(input, *, decimals=0) -> Tensor + + In-place version of :func:`torch.round` + """ + +def row_indices_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def row_stack( + tensors: tuple[Tensor, ...] | list[Tensor], + *, + out: Tensor | None = None, +) -> Tensor: + r""" + row_stack(tensors, *, out=None) -> Tensor + + Alias of :func:`torch.vstack`. + """ + +def rrelu( + input: Tensor, + lower: Number | _complex | PySymType = 0.125, + upper: Number | _complex | PySymType = 0.3333333333333333, + training: _bool = False, + generator: Generator | None = None, +) -> Tensor: ... +def rrelu_( + input: Tensor, + lower: Number | _complex | PySymType = 0.125, + upper: Number | _complex | PySymType = 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: + r""" + rsqrt_(input) -> Tensor + + In-place version of :func:`torch.rsqrt` + """ + +@overload +def rsub( + input: Tensor, + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: ... +@overload +def rsub( + input: Tensor, + other: Number | _complex | PySymType, + alpha: Number | _complex | PySymType = 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 | PySymType, + *, + 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 | PySymType, + *, + 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, + value: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + +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_` + """ + +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. PyTorch does not validate this condition when :attr:`sorter` is + not provided, and the behavior is undefined if the sequence is not 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 | PySymType, + *, + 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. PyTorch does not validate this condition when :attr:`sorter` is + not provided, and the behavior is undefined if the sequence is not 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 | PySymType | None = None, +) -> Tensor: + r""" + segment_reduce(data: Tensor, reduce: str, *, lengths: Tensor | None = None, indices: Tensor | None = None, offsets: Tensor | None = None, axis: _int = 0, unsafe: _bool = False, initial: Number | _complex | None = None) -> Tensor # noqa: B950 + + Perform a segment reduction operation on the input tensor along the specified axis. + + Args: + data (Tensor): The input tensor on which the segment reduction operation will be performed. + reduce (str): The type of reduction operation. Supported values are ``sum``, ``mean``, ``max``, ``min``, ``prod``. + + Keyword args: + lengths (Tensor, optional): Length of each segment. Default: ``None``. + offsets (Tensor, optional): Offset of each segment. Default: ``None``. + axis (int, optional): The axis perform reduction. Default: ``0``. + unsafe (bool, optional): Skip validation If `True`. Default: ``False``. + initial (Number, optional): The initial value for the reduction operation. Default: ``None``. + + Example:: + + >>> data = torch.tensor([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]], dtype=torch.float32, device='cuda') + >>> lengths = torch.tensor([2, 1], device='cuda') + >>> torch.segment_reduce(data, 'max', lengths=lengths) + tensor([[ 5., 6., 7., 8.], + [ 9., 10., 11., 12.]], device='cuda:0') + """ + +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]``. + """ + +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: + r""" + sigmoid_(input) -> Tensor + + In-place version of :func:`torch.sigmoid` + """ + +def sign(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sign(input, *, out=None) -> Tensor + + Returns a new tensor with the signs of the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \operatorname{sgn}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([0.7, -1.2, 0., 2.3]) + >>> a + tensor([ 0.7000, -1.2000, 0.0000, 2.3000]) + >>> torch.sign(a) + tensor([ 1., -1., 0., 1.]) + """ + +def signbit(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + signbit(input, *, out=None) -> Tensor + + Tests if each element of :attr:`input` has its sign bit set or not. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([0.7, -1.2, 0., 2.3]) + >>> torch.signbit(a) + tensor([ False, True, False, False]) + >>> a = torch.tensor([-0.0, 0.0]) + >>> torch.signbit(a) + tensor([ True, False]) + + .. note:: + signbit handles signed zeros, so negative zero (-0) returns True. + """ + +def sin(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sin(input, *, out=None) -> Tensor + + Returns a new tensor with the sine of the elements in the :attr:`input` tensor, + where each value in this input tensor is in radians. + + .. math:: + \text{out}_{i} = \sin(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.5461, 0.1347, -2.7266, -0.2746]) + >>> torch.sin(a) + tensor([-0.5194, 0.1343, -0.4032, -0.2711]) + """ + +def sin_(input: Tensor) -> Tensor: + r""" + sin_(input) -> Tensor + + In-place version of :func:`torch.sin` + """ + +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: + r""" + sinc_(input) -> Tensor + + In-place version of :func:`torch.sinc` + """ + +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]) + """ + +def sinh_(input: Tensor) -> Tensor: + r""" + sinh_(input) -> Tensor + + In-place version of :func:`torch.sinh` + """ + +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 + """ + +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 sort( + input: Tensor, + *, + stable: _bool | None, + dim: _int = -1, + descending: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.sort: + r""" + sort(input, dim=-1, descending=False, *, stable=False, out=None) -> (Tensor, LongTensor) + + Sorts the elements of the :attr:`input` tensor along a given dimension + in ascending order by value. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`descending` is ``True`` then the elements are sorted in descending + order by value. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. + + A namedtuple of (values, indices) is returned, where the `values` are the + sorted values and `indices` are the indices of the elements in the original + `input` tensor. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + out (tuple, optional): the output tuple of (`Tensor`, `LongTensor`) that can + be optionally given to be used as output buffers + + Example:: + + >>> x = torch.randn(3, 4) + >>> sorted, indices = torch.sort(x) + >>> sorted + tensor([[-0.2162, 0.0608, 0.6719, 2.3332], + [-0.5793, 0.0061, 0.6058, 0.9497], + [-0.5071, 0.3343, 0.9553, 1.0960]]) + >>> indices + tensor([[ 1, 0, 2, 3], + [ 3, 1, 0, 2], + [ 0, 3, 1, 2]]) + + >>> sorted, indices = torch.sort(x, 0) + >>> sorted + tensor([[-0.5071, -0.2162, 0.6719, -0.5793], + [ 0.0608, 0.0061, 0.9497, 0.3343], + [ 0.6058, 0.9553, 1.0960, 2.3332]]) + >>> indices + tensor([[ 2, 0, 0, 1], + [ 0, 1, 1, 2], + [ 1, 2, 2, 0]]) + >>> x = torch.tensor([0, 1] * 9) + >>> x.sort() + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 2, 16, 4, 6, 14, 8, 0, 10, 12, 9, 17, 15, 13, 11, 7, 5, 3, 1])) + >>> x.sort(stable=True) + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 1, 3, 5, 7, 9, 11, 13, 15, 17])) + """ + +@overload +def sort( + input: Tensor, + dim: _int = -1, + descending: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.sort: + r""" + sort(input, dim=-1, descending=False, *, stable=False, out=None) -> (Tensor, LongTensor) + + Sorts the elements of the :attr:`input` tensor along a given dimension + in ascending order by value. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`descending` is ``True`` then the elements are sorted in descending + order by value. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. + + A namedtuple of (values, indices) is returned, where the `values` are the + sorted values and `indices` are the indices of the elements in the original + `input` tensor. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + out (tuple, optional): the output tuple of (`Tensor`, `LongTensor`) that can + be optionally given to be used as output buffers + + Example:: + + >>> x = torch.randn(3, 4) + >>> sorted, indices = torch.sort(x) + >>> sorted + tensor([[-0.2162, 0.0608, 0.6719, 2.3332], + [-0.5793, 0.0061, 0.6058, 0.9497], + [-0.5071, 0.3343, 0.9553, 1.0960]]) + >>> indices + tensor([[ 1, 0, 2, 3], + [ 3, 1, 0, 2], + [ 0, 3, 1, 2]]) + + >>> sorted, indices = torch.sort(x, 0) + >>> sorted + tensor([[-0.5071, -0.2162, 0.6719, -0.5793], + [ 0.0608, 0.0061, 0.9497, 0.3343], + [ 0.6058, 0.9553, 1.0960, 2.3332]]) + >>> indices + tensor([[ 2, 0, 0, 1], + [ 0, 1, 1, 2], + [ 1, 2, 2, 0]]) + >>> x = torch.tensor([0, 1] * 9) + >>> x.sort() + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 2, 16, 4, 6, 14, 8, 0, 10, 12, 9, 17, 15, 13, 11, 7, 5, 3, 1])) + >>> x.sort(stable=True) + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 1, 3, 5, 7, 9, 11, 13, 15, 17])) + """ + +def sparse_bsc_tensor( + ccol_indices: Tensor | list, + row_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_bsc_tensor(ccol_indices, row_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in BSC (Block Compressed Sparse + Column)) ` with specified 2-dimensional blocks at the + given :attr:`ccol_indices` and :attr:`row_indices`. Sparse matrix + multiplication operations in BSC format are typically faster than that + for sparse tensors in COO format. Make you have a look at :ref:`the + note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + ccol_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, ncolblocks + 1)``. The last element of each + batch is the number of non-zeros. This tensor encodes the + index in values and row_indices depending on where the given + column starts. Each successive number in the tensor subtracted + by the number before it denotes the number of elements in a + given column. + row_indices (array_like): Row block coordinates of each block in + values. (B+1)-dimensional tensor with the same length + as values. + values (array_list): Initial blocks for the tensor. Can be a list, + tuple, NumPy ``ndarray``, and other types that + represents a (1 + 2 + K)-dimensional tensor where ``K`` is the + number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` If not provided, the size will be + inferred as the minimum size big enough to hold all non-zero + blocks. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> ccol_indices = [0, 1, 2] + >>> row_indices = [0, 1] + >>> values = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] + >>> torch.sparse_bsc_tensor(torch.tensor(ccol_indices, dtype=torch.int64), + ... torch.tensor(row_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(ccol_indices=tensor([0, 1, 2]), + row_indices=tensor([0, 1]), + values=tensor([[[1., 2.], + [3., 4.]], + [[5., 6.], + [7., 8.]]]), size=(2, 2), nnz=2, dtype=torch.float64, + layout=torch.sparse_bsc) + """ + +def sparse_bsr_tensor( + crow_indices: Tensor | list, + col_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_bsr_tensor(crow_indices, col_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in BSR (Block Compressed Sparse Row)) + ` with specified 2-dimensional blocks at the given + :attr:`crow_indices` and :attr:`col_indices`. Sparse matrix + multiplication operations in BSR format are typically faster than that + for sparse tensors in COO format. Make you have a look at :ref:`the + note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + crow_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, nrowblocks + 1)``. The last element of each + batch is the number of non-zeros. This tensor encodes the + block index in values and col_indices depending on where the + given row block starts. Each successive number in the tensor + subtracted by the number before it denotes the number of + blocks in a given row. + col_indices (array_like): Column block coordinates of each block + in values. (B+1)-dimensional tensor with the same length as + values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1 + 2 + K)-dimensional tensor where ``K`` is the + number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` where ``blocksize == + values.shape[1:3]``. If not provided, the size will be + inferred as the minimum size big enough to hold all non-zero + blocks. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> crow_indices = [0, 1, 2] + >>> col_indices = [0, 1] + >>> values = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] + >>> torch.sparse_bsr_tensor(torch.tensor(crow_indices, dtype=torch.int64), + ... torch.tensor(col_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(crow_indices=tensor([0, 1, 2]), + col_indices=tensor([0, 1]), + values=tensor([[[1., 2.], + [3., 4.]], + [[5., 6.], + [7., 8.]]]), size=(2, 2), nnz=2, dtype=torch.float64, + layout=torch.sparse_bsr) + """ + +def sparse_compressed_tensor( + compressed_indices: Tensor | list, + plain_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_compressed_tensor(compressed_indices, plain_indices, values, size=None, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in Compressed Sparse format - CSR, + CSC, BSR, or BSC - ` with specified values at + the given :attr:`compressed_indices` and :attr:`plain_indices`. Sparse + matrix multiplication operations in Compressed Sparse format are + typically faster than that for sparse tensors in COO format. Make you + have a look at :ref:`the note on the data type of the indices + `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + compressed_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, compressed_dim_size + 1)``. The last element of + each batch is the number of non-zero elements or blocks. This + tensor encodes the index in ``values`` and ``plain_indices`` + depending on where the given compressed dimension (row or + column) starts. Each successive number in the tensor + subtracted by the number before it denotes the number of + elements or blocks in a given compressed dimension. + plain_indices (array_like): Plain dimension (column or row) + coordinates of each element or block in values. (B+1)-dimensional + tensor with the same length as values. + + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types. that + represents a (1+K)-dimensional (for CSR and CSC layouts) or + (1+2+K)-dimensional tensor (for BSR and BSC layouts) where + ``K`` is the number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` where ``blocksize[0] == + blocksize[1] == 1`` for CSR and CSC formats. If not provided, + the size will be inferred as the minimum size big enough to + hold all non-zero elements or blocks. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + layout (:class:`torch.layout`, required): the desired layout of + returned tensor: :attr:`torch.sparse_csr`, + :attr:`torch.sparse_csc`, :attr:`torch.sparse_bsr`, or + :attr:`torch.sparse_bsc`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> compressed_indices = [0, 2, 4] + >>> plain_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_compressed_tensor(torch.tensor(compressed_indices, dtype=torch.int64), + ... torch.tensor(plain_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double, layout=torch.sparse_csr) + tensor(crow_indices=tensor([0, 2, 4]), + col_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csr) + """ + +def sparse_coo_tensor( + indices: Tensor, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, + is_coalesced: _bool | None = None, +) -> Tensor: + r""" + sparse_coo_tensor(indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None, is_coalesced=None) -> Tensor + + Constructs a :ref:`sparse tensor in COO(rdinate) format + ` with specified values at the given + :attr:`indices`. + + .. note:: + + This function returns an :ref:`uncoalesced tensor + ` when :attr:`is_coalesced` is + unspecified or ``None``. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + indices (array_like): Initial data for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. Will be cast to a :class:`torch.LongTensor` + internally. The indices are the coordinates of the non-zero values in the matrix, and thus + should be two-dimensional where the first dimension is the number of tensor dimensions and + the second dimension is the number of non-zero values. + values (array_like): Initial values for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. + size (list, tuple, or :class:`torch.Size`, optional): Size of the sparse tensor. If not + provided the size will be inferred as the minimum size big enough to hold all non-zero + elements. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if None, infers data type from :attr:`values`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + is_coalesced (bool, optional): When``True``, the caller is + responsible for providing tensor indices that correspond to a + coalesced tensor. If the :attr:`check_invariants` flag is + False, no error will be raised if the prerequisites are not + met and this will lead to silently incorrect results. To force + coalescing please use :meth:`coalesce` on the resulting + Tensor. + Default: None: except for trivial cases (e.g. nnz < 2) the + resulting Tensor has is_coalesced set to ``False```. + + Example:: + + >>> i = torch.tensor([[0, 1, 1], + ... [2, 0, 2]]) + >>> v = torch.tensor([3, 4, 5], dtype=torch.float32) + >>> torch.sparse_coo_tensor(i, v, [2, 4]) + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + size=(2, 4), nnz=3, layout=torch.sparse_coo) + + >>> torch.sparse_coo_tensor(i, v) # Shape inference + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + size=(2, 3), nnz=3, layout=torch.sparse_coo) + + >>> torch.sparse_coo_tensor(i, v, [2, 4], + ... dtype=torch.float64, + ... device=torch.device('cuda:0')) + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + device='cuda:0', size=(2, 4), nnz=3, dtype=torch.float64, + layout=torch.sparse_coo) + + # Create an empty sparse tensor with the following invariants: + # 1. sparse_dim + dense_dim = len(SparseTensor.shape) + # 2. SparseTensor._indices().shape = (sparse_dim, nnz) + # 3. SparseTensor._values().shape = (nnz, SparseTensor.shape[sparse_dim:]) + # + # For instance, to create an empty sparse tensor with nnz = 0, dense_dim = 0 and + # sparse_dim = 1 (hence indices is a 2D tensor of shape = (1, 0)) + >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), [], [1]) + tensor(indices=tensor([], size=(1, 0)), + values=tensor([], size=(0,)), + size=(1,), nnz=0, layout=torch.sparse_coo) + + # and to create an empty sparse tensor with nnz = 0, dense_dim = 1 and + # sparse_dim = 1 + >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), torch.empty([0, 2]), [1, 2]) + tensor(indices=tensor([], size=(1, 0)), + values=tensor([], size=(0, 2)), + size=(1, 2), nnz=0, layout=torch.sparse_coo) + + .. _torch.sparse: https://pytorch.org/docs/stable/sparse.html + """ + +def sparse_csc_tensor( + ccol_indices: Tensor | list, + row_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_csc_tensor(ccol_indices, row_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in CSC (Compressed Sparse Column) + ` with specified values at the given + :attr:`ccol_indices` and :attr:`row_indices`. Sparse matrix + multiplication operations in CSC format are typically faster than that + for sparse tensors in COO format. Make you have a look at :ref:`the + note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + ccol_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, ncols + 1)``. The last element of each batch + is the number of non-zeros. This tensor encodes the index in + values and row_indices depending on where the given column + starts. Each successive number in the tensor subtracted by the + number before it denotes the number of elements in a given + column. + row_indices (array_like): Row coordinates of each element in + values. (B+1)-dimensional tensor with the same length as + values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1+K)-dimensional tensor where ``K`` is the number + of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows, ncols, *densesize)``. If + not provided, the size will be inferred as the minimum size + big enough to hold all non-zero elements. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> ccol_indices = [0, 2, 4] + >>> row_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_csc_tensor(torch.tensor(ccol_indices, dtype=torch.int64), + ... torch.tensor(row_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(ccol_indices=tensor([0, 2, 4]), + row_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csc) + """ + +def sparse_csr_tensor( + crow_indices: Tensor | list, + col_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_csr_tensor(crow_indices, col_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in CSR (Compressed Sparse Row) ` with specified + values at the given :attr:`crow_indices` and :attr:`col_indices`. Sparse matrix multiplication operations + in CSR format are typically faster than that for sparse tensors in COO format. Make you have a look + at :ref:`the note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + crow_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, nrows + 1)``. The last element of each batch + is the number of non-zeros. This tensor encodes the index in + values and col_indices depending on where the given row + starts. Each successive number in the tensor subtracted by the + number before it denotes the number of elements in a given + row. + col_indices (array_like): Column coordinates of each element in + values. (B+1)-dimensional tensor with the same length + as values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1+K)-dimensional tensor where ``K`` is the number + of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows, ncols, *densesize)``. If + not provided, the size will be inferred as the minimum size + big enough to hold all non-zero elements. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> crow_indices = [0, 2, 4] + >>> col_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_csr_tensor(torch.tensor(crow_indices, dtype=torch.int64), + ... torch.tensor(col_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(crow_indices=tensor([0, 2, 4]), + col_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csr) + """ + +def split_copy( + input: Tensor, + split_size: _int | SymInt, + dim: _int = 0, + *, + out: tuple[Tensor, ...] | list[Tensor] | None = None, +) -> None: + r""" + Performs the same operation as :func:`torch.split`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def split_with_sizes( + input: Tensor, + split_sizes: Sequence[_int | SymInt], + dim: _int = 0, +) -> tuple[Tensor, ...]: ... +def split_with_sizes_copy( + input: Tensor, + split_sizes: Sequence[_int | SymInt], + dim: _int = 0, + *, + out: tuple[Tensor, ...] | list[Tensor] | None = None, +) -> None: + r""" + Performs the same operation as :func:`torch.split_with_sizes`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def spmm(input: Tensor, mat2: Tensor) -> Tensor: ... +def sqrt(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sqrt(input, *, out=None) -> Tensor + + Returns a new tensor with the square-root of the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \sqrt{\text{input}_{i}} + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-2.0755, 1.0226, 0.0831, 0.4806]) + >>> torch.sqrt(a) + tensor([ nan, 1.0112, 0.2883, 0.6933]) + """ + +def sqrt_(input: Tensor) -> Tensor: + r""" + sqrt_(input) -> Tensor + + In-place version of :func:`torch.sqrt` + """ + +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: + r""" + square_(input) -> Tensor + + In-place version of :func:`torch.square` + """ + +@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_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 | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + 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 | PySymType = 1, + alpha: Number | _complex | PySymType = 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 | PySymType, + 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], + 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 | PySymType | 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_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 | PySymType | 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 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 | PySymType, + 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 | PySymType, + 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 | PySymType = 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 | PySymType, + alpha: Number | _complex | PySymType = 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.]) + """ + +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`. + + .. 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 | PySymType, + *, + min: _int | None = None, + max: _int | None = None, +) -> None: ... +def sym_constrain_range_for_size( + size: Number | _complex | PySymType, + *, + 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: `None`. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.tensor([[10, 30, 20], [60, 40, 50]]) + >>> max_idx = torch.argmax(t) + >>> torch.take_along_dim(t, max_idx) + tensor([60]) + >>> sorted_idx = torch.argsort(t, dim=1) + >>> torch.take_along_dim(t, sorted_idx, dim=1) + tensor([[10, 20, 30], + [40, 50, 60]]) + """ + +def tan(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + tan(input, *, out=None) -> Tensor + + Returns a new tensor with the tangent of the elements in the :attr:`input` tensor, + where each value in this input tensor is in radians. + + .. math:: + \text{out}_{i} = \tan(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-1.2027, -1.7687, 0.4412, -1.3856]) + >>> torch.tan(a) + tensor([-2.5930, 4.9859, 0.4722, -5.3366]) + """ + +def tan_(input: Tensor) -> Tensor: + r""" + tan_(input) -> Tensor + + In-place version of :func:`torch.tan` + """ + +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: + r""" + tanh_(input) -> Tensor + + In-place version of :func:`torch.tanh` + """ + +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`. + + .. function:: tensor_split(input, sections, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` into :attr:`sections` sections along dimension :attr:`dim`. + If :attr:`input` is divisible by :attr:`sections` along dimension :attr:`dim`, each + section will be of equal size, :code:`input.size(dim) / sections`. If :attr:`input` + is not divisible by :attr:`sections`, the sizes of the first + :code:`int(input.size(dim) % sections)` sections will have size + :code:`int(input.size(dim) / sections) + 1`, and the rest will have size + :code:`int(input.size(dim) / sections)`. + + :attr:`sections` can also be a zero-dimensional long tensor. + + .. function:: tensor_split(input, indices, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` along dimension :attr:`dim` at each of the indices in + :attr:`indices`. For instance, :code:`indices=[2, 3]` and :code:`dim=0` + would result in the tensors :code:`input[:2]`, :code:`input[2:3]`, and + :code:`input[3:]`. + + :attr:`indices` can be a list or tuple of ints, or a one-dimensional long + tensor on the CPU. + + Args: + input (Tensor): the tensor to split + 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`. + + .. function:: tensor_split(input, sections, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` into :attr:`sections` sections along dimension :attr:`dim`. + If :attr:`input` is divisible by :attr:`sections` along dimension :attr:`dim`, each + section will be of equal size, :code:`input.size(dim) / sections`. If :attr:`input` + is not divisible by :attr:`sections`, the sizes of the first + :code:`int(input.size(dim) % sections)` sections will have size + :code:`int(input.size(dim) / sections) + 1`, and the rest will have size + :code:`int(input.size(dim) / sections)`. + + :attr:`sections` can also be a zero-dimensional long tensor. + + .. function:: tensor_split(input, indices, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` along dimension :attr:`dim` at each of the indices in + :attr:`indices`. For instance, :code:`indices=[2, 3]` and :code:`dim=0` + would result in the tensors :code:`input[:2]`, :code:`input[2:3]`, and + :code:`input[3:]`. + + :attr:`indices` can be a list or tuple of ints, or a one-dimensional long + tensor on the CPU. + + Args: + input (Tensor): the tensor to split + 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`. + + .. function:: tensor_split(input, sections, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` into :attr:`sections` sections along dimension :attr:`dim`. + If :attr:`input` is divisible by :attr:`sections` along dimension :attr:`dim`, each + section will be of equal size, :code:`input.size(dim) / sections`. If :attr:`input` + is not divisible by :attr:`sections`, the sizes of the first + :code:`int(input.size(dim) % sections)` sections will have size + :code:`int(input.size(dim) / sections) + 1`, and the rest will have size + :code:`int(input.size(dim) / sections)`. + + :attr:`sections` can also be a zero-dimensional long tensor. + + .. function:: tensor_split(input, indices, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` along dimension :attr:`dim` at each of the indices in + :attr:`indices`. For instance, :code:`indices=[2, 3]` and :code:`dim=0` + would result in the tensors :code:`input[:2]`, :code:`input[2:3]`, and + :code:`input[3:]`. + + :attr:`indices` can be a list or tuple of ints, or a one-dimensional long + tensor on the CPU. + + Args: + input (Tensor): the tensor to split + 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 | PySymType, + value: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: ... +def threshold_( + input: Tensor, + threshold: Number | _complex | PySymType, + value: Number | _complex | PySymType, +) -> 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.) + """ + +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`. + """ + +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 | PySymType = 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=None, *, dim=-1) -> Tensor + + Alias for :func:`torch.trapezoid`. + """ + +@overload +def trapz(y: Tensor, x: Tensor, *, dim: _int = -1) -> Tensor: + r""" + trapz(y, x=None, *, dim=-1) -> Tensor + + Alias for :func:`torch.trapezoid`. + """ + +def triangular_solve( + input: Tensor, + A: Tensor, + upper: _bool = True, + transpose: _bool = False, + unitriangular: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.triangular_solve: + r""" + triangular_solve(b, A, upper=True, transpose=False, unitriangular=False, *, out=None) -> (Tensor, Tensor) + + Solves a system of equations with a square upper or lower triangular invertible matrix :math:`A` + and multiple right-hand sides :math:`b`. + + In symbols, it solves :math:`AX = b` and assumes :math:`A` is square upper-triangular + (or lower-triangular if :attr:`upper`\ `= False`) and does not have zeros on the diagonal. + + `torch.triangular_solve(b, A)` can take in 2D inputs `b, A` or inputs that are + batches of 2D matrices. If the inputs are batches, then returns + batched outputs `X` + + If the diagonal of :attr:`A` contains zeros or elements that are very close to zero and + :attr:`unitriangular`\ `= False` (default) or if the input matrix is badly conditioned, + the result may contain `NaN` s. + + Supports input of float, double, cfloat and cdouble data types. + + .. warning:: + + :func:`torch.triangular_solve` is deprecated in favor of :func:`torch.linalg.solve_triangular` + and will be removed in a future PyTorch release. + :func:`torch.linalg.solve_triangular` has its arguments reversed and does not return a + copy of one of the inputs. + + ``X = torch.triangular_solve(B, A).solution`` should be replaced with + + .. code:: python + + X = torch.linalg.solve_triangular(A, B) + + Args: + b (Tensor): multiple right-hand sides of size :math:`(*, m, k)` where + :math:`*` is zero of more batch dimensions + A (Tensor): the input triangular coefficient matrix of size :math:`(*, m, m)` + where :math:`*` is zero or more batch dimensions + upper (bool, optional): whether :math:`A` is upper or lower triangular. Default: ``True``. + transpose (bool, optional): solves `op(A)X = b` where `op(A) = A^T` if this flag is ``True``, + and `op(A) = A` if it is ``False``. Default: ``False``. + unitriangular (bool, optional): whether :math:`A` is unit triangular. + If True, the diagonal elements of :math:`A` are assumed to be + 1 and not referenced from :math:`A`. Default: ``False``. + + Keyword args: + out ((Tensor, Tensor), optional): tuple of two tensors to write + the output to. Ignored if `None`. Default: `None`. + + Returns: + A namedtuple `(solution, cloned_coefficient)` where `cloned_coefficient` + is a clone of :math:`A` and `solution` is the solution :math:`X` to :math:`AX = b` + (or whatever variant of the system of equations, depending on the keyword arguments.) + + Examples:: + + >>> A = torch.randn(2, 2).triu() + >>> A + tensor([[ 1.1527, -1.0753], + [ 0.0000, 0.7986]]) + >>> b = torch.randn(2, 3) + >>> b + tensor([[-0.0210, 2.3513, -1.5492], + [ 1.5429, 0.7403, -1.0243]]) + >>> torch.triangular_solve(b, A) + torch.return_types.triangular_solve( + solution=tensor([[ 1.7841, 2.9046, -2.5405], + [ 1.9320, 0.9270, -1.2826]]), + cloned_coefficient=tensor([[ 1.1527, -1.0753], + [ 0.0000, 0.7986]])) + """ + +def tril( + input: Tensor, + diagonal: _int | SymInt = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + tril(input, diagonal=0, *, out=None) -> Tensor + + Returns the lower triangular part of the matrix (2-D tensor) or batch of matrices + :attr:`input`, the other elements of the result tensor :attr:`out` are set to 0. + + The lower triangular part of the matrix is defined as the elements on and + below the diagonal. + + The argument :attr:`diagonal` controls which diagonal to consider. If + :attr:`diagonal` = 0, all elements on and below the main diagonal are + retained. A positive value includes just as many diagonals above the main + diagonal, and similarly a negative value excludes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where + :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + Args: + input (Tensor): the input tensor. + diagonal (int, optional): the diagonal to consider + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-1.0813, -0.8619, 0.7105], + [ 0.0935, 0.1380, 2.2112], + [-0.3409, -0.9828, 0.0289]]) + >>> torch.tril(a) + tensor([[-1.0813, 0.0000, 0.0000], + [ 0.0935, 0.1380, 0.0000], + [-0.3409, -0.9828, 0.0289]]) + + >>> b = torch.randn(4, 6) + >>> b + tensor([[ 1.2219, 0.5653, -0.2521, -0.2345, 1.2544, 0.3461], + [ 0.4785, -0.4477, 0.6049, 0.6368, 0.8775, 0.7145], + [ 1.1502, 3.2716, -1.1243, -0.5413, 0.3615, 0.6864], + [-0.0614, -0.7344, -1.3164, -0.7648, -1.4024, 0.0978]]) + >>> torch.tril(b, diagonal=1) + tensor([[ 1.2219, 0.5653, 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.4785, -0.4477, 0.6049, 0.0000, 0.0000, 0.0000], + [ 1.1502, 3.2716, -1.1243, -0.5413, 0.0000, 0.0000], + [-0.0614, -0.7344, -1.3164, -0.7648, -1.4024, 0.0000]]) + >>> torch.tril(b, diagonal=-1) + tensor([[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.4785, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [ 1.1502, 3.2716, 0.0000, 0.0000, 0.0000, 0.0000], + [-0.0614, -0.7344, -1.3164, 0.0000, 0.0000, 0.0000]]) + """ + +def tril_indices( + row: _int, + col: _int, + offset: _int = 0, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + tril_indices(row, col, offset=0, *, dtype=torch.long, device='cpu', layout=torch.strided) -> Tensor + + Returns the indices of the lower triangular part of a :attr:`row`-by- + :attr:`col` matrix in a 2-by-N Tensor, where the first row contains row + coordinates of all indices and the second row contains column coordinates. + Indices are ordered based on rows and then columns. + + The lower triangular part of the matrix is defined as the elements on and + below the diagonal. + + The argument :attr:`offset` controls which diagonal to consider. If + :attr:`offset` = 0, all elements on and below the main diagonal are + retained. A positive value includes just as many diagonals above the main + diagonal, and similarly a negative value excludes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` + where :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + .. note:: + When running on CUDA, ``row * col`` must be less than :math:`2^{59}` to + prevent overflow during calculation. + + Args: + row (``int``): number of rows in the 2-D matrix. + col (``int``): number of columns in the 2-D matrix. + offset (``int``): diagonal offset from the main diagonal. + Default: if not provided, 0. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor, + only support ``torch.int``, ``torch.long``. Default: if ``None``, ``torch.long``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + layout (:class:`torch.layout`, optional): currently only support ``torch.strided``. + + Example:: + + >>> a = torch.tril_indices(3, 3) + >>> a + tensor([[0, 1, 1, 2, 2, 2], + [0, 0, 1, 0, 1, 2]]) + + >>> a = torch.tril_indices(4, 3, -1) + >>> a + tensor([[1, 2, 2, 3, 3, 3], + [0, 0, 1, 0, 1, 2]]) + + >>> a = torch.tril_indices(4, 3, 1) + >>> a + tensor([[0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3], + [0, 1, 0, 1, 2, 0, 1, 2, 0, 1, 2]]) + """ + +def triplet_margin_loss( + anchor: Tensor, + positive: Tensor, + negative: Tensor, + margin: _float = 1.0, + p: _float = 2, + eps: _float = 1e-06, + swap: _bool = False, + reduction: _int = 1, +) -> Tensor: ... +def triu( + input: Tensor, + diagonal: _int | SymInt = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + triu(input, diagonal=0, *, out=None) -> Tensor + + Returns the upper triangular part of a matrix (2-D tensor) or batch of matrices + :attr:`input`, the other elements of the result tensor :attr:`out` are set to 0. + + The upper triangular part of the matrix is defined as the elements on and + above the diagonal. + + The argument :attr:`diagonal` controls which diagonal to consider. If + :attr:`diagonal` = 0, all elements on and above the main diagonal are + retained. A positive value excludes just as many diagonals above the main + diagonal, and similarly a negative value includes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where + :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + Args: + input (Tensor): the input tensor. + diagonal (int, optional): the diagonal to consider + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.2072, -1.0680, 0.6602], + [ 0.3480, -0.5211, -0.4573]]) + >>> torch.triu(a) + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.0000, -1.0680, 0.6602], + [ 0.0000, 0.0000, -0.4573]]) + >>> torch.triu(a, diagonal=1) + tensor([[ 0.0000, 0.5207, 2.0049], + [ 0.0000, 0.0000, 0.6602], + [ 0.0000, 0.0000, 0.0000]]) + >>> torch.triu(a, diagonal=-1) + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.2072, -1.0680, 0.6602], + [ 0.0000, -0.5211, -0.4573]]) + + >>> b = torch.randn(4, 6) + >>> b + tensor([[ 0.5876, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [-0.2447, 0.9556, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.4333, 0.3146, 0.6576, -1.0432, 0.9348, -0.4410], + [-0.9888, 1.0679, -1.3337, -1.6556, 0.4798, 0.2830]]) + >>> torch.triu(b, diagonal=1) + tensor([[ 0.0000, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [ 0.0000, 0.0000, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.0000, 0.0000, 0.0000, -1.0432, 0.9348, -0.4410], + [ 0.0000, 0.0000, 0.0000, 0.0000, 0.4798, 0.2830]]) + >>> torch.triu(b, diagonal=-1) + tensor([[ 0.5876, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [-0.2447, 0.9556, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.0000, 0.3146, 0.6576, -1.0432, 0.9348, -0.4410], + [ 0.0000, 0.0000, -1.3337, -1.6556, 0.4798, 0.2830]]) + """ + +def triu_indices( + row: _int, + col: _int, + offset: _int = 0, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + triu_indices(row, col, offset=0, *, dtype=torch.long, device='cpu', layout=torch.strided) -> Tensor + + Returns the indices of the upper triangular part of a :attr:`row` by + :attr:`col` matrix in a 2-by-N Tensor, where the first row contains row + coordinates of all indices and the second row contains column coordinates. + Indices are ordered based on rows and then columns. + + The upper triangular part of the matrix is defined as the elements on and + above the diagonal. + + The argument :attr:`offset` controls which diagonal to consider. If + :attr:`offset` = 0, all elements on and above the main diagonal are + retained. A positive value excludes just as many diagonals above the main + diagonal, and similarly a negative value includes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` + where :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + .. note:: + When running on CUDA, ``row * col`` must be less than :math:`2^{59}` to + prevent overflow during calculation. + + Args: + row (``int``): number of rows in the 2-D matrix. + col (``int``): number of columns in the 2-D matrix. + offset (``int``): diagonal offset from the main diagonal. + Default: if not provided, 0. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor, + only support ``torch.int``, ``torch.long``. Default: if ``None``, ``torch.long``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + layout (:class:`torch.layout`, optional): currently only support ``torch.strided``. + + Example:: + + >>> a = torch.triu_indices(3, 3) + >>> a + tensor([[0, 0, 0, 1, 1, 2], + [0, 1, 2, 1, 2, 2]]) + + >>> a = torch.triu_indices(4, 3, -1) + >>> a + tensor([[0, 0, 0, 1, 1, 1, 2, 2, 3], + [0, 1, 2, 0, 1, 2, 1, 2, 2]]) + + >>> a = torch.triu_indices(4, 3, 1) + >>> a + tensor([[0, 0, 1], + [1, 2, 2]]) + """ + +def true_divide( + input: Tensor | Number, + other: Tensor | Number, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + true_divide(dividend, divisor, *, out) -> Tensor + + Alias for :func:`torch.div` with ``rounding_mode=None``. + """ + +def trunc(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + trunc(input, *, out=None) -> Tensor + + Returns a new tensor with the truncated integer values of + the elements of :attr:`input`. + + For integer inputs, follows the array-api convention of returning a + copy of the input tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 3.4742, 0.5466, -0.8008, -0.9079]) + >>> torch.trunc(a) + tensor([ 3., 0., -0., -0.]) + """ + +def trunc_(input: Tensor) -> Tensor: + r""" + trunc_(input) -> Tensor + + In-place version of :func:`torch.trunc` + """ + +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])) + """ + +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. + """ + +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 | PySymType | 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_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 | PySymType | 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 + """ + +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], + *, + 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 | PySymType, + 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 | PySymType, +) -> 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 | PySymType, + other: Number | _complex | PySymType, +) -> 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 | PySymType, + 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 | PySymType, + *, + 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: + r""" + xlogy_(input, other) -> Tensor + + In-place version of :func:`torch.xlogy` + """ + +@overload +def xlogy_(input: Tensor, other: Number | _complex | PySymType) -> Tensor: + r""" + xlogy_(input, other) -> Tensor + + In-place version of :func:`torch.xlogy` + """ + +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.]) + """ + +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/.venv/lib/python3.12/site-packages/torch/_C/__init__.pyi b/.venv/lib/python3.12/site-packages/torch/_C/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4e5157d2e91ce74a46f913bf113e5cb602c569fe --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/__init__.pyi @@ -0,0 +1,12539 @@ +# @generated by tools/pyi/gen_pyi.py from torch/_C/__init__.pyi.in +# mypy: disable-error-code="type-arg" +# mypy: allow-untyped-defs +# ruff: noqa: F401 + +from collections.abc import Callable, Iterable, Iterator, Sequence +from contextlib import AbstractContextManager +from enum import Enum, IntEnum +from pathlib import Path +from types import EllipsisType +from typing import ( + Any, + AnyStr, + Generic, + IO, + Literal, + NamedTuple, + overload, + Protocol, + runtime_checkable, + SupportsIndex, + TypeAlias, + TypeVar, +) +from typing_extensions import ParamSpec, Self + +import numpy + +import torch +from torch import inf, SymInt, Tensor +from torch._C import ( + _acc, + _aoti, + _cpu, + _dynamo, + _export, + _functionalization, + _functorch, + _lazy, + _lazy_ts_backend, + _nn, + _onnx, + _VariableFunctions, + _verbose, +) +from torch._prims_common import DeviceLikeType +from torch.autograd.graph import Node as _Node +from torch.cuda import _POOL_HANDLE +from torch.distributed.device_mesh import DeviceMesh +from torch.distributed.tensor._op_schema import OpSchema +from torch.distributed.tensor.placement_types import Placement +from torch.fx.node import Node as FxNode +from torch.package import PackageExporter +from torch.storage import TypedStorage, UntypedStorage +from torch.types import ( + _bool, + _bytes, + _complex, + _device, + _dispatchkey, + _dtype, + _float, + _int, + _layout, + _qscheme, + _size, + _str, + _symsize, + Device, + IntLikeType, + Number, + PySymType, + Storage, +) +from torch.utils._python_dispatch import TorchDispatchMode +from torch.utils.checkpoint import GraphExecGroup +from torch.xpu import _POOL_HANDLE as XPU_POOL_HANDLE + +# This module is defined in torch/csrc/Module.cpp + +K = TypeVar("K") # noqa: PYI001 +T = TypeVar("T") # noqa: PYI001 +S = TypeVar("S", bound=torch.Tensor) # noqa: PYI001 +P = ParamSpec("P") # noqa: PYI001 +R = TypeVar("R", covariant=True) # return value (always covariant) # noqa: PYI001 +T_co = TypeVar("T_co", covariant=True) # noqa: PYI001 + +@runtime_checkable +class _NestedSequence(Protocol[T_co]): + """A protocol for representing nested sequences. + + References:: + `numpy._typing._NestedSequence` + + """ + + def __len__(self, /) -> _int: ... + def __getitem__(self, index: _int, /) -> T_co | _NestedSequence[T_co]: ... + def __contains__(self, x: object, /) -> _bool: ... + def __iter__(self, /) -> Iterator[T_co | _NestedSequence[T_co]]: ... + def __reversed__(self, /) -> Iterator[T_co | _NestedSequence[T_co]]: ... + def count(self, value: Any, /) -> _int: ... + def index(self, value: Any, /) -> _int: ... + +# Defined in torch/csrc/Device.cpp +class device: + type: str # THPDevice_type + index: _int # THPDevice_index + + def __get__(self, instance, owner=None) -> device: ... + + # THPDevice_pynew + @overload + def __init__(self, device: DeviceLikeType) -> None: ... + @overload + def __init__(self, type: str, index: _int) -> None: ... + + # Uncomment if we ever make torch.device a decorator + # def __call__(self, func: T) -> T: ... + + def __enter__(self) -> Self: ... + def __exit__(self, exc_type, exc_val, exc_tb) -> None: ... + def __reduce__(self) -> tuple[Any, ...]: ... # THPDevice_reduce + +# Defined in torch/csrc/Stream.cpp +class Stream: + stream_id: _int # Stream id + device_index: _int + device_type: _int + + device: _device # The device of the stream + + @overload + def __new__( + cls, + device: DeviceLikeType | None = None, + *, + priority: _int = 0, + ) -> Self: ... + @overload + def __new__( + cls, + stream_id: _int, + device_index: _int, + device_type: _int, + *, + priority: _int = 0, + ) -> Self: ... + def query(self) -> _bool: ... + def synchronize(self) -> None: ... + def is_capturing(self) -> _bool: ... + def wait_event(self, event: Event) -> None: ... + def wait_stream(self, other: Stream) -> None: ... + def record_event(self, event: Event | None = None) -> Event: ... + def __hash__(self) -> _int: ... + def __eq__(self, other: object) -> _bool: ... + def __enter__(self) -> Self: ... + def __exit__(self, exc_type, exc_val, exc_tb) -> None: ... + +# Defined in torch/csrc/Event.cpp +class Event: + device: _device # The device of the Event + event_id: _int # The raw event created by device backend + + def __new__( + cls, + device: DeviceLikeType | None = None, + *, + enable_timing: _bool = False, + blocking: _bool = False, + interprocess: _bool = False, + ) -> Self: ... + @classmethod + def from_ipc_handle(cls, device: _device, ipc_handle: bytes) -> Event: ... + def record(self, stream: Stream | None = None) -> None: ... + def wait(self, stream: Stream | None = None) -> None: ... + def query(self) -> _bool: ... + def elapsed_time(self, other: Event) -> _float: ... + def synchronize(self) -> None: ... + def ipc_handle(self) -> bytes: ... + +# Defined in torch/csrc/Size.cpp +class Size(tuple[_int, ...]): + # TODO: __reduce__ + + @overload + def __getitem__(self: Size, key: SupportsIndex, /) -> _int: ... + @overload + def __getitem__(self: Size, key: slice, /) -> Size: ... + # Note: torch.Size does not support adding non-integer tuples. + def __add__(self, other: tuple[_int, ...], /) -> Size: ... # type: ignore[override] + def __radd__(self: Size, other: tuple[_int, ...], /) -> Size: ... + def __mul__(self, other: SupportsIndex, /) -> Size: ... + def __rmul__(self, other: SupportsIndex, /) -> Size: ... + def numel(self: Size, /) -> _int: ... + +# Defined in torch/csrc/Dtype.cpp +class dtype: + # TODO: __reduce__ + is_floating_point: _bool + is_complex: _bool + is_signed: _bool + itemsize: _int + abbr: str + def to_real(self) -> dtype: ... + def to_complex(self) -> dtype: ... + +# Defined in torch/csrc/TypeInfo.cpp +class iinfo: + bits: _int + min: _int + max: _int + dtype: str + + def __init__(self, dtype: _dtype) -> None: ... + +class finfo: + bits: _int + min: _float + max: _float + eps: _float + tiny: _float + smallest_normal: _float + resolution: _float + dtype: str + + @overload + def __init__(self, dtype: _dtype) -> None: ... + @overload + def __init__(self) -> None: ... + +float32: dtype = ... +float: dtype = ... +float64: dtype = ... +double: dtype = ... +float16: dtype = ... +bfloat16: dtype = ... +float8_e4m3fn: dtype = ... +float8_e4m3fnuz: dtype = ... +float8_e5m2: dtype = ... +float8_e5m2fnuz: dtype = ... +float8_e8m0fnu: dtype = ... +float4_e2m1fn_x2: dtype = ... +half: dtype = ... +uint8: dtype = ... +uint16: dtype = ... +uint32: dtype = ... +uint64: dtype = ... +int8: dtype = ... +int16: dtype = ... +short: dtype = ... +int32: dtype = ... +int: dtype = ... +int64: dtype = ... +long: dtype = ... +complex32: dtype = ... +complex64: dtype = ... +chalf: dtype = ... +cfloat: dtype = ... +complex128: dtype = ... +cdouble: dtype = ... +bcomplex32: dtype = ... +quint8: dtype = ... +qint8: dtype = ... +qint32: dtype = ... +bool: dtype = ... +quint4x2: dtype = ... +quint2x4: dtype = ... +bits1x8: dtype = ... +bits2x4: dtype = ... +bits4x2: dtype = ... +bits8: dtype = ... +bits16: dtype = ... + +# Defined in torch/csrc/Layout.cpp +class layout: ... + +# Defined in torch/csrc/utils/disable_torch_function.cpp +def DisableTorchFunction() -> AbstractContextManager[None]: ... +def DisableTorchFunctionSubclass() -> AbstractContextManager[None]: ... + +# Defined in torch/csrc/utils/tensor_layouts.cpp +strided: layout = ... +sparse_coo: layout = ... +sparse_csr: layout = ... +sparse_csc: layout = ... +sparse_bsr: layout = ... +sparse_bsc: layout = ... +_mkldnn: layout = ... +jagged: layout = ... + +# Defined in torch/csrc/MemoryFormat.cpp +class memory_format: ... + +# Defined in torch/csrc/utils/tensor_memoryformats.cpp +contiguous_format: memory_format = ... +channels_last: memory_format = ... +channels_last_3d: memory_format = ... +preserve_format: memory_format = ... + +# Defined in torch/csrc/QScheme.cpp +class qscheme: ... + +# Defined in torch/csrc/utils/tensor_qschemes.h +per_tensor_affine: qscheme = ... +per_channel_affine: qscheme = ... +per_tensor_symmetric: qscheme = ... +per_channel_symmetric: qscheme = ... +per_channel_affine_float_qparams: qscheme = ... + +# Defined in torch/csrc/autograd/python_function.cpp +class _FunctionBase: + saved_tensors: tuple[Tensor] + _raw_saved_tensors: tuple[Any] + next_functions: tuple[tuple[Any, _int], ...] + needs_input_grad: tuple[_bool] + metadata: dict + _materialize_non_diff_grads: _bool + # skip adding type hints for the fields that have wrappers defined + # in torch/autograd/function.py + def _sequence_nr(self) -> _int: ... + def _register_hook_dict(self, tensor: Tensor) -> None: ... + def register_hook(self, hook: Callable[..., Any]) -> Any: ... + def register_prehook(self, hook: Callable[..., Any]) -> Any: ... + +# Defined in torch/csrc/autograd/python_legacy_variable.cpp +class _LegacyVariableBase(Tensor): # inherits from Tensor to appease mypy + def __init__( + self, + data: Tensor | None = ..., + requires_grad: _bool | None = ..., + volatile: _bool | None = ..., + _grad_fn: _FunctionBase | None = ..., + ) -> None: ... + +# Defined in torch/csrc/jit/python/init.cpp +class IODescriptor: ... +class JITException(Exception): ... + +class Future(Generic[T]): + def __init__(self, devices: list[device]) -> None: ... + def done(self) -> _bool: ... + def value(self) -> T: ... + def wait(self) -> T: ... + def add_done_callback(self, callback: Callable) -> None: ... + def then(self, callback: Callable) -> Future[T]: ... + def set_result(self, result: T) -> None: ... + def _set_unwrap_func(self, callback: Callable) -> None: ... + +class _Await: + def __init__(self) -> None: ... + def fn(self) -> Callable: ... + def args(self) -> tuple[Any, ...]: ... + def is_nowait(self) -> _bool: ... + +def _jit_set_num_profiled_runs(num: _size) -> _size: ... + +# Defined in torch/csrc/jit/passes/mobile_optimizer_type.h +class _MobileOptimizerType: ... + +CONV_BN_FUSION: _MobileOptimizerType +INSERT_FOLD_PREPACK_OPS: _MobileOptimizerType +REMOVE_DROPOUT: _MobileOptimizerType +FUSE_ADD_RELU: _MobileOptimizerType +HOIST_CONV_PACKED_PARAMS: _MobileOptimizerType +VULKAN_AUTOMATIC_GPU_TRANSFER: _MobileOptimizerType + +def fork(*args: Any, **kwargs: Any) -> Future: ... +def wait(fut: Future) -> Any: ... +def _awaitable(*args: Any, **kwargs: Any) -> _Await: ... +def _awaitable_wait(aw: _Await) -> Any: ... +def _awaitable_nowait(x: Any) -> _Await: ... +def _collect_all(futures: list[Future]) -> Future: ... +def _set_print_stack_traces_on_fatal_signal(print: _bool) -> None: ... +def unify_type_list(types: list[JitType]) -> JitType: ... +def _freeze_module( + module: ScriptModule, + preserved_attrs: list[str] = ..., + freeze_interfaces: _bool = True, + preserveParameters: _bool = True, +) -> ScriptModule: ... +def _jit_pass_optimize_frozen_graph(Graph, optimize_numerics: _bool = True) -> None: ... +def _jit_pass_optimize_for_inference( + module: torch.jit.ScriptModule, + other_methods: list[str] = ..., +) -> None: ... +def _jit_pass_fold_frozen_conv_bn(graph: Graph): ... +def _jit_pass_fold_frozen_conv_add_or_sub(graph: Graph): ... +def _jit_pass_fold_frozen_conv_mul_or_div(graph: Graph): ... +def _jit_pass_fuse_frozen_conv_add_relu(graph: Graph): ... +def _jit_pass_concat_frozen_linear(graph: Graph): ... +def _jit_pass_convert_frozen_ops_to_mkldnn(graph: Graph): ... +def _jit_pass_transpose_frozen_linear(graph: Graph): ... +def _jit_pass_remove_dropout(module: torch.jit.ScriptModule): ... +def _is_tracing() -> _bool: ... +def _jit_init() -> _bool: ... +def _jit_flatten(arg: Any) -> tuple[list[Tensor], IODescriptor]: ... +def _jit_unflatten(vars: list[Tensor], desc: IODescriptor) -> Any: ... +def _jit_get_operation(op_name: str) -> tuple[Callable, list[str]]: ... +def _get_operation_overload( + op_name: str, + op_overload_name: str, +) -> tuple[Callable, Callable, list[Any]]: ... +def _get_schema(op_name: str, overload_name: str) -> FunctionSchema: ... +def _jit_pass_optimize_for_mobile( + module: torch.jit.ScriptModule, + optimization_blocklist: set[_MobileOptimizerType], + preserved_methods: list[AnyStr], +) -> torch.jit.ScriptModule: ... +def _clone_module_with_class( + module: torch.jit.ScriptModule, + ignored_methods: list[AnyStr], + ignored_attributes: list[AnyStr], +) -> torch.jit.ScriptModule: ... +def _jit_pass_vulkan_optimize_for_mobile( + module: torch.jit.ScriptModule, + optimization_blocklist: set[_MobileOptimizerType], + preserved_methods: list[AnyStr], +) -> torch.jit.ScriptModule: ... +def _jit_pass_metal_optimize_for_mobile( + module: torch.jit.ScriptModule, + preserved_methods: list[AnyStr], +) -> torch.jit.ScriptModule: ... +def _jit_pass_inline(Graph) -> None: ... +def _jit_pass_constant_propagation(Graph) -> None: ... +def _jit_pass_propagate_shapes_on_graph(Graph) -> None: ... +def _jit_register_decomposition_for_schema(schema: FunctionSchema, Graph) -> None: ... +def _jit_erase_non_input_shape_information(Graph) -> None: ... +def _jit_get_schemas_for_operator(name: str) -> list[FunctionSchema]: ... +def _jit_get_all_schemas() -> list[FunctionSchema]: ... +def _jit_check_alias_annotation( + g: Graph, + args: tuple[Any, ...], + unqualified_op_name: str, +): ... +def _jit_can_fuse_on_cpu() -> _bool: ... +def _jit_can_fuse_on_gpu() -> _bool: ... +def _jit_can_fuse_on_cpu_legacy() -> _bool: ... +def _debug_get_fusion_group_inlining() -> _bool: ... +def _debug_set_fusion_group_inlining(enable: _bool): ... +def _jit_texpr_fuser_enabled() -> _bool: ... +def _jit_nvfuser_enabled() -> _bool: ... +def _jit_llga_enabled() -> _bool: ... +def _jit_set_llga_enabled(enable: _bool): ... +def _llvm_enabled() -> _bool: ... +def _jit_override_can_fuse_on_cpu(override: _bool): ... +def _jit_override_can_fuse_on_gpu(override: _bool): ... +def _jit_override_can_fuse_on_cpu_legacy(override: _bool): ... +def _jit_set_symbolic_shapes_test_mode(override: _bool): ... +def _jit_symbolic_shapes_test_mode_enabled() -> _bool: ... +def _jit_set_texpr_fuser_enabled(enable: _bool): ... +def _jit_set_te_must_use_llvm_cpu(use_llvm: _bool): ... +def _jit_set_nvfuser_enabled(enable: _bool) -> _bool: ... +def _jit_set_autocast_mode(enable: _bool) -> _bool: ... +def _jit_cat_wo_conditionals(optimize_cat: _bool): ... +def _jit_opt_conditionals(opt_conds: _bool): ... +def _jit_pass_canonicalize(graph: Graph, keep_unique_names: _bool = True): ... +def _jit_pass_erase_shape_information(graph: Graph): ... +def _jit_pass_fold_convbn(module: torch.jit.ScriptModule): ... +def _jit_pass_insert_observers( + module: torch.jit.ScriptModule, + method_name: str, + qconfig_dict: dict[str, Any], + inplace: _bool, + quant_type: _int, +): ... +def _jit_pass_insert_quant_dequant( + module: torch.jit.ScriptModule, + method_name: str, + inplace: _bool, + debug: _bool, + quant_type: _int, +): ... +def _jit_pass_insert_quant_dequant_for_ondevice_ptq( + module: torch.jit.ScriptModule, + method_name: str, + inplace: _bool, + debug: _bool, + quant_type: _int, +): ... +def _jit_pass_quant_finalize( + module: torch.jit.ScriptModule, + quant_type: _int, + preserved_attrs: Sequence[str], +): ... +def _jit_pass_quant_finalize_for_ondevice_ptq( + module: torch.jit.ScriptModule, + quant_type: _int, + method_name: str, +): ... +def _jit_pass_insert_observer_method_for_ondevice_ptq( + module: torch.jit.ScriptModule, + method_name: str, + qconfig_dict: dict[str, Any], + inplace: _bool, + quant_type: _int, +): ... +def _jit_set_profiling_executor(profiling_flag: _bool) -> _bool: ... +def _jit_set_profiling_mode(profiling_flag: _bool) -> _bool: ... +def _jit_set_fusion_strategy( + strategy: list[tuple[str, _int]], +) -> list[tuple[str, _int]]: ... +def _jit_try_infer_type(obj: Any) -> InferredType: ... +def _jit_get_trigger_value(trigger_name: str) -> _int: ... + +# Defined in torch/csrc/jit/python/script_init.cpp +ResolutionCallback: TypeAlias = Callable[[str], Callable[..., Any]] + +# Defined in torch/csrc/jit/python/script_init.cpp +# and torch/csrc/jit/python/init.cpp +def _maybe_call_torch_function_for_op_packet( + op_overload_packet: Any, + *args: Any, + **kwargs: Any, +) -> Any: ... +def _check_schema_allow_fake_script_object( + schema: FunctionSchema, + *args: Any, + **kwargs: Any, +) -> _bool: ... +def _create_function_from_graph(qualname: str, graph: Graph) -> ScriptFunction: ... +def _debug_set_autodiff_subgraph_inlining(disabled: _bool) -> None: ... +def _ivalue_tags_match(lhs: ScriptModule, rhs: ScriptModule) -> _bool: ... +def _jit_assert_is_instance(obj: Any, type: JitType): ... +def _jit_clear_class_registry() -> None: ... +def _jit_set_emit_hooks( + ModuleHook: Callable | None, + FunctionHook: Callable | None, +) -> None: ... +def _jit_get_emit_hooks() -> tuple[Callable, Callable]: ... +def _load_for_lite_interpreter( + filename: str | Path, + map_location: DeviceLikeType | None, +): ... +def _load_for_lite_interpreter_from_buffer( + buffer: IO[bytes], + map_location: DeviceLikeType | None, +): ... +def _export_operator_list(module: LiteScriptModule): ... +def _quantize_ondevice_ptq_dynamic(module: LiteScriptModule, method_name: str): ... +def _get_model_bytecode_version(filename: str | Path) -> _int: ... +def _get_model_bytecode_version_from_buffer(buffer: IO[bytes]) -> _int: ... +def _backport_for_mobile( + filename_input: str | Path, + filename_output: str | Path, + to_version: _int, +) -> None: ... +def _backport_for_mobile_from_buffer( + buffer: IO[bytes], + filename_output: str | Path, + to_version: _int, +) -> None: ... +def _backport_for_mobile_to_buffer( + filename_input: str | Path, + to_version: _int, +) -> bytes: ... +def _backport_for_mobile_from_buffer_to_buffer( + buffer: IO[bytes], + to_version: _int, +) -> bytes: ... +def _get_model_ops_and_info(filename: str | Path): ... +def _get_model_ops_and_info_from_buffer(buffer: IO[bytes]): ... +def _get_mobile_model_contained_types(filename: str | Path): ... +def _get_mobile_model_contained_types_from_buffer(buffer: IO[bytes]): ... +def _logging_set_logger(logger: LoggerBase) -> LoggerBase: ... +def _get_graph_executor_optimize(optimize: _bool | None = None) -> _bool: ... +def _set_graph_executor_optimize(optimize: _bool): ... +def _export_opnames(module: ScriptModule) -> list[str]: ... +def _create_function_from_trace( + qualname: str, + func: Callable[..., Any], + input_tuple: tuple[Any, ...], + var_lookup_fn: Callable[[Tensor], str], + strict: _bool, + force_outplace: _bool, + argument_names: list[str], +) -> tuple[Graph, Stack]: ... +def _create_function_from_trace_with_dict( + qualname: str, + func: Callable[..., Any], + input_dict: dict[str, Any], + var_lookup_fn: Callable[[Tensor], str], + strict: _bool, + force_outplace: _bool, + argument_names: list[str], +) -> tuple[Graph, Stack]: ... +def _jit_is_script_object(obj: Any) -> _bool: ... +def _last_executed_optimized_graph() -> Graph: ... +def parse_type_comment(comment: str) -> Decl: ... +def _get_upgraders_map_size() -> _int: ... +def _get_upgraders_entry_map() -> dict[str, str]: ... +def _dump_upgraders_map() -> dict[str, str]: ... +def _test_only_populate_upgraders(content: dict[str, str]) -> None: ... +def _test_only_remove_upgraders(content: dict[str, str]) -> None: ... +def merge_type_from_type_comment( + decl: Decl, + type_annotation_decl: Decl, + is_method: _bool, +) -> Decl: ... +def parse_ir(input: str, parse_tensor_constants: _bool = False) -> Graph: ... +def parse_schema(schema: str) -> FunctionSchema: ... +def get_device(input: Tensor) -> _int: ... +def _resolve_type_from_object( + obj: Any, + range: SourceRange, + rcb: ResolutionCallback, +) -> JitType: ... +def _create_module_with_type(ty: JitType) -> ScriptModule: ... +def _create_object_with_type(ty: ClassType) -> ScriptObject: ... +def _run_emit_module_hook(m: ScriptModule): ... +def _replace_overloaded_method_decl( + overload_decl: Decl, + implementation_def: Def, + new_name: str, +) -> Def: ... +def _jit_pass_lower_all_tuples(graph: Graph) -> None: ... +def _jit_pass_onnx_set_dynamic_input_shape( + graph: Graph, + dynamic_axes: dict[str, dict[_int, str]], + input_names: list[str], +) -> None: ... +def _jit_pass_onnx_graph_shape_type_inference( + graph: Graph, + params_dict: dict[str, IValue], + opset_version: _int, +) -> None: ... +def _jit_pass_onnx_assign_output_shape( + graph: Graph, + tensors: list[Tensor], + desc: IODescriptor, + onnx_shape_inference: _bool, + is_script: _bool, + opset_version: _int, +) -> None: ... +def _jit_pass_onnx_remove_inplace_ops_for_onnx( + graph: Graph, + module: ScriptModule | None = None, +) -> None: ... +def _jit_pass_remove_inplace_ops(graph: Graph) -> None: ... +def _jit_pass_remove_mutation(graph: Graph) -> _bool: ... +def _jit_pass_canonicalize_graph_fuser_ops(graph: Graph) -> None: ... +def _jit_pass_peephole( + graph: Graph, + disable_shape_peepholes: _bool = False, +) -> None: ... +def _jit_pass_onnx_autograd_function_process(graph: Graph) -> None: ... +def _jit_pass_fuse_addmm(graph: Graph) -> None: ... +def _jit_pass_onnx_preprocess(graph: Graph) -> None: ... +def _jit_pass_prepare_division_for_onnx(graph: Graph) -> None: ... +def _jit_pass_onnx_remove_print(graph: Graph) -> None: ... +def _jit_pass_onnx_preprocess_caffe2(graph: Graph) -> None: ... +def _jit_pass_onnx_unpack_quantized_weights( + graph: Graph, + paramsDict: dict[str, IValue], +) -> dict[str, IValue]: ... +def _jit_pass_onnx_quantization_insert_permutes( + graph: Graph, + paramsDict: dict[str, IValue], +) -> dict[str, IValue]: ... +def _jit_pass_custom_pattern_based_rewrite_graph( + pattern: str, + fused_node_name: str, + graph: Graph, +) -> None: ... +def _jit_onnx_list_model_parameters( + module: ScriptModule, +) -> tuple[ScriptModule, list[IValue]]: ... +def _jit_pass_erase_number_types(graph: Graph) -> None: ... +def _jit_pass_onnx_lint(graph: Graph) -> None: ... +def _jit_pass_onnx( + graph: Graph, + _jit_pass_onnx: _onnx.OperatorExportTypes, +) -> Graph: ... +def _jit_pass_onnx_scalar_type_analysis( + graph: Graph, + lowprecision_cast: _bool, + opset_version: _int, +) -> None: ... +def _jit_pass_onnx_peephole( + graph: Graph, + opset_version: _int, + fixed_batch_size: _bool, +) -> None: ... +def _jit_pass_dce_allow_deleting_nodes_with_side_effects(graph: Graph) -> None: ... +def _jit_pass_onnx_function_substitution(graph: Graph) -> None: ... +def _jit_pass_onnx_function_extraction( + graph: Graph, + module_names: set[str], + param_names: list[str], +) -> dict[Node, dict[str, str]]: ... +def _jit_pass_onnx_clear_scope_records() -> None: ... +def _jit_pass_onnx_track_scope_attributes( + graph: Graph, + onnx_attrs: dict[str, Any], +) -> None: ... +def _jit_is_onnx_log_enabled() -> _bool: ... +def _jit_set_onnx_log_enabled(enabled: _bool) -> None: ... +def _jit_set_onnx_log_output_stream(stream_name: str) -> None: ... +def _jit_onnx_log(*args: Any) -> None: ... +def _jit_pass_lower_graph(graph: Graph, m: Module) -> tuple[Graph, list[IValue]]: ... +def _jit_pass_inline_fork_wait(graph: Graph) -> None: ... +def _jit_pass_onnx_deduplicate_initializers( + graph: Graph, + params_dict: dict[str, IValue], + is_train: _bool, +) -> dict[str, IValue]: ... +def _jit_pass_onnx_eval_peephole( + graph: Graph, + paramsDict: dict[str, IValue], +) -> dict[str, IValue]: ... +def _jit_pass_onnx_constant_fold( + graph: Graph, + paramsDict: dict[str, IValue], + opset_version: _int, +) -> dict[str, IValue]: ... +def _jit_pass_onnx_eliminate_unused_items( + graph: Graph, + paramsDict: dict[str, IValue], +) -> dict[str, IValue]: ... +def _jit_pass_onnx_cast_all_constant_to_floating(graph: Graph) -> None: ... +def _jit_pass_filter_non_tensor_arguments( + params: dict[str, IValue], +) -> dict[str, Tensor]: ... +def _jit_decay_packed_param_input_types(graph: Graph) -> None: ... +def _jit_pass_onnx_node_shape_type_inference( + n: Node, + paramsDict: dict[str, IValue], + opset_version: _int, +) -> None: ... +def _jit_onnx_convert_pattern_from_subblock( + block: Block, + n: Node, + env: dict[Value, Value], + values_in_env: set[Value], +) -> list[Value]: ... +def _jit_pass_onnx_block( + old_block: Block, + new_block: Block, + operator_export_type: _onnx.OperatorExportTypes, + env: dict[Value, Value], + values_in_env: set[Value], + is_sub_block: _bool, +) -> dict[Value, Value]: ... +def _jit_pass_onnx_assign_scoped_names_for_node_and_value(graph: Graph) -> None: ... +def _jit_pass_fixup_onnx_controlflow_node( + n: Node, + opset_version: _int, +) -> list[Value]: ... +def _jit_onnx_create_full_scope_name(class_name: str, variable_name: str) -> str: ... +def _compile_graph_to_code_table(name: str, graph: Graph) -> IValue: ... +def _generate_upgraders_graph() -> dict[str, Graph]: ... +def _calculate_package_version_based_on_upgraders(val: _bool): ... +def _get_version_calculator_flag() -> _bool: ... +def _jit_script_interface_compile( + name: str, + class_def: ClassDef, + rcb: ResolutionCallback, + is_module: _bool, +): ... +def _jit_script_compile_overload( + qualname: str, + overload_decl: Decl, + implementation_def: Def, + rcb: ResolutionCallback, + implementation_defaults: dict[str, Any], + signature: Any, +): ... +def _jit_script_compile( + qual_name: str, + definition: Def, + rcb: ResolutionCallback, + defaults: dict[str, Any], +): ... +def _jit_script_class_compile( + qual_name: str, + definition: ClassDef, + defaults: dict[str, dict[str, Any]], + rcb: ResolutionCallback, +): ... +def _parse_source_def(src: str) -> Def: ... +def import_ir_module( + cu: CompilationUnit, + filename: str | Path, + map_location: DeviceLikeType | None, + extra_files: dict[str, Any], +) -> ScriptModule: ... +def import_ir_module_from_buffer( + cu: CompilationUnit, + buffer: IO[bytes], + map_location: DeviceLikeType | None, + extra_files: dict[str, Any], +) -> ScriptModule: ... +def _import_ir_module_from_package( + cu: CompilationUnit, + reader: PyTorchFileReader, + storage_context: DeserializationStorageContext, + map_location: DeviceLikeType | None, + ts_id: str, +) -> ScriptModule: ... +def _assign_output_shapes(graph: Graph, inputs: list[Tensor]) -> Graph: ... +def _check_onnx_proto(proto: str) -> None: ... +def _propagate_and_assign_input_shapes( + graph: Graph, + inputs: tuple[Tensor, ...], + param_count_list: list[_int], + with_grad: _bool, + propagate: _bool, +) -> Graph: ... + +# Defined in torch/csrc/jit/runtime/graph_executor.h +class GraphExecutorState: ... + +# Defined in torch/torch/csrc/jit/ir/alias_analysis.h +class AliasDb: ... + +class _InsertPoint: + def __enter__(self) -> None: ... + def __exit__(self, *exc_info: object) -> None: ... + +# Defined in torch/csrc/jit/ir/ir.h +class Use: + @property + def user(self) -> Node: ... + @property + def offset(self) -> _int: ... + def isAfter(self, other: Use) -> _bool: ... + +# Defined in torch/csrc/jit/ir/ir.h +class Value: + def type(self) -> JitType: ... + def setType(self, t: JitType) -> Value: ... + def setTypeAs(self, other: Value) -> Value: ... + def inferTypeFrom(self, t: Tensor) -> None: ... + def debugName(self) -> str: ... + def setDebugName(self, name: str) -> None: ... + def unique(self) -> _int: ... + def offset(self) -> _int: ... + def node(self) -> Node: ... + def uses(self) -> list[Use]: ... + def replaceAllUsesWith(self, val: Value) -> None: ... + def replaceAllUsesAfterNodeWith(self, node: Node, val: Value) -> None: ... + def requires_grad(self) -> _bool: ... + def requiresGrad(self) -> _bool: ... + def copyMetadata(self, other: Value) -> Value: ... + def isCompleteTensor(self) -> _bool: ... + def toIValue(self) -> IValue: ... + +# Defined in torch/csrc/jit/ir/ir.h +class Block: + def inputs(self) -> Iterator[Value]: ... + def outputs(self) -> Iterator[Value]: ... + def nodes(self) -> Iterator[Node]: ... + def paramNode(self) -> Node: ... + def returnNode(self) -> Node: ... + def owningNode(self) -> Node: ... + def registerOutput(self, n: Value) -> _int: ... + def addNode(self, name: str, inputs: Sequence[Value]) -> Node: ... + +# Defined in torch/csrc/jit/ir/ir.h +class Node: + def __getitem__(self, key: str) -> Any: ... + def schema(self) -> str: ... + def input(self) -> Value: ... + def inputs(self) -> Iterator[Value]: ... + def inputsAt(self, idx: _int) -> Value: ... + def inputsSize(self) -> _int: ... + def output(self) -> Value: ... + def outputs(self) -> Iterator[Value]: ... + def outputsAt(self, idx: _int) -> Value: ... + def outputsSize(self) -> _int: ... + def hasMultipleOutputs(self) -> _bool: ... + def blocks(self) -> list[Block]: ... + def addBlock(self) -> Block: ... + def mustBeNone(self) -> _bool: ... + def matches(self, pattern: str) -> _bool: ... + def kind(self) -> str: ... + def kindOf(self, name: str) -> str: ... + def addInput(self, name: str) -> Value: ... + def replaceInput(self, i: _int, newValue: Value) -> Value: ... + def replaceInputWith(self, from_: Value, to: Value) -> None: ... + def replaceAllUsesWith(self, n: Node) -> None: ... + def insertBefore(self, n: Node) -> Node: ... + def insertAfter(self, n: Node) -> Node: ... + def isBefore(self, n: Node) -> _bool: ... + def isAfter(self, n: Node) -> _bool: ... + def moveBefore(self, n: Node) -> None: ... + def moveAfter(self, n: Node) -> None: ... + def removeInput(self, i: _int) -> None: ... + def removeAllInputs(self, i: _int) -> None: ... + def hasUses(self) -> _bool: ... + def eraseOutput(self, i: _int) -> None: ... + def addOutput(self) -> Value: ... + def scopeName(self) -> str: ... + def isNondeterministic(self) -> _bool: ... + def copyAttributes(self, rhs: Node) -> Node: ... + def copyMetadata(self, rhs: Node) -> Node: ... + def hasAttributes(self) -> _bool: ... + def hasAttribute(self, name: str) -> _bool: ... + def removeAttribute(self, attr: str) -> Node: ... + def namedInput(self, name: str) -> Value: ... + def sourceRange(self) -> SourceRange: ... + def owningBlock(self) -> Block: ... + def findNode(self, kind: str, recurse: _bool = True) -> Node: ... + def findAllNodes(self, kind: str, recurse: _bool = True) -> list[Node]: ... + def getModuleHierarchy(self) -> str: ... + def prev(self) -> Node: ... + def destroy(self) -> None: ... + def attributeNames(self) -> list[str]: ... + + # Accessors for attributes as types. + def f(self, name: str) -> _float: ... + def f_(self, name: str, val: _float) -> Node: ... + def fs(self, name: str) -> list[_float]: ... + def fs_(self, name: str, val: list[_float]) -> Node: ... + def c(self, name: str) -> complex: ... + def c_(self, name: str, val: complex) -> Node: ... + def s(self, name: str) -> str: ... + def s_(self, name: str, val: str) -> Node: ... + def ss(self, name: str) -> list[str]: ... + def ss_(self, name: str, val: list[str]) -> Node: ... + def i(self, name: str) -> _int: ... + def i_(self, name: str, val: _int) -> Node: ... + # Cannot define "is" like this because it's a reserved keyword in python. + # def is(self, name: str) -> List[_int]: ... + # def is_(self, name: str, val: List[_int]) -> Node: ... + def g(self, name: str) -> Graph: ... + def g_(self, name: str, val: Graph) -> Node: ... + def gs(self, name: str) -> list[Graph]: ... + def gs_(self, name: str, val: list[Graph]) -> Node: ... + def ival(self, name: str) -> IValue: ... + def ival_(self, name: str, val: IValue) -> Node: ... + def t(self, name: str) -> Tensor: ... + def t_(self, name: str, val: Tensor) -> Node: ... + def ts(self, name: str) -> list[Tensor]: ... + def ts_(self, name: str, val: list[Tensor]) -> Node: ... + def ty(self, name: str) -> JitType: ... + def ty_(self, name: str, val: JitType) -> Node: ... + def tys(self, name: str) -> list[JitType]: ... + def tys_(self, name: str, val: list[JitType]) -> Node: ... + +# Defined in torch/torch/csrc/jit/ir/ir.h +class Graph: + def inputs(self) -> Iterator[Value]: ... + def outputs(self) -> Iterator[Value]: ... + def nodes(self) -> Iterator[Node]: ... + def param_node(self) -> Node: ... + def return_node(self) -> Node: ... + def addInput(self, name: str = "") -> Value: ... + def eraseInput(self, i: _int) -> None: ... + def registerOutput(self, n: Value) -> _int: ... + def eraseOutput(self, i: _int) -> None: ... + def create(self, name: str, args, num_outputs: _int) -> Node: ... + def appendNode(self, n: Node) -> Node: ... + def prependNode(self, n: Node) -> Node: ... + def insertNode(self, n: Node) -> Node: ... + def block(self) -> Block: ... + def lint(self) -> None: ... + def alias_db(self) -> AliasDb: ... + def setInsertPoint(self, n: Block | Node) -> None: ... + def insert_point_guard(self, n: Block | Node) -> _InsertPoint: ... + def insertPoint(self) -> Node: ... + def insertGraph(self, callee: Graph, inputs: list[Value]) -> list[Value]: ... + def makeMultiOutputIntoTuple(self) -> None: ... + def copy(self) -> Graph: ... + +# Defined in torch/aten/src/ATen/core/alias_info.h +class AliasInfo: + is_write: _bool + before_set: set[str] + after_set: set[str] + def __init__( + self, + is_write: _bool, + before_set: set[str], + after_set: set[str], + ) -> None: ... + +# Defined in torch/aten/src/ATen/core/function_schema.h +class Argument: + name: str + type: JitType + default_value: Any | None + def has_default_value(self) -> _bool: ... + kwarg_only: _bool + is_out: _bool + alias_info: AliasInfo | None + is_write: _bool + real_type: JitType + def __init__( + self, + name: str, + type: JitType, + N: _int | None, + default_value: Any | None, + kwarg_only: _bool, + alias_info: AliasInfo | None, + ) -> None: ... + +class FunctionSchema: + arguments: list[Argument] + returns: list[Argument] + name: str + overload_name: str + is_mutable: _bool + def __init__( + self, + name: str, + overload_name: str, + arguments: list[Argument], + returns: list[Argument], + is_vararg: _bool, + is_varret: _bool, + ) -> None: ... + def _is_view_op(self) -> _bool: ... + +class _UpgraderEntry: + bumped_at_version: _int + upgrader_name: str + old_schema: str + def __init__( + self, + bumped_at_version: _int, + upgrader_name: str, + old_schema: str, + ) -> None: ... + +class _UpgraderRange: + min_version: _int + max_version: _int + +def _get_max_operator_version() -> _int: ... +def _get_operator_version_map() -> dict[str, list[_UpgraderEntry]]: ... +def _get_upgrader_ranges(name: str) -> list[_UpgraderRange]: ... +def _test_only_add_entry_to_op_version(op_name: str, entry: _UpgraderEntry) -> None: ... +def _test_only_remove_entry_to_op_version(op_name: str) -> None: ... + +# Defined in torch/csrc/jit/python/script_init.cpp +class ScriptModuleSerializer: + def __init__(self, export_writer: PyTorchFileWriter) -> None: ... + def serialize(self, model: ScriptModule, script_module_id: _int) -> None: ... + def write_files(self) -> None: ... + def storage_context(self) -> SerializationStorageContext: ... + +# Defined in torch/csrc/jit/python/script_init.cpp +class SerializationStorageContext: + def __init__(self) -> None: ... + def has_storage(self, storage: Storage) -> _bool: ... + def get_or_add_storage(self, storage: Storage) -> _int: ... + +# Defined in torch/csrc/jit/python/script_init.cpp +class DeserializationStorageContext: + def __init__(self) -> None: ... + def get_storage(self, name: str, dtype: _dtype) -> Tensor: ... + def has_storage(self, name: str) -> _bool: ... + def add_storage(self, name: str, tensor: Tensor) -> _int: ... + +# Defined in torch/csrc/jit/python/script_init.cpp +class ConcreteModuleTypeBuilder: + def __init__(self, obj: Any) -> None: ... + def set_module_dict(self) -> None: ... + def set_module_list(self) -> None: ... + def set_parameter_list(self) -> None: ... + def set_parameter_dict(self) -> None: ... + def add_attribute( + self, + name: str, + ty: JitType, + is_param: _bool, + is_buffer: _bool, + ) -> None: ... + def add_module(self, name: str, meta: ConcreteModuleType) -> None: ... + def add_constant(self, name: str, value: Any) -> None: ... + def add_overload( + self, method_name: str, overloaded_method_names: list[str] + ) -> None: ... + def add_builtin_function(self, name: str, symbol_name: str) -> None: ... + def add_failed_attribute(self, name: str, failure_reason: str) -> None: ... + def add_function_attribute( + self, + name: str, + ty: JitType, + func: Callable[..., Any], + ) -> None: ... + def add_ignored_attribute(self, name: str) -> None: ... + def add_ignored_attributes(self, names: list[str]) -> None: ... + def add_forward_hook(self, hook: Callable[..., Any]) -> None: ... + def add_forward_pre_hook(self, pre_hook: Callable[..., Any]) -> None: ... + +class ConcreteModuleType: + def get_constants(self) -> dict[str, Any]: ... + def equals(self, other: ConcreteModuleType) -> _bool: ... + @staticmethod + def from_jit_type(ty: JitType) -> ConcreteModuleType: ... + +class CallStack: + def __init__(self, name: str, range: SourceRange) -> None: ... + +class ErrorReport: + def __init__(self, range: SourceRange) -> None: ... + def what(self) -> str: ... + @staticmethod + def call_stack() -> str: ... + +class CompilationUnit: + def __init__(self, lang: str = ..., _frames_up: _int = ...) -> None: ... + def find_function(self, name: str) -> ScriptFunction: ... + def __getattr__(self, name: str) -> ScriptFunction: ... + def define( + self, + script: str, + rcb: ResolutionCallback = ..., + _frames_up: _int = ..., + ) -> list[ScriptFunction]: ... + def get_interface(self, name: str) -> InterfaceType: ... + def get_functions(self) -> None: ... + def create_function( + self, + name: str, + graph: Graph, + shouldMangle: _bool = ..., + ) -> ScriptFunction: ... + def get_class(self, name: str) -> ClassType: ... + +class ScriptObject: + def setattr(self, name: str, value: Any) -> None: ... + def _get_method(self, name: str) -> ScriptMethod: ... + def _type(self) -> ClassType: ... + +class ScriptModule(ScriptObject): + def _method_names(self) -> list[str]: ... + def _get_method(self, name: str) -> ScriptMethod: ... + +class LiteScriptModule: + def __call__(self, *input: Any) -> Any: ... + def find_method(self, method_name: str) -> bool: ... + def forward(self, *input: Any) -> list[str]: ... + def run_method(self, method_name: str, *input: Any) -> Any: ... + +# NOTE: switch to collections.abc.Callable in python 3.9 +class ScriptFunction(Generic[P, R]): + def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R: ... + def save(self, filename: str, _extra_files: dict[str, bytes]) -> None: ... + def save_to_buffer(self, _extra_files: dict[str, bytes]) -> bytes: ... + @property + def graph(self) -> Graph: ... + def inlined_graph(self) -> Graph: ... + def schema(self) -> FunctionSchema: ... + def code(self) -> str: ... + def name(self) -> str: ... + @property + def qualified_name(self) -> str: ... + +# NOTE: switch to collections.abc.Callable in python 3.9 +class ScriptMethod(Generic[P, R]): + graph: Graph + def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R: ... + @property + def owner(self) -> ScriptModule: ... + @property + def name(self) -> str: ... + @property + def schema(self) -> FunctionSchema: ... + +class ScriptDict(Generic[K, T]): + def __init__(self, dict: dict[K, T]) -> None: ... + def __len__(self) -> _int: ... + def __contains__(self, key: K) -> _bool: ... + def __getitem__(self, key: K) -> T: ... + def __setitem__(self, key: K, value: T) -> None: ... + def __delitem__(self, key: K) -> None: ... + def __iter__(self) -> Iterator[K]: ... + def items(self) -> Iterator[tuple[K, T]]: ... + def keys(self) -> Iterator[K]: ... + +class ScriptList(Generic[T]): + def __init__(self, list: list[T]) -> None: ... + def __len__(self) -> _int: ... + def __contains__(self, item: T) -> _bool: ... + @overload + def __getitem__(self, idx: _int) -> T: ... + @overload + def __getitem__(self, idx: slice) -> ScriptList[T]: ... + @overload + def __setitem__(self, idx: _int, value: T) -> None: ... + @overload + def __setitem__(self, idx: slice, value: list[T]) -> None: ... + def __delitem__(self, idx: _int) -> None: ... + def __iter__(self) -> Iterator[T]: ... + def count(self, value: T) -> _int: ... + def remove(self, value: T) -> None: ... + def append(self, value: T) -> None: ... + def clear(self) -> None: ... + @overload + def extend(self, values: list[T]) -> None: ... + @overload + def extend(self, values: Iterable[T]) -> None: ... + @overload + def pop(self) -> T: ... + @overload + def pop(self, idx: _int) -> T: ... + +class ModuleDict: + def __init__(self, mod: ScriptModule) -> None: ... + def items(self) -> list[tuple[str, Any]]: ... + +class ParameterDict: + def __init__(self, mod: ScriptModule) -> None: ... + +class BufferDict: + def __init__(self, mod: ScriptModule) -> None: ... + +# Defined in torch/csrc/jit/api/module.h +class Module: ... + +# Defined in torch/csrc/Module.cpp +def _initExtension(shm_manager_path: str) -> None: ... # THPModule_initExtension +def _autograd_init() -> _bool: ... # THPAutograd_initExtension +def _add_docstr(obj: T, doc_obj: str) -> T: ... # THPModule_addDocStr +def _init_names(arg: Sequence[type]) -> None: ... # THPModule_initNames +def _has_distributed() -> _bool: ... # THPModule_hasDistributed +def _set_default_tensor_type(type) -> None: ... # THPModule_setDefaultTensorType +def _set_default_dtype(d: _dtype) -> None: ... # THPModule_setDefaultDtype +def _infer_size(arg1: Size, arg2: Size) -> Size: ... # THPModule_inferSize +def _crash_if_csrc_asan() -> _int: ... # THPModule_crashIfCsrcASAN +def _crash_if_csrc_ubsan() -> _int: ... # THPModule_crashIfCsrcUBSAN +def _crash_if_aten_asan() -> _int: ... # THPModule_crashIfATenASAN +def _show_config() -> str: ... # THPModule_showConfig +def _cxx_flags() -> str: ... # THPModule_cxxFlags +def _parallel_info() -> str: ... # THPModule_parallelInfo +def _get_cpu_capability() -> str: ... # THPModule_getCpuCapability +def _set_backcompat_broadcast_warn( + arg: _bool, +) -> None: ... # THPModule_setBackcompatBroadcastWarn +def _get_backcompat_broadcast_warn() -> ( + _bool +): ... # THPModule_getBackcompatBroadcastWarn +def _set_backcompat_keepdim_warn( + arg: _bool, +) -> None: ... # THPModule_setBackcompatKeepdimWarn +def _get_backcompat_keepdim_warn() -> _bool: ... # THPModule_getBackcompatKeepdimWarn +def get_num_threads() -> _int: ... # THPModule_getNumThreads +def set_num_threads(nthreads: _int) -> None: ... # THPModule_setNumThreads +def get_num_interop_threads() -> _int: ... # THPModule_getNumInteropThreads +def set_num_interop_threads( + nthreads: _int, +) -> None: ... # THPModule_setNumInteropThreads +def _get_cudnn_enabled() -> _bool: ... # THPModule_userEnabledCuDNN +def _set_cudnn_enabled(arg: _bool) -> None: ... # THPModule_setUserEnabledCuDNN +def _get_flash_sdp_enabled() -> _bool: ... # THPModule_userEnabledFusedSDP +def _set_sdp_use_flash(arg: _bool) -> None: ... # THPModule_setSDPUseFlash +def _get_fa3_sdp_enabled() -> _bool: ... # THPModule_userEnabledFA3SDP +def _set_sdp_use_fa3(arg: _bool) -> None: ... # THPModule_setSDPUseFA3 +def _get_mem_efficient_sdp_enabled() -> _bool: ... # THPModule_userEnabledMathSDP +def _set_sdp_use_mem_efficient( + arg: _bool, +) -> None: ... # THPModule_setSDPUseMemEfficient +def _get_math_sdp_enabled() -> _bool: ... # THPModule_userEnabledMathSDP +def _set_sdp_use_math(arg: _bool) -> None: ... # THPModule_setSDPUseMath +def _get_math_sdp_allow_fp16_bf16_reduction() -> ( + _bool +): ... # THPModule_allowFP16BF16ReductionMathSDP +def _set_math_sdp_allow_fp16_bf16_reduction( + arg: _bool, +) -> None: ... # THPModule_setAllowFP16BF16ReductionMathSDP +def _get_overrideable_sdp_enabled() -> ( + _bool +): ... # THPModule_userEnabledOverrideableSDP +def _set_sdp_use_overrideable( + arg: _bool, +) -> None: ... # THPModule_setSDPUseOverrideable +def _get_sdp_priority_order() -> list[_int]: ... # THPModule_getSDPPriorityOrder +def _set_sdp_priority_order( + arg: list[_int], +) -> None: ... # THPModule_setSDPPriorityOrder +def _get_cudnn_sdp_enabled() -> _bool: ... # THPModule_userEnabledMathSDP +def _set_sdp_use_cudnn(arg: _bool) -> None: ... # THPModule_setSDPUseMath +def _get_mkldnn_enabled() -> _bool: ... # THPModule_userEnabledMkldnn +def _set_mkldnn_enabled(arg: _bool) -> None: ... # THPModule_setUserEnabledMkldnn +def _get_cudnn_benchmark() -> _bool: ... # THPModule_benchmarkCuDNN +def _set_cudnn_benchmark(arg: _bool) -> None: ... # THPModule_setBenchmarkCuDNN +def _get_cudnn_depthwise_kernel() -> str: ... # THPModule_getCuDNNDepthwiseKernel +def _set_cudnn_depthwise_kernel( + arg: str, +) -> None: ... # THPModule_setCuDNNDepthwiseKernel +def _get_miopen_immediate() -> _bool: ... # THPModule_userImmediateMiopen +def _set_miopen_immediate(arg: _bool) -> None: ... # THPModule_setUserImmediateMiopen +def _get_cudnn_deterministic() -> _bool: ... # THPModule_deterministicCuDNN +def _set_cudnn_deterministic(arg: _bool) -> None: ... # THPModule_setDeterministicCuDNN +def _get_mkldnn_deterministic() -> _bool: ... # THPModule_deterministicMkldnn +def _set_mkldnn_deterministic( + arg: _bool, +) -> None: ... # THPModule_setDeterministicMkldnn +def _get_onednn_allow_tf32() -> _bool: ... # THPModule_allowTF32OneDNN +def _set_onednn_allow_tf32(arg: _bool) -> None: ... # THPModule_setAllowTF32OneDNN +def _get_deterministic_algorithms() -> _bool: ... # THPModule_deterministicAlgorithms +def _get_deterministic_algorithms_warn_only() -> ( + _bool +): ... # THPModule_deterministicAlgorithmsWarnOnly +def _set_deterministic_algorithms( + mode: _bool, + *, + warn_only: _bool = ..., +) -> None: ... # THPModule_setDeterministicAlgorithms +def _get_deterministic_fill_uninitialized_memory() -> ( + _bool +): ... # THPModule_deterministicFillUninitializedMemory +def _set_deterministic_fill_uninitialized_memory( + arg: _bool, +) -> None: ... # THPModule_setDeterministicFillUninitializedMemory +def _get_nnpack_enabled() -> _bool: ... # THPModule_userEnabledNNPACK +def _set_nnpack_enabled(arg: _bool) -> None: ... # THPModule_setUserEnabledNNPACK +def _get_warnAlways() -> _bool: ... # THPModule_warnAlways +def _set_warnAlways(arg: _bool) -> None: ... # THPModule_setWarnAlways +def _get_cudnn_allow_tf32() -> _bool: ... # THPModule_allowTF32CuDNN +def _set_cudnn_allow_tf32(arg: _bool) -> None: ... # THPModule_setAllowTF32CuDNN +def _get_cublas_allow_tf32() -> _bool: ... # THPModule_allowTF32CuBLAS +def _set_cublas_allow_tf32(arg: _bool) -> None: ... # THPModule_setAllowTF32CuBLAS +def _get_cublaslt_prefer_grouped_gemm() -> _bool: ... # THPModule_preferCublasltGroupedGemm +def _set_cublaslt_prefer_grouped_gemm( + arg: _bool, +) -> None: ... # THPModule_setPreferCublasltGroupedGemm +def _get_float32_matmul_precision() -> str: ... # THPModule_float32MatmulPrecision +def _set_float32_matmul_precision( + arg: str, +) -> None: ... # THPModule_setFloat32MatmulPrecision +def _get_cublas_allow_fp16_reduced_precision_reduction() -> tuple[ + _bool, _bool +]: ... # THPModule_allowFP16ReductionCuBLAS +def _set_cublas_allow_fp16_reduced_precision_reduction( + arg: _bool, + allow_splitk: _bool = ..., +) -> None: ... # THPModule_setAllowFP16ReductionCuBLAS +def _get_cublas_allow_bf16_reduced_precision_reduction() -> tuple[ + _bool, _bool +]: ... # THPModule_allowBF16ReductionCuBLAS +def _set_cublas_allow_bf16_reduced_precision_reduction( + arg: _bool, + allow_splitk: _bool = ..., +) -> None: ... # THPModule_setAllowBF16ReductionCuBLAS +def _get_cublas_allow_fp16_accumulation() -> ( + _bool +): ... # THPModule_allowFP16AccumulationCuBLAS +def _set_cublas_allow_fp16_accumulation( + arg: _bool, +) -> None: ... # THPModule_setAllowFP16AccumulationCuBLAS +def _get_sm_carveout_experimental() -> _int | None: ... +def _set_sm_carveout_experimental(arg: _int | None) -> None: ... +def _set_conj(x: Tensor, conj: _bool) -> None: ... +def _set_neg(x: Tensor, neg: _bool) -> None: ... +def _set_meta_in_tls_dispatch_include(meta_in_tls: _bool) -> None: ... +def _autocast_supported_devices() -> list[str]: ... +def _meta_in_tls_dispatch_include() -> _bool: ... +def _stash_obj_in_tls(key: str, arg: Any) -> None: ... +def _get_obj_in_tls(key: str) -> Any: ... +def _is_key_in_tls(key: str) -> _bool: ... +def _remove_obj_from_tls(key: str) -> None: ... +def _select_batch_norm_backend(*args, **kwargs) -> BatchNormBackend: ... +def _select_conv_backend(*args, **kwargs) -> ConvBackend: ... +def _conv_determine_backend_memory_format( + input: Tensor, + weight: Tensor, + backend: ConvBackend, +) -> memory_format: ... +def _has_storage(x: Tensor) -> _bool: ... +def _construct_storage_from_data_pointer( + data_ptr: _int, + device: torch.device, + size: _int, +) -> Storage: ... +def _should_allow_numbers_as_tensors(func_name: str) -> _bool: ... +def _group_tensors_by_device_and_dtype( + nested_tensorlists: list[list[Tensor | None]], + with_indices: _bool = False, +) -> dict[ + tuple[torch.device, torch.dtype], + tuple[list[list[Tensor | None]], list[_int]], +]: ... +def _initCrashHandler() -> None: ... +def _set_warn_on_accumulate_grad_stream_mismatch(enabled: _bool) -> None: ... +def _set_override_stale_capture_stream(enabled: _bool) -> None: ... +def _override_stale_capture_stream() -> _bool: ... + +# NB: There is no Capsule type in typing, see +# https://github.com/python/cpython/issues/109562 +def _to_dlpack( + data: Tensor, + dl_device: tuple[IntEnum, _int] | None = None, + copy: _bool | None = None, + read_only: _bool = False, +) -> Any: ... # THPModule_toDLPack +def _to_dlpack_versioned( + data: Tensor, + dl_device: tuple[IntEnum, _int] | None = None, + copy: _bool | None = None, + read_only: _bool = False, +) -> Any: ... # THPModule_toDLPackVersioned +def _from_dlpack(data: Any) -> Tensor: ... # THPModule_fromDLPack +def _torchDeviceToDLDevice( + device: torch.device, +) -> tuple[_int, _int]: ... # THPModule_torchDeviceToDLDevice +def _dlpack_exchange_api() -> object: ... # THPModule_DLPackExchangeAPI +def _const_dlpack_exchange_api() -> object: ... # THPModule_ConstDLPackExchangeAPI +def _get_cpp_backtrace( + frames_to_skip: _int, + maximum_number_of_frames: _int, +) -> str: ... # THPModule_getCppBacktrace +def set_flush_denormal(arg: _bool) -> _bool: ... # THPModule_setFlushDenormal +def get_default_dtype() -> _dtype: ... # THPModule_getDefaultDtype +def _get_all_dtypes() -> list[_dtype]: ... # THPModule_getAllDtypes +def _get_default_device() -> str: ... # THPModule_getDefaultDevice +def _get_qengine() -> _int: ... # THPModule_qEngine +def _set_qengine(qengine: _int) -> None: ... # THPModule_setQEngine +def _supported_qengines() -> list[_int]: ... # THPModule_supportedQEngines +def _is_xnnpack_enabled() -> _bool: ... # THPModule_isEnabledXNNPACK +def _check_sparse_tensor_invariants() -> ( + _bool +): ... # THPModule_checkSparseTensorInvariants +def _set_check_sparse_tensor_invariants( + arg: _bool, +) -> None: ... # THPModule_setCheckSparseTensorInvariants +def _is_default_mobile_cpu_allocator_set() -> ( + _bool +): ... # THPModule_isDefaultMobileCPUAllocatorSet +def _set_default_mobile_cpu_allocator() -> ( + None +): ... # THPModule_setDefaultMobileCPUAllocator +def _unset_default_mobile_cpu_allocator() -> ( + None +): ... # THPModule_unsetDefaultMobileCPUAllocator +def _is_torch_function_enabled() -> _bool: ... # THPModule_isEnabledTorchFunction +def _is_torch_function_all_disabled() -> ( + _bool +): ... # THPModule_isAllDisabledTorchFunction +def _peek_should_skip_torch_function() -> _bool: ... # THPModule_peek_should_skip_torch_function +def _has_torch_function( + args: Iterable[Any], +) -> _bool: ... # THPModule_has_torch_function +def _has_torch_function_unary(Any) -> _bool: ... # THPModule_has_torch_function_unary +def _has_torch_function_variadic( + *args: Any, +) -> _bool: ... # THPModule_has_torch_function_variadic +def _vmapmode_increment_nesting() -> _int: ... # THPModule_vmapmode_increment_nesting +def _vmapmode_decrement_nesting() -> _int: ... # THPModule_vmapmode_decrement_nesting +def _log_api_usage_once(str) -> None: ... # LogAPIUsageOnceFromPython +def _log_api_usage_metadata( + event: str, + metadata_map: dict[str, str], +) -> None: ... # LogAPIUsageMetadataFromPython +def _demangle(str) -> str: ... # c10::demangle +def _getenv(name: str) -> str | None: ... # c10::utils::get_env +def _setenv(name: str, value: str, overwrite: _bool = True) -> None: ... # c10::utils::set_env +def _unsetenv(name: str) -> None: ... # c10::utils::unset_env +def _fake_dispatch_register_decomp(name: str, overload: str) -> None: ... +def _fake_dispatch_register_meta(name: str, overload: str) -> None: ... +def _fake_dispatch_register_op_impl(name: str, overload: str) -> None: ... +def _fake_dispatch_register_prim_meta(name: str, overload: str) -> None: ... +def _fake_dispatch_deregister_op_impl(name: str, overload: str) -> None: ... +def _disabled_torch_function_impl( + func: Callable, + types: Iterable[type], + args: tuple, + kwargs: dict, +) -> Any: ... # THPModule_disable_torch_function +def _disabled_torch_dispatch_impl( + func: Callable, + types: Iterable[type], + args: tuple, + kwargs: dict, +) -> Any: ... # THPModule_disable_dispatch_function +def _skip_one_hop_torch_function( + func: Callable, types: Iterable[type], args: tuple, kwargs: dict +) -> Any: ... # THPModule_skip_one_hop_torch_function +def _get_linalg_preferred_backend() -> _LinalgBackend: ... +def _set_linalg_preferred_backend(arg: _LinalgBackend): ... +def _get_fp32_precision_getter(backend: str, op: str) -> str: ... +def _set_fp32_precision_setter(backend: str, op: str, value: str) -> str: ... +def _ensureCUDADeviceGuardSet() -> None: ... + +class _LinalgBackend: + Default: _LinalgBackend + Cusolver: _LinalgBackend + Magma: _LinalgBackend + +# mypy error: +# Detected enum "torch._C.BatchNormBackend" in a type stub with zero +# members. There is a chance this is due to a recent change in the semantics +# of enum membership. If so, use `member = value` to mark an enum member, +# instead of `member: type` +class BatchNormBackend(Enum): ... # type: ignore[misc] + +def _get_blas_preferred_backend() -> _BlasBackend: ... +def _set_blas_preferred_backend(arg: _BlasBackend): ... +def _get_blas_default_backend() -> _BlasBackend: ... + +class _BlasBackend: + Default: _BlasBackend + Cublas: _BlasBackend + Cublaslt: _BlasBackend + Ck: _BlasBackend + +def _get_rocm_fa_preferred_backend() -> torch._C._ROCmFABackend: ... +def _set_rocm_fa_preferred_backend(arg: torch._C._ROCmFABackend): ... + +class _ROCmFABackend: + Default: _ROCmFABackend + AOTriton: _ROCmFABackend + Ck: _ROCmFABackend + +# mypy error: +# Error (MYPY) [misc] +# Detected enum "torch._C.ConvBackend" in a type stub with zero members. +# There is a chance this is due to a recent change in the semantics of enum +# membership. If so, use `member = value` to mark an enum member, instead of +# `member: type` +class ConvBackend(Enum): ... # type: ignore[misc] + +class Tag(Enum): + core = 0 + cudagraph_unsafe = 1 + data_dependent_output = 2 + dynamic_output_shape = 3 + flexible_layout = 4 + generated = 5 + inplace = 6 + inplace_view = 7 + maybe_aliasing_or_mutating = 8 + needs_contiguous_strides = 9 + needs_exact_strides = 10 + needs_fixed_stride_order = 11 + nondeterministic_bitwise = 12 + nondeterministic_seeded = 13 + out = 14 + out_variant = 15 + pointwise = 16 + pt2_compliant_tag = 17 + reduction = 18 + view_copy = 19 + +# Defined in `valgrind.h` and `callgrind.h` respectively. +def _valgrind_supported_platform() -> _bool: ... # NVALGRIND +def _valgrind_toggle() -> None: ... # CALLGRIND_TOGGLE_COLLECT +def _valgrind_toggle_and_dump_stats() -> ( + None +): ... # CALLGRIND_TOGGLE_COLLECT and CALLGRIND_DUMP_STATS + +has_openmp: _bool +has_mkl: _bool +_has_kleidiai: _bool +_has_mps: _bool +has_lapack: _bool +_has_cuda: _bool +_has_magma: _bool +_has_xpu: _bool +_has_mkldnn: _bool +_has_mkldnn_acl: _bool +_has_cudnn: _bool +_has_cusparselt: _bool +_has_gds: _bool +has_spectral: _bool +_GLIBCXX_USE_CXX11_ABI: _bool +default_generator: Generator + +# Defined in torch/csrc/autograd/init.cpp +def _set_grad_enabled(enabled: _bool) -> None: ... +def is_grad_enabled() -> _bool: ... +def _set_fwd_grad_enabled(enabled: _bool) -> None: ... +def _is_fwd_grad_enabled() -> _bool: ... +def _any_requires_grad(*args, **kwargs) -> _bool: ... +def _any_output_is_alias_to_input_or_output(*args, **kwargs) -> _bool: ... +def is_inference_mode_enabled() -> _bool: ... +@overload +def set_autocast_enabled(device_type: str, enabled: _bool) -> None: ... +@overload +def set_autocast_enabled(enabled: _bool) -> None: ... +@overload +def is_autocast_enabled(device_type: str) -> _bool: ... +@overload +def is_autocast_enabled() -> _bool: ... +def set_autocast_dtype(device_type: str, dtype: _dtype) -> None: ... +def get_autocast_dtype(device_type: str) -> _dtype: ... +def clear_autocast_cache() -> None: ... +def set_autocast_cpu_enabled(enabled: _bool) -> None: ... +def is_autocast_cpu_enabled() -> _bool: ... +def _is_any_autocast_enabled() -> _bool: ... +def _is_autocast_available(device_type: str) -> _bool: ... +def set_autocast_cpu_dtype(dtype: _dtype) -> None: ... +def set_autocast_gpu_dtype(dtype: _dtype) -> None: ... +def get_autocast_cpu_dtype() -> _dtype: ... +def get_autocast_gpu_dtype() -> _dtype: ... +def autocast_increment_nesting() -> _int: ... +def autocast_decrement_nesting() -> _int: ... +def is_autocast_cache_enabled() -> _bool: ... +def set_autocast_cache_enabled(enabled: _bool) -> None: ... +def _increment_version(tensors: Iterable[Tensor]) -> None: ... +def set_anomaly_enabled(enabled: _bool, check_nan: _bool = True) -> None: ... +def is_anomaly_enabled() -> _bool: ... +def is_anomaly_check_nan_enabled() -> _bool: ... +def _is_multithreading_enabled() -> _bool: ... +def _set_multithreading_enabled(enabled: _bool) -> None: ... +def _set_view_replay_enabled(enabled: _bool) -> None: ... +def _is_view_replay_enabled() -> _bool: ... +def _is_grad_layout_enforcement_enabled() -> _bool: ... +def _set_grad_layout_enforcement_enabled(enabled: _bool) -> None: ... +def _set_graph_exec_group(group: GraphExecGroup | None) -> None: ... +def _get_graph_exec_group() -> GraphExecGroup | None: ... +def _enter_dual_level() -> _int: ... +def _exit_dual_level(level: _int) -> None: ... +def _make_dual(tensor: Tensor, tangent: Tensor, level: _int) -> Tensor: ... +def _unpack_dual(tensor: Tensor, level: _int) -> Tensor: ... +def __set_forward_AD_enabled(enabled: _bool) -> None: ... +def __is_forward_AD_enabled() -> _bool: ... +def _register_default_hooks(pack_hook: Callable, unpack_hook: Callable) -> None: ... +def _reset_default_hooks() -> None: ... +def _is_torch_function_mode_enabled() -> _bool: ... +def _push_on_torch_function_stack(cls: Any) -> None: ... +def _pop_torch_function_stack() -> Any: ... +def _get_function_stack_at(idx: _int) -> Any: ... +def _len_torch_function_stack() -> _int: ... +def _set_torch_dispatch_mode(cls: Any) -> None: ... +def _push_on_torch_dispatch_stack(cls: TorchDispatchMode) -> None: ... +def _pop_torch_dispatch_stack(mode_key: _TorchDispatchModeKey | None = None) -> Any: ... +def _get_dispatch_mode(mode_key: _TorchDispatchModeKey | None) -> Any: ... +def _unset_dispatch_mode(mode: _TorchDispatchModeKey) -> TorchDispatchMode | None: ... +def _set_dispatch_mode(mode: TorchDispatchMode) -> None: ... +def _get_dispatch_stack_at(idx: _int) -> Any: ... +def _len_torch_dispatch_stack() -> _int: ... +def _activate_gpu_trace() -> None: ... + +class _DisableTorchDispatch: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _EnableTorchFunction: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _EnablePythonDispatcher: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _DisablePythonDispatcher: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _EnablePreDispatch: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _DisableFuncTorch: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _DisableAutocast: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _InferenceMode: + def __init__(self, enabled: _bool) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +def _set_autograd_fallback_mode(mode: str) -> None: ... +def _get_autograd_fallback_mode() -> str: ... + +# Defined in torch/csrc/jit/python/script_init.cpp +class LoggerBase: ... +class NoopLogger(LoggerBase): ... +class LockingLogger(LoggerBase): ... + +class AggregationType(Enum): + SUM = 0 + AVG = 1 + +class FileCheck: + def run(self, test_string: str) -> None: ... + def check(self, test_string: str) -> FileCheck: ... + def check_not(self, test_string: str) -> FileCheck: ... + def check_same(self, test_string: str) -> FileCheck: ... + def check_next(self, test_string: str) -> FileCheck: ... + def check_count( + self, + test_string: str, + count: _int, + exactly: _bool = False, + ) -> FileCheck: ... + def check_dag(self, test_string: str) -> FileCheck: ... + def check_source_highlighted(self, test_string: str) -> FileCheck: ... + def check_regex(self, test_string: str) -> FileCheck: ... + +# Defined in torch/csrc/jit/python/init.cpp +class PyTorchFileReader: + @overload + def __init__(self, name: str) -> None: ... + @overload + def __init__(self, buffer: IO[bytes]) -> None: ... + def get_record(self, name: str) -> bytes: ... + def get_all_records(self) -> list[str]: ... + def get_record_size(self, name: str) -> _int: ... + def get_storage_from_record(self, name: str, numel: _int, dtype: dtype) -> Tensor: ... + def serialization_id(self) -> str: ... + +class PyTorchFileWriter: + @overload + def __init__( + self, + name: str, + compute_crc32: _bool = True, + storage_alignment: _int = 64, + ) -> None: ... + @overload + def __init__( + self, + buffer: IO[bytes], + compute_crc32: _bool = True, + storage_alignment: _int = 64, + ) -> None: ... + def write_record( + self, + name: str, + data: Storage | bytes | _int, + size: _int, + ) -> None: ... + def write_end_of_file(self) -> None: ... + def set_min_version(self, version: _int) -> None: ... + def get_all_written_records(self) -> list[str]: ... + def archive_name(self) -> str: ... + def serialization_id(self) -> str: ... + +def _jit_get_inline_everything_mode() -> _bool: ... +def _jit_set_inline_everything_mode(enabled: _bool) -> None: ... +def _jit_get_logging_option() -> str: ... +def _jit_set_logging_option(option: str) -> None: ... +def _jit_set_logging_stream(stream_name: str) -> None: ... +def _jit_pass_cse(Graph) -> _bool: ... +def _jit_pass_dce(Graph) -> None: ... +def _jit_pass_dce_graph(Graph) -> None: ... +def _jit_pass_lint(Graph) -> None: ... +def _register_opaque_type(type_name: str) -> None: ... +def _is_opaque_type_registered(type_name: str) -> _bool: ... + +# Defined in torch/csrc/jit/python/python_custom_class.cpp +def _get_custom_class_python_wrapper(name: str, attr: str) -> Any: ... + +# Defined in torch/csrc/Module.cpp +def _rename_privateuse1_backend(backend: str) -> None: ... +def _get_privateuse1_backend_name() -> str: ... + +# Defined in torch/csrc/Generator.cpp +def _set_generator_metaclass(metaclass: type) -> None: ... + +class Generator: + device: _device + def __init__(self, device: DeviceLikeType | None = None) -> None: ... + def __reduce__( + self, + ) -> tuple[type[Generator], tuple[_device], tuple[_int, _int | None, Tensor]]: ... + def __setstate__(self, state: tuple[_int, _int | None, Tensor]) -> None: ... + def get_state(self) -> Tensor: ... + def set_state(self, _new_state: Tensor) -> Generator: ... + def clone_state(self) -> Generator: ... + def graphsafe_get_state(self) -> Generator: ... + def graphsafe_set_state(self, _new_state: Generator) -> Generator: ... + def set_offset(self, offset: _int) -> Generator: ... + def get_offset(self) -> _int: ... + def philox_state(self, increment: _int) -> tuple[Tensor, Tensor, Tensor]: ... + def manual_seed(self, seed: _int) -> Generator: ... + def seed(self) -> _int: ... + def initial_seed(self) -> _int: ... + +# Defined in torch/csrc/utils/python_dispatch.cpp + +class _DispatchOperatorHandle: + def schema(self) -> FunctionSchema: ... + def debug(self) -> str: ... + def redispatch_boxed(self, keyset: DispatchKeySet, *args, **kwargs) -> Any: ... + +class _DispatchModule: + def reset(self) -> None: ... + def def_(self, schema: str, alias: str = "") -> _DispatchModule: ... + def def_legacy(self, schema: str) -> _DispatchModule: ... + def def_name_t_t( + self, + name: str, + dispatch: str, + debug: str = "default_def_name_t_t", + ) -> _DispatchModule: ... + def def_schema_t_t( + self, + schema: str, + dispatch: str, + alias: str, + debug: str = "default_def_schema_t_t", + ) -> _DispatchModule: ... + def impl_t_t( + self, + name: str, + dispatch: str, + debug: str = "impl_t_t", + ) -> _DispatchModule: ... + def impl_with_aoti_compile( + self, + ns: str, + op_name_with_overload: str, + dispatch: _dispatchkey, + ) -> None: ... + def impl(self, name: str, dispatch: _dispatchkey, func: Callable) -> None: ... + def define(self, schema: str, alias: str = "") -> str: ... + def fallback_fallthrough(self, dispatch: str = "") -> _DispatchModule: ... + def fallback( + self, + dispatch: _dispatchkey, + func: Callable, + with_keyset: _bool = False, + ) -> None: ... + +_after_ADInplaceOrView_keyset: DispatchKeySet +_after_autograd_keyset: DispatchKeySet + +class _SafeKernelFunction: + def call_boxed(self, keyset: DispatchKeySet, *args, **kwargs) -> Any: ... + @property + def op_handle(self) -> _DispatchOperatorHandle: ... + +def _dispatch_library( + kind: str, + name: str, + dispatch: str, + file: str = "", + linenum: Any = 0, +) -> _DispatchModule: ... +def _dispatch_dump(name: str) -> str: ... +def _dispatch_dump_table(name: str) -> str: ... +def _dispatch_check_invariants(name: str) -> None: ... +def _dispatch_check_all_invariants() -> None: ... +def _dispatch_call_boxed(handle: _DispatchOperatorHandle, *args, **kwargs) -> Any: ... +def _dispatch_make_pyobj_dispatch_fns( + handle: _DispatchOperatorHandle, + dispatch_cpp: Callable, + redispatch_cpp: Callable, +) -> tuple[Callable, Callable]: ... +def _dispatch_find_schema_or_throw( + name: str, + overload_name: str, +) -> _DispatchOperatorHandle: ... +def _dispatch_set_report_error_callback( + handle: _DispatchOperatorHandle, + callback: Callable, +) -> None: ... +def _dispatch_has_kernel(name: str) -> _bool: ... +def _dispatch_has_kernel_for_dispatch_key( + name: str, + dispatch: _dispatchkey, +) -> _bool: ... +def _dispatch_has_kernel_for_any_dispatch_key( + name: str, + dispatch_key_set: DispatchKeySet, +) -> _bool: ... +def _dispatch_kernel_for_dispatch_key_is_fallthrough( + name: str, + dispatch: _dispatchkey, +) -> _bool: ... +def _dispatch_has_computed_kernel_for_dispatch_key( + name: str, + dispatch: _dispatchkey, +) -> _bool: ... +def _dispatch_get_computed_kernel_for_dispatch_key( + name: str, + dispatch: _dispatchkey, +) -> _SafeKernelFunction: ... +def _dispatch_find_dangling_impls() -> list[str]: ... +def _dispatch_get_all_op_names() -> list[str]: ... +def _dispatch_tls_set_dispatch_key_excluded( + dispatch: _dispatchkey, + val: _bool, +) -> None: ... +def _dispatch_tls_is_dispatch_key_excluded(dispatch: _dispatchkey) -> _bool: ... +def _dispatch_tls_set_dispatch_key_included( + dispatch: _dispatchkey, + val: _bool, +) -> None: ... +def _dispatch_tls_is_dispatch_key_included(dispatch: _dispatchkey) -> _bool: ... +def _dispatch_isTensorSubclassLike(tensor: Tensor) -> _bool: ... +def _dispatch_key_name(dispatch: _dispatchkey) -> str: ... +def _dispatch_key_for_device(device_type: str) -> str: ... +def _parse_dispatch_key(key: str) -> DispatchKey | None: ... +def _dispatch_key_parse(dispatch: _dispatchkey) -> DispatchKey: ... +def _dispatch_num_backends() -> _int: ... +def _dispatch_pystub(name: str, overload: str) -> tuple[str, str] | None: ... +def _dispatch_is_alias_key(dispatch: _dispatchkey) -> _bool: ... +def _functionality_to_backend_keys(dispatch: _dispatchkey) -> list[DispatchKey]: ... +def _functionalization_reapply_views_tls() -> _bool: ... +def _only_lift_cpu_tensors() -> _bool: ... +def _set_only_lift_cpu_tensors(value: _bool) -> None: ... +def _set_throw_on_mutable_data_ptr(tensor: Tensor) -> None: ... +def _set_warn_deprecated_on_mutable_data_ptr(tensor: Tensor) -> None: ... + +class DispatchKey(Enum): + Undefined = ... + FPGA = ... + MAIA = ... + Vulkan = ... + Metal = ... + MKLDNN = ... + OpenGL = ... + OpenCL = ... + IDEEP = ... + CustomRNGKeyId = ... + MkldnnCPU = ... + Sparse = ... + SparseCsr = ... + NestedTensor = ... + Dense = ... + PythonTLSSnapshot = ... + PreDispatch = ... + PythonDispatcher = ... + Python = ... + FuncTorchDynamicLayerBackMode = ... + ZeroTensor = ... + Conjugate = ... + Negative = ... + BackendSelect = ... + Named = ... + AutogradOther = ... + AutogradFunctionality = ... + AutogradNestedTensor = ... + Tracer = ... + Autocast = ... + AutocastCPU = ... + AutocastCUDA = ... + AutocastXPU = ... + Batched = ... + VmapMode = ... + FuncTorchGradWrapper = ... + FuncTorchBatched = ... + BatchedNestedTensor = ... + FuncTorchVmapMode = ... + FuncTorchDynamicLayerFrontMode = ... + Functionalize = ... + TESTING_ONLY_GenericWrapper = ... + TESTING_ONLY_GenericMode = ... + ADInplaceOrView = ... + Autograd = ... + CompositeImplicitAutograd = ... + CompositeImplicitAutogradNestedTensor = ... + CompositeExplicitAutograd = ... + CompositeExplicitAutogradNonFunctional = ... + FuncTorchBatchedDecomposition = ... + CPU = ... + CUDA = ... + HIP = ... + XLA = ... + MTIA = ... + MPS = ... + IPU = ... + XPU = ... + HPU = ... + VE = ... + Lazy = ... + Meta = ... + PrivateUse1 = ... + PrivateUse2 = ... + PrivateUse3 = ... + QuantizedCPU = ... + QuantizedCUDA = ... + QuantizedHIP = ... + QuantizedXLA = ... + QuantizedMTIA = ... + QuantizedMPS = ... + QuantizedIPU = ... + QuantizedXPU = ... + QuantizedHPU = ... + QuantizedVE = ... + QuantizedLazy = ... + QuantizedMeta = ... + QuantizedPrivateUse1 = ... + QuantizedPrivateUse2 = ... + QuantizedPrivateUse3 = ... + SparseCPU = ... + SparseCUDA = ... + SparseHIP = ... + SparseXLA = ... + SparseMTIA = ... + SparseMPS = ... + SparseIPU = ... + SparseXPU = ... + SparseHPU = ... + SparseVE = ... + SparseLazy = ... + SparseMeta = ... + SparsePrivateUse1 = ... + SparsePrivateUse2 = ... + SparsePrivateUse3 = ... + SparseCsrCPU = ... + SparseCsrCUDA = ... + SparseCsrHIP = ... + SparseCsrXLA = ... + SparseCsrMTIA = ... + SparseCsrMPS = ... + SparseCsrIPU = ... + SparseCsrXPU = ... + SparseCsrHPU = ... + SparseCsrVE = ... + SparseCsrLazy = ... + SparseCsrMeta = ... + SparseCsrPrivateUse1 = ... + SparseCsrPrivateUse2 = ... + SparseCsrPrivateUse3 = ... + NestedTensorCPU = ... + NestedTensorCUDA = ... + NestedTensorHIP = ... + NestedTensorXLA = ... + NestedTensorMTIA = ... + NestedTensorMPS = ... + NestedTensorIPU = ... + NestedTensorXPU = ... + NestedTensorHPU = ... + NestedTensorVE = ... + NestedTensorLazy = ... + NestedTensorMeta = ... + NestedTensorPrivateUse1 = ... + NestedTensorPrivateUse2 = ... + NestedTensorPrivateUse3 = ... + AutogradCPU = ... + AutogradCUDA = ... + AutogradHIP = ... + AutogradXLA = ... + AutogradMTIA = ... + AutogradMPS = ... + AutogradIPU = ... + AutogradXPU = ... + AutogradHPU = ... + AutogradVE = ... + AutogradLazy = ... + AutogradMeta = ... + AutogradPrivateUse1 = ... + AutogradPrivateUse2 = ... + AutogradPrivateUse3 = ... + +class DispatchKeySet: + def __init__(self, key: DispatchKey) -> None: ... + def __or__(self, other: DispatchKeySet) -> DispatchKeySet: ... + def __sub__(self, other: DispatchKeySet) -> DispatchKeySet: ... + def __and__(self, other: DispatchKeySet) -> DispatchKeySet: ... + def raw_repr(self) -> _int: ... + @staticmethod + def from_raw_repr(raw: _int) -> DispatchKeySet: ... + def highestPriorityTypeId(self) -> DispatchKey: ... + def has(self, k: _dispatchkey) -> _bool: ... + def add(self, k: _dispatchkey) -> DispatchKeySet: ... + def remove(self, k: _dispatchkey) -> DispatchKeySet: ... + +_dispatch_autogradother_backends: DispatchKeySet +_additional_keys_to_prop_for_wrapper_tensors: DispatchKeySet + +def _dispatch_has_backend_fallback(dispatch: _dispatchkey) -> _bool: ... +def _dispatch_keyset_full_after(t: _dispatchkey) -> DispatchKeySet: ... +def _dispatch_keyset_full() -> DispatchKeySet: ... +def _dispatch_keyset_to_string(keyset: DispatchKeySet) -> str: ... +def _dispatch_get_backend_keyset_from_autograd( + dispatch: _dispatchkey, +) -> DispatchKeySet: ... +def _dispatch_keys(tensor: Tensor) -> DispatchKeySet: ... +def _dispatch_tls_local_exclude_set() -> DispatchKeySet: ... +def _dispatch_tls_local_include_set() -> DispatchKeySet: ... +def _dynamo_save_local_dispatch_key_set() -> None: ... +def _dynamo_restore_local_dispatch_key_set() -> None: ... +def _dispatch_is_included_in_alias( + dispatch_a: _dispatchkey, + dispatch_b: _dispatchkey, +) -> _bool: ... +def _propagate_xla_data(a: Tensor, b: Tensor) -> None: ... +def _replace_(a: Tensor, b: Tensor) -> None: ... +def _commit_update(a: Tensor) -> None: ... + +class _ExcludeDispatchKeyGuard: + def __init__(self, keyset: DispatchKeySet) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _IncludeDispatchKeyGuard: + def __init__(self, k: DispatchKey) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _ForceDispatchKeyGuard: + def __init__(self, include: DispatchKeySet, exclude: DispatchKeySet) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _PreserveDispatchKeyGuard: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _AutoDispatchBelowAutograd: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +class _AutoDispatchBelowADInplaceOrView: + def __init__(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +def _dispatch_print_registrations_for_dispatch_key(dispatch_key: str = "") -> None: ... +def _dispatch_get_registrations_for_dispatch_key( + dispatch_key: str = "", +) -> list[str]: ... +def _are_functorch_transforms_active() -> _bool: ... + +# Define in torch/csrc/autograd/init.cpp +def _set_python_dispatcher(dispatcher: object) -> None: ... +def _get_nested_int(id: _int, coeff: _int) -> SymInt: ... +def _get_constant_bool_symnode(val: _bool) -> Any: ... + +class _TorchDispatchModeKey(Enum): + FAKE = ... + PROXY = ... + FUNCTIONAL = ... + +class _SetExcludeDispatchKeyGuard: + def __init__(self, k: DispatchKey, enabled: _bool) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + +def _get_dtensor_allow_implicit_replication() -> _bool: ... +def _set_dtensor_allow_implicit_replication(value: _bool) -> None: ... + +# Defined in torch/csrc/utils/schema_info.h +class _SchemaArgType(Enum): + input = ... + output = ... + +class _SchemaArgument: + type: _SchemaArgType + idx: _int + def __init__(self, type: _SchemaArgType, idx: _int) -> None: ... + +class _SchemaInfo: + def __init__(self, schema: FunctionSchema) -> None: ... + @overload + def is_mutable(self) -> _bool: ... + @overload + def is_mutable(self, name: str) -> _bool: ... + @overload + def is_mutable(self, argument: _SchemaArgument) -> _bool: ... + def has_argument(self, name: str) -> _bool: ... + def may_alias(self, lhs: _SchemaArgument, rhs: _SchemaArgument) -> _bool: ... + def may_contain_alias( + self, lhs: _SchemaArgument, rhs: _SchemaArgument + ) -> _bool: ... + def add_argument_value(self, name: str, value: object) -> None: ... + def add_argument_values(self, values: dict[str, object]) -> None: ... + +def _overlaps(lhs: object, rhs: object) -> _bool: ... + +# Defined in torch/csrc/utils/init.cpp +class BenchmarkConfig: + num_calling_threads: _int + num_worker_threads: _int + num_warmup_iters: _int + num_iters: _int + profiler_output_path: str + +class BenchmarkExecutionStats: + latency_avg_ms: _float + num_iters: _int + +class ThroughputBenchmark: + def __init__(self, module: Any) -> None: ... + def add_input(self, *args: Any, **kwargs: Any) -> None: ... + def run_once(self, *args: Any, **kwargs: Any) -> Any: ... + def benchmark(self, config: BenchmarkConfig) -> BenchmarkExecutionStats: ... + +# Defined in torch/csrc/Storage.cpp +class StorageBase: ... + +# TODO: where +class DoubleTensor(Tensor): ... +class FloatTensor(Tensor): ... +class BFloat16Tensor(Tensor): ... +class LongTensor(Tensor): ... +class IntTensor(Tensor): ... +class ShortTensor(Tensor): ... +class HalfTensor(Tensor): ... +class CharTensor(Tensor): ... +class ByteTensor(Tensor): ... +class BoolTensor(Tensor): ... + +# Defined in torch/csrc/autograd/python_engine.cpp +class _ImperativeEngine: + def queue_callback(self, callback: Callable[[], None]) -> None: ... + def run_backward(self, *args: Any, **kwargs: Any) -> tuple[Tensor, ...]: ... + def is_checkpoint_valid(self) -> _bool: ... + +# Defined in torch/csrc/autograd/python_variable.cpp +class _TensorMeta(type): ... + +_Index: TypeAlias = SupportsIndex | _bool | _int | slice | EllipsisType | Tensor | None | _NestedSequence[_bool | _int | slice | EllipsisType | Tensor | None] # fmt: skip + +# Defined in torch/csrc/autograd/python_variable.cpp +class TensorBase(metaclass=_TensorMeta): + requires_grad: _bool + retains_grad: _bool + shape: Size + data: Tensor + device: _device + dtype: _dtype + grad_dtype: _dtype | None + layout: _layout + real: Tensor + imag: Tensor + T: Tensor + H: Tensor + mT: Tensor + mH: Tensor + ndim: _int + output_nr: _int + _version: _int + _base: Tensor | None + _cdata: _int + grad_fn: _Node | None + _grad_fn: Any + _grad: Tensor | None + grad: Tensor | None + _backward_hooks: dict[_int, Callable[[Tensor], Tensor | None]] | None + nbytes: _int + itemsize: _int + _has_symbolic_sizes_strides: _bool + + def _view_func_unsafe( + self, + new_base: Tensor, + symint_visitor_fn: Callable[[_int], _int] | None = None, + tensor_visitor_fn: Callable[[Tensor], Tensor] | None = None, + ): ... + def __abs__(self) -> Tensor: ... + def __add__(self, other: Tensor | Number | _complex) -> Tensor: ... + @overload + def __and__(self, other: Tensor) -> Tensor: ... + @overload + def __and__(self, other: Number | _complex | PySymType) -> Tensor: ... + @overload + def __and__(self, other: Tensor | _int) -> Tensor: ... + def __bool__(self) -> _bool: ... + def __complex__(self) -> _complex: ... + def __contains__(self, item: Any, /) -> _bool: ... + def __div__(self, other: Tensor | Number | _complex) -> Tensor: ... + @overload + def __eq__(self, other: Tensor | Number | _complex) -> Tensor: ... # type: ignore[overload-overlap] + @overload + def __eq__(self, other: object) -> _bool: ... + def __float__(self) -> _float: ... + def __floordiv__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __ge__(self, other: Tensor | Number | PySymType | _complex) -> Tensor: ... + def __getitem__(self, indices: _Index | tuple[_Index, ...], /) -> Tensor: ... + def __gt__(self, other: Tensor | Number | PySymType | _complex) -> Tensor: ... + def __iadd__(self, other: Tensor | Number | _complex) -> Tensor: ... # noqa: PYI034 + @overload + def __iand__(self, other: Tensor) -> Tensor: ... + @overload + def __iand__(self, other: Number | _complex | PySymType) -> Tensor: ... + @overload + def __iand__(self, other: Tensor | _int) -> Tensor: ... + def __idiv__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __ifloordiv__(self, other: Tensor | Number | _complex) -> Tensor: ... # noqa: PYI034 + @overload + def __ilshift__(self, other: Tensor) -> Tensor: ... + @overload + def __ilshift__(self, other: Number | _complex | PySymType) -> Tensor: ... + @overload + def __ilshift__(self, other: Tensor | _int) -> Tensor: ... + def __imod__(self, other: Tensor | Number | _complex) -> Tensor: ... # noqa: PYI034 + def __imul__(self, other: Tensor | Number | _complex) -> Tensor: ... # noqa: PYI034 + def __index__(self) -> _int: ... + @overload + def __init__( + self, + *args: Any, + device: DeviceLikeType | None = None, + ) -> None: ... + @overload + def __init__(self, storage: Storage) -> None: ... + @overload + def __init__(self, other: Tensor) -> None: ... + @overload + def __init__( + self, + size: _size, + *, + device: DeviceLikeType | None = None, + ) -> None: ... + def __int__(self) -> _int: ... + def __invert__(self) -> Tensor: ... + @overload + def __ior__(self, other: Tensor) -> Tensor: ... + @overload + def __ior__(self, other: Number | _complex | PySymType) -> Tensor: ... + @overload + def __ior__(self, other: Tensor | _int) -> Tensor: ... + @overload + def __irshift__(self, other: Tensor) -> Tensor: ... + @overload + def __irshift__(self, other: Number | _complex | PySymType) -> Tensor: ... + @overload + def __irshift__(self, other: Tensor | _int) -> Tensor: ... + def __isub__(self, other: Tensor | Number | _complex) -> Tensor: ... # noqa: PYI034 + @overload + def __ixor__(self, other: Tensor) -> Tensor: ... + @overload + def __ixor__(self, other: Number | _complex | PySymType) -> Tensor: ... + @overload + def __ixor__(self, other: Tensor | _int) -> Tensor: ... + def __le__(self, other: Tensor | Number | PySymType | _complex) -> Tensor: ... + def __long__(self) -> _int: ... + @overload + def __lshift__(self, other: Tensor) -> Tensor: ... + @overload + def __lshift__(self, other: Number | _complex | PySymType) -> Tensor: ... + @overload + def __lshift__(self, other: Tensor | _int) -> Tensor: ... + def __lt__(self, other: Tensor | Number | PySymType | _complex) -> Tensor: ... + def __matmul__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __mod__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __mul__(self, other: Tensor | Number | _complex) -> Tensor: ... + @overload + def __ne__(self, other: Tensor | Number | _complex) -> Tensor: ... # type: ignore[overload-overlap] + @overload + def __ne__(self, other: object) -> _bool: ... + def __neg__(self) -> Tensor: ... + def __new__(cls, *args, **kwargs) -> Self: ... + def __nonzero__(self) -> _bool: ... + @overload + def __or__(self, other: Tensor) -> Tensor: ... + @overload + def __or__(self, other: Number | _complex | PySymType) -> Tensor: ... + @overload + def __or__(self, other: Tensor | _int) -> Tensor: ... + def __pow__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __radd__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __rand__(self, other: Tensor | _int) -> Tensor: ... + def __rfloordiv__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __rmul__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __ror__(self, other: Tensor | _int) -> Tensor: ... + def __rpow__(self, other: Tensor | Number | _complex) -> Tensor: ... # type: ignore[has-type] + @overload + def __rshift__(self, other: Tensor) -> Tensor: ... + @overload + def __rshift__(self, other: Number | _complex | PySymType) -> Tensor: ... + @overload + def __rshift__(self, other: Tensor | _int) -> Tensor: ... + def __rsub__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __rtruediv__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __rxor__(self, other: Tensor | _int) -> Tensor: ... + def __setitem__( + self, + indices: _Index | tuple[_Index, ...], + value: Tensor | Number, + /, + ) -> None: ... + def __sub__(self, other: Tensor | Number | _complex) -> Tensor: ... + def __truediv__(self, other: Tensor | Number | _complex) -> Tensor: ... + @overload + def __xor__(self, other: Tensor) -> Tensor: ... + @overload + def __xor__(self, other: Number | _complex | PySymType) -> Tensor: ... + @overload + def __xor__(self, other: Tensor | _int) -> Tensor: ... + def _addmm_activation( + self, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + use_gelu: _bool = False, + ) -> Tensor: ... + def _autocast_to_full_precision( + self, + cuda_enabled: _bool, + cpu_enabled: _bool, + ) -> Tensor: ... + def _autocast_to_reduced_precision( + self, + cuda_enabled: _bool, + cpu_enabled: _bool, + cuda_dtype: _dtype, + cpu_dtype: _dtype, + ) -> Tensor: ... + def _coalesced_(self, coalesced: _bool) -> Tensor: ... + def _conj(self) -> Tensor: ... + def _conj_physical(self) -> Tensor: ... + def _dimI(self) -> _int: ... + def _dimV(self) -> _int: ... + @staticmethod + def _dtensor__new__( + cls: type[S], + local_tensor: Tensor, + spec: torch.distributed.tensor._dtensor_spec.DTensorSpec, + requires_grad: _bool, + ) -> S: ... + def _indices(self) -> Tensor: ... + def _is_all_true(self) -> Tensor: ... + def _is_any_true(self) -> Tensor: ... + def _is_view(self) -> _bool: ... + def _is_zerotensor(self) -> _bool: ... + def _lazy_clone(self) -> Tensor: ... + @staticmethod + def _make_subclass( + cls: type[S], + data: Tensor, + require_grad: _bool = False, + dispatch_strides: _bool = False, + dispatch_device: _bool = False, + device_for_backend_keys: _device | None = None, + ) -> S: ... + @staticmethod + def _make_wrapper_subclass( + cls: type[S], + size: Sequence[_int | SymInt], + strides: Sequence[_int | SymInt] | None = None, + storage_offset: _int | SymInt | None = None, + memory_format: torch.memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout = strided, + device: _device | None = None, + pin_memory: _bool = False, + requires_grad: _bool = False, + dispatch_sizes_strides_policy: str | None = None, + dispatch_device: _bool = False, + dispatch_layout: _bool = False, + _extra_dispatch_keys: torch.DispatchKeySet | None = None, + storage_size: _int | SymInt | None = None, + ) -> S: ... + def _neg_view(self) -> Tensor: ... + def _nested_tensor_size(self) -> Tensor: ... + def _nested_tensor_storage_offsets(self) -> Tensor: ... + def _nested_tensor_strides(self) -> Tensor: ... + def _nnz(self) -> _int: ... + def _philox_normal_( + self, + key: Tensor, + mean: _float = 0, + std: _float = 1, + ) -> Tensor: ... + def _philox_uniform_( + self, + key: Tensor, + low: _float = 0, + high: _float = 1, + ) -> Tensor: ... + def _sparse_mask_projection( + self, + mask: Tensor, + accumulate_matches: _bool = False, + ) -> Tensor: ... + def _to_dense( + self, + dtype: _dtype | None = None, + masked_grad: _bool | None = None, + ) -> Tensor: ... + @overload + def _to_sparse( + self, + *, + layout: _layout | None = None, + blocksize: _int | _size | None = None, + dense_dim: _int | None = None, + ) -> Tensor: ... + @overload + def _to_sparse(self, sparse_dim: _int) -> Tensor: ... + def _to_sparse_bsc( + self, + blocksize: _int | _size, + dense_dim: _int | None = None, + ) -> Tensor: ... + def _to_sparse_bsr( + self, + blocksize: _int | _size, + dense_dim: _int | None = None, + ) -> Tensor: ... + def _to_sparse_csc(self, dense_dim: _int | None = None) -> Tensor: ... + def _to_sparse_csr(self, dense_dim: _int | None = None) -> Tensor: ... + def _values(self) -> Tensor: ... + def abs(self) -> Tensor: + r""" + abs() -> Tensor + + See :func:`torch.abs` + """ + + def abs_(self) -> Tensor: + r""" + abs_() -> Tensor + + In-place version of :meth:`~Tensor.abs` + """ + + def absolute(self) -> Tensor: + r""" + absolute() -> Tensor + + Alias for :func:`abs` + """ + + def absolute_(self) -> Tensor: + r""" + absolute_() -> Tensor + + In-place version of :meth:`~Tensor.absolute` + Alias for :func:`abs_` + """ + + def acos(self) -> Tensor: + r""" + acos() -> Tensor + + See :func:`torch.acos` + """ + + def acos_(self) -> Tensor: + r""" + acos_() -> Tensor + + In-place version of :meth:`~Tensor.acos` + """ + + def acosh(self) -> Tensor: + r""" + acosh() -> Tensor + + See :func:`torch.acosh` + """ + + def acosh_(self) -> Tensor: + r""" + acosh_() -> Tensor + + In-place version of :meth:`~Tensor.acosh` + """ + + def add( + self, + other: Tensor | Number | _complex | torch.SymInt | torch.SymFloat, + *, + alpha: Number | _complex | None = 1, + out: Tensor | None = None, + ) -> Tensor: + r""" + add(other, *, alpha=1) -> Tensor + + Add a scalar or tensor to :attr:`self` tensor. If both :attr:`alpha` + and :attr:`other` are specified, each element of :attr:`other` is scaled by + :attr:`alpha` before being used. + + When :attr:`other` is a tensor, the shape of :attr:`other` must be + :ref:`broadcastable ` with the shape of the underlying + tensor + + See :func:`torch.add` + """ + + def add_( + self, + other: Tensor | Number | _complex | torch.SymInt | torch.SymFloat, + *, + alpha: Number | _complex | None = 1, + ) -> Tensor: + r""" + add_(other, *, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.add` + """ + + def addbmm( + self, + batch1: Tensor, + batch2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addbmm(batch1, batch2, *, beta=1, alpha=1) -> Tensor + + See :func:`torch.addbmm` + """ + + def addbmm_( + self, + batch1: Tensor, + batch2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addbmm_(batch1, batch2, *, beta=1, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.addbmm` + """ + + def addcdiv( + self, + tensor1: Tensor, + tensor2: Tensor, + *, + value: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addcdiv(tensor1, tensor2, *, value=1) -> Tensor + + See :func:`torch.addcdiv` + """ + + def addcdiv_( + self, + tensor1: Tensor, + tensor2: Tensor, + *, + value: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addcdiv_(tensor1, tensor2, *, value=1) -> Tensor + + In-place version of :meth:`~Tensor.addcdiv` + """ + + def addcmul( + self, + tensor1: Tensor, + tensor2: Tensor, + *, + value: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addcmul(tensor1, tensor2, *, value=1) -> Tensor + + See :func:`torch.addcmul` + """ + + def addcmul_( + self, + tensor1: Tensor, + tensor2: Tensor, + *, + value: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addcmul_(tensor1, tensor2, *, value=1) -> Tensor + + In-place version of :meth:`~Tensor.addcmul` + """ + + def addmm( + self, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addmm(mat1, mat2, *, beta=1, alpha=1) -> Tensor + + See :func:`torch.addmm` + """ + + def addmm_( + self, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addmm_(mat1, mat2, *, beta=1, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.addmm` + """ + + def addmv( + self, + mat: Tensor, + vec: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addmv(mat, vec, *, beta=1, alpha=1) -> Tensor + + See :func:`torch.addmv` + """ + + def addmv_( + self, + mat: Tensor, + vec: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addmv_(mat, vec, *, beta=1, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.addmv` + """ + + def addr( + self, + vec1: Tensor, + vec2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addr(vec1, vec2, *, beta=1, alpha=1) -> Tensor + + See :func:`torch.addr` + """ + + def addr_( + self, + vec1: Tensor, + vec2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + addr_(vec1, vec2, *, beta=1, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.addr` + """ + + def adjoint(self) -> Tensor: + r""" + adjoint() -> Tensor + + Alias for :func:`adjoint` + """ + + @overload + def all(self) -> Tensor: + r""" + all(dim=None, keepdim=False) -> Tensor + + See :func:`torch.all` + """ + + @overload + def all(self, dim: _size | None = None, keepdim: _bool = False) -> Tensor: + r""" + all(dim=None, keepdim=False) -> Tensor + + See :func:`torch.all` + """ + + @overload + def all(self, dim: _int, keepdim: _bool = False) -> Tensor: + r""" + all(dim=None, keepdim=False) -> Tensor + + See :func:`torch.all` + """ + + def allclose( + self, + other: Tensor, + rtol: _float = 1e-05, + atol: _float = 1e-08, + equal_nan: _bool = False, + ) -> _bool: + r""" + allclose(other, rtol=1e-05, atol=1e-08, equal_nan=False) -> Tensor + + See :func:`torch.allclose` + """ + + def amax(self, dim: _int | _size = (), keepdim: _bool = False) -> Tensor: + r""" + amax(dim=None, keepdim=False) -> Tensor + + See :func:`torch.amax` + """ + + def amin(self, dim: _int | _size = (), keepdim: _bool = False) -> Tensor: + r""" + amin(dim=None, keepdim=False) -> Tensor + + See :func:`torch.amin` + """ + + def aminmax( + self, + *, + dim: _int | None = None, + keepdim: _bool = False, + ) -> torch.return_types.aminmax: + r""" + aminmax(*, dim=None, keepdim=False) -> (Tensor min, Tensor max) + + See :func:`torch.aminmax` + """ + + def angle(self) -> Tensor: + r""" + angle() -> Tensor + + See :func:`torch.angle` + """ + + @overload + def any(self) -> Tensor: + r""" + any(dim=None, keepdim=False) -> Tensor + + See :func:`torch.any` + """ + + @overload + def any(self, dim: _size | None = None, keepdim: _bool = False) -> Tensor: + r""" + any(dim=None, keepdim=False) -> Tensor + + See :func:`torch.any` + """ + + @overload + def any(self, dim: _int, keepdim: _bool = False) -> Tensor: + r""" + any(dim=None, keepdim=False) -> Tensor + + See :func:`torch.any` + """ + + def apply_(self, callable: Callable) -> Tensor: + r""" + apply_(callable) -> Tensor + + Applies the function :attr:`callable` to each element in the tensor, replacing + each element with the value returned by :attr:`callable`. + + .. note:: + + This function only works with CPU tensors and should not be used in code + sections that require high performance. + """ + + def arccos(self) -> Tensor: + r""" + arccos() -> Tensor + + See :func:`torch.arccos` + """ + + def arccos_(self) -> Tensor: + r""" + arccos_() -> Tensor + + In-place version of :meth:`~Tensor.arccos` + """ + + def arccosh(self) -> Tensor: + r""" + acosh() -> Tensor + + See :func:`torch.arccosh` + """ + + def arccosh_(self) -> Tensor: + r""" + acosh_() -> Tensor + + In-place version of :meth:`~Tensor.arccosh` + """ + + def arcsin(self) -> Tensor: + r""" + arcsin() -> Tensor + + See :func:`torch.arcsin` + """ + + def arcsin_(self) -> Tensor: + r""" + arcsin_() -> Tensor + + In-place version of :meth:`~Tensor.arcsin` + """ + + def arcsinh(self) -> Tensor: + r""" + arcsinh() -> Tensor + + See :func:`torch.arcsinh` + """ + + def arcsinh_(self) -> Tensor: + r""" + arcsinh_() -> Tensor + + In-place version of :meth:`~Tensor.arcsinh` + """ + + def arctan(self) -> Tensor: + r""" + arctan() -> Tensor + + See :func:`torch.arctan` + """ + + def arctan2(self, other: Tensor) -> Tensor: + r""" + arctan2(other) -> Tensor + + See :func:`torch.arctan2` + """ + + def arctan2_(self, other: Tensor) -> Tensor: + r""" + atan2_(other) -> Tensor + + In-place version of :meth:`~Tensor.arctan2` + """ + + def arctan_(self) -> Tensor: + r""" + arctan_() -> Tensor + + In-place version of :meth:`~Tensor.arctan` + """ + + def arctanh(self) -> Tensor: + r""" + arctanh() -> Tensor + + See :func:`torch.arctanh` + """ + + def arctanh_(self) -> Tensor: + r""" + arctanh_(other) -> Tensor + + In-place version of :meth:`~Tensor.arctanh` + """ + + def argmax(self, dim: _int | None = None, keepdim: _bool = False) -> Tensor: + r""" + argmax(dim=None, keepdim=False) -> LongTensor + + See :func:`torch.argmax` + """ + + def argmin(self, dim: _int | None = None, keepdim: _bool = False) -> Tensor: + r""" + argmin(dim=None, keepdim=False) -> LongTensor + + See :func:`torch.argmin` + """ + + @overload + def argsort( + self, + *, + stable: _bool, + dim: _int = -1, + descending: _bool = False, + ) -> Tensor: + r""" + argsort(dim=-1, descending=False) -> LongTensor + + See :func:`torch.argsort` + """ + + @overload + def argsort(self, dim: _int = -1, descending: _bool = False) -> Tensor: + r""" + argsort(dim=-1, descending=False) -> LongTensor + + See :func:`torch.argsort` + """ + + def argwhere(self) -> Tensor: + r""" + argwhere() -> Tensor + + See :func:`torch.argwhere` + """ + + def as_strided( + self, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, + ) -> Tensor: + r""" + as_strided(size, stride, storage_offset=None) -> Tensor + + See :func:`torch.as_strided` + """ + + def as_strided_( + self, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, + ) -> Tensor: + r""" + as_strided_(size, stride, storage_offset=None) -> Tensor + + In-place version of :meth:`~Tensor.as_strided` + """ + + def as_strided_scatter( + self, + src: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, + ) -> Tensor: + r""" + as_strided_scatter(src, size, stride, storage_offset=None) -> Tensor + + See :func:`torch.as_strided_scatter` + """ + + def as_subclass(self, cls: type[S]) -> S: + r""" + as_subclass(cls) -> Tensor + + Makes a ``cls`` instance with the same data pointer as ``self``. Changes + in the output mirror changes in ``self``, and the output stays attached + to the autograd graph. ``cls`` must be a subclass of ``Tensor``. + """ + + def asin(self) -> Tensor: + r""" + asin() -> Tensor + + See :func:`torch.asin` + """ + + def asin_(self) -> Tensor: + r""" + asin_() -> Tensor + + In-place version of :meth:`~Tensor.asin` + """ + + def asinh(self) -> Tensor: + r""" + asinh() -> Tensor + + See :func:`torch.asinh` + """ + + def asinh_(self) -> Tensor: + r""" + asinh_() -> Tensor + + In-place version of :meth:`~Tensor.asinh` + """ + + def atan(self) -> Tensor: + r""" + atan() -> Tensor + + See :func:`torch.atan` + """ + + def atan2(self, other: Tensor) -> Tensor: + r""" + atan2(other) -> Tensor + + See :func:`torch.atan2` + """ + + def atan2_(self, other: Tensor) -> Tensor: + r""" + atan2_(other) -> Tensor + + In-place version of :meth:`~Tensor.atan2` + """ + + def atan_(self) -> Tensor: + r""" + atan_() -> Tensor + + In-place version of :meth:`~Tensor.atan` + """ + + def atanh(self) -> Tensor: + r""" + atanh() -> Tensor + + See :func:`torch.atanh` + """ + + def atanh_(self) -> Tensor: + r""" + atanh_(other) -> Tensor + + In-place version of :meth:`~Tensor.atanh` + """ + + def baddbmm( + self, + batch1: Tensor, + batch2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + baddbmm(batch1, batch2, *, beta=1, alpha=1) -> Tensor + + See :func:`torch.baddbmm` + """ + + def baddbmm_( + self, + batch1: Tensor, + batch2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + baddbmm_(batch1, batch2, *, beta=1, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.baddbmm` + """ + + @overload + def bernoulli(self, *, generator: Generator | None = None) -> Tensor: + r""" + bernoulli(*, generator=None) -> Tensor + + Returns a result tensor where each :math:`\texttt{result[i]}` is independently + sampled from :math:`\text{Bernoulli}(\texttt{self[i]})`. :attr:`self` must have + floating point ``dtype``, and the result will have the same ``dtype``. + + See :func:`torch.bernoulli` + """ + + @overload + def bernoulli( + self, + p: _float, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + bernoulli(*, generator=None) -> Tensor + + Returns a result tensor where each :math:`\texttt{result[i]}` is independently + sampled from :math:`\text{Bernoulli}(\texttt{self[i]})`. :attr:`self` must have + floating point ``dtype``, and the result will have the same ``dtype``. + + See :func:`torch.bernoulli` + """ + + @overload + def bernoulli_( + self, + p: Tensor, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + bernoulli_(p=0.5, *, generator=None) -> Tensor + + Fills each location of :attr:`self` with an independent sample from + :math:`\text{Bernoulli}(\texttt{p})`. :attr:`self` can have integral + ``dtype``. + + :attr:`p` should either be a scalar or tensor containing probabilities to be + used for drawing the binary random number. + + If it is a tensor, the :math:`\text{i}^{th}` element of :attr:`self` tensor + will be set to a value sampled from + :math:`\text{Bernoulli}(\texttt{p\_tensor[i]})`. In this case `p` must have + floating point ``dtype``. + + See also :meth:`~Tensor.bernoulli` and :func:`torch.bernoulli` + """ + + @overload + def bernoulli_( + self, + p: _float = 0.5, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + bernoulli_(p=0.5, *, generator=None) -> Tensor + + Fills each location of :attr:`self` with an independent sample from + :math:`\text{Bernoulli}(\texttt{p})`. :attr:`self` can have integral + ``dtype``. + + :attr:`p` should either be a scalar or tensor containing probabilities to be + used for drawing the binary random number. + + If it is a tensor, the :math:`\text{i}^{th}` element of :attr:`self` tensor + will be set to a value sampled from + :math:`\text{Bernoulli}(\texttt{p\_tensor[i]})`. In this case `p` must have + floating point ``dtype``. + + See also :meth:`~Tensor.bernoulli` and :func:`torch.bernoulli` + """ + + def bfloat16(self) -> Tensor: + r""" + bfloat16(memory_format=torch.preserve_format) -> Tensor + ``self.bfloat16()`` is equivalent to ``self.to(torch.bfloat16)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def bincount( + self, + weights: Tensor | None = None, + minlength: _int | SymInt = 0, + ) -> Tensor: + r""" + bincount(weights=None, minlength=0) -> Tensor + + See :func:`torch.bincount` + """ + + @overload + def bitwise_and(self, other: Tensor) -> Tensor: + r""" + bitwise_and() -> Tensor + + See :func:`torch.bitwise_and` + """ + + @overload + def bitwise_and(self, other: Number | _complex | PySymType) -> Tensor: + r""" + bitwise_and() -> Tensor + + See :func:`torch.bitwise_and` + """ + + @overload + def bitwise_and_(self, other: Tensor) -> Tensor: + r""" + bitwise_and_() -> Tensor + + In-place version of :meth:`~Tensor.bitwise_and` + """ + + @overload + def bitwise_and_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + bitwise_and_() -> Tensor + + In-place version of :meth:`~Tensor.bitwise_and` + """ + + @overload + def bitwise_left_shift(self, other: Tensor) -> Tensor: + r""" + bitwise_left_shift(other) -> Tensor + + See :func:`torch.bitwise_left_shift` + """ + + @overload + def bitwise_left_shift( + self, + other: Number | _complex | PySymType, + ) -> Tensor: + r""" + bitwise_left_shift(other) -> Tensor + + See :func:`torch.bitwise_left_shift` + """ + + @overload + def bitwise_left_shift_(self, other: Tensor) -> Tensor: + r""" + bitwise_left_shift_(other) -> Tensor + + In-place version of :meth:`~Tensor.bitwise_left_shift` + """ + + @overload + def bitwise_left_shift_( + self, + other: Number | _complex | PySymType, + ) -> Tensor: + r""" + bitwise_left_shift_(other) -> Tensor + + In-place version of :meth:`~Tensor.bitwise_left_shift` + """ + + def bitwise_not(self) -> Tensor: + r""" + bitwise_not() -> Tensor + + See :func:`torch.bitwise_not` + """ + + def bitwise_not_(self) -> Tensor: + r""" + bitwise_not_() -> Tensor + + In-place version of :meth:`~Tensor.bitwise_not` + """ + + @overload + def bitwise_or(self, other: Tensor) -> Tensor: + r""" + bitwise_or() -> Tensor + + See :func:`torch.bitwise_or` + """ + + @overload + def bitwise_or(self, other: Number | _complex | PySymType) -> Tensor: + r""" + bitwise_or() -> Tensor + + See :func:`torch.bitwise_or` + """ + + @overload + def bitwise_or_(self, other: Tensor) -> Tensor: + r""" + bitwise_or_() -> Tensor + + In-place version of :meth:`~Tensor.bitwise_or` + """ + + @overload + def bitwise_or_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + bitwise_or_() -> Tensor + + In-place version of :meth:`~Tensor.bitwise_or` + """ + + @overload + def bitwise_right_shift(self, other: Tensor) -> Tensor: + r""" + bitwise_right_shift(other) -> Tensor + + See :func:`torch.bitwise_right_shift` + """ + + @overload + def bitwise_right_shift( + self, + other: Number | _complex | PySymType, + ) -> Tensor: + r""" + bitwise_right_shift(other) -> Tensor + + See :func:`torch.bitwise_right_shift` + """ + + @overload + def bitwise_right_shift_(self, other: Tensor) -> Tensor: + r""" + bitwise_right_shift_(other) -> Tensor + + In-place version of :meth:`~Tensor.bitwise_right_shift` + """ + + @overload + def bitwise_right_shift_( + self, + other: Number | _complex | PySymType, + ) -> Tensor: + r""" + bitwise_right_shift_(other) -> Tensor + + In-place version of :meth:`~Tensor.bitwise_right_shift` + """ + + @overload + def bitwise_xor(self, other: Tensor) -> Tensor: + r""" + bitwise_xor() -> Tensor + + See :func:`torch.bitwise_xor` + """ + + @overload + def bitwise_xor(self, other: Number | _complex | PySymType) -> Tensor: + r""" + bitwise_xor() -> Tensor + + See :func:`torch.bitwise_xor` + """ + + @overload + def bitwise_xor_(self, other: Tensor) -> Tensor: + r""" + bitwise_xor_() -> Tensor + + In-place version of :meth:`~Tensor.bitwise_xor` + """ + + @overload + def bitwise_xor_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + bitwise_xor_() -> Tensor + + In-place version of :meth:`~Tensor.bitwise_xor` + """ + + def bmm(self, mat2: Tensor) -> Tensor: + r""" + bmm(batch2) -> Tensor + + See :func:`torch.bmm` + """ + + def bool(self) -> Tensor: + r""" + bool(memory_format=torch.preserve_format) -> Tensor + + ``self.bool()`` is equivalent to ``self.to(torch.bool)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + @overload + def broadcast_to(self, size: Sequence[_int | SymInt]) -> Tensor: + r""" + broadcast_to(shape) -> Tensor + + See :func:`torch.broadcast_to`. + """ + + @overload + def broadcast_to(self, *size: _int | SymInt) -> Tensor: + r""" + broadcast_to(shape) -> Tensor + + See :func:`torch.broadcast_to`. + """ + + def byte(self) -> Tensor: + r""" + byte(memory_format=torch.preserve_format) -> Tensor + + ``self.byte()`` is equivalent to ``self.to(torch.uint8)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def cauchy_( + self, + median: _float = 0, + sigma: _float = 1, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + cauchy_(median=0, sigma=1, *, generator=None) -> Tensor + + Fills the tensor with numbers drawn from the Cauchy distribution: + + .. math:: + + f(x) = \dfrac{1}{\pi} \dfrac{\sigma}{(x - \text{median})^2 + \sigma^2} + + .. note:: + Sigma (:math:`\sigma`) is used to denote the scale parameter in Cauchy distribution. + """ + + def ccol_indices(self) -> Tensor: ... + def ceil(self) -> Tensor: + r""" + ceil() -> Tensor + + See :func:`torch.ceil` + """ + + def ceil_(self) -> Tensor: + r""" + ceil_() -> Tensor + + In-place version of :meth:`~Tensor.ceil` + """ + + def chalf(self, *, memory_format: memory_format | None = None) -> Tensor: + r""" + chalf(memory_format=torch.preserve_format) -> Tensor + + ``self.chalf()`` is equivalent to ``self.to(torch.complex32)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def char(self) -> Tensor: + r""" + char(memory_format=torch.preserve_format) -> Tensor + + ``self.char()`` is equivalent to ``self.to(torch.int8)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def cholesky_inverse(self, upper: _bool = False) -> Tensor: + r""" + cholesky_inverse(upper=False) -> Tensor + + See :func:`torch.cholesky_inverse` + """ + + def cholesky_solve(self, input2: Tensor, upper: _bool = False) -> Tensor: + r""" + cholesky_solve(input2, upper=False) -> Tensor + + See :func:`torch.cholesky_solve` + """ + + def chunk(self, chunks: _int, dim: _int = 0) -> tuple[Tensor, ...]: + r""" + chunk(chunks, dim=0) -> List of Tensors + + See :func:`torch.chunk` + """ + + @overload + def clamp( + self, + min: Tensor | None = None, + max: Tensor | None = None, + ) -> Tensor: + r""" + clamp(min=None, max=None) -> Tensor + + See :func:`torch.clamp` + """ + + @overload + def clamp( + self, + min: Number | _complex | PySymType | None = None, + max: Number | _complex | PySymType | None = None, + ) -> Tensor: + r""" + clamp(min=None, max=None) -> Tensor + + See :func:`torch.clamp` + """ + + @overload + def clamp_( + self, + min: Tensor | None = None, + max: Tensor | None = None, + ) -> Tensor: + r""" + clamp_(min=None, max=None) -> Tensor + + In-place version of :meth:`~Tensor.clamp` + """ + + @overload + def clamp_( + self, + min: Number | _complex | PySymType | None = None, + max: Number | _complex | PySymType | None = None, + ) -> Tensor: + r""" + clamp_(min=None, max=None) -> Tensor + + In-place version of :meth:`~Tensor.clamp` + """ + + @overload + def clamp_max(self, max: Tensor) -> Tensor: ... + @overload + def clamp_max(self, max: Number | _complex | PySymType) -> Tensor: ... + @overload + def clamp_max_(self, max: Tensor) -> Tensor: ... + @overload + def clamp_max_(self, max: Number | _complex | PySymType) -> Tensor: ... + @overload + def clamp_min(self, min: Tensor) -> Tensor: ... + @overload + def clamp_min(self, min: Number | _complex | PySymType) -> Tensor: ... + @overload + def clamp_min_(self, min: Tensor) -> Tensor: ... + @overload + def clamp_min_(self, min: Number | _complex | PySymType) -> Tensor: ... + @overload + def clip( + self, + min: Tensor | None = None, + max: Tensor | None = None, + ) -> Tensor: + r""" + clip(min=None, max=None) -> Tensor + + Alias for :meth:`~Tensor.clamp`. + """ + + @overload + def clip( + self, + min: Number | _complex | PySymType | None = None, + max: Number | _complex | PySymType | None = None, + ) -> Tensor: + r""" + clip(min=None, max=None) -> Tensor + + Alias for :meth:`~Tensor.clamp`. + """ + + @overload + def clip_( + self, + min: Tensor | None = None, + max: Tensor | None = None, + ) -> Tensor: + r""" + clip_(min=None, max=None) -> Tensor + + Alias for :meth:`~Tensor.clamp_`. + """ + + @overload + def clip_( + self, + min: Number | _complex | PySymType | None = None, + max: Number | _complex | PySymType | None = None, + ) -> Tensor: + r""" + clip_(min=None, max=None) -> Tensor + + Alias for :meth:`~Tensor.clamp_`. + """ + + def clone(self, *, memory_format: memory_format | None = None) -> Tensor: + r""" + clone(*, memory_format=torch.preserve_format) -> Tensor + + See :func:`torch.clone` + """ + + def coalesce(self) -> Tensor: + r""" + coalesce() -> Tensor + + Returns a coalesced copy of :attr:`self` if :attr:`self` is an + :ref:`uncoalesced tensor `. + + Returns :attr:`self` if :attr:`self` is a coalesced tensor. + + .. warning:: + Throws an error if :attr:`self` is not a sparse COO tensor. + """ + + def col_indices(self) -> Tensor: + r""" + col_indices() -> IntTensor + + Returns the tensor containing the column indices of the :attr:`self` + tensor when :attr:`self` is a sparse CSR tensor of layout ``sparse_csr``. + The ``col_indices`` tensor is strictly of shape (:attr:`self`.nnz()) + and of type ``int32`` or ``int64``. When using MKL routines such as sparse + matrix multiplication, it is necessary to use ``int32`` indexing in order + to avoid downcasting and potentially losing information. + + Example:: + + >>> csr = torch.eye(5,5).to_sparse_csr() + >>> csr.col_indices() + tensor([0, 1, 2, 3, 4], dtype=torch.int32) + """ + + def conj(self) -> Tensor: + r""" + conj() -> Tensor + + See :func:`torch.conj` + """ + + def conj_physical(self) -> Tensor: + r""" + conj_physical() -> Tensor + + See :func:`torch.conj_physical` + """ + + def conj_physical_(self) -> Tensor: + r""" + conj_physical_() -> Tensor + + In-place version of :meth:`~Tensor.conj_physical` + """ + + def contiguous( + self, + memory_format: torch.memory_format = torch.contiguous_format, + ) -> Tensor: + r""" + contiguous(memory_format=torch.contiguous_format) -> Tensor + + Returns a contiguous in memory tensor containing the same data as :attr:`self` tensor. If + :attr:`self` tensor is already in the specified memory format, this function returns the + :attr:`self` tensor. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.contiguous_format``. + """ + + def copy_(self, other: Tensor, non_blocking: _bool = False) -> Tensor: + r""" + copy_(src, non_blocking=False) -> Tensor + + Copies the elements from :attr:`src` into :attr:`self` tensor and returns + :attr:`self`. + + The :attr:`src` tensor must be :ref:`broadcastable ` + with the :attr:`self` tensor. It may be of a different data type or reside on a + different device. + + Args: + src (Tensor): the source tensor to copy from + non_blocking (bool, optional): if ``True`` and this copy is between CPU and GPU, + the copy may occur asynchronously with respect to the host. For other + cases, this argument has no effect. Default: ``False`` + + .. note:: + + When :attr:`non_blocking` is ``True`` and the copy is issued on a + non-default CUDA stream, the caller is responsible for proper + cross-stream synchronization. See :ref:`cuda-stream-semantics` for + the required pattern. + """ + + @overload + def copysign(self, other: Tensor) -> Tensor: + r""" + copysign(other) -> Tensor + + See :func:`torch.copysign` + """ + + @overload + def copysign(self, other: Number | _complex | PySymType) -> Tensor: + r""" + copysign(other) -> Tensor + + See :func:`torch.copysign` + """ + + @overload + def copysign_(self, other: Tensor) -> Tensor: + r""" + copysign_(other) -> Tensor + + In-place version of :meth:`~Tensor.copysign` + """ + + @overload + def copysign_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + copysign_(other) -> Tensor + + In-place version of :meth:`~Tensor.copysign` + """ + + def corrcoef(self) -> Tensor: + r""" + corrcoef() -> Tensor + + See :func:`torch.corrcoef` + """ + + def cos(self) -> Tensor: + r""" + cos() -> Tensor + + See :func:`torch.cos` + """ + + def cos_(self) -> Tensor: + r""" + cos_() -> Tensor + + In-place version of :meth:`~Tensor.cos` + """ + + def cosh(self) -> Tensor: + r""" + cosh() -> Tensor + + See :func:`torch.cosh` + """ + + def cosh_(self) -> Tensor: + r""" + cosh_() -> Tensor + + In-place version of :meth:`~Tensor.cosh` + """ + + @overload + def count_nonzero(self, dim: _int | None = None) -> Tensor: + r""" + count_nonzero(dim=None) -> Tensor + + See :func:`torch.count_nonzero` + """ + + @overload + def count_nonzero(self, dim: _size) -> Tensor: + r""" + count_nonzero(dim=None) -> Tensor + + See :func:`torch.count_nonzero` + """ + + @overload + def count_nonzero(self, *dim: _int) -> Tensor: + r""" + count_nonzero(dim=None) -> Tensor + + See :func:`torch.count_nonzero` + """ + + def cov( + self, + *, + correction: _int = 1, + fweights: Tensor | None = None, + aweights: Tensor | None = None, + ) -> Tensor: + r""" + cov(*, correction=1, fweights=None, aweights=None) -> Tensor + + See :func:`torch.cov` + """ + + def cpu( + self, + memory_format: torch.memory_format = torch.preserve_format, + ) -> Tensor: + r""" + cpu(memory_format=torch.preserve_format) -> Tensor + + Returns a copy of this object in CPU memory. + + If this object is already in CPU memory, + then no copy is performed and the original object is returned. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def cross(self, other: Tensor, dim: _int | None = None) -> Tensor: + r""" + cross(other, dim=None) -> Tensor + + See :func:`torch.cross` + """ + + def crow_indices(self) -> Tensor: + r""" + crow_indices() -> IntTensor + + Returns the tensor containing the compressed row indices of the :attr:`self` + tensor when :attr:`self` is a sparse CSR tensor of layout ``sparse_csr``. + The ``crow_indices`` tensor is strictly of shape (:attr:`self`.size(0) + 1) + and of type ``int32`` or ``int64``. When using MKL routines such as sparse + matrix multiplication, it is necessary to use ``int32`` indexing in order + to avoid downcasting and potentially losing information. + + Example:: + + >>> csr = torch.eye(5,5).to_sparse_csr() + >>> csr.crow_indices() + tensor([0, 1, 2, 3, 4, 5], dtype=torch.int32) + """ + + def cuda( + self, + device: _device | _int | str | None = None, + non_blocking: _bool = False, + memory_format: torch.memory_format = torch.preserve_format, + ) -> Tensor: + r""" + cuda(device=None, non_blocking=False, memory_format=torch.preserve_format) -> Tensor + + Returns a copy of this object in CUDA memory. + + If this object is already in CUDA memory and on the correct device, + then no copy is performed and the original object is returned. + + Args: + device (:class:`torch.device`, optional): The destination GPU device. + Defaults to the current CUDA device. + non_blocking (bool, optional): If ``True`` and the source is in pinned memory, + the copy will be asynchronous with respect to the host. + Otherwise, the argument has no effect. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def cummax(self, dim: _int) -> torch.return_types.cummax: + r""" + cummax(dim) -> (Tensor, Tensor) + + See :func:`torch.cummax` + """ + + def cummin(self, dim: _int) -> torch.return_types.cummin: + r""" + cummin(dim) -> (Tensor, Tensor) + + See :func:`torch.cummin` + """ + + def cumprod(self, dim: _int, *, dtype: _dtype | None = None) -> Tensor: + r""" + cumprod(dim, dtype=None) -> Tensor + + See :func:`torch.cumprod` + """ + + def cumprod_(self, dim: _int, *, dtype: _dtype | None = None) -> Tensor: + r""" + cumprod_(dim, dtype=None) -> Tensor + + In-place version of :meth:`~Tensor.cumprod` + """ + + def cumsum(self, dim: _int, *, dtype: _dtype | None = None) -> Tensor: + r""" + cumsum(dim, dtype=None) -> Tensor + + See :func:`torch.cumsum` + """ + + def cumsum_(self, dim: _int, *, dtype: _dtype | None = None) -> Tensor: + r""" + cumsum_(dim, dtype=None) -> Tensor + + In-place version of :meth:`~Tensor.cumsum` + """ + + def data_ptr(self) -> _int: + r""" + data_ptr() -> int + + Returns the address of the first element of :attr:`self` tensor. + + .. note:: + + If the tensor is a copy-on-write tensor (e.g. created via + :meth:`_lazy_clone`), calling this method will materialize the + copy. Use :meth:`const_data_ptr` if you only need read-only access + to the data pointer. + """ + + def deg2rad(self) -> Tensor: + r""" + deg2rad() -> Tensor + + See :func:`torch.deg2rad` + """ + + def deg2rad_(self) -> Tensor: + r""" + deg2rad_() -> Tensor + + In-place version of :meth:`~Tensor.deg2rad` + """ + + def dense_dim(self) -> _int: + r""" + dense_dim() -> int + + Return the number of dense dimensions in a :ref:`sparse tensor ` :attr:`self`. + + .. note:: + Returns ``len(self.shape)`` if :attr:`self` is not a sparse tensor. + + See also :meth:`Tensor.sparse_dim` and :ref:`hybrid tensors `. + """ + + def dequantize(self) -> Tensor: + r""" + dequantize() -> Tensor + + Given a quantized Tensor, dequantize it and return the dequantized float Tensor. + """ + + def det(self) -> Tensor: + r""" + det() -> Tensor + + See :func:`torch.det` + """ + + def detach(self) -> Tensor: ... + def detach_(self) -> Tensor: ... + def diag(self, diagonal: _int = 0) -> Tensor: + r""" + diag(diagonal=0) -> Tensor + + See :func:`torch.diag` + """ + + def diag_embed( + self, + offset: _int = 0, + dim1: _int = -2, + dim2: _int = -1, + ) -> Tensor: + r""" + diag_embed(offset=0, dim1=-2, dim2=-1) -> Tensor + + See :func:`torch.diag_embed` + """ + + def diagflat(self, offset: _int = 0) -> Tensor: + r""" + diagflat(offset=0) -> Tensor + + See :func:`torch.diagflat` + """ + + def diagonal( + self, + offset: _int = 0, + dim1: _int = 0, + dim2: _int = 1, + ) -> Tensor: + r""" + diagonal(offset=0, dim1=0, dim2=1) -> Tensor + + See :func:`torch.diagonal` + """ + + def diagonal_scatter( + self, + src: Tensor, + offset: _int = 0, + dim1: _int = 0, + dim2: _int = 1, + ) -> Tensor: + r""" + diagonal_scatter(src, offset=0, dim1=0, dim2=1) -> Tensor + + See :func:`torch.diagonal_scatter` + """ + + def diff( + self, + n: _int = 1, + dim: _int = -1, + prepend: Tensor | None = None, + append: Tensor | None = None, + ) -> Tensor: + r""" + diff(n=1, dim=-1, prepend=None, append=None) -> Tensor + + See :func:`torch.diff` + """ + + def digamma(self) -> Tensor: + r""" + digamma() -> Tensor + + See :func:`torch.digamma` + """ + + def digamma_(self) -> Tensor: + r""" + digamma_() -> Tensor + + In-place version of :meth:`~Tensor.digamma` + """ + + def dim(self) -> _int: + r""" + dim() -> int + + Returns the number of dimensions of :attr:`self` tensor. + """ + + def dist( + self, + other: Tensor, + p: Number | _complex | PySymType = 2, + ) -> Tensor: + r""" + dist(other, p=2) -> Tensor + + See :func:`torch.dist` + """ + + def div( + self, + other: Tensor | Number, + *, + rounding_mode: str | None = None, + ) -> Tensor: + r""" + div(value, *, rounding_mode=None) -> Tensor + + See :func:`torch.div` + """ + + def div_( + self, + other: Tensor | Number, + *, + rounding_mode: str | None = None, + ) -> Tensor: + r""" + div_(value, *, rounding_mode=None) -> Tensor + + In-place version of :meth:`~Tensor.div` + """ + + @overload + def divide(self, other: Tensor) -> Tensor: + r""" + divide(value, *, rounding_mode=None) -> Tensor + + See :func:`torch.divide` + """ + + @overload + def divide(self, other: Tensor, *, rounding_mode: str | None) -> Tensor: + r""" + divide(value, *, rounding_mode=None) -> Tensor + + See :func:`torch.divide` + """ + + @overload + def divide( + self, + other: Number | _complex | PySymType, + *, + rounding_mode: str | None, + ) -> Tensor: + r""" + divide(value, *, rounding_mode=None) -> Tensor + + See :func:`torch.divide` + """ + + @overload + def divide(self, other: Number | _complex | PySymType) -> Tensor: + r""" + divide(value, *, rounding_mode=None) -> Tensor + + See :func:`torch.divide` + """ + + @overload + def divide_(self, other: Tensor) -> Tensor: + r""" + divide_(value, *, rounding_mode=None) -> Tensor + + In-place version of :meth:`~Tensor.divide` + """ + + @overload + def divide_(self, other: Tensor, *, rounding_mode: str | None) -> Tensor: + r""" + divide_(value, *, rounding_mode=None) -> Tensor + + In-place version of :meth:`~Tensor.divide` + """ + + @overload + def divide_( + self, + other: Number | _complex | PySymType, + *, + rounding_mode: str | None, + ) -> Tensor: + r""" + divide_(value, *, rounding_mode=None) -> Tensor + + In-place version of :meth:`~Tensor.divide` + """ + + @overload + def divide_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + divide_(value, *, rounding_mode=None) -> Tensor + + In-place version of :meth:`~Tensor.divide` + """ + + def dot(self, tensor: Tensor) -> Tensor: + r""" + dot(other) -> Tensor + + See :func:`torch.dot` + """ + + def double(self) -> Tensor: + r""" + double(memory_format=torch.preserve_format) -> Tensor + + ``self.double()`` is equivalent to ``self.to(torch.float64)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + @overload + def dsplit(self, sections: _int) -> tuple[Tensor, ...]: + r""" + dsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.dsplit` + """ + + @overload + def dsplit(self, indices: _size) -> tuple[Tensor, ...]: + r""" + dsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.dsplit` + """ + + @overload + def dsplit(self, *indices: _int) -> tuple[Tensor, ...]: + r""" + dsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.dsplit` + """ + + def element_size(self) -> _int: + r""" + element_size() -> int + + Returns the size in bytes of an individual element. + + Example:: + + >>> torch.tensor([]).element_size() + 4 + >>> torch.tensor([], dtype=torch.uint8).element_size() + 1 + """ + + @overload + def eq(self, other: Tensor) -> Tensor: + r""" + eq(other) -> Tensor + + See :func:`torch.eq` + """ + + @overload + def eq(self, other: Number | _complex | PySymType) -> Tensor: + r""" + eq(other) -> Tensor + + See :func:`torch.eq` + """ + + @overload + def eq_(self, other: Tensor) -> Tensor: + r""" + eq_(other) -> Tensor + + In-place version of :meth:`~Tensor.eq` + """ + + @overload + def eq_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + eq_(other) -> Tensor + + In-place version of :meth:`~Tensor.eq` + """ + + def equal(self, other: Tensor) -> _bool: + r""" + equal(other) -> bool + + See :func:`torch.equal` + """ + + def erf(self) -> Tensor: + r""" + erf() -> Tensor + + See :func:`torch.erf` + """ + + def erf_(self) -> Tensor: + r""" + erf_() -> Tensor + + In-place version of :meth:`~Tensor.erf` + """ + + def erfc(self) -> Tensor: + r""" + erfc() -> Tensor + + See :func:`torch.erfc` + """ + + def erfc_(self) -> Tensor: + r""" + erfc_() -> Tensor + + In-place version of :meth:`~Tensor.erfc` + """ + + def erfinv(self) -> Tensor: + r""" + erfinv() -> Tensor + + See :func:`torch.erfinv` + """ + + def erfinv_(self) -> Tensor: + r""" + erfinv_() -> Tensor + + In-place version of :meth:`~Tensor.erfinv` + """ + + def exp(self) -> Tensor: + r""" + exp() -> Tensor + + See :func:`torch.exp` + """ + + def exp2(self) -> Tensor: + r""" + exp2() -> Tensor + + See :func:`torch.exp2` + """ + + def exp2_(self) -> Tensor: + r""" + exp2_() -> Tensor + + In-place version of :meth:`~Tensor.exp2` + """ + + def exp_(self) -> Tensor: + r""" + exp_() -> Tensor + + In-place version of :meth:`~Tensor.exp` + """ + + @overload + def expand( + self, + size: Sequence[_int | SymInt], + *, + implicit: _bool = False, + ) -> Tensor: + r""" + expand(*size) -> 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. + + .. note:: + + Operations on an expanded view may still allocate memory if they need to + materialize the expanded values. For example, changing dtype after + :meth:`expand` can allocate memory for the full expanded shape. + + Args: + *size (torch.Size or int...): the desired expanded size + + .. warning:: + + More than one element of an expanded tensor may refer to a single + memory location. As a result, in-place operations (especially ones that + are vectorized) may result in incorrect behavior. If you need to write + to the tensors, please clone them first. + + Example:: + + >>> x = torch.tensor([[1], [2], [3]]) + >>> x.size() + torch.Size([3, 1]) + >>> x.expand(3, 4) + tensor([[ 1, 1, 1, 1], + [ 2, 2, 2, 2], + [ 3, 3, 3, 3]]) + >>> x.expand(-1, 4) # -1 means not changing the size of that dimension + tensor([[ 1, 1, 1, 1], + [ 2, 2, 2, 2], + [ 3, 3, 3, 3]]) + """ + + @overload + def expand(self, *size: _int | SymInt, implicit: _bool = False) -> Tensor: + r""" + expand(*size) -> 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. + + .. note:: + + Operations on an expanded view may still allocate memory if they need to + materialize the expanded values. For example, changing dtype after + :meth:`expand` can allocate memory for the full expanded shape. + + Args: + *size (torch.Size or int...): the desired expanded size + + .. warning:: + + More than one element of an expanded tensor may refer to a single + memory location. As a result, in-place operations (especially ones that + are vectorized) may result in incorrect behavior. If you need to write + to the tensors, please clone them first. + + Example:: + + >>> x = torch.tensor([[1], [2], [3]]) + >>> x.size() + torch.Size([3, 1]) + >>> x.expand(3, 4) + tensor([[ 1, 1, 1, 1], + [ 2, 2, 2, 2], + [ 3, 3, 3, 3]]) + >>> x.expand(-1, 4) # -1 means not changing the size of that dimension + tensor([[ 1, 1, 1, 1], + [ 2, 2, 2, 2], + [ 3, 3, 3, 3]]) + """ + + def expand_as(self, other: Tensor) -> Tensor: + r""" + expand_as(other) -> Tensor + + Expand this tensor to the same size as :attr:`other`. + ``self.expand_as(other)`` is equivalent to ``self.expand(other.size())``. + + Please see :meth:`~Tensor.expand` for more information about ``expand``. + + Args: + other (:class:`torch.Tensor`): The result tensor has the same size + as :attr:`other`. + """ + + def expm1(self) -> Tensor: + r""" + expm1() -> Tensor + + See :func:`torch.expm1` + """ + + def expm1_(self) -> Tensor: + r""" + expm1_() -> Tensor + + In-place version of :meth:`~Tensor.expm1` + """ + + def exponential_( + self, + lambd: _float = 1, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + exponential_(lambd=1, *, generator=None) -> Tensor + + Fills :attr:`self` tensor with elements drawn from the PDF (probability density function): + + .. math:: + + f(x) = \lambda e^{-\lambda x}, x > 0 + + .. note:: + In probability theory, exponential distribution is supported on interval [0, :math:`\inf`) (i.e., :math:`x >= 0`) + implying that zero can be sampled from the exponential distribution. + However, :func:`torch.Tensor.exponential_` does not sample zero, + which means that its actual support is the interval (0, :math:`\inf`). + + Note that :func:`torch.distributions.exponential.Exponential` is supported on the interval [0, :math:`\inf`) and can sample zero. + """ + + @overload + def fill_(self, value: Tensor) -> Tensor: + r""" + fill_(value) -> Tensor + + Fills :attr:`self` tensor with the specified value. + """ + + @overload + def fill_(self, value: Number | _complex | PySymType) -> Tensor: + r""" + fill_(value) -> Tensor + + Fills :attr:`self` tensor with the specified value. + """ + + def fill_diagonal_( + self, + fill_value: Number | _complex | PySymType, + wrap: _bool = False, + ) -> Tensor: + r""" + fill_diagonal_(fill_value, wrap=False) -> Tensor + + Fill the main diagonal of a tensor that has at least 2-dimensions. + When dims>2, all dimensions of input must be of equal length. + This function modifies the input tensor in-place, and returns the input tensor. + + Arguments: + fill_value (Scalar): the fill value + wrap (bool, optional): the diagonal 'wrapped' after N columns for tall matrices. Default: ``False`` + + Example:: + + >>> a = torch.zeros(3, 3) + >>> a.fill_diagonal_(5) + tensor([[5., 0., 0.], + [0., 5., 0.], + [0., 0., 5.]]) + >>> b = torch.zeros(7, 3) + >>> b.fill_diagonal_(5) + tensor([[5., 0., 0.], + [0., 5., 0.], + [0., 0., 5.], + [0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]) + >>> c = torch.zeros(7, 3) + >>> c.fill_diagonal_(5, wrap=True) + tensor([[5., 0., 0.], + [0., 5., 0.], + [0., 0., 5.], + [0., 0., 0.], + [5., 0., 0.], + [0., 5., 0.], + [0., 0., 5.]]) + """ + + def fix(self) -> Tensor: + r""" + fix() -> Tensor + + See :func:`torch.fix`. + """ + + def fix_(self) -> Tensor: + r""" + fix_() -> Tensor + + In-place version of :meth:`~Tensor.fix` + """ + + def flatten(self, start_dim: _int = 0, end_dim: _int = -1) -> Tensor: + r""" + flatten(start_dim=0, end_dim=-1) -> Tensor + + See :func:`torch.flatten` + """ + + @overload + def flip(self, dims: _size) -> Tensor: + r""" + flip(dims) -> Tensor + + See :func:`torch.flip` + """ + + @overload + def flip(self, *dims: _int) -> Tensor: + r""" + flip(dims) -> Tensor + + See :func:`torch.flip` + """ + + def fliplr(self) -> Tensor: + r""" + fliplr() -> Tensor + + See :func:`torch.fliplr` + """ + + def flipud(self) -> Tensor: + r""" + flipud() -> Tensor + + See :func:`torch.flipud` + """ + + def float(self) -> Tensor: + r""" + float(memory_format=torch.preserve_format) -> Tensor + + ``self.float()`` is equivalent to ``self.to(torch.float32)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + @overload + def float_power(self, exponent: Tensor) -> Tensor: + r""" + float_power(exponent) -> Tensor + + See :func:`torch.float_power` + """ + + @overload + def float_power(self, exponent: Number | _complex | PySymType) -> Tensor: + r""" + float_power(exponent) -> Tensor + + See :func:`torch.float_power` + """ + + @overload + def float_power_(self, exponent: Tensor) -> Tensor: + r""" + float_power_(exponent) -> Tensor + + In-place version of :meth:`~Tensor.float_power` + """ + + @overload + def float_power_(self, exponent: Number | _complex | PySymType) -> Tensor: + r""" + float_power_(exponent) -> Tensor + + In-place version of :meth:`~Tensor.float_power` + """ + + def floor(self) -> Tensor: + r""" + floor() -> Tensor + + See :func:`torch.floor` + """ + + def floor_(self) -> Tensor: + r""" + floor_() -> Tensor + + In-place version of :meth:`~Tensor.floor` + """ + + def floor_divide( + self, + other: Tensor | Number | torch.SymInt | torch.SymFloat, + *, + out: Tensor | None = None, + ) -> Tensor: + r""" + floor_divide(value) -> Tensor + + See :func:`torch.floor_divide` + """ + + def floor_divide_( + self, + other: Tensor | Number | torch.SymInt | torch.SymFloat, + ) -> Tensor: + r""" + floor_divide_(value) -> Tensor + + In-place version of :meth:`~Tensor.floor_divide` + """ + + def fmax(self, other: Tensor) -> Tensor: + r""" + fmax(other) -> Tensor + + See :func:`torch.fmax` + """ + + def fmin(self, other: Tensor) -> Tensor: + r""" + fmin(other) -> Tensor + + See :func:`torch.fmin` + """ + + @overload + def fmod(self, other: Tensor) -> Tensor: + r""" + fmod(divisor) -> Tensor + + See :func:`torch.fmod` + """ + + @overload + def fmod(self, other: Number | _complex | PySymType) -> Tensor: + r""" + fmod(divisor) -> Tensor + + See :func:`torch.fmod` + """ + + @overload + def fmod_(self, other: Tensor) -> Tensor: + r""" + fmod_(divisor) -> Tensor + + In-place version of :meth:`~Tensor.fmod` + """ + + @overload + def fmod_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + fmod_(divisor) -> Tensor + + In-place version of :meth:`~Tensor.fmod` + """ + + def frac(self) -> Tensor: + r""" + frac() -> Tensor + + See :func:`torch.frac` + """ + + def frac_(self) -> Tensor: + r""" + frac_() -> Tensor + + In-place version of :meth:`~Tensor.frac` + """ + + def frexp(self) -> torch.return_types.frexp: + r""" + frexp(input) -> (Tensor mantissa, Tensor exponent) + + See :func:`torch.frexp` + """ + + def gather( + self, + dim: _int, + index: Tensor, + *, + sparse_grad: _bool = False, + ) -> Tensor: + r""" + gather(dim, index) -> Tensor + + See :func:`torch.gather` + """ + + def gcd(self, other: Tensor) -> Tensor: + r""" + gcd(other) -> Tensor + + See :func:`torch.gcd` + """ + + def gcd_(self, other: Tensor) -> Tensor: + r""" + gcd_(other) -> Tensor + + In-place version of :meth:`~Tensor.gcd` + """ + + @overload + def ge(self, other: Tensor) -> Tensor: + r""" + ge(other) -> Tensor + + See :func:`torch.ge`. + """ + + @overload + def ge(self, other: Number | _complex | PySymType) -> Tensor: + r""" + ge(other) -> Tensor + + See :func:`torch.ge`. + """ + + @overload + def ge_(self, other: Tensor) -> Tensor: + r""" + ge_(other) -> Tensor + + In-place version of :meth:`~Tensor.ge`. + """ + + @overload + def ge_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + ge_(other) -> Tensor + + In-place version of :meth:`~Tensor.ge`. + """ + + def geometric_( + self, + p: _float, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + geometric_(p, *, generator=None) -> Tensor + + Fills :attr:`self` tensor with elements drawn from the geometric distribution: + + .. math:: + + P(X=k) = (1 - p)^{k - 1} p, k = 1, 2, ... + + .. note:: + :func:`torch.Tensor.geometric_` `k`-th trial is the first success hence draws samples in :math:`\{1, 2, \ldots\}`, whereas + :func:`torch.distributions.geometric.Geometric` :math:`(k+1)`-th trial is the first success + hence draws samples in :math:`\{0, 1, \ldots\}`. + """ + + def geqrf(self) -> torch.return_types.geqrf: + r""" + geqrf() -> (Tensor, Tensor) + + See :func:`torch.geqrf` + """ + + def ger(self, vec2: Tensor) -> Tensor: + r""" + ger(vec2) -> Tensor + + See :func:`torch.ger` + """ + + def get_device(self) -> _int: + r""" + get_device() -> Device ordinal (Integer) + + For CUDA tensors, this function returns the device ordinal of the GPU on which the tensor resides. + For CPU tensors, this function returns `-1`. + + Example:: + + >>> x = torch.randn(3, 4, 5, device='cuda:0') + >>> x.get_device() + 0 + >>> x.cpu().get_device() + -1 + """ + + @overload + def greater(self, other: Tensor) -> Tensor: + r""" + greater(other) -> Tensor + + See :func:`torch.greater`. + """ + + @overload + def greater(self, other: Number | _complex | PySymType) -> Tensor: + r""" + greater(other) -> Tensor + + See :func:`torch.greater`. + """ + + @overload + def greater_(self, other: Tensor) -> Tensor: + r""" + greater_(other) -> Tensor + + In-place version of :meth:`~Tensor.greater`. + """ + + @overload + def greater_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + greater_(other) -> Tensor + + In-place version of :meth:`~Tensor.greater`. + """ + + @overload + def greater_equal(self, other: Tensor) -> Tensor: + r""" + greater_equal(other) -> Tensor + + See :func:`torch.greater_equal`. + """ + + @overload + def greater_equal(self, other: Number | _complex | PySymType) -> Tensor: + r""" + greater_equal(other) -> Tensor + + See :func:`torch.greater_equal`. + """ + + @overload + def greater_equal_(self, other: Tensor) -> Tensor: + r""" + greater_equal_(other) -> Tensor + + In-place version of :meth:`~Tensor.greater_equal`. + """ + + @overload + def greater_equal_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + greater_equal_(other) -> Tensor + + In-place version of :meth:`~Tensor.greater_equal`. + """ + + @overload + def gt(self, other: Tensor) -> Tensor: + r""" + gt(other) -> Tensor + + See :func:`torch.gt`. + """ + + @overload + def gt(self, other: Number | _complex | PySymType) -> Tensor: + r""" + gt(other) -> Tensor + + See :func:`torch.gt`. + """ + + @overload + def gt_(self, other: Tensor) -> Tensor: + r""" + gt_(other) -> Tensor + + In-place version of :meth:`~Tensor.gt`. + """ + + @overload + def gt_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + gt_(other) -> Tensor + + In-place version of :meth:`~Tensor.gt`. + """ + + def half(self) -> Tensor: + r""" + half(memory_format=torch.preserve_format) -> Tensor + + ``self.half()`` is equivalent to ``self.to(torch.float16)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def hardshrink(self, lambd: Number | _complex | PySymType = 0.5) -> Tensor: + r""" + hardshrink(lambd=0.5) -> Tensor + + See :func:`torch.nn.functional.hardshrink` + """ + + @overload + def hash_tensor( + self, + dim: _int | _size = (), + *, + keepdim: _bool = False, + mode: _int = 0, + ) -> Tensor: ... + @overload + def hash_tensor( + self, + *dim: _int, + keepdim: _bool = False, + mode: _int = 0, + ) -> Tensor: ... + def heaviside(self, values: Tensor) -> Tensor: + r""" + heaviside(values) -> Tensor + + See :func:`torch.heaviside` + """ + + def heaviside_(self, values: Tensor) -> Tensor: + r""" + heaviside_(values) -> Tensor + + In-place version of :meth:`~Tensor.heaviside` + """ + + def histc( + self, + bins: _int = 100, + min: Number | _complex | PySymType = 0, + max: Number | _complex | PySymType = 0, + ) -> Tensor: + r""" + histc(bins=100, min=0, max=0) -> Tensor + + See :func:`torch.histc` + """ + + @overload + def histogram( + self, + bins: Tensor, + *, + weight: Tensor | None = None, + density: _bool = False, + ) -> torch.return_types.histogram: + r""" + histogram(input, bins, *, range=None, weight=None, density=False) -> (Tensor, Tensor) + + See :func:`torch.histogram` + """ + + @overload + def histogram( + self, + bins: _int = 100, + *, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, + ) -> torch.return_types.histogram: + r""" + histogram(input, bins, *, range=None, weight=None, density=False) -> (Tensor, Tensor) + + See :func:`torch.histogram` + """ + + @overload + def hsplit(self, sections: _int) -> tuple[Tensor, ...]: + r""" + hsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.hsplit` + """ + + @overload + def hsplit(self, indices: _size) -> tuple[Tensor, ...]: + r""" + hsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.hsplit` + """ + + @overload + def hsplit(self, *indices: _int) -> tuple[Tensor, ...]: + r""" + hsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.hsplit` + """ + + def hypot(self, other: Tensor) -> Tensor: + r""" + hypot(other) -> Tensor + + See :func:`torch.hypot` + """ + + def hypot_(self, other: Tensor) -> Tensor: + r""" + hypot_(other) -> Tensor + + In-place version of :meth:`~Tensor.hypot` + """ + + def i0(self) -> Tensor: + r""" + i0() -> Tensor + + See :func:`torch.i0` + """ + + def i0_(self) -> Tensor: + r""" + i0_() -> Tensor + + In-place version of :meth:`~Tensor.i0` + """ + + def igamma(self, other: Tensor) -> Tensor: + r""" + igamma(other) -> Tensor + + See :func:`torch.igamma` + """ + + def igamma_(self, other: Tensor) -> Tensor: + r""" + igamma_(other) -> Tensor + + In-place version of :meth:`~Tensor.igamma` + """ + + def igammac(self, other: Tensor) -> Tensor: + r""" + igammac(other) -> Tensor + See :func:`torch.igammac` + """ + + def igammac_(self, other: Tensor) -> Tensor: + r""" + igammac_(other) -> Tensor + In-place version of :meth:`~Tensor.igammac` + """ + + def index_add( + self, + dim: _int, + index: Tensor, + source: Tensor, + *, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + index_add(dim, index, source, *, alpha=1) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.index_add_`. + """ + + def index_add_( + self, + dim: _int, + index: Tensor, + source: Tensor, + *, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + index_add_(dim, index, source, *, alpha=1) -> Tensor + + Accumulate the elements of :attr:`alpha` times ``source`` into the :attr:`self` + tensor by adding to the indices in the order given in :attr:`index`. For example, + if ``dim == 0``, ``index[i] == j``, and ``alpha=-1``, then the ``i``\ th row of + ``source`` is subtracted from the ``j``\ th row of :attr:`self`. + + The :attr:`dim`\ th dimension of ``source`` must have the same size as the + length of :attr:`index` (which must be a vector), and all other dimensions must + match :attr:`self`, or an error will be raised. + + For a 3-D tensor the output is given as:: + + self[index[i], :, :] += alpha * src[i, :, :] # if dim == 0 + self[:, index[i], :] += alpha * src[:, i, :] # if dim == 1 + self[:, :, index[i]] += alpha * src[:, :, i] # if dim == 2 + + Note: + This operation may behave nondeterministically when given tensors on a CUDA device. See :doc:`/notes/randomness` for more information. + + Args: + dim (int): dimension along which to index + index (Tensor): indices of ``source`` to select from, + should have dtype either `torch.int64` or `torch.int32` + source (Tensor): the tensor containing values to add + + Keyword args: + alpha (Number): the scalar multiplier for ``source`` + + Example:: + + >>> x = torch.ones(5, 3) + >>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) + >>> index = torch.tensor([0, 4, 2]) + >>> x.index_add_(0, index, t) + tensor([[ 2., 3., 4.], + [ 1., 1., 1.], + [ 8., 9., 10.], + [ 1., 1., 1.], + [ 5., 6., 7.]]) + >>> x.index_add_(0, index, t, alpha=-1) + tensor([[ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.], + [ 1., 1., 1.]]) + """ + + def index_copy(self, dim: _int, index: Tensor, source: Tensor) -> Tensor: + r""" + index_copy(dim, index, tensor2) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.index_copy_`. + """ + + def index_copy_(self, dim: _int, index: Tensor, source: Tensor) -> Tensor: + r""" + index_copy_(dim, index, tensor) -> Tensor + + Copies the elements of :attr:`tensor` into the :attr:`self` tensor by selecting + the indices in the order given in :attr:`index`. For example, if ``dim == 0`` + and ``index[i] == j``, then the ``i``\ th row of :attr:`tensor` is copied to the + ``j``\ th row of :attr:`self`. + + The :attr:`dim`\ th dimension of :attr:`tensor` must have the same size as the + length of :attr:`index` (which must be a vector), and all other dimensions must + match :attr:`self`, or an error will be raised. + + .. note:: + If :attr:`index` contains duplicate entries, multiple elements from + :attr:`tensor` will be copied to the same index of :attr:`self`. The result + is nondeterministic since it depends on which copy occurs last. + + Args: + dim (int): dimension along which to index + index (LongTensor): indices of :attr:`tensor` to select from + tensor (Tensor): the tensor containing values to copy + + Example:: + + >>> x = torch.zeros(5, 3) + >>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) + >>> index = torch.tensor([0, 4, 2]) + >>> x.index_copy_(0, index, t) + tensor([[ 1., 2., 3.], + [ 0., 0., 0.], + [ 7., 8., 9.], + [ 0., 0., 0.], + [ 4., 5., 6.]]) + """ + + @overload + def index_fill(self, dim: _int, index: Tensor, value: Tensor) -> Tensor: + r""" + index_fill(dim, index, value) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.index_fill_`. + """ + + @overload + def index_fill( + self, + dim: _int, + index: Tensor, + value: Number | _complex | PySymType, + ) -> Tensor: + r""" + index_fill(dim, index, value) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.index_fill_`. + """ + + @overload + def index_fill_(self, dim: _int, index: Tensor, value: Tensor) -> Tensor: + r""" + index_fill_(dim, index, value) -> Tensor + + Fills the elements of the :attr:`self` tensor with value :attr:`value` by + selecting the indices in the order given in :attr:`index`. + + Args: + dim (int): dimension along which to index + index (LongTensor): indices of :attr:`self` tensor to fill in + value (float): the value to fill with + + Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) + >>> index = torch.tensor([0, 2]) + >>> x.index_fill_(1, index, -1) + tensor([[-1., 2., -1.], + [-1., 5., -1.], + [-1., 8., -1.]]) + """ + + @overload + def index_fill_( + self, + dim: _int, + index: Tensor, + value: Number | _complex | PySymType, + ) -> Tensor: + r""" + index_fill_(dim, index, value) -> Tensor + + Fills the elements of the :attr:`self` tensor with value :attr:`value` by + selecting the indices in the order given in :attr:`index`. + + Args: + dim (int): dimension along which to index + index (LongTensor): indices of :attr:`self` tensor to fill in + value (float): the value to fill with + + Example:: + + >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) + >>> index = torch.tensor([0, 2]) + >>> x.index_fill_(1, index, -1) + tensor([[-1., 2., -1.], + [-1., 5., -1.], + [-1., 8., -1.]]) + """ + + def index_put( + self, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, + values: Tensor, + accumulate: _bool = False, + ) -> Tensor: + r""" + index_put(indices, values, accumulate=False) -> Tensor + + Out-place version of :meth:`~Tensor.index_put_`. + """ + + def index_put_( + self, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, + values: Tensor, + accumulate: _bool = False, + ) -> Tensor: + r""" + index_put_(indices, values, accumulate=False) -> Tensor + + Puts values from the tensor :attr:`values` into the tensor :attr:`self` using + the indices specified in :attr:`indices` (which is a tuple of Tensors). The + expression ``tensor.index_put_(indices, values)`` is equivalent to + ``tensor[indices] = values``. Returns :attr:`self`. + + If :attr:`accumulate` is ``True``, the elements in :attr:`values` are added to + :attr:`self`. If accumulate is ``False``, the behavior is undefined if indices + contain duplicate elements. + + Args: + indices (tuple of LongTensor): tensors used to index into `self`. + values (Tensor): tensor of same dtype as `self`. + accumulate (bool): whether to accumulate into self + """ + + def index_reduce( + self, + dim: _int, + index: Tensor, + source: Tensor, + reduce: str, + *, + include_self: _bool = True, + ) -> Tensor: ... + def index_reduce_( + self, + dim: _int, + index: Tensor, + source: Tensor, + reduce: str, + *, + include_self: _bool = True, + ) -> Tensor: + r""" + index_reduce_(dim, index, source, reduce, *, include_self=True) -> Tensor + + Accumulate the elements of ``source`` into the :attr:`self` + tensor by accumulating to the indices in the order given in :attr:`index` + using the reduction given by the ``reduce`` argument. For example, if ``dim == 0``, + ``index[i] == j``, ``reduce == prod`` and ``include_self == True`` then the ``i``\ th + row of ``source`` is multiplied by the ``j``\ th row of :attr:`self`. If + :obj:`include_self="True"`, the values in the :attr:`self` tensor are included + in the reduction, otherwise, rows in the :attr:`self` tensor that are accumulated + to are treated as if they were filled with the reduction identities. + + The :attr:`dim`\ th dimension of ``source`` must have the same size as the + length of :attr:`index` (which must be a vector), and all other dimensions must + match :attr:`self`, or an error will be raised. + + For a 3-D tensor with :obj:`reduce="prod"` and :obj:`include_self=True` the + output is given as:: + + self[index[i], :, :] *= src[i, :, :] # if dim == 0 + self[:, index[i], :] *= src[:, i, :] # if dim == 1 + self[:, :, index[i]] *= src[:, :, i] # if dim == 2 + + Note: + This operation may behave nondeterministically when given tensors on a CUDA device. See :doc:`/notes/randomness` for more information. + + .. note:: + + This function only supports floating point tensors. + + .. warning:: + + This function is in beta and may change in the near future. + + Args: + dim (int): dimension along which to index + index (Tensor): indices of :attr:`self` to accumulate into, + 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.]]) + """ + + def index_select(self, dim: _int, index: Tensor) -> Tensor: + r""" + index_select(dim, index) -> Tensor + + See :func:`torch.index_select` + """ + + def indices(self) -> Tensor: + r""" + indices() -> Tensor + + Return the indices tensor of a :ref:`sparse COO tensor `. + + .. warning:: + Throws an error if :attr:`self` is not a sparse COO tensor. + + See also :meth:`Tensor.values`. + + .. note:: + This method can only be called on a coalesced sparse tensor. See + :meth:`Tensor.coalesce` for details. + """ + + def inner(self, other: Tensor) -> Tensor: + r""" + inner(other) -> Tensor + + See :func:`torch.inner`. + """ + + def int(self) -> Tensor: + r""" + int(memory_format=torch.preserve_format) -> Tensor + + ``self.int()`` is equivalent to ``self.to(torch.int32)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def int_repr(self) -> Tensor: + r""" + int_repr() -> Tensor + + Given a quantized Tensor, + ``self.int_repr()`` returns a CPU Tensor with uint8_t as data type that stores the + underlying uint8_t values of the given Tensor. + """ + + def inverse(self) -> Tensor: + r""" + inverse() -> Tensor + + See :func:`torch.inverse` + """ + + def is_coalesced(self) -> _bool: + r""" + is_coalesced() -> bool + + Returns ``True`` if :attr:`self` is a :ref:`sparse COO tensor + ` that is coalesced, ``False`` otherwise. + + .. warning:: + Throws an error if :attr:`self` is not a sparse COO tensor. + + See :meth:`coalesce` and :ref:`uncoalesced tensors `. + """ + + def is_complex(self) -> _bool: + r""" + is_complex() -> bool + + Returns True if the data type of :attr:`self` is a complex data type. + """ + + def is_conj(self) -> _bool: + r""" + is_conj() -> bool + + Returns True if the conjugate bit of :attr:`self` is set to true. + """ + + def is_contiguous( + self, + memory_format: torch.memory_format = torch.contiguous_format, + ) -> _bool: + r""" + is_contiguous(memory_format=torch.contiguous_format) -> bool + + Returns True if :attr:`self` tensor is contiguous in memory in the order specified + by memory format. + + Args: + memory_format (:class:`torch.memory_format`, optional): Specifies memory allocation + order. Default: ``torch.contiguous_format``. + """ + is_cpu: _bool + r"""Is ``True`` if the Tensor is stored on the CPU, ``False`` otherwise.""" + is_cuda: _bool + r"""Is ``True`` if the Tensor is stored on the GPU, ``False`` otherwise.""" + + def is_distributed(self) -> _bool: ... + def is_floating_point(self) -> _bool: + r""" + is_floating_point() -> bool + + Returns True if the data type of :attr:`self` is a floating point data type. + """ + + def is_inference(self) -> _bool: + r""" + is_inference() -> bool + + See :func:`torch.is_inference` + """ + is_ipu: _bool + r"""Is ``True`` if the Tensor is stored on the IPU, ``False`` otherwise.""" + is_leaf: _bool + r"""All Tensors that have :attr:`requires_grad` which is ``False`` will be leaf Tensors by convention. + + For Tensors that have :attr:`requires_grad` which is ``True``, they will be leaf Tensors if they were + created by the user. This means that they are not the result of an operation and so + :attr:`grad_fn` is None. + + Only leaf Tensors will have their :attr:`grad` populated during a call to :func:`backward`. + To get :attr:`grad` populated for non-leaf Tensors, you can use :func:`retain_grad`. + + Example:: + + >>> a = torch.rand(10, requires_grad=True) + >>> a.is_leaf + True + >>> b = torch.rand(10, requires_grad=True).cuda() + >>> b.is_leaf + False + # b was created by the operation that cast a cpu Tensor into a cuda Tensor + >>> c = torch.rand(10, requires_grad=True) + 2 + >>> c.is_leaf + False + # c was created by the addition operation + >>> d = torch.rand(10).cuda() + >>> d.is_leaf + True + # d does not require gradients and so has no operation creating it (that is tracked by the autograd engine) + >>> e = torch.rand(10).cuda().requires_grad_() + >>> e.is_leaf + True + # e requires gradients and has no operations creating it + >>> f = torch.rand(10, requires_grad=True, device="cuda") + >>> f.is_leaf + True + # f requires grad, has no operation creating it""" + is_maia: _bool + is_meta: _bool + r"""Is ``True`` if the Tensor is a meta tensor, ``False`` otherwise. Meta tensors + are like normal tensors, but they carry no data.""" + is_mkldnn: _bool + is_mps: _bool + r"""Is ``True`` if the Tensor is stored on the MPS device, ``False`` otherwise.""" + is_mtia: _bool + def is_neg(self) -> _bool: + r""" + is_neg() -> bool + + Returns True if the negative bit of :attr:`self` is set to true. + """ + is_nested: _bool + def is_nonzero(self) -> _bool: ... + def is_pinned(self, device: DeviceLikeType | None = None) -> _bool: + r""" + Returns true if this tensor resides in pinned memory. + By default, the device pinned memory on will be the current :ref:`accelerator`. + """ + is_quantized: _bool + r"""Is ``True`` if the Tensor is quantized, ``False`` otherwise.""" + + def is_same_size(self, other: Tensor) -> _bool: ... + def is_set_to(self, tensor: Tensor) -> _bool: + r""" + is_set_to(tensor) -> bool + + Returns True if both tensors are pointing to the exact same memory (same + storage, offset, size and stride). + """ + + def is_signed(self) -> _bool: + r""" + is_signed() -> bool + + Returns True if the data type of :attr:`self` is a signed data type. + """ + is_sparse: _bool + r"""Is ``True`` if the Tensor uses sparse COO storage layout, ``False`` otherwise.""" + is_sparse_csr: _bool + r"""Is ``True`` if the Tensor uses sparse CSR storage layout, ``False`` otherwise.""" + is_vulkan: _bool + is_xpu: _bool + r"""Is ``True`` if the Tensor is stored on the XPU, ``False`` otherwise.""" + + def isclose( + self, + other: Tensor, + rtol: _float = 1e-05, + atol: _float = 1e-08, + equal_nan: _bool = False, + ) -> Tensor: + r""" + isclose(other, rtol=1e-05, atol=1e-08, equal_nan=False) -> Tensor + + See :func:`torch.isclose` + """ + + def isfinite(self) -> Tensor: + r""" + isfinite() -> Tensor + + See :func:`torch.isfinite` + """ + + def isinf(self) -> Tensor: + r""" + isinf() -> Tensor + + See :func:`torch.isinf` + """ + + def isnan(self) -> Tensor: + r""" + isnan() -> Tensor + + See :func:`torch.isnan` + """ + + def isneginf(self) -> Tensor: + r""" + isneginf() -> Tensor + + See :func:`torch.isneginf` + """ + + def isposinf(self) -> Tensor: + r""" + isposinf() -> Tensor + + See :func:`torch.isposinf` + """ + + def isreal(self) -> Tensor: + r""" + isreal() -> Tensor + + See :func:`torch.isreal` + """ + + def istft( + self, + n_fft: _int, + hop_length: _int | None = None, + win_length: _int | None = None, + window: Tensor | None = None, + center: _bool = True, + normalized: _bool = False, + onesided: _bool | None = None, + length: _int | None = None, + return_complex: _bool = False, + ) -> Tensor: + r""" + istft(n_fft, hop_length=None, win_length=None, window=None, + center=True, normalized=False, onesided=True, length=None) -> Tensor + + See :func:`torch.istft` + """ + + def item(self) -> Number: + r""" + item() -> number + + Returns the value of this tensor as a standard Python number. This only works + for tensors with one element. For other cases, see :meth:`~Tensor.tolist`. + + This operation is not differentiable. + + Example:: + + >>> x = torch.tensor([1.0]) + >>> x.item() + 1.0 + """ + + def kron(self, other: Tensor) -> Tensor: + r""" + kron(other) -> Tensor + + See :func:`torch.kron` + """ + + def kthvalue( + self, + k: _int | SymInt, + dim: _int = -1, + keepdim: _bool = False, + ) -> torch.return_types.kthvalue: + r""" + kthvalue(k, dim=None, keepdim=False) -> (Tensor, LongTensor) + + See :func:`torch.kthvalue` + """ + + def lcm(self, other: Tensor) -> Tensor: + r""" + lcm(other) -> Tensor + + See :func:`torch.lcm` + """ + + def lcm_(self, other: Tensor) -> Tensor: + r""" + lcm_(other) -> Tensor + + In-place version of :meth:`~Tensor.lcm` + """ + + def ldexp(self, other: Tensor) -> Tensor: + r""" + ldexp(other) -> Tensor + + See :func:`torch.ldexp` + """ + + def ldexp_(self, other: Tensor) -> Tensor: + r""" + ldexp_(other) -> Tensor + + In-place version of :meth:`~Tensor.ldexp` + """ + + @overload + def le(self, other: Tensor) -> Tensor: + r""" + le(other) -> Tensor + + See :func:`torch.le`. + """ + + @overload + def le(self, other: Number | _complex | PySymType) -> Tensor: + r""" + le(other) -> Tensor + + See :func:`torch.le`. + """ + + @overload + def le_(self, other: Tensor) -> Tensor: + r""" + le_(other) -> Tensor + + In-place version of :meth:`~Tensor.le`. + """ + + @overload + def le_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + le_(other) -> Tensor + + In-place version of :meth:`~Tensor.le`. + """ + + @overload + def lerp(self, end: Tensor, weight: Tensor) -> Tensor: + r""" + lerp(end, weight) -> Tensor + + See :func:`torch.lerp` + """ + + @overload + def lerp( + self, + end: Tensor, + weight: Number | _complex | PySymType, + ) -> Tensor: + r""" + lerp(end, weight) -> Tensor + + See :func:`torch.lerp` + """ + + @overload + def lerp_(self, end: Tensor, weight: Tensor) -> Tensor: + r""" + lerp_(end, weight) -> Tensor + + In-place version of :meth:`~Tensor.lerp` + """ + + @overload + def lerp_( + self, + end: Tensor, + weight: Number | _complex | PySymType, + ) -> Tensor: + r""" + lerp_(end, weight) -> Tensor + + In-place version of :meth:`~Tensor.lerp` + """ + + @overload + def less(self, other: Tensor) -> Tensor: + r""" + lt(other) -> Tensor + + See :func:`torch.less`. + """ + + @overload + def less(self, other: Number | _complex | PySymType) -> Tensor: + r""" + lt(other) -> Tensor + + See :func:`torch.less`. + """ + + @overload + def less_(self, other: Tensor) -> Tensor: + r""" + less_(other) -> Tensor + + In-place version of :meth:`~Tensor.less`. + """ + + @overload + def less_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + less_(other) -> Tensor + + In-place version of :meth:`~Tensor.less`. + """ + + @overload + def less_equal(self, other: Tensor) -> Tensor: + r""" + less_equal(other) -> Tensor + + See :func:`torch.less_equal`. + """ + + @overload + def less_equal(self, other: Number | _complex | PySymType) -> Tensor: + r""" + less_equal(other) -> Tensor + + See :func:`torch.less_equal`. + """ + + @overload + def less_equal_(self, other: Tensor) -> Tensor: + r""" + less_equal_(other) -> Tensor + + In-place version of :meth:`~Tensor.less_equal`. + """ + + @overload + def less_equal_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + less_equal_(other) -> Tensor + + In-place version of :meth:`~Tensor.less_equal`. + """ + + def lgamma(self) -> Tensor: + r""" + lgamma() -> Tensor + + See :func:`torch.lgamma` + """ + + def lgamma_(self) -> Tensor: + r""" + lgamma_() -> Tensor + + In-place version of :meth:`~Tensor.lgamma` + """ + + def log(self) -> Tensor: + r""" + log() -> Tensor + + See :func:`torch.log` + """ + + def log10(self) -> Tensor: + r""" + log10() -> Tensor + + See :func:`torch.log10` + """ + + def log10_(self) -> Tensor: + r""" + log10_() -> Tensor + + In-place version of :meth:`~Tensor.log10` + """ + + def log1p(self) -> Tensor: + r""" + log1p() -> Tensor + + See :func:`torch.log1p` + """ + + def log1p_(self) -> Tensor: + r""" + log1p_() -> Tensor + + In-place version of :meth:`~Tensor.log1p` + """ + + def log2(self) -> Tensor: + r""" + log2() -> Tensor + + See :func:`torch.log2` + """ + + def log2_(self) -> Tensor: + r""" + log2_() -> Tensor + + In-place version of :meth:`~Tensor.log2` + """ + + def log_(self) -> Tensor: + r""" + log_() -> Tensor + + In-place version of :meth:`~Tensor.log` + """ + + def log_normal_( + self, + mean: _float = 1, + std: _float = 2, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + log_normal_(mean=1, std=2, *, generator=None) + + Fills :attr:`self` tensor with numbers samples from the log-normal distribution + parameterized by the given mean :math:`\mu` and standard deviation + :math:`\sigma`. Note that :attr:`mean` and :attr:`std` are the mean and + standard deviation of the underlying normal distribution, and not of the + returned distribution: + + .. math:: + + f(x) = \dfrac{1}{x \sigma \sqrt{2\pi}}\ e^{-\frac{(\ln x - \mu)^2}{2\sigma^2}} + """ + + def log_softmax(self, dim: _int, dtype: _dtype | None = None) -> Tensor: ... + def logaddexp(self, other: Tensor) -> Tensor: + r""" + logaddexp(other) -> Tensor + + See :func:`torch.logaddexp` + """ + + def logaddexp2(self, other: Tensor) -> Tensor: + r""" + logaddexp2(other) -> Tensor + + See :func:`torch.logaddexp2` + """ + + def logcumsumexp(self, dim: _int) -> Tensor: + r""" + logcumsumexp(dim) -> Tensor + + See :func:`torch.logcumsumexp` + """ + + def logdet(self) -> Tensor: + r""" + logdet() -> Tensor + + See :func:`torch.logdet` + """ + + def logical_and(self, other: Tensor) -> Tensor: + r""" + logical_and() -> Tensor + + See :func:`torch.logical_and` + """ + + def logical_and_(self, other: Tensor) -> Tensor: + r""" + logical_and_() -> Tensor + + In-place version of :meth:`~Tensor.logical_and` + """ + + def logical_not(self) -> Tensor: + r""" + logical_not() -> Tensor + + See :func:`torch.logical_not` + """ + + def logical_not_(self) -> Tensor: + r""" + logical_not_() -> Tensor + + In-place version of :meth:`~Tensor.logical_not` + """ + + def logical_or(self, other: Tensor) -> Tensor: + r""" + logical_or() -> Tensor + + See :func:`torch.logical_or` + """ + + def logical_or_(self, other: Tensor) -> Tensor: + r""" + logical_or_() -> Tensor + + In-place version of :meth:`~Tensor.logical_or` + """ + + def logical_xor(self, other: Tensor) -> Tensor: + r""" + logical_xor() -> Tensor + + See :func:`torch.logical_xor` + """ + + def logical_xor_(self, other: Tensor) -> Tensor: + r""" + logical_xor_() -> Tensor + + In-place version of :meth:`~Tensor.logical_xor` + """ + + def logit(self, eps: _float | None = None) -> Tensor: + r""" + logit() -> Tensor + + See :func:`torch.logit` + """ + + def logit_(self, eps: _float | None = None) -> Tensor: + r""" + logit_() -> Tensor + + In-place version of :meth:`~Tensor.logit` + """ + + def logsumexp(self, dim: _int | _size, keepdim: _bool = False) -> Tensor: + r""" + logsumexp(dim, keepdim=False) -> Tensor + + See :func:`torch.logsumexp` + """ + + def long(self) -> Tensor: + r""" + long(memory_format=torch.preserve_format) -> Tensor + + ``self.long()`` is equivalent to ``self.to(torch.int64)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + @overload + def lt(self, other: Tensor) -> Tensor: + r""" + lt(other) -> Tensor + + See :func:`torch.lt`. + """ + + @overload + def lt(self, other: Number | _complex | PySymType) -> Tensor: + r""" + lt(other) -> Tensor + + See :func:`torch.lt`. + """ + + @overload + def lt_(self, other: Tensor) -> Tensor: + r""" + lt_(other) -> Tensor + + In-place version of :meth:`~Tensor.lt`. + """ + + @overload + def lt_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + lt_(other) -> Tensor + + In-place version of :meth:`~Tensor.lt`. + """ + + def lu_solve(self, LU_data: Tensor, LU_pivots: Tensor) -> Tensor: + r""" + lu_solve(LU_data, LU_pivots) -> Tensor + + See :func:`torch.lu_solve` + """ + + def map2_(self, x: Tensor, y: Tensor, callable: Callable) -> Tensor: ... + def map_(self, other: Tensor, callable: Callable) -> Tensor: + r""" + map_(tensor, callable) + + Applies :attr:`callable` for each element in :attr:`self` tensor and the given + :attr:`tensor` and stores the results in :attr:`self` tensor. :attr:`self` tensor and + the given :attr:`tensor` must be :ref:`broadcastable `. + + The :attr:`callable` should have the signature:: + + def callable(a, b) -> number + """ + + @overload + def masked_fill(self, mask: Tensor, value: Tensor) -> Tensor: + r""" + masked_fill(mask, value) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.masked_fill_` + """ + + @overload + def masked_fill( + self, + mask: Tensor, + value: Number | _complex | PySymType, + ) -> Tensor: + r""" + masked_fill(mask, value) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.masked_fill_` + """ + + @overload + def masked_fill_(self, mask: Tensor, value: Tensor) -> Tensor: + r""" + masked_fill_(mask, value) + + Fills elements of :attr:`self` tensor with :attr:`value` where :attr:`mask` is + True. The shape of :attr:`mask` must be + :ref:`broadcastable ` with the shape of the underlying + tensor. + + Args: + mask (BoolTensor): the boolean mask + value (float): the value to fill in with + """ + + @overload + def masked_fill_( + self, + mask: Tensor, + value: Number | _complex | PySymType, + ) -> Tensor: + r""" + masked_fill_(mask, value) + + Fills elements of :attr:`self` tensor with :attr:`value` where :attr:`mask` is + True. The shape of :attr:`mask` must be + :ref:`broadcastable ` with the shape of the underlying + tensor. + + Args: + mask (BoolTensor): the boolean mask + value (float): the value to fill in with + """ + + def masked_scatter(self, mask: Tensor, source: Tensor) -> Tensor: + r""" + masked_scatter(mask, tensor) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.masked_scatter_` + + .. note:: + + The inputs :attr:`self` and :attr:`mask` + :ref:`broadcast `. + + Example: + + >>> self = torch.tensor([0, 0, 0, 0, 0]) + >>> mask = torch.tensor( + ... [[0, 0, 0, 1, 1], [1, 1, 0, 1, 1]], + ... dtype=torch.bool, + ... ) + >>> source = torch.tensor([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) + >>> self.masked_scatter(mask, source) + tensor([[0, 0, 0, 0, 1], + [2, 3, 0, 4, 5]]) + """ + + def masked_scatter_(self, mask: Tensor, source: Tensor) -> Tensor: + r""" + masked_scatter_(mask, source) + + Copies elements from :attr:`source` into :attr:`self` tensor at positions where + the :attr:`mask` is True. Elements from :attr:`source` are copied into :attr:`self` + starting at position 0 of :attr:`source` and continuing in order one-by-one for each + occurrence of :attr:`mask` being True. + The shape of :attr:`mask` must be :ref:`broadcastable ` + with the shape of the underlying tensor. The :attr:`source` should have at least + as many elements as the number of ones in :attr:`mask`. + + Args: + mask (BoolTensor): the boolean mask + source (Tensor): the tensor to copy from + + .. note:: + + The :attr:`mask` operates on the :attr:`self` tensor, not on the given + :attr:`source` tensor. + + Example: + + >>> self = torch.tensor([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) + >>> mask = torch.tensor( + ... [[0, 0, 0, 1, 1], [1, 1, 0, 1, 1]], + ... dtype=torch.bool, + ... ) + >>> source = torch.tensor([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) + >>> self.masked_scatter_(mask, source) + tensor([[0, 0, 0, 0, 1], + [2, 3, 0, 4, 5]]) + """ + + def masked_select(self, mask: Tensor) -> Tensor: + r""" + masked_select(mask) -> Tensor + + See :func:`torch.masked_select` + """ + + def matmul(self, other: Tensor) -> Tensor: + r""" + matmul(tensor2) -> Tensor + + See :func:`torch.matmul` + """ + + def matrix_exp(self) -> Tensor: + r""" + matrix_exp() -> Tensor + + See :func:`torch.matrix_exp` + """ + + def matrix_power(self, n: _int) -> Tensor: + r""" + matrix_power(n) -> Tensor + + .. note:: :meth:`~Tensor.matrix_power` is deprecated, use :func:`torch.linalg.matrix_power` instead. + + Alias for :func:`torch.linalg.matrix_power` + """ + + @overload + def max(self) -> Tensor: + r""" + max(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + + See :func:`torch.max` + """ + + @overload + def max(self, other: Tensor) -> Tensor: + r""" + max(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + + See :func:`torch.max` + """ + + @overload + def max(self, dim: _int, keepdim: _bool = False) -> torch.return_types.max: + r""" + max(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + + See :func:`torch.max` + """ + + def maximum(self, other: Tensor) -> Tensor: + r""" + maximum(other) -> Tensor + + See :func:`torch.maximum` + """ + + @overload + def mean(self, *, dtype: _dtype | None = None) -> Tensor: + r""" + mean(dim=None, keepdim=False, *, dtype=None) -> Tensor + + See :func:`torch.mean` + """ + + @overload + def mean( + self, + dim: _int | _size | None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + ) -> Tensor: + r""" + mean(dim=None, keepdim=False, *, dtype=None) -> Tensor + + See :func:`torch.mean` + """ + + @overload + def median(self) -> Tensor: + r""" + median(dim=None, keepdim=False) -> (Tensor, LongTensor) + + See :func:`torch.median` + """ + + @overload + def median( + self, + dim: _int, + keepdim: _bool = False, + ) -> torch.return_types.median: + r""" + median(dim=None, keepdim=False) -> (Tensor, LongTensor) + + See :func:`torch.median` + """ + + @overload + def min(self) -> Tensor: + r""" + min(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + + See :func:`torch.min` + """ + + @overload + def min(self, other: Tensor) -> Tensor: + r""" + min(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + + See :func:`torch.min` + """ + + @overload + def min(self, dim: _int, keepdim: _bool = False) -> torch.return_types.min: + r""" + min(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) + + See :func:`torch.min` + """ + + def minimum(self, other: Tensor) -> Tensor: + r""" + minimum(other) -> Tensor + + See :func:`torch.minimum` + """ + + def mm(self, mat2: Tensor) -> Tensor: + r""" + mm(mat2) -> Tensor + + See :func:`torch.mm` + """ + + def mode( + self, + dim: _int = -1, + keepdim: _bool = False, + ) -> torch.return_types.mode: + r""" + mode(dim=None, keepdim=False) -> (Tensor, LongTensor) + + See :func:`torch.mode` + """ + + @overload + def moveaxis(self, source: _int, destination: _int) -> Tensor: + r""" + moveaxis(source, destination) -> Tensor + + See :func:`torch.moveaxis` + """ + + @overload + def moveaxis(self, source: _size, destination: _size) -> Tensor: + r""" + moveaxis(source, destination) -> Tensor + + See :func:`torch.moveaxis` + """ + + @overload + def movedim(self, source: _int, destination: _int) -> Tensor: + r""" + movedim(source, destination) -> Tensor + + See :func:`torch.movedim` + """ + + @overload + def movedim(self, source: _size, destination: _size) -> Tensor: + r""" + movedim(source, destination) -> Tensor + + See :func:`torch.movedim` + """ + + def msort(self) -> Tensor: + r""" + msort() -> Tensor + + See :func:`torch.msort` + """ + + def mul( + self, + other: Tensor | Number | _complex | torch.SymInt | torch.SymFloat, + *, + out: Tensor | None = None, + ) -> Tensor: + r""" + mul(value) -> Tensor + + See :func:`torch.mul`. + """ + + def mul_( + self, + other: Tensor | Number | _complex | torch.SymInt | torch.SymFloat, + ) -> Tensor: + r""" + mul_(value) -> Tensor + + In-place version of :meth:`~Tensor.mul`. + """ + + def multinomial( + self, + num_samples: _int | SymInt, + replacement: _bool = False, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + multinomial(num_samples, replacement=False, *, generator=None) -> Tensor + + See :func:`torch.multinomial` + """ + + @overload + def multiply(self, other: Tensor) -> Tensor: + r""" + multiply(value) -> Tensor + + See :func:`torch.multiply`. + """ + + @overload + def multiply(self, other: Number | _complex | PySymType) -> Tensor: + r""" + multiply(value) -> Tensor + + See :func:`torch.multiply`. + """ + + @overload + def multiply_(self, other: Tensor) -> Tensor: + r""" + multiply_(value) -> Tensor + + In-place version of :meth:`~Tensor.multiply`. + """ + + @overload + def multiply_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + multiply_(value) -> Tensor + + In-place version of :meth:`~Tensor.multiply`. + """ + + def mv(self, vec: Tensor) -> Tensor: + r""" + mv(vec) -> Tensor + + See :func:`torch.mv` + """ + + def mvlgamma(self, p: _int) -> Tensor: + r""" + mvlgamma(p) -> Tensor + + See :func:`torch.mvlgamma` + """ + + def mvlgamma_(self, p: _int) -> Tensor: + r""" + mvlgamma_(p) -> Tensor + + In-place version of :meth:`~Tensor.mvlgamma` + """ + + def nan_to_num( + self, + nan: _float | None = None, + posinf: _float | None = None, + neginf: _float | None = None, + ) -> Tensor: + r""" + nan_to_num(nan=0.0, posinf=None, neginf=None) -> Tensor + + See :func:`torch.nan_to_num`. + """ + + def nan_to_num_( + self, + nan: _float | None = None, + posinf: _float | None = None, + neginf: _float | None = None, + ) -> Tensor: + r""" + nan_to_num_(nan=0.0, posinf=None, neginf=None) -> Tensor + + In-place version of :meth:`~Tensor.nan_to_num`. + """ + + def nanmean( + self, + dim: _int | _size | None = None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + ) -> Tensor: + r""" + nanmean(dim=None, keepdim=False, *, dtype=None) -> Tensor + + See :func:`torch.nanmean` + """ + + @overload + def nanmedian(self) -> Tensor: + r""" + nanmedian(dim=None, keepdim=False) -> (Tensor, LongTensor) + + See :func:`torch.nanmedian` + """ + + @overload + def nanmedian( + self, + dim: _int, + keepdim: _bool = False, + ) -> torch.return_types.nanmedian: + r""" + nanmedian(dim=None, keepdim=False) -> (Tensor, LongTensor) + + See :func:`torch.nanmedian` + """ + + @overload + def nanquantile( + self, + q: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + ) -> Tensor: + r""" + nanquantile(q, dim=None, keepdim=False, *, interpolation='linear') -> Tensor + + See :func:`torch.nanquantile` + """ + + @overload + def nanquantile( + self, + q: _float, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + ) -> Tensor: + r""" + nanquantile(q, dim=None, keepdim=False, *, interpolation='linear') -> Tensor + + See :func:`torch.nanquantile` + """ + + def nansum( + self, + dim: _int | _size | None = None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + ) -> Tensor: + r""" + nansum(dim=None, keepdim=False, dtype=None) -> Tensor + + See :func:`torch.nansum` + """ + + @overload + def narrow(self, dim: _int, start: Tensor, length: _int | SymInt) -> Tensor: + r""" + narrow(dimension, start, length) -> Tensor + + See :func:`torch.narrow`. + """ + + @overload + def narrow( + self, + dim: _int, + start: _int | SymInt, + length: _int | SymInt, + ) -> Tensor: + r""" + narrow(dimension, start, length) -> Tensor + + See :func:`torch.narrow`. + """ + + def narrow_copy( + self, + dim: _int, + start: _int | SymInt, + length: _int | SymInt, + ) -> Tensor: + r""" + narrow_copy(dimension, start, length) -> Tensor + + See :func:`torch.narrow_copy`. + """ + + def ndimension(self) -> _int: + r""" + ndimension() -> int + + Alias for :meth:`~Tensor.dim()` + """ + + @overload + def ne(self, other: Tensor) -> Tensor: + r""" + ne(other) -> Tensor + + See :func:`torch.ne`. + """ + + @overload + def ne(self, other: Number | _complex | PySymType) -> Tensor: + r""" + ne(other) -> Tensor + + See :func:`torch.ne`. + """ + + @overload + def ne_(self, other: Tensor) -> Tensor: + r""" + ne_(other) -> Tensor + + In-place version of :meth:`~Tensor.ne`. + """ + + @overload + def ne_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + ne_(other) -> Tensor + + In-place version of :meth:`~Tensor.ne`. + """ + + def neg(self) -> Tensor: + r""" + neg() -> Tensor + + See :func:`torch.neg` + """ + + def neg_(self) -> Tensor: + r""" + neg_() -> Tensor + + In-place version of :meth:`~Tensor.neg` + """ + + def negative(self) -> Tensor: + r""" + negative() -> Tensor + + See :func:`torch.negative` + """ + + def negative_(self) -> Tensor: + r""" + negative_() -> Tensor + + In-place version of :meth:`~Tensor.negative` + """ + + def nelement(self) -> _int: + r""" + nelement() -> int + + Alias for :meth:`~Tensor.numel` + """ + + @overload + def new(cls, *args: Any, device: DeviceLikeType | None = None) -> Self: ... + @overload + def new(cls, storage: Storage) -> Self: ... + @overload + def new(cls, other: Tensor) -> Self: ... + @overload + def new(cls, size: _size, *, device: DeviceLikeType | None = None) -> Self: ... + @overload + def new_empty( + self, + size: Sequence[_int | SymInt], + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_empty(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with uninitialized data. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.ones(()) + >>> tensor.new_empty((2, 3)) + tensor([[ 5.8182e-18, 4.5765e-41, -1.0545e+30], + [ 3.0949e-41, 4.4842e-44, 0.0000e+00]]) + """ + + @overload + def new_empty( + self, + *size: _int | SymInt, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_empty(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with uninitialized data. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.ones(()) + >>> tensor.new_empty((2, 3)) + tensor([[ 5.8182e-18, 4.5765e-41, -1.0545e+30], + [ 3.0949e-41, 4.4842e-44, 0.0000e+00]]) + """ + + def new_empty_strided( + self, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_empty_strided(size, stride, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` and strides :attr:`stride` filled with + uninitialized data. By default, the returned Tensor has the same + :class:`torch.dtype` and :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.ones(()) + >>> tensor.new_empty_strided((2, 3), (3, 1)) + tensor([[ 5.8182e-18, 4.5765e-41, -1.0545e+30], + [ 3.0949e-41, 4.4842e-44, 0.0000e+00]]) + """ + + def new_full( + self, + size: Sequence[_int | SymInt], + fill_value: Number | _complex | PySymType, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_full(size, fill_value, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with :attr:`fill_value`. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + fill_value (scalar): the number to fill the output tensor with. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.ones((2,), dtype=torch.float64) + >>> tensor.new_full((3, 4), 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416, 3.1416]], dtype=torch.float64) + """ + + @overload + def new_ones( + self, + size: _size, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, + ) -> Tensor: + r""" + new_ones(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with ``1``. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.tensor((), dtype=torch.int32) + >>> tensor.new_ones((2, 3)) + tensor([[ 1, 1, 1], + [ 1, 1, 1]], dtype=torch.int32) + """ + + @overload + def new_ones( + self, + size: Sequence[_int | SymInt], + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_ones(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with ``1``. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.tensor((), dtype=torch.int32) + >>> tensor.new_ones((2, 3)) + tensor([[ 1, 1, 1], + [ 1, 1, 1]], dtype=torch.int32) + """ + + @overload + def new_ones( + self, + *size: _int | SymInt, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_ones(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with ``1``. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.tensor((), dtype=torch.int32) + >>> tensor.new_ones((2, 3)) + tensor([[ 1, 1, 1], + [ 1, 1, 1]], dtype=torch.int32) + """ + + def new_tensor( + self, + data: Any, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, + ) -> Tensor: + r""" + new_tensor(data, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a new Tensor with :attr:`data` as the tensor data. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + .. warning:: + + :func:`new_tensor` always copies :attr:`data`. If you have a Tensor + ``data`` and want to avoid a copy, use :func:`torch.Tensor.requires_grad_` + or :func:`torch.Tensor.detach`. + If you have a numpy array and want to avoid a copy, use + :func:`torch.from_numpy`. + + .. warning:: + + When data is a tensor `x`, :func:`new_tensor()` reads out 'the data' from whatever it is passed, + and constructs a leaf variable. Therefore ``tensor.new_tensor(x)`` is equivalent to ``x.detach().clone()`` + and ``tensor.new_tensor(x, requires_grad=True)`` is equivalent to ``x.detach().clone().requires_grad_(True)``. + The equivalents using ``detach()`` and ``clone()`` are recommended. + + Args: + data (array_like): The returned Tensor copies :attr:`data`. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.ones((2,), dtype=torch.int8) + >>> data = [[0, 1], [2, 3]] + >>> tensor.new_tensor(data) + tensor([[ 0, 1], + [ 2, 3]], dtype=torch.int8) + """ + + @overload + def new_zeros( + self, + size: Sequence[_int | SymInt], + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_zeros(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with ``0``. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.tensor((), dtype=torch.float64) + >>> tensor.new_zeros((2, 3)) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]], dtype=torch.float64) + """ + + @overload + def new_zeros( + self, + *size: _int | SymInt, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, + ) -> Tensor: + r""" + new_zeros(size, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) -> Tensor + + + Returns a Tensor of size :attr:`size` filled with ``0``. + By default, the returned Tensor has the same :class:`torch.dtype` and + :class:`torch.device` as this tensor. + + Args: + size (int...): a list, tuple, or :class:`torch.Size` of integers defining the + shape of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. + Default: if None, same :class:`torch.dtype` as this tensor. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, same :class:`torch.device` as this tensor. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> tensor = torch.tensor((), dtype=torch.float64) + >>> tensor.new_zeros((2, 3)) + tensor([[ 0., 0., 0.], + [ 0., 0., 0.]], dtype=torch.float64) + """ + + def nextafter(self, other: Tensor) -> Tensor: + r""" + nextafter(other) -> Tensor + See :func:`torch.nextafter` + """ + + def nextafter_(self, other: Tensor) -> Tensor: + r""" + nextafter_(other) -> Tensor + In-place version of :meth:`~Tensor.nextafter` + """ + + @overload + def nonzero(self, *, as_tuple: Literal[False] = False) -> Tensor: + r""" + nonzero() -> LongTensor + + See :func:`torch.nonzero` + """ + + @overload + def nonzero(self, *, as_tuple: Literal[True]) -> tuple[Tensor, ...]: + r""" + nonzero() -> LongTensor + + See :func:`torch.nonzero` + """ + + def nonzero_static( + self, + *, + size: _int | SymInt, + fill_value: _int = -1, + ) -> Tensor: + r""" + nonzero_static(*, size, fill_value=-1) -> LongTensor + + See :func:`torch.nonzero_static` + """ + + def normal_( + self, + mean: _float = 0, + std: _float = 1, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + normal_(mean=0, std=1, *, generator=None) -> Tensor + + Fills :attr:`self` tensor with elements samples from the normal distribution + parameterized by :attr:`mean` and :attr:`std`. + """ + + @overload + def not_equal(self, other: Tensor) -> Tensor: + r""" + not_equal(other) -> Tensor + + See :func:`torch.not_equal`. + """ + + @overload + def not_equal(self, other: Number | _complex | PySymType) -> Tensor: + r""" + not_equal(other) -> Tensor + + See :func:`torch.not_equal`. + """ + + @overload + def not_equal_(self, other: Tensor) -> Tensor: + r""" + not_equal_(other) -> Tensor + + In-place version of :meth:`~Tensor.not_equal`. + """ + + @overload + def not_equal_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + not_equal_(other) -> Tensor + + In-place version of :meth:`~Tensor.not_equal`. + """ + + def numel(self) -> _int: + r""" + numel() -> int + + See :func:`torch.numel` + """ + + def numpy(self, *, force: _bool = False) -> numpy.ndarray: + r""" + numpy(*, force=False) -> numpy.ndarray + + Returns the tensor as a NumPy :class:`ndarray`. + + If :attr:`force` is ``False`` (the default), the conversion + is performed only if the tensor is on the CPU, does not require grad, + does not have its conjugate bit set, and is a dtype and layout that + NumPy supports. The returned ndarray and the tensor will share their + storage, so changes to the tensor will be reflected in the ndarray + and vice versa. + + If :attr:`force` is ``True`` this is equivalent to + calling ``t.detach().cpu().resolve_conj().resolve_neg().numpy()``. + If the tensor isn't on the CPU or the conjugate or negative bit is set, + the tensor won't share its storage with the returned ndarray. + Setting :attr:`force` to ``True`` can be a useful shorthand. + + Args: + force (bool): if ``True``, the ndarray may be a copy of the tensor + instead of always sharing memory, defaults to ``False``. + """ + + def orgqr(self, input2: Tensor) -> Tensor: + r""" + orgqr(input2) -> Tensor + + See :func:`torch.orgqr` + """ + + def ormqr( + self, + input2: Tensor, + input3: Tensor, + left: _bool = True, + transpose: _bool = False, + ) -> Tensor: + r""" + ormqr(input2, input3, left=True, transpose=False) -> Tensor + + See :func:`torch.ormqr` + """ + + def outer(self, vec2: Tensor) -> Tensor: + r""" + outer(vec2) -> Tensor + + See :func:`torch.outer`. + """ + + @overload + def permute(self, dims: _size) -> Tensor: + r""" + permute(*dims) -> Tensor + + Returns a view of the tensor with its dimensions permuted. + + Args: + dims (torch.Size, int..., tuple of int or list of int): the desired ordering of dimensions. + + Example: + >>> x = torch.randn(2, 3, 5) + >>> x.size() + torch.Size([2, 3, 5]) + >>> x.permute(2, 0, 1).size() + torch.Size([5, 2, 3]) + """ + + @overload + def permute(self, *dims: _int) -> Tensor: + r""" + permute(*dims) -> Tensor + + Returns a view of the tensor with its dimensions permuted. + + Args: + dims (torch.Size, int..., tuple of int or list of int): the desired ordering of dimensions. + + Example: + >>> x = torch.randn(2, 3, 5) + >>> x.size() + torch.Size([2, 3, 5]) + >>> x.permute(2, 0, 1).size() + torch.Size([5, 2, 3]) + """ + + def pin_memory(self, device: DeviceLikeType | None = None) -> Tensor: + r""" + pin_memory() -> Tensor + + Copies the tensor to pinned memory, if it's not already pinned. + By default, the device pinned memory on will be the current :ref:`accelerator`. + """ + + def pinverse(self, rcond: _float = 1e-15) -> Tensor: + r""" + pinverse() -> Tensor + + See :func:`torch.pinverse` + """ + + def polygamma(self, n: _int) -> Tensor: + r""" + polygamma(n) -> Tensor + + See :func:`torch.polygamma` + """ + + def polygamma_(self, n: _int) -> Tensor: + r""" + polygamma_(n) -> Tensor + + In-place version of :meth:`~Tensor.polygamma` + """ + + def positive(self) -> Tensor: + r""" + positive() -> Tensor + + See :func:`torch.positive` + """ + + @overload + def pow(self, exponent: Tensor) -> Tensor: + r""" + pow(exponent) -> Tensor + + See :func:`torch.pow` + """ + + @overload + def pow(self, exponent: Number | _complex | PySymType) -> Tensor: + r""" + pow(exponent) -> Tensor + + See :func:`torch.pow` + """ + + @overload + def pow_(self, exponent: Tensor) -> Tensor: + r""" + pow_(exponent) -> Tensor + + In-place version of :meth:`~Tensor.pow` + """ + + @overload + def pow_(self, exponent: Number | _complex | PySymType) -> Tensor: + r""" + pow_(exponent) -> Tensor + + In-place version of :meth:`~Tensor.pow` + """ + + def prelu(self, weight: Tensor) -> Tensor: ... + @overload + def prod(self, *, dtype: _dtype | None = None) -> Tensor: + r""" + prod(dim=None, keepdim=False, dtype=None) -> Tensor + + See :func:`torch.prod` + """ + + @overload + def prod( + self, + dim: _int, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + ) -> Tensor: + r""" + prod(dim=None, keepdim=False, dtype=None) -> Tensor + + See :func:`torch.prod` + """ + + def put( + self, + index: Tensor, + source: Tensor, + accumulate: _bool = False, + ) -> Tensor: + r""" + put(input, index, source, accumulate=False) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.put_`. + `input` corresponds to `self` in :meth:`torch.Tensor.put_`. + """ + + def put_( + self, + index: Tensor, + source: Tensor, + accumulate: _bool = False, + ) -> Tensor: + r""" + put_(index, source, accumulate=False) -> Tensor + + Copies the elements from :attr:`source` into the positions specified by + :attr:`index`. For the purpose of indexing, the :attr:`self` tensor is treated as if + it were a 1-D tensor. + + :attr:`index` and :attr:`source` need to have the same number of elements, but not necessarily + the same shape. + + If :attr:`accumulate` is ``True``, the elements in :attr:`source` are added to + :attr:`self`. If accumulate is ``False``, the behavior is undefined if :attr:`index` + contain duplicate elements. + + Args: + index (LongTensor): the indices into self + source (Tensor): the tensor containing values to copy from + accumulate (bool, optional): whether to accumulate into self. Default: ``False`` + + Example:: + + >>> src = torch.tensor([[4, 3, 5], + ... [6, 7, 8]]) + >>> src.put_(torch.tensor([1, 3]), torch.tensor([9, 10])) + tensor([[ 4, 9, 5], + [ 10, 7, 8]]) + """ + + def q_per_channel_axis(self) -> _int: + r""" + q_per_channel_axis() -> int + + Given a Tensor quantized by linear (affine) per-channel quantization, + returns the index of dimension on which per-channel quantization is applied. + """ + + def q_per_channel_scales(self) -> Tensor: + r""" + q_per_channel_scales() -> Tensor + + Given a Tensor quantized by linear (affine) per-channel quantization, + returns a Tensor of scales of the underlying quantizer. It has the number of + elements that matches the corresponding dimensions (from q_per_channel_axis) of + the tensor. + """ + + def q_per_channel_zero_points(self) -> Tensor: + r""" + q_per_channel_zero_points() -> Tensor + + Given a Tensor quantized by linear (affine) per-channel quantization, + returns a tensor of zero_points of the underlying quantizer. It has the number of + elements that matches the corresponding dimensions (from q_per_channel_axis) of + the tensor. + """ + + def q_scale(self) -> _float: + r""" + q_scale() -> float + + Given a Tensor quantized by linear(affine) quantization, + returns the scale of the underlying quantizer(). + """ + + def q_zero_point(self) -> _int: + r""" + q_zero_point() -> int + + Given a Tensor quantized by linear(affine) quantization, + returns the zero_point of the underlying quantizer(). + """ + + def qscheme(self) -> _qscheme: + r""" + qscheme() -> torch.qscheme + + Returns the quantization scheme of a given QTensor. + """ + + @overload + def quantile( + self, + q: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + ) -> Tensor: + r""" + quantile(q, dim=None, keepdim=False, *, interpolation='linear') -> Tensor + + See :func:`torch.quantile` + """ + + @overload + def quantile( + self, + q: _float, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + ) -> Tensor: + r""" + quantile(q, dim=None, keepdim=False, *, interpolation='linear') -> Tensor + + See :func:`torch.quantile` + """ + + def rad2deg(self) -> Tensor: + r""" + rad2deg() -> Tensor + + See :func:`torch.rad2deg` + """ + + def rad2deg_(self) -> Tensor: + r""" + rad2deg_() -> Tensor + + In-place version of :meth:`~Tensor.rad2deg` + """ + + @overload + def random_(self, *, generator: Generator | None = None) -> Tensor: + r""" + random_(from=0, to=None, *, generator=None) -> Tensor + + Fills :attr:`self` tensor with numbers sampled from the discrete uniform + distribution over ``[from, to - 1]``. If not specified, the values are usually + only bounded by :attr:`self` tensor's data type. However, for floating point + types, if unspecified, range will be ``[0, 2^mantissa]`` to ensure that every + value is representable. For example, `torch.tensor(1, dtype=torch.double).random_()` + will be uniform in ``[0, 2^53]``. + """ + + @overload + def random_( + self, + from_: _int, + to: _int | None, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + random_(from=0, to=None, *, generator=None) -> Tensor + + Fills :attr:`self` tensor with numbers sampled from the discrete uniform + distribution over ``[from, to - 1]``. If not specified, the values are usually + only bounded by :attr:`self` tensor's data type. However, for floating point + types, if unspecified, range will be ``[0, 2^mantissa]`` to ensure that every + value is representable. For example, `torch.tensor(1, dtype=torch.double).random_()` + will be uniform in ``[0, 2^53]``. + """ + + @overload + def random_( + self, + to: _int, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + random_(from=0, to=None, *, generator=None) -> Tensor + + Fills :attr:`self` tensor with numbers sampled from the discrete uniform + distribution over ``[from, to - 1]``. If not specified, the values are usually + only bounded by :attr:`self` tensor's data type. However, for floating point + types, if unspecified, range will be ``[0, 2^mantissa]`` to ensure that every + value is representable. For example, `torch.tensor(1, dtype=torch.double).random_()` + will be uniform in ``[0, 2^53]``. + """ + + def ravel(self) -> Tensor: + r""" + ravel() -> Tensor + + see :func:`torch.ravel` + """ + + def reciprocal(self) -> Tensor: + r""" + reciprocal() -> Tensor + + See :func:`torch.reciprocal` + """ + + def reciprocal_(self) -> Tensor: + r""" + reciprocal_() -> Tensor + + In-place version of :meth:`~Tensor.reciprocal` + """ + + def record_stream(self, s: Stream) -> None: + r""" + record_stream(stream) + + Marks the tensor as having been used by this stream. When the tensor + is deallocated, ensure the tensor memory is not reused for another tensor + until all work queued on :attr:`stream` at the time of deallocation is + complete. + + .. note:: + + The caching allocator is aware of only the stream where a tensor was + allocated. Due to the awareness, it already correctly manages the life + cycle of tensors on only one stream. But if a tensor is used on a stream + different from the stream of origin, the allocator might reuse the memory + unexpectedly. Calling this method lets the allocator know which streams + have used the tensor. + + .. warning:: + + This method is most suitable for use cases where you are providing a + function that created a tensor on a side stream, and want users to be able + to make use of the tensor without having to think carefully about stream + safety when making use of them. These safety guarantees come at some + performance and predictability cost (analogous to the tradeoff between GC + and manual memory management), so if you are in a situation where + you manage the full lifetime of your tensors, you may consider instead + manually managing CUDA events so that calling this method is not necessary. + In particular, when you call this method, on later allocations the + allocator will poll the recorded stream to see if all operations have + completed yet; you can potentially race with side stream computation and + non-deterministically reuse or fail to reuse memory for an allocation. + + You can safely use tensors allocated on side streams without + :meth:`~Tensor.record_stream`; you must manually ensure that + any non-creation stream uses of a tensor are synced back to the creation + stream before you deallocate the tensor. As the CUDA caching allocator + guarantees that the memory will only be reused with the same creation stream, + this is sufficient to ensure that writes to future reallocations of the + memory will be delayed until non-creation stream uses are done. + (Counterintuitively, you may observe that on the CPU side we have already + reallocated the tensor, even though CUDA kernels on the old tensor are + still in progress. This is fine, because CUDA operations on the new + tensor will appropriately wait for the old operations to complete, as they + are all on the same stream.) + + Concretely, this looks like this:: + + with torch.cuda.stream(s0): + x = torch.zeros(N) + + s1.wait_stream(s0) + with torch.cuda.stream(s1): + y = some_comm_op(x) + + ... some compute on s0 ... + + # synchronize creation stream s0 to side stream s1 + # before deallocating x + s0.wait_stream(s1) + del x + + Note that some discretion is required when deciding when to perform + ``s0.wait_stream(s1)``. In particular, if we were to wait immediately + after ``some_comm_op``, there wouldn't be any point in having the side + stream; it would be equivalent to have run ``some_comm_op`` on ``s0``. + Instead, the synchronization must be placed at some appropriate, later + point in time where you expect the side stream ``s1`` to have finished + work. This location is typically identified via profiling, e.g., using + Chrome traces produced + :meth:`torch.autograd.profiler.profile.export_chrome_trace`. If you + place the wait too early, work on s0 will block until ``s1`` has finished, + preventing further overlapping of communication and computation. If you + place the wait too late, you will use more memory than is strictly + necessary (as you are keeping ``x`` live for longer.) For a concrete + example of how this guidance can be applied in practice, see this post: + `FSDP and CUDACachingAllocator + `_. + """ + + def relu(self) -> Tensor: ... + def relu_(self) -> Tensor: ... + @overload + def remainder(self, other: Tensor) -> Tensor: + r""" + remainder(divisor) -> Tensor + + See :func:`torch.remainder` + """ + + @overload + def remainder(self, other: Number | _complex | PySymType) -> Tensor: + r""" + remainder(divisor) -> Tensor + + See :func:`torch.remainder` + """ + + @overload + def remainder_(self, other: Tensor) -> Tensor: + r""" + remainder_(divisor) -> Tensor + + In-place version of :meth:`~Tensor.remainder` + """ + + @overload + def remainder_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + remainder_(divisor) -> Tensor + + In-place version of :meth:`~Tensor.remainder` + """ + + def renorm( + self, + p: Number | _complex | PySymType, + dim: _int, + maxnorm: Number | _complex | PySymType, + ) -> Tensor: + r""" + renorm(p, dim, maxnorm) -> Tensor + + See :func:`torch.renorm` + """ + + def renorm_( + self, + p: Number | _complex | PySymType, + dim: _int, + maxnorm: Number | _complex | PySymType, + ) -> Tensor: + r""" + renorm_(p, dim, maxnorm) -> Tensor + + In-place version of :meth:`~Tensor.renorm` + """ + + @overload + def repeat(self, repeats: Sequence[_int | SymInt]) -> Tensor: + r""" + repeat(*repeats) -> Tensor + + Repeats this tensor along the specified dimensions. + + Unlike :meth:`~Tensor.expand`, this function copies the tensor's data. + + .. warning:: + + :meth:`~Tensor.repeat` behaves differently from + `numpy.repeat `_, + but is more similar to + `numpy.tile `_. + For the operator similar to `numpy.repeat`, see :func:`torch.repeat_interleave`. + + Args: + repeat (torch.Size, int..., tuple of int or list of int): The number of times to repeat this tensor along each dimension + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.repeat(4, 2) + tensor([[ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3]]) + >>> x.repeat(4, 2, 1).size() + torch.Size([4, 2, 3]) + """ + + @overload + def repeat(self, *repeats: _int | SymInt) -> Tensor: + r""" + repeat(*repeats) -> Tensor + + Repeats this tensor along the specified dimensions. + + Unlike :meth:`~Tensor.expand`, this function copies the tensor's data. + + .. warning:: + + :meth:`~Tensor.repeat` behaves differently from + `numpy.repeat `_, + but is more similar to + `numpy.tile `_. + For the operator similar to `numpy.repeat`, see :func:`torch.repeat_interleave`. + + Args: + repeat (torch.Size, int..., tuple of int or list of int): The number of times to repeat this tensor along each dimension + + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> x.repeat(4, 2) + tensor([[ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3], + [ 1, 2, 3, 1, 2, 3]]) + >>> x.repeat(4, 2, 1).size() + torch.Size([4, 2, 3]) + """ + + @overload + def repeat_interleave( + self, + repeats: Tensor, + dim: _int | None = None, + *, + output_size: _int | SymInt | None = None, + ) -> Tensor: + r""" + repeat_interleave(repeats, dim=None, *, output_size=None) -> Tensor + + See :func:`torch.repeat_interleave`. + """ + + @overload + def repeat_interleave( + self, + repeats: _int | SymInt, + dim: _int | None = None, + *, + output_size: _int | SymInt | None = None, + ) -> Tensor: + r""" + repeat_interleave(repeats, dim=None, *, output_size=None) -> Tensor + + See :func:`torch.repeat_interleave`. + """ + + def requires_grad_(self, mode: _bool = True) -> Tensor: + r""" + requires_grad_(requires_grad=True) -> Tensor + + Change if autograd should record operations on this tensor: sets this tensor's + :attr:`requires_grad` attribute in-place. Returns this tensor. + + :func:`requires_grad_`'s main use case is to tell autograd to begin recording + operations on a Tensor ``tensor``. If ``tensor`` has ``requires_grad=False`` + (because it was obtained through a DataLoader, or required preprocessing or + initialization), ``tensor.requires_grad_()`` makes it so that autograd will + begin to record operations on ``tensor``. + + Args: + requires_grad (bool): If autograd should record operations on this tensor. + Default: ``True``. + + Example:: + + >>> # Let's say we want to preprocess some saved weights and use + >>> # the result as new weights. + >>> saved_weights = [0.1, 0.2, 0.3, 0.25] + >>> loaded_weights = torch.tensor(saved_weights) + >>> weights = preprocess(loaded_weights) # some function + >>> weights + tensor([-0.5503, 0.4926, -2.1158, -0.8303]) + + >>> # Now, start to record operations done to weights + >>> weights.requires_grad_() + >>> out = weights.pow(2).sum() + >>> out.backward() + >>> weights.grad + tensor([-1.1007, 0.9853, -4.2316, -1.6606]) + """ + + @overload + def reshape(self, shape: Sequence[_int | SymInt]) -> Tensor: + r""" + reshape(*shape) -> Tensor + + Returns a tensor with the same data and number of elements as :attr:`self` + but with the specified shape. This method returns a view if :attr:`shape` is + compatible with the current shape. See :meth:`torch.Tensor.view` on when it is + possible to return a view. + + See :func:`torch.reshape` + + Args: + shape (tuple of ints or int...): the desired shape + """ + + @overload + def reshape(self, *shape: _int | SymInt) -> Tensor: + r""" + reshape(*shape) -> Tensor + + Returns a tensor with the same data and number of elements as :attr:`self` + but with the specified shape. This method returns a view if :attr:`shape` is + compatible with the current shape. See :meth:`torch.Tensor.view` on when it is + possible to return a view. + + See :func:`torch.reshape` + + Args: + shape (tuple of ints or int...): the desired shape + """ + + def reshape_as(self, other: Tensor) -> Tensor: + r""" + reshape_as(other) -> Tensor + + Returns this tensor as the same shape as :attr:`other`. + ``self.reshape_as(other)`` is equivalent to ``self.reshape(other.sizes())``. + This method returns a view if ``other.sizes()`` is compatible with the current + shape. See :meth:`torch.Tensor.view` on when it is possible to return a view. + + Please see :meth:`reshape` for more information about ``reshape``. + + Args: + other (:class:`torch.Tensor`): The result tensor has the same shape + as :attr:`other`. + """ + + @overload + def resize_( + self, + size: Sequence[_int | SymInt], + *, + memory_format: memory_format | None = None, + ) -> Tensor: + r""" + resize_(*sizes, memory_format=torch.contiguous_format) -> Tensor + + Resizes :attr:`self` tensor to the specified size. If the number of elements is + larger than the current storage size, then the underlying storage is resized + to fit the new number of elements. If the number of elements is smaller, the + underlying storage is not changed. Existing elements are preserved but any new + memory is uninitialized. + + .. warning:: + + This is a low-level method. The storage is reinterpreted as C-contiguous, + ignoring the current strides (unless the target size equals the current + size, in which case the tensor is left unchanged). For most purposes, you + will instead want to use :meth:`~Tensor.view()`, which checks for + contiguity, or :meth:`~Tensor.reshape()`, which copies data if needed. To + change the size in-place with custom strides, see :meth:`~Tensor.set_()`. + + .. note:: + + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, new elements are initialized to prevent nondeterministic behavior + from using the result as an input to an operation. Floating point and + complex values are set to NaN, and integer values are set to the maximum + value. + + Args: + sizes (torch.Size or int...): the desired size + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + Tensor. Default: ``torch.contiguous_format``. Note that memory format of + :attr:`self` is going to be unaffected if ``self.size()`` matches ``sizes``. + + Example:: + + >>> x = torch.tensor([[1, 2], [3, 4], [5, 6]]) + >>> x.resize_(2, 2) + tensor([[ 1, 2], + [ 3, 4]]) + """ + + @overload + def resize_( + self, + *size: _int | SymInt, + memory_format: memory_format | None = None, + ) -> Tensor: + r""" + resize_(*sizes, memory_format=torch.contiguous_format) -> Tensor + + Resizes :attr:`self` tensor to the specified size. If the number of elements is + larger than the current storage size, then the underlying storage is resized + to fit the new number of elements. If the number of elements is smaller, the + underlying storage is not changed. Existing elements are preserved but any new + memory is uninitialized. + + .. warning:: + + This is a low-level method. The storage is reinterpreted as C-contiguous, + ignoring the current strides (unless the target size equals the current + size, in which case the tensor is left unchanged). For most purposes, you + will instead want to use :meth:`~Tensor.view()`, which checks for + contiguity, or :meth:`~Tensor.reshape()`, which copies data if needed. To + change the size in-place with custom strides, see :meth:`~Tensor.set_()`. + + .. note:: + + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, new elements are initialized to prevent nondeterministic behavior + from using the result as an input to an operation. Floating point and + complex values are set to NaN, and integer values are set to the maximum + value. + + Args: + sizes (torch.Size or int...): the desired size + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + Tensor. Default: ``torch.contiguous_format``. Note that memory format of + :attr:`self` is going to be unaffected if ``self.size()`` matches ``sizes``. + + Example:: + + >>> x = torch.tensor([[1, 2], [3, 4], [5, 6]]) + >>> x.resize_(2, 2) + tensor([[ 1, 2], + [ 3, 4]]) + """ + + def resize_as_( + self, + the_template: Tensor, + *, + memory_format: memory_format | None = None, + ) -> Tensor: + r""" + resize_as_(tensor, memory_format=torch.contiguous_format) -> Tensor + + Resizes the :attr:`self` tensor to be the same size as the specified + :attr:`tensor`. This is equivalent to ``self.resize_(tensor.size())``. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + Tensor. Default: ``torch.contiguous_format``. Note that memory format of + :attr:`self` is going to be unaffected if ``self.size()`` matches ``tensor.size()``. + """ + + def resize_as_sparse_(self, the_template: Tensor) -> Tensor: ... + def resolve_conj(self) -> Tensor: + r""" + resolve_conj() -> Tensor + + See :func:`torch.resolve_conj` + """ + + def resolve_neg(self) -> Tensor: + r""" + resolve_neg() -> Tensor + + See :func:`torch.resolve_neg` + """ + + def retain_grad(self) -> None: + r""" + retain_grad() -> None + + Enables this Tensor to have their :attr:`grad` populated during + :func:`backward`. This is a no-op for leaf tensors. + """ + + def roll( + self, + shifts: _int | SymInt | Sequence[_int | SymInt], + dims: _int | _size = (), + ) -> Tensor: + r""" + roll(shifts, dims) -> Tensor + + See :func:`torch.roll` + """ + + def rot90(self, k: _int = 1, dims: _size = (0, 1)) -> Tensor: + r""" + rot90(k, dims) -> Tensor + + See :func:`torch.rot90` + """ + + @overload + def round(self) -> Tensor: + r""" + round(decimals=0) -> Tensor + + See :func:`torch.round` + """ + + @overload + def round(self, *, decimals: _int) -> Tensor: + r""" + round(decimals=0) -> Tensor + + See :func:`torch.round` + """ + + @overload + def round_(self) -> Tensor: + r""" + round_(decimals=0) -> Tensor + + In-place version of :meth:`~Tensor.round` + """ + + @overload + def round_(self, *, decimals: _int) -> Tensor: + r""" + round_(decimals=0) -> Tensor + + In-place version of :meth:`~Tensor.round` + """ + + def row_indices(self) -> Tensor: ... + def rsqrt(self) -> Tensor: + r""" + rsqrt() -> Tensor + + See :func:`torch.rsqrt` + """ + + def rsqrt_(self) -> Tensor: + r""" + rsqrt_() -> Tensor + + In-place version of :meth:`~Tensor.rsqrt` + """ + + @overload + def scatter(self, dim: _int, index: Tensor, src: Tensor) -> Tensor: + r""" + scatter(dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + + @overload + def scatter( + self, + dim: _int, + index: Tensor, + src: Tensor, + *, + reduce: str, + ) -> Tensor: + r""" + scatter(dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + + @overload + def scatter( + self, + dim: _int, + index: Tensor, + value: Number | _complex | PySymType, + *, + reduce: str, + ) -> Tensor: + r""" + scatter(dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + + @overload + def scatter( + self, + dim: _int, + index: Tensor, + value: Number | _complex | PySymType, + ) -> Tensor: + r""" + scatter(dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + + @overload + def scatter_(self, dim: _int, index: Tensor, src: Tensor) -> Tensor: + r""" + scatter_(dim, index, src, *, reduce=None) -> Tensor + + Writes all values from the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index` tensor. For each value in :attr:`src`, its output + index is specified by its index in :attr:`src` for ``dimension != dim`` and by + the corresponding value in :attr:`index` for ``dimension = dim``. + + For a 3-D tensor, :attr:`self` is updated as:: + + self[index[i][j][k]][j][k] = src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] = src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] = src[i][j][k] # if dim == 2 + + This is the reverse operation of the manner described in :meth:`~Tensor.gather`. + + It is also required that + ``index.size(d) <= src.size(d)`` for all dimensions ``d``, and that + ``index.size(d) <= self.size(d)`` for all dimensions ``d != dim``. + Note that ``input`` and ``index`` do not broadcast against each other for NPUs, + so when running on NPUs, :attr:`input` and :attr:`index` must have the same number of dimensions. + Standard broadcasting occurs in all other cases. + + Moreover, as for :meth:`~Tensor.gather`, the values of :attr:`index` must be + between ``0`` and ``self.size(dim) - 1`` inclusive. + + .. warning:: + + When indices are not unique, the behavior is non-deterministic (one of the + values from ``src`` will be picked arbitrarily) and the gradient will be + incorrect (it will be propagated to all locations in the source that + correspond to the same index)! + + .. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + + Additionally accepts an optional :attr:`reduce` argument that allows + specification of an optional reduction operation, which is applied to all + values in the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index`. For each value in :attr:`src`, the reduction + operation is applied to an index in :attr:`self` which is specified by + its index in :attr:`src` for ``dimension != dim`` and by the corresponding + value in :attr:`index` for ``dimension = dim``. + + Given a 3-D tensor and reduction using the multiplication operation, :attr:`self` + is updated as:: + + self[index[i][j][k]][j][k] *= src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] *= src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] *= src[i][j][k] # if dim == 2 + + Reducing with the addition operation is the same as using + :meth:`~torch.Tensor.scatter_add_`. + + .. warning:: + The reduce argument with Tensor ``src`` is deprecated and will be removed in + a future PyTorch release. Please use :meth:`~torch.Tensor.scatter_reduce_` + instead for more reduction options. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + src (Tensor): the source element(s) to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> src = torch.arange(1, 11).reshape((2, 5)) + >>> src + tensor([[ 1, 2, 3, 4, 5], + [ 6, 7, 8, 9, 10]]) + >>> index = torch.tensor([[0, 1, 2, 0]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(0, index, src) + tensor([[1, 0, 0, 4, 0], + [0, 2, 0, 0, 0], + [0, 0, 3, 0, 0]]) + >>> index = torch.tensor([[0, 1, 2], [0, 1, 4]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(1, index, src) + tensor([[1, 2, 3, 0, 0], + [6, 7, 0, 0, 8], + [0, 0, 0, 0, 0]]) + + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='multiply') + tensor([[2.0000, 2.0000, 2.4600, 2.0000], + [2.0000, 2.0000, 2.0000, 2.4600]]) + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='add') + tensor([[2.0000, 2.0000, 3.2300, 2.0000], + [2.0000, 2.0000, 2.0000, 3.2300]]) + + .. function:: scatter_(dim, index, value, *, reduce=None) -> Tensor: + :noindex: + + Writes the value from :attr:`value` into :attr:`self` at the indices + specified in the :attr:`index` tensor. This operation is equivalent to the previous version, + with the :attr:`src` tensor filled entirely with :attr:`value`. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + value (Scalar): the value to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> index = torch.tensor([[0, 1]]) + >>> value = 2 + >>> torch.zeros(3, 5).scatter_(0, index, value) + tensor([[2., 0., 0., 0., 0.], + [0., 2., 0., 0., 0.], + [0., 0., 0., 0., 0.]]) + """ + + @overload + def scatter_( + self, + dim: _int, + index: Tensor, + src: Tensor, + *, + reduce: str, + ) -> Tensor: + r""" + scatter_(dim, index, src, *, reduce=None) -> Tensor + + Writes all values from the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index` tensor. For each value in :attr:`src`, its output + index is specified by its index in :attr:`src` for ``dimension != dim`` and by + the corresponding value in :attr:`index` for ``dimension = dim``. + + For a 3-D tensor, :attr:`self` is updated as:: + + self[index[i][j][k]][j][k] = src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] = src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] = src[i][j][k] # if dim == 2 + + This is the reverse operation of the manner described in :meth:`~Tensor.gather`. + + It is also required that + ``index.size(d) <= src.size(d)`` for all dimensions ``d``, and that + ``index.size(d) <= self.size(d)`` for all dimensions ``d != dim``. + Note that ``input`` and ``index`` do not broadcast against each other for NPUs, + so when running on NPUs, :attr:`input` and :attr:`index` must have the same number of dimensions. + Standard broadcasting occurs in all other cases. + + Moreover, as for :meth:`~Tensor.gather`, the values of :attr:`index` must be + between ``0`` and ``self.size(dim) - 1`` inclusive. + + .. warning:: + + When indices are not unique, the behavior is non-deterministic (one of the + values from ``src`` will be picked arbitrarily) and the gradient will be + incorrect (it will be propagated to all locations in the source that + correspond to the same index)! + + .. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + + Additionally accepts an optional :attr:`reduce` argument that allows + specification of an optional reduction operation, which is applied to all + values in the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index`. For each value in :attr:`src`, the reduction + operation is applied to an index in :attr:`self` which is specified by + its index in :attr:`src` for ``dimension != dim`` and by the corresponding + value in :attr:`index` for ``dimension = dim``. + + Given a 3-D tensor and reduction using the multiplication operation, :attr:`self` + is updated as:: + + self[index[i][j][k]][j][k] *= src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] *= src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] *= src[i][j][k] # if dim == 2 + + Reducing with the addition operation is the same as using + :meth:`~torch.Tensor.scatter_add_`. + + .. warning:: + The reduce argument with Tensor ``src`` is deprecated and will be removed in + a future PyTorch release. Please use :meth:`~torch.Tensor.scatter_reduce_` + instead for more reduction options. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + src (Tensor): the source element(s) to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> src = torch.arange(1, 11).reshape((2, 5)) + >>> src + tensor([[ 1, 2, 3, 4, 5], + [ 6, 7, 8, 9, 10]]) + >>> index = torch.tensor([[0, 1, 2, 0]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(0, index, src) + tensor([[1, 0, 0, 4, 0], + [0, 2, 0, 0, 0], + [0, 0, 3, 0, 0]]) + >>> index = torch.tensor([[0, 1, 2], [0, 1, 4]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(1, index, src) + tensor([[1, 2, 3, 0, 0], + [6, 7, 0, 0, 8], + [0, 0, 0, 0, 0]]) + + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='multiply') + tensor([[2.0000, 2.0000, 2.4600, 2.0000], + [2.0000, 2.0000, 2.0000, 2.4600]]) + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='add') + tensor([[2.0000, 2.0000, 3.2300, 2.0000], + [2.0000, 2.0000, 2.0000, 3.2300]]) + + .. function:: scatter_(dim, index, value, *, reduce=None) -> Tensor: + :noindex: + + Writes the value from :attr:`value` into :attr:`self` at the indices + specified in the :attr:`index` tensor. This operation is equivalent to the previous version, + with the :attr:`src` tensor filled entirely with :attr:`value`. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + value (Scalar): the value to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> index = torch.tensor([[0, 1]]) + >>> value = 2 + >>> torch.zeros(3, 5).scatter_(0, index, value) + tensor([[2., 0., 0., 0., 0.], + [0., 2., 0., 0., 0.], + [0., 0., 0., 0., 0.]]) + """ + + @overload + def scatter_( + self, + dim: _int, + index: Tensor, + value: Number | _complex | PySymType, + *, + reduce: str, + ) -> Tensor: + r""" + scatter_(dim, index, src, *, reduce=None) -> Tensor + + Writes all values from the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index` tensor. For each value in :attr:`src`, its output + index is specified by its index in :attr:`src` for ``dimension != dim`` and by + the corresponding value in :attr:`index` for ``dimension = dim``. + + For a 3-D tensor, :attr:`self` is updated as:: + + self[index[i][j][k]][j][k] = src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] = src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] = src[i][j][k] # if dim == 2 + + This is the reverse operation of the manner described in :meth:`~Tensor.gather`. + + It is also required that + ``index.size(d) <= src.size(d)`` for all dimensions ``d``, and that + ``index.size(d) <= self.size(d)`` for all dimensions ``d != dim``. + Note that ``input`` and ``index`` do not broadcast against each other for NPUs, + so when running on NPUs, :attr:`input` and :attr:`index` must have the same number of dimensions. + Standard broadcasting occurs in all other cases. + + Moreover, as for :meth:`~Tensor.gather`, the values of :attr:`index` must be + between ``0`` and ``self.size(dim) - 1`` inclusive. + + .. warning:: + + When indices are not unique, the behavior is non-deterministic (one of the + values from ``src`` will be picked arbitrarily) and the gradient will be + incorrect (it will be propagated to all locations in the source that + correspond to the same index)! + + .. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + + Additionally accepts an optional :attr:`reduce` argument that allows + specification of an optional reduction operation, which is applied to all + values in the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index`. For each value in :attr:`src`, the reduction + operation is applied to an index in :attr:`self` which is specified by + its index in :attr:`src` for ``dimension != dim`` and by the corresponding + value in :attr:`index` for ``dimension = dim``. + + Given a 3-D tensor and reduction using the multiplication operation, :attr:`self` + is updated as:: + + self[index[i][j][k]][j][k] *= src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] *= src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] *= src[i][j][k] # if dim == 2 + + Reducing with the addition operation is the same as using + :meth:`~torch.Tensor.scatter_add_`. + + .. warning:: + The reduce argument with Tensor ``src`` is deprecated and will be removed in + a future PyTorch release. Please use :meth:`~torch.Tensor.scatter_reduce_` + instead for more reduction options. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + src (Tensor): the source element(s) to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> src = torch.arange(1, 11).reshape((2, 5)) + >>> src + tensor([[ 1, 2, 3, 4, 5], + [ 6, 7, 8, 9, 10]]) + >>> index = torch.tensor([[0, 1, 2, 0]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(0, index, src) + tensor([[1, 0, 0, 4, 0], + [0, 2, 0, 0, 0], + [0, 0, 3, 0, 0]]) + >>> index = torch.tensor([[0, 1, 2], [0, 1, 4]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(1, index, src) + tensor([[1, 2, 3, 0, 0], + [6, 7, 0, 0, 8], + [0, 0, 0, 0, 0]]) + + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='multiply') + tensor([[2.0000, 2.0000, 2.4600, 2.0000], + [2.0000, 2.0000, 2.0000, 2.4600]]) + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='add') + tensor([[2.0000, 2.0000, 3.2300, 2.0000], + [2.0000, 2.0000, 2.0000, 3.2300]]) + + .. function:: scatter_(dim, index, value, *, reduce=None) -> Tensor: + :noindex: + + Writes the value from :attr:`value` into :attr:`self` at the indices + specified in the :attr:`index` tensor. This operation is equivalent to the previous version, + with the :attr:`src` tensor filled entirely with :attr:`value`. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + value (Scalar): the value to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> index = torch.tensor([[0, 1]]) + >>> value = 2 + >>> torch.zeros(3, 5).scatter_(0, index, value) + tensor([[2., 0., 0., 0., 0.], + [0., 2., 0., 0., 0.], + [0., 0., 0., 0., 0.]]) + """ + + @overload + def scatter_( + self, + dim: _int, + index: Tensor, + value: Number | _complex | PySymType, + ) -> Tensor: + r""" + scatter_(dim, index, src, *, reduce=None) -> Tensor + + Writes all values from the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index` tensor. For each value in :attr:`src`, its output + index is specified by its index in :attr:`src` for ``dimension != dim`` and by + the corresponding value in :attr:`index` for ``dimension = dim``. + + For a 3-D tensor, :attr:`self` is updated as:: + + self[index[i][j][k]][j][k] = src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] = src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] = src[i][j][k] # if dim == 2 + + This is the reverse operation of the manner described in :meth:`~Tensor.gather`. + + It is also required that + ``index.size(d) <= src.size(d)`` for all dimensions ``d``, and that + ``index.size(d) <= self.size(d)`` for all dimensions ``d != dim``. + Note that ``input`` and ``index`` do not broadcast against each other for NPUs, + so when running on NPUs, :attr:`input` and :attr:`index` must have the same number of dimensions. + Standard broadcasting occurs in all other cases. + + Moreover, as for :meth:`~Tensor.gather`, the values of :attr:`index` must be + between ``0`` and ``self.size(dim) - 1`` inclusive. + + .. warning:: + + When indices are not unique, the behavior is non-deterministic (one of the + values from ``src`` will be picked arbitrarily) and the gradient will be + incorrect (it will be propagated to all locations in the source that + correspond to the same index)! + + .. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + + Additionally accepts an optional :attr:`reduce` argument that allows + specification of an optional reduction operation, which is applied to all + values in the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index`. For each value in :attr:`src`, the reduction + operation is applied to an index in :attr:`self` which is specified by + its index in :attr:`src` for ``dimension != dim`` and by the corresponding + value in :attr:`index` for ``dimension = dim``. + + Given a 3-D tensor and reduction using the multiplication operation, :attr:`self` + is updated as:: + + self[index[i][j][k]][j][k] *= src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] *= src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] *= src[i][j][k] # if dim == 2 + + Reducing with the addition operation is the same as using + :meth:`~torch.Tensor.scatter_add_`. + + .. warning:: + The reduce argument with Tensor ``src`` is deprecated and will be removed in + a future PyTorch release. Please use :meth:`~torch.Tensor.scatter_reduce_` + instead for more reduction options. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + src (Tensor): the source element(s) to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> src = torch.arange(1, 11).reshape((2, 5)) + >>> src + tensor([[ 1, 2, 3, 4, 5], + [ 6, 7, 8, 9, 10]]) + >>> index = torch.tensor([[0, 1, 2, 0]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(0, index, src) + tensor([[1, 0, 0, 4, 0], + [0, 2, 0, 0, 0], + [0, 0, 3, 0, 0]]) + >>> index = torch.tensor([[0, 1, 2], [0, 1, 4]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_(1, index, src) + tensor([[1, 2, 3, 0, 0], + [6, 7, 0, 0, 8], + [0, 0, 0, 0, 0]]) + + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='multiply') + tensor([[2.0000, 2.0000, 2.4600, 2.0000], + [2.0000, 2.0000, 2.0000, 2.4600]]) + >>> torch.full((2, 4), 2.).scatter_(1, torch.tensor([[2], [3]]), + ... 1.23, reduce='add') + tensor([[2.0000, 2.0000, 3.2300, 2.0000], + [2.0000, 2.0000, 2.0000, 3.2300]]) + + .. function:: scatter_(dim, index, value, *, reduce=None) -> Tensor: + :noindex: + + Writes the value from :attr:`value` into :attr:`self` at the indices + specified in the :attr:`index` tensor. This operation is equivalent to the previous version, + with the :attr:`src` tensor filled entirely with :attr:`value`. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter, can be either empty + or of the same dimensionality as ``src``. When empty, the operation + returns ``self`` unchanged. + value (Scalar): the value to scatter. + + Keyword args: + reduce (str, optional): reduction operation to apply, can be either + ``'add'`` or ``'multiply'``. + + Example:: + + >>> index = torch.tensor([[0, 1]]) + >>> value = 2 + >>> torch.zeros(3, 5).scatter_(0, index, value) + tensor([[2., 0., 0., 0., 0.], + [0., 2., 0., 0., 0.], + [0., 0., 0., 0., 0.]]) + """ + + def scatter_add(self, dim: _int, index: Tensor, src: Tensor) -> Tensor: + r""" + scatter_add(dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_add_` + """ + + def scatter_add_(self, dim: _int, index: Tensor, src: Tensor) -> Tensor: + r""" + scatter_add_(dim, index, src) -> Tensor + + Adds all values from the tensor :attr:`src` into :attr:`self` at the indices + specified in the :attr:`index` tensor in a similar fashion as + :meth:`~torch.Tensor.scatter_`. For each value in :attr:`src`, it is added to + an index in :attr:`self` which is specified by its index in :attr:`src` + for ``dimension != dim`` and by the corresponding value in :attr:`index` for + ``dimension = dim``. + + For a 3-D tensor, :attr:`self` is updated as:: + + self[index[i][j][k]][j][k] += src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] += src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] += src[i][j][k] # if dim == 2 + + :attr:`self`, :attr:`index` and :attr:`src` should have same number of + dimensions. It is also required that ``index.size(d) <= src.size(d)`` for all + dimensions ``d``, and that ``index.size(d) <= self.size(d)`` for all dimensions + ``d != dim``. Note that ``index`` and ``src`` do not broadcast. + When :attr:`index` is empty, we always return the original tensor + without further error checking. + + Note: + This operation may behave nondeterministically when given tensors on a CUDA device. See :doc:`/notes/randomness` for more information. + + .. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter and add, can be + either empty or of the same dimensionality as ``src``. When empty, the + operation returns ``self`` unchanged. + src (Tensor): the source elements to scatter and add + + Example:: + + >>> src = torch.ones((2, 5)) + >>> index = torch.tensor([[0, 1, 2, 0, 0]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_add_(0, index, src) + tensor([[1., 0., 0., 1., 1.], + [0., 1., 0., 0., 0.], + [0., 0., 1., 0., 0.]]) + >>> index = torch.tensor([[0, 1, 2, 0, 0], [0, 1, 2, 2, 2]]) + >>> torch.zeros(3, 5, dtype=src.dtype).scatter_add_(0, index, src) + tensor([[2., 0., 0., 1., 1.], + [0., 2., 0., 0., 0.], + [0., 0., 2., 1., 1.]]) + """ + + def scatter_reduce( + self, + dim: _int, + index: Tensor, + src: Tensor, + reduce: str, + *, + include_self: _bool = True, + ) -> Tensor: + r""" + scatter_reduce(dim, index, src, reduce, *, include_self=True) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_reduce_` + """ + + def scatter_reduce_( + self, + dim: _int, + index: Tensor, + src: Tensor, + reduce: str, + *, + include_self: _bool = True, + ) -> Tensor: + r""" + scatter_reduce_(dim, index, src, reduce, *, include_self=True) -> Tensor + + Reduces all values from the :attr:`src` tensor to the indices specified in + the :attr:`index` tensor in the :attr:`self` tensor using the applied reduction + defined via the :attr:`reduce` argument (:obj:`"sum"`, :obj:`"prod"`, :obj:`"mean"`, + :obj:`"amax"`, :obj:`"amin"`). For each value in :attr:`src`, it is reduced to an + index in :attr:`self` which is specified by its index in :attr:`src` for + ``dimension != dim`` and by the corresponding value in :attr:`index` for + ``dimension = dim``. If :obj:`include_self="True"`, the values in the :attr:`self` + tensor are included in the reduction. + + :attr:`self`, :attr:`index` and :attr:`src` should all have + the same number of dimensions. It is also required that + ``index.size(d) <= src.size(d)`` for all dimensions ``d``, and that + ``index.size(d) <= self.size(d)`` for all dimensions ``d != dim``. + Note that ``index`` and ``src`` do not broadcast. + + For a 3-D tensor with :obj:`reduce="sum"` and :obj:`include_self=True` the + output is given as:: + + self[index[i][j][k]][j][k] += src[i][j][k] # if dim == 0 + self[i][index[i][j][k]][k] += src[i][j][k] # if dim == 1 + self[i][j][index[i][j][k]] += src[i][j][k] # if dim == 2 + + Note: + This operation may behave nondeterministically when given tensors on a CUDA device. See :doc:`/notes/randomness` for more information. + + .. note:: + + The backward pass is implemented only for ``src.shape == index.shape``. + + .. warning:: + + This function is in beta and may change in the near future. + + Args: + dim (int): the axis along which to index + index (LongTensor): the indices of elements to scatter and reduce. + src (Tensor): the source elements to scatter and reduce + reduce (str): the reduction operation to apply for non-unique indices + (:obj:`"sum"`, :obj:`"prod"`, :obj:`"mean"`, :obj:`"amax"`, :obj:`"amin"`) + include_self (bool): whether elements from the :attr:`self` tensor are + included in the reduction + + Example:: + + >>> src = torch.tensor([1., 2., 3., 4., 5., 6.]) + >>> index = torch.tensor([0, 1, 0, 1, 2, 1]) + >>> input = torch.tensor([1., 2., 3., 4.]) + >>> input.scatter_reduce(0, index, src, reduce="sum") + tensor([5., 14., 8., 4.]) + >>> input.scatter_reduce(0, index, src, reduce="sum", include_self=False) + tensor([4., 12., 5., 4.]) + >>> input2 = torch.tensor([5., 4., 3., 2.]) + >>> input2.scatter_reduce(0, index, src, reduce="amax") + tensor([5., 6., 5., 2.]) + >>> input2.scatter_reduce(0, index, src, reduce="amax", include_self=False) + tensor([3., 6., 5., 2.]) + """ + + def select(self, dim: _int, index: _int | SymInt) -> Tensor: + r""" + select(dim, index) -> Tensor + + See :func:`torch.select` + """ + + def select_scatter( + self, + src: Tensor, + dim: _int, + index: _int | SymInt, + ) -> Tensor: + r""" + select_scatter(src, dim, index) -> Tensor + + See :func:`torch.select_scatter` + """ + + @overload + def set_( + self, + source: Storage | TypedStorage | UntypedStorage, + storage_offset: IntLikeType, + size: _symsize, + stride: _symsize, + ) -> Tensor: + r""" + set_(source=None, storage_offset=0, size=None, stride=None) -> Tensor + + Sets the underlying storage, size, and strides. If :attr:`source` is a tensor, + :attr:`self` tensor will share the same storage and have the same size and + strides as :attr:`source`. Changes to elements in one tensor will be reflected + in the other. + + If :attr:`source` is a :class:`~torch.Storage`, the method sets the underlying + storage, offset, size, and stride. + + Args: + source (Tensor or Storage): the tensor or storage to use + storage_offset (int, optional): the offset in the storage + size (torch.Size, optional): the desired size. Defaults to the size of the source. + stride (tuple, optional): the desired stride. Defaults to C-contiguous strides. + """ + + @overload + def set_(self, source: Storage | TypedStorage | UntypedStorage) -> Tensor: + r""" + set_(source=None, storage_offset=0, size=None, stride=None) -> Tensor + + Sets the underlying storage, size, and strides. If :attr:`source` is a tensor, + :attr:`self` tensor will share the same storage and have the same size and + strides as :attr:`source`. Changes to elements in one tensor will be reflected + in the other. + + If :attr:`source` is a :class:`~torch.Storage`, the method sets the underlying + storage, offset, size, and stride. + + Args: + source (Tensor or Storage): the tensor or storage to use + storage_offset (int, optional): the offset in the storage + size (torch.Size, optional): the desired size. Defaults to the size of the source. + stride (tuple, optional): the desired stride. Defaults to C-contiguous strides. + """ + + def sgn(self) -> Tensor: + r""" + sgn() -> Tensor + + See :func:`torch.sgn` + """ + + def sgn_(self) -> Tensor: + r""" + sgn_() -> Tensor + + In-place version of :meth:`~Tensor.sgn` + """ + + def short(self) -> Tensor: + r""" + short(memory_format=torch.preserve_format) -> Tensor + + ``self.short()`` is equivalent to ``self.to(torch.int16)``. See :func:`to`. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def sigmoid(self) -> Tensor: + r""" + sigmoid() -> Tensor + + See :func:`torch.sigmoid` + """ + + def sigmoid_(self) -> Tensor: + r""" + sigmoid_() -> Tensor + + In-place version of :meth:`~Tensor.sigmoid` + """ + + def sign(self) -> Tensor: + r""" + sign() -> Tensor + + See :func:`torch.sign` + """ + + def sign_(self) -> Tensor: + r""" + sign_() -> Tensor + + In-place version of :meth:`~Tensor.sign` + """ + + def signbit(self) -> Tensor: + r""" + signbit() -> Tensor + + See :func:`torch.signbit` + """ + + def sin(self) -> Tensor: + r""" + sin() -> Tensor + + See :func:`torch.sin` + """ + + def sin_(self) -> Tensor: + r""" + sin_() -> Tensor + + In-place version of :meth:`~Tensor.sin` + """ + + def sinc(self) -> Tensor: + r""" + sinc() -> Tensor + + See :func:`torch.sinc` + """ + + def sinc_(self) -> Tensor: + r""" + sinc_() -> Tensor + + In-place version of :meth:`~Tensor.sinc` + """ + + def sinh(self) -> Tensor: + r""" + sinh() -> Tensor + + See :func:`torch.sinh` + """ + + def sinh_(self) -> Tensor: + r""" + sinh_() -> Tensor + + In-place version of :meth:`~Tensor.sinh` + """ + + @overload + def size(self, dim: None = None) -> Size: + r""" + size(dim=None) -> torch.Size or int + + Returns the size of the :attr:`self` tensor. If ``dim`` is not specified, + the returned value is a :class:`torch.Size`, a subclass of :class:`tuple`. + If ``dim`` is specified, returns an int holding the size of that dimension. + + Args: + dim (int, optional): The dimension for which to retrieve the size. + + Example:: + + >>> t = torch.empty(3, 4, 5) + >>> t.size() + torch.Size([3, 4, 5]) + >>> t.size(dim=1) + 4 + """ + + @overload + def size(self, dim: _int) -> _int: + r""" + size(dim=None) -> torch.Size or int + + Returns the size of the :attr:`self` tensor. If ``dim`` is not specified, + the returned value is a :class:`torch.Size`, a subclass of :class:`tuple`. + If ``dim`` is specified, returns an int holding the size of that dimension. + + Args: + dim (int, optional): The dimension for which to retrieve the size. + + Example:: + + >>> t = torch.empty(3, 4, 5) + >>> t.size() + torch.Size([3, 4, 5]) + >>> t.size(dim=1) + 4 + """ + + def slice_inverse( + self, + src: Tensor, + dim: _int = 0, + start: _int | SymInt | None = None, + end: _int | SymInt | None = None, + step: _int | SymInt = 1, + ) -> Tensor: ... + def slice_scatter( + self, + src: Tensor, + dim: _int = 0, + start: _int | SymInt | None = None, + end: _int | SymInt | None = None, + step: _int | SymInt = 1, + ) -> Tensor: + r""" + slice_scatter(src, dim=0, start=None, end=None, step=1) -> Tensor + + See :func:`torch.slice_scatter` + """ + + def slogdet(self) -> torch.return_types.slogdet: + r""" + slogdet() -> (Tensor, Tensor) + + See :func:`torch.slogdet` + """ + + def smm(self, mat2: Tensor) -> Tensor: + r""" + smm(mat) -> Tensor + + See :func:`torch.smm` + """ + + def softmax(self, dim: _int, dtype: _dtype | None = None) -> Tensor: + r""" + softmax(dim) -> Tensor + + Alias for :func:`torch.nn.functional.softmax`. + """ + + @overload + def sort( + self, + *, + stable: _bool | None, + dim: _int = -1, + descending: _bool = False, + ) -> torch.return_types.sort: + r""" + sort(dim=-1, descending=False) -> (Tensor, LongTensor) + + See :func:`torch.sort` + """ + + @overload + def sort( + self, + dim: _int = -1, + descending: _bool = False, + ) -> torch.return_types.sort: + r""" + sort(dim=-1, descending=False) -> (Tensor, LongTensor) + + See :func:`torch.sort` + """ + + def sparse_dim(self) -> _int: + r""" + sparse_dim() -> int + + Return the number of sparse dimensions in a :ref:`sparse tensor ` :attr:`self`. + + .. note:: + Returns ``0`` if :attr:`self` is not a sparse tensor. + + See also :meth:`Tensor.dense_dim` and :ref:`hybrid tensors `. + """ + + def sparse_mask(self, mask: Tensor) -> Tensor: + r""" + sparse_mask(mask) -> Tensor + + Returns a new :ref:`sparse tensor ` with values from a + strided tensor :attr:`self` filtered by the indices of the sparse + tensor :attr:`mask`. The values of :attr:`mask` sparse tensor are + ignored. :attr:`self` and :attr:`mask` tensors must have the same + shape. + + .. note:: + + The returned sparse tensor might contain duplicate values if :attr:`mask` + is not coalesced. It is therefore advisable to pass ``mask.coalesce()`` + if such behavior is not desired. + + .. note:: + + The returned sparse tensor has the same indices as the sparse tensor + :attr:`mask`, even when the corresponding values in :attr:`self` are + zeros. + + Args: + mask (Tensor): a sparse tensor whose indices are used as a filter + + Example:: + + >>> nse = 5 + >>> dims = (5, 5, 2, 2) + >>> I = torch.cat([torch.randint(0, dims[0], size=(nse,)), + ... torch.randint(0, dims[1], size=(nse,))], 0).reshape(2, nse) + >>> V = torch.randn(nse, dims[2], dims[3]) + >>> S = torch.sparse_coo_tensor(I, V, dims).coalesce() + >>> D = torch.randn(dims) + >>> D.sparse_mask(S) + tensor(indices=tensor([[0, 0, 0, 2], + [0, 1, 4, 3]]), + values=tensor([[[ 1.6550, 0.2397], + [-0.1611, -0.0779]], + + [[ 0.2326, -1.0558], + [ 1.4711, 1.9678]], + + [[-0.5138, -0.0411], + [ 1.9417, 0.5158]], + + [[ 0.0793, 0.0036], + [-0.2569, -0.1055]]]), + size=(5, 5, 2, 2), nnz=4, layout=torch.sparse_coo) + """ + + def sparse_resize_( + self, + size: _size, + sparse_dim: _int, + dense_dim: _int, + ) -> Tensor: + r""" + sparse_resize_(size, sparse_dim, dense_dim) -> Tensor + + Resizes :attr:`self` :ref:`sparse tensor ` to the desired + size and the number of sparse and dense dimensions. + + .. note:: + If the number of specified elements in :attr:`self` is zero, then + :attr:`size`, :attr:`sparse_dim`, and :attr:`dense_dim` can be any + size and positive integers such that ``len(size) == sparse_dim + + dense_dim``. + + If :attr:`self` specifies one or more elements, however, then each + dimension in :attr:`size` must not be smaller than the corresponding + dimension of :attr:`self`, :attr:`sparse_dim` must equal the number + of sparse dimensions in :attr:`self`, and :attr:`dense_dim` must + equal the number of dense dimensions in :attr:`self`. + + .. warning:: + Throws an error if :attr:`self` is not a sparse tensor. + + Args: + size (torch.Size): the desired size. If :attr:`self` is non-empty + sparse tensor, the desired size cannot be smaller than the + original size. + sparse_dim (int): the number of sparse dimensions + dense_dim (int): the number of dense dimensions + """ + + def sparse_resize_and_clear_( + self, + size: _size, + sparse_dim: _int, + dense_dim: _int, + ) -> Tensor: + r""" + sparse_resize_and_clear_(size, sparse_dim, dense_dim) -> Tensor + + Removes all specified elements from a :ref:`sparse tensor + ` :attr:`self` and resizes :attr:`self` to the desired + size and the number of sparse and dense dimensions. + + .. warning: + Throws an error if :attr:`self` is not a sparse tensor. + + Args: + size (torch.Size): the desired size. + sparse_dim (int): the number of sparse dimensions + dense_dim (int): the number of dense dimensions + """ + + @overload + def split(self, split_size: _int, dim: _int = 0) -> Sequence[Tensor]: ... + @overload + def split( + self, + split_size: tuple[_int, ...], + dim: _int = 0, + ) -> Sequence[Tensor]: ... + def split_with_sizes( + self, + split_sizes: Sequence[_int | SymInt], + dim: _int = 0, + ) -> tuple[Tensor, ...]: ... + def sqrt(self) -> Tensor: + r""" + sqrt() -> Tensor + + See :func:`torch.sqrt` + """ + + def sqrt_(self) -> Tensor: + r""" + sqrt_() -> Tensor + + In-place version of :meth:`~Tensor.sqrt` + """ + + def square(self) -> Tensor: + r""" + square() -> Tensor + + See :func:`torch.square` + """ + + def square_(self) -> Tensor: + r""" + square_() -> Tensor + + In-place version of :meth:`~Tensor.square` + """ + + @overload + def squeeze(self) -> Tensor: + r""" + squeeze(dim=None) -> Tensor + + See :func:`torch.squeeze` + """ + + @overload + def squeeze(self, dim: _int) -> Tensor: + r""" + squeeze(dim=None) -> Tensor + + See :func:`torch.squeeze` + """ + + @overload + def squeeze(self, dim: _size) -> Tensor: + r""" + squeeze(dim=None) -> Tensor + + See :func:`torch.squeeze` + """ + + @overload + def squeeze(self, *dim: _int) -> Tensor: + r""" + squeeze(dim=None) -> Tensor + + See :func:`torch.squeeze` + """ + + @overload + def squeeze_(self) -> Tensor: + r""" + squeeze_(dim=None) -> Tensor + + In-place version of :meth:`~Tensor.squeeze` + """ + + @overload + def squeeze_(self, dim: _int) -> Tensor: + r""" + squeeze_(dim=None) -> Tensor + + In-place version of :meth:`~Tensor.squeeze` + """ + + @overload + def squeeze_(self, dim: _size) -> Tensor: + r""" + squeeze_(dim=None) -> Tensor + + In-place version of :meth:`~Tensor.squeeze` + """ + + @overload + def squeeze_(self, *dim: _int) -> Tensor: + r""" + squeeze_(dim=None) -> Tensor + + In-place version of :meth:`~Tensor.squeeze` + """ + + def sspaddmm( + self, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + sspaddmm(mat1, mat2, *, beta=1, alpha=1) -> Tensor + + See :func:`torch.sspaddmm` + """ + + @overload + def std( + self, + dim: _int | _size | None, + unbiased: _bool = True, + keepdim: _bool = False, + ) -> Tensor: + r""" + std(dim=None, *, correction=1, keepdim=False) -> Tensor + + See :func:`torch.std` + """ + + @overload + def std( + self, + dim: _int | _size | None = None, + *, + correction: Number | _complex | PySymType | None = None, + keepdim: _bool = False, + ) -> Tensor: + r""" + std(dim=None, *, correction=1, keepdim=False) -> Tensor + + See :func:`torch.std` + """ + + @overload + def std(self, unbiased: _bool = True) -> Tensor: + r""" + std(dim=None, *, correction=1, keepdim=False) -> Tensor + + See :func:`torch.std` + """ + + def untyped_storage(self) -> UntypedStorage: ... + def storage_offset(self) -> _int | SymInt: + r""" + storage_offset() -> int + + Returns :attr:`self` tensor's offset in the underlying storage in terms of + number of storage elements (not bytes). + + Example:: + + >>> x = torch.tensor([1, 2, 3, 4, 5]) + >>> x.storage_offset() + 0 + >>> x[3:].storage_offset() + 3 + """ + + def storage_type(self) -> Storage: ... + @overload + def stride(self, dim: None = None) -> tuple[_int, ...]: + r""" + stride(dim) -> tuple or int + + Returns the stride of :attr:`self` tensor. + + Stride is the jump necessary to go from one element to the next one in the + specified dimension :attr:`dim`. A tuple of all strides is returned when no + argument is passed in. Otherwise, an integer value is returned as the stride in + the particular dimension :attr:`dim`. + + Args: + dim (int, optional): the desired dimension in which stride is required + + Example:: + + >>> x = torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) + >>> x.stride() + (5, 1) + >>> x.stride(0) + 5 + >>> x.stride(-1) + 1 + """ + + @overload + def stride(self, dim: _int) -> _int: + r""" + stride(dim) -> tuple or int + + Returns the stride of :attr:`self` tensor. + + Stride is the jump necessary to go from one element to the next one in the + specified dimension :attr:`dim`. A tuple of all strides is returned when no + argument is passed in. Otherwise, an integer value is returned as the stride in + the particular dimension :attr:`dim`. + + Args: + dim (int, optional): the desired dimension in which stride is required + + Example:: + + >>> x = torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) + >>> x.stride() + (5, 1) + >>> x.stride(0) + 5 + >>> x.stride(-1) + 1 + """ + + def sub( + self, + other: Tensor | Number | _complex | torch.SymInt | torch.SymFloat, + *, + alpha: Number | _complex | None = 1, + out: Tensor | None = None, + ) -> Tensor: + r""" + sub(other, *, alpha=1) -> Tensor + + See :func:`torch.sub`. + """ + + def sub_( + self, + other: Tensor | Number | _complex | torch.SymInt | torch.SymFloat, + *, + alpha: Number | _complex | None = 1, + ) -> Tensor: + r""" + sub_(other, *, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.sub` + """ + + @overload + def subtract( + self, + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + subtract(other, *, alpha=1) -> Tensor + + See :func:`torch.subtract`. + """ + + @overload + def subtract( + self, + other: Number | _complex | PySymType, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + subtract(other, *, alpha=1) -> Tensor + + See :func:`torch.subtract`. + """ + + @overload + def subtract_( + self, + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + subtract_(other, *, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.subtract`. + """ + + @overload + def subtract_( + self, + other: Number | _complex | PySymType, + alpha: Number | _complex | PySymType = 1, + ) -> Tensor: + r""" + subtract_(other, *, alpha=1) -> Tensor + + In-place version of :meth:`~Tensor.subtract`. + """ + + @overload + def sum(self, *, dtype: _dtype | None = None) -> Tensor: + r""" + sum(dim=None, keepdim=False, dtype=None) -> Tensor + + See :func:`torch.sum` + """ + + @overload + def sum( + self, + dim: _int | _size | None, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, + ) -> Tensor: + r""" + sum(dim=None, keepdim=False, dtype=None) -> Tensor + + See :func:`torch.sum` + """ + + @overload + def sum_to_size(self, size: Sequence[_int | SymInt]) -> Tensor: + r""" + sum_to_size(*size) -> Tensor + + Sum ``this`` tensor to :attr:`size`. + :attr:`size` must be broadcastable to ``this`` tensor size. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + """ + + @overload + def sum_to_size(self, *size: _int | SymInt) -> Tensor: + r""" + sum_to_size(*size) -> Tensor + + Sum ``this`` tensor to :attr:`size`. + :attr:`size` must be broadcastable to ``this`` tensor size. + + Args: + size (int...): a sequence of integers defining the shape of the output tensor. + """ + + def svd( + self, + some: _bool = True, + compute_uv: _bool = True, + ) -> torch.return_types.svd: + r""" + svd(some=True, compute_uv=True) -> (Tensor, Tensor, Tensor) + + See :func:`torch.svd` + """ + + def swapaxes(self, axis0: _int, axis1: _int) -> Tensor: + r""" + swapaxes(axis0, axis1) -> Tensor + + See :func:`torch.swapaxes` + """ + + def swapaxes_(self, axis0: _int, axis1: _int) -> Tensor: + r""" + swapaxes_(axis0, axis1) -> Tensor + + In-place version of :meth:`~Tensor.swapaxes` + """ + + def swapdims(self, dim0: _int, dim1: _int) -> Tensor: + r""" + swapdims(dim0, dim1) -> Tensor + + See :func:`torch.swapdims` + """ + + def swapdims_(self, dim0: _int, dim1: _int) -> Tensor: + r""" + swapdims_(dim0, dim1) -> Tensor + + In-place version of :meth:`~Tensor.swapdims` + """ + + def t(self) -> Tensor: + r""" + t() -> Tensor + + See :func:`torch.t` + """ + + def t_(self) -> Tensor: + r""" + t_() -> Tensor + + In-place version of :meth:`~Tensor.t` + """ + + def take(self, index: Tensor) -> Tensor: + r""" + take(indices) -> Tensor + + See :func:`torch.take` + """ + + def take_along_dim( + self, + indices: Tensor, + dim: _int | None = None, + ) -> Tensor: + r""" + take_along_dim(indices, dim) -> Tensor + + See :func:`torch.take_along_dim` + """ + + def tan(self) -> Tensor: + r""" + tan() -> Tensor + + See :func:`torch.tan` + """ + + def tan_(self) -> Tensor: + r""" + tan_() -> Tensor + + In-place version of :meth:`~Tensor.tan` + """ + + def tanh(self) -> Tensor: + r""" + tanh() -> Tensor + + See :func:`torch.tanh` + """ + + def tanh_(self) -> Tensor: + r""" + tanh_() -> Tensor + + In-place version of :meth:`~Tensor.tanh` + """ + + @overload + def tensor_split( + self, + indices: Sequence[_int | SymInt], + dim: _int = 0, + ) -> tuple[Tensor, ...]: + r""" + tensor_split(indices_or_sections, dim=0) -> List of Tensors + + See :func:`torch.tensor_split` + """ + + @overload + def tensor_split( + self, + tensor_indices_or_sections: Tensor, + dim: _int = 0, + ) -> tuple[Tensor, ...]: + r""" + tensor_split(indices_or_sections, dim=0) -> List of Tensors + + See :func:`torch.tensor_split` + """ + + @overload + def tensor_split( + self, + sections: _int | SymInt, + dim: _int = 0, + ) -> tuple[Tensor, ...]: + r""" + tensor_split(indices_or_sections, dim=0) -> List of Tensors + + See :func:`torch.tensor_split` + """ + + @overload + def tile(self, dims: Sequence[_int | SymInt]) -> Tensor: + r""" + tile(dims) -> Tensor + + See :func:`torch.tile` + """ + + @overload + def tile(self, *dims: _int | SymInt) -> Tensor: + r""" + tile(dims) -> Tensor + + See :func:`torch.tile` + """ + + @overload + def to( + self, + dtype: _dtype, + non_blocking: _bool = False, + copy: _bool = False, + *, + memory_format: torch.memory_format | None = None, + ) -> Tensor: + r""" + to(*args, **kwargs) -> Tensor + + Performs Tensor dtype and/or device conversion. A :class:`torch.dtype` and :class:`torch.device` are + inferred from the arguments of ``self.to(*args, **kwargs)``. + + .. note:: + + If the ``self`` Tensor already + has the correct :class:`torch.dtype` and :class:`torch.device`, then ``self`` is returned. + Otherwise, the returned tensor is a copy of ``self`` with the desired + :class:`torch.dtype` and :class:`torch.device`. + + .. note:: + + If ``self`` requires gradients (``requires_grad=True``) but the target + ``dtype`` specified is an integer type, the returned tensor will implicitly + set ``requires_grad=False``. This is because only tensors with + floating-point or complex dtypes can require gradients. + + Here are the ways to call ``to``: + + .. method:: to(dtype, non_blocking=False, copy=False, memory_format=torch.preserve_format) -> Tensor + :noindex: + + Returns a Tensor with the specified :attr:`dtype` + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + .. note:: + + According to `C++ type conversion rules `_, + converting floating point value to integer type will truncate the fractional part. + If the truncated value cannot fit into the target type (e.g., casting ``torch.inf`` to ``torch.long``), + the behavior is undefined and the result may vary across platforms. + + .. method:: to(device=None, dtype=None, non_blocking=False, copy=False, memory_format=torch.preserve_format) -> Tensor + :noindex: + + Returns a Tensor with the specified :attr:`device` and (optional) + :attr:`dtype`. If :attr:`dtype` is ``None`` it is inferred to be ``self.dtype``. + When :attr:`non_blocking` is set to ``True``, the function attempts to perform + the conversion asynchronously with respect to the host, if possible. This + asynchronous behavior applies to both pinned and pageable memory. However, + caution is advised when using this feature. For more information, refer to the + `tutorial on good usage of non_blocking and pin_memory `__. + When :attr:`copy` is set, a new Tensor is created even when the Tensor + already matches the desired conversion. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + .. method:: to(other, non_blocking=False, copy=False) -> Tensor + :noindex: + + Returns a Tensor with same :class:`torch.dtype` and :class:`torch.device` as + the Tensor :attr:`other`. + When :attr:`non_blocking` is set to ``True``, the function attempts to perform + the conversion asynchronously with respect to the host, if possible. This + asynchronous behavior applies to both pinned and pageable memory. However, + caution is advised when using this feature. For more information, refer to the + `tutorial on good usage of non_blocking and pin_memory `__. + When :attr:`copy` is set, a new Tensor is created even when the Tensor + already matches the desired conversion. + + .. note:: + + When :attr:`non_blocking` is ``True`` and the conversion is issued on + a non-default CUDA stream, the caller is responsible for proper + cross-stream synchronization. See :ref:`cuda-stream-semantics` for + the required pattern. + + Example:: + + >>> tensor = torch.randn(2, 2) # Initially dtype=float32, device=cpu + >>> tensor.to(torch.float64) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64) + + >>> cuda0 = torch.device('cuda:0') + >>> tensor.to(cuda0) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], device='cuda:0') + + >>> tensor.to(cuda0, dtype=torch.float64) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') + + >>> other = torch.randn((), dtype=torch.float64, device=cuda0) + >>> tensor.to(other, non_blocking=True) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') + """ + + @overload + def to( + self, + device: DeviceLikeType | None = None, + dtype: _dtype | None = None, + non_blocking: _bool = False, + copy: _bool = False, + *, + memory_format: torch.memory_format | None = None, + ) -> Tensor: + r""" + to(*args, **kwargs) -> Tensor + + Performs Tensor dtype and/or device conversion. A :class:`torch.dtype` and :class:`torch.device` are + inferred from the arguments of ``self.to(*args, **kwargs)``. + + .. note:: + + If the ``self`` Tensor already + has the correct :class:`torch.dtype` and :class:`torch.device`, then ``self`` is returned. + Otherwise, the returned tensor is a copy of ``self`` with the desired + :class:`torch.dtype` and :class:`torch.device`. + + .. note:: + + If ``self`` requires gradients (``requires_grad=True``) but the target + ``dtype`` specified is an integer type, the returned tensor will implicitly + set ``requires_grad=False``. This is because only tensors with + floating-point or complex dtypes can require gradients. + + Here are the ways to call ``to``: + + .. method:: to(dtype, non_blocking=False, copy=False, memory_format=torch.preserve_format) -> Tensor + :noindex: + + Returns a Tensor with the specified :attr:`dtype` + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + .. note:: + + According to `C++ type conversion rules `_, + converting floating point value to integer type will truncate the fractional part. + If the truncated value cannot fit into the target type (e.g., casting ``torch.inf`` to ``torch.long``), + the behavior is undefined and the result may vary across platforms. + + .. method:: to(device=None, dtype=None, non_blocking=False, copy=False, memory_format=torch.preserve_format) -> Tensor + :noindex: + + Returns a Tensor with the specified :attr:`device` and (optional) + :attr:`dtype`. If :attr:`dtype` is ``None`` it is inferred to be ``self.dtype``. + When :attr:`non_blocking` is set to ``True``, the function attempts to perform + the conversion asynchronously with respect to the host, if possible. This + asynchronous behavior applies to both pinned and pageable memory. However, + caution is advised when using this feature. For more information, refer to the + `tutorial on good usage of non_blocking and pin_memory `__. + When :attr:`copy` is set, a new Tensor is created even when the Tensor + already matches the desired conversion. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + .. method:: to(other, non_blocking=False, copy=False) -> Tensor + :noindex: + + Returns a Tensor with same :class:`torch.dtype` and :class:`torch.device` as + the Tensor :attr:`other`. + When :attr:`non_blocking` is set to ``True``, the function attempts to perform + the conversion asynchronously with respect to the host, if possible. This + asynchronous behavior applies to both pinned and pageable memory. However, + caution is advised when using this feature. For more information, refer to the + `tutorial on good usage of non_blocking and pin_memory `__. + When :attr:`copy` is set, a new Tensor is created even when the Tensor + already matches the desired conversion. + + .. note:: + + When :attr:`non_blocking` is ``True`` and the conversion is issued on + a non-default CUDA stream, the caller is responsible for proper + cross-stream synchronization. See :ref:`cuda-stream-semantics` for + the required pattern. + + Example:: + + >>> tensor = torch.randn(2, 2) # Initially dtype=float32, device=cpu + >>> tensor.to(torch.float64) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64) + + >>> cuda0 = torch.device('cuda:0') + >>> tensor.to(cuda0) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], device='cuda:0') + + >>> tensor.to(cuda0, dtype=torch.float64) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') + + >>> other = torch.randn((), dtype=torch.float64, device=cuda0) + >>> tensor.to(other, non_blocking=True) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') + """ + + @overload + def to( + self, + other: Tensor, + non_blocking: _bool = False, + copy: _bool = False, + *, + memory_format: torch.memory_format | None = None, + ) -> Tensor: + r""" + to(*args, **kwargs) -> Tensor + + Performs Tensor dtype and/or device conversion. A :class:`torch.dtype` and :class:`torch.device` are + inferred from the arguments of ``self.to(*args, **kwargs)``. + + .. note:: + + If the ``self`` Tensor already + has the correct :class:`torch.dtype` and :class:`torch.device`, then ``self`` is returned. + Otherwise, the returned tensor is a copy of ``self`` with the desired + :class:`torch.dtype` and :class:`torch.device`. + + .. note:: + + If ``self`` requires gradients (``requires_grad=True``) but the target + ``dtype`` specified is an integer type, the returned tensor will implicitly + set ``requires_grad=False``. This is because only tensors with + floating-point or complex dtypes can require gradients. + + Here are the ways to call ``to``: + + .. method:: to(dtype, non_blocking=False, copy=False, memory_format=torch.preserve_format) -> Tensor + :noindex: + + Returns a Tensor with the specified :attr:`dtype` + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + .. note:: + + According to `C++ type conversion rules `_, + converting floating point value to integer type will truncate the fractional part. + If the truncated value cannot fit into the target type (e.g., casting ``torch.inf`` to ``torch.long``), + the behavior is undefined and the result may vary across platforms. + + .. method:: to(device=None, dtype=None, non_blocking=False, copy=False, memory_format=torch.preserve_format) -> Tensor + :noindex: + + Returns a Tensor with the specified :attr:`device` and (optional) + :attr:`dtype`. If :attr:`dtype` is ``None`` it is inferred to be ``self.dtype``. + When :attr:`non_blocking` is set to ``True``, the function attempts to perform + the conversion asynchronously with respect to the host, if possible. This + asynchronous behavior applies to both pinned and pageable memory. However, + caution is advised when using this feature. For more information, refer to the + `tutorial on good usage of non_blocking and pin_memory `__. + When :attr:`copy` is set, a new Tensor is created even when the Tensor + already matches the desired conversion. + + Args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + .. method:: to(other, non_blocking=False, copy=False) -> Tensor + :noindex: + + Returns a Tensor with same :class:`torch.dtype` and :class:`torch.device` as + the Tensor :attr:`other`. + When :attr:`non_blocking` is set to ``True``, the function attempts to perform + the conversion asynchronously with respect to the host, if possible. This + asynchronous behavior applies to both pinned and pageable memory. However, + caution is advised when using this feature. For more information, refer to the + `tutorial on good usage of non_blocking and pin_memory `__. + When :attr:`copy` is set, a new Tensor is created even when the Tensor + already matches the desired conversion. + + .. note:: + + When :attr:`non_blocking` is ``True`` and the conversion is issued on + a non-default CUDA stream, the caller is responsible for proper + cross-stream synchronization. See :ref:`cuda-stream-semantics` for + the required pattern. + + Example:: + + >>> tensor = torch.randn(2, 2) # Initially dtype=float32, device=cpu + >>> tensor.to(torch.float64) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64) + + >>> cuda0 = torch.device('cuda:0') + >>> tensor.to(cuda0) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], device='cuda:0') + + >>> tensor.to(cuda0, dtype=torch.float64) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') + + >>> other = torch.randn((), dtype=torch.float64, device=cuda0) + >>> tensor.to(other, non_blocking=True) + tensor([[-0.5044, 0.0005], + [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') + """ + + def to_dense( + self, + dtype: _dtype | None = None, + *, + masked_grad: _bool | None = None, + ) -> Tensor: + r""" + to_dense(dtype=None, *, masked_grad=True) -> Tensor + + Creates a strided copy of :attr:`self` if :attr:`self` is not a strided tensor, otherwise returns :attr:`self`. + + Keyword args: + {dtype} + masked_grad (bool, optional): If set to ``True`` (default) and + :attr:`self` has a sparse layout then the backward of + :meth:`to_dense` returns ``grad.sparse_mask(self)``. + + Example:: + + >>> s = torch.sparse_coo_tensor( + ... torch.tensor([[1, 1], + ... [0, 2]]), + ... torch.tensor([9, 10]), + ... size=(3, 3)) + >>> s.to_dense() + tensor([[ 0, 0, 0], + [ 9, 0, 10], + [ 0, 0, 0]]) + """ + + def to_mkldnn(self, dtype: _dtype | None = None) -> Tensor: + r""" + to_mkldnn() -> Tensor + Returns a copy of the tensor in ``torch.mkldnn`` layout. + """ + + def to_padded_tensor( + self, + padding: _float, + output_size: Sequence[_int | SymInt] | None = None, + ) -> Tensor: + r""" + to_padded_tensor(padding, output_size=None) -> Tensor + See :func:`to_padded_tensor` + """ + + @overload + def to_sparse( + self, + *, + layout: _layout | None = None, + blocksize: _int | _size | None = None, + dense_dim: _int | None = None, + ) -> Tensor: + r""" + to_sparse(sparseDims) -> Tensor + + Returns a sparse copy of the tensor. PyTorch supports sparse tensors in + :ref:`coordinate format `. + + Args: + sparseDims (int, optional): the number of sparse dimensions to include in the new sparse tensor + + Example:: + + >>> d = torch.tensor([[0, 0, 0], [9, 0, 10], [0, 0, 0]]) + >>> d + tensor([[ 0, 0, 0], + [ 9, 0, 10], + [ 0, 0, 0]]) + >>> d.to_sparse() + tensor(indices=tensor([[1, 1], + [0, 2]]), + values=tensor([ 9, 10]), + size=(3, 3), nnz=2, layout=torch.sparse_coo) + >>> d.to_sparse(1) + tensor(indices=tensor([[1]]), + values=tensor([[ 9, 0, 10]]), + size=(3, 3), nnz=1, layout=torch.sparse_coo) + + .. method:: to_sparse(*, layout=None, blocksize=None, dense_dim=None) -> Tensor + :noindex: + + Returns a sparse tensor with the specified layout and blocksize. If + the :attr:`self` is strided, the number of dense dimensions could be + specified, and a hybrid sparse tensor will be created, with + `dense_dim` dense dimensions and `self.dim() - 2 - dense_dim` batch + dimension. + + .. note:: If the :attr:`self` layout and blocksize parameters match + with the specified layout and blocksize, return + :attr:`self`. Otherwise, return a sparse tensor copy of + :attr:`self`. + + Args: + + layout (:class:`torch.layout`, optional): The desired sparse + layout. One of ``torch.sparse_coo``, ``torch.sparse_csr``, + ``torch.sparse_csc``, ``torch.sparse_bsr``, or + ``torch.sparse_bsc``. Default: if ``None``, + ``torch.sparse_coo``. + + blocksize (list, tuple, :class:`torch.Size`, optional): Block size + of the resulting BSR or BSC tensor. For other layouts, + specifying the block size that is not ``None`` will result in a + RuntimeError exception. A block size must be a tuple of length + two such that its items evenly divide the two sparse dimensions. + + dense_dim (int, optional): Number of dense dimensions of the + resulting CSR, CSC, BSR or BSC tensor. This argument should be + used only if :attr:`self` is a strided tensor, and must be a + value between 0 and dimension of :attr:`self` tensor minus two. + + Example:: + + >>> x = torch.tensor([[1, 0], [0, 0], [2, 3]]) + >>> x.to_sparse(layout=torch.sparse_coo) + tensor(indices=tensor([[0, 2, 2], + [0, 0, 1]]), + values=tensor([1, 2, 3]), + size=(3, 2), nnz=3, layout=torch.sparse_coo) + >>> x.to_sparse(layout=torch.sparse_bsr, blocksize=(1, 2)) + tensor(crow_indices=tensor([0, 1, 1, 2]), + col_indices=tensor([0, 0]), + values=tensor([[[1, 0]], + [[2, 3]]]), size=(3, 2), nnz=2, layout=torch.sparse_bsr) + >>> x.to_sparse(layout=torch.sparse_bsr, blocksize=(2, 1)) + RuntimeError: Tensor size(-2) 3 needs to be divisible by blocksize[0] 2 + >>> x.to_sparse(layout=torch.sparse_csr, blocksize=(3, 1)) + RuntimeError: to_sparse for Strided to SparseCsr conversion does not use specified blocksize + + >>> x = torch.tensor([[[1], [0]], [[0], [0]], [[2], [3]]]) + >>> x.to_sparse(layout=torch.sparse_csr, dense_dim=1) + tensor(crow_indices=tensor([0, 1, 1, 3]), + col_indices=tensor([0, 0, 1]), + values=tensor([[1], + [2], + [3]]), size=(3, 2, 1), nnz=3, layout=torch.sparse_csr) + """ + + @overload + def to_sparse(self, sparse_dim: _int) -> Tensor: + r""" + to_sparse(sparseDims) -> Tensor + + Returns a sparse copy of the tensor. PyTorch supports sparse tensors in + :ref:`coordinate format `. + + Args: + sparseDims (int, optional): the number of sparse dimensions to include in the new sparse tensor + + Example:: + + >>> d = torch.tensor([[0, 0, 0], [9, 0, 10], [0, 0, 0]]) + >>> d + tensor([[ 0, 0, 0], + [ 9, 0, 10], + [ 0, 0, 0]]) + >>> d.to_sparse() + tensor(indices=tensor([[1, 1], + [0, 2]]), + values=tensor([ 9, 10]), + size=(3, 3), nnz=2, layout=torch.sparse_coo) + >>> d.to_sparse(1) + tensor(indices=tensor([[1]]), + values=tensor([[ 9, 0, 10]]), + size=(3, 3), nnz=1, layout=torch.sparse_coo) + + .. method:: to_sparse(*, layout=None, blocksize=None, dense_dim=None) -> Tensor + :noindex: + + Returns a sparse tensor with the specified layout and blocksize. If + the :attr:`self` is strided, the number of dense dimensions could be + specified, and a hybrid sparse tensor will be created, with + `dense_dim` dense dimensions and `self.dim() - 2 - dense_dim` batch + dimension. + + .. note:: If the :attr:`self` layout and blocksize parameters match + with the specified layout and blocksize, return + :attr:`self`. Otherwise, return a sparse tensor copy of + :attr:`self`. + + Args: + + layout (:class:`torch.layout`, optional): The desired sparse + layout. One of ``torch.sparse_coo``, ``torch.sparse_csr``, + ``torch.sparse_csc``, ``torch.sparse_bsr``, or + ``torch.sparse_bsc``. Default: if ``None``, + ``torch.sparse_coo``. + + blocksize (list, tuple, :class:`torch.Size`, optional): Block size + of the resulting BSR or BSC tensor. For other layouts, + specifying the block size that is not ``None`` will result in a + RuntimeError exception. A block size must be a tuple of length + two such that its items evenly divide the two sparse dimensions. + + dense_dim (int, optional): Number of dense dimensions of the + resulting CSR, CSC, BSR or BSC tensor. This argument should be + used only if :attr:`self` is a strided tensor, and must be a + value between 0 and dimension of :attr:`self` tensor minus two. + + Example:: + + >>> x = torch.tensor([[1, 0], [0, 0], [2, 3]]) + >>> x.to_sparse(layout=torch.sparse_coo) + tensor(indices=tensor([[0, 2, 2], + [0, 0, 1]]), + values=tensor([1, 2, 3]), + size=(3, 2), nnz=3, layout=torch.sparse_coo) + >>> x.to_sparse(layout=torch.sparse_bsr, blocksize=(1, 2)) + tensor(crow_indices=tensor([0, 1, 1, 2]), + col_indices=tensor([0, 0]), + values=tensor([[[1, 0]], + [[2, 3]]]), size=(3, 2), nnz=2, layout=torch.sparse_bsr) + >>> x.to_sparse(layout=torch.sparse_bsr, blocksize=(2, 1)) + RuntimeError: Tensor size(-2) 3 needs to be divisible by blocksize[0] 2 + >>> x.to_sparse(layout=torch.sparse_csr, blocksize=(3, 1)) + RuntimeError: to_sparse for Strided to SparseCsr conversion does not use specified blocksize + + >>> x = torch.tensor([[[1], [0]], [[0], [0]], [[2], [3]]]) + >>> x.to_sparse(layout=torch.sparse_csr, dense_dim=1) + tensor(crow_indices=tensor([0, 1, 1, 3]), + col_indices=tensor([0, 0, 1]), + values=tensor([[1], + [2], + [3]]), size=(3, 2, 1), nnz=3, layout=torch.sparse_csr) + """ + + def to_sparse_bsc( + self, + blocksize: _int | _size, + dense_dim: _int | None = None, + ) -> Tensor: + r""" + to_sparse_bsc(blocksize, dense_dim) -> Tensor + + Convert a tensor to a block sparse column (BSC) storage format of + given blocksize. If the :attr:`self` is strided, then the number of + dense dimensions could be specified, and a hybrid BSC tensor will be + created, with `dense_dim` dense dimensions and `self.dim() - 2 - + dense_dim` batch dimension. + + Args: + + blocksize (list, tuple, :class:`torch.Size`, optional): Block size + of the resulting BSC tensor. A block size must be a tuple of + length two such that its items evenly divide the two sparse + dimensions. + + dense_dim (int, optional): Number of dense dimensions of the + resulting BSC tensor. This argument should be used only if + :attr:`self` is a strided tensor, and must be a value between 0 + and dimension of :attr:`self` tensor minus two. + + Example:: + + >>> dense = torch.randn(10, 10) + >>> sparse = dense.to_sparse_csr() + >>> sparse_bsc = sparse.to_sparse_bsc((5, 5)) + >>> sparse_bsc.row_indices() + tensor([0, 1, 0, 1]) + + >>> dense = torch.zeros(4, 3, 1) + >>> dense[0:2, 0] = dense[0:2, 2] = dense[2:4, 1] = 1 + >>> dense.to_sparse_bsc((2, 1), 1) + tensor(ccol_indices=tensor([0, 1, 2, 3]), + row_indices=tensor([0, 1, 0]), + values=tensor([[[[1.]], + + [[1.]]], + + + [[[1.]], + + [[1.]]], + + + [[[1.]], + + [[1.]]]]), size=(4, 3, 1), nnz=3, + layout=torch.sparse_bsc) + """ + + def to_sparse_bsr( + self, + blocksize: _int | _size, + dense_dim: _int | None = None, + ) -> Tensor: + r""" + to_sparse_bsr(blocksize, dense_dim) -> Tensor + + Convert a tensor to a block sparse row (BSR) storage format of given + blocksize. If the :attr:`self` is strided, then the number of dense + dimensions could be specified, and a hybrid BSR tensor will be + created, with `dense_dim` dense dimensions and `self.dim() - 2 - + dense_dim` batch dimension. + + Args: + + blocksize (list, tuple, :class:`torch.Size`, optional): Block size + of the resulting BSR tensor. A block size must be a tuple of + length two such that its items evenly divide the two sparse + dimensions. + + dense_dim (int, optional): Number of dense dimensions of the + resulting BSR tensor. This argument should be used only if + :attr:`self` is a strided tensor, and must be a value between 0 + and dimension of :attr:`self` tensor minus two. + + Example:: + + >>> dense = torch.randn(10, 10) + >>> sparse = dense.to_sparse_csr() + >>> sparse_bsr = sparse.to_sparse_bsr((5, 5)) + >>> sparse_bsr.col_indices() + tensor([0, 1, 0, 1]) + + >>> dense = torch.zeros(4, 3, 1) + >>> dense[0:2, 0] = dense[0:2, 2] = dense[2:4, 1] = 1 + >>> dense.to_sparse_bsr((2, 1), 1) + tensor(crow_indices=tensor([0, 2, 3]), + col_indices=tensor([0, 2, 1]), + values=tensor([[[[1.]], + + [[1.]]], + + + [[[1.]], + + [[1.]]], + + + [[[1.]], + + [[1.]]]]), size=(4, 3, 1), nnz=3, + layout=torch.sparse_bsr) + """ + + def to_sparse_csc(self, dense_dim: _int | None = None) -> Tensor: + r""" + to_sparse_csc() -> Tensor + + Convert a tensor to compressed column storage (CSC) format. Except + for strided tensors, only works with 2D tensors. If the :attr:`self` + is strided, then the number of dense dimensions could be specified, + and a hybrid CSC tensor will be created, with `dense_dim` dense + dimensions and `self.dim() - 2 - dense_dim` batch dimension. + + Args: + + dense_dim (int, optional): Number of dense dimensions of the + resulting CSC tensor. This argument should be used only if + :attr:`self` is a strided tensor, and must be a value between 0 + and dimension of :attr:`self` tensor minus two. + + Example:: + + >>> dense = torch.randn(5, 5) + >>> sparse = dense.to_sparse_csc() + >>> sparse._nnz() + 25 + + >>> dense = torch.zeros(3, 3, 1, 1) + >>> dense[0, 0] = dense[1, 2] = dense[2, 1] = 1 + >>> dense.to_sparse_csc(dense_dim=2) + tensor(ccol_indices=tensor([0, 1, 2, 3]), + row_indices=tensor([0, 2, 1]), + values=tensor([[[1.]], + + [[1.]], + + [[1.]]]), size=(3, 3, 1, 1), nnz=3, + layout=torch.sparse_csc) + """ + + def to_sparse_csr(self, dense_dim: _int | None = None) -> Tensor: + r""" + to_sparse_csr(dense_dim=None) -> Tensor + + Convert a tensor to compressed row storage format (CSR). Except for + strided tensors, only works with 2D tensors. If the :attr:`self` is + strided, then the number of dense dimensions could be specified, and a + hybrid CSR tensor will be created, with `dense_dim` dense dimensions + and `self.dim() - 2 - dense_dim` batch dimension. + + Args: + + dense_dim (int, optional): Number of dense dimensions of the + resulting CSR tensor. This argument should be used only if + :attr:`self` is a strided tensor, and must be a value between 0 + and dimension of :attr:`self` tensor minus two. + + Example:: + + >>> dense = torch.randn(5, 5) + >>> sparse = dense.to_sparse_csr() + >>> sparse._nnz() + 25 + + >>> dense = torch.zeros(3, 3, 1, 1) + >>> dense[0, 0] = dense[1, 2] = dense[2, 1] = 1 + >>> dense.to_sparse_csr(dense_dim=2) + tensor(crow_indices=tensor([0, 1, 2, 3]), + col_indices=tensor([0, 2, 1]), + values=tensor([[[1.]], + + [[1.]], + + [[1.]]]), size=(3, 3, 1, 1), nnz=3, + layout=torch.sparse_csr) + """ + + def tolist(self) -> list: + r""" + tolist() -> list or number + + Returns the tensor as a (nested) list. For scalars, a standard + Python number is returned, just like with :meth:`~Tensor.item`. + Tensors are automatically moved to the CPU first if necessary. + + This operation is not differentiable. + + Examples:: + + >>> a = torch.randn(2, 2) + >>> a.tolist() + [[0.012766935862600803, 0.5415473580360413], + [-0.08909505605697632, 0.7729271650314331]] + >>> a[0,0].tolist() + 0.012766935862600803 + """ + + def topk( + self, + k: _int | SymInt, + dim: _int = -1, + largest: _bool = True, + sorted: _bool = True, + ) -> torch.return_types.topk: + r""" + topk(k, dim=None, largest=True, sorted=True) -> (Tensor, LongTensor) + + See :func:`torch.topk` + """ + + def trace(self) -> Tensor: + r""" + trace() -> Tensor + + See :func:`torch.trace` + """ + + def transpose(self, dim0: _int, dim1: _int) -> Tensor: + r""" + transpose(dim0, dim1) -> Tensor + + See :func:`torch.transpose` + """ + + def transpose_(self, dim0: _int, dim1: _int) -> Tensor: + r""" + transpose_(dim0, dim1) -> Tensor + + In-place version of :meth:`~Tensor.transpose` + """ + + def triangular_solve( + self, + A: Tensor, + upper: _bool = True, + transpose: _bool = False, + unitriangular: _bool = False, + ) -> torch.return_types.triangular_solve: + r""" + triangular_solve(A, upper=True, transpose=False, unitriangular=False) -> (Tensor, Tensor) + + See :func:`torch.triangular_solve` + """ + + def tril(self, diagonal: _int | SymInt = 0) -> Tensor: + r""" + tril(diagonal=0) -> Tensor + + See :func:`torch.tril` + """ + + def tril_(self, diagonal: _int | SymInt = 0) -> Tensor: + r""" + tril_(diagonal=0) -> Tensor + + In-place version of :meth:`~Tensor.tril` + """ + + def triu(self, diagonal: _int | SymInt = 0) -> Tensor: + r""" + triu(diagonal=0) -> Tensor + + See :func:`torch.triu` + """ + + def triu_(self, diagonal: _int | SymInt = 0) -> Tensor: + r""" + triu_(diagonal=0) -> Tensor + + In-place version of :meth:`~Tensor.triu` + """ + + def true_divide( + self, + other: Tensor | Number | torch.SymInt | torch.SymFloat, + *, + out: Tensor | None = None, + ) -> Tensor: + r""" + true_divide(value) -> Tensor + + See :func:`torch.true_divide` + """ + + def true_divide_( + self, + other: Tensor | Number | torch.SymInt | torch.SymFloat, + ) -> Tensor: + r""" + true_divide_(value) -> Tensor + + In-place version of :meth:`~Tensor.true_divide_` + """ + + def trunc(self) -> Tensor: + r""" + trunc() -> Tensor + + See :func:`torch.trunc` + """ + + def trunc_(self) -> Tensor: + r""" + trunc_() -> Tensor + + In-place version of :meth:`~Tensor.trunc` + """ + + @overload + def type(self, dtype: None = None, non_blocking: _bool = False) -> str: + r""" + type(dtype=None, non_blocking=False, **kwargs) -> str or Tensor + Returns the type if `dtype` is not provided, else casts this object to + the specified type. + + If this is already of the correct type, no copy is performed and the + original object is returned. + + Args: + dtype (dtype or string): The desired type + non_blocking (bool): If ``True``, and the source is in pinned memory + and destination is on the GPU or vice versa, the copy is performed + asynchronously with respect to the host. Otherwise, the argument + has no effect. + **kwargs: For compatibility, may contain the key ``async`` in place of + the ``non_blocking`` argument. The ``async`` arg is deprecated. + """ + + @overload + def type(self, dtype: str | _dtype, non_blocking: _bool = False) -> Tensor: + r""" + type(dtype=None, non_blocking=False, **kwargs) -> str or Tensor + Returns the type if `dtype` is not provided, else casts this object to + the specified type. + + If this is already of the correct type, no copy is performed and the + original object is returned. + + Args: + dtype (dtype or string): The desired type + non_blocking (bool): If ``True``, and the source is in pinned memory + and destination is on the GPU or vice versa, the copy is performed + asynchronously with respect to the host. Otherwise, the argument + has no effect. + **kwargs: For compatibility, may contain the key ``async`` in place of + the ``non_blocking`` argument. The ``async`` arg is deprecated. + """ + + def type_as(self, other: Tensor) -> Tensor: + r""" + type_as(tensor) -> Tensor + + Returns this tensor cast to the type of the given tensor. + + This is a no-op if the tensor is already of the correct type. This is + equivalent to ``self.type(tensor.type())`` + + Args: + tensor (Tensor): the tensor which has the desired type + """ + + def unbind(self, dim: _int = 0) -> tuple[Tensor, ...]: + r""" + unbind(dim=0) -> seq + + See :func:`torch.unbind` + """ + + def unflatten(self, dim: _int, sizes: Sequence[_int | SymInt]) -> Tensor: ... + def unfold(self, dimension: _int, size: _int, step: _int) -> Tensor: + r""" + unfold(dimension, size, step) -> Tensor + + Returns a view of the original tensor which contains all slices of size :attr:`size` from + :attr:`self` tensor in the dimension :attr:`dimension`. + + Step between two slices is given by :attr:`step`. + + If `sizedim` is the size of dimension :attr:`dimension` for :attr:`self`, the size of + dimension :attr:`dimension` in the returned tensor will be + `(sizedim - size) / step + 1`. + + An additional dimension of size :attr:`size` is appended in the returned tensor. + + Args: + dimension (int): dimension in which unfolding happens + size (int): the size of each slice that is unfolded + step (int): the step between each slice + + Example:: + + >>> x = torch.arange(1., 8) + >>> x + tensor([ 1., 2., 3., 4., 5., 6., 7.]) + >>> x.unfold(0, 2, 1) + tensor([[ 1., 2.], + [ 2., 3.], + [ 3., 4.], + [ 4., 5.], + [ 5., 6.], + [ 6., 7.]]) + >>> x.unfold(0, 2, 2) + tensor([[ 1., 2.], + [ 3., 4.], + [ 5., 6.]]) + """ + + def uniform_( + self, + from_: _float = 0, + to: _float = 1, + *, + generator: Generator | None = None, + ) -> Tensor: + r""" + uniform_(from=0, to=1, *, generator=None) -> Tensor + + Fills :attr:`self` tensor with numbers sampled from the continuous uniform + distribution: + + .. math:: + f(x) = \dfrac{1}{\text{to} - \text{from}} + """ + + def unsafe_chunk(self, chunks: _int, dim: _int = 0) -> tuple[Tensor, ...]: + r""" + unsafe_chunk(chunks, dim=0) -> List of Tensors + + See :func:`torch.unsafe_chunk` + """ + + def unsafe_split( + self, + split_size: _int | SymInt, + dim: _int = 0, + ) -> tuple[Tensor, ...]: + r""" + unsafe_split(split_size, dim=0) -> List of Tensors + + See :func:`torch.unsafe_split` + """ + + def unsafe_split_with_sizes( + self, + split_sizes: Sequence[_int | SymInt], + dim: _int = 0, + ) -> tuple[Tensor, ...]: ... + def unsqueeze(self, dim: _int) -> Tensor: + r""" + unsqueeze(dim) -> Tensor + + See :func:`torch.unsqueeze` + """ + + def unsqueeze_(self, dim: _int) -> Tensor: + r""" + unsqueeze_(dim) -> Tensor + + In-place version of :meth:`~Tensor.unsqueeze` + """ + + def values(self) -> Tensor: + r""" + values() -> Tensor + + Return the values tensor of a :ref:`sparse COO tensor `. + + .. warning:: + Throws an error if :attr:`self` is not a sparse COO tensor. + + See also :meth:`Tensor.indices`. + + .. note:: + This method can only be called on a coalesced sparse tensor. See + :meth:`Tensor.coalesce` for details. + """ + + @overload + def var( + self, + dim: _int | _size | None, + unbiased: _bool = True, + keepdim: _bool = False, + ) -> Tensor: + r""" + var(dim=None, *, correction=1, keepdim=False) -> Tensor + + See :func:`torch.var` + """ + + @overload + def var( + self, + dim: _int | _size | None = None, + *, + correction: Number | _complex | PySymType | None = None, + keepdim: _bool = False, + ) -> Tensor: + r""" + var(dim=None, *, correction=1, keepdim=False) -> Tensor + + See :func:`torch.var` + """ + + @overload + def var(self, unbiased: _bool = True) -> Tensor: + r""" + var(dim=None, *, correction=1, keepdim=False) -> Tensor + + See :func:`torch.var` + """ + + def vdot(self, other: Tensor) -> Tensor: + r""" + vdot(other) -> Tensor + + See :func:`torch.vdot` + """ + + @overload + def view(self, dtype: _dtype) -> Tensor: + r""" + view(*shape) -> Tensor + + Returns a new tensor with the same data as the :attr:`self` tensor but of a + different :attr:`shape`. + + The returned tensor shares the same data and must have the same number + of elements, but may have a different size. For a tensor to be viewed, the new + view size must be compatible with its original size and stride, i.e., each new + view dimension must either be a subspace of an original dimension, or only span + across original dimensions :math:`d, d+1, \dots, d+k` that satisfy the following + contiguity-like condition that :math:`\forall i = d, \dots, d+k-1`, + + .. math:: + + \text{stride}[i] = \text{stride}[i+1] \times \text{size}[i+1] + + Otherwise, it will not be possible to view :attr:`self` tensor as :attr:`shape` + without copying it (e.g., via :meth:`contiguous`). When it is unclear whether a + :meth:`view` can be performed, it is advisable to use :meth:`reshape`, which + returns a view if the shapes are compatible, and copies (equivalent to calling + :meth:`contiguous`) otherwise. + + Args: + shape (torch.Size or int...): the desired size + + Example:: + + >>> x = torch.randn(4, 4) + >>> x.size() + torch.Size([4, 4]) + >>> y = x.view(16) + >>> y.size() + torch.Size([16]) + >>> z = x.view(-1, 8) # the size -1 is inferred from other dimensions + >>> z.size() + torch.Size([2, 8]) + + >>> a = torch.randn(1, 2, 3, 4) + >>> a.size() + torch.Size([1, 2, 3, 4]) + >>> b = a.transpose(1, 2) # Swaps 2nd and 3rd dimension + >>> b.size() + torch.Size([1, 3, 2, 4]) + >>> c = a.view(1, 3, 2, 4) # Does not change tensor layout in memory + >>> c.size() + torch.Size([1, 3, 2, 4]) + >>> torch.equal(b, c) + False + + + .. method:: view(dtype) -> Tensor + :noindex: + + Returns a new tensor with the same data as the :attr:`self` tensor but of a + different :attr:`dtype`. + + If the element size of :attr:`dtype` is different than that of ``self.dtype``, + then the size of the last dimension of the output will be scaled + proportionally. For instance, if :attr:`dtype` element size is twice that of + ``self.dtype``, then each pair of elements in the last dimension of + :attr:`self` will be combined, and the size of the last dimension of the output + will be half that of :attr:`self`. If :attr:`dtype` element size is half that + of ``self.dtype``, then each element in the last dimension of :attr:`self` will + be split in two, and the size of the last dimension of the output will be + double that of :attr:`self`. For this to be possible, the following conditions + must be true: + + * ``self.dim()`` must be greater than 0. + * ``self.stride(-1)`` must be 1. + + Additionally, if the element size of :attr:`dtype` is greater than that of + ``self.dtype``, the following conditions must be true as well: + + * ``self.size(-1)`` must be divisible by the ratio between the element + sizes of the dtypes. + * ``self.storage_offset()`` must be divisible by the ratio between the + element sizes of the dtypes. + * The strides of all dimensions, except the last dimension, must be + divisible by the ratio between the element sizes of the dtypes. + + If any of the above conditions are not met, an error is thrown. + + .. warning:: + + This overload is not supported by TorchScript, and using it in a Torchscript + program will cause undefined behavior. + + + Args: + dtype (:class:`torch.dtype`): the desired dtype + + Example:: + + >>> x = torch.randn(4, 4) + >>> x + tensor([[ 0.9482, -0.0310, 1.4999, -0.5316], + [-0.1520, 0.7472, 0.5617, -0.8649], + [-2.4724, -0.0334, -0.2976, -0.8499], + [-0.2109, 1.9913, -0.9607, -0.6123]]) + >>> x.dtype + torch.float32 + + >>> y = x.view(torch.int32) + >>> y + tensor([[ 1064483442, -1124191867, 1069546515, -1089989247], + [-1105482831, 1061112040, 1057999968, -1084397505], + [-1071760287, -1123489973, -1097310419, -1084649136], + [-1101533110, 1073668768, -1082790149, -1088634448]], + dtype=torch.int32) + >>> y[0, 0] = 1000000000 + >>> x + tensor([[ 0.0047, -0.0310, 1.4999, -0.5316], + [-0.1520, 0.7472, 0.5617, -0.8649], + [-2.4724, -0.0334, -0.2976, -0.8499], + [-0.2109, 1.9913, -0.9607, -0.6123]]) + + >>> x.view(torch.cfloat) + tensor([[ 0.0047-0.0310j, 1.4999-0.5316j], + [-0.1520+0.7472j, 0.5617-0.8649j], + [-2.4724-0.0334j, -0.2976-0.8499j], + [-0.2109+1.9913j, -0.9607-0.6123j]]) + >>> x.view(torch.cfloat).size() + torch.Size([4, 2]) + + >>> x.view(torch.uint8) + tensor([[ 0, 202, 154, 59, 182, 243, 253, 188, 185, 252, 191, 63, 240, 22, + 8, 191], + [227, 165, 27, 190, 128, 72, 63, 63, 146, 203, 15, 63, 22, 106, + 93, 191], + [205, 59, 30, 192, 112, 206, 8, 189, 7, 95, 152, 190, 12, 147, + 89, 191], + [ 43, 246, 87, 190, 235, 226, 254, 63, 111, 240, 117, 191, 177, 191, + 28, 191]], dtype=torch.uint8) + >>> x.view(torch.uint8).size() + torch.Size([4, 16]) + """ + + @overload + def view(self, size: Sequence[_int | SymInt]) -> Tensor: + r""" + view(*shape) -> Tensor + + Returns a new tensor with the same data as the :attr:`self` tensor but of a + different :attr:`shape`. + + The returned tensor shares the same data and must have the same number + of elements, but may have a different size. For a tensor to be viewed, the new + view size must be compatible with its original size and stride, i.e., each new + view dimension must either be a subspace of an original dimension, or only span + across original dimensions :math:`d, d+1, \dots, d+k` that satisfy the following + contiguity-like condition that :math:`\forall i = d, \dots, d+k-1`, + + .. math:: + + \text{stride}[i] = \text{stride}[i+1] \times \text{size}[i+1] + + Otherwise, it will not be possible to view :attr:`self` tensor as :attr:`shape` + without copying it (e.g., via :meth:`contiguous`). When it is unclear whether a + :meth:`view` can be performed, it is advisable to use :meth:`reshape`, which + returns a view if the shapes are compatible, and copies (equivalent to calling + :meth:`contiguous`) otherwise. + + Args: + shape (torch.Size or int...): the desired size + + Example:: + + >>> x = torch.randn(4, 4) + >>> x.size() + torch.Size([4, 4]) + >>> y = x.view(16) + >>> y.size() + torch.Size([16]) + >>> z = x.view(-1, 8) # the size -1 is inferred from other dimensions + >>> z.size() + torch.Size([2, 8]) + + >>> a = torch.randn(1, 2, 3, 4) + >>> a.size() + torch.Size([1, 2, 3, 4]) + >>> b = a.transpose(1, 2) # Swaps 2nd and 3rd dimension + >>> b.size() + torch.Size([1, 3, 2, 4]) + >>> c = a.view(1, 3, 2, 4) # Does not change tensor layout in memory + >>> c.size() + torch.Size([1, 3, 2, 4]) + >>> torch.equal(b, c) + False + + + .. method:: view(dtype) -> Tensor + :noindex: + + Returns a new tensor with the same data as the :attr:`self` tensor but of a + different :attr:`dtype`. + + If the element size of :attr:`dtype` is different than that of ``self.dtype``, + then the size of the last dimension of the output will be scaled + proportionally. For instance, if :attr:`dtype` element size is twice that of + ``self.dtype``, then each pair of elements in the last dimension of + :attr:`self` will be combined, and the size of the last dimension of the output + will be half that of :attr:`self`. If :attr:`dtype` element size is half that + of ``self.dtype``, then each element in the last dimension of :attr:`self` will + be split in two, and the size of the last dimension of the output will be + double that of :attr:`self`. For this to be possible, the following conditions + must be true: + + * ``self.dim()`` must be greater than 0. + * ``self.stride(-1)`` must be 1. + + Additionally, if the element size of :attr:`dtype` is greater than that of + ``self.dtype``, the following conditions must be true as well: + + * ``self.size(-1)`` must be divisible by the ratio between the element + sizes of the dtypes. + * ``self.storage_offset()`` must be divisible by the ratio between the + element sizes of the dtypes. + * The strides of all dimensions, except the last dimension, must be + divisible by the ratio between the element sizes of the dtypes. + + If any of the above conditions are not met, an error is thrown. + + .. warning:: + + This overload is not supported by TorchScript, and using it in a Torchscript + program will cause undefined behavior. + + + Args: + dtype (:class:`torch.dtype`): the desired dtype + + Example:: + + >>> x = torch.randn(4, 4) + >>> x + tensor([[ 0.9482, -0.0310, 1.4999, -0.5316], + [-0.1520, 0.7472, 0.5617, -0.8649], + [-2.4724, -0.0334, -0.2976, -0.8499], + [-0.2109, 1.9913, -0.9607, -0.6123]]) + >>> x.dtype + torch.float32 + + >>> y = x.view(torch.int32) + >>> y + tensor([[ 1064483442, -1124191867, 1069546515, -1089989247], + [-1105482831, 1061112040, 1057999968, -1084397505], + [-1071760287, -1123489973, -1097310419, -1084649136], + [-1101533110, 1073668768, -1082790149, -1088634448]], + dtype=torch.int32) + >>> y[0, 0] = 1000000000 + >>> x + tensor([[ 0.0047, -0.0310, 1.4999, -0.5316], + [-0.1520, 0.7472, 0.5617, -0.8649], + [-2.4724, -0.0334, -0.2976, -0.8499], + [-0.2109, 1.9913, -0.9607, -0.6123]]) + + >>> x.view(torch.cfloat) + tensor([[ 0.0047-0.0310j, 1.4999-0.5316j], + [-0.1520+0.7472j, 0.5617-0.8649j], + [-2.4724-0.0334j, -0.2976-0.8499j], + [-0.2109+1.9913j, -0.9607-0.6123j]]) + >>> x.view(torch.cfloat).size() + torch.Size([4, 2]) + + >>> x.view(torch.uint8) + tensor([[ 0, 202, 154, 59, 182, 243, 253, 188, 185, 252, 191, 63, 240, 22, + 8, 191], + [227, 165, 27, 190, 128, 72, 63, 63, 146, 203, 15, 63, 22, 106, + 93, 191], + [205, 59, 30, 192, 112, 206, 8, 189, 7, 95, 152, 190, 12, 147, + 89, 191], + [ 43, 246, 87, 190, 235, 226, 254, 63, 111, 240, 117, 191, 177, 191, + 28, 191]], dtype=torch.uint8) + >>> x.view(torch.uint8).size() + torch.Size([4, 16]) + """ + + @overload + def view(self, *size: _int | SymInt) -> Tensor: + r""" + view(*shape) -> Tensor + + Returns a new tensor with the same data as the :attr:`self` tensor but of a + different :attr:`shape`. + + The returned tensor shares the same data and must have the same number + of elements, but may have a different size. For a tensor to be viewed, the new + view size must be compatible with its original size and stride, i.e., each new + view dimension must either be a subspace of an original dimension, or only span + across original dimensions :math:`d, d+1, \dots, d+k` that satisfy the following + contiguity-like condition that :math:`\forall i = d, \dots, d+k-1`, + + .. math:: + + \text{stride}[i] = \text{stride}[i+1] \times \text{size}[i+1] + + Otherwise, it will not be possible to view :attr:`self` tensor as :attr:`shape` + without copying it (e.g., via :meth:`contiguous`). When it is unclear whether a + :meth:`view` can be performed, it is advisable to use :meth:`reshape`, which + returns a view if the shapes are compatible, and copies (equivalent to calling + :meth:`contiguous`) otherwise. + + Args: + shape (torch.Size or int...): the desired size + + Example:: + + >>> x = torch.randn(4, 4) + >>> x.size() + torch.Size([4, 4]) + >>> y = x.view(16) + >>> y.size() + torch.Size([16]) + >>> z = x.view(-1, 8) # the size -1 is inferred from other dimensions + >>> z.size() + torch.Size([2, 8]) + + >>> a = torch.randn(1, 2, 3, 4) + >>> a.size() + torch.Size([1, 2, 3, 4]) + >>> b = a.transpose(1, 2) # Swaps 2nd and 3rd dimension + >>> b.size() + torch.Size([1, 3, 2, 4]) + >>> c = a.view(1, 3, 2, 4) # Does not change tensor layout in memory + >>> c.size() + torch.Size([1, 3, 2, 4]) + >>> torch.equal(b, c) + False + + + .. method:: view(dtype) -> Tensor + :noindex: + + Returns a new tensor with the same data as the :attr:`self` tensor but of a + different :attr:`dtype`. + + If the element size of :attr:`dtype` is different than that of ``self.dtype``, + then the size of the last dimension of the output will be scaled + proportionally. For instance, if :attr:`dtype` element size is twice that of + ``self.dtype``, then each pair of elements in the last dimension of + :attr:`self` will be combined, and the size of the last dimension of the output + will be half that of :attr:`self`. If :attr:`dtype` element size is half that + of ``self.dtype``, then each element in the last dimension of :attr:`self` will + be split in two, and the size of the last dimension of the output will be + double that of :attr:`self`. For this to be possible, the following conditions + must be true: + + * ``self.dim()`` must be greater than 0. + * ``self.stride(-1)`` must be 1. + + Additionally, if the element size of :attr:`dtype` is greater than that of + ``self.dtype``, the following conditions must be true as well: + + * ``self.size(-1)`` must be divisible by the ratio between the element + sizes of the dtypes. + * ``self.storage_offset()`` must be divisible by the ratio between the + element sizes of the dtypes. + * The strides of all dimensions, except the last dimension, must be + divisible by the ratio between the element sizes of the dtypes. + + If any of the above conditions are not met, an error is thrown. + + .. warning:: + + This overload is not supported by TorchScript, and using it in a Torchscript + program will cause undefined behavior. + + + Args: + dtype (:class:`torch.dtype`): the desired dtype + + Example:: + + >>> x = torch.randn(4, 4) + >>> x + tensor([[ 0.9482, -0.0310, 1.4999, -0.5316], + [-0.1520, 0.7472, 0.5617, -0.8649], + [-2.4724, -0.0334, -0.2976, -0.8499], + [-0.2109, 1.9913, -0.9607, -0.6123]]) + >>> x.dtype + torch.float32 + + >>> y = x.view(torch.int32) + >>> y + tensor([[ 1064483442, -1124191867, 1069546515, -1089989247], + [-1105482831, 1061112040, 1057999968, -1084397505], + [-1071760287, -1123489973, -1097310419, -1084649136], + [-1101533110, 1073668768, -1082790149, -1088634448]], + dtype=torch.int32) + >>> y[0, 0] = 1000000000 + >>> x + tensor([[ 0.0047, -0.0310, 1.4999, -0.5316], + [-0.1520, 0.7472, 0.5617, -0.8649], + [-2.4724, -0.0334, -0.2976, -0.8499], + [-0.2109, 1.9913, -0.9607, -0.6123]]) + + >>> x.view(torch.cfloat) + tensor([[ 0.0047-0.0310j, 1.4999-0.5316j], + [-0.1520+0.7472j, 0.5617-0.8649j], + [-2.4724-0.0334j, -0.2976-0.8499j], + [-0.2109+1.9913j, -0.9607-0.6123j]]) + >>> x.view(torch.cfloat).size() + torch.Size([4, 2]) + + >>> x.view(torch.uint8) + tensor([[ 0, 202, 154, 59, 182, 243, 253, 188, 185, 252, 191, 63, 240, 22, + 8, 191], + [227, 165, 27, 190, 128, 72, 63, 63, 146, 203, 15, 63, 22, 106, + 93, 191], + [205, 59, 30, 192, 112, 206, 8, 189, 7, 95, 152, 190, 12, 147, + 89, 191], + [ 43, 246, 87, 190, 235, 226, 254, 63, 111, 240, 117, 191, 177, 191, + 28, 191]], dtype=torch.uint8) + >>> x.view(torch.uint8).size() + torch.Size([4, 16]) + """ + + def view_as(self, other: Tensor) -> Tensor: + r""" + view_as(other) -> Tensor + + View this tensor as the same size as :attr:`other`. + ``self.view_as(other)`` is equivalent to ``self.view(other.size())``. + + Please see :meth:`~Tensor.view` for more information about ``view``. + + Args: + other (:class:`torch.Tensor`): The result tensor has the same size + as :attr:`other`. + """ + + @overload + def vsplit(self, sections: _int) -> tuple[Tensor, ...]: + r""" + vsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.vsplit` + """ + + @overload + def vsplit(self, indices: _size) -> tuple[Tensor, ...]: + r""" + vsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.vsplit` + """ + + @overload + def vsplit(self, *indices: _int) -> tuple[Tensor, ...]: + r""" + vsplit(split_size_or_sections) -> List of Tensors + + See :func:`torch.vsplit` + """ + + @overload + def where(self, condition: Tensor, other: Tensor) -> Tensor: + r""" + where(condition, y) -> Tensor + + ``self.where(condition, y)`` is equivalent to ``torch.where(condition, self, y)``. + See :func:`torch.where` + """ + + @overload + def where( + self, + condition: Tensor, + other: Number | _complex | PySymType, + ) -> Tensor: + r""" + where(condition, y) -> Tensor + + ``self.where(condition, y)`` is equivalent to ``torch.where(condition, self, y)``. + See :func:`torch.where` + """ + + @overload + def xlogy(self, other: Tensor) -> Tensor: + r""" + xlogy(other) -> Tensor + + See :func:`torch.xlogy` + """ + + @overload + def xlogy(self, other: Number | _complex | PySymType) -> Tensor: + r""" + xlogy(other) -> Tensor + + See :func:`torch.xlogy` + """ + + @overload + def xlogy_(self, other: Tensor) -> Tensor: + r""" + xlogy_(other) -> Tensor + + In-place version of :meth:`~Tensor.xlogy` + """ + + @overload + def xlogy_(self, other: Number | _complex | PySymType) -> Tensor: + r""" + xlogy_(other) -> Tensor + + In-place version of :meth:`~Tensor.xlogy` + """ + + def xpu( + self, + device: _device | _int | str | None = None, + non_blocking: _bool = False, + memory_format: torch.memory_format = torch.preserve_format, + ) -> Tensor: + r""" + xpu(device=None, non_blocking=False, memory_format=torch.preserve_format) -> Tensor + + Returns a copy of this object in XPU memory. + + If this object is already in XPU memory and on the correct device, + then no copy is performed and the original object is returned. + + Args: + device (:class:`torch.device`, optional): The destination XPU device. + Defaults to the current XPU device. + non_blocking (bool, optional): If ``True`` and the source is in pinned memory, + the copy will be asynchronous with respect to the host. + Otherwise, the argument has no effect. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + + def zero_(self) -> Tensor: + r""" + zero_() -> Tensor + + Fills :attr:`self` tensor with zeros. + """ + +_TensorBase = TensorBase + +def _DTensor_OpSchema_post_init(self: OpSchema) -> None: ... +def _DTensor_OpSchema_recompute_comparison_key(self: OpSchema) -> None: ... +def _DTensor_compute_global_tensor_info( + tensor: Tensor, mesh: DeviceMesh, placements: Sequence[Placement] +) -> tuple[list[_int], list[_int]]: ... +def _get_DTensor_sharding_propagator_cache_stats() -> tuple[_int, _int]: ... +def _clear_DTensor_sharding_propagator_cache() -> None: ... +def _reinit_DTensor_dispatch_logger() -> None: ... + +# Defined in torch/csrc/multiprocessing/init.cpp +def _multiprocessing_init() -> None: ... +def _set_thread_name(name: str) -> None: ... +def _get_thread_name() -> str: ... + +# Defined in torch/csrc/Module.cpp +def _accelerator_hooks_device_count() -> _int: ... +def _accelerator_hooks_set_current_device(device_index: _int) -> None: ... +def _accelerator_hooks_get_current_device() -> _int: ... +def _accelerator_hooks_exchange_device(device_index: _int) -> _int: ... +def _accelerator_hooks_maybe_exchange_device(device_index: _int) -> _int: ... +def _get_accelerator(check: _bool = False) -> _device: ... +def _storage_Use_Count(storage_ptr: _int) -> _int: ... +def _storage_throw_on_immutable_data_ptr(storage_ptr: _int) -> _bool: ... +def _storage_throw_on_mutable_data_ptr(storage_ptr: _int) -> _bool: ... +def _set_storage_data_ptr_access_error_msg(storage_ptr: _int, s: str) -> None: ... +def _clear_storage_data_ptr_access_error_msg(storage_ptr: _int) -> None: ... + +# Defined in torch/csrc/mtia/Module.cpp +def _mtia_init() -> None: ... +def _mtia_isBuilt() -> _bool: ... +def _mtia_isInBadFork() -> _bool: ... +def _mtia_deviceSynchronize() -> None: ... +def _mtia_getCurrentStream(device: _int) -> Stream: ... +def _mtia_getCurrentRawStream(device: _int) -> _int: ... +def _mtia_setCurrentStream(stream: Stream) -> None: ... +def _mtia_getDefaultStream(device: _int) -> Stream: ... +def _mtia_setStream(stream_id: _int, device_index: _int, device_type: _int) -> None: ... +def _mtia_memoryStats(device: _int) -> dict[str, Any]: ... +def _mtia_getDeviceCapability(device: _int) -> tuple[_int, _int]: ... +def _mtia_getDeviceProperties(device: _int) -> dict[str, Any]: ... +def _mtia_emptyCache() -> None: ... +def _mtia_recordMemoryHistory( + enabled: str | None, + stacks: str, + max_entries, +) -> None: ... +def _mtia_memorySnapshot() -> dict[str, Any]: ... +def _mtia_attachOutOfMemoryObserver( + observer: Callable[[_int, _int, _int, _int], None], +) -> None: ... +def _mtia_getDeviceCount() -> _int: ... +def _mtia_getDevice() -> _int: ... +def _mtia_setDevice(device: _int) -> None: ... +def _mtia_exchangeDevice(device: _int) -> _int: ... +def _mtia_maybeExchangeDevice(device: _int) -> _int: ... +def _mtia_resetPeakMemoryStats(device: _int) -> None: ... +def _mtia_graphPoolHandle() -> tuple[_int, _int]: ... + +# Defined in torch/csrc/mtia/Module.cpp +class _MTIAGraph: + def __new__(cls, keep_graph: _bool = ...) -> Self: ... + def capture_begin(self, pool: tuple[_int, _int]) -> None: ... + def capture_end(self) -> None: ... + def instantiate(self) -> None: ... + def replay(self) -> None: ... + def reset(self) -> None: ... + def pool(self) -> tuple[_int, _int]: ... + +# Defined in torch/csrc/mps/Module.cpp +def _mps_deviceSynchronize() -> None: ... +def _mps_get_core_count() -> _int: ... +def _mps_host_alias_storage(storage: UntypedStorage) -> UntypedStorage: ... +def _mps_get_default_generator() -> Generator: ... +def _mps_get_name() -> _str: ... +def _mps_emptyCache() -> None: ... +def _mps_setMemoryFraction(fraction: _float) -> None: ... +def _mps_currentAllocatedMemory() -> _int: ... +def _mps_driverAllocatedMemory() -> _int: ... +def _mps_recommendedMaxMemory() -> _int: ... +def _mps_is_available() -> _bool: ... +def _mps_is_on_macos_or_newer(major: _int, minor: _int) -> _bool: ... +def _mps_profilerStartTrace(mode: str, wait_until_completed: _bool) -> None: ... +def _mps_profilerStopTrace() -> None: ... +def _mps_acquireEvent(enable_timing: _bool) -> _int: ... +def _mps_releaseEvent(event_id: _int) -> None: ... +def _mps_recordEvent(event_id: _int) -> None: ... +def _mps_waitForEvent(event_id: _int) -> None: ... +def _mps_synchronizeEvent(event_id: _int) -> None: ... +def _mps_queryEvent(event_id: _int) -> _bool: ... +def _mps_elapsedTimeOfEvents(start_event_id: _int, end_event_id: _int) -> _float: ... +def _mps_isCaptureEnabled() -> _bool: ... +def _mps_isCapturing() -> _bool: ... +def _mps_startCapture(name: str) -> None: ... +def _mps_stopCapture() -> None: ... + +# Defined in torch/csrc/cuda/Module.cpp +def _cuda_getCurrentStream(device: _int) -> tuple: ... +def _cuda_getCurrentRawStream(device: _int) -> _int: ... +def _cuda_getDefaultStream(device: _int) -> tuple: ... +def _cuda_getStreamFromExternal(data_ptr: _int, device_index: _int) -> tuple: ... +def _cuda_getCurrentBlasHandle() -> _int: ... +def _cuda_getCurrentSolverHandle() -> _int: ... +def _cuda_clearCublasWorkspaces() -> None: ... +def _cuda_getCublasWorkspaceSize() -> _int: ... +def _cuda_setCublasWorkspaceSize(size: _int) -> None: ... +def _cuda_getCublasLtWorkspaceSize() -> _int: ... +def _cuda_setCublasLtWorkspaceSize(size: _int) -> None: ... +def _cuda_resetCublasWorkspaceSize() -> None: ... +def _cuda_resetCublasLtWorkspaceSize() -> None: ... +def _cudnn_clear_dropout_state() -> None: ... +def _cuda_setDevice(device: _int) -> None: ... +def _cuda_exchangeDevice(device: _int) -> _int: ... +def _cuda_maybeExchangeDevice(device: _int) -> _int: ... +def _cuda_getDevice() -> _int: ... +def _cuda_getDeviceCount() -> _int: ... +def _cuda_set_sync_debug_mode(warn_level: _int | str) -> None: ... +def _cuda_get_sync_debug_mode() -> _int: ... +def _cuda_sleep(cycles: _int) -> None: ... +def _cuda_synchronize() -> None: ... +def _cuda_ipc_collect() -> None: ... +def _cuda_getArchFlags() -> str | None: ... +def _cuda_init() -> None: ... +def _cuda_setStream(stream_id: _int, device_index: _int, device_type: _int) -> None: ... +def _cuda_getCompiledVersion() -> _int: ... +def _cuda_cudaHostAllocator() -> _int: ... +def _host_emptyCache() -> None: ... +def _cuda_cudaCachingAllocator_raw_alloc(size: _int, cuda_stream: _int) -> _int: ... +def _cuda_cudaCachingAllocator_raw_delete(ptr: _int) -> None: ... +def _cuda_cudaCachingAllocator_enable(val: _bool) -> None: ... +def _cuda_cudaCachingAllocator_is_enabled() -> _bool: ... +def _cuda_beginAllocateToPool(device: _int, mempool_id: tuple[_int, _int]) -> None: ... +def _cuda_beginAllocateCurrentThreadToPool( + device: _int, + mempool_id: tuple[_int, _int], +) -> None: ... +def _cuda_endAllocateToPool(device: _int, mempool_id: tuple[_int, _int]) -> None: ... +def _cuda_beginAllocateCurrentStreamToPool( + device: _int, + mempool_id: tuple[_int, _int], +) -> None: ... +def _cuda_releasePool(device: _int, mempool_id: tuple[_int, _int]) -> None: ... +def _cuda_checkPoolLiveAllocations( + device: _int, + mempool_id: tuple[_int, _int], + expected_live_allocations: set, +) -> _bool: ... +def _cuda_setCheckpointPoolState( + device: _int, + state: _cuda_CUDAAllocator_AllocatorState, + stale_storages: list[_int], + storages_to_add_deleters_to: list[_int], +) -> None: ... +def _cuda_getMemoryFraction(device: _int) -> _float: ... +def _cuda_setMemoryFraction(fraction: _float, device: _int) -> None: ... +def _cuda_emptyCache() -> None: ... +def _cuda_memoryStats(device: _int) -> dict[str, Any]: ... +def _cuda_resetAccumulatedMemoryStats(device: _int) -> None: ... +def _cuda_resetPeakMemoryStats(device: _int) -> None: ... +def _cuda_hostMemoryStats() -> dict[str, Any]: ... +def _cuda_resetAccumulatedHostMemoryStats() -> None: ... +def _cuda_resetPeakHostMemoryStats() -> None: ... +def _cuda_memorySnapshot( + mempool_id: tuple[_int, _int] | tuple[_int, _int, _bool] | None, +) -> dict[str, Any]: ... +def _cuda_memoryMetadataSupported() -> _bool: ... +def _cuda_setMemoryMetadata(metadata: str) -> None: ... +def _cuda_getMemoryMetadata() -> str: ... +def _cuda_annotateMemory(ptr: _int, metadata: str) -> None: ... +def _cuda_record_memory_history_legacy( + enabled: _bool, + record_context: _bool, + record_context_cpp: _bool, + alloc_trace_max_entries: _int, + alloc_trace_record_context: _bool, + clear_history: _bool, + compile_context: _bool, + global_record_annotations: _bool, + skip_actions: list[str], + record_pinned_host_memory: _bool, + record_cuda: _bool, +) -> None: ... +def _cuda_record_memory_history( + enabled: str | None, + context: str | None, + stacks: str, + max_entries: _int, + clear_history: _bool, + compile_context: _bool, + global_record_annotations: _bool, + skip_actions: list[str], + record_pinned_host_memory: _bool, + record_cuda: _bool, +) -> None: ... +def _cuda_allocationTraceback(data_ptr: _int) -> list[dict[str, Any]] | None: ... +def _cuda_isHistoryEnabled() -> _bool: ... +def _cuda_getAllocatorBackend() -> str: ... + +class _cuda_CUDAAllocator_AllocatorState: ... + +def _cuda_getCheckpointState( + device: _int, + mempool: tuple[_int, _int], +) -> _cuda_CUDAAllocator_AllocatorState: ... +def _set_cached_tensors_enabled(enabled: _bool) -> None: ... +def _add_cached_tensor(t: Tensor) -> None: ... +def _remove_cached_tensor(t: Tensor) -> None: ... +def _is_fake_tensor(t: Tensor) -> _bool: ... +def _tensors_data_ptrs_at_indices_equal( + tensors: list[Tensor | _int], + ptrs: list[_int | None], + indices: list[_int], +) -> _bool: ... +def _construct_CUDA_Tensor_From_Storage_And_Metadata( + metadata: dict, + storage: Storage, +) -> Tensor: ... +def _set_storage_access_error_msg(t: Tensor, s: str) -> None: ... +def _free_And_Remove_DeleterFn(storage_ptr: _int) -> None: ... +def _has_Standard_Deleter(storage_ptr: _int) -> _bool: ... + +class _cuda_CUDAAllocator: ... + +def _cuda_customAllocator(alloc_fn: _int, free_fn: _int) -> _cuda_CUDAAllocator: ... +def _cuda_changeCurrentAllocator(allocator: _cuda_CUDAAllocator) -> None: ... +def _cuda_getAllocator() -> _cuda_CUDAAllocator: ... +def _cuda_canDeviceAccessPeer(device: _int, peer_device: _int) -> _bool: ... +def _cuda_jiterator_compile_and_launch_kernel( + code_string: str, + kernel_name: str, + return_by_ref: _bool, + num_outputs: _int, + tensors: tuple, + kwargs: dict[str, _int | _float | _bool], +) -> Tensor: ... +def _cuda_get_cudnn_benchmark_limit() -> _int: ... +def _cuda_set_cudnn_benchmark_limit(arg: _int) -> None: ... +def _cuda_get_conv_benchmark_empty_cache() -> _bool: ... +def _cudnn_set_conv_benchmark_empty_cache(enable: _bool) -> None: ... +def _nccl_version() -> _int: ... +def _nccl_version_suffix() -> bytes: ... +def _nccl_unique_id() -> bytes: ... +def _nccl_init_rank(nranks: _int, comm_id: bytes, rank: _int) -> object: ... +def _nccl_reduce( + input: Sequence[Tensor], + output: Tensor, + root: _int, + op: _int, + streams: Sequence[_CudaStreamBase] | None, + comms: Sequence[object] | None, +) -> None: ... +def _nccl_all_reduce( + input: Sequence[Tensor], + output: Sequence[Tensor], + op: _int, + streams: Sequence[_CudaStreamBase] | None, + comms: Sequence[object] | None, +) -> None: ... +def _nccl_broadcast( + input: Sequence[Tensor], + root: _int, + streams: Sequence[_CudaStreamBase] | None, + comms: Sequence[object] | None, +) -> None: ... +def _nccl_all_gather( + input: Sequence[Tensor], + output: Sequence[Tensor], + streams: Sequence[_CudaStreamBase] | None, + comms: Sequence[object] | None, +) -> None: ... +def _nccl_reduce_scatter( + input: Sequence[Tensor], + output: Sequence[Tensor], + op: _int, + streams: Sequence[_CudaStreamBase] | None, + comms: Sequence[object] | None, +) -> None: ... +def _rocm_is_backward_pass() -> _bool: ... +def _cuda_tunableop_enable(val: _bool) -> None: ... +def _cuda_tunableop_is_enabled() -> _bool: ... +def _cuda_tunableop_tuning_enable(val: _bool) -> None: ... +def _cuda_tunableop_tuning_is_enabled() -> _bool: ... +def _cuda_tunableop_set_max_tuning_duration(duration: _int) -> None: ... +def _cuda_tunableop_get_max_tuning_duration() -> _int: ... +def _cuda_tunableop_set_max_tuning_iterations(iterations: _int) -> None: ... +def _cuda_tunableop_get_max_tuning_iterations() -> _int: ... +def _cuda_tunableop_set_filename( + filename: str, + insert_device_ordinal: _bool | None, +) -> None: ... +def _cuda_tunableop_get_filename() -> str: ... +def _cuda_tunableop_read_file(filename: str | None) -> _bool: ... +def _cuda_tunableop_get_results() -> tuple[str, str, str, _float]: ... +def _cuda_tunableop_get_validators() -> tuple[str, str]: ... +def _cuda_tunableop_set_rotating_buffer_size(buffer_size: _int) -> None: ... +def _cuda_tunableop_get_rotation_buffer_size() -> _int: ... +def _cuda_tunableop_set_numerical_check_tolerances( + enabled: _bool, atol: _float = 1e-5, rtol: _float = 1e-5 +) -> None: ... + +class _CudaDeviceProperties: + name: str + major: _int + minor: _int + multi_processor_count: _int + total_memory: _int + is_integrated: _int + is_multi_gpu_board: _int + max_threads_per_multi_processor: _int + gcnArchName: str + warp_size: _int + uuid: str + L2_cache_size: _int + clock_rate: _int + memory_clock_rate: _int + memory_bus_width: _int + shared_memory_per_block: _int + shared_memory_per_multiprocessor: _int + +# Functions related to SDPA +class _SDPAParams: + query: Tensor + key: Tensor + value: Tensor + attn_mask: Tensor | None + dropout: _float + is_causal: _bool + enable_gqa: _bool + def __init__( + self, + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Tensor | None, + dropout: _float, + is_causal: _bool, + enable_gqa: _bool, + ) -> None: ... + +class _SDPBackend(Enum): + ERROR = -1 + MATH = 0 + FLASH_ATTENTION = 1 + EFFICIENT_ATTENTION = 2 + CUDNN_ATTENTION = 3 + OVERRIDEABLE = 4 + +def _is_flash_attention_available() -> _bool: ... +def _can_use_cudnn_attention(params: _SDPAParams, debug: _bool) -> _bool: ... +def _can_use_flash_attention(params: _SDPAParams, debug: _bool) -> _bool: ... +def _can_use_mem_efficient_attention(params: _SDPAParams, debug: _bool) -> _bool: ... +def _is_ck_sdpa_available() -> _bool: ... + +# TensorIterator build pipeline (see torch._tensor_iterator). +class _TensorIteratorSpec: + def __init__(self) -> None: ... + outputs: list[Tensor | None] + inputs: list[Tensor] + const_inputs: list[Tensor] + check_all_same_dtype: _bool + check_all_same_device: _bool + promote_inputs_to_common_dtype: _bool + promote_integer_inputs_to_float: _bool + cast_common_dtype_to_outputs: _bool + enforce_safe_casting_to_output: _bool + enforce_linear_iteration: _bool + resize_outputs: _bool + check_mem_overlap: _bool + allow_cpu_scalars: _bool + is_reduction: _bool + static_dtype: _dtype | None + static_device: _device | None + static_shape: list[_int] | None + squash_dims: list[_int] + def build(self) -> _TensorIterator: ... + +class _TensorIterator: + @property + def ndim(self) -> _int: ... + @property + def shape(self) -> memoryview: ... + @property + def numel(self) -> _int: ... + @property + def ntensors(self) -> _int: ... + @property + def ninputs(self) -> _int: ... + @property + def noutputs(self) -> _int: ... + @property + def is_contiguous(self) -> _bool: ... + @property + def is_trivial_1d(self) -> _bool: ... + @property + def common_dtype(self) -> _dtype | None: ... + def tensor(self, index: _int) -> Tensor: ... + def input(self, index: _int = 0) -> Tensor: ... + def output(self, index: _int = 0) -> Tensor: ... + def dtype(self, index: _int = 0) -> _dtype: ... + def device(self, index: _int = 0) -> _device: ... + def strides(self, index: _int) -> memoryview: ... + def element_strides(self, index: _int) -> tuple[_int, ...]: ... + def __repr__(self) -> str: ... + +# Defined in torch/csrc/cuda/GdsFile.cpp +def _gds_register_buffer(t: Storage) -> None: ... +def _gds_deregister_buffer(t: Storage) -> None: ... +def _gds_register_handle(fd: _int) -> _int: ... +def _gds_deregister_handle(handle: _int) -> None: ... +def _gds_load_storage(handle: _int, s: Storage, offset: _int) -> None: ... +def _gds_save_storage(handle: _int, s: Storage, offset: _int) -> None: ... + +# Defined in torch/csrc/cuda/python_comm.cpp +def _broadcast(tensor: Tensor, devices: list[_int]) -> list[Tensor]: ... +def _broadcast_out(tensor: Tensor, out_tensors: list[Tensor]) -> list[Tensor]: ... +def _broadcast_coalesced( + tensors: list[Tensor], + devices: list[_int], + buffer_size: _int, +) -> list[list[Tensor]]: ... +def _scatter( + tensor: Tensor, + devices: list[_int], + chunk_sizes: list[_int] | None, + dim: _int, + streams: list[Stream] | None, +) -> list[Tensor]: ... +def _scatter_out( + tensor: Tensor, + out_tensors: list[Tensor], + dim: _int, + streams: list[Stream] | None, +) -> list[Tensor]: ... +def _gather( + tensors: list[Tensor], + dim: _int, + destination_index: _int | None, +) -> Tensor: ... +def _gather_out(tensors: list[Tensor], out_tensor: Tensor, dim: _int) -> Tensor: ... + +# Defined in torch/csrc/cuda/Stream.cpp +class _CudaStreamBase(Stream): + stream_id: _int + device_index: _int + device_type: _int + + device: _device + cuda_stream: _int + priority: _int + + def __new__( + cls, + priority: _int = 0, + stream_id: _int = 0, + device_index: _int = 0, + stream_ptr: _int = 0, + ) -> Self: ... + def query(self) -> _bool: ... + def synchronize(self) -> None: ... + def priority_range(self) -> tuple[_int, _int]: ... + +# Defined in torch/csrc/cuda/Event.cpp. At the Python C-API level +# ``THCPEventType.tp_base = THPEventClass`` (see Event.cpp), so this +# binding really does inherit from ``torch._C.Event``. Declaring the +# base here lets static checkers (pyrefly, mypy) see the relationship. +class _CudaEventBase(torch._C.Event): + device: _device + cuda_event: _int + + def __new__( + cls, + enable_timing: _bool = False, + blocking: _bool = False, + interprocess: _bool = False, + external: _bool = False, + ) -> Self: ... + @classmethod + def from_ipc_handle(cls, device: _device, ipc_handle: bytes) -> _CudaEventBase: ... + def record(self, stream: _CudaStreamBase | torch.Stream) -> None: ... + def wait(self, stream: _CudaStreamBase | torch.Stream) -> None: ... + def query(self) -> _bool: ... + def elapsed_time(self, other: _CudaEventBase) -> _float: ... + def synchronize(self) -> None: ... + def ipc_handle(self) -> bytes: ... + +# Defined in torch/csrc/cuda/Graph.cpp +class _CUDAGraph: + def __new__(cls, keep_graph: _bool = ...) -> Self: ... + def capture_begin( + self, + pool: _POOL_HANDLE | None = ..., + capture_error_mode: str = "global", + ) -> None: ... + def capture_end(self) -> None: ... + def capture_end_pre(self) -> None: ... + def capture_end_post(self) -> None: ... + def instantiate(self) -> None: ... + def register_generator_state(self, Generator) -> None: ... + def replay(self) -> None: ... + def reset(self) -> None: ... + def pool(self) -> _POOL_HANDLE: ... + def pools(self) -> list[_POOL_HANDLE]: ... + def _retain_pool(self, pool: _POOL_HANDLE) -> None: ... + def enable_debug_mode(self) -> None: ... + def raw_cuda_graph(self) -> _int: ... + def raw_cuda_graph_exec(self) -> _int: ... + @staticmethod + def get_currently_capturing_graph() -> torch.cuda.CUDAGraph: ... + def begin_capture_to_if_node(self, scalar_cuda_pred_tensor): ... + def begin_capture_to_while_node(self, scalar_cuda_pred_tensor): ... + def end_capture_to_conditional_node(self): ... + def set_conditional_handle_for_current_node(self, scalar_cuda_pred_tensor): ... + +# Defined in torch/csrc/cuda/MemPool.cpp +class _MemPool: + def __init__( + self, + allocator: _cuda_CUDAAllocator | None = None, + is_user_created: _bool = True, + use_on_oom: _bool = False, + no_split: _bool = False, + ) -> None: ... + @property + def id(self) -> tuple[_int, _int]: ... + @property + def allocator(self) -> _cuda_CUDAAllocator | None: ... + def use_count(self) -> _int: ... + +def _cuda_isCurrentStreamCapturing() -> _bool: ... +def _graph_pool_handle() -> tuple[_int, _int]: ... + +# Defined in torch/csrc/xpu/Module.cpp +def _xpu_setDevice(device: _int) -> None: ... +def _xpu_exchangeDevice(device: _int) -> _int: ... +def _xpu_maybeExchangeDevice(device: _int) -> _int: ... +def _xpu_getDevice() -> _int: ... +def _xpu_getDeviceCount() -> _int: ... +def _xpu_getArchFlags() -> str | None: ... +def _xpu_init() -> None: ... +def _xpu_setStream(stream_id: _int, device_index: _int, device_type: _int) -> None: ... +def _xpu_getCurrentStream(device: _int) -> tuple: ... +def _xpu_getCurrentRawStream(device: _int) -> _int: ... +def _xpu_getStreamFromExternal(data_ptr: _int, device_index: _int) -> tuple: ... +def _xpu_synchronize(device: _int) -> None: ... +def _xpu_emptyCache() -> None: ... +def _xpu_memoryStats(device: _int) -> dict[str, Any]: ... +def _xpu_resetAccumulatedMemoryStats(device: _int) -> None: ... +def _xpu_resetPeakMemoryStats(device: _int) -> None: ... +def _xpu_getMemoryInfo(device: _int) -> tuple[_int, _int]: ... +def _xpu_canDeviceAccessPeer(device: _int, peer: _int) -> _bool: ... +def _xpu_sleep(cycles: _int) -> None: ... +def _xpu_getMemoryFraction(device: _int) -> _float: ... +def _xpu_setMemoryFraction(fraction: _float, device: _int) -> None: ... +def _xpu_memorySnapshot(mempool_id: tuple[_int, _int] | None) -> dict[str, Any]: ... +def _xpu_recordMemoryHistory( + enabled: Literal["state", "all"] | None, + context: Literal["state", "alloc", "all"] | None, + stacks: Literal["python", "all"], + max_entries: _int, + clear_history: _bool, + skip_actions: list[str] | None, +) -> None: ... +def _xpu_beginAllocateToPool(device: _int, mempool_id: tuple[_int, _int]) -> None: ... +def _xpu_beginAllocateCurrentThreadToPool( + device: _int, + mempool_id: tuple[_int, _int], +) -> None: ... +def _xpu_endAllocateToPool(device: _int, mempool_id: tuple[_int, _int]) -> None: ... +def _xpu_releasePool(device: _int, mempool_id: tuple[_int, _int]) -> None: ... + +class _XpuDeviceProperties: + name: str + platform_name: str + vendor: str + device_id: _int + driver_version: str + version: str + max_compute_units: _int + gpu_eu_count: _int + max_work_group_size: _int + max_num_sub_groups: _int + memory_clock_rate: _int + memory_bus_width: _int + sub_group_sizes: list[_int] + local_mem_size: _int + last_level_cache_size: _int + has_fp16: _bool + has_fp64: _bool + has_atomic64: _bool + has_bfloat16_conversions: _bool + has_subgroup_matrix_multiply_accumulate: _bool + has_subgroup_matrix_multiply_accumulate_tensor_float32: _bool + has_subgroup_2d_block_io: _bool + is_integrated_gpu: _bool + total_memory: _int + gpu_subslice_count: _int + architecture: _int + type: str + uuid: Any + +class _xpu_XPUAllocator: ... + +def _xpu_customAllocator(alloc_fn: _int, free_fn: _int) -> _xpu_XPUAllocator: ... +def _xpu_changeCurrentAllocator(allocator: _xpu_XPUAllocator) -> None: ... +def _xpu_getAllocator() -> _xpu_XPUAllocator: ... + +# Defined in torch/csrc/xpu/Stream.cpp +class _XpuStreamBase(Stream): + stream_id: _int + device_index: _int + device_type: _int + + device: _device + sycl_queue: _int + priority: _int + + def __new__( + cls, + priority: _int = 0, + stream_id: _int = 0, + device_index: _int = 0, + device_type: _int = 0, + ) -> Self: ... + def query(self) -> _bool: ... + def synchronize(self) -> None: ... + @staticmethod + def priority_range() -> tuple: ... + +# Defined in torch/csrc/xpu/Event.cpp +class _XpuEventBase: + device: _device + sycl_event: _int + + def __new__(cls, enable_timing: _bool = False) -> Self: ... + def record(self, stream: _XpuStreamBase | torch.Stream) -> None: ... + def wait(self, stream: _XpuStreamBase | torch.Stream) -> None: ... + def query(self) -> _bool: ... + def elapsed_time(self, other: _XpuEventBase) -> _float: ... + def synchronize(self) -> None: ... + +# Defined in torch/csrc/xpu/MemPool.cpp +class _XPUMemPool: + def __init__( + self, + allocator: _xpu_XPUAllocator | None = None, + is_user_created: _bool = True, + use_on_oom: _bool = False, + ) -> None: ... + @property + def id(self) -> tuple[_int, _int]: ... + @property + def allocator(self) -> _xpu_XPUAllocator | None: ... + def use_count(self) -> _int: ... + +# Defined in torch/csrc/xpu/Graph.cpp +class _XPUGraph: + def __new__(cls, keep_graph: _bool = ...) -> Self: ... + def capture_begin( + self, + pool: XPU_POOL_HANDLE | None = ..., + ) -> None: ... + def capture_end(self) -> None: ... + def instantiate(self) -> None: ... + def register_generator_state(self, Generator) -> None: ... + def replay(self) -> None: ... + def reset(self) -> None: ... + def pool(self) -> XPU_POOL_HANDLE: ... + def enable_debug_mode(self) -> None: ... + def debug_dump(self, debug_path: str) -> None: ... + def raw_xpu_graph(self) -> _int: ... + def raw_xpu_graph_exec(self) -> _int: ... + +def _xpu_graph_pool_handle() -> tuple[_int, _int]: ... +def _xpu_isCurrentStreamCapturing() -> _bool: ... + +# Defined in torch/csrc/DataLoader.cpp +def _set_worker_signal_handlers( + *arg: Any, +) -> None: ... # THPModule_setWorkerSignalHandlers +def _set_worker_pids( + key: _int, + child_pids: tuple[_int, ...], +) -> None: ... # THPModule_setWorkerPIDs +def _remove_worker_pids(loader_id: _int) -> None: ... # THPModule_removeWorkerPIDs +def _error_if_any_worker_fails() -> None: ... # THPModule_errorIfAnyWorkerFails + +# Defined in torch/csrc/DeviceAccelerator.cpp +def _accelerator_getAccelerator() -> _device: ... +def _accelerator_setDeviceIndex(device_index: _int) -> None: ... +def _accelerator_getDeviceIndex() -> _int: ... +def _accelerator_getDeviceCapability(device_index: _int) -> dict[str, Any]: ... +def _accelerator_setStream(Stream) -> None: ... +def _accelerator_getStream(device_index: _int) -> Stream: ... +def _accelerator_synchronizeDevice(device_index: _int) -> None: ... +def _accelerator_exchangeDevice(device_index: _int) -> _int: ... +def _accelerator_maybeExchangeDevice(device_index: _int) -> _int: ... +def _accelerator_isAllocatorInitialized() -> _bool: ... +def _accelerator_emptyCache() -> None: ... +def _accelerator_emptyHostCache() -> None: ... +def _accelerator_getDeviceStats(device_index: _int) -> dict[str, Any]: ... +def _accelerator_resetAccumulatedStats(device_index: _int) -> None: ... +def _accelerator_resetPeakStats(device_index: _int) -> None: ... +def _accelerator_getMemoryInfo(device_index: _int) -> tuple[_int, _int]: ... +def _accelerator_getAllocatorSettings() -> str: ... +def _accelerator_setAllocatorSettings(env: str) -> None: ... +def _accelerator_getDefaultGenerator(device_index: _int) -> Generator: ... + +class _acceleratorGraph: + def __new__(cls, _bool) -> Self: ... + def __init__(self, _bool) -> None: ... + def capture_begin( + self, + pool: tuple[_int, _int] | None = None, + capture_error_mode: Literal[ + "default", "global", "thread_local", "relaxed" + ] = "default", + ) -> None: ... + def capture_end(self) -> None: ... + def instantiate(self) -> None: ... + def replay(self) -> None: ... + def reset(self) -> None: ... + def pool(self) -> tuple[_int, _int]: ... + def enable_debug_mode(self) -> None: ... + def debug_dump(self, path: str) -> None: ... + +# Defined in torch/csrc/jit/python/python_tracer.cpp +class TracingState: + def push_scope(self, scope_name: str) -> None: ... + def pop_scope(self) -> None: ... + def current_scope(self) -> str: ... + def set_graph(self, graph: Graph) -> None: ... + def graph(self) -> Graph: ... + +def _create_graph_by_tracing( + func: Callable[..., Any], + inputs: Any, + var_name_lookup_fn: Callable[[Tensor], str], + strict: Any, + force_outplace: Any, + self: Any = None, + argument_names: list[str] = ..., +) -> tuple[Graph, Stack]: ... +def _tracer_warn_use_python(): ... +def _get_tracing_state() -> TracingState: ... + +# Defined in torch/csrc/jit/python/python_ir.cpp +# Not actually defined in python_ir.cpp, not sure where they are. +class IValue: ... + +Stack: TypeAlias = list[IValue] + +class JitType: + annotation_str: str + def isSubtypeOf(self, other: JitType) -> _bool: ... + def with_dtype(self, dtype: _dtype) -> JitType: ... + def with_sizes(self, sizes: list[_int | None]) -> JitType: ... + def kind(self) -> str: ... + def scalarType(self) -> str | None: ... + def getElementType(self) -> JitType: ... + def dtype(self) -> _dtype | None: ... + +class InferredType: + def __init__(self, arg: JitType | str) -> None: ... + def type(self) -> JitType: ... + def success(self) -> _bool: ... + def reason(self) -> str: ... + +class Type(JitType): + def str(self) -> _str: ... + def containedTypes(self) -> list[JitType]: ... + def dim(self) -> _int | None: ... + def undefined(self) -> _bool | None: ... + def sizes(self) -> list[_int] | None: ... + def symbol_sizes(self) -> list[_int] | None: ... + def varyingSizes(self) -> list[_int | None] | None: ... + def strides(self) -> list[_int] | None: ... + def contiguous(self) -> Self: ... + def device(self) -> _device | None: ... + def is_interface_type(self) -> _bool: ... + def requires_grad(self) -> _bool: ... + @property + def annotation_string(self) -> _str: ... + +class AnyType(JitType): + @staticmethod + def get() -> AnyType: ... + +class NoneType(JitType): + @staticmethod + def get() -> NoneType: ... + +class BoolType(JitType): + @staticmethod + def get() -> BoolType: ... + +class FloatType(JitType): + @staticmethod + def get() -> FloatType: ... + +class ComplexType(JitType): + @staticmethod + def get() -> ComplexType: ... + +class IntType(JitType): + @staticmethod + def get() -> IntType: ... + +class SymIntType(JitType): + @staticmethod + def get() -> SymIntType: ... + +class SymBoolType(JitType): + @staticmethod + def get() -> SymBoolType: ... + +class NumberType(JitType): + @staticmethod + def get() -> NumberType: ... + +class StringType(JitType): + @staticmethod + def get() -> StringType: ... + +class DeviceObjType(JitType): + @staticmethod + def get() -> DeviceObjType: ... + +class _GeneratorType(JitType): + @staticmethod + def get() -> _GeneratorType: ... + +class StreamObjType(JitType): + @staticmethod + def get() -> StreamObjType: ... + +class ListType(JitType): + def __init__(self, a: JitType) -> None: ... + def getElementType(self) -> JitType: ... + @staticmethod + def ofInts() -> ListType: ... + @staticmethod + def ofTensors() -> ListType: ... + @staticmethod + def ofFloats() -> ListType: ... + @staticmethod + def ofComplexDoubles() -> ListType: ... + @staticmethod + def ofBools() -> ListType: ... + @staticmethod + def ofStrings() -> ListType: ... + +class DictType(JitType): + def __init__(self, key: JitType, value: JitType) -> None: ... + def getKeyType(self) -> JitType: ... + def getValueType(self) -> JitType: ... + +class TupleType(JitType): + def __init__(self, a: list[JitType | None]) -> None: ... + def elements(self) -> list[JitType]: ... + +class UnionType(JitType): + def __init__(self, a: list[JitType]) -> None: ... + +class ClassType(JitType): + def __init__(self, qualified_name: str) -> None: ... + def qualified_name(self) -> str: ... + +class InterfaceType(JitType): + def __init__(self, qualified_name: str) -> None: ... + def getMethod(self, name: str) -> FunctionSchema | None: ... + def getMethodNames(self) -> list[str]: ... + +JitTypeT = TypeVar("JitTypeT", bound=JitType) # noqa: PYI001 + +class OptionalType(JitType, Generic[JitTypeT]): + def __init__(self, a: JitTypeT) -> None: ... + def getElementType(self) -> JitTypeT: ... + @staticmethod + def ofTensor() -> OptionalType: ... + +class FutureType(JitType): + def __init__(self, a: JitType) -> None: ... + def getElementType(self) -> JitType: ... + +class AwaitType(JitType): + def __init__(self, a: JitType) -> None: ... + def getElementType(self) -> JitType: ... + +class RRefType(JitType): + def __init__(self, a: JitType) -> None: ... + +class EnumType(JitType): + def __init__( + self, + qualified_name: str, + value_type: JitType, + enum_names_values: list[Any], + ) -> None: ... + +class TensorType(JitType): + @classmethod + def get(cls) -> TensorType: ... + @classmethod + def getInferred(cls) -> TensorType: ... + def with_sizes(self, other: list[_int | None] | None) -> TensorType: ... + def sizes(self) -> list[_int] | None: ... + def varyingSizes(self) -> list[_int | None] | None: ... + def strides(self) -> list[_int] | None: ... + def device(self) -> _device | None: ... + def dim(self) -> _int: ... + def dtype(self) -> _dtype | None: ... + @staticmethod + def create_from_tensor(t: Tensor) -> TensorType: ... + +# Defined in torch/csrc/jit/python/python_tree_views.cpp +class SourceRange: ... +class TreeView: ... + +class Ident(TreeView): + @property + def name(self) -> str: ... + +class ClassDef(TreeView): ... + +class Def(TreeView): + def name(self) -> Ident: ... + +class Decl(TreeView): ... + +# Defined in torch/csrc/distributed/rpc/init.cpp +def _rpc_init() -> _bool: ... + +# Defined in torch/csrc/distributed/autograd/init.cpp +def _dist_autograd_init() -> _bool: ... + +# Defined in torch/csrc/distributed/c10d/init.cpp +def _c10d_init() -> _bool: ... + +# Defined in torch/csrc/distributed/rpc/testing/init.cpp +def _faulty_agent_init() -> _bool: ... +def _register_py_class_for_device(device: str, cls: Any) -> None: ... + +# Defined in torch/csrc/Module.cpp +def _current_graph_task_id() -> _int: ... +def _current_autograd_node() -> _Node: ... +def _will_engine_execute_node(node: _Node) -> _bool: ... +def _dispatch_key_set(tensor) -> str: ... + +# Defined in torch/csrc/Exceptions.cpp +class AcceleratorError(RuntimeError): ... +class OutOfMemoryError(RuntimeError): ... +class _DistError(RuntimeError): ... +class _DistBackendError(RuntimeError): ... +class _DistStoreError(RuntimeError): ... +class _DistNetworkError(RuntimeError): ... +class _DistQueueEmptyError(_DistStoreError): ... + +# Defined in torch/csrc/profiler/init.cpp +class CapturedTraceback: ... + +def gather_traceback(python: _bool, script: _bool, cpp: _bool) -> CapturedTraceback: ... +def symbolize_tracebacks( + tracebacks: list[CapturedTraceback], +) -> list[dict[str, Any]]: ... +def _load_mobile_module_from_file(filename: str): ... +def _load_mobile_module_from_bytes(bytes_: bytes): ... +def _load_jit_module_from_file(filename: str): ... +def _load_jit_module_from_bytes(bytes_: bytes): ... +def _save_mobile_module(m: LiteScriptModule, filename: str): ... +def _save_jit_module(m: ScriptModule, filename: str, extra_files: dict[str, Any]): ... +def _save_mobile_module_to_bytes(m: LiteScriptModule) -> bytes: ... +def _save_jit_module_to_bytes( + m: ScriptModule, + extra_files: dict[str, Any], +) -> bytes: ... +def _get_module_info_from_flatbuffer(data: bytes): ... +def _jit_resolve_packet(op_name: str, *args, **kwargs) -> str: ... +def _swap_tensor_impl(t1: Tensor, t2: Tensor): ... +def _pickle_save(obj: Any) -> bytes: ... +def _pickle_load_obj(bs: bytes) -> Any: ... + +# Defined in torch/csrc/jit/runtime/static/init.cpp +def _jit_to_static_module(graph_or_module: Graph | ScriptModule) -> Any: ... +def _fuse_to_static_module( + graph_or_module: Graph | ScriptModule, + min_size: _int, +) -> Any: ... + +# Defined in torch/csrc/fx/node.cpp +def _fx_map_aggregate(a: Any, fn: Callable[[Any], Any]) -> Any: ... +def _fx_map_arg(a: Any, fn: Callable[[Any], Any]) -> Any: ... + +class _NodeBase: + _erased: _bool + _prev: FxNode + _next: FxNode + def __init__( + self, + graph: Any, + name: str, + op: str, + target: Any, + return_type: Any, + ) -> None: ... + def _update_args_kwargs(self, args: tuple[Any, ...], kwargs: dict[str, Any]): ... + def _prepend(self, n: FxNode) -> None: ... + def _replace_input_with(self, old_input: FxNode, new_input: FxNode) -> None: ... + def _remove_from_list(self) -> None: ... + def __lt__(self, n: Self) -> _bool: ... + def __gt__(self, n: Self) -> _bool: ... + def __le__(self, n: Self) -> _bool: ... + def __ge__(self, n: Self) -> _bool: ... + +class _NodeIter(Iterator[FxNode]): + def __init__(self, root: FxNode, reversed: _bool) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> FxNode: ... + +# Defined in torch/csrc/inductor/static_launcher/cuda.cpp +class _StaticCudaLauncher: + @staticmethod + def _load_kernel( + cubin_file: str, + func_name: str, + shared_mem_bytes: _int, + device: _int, + ) -> tuple[_int, _int, _int]: ... + @staticmethod + def _launch_kernel( + func: _int, + grid_x: _int, + grid_y: _int, + grid_z: _int, + num_warps: _int, + shared_mem_bytes: _int, + arg_types: str, + args: tuple[Any, ...], + stream: _int, + ) -> None: ... + +# Defined in torch/csrc/inductor/static_launcher/xpu.cpp +class _StaticXpuLauncher(_StaticCudaLauncher): ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_acc/__init__.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_acc/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..3ee9b16c225b5ed6a34bc9ab9198eb38ad1e52a4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_acc/__init__.pyi @@ -0,0 +1,15 @@ +from torch import Tensor +from torch.types import _dtype, _int, Device + +# Defined in torch/csrc/acc/Module.cpp +class PrivateUse1Hooks: + def has_primary_context(self, device_index: _int) -> bool: ... + def is_built(self) -> bool: ... + def is_available(self) -> bool: ... + +class DeviceGuard: + def type_(self) -> Device: ... + +def register_python_privateuseone_device_guard(guard: DeviceGuard) -> bool: ... +def register_python_privateuseone_hook(hook: PrivateUse1Hooks) -> bool: ... +def create_empty_tensor(shape: tuple[_int, ...], dtype: _dtype) -> Tensor: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_aoti.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_aoti.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5002c1525899ca5cd4b411769201cbcd9713cdb7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_aoti.pyi @@ -0,0 +1,183 @@ +from ctypes import c_void_p +from typing import overload, Protocol + +from torch import Tensor + +# Defined in torch/csrc/inductor/aoti_runner/pybind.cpp + +# Tensor to AtenTensorHandle +def unsafe_alloc_void_ptrs_from_tensors(tensors: list[Tensor]) -> list[c_void_p]: ... +def unsafe_alloc_void_ptr_from_tensor(tensor: Tensor) -> c_void_p: ... + +# AtenTensorHandle to Tensor +def alloc_tensors_by_stealing_from_void_ptrs( + handles: list[c_void_p], +) -> list[Tensor]: ... +def alloc_tensor_by_stealing_from_void_ptr( + handle: c_void_p, +) -> Tensor: ... + +class AOTIModelContainerRunner(Protocol): + def run( + self, inputs: list[Tensor], stream_handle: c_void_p = ... + ) -> list[Tensor]: ... + def get_call_spec(self) -> list[str]: ... + def get_constant_names_to_original_fqns(self) -> dict[str, str]: ... + def get_constant_names_to_dtypes(self) -> dict[str, int]: ... + def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ... + def update_constant_buffer( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + user_managed: bool = ..., + ) -> None: ... + def swap_constant_buffer(self) -> None: ... + def free_inactive_constant_buffer(self) -> None: ... + +class AOTIModelContainerRunnerCpu: + def __init__(self, model_so_path: str, num_models: int) -> None: ... + def run( + self, inputs: list[Tensor], stream_handle: c_void_p = ... + ) -> list[Tensor]: ... + def get_call_spec(self) -> list[str]: ... + def get_constant_names_to_original_fqns(self) -> dict[str, str]: ... + def get_constant_names_to_dtypes(self) -> dict[str, int]: ... + def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ... + def update_constant_buffer( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + user_managed: bool = ..., + ) -> None: ... + def swap_constant_buffer(self) -> None: ... + def free_inactive_constant_buffer(self) -> None: ... + +class AOTIModelContainerRunnerCuda: + @overload + def __init__(self, model_so_path: str, num_models: int) -> None: ... + @overload + def __init__( + self, model_so_path: str, num_models: int, device_str: str + ) -> None: ... + @overload + def __init__( + self, model_so_path: str, num_models: int, device_str: str, cubin_dir: str + ) -> None: ... + def run( + self, inputs: list[Tensor], stream_handle: c_void_p = ... + ) -> list[Tensor]: ... + def get_call_spec(self) -> list[str]: ... + def get_constant_names_to_original_fqns(self) -> dict[str, str]: ... + def get_constant_names_to_dtypes(self) -> dict[str, int]: ... + def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ... + def update_constant_buffer( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + user_managed: bool = ..., + ) -> None: ... + def update_constant_buffer_from_cpu( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + ) -> None: ... + def swap_constant_buffer(self) -> None: ... + def free_inactive_constant_buffer(self) -> None: ... + +class AOTIModelContainerRunnerXpu: + @overload + def __init__(self, model_so_path: str, num_models: int) -> None: ... + @overload + def __init__( + self, model_so_path: str, num_models: int, device_str: str + ) -> None: ... + @overload + def __init__( + self, model_so_path: str, num_models: int, device_str: str, kernel_bin_dir: str + ) -> None: ... + def run( + self, inputs: list[Tensor], stream_handle: c_void_p = ... + ) -> list[Tensor]: ... + def get_call_spec(self) -> list[str]: ... + def get_constant_names_to_original_fqns(self) -> dict[str, str]: ... + def get_constant_names_to_dtypes(self) -> dict[str, int]: ... + def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ... + def update_constant_buffer( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + user_managed: bool = ..., + ) -> None: ... + def update_constant_buffer_from_cpu( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + ) -> None: ... + def swap_constant_buffer(self) -> None: ... + def free_inactive_constant_buffer(self) -> None: ... + +class AOTIModelContainerRunnerMps: + def __init__(self, model_so_path: str, num_models: int) -> None: ... + def run( + self, inputs: list[Tensor], stream_handle: c_void_p = ... + ) -> list[Tensor]: ... + def get_call_spec(self) -> list[str]: ... + def get_constant_names_to_original_fqns(self) -> dict[str, str]: ... + def get_constant_names_to_dtypes(self) -> dict[str, int]: ... + def extract_constants_map(self, use_inactive: bool) -> dict[str, Tensor]: ... + def update_constant_buffer( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + user_managed: bool = ..., + ) -> None: ... + def update_constant_buffer_from_cpu( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + ) -> None: ... + def swap_constant_buffer(self) -> None: ... + def free_inactive_constant_buffer(self) -> None: ... + +# Defined in torch/csrc/inductor/aoti_package/pybind.cpp +class AOTIModelPackageLoader: + def __init__( + self, + model_package_path: str, + model_name: str, + run_single_threaded: bool, + num_runners: int, + device_index: int, + ) -> None: ... + def get_metadata(self) -> dict[str, str]: ... + def run( + self, inputs: list[Tensor], stream_handle: c_void_p = ... + ) -> list[Tensor]: ... + def boxed_run( + self, inputs: list[Tensor], stream_handle: c_void_p = ... + ) -> list[Tensor]: ... + def get_call_spec(self) -> list[str]: ... + def get_constant_fqns(self) -> list[str]: ... + def load_constants( + self, + constants_map: dict[str, Tensor], + use_inactive: bool, + check_full_update: bool, + user_managed: bool = ..., + allow_h2d_copy: bool = ..., + ) -> None: ... + def update_constant_buffer( + self, + tensor_map: dict[str, Tensor], + use_inactive: bool, + validate_full_updates: bool, + user_managed: bool = ..., + ) -> None: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_autograd.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_autograd.pyi new file mode 100644 index 0000000000000000000000000000000000000000..6a67ccbd2e3798fa9fc3b45f0bf391545680e2aa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_autograd.pyi @@ -0,0 +1,167 @@ +# mypy: allow-untyped-defs +from collections.abc import Callable +from enum import Enum +from typing import Any + +import torch +from torch._C._profiler import ( + _ProfilerEvent, + ActiveProfilerType, + ProfilerActivity, + ProfilerConfig, +) + +# Defined in torch/csrc/autograd/init.cpp + +class DeviceType(Enum): + CPU = ... + CUDA = ... + XPU = ... + MKLDNN = ... + OPENGL = ... + OPENCL = ... + IDEEP = ... + HIP = ... + FPGA = ... + MAIA = ... + XLA = ... + MTIA = ... + MPS = ... + HPU = ... + Meta = ... + Vulkan = ... + Metal = ... + PrivateUse1 = ... + +class ProfilerEvent: + def cpu_elapsed_us(self, other: ProfilerEvent) -> float: ... + def cpu_memory_usage(self) -> int: ... + def cuda_elapsed_us(self, other: ProfilerEvent) -> float: ... + def privateuse1_elapsed_us(self, other: ProfilerEvent) -> float: ... + def cuda_memory_usage(self) -> int: ... + def device(self) -> int: ... + def handle(self) -> int: ... + def has_cuda(self) -> bool: ... + def is_remote(self) -> bool: ... + def kind(self) -> int: ... + def name(self) -> str: ... + def node_id(self) -> int: ... + def sequence_nr(self) -> int: ... + def shapes(self) -> list[list[int]]: ... + def thread_id(self) -> int: ... + def flops(self) -> float: ... + def is_async(self) -> bool: ... + +class _KinetoEvent: + def name(self) -> str: ... + def overload_name(self) -> str: ... + def device_index(self) -> int: ... + def device_resource_id(self) -> int: ... + def start_ns(self) -> int: ... + def end_ns(self) -> int: ... + def duration_ns(self) -> int: ... + def is_async(self) -> bool: ... + def linked_correlation_id(self) -> int: ... + def external_id(self) -> int: ... + def shapes(self) -> list[list[int]]: ... + def dtypes(self) -> list[str]: ... + def concrete_inputs(self) -> list[Any]: ... + def kwinputs(self) -> dict[str, Any]: ... + def device_type(self) -> DeviceType: ... + def start_thread_id(self) -> int: ... + def end_thread_id(self) -> int: ... + def correlation_id(self) -> int: ... + def fwd_thread_id(self) -> int: ... + def stack(self) -> list[str]: ... + def scope(self) -> int: ... + def sequence_nr(self) -> int: ... + def flops(self) -> int: ... + def cuda_elapsed_us(self) -> int: ... + def privateuse1_elapsed_us(self) -> int: ... + def is_user_annotation(self) -> bool: ... + def is_python_function(self) -> bool: ... + def is_hidden_event(self) -> bool: ... + def metadata_json(self) -> str: ... + def activity_type(self) -> str: ... + def extra_meta(self) -> dict[str, str]: ... + def typed_metadata(self) -> dict[str, Any]: ... + def flow_id(self) -> int: ... + def flow_type(self) -> int: ... + def flow_start(self) -> bool: ... + def structured_input_shapes(self) -> list[list[int] | list[list[int]]]: ... + def structured_input_strides(self) -> list[list[int] | list[list[int]]]: ... + def python_id(self) -> int: ... + def python_parent_id(self) -> int: ... + def python_module_id(self) -> int: ... + +class _ProfilerResult: + def events(self) -> list[_KinetoEvent]: ... + def legacy_events(self) -> list[list[ProfilerEvent]]: ... + def save(self, path: str) -> None: ... + def experimental_event_tree(self) -> list[_ProfilerEvent]: ... + def trace_start_ns(self) -> int: ... + +class SavedTensor: + def unpack(self) -> torch.Tensor: ... + +def _make_saved_tensor( + tensor: torch.Tensor, + is_output: bool, + is_inplace_on_view: bool = False, +) -> SavedTensor: ... +def _enable_profiler( + config: ProfilerConfig, + activities: set[ProfilerActivity], +) -> None: ... +def _prepare_profiler( + config: ProfilerConfig, + activities: set[ProfilerActivity], + activity_filter: dict[ProfilerActivity, set[str]] = ..., +) -> None: ... +def _toggle_collection_dynamic( + enable: bool, + activities: set[ProfilerActivity], +) -> None: ... +def _disable_profiler() -> _ProfilerResult: ... +def _profiler_enabled() -> bool: ... +def _add_metadata_json(key: str, value: str) -> None: ... +def _is_kineto_stopped() -> bool: ... +def _kineto_step() -> None: ... +def _get_current_graph_task_keep_graph() -> bool: ... +def _get_sequence_nr() -> int: ... +def kineto_available() -> bool: ... +def _record_function_with_args_enter(name: str, *args) -> torch.Tensor: ... +def _record_function_with_args_exit(handle: torch.Tensor) -> None: ... +def _supported_activities() -> set[ProfilerActivity]: ... +def _enable_record_function(enable: bool) -> None: ... +def _set_empty_test_observer(is_global: bool, sampling_prob: float) -> None: ... +def _push_saved_tensors_default_hooks( + pack_hook: Callable[[torch.Tensor], Any], + unpack_hook: Callable[[Any], torch.Tensor], +) -> None: ... +def _pop_saved_tensors_default_hooks() -> None: ... +def _push_node_creation_hook(hook: Callable[[Any], None]) -> None: ... +def _pop_node_creation_hook() -> None: ... +def _top_saved_tensors_default_hooks( + ignore_is_tracing: bool, +) -> tuple[Callable[[torch.Tensor], Any], Callable[[Any], torch.Tensor]]: ... +def _unsafe_set_version_counter( + t: tuple[torch.Tensor, ...], prev_version: tuple[int, ...] +) -> None: ... +def _enable_profiler_legacy(config: ProfilerConfig) -> None: ... +def _disable_profiler_legacy() -> list[list[ProfilerEvent]]: ... +def _profiler_type() -> ActiveProfilerType: ... +def _saved_tensors_hooks_enable() -> None: ... +def _saved_tensors_hooks_disable(message: str, fail_if_non_empty=True) -> None: ... +def _saved_tensors_hooks_get_disabled_error_message() -> str | None: ... +def _saved_tensors_hooks_set_tracing(is_tracing: bool) -> bool: ... + +class CreationMeta(Enum): + DEFAULT = ... + IN_CUSTOM_FUNCTION = ... + MULTI_OUTPUT_NODE = ... + NO_GRAD_MODE = ... + INFERENCE_MODE = ... + +def _set_creation_meta(t: torch.Tensor, creation_meta: CreationMeta) -> None: ... +def _get_creation_meta(t: torch.Tensor) -> CreationMeta: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_cpu.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_cpu.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4d8f2edc430f4611460050a3931886647a1bf31d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_cpu.pyi @@ -0,0 +1,8 @@ +from typing import Any + +from torch.types import _bool + +# Defined in torch/csrc/cpu/Module.cpp + +def _init_amx() -> _bool: ... +def _get_cpu_capability() -> dict[str, Any]: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_cudnn.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_cudnn.pyi new file mode 100644 index 0000000000000000000000000000000000000000..cfea3f956f2a373dfe6895743a49a3c6cec439fa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_cudnn.pyi @@ -0,0 +1,14 @@ +from enum import IntEnum + +# Defined in torch/csrc/cuda/shared/cudnn.cpp +is_cuda: bool + +def getRuntimeVersion() -> tuple[int, int, int]: ... +def getCompileVersion() -> tuple[int, int, int]: ... +def getVersionInt() -> int: ... + +class RNNMode(IntEnum): + rnn_relu = ... + rnn_tanh = ... + lstm = ... + gru = ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_cusparselt.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_cusparselt.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a1c4bbb217777d50b9a3384da11d9992db5e18f0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_cusparselt.pyi @@ -0,0 +1 @@ +def getVersionInt() -> int: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_distributed.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_distributed.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c8416f60edca35493ad7c1703cf2e27d58975be0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_distributed.pyi @@ -0,0 +1,21 @@ +# This module is defined in torch/csrc/distributed/python_placement.cpp + +class Placement: + def is_partial(self, reduce_op: str | None = None) -> bool: ... + def is_replicate(self) -> bool: ... + def is_shard(self, dim: int | None = None) -> bool: ... + +class Shard(Placement): + dim: int + def __init__(self, dim: int): ... + +class StridedShard(Placement): + dim: int + split_factor: int + def __init__(self, dim: int, *, split_factor: int): ... + +class Replicate(Placement): ... + +class Partial(Placement): + reduce_op: str + def __init__(self, reduce_op: str | None = None): ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_distributed_autograd.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_distributed_autograd.pyi new file mode 100644 index 0000000000000000000000000000000000000000..6e1e39bec2927c046455928ff74bc7de9683e66f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_distributed_autograd.pyi @@ -0,0 +1,26 @@ +from typing import Any + +import torch + +# This module is defined in torch/csrc/distributed/autograd/init.cpp + +class DistAutogradContext: + def _context_id(self) -> int: ... + def _recv_functions(self) -> dict[int, Any]: ... + def _send_functions(self) -> dict[int, Any]: ... + def _known_worker_ids(self) -> set[int]: ... + +def _new_context() -> DistAutogradContext: ... +def _release_context(context_id: int) -> None: ... +def _get_max_id() -> int: ... +def _is_valid_context(worker_id: int) -> bool: ... +def _retrieve_context(context_id: int) -> DistAutogradContext: ... +def _current_context() -> DistAutogradContext: ... +def _init(worker_id: int) -> None: ... +def _get_debug_info() -> dict[str, str]: ... +def backward( + context_id: int, + roots: list[torch.Tensor], + retain_graph: bool = False, +) -> None: ... +def get_gradients(context_id: int) -> dict[torch.Tensor, torch.Tensor]: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_distributed_c10d.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_distributed_c10d.pyi new file mode 100644 index 0000000000000000000000000000000000000000..62c28e342c8f55c4e93ef5671c21d7616a76b0d7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_distributed_c10d.pyi @@ -0,0 +1,1184 @@ +# mypy: allow-untyped-defs +# mypy: disable-error-code="type-arg" +from collections.abc import Callable +from datetime import timedelta +from enum import Enum +from typing import Any, overload + +import torch +from torch import Tensor +from torch._C import ScriptObject +from torch._C._autograd import DeviceType +from torch.distributed.distributed_c10d import GroupName +from torch.futures import Future + +# This module is defined in torch/csrc/distributed/c10d/init.cpp + +_DEFAULT_FIRST_BUCKET_BYTES: int +_DEFAULT_NO_TIMEOUT: timedelta +_DEFAULT_PG_TIMEOUT: timedelta +_DEFAULT_PG_NCCL_TIMEOUT: timedelta + +class BuiltinCommHookType(Enum): + ALLREDUCE = ... + FP16_COMPRESS = ... + +def _register_comm_hook(reducer: Reducer, state: Any, comm_hook: Any): ... +def _register_builtin_comm_hook( + reducer: Reducer, + comm_hook_type: BuiltinCommHookType, +): ... +def _set_global_rank(rank: int) -> None: ... +def _hash_tensors(tensors: list[Tensor]) -> int: ... + +class GradBucket: + def index(self) -> int: ... + def buffer(self) -> Tensor: ... + def gradients(self) -> list[Tensor]: ... + def is_last(self) -> bool: ... + def set_buffer(self, tensor: Tensor) -> None: ... + def parameters(self) -> list[Tensor]: ... + +class Reducer: + def __init__( + self, + params: list[Tensor], + bucket_indices: list[list[int]], + per_bucket_size_limits: list[int], + process_group: ProcessGroup, + expect_sparse_gradients: list[bool] = ..., + bucket_bytes_cap: int = ..., # kDefaultBucketBytesCap in reducer.hpp + find_unused_parameters: bool = ..., + gradient_as_bucket_view: bool = ..., + param_to_name_mapping: dict[int, str] = ..., + first_bucket_types_cap: int = ..., # kDefaultFirstBucketBytes in reducer.hpp + skip_all_reduce_unused_params: bool = ..., + use_python_reducer: bool = ..., + bucket_bytes_cap_list: list[int] = ..., + batched_grad_copy: bool = ..., + ) -> None: ... + def prepare_for_forward(self) -> None: ... + def prepare_for_backward(self, output: list[Tensor]) -> None: ... + def get_backward_stats(self) -> list[int]: ... + def _install_post_backward_futures(self, futures: list[Future]) -> None: ... + def _rebuild_buckets(self) -> bool: ... + def _get_zeros_like_grad_buckets(self) -> list[GradBucket]: ... + def _push_all_rebuilt_params(self) -> None: ... + def _set_forward_pass_work_handle( + self, + work: Work, + use_static_world_size: bool, + ): ... + def _get_local_used_map(self) -> Tensor: ... + def _set_ddp_runtime_logging_sample_rate(self, sample_rate: int) -> None: ... + def _set_static_graph(self) -> None: ... + def _run_comm_hook(self, bucket: GradBucket) -> Future: ... + def set_logger(self, logger: Logger) -> None: ... + def _remove_autograd_hooks(self) -> None: ... + def _check_reducer_finalized(self) -> None: ... + def _set_sparse_metadata(self, global_unique_ids: dict[str, Tensor]) -> None: ... + def _reset_state(self) -> None: ... + def _update_process_group(self, new_process_group: ProcessGroup) -> None: ... + +class DDPLoggingData: + strs_map: dict[str, str] + ints_map: dict[str, int] + +class Logger: + def __init__(self, reducer: Reducer) -> None: ... + def set_construction_data_and_log( + self, + module_name: str, + device_ids: list[int], + output_device: int, + broadcast_buffers: bool, + has_sync_bn: bool, + static_graph: bool, + ) -> None: ... + def set_runtime_stats_and_log(self) -> None: ... + def set_error_and_log(self, error: str) -> None: ... + def _get_ddp_logging_data(self) -> DDPLoggingData: ... + def _set_comm_hook_name(self, comm_hook: str) -> None: ... + def _set_uneven_input_join(self) -> None: ... + def _set_static_graph(self) -> None: ... + +class _WorkerServer: + port: int + + def __init__(self, host_or_file: str, port: int = ...) -> None: ... + def shutdown(self) -> None: ... + +class DebugLevel(Enum): + OFF = ... + INFO = ... + DETAIL = ... + +def get_debug_level() -> DebugLevel: ... +def set_debug_level(level: DebugLevel) -> None: ... +def set_debug_level_from_env() -> None: ... + +class ReduceOp: + # pyrefly: ignore # unknown-name + def __init__(self, op: RedOpType) -> None: ... + @property + def factor(self) -> float | Tensor: ... + + # pyrefly: ignore # unknown-name + SUM: RedOpType = ... + # pyrefly: ignore # unknown-name + AVG: RedOpType = ... + # pyrefly: ignore # unknown-name + PRODUCT: RedOpType = ... + # pyrefly: ignore # unknown-name + MIN: RedOpType = ... + # pyrefly: ignore # unknown-name + MAX: RedOpType = ... + # pyrefly: ignore # unknown-name + BAND: RedOpType = ... + # pyrefly: ignore # unknown-name + BOR: RedOpType = ... + # pyrefly: ignore # unknown-name + BXOR: RedOpType = ... + # pyrefly: ignore # unknown-name + PREMUL_SUM: RedOpType = ... + # pyrefly: ignore # unknown-name + UNUSED: RedOpType = ... + + # mypy error being ignored: + # Detected enum "torch._C._distributed_c10d.ReduceOp.RedOpType" in a type + # stub with zero members. There is a chance this is due to a recent change + # in the semantics of enum membership. If so, use `member = value` to mark + # an enum member, instead of `member: type` + class RedOpType(Enum): + def __call__(self, factor: float | int | Tensor) -> ReduceOp: + """Create a PREMUL_SUM ReduceOp with the given factor. Only PREMUL_SUM supports this.""" + +class BroadcastOptions: + rootRank: int + rootTensor: int + timeout: timedelta + asyncOp: bool + +class AllreduceOptions: + reduceOp: ReduceOp | ReduceOp.RedOpType + timeout: timedelta + asyncOp: bool + sparseIndices: Tensor | None + +class AllreduceCoalescedOptions(AllreduceOptions): ... + +class ReduceOptions: + reduceOp: ReduceOp | ReduceOp.RedOpType + rootRank: int + rootTensor: int + timeout: timedelta + asyncOp: bool + +class AllgatherOptions: + timeout: timedelta + asyncOp: bool + +class GatherOptions: + rootRank: int + timeout: timedelta + asyncOp: bool + +class ScatterOptions: + rootRank: int + timeout: timedelta + asyncOp: bool + +class ReduceScatterOptions: + reduceOp: ReduceOp | ReduceOp.RedOpType + timeout: timedelta + asyncOp: bool + +class BarrierOptions: + device_ids: list[int] + device: torch.device + timeout: timedelta + asyncOp: bool + +class AllToAllOptions: + timeout: timedelta + asyncOp: bool + +class ReconfigureOptions: + uuid: int + handles: set[str] | list[str] + timeout: timedelta | None + hints: dict[str, str] + +class PutOptions: + timeout: timedelta + hints: dict[str, str] + +class SignalOptions: + timeout: timedelta + hints: dict[str, str] + +class WaitSignalOptions: + timeout: timedelta + hints: dict[str, str] + +class WindowAccessType(Enum): + UNIFIED = ... + SEPARATE = ... + +class WindowAttr: + access_type: WindowAccessType + +class Window: + def tensor_register(self, tensor: Tensor, owning: bool = ...) -> None: ... + def tensor_deregister(self) -> None: ... + def put( + self, + tensor: Tensor, + dst_rank: int, + target_offset_nelems: int, + async_op: bool, + opts: PutOptions = ..., + ) -> Work: ... + def map_remote_tensor(self, rank: int) -> Tensor: ... + def signal( + self, + peer_rank: int, + async_op: bool, + opts: SignalOptions = ..., + ) -> Work: ... + def wait_signal( + self, + peer_rank: int, + async_op: bool, + opts: WaitSignalOptions = ..., + ) -> Work: ... + def get_attr(self, peer_rank: int) -> WindowAttr: ... + +class HookOpName(Enum): + SEND = ... + RECV = ... + BROADCAST = ... + ALLREDUCE = ... + REDUCE = ... + ALLGATHER = ... + REDUCE_SCATTER = ... + ALLTOALL = ... + BARRIER = ... + SCATTER = ... + GATHER = ... + SPLIT = ... + NEW_WINDOW = ... + UNKNOWN = ... + +class PreHookArgs: + name: HookOpName + async_op: bool + input_tensors: list[Tensor] + output_tensors: list[Tensor] + root: int + op_id: int + +class PostHookArgs: + name: HookOpName + async_op: bool + work: Work | None + op_id: int + +class Store: + def set(self, key: str, value: str) -> None: ... + def get(self, key: str) -> bytes: ... + def add(self, key: str, value: int) -> int: ... + def check(self, keys: list[str]) -> bool: ... + def compare_set( + self, + key: str, + expected_value: str, + desired_value: str, + ) -> bytes: ... + def delete_key(self, key: str) -> bool: ... + def multi_get(self, keys: list[str]) -> list[bytes]: ... + def num_keys(self) -> int: ... + def set_timeout(self, timeout: timedelta) -> None: ... + @overload + def wait(self, keys: list[str]) -> None: ... + @overload + def wait(self, keys: list[str], timeout: timedelta) -> None: ... + def queue_pop(self, key: str, block: bool = True) -> bytes: ... + def queue_push(self, key: str, value: bytes | str) -> None: ... + def queue_len(self, key: str) -> int: ... + def list_keys(self) -> list[str]: ... + def clone(self) -> Store: ... + +class FileStore(Store): + def __init__(self, path: str, numWorkers: int = ...) -> None: ... + +class HashStore(Store): + def __init__(self) -> None: ... + +class FakeStore(Store): + def __init__(self) -> None: ... + +class TCPStore(Store): + def __init__( + self, + host_name: str, + port: int, + world_size: int | None = ..., + is_master: bool = ..., + timeout: timedelta = ..., + wait_for_workers: bool = ..., + multi_tenant: bool = ..., + master_listen_fd: int | None = ..., + use_libuv: bool | None = ..., + ) -> None: ... + @property + def host(self) -> str: ... + @property + def port(self) -> int: ... + +class PrefixStore(Store): + def __init__(self, prefix: str, store: Store) -> None: ... + @property + def underlying_store(self) -> Store: ... + +class _DistributedBackendOptions: + def __init__(self) -> None: ... + @property + def store(self) -> Store: ... + @store.setter + def store(self, store: Store) -> None: ... + @property + def group_rank(self) -> int: ... + @group_rank.setter + def group_rank(self, rank: int) -> None: ... + @property + def group_size(self) -> int: ... + @group_size.setter + def group_size(self, size: int) -> None: ... + @property + def timeout(self) -> timedelta: ... + @timeout.setter + def timeout(self, timeout: timedelta) -> None: ... + @property + def group_id(self) -> GroupName: ... + @group_id.setter + def group_id(self, group_id: GroupName) -> None: ... + @property + def global_ranks_in_group(self) -> list[int]: ... + @global_ranks_in_group.setter + def global_ranks_in_group(self, ranks: list[int]) -> None: ... + process_group: ProcessGroup | None + split_from: Backend | None + enable_reconfigure: bool + +class Work: + def is_completed(self) -> bool: ... + def is_success(self) -> bool: ... + def exception(self) -> Any: ... + def wait(self, timeout: timedelta = ...) -> bool: ... + def block_current_stream(self) -> None: ... + def get_future(self) -> Future: ... + def source_rank(self) -> int: ... + def _source_rank(self) -> int: ... + def result(self) -> list[Tensor]: ... + def synchronize(self) -> None: ... + def _get_duration(self) -> float: ... + def _get_sequence_number(self) -> int: ... + @property + def timeout(self) -> timedelta: ... + def boxed(self) -> ScriptObject: ... + @staticmethod + def unbox(obj: ScriptObject) -> Work: ... + +class Backend: + class Options: + def __init__(self, backend: str, timeout: timedelta = ...) -> None: ... + @property + def backend(self) -> str: ... + @property + def _timeout(self) -> timedelta: ... + @_timeout.setter + def _timeout(self, val: timedelta) -> None: ... + global_ranks_in_group: list[int] + group_name: GroupName + use_pg_for_symm_mem_rendezvous: bool + enable_reconfigure: bool + + def __init__( + self, + rank: int, + size: int, + ) -> None: ... + @property + def supports_splitting(self) -> bool: ... + @property + def supports_coalescing(self) -> bool: ... + @property + def supports_time_estimate(self) -> bool: ... + @property + def supports_shrinking(self) -> bool: ... + def shrink( + self, + ranks_to_exclude: list[int], + shrink_flags: int = ..., + opts_override: Backend.Options | None = None, + ) -> Backend: ... + @property + def supports_reconfigure(self) -> bool: ... + def get_reconfigure_handle(self) -> str: ... + def reconfigure(self, opts: ReconfigureOptions) -> Work: ... + @property + def supports_window(self) -> bool: ... + def new_window(self, tensor: Tensor | None = None) -> Window: ... + def register_abort_hook(self, hook_id: int, hook: Callable[[], None]) -> None: ... + def unregister_abort_hook(self, hook_id: int) -> None: ... + def set_timeout(self, timeout: timedelta) -> None: ... + def _add_ephemeral_timeout(self, timeout: timedelta) -> None: ... + @property + def options(self) -> Options: ... + def rank(self) -> int: ... + def size(self) -> int: ... + def name(self) -> str: ... + def abort(self) -> None: ... + def shutdown(self) -> None: ... + def eager_connect_single_device(self, device: torch.device | None) -> None: ... + def _set_sequence_number_for_group(self) -> None: ... + def _set_default_timeout(self, timeout: timedelta) -> None: ... + def get_error(self) -> ErrorType: ... + def supports_tensor_alloc(self, device: torch.device) -> bool: ... + def allocate_tensor( + self, + size: int, + *, + dtype: torch.dtype, + device: torch.device, + ) -> Tensor: ... + @property + def mem_allocator(self) -> Any: ... + +class ProcessGroup: + class BackendType(Enum): + UNDEFINED = ... + GLOO = ... + NCCL = ... + UCC = ... + MPI = ... + XCCL = ... + CUSTOM = ... + + def __init__( + self, + store: Store, + rank: int, + size: int, + ) -> None: ... + def rank(self) -> int: ... + def size(self) -> int: ... + def get_group_store(self) -> Store: ... + def split_group( + self, + new_ranks: list[int], + timeout: timedelta | None = None, + opts: Backend.Options | None = None, + group_name: GroupName | None = None, + group_desc: str | None = None, + device_types: list[torch.device] | None = None, + ) -> ProcessGroup | None: ... + def merge_remote_group( + self, + store: Store, + size: int, + timeout: timedelta, + group_name: GroupName | None = None, + group_desc: str | None = None, + ) -> ProcessGroup: ... + def abort(self) -> None: ... + def set_timeout(self, timeout: timedelta) -> None: ... + def _add_ephemeral_timeout(self, timeout: timedelta) -> None: ... + def shutdown(self) -> None: ... + @property + def supports_reconfigure(self) -> bool: ... + def get_reconfigure_handle(self) -> str: ... + def reconfigure(self, opts: ReconfigureOptions) -> Work: ... + @property + def supports_window(self) -> bool: ... + def new_window(self, tensor: Tensor | None = None) -> Window: ... + def register_abort_hook(self, hook_id: int, hook: Callable[[], None]) -> None: ... + def unregister_abort_hook(self, hook_id: int) -> None: ... + def register_pre_hook( + self, hook_id: int, hook: Callable[[PreHookArgs], None] + ) -> None: ... + def unregister_pre_hook(self, hook_id: int) -> None: ... + def register_post_hook( + self, hook_id: int, hook: Callable[[PostHookArgs], None] + ) -> None: ... + def unregister_post_hook(self, hook_id: int) -> None: ... + @overload + def broadcast( + self, + tensors: list[Tensor], + opts=..., + ) -> Work: ... + @overload + def broadcast( + self, + tensor: Tensor, + root: int, + timeout: timedelta | None = None, + ) -> Work: ... + @overload + def allreduce( + self, + tensors: list[Tensor], + opts: AllreduceOptions = ..., + ) -> Work: ... + @overload + def allreduce( + self, + tensors: list[Tensor], + op=..., + timeout: timedelta | None = None, + ) -> Work: ... + @overload + def allreduce( + self, + tensor: Tensor, + op=..., + timeout: timedelta | None = None, + ) -> Work: ... + def allreduce_coalesced( + self, + tensors: list[Tensor], + opts=..., + ) -> Work: ... + def reduce_scatter_single_coalesced( + self, + outputTensors: list[Tensor], + inputTensors: list[Tensor], + opts: ReduceScatterOptions | None = None, + ) -> Work: ... + def reduce_scatter_tensor_coalesced( + self, + outputTensors: list[Tensor], + inputTensors: list[Tensor], + opts: ReduceScatterOptions | None = None, + ) -> Work: ... + @overload + def reduce( + self, + tensors: list[Tensor], + opts=..., + ) -> Work: ... + @overload + def reduce( + self, + tensor: Tensor, + root: int, + op=..., + timeout: timedelta | None = None, + ) -> Work: ... + @overload + def allgather( + self, + output_tensors: list[list[Tensor]], + input_tensors: list[Tensor], + opts=..., + ) -> Work: ... + @overload + def allgather( + self, + output_tensors: list[Tensor], + input_tensor: Tensor, + timeout: timedelta | None = None, + ) -> Work: ... + def all_gather_single( + self, + output: Tensor, + input: Tensor, + opts=..., + ) -> Work: ... + def _allgather_base( + self, + output: Tensor, + input: Tensor, + opts=..., + ) -> Work: ... + def allgather_coalesced( + self, + output_lists: list[list[Tensor]], + input_list: list[Tensor], + opts=..., + ) -> Work: ... + def all_gather_single_coalesced( + self, + output_lists: list[Tensor], + input_list: list[Tensor], + opts=..., + ) -> Work: ... + def allgather_into_tensor_coalesced( + self, + output_lists: list[Tensor], + input_list: list[Tensor], + opts=..., + ) -> Work: ... + @overload + def gather( + self, + output_tensors: list[list[Tensor]], + input_tensors: list[Tensor], + opts=..., + ) -> Work: ... + @overload + def gather( + self, + output_tensors: list[Tensor], + input_tensor: Tensor, + root: int, + timeout: timedelta | None = None, + ) -> Work: ... + def gather_single( + self, + output: Tensor, + input: Tensor, + opts=..., + ) -> Work: ... + def gather_into_tensor( + self, + output: Tensor, + input: Tensor, + opts=..., + ) -> Work: ... + @overload + def scatter( + self, + output_tensors: list[Tensor], + input_tensors: list[list[Tensor]], + opts=..., + ) -> Work: ... + @overload + def scatter( + self, + output_tensor: Tensor, + input_tensors: list[Tensor], + root: int, + timeout: timedelta | None = None, + ) -> Work: ... + @overload + def reduce_scatter( + self, + output_tensors: list[Tensor], + input_tensors: list[list[Tensor]], + opts=..., + ) -> Work: ... + @overload + def reduce_scatter( + self, + output_tensors: Tensor, + input_tensor: list[Tensor], + op=..., + timeout: timedelta | None = None, + ) -> Work: ... + def reduce_scatter_single( + self, + outputTensor: Tensor, + inputTensor: Tensor, + opts: ReduceScatterOptions | None, + ) -> Work: ... + def _reduce_scatter_base( + self, + outputTensor: Tensor, + inputTensor: Tensor, + opts: ReduceScatterOptions | None, + ) -> Work: ... + @overload + def all_to_all_single( + self, + output_tensor: Tensor, + input_tensor: Tensor, + output_split_sizes: list[int], + input_split_sizes: list[int], + opts=..., + ) -> Work: ... + @overload + def all_to_all_single( + self, + output: Tensor, + input: Tensor, + output_split_sizes: list[int], + input_split_sizes: list[int], + timeout: timedelta | None = None, + ) -> Work: ... + @overload + def alltoall_base( + self, + output_tensor: Tensor, + input_tensor: Tensor, + output_split_sizes: list[int], + input_split_sizes: list[int], + opts=..., + ) -> Work: ... + @overload + def alltoall_base( + self, + output: Tensor, + input: Tensor, + output_split_sizes: list[int], + input_split_sizes: list[int], + timeout: timedelta | None = None, + ) -> Work: ... + @overload + def alltoall( + self, + output_tensor: list[Tensor], + input_tensor: list[Tensor], + opts=..., + ) -> Work: ... + @overload + def alltoall( + self, + output: list[Tensor], + input: list[Tensor], + timeout: timedelta | None = None, + ) -> Work: ... + def send( + self, + tensors: list[Tensor], + dstRank: int, + tag: int, + ) -> Work: ... + def recv( + self, + tensors: list[Tensor], + srcRank: int, + tag: int, + ) -> Work: ... + def recv_anysource(self, tensors: list[Tensor], tag: int) -> Work: ... + @overload + def barrier(self, opts=...) -> Work: ... + @overload + def barrier(self, timeout: timedelta | None = None) -> Work: ... + def boxed(self) -> ScriptObject: ... + @staticmethod + def unbox(obj: ScriptObject) -> ProcessGroup: ... + def _start_coalescing(self, device: torch.device) -> None: ... + def _end_coalescing(self, device: torch.device) -> Work: ... + def _get_backend_name(self) -> str: ... + def _backend_id(self, backend_type: BackendType) -> int: ... + @property + def _device_types(self) -> list[torch.device]: ... + def get_backend(self, device: torch.device) -> Backend: ... + def _get_backend(self, device: torch.device) -> Backend: ... + def _set_default_backend(self, backend_type: BackendType) -> None: ... + def _register_backend( + self, + device: torch.device, + backend_type: BackendType, + backend: Backend | None, + ) -> None: ... + def _set_group_name(self, name: GroupName) -> None: ... + def _set_group_desc(self, desc: str) -> None: ... + def name(self) -> str: ... + def _has_hooks(self) -> bool: ... + def _wait_for_pending_works(self) -> None: ... + @property + def bound_device_id(self) -> torch.device | None: ... + @bound_device_id.setter + def bound_device_id(self, device: torch.device | None) -> None: ... + @property + def use_pg_for_symm_mem_rendezvous(self) -> bool: + """When True, symmetric memory rendezvous exchanges metadata via this + PG's NCCL allgather instead of TCPStore, which gets overloaded at large + rank counts. This will lazily create the NCCL communicator if it doesn't + already exist. If this PG is only used for symmetric memory (no regular + collectives), consider calling ``abort()`` after rendezvous to release + the communicator.""" + @use_pg_for_symm_mem_rendezvous.setter + def use_pg_for_symm_mem_rendezvous(self, value: bool) -> None: ... + @property + def group_name(self) -> GroupName: ... + @property + def group_desc(self) -> str: ... + +class FakeProcessGroup(Backend): + @staticmethod + def _create_internal(rank: int, world_size: int) -> FakeProcessGroup: ... + +class FakeWork(Work): + seq_id: int + def __init__(self) -> None: ... + def wait(self, timeout: timedelta = ...) -> bool: ... + def getFuture(self) -> Future: ... + +class NCCLXStub(Backend): + def __init__( + self, + store: Store, + rank: int, + size: int, + options: ProcessGroupNCCL.Options = ..., + ) -> None: ... + +class PythonCallbackWork(Work): + def __init__(self, callback: Callable[[timedelta], bool]) -> None: ... + def wait(self, timeout: timedelta = ...) -> bool: ... + def get_future(self) -> Future: ... + +class ProcessGroupGloo(Backend): + class Device: ... + + class Options(Backend.Options): + devices: list[ProcessGroupGloo.Device] + threads: int + + def __init__(self): ... + + def __init__( + self, + store: Store, + rank: int, + size: int, + timeout: timedelta = ..., + enable_reconfigure: bool = ..., + ) -> None: ... + @staticmethod + def create_device(hostname="", interface="", lazy_init=None) -> Device: ... + @staticmethod + def create_default_device(lazy_init=None) -> Device: ... + def _set_default_timeout(self, timeout) -> None: ... + @property + def options(self) -> Options: ... # type: ignore[override] + +class _ProcessGroupWrapper(Backend): + def __init__(self, pg: Backend, gloo_pg: ProcessGroupGloo) -> None: ... + wrapped_pg: Backend + @property + def options(self) -> Backend.Options: ... + def get_error(self) -> ErrorType: ... + +class ErrorType(Enum): + SUCCESS = ... + TIMEOUT = ... + COMM_ERROR = ... + REMOTE_ERROR = ... + +class ProcessGroupNCCL(Backend): + class NCCLConfig: + blocking: int + cga_cluster_size: int + min_ctas: int + max_ctas: int + def unsafe_get_ptr(self) -> int: ... + + class Options(Backend.Options): + config: ProcessGroupNCCL.NCCLConfig + is_high_priority_stream: bool + split_from: ProcessGroupNCCL + split_color: int + + def __init__(self, is_high_priority_stream: bool = False): ... + + def __init__( + self, + store: Store, + rank: int, + size: int, + options: Options, + ) -> None: ... + def _group_start(self) -> None: ... + def _group_end(self) -> None: ... + def _start_time_estimate(self) -> None: ... + def _end_time_estimate(self) -> float: ... + def _set_default_timeout(self, timeout) -> None: ... + def perform_nocolor_split(self, device: torch.device) -> None: ... + def register_mem_pool( + self, pool: torch.cuda.MemPool, symm: bool = False + ) -> None: ... + def deregister_mem_pool(self, pool: torch.cuda.MemPool) -> None: ... + def comm_split_count(self) -> int: ... + def abort(self) -> None: ... + def _is_initialized(self) -> bool: ... + @property + def uid(self) -> int: ... + @property + def options(self) -> Options: ... # type: ignore[override] + @staticmethod + def get_build_nccl_version(self) -> tuple[int, int, int]: ... + @staticmethod + def get_runtime_nccl_version(self) -> tuple[int, int, int]: ... + +class ProcessGroupUCC(Backend): + def __init__( + self, + store: Store, + rank: int, + size: int, + timeout: timedelta, + ) -> None: ... + +class ProcessGroupMPI(Backend): + def __init__( + self, + rank: int, + size: int, + pgComm: int, + ) -> None: ... + @staticmethod + def create(ranks: list[int]) -> ProcessGroupMPI: ... + +def _compute_bucket_assignment_by_size( + tensors: list[Tensor], + bucket_size_limits: list[int], + expect_sparse_gradient: list[bool] = ..., + tensor_indices: list[int] = ..., +) -> tuple[list[list[int]], list[int]]: ... +def _broadcast_coalesced( + process_group: ProcessGroup, + tensors: list[Tensor], + buffer_size: int, + src: int, +): ... +def _test_python_store(store: Store): ... +def _verify_params_across_processes( + process_group: ProcessGroup, + params: list[Tensor], + logger: Logger | None, +): ... +def _make_nccl_premul_sum(factor: float | Tensor) -> ReduceOp: ... +def _register_process_group( + group_name: GroupName, + process_group: ProcessGroup, +) -> None: ... +def _resolve_process_group(group_name: GroupName) -> ProcessGroup: ... +def _create_work_from_future(future: Future) -> Work: ... +def _register_work(tensor: torch.Tensor, work: Work) -> ProcessGroup: ... +def _get_work_registry_size() -> int: ... +def _set_allow_inflight_collective_as_graph_input( + value: bool, +) -> None: ... +def _allow_inflight_collective_as_graph_input() -> bool: ... +def _unregister_all_process_groups() -> None: ... +def _unregister_process_group(group_name: GroupName) -> None: ... + +# Initializes the device state in CUmodule so that it's able to perform NVSHMEM +# operations. CUmodule is a pointer to a CUDA module, carried by a int64 in +# Python. At C++ interface, it is converted to a uintptr_t. +def _nvshmemx_cumodule_init(module: int) -> None: ... + +# Check if NVSHMEM is available on current system. +def _is_nvshmem_available() -> bool: ... +def _register_external_nccl_comm( + group_name: str, comm_ptr: int, device: torch.device +) -> None: ... +def _unregister_external_nccl_comm(group_name: str, device: torch.device) -> None: ... + +# NCCL EP (contrib/nccl_ep) bindings; only registered in USE_C10D_NCCL builds. +class _NcclEpGroup: + @staticmethod + def create( + pg: ProcessGroup, + num_experts: int, + max_dispatch_tokens_per_rank: int, + max_recv_tokens_per_rank: int, + max_token_bytes: int, + ) -> _NcclEpGroup: ... + +class _NcclEpHandle: + @staticmethod + def create( + group: _NcclEpGroup, + topk_idx: Tensor, + recv_expert_counter: Tensor | None = None, + ) -> _NcclEpHandle: ... + def get_num_recv_tokens(self) -> int: ... + +# handle is Any: the Python layer (torch.distributed._token_switch.Routing) +# holds it opaquely as `object`, so callers don't carry the concrete type. +def _nccl_ep_dispatch( + handle: Any, + tokens: Tensor, + topk_weights: Tensor, + out_tokens: Tensor, + out_topk_weights: Tensor, + out_topk_idx: Tensor, +) -> None: ... +def _nccl_ep_combine( + handle: Any, + expert_tokens: Tensor, + out_tokens: Tensor, +) -> None: ... + +class _SymmetricMemory: + @staticmethod + def set_group_info( + group_name: str, + rank: int, + world_size: int, + store: Store, + ) -> None: ... + @staticmethod + def empty_strided_p2p( + size: torch.types._size, + stride: torch.types._size, + dtype: torch.dtype, + device: torch.device, + group_name: str | None = None, + alloc_id: int | None = None, + ) -> torch.Tensor: ... + @staticmethod + def has_multicast_support( + device_type: DeviceType, + device_idx: int, + ) -> bool: ... + # Set Symmetric Memory allocation backend. + @staticmethod + def set_backend(name: str) -> None: ... + @staticmethod + def get_backend(device: torch.device) -> str | None: ... + @staticmethod + def is_symm_mem_tensor(tensor: torch.Tensor) -> bool: ... + @staticmethod + def get_mempool_allocator(device: torch.device) -> Any: ... + signal_pad_size: int + @property + def rank(self) -> int: ... + @property + def world_size(self) -> int: ... + @staticmethod + def rendezvous( + tensor: torch.Tensor, group_name: str | None = None + ) -> _SymmetricMemory: ... + def boxed(self) -> ScriptObject: ... + def get_buffer( + self, + rank: int, + sizes: torch.types._size, + dtype: torch.dtype, + storage_offset: int | None = 0, + ) -> torch.Tensor: ... + def get_signal_pad( + self, + rank: int, + sizes: torch.types._size = [], + dtype: torch.dtype | None = None, + storage_offset: int | None = 0, + ) -> torch.Tensor: ... + def barrier(self, channel: int = 0, timeout_ms: int = 0) -> None: ... + def put_signal( + self, + dst_rank: int, + channel: int = 0, + timeout_ms: int = 0, + ) -> None: ... + def wait_signal( + self, + src_rank: int, + channel: int = 0, + timeout_ms: int = 0, + ) -> None: ... + def get_remote_tensor( + self, + peer: int, + sizes: torch.types._size, + dtype: torch.dtype, + ) -> torch.Tensor: ... + @staticmethod + def memset32( + tensor: torch.Tensor, offset: int, val: int, count: int = 1 + ) -> torch.Tensor: ... + @staticmethod + def stream_write_value32( + tensor: torch.Tensor, offset: int, val: int + ) -> torch.Tensor: ... + @property + def buffer_ptrs(self) -> list[int]: ... + @property + def buffer_ptrs_dev(self) -> int: ... + @property + def signal_pad_ptrs(self) -> list[int]: ... + @property + def signal_pad_ptrs_dev(self) -> int: ... + @property + def multicast_ptr(self) -> int: ... + @property + def buffer_size(self) -> int: ... + @property + def offset(self) -> int: ... + @property + def device(self) -> torch.device: ... + +class ProcessGroupXCCL(Backend): + class Options(Backend.Options): + is_high_priority_stream: bool + + def __init__(self, is_high_priority_stream: bool = False): ... + + def __init__( + self, + store: Store, + rank: int, + size: int, + options: Options, + ) -> None: ... + @property + def options(self) -> Options: ... # type: ignore[override] + @property + def uid(self) -> int: ... + def _is_initialized(self) -> bool: ... + def _set_enable_nan_check(self, enable_nan_check: bool) -> None: ... + def _set_default_timeout(self, timeout) -> None: ... + def _dump_xccl_trace_json( + self, includeCollectives: bool = False, onlyActive: bool = False + ) -> str: ... + def _reset_fr_recording_xccl(self) -> None: ... + +class ProcessGroupNCCL2(Backend): + Options = ProcessGroupNCCL.Options + + def __init__( + self, + store: Store, + rank: int, + size: int, + options: ProcessGroupNCCL.Options, + ) -> None: ... + def get_error(self) -> ErrorType: ... + @property + def options(self) -> ProcessGroupNCCL.Options: ... + +class ProcessGroupNCCLLazy(Backend): + def __init__( + self, + store: Store, + rank: int, + size: int, + options: ProcessGroupNCCL.Options, + ) -> None: ... + def get_error(self) -> ErrorType: ... + def _num_active_channels(self) -> int: ... + +class FlightRecorderHook: + @staticmethod + def attach(pg: ProcessGroup) -> FlightRecorderHook: ... + def remove(self) -> None: ... + +class NanCheckHook: + @staticmethod + def attach(pg: ProcessGroup) -> NanCheckHook: ... + def remove(self) -> None: ... + +def _set_process_group(pg: ProcessGroup) -> None: ... +def _current_process_group() -> ProcessGroup: ... + +class _Request: + def body(self) -> bytes: ... + def get_param(self, str) -> str: ... + +class _Response: + def set_content(self, content: str | bytes, content_type: str) -> None: ... + def set_status(self, status: int) -> None: ... + +def _register_handler( + name: str, handler: Callable[[_Request, _Response], None] +) -> None: ... +def _set_comm_profiling_name(name: str) -> None: ... +def _get_comm_profiling_name() -> str: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_distributed_rpc.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_distributed_rpc.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ff0e5b8379a20da0e7760a042fa0df333b6572ca --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_distributed_rpc.pyi @@ -0,0 +1,188 @@ +# mypy: allow-untyped-defs +# mypy: disable-error-code="type-arg" +from datetime import timedelta +from typing import Any, Generic, overload, TypeVar + +import torch +from torch._C import Future +from torch._C._autograd import ProfilerEvent +from torch._C._distributed_c10d import Store +from torch._C._profiler import ProfilerConfig + +# This module is defined in torch/csrc/distributed/rpc/init.cpp + +_DEFAULT_INIT_METHOD: str +_DEFAULT_NUM_WORKER_THREADS: int +_UNSET_RPC_TIMEOUT: float +_DEFAULT_RPC_TIMEOUT_SEC: float + +_T = TypeVar("_T") + +class RpcBackendOptions: + rpc_timeout: float + init_method: str + def __init__( + self, + rpc_timeout: float = ..., + init_method: str = ..., + ) -> None: ... + +class WorkerInfo: + def __init__(self, name: str, worker_id: int) -> None: ... + @property + def name(self) -> str: ... + @property + def id(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + +class RpcAgent: + def join(self, shutdown: bool = False, timeout: float = 0): ... + def sync(self): ... + def shutdown(self): ... + @overload + def get_worker_info(self) -> WorkerInfo: ... + @overload + def get_worker_info(self, workerName: str) -> WorkerInfo: ... + def get_worker_infos(self) -> list[WorkerInfo]: ... + def _get_device_map(self, dst: WorkerInfo) -> dict[torch.device, torch.device]: ... + def get_debug_info(self) -> dict[str, str]: ... + def get_metrics(self) -> dict[str, str]: ... + +class PyRRef(Generic[_T]): + def __init__(self, value: _T, type_hint: Any = None) -> None: ... + def is_owner(self) -> bool: ... + def confirmed_by_owner(self) -> bool: ... + def owner(self) -> WorkerInfo: ... + def owner_name(self) -> str: ... + def to_here(self, timeout: float = ...) -> _T: ... + def local_value(self) -> Any: ... + def rpc_sync(self, timeout: float = ...) -> Any: ... + def rpc_async(self, timeout: float = ...) -> Any: ... + def remote(self, timeout: float = ...) -> Any: ... + def _serialize(self) -> tuple: ... + @staticmethod + def _deserialize(tp: tuple) -> PyRRef: ... + def _get_type(self) -> type[_T]: ... + def _get_future(self) -> Future[_T]: ... + def _get_profiling_future(self) -> Future[_T]: ... + def _set_profiling_future(self, profilingFuture: Future[_T]): ... + +class _TensorPipeRpcBackendOptionsBase(RpcBackendOptions): + num_worker_threads: int + device_maps: dict[str, dict[torch.device, torch.device]] + devices: list[torch.device] + def __init__( + self, + num_worker_threads: int, + _transports: list | None, + _channels: list | None, + rpc_timeout: float = ..., + init_method: str = ..., + device_maps: dict[str, dict[torch.device, torch.device]] = {}, + devices: list[torch.device] = [], + ) -> None: ... + def _set_device_map( + self, + to: str, + device_map: dict[torch.device, torch.device], + ): ... + +class TensorPipeAgent(RpcAgent): + def __init__( + self, + store: Store, + name: str, + worker_id: int, + world_size: int | None, + opts: _TensorPipeRpcBackendOptionsBase, + reverse_device_maps: dict[str, dict[torch.device, torch.device]], + devices: list[torch.device], + ) -> None: ... + def join(self, shutdown: bool = False, timeout: float = 0): ... + def shutdown(self): ... + @overload + def get_worker_info(self) -> WorkerInfo: ... + @overload + def get_worker_info(self, workerName: str) -> WorkerInfo: ... + @overload + def get_worker_info(self, id: int) -> WorkerInfo: ... + def get_worker_infos(self) -> list[WorkerInfo]: ... + def _get_device_map(self, dst: WorkerInfo) -> dict[torch.device, torch.device]: ... + def _update_group_membership( + self, + worker_info: WorkerInfo, + my_devices: list[torch.device], + reverse_device_map: dict[str, dict[torch.device, torch.device]], + is_join: bool, + ): ... + def _get_backend_options(self) -> _TensorPipeRpcBackendOptionsBase: ... + @property + def is_static_group(self) -> bool: ... + @property + def store(self) -> Store: ... + +def _is_current_rpc_agent_set() -> bool: ... +def _get_current_rpc_agent() -> RpcAgent: ... +def _set_and_start_rpc_agent(agent: RpcAgent): ... +def _reset_current_rpc_agent(): ... +def _delete_all_user_and_unforked_owner_rrefs(timeout: timedelta = ...): ... +def _destroy_rref_context(ignoreRRefLeak: bool): ... +def _rref_context_get_debug_info() -> dict[str, str]: ... +def _cleanup_python_rpc_handler(): ... +def _invoke_rpc_builtin( + dst: WorkerInfo, + opName: str, + rpcTimeoutSeconds: float, + *args: Any, + **kwargs: Any, +): ... +def _invoke_rpc_python_udf( + dst: WorkerInfo, + pickledPythonUDF: str, + tensors: list[torch.Tensor], + rpcTimeoutSeconds: float, + isAsyncExecution: bool, +): ... +def _invoke_rpc_torchscript( + dstWorkerName: str, + qualifiedNameStr: str, + argsTuple: tuple, + kwargsDict: dict, + rpcTimeoutSeconds: float, + isAsyncExecution: bool, +): ... +def _invoke_remote_builtin( + dst: WorkerInfo, + opName: str, + rpcTimeoutSeconds: float, + *args: Any, + **kwargs: Any, +): ... +def _invoke_remote_python_udf( + dst: WorkerInfo, + pickledPythonUDF: str, + tensors: list[torch.Tensor], + rpcTimeoutSeconds: float, + isAsyncExecution: bool, +): ... +def _invoke_remote_torchscript( + dstWorkerName: WorkerInfo, + qualifiedNameStr: str, + rpcTimeoutSeconds: float, + isAsyncExecution: bool, + *args: Any, + **kwargs: Any, +): ... +def get_rpc_timeout() -> float: ... +def enable_gil_profiling(flag: bool): ... +def _set_rpc_timeout(rpcTimeoutSeconds: float): ... + +class RemoteProfilerManager: + @staticmethod + def set_current_profiling_key(key: str): ... + +def _enable_server_process_global_profiler(new_config: ProfilerConfig): ... +def _disable_server_process_global_profiler() -> list[list[list[ProfilerEvent]]]: ... +def _set_profiler_node_id(default_node_id: int): ... +def _enable_jit_rref_pickle(): ... +def _disable_jit_rref_pickle(): ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_distributed_rpc_testing.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_distributed_rpc_testing.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9313281027dbd89ae65ebe65c95a1d0c38593b80 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_distributed_rpc_testing.pyi @@ -0,0 +1,32 @@ +import torch +from torch._C._distributed_c10d import Store +from torch._C._distributed_rpc import _TensorPipeRpcBackendOptionsBase, TensorPipeAgent + +# This module is defined in torch/csrc/distributed/rpc/testing/init.cpp + +class FaultyTensorPipeRpcBackendOptions(_TensorPipeRpcBackendOptionsBase): + def __init__( + self, + num_worker_threads: int, + rpc_timeout: float, + init_method: str, + messages_to_fail: list[str], + messages_to_delay: dict[str, float], + num_fail_sends: int, + ) -> None: ... + num_send_recv_threads: int + messages_to_fail: list[str] + messages_to_delay: dict[str, float] + num_fail_sends: int + +class FaultyTensorPipeAgent(TensorPipeAgent): + def __init__( + self, + store: Store, + name: str, + rank: int, + world_size: int, + options: FaultyTensorPipeRpcBackendOptions, + reverse_device_maps: dict[str, dict[torch.device, torch.device]], + devices: list[torch.device], + ) -> None: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/__init__.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..06107eca199d7cc902b86d56a4e331e404c46d82 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/__init__.pyi @@ -0,0 +1,72 @@ +from . import compiled_autograd, eval_frame, guards # noqa: F401 + +def strip_function_call(name: str) -> str: ... +def is_valid_var_name(name: str) -> bool | int: ... +def get_type_slots(obj: type | object) -> tuple[int, int, int, int]: ... +def has_slot(slots: int, slot_bit: int) -> bool: ... + +class PySequenceSlots: + SQ_LENGTH: int + SQ_CONCAT: int + SQ_REPEAT: int + SQ_ITEM: int + SQ_CONTAINS: int + SQ_ASS_ITEM: int + SQ_INPLACE_CONCAT: int + SQ_INPLACE_REPEAT: int + +class PyMappingSlots: + MP_LENGTH: int + MP_SUBSCRIPT: int + MP_ASS_SUBSCRIPT: int + +class PyNumberSlots: + NB_ADD: int + NB_SUBTRACT: int + NB_MULTIPLY: int + NB_REMAINDER: int + NB_POWER: int + NB_NEGATIVE: int + NB_POSITIVE: int + NB_ABSOLUTE: int + NB_BOOL: int + NB_INVERT: int + NB_LSHIFT: int + NB_RSHIFT: int + NB_AND: int + NB_XOR: int + NB_OR: int + NB_INT: int + NB_FLOAT: int + NB_INPLACE_ADD: int + NB_INPLACE_SUBTRACT: int + NB_INPLACE_MULTIPLY: int + NB_INPLACE_REMAINDER: int + NB_INPLACE_POWER: int + NB_INPLACE_LSHIFT: int + NB_INPLACE_RSHIFT: int + NB_INPLACE_AND: int + NB_INPLACE_XOR: int + NB_INPLACE_OR: int + NB_FLOOR_DIVIDE: int + NB_TRUE_DIVIDE: int + NB_INPLACE_FLOOR_DIVIDE: int + NB_INPLACE_TRUE_DIVIDE: int + NB_INDEX: int + NB_MATRIX_MULTIPLY: int + NB_INPLACE_MATRIX_MULTIPLY: int + NB_DIVMOD: int + +class PyTypeSlots: + TP_HASH: int + TP_ITER: int + TP_ITERNEXT: int + TP_CALL: int + TP_REPR: int + TP_RICHCOMPARE: int + TP_GETATTRO: int + TP_SETATTRO: int + TP_DESCR_GET: int + TP_DESCR_SET: int + TP_STR: int + TP_INIT: int diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/compiled_autograd.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/compiled_autograd.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ef24582b5023109733955cc77db0a84fae03b3fd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/compiled_autograd.pyi @@ -0,0 +1,13 @@ +from collections.abc import Callable + +from torch import Tensor +from torch._dynamo.compiled_autograd import AutogradCompilerInstance + +def set_autograd_compiler( + autograd_compiler: Callable[[], AutogradCompilerInstance] | None, + dynamic: bool, +) -> tuple[Callable[[], AutogradCompilerInstance] | None, bool]: ... +def clear_cache() -> None: ... +def is_cache_empty() -> bool: ... +def set_verbose_logger(fn: Callable[[str], None] | None) -> bool: ... +def call_cpp_tensor_pre_hooks(idx: int, grad: Tensor) -> Tensor: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/eval_frame.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/eval_frame.pyi new file mode 100644 index 0000000000000000000000000000000000000000..303b669659e39c87214be22c868af24b9670bc3f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/eval_frame.pyi @@ -0,0 +1,106 @@ +import enum +import types +from collections.abc import Callable +from typing import overload + +from torch._dynamo.guards import GuardManagerWrapper +from torch._dynamo.types import DynamoCallback, DynamoGuardCompleteHook, DynamoGuardHook +from torch._guards import CompileId + +def set_eval_frame(callback: DynamoCallback) -> DynamoCallback: ... +def set_skip_guard_eval_unsafe(value: bool) -> bool: ... +def get_eval_frame_callback() -> DynamoCallback: ... +def reset_code(code: types.CodeType) -> None: ... +def unsupported(obj1: object, obj2: object) -> object: ... +def set_code_exec_strategy( + code: types.CodeType, strategy: _FrameExecStrategy +) -> None: ... +def set_guard_error_hook(hook: DynamoGuardHook) -> None: ... +def set_guard_complete_hook( + hook: DynamoGuardCompleteHook | None, +) -> DynamoGuardCompleteHook | None: ... +def raise_sigtrap() -> None: ... +def get_method_ml_flags(fn: object) -> int | None: ... +def set_c_recursion_limit(limit: int) -> None: ... +def get_c_recursion_limit() -> int: ... + +class _CacheEntry: + def check_fn(self, *args: object, **kwargs: object) -> bool: ... + def update_diff_guard_root_manager(self) -> None: ... + code: types.CodeType + compile_id: CompileId + # If we run into circular issues, just use object + guard_manager: GuardManagerWrapper + backend: Callable + isolate_recompiles_id: int + +class _PrecompileEntry: + guard_manager: GuardManagerWrapper + +class _ExtraState: + def invalidate( + self, cache_entry: _CacheEntry, guard_manager: GuardManagerWrapper + ) -> None: ... + +class _FrameAction(enum.IntEnum): + DEFAULT = 0 + SKIP = 1 + RUN_ONLY = 2 + +class _FrameExecStrategy: + cur_action: _FrameAction + recursive_action: _FrameAction + + @overload + def __init__(self) -> None: ... + @overload + def __init__( + self, cur_action: _FrameAction, recursive_action: _FrameAction + ) -> None: ... + +# This is an object that encapsulates the Python FrameType, and exposes +# properties Dynamo cares about for a frame. +class _PyInterpreterFrame: + f_code: types.CodeType + f_locals: dict[str, object] + f_globals: dict[str, object] + f_builtins: dict[str, object] + f_lasti: int + f_lineno: int + f_back: types.FrameType + # A tuple containing cell objects captured by this frame. + closure: tuple[types.CellType] + +def _debug_get_cache_entry_list(code: types.CodeType) -> list[_CacheEntry]: ... +def _get_cache_entries_for_region( + code: types.CodeType, isolate_recompiles_id: int +) -> list[_CacheEntry]: ... +def _get_total_cache_entry_count(code: types.CodeType) -> int: ... +def _get_frame_value_stack_with_depth( + frame: types.FrameType, depth: int +) -> list[object]: ... +def set_bytecode_debugger_callback( + callback: Callable[[types.CodeType], None] | None, +) -> None: ... +def get_bytecode_debugger_callback() -> Callable[[types.CodeType], None] | None: ... +def register_breakpoint_code(code: types.CodeType) -> None: ... + +# Sentinel for NULL stack values returned by _get_frame_value_stack_at_depth +class NullStackValue: ... + +NULL_STACK_VALUE: NullStackValue + +py_opcode_caches: list[int] + +def code_framelocals_names(code: types.CodeType) -> tuple[str, ...]: ... +def _load_precompile_entry( + code: types.CodeType, + guard_manager: GuardManagerWrapper, + dynamo_code: types.CodeType, +) -> None: ... +def _reset_precompile_entries(code: types.CodeType) -> None: ... +def _debug_get_precompile_entries(code: types.CodeType) -> list[_PrecompileEntry]: ... +def set_fullgraph_compiled_frame_count(value: int) -> int: ... +def set_fullgraph_error_on_nested_compile(value: bool) -> bool: ... +def set_eval_frame_isolate_recompiles_id(isolate_recompiles_id: int) -> int: ... +def get_eval_frame_isolate_recompiles_id() -> int: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/guards.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/guards.pyi new file mode 100644 index 0000000000000000000000000000000000000000..baafdfffa03c0f8c6ab6f1e8cdd43d97cf660940 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_dynamo/guards.pyi @@ -0,0 +1,519 @@ +import enum +import traceback +from collections.abc import Callable, Sequence +from typing import Any, TypeAlias + +import torch + +# TODO: We should move the `GuardManagerType` +# defined in `guards.py` here and update other +# imports +GuardManagerType: TypeAlias = enum.Enum + +class GlobalStateGuard: + def check(self) -> bool: ... + def reason(self) -> str: ... + +class LeafGuard: + def verbose_code_parts(self) -> list[str]: ... + +class RelationalGuard: ... + +class GuardDebugInfo: + verbose_code_parts: list[str] + result: bool + num_guards_executed: int + user_stack: traceback.StackSummary | None + +class LocalState: ... + +class GuardManager: + def check(self, value: Any) -> bool: ... + def check_verbose(self, value: Any) -> GuardDebugInfo: ... + + # Accessors + def globals_dict_manager( + self, + f_globals: dict[str, Any], + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def framelocals_manager( + self, + key: tuple[str, int], + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def dict_getitem_manager( + self, + key: Any, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def grad_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def generic_getattr_manager( + self, + attr: str, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def getitem_manager( + self, + key: Any, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def get_generic_dict_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def list_getitem_manager( + self, + key: Any, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def tuple_getitem_manager( + self, + key: Any, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def set_getitem_manager( + self, + index: Any, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def func_defaults_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def func_kwdefaults_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def tuple_iterator_getitem_manager( + self, + index: Any, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def weakref_call_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def call_function_no_args_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def global_weakref_manager( + self, + global_name: str, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def type_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def getattr_manager( + self, + attr: str, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def tensor_property_size_manager( + self, + idx: int, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def tensor_property_shape_manager( + self, + idx: int, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def tensor_property_storage_offset_manager( + self, + idx: int, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def indexed_manager( + self, + idx: int, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def lambda_manager( + self, + python_lambda: Callable[..., Any], + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def get_root(self) -> RootGuardManager: ... + def get_source(self) -> str: ... + def fail_count(self) -> int: ... + def get_child_managers(self) -> list[GuardManager]: ... + def repr(self) -> str: ... + def type_of_guarded_value(self) -> str: ... + def get_leaf_guards(self) -> list[LeafGuard]: ... + def get_accessors(self) -> list[GuardManager]: ... + def is_guarded_value_immutable(self) -> bool: ... + def is_tag_safe(self) -> bool: ... + def is_tag_safe_root(self) -> bool: ... + def has_no_accessors(self) -> bool: ... + def has_object_aliasing_guard(self) -> bool: ... + def get_type_of_guarded_value(self) -> type: ... + def type_dict_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def type_mro_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def code_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def closure_manager( + self, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + # Leaf guards + def add_lambda_guard( + self, + user_lambda: Callable[..., Any], + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_id_match_guard( + self, + id_val: int, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_equals_match_guard( + self, + equals_val: Any, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_global_state_guard( + self, + initial_state: Any, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_torch_function_mode_stack_guard( + self, + initial_stack: list[Any], + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_mapping_keys_guard( + self, + value: Any, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_dict_length_check_guard( + self, + value: int, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_length_check_guard( + self, + value: int, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_true_match_guard( + self, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_false_match_guard( + self, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_none_match_guard( + self, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_not_none_guard( + self, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_dispatch_key_set_guard( + self, + dispatch_key: Any, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_tensor_match_guard( + self, + value: Any, + sizes: list[int], + strides: list[int], + tensor_name: str, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ptype: Any, + dispatch_keys: Any, + ) -> None: ... + def add_dimension_marking_guard( + self, + expected_attrs: dict[str, set[int]], + absent_attrs: list[str], + dependent_attrs: dict[str, tuple[dict[int, Any] | None, str]], + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_no_hasattr_guard( + self, + attr_name: str, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_dict_contains_guard( + self, + contains: bool, + key: Any, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_type_match_guard( + self, + value: int, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_fake_script_type_match_guard( + self, + fake_script_object_type: type, + type_id: int, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_dict_version_guard( + self, + value: Any, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_set_contains_guard( + self, + contains: bool, + item: Any, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_dual_level_match_guard( + self, + level: int, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_float_is_nan_guard( + self, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_complex_is_nan_guard( + self, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_tuple_iterator_length_guard( + self, + length: int, + type_id: int, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_range_iterator_match_guard( + self, + start: int, + stop: int, + step: int, + type_id: int, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def add_default_device_guard( + self, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def mark_tag_safe(self) -> None: ... + def mark_tag_safe_root(self) -> None: ... + +class RootGuardManager(GuardManager): + def get_epilogue_lambda_guards(self) -> list[LeafGuard]: ... + def add_epilogue_lambda_guard( + self, + guard: LeafGuard, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, + ) -> None: ... + def clone_manager( + self, clone_filter_fn: Callable[[GuardManager], bool] + ) -> RootGuardManager: ... + def attach_compile_id(self, compile_id: str) -> None: ... + def get_local_state(self) -> LocalState: ... + def set_local_state(self, local_state: LocalState) -> None: ... + +class DictGuardManager(GuardManager): + def get_key_manager( + self, + index: int, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def get_value_manager( + self, + index: int, + source: str, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: ... + def get_key_value_managers( + self, + ) -> dict[int, tuple[GuardManager, GuardManager]]: ... + +# Guard accessor stubs +class GuardAccessor: ... +class DictGetItemGuardAccessor(GuardAccessor): ... +class GetGenericDictGuardAccessor(GuardAccessor): ... +class TypeDictGuardAccessor(GuardAccessor): ... +class TypeMROGuardAccessor(GuardAccessor): ... +class ClosureGuardAccessor(GuardAccessor): ... +class TupleGetItemGuardAccessor(GuardAccessor): ... +class TypeGuardAccessor(GuardAccessor): ... +class CodeGuardAccessor(GuardAccessor): ... +class FuncDefaultsGuardAccessor(GuardAccessor): ... +class FuncKwDefaultsGuardAccessor(GuardAccessor): ... + +class GetAttrGuardAccessor(GuardAccessor): + def get_attr_name(self) -> str: ... + +def install_object_aliasing_guard( + x: GuardManager, + y: GuardManager, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, +) -> None: ... +def install_no_tensor_aliasing_guard( + guard_managers: list[GuardManager], + tensor_names: list[str], + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, +) -> None: ... +def install_storage_overlapping_guard( + overlapping_guard_managers: list[GuardManager], + non_overlapping_guard_managers: list[GuardManager], + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, +) -> None: ... +def install_symbolic_shape_guard( + guard_managers: list[GuardManager], + nargs_int: int, + nargs_float: int, + py_addr: int, + py_addr_keep_alive: Any, + verbose_code_parts: list[str], + user_stack: traceback.StackSummary | None, +) -> None: ... +def profile_guard_manager( + guard_manager: GuardManager, + f_locals: dict[str, Any], + n_iters: int, +) -> float: ... + +class TensorGuards: + def __init__( + self, + *, + dynamic_dims_sizes: list[torch.SymInt | None] | None = None, + dynamic_dims_strides: list[torch.SymInt | None] | None = None, + ) -> None: ... + def check(self, *args: Any) -> bool: ... + def check_verbose( + self, *args: Any, tensor_check_names: list[str] | None = None + ) -> bool | str: ... + +def assert_size_stride( + item: torch.Tensor, + size: torch.types._size, + stride: torch.types._size, + op_name: str | None = None, +) -> None: ... +def assert_size_stride_grouped( + items: Sequence[torch.Tensor], + sizes: Sequence[torch.types._size], + strides: Sequence[torch.types._size], + op_name: str | None = None, +) -> None: ... +def assert_alignment( + item: torch.Tensor, + alignment: int, + op_name: str | None = None, +) -> None: ... +def copy_if_misaligned(item: torch.Tensor) -> torch.Tensor: ... +def check_obj_id(obj: object, expected: int) -> bool: ... +def check_type_id(obj: object, expected: int) -> bool: ... +def dict_version(d: dict[Any, Any]) -> int: ... +def compute_overlapping_tensors( + tensors: list[torch.Tensor], symbolic: bool = True +) -> set[int]: ... +def set_is_in_mode_without_ignore_compile_internals(value: bool) -> None: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_export/__init__.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_export/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..039f9c22eea620bc9675d233684df72c7ac4471c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_export/__init__.pyi @@ -0,0 +1,9 @@ +# Defined in torch/csrc/export/pybind.cpp +class CppExportedProgram: ... + +def deserialize_exported_program( + serialized_program: str, +) -> CppExportedProgram: ... +def serialize_exported_program( + cpp_exported_program: CppExportedProgram, +) -> str: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_export/pt2_archive_constants.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_export/pt2_archive_constants.pyi new file mode 100644 index 0000000000000000000000000000000000000000..08f847e2aeafc7f238eece7071fa4a128a60a104 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_export/pt2_archive_constants.pyi @@ -0,0 +1,26 @@ +# Defined in torch/csrc/export/pt2_archive_constants.h + +ARCHIVE_ROOT_NAME: str = ... +ARCHIVE_FORMAT_PATH: str = ... +ARCHIVE_FORMAT_VALUE: str = ... +ARCHIVE_VERSION_PATH: str = ... +ARCHIVE_VERSION_VALUE: str = ... +MODELS_DIR: str = ... +MODELS_FILENAME_FORMAT: str = ... +AOTINDUCTOR_DIR: str = ... +MTIA_DIR: str = ... +WEIGHTS_DIR: str = ... +WEIGHTS_CONFIG_FILENAME_FORMAT: str = ... +WEIGHT_FILENAME_PREFIX: str = ... +CONSTANTS_DIR: str = ... +CONSTANTS_CONFIG_FILENAME_FORMAT: str = ... +TENSOR_CONSTANT_FILENAME_PREFIX: str = ... +CUSTOM_OBJ_FILENAME_PREFIX: str = ... +OPAQUE_OBJ_FILENAME_PREFIX: str = ... +SAMPLE_INPUTS_DIR: str = ... +SAMPLE_INPUTS_FILENAME_FORMAT: str = ... +EXECUTORCH_DIR: str = ... +EXTRA_DIR: str = ... +MODULE_INFO_PATH: str = ... +XL_MODEL_WEIGHTS_DIR: str = ... +XL_MODEL_WEIGHTS_PARAM_CONFIG_PATH: str = ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_functionalization.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_functionalization.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4e00df97e2717c1d3c63db3fc42e31507211eb99 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_functionalization.pyi @@ -0,0 +1,16 @@ +from torch import Tensor +from torch.types import _bool + +# Defined in torch/csrc/functionalization/Module.cpp + +class ViewMeta: + has_symbolic_inputs: _bool + +# Returns the list of ViewMeta instances of the given functional tensor. +# +# Although we do have python bindings for their types, we won't +# expose them here, since they should not be used by users. +def get_view_meta_sequence(tensor: Tensor) -> list[ViewMeta]: ... + +# Applies the ViewMeta sequence on top of the given base. +def apply_view_meta_sequence(base: Tensor, sequence: list[ViewMeta]) -> Tensor: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_functions.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_functions.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ce0710ae6315d70a60a705fc216ad1b0071f6088 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_functions.pyi @@ -0,0 +1,22 @@ +from typing import AnyStr, overload + +from torch import Tensor + +class AccumulateGrad: + variable: Tensor + +class UndefinedGrad: + def __init__(self) -> None: ... + def __call__(self, *inputs: Tensor) -> list[Tensor]: ... + +class DelayedError: + def __init__(self, msg: AnyStr, num_inputs: int) -> None: ... + + # __call__ should really be a higher-kinded type: + # def __call__(self, arg: Tensor) -> Tensor: ... + # def __call__(self, *args: Tensor * num_inputs) -> Tuple[Tensor * num_inputs]: ... + + @overload + def __call__(self, i0: Tensor) -> Tensor: ... + @overload + def __call__(self, *args: Tensor) -> tuple[Tensor, ...]: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_functorch.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_functorch.pyi new file mode 100644 index 0000000000000000000000000000000000000000..954aa60de7b7445df594f747d9376bfbb2d2f90a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_functorch.pyi @@ -0,0 +1,102 @@ +# mypy: allow-untyped-defs +from enum import Enum +from typing import Any + +from torch import Tensor + +# Defined in torch/csrc/functorch/init.cpp + +def _assert_wrapped_functional( + input_tensor: Tensor, wrapped_tensor: Tensor +) -> None: ... +def _func_decrement_nesting() -> int: ... +def _func_increment_nesting(reapply_views: bool) -> int: ... +def _propagate_functional_input_mutation( + input_tensor: Tensor, wrapped_tensor: Tensor +) -> None: ... +def set_inplace_requires_grad_allowed(allowed: bool) -> None: ... +def get_inplace_requires_grad_allowed() -> bool: ... +def _set_dynamic_layer_keys_included(included: bool) -> None: ... +def get_unwrapped(tensor: Tensor) -> Tensor: ... +def is_batchedtensor(tensor: Tensor) -> bool: ... +def is_functionaltensor(tensor: Tensor) -> bool: ... +def is_functorch_wrapped_tensor(tensor: Tensor) -> bool: ... +def is_gradtrackingtensor(tensor: Tensor) -> bool: ... +def is_legacy_batchedtensor(tensor: Tensor) -> bool: ... +def maybe_get_bdim(tensor: Tensor) -> int: ... +def maybe_get_level(tensor: Tensor) -> int: ... +def maybe_current_level() -> int | None: ... +def unwrap_dead_wrappers(args: tuple[Any, ...]) -> tuple[Any, ...]: ... +def unwrap_if_dead(tensor: Tensor) -> Tensor: ... +def _unwrap_for_grad(tensor: Tensor, level: int) -> Tensor: ... +def _wrap_for_grad(tensor: Tensor, level: int) -> Tensor: ... +def _unwrap_batched(tensor: Tensor, level: int) -> tuple[Tensor, int | None]: ... +def current_level() -> int: ... +def count_jvp_interpreters() -> int: ... +def _add_batch_dim(tensor: Tensor, bdim: int, level: int) -> Tensor: ... +def _remove_batch_dim( + tensor: Tensor, level: int, batch_size: int, out_dim: int +) -> Tensor: ... +def _maybe_unsafe_set_level(tensor: Tensor, level: int) -> None: ... +def set_single_level_autograd_function_allowed(allowed: bool) -> None: ... +def get_single_level_autograd_function_allowed() -> bool: ... +def _unwrap_functional_tensor(tensor: Tensor, reapply_views: bool) -> Tensor: ... +def _wrap_functional_tensor(tensor: Tensor, level: int) -> Tensor: ... +def _vmap_increment_nesting(batch_size: int, randomness: str) -> int: ... +def _vmap_decrement_nesting() -> int: ... +def _grad_increment_nesting() -> int: ... +def _grad_decrement_nesting() -> int: ... +def _jvp_increment_nesting() -> int: ... +def _jvp_decrement_nesting() -> int: ... + +# Defined in aten/src/ATen/functorch/Interpreter.h +class TransformType(Enum): + Torch = ... + Vmap = ... + Grad = ... + Jvp = ... + Functionalize = ... + +class RandomnessType(Enum): + Error = ... + Same = ... + Different = ... + +class CInterpreter: + def key(self) -> TransformType: ... + def level(self) -> int: ... + def serialize(self) -> bytes: ... + @staticmethod + def deserialize(bytes) -> CInterpreter: ... + +class CGradInterpreterPtr: + def __init__(self, interpreter: CInterpreter) -> None: ... + def lift(self, Tensor) -> Tensor: ... + def prevGradMode(self) -> bool: ... + +class CJvpInterpreterPtr: + def __init__(self, interpreter: CInterpreter) -> None: ... + def lift(self, Tensor) -> Tensor: ... + def prevFwdGradMode(self) -> bool: ... + +class CFunctionalizeInterpreterPtr: + def __init__(self, interpreter: CInterpreter) -> None: ... + def key(self) -> TransformType: ... + def level(self) -> int: ... + def functionalizeAddBackViews(self) -> bool: ... + +class CVmapInterpreterPtr: + def __init__(self, interpreter: CInterpreter) -> None: ... + def key(self) -> TransformType: ... + def level(self) -> int: ... + def batchSize(self) -> int: ... + def randomness(self) -> RandomnessType: ... + +class DynamicLayer: ... + +def get_dynamic_layer_stack_depth() -> int: ... +def get_interpreter_stack() -> list[CInterpreter]: ... +def peek_interpreter_stack() -> CInterpreter: ... +def pop_dynamic_layer_stack() -> DynamicLayer: ... +def pop_dynamic_layer_stack_and_undo_to_depth(int) -> None: ... +def push_dynamic_layer_stack(dl: DynamicLayer) -> int: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_instruction_counter.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_instruction_counter.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4e3c27567eb228b8763a6d2578db827b1ffbde41 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_instruction_counter.pyi @@ -0,0 +1,4 @@ +# Defined in torch/csrc/instruction_counter/Module.cpp + +def start() -> int: ... +def end(id: int) -> int: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_itt.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_itt.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8a54437f527b994821133532f26598c951631b28 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_itt.pyi @@ -0,0 +1,5 @@ +# Defined in torch/csrc/itt.cpp +def is_available() -> None: ... +def rangePush(message: str) -> None: ... +def rangePop() -> None: ... +def mark(message: str) -> None: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_jit_tree_views.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_jit_tree_views.pyi new file mode 100644 index 0000000000000000000000000000000000000000..bc7f7c3b7c1e943a33b68f0e8af87e70312fdc52 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_jit_tree_views.pyi @@ -0,0 +1,200 @@ +from typing import Any + +# Defined in torch/csrc/jit/python/python_tree_views.cpp + +class SourceRange: + def highlight(self) -> str: ... + @property + def start(self) -> int: ... + @property + def end(self) -> int: ... + +class SourceRangeFactory: + def __init__( + self, + text: str, + filename: Any, + file_lineno: int, + leading_whitespace_chars: int, + ) -> None: ... + def make_range(self, line: int, start_col: int, end_col: int) -> SourceRange: ... + def make_raw_range(self, start: int, end: int) -> SourceRange: ... + @property + def source(self) -> str: ... + +class TreeView: + def range(self) -> SourceRange: ... + def dump(self) -> None: ... + +class Ident(TreeView): + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + @property + def name(self) -> str: ... + +class Param(TreeView): + def __init__(self, type: Any | None, name: Ident, kwarg_only: bool) -> None: ... + +class Attribute(TreeView): + def __init__(self, name: Ident, value: Any) -> None: ... + +# Literals +def TrueLiteral(range: SourceRange) -> Any: ... +def FalseLiteral(range: SourceRange) -> Any: ... +def NoneLiteral(range: SourceRange) -> Any: ... + +# Tree nodes +class Stmt(TreeView): + def __init__(self, thing: TreeView) -> None: ... + +class Expr(TreeView): ... + +class Def(TreeView): + def __init__(self, name: Ident, decl: Any, body: list[Stmt]) -> None: ... + def decl(self) -> Any: ... + def name(self) -> Ident: ... + +class Property(TreeView): + def __init__( + self, r: SourceRange, name: Ident, getter: Def, setter: Def | None + ) -> None: ... + def name(self) -> Ident: ... + def getter_name(self) -> str: ... + def setter_name(self) -> Ident | None: ... + +class ClassDef(TreeView): + def __init__( + self, name: Ident, body: list[Stmt], props: list[Property], assigns: list[Any] + ) -> None: ... + +class Decl(TreeView): + def __init__( + self, r: SourceRange, params: list[Param], return_type: Expr | None + ) -> None: ... + +class Delete(Stmt): + def __init__(self, range: SourceRange, targets: list[Expr]) -> None: ... + +class WithItem(Expr): + def __init__(self, range: SourceRange, target: Expr, var: Any | None) -> None: ... + +class Assign(Stmt): + def __init__( + self, lhs: list[Expr], rhs: Expr, type: Expr | None = None + ) -> None: ... + +class AugAssign(Stmt): + def __init__(self, lhs: Expr, kind_str: str, rhs: Expr) -> None: ... + +class Return(Stmt): + def __init__(self, range: SourceRange, value: Expr | None) -> None: ... + +class Raise(Stmt): + def __init__(self, range: SourceRange, expr: Expr) -> None: ... + +class Assert(Stmt): + def __init__(self, range: SourceRange, test: Expr, msg: Expr | None) -> None: ... + +class Pass(Stmt): + def __init__(self, range: SourceRange) -> None: ... + +class Break(Stmt): ... +class Continue(Stmt): ... + +class Dots(Expr, TreeView): + def __init__(self, range: SourceRange) -> None: ... + +class If(Stmt): + def __init__( + self, + range: SourceRange, + cond: Expr, + true_branch: list[Stmt], + false_branch: list[Stmt], + ) -> None: ... + +class While(Stmt): + def __init__(self, range: SourceRange, cond: Expr, body: list[Stmt]) -> None: ... + +class With(Stmt): + def __init__( + self, range: SourceRange, targets: list[WithItem], body: list[Stmt] + ) -> None: ... + +class For(Stmt): + def __init__( + self, + range: SourceRange, + targets: list[Expr], + itrs: list[Expr], + body: list[Stmt], + ) -> None: ... + +class ExprStmt(Stmt): + def __init__(self, expr: Expr) -> None: ... + +class Var(Expr): + def __init__(self, name: Ident) -> None: ... + @property + def name(self) -> str: ... + +class BinOp(Expr): + def __init__(self, kind: str, lhs: Expr, rhs: Expr) -> None: ... + +class UnaryOp(Expr): + def __init__(self, range: SourceRange, kind: str, expr: Expr) -> None: ... + +class Const(Expr): + def __init__(self, range: SourceRange, value: str) -> None: ... + +class StringLiteral(Expr): + def __init__(self, range: SourceRange, value: str) -> None: ... + +class Apply(Expr): + def __init__( + self, expr: Expr, args: list[Expr], kwargs: list[Attribute] + ) -> None: ... + +class Select(Expr): + def __init__(self, expr: Expr, field: Ident) -> None: ... + +class TernaryIf(Expr): + def __init__(self, cond: Expr, true_expr: Expr, false_expr: Expr) -> None: ... + +class ListComp(Expr): + def __init__( + self, range: SourceRange, elt: Expr, target: Expr, iter: Expr + ) -> None: ... + +class DictComp(Expr): + def __init__( + self, range: SourceRange, key: Expr, value: Expr, target: Expr, iter: Expr + ) -> None: ... + +class ListLiteral(Expr): + def __init__(self, range: SourceRange, args: list[Expr]) -> None: ... + +class TupleLiteral(Expr): + def __init__(self, range: SourceRange, args: list[Expr]) -> None: ... + +class DictLiteral(Expr): + def __init__( + self, range: SourceRange, keys: list[Expr], values: list[Expr] + ) -> None: ... + +class Subscript(Expr): + def __init__(self, base: Expr, subscript_exprs: list[Expr]) -> None: ... + +class SliceExpr(Expr): + def __init__( + self, + range: SourceRange, + lower: Expr | None, + upper: Expr | None, + step: Expr | None, + ) -> None: ... + +class Starred(Expr): + def __init__(self, range: SourceRange, expr: Expr) -> None: ... + +class EmptyTypeAnnotation(TreeView): + def __init__(self, range: SourceRange) -> None: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_lazy.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_lazy.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c6b2b89fa3a9e89d889d9248097315d7c9d8635c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_lazy.pyi @@ -0,0 +1,26 @@ +from torch import Tensor + +# defined in torch/csrc/lazy/python/init.cpp +def _mark_step(device: str, devices: list[str], wait: bool) -> None: ... +def _wait_device_ops(devices: list[str]) -> None: ... +def _reset_metrics() -> None: ... +def _counter_names() -> list[str]: ... +def _counter_value(name: str) -> int: ... +def _metrics_report() -> str: ... +def _get_graph_hash(tensors: list[Tensor]) -> str: ... +def _sync_multi( + tensors: list[Tensor], + devices: list[str], + wait: bool = True, + sync_ltc_data: bool = True, +) -> None: ... +def _get_tensor_id(tensor: Tensor) -> int: ... +def _get_tensors_text(tensors: list[Tensor]) -> str: ... +def _get_tensors_dot(tensors: list[Tensor]) -> str: ... +def _get_tensors_backend(tensors: list[Tensor]) -> str: ... +def _get_force_fallback() -> str: ... +def _set_force_fallback(newval: str) -> None: ... +def _clear_ir_cache() -> None: ... +def _dump_ir_cache(filename: str) -> None: ... +def _set_reuse_ir(val: bool) -> None: ... +def _get_default_device_type() -> str: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_lazy_ts_backend.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_lazy_ts_backend.pyi new file mode 100644 index 0000000000000000000000000000000000000000..cd1bef2de069dfc93cd2b6243ab97d550d75f086 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_lazy_ts_backend.pyi @@ -0,0 +1,12 @@ +# mypy: allow-untyped-defs +# defined in torch/csrc/lazy/python/init.cpp + +from typing import Any + +from torch import Tensor + +def _init(): ... +def _get_tensors_ts_device_data_node( + tensors: list[Tensor], +) -> tuple[list[int], list[Any]]: ... +def _run_cached_graph(hash_str: str, graph_inputs: list[Any]) -> list[Tensor]: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_monitor.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_monitor.pyi new file mode 100644 index 0000000000000000000000000000000000000000..82f2a3e4427038dcb0616d7b305c7c5c85c97606 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_monitor.pyi @@ -0,0 +1,58 @@ +# Defined in torch/csrc/monitor/python_init.cpp + +import datetime +from collections.abc import Callable +from enum import Enum +from types import TracebackType + +class Aggregation(Enum): + VALUE = ... + MEAN = ... + COUNT = ... + SUM = ... + MAX = ... + MIN = ... + +class Stat: + name: str + count: int + def __init__( + self, + name: str, + aggregations: list[Aggregation], + window_size: int, + max_samples: int = -1, + ) -> None: ... + def add(self, v: float) -> None: ... + def get(self) -> dict[Aggregation, float]: ... + +class Event: + name: str + timestamp: datetime.datetime + data: dict[str, int | float | bool | str] + def __init__( + self, + name: str, + timestamp: datetime.datetime, + data: dict[str, int | float | bool | str], + ) -> None: ... + +def log_event(e: Event) -> None: ... + +class EventHandlerHandle: ... + +def register_event_handler(handler: Callable[[Event], None]) -> EventHandlerHandle: ... +def unregister_event_handler(handle: EventHandlerHandle) -> None: ... + +class _WaitCounterTracker: + def __enter__(self) -> None: ... + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: TracebackType | None = None, + ) -> None: ... + +class _WaitCounter: + def __init__(self, key: str) -> None: ... + def guard(self) -> _WaitCounterTracker: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_nn.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_nn.pyi new file mode 100644 index 0000000000000000000000000000000000000000..08a9fc6e36fd7d997707a8f096ae4b6da7b1ec7b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_nn.pyi @@ -0,0 +1,347 @@ +# @generated by tools/pyi/gen_pyi.py from torch/_C/_nn.pyi.in +# mypy: disable-error-code="type-arg" + +from collections.abc import Sequence +from typing import Literal, overload + +from torch import memory_format, Tensor +from torch.types import _bool, _device, _dtype, _int, _size + +# Defined in tools/autograd/templates/python_nn_functions.cpp + +def adaptive_avg_pool2d(input: Tensor, output_size: _int | _size) -> Tensor: ... +def adaptive_avg_pool3d(input: Tensor, output_size: _int | _size) -> Tensor: ... +def adaptive_max_pool2d( + input: Tensor, + output_size: _int | _size, +) -> tuple[Tensor, Tensor]: ... +def adaptive_max_pool3d( + input: Tensor, + output_size: _int | _size, +) -> tuple[Tensor, Tensor]: ... +def avg_pool2d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size | None = None, + padding: _int | _size = 0, + ceil_mode: bool = False, + count_include_pad: bool = True, + divisor_override: int | None = None, +) -> Tensor: ... +def avg_pool3d( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size | None = None, + padding: _int | _size = 0, + ceil_mode: bool = False, + count_include_pad: bool = True, + divisor_override: int | None = None, +) -> Tensor: ... +def binary_cross_entropy( + input: Tensor, + target: Tensor, + weight: Tensor | None = None, + reduction: str = ..., +) -> Tensor: ... +def col2im( + input: Tensor, + output_size: _int | _size, + kernel_size: _int | _size, + dilation: _int | _size, + stride: _int | _size | None = None, + padding: _int | _size = 0, +) -> Tensor: ... +def cross_entropy_loss( + input: Tensor, + target: Tensor, + weight: Tensor | None = None, + reduction: str = ..., + ignore_index: int = -100, + label_smoothing: float = 0.0, +) -> Tensor: ... +def elu( + input: Tensor, + alpha: float = 1.0, + scale: float = 1.0, + input_scale: float = 1.0, +) -> Tensor: ... +def elu_(input: Tensor, alpha: float = ...) -> Tensor: ... +def fractional_max_pool2d( + input: Tensor, + kernel_size: _int | _size, + output_size: _int | _size, + _random_samples: Tensor, +) -> tuple[Tensor, Tensor]: ... +def fractional_max_pool3d( + input: Tensor, + kernel_size: _int | _size, + output_size: _int | _size, + _random_samples: Tensor, +) -> tuple[Tensor, Tensor]: ... +def gelu(input: Tensor, approximate: str = ...) -> Tensor: ... +def glu(input: Tensor, dim: int = -1) -> Tensor: ... +def hardsigmoid(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def hardsigmoid_(input: Tensor) -> Tensor: ... +def hardswish(input: Tensor) -> Tensor: ... +def hardswish_(input: Tensor) -> Tensor: ... +def hardtanh( + input: Tensor, + min_val: float = ..., + max_val: float = ..., + *, + out: Tensor | None = None, +) -> Tensor: ... +def hardtanh_( + input: Tensor, + min_val: float = ..., + max_val: float = ..., +) -> Tensor: ... +def huber_loss( + input: Tensor, + target: Tensor, + reduction: str = ..., + delta: float = 1.0, +) -> Tensor: ... +def im2col( + input: Tensor, + kernel_size: _int | _size, + dilation: _int | _size, + padding: _int | _size, + stride: _int | _size, +) -> Tensor: ... +def l1_loss(input: Tensor, target: Tensor, reduction: str = ...) -> Tensor: ... +def leaky_relu( + input: Tensor, + negative_slope: float = ..., + *, + out: Tensor | None = None, +) -> Tensor: ... +def leaky_relu_(input: Tensor, negative_slope: float = ...) -> Tensor: ... +def linear( + input: Tensor, + weight: Tensor, + bias: Tensor | None = None, +) -> Tensor: ... +def log_sigmoid(input: Tensor) -> Tensor: ... +def max_pool2d_with_indices( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size | None = None, + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: bool = False, +) -> tuple[Tensor, Tensor]: ... +def max_pool3d_with_indices( + input: Tensor, + kernel_size: _int | _size, + stride: _int | _size | None = None, + padding: _int | _size = 0, + dilation: _int | _size = 1, + ceil_mode: bool = False, +) -> tuple[Tensor, Tensor]: ... +def max_unpool2d( + input: Tensor, + indices: Tensor, + output_size: Sequence[int] | None, +) -> Tensor: ... +def max_unpool3d( + input: Tensor, + indices: Tensor, + output_size: Sequence[int] | None, + stride: _int | _size, + padding: _int | _size, +) -> Tensor: ... +def mish(input: Tensor) -> Tensor: ... +def mish_(input: Tensor) -> Tensor: ... +def mse_loss(input: Tensor, target: Tensor, reduction: str = ...) -> Tensor: ... +def multi_margin_loss( + input: Tensor, + target: Tensor, + p: float = 1.0, + margin: float = 1.0, + weight: Tensor | None = None, + reduction: str = ..., +) -> Tensor: ... +def multilabel_margin_loss( + input: Tensor, + target: Tensor, + reduction: str = ..., +) -> Tensor: ... +def nll_loss_nd( + input: Tensor, + target: Tensor, + weight: Tensor | None = None, + reduction: str = ..., + ignore_index: int = -100, +) -> Tensor: ... +def one_hot(tensor: Tensor, num_classes: int = ...) -> Tensor: ... +def pad( + input: Tensor, + pad: Sequence[int], + mode: str = ..., + value: float | None = None, +) -> Tensor: ... +def relu6(input: Tensor) -> Tensor: ... +def relu6_(input: Tensor) -> Tensor: ... +def scaled_dot_product_attention( + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Tensor | None = None, + dropout_p: float = 0.0, + is_causal: bool = False, + scale: float | None = None, + enable_gqa: bool = False, +) -> Tensor: ... +def silu(input: Tensor) -> Tensor: ... +def silu_(input: Tensor) -> Tensor: ... +def smooth_l1_loss( + input: Tensor, + target: Tensor, + reduction: str = ..., + beta: float = 1.0, +) -> Tensor: ... +def soft_margin_loss( + input: Tensor, + target: Tensor, + reduction: str = ..., +) -> Tensor: ... +def softplus( + input: Tensor, + beta: float = ..., + threshold: float = ..., +) -> Tensor: ... +def softshrink(input: Tensor, lambd: float = ...) -> Tensor: ... + +# Defined in aten/src/ATen/native/mkldnn/Linear.cpp +def mkldnn_linear(input: Tensor, weight: Tensor, bias: Tensor | None) -> Tensor: ... + +# Defined at aten/src/ATen/native/mkldnn/MKLDNNConversions.cpp +def mkldnn_reorder_conv2d_weight( + self: Tensor, + padding: list, + stride: list, + dilatation: list, + groups: int, +) -> Tensor: ... +def mkldnn_reorder_conv3d_weight( + self: Tensor, + padding: list, + stride: list, + dilatation: list, + groups: int, +) -> Tensor: ... + +# Defined in aten/src/ATen/native/mkldnn/Prelu.cpp +def mkldnn_prelu(input: Tensor, weight: Tensor) -> Tensor: ... + +# Defined at tools/autograd/templates/python_nn_functions.cpp +@overload +def _parse_to( + device: _device, + dtype: _dtype, + non_blocking: _bool, + copy: _bool, + *, + memory_format: memory_format, +) -> tuple[_device, _dtype, _bool, memory_format]: ... +@overload +def _parse_to( + dtype: _dtype, + non_blocking: _bool, + copy: _bool, + *, + memory_format: memory_format, +) -> tuple[_device, _dtype, _bool, memory_format]: ... +@overload +def _parse_to( + tensor: Tensor, + non_blocking: _bool, + copy: _bool, + *, + memory_format: memory_format, +) -> tuple[_device, _dtype, _bool, memory_format]: ... + +# Defined in aten/src/ATen/native/PackedSequence.cpp +def pad_sequence( + sequences: list[Tensor] | tuple[Tensor, ...], + batch_first: bool = False, + padding_value: float = 0.0, + padding_side: Literal["left", "right"] = "right", +) -> Tensor: ... + +# Upsample functions used by torch.nn.functional.interpolate +def upsample_nearest1d( + input: Tensor, + output_size: Sequence[int] | None, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def upsample_nearest2d( + input: Tensor, + output_size: Sequence[int] | None, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def upsample_nearest3d( + input: Tensor, + output_size: Sequence[int] | None, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def _upsample_nearest_exact1d( + input: Tensor, + output_size: Sequence[int] | None, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def _upsample_nearest_exact2d( + input: Tensor, + output_size: Sequence[int] | None, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def _upsample_nearest_exact3d( + input: Tensor, + output_size: Sequence[int] | None, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def upsample_linear1d( + input: Tensor, + output_size: Sequence[int] | None, + align_corners: bool, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def _upsample_bilinear2d_aa( + input: Tensor, + output_size: Sequence[int] | None, + align_corners: bool, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def upsample_bilinear2d( + input: Tensor, + output_size: Sequence[int] | None, + align_corners: bool, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def upsample_trilinear3d( + input: Tensor, + output_size: Sequence[int] | None, + align_corners: bool, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def _upsample_bicubic2d_aa( + input: Tensor, + output_size: Sequence[int] | None, + align_corners: bool, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def _upsample_lanczos2d_aa( + input: Tensor, + output_size: Sequence[int] | None, + align_corners: bool, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def upsample_bicubic2d( + input: Tensor, + output_size: Sequence[int] | None, + align_corners: bool, + scale_factors: Sequence[float] | None, +) -> Tensor: ... +def flatten_dense_tensors(tensors: list[Tensor]) -> Tensor: ... +def unflatten_dense_tensors(flat: Tensor, tensors: list[Tensor]) -> list[Tensor]: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_nvtx.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_nvtx.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9b96874c36578ebaba065188d726455ff0b771be --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_nvtx.pyi @@ -0,0 +1,9 @@ +# mypy: allow-untyped-defs +# Defined in torch/csrc/cuda/shared/nvtx.cpp +def rangePushA(message: str) -> int: ... +def rangePop() -> int: ... +def rangeStartA(message: str) -> int: ... +def rangeEnd(int) -> None: ... +def markA(message: str) -> None: ... +def deviceRangeStart(message: str, stream: int) -> object: ... +def deviceRangeEnd(range_handle: object, stream: int) -> None: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_onnx.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_onnx.pyi new file mode 100644 index 0000000000000000000000000000000000000000..349e0b9ad12f0dd9306fde89a40718f26b158f0e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_onnx.pyi @@ -0,0 +1,39 @@ +# Defined in torch/csrc/onnx/init.cpp + +from enum import Enum + +PRODUCER_VERSION: str + +class TensorProtoDataType(Enum): + UNDEFINED = ... + FLOAT = ... + UINT8 = ... + INT8 = ... + UINT16 = ... + INT16 = ... + INT32 = ... + INT64 = ... + STRING = ... + BOOL = ... + FLOAT16 = ... + DOUBLE = ... + UINT32 = ... + UINT64 = ... + COMPLEX64 = ... + COMPLEX128 = ... + BFLOAT16 = ... + FLOAT8E5M2 = ... + FLOAT8E4M3FN = ... + FLOAT8E5M2FNUZ = ... + FLOAT8E4M3FNUZ = ... + +class OperatorExportTypes(Enum): + ONNX = ... + ONNX_ATEN = ... + ONNX_ATEN_FALLBACK = ... + ONNX_FALLTHROUGH = ... + +class TrainingMode(Enum): + EVAL = ... + PRESERVE = ... + TRAINING = ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_profiler.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_profiler.pyi new file mode 100644 index 0000000000000000000000000000000000000000..925c5dcde668e64e47404ee78cb87f4ec5f8c8b7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_profiler.pyi @@ -0,0 +1,353 @@ +from enum import Enum +from typing import Literal, TypeAlias + +from torch._C import device, dtype, layout + +# defined in torch/csrc/profiler/python/init.cpp + +class RecordScope(Enum): + FUNCTION = ... + BACKWARD_FUNCTION = ... + TORCHSCRIPT_FUNCTION = ... + KERNEL_FUNCTION_DTYPE = ... + CUSTOM_CLASS = ... + BUILD_FEATURE = ... + LITE_INTERPRETER = ... + USER_SCOPE = ... + STATIC_RUNTIME_OP = ... + STATIC_RUNTIME_MODEL = ... + +class ProfilerState(Enum): + Disabled = ... + CPU = ... + CUDA = ... + NVTX = ... + ITT = ... + PRIVATEUSE1 = ... + KINETO = ... + KINETO_GPU_FALLBACK = ... + KINETO_PRIVATEUSE1_FALLBACK = ... + KINETO_PRIVATEUSE1 = ... + +class ActiveProfilerType(Enum): + NONE = ... + LEGACY = ... + KINETO = ... + NVTX = ... + ITT = ... + PRIVATEUSE1 = ... + +class ProfilerActivity(Enum): + CPU = ... + CUDA = ... + XPU = ... + MTIA = ... + HPU = ... + PrivateUse1 = ... + +class _EventType(Enum): + TorchOp = ... + Backend = ... + Allocation = ... + OutOfMemory = ... + PyCall = ... + PyCCall = ... + Kineto = ... + +class _ExperimentalConfig: + def __init__( + self, + profiler_metrics: list[str] = ..., + profiler_measure_per_kernel: bool = ..., + verbose: bool = ..., + performance_events: list[str] = ..., + enable_cuda_sync_events: bool = ..., + adjust_profiler_step: bool = ..., + disable_external_correlation: bool = ..., + profile_all_threads: bool = ..., + capture_overload_names: bool = ..., + record_python_gc_info: bool = ..., + expose_kineto_event_metadata: bool = ..., + custom_profiler_config: str = ..., + adjust_timestamps: bool = ..., + trace_only: bool = ..., + ) -> None: ... + trace_only: bool + # Deprecated no-ops; retained only so the Python layer can detect and warn. + profiler_metrics: list[str] + profiler_measure_per_kernel: bool + +class ProfilerConfig: + def __init__( + self, + state: ProfilerState, + report_input_shapes: bool, + profile_memory: bool, + with_stack: bool, + with_flops: bool, + with_modules: bool, + experimental_config: _ExperimentalConfig, + trace_id: str | None = None, + ) -> None: ... + +class _ProfilerEvent: + start_tid: int + start_time_ns: int + children: list[_ProfilerEvent] + + # TODO(robieta): remove in favor of `self.typed` + extra_fields: ( + _ExtraFields_TorchOp + | _ExtraFields_Backend + | _ExtraFields_Allocation + | _ExtraFields_OutOfMemory + | _ExtraFields_PyCall + | _ExtraFields_PyCCall + | _ExtraFields_Kineto + ) + + @property + def typed( + self, + ) -> ( + tuple[Literal[_EventType.TorchOp], _ExtraFields_TorchOp] + | tuple[Literal[_EventType.Backend], _ExtraFields_Backend] + | tuple[Literal[_EventType.Allocation], _ExtraFields_Allocation] + | tuple[Literal[_EventType.OutOfMemory], _ExtraFields_OutOfMemory] + | tuple[Literal[_EventType.PyCall], _ExtraFields_PyCall] + | tuple[Literal[_EventType.PyCCall], _ExtraFields_PyCCall] + | tuple[Literal[_EventType.Kineto], _ExtraFields_Kineto] + ): ... + @property + def name(self) -> str: ... + @property + def overload_name(self) -> str: ... + @property + def tag(self) -> _EventType: ... + @property + def id(self) -> int: ... + @property + def parent(self) -> _ProfilerEvent | None: ... + @property + def correlation_id(self) -> int: ... + @property + def end_time_ns(self) -> int: ... + @property + def duration_time_ns(self) -> int: ... + +class _TensorMetadata: + impl_ptr: int | None + storage_data_ptr: int | None + id: int | None + + @property + def allocation_id(self) -> int | None: ... + @property + def layout(self) -> layout: ... + @property + def device(self) -> device: ... + @property + def dtype(self) -> dtype: ... + @property + def sizes(self) -> list[int]: ... + @property + def strides(self) -> list[int]: ... + +Scalar: TypeAlias = int | float | bool | complex +Input: TypeAlias = _TensorMetadata | list[_TensorMetadata] | Scalar | None + +class _ExtraFields_TorchOp: + name: str + sequence_number: int + allow_tf32_cublas: bool + + @property + def inputs(self) -> list[Input]: ... + @property + def scope(self) -> RecordScope: ... + +class _ExtraFields_Backend: ... + +class _ExtraFields_Allocation: + ptr: int + id: int | None + alloc_size: int + total_allocated: int + total_reserved: int + + @property + def allocation_id(self) -> int | None: ... + @property + def device(self) -> device: ... + +class _ExtraFields_OutOfMemory: ... + +class _PyFrameState: + line_number: int + function_name: str + + @property + def file_name(self) -> str: ... + +class _NNModuleInfo: + @property + def self_ptr(self) -> int: ... + @property + def cls_ptr(self) -> int: ... + @property + def cls_name(self) -> str: ... + @property + def parameters( + self, + ) -> list[tuple[str, _TensorMetadata, _TensorMetadata | None]]: ... + +class _OptimizerInfo: + @property + def parameters( + self, + ) -> list[ + tuple[ + # Parameter + _TensorMetadata, + # + # Gradient (if present during optimizer.step()) + _TensorMetadata | None, + # + # Optimizer state for Parameter as (name, tensor) pairs + list[tuple[str, _TensorMetadata]], + ] + ]: ... + +class _ExtraFields_PyCCall: + @property + def caller(self) -> _PyFrameState: ... + +class _ExtraFields_PyCall: + @property + def callsite(self) -> _PyFrameState: ... + @property + def caller(self) -> _PyFrameState: ... + @property + def module(self) -> _NNModuleInfo | None: ... + @property + def optimizer(self) -> _OptimizerInfo | None: ... + +class _ExtraFields_Kineto: ... + +def _add_execution_trace_observer(output_file_path: str) -> bool: ... +def _remove_execution_trace_observer() -> None: ... +def _enable_execution_trace_observer() -> None: ... +def _disable_execution_trace_observer() -> None: ... +def _set_record_concrete_inputs_enabled_val(val: bool) -> None: ... +def _set_fwd_bwd_enabled_val(val: bool) -> None: ... +def _set_cuda_sync_enabled_val(val: bool) -> None: ... + +# Approximate-clock helpers used by the experimental CUPTI monitor. +class _ApproximateClockToUnixTimeConverter: + def __init__(self) -> None: ... + def to_unix_ns(self, t: int) -> int: ... + +def _get_approximate_time() -> int: ... + +# GIL-free CUPTI monitor buffer pool (torch/csrc/profiler/cupti/monitor_native). +# Exposed as the torch._C._profiler._cupti_monitor submodule. +class _CuptiMonitorModule: + @staticmethod + def approximate_time_callback_address() -> int: ... + @staticmethod + def configure_buffers(buffer_size: int) -> None: ... + @staticmethod + def buffer_request_callback_address() -> int: ... + @staticmethod + def buffer_complete_callback_address() -> int: ... + @staticmethod + def get_completed() -> ( + tuple[int, int, int, int, list[tuple[int, int, list[tuple[int, int, int]]]]] + | None + ): ... + @staticmethod + def return_buffer(ptr: int) -> None: ... + @staticmethod + def pending_buffers() -> int: ... + @staticmethod + def allocated_buffers() -> int: ... + @staticmethod + def shutdown_buffers() -> None: ... + @staticmethod + def reset_buffers() -> None: ... + @staticmethod + def configure_decoder( + subscriber: int, + get_next_record_fn: int, + fence_kind: int = 0, + fence_end_field: int = -1, + self_flush: bool = False, + flush_period_ns: int = 0, + flush_fn: int = 0, + ) -> None: ... + @staticmethod + def start_decoder() -> None: ... + @staticmethod + def stop_decoder() -> None: ... + @staticmethod + def decoder_max_sync_ns() -> int: ... + @staticmethod + def decoder_buffers_decoded() -> int: ... + @staticmethod + def decoder_valid_bytes() -> int: ... + @staticmethod + def drain_decoded() -> tuple[list, dict[int, str]]: ... + @staticmethod + def bench_decode( + buffer_addr: int, + valid_size: int, + record_layouts: list[tuple[int, int, list[tuple[int, int, int]]]], + iters: int, + ) -> float: ... + @staticmethod + def note_external_push(external_id: int) -> None: ... + @staticmethod + def note_external_pop() -> int: ... + @staticmethod + def current_external_id() -> int: ... + @staticmethod + def metadata_put_external(blob: str, external_id: int = 0) -> None: ... + # groups: each a tuple (ts, end, track_uuid, name_iid, int_annos, str_annos, + # arr_annos, json_annos, flow, gpu_corr, cat_iid) where gpu_corr is a + # (int32_offsets, int64_ids) CSR of per-slice render-stage event_ids or None. + # render: (gpu_specs, gfx_contexts, stage_cols, extra, launch, tables, const_extra) + # where stage_cols = (ts, dur, event_id, gpu_id, hw_queue_iid, stage_iid, + # context, name_iid, event_wait) and event_wait is a (int32_offsets, uint64_ids) + # CSR of per-stage event_wait_ids (graph node->node dependency arrows). + @staticmethod + def encode_pftrace( + base_ns: int, + tracks: list[tuple[int, int, bool, int, int, str]], + name_table: list[str], + category_table: list[str], + groups: list[tuple], + render: tuple | None = None, + counters: tuple | None = None, + compression_level: int = 1, + ) -> bytes: ... + +_cupti_monitor: _CuptiMonitorModule + +class CapturedTraceback: ... + +def gather_traceback(python: bool, script: bool, cpp: bool) -> CapturedTraceback: ... + +# The Dict has name, filename, line +def symbolize_tracebacks( + to_symbolize: list[CapturedTraceback], +) -> list[list[dict[str, str]]]: ... + +class _RecordFunctionFast: + def __init__( + self, + name: str, + input_values: list | tuple | None = None, + keyword_values: dict | None = None, + ) -> None: ... + def __enter__(self) -> None: ... + def __exit__(self, *exc_info: object) -> None: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C/_verbose.pyi b/.venv/lib/python3.12/site-packages/torch/_C/_verbose.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2388ce2bb8a5edd4c7640c374537e71607e5b72e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C/_verbose.pyi @@ -0,0 +1,3 @@ +# Defined in torch/csrc/utils/verbose.cpp +def mkl_set_verbose(enable: int) -> int: ... +def mkldnn_set_verbose(level: int) -> int: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_C_flatbuffer/__init__.pyi b/.venv/lib/python3.12/site-packages/torch/_C_flatbuffer/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..38750ed26aa26900591829fb7d51a3e3e1cdeeec --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_C_flatbuffer/__init__.pyi @@ -0,0 +1,11 @@ +# mypy: allow-untyped-defs +from torch._C import LiteScriptModule, ScriptModule + +def _load_mobile_module_from_file(filename: str): ... +def _load_mobile_module_from_bytes(bytes_: bytes): ... +def _load_jit_module_from_file(filename: str): ... +def _load_jit_module_from_bytes(bytes_: bytes): ... +def _save_mobile_module(m: LiteScriptModule, filename: str): ... +def _save_jit_module(m: ScriptModule, filename: str): ... +def _save_mobile_module_to_bytes(m: LiteScriptModule) -> bytes: ... +def _save_jit_module_to_bytes(m: ScriptModule) -> bytes: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_VF.py b/.venv/lib/python3.12/site-packages/torch/_VF.py new file mode 100644 index 0000000000000000000000000000000000000000..94166b51f1786593b584629744adc24036e8b1d7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_VF.py @@ -0,0 +1,31 @@ +""" +This makes the functions in torch._C._VariableFunctions available as + torch._VF. +without mypy being able to find them. + +A subset of those functions are mapped to ATen functions in +torch/jit/_builtins.py + +See https://github.com/pytorch/pytorch/issues/21478 for the reason for +introducing torch._VF + +""" + +import sys +import types + +import torch + + +class VFModule(types.ModuleType): + vf: types.ModuleType + + def __init__(self, name: str): + super().__init__(name) + self.vf = torch._C._VariableFunctions + + def __getattr__(self, name: str) -> object: + return getattr(self.vf, name) + + +sys.modules[__name__] = VFModule(__name__) diff --git a/.venv/lib/python3.12/site-packages/torch/_VF.pyi b/.venv/lib/python3.12/site-packages/torch/_VF.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2206a7e4093629d183276c42bfb015b061af3536 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_VF.pyi @@ -0,0 +1,31270 @@ +# @generated by tools/pyi/gen_pyi.py from torch/_C/_VariableFunctions.pyi.in +# mypy: disable-error-code="type-arg" +# mypy: allow-untyped-defs +# ruff: noqa: F401,PYI054 + +from collections.abc import Callable, Sequence +from types import EllipsisType +from typing import Any, Literal, overload, TypeVar + +import torch +from torch import ( + contiguous_format, + Generator, + inf, + memory_format, + strided, + SymInt, + Tensor, +) +from torch._prims_common import DeviceLikeType +from torch.types import ( + _bool, + _complex, + _device, + _dtype, + _float, + _int, + _layout, + _qscheme, + _size, + Device, + Number, + PySymType, +) + +__all__ = [ + "__and__", + "__lshift__", + "__or__", + "__rshift__", + "__xor__", + "_adaptive_avg_pool2d", + "_adaptive_avg_pool3d", + "_add_batch_dim", + "_add_relu", + "_add_relu_", + "_addmm_activation", + "_aminmax", + "_amp_foreach_non_finite_check_and_unscale_", + "_amp_update_scale_", + "_assert_async", + "_assert_scalar", + "_assert_tensor_metadata", + "_batch_norm_impl_index", + "_cast_Byte", + "_cast_Char", + "_cast_Double", + "_cast_Float", + "_cast_Half", + "_cast_Int", + "_cast_Long", + "_cast_Short", + "_choose_qparams_per_tensor", + "_chunk_cat", + "_coalesce", + "_compute_linear_combination", + "_conj", + "_conj_copy", + "_conj_physical", + "_convert_indices_from_coo_to_csr", + "_convert_indices_from_csr_to_coo", + "_convert_weight_to_int4pack", + "_convert_weight_to_int4pack_for_cpu", + "_convolution", + "_convolution_mode", + "_copy_from", + "_copy_from_and_resize", + "_cslt_compress", + "_cslt_sparse_mm", + "_cslt_sparse_mm_search", + "_ctc_loss", + "_cudnn_ctc_loss", + "_cudnn_init_dropout_state", + "_cudnn_rnn", + "_cudnn_rnn_flatten_weight", + "_cufft_clear_plan_cache", + "_cufft_get_plan_cache_max_size", + "_cufft_get_plan_cache_size", + "_cufft_set_plan_cache_max_size", + "_cummax_helper", + "_cummin_helper", + "_debug_has_internal_overlap", + "_dim_arange", + "_dirichlet_grad", + "_disable_functionalization", + "_dyn_quant_matmul_4bit", + "_dyn_quant_pack_4bit_weight", + "_efficientzerotensor", + "_embedding_bag", + "_embedding_bag_forward_only", + "_empty_affine_quantized", + "_empty_per_channel_affine_quantized", + "_enable_functionalization", + "_euclidean_dist", + "_fake_quantize_learnable_per_channel_affine", + "_fake_quantize_learnable_per_tensor_affine", + "_fake_quantize_per_tensor_affine_cachemask_tensor_qparams", + "_fft_c2c", + "_fft_c2r", + "_fft_r2c", + "_fill_mem_eff_dropout_mask_", + "_flash_attention_forward_no_dropout_inplace", + "_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_clone", + "_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_mm", + "_foreach_mul", + "_foreach_mul_", + "_foreach_neg", + "_foreach_neg_", + "_foreach_norm", + "_foreach_pow", + "_foreach_pow_", + "_foreach_powsum", + "_foreach_reciprocal", + "_foreach_reciprocal_", + "_foreach_round", + "_foreach_round_", + "_foreach_rsqrt", + "_foreach_rsqrt_", + "_foreach_sigmoid", + "_foreach_sigmoid_", + "_foreach_sign", + "_foreach_sign_", + "_foreach_sin", + "_foreach_sin_", + "_foreach_sinh", + "_foreach_sinh_", + "_foreach_sqrt", + "_foreach_sqrt_", + "_foreach_sub", + "_foreach_sub_", + "_foreach_tan", + "_foreach_tan_", + "_foreach_tanh", + "_foreach_tanh_", + "_foreach_trunc", + "_foreach_trunc_", + "_foreach_zero_", + "_from_functional_tensor", + "_functional_assert_async", + "_functional_assert_scalar", + "_functional_sym_constrain_range", + "_functional_sym_constrain_range_for_size", + "_functionalize_apply_view_metas", + "_functionalize_are_all_mutations_hidden_from_autograd", + "_functionalize_are_all_mutations_under_no_grad_or_inference_mode", + "_functionalize_commit_update", + "_functionalize_has_metadata_mutation", + "_functionalize_inductor_storage_resized_counter", + "_functionalize_is_symbolic", + "_functionalize_mark_mutation_hidden_from_autograd", + "_functionalize_mark_storage_changed", + "_functionalize_mutation_counter", + "_functionalize_replace", + "_functionalize_storage_changed_counter", + "_functionalize_sync", + "_functionalize_unsafe_set", + "_functionalize_was_inductor_storage_resized", + "_functionalize_was_storage_changed", + "_fused_adagrad_", + "_fused_adam_", + "_fused_adamw_", + "_fused_dropout", + "_fused_moving_avg_obs_fq_helper", + "_fused_rms_norm", + "_fused_sdp_choice", + "_fused_sgd_", + "_fw_primal_copy", + "_grid_sampler_2d_cpu_fallback", + "_grouped_mm", + "_has_compatible_shallow_copy_type", + "_histogramdd_bin_edges", + "_histogramdd_from_bin_cts", + "_histogramdd_from_bin_tensors", + "_index_put_impl_", + "_indices_copy", + "_int_mm", + "_is_all_true", + "_is_any_true", + "_is_functional_tensor", + "_is_functional_tensor_base", + "_is_zerotensor", + "_lazy_clone", + "_linalg_check_errors", + "_linalg_det", + "_linalg_eigh", + "_linalg_slogdet", + "_linalg_solve_ex", + "_linalg_svd", + "_log_softmax", + "_log_softmax_backward_data", + "_logcumsumexp", + "_lstm_mps", + "_lu_with_info", + "_make_dep_token", + "_make_dual", + "_make_dual_copy", + "_make_per_channel_quantized_tensor", + "_make_per_tensor_quantized_tensor", + "_masked_scale", + "_masked_softmax", + "_mixed_dtypes_linear", + "_mkldnn_reshape", + "_mkldnn_transpose", + "_mkldnn_transpose_", + "_mps_convolution", + "_mps_convolution_transpose", + "_native_batch_norm_legit", + "_native_batch_norm_legit_no_training", + "_native_multi_head_attention", + "_neg_view", + "_neg_view_copy", + "_nested_compute_contiguous_strides_offsets", + "_nested_from_padded", + "_nested_from_padded_and_nested_example", + "_nested_from_padded_tensor", + "_nested_get_jagged_dummy", + "_nested_get_lengths", + "_nested_get_max_seqlen", + "_nested_get_min_seqlen", + "_nested_get_offsets", + "_nested_get_ragged_idx", + "_nested_get_values", + "_nested_get_values_copy", + "_nested_tensor_from_mask", + "_nested_tensor_from_mask_left_aligned", + "_nested_tensor_from_tensor_list", + "_nested_tensor_softmax_with_shape", + "_nested_view_from_buffer", + "_nested_view_from_buffer_copy", + "_nested_view_from_jagged", + "_nested_view_from_jagged_copy", + "_nnpack_available", + "_nnpack_spatial_convolution", + "_pack_padded_sequence", + "_pad_packed_sequence", + "_philox_key_fold_in", + "_philox_key_split", + "_philox_normal_", + "_philox_uniform_", + "_pin_memory", + "_prelu_kernel", + "_print", + "_propagate_xla_data", + "_remove_batch_dim", + "_reshape_alias_copy", + "_reshape_from_tensor", + "_resize_output_", + "_rowwise_prune", + "_safe_softmax", + "_sample_dirichlet", + "_saturate_weight_to_fp16", + "_scaled_dot_product_attention_math", + "_scaled_dot_product_attention_math_for_mps", + "_scaled_dot_product_cudnn_attention", + "_scaled_dot_product_efficient_attention", + "_scaled_dot_product_flash_attention", + "_scaled_dot_product_flash_attention_for_cpu", + "_scaled_grouped_mm", + "_scaled_grouped_mm_v2", + "_scaled_mm", + "_scaled_mm_v2", + "_shape_as_tensor", + "_sobol_engine_draw", + "_sobol_engine_ff_", + "_sobol_engine_initialize_state_", + "_sobol_engine_scramble_", + "_softmax", + "_softmax_backward_data", + "_sparse_broadcast_to", + "_sparse_broadcast_to_copy", + "_sparse_csr_prod", + "_sparse_csr_sum", + "_sparse_log_softmax_backward_data", + "_sparse_semi_structured_addmm", + "_sparse_semi_structured_apply", + "_sparse_semi_structured_apply_dense", + "_sparse_semi_structured_linear", + "_sparse_semi_structured_mm", + "_sparse_semi_structured_tile", + "_sparse_softmax_backward_data", + "_sparse_sparse_matmul", + "_sparse_sum", + "_stack", + "_standard_gamma", + "_standard_gamma_grad", + "_sync", + "_test_autograd_multiple_dispatch", + "_test_autograd_multiple_dispatch_view", + "_test_autograd_multiple_dispatch_view_copy", + "_test_check_tensor", + "_test_functorch_fallback", + "_test_parallel_materialize", + "_test_serialization_subcmul", + "_to_cpu", + "_to_functional_tensor", + "_to_sparse_semi_structured", + "_transform_bias_rescale_qkv", + "_transformer_encoder_layer_fwd", + "_trilinear", + "_triton_multi_head_attention", + "_triton_scaled_dot_attention", + "_unique", + "_unique2", + "_unpack_dual", + "_unsafe_index", + "_unsafe_index_put", + "_unsafe_masked_index", + "_unsafe_masked_index_put_accumulate", + "_use_cudnn_ctc_loss", + "_use_cudnn_rnn_flatten_weight", + "_use_miopen_ctc_loss", + "_validate_compressed_sparse_indices", + "_validate_sparse_bsc_tensor_args", + "_validate_sparse_bsr_tensor_args", + "_validate_sparse_compressed_tensor_args", + "_validate_sparse_coo_tensor_args", + "_validate_sparse_csc_tensor_args", + "_validate_sparse_csr_tensor_args", + "_values_copy", + "_weight_int4pack_mm", + "_weight_int4pack_mm_for_cpu", + "_weight_int4pack_mm_with_scales_and_zeros", + "_weight_int8pack_mm", + "_weight_norm", + "_weight_norm_interface", + "_wrapped_linear_prepack", + "_wrapped_quantized_linear_prepacked", + "abs", + "abs_", + "absolute", + "acos", + "acos_", + "acosh", + "acosh_", + "adaptive_avg_pool1d", + "adaptive_max_pool1d", + "add", + "addbmm", + "addcdiv", + "addcmul", + "addmm", + "addmv", + "addmv_", + "addr", + "adjoint", + "affine_grid_generator", + "alias_copy", + "all", + "allclose", + "alpha_dropout", + "alpha_dropout_", + "amax", + "amin", + "aminmax", + "angle", + "any", + "arange", + "arccos", + "arccos_", + "arccosh", + "arccosh_", + "arcsin", + "arcsin_", + "arcsinh", + "arcsinh_", + "arctan", + "arctan2", + "arctan_", + "arctanh", + "arctanh_", + "argmax", + "argmin", + "argsort", + "argwhere", + "as_strided", + "as_strided_", + "as_strided_copy", + "as_strided_scatter", + "as_tensor", + "asarray", + "asin", + "asin_", + "asinh", + "asinh_", + "atan", + "atan2", + "atan_", + "atanh", + "atanh_", + "avg_pool1d", + "baddbmm", + "bartlett_window", + "batch_norm", + "batch_norm_backward_elemt", + "batch_norm_backward_reduce", + "batch_norm_elemt", + "batch_norm_gather_stats", + "batch_norm_gather_stats_with_counts", + "batch_norm_stats", + "batch_norm_update_stats", + "bernoulli", + "bilinear", + "binary_cross_entropy_with_logits", + "bincount", + "binomial", + "bitwise_and", + "bitwise_left_shift", + "bitwise_not", + "bitwise_or", + "bitwise_right_shift", + "bitwise_xor", + "blackman_window", + "bmm", + "broadcast_to", + "bucketize", + "can_cast", + "cat", + "ccol_indices_copy", + "ceil", + "ceil_", + "celu", + "celu_", + "channel_shuffle", + "cholesky_inverse", + "cholesky_solve", + "choose_qparams_optimized", + "chunk", + "clamp", + "clamp_", + "clamp_max", + "clamp_max_", + "clamp_min", + "clamp_min_", + "clip", + "clip_", + "clone", + "col_indices_copy", + "column_stack", + "combinations", + "complex", + "concat", + "concatenate", + "conj", + "conj_physical", + "conj_physical_", + "constant_pad_nd", + "conv1d", + "conv2d", + "conv3d", + "conv_tbc", + "conv_transpose1d", + "conv_transpose2d", + "conv_transpose3d", + "convolution", + "copysign", + "corrcoef", + "cos", + "cos_", + "cosh", + "cosh_", + "cosine_embedding_loss", + "cosine_similarity", + "count_nonzero", + "cov", + "cross", + "crow_indices_copy", + "ctc_loss", + "cudnn_affine_grid_generator", + "cudnn_batch_norm", + "cudnn_convolution", + "cudnn_convolution_add_relu", + "cudnn_convolution_relu", + "cudnn_convolution_transpose", + "cudnn_grid_sampler", + "cudnn_is_acceptable", + "cummax", + "cummin", + "cumprod", + "cumsum", + "cumulative_trapezoid", + "deg2rad", + "deg2rad_", + "dequantize", + "det", + "detach", + "detach_", + "detach_copy", + "diag", + "diag_embed", + "diagflat", + "diagonal", + "diagonal_copy", + "diagonal_scatter", + "diff", + "digamma", + "dist", + "div", + "divide", + "dot", + "dropout", + "dropout_", + "dsmm", + "dsplit", + "dstack", + "embedding", + "embedding_bag", + "embedding_renorm_", + "empty", + "empty_like", + "empty_permuted", + "empty_quantized", + "empty_strided", + "eq", + "equal", + "erf", + "erf_", + "erfc", + "erfc_", + "erfinv", + "exp", + "exp2", + "exp2_", + "exp_", + "expand_copy", + "expm1", + "expm1_", + "eye", + "fake_quantize_per_channel_affine", + "fake_quantize_per_tensor_affine", + "fbgemm_linear_fp16_weight", + "fbgemm_linear_fp16_weight_fp32_activation", + "fbgemm_linear_int8_weight", + "fbgemm_linear_int8_weight_fp32_activation", + "fbgemm_linear_quantize_weight", + "fbgemm_pack_gemm_matrix_fp16", + "fbgemm_pack_quantized_matrix", + "feature_alpha_dropout", + "feature_alpha_dropout_", + "feature_dropout", + "feature_dropout_", + "fill", + "fill_", + "fix", + "fix_", + "flatten", + "flip", + "fliplr", + "flipud", + "float_power", + "floor", + "floor_", + "floor_divide", + "fmax", + "fmin", + "fmod", + "frac", + "frac_", + "frexp", + "frobenius_norm", + "from_file", + "from_numpy", + "frombuffer", + "full", + "full_like", + "fused_moving_avg_obs_fake_quant", + "gather", + "gcd", + "gcd_", + "ge", + "geqrf", + "ger", + "get_default_dtype", + "get_num_interop_threads", + "get_num_threads", + "gradient", + "greater", + "greater_equal", + "grid_sampler", + "grid_sampler_2d", + "grid_sampler_3d", + "group_norm", + "gru", + "gru_cell", + "gt", + "hamming_window", + "hann_window", + "hardshrink", + "hash_tensor", + "heaviside", + "hinge_embedding_loss", + "histc", + "histogram", + "histogramdd", + "hsmm", + "hsplit", + "hspmm", + "hstack", + "hypot", + "i0", + "i0_", + "igamma", + "igammac", + "imag", + "index_add", + "index_copy", + "index_fill", + "index_put", + "index_put_", + "index_reduce", + "index_select", + "indices_copy", + "init_num_threads", + "inner", + "instance_norm", + "int_repr", + "inverse", + "is_complex", + "is_conj", + "is_distributed", + "is_floating_point", + "is_grad_enabled", + "is_inference", + "is_inference_mode_enabled", + "is_neg", + "is_nonzero", + "is_same_size", + "is_signed", + "is_vulkan_available", + "isclose", + "isfinite", + "isin", + "isinf", + "isnan", + "isneginf", + "isposinf", + "isreal", + "istft", + "kaiser_window", + "kl_div", + "kron", + "kthvalue", + "layer_norm", + "lcm", + "lcm_", + "ldexp", + "ldexp_", + "le", + "lerp", + "less", + "less_equal", + "lgamma", + "linspace", + "log", + "log10", + "log10_", + "log1p", + "log1p_", + "log2", + "log2_", + "log_", + "log_softmax", + "logaddexp", + "logaddexp2", + "logcumsumexp", + "logdet", + "logical_and", + "logical_not", + "logical_or", + "logical_xor", + "logit", + "logit_", + "logspace", + "logsumexp", + "lstm", + "lstm_cell", + "lt", + "lu_solve", + "lu_unpack", + "margin_ranking_loss", + "masked_fill", + "masked_scatter", + "masked_select", + "matmul", + "matrix_exp", + "matrix_power", + "max", + "max_pool1d", + "max_pool1d_with_indices", + "max_pool2d", + "max_pool3d", + "maximum", + "mean", + "median", + "min", + "minimum", + "miopen_batch_norm", + "miopen_convolution", + "miopen_convolution_add_relu", + "miopen_convolution_relu", + "miopen_convolution_transpose", + "miopen_ctc_loss", + "miopen_depthwise_convolution", + "miopen_rnn", + "mkldnn_adaptive_avg_pool2d", + "mkldnn_convolution", + "mkldnn_linear_backward_weights", + "mkldnn_max_pool2d", + "mkldnn_max_pool3d", + "mkldnn_rnn_layer", + "mm", + "mode", + "moveaxis", + "movedim", + "msort", + "mul", + "multinomial", + "multiply", + "mv", + "mvlgamma", + "nan_to_num", + "nan_to_num_", + "nanmean", + "nanmedian", + "nanquantile", + "nansum", + "narrow", + "narrow_copy", + "native_batch_norm", + "native_channel_shuffle", + "native_dropout", + "native_group_norm", + "native_layer_norm", + "native_norm", + "ne", + "neg", + "neg_", + "negative", + "negative_", + "nextafter", + "nonzero", + "nonzero_static", + "norm_except_dim", + "normal", + "not_equal", + "nuclear_norm", + "numel", + "ones", + "ones_like", + "orgqr", + "ormqr", + "outer", + "pairwise_distance", + "pdist", + "permute", + "permute_copy", + "pinverse", + "pixel_shuffle", + "pixel_unshuffle", + "poisson", + "poisson_nll_loss", + "polar", + "polygamma", + "positive", + "pow", + "prelu", + "prod", + "promote_types", + "put", + "q_per_channel_axis", + "q_per_channel_scales", + "q_per_channel_zero_points", + "q_scale", + "q_zero_point", + "quantile", + "quantize_per_channel", + "quantize_per_tensor", + "quantize_per_tensor_dynamic", + "quantized_batch_norm", + "quantized_gru_cell", + "quantized_lstm_cell", + "quantized_max_pool1d", + "quantized_max_pool2d", + "quantized_max_pool3d", + "quantized_rnn_relu_cell", + "quantized_rnn_tanh_cell", + "rad2deg", + "rad2deg_", + "rand", + "rand_like", + "randint", + "randint_like", + "randn", + "randn_like", + "randperm", + "range", + "ravel", + "real", + "reciprocal", + "reciprocal_", + "relu", + "relu_", + "remainder", + "renorm", + "repeat_interleave", + "reshape", + "resize_as_", + "resize_as_sparse_", + "resolve_conj", + "resolve_neg", + "result_type", + "rms_norm", + "rnn_relu", + "rnn_relu_cell", + "rnn_tanh", + "rnn_tanh_cell", + "roll", + "rot90", + "round", + "round_", + "row_indices_copy", + "row_stack", + "rrelu", + "rrelu_", + "rsqrt", + "rsqrt_", + "rsub", + "saddmm", + "scalar_tensor", + "scatter", + "scatter_add", + "scatter_reduce", + "searchsorted", + "segment_reduce", + "select", + "select_copy", + "select_scatter", + "selu", + "selu_", + "set_flush_denormal", + "set_num_interop_threads", + "set_num_threads", + "sgn", + "sigmoid", + "sigmoid_", + "sign", + "signbit", + "sin", + "sin_", + "sinc", + "sinc_", + "sinh", + "sinh_", + "slice_copy", + "slice_inverse", + "slice_scatter", + "slogdet", + "smm", + "softmax", + "sort", + "sparse_bsc_tensor", + "sparse_bsr_tensor", + "sparse_compressed_tensor", + "sparse_coo_tensor", + "sparse_csc_tensor", + "sparse_csr_tensor", + "split_copy", + "split_with_sizes", + "split_with_sizes_copy", + "spmm", + "sqrt", + "sqrt_", + "square", + "square_", + "squeeze", + "squeeze_copy", + "sspaddmm", + "stack", + "std", + "std_mean", + "sub", + "subtract", + "sum", + "svd", + "swapaxes", + "swapdims", + "sym_constrain_range", + "sym_constrain_range_for_size", + "t", + "t_copy", + "take", + "take_along_dim", + "tan", + "tan_", + "tanh", + "tanh_", + "tensor", + "tensor_split", + "threshold", + "threshold_", + "tile", + "topk", + "trace", + "transpose", + "transpose_copy", + "trapezoid", + "trapz", + "triangular_solve", + "tril", + "tril_indices", + "triplet_margin_loss", + "triu", + "triu_indices", + "true_divide", + "trunc", + "trunc_", + "unbind", + "unbind_copy", + "unflatten", + "unfold_copy", + "unique_dim", + "unsafe_chunk", + "unsafe_split", + "unsafe_split_with_sizes", + "unsqueeze", + "unsqueeze_copy", + "values_copy", + "vander", + "var", + "var_mean", + "vdot", + "view_as_complex", + "view_as_complex_copy", + "view_as_real", + "view_as_real_copy", + "view_copy", + "vsplit", + "vstack", + "where", + "xlogy", + "xlogy_", + "zero_", + "zeros", + "zeros_like", +] + +@overload +def __and__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __and__(input: Tensor, other: Number | _complex | PySymType) -> Tensor: ... +@overload +def __lshift__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __lshift__( + input: Tensor, + other: Number | _complex | PySymType, +) -> Tensor: ... +@overload +def __or__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __or__(input: Tensor, other: Number | _complex | PySymType) -> Tensor: ... +@overload +def __rshift__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __rshift__( + input: Tensor, + other: Number | _complex | PySymType, +) -> Tensor: ... +@overload +def __xor__(input: Tensor, other: Tensor) -> Tensor: ... +@overload +def __xor__(input: Tensor, other: Number | _complex | PySymType) -> 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 | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def _add_relu( + input: Tensor, + other: Number | _complex | PySymType, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: ... +@overload +def _add_relu_( + input: Tensor, + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: ... +@overload +def _add_relu_( + input: Tensor, + other: Number | _complex | PySymType, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: ... +def _addmm_activation( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 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], + 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 | PySymType, + 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], + 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], + 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], + 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 _flash_attention_forward_no_dropout_inplace( + out: Tensor | None, + query: Tensor, + key: Tensor, + value: Tensor, + cum_seq_q: Tensor | None, + cum_seq_k: Tensor | None, + max_q: _int | SymInt, + max_k: _int | SymInt, + dropout_p: _float, + is_causal: _bool, + return_debug_mask: _bool, + *, + scale: _float | None = None, + window_size_left: _int | SymInt | None = None, + window_size_right: _int | SymInt | None = None, + seqused_k: Tensor | None = None, + alibi_slopes: Tensor | None = None, + block_table: Tensor | None = None, + num_splits: _int | None = None, +) -> Tensor: ... +def _foobar( + input: Tensor, + arg1: _bool = True, + arg2: _bool = True, + *, + arg3: _bool = True, +) -> Tensor: ... +def _foreach_abs( + self: tuple[Tensor, ...] | list[Tensor], +) -> 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: + 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], +) -> 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: + 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], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], + *, + alpha: Number | _complex | PySymType = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], + *, + alpha: Number | _complex | PySymType = 1, +) -> None: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, +) -> None: ... +@overload +def _foreach_add_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_addcdiv( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcdiv( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcdiv( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + value: Number | _complex | PySymType = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcdiv_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_addcdiv_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Tensor, +) -> None: ... +@overload +def _foreach_addcdiv_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + value: Number | _complex | PySymType = 1, +) -> None: ... +@overload +def _foreach_addcmul( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcmul( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcmul( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + value: Number | _complex | PySymType = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_addcmul_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_addcmul_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + scalars: Tensor, +) -> None: ... +@overload +def _foreach_addcmul_( + self: tuple[Tensor, ...] | list[Tensor], + tensor1: tuple[Tensor, ...] | list[Tensor], + tensor2: tuple[Tensor, ...] | list[Tensor], + value: Number | _complex | PySymType = 1, +) -> None: ... +def _foreach_asin( + self: tuple[Tensor, ...] | list[Tensor], +) -> 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: + 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], +) -> 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: + 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], +) -> 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: + 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], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_max( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_max( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_max_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_clamp_max_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_clamp_max_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +@overload +def _foreach_clamp_min( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_min( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_min( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_clamp_min_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_clamp_min_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_clamp_min_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_clone( + self: tuple[Tensor, ...] | list[Tensor], + *, + memory_format: memory_format | None = None, +) -> tuple[Tensor, ...]: ... +def _foreach_copy_( + self: tuple[Tensor, ...] | list[Tensor], + src: tuple[Tensor, ...] | list[Tensor], + non_blocking: _bool = False, +) -> None: ... +def _foreach_cos( + self: tuple[Tensor, ...] | list[Tensor], +) -> 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: + 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], +) -> 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: + 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], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, +) -> None: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_div_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_erf( + self: tuple[Tensor, ...] | list[Tensor], +) -> 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: + 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], +) -> 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: + 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], +) -> 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: + 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], +) -> 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: + 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], +) -> 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: + 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], +) -> 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: + 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], + tensors1: tuple[Tensor, ...] | list[Tensor], + weight: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_lerp( + self: tuple[Tensor, ...] | list[Tensor], + tensors1: tuple[Tensor, ...] | list[Tensor], + weight: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_lerp( + self: tuple[Tensor, ...] | list[Tensor], + tensors1: tuple[Tensor, ...] | list[Tensor], + weights: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_lerp_( + self: tuple[Tensor, ...] | list[Tensor], + tensors1: tuple[Tensor, ...] | list[Tensor], + weight: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_lerp_( + self: tuple[Tensor, ...] | list[Tensor], + tensors1: tuple[Tensor, ...] | list[Tensor], + weight: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_lerp_( + self: tuple[Tensor, ...] | list[Tensor], + tensors1: tuple[Tensor, ...] | list[Tensor], + weights: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_lgamma( + self: tuple[Tensor, ...] | list[Tensor], +) -> 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: + 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], +) -> 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], +) -> 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: + 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], +) -> 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: + 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], +) -> 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: + 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: + 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], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_maximum_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_maximum_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_maximum_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +@overload +def _foreach_minimum( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_minimum( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_minimum( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_minimum_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_minimum_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_minimum_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_mm( + self: tuple[Tensor, ...] | list[Tensor], + mat2: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor], + other: Tensor, +) -> None: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_mul_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_neg( + self: tuple[Tensor, ...] | list[Tensor], +) -> 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: + 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], + ord: Number | _complex | PySymType = 2, + dtype: _dtype | None = None, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: tuple[Tensor, ...] | list[Tensor], + exponent: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: tuple[Tensor, ...] | list[Tensor], + exponent: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: tuple[Tensor, ...] | list[Tensor], + exponent: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow( + self: Number | _complex | PySymType, + exponent: tuple[Tensor, ...] | list[Tensor], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_pow_( + self: tuple[Tensor, ...] | list[Tensor], + exponent: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_pow_( + self: tuple[Tensor, ...] | list[Tensor], + exponent: Number | _complex | PySymType, +) -> None: ... +@overload +def _foreach_pow_( + self: tuple[Tensor, ...] | list[Tensor], + exponent: tuple[Tensor, ...] | list[Tensor], +) -> None: ... +def _foreach_powsum( + self: tuple[Tensor, ...] | list[Tensor], + ord: Number | _complex | PySymType = 2, + dtype: _dtype | None = None, +) -> tuple[Tensor, ...]: ... +def _foreach_reciprocal( + self: tuple[Tensor, ...] | list[Tensor], +) -> 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: + 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], +) -> 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: + 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], +) -> tuple[Tensor, ...]: ... +def _foreach_rsqrt_(self: tuple[Tensor, ...] | list[Tensor]) -> None: ... +def _foreach_sigmoid( + self: tuple[Tensor, ...] | list[Tensor], +) -> 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: + 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], +) -> tuple[Tensor, ...]: ... +def _foreach_sign_(self: tuple[Tensor, ...] | list[Tensor]) -> None: ... +def _foreach_sin( + self: tuple[Tensor, ...] | list[Tensor], +) -> 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: + 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], +) -> 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: + 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], +) -> 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: + 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], + scalars: Sequence[Number | _complex | PySymType], +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_sub( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], + *, + alpha: Number | _complex | PySymType = 1, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_sub( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> tuple[Tensor, ...]: ... +@overload +def _foreach_sub_( + self: tuple[Tensor, ...] | list[Tensor], + scalars: Sequence[Number | _complex | PySymType], +) -> None: ... +@overload +def _foreach_sub_( + self: tuple[Tensor, ...] | list[Tensor], + other: tuple[Tensor, ...] | list[Tensor], + *, + alpha: Number | _complex | PySymType = 1, +) -> None: ... +@overload +def _foreach_sub_( + self: tuple[Tensor, ...] | list[Tensor], + scalar: Number | _complex | PySymType, +) -> None: ... +def _foreach_tan( + self: tuple[Tensor, ...] | list[Tensor], +) -> 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: + 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], +) -> 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: + 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], +) -> 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: + 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: + 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 | PySymType, + assert_msg: str, + dep_token: Tensor, +) -> Tensor: ... +def _functional_sym_constrain_range( + size: Number | _complex | PySymType, + min: _int | None, + max: _int | None, + dep_token: Tensor, +) -> Tensor: ... +def _functional_sym_constrain_range_for_size( + size: Number | _complex | PySymType, + min: _int | None, + max: _int | None, + dep_token: Tensor, +) -> Tensor: ... +def _functionalize_apply_view_metas(tensor: Tensor, base: Tensor) -> Tensor: ... +def _functionalize_are_all_mutations_hidden_from_autograd( + t: Tensor, +) -> _bool: ... +def _functionalize_are_all_mutations_under_no_grad_or_inference_mode( + t: Tensor, +) -> _bool: ... +def _functionalize_commit_update(t: Tensor) -> None: ... +def _functionalize_has_metadata_mutation(tensor: Tensor) -> _bool: ... +def _functionalize_inductor_storage_resized_counter(t: Tensor) -> _int: ... +def _functionalize_is_symbolic(tensor: Tensor) -> _bool: ... +def _functionalize_mark_mutation_hidden_from_autograd(t: Tensor) -> None: ... +def _functionalize_mark_storage_changed(tensor: Tensor) -> _bool: ... +def _functionalize_mutation_counter(t: Tensor) -> _int: ... +def _functionalize_replace(self_: Tensor, other: Tensor) -> None: ... +def _functionalize_storage_changed_counter(t: Tensor) -> _int: ... +def _functionalize_sync(t: Tensor) -> None: ... +def _functionalize_unsafe_set(dst: Tensor, src: Tensor) -> None: ... +def _functionalize_was_inductor_storage_resized(t: Tensor) -> _bool: ... +def _functionalize_was_storage_changed(tensor: Tensor) -> _bool: ... +@overload +def _fused_adagrad_( + self: tuple[Tensor, ...] | list[Tensor], + grads: tuple[Tensor, ...] | list[Tensor], + state_sums: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + 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], + grads: tuple[Tensor, ...] | list[Tensor], + state_sums: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + 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], + grads: tuple[Tensor, ...] | list[Tensor], + exp_avgs: tuple[Tensor, ...] | list[Tensor], + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + 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], + grads: tuple[Tensor, ...] | list[Tensor], + exp_avgs: tuple[Tensor, ...] | list[Tensor], + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + 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], + grads: tuple[Tensor, ...] | list[Tensor], + exp_avgs: tuple[Tensor, ...] | list[Tensor], + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + 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], + grads: tuple[Tensor, ...] | list[Tensor], + exp_avgs: tuple[Tensor, ...] | list[Tensor], + exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + max_exp_avg_sqs: tuple[Tensor, ...] | list[Tensor], + state_steps: tuple[Tensor, ...] | list[Tensor], + *, + lr: _float, + beta1: _float, + beta2: _float, + weight_decay: _float, + eps: _float, + amsgrad: _bool, + maximize: _bool, + grad_scale: Tensor | None = None, + found_inf: Tensor | None = None, +) -> None: ... +def _fused_dropout( + input: Tensor, + p: _float, + generator: Generator | None = None, +) -> tuple[Tensor, Tensor]: ... +def _fused_moving_avg_obs_fq_helper( + input: Tensor, + observer_on: Tensor, + fake_quant_on: Tensor, + running_min: Tensor, + running_max: Tensor, + scale: Tensor, + zero_point: Tensor, + averaging_const: _float, + quant_min: _int, + quant_max: _int, + ch_axis: _int, + per_row_fake_quant: _bool = False, + symmetric_quant: _bool = False, +) -> torch.return_types._fused_moving_avg_obs_fq_helper: ... +def _fused_rms_norm( + input: Tensor, + normalized_shape: _size, + weight: Tensor | None, + eps: _float | None, +) -> tuple[Tensor, Tensor]: ... +def _fused_sdp_choice( + query: Tensor, + key: Tensor, + value: Tensor, + attn_mask: Tensor | None = None, + dropout_p: _float = 0.0, + is_causal: _bool = False, + *, + scale: _float | None = None, + enable_gqa: _bool = False, +) -> _int: ... +@overload +def _fused_sgd_( + self: tuple[Tensor, ...] | list[Tensor], + grads: tuple[Tensor, ...] | list[Tensor], + momentum_buffer_list: tuple[Tensor, ...] | list[Tensor], + *, + 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], + grads: tuple[Tensor, ...] | list[Tensor], + momentum_buffer_list: tuple[Tensor, ...] | list[Tensor], + *, + 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], + *, + weight: Tensor | None = None, + density: _bool = False, +) -> Tensor: ... +def _index_put_impl_( + input: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | 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], + params: tuple[Tensor, ...] | list[Tensor], + 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], + 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 | PySymType, + total_length: _int, +) -> tuple[Tensor, Tensor]: ... +@overload +def _philox_key_fold_in(key: Tensor, data: Tensor) -> Tensor: ... +@overload +def _philox_key_fold_in(key: Tensor, data: _int) -> Tensor: ... +def _philox_key_split(key: Tensor, num_splits: _int) -> Tensor: ... +def _philox_normal_( + input: Tensor, + key: Tensor, + mean: _float = 0, + std: _float = 1, +) -> Tensor: ... +def _philox_uniform_( + input: Tensor, + key: Tensor, + low: _float = 0, + high: _float = 1, +) -> 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, + enable_gqa: _bool = False, +) -> 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: ... +@overload +def _scaled_dot_product_flash_attention( + query: Tensor, + key: Tensor, + value: Tensor, + q_descale: Tensor | None, + k_descale: Tensor | None, + v_descale: Tensor | None, + 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: ... +@overload +def _scaled_dot_product_flash_attention( + query: Tensor, + key: Tensor, + value: Tensor, + dropout_p: _float = 0.0, + is_causal: _bool = False, + return_debug_mask: _bool = False, + *, + scale: _float | None = None, +) -> torch.return_types._scaled_dot_product_flash_attention: ... +def _scaled_dot_product_flash_attention_for_cpu( + query: Tensor, + key: Tensor, + value: Tensor, + dropout_p: _float = 0.0, + is_causal: _bool = False, + *, + attn_mask: Tensor | None = None, + scale: _float | None = None, +) -> torch.return_types._scaled_dot_product_flash_attention_for_cpu: ... +def _scaled_grouped_mm( + input: Tensor, + mat2: Tensor, + scale_a: Tensor, + scale_b: Tensor, + offs: Tensor | None = None, + bias: Tensor | None = None, + scale_result: Tensor | None = None, + out_dtype: _dtype | None = None, + use_fast_accum: _bool = False, +) -> Tensor: ... +def _scaled_grouped_mm_v2( + input: Tensor, + mat2: Tensor, + scale_a: tuple[Tensor, ...] | list[Tensor], + recipe_a: _size, + swizzle_a: _size, + scale_b: tuple[Tensor, ...] | list[Tensor], + recipe_b: _size, + swizzle_b: _size, + offs: Tensor | None = None, + bias: Tensor | None = None, + out_dtype: _dtype | None = None, + contraction_dim: _size = (), + use_fast_accum: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _scaled_mm( + input: Tensor, + mat2: Tensor, + scale_a: Tensor, + scale_b: Tensor, + bias: Tensor | None = None, + scale_result: Tensor | None = None, + out_dtype: _dtype | None = None, + use_fast_accum: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _scaled_mm_v2( + input: Tensor, + mat2: Tensor, + scale_a: tuple[Tensor, ...] | list[Tensor], + recipe_a: _size, + swizzle_a: _size, + scale_b: tuple[Tensor, ...] | list[Tensor], + recipe_b: _size, + swizzle_b: _size, + bias: Tensor | None, + out_dtype: _dtype | None, + contraction_dim: _size = (), + use_fast_accum: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _shape_as_tensor(input: Tensor) -> Tensor: ... +def _sobol_engine_draw( + quasi: Tensor, + n: _int, + sobolstate: Tensor, + dimension: _int, + num_generated: _int, + dtype: _dtype | None, +) -> tuple[Tensor, Tensor]: ... +def _sobol_engine_ff_( + input: Tensor, + n: _int, + sobolstate: Tensor, + dimension: _int, + num_generated: _int, +) -> Tensor: ... +def _sobol_engine_initialize_state_( + input: Tensor, + dimension: _int, +) -> Tensor: ... +def _sobol_engine_scramble_( + input: Tensor, + ltm: Tensor, + dimension: _int, +) -> Tensor: ... +def _softmax( + input: Tensor, + dim: _int, + half_to_float: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _softmax_backward_data( + grad_output: Tensor, + output: Tensor, + dim: _int, + input_dtype: _dtype, + *, + grad_input: Tensor | None = None, +) -> Tensor: ... +def _sparse_broadcast_to(input: Tensor, size: _size) -> Tensor: ... +def _sparse_broadcast_to_copy( + input: Tensor, + size: _size, + *, + out: Tensor | None = None, +) -> Tensor: ... +def _sparse_csr_prod( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_csr_sum( + input: Tensor, + dim: _int | _size, + keepdim: _bool = False, + *, + dtype: _dtype | None = None, +) -> Tensor: ... +def _sparse_log_softmax_backward_data( + grad_output: Tensor, + output: Tensor, + dim: _int, + input: Tensor, +) -> Tensor: ... +def _sparse_semi_structured_addmm( + input: Tensor, + mat1: Tensor, + mat1_meta: Tensor, + mat2: Tensor, + *, + alpha: Number | _complex | PySymType = 1, + beta: Number | _complex | PySymType = 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], + 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 | PySymType = 1, +) -> Tensor: ... +def _to_cpu( + tensors: tuple[Tensor, ...] | list[Tensor], +) -> 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 | None, ...] | list[Tensor | None] | None, +) -> Tensor: ... +def _unsafe_index_put( + input: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, + values: Tensor, + accumulate: _bool = False, +) -> Tensor: ... +def _unsafe_masked_index( + input: Tensor, + mask: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, + fill: Number | _complex | PySymType, +) -> Tensor: ... +def _unsafe_masked_index_put_accumulate( + input: Tensor, + mask: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | 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: ... +@overload +def _use_miopen_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int, +) -> _bool: ... +@overload +def _use_miopen_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int, +) -> _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: + r""" + abs_(input) -> Tensor + + In-place version of :func:`torch.abs` + """ + +def absolute(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + absolute(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Alias for :func:`torch.abs` + """ + +def acos(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + acos(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the arccosine (in radians) of each element in :attr:`input`. + + .. math:: + \text{out}_{i} = \cos^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.3348, -0.5889, 0.2005, -0.1584]) + >>> torch.acos(a) + tensor([ 1.2294, 2.2004, 1.3690, 1.7298]) + """ + +def acos_(input: Tensor) -> Tensor: + r""" + acos_(input) -> Tensor + + In-place version of :func:`torch.acos` + """ + +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: + r""" + acosh_(input) -> Tensor + + In-place version of :func:`torch.acosh` + """ + +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 | PySymType, + 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 | PySymType, + 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 | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + 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 | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + 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 | PySymType = 1, + alpha: Number | _complex | PySymType = 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 | PySymType, + 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 | PySymType, + 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 | PySymType, + 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 | PySymType, + 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 | PySymType = 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 | PySymType, + 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 | PySymType, + 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 | PySymType = 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 | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + mat1: Tensor, + mat2: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, 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 + + 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]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@overload +def addmm( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + mat1: Tensor, + mat2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, 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 + + 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]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@overload +def addmm( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, 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 + + 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]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@overload +def addmm( + input: Tensor, + mat1: Tensor, + mat2: Tensor, + out_dtype: _dtype, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, 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 + + 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]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@overload +def addmm( + beta: Number | _complex | PySymType, + self: Tensor, + mat1: Tensor, + mat2: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, 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 + + 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]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@overload +def addmm( + beta: Number | _complex | PySymType, + self: Tensor, + mat1: Tensor, + mat2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + addmm(input, mat1, mat2, *, 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 + + 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]]) + + .. function:: addmm(input, mat1, mat2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@overload +def addmv( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + 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 | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + 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 | PySymType = 1, + alpha: Number | _complex | PySymType = 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 | PySymType, + 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 | PySymType, + 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 | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + mat: Tensor, + vec: Tensor, +) -> Tensor: + r""" + addmv_(input, mat, vec, *, beta=1, alpha=1) -> Tensor + + In-place version of :func:`torch.addmv` + """ + +@overload +def addmv_( + input: Tensor, + mat: Tensor, + vec: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: + r""" + addmv_(input, mat, vec, *, beta=1, alpha=1) -> Tensor + + In-place version of :func:`torch.addmv` + """ + +@overload +def addmv_( + beta: Number | _complex | PySymType, + self: Tensor, + mat: Tensor, + vec: Tensor, +) -> Tensor: + r""" + addmv_(input, mat, vec, *, beta=1, alpha=1) -> Tensor + + In-place version of :func:`torch.addmv` + """ + +@overload +def addr( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + 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 | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + 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 | PySymType = 1, + alpha: Number | _complex | PySymType = 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 | PySymType, + 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 | PySymType, + 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) + """ + +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: + r""" + alpha_dropout_(input, p, train) -> Tensor + + In-place version of :func:`torch.alpha_dropout` + """ + +def amax( + input: Tensor, + dim: _int | _size = (), + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + amax(input, dim=None, keepdim=False, *, out=None) -> Tensor + + Returns the maximum value of each slice of the :attr:`input` tensor in the given + dimension(s) :attr:`dim`. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.8177, 1.4878, -0.2491, 0.9130], + [-0.7158, 1.1775, 2.0992, 0.4817], + [-0.0053, 0.0164, -1.3738, -0.0507], + [ 1.9700, 1.1106, -1.0318, -1.0816]]) + >>> torch.amax(a, 1) + tensor([1.4878, 2.0992, 0.0164, 1.9700]) + """ + +def amin( + input: Tensor, + dim: _int | _size = (), + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + amin(input, dim=None, keepdim=False, *, out=None) -> Tensor + + Returns the minimum value of each slice of the :attr:`input` tensor in the given + dimension(s) :attr:`dim`. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.6451, -0.4866, 0.2987, -1.3312], + [-0.5744, 1.2980, 1.8397, -0.2713], + [ 0.9128, 0.9214, -1.7268, -0.2995], + [ 0.9023, 0.4853, 0.9075, -1.6165]]) + >>> torch.amin(a, 1) + tensor([-1.3312, -0.5744, -1.7268, -1.6165]) + """ + +def aminmax( + input: Tensor, + *, + dim: _int | None = None, + keepdim: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.aminmax: + r""" + aminmax(input, *, dim=None, keepdim=False, out=None) -> (Tensor min, Tensor max) + + Computes the minimum and maximum values of the :attr:`input` tensor. + + Args: + input (Tensor): + The input tensor + + Keyword Args: + dim (Optional[int]): + The dimension along which to compute the values. If `None`, + computes the values over the entire :attr:`input` tensor. + Default is `None`. + keepdim (bool): + If `True`, the reduced dimensions will be kept in the output + tensor as dimensions with size 1 for broadcasting, otherwise + they will be removed, as if calling (:func:`torch.squeeze`). + Default is `False`. + out (Optional[Tuple[Tensor, Tensor]]): + Optional tensors on which to write the result. Must have the same + shape and dtype as the expected output. + Default is `None`. + + Returns: + A named tuple `(min, max)` containing the minimum and maximum values. + + Raises: + RuntimeError + If any of the dimensions to compute the values over has size 0. + + .. note:: + NaN values are propagated to the output if at least one value is NaN. + + .. seealso:: + :func:`torch.amin` computes just the minimum value + :func:`torch.amax` computes just the maximum value + + Example:: + + >>> torch.aminmax(torch.tensor([1, -3, 5])) + torch.return_types.aminmax( + min=tensor(-3), + max=tensor(5)) + + >>> # aminmax propagates NaNs + >>> torch.aminmax(torch.tensor([1, -3, 5, torch.nan])) + torch.return_types.aminmax( + min=tensor(nan), + max=tensor(nan)) + + >>> t = torch.arange(10).view(2, 5) + >>> t + tensor([[0, 1, 2, 3, 4], + [5, 6, 7, 8, 9]]) + >>> t.aminmax(dim=0, keepdim=True) + torch.return_types.aminmax( + min=tensor([[0, 1, 2, 3, 4]]), + max=tensor([[5, 6, 7, 8, 9]])) + """ + +def angle(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + angle(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Computes the element-wise angle (in radians) of the given :attr:`input` tensor. + + .. math:: + \text{out}_{i} = angle(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + .. note:: Starting in PyTorch 1.8, angle returns pi for negative real numbers, + zero for non-negative real numbers, and propagates NaNs. Previously + the function would return zero for all real numbers and not propagate + floating-point NaNs. + + Example:: + + >>> torch.angle(torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]))*180/3.14159 + tensor([ 135., 135, -45]) + """ + +@overload +def any(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + any(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Tests if any element in :attr:`input` evaluates to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.any(a) + tensor(True, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.any(a) + tensor(True) + + .. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if any element in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 2) < 0 + >>> a + tensor([[ True, True], + [False, True], + [ True, True], + [False, False]]) + >>> torch.any(a, 1) + tensor([ True, True, True, False]) + >>> torch.any(a, 0) + tensor([True, True]) + """ + +@overload +def any( + input: Tensor, + dim: _size | None = None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + any(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Tests if any element in :attr:`input` evaluates to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.any(a) + tensor(True, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.any(a) + tensor(True) + + .. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if any element in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 2) < 0 + >>> a + tensor([[ True, True], + [False, True], + [ True, True], + [False, False]]) + >>> torch.any(a, 1) + tensor([ True, True, True, False]) + >>> torch.any(a, 0) + tensor([True, True]) + """ + +@overload +def any( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + any(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Tests if any element in :attr:`input` evaluates to `True`. + + .. note:: This function matches the behaviour of NumPy in returning + output of dtype `bool` for all supported dtypes except `uint8`. + For `uint8` the dtype of output is `uint8` itself. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.rand(1, 2).bool() + >>> a + tensor([[False, True]], dtype=torch.bool) + >>> torch.any(a) + tensor(True, dtype=torch.bool) + >>> a = torch.arange(0, 3) + >>> a + tensor([0, 1, 2]) + >>> torch.any(a) + tensor(True) + + .. function:: any(input, dim, keepdim=False, *, out=None) -> Tensor + :noindex: + + For each row of :attr:`input` in the given dimension :attr:`dim`, + returns `True` if any element in the row evaluate to `True` and `False` otherwise. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 2) < 0 + >>> a + tensor([[ True, True], + [False, True], + [ True, True], + [False, False]]) + >>> torch.any(a, 1) + tensor([ True, True, True, False]) + >>> torch.any(a, 0) + tensor([True, True]) + """ + +@overload +def 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 `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.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 `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.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 `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.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 | PySymType, + *, + 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 `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.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 | PySymType, + end: Number | _complex | PySymType, + *, + 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 `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.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 | PySymType, + end: Number | _complex | PySymType, + step: Number | _complex | PySymType = 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 `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.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: + r""" + arccos_(input) -> Tensor + + In-place version of :func:`torch.arccos` + """ + +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: + r""" + arccosh_(input) -> Tensor + + In-place version of :func:`torch.arccosh` + """ + +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: + r""" + arcsin_(input) -> Tensor + + In-place version of :func:`torch.arcsin` + """ + +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: + r""" + arcsinh_(input) -> Tensor + + In-place version of :func:`torch.arcsinh` + """ + +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: + r""" + arctan_(input) -> Tensor + + In-place version of :func:`torch.arctan` + """ + +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: + r""" + arctanh_(input) -> Tensor + + In-place version of :func:`torch.arctanh` + """ + +def argmax( + input: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + argmax(input) -> LongTensor + + Returns the indices of the maximum value of all elements in the :attr:`input` tensor. + + This is the second value returned by :meth:`torch.max`. See its + documentation for the exact semantics of this method. + + .. note:: If there are multiple maximal values then the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 1.3398, 0.2663, -0.2686, 0.2450], + [-0.7401, -0.8805, -0.3402, -1.1936], + [ 0.4907, -1.3948, -1.0691, -0.3132], + [-1.6092, 0.5419, -0.2993, 0.3195]]) + >>> torch.argmax(a) + tensor(0) + + .. function:: argmax(input, dim, keepdim=False) -> LongTensor + :noindex: + + Returns the indices of the maximum values of a tensor across a dimension. + + This is the second value returned by :meth:`torch.max`. See its + documentation for the exact semantics of this method. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, the argmax of the flattened input is returned. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 1.3398, 0.2663, -0.2686, 0.2450], + [-0.7401, -0.8805, -0.3402, -1.1936], + [ 0.4907, -1.3948, -1.0691, -0.3132], + [-1.6092, 0.5419, -0.2993, 0.3195]]) + >>> torch.argmax(a, dim=1) + tensor([ 0, 2, 0, 1]) + """ + +def argmin( + input: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + argmin(input, dim=None, keepdim=False) -> LongTensor + + Returns the indices of the minimum value(s) of the flattened tensor or along a dimension + + This is the second value returned by :meth:`torch.min`. See its + documentation for the exact semantics of this method. + + .. note:: If there are multiple minimal values then the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + If ``None``, the argmin of the flattened input is returned. + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.1139, 0.2254, -0.1381, 0.3687], + [ 1.0100, -1.1975, -0.0102, -0.4732], + [-0.9240, 0.1207, -0.7506, -1.0213], + [ 1.7809, -1.2960, 0.9384, 0.1438]]) + >>> torch.argmin(a) + tensor(13) + >>> torch.argmin(a, dim=1) + tensor([ 2, 1, 3, 1]) + >>> torch.argmin(a, dim=1, keepdim=True) + tensor([[2], + [1], + [3], + [1]]) + """ + +@overload +def argsort( + input: Tensor, + *, + stable: _bool, + dim: _int = -1, + descending: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + argsort(input, dim=-1, descending=False, *, stable=False) -> Tensor + + Returns the indices that sort a tensor along a given dimension in ascending + order by value. + + This is the second value returned by :meth:`torch.sort`. See its documentation + for the exact semantics of this method. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. If ``False``, the relative order of values + which compare equal is not guaranteed. ``True`` is slower. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): controls the relative order of equivalent elements + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0785, 1.5267, -0.8521, 0.4065], + [ 0.1598, 0.0788, -0.0745, -1.2700], + [ 1.2208, 1.0722, -0.7064, 1.2564], + [ 0.0669, -0.2318, -0.8229, -0.9280]]) + + + >>> torch.argsort(a, dim=1) + tensor([[2, 0, 3, 1], + [3, 2, 1, 0], + [2, 1, 0, 3], + [3, 2, 1, 0]]) + """ + +@overload +def argsort( + input: Tensor, + dim: _int = -1, + descending: _bool = False, +) -> Tensor: + r""" + argsort(input, dim=-1, descending=False, *, stable=False) -> Tensor + + Returns the indices that sort a tensor along a given dimension in ascending + order by value. + + This is the second value returned by :meth:`torch.sort`. See its documentation + for the exact semantics of this method. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. If ``False``, the relative order of values + which compare equal is not guaranteed. ``True`` is slower. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): controls the relative order of equivalent elements + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.0785, 1.5267, -0.8521, 0.4065], + [ 0.1598, 0.0788, -0.0745, -1.2700], + [ 1.2208, 1.0722, -0.7064, 1.2564], + [ 0.0669, -0.2318, -0.8229, -0.9280]]) + + + >>> torch.argsort(a, dim=1) + tensor([[2, 0, 3, 1], + [3, 2, 1, 0], + [2, 1, 0, 3], + [3, 2, 1, 0]]) + """ + +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: + r""" + as_strided_(input, size, stride, storage_offset=None) -> Tensor + + In-place version of :func:`torch.as_strided` + """ + +def as_strided_copy( + input: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.as_strided`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def as_strided_scatter( + input: Tensor, + src: Tensor, + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + storage_offset: _int | SymInt | None = None, +) -> Tensor: + r""" + as_strided_scatter(input, src, size, stride, storage_offset=None) -> Tensor + + Embeds the values of the :attr:`src` tensor into :attr:`input` along + the elements corresponding to the result of calling + input.as_strided(size, stride, storage_offset). + + This function returns a tensor with fresh storage; it does not + return a view. + + Args: + input (Tensor): the input tensor. + size (tuple or ints): the shape of the output tensor + stride (tuple or ints): the stride of the output tensor + storage_offset (int, optional): the offset in the underlying storage of the output tensor + + .. note:: + + :attr:`src` must be of the proper size in order to be embedded + into :attr:`input`. Specifically, it should have the same shape as + `torch.as_strided(input, size, stride, storage_offset)` + + Example:: + + >>> a = torch.arange(4).reshape(2, 2) + 1 + >>> a + tensor([[1, 2], + [3, 4]]) + >>> b = torch.zeros(3, 3) + >>> b + tensor([[0., 0., 0.], + [0., 0., 0.], + [0., 0., 0.]]) + >>> torch.as_strided_scatter(b, a, (2, 2), (1, 2)) + tensor([[1., 3., 2.], + [4., 0., 0.], + [0., 0., 0.]]) + """ + +def as_tensor( + data: Any, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, +) -> Tensor: + r""" + as_tensor(data: Any, *, dtype: Optional[dtype] = None, device: Optional[DeviceLikeType]) -> Tensor + + Converts :attr:`data` into a tensor, sharing data and preserving autograd + history if possible. + + If :attr:`data` is already a tensor with the requested dtype and device + then :attr:`data` itself is returned, but if :attr:`data` is a + tensor with a different dtype or device then it's copied as if using + `data.to(dtype=dtype, device=device)`. + + If :attr:`data` is a NumPy array (an ndarray) with the same dtype and device then a + tensor is constructed using :func:`torch.from_numpy`. + + If :attr:`data` is a CuPy array, the returned tensor will be located on the same device as the CuPy array unless + specifically overwritten by :attr:`device` or a default device. The device of the CuPy array is inferred from the + pointer of the array using `cudaPointerGetAttributes` unless :attr:`device` is provided with an explicit device index. + + .. seealso:: + + :func:`torch.tensor` never shares its data and creates a new "leaf tensor" (see :doc:`/notes/autograd`). + + + Args: + data (array_like): Initial data for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, infers data type from :attr:`data`. + device (:class:`torch.device`, optional): the device of the constructed tensor. If None and data is a tensor + then the device of data is used. If None and data is not a tensor then + the result tensor is constructed on the current device. + + + Example:: + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.as_tensor(a) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([-1, 2, 3]) + + >>> a = numpy.array([1, 2, 3]) + >>> t = torch.as_tensor(a, device=torch.device('cuda')) + >>> t + tensor([ 1, 2, 3]) + >>> t[0] = -1 + >>> a + array([1, 2, 3]) + """ + +def asarray( + obj: Any, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + copy: _bool | None = None, + requires_grad: _bool | None = None, +) -> Tensor: + r""" + asarray(obj: Any, *, dtype: Optional[dtype], device: Optional[DeviceLikeType], copy: Optional[bool] = None, requires_grad: Optional[bool] = None) -> 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, have the same requires_grad as :attr:`obj` (defaulting to False), have the + same datatype, 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`` (or ``None``, and + :attr:`obj` was a tensor with requires_grad set), 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: ``None``, which causes requires_grad for the returned tensor to be + inferred from :attr:`obj`. 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, requires_grad=False) + >>> 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=) + >>> # Shares memory with tensor 'b', retaining autograd history + >>> e = torch.asarray(b) + >>> e + tensor([3., 4., 5.], grad_fn=) + + >>> array = numpy.array([1, 2, 3]) + >>> # Shares memory with array 'array' + >>> t1 = torch.asarray(array) + >>> array.__array_interface__['data'][0] == t1.data_ptr() + True + >>> # Copies memory due to dtype mismatch + >>> t2 = torch.asarray(array, dtype=torch.float32) + >>> array.__array_interface__['data'][0] == t2.data_ptr() + False + + >>> scalar = numpy.float64(0.5) + >>> torch.asarray(scalar) + tensor(0.5000, dtype=torch.float64) + """ + +def asin(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + asin(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the arcsine of the elements (in radians) in the :attr:`input` tensor. + + .. math:: + \text{out}_{i} = \sin^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.5962, 1.4985, -0.4396, 1.4525]) + >>> torch.asin(a) + tensor([-0.6387, nan, -0.4552, nan]) + """ + +def asin_(input: Tensor) -> Tensor: + r""" + asin_(input) -> Tensor + + In-place version of :func:`torch.asin` + """ + +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: + r""" + asinh_(input) -> Tensor + + In-place version of :func:`torch.asinh` + """ + +def atan(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + atan(input: Tensor, *, out: Optional[Tensor]) -> Tensor + + Returns a new tensor with the arctangent of the elements (in radians) in the :attr:`input` tensor. + + .. math:: + \text{out}_{i} = \tan^{-1}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.2341, 0.2539, -0.6256, -0.6448]) + >>> torch.atan(a) + tensor([ 0.2299, 0.2487, -0.5591, -0.5727]) + """ + +def atan2( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + atan2(input: Tensor, other: Tensor, *, out: Optional[Tensor]) -> Tensor + + Element-wise arctangent of :math:`\text{input}_{i} / \text{other}_{i}` + with consideration of the quadrant. Returns a new tensor with the signed angles + in radians between vector :math:`(\text{other}_{i}, \text{input}_{i})` + and vector :math:`(1, 0)`. (Note that :math:`\text{other}_{i}`, the second + parameter, is the x-coordinate, while :math:`\text{input}_{i}`, the first + parameter, is the y-coordinate.) + + The shapes of ``input`` and ``other`` must be + :ref:`broadcastable `. + + Args: + input (Tensor): the first input tensor + other (Tensor): the second input tensor + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 0.9041, 0.0196, -0.3108, -2.4423]) + >>> torch.atan2(a, torch.randn(4)) + tensor([ 0.9833, 0.0811, -1.9743, -1.4151]) + """ + +def atan_(input: Tensor) -> Tensor: + r""" + atan_(input) -> Tensor + + In-place version of :func:`torch.atan` + """ + +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: + r""" + atanh_(input) -> Tensor + + In-place version of :func:`torch.atanh` + """ + +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 | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + batch1: Tensor, + batch2: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, 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 + + 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]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@overload +def baddbmm( + beta: Number | _complex | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + batch1: Tensor, + batch2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, 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 + + 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]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@overload +def baddbmm( + input: Tensor, + batch1: Tensor, + batch2: Tensor, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, 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 + + 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]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@overload +def baddbmm( + input: Tensor, + batch1: Tensor, + batch2: Tensor, + out_dtype: _dtype, + *, + beta: Number | _complex | PySymType = 1, + alpha: Number | _complex | PySymType = 1, + out: Tensor | None = None, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, 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 + + 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]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@overload +def baddbmm( + beta: Number | _complex | PySymType, + self: Tensor, + batch1: Tensor, + batch2: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, 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 + + 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]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@overload +def baddbmm( + beta: Number | _complex | PySymType, + self: Tensor, + batch1: Tensor, + batch2: Tensor, + *, + out: Tensor, +) -> Tensor: + r""" + baddbmm(input, batch1, batch2, *, 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 + + 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]) + + .. function:: baddbmm(input, batch1, batch2, out_dtype, *, beta=1, alpha=1, out=None) -> Tensor + :noindex: + + 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): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + 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. + """ + +@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 | PySymType, + 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 | PySymType, + *, + 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 | PySymType, + 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 | PySymType, + *, + 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 | PySymType, + 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 | PySymType, + *, + 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 | PySymType, + 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 | PySymType, + *, + 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 | PySymType, + 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 | PySymType, + *, + 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=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 + + 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]) + + .. function:: bmm(input, mat2, out_dtype, *, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the first batch of matrices to be multiplied + mat2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword Args: + out (Tensor, optional): the output tensor. + """ + +@overload +def bmm( + input: Tensor, + mat2: Tensor, + out_dtype: _dtype, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + bmm(input, mat2, *, 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 + + 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]) + + .. function:: bmm(input, mat2, out_dtype, *, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the first batch of matrices to be multiplied + mat2 (Tensor): the second batch of matrices to be multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword Args: + out (Tensor, optional): the output tensor. + """ + +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 | PySymType, + 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 + """ + +def cat( + tensors: tuple[Tensor, ...] | list[Tensor], + 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]]) + """ + +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: + r""" + ceil_(input) -> Tensor + + In-place version of :func:`torch.ceil` + """ + +def celu( + input: Tensor, + alpha: Number | _complex | PySymType = 1.0, +) -> Tensor: ... +def celu_( + input: Tensor, + alpha: Number | _complex | PySymType = 1.0, +) -> Tensor: ... +def channel_shuffle(input: Tensor, groups: _int | SymInt) -> Tensor: ... +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 | PySymType | None = None, + max: Number | _complex | PySymType | 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: + r""" + clamp_(input, min=None, max=None) -> Tensor + + In-place version of :func:`torch.clamp` + """ + +@overload +def clamp_( + input: Tensor, + min: Number | _complex | PySymType | None = None, + max: Number | _complex | PySymType | None = None, +) -> Tensor: + r""" + clamp_(input, min=None, max=None) -> Tensor + + In-place version of :func:`torch.clamp` + """ + +@overload +def clamp_max( + input: Tensor, + max: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_max( + input: Tensor, + max: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_max_(input: Tensor, max: Tensor) -> Tensor: ... +@overload +def clamp_max_(input: Tensor, max: Number | _complex | PySymType) -> Tensor: ... +@overload +def clamp_min( + input: Tensor, + min: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_min( + input: Tensor, + min: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: ... +@overload +def clamp_min_(input: Tensor, min: Tensor) -> Tensor: ... +@overload +def clamp_min_(input: Tensor, min: Number | _complex | PySymType) -> 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 | PySymType | None = None, + max: Number | _complex | PySymType | 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: + r""" + clip_(input, min=None, max=None) -> Tensor + + In-place version of :func:`torch.clip` + """ + +@overload +def clip_( + input: Tensor, + min: Number | _complex | PySymType | None = None, + max: Number | _complex | PySymType | None = None, +) -> Tensor: + r""" + clip_(input, min=None, max=None) -> Tensor + + In-place version of :func:`torch.clip` + """ + +def clone( + input: Tensor, + *, + memory_format: memory_format | None = None, +) -> Tensor: + r""" + clone(input, *, memory_format=torch.preserve_format) -> Tensor + + Returns a copy of :attr:`input`. + + .. note:: + + This function is differentiable, so gradients will flow back from the + result of this operation to :attr:`input`. To create a tensor without an + autograd relationship to :attr:`input` see :meth:`~Tensor.detach`. + + In addition, when ``torch.preserve_format`` is used: + If the input tensor is dense (i.e., non-overlapping strided), + its memory format (including strides) is retained. + Otherwise (e.g., a non-dense view like a stepped slice), + the output is converted to the dense (contiguous) format. + + Args: + input (Tensor): the input tensor. + + Keyword args: + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned tensor. Default: ``torch.preserve_format``. + """ + +def col_indices_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.col_indices`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def column_stack( + tensors: tuple[Tensor, ...] | list[Tensor], + *, + 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 + """ + +def concat( + tensors: tuple[Tensor, ...] | list[Tensor], + dim: _int = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + concat(tensors, dim=0, *, out=None) -> Tensor + + Alias of :func:`torch.cat`. + """ + +def concatenate( + tensors: tuple[Tensor, ...] | list[Tensor], + dim: _int = 0, + *, + 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: + r""" + conj_physical_(input) -> Tensor + + In-place version of :func:`torch.conj_physical` + """ + +def constant_pad_nd( + input: Tensor, + pad: Sequence[_int | SymInt], + value: Number | _complex | PySymType = 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 | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + copysign(input, other, *, out=None) -> Tensor + + Create a new floating-point tensor with the magnitude of :attr:`input` and the sign of :attr:`other`, elementwise. + + .. math:: + \text{out}_{i} = \begin{cases} + -|\text{input}_{i}| & \text{if } \text{other}_{i} \leq -0.0 \\ + |\text{input}_{i}| & \text{if } \text{other}_{i} \geq 0.0 \\ + \end{cases} + + + Supports :ref:`broadcasting to a common shape `, + and integer and float inputs. + + Args: + input (Tensor): magnitudes. + other (Tensor or Number): contains value(s) whose signbit(s) are + applied to the magnitudes in :attr:`input`. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(5) + >>> a + tensor([-1.2557, -0.0026, -0.5387, 0.4740, -0.9244]) + >>> torch.copysign(a, 1) + tensor([1.2557, 0.0026, 0.5387, 0.4740, 0.9244]) + >>> a = torch.randn(4, 4) + >>> a + tensor([[ 0.7079, 0.2778, -1.0249, 0.5719], + [-0.0059, -0.2600, -0.4475, -1.3948], + [ 0.3667, -0.9567, -2.5757, -0.1751], + [ 0.2046, -0.0742, 0.2998, -0.1054]]) + >>> b = torch.randn(4) + tensor([ 0.2373, 0.3120, 0.3190, -1.1128]) + >>> torch.copysign(a, b) + tensor([[ 0.7079, 0.2778, 1.0249, -0.5719], + [ 0.0059, 0.2600, 0.4475, -1.3948], + [ 0.3667, 0.9567, 2.5757, -0.1751], + [ 0.2046, 0.0742, 0.2998, -0.1054]]) + >>> a = torch.tensor([1.]) + >>> b = torch.tensor([-0.]) + >>> torch.copysign(a, b) + tensor([-1.]) + + .. note:: + copysign handles signed zeros. If the other argument has a negative zero (-0), + the corresponding output value will be negative. + """ + +def corrcoef(input: Tensor) -> Tensor: + r""" + corrcoef(input) -> Tensor + + Estimates the Pearson product-moment correlation coefficient matrix of the variables given by the :attr:`input` matrix, + where rows are the variables and columns are the observations. + + .. note:: + + The correlation coefficient matrix R is computed using the covariance matrix C as given by + :math:`R_{ij} = \frac{ C_{ij} } { \sqrt{ C_{ii} * C_{jj} } }` + + .. note:: + + Due to floating point rounding, the resulting array may not be Hermitian and its diagonal elements may not be 1. + The real and imaginary values are clipped to the interval [-1, 1] in an attempt to improve this situation. + + Args: + input (Tensor): A 2D matrix containing multiple variables and observations, or a + Scalar or 1D vector representing a single variable. + + Returns: + (Tensor) The correlation coefficient matrix of the variables. + + .. seealso:: + + :func:`torch.cov` covariance matrix. + + Example:: + + >>> x = torch.tensor([[0, 1, 2], [2, 1, 0]]) + >>> torch.corrcoef(x) + tensor([[ 1., -1.], + [-1., 1.]]) + >>> x = torch.randn(2, 4) + >>> x + tensor([[-0.2678, -0.0908, -0.3766, 0.2780], + [-0.5812, 0.1535, 0.2387, 0.2350]]) + >>> torch.corrcoef(x) + tensor([[1.0000, 0.3582], + [0.3582, 1.0000]]) + >>> torch.corrcoef(x[0]) + tensor(1.) + """ + +def cos(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + cos(input, *, out=None) -> Tensor + + Returns a new tensor with the cosine of the elements of :attr:`input` given in radians. + + .. math:: + \text{out}_{i} = \cos(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 1.4309, 1.2706, -0.8562, 0.9796]) + >>> torch.cos(a) + tensor([ 0.1395, 0.2957, 0.6553, 0.5574]) + """ + +def cos_(input: Tensor) -> Tensor: + r""" + cos_(input) -> Tensor + + In-place version of :func:`torch.cos` + """ + +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]) + """ + +def cosh_(input: Tensor) -> Tensor: + r""" + cosh_(input) -> Tensor + + In-place version of :func:`torch.cosh` + """ + +def cosine_embedding_loss( + input1: Tensor, + input2: Tensor, + target: Tensor, + margin: _float = 0.0, + reduction: _int = 1, +) -> Tensor: ... +def cosine_similarity( + x1: Tensor, + x2: Tensor, + dim: _int = 1, + eps: _float = 1e-08, +) -> Tensor: ... +@overload +def count_nonzero(input: Tensor, dim: _int | None = None) -> Tensor: + r""" + count_nonzero(input, dim=None) -> Tensor + + Counts the number of non-zero values in the tensor :attr:`input` along the given :attr:`dim`. + If no dim is specified then all non-zeros in the tensor are counted. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): Dim or tuple of dims along which to count non-zeros. + + Example:: + + >>> x = torch.zeros(3,3) + >>> x[torch.randn(3,3) > 0.5] = 1 + >>> x + tensor([[0., 1., 1.], + [0., 0., 0.], + [0., 0., 1.]]) + >>> torch.count_nonzero(x) + tensor(3) + >>> torch.count_nonzero(x, dim=0) + tensor([0, 1, 2]) + """ + +@overload +def count_nonzero(input: Tensor, dim: _size) -> Tensor: + r""" + count_nonzero(input, dim=None) -> Tensor + + Counts the number of non-zero values in the tensor :attr:`input` along the given :attr:`dim`. + If no dim is specified then all non-zeros in the tensor are counted. + + Args: + input (Tensor): the input tensor. + dim (int or tuple of ints, optional): Dim or tuple of dims along which to count non-zeros. + + Example:: + + >>> x = torch.zeros(3,3) + >>> x[torch.randn(3,3) > 0.5] = 1 + >>> x + tensor([[0., 1., 1.], + [0., 0., 0.], + [0., 0., 1.]]) + >>> torch.count_nonzero(x) + tensor(3) + >>> torch.count_nonzero(x, dim=0) + tensor([0, 1, 2]) + """ + +def cov( + input: Tensor, + *, + correction: _int = 1, + fweights: Tensor | None = None, + aweights: Tensor | None = None, +) -> Tensor: + r""" + cov(input, *, correction=1, fweights=None, aweights=None) -> Tensor + + Estimates the covariance matrix of the variables given by the :attr:`input` matrix, where rows are + the variables and columns are the observations. + + A covariance matrix is a square matrix giving the covariance of each pair of variables. The diagonal contains + the variance of each variable (covariance of a variable with itself). By definition, if :attr:`input` represents + a single variable (Scalar or 1D) then its variance is returned. + + The sample covariance of the variables :math:`x` and :math:`y` is given by: + + .. math:: + \text{cov}(x,y) = \frac{\sum^{N}_{i = 1}(x_{i} - \bar{x})(y_{i} - \bar{y})}{\max(0,~N~-~\delta N)} + + where :math:`\bar{x}` and :math:`\bar{y}` are the simple means of the :math:`x` and :math:`y` respectively, and + :math:`\delta N` is the :attr:`correction`. + + If :attr:`fweights` and/or :attr:`aweights` are provided, the weighted covariance + is calculated, which is given by: + + .. math:: + \text{cov}_w(x,y) = \frac{\sum^{N}_{i = 1}w_i(x_{i} - \mu_x^*)(y_{i} - \mu_y^*)} + {\max(0,~\sum^{N}_{i = 1}w_i~-~\frac{\sum^{N}_{i = 1}w_ia_i}{\sum^{N}_{i = 1}w_i}~\delta N)} + + where :math:`w` denotes :attr:`fweights` or :attr:`aweights` (``f`` and ``a`` for brevity) based on whichever is + provided, or :math:`w = f \times a` if both are provided, and + :math:`\mu_x^* = \frac{\sum^{N}_{i = 1}w_ix_{i} }{\sum^{N}_{i = 1}w_i}` is the weighted mean of the variable. If not + provided, ``f`` and/or ``a`` can be seen as a :math:`\mathbb{1}` vector of appropriate size. + + Args: + input (Tensor): A 2D matrix containing multiple variables and observations, or a + Scalar or 1D vector representing a single variable. + + Keyword Args: + correction (int, optional): difference between the sample size and sample degrees of freedom. + Defaults to Bessel's correction, ``correction = 1`` which returns the unbiased estimate, + even if both :attr:`fweights` and :attr:`aweights` are specified. ``correction = 0`` + will return the simple average. Defaults to ``1``. + fweights (tensor, optional): A Scalar or 1D tensor of observation vector frequencies representing the number of + times each observation should be repeated. Its numel must equal the number of columns of :attr:`input`. + Must have integral dtype. Ignored if ``None``. Defaults to ``None``. + aweights (tensor, optional): A Scalar or 1D array of observation vector weights. + These relative weights are typically large for observations considered "important" and smaller for + observations considered less "important". Its numel must equal the number of columns of :attr:`input`. + Must have floating point dtype. Ignored if ``None``. Defaults to ``None``. + + Returns: + (Tensor) The covariance matrix of the variables. + + .. seealso:: + + :func:`torch.corrcoef` normalized covariance matrix. + + Example:: + + >>> x = torch.tensor([[0, 2], [1, 1], [2, 0]]).T + >>> x + tensor([[0, 1, 2], + [2, 1, 0]]) + >>> torch.cov(x) + tensor([[ 1., -1.], + [-1., 1.]]) + >>> torch.cov(x, correction=0) + tensor([[ 0.6667, -0.6667], + [-0.6667, 0.6667]]) + >>> fw = torch.randint(1, 10, (3,)) + >>> fw + tensor([1, 6, 9]) + >>> aw = torch.rand(3) + >>> aw + tensor([0.4282, 0.0255, 0.4144]) + >>> torch.cov(x, fweights=fw, aweights=aw) + tensor([[ 0.4169, -0.4169], + [-0.4169, 0.4169]]) + """ + +def cross( + input: Tensor, + other: Tensor, + dim: _int | None = None, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + cross(input, other, dim=None, *, out=None) -> Tensor + + + Returns the cross product of vectors in dimension :attr:`dim` of :attr:`input` + and :attr:`other`. + + Supports input of float, double, cfloat and cdouble dtypes. Also supports batches + of vectors, for which it computes the product along the dimension :attr:`dim`. + In this case, the output has the same batch dimensions as the inputs. + + .. warning:: + If :attr:`dim` is not given, it defaults to the first dimension found + with the size 3. Note that this might be unexpected. + + This behavior is deprecated and will be changed to match that of :func:`torch.linalg.cross` + in a future release. + + .. seealso:: + :func:`torch.linalg.cross` which has dim=-1 as default. + + + Args: + input (Tensor): the input tensor. + other (Tensor): the second input tensor + dim (int, optional): the dimension to take the cross-product in. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4, 3) + >>> a + tensor([[-0.3956, 1.1455, 1.6895], + [-0.5849, 1.3672, 0.3599], + [-1.1626, 0.7180, -0.0521], + [-0.1339, 0.9902, -2.0225]]) + >>> b = torch.randn(4, 3) + >>> b + tensor([[-0.0257, -1.4725, -1.2251], + [-1.1479, -0.7005, -1.9757], + [-1.3904, 0.3726, -1.1836], + [-0.9688, -0.7153, 0.2159]]) + >>> torch.cross(a, b, dim=1) + tensor([[ 1.0844, -0.5281, 0.6120], + [-2.4490, -1.5687, 1.9792], + [-0.8304, -1.3037, 0.5650], + [-1.2329, 1.9883, 1.0551]]) + >>> torch.cross(a, b) + tensor([[ 1.0844, -0.5281, 0.6120], + [-2.4490, -1.5687, 1.9792], + [-0.8304, -1.3037, 0.5650], + [-1.2329, 1.9883, 1.0551]]) + """ + +def crow_indices_copy( + input: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + Performs the same operation as :func:`torch.crow_indices`, but all output tensors + are freshly created instead of aliasing the input. + """ + +@overload +def ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: _size, + target_lengths: _size, + blank: _int = 0, + reduction: _int = 1, + zero_infinity: _bool = False, +) -> Tensor: ... +@overload +def ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int = 0, + reduction: _int = 1, + zero_infinity: _bool = False, +) -> Tensor: ... +def cudnn_affine_grid_generator( + theta: Tensor, + N: _int, + C: _int, + H: _int, + W: _int, +) -> Tensor: ... +def cudnn_batch_norm( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: _bool, + exponential_average_factor: _float, + epsilon: _float, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: ... +def cudnn_convolution( + input: Tensor, + weight: Tensor, + padding: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + dilation: Sequence[_int | SymInt], + groups: _int | SymInt, + benchmark: _bool, + deterministic: _bool, + allow_tf32: _bool, + *, + out: Tensor | None = None, +) -> Tensor: ... +def cudnn_convolution_add_relu( + input: Tensor, + weight: Tensor, + z: Tensor, + alpha: Number | _complex | PySymType | 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: ... +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])) + """ + +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])) + """ + +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]) + """ + +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 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 | PySymType = 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: + r""" + deg2rad_(input) -> Tensor + + In-place version of :func:`torch.deg2rad` + """ + +@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], +) -> 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: + r""" + detach_(input) -> Tensor + + In-place version of :func:`torch.detach` + """ + +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]]) + """ + +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]]]) + """ + +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 | PySymType = 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 | PySymType, + *, + 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 | PySymType) -> 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], + *, + 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]]) + """ + +def empty_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns an uninitialized tensor with the same size as :attr:`input`. + ``torch.empty_like(input)`` is equivalent to + ``torch.empty(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + When ``torch.preserve_format`` is used: + If the input tensor is dense (i.e., non-overlapping strided), + its memory format (including strides) is retained. + Otherwise (e.g., a non-dense view like a stepped slice), + the output is converted to the dense format. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + Example:: + + >>> a=torch.empty((2,3), dtype=torch.int32, device = 'cuda') + >>> torch.empty_like(a) + tensor([[0, 0, 0], + [0, 0, 0]], device='cuda:0', dtype=torch.int32) + """ + +def empty_permuted( + size: Sequence[_int | SymInt], + physical_layout: _size, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty_permuted(size, physical_layout, *, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Creates an uninitialized, non-overlapping and dense tensor with the + specified :attr:`size`, with :attr:`physical_layout` specifying how the + dimensions are physically laid out in memory (each logical dimension is listed + from outermost to innermost). :attr:`physical_layout` is a generalization + of NCHW/NHWC notation: if each dimension is assigned a number according to + what order they occur in size (N=0, C=1, H=2, W=3), then NCHW is ``(0, 1, 2, 3)`` + while NHWC is ``(0, 2, 3, 1)``. Equivalently, the strides of the output + tensor ``t`` are such that ``t.stride(physical_layout[i]) == contiguous_strides[i]`` + (notably, this function is *not* equivalent to ``torch.empty(size).permute(physical_layout)``). + + Unlike :func:`torch.empty_strided`, this is guaranteed to produce a dense + tensor with no overlaps. If possible, prefer using this function over + :func:`torch.empty_strided` or manual use of :func:`torch.as_strided`. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (tuple of int): the shape of the output tensor + physical_layout (tuple of int): the ordering of dimensions physically in memory + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Examples: + + >>> torch.empty((2, 3, 5, 7)).stride() + (105, 35, 7, 1) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 1, 2, 3)).stride() + (105, 35, 7, 1) + >>> torch.empty((2, 3, 5, 7), memory_format=torch.channels_last).stride() + (105, 1, 21, 3) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 2, 3, 1)).stride() + (105, 1, 21, 3) + >>> torch.empty_permuted((2, 3, 5, 7), (0, 2, 3, 1)).dim_order() + (0, 2, 3, 1) + """ + +def empty_quantized( + size: _size, + qtensor: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: ... +def empty_strided( + size: Sequence[_int | SymInt], + stride: Sequence[_int | SymInt], + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + empty_strided(size, stride, *, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Creates a tensor with the specified :attr:`size` and :attr:`stride` and filled with undefined data. + + .. warning:: + If the constructed tensor is "overlapped" (with multiple indices referring to the same element + in memory) its behavior is undefined. + + .. note:: + If :func:`torch.use_deterministic_algorithms()` and + :attr:`torch.utils.deterministic.fill_uninitialized_memory` are both set to + ``True``, the output tensor is initialized to prevent any possible + nondeterministic behavior from using the data as an input to an operation. + Floating point and complex tensors are filled with NaN, and integer tensors + are filled with the maximum value. + + Args: + size (tuple of int): the shape of the output tensor + stride (tuple of int): the strides of the output tensor + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> a = torch.empty_strided((2, 3), (1, 2)) + >>> a + tensor([[8.9683e-44, 4.4842e-44, 5.1239e+07], + [0.0000e+00, 0.0000e+00, 3.0705e-41]]) + >>> a.stride() + (1, 2) + >>> a.size() + torch.Size([2, 3]) + """ + +@overload +def eq( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + eq(input, other, *, out=None) -> Tensor + + Computes element-wise equality + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is equal to :attr:`other` and False elsewhere + + Example:: + + >>> torch.eq(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[ True, False], + [False, True]]) + """ + +@overload +def eq( + input: Tensor, + other: Number | _complex | PySymType, + *, + 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: + r""" + erf_(input) -> Tensor + + In-place version of :func:`torch.erf` + """ + +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: + r""" + erfc_(input) -> Tensor + + In-place version of :func:`torch.erfc` + """ + +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: + r""" + exp2_(input) -> Tensor + + In-place version of :func:`torch.exp2` + """ + +def exp_(input: Tensor) -> Tensor: + r""" + exp_(input) -> Tensor + + In-place version of :func:`torch.exp` + """ + +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: + r""" + expm1_(input) -> Tensor + + In-place version of :func:`torch.expm1` + """ + +@overload +def eye( + n: _int | SymInt, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + eye(n, m=None, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 2-D tensor with ones on the diagonal and zeros elsewhere. + + Args: + n (int): the number of rows + m (int, optional): the number of columns with default being :attr:`n` + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 2-D tensor with ones on the diagonal and zeros elsewhere + + Example:: + + >>> torch.eye(3) + tensor([[ 1., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 1.]]) + """ + +@overload +def eye( + n: _int | SymInt, + m: _int | SymInt, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + eye(n, m=None, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 2-D tensor with ones on the diagonal and zeros elsewhere. + + Args: + n (int): the number of rows + m (int, optional): the number of columns with default being :attr:`n` + + Keyword arguments: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 2-D tensor with ones on the diagonal and zeros elsewhere + + Example:: + + >>> torch.eye(3) + tensor([[ 1., 0., 0.], + [ 0., 1., 0.], + [ 0., 0., 1.]]) + """ + +def fake_quantize_per_channel_affine( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + axis: _int, + quant_min: _int, + quant_max: _int, +) -> Tensor: + r""" + fake_quantize_per_channel_affine(input, scale, zero_point, axis, quant_min, quant_max) -> Tensor + + Returns a new tensor with the data in :attr:`input` fake quantized per channel using :attr:`scale`, + :attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`, across the channel specified by :attr:`axis`. + + .. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + + Args: + input (Tensor): the input value(s), in ``torch.float32`` + scale (Tensor): quantization scale, per channel in ``torch.float32`` + zero_point (Tensor): quantization zero_point, per channel in ``torch.int32`` or ``torch.half`` or ``torch.float32`` + axis (int32): channel axis + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + + Returns: + Tensor: A newly fake_quantized per channel ``torch.float32`` tensor + + Example:: + + >>> x = torch.randn(2, 2, 2) + >>> x + tensor([[[-0.2525, -0.0466], + [ 0.3491, -0.2168]], + + [[-0.5906, 1.6258], + [ 0.6444, -0.0542]]]) + >>> scales = (torch.randn(2) + 1) * 0.05 + >>> scales + tensor([0.0475, 0.0486]) + >>> zero_points = torch.zeros(2).to(torch.int32) + >>> zero_points + tensor([0, 0]) + >>> torch.fake_quantize_per_channel_affine(x, scales, zero_points, 1, 0, 255) + tensor([[[0.0000, 0.0000], + [0.3405, 0.0000]], + + [[0.0000, 1.6134], + [0.6323, 0.0000]]]) + """ + +@overload +def fake_quantize_per_tensor_affine( + input: Tensor, + scale: _float, + zero_point: _int, + quant_min: _int, + quant_max: _int, +) -> Tensor: + r""" + fake_quantize_per_tensor_affine(input, scale, zero_point, quant_min, quant_max) -> Tensor + + Returns a new tensor with the data in :attr:`input` fake quantized using :attr:`scale`, + :attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`. + + .. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + + Args: + input (Tensor): the input value(s), ``torch.float32`` tensor + scale (double scalar or ``float32`` Tensor): quantization scale + zero_point (int64 scalar or ``int32`` Tensor): quantization zero_point + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + + Returns: + Tensor: A newly fake_quantized ``torch.float32`` tensor + + Example:: + + >>> x = torch.randn(4) + >>> x + tensor([ 0.0552, 0.9730, 0.3973, -1.0780]) + >>> torch.fake_quantize_per_tensor_affine(x, 0.1, 0, 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + >>> torch.fake_quantize_per_tensor_affine(x, torch.tensor(0.1), torch.tensor(0), 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + """ + +@overload +def fake_quantize_per_tensor_affine( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + quant_min: _int, + quant_max: _int, +) -> Tensor: + r""" + fake_quantize_per_tensor_affine(input, scale, zero_point, quant_min, quant_max) -> Tensor + + Returns a new tensor with the data in :attr:`input` fake quantized using :attr:`scale`, + :attr:`zero_point`, :attr:`quant_min` and :attr:`quant_max`. + + .. math:: + \text{output} = ( + min( + \text{quant\_max}, + max( + \text{quant\_min}, + \text{std::nearby\_int}(\text{input} / \text{scale}) + \text{zero\_point} + ) + ) - \text{zero\_point} + ) \times \text{scale} + + Args: + input (Tensor): the input value(s), ``torch.float32`` tensor + scale (double scalar or ``float32`` Tensor): quantization scale + zero_point (int64 scalar or ``int32`` Tensor): quantization zero_point + quant_min (int64): lower bound of the quantized domain + quant_max (int64): upper bound of the quantized domain + + Returns: + Tensor: A newly fake_quantized ``torch.float32`` tensor + + Example:: + + >>> x = torch.randn(4) + >>> x + tensor([ 0.0552, 0.9730, 0.3973, -1.0780]) + >>> torch.fake_quantize_per_tensor_affine(x, 0.1, 0, 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + >>> torch.fake_quantize_per_tensor_affine(x, torch.tensor(0.1), torch.tensor(0), 0, 255) + tensor([0.1000, 1.0000, 0.4000, 0.0000]) + """ + +@overload +def fbgemm_linear_fp16_weight( + input: Tensor, + packed_weight: Tensor, + bias: Tensor, +) -> Tensor: ... +@overload +def fbgemm_linear_fp16_weight( + input: Tensor, + packed_weight: Tensor, + bias: Tensor, + output: Tensor, +) -> Tensor: ... +@overload +def fbgemm_linear_fp16_weight_fp32_activation( + input: Tensor, + packed_weight: Tensor, + bias: Tensor | None, +) -> Tensor: ... +@overload +def fbgemm_linear_fp16_weight_fp32_activation( + input: Tensor, + packed_weight: Tensor, + bias: Tensor | None, + output: Tensor, +) -> Tensor: ... +def fbgemm_linear_int8_weight( + input: Tensor, + weight: Tensor, + packed: Tensor, + col_offsets: Tensor, + weight_scale: Number | _complex | PySymType, + weight_zero_point: Number | _complex | PySymType, + bias: Tensor, +) -> Tensor: ... +def fbgemm_linear_int8_weight_fp32_activation( + input: Tensor, + weight: Tensor, + packed: Tensor, + col_offsets: Tensor, + weight_scale: Number | _complex | PySymType, + weight_zero_point: Number | _complex | PySymType, + 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: + r""" + feature_alpha_dropout_(input, p, train) -> Tensor + + In-place version of :func:`torch.feature_alpha_dropout` + """ + +def feature_dropout(input: Tensor, p: _float, train: _bool) -> Tensor: ... +def feature_dropout_(input: Tensor, p: _float, train: _bool) -> Tensor: + r""" + feature_dropout_(input, p, train) -> Tensor + + In-place version of :func:`torch.feature_dropout` + """ + +@overload +def fill(input: Tensor, value: Tensor) -> Tensor: ... +@overload +def fill(input: Tensor, value: Number | _complex | PySymType) -> Tensor: ... +@overload +def fill_(input: Tensor, value: Tensor) -> Tensor: + r""" + fill_(input, value) -> Tensor + + In-place version of :func:`torch.fill` + """ + +@overload +def fill_(input: Tensor, value: Number | _complex | PySymType) -> Tensor: + r""" + fill_(input, value) -> Tensor + + In-place version of :func:`torch.fill` + """ + +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: + r""" + fix_(input) -> Tensor + + In-place version of :func:`torch.fix` + """ + +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]]) + """ + +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 | PySymType, + 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 | PySymType, + *, + 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: + r""" + floor_(input) -> Tensor + + In-place version of :func:`torch.floor` + """ + +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 | PySymType, + *, + 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: + r""" + frac_(input) -> Tensor + + In-place version of :func:`torch.frac` + """ + +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 | PySymType, + *, + 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]]) + """ + +def full_like( + input: Tensor, + fill_value: Number | _complex | PySymType, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + full_like(input, fill_value, \*, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` filled with :attr:`fill_value`. + ``torch.full_like(input, fill_value)`` is equivalent to + ``torch.full(input.size(), fill_value, dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + fill_value: the number to fill the output tensor with. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + + Example:: + + >>> x = torch.ones(2, 3) + >>> torch.full_like(x, 3.141592) + tensor([[ 3.1416, 3.1416, 3.1416], + [ 3.1416, 3.1416, 3.1416]]) + >>> torch.full_like(x, 7) + tensor([[7., 7., 7.], + [7., 7., 7.]]) + >>> torch.full_like(x, 0.5, dtype=torch.int32) + tensor([[0, 0, 0], + [0, 0, 0]], dtype=torch.int32) + >>> y = torch.randn(3, 4, dtype=torch.float64) + >>> torch.full_like(y, -1.0) + tensor([[-1., -1., -1., -1.], + [-1., -1., -1., -1.], + [-1., -1., -1., -1.]], dtype=torch.float64) + """ + +def fused_moving_avg_obs_fake_quant( + input: Tensor, + observer_on: Tensor, + fake_quant_on: Tensor, + running_min: Tensor, + running_max: Tensor, + scale: Tensor, + zero_point: Tensor, + averaging_const: _float, + quant_min: _int, + quant_max: _int, + ch_axis: _int, + per_row_fake_quant: _bool = False, + symmetric_quant: _bool = False, +) -> Tensor: ... +def gather( + input: Tensor, + dim: _int, + index: Tensor, + *, + sparse_grad: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + gather(input, dim, index, *, sparse_grad=False, out=None) -> Tensor + + Gathers values along an axis specified by `dim`. + + For a 3-D tensor the output is specified by:: + + out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0 + out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1 + out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2 + + :attr:`input` and :attr:`index` must have the same number of dimensions. + It is also required that ``index.size(d) <= input.size(d)`` for all + dimensions ``d != dim``. :attr:`out` will have the same shape as :attr:`index`. + Note that ``input`` and ``index`` do not broadcast against each other. + When :attr:`index` is empty, we always return an empty output with the same shape + without further error checking. + + Args: + input (Tensor): the source tensor + dim (int): the axis along which to index + index (LongTensor): the indices of elements to gather + + Keyword arguments: + sparse_grad (bool, optional): If ``True``, gradient w.r.t. :attr:`input` will be a sparse tensor. + out (Tensor, optional): the destination tensor + + Example:: + + >>> t = torch.tensor([[1, 2], [3, 4]]) + >>> torch.gather(t, 1, torch.tensor([[0, 0], [1, 0]])) + tensor([[ 1, 1], + [ 4, 3]]) + """ + +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: + r""" + gcd_(input, other) -> Tensor + + In-place version of :func:`torch.gcd` + """ + +@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 | PySymType, + *, + 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 | PySymType | None = None, + dim: _int | None = None, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: Sequence[Number | _complex | PySymType], + dim: _int | None = None, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: Sequence[Number | _complex | PySymType], + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: tuple[Tensor, ...] | list[Tensor], + dim: _int | None = None, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: Number | _complex | PySymType, + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + spacing: tuple[Tensor, ...] | list[Tensor], + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def gradient( + input: Tensor, + *, + dim: _size, + edge_order: _int = 1, +) -> tuple[Tensor, ...]: + r""" + gradient(input, *, spacing=1, dim=None, edge_order=1) -> List of Tensors + + Estimates the gradient of a function :math:`g : \mathbb{R}^n \rightarrow \mathbb{R}` in + one or more dimensions using the `second-order accurate central differences method + `_ and + either first or second order estimates at the boundaries. + + The gradient of :math:`g` is estimated using samples. By default, when :attr:`spacing` is not + specified, the samples are entirely described by :attr:`input`, and the mapping of input coordinates + to an output is the same as the tensor's mapping of indices to values. For example, for a three-dimensional + :attr:`input` the function described is :math:`g : \mathbb{R}^3 \rightarrow \mathbb{R}`, and + :math:`g(1, 2, 3)\ == input[1, 2, 3]`. + + When :attr:`spacing` is specified, it modifies the relationship between :attr:`input` and input coordinates. + This is detailed in the "Keyword Arguments" section below. + + The gradient is estimated by estimating each partial derivative of :math:`g` independently. This estimation is + accurate if :math:`g` is in :math:`C^3` (it has at least 3 continuous derivatives), and the estimation can be + improved by providing closer samples. Mathematically, the value at each interior point of a partial derivative + is estimated using `Taylor's theorem with remainder `_. + Letting :math:`x` be an interior point with :math:`x-h_l` and :math:`x+h_r` be points neighboring + it to the left and right respectively, :math:`f(x+h_r)` and :math:`f(x-h_l)` can be estimated using: + + .. math:: + \begin{aligned} + f(x+h_r) = f(x) + h_r f'(x) + {h_r}^2 \frac{f''(x)}{2} + {h_r}^3 \frac{f'''(\xi_1)}{6}, \xi_1 \in (x, x+h_r) \\ + f(x-h_l) = f(x) - h_l f'(x) + {h_l}^2 \frac{f''(x)}{2} - {h_l}^3 \frac{f'''(\xi_2)}{6}, \xi_2 \in (x, x-h_l) \\ + \end{aligned} + + Using the fact that :math:`f \in C^3` and solving the linear system, we derive: + + .. math:: + f'(x) \approx \frac{ {h_l}^2 f(x+h_r) - {h_r}^2 f(x-h_l) + + ({h_r}^2-{h_l}^2 ) f(x) }{ {h_r} {h_l}^2 + {h_r}^2 {h_l} } + + .. note:: + We estimate the gradient of functions in complex domain + :math:`g : \mathbb{C}^n \rightarrow \mathbb{C}` in the same way. + + The value of each partial derivative at the boundary points is computed differently. See edge_order below. + + Args: + input (``Tensor``): the tensor that represents the values of the function + + Keyword args: + spacing (``scalar``, ``list of scalar``, ``list of Tensor``, optional): :attr:`spacing` can be used to modify + how the :attr:`input` tensor's indices relate to sample coordinates. If :attr:`spacing` is a scalar then + the indices are multiplied by the scalar to produce the coordinates. For example, if :attr:`spacing=2` the + indices (1, 2, 3) become coordinates (2, 4, 6). If :attr:`spacing` is a list of scalars then the corresponding + indices are multiplied. For example, if :attr:`spacing=(2, -1, 3)` the indices (1, 2, 3) become coordinates (2, -2, 9). + Finally, if :attr:`spacing` is a list of one-dimensional tensors then each tensor specifies the coordinates for + the corresponding dimension. For example, if the indices are (1, 2, 3) and the tensors are (t0, t1, t2), then + the coordinates are (t0[1], t1[2], t2[3]) + + dim (``int``, ``list of int``, optional): the dimension or dimensions to approximate the gradient over. By default + the partial gradient in every dimension is computed. Note that when :attr:`dim` is specified the elements of + the :attr:`spacing` argument must correspond with the specified dims." + + edge_order (``int``, optional): 1 or 2, for `first-order + `_ or + `second-order `_ + estimation of the boundary ("edge") values, respectively. Note that when :attr:`edge_order` is specified, each + dimension size of :attr:`input` should be at least edge_order+1 + + Examples:: + + >>> # Estimates the gradient of f(x)=x^2 at points [-2, -1, 2, 4] + >>> coordinates = (torch.tensor([-2., -1., 1., 4.]),) + >>> values = torch.tensor([4., 1., 1., 16.], ) + >>> torch.gradient(values, spacing = coordinates) + (tensor([-3., -2., 2., 5.]),) + + >>> # Estimates the gradient of the R^2 -> R function whose samples are + >>> # described by the tensor t. Implicit coordinates are [0, 1] for the outermost + >>> # dimension and [0, 1, 2, 3] for the innermost dimension, and function estimates + >>> # partial derivative for both dimensions. + >>> t = torch.tensor([[1, 2, 4, 8], [10, 20, 40, 80]]) + >>> torch.gradient(t) + (tensor([[ 9., 18., 36., 72.], + [ 9., 18., 36., 72.]]), + tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]])) + + >>> # A scalar value for spacing modifies the relationship between tensor indices + >>> # and input coordinates by multiplying the indices to find the + >>> # coordinates. For example, below the indices of the innermost + >>> # 0, 1, 2, 3 translate to coordinates of [0, 2, 4, 6], and the indices of + >>> # the outermost dimension 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = 2.0) # dim = None (implicitly [0, 1]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.5000, 0.7500, 1.5000, 2.0000], + [ 5.0000, 7.5000, 15.0000, 20.0000]])) + >>> # doubling the spacing between samples halves the estimated partial gradients. + + >>> + >>> # Estimates only the partial derivative for dimension 1 + >>> torch.gradient(t, dim = 1) # spacing = None (implicitly 1.) + (tensor([[ 1.0000, 1.5000, 3.0000, 4.0000], + [10.0000, 15.0000, 30.0000, 40.0000]]),) + + >>> # When spacing is a list of scalars, the relationship between the tensor + >>> # indices and input coordinates changes based on dimension. + >>> # For example, below, the indices of the innermost dimension 0, 1, 2, 3 translate + >>> # to coordinates of [0, 3, 6, 9], and the indices of the outermost dimension + >>> # 0, 1 translate to coordinates of [0, 2]. + >>> torch.gradient(t, spacing = [3., 2.]) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + + >>> # The following example is a replication of the previous one with explicit + >>> # coordinates. + >>> coords = (torch.tensor([0, 2]), torch.tensor([0, 3, 6, 9])) + >>> torch.gradient(t, spacing = coords) + (tensor([[ 4.5000, 9.0000, 18.0000, 36.0000], + [ 4.5000, 9.0000, 18.0000, 36.0000]]), + tensor([[ 0.3333, 0.5000, 1.0000, 1.3333], + [ 3.3333, 5.0000, 10.0000, 13.3333]])) + """ + +@overload +def greater( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + greater(input, other, *, out=None) -> Tensor + + Alias for :func:`torch.gt`. + """ + +@overload +def greater( + input: Tensor, + other: Number | _complex | PySymType, + *, + 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 | PySymType, + *, + 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], + 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], + 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 | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + gt(input, other, *, out=None) -> Tensor + + Computes :math:`\text{input} > \text{other}` element-wise. + + + The second argument can be a number or a tensor whose shape is + :ref:`broadcastable ` with the first argument. + + Args: + input (Tensor): the tensor to compare + other (Tensor or float): the tensor or value to compare + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is greater than :attr:`other` and False elsewhere + + Example:: + + >>> torch.gt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) + tensor([[False, True], [False, False]]) + """ + +@overload +def hamming_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hamming_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hamming_window( + window_length: _int, + periodic: _bool, + alpha: _float, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hamming_window( + window_length: _int, + periodic: _bool, + alpha: _float, + beta: _float, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hamming_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False) -> Tensor + + Hamming window function. + + .. math:: + w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hamming_window(L, periodic=True)`` equal to + ``torch.hamming_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + .. note:: + This is a generalized version of :meth:`torch.hann_window`. + + Arguments: + window_length (int): the size of returned window + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, *, dtype=None, layout=None, device=None, \ + pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic and alpha specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + + .. function:: hamming_window(window_length, periodic, float alpha, float beta, *, dtype=None, layout=None, \ + device=None, pin_memory=False, requires_grad=False) -> Tensor + :noindex: + + Hamming window function with periodic, alpha and beta specified. + + Arguments: + window_length (int): the size of returned window + periodic (bool): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + alpha (float): The coefficient :math:`\alpha` in the equation above + beta (float): The coefficient :math:`\beta` in the equation above + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window. + """ + +@overload +def hann_window( + window_length: _int, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hann_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Hann window function. + + .. math:: + w[n] = \frac{1}{2}\ \left[1 - \cos \left( \frac{2 \pi n}{N - 1} \right)\right] = + \sin^2 \left( \frac{\pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hann_window(L, periodic=True)`` equal to + ``torch.hann_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +@overload +def hann_window( + window_length: _int, + periodic: _bool, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + hann_window(window_length, periodic=True, *, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Hann window function. + + .. math:: + w[n] = \frac{1}{2}\ \left[1 - \cos \left( \frac{2 \pi n}{N - 1} \right)\right] = + \sin^2 \left( \frac{\pi n}{N - 1} \right), + + where :math:`N` is the full window size. + + The input :attr:`window_length` is a positive integer controlling the + returned window size. :attr:`periodic` flag determines whether the returned + window trims off the last duplicate value from the symmetric window and is + ready to be used as a periodic window with functions like + :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in + above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have + ``torch.hann_window(L, periodic=True)`` equal to + ``torch.hann_window(L + 1, periodic=False)[:-1])``. + + .. note:: + If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. + + Arguments: + window_length (int): the size of returned window + periodic (bool, optional): If True, returns a window to be used as periodic + function. If False, return a symmetric window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). Only floating point types are supported. + layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only + ``torch.strided`` (dense layout) is supported. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Returns: + Tensor: A 1-D tensor of size :math:`(\text{window\_length},)` containing the window + """ + +def hardshrink( + input: Tensor, + lambd: Number | _complex | PySymType = 0.5, + *, + out: Tensor | None = None, +) -> Tensor: ... +def hash_tensor( + input: Tensor, + dim: _int | _size = (), + *, + keepdim: _bool = False, + mode: _int = 0, + out: Tensor | None = None, +) -> Tensor: + r""" + hash_tensor(input, *, mode=0) -> Tensor + + Returns a hash of all elements in the :attr:`input` tensor. + + Currently only mode=0 (reduction via xor) is supported. The output will always + be of type ``torch.uint64``. The elements of ``input`` are upcasted to their + 64 bit float / integer equivalent and bitcasted to ``torch.uint64`` before + reduction via xor. + + Args: + input (Tensor): the input tensor. + + Keyword Args: + mode (int) : The hash to use. Default: 0 (xor_reduction) + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 1.1918, -1.1813, 0.3373]]) + >>> torch.hash_tensor(a) + tensor(13822780554648485888, dtype=torch.uint64) + + .. function:: hash_tensor(input, dim, *, keepdim=False, mode=0) -> Tensor + :noindex: + + Returns the hash of each row of the :attr:`input` tensor in the given + dimension :attr:`dim` given by mode. If :attr:`dim` is a list of dimensions, + reduce over all of them. + + + If :attr:`keepdim` is ``True``, the output tensor is of the same size + as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the + output tensor having 1 (or ``len(dim)``) fewer dimension(s). + + + Args: + input (Tensor): the input tensor. + + dim (int or tuple of ints, optional): the dimension or dimensions to reduce. + If ``None``, all dimensions are reduced. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword Args: + mode (int) : The hash to use. Default: 0 (xor_reduction) + + Example:: + + >>> a = torch.randn(2, 4) + >>> a + tensor([[ 0.1317, -0.5554, -1.4724, -1.1391], + [ 0.0778, -0.6070, 0.6375, 0.1798]]) + >>> torch.hash_tensor(a, 1) + tensor([9233691267014066176, 9255993250844508160], dtype=torch.uint64) + """ + +def heaviside( + input: Tensor, + values: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + heaviside(input, values, *, out=None) -> Tensor + + Computes the Heaviside step function for each element in :attr:`input`. + The Heaviside step function is defined as: + + .. math:: + \text{{heaviside}}(input, values) = \begin{cases} + 0, & \text{if input < 0}\\ + values, & \text{if input == 0}\\ + 1, & \text{if input > 0} + \end{cases} + + + Args: + input (Tensor): the input tensor. + values (Tensor): The values to use where :attr:`input` is zero. + + Keyword arguments: + out (Tensor, optional): the output tensor. + + Example:: + + >>> input = torch.tensor([-1.5, 0, 2.0]) + >>> values = torch.tensor([0.5]) + >>> torch.heaviside(input, values) + tensor([0.0000, 0.5000, 1.0000]) + >>> values = torch.tensor([1.2, -2.0, 3.5]) + >>> torch.heaviside(input, values) + tensor([0., -2., 1.]) + """ + +def hinge_embedding_loss( + input: Tensor, + target: Tensor, + margin: _float = 1.0, + reduction: _int = 1, +) -> Tensor: ... +def histc( + input: Tensor, + bins: _int = 100, + min: Number | _complex | PySymType = 0, + max: Number | _complex | PySymType = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + histc(input, bins=100, min=0, max=0, *, out=None) -> Tensor + + Computes the histogram of a tensor. + + The elements are sorted into equal width bins between :attr:`min` and + :attr:`max`. If :attr:`min` and :attr:`max` are both zero, the minimum and + maximum values of the data are used. + + Elements lower than min and higher than max and ``NaN`` elements are ignored. + + Args: + input (Tensor): the input tensor. + bins (int): number of histogram bins + min (Scalar): lower end of the range (inclusive) + max (Scalar): upper end of the range (inclusive) + + Keyword args: + out (Tensor, optional): the output tensor. + + Returns: + Tensor: Histogram represented as a tensor + + Example:: + + >>> torch.histc(torch.tensor([1., 2, 1]), bins=4, min=0, max=3) + tensor([ 0., 2., 1., 0.]) + """ + +@overload +def histogram( + input: Tensor, + bins: Tensor, + *, + weight: Tensor | None = None, + density: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.histogram: + r""" + histogram(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor) + + Computes a histogram of the values in a tensor. + + :attr:`bins` can be an integer or a 1D tensor. + + If :attr:`bins` is an int, it specifies the number of equal-width bins. + By default, the lower and upper range of the bins is determined by the + minimum and maximum elements of the input tensor. The :attr:`range` + argument can be provided to specify a range for the bins. + + If :attr:`bins` is a 1D tensor, it specifies the sequence of bin edges + including the rightmost edge. It should contain at least 2 elements + and its elements should be increasing. + + Args: + input (Tensor): the input tensor. + bins: int or 1D Tensor. If int, defines the number of equal-width bins. If tensor, + defines the sequence of bin edges including the rightmost edge. + + Keyword args: + range (tuple of float): Defines the range of the bins. + weight (Tensor): If provided, weight should have the same shape as input. Each value in + input contributes its associated weight towards its bin's result. + density (bool): If False, the result will contain the count (or total weight) in each bin. + If True, the result is the value of the probability density function over the bins, + normalized such that the integral over the range of the bins is 1. + out (Tensor, optional): the output tensor. (tuple, optional): The result tuple of two output tensors (hist, bin_edges). + + Returns: + hist (Tensor): 1D Tensor containing the values of the histogram. + bin_edges(Tensor): 1D Tensor containing the edges of the histogram bins. + + Example:: + + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.])) + (tensor([ 0., 5., 2., 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.]), density=True) + (tensor([ 0., 0.9524, 0.3810, 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + """ + +@overload +def histogram( + input: Tensor, + bins: _int = 100, + *, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.histogram: + r""" + histogram(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor) + + Computes a histogram of the values in a tensor. + + :attr:`bins` can be an integer or a 1D tensor. + + If :attr:`bins` is an int, it specifies the number of equal-width bins. + By default, the lower and upper range of the bins is determined by the + minimum and maximum elements of the input tensor. The :attr:`range` + argument can be provided to specify a range for the bins. + + If :attr:`bins` is a 1D tensor, it specifies the sequence of bin edges + including the rightmost edge. It should contain at least 2 elements + and its elements should be increasing. + + Args: + input (Tensor): the input tensor. + bins: int or 1D Tensor. If int, defines the number of equal-width bins. If tensor, + defines the sequence of bin edges including the rightmost edge. + + Keyword args: + range (tuple of float): Defines the range of the bins. + weight (Tensor): If provided, weight should have the same shape as input. Each value in + input contributes its associated weight towards its bin's result. + density (bool): If False, the result will contain the count (or total weight) in each bin. + If True, the result is the value of the probability density function over the bins, + normalized such that the integral over the range of the bins is 1. + out (Tensor, optional): the output tensor. (tuple, optional): The result tuple of two output tensors (hist, bin_edges). + + Returns: + hist (Tensor): 1D Tensor containing the values of the histogram. + bin_edges(Tensor): 1D Tensor containing the edges of the histogram bins. + + Example:: + + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.])) + (tensor([ 0., 5., 2., 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + >>> torch.histogram(torch.tensor([1., 2, 1]), bins=4, range=(0., 3.), weight=torch.tensor([1., 2., 4.]), density=True) + (tensor([ 0., 0.9524, 0.3810, 0.]), tensor([0., 0.75, 1.5, 2.25, 3.])) + """ + +@overload +def histogramdd( + input: Tensor, + bins: _int, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> torch.return_types.histogramdd: + r""" + histogramdd(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor[]) + + Computes a multi-dimensional histogram of the values in a tensor. + + Interprets the elements of an input tensor whose innermost dimension has size N + as a collection of N-dimensional points. Maps each of the points into a set of + N-dimensional bins and returns the number of points (or total weight) in each bin. + + :attr:`input` must be a tensor with at least 2 dimensions. + If input has shape (M, N), each of its M rows defines a point in N-dimensional space. + If input has three or more dimensions, all but the last dimension are flattened. + + Each dimension is independently associated with its own strictly increasing sequence + of bin edges. Bin edges may be specified explicitly by passing a sequence of 1D + tensors. Alternatively, bin edges may be constructed automatically by passing a + sequence of integers specifying the number of equal-width bins in each dimension. + + For each N-dimensional point in input: + - Each of its coordinates is binned independently among the bin edges + corresponding to its dimension + - Binning results are combined to identify the N-dimensional bin (if any) + into which the point falls + - If the point falls into a bin, the bin's count (or total weight) is incremented + - Points which do not fall into any bin do not contribute to the output + + :attr:`bins` can be a sequence of N 1D tensors, a sequence of N ints, or a single int. + + If :attr:`bins` is a sequence of N 1D tensors, it explicitly specifies the N sequences + of bin edges. Each 1D tensor should contain a strictly increasing sequence with at + least one element. A sequence of K bin edges defines K-1 bins, explicitly specifying + the left and right edges of all bins. Every bin is inclusive of its left edge. Only + the rightmost bin is inclusive of its right edge. + + If :attr:`bins` is a sequence of N ints, it specifies the number of equal-width bins + in each dimension. By default, the leftmost and rightmost bin edges in each dimension + are determined by the minimum and maximum elements of the input tensor in the + corresponding dimension. The :attr:`range` argument can be provided to manually + specify the leftmost and rightmost bin edges in each dimension. + + If :attr:`bins` is an int, it specifies the number of equal-width bins for all dimensions. + + .. note:: + See also :func:`torch.histogram`, which specifically computes 1D histograms. + While :func:`torch.histogramdd` infers the dimensionality of its bins and + binned values from the shape of :attr:`input`, :func:`torch.histogram` + accepts and flattens :attr:`input` of any shape. + + Args: + input (Tensor): the input tensor. + bins: Tensor[], int[], or int. + If Tensor[], defines the sequences of bin edges. + If int[], defines the number of equal-width bins in each dimension. + If int, defines the number of equal-width bins for all dimensions. + Keyword args: + range (sequence of float): Defines the leftmost and rightmost bin edges + in each dimension. + weight (Tensor): By default, each value in the input has weight 1. If a weight + tensor is passed, each N-dimensional coordinate in input + contributes its associated weight towards its bin's result. + The weight tensor should have the same shape as the :attr:`input` + tensor excluding its innermost dimension N. + density (bool): If False (default), the result will contain the count (or total weight) + in each bin. If True, each count (weight) is divided by the total count + (total weight), then divided by the volume of its associated bin. + Returns: + hist (Tensor): N-dimensional Tensor containing the values of the histogram. + bin_edges(Tensor[]): sequence of N 1D Tensors containing the bin edges. + + Example:: + + >>> torch.histogramdd(torch.tensor([[0., 1.], [1., 0.], [2., 0.], [2., 2.]]), bins=[3, 3], + ... weight=torch.tensor([1., 2., 4., 8.])) + torch.return_types.histogramdd( + hist=tensor([[0., 1., 0.], + [2., 0., 0.], + [4., 0., 8.]]), + bin_edges=(tensor([0.0000, 0.6667, 1.3333, 2.0000]), + tensor([0.0000, 0.6667, 1.3333, 2.0000]))) + + >>> torch.histogramdd(torch.tensor([[0., 0.], [1., 1.], [2., 2.]]), bins=[2, 2], + ... range=[0., 1., 0., 1.], density=True) + torch.return_types.histogramdd( + hist=tensor([[2., 0.], + [0., 2.]]), + bin_edges=(tensor([0.0000, 0.5000, 1.0000]), + tensor([0.0000, 0.5000, 1.0000]))) + """ + +@overload +def histogramdd( + input: Tensor, + bins: _size, + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> torch.return_types.histogramdd: + r""" + histogramdd(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor[]) + + Computes a multi-dimensional histogram of the values in a tensor. + + Interprets the elements of an input tensor whose innermost dimension has size N + as a collection of N-dimensional points. Maps each of the points into a set of + N-dimensional bins and returns the number of points (or total weight) in each bin. + + :attr:`input` must be a tensor with at least 2 dimensions. + If input has shape (M, N), each of its M rows defines a point in N-dimensional space. + If input has three or more dimensions, all but the last dimension are flattened. + + Each dimension is independently associated with its own strictly increasing sequence + of bin edges. Bin edges may be specified explicitly by passing a sequence of 1D + tensors. Alternatively, bin edges may be constructed automatically by passing a + sequence of integers specifying the number of equal-width bins in each dimension. + + For each N-dimensional point in input: + - Each of its coordinates is binned independently among the bin edges + corresponding to its dimension + - Binning results are combined to identify the N-dimensional bin (if any) + into which the point falls + - If the point falls into a bin, the bin's count (or total weight) is incremented + - Points which do not fall into any bin do not contribute to the output + + :attr:`bins` can be a sequence of N 1D tensors, a sequence of N ints, or a single int. + + If :attr:`bins` is a sequence of N 1D tensors, it explicitly specifies the N sequences + of bin edges. Each 1D tensor should contain a strictly increasing sequence with at + least one element. A sequence of K bin edges defines K-1 bins, explicitly specifying + the left and right edges of all bins. Every bin is inclusive of its left edge. Only + the rightmost bin is inclusive of its right edge. + + If :attr:`bins` is a sequence of N ints, it specifies the number of equal-width bins + in each dimension. By default, the leftmost and rightmost bin edges in each dimension + are determined by the minimum and maximum elements of the input tensor in the + corresponding dimension. The :attr:`range` argument can be provided to manually + specify the leftmost and rightmost bin edges in each dimension. + + If :attr:`bins` is an int, it specifies the number of equal-width bins for all dimensions. + + .. note:: + See also :func:`torch.histogram`, which specifically computes 1D histograms. + While :func:`torch.histogramdd` infers the dimensionality of its bins and + binned values from the shape of :attr:`input`, :func:`torch.histogram` + accepts and flattens :attr:`input` of any shape. + + Args: + input (Tensor): the input tensor. + bins: Tensor[], int[], or int. + If Tensor[], defines the sequences of bin edges. + If int[], defines the number of equal-width bins in each dimension. + If int, defines the number of equal-width bins for all dimensions. + Keyword args: + range (sequence of float): Defines the leftmost and rightmost bin edges + in each dimension. + weight (Tensor): By default, each value in the input has weight 1. If a weight + tensor is passed, each N-dimensional coordinate in input + contributes its associated weight towards its bin's result. + The weight tensor should have the same shape as the :attr:`input` + tensor excluding its innermost dimension N. + density (bool): If False (default), the result will contain the count (or total weight) + in each bin. If True, each count (weight) is divided by the total count + (total weight), then divided by the volume of its associated bin. + Returns: + hist (Tensor): N-dimensional Tensor containing the values of the histogram. + bin_edges(Tensor[]): sequence of N 1D Tensors containing the bin edges. + + Example:: + + >>> torch.histogramdd(torch.tensor([[0., 1.], [1., 0.], [2., 0.], [2., 2.]]), bins=[3, 3], + ... weight=torch.tensor([1., 2., 4., 8.])) + torch.return_types.histogramdd( + hist=tensor([[0., 1., 0.], + [2., 0., 0.], + [4., 0., 8.]]), + bin_edges=(tensor([0.0000, 0.6667, 1.3333, 2.0000]), + tensor([0.0000, 0.6667, 1.3333, 2.0000]))) + + >>> torch.histogramdd(torch.tensor([[0., 0.], [1., 1.], [2., 2.]]), bins=[2, 2], + ... range=[0., 1., 0., 1.], density=True) + torch.return_types.histogramdd( + hist=tensor([[2., 0.], + [0., 2.]]), + bin_edges=(tensor([0.0000, 0.5000, 1.0000]), + tensor([0.0000, 0.5000, 1.0000]))) + """ + +@overload +def histogramdd( + input: Tensor, + bins: tuple[Tensor, ...] | list[Tensor], + range: Sequence[_float] | None = None, + weight: Tensor | None = None, + density: _bool = False, +) -> torch.return_types.histogramdd: + r""" + histogramdd(input, bins, *, range=None, weight=None, density=False, out=None) -> (Tensor, Tensor[]) + + Computes a multi-dimensional histogram of the values in a tensor. + + Interprets the elements of an input tensor whose innermost dimension has size N + as a collection of N-dimensional points. Maps each of the points into a set of + N-dimensional bins and returns the number of points (or total weight) in each bin. + + :attr:`input` must be a tensor with at least 2 dimensions. + If input has shape (M, N), each of its M rows defines a point in N-dimensional space. + If input has three or more dimensions, all but the last dimension are flattened. + + Each dimension is independently associated with its own strictly increasing sequence + of bin edges. Bin edges may be specified explicitly by passing a sequence of 1D + tensors. Alternatively, bin edges may be constructed automatically by passing a + sequence of integers specifying the number of equal-width bins in each dimension. + + For each N-dimensional point in input: + - Each of its coordinates is binned independently among the bin edges + corresponding to its dimension + - Binning results are combined to identify the N-dimensional bin (if any) + into which the point falls + - If the point falls into a bin, the bin's count (or total weight) is incremented + - Points which do not fall into any bin do not contribute to the output + + :attr:`bins` can be a sequence of N 1D tensors, a sequence of N ints, or a single int. + + If :attr:`bins` is a sequence of N 1D tensors, it explicitly specifies the N sequences + of bin edges. Each 1D tensor should contain a strictly increasing sequence with at + least one element. A sequence of K bin edges defines K-1 bins, explicitly specifying + the left and right edges of all bins. Every bin is inclusive of its left edge. Only + the rightmost bin is inclusive of its right edge. + + If :attr:`bins` is a sequence of N ints, it specifies the number of equal-width bins + in each dimension. By default, the leftmost and rightmost bin edges in each dimension + are determined by the minimum and maximum elements of the input tensor in the + corresponding dimension. The :attr:`range` argument can be provided to manually + specify the leftmost and rightmost bin edges in each dimension. + + If :attr:`bins` is an int, it specifies the number of equal-width bins for all dimensions. + + .. note:: + See also :func:`torch.histogram`, which specifically computes 1D histograms. + While :func:`torch.histogramdd` infers the dimensionality of its bins and + binned values from the shape of :attr:`input`, :func:`torch.histogram` + accepts and flattens :attr:`input` of any shape. + + Args: + input (Tensor): the input tensor. + bins: Tensor[], int[], or int. + If Tensor[], defines the sequences of bin edges. + If int[], defines the number of equal-width bins in each dimension. + If int, defines the number of equal-width bins for all dimensions. + Keyword args: + range (sequence of float): Defines the leftmost and rightmost bin edges + in each dimension. + weight (Tensor): By default, each value in the input has weight 1. If a weight + tensor is passed, each N-dimensional coordinate in input + contributes its associated weight towards its bin's result. + The weight tensor should have the same shape as the :attr:`input` + tensor excluding its innermost dimension N. + density (bool): If False (default), the result will contain the count (or total weight) + in each bin. If True, each count (weight) is divided by the total count + (total weight), then divided by the volume of its associated bin. + Returns: + hist (Tensor): N-dimensional Tensor containing the values of the histogram. + bin_edges(Tensor[]): sequence of N 1D Tensors containing the bin edges. + + Example:: + + >>> torch.histogramdd(torch.tensor([[0., 1.], [1., 0.], [2., 0.], [2., 2.]]), bins=[3, 3], + ... weight=torch.tensor([1., 2., 4., 8.])) + torch.return_types.histogramdd( + hist=tensor([[0., 1., 0.], + [2., 0., 0.], + [4., 0., 8.]]), + bin_edges=(tensor([0.0000, 0.6667, 1.3333, 2.0000]), + tensor([0.0000, 0.6667, 1.3333, 2.0000]))) + + >>> torch.histogramdd(torch.tensor([[0., 0.], [1., 1.], [2., 2.]]), bins=[2, 2], + ... range=[0., 1., 0., 1.], density=True) + torch.return_types.histogramdd( + hist=tensor([[2., 0.], + [0., 2.]]), + bin_edges=(tensor([0.0000, 0.5000, 1.0000]), + tensor([0.0000, 0.5000, 1.0000]))) + """ + +def hsmm(input: Tensor, mat2: Tensor) -> Tensor: ... +@overload +def hsplit(input: Tensor, sections: _int) -> tuple[Tensor, ...]: + r""" + hsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with one or more dimensions, into multiple tensors + horizontally according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + If :attr:`input` is one dimensional this is equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=0) (the split dimension is + zero), and if :attr:`input` has two or more dimensions it's equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=1) (the split dimension is 1), + except that if :attr:`indices_or_sections` is an integer it must evenly divide + the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.hsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.hsplit(t, 2) + (tensor([[ 0., 1.], + [ 4., 5.], + [ 8., 9.], + [12., 13.]]), + tensor([[ 2., 3.], + [ 6., 7.], + [10., 11.], + [14., 15.]])) + >>> torch.hsplit(t, [3, 6]) + (tensor([[ 0., 1., 2.], + [ 4., 5., 6.], + [ 8., 9., 10.], + [12., 13., 14.]]), + tensor([[ 3.], + [ 7.], + [11.], + [15.]]), + tensor([], size=(4, 0))) + """ + +@overload +def hsplit(input: Tensor, indices: _size) -> tuple[Tensor, ...]: + r""" + hsplit(input, indices_or_sections) -> List of Tensors + + Splits :attr:`input`, a tensor with one or more dimensions, into multiple tensors + horizontally according to :attr:`indices_or_sections`. Each split is a view of + :attr:`input`. + + If :attr:`input` is one dimensional this is equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=0) (the split dimension is + zero), and if :attr:`input` has two or more dimensions it's equivalent to calling + torch.tensor_split(input, indices_or_sections, dim=1) (the split dimension is 1), + except that if :attr:`indices_or_sections` is an integer it must evenly divide + the split dimension or a runtime error will be thrown. + + This function is based on NumPy's :func:`numpy.hsplit`. + + Args: + input (Tensor): tensor to split. + indices_or_sections (int or list or tuple of ints): See argument in :func:`torch.tensor_split`. + + Example:: + + >>> t = torch.arange(16.0).reshape(4,4) + >>> t + tensor([[ 0., 1., 2., 3.], + [ 4., 5., 6., 7.], + [ 8., 9., 10., 11.], + [12., 13., 14., 15.]]) + >>> torch.hsplit(t, 2) + (tensor([[ 0., 1.], + [ 4., 5.], + [ 8., 9.], + [12., 13.]]), + tensor([[ 2., 3.], + [ 6., 7.], + [10., 11.], + [14., 15.]])) + >>> torch.hsplit(t, [3, 6]) + (tensor([[ 0., 1., 2.], + [ 4., 5., 6.], + [ 8., 9., 10.], + [12., 13., 14.]]), + tensor([[ 3.], + [ 7.], + [11.], + [15.]]), + tensor([], size=(4, 0))) + """ + +def hspmm( + mat1: Tensor, + mat2: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + hspmm(mat1, mat2, *, out=None) -> Tensor + + Performs a matrix multiplication of a :ref:`sparse COO matrix + ` :attr:`mat1` and a strided matrix :attr:`mat2`. The + result is a (1 + 1)-dimensional :ref:`hybrid COO matrix + `. + + Args: + mat1 (Tensor): the first sparse matrix to be matrix multiplied + mat2 (Tensor): the second strided matrix to be matrix multiplied + + Keyword args: + out (Tensor, optional): the output tensor. + """ + +def hstack( + tensors: tuple[Tensor, ...] | list[Tensor], + *, + 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: + r""" + i0_(input) -> Tensor + + In-place version of :func:`torch.i0` + """ + +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]) + """ + +def index_add( + input: Tensor, + dim: _int, + index: Tensor, + source: Tensor, + *, + alpha: Number | _complex | PySymType = 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. + """ + +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_copy_` for function description. + """ + +@overload +def index_fill( + input: Tensor, + dim: _int, + index: Tensor, + value: Tensor, +) -> Tensor: ... +@overload +def index_fill( + input: Tensor, + dim: _int, + index: Tensor, + value: Number | _complex | PySymType, +) -> Tensor: ... +def index_put( + input: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | None, + values: Tensor, + accumulate: _bool = False, +) -> Tensor: ... +def index_put_( + input: Tensor, + indices: tuple[Tensor | None, ...] | list[Tensor | None] | 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. + """ + +def index_select( + input: Tensor, + dim: _int, + index: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + index_select(input, dim, index, *, out=None) -> Tensor + + Returns a new tensor which indexes the :attr:`input` tensor along dimension + :attr:`dim` using the entries in :attr:`index`. + + The returned tensor has the same number of dimensions as the original tensor + (:attr:`input`). The :attr:`dim`\ th dimension has the same size as the length + of :attr:`index`; other dimensions have the same size as in the original tensor. + + .. note:: The returned tensor does **not** use the same storage as the original + tensor. If :attr:`out` has a different shape than expected, we + silently change it to the correct shape, reallocating the underlying + storage if necessary. + + Args: + input (Tensor): the input tensor. + dim (int): the dimension in which we index + index (IntTensor or LongTensor): the 1-D tensor containing the indices to index + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(3, 4) + >>> x + tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], + [-0.4664, 0.2647, -0.1228, -1.1068], + [-1.1734, -0.6571, 0.7230, -0.6004]]) + >>> indices = torch.tensor([0, 2]) + >>> torch.index_select(x, 0, indices) + tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], + [-1.1734, -0.6571, 0.7230, -0.6004]]) + >>> torch.index_select(x, 1, indices) + tensor([[ 0.1427, -0.5414], + [-0.4664, -0.1228], + [-1.1734, 0.7230]]) + """ + +def indices_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + Performs the same operation as :func:`torch.indices`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def init_num_threads() -> None: ... +def inner( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + inner(input, other, *, out=None) -> Tensor + + Computes the dot product for 1D tensors. For higher dimensions, sums the product + of elements from :attr:`input` and :attr:`other` along their last dimension. + + .. note:: + + If either :attr:`input` or :attr:`other` is a scalar, the result is equivalent + to `torch.mul(input, other)`. + + If both :attr:`input` and :attr:`other` are non-scalars, the size of their last + dimension must match and the result is equivalent to `torch.tensordot(input, + other, dims=([-1], [-1]))` + + Args: + input (Tensor): First input tensor + other (Tensor): Second input tensor + + Keyword args: + out (Tensor, optional): Optional output tensor to write result into. The output + shape is `input.shape[:-1] + other.shape[:-1]`. + + Example:: + + # Dot product + >>> torch.inner(torch.tensor([1, 2, 3]), torch.tensor([0, 2, 1])) + tensor(7) + + # Multidimensional input tensors + >>> a = torch.randn(2, 3) + >>> a + tensor([[0.8173, 1.0874, 1.1784], + [0.3279, 0.1234, 2.7894]]) + >>> b = torch.randn(2, 4, 3) + >>> b + tensor([[[-0.4682, -0.7159, 0.1506], + [ 0.4034, -0.3657, 1.0387], + [ 0.9892, -0.6684, 0.1774], + [ 0.9482, 1.3261, 0.3917]], + + [[ 0.4537, 0.7493, 1.1724], + [ 0.2291, 0.5749, -0.2267], + [-0.7920, 0.3607, -0.3701], + [ 1.3666, -0.5850, -1.7242]]]) + >>> torch.inner(a, b) + tensor([[[-0.9837, 1.1560, 0.2907, 2.6785], + [ 2.5671, 0.5452, -0.6912, -1.5509]], + + [[ 0.1782, 2.9843, 0.7366, 1.5672], + [ 3.5115, -0.4864, -1.2476, -4.4337]]]) + + # Scalar input + >>> torch.inner(a, torch.tensor(2)) + tensor([[1.6347, 2.1748, 2.3567], + [0.6558, 0.2469, 5.5787]]) + """ + +def instance_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + use_input_stats: _bool, + momentum: _float, + eps: _float, + cudnn_enabled: _bool, +) -> Tensor: ... +def int_repr(input: Tensor) -> Tensor: ... +def inverse(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + inverse(input, *, out=None) -> Tensor + + Alias for :func:`torch.linalg.inv` + """ + +def is_complex(input: Tensor) -> _bool: + r""" + is_complex(input: Tensor) -> bool + + Returns True if the data type of :attr:`input` is a complex data type i.e., + one of ``torch.complex64``, and ``torch.complex128``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.complex64)) + True + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.complex128)) + True + >>> torch.is_complex(torch.tensor([1, 2, 3], dtype=torch.int32)) + False + >>> torch.is_complex(torch.tensor([1.0, 2.0, 3.0], dtype=torch.float16)) + False + """ + +def is_conj(input: Tensor) -> _bool: + r""" + is_conj(input) -> (bool) + + Returns True if the :attr:`input` is a conjugated tensor, i.e. its conjugate bit is set to `True`. + + Args: + input (Tensor): the input tensor. + """ + +def is_distributed(input: Tensor) -> _bool: ... +def is_floating_point(input: Tensor) -> _bool: + r""" + is_floating_point(input: Tensor) -> bool + + Returns True if the data type of :attr:`input` is a floating point data type i.e., + one of ``torch.float64``, ``torch.float32``, ``torch.float16``, and ``torch.bfloat16``. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> torch.is_floating_point(torch.tensor([1.0, 2.0, 3.0])) + True + >>> torch.is_floating_point(torch.tensor([1, 2, 3], dtype=torch.int32)) + False + >>> torch.is_floating_point(torch.tensor([1.0, 2.0, 3.0], dtype=torch.float16)) + True + >>> torch.is_floating_point(torch.tensor([1, 2, 3], dtype=torch.complex64)) + False + """ + +def is_grad_enabled() -> _bool: + r""" + is_grad_enabled() -> (bool) + + Returns True if grad mode is currently enabled. + """ + +def is_inference(input: Tensor) -> _bool: + r""" + is_inference(input) -> (bool) + + Returns True if :attr:`input` is an inference tensor. + + A non-view tensor is an inference tensor if and only if it was + allocated during inference mode. A view tensor is an inference + tensor if and only if the tensor it is a view of is an inference tensor. + + For details on inference mode please see + `Inference Mode `_. + + Args: + input (Tensor): the input tensor. + """ + +def is_inference_mode_enabled() -> _bool: + r""" + is_inference_mode_enabled() -> (bool) + + Returns True if inference mode is currently enabled. + """ + +def is_neg(input: Tensor) -> _bool: ... +def is_nonzero(input: Tensor) -> _bool: + r""" + is_nonzero(input) -> (bool) + + Returns True if the :attr:`input` is a single element tensor which is not equal to zero + after type conversions. + i.e. not equal to ``torch.tensor([0.])`` or ``torch.tensor([0])`` or + ``torch.tensor([False])``. + Throws a ``RuntimeError`` if ``torch.numel() != 1`` (even in case + of sparse tensors). + + Args: + input (Tensor): the input tensor. + + Examples:: + + >>> torch.is_nonzero(torch.tensor([0.])) + False + >>> torch.is_nonzero(torch.tensor([1.5])) + True + >>> torch.is_nonzero(torch.tensor([False])) + False + >>> torch.is_nonzero(torch.tensor([3])) + True + >>> torch.is_nonzero(torch.tensor([1, 3, 5])) + Traceback (most recent call last): + ... + RuntimeError: Boolean value of Tensor with more than one value is ambiguous + >>> torch.is_nonzero(torch.tensor([])) + Traceback (most recent call last): + ... + RuntimeError: Boolean value of Tensor with no values is ambiguous + """ + +def is_same_size(input: Tensor, other: Tensor) -> _bool: ... +def is_signed(input: Tensor) -> _bool: ... +def is_vulkan_available() -> _bool: ... +def isclose( + input: Tensor, + other: Tensor, + rtol: _float = 1e-05, + atol: _float = 1e-08, + equal_nan: _bool = False, +) -> Tensor: + r""" + isclose(input, other, rtol=1e-05, atol=1e-08, equal_nan=False) -> Tensor + + Returns a new tensor with boolean elements representing if each element of + :attr:`input` is "close" to the corresponding element of :attr:`other`. + Closeness is defined as: + + .. math:: + \lvert \text{input}_i - \text{other}_i \rvert \leq \texttt{rtol} \times \lvert \text{other}_i \rvert + \texttt{atol} + + + where :attr:`input` and :attr:`other` are finite. Where :attr:`input` + and/or :attr:`other` are nonfinite they are close if and only if + they are equal, with NaNs being considered equal to each other when + :attr:`equal_nan` is True. + + Args: + input (Tensor): first tensor to compare + other (Tensor): second tensor to compare + rtol (float, optional): relative tolerance. Default: 1e-05 + atol (float, optional): absolute tolerance. Default: 1e-08 + equal_nan (bool, optional): if ``True``, then two ``NaN`` s will be considered equal. Default: ``False`` + + Examples:: + + >>> torch.isclose(torch.tensor((1., 2, 3)), torch.tensor((1 + 1e-10, 3, 4))) + tensor([ True, False, False]) + >>> torch.isclose(torch.tensor((float('inf'), 4)), torch.tensor((float('inf'), 6)), rtol=.5) + tensor([True, True]) + """ + +def isfinite(input: Tensor) -> Tensor: + r""" + isfinite(input) -> Tensor + + Returns a new tensor with boolean elements representing if each element is `finite` or not. + + Real values are finite when they are not NaN, negative infinity, or infinity. + Complex values are finite when both their real and imaginary parts are finite. + + Args: + input (Tensor): the input tensor. + + Returns: + A boolean tensor that is True where :attr:`input` is finite and False elsewhere + + Example:: + + >>> torch.isfinite(torch.tensor([1, float('inf'), 2, float('-inf'), float('nan')])) + tensor([True, False, True, False, False]) + """ + +@overload +def isin( + elements: Tensor, + test_elements: Tensor, + *, + assume_unique: _bool = False, + invert: _bool = False, + out: Tensor | None = None, +) -> Tensor: + r""" + isin(elements, test_elements, *, assume_unique=False, invert=False) -> Tensor + + Tests if each element of :attr:`elements` is in :attr:`test_elements`. Returns + a boolean tensor of the same shape as :attr:`elements` that is True for elements + in :attr:`test_elements` and False otherwise. + + .. note:: + One of :attr:`elements` or :attr:`test_elements` can be a scalar, but not both. + + Args: + elements (Tensor or Scalar): Input elements + test_elements (Tensor or Scalar): Values against which to test for each input element + assume_unique (bool, optional): If True, assumes both :attr:`elements` and + :attr:`test_elements` contain unique elements, which can speed up the + calculation. Default: False + invert (bool, optional): If True, inverts the boolean return tensor, resulting in True + values for elements *not* in :attr:`test_elements`. Default: False + + Returns: + A boolean tensor of the same shape as :attr:`elements` that is True for elements in + :attr:`test_elements` and False otherwise + + Example: + >>> torch.isin(torch.tensor([[1, 2], [3, 4]]), torch.tensor([2, 3])) + tensor([[False, True], + [ True, False]]) + """ + +@overload +def isin( + element: Number | _complex | PySymType, + 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 | PySymType, + *, + 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.]]) + """ + +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]])) + """ + +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: + r""" + lcm_(input, other) -> Tensor + + In-place version of :func:`torch.lcm` + """ + +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: + r""" + ldexp_(input, other) -> Tensor + + In-place version of :func:`torch.ldexp` + """ + +@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 | PySymType, + *, + 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 | PySymType, + *, + 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 | PySymType, + *, + 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 | PySymType, + *, + 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 | PySymType, + 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 | PySymType, + 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 | PySymType, + end: Number | _complex | PySymType, + 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: + r""" + log10_(input) -> Tensor + + In-place version of :func:`torch.log10` + """ + +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: + r""" + log1p_(input) -> Tensor + + In-place version of :func:`torch.log1p` + """ + +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: + r""" + log2_(input) -> Tensor + + In-place version of :func:`torch.log2` + """ + +def log_(input: Tensor) -> Tensor: + r""" + log_(input) -> Tensor + + In-place version of :func:`torch.log` + """ + +def log_softmax( + input: Tensor, + dim: _int, + dtype: _dtype | None = None, + *, + out: Tensor | 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. + """ + +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])) + """ + +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: + r""" + logit_(input, eps=None) -> Tensor + + In-place version of :func:`torch.logit` + """ + +@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 | PySymType, + 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 | PySymType, + 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 | PySymType, + end: Number | _complex | PySymType, + 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]) + """ + +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 lstm( + data: Tensor, + batch_sizes: Tensor, + hx: tuple[Tensor, ...] | list[Tensor], + params: tuple[Tensor, ...] | list[Tensor], + 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], + params: tuple[Tensor, ...] | list[Tensor], + 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], + 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 | PySymType, + *, + 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 | PySymType, +) -> Tensor: ... +def masked_scatter(input: Tensor, mask: Tensor, source: Tensor) -> Tensor: ... +def masked_select( + input: Tensor, + mask: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + masked_select(input, mask, *, out=None) -> Tensor + + Returns a new 1-D tensor which indexes the :attr:`input` tensor according to + the boolean mask :attr:`mask` which is a `BoolTensor`. + + The shapes of the :attr:`mask` tensor and the :attr:`input` tensor don't need + to match, but they must be :ref:`broadcastable `. + + .. note:: The returned tensor does **not** use the same storage + as the original tensor + + Args: + input (Tensor): the input tensor. + mask (BoolTensor): the tensor containing the binary mask to index with + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> x = torch.randn(3, 4) + >>> x + tensor([[ 0.3552, -2.3825, -0.8297, 0.3477], + [-1.2035, 1.2252, 0.5002, 0.6248], + [ 0.1307, -2.0608, 0.1244, 2.0139]]) + >>> mask = x.ge(0.5) + >>> mask + tensor([[False, False, False, False], + [False, True, True, True], + [False, False, False, True]]) + >>> torch.masked_select(x, mask) + tensor([ 1.2252, 0.5002, 0.6248, 2.0139]) + """ + +def matmul( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + matmul(input, other, *, out=None) -> Tensor + + Matrix product of two tensors. + + The behavior depends on the dimensionality of the tensors as follows: + + - If both tensors are 1-dimensional, the dot product (scalar) is returned. + - If both arguments are 2-dimensional, the matrix-matrix product is returned. + - If the first argument is 1-dimensional and the second argument is 2-dimensional, + a 1 is prepended to its dimension for the purpose of the matrix multiply. + After the matrix multiply, the prepended dimension is removed. + - If the first argument is 2-dimensional and the second argument is 1-dimensional, + the matrix-vector product is returned. + - If both arguments are at least 1-dimensional and at least one argument is + N-dimensional (where N > 2), then a batched matrix multiply is returned. If the first + argument is 1-dimensional, a 1 is prepended to its dimension for the purpose of the + batched matrix multiply and removed after. If the second argument is 1-dimensional, a + 1 is appended to its dimension for the purpose of the batched matrix multiply and removed after. + + The first N-2 dimensions of each argument, the batch dimensions, are + :ref:`broadcast ` (and thus must be broadcastable). + The last 2, the matrix dimensions, are handled as in the matrix-matrix product. + + For example, if :attr:`input` is a + :math:`(j \times 1 \times n \times m)` tensor and :attr:`other` is a :math:`(k \times m \times p)` + tensor, the batch dimensions are :math:`(j \times 1)` and :math:`(k)`, + and the matrix dimensions are :math:`(n \times m)` and :math:`(m \times p)`. + :attr:`out` will be a :math:`(j \times k \times n \times p)` tensor. + + This operation has support for arguments with :ref:`sparse layouts`. In particular the + matrix-matrix (both arguments 2-dimensional) supports sparse arguments with the same restrictions + as :func:`torch.mm` + + + .. warning:: + Sparse support is a beta feature and some layout(s)/dtype/device combinations may not be supported, + or may not have autograd support. If you notice missing functionality please + open a feature request. + + This operator supports :ref:`TensorFloat32`. + + On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision` for backward. + + .. note:: + + The 1-dimensional dot product version of this function does not support an :attr:`out` parameter. + + Arguments: + input (Tensor): the first tensor to be multiplied + other (Tensor): the second tensor to be multiplied + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> # vector x vector + >>> tensor1 = torch.randn(3) + >>> tensor2 = torch.randn(3) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([]) + >>> # matrix x vector + >>> tensor1 = torch.randn(3, 4) + >>> tensor2 = torch.randn(4) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([3]) + >>> # batched matrix x broadcasted vector + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(4) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3]) + >>> # batched matrix x batched matrix + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(10, 4, 5) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3, 5]) + >>> # batched matrix x broadcasted matrix + >>> tensor1 = torch.randn(10, 3, 4) + >>> tensor2 = torch.randn(4, 5) + >>> torch.matmul(tensor1, tensor2).size() + torch.Size([10, 3, 5]) + """ + +def matrix_exp(input: Tensor) -> Tensor: + r""" + matrix_exp(A) -> Tensor + + Alias for :func:`torch.linalg.matrix_exp`. + """ + +def matrix_power( + input: Tensor, + n: _int, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + matrix_power(input, n, *, out=None) -> Tensor + + Alias for :func:`torch.linalg.matrix_power` + """ + +@overload +def max(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + max(input, *, out=None) -> Tensor + + Returns the maximum value of all elements in the ``input`` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6763, 0.7445, -2.2369]]) + >>> torch.max(a) + tensor(0.7445) + + .. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each maximum value found + (argmax). + + If ``keepdim`` is ``True``, the output tensors are of the same size + as ``input`` except in the dimension ``dim`` where they are of size 1. + Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than ``input``. + + .. note:: If there are multiple maximal values in a reduced row then + the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (max, max_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-1.2360, -0.2942, -0.1222, 0.8475], + [ 1.1949, -1.1127, -2.2379, -0.6702], + [ 1.5717, -0.9207, 0.1297, -1.8768], + [-0.6172, 1.0036, -0.6060, -0.2432]]) + >>> torch.max(a, 1) + torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1])) + >>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + >>> a.max(dim=1, keepdim=True) + torch.return_types.max( + values=tensor([[2.], [4.]]), + indices=tensor([[1], [1]])) + >>> a.max(dim=1, keepdim=False) + torch.return_types.max( + values=tensor([2., 4.]), + indices=tensor([1, 1])) + + .. function:: max(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.maximum`. + """ + +@overload +def max( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + max(input, *, out=None) -> Tensor + + Returns the maximum value of all elements in the ``input`` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6763, 0.7445, -2.2369]]) + >>> torch.max(a) + tensor(0.7445) + + .. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each maximum value found + (argmax). + + If ``keepdim`` is ``True``, the output tensors are of the same size + as ``input`` except in the dimension ``dim`` where they are of size 1. + Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than ``input``. + + .. note:: If there are multiple maximal values in a reduced row then + the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (max, max_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-1.2360, -0.2942, -0.1222, 0.8475], + [ 1.1949, -1.1127, -2.2379, -0.6702], + [ 1.5717, -0.9207, 0.1297, -1.8768], + [-0.6172, 1.0036, -0.6060, -0.2432]]) + >>> torch.max(a, 1) + torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1])) + >>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + >>> a.max(dim=1, keepdim=True) + torch.return_types.max( + values=tensor([[2.], [4.]]), + indices=tensor([[1], [1]])) + >>> a.max(dim=1, keepdim=False) + torch.return_types.max( + values=tensor([2., 4.]), + indices=tensor([1, 1])) + + .. function:: max(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.maximum`. + """ + +@overload +def max( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.max: + r""" + max(input, *, out=None) -> Tensor + + Returns the maximum value of all elements in the ``input`` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6763, 0.7445, -2.2369]]) + >>> torch.max(a) + tensor(0.7445) + + .. function:: max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the maximum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each maximum value found + (argmax). + + If ``keepdim`` is ``True``, the output tensors are of the same size + as ``input`` except in the dimension ``dim`` where they are of size 1. + Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than ``input``. + + .. note:: If there are multiple maximal values in a reduced row then + the indices of the first maximal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (max, max_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-1.2360, -0.2942, -0.1222, 0.8475], + [ 1.1949, -1.1127, -2.2379, -0.6702], + [ 1.5717, -0.9207, 0.1297, -1.8768], + [-0.6172, 1.0036, -0.6060, -0.2432]]) + >>> torch.max(a, 1) + torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1])) + >>> a = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) + >>> a.max(dim=1, keepdim=True) + torch.return_types.max( + values=tensor([[2.], [4.]]), + indices=tensor([[1], [1]])) + >>> a.max(dim=1, keepdim=False) + torch.return_types.max( + values=tensor([2., 4.]), + indices=tensor([1, 1])) + + .. function:: max(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.maximum`. + """ + +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 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 min(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + min(input, *, out=None) -> Tensor + + Returns the minimum value of all elements in the :attr:`input` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6750, 1.0857, 1.7197]]) + >>> torch.min(a) + tensor(0.6750) + + .. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each minimum value found + (argmin). + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensors having 1 fewer dimension than :attr:`input`. + + .. note:: If there are multiple minimal values in a reduced row then + the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the tuple of two output tensors (min, min_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.6248, 1.1334, -1.1899, -0.2803], + [-1.4644, -0.2635, -0.3651, 0.6134], + [ 0.2457, 0.0384, 1.0128, 0.7015], + [-0.1153, 2.9849, 2.1458, 0.5788]]) + >>> torch.min(a, 1) + torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0])) + + .. function:: min(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.minimum`. + """ + +@overload +def min( + input: Tensor, + other: Tensor, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + min(input, *, out=None) -> Tensor + + Returns the minimum value of all elements in the :attr:`input` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6750, 1.0857, 1.7197]]) + >>> torch.min(a) + tensor(0.6750) + + .. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each minimum value found + (argmin). + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensors having 1 fewer dimension than :attr:`input`. + + .. note:: If there are multiple minimal values in a reduced row then + the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the tuple of two output tensors (min, min_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.6248, 1.1334, -1.1899, -0.2803], + [-1.4644, -0.2635, -0.3651, 0.6134], + [ 0.2457, 0.0384, 1.0128, 0.7015], + [-0.1153, 2.9849, 2.1458, 0.5788]]) + >>> torch.min(a, 1) + torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0])) + + .. function:: min(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.minimum`. + """ + +@overload +def min( + input: Tensor, + dim: _int, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.min: + r""" + min(input, *, out=None) -> Tensor + + Returns the minimum value of all elements in the :attr:`input` tensor. + + .. note:: + The difference between ``max``/``min`` and ``amax``/``amin`` is: + - ``amax``/``amin`` supports reducing on multiple dimensions, + - ``amax``/``amin`` does not return indices. + + Both ``amax``/``amin`` evenly distribute gradients between equal values + when there are multiple input elements with the same minimum or maximum value. + + For ``max``/``min``: + - If reduce over all dimensions(no dim specified), gradients evenly distribute between equally ``max``/``min`` values. + - If reduce over one specified axis, only propagate to the indexed element. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(1, 3) + >>> a + tensor([[ 0.6750, 1.0857, 1.7197]]) + >>> torch.min(a) + tensor(0.6750) + + .. function:: min(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor) + :noindex: + + Returns a namedtuple ``(values, indices)`` where ``values`` is the minimum + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`. And ``indices`` is the index location of each minimum value found + (argmin). + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in + the output tensors having 1 fewer dimension than :attr:`input`. + + .. note:: If there are multiple minimal values in a reduced row then + the indices of the first minimal value are returned. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. If omitted, all dimensions are reduced. Explicit ``None`` is not supported. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the tuple of two output tensors (min, min_indices) + + Example:: + + >>> a = torch.randn(4, 4) + >>> a + tensor([[-0.6248, 1.1334, -1.1899, -0.2803], + [-1.4644, -0.2635, -0.3651, 0.6134], + [ 0.2457, 0.0384, 1.0128, 0.7015], + [-0.1153, 2.9849, 2.1458, 0.5788]]) + >>> torch.min(a, 1) + torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=tensor([2, 0, 1, 0])) + + .. function:: min(input, other, *, out=None) -> Tensor + :noindex: + + See :func:`torch.minimum`. + """ + +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 | PySymType | 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: ... +@overload +def miopen_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 miopen_ctc_loss( + log_probs: Tensor, + targets: Tensor, + input_lengths: Tensor, + target_lengths: Tensor, + blank: _int, + deterministic: _bool, + zero_infinity: _bool, +) -> tuple[Tensor, 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], + 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=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 + + 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]]) + + .. function:: mm(input, mat2, out_dtype, *, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + out (Tensor, optional): the output tensor. + """ + +@overload +def mm( + input: Tensor, + mat2: Tensor, + out_dtype: _dtype, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + mm(input, mat2, *, 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 + + 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]]) + + .. function:: mm(input, mat2, out_dtype, *, out=None) -> Tensor + :noindex: + + Args: + input (Tensor): the first matrix to be matrix multiplied + mat2 (Tensor): the second matrix to be matrix multiplied + out_dtype (dtype): the dtype of the output tensor. + On CUDA and XPU, only ``torch.float32`` is supported given + ``torch.float16``/``torch.bfloat16`` input dtypes. Other backends + (including out-of-tree accelerators) may support additional + input/output dtype combinations. + + Keyword args: + out (Tensor, optional): the output tensor. + """ + +def mode( + input: Tensor, + dim: _int = -1, + keepdim: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.mode: + r""" + mode(input, dim=-1, keepdim=False, *, out=None) -> (Tensor, LongTensor) + + Returns a namedtuple ``(values, indices)`` where ``values`` is the mode + value of each row of the :attr:`input` tensor in the given dimension + :attr:`dim`, i.e. a value which appears most often + in that row, and ``indices`` is the index location of each mode value found. + + By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. + + If :attr:`keepdim` is ``True``, the output tensors are of the same size as + :attr:`input` except in the dimension :attr:`dim` where they are of size 1. + Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting + in the output tensors having 1 fewer dimension than :attr:`input`. + + Args: + input (Tensor): the input tensor. + + dim (int, optional): the dimension to reduce. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword args: + out (tuple, optional): the result tuple of two output tensors (values, indices) + + Example:: + + >>> b = torch.tensor([[0, 0, 0, 2, 0, 0, 2], + ... [0, 3, 0, 0, 2, 0, 1], + ... [2, 2, 2, 0, 0, 0, 3], + ... [2, 2, 3, 0, 1, 1, 0], + ... [1, 1, 0, 0, 2, 0, 2]]) + >>> torch.mode(b, 0) + torch.return_types.mode( + values=tensor([0, 2, 0, 0, 0, 0, 2]), + indices=tensor([1, 3, 4, 4, 2, 4, 4])) + """ + +@overload +def 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 | PySymType) -> 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: + r""" + nan_to_num_(input, nan=0.0, posinf=None, neginf=None) -> Tensor + + In-place version of :func:`torch.nan_to_num` + """ + +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 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 | PySymType | None, + dim: _int | _size, + keepdim: _bool, + dtype: _dtype | None, +) -> Tensor: ... +@overload +def native_norm( + input: Tensor, + p: Number | _complex | PySymType = 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 | PySymType, + *, + 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: + r""" + neg_(input) -> Tensor + + In-place version of :func:`torch.neg` + """ + +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: + r""" + negative_(input) -> Tensor + + In-place version of :func:`torch.negative` + """ + +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: + 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. + + Keyword args: + size (int): the size of non-zero elements expected to be included in the out + tensor. Pad the out tensor with `fill_value` if the `size` is larger + than total number of non-zero elements, truncate out tensor if `size` + is smaller. The size must be a non-negative integer. + fill_value (int, optional): the value to fill the output tensor with when `size` is larger + than the total number of non-zero elements. Default is `-1` to represent + invalid index. + + Example:: + + # Example 1: Padding + >>> input_tensor = torch.tensor([[1, 0], [3, 2]]) + >>> static_size = 4 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([[ 0, 0], + [ 1, 0], + [ 1, 1], + [ -1, -1]], dtype=torch.int64) + + # Example 2: Truncating + >>> input_tensor = torch.tensor([[1, 0], [3, 2]]) + >>> static_size = 2 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([[ 0, 0], + [ 1, 0]], dtype=torch.int64) + + # Example 3: 0 size + >>> input_tensor = torch.tensor([10]) + >>> static_size = 0 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([], size=(0, 1), dtype=torch.int64) + + # Example 4: 0 rank input + >>> input_tensor = torch.tensor(10) + >>> static_size = 2 + >>> t = torch.nonzero_static(input_tensor, size=static_size) + tensor([], size=(2, 0), dtype=torch.int64) + """ + +def 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 (float or Tensor): per-element mean(s). Only floating point types are supported. + std (float or Tensor): per-element standard deviation(s). Only floating point types are supported. + + 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, *, generator=None, out=None, dtype=None, \ + layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> 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: + 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.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 (float or Tensor): per-element mean(s). Only floating point types are supported. + std (float or Tensor): per-element standard deviation(s). Only floating point types are supported. + + 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, *, generator=None, out=None, dtype=None, \ + layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> 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: + 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.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 (float or Tensor): per-element mean(s). Only floating point types are supported. + std (float or Tensor): per-element standard deviation(s). Only floating point types are supported. + + 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, *, generator=None, out=None, dtype=None, \ + layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> 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: + 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.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 (float or Tensor): per-element mean(s). Only floating point types are supported. + std (float or Tensor): per-element standard deviation(s). Only floating point types are supported. + + 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, *, generator=None, out=None, dtype=None, \ + layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> 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: + 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.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 | PySymType, + *, + 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.]) + """ + +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 (torch.Size, tuple of int or list 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 | PySymType, + 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 | PySymType, + *, + 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]) + """ + +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: ... +@overload +def quantile( + input: Tensor, + q: Tensor, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + out: Tensor | None = None, +) -> Tensor: + r""" + quantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + + Computes the q-th quantiles of each row of the :attr:`input` tensor along the dimension :attr:`dim`. + + To compute the quantile, we map q in [0, 1] to the range of indices [0, n] to find the location + of the quantile in the sorted input. If the quantile lies between two data points ``a < b`` with + indices ``i`` and ``j`` in the sorted order, result is computed according to the given + :attr:`interpolation` method as follows: + + - ``linear``: ``a + (b - a) * fraction``, where ``fraction`` is the fractional part of the computed quantile index. + - ``lower``: ``a``. + - ``higher``: ``b``. + - ``nearest``: ``a`` or ``b``, whichever's index is closer to the computed quantile index (follows :func:`torch.round`). + - ``midpoint``: ``(a + b) / 2``. + + If :attr:`q` is a 1D tensor, the first dimension of the output represents the quantiles and has size + equal to the size of :attr:`q`, the remaining dimensions are what remains from the reduction. + + .. note:: + By default :attr:`dim` is ``None`` resulting in the :attr:`input` tensor being flattened before computation. + + Args: + input (Tensor): the input tensor. + q (float or Tensor): a scalar or 1D tensor of values in the range [0, 1]. + + dim (int, optional): the dimension to reduce. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword arguments: + interpolation (str, optional): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(2, 3) + >>> a + tensor([[ 0.0795, -1.2117, 0.9765], + [ 1.1707, 0.6706, 0.4884]]) + >>> q = torch.tensor([0.25, 0.5, 0.75]) + >>> torch.quantile(a, q, dim=1, keepdim=True) + tensor([[[-0.5661], + [ 0.5795]], + + [[ 0.0795], + [ 0.6706]], + + [[ 0.5280], + [ 0.9206]]]) + >>> torch.quantile(a, q, dim=1, keepdim=True).shape + torch.Size([3, 2, 1]) + >>> a = torch.arange(4.) + >>> a + tensor([0., 1., 2., 3.]) + >>> torch.quantile(a, 0.6, interpolation='linear') + tensor(1.8000) + >>> torch.quantile(a, 0.6, interpolation='lower') + tensor(1.) + >>> torch.quantile(a, 0.6, interpolation='higher') + tensor(2.) + >>> torch.quantile(a, 0.6, interpolation='midpoint') + tensor(1.5000) + >>> torch.quantile(a, 0.6, interpolation='nearest') + tensor(2.) + >>> torch.quantile(a, 0.4, interpolation='nearest') + tensor(1.) + """ + +@overload +def quantile( + input: Tensor, + q: _float, + dim: _int | None = None, + keepdim: _bool = False, + *, + interpolation: str = "linear", + out: Tensor | None = None, +) -> Tensor: + r""" + quantile(input, q, dim=None, keepdim=False, *, interpolation='linear', out=None) -> Tensor + + Computes the q-th quantiles of each row of the :attr:`input` tensor along the dimension :attr:`dim`. + + To compute the quantile, we map q in [0, 1] to the range of indices [0, n] to find the location + of the quantile in the sorted input. If the quantile lies between two data points ``a < b`` with + indices ``i`` and ``j`` in the sorted order, result is computed according to the given + :attr:`interpolation` method as follows: + + - ``linear``: ``a + (b - a) * fraction``, where ``fraction`` is the fractional part of the computed quantile index. + - ``lower``: ``a``. + - ``higher``: ``b``. + - ``nearest``: ``a`` or ``b``, whichever's index is closer to the computed quantile index (follows :func:`torch.round`). + - ``midpoint``: ``(a + b) / 2``. + + If :attr:`q` is a 1D tensor, the first dimension of the output represents the quantiles and has size + equal to the size of :attr:`q`, the remaining dimensions are what remains from the reduction. + + .. note:: + By default :attr:`dim` is ``None`` resulting in the :attr:`input` tensor being flattened before computation. + + Args: + input (Tensor): the input tensor. + q (float or Tensor): a scalar or 1D tensor of values in the range [0, 1]. + + dim (int, optional): the dimension to reduce. + + + keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not. Default: ``False``. + + + Keyword arguments: + interpolation (str, optional): interpolation method to use when the desired quantile lies between two data points. + Can be ``linear``, ``lower``, ``higher``, ``midpoint`` and ``nearest``. + Default is ``linear``. + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(2, 3) + >>> a + tensor([[ 0.0795, -1.2117, 0.9765], + [ 1.1707, 0.6706, 0.4884]]) + >>> q = torch.tensor([0.25, 0.5, 0.75]) + >>> torch.quantile(a, q, dim=1, keepdim=True) + tensor([[[-0.5661], + [ 0.5795]], + + [[ 0.0795], + [ 0.6706]], + + [[ 0.5280], + [ 0.9206]]]) + >>> torch.quantile(a, q, dim=1, keepdim=True).shape + torch.Size([3, 2, 1]) + >>> a = torch.arange(4.) + >>> a + tensor([0., 1., 2., 3.]) + >>> torch.quantile(a, 0.6, interpolation='linear') + tensor(1.8000) + >>> torch.quantile(a, 0.6, interpolation='lower') + tensor(1.) + >>> torch.quantile(a, 0.6, interpolation='higher') + tensor(2.) + >>> torch.quantile(a, 0.6, interpolation='midpoint') + tensor(1.5000) + >>> torch.quantile(a, 0.6, interpolation='nearest') + tensor(2.) + >>> torch.quantile(a, 0.4, interpolation='nearest') + tensor(1.) + """ + +def quantize_per_channel( + input: Tensor, + scales: Tensor, + zero_points: Tensor, + axis: _int, + dtype: _dtype, +) -> Tensor: + r""" + quantize_per_channel(input, scales, zero_points, axis, dtype) -> Tensor + + Converts a float tensor to a per-channel quantized tensor with given scales and zero points. + + Arguments: + input (Tensor): float tensor to quantize + scales (Tensor): float 1D tensor of scales to use, size should match ``input.size(axis)`` + zero_points (int): integer 1D tensor of offset to use, size should match ``input.size(axis)`` + axis (int): dimension on which apply per-channel quantization + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + + Returns: + Tensor: A newly quantized tensor + + Example:: + + >>> x = torch.tensor([[-1.0, 0.0], [1.0, 2.0]]) + >>> torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8) + tensor([[-1., 0.], + [ 1., 2.]], size=(2, 2), dtype=torch.quint8, + quantization_scheme=torch.per_channel_affine, + scale=tensor([0.1000, 0.0100], dtype=torch.float64), + zero_point=tensor([10, 0]), axis=0) + >>> torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8).int_repr() + tensor([[ 0, 10], + [100, 200]], dtype=torch.uint8) + """ + +@overload +def quantize_per_tensor( + input: Tensor, + scale: Tensor, + zero_point: Tensor, + dtype: _dtype, +) -> Tensor: + r""" + quantize_per_tensor(input, scale, zero_point, dtype) -> Tensor + + Converts a float tensor to a quantized tensor with given scale and zero point. + + Arguments: + input (Tensor): float tensor or list of tensors to quantize + scale (float or Tensor): scale to apply in quantization formula + zero_point (int or Tensor): offset in integer value that maps to float zero + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + + Returns: + Tensor: A newly quantized tensor or list of quantized tensors. + + Example:: + + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8).int_repr() + tensor([ 0, 10, 20, 30], dtype=torch.uint8) + >>> torch.quantize_per_tensor([torch.tensor([-1.0, 0.0]), torch.tensor([-2.0, 2.0])], + >>> torch.tensor([0.1, 0.2]), torch.tensor([10, 20]), torch.quint8) + (tensor([-1., 0.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10), + tensor([-2., 2.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=20)) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.tensor(0.1), torch.tensor(10), torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.10, zero_point=10) + """ + +@overload +def quantize_per_tensor( + input: Tensor, + scale: _float, + zero_point: _int, + dtype: _dtype, +) -> Tensor: + r""" + quantize_per_tensor(input, scale, zero_point, dtype) -> Tensor + + Converts a float tensor to a quantized tensor with given scale and zero point. + + Arguments: + input (Tensor): float tensor or list of tensors to quantize + scale (float or Tensor): scale to apply in quantization formula + zero_point (int or Tensor): offset in integer value that maps to float zero + dtype (:class:`torch.dtype`): the desired data type of returned tensor. + Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32`` + + Returns: + Tensor: A newly quantized tensor or list of quantized tensors. + + Example:: + + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8).int_repr() + tensor([ 0, 10, 20, 30], dtype=torch.uint8) + >>> torch.quantize_per_tensor([torch.tensor([-1.0, 0.0]), torch.tensor([-2.0, 2.0])], + >>> torch.tensor([0.1, 0.2]), torch.tensor([10, 20]), torch.quint8) + (tensor([-1., 0.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10), + tensor([-2., 2.], size=(2,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.2, zero_point=20)) + >>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), torch.tensor(0.1), torch.tensor(10), torch.quint8) + tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8, + quantization_scheme=torch.per_tensor_affine, scale=0.10, zero_point=10) + """ + +@overload +def quantize_per_tensor( + tensors: tuple[Tensor, ...] | list[Tensor], + 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 | PySymType, + scale_hh: Number | _complex | PySymType, + zero_point_ih: Number | _complex | PySymType, + zero_point_hh: Number | _complex | PySymType, +) -> Tensor: ... +def quantized_lstm_cell( + input: Tensor, + hx: tuple[Tensor, ...] | list[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 | PySymType, + scale_hh: Number | _complex | PySymType, + zero_point_ih: Number | _complex | PySymType, + zero_point_hh: Number | _complex | PySymType, +) -> 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 | PySymType, + scale_hh: Number | _complex | PySymType, + zero_point_ih: Number | _complex | PySymType, + zero_point_hh: Number | _complex | PySymType, +) -> 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 | PySymType, + scale_hh: Number | _complex | PySymType, + zero_point_ih: Number | _complex | PySymType, + zero_point_hh: Number | _complex | PySymType, +) -> 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: + r""" + rad2deg_(input) -> Tensor + + In-place version of :func:`torch.rad2deg` + """ + +@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_like( + input: Tensor, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a uniform distribution on the interval :math:`[0, 1)`. + ``torch.rand_like(input)`` is equivalent to + ``torch.rand(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def rand_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + rand_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a uniform distribution on the interval :math:`[0, 1)`. + ``torch.rand_like(input)`` is equivalent to + ``torch.rand(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint( + low: _int, + high: _int, + size: _size, + *, + generator: Generator | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + high: _int, + size: _size, + *, + generator: Generator | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + low: _int | SymInt, + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint( + low: _int | SymInt, + high: _int | SymInt, + size: Sequence[_int | SymInt], + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint(low=0, high, size, \*, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a tensor filled with random integers generated uniformly + between :attr:`low` (inclusive) and :attr:`high` (exclusive). + + The shape of the tensor is defined by the variable argument :attr:`size`. + + .. note:: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + size (tuple): a tuple defining the shape of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (torch.dtype, optional): the desired data type of returned tensor. Default: if ``None``, + this function returns a tensor with dtype ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.randint(3, 5, (3,)) + tensor([4, 3, 4]) + + + >>> torch.randint(10, (2, 2)) + tensor([[0, 2], + [5, 5]]) + + + >>> torch.randint(3, 10, (2, 2)) + tensor([[4, 5], + [6, 7]]) + """ + +@overload +def randint_like( + input: Tensor, + low: _int | SymInt, + high: _int | SymInt, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + low: _int | SymInt, + high: _int | SymInt, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: Tensor, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: _int | SymInt, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randint_like( + input: Tensor, + high: _int | SymInt, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randint_like(input, low=0, high, \*, generator=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same shape as Tensor :attr:`input` filled with + random integers generated uniformly between :attr:`low` (inclusive) and + :attr:`high` (exclusive). + + .. note: + With the global dtype default (``torch.float32``), this function returns + a tensor with dtype ``torch.int64``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. + high (int): One above the highest integer to be drawn from the distribution. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randn( + size: Sequence[_int | SymInt], + *, + generator: Generator | None, + 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_like( + input: Tensor, + *, + generator: Generator | None, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a normal distribution with mean 0 and variance 1. Please refer to :func:`torch.randn` for the + sampling process of complex dtypes. ``torch.randn_like(input)`` is equivalent to + ``torch.randn(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randn_like( + input: Tensor, + *, + memory_format: memory_format | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randn_like(input, *, generator=None, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) -> Tensor + + Returns a tensor with the same size as :attr:`input` that is filled with + random numbers from a normal distribution with mean 0 and variance 1. Please refer to :func:`torch.randn` for the + sampling process of complex dtypes. ``torch.randn_like(input)`` is equivalent to + ``torch.randn(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. + + Args: + input (Tensor): the size of :attr:`input` will determine size of the output tensor. + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling. + dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. + Default: if ``None``, defaults to the dtype of :attr:`input`. + layout (:class:`torch.layout`, optional): the desired layout of returned tensor. + Default: if ``None``, defaults to the layout of :attr:`input`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, defaults to the device of :attr:`input`. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + memory_format (:class:`torch.memory_format`, optional): the desired memory format of + returned Tensor. Default: ``torch.preserve_format``. + """ + +@overload +def randperm( + n: _int | SymInt, + *, + generator: Generator | None, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randperm(n, *, generator=None, out=None, dtype=torch.int64,layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a random permutation of integers from ``0`` to ``n - 1``. + + Args: + n (int): the upper bound (exclusive) + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randperm(4) + tensor([2, 1, 0, 3]) + """ + +@overload +def randperm( + n: _int | SymInt, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + randperm(n, *, generator=None, out=None, dtype=torch.int64,layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor + + Returns a random permutation of integers from ``0`` to ``n - 1``. + + Args: + n (int): the upper bound (exclusive) + + Keyword args: + generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: ``torch.int64``. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + + Example:: + + >>> torch.randperm(4) + tensor([2, 1, 0, 3]) + """ + +def range( + start: Number, + end: Number, + step: Number = 1, + *, + out: Tensor | None = None, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + pin_memory: _bool = False, +) -> Tensor: + r""" + range(start=0, end, step=1, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor + + Returns a 1-D tensor of size :math:`\left\lfloor \frac{\text{end} - \text{start}}{\text{step}} \right\rfloor + 1` + with values from :attr:`start` to :attr:`end` with step :attr:`step`. Step is + the gap between two values in the tensor. + + .. math:: + \text{out}_{i+1} = \text{out}_i + \text{step}. + + .. warning:: + This function is deprecated and will be removed in a future release because its behavior is inconsistent with + Python's range builtin. Instead, use :func:`torch.arange`, which produces values in [start, end). + + Args: + start (float, optional): the starting value for the set of points. Default: ``0``. + end (float): the ending value for the set of points + step (float, optional): the gap between each pair of adjacent points. Default: ``1``. + + Keyword args: + out (Tensor, optional): the output tensor. + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if ``None``, uses a global default (see :func:`torch.set_default_dtype`). If `dtype` is not given, infer the data type from the other input + arguments. If any of `start`, `end`, or `step` are floating-point, the + `dtype` is inferred to be the default dtype, see + :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to + be `torch.int64`. + layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. + Default: ``torch.strided``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + + Example:: + + >>> torch.range(1, 4) + tensor([ 1., 2., 3., 4.]) + >>> torch.range(1, 4, 0.5) + tensor([ 1.0000, 1.5000, 2.0000, 2.5000, 3.0000, 3.5000, 4.0000]) + """ + +def ravel(input: Tensor) -> Tensor: + r""" + ravel(input) -> Tensor + + Return a contiguous flattened tensor. A copy is made only if needed. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> t = torch.tensor([[[1, 2], + ... [3, 4]], + ... [[5, 6], + ... [7, 8]]]) + >>> torch.ravel(t) + tensor([1, 2, 3, 4, 5, 6, 7, 8]) + """ + +def real(input: Tensor) -> Tensor: + r""" + real(input) -> Tensor + + Returns a new tensor containing real values of the :attr:`self` tensor. + The returned tensor and :attr:`self` share the same underlying storage. + + Args: + input (Tensor): the input tensor. + + Example:: + + >>> x=torch.randn(4, dtype=torch.cfloat) + >>> x + tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)]) + >>> x.real + tensor([ 0.3100, -0.5445, -1.6492, -0.0638]) + """ + +def reciprocal(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + reciprocal(input, *, out=None) -> Tensor + + Returns a new tensor with the reciprocal of the elements of :attr:`input` + + .. math:: + \text{out}_{i} = \frac{1}{\text{input}_{i}} + + .. note:: + Unlike NumPy's reciprocal, torch.reciprocal supports integral inputs. Integral + inputs to reciprocal are automatically :ref:`promoted ` to + the default scalar type. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.4595, -2.1219, -1.4314, 0.7298]) + >>> torch.reciprocal(a) + tensor([-2.1763, -0.4713, -0.6986, 1.3702]) + """ + +def reciprocal_(input: Tensor) -> Tensor: + r""" + reciprocal_(input) -> Tensor + + In-place version of :func:`torch.reciprocal` + """ + +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 | PySymType, 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 | PySymType, + *, + 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 | PySymType, + dim: _int, + maxnorm: Number | _complex | PySymType, + *, + 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 | PySymType, + 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 | PySymType, +) -> _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 | PySymType, + scalar2: Number | _complex | PySymType, +) -> _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], + 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], + 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], + 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], + 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 + >>> # 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 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 + >>> # 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 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: + r""" + round_(input, *, decimals=0) -> Tensor + + In-place version of :func:`torch.round` + """ + +@overload +def round_(input: Tensor, *, decimals: _int) -> Tensor: + r""" + round_(input, *, decimals=0) -> Tensor + + In-place version of :func:`torch.round` + """ + +def row_indices_copy(input: Tensor, *, out: Tensor | None = None) -> Tensor: ... +def row_stack( + tensors: tuple[Tensor, ...] | list[Tensor], + *, + out: Tensor | None = None, +) -> Tensor: + r""" + row_stack(tensors, *, out=None) -> Tensor + + Alias of :func:`torch.vstack`. + """ + +def rrelu( + input: Tensor, + lower: Number | _complex | PySymType = 0.125, + upper: Number | _complex | PySymType = 0.3333333333333333, + training: _bool = False, + generator: Generator | None = None, +) -> Tensor: ... +def rrelu_( + input: Tensor, + lower: Number | _complex | PySymType = 0.125, + upper: Number | _complex | PySymType = 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: + r""" + rsqrt_(input) -> Tensor + + In-place version of :func:`torch.rsqrt` + """ + +@overload +def rsub( + input: Tensor, + other: Tensor, + *, + alpha: Number | _complex | PySymType = 1, +) -> Tensor: ... +@overload +def rsub( + input: Tensor, + other: Number | _complex | PySymType, + alpha: Number | _complex | PySymType = 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 | PySymType, + *, + 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 | PySymType, + *, + 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, + value: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + scatter(input, dim, index, src) -> Tensor + + Out-of-place version of :meth:`torch.Tensor.scatter_` + """ + +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_` + """ + +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. PyTorch does not validate this condition when :attr:`sorter` is + not provided, and the behavior is undefined if the sequence is not 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 | PySymType, + *, + 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. PyTorch does not validate this condition when :attr:`sorter` is + not provided, and the behavior is undefined if the sequence is not 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 | PySymType | None = None, +) -> Tensor: + r""" + segment_reduce(data: Tensor, reduce: str, *, lengths: Tensor | None = None, indices: Tensor | None = None, offsets: Tensor | None = None, axis: _int = 0, unsafe: _bool = False, initial: Number | _complex | None = None) -> Tensor # noqa: B950 + + Perform a segment reduction operation on the input tensor along the specified axis. + + Args: + data (Tensor): The input tensor on which the segment reduction operation will be performed. + reduce (str): The type of reduction operation. Supported values are ``sum``, ``mean``, ``max``, ``min``, ``prod``. + + Keyword args: + lengths (Tensor, optional): Length of each segment. Default: ``None``. + offsets (Tensor, optional): Offset of each segment. Default: ``None``. + axis (int, optional): The axis perform reduction. Default: ``0``. + unsafe (bool, optional): Skip validation If `True`. Default: ``False``. + initial (Number, optional): The initial value for the reduction operation. Default: ``None``. + + Example:: + + >>> data = torch.tensor([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]], dtype=torch.float32, device='cuda') + >>> lengths = torch.tensor([2, 1], device='cuda') + >>> torch.segment_reduce(data, 'max', lengths=lengths) + tensor([[ 5., 6., 7., 8.], + [ 9., 10., 11., 12.]], device='cuda:0') + """ + +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]``. + """ + +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: + r""" + sigmoid_(input) -> Tensor + + In-place version of :func:`torch.sigmoid` + """ + +def sign(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sign(input, *, out=None) -> Tensor + + Returns a new tensor with the signs of the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \operatorname{sgn}(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([0.7, -1.2, 0., 2.3]) + >>> a + tensor([ 0.7000, -1.2000, 0.0000, 2.3000]) + >>> torch.sign(a) + tensor([ 1., -1., 0., 1.]) + """ + +def signbit(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + signbit(input, *, out=None) -> Tensor + + Tests if each element of :attr:`input` has its sign bit set or not. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.tensor([0.7, -1.2, 0., 2.3]) + >>> torch.signbit(a) + tensor([ False, True, False, False]) + >>> a = torch.tensor([-0.0, 0.0]) + >>> torch.signbit(a) + tensor([ True, False]) + + .. note:: + signbit handles signed zeros, so negative zero (-0) returns True. + """ + +def sin(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sin(input, *, out=None) -> Tensor + + Returns a new tensor with the sine of the elements in the :attr:`input` tensor, + where each value in this input tensor is in radians. + + .. math:: + \text{out}_{i} = \sin(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-0.5461, 0.1347, -2.7266, -0.2746]) + >>> torch.sin(a) + tensor([-0.5194, 0.1343, -0.4032, -0.2711]) + """ + +def sin_(input: Tensor) -> Tensor: + r""" + sin_(input) -> Tensor + + In-place version of :func:`torch.sin` + """ + +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: + r""" + sinc_(input) -> Tensor + + In-place version of :func:`torch.sinc` + """ + +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]) + """ + +def sinh_(input: Tensor) -> Tensor: + r""" + sinh_(input) -> Tensor + + In-place version of :func:`torch.sinh` + """ + +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 + """ + +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 sort( + input: Tensor, + *, + stable: _bool | None, + dim: _int = -1, + descending: _bool = False, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.sort: + r""" + sort(input, dim=-1, descending=False, *, stable=False, out=None) -> (Tensor, LongTensor) + + Sorts the elements of the :attr:`input` tensor along a given dimension + in ascending order by value. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`descending` is ``True`` then the elements are sorted in descending + order by value. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. + + A namedtuple of (values, indices) is returned, where the `values` are the + sorted values and `indices` are the indices of the elements in the original + `input` tensor. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + out (tuple, optional): the output tuple of (`Tensor`, `LongTensor`) that can + be optionally given to be used as output buffers + + Example:: + + >>> x = torch.randn(3, 4) + >>> sorted, indices = torch.sort(x) + >>> sorted + tensor([[-0.2162, 0.0608, 0.6719, 2.3332], + [-0.5793, 0.0061, 0.6058, 0.9497], + [-0.5071, 0.3343, 0.9553, 1.0960]]) + >>> indices + tensor([[ 1, 0, 2, 3], + [ 3, 1, 0, 2], + [ 0, 3, 1, 2]]) + + >>> sorted, indices = torch.sort(x, 0) + >>> sorted + tensor([[-0.5071, -0.2162, 0.6719, -0.5793], + [ 0.0608, 0.0061, 0.9497, 0.3343], + [ 0.6058, 0.9553, 1.0960, 2.3332]]) + >>> indices + tensor([[ 2, 0, 0, 1], + [ 0, 1, 1, 2], + [ 1, 2, 2, 0]]) + >>> x = torch.tensor([0, 1] * 9) + >>> x.sort() + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 2, 16, 4, 6, 14, 8, 0, 10, 12, 9, 17, 15, 13, 11, 7, 5, 3, 1])) + >>> x.sort(stable=True) + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 1, 3, 5, 7, 9, 11, 13, 15, 17])) + """ + +@overload +def sort( + input: Tensor, + dim: _int = -1, + descending: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.sort: + r""" + sort(input, dim=-1, descending=False, *, stable=False, out=None) -> (Tensor, LongTensor) + + Sorts the elements of the :attr:`input` tensor along a given dimension + in ascending order by value. + + If :attr:`dim` is not given, the last dimension of the `input` is chosen. + + If :attr:`descending` is ``True`` then the elements are sorted in descending + order by value. + + If :attr:`stable` is ``True`` then the sorting routine becomes stable, preserving + the order of equivalent elements. + + A namedtuple of (values, indices) is returned, where the `values` are the + sorted values and `indices` are the indices of the elements in the original + `input` tensor. + + Args: + input (Tensor): the input tensor. + dim (int, optional): the dimension to sort along + descending (bool, optional): controls the sorting order (ascending or descending) + + Keyword args: + stable (bool, optional): makes the sorting routine stable, which guarantees that the order + of equivalent elements is preserved. + out (tuple, optional): the output tuple of (`Tensor`, `LongTensor`) that can + be optionally given to be used as output buffers + + Example:: + + >>> x = torch.randn(3, 4) + >>> sorted, indices = torch.sort(x) + >>> sorted + tensor([[-0.2162, 0.0608, 0.6719, 2.3332], + [-0.5793, 0.0061, 0.6058, 0.9497], + [-0.5071, 0.3343, 0.9553, 1.0960]]) + >>> indices + tensor([[ 1, 0, 2, 3], + [ 3, 1, 0, 2], + [ 0, 3, 1, 2]]) + + >>> sorted, indices = torch.sort(x, 0) + >>> sorted + tensor([[-0.5071, -0.2162, 0.6719, -0.5793], + [ 0.0608, 0.0061, 0.9497, 0.3343], + [ 0.6058, 0.9553, 1.0960, 2.3332]]) + >>> indices + tensor([[ 2, 0, 0, 1], + [ 0, 1, 1, 2], + [ 1, 2, 2, 0]]) + >>> x = torch.tensor([0, 1] * 9) + >>> x.sort() + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 2, 16, 4, 6, 14, 8, 0, 10, 12, 9, 17, 15, 13, 11, 7, 5, 3, 1])) + >>> x.sort(stable=True) + torch.return_types.sort( + values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), + indices=tensor([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 1, 3, 5, 7, 9, 11, 13, 15, 17])) + """ + +def sparse_bsc_tensor( + ccol_indices: Tensor | list, + row_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_bsc_tensor(ccol_indices, row_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in BSC (Block Compressed Sparse + Column)) ` with specified 2-dimensional blocks at the + given :attr:`ccol_indices` and :attr:`row_indices`. Sparse matrix + multiplication operations in BSC format are typically faster than that + for sparse tensors in COO format. Make you have a look at :ref:`the + note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + ccol_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, ncolblocks + 1)``. The last element of each + batch is the number of non-zeros. This tensor encodes the + index in values and row_indices depending on where the given + column starts. Each successive number in the tensor subtracted + by the number before it denotes the number of elements in a + given column. + row_indices (array_like): Row block coordinates of each block in + values. (B+1)-dimensional tensor with the same length + as values. + values (array_list): Initial blocks for the tensor. Can be a list, + tuple, NumPy ``ndarray``, and other types that + represents a (1 + 2 + K)-dimensional tensor where ``K`` is the + number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` If not provided, the size will be + inferred as the minimum size big enough to hold all non-zero + blocks. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> ccol_indices = [0, 1, 2] + >>> row_indices = [0, 1] + >>> values = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] + >>> torch.sparse_bsc_tensor(torch.tensor(ccol_indices, dtype=torch.int64), + ... torch.tensor(row_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(ccol_indices=tensor([0, 1, 2]), + row_indices=tensor([0, 1]), + values=tensor([[[1., 2.], + [3., 4.]], + [[5., 6.], + [7., 8.]]]), size=(2, 2), nnz=2, dtype=torch.float64, + layout=torch.sparse_bsc) + """ + +def sparse_bsr_tensor( + crow_indices: Tensor | list, + col_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_bsr_tensor(crow_indices, col_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in BSR (Block Compressed Sparse Row)) + ` with specified 2-dimensional blocks at the given + :attr:`crow_indices` and :attr:`col_indices`. Sparse matrix + multiplication operations in BSR format are typically faster than that + for sparse tensors in COO format. Make you have a look at :ref:`the + note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + crow_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, nrowblocks + 1)``. The last element of each + batch is the number of non-zeros. This tensor encodes the + block index in values and col_indices depending on where the + given row block starts. Each successive number in the tensor + subtracted by the number before it denotes the number of + blocks in a given row. + col_indices (array_like): Column block coordinates of each block + in values. (B+1)-dimensional tensor with the same length as + values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1 + 2 + K)-dimensional tensor where ``K`` is the + number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` where ``blocksize == + values.shape[1:3]``. If not provided, the size will be + inferred as the minimum size big enough to hold all non-zero + blocks. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> crow_indices = [0, 1, 2] + >>> col_indices = [0, 1] + >>> values = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] + >>> torch.sparse_bsr_tensor(torch.tensor(crow_indices, dtype=torch.int64), + ... torch.tensor(col_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(crow_indices=tensor([0, 1, 2]), + col_indices=tensor([0, 1]), + values=tensor([[[1., 2.], + [3., 4.]], + [[5., 6.], + [7., 8.]]]), size=(2, 2), nnz=2, dtype=torch.float64, + layout=torch.sparse_bsr) + """ + +def sparse_compressed_tensor( + compressed_indices: Tensor | list, + plain_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_compressed_tensor(compressed_indices, plain_indices, values, size=None, *, dtype=None, layout=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in Compressed Sparse format - CSR, + CSC, BSR, or BSC - ` with specified values at + the given :attr:`compressed_indices` and :attr:`plain_indices`. Sparse + matrix multiplication operations in Compressed Sparse format are + typically faster than that for sparse tensors in COO format. Make you + have a look at :ref:`the note on the data type of the indices + `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + compressed_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, compressed_dim_size + 1)``. The last element of + each batch is the number of non-zero elements or blocks. This + tensor encodes the index in ``values`` and ``plain_indices`` + depending on where the given compressed dimension (row or + column) starts. Each successive number in the tensor + subtracted by the number before it denotes the number of + elements or blocks in a given compressed dimension. + plain_indices (array_like): Plain dimension (column or row) + coordinates of each element or block in values. (B+1)-dimensional + tensor with the same length as values. + + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types. that + represents a (1+K)-dimensional (for CSR and CSC layouts) or + (1+2+K)-dimensional tensor (for BSR and BSC layouts) where + ``K`` is the number of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows * blocksize[0], ncols * + blocksize[1], *densesize)`` where ``blocksize[0] == + blocksize[1] == 1`` for CSR and CSC formats. If not provided, + the size will be inferred as the minimum size big enough to + hold all non-zero elements or blocks. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + layout (:class:`torch.layout`, required): the desired layout of + returned tensor: :attr:`torch.sparse_csr`, + :attr:`torch.sparse_csc`, :attr:`torch.sparse_bsr`, or + :attr:`torch.sparse_bsc`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> compressed_indices = [0, 2, 4] + >>> plain_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_compressed_tensor(torch.tensor(compressed_indices, dtype=torch.int64), + ... torch.tensor(plain_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double, layout=torch.sparse_csr) + tensor(crow_indices=tensor([0, 2, 4]), + col_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csr) + """ + +def sparse_coo_tensor( + indices: Tensor, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, + is_coalesced: _bool | None = None, +) -> Tensor: + r""" + sparse_coo_tensor(indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None, is_coalesced=None) -> Tensor + + Constructs a :ref:`sparse tensor in COO(rdinate) format + ` with specified values at the given + :attr:`indices`. + + .. note:: + + This function returns an :ref:`uncoalesced tensor + ` when :attr:`is_coalesced` is + unspecified or ``None``. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + indices (array_like): Initial data for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. Will be cast to a :class:`torch.LongTensor` + internally. The indices are the coordinates of the non-zero values in the matrix, and thus + should be two-dimensional where the first dimension is the number of tensor dimensions and + the second dimension is the number of non-zero values. + values (array_like): Initial values for the tensor. Can be a list, tuple, + NumPy ``ndarray``, scalar, and other types. + size (list, tuple, or :class:`torch.Size`, optional): Size of the sparse tensor. If not + provided the size will be inferred as the minimum size big enough to hold all non-zero + elements. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. + Default: if None, infers data type from :attr:`values`. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if None, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + is_coalesced (bool, optional): When``True``, the caller is + responsible for providing tensor indices that correspond to a + coalesced tensor. If the :attr:`check_invariants` flag is + False, no error will be raised if the prerequisites are not + met and this will lead to silently incorrect results. To force + coalescing please use :meth:`coalesce` on the resulting + Tensor. + Default: None: except for trivial cases (e.g. nnz < 2) the + resulting Tensor has is_coalesced set to ``False```. + + Example:: + + >>> i = torch.tensor([[0, 1, 1], + ... [2, 0, 2]]) + >>> v = torch.tensor([3, 4, 5], dtype=torch.float32) + >>> torch.sparse_coo_tensor(i, v, [2, 4]) + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + size=(2, 4), nnz=3, layout=torch.sparse_coo) + + >>> torch.sparse_coo_tensor(i, v) # Shape inference + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + size=(2, 3), nnz=3, layout=torch.sparse_coo) + + >>> torch.sparse_coo_tensor(i, v, [2, 4], + ... dtype=torch.float64, + ... device=torch.device('cuda:0')) + tensor(indices=tensor([[0, 1, 1], + [2, 0, 2]]), + values=tensor([3., 4., 5.]), + device='cuda:0', size=(2, 4), nnz=3, dtype=torch.float64, + layout=torch.sparse_coo) + + # Create an empty sparse tensor with the following invariants: + # 1. sparse_dim + dense_dim = len(SparseTensor.shape) + # 2. SparseTensor._indices().shape = (sparse_dim, nnz) + # 3. SparseTensor._values().shape = (nnz, SparseTensor.shape[sparse_dim:]) + # + # For instance, to create an empty sparse tensor with nnz = 0, dense_dim = 0 and + # sparse_dim = 1 (hence indices is a 2D tensor of shape = (1, 0)) + >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), [], [1]) + tensor(indices=tensor([], size=(1, 0)), + values=tensor([], size=(0,)), + size=(1,), nnz=0, layout=torch.sparse_coo) + + # and to create an empty sparse tensor with nnz = 0, dense_dim = 1 and + # sparse_dim = 1 + >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), torch.empty([0, 2]), [1, 2]) + tensor(indices=tensor([], size=(1, 0)), + values=tensor([], size=(0, 2)), + size=(1, 2), nnz=0, layout=torch.sparse_coo) + + .. _torch.sparse: https://pytorch.org/docs/stable/sparse.html + """ + +def sparse_csc_tensor( + ccol_indices: Tensor | list, + row_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_csc_tensor(ccol_indices, row_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in CSC (Compressed Sparse Column) + ` with specified values at the given + :attr:`ccol_indices` and :attr:`row_indices`. Sparse matrix + multiplication operations in CSC format are typically faster than that + for sparse tensors in COO format. Make you have a look at :ref:`the + note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + ccol_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, ncols + 1)``. The last element of each batch + is the number of non-zeros. This tensor encodes the index in + values and row_indices depending on where the given column + starts. Each successive number in the tensor subtracted by the + number before it denotes the number of elements in a given + column. + row_indices (array_like): Row coordinates of each element in + values. (B+1)-dimensional tensor with the same length as + values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1+K)-dimensional tensor where ``K`` is the number + of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows, ncols, *densesize)``. If + not provided, the size will be inferred as the minimum size + big enough to hold all non-zero elements. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> ccol_indices = [0, 2, 4] + >>> row_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_csc_tensor(torch.tensor(ccol_indices, dtype=torch.int64), + ... torch.tensor(row_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(ccol_indices=tensor([0, 2, 4]), + row_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csc) + """ + +def sparse_csr_tensor( + crow_indices: Tensor | list, + col_indices: Tensor | list, + values: Tensor | list, + size: _size | None = None, + *, + dtype: _dtype | None = None, + device: DeviceLikeType | None = None, + requires_grad: _bool = False, + check_invariants: _bool | None = None, +) -> Tensor: + r""" + sparse_csr_tensor(crow_indices, col_indices, values, size=None, *, dtype=None, device=None, pin_memory=False, requires_grad=False, check_invariants=None) -> Tensor + + Constructs a :ref:`sparse tensor in CSR (Compressed Sparse Row) ` with specified + values at the given :attr:`crow_indices` and :attr:`col_indices`. Sparse matrix multiplication operations + in CSR format are typically faster than that for sparse tensors in COO format. Make you have a look + at :ref:`the note on the data type of the indices `. + + .. note:: + + If the ``device`` argument is not specified the device of the given + :attr:`values` and indices tensor(s) must match. If, however, the + argument is specified the input Tensors will be converted to the + given device and in turn determine the device of the constructed + sparse tensor. + + Args: + crow_indices (array_like): (B+1)-dimensional array of size + ``(*batchsize, nrows + 1)``. The last element of each batch + is the number of non-zeros. This tensor encodes the index in + values and col_indices depending on where the given row + starts. Each successive number in the tensor subtracted by the + number before it denotes the number of elements in a given + row. + col_indices (array_like): Column coordinates of each element in + values. (B+1)-dimensional tensor with the same length + as values. + values (array_list): Initial values for the tensor. Can be a list, + tuple, NumPy ``ndarray``, scalar, and other types that + represents a (1+K)-dimensional tensor where ``K`` is the number + of dense dimensions. + size (list, tuple, :class:`torch.Size`, optional): Size of the + sparse tensor: ``(*batchsize, nrows, ncols, *densesize)``. If + not provided, the size will be inferred as the minimum size + big enough to hold all non-zero elements. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of + returned tensor. Default: if None, infers data type from + :attr:`values`. + device (:class:`torch.device`, optional): the desired device of + returned tensor. Default: if None, uses the current device + for the default tensor type (see + :func:`torch.set_default_device`). :attr:`device` will be + the CPU for CPU tensor types and the current CUDA device for + CUDA tensor types. + pin_memory (bool, optional): If set, returned tensor would be allocated in + the pinned memory. Works only for CPU tensors. Default: ``False``. + requires_grad (bool, optional): If autograd should record operations on the + returned tensor. Default: ``False``. + check_invariants (bool, optional): If sparse tensor invariants are checked. + Default: as returned by :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled`, + initially False. + + Example:: + + >>> crow_indices = [0, 2, 4] + >>> col_indices = [0, 1, 0, 1] + >>> values = [1, 2, 3, 4] + >>> torch.sparse_csr_tensor(torch.tensor(crow_indices, dtype=torch.int64), + ... torch.tensor(col_indices, dtype=torch.int64), + ... torch.tensor(values), dtype=torch.double) + tensor(crow_indices=tensor([0, 2, 4]), + col_indices=tensor([0, 1, 0, 1]), + values=tensor([1., 2., 3., 4.]), size=(2, 2), nnz=4, + dtype=torch.float64, layout=torch.sparse_csr) + """ + +def split_copy( + input: Tensor, + split_size: _int | SymInt, + dim: _int = 0, + *, + out: tuple[Tensor, ...] | list[Tensor] | None = None, +) -> None: + r""" + Performs the same operation as :func:`torch.split`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def split_with_sizes( + input: Tensor, + split_sizes: Sequence[_int | SymInt], + dim: _int = 0, +) -> tuple[Tensor, ...]: ... +def split_with_sizes_copy( + input: Tensor, + split_sizes: Sequence[_int | SymInt], + dim: _int = 0, + *, + out: tuple[Tensor, ...] | list[Tensor] | None = None, +) -> None: + r""" + Performs the same operation as :func:`torch.split_with_sizes`, but all output tensors + are freshly created instead of aliasing the input. + """ + +def spmm(input: Tensor, mat2: Tensor) -> Tensor: ... +def sqrt(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + sqrt(input, *, out=None) -> Tensor + + Returns a new tensor with the square-root of the elements of :attr:`input`. + + .. math:: + \text{out}_{i} = \sqrt{\text{input}_{i}} + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-2.0755, 1.0226, 0.0831, 0.4806]) + >>> torch.sqrt(a) + tensor([ nan, 1.0112, 0.2883, 0.6933]) + """ + +def sqrt_(input: Tensor) -> Tensor: + r""" + sqrt_(input) -> Tensor + + In-place version of :func:`torch.sqrt` + """ + +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: + r""" + square_(input) -> Tensor + + In-place version of :func:`torch.square` + """ + +@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_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 | PySymType, + self: Tensor, + alpha: Number | _complex | PySymType, + 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 | PySymType = 1, + alpha: Number | _complex | PySymType = 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 | PySymType, + 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], + 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 | PySymType | 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_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 | PySymType | 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 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 | PySymType, + 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 | PySymType, + 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 | PySymType = 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 | PySymType, + alpha: Number | _complex | PySymType = 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.]) + """ + +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`. + + .. 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 | PySymType, + *, + min: _int | None = None, + max: _int | None = None, +) -> None: ... +def sym_constrain_range_for_size( + size: Number | _complex | PySymType, + *, + 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: `None`. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> t = torch.tensor([[10, 30, 20], [60, 40, 50]]) + >>> max_idx = torch.argmax(t) + >>> torch.take_along_dim(t, max_idx) + tensor([60]) + >>> sorted_idx = torch.argsort(t, dim=1) + >>> torch.take_along_dim(t, sorted_idx, dim=1) + tensor([[10, 20, 30], + [40, 50, 60]]) + """ + +def tan(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + tan(input, *, out=None) -> Tensor + + Returns a new tensor with the tangent of the elements in the :attr:`input` tensor, + where each value in this input tensor is in radians. + + .. math:: + \text{out}_{i} = \tan(\text{input}_{i}) + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([-1.2027, -1.7687, 0.4412, -1.3856]) + >>> torch.tan(a) + tensor([-2.5930, 4.9859, 0.4722, -5.3366]) + """ + +def tan_(input: Tensor) -> Tensor: + r""" + tan_(input) -> Tensor + + In-place version of :func:`torch.tan` + """ + +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: + r""" + tanh_(input) -> Tensor + + In-place version of :func:`torch.tanh` + """ + +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`. + + .. function:: tensor_split(input, sections, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` into :attr:`sections` sections along dimension :attr:`dim`. + If :attr:`input` is divisible by :attr:`sections` along dimension :attr:`dim`, each + section will be of equal size, :code:`input.size(dim) / sections`. If :attr:`input` + is not divisible by :attr:`sections`, the sizes of the first + :code:`int(input.size(dim) % sections)` sections will have size + :code:`int(input.size(dim) / sections) + 1`, and the rest will have size + :code:`int(input.size(dim) / sections)`. + + :attr:`sections` can also be a zero-dimensional long tensor. + + .. function:: tensor_split(input, indices, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` along dimension :attr:`dim` at each of the indices in + :attr:`indices`. For instance, :code:`indices=[2, 3]` and :code:`dim=0` + would result in the tensors :code:`input[:2]`, :code:`input[2:3]`, and + :code:`input[3:]`. + + :attr:`indices` can be a list or tuple of ints, or a one-dimensional long + tensor on the CPU. + + Args: + input (Tensor): the tensor to split + 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`. + + .. function:: tensor_split(input, sections, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` into :attr:`sections` sections along dimension :attr:`dim`. + If :attr:`input` is divisible by :attr:`sections` along dimension :attr:`dim`, each + section will be of equal size, :code:`input.size(dim) / sections`. If :attr:`input` + is not divisible by :attr:`sections`, the sizes of the first + :code:`int(input.size(dim) % sections)` sections will have size + :code:`int(input.size(dim) / sections) + 1`, and the rest will have size + :code:`int(input.size(dim) / sections)`. + + :attr:`sections` can also be a zero-dimensional long tensor. + + .. function:: tensor_split(input, indices, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` along dimension :attr:`dim` at each of the indices in + :attr:`indices`. For instance, :code:`indices=[2, 3]` and :code:`dim=0` + would result in the tensors :code:`input[:2]`, :code:`input[2:3]`, and + :code:`input[3:]`. + + :attr:`indices` can be a list or tuple of ints, or a one-dimensional long + tensor on the CPU. + + Args: + input (Tensor): the tensor to split + 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`. + + .. function:: tensor_split(input, sections, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` into :attr:`sections` sections along dimension :attr:`dim`. + If :attr:`input` is divisible by :attr:`sections` along dimension :attr:`dim`, each + section will be of equal size, :code:`input.size(dim) / sections`. If :attr:`input` + is not divisible by :attr:`sections`, the sizes of the first + :code:`int(input.size(dim) % sections)` sections will have size + :code:`int(input.size(dim) / sections) + 1`, and the rest will have size + :code:`int(input.size(dim) / sections)`. + + :attr:`sections` can also be a zero-dimensional long tensor. + + .. function:: tensor_split(input, indices, dim=0) -> List of Tensors + :noindex: + + Splits :attr:`input` along dimension :attr:`dim` at each of the indices in + :attr:`indices`. For instance, :code:`indices=[2, 3]` and :code:`dim=0` + would result in the tensors :code:`input[:2]`, :code:`input[2:3]`, and + :code:`input[3:]`. + + :attr:`indices` can be a list or tuple of ints, or a one-dimensional long + tensor on the CPU. + + Args: + input (Tensor): the tensor to split + 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 | PySymType, + value: Number | _complex | PySymType, + *, + out: Tensor | None = None, +) -> Tensor: ... +def threshold_( + input: Tensor, + threshold: Number | _complex | PySymType, + value: Number | _complex | PySymType, +) -> 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.) + """ + +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`. + """ + +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 | PySymType = 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=None, *, dim=-1) -> Tensor + + Alias for :func:`torch.trapezoid`. + """ + +@overload +def trapz(y: Tensor, x: Tensor, *, dim: _int = -1) -> Tensor: + r""" + trapz(y, x=None, *, dim=-1) -> Tensor + + Alias for :func:`torch.trapezoid`. + """ + +def triangular_solve( + input: Tensor, + A: Tensor, + upper: _bool = True, + transpose: _bool = False, + unitriangular: _bool = False, + *, + out: Tensor | tuple[Tensor, ...] | list[Tensor] | None = None, +) -> torch.return_types.triangular_solve: + r""" + triangular_solve(b, A, upper=True, transpose=False, unitriangular=False, *, out=None) -> (Tensor, Tensor) + + Solves a system of equations with a square upper or lower triangular invertible matrix :math:`A` + and multiple right-hand sides :math:`b`. + + In symbols, it solves :math:`AX = b` and assumes :math:`A` is square upper-triangular + (or lower-triangular if :attr:`upper`\ `= False`) and does not have zeros on the diagonal. + + `torch.triangular_solve(b, A)` can take in 2D inputs `b, A` or inputs that are + batches of 2D matrices. If the inputs are batches, then returns + batched outputs `X` + + If the diagonal of :attr:`A` contains zeros or elements that are very close to zero and + :attr:`unitriangular`\ `= False` (default) or if the input matrix is badly conditioned, + the result may contain `NaN` s. + + Supports input of float, double, cfloat and cdouble data types. + + .. warning:: + + :func:`torch.triangular_solve` is deprecated in favor of :func:`torch.linalg.solve_triangular` + and will be removed in a future PyTorch release. + :func:`torch.linalg.solve_triangular` has its arguments reversed and does not return a + copy of one of the inputs. + + ``X = torch.triangular_solve(B, A).solution`` should be replaced with + + .. code:: python + + X = torch.linalg.solve_triangular(A, B) + + Args: + b (Tensor): multiple right-hand sides of size :math:`(*, m, k)` where + :math:`*` is zero of more batch dimensions + A (Tensor): the input triangular coefficient matrix of size :math:`(*, m, m)` + where :math:`*` is zero or more batch dimensions + upper (bool, optional): whether :math:`A` is upper or lower triangular. Default: ``True``. + transpose (bool, optional): solves `op(A)X = b` where `op(A) = A^T` if this flag is ``True``, + and `op(A) = A` if it is ``False``. Default: ``False``. + unitriangular (bool, optional): whether :math:`A` is unit triangular. + If True, the diagonal elements of :math:`A` are assumed to be + 1 and not referenced from :math:`A`. Default: ``False``. + + Keyword args: + out ((Tensor, Tensor), optional): tuple of two tensors to write + the output to. Ignored if `None`. Default: `None`. + + Returns: + A namedtuple `(solution, cloned_coefficient)` where `cloned_coefficient` + is a clone of :math:`A` and `solution` is the solution :math:`X` to :math:`AX = b` + (or whatever variant of the system of equations, depending on the keyword arguments.) + + Examples:: + + >>> A = torch.randn(2, 2).triu() + >>> A + tensor([[ 1.1527, -1.0753], + [ 0.0000, 0.7986]]) + >>> b = torch.randn(2, 3) + >>> b + tensor([[-0.0210, 2.3513, -1.5492], + [ 1.5429, 0.7403, -1.0243]]) + >>> torch.triangular_solve(b, A) + torch.return_types.triangular_solve( + solution=tensor([[ 1.7841, 2.9046, -2.5405], + [ 1.9320, 0.9270, -1.2826]]), + cloned_coefficient=tensor([[ 1.1527, -1.0753], + [ 0.0000, 0.7986]])) + """ + +def tril( + input: Tensor, + diagonal: _int | SymInt = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + tril(input, diagonal=0, *, out=None) -> Tensor + + Returns the lower triangular part of the matrix (2-D tensor) or batch of matrices + :attr:`input`, the other elements of the result tensor :attr:`out` are set to 0. + + The lower triangular part of the matrix is defined as the elements on and + below the diagonal. + + The argument :attr:`diagonal` controls which diagonal to consider. If + :attr:`diagonal` = 0, all elements on and below the main diagonal are + retained. A positive value includes just as many diagonals above the main + diagonal, and similarly a negative value excludes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where + :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + Args: + input (Tensor): the input tensor. + diagonal (int, optional): the diagonal to consider + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[-1.0813, -0.8619, 0.7105], + [ 0.0935, 0.1380, 2.2112], + [-0.3409, -0.9828, 0.0289]]) + >>> torch.tril(a) + tensor([[-1.0813, 0.0000, 0.0000], + [ 0.0935, 0.1380, 0.0000], + [-0.3409, -0.9828, 0.0289]]) + + >>> b = torch.randn(4, 6) + >>> b + tensor([[ 1.2219, 0.5653, -0.2521, -0.2345, 1.2544, 0.3461], + [ 0.4785, -0.4477, 0.6049, 0.6368, 0.8775, 0.7145], + [ 1.1502, 3.2716, -1.1243, -0.5413, 0.3615, 0.6864], + [-0.0614, -0.7344, -1.3164, -0.7648, -1.4024, 0.0978]]) + >>> torch.tril(b, diagonal=1) + tensor([[ 1.2219, 0.5653, 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.4785, -0.4477, 0.6049, 0.0000, 0.0000, 0.0000], + [ 1.1502, 3.2716, -1.1243, -0.5413, 0.0000, 0.0000], + [-0.0614, -0.7344, -1.3164, -0.7648, -1.4024, 0.0000]]) + >>> torch.tril(b, diagonal=-1) + tensor([[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [ 0.4785, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], + [ 1.1502, 3.2716, 0.0000, 0.0000, 0.0000, 0.0000], + [-0.0614, -0.7344, -1.3164, 0.0000, 0.0000, 0.0000]]) + """ + +def tril_indices( + row: _int, + col: _int, + offset: _int = 0, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + tril_indices(row, col, offset=0, *, dtype=torch.long, device='cpu', layout=torch.strided) -> Tensor + + Returns the indices of the lower triangular part of a :attr:`row`-by- + :attr:`col` matrix in a 2-by-N Tensor, where the first row contains row + coordinates of all indices and the second row contains column coordinates. + Indices are ordered based on rows and then columns. + + The lower triangular part of the matrix is defined as the elements on and + below the diagonal. + + The argument :attr:`offset` controls which diagonal to consider. If + :attr:`offset` = 0, all elements on and below the main diagonal are + retained. A positive value includes just as many diagonals above the main + diagonal, and similarly a negative value excludes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` + where :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + .. note:: + When running on CUDA, ``row * col`` must be less than :math:`2^{59}` to + prevent overflow during calculation. + + Args: + row (``int``): number of rows in the 2-D matrix. + col (``int``): number of columns in the 2-D matrix. + offset (``int``): diagonal offset from the main diagonal. + Default: if not provided, 0. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor, + only support ``torch.int``, ``torch.long``. Default: if ``None``, ``torch.long``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + layout (:class:`torch.layout`, optional): currently only support ``torch.strided``. + + Example:: + + >>> a = torch.tril_indices(3, 3) + >>> a + tensor([[0, 1, 1, 2, 2, 2], + [0, 0, 1, 0, 1, 2]]) + + >>> a = torch.tril_indices(4, 3, -1) + >>> a + tensor([[1, 2, 2, 3, 3, 3], + [0, 0, 1, 0, 1, 2]]) + + >>> a = torch.tril_indices(4, 3, 1) + >>> a + tensor([[0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3], + [0, 1, 0, 1, 2, 0, 1, 2, 0, 1, 2]]) + """ + +def triplet_margin_loss( + anchor: Tensor, + positive: Tensor, + negative: Tensor, + margin: _float = 1.0, + p: _float = 2, + eps: _float = 1e-06, + swap: _bool = False, + reduction: _int = 1, +) -> Tensor: ... +def triu( + input: Tensor, + diagonal: _int | SymInt = 0, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + triu(input, diagonal=0, *, out=None) -> Tensor + + Returns the upper triangular part of a matrix (2-D tensor) or batch of matrices + :attr:`input`, the other elements of the result tensor :attr:`out` are set to 0. + + The upper triangular part of the matrix is defined as the elements on and + above the diagonal. + + The argument :attr:`diagonal` controls which diagonal to consider. If + :attr:`diagonal` = 0, all elements on and above the main diagonal are + retained. A positive value excludes just as many diagonals above the main + diagonal, and similarly a negative value includes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where + :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + Args: + input (Tensor): the input tensor. + diagonal (int, optional): the diagonal to consider + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(3, 3) + >>> a + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.2072, -1.0680, 0.6602], + [ 0.3480, -0.5211, -0.4573]]) + >>> torch.triu(a) + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.0000, -1.0680, 0.6602], + [ 0.0000, 0.0000, -0.4573]]) + >>> torch.triu(a, diagonal=1) + tensor([[ 0.0000, 0.5207, 2.0049], + [ 0.0000, 0.0000, 0.6602], + [ 0.0000, 0.0000, 0.0000]]) + >>> torch.triu(a, diagonal=-1) + tensor([[ 0.2309, 0.5207, 2.0049], + [ 0.2072, -1.0680, 0.6602], + [ 0.0000, -0.5211, -0.4573]]) + + >>> b = torch.randn(4, 6) + >>> b + tensor([[ 0.5876, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [-0.2447, 0.9556, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.4333, 0.3146, 0.6576, -1.0432, 0.9348, -0.4410], + [-0.9888, 1.0679, -1.3337, -1.6556, 0.4798, 0.2830]]) + >>> torch.triu(b, diagonal=1) + tensor([[ 0.0000, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [ 0.0000, 0.0000, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.0000, 0.0000, 0.0000, -1.0432, 0.9348, -0.4410], + [ 0.0000, 0.0000, 0.0000, 0.0000, 0.4798, 0.2830]]) + >>> torch.triu(b, diagonal=-1) + tensor([[ 0.5876, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], + [-0.2447, 0.9556, -1.2919, 1.3378, -0.1768, -1.0857], + [ 0.0000, 0.3146, 0.6576, -1.0432, 0.9348, -0.4410], + [ 0.0000, 0.0000, -1.3337, -1.6556, 0.4798, 0.2830]]) + """ + +def triu_indices( + row: _int, + col: _int, + offset: _int = 0, + *, + dtype: _dtype | None = None, + layout: _layout | None = None, + device: DeviceLikeType | None = None, + pin_memory: _bool | None = False, + requires_grad: _bool | None = False, +) -> Tensor: + r""" + triu_indices(row, col, offset=0, *, dtype=torch.long, device='cpu', layout=torch.strided) -> Tensor + + Returns the indices of the upper triangular part of a :attr:`row` by + :attr:`col` matrix in a 2-by-N Tensor, where the first row contains row + coordinates of all indices and the second row contains column coordinates. + Indices are ordered based on rows and then columns. + + The upper triangular part of the matrix is defined as the elements on and + above the diagonal. + + The argument :attr:`offset` controls which diagonal to consider. If + :attr:`offset` = 0, all elements on and above the main diagonal are + retained. A positive value excludes just as many diagonals above the main + diagonal, and similarly a negative value includes just as many diagonals below + the main diagonal. The main diagonal are the set of indices + :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` + where :math:`d_{1}, d_{2}` are the dimensions of the matrix. + + .. note:: + When running on CUDA, ``row * col`` must be less than :math:`2^{59}` to + prevent overflow during calculation. + + Args: + row (``int``): number of rows in the 2-D matrix. + col (``int``): number of columns in the 2-D matrix. + offset (``int``): diagonal offset from the main diagonal. + Default: if not provided, 0. + + Keyword args: + dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor, + only support ``torch.int``, ``torch.long``. Default: if ``None``, ``torch.long``. + device (:class:`torch.device`, optional): the desired device of returned tensor. + Default: if ``None``, uses the current device for the default tensor type + (see :func:`torch.set_default_device`). :attr:`device` will be the CPU + for CPU tensor types and the current CUDA device for CUDA tensor types. + layout (:class:`torch.layout`, optional): currently only support ``torch.strided``. + + Example:: + + >>> a = torch.triu_indices(3, 3) + >>> a + tensor([[0, 0, 0, 1, 1, 2], + [0, 1, 2, 1, 2, 2]]) + + >>> a = torch.triu_indices(4, 3, -1) + >>> a + tensor([[0, 0, 0, 1, 1, 1, 2, 2, 3], + [0, 1, 2, 0, 1, 2, 1, 2, 2]]) + + >>> a = torch.triu_indices(4, 3, 1) + >>> a + tensor([[0, 0, 1], + [1, 2, 2]]) + """ + +def true_divide( + input: Tensor | Number, + other: Tensor | Number, + *, + out: Tensor | None = None, +) -> Tensor: + r""" + true_divide(dividend, divisor, *, out) -> Tensor + + Alias for :func:`torch.div` with ``rounding_mode=None``. + """ + +def trunc(input: Tensor, *, out: Tensor | None = None) -> Tensor: + r""" + trunc(input, *, out=None) -> Tensor + + Returns a new tensor with the truncated integer values of + the elements of :attr:`input`. + + For integer inputs, follows the array-api convention of returning a + copy of the input tensor. + + Args: + input (Tensor): the input tensor. + + Keyword args: + out (Tensor, optional): the output tensor. + + Example:: + + >>> a = torch.randn(4) + >>> a + tensor([ 3.4742, 0.5466, -0.8008, -0.9079]) + >>> torch.trunc(a) + tensor([ 3., 0., -0., -0.]) + """ + +def trunc_(input: Tensor) -> Tensor: + r""" + trunc_(input) -> Tensor + + In-place version of :func:`torch.trunc` + """ + +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])) + """ + +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. + """ + +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 | PySymType | 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_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 | PySymType | 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 + """ + +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], + *, + 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 | PySymType, + 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 | PySymType, +) -> 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 | PySymType, + other: Number | _complex | PySymType, +) -> 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 | PySymType, + 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 | PySymType, + *, + 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: + r""" + xlogy_(input, other) -> Tensor + + In-place version of :func:`torch.xlogy` + """ + +@overload +def xlogy_(input: Tensor, other: Number | _complex | PySymType) -> Tensor: + r""" + xlogy_(input, other) -> Tensor + + In-place version of :func:`torch.xlogy` + """ + +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.]) + """ + +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/.venv/lib/python3.12/site-packages/torch/__config__.py b/.venv/lib/python3.12/site-packages/torch/__config__.py new file mode 100644 index 0000000000000000000000000000000000000000..1187fab3713996932d4f3bad71bac243c6baff35 --- /dev/null +++ b/.venv/lib/python3.12/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/.venv/lib/python3.12/site-packages/torch/__future__.py b/.venv/lib/python3.12/site-packages/torch/__future__.py new file mode 100644 index 0000000000000000000000000000000000000000..f172ee3c8fe223aa316667f37f356e5b6658d20e --- /dev/null +++ b/.venv/lib/python3.12/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/.venv/lib/python3.12/site-packages/torch/__init__.py b/.venv/lib/python3.12/site-packages/torch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f69b12c7b98759b6c44e80ad4f7ac23aa40884d8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/__init__.py @@ -0,0 +1,3539 @@ +""" +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. +""" + +import builtins +import ctypes +import functools +import glob +import importlib +import inspect +import math +import os +import platform +import sys +import textwrap +import threading +import typing +import typing_extensions +import warnings +from collections.abc import Callable as _Callable, Sequence as _Sequence +from types import ModuleType as _ModuleType +from typing import ( + Any as _Any, + get_origin as _get_origin, + overload as _overload, + TYPE_CHECKING, + TypeAlias as _TypeAlias, + TypeGuard as _TypeGuard, + TypeVar as _TypeVar, +) +from typing_extensions import ( + deprecated as _deprecated, + LiteralString as _LiteralString, + Never as _Never, + ParamSpec as _ParamSpec, + Self as _Self, + TypeIs as _TypeIs, +) + + +# As a bunch of torch.packages internally still have this check +# we need to keep this. @todo: Remove tests that rely on this check as +# they are likely stale. +def _running_with_deploy() -> builtins.bool: + return False + + +from torch._utils import ( + _functionalize_sync as _sync, + _import_dotted_name, + classproperty, +) +from torch._utils_internal import ( + get_file_path, + prepare_multiprocessing_environment, + profiler_allow_cudagraph_cupti_lazy_reinit_cuda12, + USE_GLOBAL_DEPS, + USE_RTLD_GLOBAL_WITH_LIBTORCH, +) +from torch.torch_version import __version__ as __version__ + + +if TYPE_CHECKING: + import sympy + + from torch.distributed._local_tensor import LocalIntNode + from torch.fx.experimental._constant_symnode import ConstantIntNode + from torch.fx.experimental.dynamic_spec import ParamsSpec, ShapesSpec + from torch.fx.experimental.sym_node import SymNode + from torch.nested._internal.nested_int import NestedIntNode + from torch.types import BoolLikeType, Device, FloatLikeType, IntLikeType, PySymType + + _SymNodeLike = SymNode | NestedIntNode | ConstantIntNode | LocalIntNode + + +__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", + "thread_safe_generator", + "typename", + "unravel_index", + "use_deterministic_algorithms", + "vmap", +] + +# Please keep this list sorted +if __all__ != sorted(__all__): + raise AssertionError("__all__ must be kept sorted") + +################################################################################ +# 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 importlib.util + 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") + # Anchor the DLL dir on the compiled _C extension rather than __file__: + # editable installs (e.g. scikit-build-core) run this __init__ from the + # source tree, whose lib/ is empty, while _C and its dependent DLLs live + # in the installed tree. In a wheel install both resolve to the same dir. + _spec = importlib.util.find_spec("torch._C") + if _spec is not None and _spec.origin: + th_dll_path = os.path.join(os.path.dirname(_spec.origin), "lib") + usebase_path = os.path.join( + sysconfig.get_config_var("userbase"), "Library", "bin" + ) + py_root_bin_path = os.path.join(sys.exec_prefix, "bin") + + # When users create a virtualenv that inherits the base environment, + # we will need to add the corresponding library directory into + # DLL search directories. Otherwise, it will rely on `PATH` which + # is dependent on user settings. + if sys.exec_prefix != sys.base_exec_prefix: + base_py_dll_path = os.path.join(sys.base_exec_prefix, "Library", "bin") + else: + base_py_dll_path = "" + + dll_paths = [ + p + for p in ( + th_dll_path, + py_dll_path, + base_py_dll_path, + usebase_path, + py_root_bin_path, + ) + if os.path.exists(p) + ] + + if not builtins.any( + os.path.exists(os.path.join(p, "nvToolsExt64_1.dll")) for p in dll_paths + ): + nvtoolsext_dll_path = os.path.join( + os.getenv( + "NVTOOLSEXT_PATH", + os.path.join(pfiles_path, "NVIDIA Corporation", "NvToolsExt"), + ), + "bin", + "x64", + ) + else: + nvtoolsext_dll_path = "" + + if cuda_version and builtins.all( + not glob.glob(os.path.join(p, "cudart64*.dll")) for p in dll_paths + ): + cuda_version_1 = cuda_version.replace(".", "_") + cuda_path_var = "CUDA_PATH_V" + cuda_version_1 + default_path = os.path.join( + pfiles_path, "NVIDIA GPU Computing Toolkit", "CUDA", f"v{cuda_version}" + ) + cuda_path = os.path.join(os.getenv(cuda_path_var, default_path), "bin") + else: + cuda_path = "" + + dll_paths.extend( + p for p in (nvtoolsext_dll_path, cuda_path) if os.path.exists(p) + ) + + kernel32 = ctypes.WinDLL("kernel32.dll", use_last_error=True) + with_load_library_flags = hasattr(kernel32, "AddDllDirectory") + prev_error_mode = kernel32.SetErrorMode(0x0001) + + kernel32.LoadLibraryW.restype = ctypes.c_void_p + if with_load_library_flags: + kernel32.LoadLibraryExW.restype = ctypes.c_void_p + + for dll_path in dll_paths: + os.add_dll_directory(dll_path) + + try: + ctypes.CDLL("vcruntime140.dll") + ctypes.CDLL("msvcp140.dll") + if platform.machine() != "ARM64": + ctypes.CDLL("vcruntime140_1.dll") + except OSError: + print( + textwrap.dedent( + """ + Microsoft Visual C++ Redistributable is not installed, this may lead to the DLL load failure. + It can be downloaded at https://aka.ms/vs/17/release/vc_redist.x64.exe + """ + ).strip() + ) + + dlls = glob.glob(os.path.join(th_dll_path, "*.dll")) + path_patched = False + for dll in dlls: + is_loaded = False + if with_load_library_flags: + res = kernel32.LoadLibraryExW(dll, None, 0x00001100) + last_error = ctypes.get_last_error() + if res is None and last_error != 126: + err = ctypes.WinError(last_error) + err.strerror += ( + f' Error loading "{dll}" or one of its dependencies.' + ) + raise err + elif res is not None: + is_loaded = True + if not is_loaded: + if not path_patched: + os.environ["PATH"] = ";".join(dll_paths + [os.environ["PATH"]]) + path_patched = True + res = kernel32.LoadLibraryW(dll) + if res is None: + err = ctypes.WinError(ctypes.get_last_error()) + err.strerror += ( + f' Error loading "{dll}" or one of its dependencies.' + ) + raise err + + kernel32.SetErrorMode(prev_error_mode) + + _load_dll_libraries() + del _load_dll_libraries + + +def _get_cuda_dep_paths(path: str, lib_folder: str, lib_name: str) -> list[str]: + # Libraries can either be in + # path/nvidia/lib_folder/lib or + # path/nvidia/cuXX/lib (since CUDA 13.0) or + # path/lib_folder/lib + from torch.version import cuda as cuda_version + + nvidia_lib_paths = glob.glob( + os.path.join(path, "nvidia", lib_folder, "lib", lib_name) + ) + if cuda_version is not None: + maj_cuda_version = cuda_version.split(".")[0] + nvidia_lib_paths += glob.glob( + os.path.join(path, "nvidia", f"cu{maj_cuda_version}", "lib", lib_name) + ) + lib_paths = glob.glob(os.path.join(path, lib_folder, "lib", lib_name)) + + return nvidia_lib_paths + lib_paths + + +def _preload_cuda_lib(lib_folder: str, lib_name: str, required: bool = True) -> None: # type: ignore[valid-type] + """Preloads cuda library if it could not be found otherwise.""" + # Should only be called on Linux if default path resolution have failed + if platform.system() != "Linux": + raise AssertionError(f"Should only be called on Linux, got {platform.system()}") + + lib_path = None + for path in sys.path: + candidate_lib_paths = _get_cuda_dep_paths(path, lib_folder, lib_name) + if candidate_lib_paths: + lib_path = candidate_lib_paths[0] + break + if not lib_path and required: + raise ValueError(f"{lib_name} not found in the system path {sys.path}") + if lib_path: + ctypes.CDLL(lib_path) + + +def _preload_cuda_deps(err: OSError | None = None, required: bool = True) -> None: + cuda_libs: list[tuple[str, str]] = [ + # NOTE: Order matters! We must preload libcublasLt BEFORE libcublas to prevent + # libcublas from loading a mismatched system-wide libcublasLt via its RUNPATH. + # Without this, if a different CUDA Toolkit version exists in the system PATH, + # libcublas may load the wrong libcublasLt, causing symbol errors or runtime failures. + ("cublas", "libcublasLt.so.*[0-9]"), + ("cublas", "libcublas.so.*[0-9]"), + ("cudnn", "libcudnn.so.*[0-9]"), + ("cuda_nvrtc", "libnvrtc.so.*[0-9]"), + ("cuda_nvrtc", "libnvrtc-builtins.so.*[0-9]"), + ("cuda_runtime", "libcudart.so.*[0-9]"), + ("cuda_cupti", "libcupti.so.*[0-9]"), + ("cufft", "libcufft.so.*[0-9]"), + ("curand", "libcurand.so.*[0-9]"), + ("nvjitlink", "libnvJitLink.so.*[0-9]"), + ("cusparse", "libcusparse.so.*[0-9]"), + ("cusparselt", "libcusparseLt.so.*[0-9]"), + ("cusolver", "libcusolver.so.*[0-9]"), + ("nccl", "libnccl.so.*[0-9]"), + ("nvshmem", "libnvshmem_host.so.*[0-9]"), + ("cufile", "libcufile.so.*[0-9]"), + ] + # If error is passed, re-raise it if it's not about one of the abovementioned + # libraries + if err is not None and not [ + lib for _, lib in cuda_libs if lib.split(".", 1)[0] in err.args[0] + ]: + raise err + + # Otherwise, try to preload dependencies from site-packages. With + # required=False each lib is best-effort: a partial install that only ships + # some of these wheels (e.g. just a cupti wheel alongside a system CUDA) + # preloads the ones present instead of aborting on the first missing one. + for lib_folder, lib_name in cuda_libs: + _preload_cuda_lib(lib_folder, lib_name, required=required) + + # libnvToolsExt is Optional Dependency + _preload_cuda_lib("nvtx", "libnvToolsExt.so.*[0-9]", required=False) + + +# See Note [Global dependencies] +def _load_global_deps() -> None: + if platform.system() == "Windows": + return + + # Determine the file extension based on the platform + lib_ext = ".dylib" if platform.system() == "Darwin" else ".so" + lib_name = f"libtorch_global_deps{lib_ext}" + here = os.path.abspath(__file__) + global_deps_lib_path = os.path.join(os.path.dirname(here), "lib", lib_name) + + # In scikit-build-core editable installs with redirect mode, native libs are + # installed to the dist package location rather than relative to __file__. + if not os.path.exists(global_deps_lib_path): + try: + from importlib.metadata import distribution + + installed = distribution("torch").locate_file( + os.path.join("torch", "lib", lib_name) + ) + # The importlib metadata SimplePath protocol was missing the exists + # method in older versions; however, the actual Path implementation + # has it and newer versions of importlib metadata have added it to + # the protocol, making the following ignore unnecessary from + # importlib_metadata 7.0.1 and Python 3.13 onwards. + # pyrefly: ignore[missing-attribute] + if installed.exists(): + global_deps_lib_path = str(installed) + except Exception: + pass + + try: + ctypes.CDLL(global_deps_lib_path, mode=ctypes.RTLD_GLOBAL) + # Workaround slim-wheel CUDA dependency bugs in cusparse and cudnn by preloading nvjitlink + # and nvrtc. In CUDA-12.4+ cusparse depends on nvjitlink, but does not have rpath when + # shipped as wheel, which results in OS picking wrong/older version of nvjitlink library + # if `LD_LIBRARY_PATH` is defined, see https://github.com/pytorch/pytorch/issues/138460 + # Similar issue exist in cudnn that dynamically loads nvrtc, unaware of its relative path. + # See https://github.com/pytorch/pytorch/issues/145580 + try: + with open("/proc/self/maps") as f: + _maps = f.read() + + # libtorch_global_deps.so always depends in cudart, check if its installed and loaded + if "libcudart.so" not in _maps: + return + # If all above-mentioned conditions are met, preload CUDA dependencies. + # Only libtorch_global_deps is loaded so far (it pulls libcudart, not + # the rest); libtorch_cpu, which DT_NEEDEDs the other CUDA libs, is + # imported below via torch._C. So be best-effort and front-load any + # component wheels that ARE present now, before that import, so they + # win libtorch_cpu's DT_NEEDED soname lookups (e.g. a newer cupti + # wheel over a system copy). A missing wheel must not abort -- rpath + # will satisfy libtorch_cpu's DT_NEEDED for whatever isn't preloaded. + _preload_cuda_deps(required=False) + except Exception: + pass + + except OSError as err: + # Can happen for wheel with cuda libs as PYPI deps + # As PyTorch is not purelib, but nvidia-*-cu12 is + _preload_cuda_deps(err) + ctypes.CDLL(global_deps_lib_path, mode=ctypes.RTLD_GLOBAL) + + +if (USE_RTLD_GLOBAL_WITH_LIBTORCH or os.getenv("TORCH_USE_RTLD_GLOBAL")) and ( + platform.system() != "Windows" +): + # Do it the hard way. You might want to load libtorch with RTLD_GLOBAL in a + # few circumstances: + # + # 1. You're in a build environment (e.g., fbcode) where + # libtorch_global_deps is not available, but you still need + # to get mkl to link in with RTLD_GLOBAL or it will just + # not work. + # + # 2. You're trying to run PyTorch under UBSAN and you need + # to ensure that only one copy of libtorch is loaded, so + # vptr checks work properly + # + # If you're using this setting, you must verify that all the libraries + # you load consistently use the same libstdc++, or you may have + # mysterious segfaults. + # + old_flags = sys.getdlopenflags() + sys.setdlopenflags(os.RTLD_GLOBAL | os.RTLD_LAZY) + + from torch._C import * # noqa: F403 + + sys.setdlopenflags(old_flags) + del old_flags + +else: + # Easy way. You want this most of the time, because it will prevent + # C++ symbols from libtorch clobbering C++ symbols from other + # libraries, leading to mysterious segfaults. + # + # If building in an environment where libtorch_global_deps isn't available + # like parts of fbsource, but where RTLD_GLOBAL causes segfaults, you will + # want USE_RTLD_GLOBAL_WITH_LIBTORCH = False and USE_GLOBAL_DEPS = False + # + # See Note [Global dependencies] + if USE_GLOBAL_DEPS: + _load_global_deps() + from torch._C import * # noqa: F403 + + +_PrimType = _TypeVar("_PrimType") +_SymType = _TypeVar("_SymType") +_SymIteT = _TypeVar("_SymIteT") +_BecomesIntPrimType = _TypeVar("_BecomesIntPrimType") +_BecomesIntSymType = _TypeVar("_BecomesIntSymType") +# Operand type for bitwise ops: IntLikeType for SymInt; BoolLikeType for SymBool. +_BitwiseLikeType = _TypeVar("_BitwiseLikeType") +# Operand types that promote the result to SymFloat. _Never for SymFloat +# (no further promotion); float | SymFloat for SymInt and SymBool. +_FloatPromotionType = _TypeVar("_FloatPromotionType") +_LikeNumber: _TypeAlias = "torch.types.Number | torch.types.PySymType" + + +class _SymTypingMagicAlsoBool( + typing.Generic[ + _PrimType, _BecomesIntPrimType, _BecomesIntSymType, _FloatPromotionType + ] +): + # Magic methods installed by torch.fx.experimental.sym_node + # From sym_node: also_bool_magic_methods + + __LikeType: _TypeAlias = ( + _PrimType | _Self | _BecomesIntPrimType | _BecomesIntSymType + ) + _BecomesIntLikeType: _TypeAlias = _BecomesIntPrimType | _BecomesIntSymType + + @_overload + def __eq__(self, other: __LikeType) -> "SymBool": ... + + @_overload + def __eq__(self, other: object) -> builtins.bool: ... + + def __eq__(self, other: object) -> "builtins.bool | SymBool": + raise TypeError("type stub not overridden") + + @_overload + def __ne__(self, other: __LikeType) -> "SymBool": ... + + @_overload + def __ne__(self, other: object) -> builtins.bool: ... + + def __ne__(self, other: object) -> "builtins.bool | SymBool": + raise TypeError("type stub not overridden") + + # bool_becomes_int_magic_methods + + @_overload + def __add__(self, other: __LikeType) -> _BecomesIntSymType: ... + + @_overload + def __add__(self, other: _FloatPromotionType) -> "SymFloat": ... + + def __add__(self, other: object) -> object: + raise TypeError("type stub not overridden") + + # Tensor + SymT -> Tensor + # prim|SymT + SymT -> SymT + @_overload + def __radd__(self, other: "torch.Tensor") -> "torch.Tensor": ... + + @_overload + def __radd__( + self, other: _PrimType | _BecomesIntPrimType | _BecomesIntSymType + ) -> _BecomesIntSymType: ... + + @_overload + def __radd__(self, other: _FloatPromotionType) -> "SymFloat": ... + + def __radd__(self, other: object) -> object: + raise TypeError("type stub not overridden") + + @_overload + def __sub__(self, other: __LikeType) -> _BecomesIntSymType: ... + + @_overload + def __sub__(self, other: _FloatPromotionType) -> "SymFloat": ... + + def __sub__(self, other: object) -> object: + raise TypeError("type stub not overridden") + + # Tensor - SymT = Tensor + # prim|SymT - SymT = SymT + @_overload + def __rsub__(self, other: "torch.Tensor") -> "torch.Tensor": ... + + @_overload + def __rsub__( + self, other: _PrimType | _BecomesIntPrimType | _BecomesIntSymType + ) -> _BecomesIntSymType: ... + + @_overload + def __rsub__(self, other: _FloatPromotionType) -> "SymFloat": ... + + def __rsub__(self, other: object) -> object: + raise TypeError("type stub not overridden") + + @_overload + def __mul__(self, other: __LikeType) -> _BecomesIntSymType: ... + + @_overload + def __mul__(self, other: _FloatPromotionType) -> "SymFloat": ... + + def __mul__(self, other: object) -> object: + raise TypeError("type stub not overridden") + + @_overload + def __rmul__(self, other: __LikeType) -> _BecomesIntSymType: ... + + @_overload + def __rmul__(self, other: _FloatPromotionType) -> "SymFloat": ... + + def __rmul__(self, other: object) -> object: + raise TypeError("type stub not overridden") + + +class _SymTypingMagic( + _SymTypingMagicAlsoBool[_PrimType, _PrimType, _SymType, _FloatPromotionType], + typing.Generic[_PrimType, _SymType, _FloatPromotionType], +): + # Magic methods installed by torch.fx.experimental.sym_node + # From sym_node: + # magic_methods + # - only_float_magic_methods + # - bitwise_ops + # - only_bool_magic_methods + # - also_bool_magic_methods + # - bool_becomes_int_magic_methods + + __LikeType: _TypeAlias = _PrimType | _Self + + # Ordering comparisons: only on ordered types (SymInt/SymFloat), not SymBool. + @_overload + def __ge__(self, other: __LikeType) -> "SymBool": ... + + @_overload + def __ge__(self, other: object) -> builtins.bool: ... + + def __ge__(self, other: object) -> "builtins.bool | SymBool": + raise TypeError("type stub not overridden") + + @_overload + def __gt__(self, other: __LikeType) -> "SymBool": ... + + @_overload + def __gt__(self, other: object) -> builtins.bool: ... + + def __gt__(self, other: object) -> "builtins.bool | SymBool": + raise TypeError("type stub not overridden") + + @_overload + def __le__(self, other: __LikeType) -> "SymBool": ... + + @_overload + def __le__(self, other: object) -> builtins.bool: ... + + def __le__(self, other: object) -> "builtins.bool | SymBool": + raise TypeError("type stub not overridden") + + @_overload + def __lt__(self, other: __LikeType) -> "SymBool": ... + + @_overload + def __lt__(self, other: object) -> builtins.bool: ... + + def __lt__(self, other: object) -> "builtins.bool | SymBool": + raise TypeError("type stub not overridden") + + def __abs__(self) -> _Self: + raise TypeError("type stub not overridden") + + def __ceil__(self) -> "SymInt": + raise TypeError("type stub not overridden") + + def __float_pow__(self, other: _LikeNumber) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __rfloat_pow__(self, other: _LikeNumber) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __float_truediv__(self, other: _LikeNumber) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __rfloat_truediv__(self, other: _LikeNumber) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __floor__(self) -> "SymInt": + raise TypeError("type stub not overridden") + + def __int_floordiv__(self, other: _LikeNumber) -> "SymInt": + raise TypeError("type stub not overridden") + + def __rint_floordiv__(self, other: _LikeNumber) -> "SymInt": + raise TypeError("type stub not overridden") + + def __int_truediv__(self, other: _LikeNumber) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __rint_truediv__(self, other: _LikeNumber) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __lshift__(self, other: "IntLikeType") -> _Self: + raise TypeError("type stub not overridden") + + def __rlshift__(self, other: "IntLikeType") -> _Self: + raise TypeError("type stub not overridden") + + @_overload + def __mod__(self, other: __LikeType) -> _SymType: ... + + @_overload + def __mod__(self, other: _FloatPromotionType) -> "SymFloat": ... + + def __mod__(self, other: object) -> object: + raise TypeError("type stub not overridden") + + @_overload + def __rmod__(self, other: __LikeType) -> _SymType: ... + + @_overload + def __rmod__(self, other: _FloatPromotionType) -> "SymFloat": ... + + def __rmod__(self, other: object) -> object: + raise TypeError("type stub not overridden") + + def __neg__(self) -> _Self: + raise TypeError("type stub not overridden") + + def __pos__(self) -> _Self: + raise TypeError("type stub not overridden") + + def __pow_by_natural__(self, other: "IntLikeType") -> "SymInt": + raise TypeError("type stub not overridden") + + def __rpow_by_natural__(self, other: "IntLikeType") -> "SymInt": + raise TypeError("type stub not overridden") + + def __rshift__(self, other: "IntLikeType") -> _Self: + raise TypeError("type stub not overridden") + + def __rrshift__(self, other: "IntLikeType") -> _Self: + raise TypeError("type stub not overridden") + + def __sym_acos__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __sym_asin__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __sym_atan__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __sym_cos__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __sym_cosh__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __sym_float__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __sym_max__(self, other: _LikeNumber) -> _LikeNumber: + raise TypeError("type stub not overridden") + + def __sym_min__(self, other: _LikeNumber) -> _LikeNumber: + raise TypeError("type stub not overridden") + + def __sym_sin__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __sym_sinh__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __sym_sqrt__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __sym_tan__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __sym_tanh__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def __trunc__(self) -> "SymInt": + raise TypeError("type stub not overridden") + + +class _SymTypingMagicBitwise(typing.Generic[_BitwiseLikeType]): + # Magic methods installed by torch.fx.experimental.sym_node + # From sym_node: bitwise_ops + + def __and__(self, other: _BitwiseLikeType) -> _Self: + raise TypeError("type stub not overridden") + + def __rand__(self, other: _BitwiseLikeType) -> _Self: + raise TypeError("type stub not overridden") + + def __or__(self, other: _BitwiseLikeType) -> _Self: + raise TypeError("type stub not overridden") + + def __ror__(self, other: _BitwiseLikeType) -> _Self: + raise TypeError("type stub not overridden") + + def __xor__(self, other: _BitwiseLikeType) -> _Self: + raise TypeError("type stub not overridden") + + def __rxor__(self, other: _BitwiseLikeType) -> _Self: + raise TypeError("type stub not overridden") + + +class SymInt( + _SymTypingMagic[builtins.int, "SymInt", "FloatLikeType"], + _SymTypingMagicBitwise["IntLikeType"], +): + """ + 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: "_SymNodeLike") -> None: + # This field MUST be named node; C++ binding code assumes that this + # class has a field named node that stores SymNode + self.node = typing.cast("SymNode", node) + + def __bool__(self) -> builtins.bool: + return builtins.bool(self != 0) + + def __int__(self) -> builtins.int: + # pyrefly: ignore[missing-attribute] # duck-typed: not on NestedIntNode/ConstantIntNode/LocalIntNode + return self.node.int_() + + def __index__(self) -> builtins.int: + # pyrefly: ignore[missing-attribute] # duck-typed: not on NestedIntNode/ConstantIntNode/LocalIntNode + return self.node.int_() + + # Magic methods installed by torch.fx.experimental.sym_node + + def __round__(self, ndigits: builtins.int | None = None) -> "SymInt": + return self + + def __truediv__(self, other: object) -> "SymFloat": + if isinstance(other, (builtins.float, SymFloat)): + return sym_float(self).__float_truediv__(other) + if not isinstance(other, (builtins.int, SymInt)): + return NotImplemented # type: ignore[return-value] + return self.__int_truediv__(other) + + def __rtruediv__(self, other: object) -> "SymFloat": + if isinstance(other, (builtins.float, SymFloat)): + return sym_float(self).__rfloat_truediv__(other) + if not isinstance(other, (builtins.int, SymInt)): + return NotImplemented # type: ignore[return-value] + return self.__rint_truediv__(other) + + @_overload + def __floordiv__(self, other: "builtins.int | SymInt") -> "SymInt": ... + + @_overload + def __floordiv__(self, other: "builtins.float | SymFloat") -> "SymFloat": ... + + def __floordiv__(self, other: object) -> "SymInt | SymFloat": + if isinstance(other, (builtins.float, SymFloat)): + return sym_float(math.floor(sym_float(self) / other)) + if not isinstance(other, (builtins.int, SymInt)): + return NotImplemented # type: ignore[return-value] + return self.__int_floordiv__(other) + + @_overload + def __rfloordiv__(self, other: "builtins.int | SymInt") -> "SymInt": ... + + @_overload + def __rfloordiv__(self, other: "builtins.float | SymFloat") -> "SymFloat": ... + + def __rfloordiv__(self, other: object) -> "SymInt | SymFloat": + if isinstance(other, (builtins.float, SymFloat)): + return sym_float(math.floor(other / sym_float(self))) + if not isinstance(other, (builtins.int, SymInt)): + return NotImplemented # type: ignore[return-value] + 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: object) -> "SymInt | SymFloat": + if isinstance(other, (builtins.float, SymFloat)): + return sym_float(self).__pow__(other) + if not isinstance(other, (builtins.int, SymInt)): + return NotImplemented # type: ignore[return-value] + # 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: object) -> "SymInt | SymFloat": + if isinstance(other, (builtins.float, SymFloat)): + return sym_float(self).__rpow__(other) + if not isinstance(other, (builtins.int, SymInt)): + return NotImplemented # type: ignore[return-value] + if self >= 0: # self is exponent + return self.__rpow_by_natural__(other) + else: + return sym_float(self).__rpow__(sym_float(other)) + + def __repr__(self) -> str: + return self.node._graph_repr() + + def _sympy_(self) -> "sympy.Basic": + # pyrefly: ignore[missing-attribute] # duck-typed: not on NestedIntNode/ConstantIntNode/LocalIntNode + return self.node.expr + + def __hash__(self) -> builtins.int: + if self.node.is_nested_int(): + # pyrefly: ignore[missing-attribute] # narrowed by is_nested_int(); only NestedIntNode/SymNode reach here + 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 + + def has_hint(self) -> builtins.bool: + return self.node.has_hint() + + @property + def hint(self) -> builtins.int | None: + return typing.cast(builtins.int | None, self.node.hint) + + @property + def constant(self) -> builtins.int | None: + return typing.cast(builtins.int | None, self.node.constant) + + +class SymFloat(_SymTypingMagic[builtins.float, "SymFloat", _Never]): + """ + 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: "SymNode") -> None: + # 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: object) -> "SymFloat": + if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)): + return NotImplemented # type: ignore[return-value] + return self.__float_truediv__(sym_float(other)) + + def __rtruediv__(self, other: object) -> "SymFloat": + if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)): + return NotImplemented # type: ignore[return-value] + return self.__rfloat_truediv__(sym_float(other)) + + def __floordiv__(self, other: object) -> "SymFloat": + if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)): + return NotImplemented # type: ignore[return-value] + return sym_float(math.floor(self / sym_float(other))) + + def __rfloordiv__(self, other: object) -> "SymFloat": + if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)): + return NotImplemented # type: ignore[return-value] + return sym_float(math.floor(sym_float(other) / self)) + + def __bool__(self) -> builtins.bool: + return self.node.bool_() + + def __float__(self) -> builtins.float: + return self.node.guard_float("", 0) + + def __int__(self) -> builtins.int: + return self.__trunc__().__int__() + + # Symbolic power does NOT work with negative base, this is to avoid + # potential complex outputs + def __pow__(self, other: object) -> "SymFloat": + if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)): + return NotImplemented # type: ignore[return-value] + torch._check(self >= 0) + return self.__float_pow__(other) + + def __rpow__(self, other: object) -> "SymFloat": + if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)): + return NotImplemented # type: ignore[return-value] + torch._check(other >= 0) + return self.__rfloat_pow__(other) + + # Magic methods installed by torch.fx.experimental.sym_node + + @_overload + def __round__(self) -> "SymInt": ... + + @_overload + def __round__(self, ndigits: "IntLikeType") -> "SymFloat": ... + + def __round__(self, ndigits: "IntLikeType | None" = None) -> "SymFloat | SymInt": + raise TypeError("type stub not overridden") + + # def __sym_int__(self) -> "SymInt": + # raise TypeError("type stub not overridden") + + def __sym_log2__(self) -> "SymFloat": + raise TypeError("type stub not overridden") + + def is_integer(self) -> builtins.bool: + """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) -> str: + return self.node._graph_repr() + + def _sympy_(self) -> "sympy.Basic": + return self.node.expr + + def __hash__(self) -> builtins.int: + 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() + + def has_hint(self) -> builtins.bool: + return self.node.has_hint() + + @property + def hint(self) -> builtins.float | None: + return typing.cast(builtins.float | None, self.node.hint) + + @property + def constant(self) -> builtins.float | None: + return typing.cast(builtins.float | None, self.node.constant) + + +class SymBool( + _SymTypingMagicAlsoBool[builtins.bool, builtins.int, "SymInt", "FloatLikeType"], + _SymTypingMagicBitwise["BoolLikeType"], +): + """ + 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: "SymNode") -> None: + # 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) -> builtins.bool: + return self.node.bool_() + + def __int__(self) -> builtins.int: + return builtins.int(self.node.bool_()) + + # Magic methods installed by torch.fx.experimental.sym_node + + # 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: _SymIteT, else_val: _SymIteT) -> _SymIteT: + raise TypeError("type stub not overridden") + + def __repr__(self) -> str: + return self.node._graph_repr() + + def _sympy_(self) -> "sympy.Basic": + return self.node.expr + + def __hash__(self) -> builtins.int: + if self.node.is_constant(): + return hash(self.node.bool_()) + else: + # Force specialization + return hash(builtins.bool(self)) + + def __sym_float__(self) -> "SymFloat": + """ + Provides a SymFloat representation (0.0 or 1.0) for this SymBool. + Called by torch.sym_float() when casting SymBool to float. + """ + from torch.fx.experimental.sym_node import wrap_node + + # pyrefly: ignore[bad-return] + return wrap_node(self.node.sym_float()) + + @property + def hint(self) -> builtins.bool | None: + return typing.cast(builtins.bool | None, self.node.hint) + + @property + def constant(self) -> builtins.bool | None: + return typing.cast(builtins.bool | None, self.node.constant) + + +@_overload +def sym_not(a: "BoolLikeType") -> "BoolLikeType": ... + + +@_overload +def sym_not(a: object) -> object: ... + + +def sym_not(a: object) -> object: + r"""SymInt-aware utility for logical negation. + + Args: + a (SymBool or bool): Object to negate + """ + import sympy + + if overrides.has_torch_function_unary(a): + # pyrefly: ignore[bad-argument-type] + return overrides.handle_torch_function(sym_not, (a,), a) + if hasattr(a, "__sym_not__"): + return a.__sym_not__() # type: ignore[attr-defined] + if isinstance(a, sympy.Basic): + return ~a # type: ignore[operator] + return not a + + +@_overload +def sym_float(a: "PySymType") -> "SymFloat": ... + + +@_overload +def sym_float(a: object) -> "FloatLikeType": ... + + +def sym_float(a: object) -> "FloatLikeType": + r"""SymInt-aware utility for float casting. + + Args: + a (SymInt, SymFloat, or object): Object to cast + """ + if overrides.has_torch_function_unary(a): + # pyrefly: ignore[bad-argument-type] + return overrides.handle_torch_function(sym_float, (a,), a) + if isinstance(a, SymFloat): + return a + elif hasattr(a, "__sym_float__"): + return a.__sym_float__() # type: ignore[attr-defined] + return builtins.float(a) # type: ignore[arg-type] + + +@_overload +def sym_int(a: "PySymType") -> "IntLikeType": ... + + +@_overload +def sym_int(a: object) -> builtins.int: ... + + +def sym_int(a: object) -> "IntLikeType": + r"""SymInt-aware utility for int casting. + + Args: + a (SymInt, SymFloat, or object): Object to cast + """ + if overrides.has_torch_function_unary(a): + # pyrefly: ignore[bad-argument-type] + 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[arg-type] + + +@_overload +def sym_max(a: "IntLikeType", b: "IntLikeType") -> "IntLikeType": ... + + +@_overload +def sym_max( + a: "IntLikeType | FloatLikeType", b: "IntLikeType | FloatLikeType" +) -> "FloatLikeType": ... + + +def sym_max( + a: "IntLikeType | FloatLikeType", b: "IntLikeType | FloatLikeType" +) -> "IntLikeType | FloatLikeType": + """ + 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)): + # pyrefly: ignore[bad-argument-type] + return overrides.handle_torch_function(sym_max, (a, b), a, b) + if isinstance(a, (SymInt, SymFloat)): + return a.__sym_max__(b) # type: ignore[return-value] + 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) # type: ignore[return-value] + # TODO: Probably can make bool work too, just lazy + + all_types, float_types = __all_and_float_types() + + if not isinstance(a, all_types): + raise AssertionError(f"expected {all_types}, got {type(a)}") + if not isinstance(b, all_types): + raise AssertionError(f"expected {all_types}, got {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 + + +@_overload +def sym_min(a: "IntLikeType", b: "IntLikeType") -> "IntLikeType": ... + + +@_overload +def sym_min( + a: "IntLikeType | FloatLikeType", b: "IntLikeType | FloatLikeType" +) -> "FloatLikeType": ... + + +def sym_min( + a: "IntLikeType | FloatLikeType", b: "IntLikeType | FloatLikeType" +) -> "IntLikeType | FloatLikeType": + """SymInt-aware utility for min().""" + if overrides.has_torch_function((a, b)): + # pyrefly: ignore[bad-argument-type] + return overrides.handle_torch_function(sym_min, (a, b), a, b) + if isinstance(a, (SymInt, SymFloat)): + return a.__sym_min__(b) # type: ignore[return-value] + elif isinstance(b, (SymInt, SymFloat)): + return b.__sym_min__(a) # type: ignore[return-value] + + all_types, float_types = __all_and_float_types() + + if not isinstance(a, all_types): + raise AssertionError(f"expected {all_types}, got {type(a)}") + if not isinstance(b, all_types): + raise AssertionError(f"expected {all_types}, got {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: "IntLikeType | _Sequence[IntLikeType]", +) -> "IntLikeType": + """ + N-ary add which is faster to compute for long lists than iterated binary + addition. Only does something special for integers. + + Accepts both ``sym_sum([a, b, c])`` and ``sym_sum(a, b, c)``. + """ + # Normalise: accept both sym_sum([a, b, c]) and sym_sum(a, b, c). + items: _Sequence[IntLikeType] = args # type: ignore[assignment] + if len(args) == 1 and isinstance(args[0], (list, tuple)): + items = args[0] + + if overrides.has_torch_function(items): + return overrides.handle_torch_function(sym_sum, items, items) + + found = None + for a in items: + if not isinstance(a, (SymInt, builtins.int)): + return builtins.sum(items) + if isinstance(a, SymInt): + found = a.node + if found is None: + return builtins.sum(items) + + from torch.fx.experimental.sym_node import to_node, wrap_node + + # pyrefly: ignore[missing-attribute, bad-argument-type, bad-return] # found is a SymNode in practice (LocalIntNode also has sym_sum) + return wrap_node(found.sym_sum([to_node(found, a) for a in items])) + + +# Drop in replacement for math.sqrt, math.sin, math.cos etc +def _get_sym_math_fn(name: str) -> _Callable[[_Any], _Any]: + def fn(a: _Any) -> _Any: + 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: "BoolLikeType", t: _SymIteT, f: _SymIteT) -> _SymIteT: + """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) + if not isinstance(b, (SymBool, builtins.bool)): + raise AssertionError(f"expected SymBool or bool, got {type(b)}") + if type(t) is not type(f): + raise AssertionError(f"type mismatch: {type(t)} vs {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: "IntLikeType") -> "IntLikeType": + return typing.cast("IntLikeType", torch.tensor(expr).item()) + + +# Check to see if we can load C extensions, and if not provide some guidance +# on what the problem might be. +try: + # _initExtension is chosen (arbitrarily) as a sentinel. + from torch._C import _initExtension +except ImportError: + import torch._C as _C_for_compiled_check + + if _C_for_compiled_check.__file__ is None: + raise ImportError( + textwrap.dedent( + """ + Failed to load PyTorch C extensions: + It appears that PyTorch has loaded the `torch/_C` folder + of the PyTorch repository rather than the C extensions which + are expected in the `torch._C` namespace. This can occur when + using the `install` workflow. e.g. + $ python -m pip install --no-build-isolation -v . && python -c "import torch" + + This error can generally be solved using the `develop` workflow + $ python -m pip install --no-build-isolation -v -e . && python -c "import torch" # This should succeed + or by running Python from a different directory. + """ + ).strip() + ) from None + raise # If __file__ is not None the cause is unknown, so just re-raise. + +# The torch._C submodule is already loaded via `from torch._C import *` above +# Make an explicit reference to the _C submodule to appease linters +from torch import _C as _C + + +__name, __obj = "", None +for __name in dir(_C): + if __name[0] != "_" and not __name.endswith("Base"): + __all__.append(__name) + __obj = getattr(_C, __name) + if callable(__obj) or inspect.isclass(__obj): + if __obj.__module__ != __name__: # "torch" + # TODO: fix their module from C++ side + if __name not in { + "DisableTorchFunctionSubclass", + "DisableTorchFunction", + "Generator", + }: + __obj.__module__ = __name__ # "torch" + elif __name == "TensorBase": + # issue 109438 / pr 109940. Prevent TensorBase from being copied into torch. + delattr(sys.modules[__name__], __name) + +del __name, __obj + +if not TYPE_CHECKING: + # issue 38137 and python issue 43367. Submodules of a C extension are + # non-standard, and attributes of those submodules cannot be pickled since + # pickle expect to be able to import them as "from _C.sub import attr" + # which fails with "_C is not a package + def _import_extension_to_sys_modules(module, memo=None): + if memo is None: + memo = set() + if module in memo: + return + memo.add(module) + module_name = module.__name__ + for name in dir(module): + member = getattr(module, name) + member_name = getattr(member, "__name__", "") + if inspect.ismodule(member) and member_name.startswith(module_name): + sys.modules.setdefault(member_name, member) + # Recurse for submodules (e.g., `_C._dynamo.eval_frame`) + _import_extension_to_sys_modules(member, memo) + + _import_extension_to_sys_modules(_C) + del _import_extension_to_sys_modules + +################################################################################ +# Define basic utilities +################################################################################ + + +def typename(obj: object, /) -> 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__ # type: ignore[attr-defined] + elif hasattr(obj, "__name__"): + qualname = obj.__name__ # type: ignore[attr-defined] + else: + module = obj.__class__.__module__ or "" + qualname = obj.__class__.__qualname__ + + if module in {"", "builtins"}: + return qualname + return f"{module}.{qualname}" + + +def is_tensor(obj: object, /) -> _TypeIs["torch.Tensor"]: + r"""Returns True if `obj` is a PyTorch tensor. + + Args: + obj (object): Object to test + Example:: + + >>> x = torch.tensor([1, 2, 3]) + >>> torch.is_tensor(x) + True + + """ + return isinstance(obj, torch.Tensor) + + +def is_storage(obj: object, /) -> _TypeGuard["TypedStorage | UntypedStorage"]: + r"""Returns True if `obj` is a PyTorch storage object. + + Args: + obj (Object): Object to test + Example:: + + >>> import torch + >>> # UntypedStorage (recommended) + >>> tensor = torch.tensor([1, 2, 3]) + >>> storage = tensor.untyped_storage() + >>> torch.is_storage(storage) + True + >>> + >>> # TypedStorage (legacy) + >>> warnings.filterwarnings("ignore", message=".*TypedStorage is deprecated") # docs: hide + >>> typed_storage = torch.TypedStorage(5, dtype=torch.float32) + >>> torch.is_storage(typed_storage) + True + >>> + >>> # regular tensor (should return False) + >>> torch.is_storage(tensor) + False + >>> + >>> # non-storage object + >>> torch.is_storage([1, 2, 3]) + False + """ + return type(obj) in _storage_classes + + +_GLOBAL_DEVICE_CONTEXT = threading.local() + + +def get_default_device() -> "torch.device": + r"""Gets the default ``torch.Tensor`` to be allocated on ``device``""" + global _GLOBAL_DEVICE_CONTEXT + + from torch.overrides import _get_current_function_mode_stack + from torch.utils._device import DeviceContext + + def _get_device_with_index(device: "torch.device") -> "torch.device": + if device.index is not None: + return device + else: + # TODO: Call like get_device_index() method corresponding to + # each device type + return torch.tensor([]).device + + # Get device from any active DeviceContext. + device_mode = next( + filter( + lambda mode: isinstance(mode, DeviceContext), + reversed(_get_current_function_mode_stack()), + ), + None, + ) + if device_mode: + device = device_mode.device + return _get_device_with_index(device) + + device_context = getattr(_GLOBAL_DEVICE_CONTEXT, "device_context", None) + if device_context is not None: + return _get_device_with_index(device_context.device) + return torch.device("cpu") + + +def set_default_device(device: "Device") -> None: + """Sets the default ``torch.Tensor`` to be allocated on ``device``. This + does not affect factory function calls which are called with an explicit + ``device`` argument. Factory calls will be performed as if they + were passed ``device`` as an argument. + + To only temporarily change the default device instead of setting it + globally, use ``with torch.device(device):`` instead. + + The default device is initially ``cpu``. If you set the default tensor + device to another device (e.g., ``cuda``) without a device index, tensors + will be allocated on whatever the current device for the device type, + even after :func:`torch.cuda.set_device` is called. + + .. warning:: + + This function imposes a slight performance cost on every Python + call to the torch API (not just factory functions). If this + is causing problems for you, please comment on + https://github.com/pytorch/pytorch/issues/92701 + + .. note:: + + This doesn't affect functions that create tensors that share the same memory as the input, like: + :func:`torch.from_numpy` and :func:`torch.frombuffer` + + Args: + device (:class:`torch.device`, str, int, or None): the device to set as + default, or ``None`` to clear the override. An integer is + interpreted as an index for the current accelerator. + + Example:: + + >>> # xdoctest: +SKIP("requires cuda, changes global state") + >>> torch.get_default_device() + device(type='cpu') + >>> torch.set_default_device('cuda') # current device is 0 + >>> torch.get_default_device() + device(type='cuda', index=0) + >>> torch.set_default_device('cuda') + >>> torch.cuda.set_device('cuda:1') # current device is 1 + >>> torch.get_default_device() + device(type='cuda', index=1) + >>> torch.set_default_device('cuda:1') + >>> torch.get_default_device() + device(type='cuda', index=1) + + """ + global _GLOBAL_DEVICE_CONTEXT + if hasattr(_GLOBAL_DEVICE_CONTEXT, "device_context"): + device_context = _GLOBAL_DEVICE_CONTEXT.device_context + if device_context is not None: + device_context.__exit__(None, None, None) + + if device is None: + device_context = None + else: + from torch.utils._device import DeviceContext + + device_context = DeviceContext(device) + device_context.__enter__() + _GLOBAL_DEVICE_CONTEXT.device_context = device_context + + +def set_default_tensor_type(t: type["torch.Tensor"] | str, /) -> None: + r""" + .. warning:: + + This function is deprecated as of PyTorch 2.1, please use :func:`torch.set_default_dtype()` and + :func:`torch.set_default_device()` as alternatives. + + Sets the default ``torch.Tensor`` type to floating point tensor type + ``t``. This type will also be used as default floating point type for + type inference in :func:`torch.tensor`. + + The default floating point tensor type is initially ``torch.FloatTensor``. + + Args: + t (type or string): the floating point tensor type or its name + + Example:: + + >>> # xdoctest: +SKIP("Other tests may have changed the default type. Can we reset it?") + >>> torch.tensor([1.2, 3]).dtype # initial default for floating point is torch.float32 + torch.float32 + >>> torch.set_default_tensor_type(torch.DoubleTensor) + >>> torch.tensor([1.2, 3]).dtype # a new floating point tensor + torch.float64 + + """ + if isinstance(t, str): + t = _import_dotted_name(t) + _C._set_default_tensor_type(t) + + +def set_default_dtype(d: "torch.dtype", /) -> None: + r""" + + Sets the default floating point dtype to :attr:`d`. Supports floating point dtype + as inputs. Other dtypes will cause torch to raise an exception. + + When PyTorch is initialized its default floating point dtype is torch.float32, + and the intent of set_default_dtype(torch.float64) is to facilitate NumPy-like + type inference. The default floating point dtype is used to: + + 1. Implicitly determine the default complex dtype. When the default floating type is float16, + the default complex dtype is complex32. For float32, the default complex dtype is complex64. + For float64, it is complex128. For bfloat16, an exception will be raised because + there is no corresponding complex type for bfloat16. + 2. Infer the dtype for tensors constructed using Python floats or complex Python + numbers. See examples below. + 3. Determine the result of type promotion between bool and integer tensors and + Python floats and complex Python numbers. + + Args: + d (:class:`torch.dtype`): the floating point dtype to make the default. + + Example: + >>> # xdoctest: +SKIP("Other tests may have changed the default type. Can we reset it?") + >>> # initial default for floating point is torch.float32 + >>> # Python floats are interpreted as float32 + >>> torch.tensor([1.2, 3]).dtype + torch.float32 + >>> # initial default for floating point is torch.complex64 + >>> # Complex Python numbers are interpreted as complex64 + >>> torch.tensor([1.2, 3j]).dtype + torch.complex64 + + >>> torch.set_default_dtype(torch.float64) + >>> # Python floats are now interpreted as float64 + >>> torch.tensor([1.2, 3]).dtype # a new floating point tensor + torch.float64 + >>> # Complex Python numbers are now interpreted as complex128 + >>> torch.tensor([1.2, 3j]).dtype # a new complex tensor + torch.complex128 + + >>> torch.set_default_dtype(torch.float16) + >>> # Python floats are now interpreted as float16 + >>> torch.tensor([1.2, 3]).dtype # a new floating point tensor + torch.float16 + >>> # Complex Python numbers are now interpreted as complex128 + >>> torch.tensor([1.2, 3j]).dtype # a new complex tensor + torch.complex32 + + """ + _C._set_default_dtype(d) + + +def use_deterministic_algorithms( + mode: builtins.bool, + *, + warn_only: builtins.bool = False, +) -> None: + r"""Sets whether PyTorch operations must use "deterministic" + algorithms. That is, algorithms which, given the same input, and when + run on the same software and hardware, always produce the same output. + When enabled, operations will use deterministic algorithms when available, + and if only nondeterministic algorithms are available they will throw a + :class:`RuntimeError` when called. + + .. note:: This setting alone is not always enough to make an application + reproducible. Refer to :ref:`reproducibility` for more information. + + .. note:: :func:`torch.set_deterministic_debug_mode` offers an alternative + interface for this feature. + + The following normally-nondeterministic operations will act + deterministically when ``mode=True``: + + * :class:`torch.nn.Conv1d` when called on CUDA tensor + * :class:`torch.nn.Conv2d` when called on CUDA tensor + * :class:`torch.nn.Conv3d` when called on CUDA tensor + * :class:`torch.nn.ConvTranspose1d` when called on CUDA tensor + * :class:`torch.nn.ConvTranspose2d` when called on CUDA tensor + * :class:`torch.nn.ConvTranspose3d` when called on CUDA tensor + * :class:`torch.nn.ReplicationPad1d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.ReplicationPad2d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.ReplicationPad3d` when attempting to differentiate a CUDA tensor + * :func:`torch.bmm` when called on sparse-dense CUDA tensors + * :func:`torch.cumsum` when called on a CUDA tensor when dtype is floating point or complex + * :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 + * :class:`torch.nn.MaxPool3d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.Embedding` when attempting to differentiate a 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.AdaptiveMaxPool2d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.FractionalMaxPool2d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.FractionalMaxPool3d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.MaxUnpool1d` + * :class:`torch.nn.MaxUnpool2d` + * :class:`torch.nn.MaxUnpool3d` + * :func:`torch.nn.functional.interpolate` when attempting to differentiate a CUDA tensor + and one of the following modes is used: + + - ``linear`` + - ``bilinear`` + - ``bicubic`` + - ``trilinear`` + + * :class:`torch.nn.ReflectionPad1d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.ReflectionPad2d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.ReflectionPad3d` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.NLLLoss` when called on a CUDA tensor + * :class:`torch.nn.CTCLoss` when attempting to differentiate a CUDA tensor + * :class:`torch.nn.EmbeddingBag` when attempting to differentiate a CUDA tensor when + ``mode='max'`` + * :func:`torch.Tensor.put_` when ``accumulate=False`` + * :func:`torch.Tensor.put_` when ``accumulate=True`` and called on a CUDA tensor + * :func:`torch.histc` when called on a CUDA tensor + * :func:`torch.bincount` when called on a CUDA tensor and ``weights`` + tensor is given + * :func:`torch.median` with indices output when called on a CUDA tensor + * :func:`torch.nn.functional.grid_sample` when attempting to differentiate a CUDA tensor + * :func:`torch.Tensor.scatter_reduce` when ``reduce='prod'`` and called on CUDA tensor + * :func:`torch.Tensor.resize_` when called with a quantized tensor + + In addition, several operations fill uninitialized memory when this setting + is turned on and when + :attr:`torch.utils.deterministic.fill_uninitialized_memory` is turned on. + See the documentation for that attribute for more information. + + Note that deterministic operations tend to have worse performance than + nondeterministic operations. + + + When this setting is turned on, the Inductor deterministic mode is also tuned on + automatically. In deterministic mode, Inductor would avoid doing on device benchmarking + that affect numerics. This includes: + + - don't pad matmul input shapes. Without enabling deterministic mode, Inductor would do + benchmarking to check if padding matmul shape is beneficial. + - don't autotune templates. Inductor has templates for kernels like matmul/conv/attention. + Without enabling deterministic mode, Inductor would do autotuning to + pick the best configs for those templates and adopt it if it's faster + than the kernel in eager mode. In deterministic mode, we pick the eager kernel. + - don't autotune triton configs for reduction. Reduction numerics are + very sensitive to triton configs. In deterministic mode, Inductor + will use some heuristics to pick the most promising configs rather + than do autotuning. + - Skip autotuning for reduction in coordinate descent tuning. + - Don't benchmark for the computation/communication reordering pass + - Disable the feature that dynamically scale down RBLOCK triton config for higher + occupancy. + + + .. note:: + + This flag does not detect or prevent nondeterministic behavior caused + by calling an inplace operation on a tensor with an internal memory + overlap or by giving such a tensor as the :attr:`out` argument for an + operation. In these cases, multiple writes of different data may target + a single memory location, and the order of writes is not guaranteed. + + Args: + mode (:class:`bool`): If True, makes potentially nondeterministic + operations switch to a deterministic algorithm or throw a runtime + error. If False, allows nondeterministic operations. + + Keyword args: + warn_only (:class:`bool`, optional): If True, operations that do not + have a deterministic implementation will throw a warning instead of + an error. Default: ``False`` + + Example:: + + >>> # xdoctest: +SKIP + >>> torch.use_deterministic_algorithms(True) + + # Backward mode nondeterministic error + >>> torch.nn.AvgPool3d(1)(torch.randn(3, 4, 5, 6, requires_grad=True).cuda()).sum().backward() + ... + RuntimeError: avg_pool3d_backward_cuda does not have a deterministic implementation... + """ + import torch._inductor.config as inductor_config + + inductor_config.deterministic = mode + _C._set_deterministic_algorithms(mode, warn_only=warn_only) + + +def are_deterministic_algorithms_enabled() -> builtins.bool: + r"""Returns True if the global deterministic flag is turned on. Refer to + :func:`torch.use_deterministic_algorithms` documentation for more details. + """ + return _C._get_deterministic_algorithms() + + +def is_deterministic_algorithms_warn_only_enabled() -> builtins.bool: + r"""Returns True if the global deterministic flag is set to warn only. + Refer to :func:`torch.use_deterministic_algorithms` documentation for more + details. + """ + return _C._get_deterministic_algorithms_warn_only() + + +def set_deterministic_debug_mode(debug_mode: builtins.int | str) -> None: + r"""Sets the debug mode for deterministic operations. + + .. note:: This is an alternative interface for + :func:`torch.use_deterministic_algorithms`. Refer to that function's + documentation for details about affected operations. + + Args: + debug_mode(str or int): If "default" or 0, don't error or warn on + nondeterministic operations. If "warn" or 1, warn on + nondeterministic operations. If "error" or 2, error on + nondeterministic operations. + """ + + # NOTE: builtins.int is used here because int in this scope resolves + # to torch.int + if not isinstance(debug_mode, (builtins.int, str)): + raise TypeError(f"debug_mode must be str or int, but got {type(debug_mode)}") + + if isinstance(debug_mode, str): + if debug_mode == "default": + debug_mode = 0 + elif debug_mode == "warn": + debug_mode = 1 + elif debug_mode == "error": + debug_mode = 2 + else: + raise RuntimeError( + "invalid value of debug_mode, expected one of `default`, " + f"`warn`, `error`, but got {debug_mode}" + ) + + if debug_mode == 0: + _C._set_deterministic_algorithms(False) + elif debug_mode == 1: + _C._set_deterministic_algorithms(True, warn_only=True) + elif debug_mode == 2: + _C._set_deterministic_algorithms(True) + else: + raise RuntimeError( + f"invalid value of debug_mode, expected 0, 1, or 2, but got {debug_mode}" + ) + + +def get_deterministic_debug_mode() -> builtins.int: + r"""Returns the current value of the debug mode for deterministic + operations. Refer to :func:`torch.set_deterministic_debug_mode` + documentation for more details. + """ + + if _C._get_deterministic_algorithms(): + if _C._get_deterministic_algorithms_warn_only(): + return 1 + else: + return 2 + else: + return 0 + + +def get_float32_matmul_precision() -> str: + r"""Returns the current value of float32 matrix multiplication precision. Refer to + :func:`torch.set_float32_matmul_precision` documentation for more details. + """ + return _C._get_float32_matmul_precision() + + +def set_float32_matmul_precision(precision: str) -> None: + r"""Sets the internal precision of float32 matrix multiplications. + + Running float32 matrix multiplications in lower precision may significantly increase + performance, and in some programs the loss of precision has a negligible impact. + + Supports three settings: + + * "highest", float32 matrix multiplications use the float32 datatype (24 mantissa + bits with 23 bits explicitly stored) for internal computations. + * "high", float32 matrix multiplications either use the TensorFloat32 datatype (10 + mantissa bits explicitly stored) or treat each float32 number as the sum of two bfloat16 numbers + (approximately 16 mantissa bits with 14 bits explicitly stored), if the appropriate fast matrix multiplication + algorithms are available. Otherwise float32 matrix multiplications are computed + as if the precision is "highest". See below for more information on the bfloat16 + approach. + * "medium", float32 matrix multiplications use the bfloat16 datatype (8 mantissa + bits with 7 bits explicitly stored) for internal computations, if a fast matrix multiplication algorithm + using that datatype internally is available. Otherwise float32 + matrix multiplications are computed as if the precision is "high". + + When using "high" precision, float32 multiplications may use a bfloat16-based algorithm + that is more complicated than simply truncating to some smaller number mantissa bits + (e.g. 10 for TensorFloat32, 7 for bfloat16 explicitly stored). Refer to [Henry2019]_ for a complete + description of this algorithm. To briefly explain here, the first step is to realize + that we can perfectly encode a single float32 number as the sum of three bfloat16 + numbers (because float32 has 23 mantissa bits while bfloat16 has 7 explicitly stored, and both have the + same number of exponent bits). This means that the product of two float32 numbers can + be exactly given by the sum of nine products of bfloat16 numbers. We can then trade + accuracy for speed by dropping some of these products. The "high" precision algorithm + specifically keeps only the three most significant products, which conveniently excludes + all of the products involving the last 8 mantissa bits of either input. This means that + we can represent our inputs as the sum of two bfloat16 numbers rather than three. + Because bfloat16 fused-multiply-add (FMA) instructions are typically >10x faster than + float32 ones, it's faster to do three multiplications and 2 additions with bfloat16 + precision than it is to do a single multiplication with float32 precision. + + .. [Henry2019] http://arxiv.org/abs/1904.06376 + + .. note:: + + This does not change the output dtype of float32 matrix multiplications, + it controls how the internal computation of the matrix multiplication is performed. + + .. note:: + + This does not change the precision of convolution operations. Other flags, + like `torch.backends.cudnn.allow_tf32`, may control the precision of convolution + operations. + + .. note:: + + This flag currently only affects one native device type: CUDA. + If "high" or "medium" are set then the TensorFloat32 datatype will be used + when computing float32 matrix multiplications, equivalent to setting + `torch.backends.cuda.matmul.allow_tf32 = True`. When "highest" (the default) + is set then the float32 datatype is used for internal computations, equivalent + to setting `torch.backends.cuda.matmul.allow_tf32 = False`. + + Args: + precision(str): can be set to "highest" (default), "high", or "medium" (see above). + + """ + _C._set_float32_matmul_precision(precision) + + +def set_warn_always(b: builtins.bool, /) -> None: + r"""When this flag is False (default) then some PyTorch warnings may only + appear once per process. This helps avoid excessive warning information. + Setting it to True causes these warnings to always appear, which may be + helpful when debugging. + + Args: + b (:class:`bool`): If True, force warnings to always be emitted + If False, set to the default behaviour + """ + _C._set_warnAlways(b) + + +def is_warn_always_enabled() -> builtins.bool: + r"""Returns True if the global warn_always flag is turned on. Refer to + :func:`torch.set_warn_always` documentation for more details. + """ + return _C._get_warnAlways() + + +################################################################################ +# Define error checking functions +################################################################################ + +# These error checking functions must be kept consistent with their C++ +# equivalents. Their C++ equivalents are mentioned where applicable. + + +def _check_with( + error_type: type[BaseException], + cond: builtins.bool | SymBool, + message: _LiteralString | _Callable[[], object] | None, +) -> None: + if not isinstance(cond, (builtins.bool, SymBool)): + if isinstance(cond, torch.Tensor): + raise TypeError( + "cond must be a bool, but got a Tensor. " + "For tensor conditions, use torch._check_tensor_all() " + "to assert that all elements are true." + ) + 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 + if not issubclass(error_type, Exception) or issubclass(error_type, Warning): + raise AssertionError( + f"error_type must be a subclass of Exception but not Warning, got {error_type}" + ) + + 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: + # message may be a callable (deferred construction) or a plain + # str/object; both are accepted. + message_evaluated = str(message() if callable(message) else message) + + raise error_type(message_evaluated) + + +def _check( + cond: builtins.bool | SymBool, + message: _LiteralString | _Callable[[], object] | None = None, +) -> None: + 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 (LiteralString or Callable, optional): A literal string, or a + callable that returns a string or an object with a ``__str__()`` + method, to be used as the error message. Use the callable form for a + dynamically constructed message. Default: ``None`` + """ + _check_with(RuntimeError, cond, message) + + +@_deprecated( + "_check_is_size will be removed in a future PyTorch release along with guard_size_oblivious. \ + Use _check(i >= 0) instead.", + category=FutureWarning, +) +def _check_is_size( + i: "IntLikeType", + message: _LiteralString | _Callable[[], object] | None = None, + *, + max: "IntLikeType | None" = None, +) -> 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) # type: ignore[arg-type] + + if max is not None: + _check(i <= max, message) + + from torch.fx.experimental.symbolic_shapes import _advise_is_bounded + + _advise_is_bounded(i, max) # type: ignore[arg-type] + + +def _check_index( + cond: builtins.bool | SymBool, + message: _LiteralString | _Callable[[], object] | None = None, +) -> None: + 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 (LiteralString or Callable, optional): A literal string, or a + callable that returns a string or an object with a ``__str__()`` + method, to be used as the error message. Use the callable form for a + dynamically constructed message. Default: ``None`` + """ + _check_with(IndexError, cond, message) + + +def _check_value( + cond: builtins.bool | SymBool, + message: _LiteralString | _Callable[[], object] | None = None, +) -> None: + 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 (LiteralString or Callable, optional): A literal string, or a + callable that returns a string or an object with a ``__str__()`` + method, to be used as the error message. Use the callable form for a + dynamically constructed message. Default: ``None`` + """ + _check_with(ValueError, cond, message) + + +def _check_type( + cond: builtins.bool | SymBool, + message: _LiteralString | _Callable[[], object] | None = None, +) -> None: + 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 (LiteralString or Callable, optional): A literal string, or a + callable that returns a string or an object with a ``__str__()`` + method, to be used as the error message. Use the callable form for a + dynamically constructed message. Default: ``None`` + """ + _check_with(TypeError, cond, message) + + +def _check_not_implemented( + cond: builtins.bool | SymBool, + message: _LiteralString | _Callable[[], object] | None = None, +) -> None: + 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 (LiteralString or Callable, optional): A literal string, or a + callable that returns a string or an object with a ``__str__()`` + method, to be used as the error message. Use the callable form for a + dynamically constructed message. Default: ``None`` + """ + _check_with(NotImplementedError, cond, message) + + +def _check_tensor_all_with( + error_type: type[BaseException], + cond: "torch.Tensor", + message: _LiteralString | _Callable[[], object] | None = None, +) -> None: + 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: "torch.Tensor", + message: _LiteralString | _Callable[[], object] | None = None, +) -> None: + 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 (LiteralString or Callable, optional): A literal string, or a + callable that returns a string or an object with a ``__str__()`` + method, to be used as the error message. Use the callable form for a + dynamically constructed 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) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.uint8 + + +class DoubleStorage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.double + + +class FloatStorage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.float + + +class HalfStorage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.half + + +class LongStorage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.long + + +class IntStorage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.int + + +class ShortStorage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.short + + +class CharStorage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.int8 + + +class BoolStorage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.bool + + +class BFloat16Storage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.bfloat16 + + +class ComplexDoubleStorage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.cdouble + + +class ComplexFloatStorage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.cfloat + + +class QUInt8Storage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.quint8 + + +class QInt8Storage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.qint8 + + +class QInt32Storage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.qint32 + + +class QUInt4x2Storage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.quint4x2 + + +class QUInt2x4Storage(_LegacyStorage): + @classproperty + def dtype(self) -> "torch.dtype": + _warn_typed_storage_removal(stacklevel=3) + return self._dtype + + @classproperty + def _dtype(self) -> "torch.dtype": + return torch.quint2x4 + + +_storage_classes: set[type[TypedStorage | UntypedStorage]] = { + UntypedStorage, + DoubleStorage, + FloatStorage, + LongStorage, + IntStorage, + ShortStorage, + CharStorage, + ByteStorage, + HalfStorage, + BoolStorage, + QUInt8Storage, + QInt8Storage, + QInt32Storage, + BFloat16Storage, + ComplexFloatStorage, + ComplexDoubleStorage, + QUInt4x2Storage, + QUInt2x4Storage, + TypedStorage, +} + +# The _tensor_classes set is initialized by the call to initialize_python_bindings. +_tensor_classes: set[type["torch.Tensor"]] = set() + +# If you edit these imports, please update torch/__init__.py.in as well +from torch import amp as amp, random as random, serialization as serialization +from torch._tensor_str import set_printoptions +from torch.amp import autocast, GradScaler +from torch.random import ( + get_rng_state, + initial_seed, + manual_seed, + seed, + set_rng_state, + thread_safe_generator, +) +from torch.serialization import load, save + + +################################################################################ +# Initialize extension +################################################################################ + + +# Shared memory manager needs to know the exact location of manager executable +def _manager_path() -> bytes: + if platform.system() == "Windows": + return b"" + path = get_file_path("torch", "bin", "torch_shm_manager") + prepare_multiprocessing_environment(get_file_path("torch")) + if not os.path.exists(path): + raise RuntimeError("Unable to find torch_shm_manager at " + path) + return path.encode("utf-8") + + +_C._initExtension(_manager_path()) # pyrefly: ignore[bad-argument-type] + +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( + # pyrefly: ignore [unresolvable-dunder-all] + name + for name in dir(torch) + if isinstance(getattr(torch, name), torch.dtype) +) + +################################################################################ +# Import TorchDynamo's lazy APIs to avoid circular dependencies +################################################################################ + +# needs to be before from torch.functional import * to avoid circular dependencies +from torch._compile import _disable_dynamo # usort: skip + +################################################################################ +# Import interface functions defined in Python +################################################################################ + +# needs to be after the above ATen bindings so we can overwrite from Python side +from torch import _VF as _VF, functional as functional # usort: skip +from torch.functional import * # usort: skip # noqa: F403 + +################################################################################ +# Remove unnecessary members +################################################################################ + +del _StorageBase +del _LegacyStorage + +################################################################################ +# Define _assert +################################################################################ + + +# needs to be before the submodule imports to avoid circular dependencies +def _assert(condition: object, message: object) -> None: + 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 + ) + if not condition: + raise AssertionError(message) + + +################################################################################ +# Import most common subpackages +################################################################################ + +# Use the redundant form so that type checkers know that these are a part of +# the public API. The "regular" import lines are there solely for the runtime +# side effect of adding to the imported module's members for other users. + +# needs to be before import torch.nn as nn to avoid circular dependencies +from torch.autograd import ( # usort: skip + enable_grad as enable_grad, + inference_mode as inference_mode, + no_grad as no_grad, + set_grad_enabled as set_grad_enabled, +) + +from torch import ( + __config__ as __config__, + __future__ as __future__, + _awaits as _awaits, + accelerator as accelerator, + autograd as autograd, + backends as backends, + cpu as cpu, + cuda as cuda, + distributed as distributed, + distributions as distributions, + fft as fft, + futures as futures, + hub as hub, + jit as jit, + linalg as linalg, + mps as mps, + mtia as mtia, + multiprocessing as multiprocessing, + nested as nested, + nn as nn, + optim as optim, + overrides as overrides, + profiler as profiler, + sparse as sparse, + special as special, + testing as testing, + types as types, + utils as utils, + version as version, + xpu as xpu, +) +from torch.signal import windows as windows + + +# Quantized, sparse, AO, etc. should be last to get imported, as nothing +# is expected to depend on them. +from torch import ao as ao # usort: skip + +# nn.quant* depends on ao -- so should be after those. +import torch.nn.intrinsic +import torch.nn.qat +import torch.nn.quantizable +import torch.nn.quantized + + +_C._init_names(list(_storage_classes)) + +# attach docstrings to torch and tensor functions +from torch import _size_docs, _storage_docs, _tensor_docs, _torch_docs + + +del _torch_docs, _tensor_docs, _storage_docs, _size_docs + + +def compiled_with_cxx11_abi() -> builtins.bool: + r"""Returns whether PyTorch was built with _GLIBCXX_USE_CXX11_ABI=1""" + return True + + +from torch import _library as _library, _ops as _ops + + +# Import the ops and classes "namespace" +from torch._ops import ops as ops # usort: skip +from torch._classes import classes as classes # usort: skip + +sys.modules.setdefault(f"{__name__}.ops", ops) +sys.modules.setdefault(f"{__name__}.classes", classes) + +if hasattr(torch._C, "_c10d_init"): + from torch.distributed.distributed_c10d import _register_process_group_opaque_type + + _register_process_group_opaque_type() + del _register_process_group_opaque_type + +# 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, + cholesky, + eig, + lstsq, + matrix_rank, + qr, + solve, +) +from torch.utils.dlpack import from_dlpack, to_dlpack + + +class _TorchCompileInductorWrapper: + compiler_name = "inductor" + + def __init__( + self, + mode: str | None, + options: dict[str, _Any] | None, + dynamic: builtins.bool | None, + name: str | None = None, + ) -> None: + from torch._inductor.compiler_bisector import CompilerBisector + + self.config: dict[str, _Any] = {} + self.dynamic = dynamic + self.name = name + 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: object) -> builtins.bool: + return ( + isinstance(other, _TorchCompileInductorWrapper) + and self.config == other.config + and self.dynamic == other.dynamic + and self.name == other.name + ) + + def apply_mode(self, mode: str | None) -> None: + if mode and mode != "default": + from torch._inductor import list_mode_options + + self.apply_options(list_mode_options(mode, self.dynamic)) + + def apply_options(self, options: dict[str, _Any] | None) -> None: + if not options: + return + + from torch._inductor import config + + current_config: dict[str, _Any] = config.get_config_copy() + + for key, val in options.items(): + attr_name = key.replace("-", "_") + if attr_name not in current_config: + raise RuntimeError( + f"Unexpected optimization option {key}, known options are {list(current_config.keys())}" + ) + attr_type = config.get_type(attr_name) # type: ignore[attr-defined] + # Subscriptable generic types don't support isinstance so skip the type + # check. There doesn't seem to be a good way of checking membership without + # 3rd party libraries. + if _get_origin(attr_type) is None: + if not isinstance(val, attr_type): + val_type_str = type(val).__name__ + expected_type_str = type(current_config[attr_name]).__name__ + raise RuntimeError( + f"Unexpected type of attr {key}, got {val_type_str} should be {expected_type_str}" + ) + self.config[attr_name] = val + + def __call__( + self, + model_: _Any, + inputs_: _Any, + *, + config_patches: dict[str, _Any] | None = None, + ) -> _Any: + from torch._inductor.compile_fx import compile_fx + + all_patches = {**self.config, **(config_patches or {})} + return compile_fx( + model_, + inputs_, + config_patches=all_patches, + compile_region_name=self.name, + ) + + def get_compiler_config(self) -> dict[str, _Any]: + from torch._inductor.compile_fx import get_patched_config_dict + + return get_patched_config_dict(config_patches=self.config) + + def reset(self) -> None: + from torch._inductor import config + + if "triton.cudagraphs" in self.config or config.triton.cudagraphs: + if self.config.get("triton.cudagraphs", True): + from torch._inductor.cudagraph_trees import reset_cudagraph_trees + + reset_cudagraph_trees() + + +class _TorchCompileAOTInductorWrapper(_TorchCompileInductorWrapper): + compiler_name = "aotinductor" + + def __init__( + self, + mode: str | None, + options: dict[str, _Any] | None, + dynamic: builtins.bool | None, + name: str | None = None, + ) -> None: + super().__init__(mode, options, dynamic, name) + self.apply_options({"cpp_wrapper": True}) + self.apply_options({"aot_inductor.package": True}) + + def __call__( + self, + model_: _Any, + inputs_: _Any, + *, + config_patches: dict[str, _Any] | None = None, + ) -> _Any: + from contextlib import nullcontext + from unittest import mock + + from torch._guards import detect_fake_mode + from torch._inductor.virtualized import V + + fake_mode = detect_fake_mode(inputs_) + ctx = ( + mock.patch.object(fake_mode, "allow_non_fake_inputs", True) + if fake_mode + else nullcontext() + ) + with ( + V.set_aot_compilation(True), + ctx, + torch._inductor.config.patch("enable_autograd_for_aot", True), + ): + return super().__call__(model_, inputs_, config_patches=config_patches) + + +class _TorchCompileWrapper: + def __init__( + self, + backend: str | _Callable[..., _Any], + mode: str | None, + options: dict[str, _Any] | None, + dynamic: builtins.bool | None, + ) -> None: + 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: dict[str, _Any] = {} + # 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: object) -> builtins.bool: + 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_: _Any, inputs_: _Any) -> _Any: + return self.compiler_fn(model_, inputs_, **self.kwargs) + + def reset(self) -> None: + if hasattr(self.compiler_fn, "reset"): + self.compiler_fn.reset() + + +_InputT = _ParamSpec("_InputT") +_RetT = _TypeVar("_RetT") + + +@_overload +def compile( + model: _Callable[_InputT, _RetT], + *, + fullgraph: builtins.bool = False, + dynamic: builtins.bool | None = None, + backend: str | _Callable[..., _Any] = "inductor", + mode: str | None = None, + options: dict[str, str | builtins.int | builtins.bool | _Callable[..., _Any]] + | None = None, + name: str | None = None, + disable: builtins.bool = False, + dynamic_shapes: _Any = None, +) -> _Callable[_InputT, _RetT]: ... + + +@_overload +def compile( + model: None = None, + *, + fullgraph: builtins.bool = False, + dynamic: builtins.bool | None = None, + backend: str | _Callable[..., _Any] = "inductor", + mode: str | None = None, + options: dict[str, str | builtins.int | builtins.bool | _Callable[..., _Any]] + | None = None, + name: str | None = None, + disable: builtins.bool = False, + dynamic_shapes: _Any = None, +) -> _Callable[[_Callable[_InputT, _RetT]], _Callable[_InputT, _RetT]]: ... + + +def compile( + model: _Callable[_InputT, _RetT] | None = None, + *, + fullgraph: builtins.bool = False, + dynamic: builtins.bool | None = None, + backend: str | _Callable[..., _Any] | None = None, + mode: str | None = None, + options: dict[str, str | builtins.int | builtins.bool | _Callable[..., _Any]] + | None = None, + name: str | None = None, + disable: builtins.bool = False, + recompile_limit: builtins.int | None = None, + isolate_recompiles: builtins.bool = False, + dynamic_shapes: _Any = None, +) -> ( + _Callable[[_Callable[_InputT, _RetT]], _Callable[_InputT, _RetT]] + | _Callable[_InputT, _RetT] +): + """ + Optimizes given model/function using TorchDynamo and specified backend. + If you are compiling an :class:`torch.nn.Module`, you can also use :meth:`torch.nn.Module.compile` + to compile the module inplace without changing its structure. + + Concretely, for every frame executed within the compiled region, we will attempt + to compile it and cache the compiled result on the code object for future + use. A single frame may be compiled multiple times if previous compiled + results are not applicable for subsequent calls (this is called a "guard + failure"), you can use TORCH_LOGS=guards to debug these situations. + Multiple compiled results can be associated with a frame up to + ``torch._dynamo.config.recompile_limit``, which defaults to 8; at which + point we will fall back to eager. Note that compile caches are per + *code object*, not frame; if you dynamically create multiple copies of a + function, they will all share the same code cache. + + Args: + model (Callable or None): Module/function to optimize + fullgraph (bool): If False (default), torch.compile attempts to discover compilable regions + in the function that it will optimize. If True, then we require that the entire function be + capturable into a single graph. If this is not possible (that is, if there are graph breaks), + then this will raise an error. This also opts into unbacked semantics, notably it will turn on + capture_scalar_outputs and capture_dynamic_output_shape_ops on by default. + dynamic (bool or None): Use dynamic shape tracing. When this is True, we will up-front attempt + to generate a kernel that is as dynamic as possible to avoid recompilations when + sizes change. This may not always work as some operations/optimizations will + force specialization; use TORCH_LOGS=dynamic to debug overspecialization. + When this is False, we will NEVER generate dynamic kernels, we will always specialize. + By default (None), we automatically detect if dynamism has occurred and compile a more + dynamic kernel upon recompile. + backend (str or Callable): backend to be used + + - "inductor" is the default backend, which is a good balance between performance and overhead + + - Non experimental in-tree backends can be seen with `torch._dynamo.list_backends()` + + - Experimental or debug in-tree backends can be seen with `torch._dynamo.list_backends(None)` + + - To register an out-of-tree custom backend: + https://docs.pytorch.org/docs/main/user_guide/torch_compiler/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_LOGS=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 documentation 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()` + name (str or None): Optional identifier for the compiled region. When supported by downstream + tooling, this is surfaced on wrapped compiled-region higher-order operators and other debug metadata. + disable (bool): Turn torch.compile() into a no-op for testing + recompile_limit (int or None): Maximum number of recompilations allowed for this + ``torch.compile()`` call before falling back to eager. If None (default), uses + the global ``torch._dynamo.config.recompile_limit`` (default 8). With + ``fullgraph=True``, exceeding the limit raises ``FailOnRecompileLimitHit``. + isolate_recompiles (bool): If True, this ``torch.compile()`` call tracks + recompilations independently. By default, all ``torch.compile()`` calls on the + same function share a single set of compiled entries, so one call's + recompilations count against every other call's limit. With + ``isolate_recompiles=True``, each call gets its own isolated set of entries. + Lookups for an isolated compile call will still fall back to entries from + non-isolated compile calls (BC-friendly reuse), but new compilations are + stored separately. ``recompile_limit`` is checked per-region; + ``accumulated_recompile_limit`` is a global cap across all regions. + Default-strategy behavior is asymmetric: SKIP decisions (from + ``skip_code``, ``@torch._dynamo.skip``, FX-generated code, etc.) are + inherited by isolated regions — those remain skipped. RUN_ONLY persisted + by a non-isolated region hitting its recompile limit does NOT bleed + into isolated regions — each region manages its own RUN_ONLY state. + Default False. + + Example:: + + @torch.compile(options={"triton.cudagraphs": True}, fullgraph=True) + def foo(x): + return torch.sin(x) + torch.cos(x) + + """ + import sysconfig + + _C._log_api_usage_once("torch.compile") + if sys.version_info >= (3, 15): + raise RuntimeError("torch.compile is not supported on Python 3.15+") + elif sysconfig.get_config_var("Py_GIL_DISABLED") == 1 and sys.version_info < ( + 3, + 13, + 3, + ): + raise RuntimeError( + "torch.compile is not supported on Python < 3.13.3 built with GIL disabled. " + "Please use Python 3.13.3+." + ) + + if backend is None: + from torch._dynamo.backends.registry import get_default_backend + + backend = get_default_backend() + + # Auto-wrap ParamsSpec → ShapesSpec for convenience + if dynamic_shapes is not None: + from torch.fx.experimental.dynamic_spec import ParamsSpec, ShapesSpec + + if isinstance(dynamic_shapes, ParamsSpec): + dynamic_shapes = ShapesSpec(dynamic_shapes) + + # If ``model`` carries an ``@dynamic_spec(...)`` decorator, the attached + # ``ShapesSpec`` is used as ``dynamic_shapes``. Passing both raises. + if model is not None: + from torch.fx.experimental.dynamic_spec import _resolve_dynamic_shapes + + dynamic_shapes = _resolve_dynamic_shapes(model, dynamic_shapes) + + # Decorator mode + if model is None: + + def fn(model: _Callable[_InputT, _RetT]) -> _Callable[_InputT, _RetT]: + if model is None: + raise RuntimeError("Model can't be None") + return compile( # pyrefly: ignore # no-matching-overload + model, + fullgraph=fullgraph, + dynamic=dynamic, + backend=backend, + mode=mode, + options=options, + name=name, + disable=disable, + recompile_limit=recompile_limit, + isolate_recompiles=isolate_recompiles, + dynamic_shapes=dynamic_shapes, + ) + + return fn + + if mode is not None and options is not None: + raise RuntimeError( + "Either mode or options can be specified, but both can't be specified at the same time." + ) + if mode is None and options is None: + mode = "default" + + from torch._inductor.compiler_bisector import CompilerBisector + + if bisect_backend := CompilerBisector.get_backend(): + import torch._inductor.config as inductor_config + + # don't override the backend for use cases like vllm + # which leverages their custom backend. + if not ( + inductor_config.test_configs.bisect_keep_custom_backend_for_inductor + and bisect_backend == "inductor" + and not isinstance(backend, str) + ): + backend = bisect_backend + + guard_filter_fn = None + use_aoti = False + if options and isinstance(options, dict): + guard_filter_fn = options.pop("guard_filter_fn", None) + use_aoti = options.pop("use_aoti", False) + + if torch.compiler.is_exporting(): + from torch._higher_order_ops.utils import _in_hop_compile + + if not _in_hop_compile(): + warnings.warn( + "torch.compile is ignored when called inside torch.export region", + stacklevel=2, + ) + # torch.compile is a no-op when inside torch.export region + return model + + if backend == "inductor": + if use_aoti: + backend = _TorchCompileAOTInductorWrapper(mode, options, dynamic, name) + else: + backend = _TorchCompileInductorWrapper(mode, options, dynamic, name) + 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, + recompile_limit=recompile_limit, + isolate_recompiles=isolate_recompiles, + dynamic_shapes=dynamic_shapes, + )(model) # type: ignore[return-value] + + +def _register_device_module(device_type: str, module: _ModuleType) -> None: + 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: + # register python metas for distributed ops + # Only import if distributed is available (USE_DISTRIBUTED=1) + if hasattr(torch._C, "_c10d_init"): + import torch.distributed._meta_registrations as coll_meta_registrations + + del coll_meta_registrations + 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 compiler as compiler, fx as fx + + +class _TritonLibrary: + lib = torch.library.Library("triton", "DEF") + ops_table: dict[tuple[str, str], _Callable[..., _Any]] = {} + + @classmethod + def registerOp( + cls, + op_key: str, + full_schema: str, + op_impl: _Callable[..., _Any], + dispatch_key: str, + ) -> _Callable[..., _Any]: + 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: str) -> _Any: + # 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__) + + # set_vital + if name == "set_vital": + import warnings + + warnings.warn(f"'{name}' is deprecated, please do not call", stacklevel=2) + return lambda *args: None + + raise AttributeError(f"module '{__name__}' has no attribute '{name}'") + + +@functools.cache +def get_device_module(device: "torch.device | str | None" = None) -> _ModuleType: + """ + 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: + # Use the current accelerator's type, falling back to CPU when none is available. + acc = torch._C._accelerator_getAccelerator() + device_module_name = acc.type if acc is not None else "cpu" + 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: "IntLikeType", + min: builtins.int | None = None, + max: builtins.int | None = None, +) -> None: + """ + This indicates that a given int is size-like, and can be used in any context where a size is expected. + You will typically use this when reading out integers from Tensors, e.g., max.item() or lengths.tolist() + which then need to be used as tensor constructors. Providing these assertions to PyTorch can help resolve + GuardOnDataDependentSymNode errors upon export, since we cannot guard on unbacked SymInts. + + This function has unusual semantics in some circumstances in framework + code, we will treat this int as >= 2 (when we do a size-oblivious guard). + This makes it easier to use the unbacked int in size contexts, + as we will often attempt to guard on a size being zero/one + (e.g., when computing the contiguity of a tensor, or testing if + broadcasting can occur), which will not work on unbacked SymInts. + However, if we conservatively assume that the size is not zero/one, we will + end up with a graph that will still work even if the size is zero/one. + + For more details, see https://docs.google.com/document/d/1HSuTTVvYH1pTew89Rtpeu84Ht3nQEFTYhAX3Ypa_xJs/edit + ``` + """ + # pyrefly: ignore[bad-argument-type] + torch.sym_constrain_range_for_size(symbol, min=min, max=max) + + +def _import_device_backends() -> None: + """ + Leverage the Python plugin mechanism to load out-of-the-tree device extensions. + See this RFC: https://github.com/pytorch/pytorch/issues/122468 + """ + from importlib.metadata import entry_points + + group_name = "torch.backends" + backend_extensions = entry_points(group=group_name) + + for backend_extension in backend_extensions: + try: + # Load the extension + entrypoint = backend_extension.load() + # Call the entrypoint + entrypoint() + except Exception as err: + raise RuntimeError( + f"Failed to load the backend extension: {backend_extension.name}. " + f"You can disable extension auto-loading with TORCH_DEVICE_BACKEND_AUTOLOAD=0." + ) from err + + +def _is_device_backend_autoload_enabled() -> builtins.bool: + """ + Whether autoloading out-of-the-tree device extensions is enabled. + The switch depends on the value of the environment variable + `TORCH_DEVICE_BACKEND_AUTOLOAD`. + + Returns: + bool: Whether to enable autoloading the extensions. Enabled by default. + + Examples: + >>> torch._is_device_backend_autoload_enabled() + True + """ + # enabled by default + return os.getenv("TORCH_DEVICE_BACKEND_AUTOLOAD", "1") == "1" + + +def _as_tensor_fullprec(t: object) -> "torch.Tensor": + """ + Like torch.as_tensor, but when given Python data types it will keep + them in full precision. Used for calling convention for Dynamo. + Python scalars (float, int) are always created on CPU to avoid being + affected by DeviceContext. + """ + ty = type(t) + if ty is builtins.float: + return torch.as_tensor(t, dtype=torch.float64, device="cpu") + elif ty is builtins.int: + return torch.as_tensor(t, dtype=torch.int64, device="cpu") + else: + return torch.as_tensor(t) + + +# `_import_device_backends` should run after the definitions above 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() + +from torch import _logging + + +# Keep `TORCH_LOGS` initialization after backend autoload so backends can +# register their log names before `TORCH_LOGS` is parsed and validated. +_logging._init_logs() + +# Register all registered custom / override ops in torch/_native +import torch._native diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_VF.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_VF.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0d20ca7ac060b53676c7bf49bd357299ccb0bac Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_VF.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/__config__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/__config__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40eb5754aafcfdc1584806077bf3cb595168c843 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/__config__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/__future__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/__future__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12eee04f60a29517b2f3be296e382adc6e87af73 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/__future__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d8fc052c25f59eb434c045c9e8e7b7747af0809 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/__pycache__/__init__.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:968f7c68c8907b2bc9ab1adf9dd860ddc600ed7e7d5f0fe41d6596c9c76b76a5 +size 145169 diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_appdirs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_appdirs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..744d5333ed55c17e5001963d84596f676333c73b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_appdirs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_classes.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_classes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1302811ca92e8e3600ca3a4ce87eb193c1310df7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_classes.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_compile.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_compile.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..830015ceb91f2f64cc15a449397deb32ebf4b661 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_compile.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_custom_class_base.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_custom_class_base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..681d9d5c4d77981163f2238791fe447c63739c1a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_custom_class_base.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_custom_ops.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_custom_ops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f6c36e8b8cb8a8de13e6acdcc7ac432a6c2465f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_custom_ops.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_environment.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_environment.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..367112314f477145aeb4ee26a181240cdbc0299d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_environment.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_guards.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_guards.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ee52a494a69dc459d75ab4d4c6f487a5e8a530d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_guards.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_jit_internal.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_jit_internal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29b688800ac4e50b2a59347f0f312d9ef9abe9bc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_jit_internal.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_linalg_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_linalg_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8eb8be7a1326e504f28e62a137c378ea68c50974 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_linalg_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_lobpcg.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_lobpcg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a28eff03d4c47a2147b87c4dc9d2514e7aced70 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_lobpcg.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_lowrank.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_lowrank.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4ec7d8ed4abfb8ec7e6822d298aff4addd13672 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_lowrank.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_meta_registrations.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_meta_registrations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09d0a6ed095be6bd23541c336ace9c34648eacf2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/__pycache__/_meta_registrations.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ca8404f648182f9be25a92e09ffb354fb710ad274f556560bfd61b97edfa1576 +size 430296 diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_opaque_base.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_opaque_base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9812f464c1de1631535ae45ca8d3823f273f2a7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_opaque_base.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_ops.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_ops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5089e7ed0a3a0d0d6f6ad31849dd003b55820e16 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_ops.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_precompile.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_precompile.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43361ef9ac4a20c1811bcde50cb52ec658e654ea Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_precompile.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_precompile_driver.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_precompile_driver.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f968ec00c83aa1b3961347c620b43a786e56b57 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_precompile_driver.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_python_dispatcher.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_python_dispatcher.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d3e6944e3da52b4776ce9cb494498f95a682f0d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_python_dispatcher.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_size_docs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_size_docs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79200025b5804baa8bd98bcd7be51ed3ceae1744 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_size_docs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_sources.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_sources.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee6ad076b71e650f8a243eb4b7161db86b78803e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_sources.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_storage_docs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_storage_docs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..074ec074f5f5a68d2f4162be4e49bc6ead07be91 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_storage_docs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_streambase.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_streambase.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2838d72defa3ad10d9397642ef7664f042590739 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_streambase.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b013c08997f96d3f25961ab69ec8216ac78dd730 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor_docs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor_docs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c72a009a7242534e257b7ff6cf5f98b0a9a52034 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor_docs.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a66420718dd30504cb5975f2844e25783ebec7442c9606696fcad328c125e99d +size 146282 diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor_iterator.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor_iterator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f864f455b40a01471c05a1d37c991f0a6ac0485 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor_iterator.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor_str.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor_str.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70c1b9a73860eb07b0b65aee704f1e7f56d71890 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_tensor_str.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_thread_safe_fork.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_thread_safe_fork.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b2d096ecfbcf48a91f7fa17cc1b0e22665e1219 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_thread_safe_fork.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_torch_docs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_torch_docs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e724a9d5fd702a335fb25c7e053dbc517a3688aa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/__pycache__/_torch_docs.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43967e160908aa312ed44c07e7c0c303b76b3c5287b4f365ac3c68f8d8dc730c +size 468356 diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01f7383c405702556872385513e7c1347787f4b1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_utils_internal.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_utils_internal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42e144d14a2d4db10ab1d6e5696fdf828d22bca0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_utils_internal.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_vmap_internals.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_vmap_internals.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84ab15bb65b690ba93b46c180e791f26a42546a4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_vmap_internals.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/_weights_only_unpickler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/_weights_only_unpickler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a2515497eec3388cd6290bb1b90890f3c41f44a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/_weights_only_unpickler.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/functional.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/functional.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aca5456550ab6ca7b5b0ed6bcd9d343d473a3c53 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/functional.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/hub.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/hub.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..553db869f31fbf2b749e38bf2e8d989b9b039d39 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/hub.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/library.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/library.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2d1e105b83eafed600e3b1d37086c5934dabde4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/library.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/overrides.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/overrides.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e899475812ccf64f098be88417b14c32dd08bcb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/__pycache__/overrides.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:93e036d0c3777f60525f1e7d28b3a79b65602052b318f05bd1aa5a2b4dda25a0 +size 259003 diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/quasirandom.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/quasirandom.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f48c3fa4a01433ab2dde84052a3cf4805ef91bc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/quasirandom.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/random.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/random.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..596f9d2ad012a06f952eb6e1082d15badfcf0d0b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/random.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/return_types.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/return_types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd260503a9d26fd0badfe4e131c3dbdf4b8c17c2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/return_types.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/serialization.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/serialization.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..706bc384c5e609cf8cb6f4ec8f568f87d318436a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/serialization.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/storage.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/storage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d99ccf380835cdb762423f0c23a2e7cdd5e15fa9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/storage.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/torch_version.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/torch_version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84423d5fbe482113658b7a3f8bfe15a67b0c084f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/torch_version.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/types.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff878749aa2b05333cd235f307f46ce59061b30d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/types.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/__pycache__/version.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/__pycache__/version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78cc984c1fa1af4e052d8d667d975791a0a0db54 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/__pycache__/version.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_appdirs.py b/.venv/lib/python3.12/site-packages/torch/_appdirs.py new file mode 100644 index 0000000000000000000000000000000000000000..9d8ad9487e255ad2ebac86b2fbe9245f72657332 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_appdirs.py @@ -0,0 +1,666 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright (c) 2005-2010 ActiveState Software Inc. +# Copyright (c) 2013 Eddy Petrișor + +# flake8: noqa + +""" +This file is directly from +https://github.com/ActiveState/appdirs/blob/3fe6a83776843a46f20c2e5587afcffe05e03b39/appdirs.py + +The license of https://github.com/ActiveState/appdirs copied below: + + +# This is the MIT license + +Copyright (c) 2010 ActiveState Software Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +""" + +"""Utilities for determining application-specific dirs. + +See for details and usage. +""" +# Dev Notes: +# - Windows "Known Folders": https://learn.microsoft.com/en-us/windows/win32/shell/csidl +# - macOS File System Programming Guide: https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/Introduction/Introduction.html +# - XDG spec for Un*x: https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html + +__version__ = "1.4.4" +__version_info__ = tuple(int(segment) for segment in __version__.split(".")) + + +import os +import sys + + +unicode = str + +if sys.platform.startswith("java"): + import platform + + os_name = platform.java_ver()[3][0] + if os_name.startswith("Windows"): # "Windows XP", "Windows 7", etc. + system = "win32" + elif os_name.startswith("Mac"): # "Mac OS X", etc. + system = "darwin" + else: # "Linux", "SunOS", "FreeBSD", etc. + # Setting this to "linux2" is not ideal, but only Windows or Mac + # are actually checked for and the rest of the module expects + # *sys.platform* style strings. + system = "linux2" +else: + system = sys.platform + + +def user_data_dir(appname=None, appauthor=None, version=None, roaming=False): + r"""Return full path to the user-specific data dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "roaming" (boolean, default False) can be set True to use the Windows + roaming appdata directory. That means that for users on a Windows + network setup for roaming profiles, this user data will be + sync'd on login. See + + for a discussion of issues. + + Typical user data directories are: + Mac OS X: ~/Library/Application Support/ + Unix: ~/.local/share/ # or in $XDG_DATA_HOME, if defined + Win XP (not roaming): C:\Documents and Settings\\Application Data\\ + Win XP (roaming): C:\Documents and Settings\\Local Settings\Application Data\\ + Win 7 (not roaming): C:\Users\\AppData\Local\\ + Win 7 (roaming): C:\Users\\AppData\Roaming\\ + + For Unix, we follow the XDG spec and support $XDG_DATA_HOME. + That means, by default "~/.local/share/". + """ + if system == "win32": + if appauthor is None: + appauthor = appname + const = roaming and "CSIDL_APPDATA" or "CSIDL_LOCAL_APPDATA" + path = os.path.normpath(_get_win_folder(const)) + if appname: + if appauthor is not False: + path = os.path.join(path, appauthor, appname) + else: + path = os.path.join(path, appname) + elif system == "darwin": + path = os.path.expanduser("~/Library/Application Support/") + if appname: + path = os.path.join(path, appname) + else: + path = os.getenv("XDG_DATA_HOME", os.path.expanduser("~/.local/share")) + if appname: + path = os.path.join(path, appname) + if appname and version: + path = os.path.join(path, version) + return path + + +def site_data_dir(appname=None, appauthor=None, version=None, multipath=False): + r"""Return full path to the user-shared data dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "multipath" is an optional parameter only applicable to *nix + which indicates that the entire list of data dirs should be + returned. By default, the first item from XDG_DATA_DIRS is + returned, or '/usr/local/share/', + if XDG_DATA_DIRS is not set + + Typical site data directories are: + Mac OS X: /Library/Application Support/ + Unix: /usr/local/share/ or /usr/share/ + Win XP: C:\Documents and Settings\All Users\Application Data\\ + Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) + Win 7: C:\ProgramData\\ # Hidden, but writeable on Win 7. + + For Unix, this is using the $XDG_DATA_DIRS[0] default. + + WARNING: Do not use this on Windows. See the Vista-Fail note above for why. + """ + if system == "win32": + if appauthor is None: + appauthor = appname + path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA")) + if appname: + if appauthor is not False: + path = os.path.join(path, appauthor, appname) + else: + path = os.path.join(path, appname) + elif system == "darwin": + path = os.path.expanduser("/Library/Application Support") + if appname: + path = os.path.join(path, appname) + else: + # XDG default for $XDG_DATA_DIRS + # only first, if multipath is False + path = os.getenv( + "XDG_DATA_DIRS", os.pathsep.join(["/usr/local/share", "/usr/share"]) + ) + pathlist = [ + os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep) + ] + if appname: + if version: + appname = os.path.join(appname, version) + pathlist = [os.sep.join([x, appname]) for x in pathlist] + + if multipath: + path = os.pathsep.join(pathlist) + else: + path = pathlist[0] + return path + + if appname and version: + path = os.path.join(path, version) + return path + + +def user_config_dir(appname=None, appauthor=None, version=None, roaming=False): + r"""Return full path to the user-specific config dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "roaming" (boolean, default False) can be set True to use the Windows + roaming appdata directory. That means that for users on a Windows + network setup for roaming profiles, this user data will be + sync'd on login. See + + for a discussion of issues. + + Typical user config directories are: + Mac OS X: ~/Library/Preferences/ + Unix: ~/.config/ # or in $XDG_CONFIG_HOME, if defined + Win *: same as user_data_dir + + For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME. + That means, by default "~/.config/". + """ + if system == "win32": + path = user_data_dir(appname, appauthor, None, roaming) + elif system == "darwin": + path = os.path.expanduser("~/Library/Preferences/") + if appname: + path = os.path.join(path, appname) + else: + path = os.getenv("XDG_CONFIG_HOME", os.path.expanduser("~/.config")) + if appname: + path = os.path.join(path, appname) + if appname and version: + path = os.path.join(path, version) + return path + + +def site_config_dir(appname=None, appauthor=None, version=None, multipath=False): + r"""Return full path to the user-shared data dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "multipath" is an optional parameter only applicable to *nix + which indicates that the entire list of config dirs should be + returned. By default, the first item from XDG_CONFIG_DIRS is + returned, or '/etc/xdg/', if XDG_CONFIG_DIRS is not set + + Typical site config directories are: + Mac OS X: same as site_data_dir + Unix: /etc/xdg/ or $XDG_CONFIG_DIRS[i]/ for each value in + $XDG_CONFIG_DIRS + Win *: same as site_data_dir + Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) + + For Unix, this is using the $XDG_CONFIG_DIRS[0] default, if multipath=False + + WARNING: Do not use this on Windows. See the Vista-Fail note above for why. + """ + if system == "win32": + path = site_data_dir(appname, appauthor) + if appname and version: + path = os.path.join(path, version) + elif system == "darwin": + path = os.path.expanduser("/Library/Preferences") + if appname: + path = os.path.join(path, appname) + else: + # XDG default for $XDG_CONFIG_DIRS + # only first, if multipath is False + path = os.getenv("XDG_CONFIG_DIRS", "/etc/xdg") + pathlist = [ + os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep) + ] + if appname: + if version: + appname = os.path.join(appname, version) + pathlist = [os.sep.join([x, appname]) for x in pathlist] + + if multipath: + path = os.pathsep.join(pathlist) + else: + path = pathlist[0] + return path + + +def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True): + r"""Return full path to the user-specific cache dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "opinion" (boolean) can be False to disable the appending of + "Cache" to the base app data dir for Windows. See + discussion below. + + Typical user cache directories are: + Mac OS X: ~/Library/Caches/ + Unix: ~/.cache/ (XDG default) + Win XP: C:\Documents and Settings\\Local Settings\Application Data\\\Cache + Vista: C:\Users\\AppData\Local\\\Cache + + On Windows the only suggestion in the MSDN docs is that local settings go in + the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming + app data dir (the default returned by `user_data_dir` above). Apps typically + put cache data somewhere *under* the given dir here. Some examples: + ...\Mozilla\Firefox\Profiles\\Cache + ...\Acme\SuperApp\Cache\1.0 + OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. + This can be disabled with the `opinion=False` option. + """ + if system == "win32": + if appauthor is None: + appauthor = appname + path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA")) + if appname: + if appauthor is not False: + path = os.path.join(path, appauthor, appname) + else: + path = os.path.join(path, appname) + if opinion: + path = os.path.join(path, "Cache") + elif system == "darwin": + path = os.path.expanduser("~/Library/Caches") + if appname: + path = os.path.join(path, appname) + else: + path = os.getenv("XDG_CACHE_HOME", os.path.expanduser("~/.cache")) + if appname: + path = os.path.join(path, appname) + if appname and version: + path = os.path.join(path, version) + return path + + +def user_state_dir(appname=None, appauthor=None, version=None, roaming=False): + r"""Return full path to the user-specific state dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "roaming" (boolean, default False) can be set True to use the Windows + roaming appdata directory. That means that for users on a Windows + network setup for roaming profiles, this user data will be + sync'd on login. See + + for a discussion of issues. + + Typical user state directories are: + Mac OS X: same as user_data_dir + Unix: ~/.local/state/ # or in $XDG_STATE_HOME, if defined + Win *: same as user_data_dir + + For Unix, we follow this Debian proposal + to extend the XDG spec and support $XDG_STATE_HOME. + + That means, by default "~/.local/state/". + """ + if system in ["win32", "darwin"]: + path = user_data_dir(appname, appauthor, None, roaming) + else: + path = os.getenv("XDG_STATE_HOME", os.path.expanduser("~/.local/state")) + if appname: + path = os.path.join(path, appname) + if appname and version: + path = os.path.join(path, version) + return path + + +def user_log_dir(appname=None, appauthor=None, version=None, opinion=True): + r"""Return full path to the user-specific log dir for this application. + + "appname" is the name of application. + If None, just the system directory is returned. + "appauthor" (only used on Windows) is the name of the + appauthor or distributing body for this application. Typically + it is the owning company name. This falls back to appname. You may + pass False to disable it. + "version" is an optional version path element to append to the + path. You might want to use this if you want multiple versions + of your app to be able to run independently. If used, this + would typically be ".". + Only applied when appname is present. + "opinion" (boolean) can be False to disable the appending of + "Logs" to the base app data dir for Windows, and "log" to the + base cache dir for Unix. See discussion below. + + Typical user log directories are: + Mac OS X: ~/Library/Logs/ + Unix: ~/.cache//log # or under $XDG_CACHE_HOME if defined + Win XP: C:\Documents and Settings\\Local Settings\Application Data\\\Logs + Vista: C:\Users\\AppData\Local\\\Logs + + On Windows the only suggestion in the MSDN docs is that local settings + go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in + examples of what some windows apps use for a logs dir.) + + OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA` + value for Windows and appends "log" to the user cache dir for Unix. + This can be disabled with the `opinion=False` option. + """ + if system == "darwin": + path = os.path.join(os.path.expanduser("~/Library/Logs"), appname) + elif system == "win32": + path = user_data_dir(appname, appauthor, version) + version = False + if opinion: + path = os.path.join(path, "Logs") + else: + path = user_cache_dir(appname, appauthor, version) + version = False + if opinion: + path = os.path.join(path, "log") + if appname and version: + path = os.path.join(path, version) + return path + + +class AppDirs: + """Convenience wrapper for getting application dirs.""" + + def __init__( + self, appname=None, appauthor=None, version=None, roaming=False, multipath=False + ): + self.appname = appname + self.appauthor = appauthor + self.version = version + self.roaming = roaming + self.multipath = multipath + + @property + def user_data_dir(self): + return user_data_dir( + self.appname, self.appauthor, version=self.version, roaming=self.roaming + ) + + @property + def site_data_dir(self): + return site_data_dir( + self.appname, self.appauthor, version=self.version, multipath=self.multipath + ) + + @property + def user_config_dir(self): + return user_config_dir( + self.appname, self.appauthor, version=self.version, roaming=self.roaming + ) + + @property + def site_config_dir(self): + return site_config_dir( + self.appname, self.appauthor, version=self.version, multipath=self.multipath + ) + + @property + def user_cache_dir(self): + return user_cache_dir(self.appname, self.appauthor, version=self.version) + + @property + def user_state_dir(self): + return user_state_dir(self.appname, self.appauthor, version=self.version) + + @property + def user_log_dir(self): + return user_log_dir(self.appname, self.appauthor, version=self.version) + + +# ---- internal support stuff + + +def _get_win_folder_from_registry(csidl_name): + """This is a fallback technique at best. I'm not sure if using the + registry for this guarantees us the correct answer for all CSIDL_* + names. + """ + import winreg as _winreg + + shell_folder_name = { + "CSIDL_APPDATA": "AppData", + "CSIDL_COMMON_APPDATA": "Common AppData", + "CSIDL_LOCAL_APPDATA": "Local AppData", + }[csidl_name] + + key = _winreg.OpenKey( + _winreg.HKEY_CURRENT_USER, + r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders", + ) + dir, _type = _winreg.QueryValueEx(key, shell_folder_name) + return dir + + +def _get_win_folder_with_pywin32(csidl_name): + from win32com.shell import shell, shellcon + + dir = shell.SHGetFolderPath(0, getattr(shellcon, csidl_name), 0, 0) + # Try to make this a unicode path because SHGetFolderPath does + # not return unicode strings when there is unicode data in the + # path. + try: + dir = unicode(dir) + + # Downgrade to short path name if have highbit chars. See + # . + has_high_char = False + for c in dir: + if ord(c) > 255: + has_high_char = True + break + if has_high_char: + try: + import win32api + + dir = win32api.GetShortPathName(dir) + except ImportError: + pass + except UnicodeError: + pass + return dir + + +def _get_win_folder_with_ctypes(csidl_name): + import ctypes + + csidl_const = { + "CSIDL_APPDATA": 26, + "CSIDL_COMMON_APPDATA": 35, + "CSIDL_LOCAL_APPDATA": 28, + }[csidl_name] + + buf = ctypes.create_unicode_buffer(1024) + ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf) + + # Downgrade to short path name if have highbit chars. See + # . + has_high_char = False + for c in buf: + if ord(c) > 255: + has_high_char = True + break + if has_high_char: + buf2 = ctypes.create_unicode_buffer(1024) + if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024): + buf = buf2 + + return buf.value + + +def _get_win_folder_with_jna(csidl_name): + import array + + from com.sun import jna + from com.sun.jna.platform import win32 + + buf_size = win32.WinDef.MAX_PATH * 2 + buf = array.zeros("c", buf_size) + shell = win32.Shell32.INSTANCE + shell.SHGetFolderPath( + None, + getattr(win32.ShlObj, csidl_name), + None, + win32.ShlObj.SHGFP_TYPE_CURRENT, + buf, + ) + dir = jna.Native.toString(buf.tostring()).rstrip("\0") + + # Downgrade to short path name if have highbit chars. See + # . + has_high_char = False + for c in dir: + if ord(c) > 255: + has_high_char = True + break + if has_high_char: + buf = array.zeros("c", buf_size) + kernel = win32.Kernel32.INSTANCE + if kernel.GetShortPathName(dir, buf, buf_size): + dir = jna.Native.toString(buf.tostring()).rstrip("\0") + + return dir + + +if system == "win32": + try: + import win32com.shell + + _get_win_folder = _get_win_folder_with_pywin32 + except ImportError: + try: + from ctypes import windll + + _get_win_folder = _get_win_folder_with_ctypes + except ImportError: + try: + import com.sun.jna + + _get_win_folder = _get_win_folder_with_jna + except ImportError: + _get_win_folder = _get_win_folder_from_registry + + +# ---- self test code + +if __name__ == "__main__": + appname = "MyApp" + appauthor = "MyCompany" + + props = ( + "user_data_dir", + "user_config_dir", + "user_cache_dir", + "user_state_dir", + "user_log_dir", + "site_data_dir", + "site_config_dir", + ) + + print(f"-- app dirs {__version__} --") + + print("-- app dirs (with optional 'version')") + dirs = AppDirs(appname, appauthor, version="1.0") + for prop in props: + print(f"{prop}: {getattr(dirs, prop)}") + + print("\n-- app dirs (without optional 'version')") + dirs = AppDirs(appname, appauthor) + for prop in props: + print(f"{prop}: {getattr(dirs, prop)}") + + print("\n-- app dirs (without optional 'appauthor')") + dirs = AppDirs(appname) + for prop in props: + print(f"{prop}: {getattr(dirs, prop)}") + + print("\n-- app dirs (with disabled 'appauthor')") + dirs = AppDirs(appname, appauthor=False) + for prop in props: + print(f"{prop}: {getattr(dirs, prop)}") diff --git a/.venv/lib/python3.12/site-packages/torch/_awaits/__init__.py b/.venv/lib/python3.12/site-packages/torch/_awaits/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3f8d2bf058c08847bd09afc905bc88e6823bc917 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_awaits/__init__.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +from typing import Generic, TypeVar + +import torch + +# pyrefly: ignore [bad-dunder-all] +__all__ = ['Await'] + +W = TypeVar("W") + +class _PyAwaitMeta(type(torch._C._Await), type(Generic)): # type: ignore[misc, no-redef] + pass + +class _Await(torch._C._Await, Generic[W], metaclass=_PyAwaitMeta): + r""" + Wrapper around a ``torch._C.Await`` which encapsulates delayed execution + of a callable. All manipulations happen with functions ``torch.jit._awaitable``, + ``torch.jit._awaitable_wait``, ``torch.jit._awaitable_nowait``. + + Torch scriptable manipulations: + ``torch.jit._awaitable(func, *args)`` + Creates ``Await[W]`` object, where W is return type of func. + + Returns: + ``torch.jit._awaitable_wait(Await[W])`` + Returns the result of the function, specified at ``_awaitable``, with specified arguments. + + Returns: + The result of type ``W`` of the function call. The result is owned by ``Await[W]`` + and returned on all following ``_awaitable_wait`` calls. + + + ``torch.jit._awaitable_nowait(W)`` + Returns: + Trivial ``Await[W]`` with specified result. + + + Only in eager mode: + ``fn() -> Callable[Tuple[Any], W]`` + Returns: + Specified at ``_awaitable`` python function ``func``. + + ``args() -> Tuple[Any]`` + Returns: + Specified at ``_awaitable`` python args. + + ``is_nowait() -> _bool`` + Returns: + ``True`` if this object was created via ``_awaitable_nowait`` call (trivial `Await[W]`). + + In eager mode ``Await[W]`` can be used as ``W`` i.e. attributes of W can be called on ``Await[W]``, + ``_awaitable_wait()`` call will be transparently added. + """ diff --git a/.venv/lib/python3.12/site-packages/torch/_awaits/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_awaits/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00c5364e3d97162646807893fc37c3c5d42e3e37 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_awaits/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_classes.py b/.venv/lib/python3.12/site-packages/torch/_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..a811c7c30be612bf0a89e5c8a5473e9d54d02ba3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_classes.py @@ -0,0 +1,56 @@ +import types +from typing import Any + +import torch._C + + +class _ClassNamespace(types.ModuleType): + def __init__(self, name: str) -> None: + super().__init__("torch.classes" + name) + self.name = name + + def __getattr__(self, attr: str) -> Any: + proxy = torch._C._get_custom_class_python_wrapper(self.name, attr) + if proxy is None: + raise RuntimeError(f"Class {self.name}.{attr} not registered!") + return proxy + + +class _Classes(types.ModuleType): + __file__ = "_classes.py" + + def __init__(self) -> None: + super().__init__("torch.classes") + + def __getattr__(self, name: str) -> _ClassNamespace: + namespace = _ClassNamespace(name) + setattr(self, name, namespace) + return namespace + + @property + def loaded_libraries(self) -> Any: + return torch.ops.loaded_libraries + + def load_library(self, path: str) -> None: + """ + Loads a shared library from the given path into the current process. + + The library being loaded may run global initialization code to register + custom classes with the PyTorch JIT runtime. This allows dynamically + loading custom classes. For this, you should compile your class + and the static registration code into a shared library object, and then + call ``torch.classes.load_library('path/to/libcustom.so')`` to load the + shared object. + + After the library is loaded, it is added to the + ``torch.classes.loaded_libraries`` attribute, a set that may be inspected + for the paths of all libraries loaded using this function. + + Args: + path (str): A path to a shared library to load. + """ + torch.ops.load_library(path) + + +# The classes "namespace" +classes = _Classes() diff --git a/.venv/lib/python3.12/site-packages/torch/_compile.py b/.venv/lib/python3.12/site-packages/torch/_compile.py new file mode 100644 index 0000000000000000000000000000000000000000..bf7d715883d58588c7f991a7393f016d2320213c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_compile.py @@ -0,0 +1,60 @@ +""" +APIs related to torch.compile which lazily import torch._dynamo to avoid +circular dependencies. +""" + +import functools +from collections.abc import Callable +from typing import overload, TypeVar +from typing_extensions import ParamSpec + + +_T = TypeVar("_T") +_P = ParamSpec("_P") + + +@overload +def _disable_dynamo( + fn: Callable[_P, _T], recursive: bool = True +) -> Callable[_P, _T]: ... + + +@overload +def _disable_dynamo( + fn: None = None, recursive: bool = True +) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: ... + + +def _disable_dynamo( + fn: Callable[_P, _T] | None = None, recursive: bool = True +) -> Callable[_P, _T] | Callable[[Callable[_P, _T]], Callable[_P, _T]]: + """ + This API should be only used inside torch, external users should still use + torch._dynamo.disable. The main goal of this API is to avoid circular + imports issues that is common while using _dynamo.disable inside torch + itself. + + This API avoids it by lazily importing torch._dynamo from the import time to + the invocation of the decorated function. + """ + if fn is not None: + + @functools.wraps(fn) + def inner(*args: _P.args, **kwargs: _P.kwargs) -> _T: + # cache this on the first invocation to avoid adding too much overhead. + disable_fn = getattr(fn, "__dynamo_disable", None) + if disable_fn is None: + import torch._dynamo + + # We can safely turn off functools.wraps here because the inner + # already wraps fn in the outer scope. + disable_fn = torch._dynamo.disable(fn, recursive, wrapping=False) + fn.__dynamo_disable = disable_fn # type: ignore[attr-defined] + + return disable_fn(*args, **kwargs) + + return inner + else: + # decorator usage like @_disable_dynamo(recursive=False). The resulting + # object expects the original decorated function as the arg. + return functools.partial(_disable_dynamo, recursive=recursive) diff --git a/.venv/lib/python3.12/site-packages/torch/_custom_class_base.py b/.venv/lib/python3.12/site-packages/torch/_custom_class_base.py new file mode 100644 index 0000000000000000000000000000000000000000..051cf5cc623fe9a13a17e25d56e8089cf772e4ff --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_custom_class_base.py @@ -0,0 +1,43 @@ +# Cached lazily on first __instancecheck__ miss to avoid an import cycle at +# module load (FakeScriptObject's module imports torch, which imports us). +_FakeScriptObject_cls: type | None = None + + +class CustomClassBaseMeta(type): + def __instancecheck__(cls, instance): + # When checking against CustomClassBase itself (not a concrete subclass), + # delegate to the registration system which correctly covers all + # custom classes (constant types, metaclass-only symbolic types, and + # FakeScriptObject wrappers). + if cls is CustomClassBase: + from torch._library.opaque_object import is_custom_class_obj + + return is_custom_class_obj(instance) + + if super().__instancecheck__(instance): + return True + + # Check FakeScriptObject before hasattr to avoid triggering custom + # __getattr__ on arbitrary user objects (e.g. dict-like objects that + # raise KeyError on unknown attributes). + # e.g. test/dynamo/test_dynamic_shapes.py -k test_user_getattr1_dynamic_shapes + global _FakeScriptObject_cls + if _FakeScriptObject_cls is None: + from torch._library.fake_class_registry import FakeScriptObject + + _FakeScriptObject_cls = FakeScriptObject + if isinstance(instance, _FakeScriptObject_cls) and hasattr( + instance, "real_obj" + ): + return super().__instancecheck__(instance.real_obj) + + return False + + +class CustomClassBase(metaclass=CustomClassBaseMeta): + pass + + +# Backward compatibility aliases +OpaqueBaseMeta = CustomClassBaseMeta +OpaqueBase = CustomClassBase diff --git a/.venv/lib/python3.12/site-packages/torch/_custom_op/__init__.py b/.venv/lib/python3.12/site-packages/torch/_custom_op/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_custom_op/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_custom_op/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d4ba5ac94a4d7583875af83a6dfde5ee1b373ae Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_custom_op/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_custom_op/__pycache__/autograd.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_custom_op/__pycache__/autograd.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25743e9c90ee5c8e669e62f94ea249188e0316b8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_custom_op/__pycache__/autograd.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_custom_op/__pycache__/impl.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_custom_op/__pycache__/impl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36f48e4aad1a6b4f1f96cc59f019d9e6018e6259 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_custom_op/__pycache__/impl.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_custom_op/autograd.py b/.venv/lib/python3.12/site-packages/torch/_custom_op/autograd.py new file mode 100644 index 0000000000000000000000000000000000000000..e4dffbd4c026627f7c8ac7c6a1fb988b96c187a6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_custom_op/autograd.py @@ -0,0 +1,314 @@ +# mypy: allow-untyped-defs +import functools +from collections import namedtuple + +import torch +import torch.utils._pytree as pytree + + +# NOTE [CustomOp autograd kernel indirection] +# We register `inner` as the autograd kernel for this custom_op. +# `inner` either calls the autograd formula registered by the user, +# or goes into an `autograd_not_implemented` kernel. +# +# The reason why this indirection exists is +# so that we can swap out the autograd kernel (the PyTorch dispatcher +# doesn't actually allow us to do this). By default, we want +# the `autograd_not_implemented` behavior, but then the user may come +# and register something that is actually a backward formula +def autograd_kernel_indirection(custom_op): + autograd_fallback = autograd_not_implemented(custom_op) + + def inner(*args, **kwargs): + if custom_op._has_impl("autograd"): + kernel = custom_op._get_impl("autograd").func + return kernel(*args, **kwargs) + # As explained in NOTE ["backward", "save_for_backward", and "autograd"], + # after the user gives us "backward" and "save_for_backward", we generate + # the "autograd" impl. If the user only provided one, then we tell + # the user they've done something wrong. + if custom_op._has_impl("save_for_backward") or custom_op._has_impl("backward"): + missing = ( + "save_for_backward" if custom_op._has_impl("backward") else "backward" + ) + found = "save_for_backward" if missing == "backward" else "backward" + loc = custom_op._get_impl(found).location + raise RuntimeError( + f"We found a '{found}' registration for {custom_op} at " + f"{loc} but were unable to find a '{missing}' registration. " + f"To use the CustomOp API to register a backward formula, " + f"please provide us both a backward function and a " + f"'save for backward' function via `impl_backward` and " + f"`impl_save_for_backward` respectively." + ) + return autograd_fallback(*args, **kwargs) + + return inner + + +# TODO(#101191): Use the actual C++ autograd not implemented fallback, +# or change the default autograd fallback to the autograd not implemented fallback. +def autograd_not_implemented(custom_op): + def kernel(*args, **kwargs): + if torch.is_grad_enabled() and pytree.tree_any( + lambda x: isinstance(x, torch.Tensor) and x.requires_grad, (args, kwargs) + ): + raise RuntimeError("Autograd has not been implemented for operator") + with torch._C._AutoDispatchBelowAutograd(): + return custom_op(*args, **kwargs) + + return kernel + + +def mark_non_differentiable(ctx, output, output_differentiability): + # Output types are restricted to be: + # - Tensor + # - Tensor[] + # - int, bool, Scalar, float + # See _check_can_register_backward + if output_differentiability is not None: + if not isinstance(output, tuple): + tuple_output = (output,) + else: + tuple_output = output # type: ignore[assignment] + if len(output_differentiability) != len(tuple_output): + raise AssertionError( + f"output_differentiability length {len(output_differentiability)} " + f"!= output length {len(tuple_output)}" + ) + non_differentiable_tensors = [] + for idx, (differentiable, out) in enumerate( + zip(output_differentiability, tuple_output) + ): + if isinstance(out, torch.Tensor): + if not differentiable: + non_differentiable_tensors.append(out) + continue + if isinstance(out, list): + if not differentiable: + non_differentiable_tensors.extend(out) + continue + if differentiable: + raise RuntimeError( + f"With output_differentiability={output_differentiability}. " + f"At idx {idx}, we received an object of type {type(out)} that " + f"is not a Tensor, so it cannot have been marked as differentiable in " + f"output_differentiability." + ) + if non_differentiable_tensors: + ctx.mark_non_differentiable(*non_differentiable_tensors) + + +def construct_autograd_kernel( + schema, + output_differentiability, + custom_op, + op_overload, + save_for_backward_fn, + backward_fn, +): + def apply(*args): + flat_args, spec = pytree.tree_flatten(args) + out_spec = None + + def forward(ctx, *flat_args): + ctx.set_materialize_grads(True) + args = pytree.tree_unflatten(list(flat_args), spec) + with torch._C._AutoDispatchBelowAutograd(): + output = op_overload(*args) + + # We use the info about args to give better error messages in backward + args_info = namedtuple_args(schema, pytree.tree_map(type, args)) + + save_for_backward_fn_inputs = namedtuple_args(schema, args) + to_save = save_for_backward_fn(save_for_backward_fn_inputs, output) + + save_pytree_for_backward(ctx, (to_save, args_info)) + mark_non_differentiable(ctx, output, output_differentiability) + + nonlocal out_spec + flat_output, out_spec = pytree.tree_flatten(output) + return tuple(flat_output) + + def backward(ctx, *flat_grad_output): + if out_spec is None: + raise AssertionError("out_spec is unexpectedly None") + grads = pytree.tree_unflatten(list(flat_grad_output), out_spec) + saved, args_info = unpack_saved(ctx) + # There is nothing on the ctx object for now, it is just there so + # that we can add additional things in the future. + inner_ctx = object() + if not isinstance(grads, tuple): + grads = (grads,) + grad_inputs_dict = backward_fn(inner_ctx, saved, *grads) + + # Massage the grad_inputs_dict to a form acceptable by + # autograd.Function. + validate_grad_inputs_dict(grad_inputs_dict, custom_op, args_info) + return grad_inputs_dict_to_flat_tuple(grad_inputs_dict, args_info) + + generated_cls = gen_autograd_function( + custom_op._opname + "_customop", forward, backward + ) + + flat_output = generated_cls.apply(*flat_args) + if out_spec is None: + raise AssertionError("out_spec is unexpectedly None") + return pytree.tree_unflatten(list(flat_output), out_spec) + + return apply + + +def gen_autograd_function(name, forward, backward): + generated_cls = type( + name, + (torch.autograd.Function,), + { + "forward": staticmethod(forward), + "backward": staticmethod(backward), + }, + ) + return generated_cls + + +@functools.lru_cache +def namedtuple_args_cls(schema): + attribs = [arg.name for arg in schema.arguments.flat_all] + name = str(schema.name) + "_args" + # mypy doesn't support dynamic namedtuple name + tuple_cls = namedtuple(name, attribs) # type: ignore[misc] + return tuple_cls + + +def namedtuple_args(schema, args): + if not isinstance(args, tuple): + raise AssertionError(f"expected tuple, got {type(args)}") + tuple_cls = namedtuple_args_cls(schema) + return tuple_cls(*args) + + +def validate_grad_inputs_dict(grad_inputs_dict, forward_op, args_info): + def error(what): + backward = forward_op._get_impl("backward") + raise RuntimeError( + f"In the backward function defined for {forward_op} at " + f"{backward.location} using the CustomOp API, {what}" + ) + + if not isinstance(grad_inputs_dict, dict): + error( + f"expected the output of the backward function to be a dict but " + f"got {type(grad_inputs_dict)}" + ) + + expected_keys = { + arg.name + for arg in forward_op._schema.arguments.flat_all + if arg.type.is_tensor_like() + } + actual_keys = grad_inputs_dict.keys() + if expected_keys != actual_keys: + error( + f"expected the returned grad_input dict to have keys " + f"{expected_keys} but got {actual_keys}. The backward " + f"function must return a gradient (can be None) for each arg " + f"to the CustomOp that may be a Tensor or Sequence[Tensor]. " + f"Args declared to be non-Tensor-like types should not appear " + f"in the grad_input dict" + ) + + for name, grad in grad_inputs_dict.items(): + arg_info = getattr(args_info, name) + + if isinstance(arg_info, list): + if not isinstance(grad, (tuple, list)): + error( + f"for input '{name}' expected the grad_input dict to " + f"hold a list of gradients but got object of type " + f"{type(grad)}." + ) + if len(grad) != len(arg_info): + error( + f"for input '{name}' expected the grad_input dict to " + f"hold a list of {len(arg_info)} gradients but got " + f"{len(grad)}" + ) + for idx, (g, info) in enumerate(zip(grad, arg_info)): + if g is None: + continue + if not isinstance(g, torch.Tensor): + error( + f"for input '{name}' expected the grad_input dict to " + f"hold a list of None or Tensor gradients but got " + f"object of {type(g)} at index {idx}" + ) + if not issubclass(info, torch.Tensor): + error( + f"for input '{name}', got a Tensor as the gradient " + f"for the {idx}-th value but expected None because " + f"the {idx}-th value was not a Tensor (it was " + f"type {arg_info}" + ) + continue + + if grad is None: + continue + if not isinstance(grad, torch.Tensor): + error( + f"got object of type {type(grad)} as the gradient for input " + f"'{name}', " + f"but expected the gradient to be either None or a Tensor" + ) + if not issubclass(arg_info, torch.Tensor): + error( + f"got a Tensor as the gradient for input '{name}' but " + f"expected None as the gradient because input '{name}' " + f"was not a Tensor (it was type {arg_info})." + ) + + +def grad_inputs_dict_to_flat_tuple(grad_inputs_dict, args_info): + result = [] + for name, arg_info in args_info._asdict().items(): + if name not in grad_inputs_dict: + result.append(pytree.tree_map(lambda x: None, arg_info)) + continue + result.append(grad_inputs_dict[name]) + return tuple(pytree.tree_leaves(result)) + + +# Saves "stuff" (a pytree) onto the ctx object. Use unpack_saved to unpack it. +# autograd.Function prefers that users use ctx.save_for_backward to +# save Tensors (to avoid reference cycles) and for non-Tensors to go onto the +# ctx object. +def save_pytree_for_backward(ctx, stuff): + flat_stuff, spec = pytree.tree_flatten(stuff) + num_elts = len(flat_stuff) + tensor_idxs = [ + idx for idx, thing in enumerate(flat_stuff) if isinstance(thing, torch.Tensor) + ] + non_tensor_idxs = [ + idx + for idx, thing in enumerate(flat_stuff) + if not isinstance(thing, torch.Tensor) + ] + tensors = [thing for thing in flat_stuff if isinstance(thing, torch.Tensor)] + non_tensors = [thing for thing in flat_stuff if not isinstance(thing, torch.Tensor)] + + ctx.spec = spec + ctx.num_elts = num_elts + ctx.save_for_backward(*tensors) + ctx.tensor_idxs = tensor_idxs + ctx.saved_non_tensors = non_tensors + ctx.non_tensor_idxs = non_tensor_idxs + + +# Inverse operation to save_pytree_for_backward +def unpack_saved(ctx): + flat_stuff = [None] * ctx.num_elts + for tensor, idx in zip(ctx.saved_tensors, ctx.tensor_idxs): + flat_stuff[idx] = tensor + for non_tensor, idx in zip(ctx.saved_non_tensors, ctx.non_tensor_idxs): + flat_stuff[idx] = non_tensor + stuff = pytree.tree_unflatten(flat_stuff, ctx.spec) + return stuff diff --git a/.venv/lib/python3.12/site-packages/torch/_custom_op/impl.py b/.venv/lib/python3.12/site-packages/torch/_custom_op/impl.py new file mode 100644 index 0000000000000000000000000000000000000000..03a76244f8353a05d46606e93778b18991257552 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_custom_op/impl.py @@ -0,0 +1,718 @@ +# mypy: allow-untyped-defs +import dataclasses +import functools +import inspect +import sys +import typing +import warnings +import weakref + +import torch +import torch._C as _C +import torch._library.infer_schema +import torch.library as library +from torch._library.infer_schema import infer_schema +from torch.library import get_ctx +from torchgen.model import ( + BaseTy, + BaseType, + FunctionSchema, + ListType, + OperatorName, + SchemaKind, +) + +from .autograd import autograd_kernel_indirection, construct_autograd_kernel + + +""" +torch._custom_op is deprecated. We shipped a production-ready version of it into torch.library. +Please use those APIs instead. +""" + +__all__ = ["custom_op", "CustomOp", "get_ctx"] + + +SUPPORTED_DEVICE_TYPE_TO_KEY = { + "cpu": "CPU", + "cuda": "CUDA", +} + +# We will not let users register CustomOps with anything that could look like +# PyTorch internals to avoid confusion. +RESERVED_NS = { + "prim", + "prims", + "aten", + "at", + "torch", + "pytorch", +} + + +def warn_deprecated(): + warnings.warn( + "torch._custom_op is deprecated and will be removed in PyTorch 2.6, please " + "use the equivalent torch.library API instead.", + DeprecationWarning, + stacklevel=2, + ) + + +def custom_op(qualname: str, manual_schema: str | None = None) -> typing.Callable: + r""" + This API is deprecated, please use torch.library.custom_op instead + """ + warn_deprecated() + + def inner(func): + if not inspect.isfunction(func): + raise ValueError( + f"custom_op(...)(func): Expected `func` to be a Python " + f"function, got: {type(func)}" + ) + + ns, name = parse_qualname(qualname) + validate_namespace(ns) + if func.__name__ != name: + raise ValueError( + f"custom_op(qualname='{qualname}', ...)(func): expected `func` " + f"to have name '{name}' but got '{func.__name__}'. " + f"Please either change the name of `func` or the qualname that " + f"is passed to `custom_op`" + ) + + schema = ( + infer_schema(func, mutates_args=()) + if manual_schema is None + else manual_schema + ) + schema_str = f"{name}{schema}" + function_schema = FunctionSchema.parse(schema_str) + validate_schema(function_schema) + if manual_schema is not None: + validate_function_matches_schema(function_schema, func) + + lib = library.Library(ns, "FRAGMENT") + lib.define(schema_str) + ophandle = find_ophandle_or_throw(ns, function_schema.name) + result = CustomOp( + lib, ns, function_schema, name, ophandle, _private_access=True + ) + + result.__name__ = func.__name__ # pyrefly: ignore [bad-assignment] + result.__module__ = func.__module__ + result.__doc__ = func.__doc__ + + library.impl(lib, result._opname, "Autograd")( + autograd_kernel_indirection(weakref.proxy(result)) + ) + + torch._C._dispatch_set_report_error_callback( + ophandle, functools.partial(report_error_callback, weakref.proxy(result)) + ) + + return result + + return inner + + +# Global dictionary holding references to all CustomOp objects +# Yes, it keeps all CustomOps alive (see NOTE [CustomOp lifetime]) +# Used to query the CustomOp associated with a specific C++ dispatcher operator. +# An example usage is FakeTensor: FakeTensor checks if a specific operator +# has an implementation registered via the CustomOp API. +# Indexed by qualname (e.g. aten::foo) +global_registry: dict[str, "CustomOp"] = {} + + +class CustomOp: + r""" + This API is deprecated, please use torch.library.custom_op instead + """ + + def __init__( + self, lib, cpp_ns, schema, operator_name, ophandle, *, _private_access=False + ): + super().__init__() + warn_deprecated() + if not _private_access: + raise RuntimeError( + "The CustomOp constructor is private and we do not guarantee " + "BC for it. Please use custom_op(...) to create a CustomOp object" + ) + name = f"{cpp_ns}::{operator_name}" + self._schema = schema + self._cpp_ns = cpp_ns + self._lib: library.Library = lib + self._ophandle: _C._DispatchOperatorHandle = ophandle + # Has the name of the op, e.g. "foo". We cache here for convenience. + self._opname: str = operator_name + # this is _opname but with namespace. e.g. "custom::foo" + self._qualname: str = name + self.__name__ = None # mypy requires this + # NB: Some of these impls are registered as kernels to DispatchKeys. + # Modifying the _impls dict directly won't do anything in that case. + self._impls: dict[str, FuncAndLocation | None] = {} + # See NOTE [CustomOp autograd kernel indirection] + self._registered_autograd_kernel_indirection = False + + global_registry[self._qualname] = self + + def _register_autograd_kernel_indirection(self): + if self._registered_autograd_kernel_indirection: + raise AssertionError("autograd kernel indirection already registered") + self._lib.impl( + self._opname, autograd_kernel_indirection(weakref.proxy(self)), "Autograd" + ) + self._registered_autograd_kernel_indirection = True + + # Records the impl and the source location in self._impls + # Note that this doesn't cause torch.library to use the impl, that + # needs to be done in a separate self._lib.impl call. + def _register_impl(self, kind, func, stacklevel=2): + if self._has_impl(kind): + func_and_location = self._impls[kind] + if func_and_location is None: + raise AssertionError("func_and_location is unexpectedly None") + location = func_and_location.location + raise RuntimeError( + f"Attempting to register a {kind} impl for operator {self._qualname} " + f"that already has a {kind} impl registered from Python at " + f"{location}. This is not supported." + ) + frame = inspect.getframeinfo(sys._getframe(stacklevel)) + location = f"{frame.filename}:{frame.lineno}" + self._impls[kind] = FuncAndLocation(func, location) + + def _get_impl(self, kind): + return self._impls[kind] + + def _has_impl(self, kind): + return kind in self._impls + + def _destroy(self): + # NOTE: [CustomOp lifetime] + # A CustomOp, once created, lives forever. The mechanism is that the + # global registry holds a reference to it. However, to make testing + # easier, we want to be able to destroy CustomOp objects. + # CustomOp._destroy does the job, though it leaves the CustomOp + # in a garbage state. + del self._lib + + opnamespace = getattr(torch.ops, self._cpp_ns) + if hasattr(opnamespace, self._opname): + delattr(opnamespace, self._opname) + + del global_registry[self._qualname] + + def __repr__(self): + return f'' + + def __call__(self, *args, **kwargs): + # Bypass torch.ops.* and directly do OperatorHandle::callBoxed. + # Using torch.ops.* is a bit of a pain (it can be slow and it has lifetime + # issues from caching operators that make testing CustomOp difficult). + result = _C._dispatch_call_boxed(self._ophandle, *args, **kwargs) + return result + + def impl( + self, + device_types: str | typing.Iterable[str], + _stacklevel=2, + ) -> typing.Callable: + r""" + This API is deprecated, please use torch.library.custom_op instead + """ + if isinstance(device_types, str): + device_types = [device_types] + for device_type in device_types: + validate_device_type(device_type) + + def inner(f): + for device_type in set(device_types): + self._check_doesnt_have_library_impl(device_type) + self._register_impl(device_type, f, stacklevel=_stacklevel) + dispatch_key = SUPPORTED_DEVICE_TYPE_TO_KEY[device_type] + library.impl(self._lib, self._opname, dispatch_key)(f) + return f + + return inner + + def _check_doesnt_have_library_impl(self, device_type): + if self._has_impl(device_type): + return + key = SUPPORTED_DEVICE_TYPE_TO_KEY[device_type] + if _C._dispatch_has_computed_kernel_for_dispatch_key(self._qualname, key): + raise RuntimeError( + f"impl(..., device_types={device_type}): the operator {self._qualname} " + f"already has an implementation for this device type via a " + f"pre-existing torch.library or TORCH_LIBRARY registration." + ) + + def impl_factory(self) -> typing.Callable: + r"""Register an implementation for a factory function.""" + + def inner(f): + self._register_impl("factory", f) + library.impl(self._lib, self._opname, "BackendSelect")(f) + return f + + return inner + + def impl_abstract(self, _stacklevel=2) -> typing.Callable: + r""" + This API is deprecated, please use torch.library.custom_op instead + """ + + def inner(f): + self._check_doesnt_have_library_meta_impl() + self._register_impl("abstract", f, stacklevel=_stacklevel) + location = self._get_impl("abstract").location + + qualname = self._qualname + + # Handle DispatchKey.Meta registration + @functools.wraps(f) + def f_with_ctx(*args, **kwargs): + def error_on_ctx(): + raise RuntimeError( + f"Attempted to call get_ctx() for the meta implementation " + f"for {qualname}." + f"You have presumably called get_ctx() because the operator " + f"has a data-dependent output shape; if so, there is no " + f"such meta implementation and this error is the correct " + f"behavior. Otherwise, please remove the call to get_ctx() " + f"in the implementation registered with impl_abstract " + f"at {location}" + ) + + with torch._library.fake_impl.set_ctx_getter(error_on_ctx): + return f(*args, **kwargs) + + self._lib.impl(self._opname, f_with_ctx, "Meta") + return f + + return inner + + def _check_can_register_backward(self): + def error(detail): + raise RuntimeError( + f"Cannot use torch._custom_ops APIs to register backward " + f"formula for {detail}. Got operator " + f"{self._qualname} with schema: {schema}" + ) + + schema = self._schema + if schema.kind() != SchemaKind.functional: + error("non-functional operator") + + rets = schema.returns + if not schema.returns: + error("operator with no returns") + + if len(rets) <= 0: + raise AssertionError(f"expected at least one return, got {len(rets)}") + is_non_mutating_view = any( + r.annotation is not None and not r.annotation.is_write for r in rets + ) + if is_non_mutating_view: + error("operator that returns views") + + # We make assumptions about the schema's return types. + allowed_return_types = { + BaseType(BaseTy.int): "int", + BaseType(BaseTy.SymInt): "SymInt", + BaseType(BaseTy.bool): "bool", + BaseType(BaseTy.float): "float", + BaseType(BaseTy.Tensor): "Tensor", + ListType(BaseType(BaseTy.Tensor), None): "List[Tensor]", + } + for ret in schema.returns: + if ret.type in allowed_return_types: + continue + error( + f"operator with return not in {list(allowed_return_types.values())} (got {ret.type})" + ) + + def _check_doesnt_have_library_autograd_impl(self): + if self._registered_autograd_kernel_indirection: + return + + if _C._dispatch_has_kernel_for_dispatch_key( + self._qualname, "CompositeImplicitAutograd" + ): + raise RuntimeError( + f"impl_backward/impl_save_for_backward: the operator {self._qualname} " + f"already has an implementation for this device type via a " + f"pre-existing registration to DispatchKey::CompositeImplicitAutograd." + f"CompositeImplicitAutograd operators do not need an autograd formula; " + f"instead, the operator will decompose into its constituents and those " + f"can have autograd formulas defined on them." + ) + + # We can improve this by adding "all Autograd keys", but + # realistically people will just be using this API for CPU/CUDA for now. + for key in ["Autograd", "AutogradCPU", "AutogradCUDA"]: + if _C._dispatch_has_kernel_for_dispatch_key(self._qualname, key): + raise RuntimeError( + f"impl_backward/impl_save_for_backward: " + f"the operator {self._qualname} already has an Autograd kernel " + f"registered to DispatchKey::{key} via a pre-existing " + f"torch.library or TORCH_LIBRARY registration. Please either " + f"remove those registrations or don't use the torch._custom_ops APIs" + ) + + def _check_doesnt_have_library_meta_impl(self): + if self._has_impl("abstract"): + return + + # If the user's operator is CompositeExplicitAutograd, + # allow them to impl_abstract. This is being pragmatic + # (existing custom ops may have CompositeExplicitAutograd + # registration that don't work with Meta kernels, so this + # gives them an escape hatch). + if _C._dispatch_has_kernel_for_dispatch_key( + self._qualname, "CompositeExplicitAutograd" + ) and not _C._dispatch_has_kernel_for_dispatch_key(self._qualname, "Meta"): + return + + # Otherwise, if the user's already has a Meta kernel or their + # op is CompositeImplicitAutograd or some other alias dispatch key, + # raise. + + # Special case for CompositeImplicitAutograd + if _C._dispatch_has_kernel_for_dispatch_key( + self._qualname, "CompositeImplicitAutograd" + ): + raise RuntimeError( + f"impl_abstract(...): the operator {self._qualname} " + f"already has an implementation for this device type via a " + f"pre-existing registration to DispatchKey::CompositeImplicitAutograd." + f"CompositeImplicitAutograd operators do not need an abstract impl; " + f"instead, the operator will decompose into its constituents and those " + f"can have abstract impls defined on them." + ) + + if _C._dispatch_has_kernel_for_dispatch_key(self._qualname, "Meta"): + raise RuntimeError( + f"impl_abstract(...): the operator {self._qualname} " + f"already has a DispatchKey::Meta implementation via a " + f"pre-existing torch.library or TORCH_LIBRARY registration. " + f"Please either remove that registration or don't call impl_abstract." + ) + + # NOTE ["backward", "save_for_backward", and "autograd"] + # As a part of the explicit autograd API, a user must provide us + # a "save_for_backward" function and a "backward" function. + # When both of these have been provided, then we automatically + # construct the "autograd" kernel. + def _register_autograd_kernel(self): + if not self._has_impl("backward"): + raise AssertionError("backward impl must be registered first") + if not self._has_impl("save_for_backward"): + raise AssertionError("save_for_backward impl must be registered first") + kernel = construct_autograd_kernel( + self._schema, + self._output_differentiability, + self, + get_op(self._qualname), + self._get_impl("save_for_backward").func, + self._get_impl("backward").func, + ) + self._register_impl("autograd", kernel) + + def impl_save_for_backward(self, _stacklevel=2): + r"""Register a function that tells us what to save for backward. + + Please see impl_backward for more details. + """ + + def inner(f): + self._check_can_register_backward() + self._check_doesnt_have_library_autograd_impl() + if not self._registered_autograd_kernel_indirection: + self._register_autograd_kernel_indirection() + self._register_impl("save_for_backward", f, stacklevel=_stacklevel) + if self._has_impl("backward"): + self._register_autograd_kernel() + + return inner + + def impl_backward(self, output_differentiability=None, _stacklevel=2): + r""" + This API is deprecated, please use torch.library.custom_op instead + """ + if output_differentiability is not None: + + def yell(): + raise RuntimeError( + f"impl_backward(output_differentiability): expected " + f"output_differentiability to be a list of bools with " + f"length equal to the number of outputs of this CustomOp " + f"got: {output_differentiability}" + ) + + if not isinstance(output_differentiability, list): + yell() + for diff in output_differentiability: + if not isinstance(diff, bool): + yell() + if len(self._schema.returns) != len(output_differentiability): + yell() + + def inner(f): + self._check_can_register_backward() + self._check_doesnt_have_library_autograd_impl() + if not self._registered_autograd_kernel_indirection: + self._register_autograd_kernel_indirection() + self._register_impl("backward", f, stacklevel=_stacklevel) + self._output_differentiability = output_differentiability + if self._has_impl("save_for_backward"): + self._register_autograd_kernel() + + return inner + + +@dataclasses.dataclass +class FuncAndLocation: + func: typing.Callable + location: str + + +def find_ophandle_or_throw(cpp_ns: str, operator_name: OperatorName): + overload_name = ( + "" if operator_name.overload_name is None else operator_name.overload_name + ) + return _C._dispatch_find_schema_or_throw( + f"{cpp_ns}::{str(operator_name.name)}", overload_name + ) + + +def validate_namespace(ns: str) -> None: + if "." in ns: + raise ValueError( + f'custom_op(..., ns="{ns}"): expected ns to not contain any . (and be a ' + f"valid variable name)" + ) + if ns in RESERVED_NS: + raise ValueError( + f"custom_op(..., ns='{ns}'): '{ns}' is a reserved namespace, " + f"please choose something else. " + ) + + +def validate_schema(schema: FunctionSchema) -> None: + if not torch._library.utils.is_functional_schema(schema): + raise ValueError( + f"custom_op only supports functional operators " + f"(ops that do not mutate any inputs, do not return " + f"views of the inputs, and has at least one return). " + f"Got the following non-functional schema: {schema}" + ) + + # For simplicity: don't allow self arguments + if schema.arguments.self_arg is not None: + raise ValueError( + f"custom_op does not support arguments named 'self'. Please " + f"rename your argument. Got: {schema}" + ) + + +def parse_qualname(qualname: str) -> tuple[str, str]: + names = qualname.split("::", 1) + if len(names) != 2: + raise ValueError( + f"Expected there to be a namespace in {qualname}, i.e. The " + f"operator name should look something like ns::foo" + ) + if "." in names[1]: + raise ValueError( + f"The torch.custom_ops APIs do not handle overloads, " + f"i.e. operator names with '.' in them. " + f"Please name your operator something like ns::foo. " + f"Got: {qualname}" + ) + return names[0], names[1] + + +def validate_device_type(device_type: str) -> None: + if device_type not in SUPPORTED_DEVICE_TYPE_TO_KEY: + raise ValueError( + f"CustomOp.impl(device_types=[{device_type}, ...]): we only support device_type " + f"in {SUPPORTED_DEVICE_TYPE_TO_KEY.keys()}." + ) + + +def supported_param(param: inspect.Parameter) -> bool: + return param.kind in ( + inspect.Parameter.POSITIONAL_OR_KEYWORD, + inspect.Parameter.KEYWORD_ONLY, + ) + + +def validate_function_matches_schema( + schema: FunctionSchema, func: typing.Callable +) -> None: + sig = inspect.signature(func) + + if not all(supported_param(p) for p in sig.parameters.values()): + raise ValueError( + f"custom_op(..., manual_schema)(func): positional-only args, " + f"varargs, and kwargs are not supported. Please rewrite `func` " + f"to not have them. Got `func` with signature: {sig}" + ) + + if ( + any( + p.annotation is not inspect.Parameter.empty for p in sig.parameters.values() + ) + or sig.return_annotation is not inspect.Signature.empty + ): + raise ValueError( + f"custom_op(..., manual_schema)(func): When passing in a manual " + f"schema, we expect `func` to have no type annotations to avoid " + f"ambiguity. Got `func` with signature: {sig}" + ) + + positional = [ + (name, param) + for name, param in sig.parameters.items() + if param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD + ] + kwargonly = [ + (name, param) + for name, param in sig.parameters.items() + if param.kind == inspect.Parameter.KEYWORD_ONLY + ] + + def error(): + raise ValueError( + f"custom_op(..., manual_schema)(func): When passing in a manual " + f"schema, we expect `func`'s signature to match `manual_schema` " + f"(aside from type annotations). " + f"func's signature: {sig}, manual_schema: {schema}" + ) + + def error_default_args(): + raise ValueError( + f"custom_op(..., manual_schema)(func): " + f"neither func nor manual_schema should have default " + f"arguments. Got " + f"func's signature: {sig}, manual_schema: {schema}" + ) + + def compare(sig_args, schema_args): + if len(sig_args) != len(schema_args): + error() + for (name, param), arg in zip(sig_args, schema_args): + if name != arg.name: + error() + if param.default is not inspect.Parameter.empty or arg.default is not None: + error_default_args() + + compare(positional, schema.arguments.flat_positional) + compare(kwargonly, schema.arguments.flat_kwarg_only) + + +def report_error_callback(custom_op: typing.Any, key: str) -> None: + if key == "Undefined": + raise NotImplementedError( + f"{custom_op}: There were no Tensor inputs to this operator " + f"(e.g. you passed an empty list of Tensors). If your operator is a " + f"factory function (that is, it takes no Tensors and constructs " + f"a new one), then please use CustomOp.impl_factory to register " + f"an implementation for it" + ) + if key == "Meta": + raise NotImplementedError( + f"{custom_op}: when running with device='Meta' tensors: there is no " + f"abstract impl registered for this CustomOp. Please register one via " + f"CustomOp.impl_abstract to get this CustomOp to work with Meta tensors" + ) + if key in ("CPU", "CUDA"): + device = key.lower() + raise NotImplementedError( + f"{custom_op}: when running with device='{device}' tensors: there is no " + f"{device} impl registered for this CustomOp. Please register one via " + f"CustomOp.impl(device_type='{device}')" + ) + raise NotImplementedError( + f"{custom_op}: No implementation for dispatch key {key}. It is likely " + f"that we have not added this functionality yet, please either open an " + f"issue or if you're feeling adventurous, use the low-level " + f"torch.library API" + ) + + +def custom_op_from_existing(op): + ns = op.namespace + lib = torch.library.Library(ns, "FRAGMENT") + name = op.name().split("::")[-1] + schema_str = str(op._schema) + # CustomOp expects the schema string without the namespace + schema_str = schema_str.rsplit("::", maxsplit=1)[-1] + schema = FunctionSchema.parse(schema_str) + return CustomOp(lib, ns, schema, name, op, _private_access=True) + + +def get_op(qualname): + def error_not_found(): + raise ValueError( + f"Could not find the operator {qualname}. Please make sure you have " + f"already registered the operator and (if registered from C++) " + f"loaded it via torch.ops.load_library." + ) + + ns, name = parse_qualname(qualname) + if not hasattr(torch.ops, ns): + error_not_found() + opnamespace = getattr(torch.ops, ns) + if not hasattr(opnamespace, name): + error_not_found() + packet = getattr(opnamespace, name) + if not hasattr(packet, "default"): + error_not_found() + return packet.default + + +def _find_custom_op(qualname, also_check_torch_library=False): + if qualname in global_registry: + return global_registry[qualname] + if not also_check_torch_library: + raise RuntimeError( + f'Could not find custom op "{qualname}". Did you register it via ' + f"the torch._custom_ops API?" + ) + overload = get_op(qualname) + result = custom_op_from_existing(overload) + return result + + +def get_abstract_impl(qualname): + if qualname not in torch._custom_op.impl.global_registry: + return None + custom_op = torch._custom_op.impl.global_registry[qualname] + if custom_op is None: + return None + if not custom_op._has_impl("abstract"): + return None + return custom_op._get_impl("abstract").func + + +def _custom_op_with_schema(qualname, schema, needs_fixed_stride_order=True): + ns, name = qualname.split("::") + schema_str = f"{name}{schema}" + function_schema = FunctionSchema.parse(schema_str) + validate_schema(function_schema) + tags = [torch._C.Tag.needs_fixed_stride_order] if needs_fixed_stride_order else [] + lib = library.Library(ns, "FRAGMENT") + lib.define(schema_str, tags=tags) + ophandle = find_ophandle_or_throw(ns, function_schema.name) + result = CustomOp(lib, ns, function_schema, name, ophandle, _private_access=True) + result._register_autograd_kernel_indirection() + + torch._C._dispatch_set_report_error_callback( + ophandle, functools.partial(report_error_callback, weakref.proxy(result)) + ) + return get_op(qualname) diff --git a/.venv/lib/python3.12/site-packages/torch/_custom_ops.py b/.venv/lib/python3.12/site-packages/torch/_custom_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..5203da640fa58e9ab7bf6785eb26ae1186059bee --- /dev/null +++ b/.venv/lib/python3.12/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/.venv/lib/python3.12/site-packages/torch/_decomp/__init__.py b/.venv/lib/python3.12/site-packages/torch/_decomp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3083ba8222499cacc0ee35206090ac5eda8e0213 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_decomp/__init__.py @@ -0,0 +1,571 @@ +# mypy: allow-untyped-defs +import inspect +import typing +from collections import defaultdict +from collections.abc import Callable, Sequence +from functools import lru_cache, partial, wraps +from itertools import chain +from typing import Optional, TYPE_CHECKING, TypeVar, Union +from typing_extensions import ParamSpec + + +if TYPE_CHECKING: + from torch.export.decomp_utils import CustomDecompTable + +import torch +import torch.library +from torch._ops import HigherOrderOperator, OperatorBase, OpOverload, OpOverloadPacket +from torch._prims_common import CustomOutParamAnnotation +from torch._subclasses.functional_tensor import FunctionalTensor +from torch.utils import _pytree as pytree + + +__all__ = [ + "decomposition_table", + "pre_autograd_decomposition_table", + "meta_table", + "register_decomposition", + "get_decompositions", + "core_aten_decompositions", + "_should_decompose_because_unsafe_op", +] + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +# TODO: relax key type here; torch registrations should be possible to; but +# right now this type is accurate +global_decomposition_table: dict[str, dict[torch._ops.OperatorBase, Callable]] = ( + defaultdict(dict) +) + +decomposition_table = global_decomposition_table["post_autograd"] +pre_autograd_decomposition_table = global_decomposition_table["pre_autograd"] +meta_table = global_decomposition_table["meta"] + + +def _should_decompose_because_unsafe_op(op: torch._ops.OperatorBase) -> bool: + """ + Returns True if the op must always decompose in export/compile tracing system + + In export, we always decompose certain CIA ops that are tagged with + maybe_aliasing_or_mutating because we statically need to know if the op is + mutating or not. But these CIA ops could have different behaviour in runtime. + + native_batch_norm is a prim op which has a wrong schema and it needs to be replaced + with correct schema. But until then, we will force decompose it via this tag. + """ + if not isinstance(op, torch._ops.OpOverload): + return False + if torch.Tag.maybe_aliasing_or_mutating in op.tags: + return True + return op is torch.ops.aten.native_batch_norm.default + + +def _add_op_to_registry(registry, op, fn): + """ + This is an internal API for adding an op to the decomposition table. + + If op is OpOverload, it will be added to the registry directly. + If op is OpOverloadPacket, all the valid overload_ops in the packet will be added to the registry. + """ + overloads: list[torch._ops.OpOverload] = [] + if isinstance(op, HigherOrderOperator): + # There's no concept of overloads for HigherOrderOperator + registry[op] = fn + return + elif isinstance(op, OpOverload): + overloads.append(op) + else: + if not isinstance(op, OpOverloadPacket): + raise AssertionError(f"expected OpOverloadPacket, got {type(op)}") + overloads.extend(op.op_overloads()) + + for op_overload in overloads: + if op_overload in registry: + raise RuntimeError(f"duplicate registrations for {op_overload}") + # TorchScript dumps a bunch of extra nonsense overloads + # which don't have corresponding dispatcher entries, we need + # to filter those out, e.g aten.add.float_int + if torch._C._dispatch_has_kernel(op_overload.name()): + registry[op_overload] = fn + schema = op_overload._schema + if registry is decomposition_table: + torch._C._fake_dispatch_register_decomp( + schema.name, schema.overload_name + ) + elif registry is meta_table: + torch._C._fake_dispatch_register_meta(schema.name, schema.overload_name) + elif registry is pre_autograd_decomposition_table: + # pre-autograd decomp not used by C++ faketensor + pass + elif any(registry is t for t in global_decomposition_table.values()): + raise AssertionError( + f"decomposition registry {registry!r} is not mirrored into " + "the C++ fake dispatch tables" + ) + + +def _convert_out_params(f): + out_annotation = f.__annotations__.get("out") + + # If there are no out params, do not wrap the function. + if not out_annotation: + return f + + # Hack to detect when out is a Tuple. There seems to be no pretty way of doing this + if getattr(out_annotation, "__origin__", None) is tuple: + sig = inspect.signature(f) + out_names = sig.return_annotation._fields + # If out is a tuple, we need to register a function that unpacks all the out + # elements as this is what native_functions.yaml expects + + @wraps(f) + def _fn(*args, **kwargs): + out_kwargs = tuple(kwargs.pop(o, None) for o in out_names) + # Either all of the out kwargs are set or none of them + is_none = out_kwargs[0] is None + if not all((o is None) == is_none for o in out_kwargs): + raise AssertionError( + f"all out kwargs must be set or none of them, got {out_kwargs}" + ) + return f(*args, **kwargs, out=None if is_none else out_kwargs) + + out_params = [ + inspect.Parameter( + o, + kind=inspect.Parameter.KEYWORD_ONLY, + default=None, + annotation=t, + ) + for o, t in zip(out_names, typing.get_args(out_annotation)) + ] + # Drop the out parameter and concatenate the new kwargs in the signature + params = chain((v for k, v in sig.parameters.items() if k != "out"), out_params) + _fn.__signature__ = inspect.Signature( # type: ignore[attr-defined] + parameters=params, # type: ignore[arg-type] + return_annotation=sig.return_annotation, + ) + # Drop the out parameter and concatenate the new kwargs in the annotations + _fn.__annotations__ = {k: v for k, v in f.__annotations__.items() if k != "out"} + for o in out_params: + _fn.__annotations__[o.name] = o.annotation + + # Propagate that this function is wrapped by `out_wrapper` + _fn._torch_decompositions_out_wrapper = f._torch_decompositions_out_wrapper # type: ignore[attr-defined] + + return _fn + + # Alternatively, there may be a single tensor out parameter with a name + # other than "out". This will need special treatment and is indicated by an + # annotation, which we will remove here so it is not exposed after wrapping. + custom_out_param_name = f.__annotations__.pop(CustomOutParamAnnotation, None) + if custom_out_param_name: + + @wraps(f) + def _fn(*args, **kwargs): + out_kwarg = kwargs.pop(custom_out_param_name, None) + return f(*args, **kwargs, out=out_kwarg) + + out_param = inspect.Parameter( + custom_out_param_name, + kind=inspect.Parameter.KEYWORD_ONLY, + default=None, + annotation=out_annotation, + ) + + # Drop the out parameter and concatenate the new kwarg in the signature + sig = inspect.signature(f) + params = chain( + (v for k, v in sig.parameters.items() if k != "out"), (out_param,) + ) + _fn.__signature__ = inspect.Signature( # type: ignore[attr-defined] + parameters=params, # type: ignore[arg-type] + return_annotation=sig.return_annotation, + ) + + # Drop the out parameter and concatenate the new kwargs in the annotations + _fn.__annotations__ = {k: v for k, v in f.__annotations__.items() if k != "out"} + _fn.__annotations__[out_param.name] = out_param.annotation + + return _fn + + return f + + +def register_decomposition( + aten_op, registry=None, *, type="post_autograd", unsafe=False +) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: + """ + A decorator to register a function as a decomposition to the Python + decomposition table. Use it like this:: + + @register_decomposition(torch.ops.aten.clamp_min) + def clamp_min(x): + return torch.clamp(self, min=min) + + If you are writing a new decomposition, consider contributing it + directly to PyTorch in torch._decomp.decompositions. + + This API is experimental; we are almost certainly going to extend + the API when we make decompositions eligible for use in transforms (e.g., + autograd) and not just backend tracing, where we then need to know if a + decomposition can be used to simulate a transform. + + By default, we also will register it to the Meta key of dispatcher, + and replace the c++ Meta implementation if there is already one. + + unsafe kwarg is for reuse of this function for registering non-function + things + """ + + if type not in {"post_autograd", "pre_autograd", "meta"}: + raise AssertionError( + f"type must be one of post_autograd, pre_autograd, or meta, got {type}" + ) + + def decomposition_decorator(fn: Callable[_P, _T]) -> Callable[_P, _T]: + orig_fn = fn + if not unsafe: + fn = _convert_out_params(fn) + + nonlocal registry + if registry is None: + registry = global_decomposition_table[type] + + def register(op): + _add_op_to_registry(registry, op, fn) + + # To handle allowing multiple aten_ops at once + pytree.tree_map_(register, aten_op) + return orig_fn + + return decomposition_decorator + + +def get_decompositions( + aten_ops: Sequence[torch._ops.OperatorBase | OpOverloadPacket], + type: str = "post_autograd", +) -> dict[torch._ops.OperatorBase, Callable]: + """ + Retrieve a dictionary of decompositions corresponding to the list of + operator overloads and overload packets passed as input. Overload + packets will include all decomposed overloads in the packet. If there is + no decomposition for a requested operator, it is silently ignored. + + This API is experimental; we are almost certainly going to give an alternate, + more recommended formulation, where a user provides the set of operators + they know how to implement, and we provide decompositions for everything + not in this set. + """ + if type not in {"post_autograd", "pre_autograd", "meta"}: + raise AssertionError( + f"type must be one of post_autograd, pre_autograd, or meta, got {type}" + ) + + registry = global_decomposition_table[type] + packets_to_overloads = defaultdict(list) + + for opo in registry: + if isinstance(opo, (OpOverload, OpOverloadPacket)): + packets_to_overloads[opo.overloadpacket].append(opo) + decompositions: dict[torch._ops.OperatorBase, Callable] = {} + for op in aten_ops: + if isinstance(op, OpOverloadPacket) and op in packets_to_overloads: + for op_overload in packets_to_overloads[op]: + decompositions[op_overload] = registry[op_overload] + elif isinstance(op, (torch._ops.OperatorBase)) and op in registry: + decompositions[op] = registry[op] + return decompositions + + +def remove_decompositions( + decompositions: dict[torch._ops.OperatorBase, Callable], + aten_ops: Sequence[OpOverload | OpOverloadPacket], +) -> None: + """ + Given a dictionary of decompositions obtained from get_decompositions(), removes + operators associated with a list of operator overloads and overload packets passed + as input. If the decomposition dictionary does not contain a decomposition that is + specified to be removed, it is silently ignored. + """ + for op in aten_ops: + if isinstance(op, OpOverloadPacket): + for opo in op.op_overloads(): + decompositions.pop(opo, None) + elif isinstance(op, OpOverload): + decompositions.pop(op, None) + + +# populate the table +import torch._decomp.decompositions +import torch._refs + + +def core_aten_decompositions() -> "CustomDecompTable": + from torch.export.exported_program import default_decompositions + + return default_decompositions() + + +# See NOTE [Core ATen Ops] +# +# list was copied from torch/_inductor/decomposition.py +# excluding decompositions that results in prim ops +# Resulting opset of decomposition is core aten ops +def _core_aten_decompositions_post_autograd() -> dict[ + torch._ops.OperatorBase, Callable +]: + aten = torch.ops.aten + return get_decompositions( + [ + aten.addcdiv, + aten.addcdiv_, + aten.addcmul, + aten.addcmul_, + aten.addr, + aten.affine_grid_generator, + aten.alias_copy, + aten.all, + aten.aminmax, + aten.arange.default, + aten.arange.start, + aten.avg_pool2d_backward, + aten.baddbmm, + aten.binary_cross_entropy, + aten.binary_cross_entropy_backward, + aten.binary_cross_entropy_with_logits, + aten.block_diag, + aten.bernoulli.p, + aten.bernoulli.default, + aten.celu, + aten.celu_, + aten.channel_shuffle, + aten.clamp_max, + aten.clamp_min, + aten.col2im, + aten.count_nonzero, + aten.linalg_cross, + aten.cudnn_batch_norm, + aten.cudnn_batch_norm_backward, + aten.miopen_batch_norm_backward, + aten.deg2rad, + aten.deg2rad_, + aten.detach, + aten.diag_embed, + aten.diagonal_backward, + aten.diagonal_copy, + aten.dot, + aten.vdot, + aten.elu_, + aten.elu_backward, + aten._embedding_bag, + aten.embedding_dense_backward, + aten.empty_like, + aten._euclidean_dist.default, + aten.expand_as, + aten.expand_copy, + aten.eye, + aten.fill, + aten.fill_, + aten.floor_divide, + aten.frac, + aten.frac_, + aten._fused_moving_avg_obs_fq_helper, + aten.gelu_, + aten.gelu_backward, + aten.glu, + aten.glu_backward, + aten.hardshrink, + aten.hardsigmoid, + aten.hardsigmoid_, + aten.hardsigmoid_backward, + aten.hardswish, + aten.hardswish_, + aten.hardswish_backward, + aten.hardtanh_, + aten.hardtanh_backward, + aten.hann_window, + aten.heaviside, + aten.heaviside_, + aten.huber_loss, + aten.huber_loss_backward, + aten.im2col, + aten.index_add.out, + aten.index_add.default, + aten.index_add_, + aten.index_copy.out, + aten.index_copy.default, + aten.index_copy_, + aten.index_fill.int_Scalar, + aten.index_fill.int_Tensor, + aten.index_fill.int_Scalar_out, + aten.index_fill.int_Tensor_out, + aten.index_fill_, + aten.isin, + aten.isneginf, + aten.isposinf, + aten.l1_loss, + aten._lazy_clone, + aten._test_parallel_materialize, + aten.leaky_relu_, + aten.leaky_relu_backward, + aten.lerp, + aten.lerp_, + aten.linalg_vector_norm, + aten.linspace, + aten.logaddexp, + aten.logaddexp2, + aten.logit, + aten.logit_, + aten.logit_backward, + aten.log_sigmoid_backward, + aten.log_sigmoid_forward, + aten._log_softmax_backward_data, + aten.logspace, + aten.logsumexp.default, + aten.masked_fill, + aten.masked_fill_, + aten.max_unpool2d, + aten.max_unpool3d, + aten.mish, + aten.mish_, + aten.mish_backward, + aten.mse_loss, + aten.mse_loss_backward, + aten.multi_margin_loss, + aten.multilabel_margin_loss_forward, + aten.mv, + aten.mvlgamma, + aten.mvlgamma_, + aten.nansum, + aten.nan_to_num, + aten.nan_to_num_, + aten.narrow, + aten.native_batch_norm_backward, + aten.native_dropout_backward, + aten.native_group_norm_backward, + aten.native_layer_norm_backward, + aten._fused_rms_norm, + aten._fused_rms_norm_backward, + aten.new_empty, + aten.new_full, + aten.new_ones, + aten.new_zeros, + aten.nll_loss2d_forward, + aten.nll_loss2d_backward, + aten.nll_loss_backward, + aten.nll_loss_forward, + aten.norm.ScalarOpt_dtype, + aten.norm.Scalar, + aten.norm.ScalarOpt_dim_dtype, + aten.norm.ScalarOpt_dim, + aten.norm.dtype_out, + aten.norm.out, + aten.norm.ScalarOpt_dtype_out, + aten.norm.Scalar_out, + aten.ones, + aten.ones_like, + aten.pixel_shuffle, + aten.pixel_unshuffle, + aten._prelu_kernel, + aten._prelu_kernel_backward, + aten._reshape_alias, + aten.rad2deg, + aten.rad2deg_, + aten.reflection_pad1d, + aten.reflection_pad1d_backward, + aten.reflection_pad2d, + aten.reflection_pad2d_backward, + aten.reflection_pad3d, + aten.reflection_pad3d_backward, + aten.replication_pad1d, + aten.replication_pad2d, + aten.replication_pad3d, + aten.renorm, + aten.renorm_, + aten.replication_pad2d, + aten.resize_as, + aten.roll, + aten.rot90, + aten.rrelu_with_noise, + aten.rrelu_with_noise_, + aten.rsub, + aten._safe_softmax, + aten._scaled_dot_product_flash_attention_for_cpu.default, + aten.select_backward, + aten.select_scatter, + aten.sgn, + aten.sgn_, + aten.sigmoid_backward, + aten.silu, + aten.silu_, + aten.silu_backward.grad_input, + aten.silu_backward, + aten.sinc, + aten.sinc_, + aten.slice_backward, + aten.smooth_l1_loss, + aten.smooth_l1_loss_backward, + aten.soft_margin_loss, + aten.soft_margin_loss_backward, + aten._softmax_backward_data, + aten.softplus, + aten.softplus_backward, + aten.softshrink, + aten.special_entr, + aten.special_log_ndtr, + aten.special_xlog1py, + aten.split.Tensor, + aten.split_with_sizes_copy, + aten.squeeze_copy, + aten.squeeze.default, + aten.squeeze.dim, + aten.std.correction, + aten.std.out, + aten.std.correction_out, + aten.std_mean.correction, + aten.std_mean.correction_out, + aten.stack, + aten.sum.default, + aten.sum.out, + aten.t, + aten.t_copy, + aten.take, + aten.tanh_backward, + aten.threshold, + aten.threshold_, + aten.threshold_backward, + aten.trace, + aten.transpose.int, + aten.transpose_copy, + aten.tril, + aten.tril_, + aten.triu, + aten.triu_, + aten.unbind, + aten.unfold_backward, + aten.unfold_copy, + aten._unsafe_index, + aten._unsafe_index_put, + aten._unsafe_masked_index, + aten._unsafe_masked_index_put_accumulate, + aten.unsafe_split.Tensor, + aten.unsafe_split_with_sizes, + aten.unsqueeze_copy, + aten._unsafe_view, + aten.upsample_linear1d, + aten.upsample_bilinear2d.out, + aten.upsample_trilinear3d.out, + aten.upsample_nearest2d_backward, + aten.view_as_complex, + aten.xlogy, + aten.xlogy_, + aten.zero, + aten.zero_, + aten.zeros, + aten.zeros_like, + aten._chunk_cat, + aten._weight_norm_interface, + ] + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3042b6dbc42e2fc0b5ada783622ff14a6be133a0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/decompositions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/decompositions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1038608847176f5fd13b67e2a99e21d8bdf1428 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/decompositions.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1727002c793d917760fda14fe2ef9ae3f2c26f9ea597a55fdddec5ac57540701 +size 282721 diff --git a/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/decompositions_for_jvp.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/decompositions_for_jvp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da2b6030104fa12b9f4168491eb14d470a59b4f4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/decompositions_for_jvp.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/decompositions_for_rng.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/decompositions_for_rng.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..249879b77f73818d363843bf955dcfe395ce8749 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_decomp/__pycache__/decompositions_for_rng.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_decomp/decompositions.py b/.venv/lib/python3.12/site-packages/torch/_decomp/decompositions.py new file mode 100644 index 0000000000000000000000000000000000000000..63be1dabca1dd2a0591511f673dd25f5d130d313 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_decomp/decompositions.py @@ -0,0 +1,6305 @@ +# mypy: allow-untyped-decorators +# mypy: allow-untyped-defs +import functools +import itertools +import numbers +import operator +import sys +from collections.abc import Callable, Iterable +from contextlib import nullcontext +from enum import Enum +from functools import partial, reduce +from itertools import chain, product +from typing import Any, cast + +import torch +import torch._meta_registrations +import torch._prims as prims +import torch._prims_common as utils +import torch.nn.functional as F +from torch import sym_float, sym_int, Tensor +from torch._decomp import register_decomposition +from torch._higher_order_ops.out_dtype import out_dtype +from torch._prims_common import ( + IntLike, + NumberType, + suggest_memory_format, + TensorLike, + TensorSequenceType, +) +from torch._prims_common.wrappers import ( + _maybe_convert_to_dtype, + _maybe_resize_out, + _safe_copy_out, + out_wrapper, +) +from torch.utils import _pytree as pytree +from torch.utils._pytree import tree_map + + +DispatchKey = torch._C.DispatchKey # type: ignore[attr-defined] + +# None of these functions are publicly accessible; get at them +# from torch._decomps +__all__: list[str] = [] + +aten = torch._ops.ops.aten + + +class Reduction(Enum): + NONE = 0 + MEAN = 1 + SUM = 2 + + +# This wraps a decomposition and performs various type promotion logic within it, depending on the strategy provided +# We're currently reusing ELEMENTWISE_TYPE_PROMOTION_KIND, although some of the usages are on non-elementwise ops +# Will need to validate the non-elementwise uses +def type_casts( + f: Callable, + type_promotion: utils.ELEMENTWISE_TYPE_PROMOTION_KIND, + compute_dtype_only: bool = False, + include_non_tensor_args: bool = False, +): + @functools.wraps(f) + def inner(*args, **kwargs): + allowed_types = ( + (Tensor, torch.types._Number) if include_non_tensor_args else (Tensor,) + ) # type: ignore[arg-type] + flat_args = [ + x + for x in pytree.arg_tree_leaves(*args, **kwargs) + if isinstance(x, allowed_types) + ] + computation_dtype, result_dtype = utils.elementwise_dtypes( + *flat_args, type_promotion_kind=type_promotion + ) + + # TODO: pretty sure this is not quite right + def increase_prec(x): + if isinstance(x, Tensor): + return x.to(computation_dtype) + else: + return x + + def decrease_prec(x): + if isinstance(x, Tensor): + return x.to(result_dtype) + else: + return x + + r = f(*tree_map(increase_prec, args), **tree_map(increase_prec, kwargs)) + if compute_dtype_only: + return r + else: + return tree_map(decrease_prec, r) + + return inner + + +compute_only_pw_cast_for_opmath = partial( + type_casts, + type_promotion=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + compute_dtype_only=True, +) +pw_cast_for_opmath = partial( + type_casts, type_promotion=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT +) +pw_cast_for_opmath_non_tensor_args = partial( + type_casts, + type_promotion=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + include_non_tensor_args=True, +) +pw_cast_for_int_to_real = partial( + type_casts, type_promotion=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT +) + + +# This expands x until x.dim() == dim. Might be useful as an operator +def _unsqueeze_to_dim(x: Tensor, dim: int) -> Tensor: + for _ in range(dim - x.dim()): + x = x.unsqueeze(-1) + return x + + +@register_decomposition(aten.tanh_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def tanh_backward(out_grad: Tensor, y: Tensor): + return out_grad * (1 - y * y).conj_physical() + + +@register_decomposition(aten.sigmoid_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def sigmoid_backward(out_grad: Tensor, y: Tensor): + return out_grad * (y * (1 - y)).conj_physical() + + +@register_decomposition(aten.softplus_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def softplus_backward(out_grad: Tensor, x: Tensor, beta: float, threshold: float): + z = (x * beta).exp() + return torch.where((x * beta) > threshold, out_grad, out_grad * z / (z + 1.0)) + + +@register_decomposition(aten.elu_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def elu_backward( + grad_output: Tensor, + alpha: float, + scale: float, + input_scale: float, + is_result: bool, + self_or_result: Tensor, +): + negcoef = alpha * scale + poscoef = scale + negiptcoef = input_scale + if is_result: + return torch.where( + self_or_result <= 0, + grad_output * negiptcoef * (self_or_result + negcoef), + grad_output * poscoef, + ) + else: + return torch.where( + self_or_result <= 0, + grad_output * negiptcoef * negcoef * torch.exp(self_or_result * negiptcoef), + grad_output * poscoef, + ) + + +@register_decomposition([aten.fill.Scalar]) +def fill_scalar(self, value): + return torch.full_like(self, value) + + +@register_decomposition([aten.fill.Tensor]) +def fill_tensor(self, value: Tensor): + torch._check( + value.dim() == 0, + lambda: f"fill only supports 0-dimension value tensor but got tensor with {value.dim()} dimensions", + ) + return aten.copy(self, value) + + +@register_decomposition(aten.hardsigmoid) +@out_wrapper() +@pw_cast_for_opmath +def hardsigmoid(self: Tensor) -> Tensor: + return torch.clamp(torch.clamp(self + 3, min=0), max=6) / 6 + + +@register_decomposition(aten.hardsigmoid_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def hardsigmoid_backward(grad_output: Tensor, self: Tensor): + return torch.where( + (self > -3.0) & (self < 3.0), + grad_output * (1.0 / 6.0), + 0.0, + ) + + +@register_decomposition(aten.hardtanh_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def hardtanh_backward( + grad_output: Tensor, self: Tensor, min_val: float, max_val: float +): + # Compare in opmath (compute) dtype to match the eager kernel, which casts + # self to opmath_t before comparing against the float bounds. Comparing in + # the low-precision input dtype would round the bound and misclassify + # boundary values (e.g. bf16(0.7) == 0.69921875 vs max_val=0.7). + return torch.where((self <= min_val) | (self >= max_val), 0.0, grad_output) + + +@register_decomposition(aten.hardswish) +@out_wrapper() +@pw_cast_for_opmath +def hardswish(self: Tensor) -> Tensor: + return self * torch.clamp(torch.clamp(self + 3, min=0), max=6) / 6 + + +@register_decomposition(aten.hardswish_backward) +@out_wrapper() +@pw_cast_for_opmath +def hardswish_backward(grad_output: Tensor, self: Tensor) -> Tensor: + return torch.where( + self <= -3, + 0.0, + torch.where(self < 3, grad_output * ((self / 3) + 0.5), grad_output), + ) + + +@register_decomposition(aten.threshold_backward) +@out_wrapper("grad_input") +def threshold_backward(grad_output: Tensor, self: Tensor, threshold: float): + return torch.where(self <= threshold, 0, grad_output) + + +@register_decomposition(aten.leaky_relu_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def leaky_relu_backward( + grad_output: Tensor, self: Tensor, negative_slope: float, self_is_result: bool +): + return torch.where(self > 0, grad_output, grad_output * negative_slope) + + +@register_decomposition(aten.gelu_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def gelu_backward(grad: Tensor, self: Tensor, approximate: str = "none"): + M_SQRT2 = 1.41421356237309504880 + M_SQRT1_2 = 0.70710678118654752440 + M_2_SQRTPI = 1.12837916709551257390 + if approximate == "tanh": + kBeta = M_SQRT2 * M_2_SQRTPI * 0.5 + kKappa = 0.044715 + x_sq = self * self + x_cube = x_sq * self + inner = kBeta * (self + kKappa * x_cube) + tanh_inner = torch.tanh(inner) + + left = 0.5 * self + right = 1 + tanh_inner + + left_derivative = 0.5 * right + + tanh_derivative = 1 - tanh_inner * tanh_inner + inner_derivative = kBeta * (1 + 3 * kKappa * x_sq) + right_derivative = left * tanh_derivative * inner_derivative + + return grad * (left_derivative + right_derivative) + else: + kAlpha = M_SQRT1_2 + kBeta = M_2_SQRTPI * M_SQRT1_2 * 0.5 + cdf = 0.5 * (1 + torch.erf(self * kAlpha)) + pdf = kBeta * torch.exp(self * self * -0.5) + return grad * (cdf + self * pdf) + + +@register_decomposition(aten.mish_backward) +@pw_cast_for_opmath +def mish_backward(grad_output: Tensor, input: Tensor): + input_tanh_softplus = torch.tanh(F.softplus(input)) + input_sigmoid = torch.sigmoid(input) + out = input * input_sigmoid * (1 - input_tanh_softplus * input_tanh_softplus) + return grad_output * (input_tanh_softplus + out) + + +@register_decomposition(aten.silu) +@out_wrapper() +@pw_cast_for_opmath +def silu(self: Tensor) -> Tensor: + return self * torch.sigmoid(self) + + +@register_decomposition(aten.silu_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def silu_backward(grad_output: Tensor, self: Tensor) -> Tensor: + sigmoid = torch.sigmoid(self) + return grad_output * sigmoid * (1 + self * (1 - sigmoid)) + + +@register_decomposition(aten._prelu_kernel) +def _prelu_kernel(self: Tensor, weight: Tensor) -> Tensor: + return torch.where(self > 0, self, weight * self) + + +@register_decomposition(aten._prelu_kernel_backward) +def _prelu_kernel_backward( + grad_output: Tensor, + self: Tensor, + weight: Tensor, +) -> tuple[Tensor, Tensor]: + input_grad = torch.where(self > 0, grad_output, weight * grad_output) + weight_grad = torch.where(self > 0, 0.0, self * grad_output) + return (input_grad, weight_grad) + + +@register_decomposition(aten.rrelu_with_noise_backward) +@out_wrapper() +@pw_cast_for_opmath +def rrelu_with_noise_backward( + grad_output: Tensor, + self: Tensor, + noise: Tensor, + lower: float, + upper: float, + training: bool, + self_is_result: bool, +) -> Tensor: + if training: + return grad_output.mul(noise) + else: + negative_slope = (lower + upper) / 2 + return aten.leaky_relu_backward( + grad_output, self, negative_slope, self_is_result + ) + + +@register_decomposition(aten.log_sigmoid_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def log_sigmoid_backward(grad_output: Tensor, self: Tensor, buffer: Tensor) -> Tensor: + in_negative = self < 0 + max_deriv = torch.where(in_negative, 1, 0) + sign = torch.where(in_negative, 1, -1) + # On CPU, forward saves buffer = exp(-|x|); reuse it to match the native kernel. + # On CUDA/XPU, buffer is empty so we recompute. + z = buffer if buffer.numel() > 0 else torch.exp(-torch.abs(self)) + return grad_output * (max_deriv - sign * (z / (1 + z))) + + +@register_decomposition(aten.ldexp) +@out_wrapper() +def ldexp(self: Tensor, other: Tensor) -> Tensor: + two_dtype = ( + torch.float32 + if utils.is_integer_dtype(self.dtype) or utils.is_boolean_dtype(self.dtype) + else self.dtype + ) + two_tensor = self.new_full((), 2.0, dtype=two_dtype) + return self * torch.pow(two_tensor, other) + + +def apply_loss_reduction(loss: Tensor, reduction: int): + if reduction == Reduction.MEAN.value: + return torch.mean(loss) + elif reduction == Reduction.SUM.value: + return torch.sum(loss) + else: + return loss + + +def to_real_dtype(dtype: torch.dtype): + if dtype == torch.complex32: + return torch.float16 + elif dtype == torch.complex64: + return torch.float32 + elif dtype == torch.complex128: + return torch.float64 + + +# TODO: None of these loss castings are quite correct, see +# https://github.com/pytorch/pytorch/issues/76870. Also, the ATen kernels +# perform the pointwise portion in opmath, but don't maintain it between the +# pointwise portion and the reduction + + +@register_decomposition(aten.mse_loss) +@out_wrapper() +@pw_cast_for_opmath +def mse_loss( + self: Tensor, target: Tensor, reduction: int = Reduction.MEAN.value +) -> Tensor: + loss = (self - target) ** 2 + return apply_loss_reduction(loss, reduction) + + +@register_decomposition(aten.mse_loss_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def mse_loss_backward( + grad_output: Tensor, input: Tensor, target: Tensor, reduction: int +): + norm = 2.0 / input.numel() if reduction == Reduction.MEAN.value else 2.0 + return norm * (input - target) * grad_output + + +@register_decomposition(aten._safe_softmax) +def safe_softmax(self, dim, dtype=None): + out = torch.softmax(self, dim=dim, dtype=dtype) + masked = self.eq(float("-inf")) + masked_rows = torch.all(masked, dim=dim, keepdim=True) + zeros = torch.zeros_like(out) + return torch.where(masked_rows, zeros, out) + + +@register_decomposition(aten.smooth_l1_loss) +@out_wrapper() +@pw_cast_for_opmath +def smooth_l1_loss( + self: Tensor, + target: Tensor, + reduction: int = Reduction.MEAN.value, + beta: float = 1.0, +): + loss = (self - target).abs() + + loss = torch.where(loss < beta, 0.5 * loss**2 / beta, loss - 0.5 * beta) + return apply_loss_reduction(loss, reduction) + + +@register_decomposition(aten.smooth_l1_loss_backward.default) +@pw_cast_for_opmath +def smooth_l1_loss_backward( + grad_output: Tensor, self: Tensor, target: Tensor, reduction: int, beta: float +): + norm = 1.0 / self.numel() if reduction == Reduction.MEAN.value else 1.0 + x = self - target + abs_x = torch.abs(x) + norm_grad = norm * grad_output + return torch.where( + abs_x < beta, + norm_grad * x / beta, + norm_grad * torch.sign(x), + ) + + +@register_decomposition(aten.smooth_l1_loss_backward.grad_input) +@pw_cast_for_opmath +def smooth_l1_loss_backward_out( + grad_output: Tensor, + self: Tensor, + target: Tensor, + reduction: int, + beta: float, + grad_input: Tensor, +): + result = smooth_l1_loss_backward(grad_output, self, target, reduction, beta) + _maybe_resize_out(grad_input, result.shape) + return _safe_copy_out(copy_from=result, copy_to=grad_input, exact_dtype=True) + + +@register_decomposition(aten.huber_loss_backward.default) +@pw_cast_for_opmath +def huber_loss_backward( + grad_output: Tensor, self: Tensor, target: Tensor, reduction: int, delta: float +): + norm = 1.0 / self.numel() if reduction == Reduction.MEAN.value else 1.0 + x = self - target + return torch.where( + x < -delta, + -norm * grad_output * delta, + torch.where(x > delta, norm * grad_output * delta, norm * x * grad_output), + ) + + +# We cannot use @out_wrapper() here, because the output tensor is not named 'out', it's 'grad_input' +@register_decomposition(aten.huber_loss_backward.out) +@pw_cast_for_opmath +def huber_loss_backward_out( + grad_output: Tensor, + self: Tensor, + target: Tensor, + reduction: int, + delta: float, + grad_input: Tensor, +): + result = huber_loss_backward(grad_output, self, target, reduction, delta) + _maybe_resize_out(grad_input, result.shape) + return _safe_copy_out(copy_from=result, copy_to=grad_input, exact_dtype=True) + + +def _nll_loss_backward( + grad_output: Tensor, + self: Tensor, + target: Tensor, + weight: Tensor | None, + reduction: int, + ignore_index: int, + total_weight: Tensor, +) -> Tensor: + channel_dim = 0 if self.dim() < 2 else 1 + if reduction == Reduction.MEAN.value: + grad_output = grad_output / total_weight + + # When self is 1D (no batch dim), the C++ kernel only uses target[0]. + # Reduce target to a scalar so the subsequent unsqueeze produces a 1D + # tensor matching self's dimensionality. + if self.dim() == 1 and target.dim() > 0: + target = target[0] + + target = target.unsqueeze(channel_dim) + safe_target = torch.where(target != ignore_index, target, 0) + grad_input = torch.zeros_like(self) + grad_input = torch.scatter(grad_input, channel_dim, safe_target, -1.0) + + if grad_input.dim() > grad_output.dim() > 0: + grad_output = grad_output.unsqueeze(channel_dim) + + if weight is not None: + new_shape = [1 for _ in range(self.dim())] + new_shape[channel_dim] = weight.shape[0] + weight = weight.reshape(new_shape) + grad_output = grad_output * weight + + grad_output = torch.where(target != ignore_index, grad_output, 0) + + return grad_input * grad_output + + +@register_decomposition(aten.glu_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def glu_backward(grad_output: Tensor, self: Tensor, dim: int) -> Tensor: + if self.dim() <= 0: + raise AssertionError("glu does not support 0-dimensional tensors") + wrap_dim = utils.canonicalize_dim(self.dim(), dim) + nIn = self.size(wrap_dim) + if nIn % 2 != 0: + raise AssertionError( + f"Halving dimension must be even, but dimension {wrap_dim} is size {nIn}" + ) + inputSize = nIn // 2 + firstHalf = self.narrow(wrap_dim, 0, inputSize) + secondHalf = self.narrow(wrap_dim, inputSize, inputSize) + gradInputFirstHalf = torch.sigmoid(secondHalf) + gradInputSecondHalf = ( + (1.0 - gradInputFirstHalf) * gradInputFirstHalf * firstHalf * grad_output + ) + gradInputFirstHalf = gradInputFirstHalf * grad_output + return torch.cat([gradInputFirstHalf, gradInputSecondHalf], dim=wrap_dim) + + +@register_decomposition(aten.nll_loss_backward) +@out_wrapper("grad_input") +def nll_loss_backward( + grad_output: Tensor, + self: Tensor, + target: Tensor, + weight: Tensor | None, + reduction: int, + ignore_index: int, + total_weight: Tensor, +) -> Tensor: + if not (0 <= self.dim() <= 2): + raise AssertionError(f"input tensor should be 1D or 2D, got {self.dim()}D") + if target.dim() > 1: + raise AssertionError( + f"0D or 1D target tensor expected, multi-target not supported, got {target.dim()}D" + ) + + no_batch_dim = self.dim() == 1 and target.dim() == 0 + if not (no_batch_dim or (self.shape[0] == target.shape[0])): + raise AssertionError( + f"size mismatch (got input: {self.shape}, target: {target.shape})" + ) + if total_weight.numel() != 1: + raise AssertionError( + f"expected total_weight to be a single element tensor, got: " + f"{total_weight.shape} ({total_weight.numel()} elements)" + ) + + if weight is not None and weight.numel() != self.shape[-1]: + raise AssertionError( + "weight tensor should be defined either for all or no classes" + ) + + if reduction == Reduction.NONE.value and self.dim() == 2: + if not (grad_output.dim() == 1 and grad_output.shape[0] == self.shape[0]): + raise AssertionError( + f"Expected a tensor of dimension 1 and tensor.size[0] == {self.shape[0]} but " + f"got: dimension {grad_output.dim()} and tensor.size[0] == {grad_output.shape[0]}" + ) + else: + if not (grad_output.dim() <= 1 and grad_output.numel() == 1): + raise AssertionError( + f"Expected a single element grad_output tensor, but got: {grad_output.shape}" + ) + + return _nll_loss_backward( + grad_output, self, target, weight, reduction, ignore_index, total_weight + ) + + +@register_decomposition(aten.nll_loss2d_backward) +@out_wrapper("grad_input") +def nll_loss2d_backward( + grad_output: Tensor, + self: Tensor, + target: Tensor, + weight: Tensor | None, + reduction: int, + ignore_index: int, + total_weight: Tensor, +) -> Tensor: + if self.dim() != 4: + raise AssertionError( + f"only batches of spatial inputs supported (4D tensors), but got input of dimension: {self.dim()}" + ) + + if target.dim() != 3: + raise AssertionError( + f"only batches of spatial targets supported (3D tensors) but got targets of dimension: {target.dim()}" + ) + + if not ( + self.shape[0] == target.shape[0] + and self.shape[2] == target.shape[1] + and self.shape[3] == target.shape[2] + ): + raise AssertionError( + f"size mismatch (got input: {self.shape}, target: {target.shape}" + ) + + if total_weight.numel() != 1: + raise AssertionError( + f"expected total_weight to be a single element tensor, " + f"got: {total_weight.shape} ( {total_weight.numel()}, elements)" + ) + + return _nll_loss_backward( + grad_output, self, target, weight, reduction, ignore_index, total_weight + ) + + +@register_decomposition(aten.binary_cross_entropy) +@out_wrapper() +@pw_cast_for_opmath +def binary_cross_entropy( + self: Tensor, + target: Tensor, + weight: Tensor | None = None, + reduction: int = Reduction.MEAN.value, +) -> Tensor: + # We cannot currently model this without introducing data-dependent control flow + # TORCH_CHECK( + # (input_val >= 0) && (input_val <= 1), + # "all elements of input should be between 0 and 1" + # ) + loss = (target - 1) * torch.maximum( + torch.log1p(-self), self.new_full((), -100) + ) - target * torch.maximum(torch.log(self), self.new_full((), -100)) + if weight is not None: + loss = loss * weight + return apply_loss_reduction(loss, reduction) + + +@register_decomposition(aten.binary_cross_entropy_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def binary_cross_entropy_backward( + grad_output: Tensor, + self: Tensor, + target: Tensor, + weight: Tensor | None = None, + reduction: int = Reduction.MEAN.value, +) -> Tensor: + EPSILON = 1e-12 + result = grad_output * (self - target) / torch.clamp(self * (1 - self), min=EPSILON) + if weight is not None: + result = result * weight + if reduction == Reduction.MEAN.value: + result = result / self.numel() + return result + + +@register_decomposition(aten.soft_margin_loss) +@out_wrapper() +@pw_cast_for_opmath +def soft_margin_loss( + input: Tensor, + target: Tensor, + reduction: int = Reduction.MEAN.value, +) -> Tensor: + loss = torch.log1p(torch.exp(-input * target)) + return apply_loss_reduction(loss, reduction) + + +@register_decomposition(aten.soft_margin_loss_backward) +@out_wrapper("grad_input") +@pw_cast_for_opmath +def soft_margin_loss_backward( + grad_output: Tensor, + self: Tensor, + target: Tensor, + reduction: int = Reduction.MEAN.value, +) -> Tensor: + grad_input = target * grad_output * (torch.sigmoid(target * self) - 1) + if reduction == Reduction.MEAN.value: + grad_input = grad_input / self.numel() + return grad_input + + +@register_decomposition(aten.dist) +@out_wrapper() +def dist(input: Tensor, other: Tensor, p: float = 2): + return aten.norm(input - other, p=p) + + +@register_decomposition(aten._euclidean_dist) +@out_wrapper() +def _euclidean_dist(x1: Tensor, x2: Tensor) -> Tensor: + x1_norm = x1.pow(2).sum(-1, True) + x1_pad = torch.ones_like(x1_norm, memory_format=torch.contiguous_format) + x2_norm = x2.pow(2).sum(-1, True) + x2_pad = torch.ones_like(x2_norm, memory_format=torch.contiguous_format) + x1_ = torch.cat([x1.mul(-2), x1_norm, x1_pad], -1) + x2_ = torch.cat([x2, x2_pad, x2_norm], -1) + result = x1_.matmul(x2_.mT) + return result.clamp_min(0).sqrt() + + +@register_decomposition(aten.slice_backward) +@out_wrapper() +def slice_backward( + grad_output: Tensor, + input_sizes: list[int], + dim: int, + start: int, + end: int, + step: int, +): + grad_input = grad_output.new_zeros(input_sizes) + return torch.slice_scatter(grad_input, grad_output, dim, start, end, step) + + +@register_decomposition(aten.slice.Tensor) +def slice_forward( + # Tensor(a) self, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1 + self: Tensor, + dim: int = 0, + start: int | None = None, + end: int | None = None, + step: int = 1, +): + from torch.fx.experimental.symbolic_shapes import statically_known_true + + ndim = self.dim() + if ndim == 0: + raise RuntimeError("slice() cannot be applied to a 0-dim tensor.") + dim = utils.canonicalize_dim(self.dim(), dim) + sizes = list(self.size()) + strides = list(self.stride()) + + if step <= 0: + raise RuntimeError("slice step must be positive") + + start_val = start if start is not None else 0 + end_val = end if end is not None else sys.maxsize # 2^63 - 1 + + if start_val < 0: + start_val += sizes[dim] + + if end_val < 0: + end_val += sizes[dim] + + if start_val < 0: + start_val = 0 + elif start_val > sizes[dim]: + start_val = sizes[dim] + + if statically_known_true(end_val == sys.maxsize): + end_val = sizes[dim] + elif end_val < start_val: + end_val = start_val + elif end_val > sizes[dim]: + end_val = sizes[dim] + + storage_offset = self.storage_offset() + start_val * strides[dim] + len = end_val - start_val + sizes[dim] = (len + step - 1) // step + strides[dim] *= step + + if self.is_quantized: + raise NotImplementedError( + "Slice decomposition for quantized tensors aren't implemented" + ) + else: + return self.as_strided(sizes, strides, storage_offset) + + +def _normalize_start_end( + x: Tensor, dim: int, start: int | None, end: int | None +) -> tuple[int, int]: + """ + Normalize start and end such that both are in the range + [0, x.get_size()[dim]] and start <= end. + """ + dim_size = x.shape[dim] + + def clamp_wrap(val, lower, upper, default) -> int: + if val is None: + return default + if val < 0: + val = val + dim_size + return min(max(val, lower), upper) + + start = clamp_wrap(start, 0, dim_size, 0) + end = clamp_wrap(end, start, dim_size, dim_size) + return start, end + + +# This is not in torch._refs because aten.index used by +# aten._unsafe_masked_index does not have a decomposition. +@register_decomposition(aten.slice_scatter) +@out_wrapper() +def slice_scatter( + input: Tensor, + src: Tensor, + dim: int = 0, + start: int | None = None, + end: int | None = None, + step: int = 1, +): + dim = utils.canonicalize_dim(input.ndim, dim) + dim_size = input.shape[dim] + start, end = _normalize_start_end(input, dim, start, end) + + src_size = list(input.shape) + src_size[dim] = (end - start + (step - 1)) // step + src = src.expand(src_size) + + if start == 0 and end == dim_size and step == 1: + return src.clone() + + indices: list[Tensor | None] = [None] * input.dim() + idx = torch.arange(dim_size, device=input.device) + indices[dim] = (idx - start) // step + + mask = torch.ones(dim_size, device=input.device, dtype=torch.bool) + if start != 0: + mask = torch.logical_and(mask, idx >= start) + + if end != dim_size: + mask = torch.logical_and(mask, idx < end) + + if step != 1: + mask = torch.logical_and(mask, (idx - start) % step == 0) + + mask_shape = [1] * input.dim() + mask_shape[dim] = -1 + mask = mask.view(mask_shape) + return aten.where(mask, aten._unsafe_masked_index(src, mask, indices, 0), input) + + +@register_decomposition(aten.select_backward) +@out_wrapper() +def select_backward(grad_output: Tensor, input_sizes: list[int], dim: int, index: int): + grad_input = grad_output.new_zeros(input_sizes) + return torch.select_scatter(grad_input, grad_output, dim, index) + + +@register_decomposition(aten.diagonal_backward) +@out_wrapper() +def diagonal_backward( + grad_output: Tensor, input_sizes: list[int], offset: int, dim1: int, dim2: int +): + grad_input = grad_output.new_zeros(input_sizes) + return torch.diagonal_scatter(grad_input, grad_output, offset, dim1, dim2) + + +def _cast_grad_to_input_dtype( + grad_output: Tensor, grad_input: Tensor, input_dtype: torch.dtype +): + if grad_output.dtype != input_dtype: + grad_input = grad_input.to(input_dtype) + return grad_input + + +@register_decomposition(aten._softmax_backward_data) +@out_wrapper("grad_input") +@compute_only_pw_cast_for_opmath +def _softmax_backward_data( + grad_output: Tensor, output: Tensor, dim: int, input_dtype: torch.dtype +): + new_grad_output = grad_output * output + grad_input = new_grad_output - output * torch.sum( + new_grad_output, dim=dim, keepdim=True + ) + + # CPU kernel doesn't respect input_dtype, but following check doesn't work for meta tensor + # if grad_output.device == torch.device("cpu"): + # return grad_input.contiguous() + + return _cast_grad_to_input_dtype(grad_output, grad_input, input_dtype).contiguous() + + +@register_decomposition(aten._log_softmax_backward_data) +@out_wrapper() +@compute_only_pw_cast_for_opmath +def _log_softmax_backward_data( + grad_output: Tensor, output: Tensor, dim: int, input_dtype: torch.dtype +): + grad_input = grad_output - torch.exp(output) * torch.sum( + grad_output, dim=dim, keepdim=True + ) + return _cast_grad_to_input_dtype(grad_output, grad_input, input_dtype) + + +def _im2col_col2im_indices_along_dim( + input_d, kernel_d, dilation_d, padding_d, stride_d, device +): + """Utility function to implement im2col and col2im""" + blocks_d = input_d + padding_d * 2 - dilation_d * (kernel_d - 1) + + arange_kw = partial(torch.arange, dtype=torch.int64, device=device) + + # Stride kernel over input and find starting indices along dim d + blocks_d_indices = arange_kw(0, blocks_d, stride_d).unsqueeze(0) + + # Apply dilation on kernel and find its indices along dim d + kernel_grid = arange_kw(0, kernel_d * dilation_d, dilation_d).unsqueeze(-1) + + # Broadcast and add kernel starting positions (indices) with + # kernel_grid along dim d, to get block indices along dim d + return blocks_d_indices + kernel_grid + + +@register_decomposition(aten.im2col) +@out_wrapper() +def im2col( + input: Tensor, + kernel_size: list[int], + dilation: list[int], + padding: list[int], + stride: list[int], +) -> Tensor: + torch._check(len(kernel_size) == 2, lambda: "im2col(): only 2D kernel supported") + torch._check(len(dilation) == 2, lambda: "im2col(): only 2D dilation supported") + torch._check(len(padding) == 2, lambda: "im2col(): only 2D padding supported") + torch._check(len(stride) == 2, lambda: "im2col(): only 2D stride supported") + + def check_positive(param, param_name, strict=True): + cond = all(p > 0 for p in param) if strict else all(p >= 0 for p in param) + torch._check( + cond, lambda: f"{param_name} should be greater than zero, but got {param}" + ) + + check_positive(kernel_size, "kernel_size") + check_positive(dilation, "dilation") + check_positive(dilation, "padding", strict=False) + check_positive(stride, "stride") + + shape = input.shape + ndim = len(shape) + torch._check( + ndim in (3, 4) and all(d != 0 for d in shape[-3:]), + lambda: "Expected 3D or 4D (batch mode) tensor for input with possible 0 batch size " + f"and non-zero dimensions, but got: {tuple(shape)}", + ) + output_size = tuple( + 1 + (out + 2 * pad - dil * (ker - 1) - 1) // st + for out, pad, dil, ker, st in zip( + shape[-2:], padding, dilation, kernel_size, stride + ) + ) + torch._check( + all(c > 0 for c in output_size), + lambda: f"Given an input with spatial size {tuple(shape[-2:])}, " + f"kernel_size={kernel_size}, dilation={dilation}, " + f"padding={padding}, stride={stride}, " + "the calculated shape of the array of sliding blocks " + f"is {output_size}, but its components must be at least one.", + ) + batched_input = ndim == 4 + if not batched_input: + input = input.unsqueeze(0) + + batch_dim, channel_dim, input_h, input_w = input.shape + + stride_h, stride_w = stride + padding_h, padding_w = padding + dilation_h, dilation_w = dilation + kernel_h, kernel_w = kernel_size + + blocks_row_indices = _im2col_col2im_indices_along_dim( + input_h, kernel_h, dilation_h, padding_h, stride_h, input.device + ) + blocks_col_indices = _im2col_col2im_indices_along_dim( + input_w, kernel_w, dilation_w, padding_w, stride_w, input.device + ) + + # Note that F.pad takes (padding_left, padding_right, padding_top, padding_bottom) + # ugh + padded_input = F.pad(input, (padding_w, padding_w, padding_h, padding_h)) + + blocks_row_indices = blocks_row_indices.unsqueeze(-1).unsqueeze(-1) + output = padded_input[:, :, blocks_row_indices, blocks_col_indices] + output = output.permute(0, 1, 2, 4, 3, 5) + num_blocks_row = blocks_row_indices.size(1) + num_blocks_col = blocks_col_indices.size(1) + output = output.reshape( + batch_dim, channel_dim * kernel_h * kernel_w, num_blocks_row * num_blocks_col + ) + + if not batched_input: + output = output.squeeze(0) + return output + + +@register_decomposition(aten.col2im) +@out_wrapper() +@pw_cast_for_opmath +def col2im( + input: Tensor, + output_size: list[int], + kernel_size: list[int], + dilation: list[int], + padding: list[int], + stride: list[int], +) -> Tensor: + torch._check(len(output_size) == 2, lambda: "only 2D output_size supported") + torch._check(len(kernel_size) == 2, lambda: "only 2D kernel supported") + torch._check(len(dilation) == 2, lambda: "only 2D dilation supported") + torch._check(len(padding) == 2, lambda: "only 2D padding supported") + torch._check(len(stride) == 2, lambda: "only 2D stride supported") + + def check_positive(param, param_name, strict=True): + cond = all(p > 0 for p in param) if strict else all(p >= 0 for p in param) + torch._check( + cond, lambda: f"{param_name} should be greater than zero, but got {param}" + ) + + check_positive(kernel_size, "kernel_size") + check_positive(dilation, "dilation") + check_positive(padding, "padding", strict=False) + check_positive(stride, "stride") + check_positive(output_size, "output_size") + + shape = input.shape + ndim = len(shape) + torch._check( + ndim in (2, 3) and all(d != 0 for d in shape[-2:]), + lambda: "Expected 2D or 3D (batch mode) tensor for input with possible 0 batch size " + f"and non-zero dimensions, but got: {tuple(shape)}", + ) + prod_kernel_size = kernel_size[0] * kernel_size[1] + torch._check( + shape[-2] % prod_kernel_size == 0, + lambda: "Expected size of input's first non-batch dimension to be divisible by the " + f"product of kernel_size, but got input.shape[-2] = {shape[-2]} and " + f"kernel_size={kernel_size}", + ) + col = [ + 1 + (out + 2 * pad - dil * (ker - 1) - 1) // st + for out, pad, dil, ker, st in zip( + output_size, padding, dilation, kernel_size, stride + ) + ] + L = col[0] * col[1] + torch._check( + shape[-1] == L, + lambda: f"Given output_size={output_size}, kernel_size={kernel_size}, " + f"dilation={dilation}, padding={padding}, stride={stride}, " + f"expected input.size(-1) to be {L} but got {shape[-1]}.", + ) + torch._check( + L > 0, + lambda: f"Given output_size={output_size}, kernel_size={kernel_size}, " + f"dilation={dilation}, padding={padding}, stride={stride}, " + f"expected input.size(-1) to be {L} but got {shape[-1]}.", + ) + batched_input = ndim == 3 + if not batched_input: + input = input.unsqueeze(0) + + shape = input.shape + + out_h, out_w = output_size + stride_h, stride_w = stride + padding_h, padding_w = padding + dilation_h, dilation_w = dilation + kernel_h, kernel_w = kernel_size + + # col2im is defined as the backwards of im2col, so we differentiate its decomposition by hand + input = input.reshape([shape[0], shape[1] // prod_kernel_size] + kernel_size + col) + input = input.permute(0, 1, 2, 4, 3, 5) + + indices_row = _im2col_col2im_indices_along_dim( + out_h, kernel_h, dilation_h, padding_h, stride_h, input.device + ) + indices_row = _unsqueeze_to_dim(indices_row, 4) + indices_col = _im2col_col2im_indices_along_dim( + out_w, kernel_w, dilation_w, padding_w, stride_w, input.device + ) + + output_padded_size = [o + 2 * p for o, p in zip(output_size, padding)] + output = input.new_zeros( + [shape[0], shape[1] // prod(kernel_size)] + output_padded_size + ) + idx = (None, None, indices_row, indices_col) + output = aten._unsafe_index_put(output, idx, input, accumulate=True) + output = F.pad(output, (-padding_w, -padding_w, -padding_h, -padding_h)) + + if not batched_input: + output = output.squeeze(0) + return output + + +@register_decomposition(aten.native_dropout_backward) +@out_wrapper() +def native_dropout_backward(grad_output: Tensor, mask: Tensor, scale: float): + # According to the CUDA kernel implementation we should have this test; + # but it seems to fail tests! + # torch._check(mask.dtype == torch.bool, lambda: f"Mask should be Bool Scalar Type {mask.dtype}") + + # Mimicking CUDA kernel's behavior for output stride: output follow input's memory format + # This different from TensorIterator's behavior + r = (grad_output * (mask.type_as(grad_output) * scale)).clone( + memory_format=utils.suggest_memory_format(grad_output) + ) + return r + + +@register_decomposition(aten.unfold_backward) +@out_wrapper() +def unfold_backward( + grad: Tensor, input_size: list[int], dimension: int, size: int, step: int +) -> Tensor: + torch._check_value(step > 0, lambda: f"step is {step} but must be > 0") + if len(input_size) == 0: + return torch.squeeze_copy(grad, 0) + dim = utils.canonicalize_dim(len(input_size), dimension) + grad_input = grad.new_zeros(input_size) + + def _vectorized_index_put() -> Tensor: + idx = torch.arange(input_size[dim], device=grad.device, dtype=torch.int32) + idx = idx.unfold(0, size, step).flatten() + source = grad.movedim(-1, dim + 1).flatten(dim, dim + 1) + index = (None,) * dim + (idx,) + return aten._unsafe_index_put( + grad_input, index, source, accumulate=True + ).contiguous() + + if step >= size: + return _vectorized_index_put() + + from torch.fx.experimental.symbolic_shapes import statically_known_true + + def _is_canonical_grad_shape() -> bool: + if grad.dim() != len(input_size) + 1: + return False + if not statically_known_true(grad.size(-1) == size): + return False + + n_folds = (input_size[dim] - size) // step + 1 + if not statically_known_true(grad.size(dim) == n_folds): + return False + + return all( + source_dim == dim + or statically_known_true(grad.size(source_dim) == dim_size) + for source_dim, dim_size in enumerate(input_size) + ) + + if _is_canonical_grad_shape(): + return _vectorized_index_put() + + def _sym_min_if_needed(a, b): + if statically_known_true(a <= b): + return a + if statically_known_true(b <= a): + return b + return torch.sym_min(a, b) + + def _sym_max_if_needed(a, b): + if statically_known_true(a >= b): + return a + if statically_known_true(b >= a): + return b + return torch.sym_max(a, b) + + def _reshape_source(source: Tensor, target_shape: list[int]) -> Tensor: + ndim = len(target_shape) + source_ndim = source.dim() + if source_ndim > ndim: + return source.expand(target_shape) + + dim_offset = ndim - source_ndim + view_shape = [1] * ndim + for source_dim in range(source_ndim): + target_dim = dim if source_dim == dim else source_dim + dim_offset + if target_dim < 0 or target_dim >= ndim: + return source.expand(target_shape) + if statically_known_true(view_shape[target_dim] == 1): + view_shape[target_dim] = source.shape[source_dim] + else: + # Multiple grad dimensions may align to the unfolded input + # dimension after select(); only singleton collisions can + # still be reshaped and broadcast to the target shape. + torch._check( + source.shape[source_dim] == 1, + lambda: "unfold_backward grad shape is not broadcastable " + "to input_size", + ) + + return source.reshape(view_shape).expand(target_shape) + + input_dim_size = input_size[dim] + grad_dim_size = grad.size(dim) + # Descending offsets make each grad_input element accumulate overlapping + # windows in increasing fold-index order, matching native numerics. + for offset in reversed(range(size)): + max_valid_len = _sym_max_if_needed( + (input_dim_size - offset + step - 1) // step, 0 + ) + valid_len = _sym_min_if_needed(grad_dim_size, max_valid_len) + idx = torch.arange(valid_len, device=grad.device, dtype=torch.int32) + idx = idx * step + offset + source = grad.select(-1, offset).narrow(dim, 0, valid_len) + source_shape = list(input_size) + source_shape[dim] = valid_len + source = _reshape_source(source, source_shape) + grad_input = aten.index_add(grad_input, dim, idx, source) + + return grad_input.contiguous() + + +@register_decomposition(aten.logit_backward.default) +@pw_cast_for_opmath +def logit_backward( + grad_output: Tensor, self: Tensor, eps: float | None = None +) -> Tensor: + if eps is not None: + lo = eps + hi = 1.0 - lo + return torch.where( + torch.logical_and(self >= lo, self <= hi), + grad_output / (self * (1.0 - self)), + 0.0, + ) + else: + return torch.where( + torch.logical_and(self >= 0.0, self <= 1.0), + grad_output / (self * (1.0 - self)), + self.new_full((), float("nan")), + ) + + +@register_decomposition(aten.dropout) +@aten.dropout.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.dropout.default.py_impl(DispatchKey.Autograd) +def dropout(input: Tensor, p: float, train: bool | None): + if train and p != 0: + return aten.native_dropout(input, p, train)[0] + else: + return input + + +@register_decomposition(aten.native_dropout) +@out_wrapper("out0", "out1") +def native_dropout(input: Tensor, p: float, train: bool | None): + if train and p != 0: + if p == 1: + return (torch.zeros_like(input), torch.zeros_like(input, dtype=torch.bool)) + if not input.dtype.is_floating_point: + raise RuntimeError( + "result type Float can't be cast to the desired output type Long" + ) + bool_mask = torch.rand_like(input) > p + res = bool_mask * input * float(1.0 / (1.0 - p)) + return (res, bool_mask) + else: + return (input, torch.ones_like(input, dtype=torch.bool)) + + +@register_decomposition(aten._softmax) +@out_wrapper() +def _softmax(x: Tensor, dim: int, half_to_float: bool): + # eager softmax returns a contiguous tensor. Ensure that decomp also returns + # a contiguous tensor. + x = x.contiguous() + if half_to_float: + if x.dtype != torch.half: + raise AssertionError( + f"half_to_float is True but x.dtype is {x.dtype}, expected torch.half" + ) + computation_dtype, result_dtype = utils.elementwise_dtypes( + x, type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + x = x.to(computation_dtype) + x_max = _softmax_unbacked_safe_amax(x, dim) + unnormalized = torch.exp(x - x_max) + result = unnormalized / torch.sum(unnormalized, dim, keepdim=True) + if not half_to_float: + result = result.to(result_dtype) + return result + + +def _softmax_unbacked_safe_amax(x: Tensor, dim: int) -> Tensor: + from torch.fx.experimental.symbolic_shapes import guard_or_false + + if x.ndim == 0: + return torch.amax(x, dim, keepdim=True) + + canonical_dim = utils.canonicalize_dim(x.ndim, dim) + if guard_or_false(x.shape[canonical_dim] > 0): + return torch.amax(x, dim, keepdim=True) + + # Plain amax has no identity, so it cannot reduce over an empty dim. + # With unbacked sizes this becomes a deferred runtime assert, but eager + # softmax handles empty inputs. Pad a single -inf, the identity for max: + # it never wins for non-empty input and makes empty input well-defined. + pad_shape = list(x.shape) + pad_shape[canonical_dim] = 1 + x = torch.cat((x, x.new_full(pad_shape, float("-inf"))), dim=dim) + return torch.amax(x, dim, keepdim=True) + + +@register_decomposition(aten._log_softmax) +@out_wrapper(exact_dtype=True) +def _log_softmax(x: Tensor, dim: int, half_to_float: bool): + # eager log_softmax returns a contiguous tensor. Ensure that decomp also + # returns a contiguous tensor. + x = x.contiguous() + if half_to_float: + if x.dtype != torch.half: + raise AssertionError( + f"half_to_float is True but x.dtype is {x.dtype}, expected torch.half" + ) + computation_dtype, result_dtype = utils.elementwise_dtypes( + x, type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + x = x.to(computation_dtype) + x_max = _softmax_unbacked_safe_amax(x, dim) + shifted = x - x_max + shifted_logsumexp = torch.log(torch.sum(torch.exp(shifted), dim, keepdim=True)) + result = shifted - shifted_logsumexp + if not half_to_float: + result = result.to(result_dtype) + return result + + +@register_decomposition(aten.embedding) +@out_wrapper() +def embedding( + weight: Tensor, + indices: Tensor, + padding_idx: int = -1, + scale_grad_by_freq: bool = False, + sparse: bool = False, +) -> Tensor: + if weight.dim() != 2: + raise AssertionError(f"'weight' must be 2-D, got {weight.dim()}-D") + # Nb. scale_grad_by_freq is not used in the forward + if indices.ndim <= 1: + # We need this one as weight[indices] calls item() in these cases + out = weight.index_select(0, indices) + if indices.ndim == 0: + out = out.squeeze(0) + return out + else: + return weight[indices] + + +@register_decomposition(aten.embedding_dense_backward) +@out_wrapper() +def embedding_dense_backward( + grad_output: Tensor, + indices: Tensor, + num_weights: int, + padding_idx: int, + scale_grad_by_freq: bool, +): + computation_dtype, result_dtype = utils.elementwise_dtypes( + grad_output, type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + grad_output = grad_output.to(computation_dtype) + indices = _maybe_convert_to_dtype(indices, torch.long) # type: ignore[assignment] + valid_indices = (indices >= 0) & (indices < num_weights) + if scale_grad_by_freq: + counts = indices.new_zeros((num_weights,)) + ones = torch.ones_like(indices) + counts = aten._unsafe_masked_index_put_accumulate( + counts, valid_indices, [indices], ones + ) + grad_weights_scale = aten._unsafe_masked_index( + counts, valid_indices, [indices], 1 + ) + grad_output = grad_output / grad_weights_scale.unsqueeze(-1) + + mask = _unsqueeze_to_dim(valid_indices & (indices != padding_idx), grad_output.ndim) + grad_weight = grad_output.new_zeros( + (num_weights,) + grad_output.shape[indices.ndim :] + ) + return aten._unsafe_masked_index_put_accumulate( + grad_weight, mask, [indices], grad_output + ).to(result_dtype) + + +def prod(x: list[int]): + r = 1 + for i in x: + r *= i + return r + + +def _pad_chunk( + tensors: list[Tensor], + dim: int, + num_chunks: int, +) -> list[Tensor]: + padded_tensors = [] + for tensor in tensors: + tensor_size = tensor.size() + pad_along_dim = (tensor_size[dim] + num_chunks - 1) // num_chunks * num_chunks + if pad_along_dim != tensor_size[dim]: + # Use aten.constant_pad_nd instead of copy_ for functionalization + pad = [0] * 2 * (tensor.ndim - dim - 1) + [ + 0, + pad_along_dim - tensor_size[dim], + ] + tensor = aten.constant_pad_nd(tensor, pad, 0) + view_size = tensor_size[:dim] + torch.Size([num_chunks, -1]) + padded_tensors.append(tensor.reshape(view_size)) + return padded_tensors + + +def have_same_ndims(tensors: list[Tensor]): + ndim = tensors[0].ndim + for tensor in tensors: + if tensor.ndim != ndim: + return False + return True + + +def leading_dimension_matches(tensors: list[Tensor], dim: int): + leading_dim_sizes = tensors[0].size()[:dim] + for tensor in tensors: + torch._check( + tensor.size()[:dim] == leading_dim_sizes, + lambda: "_chunk_cat expects same sizes of 0,...,dim-1 dimensions for all tensors", + ) + + +def _preprocess_chunk_cat_inputs( + tensors: list[Tensor], + dim: int, + num_chunks: int, +): + torch._check(num_chunks >= 1, lambda: "_chunk_cat expects positive num_chunks") + torch._check( + len(tensors) > 0, lambda: "_chunk_cat expects a non-empty input tensor list" + ) + expected_dtype = tensors[0].dtype + expected_device = tensors[0].device + for tensor in tensors: + torch._check(tensor.numel() > 0, lambda: "_chunk_cat expects non-empty tensor") + torch._check( + tensor.dtype == expected_dtype, + lambda: "_chunk_cat expects all input tensors with the same dtype", + ) + torch._check( + tensor.device == expected_device, + lambda: "_chunk_cat expects all inputs tensors on the same device", + ) + if have_same_ndims(tensors): + dim = utils.canonicalize_dim(tensors[0].dim(), dim) + else: + torch._check( + dim >= 0, + lambda: "_chunk_cat expects non-negative dim when input tensors have different ndims", + ) + for tensor in tensors: + torch._check( + dim < tensor.ndim, + lambda: "_chunk_cat expects dim < ndim for all input tensors", + ) + leading_dimension_matches(tensors, dim) + return dim + + +@register_decomposition([aten._chunk_cat.default, aten._chunk_cat.out]) +def _chunk_cat( + tensors: list[Tensor], + dim: int, + num_chunks: int, + out: Tensor | None = None, +) -> Tensor: + dim = _preprocess_chunk_cat_inputs(tensors, dim, num_chunks) + padded_tensors = _pad_chunk(tensors, dim, num_chunks) + if out is None: + return torch.cat(padded_tensors, dim + 1) + else: + torch.cat(padded_tensors, dim + 1, out=out) + return out + + +# out_wrapper currently does not allow optional outputs +@register_decomposition( + [aten.split_with_sizes_copy.default, aten.split_with_sizes_copy.out] +) +def split_with_sizes_copy( + self: Tensor, + split_sizes: list[int], + dim: int = 0, + out: list[Tensor] | None = None, +) -> list[Tensor] | None: + splits = aten.split_with_sizes(self, split_sizes, dim=dim) + if out is None: + return [s.clone(memory_format=torch.contiguous_format) for s in splits] + else: + for output, split in zip(out, splits): + _maybe_resize_out(output, split.shape) + _safe_copy_out(copy_from=split, copy_to=output, exact_dtype=True) + return None + + +@register_decomposition(aten.unsafe_split.Tensor) +def unsafe_split(input: Tensor, split_size: int, dim: int = 0) -> tuple[Tensor, ...]: + return aten.split.Tensor(input, split_size, dim) + + +@register_decomposition(aten.unsafe_split_with_sizes.default) +def unsafe_split_with_sizes( + input: Tensor, split_sizes: list[int], dim: int = 0 +) -> tuple[Tensor, ...]: + return aten.split_with_sizes.default(input, split_sizes, dim) + + +@register_decomposition(aten.split.Tensor) +def split(self: Tensor, split_size: int, dim: int = 0) -> tuple[Tensor, ...]: + input_sizes = self.shape + dim_size = input_sizes[dim] + torch._check( + split_size >= 0, + lambda: f"split expects split_size be non-negative, but got split_size={split_size}", + ) + if dim_size == 0: + return (self.detach(),) + torch._check( + split_size > 0, + lambda: "split_size can only be 0 if dimension size is 0, " + f"but got dimension size of {dim_size}", + ) + chunks = (dim_size + split_size - 1) // split_size + + # Avoid importing sympy at a module level + from torch.fx.experimental.symbolic_shapes import guard_int + + chunks = guard_int(chunks) + split_sizes = [split_size for i in range(chunks)] + split_sizes[-1] = split_size - (split_size * chunks - dim_size) + return torch.split(self, split_sizes, dim) + + +@aten.tensor_split.tensor_indices_or_sections.py_impl( + DispatchKey.CompositeImplicitAutograd +) +def tensor_split_tensor_indices_or_sections_py_impl( + self: Tensor, + tensor_indices_or_sections: Tensor, + dim: int = 0, +) -> tuple[Tensor, ...]: + if tensor_indices_or_sections.device.type != "cpu": + raise AssertionError( + f"tensor_indices_or_sections must be on CPU, got {tensor_indices_or_sections.device}" + ) + if tensor_indices_or_sections.dtype != torch.int64: + raise AssertionError( + f"tensor_indices_or_sections must be int64, got {tensor_indices_or_sections.dtype}" + ) + split_dim = tensor_indices_or_sections.dim() + torch._check( + split_dim == 1 or split_dim == 0, + lambda: "tensor_split expected tensor_indices_or_sections to be a zero-dimensional " + f"or one-dimensional tensor, but got a tensor with {split_dim} dims", + ) + if split_dim == 0: + sections = tensor_indices_or_sections.item() + if not isinstance(sections, IntLike): + raise AssertionError( + f"Expected sections to be IntLike, got {type(sections).__name__}" + ) + return self.tensor_split(sections, dim) + else: + ctx = nullcontext + if (fake_mode := torch._guards.detect_fake_mode()) and ( + shape_env := fake_mode.shape_env + ): + ctx = shape_env.ignore_fresh_unbacked_symbols # type: ignore[assignment] + # In fake tensor prop, we end up calling slice() with these unbacked indices. + # Because slice has flexible semantics, the unbacked handling generates new output sizes + # for each slice, effectively clobbering over these index symbols. + # To avoid PendingUnbackedSymbolNotFound errors, we tell the compiler it's fine to not bind these. + with ctx(): + indices = [i.item() for i in tensor_indices_or_sections] + # WARNING: Tempted to torch._check(x>0) on the indices here? You + # can't: tensor_split works with negative values in indices: + # + # >>> torch.tensor_split(torch.randn(10), torch.tensor([-5, 5])) + # (tensor([ 0.3540, 2.1074, -0.8507, 1.1639, 0.3055]), tensor([]), + # tensor([-0.4285, 1.0692, -0.1776, 0.9362, 1.6143])) + # + # Sorry, I don't make the rules. Explicitly do the item call in user + # code if you KNOW that they are non-negative. + return self.tensor_split(indices, dim) + + +# TODO: this doesn't appear to have enough precision in bfloat16 +@register_decomposition([aten.addmm.default, aten.addmm.out]) +@out_wrapper(exact_dtype=True) +@pw_cast_for_opmath +def addmm(self: Tensor, mat1: Tensor, mat2: Tensor, beta: int = 1, alpha: int = 1): + if not self.is_floating_point() and not self.is_complex(): + beta = int(beta) + alpha = int(alpha) + out = alpha * torch.mm(mat1, mat2) + if beta == 0: + return out + + # The output of aten.addmm is contiguous, we need to match this behavior in the decomposition. + # The original implementation 'beta * self + out' would return a strided tensor if `self` is strided. + # We thus use `out`, the output of torch.mm, which is always contiguous, as the first argument for addition. + # This is relying on TensorIterator's behavior that it takes higher precedence on the stride of first input. + # Alternative, we can write `(beta * self + out).contiguous()`, but it introduces another copy in some cases. + # This implementation is not ideal, and we should revisit this when we have a better solution. + return out + beta * self + + +@register_decomposition([aten.addmm.dtype, aten.addmm.dtype_out]) +@out_wrapper(exact_dtype=True) +def addmm_dtype( + self: Tensor, + mat1: Tensor, + mat2: Tensor, + out_dtype: torch.dtype, + beta: int = 1, + alpha: int = 1, +): + out = alpha * torch.mm(mat1, mat2, out_dtype=out_dtype) + if beta == 0: + return out + return out + beta * self.to(out_dtype) + + +@register_decomposition(aten._addmm_activation) +@out_wrapper() +@pw_cast_for_opmath +def _addmm_activation( + self: Tensor, + mat1: Tensor, + mat2: Tensor, + beta: int = 1, + alpha: int = 1, + use_gelu: bool = False, +): + out = addmm(self, mat1, mat2, beta, alpha) + if use_gelu: + if self.is_cuda: + return aten.gelu(out, approximate="tanh") + else: + return aten.gelu(out) + return aten.relu(out) + + +@pw_cast_for_opmath +def _addmv_impl(self: Tensor, mat1: Tensor, vec: Tensor, beta: int = 1, alpha: int = 1): + if not self.is_floating_point() and not self.is_complex(): + beta = int(beta) + alpha = int(alpha) + out = alpha * torch.mv(mat1, vec) + if beta == 0: + return out + if out.numel() == 0: # handle empty matrix + return beta * self + return out + beta * self + + +@register_decomposition(aten.addmv) +@out_wrapper(exact_dtype=True) +def addmv(self: Tensor, mat1: Tensor, vec: Tensor, beta: int = 1, alpha: int = 1): + torch._check( + self.dtype == mat1.dtype and mat1.dtype == vec.dtype, + lambda: f"addmv input tensors must have the same dtype, but got {self.dtype}, {mat1.dtype}, and {vec.dtype}", + ) + return _addmv_impl(self, mat1, vec, beta, alpha) + + +@register_decomposition(aten.native_group_norm_backward.default) +@pw_cast_for_opmath +def native_group_norm_backward( + grad_output: Tensor, + input: Tensor, + mean: Tensor, + rstd: Tensor, + gamma: Tensor | None, + N: int, + C: int, + HxW: int, + group: int, + output_mask: list[bool], +) -> tuple[Tensor | None, Tensor | None, Tensor | None]: + utils.check_same_device( + grad_output, input, mean, rstd, allow_cpu_scalar_tensors=False + ) + utils.check_same_shape(input, grad_output, allow_cpu_scalar_tensors=False) + utils.check_same_shape(mean, rstd, allow_cpu_scalar_tensors=False) + torch._check( + input.numel() == N * C * HxW, + lambda: f"Expect input to have {N * C * HxW} elements", + ) + torch._check( + mean.shape == (N, group), + lambda: f"Expect mean to have shape ({N}, {group}, but got {mean.shape}", + ) + torch._check( + gamma is None or gamma.numel() == C, + lambda: f"Expect gamma to have {C} elements but got {gamma.numel() if gamma is not None else -1}", + ) + + cpg = C // group + torch._check( + C == cpg * group, + lambda: f"Expect number of channels {C} to be evenly-divisible by number of groups {group}", + ) + + # Compute Internal gradients + ds = torch.mul(grad_output, input).reshape(N, C, HxW).sum(dim=[2]) + db = grad_output.reshape(N, C, HxW).sum(dim=[2]) + + d_input: Tensor | None = None + d_gamma: Tensor | None = None + d_bias: Tensor | None = None + if output_mask[0]: + s = 1.0 / (HxW * cpg) + if gamma is not None: + ds_val = torch.mul(ds, gamma.unsqueeze(0)).reshape(N, group, cpg).sum(2) + db_val = torch.mul(db, gamma.unsqueeze(0)).reshape(N, group, cpg).sum(2) + c1 = torch.mul( + rstd.unsqueeze(-1), + gamma.reshape(1, group, cpg), + ) + else: + ds_val = ds.reshape(N, group, cpg).sum(2) + db_val = db.reshape(N, group, cpg).sum(2) + c1 = torch.mul( + rstd.unsqueeze(-1), + torch.ones((1, group, cpg), device=rstd.device), + ) + c2 = torch.addcmul(-ds_val, db_val, mean) * rstd * rstd * rstd * s + c3 = -c2 * mean - db_val * rstd * s + + c1 = c1.unsqueeze(-1) + c2 = _unsqueeze_to_dim(c2, 4) + c3 = _unsqueeze_to_dim(c3, 4) + d_input = ( + torch.mul(grad_output.reshape(N, group, cpg, HxW), c1) + + torch.mul(input.reshape(N, group, cpg, HxW), c2) + + c3 + ) + d_input = d_input.reshape(input.shape).to(input.dtype) + if output_mask[1]: + d_gamma = ( + ( + (ds.view(N, group, cpg) - db.view(N, group, cpg) * mean.unsqueeze(-1)) + * rstd.unsqueeze(-1) + ) + .sum(dim=[0]) + .reshape(C) + ) + if output_mask[2]: + d_bias = db.sum(dim=[0]) + + return (d_input, d_gamma, d_bias) + + +# out_wrapper currently does not allow optional outputs +@register_decomposition(aten.native_group_norm_backward.out) +def native_group_norm_backward_out( + grad_output: Tensor, + input: Tensor, + mean: Tensor, + rstd: Tensor, + gamma: Tensor | None, + N: int, + C: int, + HxW: int, + group: int, + output_mask: list[bool], + *, + out0: torch.Tensor, + out1: torch.Tensor, + out2: torch.Tensor, +) -> tuple[Tensor | None, Tensor | None, Tensor | None]: + result = native_group_norm_backward( + grad_output, input, mean, rstd, gamma, N, C, HxW, group, output_mask + ) + grad_input = (out0, out1, out2) + for i, r in enumerate(result): + if r is not None: + _maybe_resize_out(grad_input[i], r.shape) + _safe_copy_out(copy_from=r, copy_to=grad_input[i], exact_dtype=True) + + return grad_input + + +def _maybe_cast(x: Tensor | None, dtype) -> Tensor | None: + if x is not None: + return x.to(dtype) + return x + + +# TODO: Take a closer look at the type promotion semantics +@register_decomposition(aten.native_layer_norm_backward.default) +def native_layer_norm_backward( + grad_out: Tensor, + input: Tensor, + normalized_shape: list[int], + mean: Tensor, + rstd: Tensor, + weight: Tensor | None, + bias: Tensor | None, + output_mask: list[bool], +) -> tuple[Tensor | None, Tensor | None, Tensor | None]: + input_shape = input.shape + input_ndim = input.dim() + computation_dtype = utils.get_computation_dtype(input.dtype) + grad_out_cast, input_cast, weight_cast, bias_cast = ( + x.to(computation_dtype, memory_format=torch.contiguous_format) + if x is not None + else x + for x in (grad_out, input, weight, bias) + ) + if grad_out_cast is None: + raise AssertionError("grad_out_cast should not be None") + + axis = input_ndim - len(normalized_shape) + inner_dims = input_shape[axis:] + outer_dims = input_shape[:axis] + inner_dim_indices: list[int] = [] + outer_dim_indices: list[int] = [] + for i in range(input_ndim): + if i >= axis: + inner_dim_indices.append(i) + else: + outer_dim_indices.append(i) + + N = prod(inner_dims) # type: ignore[arg-type] + M = prod(outer_dims) # type: ignore[arg-type] + from torch.fx.experimental.symbolic_shapes import statically_known_true + + if statically_known_true(M == 0) or statically_known_true(N == 0): + return ( + input.new_zeros(input_shape) if output_mask[0] else None, + input.new_zeros(input_shape[axis:]) if output_mask[1] else None, + input.new_zeros(input_shape[axis:]) if output_mask[2] else None, + ) + mean = _unsqueeze_to_dim(mean, input_cast.dim()) # type: ignore[union-attr] + rstd = _unsqueeze_to_dim(rstd, input_cast.dim()) # type: ignore[union-attr] + if input_cast is None: + raise AssertionError("input_cast should not be None") + x_hat = (input_cast - mean) * rstd + if weight_cast is not None: + grad_x_hat = grad_out_cast * weight_cast + else: + grad_x_hat = grad_out_cast + a = grad_x_hat * N + b = torch.sum(grad_x_hat, inner_dim_indices, True) + c1 = torch.mul(grad_x_hat, x_hat) + c2 = torch.sum(c1, inner_dim_indices, True) + c3 = torch.mul(x_hat, c2) + + inner = a - b - c3 + d_input: Tensor | None = None + d_weight: Tensor | None = None + d_bias: Tensor | None = None + if output_mask[0]: + d_input = (rstd / N) * inner + + if output_mask[1] and weight_cast is not None: + if len(outer_dim_indices) > 0: + d_weight = torch.sum(grad_out_cast * x_hat, outer_dim_indices, False) + else: + d_weight = grad_out_cast * x_hat + + if output_mask[2] and bias_cast is not None: + if len(outer_dim_indices) > 0: + d_bias = torch.sum(grad_out_cast, outer_dim_indices, False) + else: + d_bias = grad_out_cast.clone() + + return ( + _maybe_cast(d_input, input.dtype), + _maybe_cast(d_weight, weight.dtype if weight is not None else None), + _maybe_cast(d_bias, bias.dtype if bias is not None else None), + ) + + +# out_wrapper currently does not allow optional outputs +@register_decomposition(aten.native_layer_norm_backward.out) +def native_layer_norm_backward_out( + grad_out: Tensor, + input: Tensor, + normalized_shape: list[int], + mean: Tensor, + rstd: Tensor, + weight: Tensor | None, + bias: Tensor | None, + output_mask: list[bool], + *, + out0: torch.Tensor, + out1: torch.Tensor, + out2: torch.Tensor, +) -> tuple[Tensor | None, Tensor | None, Tensor | None]: + result = native_layer_norm_backward( + grad_out, input, normalized_shape, mean, rstd, weight, bias, output_mask + ) + grad_input = (out0, out1, out2) + for i, r in enumerate(result): + if r is not None: + _maybe_resize_out(grad_input[i], r.shape) + _safe_copy_out(copy_from=r, copy_to=grad_input[i], exact_dtype=True) + + return grad_input + + +@register_decomposition(aten._fused_rms_norm.default) +def _fused_rms_norm( + input: Tensor, + normalized_shape: list[int], + weight: Tensor | None, + eps: float | None, +) -> tuple[Tensor, Tensor]: + dims_to_reduce: list[int] = [] + for i in range(len(normalized_shape)): + dims_to_reduce.append(input.dim() - i - 1) + + # upcast is needed for fp16 and bf16 + computation_dtype = utils.get_computation_dtype(input.dtype) + upcasted_input = input.to(computation_dtype) + + # computation_dtype would be one of [Double, Float, ComplexFloat, ComplexDouble] + if eps is None: + if computation_dtype in (torch.float32, torch.complex64): + eps_val = torch.finfo(torch.float32).eps + else: + eps_val = torch.finfo(torch.float64).eps + else: + eps_val = eps + + rqrst_input = torch.rsqrt( + # NB: don't inplace here, will violate functional IR invariant + # NB: carefully use the Scalar overload of add to ensure compatibility with the C++ decomp + torch.ops.aten.add.Scalar( + torch.pow(upcasted_input, 2).mean(dim=dims_to_reduce, keepdim=True), eps_val + ) + ) + + upcasted_result = upcasted_input.mul(rqrst_input) + + if weight is not None: + upcasted_result = upcasted_result.mul(weight) + + # NB: nested should be dead here, just here for fidelity + is_nested = input.is_nested or (weight is not None and weight.is_nested) + memory_format = utils.suggest_memory_format(input) + is_channels_last = memory_format in ( + torch.channels_last, + torch.channels_last_3d, + ) + + if not is_nested and not is_channels_last: + upcasted_result = upcasted_result.contiguous() + rqrst_input = rqrst_input.contiguous() + + # Cast normalized result back to original input type + result = upcasted_result.type_as(input) + + return result, rqrst_input + + +@register_decomposition(aten._fused_rms_norm_backward.default) +def _fused_rms_norm_backward( + grad_out: Tensor, + input: Tensor, + normalized_shape: list[int], + rstd: Tensor, + weight: Tensor | None, + output_mask: list[bool], +) -> tuple[Tensor | None, Tensor | None]: + input_shape = input.shape + input_ndim = input.dim() + computation_dtype = utils.get_computation_dtype(input.dtype) + + grad_out_cast = grad_out.to( + computation_dtype, memory_format=torch.contiguous_format + ) + input_cast = input.to(computation_dtype, memory_format=torch.contiguous_format) + weight_cast = ( + weight.to(computation_dtype, memory_format=torch.contiguous_format) + if weight is not None + else None + ) + if grad_out_cast is None: + raise AssertionError("grad_out_cast should not be None") + + axis = input_ndim - len(normalized_shape) + inner_dims = input_shape[axis:] + outer_dims = input_shape[:axis] + inner_dim_indices: list[int] = [] + outer_dim_indices: list[int] = [] + for i in range(input_ndim): + if i >= axis: + inner_dim_indices.append(i) + else: + outer_dim_indices.append(i) + + N = prod(inner_dims) # type: ignore[arg-type] + M = prod(outer_dims) # type: ignore[arg-type] + from torch.fx.experimental.symbolic_shapes import guard_or_false + + if guard_or_false(M == 0) or guard_or_false(N == 0): + return ( + input.new_zeros(input_shape) if output_mask[0] else None, + input.new_zeros(input_shape[axis:]) if output_mask[1] else None, + ) + + rstd = _unsqueeze_to_dim(rstd, input_cast.dim()) # type: ignore[union-attr] + if weight_cast is not None: + grad_x_hat = grad_out_cast * weight_cast + else: + grad_x_hat = grad_out_cast + + d_input: Tensor | None = None + d_weight: Tensor | None = None + + x_hat = input_cast * rstd + + if output_mask[0]: + sum_val = torch.sum(x_hat * grad_x_hat, dim=inner_dim_indices, keepdim=True) + d_input = (grad_x_hat - (x_hat / N) * sum_val) * rstd + + if output_mask[1] and weight_cast is not None: + d_weight_full_shape = grad_out_cast * x_hat + if len(outer_dim_indices) > 0: + d_weight = torch.sum( + d_weight_full_shape, dim=outer_dim_indices, keepdim=False + ) + else: + d_weight = d_weight_full_shape + + return ( + _maybe_cast(d_input, input.dtype), + _maybe_cast(d_weight, input.dtype), + ) + + +def native_batch_norm_helper( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: bool, + momentum: float, + eps: float, + functional: bool, +) -> tuple[Tensor, Tensor, Tensor, Tensor | None, Tensor | None]: + reduction_dims = [0] + list(range(2, input.dim())) + computation_dtype = utils.get_computation_dtype(input.dtype) + new_running_mean = running_mean + new_running_var = running_var + if training: + computation_dtype = utils.get_computation_dtype(input.dtype) + input_acc = input.to(dtype=computation_dtype) + biased_var, mean = torch.var_mean( + input_acc, dim=reduction_dims, correction=0, keepdim=True + ) + rstd = torch.rsqrt(biased_var + eps) + + output = (input - mean) * rstd + + save_mean = torch.squeeze(mean, reduction_dims) + save_rstd = torch.squeeze(rstd, reduction_dims) + if running_mean is not None: + new_running_mean = momentum * save_mean + (1 - momentum) * running_mean + if not functional: + running_mean.copy_(new_running_mean) + if running_var is not None: + n = input.numel() / input.shape[1] + # This doesn't strictly match eager's numerics, which accumulates var sum and then directly applies the correction + # But... that would require re-implementing var here, for negligible numerics gain on a tensor whose + # numerics probably don't matter. + squeezed_var = torch.squeeze(biased_var, reduction_dims) + unbiased_var = squeezed_var * (n / (n - 1)) + new_running_var = momentum * unbiased_var + (1 - momentum) * running_var + if not functional: + running_var.copy_(new_running_var) + else: + if running_mean is None or running_var is None: + raise AssertionError( + "running_mean and running_var must not be None in eval mode" + ) + running_mean = running_mean.to(dtype=computation_dtype, copy=True) + new_running_mean = running_mean + running_var = running_var.to(dtype=computation_dtype, copy=True) + new_running_var = running_var + mean = running_mean + invstd = torch.rsqrt(running_var + eps) + # Very annoying inconsistency where CPU and CUDA give different shapes + if input.device.type != "cpu": + save_mean = running_mean + save_rstd = invstd + else: + save_mean = input.new_zeros((0,)) + save_rstd = input.new_zeros((0,)) + mean = _unsqueeze_to_dim(mean, input.dim() - 1) + invstd = _unsqueeze_to_dim(invstd, input.dim() - 1) + output = (input - mean) * invstd + + if weight is not None: + weight = weight.flatten() + weight = _unsqueeze_to_dim(weight, input.dim() - 1) + output = output * weight + + if bias is not None: + bias = bias.flatten() + bias = _unsqueeze_to_dim(bias, input.dim() - 1) + output = output + bias + + if input.device.type == "cpu": + save_mean = save_mean.to(dtype=input.dtype) + save_rstd = save_rstd.to(dtype=input.dtype) + return ( + output.to(dtype=input.dtype), + save_mean, + save_rstd, + new_running_mean, + new_running_var, + ) + + +@register_decomposition(aten.native_batch_norm) +@out_wrapper("out", "save_mean", "save_invstd") +def native_batch_norm( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: bool, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor]: + output, save_mean, save_rstd, _, _ = native_batch_norm_helper( + input, weight, bias, running_mean, running_var, training, momentum, eps, False + ) + return output, save_mean, save_rstd + + +# TODO: this decomposition is NOT here to stay. We would much prefer replacing native_batch_norm +# with our new correctly schema'd _native_batch_norm_legit and its variants, but +# we cannot do that immediately in the C++ because it would be forwards incompatible +# with some mobile use cases. +# +# Since this change is most impactful for aot autograd/functionalization, we simply +# register this decomposition on the Autograd key for the python dispatcher (which is +# currently only used by aot autograd/functionalization and no one else, really). +# In two weeks or so, we should remove this decomposition and phase out the current native_batch_norm +# to be _native_batch_norm_legit and have the right schema (stating that there are input mutations). +@aten.native_batch_norm.default.py_impl(DispatchKey.Autograd) +@aten.native_batch_norm.default.py_impl(DispatchKey.CompositeImplicitAutograd) +def native_batch_norm_decomposition( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: bool, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor]: + if running_mean is None and running_var is None: + return aten._native_batch_norm_legit( + input, weight, bias, training, momentum, eps + ) + if running_mean is None: + raise RuntimeError( + "running_mean is None, but running_var is provided. " + "They should both be None or both be provided." + ) + if running_var is None: + raise RuntimeError( + "running_var is None, but running_mean is provided. " + "They should both be None or both be provided." + ) + if training: + # HACK: batch norm consolidation should clean this up so this op doesn't take in a training arg. + return aten._native_batch_norm_legit( + input, weight, bias, running_mean, running_var, training, momentum, eps + ) + else: + return aten._native_batch_norm_legit_no_training( + input, weight, bias, running_mean, running_var, momentum, eps + ) + + +@aten.unsafe_chunk.default.py_impl(DispatchKey.CompositeImplicitAutograd) +def unsafe_chunk_py_impl(tensor, chunks, dim=0) -> list[Tensor]: + dim_size = tensor.size(dim) + split_size = (dim_size + chunks - 1) // chunks + + if split_size == 0 and dim_size == 0: + split_sizes = [split_size for _ in range(chunks)] + split_sizes[chunks - 1] = split_size - (split_size * chunks - dim_size) + return torch.ops.aten.unsafe_split_with_sizes.default(tensor, split_sizes, dim) + return torch.ops.aten.unsafe_split.Tensor(tensor, split_size, dim) + + +@register_decomposition(aten._native_batch_norm_legit_no_training.default) +def _native_batch_norm_legit_no_training( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor, + running_var: Tensor, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor]: + return aten._native_batch_norm_legit.default( + input, + weight, + bias, + running_mean, + running_var, + False, # training + momentum, + eps, + ) + + +@register_decomposition(aten._native_batch_norm_legit.default) +def _native_batch_norm_legit( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor, + running_var: Tensor, + training: bool, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor]: + output, save_mean, save_rstd, _, _ = native_batch_norm_helper( + input, weight, bias, running_mean, running_var, training, momentum, eps, False + ) + return output, save_mean, save_rstd + + +@register_decomposition(aten._native_batch_norm_legit.no_stats) +def _native_batch_norm_legit_no_stats( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + training: bool, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor]: + output, save_mean, save_rstd, _, _ = native_batch_norm_helper( + input, weight, bias, None, None, training, momentum, eps, False + ) + return output, save_mean, save_rstd + + +@register_decomposition(aten._native_batch_norm_legit_functional.default) +def _native_batch_norm_legit_functional( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor, + running_var: Tensor, + training: bool, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: + ( + output, + save_mean, + save_rstd, + new_running_mean, + new_running_var, + ) = native_batch_norm_helper( + input, weight, bias, running_mean, running_var, training, momentum, eps, True + ) + if new_running_mean is None: + raise AssertionError("new_running_mean should not be None") + if new_running_var is None: + raise AssertionError("new_running_var should not be None") + return output, save_mean, save_rstd, new_running_mean, new_running_var + + +def _get_batch_norm_reserve_tensor( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor, + running_var: Tensor, + eps: float, + training: bool, +) -> Tensor: + """ + Return a reserve tensor for batch norm, used only by cudnn to pass forward state to the + backward pass. This is needed for `_batch_norm_with_update` and `_batch_norm_no_update`, + which support a variety of backends including cudnn. We create this tensor here to get + the correct shape in the traced graph if we detect that will call the cudnn kernel, + and rely on DCE to avoid materializing this tensor. + """ + backend = torch._C._select_batch_norm_backend( # type: ignore[attr-defined] + input, weight, bias, running_mean, running_var, True, eps + ) + reserve_size = 0 + if backend == torch._C._BatchNormBackend.Cudnn: # type: ignore[attr-defined] + reserve_size = torch._C._get_cudnn_batch_norm_reserve_space_size( # type: ignore[attr-defined] + input, training + ) + return torch.empty( + reserve_size, dtype=torch.uint8, layout=input.layout, device=input.device + ) + + +@register_decomposition(aten._batch_norm_with_update.default) +def _batch_norm_with_update( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor, + running_var: Tensor, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: + output, save_mean, save_rstd, _, _ = native_batch_norm_helper( + input, + weight, + bias, + running_mean, + running_var, + True, # training + momentum, + eps, + False, # functional + ) + reserve = _get_batch_norm_reserve_tensor( + input, weight, bias, running_mean, running_var, eps, training=True + ) + return output, save_mean, save_rstd, reserve + + +@register_decomposition(aten._batch_norm_with_update_functional.default) +def _batch_norm_with_update_functional( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor, + running_var: Tensor, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]: + ( + output, + save_mean, + save_rstd, + new_rm, + new_rv, + ) = native_batch_norm_helper( + input, weight, bias, running_mean, running_var, True, momentum, eps, True + ) + reserve = _get_batch_norm_reserve_tensor( + input, weight, bias, running_mean, running_var, eps, training=True + ) + if new_rm is None: + raise AssertionError("new_running_mean should not be None") + if new_rv is None: + raise AssertionError("new_running_var should not be None") + return (output, save_mean, save_rstd, reserve, new_rm, new_rv) + + +@register_decomposition(aten._batch_norm_no_update.default) +def _batch_norm_no_update( + input: Tensor, + weight: Tensor | None, + bias: Tensor | None, + running_mean: Tensor, + running_var: Tensor, + momentum: float, + eps: float, +) -> tuple[Tensor, Tensor, Tensor, Tensor]: + output, save_mean, save_rstd, _, _ = native_batch_norm_helper( + input, + weight, + bias, + running_mean, + running_var, + False, # training + momentum, + eps, + False, # functional + ) + reserve = _get_batch_norm_reserve_tensor( + input, weight, bias, running_mean, running_var, eps, training=False + ) + return output, save_mean, save_rstd, reserve + + +@register_decomposition(aten._fused_dropout) +@out_wrapper("out0", "out1") +def _fused_dropout_decomposition(input, p, generator=None): + if generator is not None: + raise AssertionError( + f"generator must be None for _fused_dropout decomposition, got {generator}" + ) + computation_dtype, result_dtype = utils.elementwise_dtypes( + input, type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + input_acc = input.to(computation_dtype) + mask = (torch.rand_like(input_acc) < p).to(dtype=torch.uint8) + scale = torch.scalar_tensor(1.0, dtype=computation_dtype, device=input.device) / p + res = mask.to(computation_dtype) * input_acc * scale + return (res.to(result_dtype), mask) + + +@register_decomposition(aten._to_copy) +@out_wrapper() +def _to_copy( + x: Tensor | NumberType, + *, + dtype: torch.dtype | None = None, + layout=None, + device: torch.device | None = None, + pin_memory: bool = False, + non_blocking: bool = False, + memory_format: torch.memory_format | None = None, +): + if layout and layout != torch.strided: + raise AssertionError(f"layout must be None or torch.strided, got {layout}") + if pin_memory: + raise AssertionError( + "pin_memory=True is not supported in _to_copy decomposition" + ) + if not isinstance(x, (torch.Tensor, int, float, bool, complex)): + raise AssertionError(f"x must be Tensor or scalar, got {type(x).__name__}") + if device is None and dtype is None and memory_format is None: + if isinstance(x, torch.Tensor): + return x.clone() + else: + return x + dtype_converted = False + + if isinstance(x, torch.Tensor): + x_tensor = x + else: + x_tensor = torch.scalar_tensor(x) + + if device is not None and device != x_tensor.device: + # When both dtype and device change, decide where to do the dtype + # conversion. The general heuristic is to convert on the faster + # device (i.e. avoid conversions on cpu when the source is a gpu). + # However, we must convert on the *source* device when the target + # device does not support the source dtype – e.g. copying a float64 + # tensor to an XPU device that lacks fp64 hardware would otherwise + # create an unsupported intermediate buffer on the target device. + if dtype is not None: + convert_before_transfer = False + if device.type == "cpu": + # Source is accelerator, target is CPU – convert on the + # (faster) source device before the transfer. + convert_before_transfer = True + elif x_tensor.dtype == torch.float64: + # The target device may not support float64 (e.g. Intel Arc + # consumer GPUs). Convert to the requested dtype on the + # source device to avoid creating an unsupported fp64 + # intermediate buffer on the target device. + from torch._inductor.utils import device_supports_fp64 + + if not device_supports_fp64(device): + convert_before_transfer = True + + if convert_before_transfer: + x_tensor = torch._prims.convert_element_type(x_tensor, dtype) + dtype_converted = True + x_tensor = torch._prims.device_put(x_tensor, device, non_blocking) + + if dtype is not None and not dtype_converted: + x_tensor = torch._prims.convert_element_type(x_tensor, dtype) + dtype_converted = True + + if memory_format is not None: # no ref/prim for memory format + return torch.clone(x_tensor, memory_format=memory_format) + return x_tensor + + +# Questionable decompositions +# This is only valid if we're running the graph without autograd, such as if the backward pass has been traced. +# Note that this decomposition causes issues with in-place ops +@register_decomposition([aten.detach, aten.lift, aten.lift_fresh]) +@out_wrapper() +def nop_decomposition(x): + return aten.alias(x) + + +# Also register to the Autograd dispatch key, so this decomp can run above autograd. +# native_batch_norm needs to decompose into other ops before autograd. +@aten.cudnn_batch_norm.default.py_impl(DispatchKey.Autograd) +@register_decomposition(aten.cudnn_batch_norm) +@out_wrapper("out0", "out1", "out2", "out3") +def cudnn_batch_norm( + input: Tensor, + weight: Tensor, + bias: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + training: bool, + exponential_average_factor: float, + epsilon: float, +): + a, b, c = aten.native_batch_norm( + input, + weight, + bias, + running_mean, + running_var, + training, + exponential_average_factor, + epsilon, + ) + # Cudnn return running mean and variance when training is True + if training: + return (a, b, c, input.new_zeros((0,), dtype=torch.uint8)) + return ( + a, + weight.new_zeros((0,)), + weight.new_zeros((0,)), + input.new_zeros((0,), dtype=torch.uint8), + ) + + +def _broadcast_batch_norm_backward(x, broadcast_mask): + for axis, mask in enumerate(broadcast_mask): + if mask == 1 and not (axis < x.ndim and x.shape[axis] == mask): + x = x.unsqueeze(axis) + return x + + +@register_decomposition(aten.batch_norm_backward.default) +def batch_norm_backward( + grad_out: Tensor, + input: Tensor, + weight: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + save_mean: Tensor | None, + save_invstd: Tensor | None, + train: bool, + eps: float, + output_mask: list[bool], + reserve: Tensor, +) -> tuple[Tensor, Tensor | None, Tensor | None]: + return native_batch_norm_backward( + grad_out, + input, + weight, + running_mean, + running_var, + save_mean, + save_invstd, + train, + eps, + output_mask, + ) + + +@register_decomposition(aten.native_batch_norm_backward.default) +def native_batch_norm_backward( + grad_out: Tensor, + input: Tensor, + weight: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + save_mean: Tensor | None, + save_invstd: Tensor | None, + train: bool, + eps: float, + output_mask: list[bool], +) -> tuple[Tensor, Tensor | None, Tensor | None]: + input_dtype = input.dtype + if weight is not None: + weight_dtype = weight.dtype + else: + weight_dtype = input_dtype + computation_dtype = utils.get_computation_dtype(input.dtype) + ( + grad_out_cast, + input_cast, + weight_cast, + running_mean_cast, + running_var_cast, + save_mean_cast, + save_invstd_cast, + ) = ( + x.to(computation_dtype) if x is not None else x + for x in ( + grad_out, + input, + weight, + running_mean, + running_var, + save_mean, + save_invstd, + ) + ) + input_shape = input.shape + input_rank = input.dim() + if input_rank < 2: + raise AssertionError(f"rank of the input must be at least 2, got {input_rank}") + + axis = 1 + num_features = prod(list(input_shape)) / input_shape[axis] + mean = save_mean_cast + invstd = save_invstd_cast + if train: + if mean is None or invstd is None: + raise AssertionError("mean and invstd must not be None in training mode") + + else: + if running_mean_cast is None or running_var_cast is None: + raise AssertionError( + "running_mean_cast and running_var_cast must not be None in eval mode" + ) + mean = running_mean_cast + invstd = torch.rsqrt(running_var_cast + eps) + + broadcast_mask: list[int] = [1] * input_rank + broadcast_mask[axis] = input_shape[axis] + + reduction_axes: list[int] = [] + for i in range(input_rank): + if i != axis: + reduction_axes.append(i) + + mean = _broadcast_batch_norm_backward(mean, broadcast_mask) # type: ignore[arg-type] + norm = 1.0 / num_features + grad_output_sum = torch.sum(grad_out_cast, reduction_axes) # type: ignore[arg-type] + dot_p = torch.sum(grad_out_cast * (input_cast - mean), reduction_axes) # type: ignore[operator] + + grad_mean = _broadcast_batch_norm_backward(grad_output_sum * norm, broadcast_mask) + proj_scale = _broadcast_batch_norm_backward( + torch.mul(dot_p * norm, invstd * invstd), # type: ignore[operator] + broadcast_mask, + ) + + if weight_cast is None: + grad_scale = _broadcast_batch_norm_backward(invstd, broadcast_mask) * 1.0 # type: ignore[arg-type] + else: + grad_scale = _broadcast_batch_norm_backward( + invstd * weight_cast, broadcast_mask + ) + + if train: + proj = (input_cast - mean) * proj_scale # type: ignore[operator] + grad_input = ((grad_out_cast - proj) - grad_mean) * grad_scale + else: + grad_input = grad_out_cast * grad_scale + + if output_mask[1]: + grad_weight = dot_p * invstd + else: + grad_weight = None # "None" doesn't work with vjp, should use zeros for vjp + + if output_mask[2]: + grad_bias = grad_output_sum + else: + grad_bias = None # "None" doesn't work with vjp, should use zeros for vjp + + return ( + grad_input.to(input_dtype), + _maybe_cast(grad_weight, weight_dtype), + _maybe_cast(grad_bias, weight_dtype), + ) + + +# out_wrapper currently does not allow optional outputs +@register_decomposition(aten.native_batch_norm_backward.out) +def native_batch_norm_backward_out( + grad_out: Tensor, + input: Tensor, + weight: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + save_mean: Tensor | None, + save_invstd: Tensor | None, + train: bool, + eps: float, + output_mask: list[bool], + *, + out0: torch.Tensor, + out1: torch.Tensor, + out2: torch.Tensor, +) -> tuple[Tensor, Tensor | None, Tensor | None]: + result = native_batch_norm_backward( + grad_out, + input, + weight, + running_mean, + running_var, + save_mean, + save_invstd, + train, + eps, + output_mask, + ) + grad_input = (out0, out1, out2) + for i, r in enumerate(result): + if r is not None: + _maybe_resize_out(grad_input[i], r.shape) + _safe_copy_out(copy_from=r, copy_to=grad_input[i], exact_dtype=True) + + return grad_input + + +@register_decomposition(aten.miopen_batch_norm_backward) +@out_wrapper("out0", "out1", "out2") +def miopen_batch_norm_backward( + input: Tensor, + grad_output: Tensor, + weight: Tensor, + running_mean: Tensor | None, + running_var: Tensor | None, + save_mean: Tensor | None, + save_var: Tensor | None, + epsilon: float, +): + return aten.native_batch_norm_backward( + grad_output, + input, + weight, + running_mean, + running_var, + save_mean, + save_var, + True, + epsilon, + [True, True, True], + ) + + +@register_decomposition(aten.cudnn_batch_norm_backward) +@out_wrapper("out0", "out1", "out2") +def cudnn_batch_norm_backward( + input: Tensor, + grad_output: Tensor, + weight: Tensor, + running_mean: Tensor | None, + running_var: Tensor | None, + save_mean: Tensor | None, + save_var: Tensor | None, + epsilon: float, + reserveSpace: Tensor, +): + return aten.native_batch_norm_backward( + grad_output, + input, + weight, + running_mean, + running_var, + save_mean, + save_var, + True, + epsilon, + [True, True, True], + ) + + +@register_decomposition(aten._adaptive_avg_pool2d) +@out_wrapper() +@pw_cast_for_opmath +def adaptive_avg_pool2d(input: Tensor, output_size: tuple[int, int]): + # Preconditions + device = input.device + shape = input.shape + ndim = len(shape) + torch._check( + ndim in (3, 4), + lambda: f"adaptive_avg_pool2d(): Expected 3D or 4D tensor, but got {ndim}", + ) + for d in input.shape[-2:]: + torch._check( + d != 0, + lambda: "adaptive_avg_pool2d(): Expected input to have non-zero size for " + f"non-batch dimensions, but input has shape {tuple(shape)}.", + ) + + # Optimisation (we should also do this in the kernel implementation) + if shape[-2] % output_size[-2] == 0 and shape[-1] % output_size[-1] == 0: + stride = tuple(i // o for i, o in zip(shape[-2:], output_size)) + kernel = tuple( + i - (o - 1) * s for i, o, s in zip(shape[-2:], output_size, stride) + ) + return torch.nn.functional.avg_pool2d(input, kernel, stride) + + def start_index(a, b, c): + return torch.div(a * c, b, rounding_mode="trunc") + + def end_index(a, b, c): + return torch.div((a + 1) * c + b - 1, b, rounding_mode="trunc") + + def compute_idx(in_size, out_size): + orange = torch.arange(out_size, device=device, dtype=torch.int64) + i0 = start_index(orange, out_size, in_size) + # Let length = end_index - start_index, i.e. the length of the pooling kernels + # length.max() can be computed analytically as follows: + maxlength = in_size // out_size + 1 + in_size_mod = in_size % out_size + # adaptive = True iff there are kernels with different lengths + adaptive = not (in_size_mod == 0 or out_size % in_size_mod == 0) + if adaptive: + maxlength += 1 + elif in_size_mod == 0: + maxlength -= 1 + + range_max = torch.arange(maxlength, device=device, dtype=torch.int64) + idx = i0.unsqueeze(-1) + range_max + if adaptive: + # Need to clamp to avoid accessing out-of-bounds memory + # TODO make minimum accept scalars + maxval = torch.scalar_tensor( + in_size - 1, dtype=idx.dtype, device=idx.device + ) + idx = torch.minimum(idx, maxval) + + # Compute the length + i1 = end_index(orange, out_size, in_size) + length = i1 - i0 + else: + length = maxlength + return idx, length, range_max, adaptive + + # length is not None if it's constant, otherwise we'll need to compute it + idxh, length_h, range_max_h, adaptive_h = compute_idx(shape[-2], output_size[-2]) + idxw, length_w, range_max_w, adaptive_w = compute_idx(shape[-1], output_size[-1]) + + vals = input[..., _unsqueeze_to_dim(idxh, 4), idxw] + # Shortcut for the simpler case + if not adaptive_h and not adaptive_w: + return torch.mean(vals, dim=(-3, -1)) + + def maybe_mask(vals, length, range_max, adaptive, dim): + if isinstance(length, IntLike): + return vals, length + else: + # zero-out the things we didn't really want to select + if dim >= 0: + raise AssertionError(f"dim should be negative when masking, got {dim}") + # hack + mask = range_max >= length.unsqueeze(-1) + if dim == -2: + mask = _unsqueeze_to_dim(mask, 4) + vals = torch.masked_fill(vals, mask, 0.0) + # Compute the length of each window + length = _unsqueeze_to_dim(length, -dim) + return vals, length + + vals, length_h = maybe_mask( + vals, length_h, range_max_h, adaptive=adaptive_h, dim=-2 + ) + vals, length_w = maybe_mask( + vals, length_w, range_max_w, adaptive=adaptive_w, dim=-1 + ) + + # We unroll the sum as we assume that the kernels are going to be small + ret = None + for i, j in product(range(vals.shape[-3]), range(vals.shape[-1])): + if ret is None: + ret = vals[..., i, :, j] + else: + ret = ret + vals[..., i, :, j] + return ret / (length_h * length_w) + + +def _max_pool_nd_with_indices( + self: Tensor, + kernel_size: list[int], + stride: list[int], + padding: list[int], + dilation: list[int], + ceil_mode: bool, + n_dim: int, +) -> tuple[Tensor, Tensor]: + def _expand(val: list[int] | int, default: list[int] | None = None) -> list[int]: + if not isinstance(val, (list, tuple)): + return [val] * n_dim + if not val: + torch._check(default is not None, lambda: "default must be provided") + return default # type: ignore[return-value] + return val * n_dim if len(val) == 1 else list(val) + + ks = _expand(kernel_size) + st = _expand(stride, default=ks) + pa = _expand(padding) + di = _expand(dilation) + + torch._check( + self.ndim in (n_dim + 1, n_dim + 2), + lambda: f"Expected {n_dim + 1}D or {n_dim + 2}D input, got {self.ndim}D", + ) + + is_batched = self.ndim == n_dim + 2 + if not is_batched: + self = self.unsqueeze(0) + + input_sizes = list(self.shape[-n_dim:]) + device = self.device + + output_sizes = [ + torch._meta_registrations.pooling_output_shape( + input_sizes[d], ks[d], pa[d], st[d], di[d], ceil_mode + ) + for d in range(n_dim) + ] + + # Pad with -inf so out-of-bounds positions never win the max. For integer + # types, iinfo.min is a valid data value, so padding with it causes ties + # in argmax that produce wrong indices. Promote to a wider type so the + # sentinel is strictly below any representable value in the original dtype. + dtype = self.dtype + promoted = False + if dtype is torch.bool: + fill_value = 0.0 + elif dtype.is_floating_point: + fill_value = float("-inf") + else: + info = torch.iinfo(dtype) + if info.bits < 32: + self = self.to(torch.int32) + elif info.bits < 64: + self = self.to(torch.int64) + fill_value = float(info.min - 1) if info.bits < 64 else float(info.min) + promoted = True + + # Compute asymmetric padding: left = pa[d], right may be larger for ceil_mode + pad_args: list[int] = [] + for d in reversed(range(n_dim)): # F.pad takes last dim first + left = pa[d] + needed = (output_sizes[d] - 1) * st[d] + (ks[d] - 1) * di[d] + 1 + right = max(0, needed - (input_sizes[d] + 2 * pa[d])) + pa[d] + pad_args.extend([left, right]) + x = F.pad(self, pad_args, value=fill_value) + + # Build index tensor per spatial dim: + # idx[out_pos, ker_pos] = out_pos * stride + ker_pos * dilation + # Reshape each for broadcasting into the Cartesian product of all dims + idx_tensors = [] + for d in range(n_dim): + idx = ( + torch.arange(output_sizes[d], device=device, dtype=torch.int64).unsqueeze(1) + * st[d] + + torch.arange(ks[d], device=device, dtype=torch.int64).unsqueeze(0) * di[d] + ) + shape = [1] * (2 * n_dim) + shape[2 * d] = output_sizes[d] + shape[2 * d + 1] = ks[d] + idx_tensors.append(idx.reshape(shape)) + + # Advanced indexing gathers all pooling windows at once via broadcasting. + # Result: (N, C, out_0, k_0, out_1, k_1, ..., out_{n-1}, k_{n-1}) + windows = x[(Ellipsis, *idx_tensors)] + + # Permute to (N, C, out_0, ..., out_{n-1}, k_0, ..., k_{n-1}) + n_batch = 2 + perm = list(range(n_batch)) + perm += [n_batch + 2 * d for d in range(n_dim)] + perm += [n_batch + 2 * d + 1 for d in range(n_dim)] + windows = windows.permute(perm) + + # Flatten kernel dims and take the max + out_shape = list(windows.shape[: n_batch + n_dim]) + windows = windows.reshape(*out_shape, -1) + values, local_argmax = windows.max(dim=-1) + + # Convert local_argmax in [0, prod(ks)) to per-dim kernel offsets + kernel_pos = [] + remaining = local_argmax + for d in range(n_dim): + divisor = 1 + for dd in range(d + 1, n_dim): + divisor *= ks[dd] + kernel_pos.append(remaining // divisor) + remaining = remaining % divisor + + # Compute flat index into the original (unpadded) input spatial volume + orig_coords = [] + for d in range(n_dim): + shape = [1] * (n_batch + n_dim) + shape[n_batch + d] = output_sizes[d] + out_pos = torch.arange( + output_sizes[d], device=device, dtype=torch.int64 + ).reshape(shape) + orig_coords.append(out_pos * st[d] + kernel_pos[d] * di[d] - pa[d]) + + flat_indices = orig_coords[0] + for d in range(1, n_dim): + flat_indices = flat_indices * input_sizes[d] + orig_coords[d] + + if promoted: + values = values.to(dtype) + + if not is_batched: + values = values.squeeze(0) + flat_indices = flat_indices.squeeze(0) + + return values, flat_indices + + +@register_decomposition(aten.max_pool2d_with_indices) +@out_wrapper("out", "indices") +def max_pool2d_with_indices( + self: Tensor, + kernel_size: list[int], + stride: list[int] = [], # noqa: B006 + padding: list[int] = [0], # noqa: B006 + dilation: list[int] = [1], # noqa: B006 + ceil_mode: bool = False, +) -> tuple[Tensor, Tensor]: + return _max_pool_nd_with_indices( + self, kernel_size, stride, padding, dilation, ceil_mode, n_dim=2 + ) + + +@register_decomposition(aten.max_pool3d_with_indices) +@out_wrapper("out", "indices") +def max_pool3d_with_indices( + self: Tensor, + kernel_size: list[int], + stride: list[int] = [], # noqa: B006 + padding: list[int] = [0], # noqa: B006 + dilation: list[int] = [1], # noqa: B006 + ceil_mode: bool = False, +) -> tuple[Tensor, Tensor]: + return _max_pool_nd_with_indices( + self, kernel_size, stride, padding, dilation, ceil_mode, n_dim=3 + ) + + +@register_decomposition(aten.adaptive_max_pool2d) +@out_wrapper("out", "indices") +def adaptive_max_pool2d( + input: Tensor, + output_size: tuple[int, int], +) -> tuple[Tensor, Tensor]: + ndim = input.ndim + torch._check( + ndim in (3, 4), + lambda: f"adaptive_max_pool2d(): Expected 3D or 4D tensor, but got {ndim}D", + ) + for i in range(1, ndim): + torch._check( + input.size(i) > 0, + lambda: ( + "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" + ), + ) + + h_in = input.shape[-2] + w_in = input.shape[-1] + h_out, w_out = output_size + + # Case 1: empty output + if h_out == 0 or w_out == 0: + output_shape = list(input.shape[:-2]) + [h_out, w_out] + return ( + input.new_empty(output_shape), + input.new_empty(output_shape, dtype=torch.int64), + ) + + # Case 2: global pooling (output_size == (1, 1)) + # Equivalent to amax over spatial dims. argmax on the flattened spatial + # plane produces flat indices encoded as ih*W+iw. + if h_out == 1 and w_out == 1: + values = torch.amax(input, dim=(-2, -1), keepdim=True) + indices = torch.argmax(input.flatten(-2), dim=-1).unsqueeze(-1).unsqueeze(-1) + return values, indices + + # Case 3: evenly divisible -- delegate to max_pool2d_with_indices + if h_in % h_out == 0 and w_in % w_out == 0: + kernel_size = [h_in // h_out, w_in // w_out] + return aten.max_pool2d_with_indices(input, kernel_size) + + # Case 4: general (non-evenly-divisible, output_size > 1) + return NotImplemented + + +@register_decomposition(aten.adaptive_max_pool3d) +@out_wrapper("out", "indices") +def adaptive_max_pool3d( + input: Tensor, + output_size: tuple[int, int, int], +) -> tuple[Tensor, Tensor]: + ndim = input.ndim + torch._check( + ndim in (4, 5), + lambda: f"adaptive_max_pool3d(): Expected 4D or 5D tensor, but got {ndim}D", + ) + for i in range(1, ndim): + torch._check( + input.size(i) > 0, + lambda: ( + "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" + ), + ) + + d_in = input.shape[-3] + h_in = input.shape[-2] + w_in = input.shape[-1] + d_out, h_out, w_out = output_size + + # Case 1: empty output + if d_out == 0 or h_out == 0 or w_out == 0: + output_shape = list(input.shape[:-3]) + [d_out, h_out, w_out] + return ( + input.new_empty(output_shape), + input.new_empty(output_shape, dtype=torch.int64), + ) + + # Case 2: global pooling (output_size == (1, 1, 1)) + # Equivalent to amax over spatial dims. argmax on the flattened spatial + # volume produces flat indices encoded as + # id*H*W + ih*W + iw. + if d_out == 1 and h_out == 1 and w_out == 1: + values = torch.amax(input, dim=(-3, -2, -1), keepdim=True) + indices = ( + torch.argmax(input.flatten(-3), dim=-1) + .unsqueeze(-1) + .unsqueeze(-1) + .unsqueeze(-1) + ) + return values, indices + + # Case 3: evenly divisible -- delegate to max_pool3d_with_indices + if d_in % d_out == 0 and h_in % h_out == 0 and w_in % w_out == 0: + kernel_size = [d_in // d_out, h_in // h_out, w_in // w_out] + return aten.max_pool3d_with_indices(input, kernel_size) + + # Case 4: general (non-evenly-divisible, output_size > 1) + return NotImplemented + + +def _max_unpoolnd( + self: TensorLike, indices: TensorLike, output_size: list[int], dim: int +): + # If the input tensors self and indices came from max_pool call as + # required by the documentation, this operation is deterministic + # because that ensures that if there are two entries in `indices` + # tensor that are equal, the corresponding values in `self` are also + # equal. If this condition is not satisfied, the operation is + # non-deterministic as one of the different values in `self` 'wins'. + utils.alert_not_deterministic(f"max_unpooling{dim}d_forward_out") + for i, size in enumerate(output_size): + torch._check( + size >= 0, + lambda i=i, size=size: ( + f"max_unpooling{dim}d(): output_size must contain non-negative " + f"spatial dimensions, but got output_size[{i}]={size}" + ), + ) + + # The native CPU kernel (aten/src/ATen/native/MaxUnpooling.cpp) and the XPU + # kernel (torch-xpu-ops MaxUnpoolingKernels.cpp) preserve the input's memory + # format via suggest_memory_format, while the CUDA kernel and the 3d kernels + # always return contiguous output. + def _restride(t: TensorLike) -> TensorLike: + if dim == 2 and self.device.type in ("cpu", "xpu"): + return t.contiguous(memory_format=utils.suggest_memory_format(self)) + return t + + output_shape = list(self.shape[:-dim]) + list(output_size) + if any(s == 0 for s in output_shape): + # The native CPU kernel still applies the memory format to the empty + # output (resize_ runs before the numel()==0 guard); mirror it here. + return _restride(self.new_zeros(output_shape)) + nc = reduce(operator.mul, self.shape[:-dim]) + hw = reduce(operator.mul, output_size) + indices_nc_shape = [1] * self.ndim + indices_nc_shape[:-dim] = self.shape[:-dim] + indices_flat = ( + indices + aten.arange(nc, device=self.device).view(indices_nc_shape) * hw + ).reshape(-1) + + output = self.new_zeros(output_shape) + result = aten._unsafe_index_put( + output.reshape(-1), [indices_flat], self.reshape(-1), accumulate=False + ).view(output.shape) + return _restride(result) + + # Match the CPU max_unpool2d layout behavior: the native 4D path resizes + # the output with self.suggest_memory_format(), preserving channels-last. + # The 3D path uses the default contiguous layout. + # For compile, FakeTensor preserves the real device here. + # The only edge-case we see is direct meta calls, which follow meta strides + # and may differ from CPU eager layout. + if dim == 2 and self.ndim == 4 and self.device.type == "cpu": + result = result.contiguous(memory_format=utils.suggest_memory_format(self)) + + return result + + +@register_decomposition(aten.max_unpool2d) +@out_wrapper() +def max_unpool2d( + self: TensorLike, + indices: TensorLike, + output_size: list[int], +): + torch._check( + indices.dtype == torch.int64, + lambda: f"elements in indices should be type int64 but got: {indices.dtype}", + ) + torch._check( + len(output_size) == 2, + lambda: ( + f"There should be exactly two elements (height, width) in output_size, " + f"but got {len(output_size)} elements." + ), + ) + + torch._check( + self.ndim in (3, 4), + lambda: ( + f"Input to max_unpooling2d should be a 3d or 4d Tensor, " + f"but got a tensor with {self.ndim} dimensions." + ), + ) + torch._check( + self.shape == indices.shape, + lambda: ( + f"Expected shape of indices to be same as that of the input tensor ({self.shape}) " + f"but got indices tensor with shape: {indices.shape}" + ), + ) + + for i in range(1, self.ndim): + torch._check( + self.size(i) > 0, + lambda: ( + f"max_unpooling2d(): " + f"Expected input to have non-zero size for non-batch dimensions, " + f"but got {self.shape} with dimension {i} being empty." + ), + ) + + return _max_unpoolnd(self, indices, output_size, 2) + + +@register_decomposition(aten.max_unpool3d) +@out_wrapper() +def max_unpool3d( + input: TensorLike, + indices: TensorLike, + output_size: list[int], + stride: list[int], + padding: list[int], +): + torch._check( + indices.dtype == torch.int64, lambda: "elements in indices should be type int64" + ) + torch._check( + input.ndim in (4, 5), + lambda: f"Input to max_unpooling3d should be a 4d or 5d Tensor, but got a tensor with {input.ndim} dimensions.", + ) + torch._check( + len(output_size) == 3, + lambda: ( + f"There should be exactly three elements (depth, height, width) in output_size, " + f"but got {len(output_size)} elements." + ), + ) + torch._check( + len(stride) == 3, + lambda: f"There should be exactly three elements (depth, height, width) in stride, but got: {len(stride)} elements.", + ) + torch._check( + len(padding) == 3, + lambda: f"There should be exactly three elements (depth, height, width) in padding, but got: {len(padding)} elements.", + ) + torch._check( + input.shape == indices.shape, + lambda: ( + f"Expected shape of indices to be same as that of the input tensor ({input.shape}) " + f"but got indices tensor with shape: {indices.shape}" + ), + ) + + for i in range(1, input.ndim): + torch._check( + input.size(i) > 0, + lambda: ( + f"max_unpooling3d(): " + f"Expected input to have non-zero size for non-batch dimensions, " + f"but got {input.shape} with dimension {i} being empty." + ), + ) + + torch._check( + stride[0] > 0 and stride[1] > 0 and stride[2] > 0, + lambda: f"strides should be greater than zero, but got stride: {stride}", + ) + + return _max_unpoolnd(input, indices, output_size, 3) + + +@register_decomposition(aten.index_add_) +def index_add_( + x: TensorLike, + dim: int, + index: TensorLike, + tensor: TensorLike, + *, + alpha: NumberType = 1, +): + return _index_add(x, dim, index, tensor, inplace=True, alpha=alpha) + + +@register_decomposition(aten.index_add) +@out_wrapper() +def index_add( + x: TensorLike, + dim: int, + index: TensorLike, + tensor: TensorLike, + *, + alpha: NumberType = 1, +): + return _index_add(x, dim, index, tensor, inplace=False, alpha=alpha) + + +def _index_add( + x: TensorLike, + dim: int, + index: TensorLike, + tensor: TensorLike, + *, + inplace: bool, + alpha: NumberType = 1, +): + dim = utils.canonicalize_dims(x.ndim, dim) + torch._check( + x.device == index.device and x.device == tensor.device, + lambda: ( + f"index_add(): self, index and source expected to be in the same device, " + f"but got (self) {x.device}, (index) {index.device}, " + f"and (source) {tensor.device}" + ), + ) + torch._check( + index.ndim <= 1, + lambda: f"Index should have dimension 1 or 0 (got {index.ndim})", + ) + index_size = index.size(0) if index.ndim == 1 else 1 + tensor_size = tensor.size(dim) if tensor.ndim > 0 else 1 + torch._check( + tensor_size == index_size, + lambda: f"Number of indices ({index_size}) should be equal to tensor.size(dim) ({tensor_size}), for {dim=}", + ) + if alpha != 1: + python_type = utils.dtype_to_type(x.dtype) + torch._check( + python_type is bool + or utils.is_weakly_lesser_type(type(alpha), python_type), + lambda: f"alpha argument of type {type(alpha)} cannot be safely cast to type {python_type}!", + ) + tensor = tensor * alpha + # Treat scalars as elements of \R^1 + zero_dim = x.ndim == 0 + x1 = x.unsqueeze(0) if zero_dim else x + idx = (None,) * dim + (index,) + index_put = aten.index_put_ if inplace else aten.index_put + out = index_put(x1, idx, tensor, accumulate=True) + if inplace: + return x + else: + return out.squeeze(0) if zero_dim else out.contiguous() + + +@register_decomposition(aten.pad_sequence.default) +@aten.pad_sequence.default.py_impl(DispatchKey.CompositeImplicitAutograd) +def pad_sequence(sequences, batch_first=False, padding_value=0.0, padding_side="right"): + torch._check(len(sequences) > 0, lambda: "received an empty list of sequences") + torch._check( + padding_side == "left" or padding_side == "right", + lambda: f"Expected padding_side to be one of left or right, but got {padding_side}.", + ) + sequences_size = len(sequences) + max_size = sequences[0].size() + trailing_dims = max_size[1:] + # Fold with sym_max (not Python max, which does pairwise `>` comparisons) + # so symbolic/unbacked sequence lengths don't trigger a data-dependent guard. + max_len = reduce(torch.sym_max, (x.size(0) for x in sequences)) + if batch_first: + out_dims = (sequences_size, max_len) + else: + out_dims = (max_len, sequences_size) + out_dims = out_dims + trailing_dims + out = sequences[0].new_full(out_dims, padding_value) + dim_paddings = (0, 0) * len(trailing_dims) + for i in range(sequences_size): + currseq = sequences[i].to(dtype=out.dtype) + pad_amount = max_len - currseq.size(0) + if padding_side == "right": + row = aten.constant_pad_nd( + currseq, dim_paddings + (0, pad_amount), padding_value + ) + else: + row = aten.constant_pad_nd( + currseq, dim_paddings + (pad_amount, 0), padding_value + ) + if batch_first: + out = aten.select_scatter(out, row, dim=0, index=i) + else: + out = aten.select_scatter(out, row, dim=1, index=i) + return out + + +@register_decomposition(aten.index_copy_) +def index_copy_(x: TensorLike, dim: int, index: TensorLike, tensor: TensorLike): + return _index_copy(x, dim, index, tensor, inplace=True) + + +@register_decomposition(aten.index_copy) +@out_wrapper() +def index_copy(x: TensorLike, dim: int, index: TensorLike, tensor: TensorLike): + return _index_copy(x, dim, index, tensor, inplace=False) + + +def _index_copy( + x: TensorLike, dim: int, index: TensorLike, tensor: TensorLike, *, inplace: bool +): + from torch.fx.experimental.symbolic_shapes import sym_eq + + dim = utils.canonicalize_dims(x.ndim, dim) + torch._check( + x.device == index.device and x.device == tensor.device, + lambda: ( + f"index_copy(): self, index and source expected to be in the same device, " + f"but got (self) {x.device}, (index) {index.device}, " + f"and (source) {tensor.device}" + ), + ) + torch._check( + index.ndim <= 1, + lambda: f"Index should have dimension 1 or 0 (got {index.ndim})", + ) + num_indices = index.numel() + if tensor.ndim == 0: + torch._check( + num_indices == 1, + lambda: ( + "index_copy_(): When source is scalar, index should have " + f"one element (got {num_indices})" + ), + ) + elif x.ndim != 0: + torch._check( + tensor.ndim == x.ndim, + lambda: ( + "index_copy_(): When source and destination are not scalars, " + "their dimensionality must match. Source dimensionality " + f"({tensor.ndim}), destination dimensionality ({x.ndim})" + ), + ) + + x_sliced_shape = x.shape[:dim] + x.shape[dim + 1 :] if x.ndim > 0 else () + tensor_sliced_shape = ( + tensor.shape[:dim] + tensor.shape[dim + 1 :] if tensor.ndim > 0 else () + ) + torch._check( + sym_eq(x_sliced_shape, tensor_sliced_shape), + lambda: ( + "index_copy_(): Source/destination tensor must have same slice shapes. " + f"Destination slice shape: {x_sliced_shape} at dimension {dim} " + f"and source slice shape: {tensor_sliced_shape} at dimension 0." + ), + ) + if tensor.ndim != 0: + torch._check( + num_indices == tensor.size(dim), + lambda: ( + f"index_copy_(): Number of indices ({num_indices}) should be " + f"equal to source.size(dim) ({tensor.size(dim)})" + ), + ) + # Treat scalars as elements of \R^1 + zero_dim = x.ndim == 0 + x1 = x.unsqueeze(0) if zero_dim else x + index = index.unsqueeze(0) if index.ndim == 0 else index + idx = (None,) * dim + (index,) + index_put = aten.index_put_ if inplace else aten.index_put + out = index_put(x1, idx, tensor) + if inplace: + return x + else: + return out.squeeze(0) if zero_dim else out.contiguous() + + +# nb: Should use acc_t, not op_math +@register_decomposition(aten.log_sigmoid_forward) +@out_wrapper("output", "buffer") +@pw_cast_for_opmath +def log_sigmoid_forward(self: Tensor) -> tuple[Tensor, Tensor]: + min = torch.minimum(self.new_zeros(()), self) + z = torch.exp(-torch.abs(self)) + if self.is_cuda or self.is_xpu: + buffer = self.new_zeros((0,)) + else: + buffer = z + return min - torch.log1p(z), buffer + + +@register_decomposition(aten.uniform) +@out_wrapper() +def uniform( + x: Tensor, + low: bool | int | float = 0.0, + high: bool | int | float = 1.0, + generator: torch.Generator | None = None, +): + return prims._uniform_helper( + x.shape, + stride=x.stride(), + low=sym_float(low), + high=sym_float(high), + dtype=x.dtype, + device=x.device, + generator=generator, + ) + + +@register_decomposition(aten.uniform_) +def uniform_(self, low=0, high=1, generator=None): + return self.copy_(uniform(self, low, high, generator)) + + +# aten/src/ATen/native/UpSample.cpp compute_output_size +def upsample_compute_output_size(input_size, output_size, scale_factors): + spatial_dimensions = len(input_size) - 2 + if output_size is not None: + torch._check( + scale_factors is None, + lambda: "Must specify exactly one of output_size and scale_factors", + ) + torch._check(len(output_size) == spatial_dimensions, lambda: "") + return output_size + if scale_factors is not None: + # NB: this isn't necessary lol + torch._check( + output_size is None, + lambda: "Must specify exactly one of output_size and scale_factors", + ) + torch._check(len(scale_factors) == spatial_dimensions, lambda: "") + output_size = [] + for i, s in enumerate(scale_factors): + if int(s) == s: + output_size.append(input_size[i + 2] * int(s)) + else: + output_size.append(sym_int(input_size[i + 2] * s)) + return output_size + torch._check( + False, lambda: "Must specify exactly one of output_size and scale_factors" + ) + + +def get_scale_value(scales, idx): + if scales is None: + return None + return scales[idx] + + +@register_decomposition(aten.upsample_nearest1d.vec) +@register_decomposition(aten.upsample_nearest2d.vec) +@register_decomposition(aten.upsample_nearest3d.vec) +@aten.upsample_nearest1d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_nearest1d.vec.py_impl(DispatchKey.Autograd) +@aten.upsample_nearest2d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_nearest2d.vec.py_impl(DispatchKey.Autograd) +@aten.upsample_nearest3d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_nearest3d.vec.py_impl(DispatchKey.Autograd) +def _upsample_nearest_vec( + input: Tensor, + output_size: list[int] | None, + scale_factors: list[float] | None, +) -> Tensor: + osize = upsample_compute_output_size(input.size(), output_size, scale_factors) + scales = ( + scale_factors if scale_factors else [None] * len(osize) # type: ignore[list-item] + ) + return _upsample_nearest(input, osize, scales) + + +@register_decomposition(aten._upsample_nearest_exact1d.vec) +@register_decomposition(aten._upsample_nearest_exact2d.vec) +@register_decomposition(aten._upsample_nearest_exact3d.vec) +@aten._upsample_nearest_exact1d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_nearest_exact1d.vec.py_impl(DispatchKey.Autograd) +@aten._upsample_nearest_exact2d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_nearest_exact2d.vec.py_impl(DispatchKey.Autograd) +@aten._upsample_nearest_exact3d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_nearest_exact3d.vec.py_impl(DispatchKey.Autograd) +def _upsample_nearest_exact_vec( + input: Tensor, + output_size: list[int] | None, + scale_factors: list[float] | None, +) -> Tensor: + osize = upsample_compute_output_size(input.size(), output_size, scale_factors) + scales = ( + scale_factors if scale_factors else [None] * len(osize) # type: ignore[list-item] + ) + return _upsample_nearest(input, osize, scales, exact=True) + + +def _compute_upsample_nearest_indices(input, output_size, scales, exact=False): + # For each dim in output_size, compute the set of input indices used + # to produce the upsampled output. + indices = [] + num_spatial_dims = len(output_size) + offset = 0.5 if exact else 0.0 + + for d in range(num_spatial_dims): + # Math matches aten/src/ATen/native/cpu/UpSampleKernel.cpp + # + # Indices are computed as following: + # scale = isize / osize + # Case: exact=False + # input_index = floor(output_index * scale) + # Same as OpenCV INTER_NEAREST + # + # Case: exact=False + # index_f32 = (output_index + 0.5) * scale - 0.5 + # input_index = round(index_f32) + # Same as Pillow and Scikit-Image/Scipy ndi.zoom + osize = output_size[d] + isize = input.shape[-num_spatial_dims + d] + + # check for scales[d] > 0 is in compute_scales_value in aten/src/ATen/native/UpSample.h + scale = ( + isize / (isize * scales[d]) + if scales[d] is not None and scales[d] > 0 + else isize / osize + ) + + output_indices = torch.arange(osize, dtype=torch.float32, device=input.device) + input_indices = ((output_indices + offset) * scale).to(torch.int64) + for _ in range(num_spatial_dims - 1 - d): + input_indices = input_indices.unsqueeze(-1) + indices.append(input_indices) + return indices + + +@register_decomposition([aten.upsample_nearest1d.default, aten.upsample_nearest1d.out]) +@aten.upsample_nearest1d.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_nearest1d.default.py_impl(DispatchKey.Autograd) +@out_wrapper(preserve_memory_format=True, exact_dtype=True) +def upsample_nearest1d( + input: Tensor, + output_size: list[int], + scales: float | None = None, +) -> Tensor: + return _upsample_nearest(input, output_size, [scales]) + + +@register_decomposition( + [aten._upsample_nearest_exact1d.default, aten._upsample_nearest_exact1d.out] +) +@aten._upsample_nearest_exact1d.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_nearest_exact1d.default.py_impl(DispatchKey.Autograd) +@out_wrapper(preserve_memory_format=True, exact_dtype=True) +def upsample_nearest_exact1d( + input: Tensor, + output_size: list[int], + scales: float | None = None, +) -> Tensor: + return _upsample_nearest(input, output_size, [scales], exact=True) + + +@register_decomposition([aten.upsample_nearest2d.default, aten.upsample_nearest2d.out]) +@aten.upsample_nearest2d.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_nearest2d.default.py_impl(DispatchKey.Autograd) +@out_wrapper(preserve_memory_format=True, exact_dtype=True) +def upsample_nearest2d( + input: Tensor, + output_size: list[int], + scales_h: float | None = None, + scales_w: float | None = None, +) -> Tensor: + return _upsample_nearest(input, output_size, [scales_h, scales_w]) + + +@register_decomposition( + [aten._upsample_nearest_exact2d.default, aten._upsample_nearest_exact2d.out] +) +@aten._upsample_nearest_exact2d.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_nearest_exact2d.default.py_impl(DispatchKey.Autograd) +@out_wrapper(preserve_memory_format=True, exact_dtype=True) +def _upsample_nearest_exact2d( + input: Tensor, + output_size: list[int], + scales_h: float | None = None, + scales_w: float | None = None, +) -> Tensor: + return _upsample_nearest(input, output_size, [scales_h, scales_w], exact=True) + + +@register_decomposition([aten.upsample_nearest3d.default, aten.upsample_nearest3d.out]) +@aten.upsample_nearest3d.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_nearest3d.default.py_impl(DispatchKey.Autograd) +@out_wrapper(preserve_memory_format=True, exact_dtype=True) +def upsample_nearest3d( + input: Tensor, + output_size: list[int], + scales_d: float | None = None, + scales_h: float | None = None, + scales_w: float | None = None, +) -> Tensor: + return _upsample_nearest(input, output_size, [scales_d, scales_h, scales_w]) + + +@register_decomposition( + [aten._upsample_nearest_exact3d.default, aten._upsample_nearest_exact3d.out] +) +@aten._upsample_nearest_exact3d.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_nearest_exact3d.default.py_impl(DispatchKey.Autograd) +@out_wrapper(preserve_memory_format=True, exact_dtype=True) +def _upsample_nearest_exact3d( + input: Tensor, + output_size: list[int], + scales_d: float | None = None, + scales_h: float | None = None, + scales_w: float | None = None, +) -> Tensor: + return _upsample_nearest( + input, output_size, [scales_d, scales_h, scales_w], exact=True + ) + + +@pw_cast_for_opmath +def _upsample_nearest( + input: Tensor, + output_size: list[int], + scales: list[float | None], + exact: bool = False, +) -> Tensor: + spatial_indices = _compute_upsample_nearest_indices( + input, output_size, scales, exact=exact + ) + + indices = [None, None] + spatial_indices + result = aten._unsafe_index(input, indices) + + if result.ndim in (4, 5): + # convert output to correct memory format, if necessary + memory_format = utils.suggest_memory_format(input) + + # following "heuristic: only use channels_last path when it's faster than the contiguous path" + n_channels = input.shape[1] + if result.ndim == 4 and input.device.type == "cuda" and n_channels < 4: + memory_format = torch.contiguous_format + + result = result.contiguous(memory_format=memory_format) + return result + + +def gather_params(params, has_biases, has_projections): + if has_biases and has_projections: + group_size = 5 + elif has_biases: + group_size = 4 + elif has_projections: + group_size = 3 + else: + group_size = 2 + + if len(params) % group_size != 0: + raise AssertionError( + f"len(params)={len(params)} is not divisible by group_size={group_size}" + ) + return [ + tuple(params[i : i + group_size]) for i in range(0, len(params), group_size) + ] + + +def params_hiddens(params, hiddens, i, bidirectional): + if bidirectional: + cur_params, cur_hidden = params[2 * i], hiddens[2 * i] + bidir_params, bidir_hidden = params[2 * i + 1], hiddens[2 * i + 1] + else: + cur_params, cur_hidden = params[i], hiddens[i] + bidir_params, bidir_hidden = None, None + + return cur_params, cur_hidden, bidir_params, bidir_hidden + + +def update_hidden_for_packed(cur_hidden, last_batch_size, batch_size, hiddens): + if last_batch_size <= batch_size: + raise AssertionError( + f"last_batch_size ({last_batch_size}) must be > batch_size ({batch_size})" + ) + hiddens.append(cur_hidden.narrow(0, batch_size, last_batch_size - batch_size)) + return cur_hidden.narrow(0, 0, batch_size) + + +def update_hidden_for_packed_reverse( + cur_hidden, last_batch_size, batch_size, inp_hidden +): + if last_batch_size == batch_size: + return cur_hidden + if last_batch_size >= batch_size: + raise AssertionError( + f"last_batch_size ({last_batch_size}) must be < batch_size ({batch_size})" + ) + return torch.concat( + ( + cur_hidden, + inp_hidden.narrow(0, last_batch_size, batch_size - last_batch_size), + ) + ) + + +def one_layer_rnn_data( + inp, hidden, params, has_biases, hidden_fn, batch_sizes, reverse=False +): + ih_weight = params[0] + hh_weight = params[1] + ih_bias = params[2] if has_biases else None + hh_bias = params[3] if has_biases else None + + step_output = [] + hiddens: list[torch.Tensor] = [] + + last_batch_size = batch_sizes[-1] if reverse else batch_sizes[0] + cur_hidden = hidden.narrow(0, 0, last_batch_size) + split_inp = torch.split(inp, list(batch_sizes)) + if reverse: + split_inp = split_inp[::-1] + for inp in split_inp: + i = inp.shape[0] + + if last_batch_size == i: + pass # don't update cur_hidden + # this will only happen when reverse=False, since batch sizes are sorted largest -> smallest + elif reverse: + cur_hidden = update_hidden_for_packed_reverse( + cur_hidden, last_batch_size, i, hidden + ) + else: + cur_hidden = update_hidden_for_packed( + cur_hidden, last_batch_size, i, hiddens + ) + + cur_hidden = hidden_fn(inp, cur_hidden, ih_weight, ih_bias, hh_weight, hh_bias) + last_batch_size = i + step_output.append(cur_hidden) + + if reverse: + step_output.reverse() + else: + hiddens.append(cur_hidden) + hiddens.reverse() + + out = torch.cat(step_output, 0) + hidden_out = torch.cat(hiddens, 0) if not reverse else cur_hidden + return out, hidden_out + + +def rnn_cell(nonlinearity): + def inner(i, cur_hidden, ih_weight, ih_bias, hh_weight, hh_bias): + return nonlinearity(F.linear(cur_hidden, hh_weight, hh_bias) + i) + + return inner + + +def rnn_cell_data(nonlinearity): + def inner(i, cur_hidden, ih_weight, ih_bias, hh_weight, hh_bias): + i = F.linear(i, ih_weight, ih_bias) + return nonlinearity(F.linear(cur_hidden, hh_weight, hh_bias) + i) + + return inner + + +def one_layer_rnn(inp, hidden, params, has_biases, hidden_fn, reverse=False): + ih_weight = params[0] + hh_weight = params[1] + ih_bias = params[2] if has_biases else None + hh_bias = params[3] if has_biases else None + + precomputed_input = F.linear(inp, ih_weight, ih_bias) + precomputed_input = precomputed_input.flip(0) if reverse else precomputed_input + cur_hidden = hidden.unsqueeze(0) + step_output = [] + for i in precomputed_input: + cur_hidden = hidden_fn(i, cur_hidden, ih_weight, ih_bias, hh_weight, hh_bias) + step_output.append(cur_hidden) + + if reverse: + step_output.reverse() + + out = torch.cat(step_output, 0) + + return out, cur_hidden.squeeze(0) + + +def mkldnn_one_layer_lstm(inp, hidden, params, has_biases, reverse=False): + w0 = params[0] + w1 = params[1] + if has_biases: + w2 = params[2] + w3 = params[3] + else: + w2 = torch.zeros(w0.size()) + w3 = torch.zeros(w1.size()) + + hx = hidden[0].unsqueeze(0) + cx = hidden[1].unsqueeze(0) + + batch_sizes: list[int] = [] + mode = 2 # third_party/ideep/include/ideep/abstract_types.hpp: ideep::rnn_kind::LSTM = 2 + hidden_size = hx.size(2) + num_layers = 1 + + # _rnn_helper already handles bidirectional and batch_first so we hard-code them to False here + bidirectional = False + batch_first = False + + train = False + # If batch_first, inp has been permuted in _rnn_helper. Convert to contiguous here. + # Same as aten/src/ATen/native/mkldnn/RNN.cpp: mkldnn_rnn: input = input.contiguous(); + inp = inp.contiguous() + hx = hx.contiguous() + cx = cx.contiguous() + outputs = torch.ops.aten.mkldnn_rnn_layer.default( + inp, + w0, + w1, + w2, + w3, + hx, + cx, + reverse, + batch_sizes, + mode, + hidden_size, + num_layers, + has_biases, + bidirectional, + batch_first, + train, + ) + y, hy, cy = outputs[0], outputs[1], outputs[2] + return y, (hy.squeeze(0), cy.squeeze(0)) + + +def _rnn_helper( + input, + hidden, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, + layer_fn, +): + input = input.transpose(0, 1) if batch_first else input + final_hiddens = [] + + for i in range(num_layers): + cur_params, cur_hidden, bidir_params, bidir_hidden = params_hiddens( + params, hidden, i, bidirectional + ) + dropout = dropout if (train and num_layers < i - 1) else 0.0 + fwd_inp, fwd_hidden = layer_fn(input, cur_hidden, cur_params, has_biases) + final_hiddens.append(fwd_hidden) + + if bidirectional: + bwd_inp, bwd_hidden = layer_fn( + input, bidir_hidden, bidir_params, has_biases, reverse=True + ) + final_hiddens.append(bwd_hidden) + + if bidirectional: + input = torch.cat([fwd_inp, bwd_inp], fwd_inp.dim() - 1) # type: ignore[possibly-undefined] + else: + input = fwd_inp + + if dropout != 0 and train and i < num_layers - 1: + input = torch.dropout(input, dropout, train=True) + + input = input.transpose(0, 1) if batch_first else input + return input, final_hiddens + + +@register_decomposition(aten.rnn_tanh.input) +@aten.rnn_tanh.input.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.rnn_tanh.input.py_impl(DispatchKey.Autograd) +def rnn_tanh_input( + input, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, +): + hidden = hx.unbind(0) + params = gather_params(params, has_biases, False) + out, final_hiddens = _rnn_helper( + input, + hidden, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, + partial(one_layer_rnn, hidden_fn=rnn_cell(torch.tanh)), + ) + return out, torch.stack(final_hiddens, 0) + + +@register_decomposition(aten.rnn_relu.input) +@aten.rnn_relu.input.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.rnn_relu.input.py_impl(DispatchKey.Autograd) +def rnn_relu_input( + input, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, +): + hidden = hx.unbind(0) + params = gather_params(params, has_biases, False) + out, final_hiddens = _rnn_helper( + input, + hidden, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, + partial(one_layer_rnn, hidden_fn=rnn_cell(torch.relu)), + ) + return out, torch.stack(final_hiddens, 0) + + +@register_decomposition(aten.rnn_relu.data) +@aten.rnn_relu.data.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.rnn_relu.data.py_impl(DispatchKey.Autograd) +def rnn_relu_data( + data, + batch_sizes, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, +): + hidden = hx.unbind(0) + params = gather_params(params, has_biases, False) + out, final_hiddens = _rnn_helper( + data, + hidden, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + False, + partial( + one_layer_rnn_data, + batch_sizes=batch_sizes, + hidden_fn=rnn_cell_data(torch.relu), + ), + ) + return out, torch.stack(final_hiddens, 0) + + +@register_decomposition(aten.rnn_tanh.data) +@aten.rnn_tanh.data.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.rnn_tanh.data.py_impl(DispatchKey.Autograd) +def rnn_tanh_data( + data, + batch_sizes, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, +): + hidden = hx.unbind(0) + params = gather_params(params, has_biases, False) + out, final_hiddens = _rnn_helper( + data, + hidden, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + False, + partial( + one_layer_rnn_data, + batch_sizes=batch_sizes, + hidden_fn=rnn_cell_data(torch.tanh), + ), + ) + return out, torch.stack(final_hiddens, 0) + + +def lstm_cell(inp, hx, cx, hh_weight, hh_bias, hr_weight, chunk_dim): + gates = F.linear(hx, hh_weight, hh_bias) + inp + chunked_gates = gates.chunk(4, chunk_dim) + in_gate = chunked_gates[0].sigmoid() + forget_gate = chunked_gates[1].sigmoid() + cell_gate = chunked_gates[2].tanh() + out_gate = chunked_gates[3].sigmoid() + cy = forget_gate * cx + (in_gate * cell_gate) + hy = out_gate * cy.tanh() + hy = hy if hr_weight is None else F.linear(hy, hr_weight, None) + + return hy, cy + + +def one_layer_lstm(inp, hidden, params, has_biases, reverse=False): + ih_weight = params[0] + hh_weight = params[1] + ih_bias = params[2] if has_biases else None + hh_bias = params[3] if has_biases else None + hr_weight = ( + params[4] if len(params) == 5 else params[2] if len(params) == 3 else None + ) + + hx = hidden[0].unsqueeze(0) + cx = hidden[1].unsqueeze(0) + + precomputed_input = F.linear(inp, ih_weight, ih_bias) + precomputed_input = precomputed_input.flip(0) if reverse else precomputed_input + step_output = [] + for inp in precomputed_input: + hx, cx = lstm_cell(inp, hx, cx, hh_weight, hh_bias, hr_weight, chunk_dim=2) + step_output.append(hx) + + if reverse: + step_output.reverse() + + out = torch.cat(step_output, 0) + + return out, (hx.squeeze(0), cx.squeeze(0)) + + +def one_layer_lstm_data(inp, hidden, params, has_biases, batch_sizes, reverse=False): + ih_weight = params[0] + hh_weight = params[1] + ih_bias = params[2] if has_biases else None + hh_bias = params[3] if has_biases else None + hr_weight = ( + params[4] if len(params) == 5 else params[2] if len(params) == 3 else None + ) + + step_output = [] + hiddens = [] + + last_batch_size = batch_sizes[-1] if reverse else batch_sizes[0] + split_inp = torch.split(inp, list(batch_sizes)) + if reverse: + split_inp = split_inp[::-1] + + orig_hx = hidden[0] + orig_cx = hidden[1] + hx, cx = ( + orig_hx.narrow(0, 0, last_batch_size), + orig_cx.narrow(0, 0, last_batch_size), + ) + + for inp in split_inp: + i = inp.shape[0] + inp = F.linear(inp, ih_weight, ih_bias) + + # this will only happen when reverse=False, since batch sizes are sorted largest -> smallest + if i < last_batch_size: + hiddens.append( + ( + hx.narrow(0, i, last_batch_size - i), + cx.narrow(0, i, last_batch_size - i), + ) + ) + hx, cx = hx.narrow(0, 0, i), cx.narrow(0, 0, i) + + # this will only happen when reverse=True + if i > last_batch_size: + hx = torch.concat( + (hx, orig_hx.narrow(0, last_batch_size, i - last_batch_size)), 0 + ) + cx = torch.concat( + (cx, orig_cx.narrow(0, last_batch_size, i - last_batch_size)), 0 + ) + + hx, cx = lstm_cell(inp, hx, cx, hh_weight, hh_bias, hr_weight, chunk_dim=1) + last_batch_size = i + step_output.append(hx) + + if reverse: + step_output.reverse() + hidden_out = (hx, cx) + else: + hiddens.append((hx, cx)) + hiddens.reverse() + hidden0, hidden1 = zip(*hiddens) + hidden_out = torch.cat(hidden0, 0), torch.cat(hidden1, 0) + + out = torch.cat(step_output, 0) + return out, hidden_out + + +def select_one_layer_lstm_function(input, hx, params): + r"""Check whether we could use decompose lstm with mkldnn_rnn_layer. + All the below conditions need to be met: + * ``torch._C._get_mkldnn_enabled()`` returns ``True``. + * All the input args are on CPU. + * The dtypes of args are either torch.float or torch.bfloat16. + * Inference. + * ``has_projections`` returns ``False``. + + Args: + * input: the input sequence to LSTM + * hx: a tuple of the input hidden state and cell state ``(h_0, c_0)`` to LSTM + * params: the weight and bias tensors of LSTM + """ + + def use_mkldnn(input, hx, params): + if not torch._C._get_mkldnn_enabled(): + return False + + tensors = [input] + list(hx) + list(chain.from_iterable(params)) + devices = {t.device for t in tensors} + if len(devices) != 1: + return False + + device = devices.pop() + if device != torch.device("cpu"): + return False + # With autocast, possible to have mixed dtype here + dtypes = {t.dtype for t in tensors} + for dtype in dtypes: + if dtype not in [torch.float, torch.bfloat16]: + return False + + if input.requires_grad: + return False + + has_projections = hx[0].size(2) != hx[1].size(2) + if has_projections: + return False + + return True + + # mkldnn_one_layer_lstm does not depend on seq_len while one_layer_lstm + # will expand over the seq_len dim + if use_mkldnn(input, hx, params): + return mkldnn_one_layer_lstm + else: + return one_layer_lstm + + +@register_decomposition(aten.lstm.input) +@aten.lstm.input.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.lstm.input.py_impl(DispatchKey.Autograd) +def lstm_impl( + input, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, +): + if len(hx) != 2: + raise AssertionError(f"lstm expects two hidden states, got {len(hx)}") + params = gather_params(params, has_biases, hx[0].size(2) != hx[1].size(2)) + hidden = list(zip(hx[0], hx[1])) + layer_fn = select_one_layer_lstm_function(input, hx, params) + out, final_hiddens = _rnn_helper( + input, + hidden, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, + layer_fn, + ) + final_hiddens = list(zip(*final_hiddens)) + return out, torch.stack(final_hiddens[0], 0), torch.stack(final_hiddens[1], 0) + + +@register_decomposition(aten.lstm.data) +@aten.lstm.data.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.lstm.data.py_impl(DispatchKey.Autograd) +def lstm_data_impl( + data, + batch_sizes, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, +): + if len(hx) != 2: + raise AssertionError(f"lstm expects two hidden states, got {len(hx)}") + params = gather_params(params, has_biases, hx[0].size(2) != hx[1].size(2)) + hidden = list(zip(hx[0], hx[1])) + out, final_hiddens = _rnn_helper( + data, + hidden, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + False, + partial(one_layer_lstm_data, batch_sizes=batch_sizes), + ) + final_hiddens = list(zip(*final_hiddens)) + return out, torch.stack(final_hiddens[0], 0), torch.stack(final_hiddens[1], 0) + + +def gru_cell(inp, cur_hidden, ih_weight, ih_bias, hh_weight, hh_bias): + chunked_igates = inp.chunk(3, 1) + chunked_hgates = F.linear(cur_hidden, hh_weight, hh_bias).chunk(3, 2) + reset_gate = (chunked_hgates[0] + chunked_igates[0]).sigmoid() + input_gate = (chunked_hgates[1] + chunked_igates[1]).sigmoid() + new_gate = (chunked_igates[2] + (chunked_hgates[2] * reset_gate)).tanh() + return (cur_hidden - new_gate) * input_gate + new_gate + + +def gru_cell_data(inp, cur_hidden, ih_weight, ih_bias, hh_weight, hh_bias): + chunked_igates = F.linear(inp, ih_weight, ih_bias).chunk(3, 1) + chunked_hgates = F.linear(cur_hidden, hh_weight, hh_bias).chunk(3, 1) + reset_gate = (chunked_hgates[0] + chunked_igates[0]).sigmoid() + input_gate = (chunked_hgates[1] + chunked_igates[1]).sigmoid() + new_gate = (chunked_igates[2] + (chunked_hgates[2] * reset_gate)).tanh() + return (cur_hidden - new_gate) * input_gate + new_gate + + +@register_decomposition(aten.gru.data) +@aten.gru.data.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.gru.data.py_impl(DispatchKey.Autograd) +def gru_impl_data( + data, + batch_sizes, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, +): + params = gather_params(params, has_biases, False) + out, final_hiddens = _rnn_helper( + data, + hx.unbind(0), + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + False, + partial(one_layer_rnn_data, batch_sizes=batch_sizes, hidden_fn=gru_cell_data), + ) + return out, torch.stack(final_hiddens, 0) + + +@register_decomposition(aten.gru.input) +@aten.gru.input.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.gru.input.py_impl(DispatchKey.Autograd) +def gru_impl( + input, + hx, + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, +): + params = gather_params(params, has_biases, False) + out, final_hiddens = _rnn_helper( + input, + hx.unbind(0), + params, + has_biases, + num_layers, + dropout, + train, + bidirectional, + batch_first, + partial(one_layer_rnn, hidden_fn=gru_cell), + ) + return out, torch.stack(final_hiddens, 0) + + +@register_decomposition(aten._upsample_bilinear2d_aa.vec) +@aten._upsample_bilinear2d_aa.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_bilinear2d_aa.vec.py_impl(DispatchKey.Autograd) +def upsample_bilinear2d_aa_vec(input, output_size, align_corners, scale_factors): + osize = upsample_compute_output_size(input.size(), output_size, scale_factors) + scale_h = get_scale_value(scale_factors, 0) + scale_w = get_scale_value(scale_factors, 1) + return torch.ops.aten._upsample_bilinear2d_aa( + input, osize, align_corners, scale_h, scale_w + ) + + +@register_decomposition(aten._upsample_bicubic2d_aa.vec) +@aten._upsample_bicubic2d_aa.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_bicubic2d_aa.vec.py_impl(DispatchKey.Autograd) +def upsample_bicubic2d_aa_vec(input, output_size, align_corners, scale_factors): + osize = upsample_compute_output_size(input.size(), output_size, scale_factors) + scale_h = get_scale_value(scale_factors, 0) + scale_w = get_scale_value(scale_factors, 1) + return torch.ops.aten._upsample_bicubic2d_aa( + input, osize, align_corners, scale_h, scale_w + ) + + +@register_decomposition(aten._upsample_lanczos2d_aa.vec) +@aten._upsample_lanczos2d_aa.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten._upsample_lanczos2d_aa.vec.py_impl(DispatchKey.Autograd) +def upsample_lanczos2d_aa_vec(input, output_size, align_corners, scale_factors): + osize = upsample_compute_output_size(input.size(), output_size, scale_factors) + scale_h = get_scale_value(scale_factors, 0) + scale_w = get_scale_value(scale_factors, 1) + return torch.ops.aten._upsample_lanczos2d_aa( + input, osize, align_corners, scale_h, scale_w + ) + + +@register_decomposition(aten.upsample_bilinear2d.vec) +@register_decomposition(aten.upsample_trilinear3d.vec) +@aten.upsample_linear1d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_linear1d.vec.py_impl(DispatchKey.Autograd) +@aten.upsample_bilinear2d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_bilinear2d.vec.py_impl(DispatchKey.Autograd) +@aten.upsample_trilinear3d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_trilinear3d.vec.py_impl(DispatchKey.Autograd) +def _upsample_linear_vec(input, output_size, align_corners, scale_factors): + osize = upsample_compute_output_size(input.size(), output_size, scale_factors) + scales = scale_factors if scale_factors else [None] * len(osize) + return _upsample_linear(input, osize, align_corners, scales) + + +@register_decomposition([aten.upsample_linear1d.default, aten.upsample_linear1d.out]) +@out_wrapper() +def upsample_linear1d( + input: Tensor, + output_size: list[int], + align_corners: bool, + scales_w: float | None = None, +) -> Tensor: + return _upsample_linear(input, output_size, align_corners, [scales_w]) + + +@register_decomposition( + [aten.upsample_bilinear2d.default, aten.upsample_bilinear2d.out] +) +@aten.upsample_bilinear2d.default.py_impl(DispatchKey.Autograd) +@out_wrapper() +def upsample_bilinear2d( + input: Tensor, + output_size: list[int], + align_corners: bool, + scales_h: float | None = None, + scales_w: float | None = None, +) -> Tensor: + return _upsample_linear(input, output_size, align_corners, [scales_h, scales_w]) + + +@register_decomposition( + [aten.upsample_trilinear3d.default, aten.upsample_trilinear3d.out] +) +@out_wrapper() +def upsample_trilinear3d( + input: Tensor, + output_size: list[int], + align_corners: bool, + scales_d: float | None = None, + scales_h: float | None = None, + scales_w: float | None = None, +) -> Tensor: + return _upsample_linear( + input, output_size, align_corners, [scales_d, scales_h, scales_w] + ) + + +def _compute_scale(in_size, out_size, align_corners, scale=None): + if align_corners: + return (in_size - 1.0) / (out_size - 1.0) if out_size > 1 else 0 + else: + return 1.0 / scale if scale is not None and scale > 0 else in_size / out_size + + +def _compute_source_index(scale, dst_index, align_corners): + if align_corners: + return scale * dst_index + else: + return scale * (dst_index + 0.5) - 0.5 + + +def _sum_tensors_uint8( + src: Iterable[Tensor], weights: Iterable[Tensor], weights_precision: Tensor +) -> Tensor: + output = _sum_tensors( + s.to(torch.int32) * c.to(torch.int32) for s, c in zip(src, weights) + ) + (1 << (weights_precision - 1)) + output = output >> weights_precision + return torch.clamp(output, 0, 255).to(torch.uint8) + + +def _compute_weight_precision(weights: TensorSequenceType) -> Tensor: + max_weight = torch.stack(weights).max() + max_weight_precision = 22 + precisions = torch.arange(max_weight_precision, device=max_weight.device) + values = 0.5 + max_weight * (1 << (precisions + 1)) + mask = values >= (1 << 15) + return max_weight_precision - mask.sum() + + +@pw_cast_for_opmath +def _upsample_linear( + input: Tensor, + output_size: list[int], + align_corners: bool, + scales: list[float | None], +) -> Tensor: + # get dimensions of original image + n_channels = input.shape[1] + inp_sizes = input.shape[2:] + n_dims = len(inp_sizes) + + _, dtype = utils.elementwise_dtypes( + input, + type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + ) + + def get_values(inp_size, out_size, scales, nsqueeze): + # First Calculate scaling factor + scale_factor = _compute_scale(inp_size, out_size, align_corners, scales) + # We have to create arange with int64 dtype and use .to in order to avoid + # additional kernels creation in inductor and get a perf slowdown + i = torch.arange(out_size, device=input.device).to(dtype=dtype) + + x_f32 = _compute_source_index(scale_factor, i, align_corners).clamp(min=0.0) + x_f32 = x_f32.reshape(x_f32.shape[0], *[1] * (nsqueeze)) + x = x_f32.to(torch.int64) + xp1 = (x + 1).clamp(max=inp_size - 1) + return x_f32, x, xp1 + + values = [ + get_values(inp_size, out_size, scales, n_dims - 1 - i) + for i, (inp_size, out_size, scales) in enumerate( + zip(inp_sizes, output_size, scales) + ) + ] + xs_f32, xs, xp1s = list(zip(*values)) + + vs = [] + for a in product(*[[0, 1]] * n_dims): + idx = [None, None] + [xs[k] if a[k] == 0 else xp1s[k] for k in range(n_dims)] + v = aten._unsafe_index(input, idx) + v = _maybe_convert_to_dtype(v, dtype) + vs.append(v) + + for i in reversed(range(n_dims)): + xscale = (xs_f32[i] - xs[i]).clamp(0.0, 1.0).to(dtype) + vs = [ + # x1 * (1 - alpha) + x2 * alpha == x1 + (x2 - x1) * alpha + v1 + torch.mul(v2 - v1, xscale) + for v1, v2 in zip(vs[::2], vs[1::2]) + ] + + if len(vs) != 1: + raise AssertionError(f"Expected vs to have exactly 1 element, got {len(vs)}") + result = vs[0] + + # convert output to correct memory format, if necessary + memory_format = utils.suggest_memory_format(input) + + # following "heuristic: only use channels_last path when it's faster than the contiguous path" + if input.device.type == "cuda" and n_channels < 16: + memory_format = torch.contiguous_format + + if not isinstance(result, torch.Tensor): + raise AssertionError( + f"Expected result to be a Tensor, got {type(result).__name__}" + ) + + result = result.contiguous(memory_format=memory_format) + + if not input.is_floating_point(): + result = result.round() + + return result + + +# We should be applying decompositions after all transformations +@register_decomposition(aten.is_same_size.default) +def is_same_size(a: Tensor, b: Tensor) -> bool: + return a.shape == b.shape + + +@register_decomposition([aten._reshape_alias, aten._unsafe_view]) +@out_wrapper() +def _reshape_alias(x, shape, *args): + return aten.view(x, shape) + + +@register_decomposition([aten._unsafe_index]) +def _unsafe_index(x, indices): + return aten.index(x, indices) + + +@register_decomposition([aten._unsafe_index_put]) +def _unsafe_index_put(x, indices, value, accumulate=False): + return aten.index_put(x, indices, value, accumulate) + + +@register_decomposition([aten._unsafe_masked_index]) +def _unsafe_masked_index(x, mask, indices, fill): + for index in indices: + if index is not None: + torch._check( + index.dtype in [torch.long, torch.int], + lambda: "tensors used as indices must be long or int tensors", + ) + + torch._check( + mask.dtype == torch.bool, + lambda: "tensors used as masks must be bool tensors", + ) + + from torch.fx.experimental.symbolic_shapes import guard_or_false + + if guard_or_false(x.numel() == 0): + meta_result = torch._meta_registrations.meta_index_Tensor(x, indices) + return x.new_full(meta_result.shape, fill) + + for i in range(len(indices)): + index = indices[i] + if index is not None: + indices[i] = index.clamp(min=0, max=x.size(i) - 1) + + return aten._unsafe_index(x, indices).masked_fill(~mask, fill) + + +@register_decomposition([aten._unsafe_masked_index_put_accumulate]) +def _unsafe_masked_index_put_accumulate(x, mask, indices, values): + for index in indices: + if index is not None: + torch._check( + index.dtype in [torch.long, torch.int], + lambda: "tensors used as indices must be long or int tensors", + ) + + torch._check( + mask.dtype == torch.bool, + lambda: "tensors used as masks must be bool tensors", + ) + + if x.numel() == 0: + return x.clone() + + for i in range(len(indices)): + index = indices[i] + if index is not None: + indices[i] = index.clamp(min=-x.size(i), max=x.size(i) - 1) + + masked_value = values.masked_fill(~mask, 0) + return aten._unsafe_index_put(x, indices, masked_value, accumulate=True) + + +def _nll_loss_forward( + self: Tensor, + target: Tensor, + weight: Tensor | None, + reduction: int, + ignore_index: int, +) -> tuple[Tensor, Tensor]: + # self can be [N, C] or [C] + # target can be [N] or [] + + n_dims = self.dim() + channel_dim = 1 + if n_dims < 2: + channel_dim = 0 + + if weight is not None: + if n_dims > 1: + shape = [ + 1, + ] * n_dims + shape[channel_dim] = weight.shape[0] + w = weight.view(shape) + else: + w = weight + self = self * w + safe_target = torch.where(target != ignore_index, target, 0) + safe_target_ = safe_target.unsqueeze(channel_dim) + # target can be [N, 1] or [1] + + result = -torch.gather(self, channel_dim, safe_target_).squeeze(channel_dim) + + result = torch.where(target != ignore_index, result, 0) + + if reduction == Reduction.NONE.value and n_dims > 1: + total_weight = self.new_full((), 0.0) + return result, total_weight + + if weight is not None: + # pyrefly: ignore [unbound-name] + w = w.expand(self.shape) + wsum = torch.gather(w, channel_dim, safe_target_).squeeze(channel_dim) + wsum = torch.where(target != ignore_index, wsum, 0) + total_weight = wsum.sum() + else: + total_weight = (target != ignore_index).sum().to(self) + + if reduction == Reduction.SUM.value: + result = result.sum() + elif reduction == Reduction.MEAN.value: + result = result.sum() / total_weight + + return result, total_weight + + +@register_decomposition(aten.nll_loss_forward) +@out_wrapper("output", "total_weight") +def nll_loss_forward( + self: Tensor, + target: Tensor, + weight: Tensor | None, + reduction: int, + ignore_index: int, +) -> tuple[Tensor, Tensor]: + if not (self.dim() > 0 and self.dim() <= 2): + raise AssertionError(f"input tensor should be 1D or 2D, got {self.dim()}D") + if target.dim() > 1: + raise AssertionError( + f"0D or 1D target tensor expected, multi-target not supported, got {target.dim()}D" + ) + + no_batch_dim = self.dim() == 1 and target.dim() == 0 + if not no_batch_dim: + torch._check( + self.shape[0] == target.shape[0], + lambda: f"size mismatch (got input: {self.shape}, target: {target.shape})", + ) + + n_classes = self.shape[-1] + + if weight is not None and not (weight.dim() == 1 and weight.numel() == n_classes): + raise AssertionError( + f"weight tensor should be defined either for all {n_classes} classes or no classes " + f"but got weight tensor of shape: {weight.shape}" + ) + + return _nll_loss_forward(self, target, weight, reduction, ignore_index) + + +@register_decomposition(aten.nll_loss2d_forward) +@out_wrapper("output", "total_weight") +def nll_loss2d_forward( + self: Tensor, + target: Tensor, + weight: Tensor | None, + reduction: int, + ignore_index: int, +) -> tuple[Tensor, Tensor]: + return _nll_loss_forward(self, target, weight, reduction, ignore_index) + + +# These are adapted from aten/src/ATen/native/UpSample.h, which is based on +# https://en.wikipedia.org/wiki/Bicubic_interpolation#Bicubic_convolution_algorithm +def _upsample_cubic_convolution1(x: Tensor, A: float) -> Tensor: + return ((A + 2) * x - (A + 3)) * x * x + 1 + + +def _upsample_cubic_convolution2(x: Tensor, A: float) -> Tensor: + return ((A * x - 5 * A) * x + 8 * A) * x - 4 * A + + +def _upsample_get_cubic_coefficients(t: Tensor) -> TensorSequenceType: + A = -0.75 + + if t.device == torch.device("cpu"): + tt1 = torch.stack([t, 1.0 - t], dim=0) + tt2 = torch.stack([t + 1.0, 2.0 - t], dim=0) + w03 = _upsample_cubic_convolution2(tt2, A) + w12 = _upsample_cubic_convolution1(tt1, A) + w0, w3 = torch.unbind(w03, dim=0) + w1, w2 = torch.unbind(w12, dim=0) + return w0, w1, w2, w3 + else: + return ( + _upsample_cubic_convolution2(t + 1.0, A), + _upsample_cubic_convolution1(t, A), + _upsample_cubic_convolution1(1.0 - t, A), + _upsample_cubic_convolution2(2.0 - t, A), + ) + + +def _upsample_cubic_interp1d(coeffs: TensorSequenceType, ts: Tensor) -> Tensor: + coeffs2 = _upsample_get_cubic_coefficients(ts) + return _sum_tensors(c1 * c2 for (c1, c2) in zip(coeffs, coeffs2)) + + +# Need this instead of just sum() to keep mypy happy +def _sum_tensors(ts: Iterable[Tensor]) -> Tensor: + return reduce(torch.add, ts) + + +def _linspace_from_neg_one( + num_steps: int, align_corners: bool, dtype: torch.dtype, device: torch.device +): + if num_steps <= 1: + return torch.tensor(0, device=device, dtype=dtype) + + a = ((num_steps - 1) / num_steps) if not align_corners else 1 + return torch.linspace(-a, a, steps=num_steps, device=device, dtype=dtype) + + +def _make_base_grid_4d(theta: Tensor, h: int, w: int, align_corners: bool): + dtype = theta.dtype + device = theta.device + + # Using padding and summation generates a single kernel vs using torch.stack where 3 kernels generated + # corresponding to each individual tensor: grid_x, grid_y, grid_one + grid_x = _linspace_from_neg_one(w, align_corners, dtype, device).view(1, w, 1) + grid_y = _linspace_from_neg_one(h, align_corners, dtype, device).view(h, 1, 1) + grid_one = torch.ones((1, 1, 1), dtype=dtype, device=device) + + # this is just a temporary hack and we should use torch.stack here once #104480 is merged + grid_x = torch.nn.functional.pad(grid_x, pad=(0, 2), mode="constant", value=0) + grid_y = torch.nn.functional.pad(grid_y, pad=(1, 1), mode="constant", value=0) + grid_one = torch.nn.functional.pad(grid_one, pad=(2, 0), mode="constant", value=0) + return grid_x + grid_y + grid_one + + +def _make_base_grid_5d(theta: Tensor, d: int, h: int, w: int, align_corners: bool): + dtype = theta.dtype + device = theta.device + + grid_x = _linspace_from_neg_one(w, align_corners, dtype, device).view(1, 1, w, 1) + grid_y = _linspace_from_neg_one(h, align_corners, dtype, device).view(1, h, 1, 1) + grid_z = _linspace_from_neg_one(d, align_corners, dtype, device).view(d, 1, 1, 1) + grid_one = torch.ones((1, 1, 1, 1), dtype=dtype, device=device) + + # this is just a temporary hack and we should use torch.stack here once #104480 is merged + grid_x = torch.nn.functional.pad(grid_x, pad=(0, 3), mode="constant", value=0) + grid_y = torch.nn.functional.pad(grid_y, pad=(1, 2), mode="constant", value=0) + grid_z = torch.nn.functional.pad(grid_z, pad=(2, 1), mode="constant", value=0) + grid_one = torch.nn.functional.pad(grid_one, pad=(3, 0), mode="constant", value=0) + return grid_x + grid_y + grid_z + grid_one + + +def _affine_grid_generator_4d(theta: Tensor, size: list[int], align_corners: bool): + n, _, h, w = size + base_grid = _make_base_grid_4d(theta, h, w, align_corners=align_corners) + # base_grid shape is (h, w, 3) and theta shape is (n, 2, 3) + # We do manually a matrix multiplication which is faster than mm() + # (h * w, 3, 1) * (n, 1, 3, 2) -> (n, h * w, 2) + grid = (base_grid.view(-1, 3, 1) * theta.mT.unsqueeze(1)).sum(-2) + return grid.view(n, h, w, 2) + + +def _affine_grid_generator_5d(theta: Tensor, size: list[int], align_corners: bool): + n, _, d, h, w = size + base_grid = _make_base_grid_5d(theta, d, h, w, align_corners=align_corners) + # base_grid shape is (d, h, w, 4) and theta shape is (n, 3, 4) + # We do manually a matrix multiplication which is faster than mm() + # (d * h * w, 4, 1) * (n, 1, 4, 3) -> (n, h * w, 3) + grid = (base_grid.view(-1, 4, 1) * theta.mT.unsqueeze(1)).sum(-2) + return grid.view(n, d, h, w, 3) + + +@register_decomposition(aten.affine_grid_generator) +@out_wrapper() +@pw_cast_for_opmath +def affine_grid_generator(theta: Tensor, size: list[int], align_corners: bool): + torch._check( + len(size) in (4, 5), + lambda: "affine_grid_generator needs 4d (spatial) or 5d (volumetric) inputs.", + ) + if len(size) == 4: + return _affine_grid_generator_4d(theta, size, align_corners=align_corners) + else: + return _affine_grid_generator_5d(theta, size, align_corners=align_corners) + + +def _grid_sampler_2d( + a: Tensor, + grid: Tensor, + interpolation_mode: int = 0, + padding_mode: int = 0, + align_corners: bool = False, + _expand_grid: bool = True, +) -> Tensor: + # This method is a copy of grid_sampler_2d implementation and introduced with additional arg _expand_grid to + # optionally expand the input grid for performance reasons. + # Experimenting locally it was found that compiled CUDA code is accelerated by ~5x + # and CPU code by ~2x on bicubic mode, if we expand the grid from (N, H, W, 2) into (N, C, H, W, 2) + # However, this leads to a slowdown around ~0.8x on CPU bilinear mode, channels first. + # Thus we apply this hack to not expand the grid for this case. + + torch._check( + interpolation_mode in (0, 1, 2), + lambda: f"Invalid interpolation mode {interpolation_mode}", + ) + torch._check( + padding_mode in (0, 1, 2), lambda: f"Invalid padding mode {padding_mode}" + ) + + def unnormalize(coords: Tensor, size: int) -> Tensor: + # Rescale coordinates from [-1, 1] to: + # [0, size - 1] if align_corners is True + # [-.5, size -.5] if align_corners is False + mul = (size * 0.5 - 0.5) if align_corners else (size * 0.5) + ofs = size * 0.5 - 0.5 + return coords * mul + ofs + + # Reflects coordinates until they fall between low and high (inclusive). + # The bounds are passed as twice their value so that half-integer values + # can be represented as ints. + def reflect_coordinates(coords: Tensor, twice_low: int, twice_high: int) -> Tensor: + if twice_low == twice_high: + return torch.zeros_like(coords) + coords_min = twice_low / 2 + coords_span = (twice_high - twice_low) / 2 + coords2 = (coords - coords_min).abs() + extra = torch.fmod(coords2, coords_span) + flips = (coords2 / coords_span).floor().to(dtype=torch.int8) + return torch.where( + flips & 1 == 0, extra + coords_min, coords_span + coords_min - extra + ) + + def compute_coordinates(coords: Tensor, size: int) -> Tensor: + if padding_mode == 0: # Zero + return coords + elif padding_mode == 1: # Borders + return torch.clamp(coords, 0, size - 1) + else: # padding_mode == 2, Reflection + if align_corners: + coords_reflected = reflect_coordinates(coords, 0, 2 * (size - 1)) + else: + coords_reflected = reflect_coordinates(coords, -1, 2 * size - 1) + return torch.clamp(coords_reflected, 0, size - 1) + + def compute_source_index(coords: Tensor, size: int) -> Tensor: + coords_un = unnormalize(coords, size) + return compute_coordinates(coords_un, size) + + N, C, iH, iW = a.shape + _, oH, oW, two = grid.shape + if two != 2: + raise AssertionError( + f"grid last dimension must be 2 (for x,y coords), got {two}" + ) + + from torch.fx.experimental.symbolic_shapes import guard_or_false, sym_and + + int32_max = torch.iinfo(torch.int32).max + # CUDA/XPU codegen can keep bounded coordinate indices in int32. CPU keeps + # the historical int64 path, and dynamic shapes fall back if we cannot guard. + use_32bit_indices = a.device.type in ("cuda", "xpu") and guard_or_false( + sym_and(iH <= int32_max, iW <= int32_max) + ) + index_dtype = torch.int32 if use_32bit_indices else torch.int64 + + if _expand_grid: + # Let's expand grid to [N, C, oH, oW, 2] + # This allows generating a single triton cuda kernel instead of two kernels. + # Two kernels are due source indices, weights have shape (N, 1, oH, oW), xnumel=N*oH*oW + # and output has shape (N, C, oH, oW), xnumel=N*C*oH*oW + # Expanding grid to (N, C, oH, oW, two) unifies xnumel to N*C*oH*oW + grid = grid.view(N, 1, oH, oW, two).expand(N, C, oH, oW, 2) + + def in_bounds_cond(xs: Tensor, ys: Tensor) -> Tensor: + return torch.logical_and( + 0 <= xs, torch.logical_and(xs < iW, torch.logical_and(0 <= ys, ys < iH)) + ) + + N_idx = torch.arange(N, device=a.device).view(N, 1, 1, 1) + C_idx = torch.arange(C, device=a.device).view(1, C, 1, 1) + + def clip(xs: Tensor, ys: Tensor, ws: Tensor) -> TensorSequenceType: + cond = in_bounds_cond(xs, ys) + # To clip to inside valid coordinates, we map the coordinates + # to (x, y) = (0, 0) and also set the weight to 0 + # We also change the shape of the tensor to the appropriate one for + # broadcasting with N_idx, C_idx for the purposes of advanced indexing + c = C if _expand_grid else 1 + return tuple( + torch.where(cond, t, 0).view(N, c, oH, oW) + for t in (xs.to(dtype=index_dtype), ys.to(dtype=index_dtype), ws) + ) + + def get_summand(ix: Tensor, iy: Tensor, w) -> Tensor: + # Perform clipping, index into input tensor and multiply by weight + idx_x, idx_y, w_ = clip(ix, iy, w) + return a[N_idx, C_idx, idx_y, idx_x] * w_ + + x = grid[..., 0] + y = grid[..., 1] + + if interpolation_mode == 0: # Bilinear + ix = compute_source_index(x, iW) + iy = compute_source_index(y, iH) + + ix_nw, iy_nw = ix.floor(), iy.floor() + ix_ne, iy_ne = ix_nw + 1, iy_nw + ix_sw, iy_sw = ix_nw, iy_nw + 1 + ix_se, iy_se = ix_ne, iy_sw + + w_nw = (ix_se - ix) * (iy_se - iy) + w_ne = (ix - ix_sw) * (iy_sw - iy) + w_sw = (ix_ne - ix) * (iy - iy_ne) + w_se = (ix - ix_nw) * (iy - iy_nw) + + return _sum_tensors( + get_summand(ix, iy, w) + for (ix, iy, w) in ( + (ix_nw, iy_nw, w_nw), + (ix_ne, iy_ne, w_ne), + (ix_sw, iy_sw, w_sw), + (ix_se, iy_se, w_se), + ) + ) + elif interpolation_mode == 1: # Nearest + ix = compute_source_index(x, iW) + iy = compute_source_index(y, iH) + + ix_nearest = ix.round() + iy_nearest = iy.round() + + return get_summand(ix_nearest, iy_nearest, 1) + else: # interpolation_mode == 2, Bicubic + ix = unnormalize(x, iW) + iy = unnormalize(y, iH) + + ix_nw = ix.floor() + iy_nw = iy.floor() + + tx = ix - ix_nw + ty = iy - iy_nw + + if not _expand_grid: + tx = tx.unsqueeze(1) + ty = ty.unsqueeze(1) + + def get_value_bounded(ix: Tensor, iy: Tensor) -> Tensor: + x = compute_coordinates(ix, iW) + y = compute_coordinates(iy, iH) + return get_summand(x, y, 1) + + def get_coeff(ofs: int) -> Tensor: + iy_ofs = iy_nw + (ofs - 1) + cs = ( + get_value_bounded(ix_nw - 1, iy_ofs), + get_value_bounded(ix_nw, iy_ofs), + get_value_bounded(ix_nw + 1, iy_ofs), + get_value_bounded(ix_nw + 2, iy_ofs), + ) + return _upsample_cubic_interp1d(cs, tx) + + coeffs = tuple(get_coeff(ofs) for ofs in range(4)) + return _upsample_cubic_interp1d(coeffs, ty) + + +@register_decomposition(aten.grid_sampler_2d) +@out_wrapper() +@pw_cast_for_opmath +def grid_sampler_2d( + a: Tensor, + grid: Tensor, + interpolation_mode: int = 0, + padding_mode: int = 0, + align_corners: bool = False, +) -> Tensor: + return _grid_sampler_2d( + a, + grid=grid, + interpolation_mode=interpolation_mode, + padding_mode=padding_mode, + align_corners=align_corners, + ) + + +@register_decomposition(aten.mv) +@out_wrapper(exact_dtype=True) +@pw_cast_for_opmath +def mv(self, vec): + torch._check( + self.dim() == 2 and vec.dim() == 1, + lambda: f"matrix @ vector expected, got {self.dim()}, {vec.dim()}", + ) + torch._check( + self.size(1) == vec.size(0), + lambda: f"size mismatch, got input ({self.size(0)}x{self.size(1)}), vec ({vec.size(0)})", + ) + return (self * vec).sum(dim=1) + + +@register_decomposition(aten.binary_cross_entropy_with_logits) +@out_wrapper() +def binary_cross_entropy_with_logits( + self, target, weight=None, pos_weight=None, reduction=Reduction.MEAN.value +): + if pos_weight is not None: + log_weight = (pos_weight - 1) * target + 1 + loss = (1 - target) * self - (log_weight * F.logsigmoid(self)) + else: + loss = (1 - target) * self - F.logsigmoid(self) + + if weight is not None: + loss = loss * weight + + # this is to align the resulted data type with the in-place + # operation in binary_cross_entropy_with_logits of aten/src/ATen/native/Loss.cpp + loss = loss.to(target.dtype) + return apply_loss_reduction(loss, reduction) + + +def should_fold(tensor1: torch.Tensor, tensor2: torch.Tensor, is_out: bool) -> bool: + # For comments of the logic of this function see eager in /native/LinearAlgebra.cpp + + t1, t2 = (tensor1, tensor2) if tensor1.ndim >= tensor2.ndim else (tensor2, tensor1) + + from torch.fx.experimental.symbolic_shapes import guard_or_false + + if not (t1.ndim >= 3 and t2.ndim <= 2): + return False + if t2.requires_grad and not is_out: + return True + if tensor1.ndim == 2: + return False + if guard_or_false(sym_numel(t1) == 0): + return True + + t1_shape = t1.shape + t1_stride = t1.stride() + + # Check the contiguous, we can skip the dim with size of 1 + # as aten: https://github.com/pytorch/pytorch/blob/e201460f8aa1510b4c4686627d57b69756c4b916/aten/src/ATen/TensorGeometry.cpp#L17 + expected_stride = [1] + for size in reversed(t1_shape[1:]): + expected_stride.append(size * expected_stride[-1]) + return all( + guard_or_false(size == 1) or guard_or_false(left == right) + for left, right, size in zip( + t1_stride, list(reversed(expected_stride)), t1_shape + ) + ) + + +@aten.matmul.default.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.matmul.out.py_impl(DispatchKey.CompositeImplicitAutograd) +@out_wrapper(pass_is_out=True) +def matmul(tensor1, tensor2, *, is_out=False): + from torch.fx.experimental.symbolic_shapes import guard_or_false, guard_or_true + + dim_tensor1 = tensor1.dim() + dim_tensor2 = tensor2.dim() + if dim_tensor1 == 0 or dim_tensor2 == 0: + raise AssertionError( + f"matmul does not support 0-dimensional tensors, got dims: {dim_tensor1} and {dim_tensor2}" + ) + if dim_tensor1 == 1 and dim_tensor2 == 1: + return torch.dot(tensor1, tensor2) + elif dim_tensor1 == 2 and dim_tensor2 == 1: + return torch.mv(tensor1, tensor2) + elif dim_tensor1 == 1 and dim_tensor2 == 2: + return torch.squeeze(torch.mm(torch.unsqueeze(tensor1, 0), tensor2), 0) + elif dim_tensor1 == 2 and dim_tensor2 == 2: + return torch.mm(tensor1, tensor2) + elif should_fold(tensor1, tensor2, is_out): + # dim_tensor1 >=3 && (dim_tensor2 == 1 || dim_tensor2 == 2) || + # dim_tensor2 >=3 && (dim_tensor1 == 1 || dim_tensor1 == 2) + # and some condition on the strides is fulfilled + + # optimization: use mm instead of bmm by folding the batch of the larger tensor + # into its leading matrix dimension + transpose = dim_tensor2 > dim_tensor1 + t1 = tensor2.mT if transpose else tensor1 + t2 = ( + tensor2 if not transpose else (tensor1.t() if dim_tensor1 == 2 else tensor1) + ) + # Invariant: t1.dim() >= 3 && (t2.dim() == 1 || t2.dim() == 2) + # and t1 and t2 are matmul-compatible + + # Why not t1.view(-1, sizes_1[-1])? + # If the last dim is 0, then view(-1, 0) won't work because the -1 becomes ambiguous. + # This can happen in e.g. [3, 5, 0] @ [0, 0]. + sizes_1 = t1.shape + output_shape = list(sizes_1[:-1]) + folded_dim1 = reduce(operator.mul, output_shape) + + # Readjust output_shape if we are multiplying by a matrix + t2_is_matrix = t2.dim() == 2 + if t2_is_matrix: + output_shape.append(t2.shape[1]) + + # This will almost always be a view. + # It may not be a view if t2->requires_grad(). See should_fold in aten/ for an explanation + t1_folded = t1.reshape(folded_dim1, sizes_1[-1]) + if t2_is_matrix: + # This copies if we perform a 2D @ 3D and the first tensor requires_grad + # See should_fold native/LinearAlgebra.cpp for why. + output = torch.ops.aten._unsafe_view(t1_folded.mm(t2), output_shape) + return output.mT.contiguous() if transpose else output + else: + return torch.ops.aten._unsafe_view(t1_folded.mv(t2), output_shape) + + elif dim_tensor1 >= 1 and dim_tensor2 >= 1: + # We are multiplying b1 x n x m1 by x2 x m2 x p (where b1 can be a list); + # we track m1 vs m2 separately even though they must match for nicer error messages + n = tensor1.size(-2) if dim_tensor1 > 1 else 1 + m1 = tensor1.size(-1) + batch_tensor1 = tensor1.shape[:-2] + m2 = tensor2.size(-2) if dim_tensor2 > 1 else tensor2.size(-1) + p = tensor2.size(-1) if dim_tensor2 > 1 else 1 + + batch_tensor2: list[int] = [] + # TODO: handling of slice + for i in range(dim_tensor2 - 2): + batch_tensor2.append(tensor2.size(i)) + + # Same optimization for the gradients as that in should_fold + # If we're going to broadcast, we force it to go through the should_fold branch + if ( + dim_tensor1 == 3 + and dim_tensor2 == 3 + and guard_or_true(batch_tensor1[0] != batch_tensor2[0]) + ): + if guard_or_false(batch_tensor1[0] == 1) and tensor1.requires_grad: + return matmul(tensor1.squeeze(0), tensor2) + if guard_or_false(batch_tensor2[0] == 1) and tensor2.requires_grad: + return matmul(tensor1, tensor2.squeeze(0)) + + # expand the batch portion (i.e. cut off matrix dimensions and expand rest) + expand_batch_portion = list( + torch.broadcast_shapes(batch_tensor1, batch_tensor2) + ) + + tensor1_expand_size = expand_batch_portion + [n, m1] + + expand_batch_product = prod(expand_batch_portion) + + # HACK: We need reshape with symint support + tensor1_expanded = tensor1.expand(tensor1_expand_size).reshape( + expand_batch_product, n, m1 + ) + + vector_rhs = dim_tensor2 == 1 + if vector_rhs: + tensor2_expand_size = expand_batch_portion + [m2] + tensor2_expanded = ( + tensor2.expand(tensor2_expand_size) + .reshape(expand_batch_product, m2) + .unsqueeze(2) + ) + else: + tensor2_expand_size = expand_batch_portion + [m2, p] + tensor2_expanded = tensor2.expand(tensor2_expand_size).reshape( + expand_batch_product, m2, p + ) + + output_shape = expand_batch_portion + if dim_tensor1 > 1: + output_shape.append(n) + + if dim_tensor2 > 1: + output_shape.append(p) + + if vector_rhs: + return tensor1_expanded.bmm(tensor2_expanded).squeeze(-1).view(output_shape) + else: + return tensor1_expanded.bmm(tensor2_expanded).view(output_shape) + else: + torch._check(False, lambda: "both arguments to matmul need to be at least 1D") + + +@register_decomposition([aten.upsample_bicubic2d.default, aten.upsample_bicubic2d.out]) +@aten.upsample_bicubic2d.default.py_impl(DispatchKey.Autograd) +@out_wrapper() +@pw_cast_for_opmath +def upsample_bicubic2d_default( + input: Tensor, + output_size: tuple[int, int], + align_corners: bool, + scale_h: float | None = None, + scale_w: float | None = None, +) -> Tensor: + # get dimensions of original image + _, _, in_h, in_w = input.shape + + # Calculate horizontal and vertical scaling factor + h_scale_factor = _compute_scale(in_h, output_size[0], align_corners, scale_h) + w_scale_factor = _compute_scale(in_w, output_size[1], align_corners, scale_w) + + _, dtype = utils.elementwise_dtypes( + input, type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT + ) + + # We have to create arange with int64 dtype and use .to in order to avoid + # additional kernels creation in inductor and get a perf slowdown + i = torch.arange(output_size[0], device=input.device).to(dtype=dtype) + j = torch.arange(output_size[1], device=input.device).to(dtype=dtype) + + x_float = _compute_source_index(w_scale_factor, j, align_corners) + y_float = _compute_source_index(h_scale_factor, i, align_corners) + y_float = y_float.unsqueeze(-1) + + x = x_float.floor() + y = y_float.floor() + + # We should also clamp xscale/yscale + # See guard_index_and_lambda in UpSample.h + yscale = (y_float - y).clamp(0.0, 1.0) + xscale = (x_float - x).clamp(0.0, 1.0) + x = x.to(torch.int64) + y = y.to(torch.int64) + + iys_ofs = (y - 1, y, y + 1, y + 2) + ixs_ofs = (x - 1, x, x + 1, x + 2) + + weights_x = _upsample_get_cubic_coefficients(xscale) + weights_y = _upsample_get_cubic_coefficients(yscale) + + weights_precision_x, weights_precision_y = None, None + if input.dtype == torch.uint8: + weights_precision_x = _compute_weight_precision(weights_x) + weights_precision_y = _compute_weight_precision(weights_y) + + weights_x = [ + (w * (1 << weights_precision_x) + torch.sign(w) * 0.5).to(torch.int16) + for w in weights_x + ] + weights_y = [ + (w * (1 << weights_precision_y) + torch.sign(w) * 0.5).to(torch.int16) + for w in weights_y + ] + + def load_bounded(ys, xs): + y_idx = torch.clamp(ys, 0, in_h - 1) + x_idx = torch.clamp(xs, 0, in_w - 1) + v = aten._unsafe_index(input, [None, None, y_idx, x_idx]) + return v + + def get_x_interp(y): + src_x = tuple(load_bounded(y, x_ofs) for x_ofs in ixs_ofs) + if input.dtype == torch.uint8: + if weights_precision_x is None: + raise AssertionError( + "weights_precision_x must not be None for uint8 input" + ) + return _sum_tensors_uint8(src_x, weights_x, weights_precision_x) + return _sum_tensors(c1 * c2 for (c1, c2) in zip(src_x, weights_x)) + + src_y = tuple(get_x_interp(y_ofs) for y_ofs in iys_ofs) + if input.dtype == torch.uint8: + if weights_precision_y is None: + raise AssertionError("weights_precision_y must not be None for uint8 input") + result = _sum_tensors_uint8(src_y, weights_y, weights_precision_y) + else: + result = _sum_tensors(c1 * c2 for (c1, c2) in zip(src_y, weights_y)) + + # convert output to correct memory format, if necessary + memory_format = utils.suggest_memory_format(input) + result = result.contiguous(memory_format=memory_format) + return result + + +@register_decomposition(aten.upsample_bicubic2d.vec) +@aten.upsample_bicubic2d.vec.py_impl(DispatchKey.CompositeImplicitAutograd) +@aten.upsample_bicubic2d.vec.py_impl(DispatchKey.Autograd) +@out_wrapper() +@pw_cast_for_opmath +def upsample_bicubic2d_vec( + a: Tensor, + output_size: tuple[int, int] | None, + align_corners: bool, + scale_factors: tuple[float, float] | None = None, +) -> Tensor: + torch._check( + bool(output_size) + bool(scale_factors) == 1, + lambda: "Must specify exactly one of output_size and scale_factors.", + ) + if output_size is None: + if scale_factors is None: + raise AssertionError( + "scale_factors must not be None when output_size is None" + ) + output_size = cast( + tuple[int, int], + tuple( + sym_int(sym_float(w) * scale) + for w, scale in zip(a.shape[2:], scale_factors) + ), + ) + scale_h, scale_w = scale_factors if scale_factors else (None, None) + return upsample_bicubic2d_default(a, output_size, align_corners, scale_h, scale_w) + + +@register_decomposition(aten.reflection_pad1d) +@register_decomposition(aten.reflection_pad2d) +@register_decomposition(aten.reflection_pad3d) +@pw_cast_for_opmath +@out_wrapper() +def _reflection_pad(a: Tensor, padding: tuple[int, ...]) -> Tensor: + def idx(left, middle, right): + dim_idx = torch.arange(-left, middle + right, device=a.device) + return middle - 1 - (middle - 1 - dim_idx.abs()).abs() + + return _reflection_or_replication_pad( + a, + padding, + idx, + ) + + +@register_decomposition(aten.replication_pad1d) +@register_decomposition(aten.replication_pad2d) +@register_decomposition(aten.replication_pad3d) +@pw_cast_for_opmath +@out_wrapper() +def _replication_pad(a: Tensor, padding: tuple[int, ...]) -> Tensor: + def idx(left, middle, right): + dim_idx = torch.arange(-left, middle + right, device=a.device) + return torch.clamp(dim_idx, 0, middle - 1) + + return _reflection_or_replication_pad( + a, + padding, + idx, + ) + + +def _reflection_or_replication_pad( + a: Tensor, + padding: tuple[int, ...], + idx_fn: Callable[[int, int, int], Tensor], +) -> Tensor: + dim = len(padding) // 2 + torch._check( + a.dim() in (dim + 1, dim + 2), + lambda: f"reflection_pad{dim}d requires {dim + 1}D or {dim + 2}D input", + ) + inp_shape = a.shape[-dim:] + nc_dim = a.dim() - dim + + padding_left = [padding[2 * (dim - 1 - i)] for i in range(dim)] + padding_right = [padding[2 * (dim - 1 - i) + 1] for i in range(dim)] + + result = a + for i in range(dim): + idx: list[Any] = [None] * result.dim() + idx[i + nc_dim] = idx_fn(padding_left[i], inp_shape[i], padding_right[i]) + result = aten._unsafe_index(result, idx) + + # Convert output to correct memory format, if necessary. + # Use the original input (a), not result, because _unsafe_index can + # produce non-standard strides — so suggest_memory_format(result) may + # not reflect the desired output format. + # + # CPU vs CUDA/XPU/MPS eager behavior differs: + # CPU: allocates output via at::empty_like with suggest_memory_format, + # preserving the input's format (e.g. channels_last). + # CUDA/XPU/MPS: kernel writes to a flat contiguous buffer with linear indexing, + # always producing contiguous output regardless of input format. + if a.device.type in ("cuda", "mps", "xpu"): + memory_format = torch.contiguous_format + else: + memory_format = utils.suggest_memory_format(a) + result = result.contiguous(memory_format=memory_format) + return result + + +@register_decomposition(aten.reflection_pad1d_backward) +@register_decomposition(aten.reflection_pad2d_backward) +@register_decomposition(aten.reflection_pad3d_backward) +@out_wrapper("grad_input") +def _reflection_pad_backward(grad_output, x, padding): + dim = len(padding) // 2 + + dhw = [h - 1 for h in x.shape[-dim:]] + + padding_left = [padding[2 * (dim - 1 - i)] for i in range(dim)] + padding_right = [padding[2 * (dim - 1 - i) + 1] for i in range(dim)] + + indices = [] + for i in range(x.ndim): + view_shape = [1] * x.ndim + view_shape[i] = -1 + indices.append(torch.arange(x.shape[i], device=x.device).view(view_shape)) + + b = indices[:-dim] + xyz = indices[-dim:] + + def index_range_condition(index_range): + i, lb, ub = index_range + return torch.logical_and(i >= lb, i <= ub) + + # Areas after reflection: + # + # top-left | top | top-right + # ----------------------------------------- + # left | center | right + # ----------------------------------------- + # bottom-left | bottom | bottom-right + # + # The center area is the original matrix. Other areas are reflections. + + center = [xyz[i] + padding_left[i] for i in range(dim)] + left_reflect = [padding_left[i] - xyz[i] for i in range(dim)] + right_reflect = [2 * dhw[i] + padding_left[i] - xyz[i] for i in range(dim)] + + # Accumulate gradients from different areas + # If some of the padding is negative, center load is not always valid + range_c = [ + (center[i], 0, dhw[i] + padding_left[i] + padding_right[i]) for i in range(dim) + ] + cond = functools.reduce( + aten.logical_and, [index_range_condition(range_c[i]) for i in range(dim)] + ) + grad = aten._unsafe_masked_index(grad_output, cond, b + center, 0.0) + + def accumulate(grad, out, index_ranges): + # If the upper bound is less than the lower bound, we can get rid of one accumulation. + # This happens when the padding size is zero. + for i in range(dim): + upper_less_than_lower = index_ranges[i][2] < index_ranges[i][1] + if isinstance(upper_less_than_lower, bool) and upper_less_than_lower: + return grad + + cond = functools.reduce( + aten.logical_and, + [index_range_condition(index_range) for index_range in index_ranges], + ) + g = aten._unsafe_masked_index(grad_output, cond, b + out, 0.0) + return grad + g + + for area in itertools.product(*[[-1, 0, 1] for _ in range(dim)]): + if area == tuple([0] * dim): + # center, this is already done. + continue + + outs = [] + index_ranges = [] + + for i in range(dim): + if area[i] == 0: + out = center[i] + index_range = range_c[i] + elif area[i] == -1: + out = left_reflect[i] + index_range = (xyz[i], 1, padding_left[i]) + elif area[i] == 1: + out = right_reflect[i] + index_range = (xyz[i], dhw[i] - padding_right[i], dhw[i] - 1) + + outs.append(out) # type: ignore[possibly-undefined] + index_ranges.append(index_range) # type: ignore[possibly-undefined] + + grad = accumulate(grad, outs, index_ranges) + + return grad + + +@register_decomposition(aten.aminmax) +@out_wrapper("min", "max", exact_dtype=True) +def aminmax(self, *, dim=None, keepdim=False): + # pyrefly: ignore [bad-argument-type] + amin = torch.amin(self, dim=dim, keepdim=keepdim) + # pyrefly: ignore [bad-argument-type] + amax = torch.amax(self, dim=dim, keepdim=keepdim) + return amin, amax + + +@register_decomposition(aten.nansum) +@out_wrapper() +def nansum(self, dim=None, keepdim=False, *, dtype=None): + return aten.sum(torch.where(torch.isnan(self), 0, self), dim, keepdim, dtype=dtype) + + +@register_decomposition([aten.arange.default, aten.arange.out]) +@out_wrapper() +def arange_default( + end: NumberType, + *, + dtype: torch.dtype | None = None, + layout: torch.layout = torch.strided, + device: torch.device | None = None, + pin_memory: bool = False, +): + return aten.arange.start_step( + 0, end, 1, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +@register_decomposition([aten.arange.start]) +def arange_start( + start: NumberType, + end: NumberType, + *, + dtype: torch.dtype | None = None, + layout: torch.layout = torch.strided, + device: torch.device | None = None, + pin_memory: bool = False, +): + return aten.arange.start_step( + start, end, 1, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +@register_decomposition(out_dtype) +def out_dtype_decomp(*args, **kwargs): + from torch._higher_order_ops.out_dtype import out_dtype_dense + + return out_dtype_dense(*args, **kwargs) + + +@register_decomposition(aten.multi_margin_loss) +@aten.multi_margin_loss.default.py_impl(DispatchKey.Autograd) +@out_wrapper() +def multi_margin_loss( + input: Tensor, + target: Tensor, + p: NumberType = 1, + margin: NumberType = 1, + weight: Tensor | None = None, + reduction: int = Reduction.MEAN.value, +) -> Tensor: + input = torch.atleast_2d(input) + target = torch.atleast_1d(target) + nframe = input.shape[0] + dim = input.shape[1] + torch._check(p == 1 or p == 2, lambda: "only p == 1 and p == 2 supported") + torch._check( + input.ndim == 2 and dim != 0, + lambda: f"Expected non-empty vector or matrix with optional 0-dim batch size, but got: {input.shape}", + ) + torch._check( + target.ndim == 1 and target.numel() == nframe, + lambda: f"inconsistent target size, expected {nframe} but got {target.shape}", + ) + if weight is not None: + weight = torch.atleast_1d(weight) + torch._check( + weight.ndim == 1 and weight.numel() == dim, # type: ignore[union-attr] + lambda: f"inconsistent weight size, expected {dim} but got {weight.shape}", # type: ignore[union-attr] + ) + # Keep 1D target for weight indexing + target_1d = target + target = target.unsqueeze(1) + u = torch.gather(input, dim=1, index=target) + z = margin - u + input + z = z.clamp_min(0) + z = z if p == 1 else z * z + if weight is not None: + # Use 1D indexing to avoid issues with advanced indexing in inductor + z = z * weight[target_1d].unsqueeze(1) + idx = torch.arange(dim, device=input.device) + z = torch.where(idx != target, z, 0) + if reduction == Reduction.MEAN.value: + return z.mean() + elif reduction == Reduction.SUM.value: + return z.sum() / z.shape[1] + else: + return z.mean(dim=1) + + +@register_decomposition(aten.multilabel_margin_loss_forward) +@aten.multilabel_margin_loss_forward.default.py_impl(DispatchKey.Autograd) +@out_wrapper("output", "is_target") +def multilabel_margin_loss_forward( + input: Tensor, + target: Tensor, + reduction: int, +) -> tuple[Tensor, Tensor]: + orig_input_shape = input.shape + orig_target_shape = target.shape + input = torch.atleast_2d(input) + target = torch.atleast_2d(target) + dim = input.shape[1] + torch._check( + len(orig_input_shape) <= 2 and dim != 0, + lambda: f"Expected non-empty vector or matrix with optional 0-dim batch size, but got: {orig_input_shape}", + ) + torch._check( + len(orig_target_shape) <= 2 and orig_target_shape == orig_input_shape, + lambda: f"inconsistent target size: {orig_target_shape} for input of size: {orig_input_shape}", + ) + # ignores labels after the first -1, detects when -1 is not present + idx = torch.arange(dim, device=target.device) + is_end = target == -1 + end_idx = torch.amin(torch.where(is_end, idx, dim), dim=-1, keepdim=True) + # target indices + target_mask = idx < end_idx + # masks target to be able to use gather, which doesn't allow -1 + tidx0 = torch.where(target_mask, target, 0) + u = torch.gather(input, dim=-1, index=tidx0) + # is_target + tidx1 = torch.where(target_mask, target, -1) + is_target = torch.any(idx == tidx1.unsqueeze(dim=-1), dim=1) + # loss + z = 1.0 - u.T.unsqueeze(dim=-1) + input + z = z.clamp_min(0) + z = z / dim + # masks loss + z = torch.where(is_target, 0, z) + # drops contributions from padded target slots (positions at/after the first -1) + z = torch.where(target_mask.T.unsqueeze(dim=-1), z, 0) + # reduction + if reduction == Reduction.MEAN.value: + z = z.sum(dim=(0, -1)).mean() + elif reduction == Reduction.SUM.value: + z = z.sum() + else: + z = z.sum(dim=(0, -1)) + # result + is_target = is_target.to(input.dtype).reshape(orig_target_shape) + return z, is_target + + +# scaled_dot_product_attention used to be decomposed in pre-autograd, given that +# it calls _scaled_dot_product_attention_math and +# _scaled_dot_product_attention_math only has a CompositeImplicitAutograd +# kernel. As a result it's decomposed into ops with finer granularity. +# However recent PRs (#103826 #105131 #115913) added new logic in +# scaled_dot_product_attention and now it calls +# _scaled_dot_product_flash_attention_for_cpu in export path. This results +# in _scaled_dot_product_flash_attention_for_cpu showing up in export result. +# This decomposition ensures scaled_dot_product_attention is still decomposed +# the same way as before, i.e., going through +# _scaled_dot_product_attention_math. Notice that this decomp rule should be +# excluded by inductor. +@register_decomposition(aten._scaled_dot_product_flash_attention_for_cpu.default) +def scaled_dot_product_flash_attention_for_cpu( + query: Tensor, + key: Tensor, + value: Tensor, + dropout_p: float = 0.0, + is_causal: bool = False, + *, + attn_mask: Tensor | None = None, + scale: float | None = None, +) -> tuple[Tensor, Tensor]: + torch._check( + torch.is_floating_point(query), + lambda: f"query must be FP32, FP64, BF16, FP16 but got {query.dtype}", + ) + torch._check( + query.dim() == 4 and key.dim() == 4 and value.dim() == 4, + lambda: f"q, k, v must be a 4 dimensional tensor, got {query.dim()}, {key.dim()}, {value.dim()}", + ) + torch._check( + dropout_p == 0.0, lambda: f"dropout probability must be zero, got {dropout_p}" + ) + torch._check( + query.shape[3] == value.shape[3] and key.shape[3] == value.shape[3], + lambda: "q, k, v should have the same head size", + ) + + output, attn = aten._scaled_dot_product_attention_math.default( + query, + key, + value, + attn_mask=attn_mask, + dropout_p=dropout_p, + is_causal=is_causal, + dropout_mask=None, + scale=scale, + enable_gqa=query.size(1) != key.size(1), + ) + # Why this change? + # In pre-dispatch export scaled_dot_product_attention is executed via + # * flash_attention. + # flash_attention allocates output tensor as (N, H, L, E) (see PR #134656) + # assume x: [N, H, L, E] is the output sdpa + # In MHA code, this output is then permuted via (2, 0, 1, 3) to get + # (L, N, H, E) dim tensor + # x = x.permute(2, 0, 1, 3).contiguous() and the viewed via + # x = x.view(L * N, H * E) + # During pre autograd dispatch call to contiguous is not traced because + # flash_attention output after the x.permute is already contiguous + # on which the view is valid + # However, during 2nd stage export, post-dispatch, we run _match variant + # instead of flash* to get the decomposition. _match variant returns + # x: [N, H, L, E] applying x.permute(2, 0, 1, 3) returns + # x: [L, N, H, E] and without converting this to contiguous tensor + # subsequent view is not valid and the export fails + # solution is to maintain the return tensor view from the decomp to be + # exactly same as *flash* variant. + + # Really the invariant you want to maintain is: + # pre-dispatch op-output and its decomposed representation must + # return tensor with same view and dims + output = ( + output.permute(2, 0, 1, 3) + .contiguous(memory_format=torch.contiguous_format) + .permute(1, 2, 0, 3) + ) + return output, attn + + +def register_inplace(aten_op, outplace_op): + @register_decomposition(aten_op) + def inplace_op(*args, **kwargs): + out = outplace_op(*args, **kwargs) + return args[0].copy_(out) + + return inplace_op + + +@register_decomposition([aten.baddbmm]) +@out_wrapper(exact_dtype=True) +@pw_cast_for_opmath +def baddbmm(self, batch1, batch2, beta=1, alpha=1): + if not self.is_floating_point() and not self.is_complex(): + beta = int(beta) + alpha = int(alpha) + result = torch.bmm(batch1, batch2) + if not isinstance(alpha, numbers.Number) or alpha != 1: + result = result * alpha + if beta == 0: + return result + if not isinstance(beta, numbers.Number) or beta != 1: + self = self * beta + return self + result + + +@register_decomposition(aten.floor_divide) +@out_wrapper() +def floor_divide(self, other): + return torch.div(self, other, rounding_mode="floor") + + +@register_decomposition(aten.sym_numel) +def sym_numel(t): + return functools.reduce(operator.mul, t.shape, 1) + + +@register_decomposition([aten.sum.default, aten.sum.out]) +def sum_default( + self: Tensor, + *, + dtype: torch.dtype | None = None, + out: Tensor | None = None, +) -> Tensor: + if out is None: + return aten.sum.dim_IntList(self, [], dtype=dtype) + else: + return aten.sum.IntList_out(self, [], dtype=dtype, out=out) + + +@register_decomposition([aten.squeeze.default, aten.squeeze.dim]) +def squeeze_default(self: Tensor, dim: int | None = None): + # handle a scalar directly + if not isinstance(self, torch.Tensor): + return self + # perform squeeze + if dim is None: + return aten.squeeze.dims(self, list(range(self.dim()))) + else: + return aten.squeeze.dims(self, [dim]) + + +@register_decomposition(torch.ops.aten._weight_norm_interface) +def _weight_norm_interface(v, g, dim=0): + # https://github.com/pytorch/pytorch/blob/852f8526c52190125446adc9a6ecbcc28fb66182/aten/src/ATen/native/WeightNorm.cpp#L58 + keep_dim = tuple(i for i in range(len(v.shape)) if i != dim) + # align with cuda behavior, keep norm in 'float' when g is 'bfloat16' + norm_dtype = torch.float if g.dtype == torch.bfloat16 else None + norm = v.norm(2, keep_dim, keepdim=True, dtype=norm_dtype) + return v * (g / norm.to(g.dtype)), norm + + +@register_decomposition(aten.isin) +@out_wrapper() +def isin(elements, test_elements, *, assume_unique=False, invert=False): + # handle when either elements or test_elements are Scalars (they can't both be) + if not isinstance(elements, torch.Tensor): + elements = torch.scalar_tensor(elements, device=test_elements.device) + if not isinstance(test_elements, torch.Tensor): + if invert: + return torch.ne(elements, test_elements) + else: + return torch.eq(elements, test_elements) + + from torch.fx.experimental.symbolic_shapes import guard_or_false + + if guard_or_false(test_elements.numel() < 10.0 * pow(elements.numel(), 0.145)): + return isin_default(elements, test_elements, invert=invert) + else: + return isin_sorting( + elements, test_elements, assume_unique=assume_unique, invert=invert + ) + + +@register_decomposition(aten.bernoulli.default) +def bernoulli( + self: torch.Tensor, + *, + generator: torch.Generator | None = None, +) -> torch.Tensor: + if generator is None: + raw_p = torch.rand(self.size(), dtype=torch.float32, device=self.device) + else: + raw_p = torch.rand( + self.size(), + generator=generator, + dtype=torch.float32, + device=self.device, + ) + p = (raw_p < self).to(self.dtype) + return p + + +def isin_default(elements, test_elements, *, invert=False): + if elements.numel() == 0: + return torch.empty_like(elements, dtype=torch.bool) + if test_elements.ndim == 0: + res = elements == test_elements + return ~res if invert else res + expanded_elem_shape = elements.shape + (1,) * test_elements.ndim + x = elements.view(expanded_elem_shape) + dim = tuple(range(-1, -test_elements.ndim - 1, -1)) + res = (x == test_elements).any(dim=dim) + return ~res if invert else res + + +def isin_sorting(elements, test_elements, *, assume_unique=False, invert=False): + elements_flat = elements.flatten() + test_elements_flat = test_elements.flatten() + if assume_unique: + # This is the same as the aten implementation. For + # assume_unique=False, we cannot use unique() here, so we use a + # version with searchsorted instead. + all_elements = torch.cat([elements_flat, test_elements_flat]) + sorted_elements, sorted_order = torch.sort(all_elements, stable=True) + + duplicate_mask = sorted_elements[1:] == sorted_elements[:-1] + duplicate_mask = torch.constant_pad_nd(duplicate_mask, [0, 1], False) + + if invert: + duplicate_mask = duplicate_mask.logical_not() + + mask = torch.empty_like(duplicate_mask) + mask = mask.index_copy(0, sorted_order, duplicate_mask) + + return mask[0 : elements.numel()].reshape(elements.shape) + else: + sorted_test_elements, _ = torch.sort(test_elements_flat) + idx = torch.searchsorted(sorted_test_elements, elements_flat) + test_idx = torch.where(idx < sorted_test_elements.numel(), idx, 0) + cmp = sorted_test_elements[test_idx] == elements_flat + cmp = cmp.logical_not() if invert else cmp + return cmp.reshape(elements.shape) + + +@register_decomposition(aten.take) +@out_wrapper() +def take(self, index): + flattened = self.reshape(-1) + return flattened[index] + + +@register_decomposition(aten.resize_as) +def resize_as(self, other, memory_format=None): + if memory_format is None: + memory_format = torch.contiguous_format + if memory_format == torch.preserve_format: + memory_format = suggest_memory_format(other) + return aten.resize(self, other.shape, memory_format=memory_format) + + +@register_decomposition(aten.max_pool2d_with_indices_backward) +def max_pool2d_with_indices_backward( + grad_output: Tensor, + self: Tensor, + kernel_size, + stride, + padding, + dilation, + ceil_mode: bool, + indices: Tensor, +): + """ + Decomposition of max_pool2d_with_indices_backward using scatter_add. + + This replaces the native implementation with a high-level decomposition + that uses scatter_add for gradient accumulation. The scatter-based approach + provides automatic optimization opportunities for Inductor and handles all + pooling configurations without requiring specialized fallback paths. + + Algorithm: + For each output gradient position, use the corresponding index from the + forward pass to scatter the gradient to the input position. When multiple + output positions select the same input position as max, scatter_add + automatically accumulates their gradients. + + Complexity: O(B * C * H_out * W_out) + Independent of kernel size, unlike traditional O(B * C * H_in * W_in * K²) + approaches that iterate over input positions and kernel windows. + + Known Limitations: + - FP16/BF16: Uses FP32 accumulation internally to preserve precision when + many gradients accumulate to the same position (overlapping pooling windows). + This adds slight overhead but ensures numerical stability. + - Deterministic mode: Falls back to native implementation to ensure + consistent results across runs + + Args: + grad_output: Gradient w.r.t. pooling output [B, C, H_out, W_out] + self: Original input tensor (for shape) [B, C, H_in, W_in] + kernel_size: Pooling kernel size + stride: Pooling stride + padding: Pooling padding + dilation: Pooling dilation + ceil_mode: Whether to use ceil for output size calculation + indices: Indices from forward pass (per-channel linear positions) + + Returns: + Gradient w.r.t. input [B, C, H_in, W_in] + """ + # Use native kernel in deterministic mode + if torch.are_deterministic_algorithms_enabled(): + return NotImplemented + + if grad_output.is_xpu: + return NotImplemented + + # MPS: Use native kernel. scatter_add has correctness issues on macOS 14 + # (#163327) and numerical differences on macOS 15+. + if grad_output.device.type == "mps": + return NotImplemented + + # Get spatial dimensions + in_height = self.size(-2) + in_width = self.size(-1) + out_height = grad_output.size(-2) + out_width = grad_output.size(-1) + + # Handle both 3D (C, H, W) and 4D (B, C, H, W) cases by treating 3D as 4D + is_batched = self.dim() == 4 + if not is_batched: + self = self.unsqueeze(0) + grad_output = grad_output.unsqueeze(0) + indices = indices.unsqueeze(0) + + batch_size = self.size(0) + channels = self.size(1) + + # For FP16/BF16, use FP32 accumulation to avoid precision loss + # This is critical when many gradients accumulate to the same position + # (overlapping pooling windows with large kernels or stride < kernel_size) + use_fp32_accum = grad_output.dtype in (torch.float16, torch.bfloat16) + accum_dtype = torch.float32 if use_fp32_accum else grad_output.dtype + + # Create grad_input with correct accumulation dtype from the start + grad_input_flat = torch.zeros( + batch_size * channels, + in_height * in_width, + dtype=accum_dtype, + device=grad_output.device, + ) + + # Reshape grad_output and indices to (B*C, H_out*W_out) + grad_output_flat = grad_output.reshape( + batch_size * channels, out_height * out_width + ) + indices_flat = indices.reshape(batch_size * channels, out_height * out_width) + + # Convert grad_output to accumulation dtype if needed + if use_fp32_accum: + grad_output_flat = grad_output_flat.to(torch.float32) + + # Scatter gradients to input positions + grad_input_flat = grad_input_flat.scatter_add(1, indices_flat, grad_output_flat) + + # Reshape back to original input shape + grad_input = grad_input_flat.reshape(batch_size, channels, in_height, in_width) + + # Convert back to original dtype if we used FP32 accumulation + if use_fp32_accum: + grad_input = grad_input.to(grad_output.dtype) + + # Preserve memory format from input (channels_last vs channels_first) + memory_format = utils.suggest_memory_format(self) + grad_input = grad_input.contiguous(memory_format=memory_format) + + # Remove batch dimension for 3D case + if not is_batched: + grad_input = grad_input.squeeze(0) + + return grad_input + + +@register_decomposition([aten.hann_window.default, aten.hann_window.out]) +@out_wrapper() +def hann_window( + window_length: int, + *, + dtype: torch.dtype | None = None, + layout: torch.layout | None = None, + device: torch.device | None = None, + pin_memory: bool | None = None, +) -> Tensor: + """hann_window(window_length, *, dtype=None, layout=None, device=None, pin_memory=False) -> Tensor + + Returns a Hann window of size :attr:`window_length` with ``periodic=True``. + + Equivalent to :func:`torch.hann_window` with ``periodic=True``. + + Args: + window_length (int): the size of returned window. + + Keyword args: + dtype (:class:`torch.dtype`, optional): desired dtype. Default: global default. + layout (:class:`torch.layout`, optional): desired layout. Default: ``torch.strided``. + device (:class:`torch.device`, optional): desired device. Default: current device. + pin_memory (bool, optional): if ``True``, pins the returned tensor. Default: ``False``. + """ + return aten.hann_window.periodic( + window_length, + True, + dtype=dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + ) + + +@register_decomposition([aten.hann_window.periodic, aten.hann_window.periodic_out]) +@out_wrapper() +def hann_window_periodic( + window_length: int, + periodic: bool = True, + *, + dtype: torch.dtype | None = None, + layout: torch.layout | None = None, + device: torch.device | None = None, + pin_memory: bool | None = None, +) -> Tensor: + r"""hann_window(window_length, periodic=True, *, dtype=None, layout=None, device=None, pin_memory=False) -> Tensor + + Returns a Hann window of size :attr:`window_length`. + + .. math:: + w[n] = 0.5 - 0.5 \cos\!\left(\frac{2\pi n}{N-1}\right) + + where :math:`N` is ``window_length + 1`` when ``periodic=True`` (for spectral analysis), + or ``window_length`` when ``periodic=False`` (symmetric window). + + Low-precision dtypes (``bfloat16``, ``float16``) are computed in ``float32`` then cast. + + Args: + window_length (int): the size of returned window. + periodic (bool, optional): if ``True``, returns a periodic window for use with STFT. + Default: ``True``. + + Keyword args: + dtype (:class:`torch.dtype`, optional): desired dtype. Default: global default. + layout (:class:`torch.layout`, optional): desired layout. Default: ``torch.strided``. + device (:class:`torch.device`, optional): desired device. Default: current device. + pin_memory (bool, optional): if ``True``, pins the returned tensor. Default: ``False``. + """ + dtype = dtype if dtype is not None else torch.get_default_dtype() + if window_length == 0: + return torch.empty( + (0,), dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + if window_length == 1: + return torch.ones( + (1,), dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + compute_dtype = utils.get_computation_dtype(dtype) + n = window_length + 1 if periodic else window_length + t = torch.arange( + n, + dtype=compute_dtype, + layout=layout, + device=device, + pin_memory=pin_memory, + ) + t = t * (2.0 * torch.pi / (n - 1)) + t = torch.cos(t) + t = t * -0.5 + 0.5 + window = t.narrow(0, 0, window_length) if periodic else t + return window.to(dtype) + + +register_inplace(aten.addbmm_, aten.addbmm) +register_inplace(aten.addmm_, aten.addmm) +register_inplace(aten.addmv_, aten.addmv) +register_inplace(aten.baddbmm_, aten.baddbmm) +register_inplace(aten.fill_, aten.fill) +register_inplace(aten.gelu_, aten.gelu) +register_inplace(aten.hardswish_, aten.hardswish) +register_inplace(aten.hardtanh_, aten.hardtanh) +register_inplace(aten.hardsigmoid_, aten.hardsigmoid) +register_inplace(aten.__iand__, aten.__and__) +register_inplace(aten.__ilshift__, aten.__lshift__) +register_inplace(aten.index_put_, aten.index_put) +register_inplace(aten.index_reduce_, aten.index_reduce) +register_inplace(aten.__ior__, aten.__or__) +register_inplace(aten.__irshift__, aten.__rshift__) +register_inplace(aten.__ixor__, aten.__xor__) +register_inplace(aten.ldexp_, aten.ldexp) +register_inplace(aten.leaky_relu_, aten.leaky_relu) +register_inplace(aten.logit_, aten.logit) +register_inplace(aten.relu_, aten.relu) +register_inplace(aten.renorm_, aten.renorm) +register_inplace(aten.round_, aten.round) +register_inplace(aten.scatter_, aten.scatter) +register_inplace(aten.scatter_add_, aten.scatter_add) +register_inplace(aten.scatter_reduce_, aten.scatter_reduce) +register_inplace(aten.silu_, aten.silu) + + +@aten.one_hot.default.py_impl(DispatchKey.CompositeImplicitAutograd) +def one_hot(self: Tensor, num_classes: int = -1) -> Tensor: + if num_classes == -1: + num_classes = int(self.max().item()) + 1 + # _assert_async is side-effectful and won't be DCE'd + aten._assert_async.msg( + torch.all(self >= 0), + "one_hot: Class values must be non-negative.", + ) + aten._assert_async.msg( + torch.all(self < num_classes), + "one_hot: Class values must be smaller than num_classes.", + ) + return ( + self.unsqueeze(-1) + == torch.arange(num_classes, dtype=self.dtype, device=self.device) + ).to(torch.int64) diff --git a/.venv/lib/python3.12/site-packages/torch/_decomp/decompositions_for_jvp.py b/.venv/lib/python3.12/site-packages/torch/_decomp/decompositions_for_jvp.py new file mode 100644 index 0000000000000000000000000000000000000000..2d3d4ecb77e074ebe680cdcd099a1f700960a5b6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_decomp/decompositions_for_jvp.py @@ -0,0 +1,345 @@ +# mypy: allow-untyped-decorators +# mypy: allow-untyped-defs +import inspect +from collections.abc import Callable + +import torch +import torch._decomp +from torch import Tensor +from torch._prims_common.wrappers import _maybe_remove_out_wrapper + + +decomposition_table = torch._decomp.decomposition_table +decomposition_table_for_jvp: dict[torch._ops.OperatorBase, Callable] = {} +register_decomposition = torch._decomp.register_decomposition +aten = torch.ops.aten + +# NOTE: [forward-mode AD decompositions mechanism] +# +# The mechanism is in VariableType, +# IF any inputs have forward grad +# AND there is no forward AD formula implemented +# AND the functions are actually differentiable +# run the decomposition +# See run_jit_decomposition_with_args_for_jvp +# We currently use python decompositions that we torchscript. +# +# Note that we would be building the backward graph at the decomposed level +# too, but that is OK, because we would've errored out otherwise anyway. +# +# TODO: The mechanism we are using to register decompositions doesn't +# seem to be exclusively used for jvp. So open question here is whether +# torch/csrc/jit/runtime/decomposition_registry.cpp is being used for other things. +# If that is the case, we may go down the decomposition path unexpectedly +# (and possibly produce an unintelligible error) vs erroring out earlier and +# printing that the forward AD formula is not implemented. +# +# The solution to this may be to have an explicit whitelist to control when +# to enable the decomposition. + + +def maybe_register_decomposition(op): + def decorator(f): + try: + return register_decomposition(op)(f) + except Exception: + return f + + return decorator + + +# Functions where we need a special decomposition for jvp but there's another version that +# should be used more generally (ex. for jvp we need to recompute the mean and variance for +# the backwards of a normalization function. Without jvp, it should use the saved value) +decomposition_table_for_jvp = {} + + +def register_decomposition_for_jvp(fn): + return register_decomposition(fn, registry=decomposition_table_for_jvp) + + +def _register_jit_decomposition_for_jvp(decomp, use_python=False): + if decomp in decomposition_table_for_jvp: + decomposition_table_used = decomposition_table_for_jvp + elif decomp in decomposition_table: + decomposition_table_used = decomposition_table + else: + raise RuntimeError(f"could not find decomposition for {decomp}") + decomp_fn = decomposition_table_used[decomp] + + # `out_wrapper` extends a decompositions signature with + # an `out` parameter. However jit will use the unwrapped function's + # signature instead so we need to unwrap here to prevent an error + decomp_fn = _maybe_remove_out_wrapper(decomp_fn) + + if use_python: + decomp_fn = torch.jit.ignore(decomp_fn) + sig = inspect.signature(decomp_fn) + + # Create a string wrapping the function from the signature + # example output: + # def wrapped_decomp(x: torch.Tensor, y: int, z: int): + # return decomp_fn(x, y, z) + # Thanks copilot! + def get_function_def(sig): + param_def = [f"{param_str}" for param_str in sig.parameters.values()] + param_use = [f"{param_str}" for param_str in sig.parameters] + + return f"def wrapped_decomp({', '.join(param_def)}):\n return decomp_fn({', '.join(param_use)})\n" + + f_str = get_function_def(sig) + graph = torch.jit.CompilationUnit(f_str).wrapped_decomp.graph + else: + graph = torch.jit.script(decomp_fn).graph + torch.jit._register_decomposition(decomp, graph) + + +# The only decompositions here are temporary or hacks for the purposes of jvp + + +# TODO: do these also belong here? +@maybe_register_decomposition(aten.trace.default) +def trace(self: Tensor) -> Tensor: + return torch.sum(torch.diag(self)) + + +@maybe_register_decomposition(aten.log_sigmoid_forward.default) +def log_sigmoid_forward(self: Tensor) -> tuple[Tensor, Tensor]: + min = torch.minimum(self.new_zeros(()), self) + z = torch.exp(-torch.abs(self)) + if self.is_cuda or self.is_xpu: + buffer = self.new_zeros((0,)) + else: + buffer = z + return min - torch.log1p(z), buffer + + +def recompute_mean_var( + input: Tensor, rstd: Tensor, inner_dim_indices: list[int], keepdim: bool +): + # for most norm decompositions, it will be the same as the core version except for here. + # We recompute the mean and variance so that they track gradients through input + + var, mean = torch.var_mean( + input, dim=inner_dim_indices, correction=0, keepdim=keepdim + ) + eps = torch.pow(1 / rstd, 2) - var # this makes me so sad inside + eps = eps.detach() + rstd = torch.rsqrt(var + eps) + return mean, rstd + + +@register_decomposition_for_jvp(aten.native_layer_norm_backward) +def native_layer_norm_backward( + grad_out: Tensor, + input: Tensor, + normalized_shape: list[int], + mean: Tensor, + rstd: Tensor, + weight: Tensor | None, + bias: Tensor | None, + output_mask: list[bool], +) -> tuple[Tensor | None, Tensor | None, Tensor | None]: + input_shape = input.shape + input_ndim = input.dim() + + axis = input_ndim - len(normalized_shape) + inner_dims = input_shape[axis:] + outer_dims = input_shape[:axis] + inner_dim_indices = list(range(axis, input_ndim)) + outer_dim_indices = list(range(axis)) + + N = 1 + for i in inner_dims: + N *= i + M = 1 + for i in outer_dims: + M *= i + if M <= 0 or N <= 0: + return ( + input.new_zeros(input_shape), + input.new_zeros(input_shape[axis:]), + input.new_zeros(input_shape[axis:]), + ) + + mean_, rstd_ = recompute_mean_var(input, rstd, inner_dim_indices, keepdim=True) + + x_hat = (input - mean_) * rstd_ + if weight is not None: + grad_x_hat = grad_out * weight + else: + grad_x_hat = grad_out + a = grad_x_hat * N + b = torch.sum(grad_x_hat, inner_dim_indices, True) + c1 = torch.mul(grad_x_hat, x_hat) + c2 = torch.sum(c1, inner_dim_indices, True) + c3 = torch.mul(x_hat, c2) + inner = a - b - c3 + + if output_mask[0]: + d_input: Tensor | None = (rstd_ / N) * inner + else: + d_input = torch.zeros_like(input) # should be None but doesn't work with vjp + + if output_mask[1] and weight is not None: + if len(outer_dim_indices) > 0: + d_weight: Tensor | None = torch.sum( + grad_out * x_hat, outer_dim_indices, False + ) + else: + d_weight = grad_out * x_hat + elif weight is not None: + d_weight = torch.zeros_like(weight) # should be None but doesn't work with vjp + else: + d_weight = torch.zeros(()) # should be None but doesn't work with vjp + + if output_mask[2] and bias is not None: + if len(outer_dim_indices) > 0: + d_bias: Tensor | None = torch.sum(grad_out, outer_dim_indices, False) + else: + d_bias = grad_out.clone() + elif bias is not None: + d_bias = torch.zeros_like(bias) # should be None but doesn't work with vjp + else: + d_bias = torch.zeros(()) # should be None but doesn't work with vjp + + return (d_input, d_weight, d_bias) + + +def prod(x: list[int]): + r = 1 + for i in x: + r *= i + return r + + +@register_decomposition_for_jvp(aten.native_batch_norm_backward) +def native_batch_norm_backward( + grad_out: Tensor, + input: Tensor, + weight: Tensor | None, + running_mean: Tensor | None, + running_var: Tensor | None, + save_mean: Tensor | None, + save_invstd: Tensor | None, + train: bool, + eps: float, + output_mask: list[bool], +) -> tuple[Tensor, Tensor | None, Tensor | None]: + input_shape = input.shape + input_rank = input.dim() + if input_rank < 2: + raise AssertionError(f"rank of the input must be at least 2, got {input_rank}") + + axis = 1 + num_features = prod(input_shape) / input_shape[axis] # type: ignore[arg-type] + mean = save_mean + invstd = save_invstd + if train: + if save_mean is None or save_invstd is None: + raise AssertionError( + "when train=True, save_mean and save_invstd are required" + ) + + reduciton_dims = [0] + list(range(2, input.dim())) + if invstd is None: + raise AssertionError("invstd must not be None for typing") + mean, invstd = recompute_mean_var(input, invstd, reduciton_dims, keepdim=False) + else: + if running_mean is None or running_var is None: + raise AssertionError( + "running_mean and running_var must not be None when train=False" + ) + mean = running_mean + invstd = torch.rsqrt(running_var + eps) + + if invstd is None or mean is None: + raise AssertionError( + f"invstd and mean must not be None, got invstd={invstd}, mean={mean}" + ) + + broadcast_mask = [1] * input_rank + broadcast_mask[axis] = input_shape[axis] + + reduction_axes: list[int] = [] + for i in range(input_rank): + if i != axis: + reduction_axes.append(i) + + mean = torch.reshape(mean, broadcast_mask) + norm = 1.0 / num_features + grad_output_sum = torch.sum(grad_out, reduction_axes) + dot_p = torch.sum(grad_out * (input - mean), reduction_axes) + + grad_mean = torch.reshape(grad_output_sum * norm, broadcast_mask) + proj_scale = torch.reshape(torch.mul(dot_p * norm, invstd * invstd), broadcast_mask) + + if weight is None: + grad_scale = torch.reshape(invstd, broadcast_mask) * 1.0 + else: + grad_scale = torch.reshape(invstd * weight, broadcast_mask) + + if train: + proj = (input - mean) * proj_scale + grad_input = ((grad_out - proj) - grad_mean) * grad_scale + else: + grad_input = grad_out * grad_scale + + if output_mask[1]: + grad_weight = dot_p * invstd + elif weight is not None: + grad_weight = torch.zeros_like( + weight + ) # should be None but doesn't work with vjp + else: + grad_weight = torch.zeros(()) # should be None but doesn't work with vjp + + if output_mask[2]: + grad_bias = grad_output_sum + else: + grad_bias = torch.zeros_like( + grad_output_sum + ) # should be None but doesn't work with vjp + + return (grad_input, grad_weight, grad_bias) + + +@register_decomposition_for_jvp(aten.batch_norm_backward) +def batch_norm_backward( + grad_out: Tensor, + input: Tensor, + weight: Tensor, + running_mean: Tensor | None, + running_var: Tensor | None, + save_mean: Tensor | None, + save_var: Tensor | None, + update: bool, + eps: float, + output_mask: list[bool], + reserve: Tensor, +) -> tuple[Tensor, Tensor | None, Tensor | None]: + return native_batch_norm_backward( + grad_out, + input, + weight, + running_mean, + running_var, + save_mean, + save_var, + update, + eps, + output_mask, + ) + + +_register_jit_decomposition_for_jvp(torch.ops.aten.trace.default, use_python=True) +_register_jit_decomposition_for_jvp(torch.ops.aten.nll_loss_backward.default) +_register_jit_decomposition_for_jvp(torch.ops.aten.nll_loss2d_backward.default) +_register_jit_decomposition_for_jvp(torch.ops.aten._log_softmax_backward_data.default) +_register_jit_decomposition_for_jvp(torch.ops.aten._softmax_backward_data.default) +_register_jit_decomposition_for_jvp(torch.ops.aten.log_sigmoid_forward.default) +_register_jit_decomposition_for_jvp(torch.ops.aten.native_layer_norm_backward.default) +_register_jit_decomposition_for_jvp(torch.ops.aten.native_batch_norm_backward.default) +_register_jit_decomposition_for_jvp(torch.ops.aten.cudnn_batch_norm_backward.default) +_register_jit_decomposition_for_jvp(torch.ops.aten.batch_norm_backward.default) +_register_jit_decomposition_for_jvp(torch.ops.aten.miopen_batch_norm_backward.default) diff --git a/.venv/lib/python3.12/site-packages/torch/_decomp/decompositions_for_rng.py b/.venv/lib/python3.12/site-packages/torch/_decomp/decompositions_for_rng.py new file mode 100644 index 0000000000000000000000000000000000000000..bd2f189c8071a54d30ca3d366c818cd95ccecf9a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_decomp/decompositions_for_rng.py @@ -0,0 +1,273 @@ +# mypy: allow-untyped-decorators +# mypy: allow-untyped-defs +import functools +from collections import defaultdict +from collections.abc import Callable + +import torch +import torch._decomp as decomp +from torch._decomp import get_decompositions +from torch._ops import OpOverload + + +aten = torch.ops.aten + +rng_decompositions: dict[str, dict[OpOverload, Callable]] = defaultdict(dict) + + +def register_rng_decomposition(aten_op): + return decomp.register_decomposition(aten_op, rng_decompositions) + + +def throw_on_non_cuda(device): + raise RuntimeError( + f"You are trying to functionalize a {device.type} RNG operator but {device.type} does not " + f"use Philox/counter-based RNG. Therefore, functionalizing a {device.type} RNG operator is " + "not supported. We are discussing the possibility of a Philox-based RNG implementation for CPU." + ) + + +# TODO - We have to register many more distributions here, and also higher level +# ops like dropout which have fused implementation and can hide the rand inside. +@register_rng_decomposition(aten.rand) +def rand(shape, dtype=None, layout=torch.strided, device=None, pin_memory=False): + if device and device.type != "cuda": + throw_on_non_cuda(device) + seed, offset = PhiloxStateTracker.get_state_as_tuple() + dtype = dtype or torch.float32 + out, offset_jump = torch.ops.rngprims.philox_rand( + shape, seed, offset, None, device, dtype + ) + PhiloxStateTracker.advance_offset(offset_jump) + return out + + +@register_rng_decomposition(aten.rand_like) +def rand_like( + x: torch.Tensor, + dtype=None, + layout=None, + device=None, + pin_memory=False, + memory_format=torch.preserve_format, +): + device = device or x.device + if device.type != "cuda": + throw_on_non_cuda(device) + dtype = dtype or x.dtype + seed, offset = PhiloxStateTracker.get_state_as_tuple() + out, offset_jump = torch.ops.rngprims.philox_rand( + x.shape, seed, offset, None, device, dtype + ) + PhiloxStateTracker.advance_offset(offset_jump) + return out + + +class PhiloxState: + """ + Represents a PhiloxRngState - (seed, offset) where offset = base_offset + + relative_offset. seed and base_offset basically point to the rng state just + before tracing starts. relative offset tracks the totally consumed offset at + trace time. + """ + + def __init__(self) -> None: + self.reset() + + def reset(self): + self.seed = torch.tensor(()) + self.base_offset = torch.tensor(()) + self.relative_offset = 0 + self.offset_advanced_at_least_once = False + + def validate_state(self): + if self.seed.numel() == 0 or self.base_offset.numel() == 0: + raise AssertionError( + f"seed and base_offset must not be empty, got " + f"seed.numel()={self.seed.numel()}, base_offset.numel()={self.base_offset.numel()}" + ) + + def advance_offset(self, consumed_offset): + self.offset_advanced_at_least_once = True + self.relative_offset = self.relative_offset + consumed_offset + + def set_state(self, seed, base_offset, relative_offset=0): + self.seed = seed + self.base_offset = base_offset + self.relative_offset = relative_offset + + def get_state_as_tuple(self): + self.validate_state() + return (self.seed, self.base_offset + self.relative_offset) + + def get_state_as_tensor(self): + # Only needed because we override get_rng_state. + self.validate_state() + return torch.stack([self.seed, self.base_offset + self.relative_offset]) + + def set_state_from_tensor(self, state): + # Only needed because we override set_rng_state. + self.seed, self.base_offset = torch.unbind(state) + self.relative_offset = 0 + + +class PhiloxStateTracker: + """ + Singleton class to track the philox rng state during AOT Autograd tracing. + For each aot tracing instance, AOT Autograd resets this tracker and keeps + track of both forward and backward offsets. At runtime, we only care about + the total consumed forward and backward offsets. For dynamic shapes, these + offsets are a function of input shapes. Therefore, the AOT generated graphs + have additional outputs that compute total consumed forward and backward + offsets. + """ + + running_state: PhiloxState + fwd_state: PhiloxState + bwd_state: PhiloxState + + def __enter__(self): + PhiloxStateTracker.reset() + return self + + def __exit__(self, exc_type, exc_cal, exc_tb): + PhiloxStateTracker.reset() + + @classmethod + def reset(cls): + cls.running_state = PhiloxState() + cls.fwd_state = PhiloxState() + cls.bwd_state = PhiloxState() + + @classmethod + def mark_beginning_of_forward(cls): + # Tells the tracker to use fwd_state as the running state + cls.running_state = cls.fwd_state + + @classmethod + def mark_beginning_of_backward(cls): + # Tells the tracker to use bwd_state as the running state + cls.running_state = cls.bwd_state + + @classmethod + def record_state(cls, seed, offset, mode): + # Records the seed and offset tensors. These tensors are used to invoke + # the philox_rand functional primitives. + if mode == "forward": + cls.fwd_state.set_state(seed, offset) + cls.mark_beginning_of_forward() + else: + if mode != "backward": + raise AssertionError(f"mode must be 'backward', got {mode}") + cls.bwd_state.set_state(seed, offset) + + @classmethod + def get_state_as_tensor(cls): + # The only reason this exists is because we override get_rng_state and + # set_rng_state during tracing. get_rng_state expects a tensor output, + # so return (seed, offset) tuple upset other parts of the program like + # ctx.saved_tensors. + + # A bad consequence is that if user saves and restores rng state, we + # have little bit of ugliness in the generated code, where we first + # concat the (seed, offset) to create a tensor for get_rng_state, and + # then split it back to get (seed, offset) tuple in set_rng_state. + + # TODO: Investigate if there is a better way to wrap the tuple in a + # false Tensor object, and then desugar it later on. + return cls.running_state.get_state_as_tensor() + + @classmethod + def get_state_as_tuple(cls): + return cls.running_state.get_state_as_tuple() + + @classmethod + def set_state_from_tensor(cls, x): + # This is only needed because we override set_rng_state. Look at the + # comment in get_state_from_tensor method. + cls.running_state.set_state_from_tensor(x) + + @classmethod + def advance_offset(cls, consumed_offset): + cls.running_state.advance_offset(consumed_offset) + + @classmethod + def get_current_relative_offset(cls): + return cls.running_state.relative_offset + + @staticmethod + def multiple_of_4(offset): + # torch cuda rng state offset must be a multiple of 4. For inductor, as + # we sum up all the numel, the result might not be a multiple of 4. This + # method achieves that. + return (offset + 3) // 4 * 4 + + @classmethod + def get_updated_fwd_offset(cls): + # Short circuit if no rand ops were observed + if not cls.fwd_state.offset_advanced_at_least_once: + return cls.fwd_state.base_offset + return cls.multiple_of_4( + cls.fwd_state.base_offset + cls.fwd_state.relative_offset + ) + + @classmethod + def get_updated_bwd_offset(cls): + # Short circuit if no rand ops were observed + if not cls.bwd_state.offset_advanced_at_least_once: + return cls.bwd_state.base_offset + return cls.multiple_of_4( + cls.bwd_state.base_offset + cls.bwd_state.relative_offset + ) + + +# Adding more decompositions which eventually use rand_like inside decomps. +# Adding these in rng_decompositions ensures the functionalization of rand_like +# ops used in these decomps. The list is copied from inductor codebase, which +# uses it for similar purpose. +# +# Caution - These decomps do not have same accuracy as that of eager. However, +# we can't just disable them with a config flag like fallback_random, because +# for functionalization of rng ops, we have to decompose these ops. +extra_random_decomps = get_decompositions( + [ + aten.cauchy, + aten.cauchy_, + aten.exponential, + aten.exponential_, + aten.geometric, + aten.geometric_, + aten.native_dropout, + aten.normal, + aten.normal_, + aten.normal_functional, + aten.log_normal, + aten.log_normal_, + aten.rrelu_with_noise, + aten.rrelu_with_noise_, + aten.uniform, + aten.uniform_, + ] +) +register_extra_random_decomp = functools.partial( + decomp.register_decomposition, registry=extra_random_decomps +) + + +@register_extra_random_decomp([aten.bernoulli_]) +def bernoulli_(self, p=0.5): + if self.device == torch.device("cpu"): + return NotImplemented + return self.copy_(torch.rand_like(self, dtype=torch.float32) < p) + + +@register_extra_random_decomp([aten.bernoulli.p]) +def bernoulli_p(self, p=0.5, *, generator=None): + if self.device == torch.device("cpu"): + return NotImplemented + if generator is not None: + raise AssertionError(f"generator must be None, got {generator}") + return torch.rand_like(self, dtype=torch.float32) < p + + +rng_decompositions.update(extra_random_decomps) # type: ignore[arg-type] diff --git a/.venv/lib/python3.12/site-packages/torch/_dispatch/__init__.py b/.venv/lib/python3.12/site-packages/torch/_dispatch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_dispatch/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dispatch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0df6213e3d2324fa6cede1a74750055e16dd9f5b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dispatch/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dispatch/__pycache__/python.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dispatch/__pycache__/python.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49df8b5482667c6f53c22876df52fb51fdb2ef06 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dispatch/__pycache__/python.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dispatch/python.py b/.venv/lib/python3.12/site-packages/torch/_dispatch/python.py new file mode 100644 index 0000000000000000000000000000000000000000..ef6d1d652bf2da3b966945c01770b7743e366a7f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dispatch/python.py @@ -0,0 +1,204 @@ +import itertools +import unittest.mock +from collections.abc import Callable, Generator, Iterator +from contextlib import contextmanager +from typing import TypeVar +from typing_extensions import ParamSpec + +import torch +import torch._C +import torch._ops +import torch.utils._python_dispatch +import torch.utils._pytree as pytree +from torch._C import DispatchKey + + +__all__ = ["enable_python_dispatcher", "no_python_dispatcher", "enable_pre_dispatch"] + +no_python_dispatcher = torch._C._DisablePythonDispatcher +enable_python_dispatcher = torch._C._EnablePythonDispatcher +enable_pre_dispatch = torch._C._EnablePreDispatch + +CROSSREF_FUNCTIONALIZE = False + +_P = ParamSpec("_P") +_T = TypeVar("_T") +_R = TypeVar("_R") + + +def all_py_loaded_overloads() -> Iterator[torch._ops.OpOverload]: + """ + Warning: the set of overloads this will report is very subtle. It is precisely + the set of torch.ops functions that have actually been accessed from Python + (e.g., we actually called torch.ops.aten.blah at some point. This is DIFFERENT + from the set of registered operators, which will in general be a larger set, + as this would include all operators which we ran C++ static initializers or + Python operator registration on. This does not eagerly populate the list on + torch.ops.aten; this list is lazy! + + In other words, this is good for traversing over everything that has an + OpOverload object allocated in Python. We use it for cache invalidation, but + don't rely on this list being complete. + + Note that even if we did report all C++ registered overloads, this isn't guaranteed + to be complete either, as a subsequent lazy load of a library which triggers more + registrations could add more things to the set. + """ + for ns in torch.ops: + packets = getattr(torch.ops, ns) + for op_name in packets: + packet = getattr(packets, op_name) + for overload in packet: + yield getattr(packet, overload) + + +@contextmanager +def suspend_functionalization() -> Generator[None, None, None]: + f_tls = torch._C._dispatch_tls_is_dispatch_key_included( + torch._C.DispatchKey.Functionalize + ) + f_rv = torch._C._functionalization_reapply_views_tls() + if f_tls: + torch._disable_functionalization() + try: + yield + finally: + if f_tls: + torch._enable_functionalization(reapply_views=f_rv) + + +def check_tensor_metadata_matches( + nv: torch.Tensor, rv: torch.Tensor, desc: Callable[[], str] +) -> None: + if not callable(desc): + raise AssertionError(f"desc must be callable, got {type(desc)}") + if nv.size() != rv.size(): + raise AssertionError(f"{desc()}: sizes {nv.size()} != {rv.size()}") + if nv.dtype != rv.dtype: + raise AssertionError(f"{desc()}: dtype {nv.dtype} != {rv.dtype}") + same_strides, idx = torch._prims_common.check_significant_strides( + nv, rv, only_cuda=False + ) + if not same_strides: + raise AssertionError( + f"{desc()}: strides {nv.stride()} != {rv.stride()} (mismatch at index {idx})" + ) + + +def check_metadata_matches(n: object, r: object, desc: Callable[[], str]) -> None: + if not callable(desc): + raise AssertionError(f"desc must be callable, got {type(desc)}") + n_vals, _n_spec = pytree.tree_flatten(n) + r_vals, _r_spec = pytree.tree_flatten(r) + # TODO: test the specs match; empirically sometimes we have a tuple + # on one side and a list on the other + if len(n_vals) != len(r_vals): + raise AssertionError(f"{len(n_vals)} != {len(r_vals)}") + for i, nv, rv in zip(range(len(n_vals)), n_vals, r_vals): + if not isinstance(rv, torch.Tensor): + continue + check_tensor_metadata_matches(nv, rv, lambda: f"{desc()} output {i}") + + +class Lit: + def __init__(self, s: str) -> None: + self.s = s + + def __repr__(self) -> str: + return self.s + + +def _fmt(a: object) -> object: + if isinstance(a, torch.Tensor): + return Lit( + f"torch.empty_strided({tuple(a.size())}, {a.stride()}, dtype={a.dtype})" + ) + else: + return a + + +def make_crossref_functionalize( + op: torch._ops.OpOverload[_P, _T], final_key: DispatchKey +) -> Callable[_P, _T] | DispatchKey: + from torch._subclasses.fake_tensor import FakeTensorMode + + # This case is pretty weird, suppress it for now + if op is torch.ops.aten.lift_fresh.default: + return final_key + + def handler(*args: _P.args, **kwargs: _P.kwargs) -> _T: + fake_mode = FakeTensorMode() + + def fakeify_defun(t: _R) -> _R | torch._subclasses.fake_tensor.FakeTensor: + if isinstance(t, torch.Tensor): + if torch._is_functional_tensor(t): + r = torch._from_functional_tensor(t) + # NB: This assumes that the inner tensor sizes/strides match + # the outer tensor sizes/strides. This doesn't necessarily have to + # be the case, see discussion at + # https://github.com/pytorch/pytorch/pull/87610/files/401ddeda1d769bedc88a12de332c7357b60e51a4#r1007264456 + if t.size() != r.size(): + raise AssertionError(f"size mismatch: {t.size()} != {r.size()}") + if t.stride() != r.stride(): + raise AssertionError( + f"stride mismatch: {t.stride()} != {r.stride()}" + ) + else: + r = t + # TODO: suppress guards + return fake_mode.from_tensor(r) + return t + + def maybe_detach(t: _R) -> _R | torch.Tensor: + if isinstance(t, torch.Tensor): + return t.detach() + else: + return t + + # TODO: This probably does the wrong thing if you're running other + # substantive modes with the normal op outside here + with ( + torch.utils._python_dispatch._disable_current_modes(), + suspend_functionalization(), + ): + f_args, f_kwargs = pytree.tree_map(fakeify_defun, (args, kwargs)) + orig_f_args, orig_f_kwargs = pytree.tree_map( + maybe_detach, (f_args, f_kwargs) + ) + with fake_mode: + f_r = op(*f_args, **f_kwargs) # pyrefly: ignore [invalid-param-spec] + r = op._op_dk(final_key, *args, **kwargs) + + def desc() -> str: + fmt_args = ", ".join( + itertools.chain( + (repr(pytree.tree_map(_fmt, a)) for a in orig_f_args), + ( + f"{k}={pytree.tree_map(_fmt, v)}" + for k, v in orig_f_kwargs.items() + ), + ) + ) + return f"{op}({fmt_args})" + + check_metadata_matches(f_r, r, desc) + return r + + return handler + + +# NB: enabling this is slow, don't do it in a hot loop. This is purely +# for debugging purposes. +@contextmanager +def enable_crossref_functionalize() -> Generator[None, None, None]: + for op in all_py_loaded_overloads(): + op._uncache_dispatch(torch._C.DispatchKey.Functionalize) + try: + with ( + enable_python_dispatcher(), + unittest.mock.patch("torch._dispatch.python.CROSSREF_FUNCTIONALIZE", True), + ): + yield + finally: + for op in all_py_loaded_overloads(): + op._uncache_dispatch(torch._C.DispatchKey.Functionalize) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__init__.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b78f3361a3334fc694689c5416d60091c99c9e83 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/__init__.py @@ -0,0 +1,248 @@ +""" +TorchDynamo is a Python-level JIT compiler designed to make unmodified PyTorch programs faster. +TorchDynamo hooks into the frame evaluation API in CPython (PEP 523) to dynamically modify Python +bytecode right before it is executed. It rewrites Python bytecode in order to extract sequences of +PyTorch operations into an FX Graph which is then just-in-time compiled with a customizable backend. +It creates this FX Graph through bytecode analysis and is designed to mix Python execution with +compiled backends to get the best of both worlds: usability and performance. This allows it to +seamlessly optimize PyTorch programs, including those using modern Python features. +""" + +import torch + +from . import ( + aot_compile, + bytecode_debugger, + config, + convert_frame, + eval_frame, + functional_export, + resume_execution, +) +from .backends.registry import list_backends, lookup_backend, register_backend +from .callback import callback_handler, on_compile_end, on_compile_start +from .code_context import code_context +from .convert_frame import replay +from .decorators import ( + allow_c_slot, + allow_in_graph, + assume_constant_result, + disable, + disable_nested_graph_breaks, + disallow_in_graph, + dont_skip_tracing, + error_on_graph_break, + forbid_in_graph, + graph_break, + is_dynamo_disable_recursive, + mark_dynamic, + mark_static, + mark_static_address, + maybe_mark_dynamic, + nonstrict_trace, + override_cudagraphs, + override_optimization_hint, + patch_dynamo_config, + run, + set_stance, + skip_frame, + step_unsupported, + substitute_in_graph, +) +from .eval_frame import ( + _reset_guarded_backend_cache, + explain, + export, + is_dynamo_supported, + is_inductor_supported, + optimize, + optimize_assert, + OptimizedModule, + reset_code, +) + +# pyrefly: ignore [deprecated] +from .external_utils import is_compiling +from .mutation_guard import GenerationTracker +from .pgo import reset_code_state +from .symbolic_convert import TensorifyState +from .utils import ( + graph_break_reasons, + guard_failures, + orig_code_map, + register_hook_for_recompile_user_context, + reset_frame_count, + reset_recompile_user_contexts, +) + + +# Register polyfill functions +from .polyfills import loader as _ # usort: skip + + +__all__ = [ + "allow_c_slot", + "allow_in_graph", + "assume_constant_result", + "bytecode_debugger", + "config", + "disable", + "disable_nested_graph_breaks", + "disallow_in_graph", + "dont_skip_tracing", + "export", + "explain", + "forbid_in_graph", + "graph_break", + "is_compiling", + "is_dynamo_disable_recursive", + "list_backends", + "lookup_backend", + "mark_dynamic", + "maybe_mark_dynamic", + "mark_static", + "mark_static_address", + "nonstrict_trace", + "override_optimization_hint", + "optimize", + "optimize_assert", + "OptimizedModule", + "patch_dynamo_config", + "register_backend", + "replay", + "reset", + "reset_recompile_user_contexts", + "run", + "override_cudagraphs", + "error_on_graph_break", + "set_recursion_limit", + "set_stance", + "skip_frame", + "step_unsupported", + "substitute_in_graph", +] + +# allowlist this for weights_only load of NJTs +torch.serialization.add_safe_globals([torch._dynamo.decorators._DimRange]) + +if torch.manual_seed is torch.random.manual_seed: + import torch.jit._builtins + + # Wrap manual_seed with the disable decorator. + # Can't do it at its implementation due to dependency issues. + torch.manual_seed = torch._disable_dynamo(torch.manual_seed) + # Add the new manual_seed to the builtin registry. + torch.jit._builtins._register_builtin(torch.manual_seed, "aten::manual_seed") + + +def reset() -> None: + """ + Clear all compile caches and restore initial state. This function is intended + to reset Dynamo's state *as if* you had started a fresh process invocation, which + makes it good for testing scenarios where you want to behave as if you started + a new process. It does NOT affect any file system caches. + + NB: this does NOT reset logging state. Don't use this to test logging + initialization/reinitialization. + """ + # TODO: https://github.com/pytorch/pytorch/issues/139200 + import logging + + log = logging.getLogger(__name__) + log.info("torch._dynamo.reset") + with convert_frame.compile_lock: + reset_code_caches() + convert_frame.input_codes.clear() + reset_code_state() + convert_frame.output_codes.clear() + orig_code_map.clear() + guard_failures.clear() + graph_break_reasons.clear() + resume_execution.ContinueExecutionCache.cache.clear() + _reset_guarded_backend_cache() + reset_frame_count() + torch._dynamo.compiled_autograd.reset() + convert_frame.FRAME_COUNTER = 0 + convert_frame.FRAME_COMPILE_COUNTER.clear() + callback_handler.clear() + GenerationTracker.clear() + TensorifyState.clear() + torch._dynamo.utils.warn_once_cache.clear() + torch._C._autograd._saved_tensors_hooks_set_tracing(False) + + # Reset cudagraph trees unconditionally since they are global state + # not tied to a specific backend instance + from torch._higher_order_ops.triton_kernel_wrap import kernel_side_table + from torch._higher_order_ops.wrap import inductor_code_side_table + + kernel_side_table.reset_table() + inductor_code_side_table.reset_table() + + # The fake tensor dispatch cache is process-global (shared across + # FakeTensorMode instances), so it survives into later compiles. That + # is normally fine since it caches pure metadata propagation, but if a + # meta kernel errantly mutates input metadata (a bug, e.g. #191283), + # the mutation happens only on cache miss: a compile that failed cold + # can then "succeed" when retried in the same process, which test + # harness reruns misclassify as flakiness. + from torch._subclasses.fake_tensor import FakeTensorMode + + FakeTensorMode.cache_clear() + + if torch.cuda.is_initialized(): + from torch._inductor.cudagraph_trees import reset_cudagraph_trees + + reset_cudagraph_trees() + + +def reset_code_caches() -> None: + """ + Clears in-memory code cache, which is what stores compiled products. This + resets less state than :func:`reset` and is mostly only used for testing + purposes. + """ + # TODO: https://github.com/pytorch/pytorch/issues/139200 + import logging + + log = logging.getLogger(__name__) + log.info("torch._dynamo.reset_code_caches") + """Clear compile caches that are keyed by code objects""" + with convert_frame.compile_lock: + reset_code_state() + for weak_code in ( + convert_frame.input_codes.seen + convert_frame.output_codes.seen + ): + code = weak_code() + if code: + reset_code(code) + code_context.clear() + + +def get_recursion_limit() -> int: + """ + Returns the internal dynamo recursion limit set by `torch._dynamo.set_recursion_limit`. + + Returns -1 if no c recursion limit has been set. + """ + return torch._C._dynamo.eval_frame.get_c_recursion_limit() + + +def set_recursion_limit(limit: int) -> None: + """ + Sets an internal dynamo recursion limit. The limit must be >= 1, or -1 to reset + to the default (unset) state. + + This is possibly needed in Python 3.12-3.13 since there is a separate C recursion limit + that is not visible at the Python level. If you are getting RecursionErrors during + Dynamo compilation and `sys.setrecursionlimit()` doesn't help, this function may alleviate + the issue. + + NOTE: this function does NOT call `sys.setrecursionlimit()` - the user is expected to manually + call this if required. This is because the 2 recursion limits are not sync'd up - e.g. in + Python 3.12, functions can be inline-evaluated, which apparently doesn't use up the C stack. + + WARNING: increasing the recursion limit to an arbitrary large value may cause segfaults + due to stack overflows! You can try also try to manually increase the stack size, e.g. + with `$ ulimit -s ...` + """ + torch._C._dynamo.eval_frame.set_c_recursion_limit(limit) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e4c83eb6bf1909e3fdb3fdaf325d2e3ef4382ca Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/_trace_wrapped_higher_order_op.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/_trace_wrapped_higher_order_op.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ac6b9d6b54e42103de84df6c529169d5f71f579 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/_trace_wrapped_higher_order_op.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/aot_compile.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/aot_compile.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74571126f1f0f52c876d380f0215dd4ba16a09a5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/aot_compile.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/aot_compile_types.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/aot_compile_types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9004e431117b14c9124dcd77d452ffd560f52e00 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/aot_compile_types.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/bytecode_analysis.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/bytecode_analysis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e245842b99c498e543c5dc1e6071032cc4424cf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/bytecode_analysis.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/bytecode_debugger.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/bytecode_debugger.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..065fa38192de856086d38a0d414f9f90a4d6d65e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/bytecode_debugger.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/bytecode_transformation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/bytecode_transformation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..434328b5bd6746c38fd2e9f1d4c0770f29b78c71 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/bytecode_transformation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/cache_size.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/cache_size.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d5dfb05d21b49499f429d6b986596c03c0dda77 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/cache_size.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/callback.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/callback.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ecf433344d3c4dc93d22863243f8170b8ab4599d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/callback.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/code_context.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/code_context.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15ff7f90f99b45c66dd1ef50caaa09255e4df7e8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/code_context.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/codegen.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/codegen.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..145f6b30b1c10e870e3eb578021d9df8e8d77c73 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/codegen.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/compiled_autograd.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/compiled_autograd.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94d64ed19edd7bf954488ed8da4a6befc7b260be Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/compiled_autograd.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/comprehension_graph_break.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/comprehension_graph_break.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c3cbcef6117a0c48ecd4d3522664d3a8f9943d3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/comprehension_graph_break.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/comptime.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/comptime.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9230ca80e731596878dda5790ef91c5a167f285 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/comptime.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/config.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b284c17128478c1bf5224b120a1166faae5c5b5b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/config.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/convert_frame.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/convert_frame.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a54890b77b634f0aa0a9f3e5b34d9ff3308b6134 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/convert_frame.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f13294cca599c924873fb74f40c0efad223b6513096f07a1e9057f250764c8ed +size 107944 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/create_parameter_op.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/create_parameter_op.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b6550216a90f92a02e23f3af14ce5e39fd6820f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/create_parameter_op.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/current_scope_id.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/current_scope_id.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9f463ea2f3a611f6a9a8fd7f87c6e1b5732b061 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/current_scope_id.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/dce_extra_outputs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/dce_extra_outputs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..082e00e253854cc2f8c16f87063b19419c1e37d5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/dce_extra_outputs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/debug_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/debug_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ff6979fb99eef8b5941961ce63baa908c501529 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/debug_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/decorators.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/decorators.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69f02ad8412d0bfb86d8061094bd3112973ac6d2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/decorators.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/device_interface.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/device_interface.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49c18f8a2ab24f98fd659b358a75a4d83eb4bb27 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/device_interface.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/distributed.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/distributed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..644ca48ee8f61bb9721568fd899e2ca9f518bb6b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/distributed.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/dynamo_profiler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/dynamo_profiler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd86f241b5d7700a94e590df1c3992099da73b32 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/dynamo_profiler.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/eval_frame.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/eval_frame.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..788eaedec379d71bd12e27bde3ea52fdf557edc6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/eval_frame.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:780fe33841e8adc2efe5e6aaafce34c737dc5d9734a362221bf05b2179a38b48 +size 117609 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/exc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/exc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f746e0f7095763a99fb0fd4c9c28a23afe60c6a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/exc.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/external_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/external_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5224638802d6496a5b576141302159c318fd330 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/external_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/funcname_cache.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/funcname_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02fbf761185b450fb9e8fc6cfb90d0227f28b49e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/funcname_cache.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/functional_export.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/functional_export.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f69b11927bad6aed0df45b9c4dafb747f25ffe3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/functional_export.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_break_hints.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_break_hints.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29364cd09c079e892e2f4bcd5a798440f08540a7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_break_hints.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_bytecode_inputs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_bytecode_inputs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..badd6c07f1faf9c26b92c74e10246aa0b03527d5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_bytecode_inputs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_deduplication.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_deduplication.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c0a01243bfe06a012f08c1c7aaa37c35d857ace Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_deduplication.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_id_filter.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_id_filter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8b0c10a60d4eeb504296c647982f1629b2a7f28 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_id_filter.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_region_tracker.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_region_tracker.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..755491c0e98f148ab06b5ffaa30df98660e21d54 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_region_tracker.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9485bd1c1361c782783de6b4304f40c9b8b8924 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/graph_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/guards.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/guards.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53fd2e8fb28b73d239253213152d204cd6873109 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/guards.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c156a0208730d2502ddd33a68c8a945e11fd20bfd6562558c026d8bcf66fe4d8 +size 231994 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/hooks.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/hooks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..febd15378d598566e206cee8ed34aeb0ddbcc07c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/hooks.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/logging.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/logging.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2442e19402babfb525d289ee48e115b1076a6075 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/logging.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/metrics_context.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/metrics_context.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b50d1d575436f98c62184beb3dfa257b7a61045c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/metrics_context.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/mutation_guard.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/mutation_guard.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ea2181a21feb15e3d4e823d550db164c8cec379 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/mutation_guard.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/output_graph.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/output_graph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51e453ccfd251a8a5dbecad60f0129431439a2ac --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/output_graph.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b319ca877d70fcb91dca8172d5b37319a8367fe4daf24ecd6e5b6fa49c083f36 +size 197649 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/package.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/package.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bdd8556e8ffd0611d54af2be38fffa88ec1bbe8e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/package.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/pgo.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/pgo.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a8436bab6513939b38dda4397b86b2dd641d578 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/pgo.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/precompile_context.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/precompile_context.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95723f88c948d8972814dc01ac402932fd4f4dc5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/precompile_context.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/profiler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/profiler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca56ae625c47c3ebe92fe09a17bb5067a7e2fa9f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/profiler.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/replay_record.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/replay_record.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e1111ad61e541c48be2f1cad0ff150692ffd27e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/replay_record.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/resume_execution.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/resume_execution.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f33de6c3bcaec454d5f1270b6754d4c8aa47f102 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/resume_execution.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/side_effects.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/side_effects.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fbd6dde8d0f19921f1bef980266d992969b867ca Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/side_effects.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/source.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/source.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b435308024508964f27c8869ac4a3881abd9f05 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/source.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/symbolic_convert.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/symbolic_convert.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43a1e09e2c90ea356cc89cbbbed48ccbc5e03172 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/symbolic_convert.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:55b5f8811040d6de5cfebb1cbc549beef5bddc045900031ec2379f0af07214a9 +size 275231 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/tensor_version_op.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/tensor_version_op.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa7357afa997bf7dea436868cb5a49e14e18eb59 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/tensor_version_op.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/test_case.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/test_case.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..490dd221c0905dcae2325218cc239514612aec5a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/test_case.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/test_dont_skip_tracing_functions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/test_dont_skip_tracing_functions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..309d201c789cdd238a37d547068f47af430f336d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/test_dont_skip_tracing_functions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/test_minifier_common.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/test_minifier_common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3dd32cd5e6ce7b46468f9dc5839b22ffecbc7c6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/test_minifier_common.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/testing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/testing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad09dce3d8a885d3a9b89cd78a4ed282c4686cc9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/testing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/trace_rules.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/trace_rules.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c4a487d32b2cc7aebd6a1c264325db677ba6c19 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/trace_rules.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:52cb06863669e3b0875b16d4deab3118b3f70a0bb90d1a901fcbb1ec157e5264 +size 135986 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/types.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..639e3d307000f3f991e48fd6e9bd3dd05fc8d7d7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/types.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3edc45911c81d2b0dc4e32c9dada201218691100 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/__pycache__/utils.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:79cd173ba5bf24936e876d554394374a63bfc9f057b45930c091f863bea43542 +size 259838 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/_trace_wrapped_higher_order_op.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/_trace_wrapped_higher_order_op.py new file mode 100644 index 0000000000000000000000000000000000000000..4f9d1d370ecbc0802432e5f19246e05f7e9fc678 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/_trace_wrapped_higher_order_op.py @@ -0,0 +1,287 @@ +"""trace_wrapped(*args, fn) is equivalent to fn(*args), but with a twist: +if you make_fx trace through this call, we will not actually trace into fn; instead, +we will directly insert it as a call_function to fn in the graph. +(Unlike make_fx, Dynamo WILL inline into fn.) +You can think of this as a one off allow_in_graph equivalent for proxy tensor tracing. + +Because proxy tensor tracing does not actually run the function, there are +requirements on the behavior of fn. We are still figuring it out, but here is the current state: + +1) fn SHOULD only take a single argument, which must be a tensor +2) fn MUST return a new tensor with the same metadata as the original tensor + (e.g., zeros_like(input) is a permissible implementation of fn). + This is verified via an extra assert that is inserted into the traced graph. +3) fn MAY have side effects, but it MAY NOT perform metadata mutation on other tensors + participating in proxy tensor tracing (it MAY mutate other tensors, it MAY mutate Python state) +These requirements stem from the requirement that we need to continue performing proxy tensor tracing, +which assumes accurate fake tensor metadata, without actually running fn. +In the future, we may allow for a "meta" function associated with fn to allow for more interesting input-output patterns. + +Note that tensors / Python state are allowed to be mutated. +This relaxed constraint is not always sound, but it is sound for backward tracing with fake +tensors as it takes place in AOTAutograd, as the backward pass is guaranteed not to depend on concrete +tensor values (via fake tensor) or Python state (because the autograd engine doesn't depend on Python). + +The intended use case for this function is to allow AOTAutograd to defer complex +backward hooks to compiled autograd. AOTAutograd performs a make_fx trace which preserves +the function call as is in the graph, and only when we Dynamo through the backward graph in +compiled autograd do we inline into the function. +""" + +from typing import Any + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._higher_order_ops.utils import autograd_not_implemented +from torch._ops import HigherOrderOperator, OpOverload +from torch._subclasses import FakeTensorMode +from torch.fx.experimental._backward_state import BackwardState +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree +from torch.overrides import TorchFunctionMode +from torch.utils._python_dispatch import _get_current_dispatch_mode +from torch.utils._pytree import tree_map_only + + +Tensor = torch.Tensor + + +__all__ = ["trace_wrapped"] + + +@torch.library.custom_op("flex_lib::zeros_and_scatter", mutates_args=()) # type: ignore[misc] +def zeros_and_scatter( + shape: list[int], + indices: list[Tensor], + vals: Tensor, +) -> Tensor: + """Custom Op so that we can register a custom lowering for the new_output + scatter in the backwards pass""" + if not indices: + if shape: + raise RuntimeError( + "zeros_and_scatter with no indices only supports scalar outputs" + ) + return vals.sum() + grad = torch.zeros(shape, device=vals.device, dtype=vals.dtype) + return torch.ops.aten.index_put(grad, indices, vals, accumulate=True) + + +@zeros_and_scatter.register_fake # type: ignore[misc] +def _( + shape: list[int], + indices: list[Tensor], + vals: Tensor, +) -> Tensor: + return vals.new_empty(shape) + + +@zeros_and_scatter.register_vmap # type: ignore[misc] +def _(info, indims, shape, indices, value): # type: ignore[no-untyped-def] + """The batching rule is special in that it returns a tensor that is not batched""" + indices_indims: list[int | None] = indims[1] if indims[1] is not None else [] + expanded_indices = [] + for idx, idx_indim in zip(indices, indices_indims): + # The index is not being batched, we should unsqueeze and expand to val + if idx_indim is None: + expanded_indices.append(idx.expand(value.shape)) + else: + # the index is being part of the vmap batch, it should be the same size as val + if idx.shape != value.shape: + raise AssertionError( + f"idx shape {idx.shape} must match value shape {value.shape}" + ) + expanded_indices.append(idx) + + out = torch.ops.flex_lib.zeros_and_scatter( + shape, + expanded_indices, + value, + ) + return out, None + + +class ModIndex(torch.autograd.Function): + generate_vmap_rule = True + + @staticmethod + # pyrefly: ignore [bad-override] + def forward(x: Tensor, indices: list[Tensor]) -> Tensor: + if not indices: + if x.ndim != 0: + raise RuntimeError( + "mod_index with no indices only supports scalar tensors" + ) + return x + return torch.ops.aten.index(x, indices) + + @staticmethod + def setup_context(ctx: Any, inputs: tuple[Any, ...], output: Any) -> None: + x, indices = inputs + ctx.save_for_backward(*indices) + ctx.input_shape = x.shape + + @staticmethod + def backward(ctx, gradOut): # type: ignore[no-untyped-def] + indices = ctx.saved_tensors + return ( + torch.ops.flex_lib.zeros_and_scatter( + ctx.input_shape, + indices, + gradOut, + ), + None, + ) + + @classmethod + @torch._export.wrappers.allow_in_pre_dispatch_graph + def apply(cls, *args, **kwargs): # type: ignore[no-untyped-def] + return super().apply(*args, **kwargs) + + +mod_index = ModIndex.apply + + +class TransformGetItemToIndex(TorchFunctionMode): + # This is needed since we want to support calling + # A[q_idx], where q_idx is a scalar tensor in score_mod. + # Today, when q_idx is a scalar tensor, we implicitly convert it to a python + # scalar and create a view. We do not want that behavior in this case, so we + # use this torchfunctionmode to override that behavior for score_mod + # wherever we're running it. + # + # We also convert integer indices to 0-D tensors so that temp[0] produces + # the same backward graph as temp[0 * q_idx] (zeros_and_scatter with atomic_add). + def __torch_function__( + self, + func: OpOverload, + types: tuple[torch._C._TensorMeta, ...], + args: tuple[object, ...] = (), + kwargs: dict[str, object] | None = None, + ) -> object: + if func is torch.Tensor.__getitem__: + tensor_to_index = args[0] + if not isinstance(tensor_to_index, torch.Tensor): + raise AssertionError( + f"expected torch.Tensor, got {type(tensor_to_index)}" + ) + index_args = pytree.tree_leaves(args[1]) + if all(isinstance(x, (torch.Tensor, int)) for x in index_args): + converted_indices = [ + torch.tensor(x, dtype=torch.int64, device=tensor_to_index.device) + if isinstance(x, int) + else x + for x in index_args + ] + return mod_index(tensor_to_index, converted_indices) + return func(*args, **(kwargs or {})) + + +def trace_wrapped(*args: Any, **kwargs: Any) -> Any: + with torch.no_grad(): + return _trace_wrapped_op(*args, **kwargs) + + +class TraceWrapped(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("trace_wrapped") + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + # pyrefly: ignore [missing-attribute] + return super().__call__(*args, **kwargs) + + +# TODO(jansel): need to ensure this does not get DCEed +_trace_wrapped_op = TraceWrapped() + + +def _assert_meta( + grad: torch.Tensor, + size: tuple[int, ...], + stride: tuple[int, ...], + dtype: torch.dtype, +) -> torch.Tensor: + if grad.size() != size: + raise AssertionError("size mismatch") + if grad.stride() != stride: + raise AssertionError("stride mismatch") + if grad.dtype != dtype: + raise AssertionError("dtype mismatch") + return grad + + +@_trace_wrapped_op.py_impl(ProxyTorchDispatchMode) +def inner_trace( + mode: ProxyTorchDispatchMode, + *args: Any, + bw_state: BackwardState | None = None, + **kwargs: Any, +) -> Any: + def self_invoke(*args: Any, **dyn_kwargs: Any) -> Any: + with torch.no_grad(): + return _trace_wrapped_op(*args, **dyn_kwargs, **kwargs) + + def unwrap_proxies(x: Any) -> Any: + if isinstance(x, torch.Tensor): + return mode.tracer.unwrap_proxy(x) # type: ignore[union-attr] + if isinstance(x, (list, tuple)): + return type(x)(map(unwrap_proxies, x)) + if x is None: + return None + raise AssertionError(f"unhandled type: {type(x)}") + + proxy_kwargs = {} + if bw_state is not None: + if not isinstance(bw_state, BackwardState): + raise AssertionError(f"expected BackwardState, got {type(bw_state)}") + if bw_state.proxy is None: + raise AssertionError("bw_state.proxy must not be None") + proxy_kwargs["bw_state"] = bw_state.proxy + out_proxy = mode.tracer.create_proxy( + "call_function", + self_invoke, + unwrap_proxies(args), + proxy_kwargs, + name="trace_wrapped", + ) + + if args[0] is None: + grad = args[1] # module backward hooks + else: + grad = args[0] # other backward hooks + grad = tree_map_only(torch.Tensor, torch.empty_like, grad) + track_tensor_tree(grad, out_proxy, constant=None, tracer=mode.tracer) + return grad + + +@_trace_wrapped_op.py_impl(FakeTensorMode) +def inner_fake(*args: Any, **kwargs: Any) -> None: + raise RuntimeError("This op should never be invoked here") + + +@_trace_wrapped_op.py_impl(DispatchKey.CompositeExplicitAutograd) +def _trace_wrapped_op_dense(*args: Any, fn: Any, **kwargs: Any) -> Any: + mode = _get_current_dispatch_mode() + if mode is not None: + raise AssertionError("Mode should never be enabled for CPU/CUDA key") + return fn(*args, **kwargs) + + +_trace_wrapped_op.py_impl(DispatchKey.Autograd)( + autograd_not_implemented(_trace_wrapped_op, deferred_error=True) +) + + +@_trace_wrapped_op.py_functionalize_impl +def _trace_wrapped_functionalized(ctx: Any, *args: Any, **kwargs: Any) -> Any: + unwrapped_args = ctx.unwrap_tensors(args) + with ctx.redispatch_to_next(): + return ctx.wrap_tensors(_trace_wrapped_op(*unwrapped_args, **kwargs)) + + +def autograd_function_backward_rewritten(original_backward: Any) -> Any: + def new_backward(ctx: Any, *grads: Any) -> Any: + # pyrefly: ignore [bad-assignment] + grads = [g.contiguous() for g in grads] + return original_backward(ctx, *grads) + + return new_backward diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/aot_compile.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/aot_compile.py new file mode 100644 index 0000000000000000000000000000000000000000..10079dde9b5e13a2d6669ad4a9134e20a63deb25 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/aot_compile.py @@ -0,0 +1,550 @@ +import dataclasses +import importlib +import inspect +import io +import logging +import os +import pickle +import tempfile +import types +from collections.abc import Callable, Sequence +from contextlib import AbstractContextManager, ExitStack, nullcontext +from dataclasses import dataclass +from typing import Any, Optional, TYPE_CHECKING + +import torch +import torch.fx +from torch._dynamo.convert_frame import GraphRuntimeEnv +from torch._dynamo.graph_utils import _graph_device_type +from torch._dynamo.package import SystemInfo + +from . import convert_frame +from .aot_compile_types import ( + BundledAOTAutogradSerializableCallable, + SerializableCallable, +) +from .hooks import Hooks + + +if TYPE_CHECKING: + from .guards import GuardManagerWrapper + from .package import SerializedCode, SourceInfo + + +log = logging.getLogger(__name__) + + +def bind_locals( + signature: inspect.Signature, *args: Any, **kwargs: Any +) -> dict[str, Any]: + bound_arguments = signature.bind(*args, **kwargs) + bound_arguments.apply_defaults() + return bound_arguments.arguments + + +@dataclass +class CompileArtifacts: + signature: inspect.Signature + guard_manager: Optional["GuardManagerWrapper"] + guards_state: bytes + backend_id: str + compiled_fn: SerializableCallable + original_code: types.CodeType + runtime_env: GraphRuntimeEnv + source_info: "SourceInfo" + device_type: str + backend_name: str + system_info: SystemInfo = dataclasses.field(default_factory=SystemInfo.current) + + def check_compatibility(self) -> None: + current_system = SystemInfo.current() + current_system.check_compatibility(self.system_info, self.device_type) + + +class AOTCompilePickler(pickle.Pickler): + def __init__(self, external_data: dict[str, object], buf: io.BytesIO) -> None: + super().__init__(buf) + self.external_data = external_data + self.id_map: dict[int, str] = { + id(value): key for key, value in external_data.items() + } + self.errors = {} + + def persistent_id(self, obj: object) -> int | str | None: + if id(obj) in self.id_map: + return self.id_map[id(obj)] + elif isinstance(obj, torch.nn.Module): + self.errors[id(obj)] = obj + return id(obj) + else: + return None + + @classmethod + def _unpickle_cell(cls, val: object) -> object: + def _() -> object: + return val + + if _.__closure__ is None: + raise AssertionError("closure must not be None") + return _.__closure__[0] + + @classmethod + # pyrefly: ignore [implicit-any] + def _unpickle_bound_method(cls, func: Callable, base: object) -> types.MethodType: + return types.MethodType(func, base) + + @classmethod + def _unpickle_module(cls, name: str) -> types.ModuleType: + return importlib.import_module(name) + + @classmethod + def _unpickle_code(cls, serialized_code: "SerializedCode") -> types.CodeType: + from torch._dynamo.package import SerializedCode + + return SerializedCode.to_code_object(serialized_code) + + @classmethod + def _unpickle_nested_function( + cls, + code: types.CodeType, + module: str, + qualname: str, + argdefs: tuple[object, ...] | None, + closure: tuple[types.CellType, ...] | None, + ) -> types.FunctionType: + f_globals = importlib.import_module(module).__dict__ + return types.FunctionType(code, f_globals, qualname, argdefs, closure) + + # pyrefly: ignore [bad-override] + def reducer_override(self, obj: Any) -> Any: + if isinstance(obj, type((lambda x: lambda: x)(0).__closure__[0])): # type: ignore[index] # noqa: PLC3002 + return type(self)._unpickle_cell, (obj.cell_contents,) + elif inspect.iscode(obj): + from torch._dynamo.package import SerializedCode + + return type(self)._unpickle_code, (SerializedCode.from_code_object(obj),) + + elif inspect.ismodule(obj): + return type(self)._unpickle_module, (obj.__name__,) + elif inspect.ismethod(obj): + """ + By default, pickle will call getattr() directly on the self object + for pickling bounded methods, this is not what we want, instead we + always want to serialize the original function and the self object + in their original form. + """ + func = obj.__func__ + method_self = obj.__self__ + inner_func = getattr(method_self, func.__name__) + if inspect.ismethod(inner_func): + inner_func = inner_func.__func__ + if func is not inner_func: + return type(self)._unpickle_bound_method, (func, method_self) + elif inspect.isfunction(obj): + if "" in obj.__qualname__: + return type(self)._unpickle_nested_function, ( + obj.__code__, + obj.__module__, + obj.__qualname__, + obj.__defaults__, + obj.__closure__, + ) + + return NotImplemented + + +class AOTCompileUnpickler(pickle.Unpickler): + def __init__(self, external_data: dict[str, object], file: io.BytesIO) -> object: + super().__init__(file) + self.external_data = external_data + + def persistent_load(self, key: str) -> object: + if key not in self.external_data: + raise RuntimeError( + f"Missing required external reference to data: {key}. " + "Please load AOT compiled function with " + "`external_data=`" + f"{self.external_data}" + ) + return self.external_data[key] + + +@dataclass +class AOTCompileSaveResult: + serialized_data: bytes + + +def atomic_write_binary(file_path: str, data: bytes): + dir_name = os.path.dirname(file_path) or "." + + with tempfile.NamedTemporaryFile( + dir=dir_name, delete=False, mode="wb" + ) as temp_file: + temp_path = temp_file.name + temp_file.write(data) + temp_file.flush() + os.fsync(temp_file.fileno()) + + os.replace(temp_path, file_path) + + +@dataclass +class AOTCompiledFunction: + _artifacts: CompileArtifacts + _guard_check_enabled: bool = True + _extra_globals: dict[str, object] | None = None + + def prepare_f_locals(self, *args: object, **kwargs: object) -> dict[str, object]: + f_locals: dict[str, object] = {} + env = self._artifacts.runtime_env + if env.closure: + if not env.bytecode.co_freevars or len(env.closure) != len( + env.bytecode.co_freevars + ): + raise AssertionError("closure length must match co_freevars length") + f_locals = { + name: cell.cell_contents + for name, cell in zip(env.bytecode.co_freevars, env.closure) + } + f_locals.update(bind_locals(self._artifacts.signature, *args, **kwargs)) + return f_locals + + def guard_check(self, *args: Any, **kwargs: Any) -> bool: + f_locals = self.prepare_f_locals(*args, **kwargs) + if self._artifacts.guard_manager is None: + raise AssertionError("guard_manager must not be None") + return self._artifacts.guard_manager.check(f_locals) + + def __post_init__(self) -> None: + from .package import load_guard_manager, load_guards_state + + self._artifacts.check_compatibility() + + self.fn = self._artifacts.runtime_env.forward_callable( + self._artifacts.backend_id, + self._artifacts.compiled_fn, + extra_globals=self._extra_globals, + ) + + if self._artifacts.guard_manager is None: + guards_state = load_guards_state(self._artifacts.guards_state) + self._artifacts.guard_manager = load_guard_manager( + guards_state, + self._artifacts.original_code, + self.fn.__globals__, + ) + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + if self._artifacts.guard_manager is None: + raise AssertionError("guard_manager must not be None") + if self._guard_check_enabled and not self.guard_check(*args, **kwargs): + f_locals = self.prepare_f_locals(*args, **kwargs) + reason = str(self._artifacts.guard_manager.check_verbose(f_locals)) + raise RuntimeError(f"GuardManager check failed, reason: {reason}") + return self.fn(*args, **kwargs) + + def source_info(self) -> "SourceInfo": + return self._artifacts.source_info + + def save_compiled_function( + self, path: str, external_data: dict[str, Any] | None = None + ) -> AOTCompileSaveResult: + result = type(self).serialize(self, external_data) + atomic_write_binary(path, result.serialized_data) + return result + + @classmethod + def serialize( + cls, fn: "AOTCompiledFunction", external_data: dict[str, Any] | None = None + ) -> AOTCompileSaveResult: + from torch._dynamo.package import SerializedCode + + state = fn._artifacts.__dict__.copy() + state["guard_manager"] = None + state["runtime_env"] = dataclasses.replace( + state["runtime_env"], + bytecode=SerializedCode.from_code_object(state["runtime_env"].bytecode), + ) + compiled_fn = state["compiled_fn"] + state["compiled_fn"] = ( + type(compiled_fn).deserialize_compile_artifacts, + type(compiled_fn).serialize_compile_artifacts(compiled_fn), + ) + state["original_code"] = SerializedCode.from_code_object(state["original_code"]) + buf = io.BytesIO() + pickler = AOTCompilePickler(external_data or {}, buf) + pickler.dump(state) + if pickler.errors: + raise RuntimeError( + f"Failed to serialize the following objects: {list(pickler.errors.values())}\n" + "Please mark these as external data by using `external_data={'key': ...}`" + ) + return AOTCompileSaveResult(serialized_data=buf.getvalue()) + + @classmethod + def deserialize( + cls, + data: bytes, + f_globals: dict[str, object] | None = None, + external_closure_data: dict[str, Any] | None = None, + ) -> "AOTCompiledFunction": + from torch._dynamo.package import SerializedCode + + f = io.BytesIO(data) + f.seek(0) + unpickler = AOTCompileUnpickler(external_closure_data or {}, f) + state = unpickler.load() + f.close() + state["runtime_env"] = dataclasses.replace( + state["runtime_env"], + bytecode=SerializedCode.to_code_object(state["runtime_env"].bytecode), + ) + deserializer, compiled_fn_state = state["compiled_fn"] + with torch._inductor.config.patch(enable_autograd_for_aot=True): + state["compiled_fn"] = deserializer(compiled_fn_state) + state["original_code"] = SerializedCode.to_code_object(state["original_code"]) + + artifacts = CompileArtifacts(**state) + return cls(artifacts, _extra_globals=f_globals) + + def disable_guard_check(self) -> None: + self._guard_check_enabled = False + + +def aot_compile_fullgraph( + model: Any, + example_inputs: tuple[tuple[Any, ...], dict[str, Any]], + hooks: Hooks, + backend: Callable[[torch.fx.GraphModule, list[torch.Tensor]], SerializableCallable], + dynamic: bool | None = None, +) -> AOTCompiledFunction: + from torch._dynamo.guards import CheckFunctionManager + from torch._dynamo.package import SourceInfo + from torch._dynamo.utils import dynamo_timed, get_metrics_context + from torch._dynamo.variables.torch_function import ( + torch_function_mode_stack_state_mgr, + ) + from torch._guards import TracingContext + + args, kwargs = example_inputs + + dynamic_ctx = nullcontext() + if dynamic is not None: + from torch._dynamo.eval_frame import set_enable_dynamic + + dynamic_ctx = set_enable_dynamic(dynamic) + + with ( + get_metrics_context(), + dynamo_timed("fullgraph_capture"), + torch._functorch.config.patch(strict_autograd_cache=True), + dynamic_ctx, + torch_function_mode_stack_state_mgr, + ): + capture_output = convert_frame.fullgraph_capture(model, args, kwargs) + graph_capture_output = capture_output.graph_capture_output + if graph_capture_output.output_graph is None: + raise AssertionError("output_graph must not be None") + + if not hooks.guard_filter_fn: + from torch._dynamo.types import GuardFilterEntry + + def new_guard_filter_fn( + guard_entries: Sequence[GuardFilterEntry], + ) -> Sequence[bool]: + return [ + ( + not ( + g.is_global + or g.guard_type + in CheckFunctionManager.UNSUPPORTED_SERIALIZATION_GUARD_TYPES + ) + ) + for g in guard_entries + ] + + hooks.guard_filter_fn = new_guard_filter_fn + + fn, _ = convert_frame.get_traced_fn(model) + + backend_input = capture_output.backend_input + if backend_input is None: + raise AssertionError("backend_input must not be None") + backend_input.graph_module._backend_id = backend_input.backend_id # type: ignore[assignment] + device_type = _graph_device_type(backend_input.graph_module.graph) + if ( + backend_input.fake_mode.shape_env + is not graph_capture_output.output_graph.shape_env + ): + raise AssertionError( + "fake_mode.shape_env must be the same as output_graph.shape_env" + ) + tracing_context = TracingContext(backend_input.fake_mode) + tracing_context.tensor_to_context = backend_input.tensor_to_context + with ( + torch._guards.tracing(tracing_context), + torch._functorch.config.patch( + { + "strict_autograd_cache": True, + "bypass_autograd_cache_key": True, + "bundled_autograd_cache": True, + "force_non_lazy_backward_lowering": True, + "force_autograd_cache": True, + } + ), + ): + compiled_fn = backend( + backend_input.graph_module, backend_input.example_inputs + ) + # If Inductor backend or AOTAutograd-based backend is used, + # wrap the compiled_fn for serialization. + # TODO: this should be replaced once we make the backend return the SerializableCallable directly. + if ( + isinstance(backend, torch._TorchCompileInductorWrapper) + or ( + hasattr(backend, "compiler_fn") + and isinstance( + backend.compiler_fn, torch._dynamo.backends.common.AotAutograd + ) + ) + or ( + hasattr(compiled_fn, "serialize") + and compiled_fn.serialize is not None + ) + ): + compiled_fn = BundledAOTAutogradSerializableCallable(compiled_fn) + + if not isinstance(compiled_fn, SerializableCallable): + if hasattr(backend, "compiler_fn"): + compiler_fn = backend.compiler_fn + else: + compiler_fn = backend + raise RuntimeError( + f"Compiled function type {type(compiled_fn)} (produced " + + f"from backend {compiler_fn}) does not implement SerializableCallable." + ) + + # Temporarily restore the mode stack so guard expressions that + # reference modes can evaluate, matching the compile_inner path. + build_guards_ctx = ExitStack() + if torch_function_mode_stack_state_mgr.stack: + build_guards_ctx.enter_context( + torch_function_mode_stack_state_mgr.temp_restore_stack() + ) + with build_guards_ctx: + check_fn = graph_capture_output.build_guards( + fn.__code__, hooks=hooks, save=True, strict_error=True + ) + + if check_fn.guards_state is None: + raise AssertionError("guards_state must not be None") + + source_info = SourceInfo(inlined_sources=set()) + for traced_code in graph_capture_output.traced_code: + source_info.add_code(traced_code) + + artifacts = CompileArtifacts( + signature=convert_frame._get_signature(fn), + guard_manager=check_fn.guard_manager, + guards_state=check_fn.guards_state, + backend_id=backend_input.backend_id, + compiled_fn=compiled_fn, + original_code=fn.__code__, + runtime_env=graph_capture_output.get_runtime_env(), + source_info=source_info, + device_type=device_type, + backend_name=getattr(backend, "compiler_name", "unknown"), + ) + aot_compiled_fn = AOTCompiledFunction( + _artifacts=artifacts, _extra_globals=fn.__globals__ + ) + + return aot_compiled_fn + + +@dataclass +class ModelInput: + """ + WIP type: represents a single model input + Which consists of a tuple of arguments and a set of contexts in which to run the model. + + For each ModelInput, we'll compile one full graph of the model, and then use the guards generated + to dispatch between the compiled graphs. + + + """ + + args: tuple[Any] + kwargs: dict[str, Any] + contexts: list[AbstractContextManager[Any]] + + +@dataclass +class AOTCompiledModel: + # Represents a single forward function of a model along with dispatch + # compiled_results is serializable. We require the model to deserialize again. + model: torch.nn.Module + compiled_results: list[AOTCompiledFunction] + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + for result in self.compiled_results: + if result.guard_check(self.model, *args, **kwargs): + return result(self.model, *args, **kwargs) + # All guards failed, just run one of them and throw the guard check error. + return self.compiled_results[0](self.model, *args, **kwargs) + + def serialize(self) -> bytes: + data: list[bytes] = [] + for result in self.compiled_results: + data.append(AOTCompiledFunction.serialize(result).serialized_data) + return pickle.dumps(data) + + @classmethod + def deserialize(cls, model: torch.nn.Module, data: bytes) -> "AOTCompiledModel": + from torch._dynamo.utils import get_metrics_context + from torch._guards import compile_context, CompileContext + + results: list[bytes] = pickle.loads(data) + compiled_results = [] + for result in results: + with ( + compile_context(CompileContext(convert_frame.get_compile_id({}))), + get_metrics_context(), + ): + compiled_results.append(AOTCompiledFunction.deserialize(result)) + return cls(model, compiled_results) + + +def aot_compile_module( + model: torch.nn.Module, + inputs: list[ModelInput], + hooks: Hooks, + backend: Callable[[torch.fx.GraphModule, list[torch.Tensor]], SerializableCallable], +) -> AOTCompiledModel: + """ + Compiles a single nn.Module with any number of inputs, and returns a compiled forward function. + """ + + def compile_single_graph(model_input: ModelInput) -> AOTCompiledFunction: + example_inputs = (model_input.args, model_input.kwargs) + orig_forward = model.forward + with ExitStack() as stack: + for ctx in model_input.contexts: + stack.enter_context(ctx) + return aot_compile_fullgraph( + orig_forward, + example_inputs, + hooks=hooks, + backend=backend, + ) + + # pyrefly: ignore [implicit-any] + compiled_results = [] + for model_input in inputs: + log.info("Compiling input %s..", model_input) + compiled_results.append(compile_single_graph(model_input)) + + if len(compiled_results) == 0: + raise AssertionError("Expected at least one compiled result") + + return AOTCompiledModel(model, compiled_results) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/aot_compile_types.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/aot_compile_types.py new file mode 100644 index 0000000000000000000000000000000000000000..19ed258ac2b191ee20c40e957e8b4ec4beb32e8a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/aot_compile_types.py @@ -0,0 +1,221 @@ +import abc +import importlib +import pickle +from typing import Any + +import torch + + +def _serialize_triton_kernel(kernel: Any) -> tuple[str, str]: + """ + Serialize a triton kernel by extracting its module path and function name. + Returns (module_path, function_name) tuple. + + Triton JITFunction objects contain unpicklable _thread.RLock objects, so we + serialize the import path instead and reimport on load. + + Raises: + RuntimeError: If the kernel cannot be serialized (missing attributes). + """ + fn = getattr(kernel, "fn", None) + module_path = fn and getattr(fn, "__module__", None) + func_name = fn and getattr(fn, "__name__", None) + if fn is None or module_path is None or func_name is None: + raise RuntimeError( + f"Kernel fn missing __module__ or __name__: " + f"module={module_path}, name={func_name}. " + f"Cannot serialize for precompilation." + ) + return (module_path, func_name) + + +def _deserialize_triton_kernel(kernel_info: tuple[str, str]) -> Any: + """ + Deserialize a triton kernel by reimporting from its module. + kernel_info is (module_path, function_name) tuple. + """ + module_path, func_name = kernel_info + module = importlib.import_module(module_path) + kernel = getattr(module, func_name) + return kernel + + +# Note: [Triton Kernel Side Table Serialization] +# +# When dynamo captures user-defined triton kernels, it creates FX graph nodes +# (triton_kernel_wrapper_mutation/functional) with a `kernel_idx` parameter that +# references the global `kernel_side_table` in triton_kernel_wrap.py. This side +# table maps integer indices to actual triton kernel objects. +# +# For kernels that go through inductor's codegen path, this is fine - inductor +# looks up the kernel from the side table at codegen time and embeds the kernel +# source code directly into the generated wrapper. The compiled code doesn't +# need the side table at runtime. +# +# However, not all triton kernels go through inductor codegen. When using +# regional_inductor, only annotated regions are compiled by inductor. Triton +# kernels outside these regions are executed via the FX interpreter, which +# calls the higher-order op directly and needs the kernel to be in the side +# table at runtime. +# +# When serializing/deserializing bundled AOT artifacts across process boundaries, +# the kernel_side_table is empty in the new process, causing: +# AssertionError: Kernel index X not found in id_to_kernel +# +# To fix this, we capture the kernel_side_table state during serialization and +# restore it during deserialization. Kernels are serialized by their import path +# (module_path, function_name) since triton JITFunction objects contain +# unpicklable RLock objects. + + +class SerializableCallable(abc.ABC): + @classmethod + @abc.abstractmethod + def serialize_compile_artifacts(cls, fn: Any) -> bytes: + pass + + @classmethod + @abc.abstractmethod + def deserialize_compile_artifacts(cls, data: bytes) -> Any: + pass + + @abc.abstractmethod + def __call__(self, *args: Any, **kwargs: Any) -> Any: + pass + + +class GraphModuleSerializableCallable(SerializableCallable): + def __init__(self, graph_module: torch.fx.GraphModule) -> None: + if not isinstance(graph_module, torch.fx.GraphModule): + raise AssertionError( + f"Expected torch.fx.GraphModule, got {type(graph_module)}" + ) + self.graph_module = graph_module + + @classmethod + def serialize_compile_artifacts( + cls, fn: "GraphModuleSerializableCallable" + ) -> bytes: + from torch.fx._graph_pickler import GraphPickler, Options + + state = fn.__dict__.copy() + + graph_module = state["graph_module"] + for node in graph_module.graph.nodes: + node.meta.pop("nn_module_stack", None) + node.meta.pop("source_fn_stack", None) + node.meta.pop("example_value", None) + + state["graph_module"] = GraphPickler.dumps( + graph_module, Options(ops_filter=None) + ) + return pickle.dumps(state) + + @classmethod + def deserialize_compile_artifacts(cls, data: bytes) -> Any: + from torch._subclasses import FakeTensorMode + from torch.fx._graph_pickler import GraphPickler + from torch.fx.experimental.symbolic_shapes import ShapeEnv + + state = pickle.loads(data) + + fake_mode = FakeTensorMode(shape_env=ShapeEnv()) + state["graph_module"] = GraphPickler.loads(state["graph_module"], fake_mode) + if not isinstance(state["graph_module"], torch.fx.GraphModule): + raise AssertionError( + f"Expected deserialized graph_module to be torch.fx.GraphModule, " + f"got {type(state['graph_module'])}" + ) + state["graph_module"].recompile() + + return cls(**state) + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + return self.graph_module.forward(*args, **kwargs) + + +class BundledAOTAutogradSerializableCallable(SerializableCallable): + """ + Represents a serializable callable generated by compile_fx. + This class wraps around the compiled function generated by AOTAutograd. + + TODO: Instead of using PrecompileContext to grab it from AOTAutograd, + this object should be what's *returned* by aot_module_simplified. + We'll do that refactor in a later PR. + """ + + def __init__(self, compiled_fn: Any) -> None: + """ + Takes in a BundledAOTAutogradCacheArtifact, which is the serialized form + of a compiled function generated by AOTAutograd. + """ + if not hasattr(compiled_fn, "serialize"): + raise AssertionError( + f"compiled_fn must have a 'serialize' method, got {type(compiled_fn)}" + ) + self.compiled_fn = compiled_fn + + def __getattr__(self, attr: Any) -> Any: + return getattr(self.compiled_fn, attr) + + @classmethod + def serialize_compile_artifacts( + cls, fn: "BundledAOTAutogradSerializableCallable" + ) -> bytes: + from torch._higher_order_ops.triton_kernel_wrap import kernel_side_table + + # See Note: [Triton Kernel Side Table Serialization] + # Capture triton kernel side table state BEFORE serialization. + triton_kernels: dict[int, tuple[str, str]] = { + idx: _serialize_triton_kernel(kernel) + for idx, kernel in kernel_side_table.id_to_kernel.items() + } + triton_constant_args: dict[int, dict[str, Any]] = dict( + kernel_side_table.constant_args + ) + + with torch._functorch.config.patch("bundled_autograd_cache", True): + serialized_entry = fn.compiled_fn.serialize() + # Bundle the triton kernel side table with the serialized entry + bundle = (serialized_entry, triton_kernels, triton_constant_args) + result = pickle.dumps(bundle) + return result + + @classmethod + def deserialize_compile_artifacts(cls, data: bytes) -> Any: + from torch._functorch._aot_autograd.aot_autograd_result import ( + deserialize_bundled_cache_entry, + ) + from torch._higher_order_ops.triton_kernel_wrap import kernel_side_table + + bundle = pickle.loads(data) + + # Handle both old format (just entry) and new format (entry, kernels, const_args) + if isinstance(bundle, tuple) and len(bundle) == 3: + entry, triton_kernels, triton_constant_args = bundle + else: + # Backwards compatibility with old serialized artifacts + entry = bundle + # pyrefly: ignore [implicit-any] + triton_kernels = {} + # pyrefly: ignore [implicit-any] + triton_constant_args = {} + + # See Note: [Triton Kernel Side Table Serialization] + # Restore triton kernel side table BEFORE deserializing the compiled function. + # The compiled function may reference kernels by index if any triton kernels + # don't go through inductor codegen (e.g., triton kernels outside of + # regional_inductor compiled regions). + for idx, kernel_info in triton_kernels.items(): + kernel = _deserialize_triton_kernel(kernel_info) + kernel_side_table.id_to_kernel[idx] = kernel + kernel_side_table.kernel_to_id[kernel] = idx + + for idx, args in triton_constant_args.items(): + kernel_side_table.constant_args[idx] = args + + compiled_fn = deserialize_bundled_cache_entry(entry) + return cls(compiled_fn) + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + return self.compiled_fn(*args, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__init__.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7e764b3f09c6c0548e7f6f5150ec915384a58a9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/common.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed876cc385eddcbd99bb1c633d6cbc447a2b3cf8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/common.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/cudagraphs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/cudagraphs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..031014ba8427cd1f5e8de4ee6e364690bef441a7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/cudagraphs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/debugging.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/debugging.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05ce1f3e4fe1e1e238882e52393dff9c7541cb23 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/debugging.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/distributed.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/distributed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e6dc19b76d45014fa191128a7903984a23789a7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/distributed.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/inductor.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/inductor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a642840668923e83e8987266fcae9dfa63ebe11 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/inductor.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/onnxrt.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/onnxrt.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfbdc8900192b5ef56e9642e2ed254bb5ce95703 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/onnxrt.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/registry.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/registry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93671ab48d865bc7262ec16e0b9d7ade13df3d89 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/registry.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/tensorrt.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/tensorrt.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1eac2338f917221350c2f4654e2ed15cae09818 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/tensorrt.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/torchxla.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/torchxla.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..748e18b52dcc6b0a7c751a6181f12660ccac5694 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/torchxla.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/tvm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/tvm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb9eb6ad0237a95d07313690d6cfbc998282870b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/__pycache__/tvm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/common.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/common.py new file mode 100644 index 0000000000000000000000000000000000000000..8512144eb5790664cf458fd1744271d56320e2a2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/common.py @@ -0,0 +1,215 @@ +""" +This module provides common utilities and base classes for TorchDynamo backends. + +Key components: +- AotAutograd: Base class for implementing AOT (Ahead-of-Time) autograd backends +- Backend utilities for handling: + - Fake tensor conversion + - Device/dtype detection from inputs + - Memory efficient fusion + - Graph flattening + - Common compiler configurations + +The utilities here are used by various backend implementations to handle +common operations and provide consistent behavior across different backends. +AOT autograd functionality is particularly important as it enables ahead-of-time +optimization of both forward and backward passes. +""" + +from __future__ import annotations + +import contextlib +import functools +import logging +from typing import Any, TYPE_CHECKING +from typing_extensions import ParamSpec, Required, TypedDict, TypeVar, Unpack +from unittest.mock import patch + +import torch +from torch._dynamo import disable +from torch._dynamo.exc import TensorifyScalarRestartAnalysis +from torch._dynamo.utils import counters, defake, flatten_graph_inputs +from torch._functorch.aot_autograd import ( + aot_module_simplified, + SerializableAOTDispatchCompiler, +) +from torch.utils._python_dispatch import _disable_current_modes + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Sequence + + from torch._inductor.compile_fx import CompilerConfigExtra + from torch._ops import OpOverload + + +log = logging.getLogger(__name__) + +P = ParamSpec("P") +R = TypeVar("R") + + +class AotAutogradKwargs(TypedDict, total=False): + """Keyword arguments accepted by AotAutograd and forwarded verbatim to + aot_module_simplified. decompositions may also be a zero-arg thunk returning + the decomposition table (a workaround for circular imports); AotAutograd + resolves it to the table before forwarding.""" + + fw_compiler: Required[Callable[..., Any]] + bw_compiler: Callable[..., Any] | None + inference_compiler: Callable[..., Any] | None + partition_fn: Callable[..., Any] + decompositions: ( + dict[OpOverload, Callable[..., Any]] + | Callable[[], dict[OpOverload, Callable[..., Any]]] + ) + keep_inference_input_mutations: bool + compiler_config_extra: CompilerConfigExtra | None + ignore_shape_env: bool + disable_functionalization: bool + pre_grad_passes: Callable[..., Any] | None + compile_region_name: str | None + + +class AotAutograd: + def __init__(self, **kwargs: Unpack[AotAutogradKwargs]) -> None: + self.__name__ = "compiler_fn" + self.kwargs: AotAutogradKwargs = kwargs + + def __call__( + self, gm: torch.fx.GraphModule, example_inputs: Sequence[Any], **kwargs: Any + ) -> Callable[..., Any]: + if kwargs: + log.warning("aot_autograd-based backend ignoring extra kwargs %s", kwargs) + + if any(isinstance(x, (list, tuple, dict)) for x in example_inputs): + return flatten_graph_inputs( + gm, + example_inputs, + self, + ) + + # Hack to get around circular import problems with aot_eager_decomp_partition + decompositions = self.kwargs.get("decompositions") + if callable(decompositions): + self.kwargs["decompositions"] = decompositions() + + # NB: don't delete counter increment + counters["aot_autograd"]["total"] += 1 + + def wrap_bw_compiler(bw_compiler_fn: Callable[P, R]) -> Callable[..., R]: + def _wrapped_bw_compiler(*args: P.args, **kwargs: P.kwargs) -> R: + # Note [Wrapping bw_compiler in disable] + # The two disables here: + # - stop TorchDynamo from trying to compile the bw_compiler function itself + # - stop TorchDynamo from trying to compile our the generated backwards pass bw_compiler produces + + return disable( + disable( + bw_compiler_fn, reason="do not trace backward compiler function" + )(*args, **kwargs), # type: ignore[misc] + reason="do not trace generated backwards pass", + ) + + _wrapped_bw_compiler._is_wrapped_bw_compiler = ( # pyrefly: ignore [missing-attribute] + True + ) + return _wrapped_bw_compiler + + bw_compiler = self.kwargs.get("bw_compiler") or self.kwargs["fw_compiler"] + + if isinstance(bw_compiler, SerializableAOTDispatchCompiler): + if not getattr(bw_compiler.compiler_fn, "_is_wrapped_bw_compiler", False): + bw_compiler.compiler_fn = wrap_bw_compiler(bw_compiler.compiler_fn) + elif not getattr(bw_compiler, "_is_wrapped_bw_compiler", False): + bw_compiler = wrap_bw_compiler(bw_compiler) + + self.kwargs["bw_compiler"] = bw_compiler + self.kwargs["inference_compiler"] = ( + self.kwargs.get("inference_compiler") or self.kwargs["fw_compiler"] + ) + + from functorch.compile import nop + from torch._inductor.debug import enable_aot_logging + + # debug asserts slow down compile time noticeably, + # So only default them on when the aot_eager backend is used. + if self.kwargs.get("fw_compiler", None) is nop: + patch_config: contextlib.AbstractContextManager[Any] = patch( + "functorch.compile.config.debug_assert", True + ) + else: + patch_config = contextlib.nullcontext() + + try: + # NB: NOT cloned! + with enable_aot_logging(), patch_config: + # The decompositions thunk is resolved to a concrete table by the + # callable check above, but pyrefly cannot narrow that through the + # TypedDict subscript assignment, so the spread looks ill-typed. + cg = aot_module_simplified( + gm, + example_inputs, + **self.kwargs, # pyrefly: ignore [bad-argument-type] + ) + counters["aot_autograd"]["ok"] += 1 + return disable(cg, reason="do not trace AOT-compiled graph") + except TensorifyScalarRestartAnalysis: + raise + except Exception: + counters["aot_autograd"]["not_ok"] += 1 + raise + + +def aot_autograd(**kwargs: Unpack[AotAutogradKwargs]) -> AotAutograd: + return AotAutograd(**kwargs) + + +def mem_efficient_fusion_kwargs(use_decomps: bool) -> dict[str, Any]: + from functorch.compile import ( + default_decompositions, + min_cut_rematerialization_partition, + ts_compile, + ) + + kwargs = { + # these are taken from memory_efficient_fusion() + "fw_compiler": ts_compile, + "bw_compiler": ts_compile, + "partition_fn": min_cut_rematerialization_partition, + } + + if use_decomps: + # pyrefly: ignore [bad-typed-dict-key] + kwargs["decompositions"] = default_decompositions + + return kwargs + + +def fake_tensor_unsupported(fn: Callable[[Any, list[Any], Any], R]) -> Any: + """ + Decorator for backends that need real inputs. We swap out fake + tensors for zero tensors. + """ + + @functools.wraps(fn) + def wrapper(model: Any, inputs: Any, **kwargs: Any) -> Any: + with _disable_current_modes(): + inputs = list(map(defake, inputs)) + return fn(model, inputs, **kwargs) # type: ignore[call-arg] + + return wrapper + + +def device_from_inputs(example_inputs: Iterable[Any]) -> torch.device: + for x in example_inputs: + if isinstance(x, torch.Tensor): + return x.device + return torch.device("cpu") # Default fallback + + +def dtype_from_inputs(example_inputs: Iterable[Any]) -> torch.dtype: + for x in example_inputs: + if isinstance(x, torch.Tensor): + return x.dtype + return torch.float32 # Default fallback diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/cudagraphs.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/cudagraphs.py new file mode 100644 index 0000000000000000000000000000000000000000..b6af7eaa74210345e99820b8313a2bbfc6492d61 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/cudagraphs.py @@ -0,0 +1,318 @@ +""" +This module implements CUDA graphs support for TorchDynamo backends. + +CUDA graphs allow for capturing and replaying GPU operations, which can significantly +reduce CPU overhead in GPU-accelerated PyTorch models. This module provides: + +- CUDA graph creation and management for both forward and backward passes +- Input mutation detection and handling +- Device compatibility checking +- Stack trace management for debugging +- Integration with TorchInductor's cudagraph trees + +The backend supports two main modes: +1. cudagraphs: Full CUDA graph support with both forward and backward pass optimization +2. cudagraphs_inner: Lower-level CUDA graph implementation used for benchmarking + +Key components: +- CudagraphsBackend: Main backend class for CUDA graph integration +- Mutation detection utilities to ensure graph safety +- Device mapping and compatibility checks +- Stack trace collection for debugging +""" + +import functools +import logging +from collections import defaultdict +from collections.abc import Callable, Sequence +from typing import Any + +import torch +import torch.fx +from torch._dynamo import config +from torch._dynamo.backends.common import aot_autograd +from torch._dynamo.backends.debugging import boxed_nop +from torch._inductor.cudagraph_utils import ( + BoxedDeviceIndex, + check_multiple_devices_or_any_cpu_nodes, + format_default_skip_message, + get_mutation_stack_trace, + get_placeholder_info, + log_cudagraph_skip_and_bump_counter, +) +from torch._inductor.utils import ( + BoxedBool, + count_tangents, + get_first_incompatible_cudagraph_node, + num_fw_fixed_arguments, + output_node, +) +from torch.multiprocessing.reductions import StorageWeakRef + +from .registry import register_backend + + +log = logging.getLogger(__name__) + + +def find_input_mutations(g: torch.fx.Graph) -> set[int]: + def meta_fk(meta: dict[str, Any]) -> Any: + return meta["val"] if "val" in meta else meta["fake_result"] + + inputs = defaultdict(set) + input_idx = 0 + mutated_inputs = set() + for n in g.nodes: + if n.op == "placeholder": + if isinstance(meta_fk(n.meta), torch.Tensor): + inputs[StorageWeakRef(meta_fk(n.meta)._typed_storage())].add(input_idx) + input_idx += 1 + elif n.op == "call_function": + if not hasattr(n.target, "_schema"): + continue + + schema = n.target._schema + for i, arg in enumerate(schema.arguments): + if i < len(n.args): + argument = n.args[i] + else: + if arg.name not in n.kwargs: + continue + argument = n.kwargs[arg.name] + mut_arg = False + if arg.alias_info: + if arg.alias_info.is_write: + mut_arg = True + if mut_arg: + # TODO: not correct for args that contain tensors in a struct + # like list + mutated_inputs |= inputs[ + StorageWeakRef(meta_fk(argument.meta)._typed_storage()) + ] + + # TODO: error on unrecognized nodes + return mutated_inputs + + +def get_device_node_mapping( + gm: torch.fx.GraphModule, +) -> dict[torch.device, torch.fx.Node]: + device_node_mapping: dict[torch.device, torch.fx.Node] = {} + for n in gm.graph.nodes: + t = n.meta.get("val", None) + if isinstance(t, torch.Tensor) and t.device not in device_node_mapping: + device_node_mapping[t.device] = n + return device_node_mapping + + +def check_for_mutation_ignore_cuda_graph_managed_tensor( + aot_model: torch.fx.GraphModule, num_fixed: int +) -> str | None: + mutation_indices = find_input_mutations(aot_model.graph) - set(range(num_fixed)) + if not mutation_indices: + return None + + placeholders = get_placeholder_info(aot_model.graph) + return get_mutation_stack_trace(placeholders, mutation_indices) + + +def check_for_skip(aot_model: torch.fx.GraphModule, num_fixed: int) -> str | None: + if not config.cudagraph_backend_support_input_mutation: + if mut_skip := check_for_mutation_ignore_cuda_graph_managed_tensor( + aot_model, num_fixed + ): + return mut_skip + + if skip := check_multiple_devices_or_any_cpu_nodes( + get_device_node_mapping(aot_model) + ): + return skip + + if node := get_first_incompatible_cudagraph_node(aot_model): + return format_default_skip_message(f"incompatible op ({node.name})") + + return None + + +def get_device_index(gm: torch.fx.GraphModule) -> int: + device = next(iter(get_device_node_mapping(gm))) + if device.type != "cuda": + raise AssertionError(f"Expected CUDA device, got {device.type}") + return device.index + + +def get_stack_traces(gm: torch.fx.GraphModule) -> list[str | None]: + output = output_node(gm) + if len(output.args) != 1: + raise AssertionError( + f"Expected output node to have 1 arg, got {len(output.args)}" + ) + args = output.args[0] + if not hasattr(args, "__iter__"): + return [] + return [ + (arg.stack_trace if isinstance(arg, torch.fx.node.Node) else None) + for arg in args # type: ignore[union-attr] + ] + + +def cudagraphs(dynamo_model: torch.fx.GraphModule, dynamo_inputs: Sequence[Any]) -> Any: + from torch._inductor.cudagraph_trees import cudagraphify_impl + + do_cudagraphs = BoxedBool(True) + boxed_device_index = BoxedDeviceIndex(None) + + def forward_cudagraphs( + aot_model: torch.fx.GraphModule, + aot_inputs: list[Any], + is_inference: bool = False, + ) -> Any: + interp = boxed_nop(aot_model, aot_inputs) + fixed = num_fw_fixed_arguments(len(dynamo_inputs), len(aot_inputs)) + if skip_msg := check_for_skip(aot_model, fixed): + BoxedBool.disable(do_cudagraphs) + log_cudagraph_skip_and_bump_counter( + f"skipping cudagraphs due to {skip_msg}" + ) + return interp + + boxed_device_index.set(get_device_index(aot_model)) + out = cudagraphify_impl( + interp, + aot_inputs, + range(fixed), + device_index=boxed_device_index.value, + is_backward=False, + is_inference=is_inference, + stack_traces=get_stack_traces(aot_model), + placeholders=get_placeholder_info(aot_model.graph), + mutated_input_idxs=find_input_mutations(aot_model.graph), + ) + out._boxed_call = True # type: ignore[attr-defined] + return out + + def backward_cudagraphs( + aot_model: torch.fx.GraphModule, aot_inputs: list[Any] + ) -> Any: + interp = boxed_nop(aot_model, aot_inputs) + if not do_cudagraphs: + return aot_model + + fixed = count_tangents(aot_model) + if skip_msg := check_for_skip(aot_model, fixed): + log_cudagraph_skip_and_bump_counter( + f"skipping cudagraphs due to {skip_msg}" + ) + + # See [Backward Generation Handling] + device_idx = boxed_device_index.value + if device_idx is None: + device_idx = 0 # Default to device 0 if not set + manager = torch._inductor.cudagraph_trees.get_manager( + device_idx, create_if_none_exists=False + ) + if manager is None: + raise AssertionError("cudagraph manager must exist for backward") + + def fn(inputs: list[Any]) -> Any: + # pyrefly: ignore [missing-attribute] + manager.set_to_running_backward() + return aot_model(inputs) + + fn._boxed_call = True # type: ignore[attr-defined] + return fn + + out = cudagraphify_impl( + interp, + aot_inputs, + range(fixed), + device_index=get_device_index(aot_model), + is_backward=True, + is_inference=False, + stack_traces=get_stack_traces(aot_model), + placeholders=get_placeholder_info(aot_model.graph), + mutated_input_idxs=find_input_mutations(aot_model.graph), + ) + out._boxed_call = True # type: ignore[attr-defined] + return out + + aot_cudagraphs = aot_autograd( + fw_compiler=forward_cudagraphs, + bw_compiler=backward_cudagraphs, + inference_compiler=functools.partial(forward_cudagraphs, is_inference=True), + keep_inference_input_mutations=torch._dynamo.config.cudagraph_backend_keep_input_mutation, + ) + return aot_cudagraphs(dynamo_model, dynamo_inputs) + + +class CudagraphsBackend: + compiler_name = "cudagraphs" + + @staticmethod + def reset() -> None: + from torch._inductor.cudagraph_trees import reset_cudagraph_trees + + reset_cudagraph_trees() + + @staticmethod + def __call__( + model: torch.fx.GraphModule, inputs: Sequence[Any], **kwargs: Any + ) -> Any: + if kwargs: + log.warning("cudagraphs backend ignoring extra kwargs %s", kwargs) + return cudagraphs(model, inputs) + + +# aot_cudagraphs only applies CUDA graphs to the graph. It is also helpful +# for debugging and can serve as a perf baseline. +register_backend(name="cudagraphs", compiler_fn=CudagraphsBackend()) + + +def cudagraphs_inner( + model: Callable[..., Any], + inputs: Sequence[Any], + copy_outputs: bool = True, + copy_inputs: bool = True, +) -> Callable[..., Sequence[Any]]: + """This isn't registered as a backend, but is used in some benchmarks""" + if not isinstance(inputs, (list, tuple)): + raise AssertionError( + f"Expected inputs to be a list or tuple, got {type(inputs)}" + ) + if copy_inputs: + static_inputs = [torch.zeros_like(x) for x in inputs] + else: + static_inputs = list(inputs) + + # warmup + torch.cuda.synchronize() + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + model(*inputs) + stream.synchronize() + torch.cuda.current_stream().wait_stream(stream) + torch.cuda.synchronize() + + # record + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + static_outputs = model(*static_inputs) + if not isinstance(static_outputs, (list, tuple)): + static_outputs = (static_outputs,) + + def run(*new_inputs: Any) -> Sequence[Any]: + if len(static_inputs) != len(new_inputs): + raise AssertionError( + f"Expected {len(static_inputs)} inputs, got {len(new_inputs)}" + ) + if copy_inputs: + for dst, src in zip(static_inputs, new_inputs): + dst.copy_(src) + graph.replay() + if copy_outputs: + return [x.clone() for x in static_outputs] + else: + return static_outputs + + return run diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/debugging.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/debugging.py new file mode 100644 index 0000000000000000000000000000000000000000..63c9728091c92c675753b1f763312dc7647ec729 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/debugging.py @@ -0,0 +1,742 @@ +""" +This module provides debugging backends for TorchDynamo to help diagnose and troubleshoot +compilation and execution issues. It includes: + +Key Debugging Backends: +- eager: Simple pass-through backend that runs models in eager mode +- eager_noexcept: Similar to eager but with additional exception handling +- eager_debug: Adds schema validation checks for custom operators +- aot_eager: Uses AOT Autograd with nop compiler for debugging +- aot_eager_decomp_partition: Uses TorchInductor decompositions for debugging +- torchscript: Compiles using TorchScript for debugging JIT-related issues + +Testing and Development Tools: +- Backends for inducing specific errors (compile/runtime/accuracy) +- ExplainOutput class for detailed graph compilation analysis +- Utilities for cross-referencing and mode management +- Tools for graph detail inspection and break reason analysis + +These backends are primarily used for: +1. Debugging graph breaks and compilation failures +2. Testing error handling and recovery mechanisms +3. Analyzing performance bottlenecks +4. Validating operator schemas and decompositions +""" + +import dataclasses +import functools +import logging +from collections.abc import Callable, Iterable +from importlib import import_module +from typing import Any, TYPE_CHECKING + +import torch +from functorch.compile import min_cut_rematerialization_partition +from torch import _guards +from torch._dynamo.output_graph import GraphCompileReason +from torch._functorch import config as functorch_config +from torch._functorch.compilers import ts_compile +from torch._inductor.output_code import OutputCode + +from .common import aot_autograd +from .registry import CompiledFn, CompilerFn, register_debug_backend as register_backend + + +if TYPE_CHECKING: + from torch.fx.node import Target + + +log = logging.getLogger(__name__) + + +@register_backend +def eager( + gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any +) -> Callable[..., Any]: + if kwargs: + log.warning("eager backend ignoring extra kwargs %s", kwargs) + + if torch._functorch.config.force_autograd_cache: + from torch._dynamo.aot_compile_types import GraphModuleSerializableCallable + + return GraphModuleSerializableCallable(gm) + return gm.forward + + +def make_eager_backend_with_torch_function_mode( + mode: torch.overrides.TorchFunctionMode, +) -> Callable[..., Any]: + return make_eager_backend_with_torch_function_modes([mode]) + + +def make_eager_backend_with_torch_function_modes( + modes: Iterable[torch.overrides.TorchFunctionMode], +) -> Callable[..., Any]: + """Used to trace HOPs (cond and while) for eager execution, the metadata + TF mode mutates vars outside of the scope of the HOP, and we can't have graph breaks + in the HOP, so we need to externally run this mode and not trace it.""" + from contextlib import ExitStack + + def fn( + gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any + ) -> Callable[..., Any]: + def wrapper(*args: Any, **kwargs: Any) -> Any: + with ExitStack() as stack: + for mode in modes: + stack.enter_context(mode) + return gm.forward(*args, **kwargs) + + return wrapper + + return fn + + +@register_backend +def eager_noexcept( + gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any +) -> Callable[..., Any]: + if kwargs: + log.warning("eager_noexcept backend ignoring extra kwargs %s", kwargs) + + # This backend is intended to check that dynamo-generated GraphModules + # do not cause errors. + def inner(*args: Any) -> Any: + try: + return gm(*args) + except Exception as e: + raise torch._dynamo.exc.TorchDynamoException( + "Unexpected exception when running generated GraphModule" + ) from e + + return inner + + +@register_backend +def pre_dispatch_eager( + gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any +) -> torch.fx.GraphModule: + if kwargs: + log.warning("pre_dispatch_eager backend ignoring extra kwargs %s", kwargs) + + from torch.fx.experimental.proxy_tensor import make_fx + + def runnable_gm(*args: Any) -> Any: + return torch.fx.Interpreter(gm).run(*args) + + pre_dispatch_gm = make_fx(runnable_gm, pre_dispatch=True)(*fake_tensor_inputs) + pre_dispatch_gm.print_readable() + + return pre_dispatch_gm + + +@register_backend +def eager_debug( + gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any +) -> Callable[..., Any]: + if kwargs: + log.warning("eager_debug backend ignoring extra kwargs %s", kwargs) + + from torch._subclasses.schema_check_mode import SchemaCheckMode + + # We could add more debugging bits here. + # Right now, this backend can be used to check for and error on + # custom dispatcher ops that have incorrect schemas. + def inner(*args: Any) -> Any: + with SchemaCheckMode(): + return torch.fx.Interpreter(gm).run(*args) + + return inner + + +@register_backend(name="ts") # type: ignore[misc] +def torchscript( + gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor] +) -> torch.jit.ScriptModule: + from torch.fx._lazy_graph_module import _unwrap_lazy_graph_module + + return torch.jit.script(_unwrap_lazy_graph_module(gm)) + + +def invoke_subgraph_inner_compiler( + subgraph: torch.fx.GraphModule, example_inputs: list[torch.Tensor] +) -> Callable[..., Any]: + """Inner compiler that wraps forward/backward graphs in invoke_subgraph HOP. + + This is used as the fw_compiler/bw_compiler for aot_autograd. When the resulting + function is traced by make_fx, it emits an invoke_subgraph HOP instead of inlining. + """ + from torch._dynamo import disable + from torch._higher_order_ops.invoke_subgraph import invoke_subgraph_infer + + # pyrefly: ignore [deprecated] + @torch._dynamo.allow_in_graph + @disable + def invoke_subgraph_wrapper_unboxed(*operands: Any) -> Any: + return invoke_subgraph_infer(subgraph, *operands) + + # NB: The direct to unboxed path is broken, you MUST DO THIS + + def invoke_subgraph_wrapper(args: list[Any]) -> Any: + # `allow_in_graph` is untyped and its `list` branch leaks a + # `list | fn` union into the inferred return; as the outer decorator + # here that makes `invoke_subgraph_wrapper_unboxed` look non-callable. + # pyrefly: ignore [not-callable] + return invoke_subgraph_wrapper_unboxed(*args) + + invoke_subgraph_wrapper._boxed_call = True # type: ignore[attr-defined] + + return invoke_subgraph_wrapper + + +# I cannot say how many times I had to revert to this vibe coded version of +# the code, which worked, and the cleaner versions of the code did not work, +# so I'm leaving this here until we fix the rest of the bugs. +''' +# Counter for unique subgraph names in invoke_subgraph backend +_invoke_subgraph_counter = 0 + + +def invoke_subgraph_inner_compiler_good( + fx_g: torch.fx.GraphModule, example_inputs: list[torch.Tensor] +) -> Callable[..., Any]: + """Inner compiler that wraps forward/backward graphs in invoke_subgraph HOP. + + This is used as the fw_compiler/bw_compiler for aot_autograd. When the resulting + function is traced by make_fx, it emits an invoke_subgraph HOP instead of inlining. + """ + from torch._higher_order_ops.invoke_subgraph import ( + invoke_subgraph as invoke_subgraph_hop, + ) + from torch.fx.experimental.proxy_tensor import get_proxy_mode + + global _invoke_subgraph_counter + _invoke_subgraph_counter += 1 + name = f"invoke_subgraph_{_invoke_subgraph_counter}" + + from torch._dynamo import disable + + # Check if fx_g uses boxed calling convention + fx_g_is_boxed = getattr(fx_g, "_boxed_call", False) + + @disable + @torch._dynamo.allow_in_graph + def invoke_subgraph_wrapper_unboxed(*args: Any) -> Any: + proxy_mode = get_proxy_mode() + if proxy_mode is not None: + # When being traced by make_fx, emit invoke_subgraph HOP + return invoke_subgraph_hop(fx_g, name, *args) # type: ignore[arg-type] + else: + # Normal execution path - call fx_g with proper calling convention + if fx_g_is_boxed: + return fx_g(list(args)) + else: + return fx_g(*args) + + # Wrap to handle boxed arguments (list of args) as expected by AOTAutograd + def invoke_subgraph_wrapper(args: list[Any]) -> Any: + return invoke_subgraph_wrapper_unboxed(*args) + + invoke_subgraph_wrapper._boxed_call = True # type: ignore[attr-defined] + return invoke_subgraph_wrapper +''' + + +@register_backend +def invoke_subgraph( + gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any +) -> Callable[..., Any]: + """Backend that wraps forward/backward graphs in invoke_subgraph HOP when traced by make_fx. + + This backend uses AOTAutograd to partition into forward/backward graphs, then wraps + each in an invoke_subgraph HOP. This is useful for recursive Dynamo tracing scenarios + where you want the compiled subgraph to appear as invoke_subgraph HOPs in the outer + trace rather than being inlined. + + Requires: + - torch._dynamo.config.force_compile_during_fx_trace = True + (this implicitly overrides error_on_nested_fx_trace) + """ + if kwargs: + log.warning("invoke_subgraph backend ignoring extra kwargs %s", kwargs) + + # Use AOTAutograd to partition into forward/backward + return aot_autograd( + fw_compiler=invoke_subgraph_inner_compiler, + bw_compiler=invoke_subgraph_inner_compiler, + partition_fn=min_cut_rematerialization_partition, + keep_inference_input_mutations=True, + )(gm, fake_tensor_inputs) + + +@dataclasses.dataclass +class AOTEagerOutputCode(OutputCode): + """ + An OutputCode that wraps a GraphModule for eager-mode execution. + + This allows non-inductor backends (like aot_eager) to participate in + the bundled autograd cache and aot_compile serialization flow. + """ + + gm: torch.fx.GraphModule | None = None + _serialized_gm: bytes | None = dataclasses.field(default=None, init=False) + + def __call__(self, inputs: Any) -> Any: + if self.gm is None: + raise AssertionError("gm must not be None") + return self.gm.forward(inputs) + + def prepare_for_serialization(self) -> None: + from torch.fx._graph_pickler import GraphPickler, Options + + if self.gm is None: + raise AssertionError("gm must not be None") + for node in self.gm.graph.nodes: + node.meta.pop("nn_module_stack", None) + node.meta.pop("source_fn_stack", None) + node.meta.pop("example_value", None) + + self._serialized_gm = GraphPickler.dumps(self.gm, Options(ops_filter=None)) + self.gm = None + + def post_compile(self, *args: Any, **kwargs: Any) -> None: + if self.gm is None and self._serialized_gm is not None: + from torch._subclasses import FakeTensorMode + from torch.fx._graph_pickler import GraphPickler + from torch.fx.experimental.symbolic_shapes import ShapeEnv + from torch.fx.graph import _BoxedCodeGen + + fake_mode = FakeTensorMode(shape_env=ShapeEnv()) + gm = GraphPickler.loads(self._serialized_gm, fake_mode) + if not isinstance(gm, torch.fx.GraphModule): + raise AssertionError(f"Expected torch.fx.GraphModule, got {type(gm)}") + self.gm = gm + self.gm.graph.set_codegen(_BoxedCodeGen()) + self.gm.recompile() + self._serialized_gm = None + + def set_triton_bundle(self, triton_bundle: Any) -> None: + pass + + +# used boxed call to discard inputs when they are no longer needed +def boxed_nop( + fx_g: torch.fx.GraphModule, example_inputs: list[torch.Tensor] +) -> Callable[..., Any]: + from torch.fx.graph import _BoxedCodeGen + + # Set the graph to use boxed codegen + fx_g.graph.set_codegen(_BoxedCodeGen()) + fx_g.recompile() + + if functorch_config.force_autograd_cache or functorch_config.bundled_autograd_cache: + result = AOTEagerOutputCode(gm=fx_g) + result._boxed_call = True # type: ignore[attr-defined] + return result + + # Wrap the forward method in a function so we can set _boxed_call attribute + forward_fn = fx_g.forward + + def run(args: Any) -> Any: + from torch.utils._debug_mode import DebugInterpreter, get_active_debug_mode + + if ( + debug_mode := get_active_debug_mode() + ) is not None and debug_mode.run_compile_with_interpreter: + return DebugInterpreter(fx_g, backend="aot_eager").run(*args) + return forward_fn(args) + + run._boxed_call = True # type: ignore[attr-defined] + return run + + +def boxed_nop_with_mode( + fx_g: torch.fx.GraphModule, + example_inputs: list[torch.Tensor], + *, + mode: torch.overrides.TorchFunctionMode, +) -> Callable[..., Any]: + from torch.fx.graph import _BoxedCodeGen + + # Set the graph to use boxed codegen + fx_g.graph.set_codegen(_BoxedCodeGen()) + fx_g.recompile() + + # Create a wrapper that runs with the mode + forward_fn = fx_g.forward + + def run(args: Any) -> Any: + with mode: + return forward_fn(args) + + run._boxed_call = True # type: ignore[attr-defined] + return run + + +def fake_crossref_boxed_nop( + fx_g: torch.fx.GraphModule, + example_inputs: list[torch.Tensor], + ignore_op_fn: Callable[[torch._ops.OpOverload], bool] | None = None, +) -> Callable[..., Any]: + from torch.fx.graph import _BoxedCodeGen + + # Set the graph to use boxed codegen + fx_g.graph.set_codegen(_BoxedCodeGen()) + fx_g.recompile() + + # Create a wrapper that runs with the mode + forward_fn = fx_g.forward + + def run(args: Any) -> Any: + with torch._subclasses.CrossRefFakeMode(ignore_op_fn): + return forward_fn(args) + + run._boxed_call = True # type: ignore[attr-defined] + return run + + +def ignore_builtins(op: torch._ops.OpOverload) -> bool: + return op.namespace in ("aten", "prims", "prim") + + +def get_nop_func() -> Callable[ + [torch.fx.GraphModule, list[torch.Tensor]], Callable[..., Any] +]: + if not torch._functorch.config.fake_tensor_crossref: + return boxed_nop + elif torch._functorch.config.fake_tensor_crossref == "all": + return fake_crossref_boxed_nop + else: + if torch._functorch.config.fake_tensor_crossref != "custom_ops": + raise AssertionError( + f"Expected fake_tensor_crossref to be 'custom_ops', " + f"got {torch._functorch.config.fake_tensor_crossref!r}" + ) + return functools.partial(fake_crossref_boxed_nop, ignore_op_fn=ignore_builtins) + + +# Useful for debugging purpose +# aot_eager uses AOT Autograd backend with nop compiler. It is helpful in debugging. +def aot_eager( + gm: torch.fx.GraphModule, + fake_tensor_inputs: list[torch.Tensor], + fw_compiler: Callable[..., Any] | None = None, + bw_compiler: Callable[..., Any] | None = None, + **kwargs: Any, +) -> Callable[..., Any]: + return aot_autograd( + fw_compiler=fw_compiler or boxed_nop, + bw_compiler=bw_compiler or boxed_nop, + partition_fn=min_cut_rematerialization_partition, + keep_inference_input_mutations=True, + )(gm, fake_tensor_inputs, **kwargs) + + +register_backend(name="aot_eager", compiler_fn=aot_eager) + +aot_eager_default_partitioner = aot_autograd( + fw_compiler=boxed_nop, keep_inference_input_mutations=True +) +register_backend( + name="aot_eager_default_partitioner", compiler_fn=aot_eager_default_partitioner +) + + +# Uses TorchInductor AOT Autograd decomps and partitioner to isolate aot vs +# inductor problems. +# aot_eager_decomp_partition just replaces the inductor compiler with nop to help +# isolate inductor vs aot_eager errors +def aot_eager_decomp_partition( + gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any +) -> Callable[..., Any]: + if kwargs: + log.warning( + "aot_eager_decomp_partition backend ignoring extra kwargs %s", kwargs + ) + + from torch._inductor.compiler_bisector import CompilerBisector + + config_patches = {"unlift_effect_tokens": True} + if bisect_changes := CompilerBisector.get_config_change( + "aot_eager_decomp_partition" + ): + config_patches.update(bisect_changes) # type: ignore[arg-type] + + with functorch_config.patch(config_patches): + return aot_autograd( + # these are taken from memory_efficient_fusion() + fw_compiler=get_nop_func(), + bw_compiler=get_nop_func(), + # NB: lambda here is to delay import of inductor + decompositions=lambda: import_module( + "torch._inductor.compile_fx" + ).select_decomp_table(), + partition_fn=functools.partial( + min_cut_rematerialization_partition, compiler="inductor" + ), + )(gm, fake_tensor_inputs) + + +register_backend( + name="aot_eager_decomp_partition", compiler_fn=aot_eager_decomp_partition +) + + +# aot_eager_decomp_partition_with_mode is similar as aot_eager_decomp_partition, +# except that it takes a TorchDispatchMode mode and run the fw/bw in the mode +def aot_eager_decomp_partition_with_mode( + gm: torch.fx.GraphModule, + fake_tensor_inputs: list[torch.Tensor], + mode: Any, + **kwarg: Any, +) -> Callable[..., Any]: + return aot_autograd( + # these are taken from memory_efficient_fusion() + fw_compiler=functools.partial(boxed_nop_with_mode, mode=mode), + bw_compiler=functools.partial(boxed_nop_with_mode, mode=mode), + # NB: lambda here is to delay import of inductor + decompositions=lambda: import_module( + "torch._inductor.compile_fx" + ).select_decomp_table(), + partition_fn=functools.partial( + min_cut_rematerialization_partition, compiler="inductor" + ), + )(gm, fake_tensor_inputs) + + +register_backend( + name="aot_eager_decomp_partition_with_mode", + compiler_fn=aot_eager_decomp_partition_with_mode, # type: ignore[arg-type] +) + + +def aot_eager_decomp_partition_crossref( + gm: torch.fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], **kwargs: Any +) -> Callable[..., Any]: + # if the config is set, respect it, otherwise only test custom_ops. + # custom_op bad metas always manifest as an error whereas aten will only sometimes. + # by default, use the less noisy option + config_val = ( + "custom_ops" + if not functorch_config.fake_tensor_crossref + else functorch_config.fake_tensor_crossref + ) + with functorch_config.patch(fake_tensor_crossref=config_val): + return aot_eager_decomp_partition(gm, fake_tensor_inputs, **kwargs) + + +register_backend( + name="aot_eager_decomp_partition_crossref", + compiler_fn=aot_eager_decomp_partition_crossref, +) + + +# AOT Autograd with torchscript backend. Default partitioner. +# aot_ts uses torchscript backend. We can use this with both nnc and nvfuser +# by using the relevant fuser with torch.jit.fuser(...) +aot_ts = aot_autograd(fw_compiler=ts_compile) +register_backend(name="aot_ts", compiler_fn=aot_ts) + +# These buggy backends are used for inducing bugs so that we can test +# our repro extraction / minifier scripts + + +class ReluCompileError(Exception): + pass + + +class TestingOnlyCompileError(Exception): + pass + + +@register_backend +def relu_compile_error_TESTING_ONLY( + gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] +) -> torch.fx.GraphModule: + for node in gm.graph.nodes: + if node.target is torch.relu: + raise ReluCompileError + return gm + + +@register_backend +def relu_runtime_error_TESTING_ONLY( + gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] +) -> torch.fx.GraphModule: + for node in gm.graph.nodes: + if node.target is torch.relu: + node.target = torch._assert + node.args = (False, "ReluRuntimeError") + gm.recompile() + return gm + + +@register_backend +def relu_accuracy_error_TESTING_ONLY( + gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] +) -> torch.fx.GraphModule: + for node in gm.graph.nodes: + if node.target is torch.relu: + node.target = torch.add + node.args = (node.args[0], 1) + gm.recompile() + + return gm + + +@register_backend +def non_leaf_compile_error_TESTING_ONLY( + gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] +) -> torch.fx.GraphModule: + # Require at least one non-trivial thing in the graph, + # see https://github.com/pytorch/pytorch/issues/102898 + for node in gm.graph.nodes: + if node.op == "call_function": + break + else: + return gm + for t in example_inputs: + if not t.is_leaf: + raise TestingOnlyCompileError + return gm + + +@dataclasses.dataclass +class ExplainOutput: + """ + This is the output of :func:`torch._dynamo.explain()` + There is no reason to create this class directly. + """ + + graphs: list[torch.fx.GraphModule] + graph_count: int + graph_break_count: int + break_reasons: list[GraphCompileReason] + op_count: int + ops_per_graph: list[list["Target"]] | None = None + out_guards: list[_guards.Guard] | None = None + compile_times: str | None = None + + def __str__(self) -> str: + output = f"Graph Count: {self.graph_count}\n" + output += f"Graph Break Count: {self.graph_break_count}\n" + output += f"Op Count: {self.op_count}\n" + + output += "Break Reasons:\n" + for idx, break_reason in enumerate(self.break_reasons): + output += f" Break Reason {idx + 1}:\n" + output += f" Reason: {break_reason.reason}\n" + output += " User Stack:\n" + for frame_summary in break_reason.user_stack: + output += f" {frame_summary}\n" + + if self.ops_per_graph is not None: + output += "Ops per Graph:\n" + for idx, ops in enumerate(self.ops_per_graph): + output += f" Ops {idx + 1}:\n" + for op in ops: + output += f" {op}\n" + + if self.out_guards is not None: + output += "Out Guards:\n" + for i, guard in enumerate(self.out_guards): + output += f" Guard {i + 1}:\n" + output += f" {str(guard)}" + + if self.compile_times is not None: + output += f"Compile Times: {self.compile_times}\n" + return output + + +def _explain_graph_detail( + gm: torch.fx.GraphModule, + graphs: list[torch.fx.GraphModule], + op_count: int, + ops_per_graph: list[list["Target"]], + break_reasons: list[GraphCompileReason], +) -> tuple[ + torch.fx.GraphModule, + list[torch.fx.GraphModule], + int, + list[list["Target"]], + list[GraphCompileReason], +]: + """ + This function is a utility which processes a torch.fx.GraphModule and + accumulates information about its ops, graph breaks, and other details. It + is intended to be used by the ExplainWithBackend class and + `torch._dynamo.explain()` to provide details from Dynamo's graph capture. + + Parameters: + gm (torch.fx.GraphModule): The GraphModule to be processed. + graphs (list): A list that accumulates all the GraphModules processed. + op_count (int): The total count of operations in all GraphModules processed so far. + ops_per_graph (list): A list that accumulates the operations of each GraphModule. + break_reasons (list): A list that accumulates the reasons for breaks in each GraphModule. + + Returns: + tuple: A tuple containing the processed GraphModule, the updated lists of graphs, + operations per graph, and break reasons, and the updated operation count. + """ + graphs.append(gm) + ops = [node.target for node in gm.graph.nodes if node.op == "call_function"] + op_count += len(ops) + ops_per_graph.append(ops) + if gm.compile_subgraph_reason.graph_break: # type: ignore[union-attr] + break_reasons.append(gm.compile_subgraph_reason) # type: ignore[arg-type] + + return gm, graphs, op_count, ops_per_graph, break_reasons + + +class ExplainWithBackend: + """ + This class is intended to be used as a backend for `torch.compile`. It is + composable with other backends. When used in this way, it accumulates + information about graph breaks, ops, and other info and provides a string + representation summarizing this information. + + Attributes: + backend (str): The name of the backend to use for optimization. + graphs (list): A list of the graphs captured by TorchDynamo. + op_count (int): The total number of operations in all optimized graphs. + break_reasons (list): A list of graph break reasons with stack traces. + + Example Usage: + def fn(x): + x = torch.sigmoid(x) + return x + + torch._dynamo.reset() + eb = ExplainWithBackend("inductor") + optimized_fn = torch.compile(fn, backend=eb) + result = optimized_fn(torch.randn(5)) + print(eb.output()) + """ + + def __init__(self, backend: CompilerFn | str) -> None: + from .registry import lookup_backend + + self.backend = lookup_backend(backend) + self.graphs: list[torch.fx.GraphModule] = [] + self.op_count = 0 + self.break_reasons: list[GraphCompileReason] = [] + + def __call__( + self, gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] + ) -> CompiledFn: + ops_per_graph: list[list[Target]] = [] + gm, self.graphs, self.op_count, _, self.break_reasons = _explain_graph_detail( + gm, self.graphs, self.op_count, ops_per_graph, self.break_reasons + ) + return self.backend(gm, example_inputs) + + def output(self) -> ExplainOutput: + graph_count = len(self.graphs) + output = ExplainOutput( + self.graphs, + graph_count, + graph_count - 1, + self.break_reasons, + self.op_count, + ) + + return output diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/distributed.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..f09ce836273288eb345cb86f1afae3d1cd0f32af --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/distributed.py @@ -0,0 +1,647 @@ +""" +This module implements distributed training optimizations for TorchDynamo backends. + +It provides functionality to optimize models wrapped in DistributedDataParallel (DDP) +by intelligently splitting compiled graphs to align with DDP's gradient synchronization +boundaries. Key features include: + +- Graph partitioning based on parameter bucket sizes +- Optimization of allreduce operations for distributed training +- Support for parameter ignoring and buffer handling +- Submodule compilation and management +- Debugging utilities for distributed training + +The main component is the DDPOptimizer class, which handles graph splitting and +recompilation to enable efficient distributed training while maintaining the benefits +of compilation. +""" + +import logging +import traceback +from collections.abc import Callable +from dataclasses import dataclass, field +from typing import Any, TYPE_CHECKING +from unittest import mock + +import torch +from torch import fx +from torch._dynamo.backends.registry import CompiledFn, CompilerFn +from torch._dynamo.output_graph import GraphCompileReason +from torch._dynamo.utils import deepcopy_to_fake_tensor, detect_fake_mode +from torch._logging import trace_structured +from torch.fx.node import Node + + +if TYPE_CHECKING: + from torch._functorch._aot_autograd.schemas import ViewAndMutationMeta + + +# Regular log messages should go through 'log'. +# ddp_graph_log is a separate artifact logger reserved for dumping graphs. +# See docs/source/logging.rst for more info. +log = logging.getLogger(__name__) +ddp_graph_log = torch._logging.getArtifactLogger(__name__, "ddp_graphs") + + +def args_str(args: Any) -> str: + # a debug helper + if torch.is_tensor(args): + return f"T[{args.shape}]" + elif isinstance(args, tuple): + return f"tuple({', '.join([args_str(x) for x in args])})" + elif isinstance(args, list): + return f"list({', '.join([args_str(x) for x in args])})" + else: + return str(args) + + +@dataclass +class Bucket: + size: int = 0 + params: list[str] = field(default_factory=list) + nodes: list[fx.Node] = field(default_factory=list) + + # param_ids is just used for unit testing + param_ids: list[int] = field(default_factory=list) + + # keep track of any buckets that were extended for logging purposes + opcount_increased_to_capture_external_output: int = 0 + paramsize_before_opcount_increase: int = 0 + + +def bucket_has_external_output(bucket: Bucket) -> bool: + nodes_in_bucket = set() + # we want to iterate in reverse order, but clumsi-luckily the bucket.nodes list was already created backwards + # so we don't reverse it here + for node in bucket.nodes: + # assume node.op != output, since those are filtered in the original iteration + nodes_in_bucket.add(node) + for user in node.users: + if user not in nodes_in_bucket: + return True + return False + + +def pretty_print_buckets(buckets: list[Bucket], bucket_bytes_cap: int) -> None: + headers = ("Index", "Size (b)", "Param Names") + rows: list[tuple[int | None, int | None, str]] = [] + # pyrefly: ignore [implicit-any] + extended_buckets = [] + for idx, bucket in enumerate(reversed(buckets)): + if len(bucket.params) > 0: + rows.append((idx, bucket.size, bucket.params[0])) + rows.extend((None, None, param) for param in bucket.params[1:]) + if bucket.opcount_increased_to_capture_external_output > 0: + extended_buckets.append( + ( + idx, + bucket.opcount_increased_to_capture_external_output, + bucket.size - bucket.paramsize_before_opcount_increase, + ) + ) + + if rows: + log.info( + "\nDDPOptimizer used bucket cap %s and created %d buckets. Enable debug logs for detailed bucket info.", + bucket_bytes_cap, + len(buckets), + ) + + if extended_buckets: + log.warning( + "Some buckets were extended beyond their requested parameter capacities" + " in order to ensure each subgraph has an output node, required for fx graph partitioning." + " This can be the case when a subgraph would have only contained nodes performing inplace mutation," + " and returning no logical outputs. This should not be a problem, unless it results in too few graph" + " partitions for optimal DDP performance." + ) + + try: + from tabulate import tabulate + + log.debug( + "\nDDPOptimizer produced the following bucket assignments:\n%s", + tabulate(rows, headers=headers, tablefmt="simple_grid"), + ) + + if extended_buckets: + log.warning( + "DDPOptimizer extended these buckets to ensure per-subgraph output nodes:\n%s", + tabulate( + extended_buckets, + headers=("Index", "Extra Ops", "Extra Param Size (b)"), + tablefmt="simple_grid", + ), + ) + except ImportError: + log.debug( + "Please `pip install tabulate` in order to display ddp bucket sizes and diagnostic information." + ) + else: + log.debug("DDPOptimizer captured no parameters and did not split this graph.") + + +def has_higher_order_op(gm: fx.GraphModule) -> bool: + # Check if there is a higher order op in the graph + for node in gm.graph.nodes: + if node.op == "get_attr": + maybe_param = getattr(gm, node.target) + if isinstance(maybe_param, torch.fx.GraphModule): + return True + return False + + +def propagate_metadata(orig_gm: fx.GraphModule, split_gm: fx.GraphModule) -> None: + # Only propagate to partition submodules, not to HOP body subgraphs (e.g. + # wrap_body_*) which are also hoisted as top-level children by split_module + # and carry their own metadata (e.g. _checkpoint_context_fn for SAC). + partition_names = split_gm.meta["partition_names"] + for name, module in split_gm.named_modules(): + if name in partition_names: + # TODO: add split id to CompileId: https://github.com/pytorch/tlparse/pull/83/files#r1880649384 + module.meta = orig_gm.meta + module._param_name_to_source = orig_gm._param_name_to_source + + +def propagate_dynamo_source(orig_gm: fx.GraphModule, split_gm: fx.GraphModule) -> None: + name_to_dynamo_source = {} + for node in orig_gm.graph.find_nodes(op="placeholder"): + name_to_dynamo_source[node.name] = node._dynamo_source + + partition_names = split_gm.meta["partition_names"] + for name, module in split_gm.named_modules(): + if name in partition_names: + for node in module.graph.find_nodes(op="placeholder"): + # non-placeholder in original_gm may become placeholder in submodules + node._dynamo_source = name_to_dynamo_source.get(node.name) + + +class DDPOptimizerContext: + def __init__(self) -> None: + self.curr_bucket: int = -1 + self.metadata_per_bucket: list[ViewAndMutationMeta] = [] + + +# compile each of the partitioned submodules using the user-provided compiler +class SubmodCompiler(torch.fx.interpreter.Interpreter): + def __init__( + self, + module: fx.GraphModule, + compiler: CompilerFn, + fake_mode: torch._subclasses.fake_tensor.FakeTensorMode, + **compiler_configs: Any, + ) -> None: + super().__init__(module) + self.compiler = compiler + self.compiler_configs = compiler_configs + self.fake_mode = fake_mode + # See Note [DDPOptimizer and fw_metadata] + ctx = torch._guards.TracingContext.try_get() + if ctx is not None: + ctx.ddp_optimizer_ctx = DDPOptimizerContext() + + def compile_submod( + self, input_mod: fx.GraphModule, args: list[torch.Tensor], kwargs: Any + ) -> Any: + """ + Compile the submodule, + using a wrapper to make sure its output is always a tuple, + which is required by AotAutograd based compilers + """ + if len(kwargs) != 0: + raise AssertionError("We assume only args for these modules") + + class WrapperModule(torch.nn.Module): + def __init__( + self, submod: Callable[..., Any], unwrap_singleton_tuple: bool + ) -> None: + super().__init__() + self.submod = submod + self.unwrap_singleton_tuple = unwrap_singleton_tuple + + def forward(self, *args: Any) -> Any: + x = self.submod(*args) + # TODO(whc) + # for some reason the isinstance check is necessary if I split one node per submod + # - even though I supposedly wrapped the output in a tuple in those cases, the real + # compiled module was still returning a tensor + if self.unwrap_singleton_tuple and isinstance(x, (tuple, list)): + return x[0] + return x + + unwrap_singleton_tuple = False + for sn in input_mod.graph.nodes: + if sn.op == "output": + if not isinstance(sn.args[0], tuple): + unwrap_singleton_tuple = True + sn.args = (sn.args,) + + input_mod.recompile() + input_mod.compile_subgraph_reason = GraphCompileReason( # type: ignore[assignment] + "DDPOptimizer intentional graph-break (See Note [DDPOptimizer])." + " Set `torch._dynamo.config.optimize_ddp = False` to disable.", + [ + # it's close to useless to get a real stacktrace here, and quite verbose. + traceback.FrameSummary(__file__, 0, "DDPOptimizer"), + ], + ) + + wrapper = WrapperModule( + self.compiler(input_mod, args, **self.compiler_configs), + unwrap_singleton_tuple, + ) + return wrapper + + # Note: + # + # The way distributed works today around fake tensors can be somewhat confusing. + # Some of these codepaths are shared in both runtime, and compile time. The presence + # of a fake_mode, read off of fake tensor inputs, dictates how we will operate. + # + # A few things to keep in mind: + # + # 1) We invoke `compile_submod` with a real module. The output of that gets stored + # on the graph via `self.module.add_submodule(n.target, compiled_submod_real)`. + # + # 2) When running a call_module targeted node, if we have a fake_mode, we fakify the + # module we got from self.fetch_attr(n.target). Regardless of fake_mode, we then execute it. + # + # 3) Fake tensors should always be around during compile time. + # + # 4) Fake tensors should never be around at runtime. + # + # 5) We end up with a compilation mode that takes a real submodule and fake tensors, + # to match what aot_autograd expects. See Note: [Fake Modules and AOTAutograd] + def run_node(self, n: Node) -> Any: + args, kwargs = self.fetch_args_kwargs_from_env(n) + new_args = [] + if not self.fake_mode: + raise AssertionError("fake_mode must be set") + for arg in args: + if isinstance(arg, torch.Tensor) and not isinstance( + arg, torch._subclasses.FakeTensor + ): + new_args.append(torch._dynamo.utils.to_fake_tensor(arg, self.fake_mode)) + else: + new_args.append(arg) + + log.debug("run_node %s, %s got args %s", n.op, n.target, args_str(args)) + if not isinstance(args, tuple): + raise AssertionError(f"Expected args to be a tuple, got {type(args)}") + if not isinstance(kwargs, dict): + raise AssertionError(f"Expected kwargs to be a dict, got {type(kwargs)}") + + if n.op == "call_module": + real_mod = self.fetch_attr(str(n.target)) + if self.fake_mode: + curr_submod = deepcopy_to_fake_tensor(real_mod, self.fake_mode) + else: + curr_submod = real_mod + + ddp_graph_log.debug("\n---%s graph---\n%s", n.target, curr_submod.graph) + + # When calling the compiler on the submod, inputs (new_args) are expected to + # be FakeTensors already since Dynamo would have made them FakeTensors in the + # non-DDP flow. However, the parameters are _not_ expected to be FakeTensors, + # since this wrapping happens during compilation + + # Note: Returning Fake Tensors on First AOT Autograd Call + # + # Inductor will optimize strides of outputs when it deems it profitable. + # For instance, converting to channels last. When we split the graph here + # into multiple inductor compilations, we need to make sure that the + # output strides of one compilation is appropriately passed to the subsequent + # compilations. However, the mapping from inductor output to dynamo output + # is non-trivial due to aot_autograd's deduping, de-aliasing, mutation, re-writing, + # subclass handling, etc. In order to replay all this logic we set a flag such that + # the first invocation of inductor in aot_autograd will return Fake Tensors with + # appropriate strides. Then, all of aot autograd's runtime logic is replayed. + # This gives us the appropriately strided outputs here which will reflect runtime strides. + + class FakeifyFirstAOTInvocationGuard: + def __init__(self) -> None: + self.tc = torch._guards.TracingContext.try_get() + if not self.tc: + raise AssertionError("TracingContext must be set") + self.tc.fakify_first_call = True + + def __del__(self) -> None: + self.tc.fakify_first_call = False # type: ignore[union-attr] + + # For aot_eager and other backends, tracing context is not set + has_tracing_context = torch._guards.TracingContext.try_get() is not None + if has_tracing_context: + g = FakeifyFirstAOTInvocationGuard() # noqa: F841 + + from torch._dynamo.utils import counters + + init = counters["aot_autograd"]["total"] + compiled_submod_real = self.compile_submod(real_mod, new_args, kwargs) + + # TODO - better way of doing this? + # Only aot autograd handles fakifying first call + invoked_aot_autograd = init != counters["aot_autograd"]["total"] + + # We update the original (outer) graph with a call into the compiled module + # instead of the uncompiled one. + self.module.delete_submodule(n.target) # type: ignore[operator] + n.target = "compiled_" + n.target # type: ignore[operator] + self.module.add_submodule(n.target, compiled_submod_real) # type: ignore[operator] + + # Finally, we have to produce inputs for use compiling the next submodule, + # and these need to be FakeTensors, so we execute the module under fake_mode + # Because parameters are not fake we patch fake tensor mode to allow non fake inputs + with ( + self.fake_mode, + mock.patch.object(self.fake_mode, "allow_non_fake_inputs", True), + ): + if has_tracing_context and invoked_aot_autograd: + tracing_ctx = torch._guards.TracingContext.try_get() + if tracing_ctx is None: + raise AssertionError("TracingContext must not be None") + # DDPOptimizer maintains 1 dynamo graph -> N AOT graphs + # Dynamo only has 1 tracing context, so it needs to maintain all N AOT metadata instances + ddp_ctx = tracing_ctx.ddp_optimizer_ctx + if ddp_ctx is None: + raise AssertionError("ddp_optimizer_ctx must not be None") + if tracing_ctx.fw_metadata is None: + raise AssertionError("fw_metadata must not be None") + ddp_ctx.curr_bucket += 1 + ddp_ctx.metadata_per_bucket.append(tracing_ctx.fw_metadata) + + out = compiled_submod_real(*new_args, **kwargs) + # output should be fake or subclass + if not all( + (not isinstance(t, torch.Tensor) or type(t) is not torch.Tensor) + for t in (out if isinstance(out, (list, tuple)) else [out]) + ): + raise AssertionError( + "Output should be fake or subclass, not plain torch.Tensor" + ) + return out + else: + return curr_submod(*new_args, **kwargs) + else: + # placeholder or output nodes don't need to get compiled, just executed + return getattr(self, n.op)(n.target, new_args, kwargs) + + +class DDPOptimizer: + """Note [DDPOptimizer] + DDPOptimizer applies when dynamo compiles models wrapped in DistributedDataParallel (DDP), + breaking the dynamo graph into chunks to compile separately, with the breaks aligning to + the boundaries of gradient-allreduce buckets chosen by DDP. + + Background/Motivation + - DDP uses allreduce collectives to synchronize partial gradients computed on different workers + - DDP groups gradient allreduces into 'buckets' to optimize communication efficiency of all-reduce + - Parameters grouped into buckets are assumed to be adjacent in time, so they become ready + at around the same time during backward and thus can share the same allreduce efficiently + - Allreduces must overlap with backward compute for optimal training performance + - DDP schedules allreduces using 'hooks' fired from the c++ autograd engine in pytorch, which + operates when individual grads become 'ready' + - Dynamo+AOTAutograd produces a single fused graph that runs 'atomically' from the perspective of the + autograd engine, such that all gradients become 'ready' at the same time. Hooks fire after the whole + fused backward function executes, preventing any overlap of compute and communication + + Algorithm + - DDPOptimizer starts off with an FX graph traced by dynamo which represents forward. It can traverse + this graph in reverse order to determine the true order that gradients will become ready during backward. + - Parameter sizes are counted in reverse order, up to a bucket size limit, at which point a new bucket is started + and a graph break introduced + - Each of the subgraphs is compiled by the compiler provided to dynamo by the user, and then fused back together + into an outer module that is returned to the user + + Notes + - It would be better to enforce (by adding an API to DDP) that the bucket splits chosen here are used by DDP, + and that DDP does not need to detect or optimize bucket order by observing execution at runtime, as it does + in eager. + - If Dynamo can't capture a whole graph for the portion of the model wrapped by DDP, this algorithm will currently + produce splits that do not necessarily align with the buckets used by DDP. This should result in performance + degradation approaching the baseline case where graph-splits are not used, but not worse. + - If the backend compiler fails to compile a single subgraph, it will execute eagerly despite the rest of the + subgraphs being compiled + - DDP has a 'parameters_and_buffers_to_ignore' field, which DDPOptimizer attempts to honor by reading markers + left by DDP on individual parameters. In cases where other transformations, such as reparameterization, are + also used, the ignore markers could be lost. If DDPOptimizer fails to ignore a parameter ignored by DDP, + it is not catastrophic but could impact performance by choosing sub-optimal bucket splits. + - DDPOptimizer always ignores all buffers, regardless of their ignore flag, since buffers do not require gradients, + and therefore aren't allreduced by DDP. (They are broadcast during forward, but this is not covered by + DDPOptimizer) + + Debugging + - Generally, it is easiest to debug DDPOptimizer in a single process program, using pdb. + - In many cases, the log messages are helpful (they show bucket size assignments)- + just set TORCH_LOGS env to include any of 'dynamo', 'distributed', or 'dist_ddp'. + - See `benchmarks/dynamo/distributed.py` for a simple harness that will run a toy model or a torchbench model + in a single process (or with torchrun, in multiple processes) + + Args: + bucket_bytes_cap (int): Controls the size of buckets, in bytes, used to determine graphbreaks. Should be + set to match the equivalent parameter on the original DDP module. + + backend_compile_fn (callable): A dynamo compiler function, to be invoked to compile each subgraph. + + first_bucket_cap (int): Controls the size of the first bucket. Should match DDP's first bucket cap. DDP + special-cases the first bucket size since it is sometimes optimal to start a small allreduce early. + + """ + + def __init__( + self, + bucket_bytes_cap: int, + backend_compile_fn: CompilerFn, + first_bucket_cap: int | None = None, + ) -> None: + if first_bucket_cap is not None: + self.first_bucket_cap = first_bucket_cap + elif torch.distributed.is_available(): + # this constant comes from C10D lib which is not always built + self.first_bucket_cap = torch.distributed._DEFAULT_FIRST_BUCKET_BYTES + else: + self.first_bucket_cap = bucket_bytes_cap + + self.bucket_bytes_cap = bucket_bytes_cap + if self.first_bucket_cap > self.bucket_bytes_cap: + raise AssertionError( + "First bucket should be smaller/equal to other buckets to get comms warmed up ASAP" + ) + + self.backend_compile_fn = backend_compile_fn + + def _ignore_parameter(self, parameter: torch.nn.Parameter) -> bool: + return hasattr(parameter, "_ddp_ignored") and parameter._ddp_ignored + + def add_param(self, bucket: Bucket, param: torch.nn.Parameter, name: str) -> None: + bucket.size += param.untyped_storage().nbytes() + bucket.params.append(name) + bucket.param_ids.append(id(param)) + + def add_module_params_to_bucket( + self, + mod: torch.nn.Module, + bucket: Bucket, + processed_modules: set[torch.nn.Module], + prefix: str, + ) -> None: + processed_modules.add(mod) + for name, param in mod.named_parameters(): + if param.requires_grad and not self._ignore_parameter(param): + self.add_param(bucket, param, f"{prefix}_{name}") + + def add_param_args(self, bucket: Bucket, node: fx.Node) -> None: + for arg in node.args: + if not isinstance(arg, torch.fx.node.Node): + continue + if arg.op != "placeholder": + continue + param = arg.meta["example_value"] + if ( + isinstance(param, torch.nn.Parameter) + and param.requires_grad + and not self._ignore_parameter(param) + ): + self.add_param(bucket, param, str(arg.target)) + + def compile_fn( + self, + gm: fx.GraphModule, + example_inputs: list[torch.Tensor], + **compiler_configs: Any, + ) -> CompiledFn: + """ + Implements graph splitting, first determining a set of buckets by counting + parameter sizes in reverse graph order, then invoking the user/backend compiler + to compile each subgraph. Finally, stitches compiled graphs into one graphmodule + and returns its callable. + """ + # 1: compute the partition map according to DDP bucket logic + buckets = [Bucket()] # (size, param_names) + processed_modules: set[torch.nn.Module] = set() + for node in reversed(gm.graph.nodes): + if node.op in ("output", "placeholder"): + continue + + if ( + buckets[0].size >= self.bucket_bytes_cap + or len(buckets) == 1 + and buckets[0].size >= self.first_bucket_cap + ): + if bucket_has_external_output(buckets[0]): + buckets.insert(0, Bucket()) + else: + # continue building this bucket past the point of filling its parameter capacity, + # to increase chances it contains at least one node that is either a global output or + # passed as input to a subsequent graph + + if buckets[0].opcount_increased_to_capture_external_output == 0: + buckets[0].paramsize_before_opcount_increase = buckets[0].size + buckets[0].opcount_increased_to_capture_external_output += 1 + + if node.op == "call_function": + self.add_param_args(buckets[0], node) + + elif node.op == "call_module": + target_mod = gm.get_submodule(node.target) + if target_mod not in processed_modules: + self.add_module_params_to_bucket( + target_mod, buckets[0], processed_modules, node.target + ) + elif node.op == "call_method": + if isinstance(node.args[0].target, str): + target_mod = None + try: + target_mod = gm.get_submodule(node.args[0].target) + except AttributeError: + pass + if target_mod is not None and target_mod not in processed_modules: + self.add_module_params_to_bucket( + target_mod, buckets[0], processed_modules, node.target + ) + # This handles situations like tmp = torch.mm(x, self.weight.t()) + # t: "f32[512, 512]" = l_self_seq_2_weight.t(); l_self_seq_2_weight = None + # tmp: "f32[512, 512]" = torch.mm(input_2, t); input_2 = t = None + self.add_param_args(buckets[0], node) + + elif node.op == "get_attr": + maybe_param = getattr(gm, node.target) + if ( + isinstance(maybe_param, torch.nn.Parameter) + and maybe_param.requires_grad + and not self._ignore_parameter(maybe_param) + ): + self.add_param(buckets[0], maybe_param, node.target) + + # All nodes have to be mapped to a bucket, even if they don't have their own params + # Ignored params still end up in buckets, we just don't count them towards the capacity + buckets[0].nodes.append(node) + + if len(buckets) > 1 and buckets[0].size == 0: + # we collected a small preamble graph with ops that don't include parameters, fuse it back + buckets[1].nodes.extend(buckets[0].nodes) + if len(buckets[0].params) != 0: + raise AssertionError("Params should be empty if size is 0") + del buckets[0] + + # stash buckets for testing/debugging purposes + self.buckets = buckets + pretty_print_buckets(buckets, self.bucket_bytes_cap) + + if len(buckets) == 1: + # bypass split/fuse logic if there is only one bucket + return self.backend_compile_fn(gm, example_inputs, **compiler_configs) + + # 2: partition the graphmodule according to bucket capacity + partition_map = {} + for idx, b in enumerate(buckets): + for node in b.nodes: + partition_map[node] = idx + + split_gm = fx.passes.split_module.split_module( + gm, + None, # type: ignore[arg-type] + lambda node: partition_map[node], + ) + + # See note [Assumption on Dynamo Metadata] + propagate_dynamo_source(gm, split_gm) + propagate_metadata(gm, split_gm) + + debug_str = ( + f"\n---orig graph---\n{gm.graph}\n" + + f"\n---split graph---\n{split_gm.graph}\n" + ) + for name, module in split_gm.named_modules(): + if "." not in name and len(name): + # only print the submod graphs, not their children + debug_str += f"\n---{name} graph---\n{module.graph}\n" + debug_str += "\n---------------\n" + ddp_graph_log.debug(debug_str) + + trace_structured( + "optimize_ddp_split_graph", + payload_fn=lambda: split_gm.print_readable(print_output=False), + ) + for name, module in split_gm.named_modules(): + if "." not in name and len(name): + trace_structured( + "optimize_ddp_split_child", + lambda: {"name": name}, + payload_fn=lambda: module.print_readable(print_output=False), + ) + + fake_mode = detect_fake_mode(example_inputs) + if fake_mode is None: + fake_mode = torch._subclasses.fake_tensor.FakeTensorMode() + + submod_compiler = SubmodCompiler( + split_gm, self.backend_compile_fn, fake_mode, **compiler_configs + ) + with torch._dynamo.utils._disable_saved_tensors_hooks_during_tracing(): + submod_compiler.run(*example_inputs) + split_gm.recompile() + + ddp_graph_log.debug( + "\n---final graph---\n%s\n---------------\n", split_gm.graph + ) + return split_gm diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/inductor.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/inductor.py new file mode 100644 index 0000000000000000000000000000000000000000..ae62dd56678b8349d27fe909f12482b884ca596c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/inductor.py @@ -0,0 +1,31 @@ +""" +This module provides the TorchInductor backend integration for TorchDynamo. + +TorchInductor is a compiler backend that generates optimized code for both CPU and GPU. +This module lazily imports and registers the TorchInductor compiler to avoid loading it +into memory when it is not being used. This helps reduce memory overhead when using +other backends. + +The inductor backend can be used with torch.compile(): + model = torch.compile(model, backend="inductor") +""" + +from typing import Any + +from torch._dynamo import register_backend +from torch._dynamo.utils import dynamo_timed + + +@register_backend +def inductor(*args: Any, **kwargs: Any) -> Any: + with dynamo_timed("inductor_import", log_pt2_compile_event=True): + # do import here to avoid loading inductor into memory when it is not used + # The AsyncCompile subproc pool can be slow to start, so warm it up as early + # as possible. + from torch._inductor.async_compile import maybe_warm_pool + + maybe_warm_pool() + + from torch._inductor.compile_fx import compile_fx + + return compile_fx(*args, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/onnxrt.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/onnxrt.py new file mode 100644 index 0000000000000000000000000000000000000000..93490e64f4ae2044d0c641f8171e733ed7a8e141 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/onnxrt.py @@ -0,0 +1,39 @@ +# This backend is maintained by ONNX team. To direct issues +# to the right people, please tag related GitHub issues with `module: onnx`. +# +# Maintainers' Github IDs: wschin, xadupre +# from torch.onnx._internal.onnxruntime import ( +# is_onnxrt_backend_supported, +# torch_compile_backend, +# ) + +# from .registry import register_backend + +""" +Placeholder for onnxruntime backend for dynamo +""" + +# def has_onnxruntime(): +# # FIXME: update test/dynamo/test_backends.py to call is_onnxrt_backend_supported() +# return is_onnxrt_backend_supported() + + +# if is_onnxrt_backend_supported(): +# register_backend(name="onnxrt", compiler_fn=torch_compile_backend) +# else: + +# def information_displaying_backend(*args, **kwargs): +# raise ImportError( +# "onnxrt is not registered as a backend. " +# "Please make sure all dependencies such as " +# "numpy, onnx, onnxscript, and onnxruntime-training are installed. " +# "Suggested procedure to fix dependency problem:\n" +# " (1) pip or conda install numpy onnx onnxscript onnxruntime-training.\n" +# " (2) Open a new python terminal.\n" +# " (3) Call the API `torch.onnx.is_onnxrt_backend_supported()`:\n" +# " (4) If it returns `True`, then you can use `onnxrt` backend.\n" +# " (5) If it returns `False`, please execute the package importing section in " +# "torch/onnx/_internal/onnxruntime.py under pdb line-by-line to see which import fails." +# ) + +# register_backend(name="onnxrt", compiler_fn=information_displaying_backend) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/registry.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..4b41922873e91a3b973baecc560e9eec11ef94c5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/registry.py @@ -0,0 +1,229 @@ +""" +This module implements TorchDynamo's backend registry system for managing compiler backends. + +The registry provides a centralized way to register, discover and manage different compiler +backends that can be used with torch.compile(). It handles: + +- Backend registration and discovery through decorators and entry points +- Lazy loading of backend implementations +- Lookup and validation of backend names +- Categorization of backends using tags (debug, experimental, etc.) + +Key components: +- CompilerFn: Type for backend compiler functions that transform FX graphs +- _BACKENDS: Registry mapping backend names to entry points +- _COMPILER_FNS: Registry mapping backend names to loaded compiler functions +- _BACKEND_TAGS: Registry mapping backend names to their tags + +Example usage: + @register_backend + def my_compiler(fx_graph, example_inputs): + # Transform FX graph into optimized implementation + return compiled_fn + + # Use registered backend + torch.compile(model, backend="my_compiler") + +The registry also supports discovering backends through setuptools entry points +in the "torch_dynamo_backends" group. Example: +``` +setup.py +--- +from setuptools import setup + +setup( + name='my_torch_backend', + version='0.1', + packages=['my_torch_backend'], + entry_points={ + 'torch_dynamo_backends': [ + # name = path to entry point of backend implementation + 'my_compiler = my_torch_backend.compiler:my_compiler_function', + ], + }, +) +``` +``` +my_torch_backend/compiler.py +--- +def my_compiler_function(fx_graph, example_inputs): + # Transform FX graph into optimized implementation + return compiled_fn +``` +Using `my_compiler` backend: +``` +import torch + +model = ... # Your PyTorch model +optimized_model = torch.compile(model, backend="my_compiler") +``` +""" + +import functools +import logging +from collections.abc import Callable, Sequence +from importlib.metadata import EntryPoint +from typing import Any, Protocol + +import torch +from torch import fx + + +log = logging.getLogger(__name__) + + +class CompiledFn(Protocol): + def __call__(self, *args: torch.Tensor) -> tuple[torch.Tensor, ...]: ... + + +CompilerFn = Callable[[fx.GraphModule, list[torch.Tensor]], CompiledFn] + +_BACKENDS: dict[str, EntryPoint | None] = {} +_COMPILER_FNS: dict[str, CompilerFn] = {} +_BACKEND_TAGS: dict[str, tuple[str, ...]] = {} +_default_backend: str | CompilerFn = "inductor" + + +def register_backend( + compiler_fn: CompilerFn | None = None, + name: str | None = None, + tags: Sequence[str] = (), +) -> Callable[..., Any]: + """ + Decorator to add a given compiler to the registry to allow calling + `torch.compile` with string shorthand. Note: for projects not + imported by default, it might be easier to pass a function directly + as a backend and not use a string. + + Args: + compiler_fn: Callable taking a FX graph and fake tensor inputs + name: Optional name, defaults to `compiler_fn.__name__` + tags: Optional set of string tags to categorize backend with + """ + if compiler_fn is None: + # @register_backend(name="") syntax + return functools.partial(register_backend, name=name, tags=tags) # type: ignore[return-value] + if not callable(compiler_fn): + raise AssertionError(f"compiler_fn must be callable, got {type(compiler_fn)}") + name = name or compiler_fn.__name__ + if name in _COMPILER_FNS: + raise AssertionError(f"duplicate name: {name}") + if name not in _BACKENDS: + _BACKENDS[name] = None + _COMPILER_FNS[name] = compiler_fn + _BACKEND_TAGS[name] = tuple(tags) + return compiler_fn + + +register_debug_backend = functools.partial(register_backend, tags=("debug",)) +register_experimental_backend = functools.partial( + register_backend, tags=("experimental",) +) + + +def lookup_backend(compiler_fn: str | CompilerFn) -> CompilerFn: + """Expand backend strings to functions""" + if isinstance(compiler_fn, str): + if compiler_fn not in _BACKENDS: + _lazy_import() + if compiler_fn not in _BACKENDS: + import difflib + + from ..exc import InvalidBackend + + suggestions = difflib.get_close_matches(compiler_fn, list_backends(), n=2) + raise InvalidBackend(name=compiler_fn, suggestions=suggestions) + + if compiler_fn not in _COMPILER_FNS: + entry_point = _BACKENDS[compiler_fn] + if entry_point is not None: + register_backend(compiler_fn=entry_point.load(), name=compiler_fn) + compiler_fn = _COMPILER_FNS[compiler_fn] + return compiler_fn + + +# NOTE: can't type this due to public api mismatch; follow up with dev team +def list_backends(exclude_tags=("debug", "experimental")) -> list[str]: # type: ignore[no-untyped-def] + """ + Return valid strings that can be passed to: + + torch.compile(..., backend="name") + """ + _lazy_import() + exclude_tags_set = set(exclude_tags or ()) + + backends = [ + name + for name in _BACKENDS + if not exclude_tags_set.intersection(_BACKEND_TAGS.get(name, ())) + ] + return sorted(backends) + + +@functools.cache +def _lazy_import() -> None: + from .. import backends + from ..utils import import_submodule + + import_submodule(backends) + + from ..repro.after_dynamo import dynamo_minifier_backend + + if dynamo_minifier_backend is None: + raise AssertionError("dynamo_minifier_backend failed to load") + + _discover_entrypoint_backends() + + +@functools.cache +def _discover_entrypoint_backends() -> None: + # importing here so it will pick up the mocked version in test_backends.py + from importlib.metadata import entry_points + + group_name = "torch_dynamo_backends" + eps = entry_points(group=group_name) + # pyrefly: ignore [bad-index] + eps_dict = {name: eps[name] for name in eps.names} + for backend_name in eps_dict: + _BACKENDS[backend_name] = eps_dict[backend_name] + + +def _is_registered_backend(compiler_fn: CompilerFn) -> bool: + """ + Check if the given compiler function is a registered backend. + Custom backends (user-provided callables not in the registry) return False. + """ + # Ensure backends are loaded + _lazy_import() + + # Check if it's directly a registered backend function + if compiler_fn in _COMPILER_FNS.values(): + return True + + if isinstance(compiler_fn, torch._TorchCompileInductorWrapper): + return True + + # _TorchCompileWrapper wraps either a registered backend or a custom callable + if isinstance(compiler_fn, torch._TorchCompileWrapper): + return compiler_fn.compiler_fn in _COMPILER_FNS.values() + + return False + + +def set_default_backend(backend: str | CompilerFn | None) -> None: + """Set the default backend used by torch.compile when no backend is explicitly specified. + + Pass None to reset to the default ("inductor"). + """ + global _default_backend + if backend is None: + _default_backend = "inductor" + return + if not isinstance(backend, str) and not callable(backend): + raise TypeError(f"backend must be a string or callable, got {type(backend)}") + _default_backend = backend + + +def get_default_backend() -> str | CompilerFn: + """Return the current default backend for torch.compile.""" + return _default_backend diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/tensorrt.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/tensorrt.py new file mode 100644 index 0000000000000000000000000000000000000000..493e21a9dfc5fe929fdeefdf6153834d470ab561 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/tensorrt.py @@ -0,0 +1,12 @@ +# import torch # type: ignore[import] +# from .common import device_from_inputs, fake_tensor_unsupported # type: ignore[import] +# from .registry import register_backend # type: ignore[import] + +""" +Placeholder for TensorRT backend for dynamo via torch-tensorrt +""" + +# @register_backend +# def tensorrt(gm, example_inputs): +# import torch_tensorrt # type: ignore[import] +# pass diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/torchxla.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/torchxla.py new file mode 100644 index 0000000000000000000000000000000000000000..60d7b87bd0876a85702c07db7c82cd804ee608d1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/torchxla.py @@ -0,0 +1,55 @@ +import logging +from collections.abc import Callable +from typing import Any + +import torch +from functorch.compile import make_boxed_func +from torch import fx + +from ..backends.common import aot_autograd +from .registry import CompiledFn, register_backend, register_experimental_backend + + +log = logging.getLogger(__name__) + + +@register_experimental_backend +def openxla_eval( + model: fx.GraphModule, fake_tensor_inputs: list[torch.Tensor] +) -> CompiledFn: + return xla_backend_helper(model, fake_tensor_inputs, boxed=False) + + +def openxla_eval_boxed( + model: fx.GraphModule, fake_tensor_inputs: list[torch.Tensor] +) -> Callable[..., Any]: + return xla_backend_helper(model, fake_tensor_inputs, boxed=True) + + +def xla_backend_helper( + model: fx.GraphModule, fake_tensor_inputs: list[torch.Tensor], boxed: bool = False +) -> Callable[..., Any]: + try: + import torch_xla.core.dynamo_bridge as bridge + except ImportError as e: + raise ImportError( + "Please follow the instruction in https://github.com/pytorch/xla#pytorchxla to install torch_xla" + ) from e + + compiled_graph = None + + def fwd(*args: torch.Tensor) -> Any: + nonlocal model + nonlocal compiled_graph + if compiled_graph is None: + compiled_graph = bridge.extract_compiled_graph(model, args) + del model + return compiled_graph(*args) + + return make_boxed_func(fwd) if boxed else fwd + + +openxla = aot_autograd( + fw_compiler=openxla_eval_boxed, +) +register_backend(name="openxla", compiler_fn=openxla) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/tvm.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/tvm.py new file mode 100644 index 0000000000000000000000000000000000000000..8093cedc7a50ab4374f7598fcf9319e0bf2678f4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/backends/tvm.py @@ -0,0 +1,50 @@ +""" +This module provides TVM backend integration for TorchDynamo. + +Apache TVM is a deep learning compiler framework that can optimize and execute +models on various hardware backends. The backend compiles graphs through TVM's +relax frontend and can be used with torch.compile(): + + model = torch.compile(model, backend="tvm") + +Tuning and target selection are configured through a TVM pipeline: + + pipeline = tvm.relax.get_pipeline("static_shape_tuning", target="llvm", total_trials=2000) + model = torch.compile(model, backend="tvm", options={"pipeline": pipeline}) +""" + +import importlib.util +from collections.abc import Callable +from types import MappingProxyType +from typing import Any + +import torch +from torch import fx + +from .common import fake_tensor_unsupported +from .registry import register_backend + + +@register_backend +@fake_tensor_unsupported # type: ignore[arg-type] +def tvm( + gm: fx.GraphModule, + example_inputs: list[torch.Tensor], + *, + options: MappingProxyType[str, Any] | None = None, +) -> Callable[..., Any]: + try: + from tvm.relax.frontend.torch import relax_dynamo # type: ignore[import] + except ImportError as e: + raise ImportError( + "Please install apache-tvm to use the tvm backend. " + "See https://tvm.apache.org/docs/install/index.html for instructions." + ) from e + + pipeline = options.get("pipeline", None) if options else None + return relax_dynamo(pipeline=pipeline)(gm, example_inputs) + + +def has_tvm() -> bool: + # avoid the heavy tvm import just to check availability + return importlib.util.find_spec("tvm") is not None diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/bytecode_analysis.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/bytecode_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..e43235062d853ddd19a5dac86e691fa8db584429 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/bytecode_analysis.py @@ -0,0 +1,290 @@ +""" +This module provides utilities for analyzing and optimizing Python bytecode. +Key functionality includes: +- Dead code elimination +- Jump instruction optimization +- Stack size analysis and verification +- Live variable analysis +- Line number propagation and cleanup +- Exception table handling for Python 3.11+ + +The utilities in this module are used to analyze and transform bytecode +for better performance while maintaining correct semantics. +""" + +import bisect +import dataclasses +import dis +import itertools +import sys +from typing import Any, TYPE_CHECKING + + +if TYPE_CHECKING: + # TODO(lucaskabela): consider moving Instruction into this file + # and refactoring in callsite; that way we don't have to guard this import + from .bytecode_transformation import Instruction + +TERMINAL_OPCODES = { + dis.opmap["RETURN_VALUE"], + dis.opmap["JUMP_FORWARD"], + dis.opmap["RAISE_VARARGS"], + # TODO(jansel): double check exception handling +} +TERMINAL_OPCODES.add(dis.opmap["RERAISE"]) +if sys.version_info >= (3, 11): + TERMINAL_OPCODES.add(dis.opmap["JUMP_BACKWARD"]) + TERMINAL_OPCODES.add(dis.opmap["JUMP_FORWARD"]) +else: + TERMINAL_OPCODES.add(dis.opmap["JUMP_ABSOLUTE"]) + +if (3, 12) <= sys.version_info < (3, 14): + TERMINAL_OPCODES.add(dis.opmap["RETURN_CONST"]) +if sys.version_info >= (3, 13): + TERMINAL_OPCODES.add(dis.opmap["JUMP_BACKWARD_NO_INTERRUPT"]) +JUMP_OPCODES = set(dis.hasjrel + dis.hasjabs) +JUMP_OPNAMES = {dis.opname[opcode] for opcode in JUMP_OPCODES} +HASLOCAL = set(dis.haslocal) +HASFREE = set(dis.hasfree) + +stack_effect = dis.stack_effect + + +def get_indexof(insts: list["Instruction"]) -> dict["Instruction", int]: + """ + Get a mapping from instruction memory address to index in instruction list. + Additionally checks that each instruction only appears once in the list. + """ + # pyrefly: ignore [implicit-any] + indexof = {} + for i, inst in enumerate(insts): + if inst in indexof: + raise AssertionError( + f"duplicate instruction at index {i} in instruction list" + ) + indexof[inst] = i + return indexof + + +def remove_dead_code(instructions: list["Instruction"]) -> list["Instruction"]: + """Dead code elimination""" + indexof = get_indexof(instructions) + live_code = set() + + def find_live_code(start: int) -> None: + for i in range(start, len(instructions)): + if i in live_code: + return + live_code.add(i) + inst = instructions[i] + if inst.exn_tab_entry: + find_live_code(indexof[inst.exn_tab_entry.target]) + if inst.opcode in JUMP_OPCODES: + if inst.target is None: + raise AssertionError( + f"jump instruction {inst.opname} has no target" + ) + find_live_code(indexof[inst.target]) + if inst.opcode in TERMINAL_OPCODES: + return + + find_live_code(0) + + # change exception table entries if start/end instructions are dead + # assumes that exception table entries have been propagated, + # e.g. with bytecode_transformation.propagate_inst_exn_table_entries, + # and that instructions with an exn_tab_entry lies within its start/end. + if sys.version_info >= (3, 11): + live_idx = sorted(live_code) + for i, inst in enumerate(instructions): + if i in live_code and inst.exn_tab_entry: + # find leftmost live instruction >= start + start_idx = bisect.bisect_left( + live_idx, indexof[inst.exn_tab_entry.start] + ) + if start_idx >= len(live_idx): + raise AssertionError( + "no live instruction found at or after exn_tab_entry start" + ) + # find rightmost live instruction <= end + end_idx = ( + bisect.bisect_right(live_idx, indexof[inst.exn_tab_entry.end]) - 1 + ) + if end_idx < 0: + raise AssertionError( + "no live instruction found at or before exn_tab_entry end" + ) + if not (live_idx[start_idx] <= i <= live_idx[end_idx]): + raise AssertionError( + f"instruction {i} not within live range " + f"[{live_idx[start_idx]}, {live_idx[end_idx]}]" + ) + inst.exn_tab_entry.start = instructions[live_idx[start_idx]] + inst.exn_tab_entry.end = instructions[live_idx[end_idx]] + + return [inst for i, inst in enumerate(instructions) if i in live_code] + + +def remove_pointless_jumps(instructions: list["Instruction"]) -> list["Instruction"]: + """Eliminate jumps to the next instruction""" + pointless_jumps = { + id(a) + for a, b in itertools.pairwise(instructions) + if a.opname == "JUMP_ABSOLUTE" and a.target is b + } + return [inst for inst in instructions if id(inst) not in pointless_jumps] + + +def propagate_line_nums(instructions: list["Instruction"]) -> None: + """Ensure every instruction has line number set in case some are removed""" + cur_line_no = None + + def populate_line_num(inst: "Instruction") -> None: + nonlocal cur_line_no + if inst.starts_line: + cur_line_no = inst.starts_line + + inst.starts_line = cur_line_no + + for inst in instructions: + populate_line_num(inst) + + +def remove_extra_line_nums(instructions: list["Instruction"]) -> None: + """Remove extra starts line properties before packing bytecode""" + + cur_line_no = None + + def remove_line_num(inst: "Instruction") -> None: + nonlocal cur_line_no + if inst.starts_line is None: + return + elif inst.starts_line == cur_line_no: + inst.starts_line = None + else: + cur_line_no = inst.starts_line + + for inst in instructions: + remove_line_num(inst) + + +@dataclasses.dataclass +class ReadsWrites: + reads: set[Any] + writes: set[Any] + visited: set[Any] + + +def livevars_analysis( + instructions: list["Instruction"], instruction: "Instruction" +) -> set[Any]: + indexof = get_indexof(instructions) + must = ReadsWrites(set(), set(), set()) + may = ReadsWrites(set(), set(), set()) + + def walk(state: ReadsWrites, start: int) -> None: + if start in state.visited: + return + state.visited.add(start) + + for i in range(start, len(instructions)): + inst = instructions[i] + if inst.opcode in HASLOCAL or inst.opcode in HASFREE: + if "LOAD" in inst.opname or "DELETE" in inst.opname: + if inst.argval not in must.writes: + state.reads.add(inst.argval) + elif "STORE" in inst.opname: + state.writes.add(inst.argval) + elif inst.opname == "MAKE_CELL": + pass + else: + raise NotImplementedError(f"unhandled {inst.opname}") + if inst.exn_tab_entry: + walk(may, indexof[inst.exn_tab_entry.target]) + if inst.opcode in JUMP_OPCODES: + if inst.target is None: + raise AssertionError( + f"jump instruction {inst.opname} has no target" + ) + walk(may, indexof[inst.target]) + state = may + if inst.opcode in TERMINAL_OPCODES: + return + + walk(must, indexof[instruction]) + return must.reads | may.reads + + +@dataclasses.dataclass +class FixedPointBox: + value: bool = True + + +@dataclasses.dataclass +class StackSize: + low: int | float + high: int | float + fixed_point: FixedPointBox + + def zero(self) -> None: + self.low = 0 + self.high = 0 + self.fixed_point.value = False + + def offset_of(self, other: "StackSize", n: int) -> None: + prior = (self.low, self.high) + self.low = min(self.low, other.low + n) + self.high = max(self.high, other.high + n) + if (self.low, self.high) != prior: + self.fixed_point.value = False + + def exn_tab_jump(self, depth: int) -> None: + prior = (self.low, self.high) + self.low = min(self.low, depth) + self.high = max(self.high, depth) + if (self.low, self.high) != prior: + self.fixed_point.value = False + + +def stacksize_analysis(instructions: list["Instruction"]) -> int | float: + if not instructions: + raise AssertionError("instructions list must not be empty") + fixed_point = FixedPointBox() + stack_sizes = { + inst: StackSize(float("inf"), float("-inf"), fixed_point) + for inst in instructions + } + stack_sizes[instructions[0]].zero() + + for _ in range(100): + if fixed_point.value: + break + fixed_point.value = True + + for inst, next_inst in zip(instructions, instructions[1:] + [None]): + stack_size = stack_sizes[inst] + if inst.opcode not in TERMINAL_OPCODES: + if next_inst is None: + raise AssertionError(f"missing next inst: {inst}") + eff = stack_effect(inst.opcode, inst.arg, jump=False) + stack_sizes[next_inst].offset_of(stack_size, eff) + if inst.opcode in JUMP_OPCODES: + if inst.target is None: + raise AssertionError(f"missing target: {inst}") + stack_sizes[inst.target].offset_of( + stack_size, stack_effect(inst.opcode, inst.arg, jump=True) + ) + if inst.exn_tab_entry: + # see https://github.com/python/cpython/blob/3.11/Objects/exception_handling_notes.txt + # on why depth is computed this way. + depth = inst.exn_tab_entry.depth + int(inst.exn_tab_entry.lasti) + 1 + stack_sizes[inst.exn_tab_entry.target].exn_tab_jump(depth) + + low = min(x.low for x in stack_sizes.values()) + high = max(x.high for x in stack_sizes.values()) + + if not fixed_point.value: + raise AssertionError("failed to reach fixed point") + if low < 0: + raise AssertionError(f"stack size analysis produced negative low value: {low}") + return high diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/bytecode_debugger.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/bytecode_debugger.py new file mode 100644 index 0000000000000000000000000000000000000000..ef8c35a92b5fb76bf88cbd93b9b55af0afb7fbf2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/bytecode_debugger.py @@ -0,0 +1,1151 @@ +""" +Bytecode debugger for Dynamo-optimized code. + +This module provides a pdb-like debugger for stepping through Python bytecode +one instruction at a time, with the ability to inspect the value stack, +locals, and globals. + +Usage: + >>> # xdoctest: +SKIP + >>> import torch + >>> + >>> @torch.compile + >>> def my_fn(x): + ... return x + 1 + >>> + >>> with torch._dynamo.bytecode_debugger.debug(): + ... my_fn(torch.randn(3)) # Debugger activates on Dynamo-generated code + +Programmatic breakpoints (for Dynamo developers): + In PyCodegen, use create_breakpoint() to insert a debugger stop: + + from torch._dynamo.bytecode_transformation import create_breakpoint + codegen.extend_output(create_breakpoint()) +""" + +from __future__ import annotations + +import dis +import sys +import types +from contextlib import contextmanager +from dataclasses import dataclass, field +from typing import Any, cast, TYPE_CHECKING + + +if TYPE_CHECKING: + from collections.abc import Callable, Generator + + from typing_extensions import Self + +from .bytecode_transformation import convert_instruction, Instruction, instruction_size + + +# Python 3.12+ has sys.monitoring for efficient instruction-level tracing +_HAS_SYS_MONITORING = hasattr(sys, "monitoring") + + +# Sentinel for breakpoints inserted by PyCodegen via create_breakpoint() +class _BreakpointMarker: + """Sentinel constant that signals the debugger to break. + + Usage in PyCodegen: + from torch._dynamo.bytecode_transformation import create_breakpoint + codegen.extend_output(create_breakpoint()) + """ + + __slots__ = () + _instance: _BreakpointMarker | None = None + + def __new__(cls) -> Self: + if cls._instance is None: + cls._instance = cast("_BreakpointMarker", object.__new__(cls)) + return cls._instance + + def __repr__(self) -> str: + return "" + + +BREAKPOINT_MARKER = _BreakpointMarker() + + +# Import NULL_STACK_VALUE sentinel from C++ module +# This is returned by _get_frame_value_stack_with_depth for NULL stack slots +from torch._C._dynamo.eval_frame import NULL_STACK_VALUE + + +@dataclass +class CodeInfo: + """Per-code-object data shared across all frames executing the same code.""" + + code: types.CodeType + instructions: list[Instruction] + offset_to_inst: dict[int, Instruction] + offset_to_index: dict[int, int] + index_width: int + offset_width: int + breakpoints: set[int] = field(default_factory=set) + + +@dataclass +class DebuggerState: + """Per-frame debugging state.""" + + code_info: CodeInfo + frame: types.FrameType + current_offset: int = -1 # -1 indicates first instruction not yet seen + current_stack_depth: int = 0 # Tracked dynamically + first_instruction_seen: bool = False + step_mode: bool = True + step_count: int = 0 # Remaining steps for "s [n]" command (0 = prompt each time) + user_locals: dict[str, Any] = field( + default_factory=dict + ) # User-defined variables from debugger + last_command: str = "s" # Last command for repeat on empty input + list_index: int | None = ( + None # Current position for 'l' command (None = use current) + ) + + @property + def code(self) -> types.CodeType: + return self.code_info.code + + @property + def instructions(self) -> list[Instruction]: + return self.code_info.instructions + + @property + def offset_to_inst(self) -> dict[int, Instruction]: + return self.code_info.offset_to_inst + + @property + def offset_to_index(self) -> dict[int, int]: + return self.code_info.offset_to_index + + @property + def index_width(self) -> int: + return self.code_info.index_width + + @property + def offset_width(self) -> int: + return self.code_info.offset_width + + @property + def breakpoints(self) -> set[int]: + return self.code_info.breakpoints + + +class _DebugContext: + """Internal debug context that manages the debugging session.""" + + def __init__(self) -> None: + self._code_info: dict[types.CodeType, CodeInfo] = {} + self._frame_states: dict[types.FrameType, DebuggerState] = {} + self._active = False + self._tracked_codes: set[types.CodeType] = set() + self._old_trace: Callable[..., Any] | None = None + self._prev_callback: Callable[..., Any] | None = None + self._return_from_frame: types.FrameType | None = None + self._stop_after_return: bool = False + self._next_in_frame: types.FrameType | None = None + self._next_count: int = 0 + self._verbose: bool = False + self._stop_at_new_code: bool = True + self._quitting: bool = False + if _HAS_SYS_MONITORING: + self._tool_id = sys.monitoring.DEBUGGER_ID + + def get_instructions(self, code: types.CodeType | None = None) -> list[Instruction]: + """Get the list of instructions for a tracked code object. + + Args: + code: The code object to get instructions for. If None, returns + instructions from the most recently tracked code object. + + Returns: + List of instructions, or empty list if the code is not tracked. + """ + if not self._code_info: + return [] + if code is None: + info = next(reversed(self._code_info.values())) + else: + info = self._code_info.get(code) + if info is None: + return [] + return info.instructions + + def get_tracked_codes(self) -> list[types.CodeType]: + """Get all code objects that have been tracked by the debugger.""" + return list(self._code_info.keys()) + + @staticmethod + def is_programmatic_breakpoint(inst: Instruction) -> bool: + return inst.opname == "LOAD_CONST" and inst.argval is BREAKPOINT_MARKER + + def _get_or_create_code_info(self, code: types.CodeType) -> CodeInfo: + """Get or create CodeInfo for a code object.""" + if code not in self._code_info: + # Use dis.get_instructions directly to preserve original offsets. + # cleaned_instructions strips EXTENDED_ARG and recalculates offsets, + # which would cause mismatches with offsets reported by callbacks. + instructions = [convert_instruction(i) for i in dis.get_instructions(code)] + + # In 3.11+, instructions have inline cache entries that occupy + # bytecode space (e.g. BINARY_OP is 2 bytes + 2 bytes cache). + # dis.get_instructions only reports the instruction start offset, + # but sys.monitoring RAISE reports offsets within cache entries. + # Map the full byte range of each instruction so lookups succeed. + offset_to_inst: dict[int, Instruction] = {} + offset_to_index: dict[int, int] = {} + for i, inst in enumerate(instructions): + if inst.offset is not None: + inst_size = instruction_size(inst) + for off in range(inst.offset, inst.offset + inst_size, 2): + offset_to_inst[off] = inst + offset_to_index[off] = i + + max_index = len(instructions) - 1 if instructions else 0 + max_offset = max( + (inst.offset for inst in instructions if inst.offset is not None), + default=0, + ) + + # Pre-populate breakpoints from BREAKPOINT_MARKER instructions + programmatic_breakpoints: set[int] = { + i + for i, inst in enumerate(instructions) + if self.is_programmatic_breakpoint(inst) + } + + self._code_info[code] = CodeInfo( + code=code, + instructions=instructions, + offset_to_inst=offset_to_inst, + offset_to_index=offset_to_index, + index_width=max(1, len(str(max_index))), + offset_width=max(1, len(str(max_offset))), + breakpoints=programmatic_breakpoints, + ) + return self._code_info[code] + + def _get_or_create_frame_state( + self, code: types.CodeType, frame: types.FrameType + ) -> DebuggerState: + """Get or create per-frame DebuggerState.""" + if frame not in self._frame_states: + code_info = self._get_or_create_code_info(code) + self._frame_states[frame] = DebuggerState(code_info=code_info, frame=frame) + return self._frame_states[frame] + + def _find_frame_for_code(self, code: types.CodeType) -> types.FrameType | None: + """Walk the stack to find the frame executing the given code.""" + f: types.FrameType | None = sys._getframe() + while f is not None: + if f.f_code is code: + return f + f = f.f_back + return None + + def _build_tracked_frame_stack(self, state: DebuggerState) -> list[DebuggerState]: + """Build list of tracked ancestor frames, outermost-first. + + Walks f_back from the current execution frame to find all ancestor + frames whose code is tracked by the debugger. Returns the corresponding + DebuggerState objects with the execution state (state) last. + """ + ancestors: list[DebuggerState] = [] + f: types.FrameType | None = state.frame.f_back + while f is not None: + ancestor_state = self._frame_states.get(f) + if ancestor_state is not None: + ancestors.append(ancestor_state) + f = f.f_back + ancestors.reverse() + ancestors.append(state) + return ancestors + + def _format_instruction( + self, state: DebuggerState, offset: int, mark_current: bool = True + ) -> str: + """Format an instruction for display.""" + inst = state.offset_to_inst.get(offset) + iw, ow = state.index_width, state.offset_width + if inst is None: + return f" [{offset:{ow}d}]: " + + index = state.offset_to_index.get(offset, -1) + marker = ">>>" if mark_current and offset == state.current_offset else " " + bp_marker = ( + "*" if state.offset_to_index.get(offset, -1) in state.breakpoints else " " + ) + arg_str = f" {inst.argval}" if inst.arg is not None else "" + return f"{marker}{bp_marker} {index:{iw}d} [{offset:{ow}d}]: {inst.opname}{arg_str}" + + def _format_header(self, state: DebuggerState) -> str: + """Format the header line for instruction listings.""" + iw, ow = state.index_width, state.offset_width + return f" {'#':>{iw}} [{'offset':>{ow}}]" + + def _print_context( + self, state: DebuggerState, before: int = 3, after: int = 3 + ) -> None: + """Print instructions around the current position.""" + current_idx = state.offset_to_index.get(state.current_offset, 0) + start = max(0, current_idx - before) + end = min(len(state.instructions), current_idx + after + 1) + + print(f"\nInstruction {current_idx} at offset {state.current_offset}:") + print(self._format_header(state)) + for i in range(start, end): + inst = state.instructions[i] + if inst.offset is not None: + print(self._format_instruction(state, inst.offset)) + print() + + def _safe_stack_depth(self, state: DebuggerState, is_current_frame: bool) -> int: + """Compute a safe stack depth for reading frame values. + + For parent frames suspended at a CALL instruction, CPython has already + popped (and DECREF'd) the call arguments. The tracked depth still + includes those consumed entries, so reading them would dereference + dangling pointers. Adjust by the current instruction's stack_effect. + """ + depth = state.current_stack_depth + if not is_current_frame and state.current_offset >= 0: + inst = state.offset_to_inst.get(state.current_offset) + if inst is not None: + try: + effect = dis.stack_effect(inst.opcode, inst.arg) + if effect < 0: + depth = max(0, depth + effect) + except (ValueError, TypeError): + pass + return depth + + def _print_stack(self, state: DebuggerState, is_current_frame: bool = True) -> None: + """Print the current value stack.""" + from torch._C._dynamo.eval_frame import _get_frame_value_stack_with_depth + + depth = self._safe_stack_depth(state, is_current_frame) + try: + stack = _get_frame_value_stack_with_depth(state.frame, depth) + except Exception as e: + print(f"\nStack: (error reading stack: {e})") + return + print("\nStack (TOS at end):") + if not stack: + print(" (empty)") + else: + for i, value in enumerate(stack): + if value is NULL_STACK_VALUE: + addr = "0x0" + else: + addr = f"0x{id(value):x}" + print(f" [{i}] {addr} {value!r}") + print() + + def _print_locals(self, state: DebuggerState) -> None: + """Print local variables.""" + print("\nLocals:") + locals_dict = state.frame.f_locals + if not locals_dict: + print(" (none)") + else: + for name, value in locals_dict.items(): + print(f" {name} = {value!r}") + print() + + def _print_globals(self, state: DebuggerState, pattern: str | None = None) -> None: + """Print global variables.""" + print("\nGlobals:") + for name, value in state.frame.f_globals.items(): + if pattern and pattern not in name: + continue + if name.startswith("__") and name.endswith("__"): + continue + if isinstance(value, types.ModuleType): + continue + print(f" {name} = {value!r}") + print() + + def _disassemble(self, state: DebuggerState) -> None: + """Print the full disassembly.""" + print(f"\nDisassembly ({len(state.instructions)} instructions):") + print(self._format_header(state)) + for inst in state.instructions: + if inst.offset is not None: + print(self._format_instruction(state, inst.offset, mark_current=False)) + print() + + def _print_help(self) -> None: + """Print help message.""" + print("\nCommands:") + print(" s [n] - Step n instructions (default 1), stepping into calls") + print(" n [n] - Step n instructions (default 1), stepping over calls") + print(" c, cont - Continue until breakpoint or exception") + print(" r - Continue until current function's return instruction") + print( + " v, verbose - Toggle verbose mode (print each instruction before executing)" + ) + print(" Use with 'c' to find segfaults - last printed = culprit") + print(" u [count] - Move up the call stack (toward caller) for inspection") + print(" d [count] - Move down the call stack (toward callee)") + print(" bt, w - Print tracked frame backtrace") + print(" p - Print expression") + print(" l [first[, last]] - List instructions (like pdb)") + print(" l . - List around current instruction") + print(" ll - Disassemble all bytecode") + print(" stack - Print value stack") + print(" locals - Print local variables") + print(" globals - Print global variables") + print(" b - Set breakpoint at instruction n (see # column)") + print(" b - List breakpoints") + print(" cl - Clear breakpoint at instruction n") + print(" q, quit - Exit debugger") + print(" - Evaluate Python expression (like pdb)") + print() + print("Special variables: __stack__ (list of stack values, TOS at end)") + print("Note: Debugger stops on exceptions and shows the failing instruction.") + print() + + def _get_stack_for_eval( + self, state: DebuggerState, is_current_frame: bool = True + ) -> list[Any]: + """Get the current stack for use in expression evaluation.""" + from torch._C._dynamo.eval_frame import _get_frame_value_stack_with_depth + + depth = self._safe_stack_depth(state, is_current_frame) + try: + return _get_frame_value_stack_with_depth(state.frame, depth) + except Exception: + return [] + + def _build_eval_locals( + self, state: DebuggerState, is_current_frame: bool = True + ) -> dict[str, Any]: + """Build locals dict for expression evaluation, including user-defined variables.""" + eval_locals = dict(state.frame.f_locals) + eval_locals.update(state.user_locals) + eval_locals["__stack__"] = self._get_stack_for_eval(state, is_current_frame) + return eval_locals + + def _interactive_prompt(self, state: DebuggerState) -> None: + """Interactive prompt during debugging.""" + frame_stack = self._build_tracked_frame_stack(state) + view_index = len(frame_stack) - 1 + view_state = frame_stack[view_index] + + self._print_context(view_state) + + while True: + try: + cmd = input("(bdb) ").strip() + except (EOFError, KeyboardInterrupt): + print("\nExiting debugger.") + self._quitting = True + raise KeyboardInterrupt from None + + if not cmd: + cmd = state.last_command + else: + state.last_command = cmd + + parts = cmd.split(maxsplit=1) + action = parts[0].lower() + arg = parts[1] if len(parts) > 1 else "" + + if action in ("s", "step"): + state.step_mode = True + self._stop_at_new_code = True + # Parse optional count argument (e.g., "s 3" to step 3 times) + if arg: + try: + count = int(arg) + state.step_count = ( + count - 1 + ) # -1 because we're about to execute one + except ValueError: + print(f"Invalid count: {arg}") + continue + else: + state.step_count = 0 + return + + elif action in ("n", "next"): + self._next_in_frame = view_state.frame + if arg: + try: + count = int(arg) + self._next_count = count - 1 + except ValueError: + print(f"Invalid count: {arg}") + continue + else: + self._next_count = 0 + state.step_mode = False + self._stop_at_new_code = False + return + + elif action in ("c", "cont", "continue"): + state.step_mode = False + self._stop_at_new_code = False + self._stop_after_return = False + return + + elif action in ("r", "return"): + self._return_from_frame = state.frame + state.step_mode = False + self._stop_at_new_code = False + return + + elif action in ("u", "up"): + count = 1 + if arg: + try: + count = int(arg) + except ValueError: + print(f"Invalid count: {arg}") + continue + new_index = view_index - count + if new_index < 0: + new_index = 0 + print("Oldest tracked frame") + view_index = new_index + view_state = frame_stack[view_index] + print(f"> {view_state.code.co_name}") + self._print_context(view_state) + + elif action in ("d", "down"): + count = 1 + if arg: + try: + count = int(arg) + except ValueError: + print(f"Invalid count: {arg}") + continue + max_index = len(frame_stack) - 1 + new_index = view_index + count + if new_index > max_index: + new_index = max_index + print("Newest tracked frame") + view_index = new_index + view_state = frame_stack[view_index] + print(f"> {view_state.code.co_name}") + self._print_context(view_state) + + elif action in ("bt", "w", "where"): + for i, fs in enumerate(frame_stack): + marker = ">" if i == view_index else " " + idx = fs.offset_to_index.get(fs.current_offset, -1) + inst = fs.offset_to_inst.get(fs.current_offset) + inst_str = inst.opname if inst else "" + print( + f" {marker} [{i}] {fs.code.co_name} instruction {idx} ({inst_str})" + ) + + elif action in ("v", "verbose"): + self._verbose = not self._verbose + status = "enabled" if self._verbose else "disabled" + print(f"Verbose mode {status}.") + + elif action in ("l", "list"): + # Like pdb: + # - 'l' continues from last position (or centers on current if first time) + # - 'l .' centers on current instruction + # - 'l N' lists 11 instructions starting at N + # - 'l first, last' lists range (if last < first, last is a count) + num_lines = 11 # pdb default + start: int | None = None + end: int | None = None + + if arg == ".": + # Reset to current instruction + view_state.list_index = None + elif arg: + # Check for range syntax: "first, last" or "first,last" + if "," in arg: + parts = arg.split(",", 1) + try: + first = int(parts[0].strip()) + second = int(parts[1].strip()) + if second < first: + # second is a count + start = first + end = first + second + else: + start = first + end = second + 1 # inclusive + except ValueError: + print(f"Invalid range: {arg}") + continue + else: + # Single number: start at that instruction + try: + start = int(arg) + end = start + num_lines + except ValueError: + print(f"Invalid argument: {arg}") + continue + + if start is None: + if view_state.list_index is None: + # Center on current instruction + current_idx = view_state.offset_to_index.get( + view_state.current_offset, 0 + ) + start = max(0, current_idx - num_lines // 2) + else: + start = view_state.list_index + end = start + num_lines + + if end is None: + raise AssertionError("end must be set before listing instructions") + end = min(len(view_state.instructions), end) + if start >= len(view_state.instructions): + print("(End of bytecode)") + else: + print(self._format_header(view_state)) + for i in range(start, end): + inst = view_state.instructions[i] + if inst.offset is not None: + print(self._format_instruction(view_state, inst.offset)) + print() + view_state.list_index = end + + elif action == "ll": + self._disassemble(view_state) + + elif action == "locals": + self._print_locals(view_state) + + elif action == "globals": + self._print_globals(view_state, arg if arg else None) + + elif action == "stack": + is_current = view_state is frame_stack[-1] + self._print_stack(view_state, is_current_frame=is_current) + + elif action == "b": + if arg: + try: + index = int(arg) + num_instructions = len(view_state.instructions) + if index < 0 or index >= num_instructions: + print( + f"Invalid instruction number: {index} " + f"(must be 0-{num_instructions - 1})" + ) + else: + view_state.breakpoints.add(index) + print(f"Breakpoint set at instruction {index}") + except ValueError: + print(f"Invalid instruction number: {arg}") + else: + print("\nBreakpoints:") + if not view_state.breakpoints: + print(" (none)") + else: + for bp_index in sorted(view_state.breakpoints): + if bp_index < len(view_state.instructions): + inst = view_state.instructions[bp_index] + if inst.offset is not None: + print( + f" {self._format_instruction(view_state, inst.offset, mark_current=False)}" + ) + print() + + elif action == "cl": + if arg: + try: + index = int(arg) + num_instructions = len(view_state.instructions) + if index < 0 or index >= num_instructions: + print( + f"Invalid instruction number: {index} " + f"(must be 0-{num_instructions - 1})" + ) + elif index in view_state.breakpoints: + view_state.breakpoints.discard(index) + print(f"Breakpoint cleared at instruction {index}") + else: + print(f"No breakpoint at instruction {index}") + except ValueError: + print(f"Invalid instruction number: {arg}") + + elif action == "p": + if arg: + try: + is_current = view_state is frame_stack[-1] + frame_globals = view_state.frame.f_globals + eval_locals = self._build_eval_locals( + view_state, is_current_frame=is_current + ) + result = eval(arg, frame_globals, eval_locals) + print(f"{arg} = {result!r}") + except Exception as e: + print(f"Error evaluating '{arg}': {e}") + else: + print("Usage: p ") + + elif action in ("h", "help", "?"): + self._print_help() + + elif action in ("q", "quit", "exit"): + print("Exiting debugger.") + self._quitting = True + raise KeyboardInterrupt + + else: + # Try to execute as Python code (like pdb) + is_current = view_state is frame_stack[-1] + frame_globals = view_state.frame.f_globals + eval_locals = self._build_eval_locals( + view_state, is_current_frame=is_current + ) + + try: + # First try as expression (eval) + result = eval(cmd, frame_globals, eval_locals) + if result is not None: + print(repr(result)) + except SyntaxError: + # If not a valid expression, try as statement (exec) + try: + keys_before = set(eval_locals.keys()) + ids_before = {k: id(v) for k, v in eval_locals.items()} + exec(cmd, frame_globals, eval_locals) + # Capture any new or modified variables into user_locals + for key in eval_locals: + is_new = key not in keys_before + is_user_var = key in view_state.user_locals + is_modified = id(eval_locals[key]) != ids_before.get(key) + if ( + is_new or is_user_var or is_modified + ) and key != "__stack__": + view_state.user_locals[key] = eval_locals[key] + except Exception as e: + print(f"*** {type(e).__name__}: {e}") + except Exception as e: + print(f"*** {type(e).__name__}: {e}") + + def _handle_instruction( + self, code: types.CodeType, offset: int, frame: types.FrameType | None = None + ) -> None: + """Common instruction handling logic for both tracing backends.""" + if frame is None: + frame = self._find_frame_for_code(code) + if frame is None: + raise AssertionError( + f"Could not find frame for code object {code.co_name}" + ) + state = self._get_or_create_frame_state(code, frame) + + # Update stack depth based on the previous instruction's effect. + # The callback is called BEFORE instruction at 'offset' executes, + # so we need to apply the effect of the previous instruction first. + previous_offset = state.current_offset + if previous_offset >= 0: + prev_inst = state.offset_to_inst.get(previous_offset) + if prev_inst is not None: + # Detect if a jump was taken: current offset != sequential next + prev_index = state.offset_to_index.get(previous_offset, -1) + expected_next_index = prev_index + 1 + current_index = state.offset_to_index.get(offset, -1) + did_jump = current_index != expected_next_index + + try: + effect = dis.stack_effect( + prev_inst.opcode, prev_inst.arg, jump=did_jump + ) + state.current_stack_depth += effect + if state.current_stack_depth < 0: + raise RuntimeError( + f"Stack depth went negative after {prev_inst.opname} " + f"at offset {previous_offset}: depth={state.current_stack_depth}" + ) + except (ValueError, TypeError): + pass + + state.current_offset = offset + state.list_index = None # Reset list position when stepping + + # After 'r' command completes, resume stepping at the next instruction + if self._stop_after_return: + self._stop_after_return = False + state.step_mode = True + state.step_count = 0 + self._stop_at_new_code = True + + # After 'n', resume stepping when we reach that frame + if self._next_in_frame is not None and frame is self._next_in_frame: + if self._next_count > 0: + # More steps remaining — re-arm for the next instruction in this frame + self._next_count -= 1 + else: + self._next_in_frame = None + state.step_mode = True + state.step_count = 0 + self._stop_at_new_code = True + if _HAS_SYS_MONITORING: + sys.monitoring.restart_events() + + # First instruction - print header and enter step mode (unless suppressed) + if not state.first_instruction_seen: + state.first_instruction_seen = True + if not self._stop_at_new_code: + state.step_mode = False + if state.step_mode: + print(f"\n=== Entering Dynamo-generated code: {code.co_name} ===") + self._print_help() + elif self._verbose: + print(f"\n=== Entering Dynamo-generated code: {code.co_name} ===") + + # Verbose mode: print each instruction before executing (for segfault debugging) + if self._verbose: + inst = state.offset_to_inst.get(offset) + if inst: + idx = state.offset_to_index.get(offset, -1) + arg_str = f" {inst.argval}" if inst.arg is not None else "" + print(f"Running [{idx}] {inst.opname}{arg_str}", flush=True) + + inst = state.offset_to_inst.get(offset) + + # Check if current instruction has a breakpoint (by index) + current_index = state.offset_to_index.get(offset, -1) + hit_breakpoint = current_index in state.breakpoints + + # 'r' command: stop at RETURN_VALUE/RETURN_CONST in the target frame + # so the user can inspect the return value on the stack before returning. + hit_return_target = False + if self._return_from_frame is not None and frame is self._return_from_frame: + if inst is not None and inst.opname in ("RETURN_VALUE", "RETURN_CONST"): + self._return_from_frame = None + # After stepping past the return, stop in the caller + self._stop_after_return = True + hit_return_target = True + + # Check if we should stop + # If step_count > 0, we're in the middle of "N s" and should continue + if state.step_count > 0: + state.step_count -= 1 + # But still stop for breakpoints and return targets + if hit_breakpoint or hit_return_target: + state.step_count = 0 # Cancel remaining steps + else: + return # Continue without prompting + + should_stop = state.step_mode or hit_breakpoint or hit_return_target + if should_stop: + if hit_breakpoint: + if inst is not None and self.is_programmatic_breakpoint(inst): + print("Breakpoint hit (programmatic)") + else: + print(f"Breakpoint hit at instruction {current_index}") + elif hit_return_target: + print(f"About to return from {code.co_name}") + self._interactive_prompt(state) + + def _handle_return( + self, code: types.CodeType, retval: object, frame: types.FrameType | None = None + ) -> None: + """Common return handling logic.""" + if self._quitting: + return + print(f"\n=== {code.co_name} returned: {retval!r} ===") + + # For sys.monitoring, we don't get the frame directly, but since + # the frame that's currently returning is the one whose PY_RETURN just + # fired, code identity is sufficient to match. + if self._return_from_frame is not None and ( + frame is self._return_from_frame + or (frame is None and code is self._return_from_frame.f_code) + ): + self._return_from_frame = None + self._stop_after_return = True + if _HAS_SYS_MONITORING: + sys.monitoring.restart_events() + if self._next_in_frame is not None and ( + frame is self._next_in_frame + or (frame is None and code is self._next_in_frame.f_code) + ): + self._next_in_frame = None + self._stop_after_return = True + if _HAS_SYS_MONITORING: + sys.monitoring.restart_events() + + # Clean up frame state to avoid holding dead frame references + if frame is not None: + self._frame_states.pop(frame, None) + else: + # sys.monitoring path: find and remove matching frame state by code + for f, s in list(self._frame_states.items()): + if s.code is code: + self._frame_states.pop(f, None) + break + + def _handle_exception( + self, code: types.CodeType, offset: int, exception: BaseException + ) -> None: + """Common exception handling logic.""" + if self._quitting: + return + frame = self._find_frame_for_code(code) + if frame is None: + return + state = self._frame_states.get(frame) + if state is None: + return + + # If we're waiting for this frame to return, the return was interrupted + if self._return_from_frame is not None and ( + frame is self._return_from_frame or code is self._return_from_frame.f_code + ): + self._return_from_frame = None + + # If we're waiting for next-in-frame, the execution was interrupted + if self._next_in_frame is not None and ( + frame is self._next_in_frame or code is self._next_in_frame.f_code + ): + self._next_in_frame = None + self._stop_at_new_code = True + + state.current_offset = offset + + inst = state.offset_to_inst.get(offset) + inst_str = inst.opname if inst else "" + current_index = state.offset_to_index.get(offset, -1) + + print(f"\n=== Exception raised at instruction {current_index}: {inst_str} ===") + print(f"=== {type(exception).__name__}: {exception} ===") + self._interactive_prompt(state) + + # ========================================================================= + # Python 3.12+ implementation using sys.monitoring + # ========================================================================= + + def _dynamo_code_callback(self, code: types.CodeType) -> None: + """Called by C++ before executing Dynamo-generated code.""" + if code in self._tracked_codes: + return + self._tracked_codes.add(code) + + if _HAS_SYS_MONITORING: + # Enable INSTRUCTION and PY_RETURN events for this specific code object + # RAISE must be a global event (cannot be set locally) + sys.monitoring.set_local_events( + self._tool_id, + code, + sys.monitoring.events.INSTRUCTION | sys.monitoring.events.PY_RETURN, + ) + # For settrace, we enable opcode tracing when we see the frame + + # Pre-create code info for this code + self._get_or_create_code_info(code) + + def _monitoring_return_callback( + self, code: types.CodeType, instruction_offset: int, retval: object + ) -> None: + """Callback for PY_RETURN events (sys.monitoring).""" + self._handle_return(code, retval) + + def _monitoring_instruction_callback( + self, code: types.CodeType, offset: int + ) -> object: + """Callback for INSTRUCTION events (sys.monitoring).""" + self._handle_instruction(code, offset) + return sys.monitoring.DISABLE + + def _monitoring_raise_callback( + self, code: types.CodeType, offset: int, exception: BaseException + ) -> object: + """Callback for RAISE events (sys.monitoring).""" + # Only handle exceptions from tracked Dynamo-generated code + if code not in self._tracked_codes: + return None + self._handle_exception(code, offset, exception) + # Cannot return DISABLE for global events like RAISE + return None + + # ========================================================================= + # Python 3.11 and below implementation using sys.settrace + # ========================================================================= + + def _settrace_callback( + self, frame: types.FrameType, event: str, arg: Any + ) -> Callable[..., Any] | None: + """Trace function for sys.settrace.""" + code = frame.f_code + + # Only trace Dynamo-generated code + if code not in self._tracked_codes: + return self._settrace_callback + + if event == "call": + # Enable opcode tracing for this frame + frame.f_trace_opcodes = True + return self._settrace_callback + + elif event == "opcode": + # Get the current instruction offset + offset = frame.f_lasti + self._handle_instruction(code, offset, frame) + return self._settrace_callback + + elif event == "return": + self._handle_return(code, arg, frame) + return self._settrace_callback + + elif event == "exception": + # arg is (exception_type, exception_value, traceback) + offset = frame.f_lasti + exc_type, exc_value, exc_tb = arg + self._handle_exception(code, offset, exc_value) + return self._settrace_callback + + return self._settrace_callback + + # ========================================================================= + # Context manager implementation + # ========================================================================= + + def __enter__(self) -> Self: + """Start the debug context.""" + from torch._C._dynamo.eval_frame import ( + get_bytecode_debugger_callback, + set_bytecode_debugger_callback, + ) + + self._active = True + self._prev_callback = get_bytecode_debugger_callback() + self._code_info.clear() + self._frame_states.clear() + self._tracked_codes.clear() + + if _HAS_SYS_MONITORING: + # Python 3.12+: Use sys.monitoring + try: + sys.monitoring.use_tool_id(self._tool_id, "bytecode_debugger") + except ValueError: + pass + + # Register callbacks (events enabled per-code via set_local_events) + sys.monitoring.register_callback( + self._tool_id, + sys.monitoring.events.INSTRUCTION, + self._monitoring_instruction_callback, + ) + sys.monitoring.register_callback( + self._tool_id, + sys.monitoring.events.PY_RETURN, + self._monitoring_return_callback, + ) + sys.monitoring.register_callback( + self._tool_id, + sys.monitoring.events.RAISE, + self._monitoring_raise_callback, + ) + # RAISE must be a global event (cannot be local) + sys.monitoring.set_events(self._tool_id, sys.monitoring.events.RAISE) + else: + # Python 3.11 and below: Use sys.settrace + self._old_trace = sys.gettrace() + sys.settrace(self._settrace_callback) + + # Set the C callback that will be called before executing Dynamo code + set_bytecode_debugger_callback(self._dynamo_code_callback) + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: types.TracebackType | None, + ) -> bool: + """End the debug context.""" + if not self._active: + return False + from torch._C._dynamo.eval_frame import set_bytecode_debugger_callback + + self._active = False + prev = self._prev_callback + set_bytecode_debugger_callback(prev) + + if _HAS_SYS_MONITORING: + if prev is None: + sys.monitoring.set_events(self._tool_id, 0) + try: + sys.monitoring.free_tool_id(self._tool_id) + except ValueError: + pass + else: + # Restore outer context's monitoring callbacks and events + if not isinstance(prev, types.MethodType): + raise AssertionError( + f"Expected prev callback to be a MethodType, got {type(prev)}" + ) + outer = cast("_DebugContext", prev.__self__) + sys.monitoring.register_callback( + self._tool_id, + sys.monitoring.events.INSTRUCTION, + outer._monitoring_instruction_callback, + ) + sys.monitoring.register_callback( + self._tool_id, + sys.monitoring.events.PY_RETURN, + outer._monitoring_return_callback, + ) + sys.monitoring.register_callback( + self._tool_id, + sys.monitoring.events.RAISE, + outer._monitoring_raise_callback, + ) + sys.monitoring.set_events(self._tool_id, sys.monitoring.events.RAISE) + for code in outer._tracked_codes: + sys.monitoring.set_local_events( + self._tool_id, + code, + sys.monitoring.events.INSTRUCTION + | sys.monitoring.events.PY_RETURN, + ) + else: + # Python 3.11 and below: Restore old trace + sys.settrace(self._old_trace) + + return False # Don't suppress exceptions + + +@contextmanager +def debug() -> Generator[_DebugContext, None, None]: + """ + Context manager for debugging Dynamo-generated bytecode. + + Any Dynamo-generated code executed within this context will trigger + the interactive bytecode debugger. + + Example: + >>> # xdoctest: +SKIP + >>> import torch + >>> + >>> @torch.compile + >>> def my_fn(x): + ... return x + 1 + >>> + >>> with torch._dynamo.bytecode_debugger.debug(): + ... my_fn(torch.randn(3)) + """ + ctx = _DebugContext() + try: + with ctx: + yield ctx + except KeyboardInterrupt: + print("\n=== Debug session ended ===") + + +def breakpoint() -> None: + """Programmatic breakpoint for user code. + + Place this in code compiled by Dynamo. During tracing, Dynamo inserts a + BREAKPOINT_MARKER into the compiled bytecode. When the bytecode debugger + is active, execution pauses at this marker. + """ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/bytecode_transformation.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/bytecode_transformation.py new file mode 100644 index 0000000000000000000000000000000000000000..53414504974269855da42a43313d423c9d56f6ae --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/bytecode_transformation.py @@ -0,0 +1,2110 @@ +""" +This module provides utilities for analyzing, transforming and manipulating Python bytecode. +It includes functionality for: +- Converting between different bytecode formats and versions +- Virtualizing jumps and managing jump targets +- Handling exception tables and their entries +- Managing instruction offsets and extended arguments +- Providing a clean API for bytecode modification and transformation +- Supporting Python version-specific bytecode features +- Generating bytecode from template functions + +The module is designed to work across different Python versions (3.7+) and handles +version-specific bytecode differences transparently. +""" + +import copy +import dataclasses +import dis +import functools +import itertools +import re +import sys +import types +import uuid +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from typing import Any, cast, Optional, TYPE_CHECKING + +from . import config +from .bytecode_analysis import ( + get_indexof, + propagate_line_nums, + remove_extra_line_nums, + stacksize_analysis, +) +from .utils import is_safe_constant + + +if TYPE_CHECKING: + from .output_graph import DynamoTracerOutput + + +@dataclasses.dataclass(slots=True) +class InstructionExnTabEntry: + start: "Instruction" + end: "Instruction" + target: "Instruction" + depth: int + lasti: bool + + def __repr__(self) -> str: + return ( + f"InstructionExnTabEntry(start={self.start.short_inst_repr()}, " + f"end={self.end.short_inst_repr()}, " + f"target={self.target.short_inst_repr()}, " + f"depth={self.depth}, lasti={self.lasti})" + ) + + def __eq__(self, o: object) -> bool: + if not isinstance(o, InstructionExnTabEntry): + return False + return ( + self.start is o.start + and self.end is o.end + and self.target is o.target + and self.depth == o.depth + and self.lasti == o.lasti + ) + + +@dataclasses.dataclass(slots=True) +class Instruction: + """A mutable version of dis.Instruction""" + + opcode: int + opname: str + arg: int | None + argval: Any + offset: int | None = None + starts_line: int | None = None + is_jump_target: bool = False + + positions: Optional["dis.Positions"] = None + # extra fields to make modification easier: + target: Optional["Instruction"] = None + exn_tab_entry: InstructionExnTabEntry | None = None + argrepr: str | None = None + + def __hash__(self) -> int: + return id(self) + + def __eq__(self, other: object) -> bool: + return id(self) == id(other) + + def short_inst_repr(self) -> str: + return f"Instruction(opname={self.opname}, offset={self.offset})" + + def copy_positions(self, other: "Instruction") -> None: + self.starts_line = other.starts_line + self.positions = other.positions + + +if sys.version_info >= (3, 13): + + def convert_instruction(i: dis.Instruction) -> Instruction: + return Instruction( + i.opcode, + i.opname, + i.arg, + i.argval, + i.offset, + i.line_number, + i.is_jump_target, + i.positions, + ) + +elif sys.version_info >= (3, 11): + + def convert_instruction(i: dis.Instruction) -> Instruction: + return Instruction( + i.opcode, + i.opname, + i.arg, + i.argval, + i.offset, + i.starts_line, + i.is_jump_target, + i.positions, + ) + +else: + + def convert_instruction(i: dis.Instruction) -> Instruction: + return Instruction( + i.opcode, + i.opname, + i.arg, + i.argval, + i.offset, + i.starts_line, + i.is_jump_target, + None, + ) + + +class _NotProvided: + def __repr__(self) -> str: + return "_NotProvided" + + +if sys.version_info >= (3, 12): + + def inst_has_op_bits(name: str) -> bool: + return name in ("LOAD_ATTR", "LOAD_GLOBAL", "LOAD_SUPER_ATTR") + +elif sys.version_info >= (3, 11): + + def inst_has_op_bits(name: str) -> bool: + return name == "LOAD_GLOBAL" + +else: + + def inst_has_op_bits(name: str) -> bool: + return False + + +def create_instruction( + name: str, + *, + arg: int | None = None, + argval: Any | None = _NotProvided, + target: Instruction | None = None, +) -> Instruction: + """ + At most one of `arg`, `argval`, and `target` can be not None/_NotProvided. + This is to prevent ambiguity, e.g. does + create_instruction("LOAD_CONST", 5) + mean load the constant at co_consts[5], or load the constant 5? + + If `arg` is not provided, it will be computed during assembly from + `argval` or `target`. + + Bits in the args of instructions LOAD_GLOBAL, LOAD_ATTR (3.12+), and LOAD_SUPER_ATTR + modify the behavior of the instruction. In this case, we allow both `arg` + and `argval` to be set. The value of `arg` here is expected to be the value of + the op bits and the true value of `arg` will be computed during assembly. + If `arg` is not set, the bits are assumed to be 0. + """ + + # allow for instructions with op bits to have both arg and argval specified + if inst_has_op_bits(name): + if target is not None: + raise RuntimeError("target cannot be specified for instruction") + if arg is None: + arg = 0 + else: + cnt = (arg is not None) + (argval is not _NotProvided) + (target is not None) + if cnt > 1: + raise RuntimeError( + "only one of arg, argval, and target can be not None/_NotProvided" + ) + if arg is not None and not isinstance(arg, int): + raise RuntimeError("instruction arg must be int or None") + return Instruction( + opcode=dis.opmap[name], opname=name, arg=arg, argval=argval, target=target + ) + + +# Python 3.11 remaps +def create_jump_absolute(target: Instruction) -> Instruction: + inst = "JUMP_FORWARD" if sys.version_info >= (3, 11) else "JUMP_ABSOLUTE" + return create_instruction(inst, target=target) + + +def is_jump_absolute(target: Instruction) -> bool: + return target.opname in ("JUMP_FORWARD", "JUMP_ABSOLUTE") + + +def create_load_const(val: Any, checked: bool = True) -> Instruction: + """ + In general we should only create `LOAD_CONST` for immutable objects, but + sometimes it's convenient _and safe_ for Dynamo create `LOAD_CONST` for + mutable objects. In such cases, use `checked=False`. + """ + if checked: + if not is_safe_constant(val): + raise AssertionError(f"unsafe constant {val}") + return create_instruction("LOAD_CONST", argval=val) + + +def create_breakpoint() -> list[Instruction]: + """ + Create instructions that trigger the bytecode debugger to stop. + + Usage: + codegen.extend_output(create_breakpoint()) + + When the bytecode debugger is active, execution will pause at this point. + At runtime, these instructions have no effect on program state. + """ + from .bytecode_debugger import BREAKPOINT_MARKER + + return [ + create_instruction("LOAD_CONST", argval=BREAKPOINT_MARKER), + create_instruction("POP_TOP"), + ] + + +def create_dup_top() -> Instruction: + if sys.version_info >= (3, 11): + return create_instruction("COPY", arg=1) + return create_instruction("DUP_TOP") + + +def create_rot_n(n: int) -> list[Instruction]: + """ + Returns a "simple" sequence of instructions that rotates TOS to the n-th + position in the stack. For Python < 3.11, returns a single ROT_* + instruction. If no such instruction exists, an error is raised and the + caller is expected to generate an equivalent sequence of instructions. + For Python >= 3.11, any rotation can be expressed as a simple sequence of + swaps. + """ + if n <= 1: + # don't rotate + return [] + + if sys.version_info >= (3, 11): + # rotate can be expressed as a sequence of swap operations + # e.g. rotate 3 is equivalent to swap 3, swap 2 + return [create_instruction("SWAP", arg=i) for i in range(n, 1, -1)] + + if n <= 4: + return [create_instruction("ROT_" + ["TWO", "THREE", "FOUR"][n - 2])] + return [create_instruction("ROT_N", arg=n)] + + +def add_push_null( + inst_or_insts: Instruction | list[Instruction], +) -> list[Instruction]: + """ + Appends or prepends a PUSH_NULL instruction to `inst_or_insts`, + depending on Python version. Used when you know that + `inst_or_insts` generates a callable that will be called. + + NOTE: Assumes `inst_or_insts` is a single instruction or sequence of + instructions that pushes exactly 1 object to the stack that is to + be called. It is important that you include ALL instructions that + construct the callable - not just the first instruction/a prefix. + + Will attempt to use the NULL push bit for instructions + with such bits (LOAD_GLOBAL 3.11+, LOAD_ATTR 3.12+, LOAD_SUPER_ATTR). + In this case, instructions WILL be modified. + """ + if isinstance(inst_or_insts, Instruction): + insts: list[Instruction] = [inst_or_insts] + else: + if not isinstance(inst_or_insts, list): + raise AssertionError( + f"expected inst_or_insts to be a list, got {type(inst_or_insts)}" + ) + insts = inst_or_insts + + def inst_has_bit_set(idx: int) -> bool: + if insts[idx].arg is None: + raise AssertionError(f"expected insts[{idx}].arg to be not None") + return insts[idx].arg & 1 == 1 # type: ignore[operator] + + def set_inst_bit(idx: int) -> None: + if insts[idx].arg is None: + raise AssertionError(f"expected insts[{idx}].arg to be not None") + insts[idx].arg |= 1 # type: ignore[operator] + + if sys.version_info >= (3, 13): + # In 3.13, NULL follows the callable + if inst_has_op_bits(insts[-1].opname) and not inst_has_bit_set(-1): + # All insts with op bits have the push_null bit as the last one. + # Only set the bit if it hasn't been set - otherwise, we need + # to add another PUSH_NULL. + set_inst_bit(-1) + else: + insts = insts + [create_instruction("PUSH_NULL")] + elif sys.version_info >= (3, 12): + # LOAD_ATTR/LOAD_SUPER_ATTR at the end + # We assume that `insts` will only load 1 object, so + # LOAD_GLOBAL at the end doesn't need to be checked + if inst_has_op_bits(insts[-1].opname) and not inst_has_bit_set(-1): + set_inst_bit(-1) + elif insts[0].opname == "LOAD_GLOBAL" and not inst_has_bit_set(0): + set_inst_bit(0) + else: + insts = [create_instruction("PUSH_NULL")] + insts + elif sys.version_info >= (3, 11): + # 3.11 introduced NULL preceding callable + if inst_has_op_bits(insts[0].opname) and not inst_has_bit_set(0): + set_inst_bit(0) + else: + insts = [create_instruction("PUSH_NULL")] + insts + return insts + + +def add_push_null_call_function_ex( + inst_or_insts: Instruction | list[Instruction], +) -> list[Instruction]: + """Like add_push_null, but the low bit of LOAD_ATTR/LOAD_SUPER_ATTR + is not set, due to an expected CALL_FUNCTION_EX instruction. + """ + if isinstance(inst_or_insts, Instruction): + insts: list[Instruction] = [inst_or_insts] + else: + if not isinstance(inst_or_insts, list): + raise AssertionError( + f"expected inst_or_insts to be a list, got {type(inst_or_insts)}" + ) + insts = inst_or_insts + + if sys.version_info < (3, 11): + return insts + + idx = -1 if sys.version_info >= (3, 13) else 0 + if insts[idx].opname == "LOAD_GLOBAL": + if insts[idx].arg is None: + raise AssertionError( + f"expected insts[{idx}].arg to be not None for LOAD_GLOBAL" + ) + if insts[idx].arg & 1 == 0: # type: ignore[operator] + insts[idx].arg |= 1 # type: ignore[operator] + return insts + + if sys.version_info >= (3, 13): + insts = insts + [create_instruction("PUSH_NULL")] + else: + insts = [create_instruction("PUSH_NULL")] + insts + + return insts + + +def create_call_function(nargs: int, push_null: bool) -> list[Instruction]: + """ + Creates a sequence of instructions that makes a function call. + + `push_null` is used in Python 3.11+ only. It is used in codegen when + a function call is intended to be made with the NULL + fn convention, + and we know that the NULL has not been pushed yet. We will push a + NULL and rotate it to the correct position immediately before making + the function call. + + `push_null` should be True if no NULL is pushed for the callable. + Conversely, `push_null` should be False if a NULL was pushed for the callable. + Prefer using `push_null=False` when possible since we will not need to rotate + NULL to the right place, which is less efficient. + + Generally, you should codegen a function by using `add_push_null` then + `create_call_function` with `push_null=False`. + + Example of when to set push_null False: + + insts = [ + create_instruction("LOAD_GLOBAL", argval="torch"), + create_instruction("LOAD_ATTR", argval="nn"), + create_instruction("LOAD_ATTR", argval="functional"), + create_instruction("LOAD_ATTR", argval="relu"), + ] + insts = add_push_null(insts) + insts.append(create_instruction("LOAD_FAST", argval="x")) + insts.extend(create_call_function(1, False)) + + Example of when to set push_null True: + + insts = [create_instruction("LOAD_FAST", x)] + for should_wrap, wrapper_name in wrappers: + if should_wrap: + insts.extend([ + create_instruction("LOAD_GLOBAL", argval="wrapper1"), + create_instruction("SWAP", arg=2), + *create_call_function(1, True), + ) + """ + if sys.version_info >= (3, 11): + output = [] + if push_null: + output.append(create_instruction("PUSH_NULL")) + # 3.13 swapped NULL and callable + rots = nargs + 1 if sys.version_info >= (3, 13) else nargs + 2 + output.extend(create_rot_n(rots)) + if sys.version_info < (3, 12): + output.append(create_instruction("PRECALL", arg=nargs)) + output.append(create_instruction("CALL", arg=nargs)) + return output + return [create_instruction("CALL_FUNCTION", arg=nargs)] + + +def create_call_function_ex( + has_kwargs: bool, push_null: bool, ignore_314_kwargs_push: bool = False +) -> list[Instruction]: + """ + Assumes that in 3.14+, if has_kwargs=False, there is NOT a NULL + on the TOS for the kwargs. This utility function will add a PUSH_NULL. + + If the caller has already pushed a NULL for the kwargs, then set ignore_314_kwargs_push=True + so we don't push another NULL for the kwargs. + """ + if sys.version_info >= (3, 11): + output = [] + if ( + sys.version_info >= (3, 14) + and not has_kwargs + and not ignore_314_kwargs_push + ): + output.append(create_instruction("PUSH_NULL")) + has_kwargs = True + if push_null: + output.append(create_instruction("PUSH_NULL")) + # 3.13 swapped NULL and callable + # if flags == 1, 2 values popped - otherwise if flags == 0, 1 value + rots = ( + int(has_kwargs) + 2 + if sys.version_info >= (3, 13) + else int(has_kwargs) + 3 + ) + output.extend(create_rot_n(rots)) + output.append(create_instruction("CALL_FUNCTION_EX", arg=int(has_kwargs))) + return output + return [create_instruction("CALL_FUNCTION_EX", arg=int(has_kwargs))] + + +def create_call_method(nargs: int) -> list[Instruction]: + if sys.version_info >= (3, 12): + return [create_instruction("CALL", arg=nargs)] + if sys.version_info >= (3, 11): + return [ + create_instruction("PRECALL", arg=nargs), + create_instruction("CALL", arg=nargs), + ] + return [create_instruction("CALL_METHOD", arg=nargs)] + + +def create_load_method(name: str) -> Instruction: + if sys.version_info >= (3, 12): + # in 3.12, create a LOAD_ATTR instruction with the low bit set + return create_instruction("LOAD_ATTR", arg=1, argval=name) + return create_instruction("LOAD_METHOD", argval=name) + + +def create_setup_with(target: Instruction) -> Instruction: + opname = "BEFORE_WITH" if sys.version_info >= (3, 11) else "SETUP_WITH" + return create_instruction(opname, target=target) + + +def create_swap(n: int) -> list[Instruction]: + if sys.version_info >= (3, 11): + return [create_instruction("SWAP", arg=n)] + # in Python < 3.11, SWAP is a macro that expands to multiple instructions + if n == 1: + return [] + elif n == 2: + return [create_instruction("ROT_TWO")] + elif n == 3: + return [create_instruction("ROT_THREE"), create_instruction("ROT_TWO")] + """ + e.g. swap "a" and "b" in this stack: + 0 a 1 2 3 b + 0 a [1 2 3 b] + 0 a [1 2 3 b] [1 2 3 b] + 0 a [1 2 3 b] [1 2 3 b] -1 + 0 a [1 2 3 b] b + 0 b a [1 2 3 b] + 0 b a [1 2 3 b] [1 2 3 b] + 0 b [1 2 3 b] a [1 2 3 b] + 0 b [1 2 3 b] a [1 2 3 b] -1 + 0 b [1 2 3 a] + 0 b [1 2 3 a] [1 2 3 a] + 0 b [1 2 3 a] [1 2 3 a] reverse + 0 b [a 3 2 1] None + 0 b [a 3 2 1] + 0 b 1 2 3 a + """ + return [ + create_instruction("BUILD_LIST", arg=n - 1), + create_instruction("DUP_TOP"), + create_instruction("LOAD_CONST", argval=-1), + create_binary_subscr(), + create_instruction("ROT_THREE"), + create_instruction("DUP_TOP"), + create_instruction("ROT_THREE"), + create_instruction("LOAD_CONST", argval=-1), + create_instruction("STORE_SUBSCR"), + create_instruction("DUP_TOP"), + create_load_method("reverse"), + *create_call_method(0), + create_instruction("POP_TOP"), + create_instruction("UNPACK_SEQUENCE", arg=n - 1), + ] + + +def get_call_callable_depth(opname: str, arg: int) -> int: + """Return the depth of the callable from TOS for a call instruction. + + Depth is 1-indexed: TOS = 1, below-TOS = 2, etc. This encodes the + per-version stack layouts for every call instruction variant. + + Note: on 3.11-3.12, CPython's CALL can have either NULL or self at the + bottom depending on function vs method call. Dynamo's LOAD_METHOD + normalizes method calls to NULL + bound_method, so the bottom is always + NULL and the callable is always at depth arg + 1. + + Stack layouts (bottom-to-top within the call's frame): + CALL (3.13+): callable NULL arg0 ... argN-1 + CALL (3.11-3.12): NULL callable arg0 ... argN-1 + CALL_KW (3.13+): callable NULL arg0 ... argN-1 kw_names + CALL_FUNCTION (3.10): callable arg0 ... argN-1 + CALL_FUNCTION_KW (3.10): callable arg0 ... argN-1 kw_names + CALL_FUNCTION_EX: + 3.14+: callable NULL args_tuple kwargs_or_null + 3.13: callable NULL args_tuple [kwargs_dict] + 3.11-3.12: NULL callable args_tuple [kwargs_dict] + 3.10: callable args_tuple [kwargs_dict] + """ + if opname in ("CALL", "CALL_KW"): + kw_extra = 1 if opname == "CALL_KW" else 0 + if sys.version_info >= (3, 13): + return arg + 2 + kw_extra + else: + # 3.11-3.12: NULL is always at bottom (Dynamo normalizes + # LOAD_METHOD to NULL + bound_method) + return arg + 1 + kw_extra + elif opname in ("CALL_FUNCTION", "CALL_FUNCTION_KW"): + kw_extra = 1 if opname == "CALL_FUNCTION_KW" else 0 + return arg + 1 + kw_extra + elif opname == "CALL_FUNCTION_EX": + if sys.version_info >= (3, 14): + return 4 + elif sys.version_info >= (3, 13): + return 3 + (arg & 1) + elif sys.version_info >= (3, 11): + return 2 + (arg & 1) + else: + return 2 + (arg & 1) + else: + raise ValueError(f"not a call instruction: {opname}") + + +def create_binary_slice( + start: int | None, end: int | None, store: bool = False +) -> list[Instruction]: + """ + BINARY_SLICE and STORE_SLICE (if `set` is True) for all Python versions + """ + if sys.version_info >= (3, 14): + subscr_inst = ( + create_instruction("STORE_SUBSCR") if store else create_binary_subscr() + ) + return [ + create_load_const(slice(start, end)), + subscr_inst, + ] + elif sys.version_info >= (3, 12): + inst_name = "STORE_SLICE" if store else "BINARY_SLICE" + return [ + create_load_const(start), + create_load_const(end), + create_instruction(inst_name), + ] + else: + inst_name = "STORE_SUBSCR" if store else "BINARY_SUBSCR" + return [ + create_load_const(start), + create_load_const(end), + create_instruction("BUILD_SLICE", arg=2), + create_instruction(inst_name), + ] + + +def create_copy(i: int) -> list[Instruction]: + if sys.version_info >= (3, 11): + return [create_instruction("COPY", arg=i)] + if i == 1: + return [create_instruction("DUP_TOP")] + # COPY 4 + # 0 1 2 3 + # 3 1 2 0 + # 3 1 2 0 0 + # 0 1 2 0 3 + # 0 1 2 3 0 + return [ + *create_swap(i), + create_dup_top(), + *create_swap(i + 1), + *create_swap(2), + ] + + +# mainly for debugging generated bytecode +def create_print_on_stack(depth: int) -> list[Instruction]: + return [ + *add_push_null(create_instruction("LOAD_CONST", argval=print)), + *create_copy(depth + (2 if sys.version_info >= (3, 11) else 1)), + *create_call_function(1, False), + create_instruction("POP_TOP"), + ] + + +# mainly for debugging generated bytecode +def create_print_value(value: Any) -> list[Instruction]: + return [ + *add_push_null(create_instruction("LOAD_CONST", argval=print)), + create_instruction("LOAD_CONST", argval=value), + *create_call_function(1, False), + create_instruction("POP_TOP"), + ] + + +def create_binary_subscr() -> Instruction: + if sys.version_info < (3, 14): + return create_instruction("BINARY_SUBSCR") + # https://github.com/python/cpython/blob/0e46c0499413bc5f9f8336fe76e2e67cf93f64d8/Include/opcode.h#L36 + return create_instruction("BINARY_OP", arg=26) + + +def create_build_tuple(n: int) -> Instruction: + if sys.version_info >= (3, 14) and n == 0: + return create_load_const(()) + return create_instruction("BUILD_TUPLE", arg=n) + + +def linetable_writer( + first_lineno: int, +) -> tuple[list[int], Callable[[int, int], None], Callable[[int], None]]: + """ + Used to create typing.CodeType.co_linetable + See https://github.com/python/cpython/blob/3.10/Objects/lnotab_notes.txt + This is the internal format of the line number table for Python 3.10 + """ + if sys.version_info[:2] != (3, 10): + raise AssertionError( + f"linetable_writer requires Python 3.10, got {sys.version_info[:2]}" + ) + linetable: list[int] = [] + lineno = first_lineno + lineno_delta = 0 + byteno = 0 + + def _update(byteno_delta: int, lineno_delta: int) -> None: + while byteno_delta != 0 or lineno_delta != 0: + byte_offset = max(0, min(byteno_delta, 254)) + line_offset = max(-127, min(lineno_delta, 127)) + if byte_offset == 0 and line_offset == 0: + raise AssertionError("byte_offset and line_offset cannot both be 0") + byteno_delta -= byte_offset + lineno_delta -= line_offset + linetable.extend((byte_offset, line_offset & 0xFF)) + + def update(lineno_new: int, byteno_new: int) -> None: + nonlocal lineno, lineno_delta, byteno + byteno_delta = byteno_new - byteno + byteno = byteno_new + _update(byteno_delta, lineno_delta) + lineno_delta = lineno_new - lineno + lineno = lineno_new + + def end(total_bytes: int) -> None: + _update(total_bytes - byteno, lineno_delta) + + return linetable, update, end + + +def encode_varint(n: int) -> list[int]: + """ + 6-bit chunk encoding of an unsigned integer + See https://github.com/python/cpython/blob/3.11/Objects/locations.md + """ + if n < 0: + raise AssertionError(f"encode_varint requires non-negative n, got {n}") + b = [n & 63] + n >>= 6 + while n > 0: + b[-1] |= 64 + b.append(n & 63) + n >>= 6 + return b + + +if sys.version_info >= (3, 11): + + def linetable_311_writer( + first_lineno: int, + ) -> tuple[list[int], Callable[[dis.Positions | None, int], None]]: + """ + Used to create typing.CodeType.co_linetable + See https://github.com/python/cpython/blob/3.11/Objects/locations.md + This is the internal format of the line number table for Python 3.11 + """ + if sys.version_info < (3, 11): + raise AssertionError( + f"linetable_311_writer requires Python 3.11+, got {sys.version_info}" + ) + linetable = [] + lineno = first_lineno + + def update(positions: dis.Positions | None, inst_size: int) -> None: + nonlocal lineno + lineno_new = positions.lineno if positions else None + + def _update(delta: int, size: int) -> None: + if not (0 < size <= 8): + raise AssertionError(f"size must be in range (0, 8], got {size}") + # first byte - use 13 (no column info) is positions is + # malformed, otherwise use 14 (long form) + other_varints: tuple[int, ...] = () + if ( + positions + and positions.lineno is not None + and positions.end_lineno is not None + and positions.col_offset is not None + and positions.end_col_offset is not None + ): + linetable.append(0b1_1110_000 + size - 1) + # for whatever reason, column offset needs `+ 1` + # https://github.com/python/cpython/blob/1931c2a438c50e6250725c84dff94fc760b9b951/Python/compile.c#L7603 + other_varints = ( + positions.end_lineno - positions.lineno, + positions.col_offset + 1, + positions.end_col_offset + 1, + ) + else: + linetable.append(0b1_1101_000 + size - 1) + # encode signed int + if delta < 0: + delta = ((-delta) << 1) | 1 + else: + delta <<= 1 + # encode unsigned int + linetable.extend(encode_varint(delta)) + for n in other_varints: + linetable.extend(encode_varint(n)) + + if lineno_new is None: + lineno_delta = 0 + else: + lineno_delta = lineno_new - lineno + lineno = lineno_new + while inst_size > 8: + _update(lineno_delta, 8) + inst_size -= 8 + _update(lineno_delta, inst_size) + + return linetable, update + + +@dataclasses.dataclass(slots=True) +class ExceptionTableEntry: + start: int + end: int + target: int + depth: int + lasti: bool + + +def encode_exception_table_varint(n: int) -> list[int]: + """ + Similar to `encode_varint`, but the 6-bit chunks are ordered in reverse. + """ + if n < 0: + raise AssertionError( + f"encode_exception_table_varint requires non-negative n, got {n}" + ) + b = [n & 63] + n >>= 6 + while n > 0: + b.append(n & 63) + n >>= 6 + b.reverse() + for i in range(len(b) - 1): + b[i] |= 64 + return b + + +def decode_exception_table_varint(bytes_iter: Iterator[int]) -> int: + """ + Inverse of `encode_exception_table_varint`. + """ + b = next(bytes_iter) + val = b & 63 + while b & 64: + val <<= 6 + b = next(bytes_iter) + val |= b & 63 + return val + + +def check_exception_table(tab: list[ExceptionTableEntry]) -> None: + """ + Verifies that a list of ExceptionTableEntries will make a well-formed + jump table: entries are non-empty, sorted, and do not overlap. + """ + for i in range(len(tab) - 1): + if not ( + tab[i].start <= tab[i].end + and tab[i].end < tab[i + 1].start + and tab[i + 1].start <= tab[i + 1].end + ): + raise AssertionError( + f"exception table entries are not well-formed at index {i}: " + f"entry[{i}]=(start={tab[i].start}, end={tab[i].end}), " + f"entry[{i + 1}]=(start={tab[i + 1].start}, end={tab[i + 1].end})" + ) + + +def parse_exception_table(exntab: bytes) -> list[ExceptionTableEntry]: + """ + Parse the exception table according to + https://github.com/python/cpython/blob/3.11/Objects/exception_handling_notes.txt + """ + exntab_iter = iter(exntab) + tab = [] + try: + while True: + start = decode_exception_table_varint(exntab_iter) * 2 + length = decode_exception_table_varint(exntab_iter) * 2 + end = start + length - 2 + target = decode_exception_table_varint(exntab_iter) * 2 + dl = decode_exception_table_varint(exntab_iter) + depth = dl >> 1 + lasti = bool(dl & 1) + tab.append(ExceptionTableEntry(start, end, target, depth, lasti)) + except StopIteration: + check_exception_table(tab) + return tab + + +def assemble_exception_table(tab: list[ExceptionTableEntry]) -> bytes: + """ + Inverse of parse_exception_table - encodes list of exception + table entries into bytes. + """ + b = [] + for entry in tab: + first_entry = encode_exception_table_varint(entry.start // 2) + first_entry[0] |= 1 << 7 + b.extend(first_entry) + length = entry.end - entry.start + 2 + b.extend(encode_exception_table_varint(length // 2)) + b.extend(encode_exception_table_varint(entry.target // 2)) + dl = (entry.depth << 1) + entry.lasti + b.extend(encode_exception_table_varint(dl)) + return bytes(b) + + +def assemble(instructions: list[Instruction], firstlineno: int) -> tuple[bytes, bytes]: + """Do the opposite of dis.get_instructions()""" + code: list[int] = [] + if sys.version_info >= (3, 11): + lnotab, update_lineno = linetable_311_writer(firstlineno) + num_ext = 0 + for i, inst in enumerate(instructions): + if inst.opname == "EXTENDED_ARG": + inst_size = 1 + num_ext += 1 + # copy positions from the actual instruction + for j in (1, 2, 3): + if instructions[i + j].opname != "EXTENDED_ARG": + inst.positions = instructions[i + j].positions + break + else: + inst_size = instruction_size(inst) // 2 + num_ext + num_ext = 0 + update_lineno(inst.positions, inst_size) + num_ext = 0 + arg = inst.arg or 0 + code.extend((inst.opcode, arg & 0xFF)) + for _ in range(instruction_size(inst) // 2 - 1): + code.extend((0, 0)) + else: + lnotab, update_lineno, end = linetable_writer(firstlineno) + + for inst in instructions: + if inst.starts_line is not None: + update_lineno(inst.starts_line, len(code)) + arg = inst.arg or 0 + code.extend((inst.opcode, arg & 0xFF)) + + end(len(code)) + + return bytes(code), bytes(lnotab) + + +def _get_instruction_by_offset( + offset_to_inst: dict[int, Instruction], offset: int +) -> Instruction | None: + """ + Get the instruction located at a given offset, accounting for EXTENDED_ARGs + """ + for n in (0, 2, 4, 6): + if offset_to_inst[offset + n].opcode != dis.EXTENDED_ARG: + return offset_to_inst[offset + n] + return None + + +def virtualize_jumps(instructions: Iterable[Instruction]) -> None: + """Replace jump targets with pointers to make editing easier""" + jump_targets = { + inst.offset: inst for inst in instructions if inst.offset is not None + } + + for inst in instructions: + if inst.opcode in dis.hasjabs or inst.opcode in dis.hasjrel: + inst.target = _get_instruction_by_offset(jump_targets, inst.argval) + + +_REL_JUMPS = set(dis.hasjrel) + + +def flip_jump_direction(instruction: Instruction) -> None: + if sys.version_info < (3, 11): + raise RuntimeError("Cannot flip jump direction in Python < 3.11") + if "FORWARD" in instruction.opname: + instruction.opname = instruction.opname.replace("FORWARD", "BACKWARD") + elif "BACKWARD" in instruction.opname: + instruction.opname = instruction.opname.replace("BACKWARD", "FORWARD") + else: + raise AttributeError("Instruction is not a forward or backward jump") + instruction.opcode = dis.opmap[instruction.opname] + if instruction.opcode not in _REL_JUMPS: + raise AssertionError( + f"expected {instruction.opname} to be a relative jump instruction" + ) + + +def _get_instruction_front(instructions: list[Instruction], idx: int) -> Instruction: + """ + i.e. get the first EXTENDED_ARG instruction (if any) when targeting + instructions[idx] with a jump. + """ + target = instructions[idx] + for offset in (1, 2, 3): + if idx >= offset and instructions[idx - offset].opcode == dis.EXTENDED_ARG: + target = instructions[idx - offset] + else: + break + return target + + +def devirtualize_jumps(instructions: list[Instruction]) -> None: + """Fill in args for virtualized jump target after instructions may have moved""" + jumps = set(dis.hasjabs).union(set(dis.hasjrel)) + + # check for negative jump args and fix them + for inst in instructions: + if inst.opcode in jumps: + if inst.opcode not in dis.hasjabs: + if inst.target is None: + raise AssertionError( + f"jump instruction {inst.opname} has no target" + ) + if inst.target.offset is None: + raise AssertionError(f"jump target for {inst.opname} has no offset") + if inst.offset is None: + raise AssertionError( + f"jump instruction {inst.opname} has no offset" + ) + if inst.target.offset < inst.offset: + if sys.version_info < (3, 11): + raise RuntimeError("Got negative jump offset for Python < 3.11") + # forward jumps become backward + if "FORWARD" in inst.opname: + flip_jump_direction(inst) + else: + # backward jumps become forward + if sys.version_info >= (3, 11) and "BACKWARD" in inst.opname: + flip_jump_direction(inst) + + # jump instruction size may have changed due to flips + update_offsets(instructions) + indexof = get_indexof(instructions) + + # compute jump instruction arg + for inst in instructions: + if inst.opcode in jumps: + if inst.target is None: + raise AssertionError(f"jump instruction {inst.opname} has no target") + target = _get_instruction_front(instructions, indexof[inst.target]) + if inst.opcode in dis.hasjabs: + if sys.version_info < (3, 11): + # `arg` is expected to be bytecode offset, whereas `offset` is byte offset. + # Divide since bytecode is 2 bytes large. + if target.offset is None: + raise AssertionError("absolute jump target has no offset") + inst.arg = int(target.offset / 2) + else: + raise RuntimeError("Python 3.11+ should not have absolute jumps") + else: # relative jump + # byte offset between target and next instruction + if target.offset is None: + raise AssertionError("relative jump target has no offset") + if inst.offset is None: + raise AssertionError( + f"relative jump instruction {inst.opname} has no offset" + ) + inst.arg = abs( + int(target.offset - inst.offset - instruction_size(inst)) + ) + # pyrefly: ignore [unsupported-operation] + inst.arg //= 2 + inst.argval = target.offset + inst.argrepr = f"to {target.offset}" + + +def virtualize_exception_table( + exn_tab_bytes: bytes, instructions: list[Instruction] +) -> None: + """Replace exception table entries with pointers to make editing easier""" + exn_tab = parse_exception_table(exn_tab_bytes) + offset_to_inst = {cast(int, inst.offset): inst for inst in instructions} + offsets = sorted(offset_to_inst.keys()) + end_offset_idx = 0 + exn_tab_iter = iter(exn_tab) + try: + + def step() -> tuple[ExceptionTableEntry, InstructionExnTabEntry]: + nonlocal end_offset_idx + entry = next(exn_tab_iter) + # find rightmost offset <= entry.end, since entry.end may not be + # an actual instruction, e.g. if the end instruction is LOAD_GLOBAL, + # which takes more than 2 bytes, then entry.end points to the end + # of the LOAD_GLOBAL instruction, not the beginning. + while ( + end_offset_idx < len(offsets) and offsets[end_offset_idx] <= entry.end + ): + end_offset_idx += 1 + if end_offset_idx <= 0: + raise AssertionError( + "end_offset_idx must be positive in exception table virtualization" + ) + end_offset = offsets[end_offset_idx - 1] + inst_entry = InstructionExnTabEntry( + _get_instruction_by_offset(offset_to_inst, entry.start), # type: ignore[arg-type] + _get_instruction_by_offset(offset_to_inst, end_offset), # type: ignore[arg-type] + _get_instruction_by_offset(offset_to_inst, entry.target), # type: ignore[arg-type] + entry.depth, + entry.lasti, + ) + return entry, inst_entry + + entry, inst_entry = step() + for inst in instructions: + if inst.offset is None: + raise AssertionError( + f"instruction {inst.opname} has no offset during exception " + "table virtualization" + ) + while inst.offset > entry.end: + entry, inst_entry = step() + if inst.offset >= entry.start: + inst.exn_tab_entry = copy.copy(inst_entry) + except StopIteration: + pass + + +def compute_exception_table( + instructions: list[Instruction], +) -> list[ExceptionTableEntry]: + """Compute exception table in list format from instructions with exn_tab_entries""" + exn_dict: dict[tuple[int, int], tuple[int, int, bool]] = {} + indexof = get_indexof(instructions) + + for inst in instructions: + if inst.exn_tab_entry: + # account for prefixed EXTENDED_ARGS + start = _get_instruction_front( + instructions, indexof[inst.exn_tab_entry.start] + ).offset + if start is None: + raise AssertionError( + "exception table entry start instruction has no offset" + ) + # point to the last 2 bytes of the end instruction + end = ( + cast(int, inst.exn_tab_entry.end.offset) + + instruction_size(inst.exn_tab_entry.end) + - 2 + ) + if end is None: + raise AssertionError( + "exception table entry end instruction has no offset" + ) + target = _get_instruction_front( + instructions, indexof[inst.exn_tab_entry.target] + ).offset + if target is None: + raise AssertionError( + "exception table entry target instruction has no offset" + ) + key = (start, end) + val = (target, inst.exn_tab_entry.depth, inst.exn_tab_entry.lasti) + if key in exn_dict: + if exn_dict[key] != val: + raise AssertionError( + f"conflicting exception table entries for range " + f"{key}: {exn_dict[key]} vs {val}" + ) + exn_dict[key] = val + + # Dynamo may construct nested exception table entries for convenience, + # but Python expects exception table entries to not overlap. + # NOTE: below, "keys" refer to old instruction entries' starts and ends, + # and "entries" refer to the generated exception table entries. + + # Sort keys by increasing start, then decreasing end + keys_sorted = sorted(exn_dict.keys(), key=lambda t: (t[0], -t[1])) + # smallest byte that the next exception table entry can start at + nexti = 0 + # stack of current nested keys + key_stack: list[tuple[int, int]] = [] + exn_tab: list[ExceptionTableEntry] = [] + + def pop() -> None: + """ + Pop the key_stack and append an exception table entry if possible. + """ + nonlocal nexti + if key_stack: + key = key_stack.pop() + if nexti <= key[1]: + exn_tab.append( + ExceptionTableEntry(max(key[0], nexti), key[1], *exn_dict[key]) + ) + nexti = key[1] + 2 + + for key in keys_sorted: + # pop keys that are no longer nested over the current key + while key_stack and key_stack[-1][1] < key[0]: + pop() + if key_stack: + # create an entry covering to the current key, if possible + if not (key_stack[-1][0] <= key[0] <= key[1] <= key_stack[-1][1]): + raise AssertionError( + f"exception table key {key} is not properly nested within " + f"parent {key_stack[-1]}" + ) + left = max(nexti, key_stack[-1][0]) + if left < key[0]: + exn_tab.append( + ExceptionTableEntry(left, key[0] - 2, *exn_dict[key_stack[-1]]) + ) + nexti = key[0] + key_stack.append(key) + while key_stack: + pop() + check_exception_table(exn_tab) + return exn_tab + + +def check_inst_exn_tab_entries_nested( + tab: list[InstructionExnTabEntry], indexof: dict[Instruction, int] +) -> None: + """ + Checks `tab` is a properly sorted list of nested InstructionExnTabEntry's, + i.e. no entries partially overlap. + "Properly sorted" means entries are sorted by increasing starts, then + decreasing ends. + """ + entry_stack: list[tuple[int, int]] = [] + for entry in tab: + key = (indexof[entry.start], indexof[entry.end]) + while entry_stack and entry_stack[-1][1] < key[0]: + entry_stack.pop() + if entry_stack: + if not (entry_stack[-1][0] <= key[0] <= key[1] <= entry_stack[-1][1]): + raise AssertionError( + f"exception table entry {key} is not properly nested " + f"within parent {entry_stack[-1]}" + ) + entry_stack.append(key) + + +def propagate_inst_exn_table_entries(instructions: list[Instruction]) -> None: + """ + Copies exception table entries to all instructions in an entry's range. + Supports nested exception table entries. + """ + indexof = get_indexof(instructions) + entries: dict[tuple[int, int], InstructionExnTabEntry] = {} + for inst in instructions: + if inst.exn_tab_entry: + key = ( + indexof[inst.exn_tab_entry.start], + indexof[inst.exn_tab_entry.end], + ) + if key in entries: + if inst.exn_tab_entry != entries[key]: + raise AssertionError( + f"conflicting exn_tab_entry for instruction at key {key}" + ) + entries[key] = inst.exn_tab_entry + sorted_entries = [ + entries[key] for key in sorted(entries.keys(), key=lambda t: (t[0], -t[1])) + ] + check_inst_exn_tab_entries_nested(sorted_entries, indexof) + # Propagation of nested entries works since nested entries come later + # in sorted order. + for entry in sorted_entries: + for i in range(indexof[entry.start], indexof[entry.end] + 1): + instructions[i].exn_tab_entry = copy.copy(entry) + + +def check_inst_exn_tab_entries_valid(instructions: list[Instruction]) -> None: + """ + Checks that exn_tab_entries of instructions are valid. + An entry's start, end, and target must be in instructions. + Instructions with an exn_tab_entry are located within + the entry's start and end instructions. + Instructions do not share exn_tab_entries. + + Implicitly checks for no duplicate instructions. + """ + indexof = get_indexof(instructions) + exn_tab_entry_set = set() + for i, inst in enumerate(instructions): + if inst.exn_tab_entry: + if sys.version_info < (3, 11): + raise AssertionError("exn_tab_entry is only supported in Python 3.11+") + if id(inst.exn_tab_entry) in exn_tab_entry_set: + raise AssertionError( + f"duplicate exn_tab_entry at instruction index {i}" + ) + exn_tab_entry_set.add(id(inst.exn_tab_entry)) + entry = inst.exn_tab_entry + if entry.start not in indexof: + raise AssertionError( + "exn_tab_entry start instruction not found in instructions" + ) + if entry.end not in indexof: + raise AssertionError( + "exn_tab_entry end instruction not found in instructions" + ) + if entry.target not in indexof: + raise AssertionError( + "exn_tab_entry target instruction not found in instructions" + ) + if not (indexof[entry.start] <= i <= indexof[entry.end]): + raise AssertionError( + f"instruction at index {i} is outside its exn_tab_entry " + f"range [{indexof[entry.start]}, {indexof[entry.end]}]" + ) + + +def strip_extended_args(instructions: list[Instruction]) -> None: + instructions[:] = [i for i in instructions if i.opcode != dis.EXTENDED_ARG] + + +# Overwrites old_inst with a sequence of new instructions. +# This is necessary in order to preserve jump targets to the old +# instruction, exception table entries, and positions. +# Returns the modified sequence of instructions (including the modified +# old instruction!) that can be manipulated elsewhere. +def overwrite_instruction( + old_inst: Instruction, new_insts: list[Instruction] +) -> list[Instruction]: + # update old_inst.exn_tab_entry.end if necessary + if ( + old_inst.exn_tab_entry + and old_inst.exn_tab_entry.end is old_inst + and len(new_insts) > 1 + ): + old_inst.exn_tab_entry.end = new_insts[-1] + # preserve exception table entries and positions + for inst in new_insts[1:]: + inst.exn_tab_entry = copy.copy(old_inst.exn_tab_entry) + inst.positions = old_inst.positions + # modify old_inst in-place to preserve jump target + old_inst.opcode = new_insts[0].opcode + old_inst.opname = new_insts[0].opname + old_inst.arg = new_insts[0].arg + old_inst.argval = new_insts[0].argval + old_inst.target = new_insts[0].target + return [old_inst] + new_insts[1:] + + +def remove_load_call_method(instructions: list[Instruction]) -> list[Instruction]: + """LOAD_METHOD puts a NULL on the stack which causes issues, so remove it""" + if sys.version_info >= (3, 11): + raise AssertionError( + "remove_load_call_method should not be called on Python 3.11+" + ) + rewrites = {"LOAD_METHOD": "LOAD_ATTR", "CALL_METHOD": "CALL_FUNCTION"} + for inst in instructions: + if inst.opname in rewrites: + inst.opname = rewrites[inst.opname] + inst.opcode = dis.opmap[inst.opname] + return instructions + + +def remove_jump_if_none(instructions: list[Instruction]) -> None: + new_insts = [] + for inst in instructions: + if "_NONE" in inst.opname: + is_op = create_instruction("IS_OP", arg=int("NOT" in inst.opname)) + # need both argval and arg set correctly now (not later) + is_op.argval = is_op.arg + + if sys.version_info < (3, 12): + jump_op = create_instruction( + ( + "POP_JUMP_FORWARD_IF_TRUE" + if "FORWARD" in inst.opname + else "POP_JUMP_BACKWARD_IF_TRUE" + ), + target=inst.target, + ) + else: + jump_op = create_instruction("POP_JUMP_IF_TRUE", target=inst.target) + + replace_insts = [ + create_instruction("LOAD_CONST", argval=None), + is_op, + jump_op, + ] + new_insts.extend(overwrite_instruction(inst, replace_insts)) + else: + new_insts.append(inst) + instructions[:] = new_insts + + +def remove_binary_store_slice(instructions: list[Instruction]) -> None: + new_insts = [] + for inst in instructions: + new_insts.append(inst) + if inst.opname in ("BINARY_SLICE", "STORE_SLICE"): + # new instruction + if sys.version_info >= (3, 14) and inst.opname == "BINARY_SLICE": + subscr_inst = create_binary_subscr() + else: + subscr_inst = create_instruction(inst.opname.replace("SLICE", "SUBSCR")) + if inst.exn_tab_entry and inst.exn_tab_entry.end is inst: + inst.exn_tab_entry.end = subscr_inst + subscr_inst.exn_tab_entry = copy.copy(inst.exn_tab_entry) + subscr_inst.positions = inst.positions + # modify inst in-place to preserve jump target + inst.opcode = dis.opmap["BUILD_SLICE"] + inst.opname = "BUILD_SLICE" + inst.arg = 2 + inst.argval = 2 + new_insts.append(subscr_inst) + instructions[:] = new_insts + + +def remove_load_attr_method_variant(instructions: list[Instruction]) -> None: + """On 3.12+, LOAD_ATTR with arg%2==1 is the method variant that pushes 2 + values (NULL/self + method). Normalize it to a non-method LOAD_ATTR + (1 value) followed by PUSH_NULL (+ SWAP on 3.12 where NULL goes below + the callable). This lets break_graph_if_unsupported handle LOAD_ATTR + uniformly as a single-output instruction.""" + new_insts: list[Instruction] = [] + for inst in instructions: + if inst.opname == "LOAD_ATTR" and inst.arg is not None and inst.arg % 2: + replace_insts = [ + create_instruction("LOAD_ATTR", arg=inst.arg & ~1, argval=inst.argval), + create_instruction("PUSH_NULL"), + ] + if sys.version_info < (3, 13): + replace_insts.append(create_instruction("SWAP", arg=2)) + new_insts.extend(overwrite_instruction(inst, replace_insts)) + else: + new_insts.append(inst) + instructions[:] = new_insts + + +FUSED_INSTS = { + "LOAD_FAST_LOAD_FAST": ("LOAD_FAST", "LOAD_FAST"), + "LOAD_FAST_BORROW_LOAD_FAST_BORROW": ("LOAD_FAST_BORROW", "LOAD_FAST_BORROW"), + "STORE_FAST_STORE_FAST": ("STORE_FAST", "STORE_FAST"), + "STORE_FAST_LOAD_FAST": ("STORE_FAST", "LOAD_FAST"), +} + + +def remove_fused_load_store(instructions: list[Instruction]) -> None: + new_insts = [] + for inst in instructions: + if inst.opname in FUSED_INSTS: + inst0, inst1 = FUSED_INSTS[inst.opname] + argval0, argval1 = inst.argval + + replace_insts = [ + create_instruction(inst0, argval=argval0), + create_instruction(inst1, argval=argval1), + ] + new_insts.extend(overwrite_instruction(inst, replace_insts)) + else: + new_insts.append(inst) + instructions[:] = new_insts + + +# adds GRAPH_BREAK_IF_LEAF (not a real instruction) before RETURN_* instructions +# for testing purposes +def add_graph_break_if_leaf_instructions(instructions: list[Instruction]) -> None: + new_insts = [] + for inst in instructions: + if "RETURN" in inst.opname: + replace_insts = [ + create_instruction("NOP", argval="GRAPH_BREAK_IF_LEAF"), + create_instruction(inst.opname, argval=inst.argval), + ] + new_insts.extend(overwrite_instruction(inst, replace_insts)) + else: + new_insts.append(inst) + instructions[:] = new_insts + + +def remove_graph_break_if_leaf_instructions(instructions: list[Instruction]) -> None: + new_insts = [] + for inst, next_inst in itertools.pairwise(instructions): + if ( + inst.opname == "NOP" + and inst.argval == "GRAPH_BREAK_IF_LEAF" + and next_inst.opname.startswith("RETURN") + ): + # remove this instruction and update all other instructions' jump targets + for i in range(len(instructions)): + if instructions[i].target is inst: + instructions[i].target = next_inst + if instructions[i].exn_tab_entry: + # linter is mistakenly complaining that None has no attribute "..." + # but this codepath only runs if instructions[i] is not None + if instructions[i].exn_tab_entry.start is inst: # type: ignore[union-attr] + instructions[i].exn_tab_entry.start = next_inst # type: ignore[union-attr] + if instructions[i].exn_tab_entry.end is inst: # type: ignore[union-attr] + instructions[i].exn_tab_entry.end = next_inst # type: ignore[union-attr] + if instructions[i].exn_tab_entry.target is inst: # type: ignore[union-attr] + instructions[i].exn_tab_entry.target = next_inst # type: ignore[union-attr] + else: + new_insts.append(inst) + new_insts.append(instructions[-1]) + instructions[:] = new_insts + + +def explicit_super(code: types.CodeType, instructions: list[Instruction]) -> None: + """convert super() with no args into explicit arg form""" + cell_and_free = (code.co_cellvars or ()) + (code.co_freevars or ()) + if not len(code.co_varnames): + # A function with no argument cannot contain a valid "super()" call + return + output = [] + for idx, inst in enumerate(instructions): + output.append(inst) + if inst.opname == "LOAD_GLOBAL" and inst.argval == "super": + nexti = instructions[idx + 1] + if nexti.arg == 0 and ( + (sys.version_info >= (3, 12) and nexti.opname == "CALL") + or ( + sys.version_info >= (3, 11) + and sys.version_info < (3, 12) + and nexti.opname == "PRECALL" + ) + or (sys.version_info < (3, 11) and nexti.opname == "CALL_FUNCTION") + ): + if "__class__" not in cell_and_free: + raise AssertionError( + "__class__ not found in cell_and_free for super() call" + ) + output.append(create_instruction("LOAD_DEREF", argval="__class__")) + first_var = code.co_varnames[0] + if first_var in cell_and_free: + output.append(create_instruction("LOAD_DEREF", argval=first_var)) + else: + output.append(create_instruction("LOAD_FAST", argval=first_var)) + nexti.arg = 2 + nexti.argval = 2 + if nexti.opname == "PRECALL": + # also update the following CALL instruction + call_inst = instructions[idx + 2] + call_inst.arg = 2 + call_inst.argval = 2 + + instructions[:] = output + + +def fix_extended_args(instructions: list[Instruction]) -> int: + """Fill in correct argvals for EXTENDED_ARG ops""" + output: list[Instruction] = [] + + def maybe_pop_n(n: int) -> None: + for _ in range(n): + if output and output[-1].opcode == dis.EXTENDED_ARG: + output.pop() + + for inst in instructions: + if inst.opcode == dis.EXTENDED_ARG: + # Leave this instruction alone for now so we never shrink code + inst.arg = 0 + elif inst.arg and inst.arg > 0xFFFFFF: + maybe_pop_n(3) + output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 24)) + output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 16)) + output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 8)) + elif inst.arg and inst.arg > 0xFFFF: + maybe_pop_n(2) + output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 16)) + output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 8)) + elif inst.arg and inst.arg > 0xFF: + maybe_pop_n(1) + output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 8)) + output.append(inst) + + added = len(output) - len(instructions) + if added < 0: + raise AssertionError( + f"fix_extended_args removed instructions (added={added}), " + "expected non-negative" + ) + instructions[:] = output + return added + + +def instruction_size(inst: Instruction) -> int: + import torch + + if sys.version_info >= (3, 11): + return 2 * (torch._C._dynamo.eval_frame.py_opcode_caches[inst.opcode] + 1) + return 2 + + +def check_offsets(instructions: Sequence[Instruction]) -> None: + offset = 0 + for inst in instructions: + if inst.offset != offset: + raise AssertionError( + f"instruction {inst.opname} has offset {inst.offset}, expected {offset}" + ) + offset += instruction_size(inst) + + +def update_offsets(instructions: Sequence[Instruction]) -> None: + offset = 0 + for inst in instructions: + inst.offset = offset + + offset += instruction_size(inst) + + +def debug_bytes(*args: bytes) -> str: + index = range(max(map(len, args))) + result = [ + " ".join(f"{x:03}" for x in arg) + for arg in [index] + + list(args) + + [[int(a != b) for a, b in zip(args[-1], args[-2])]] + ] + + return "bytes mismatch\n" + "\n".join(result) + + +def debug_checks(code: types.CodeType) -> None: + """Make sure our assembler produces same bytes as we start with""" + dode, _ = transform_code_object(code, lambda x, y: None, safe=True) + if code.co_code != dode.co_code: + raise AssertionError(debug_bytes(code.co_code, dode.co_code)) + # TODO: reenable after better understanding how to handle sourceless + # (None) codes + # assert list(code.co_lines()) == list(dode.co_lines()), ( + # "line table mismatch via co_lines()" + # ) + + +HAS_LOCAL = set(dis.haslocal) +HAS_NAME = set(dis.hasname) +HAS_FREE = set(dis.hasfree) +HAS_CONST = set(dis.hasconst) + + +def get_const_index(code_options: dict[str, Any], val: Any) -> int: + for i, v in enumerate(code_options["co_consts"]): + # NOTE: stronger comparison is required, since we have + # examples where two values compare equal but have + # different semantic meaning in some cases, e.g. + # 0.0 == -0.0 but have different effects in torch.copysign. + if val is v: + return i + code_options["co_consts"] += (val,) + return len(code_options["co_consts"]) - 1 + + +def fix_vars( + instructions: list[Instruction], + code_options: dict[str, Any], + varname_from_oparg: Callable[..., Any] | None = None, +) -> None: + # compute instruction arg from argval if arg is not provided + names = {name: idx for idx, name in enumerate(code_options["co_names"])} + + def get_name_index(name: str) -> int: + try: + idx = names[name] + except KeyError: + # Add a missing item to co_names + idx = names[name] = len(names) + code_options["co_names"] = (*code_options["co_names"], name) + if len(code_options["co_names"]) != len(names): + raise AssertionError( + f"co_names length {len(code_options['co_names'])} does not " + f"match names dict length {len(names)}" + ) from None + return idx + + if sys.version_info < (3, 11): + if varname_from_oparg is not None: + raise AssertionError("varname_from_oparg should be None for Python < 3.11") + varnames = {name: idx for idx, name in enumerate(code_options["co_varnames"])} + freenames = { + name: idx + for idx, name in enumerate( + code_options["co_cellvars"] + code_options["co_freevars"] + ) + } + else: + if not callable(varname_from_oparg): + raise AssertionError("varname_from_oparg must be callable for Python 3.11+") + allnames = {} + for idx in itertools.count(): + try: + name = varname_from_oparg(idx) + allnames[name] = idx + except IndexError: + break + varnames = {name: allnames[name] for name in code_options["co_varnames"]} + freenames = { + name: allnames[name] + for name in code_options["co_cellvars"] + code_options["co_freevars"] + } + for i in range(len(instructions)): + + def should_compute_arg() -> bool: + # argval is prioritized over arg + return instructions[i].argval is not _NotProvided + + if instructions[i].opname == "LOAD_GLOBAL": + # 3.11 LOAD_GLOBAL requires both arg and argval - see create_instruction + if instructions[i].argval is _NotProvided: + raise AssertionError("LOAD_GLOBAL instruction must have argval set") + if sys.version_info >= (3, 11): + if instructions[i].arg is None: + raise AssertionError( + "LOAD_GLOBAL instruction must have arg set in Python 3.11+" + ) + instructions[i].arg = (get_name_index(instructions[i].argval) << 1) + ( + cast(int, instructions[i].arg) % 2 + ) + else: + instructions[i].arg = get_name_index(instructions[i].argval) + elif instructions[i].opname == "LOAD_ATTR": + # 3.12 LOAD_ATTR requires both arg and argval, like LOAD_GLOBAL + if instructions[i].argval is _NotProvided: + raise AssertionError("LOAD_ATTR instruction must have argval set") + if sys.version_info >= (3, 12): + if instructions[i].arg is None: + raise AssertionError( + "LOAD_ATTR instruction must have arg set in Python 3.12+" + ) + instructions[i].arg = (get_name_index(instructions[i].argval) << 1) + ( + cast(int, instructions[i].arg) % 2 + ) + else: + instructions[i].arg = get_name_index(instructions[i].argval) + elif instructions[i].opname == "LOAD_SUPER_ATTR": + if instructions[i].arg is None: + raise AssertionError("LOAD_SUPER_ATTR instruction must have arg set") + if instructions[i].argval is _NotProvided: + raise AssertionError("LOAD_SUPER_ATTR instruction must have argval set") + # Copy low bit, force second bit on for explicit super (the "+ 2") + instructions[i].arg = ( + (get_name_index(instructions[i].argval) << 2) + + (cast(int, instructions[i].arg) % 2) + + 2 + ) + elif instructions[i].opname in FUSED_INSTS: + if sys.version_info < (3, 13): + raise AssertionError( + f"fused instruction {instructions[i].opname} requires Python 3.13+" + ) + if not isinstance(instructions[i].argval, tuple): + raise AssertionError( + f"fused instruction {instructions[i].opname} argval must be a tuple, " + f"got {type(instructions[i].argval)}" + ) + if len(instructions[i].argval) != 2: + raise AssertionError( + f"fused instruction {instructions[i].opname} argval must have " + f"length 2, got {len(instructions[i].argval)}" + ) + arg_tuple = tuple( + varnames[name] if name in varnames else freenames[name] + for name in instructions[i].argval + ) + instructions[i].arg = (arg_tuple[0] << 4) + (arg_tuple[1] & 15) + elif instructions[i].opcode in HAS_LOCAL: + if should_compute_arg(): + if ( + sys.version_info >= (3, 13) + and instructions[i].argval not in varnames + ): + # instructions like LOAD_FAST used for both local and free vars + instructions[i].arg = freenames[instructions[i].argval] + else: + instructions[i].arg = varnames[instructions[i].argval] + elif instructions[i].opcode in HAS_NAME: + if should_compute_arg(): + arg = get_name_index(instructions[i].argval) + if ( + sys.version_info >= (3, 15) + and instructions[i].opname == "IMPORT_NAME" + ): + arg <<= 2 + # Set the second bit to ensure eager imports, since lazy imports are only valid at module scope + arg |= 0x02 + instructions[i].arg = arg + elif instructions[i].opcode in HAS_FREE: + if should_compute_arg(): + instructions[i].arg = freenames[instructions[i].argval] + elif instructions[i].opcode in HAS_CONST: + # NOTE: only update argval if arg is not provided. This assumes + # that any additions to co_consts are appended. + if instructions[i].arg is None: + # cannot use a dictionary since consts may not be hashable + idx = get_const_index(code_options, instructions[i].argval) + if idx < 0: + raise AssertionError( + f"failed to find constant index for {instructions[i].argval}" + ) + instructions[i].arg = idx + + +def clear_instruction_args(instructions: list[Instruction]) -> None: + # Clear the instruction arg for instructions that have argvals. + # Useful for using dis'd bytecode within generated bytecode. + for inst in instructions: + if ( + inst.argval is not _NotProvided + and ( + inst.opcode in HAS_LOCAL + or inst.opcode in HAS_NAME + or inst.opcode in HAS_FREE + or inst.opcode in HAS_CONST + ) + and inst.opname not in ("LOAD_GLOBAL", "LOAD_ATTR", "LOAD_SUPER_ATTR") + ): + inst.arg = None + + +@functools.lru_cache +def get_code_keys() -> list[str]: + # Python 3.11 changes to code keys are not fully documented. + # See https://github.com/python/cpython/blob/3.11/Objects/clinic/codeobject.c.h#L24 + # for new format. + keys = ["co_argcount"] + keys.append("co_posonlyargcount") + keys.extend( + [ + "co_kwonlyargcount", + "co_nlocals", + "co_stacksize", + "co_flags", + "co_code", + "co_consts", + "co_names", + "co_varnames", + "co_filename", + "co_name", + ] + ) + if sys.version_info >= (3, 11): + keys.append("co_qualname") + keys.append("co_firstlineno") + keys.append("co_linetable") + if sys.version_info >= (3, 11): + # not documented, but introduced in https://github.com/python/cpython/issues/84403 + keys.append("co_exceptiontable") + keys.extend( + [ + "co_freevars", + "co_cellvars", + ] + ) + return keys + + +def transform_code_object( + code: types.CodeType, + transformations: Callable[ + [list[Instruction], dict[str, Any]], Optional["DynamoTracerOutput"] + ], + safe: bool = False, +) -> tuple[types.CodeType, Optional["DynamoTracerOutput"]]: + keys = get_code_keys() + code_options = {k: getattr(code, k) for k in keys} + if len(code_options["co_varnames"]) != code_options["co_nlocals"]: + raise AssertionError( + f"co_varnames length {len(code_options['co_varnames'])} does not " + f"match co_nlocals {code_options['co_nlocals']}" + ) + + instructions = cleaned_instructions(code, safe) + # propagate line nums again for added instructions + propagate_line_nums(instructions) + + tracer_output = transformations(instructions, code_options) + _, bytecode = clean_and_assemble_instructions(instructions, keys, code_options) + return bytecode, tracer_output + + +def clean_and_assemble_instructions( + instructions: list[Instruction], keys: list[str], code_options: dict[str, Any] +) -> tuple[list[Instruction], types.CodeType]: + remove_graph_break_if_leaf_instructions(instructions) + # also implicitly checks for no duplicate instructions + check_inst_exn_tab_entries_valid(instructions) + + code_options["co_nlocals"] = len(code_options["co_varnames"]) + varname_from_oparg = None + if sys.version_info >= (3, 11): + # temporary code object with updated names + tmp_code = types.CodeType(*[code_options[k] for k in keys]) + varname_from_oparg = tmp_code._varname_from_oparg # type: ignore[attr-defined] + fix_vars(instructions, code_options, varname_from_oparg=varname_from_oparg) + + dirty = True + while dirty: + update_offsets(instructions) + devirtualize_jumps(instructions) + # this pass might change offsets, if so we need to try again + dirty = bool(fix_extended_args(instructions)) + + remove_extra_line_nums(instructions) + bytecode, lnotab = assemble(instructions, code_options["co_firstlineno"]) + + code_options["co_linetable"] = lnotab + code_options["co_code"] = bytecode + code_options["co_stacksize"] = stacksize_analysis(instructions) + if set(keys) - {"co_posonlyargcount"} != set(code_options.keys()) - { + "co_posonlyargcount" + }: + raise AssertionError( + f"code_options keys mismatch: expected {set(keys) - {'co_posonlyargcount'}}, " + f"got {set(code_options.keys()) - {'co_posonlyargcount'}}" + ) + if sys.version_info >= (3, 11): + code_options["co_exceptiontable"] = assemble_exception_table( + compute_exception_table(instructions) + ) + + return instructions, types.CodeType(*[code_options[k] for k in keys]) + + +def populate_kw_names_argval(instructions: Sequence[Instruction], consts: Any) -> None: + for inst in instructions: + if inst.opname == "KW_NAMES": + inst.argval = consts[inst.arg] + + +# If safe=True, we do not make any bytecode modifications. +# Mainly used for debugging bytecode_transformation (see debug_checks) +def cleaned_instructions(code: types.CodeType, safe: bool = False) -> list[Instruction]: + instructions = _cached_cleaned_instructions(code, safe) + # We have a lot of code that implicitly mutates the instruction array. We + # could do better here by making the copies explicit when necessary. + return _clone_instructions(instructions) + + +# Copy an instructions array, making sure to remap the individual instruction targets. +def _clone_instructions(instructions: Sequence[Instruction]) -> list[Instruction]: + # This is super hot and this is the fastest way to do this (tried copy.copy + # and dataclasses.replace). + copied = [ + Instruction( + i.opcode, + i.opname, + i.arg, + i.argval, + i.offset, + i.starts_line, + i.is_jump_target, + i.positions, + i.target, + i.exn_tab_entry, + i.argrepr, + ) + for i in instructions + ] + + remap = dict(zip(instructions, copied)) + # Handle `None` in the remapper so we don't need an extra `if`. + remap[None] = None # type: ignore[index, assignment] + + for i in copied: + i.target = remap[i.target] # type: ignore[index] + if entry := i.exn_tab_entry: + i.exn_tab_entry = InstructionExnTabEntry( + remap[entry.start], + remap[entry.end], + remap[entry.target], + entry.depth, + entry.lasti, + ) + return copied + + +@functools.lru_cache +def _cached_cleaned_instructions( + code: types.CodeType, safe: bool = False +) -> Sequence[Instruction]: + instructions = list(map(convert_instruction, dis.get_instructions(code))) + # propagate now in case we remove some instructions + propagate_line_nums(instructions) + check_offsets(instructions) + if sys.version_info >= (3, 11): + populate_kw_names_argval(instructions, code.co_consts) + virtualize_exception_table(code.co_exceptiontable, instructions) + virtualize_jumps(instructions) + strip_extended_args(instructions) + if not safe: + if sys.version_info < (3, 11): + remove_load_call_method(instructions) + if sys.version_info < (3, 12): + explicit_super(code, instructions) + if sys.version_info >= (3, 11): + remove_jump_if_none(instructions) + if sys.version_info >= (3, 12): + remove_binary_store_slice(instructions) + remove_load_attr_method_variant(instructions) + if sys.version_info >= (3, 13): + remove_fused_load_store(instructions) + if config.debug_force_graph_break_on_leaf_return: + add_graph_break_if_leaf_instructions(instructions) + if sys.version_info >= (3, 11): + update_offsets(instructions) + devirtualize_jumps(instructions) + return instructions + + +_unique_id_counter = itertools.count() + + +def unique_id(name: str, with_uuid: bool = False) -> str: + ret = f"{name}_{next(_unique_id_counter)}" + if with_uuid: + ret += f"_{uuid.uuid4()}".replace("-", "_") + return ret + + +COMPILED_FN_PREFIX = "__compiled_fn" +_COMPILED_FN_NAME_RE = re.compile( + rf"^{COMPILED_FN_PREFIX}_\d+_" + r"[0-9a-f]{8}_[0-9a-f]{4}_[0-9a-f]{4}_[0-9a-f]{4}_[0-9a-f]{12}$" +) + + +def make_compiled_fn_name() -> str: + return unique_id(COMPILED_FN_PREFIX, with_uuid=True) + + +def is_compiled_fn_name(name: str) -> bool: + return _COMPILED_FN_NAME_RE.fullmatch(name) is not None + + +def is_generator(code: types.CodeType) -> bool: + co_generator = 0x20 + return (code.co_flags & co_generator) > 0 + + +def bytecode_from_template( + fn: Callable[..., Any], + varname_map: Mapping[Any, Any] | None = None, + noreturn: bool = True, + noprefix: bool = True, +) -> list[Instruction]: + """Generates bytecode from a template function `fn` for use in + dynamo bytecode generation. + + For example, we can generate Python-version-independent bytecode + for looping through a dictionary and copying the values to a new dictionary. + + def template(d1, d2): + for k, v in d1.items(): + d2[k] = v + + + or a try block: + + def template(): + try: + dummy1 + except: + dummy2 + raise + dummy3 + + Args: + fn: a function template to generate bytecode from + varname_map: a mapping of `fn`'s varnames to new names. This + map will be applied to the generated bytecode's varnames. + For example, local variables in `fn` can be replaced with + new names that are generated by `OutputGraph.new_var`. + noreturn: remove all RETURN_* bytecodes and replace them with a jump + to the end of the bytecode. NOTE: any items pushed to the stack + for return WILL remain on the stack! Append a POP_TOP if you don't want + that item to be present. + noprefix: remove prefix bytecodes (all bytecode before the first RESUME, inclusive). + """ + insts = cleaned_instructions(fn.__code__) + clear_instruction_args(insts) + + if noprefix: + for i, inst in enumerate(insts): + if inst.opname == "RESUME": + insts = insts[i + 1 :] + break + + for inst in insts: + # If we don't reset starts_line, then the generated + # bytecode's line number will be based on fn's. + inst.starts_line = None + inst.positions = None + if varname_map and inst.argval in varname_map: + inst.argval = varname_map[inst.argval] + + if noreturn: + if sys.version_info >= (3, 12): + # replace RETURN_CONST with LOAD_CONST RETURN_VALUE + new_insts = [] + for inst in insts: + if inst.opname == "RETURN_CONST": + inst.opcode = dis.opmap["LOAD_CONST"] + inst.opname = "LOAD_CONST" + new_insts.append(inst) + # no need to propagate target/exn table + new_insts.append(create_instruction("RETURN_VALUE")) + else: + new_insts.append(inst) + insts = new_insts + + # pyrefly: ignore [implicit-any] + returns = [] + for inst in insts: + if inst.opname == "RETURN_VALUE": + returns.append(inst) + + if len(returns) == 1 and returns[0] is insts[-1]: + # only 1 return at the end - just pop it + insts.pop(-1) + elif len(returns) > 0: + # create jump target - if the last inst is a return, + # we can replace it with a NOP and make that the jump target. + if insts[-1] is returns[-1]: + insts[-1].opname = "NOP" + insts[-1].opcode = dis.opmap["NOP"] + insts[-1].arg = None + insts[-1].argval = _NotProvided + returns.pop(-1) + else: + insts.append(create_instruction("NOP")) + + # replace returns with jumps + for inst in returns: + # don't replace inst with new instruction + # due to targeting/exn table/etc. + jump_inst = create_jump_absolute(insts[-1]) + inst.opname = jump_inst.opname + inst.opcode = jump_inst.opcode + inst.arg = jump_inst.arg + inst.argval = jump_inst.argval + inst.target = jump_inst.target + + return insts diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/cache_size.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/cache_size.py new file mode 100644 index 0000000000000000000000000000000000000000..bdd8d18eafad0f89c303d911dbef1a116c11938f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/cache_size.py @@ -0,0 +1,197 @@ +import logging +import weakref +from dataclasses import dataclass +from typing import Any + +from torch._guards import CompileId + +from . import config +from .types import DynamoFrameType + + +log: logging.Logger = logging.getLogger(__name__) +""" +[Note on cache size limit] + +Background - TorchDynamo cache is a linked list. Each cache entry is a +(guard_manager, out_code, next pointer). These are stored on the f_code's co_extra +scratch space. When a frame is invoked, we walk this linked list and run +guard_manager in each cache_entry to decide if the frame needs recompilation. If none +of the guard_manager's returns True, we recompile and add a new entry. To ensure we +don't end up recompiling infinitely, we put limits on the cache size. + +There are two limits +1) recompile_limit +2) accumulated_recompile_limit + + +Earlier we used to have only one limit - maximum number of entries in 1 cache line +(which is now represented by (2) above). So, why do we need two limits? Let's try +to understand that. + +In general, we want our cache limit value to be a small number (e.g. 8 or even +lower). This ensures that for frames that cause too many recompilations fall to +eager quickly. However, there is another problem that prevents us from lowering +the value of recompile_limit. This is due to ID_MATCH'd guards. Today, we put +ID_MATCH guards on nn module if there is a graph break. This means we will have +many recompilations for the same code object because the ID_MATCH guard fails +for different instances of the nn module. This is a common pattern in how models +are authored. Therefore, this requires us to keep the recompile_limit high. + +We resolve this by introducing these two limits. The first limit (1) limits the +number of cache entries that have an ID_MATCH'd guard for an nn module instance. +And, (2)nd limit becomes a safeguard mechanism to have a maximum compilations +for a code object. One important question is - what is the limit for the code +object that does not have any ID_MATCH guard? For such code objects, we choose +(1) as the cache size limit. + +Let's take an example to understand how these limits help. Suppose, we have 16 +instances of a nn module and we ID_MATCH on the self object. Further, suppose +the inputs to these functions have varying batch size, leading to one +recompilation. In total, there will be 32 recompilations, and therefore 32 cache +entries on the forward code object. In the older case when we had only 1 limit, +our cache size limit must be >= 32 to capture all these recompilations. Now, +suppose there is a separate function in the same program which is very dynamic +and unsuitable for compilation. Such a function will need to undergo 32 +compilations to burst the cache and fallback to eager. These 32 recompilations +are too many and we want to fallback for these compilation-unfriendly functions +sooner. + +In the new scenario, we can have (1) recompile_limit = 2, (2) +accumulated_recompile_limit = 32. This means that each ID_MATCH'd object can +have maximum of two cache entries, and the maximum number of cache entries +(irrespective of ID_MATCH obj) is 32. This covers the case of forward code +object which has 32 recompilations. For the other function, the one unsuitable +for recompilation, our limit is 2. So, we will burst the cache in just 2 +recompilations. In this manner, these 2 limits help us resolve the tension +mentioned earlier. +""" + + +@dataclass +class CacheSizeRelevantForFrame: + """ + We track the number of cache entries that have same id_match objects as the + given frame. + + TODO(janimesh) - Consider adding a map from tuple_of_match_ids to count - + https://github.com/pytorch/pytorch/pull/107496#discussion_r1304564682 - this + could be useful for debugging as well. + """ + + # Number of CacheEntry objects in this region's cache list + num_cache_entries: int = 0 + + # Number of CacheEntry objects having same ID_MATCH'd objects as given frame. + num_cache_entries_with_same_id_matched_objs: int = 0 + + # Total cache entries across ALL regions on this code object. + # Used for accumulated_recompile_limit which is a global safety cap. + total_cache_entries_all_regions: int = 0 + + def will_compilation_exceed(self, limit: int) -> bool: + # Checks if a compilation will exceed the given limit (that's why >=). + return ( + self.will_compilation_exceed_accumulated_limit() + or self.will_compilation_exceed_specific_limit(limit) + ) + + def will_compilation_exceed_accumulated_limit(self) -> bool: + # accumulated_recompile_limit is a global safety cap across all regions. + return ( + self.total_cache_entries_all_regions >= config.accumulated_recompile_limit + ) + + def will_compilation_exceed_specific_limit(self, limit: int) -> bool: + return self.num_cache_entries_with_same_id_matched_objs >= limit + + +def _get_weakref_from_f_locals( + frame: DynamoFrameType, local_name: str +) -> weakref.ref[Any] | None: + obj = frame.f_locals.get(local_name, None) + weak_id = None + try: + weak_id = weakref.ref(obj) + except TypeError: + pass # cannot weakref bool object + return weak_id + + +def _has_same_id_matched_objs(frame: DynamoFrameType, cache_entry: Any) -> bool: + """ + Checks if the ID_MATCH'd objects saved on cache_entry are same as the ones + in frame.f_locals. + """ + if not cache_entry: + return False + + for ( + local_name, + weakref_from_cache_entry, + ) in cache_entry.guard_manager.id_matched_objs.items(): + if weakref_from_cache_entry() is not None: + weakref_from_frame = _get_weakref_from_f_locals(frame, local_name) + if weakref_from_frame is not weakref_from_cache_entry: + return False + + # Also covers the case where no ID_MATCH objects are saved in frame.f_locals + return True + + +def compute_cache_size( + frame: DynamoFrameType, + cache_entries: list[Any], + total_cache_entries_all_regions: int = 0, +) -> CacheSizeRelevantForFrame: + # cache_entries is already scoped to a single isolate_recompiles region. + # recompile_limit is checked per-region. accumulated_recompile_limit uses + # total_cache_entries_all_regions as a global safety cap. + num_cache_entries = 0 + num_cache_entries_with_same_id_matched_objs = 0 + + for cache_entry in cache_entries: + num_cache_entries += 1 + if _has_same_id_matched_objs(frame, cache_entry): + num_cache_entries_with_same_id_matched_objs += 1 + + return CacheSizeRelevantForFrame( + num_cache_entries, + num_cache_entries_with_same_id_matched_objs, + max(total_cache_entries_all_regions, num_cache_entries), + ) + + +def is_recompilation(cache_size: CacheSizeRelevantForFrame) -> bool: + """ + If the frame (earlier parsed by compute_cache_size) has more than 1 cache + entry with same ID_MATCH'd objects, then its a recompilation. + """ + # Note that you can have multiple entries in the cache but still not a + # recompile, e.g., you can have 64 nn module instances, each one having an + # ID_MATCH guard, and each one having just 1 cache entry in the cache. In + # this case, we can have 64 entries in the cache, but no recompilation + # because there is only one entry for each id_matched_obj. + return cache_size.will_compilation_exceed(1) + + +def exceeds_recompile_limit( + cache_size: CacheSizeRelevantForFrame, compile_id: CompileId +) -> tuple[bool, str]: + """ + Checks if we are exceeding the cache size limit. + """ + if cache_size.will_compilation_exceed_accumulated_limit(): + return True, "accumulated_recompile_limit" + if cache_size.will_compilation_exceed_specific_limit(config.recompile_limit): + return True, "recompile_limit" + # NOTE this check is needed in the case that the frame's cache doesn't grow + # and we keep recompiling. This can happen if the guard guard_manager becomes invalidated, + # e.g. due to guarded objects being freed. This technically makes the + # will_compilation_exceed_accumulated_limit check unnecessary, but we will keep the + # check in case we have a better fix in the future. + if compile_id.frame_compile_id is None: + raise AssertionError("compile_id.frame_compile_id must not be None") + if compile_id.frame_compile_id >= config.accumulated_recompile_limit: + return True, "accumulated_recompile_limit" + return False, "" diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/callback.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/callback.py new file mode 100644 index 0000000000000000000000000000000000000000..5723d849876f0597b33e0a6686e46e3851487458 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/callback.py @@ -0,0 +1,175 @@ +""" +This module provides callback management functionality for TorchDynamo's compilation process. + +It implements a thread-safe system for registering, managing and executing callbacks that run +at the start and end of TorchDynamo compilations. Key features include: + +- Registration and deregistration of compilation callbacks +- Thread-safe callback handling with proper locking mechanisms +- Prevention of duplicate callback execution when configured +- Decorator utilities for easy callback registration +- Context manager for controlled callback lifecycle + +The module centers around the CompilationCallbackHandler class which maintains separate +lists for start and end callbacks, manages their execution order, and ensures thread-safety. +Utility decorators @on_compile_start and @on_compile_end provide a convenient way to +register compilation hooks. + +Example usage: + @on_compile_start + def my_start_callback(): + print("Starting compilation") + + @on_compile_end + def my_end_callback(): + print("Compilation complete") +""" + +import enum +import threading +from collections.abc import Callable, Generator +from contextlib import contextmanager +from dataclasses import dataclass, field +from typing import Any + + +class CallbackTrigger(enum.Enum): + # most common case, dynamo attempts to trace a new frame + DYNAMO = 1 + # backward compilation can be deferred to runtime + LAZY_BACKWARD = 2 + # some backends autotune at runtime + TRITON_AUTOTUNING = 3 # Temporarily disabled due to spam + # cudagraphs record at runtime + CUDAGRAPH_RECORDING = 4 + + +@dataclass +class CallbackArgs: + callback_trigger: CallbackTrigger + compile_id: str + + +@dataclass +class CompilationCallbackHandler: + start_callbacks: list[Callable[[CallbackArgs], None]] = field(default_factory=list) + end_callbacks: list[Callable[[CallbackArgs], None]] = field(default_factory=list) + + __pending_callbacks_counter: int = field(default=0, init=False, repr=False) + __pending_callbacks_counter_lock: threading.Lock = field( + default_factory=threading.Lock, init=False, repr=False + ) + + def register_start_callback( + self, callback: Callable[[CallbackArgs], None] + ) -> Callable[[CallbackArgs], None]: + """ + Register a callback function to be called when the compilation starts. + + Args: + - callback (Callable): The callback function to register. + """ + self.start_callbacks.append(callback) + return callback + + def register_end_callback( + self, callback: Callable[[CallbackArgs], None] + ) -> Callable[[CallbackArgs], None]: + """ + Register a callback function to be called when the compilation ends. + + Args: + - callback (Callable): The callback function to register. + """ + self.end_callbacks.append(callback) + return callback + + def remove_start_callback(self, callback: Callable[[CallbackArgs], None]) -> None: + """ + Remove a registered start callback function. + + Args: + - callback (Callable): The callback function to remove. + """ + self.start_callbacks.remove(callback) + + def remove_end_callback(self, callback: Callable[[CallbackArgs], None]) -> None: + """ + Remove a registered end callback function. + + Args: + - callback (Callable): The callback function to remove. + """ + self.end_callbacks.remove(callback) + + def run_start_callbacks(self, args: CallbackArgs) -> None: + """ + Execute all registered start callbacks. + """ + for callback in self.start_callbacks: + callback(args) + + def run_end_callbacks(self, args: CallbackArgs) -> None: + """ + Execute all registered end callbacks. + """ + for callback in self.end_callbacks: + callback(args) + + @contextmanager + def install_callbacks( + self, trigger: CallbackTrigger, compile_id: str + ) -> Generator[None, Any, Any]: + """ + Context manager to install the callbacks and run them when the context is exited. + """ + args = CallbackArgs(trigger, compile_id) + try: + with self.__pending_callbacks_counter_lock: + self.__pending_callbacks_counter += 1 + if self.__pending_callbacks_counter == 1: + self.run_start_callbacks(args) + yield + finally: + with self.__pending_callbacks_counter_lock: + if self.__pending_callbacks_counter <= 0: + raise AssertionError( + "Pending callbacks counter cannot become negative." + ) + if self.__pending_callbacks_counter == 1: + self.run_end_callbacks(args) + self.__pending_callbacks_counter -= 1 + + def clear(self) -> None: + """ + Clear all registered callbacks. + """ + self.start_callbacks.clear() + self.end_callbacks.clear() + if self.__pending_callbacks_counter != 0: + raise AssertionError( + f"Cannot clear callbacks while {self.__pending_callbacks_counter} are pending" + ) + + +callback_handler = CompilationCallbackHandler() + + +def on_compile_start( + callback: Callable[[CallbackArgs], None], +) -> Callable[[CallbackArgs], None]: + """ + Decorator to register a callback function for the start of the compilation. + """ + callback_handler.register_start_callback(callback) + return callback + + +def on_compile_end( + callback: Callable[[CallbackArgs], None], +) -> Callable[[CallbackArgs], None]: + """ + Decorator to register a callback function for the end of the compilation. + """ + callback_handler.register_end_callback(callback) + return callback diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/code_context.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/code_context.py new file mode 100644 index 0000000000000000000000000000000000000000..b4a0a55752828277a5ea30622bde5e5436c821ae --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/code_context.py @@ -0,0 +1,61 @@ +""" +This module provides thread-safe code context management for TorchDynamo using weak references. + +The CodeContextDict class maintains a mapping between Python code objects and their associated +context data, using weak references to automatically clean up entries when code objects are +garbage collected. This prevents memory leaks while allowing context data to be associated +with code objects throughout their lifecycle. + +Key features: +- Thread-safe context storage and retrieval +- Automatic cleanup using weak references +- Safe context management for Python code objects +- Memory-leak prevention + +Example usage: + code_obj = compile('x = 1', '', 'exec') + + # Store context + context = code_context.get_context(code_obj) + context['metadata'] = {'optimized': True} + + # Retrieve context + if code_context.has_context(code_obj): + ctx = code_context.get_context(code_obj) + # Use context data... + + # Remove context + ctx = code_context.pop_context(code_obj) +""" + +import types +from typing import Any + +from .utils import ExactWeakKeyDictionary + + +class CodeContextDict: + def __init__(self) -> None: + self.code_context: ExactWeakKeyDictionary = ExactWeakKeyDictionary() + + def has_context(self, code: types.CodeType) -> bool: + return code in self.code_context + + def get_context(self, code: types.CodeType) -> dict[str, Any]: + ctx = self.code_context.get(code) + if ctx is None: + # pyrefly: ignore [implicit-any] + ctx = {} + self.code_context[code] = ctx + return ctx + + def pop_context(self, code: types.CodeType) -> dict[str, Any]: + ctx = self.get_context(code) + self.code_context._remove_id(id(code)) + return ctx + + def clear(self) -> None: + self.code_context.clear() + + +code_context: CodeContextDict = CodeContextDict() diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/codegen.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/codegen.py new file mode 100644 index 0000000000000000000000000000000000000000..9679284fefecd9c1bedf35e1f9b6b58710f475cf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/codegen.py @@ -0,0 +1,829 @@ +""" +This module provides utilities for generating Python bytecode in PyTorch's Dynamo system. +It includes functionality for: +- Constructing bytecode sequences for Python operations +- Managing stack operations and variable tracking +- Handling graph outputs and their conversions +- Supporting different Python versions (3.11+, 3.12+, 3.13+) +- Converting high-level operations to low-level bytecode instructions +- Managing constant loading and attribute access +- Supporting function creation and closure handling +""" + +import collections +import dataclasses +import re +import sys +import types +from collections import Counter, deque +from collections.abc import Callable, Iterable +from typing import Any, TYPE_CHECKING, Union + +import torch.nn +from torch._library.opaque_object import is_opaque_constant_type +from torch.utils._ordered_set import OrderedSet + +from . import config, graph_break_hints, utils +from .bytecode_transformation import ( + add_push_null, + add_push_null_call_function_ex, + create_binary_subscr, + create_build_tuple, + create_call_function, + create_call_function_ex, + create_call_method, + create_dup_top, + create_instruction, + create_load_const, + create_load_method, + create_rot_n, + Instruction, +) +from .exc import unimplemented +from .source import AttrSource, ChainedSource, DictGetItemSource, Source +from .utils import is_safe_constant, rot_n_helper +from .variables.base import ValueMutationExisting, VariableTracker +from .variables.functions import ( + ContextlibContextManagerLocalGeneratorObjectVariable, + LocalGeneratorObjectVariable, +) +from .variables.lazy import ComputedLazyConstantVariable +from .variables.nn_module import NNModuleVariable +from .variables.script_object import CustomClassObjectVariable +from .variables.tensor import ( + NumpyNdarrayVariable, + SymNodeVariable, + TensorVariable, + UnspecializedPythonVariable, +) +from .variables.torch_function import TensorWithTFOverrideVariable + + +if TYPE_CHECKING: + from torch._dynamo.variables.builder import GraphArg + + from .symbolic_convert import InstructionTranslatorBase + + +@dataclasses.dataclass +class GraphOutputEntry: + index: int + variable: VariableTracker + + +class PyCodegen: + """ + Helper class uses for constructing Python bytecode + """ + + def __init__( + self, + tx: "InstructionTranslatorBase", + root: torch.nn.Module | None = None, + graph_output_var: str | None = None, + tempvars: dict[VariableTracker | Source, Any] | None = None, + overridden_sources: dict[Source, Source] | None = None, + ) -> None: + self.root = root + self.top_of_stack: VariableTracker | Source | None = None + self.uses: Counter[VariableTracker | Source] = collections.Counter() + self.graph_outputs: dict[int, GraphOutputEntry] = {} + self._output: list[Instruction] = [] + # This determines which VariableTracker/Source should be stored as + # locals, and maps the VariableTracker/Source to the local variable + # name. Note that it could map to None initially, in which case we'll + # overwrite it to map to real temporary names via `add_cache`. + self.tempvars: dict[VariableTracker | Source, Any] = tempvars or {} + self.tx = tx + self.graph_output_var = graph_output_var + self.code_options = self.tx.output.code_options + self.cell_and_freevars = self.tx.cell_and_freevars + self.new_var = self.tx.output.new_var + self.value_from_source: bool = True + # This serves as a way for codegen to use a different source; we need + # this because sometimes we can't easily modify the original source + # without affecting other components, e.g., guards. + self.overridden_sources: dict[Source, Source] = overridden_sources or {} + self.pycodes = [] + + def add_pycode(self, pycode: str, *args): + if not config.generate_pycode: + return + for a in args: + if isinstance(a, VariableTracker): + a.realize() + self.pycodes.append(pycode.format(*[a.reconstruct_pycode(self) for a in args])) + + def restore_stack( + self, stack_values: list[Any], *, value_from_source: bool = True + ) -> None: + prev = self.value_from_source + self.value_from_source &= value_from_source + try: + self.foreach(stack_values) + # `restore_stack` is called once per codegen pass (e.g. pass1 for + # use tracking, pass2 for actual emission). Reset the stack counter + # so each pass produces the same `__stackN` names. + self.tx.reset_pycode_varname_counter("stack") + for v in stack_values: + self.add_pycode(f"{self.tx.new_pycode_varname('stack')} = {{}}", v) + finally: + self.value_from_source = prev + + def graph_output_vars(self) -> list[VariableTracker]: + return [x.variable for x in self.graph_outputs.values()] + + def call_reconstruct( + self, value: Union[VariableTracker, Source, "GraphArg"] + ) -> None: + res = value.reconstruct(self) + if res is not None: + raise AssertionError(f"reconstruct!=None {value}") + + def add_push_null( + self, gen_fn: Callable[[], None], call_function_ex: bool = False + ) -> None: + """ + `gen_fn` generates instructions via PyCodegen methods + that push a single callable to the stack. + + `add_push_null` pushes a NULL to the stack before or after the + instructions generated by `gen_fn`, depending on Python version. + + Will attempt to use the NULL push bit for instructions + with such bits (LOAD_GLOBAL 3.11+, LOAD_ATTR 3.12+, LOAD_SUPER_ATTR). + """ + old_len = len(self._output) + if sys.version_info < (3, 13): + # gen_fn may DUP_TOP instead if TOS is not cleared. + # Will cause problems since NULL will be pushed right + # before the generated instructions in <= 3.12 + self.clear_tos() + gen_fn() + # inplace modify self._output + added_insts = self._output[old_len:] + del self._output[old_len:] + if call_function_ex: + self._output.extend(add_push_null_call_function_ex(added_insts)) + else: + self._output.extend(add_push_null(added_insts)) + if sys.version_info >= (3, 13): + # NULL will be at top of stack + self.clear_tos() + + def __call__( + self, value: VariableTracker | Source | None, allow_cache: bool = True + ) -> None: + """ + Generate code such that top-of-stack (TOS) is set to value. + + `allow_cache` controls the behavior in the following manner. `value` can + either be a VariableTracker or a Source. + + If `value` is a `Source`, `allow_cache` must be True (invariant asserted + below). If the source was reconstructed earlier, we will reuse the + generated code by loading from top of stack or tempvars. + + If `value` is a `VariableTracker`, we have the following cases: + + 1) `allow_cache=True` + a) If the value.source is not None, we will emit the code based on + `value.source` to handle aliasing. + b) If value.source is None (example reconstructing a local list + returned by the compiled function), we will reconstruct the variable + tracker (w/o any source) to emit bytecode that generates a new + python object. + + In both cases of value.source being None or not, if the value was + reconstructed earlier, we will reuse the generated code by loading from + top of stack or tempvars. + + 2) `allow_cache=False` - This is a special case (allow_cache defaults to + True). + a) If the value.source is not None, we reconstruct the variable + tracker and emit a new python object. You might wonder what about + aliasing? The place where we use this config also has the followup + code where the original python object is assigned to this new python + value to handle aliasing (check side_effects.py and search for + allow_cache=False). + + b) If value.source is None, this is not allowed + + Notable effects: + 1. `self.top_of_stack` will be set to `value`, if we don't codegen + `value` based on source. + 2. `self.uses[value]` will increment, unless (a). we codegen via + `top_of_stack` or cached `tempvars`, or (b). `value` has special VT + types like `NNModuleVariable`, etc. + """ + if value is None: + raise AssertionError("value must not be None") + if isinstance(value, Source): + # If the source needs to be overridden, use the new one. + source = self.overridden_sources.get(value, value) + if allow_cache is not True: + raise AssertionError("allow_cache must be True for Source") + if self.top_of_stack is value: + self._output.append(create_dup_top()) + return + + if self.tempvars.get(source) is not None: + self._output.append(self.create_load(self.tempvars[source])) + self.top_of_stack = source + return + + self.uses[source] += 1 + try: + self.call_reconstruct(source) + except NotImplementedError: + unimplemented( + gb_type="Reconstruction failure: source.reconstruct not implemented", + context=str(source), + explanation=f"Dynamo has no bytecode reconstruction implemented for {type(source)} variable {source}.", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + if source in self.tempvars: + self._output.append(create_dup_top()) + self.add_cache(source) + self.top_of_stack = source + + return + + if not isinstance(value, VariableTracker): + raise AssertionError(f"expected VariableTracker, got {type(value)}") + output = self._output + graph_outputs = self.graph_outputs + + if allow_cache: + if self.top_of_stack is value: + output.append(create_dup_top()) + return + + if self.tempvars.get(value) is not None: + output.append(self.create_load(self.tempvars[value])) + self.top_of_stack = value + return + + if value.is_realized() and isinstance( + value, ContextlibContextManagerLocalGeneratorObjectVariable + ): + unimplemented( + gb_type="reconstructing @contextmanager object", + context=f"object: {value}", + explanation="Returning a @contextmanager object from a compiled function is not supported.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + # Dynamo normally prefers codegen from source to account for aliasing. + if ( + value.source is not None + and allow_cache + and not ( + value.is_realized() and isinstance(value, LocalGeneratorObjectVariable) + ) + ): + # There's a corner case for export: for instance, if the computation + # graph is just identity on an input tensor, Dynamo would just emit + # a `LOAD_FAST` from the input source, rather than generating an + # identity FX graph. + # + # However, export wants to maximize graph capture; in the case + # above, export _wants to_ obtain an identity FX graph (despite it + # appears unnecessarily expensive for `torch.compile`), so we have + # the following option to override Dynamo's preference for codegen + # from source. Moreover, this option applies recursively, for cases + # like input tensor being returned in a new dictionary. + # + # And why the `ValueMutationExisting` check? Not sure, so leaving it + # to keep the old behavior, as when `value_from_source` was + # introduced. TODO sort out the invariants among side effect, + # codegen and export. + if ( + isinstance(value.mutation_type, ValueMutationExisting) + or self.value_from_source + ): + return self(value.source) + + if isinstance(value, ComputedLazyConstantVariable) and not value.is_realized(): + # Recompute from the operands at runtime instead of burning in the value + self.uses[value] += 1 + self.call_reconstruct(value) + if allow_cache and value in self.tempvars: + self._output.append(create_dup_top()) + self.add_cache(value) + elif value.is_python_constant() and is_safe_constant( + value.as_python_constant() + ): + output.append(self.create_load_const(value.as_python_constant())) + elif isinstance(value, TensorWithTFOverrideVariable): + graph_outputs_key = self.add_graph_output(value) + + self.add_push_null( + lambda: self.load_import_from(utils.__name__, "to_subclass") + ) + self.load_graph_output(graph_outputs[graph_outputs_key].index) + output.append( + self.create_load_global( + value.global_mangled_class_name(self.tx), # type: ignore[arg-type] + add=True, + ) + ) + output.extend(create_call_function(2, False)) + elif ( + isinstance(value, SymNodeVariable) + and value.python_type() is float + and not self.tx.export + ): + # This is a little unusual; force the output convention to be a + # Tensor here. Don't do this for export because this is + # apparently load bearing for export tests (but I am a bit + # doubtful it actually works in the real world) + # NB: It works to add_graph_output on a computed expression + # as_tensor here, because we memoize as_tensor calls on + # SymNodeVariable! + graph_outputs_key = self.add_graph_output( + value.as_tensor(self.tx, torch.float64) + ) + + def gen_fn() -> None: + self.load_graph_output(graph_outputs[graph_outputs_key].index) + output.append(self.create_load_attr("item")) + + self.add_push_null(gen_fn) + output.extend(create_call_function(0, False)) + elif isinstance( + value, + ( + TensorVariable, + SymNodeVariable, + UnspecializedPythonVariable, + NumpyNdarrayVariable, + CustomClassObjectVariable, + ), + ): + graph_outputs_key = self.add_graph_output(value) + + if isinstance(value, NumpyNdarrayVariable): + self.add_push_null( + lambda: self.load_import_from(utils.__name__, "to_numpy_helper") + ) + self.load_graph_output(graph_outputs[graph_outputs_key].index) + output.extend(create_call_function(1, False)) + elif isinstance(value, UnspecializedPythonVariable) and value.need_unwrap: + + def gen_fn() -> None: + self.load_graph_output(graph_outputs[graph_outputs_key].index) + output.append(self.create_load_attr("item")) + + self.add_push_null(gen_fn) + output.extend(create_call_function(0, False)) + elif isinstance(value, CustomClassObjectVariable): + try: + py_value = value.as_python_constant() + except NotImplementedError: + py_value = None + + if is_opaque_constant_type(type(py_value)): + self.add_push_null( + lambda: self.load_import_from( + "torch._library.fake_class_registry", + "maybe_unwrap_fake_script_object", + ) + ) + self.load_graph_output(graph_outputs[graph_outputs_key].index) + output.extend(create_call_function(1, False)) + else: + self.load_graph_output(graph_outputs[graph_outputs_key].index) + else: + self.load_graph_output(graph_outputs[graph_outputs_key].index) + elif isinstance(value, NNModuleVariable): + parts = value.module_key.split(".") + if parts[0] in self.code_options["co_varnames"]: + output.append(self.create_load(parts[0])) + parts = parts[1:] + else: + if self.root is None: + raise AssertionError("self.root must not be None") + output.append(self.create_load_const_unchecked(self.root)) + for part in parts: + output.append(self.create_load_attr(part)) + else: + self.uses[value] += 1 + try: + self.call_reconstruct(value) + except NotImplementedError as e: + unimplemented( + gb_type="Reconstruction failure", + context=str(value), + explanation=f"Dynamo has no bytecode reconstruction implemented for sourceless variable {value}.", + hints=[ + "If Dynamo is attempting to trace a return statement and your code is attempting to return a variable " + "that Dynamo cannot reconstruct, then remove it from the return statement.", + *graph_break_hints.CAUSED_BY_EARLIER_GRAPH_BREAK, + "Report an issue to PyTorch if you need reconstrtuction support. Note that objects that don't have " + "reconstruction rules may be fundamentally unreconstructable.", + ], + from_exc=e, + ) + if allow_cache and value in self.tempvars: + self._output.append(create_dup_top()) + self.add_cache(value) + + self.top_of_stack = value + + def add_graph_output(self, value: VariableTracker) -> int: + graph_outputs_key = id(value.as_proxy()) + if graph_outputs_key not in self.graph_outputs: + self.graph_outputs[graph_outputs_key] = GraphOutputEntry( + len(self.graph_outputs), value + ) + return graph_outputs_key + + def load_graph_output(self, index: int) -> None: + output = self._output + if self.graph_output_var is None: + raise AssertionError("graph_output_var must not be None") + output.append(self.create_load(self.graph_output_var)) + output.append(self.create_load_const(index)) + output.append(self.create_binary_subscr()) + + def add_cache(self, value: VariableTracker | Source) -> None: + var = self.new_var() + self.tempvars[value] = var + self._output.append(self.create_store(var)) + + def foreach(self, items: Iterable[VariableTracker | Source]) -> None: + for i in items: + self(i) + + def create_binary_subscr(self) -> Instruction: + return create_binary_subscr() + + def setup_globally_cached(self, name: str, value: Any) -> list[Instruction]: + """Store value in a new global""" + name = re.sub(r"[^a-zA-Z0-9_]+", "_", name) + f_globals = self.tx.f_globals + if name in f_globals: + if id(f_globals[name]) != id(value): + raise AssertionError( + f"f_globals[{name!r}] already exists with a different identity" + ) + else: + f_globals[name] = value + return [self.create_load_global(name, add=True)] + + def clear_tos(self) -> None: + self.top_of_stack = None + + def append_output(self, inst: Instruction) -> None: + if not isinstance(inst, Instruction): + raise AssertionError(f"expected Instruction, got {type(inst)}") + self._output.append(inst) + self.clear_tos() + + def extend_output(self, insts: list[Instruction]) -> None: + if not all(isinstance(x, Instruction) for x in insts): + raise AssertionError("all elements of insts must be Instruction instances") + self._output.extend(insts) + self.clear_tos() + + def get_instructions(self) -> list[Instruction]: + return self._output + + def get_pycode(self) -> list[str] | None: + if not config.generate_pycode: + return None + return self.pycodes + + def create_load(self, name: str) -> Instruction: + if name not in self.code_options["co_varnames"]: + raise AssertionError(f"{name} missing") + return create_instruction("LOAD_FAST", argval=name) + + def create_load_closure(self, name: str) -> Instruction: + if name not in self.cell_and_freevars(): + raise AssertionError(f"{name!r} not in cell_and_freevars") + inst_name = "LOAD_FAST" if sys.version_info >= (3, 13) else "LOAD_CLOSURE" + return create_instruction(inst_name, argval=name) + + def create_load_deref(self, name: str) -> Instruction: + if name not in self.cell_and_freevars(): + raise AssertionError(f"{name!r} not in cell_and_freevars") + return create_instruction("LOAD_DEREF", argval=name) + + def create_store(self, name: str) -> Instruction: + if name not in self.code_options["co_varnames"]: + raise AssertionError(f"{name} missing") + return create_instruction("STORE_FAST", argval=name) + + def create_store_deref(self, name: str) -> Instruction: + if name not in self.cell_and_freevars(): + raise AssertionError(f"{name!r} not in cell_and_freevars") + return create_instruction("STORE_DEREF", argval=name) + + def create_load_global(self, name: str, add: bool = False) -> Instruction: + if add: + self.tx.output.update_co_names(name) + if name not in self.code_options["co_names"]: + raise AssertionError(f"{name} not in co_names") + return create_instruction("LOAD_GLOBAL", argval=name) + + def create_load_const(self, value: Any) -> Instruction: + return create_load_const(value) + + def create_load_const_unchecked(self, value: Any) -> Instruction: + return create_load_const(value, checked=False) + + def load_method(self, name: str) -> None: + self.tx.output.update_co_names(name) + self.append_output(create_load_method(name)) + + def call_method(self, nargs: int) -> None: + self.extend_output(create_call_method(nargs)) + + def create_list_append(self) -> list[Instruction]: + # Append TOS to the list at TOS-1, leaving the list on the stack + # (same stack effect as LIST_APPEND with arg=1). + # + # The bare LIST_APPEND opcode does not lock the list and so requires + # the target be uniquely owned (refcnt == 1) on free-threaded builds. + # Dynamo can't enforce this, so instead use LIST_EXTEND, which does + # lock + return [ + create_instruction("BUILD_LIST", arg=1), + create_instruction("LIST_EXTEND", arg=1), + ] + + def create_load_attr(self, name: str) -> Instruction: + if name not in self.code_options["co_names"]: + self.code_options["co_names"] += (name,) + return create_instruction("LOAD_ATTR", argval=name) + + def load_attr(self, name: str) -> None: + self.append_output(self.create_load_attr(name)) + + def create_load_attrs(self, names: str) -> list[Instruction]: + return [self.create_load_attr(name) for name in names.split(".")] + + def create_store_attr(self, name: str) -> Instruction: + if name not in self.code_options["co_names"]: + self.code_options["co_names"] += (name,) + return create_instruction("STORE_ATTR", argval=name) + + def store_attr(self, name: str) -> None: + self.append_output(self.create_store_attr(name)) + + def load_function_name( + self, fn_name: str, push_null: bool, num_on_stack: int = 0 + ) -> list[Instruction]: + """Load the global fn_name on the stack num_on_stack down""" + output = [] + if push_null and sys.version_info >= (3, 11): + output.extend(add_push_null(self.create_load_global(fn_name, add=True))) + if num_on_stack > 0: + output.extend( + [ + *self.rot_n(num_on_stack + 2), + *self.rot_n(num_on_stack + 2), + ] + ) + else: + output.extend( + [ + self.create_load_global(fn_name, add=True), + *self.rot_n(num_on_stack + 1), + ] + ) + return output + + def rot_n(self, n: int) -> list[Instruction]: + try: + return create_rot_n(n) + except AttributeError: + # desired rotate bytecode doesn't exist, generate equivalent bytecode + return [ + create_build_tuple(n), + self.create_load_const_unchecked(rot_n_helper(n)), + *create_rot_n(2), + *create_call_function_ex(False, False), + create_instruction("UNPACK_SEQUENCE", arg=n), + ] + + def pop_null(self) -> list[Instruction]: + # POP_TOP doesn't work for null, so we pop nulls by pushing in a + # nop function, calling it (which consumes the null), and popping the result. + if sys.version_info < (3, 11): + raise AssertionError("pop_null requires Python 3.11+") + return [ + self.create_load_const_unchecked(lambda: None), + # 3.13 swapped NULL and callable + *( + (create_instruction("SWAP", arg=2),) + if sys.version_info >= (3, 13) + else () + ), + *create_call_function(0, False), + create_instruction("POP_TOP"), + ] + + def pop_top(self) -> None: + self.append_output(create_instruction("POP_TOP")) + + def call_function(self, nargs: int, push_null: bool) -> None: + self.extend_output(create_call_function(nargs, push_null=push_null)) + + def dup_top(self) -> None: + self.append_output(create_dup_top()) + + def store(self, varname: str) -> None: + self.append_output(self.create_store(varname)) + + def load_deref(self, varname: str) -> None: + self.append_output(self.create_load_deref(varname)) + + def make_function_with_closure( + self, + fn_name: str, + code: types.CodeType, + ) -> None: + """Creates a closure with code object `code`. + + Expects the TOS to be the tuple of cells to use for this closure. + TOS will be popped to create the closure. + Args: + - fn_name: name of the function + - code: code object of the function + (does not include the tuple of cells on the TOS) + """ + output = self._output + + output.append(self.create_load_const(code)) + if sys.version_info < (3, 11): + output.append(self.create_load_const(fn_name)) + if sys.version_info >= (3, 13): + output.extend( + [ + create_instruction("MAKE_FUNCTION"), + create_instruction("SET_FUNCTION_ATTRIBUTE", arg=0x08), + ] + ) + else: + output.append(create_instruction("MAKE_FUNCTION", arg=0x08)) + + self.clear_tos() + + def create_load_python_module(self, mod: types.ModuleType) -> Instruction: + """ + Generate a LOAD_GLOBAL instruction to fetch a given python module. + """ + output = self.tx.output + global_scope = output.global_scope + name = re.sub(r"^.*[.]", "", mod.__name__) + if global_scope.get(name, None) is mod: + return self.create_load_global(name, add=True) + prefix = f"___module_{name}" + global_name = self.tx.output.install_global_by_id(prefix, mod) + return self.create_load_global(global_name, add=True) + + def mark_source_temp(self, source: Source) -> None: + """ + Mark a source as a temp variable, so that it can be reused. + """ + if source not in self.tempvars: + self.tempvars[source] = None + + def make_call_generated_code(self, fn_name: str) -> None: + """Call the generated code function stored in fn_name""" + self.extend_output(self.load_function_name(fn_name, True)) + + graphargs = self.tx.output.graphargs + + def extract_nested_sources(source: Source) -> list[Source]: + nested_sources: list[Source] = [] + if isinstance(source, ChainedSource): + nested_sources.append(source.base) + if isinstance(source, DictGetItemSource) and isinstance( + source.index, Source + ): + nested_sources.append(source.index) + return nested_sources + + def collect_temp_sources(sources: deque[Source], codegen: PyCodegen) -> None: + seen_sources: OrderedSet[Source] = OrderedSet() + while sources: + current_source = sources.popleft() + if current_source in seen_sources: + # This source is used at least twice, so it can be reused + codegen.mark_source_temp(current_source) + # Don't trace source further. This prevents us from marking too + # many nodes as temp sources. + continue + seen_sources.add(current_source) + sources.extend(extract_nested_sources(current_source)) + + # Collect all the sources that are used more than once, so that we can + # generate tmp variables in the generated pre-graph bytecode. This + # essentially implements CSE. + collect_temp_sources( + deque([arg.source for arg in graphargs if arg.source is not None]), self + ) + + cm_var = None + if config.record_runtime_overhead: + # Record the pregraph bytecode start + self.add_push_null( + lambda: self.load_import_from( + utils.__name__, "record_pregraph_bytecode_enter" + ) + ) + self.extend_output(create_call_function(0, False)) + cm_var = self.new_var() + self.store(cm_var) + + arg_varnames = [] + for i, arg in enumerate(graphargs): + arg_varname = self.tx.new_pycode_varname("arg") + arg_varnames.append(arg_varname) + if arg.pass_arg_as_tensor: + self.add_push_null( + lambda: self.extend_output( + [ + self.create_load_python_module(torch), + self.create_load_attr("_as_tensor_fullprec"), + ] + ) + ) + self.call_reconstruct(arg) + self.extend_output(create_call_function(1, False)) + self.add_pycode(f"{arg_varname} = torch._as_tensor_fullprec({{}})", arg) + else: + self.call_reconstruct(arg) + self.add_pycode(f"{arg_varname} = {{}}", arg) + + if config.record_runtime_overhead: + # Record the pregraph bytecode end + self.add_push_null( + lambda: self.load_import_from( + utils.__name__, "record_pregraph_bytecode_exit" + ) + ) + if cm_var is None: + raise AssertionError("cm_var must not be None") + self.extend_output([self.create_load(cm_var)]) + self.extend_output(create_call_function(1, False)) + self.pop_top() + + self.extend_output(create_call_function(len(graphargs), False)) + self.add_pycode( + f"__graph_out = {fn_name}({', '.join(arg_varnames)})", + ) + + def create_import_name(self, module_name: str) -> Instruction: + return create_instruction("IMPORT_NAME", argval=module_name) + + def load_import_from(self, module_name: str, object_name: str) -> None: + source = AttrSource(self.tx.import_source(module_name), object_name) + # Note: This approach is somewhat aggressive because typically, a source is marked + # as a tempvar only when it is used more than once. In this case, we're marking it + # as a tempvar without performing that analysis. However, this is a simple solution, + # and in many cases, load imports are reused multiple times. + self.mark_source_temp(source) + self(source) + + def create_call_function_kw( + self, nargs: int, kw_names: Iterable[str], push_null: bool + ) -> list[Instruction]: + if sys.version_info >= (3, 13): + output = create_call_function(nargs, push_null) + if output[-1].opname != "CALL": + raise AssertionError( + f"expected last instruction to be CALL, got {output[-1].opname}" + ) + output.insert(-1, self.create_load_const(kw_names)) + output[-1] = create_instruction("CALL_KW", arg=nargs) + return output + elif sys.version_info >= (3, 11): + output = create_call_function(nargs, push_null) + if sys.version_info >= (3, 12): + idx = -1 + expected_inst = "CALL" + else: + idx = -2 + expected_inst = "PRECALL" + if output[idx].opname != expected_inst: + raise AssertionError( + f"expected instruction at index {idx} to be {expected_inst}, " + f"got {output[idx].opname}" + ) + kw_names_inst = create_instruction("KW_NAMES", argval=kw_names) + output.insert(idx, kw_names_inst) + return output + return [ + self.create_load_const(kw_names), + create_instruction("CALL_FUNCTION_KW", arg=nargs), + ] + + def create_delete(self, value: object) -> Instruction: + return create_instruction("DELETE_FAST", argval=value) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/compiled_autograd.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/compiled_autograd.py new file mode 100644 index 0000000000000000000000000000000000000000..9edb103a6a51dfd6a1444b2af560107d8decb051 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/compiled_autograd.py @@ -0,0 +1,1794 @@ +""" +Provides functionality for compiling PyTorch's autograd (automatic differentiation) system. + +This module implements compiled autograd, which traces and optimizes backward pass +computations at runtime. The key components are: + +- AutogradCompilerInstance: Traces and compiles autograd graphs using FX +- Context managers (_enable/_disable): Control when compiled autograd is active +- Utility functions: Support graph manipulation, tensor operations, and hooks + +Compiled autograd can significantly improve backward pass performance by removing +Python overhead and enabling additional optimizations. It works by capturing +backward computations into an FX graph that can be compiled and optimized, +while maintaining the same semantics as eager mode autograd. +""" + +import contextlib +import functools +import itertools +import operator +import time +from collections import Counter, defaultdict +from collections.abc import Callable, Generator, Sequence +from typing import Any, cast, Literal, Protocol, TYPE_CHECKING + +import torch +import torch.utils._pytree as pytree +from torch._dispatch.python import enable_python_dispatcher +from torch._dynamo.external_utils import ( + call_accumulate_grad, + call_backward, + call_hook, + FakeCompiledAutogradEngine, + unwrap_maybe_dynamic_int, +) +from torch._dynamo.source import GetItemSource, LocalSource +from torch._dynamo.utils import ( + counters, + get_chromium_event_logger, + lazy_format_graph_code, + set_locals_to_steal, +) +from torch._functorch._aot_autograd.runtime_wrappers import ( + AutogradLazyBackwardCompileInfo, + CachedAutogradLazyBackwardCompileInfo, +) +from torch._guards import compile_context, CompileContext, CompileId, Source +from torch._logging import getArtifactLogger, trace_structured +from torch._prims_common import clone_preserve_strides +from torch._subclasses import FakeTensorMode +from torch._subclasses.fake_tensor import FakeTensor +from torch.fx import GraphModule +from torch.fx.experimental._backward_state import BackwardState +from torch.fx.experimental.proxy_tensor import ( + disable_autocast_cache, + disable_proxy_modes_tracing, + fetch_object_proxy, + ProxyTorchDispatchMode, + PythonKeyTracer, + track_tensor_tree, +) +from torch.fx.experimental.symbolic_shapes import DimDynamic, ShapeEnv +from torch.fx.traceback import preserve_node_meta, set_stack_trace +from torch.types import FloatLikeType, IntLikeType +from torch.utils._ordered_set import OrderedSet +from torch.utils._traceback import CapturedTraceback + + +if TYPE_CHECKING: + from torch._functorch._aot_autograd.schemas import SubclassMeta, ViewAndMutationMeta + from torch.fx.proxy import Proxy + + +TURN_OFF_MSG = """You can turn off compiled autograd by either: +1. Moving the unsupported autograd call outside of the torch.compile'd region. +2. Wrapping the unsupported autograd call in the torch._dynamo.compiled_autograd._disable() context manager. +3. Setting torch._dynamo.config.compiled_autograd=False for the torch.compile call containing the unsupported autograd call. +4. Setting torch._dynamo.config.compiled_autograd=False at the start of the program.""" + +compiled_autograd_log = getArtifactLogger(__name__, "compiled_autograd") +verbose_log = getArtifactLogger(__name__, "compiled_autograd_verbose") + +# The kind of autograd hook being proxied. Threaded through proxy_call_hook into +# the fx node's kwargs, where the graph post-processing passes read it back to +# match nodes (e.g. node.kwargs["hook_type"] == "post_hook"). +HookType = Literal[ + "unpack_hook", + "tensor_pre_hook", + "pre_hook", + "post_hook", + "post_acc_grad_hook", +] + + +def snapshot_verbose_logging_enabled() -> bool: + return torch._logging._internal.log_state.is_artifact_enabled( + "compiled_autograd_verbose" + ) + + +def snapshot_cudagraph_enabled() -> bool: + return torch._inductor.config.triton.cudagraphs + + +def maybe_clone(x: torch.Tensor | None) -> torch.Tensor | None: + if x is not None: + return clone_preserve_strides(x) + return x + + +class _AOTCompiledFunction(Protocol): + """Structural type for the AOTAutograd autograd.Function subclass that + compiled autograd retraces. The concrete class is generated locally inside + AOTAutograd, so we describe only the private attributes consumed here. + """ + + _lazy_backward_info: ( + AutogradLazyBackwardCompileInfo | CachedAutogradLazyBackwardCompileInfo | None + ) + metadata: "ViewAndMutationMeta" + maybe_subclass_metadata: "SubclassMeta | None" + _aot_id: int + _bw_prologue_fn: Callable[..., Any] + _bw_epilogue_fn: Callable[..., Any] + + +def extract_bw_module(CompiledFunction: _AOTCompiledFunction) -> GraphModule: + if isinstance( + CompiledFunction._lazy_backward_info, AutogradLazyBackwardCompileInfo + ): + return cast(GraphModule, CompiledFunction._lazy_backward_info.bw_module) + elif isinstance( + CompiledFunction._lazy_backward_info, CachedAutogradLazyBackwardCompileInfo + ): + with torch._subclasses.fake_tensor.unset_fake_temporarily(): + return CompiledFunction._lazy_backward_info.bw_module_fn() + else: + raise AssertionError( + "Unexpected Lazy Backward Compilation Info Type. Please file an issue." + ) + + +# Note: [Anomaly Mode Semantics in Compiled Autograd] +# In the eager autograd engine, anomaly mode is able to detect NaNs +# after each node. This is useful, because the executed code with +# and without anomaly mode are the same. So assuming determinism, +# a NaN in regular mode should also happen in anomaly mode. +# +# With torch.compile, following eager semantics would require inserting +# runtime asserts to check for NaNs, which could prevent some fusions. +# This results in different code being run with and without anomaly mode. +# So different semantics are needed, this implementation below will check +# for NaNs at the end of the autograd call, instead of after each node +class NaNChecker: + def __init__(self, accumulate_grad: bool) -> None: + self.accumulate_grad = accumulate_grad + self.params_indices: list[int] = [] + self.params_to_check: dict[str, torch.Tensor] = {} + self.output_names: list[str] = [] + + def prep_with_graph(self, graph: torch.fx.Graph) -> None: + inputs_node = next(iter(graph.nodes)) + acc_grad_nodes = graph.find_nodes( + op="call_function", target=call_accumulate_grad + ) + output_nodes = graph.find_nodes(op="output")[0].args[0] + if self.accumulate_grad != bool(acc_grad_nodes): + raise AssertionError( + f"accumulate_grad mismatch: expected {self.accumulate_grad}, " + f"got {bool(acc_grad_nodes)} acc_grad_nodes" + ) + if self.accumulate_grad != (not output_nodes): + raise AssertionError( + f"accumulate_grad mismatch with output_nodes: expected {self.accumulate_grad}, " + f"got {not output_nodes}" + ) + + for node in acc_grad_nodes: + param_node = node.args[0] + # AccumulateGrad always saves a reference to the param + # so Compiled Autograd will always lift the param and + # this should always be true + if param_node.target is not operator.getitem: + raise AssertionError( + f"Expected param_node target to be operator.getitem, got {param_node.target}" + ) + if param_node.args[0] is not inputs_node: # type: ignore[possibly-undefined] + raise AssertionError("Expected param_node.args[0] to be inputs_node") + if not isinstance(param_node.args[1], int): + raise AssertionError( + f"Expected param_node.args[1] to be int, got {type(param_node.args[1])}" + ) + self.params_indices.append(param_node.args[1]) + + self.output_names = [node.name for node in output_nodes] + + def prep_with_inputs(self, inputs: tuple[torch.Tensor, ...]) -> None: + if not self.accumulate_grad: + # Using .grad, nothing to prep + return + + # Using .backward, we must check existing grads on params if any + for idx in self.params_indices: + grad = inputs[idx].grad + if grad is not None: + if torch.isnan(grad).any(): + raise AssertionError( + f"Compiled autograd running under anomaly mode with inputs[{idx}] already " + f"having NaN gradient. This is not supported. {TURN_OFF_MSG}" + ) + + self.params_to_check[f"inputs[{idx}]"] = inputs[idx] + + def check(self, out: tuple[torch.Tensor, ...]) -> None: + if self.accumulate_grad: + # Using .backward, graph outputs are empty + if out: + raise AssertionError( + "Expected empty output for accumulate_grad backward" + ) + nan_params: list[str] = [] + for inputs_str, param in self.params_to_check.items(): + if param.grad is None: # not true for autograd.grad + raise AssertionError( + "Expected param.grad to be non-None for backward mode" + ) + if torch.isnan(param.grad).any(): + nan_params.append(inputs_str) + + if nan_params: + raise RuntimeError( + f"Compiled Autograd returned NaN gradients for parameters: {','.join(nan_params)}." + ) + else: + # Using .grad, graph outputs are grads + nan_grads: list[str] = [] + for i, grad in enumerate(out): + if torch.isnan(grad).any(): + nan_grads.append(self.output_names[i]) + + if nan_grads: + raise RuntimeError( + f"Compiled Autograd returned NaN gradients for output nodes: {','.join(nan_grads)}." + ) + + +# We lazily bind "functional backward" variants for PyTorch built-in autograd +# nodes to this class. Example: torch._dynamo.compiled_autograd.ops.MulBackward0 +# Each "functional backward" is bound the first time the node's apply_with_saved +# function is called. It's possible to avoid lazy binding and instead bind +# all of this upfront (perhaps at import time) via codegen changes. +class OpNamespace: + def __init__(self) -> None: + self.custom_function_name_counter: Counter[str] = Counter() + + def add( + self, + name: str, + fn: Callable[..., Any], + is_custom_function: bool, + is_traceable: bool, + ) -> str: + if is_custom_function: + name = "CppNode" + name + count = self.custom_function_name_counter[name] + self.custom_function_name_counter[name] += 1 + name = f"{name}{count}" + + if hasattr(self, name): + raise AssertionError(f"Op with name '{name}' already exists") + result = Op(name, fn, is_custom_function) + if is_traceable: + # pyrefly: ignore [deprecated] + setattr(self, name, torch._dynamo.allow_in_graph(result)) + else: + # C++ autograd function was not marked as traceable + # Dynamo can't dry run it at compile time, so must fallback to eager + @torch._dynamo.disable # type: ignore[misc] + def run_non_traceable_cpp_in_eager(*args: Any, **kwargs: Any) -> Any: + return result(*args, **kwargs) + + setattr(self, name, run_non_traceable_cpp_in_eager) + return name + + def get(self, name: str) -> Any: + return getattr(self, name) + + +class Op: + def __init__( + self, name: str, fn: Callable[..., Any], is_custom_function: bool + ) -> None: + self.fn = fn + self.is_custom_function = is_custom_function + self.__name__ = name + self.__module__ = "torch._dynamo.compiled_autograd.ops" + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + return self.fn(*args, **kwargs) + + def __repr__(self) -> str: + return self.__module__ + "." + self.__name__ + + +ops = OpNamespace() + + +_graph_placeholders = ["inputs", "sizes", "scalars", "hooks", "packed_data"] +_impure_targets = OrderedSet( + [ + call_hook, + call_backward, + FakeCompiledAutogradEngine._exec_final_callbacks_stub, + call_accumulate_grad, + ] +) + +COMPILE_COUNTER = itertools.count() + + +def make_compile_context(compiled_autograd_id: int) -> Any: + return compile_context( + CompileContext( + CompileId( + compiled_autograd_id=compiled_autograd_id, + frame_id=None, + frame_compile_id=None, + ) + ) + ) + + +class AutogradCompilerInstance: + def __init__(self, compiler_fn: Callable[..., Any]) -> None: + self.compiler_fn = compiler_fn + self.stack = contextlib.ExitStack() + self.close = self.stack.close + self.shape_env = ShapeEnv() + self.fake_tensor_mode = FakeTensorMode( + allow_fallback_kernels=True, + allow_non_fake_inputs=True, + shape_env=self.shape_env, + ) + self.fx_tracer = PythonKeyTracer() + self.proxy_mode = ProxyTorchDispatchMode(self.fx_tracer, "symbolic") + self.hooks_proxy: Proxy | None = None + + def wrap_fake(self, x: torch.Tensor, source: Source | None) -> FakeTensor: + if not isinstance(x, torch.Tensor): + raise AssertionError(f"Expected torch.Tensor, got {type(x)}") + return self.fake_tensor_mode.from_tensor(x, source=source) + + @staticmethod + def source(name: str, idx: Any) -> GetItemSource: + return GetItemSource(LocalSource(name), idx) + + def begin_capture( + self, + inputs: list[torch.Tensor], + sizes: list[int], + scalars: list[IntLikeType | FloatLikeType], + origins: list[list[tuple[int, str]]], + accumulate_grad: bool, + check_nans: bool, + ) -> tuple[str, list[torch.Tensor], list[IntLikeType], list[FloatLikeType]]: + counters["compiled_autograd"]["captures"] += 1 + self.id = next(COMPILE_COUNTER) + self.aot_id_counter: dict[int, int] = defaultdict(int) + self.compile_context = make_compile_context(self.id) + self.compile_context.__enter__() + self.nan_checker = NaNChecker(accumulate_grad) if check_nans else None + self.start_time_ns = time.time_ns() + get_chromium_event_logger().log_event_start( + "compiled_autograd", + self.start_time_ns, + {"graph_id": self.id}, + log_pt2_compile_event=True, + ) + self.fx_tracer.root = torch.nn.Module() + self.fx_tracer.graph = torch.fx.Graph(tracer_cls=PythonKeyTracer) + self.fx_tracer.tensor_attrs = {} + self.symnode_proxy_lookup = {} + ( + args_proxy, + self.sizes_proxy, + self.scalars_proxy, + self.hooks_proxy, + self.packed_data_proxy, + ) = ( + self.fx_tracer.create_proxy("placeholder", name, (), {}) + for name in _graph_placeholders + ) + + self.stack.enter_context(preserve_node_meta()) + inputs_origins, sizes_origins, scalars_origins = origins + + # Turn on PythonDispatcher during initial trace to make it identifiable + # that tracing is happening, which is needed to prevent hashing symints + self.stack.enter_context(enable_python_dispatcher()) + + # tensor inputs to fake tensors + x = inputs[0] # mypy will complain about unbound x + try: + for idx, x in enumerate(inputs): + inputs[idx] = self.wrap_fake(x, self.source("inputs", idx)) + except Exception as e: + raise NotImplementedError( + f"Found tensor of type {type(x)}, which is not supported by FakeTensorMode. {TURN_OFF_MSG}" + ) from e + self.bind_objects_to_proxies(inputs, args_proxy, inputs_origins) + + # size inputs to symints + sym_sizes = [ + self.shape_env.create_unspecified_symint_and_symbol( + val, + self.source("sizes", idx), + DimDynamic.DYNAMIC, + ) + for idx, val in enumerate(sizes) + ] + + # We want to mark every size as dynamic, but since there's no way to + # mark a primitive `int` as dynamic, we need to wrap it in a tensor. + # In the graph, we unwrap it with `unwrap_maybe_dynamic_int` back into a primitive. + proxies = [self.sizes_proxy[i] for i in range(len(sym_sizes))] # type: ignore[index] + for i, symint in enumerate(sym_sizes): + proxies[i] = self.fx_tracer.create_proxy( + "call_function", + unwrap_maybe_dynamic_int, + (proxies[i],), + {}, + ) + if not isinstance(symint, int): + self.symnode_proxy_lookup[symint.node] = proxies[i] + proxies = self.bind_objects_to_proxies(sym_sizes, proxies, sizes_origins) + + for idx, val in enumerate(scalars): + source = self.source("scalars", idx) + if isinstance(val, int): + scalars[idx] = self.shape_env.create_unspecified_symint_and_symbol( + val, + source, + DimDynamic.DYNAMIC, + ) + elif isinstance(val, float): + scalars[idx] = self.shape_env.create_symfloatnode( + self.shape_env.create_unspecified_symbol( + val, + source=source, + dynamic_dim=DimDynamic.DYNAMIC, + ), + hint=val, + source=source, + ) + else: + raise AssertionError("Unexpected scalar type: ", type(val)) + self.bind_objects_to_proxies(scalars, self.scalars_proxy, scalars_origins) + for i, symval in enumerate(scalars): + self.symnode_proxy_lookup[symval.node] = self.scalars_proxy[i] # type: ignore[union-attr] + + # TODO(jansel): are all these modes needed? + self.stack.enter_context(self.fake_tensor_mode) + self.stack.enter_context(self.proxy_mode) + self.stack.enter_context(disable_autocast_cache()) + # Needed to make sure we don't accidentally specialize any symbols + if self.fake_tensor_mode.shape_env is None: + raise AssertionError("fake_tensor_mode.shape_env must not be None") + env = self.fake_tensor_mode.shape_env + self.stack.enter_context( + torch.fx.experimental.symbolic_shapes._suppress_guards(env) + ) + # pyrefly: ignore [bad-return] + return ( + str(CompileContext.current_compile_id()), + inputs, + sym_sizes, + scalars, # type: ignore[return-value] + ) + + def log_compile_reasons( + self, + compile_reasons: list[str], + ) -> None: + if not compile_reasons: + raise AssertionError("compile_reasons must not be empty") + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "compiled_autograd_compile_reasons", + "encoding": "json", + }, + payload_fn=lambda: compile_reasons, + ) + + def proxy_call_aot_backward( + self, + pinputs: Sequence[Any], + psaved_tensors: Sequence[torch.Tensor], + saved_tensors: Sequence[torch.Tensor], + pctx: "Proxy", + ctx: torch.autograd.function.BackwardCFunction, + maybe_backward_state_idx: int | None, + opaque_object_indices: list[int], + ) -> Sequence[Any]: + # The AOTBackward call consists of three things: the prologue, the + # backward graph, and the epilogue. + # Our strategy is: + # - allow_in_graph the prologue (in the CA graph and Dynamo graph), + # - copy-paste the backward graph into the CA graph so that CA passes and Dynamo can see it + # - trace directly through the epilogue. Anything that gets baked in is + # constant metadata (for example, metadata about the number of outputs, or removing + # RNG arguments or effect tokens). + # If Dynamo graph capture were better, then we could add a node for the prologue + # into the CA graph and have Dynamo trace into it. + + psymints = [ + self.to_proxy(e) + for e in ctx._get_compiled_autograd_symints() # type: ignore[attr-defined] + ] + + popaque_objects = [ + self.hooks_proxy[idx] # type: ignore[index] + for idx in opaque_object_indices + ] + + # NOTE: we should only close over constants + CompiledFunction: _AOTCompiledFunction = ctx._forward_cls # type: ignore[attr-defined] + bw_module = extract_bw_module(CompiledFunction) + metadata = CompiledFunction.metadata + maybe_subclass_metadata = CompiledFunction.maybe_subclass_metadata + aot_id = CompiledFunction._aot_id + bw_prologue_fn = CompiledFunction._bw_prologue_fn + bw_epilogue_fn = CompiledFunction._bw_epilogue_fn + del CompiledFunction + + if torch.is_grad_enabled(): + for output_alias_info in metadata.output_info: + if output_alias_info.requires_grad: + raise RuntimeError( + "torch.compile does not currently support higher order gradients." + ) + + @torch._dynamo.allow_in_graph # type: ignore[misc] + def call_aot_bwd_prologue( + ctx_saved_tensors: Sequence[torch.Tensor], + ctx_symints: Sequence[IntLikeType], + ctx_opaque_objs: Sequence[Any], + flat_args: Sequence[Any], + ) -> Any: + return bw_prologue_fn( + ctx_saved_tensors, + ctx_symints, + ctx_opaque_objs, + flat_args, + ) + + pgrads = self.fx_tracer.create_proxy( + kind="call_function", + # pyrefly: ignore [bad-argument-type] + target=call_aot_bwd_prologue, + args=( + psaved_tensors, + psymints, + popaque_objects, + pinputs, + ), + kwargs={}, + ) + + pbackward_state = None + if maybe_backward_state_idx is not None: + pbackward_state = self.hooks_proxy[maybe_backward_state_idx] # type: ignore[index] + + # Copy-paste the AOT backward graph into the compiled autograd graph + def copy_paste_aot_backward_graph() -> list[torch.Tensor]: + def num_inputs(graph: torch.fx.Graph) -> int: + num_args = 0 + for node in graph.nodes: + if node.op == "placeholder": + num_args += 1 + continue + else: + break + return num_args + + # set up the proxy inputs to bw_module + # the calling convention is: [*symints, *args (primals and tangents), backward_state] + num_args = num_inputs(bw_module.graph) + pall_args = [ + pgrads[i] for i in range(num_args - int(pbackward_state is not None)) + ] + # replace the symints with our symints + symints = ctx._get_compiled_autograd_symints() # type: ignore[attr-defined] + if len(symints) != len(ctx.symints): # type: ignore[attr-defined] + raise AssertionError( + f"symints length mismatch: {len(symints)} vs {len(ctx.symints)}" # type: ignore[attr-defined] + ) + psymints = [self.to_proxy(e) for e in symints] + pall_args[: len(symints)] = psymints + # Add backward_state + if pbackward_state is not None: + pall_args.append(pbackward_state) + + # run over all nodes of the aot_backward graph. + # copy and paste them all into the compiled autograd graph. + args_idx = 0 + # pyrefly: ignore [implicit-any] + value_remap = {} + poutputs: list[torch.fx.Proxy] | None = None + + # names of nodes must appear only once in the fx.Graph + # dedup AOT backwards that appear multiple times + deduped_aot_id = str(aot_id) + if self.aot_id_counter[aot_id]: + deduped_aot_id += f"_{self.aot_id_counter[aot_id]}" + self.aot_id_counter[aot_id] += 1 + + def make_unique(node_name: str) -> str: + # make it both informative and unique + return f"aot{deduped_aot_id}_{node_name}" + + for node in bw_module.graph.nodes: + if node.op == "placeholder": + ph = pall_args[args_idx].node + ph.name = make_unique(node.name) + value_remap[node] = ph + args_idx += 1 + elif node.op == "output": + if len(node.args) != 1: + raise AssertionError( + f"Expected output node to have 1 arg, got {len(node.args)}" + ) + poutputs = [ + torch.fx.Proxy(value_remap[n], self.fx_tracer) + if isinstance(n, torch.fx.Node) + else n + for n in node.args[0] + ] + elif node.op == "get_attr": + name = node.target + qualname = self.fx_tracer.get_fresh_qualname(name) + setattr(self.fx_tracer.root, qualname, getattr(bw_module, name)) + result = self.fx_tracer.create_node("get_attr", qualname, (), {}) + result.name = make_unique(node.name) + value_remap[node] = result + elif node.op == "call_function": + if node.target is torch.ops.aten.view.default: + # this aot bwd graph is being lazily compiled + # we must manually apply the view_to_reshape post grad pass + # since it was already applied to the aot fwd, and baked into the gradients + node.target = torch.ops.aten.reshape.default + result = self.fx_tracer.graph.node_copy( + node, lambda n: value_remap[n] + ) + result.name = make_unique(node.name) + value_remap[node] = result + elif node.op == "call_module": + name = node.target + qualname = self.fx_tracer.get_fresh_qualname(name) + setattr(self.fx_tracer.root, qualname, getattr(bw_module, name)) + result = self.fx_tracer.graph.node_copy( + node, lambda n: value_remap[n] + ) + result.target = qualname + value_remap[node] = result + else: + raise AssertionError("shouldn't get here") + + if poutputs is None: + raise AssertionError("No output node found in backward graph") + + # In general we don't know what the shapes of the outputs are, so allocate + # some dummy sizes for them. + def dummy() -> torch.Tensor: + with disable_proxy_modes_tracing(): + return torch.zeros(0, 0, 0, 0, 123) + + outputs = [ + dummy() if isinstance(o, torch.fx.Proxy) else o for o in poutputs + ] + self.bind_objects_to_proxies(outputs, poutputs) + return outputs + + outputs = copy_paste_aot_backward_graph() + + if maybe_subclass_metadata is not None: + + def proxy_subclass_constructor( + subclass_meta: Any, + is_runtime: bool, + unwrapped_args: Sequence[Any], + ) -> torch.Tensor: + @torch._dynamo.allow_in_graph # type: ignore[misc] + def make_subclass(*unwrapped_args: Any) -> Any: + return subclass_meta.creation_fn( + unwrapped_args, is_runtime=is_runtime + ) + + punwrapped_args = pytree.tree_map(self.to_proxy, unwrapped_args) + + poutput = self.fx_tracer.create_proxy( + kind="call_function", + # pyrefly: ignore [bad-argument-type] + target=make_subclass, + args=tuple(punwrapped_args), + kwargs={}, + ) + + output = self.allocate_dummy() + self.bind_objects_to_proxies([output], [poutput]) + return output + + results = bw_epilogue_fn( + outputs, make_subclass_override=proxy_subclass_constructor + ) + else: + results = bw_epilogue_fn(outputs) + + presults = pytree.tree_map(self.to_proxy, results) + return presults + + def proxy_call_backward( + self, + inputs: Sequence[Any], + output_metadatas: Sequence[Any], + saved_tensors: Sequence[torch.Tensor], + backward_idx: int, + ctx: torch.autograd.function.BackwardCFunction, + maybe_backward_state_idx: int | None, + opaque_object_indices: list[int], + ) -> tuple[torch.Tensor | None, ...]: + if self.hooks_proxy is None: + raise AssertionError("hooks_proxy must be set before proxy_call_backward") + pctx = self.hooks_proxy[backward_idx] # type: ignore[index] + pinputs = self.to_proxy(inputs) + psaved_tensors = self.to_proxy(saved_tensors) + if hasattr(ctx._forward_cls, "_aot_id"): # type: ignore[attr-defined] + # AOT backward + proxies = self.proxy_call_aot_backward( + pinputs, + psaved_tensors, + saved_tensors, + pctx, + ctx, + maybe_backward_state_idx, + opaque_object_indices, + ) + else: + if getattr(ctx._forward_cls, "boxed_grads_call", False): # type: ignore[attr-defined] + raise RuntimeError( + f"boxed_grads_call=True on {ctx._forward_cls.__name__} " # type: ignore[attr-defined] + "is not supported with compiled autograd. " + ) + proxies = self.fx_tracer.create_proxy( + kind="call_function", + target=call_backward, + args=( + pctx, + psaved_tensors, + *pinputs, + ), + kwargs={}, + ) + if proxies is None: + raise AssertionError("proxies must not be None after backward call") + + with disable_proxy_modes_tracing(): + # create fake Tensors + grad_ins: list[torch.Tensor | None] = [] + for idx, output_metadata in enumerate(output_metadatas): + if output_metadata is None or proxies[idx] is None: + grad_ins.append(None) + continue + + layout, device, dtype, size = output_metadata + grad_ins.append( + torch.empty(size=size, dtype=dtype, layout=layout, device=device) + ) + self.bind_objects_to_proxies(grad_ins, proxies) + return tuple(grad_ins) + + def call_copy_slices_prologue( + self, + inputs: Sequence[Any], + base_sizes: Sequence[Any], + base_strides: Sequence[Any], + base_storage_offset: Any, + view_sizes: Sequence[Any], + view_strides: Sequence[Any], + view_storage_offset: Any, + ) -> Sequence[torch.Tensor]: + args = ( + inputs, + self.to_proxy(base_sizes), + self.to_proxy(base_strides), + self.to_proxy(base_storage_offset), + self.to_proxy(view_sizes), + self.to_proxy(view_strides), + self.to_proxy(view_storage_offset), + ) + return self.proxy_call(copy_slices_prologue, args, [None] * 3) + + def call_copy_slices_epilogue( + self, + needs_input_grad: Sequence[bool], + result: torch.Tensor, + res: Sequence[Any], + grad_slice: torch.Tensor, + ) -> Sequence[torch.Tensor]: + return self.proxy_call( + copy_slices_epilogue, + (needs_input_grad, result, res, grad_slice), + [None] * len(needs_input_grad), + ) + + def allocate_dummy(self) -> torch.Tensor: + with disable_proxy_modes_tracing(): + # Weird quantity so it's easy to grep + return torch.zeros([0, 123456789]) + + def allocate_dummy_like(self, x: torch.Tensor) -> torch.Tensor: + with disable_proxy_modes_tracing(): + return torch.empty_like(x) + + def bind_function( + self, + fn_name: str, + fn: Callable[..., Any], + is_custom_function: bool, + is_traceable: bool, + ) -> str: + """Binds ops.fn_name = fn""" + return ops.add(fn_name, fn, is_custom_function, is_traceable) + + def apply_functional( + self, + fn_name: str, + grads: Sequence[Any], + args: Any, + output_metadata: Sequence[Any], + ) -> Sequence[torch.Tensor]: + """Proxies a call to ops.fn_name(grads, *args) into the graph""" + op = ops.get(fn_name) + return self.proxy_call(op, (grads, *args), output_metadata) + + def proxy_call( + self, fn: Callable[..., Any], args: Any, output_metadata: Sequence[Any] + ) -> Sequence[torch.Tensor]: + """Proxies a call to fn(*args) into the graph""" + proxy_args = pytree.tree_map(lambda e: self.to_proxy(e), args) + proxy_out = self.fx_tracer.create_proxy( + "call_function", fn, args=proxy_args, kwargs={} + ) + result = [self.allocate_dummy() for _ in output_metadata] + self.bind_objects_to_proxies(result, [proxy_out[i] for i in range(len(result))]) + return result + + def validate_outputs( + self, _: Any, outputs: Sequence[Any], args: Any, output_metadata: Sequence[Any] + ) -> Sequence[torch.Tensor]: + """Proxies a call to ops.validate_outputs(outputs, *args) into the graph""" + op = ops.get("validate_outputs") + proxy_args = pytree.tree_map(self.to_proxy, (outputs, *args)) + new_proxy_outputs = self.fx_tracer.create_proxy( + "call_function", op, args=proxy_args, kwargs={} + ) + if len(output_metadata) != len(outputs): + raise AssertionError( + f"output_metadata length ({len(output_metadata)}) != outputs length ({len(outputs)})" + ) + self.bind_objects_to_proxies(outputs, new_proxy_outputs) + return outputs + + def accumulate(self, old_var: Any, new_var: Any) -> torch.Tensor: + old_var_proxy = self.to_proxy(old_var) + new_var_proxy = self.to_proxy(new_var) + proxy_out = self.fx_tracer.create_proxy( + "call_function", torch.add, args=(old_var_proxy, new_var_proxy), kwargs={} + ) + result = self.allocate_dummy() + self.bind_objects_to_proxies([result], [proxy_out]) + return result + + def accumulate_grad( + self, + variable: torch.Tensor, + variable_grad: torch.Tensor | None, + grad: torch.Tensor | bool, + has_post_hooks: bool | None = None, + ) -> torch.Tensor | None: + old_call = has_post_hooks is None + if has_post_hooks is None: + # Backward compatibility for extensions built before current grad + # became an explicit capture argument. + has_post_hooks = bool(grad) + grad = variable_grad # type: ignore[assignment] + variable_grad = variable.grad + + proxy_out = self.fx_tracer.create_proxy( + "call_function", + call_accumulate_grad, + args=( + self.to_proxy(variable), + self.to_proxy(variable_grad), + self.to_proxy(grad), + has_post_hooks, + ), + kwargs={}, + ) + result = self.allocate_dummy_like(variable) + self.bind_objects_to_proxies([result], [proxy_out]) + variable.grad = result + if old_call: + return None + return result + + def proxy_call_hook( + self, hook: Callable[..., Any], *args: Any, hook_type: HookType + ) -> torch.fx.Proxy: + return self.fx_tracer.create_proxy( + "call_function", + call_hook, + ( + hook, + *[self.to_proxy(x) for x in args], + ), + {"hook_type": hook_type}, + ) + + def unpack_hook(self, hook_id: int, data_id: int) -> torch.Tensor: + if self.hooks_proxy is None: + raise AssertionError("hooks_proxy must be set before unpack_hook") + hook = self.hooks_proxy[hook_id] # type: ignore[index] + data = self.packed_data_proxy[data_id] # type: ignore[index] + proxy = self.proxy_call_hook( + hook, + data, + hook_type="unpack_hook", + ) + out = self.allocate_dummy() + self.bind_objects_to_proxies([out], [proxy]) + return out + + def tensor_pre_hook( + self, inputs: list[torch.Tensor], hook_id: int, i: int + ) -> list[torch.Tensor]: + if self.hooks_proxy is None: + raise AssertionError("hooks_proxy must be set before tensor_pre_hook") + hook = self.hooks_proxy[hook_id] # type: ignore[index] + proxy = self.proxy_call_hook( + hook, + inputs[i], + hook_type="tensor_pre_hook", + ) + with disable_proxy_modes_tracing(): + inputs[i] = maybe_clone(inputs[i]) # type: ignore[assignment] + self.bind_objects_to_proxies([inputs[i]], [proxy]) + return inputs + + def cpp_tensor_pre_hook( + self, inputs: list[torch.Tensor], hook_id: int, i: int + ) -> list[torch.Tensor]: + proxy = self.fx_tracer.create_proxy( + "call_function", + torch._C._dynamo.compiled_autograd.call_cpp_tensor_pre_hooks, + (hook_id, self.to_proxy(inputs[i])), + {}, + ) + with disable_proxy_modes_tracing(): + inputs[i] = maybe_clone(inputs[i]) # type: ignore[assignment] + self.bind_objects_to_proxies([inputs[i]], [proxy]) + return inputs + + def pre_hook(self, inputs: Sequence[Any], hook_id: int) -> list[torch.Tensor]: + if self.hooks_proxy is None: + raise AssertionError("hooks_proxy must be set before pre_hook") + hook = self.hooks_proxy[hook_id] # type: ignore[index] + proxies = self.proxy_call_hook( + hook, + inputs, + hook_type="pre_hook", + ) + with disable_proxy_modes_tracing(): + inputs = [maybe_clone(x) for x in inputs] + self.bind_objects_to_proxies(inputs, proxies) + return inputs + + def post_hook( + self, outputs: list[torch.Tensor], inputs: Sequence[torch.Tensor], hook_id: int + ) -> list[torch.Tensor]: + if self.hooks_proxy is None: + raise AssertionError("hooks_proxy must be set before post_hook") + hook = self.hooks_proxy[hook_id] # type: ignore[index] + proxies = self.proxy_call_hook( + hook, + outputs, + inputs, + hook_type="post_hook", + ) + with disable_proxy_modes_tracing(): + outputs = [maybe_clone(x) for x in outputs] # type: ignore[misc] + self.bind_objects_to_proxies(outputs, proxies) + return outputs + + def post_acc_grad_hook( + self, input: torch.Tensor, hook_id: int + ) -> list[torch.Tensor]: + if not isinstance(input, torch.Tensor): + raise AssertionError(f"Expected torch.Tensor, got {type(input)}") + if self.hooks_proxy is None: + raise AssertionError("hooks_proxy must be set before post_acc_grad_hook") + hook = self.hooks_proxy[hook_id] # type: ignore[index] + proxy = self.proxy_call_hook( + hook, + input, + hook_type="post_acc_grad_hook", + ) + with disable_proxy_modes_tracing(): + res = [maybe_clone(input)] + self.bind_objects_to_proxies(res, [proxy]) + return res # type: ignore[return-value] + + # Note: [Compiled autograd and cudagraphs] + # Eager autograd backward implements scalars as 0-dim tensors, see DivBackward0::other_. + # When compiled autograd traces those nodes, it lifts the scalar tensors, resulting in a graph + # with some cpu 0-dim tensor inputs. To prevent the entire graph from skipping cudagraph, we move the + # scalar tensors to cuda. This works because ATen/prims ops will accept cuda 0-dim tensors too. + def move_graph_nodes_to_cuda(self, graph: torch.fx.Graph) -> list[int]: + to_move: dict[int, torch.fx.Node] = {} + has_cuda_inputs = False + nodes = list(graph.nodes) + if nodes[0].target != "inputs": + raise AssertionError( + f"Expected first node target to be 'inputs', got '{nodes[0].target}'" + ) + inputs = nodes[0] + inputs_users = list(inputs.users.keys()) + # input access nodes should immediately follow placeholder nodes + first_getitem_idx = len(_graph_placeholders) + if nodes[first_getitem_idx] != inputs_users[0]: + raise AssertionError("First getitem node does not match first inputs user") + last_getitem_idx = first_getitem_idx + len(inputs_users) - 1 + if nodes[last_getitem_idx] != inputs_users[-1]: + raise AssertionError("Last getitem node does not match last inputs user") + # getitem nodes on inputs + for i, node in enumerate(inputs_users): + if not has_cuda_inputs and node.meta["val"].device.type == "cuda": + has_cuda_inputs = True + continue + + is_cpu = node.meta["val"].device.type == "cpu" + is_scalar = len(node.meta["val"].size()) == 0 + if is_cpu and is_scalar: + node_users = list(node.users.keys()) + # We can only move the cpu scalar if it is not exposed to user code. + if all( + ( + isinstance(user.target, torch._ops.OpOverload) + and user.target.namespace in ("prims", "aten") + ) + or ( + isinstance(user.target, Op) + and not user.target.is_custom_function + ) + for user in node_users + ): + # all users are prims/aten, can move safely + to_move[i] = node + + # only move cpu scalars to cuda if there were cuda activations in this graph, + # this is to handle the case where cudagraphs is enabled on a cpu-only graph + if has_cuda_inputs: + for node in to_move.values(): + verbose_log.debug("Moving node %s from cpu to cuda", node) + node.meta["val"] = node.meta["val"].cuda() + + # return runtime indices we need to move to cuda + return list(to_move.keys()) + + return [] + + def is_sym_node(self, node: Any) -> bool: + return ( + isinstance(node, torch.fx.Node) + and node.op == "call_function" + and node.target + in [torch.ops.aten.sym_size.int, torch.ops.aten.sym_numel.default] + ) + + def dce(self) -> None: + # Most of these removed nodes would have been removed during Dynamo and AOTDispatch + # Remove some of these nodes earlier to improve compilation speed + + # Dynamo guards will error instead of creating aliasing guards unless we unpack them in the graph + unpack_nodes: OrderedSet[torch.fx.Node] = OrderedSet() + i: int | None = None + for i, node in enumerate(self.fx_tracer.graph.find_nodes(op="placeholder")): + unpack_nodes.update(node.users.keys()) + if i != len(_graph_placeholders) - 1: + raise AssertionError( + f"Expected {len(_graph_placeholders) - 1} placeholders, got {i}" + ) + + def is_impure(node: torch.fx.Node) -> bool: + if node in unpack_nodes or ( + node.op == "call_function" and node.target in _impure_targets + ): + return True + return node.is_impure() + + before = len(self.fx_tracer.graph.nodes) + self.fx_tracer.graph.eliminate_dead_code(is_impure) + after = len(self.fx_tracer.graph.nodes) + verbose_log.debug("DCE removed %d nodes", before - after) + + def remove_unused_sizes(self) -> set[int]: + used_sizes = [] + unused_sizes = [] + + # seek placeholder, should be at nodes[1] + it = iter(self.fx_tracer.graph.nodes) + next(it) + sizes_node = next(it) + if sizes_node.name != "sizes": + raise AssertionError( + f"Expected placeholder 'sizes', got '{sizes_node.name}'" + ) + + for getitem_node in sizes_node.users: + if getitem_node.target is not operator.getitem: + raise AssertionError( + f"Expected operator.getitem target, got {getitem_node.target}" + ) + if getitem_node.users: + used_sizes.append(getitem_node) + else: + # remove from the graph + unused_sizes.append(getitem_node) + + used_sizes_idx: set[int] = set() + for used in used_sizes: + if not isinstance(used.args, tuple): + raise AssertionError( + f"Expected used.args to be tuple, got {type(used.args)}" + ) + if used.args[0] != sizes_node: + raise AssertionError("Expected used.args[0] to be sizes_node") + if not isinstance(used.args[1], int): + raise AssertionError( + f"Expected used.args[1] to be int, got {type(used.args[1])}" + ) + next_size_idx = len(used_sizes_idx) + # used later reindex the runtime sizes arg + used_sizes_idx.add(used.args[1]) + # reindex the graph + used.args = (used.args[0], next_size_idx) + + for unused in unused_sizes: + self.fx_tracer.graph.erase_node(unused) + + return used_sizes_idx + + def create_graph_module(self, id: str) -> GraphModule: + return GraphModule(self.fx_tracer.root, self.fx_tracer.graph, id) + + def end_capture(self, outputs: Any) -> tuple[Callable[..., Any], Any]: + self.fx_tracer.create_proxy( + "call_function", + FakeCompiledAutogradEngine._exec_final_callbacks_stub, + (), + {}, + ) + self.stack.close() + self.fx_tracer.create_node( + "output", + "output", + (self.fx_tracer.create_arg(self.to_proxy(outputs)),), + {}, + ) + runtime_inputs_to_move: list[int] = [] + if snapshot_cudagraph_enabled(): + runtime_inputs_to_move = self.move_graph_nodes_to_cuda(self.fx_tracer.graph) + + # We traced using dummy tensors. Delete all the metadata of the dummy tensors. + # It's probably better to refactor this class to use a different tracer + # than the make_fx tracer, but that is a larger change. + for node in self.fx_tracer.graph.nodes: + for field in ["tensor_meta", "example_value", "val"]: + if field in node.meta: + del node.meta[field] + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "compiled_autograd_graph_pre_reordering", + "encoding": "string", + }, + payload_fn=lambda: GraphModule( + self.fx_tracer.root, + self.fx_tracer.graph, + f"CompiledAutograd{self.id}PreReordering", + ).print_readable(print_output=False), + ) + self.delay_unpack_hook_nodes() + self.reorder_tensor_pre_hook_nodes() + self.reorder_pre_hook_nodes_to_schedule_asap() + self.reorder_accumulate_grad_nodes() + self.reorder_pre_hook_nodes_to_mimic_eager() + self.reorder_post_acc_grad_hook_nodes() + self.reorder_post_hook_nodes() + # TODO(yf225): work around: remove dead codes like `sym_size` and `sym_numel` which are not used downstream. e.g. + # ``` + # sym_numel_default = torch.ops.aten.sym_numel.default(sum_109); sum_109 = None + # eq_115 = 16 == sym_numel_default; sym_numel_default = eq_115 = None + # sym_size_int_39 = torch.ops.aten.sym_size.int(getitem_112, 1); getitem_112 = None + # eq_116 = 16 == sym_size_int_39; eq_116 = None + # eq_117 = 16 == sym_size_int_39; sym_size_int_39 = eq_117 = None + # ``` + # Proper fix is Richard's Python compiled autograd effort which will avoid calling make_fx and + # should prevent these ops from going into the CA graph. + self.dce() + if self.nan_checker: + self.nan_checker.prep_with_graph(self.fx_tracer.graph) + + # keep only sizes that are actually used in the graph + used_sizes_idx = self.remove_unused_sizes() + + graph = self.create_graph_module(f"CompiledAutograd{self.id}") + set_locals_to_steal(graph, ["inputs"]) + lazy_graph_code = lazy_format_graph_code( + "Compiled autograd graph", + graph, + include_device=True, + include_stride=True, + colored=True, + ) + compiled_autograd_log.info("%s", lazy_graph_code) + verbose_log.debug("%s", lazy_graph_code) + trace_structured( + "compiled_autograd_graph", + payload_fn=lambda: graph.print_readable(print_output=False), + ) + + def runtime_wrapper( + compiled_fn: Callable[..., Any], + inputs: Any, + sizes: Any, + scalars: Any, + hooks: Any, + packed_inputs: Any, + ) -> tuple[Any, Any]: + global in_compiled_autograd_region + try: + in_compiled_autograd_region = True + + if self.nan_checker: + self.nan_checker.prep_with_inputs(inputs) + + filtered_sizes = [] + for idx, integer in enumerate(sizes): + if idx in used_sizes_idx: + # can't create negative size + if integer > 0: + filtered_sizes.append(torch.empty(0, integer)) + torch._dynamo.maybe_mark_dynamic(filtered_sizes[-1], 1) + else: + filtered_sizes.append(integer) + + for i in runtime_inputs_to_move: + inputs[i] = inputs[i].pin_memory().cuda(non_blocking=True) + + with _disable(), make_compile_context(self.id): + out = compiled_fn( + inputs, filtered_sizes, scalars, hooks, packed_inputs + ) + if self.nan_checker: + self.nan_checker.check(out) + return out + finally: + in_compiled_autograd_region = False + + get_chromium_event_logger().log_event_end( + "compiled_autograd", + time.time_ns(), + {"graph_id": self.id}, + self.start_time_ns, + log_pt2_compile_event=True, + ) + self.compile_context.__exit__(None, None, None) + return runtime_wrapper, self.compiler_fn(graph) + + @staticmethod + def get_all_nodes(args: Sequence[Any]) -> list[torch.fx.Node]: + # filter out non-Node args, like None + nodes = [n for n in args if type(n) is torch.fx.Node] + return nodes + + @staticmethod + def is_placeholder(node: torch.fx.Node) -> bool: + if node.op == "placeholder" or ( + node.op == "call_function" + and node.target is operator.getitem + and node.args[0].op == "placeholder" # type: ignore[union-attr, arg-type] + ): + return True + return False + + def reorder_accumulate_grad_nodes(self) -> None: + """ + Usage of AOTAutograd causes all the accumulate_grad_ nodes to get pushed to the end of + the graph. This differs from eager mode, which schedules them as soon as possible. This + pass attempts to reorder the graph to mimic eager behavior. + """ + for node in self.fx_tracer.graph.find_nodes( + op="call_function", target=call_accumulate_grad + ): + param_node, variable_grad_node, grad_node = ( + node.args[0], + node.args[1], + node.args[2], + ) + getitem_node = None + if ( + isinstance(grad_node, torch.fx.Node) + and grad_node.target is operator.getitem + ): + getitem_node = grad_node + grad_node = getitem_node.args[0] + + arg = max( + self.get_all_nodes([param_node, variable_grad_node, grad_node]) + ) # last arg + if arg is not node.prev and not self.is_placeholder(arg): + arg.append(node) + if getitem_node is not None: + arg.append(getitem_node) + + def delay_unpack_hook_nodes(self) -> None: + """ + We can delay unpack hooks until they are needed, even later than in the eager autograd engine. + """ + for node in self.fx_tracer.graph.find_nodes( + op="call_function", target=call_hook + ): + if node.kwargs.get("hook_type", None) != "unpack_hook": + continue + + first_user = min(node.users) + first_user.prepend(node) + + def reorder_tensor_pre_hook_nodes(self) -> None: + """ + Usage of AOTAutograd causes all the tensor_pre_hook nodes to get pushed + to the end of the graph. This differs from eager mode, which schedules + them as soon as possible. This pass attempts to reorder the graph to + mimic eager behavior. + """ + for node in self.fx_tracer.graph.find_nodes( + op="call_function", target=call_hook + ): + if node.kwargs.get("hook_type", None) != "tensor_pre_hook": + continue + + getitem_node = node.args[0] + input_node = node.args[1] # tensor_pre_hook handle only one grad tensor + + if input_node is not node.prev and not self.is_placeholder(input_node): + input_node.append(getitem_node) + getitem_node.append(node) + + def reorder_pre_hook_nodes_to_schedule_asap(self) -> None: + """ + In this function, we schedule the pre hooks as soon as possible. This + does not match eager behavior (schedule pre hook right before its + registered node), but it can make acc grad be scheduled properly when + the pre hooks are registered to them. After reordering acc grad node, we + will reorder the pre hooks again to mimic eager behavior. + """ + for node in self.fx_tracer.graph.find_nodes( + op="call_function", target=call_hook + ): + if node.kwargs.get("hook_type", None) != "pre_hook": + continue + + getitem_node = node.args[0] + # pre_hook handle a tuple of grad tensors + input_nodes = self.get_all_nodes(node.args[1]) + + to_remove = [] + to_append = [] + hook_block = [node] # contain the hook and hook args getitem + for n in input_nodes: + if n.op == "call_function" and n.target is operator.getitem: + to_append.append(n.args[0]) + to_remove.append(n) + hook_block.append(n) + for a, b in zip(to_remove, to_append): + input_nodes.remove(a) + input_nodes.append(b) # type: ignore[arg-type] + + arg = max(input_nodes) # last input + if arg is not node.prev and not self.is_placeholder(arg): + arg.append(getitem_node) + for n in hook_block: + getitem_node.append(n) + + def reorder_pre_hook_nodes_to_mimic_eager(self) -> None: + """ + Usage of AOTAutograd causes all the pre_hook nodes to get pushed to the + end of the graph. This differs from eager mode, which schedules them + right before their registered node execution. This pass attempts to + reorder the graph to mimic eager behavior. + """ + pre_hooks = [] + for node in self.fx_tracer.graph.find_nodes( + op="call_function", target=call_hook + ): + if node.kwargs.get("hook_type", None) != "pre_hook": + continue + pre_hooks.append(node) + + for node in reversed(pre_hooks): + hook_getitem_node = node.args[0] + + users = list(node.users.keys()) + if len(users) == 0: + continue + + # users are all getitem ops and they are used by same registered node + if not all( + user.op == "call_function" and user.target is operator.getitem + for user in users + ): + raise AssertionError( + "Expected all users of pre_hook to be operator.getitem call_function nodes" + ) + registered_node = next(iter(users[0].users.keys())) + + if registered_node is not node.next: + registered_node.prepend(hook_getitem_node) + registered_node.prepend(node) + for getitem in users: + registered_node.prepend(getitem) + + def reorder_post_acc_grad_hook_nodes(self) -> None: + """ + Usage of AOTAutograd causes all the post_acc_grad_hook nodes to get + pushed to the end of the graph. This differs from eager mode, which + schedules them as soon as possible. This pass attempts to reorder the + graph to mimic eager behavior. + """ + post_acc_grad_hooks = [] + for node in self.fx_tracer.graph.find_nodes( + op="call_function", target=call_hook + ): + if node.kwargs.get("hook_type", None) != "post_acc_grad_hook": + continue + post_acc_grad_hooks.append(node) + + # nodes in post_acc_grad_hooks are in topo order. For hooks registered + # to same node, we should keep their relative order + for node in reversed(post_acc_grad_hooks): + getitem_node = node.args[0] + param_node = node.args[1] # post_acc_grad_hook handle one param + + # find the corresponding acc_grad node + acc_grad_node = None + for n in list(param_node.users.keys()): + if n.op == "call_function" and n.target is call_accumulate_grad: + acc_grad_node = n + break + + if acc_grad_node is None: + raise AssertionError( + "post_acc_grad_hook must have corresponding acc grad node" + ) + + # append post_acc_grad_hook after acc_grad node + acc_grad_node.append(getitem_node) + getitem_node.append(node) + + def reorder_post_hook_nodes(self) -> None: + """ + Usage of AOTAutograd causes all the post_hook nodes to get pushed to the + end of the graph. This differs from eager mode, which schedules them as + soon as possible. This pass attempts to reorder the graph to mimic eager + behavior. + """ + post_hooks = [] + for node in self.fx_tracer.graph.find_nodes( + op="call_function", target=call_hook + ): + if node.kwargs.get("hook_type", None) != "post_hook": + continue + post_hooks.append(node) + + for node in reversed(post_hooks): + getitem_node = node.args[0] + output_nodes = node.args[1] + input_nodes = node.args[2] + + if len(output_nodes) > 0: + continue + + # pyrefly: ignore [implicit-any] + input_nodes_and_users = [] + input_nodes_and_users.extend(list(input_nodes)) + for input_node in input_nodes: + input_nodes_and_users.extend( + user + for user in list(input_node.users.keys()) + if not ( + user.op == "call_function" + and user.target is call_hook + and node.kwargs.get("hook_type", None) == "post_hook" + ) + ) + + arg = max(input_nodes_and_users) # last input users + if arg.op == "call_function" and arg.target is call_accumulate_grad: + param_node = arg.args[0] + post_acc_grad_hook_node = None + for n in list(param_node.users.keys()): + if ( + n.op == "call_function" + and n.target is call_hook + and n.kwargs.get("hook_type", None) == "post_acc_grad_hook" + ): + post_acc_grad_hook_node = n + + if post_acc_grad_hook_node is not None: + post_acc_grad_hook_node.append(getitem_node) + getitem_node.append(node) + continue + + if arg is not node.prev and not self.is_placeholder(arg): + arg.append(getitem_node) + getitem_node.append(node) + + def to_proxy(self, t: Any) -> Any: + if t is None: + return None + if isinstance(t, list): + return [self.to_proxy(x) for x in t] + if isinstance(t, tuple): + return tuple(self.to_proxy(x) for x in t) + if isinstance(t, (torch.SymInt, torch.SymFloat)): + return self.symnode_proxy_lookup[t.node] + if not isinstance(t, torch.Tensor): + # constant types like device, dtype, str + return t + proxy_tensor = fetch_object_proxy(self.fx_tracer, t) + if not isinstance( + proxy_tensor, torch.fx.experimental.proxy_tensor._ProxyTensor + ): + raise AssertionError(f"Expected _ProxyTensor, got {type(proxy_tensor)}") + return proxy_tensor.proxy + + def bind_objects_to_proxies( + self, + objects: Sequence[Any], + proxies: Any, + origins: list[tuple[int, str]] | None = None, + ) -> Sequence[Any]: + if isinstance(proxies, torch.fx.Proxy): + if origins: + if len(origins) != len(objects): + raise AssertionError( + f"origins length ({len(origins)}) != objects length ({len(objects)})" + ) + bound_proxies = [] + for i in range(len(objects)): + nodecall_index, node_name = origins[i] + self.set_node_origin(node_name, nodecall_index, None) + bound_proxies.append(proxies[i]) # type: ignore[index] + proxies = bound_proxies + else: + proxies = [proxies[i] for i in range(len(objects))] # type: ignore[index] + + if len(objects) != len(proxies): + raise AssertionError( + f"objects length ({len(objects)}) != proxies length ({len(proxies)})" + ) + track_tensor_tree(objects, proxies, constant=None, tracer=self.fx_tracer) + return proxies + + def bind_backward_state(self, index: int) -> BackwardState: + if self.hooks_proxy is None: + raise AssertionError("hooks_proxy must be set before bind_backward_state") + proxy = self.hooks_proxy[index] # type: ignore[index] + bw_state = BackwardState() + track_tensor_tree(bw_state, proxy, constant=None, tracer=self.fx_tracer) + return bw_state + + def set_node_origin( + self, + node_name: str, + nodecall_index: int, + pyobj: torch.autograd.Function | None, + ) -> None: + maybe_aot_id = "" + if pyobj is not None: + forward_cls = pyobj._forward_cls # type: ignore[attr-defined] + if hasattr(forward_cls, "_aot_id"): + # backward was created by AOT Dispatcher + if forward_cls._lazy_backward_info is None: + raise RuntimeError( + """This compiled backward function was saved by AOTAutogradCache, which does not support + compiled autograd. Please turn off AOTAutogradCache using `TORCHINDUCTOR_AUTOGRAD_CACHE=0`.""" + ) + maybe_aot_id = forward_cls._aot_id + new_code = f"{node_name}{maybe_aot_id} (NodeCall {nodecall_index})" + raw_stack_trace = CapturedTraceback.extract().format()[-1] + new_stack_trace = raw_stack_trace.replace( + "raw_stack_trace = CapturedTraceback.extract().format()[-1]", new_code + ) + set_stack_trace(new_stack_trace) + + +# state of the autograd engine dispatch, kept in sync by enable/disable context managers +compiled_autograd_enabled = False + +# global flag to check if compiled autograd is enabled but Dynamo stance is "force_eager" +compiled_autograd_enabled_force_eager = False + +# global flag to check if we are processing graphs produced from a compiled autograd graph +in_compiled_autograd_region = False + +active_disable_ctx = False + +depth = 0 + + +@contextlib.contextmanager +def _enable( + compiler_fn: Callable[..., Any], + dynamic: bool = True, + ignore_active_disable_ctx: bool = True, +) -> Generator[None, None, None]: + # The entrypoint to enable CA. + # It is recommended to enable via `torch._dynamo.config.compiled_autograd = True` rather + # than using this context manager directly. If you are torch.compiling the corresponding + # forward pass, make sure they are wrapped under this context as well. + # + # Example: + # def train(model, inputs, target): + # compiled_model = torch.compile(model) + # pred = compiled_model(data) + # loss = compute_loss(pred, target) + # loss.backward() + # + # with _enable(compiler_fn): + # train(model, inputs, target) + # + # Inputs: + # - compiler_fn: The wrapper that will consume the compiled autograd graph, e.g. `torch.compile` + # - dynamic: Whether compiled autograd will treat tensors in the autograd graph (params, activations) as dynamic. + # This doesn't affect the dynamic configuration of the compilation wrapper. + + if not ignore_active_disable_ctx and active_disable_ctx: + yield + else: + if dynamic: + if type(dynamic) is not bool: + raise AssertionError( + f"Expected dynamic to be bool, got {type(dynamic)}" + ) + + from torch._dynamo import eval_frame + + if eval_frame._stance.stance == "force_eager": + # If user explicitly sets Dynamo stance to "force_eager", we want Compiled Autograd + # to fall back to eager as well. + global compiled_autograd_enabled_force_eager + compiled_autograd_enabled_force_eager = True + try: + yield + finally: + compiled_autograd_enabled_force_eager = False + else: + # we need to import this, because user might not have imported it if they directly use this context manager + # we need to lazily import it, because of circular dependencies + if torch.cuda.is_available(): + from torch._inductor import cudagraph_trees # noqa: F401 + + ( + prior_compiler, + prior_dynamic, + ) = torch._C._dynamo.compiled_autograd.set_autograd_compiler( + functools.partial(AutogradCompilerInstance, compiler_fn), dynamic + ) + if snapshot_verbose_logging_enabled(): + torch._C._dynamo.compiled_autograd.set_verbose_logger(verbose_log) # type:ignore[arg-type] + global compiled_autograd_enabled + compiled_autograd_enabled = True + global depth + prior_depth = depth + depth += 1 + try: + with torch.autograd.set_multithreading_enabled(False): + yield + finally: + if not prior_compiler: + compiled_autograd_enabled = False + torch._C._dynamo.compiled_autograd.set_autograd_compiler( + prior_compiler, prior_dynamic + ) + depth -= 1 + if depth != prior_depth: + raise AssertionError( + "Nested Compiled Autograd Contexts must return before their parent context" + ) + + +@contextlib.contextmanager +def _disable() -> Generator[None, None, None]: + ( + prior_compiler, + prior_dynamic, + ) = torch._C._dynamo.compiled_autograd.set_autograd_compiler(None, False) + global compiled_autograd_enabled + compiled_autograd_enabled = False + global active_disable_ctx + if not active_disable_ctx: + active_disable_ctx = True + try: + yield + finally: + if prior_compiler: + compiled_autograd_enabled = True + active_disable_ctx = False + torch._C._dynamo.compiled_autograd.set_autograd_compiler( + prior_compiler, prior_dynamic + ) + + +# return to starting state of a new process +def reset() -> None: + global compiled_autograd_enabled + compiled_autograd_enabled = False + if in_compiled_autograd_region: + raise AssertionError("Cannot reset while in_compiled_autograd_region is True") + torch._C._dynamo.compiled_autograd.set_autograd_compiler(None, False) + torch._C._dynamo.compiled_autograd.set_verbose_logger(None) + torch._C._dynamo.compiled_autograd.clear_cache() + global COMPILE_COUNTER + COMPILE_COUNTER = itertools.count() + + +# Reimplementation of part of CopySlices::apply in Python. +# The shared code is really similar so we're not going to try to deduplicate. +def copy_slices_prologue( + inputs: Sequence[torch.Tensor], + base_sizes: Sequence[IntLikeType], + base_strides: Sequence[IntLikeType], + base_storage_offset: IntLikeType, + view_sizes: Sequence[IntLikeType], + view_strides: Sequence[IntLikeType], + view_storage_offset: IntLikeType, +) -> list[torch.Tensor]: + grad = inputs[0] + result = grad.new_empty_strided(base_sizes, base_strides) + if grad is None: + raise AssertionError("grad must not be None in copy_slices_prologue") + result.copy_(grad) + offset = view_storage_offset - base_storage_offset + grad_slice = result.as_strided(view_sizes, view_strides, offset) + return [result, grad_slice, grad_slice.clone(memory_format=torch.contiguous_format)] + + +# Reimplementation of part of CopySlices::apply in Python. +# The shared code is really similar so we're not going to try to deduplicate. +def copy_slices_epilogue( + needs_input_grad: Sequence[bool], + result: torch.Tensor, + res: Sequence[torch.Tensor | None], + grad_slice: torch.Tensor, +) -> list[torch.Tensor | None]: + grad_inputs: list[torch.Tensor | None] = [None] * len(needs_input_grad) + for i in range(len(needs_input_grad)): + if needs_input_grad[i]: + if res[i] is None: + continue + if i == 0: + to_copy = res[i] + if to_copy is None: + raise AssertionError( + "res[0] must not be None for needs_input_grad[0]" + ) + grad_slice.copy_(to_copy) + grad_inputs[i] = result + else: + grad_inputs[i] = res[i] + return grad_inputs diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/comprehension_graph_break.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/comprehension_graph_break.py new file mode 100644 index 0000000000000000000000000000000000000000..df34beb74120756cbc3d9c267ce5a101660bdaab --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/comprehension_graph_break.py @@ -0,0 +1,672 @@ +from __future__ import annotations + +import copy +import dataclasses +import dis +import functools +import logging +import sys +from collections import Counter +from typing import Any, TYPE_CHECKING + + +if TYPE_CHECKING: + import types + + from .symbolic_convert import InstructionTranslatorBase + +from .bytecode_transformation import ( + create_copy, + create_dup_top, + create_instruction, + create_swap, + Instruction, + unique_id, +) +from .codegen import PyCodegen +from .exc import unimplemented +from .graph_break_hints import DYNAMO_BUG +from .output_graph import GraphCompileReason, StackLocalsMetadata +from .variables.misc import NullVariable, UnknownVariable + + +log = logging.getLogger(__name__) + + +@functools.cache +def _get_comprehension_bytecode_prefix() -> list[str]: + """Get the bytecode instructions that precede BUILD_LIST in a list comprehension.""" + + if sys.version_info < (3, 12): + raise AssertionError( + f"comprehension bytecode prefix requires Python 3.12+, got {sys.version_info}" + ) + + def fn() -> list[int]: + return [i for i in range(1)] # noqa: C416 + + insts = [inst.opname for inst in dis.get_instructions(fn)] + + start_idx = len(insts) - 1 - insts[::-1].index("LOAD_FAST_AND_CLEAR") + end_idx = insts.index("BUILD_LIST") + + return insts[start_idx:end_idx] + + +@dataclasses.dataclass +class ComprehensionAnalysis: + """Metadata about a comprehension's bytecode structure. + + Attributes: + end_ip: Instruction pointer after all comprehension bytecode + result_var: Name of result variable, or None if result stays on stack + result_on_stack: True if result stays on stack (discarded, returned, or in expression) + iterator_vars: Variables from LOAD_FAST_AND_CLEAR (need restoration) + walrus_vars: Variables assigned via walrus operator (:=) inside comprehension + captured_vars: Variables read from outer scope via LOAD_FAST inside comprehension + """ + + end_ip: int + result_var: str | None + result_on_stack: bool + iterator_vars: list[str] + walrus_vars: list[str] + captured_vars: list[str] + + +def _is_comprehension_start(tx: InstructionTranslatorBase) -> bool: + """Detect if we're at the start of a list/dict comprehension in 3.12+. + + In Python 3.12+, comprehensions are inlined with a bytecode pattern that + precedes BUILD_LIST/BUILD_MAP. + """ + if sys.version_info < (3, 12): + raise AssertionError( + f"comprehension start detection requires Python 3.12+, got {sys.version_info}" + ) + + if tx.instruction_pointer is None: + raise AssertionError("instruction_pointer must not be None") + ip = tx.instruction_pointer - 1 + + pattern = _get_comprehension_bytecode_prefix() + prefix = [inst.opname for inst in tx.instructions[ip - len(pattern) : ip]] + + return prefix == pattern + + +def _find_comprehension_end_for_ip(tx: InstructionTranslatorBase) -> int: + """Find the instruction pointer of the outermost END_FOR for current comprehension.""" + if sys.version_info < (3, 12): + raise AssertionError( + f"comprehension END_FOR search requires Python 3.12+, got {sys.version_info}" + ) + if tx.instruction_pointer is None: + raise AssertionError("instruction_pointer must not be None") + + nesting_depth = 0 + for search_ip in range(tx.instruction_pointer, len(tx.instructions)): + inst = tx.instructions[search_ip] + if inst.opname == "FOR_ITER": + nesting_depth += 1 + elif inst.opname == "END_FOR": + nesting_depth -= 1 + if nesting_depth == 0: + return search_ip + return -1 + + +def _analyze_comprehension(tx: InstructionTranslatorBase) -> ComprehensionAnalysis: + """Analyze comprehension bytecode to determine result handling pattern.""" + if sys.version_info < (3, 12): + raise AssertionError( + f"comprehension analysis requires Python 3.12+, got {sys.version_info}" + ) + if tx.instruction_pointer is None: + raise AssertionError("instruction_pointer must not be None") + + start_ip = tx.instruction_pointer - 1 # BUILD_LIST/BUILD_MAP + + iterator_vars: list[str] = [] + walrus_vars: list[str] = [] + captured_vars: list[str] = [] + defined_inside: set[str] = set() + + # Collect iterator variables from LOAD_FAST_AND_CLEAR before BUILD_LIST/BUILD_MAP + iter_scan_ip = start_ip - 1 + while iter_scan_ip >= 0: + inst = tx.instructions[iter_scan_ip] + if inst.opname == "LOAD_FAST_AND_CLEAR": + iterator_vars.insert(0, inst.argval) + iter_scan_ip -= 1 + elif inst.opname in ("SWAP", "GET_ITER"): + iter_scan_ip -= 1 + else: + break + defined_inside.update(iterator_vars) + + end_for_ip = _find_comprehension_end_for_ip(tx) + if end_for_ip == -1: + unimplemented( + gb_type="Comprehension analysis failed: No END_FOR", + context="", + explanation="Could not find END_FOR instruction in comprehension bytecode.", + hints=[], + ) + + # Find first FOR_ITER to know where loop body starts + for_iter_ip = next( + i + for i in range(start_ip, end_for_ip) + if tx.instructions[i].opname == "FOR_ITER" + ) + + # Single pass through loop body to detect walrus vars and captured vars + for body_ip in range(for_iter_ip + 1, end_for_ip): + inst = tx.instructions[body_ip] + + # Detect walrus pattern: COPY 1 followed by STORE_FAST + if inst.opname == "COPY" and inst.arg == 1 and body_ip + 1 < end_for_ip: + next_inst = tx.instructions[body_ip + 1] + if next_inst.opname == "STORE_FAST": + var_name = next_inst.argval + if var_name not in iterator_vars and var_name not in walrus_vars: + walrus_vars.append(var_name) + defined_inside.add(var_name) + + # Track variables defined inside the loop + if inst.opname == "STORE_FAST": + defined_inside.add(inst.argval) + + # Detect LOAD_FAST referencing outer variables + elif inst.opname.startswith("LOAD_FAST"): + var_names = ( + inst.argval if isinstance(inst.argval, tuple) else (inst.argval,) + ) + for var_name in var_names: + if var_name not in defined_inside and var_name not in captured_vars: + captured_vars.append(var_name) + + # Extract pre_store_ops: all opcodes from END_FOR+1 until first STORE_FAST + pre_store_ops: list[str] = [] + scan_ip = end_for_ip + 1 + # In 3.13 END_FOR is followed by POP_TOP to pop the iter. In 3.12, END_FOR is responsible for doing the pop, and in + # 3.14+ POP_ITER is used instead. We skip over the mandatory POP_TOP in 3.13 to avoid confusing the analysis below + # (which looks for an additional POP_TOP if the result is discarded). + if sys.version_info[:2] == (3, 13): + scan_ip += 1 + while ( + scan_ip < len(tx.instructions) + and tx.instructions[scan_ip].opname != "STORE_FAST" + ): + pre_store_ops.append(tx.instructions[scan_ip].opname) + scan_ip += 1 + + store_fast_ip = scan_ip + + # Skip all STORE_FASTs (iteration-variable restores plus an optional result + # assignment) to find the end of the comprehension epilogue. + while ( + scan_ip < len(tx.instructions) + and tx.instructions[scan_ip].opname == "STORE_FAST" + ): + scan_ip += 1 + + # The comprehension epilogue always restores the iteration variables that + # were saved by LOAD_FAST_AND_CLEAR (one STORE_FAST each). The disposition + # of the result is determined relative to those restores: + # - a POP_TOP right after the loop teardown discards the result + # (bare statement) + # - one extra STORE_FAST beyond the iteration vars is a result + # assignment (the extra store may reuse an iteration var's name) + # - no extra store leaves the result on the stack (returned/consumed) + # We use this to classify the handling of the result as discarded, stored, + # or returned/consumed + n_iter = len(iterator_vars) + store_targets = Counter( + tx.instructions[i].argval for i in range(store_fast_ip, scan_ip) + ) + + result_var: str | None = None + if pre_store_ops[-1:] == ["POP_TOP"]: # discarded + result_var = None + result_on_stack = False + elif store_targets.total() > n_iter: # stored + store_targets.subtract(iterator_vars) + if store_targets.total() != 1: + unimplemented( + gb_type="Comprehension analysis failed: ambiguous result store", + context=f"store_targets={store_targets}, iterator_vars={iterator_vars}", + explanation="Expected exactly one comprehension result assignment.", + hints=DYNAMO_BUG, + ) + result_var = next(iter(store_targets)) + result_on_stack = False + elif store_targets.total() == n_iter: # returned/consumed + result_var = None + result_on_stack = True + else: + unimplemented( + gb_type="Comprehension analysis failed: No matches", + context=f"pre_store_ops={pre_store_ops}, store_targets={store_targets}, " + f"iterator_vars={iterator_vars}", + explanation="Comprehension does not match any known bytecode pattern.", + hints=DYNAMO_BUG, + ) + + return ComprehensionAnalysis( + end_ip=scan_ip, + result_var=result_var, + # pyrefly: ignore [unbound-name] + result_on_stack=result_on_stack, + iterator_vars=iterator_vars, + walrus_vars=walrus_vars, + captured_vars=captured_vars, + ) + + +def _handle_comprehension_graph_break( + tx: InstructionTranslatorBase, inst: Instruction +) -> None: + """Handle list/dict comprehension graph break. + + Builds a synthetic function wrapping the comprehension bytecode, + calls it via codegen_call_resume, then chains into the resume + function for the post-comprehension code. + """ + if sys.version_info < (3, 12): + raise AssertionError( + f"comprehension graph break requires Python 3.12+, got {sys.version_info}" + ) + if tx.instruction_pointer is None: + raise AssertionError("instruction_pointer must not be None") + + start_ip = tx.instruction_pointer - 1 # BUILD_LIST/BUILD_MAP + analysis = _analyze_comprehension(tx) + stack_pops = 1 + len(analysis.iterator_vars) + reason = GraphCompileReason("comprehension_graph_break", [tx.frame_summary()]) + log.debug("comprehension triggered compile") + + # --- Step 1: Compile the graph up to the comprehension --- + + all_stack_locals_metadata = tx.output.compile_subgraph( + tx, + reason=reason, + stack_pops=stack_pops, + ) + # Record which stack_pops items are NULL before popn loses the info. + # NULLs on the CPython stack can't be passed as function arguments. + stack_pops_null_mask = [ + isinstance(tx.stack[len(tx.stack) - stack_pops + i], NullVariable) + for i in range(stack_pops) + ] + + tx.popn(stack_pops) + meta = all_stack_locals_metadata[0] + cg = PyCodegen(tx.output.root_tx) + + # Runtime stack after compile_subgraph: + # cells, [frame_values], *(non-popped items), *(stack_pops items w/ NULLs) + # frame_values[0] = [frame N locals] (no stack items yet) + + nonnull_count = sum(1 for m in stack_pops_null_mask if not m) + + # live_stack_depth: stack items above cells/frame_values excluding NULLs + # that compile_subgraph didn't codegen (tracked in stack_null_idxes). + live_stack_depth = len(tx.stack) - len(meta.stack_null_idxes) + + # --- Step 2: Pop stack_pops items and append non-nulls to frame_values[0] --- + # SWAP each item to TOS then LIST_APPEND or pop_null; fv_list stays at + # TOS throughout. Items append in TOS-first (reversed) order; + # _build_comprehension_fn compensates by loading in reverse. + cg.extend_output( + [ + # frame_values[0] to TOS + *create_copy(live_stack_depth + stack_pops + 1), + cg.create_load_const(0), + cg.create_binary_subscr(), + ] + ) + for i in reversed(range(stack_pops)): + cg.extend_output(create_swap(2)) + if stack_pops_null_mask[i]: + cg.extend_output(cg.pop_null()) + else: + cg.extend_output(cg.create_list_append()) + cg.extend_output([create_instruction("POP_TOP")]) + + # Stack: cells, [frame_values], *(non-popped items) + + # --- Step 3: Build comprehension function --- + new_code, fn_name = _build_comprehension_fn( + tx, + analysis, + start_ip, + stack_pops, + stack_pops_null_mask, + nonnull_count, + meta, + ) + + # --- Step 4: Extract [cells[0]] and [frame_values[0]] for codegen_call_resume --- + cg.extend_output( + [ + *create_copy(live_stack_depth + 2), + cg.create_load_const(0), + cg.create_binary_subscr(), + create_instruction("BUILD_LIST", arg=1), + *create_copy(live_stack_depth + 2), + cg.create_load_const(0), + cg.create_binary_subscr(), + create_instruction("BUILD_LIST", arg=1), + ] + ) + + # Stack: ..., *(non-popped), [cells[0]], [frame_values[0]] + + # --- Step 5: Call comprehension function via codegen_call_resume --- + tx.codegen_call_resume([new_code], [fn_name], cg) + + # Stack: ..., *(non-popped), comp_result + + # --- Step 6: Remove appended stack_pops items from frame_values[0] --- + if nonnull_count > 0: + frame_values_pos = live_stack_depth + 1 + 1 # +1 result, +1 frame_values + cg.extend_output( + [ + *create_copy(frame_values_pos), + cg.create_load_const(0), + cg.create_binary_subscr(), + # frame_values[0] on TOS + create_dup_top(), + # frame_values[0], frame_values[0] + cg.create_load_const(-nonnull_count), + cg.create_load_const(None), + create_instruction("BUILD_SLICE", arg=2), + create_instruction("DELETE_SUBSCR"), + # del frame_values[0][-nonnull_count:] + create_instruction("POP_TOP"), + ] + ) + + # --- Step 7: Pass comprehension outputs to frame_values[0] --- + # Walrus vars first, then result_var. + vars_to_pass = analysis.walrus_vars + ( + [analysis.result_var] if analysis.result_var else [] + ) + + existing_vars: dict[str, int] = {} + for var_name in vars_to_pass: + tx.symbolic_locals[var_name] = UnknownVariable() + if var_name in meta.locals_names: + existing_vars[var_name] = meta.locals_names[var_name] + else: + # The var was cleared to NULL at the break (e.g. a comprehension + # iteration variable reused as the result target). We are binding + # it to a real value, so drop the NULL restoration; otherwise the + # resume function would reset it to NULL and clobber the result. + if var_name in meta.locals_null_keys: + meta.locals_null_keys.remove(var_name) + meta.locals_names[var_name] = len(meta.locals_names) + + fv_depth = live_stack_depth + 2 # comp_result + frame_values + + # --- Walrus vars: extract from comp_result tuple --- + if analysis.walrus_vars: + # comp_result is (result, *walrus_vars). + cg.extend_output( + [ + *create_copy(fv_depth), + cg.create_load_const(0), + cg.create_binary_subscr(), + ] + ) + # Stack: ..., comp_tuple, fv0 + for j, walrus_var in enumerate(analysis.walrus_vars): + cg.extend_output( + [ + *create_copy(2), + cg.create_load_const(j + 1), + cg.create_binary_subscr(), + ] + ) + # Stack: ..., comp_tuple, fv0, walrus_value + if walrus_var in existing_vars: + # fv0[idx] = walrus_value + cg.extend_output( + [ + *create_copy(2), # copy fv0 + cg.create_load_const(existing_vars[walrus_var]), + create_instruction("STORE_SUBSCR"), + ] + ) + else: + cg.extend_output(cg.create_list_append()) + # Stack: ..., comp_tuple, fv0 + cg.extend_output( + [ + create_instruction("POP_TOP"), # pop fv0 + # Extract the result from the tuple. + cg.create_load_const(0), + cg.create_binary_subscr(), + ] + ) + # Stack: ..., result + + # --- Result: keep on stack, overwrite/append to fv[0], or discard --- + if analysis.result_on_stack: + tx.push(UnknownVariable()) + elif analysis.result_var: + cg.extend_output( + [ + *create_copy(fv_depth), + cg.create_load_const(0), + cg.create_binary_subscr(), + # Stack: ..., result, fv0 + ] + ) + if analysis.result_var in existing_vars: + cg.extend_output( + [ + cg.create_load_const(existing_vars[analysis.result_var]), + create_instruction("STORE_SUBSCR"), + # fv0[idx] = result + ] + ) + else: + cg.extend_output( + [ + *create_swap(2), + *cg.create_list_append(), + create_instruction("POP_TOP"), + ] + ) + else: + cg.extend_output([create_instruction("POP_TOP")]) + + # Stack: cells, [frame_values], *(non-popped stack) + tx.output.add_output_instructions(cg.get_instructions()) + + # --- Step 8: Create resume function chain --- + resume_inst = tx.instructions[analysis.end_ip] + tx.output.add_output_instructions( + tx.create_call_resume_at(resume_inst, all_stack_locals_metadata) + ) + + tx.instruction_pointer = None + + +def _build_comprehension_fn( + tx: InstructionTranslatorBase, + analysis: ComprehensionAnalysis, + start_ip: int, + stack_pops: int, + stack_pops_null_mask: list[bool], + nonnull_count: int, + meta: StackLocalsMetadata, +) -> tuple[types.CodeType, str]: + """Build a synthetic function wrapping comprehension bytecode. + + Uses the same calling convention as resume functions created by + create_resume / ContinueExecutionCache.generate: the first two args + are __nested_resume_fns and __nested_frame_values (ignored here), + followed by stack items and live locals. + + Returns (code, name) where name is the global name for the function. + """ + from .bytecode_transformation import transform_code_object + from .eval_frame import skip_code + from .resume_execution import CO_VARARGS, CO_VARKEYWORDS + + # Args follow frame_values layout: locals first, then stack_pops items + # (appended to end of frame_values[0] by the caller). + # codegen_call_resume unpacks frame_values[0] as positional args. + argnames = tuple(k for k in meta.locals_names if k not in tx.cell_and_freevars()) + args = ( + ["__nested_resume_fns", "__nested_frame_values"] + + list(argnames) + + [f"___stack{i}" for i in range(nonnull_count)] + ) + + freevars = tuple( + sorted(list(tx.f_code.co_cellvars or []) + list(tx.f_code.co_freevars or [])) + ) + + lineno = tx.lineno if tx.lineno is not None else tx.f_code.co_firstlineno + fn_name = unique_id(f"__comprehension_{tx.f_code.co_name}_at_{lineno}") + + comprehension_body_vars = ( + analysis.iterator_vars + + analysis.walrus_vars + + ([analysis.result_var] if analysis.result_var else []) + + analysis.captured_vars + ) + + def update(instructions: list[Instruction], code_options: dict[str, Any]) -> None: + code_options["co_name"] = fn_name + if sys.version_info >= (3, 11): + code_options["co_qualname"] = fn_name + code_options["co_firstlineno"] = lineno + code_options["co_cellvars"] = () + code_options["co_freevars"] = freevars + code_options["co_argcount"] = len(args) + code_options["co_posonlyargcount"] = 0 + code_options["co_kwonlyargcount"] = 0 + code_options["co_varnames"] = tuple( + args + [v for v in comprehension_body_vars if v not in args] + ) + code_options["co_flags"] = code_options["co_flags"] & ~( + CO_VARARGS | CO_VARKEYWORDS + ) + + prefix: list[Instruction] = [] + if freevars: + prefix.append(create_instruction("COPY_FREE_VARS", arg=len(freevars))) + prefix.append(create_instruction("RESUME", arg=0)) + + # Push stack_pops items onto operand stack so the comprehension + # bytecode finds them where it expects (iterator + saved vars). + # NULL positions get PUSH_NULL, non-null get LOAD_FAST. + # Items were appended to frame_values[0] in TOS-first order, + # so load in reverse to reconstruct the original stack layout. + nonnull_i = nonnull_count - 1 + for i in range(stack_pops): + if stack_pops_null_mask[i]: + prefix.append(create_instruction("PUSH_NULL")) + else: + prefix.append( + create_instruction("LOAD_FAST", argval=f"___stack{nonnull_i}") + ) + nonnull_i -= 1 + + comp_insts = _copy_comprehension_bytecode(tx, start_ip, analysis.end_ip) + + # Epilogue: ensure result is on stack, pack walrus vars, return. + epilogue: list[Instruction] = [] + if not analysis.result_on_stack: + if analysis.result_var: + epilogue.append( + create_instruction("LOAD_FAST", argval=analysis.result_var) + ) + else: + epilogue.append(create_instruction("LOAD_CONST", argval=None)) + if analysis.walrus_vars: + for var_name in analysis.walrus_vars: + epilogue.append(create_instruction("LOAD_FAST", argval=var_name)) + epilogue.append( + create_instruction( + "BUILD_TUPLE", + arg=1 + len(analysis.walrus_vars), + ) + ) + epilogue.append(create_instruction("RETURN_VALUE")) + + instructions[:] = prefix + comp_insts + epilogue + + new_code, _ = transform_code_object(tx.f_code, update) + skip_code(new_code) + + # Install as global + tx.output.install_resume_function_global(fn_name, new_code, tx.f_globals) + + return new_code, fn_name + + +def _copy_comprehension_bytecode( + tx: InstructionTranslatorBase, start_ip: int, end_ip: int +) -> list[Instruction]: + """Copy comprehension bytecode instructions, updating jump targets.""" + inst_map: dict[Instruction, Instruction] = {} + copied_insts: list[Instruction] = [] + + for ip in range(start_ip, end_ip): + original_inst = tx.instructions[ip] + copied_inst = copy.copy(original_inst) + copied_inst.exn_tab_entry = None + inst_map[original_inst] = copied_inst + copied_insts.append(copied_inst) + + for copied_inst in copied_insts: + if copied_inst.target is not None and copied_inst.target in inst_map: + copied_inst.target = inst_map[copied_inst.target] + + return copied_insts + + +def maybe_setup_comprehension_speculation( + tx: InstructionTranslatorBase, inst: Instruction +) -> bool: + """ + Handle comprehension start for Python 3.12+ BUILD_LIST/BUILD_MAP with argval 0. + Returns True if a graph break was triggered and the caller should return early. + """ + if not (sys.version_info >= (3, 12) and inst.argval == 0): + return False + + if not _is_comprehension_start(tx): + return False + + can_speculate = ( + all(b.can_restore() for b in tx.block_stack) + and not tx.one_graph + and not tx.error_on_graph_break + and not tx.is_tracing_resume_prologue + and not tx.active_generic_context_managers + and tx.output.current_tracer.parent is None + ) + + if can_speculate and tx.parent is not None: + can_speculate = tx._can_speculate_comprehension_nested() + # Only set up speculation at depth 0 (outermost comprehension) + if can_speculate and tx._comprehension_depth == 0: + speculation = tx.speculate() + if speculation.failed(tx): + _handle_comprehension_graph_break(tx, inst) + return True + tx.current_speculation = speculation + end_for_ip = _find_comprehension_end_for_ip(tx) + if end_for_ip < 0: + raise AssertionError("failed to find END_FOR for comprehension") + tx._comprehension_end_for_ips.add(end_for_ip) + tx._comprehension_depth += 1 + return False diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/comptime.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/comptime.py new file mode 100644 index 0000000000000000000000000000000000000000..b5c5c71da86bc0b7c6e5a66f3ec70da906991a78 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/comptime.py @@ -0,0 +1,439 @@ +""" +This module provides the public comptime interface to TorchDynamo, enabling users to execute +arbitrary Python code during symbolic evaluation of their programs. + +The comptime interface allows inspection and modification of TorchDynamo's compilation +process while it is running. This can be useful for: + +- Debugging compilation issues +- Inspecting intermediate state +- Adding custom guards or graph breaks +- Analyzing symbolic shapes and values + +Example usage: + + import torch + from torch._dynamo.comptime import comptime + + def my_model(x): + # Print the compile-time known information about x + comptime.print(x) + + # Print the current FX graph being constructed + comptime.print_graph() + + # Force a value to be treated as static + if comptime(lambda ctx: ctx.get_local("x").is_dynamic()): + comptime.force_static(x) + + # Add a manual graph break + comptime.graph_break() + +Note: While this API provides significant flexibility, it intentionally avoids +exposing internal implementation details of TorchDynamo to maintain compatibility +across versions. +""" + +import builtins +import dis +import time +import traceback +from collections.abc import Callable +from typing import Any, TextIO + +import torch +from torch._dynamo.symbolic_convert import InstructionTranslatorBase +from torch._dynamo.variables.base import VariableTracker +from torch._subclasses.fake_tensor import FakeTensor +from torch.fx.experimental.symbolic_shapes import free_symbols + +from .exc import unimplemented +from .variables import CellVariable +from .variables.tensor import SymNodeVariable + + +class ComptimeVar: + """ + A ComptimeVar represents a Python value, at some particular point + in time, in the Python code we are symbolically evaluating with + torchdynamo. This must be distinguished from a runtime value, as + at compile-time there are some properties of the variable we + do not know (for example, if the ComptimeVar represents a Tensor, + we only know metadata about the tensor; we do NOT know what the + actual data in the Tensor is.) + """ + + def __init__(self, v: VariableTracker) -> None: + self.__variable = v + + def as_proxy(self) -> VariableTracker | list[VariableTracker]: + """ + Returns an fx.Proxy (or tuple/list of fx.Proxy) representing + this variable in the FX graph we are assembling to pass + to the user compiler. + + This method only works for variables we actually track in + the FX graph, aka Tensors (and ints, if you are compiling + with dynamic shapes). In particular, if you have a list + or tuple of tensors, you will get a list/tuple of proxies + (not a single proxy representing the entire list/tuple). + """ + return self.__variable.as_proxy() + + def is_proxy(self) -> bool: + """ + Returns True if as_proxy() would succeed. + """ + return self.__variable.is_proxy() + + def as_fake(self) -> FakeTensor | torch.SymInt: + """ + Returns a "fake" value (either a FakeTensor or a SymInt) + representing the variable in question. This only works + for variables that denote Tensor or int. You can use + this to query metadata; e.g., v.as_fake().size(0) will + tell you the compile-time known size of the tensor. + + WARNING: Do NOT mutate the returned tensor. + """ + return self.__variable.as_proxy().node.meta["example_value"] + + def size(self, dim: int | None = None) -> int | torch.SymInt: + """ + Returns the size of the tensor (if dim is None) or the size + at the dimension dim. The returned size may be a SymInt. + """ + return self.as_fake().size(dim) # type: ignore[union-attr, return-value] + + def python_type(self) -> type: + """ + Returns what type(v) would have returned for the variable + at compile time. + """ + return self.__variable.python_type() + + def as_python_constant(self) -> Any: + """ + Returns the Python value this variable would have, but only if it is + completely known at compile-time (e.g., it is constant). + + WARNING: Do NOT mutate the returned constant. The returned constant + may or may not correspond to the actual value this variable may take + on at runtime; for example, if the variable in question is a constant + list, we may return a copy of that list. + """ + return self.__variable.as_python_constant() + + def is_python_constant(self) -> bool: + """ + Returns True if as_python_constant would succeed. + """ + return self.__variable.is_python_constant() + + def is_dynamic(self) -> bool: + if isinstance(self.__variable, SymNodeVariable): + fs = free_symbols(self.__variable.sym_num) + return bool(fs) + return False + + def force_static(self) -> None: + """ + Forces that a value is static, inducing a guard on its specific value + """ + if isinstance(self.__variable, SymNodeVariable): + self.__variable.evaluate_expr() + elif self.__variable.is_python_constant(): + # TODO: Maybe complain if this isn't a int/bool/float variable + pass + else: + raise AssertionError( + f"cannot force {self.__variable} ({type(self.__variable)}) static" + ) + + def _i_will_not_complain_if_bc_breaks_VariableTracker(self) -> VariableTracker: + """ + Returns the internal data structure VariableTracker that Dynamo uses + to represent variables at compile time. There are no BC guarantees on + this API and WE RESERVE THE RIGHT TO BREAK YOUR CODE if you rely on + it. + """ + return self.__variable + + def __repr__(self) -> str: + return self.__variable.debug_repr() + + # TODO: API for adding a custom guard + + +class ComptimeContext: + """ + This context class provides access to a public API for Dynamo's internals. + If there is something here you would find useful that is missing, please + file a feature request at https://github.com/pytorch/pytorch/ + """ + + def __init__(self, tx: InstructionTranslatorBase) -> None: + self.__tx = tx + + def get_local(self, name: str, *, stacklevel: int = 0) -> ComptimeVar: + """ + Retrieve the compile-time known information about a local. + """ + tx = self.__get_tx(stacklevel) + var = tx.symbolic_locals[name] + + # Auto-dereference when accessing cell locals in python. + if isinstance(var, CellVariable): + return ComptimeVar(tx.output.side_effects.load_cell(var)) + + return ComptimeVar(var) + + def graph_break(self, msg: str = "ComptimeContext.graph_break") -> None: + """ + Manually trigger a graph break + """ + unimplemented( + gb_type="ComptimeContext graph break", + context=msg, + explanation=f"Manually triggered ComptimeContext graph break with message {msg}.", + hints=[], + ) + + def graph(self) -> torch.fx.Graph: + """ + Retrieve the partially constructed FX graph that would be + passed to the user compiler after compilation. + """ + return self.__tx.output.graph + + def assert_static(self, val: ComptimeVar) -> None: + """ + Asserts that the int is static (and not dynamic, per dynamic shapes) + """ + if val.is_dynamic(): + raise AssertionError( + "expected static but got dynamic (run with TORCH_LOGS=dynamic for more info)" + ) + + def print_graph(self, *, verbose: bool = True, file: TextIO | None = None) -> None: + """ + Print the partially constructed FX graph that would be passed + to the user compiler after compilation. + """ + print( + self.__tx.output.graph.python_code("self", verbose=verbose).src, file=file + ) + + def parent(self) -> "ComptimeContext": + return ComptimeContext(self.__tx.parent) # type: ignore[arg-type] + + def __get_tx(self, stacklevel: int) -> Any: + tx = self.__tx + # pyrefly: ignore [bad-assignment, non-convergent-recursion] + for _ in range(stacklevel): + tx = tx.parent # type: ignore[assignment] + return tx + + def print(self, val: Any, *, file: TextIO | None = None) -> None: + print(repr(val), file=file) + + def print_disas(self, *, file: TextIO | None = None, stacklevel: int = 0) -> None: + """ + Print the current series of opcodes being executed (not including + parent frames), including where you are in the particular opcode + stream. + """ + tx = self.__get_tx(stacklevel) + print( + dis.Bytecode( + tx.f_code, + current_offset=tx.instructions[tx.instruction_pointer].offset, + ).dis(), + file=file, + ) + + def print_value_stack( + self, *, file: TextIO | None = None, stacklevel: int = 0 + ) -> None: + """ + Print the current Python value stack. Note that this is NOT the same + as the traceback; use print_bt() to print that. Note that at + stacklevel=0, this will typically be empty, as comptime cannot + currently be used in an expression context where there would be + intermediates on the stack. If you would find this useful, please + file a bug at https://github.com/pytorch/pytorch/ + + NB: Stack grows downwards in our print + """ + tx = self.__get_tx(stacklevel) + for s in tx.stack: + print(f"- {s.debug_repr()}", file=file) + + def print_locals(self, *, file: TextIO | None = None, stacklevel: int = 0) -> None: + """ + Print all of the locals available in the current context. + By default this view is very limited; you can get more information + about any individual local using get_local(). + """ + tx = self.__get_tx(stacklevel) + for k, v in tx.symbolic_locals.items(): + print(f"{k} = {v.debug_repr()}", file=file) + + def print_bt(self, *, file: TextIO | None = None, stacklevel: int = 0) -> None: + """ + Print the user code backtrace, starting at the beginning of the + frame Dynamo started evaluating. Note that this MAY NOT go all + the way to the torch.compile invocation, as we may have done + a graph break and are compiling an intermediate frame as the + starting point. If you think the other behavior would be better, + file a bug at https://github.com/pytorch/pytorch/ + """ + stack = [] + tx = self.__get_tx(stacklevel) + while tx is not None: + stack.append(tx.frame_summary()) + tx = getattr(tx, "parent", None) + print( + "".join(traceback.StackSummary.from_list(reversed(stack)).format()), + file=file, + ) + + def print_guards(self, *, file: TextIO | None = None) -> None: + """ + Print the currently installed guards for the Dynamo context. + This does NOT include guards associated with variables that + may or may not be installed in the future if those variables + are used. + """ + # TODO: improve print format, current guard format is extremely + # verbose + print( + "\n".join(f"{repr(guard)}" for guard in sorted(self.__tx.output.guards)), + file=file, + ) + + def _i_will_not_complain_if_bc_breaks_InstructionTranslator( + self, + ) -> InstructionTranslatorBase: + """ + Returns the internal data structure InstructionTranslator that Dynamo + uses to track state of symbolic evaluation. There are no BC + guarantees on this API and WE RESERVE THE RIGHT TO BREAK YOUR CODE if + you rely on it. + """ + return self.__tx + + def sleep(self, sec: int | float) -> None: + time.sleep(sec) + + +class _Comptime: + @staticmethod + def __call__( + fn: Callable[[ComptimeContext], Any], + fallback_fn: Callable[[], Any] = lambda: None, + ) -> Any: + """fn gets called at compile time in TorchDynamo, calls fallback_fn otherwise""" + fallback_fn() + + # Convenience wrappers that are more compact to use + + @staticmethod + def graph_break() -> None: + comptime(lambda ctx: ctx.graph_break()) + + @staticmethod + def print(e: Any) -> None: + comptime(lambda ctx: ctx.print(ctx.get_local("e")), lambda: print(e)) + + @staticmethod + def print_graph() -> None: + comptime(lambda ctx: ctx.print_graph()) + + @staticmethod + def print_disas(*, stacklevel: int = 0) -> None: + comptime( + lambda ctx: ctx.print_disas( + stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1 + ) + ) + + @staticmethod + def print_value_stack(*, stacklevel: int = 0) -> None: + comptime( + lambda ctx: ctx.print_value_stack( + stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1 + ) + ) + + # This is a more useful variant of print_value_stack that can be used + # in an expression context; e.g., x + print_value_stack_and_return(y + z), + # you will see x on the stack prior to the addition operation + @staticmethod + def print_value_stack_and_return(e: Any, *, stacklevel: int = 0) -> Any: + comptime( + lambda ctx: ctx.print_value_stack( + stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1 + ) + ) + return e + + @staticmethod + def print_locals(*, stacklevel: int = 0) -> None: + comptime( + lambda ctx: ctx.print_locals( + stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1 + ) + ) + + @staticmethod + def print_bt(*, stacklevel: int = 0) -> None: + comptime( + lambda ctx: ctx.print_bt( + stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1 + ) + ) + + @staticmethod + def print_guards() -> None: + comptime(lambda ctx: ctx.print_guards()) + + @staticmethod + def assert_static(val: Any) -> None: + comptime(lambda ctx: ctx.assert_static(ctx.get_local("val"))) + + @staticmethod + def force_static(val: Any) -> None: + comptime(lambda ctx: ctx.get_local("val").force_static()) + + @staticmethod + def breakpoint() -> None: + """ + Like pdb breakpoint(), but drop into pdb whenever this line + of code is compiled by dynamo. Use it by putting + this in your model code:: + + from torch._dynamo.comptime import comptime + + comptime.breakpoint() + + And then, inside pdb, you can access 'ctx' to query things + about the compilation context:: + + (Pdb) !ctx.print_bt() + (Pdb) !ctx.print_locals() + (Pdb) p ctx.get_local("attention").as_fake() + """ + + def inner(inner_ctx: ComptimeContext) -> None: + ctx = inner_ctx.parent() # noqa: F841 + builtins.breakpoint() + + comptime(inner) + + @staticmethod + def sleep(sec: int | float) -> None: + comptime(lambda ctx: ctx.sleep(ctx.get_local("sec").as_python_constant())) + + +comptime = _Comptime() diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/config.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/config.py new file mode 100644 index 0000000000000000000000000000000000000000..6759a6a1d9486d2bf8110df949a766ad00d1c758 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/config.py @@ -0,0 +1,942 @@ +""" +Configuration module for TorchDynamo compiler and optimization settings. + +This module contains various configuration flags and settings that control TorchDynamo's +behavior, including: + +- Runtime behavior flags (e.g., guard settings, specialization options) +- Debugging and development options +- Performance tuning parameters +- Feature toggles for experimental features +""" + +import getpass +import os +import sys +import sysconfig +import tempfile +from collections.abc import Callable +from os.path import abspath, dirname +from typing import Any, Literal, TYPE_CHECKING + +from torch._environment import is_fbcode +from torch.utils._config_module import Config, get_tristate_env, install_config_module + + +# to configure logging for dynamo, aot, and inductor +# use the following API in the torch._logging module +# torch._logging.set_logs(dynamo=, aot=, inductor) +# or use the environment variable TORCH_LOGS="dynamo,aot,inductor" (use a prefix + to indicate higher verbosity) +# see this design doc for more detailed info +# Design doc: https://docs.google.com/document/d/1ZRfTWKa8eaPq1AxaiHrq4ASTPouzzlPiuquSBEJYwS8/edit# +# the name of a file to write the logs to +# [@compile_ignored: debug] +log_file_name: str | None = None + +# [@compile_ignored: debug] Verbose will print full stack traces on warnings and errors +verbose = os.environ.get("TORCHDYNAMO_VERBOSE", "0") == "1" + +# [@compile_ignored: runtime_behaviour] verify the correctness of optimized backend +verify_correctness = False + +# Override backend for specific graphs (for debugging/bisecting). +# Format: "filter1:backend1;filter2:backend2;..." where filter can be: +# - Individual IDs: "0,5,10" +# - Ranges: "10-20" (inclusive) +# - Comparisons: ">10", ">=10", "<5", "<=5" +# Backends can be: "eager", "aot_eager", "inductor", etc. +# Examples: +# ">10:eager" - Run graphs with frame_id > 10 in dynamo eager backend +# "<=5:aot_eager;>5:inductor" - First 6 graphs use aot_eager, rest use inductor +# [@compile_ignored: debug] +debug_backend_override: str = os.environ.get("TORCH_COMPILE_OVERRIDE_BACKENDS", "") + +# Override inductor config for specific graphs (for debugging/bisecting). +# Format: "filter1:config1;filter2:config2;..." where filter uses same syntax as +# debug_backend_override, and config is "key=value" or "key=value,key2=value2". +# Examples: +# "0-5:triton.cudagraph_skip_dynamic_graphs=False" - Disable skip for graphs 0-5 +# ">10:triton.cudagraphs=False" - Disable cudagraphs for graphs > 10 +# [@compile_ignored: debug] +debug_inductor_config_override: str = os.environ.get( + "TORCH_COMPILE_OVERRIDE_INDUCTOR_CONFIGS", "" +) + +# Override dynamo config for specific graphs (for debugging/bisecting). +# Format: "filter1:config1;filter2:config2;..." where filter uses same syntax as +# debug_backend_override, and config is "key=value" or "key=value,key2=value2". +# Examples: +# "0-5:specialize_float=True" - Specialize floats for graphs 0-5 +# ">10:automatic_dynamic_shapes=False" - Disable dynamic shapes for graphs > 10 +# [@compile_ignored: debug] +debug_dynamo_config_override: str = os.environ.get( + "TORCH_COMPILE_OVERRIDE_DYNAMO_CONFIGS", "" +) + +# Validate that fake_fn and real_fn in @leaf_function decorators produce outputs +# with matching shapes and dtypes in eager mode. Helps catch mismatches early. +# Disabled by default to avoid runtime overhead. +# [@compile_ignored: debug] +leaf_function_validate_outputs = False + +# Check for escaped gradients in @leaf_function. When a leaf_function closes over +# a tensor with requires_grad=True, gradients won't flow back to it. This check +# walks the autograd graph to detect such cases and raises an error. +# Disabled by default to avoid runtime overhead. Enable for debugging. +# [@compile_ignored: debug] +leaf_function_check_escaped_gradients = False + +# need this many ops to create an FX graph (deprecated: not used) +minimum_call_count = 1 + +# turn on/off DCE pass (deprecated: always true) +dead_code_elimination = None + +# Enable or disable side effect replay after graph execution. +# When False, mutations to Python objects (lists, dicts, attributes) won't be +# replayed after the compiled graph runs. This can cause correctness issues +# if your code depends on these mutations being visible. This should probably +# never be False by default. At the moment, only export will need it. +replay_side_effects = True + +# Generate Python code strings for compiled graph calls. +# When enabled, the generated Python code will be stored in output_pycode. +# [@compile_ignored: debug] +generate_pycode = False + +# Configure side effect warning level +# If `info` (default): allow side effects and log to TORCH_LOGS="side_effects" and tlparse +# If `silent`, we allow side effects, no logs are made. +# If `warn`, we allow side effects but issue warnings +# If `error`, we error on side effects +# NOTE: it is NOT safe to change this config during compilation! +side_effect_replay_policy = "info" + +# disable (for a function) when cache reaches this size + +# controls the maximum number of cache entries with a guard on same ID_MATCH'd +# object. It also controls the maximum size of cache entries if they don't have +# any ID_MATCH'd guards. +# [@compile_ignored: runtime_behaviour] +recompile_limit = 8 + +# [@compile_ignored: runtime_behaviour] safeguarding to prevent horrible recomps +accumulated_recompile_limit = 256 + +skip_code_recursive_on_recompile_limit_hit: bool = Config( + default=True, deprecated=True, deprecation_message="does not do anything" +) + +# raise a hard error if cache limit is hit. If you are on a model where you +# know you've sized the cache correctly, this can help detect problems when +# you regress guards/specialization. This works best when recompile_limit = 1. +# This flag is incompatible with: suppress_errors. +# [@compile_ignored: runtime_behaviour] +fail_on_recompile_limit_hit = False + +cache_size_limit: int = Config(alias="torch._dynamo.config.recompile_limit") +accumulated_cache_size_limit: int = Config( + alias="torch._dynamo.config.accumulated_recompile_limit" +) + +skip_code_recursive_on_cache_limit_hit: bool = Config( + alias="torch._dynamo.config.skip_code_recursive_on_recompile_limit_hit", + deprecated=True, + deprecation_message="does not do anything", +) + +fail_on_cache_limit_hit: bool = Config( + alias="torch._dynamo.config.fail_on_recompile_limit_hit" +) + +# whether or not to specialize on int inputs. This only has an effect with +# dynamic_shapes; when dynamic_shapes is False, we ALWAYS specialize on int +# inputs. Note that assume_static_by_default will also cause ints to get +# specialized, so this is mostly useful for export, where we want inputs +# to be dynamic, but accesses to ints should NOT get promoted into inputs. +specialize_int = False + +# Whether or not to specialize on float inputs. Dynamo will always promote +# float inputs into Tensor inputs, but at the moment, backends inconsistently +# support codegen on float (this is to be fixed). +specialize_float = False + +# Max ops per ComputedLazyConstantVariable chain before realizing under guards; 0 disables +computed_lazy_constant_max_nodes = 64 + +# legacy config, does nothing now! +dynamic_shapes = True + +use_lazy_graph_module = ( + os.environ.get("TORCH_COMPILE_USE_LAZY_GRAPH_MODULE", "1") == "1" +) + +# This is a temporarily flag, which changes the behavior of dynamic_shapes=True. +# When assume_static_by_default is True, we only allocate symbols for shapes marked dynamic via mark_dynamic. +# NOTE - this flag can be removed once we can run dynamic_shapes=False w/ the mark_dynamic API +# see [Note - on the state of mark_dynamic] +assume_static_by_default = True + +# Internal: Shape specification patched during tracing by enter_exit_hooks. +# Set via torch.compile(dynamic_shapes=...), not directly by users. +_dynamic_shapes_spec = None + +# This flag changes how dynamic_shapes=True works, and is meant to be used in conjunction +# with assume_static_by_default=True. +# With this flag enabled, we always compile a frame as fully static for the first time, and, if we fail +# any guards due to wobbles in shape, we recompile with *all* the wobbled shapes as being marked dynamic. +automatic_dynamic_shapes = ( + os.environ.get("TORCH_DYNAMO_AUTOMATIC_DYNAMIC_SHAPES", "1") == "1" +) + +# Valid options: "dynamic", "unbacked" +automatic_dynamic_shapes_mark_as: Literal["dynamic", "unbacked"] = "dynamic" + +# When True, adds exclusion guards for tensor dims and scalars that transition +# from static to dynamic via automatic_dynamic_shapes. +# +# Invariant: when enabled, automatic_dynamic recompilation preserves graph +# selection — inputs that matched a previous static cache entry will continue +# to use that entry, not be intercepted by a newer dynamic entry. This holds +# as long as recompilations are caused solely by the same variable being +# observed with different static values (progressive dynamism). A recompilation +# triggered by a different reason (e.g., a guard failure unrelated to shape +# transitions) will clear the exclusion state for that entry. +# +# Mechanism: the exclusion guard rejects inputs matching the prior static +# graph's sizes, so those inputs fall through to the more specialized static +# graph instead of being captured by the newer dynamic graph. +# +# Scope: applies only to graph-input-level dimension and scalar transitions. +# Does NOT handle data-dependent branching (if x.size(0) > k), graph breaks, +# or other recompilation triggers where no dimension actually transitions. +automatic_dynamic_exclusion_guard = False + +# log graph in/out metadata +# This is only turned on for export today since we +# know we are tracing a flat callable. later, this +# can extended to other use cases as well. +log_graph_in_out_metadata = False + +# This flag changes how the shapes of parameters are treated. +# If this flag is set to True, then the shapes of torch.nn.Parameter as well as of torch.Tensor are attempted to be dynamic +# If this flag is set to False, then the shapes of torch.nn.Parameter are assumed to be static, +# while the shapes of torch.Tensor are assumed to be dynamic. +force_parameter_static_shapes = True + +# This flag ensures that the shapes of a nn module are always assumed to be static +# If the flag is set to True, then the shapes of a nn.module are assumed to be static +# If the flag is set to False, then the shapes of a nn.module can be dynamic +force_nn_module_property_static_shapes = True + +# Typically, if you mark_dynamic a dimension, we will error if the dimension +# actually ended up getting specialized. This knob changes the behavior so +# that we don't error at all. This is helpful for our CI where I'm using a +# heuristic to mark batch dimensions as dynamic and the heuristic may get it +# wrong. +allow_ignore_mark_dynamic = False + +# Set this to False to assume nn.Modules() contents are immutable (similar assumption as freezing) +guard_nn_modules = True + +# Uses CPython internal dictionary tags to detect mutation. There is some +# overlap between guard_nn_modules_using_dict_tags and guard_nn_modules flag. +# guard_nn_modules unspecializes the nn module instance and adds guard for each +# relevant member of the nn modules. On the other hand, +# guard_nn_modules_using_dict_tags specializes on each nn module instance but +# uses low overhead dict version matching to detect mutations, obviating the +# need to guard on members of the nn modules. With +# guard_nn_modules_using_dict_tags, the guard_nn_modules is not really required +# but kept around for debugging and discussing unspecializing nn module +# variables. +# TODO(janimesh, voz): Remove both of these flags (or at least guard_nn_modules) +# once we have reached stability for the guard_nn_modules_using_dict_tags. +guard_nn_modules_using_dict_tags = True + +# Flag to enable preparation for graph freezing, so that the named parameters and +# buffers are passed as params_flat in tracing context by AOT autograd. +# Non-Inductor backends can use this list for graph freezing. +prepare_freezing = os.environ.get("TORCHDYNAMO_PREPARE_FREEZING", "0") == "1" + +# NOTE this has been deprecated, it does nothing now. +traceable_tensor_subclasses: set[type[Any]] = set() + +# If a tensor subclass is put into this set, Dynamo will model its instances in +# a very conservative and limited way (most likely causing lots of graph breaks +# if one apply tensor ops on these instances). This is useful if you encounter +# internal compiler errors from Dynamo which are caused by tensor subclasses, +# and you are willing to tolerate potential graph breaks rather than hard error. +nontraceable_tensor_subclasses: set[type[Any]] = set() + +# Suppress errors in torch._dynamo.optimize, instead forcing a fallback to eager. +# This is a good way to get your model to work one way or another, but you may +# lose optimization opportunities this way. Devs, if your benchmark model is failing +# this way, you should figure out why instead of suppressing it. +# This flag is incompatible with: fail_on_recompile_limit_hit. +suppress_errors = bool(os.environ.get("TORCHDYNAMO_SUPPRESS_ERRORS", False)) + +# Record and write an execution record of the current frame to a file +# if an exception is encountered +# @compile_ignored[debug] +replay_record_enabled = os.environ.get("TORCH_COMPILE_REPLAY_RECORD", "0") == "1" + +# Rewrite assert statement in python with torch._assert +rewrite_assert_with_torch_assert = True + +# Disable dynamo +disable = os.environ.get("TORCH_COMPILE_DISABLE", "0") == "1" + +# [@compile_ignored: runtime_behaviour] Get a cprofile trace of Dynamo +cprofile = os.environ.get("TORCH_COMPILE_CPROFILE", False) + +# Enable Dynamo profiler. When enabled, prints pstats output showing +# time spent tracing each user function. Set to True to enable, or set to a +# file path to save the .prof file for snakeviz. +# [@compile_ignored: runtime_behaviour] +dynamo_profiler: bool | str = os.environ.get("TORCH_COMPILE_DYNAMO_PROFILER", False) + +# Legacy config, does nothing now! +skipfiles_inline_module_allowlist: dict[Any, Any] = {} +"""Allowlist of inline modules to skip during compilation. + +Legacy configuration that previously controlled which modules could be +inlined during tracing. This configuration is deprecated and no longer used. + +:type: dict[Any, Any] +:default: {} + +.. deprecated:: + This configuration is deprecated and does nothing now. + +.. note:: + DEPRECATED: This setting has no effect on current behavior. +""" + +# If a string representing a PyTorch module is in this ignorelist, +# the `allowed_functions.is_allowed` function will not consider it +# when creating a list of PyTorch functions that will appear in +# FX IR. +allowed_functions_module_string_ignorelist = { + "torch.distributions", + "torch.testing", + "torch._refs", + "torch._prims", + "torch._decomp", +} + +# Debug Flag to try minifier at different stages. Possible values are {None, "aot", "dynamo"} +# None - Minifier is switched off +# dynamo - Runs minifier on the TorchDynamo produced graphs, if compilation fails +# aot - Runs minifier on the Aot Autograd produced graphs, if compilation fails +# [@compile_ignored: debug] +repro_after = os.environ.get("TORCHDYNAMO_REPRO_AFTER", None) + +# Compiler compilation debug info +# 1: Dumps the original graph out to repro.py if compilation fails +# 2: Dumps a minifier_launcher.py if compilation fails. +# 3: Always dumps a minifier_launcher.py. Good for segfaults. +# 4: Dumps a minifier_launcher.py if the accuracy fails. +# [@compile_ignored: debug] +repro_level = int(os.environ.get("TORCHDYNAMO_REPRO_LEVEL", 2)) + +# By default, we try to detect accuracy failure by running both forward +# and backward of a torchdynamo produced graph (if you are using repro_after +# 'dynamo'). This setting forces us to only test the forward graph and +# not the backward graph. This can be helpful if you're trying to debug +# an inference only problem, but the minifier seems to be choking on the +# backwards step +# TODO: Detect this situation automatically so the user doesn't need +# to manually configure this +# [@compile_ignored: debug] +repro_forward_only = os.environ.get("TORCHDYNAMO_REPRO_FORWARD_ONLY") == "1" + +# The tolerance we should use when testing if a compiled graph +# has diverged so that we should treat it as an accuracy failure +# [@compile_ignored: debug] +repro_tolerance = 1e-3 + + +# Whether to ignore non-floating point values when checking accuracy. +# Checking accuracy of non-floating point values such as boolean tensors +# can lead to false positives. +# [@compile_ignored: debug] +repro_ignore_non_fp = os.environ.get("TORCHDYNAMO_REPRO_IGNORE_NON_FP") == "1" + +# If True, when testing if two models are the same, we will test them against +# a third fp64 reference and only report a problem if the RMSE relative to the +# fp64 is greater. However, this will use more memory; you may disable this +# if memory usage is too high. +# [@compile_ignored: runtime_behaviour] +same_two_models_use_fp64 = True + +# Not all backends support scalars. Some calls on torch.Tensor (like .item()) return a scalar type. +# When this flag is set to False, we introduce a graph break instead of capturing. +# This requires dynamic_shapes to be True. +capture_scalar_outputs = os.environ.get("TORCHDYNAMO_CAPTURE_SCALAR_OUTPUTS") == "1" + +# Not all backends support operators that have dynamic output shape (e.g., +# nonzero, unique). When this flag is set to False, we introduce a graph +# break instead of capturing. This requires dynamic_shapes to be True. +# If you set this to True, you probably also want capture_scalar_outputs +# (these are separated for historical reasons). +capture_dynamic_output_shape_ops = ( + os.environ.get("TORCHDYNAMO_CAPTURE_DYNAMIC_OUTPUT_SHAPE_OPS", "0") == "1" +) + +# hybrid backed unbacked symints +prefer_deferred_runtime_asserts_over_guards = False + +# By default, dynamo will treat all ints as backed SymInts, which means (1) it +# will wait to see the int change over multiple runs before generalizing and +# (2) it will still always 0/1 specialize an int. When true, this knob +# forces dynamo to treat _length_per_key and _offset_per_key on +# KeyedJaggedTensor from torchrec as size-like unbacked SymInts, so that +# they (1) generalize immediately and (2) unsoundly never compare equal to +# 0/1. This is not on by default as AOTAutograd/Inductor cannot currently +# compile this code; however, this can be useful for export. +force_unspec_int_unbacked_size_like_on_torchrec_kjt = False + +# Currently, Dynamo will always specialize on int members of NN module. +# However, there could be cases where this is undesirable, e.g., when tracking +# step count leading to constant recompilation and eventually eager fallback. +# Setting this flag to True will allow int members to be potentially unspecialized +# through dynamic shape mechanism. +# Defaults to False for BC. +allow_unspec_int_on_nn_module = False + +# Specify how to optimize a compiled DDP module. The flag accepts a boolean +# value or a string. There are 3 modes. +# 1. "ddp_optimizer" (or True): with "ddp_optimizer", Dynamo will automatically +# split model graph into pieces to match DDP bucket sizes to allow DDP +# comm/compute overlap. +# 2. "python_reducer" (experimental): this optimization requires the usage +# of compiled_autograd. With "python_reducer", DDP will disable the C++ reducer +# and use the Python reducer to allow compiled_autograd to trace the +# communication and allow comm/compute overlap without graph-breaks. +# 3. "no_optimization" (or False): Dynamo won't split the model graph, nor +# will Python reducer be used. With this mode, there will be no graph-breaks +# and the original DDP C++ reducer will be used. There will no comm/compute +# overlap. This mode CANNOT be used with compiled_autograd. +# Note that to avoid breaking the existing usage, mode 1 and mode 4 can be +# specified with a boolean value. True is using ddp_optimizer and False is +# no optimization. +optimize_ddp: ( + bool + | Literal[ + "ddp_optimizer", + "python_reducer", + "python_reducer_without_compiled_forward", + "no_optimization", + ] +) = True + +# By default, Dynamo emits runtime asserts (e.g. torch._check) in the graph. +# In some cases those asserts could be performance costly +# E.g. torch._check(tensor[0].item() > 2) for tensor on cuda will require cuda sync. +# Setting this to True keeps them hinting to symbolic shapes engine, +# but not be emitted in the graph. +do_not_emit_runtime_asserts: bool = ( + os.environ.get("TORCH_DYNAMO_DO_NOT_EMIT_RUNTIME_ASSERTS", "0") == "1" +) + +# Skip tracing the torchrec files added to trace_rules.FBCODE_SKIP_DIRS +skip_torchrec = True + +# Don't apply most trace_rules.py rules +dont_skip_tracing = False + +# No longer used +optimize_ddp_lazy_compile = False + +# lambda guarding on object aliasing to improve opportunity for dict tag +# optimization +use_lamba_guard_for_object_aliasing = False + +# Whether to skip guarding on FSDP-managed modules +skip_fsdp_guards = True + +# Make dynamo skip guarding on hooks on nn modules +# Note: unsafe: if your model actually has hooks and you remove them, or doesn't and you add them, +# dynamo will not notice and will execute whichever version you first compiled. +skip_nnmodule_hook_guards = True + +# Make dynamo skip no tensor aliasing guard on parameters +# Note: unsafe: if you compile a function with different parameters as inputs, +# and then later pass on the same parameter as two inputs, dynamo will not +# notice and lead to incorrect result. +skip_no_tensor_aliasing_guards_on_parameters = True + +# Considers a tensor immutable if it is one of the values of a dictionary, and +# the dictionary tag is same across invocation calls. +skip_tensor_guards_with_matching_dict_tags = True + +# Skips guards on func.__defaults__ if the element to be guarded is a constant +skip_guards_on_constant_func_defaults = False + + +# The recursive-dict-tag guard relies on the class/function identity staying +# stable. We therefore assume that the following function dunder attributes +# are **never rebound** to a different object: +# +# • __code__ • __closure__ +# • __defaults__ • __kwdefaults__ +# • __annotations__ • __mro__ +# +# It is fine to mutate the objects they already point to (e.g. tweak an element +# inside __defaults__), but assignments like +# +# foo.__defaults__ = (3, 4) # REBIND - NOT SUPPORTED +# +# would invalidate the optimization. This type of rebinding is rare, so we +# assume that the rebinding never happens for guard purposes. Set the flag +# below to False only in environments where such rebinding is known to occur. +assume_dunder_attributes_remain_unchanged = True + +# Speedup guard execution of nested nn modules by recursively checking for dict +# tags to avoid full guard execution. +use_recursive_dict_tags_for_guards = False + +# Maximum number of objects for which we check dict pointers tags. This is +# useful for regional compilation. +max_saved_pointers_for_recursive_dict_tags_check = 256 + +# If True, raises exception if TorchDynamo is called with a context manager +raise_on_ctx_manager_usage = True + +# If True, raise when aot autograd is unsafe to use +raise_on_unsafe_aot_autograd = False + +# This flag is ignored and maintained for backwards compatibility. +error_on_nested_jit_trace = True + +# If true, error with a better message if we symbolically trace over a +# dynamo-optimized function. If false, silently suppress dynamo. +error_on_nested_fx_trace = True + +# If true, force dynamo compilation even when inside FX symbolic tracing. +# This allows nested compilation where the outer tracer (e.g., make_fx) can +# trace over dynamo-compiled functions. Use with error_on_nested_fx_trace=False. +force_compile_during_fx_trace = False + +# Disables graph breaking on rnn. YMMV with backends. +allow_rnn = False + +# If true, enables feature that captures PyTorch sparsity in the +# exported FX graph. This flag should become the default eventually +# and be removed, but currently provides a way to fall back to old +# graph breaking behavior. +capture_sparse_compute = True + +# If true, error if we try to compile a function that has +# been seen before. +# [@compile_ignored: runtime_behaviour] +error_on_recompile = False + +# [@compile_ignored: debug] Whether to report any guard failures (deprecated: does not do anything) +report_guard_failures = True + +# [@compile_ignored: debug] root folder of the project +base_dir = dirname(dirname(dirname(abspath(__file__)))) + +# Trace through NumPy or graphbreak +trace_numpy = True + +# Trace through torch.autograd.grad or graphbreak +trace_autograd_ops = False + +# Default NumPy dtypes when tracing with torch.compile +# We default to 64bits. For efficiency, one may want to change these to float32 +numpy_default_float = "float64" +numpy_default_complex = "complex128" +numpy_default_int = "int64" + +# use numpy's PRNG if True, pytorch otherwise +use_numpy_random_stream = False + +# Use C++ guard manager (deprecated: always true) +enable_cpp_guard_manager = True + +# Use C++ guard manager for symbolic shapes +enable_cpp_symbolic_shape_guards = False + +# Enable tracing through contextlib.contextmanager +enable_trace_contextlib = True + +# Enable tracing through unittest +enable_trace_unittest = False + +# Enable tracing LOAD_BUILD_CLASS bytecode +enable_trace_load_build_class = False + +enable_faithful_generator_behavior = Config( # type: ignore[var-annotated] + default=True, + deprecated=True, + deprecation_message="does not do anything, generators are always traced lazily", +) + +# Inline inbuilt nn modules +inline_inbuilt_nn_modules = Config( # type: ignore[var-annotated] + default=True, + justknob="pytorch/compiler:inline_inbuilt_nn_modules", + deprecated=True, + deprecation_message="does not do anything, inline_inbuilt_nn_modules is always True", +) + +# Resume tracing in nested frames if a nested graph break occurs +# Old behavior is to bubble up the graph break to the top level frame. +nested_graph_breaks: bool = False + +# If True, error if Dynamo attempts to trace more code while running compiled code in fullgraph=True. +# If Dynamo determines that it should skip tracing the code (either at the C/C++ or Python level), +# no error will be raised. +# Set to false if force falling back to eager is desired. +error_on_dynamo_callback_in_fullgraph_compiled_code = False + +# Install "free" tensor variables (globals, non-locals, nn module attributes) +# as graph attributes. This is useful for export, as it +# produces a consistent number of inputs to the graph. +install_free_tensors = False + +# Temporary flag to control the turning of install_free_tensors to True for +# export. We will remove this flag in a few weeks when stable. +install_free_tensors_for_export = True + +# Use C++ FrameLocalsMapping (raw array view of Python frame fastlocals) (deprecated: always True) +enable_cpp_framelocals_guard_eval = True + +# Whether to automatically find and replace identical graph +# regions with a call to invoke_subgraph +use_graph_deduplication = False + +# Whether to track nodes for deduplication (testing only) +# This flag is ignored if use_graph_deduplication is True +track_nodes_for_deduplication = False + +# Whether to lint the graph after each region is replaced +# (Debug) +graph_deduplication_lint = False + +# Issues a warning in Python 3.13.0 for possibly slower guard evaluation and +# instructs user to attempt using 3.13.1+, where the CPython bug is fixed. +# Should be disabled in dynamo-wrapped tests since some tests check that no warnings are issued. +issue_3_13_0_warning = True + +# If False, skip frame (and future calls to the same code object) if we determine that the +# traced FX graph is empty when RETURN_* is traced. +allow_empty_graphs = False + +# Used for testing - forces all top-level functions to be nested when traced with Dynamo. +# There are slight differences between this config and wrap_top_frame. +debug_force_nested_calls = False + +# Used for testing - forces a graph break when a function +# that doesn't make any Dynamo-inlined calls returns +debug_force_graph_break_on_leaf_return = False + +# Used for testing - causes CompileCounter.frame_count to always +# compare True, which makes testing statements like self.assertEqual(CompileCounter.frame_count, n) +# always pass. +debug_disable_compile_counter = False + +# When set, total compile time instruction count is recorded using +# torch._dynamo.utilsCompileTimeInstructionCounter. +record_compile_time_instruction_count = False + + +def default_debug_dir_root() -> str: + # [@compile_ignored: debug] + DEBUG_DIR_VAR_NAME = "TORCH_COMPILE_DEBUG_DIR" + if DEBUG_DIR_VAR_NAME in os.environ: + return os.path.join(os.environ[DEBUG_DIR_VAR_NAME], "torch_compile_debug") + elif is_fbcode(): + return os.path.join( + tempfile.gettempdir(), getpass.getuser(), "torch_compile_debug" + ) + else: + return os.path.join(os.getcwd(), "torch_compile_debug") + + +# [@compile_ignored: debug] +debug_dir_root = default_debug_dir_root() + +# [@compile_ignored: debug] +_save_config_ignore = { + "repro_after", + "repro_level", + # workaround: "cannot pickle PyCapsule" + "constant_functions", + # workaround: "cannot pickle module" + "skipfiles_inline_module_allowlist", +} + +# for backend="cudagraphs", mutations on input be sent to the cudagraph backend +# or replayed in aot_autograd epilogue. default is False because mutation on inputs +# can prevent cudagraphing. +cudagraph_backend_keep_input_mutation = False + +# enable cudagraph support for mutated inputs from prior cudagraph pool +cudagraph_backend_support_input_mutation = False + +# When True, only ops that have the torch.Tag.pt2_compliant tag +# will be allowed into the graph; all other ops will be disallowed +# and will fall back to eager-mode PyTorch. Useful to ensure +# correctness of custom ops. +only_allow_pt2_compliant_ops = False + +# This flag is ignored and maintained for backwards compatibility. +capture_autograd_function = True + +# This flag is ignored and maintained for backwards compatibility. +capture_func_transforms = True + +# Enable capturing torch.profiler.record_function ops in the graph +# When True, profiler ops are emitted to the graph and preserved through +# compilation (make_fx, functionalization). When False, profiler ops +# are treated as nullcontext. +capture_profiler_record_function: bool = False + +# If to log Dynamo compilation metrics into log files (for OSS) and Scuba tables (for fbcode). +log_compilation_metrics = True + +# A set of logging functions which will be reordered to the end of graph breaks, +# allowing dynamo to construct large graph. Note that there are some +# limitations to this, such as how it does not correctly print objects that were +# mutated after the print statement. +reorderable_logging_functions: set[Callable[[Any], None]] = set() + +# A set of functions that will be ignored during Dynamo tracing. +# These functions will NOT run, will NOT be reordered, and will NOT +# cause graph breaks. They act as full no-ops. +# Ignored functions can take any arguments, but MUST return None. +# Functions should either be module-level functions, +# `logging.Logger.` (ignores all method for all logging.Logger instances) +# or `logger_obj.` (ignores method only for logger_obj logging.Logger instance). +# Other functions may or may not be ignored due to implementation details. If you want to ignore a function +# that `ignore_logging_functions` is failing to ignore, please submit an issue. +ignore_logging_functions: set[Callable[..., Any]] = set() + +# Backwards compat: `ignore_logger_methods` now aliases `ignore_logging_functions`. +# Existing code that used `ignore_logger_methods` will continue to work. +ignore_logger_methods: set[Callable[..., Any]] = Config( + alias="torch._dynamo.config.ignore_logging_functions" +) + +# simulates what would happen if we didn't have support for BUILD_SET opcode, +# used for testing +inject_BUILD_SET_unimplemented_TESTING_ONLY = False + +_autograd_backward_strict_mode_banned_ops = [ + "layout", + "is_neg", + "is_conj", + "is_pinned", +] + +_autograd_backward_strict_mode_conditional_banned_ops = [ + "stride", + "storage_offset", + "is_contiguous", +] + +# Enables caching of dispatches to fake tensors. +fake_tensor_cache_enabled = ( + os.environ.get("TORCH_FAKE_TENSOR_DISPATCH_CACHE", "1") == "1" +) + +# Enables cross checking between the fake tensor cache and dispatch. +fake_tensor_cache_crosscheck_enabled = ( + os.environ.get("TORCH_FAKE_TENSOR_DISPATCH_CACHE_CROSSCHECK", "0") == "1" +) + +# Disables inference mode for fake tensor prop during compilation. At runtime, +# the inference_mode is still respected. +fake_tensor_disable_inference_mode = True + +# Experimental feature for running automatic caching precompile. +# Enables automatic DynamoCache save/load +caching_precompile = os.environ.get("TORCH_CACHING_PRECOMPILE", "0") == "1" + +strict_precompile = os.environ.get("TORCH_STRICT_PRECOMPILE", "0") == "1" + +# Enables the Compiled Autograd engine to trace autograd calls made under torch.compile(). +# Note: AOTAutograd will still trace and partition an AOT backward graph local to that +# compiled region. But AOTAutograd traces without knowledge of backward hooks which are +# coordinated by the Autograd engine, and under the hood, it uses the torch.autograd.grad +# API, so it cannot capture gradient accumulation operations (AccumulateGrad). +# +# Compiled Autograd will trace all autograd operations as seen by the Autograd engine. +# This flag will also lift certain restrictions during the forward trace such as +# registering backward hooks on tensors contained within the compiled region. +compiled_autograd = False + +# We have small decompositions for some optimizer ops such as +# addcmul and foreach_addcmul which avoid item() graph breaks by decomposing +# into their constituent ops. This flag controls whether we use these decompositions +# This can affect numerics for non-inductor backends. +enable_dynamo_decompositions = True + + +# Checks if we should graph break when seeing nn parameter constructors +# in dynamo; this is so that we clearly fail and ask users to move outside +# the function as opposed to trying to support the ctor with unclear semantics +# See https://github.com/pytorch/pytorch/issues/157452 for more context +graph_break_on_nn_param_ctor = True + +# If True, enable calling torch.compile inside __torch_dispatch__ handlers. +# When enabled: +# 1. __torch_dispatch__ methods are automatically wrapped with torch._dynamo.disable +# 2. torch.compile is skipped when active TorchDispatchModes are on the stack +# (unless they have ignore_compile_internals=True) +# This allows torch.compile to work inside dispatch mode handlers once all +# ambient modes have been "consumed". +# See https://github.com/pytorch/pytorch/issues/155331 for more context. +inline_torch_dispatch_torch_compile = True + +# Eager AC/SAC reapplies the mutations (like global dict mutations) in the +# backward during the recomputation of forward. torch.compile has no easy way to +# reapply python mutations in the backward. But many users might be ok to skip +# reapplication of side effects in the backward. They can set this config flag +# to accept this eager and compile divergence. +skip_fwd_side_effects_in_bwd_under_checkpoint = False + + +# Overrides torch.compile() kwargs for Compiled Autograd: +compiled_autograd_kwargs_override: dict[str, Any] = {} +"""Overrides torch.compile() kwargs for Compiled Autograd. + +This dictionary allows overriding specific torch.compile() keyword arguments +when using Compiled Autograd. Only certain overrides are currently supported. + +:type: dict[str, Any] +:default: {} + +Example:: + + torch._dynamo.config.compiled_autograd_kwargs_override = { + "fullgraph": True + } + +.. note:: + Currently only the "fullgraph" kwarg override is supported. Other kwargs + may be added in future versions. +""" + + +# Enables use of collectives *during* compilation to synchronize behavior +# across ranks. Today, this is used solely to modify automatic_dynamic_shapes +# behavior, making it so that we infer that if an input is dynamic by +# inspecting whether or not its input size varies across ranks. Because +# this synchronization uses collectives, all ranks must run compilation at +# the same time; ranks must not diverge with graph breaks. This can be most +# reliably achieved by ensuring PT2 only is run on SPMD programs. If this +# invariant is inviolated, you will likely deadlock NCCL and encounter a +# NCCL timeout. +enable_compiler_collectives = os.environ.get("TORCH_COMPILER_COLLECTIVES", "0") == "1" + +# Allow for experimental support of compiled p2p ops +enable_p2p_compilation = ( + os.environ.get("TORCHDYNAMO_ENABLE_P2P_COMPILATION", "0") == "1" +) + +# Enables a local, filesystem "profile" which can be used for automatic +# dynamic decisions, analogous to profile-guided optimization. This config +# ONLY has an effect if torch.compiler.config.workflow_id is specified, +# which specifies the name of the profile we will save/load. +# +# The idea is that if we observe that a particular input is dynamic over +# multiple iterations on one run, we can save a profile with this information +# so the next time we run we can just make it dynamic the first time around, +# skipping an unnecessary static compilation. The profile can be soundly +# stale, if it is wrong, it just means we may make more things dynamic than +# was actually necessary (NB: this /can/ cause a failure if making something +# dynamic causes the compiler to stop working because you tickled a latent +# bug.) +# +# The profile is ONLY guaranteed to work if the user source code is 100% +# unchanged. Applying the profile if there are user code changes is only +# best effort otherwise. In particular, we identify particular code objects +# by filename, line number and name of their function, so adding/removing newlines +# will typically cause cache misses. We continuously update the profile, +# so if we only discover something is dynamic on the second run, we will update +# the profile for subsequent runs. +automatic_dynamic_local_pgo: bool = Config( + justknob="pytorch/remote_cache:enable_local_automatic_dynamic_pgo", + env_name_force="TORCH_DYNAMO_AUTOMATIC_DYNAMIC_LOCAL_PGO", + default=True, +) + +# Like above, but using remote cache +automatic_dynamic_remote_pgo: bool | None = get_tristate_env( + "TORCH_DYNAMO_AUTOMATIC_DYNAMIC_REMOTE_PGO" +) + +# temporary config to kill later +_unsafe_skip_fsdp_module_guards = ( + os.environ.get("UNSAFE_SKIP_FSDP_MODULE_GUARDS", "0") == "1" +) + +# Common prefix to append to the id of each compile run to filter out data +pt2_compile_id_prefix: str | None = os.environ.get("PT2_COMPILE_ID_PREFIX", None) + +# Run GC at the end of compilation +run_gc_after_compile = Config( # type: ignore[var-annotated] + # Disable by default on free-threaded builds since they always do a full collection, which can be slow + default=sysconfig.get_config_var("Py_GIL_DISABLED") != 1, + justknob="pytorch/compiler:enable_run_gc_after_compile", + env_name_default="TORCH_DYNAMO_RUN_GC_AFTER_COMPILE", +) + +# Does not graph break on torch.autograd._profiler_enabled if set to True. We +# want this flag to be True by default, but there is an unsolved bug that causes +# distributed jobs to timeout with Kineto profiler when this is set to True. +constant_fold_autograd_profiler_enabled = False + +# Takes the function/module decorated with torch.compile and passes it through a +# wrapper. This ensures that nn.module hooks are also compiled in the same frame. +wrap_top_frame = False + +# Flag to record runtime overhead in profile traces. Used for pre-graph bytecode +# and AOTAutograd runtime wrapper. +record_runtime_overhead = True + +# Flag to enable the use of torch.compile().aot_compile() API. Should be always True. +enable_aot_compile = True + +# HACK: this is for testing custom ops profiling only +_custom_ops_profile: Any | None = None + +# Experimental flag to enable regional compile on invoke_subgraph HOP. +# For testing only! +enable_invoke_subgraph_regional_compile: bool = False + +# When True, run a post-tracing pass that inlines all invoke_subgraph HOPs +# back into the parent graph, producing a flat FX graph. Useful when +# downstream compilers (like vllm-compile) don't support HOPs or prefer a +# flat graph. +inline_invoke_subgraph: bool = False + +# Inline invoke_subgraph HOPs that are referenced by exactly one call site. +# Single-use subgraphs add overhead without deduplication benefit. +inline_single_use_invoke_subgraph: bool = True + +# Clear WeakIdRef entries from TracingContext.tensor_to_context and +# MetaTensorDescriber.lookup_tensor at the end of compile. These weakrefs +# can block torch.utils.swap_tensors from working after compile. +# - None (default): clear for registered backends (inductor, eager, etc.), +# don't clear for custom backends (to support standalone_compile, etc.) +# - True: always clear regardless of backend +# - False: never clear regardless of backend +invalidate_compile_context_weakrefs: bool | None = None + +# Reorder and rename output graph nodes into a canonical topological order so +# that structurally equivalent graphs (e.g., same model traced with different +# dict iteration orders across distributed ranks) produce identical FX graphs. +canonicalize_output_graph_node_order: bool = False + +if TYPE_CHECKING: + from torch.utils._config_typing import * # noqa: F403 + + def _make_closure_patcher(**changes: Any) -> Any: ... + + +install_config_module(sys.modules[__name__]) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/convert_frame.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/convert_frame.py new file mode 100644 index 0000000000000000000000000000000000000000..14e6026eba0a8f5d9a5986c031c981c3a28dad5e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/convert_frame.py @@ -0,0 +1,2658 @@ +""" +This module implements TorchDynamo's core frame conversion functionality, transforming Python +frames into FX graphs. It handles: + +- Frame analysis and bytecode transformation +- Guard creation and management for dynamic behaviors +- Cache management for recompilation +- Error handling and fallback mechanisms + +Key classes: +- ConvertFrame: Main entry point for frame conversion with error handling +- ConvertFrameAssert: Implements core frame to graph conversion logic +- Tracker: Tracks input/output code objects during conversion +- CatchErrorsWrapper: Provides error handling and suppression logic + +The conversion process preserves program semantics while enabling optimizations +through torch.compile() and related systems. + +NOTE: _torchdynamo_orig_backend is used for convert frame wrappers to identify the inner wrapped function. +By going down the _torchdynamo_orig_backend chain, one can recover the original unwrapped backend, +which is checked for during the Dynamo cache lookup. +""" + +from __future__ import annotations + +import collections +import contextlib +import cProfile +import dataclasses +import dis +import functools +import gc +import importlib +import inspect +import itertools +import logging +import os +import pstats +import random # noqa: F401 -- eval_frame_cpp.cpp imports random at runtime; torch.package needs this to detect the dependency +import subprocess +import sys +import tempfile +import threading +import time +import traceback +import types +import typing +import unittest.mock as mock +import weakref +from dataclasses import dataclass +from pathlib import Path +from types import CellType, CodeType, FunctionType, ModuleType +from typing import Any, cast, NoReturn, TypeVar +from typing_extensions import ParamSpec +from weakref import ReferenceType + +import torch +import torch._logging +from torch._C._dynamo.guards import GlobalStateGuard +from torch._dynamo.callback import CallbackTrigger +from torch._dynamo.distributed import get_compile_pg +from torch._dynamo.symbolic_convert import TensorifyState +from torch._guards import compile_context, CompileContext, CompileId, tracing +from torch._higher_order_ops.utils import _in_hop_compile +from torch._logging import structured +from torch._utils_internal import ( + compile_time_strobelight_meta, + maybe_upload_prof_stats_to_manifold, + signpost_event, +) +from torch.fx._lazy_graph_module import _use_lazy_graph_module +from torch.fx.experimental.symbolic_shapes import ( + ConstraintViolationError, + GuardOnDataDependentSymNode, +) +from torch.fx.graph_module import _forward_from_src as original_forward_from_src +from torch.monitor import _WaitCounter +from torch.nn.parallel.distributed import DistributedDataParallel +from torch.utils._python_dispatch import ( + _disable_current_modes, + any_torch_dispatch_mode_on_stack, + is_in_any_mode_without_ignore_compile_internals, + is_traceable_wrapper_subclass, +) +from torch.utils._traceback import CapturedTraceback, format_traceback_short + +from . import config, decorators, exc, graph_break_hints, trace_rules +from .backends.registry import _is_registered_backend +from .bytecode_analysis import remove_dead_code, remove_pointless_jumps +from .bytecode_transformation import ( + check_inst_exn_tab_entries_valid, + Instruction, + is_generator, + propagate_inst_exn_table_entries, + transform_code_object, +) +from .cache_size import ( + CacheSizeRelevantForFrame, + compute_cache_size, + exceeds_recompile_limit, + is_recompilation, +) +from .code_context import code_context +from .eval_frame import ( + _get_cache_entries_for_region, + _get_total_cache_entry_count, + add_skip_reason, + always_optimize_code_objects, + Constraint, + dynamo_tls, + get_eval_frame_isolate_recompiles_id, + innermost_backend, + skip_code, + TorchPatcher, +) +from .exc import ( + augment_exc_message, + BackendCompilerFailed, + FailOnRecompileLimitHit, + format_error_msg, + InternalTorchDynamoError, + PackageError, + ResumePrologueTracingError, + ShortenTraceback, + TorchRuntimeError, + UncapturedHigherOrderOpError, + unimplemented, + Unsupported, + UserError, +) +from .graph_bytecode_inputs import reset_user_object_tracking +from .guards import ( + CheckFunctionManager, + get_and_maybe_log_recompilation_reasons, + GuardedCode, +) +from .hooks import Hooks +from .output_graph import CodeOptions, DynamoTracerOutput, OutputGraphCommon +from .pgo import ( + _log_size_mismatch_recompile, + log_frame_dynamic_whitelist, + put_code_state, +) +from .replay_record import ExecutionRecord +from .resume_execution import TORCH_DYNAMO_RESUME_IN_PREFIX +from .symbolic_convert import ( + DistributedState, + ExceptionStack, + InstructionTranslator, + LocalState, + SpeculationLog, +) +from .trace_rules import is_numpy +from .types import ConvertFrameReturn, FrameAction, FrameExecStrategy, wrap_guarded_code +from .utils import ( + _get_error_on_graph_break, + chromium_event_timed, + CleanupManager, + CompileTimeInstructionCounter, + counters, + dynamo_timed, + format_bytecode, + gen_record_file_name, + get_hook_for_recompile_user_context, + get_metrics_context, + increment_frame, + is_namedtuple, + istype, + LazyString, + maybe_disable_inference_mode, + maybe_disable_inference_mode_for_fake_prop, + orig_code_map, + reset_graph_break_dup_checker, + setup_compile_debug, + to_int_us, + troubleshooting_url, + write_record_to_file, +) +from .variables.torch_function import torch_function_mode_stack_state_mgr + + +np: ModuleType | None +try: + import numpy as np +except ModuleNotFoundError: + np = None + + +if typing.TYPE_CHECKING: + from collections.abc import Callable + + from torch.utils.weak import WeakIdKeyDictionary + + from .backends.registry import CompilerFn + from .package import CompilePackage + from .repro.after_dynamo import WrapBackendDebug + from .types import BytecodeHook, CacheEntry, DynamoFrameType + from .variables.builder import FrameStateSizeEntry + + +log = logging.getLogger(__name__) +bytecode_log = torch._logging.getArtifactLogger(__name__, "bytecode") +graph_break_log = torch._logging.getArtifactLogger(__name__, "graph_breaks") + + +compile_lock = threading.RLock() + +_T = TypeVar("_T") +_P = ParamSpec("_P") + + +class TODO_UNKNOWN: + pass + + +def _clear_fake_mode_weakrefs( + fake_mode: torch._subclasses.fake_tensor.FakeTensorMode | None, +) -> None: + """Clear WeakIdRef entries from a FakeTensorMode's describer.""" + if fake_mode is None: + return + describer = fake_mode.fake_tensor_converter.meta_converter.describer + describer.lookup_tensor.clear() + describer.lookup_storage.clear() + + +def clear_compile_context_weakrefs( + tracer_output: DynamoTracerOutput | None, + compiler_fn: CompilerFn, +) -> None: + """Clear WeakIdRef entries that can block swap_tensors after compile.""" + should_clear = config.invalidate_compile_context_weakrefs + if should_clear is None: + should_clear = _is_registered_backend(innermost_backend(compiler_fn)) + if not should_clear or not tracer_output: + return + # Use output_graph_for_cleanup which is set even on error paths + # (output_graph is None when the compilation errored). + output_graph = tracer_output.output_graph_for_cleanup + if output_graph is None: + return + tc = output_graph.tracing_context + tc.tensor_to_context.clear() + _clear_fake_mode_weakrefs(tc.fake_mode) + if hasattr(output_graph, "_old_fake_mode"): + _clear_fake_mode_weakrefs(output_graph._old_fake_mode) + + +class Tracker: + def __init__(self) -> None: + self.seen: list[ReferenceType[CodeType]] = [] + self.seen_ids: set[int] = set() + + def add(self, strong_obj: CodeType) -> None: + idx = id(strong_obj) + if idx not in self.seen_ids: + obj = weakref.ref(strong_obj, lambda _: self.seen_ids.remove(idx)) + self.seen.append(obj) + self.seen_ids.add(idx) + + def __contains__(self, item: CodeType) -> bool: + return id(item) in self.seen_ids + + def clear(self) -> None: + self.seen.clear() + self.seen_ids.clear() + + +input_codes = Tracker() +output_codes = Tracker() + +initial_global_state: GlobalStateGuard | None = None + + +@functools.wraps(original_forward_from_src) +def fx_forward_from_src_skip_result( + src: str, globals: dict[str, Any], co_fields: dict[str, str] | None = None +) -> FunctionType: + # we monkey patch FX to prevent infinite loop of trying to convert + # our generated code + result = original_forward_from_src(src, globals, co_fields) + skip_code(result.__code__) + return result + + +def log_dynamo_start(code: CodeType, skip: int = 0) -> list[str]: + convert_frame_intern = structured.intern_string(__file__) + captured_tb = CapturedTraceback.extract(skip=4 + skip).summary() + frames_interned = structured.from_traceback(captured_tb) + # Extract and filter the stack + stack = list( + itertools.takewhile( + lambda f: f["filename"] != convert_frame_intern, + frames_interned, + ) + ) + [ + { + "line": code.co_firstlineno, + "name": code.co_name, + "filename": structured.intern_string(code.co_filename), + } + ] + # Initialize the ChromiumEventLogger on start + torch._logging.trace_structured( + "dynamo_start", + lambda: {"stack": stack}, + ) + + # Capture stack separately without using from_traceback to get the actual filenames + stack_strings = [ + f"Line: {frame.lineno}, Name: {frame.name}, Filename: {frame.filename}" + for frame in captured_tb + if frame.filename != convert_frame_intern + ] + [ + f"Line: {code.co_firstlineno}, Name: {code.co_name}, Filename: {code.co_filename}" + ] + return stack_strings + + +def preserve_global_state(fn: Callable[_P, _T]) -> Callable[_P, _T]: + """ + Context manager to: + 1) Save/restore torch.is_grad_enabled() state + 2) Save/restore torch random state + 3) Monkey patch torch.fx.graph_module._forward_from_src + + NOTE: Python random state is preserved in eval_frame_cpp.cpp instead, + so that it wraps more of the compilation pipeline. + """ + + @functools.wraps(fn) + def _fn(*args: _P.args, **kwargs: _P.kwargs) -> _T: + guards = GlobalStateGuard() + prior_grad_mode = torch.is_grad_enabled() + + # Just in case we get left in a bad dispatch state we want to restore + # it. This can happen because the dispatch bits aren't a true + # stack/counter - so we can't just increment/decrement them as we enter + # and leave. + with ( + torch._C._PreserveDispatchKeyGuard(), + maybe_disable_inference_mode(), + maybe_disable_inference_mode_for_fake_prop(), + ): + prior_inference_mode = torch.is_inference_mode_enabled() + prior_deterministic = torch.are_deterministic_algorithms_enabled() + prior_warn_only = torch.is_deterministic_algorithms_warn_only_enabled() + prior_mobile_allocator_state = ( + torch._C._is_default_mobile_cpu_allocator_set() + ) + prior_dtype = torch.get_default_dtype() + torch_rng_state = torch.random.get_rng_state() + cuda_rng_state = None + if torch.cuda.is_available(): + with torch._C.DisableTorchFunction(): + cuda_rng_state = torch.cuda.get_rng_state() + cuda_matmul_fp32_prec = torch._C._get_fp32_precision_getter( + "cuda", "matmul" + ) + prior_fwd_from_src = torch.fx.graph_module._forward_from_src + torch.fx.graph_module._forward_from_src = fx_forward_from_src_skip_result + cleanup = setup_compile_debug() + exit_stack = contextlib.ExitStack() + exit_stack.enter_context( + torch.fx._symbolic_trace._maybe_revert_all_patches() + ) + reset_user_object_tracking() + try: + return fn(*args, **kwargs) + finally: + cleanup.close() + exit_stack.close() + torch._C._set_grad_enabled(prior_grad_mode) + torch.autograd.grad_mode._enter_inference_mode(prior_inference_mode) + torch.use_deterministic_algorithms( + prior_deterministic, warn_only=prior_warn_only + ) + torch.random.set_rng_state(torch_rng_state) + torch.set_default_dtype(prior_dtype) + curr_mobile_allocator_state = ( + torch._C._is_default_mobile_cpu_allocator_set() + ) + if prior_mobile_allocator_state != curr_mobile_allocator_state: + torch._C._unset_default_mobile_cpu_allocator() + if cuda_rng_state is not None: + with torch._C.DisableTorchFunction(): + torch.cuda.set_rng_state(cuda_rng_state) + torch._C._set_fp32_precision_setter( + "cuda", "matmul", cuda_matmul_fp32_prec + ) + torch.fx.graph_module._forward_from_src = prior_fwd_from_src + if not guards.check(): + raise AssertionError( + f"Global {guards.reason()}state changed while dynamo tracing, please report a bug" + ) + + _fn._torchdynamo_orig_backend = fn # type: ignore[attr-defined] + return _fn + + +@TorchPatcher.suppress_torch_distributed_warnings +def has_tensor_in_frame(frame: DynamoFrameType) -> bool: + """Check if the frame has torch.* related bits""" + # Check if the function was decorated using torch._dynamo.optimize + if frame.f_code in always_optimize_code_objects: + return True + + # Check if there is global import of torch.* + for co_name in frame.f_code.co_names: + if co_name in frame.f_globals: + obj = frame.f_globals[co_name] + if isinstance(obj, ModuleType) and ( + obj.__name__.startswith("torch.") or obj is torch + ): + return True + # ... or a global import of numpy.* + if np and config.trace_numpy and (obj is np or is_numpy(obj)): + return True + + seen_ids: dict[int, bool] = {} + + def has_tensor(obj: object) -> bool: + """Recursively check if the obj has a tensor""" + obj_id = id(obj) + if obj_id in seen_ids: + return seen_ids[obj_id] + seen_ids[obj_id] = False + + if isinstance(obj, (torch.Tensor, torch.nn.Module)) or ( + istype(obj, type) and issubclass(obj, torch.nn.Module) + ): + seen_ids[obj_id] = True + return seen_ids[obj_id] + elif ( + config.trace_numpy + and np + and (istype(obj, np.ndarray) or isinstance(obj, np.generic)) + ): + seen_ids[obj_id] = True + return seen_ids[obj_id] + elif istype(obj, (list, tuple)): + seen_ids[obj_id] = any(has_tensor(v) for v in obj) + return seen_ids[obj_id] + elif istype(obj, dict): + # Some packages like pytest can be updated during runtime. So, make a + # copy of values to avoid issues like "RuntimeError: dictionary + # changed size during iteration" + values = list(obj.values()) + seen_ids[obj_id] = any(has_tensor(v) for v in values) + return seen_ids[obj_id] + elif istype(obj, (str, int, float, type(None), bool)): + seen_ids[obj_id] = False + return seen_ids[obj_id] + elif is_namedtuple(obj) and hasattr(obj, "_fields"): + seen_ids[obj_id] = any(has_tensor(getattr(obj, v)) for v in obj._fields) + return seen_ids[obj_id] + else: + # if config.debug: + # print( + # f"Assuming that object of type {type(obj)} does not have a tensor" + # ) + return False + + # Check if the passed arguments are of type Tensor + for value in frame.f_locals.values(): + if has_tensor(value): + return True + + return False + + +def exception_handler( + e: Exception, + code: CodeType, + frame: DynamoFrameType | None = None, + export: bool = False, +) -> None: + record_filename = None + if hasattr(e, "exec_record"): + record_filename = gen_record_file_name(e, code) + write_record_to_file(record_filename, e.exec_record) + e.record_filename = record_filename # type: ignore[attr-defined] + + augment_exc_message(e, export=export) + + +FRAME_COUNTER = 0 +FRAME_COMPILE_COUNTER: typing.Counter[int | FrameStateSizeEntry] = collections.Counter() + + +def maybe_cprofile(func: Callable[_P, _T]) -> Callable[_P, _T]: + if config.cprofile: + return cprofile_wrapper(func) + return func + + +def cprofile_wrapper(func: Callable[_P, _T]) -> Callable[_P, _T]: + @functools.wraps(func) + def profile_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _T: + trace_id = CompileContext.current_trace_id() + if not trace_id: + raise AssertionError("Trace id is None") + profile_path = Path( + os.path.join( + tempfile.gettempdir(), + f"{func.__name__}_{str(trace_id).replace('/', '_')}.profile", + ) + ) + prof = cProfile.Profile() + try: + start_ts = time.time() + # runcall calls prof.enable() and prof.disable(), so do NOT call + # enable outside. This leads to issues like + # ValueError: Another profiling tool is already active + # pyrefly: ignore [bad-argument-type] + retval = prof.runcall(func, *args, **kwargs) + profile_latency = time.time() - start_ts + except ValueError: + log.exception("failed to enable cProfile") + profile_latency = 0 + retval = func(*args, **kwargs) + log.warning( + "### Cprofile for %s trace id [%s] took %.3f seconds ###", + func.__name__, + trace_id, + profile_latency, + ) + ps = pstats.Stats(prof) + try: + prof.dump_stats(profile_path) + except OSError: + log.exception("Cannot write to %s", profile_path) + log.warning("Raw profile at %s", profile_path) + svg_path = profile_path.with_suffix(".svg") + try: + with subprocess.Popen( + [ + "gprof2dot", + "-f", + "pstats", + "--node-label=total-time-percentage", + "--node-label=self-time-percentage", + "--node-label=total-time", + str(profile_path), + ], + stdout=subprocess.PIPE, + ) as gprof2dot_process: + subprocess.check_call( + ["dot", "-Tsvg", "-o", str(svg_path)], + stdin=gprof2dot_process.stdout, + ) + log.warning("Generated SVG from profile at %s", svg_path) + except FileNotFoundError: + log.warning( + "Failed to generate SVG from profile -- dumping stats instead." + "Try installing gprof2dot and dot for a better visualization" + ) + ps.sort_stats(pstats.SortKey.TIME).print_stats(20) + ps.sort_stats(pstats.SortKey.CUMULATIVE).print_stats(20) + + if manifold_link := maybe_upload_prof_stats_to_manifold( + str(profile_path) + ): # fb-only + torch._logging.trace_structured( + "link", + lambda: {"name": "cprofile_manifold_url", "url": manifold_link}, + ) + return retval + + return profile_wrapper + + +@dataclass +class ConvertFrameBox: + error_on_graph_break: bool | None = None + + +def get_compile_id( + frame_state: dict[str, int | FrameStateSizeEntry], +) -> CompileId: + global FRAME_COUNTER + if "_id" not in frame_state: + frame_state["_id"] = FRAME_COUNTER + FRAME_COUNTER += 1 + frame_id = frame_state["_id"] + if not isinstance(frame_id, int): + raise AssertionError(f"frame_id must be an int, got {type(frame_id)}") + + frame_compile_id = FRAME_COMPILE_COUNTER[frame_id] + FRAME_COMPILE_COUNTER[frame_id] += 1 + + compiled_autograd_id = None + if prior := CompileContext.current_compile_id(): + compiled_autograd_id = prior.compiled_autograd_id + return CompileId( + compiled_autograd_id=compiled_autograd_id, + frame_id=frame_id, + frame_compile_id=frame_compile_id, + ) + + +class ConvertFrameAssert: + def __init__( + self, + compiler_fn: CompilerFn, + one_graph: bool = True, + export: bool = False, + export_constraints: Any | None = None, + package: CompilePackage | None = None, + recompile_limit: int | None = None, + ) -> None: + # assert export_constraints is None + reset_graph_break_dup_checker() + self._torchdynamo_orig_backend = compiler_fn + self._one_graph = one_graph + self._export = export + self._export_constraints = export_constraints + self._package = package + self._recompile_limit = recompile_limit + self._box = ConvertFrameBox() + + @property + def _clone_with_backend(self) -> Callable[[CompilerFn], ConvertFrameAssert]: + return lambda backend: convert_frame_assert( + backend, + self._one_graph, + self._export, + self._export_constraints, + recompile_limit=self._recompile_limit, + ) + + def __call__( + self, + frame: DynamoFrameType, + cache_entry: CacheEntry | None, + hooks: Hooks, + frame_state: dict[str, int | FrameStateSizeEntry], + *, + skip: int = 0, + ) -> ConvertFrameReturn: + increment_frame() + code = frame.f_code + + isolate_recompiles_id = get_eval_frame_isolate_recompiles_id() + cache_entries = _get_cache_entries_for_region(code, isolate_recompiles_id) + # For recompile-reason logging: lookup() also checks the default (-1) + # bucket for isolated regions, so include those entries here to avoid + # dropping their guard-failure reasons. + if isolate_recompiles_id >= 0: + cache_entries_for_reasons = cache_entries + _get_cache_entries_for_region( + code, -1 + ) + else: + cache_entries_for_reasons = cache_entries + total_count = _get_total_cache_entry_count(code) + cache_size = compute_cache_size(frame, cache_entries, total_count) + input_codes.add(code) + if code in output_codes: + return ConvertFrameReturn( + skip_reason="frame is already Dynamo-generated code" + ) + if ( + os.environ.get("TORCHDYNAMO_DEBUG_FUNCTION") + and os.environ.get("TORCHDYNAMO_DEBUG_FUNCTION") != code.co_name + ): + return ConvertFrameReturn( + skip_reason="function name does not match TORCHDYNAMO_DEBUG_FUNCTION filter" + ) + if code.co_name == "" and code.co_filename.endswith( + ( + "transformers/file_utils.py", + "transformers/utils/generic.py", + "diffusers/utils/outputs.py", + ) + ): + # not needed, but cleans up torchbench error stats + return ConvertFrameReturn( + skip_reason="skipping generator expression in transformers/diffusers" + ) + if code.co_name == "__setattr__": + return ConvertFrameReturn(skip_reason="__setattr__ frames are not compiled") + if code.co_name == "__init__" and code.co_filename.startswith( + os.path.dirname(torch.optim.__file__) + ): + return ConvertFrameReturn( + skip_reason="torch.optim __init__ frames are not compiled" + ) + + # Check if the frame is generated by an exec builtin call + # TODO - Running exec generated frame seems propagates f_globals to the + # next frames. + if code.co_name == "" and code.co_filename == "": + return ConvertFrameReturn(skip_reason="frame was generated by exec()") + + if ( + code.co_name == "" + and code.co_filename == "" + and not bool(frame.f_builtins) + ): + # namedtuple subclass constructor. Empty builtins cause issue with + # len keyword in LIST_LEN guard. + return ConvertFrameReturn(skip_reason="frame is a namedtuple constructor") + + if is_generator(code): + unimplemented( + gb_type="Attempt to trace generator", + context="", + explanation="Generators cannot be compiled directly with `torch.compile`.", + hints=[ + "Call a generator from inside of a non-generator Python function and " + "compile that function instead.", + *graph_break_hints.FUNDAMENTAL, + ], + ) + + if not has_tensor_in_frame(frame): + return ConvertFrameReturn( + skip_reason="no tensor-related objects found in frame" + ) + + # skip tracing non-recursive disabled functions + # detect if the previous frame (non-convert_frame) is a non-recursive disable wrapper + prev_frame = sys._getframe() + # pyrefly: ignore [bad-assignment] + while ( + prev_frame + and "torch/_dynamo/convert_frame.py" in prev_frame.f_code.co_filename + ): + prev_frame = prev_frame.f_back # type: ignore[assignment] + if ( + prev_frame + and prev_frame.f_code is decorators._nonrecursive_disable_wrapper_code + ): + return ConvertFrameReturn( + apply_to_code=False, + skip_reason="tracing is non-recursively disabled for this frame", + ) + + global initial_global_state + # Save the previous initial_global_state to handle nested compilations + # (e.g., compiled autograd running during graph execution can trigger + # nested compilations that would otherwise overwrite the outer state) + prev_initial_global_state = initial_global_state + initial_global_state = GlobalStateGuard() + + compile_id = get_compile_id(frame_state) + frame_id = compile_id.frame_id + + signpost_event( + "dynamo", + "_convert_frame_assert._compile", + { + "co_name": code.co_name, + "frame_id": frame_id, + "compile_id": str(compile_id), + "co_filename": code.co_filename, + "co_firstlineno": code.co_firstlineno, + "cache_size": cache_size.num_cache_entries_with_same_id_matched_objs, + "accumulated_cache_size": cache_size.num_cache_entries, + }, + ) + + # Record traced frames, skipping Dynamo generated ones. + if not code.co_name.startswith(TORCH_DYNAMO_RESUME_IN_PREFIX): + info = f"{code.co_name} {code.co_filename}:{code.co_firstlineno}" + dynamo_tls.traced_frame_infos.append(info) + + try: + compile_ctx = compile_context(CompileContext(compile_id)) + # When recompile_limit is set, temporarily override the global + # config so the existing exceeds_recompile_limit check uses it. + recompile_ctx = ( + config.patch(recompile_limit=self._recompile_limit) + if self._recompile_limit is not None + else contextlib.nullcontext() + ) + with compile_ctx, recompile_ctx: + result = _compile( + frame.f_code, + frame.f_globals, + frame.f_locals, + frame.f_builtins, + frame.closure, + self._torchdynamo_orig_backend, + self._one_graph, + self._export, + self._export_constraints, + hooks, + cache_entry, + cache_entries, + cache_entries_for_reasons, + cache_size, + frame, + frame_state=frame_state, + compile_id=compile_id, + skip=skip + 1, + package=self._package, + convert_frame_box=self._box, + ) + finally: + # Restore the previous initial_global_state for nested compilation handling + initial_global_state = prev_initial_global_state + + if config.caching_precompile and self._package is not None: + from .package import DynamoCache + + # Record that the dynamo package has changed + DynamoCache.record_package(self._package) + return result + + +def convert_frame_assert( + compiler_fn: CompilerFn, + one_graph: bool = True, + export: bool = False, + export_constraints: Any | None = None, + package: CompilePackage | None = None, + recompile_limit: int | None = None, +) -> ConvertFrameAssert: + """Fully convert a frame into an FX graph, raising an exception if we fail.""" + return ConvertFrameAssert( + compiler_fn, + one_graph, + export, + export_constraints, + package, + recompile_limit, + ) + + +from collections import OrderedDict + +from torch.utils.hooks import RemovableHandle + + +# we have to use `OrderedDict` to make `RemovableHandle` work. +_bytecode_hooks: dict[int, BytecodeHook] = OrderedDict() +_BYTECODE_HOOK_SIDE_EFFECTS_CONTEXT_KEY = "bytecode_hook_side_effects" + + +def get_compiled_code_side_effects( + code: types.CodeType, +) -> tuple[str, ...] | None: + """Return Dynamo's replayed Python side-effect sources for compiled code. + + Returns ``None`` when ``code`` was not produced by Dynamo or no metadata was + attached to it. + """ + if not code_context.has_context(code): + return None + side_effects = code_context.get_context(code).get( + _BYTECODE_HOOK_SIDE_EFFECTS_CONTEXT_KEY + ) + if side_effects is None: + return None + return side_effects + + +def compiled_code_has_side_effects(code: types.CodeType) -> bool: + """Return whether Dynamo recorded replayed Python side effects for compiled code.""" + return bool(get_compiled_code_side_effects(code)) + + +def _copy_code_context(src_code: types.CodeType, dst_code: types.CodeType) -> None: + if not code_context.has_context(src_code): + return + src_context = code_context.get_context(src_code) + if _BYTECODE_HOOK_SIDE_EFFECTS_CONTEXT_KEY in src_context: + code_context.get_context(dst_code)[_BYTECODE_HOOK_SIDE_EFFECTS_CONTEXT_KEY] = ( + src_context[_BYTECODE_HOOK_SIDE_EFFECTS_CONTEXT_KEY] + ) + + +def register_bytecode_hook(hook: BytecodeHook) -> RemovableHandle: + """Register hooks for bytecode generated by Dynamo. The hook can do some + logging, as well as return a new code object to be used. Hooks can query + `get_compiled_code_side_effects(new_code)` for replayed Python side effect + sources. Please refer to `BytecodeHook` for the hook signature. + """ + handle = RemovableHandle(_bytecode_hooks) + _bytecode_hooks[handle.id] = hook + return handle + + +# TODO - We want to run preserve_node_meta context manager here, but the CI +# fails (its unclear if the failures were flaky) +# @torch.fx.traceback.preserve_node_meta() +@preserve_global_state +def trace_frame( + code: types.CodeType, + globals: dict[str, object], + locals: dict[str, object], + builtins: dict[str, object], + closure: tuple[CellType], + compiler_fn: CompilerFn, + tf_mode_stack: list[torch.overrides.TorchFunctionMode], + one_graph: bool, + speculation_log: SpeculationLog, + instructions: list[Instruction], + code_options: CodeOptions, + *, + export: bool = False, + export_constraints: Any | None = None, + frame_state: dict[str, int | FrameStateSizeEntry] | None = None, + distributed_state: DistributedState | None = None, + package: CompilePackage | None = None, +) -> DynamoTracerOutput: + from torch.fx.experimental.validator import bisect, translation_validation_enabled + + if ( + torch.cuda.is_available() + and hasattr(torch._C, "_cuda_isCurrentStreamCapturing") + and not isinstance(torch._C._cuda_isCurrentStreamCapturing, type) + and torch.cuda.is_current_stream_capturing() + and not _in_hop_compile() + ): + raise exc.TorchRuntimeError( + "torch.compile cannot JIT compile during CUDA graph capture. " + "Execute warmup iterations outside of CUDA graph capture to trigger " + "compilation, then capture the graph after compilation has completed." + ) + + speculation_log.restart() # type: ignore[has-type] + exn_vt_stack = ExceptionStack() + tracer = InstructionTranslator( + instructions, + code, + locals, + globals, + builtins, + closure, + tf_mode_stack, + code_options, + compiler_fn, + one_graph, + export, + export_constraints, + frame_state=frame_state, + speculation_log=speculation_log, # type: ignore[has-type] + exn_vt_stack=exn_vt_stack, + distributed_state=distributed_state, # type: ignore[has-type] + package=package, + ) + + def run_tracer() -> None: + try: + tracer.output.mark_bytecode_tracing_start() + with tracing(tracer.output.tracing_context), tracer.set_current_tx(): + tracer.run() + except exc.UnspecializeRestartAnalysis: + speculation_log.clear() # type: ignore[has-type] + raise + except ( + exc.SpeculationRestartAnalysis, + exc.TensorifyScalarRestartAnalysis, + exc.SkipFrame, + ): + raise + except Exception: + if translation_validation_enabled(): + bisect(tracer.output.shape_env) + raise + finally: + tracer.output.call_cleanup_hooks() + tracer.f_locals = {} + + try: + run_tracer() + tracer_output = DynamoTracerOutput(tracer) + output = tracer_output.output_graph + if output is None: + raise AssertionError("tracer output_graph must not be None") + if not output.output_instructions: + raise AssertionError("output_graph must have output_instructions") + instructions[:] = output.output_instructions + code_options.update(output.code_options) + propagate_inst_exn_table_entries(instructions) + check_inst_exn_tab_entries_valid(instructions) + instructions[:] = remove_pointless_jumps(remove_dead_code(instructions)) + except Exception as e: + e._torch_dynamo_tracer_output = DynamoTracerOutput(tracer, error=True) # type: ignore[attr-defined] + raise + return tracer_output + + +@dataclass +class DynamoOutput: + """ + Represents the core data returned from a single dynamo run, including: + - Guards, wrapped inside tracer_output.output_graph.guards + - Generated bytecode + - Other information needed for compilation. + This data structure should capture all the "interesting" information dynamo + produces on the frontend side before it enters user backend. + """ + + tracer_output: DynamoTracerOutput + bytecode: types.CodeType + pycode: list[list[str] | None] + last_attempt_start_time: float | None + + def build_guards( + self, + code: types.CodeType, + hooks: Hooks | None = None, + save: bool = False, + cache_entries: list[CacheEntry] | None = None, + strict_error: bool = False, + ) -> CheckFunctionManager: + output_graph = self.tracer_output.output_graph + if output_graph is None: + raise AssertionError("output_graph must not be None when building guards") + return CheckFunctionManager( + code, + output_graph, + cache_entries, + hooks.guard_fail_fn if hooks else None, + hooks.guard_filter_fn if hooks else None, + save_guards=save, + strict_error=strict_error, + ) + + def graph_capture_output( + self, + argdefs: tuple[Any, ...] | None = None, + kwdefaults: dict[str, Any] | None = None, + ) -> GraphCaptureOutput: + output_graph = self.tracer_output.output_graph + if output_graph is None: + raise AssertionError( + "output_graph must not be None when producing graph capture output" + ) + return GraphCaptureOutput( + OutputGraphCommon( + output_graph.dump_guards_state(), + output_graph.import_sources, + output_graph.shape_env, + output_graph.export_metadata, + output_graph.tracked_fakes_id_to_source, + ), + output_graph.import_sources, + output_graph.traced_code, + self.bytecode, + self.pycode, + self.tracer_output.closure, + argdefs, + kwdefaults, + self.tracer_output.f_globals, + ) + + +@dataclass +class BackendInput: + """ + Represents core data structure that dynamo will pass to a backend, including: + - Graph module + - Example inputs + - The FakeTensorMode used for compiling graph. + This data structure should capture all the information dynamo produces + on for the user backend. + """ + + backend_id: str + graph_module: torch.fx.GraphModule + example_inputs: Any + fake_mode: torch._subclasses.fake_tensor.FakeTensorMode + tensor_to_context: WeakIdKeyDictionary + + +@dataclass(frozen=True) +class GraphRuntimeEnv: + bytecode: types.CodeType + pycode: list[list[str] | None] + import_sources: dict[str, str] + used_globals: dict[str, Any] + closure: tuple[Any, ...] | None + argdefs: tuple[Any, ...] | None + kwdefaults: dict[str, Any] | None = None + external_refs: set[str] = dataclasses.field(default_factory=set) + + def forward_callable( + self, + backend_id: str, + compiled_fn: Callable[..., Any], + *, + extra_globals: dict[str, Any] | None = None, + use_python_codegen: bool = False, + ) -> Callable[..., Any]: + import_sources = { + alias: importlib.import_module(module_name) + for alias, module_name in self.import_sources.items() + } + f_globals = { + **import_sources, + **self.used_globals, + **(extra_globals or {}), + backend_id: compiled_fn, + } + + # check that all external references are available + self._check_external_refs(f_globals) + + if use_python_codegen: + bytecode = self._build_python_wrapper(f_globals, backend_id) + else: + bytecode = self.bytecode + + fn = types.FunctionType( + bytecode, + f_globals, + closure=self.closure, + argdefs=self.argdefs, + ) + if self.kwdefaults: + fn.__kwdefaults__ = self.kwdefaults + return fn + + def _build_python_wrapper_source(self) -> str: + """Build Python source for the wrapper function from generated pycode.""" + pycode_parts = [p for p in self.pycode if p is not None] + if not pycode_parts: + raise RuntimeError("No Python code generated from Dynamo.") + orig_code = self.bytecode + argcount = orig_code.co_argcount + varnames = orig_code.co_varnames[:argcount] + argnames = ", ".join(varnames) + + func_lines = ["def __generate_func__():"] + func_lines.append(f" def __dynamo_func__({argnames}):") + for part in pycode_parts: + for line in part: + func_lines.append(f" {line}") + func_lines.append(" return __ret") + func_lines.append(" return __dynamo_func__") + func_lines.append("__dynamo_generated_func__ = __generate_func__()") + return "\n".join(func_lines) + + def _build_python_wrapper( + self, f_globals: dict[str, Any], backend_id: str + ) -> types.CodeType: + """Build a Python code object from the generated pycode strings.""" + func_source = self._build_python_wrapper_source() + # Execute to get the function, then extract its code + namespace: dict[str, Any] = f_globals.copy() + # exec() should be fine because we only define a function in the scope + # without actually running the code inside the function, so in theory + # it should be safe. + exec(func_source, namespace) + func = namespace["__dynamo_generated_func__"] + return func.__code__ + + def _check_external_refs(self, f_globals: dict[str, Any]) -> None: + # pyrefly: ignore [implicit-any] + missing_refs = [] + for ref in self.external_refs: + if ref not in f_globals: + missing_refs.append(ref) + + if missing_refs: + raise RuntimeError( + f"Missing required external references: {missing_refs}. " + "Please load AOT compiled function with `f_globals=`" + ) + + +def _safe_builtins_dict(builtins_dict: dict[str, Any]) -> dict[str, Any]: + """Filter a builtins dict to only picklable entries for serialization.""" + import pickle + + result = {} + for k, v in builtins_dict.items(): + try: + pickle.dumps(v) + result[k] = v + except Exception: + pass + return result + + +@dataclass +class GraphCaptureOutput: + """ + Minimal version of DynamoOutput + """ + + output_graph: OutputGraphCommon + import_sources: dict[str, str] + traced_code: list[CodeType] + bytecode: CodeType + pycode: list[list[str] | None] + closure: tuple[Any, ...] | None + argdefs: tuple[Any, ...] | None + kwdefaults: dict[str, Any] | None + f_globals: dict[str, Any] + + def build_guards( + self, + code: types.CodeType, + hooks: Hooks | None = None, + save: bool = False, + cache_entries: list[CacheEntry] | None = None, + strict_error: bool = False, + ) -> CheckFunctionManager: + return CheckFunctionManager( + code, + self.output_graph, + cache_entries, + hooks.guard_fail_fn if hooks else None, + hooks.guard_filter_fn if hooks else None, + save_guards=save, + strict_error=strict_error, + ) + + def get_runtime_env(self) -> GraphRuntimeEnv: + from torch._dynamo.source import get_global_source_name + + used_globals = {} + for ( + source + ) in self.output_graph.export_metadata.graph_input_idx_to_local_source.values(): + global_name = get_global_source_name(source) + if global_name is None: + continue + if global_name in self.f_globals: + used_globals[global_name] = self.f_globals[global_name] + + # Scan bytecode for all external references + external_refs = self._get_external_refs(self.bytecode) + + # Best-effort serialization of builtins referenced by the bytecode. + # Similar to how guards prune __builtins_dict__ to only used entries. + import builtins as _builtins + + for ref in external_refs: + if ref not in used_globals: + if ref.startswith("__builtins_dict__") and ref in self.f_globals: + used_globals[ref] = _safe_builtins_dict(self.f_globals[ref]) + elif hasattr(_builtins, ref): + used_globals[ref] = getattr(_builtins, ref) + + return GraphRuntimeEnv( + bytecode=self.bytecode, + pycode=self.pycode, + import_sources=self.import_sources, + used_globals=used_globals, + closure=self.closure, + argdefs=self.argdefs, + kwdefaults=self.kwdefaults, + external_refs=external_refs, + ) + + @staticmethod + def _get_external_refs(bytecode: types.CodeType) -> set[str]: + import dis + + external_refs: set[str] = set() + + # Get all instructions from the bytecode + for instruction in dis.get_instructions(bytecode): + # LOAD_GLOBAL loads a global variable or a builtin + if instruction.opname == "LOAD_GLOBAL": + if instruction.argval: + external_refs.add(instruction.argval) + # LOAD_NAME loads a name (used in module-level code, less common in functions) + elif instruction.opname == "LOAD_NAME": + if instruction.argval: + external_refs.add(instruction.argval) + + return external_refs + + +@dataclass +class CaptureOutput: + """ + CaptureOutput should represent all the information produced from torch + compiler for a single graph capture. This intends to be consumed by + various compiler frontends so that we can share as much compiler internals + as possible and avoid great divergence between different stacks. + This data structure should eventually contain all the information compiler + produces as more refactors happens to converge different compiler + frontends. + """ + + graph_capture_output: GraphCaptureOutput + # BackendInput can be None when dynamo didn't compile any graph (no tensor op) + backend_input: BackendInput | None + + def forward_callable( + self, + *, + compiled_fn: Callable[..., Any] | None = None, + extra_globals: dict[str, Any] | None = None, + use_python_codegen: bool = False, + ) -> Callable[..., Any]: + runtime_env = self.graph_capture_output.get_runtime_env() + if self.backend_input is None: + raise AssertionError("backend_input must not be None") + backend_id = self.backend_input.backend_id + compiled_fn = compiled_fn or self.backend_input.graph_module + return runtime_env.forward_callable( + backend_id, + compiled_fn, + extra_globals=extra_globals, + use_python_codegen=use_python_codegen, + ) + + +def get_traced_fn(mod: Any) -> tuple[FunctionType, object | None]: + """ + Utility function to get the function to trace, and optionally a bound self + object, from a callable (nn.Module, function, or method). + """ + import inspect + + if isinstance(mod, torch.nn.Module): + resolved_forward = mod.forward + if hasattr(resolved_forward, "__self__"): + # pyrefly: ignore [missing-attribute] + resolved_forward = resolved_forward.__func__ + + resolved_call = mod.__call__ + if hasattr(resolved_call, "__self__"): + resolved_call = resolved_call.__func__ + + # Mirrored from NNModuleVariable.call_function: + # https://github.com/pytorch/pytorch/blob/main/torch/_dynamo/variables/nn_module.py#L1035 + if ( + len(mod._forward_pre_hooks) == 0 + and len(mod._forward_hooks) == 0 + and len(torch.nn.modules.module._global_forward_pre_hooks) == 0 + and len(torch.nn.modules.module._global_forward_hooks) == 0 + and len(mod._backward_pre_hooks) == 0 + and len(mod._backward_hooks) == 0 + and len(torch.nn.modules.module._global_backward_pre_hooks) == 0 + and len(torch.nn.modules.module._global_backward_hooks) == 0 + and resolved_forward != torch.nn.Module.forward # has forward impl + and resolved_call == torch.nn.Module.__call__ # no custom __call__ impl + ): + # We cannot trace __call__ by default because it will break + # the legacy dynamo export. If we want to revisit this, + # feel free to remove this path and try unittests in + # test_strict_export_v2.py + mod = mod.forward + elif isinstance(mod, torch.fx.GraphModule): + mod = mod._call_impl + else: + mod = mod.__call__ + + if hasattr(mod, "__self__"): + return mod.__func__, mod.__self__ + elif inspect.isfunction(mod): + return mod, None + else: + raise RuntimeError(f"Unsupported model code type {mod}") + + +def _get_signature(fn: Any) -> inspect.Signature: + return inspect.signature(fn, follow_wrapped=False) + + +def _get_frame( + mod: Any, + args: tuple[Any, ...], + kwargs: dict[str, Any] | None = None, +) -> FrameInfo: + """ + Create a frame to trace, given a model, args, and optional kwargs. + """ + import builtins + + fn, self_opt = get_traced_fn(mod) + if self_opt is not None: + args = (self_opt,) + args + if kwargs is None: + kwargs = {} + + signature = _get_signature(fn) + bound_arguments = signature.bind(*args, **kwargs) + bound_arguments.apply_defaults() + f_locals = bound_arguments.arguments + + closure = fn.__closure__ or () + freevars = fn.__code__.co_freevars + if freevars or closure: + if len(closure) != len(freevars): + raise AssertionError( + f"closure length ({len(closure)}) must match freevars length ({len(freevars)})" + ) + f_locals.update( + {name: cell.cell_contents for name, cell in zip(freevars, closure)} + ) + + return FrameInfo( + fn.__code__, + fn.__globals__, + f_locals, + builtins.__dict__, + closure=fn.__closure__ or (), # type: ignore[arg-type] + argdefs=fn.__defaults__, + kwdefaults=fn.__kwdefaults__, + ) + + +def fullgraph_capture( + mod: Any, + args: tuple[Any, ...], + kwargs: dict[str, Any] | None = None, + *, + constraints: list[Constraint] | None = None, + _is_export_deprecated_do_not_use: bool = False, +) -> CaptureOutput: + """ + This API captures a full graph for a model, given example inputs to trace with. + + Specifically, it takes a callable (nn.Module, method, or function), args, and + optional kwargs, and returns Dynamo-captured graph along with other important + compile-time information. This serves as the common graph-capture mechanism + for different torch compiler AOT frontends (e.g. AOT precompile, export). + + Note that this API doesn't apply context managers like metrics context, + and the expectation is that the caller will apply them depending + on the use case. + + The CaptureOutput is separated into two parts: + 1. Frontend specific information, which includes: + - guards + - generated bytecode + - other information tracked by OutputGraphCommon. + 2. Backend specific information (indexed by unique backend id) such as: + - fx graph + - example inputs + """ + frame = _get_frame(mod, args, kwargs) + + with compile_context(CompileContext(get_compile_id({}))): + return _fullgraph_capture_frame( + frame, + constraints=constraints, + _is_export_deprecated_do_not_use=_is_export_deprecated_do_not_use, + ) + + +@dataclass +class FrameInfo: + code: types.CodeType + globals: dict[str, object] + locals: dict[str, object] + builtins: dict[str, object] + closure: tuple[CellType] + argdefs: tuple[Any, ...] | None + kwdefaults: dict[str, Any] | None + + +def _fullgraph_capture_frame( + frame: FrameInfo, + *, + constraints: list[Constraint] | None = None, + _is_export_deprecated_do_not_use: bool = False, +) -> CaptureOutput: + from torch._guards import TracingContext + + backend_input: BackendInput | None = None + + def fullgraph_compiler( + gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] + ) -> torch.fx.GraphModule: + nonlocal backend_input + tracing_context = TracingContext.get() + fake_mode = tracing_context.fake_mode + tensor_to_context = tracing_context.tensor_to_context + if fake_mode is None: + raise AssertionError("fake_mode must not be None") + if not isinstance(gm.meta["backend_id"], str): + raise AssertionError( + f"gm.meta['backend_id'] must be a str, got {type(gm.meta['backend_id'])}" + ) + backend_input = BackendInput( + gm.meta["backend_id"], gm, example_inputs, fake_mode, tensor_to_context + ) + return gm + + try: + # TODO with torch._dynamo.config.patch(generate_pycode=True): + dynamo_output = compile_frame( + frame.code, + frame.globals, + frame.locals, + frame.builtins, + frame.closure, + compiler_fn=fullgraph_compiler, + export=_is_export_deprecated_do_not_use, + export_constraints=constraints, # type: ignore[arg-type] + one_graph=True, + restart_reasons=set(), + ) + # https://github.com/pytorch/pytorch/blob/main/torch/_dynamo/eval_frame.py#L831 + except (Unsupported, UncapturedHigherOrderOpError, UserError) as e: + augment_exc_message(e) + if config.verbose: + raise + # strip internal tracebacks from causes + cur_exn: BaseException = e + while cur_exn.__cause__ is not None: + cur_exn.__cause__.with_traceback(None) + cur_exn = cur_exn.__cause__ + + raise e.with_traceback(None) from e.__cause__ # User compiler error + + return CaptureOutput( + dynamo_output.graph_capture_output(frame.argdefs, frame.kwdefaults), + backend_input, + ) + + +# Called by eval_frame_cpp.cpp in order to raise an error if Dynamo attempts to compile_frame +def get_fail_callback(callback: ConvertFrameProtocol) -> ConvertFrameProtocol: + fail_callback = getattr(callback, "_dynamo_fail_callback", None) + if fail_callback is not None: + return fail_callback + + def compile_frame_error(*args: Any, **kwargs: Any) -> NoReturn: + raise RuntimeError( + "Dynamo: expected not to compile nested code - this happens because " + "a Dynamo callback was triggered and succeeded in compiling " + "when running fullgraph=True compiled code." + ) + + def fail_callback(*args: Any, **kwargs: Any) -> ConvertFrameReturn: + with mock.patch(__name__ + ".compile_frame", compile_frame_error): + return callback(*args, **kwargs) + + # pyrefly: ignore [missing-attribute] + callback._dynamo_fail_callback = fail_callback + return fail_callback + + +def compile_frame( # type: ignore[return] + code: types.CodeType, + globals: dict[str, object], + locals: dict[str, object], + builtins: dict[str, object], + closure: tuple[CellType], + compiler_fn: CompilerFn, + one_graph: bool, + restart_reasons: set[str], + *, + export: bool = False, + export_constraints: Any | None = None, + frame_state: dict[str, int | FrameStateSizeEntry] | None = None, + distributed_state: DistributedState | None = None, + package: CompilePackage | None = None, + # pyrefly: ignore [bad-return] +) -> DynamoOutput: + """ + A helper function taking a frame and backend, then return the generated bytecode + and guards as a common data structure. + This is a shared interface for multiple compiler frontends (e.g. torch.compile, + torch.export) that needs to capture a graph out of python code. + """ + # This is shared across restarts + speculation_log = SpeculationLog() + + def transform( + instructions: list[Instruction], code_options: dict[str, Any] + ) -> DynamoTracerOutput: + tf_mode_stack: list[torch.overrides.TorchFunctionMode] = list( + torch_function_mode_stack_state_mgr.stack + ) + tracer_output = trace_frame( + code, + globals, + locals, + builtins, + closure, + compiler_fn, + tf_mode_stack, + one_graph, + speculation_log, + instructions, + cast(CodeOptions, code_options), + export=export, + export_constraints=export_constraints, + frame_state=frame_state, + distributed_state=distributed_state, + package=package, + ) + + if tracer_output is None: + raise AssertionError("tracer_output must not be None after transform") + return tracer_output + + last_attempt_start_time = None + for attempt in itertools.count(): + CompileContext.get().attempt = attempt + + try: + with dynamo_timed(f"compile_attempt_{attempt}", log_pt2_compile_event=True): + bytecode, tracer_output = transform_code_object(code, transform) + if tracer_output is None: + raise AssertionError( + "tracer_output must not be None after transform_code_object" + ) + if tracer_output.output_graph is None: + raise AssertionError( + "tracer_output.output_graph must not be None after transform_code_object" + ) + return DynamoOutput( + tracer_output=tracer_output, + bytecode=bytecode, + pycode=tracer_output.output_graph.output_pycode, + last_attempt_start_time=last_attempt_start_time, + ) + except exc.RestartAnalysis as e: + if not isinstance(e, exc.TensorifyScalarRestartAnalysis): + TensorifyState.clear() + log.info( + "Restarting analysis due to %s", + LazyString(format_traceback_short, e.__traceback__), + ) + # Clean up the failed tracer output's graph to break reference cycles + failed_tracer_output = getattr(e, "_torch_dynamo_tracer_output", None) + if failed_tracer_output: + failed_tracer_output._cleanup_output_graph() + # If restart reason is None just log the type of the exception + restart_reasons.add(e.restart_reason or str(type(e))) + # We now have a new "last attempt", reset the clock + last_attempt_start_time = time.time() + if attempt > 100: + unimplemented( + gb_type="Excessive RestartAnalysis() calls", + context="", + explanation="Dynamo attempted to trace the same frame 100+ times. " + "Giving up on compiling as the compile time tradeoff is likely not " + "worth the performance gain.", + hints=[], + ) + except exc.SkipFrame as e: + if not isinstance(e, exc.TensorifyScalarRestartAnalysis): + TensorifyState.clear() + # Clean up the failed tracer output's graph to break reference cycles + failed_tracer_output = getattr(e, "_torch_dynamo_tracer_output", None) + if failed_tracer_output: + failed_tracer_output._cleanup_output_graph() + raise + + +def _compile( + code: CodeType, + globals: dict[str, object], + locals: dict[str, object], + builtins: dict[str, object], + closure: tuple[CellType], + compiler_fn: CompilerFn, + one_graph: bool, + export: bool, + export_constraints: Any | None, + hooks: Hooks, + cache_entry: CacheEntry | None, + cache_entries: list[CacheEntry], + cache_entries_for_reasons: list[CacheEntry], + cache_size: CacheSizeRelevantForFrame, + frame: DynamoFrameType | None = None, + frame_state: dict[str, int | FrameStateSizeEntry] | None = None, + *, + compile_id: CompileId, + skip: int = 0, + package: CompilePackage | None = None, + # Can be used to record things for the caller, both + # in the case of normal and exception code paths + convert_frame_box: ConvertFrameBox | None = None, +) -> ConvertFrameReturn: + from torch.fx.experimental.validator import ( + BisectValidationException, + ValidationException, + ) + + # Only nonlocal defs here please! + # Time spent compiling this frame before restarting or failing analysis + dynamo_time_before_restart: float = 0.0 + + @compile_time_strobelight_meta(phase_name="compile_inner") + def compile_inner( + code: CodeType, one_graph: bool, hooks: Hooks + ) -> tuple[ConvertFrameReturn, DynamoTracerOutput | None]: + with contextlib.ExitStack() as stack: + # Hold _is_compiling_flag True for the duration of compilation so + # torch.compiler.is_compiling() is observable in code that runs + # during the compile session but is not directly Dynamo-traced + # (wrapper-subclass __torch_dispatch__ invoked by AOTAutograd, + # make_fx invoked from a custom backend, etc.). Export sets the + # flag itself via _compiling_state_context, so skip there. + if not export: + stack.enter_context(torch.compiler._compile_session_context()) + stack.enter_context( + torch._dynamo.callback_handler.install_callbacks( + CallbackTrigger.DYNAMO, str(CompileContext.current_compile_id()) + ) + ) + stack.enter_context(CompileTimeInstructionCounter.record()) + stack.enter_context(torch_function_mode_stack_state_mgr) + result = _compile_inner(code, one_graph, hooks) + if torch._C._len_torch_function_stack() != 0: + raise AssertionError( + "Torch function mode stack state changed while dynamo tracing, please report a bug" + ) + return result + + return ( + ConvertFrameReturn(), + None, + ) # dead, but see https://github.com/python/mypy/issues/7577 + + @maybe_cprofile + def _compile_inner( + code: CodeType, + one_graph: bool, + hooks: Hooks, + ) -> tuple[ConvertFrameReturn, DynamoTracerOutput]: + nonlocal dynamo_time_before_restart + last_attempt_start_time = start_time = time.time() + + def log_bytecode( + prefix: str, name: str, filename: str, line_no: int, code: CodeType + ) -> None: + if bytecode_log.isEnabledFor(logging.DEBUG): + bytecode_log.debug( + format_bytecode(prefix, name, filename, line_no, code) + ) + + log_bytecode( + "ORIGINAL BYTECODE", + code.co_name, + code.co_filename, + code.co_firstlineno, + code, + ) + # Dump the ORIGINAL bytecode of resumption frame into TORCH_TRACE + # log file, so that it is parsed by tlparse tool. + is_resumption_frame = "torch_dynamo_resume_in" in code.co_name + if is_resumption_frame: + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": code.co_name + "_ORIGINAL_BYTECODE", + "encoding": "string", + }, + payload_fn=lambda: dis.Bytecode(code).dis(), + ) + out_code = None + from .graph_id_filter import get_dynamo_config_override_for_compile_id + + dynamo_config_override = get_dynamo_config_override_for_compile_id( + compile_id, config.debug_dynamo_config_override + ) + try: + with ( + config.patch(dynamo_config_override) + if dynamo_config_override + else contextlib.nullcontext() + ): + dynamo_output = compile_frame( + code, + globals, + locals, + builtins, + closure, + compiler_fn, + one_graph, + restart_reasons, + export=export, + export_constraints=export_constraints, + frame_state=frame_state, + distributed_state=distributed_state, + package=package, + ) + except exc.SkipFrame as e: + if one_graph: + log.debug("No graph captured with export/fullgraph=True") + if e._torch_dynamo_tracer_output is None: + raise AssertionError( + "SkipFrame exception must have _torch_dynamo_tracer_output set" + ) from None + return ( + ConvertFrameReturn( + skip_reason=f"Dynamo decided to skip the frame while tracing: {e}" + ), + e._torch_dynamo_tracer_output, + ) + + if distributed_state is not None and distributed_state.all_states is None: # type: ignore[has-type] + raise AssertionError( + "compiler collective wasn't run before compilation completed" + ) + out_code = dynamo_output.bytecode + tracer_output = dynamo_output.tracer_output + if dynamo_output.last_attempt_start_time is not None: + last_attempt_start_time = dynamo_output.last_attempt_start_time + + if out_code is None: + raise AssertionError("out_code must not be None after compilation") + log_bytecode( + "MODIFIED BYTECODE", + code.co_name, + code.co_filename, + code.co_firstlineno, + out_code, + ) + # Dump the MODIFIED bytecode of resumption frame into TORCH_TRACE + # log file, so that it is parsed by tlparse tool. + if is_resumption_frame: + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": code.co_name + "_MODIFIED_BYTECODE", + "encoding": "string", + }, + payload_fn=lambda: dis.Bytecode(out_code).dis(), + ) + + if tracer_output.output_graph is None: + raise AssertionError("tracer_output.output_graph must not be None") + output = tracer_output.output_graph + code_context.get_context(out_code)[_BYTECODE_HOOK_SIDE_EFFECTS_CONTEXT_KEY] = ( + tuple(output.get_replayed_side_effect_source_refs()) + ) + + for idx, hook in enumerate(_bytecode_hooks.values()): + with dynamo_timed(f"bytecode_hooks_{idx}", log_pt2_compile_event=True): + hook_output = hook(code, out_code) + if hook_output is not None: + if hook_output is not out_code: + _copy_code_context(out_code, hook_output) + out_code = hook_output + + orig_code_map[out_code] = code + output_codes.add(out_code) + dynamo_time_before_restart = last_attempt_start_time - start_time + + from .bytecode_debugger import BREAKPOINT_MARKER + + if BREAKPOINT_MARKER in out_code.co_consts: + from torch._C._dynamo.eval_frame import register_breakpoint_code + + register_breakpoint_code(out_code) + + # Tests for new code objects. + # The rationale for these tests can be found in torch/csrc/dynamo/eval_frame.c + # Only test once the code object is created. + # They are not tested during runtime. + + def count_args(code: CodeType) -> int: + import inspect + + return ( + code.co_argcount + + code.co_kwonlyargcount + + bool(code.co_flags & inspect.CO_VARARGS) + + bool(code.co_flags & inspect.CO_VARKEYWORDS) + ) + + if out_code is None: + raise AssertionError( + "out_code must not be None after bytecode hook processing" + ) + + total_argcount_old = count_args(code) + total_argcount_new = count_args(out_code) + if ( + code.co_varnames[:total_argcount_old] + != out_code.co_varnames[:total_argcount_new] + ): + msg = "arg mismatch: " + msg += f"old code object has args {code.co_varnames[:total_argcount_old]}, " + msg += ( + f"new code object has args {out_code.co_varnames[:total_argcount_new]}" + ) + raise AssertionError(msg) + + if code.co_freevars != out_code.co_freevars: + msg = "free var mismatch: " + msg += f"old code object has free var {code.co_freevars}, " + msg += f"new code object has free var {out_code.co_freevars}" + raise AssertionError(msg) + + if code.co_cellvars != out_code.co_cellvars: + msg = "cell var mismatch: " + msg += f"old code object has cell var {code.co_cellvars}, " + msg += f"new code object has cell var {out_code.co_cellvars}" + raise AssertionError(msg) + + # Skipping Dynamo on a frame without any extracted graph. + # This does not affect eager functionality. But this is necessary + # for export for cases where Dynamo-reconstructed bytecode can create + # new function frames, confusing export in thinking that there + # are extra graphs now. + + if output.export and output.is_empty_graph(): + return ( + ConvertFrameReturn(skip_reason="export mode produced an empty graph"), + tracer_output, + ) + + if output.guards is None: + raise AssertionError("output.guards must not be None") + CleanupManager.instance[out_code] = output.cleanups + nonlocal cache_entry + # Temporarily restore the mode stack so guard expressions that + # reference modes can evaluate. DisableTorchFunction prevents + # __torch_function__ dispatch during guard construction so modes + # with mutable state aren't triggered. + build_guards_ctx = contextlib.ExitStack() + if torch_function_mode_stack_state_mgr.stack: + build_guards_ctx.enter_context( + torch_function_mode_stack_state_mgr.temp_restore_stack() + ) + with dynamo_timed("build_guards", log_pt2_compile_event=True), build_guards_ctx: + check_fn = dynamo_output.build_guards( + code, + hooks=hooks, + save=package is not None, + cache_entries=cache_entries, + ) + + if package is not None: + if check_fn.guards_state is None: + raise AssertionError("check_fn.guards_state must not be None") + package.add_guarded_code(check_fn.guards_state, out_code) + package.add_inlined_source(output.tracing_context.traced_code) + package.update_device_type(output.current_tracer.graph) + + compile_id_str = str(compile_id) if compile_id is not None else "Unknown" + annotation_str = "Torch-Compiled Region: " + compile_id_str + guarded_code = GuardedCode( + out_code, + check_fn.guard_manager, # type: ignore[arg-type] + compile_id, + annotation_str, + ) + + if not output.is_empty_graph() and hooks.guard_export_fn is not None: + # We should not run the guard_export_fn when Dynamo does not + # generate any graph. This can happen in export when TorchDynamo + # generated bytecode has some reconstruction logic for mutated + # variables which can trigger TorchDynamo on the children frames but + # they are benign and do not generate any new graphs. + hooks.guard_export_fn(output.guards) + + return wrap_guarded_code(guarded_code), tracer_output + + metrics_context = get_metrics_context() + package_code_context = ( + package.code_context(code) if package is not None else contextlib.nullcontext() + ) + with ( + _use_lazy_graph_module(config.use_lazy_graph_module), + compile_context(CompileContext(compile_id)), + chromium_event_timed( + "dynamo", reset_event_log_on_exit=True, log_pt2_compile_event=True + ), + _WaitCounter("pytorch.wait_counter.entire_forward_compile").guard(), + metrics_context, + dynamo_timed( + "_compile.compile_inner", + phase_name="entire_frame_compile", + dynamo_compile_column_us="dynamo_cumulative_compile_time_us", + ), + package_code_context, + ): + restart_reasons: set[str] = set() + if compile_pg := get_compile_pg(): + distributed_state = DistributedState(compile_pg, LocalState()) + else: + distributed_state = None + + # Check recompilations + recompile_reason: str | None = None + if is_recompilation(cache_size) and frame: + reasons = get_and_maybe_log_recompilation_reasons( + cache_entries_for_reasons, frame, innermost_backend(compiler_fn) + ) + recompile_reason = ( + "Unable to find recompilation reasons" if not reasons else reasons[0] + ) + metrics_context.update_outer( + { + "recompile_reason": recompile_reason, + "inline_inbuilt_nn_modules_candidate": False, + } + ) + + recompile_user_contexts = get_hook_for_recompile_user_context() + if recompile_user_contexts: + # cap each user context to N chars for data retention purposes. N=256 + # is chosen to be large enough to capture the most important info. + user_contexts_msg = { + user_context()[:256] for user_context in recompile_user_contexts + } + metrics_context.set("recompile_user_contexts", user_contexts_msg) + + exceeded, limit_type = exceeds_recompile_limit(cache_size, compile_id) + if exceeded: + + def format_func_info(code: CodeType) -> str: + return f"'{code.co_name}' ({code.co_filename}:{code.co_firstlineno})" + + # NS: Don't add period at the end of string, as it'll be added to URL + # rendering it incorrect + log.warning( + "torch._dynamo hit config.%s (%s)\n" + " function: %s\n" + " last reason: %s\n" + 'To log all recompilation reasons, use TORCH_LOGS="recompiles".\n' + "To diagnose recompilation issues, see %s", + limit_type, + getattr(config, limit_type), + format_func_info(code), + recompile_reason, + troubleshooting_url, + ) + + def raise_unimplemented_cache_limit_exceeded() -> NoReturn: + unimplemented( + gb_type="Dynamo recompile limit exceeded", + context=f"Limit type: {limit_type}", + explanation="Dynamo attempted to recompile the code object too many times, " + f"exceeding the {limit_type} cache size limit (currently set to {getattr(config, limit_type)}). " + "Excessive recompilations can degrade " + "performance due to the compilation overhead of each recompilation.", + hints=[ + "To monitor recompilations, enable TORCH_LOGS=recompiles. " + "If recompilations are expected, consider " + f"increasing torch._dynamo.config.{limit_type} to an appropriate value.", + f"See {troubleshooting_url} for tips on dealing with recompilations.", + ], + ) + + try: + raise_unimplemented_cache_limit_exceeded() + except Unsupported as e: + if config.fail_on_recompile_limit_hit: + raise FailOnRecompileLimitHit( + "Hard failure due to fail_on_recompile_limit_hit" + ) from e + elif one_graph: + raise FailOnRecompileLimitHit( + "Hard failure due to fullgraph=True" + ) from e + else: + # Set frame execution strategy to RUN_ONLY for this recompile limit case + e.frame_exec_strategy = FrameExecStrategy( + FrameAction.RUN_ONLY, FrameAction.RUN_ONLY + ) + raise + + log.debug( + "torchdynamo start compiling %s %s:%s, stack (elided %s frames):\n%s", + code.co_name, + code.co_filename, + code.co_firstlineno, + skip + 2, + # -2: omit current frame, omit contextlib decorator + "".join(CapturedTraceback.extract(skip=2 + skip).format()), + ) + # -4: -2 as above, plus trace_structured frames + # + # NB: the frame looks like this: + # + # # handled by skip argument + # torch/_dynamo/convert_frame.py:1069 in catch_errors + # torch/_dynamo/convert_frame.py:910 in _convert_frame + # torch/_dynamo/convert_frame.py:464 in _convert_frame_assert + # torch/_utils_internal.py:70 in wrapper_function + # + # # 2 current frame and context lib + # env/lib/python3.10/contextlib.py:79 in inner + # torch/_dynamo/convert_frame.py:776 in _compile + # + # # 2 extra here + # torch/_logging/_internal.py:1064 in trace_structured + # torch/_dynamo/convert_frame.py:780 in + stack_trace = log_dynamo_start(code, skip) + start_time_ns = time.time_ns() + fail_type: str | None = None + fail_reason: str | None = None + exception_stack_trace: list[str] | None = None + fail_user_frame_filename: str | None = None + fail_user_frame_lineno: int | None = None + torch._dynamo.utils.ReinplaceCounters.clear() + guarded_code = None + tracer_output = None + + if ( + config.debug_backend_override + or config.debug_dynamo_config_override + or config.debug_inductor_config_override + ): + # Eagerly validate config override strings before entering the + # compilation try/except so that typos surface as clean ValueErrors + # instead of being wrapped as InternalTorchDynamoError. + from .graph_id_filter import ( + _validate_backend_names, + _validate_dynamo_config_keys, + _validate_inductor_config_keys, + ) + + if err := _validate_backend_names(config.debug_backend_override): + raise ValueError(err) + if err := _validate_dynamo_config_keys(config.debug_dynamo_config_override): + raise ValueError(err) + if err := _validate_inductor_config_keys( + config.debug_inductor_config_override + ): + raise ValueError(err) + + try: + guarded_code, tracer_output = compile_inner(code, one_graph, hooks) + + # NB: We only put_code_state in success case. Success case here + # does include graph breaks; specifically, if a graph break still + # resulted in a partially compiled graph, we WILL return here. An + # Unsupported exception will only bubble to the top level if we + # are unable to compile the frame at all. In this case, there's + # no point in uploading the code state, because we will always + # fail exactly the same way even without the update. (It's useful + # to upload for graph break though, because this can prevent + # extra graph break compilations.) + put_code_state() + if ( + tracer_output + and (output_graph := tracer_output.output_graph) + and output_graph.has_outputs() + ): + log_frame_dynamic_whitelist(code) + if recompile_reason and "size mismatch at index" in recompile_reason: + _log_size_mismatch_recompile() + + clear_compile_context_weakrefs(tracer_output, compiler_fn) + return guarded_code + except Exception as e: + # NB: e's msg is mutated here to add user stack, but we DON'T want + # that stack in the Scuba logged fail_reason. So we grab the fail + # info here and add it to the metrics context below. + fail_type = type(e).__qualname__ + fail_reason = str(e) + exception_stack_trace = [traceback.format_exc()] + exception_handler(e, code, frame, export=export) + # NB: this is the post-mutation exception + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "dynamo_error", + "encoding": "string", + }, + payload_fn=lambda: traceback.format_exc(), + ) + fail_user_frame_filename, fail_user_frame_lineno = exc.get_exc_message( + e, compile_id + ) + tracer_output = getattr(e, "_torch_dynamo_tracer_output", None) + if isinstance( + e, + ( + Unsupported, + UserError, + TorchRuntimeError, + BackendCompilerFailed, + AssertionError, + IndexError, # dim out-of-range from canonicalize_dim/maybe_wrap_dim + ConstraintViolationError, + GuardOnDataDependentSymNode, + ValidationException, + UncapturedHigherOrderOpError, + BisectValidationException, + ShortenTraceback, + PackageError, + ResumePrologueTracingError, + ), + ): + raise + else: + # Rewrap for clarity + raise InternalTorchDynamoError( + f"{type(e).__qualname__}: {str(e)}" + ).with_traceback(e.__traceback__) from None + finally: + # === WARNING WARNING WARNING === + # If you commit a bug here, it will suppress writing to + # dynamo_compile table, and we will not have telemetry. + # Be extra careful when making changes here! + + if torch._dynamo.config.run_gc_after_compile: + with dynamo_timed("gc", dynamo_compile_column_us="gc_time_us"): + log.info("run_gc_after_compile: running gc") + gc.collect(1) + + output = None + if tracer_output: + output = tracer_output.output_graph + if output: + # pyrefly: ignore [implicit-any] + output.local_scope = {} + # tracer should already be None, keep an extra check here just in case. + if tracer := output.root_tx: + # pyrefly: ignore [implicit-any] + tracer.f_locals = {} + + from .utils import curr_frame + + frame_key = str(curr_frame) + if fail_reason is None and output is not None: + guard_count = len(output.guards) + shape_env_guard_count = len(output.shape_env.guards) + graph_op_count = output.count_calls() + graph_node_count = len(output.graph.nodes) + graph_node_shapes = output.get_graph_sizes_structured() + graph_input_count = len(output.placeholders) + non_compliant_ops = {op.__qualname__ for op in output.non_compliant_ops} + compliant_custom_ops = { + op.__qualname__ for op in output.compliant_custom_ops + } + torch._dynamo.utils.ReinplaceCounters.log() + else: + guard_count = None + shape_env_guard_count = None + graph_op_count = None + graph_node_count = None + # pyrefly: ignore [implicit-any] + graph_node_shapes = {} + graph_input_count = None + non_compliant_ops = set({}) + compliant_custom_ops = set({}) + restart_reasons = set() + # If compilation failed, the entire time is wasted + dynamo_time_before_restart = (time.time_ns() - start_time_ns) / 1e9 + + metrics = { + "frame_key": frame_key, + "co_name": code.co_name, + "co_filename": code.co_filename, + "co_firstlineno": code.co_firstlineno, + "cache_size": cache_size.num_cache_entries_with_same_id_matched_objs, + "accumulated_cache_size": cache_size.num_cache_entries, + "guard_count": guard_count, + "shape_env_guard_count": shape_env_guard_count, + "graph_op_count": graph_op_count, + "graph_node_count": graph_node_count, + "graph_input_count": graph_input_count, + "fail_type": fail_type, + "fail_reason": fail_reason, + "fail_user_frame_filename": fail_user_frame_filename, + "fail_user_frame_lineno": fail_user_frame_lineno, + "non_compliant_ops": non_compliant_ops, + "compliant_custom_ops": compliant_custom_ops, + "restart_reasons": restart_reasons, + "dynamo_time_before_restart_s": dynamo_time_before_restart, + "has_guarded_code": guarded_code is not None, + "specialize_float": config.specialize_float, + "is_forward": True, + "dynamo_compile_time_before_restart_us": to_int_us( + dynamo_time_before_restart + ), + "stack_trace": stack_trace, + "graph_node_shapes": str(graph_node_shapes), + "exception_stack_trace": exception_stack_trace, + } + # TODO: replace with CompileEventLogger.compilation_metrics + # There are some columns here not in PT2 Compile Events + # so we need to slightly change it + metrics_context.update_outer(metrics) + # === END WARNING WARNING WARNING === + + # If tracer is available, then tracer.error_on_graph_break reflects value of + # global symbolic_convert.error_on_graph_break at the time of the graph break - + # symbolic_convert.error_on_graph_break may have been (correctly) changed during cleanup. + # If tracer is unavailable, then fallback to symbolic_convert.error_on_graph_break. + if convert_frame_box: + convert_frame_box.error_on_graph_break = ( + tracer_output.error_on_graph_break + if tracer_output + else _get_error_on_graph_break() + ) + + # Cleanup guards unless if in export, which will return guards + # Make sure to do this after collecting metrics + if ( + tracer_output is not None + and tracer_output.output_graph is not None + and not tracer_output.output_graph.export + ): + tracer_output.output_graph.tracing_context.guards_context.dynamo_guards.clear() + + clear_compile_context_weakrefs(tracer_output, compiler_fn) + + +class ConvertFrame: + def __init__( + self, + compiler_fn: CompilerFn, + hooks: Hooks, + package: CompilePackage | None = None, + recompile_limit: int | None = None, + ) -> None: + self._torchdynamo_orig_backend = compiler_fn + self._inner_convert = convert_frame_assert( + compiler_fn, + one_graph=False, + package=package, + recompile_limit=recompile_limit, + ) + self._hooks = hooks + self._recompile_limit = recompile_limit + + @property + def _clone_with_backend(self) -> Callable[[WrapBackendDebug], ConvertFrame]: + # Used by DDPOptimizer to swap in its own backend. + return lambda backend: convert_frame( + backend, + self._hooks, + recompile_limit=self._recompile_limit, + ) + + def __call__( + self, + frame: DynamoFrameType, + cache_entry: CacheEntry | None, + hooks: Hooks, + frame_state: dict[str, int | FrameStateSizeEntry], + skip: int = 0, + ) -> ConvertFrameReturn: + input_codes.add(frame.f_code) + counters["frames"]["total"] += 1 + try: + result = self._inner_convert( + frame, cache_entry, hooks, frame_state, skip=skip + 1 + ) + counters["frames"]["ok"] += 1 + return result + except Exception as e: + # Do not allow errors to be suppressed if we're tracing a resume function prologue + if isinstance(e, ResumePrologueTracingError): + raise + + error_on_graph_break = ( + self._inner_convert._box.error_on_graph_break is not None + ) + if error_on_graph_break is None: + raise AssertionError("error_on_graph_break must not be None") from None + if self._inner_convert._box.error_on_graph_break: + # NOTE we _might_ have to wrap the current in a custom exception + # in order to correctly bubble up to the top-level compile wrapper in + # eval_frame.py. But re-raising seems to work for now because exceptions from tracing + # a nested call that results in a top-level frame compile will be handled by the caller + # as an observed exception - we don't expect that exception to be suppressed. + raise + + # These two exception types are "soft" failure, in the sense that + # we know this is due to something we didn't implement all the + # way, scare the user less about it. That being said, if you + # are trying to understand why a graph break happened, it's still + # important to have this information, so offer it. + # + # NB: NotImplementedError used to be on this list, but actually + # it is impossible for it to reach here, as it is converted into + # InternalTorchDynamoError. This behavior seemed reasonable + # to me (ezyang, Aug 2023) so I kept it, but maybe at some point + # someone wanted these to also get suppressed. If so, you'll + # need to make these exceptions not get wrapped + + # We intentionally don't want to suppress error here. + if isinstance(e, UncapturedHigherOrderOpError): + raise + + soft_fail = isinstance(e, (Unsupported, UserError)) + code = frame.f_code + # Log soft failure that was not already logged by symbolic_convert. + # This happens e.g. for graph breaks that are raised in convert_frame.py + # TODO(williamwen42) Unsupported exn's from tracing are handled and logged by symbolic_convert.py + # Unsupported exn's caught here should be from convert_frame.py - figure out a better way + # to log these. + if ( + soft_fail + and not getattr(e, "logged", False) + and graph_break_log.isEnabledFor(logging.DEBUG) + ): + # Log this message in the graph break. Also use the string + # "skip: " to tell that the whole frame is falling back to + # eager. + if hasattr(e, "compile_id") and hasattr(e, "real_stack"): + with compile_context(CompileContext(e.compile_id)): # type: ignore[attr-defined] + user_stack = e.real_stack + user_stack_formatted = "".join( + traceback.format_list(user_stack) + ) + frame_info = exc.format_frame_info(code) + user_stack_trace = ( + "Graph break: torch.compile cannot properly resume from this graph break, which results in a skip.\n" + f"torch.compile will skip tracing the frame {frame_info} and fall back to eager.\n" + "The graph break occurred in the following user code:\n" + f"{user_stack_formatted}" + ) + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "dynamo_graph_break_reason", + "encoding": "string", + }, + payload_fn=lambda: f"{user_stack_trace}\n{traceback.format_exc()}", + ) + graph_break_log.debug( + user_stack_trace, + exc_info=True, + stack_info=config.verbose, + ) + + if not config.suppress_errors and not soft_fail: + raise + + # Suppress the error. NB: It's very important to do the + # suppression logging HERE, where the actual suppression + # happens. Previously it was somewhere else and so it was + # possible to accidentally not log at all. + record_filename = getattr(e, "record_filename", None) + code = frame.f_code + error_msg = format_error_msg(e, code, record_filename, frame) + + if soft_fail: + log.info(error_msg, exc_info=True) + else: + log.warning(error_msg, exc_info=True) + + # Check if the exception has a specific frame execution strategy + if ( + isinstance(e, exc.TorchDynamoException) + and e.frame_exec_strategy is not None + ): + return ConvertFrameReturn( + frame_exec_strategy=e.frame_exec_strategy, + skip_reason="compilation failed with a custom frame execution strategy", + ) + + return ConvertFrameReturn( + skip_reason="an error was suppressed during compilation" + ) + + +def convert_frame( + compiler_fn: CompilerFn, + hooks: Hooks, + package: CompilePackage | None = None, + recompile_limit: int | None = None, +) -> ConvertFrame: + """Try to convert a frame into an FX graph, if error leave frame unmodified""" + return ConvertFrame( + compiler_fn, + hooks, + package=package, + recompile_limit=recompile_limit, + ) + + +# TODO mlazos: add support for same args, or record them +def replay(filename: str) -> None: + from .backends.debugging import eager + + original_replay_val = config.replay_record_enabled + config.replay_record_enabled = False + with open(filename, "rb") as in_file: + record = ExecutionRecord.load(in_file) + record.globals = dict(itertools.chain(record.globals.items(), globals().items())) + + with decorators.error_on_graph_break(False): + try: + _compile( + record.code, + record.globals, + record.locals, + record.builtins, + record.closure, + compiler_fn=eager, + one_graph=False, + export=False, + export_constraints=None, + hooks=Hooks(), + cache_entry=None, + cache_entries=[], + cache_entries_for_reasons=[], + cache_size=CacheSizeRelevantForFrame(0, 0), + frame=None, + frame_state={}, + compile_id=CompileId(frame_id=42, frame_compile_id=999), + ) + finally: + config.replay_record_enabled = original_replay_val + + +def first_real_inst_idx(code: CodeType) -> int: + if sys.version_info < (3, 11): + return 0 + for inst in dis.get_instructions(code): + if inst.opname == "RESUME": + return inst.offset // 2 + raise RuntimeError("RESUME instruction not found in code") + + +class ConvertFrameProtocol(typing.Protocol): + def __call__( + self, + frame: DynamoFrameType, + cache_entry: CacheEntry | None, + hooks: Hooks, + frame_state: dict[str, int | FrameStateSizeEntry], + *, + skip: int = 0, + ) -> ConvertFrameReturn: ... + + +class CatchErrorsWrapper: + def __init__(self, callback: ConvertFrameProtocol, hooks: Hooks) -> None: + functools.wraps(callback)(self) + self._torchdynamo_orig_backend = callback + self.hooks = hooks + + def _handle_skip( + self, result: ConvertFrameReturn, frame: DynamoFrameType + ) -> ConvertFrameReturn: + if result.skip_reason is not None and result.guarded_code is None: + log.debug( + "skipping: %s (reason: %s, file: %s)", + frame.f_code.co_name, + result.skip_reason, + frame.f_code.co_filename, + ) + add_skip_reason(result.skip_reason, frame) + return result + + def __call__( + self, + frame: DynamoFrameType, + cache_entry: CacheEntry | None, + frame_state: dict[str, int | FrameStateSizeEntry], + ) -> ConvertFrameReturn: + if frame_state is None: + raise AssertionError("frame_state must not be None") + input_codes.add(frame.f_code) + + is_skipfile = trace_rules.check(frame.f_code, frame=frame) + if sys.version_info >= (3, 13): + has_started_execution = frame.f_lasti > first_real_inst_idx(frame.f_code) + else: + has_started_execution = frame.f_lasti >= first_real_inst_idx(frame.f_code) + + # Check if we should skip due to torch dispatch mode. + # When inline_torch_dispatch_torch_compile is True (new behavior), we walk + # the stack to check for active modes. When False (old behavior), we use + # the global flag that tracks if we're inside any mode. + if config.inline_torch_dispatch_torch_compile: + should_skip_for_dispatch_mode = any_torch_dispatch_mode_on_stack() + else: + should_skip_for_dispatch_mode = ( + is_in_any_mode_without_ignore_compile_internals() + ) + + if ( + # TODO: the first condition is not covered by any test + has_started_execution + or is_skipfile + or config.disable + or ( + should_skip_for_dispatch_mode + and not getattr(self._torchdynamo_orig_backend, "_export", False) + ) + ): + apply_to_code = True + if has_started_execution: + skip_reason = "frame has already started executing" + elif is_skipfile: + skip_reason = "frame is in the Dynamo skipfiles list" + elif config.disable: + skip_reason = "Dynamo tracing is disabled" + else: + skip_reason = ( + "non-infra torch dispatch mode present, this is not" + " supported today in torch.compile" + ) + apply_to_code = False + return self._handle_skip( + ConvertFrameReturn( + apply_to_code=apply_to_code, skip_reason=skip_reason + ), + frame, + ) + + if ( + frame.f_code.co_filename == "" and frame.f_code.co_name == "__new__" + ) or ( + frame.f_code.co_filename.endswith("collections/__init__.py") + and frame.f_code.co_name == "_make" + ): + return self._handle_skip( + ConvertFrameReturn( + skip_reason="frame is a namedtuple __new__/_make constructor" + ), + frame, + ) + + if ( + frame.f_code.co_name == "__init__" + and frame.f_code.co_argcount > 0 + and frame.f_code.co_varnames + and is_traceable_wrapper_subclass( + frame.f_locals.get(frame.f_code.co_varnames[0]) + ) + ): + return self._handle_skip( + ConvertFrameReturn( + skip_reason="__init__ of a traceable wrapper subclass cannot be traced" + ), + frame, + ) + + if torch._dynamo.utils.get_optimize_ddp_mode() == "ddp_optimizer": + ddp_module = DistributedDataParallel._get_active_ddp_module() + if ddp_module: + with compile_lock: + from torch._dynamo.backends.distributed import DDPOptimizer + + ddp_optimizer = DDPOptimizer( + bucket_bytes_cap=ddp_module.bucket_bytes_cap, + backend_compile_fn=self._torchdynamo_orig_backend._torchdynamo_orig_backend, # type: ignore[attr-defined] + ) + if not hasattr( + self._torchdynamo_orig_backend, "_clone_with_backend" + ): + raise AssertionError( + "DDPOptimizer only supports callback fns that know how to clone themselves." + ) + hijacked_callback = ( + self._torchdynamo_orig_backend._clone_with_backend( + ddp_optimizer.compile_fn, + ) + ) + return self._handle_skip( + hijacked_callback(frame, cache_entry, self.hooks, frame_state), + frame, + ) + + with compile_lock, _disable_current_modes(): + # skip=1: skip this frame + result = self._torchdynamo_orig_backend( + frame, cache_entry, self.hooks, frame_state, skip=1 + ) + return self._handle_skip(result, frame) + + +def catch_errors_wrapper( + callback: ConvertFrameProtocol, hooks: Hooks +) -> CatchErrorsWrapper: + return CatchErrorsWrapper(callback, hooks) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/create_parameter_op.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/create_parameter_op.py new file mode 100644 index 0000000000000000000000000000000000000000..aa2481ffda7713de95678ffc1bf50e3ccec39a1d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/create_parameter_op.py @@ -0,0 +1,70 @@ +import threading +from collections.abc import Generator +from contextlib import contextmanager +from typing import Any + +import torch + + +# See [Note: Metadata mutation in proxy tracing] for why sacrificial parameter mutates +# metadata during proxy tracing and we should remove the sacrificial parameter logic. +doc = """ +This is used when dynamo traces torch.nn.Parameter, which normally would not trace properly +with AOTAutograd. We instead create a placeholder torch.nn.Parameter before the graph, which +becomes a graph arg and has no storage backing it. At the point in the graph where the parameter +actually should be created we mutate this sacrificial placeholder into it. This allows gradients +to flow into the parameter as if it were an input to the graph (which is the only thing we are +allowed to compute gradients on). +""".strip() + + +class TracableCreateParameter(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward(ctx: Any, tensor: Any, placeholder: Any) -> torch.nn.Parameter: + if tensor.requires_grad: + tensor = tensor.detach() + return placeholder.set_(tensor) + + @staticmethod + def backward(ctx: Any, *grad_outputs: torch.Tensor) -> tuple[None, torch.Tensor]: + grad = grad_outputs[0] + return None, grad # grad flows to placeholder + + +def tracable_create_parameter( + tensor: torch.Tensor, placeholder: torch.nn.Parameter +) -> torch.nn.Parameter: + with torch.set_grad_enabled(placeholder.requires_grad): + out = TracableCreateParameter.apply(tensor, placeholder) + return out + + +def new_parameter_placeholder( + size: tuple[int, ...], dtype: torch.dtype, device: torch.device, requires_grad: bool +) -> torch.nn.Parameter: + """Create a placeholder to be passed to the above functions""" + result = torch.nn.Parameter( + torch.empty(size, dtype=dtype, device=device), requires_grad=requires_grad + ) + # TODO(jansel): alloc followed by free is inefficient, need a way to allocate an unbacked tensor. + # Allocating a zero tensor would cause assert failures in autograd. + result.untyped_storage().resize_(0) + return result + + +_TLS = threading.local() + + +@contextmanager +def do_not_convert_to_tracable_parameter() -> Generator[bool, None, None]: + old_flag = getattr(_TLS, "convert_tracable_parameter", True) + _TLS.convert_tracable_parameter = False + try: + yield False + finally: + _TLS.convert_tracable_parameter = old_flag + + +def can_convert_to_tracable_parameter() -> bool: + return getattr(_TLS, "convert_tracable_parameter", True) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/current_scope_id.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/current_scope_id.py new file mode 100644 index 0000000000000000000000000000000000000000..74a5f4888c64629f3225118d91b52ba05e000ce0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/current_scope_id.py @@ -0,0 +1,42 @@ +""" +Provides thread-local scope identification for SubgraphTracer instances. + +This module implements a thread-safe mechanism for tracking nested tracing contexts, +which is essential when multiple SubgraphTracer instances are active. The scope ID +helps identify which tracer context is currently active when direct access to the +InstructionTranslator is difficult. + +Key components: +- Thread-local scope ID storage (_current_scope_id) +- Getter function (current_scope_id) to safely access the current scope +- Context manager (enter_new_scope) for managing nested scope transitions + +The scope ID increments when entering a new context and decrements when exiting, +allowing proper tracking of nested tracing operations across different threads. +""" + +import contextlib +import threading +from collections.abc import Generator + + +# Global variable to identify which SubgraphTracer we are in. +# It is sometimes difficult to find an InstructionTranslator to use. +_current_scope_id = threading.local() + + +def current_scope_id() -> int: + global _current_scope_id + if not hasattr(_current_scope_id, "value"): + _current_scope_id.value = 1 + return _current_scope_id.value + + +@contextlib.contextmanager +def enter_new_scope() -> Generator[None, None, None]: + global _current_scope_id + try: + _current_scope_id.value = current_scope_id() + 1 + yield + finally: + _current_scope_id.value = current_scope_id() - 1 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/dce_extra_outputs.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/dce_extra_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..4650d3de710481f0f37a7da37e6d1cabd454a305 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/dce_extra_outputs.py @@ -0,0 +1,228 @@ +""" +DCE pass for unused extra outputs in HOP subgraphs. + +When enable_side_effects_with_extra_outputs is True, HOPs like invoke_subgraph and +checkpoint (tag_activation_checkpoint) +return all intermediate tensors/symints as extra outputs to support side effects. +However, many of these extra outputs may not actually be used in the parent graph. + +This pass removes unused extra outputs by: +1. Collecting all callers for each subgraph +2. Checking if each output is used by all callers +3. Removing unused outputs from the subgraph's output node +4. Updating the HOP call and getitem indices in all call sites + +""" + +import collections +import operator + +import torch + + +# HOPs that may have extra outputs that can be DCE'd +_HOPS_WITH_EXTRA_OUTPUTS = { + torch.ops.higher_order.invoke_subgraph, + torch.ops.higher_order.tag_activation_checkpoint, + # torch.ops.higher_order.autograd_function_apply, +} + + +def dce_hop_extra_outputs(gm: torch.fx.GraphModule) -> bool: + """ + Remove unused extra outputs from HOP calls in all submodules. + + For each subgraph output, check if any caller has a getitem for that index + with users. If no caller uses it, remove the output. + If the user in caller is an output node, to simplify the algorithm, we do not recursively check + if the caller's output is used further up in the call chain. + + Args: + gm: The GraphModule to optimize + + Returns: + True if any modifications were made, False otherwise + """ + # Collect all subgraph usages: subgraph_id -> list of (parent_gm, subgraph_name, hop_node) + subgraph_id_to_callers: dict[ + int, list[tuple[torch.fx.GraphModule, str, torch.fx.Node]] + ] = collections.defaultdict(list) + _collect_all_subgraph_usages(gm, subgraph_id_to_callers) + + if not subgraph_id_to_callers: + return False + + modified = False + + for callers in subgraph_id_to_callers.values(): + parent_gm, subgraph_name, _ = callers[0] + subgraph = getattr(parent_gm, subgraph_name) + + if not isinstance(subgraph, torch.fx.GraphModule): + continue + + output_node = next(n for n in subgraph.graph.nodes if n.op == "output") + output_args = output_node.args[0] + if not isinstance(output_args, (tuple, list)): + continue + + num_outputs = len(output_args) + used_indices: set[int] = set() + + # Check which outputs are used by any caller + for idx in range(num_outputs): + if _is_output_used(idx, callers): + used_indices.add(idx) + + # DCE if some outputs are unused + if 0 < len(used_indices) < num_outputs: + if _dce_subgraph(subgraph, callers, used_indices): + modified = True + + return modified + + +def _collect_all_subgraph_usages( + gm: torch.fx.GraphModule, + subgraph_id_to_callers: dict[ + int, list[tuple[torch.fx.GraphModule, str, torch.fx.Node]] + ], +) -> None: + """Recursively collect all HOP usages across the graph tree.""" + for node in gm.graph.nodes: + if node.op == "call_function" and node.target in _HOPS_WITH_EXTRA_OUTPUTS: + subgraph_attr = node.args[0] + if ( + isinstance(subgraph_attr, torch.fx.Node) + and subgraph_attr.op == "get_attr" + ): + subgraph_name = subgraph_attr.target + if not isinstance(subgraph_name, str): + raise AssertionError( + f"Expected subgraph_name to be str, got {type(subgraph_name)}" + ) + subgraph = getattr(gm, subgraph_name, None) + if isinstance(subgraph, torch.fx.GraphModule): + subgraph_id = id(subgraph) + subgraph_id_to_callers[subgraph_id].append( + (gm, subgraph_name, node) + ) + _collect_all_subgraph_usages(subgraph, subgraph_id_to_callers) + + +def _is_output_used( + output_idx: int, + callers: list[tuple[torch.fx.GraphModule, str, torch.fx.Node]], +) -> bool: + """Check if output_idx is used by ANY caller (has a getitem with users).""" + for _parent_gm, _subgraph_name, hop_node in callers: + for user in hop_node.users: + if user.op == "call_function" and user.target == operator.getitem: + if user.args[1] == output_idx and len(user.users) > 0: + return True + return False + + +def _dce_subgraph( + subgraph: torch.fx.GraphModule, + callers: list[tuple[torch.fx.GraphModule, str, torch.fx.Node]], + used_indices: set[int], +) -> bool: + """ + DCE a subgraph by removing unused output indices. + + Updates the subgraph's output node, all getitem nodes in callers, + and example_value metadata on HOP nodes. + """ + output_node = next(n for n in subgraph.graph.nodes if n.op == "output") + old_outputs = list(output_node.args[0]) + + # Check if this is the forward subgraph of autograd_function_apply + # For autograd_function_apply, the fwd subgraph must return (output, saved_values, ...) + # where indices 0 and 1 are ALWAYS required by the runtime + # is_autograd_fwd = any( + # node.target == torch.ops.higher_order.autograd_function_apply + # for node in hop_nodes + # ) + is_autograd_fwd = False + + # For autograd_function_apply forward subgraph, indices 0 (output) and 1 (saved_values) + # are ALWAYS used by the runtime, even if not explicitly accessed via getitem + if is_autograd_fwd and len(old_outputs) >= 2: + used_indices.add(0) # output + used_indices.add(1) # saved_values + + # Nothing to DCE if all outputs are used or no outputs are used + if len(used_indices) >= len(old_outputs) or len(used_indices) == 0: + return False + + # Build mapping from old indices to new indices + old_to_new: dict[int, int] = {} + new_outputs = [] + new_idx = 0 + + for old_idx in range(len(old_outputs)): + if old_idx in used_indices: + old_to_new[old_idx] = new_idx + new_outputs.append(old_outputs[old_idx]) + new_idx += 1 + + # Update subgraph output node + # Create a new output node with the filtered outputs + with subgraph.graph.inserting_before(output_node): + new_output_node = subgraph.graph.output(tuple(new_outputs)) + output_node.replace_all_uses_with(new_output_node) + subgraph.graph.erase_node(output_node) + + for parent_gm, _, hop_node in callers: + # Update getitem nodes to use new indices + for user in list(hop_node.users): + if user.op == "call_function" and user.target == operator.getitem: + old_idx = user.args[1] + if not isinstance(old_idx, int): + raise AssertionError( + f"Expected getitem index to be int, got {type(old_idx)}" + ) + + if old_idx not in old_to_new: + if len(list(user.users)) != 0: + raise AssertionError( + f"Expected unused getitem node at index {old_idx} to have no users" + ) + parent_gm.graph.erase_node(user) + continue + + new_idx = old_to_new[old_idx] + # Create a new getitem node with the new index + with parent_gm.graph.inserting_before(user): + new_getitem = parent_gm.graph.call_function( + operator.getitem, args=(user.args[0], new_idx) + ) + # Copy metadata from old node + new_getitem.meta = user.meta.copy() + user.replace_all_uses_with(new_getitem) + parent_gm.graph.erase_node(user) + + # Update example_value metadata on hop_node + if "example_value" in hop_node.meta: + old_example = hop_node.meta["example_value"] + if not isinstance(old_example, (tuple, list)): + raise AssertionError( + f"Expected example_value to be tuple or list, got {type(old_example)}" + ) + new_example = tuple( + old_example[old_idx] + for old_idx in range(len(old_outputs)) + if old_idx in used_indices + ) + hop_node.meta["example_value"] = new_example + + # Recompile subgraph and all modified parent graphs + subgraph.graph.lint() + subgraph.recompile() + + for parent_gm in {caller[0] for caller in callers}: + parent_gm.graph.lint() + parent_gm.recompile() + + return True diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/debug_utils.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/debug_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e9b9dac5da5249d04e5af18033cae97d61473924 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/debug_utils.py @@ -0,0 +1,1238 @@ +""" +Debug utilities for TorchDynamo compilation and execution. + +This module provides various debugging tools and utilities for TorchDynamo, including: + +- Minification support for reducing test cases while preserving bugs +- Input/output handling via InputReader and InputWriter for reproducible testing +- Accuracy checking between original and compiled models +- Neural network module string conversion via NNModuleToString +- Profiling tools and system information collection +- Buck build system integration for Meta-internal testing + +Key classes: +- InputReader/InputWriter: Handle serialization of model inputs/outputs +- NNModuleToString: Converts nn.Modules to string representations +- BuckTargetWriter: Manages Buck build system integration +""" + +from __future__ import annotations + +import atexit +import copy +import cProfile +import functools +import getpass +import inspect +import itertools +import logging +import os +import re +import subprocess +import sys +import tempfile +import textwrap +from collections import Counter +from importlib import import_module +from typing import Any, cast, TYPE_CHECKING, TypeVar + +import torch +import torch._prims_common as utils +import torch._subclasses.meta_utils +from torch import Tensor +from torch._dynamo.testing import rand_strided +from torch._inductor.cpp_builder import normalize_path_separator +from torch._prims_common import is_float_dtype +from torch.multiprocessing.reductions import StorageWeakRef +from torch.utils._config_module import ConfigModule +from torch.utils._content_store import ContentStoreReader, ContentStoreWriter + +from . import config +from .utils import clone_inputs, get_debug_dir, warn_once + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + from torch.hub import tqdm + from torch.storage import UntypedStorage + + +log = logging.getLogger(__name__) + +T = TypeVar("T") + + +inductor_config = import_module("torch._inductor.config") +use_buck = inductor_config.is_fbcode() + +if use_buck: + import libfb.py.build_info + + +# pyrefly: ignore [implicit-any] +extra_deps = [] +extra_imports = "" +cur_target = "" +if use_buck: + extra_deps = [ + "//caffe2/torch/fb/sparsenn:sparsenn_operators_gpu", + "//caffe2/torch/fb/sparsenn:sparsenn_operators", + "//deeplearning/fbgemm/fbgemm_gpu:sparse_ops_cpu", + "//deeplearning/fbgemm/fbgemm_gpu:sparse_ops", + ] + cur_target = libfb.py.build_info.BuildInfo.get_build_rule().replace("fbcode:", "//") # type: ignore[possibly-undefined] + # Preload common fbcode custom-op libraries so repros that use those ops + # work out of the box. Best-effort: a repro whose graph doesn't use these + # ops (or that is run outside a buck target linking them) must not fail + # just because the library isn't present. + _extra_deps_list = "\n".join(f' "{x}",' for x in extra_deps) + extra_imports = ( + f"for _extra_dep in [\n{_extra_deps_list}\n]:\n" + " try:\n" + " torch.ops.load_library(_extra_dep)\n" + " except OSError:\n" + " pass\n" + ) + + +BUCK_CMD_PREFIX = ["buck2", "run", "@mode/dev-nosan"] + + +class BuckTargetWriter: + def __init__(self, filename: str) -> None: + self.subdir, self.py_file = os.path.split(os.path.abspath(filename)) + self.target = self.py_file.replace(".py", "") + + # Get main_module path from fbcode + self.path = f"{self.subdir.replace('/', '.')}.{self.target}" + self.path = self.path[self.path.find("fbcode.") :] + self.path = self.path[7:] + + # Get cmd line path + tmp = self.subdir + tmp = tmp[tmp.find("fbcode/") :][7:] + self.cmd_line_path = f"//{tmp}:{self.target}" + + def build(self) -> str: + extra_cpp_deps = "\n".join([f' "{x}",' for x in extra_deps]) + return textwrap.dedent( + f""" +load("@fbcode_macros//build_defs:python_binary.bzl", "python_binary") + +python_binary( + name="{self.target}", + srcs = ["{self.py_file}"], + compile = False, + deps = [ + "//caffe2:torch", + "//caffe2:libtorch", + "//caffe2/functorch:functorch", + "//triton:triton", + "{cur_target}", + ], + cpp_deps = [ +{extra_cpp_deps} + ], + main_module = "{self.path}", + par_style = "xar", +) +""" + ) + + def write(self, print_msg: bool = True) -> list[str]: + target_file = os.path.join(self.subdir, "TARGETS") + with open(target_file, "w") as fd: + fd.write(self.build()) + # log.warning("Wrote isolation TARGETS file at %s", target_file) + cmd_split = BUCK_CMD_PREFIX + [self.cmd_line_path] + if print_msg: + log.warning( + "Found an example that reproduces the error. Run this cmd to repro - %s", + " ".join(cmd_split), + ) + return cmd_split + + +def minifier_dir() -> str: + path = os.path.join(get_debug_dir(), "minifier") + if path is None: + path = f"{tempfile.gettempdir()}/minifier_{getpass.getuser()}" + if not os.path.exists(path): + os.makedirs(path, exist_ok=True) + return path + + +MAX_CONSTANT_NUMEL_INLINE = 4 + + +class UnsupportedNNModuleError(AssertionError): + pass + + +class NNModuleToString: + fake_quant_modules = { + "torch.ao.quantization.fake_quantize.FakeQuantize", + "torch.ao.quantization.fake_quantize.FusedMovingAvgObsFakeQuantize", + } + + qat_conv_modules = { + "torch.ao.nn.qat.modules.conv.Conv1d", + "torch.ao.nn.qat.modules.conv.Conv2d", + "torch.ao.nn.qat.modules.conv.Conv3d", + "torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBn1d", + "torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBn2d", + "torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBn3d", + "torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU1d", + "torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU2d", + "torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvBnReLU3d", + "torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvReLU1d", + "torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvReLU2d", + "torch.ao.nn.intrinsic.qat.modules.conv_fused.ConvReLU3d", + } + + qat_linear_modules = { + "torch.ao.nn.qat.modules.linear.Linear", + "torch.ao.nn.intrinsic.qat.modules.linear_relu.LinearReLU", + } + + # x86 currently aliases fbgemm in repr, so emit fbgemm as the canonical + # constructor for both until those default qconfigs diverge. + default_qat_qconfig_backends = ("fbgemm", "x86", "qnnpack", "onednn") + + safe_reprs = [ + torch.nn.Linear, + torch.nn.Conv1d, + torch.nn.Conv2d, + torch.nn.Conv3d, + torch.nn.BatchNorm1d, + torch.nn.BatchNorm2d, + torch.nn.BatchNorm3d, + torch.nn.LayerNorm, + torch.nn.Dropout, + torch.nn.Softmax, + torch.nn.ReLU, + torch.nn.GELU, + torch.nn.Identity, + torch.nn.MaxPool2d, + torch.nn.Embedding, + torch.nn.Tanh, + torch.nn.ConvTranspose1d, + torch.nn.GLU, + torch.nn.LSTM, + torch.nn.Flatten, + torch.nn.AdaptiveAvgPool2d, + ] + + @staticmethod + def can_convert_to_string(gm: torch.fx.GraphModule) -> bool: + cant_convert = set() + for _, module in gm.named_children(): + # Nested GraphModules (e.g. torch.cond / torch.while_loop subgraphs) + # are serialized recursively by convert(). + if isinstance(module, torch.fx.GraphModule): + continue + if NNModuleToString._module_constructor_string(module) is None: + cant_convert.add(module) + + if len(cant_convert) > 0: + log.warning( + "Cannot safely convert some modules to strings - %s", cant_convert + ) + return False + return True + + @staticmethod + def _module_type_name(module: torch.nn.Module) -> str: + return f"{type(module).__module__}.{type(module).__name__}" + + @staticmethod + def _type_name(type_: type[object]) -> str: + return f"{type_.__module__}.{type_.__name__}" + + @staticmethod + def _fake_quant_constructor(module: torch.nn.Module) -> str | None: + module_type = NNModuleToString._module_type_name(module) + if module_type not in NNModuleToString.fake_quant_modules: + return None + + observer = module.activation_post_process # type: ignore[attr-defined] + quant_min = cast(int, module.quant_min) # type: ignore[attr-defined] + quant_max = cast(int, module.quant_max) # type: ignore[attr-defined] + if getattr(observer, "reduce_range", False): + quant_min *= 2 + quant_max = quant_max * 2 + 1 + args = [ + f"observer={NNModuleToString._type_name(type(observer))}", + f"quant_min={quant_min!r}", + f"quant_max={quant_max!r}", + f"dtype={module.dtype!r}", # type: ignore[attr-defined] + f"qscheme={module.qscheme!r}", # type: ignore[attr-defined] + f"is_dynamic={module.is_dynamic!r}", # type: ignore[attr-defined] + ] + if hasattr(observer, "reduce_range"): + args.append(f"reduce_range={observer.reduce_range!r}") + if hasattr(observer, "ch_axis"): + args.append(f"ch_axis={observer.ch_axis!r}") + return f"{module_type}({', '.join(args)})" + + @staticmethod + def _qat_qconfig_constructor(module: torch.nn.Module) -> str | None: + qconfig = getattr(module, "qconfig", None) + for backend in NNModuleToString.default_qat_qconfig_backends: + try: + default_qconfig = torch.ao.quantization.get_default_qat_qconfig(backend) + except AssertionError: + continue + if repr(qconfig) == repr(default_qconfig): + return ( + "qconfig=torch.ao.quantization.get_default_qat_qconfig" + f"({backend!r})" + ) + return None + + @staticmethod + def _qat_conv_constructor(module: torch.nn.Module) -> str | None: + module_type = NNModuleToString._module_type_name(module) + if module_type not in NNModuleToString.qat_conv_modules: + return None + qconfig = NNModuleToString._qat_qconfig_constructor(module) + if qconfig is None: + return None + + args = [ + repr(module.in_channels), # type: ignore[attr-defined] + repr(module.out_channels), # type: ignore[attr-defined] + f"kernel_size={module.kernel_size!r}", # type: ignore[attr-defined] + f"stride={module.stride!r}", # type: ignore[attr-defined] + f"padding={module.padding!r}", # type: ignore[attr-defined] + f"dilation={module.dilation!r}", # type: ignore[attr-defined] + f"groups={module.groups!r}", # type: ignore[attr-defined] + f"bias={module.bias is not None}", # type: ignore[attr-defined] + f"padding_mode={module.padding_mode!r}", # type: ignore[attr-defined] + ] + bn = getattr(module, "bn", None) + if bn is not None: + args.extend( + [ + f"eps={bn.eps!r}", + f"momentum={bn.momentum!r}", + f"freeze_bn={module.freeze_bn!r}", # type: ignore[attr-defined] + ] + ) + args.append(qconfig) + return f"{module_type}({', '.join(args)})" + + @staticmethod + def _qat_linear_constructor(module: torch.nn.Module) -> str | None: + module_type = NNModuleToString._module_type_name(module) + if module_type not in NNModuleToString.qat_linear_modules: + return None + qconfig = NNModuleToString._qat_qconfig_constructor(module) + if qconfig is None: + return None + + args = [ + repr(module.in_features), # type: ignore[attr-defined] + repr(module.out_features), # type: ignore[attr-defined] + f"bias={module.bias is not None}", # type: ignore[attr-defined] + qconfig, + ] + return f"{module_type}({', '.join(args)})" + + @staticmethod + def _can_emit_module_constructor(module: torch.nn.Module, module_str: str) -> bool: + if type(module) not in NNModuleToString.safe_reprs: + return False + + try: + compile(f"mod = {module_str}", "", "exec") + except SyntaxError: + return False + return True + + @staticmethod + def _module_constructor_string( + module: torch.nn.Module, *, allow_unsafe_repr: bool = False + ) -> str | None: + module_str = repr(module) + if NNModuleToString._can_emit_module_constructor(module, module_str): + return module_str + constructor_str = ( + NNModuleToString._fake_quant_constructor(module) + or NNModuleToString._qat_conv_constructor(module) + or NNModuleToString._qat_linear_constructor(module) + ) + if constructor_str is not None: + return constructor_str + if allow_unsafe_repr: + return module_str + return None + + @staticmethod + def convert(gm: torch.fx.GraphModule, *, allow_unsafe_repr: bool = False) -> str: + from torch.nn.modules.module import _addindent + + tab = " " * 4 + + # Higher-order ops (torch.cond, torch.while_loop, ...) attach their + # subgraphs as nested GraphModule children. These have no + # constructor-style repr, so serialize each nested GraphModule as its + # own top-level class (defined before Repro so it is in scope) and + # instantiate it in __init__. Leaf nn.Modules use the constructor-string + # path below. + subgraph_classes: dict[int, str] = {} + subgraph_defs: list[str] = [] + + def register_subgraph(name_hint: str, sub: torch.fx.GraphModule) -> str: + # Reserve the name before recursing so nested/shared subgraphs are + # deduplicated by identity and cannot recurse infinitely. + if id(sub) in subgraph_classes: + return subgraph_classes[id(sub)] + class_name = f"{name_hint}_{len(subgraph_classes)}" + subgraph_classes[id(sub)] = class_name + body = emit_module_body(sub) + subgraph_defs.append(f"class {class_name}(torch.nn.Module):\n{body}") + return class_name + + def emit_module_body(module: torch.nn.Module) -> str: + model_str = ( + f"{tab}def __init__(self) -> None:\n{tab * 2}super().__init__()\n" + ) + + for module_name, child in module.named_children(): + if isinstance(child, torch.fx.GraphModule): + class_name = register_subgraph(module_name, child) + model_str += f"{tab * 2}self.{module_name} = {class_name}()\n" + continue + module_str = NNModuleToString._module_constructor_string( + child, allow_unsafe_repr=allow_unsafe_repr + ) + if module_str is None: + raise UnsupportedNNModuleError( + f"Cannot convert module to string: {child!r}" + ) + # module should be a core torch.nn.Module, so all parameters + # and buffers should be on the same device. + example_param = next(child.parameters(), None) + example_tensor = ( + example_param + if example_param is not None + else next(child.buffers(), None) + ) + if example_tensor is not None and example_tensor.device.type != "cpu": + module_str = f'{module_str}.to("{example_tensor.device}")' + model_str += f"{tab * 2}self.{module_name} = {module_str}\n" + + for buffer_name, buffer in module._buffers.items(): + if buffer is None: + continue + # Serialize full data for small buffers + if buffer.numel() <= MAX_CONSTANT_NUMEL_INLINE: + from torch._tensor_str import PRINT_OPTS + + if PRINT_OPTS.threshold < MAX_CONSTANT_NUMEL_INLINE: + raise AssertionError( + f"PRINT_OPTS.threshold ({PRINT_OPTS.threshold}) must be >= " + f"MAX_CONSTANT_NUMEL_INLINE ({MAX_CONSTANT_NUMEL_INLINE})" + ) + tensor_str = repr(buffer) + elif torch.is_floating_point(buffer): + tensor_str = ( + f"torch.randn({list(buffer.shape)}, dtype={buffer.dtype})" + ) + else: + tensor_str = f"torch.randint(1, size={list(buffer.shape)}, dtype={buffer.dtype})" + if buffer.device.type != "cpu": + tensor_str = f'{tensor_str}.to("{buffer.device}")' + model_str += ( + f"{tab * 2}self.register_buffer('{buffer_name}', {tensor_str})\n" + ) + + for param_name, param in module._parameters.items(): + if param is None: + continue + maybe_device = "" + if param.device.type != "cpu": + maybe_device = f', device="{param.device}"' + tensor_str = f"torch.nn.Parameter(torch.randn({list(param.shape)}, dtype={param.dtype}{maybe_device}))" + model_str += f"{tab * 2}self.{param_name} = {tensor_str}\n" + + model_str += f"{_addindent(module.code, len(tab))}\n" + return model_str + + repro_class = f"class Repro(torch.nn.Module):\n{emit_module_body(gm)}" + # Subgraph classes must be defined before Repro instantiates them. + return "\nfrom torch.nn import *\n" + "\n".join(subgraph_defs + [repro_class]) + + +@functools.cache # subprocess is expensive +def _cuda_system_info_comment() -> str: + if not torch.cuda.is_available(): + return "# torch.cuda.is_available()==False, no GPU info collected\n" + + model_str = "# CUDA Info: \n" + try: + if torch.version.hip is None: + cuda_version_out = subprocess.check_output(["nvcc", "--version"]) + cuda_version_lines = cuda_version_out.decode().split("\n") + comment = "".join([f"# {s} \n" for s in cuda_version_lines if s != ""]) + model_str += f"{comment}\n" + else: + model_str += "# Not searching for nvcc on ROCM setup\n" + except (OSError, subprocess.CalledProcessError): + model_str += "# nvcc not found\n" + + gpu_names = Counter( + torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count()) + ) + + model_str += "# GPU Hardware Info: \n" + for name, count in gpu_names.items(): + model_str += f"# {name} : {count} \n" + model_str += "\n" + return model_str + + +def generate_env_vars_string(*, stable_output: bool = False) -> str: + """ + Generate a string configuration for environment variables related to Dynamo, Inductor, and Triton. + """ + if stable_output: + return "# env var omitted due to stable_output=True" + + allow_list = ["TORCH", "DYNAMO", "INDUCTOR", "TRITON"] + skip_list = ["TRITON_LIBDEVICE_PATH", "TRITON_PTXAS_PATH", "TRITON_LIBCUDA_PATH"] + repro_env_vars = ["TORCHDYNAMO_REPRO_AFTER", "TORCHDYNAMO_REPRO_LEVEL"] + + def filter(key: str) -> bool: + return ( + any(string in key for string in allow_list) + and key not in skip_list + and key not in repro_env_vars + ) + + config_lines = [ + f"""os.environ['{key}'] = '{value.replace("'", '"')}'""" + for key, value in os.environ.items() + if filter(key) + ] + # Repro scripts should not recursively generate more repro scripts when run. + config_lines.extend(f"os.environ.pop('{key}', None)" for key in repro_env_vars) + config_string = "\n".join(config_lines) + return normalize_path_separator(f"""\ +import os +{config_string} + """) + + +def generate_config_string(*, stable_output: bool = False) -> str: + import torch._functorch.config + import torch._inductor.config + from torch._inductor.codegen import common + + if stable_output: + return "# config omitted due to stable_output=True" + + # Third-party Inductor backends can register their own ConfigModule. + # Repros need to replay non-default values from those modules, and + # ConfigModule.codegen_config() emits assignments but not the module import. + extra_codegen_configs = [] + for c in common.custom_backend_codegen_configs.values(): + if isinstance(c, ConfigModule): + codegen_config = c.codegen_config() + if codegen_config: + extra_codegen_configs.append(f"import {c.__name__}\n{codegen_config}") + extra_codegen_configs_str = "\n".join(extra_codegen_configs) + + experimental_config = torch.fx.experimental._config.codegen_config() # type: ignore[attr-defined] + + return f"""\ +import torch._dynamo.config +import torch._inductor.config +import torch._functorch.config +import torch.fx.experimental._config +{torch._dynamo.config.codegen_config()} +{torch._inductor.config.codegen_config()} +{torch._functorch.config.codegen_config()} +{experimental_config} +{extra_codegen_configs_str} +""" + + +def get_minifier_repro_path() -> str: + return os.path.join(minifier_dir(), "minifier_launcher.py") + + +def helper_for_dump_minify(contents: str) -> None: + minified_repro_path = get_minifier_repro_path() + log.warning("Writing minified repro to:\n%s", minified_repro_path) + + if use_buck: + BuckTargetWriter(minified_repro_path).write() + try: + with open(minified_repro_path, "w") as fd: + fd.write(contents) + + except OSError as e: + log.exception("") + raise NotImplementedError(f"Could not write to {minified_repro_path}") from e + + +class AccuracyError(Exception): + pass + + +def clone_inputs_retaining_gradness(example_inputs: Sequence[Any]) -> list[Any]: + """ + This clone inputs is different from utils clone_input. In case of minifier, + all the tensors are leaf tensors while creating a new graph. So, we set the + requires_grad field w/o checking the leafness of the tensor. + """ + cloned_inputs = clone_inputs(example_inputs) + for idx in range(len(example_inputs)): + if isinstance(cloned_inputs[idx], torch.Tensor): + cloned_inputs[idx].requires_grad_(example_inputs[idx].requires_grad) + return cloned_inputs # type: ignore[return-value] + + +def run_fwd_maybe_bwd( + gm: torch.fx.GraphModule, + args: Sequence[Any], + only_fwd: bool = False, + disable_clone: bool = False, +) -> Any: + """ + Runs a forward and possibly backward iteration for a given mod and args. + + When disable_clone is True, we will use args as-is without cloning. + This is higher fidelity but we may destroy the args in the process. + """ + from .testing import collect_results, reduce_to_scalar_loss, requires_bwd_pass + + gm = copy.deepcopy(gm) + if not disable_clone: + args = clone_inputs_retaining_gradness(args) + + if hasattr(gm, "zero_grad"): + gm.zero_grad(True) + + # TorchInductor returned callable expects lists. So, may need a boxed calling convention. + out = gm(args) if getattr(gm, "_boxed_call", False) else gm(*args) + + if only_fwd: + return out + if requires_bwd_pass(out): + loss = reduce_to_scalar_loss(out) + loss.backward() + return collect_results(gm, out, None, args) + + +def same_two_models( + gm: torch.fx.GraphModule, + opt_gm: torch.fx.GraphModule, + example_inputs: Sequence[Any], + only_fwd: bool = False, + *, + require_fp64: bool = False, + ignore_non_fp: bool = False, +) -> bool: + """ + Check two models have same accuracy. + + require_fp64: if True, raise an error if we unable to calculate the fp64 reference + ignore_non_fp: if True, do not compare outputs which are not floating point. This + is mostly useful for the minifier (which wants to avoid quantizing floating point + error into integer/boolean error) + """ + from .utils import same + + ref = run_fwd_maybe_bwd(gm, example_inputs, only_fwd) + + fp64_ref = None + if config.same_two_models_use_fp64: + try: + fp64_model, fp64_examples = cast_to_fp64( + copy.deepcopy(gm), clone_inputs_retaining_gradness(example_inputs) + ) + fp64_ref = run_fwd_maybe_bwd(fp64_model, fp64_examples, only_fwd) + except Exception: + if require_fp64: + raise RuntimeError( # noqa: B904 + "Could not generate fp64 outputs, workaround with torch._dynamo.config.same_two_models_use_fp64 = False" + ) + log.warning("Could not generate fp64 outputs") + + try: + res = run_fwd_maybe_bwd(opt_gm, example_inputs, only_fwd) + except Exception: + # This means that the minified graph is bad/exposes a different problem. + # As we are checking accuracy here, lets log the exception and return True. + log.exception( + "While minifying the program in accuracy minification mode, " + "ran into a runtime exception which is likely an unrelated issue." + " Skipping this graph." + ) + return True + + passing = same( + ref, + res, + fp64_ref, + tol=config.repro_tolerance, + equal_nan=True, + ignore_non_fp=ignore_non_fp, + ) + return passing + + +def cast_dtype_args_to_fp64(model: torch.fx.GraphModule) -> torch.fx.GraphModule: + for node in model.graph.nodes: + if ( + node.op == "call_function" + and node.target is torch.ops.prims.convert_element_type.default + ): + if len(node.args) != 2: + raise AssertionError( + f"Expected node to have 2 args, got {len(node.args)}" + ) + if is_float_dtype(node.args[1]) and node.args[1] != torch.float64: + node.args = (node.args[0], torch.float64) + if node.op == "call_function": + dtype = node.kwargs.get("dtype") + if dtype is not None and is_float_dtype(dtype): + new_kwargs = dict(node.kwargs) + new_kwargs["dtype"] = torch.float64 + node.kwargs = new_kwargs + + model.graph.lint() + model.recompile() + return model + + +def cast_to( + dtype: torch.dtype, model: torch.fx.GraphModule, inputs: list[Any] +) -> tuple[torch.fx.GraphModule, list[Any]]: + from torch.utils._pytree import tree_map + + model = model.to(dtype) + if dtype == torch.float64: + # If casting to fp64 for accuracy comparison, we need to + # replace dtype arguments embedded in the graph with fp64 + model = cast_dtype_args_to_fp64(model) + + inputs = tree_map( + lambda x: x.to(dtype) + if isinstance(x, torch.Tensor) and x.is_floating_point() + else x, + inputs, + ) + return model, inputs + + +def cast_to_fp64( + model: torch.fx.GraphModule, inputs: list[Any] +) -> tuple[torch.fx.GraphModule, list[Any]]: + return cast_to(torch.float64, model, inputs) + + +def backend_accuracy_fails( + gm: torch.fx.GraphModule, + example_inputs: Sequence[Any], + compiler_fn: Callable[[torch.fx.GraphModule, list[Any]], torch.fx.GraphModule], + only_fwd: bool = False, + *, + require_fp64: bool = False, + ignore_non_fp: bool = False, +) -> bool: + try: + compiled_gm = compiler_fn( + copy.deepcopy(gm), clone_inputs_retaining_gradness(example_inputs) + ) + return not same_two_models( + gm, + compiled_gm, + example_inputs, + only_fwd, + require_fp64=require_fp64, + ignore_non_fp=ignore_non_fp, + ) + except Exception: + # This means that the minified graph is bad/exposes a different problem. + # As we are checking accuracy here, lets log the exception and return False. + log.exception( + "While minifying the program in accuracy minification mode, " + "ran into a runtime exception which is likely an unrelated issue." + " Skipping this graph" + ) + return False + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# REPRO SUPPORT CODE +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +# Helper functions for computing what the default values of tensor +# values should be. These all coincide with factory functions, e.g., torch.empty + + +def _stride_or_default( + stride: torch._prims_common.StrideType | None, + *, + shape: torch._prims_common.ShapeType, +) -> torch._prims_common.StrideType: + return stride if stride is not None else utils.make_contiguous_strides_for(shape) + + +def _mk_defaulter(d: T) -> Callable[[T | None], T]: + return lambda x: x if x is not None else d + + +_dtype_or_default = _mk_defaulter(torch.float32) +_device_or_default = _mk_defaulter(torch.device("cpu")) +_storage_offset_or_default = _mk_defaulter(0) +_requires_grad_or_default = _mk_defaulter(False) +_is_leaf_or_default = _mk_defaulter(False) + + +class NopInputReader: + def __init__(self) -> None: + self.total = 0 + + def storage( + self, + storage_hash: str | None, + nbytes: int, + *, + device: torch._prims_common.DeviceLikeType | None = None, + dtype_hint: torch.dtype | None = None, + ) -> None: + self.total += 1 + + def tensor(self, *args: Any, **kwargs: Any) -> torch.Tensor | None: + pass + + def symint(self, *args: Any, **kwargs: Any) -> int | None: + pass + + def const(self, name: str) -> None: + pass + + def unsupported(self, name: str) -> None: + pass + + def generator(self, device_type: str, device_index: int) -> None: + pass + + def opaque(self, script_class_name: str) -> None: + self.total += 1 + + +# TODO: Support bundling the entire repro into a zip file for ease of +# transferring around +class InputReader: + def __init__( + self, save_dir: str | None = None, *, pbar: tqdm | None = None + ) -> None: + # If None, we will generate random data instead. It's important + # to natively support this use case as it will allow people to + # share repros without including the real data, if the problem + # reproduces even on random data. + if save_dir is None: + log.warning("no save_dir specified, will generate random data") + self.store = ContentStoreReader(save_dir) if save_dir is not None else None + self.args: list[Any] = [] + self.pbar = pbar + + def storage( + self, + storage_hash: str | None, + nbytes: int, + *, + device: torch._prims_common.DeviceLikeType | None = None, + dtype_hint: torch.dtype | None = None, + ) -> UntypedStorage: + if self.pbar is not None: + self.pbar.update(1) + device = _device_or_default(device) # type: ignore[arg-type] + dtype_hint = _dtype_or_default(dtype_hint) + if self.store is not None and storage_hash is not None: + try: + storage = self.store.read_storage(storage_hash) + except FileNotFoundError: + pass + else: + if device != storage.device: + log.warning("device mismatch: %s != %s", device, storage.device) + # TODO: transfer it to the right device? But failing this + # way would be very mysterious! Would have been better + # not to store device in the serialized format... + return storage + warn_once(f"could not load {storage_hash}, generating random data instead") + shape = (nbytes // dtype_hint.itemsize,) + stride = _stride_or_default(None, shape=shape) + return rand_strided(shape, stride, dtype_hint, device).untyped_storage() + + def tensor( + self, + storage: UntypedStorage, + shape: torch._prims_common.ShapeType, + stride: torch._prims_common.StrideType | None = None, + *, + storage_offset: int | None = None, + dtype: torch.dtype | None = None, + requires_grad: bool | None = None, + is_leaf: bool | None = None, + **metadata: Any, + ) -> torch.Tensor: + stride = _stride_or_default(stride, shape=shape) + storage_offset = _storage_offset_or_default(storage_offset) + dtype = _dtype_or_default(dtype) + is_leaf = _is_leaf_or_default(is_leaf) + requires_grad = _requires_grad_or_default(requires_grad) + t = torch.tensor( + [], dtype=dtype, device=storage.device, requires_grad=requires_grad + ) + with torch.no_grad(): + t.set_(storage, storage_offset, shape, stride) + if not is_leaf: + # Fake up some autograd history in a very naughty way + with torch.enable_grad(): + t = t.clone(memory_format=torch.preserve_format) + with torch.no_grad(): + t.set_(storage, storage_offset, shape, stride) + if torch._subclasses.meta_utils.safe_is_leaf(t) != is_leaf: + raise AssertionError( + f"Tensor leaf status mismatch: safe_is_leaf(t) = " + f"{torch._subclasses.meta_utils.safe_is_leaf(t)}, expected {is_leaf}" + ) + torch._utils.set_tensor_metadata(t, metadata) + self.args.append(t) + return t # for BC + + def symint(self, val: Any, *, expr: str | None = None) -> Any: + self.args.append(val) + if expr is not None: + if not hasattr(self, "symint_exprs"): + self.symint_exprs: dict[int, str] = {} + self.symint_exprs[len(self.args) - 1] = expr + return val # for BC + + def const(self, name: str) -> None: + self.args.append(None) + + def unsupported(self, name: str) -> None: + self.args.append(None) + + def generator(self, device_type: str, device_index: int) -> Any: + device = torch.device(device_type, device_index) + gen = torch.Generator(device=device) + self.args.append(gen) + return gen + + def opaque(self, script_class_name: str) -> None: + self.args.append(None) + + +# Here is our writer strategy: +# 1. We will stream all of the inputs to disk +# 2. You can now deterministically randomize the inputs, or reload +# the inputs from disk +# 3. You can YOLO run the script without the inputs, in which case +# we'll fill the inputs with random data and pray. This is the +# legacy behavior, but it's also useful if you want to find out +# if we're so broken even random inputs trigger it +# 4. We could offer an in process "check if the randomized thing +# works too" but this is delicate so we don't do it + + +def _serialize_storage_nbytes(nbytes: int | torch.SymInt) -> str: + if isinstance(nbytes, torch.SymInt): + from torch.fx.experimental.symbolic_shapes import SymExprPrinter + + return SymExprPrinter().doprint(nbytes.node.expr) + return repr(nbytes) + + +class InputWriter: + def __init__(self, save_dir: str | None, *, stable_hash: bool = False) -> None: + self._lines: list[str] = [] + # TODO: consider ensuring tensor and storage counters line up? + self.storage_counter = itertools.count() + self.save_dir = save_dir + self.store = ( + ContentStoreWriter(save_dir, stable_hash=stable_hash) + if save_dir is not None + else None + ) + self.seen_storages: dict[StorageWeakRef, str] = {} + + def lines(self) -> list[str]: + r = [ + "def load_args(reader):", + ] + r.extend(f" {l}" for l in self._lines) + # In case we need to change the internal format of load_args + # in an FC-breaking way + r.append("load_args._version = 0") + return r + + # Storages are untyped, but we need to initialize them with data if + # we don't have the real data, so we give a hint saying what kind + # of initialization may be appropriate + # + # If we had a FakeTensor, device_hint tells us what device should be + def storage( + self, + untyped_storage: UntypedStorage, + *, + device_hint: torch._prims_common.DeviceLikeType | None = None, + dtype_hint: torch.dtype | None = None, + ) -> str: + ws = StorageWeakRef(untyped_storage) + v = self.seen_storages.get(ws) + if v is not None: + return v + v = f"buf{next(self.storage_counter)}" + maybe_dtype_hint = "" + if _dtype_or_default(None) != _dtype_or_default(dtype_hint): + maybe_dtype_hint = f", dtype_hint={dtype_hint!r}" + # TODO: being optional on device is kind of pointless as the default + # is CPU but most repros we care about are CUDA + maybe_device = "" + device = untyped_storage.device + if device.type == "meta": + if device_hint is None: + raise AssertionError( + "device_hint must be provided when storage device is 'meta'" + ) + device = device_hint # type: ignore[assignment] + if _device_or_default(None) != device: + maybe_device = f", device={device!r}" + nbytes = untyped_storage.nbytes() + nbytes_source = _serialize_storage_nbytes(nbytes) + storage_hash = None + if self.store is not None and untyped_storage.device.type != "meta": + storage_hash = self.store.write_storage(untyped_storage) + self._lines.append( + f"{v} = reader.storage({storage_hash!r}, {nbytes_source}{maybe_device}{maybe_dtype_hint})" + ) + self.seen_storages[ws] = v + return v + + def tensor(self, name: str, t: torch.Tensor) -> None: + from torch.fx.experimental.symbolic_shapes import statically_known_true, sym_eq + + storage = self.storage( + t.untyped_storage(), dtype_hint=t.dtype, device_hint=t.device + ) + args = [] + # NB: this is positional, must come first + if not statically_known_true( + sym_eq(_stride_or_default(None, shape=t.shape), t.stride()) + ): + args.append(str(tuple(t.stride()))) + if _dtype_or_default(None) != t.dtype: + args.append(f"dtype={t.dtype!r}") + if not statically_known_true( + _storage_offset_or_default(None) == t.storage_offset() + ): + args.append(f"storage_offset={t.storage_offset()!r}") + tensor_metadata = torch._utils.get_tensor_metadata(t) + if tensor_metadata: + args.extend(f"{k}={v!r}" for k, v in tensor_metadata.items()) + if _requires_grad_or_default(None) != t.requires_grad: + args.append(f"requires_grad={t.requires_grad!r}") + is_leaf = torch._subclasses.meta_utils.safe_is_leaf(t) + if _is_leaf_or_default(None) != is_leaf: + args.append(f"is_leaf={is_leaf!r}") + self._lines.append( + "reader.tensor(" + + ", ".join([storage, str(tuple(t.shape)), *args]) + + f") # {name}" + ) + + def unsupported(self, name: str, arg: Any) -> None: + # NB: Try hard not to /print/ a tensor, that will be very slow + self._lines.append( + f"reader.unsupported({name!r}) # unsupported type for dumping: {type(arg)}" + ) + # Best effort dump as much useful stuff we can lol, in case you want + # to repair the repro + if isinstance(arg, (list, tuple)): + self._lines.append('"""') + for i, a in enumerate(arg): + name_i = f"{name}[{i}]" + if isinstance(a, torch.Tensor): + self.tensor(name_i, a) + elif isinstance(a, (int, torch.SymInt)): + self.symint(name_i, a) + else: + self.unsupported(name_i, a) + self._lines.append('"""') + + # write out that the arg was filtered out as it is constant + def const(self, name: str) -> None: + self._lines.append( + f"reader.const({name!r}) # {name}, filtered out during compilation" + ) + + # TODO: this doesn't actually symint atm + def symint(self, name: str, val: Any) -> None: + if isinstance(val, torch.SymInt): + expr_str = str(val.node.expr) + hint = val.node.hint + self._lines.append(f"reader.symint({hint!r}, expr={expr_str!r}) # {name}") + else: + self._lines.append(f"reader.symint({val!r}) # {name}") + + def generator(self, name: str, arg: torch._C.Generator) -> None: + device = arg.device + self._lines.append( + f"reader.generator({device.type!r}, {device.index!r}) # {name}" + ) + + def opaque(self, name: str, script_class_name: str) -> None: + self._lines.append(f"reader.opaque({script_class_name!r}) # {name}") + + +def aot_graph_input_parser( + func: Callable[[list[Tensor]], list[Tensor]], + device: str = "cuda", + sym_shapes: dict[str, int] | None = None, + default_sym_shape: int | None = None, +) -> dict[str, Any]: + """ + Takes in a function which has been printed with print_readable() and constructs kwargs to run it. + + Handles Tensor inputs, Symints, and a graph module which might have tensor constants. + + Consider a function `forward` defined as follows: + + def forward(self, primals_1: "f32[1001, 6]", primals_2: "f32[s0]", primals_3: "Sym(s0)",): + _tensor_constant0: "i64[4190]" = self._tensor_constant0 + # Further implementation + + kwargs = aot_graph_input_parser(forward) + forward(**kwargs) + """ + + from torch.utils._dtype_abbrs import dtype_abbrs + + dtype_map: dict[str, torch.dtype] = { + value: key for key, value in dtype_abbrs.items() + } + dtype_pattern: str = "|".join(dtype_abbrs.values()) + + # Extracting the source code from the function + source = inspect.getsource(func) + + # Regular expressions + tensor_assignment_regex = rf"(_tensor_constant\d+): \"({dtype_pattern})\[\s*(.*?)\s*\]\" = self\.(_tensor_constant\d+)" + tensor_regex = rf"({dtype_pattern})\[\s*(.*?)\s*\]" + sym_shape_regex = r"Sym\((s\d+)\)" + + class TensorContainer: + "Container for tensors as attributes" + + # Dictionary for tensors from annotations + kwargs: dict[str, Any] = {} + + sym_shapes_dict: dict[str, int] = sym_shapes or {} + + def get_sym_int(symint: str) -> int: + torch._check( + symint in sym_shapes_dict or default_sym_shape is not None, + lambda: f"{symint} not in symbolic_shapes and default sym shape not passed in", + ) + return sym_shapes_dict.get(symint, default_sym_shape) # type: ignore[return-value] + + def gen_tensor(shape: torch._prims_common.ShapeType, dtype: torch.dtype) -> Tensor: + # Resolve symbolic shapes to concrete values + resolved_shape = [] + dynamic_dims = [] + for i, dim in enumerate(shape): + dim = dim.strip() # type: ignore[attr-defined] + if "s" in dim: + s = get_sym_int(dim) + resolved_shape.append(s) + dynamic_dims.append(i) + else: + if dim: + resolved_shape.append(int(dim)) + + constructor = torch.randn if dtype.is_floating_point else torch.zeros + out = constructor(resolved_shape, dtype=dtype, device=device) # type: ignore[call-arg] + for d in dynamic_dims: + torch._dynamo.mark_dynamic(out, d) + return out + + # Parse function annotations for tensor generation + annotations = func.__annotations__ + for param, annotation in annotations.items(): + # Skip 'return' annotation + if param == "return": + continue + + match = re.search(tensor_regex, annotation) + if match: + data_type, shape_str = match.groups() + shape = tuple(shape_str.split(",")) + dtype = dtype_map[data_type] + # pyrefly: ignore [bad-argument-type] + kwargs[param] = gen_tensor(shape, dtype) + + match = re.search(sym_shape_regex, annotation) + if match: + kwargs[param] = get_sym_int(match.group(1)) + + if "self" in inspect.signature(func).parameters: + container = TensorContainer() + kwargs["self"] = container + for match in re.finditer(tensor_assignment_regex, source): + attr_name, data_type, shape_str, _ = match.groups() + shape = tuple(shape_str.split(",")) + dtype = dtype_map[data_type] + # pyrefly: ignore [bad-argument-type] + setattr(container, attr_name, gen_tensor(shape, dtype)) + + return kwargs + + +def profile_to_file(filename: str) -> Callable[[T], T]: + """ + Decorator to cProfile a given function and save the result to disk on process exit. + + Args: + filename: filename to save profile to + """ + prof = cProfile.Profile() + filename = os.path.abspath(os.path.expanduser(filename)) + + def decorator(fn: Any) -> Any: + @functools.wraps(fn) + def wrapper(*args: Any, **kwargs: Any) -> Any: + prof.enable() + try: + return fn(*args, **kwargs) + finally: + prof.disable() + + return wrapper + + def save_it() -> None: + prof.dump_stats(filename) + sys.stderr.write( + textwrap.dedent( + f"""\ + Wrote profile to {filename}, view with: + + snakeviz {filename} + + """ + ) + ) + + atexit.register(save_it) + return decorator diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/decorators.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..91e4ac517c4f4826418d2ea0d82114ecdedd9881 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/decorators.py @@ -0,0 +1,1890 @@ +""" +This module provides decorators and utilities for controlling TorchDynamo's behavior during compilation. +""" + +import functools +import inspect +import weakref +from collections.abc import Callable +from dataclasses import dataclass +from types import TracebackType +from typing import Any, overload, Protocol, TYPE_CHECKING, TypeVar +from typing_extensions import ParamSpec + +import torch +import torch.utils._pytree as pytree +from torch._custom_class_base import CustomClassBase +from torch._vendor.packaging.version import InvalidVersion, Version +from torch.compiler import is_compiling +from torch.utils._contextlib import _DecoratorContextManager +from torch.utils._python_dispatch import is_traceable_wrapper_subclass +from torch.utils._typing_utils import not_none + +from .._utils_internal import justknobs_check +from . import trace_rules, variables +from .comptime import comptime +from .eval_frame import ( + _set_stance, + DisableContext, + DynamoStance, + innermost_fn, + RunOnlyContext, + skip_code, + StanceStr, +) +from .external_utils import ( + get_nonrecursive_disable_wrapper, + wrap_dunder_call_ctx_manager, +) +from .utils import ( + _get_cudagraph_override, + _get_error_on_graph_break, + _set_cudagraph_override, + _set_error_on_graph_break, + allow_lru_cache_wrapper_trace_without_warning, + is_function, + is_lru_cache_wrapped_function, +) + + +justknobs_check._dynamo_marked_constant = True # type: ignore[attr-defined] + +if TYPE_CHECKING: + from types import FunctionType + + from torch._C._dynamo.eval_frame import ( # noqa: F401 + reset_code, + set_eval_frame, + set_guard_complete_hook, + set_guard_error_hook, + unsupported, + ) + + from .variables import VariableTracker +else: + for name in dir(torch._C._dynamo.eval_frame): + if name.startswith("__"): + continue + globals()[name] = getattr(torch._C._dynamo.eval_frame, name) + + +_P = ParamSpec("_P") +_R = TypeVar("_R") +FuncType = Callable[..., Any] +F = TypeVar("F", bound=FuncType) + + +def run(fn: Callable[_P, _R] | None = None) -> Any: + """Don't do any dynamic compiles, just use prior optimizations""" + if fn is not None: + fn = innermost_fn(fn) + if not callable(fn): + raise AssertionError("fn must be callable") + return RunOnlyContext()(fn) + return RunOnlyContext() + + +def disable(fn=None, recursive=True, *, reason=None, wrapping=True): # type: ignore[no-untyped-def] + """ + Decorator to disable TorchDynamo + + If recursive=True, Dynamo is completely skipped on the decorated function + frame as well as the recursively invoked functions. + + If recursive=False, Dynamo skips frames associated with the function code, + but still process recursively invoked frames. + + If reason is provided, it will be printed when Dynamo attempts to trace the disabled function. + """ + if recursive: + if fn is not None: + fn = innermost_fn(fn) + if not callable(fn): + raise AssertionError("fn must be callable") + return DisableContext(msg=reason, wrapping=wrapping)(fn) + return DisableContext(msg=reason, wrapping=wrapping) + else: + + def wrap(fn: Callable[_P, _R]) -> Callable[_P, _R]: + fn = innermost_fn(fn) + if not callable(fn): + raise AssertionError("fn must be callable") + + nonrecursive_disable_wrapper = get_nonrecursive_disable_wrapper(fn) + nonrecursive_disable_wrapper._torchdynamo_disable = True # type: ignore[attr-defined] + nonrecursive_disable_wrapper._torchdynamo_disable_msg = reason # type: ignore[attr-defined] + nonrecursive_disable_wrapper._torchdynamo_orig_callable = fn # type: ignore[attr-defined] + nonrecursive_disable_wrapper._torchdynamo_wrapper_id = id( # type: ignore[attr-defined] + nonrecursive_disable_wrapper + ) + nonrecursive_disable_wrapper._torchdynamo_disable_recursive = False # type: ignore[attr-defined] + return nonrecursive_disable_wrapper + + if fn is None: + return wrap + return wrap(fn) + + +_nonrecursive_disable_wrapper_code = disable(lambda: None, recursive=False).__code__ # type: ignore[attr-defined] +skip_code(_nonrecursive_disable_wrapper_code) + + +def skip(fn: Callable[_P, _R] | None = None) -> Callable[..., Any]: + """ + Skip frames associated with the function code, but still process recursively + invoked frames + """ + if fn is None: + return skip + fn = innermost_fn(fn) + if not callable(fn): + raise AssertionError("fn must be callable") + skip_code(fn.__code__) + fn._torchdynamo_disable = True # type: ignore[attr-defined] + return fn + + +class set_stance(_DecoratorContextManager): + """ + Decorator, context manager, function to set the current stance of the compiler. + + Stances documented in corresponding function in torch/compiler/__init__.py + """ + + _dynamo_forbidden = True + + def __init__( + self, + stance: StanceStr = "default", + *, + skip_guard_eval_unsafe: bool = False, + force_backend: str | Callable[..., Any] | None = None, + ) -> None: + if force_backend is not None and stance != "default": + raise RuntimeError("non-default stance cannot have force_backend set") + + self.stance = DynamoStance(stance, skip_guard_eval_unsafe, force_backend) + self.prev = _set_stance(self.stance) + + def __call__(self, fn: F) -> F: + _set_stance(self.prev) + wrapper = super().__call__(fn) + # forbid wrapper in graph + wrapper._dynamo_forbidden = True # type: ignore[attr-defined] + return wrapper + + def __enter__(self) -> None: + _set_stance(self.stance) + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + _set_stance(self.prev) + + def clone(self) -> "set_stance": + return self.__class__(self.stance.stance, force_backend=self.stance.backend) + + +def assume_constant_result(fn): # type: ignore[no-untyped-def] + fn._dynamo_marked_constant = True # type: ignore[attr-defined] + return fn + + +def allow_in_graph(fn): # type: ignore[no-untyped-def] + """ + Tells the compiler frontend (Dynamo) to skip symbolic introspection of the function + and instead directly write it to the graph when encountered. + + See :func:`torch.compiler.allow_in_graph`'s docstring for the full documentation + + WARNING: this API can be a footgun, please read the documentation carefully. + """ + if isinstance(fn, (list, tuple)): + return [allow_in_graph(x) for x in fn] + if not callable(fn): + raise AssertionError("allow_in_graph expects a callable") + if trace_rules.lookup_callable(fn) != variables.TorchInGraphFunctionVariable: + fn_id = id(fn) + trace_rules._disallowed_callable_ids.remove(fn_id) + trace_rules._allowed_callable_ids.add(fn_id) + + # Avoid id reuse which creates subtle bugs. + def deregister() -> None: + trace_rules._allowed_callable_ids.remove(fn_id) + + weakref.finalize(fn, deregister) + return fn + + +# pyrefly: ignore [implicit-any] +def _check_mutually_exclusive_decorators(fn: Callable, decorator_name: str) -> None: + mutually_exclusive = { + "leaf_function": trace_rules.is_leaf_function, + "nonstrict_trace": trace_rules.is_nonstrict_trace_callable, + } + + for other_name, check_fn in mutually_exclusive.items(): + if other_name != decorator_name and check_fn(fn): + first, second = sorted([decorator_name, other_name]) + raise ValueError( + f"Function {fn} cannot be both marked as @{first} and " + f"@{second}. Please use only one decorator." + ) + + +def nonstrict_trace(traceable_fn: Callable[_P, _R]) -> Callable[_P, _R]: + """ + Decorator to mark a function as nonstrict-traceable for dynamo. + + See :func:`torch.compiler.nonstrict_trace` for the full documentation. + """ + if not callable(traceable_fn): + raise AssertionError("nonstrict_trace expects a callable") + + _check_mutually_exclusive_decorators(traceable_fn, "nonstrict_trace") + + @functools.wraps(traceable_fn) + def wrapped(*args: _P.args, **kwargs: _P.kwargs) -> _R: + return traceable_fn(*args, **kwargs) + + wrapped_id = id(wrapped) + + # This line allows us to reuse much of the `allow_in_graph` impl. + trace_rules._allowed_callable_ids.add(wrapped_id) + + # This line allows us to diverge the impl from `allow_in_graph`. + trace_rules._nonstrict_trace_callable_ids.add(wrapped_id) + + # Avoid id reuse which creates subtle bugs. + def deregister() -> None: + trace_rules._allowed_callable_ids.remove(wrapped_id) + trace_rules._nonstrict_trace_callable_ids.remove(wrapped_id) + + weakref.finalize(wrapped, deregister) + + return wrapped + + +def _invoke_leaf_function_python( + real_impl: Callable[..., Any], + fake_impl: Callable[..., Any], + args: tuple[Any, ...], + kwargs: dict[str, Any], + mutates_args: frozenset[str] | None = None, + hook_fn: Callable[..., Any] | None = None, + hook_fake_fn: Callable[..., Any] | None = None, +) -> Any: + """Call invoke_leaf_function HOP directly from Python. + + This enables @leaf_function to work with make_fx + without relying on Dynamo to intercept the call. + """ + from torch._higher_order_ops.invoke_leaf_function import ( + _LeafCallable, + convert_modules_to_states, + invoke_leaf_function, + make_leaf_function_wrappers, + store_makefx_modules, + ) + + captured_modules: list[torch.nn.Module] = [] + seen_module_ids: dict[int, int] = {} # id(module) -> position in captured_modules + for val in pytree.tree_flatten( + (args, kwargs), is_leaf=lambda x: isinstance(x, torch.nn.Module) + )[0]: + if isinstance(val, torch.nn.Module) and id(val) not in seen_module_ids: + seen_module_ids[id(val)] = len(captured_modules) + captured_modules.append(val) + + global_indices = store_makefx_modules(captured_modules) + module_to_index = { + mod_id: global_indices[pos] for mod_id, pos in seen_module_ids.items() + } + + processed = convert_modules_to_states((args, kwargs), module_to_index) + flat_args, input_spec = pytree.tree_flatten(processed) + + # Single-element mutable list so the wrappers can write back the output + # TreeSpec. Read captured_out_spec[0] after the wrappers have been called. + captured_out_spec: list[pytree.TreeSpec | None] = [None] + wrapped_real, wrapped_fake = make_leaf_function_wrappers( + real_impl, fake_impl, captured_out_spec + ) + + real_fn_callable = _LeafCallable(wrapped_real) + fake_fn_callable = _LeafCallable(wrapped_fake) + + if hook_fn is not None: + real_fn_callable._leaf_hook_real_fn = hook_fn # type: ignore[attr-defined] + real_fn_callable._leaf_hook_fake_fn = hook_fake_fn # type: ignore[attr-defined] + + mutated_flat_indices = "" + if mutates_args: + from torch._higher_order_ops.invoke_leaf_function import ( + _resolve_mutated_flat_indices, + ) + + mutated_flat_indices = _resolve_mutated_flat_indices( + real_impl, mutates_args, len(flat_args), input_spec + ) + + flat_out = invoke_leaf_function( + real_fn_callable, fake_fn_callable, input_spec, mutated_flat_indices, *flat_args + ) + + if captured_out_spec[0] is None: + raise AssertionError("captured_out_spec was not set by leaf function wrappers") + return pytree.tree_unflatten(flat_out, captured_out_spec[0]) + + +@overload +def leaf_function(fn: Callable[_P, _R]) -> Callable[_P, _R]: ... + + +@overload +def leaf_function( + *, mutates_args: set[str] +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ... + + +def leaf_function( + fn: Callable[_P, _R] | None = None, *, mutates_args: set[str] | None = None +) -> Callable[_P, _R] | Callable[[Callable[_P, _R]], Callable[_P, _R]]: + """ + Decorator to mark a function as a leaf function for :func:`torch.compile`. + + A leaf function appears as an opaque operation in the compiled graph. During + compilation, Dynamo and AOT autograd do not trace into it. At runtime, the + original eager Python code is executed directly. + + Quick Start: + Suppose we want to log per-sample statistics during the forward pass:: + + def compute_and_log_stats(x): + stats = x.mean(dim=1) + logger.info(f"Per-sample means: {stats}") + return (stats,) + + With ``torch.compile(..., fullgraph=True)``, this fails because + ``logger.info`` causes a graph break. To fix it, follow the steps below: + + 1. Decorate your function with ``@leaf_function`` + 2. Define a shape-inference function using ``@your_fn.register_fake`` + + Concrete implementation:: + + >>> import logging + >>> import torch + >>> from torch._dynamo.decorators import leaf_function + >>> + >>> logging.basicConfig(level=logging.INFO) + >>> logger = logging.getLogger(__name__) + >>> + >>> @leaf_function + ... def compute_and_log_stats(x): + ... stats = x.mean(dim=1) # Shape: (x.shape[0],) + ... logger.info(f"Per-sample means: {stats}") + ... return (stats,) + ... + >>> @compute_and_log_stats.register_fake + ... def compute_and_log_stats_fake(x): + ... # Match the output shape: (x.shape[0],) + ... return (x.new_empty(x.shape[0]),) + ... + >>> def fn(x): + ... return compute_and_log_stats(x) + ... + >>> x = torch.randn(3, 4) + >>> compiled_fn = torch.compile(fn, backend="aot_eager", fullgraph=True) + >>> out = compiled_fn(x)[0] + + When to Use: + Use ``leaf_function`` when you need eager execution semantics that tracing + cannot preserve: + + - **Non-traceable code**: The function consists of code that Dynamo or + AOT Autograd cannot trace. + - **Runtime side effects**: Operations that must happen exactly once per call + at runtime (e.g., logging, external library calls). + + If your function has a static computation graph and no runtime side effects, + prefer :func:`allow_in_graph` or :func:`nonstrict_trace` instead. They allow AOT autograd + to trace through and potentially optimize the code. + + Usage: + **Inputs and Outputs**: + - Both inputs and outputs must use pytree-compatible types. + Tensors, Python primitives (int, float, bool, str), and built-in containers + (list, tuple, dict) are supported by default. + + Note: We recommend leaf_functions only accept and return tensors. Though primitive + types (int, float, bool, str) are supported in inputs and outputs, they may cause + surprising behavior: primitive inputs are guarded and may trigger recompilation, + while primitive output values are captured from the fake implementation at compile time and + remain fixed for all subsequent executions. Even though the real function runs + at runtime, its primitive return values are silently replaced with the compile-time + values from the fake implementation. + + Example:: + + # BAD: primitive output varies at runtime + counter = 0 + + + @leaf_function + def count_calls(x): + global counter + counter += 1 + return (x, counter) + + + @count_calls.register_fake + def count_calls_fake(x): + return (x, 999) # placeholder value + + + # At runtime: real function runs (counter increments to 1, 2, 3, ...) + # But returned count is always 999 (from fake implementation at compile time) + + - User-defined classes must be registered via :func:`torch.utils._pytree.register_pytree_node` + or :func:`torch.utils._pytree.register_dataclass`. + + - :class:`torch.nn.Module` can also be passed as input; its parameters and buffers + are tracked for autograd. The module must exist outside the compile region. + Running the module multiple times must not modify its parameters, buffers, or attributes. + + **register_fake (required)**: + Since the function body is not traced, you must + provide a shape-inference function via ``@fn.register_fake``. It runs at compile + time with FakeTensor inputs (tensors with no data, only metadata) and must + satisfy the following requirements: + + - Must have the same input and output signature (e.g., same pytree structure, same tensor metadata + such as shapes, dtypes, device, strides) as the real function + - Must be runnable with FakeTensor inputs + - Must only use its explicit arguments (no closures over tensors or modules) + + Note: The input and output signature must be determinable at compile time. + If your function's output structure depends on runtime values, adjust the leaf function + boundary until outputs become predictable. + + To validate that your fake implementation matches the real function's outputs, set + ``torch._dynamo.config.leaf_function_validate_outputs = True``. + + **register_multi_grad_hook (optional)**: + You can register a backward hook via ``@fn.register_multi_grad_hook`` + to run code when gradients have been computed for all requires_grad + tensor inputs during backward. The hook fires exactly once per + backward pass. The hook receives only the gradients of the leaf + function's requires_grad tensor inputs, in the order they appeared; + non-tensor arguments and tensors without ``requires_grad`` are not + forwarded to the hook. The hook must return ``None``. The hook is + called as a leaf function itself, so it is also opaque to the + compiler. + + Example:: + + >>> @leaf_function + ... def debug_log(t): + ... return None + ... + >>> @debug_log.register_fake + ... def debug_log_fake(t): + ... return None + ... + >>> @debug_log.register_multi_grad_hook + ... def debug_log_hook(t_grad): + ... print(f"[bwd] norm={t_grad.norm().item()}") + ... + >>> x = torch.randn(4, requires_grad=True) + >>> debug_log(x) # no assignment needed + >>> (x * 2).sum().backward() + [bwd] norm=... + + Limitations: + Currently, inductor backend and :func:`torch.export.export` are not yet supported. + + Training / Autograd: + Training is supported automatically if your leaf function is differentiable + in eager mode (e.g., it's implemented with PyTorch ops, :class:`torch.autograd.Function`, + or differentiable custom ops). + + **Restriction**: Calling ``.backward()`` *inside* the leaf function is not + supported. + + **Escaped gradients check**: If the leaf function closes over a tensor with + ``requires_grad=True``, gradients will not flow back to it (only explicit inputs + receive gradients). To detect such cases, set + ``torch._dynamo.config.leaf_function_check_escaped_gradients = True``. + When enabled, a ``RuntimeError`` is raised with details about the escaped tensors. + + Internally, inputs and outputs are detached from the outer autograd graph at the + leaf function boundary. The leaf function builds its own local autograd + graph. In backward, gradients propagate through this local graph to the + leaf function's inputs. If a :class:`torch.nn.Module` is passed in as input, the gradients + will also flow back to its parameters and buffers. + + How leaf_function Works: + Understanding this helps avoid pitfalls: + + 1. **Compilation**: Dynamo and AOT autograd do not trace into the leaf function. + Only your fake implementation runs during compilation to determine output signatures, + shapes, and dtypes. The real function runs at runtime as eager Python. + + 2. **Isolation**: Mutations to shared state (globals, closures) may not be + visible across the boundary between leaf functions and compiled regions. Pass data + explicitly as function arguments and return results as outputs. + + Dangerous Patterns: + These patterns may cause silent incorrectness or errors: + + - **Side effects between leaf functions and compiled regions**: Mutations to + Python state inside a leaf function may not be visible to the compiled + region, and vice versa. The compiled graph may reorder or eliminate + operations in ways that break assumptions about side effect ordering. + + Bad:: + + # Compiled region + self.counter += 1 + y = my_leaf_fn(self, x) # Don't depend on self.counter inside leaf_fn + + y = my_leaf_fn(self, x) + result = self.state # Don't depend on state mutated by leaf_fn + + Logging/printing inside the leaf function is fine since it doesn't affect + correctness. + + - **In-place mutations on inputs**: Undeclared in-place mutations on input + tensors are detected and will raise an error. Either declare mutations via + ``mutates_args`` or clone inputs before mutating. + + Bad:: + + @leaf_function + def my_leaf_fn(x): + x.add_(1) # Will raise: "Undeclared in-place mutation" + return (x,) + + Good:: + + @leaf_function(mutates_args={"buf"}) + def my_leaf_fn(x, buf): + buf.add_(1) # OK: declared in mutates_args + return (x + buf,) + + For pytree args (lists, tuples, dicts of tensors), use the parameter name + to declare mutation on all contained tensors:: + + @leaf_function(mutates_args={"buffers"}) + def my_leaf_fn(x, buffers): + for buf in buffers: + buf.add_(1) # OK: 'buffers' declared in mutates_args + return (x + sum(buffers),) + + Or use bracket notation for fine-grained control:: + + @leaf_function(mutates_args={"buffers[0]"}) + def my_leaf_fn(x, buffers): + buffers[0].add_(1) # OK: 'buffers[0]' declared + return (x + buffers[1],) # buffers[1] is not cloned + + - **Closures in fake implementation**: Tensors or modules captured from enclosing scopes + in the fake implementation will cause compilation errors. The real function can + close over them if they don't require gradient, but the fake implementation must + only use its arguments. + + Bad:: + + weight = torch.randn(3, 3) + + + @leaf_function + def my_leaf_fn(x): + return (x @ weight,) + + + @my_leaf_fn.register_fake + def my_leaf_fn_fake(x): + return (x @ weight,) # Error: weight used in fake implementation + + Good:: + + weight = torch.randn(3, 3) + + + @leaf_function + def my_leaf_fn(x): + return (x @ weight,) # OK: real function can use closure + + + @my_leaf_fn.register_fake + def my_leaf_fn_fake(x): + return (x @ torch.empty_like(x),) # OK: uses only args + + Example:: + Wrapping a linear function with logging as a leaf_function. Gradients + flow back because the inner operations are differentiable:: + + >>> import torch + >>> import torch.nn.functional as F + >>> from torch._dynamo.decorators import leaf_function + >>> + >>> @leaf_function + ... def custom_forward(linear, x): + ... # Logging at runtime + ... print(f"Input: shape={x.shape}, mean={x.mean().item():.4f}") + ... out = F.linear(x, linear.weight, linear.bias) + ... print(f"Output: shape={out.shape}, norm={out.norm().item():.4f}") + ... return (out,) + ... + >>> @custom_forward.register_fake + ... def custom_forward_fake(linear, x): + ... # Return tensor with correct shape: (batch, out_features) + ... return (x.new_empty(x.shape[0], linear.weight.shape[0]),) + ... + >>> class MyModel(torch.nn.Module): + ... def __init__(self): + ... super().__init__() + ... self.linear = torch.nn.Linear(10, 20) + ... def forward(self, x): + ... return custom_forward(self.linear, x) + ... + >>> model = MyModel() + >>> compiled = torch.compile(model, backend="aot_eager", fullgraph=True) + >>> x = torch.randn(32, 10, requires_grad=True) + >>> out = compiled(x)[0] + >>> out.sum().backward() # Gradients flow to model.linear.weight/bias and x + + Args: + fn: The function being decorated. + mutates_args: Set of Python expressions (as strings) identifying arguments + that the function mutates in-place. Each string is evaluated against + the function's parameters. Examples: ``'buf'`` for a plain tensor, + ``'model.running_mean'`` for an nn.Module buffer, + ``'buffers'`` to mark all tensors in a list, ``'buffers[0]'`` for a + specific element, ``'state["key"]'`` for a dict entry. + """ + if fn is None: + return functools.partial(leaf_function, mutates_args=mutates_args) + + from . import trace_rules + + _check_mutually_exclusive_decorators(fn, "leaf_function") + + if mutates_args: + import inspect + import re + + params = set(inspect.signature(fn).parameters) + for expr in mutates_args: + root = re.split(r"[.\[]", expr, maxsplit=1)[0] + if root not in params: + raise ValueError( + f"mutates_args expression '{expr}' refers to parameter '{root}', " + f"which is not a parameter of '{fn.__name__}'. " + f"Available parameters: {', '.join(params)}" + ) + + @functools.wraps(fn) + def inner(*args: _P.args, **kwargs: _P.kwargs) -> _R: + if inner._torchdynamo_leaf_fake_fn is None: # type: ignore[attr-defined] + raise ValueError( + f"leaf_function '{getattr(fn, '__name__', fn)}' " + "requires a fake implementation. Please provide one using the @.register_fake " + "decorator. See the leaf_function docstring for details." + ) + + return _invoke_leaf_function_python( + fn, # pyrefly: ignore [bad-argument-type] + # pyrefly: ignore [bad-argument-type] + inner._torchdynamo_leaf_fake_fn, + args, + kwargs, + mutates_args=inner._torchdynamo_leaf_mutates_args, # pyrefly: ignore [missing-attribute] + hook_fn=inner._torchdynamo_leaf_hook_fn, # type: ignore[attr-defined] + hook_fake_fn=inner._torchdynamo_leaf_hook_fake_fn, # type: ignore[attr-defined] + ) # type: ignore[attr-defined] + + inner._torchdynamo_leaf_real_fn = fn # type: ignore[attr-defined] + inner._torchdynamo_leaf_fake_fn = None # type: ignore[attr-defined] + inner._torchdynamo_leaf_mutates_args = ( # pyrefly: ignore [missing-attribute] + frozenset(mutates_args) if mutates_args else frozenset() + ) # type: ignore[attr-defined] + inner._torchdynamo_leaf_hook_fn = None # type: ignore[attr-defined] + inner._torchdynamo_leaf_hook_fake_fn = None # type: ignore[attr-defined] + + # Follow nonstrict_trace implementation + wrapped_id = id(inner) + trace_rules._allowed_callable_ids.add(wrapped_id) + trace_rules._leaf_function_ids.add(wrapped_id) + + def deregister() -> None: + trace_rules._allowed_callable_ids.remove(wrapped_id) + trace_rules._leaf_function_ids.remove(wrapped_id) + + weakref.finalize(inner, deregister) + + def register_fake_setter(fake_fn: Callable[..., Any]) -> Callable[..., Any]: + inner._torchdynamo_leaf_fake_fn = fake_fn # type: ignore[attr-defined] + return inner + + inner.register_fake = register_fake_setter # type: ignore[attr-defined] + + def register_hook_setter(hook_fn: Callable[..., Any]) -> Callable[..., Any]: + inner._torchdynamo_leaf_hook_fn = hook_fn # type: ignore[attr-defined] + inner._torchdynamo_leaf_hook_fake_fn = lambda *args, **kwargs: None # type: ignore[attr-defined] + return inner + + inner.register_multi_grad_hook = register_hook_setter # type: ignore[attr-defined] + + return inner + + +def _disallow_in_graph_helper(throw_if_not_allowed: bool) -> Callable[..., Any]: + def inner(fn: Any) -> Any: + if isinstance(fn, (list, tuple)): + return [disallow_in_graph(x) for x in fn] + if not callable(fn): + raise AssertionError("disallow_in_graph expects a callable") + if ( + throw_if_not_allowed + and trace_rules.lookup_callable(fn) + != variables.TorchInGraphFunctionVariable + and trace_rules.lookup(fn) != variables.TorchInGraphFunctionVariable + ): + raise RuntimeError( + "disallow_in_graph is expected to be used on an already allowed callable (like torch.* ops). " + "Allowed callables means callables that TorchDynamo puts as-is in the extracted graph." + ) + trace_rules._allowed_callable_ids.remove(id(fn)) + trace_rules._nonstrict_trace_callable_ids.remove(id(fn)) + trace_rules._disallowed_callable_ids.add(id(fn)) + return fn + + return inner + + +def disallow_in_graph(fn: Callable[..., Any]) -> Any: + """ + Customize which functions TorchDynamo will exclude in the generated + graph and force a graph break on. + :: + + torch._dynamo.disallow_in_graph(torch.sub) + + + @torch._dynamo.optimize(...) + def fn(a): + x = torch.add(x, 1) + x = torch.sub(x, 1) + x = torch.add(x, 1) + return x + + + fn(...) + + Will break the graph on `torch.sub`, and give two graphs each with a + single `torch.add()` op. + """ + return _disallow_in_graph_helper(throw_if_not_allowed=True)(fn) + + +@_disallow_in_graph_helper(throw_if_not_allowed=False) +def graph_break(msg: str = "") -> None: + """Force a graph break""" + + +# NOTE: primarily used for internal debugging purposes! +@_disallow_in_graph_helper(throw_if_not_allowed=False) +def skip_frame(msg: str = "") -> None: + """Force a skipped frame""" + + +@_disallow_in_graph_helper(throw_if_not_allowed=False) +def step_unsupported(msg: str = "") -> None: + """Force a step unsupported graph break, which results in compiling + the traced FX graph so far, then skipping the rest of the frame. + In order to get expected behavior, there should be at least 2 ops + and a part of the code not contained in any try/with blocks.""" + + +def forbid_in_graph(fn: Any) -> Any: + """ + Customize which functions TorchDynamo will assert are not present while tracing. + + If you want a graph break on this function instead, use disallow_in_graph. + TODO(voz): We now have allow_in_graph, disallow_in_graph, forbid_in_graph - some more robust + documentation would not be amiss. + """ + if isinstance(fn, (list, tuple)): + return [forbid_in_graph(x) for x in fn] + if not callable(fn): + raise AssertionError("forbid_in_graph applies only to callables") + # pyrefly: ignore [missing-attribute] + fn._dynamo_forbidden = True + return fn + + +def substitute_in_graph( + original_fn: Callable[_P, _R], + *, + can_constant_fold_through: bool = False, + skip_signature_check: bool = False, + # type that is embedded in the Python interpreter + is_embedded_type: bool = False, # internal use only +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: + """ + Register a polyfill handler for a function, usually a C function from the C extension, to be + used in place of the original function when inlining the original function in the graph. + + .. note:: + + The polyfill handler is only used when inlining the original function. It is not used when + the original function is called directly. In the eager mode, the decorated function calls + the performant C function rather than the polyfill handler. + + The polyfill handler is a function that will be called in place of the original function when + inlining the original function. The polyfill handler should have the same signature and the same + behavior as the original function. + + Args: + original_fn (callable): The original function, usually a C function, to register a polyfill + handler for. + can_constant_fold_through (bool, optional): Whether the polyfill handler can be constant + folded through. That is, if the polyfill handler is a pure function and its arguments + are constant, the result of the polyfill handler can be constant folded during the + compilation. Defaults to ``False``. + skip_signature_check (bool, optional): Whether to skip the signature check between the + original function and the polyfill handler. Defaults to ``False``. + + Returns: + A decorator that registers the polyfill handler for the original function. + + Example:: + + >>> # xdoctest: +SKIP("conflict with the tests: duplicate polyfill handlers") + >>> import operator + >>> operator.indexOf([1, 2, 3, 4, 5], 3) + 2 + >>> torch.compile(operator.indexOf, fullgraph=True)([1, 2, 3, 4, 5], 3) + Traceback (most recent call last): + ... + torch._dynamo.exc.Unsupported: ... + + >>> @torch.compiler.substitute_in_graph(operator.indexOf) + ... def indexOf(a, b, /): + ... for i, item in enumerate(a): + ... if item is b or item == b: + ... return i + ... raise ValueError("sequence.index(x): x not in sequence") + >>> + >>> torch.compile(operator.indexOf, fullgraph=True)([1, 2, 3, 4, 5], 3) + 2 + """ + if not is_function(original_fn) and not ( + is_embedded_type and inspect.isclass(original_fn) + ): + raise TypeError( + f"substitute_in_graph expects a function but got {type(original_fn)!r}" + ) + if is_embedded_type: + if not inspect.isclass(original_fn): + raise TypeError( + f"substitute_in_graph expects a class but got {type(original_fn)!r}" + ) + + from .variables.builder import ITERTOOLS_POLYFILLED_TYPE_IDS, ITERTOOLS_TYPE_IDS + + if id(original_fn) in ITERTOOLS_TYPE_IDS: + ITERTOOLS_POLYFILLED_TYPE_IDS.add(id(original_fn)) + + def wrapper(traceable_fn: Callable[_P, _R]) -> Callable[_P, _R]: + if not is_function(traceable_fn): + raise TypeError( + f"@substitute_in_graph(...) expects a function but got {type(traceable_fn)!r}" + ) + + if not skip_signature_check: + try: + original_sig = inspect.signature(original_fn) + except ValueError: + pass + else: + traceable_sig = inspect.signature(traceable_fn) + + def sig_ident( + sig: inspect.Signature, + ) -> tuple[tuple[str, ...], set[str], dict[str, Any]]: + # Ignore annotations for parameters and return type + return ( + tuple( + p.name + for p in sig.parameters.values() + if ( + p.kind + not in { + p.KEYWORD_ONLY, + # the name of *args and **kwargs is not important + p.VAR_POSITIONAL, + p.VAR_KEYWORD, + } + ) + ), + { + p.name + for p in sig.parameters.values() + if p.kind == p.KEYWORD_ONLY + }, + { + p.name: p.default + for p in sig.parameters.values() + # the name of *args and **kwargs is not important + if p.kind not in {p.VAR_POSITIONAL, p.VAR_KEYWORD} + }, + ) + + wildcard_sig = inspect.signature(lambda *args, **kwargs: None) + + if ( + sig_ident(original_sig) != sig_ident(traceable_sig) + and sig_ident(original_sig) != sig_ident(wildcard_sig) + and sig_ident(traceable_sig) != sig_ident(wildcard_sig) + ): + raise TypeError( + f"Signature mismatch between {original_fn} and {traceable_fn}: " + f"{original_sig} != {traceable_sig}" + ) + + from torch._dynamo.guards import GuardBuilder + from torch._dynamo.trace_rules import ( + _polyfilled_function_ids, + get_torch_obj_rule_map, + ) + from torch._dynamo.variables import PolyfilledFunctionVariable + from torch._dynamo.variables.builder import VariableBuilder + + id_dispatch_map = VariableBuilder._id_dispatch() + if id(original_fn) in id_dispatch_map: + raise ValueError( + f"Duplicate dispatch rule for {original_fn}: " + "already registered in VariableBuilder's id dispatch map" + ) + + if id(original_fn) in _polyfilled_function_ids: + raise ValueError(f"Duplicate polyfilled object {original_fn}") + + rule_map: dict[Any, type[VariableTracker]] = get_torch_obj_rule_map() + if original_fn in rule_map: + raise ValueError( + f"Duplicate object {original_fn} with different rules: " + f"{PolyfilledFunctionVariable}, {rule_map[original_fn]}" + ) + + polyfill_handlers: dict[Callable[..., Any], FunctionType] + polyfill_handlers = PolyfilledFunctionVariable._get_polyfill_handlers() + if original_fn in polyfill_handlers: + raise ValueError( + f"Duplicate polyfill handlers for {original_fn}: " + f"already handled by {polyfill_handlers[original_fn]}" + ) + + # Need to wrap the function because we may cannot assign __torch_dynamo_polyfill__ to a + # C++ function. + @functools.wraps(traceable_fn) + def wrapped(*args: _P.args, **kwargs: _P.kwargs) -> _R: + return original_fn(*args, **kwargs) + + def dispatch_fn( + self: VariableBuilder, value: Callable[_P, _R] + ) -> PolyfilledFunctionVariable: + if inspect.isclass(value): + guard_type = GuardBuilder.CLASS_MATCH + elif inspect.ismodule(value): + guard_type = GuardBuilder.MODULE_MATCH + else: + guard_type = GuardBuilder.ID_MATCH + guards = self.install_guards(guard_type) + if guards is None: + raise AssertionError("install_guards returned None") + return PolyfilledFunctionVariable( + value, + source=self.source, + **guards, + ) + + id_dispatch_map[id(original_fn)] = id_dispatch_map[id(wrapped)] = dispatch_fn + _polyfilled_function_ids.add(id(original_fn)) + _polyfilled_function_ids.add(id(wrapped)) + rule_map[original_fn] = rule_map[wrapped] = PolyfilledFunctionVariable + polyfill_handlers[original_fn] = polyfill_handlers[wrapped] = wrapped # type: ignore[assignment] + + wrapped.__torch_dynamo_original__ = original_fn # type: ignore[attr-defined] + wrapped.__torch_dynamo_polyfill__ = traceable_fn # type: ignore[attr-defined] + wrapped.__torch_dynamo_can_constant_fold_through__ = can_constant_fold_through # type: ignore[attr-defined] + + return wrapped # type: ignore[return-value] + + return wrapper + + +# Helper function to flatten a tensor subclass and apply a function to +# all inner tensors that match the outer dim. Used to reduce duplication +# across the various marking APIs. +def _apply_func_to_inner_tensors_of_same_dim( + func: Callable[..., Any], t: object, *args: Any, **kwargs: Any +) -> None: + if not is_traceable_wrapper_subclass(t): + raise AssertionError(f"Expected a traceable wrapper subclass, got {type(t)}") + + attrs, _ctx = t.__tensor_flatten__() + if not isinstance(t, torch.Tensor): + raise AssertionError(f"Expected a Tensor, got {type(t)}") + for attr in attrs: + match getattr(t, attr): + case torch.Tensor() as inner: + if inner.dim() == t.dim(): + func(inner, *args, **kwargs) + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + + +@dataclass(frozen=True, slots=True) +class _DimRange: + """ + This represents a dimension of a tensor and the corresponding + min and max values it can take. Don't create this + class directly; instead, use :func:`mark_dynamic`. + """ + + dim: int + min: int + max: int + + +@forbid_in_graph +def mark_unbacked( + t: Any, + index: int | list[Any] | tuple[Any], + hint_override: int | None = None, + strict: bool = False, + specialize_on: list[Any] | None = None, + shape_id: str | None = None, + min: int | None = None, + max: int | None = None, +) -> None: + """ + Mark a tensor as having an unbacked dimension. This changes the semantics of operations: + - The size of the specified dimension will always be reported as not equal to zero or one. + - Assertions on this index will be turned into runtime asserts. + - Attempting to get the real value of this dimension will raise an exception. + - In effect, this dimension is treated as data-dependent (its value is unknown). + + Args: + t (Any): The tensor to mark as having an unbacked dimension. + index (int or list/tuple of int): The dimension(s) to mark as unbacked. Can be a single + integer or a list/tuple of integers. Calls are additive: mark_unbacked(x, 0) followed + by mark_unbacked(x, 1) marks both dims. + hint_override (Optional[int], default=None): An optional integer to override the size hint for this dimension. + This is only used by the inductor backend for size hint queries, such as during autotuning. + NOTE: changing hint_override values will cause FxGraphCache misses, since hint overrides + affect inductor codegen decisions and are included in the cache key via + ShapeEnv.var_to_hint_override. + strict (bool, default=False): If True, an error will be raised if the unbacked dimension is specialized. + By default (strict=False), specialization is allowed and will proceed without error. + specialize_on (Optional[list[Any]], default=None): A list of specialization criteria (e.g., lambdas) for this dimension. + If provided, Dynamo will generate specialized compiled regions for each criterion in addition to a generic trace. + shape_id (Optional[str], default=None): An optional identifier to group unbacked dimensions together. + All unbacked dimensions with the same shape_id will share the same unbacked symbol. This is useful when multiple tensors + are known to have the same batch size at runtime. A runtime assertion is added + to ensure this property at runtime. + min (Optional[int], default=None): Minimum value constraint for this dimension. + If provided, a runtime check will be added to ensure the dimension is >= min. + max (Optional[int], default=None): Maximum value constraint for this dimension. + If provided, a runtime check will be added to ensure the dimension is <= max. + """ + if torch.distributed.is_available() and isinstance( + t, torch.distributed.tensor.DTensor + ): + # apply on inner tensor sizes/strides + mark_unbacked(t._local_tensor, index, shape_id=shape_id) + else: + # You could have copied the mark_dynamic behavior but I'm not convinced + # it's what you want + if is_traceable_wrapper_subclass(t): + raise AssertionError("not implemented yet") + + if isinstance(index, int): + if strict: + if not hasattr(t, "_dynamo_strict_unbacked_indices"): + t._dynamo_strict_unbacked_indices = set() + + t._dynamo_strict_unbacked_indices.add(index) + t._has_dynamo_dim_marking = True # type: ignore[attr-defined] + return + + if not hasattr(t, "_specialized_on"): + # pyrefly: ignore [implicit-any] + t._specialize_on = {} + + if not hasattr(t, "_dynamo_unbacked_indices"): + t._dynamo_unbacked_indices = set() + + if not hasattr(t, "_dynamo_hint_overrides"): + # pyrefly: ignore [implicit-any] + t._dynamo_hint_overrides = {} + + if hint_override: + t._dynamo_hint_overrides[index] = hint_override + + if min is not None or max is not None: + if not hasattr(t, "_dynamo_unbacked_bounds"): + # pyrefly: ignore [implicit-any] + t._dynamo_unbacked_bounds = {} + t._dynamo_unbacked_bounds[index] = (min, max) + + if shape_id is not None: + if not hasattr(t, "_dynamo_shape_ids"): + # pyrefly: ignore [implicit-any] + t._dynamo_shape_ids = {} + t._dynamo_shape_ids[index] = shape_id + + # FX tracers don't respect @forbid_in_graph and choke on the following error since it passes in proxies: + # TypeError: 'Attribute' object does not support item assignment + + if isinstance(t._specialize_on, dict): + t._specialize_on[index] = specialize_on if specialize_on is not None else [] + + t._dynamo_unbacked_indices.add(index) + t._has_dynamo_dim_marking = True # type: ignore[attr-defined] + return + + if not isinstance(index, (list, tuple)): + raise AssertionError( + f"Expected index to be int, list, or tuple, got {type(index)}" + ) + for i in index: + mark_unbacked(t, i, shape_id=shape_id, min=min, max=max) + + +@forbid_in_graph +def mark_dynamic( + t: Any, + index: int | list[Any] | tuple[Any], + *, + hint_override: int | None = None, + min: int | None = None, + max: int | None = None, + specialize_on: list[Any] | None = None, +) -> None: + """ + Mark a tensor as having a dynamic dim and set corresponding min and max range for the dim. + + [Note - on the state of mark_dynamic] + + The behavior of having a dynamic dimension on a tensor is governed by a few factors: + + 1) torch._dynamo.config dynamic_shapes True or False. + a) dynamic_shapes=True - dynamic_shapes must be True for mark_dynamic to work. + a) dynamic_shapes=False - This config will raise an exception when used in conjunction with + mark_dynamic. We will eventually support this. + + 2) If the dimension is fully constrained - as in, it does not allow more than a single value + in both eager (torch.compile, torch._dynamo.optimize) mode and export mode (torch._dynamo.export), + we will raise an error + + 3) If the dimension is partially constrained - allowing at least 2 values but not the full unbounded + range of shapes, in eager we will pass it through, but export will raise an error. + + 4) Attempts to trace this function will explicitly raise. As such, all calls to mark_dynamic must be made + before torch.compile. + + 5) If hint_override is passed, the hint_override for the specified dimension will replace the provided value + from the first example input as the official size hint. Note: changing hint_override values will cause + FxGraphCache misses, since hint overrides affect inductor codegen decisions (autotuning, reduction + strategy, etc.) and are included in the cache key via ShapeEnv.var_to_hint_override. + + 6) If specialize_on is passed in, we will perform a single generic Dynamo trace followed by + multiple specialized compilations in addition to a single generic compilation. NB: For now we only support + per dimension specialization, or in other words we do not generate a cross product of specializations. + At runtime, we will dispatch to a specialized compiled region if the input matches the specialization criteria. + + For example: + mark_dynamic(..., specialize_on=[ + lambda x: x == 8, + lambda x: x == 16 + ]) + + This approach results in one Dynamo trace and two backend compilations. When the input dimension equals 8 or 16 + at runtime, execution will be directed to the specialized compiled region. Performance measurements indicate + 2-8x speedups depending on the specific specialization and model architecture. + """ + if is_traceable_wrapper_subclass(t): + # default behavior: mirror mark_dynamic() on all inner tensors with same dim as t + # TODO: Make this configurable via a supported public API + _apply_func_to_inner_tensors_of_same_dim( + mark_dynamic, t, index, min=min, max=max + ) + + if isinstance(index, int): + if not hasattr(t, "_dynamo_dynamic_indices"): + t._dynamo_dynamic_indices = set() + + t._dynamo_dynamic_range = set() + + # pyrefly: ignore [implicit-any] + t._dynamo_hint_overrides = {} + + if not hasattr(t, "_specialize_on"): + # pyrefly: ignore [implicit-any] + t._specialize_on = {} + + if hint_override: + t._dynamo_hint_overrides[index] = hint_override + # TODO(voz): Should we bounds check? + + t._dynamo_dynamic_indices.add(index) + t._dynamo_dynamic_range.add(_DimRange(index, min, max)) # type: ignore[arg-type] + t._has_dynamo_dim_marking = True # type: ignore[attr-defined] + + # FX tracers don't respect @forbid_in_graph and choke on the following error since it passes in proxies: + # TypeError: 'Attribute' object does not support item assignment + + if isinstance(t._specialize_on, dict): + t._specialize_on[index] = specialize_on if specialize_on is not None else [] + + return + + if not isinstance(index, (list, tuple)): + raise AssertionError( + f"Expected index to be int, list, or tuple, got {type(index)}" + ) + for i in index: + mark_dynamic(t, i, min=min, max=max, specialize_on=specialize_on) + + +@forbid_in_graph +def maybe_mark_dynamic(t: Any, index: int | list[Any] | tuple[Any]) -> None: + """ + Mark a tensor as having a dynamic dim, but don't enforce it (i.e., if this + dimension ends up getting specialized, don't error). + """ + if is_traceable_wrapper_subclass(t): + # default behavior: mirror maybe_mark_dynamic() on all inner tensors with same dim as t + # TODO: Make this configurable via a supported public API + _apply_func_to_inner_tensors_of_same_dim(maybe_mark_dynamic, t, index) + + if isinstance(index, int): + if not hasattr(t, "_dynamo_weak_dynamic_indices"): + t._dynamo_weak_dynamic_indices = set() + # TODO(voz): Should we bounds check? + + t._dynamo_weak_dynamic_indices.add(index) + t._has_dynamo_dim_marking = True # type: ignore[attr-defined] + return + + if not isinstance(index, (list, tuple)): + raise AssertionError( + f"Expected index to be int, list, or tuple, got {type(index)}" + ) + for i in index: + maybe_mark_dynamic(t, i) + + +def mark_static(t: Any, index: int | list[Any] | tuple[Any] | None = None) -> None: + """ + Mark a tensor as having a static dim or mark a nn module class as static. + + For tensors + =========== + This will prevent us from attempting to compile it dynamically + when dynamic=True; this can improve trace-time performance. + + This has lower precedence than mark_dynamic. + + Unlike mark_dynamic, this can be done inside a graph, in which case it + induces specialization on the tensor. + + For nn.Module classes + ===================== + For static nn.Module classes, TorchDynamo assumes that the module instance + attributes will not be modified after compilation. This will ensure that + TorchDynamo keeps integer attributes CONSTANT and not symints. + + From TorchDynamo implementation side, the instances of static-marked + nn.Module class will be converted to UnspecializedBuiltinNNModuleVariable, + which have the same properties. + + Note that we still have to guard on the attributes, because different + instances of the nn.Module can have different values of the attributes. The + key point here is that the attributes are static. + """ + if is_compiling(): + if index is None: + for s in t.size(): + comptime.force_static(s) + else: + comptime.force_static(t.size(index)) + return + + if is_traceable_wrapper_subclass(t): + # default behavior: mirror mark_static() on all inner tensors with same dim as t + # TODO: Make this configurable via a supported public API + _apply_func_to_inner_tensors_of_same_dim(mark_static, t, index) + + if not isinstance(t, torch.Tensor) and issubclass(t, torch.nn.Module): + t._dynamo_marked_static = True + # pyrefly: ignore [bad-return] + return t + + if not isinstance(t, torch.Tensor): + raise TypeError( + f"mark_static expects a tensor/nn.Module class but received {type(t)}" + ) + + if isinstance(index, int): + if not hasattr(t, "_dynamo_static_indices"): + t._dynamo_static_indices = set() # type: ignore[attr-defined] + # TODO(voz): Should we bounds check? + t._dynamo_static_indices.add(index) # type: ignore[attr-defined] + t._has_dynamo_dim_marking = True # type: ignore[attr-defined] + elif index is None: + for i in range(t.dim()): + mark_static(t, i) + else: + if not isinstance(index, (list, tuple)): + raise AssertionError( + f"Expected index to be int, list, or tuple, got {type(index)}" + ) + for i in index: + mark_static(t, i) + + +@forbid_in_graph +def mark_static_address(t: Any, guard: bool = False) -> None: + """ + Marks an input tensor whose address should be treated as constant across calls to the + same dynamo-compiled function. This indicates to cudagraphs that an extra allocation + is not needed for this input. The data_ptr will be guarded if guard=True, and cause a full + recompile if the data_ptr changes. Note: If this address changes, cudagraphs will re-record + if guard=False. + """ + if not isinstance(t, torch.Tensor): + raise TypeError(f"mark_static_address expects a tensor but received {type(t)}") + + if guard: + t._dynamo_static_input_type = "guarded" # type: ignore[attr-defined] + else: + t._dynamo_static_input_type = "unguarded" # type: ignore[attr-defined] + + +def _patch_einops_symint_compat(einops_mod: Any) -> None: + """Backport the SymInt lru_cache fix from einops 0.7.0 into einops <= 0.6.1.""" + for name in ("_reconstruct_from_shape", "_prepare_transformation_recipe"): + cached = getattr(einops_mod, name) + uncached = cached.__wrapped__ + + def make_wrapper(cached_fn: Any, uncached_fn: Any) -> Any: + @functools.wraps(cached_fn) + def wrapper(*args: Any, **kwargs: Any) -> Any: + try: + return cached_fn(*args, **kwargs) + except TypeError: + return uncached_fn(*args, **kwargs) + + return wrapper + + setattr(einops_mod, name, make_wrapper(cached, uncached)) + + +_EINOPS_DYNAMO_TRACING_MIN_VERSION = Version("0.8.2") +# Known pure parser/shape helpers in einops 0.8.2. Keep this explicit so +# unrelated or future lru_cache wrappers continue through the normal warning path. +_EINOPS_LRU_CACHE_WRAPPER_ALLOWLIST = ( + ( + "einops.einops", + ( + "_reconstruct_from_shape", + "_prepare_transformation_recipe", + "_compactify_pattern_for_einsum", + ), + ), + ("einops.packing", ("analyze_pattern",)), +) + + +def _einops_supports_dynamo_tracing(einops_mod: Any) -> bool: + try: + return Version(einops_mod.__version__) >= _EINOPS_DYNAMO_TRACING_MIN_VERSION + except InvalidVersion: + return False + + +def _allow_lru_cache_trace_without_warning_for_einops() -> None: + import importlib + + for module_name, attr_names in _EINOPS_LRU_CACHE_WRAPPER_ALLOWLIST: + try: + module = importlib.import_module(module_name) + except ImportError: + continue + + for attr_name in attr_names: + obj = getattr(module, attr_name, None) + if is_lru_cache_wrapped_function(obj): + allow_lru_cache_wrapper_trace_without_warning(obj) + + +# Dynamo can trace through einops 0.8.2+ directly (no allow_in_graph needed). +# Older versions still need the allow_in_graph registration below. +def _allow_in_graph_einops() -> None: + import einops + + if _einops_supports_dynamo_tracing(einops): + if hasattr(einops, "einops") and hasattr(einops.einops, "get_backend"): + # trigger backend registration up front to avoid a later guard failure + # that would otherwise cause a recompilation + einops.rearrange(torch.empty(1), "i -> i") + # einops uses lru_cache for pure library-internal recipe helpers. Mark + # only those wrappers so general lru_cache warnings are unchanged. + _allow_lru_cache_trace_without_warning_for_einops() + return + + try: + # requires einops > 0.6.1, torch >= 2.0 + from einops._torch_specific import ( # type: ignore[attr-defined] # noqa: F401 + _ops_were_registered_in_torchdynamo, + ) + + # einops > 0.6.1 will call the op registration logic as it is imported. + except ImportError: + # einops <= 0.6.1 doesn't handle unhashable SymInt in its lru_cache'd + # helpers. Backport the try/except TypeError fallback from einops 0.7.0+ + # so allow_in_graph works during fake tensor validation. + _patch_einops_symint_compat(einops.einops) # type: ignore[attr-defined] + allow_in_graph(einops.rearrange) + allow_in_graph(einops.reduce) + if hasattr(einops, "repeat"): + allow_in_graph(einops.repeat) # available since einops 0.2.0 + if hasattr(einops, "einsum"): + allow_in_graph(einops.einsum) # available since einops 0.5.0 + if hasattr(einops, "pack"): + allow_in_graph(einops.pack) # available since einops 0.6.0 + if hasattr(einops, "unpack"): + allow_in_graph(einops.unpack) # available since einops 0.6.0 + + +# Note: this carefully avoids eagerly import einops. +trace_rules.add_module_init_func("einops", _allow_in_graph_einops) + + +class _ConfigPatchProtocol(Protocol): + """The config.patch() context manager object wrapped by DynamoConfigPatchProxy.""" + + changes: dict[str, Any] + + def __enter__(self) -> None: ... + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: ... + + +# Proxy class for torch._dynamo.config patching - so dynamo can identify context managers/decorators +# created by patch_dynamo_config, compared to ones created by a raw torch._dynamo.config.patch. +class DynamoConfigPatchProxy: + def __init__(self, config_patch: _ConfigPatchProtocol) -> None: + self.config_patch = config_patch + + @property + def changes(self) -> dict[str, Any]: + return self.config_patch.changes + + # Decorator implementation that simply sets up `self` as a context manager. + # Placed in external_utils so that we can trace through it. + __call__ = wrap_dunder_call_ctx_manager + + def __enter__(self) -> None: + return self.config_patch.__enter__() + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + return self.config_patch.__exit__(exc_type, exc_val, exc_tb) + + +# Criteria for patchable config: +# - Config values must be constants (i.e. int, float, str, bool, None). +# - in particular, NO list, set, dict. +# - Traceable config patches are only useful for configs that change dynamo behavior +# from symbolic_convert and below. +# - e.g. patching recompile_limit won't really do anything. +# - For patching configs that affect Dynamo behavior above symbolic_convert, +# ensure that Dynamo behaves soundly even if tracing is done with different config. +# - e.g. be careful if patching guard-related configs as configs may have changed +# between guard creation and evaluation. +_allowed_config_patches = ( + "verbose", + "verify_correctness", + "rewrite_assert_with_torch_assert", + "capture_scalar_outputs", + "allow_unspec_int_on_nn_module", + "skip_torchrec", + "dont_skip_tracing", + "nested_graph_breaks", +) + +from . import config + + +for name in _allowed_config_patches: + if not hasattr(config, name): + raise AssertionError(f"nonexistent config: {name}") +del config + + +def _patch_dynamo_config_check(changes: dict[str, Any]) -> None: + for k, v in changes.items(): + if k not in _allowed_config_patches: + raise ValueError( + f"patch_dynamo_config does not support patching config {k}" + ) + if not torch._dynamo.utils.is_safe_constant(v): + raise ValueError( + f"patch_dynamo_config does not support patching config {k} " + f"with non-safe-constant value {v}" + ) + + +# TODO: also implement nonrecursive patch_dynamo_config/dont_skip_tracing. +# Unlike config.patch, we also need to accept tuple as input in order to +# deal with context manager reconstruction. +def patch_dynamo_config( + arg1: str | dict[str, Any] | tuple[tuple[str, Any], ...] | None = None, + arg2: Any = None, + **kwargs: Any, +) -> DynamoConfigPatchProxy: + """ + A wrapper around torch._dynamo.config.patch that can be traced by Dynamo to + temporarily change config values DURING tracing. + + See _allowed_config_patches for the list of allowed config patches. + + Arguments are the same as with torch._dynamo.config.patch. + + Can be used as a decorator or a context manager. + + User code SHOULD NOT MODIFY the return value of this function. + + WARNING: changing Dynamo config during tracing can lead to unpredictable tracing behavior! + Proceed only as advised! + """ + if isinstance(arg1, tuple): + arg1 = dict(arg1) + config_patch = torch._dynamo.config.patch(arg1, arg2, **kwargs) + _patch_dynamo_config_check(config_patch.changes) + # check for valid patching using config_patch.changes + return DynamoConfigPatchProxy(config_patch) + + +@overload +def dont_skip_tracing(fn: None = None) -> DynamoConfigPatchProxy: ... + + +@overload +def dont_skip_tracing(fn: Callable[_P, _R]) -> Callable[_P, _R]: ... + + +def dont_skip_tracing(fn: Any | None = None) -> Any: + """ + Context manager/decorator to trace into functions intentionally marked by developers to be skipped + when tracing. + + This decorator will also apply to recursively invoked functions. + """ + ctx = patch_dynamo_config(dont_skip_tracing=True) + if fn: + return ctx(fn) + return ctx + + +@overload +def disable_nested_graph_breaks(fn: None = None) -> DynamoConfigPatchProxy: ... + + +@overload +def disable_nested_graph_breaks(fn: Callable[_P, _R]) -> Callable[_P, _R]: ... + + +def disable_nested_graph_breaks(fn: Any | None = None) -> Any: + """ + Context manager/decorator to disable nested graph breaks when tracing + this function and any nested functions. Used when nested graph breaks + is causing problems. + """ + ctx = patch_dynamo_config(nested_graph_breaks=False) + if fn: + return ctx(fn) + return ctx + + +class ErrorOnGraphBreakDecoratorContextManager: + def __init__(self, error_on_graph_break: bool) -> None: + self.error_on_graph_break = error_on_graph_break + self.prev_error_on_graph_break: list[bool | None] = [] + + __call__ = wrap_dunder_call_ctx_manager + + def __enter__(self) -> None: + current_error_on_graph_break = _get_error_on_graph_break() + if current_error_on_graph_break != self.error_on_graph_break: + self.prev_error_on_graph_break.append(current_error_on_graph_break) + _set_error_on_graph_break(self.error_on_graph_break) + else: + self.prev_error_on_graph_break.append(None) + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + prev_error_on_graph_break = self.prev_error_on_graph_break.pop() + if prev_error_on_graph_break is not None: + _set_error_on_graph_break(prev_error_on_graph_break) + + +def error_on_graph_break( + error_on_graph_break: bool, +) -> ErrorOnGraphBreakDecoratorContextManager: + """ + Context manager/decorator to toggle torch.compile's `error_on_graph_break` setting at compile time. + + If `fullgraph` is set, then `error_on_graph_break` does nothing + (i.e. `fullgraph = True` takes higher precedence). If `fullgraph` is False, then + `error_on_graph_break` determines whether `torch.compile` throws an error upon + encountering a graph break, or attempts to continue tracing. + + `error_on_graph_break` can be toggled during compile time with this decorator to allow graph breaks in some + compiled regions but not others. One key difference from `fullgraph` is that `error_on_graph_break = True` + does NOT guarantee that a single graph is captured from the compiled function. + + The default value of torch.compile's `error_on_graph_break` setting is False. + """ + return ErrorOnGraphBreakDecoratorContextManager(error_on_graph_break) + + +class CudagraphOverrideContextManager: + """Context manager that overrides cudagraph recording during tracing.""" + + def __init__(self, fwd: bool | None = None, bwd: bool | None = None) -> None: + self.fwd = fwd + self.bwd = bwd + self.prev_cudagraph_override: list[tuple[bool | None, bool | None] | None] = [] + + __call__ = wrap_dunder_call_ctx_manager + + def __enter__(self) -> None: + # Set the override at runtime so it follows the dynamic call stack. + # Dynamo handles the lexical `with` symbolically and does not run this + # __enter__ at trace time; it runs when the generated/resumed bytecode + # re-enters the context, before invoking callees that are compiled as + # separate frames. OutputGraph seeds its annotation from this value via + # _get_cudagraph_override. Mirrors ErrorOnGraphBreakDecoratorContextManager. + self.prev_cudagraph_override.append(_get_cudagraph_override()) + _set_cudagraph_override((self.fwd, self.bwd)) + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + _set_cudagraph_override(self.prev_cudagraph_override.pop()) + + +def override_cudagraphs( + fwd: bool | None = None, bwd: bool | None = None +) -> CudagraphOverrideContextManager: + """ + Context manager/decorator to override cudagraph recording for compiled graphs. + + When used as a context manager, overrides cudagraphs for all graph segments + within the block (including across graph breaks). + + When used as a decorator, marks a function so that any compiled graph + inlining it will have cudagraphs overridden. + + Args: + fwd: If False, disable cudagraphs for forward. If True, force enable. + If None, don't override. + bwd: If False, disable cudagraphs for backward. If True, force enable. + If None, don't override. + """ + return CudagraphOverrideContextManager(fwd=fwd, bwd=bwd) + + +def override_optimization_hint(x: Any, val: int) -> None: + """Override the optimization hint for a scalar unbacked symbol. + + When the compiler or runtime needs a non-guarding integer hint for an + unbacked ``SymInt`` — for example during FX passes, graph partitioning, + or inductor autotuning — it calls + ``_optimization_hint_base`` + (see ``torch/fx/experimental/_size_hinting.py``). By default + that function uses internal heuristics to choose a hint and a global fixed + fallback; + this function lets user code override that choice. This is similar to + the ``hint_override`` parameter in ``mark_unbacked``, but applies to + symbols that already exist (e.g. from ``.item()`` calls). + + Typical usage:: + + u = x.item() # unbacked SymInt + torch._dynamo.override_optimization_hint(u, 42) + # From now on, any call to shape_env.optimization_hint(u, ...) + # returns 42 instead of the default heuristic value. + + This updates ``shape_env.var_to_hint_override`` so that any consumer + of ``_optimization_hint_base`` sees *val* as the hint for the + unbacked symbol behind *x*. + + Works both eagerly (during FX passes or outside dynamo) and inside + ``torch.compile`` regions. + + Behavior during compilation: + The dynamo handler applies the hint as a **side effect** on + ``shape_env.var_to_hint_override`` during tracing. No FX graph + node is emitted — the call is fully consumed at trace time and + does not appear in the pre-grad, joint, or post-autograd graphs. + ``FXGraphCache`` includes ``var_to_hint_override`` in its cache + key, so cache hits/misses correctly reflect hint changes. + + .. note:: + + To maximize performance, it is recommended to pass hints for + **all** unbacked symbols in the program to guide optimizations. + + Args: + x: A ``torch.SymInt`` wrapping an unbacked symbol (e.g. from + ``.item()``), or a plain ``int``. If *x* is a plain ``int`` + the call is a no-op. + val: The integer hint value to record. + """ + if not isinstance(val, int): + raise TypeError( + f"override_optimization_hint expects val to be an int, got {type(val)}" + ) + if isinstance(x, int): + return + if not isinstance(x, torch.SymInt): + raise TypeError( + f"override_optimization_hint expects a torch.SymInt or int, got {type(x)}" + ) + shape_env = not_none(x.node.shape_env) + expr = x.node.expr + import sympy + + if not isinstance(expr, sympy.Symbol): + raise ValueError( + f"override_optimization_hint expects a single unbacked symbol, " + f"got derived expression: {expr}" + ) + if not shape_env.is_unbacked_symint(expr): + raise ValueError( + f"override_optimization_hint expects an unbacked symbol, " + f"but {expr} is backed" + ) + shape_env._set_unbacked_var_to_hint_override(x, val) + + +def is_dynamo_disable_recursive(method: Callable[[Any], Any]) -> bool | None: + """ + Check if a method is marked as `dynamo_disable` recursively. It returns: + - True if disable(recursive=True) + - False if disable(recursive=False) + - None if method is not a disable decorator + """ + return getattr(method, "_torchdynamo_disable_recursive", None) + + +_HASH_SLOTS = ("__hash__",) +_RICHCOMPARE_SLOTS = ("__eq__", "__ne__", "__lt__", "__le__", "__gt__", "__ge__") + + +def allow_c_slot( + tp: type, + *, + tp_hash: bool = True, + tp_richcompare: bool = True, +) -> type: + """Register a C extension type's slots as safe to call at trace time. + + By default, ``torch.compile`` graph-breaks when it encounters ``hash()`` + or comparison operators on a C extension type with custom C slots (e.g., + types defined in C extension modules). This function tells Dynamo that the + type's C slots are safe to evaluate during tracing, avoiding graph breaks. + + The slot functions must satisfy these requirements: + + - **Pure**: depends only on the object's value, with no observable side + effects (no I/O, no mutation of global state). + - **Deterministic**: returns the same result for the same object across + calls within a process. + - **Immutable objects**: the object's state must not change after + construction in a way that affects the slot's return value. + + Builtin types (``int``, ``str``, etc.) and Python-level dunder methods + are already handled and do not need registration. This API is only needed + for C extension types whose C slots Dynamo cannot trace into. + + Args: + tp: The C extension type whose C slots should be allowed. + tp_hash: Register ``__hash__`` as safe (default True). + tp_richcompare: Register comparison dunders as safe (default True). + + Returns: + The type, unchanged (so it can be used as a decorator). + + Example:: + + import torch._dynamo + from my_extension import MyType + + # Register all slots (hash + comparison) + torch._dynamo.allow_c_slot(MyType) + + # Register only hash + torch._dynamo.allow_c_slot(MyType, tp_richcompare=False) + + # Register only comparison + torch._dynamo.allow_c_slot(MyType, tp_hash=False) + """ + from .variables.user_defined import _safe_c_slots + + if not isinstance(tp, type): + raise TypeError(f"allow_c_slot expects a type, got {type(tp).__name__}") + safe = _safe_c_slots() + dunders = () + if tp_hash: + dunders += _HASH_SLOTS + if tp_richcompare: + dunders += _RICHCOMPARE_SLOTS + for dunder in dunders: + fn = getattr(tp, dunder, None) + if fn is not None and fn is not getattr(object, dunder, None): + safe.add(fn) + return tp diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/device_interface.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/device_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..2a892269d32a48d0518cf6ff1149a2933921ed03 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/device_interface.py @@ -0,0 +1,681 @@ +""" +Device abstraction layer for TorchDynamo and Inductor backends. + +This module provides a unified interface for different hardware backends (CUDA, XPU, +CPU, MPS, MTIA) through a common device interface. Key components include: + +- DeviceInterface: Base class defining the common API for all device types +- Device-specific implementations: CudaInterface, XpuInterface, CpuInterface, MpsInterface, MtiaInterface +- Device registration system for managing available backends +- Worker APIs for multi-processing scenarios +- Stream and event management across different devices +- Device property caching for worker processes + +The abstraction layer enables device-agnostic code in TorchDynamo while allowing +specialized implementations for each hardware backend's unique features. +""" + +import inspect +import time +from collections import namedtuple +from collections.abc import Callable, Iterable +from dataclasses import dataclass +from typing import Any, Literal + +import torch +from torch.utils._pallas import has_torch_tpu + + +get_cuda_stream: Callable[[int], int] | None +if torch.cuda._is_compiled(): + from torch._C import _cuda_getCurrentRawStream as get_cuda_stream +else: + get_cuda_stream = None + +# Recording the device properties in the main process but used in worker process. +caching_worker_device_properties: dict[str, Any] = {} +caching_worker_current_devices: dict[str, int] = {} + + +class DeviceInterface: + """ + This is a simple device runtime interface for Inductor. It enables custom + backends to be integrated with Inductor in a device-agnostic semantic. + """ + + class device: + def __new__(cls, device: torch.types.Device) -> Any: + raise NotImplementedError + + class Event: + def __new__(cls, *args: Any, **kwargs: Any) -> Any: + raise NotImplementedError( + "Event should be inherited from torch.Event, otherwise, it couldn't be captured by dynamo." + ) + + class Stream: + def __new__(cls, *args: Any, **kwargs: Any) -> Any: + raise NotImplementedError( + "Stream should be inherited from torch.Stream, otherwise, it couldn't be captured by dynamo." + ) + + class Worker: + """ + Worker API to query device properties that will work in multi processing + workers that cannot use the GPU APIs (due to processing fork() and + initialization time issues). Properties are recorded in the main process + before we fork the workers. + """ + + @staticmethod + def set_device(device: int) -> None: + raise NotImplementedError + + @staticmethod + def current_device() -> int: + raise NotImplementedError + + @staticmethod + def get_device_properties(device: torch.types.Device = None) -> Any: + raise NotImplementedError + + @staticmethod + def current_device() -> int: + raise NotImplementedError + + @staticmethod + def set_device(device: torch.types.Device) -> None: + raise NotImplementedError + + @staticmethod + def maybe_exchange_device(device: int) -> int: + raise NotImplementedError + + @staticmethod + def exchange_device(device: int) -> int: + raise NotImplementedError + + @staticmethod + def device_count() -> int: + raise NotImplementedError + + @staticmethod + def is_available() -> bool: + raise NotImplementedError + + @staticmethod + def stream(stream: torch.Stream) -> Any: + raise NotImplementedError + + @staticmethod + def current_stream() -> torch.Stream: + raise NotImplementedError + + @staticmethod + def set_stream(stream: torch.Stream) -> None: + raise NotImplementedError + + @staticmethod + def _set_stream_by_id(stream_id: int, device_index: int, device_type: int) -> None: + raise NotImplementedError + + @staticmethod + def get_raw_stream(device_idx: int) -> int: + raise NotImplementedError + + @staticmethod + def synchronize(device: torch.types.Device = None) -> None: + raise NotImplementedError + + @classmethod + def get_device_properties(cls, device: torch.types.Device = None) -> Any: + return cls.Worker.get_device_properties(device) + + @staticmethod + def get_compute_capability(device: torch.types.Device = None) -> Any: + raise NotImplementedError + + @staticmethod + def is_bf16_supported(including_emulation: bool = False) -> bool: + raise NotImplementedError + + @classmethod + def is_dtype_supported( + cls, dtype: torch.dtype, including_emulation: bool = False + ) -> bool: + return dtype != torch.bfloat16 or cls.is_bf16_supported(including_emulation) + + @staticmethod + def memory_allocated(device: torch.types.Device = None) -> int: + raise NotImplementedError + + @staticmethod + def is_triton_capable(device: torch.types.Device = None) -> bool: + """ + Returns True if the device has Triton support, False otherwise, even if + the appropriate Triton backend is not available. + """ + return False + + @classmethod + def raise_if_triton_unavailable(cls, device: torch.types.Device = None) -> None: + """ + Raises a `TritonUnavailableError` with human-readable instructions if + the Triton backend for the given device (or the default device if + `device` is `None`) is not built. Implementations may raise a + different, more specific error when the device itself is not + Triton-capable (e.g. CUDA raises `GPUTooOldForTriton`), so callers + that only want an availability answer should check + `is_triton_capable()` first. + + The caller should ensure the presence of the 'triton' package before + calling this method. + """ + from torch._dynamo.exc import TritonUnavailableError + + if not cls.is_triton_capable(): + raise TritonUnavailableError( + "This device is not capable of supporting Triton" + ) + + +class DeviceGuard: + """ + This class provides a context manager for device switching. This is a stripped + down version of torch.{device_name}.device. + + The context manager changes the current device to the given device index + on entering the context and restores the original device on exiting. + The device is switched using the provided device interface. + """ + + def __init__( + self, device_interface: type[DeviceInterface], index: int | None + ) -> None: + self.device_interface = device_interface + self.idx = index + self.prev_idx = -1 + + def __enter__(self) -> None: + if self.idx is not None: + self.prev_idx = self.device_interface.exchange_device(self.idx) + + def __exit__(self, type: Any, value: Any, traceback: Any) -> Literal[False]: + if self.idx is not None: + self.idx = self.device_interface.maybe_exchange_device(self.prev_idx) + return False + + +class CudaInterface(DeviceInterface): + device = torch.cuda.device # type: ignore[assignment] + + # register Event and Stream class into the backend interface + # make sure Event and Stream are implemented and inherited from the torch.Event and torch.Stream + Event = torch.cuda.Event # type: ignore[assignment] + Stream = torch.cuda.Stream # type: ignore[assignment] + + # pyrefly: ignore [bad-override] + class Worker: + @staticmethod + def set_device(device: int) -> None: + caching_worker_current_devices["cuda"] = device + + @staticmethod + def current_device() -> int: + if "cuda" in caching_worker_current_devices: + return caching_worker_current_devices["cuda"] + return torch.cuda.current_device() + + @staticmethod + def get_device_properties(device: torch.types.Device = None) -> Any: + if device is not None: + if isinstance(device, str): + device = torch.device(device) + if device.type != "cuda": + raise AssertionError( + f"Expected device type 'cuda', got '{device.type}'" + ) + if isinstance(device, torch.device): + device = device.index + if device is None: + device = CudaInterface.Worker.current_device() + + if "cuda" not in caching_worker_device_properties: + device_prop = [ + torch.cuda.get_device_properties(i) + for i in range(torch.cuda.device_count()) + ] + caching_worker_device_properties["cuda"] = device_prop + + return caching_worker_device_properties["cuda"][device] + + current_device = staticmethod(torch.cuda.current_device) + set_device = staticmethod(torch.cuda.set_device) + device_count = staticmethod(torch.cuda.device_count) + stream = staticmethod(torch.cuda.stream) # type: ignore[assignment] + current_stream = staticmethod(torch.cuda.current_stream) + set_stream = staticmethod(torch.cuda.set_stream) # type: ignore[assignment] + _set_stream_by_id = staticmethod(torch.cuda._set_stream_by_id) # type: ignore[assignment] + synchronize = staticmethod(torch.cuda.synchronize) + get_device_properties = staticmethod(torch.cuda.get_device_properties) # type: ignore[assignment] + get_raw_stream = staticmethod(get_cuda_stream) # type: ignore[assignment, arg-type] + exchange_device = staticmethod(torch.cuda._exchange_device) # type: ignore[arg-type, has-type] + maybe_exchange_device = staticmethod(torch.cuda._maybe_exchange_device) # type: ignore[arg-type, has-type] + memory_allocated = staticmethod(torch.cuda.memory_allocated) + is_bf16_supported = staticmethod(torch.cuda.is_bf16_supported) # type: ignore[arg-type] + + # Can be mock patched by @patch decorator. + @staticmethod + def is_available() -> bool: + return torch.cuda.is_available() + + @staticmethod + def get_compute_capability(device: torch.types.Device = None) -> int | str: + if torch.version.hip is None: + major, min = torch.cuda.get_device_capability(device) + return major * 10 + min + else: + return torch.cuda.get_device_properties(device).gcnArchName.split(":", 1)[0] + + @staticmethod + def is_triton_capable(device: torch.types.Device = None) -> bool: + # Use the Worker API (device properties cached in the main process + # before fork) instead of torch.cuda.get_device_properties directly, so + # the capability check stays safe when called from spawn-based compile + # workers. + return ( + torch.version.hip is not None + or CudaInterface.Worker.get_device_properties(device).major >= 7 + ) + + @staticmethod + def raise_if_triton_unavailable(device: torch.types.Device = None) -> None: + from torch._dynamo.exc import TritonUnavailableError + from torch._inductor.exc import GPUTooOldForTriton + + if not CudaInterface.is_triton_capable(device): + device_props = torch.cuda.get_device_properties(device) + raise GPUTooOldForTriton(device_props, inspect.currentframe()) + + import triton.backends + + if torch.version.hip is not None: + if "amd" not in triton.backends.backends: + raise TritonUnavailableError("triton not built with the 'amd' backend") + elif "nvidia" not in triton.backends.backends: + raise TritonUnavailableError("triton not built with the 'nvidia' backend") + + +get_mtia_stream: Callable[[int], int] | None +if torch.mtia._is_compiled(): + from torch._C import _mtia_getCurrentRawStream as get_mtia_stream +else: + get_mtia_stream = None + + +class MtiaInterface(DeviceInterface): + device = torch.mtia.device # type: ignore[assignment] + Event = torch.mtia.Event # type: ignore[assignment] + Stream = torch.mtia.Stream # type: ignore[assignment] + + # pyrefly: ignore [bad-override] + class Worker: + @staticmethod + def set_device(device: int) -> None: + caching_worker_current_devices["mtia"] = device + + @staticmethod + def current_device() -> int: + if "mtia" in caching_worker_current_devices: + return caching_worker_current_devices["mtia"] + return torch.mtia.current_device() + + @staticmethod + def get_device_properties(device: torch.types.Device = None) -> Any: + if device is not None: + if isinstance(device, str): + device = torch.device(device) + if device.type != "mtia": + raise AssertionError( + f"Expected device type 'mtia', got '{device.type}'" + ) + if isinstance(device, torch.device): + device = device.index + if device is None: + device = MtiaInterface.Worker.current_device() + + if "mtia" not in caching_worker_device_properties: + device_prop = [ + torch.mtia.get_device_properties(i) + for i in range(torch.mtia.device_count()) + ] + caching_worker_device_properties["mtia"] = device_prop + + return caching_worker_device_properties["mtia"][device] + + current_device = staticmethod(torch.mtia.current_device) + set_device = staticmethod(torch.mtia.set_device) # type: ignore[assignment] + device_count = staticmethod(torch.mtia.device_count) + stream = staticmethod(torch.mtia.stream) # type: ignore[assignment] + current_stream = staticmethod(torch.mtia.current_stream) + set_stream = staticmethod(torch.mtia.set_stream) # type: ignore[assignment] + _set_stream_by_id = staticmethod(torch.mtia._set_stream_by_id) # type: ignore[assignment] + synchronize = staticmethod(torch.mtia.synchronize) + get_device_properties = staticmethod(torch.mtia.get_device_properties) # type: ignore[assignment] + get_raw_stream = staticmethod(get_mtia_stream) # type: ignore[assignment, arg-type] + exchange_device = staticmethod(torch.mtia._exchange_device) # type: ignore[arg-type, has-type] + maybe_exchange_device = staticmethod(torch.mtia._maybe_exchange_device) # type: ignore[arg-type, has-type] + memory_allocated = staticmethod(torch.mtia.memory_allocated) # type: ignore[assignment] + is_bf16_supported = staticmethod(torch.mtia.is_bf16_supported) # type: ignore[arg-type] + + # Can be mock patched by @patch decorator. + @staticmethod + def is_available() -> bool: + ret = torch.mtia.is_available() + return ret + + @staticmethod + def get_compute_capability(device: torch.types.Device = None) -> Any: + cc = torch.mtia.get_device_capability(device) + return cc + + @staticmethod + def is_triton_capable(device: torch.types.Device = None) -> bool: + return True + + @staticmethod + def raise_if_triton_unavailable(device: torch.types.Device = None) -> None: + import triton.backends + + from torch._dynamo.exc import TritonUnavailableError + + if "mtia" not in triton.backends.backends: + raise TritonUnavailableError("triton not built with the 'mtia' backend") + + +get_xpu_stream: Callable[[int], int] | None +if torch.xpu._is_compiled(): + from torch._C import _xpu_getCurrentRawStream as get_xpu_stream +else: + get_xpu_stream = None + + +class XpuInterface(DeviceInterface): + device = torch.xpu.device # type: ignore[assignment] + Event = torch.xpu.Event # type: ignore[assignment] + Stream = torch.xpu.Stream # type: ignore[assignment] + + # pyrefly: ignore [bad-override] + class Worker: + @staticmethod + def set_device(device: int) -> None: + caching_worker_current_devices["xpu"] = device + + @staticmethod + def current_device() -> int: + if "xpu" in caching_worker_current_devices: + return caching_worker_current_devices["xpu"] + return torch.xpu.current_device() + + @staticmethod + def get_device_properties(device: torch.types.Device = None) -> Any: + if device is not None: + if isinstance(device, str): + device = torch.device(device) + if device.type != "xpu": + raise AssertionError( + f"Expected device type 'xpu', got '{device.type}'" + ) + if isinstance(device, torch.device): + device = device.index + if device is None: + device = XpuInterface.Worker.current_device() + + if "xpu" not in caching_worker_device_properties: + device_prop = [ + torch.xpu.get_device_properties(i) + for i in range(torch.xpu.device_count()) + ] + caching_worker_device_properties["xpu"] = device_prop + + return caching_worker_device_properties["xpu"][device] + + current_device = staticmethod(torch.xpu.current_device) + set_device = staticmethod(torch.xpu.set_device) + device_count = staticmethod(torch.xpu.device_count) # type: ignore[has-type] + stream = staticmethod(torch.xpu.stream) # type: ignore[assignment] + current_stream = staticmethod(torch.xpu.current_stream) + set_stream = staticmethod(torch.xpu.set_stream) # type: ignore[assignment] + _set_stream_by_id = staticmethod(torch.xpu._set_stream_by_id) # type: ignore[assignment] + synchronize = staticmethod(torch.xpu.synchronize) + get_device_properties = staticmethod(torch.xpu.get_device_properties) # type: ignore[assignment] + get_raw_stream = staticmethod(get_xpu_stream) # type: ignore[assignment, arg-type] + exchange_device = staticmethod(torch.xpu._exchange_device) # type: ignore[arg-type, has-type] + maybe_exchange_device = staticmethod(torch.xpu._maybe_exchange_device) # type: ignore[arg-type, has-type] + memory_allocated = staticmethod(torch.xpu.memory_allocated) + + # Can be mock patched by @patch decorator. + @staticmethod + def is_available() -> bool: + return torch.xpu.is_available() + + @staticmethod + def get_compute_capability(device: torch.types.Device = None) -> Any: + cc = torch.xpu.get_device_capability(device) + return cc + + @staticmethod + def is_bf16_supported(including_emulation: bool = False) -> bool: + return torch.xpu.is_bf16_supported() + + @staticmethod + def is_triton_capable(device: torch.types.Device = None) -> bool: + return True + + @staticmethod + def raise_if_triton_unavailable(device: torch.types.Device = None) -> None: + import triton.backends + + from torch._dynamo.exc import TritonUnavailableError + + if "intel" not in triton.backends.backends: + raise TritonUnavailableError("triton not built with the 'intel' backend") + + +@dataclass +class CpuDeviceProperties: + multi_processor_count: int + + +class CpuInterface(DeviceInterface): + # pyrefly: ignore [bad-override] + class Event(torch.Event): + def __init__(self, enable_timing: bool = True) -> None: + self.time = 0.0 + + def elapsed_time(self, other: Any) -> float: + return (other.time - self.time) * 1000 + + def record(self, stream: Any = None) -> None: + self.time = time.perf_counter() + + # pyrefly: ignore [bad-override] + class Worker: + @staticmethod + def get_device_properties( + device: torch.types.Device = None, + ) -> CpuDeviceProperties: + import multiprocessing + + cpu_count = multiprocessing.cpu_count() + return CpuDeviceProperties(cpu_count) + + @staticmethod + def is_available() -> bool: + return True + + @staticmethod + def is_bf16_supported(including_emulation: bool = False) -> bool: + return True + + @staticmethod + def get_compute_capability(device: torch.types.Device = None) -> str: + return "" + + @staticmethod + def get_raw_stream(device_idx: Any) -> int: + return 0 + + @staticmethod + def current_device() -> int: + return 0 + + @staticmethod + def synchronize(device: torch.types.Device = None) -> None: + pass + + @staticmethod + def is_triton_capable(device: torch.types.Device = None) -> bool: + return True + + @staticmethod + def raise_if_triton_unavailable(device: torch.types.Device = None) -> None: + import triton.backends + + from torch._dynamo.exc import TritonUnavailableError + + if "cpu" not in triton.backends.backends: + raise TritonUnavailableError("triton not built with the 'cpu' backend") + + +class MpsInterface(DeviceInterface): + @staticmethod + def is_bf16_supported(including_emulation: bool = False) -> bool: + return True + + @classmethod + def is_dtype_supported( + cls, dtype: torch.dtype, including_emulation: bool = False + ) -> bool: + if dtype in [torch.float64, torch.complex128]: + return False + return True + + @staticmethod + def is_available() -> bool: + return torch.backends.mps.is_available() + + @staticmethod + def current_device() -> int: + return 0 + + @staticmethod + def get_compute_capability(device: torch.types.Device = None) -> str: + return "" + + @staticmethod + def synchronize(device: torch.types.Device = None) -> None: + torch.mps.synchronize() + + # pyrefly: ignore [bad-override] + class Worker: + @staticmethod + def get_device_properties(device: torch.types.Device = None) -> Any: + return namedtuple("MPSProperties", ["multi_processor_count"])( + torch.backends.mps.get_core_count() # type: ignore[arg-type] + ) + + @staticmethod + def current_device() -> int: + return 0 + + +class TpuInterface(DeviceInterface): + @staticmethod + def is_bf16_supported(including_emulation: bool = False) -> bool: + return True + + @classmethod + def is_dtype_supported( + cls, dtype: torch.dtype, including_emulation: bool = False + ) -> bool: + return dtype not in ( + torch.float64, + torch.complex32, + torch.complex64, + torch.complex128, + torch.half, + ) + + @staticmethod + def is_available() -> bool: + return has_torch_tpu() + + @staticmethod + def current_device() -> int: + return 0 + + @staticmethod + def get_compute_capability(device: torch.types.Device = None) -> str: + return "" + + # pyrefly: ignore [bad-override] + class Worker: + @staticmethod + def get_device_properties(device: torch.types.Device = None) -> Any: + return namedtuple("TPUProperties", ["multi_processor_count"])( + 1 # type: ignore[arg-type] + ) + + @staticmethod + def current_device() -> int: + return 0 + + +device_interfaces: dict[str, type[DeviceInterface]] = {} +_device_initialized = False + + +def register_interface_for_device( + device: str | torch.device, device_interface: type[DeviceInterface] +) -> None: + if isinstance(device, torch.device): + device = device.type + device_interfaces[device] = device_interface + + +def get_interface_for_device(device: str | torch.device) -> type[DeviceInterface]: + if isinstance(device, torch.device): + device = device.type + if not _device_initialized: + init_device_reg() + if device in device_interfaces: + return device_interfaces[device] + raise NotImplementedError(f"No interface for device {device}") + + +def get_registered_device_interfaces() -> Iterable[tuple[str, type[DeviceInterface]]]: + if not _device_initialized: + init_device_reg() + return device_interfaces.items() + + +def init_device_reg() -> None: + global _device_initialized + register_interface_for_device("cuda", CudaInterface) + for i in range(torch.cuda.device_count()): + register_interface_for_device(f"cuda:{i}", CudaInterface) + + register_interface_for_device("xpu", XpuInterface) + for i in range(torch.xpu.device_count()): + register_interface_for_device(f"xpu:{i}", XpuInterface) + + register_interface_for_device("mtia", MtiaInterface) + for i in range(torch.mtia.device_count()): + register_interface_for_device(f"mtia:{i}", MtiaInterface) + + register_interface_for_device("cpu", CpuInterface) + register_interface_for_device("mps", MpsInterface) + register_interface_for_device("tpu", TpuInterface) + + _device_initialized = True diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/distributed.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..54450f5d98a16b2a33c66d1ee69482f35dcdbd33 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/distributed.py @@ -0,0 +1,58 @@ +""" +Manages process groups for distributed compilation in TorchDynamo. + +This module handles the initialization and management of process groups used for +distributed compilation. Key features: + +- Lazy initialization of compilation process groups +- Only creates groups when distributed mode is enabled and available +- Integrates with compiler_collectives configuration setting +- Provides a single global process group for compilation coordination + +The process group is created only when needed and if the distributed environment +is properly initialized, making it safe to import and use this module even in +non-distributed scenarios. +""" + +import torch.distributed as dist + +from . import config + + +_COMPILE_PG: dist.ProcessGroup | None = None +_GUARD_PG: dist.ProcessGroup | None = None + + +def get_compile_pg() -> dist.ProcessGroup | None: + if ( + config.enable_compiler_collectives + and dist.is_available() + and dist.is_initialized() + ): + global _COMPILE_PG + if _COMPILE_PG is None: + # , timeout=datetime.timedelta(seconds=2) + compile_pg = dist.distributed_c10d._new_group_with_tag( + pg_tag="pt2_compile_pg" + ) + if compile_pg == dist.GroupMember.NON_GROUP_MEMBER: + raise AssertionError("Compiler process group must include all ranks") + _COMPILE_PG = compile_pg + return _COMPILE_PG + + return None + + +# NB: Unlike get_compile_pg, this is only called when guard collectives were +# explicitly requested +def get_guard_pg() -> dist.ProcessGroup | None: + if dist.is_available() and dist.is_initialized(): + global _GUARD_PG + if _GUARD_PG is None: + guard_pg = dist.distributed_c10d._new_group_with_tag(pg_tag="pt2_guard_pg") + if guard_pg == dist.GroupMember.NON_GROUP_MEMBER: + raise AssertionError("Guard process group must include all ranks") + _GUARD_PG = guard_pg + return _GUARD_PG + + return None diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/dynamo_profiler.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/dynamo_profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..7c645b7f17071a56373b33a62d683286efaa96a5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/dynamo_profiler.py @@ -0,0 +1,426 @@ +""" +Dynamo Profiler - tracks where Dynamo spends time during compilation. + +This module provides profiling functionality for Dynamo tracing, showing per-function +cumtime (inclusive) and tottime (exclusive) in a cProfile-compatible format. +The output can be visualized with tools like snakeviz. + +Usage: + # Enable via config (prints pstats output): + torch._dynamo.config.dynamo_profiler = True + + # Or save to file for snakeviz: + torch._dynamo.config.dynamo_profiler = "/tmp/dynamo.prof" + # Then: snakeviz /tmp/dynamo.prof +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, TYPE_CHECKING + + +if TYPE_CHECKING: + import pstats + + +@dataclass +class FunctionTraceTiming: + """ + Timing data for a single inlined function trace. + + Follows cProfile conventions: + - cumtime: total time in function including all subcalls (inclusive) + - tottime: time in function excluding subcalls (exclusive) + - caller info: who called this function (for building call graph) + """ + + # Function identification + func_name: str + filename: str + firstlineno: int + # Timing data (in nanoseconds) - cProfile-style + cumtime_ns: int # Inclusive time (includes subcalls) + tottime_ns: int # Exclusive time (excludes subcalls) + # Code stats (for comparing tracing overhead vs function complexity) + bytecode_count: int + # Nesting depth when this function was traced + inline_depth: int + # Caller information (for building call graph edges) + caller_func_name: str | None = None + caller_filename: str | None = None + caller_firstlineno: int | None = None + # Whether this is a primitive (non-recursive) call + # A call is primitive if the function doesn't appear anywhere in the call stack + is_primitive_call: bool = True + # Full call stack at the time of this call (for proper snakeviz drill-down) + # Each entry is (func_name, filename, firstlineno) + call_stack: tuple[tuple[str, str, int], ...] = () + + # Backwards compatibility alias + @property + def trace_time_ns(self) -> int: + return self.cumtime_ns + + @property + def trace_time_ms(self) -> float: + return self.cumtime_ns / 1e6 + + @property + def cumtime_ms(self) -> float: + return self.cumtime_ns / 1e6 + + @property + def tottime_ms(self) -> float: + return self.tottime_ns / 1e6 + + @property + def caller_key(self) -> tuple[str, int, str] | None: + """Return caller as a pstats-compatible key tuple.""" + if self.caller_func_name is not None: + return ( + self.caller_filename or "", + self.caller_firstlineno or 0, + self.caller_func_name, + ) + return None + + @property + def func_key(self) -> tuple[str, int, str]: + """Return this function as a pstats-compatible key tuple.""" + return (self.filename, self.firstlineno, self.func_name) + + def __repr__(self) -> str: + return ( + f"FunctionTraceTiming({self.func_name} at {self.filename}:{self.firstlineno}, " + f"cumtime={self.cumtime_ms:.2f}ms, tottime={self.tottime_ms:.2f}ms, " + f"bytecode={self.bytecode_count}, depth={self.inline_depth})" + ) + + +@dataclass +class ProfilerStackEntry: + """Stack entry for tracking function timing in the Dynamo profiler.""" + + func_name: str + filename: str + firstlineno: int + start_time_ns: int + child_time_ns: int # Accumulated time spent in traced children + is_primitive_call: bool = True # Whether this is a non-recursive call + + +class DynamoProfilerState: + """State for Dynamo profiler tracking function trace timings.""" + + def __init__(self) -> None: + self.timings: list[FunctionTraceTiming] = [] + self.stack: list[ProfilerStackEntry] = [] + + def record_timing(self, timing: FunctionTraceTiming) -> None: + """Record timing data for a traced function.""" + self.timings.append(timing) + + def get_timings(self) -> list[FunctionTraceTiming]: + """Get all recorded timings.""" + return self.timings + + def push( + self, func_name: str, filename: str, firstlineno: int, start_time_ns: int + ) -> None: + """Push a new entry onto the timing stack.""" + # Check if this function already exists in the stack (indirect recursion) + is_primitive = not any( + entry.func_name == func_name + and entry.filename == filename + and entry.firstlineno == firstlineno + for entry in self.stack + ) + self.stack.append( + ProfilerStackEntry( + func_name=func_name, + filename=filename, + firstlineno=firstlineno, + start_time_ns=start_time_ns, + child_time_ns=0, + is_primitive_call=is_primitive, + ) + ) + + def pop(self) -> ProfilerStackEntry | None: + """Pop the top entry from the timing stack.""" + if self.stack: + return self.stack.pop() + return None + + def add_child_time(self, child_cumtime_ns: int) -> None: + """Add the child's cumulative time to the parent's child_time accumulator.""" + if self.stack: + self.stack[-1].child_time_ns += child_cumtime_ns + + def get_current_caller(self) -> tuple[str, str, int] | None: + """Get the current caller (top of stack) as (func_name, filename, firstlineno).""" + if self.stack: + entry = self.stack[-1] + return (entry.func_name, entry.filename, entry.firstlineno) + return None + + def get_call_stack(self) -> tuple[tuple[str, str, int], ...]: + """Get the full current call stack as tuple of (func_name, filename, firstlineno).""" + return tuple( + (entry.func_name, entry.filename, entry.firstlineno) for entry in self.stack + ) + + def generate_pstats( + self, output_file: str | None = None, print_raw: bool = False + ) -> pstats.Stats: + """Generate pstats.Stats object from recorded timings. + + Args: + output_file: Optional file path to save the stats. + print_raw: If True, print raw aggregate timings before returning. + """ + import cProfile + import io + import logging + import pstats + + log = logging.getLogger(__name__) + + # Aggregate by (filename, lineno, func_name) + aggregated: dict[tuple[str, int, str], dict[str, Any]] = {} + # caller_edges[callee_key][caller_key] -> edge stats + caller_edges: dict[ + tuple[str, int, str], dict[tuple[str, int, str], dict[str, Any]] + ] = {} + + for t in self.timings: + key = (t.filename, t.firstlineno, t.func_name) + + if key not in aggregated: + aggregated[key] = { + "ncalls": 0, + "pcalls": 0, + "tottime": 0.0, + "cumtime": 0.0, + } + caller_edges[key] = {} + + agg = aggregated[key] + agg["ncalls"] += 1 + agg["tottime"] += t.tottime_ns / 1e9 + + if t.is_primitive_call: + agg["pcalls"] += 1 + agg["cumtime"] += t.cumtime_ns / 1e9 + + # Build caller edge + if t.caller_filename is not None: + caller_key = ( + t.caller_filename, + t.caller_firstlineno or 0, + t.caller_func_name or "", + ) + if caller_key not in caller_edges[key]: + caller_edges[key][caller_key] = { + "ncalls": 0, + "pcalls": 0, + "tottime": 0.0, + "cumtime": 0.0, + } + edge = caller_edges[key][caller_key] + edge["ncalls"] += 1 + edge["tottime"] += t.tottime_ns / 1e9 + # Always add cumtime to edges for visualization (gprof2dot) + # Function-level cumtime is already correct (only primitive calls) + edge["cumtime"] += t.cumtime_ns / 1e9 + if t.is_primitive_call: + edge["pcalls"] += 1 + + if print_raw: + sorted_items = sorted( + aggregated.items(), key=lambda x: x[1]["cumtime"], reverse=True + ) + print("\n=== Aggregate Timings (raw) ===") + print( + f"{'ncalls':>8} {'pcalls':>8} {'tottime':>12} {'cumtime':>12} function" + ) + print("-" * 80) + total_cumtime = 0.0 + total_tottime = 0.0 + for (filename, lineno, func_name), agg in sorted_items: + ncalls = agg["ncalls"] + pcalls = agg["pcalls"] + tottime = agg["tottime"] * 1000 # convert to ms + cumtime = agg["cumtime"] * 1000 + total_cumtime += cumtime + total_tottime += tottime + short_file = filename.split("/")[-1] if "/" in filename else filename + print( + f"{ncalls:>8} {pcalls:>8} {tottime:>10.2f}ms {cumtime:>10.2f}ms " + f"{func_name} ({short_file}:{lineno})" + ) + print("-" * 80) + print( + f"Total timings: {len(self.timings)}, unique functions: {len(aggregated)}" + ) + print( + f"Sum tottime: {total_tottime:.2f}ms, Sum cumtime: {total_cumtime:.2f}ms" + ) + + # Ensure caller-only functions have a top-level entry. + # gprof2dot expects every function referenced as a caller to also + # exist as a top-level entry in the stats dict with timing data. + for key in list(caller_edges.keys()): + for caller_key in caller_edges[key]: + if caller_key not in aggregated: + aggregated[caller_key] = { + "ncalls": 0, + "pcalls": 0, + "tottime": 0.0, + "cumtime": 0.0, + } + caller_edges[caller_key] = {} + + # Build the stats dict in pstats format + stats_dict: dict[ + tuple[str, int, str], tuple[int, int, float, float, dict[Any, Any]] + ] = {} + + for key, agg in aggregated.items(): + callers: dict[tuple[str, int, str], tuple[int, int, float, float]] = {} + for caller_key, edge in caller_edges[key].items(): + callers[caller_key] = ( + edge["ncalls"], + edge["pcalls"], + edge["tottime"], + edge["cumtime"], + ) + + stats_dict[key] = ( + agg["pcalls"], + agg["ncalls"], + agg["tottime"], + agg["cumtime"], + callers, + ) + + # Create a pstats.Stats object + dummy_profile = cProfile.Profile() + dummy_profile.enable() + dummy_profile.disable() + stats = pstats.Stats(dummy_profile, stream=io.StringIO()) + + stats.stats = stats_dict # type: ignore[attr-defined] + stats.total_calls = sum(s[1] for s in stats_dict.values()) # type: ignore[attr-defined] + stats.prim_calls = sum(s[0] for s in stats_dict.values()) # type: ignore[attr-defined] + stats.total_tt = sum(s[2] for s in stats_dict.values()) # type: ignore[attr-defined] + + if output_file: + stats.dump_stats(output_file) + log.info( + "Saved pstats to %s. Visualize with: snakeviz %s", + output_file, + output_file, + ) + + return stats + + def generate_svg( + self, profile_file: str, svg_file: str | None = None + ) -> str | None: + """Generate an SVG call graph from a profile file using gprof2dot and graphviz. + + Args: + profile_file: Path to the pstats profile file. + svg_file: Optional path for the output SVG. If not provided, uses + profile_file with .svg extension. + + Returns: + Path to the generated SVG file, or None if generation failed. + """ + import os + import shutil + import subprocess + + if not shutil.which("gprof2dot"): + print("gprof2dot not found. Install with: pip install gprof2dot") + return None + + if not shutil.which("dot"): + print("graphviz 'dot' not found. Install graphviz package.") + return None + + if svg_file is None: + svg_file = profile_file.rsplit(".", 1)[0] + ".svg" + + try: + # gprof2dot -f pstats profile.prof | dot -Tsvg -o profile.svg + gprof2dot = subprocess.Popen( + [ + "gprof2dot", + "-f", + "pstats", + "--node-label=total-time-percentage", + "--node-label=self-time-percentage", + "--node-label=total-time", + profile_file, + ], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + dot = subprocess.Popen( + ["dot", "-Tsvg", "-o", svg_file], + stdin=gprof2dot.stdout, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + gprof2dot.stdout.close() # type: ignore[union-attr] + _, dot_err = dot.communicate() + _, gprof2dot_err = gprof2dot.communicate() + + if gprof2dot.returncode != 0: + print(f"gprof2dot failed: {gprof2dot_err.decode()}") + return None + + if dot.returncode != 0: + print(f"graphviz dot failed: {dot_err.decode()}") + return None + + if not os.path.isfile(svg_file): + print(f"SVG file was not created: {svg_file}") + return None + + print(f"SVG call graph saved to: {svg_file}") + return svg_file + + except Exception as e: + print(f"Failed to generate SVG: {e}") + return None + + def dump_stats( + self, output_file: str | None = None, generate_svg: bool = True + ) -> None: + """Print profiler stats to stdout and optionally save to file. + + Args: + output_file: Optional path to save the pstats profile. + generate_svg: If True and output_file is provided, also generate an SVG + call graph using gprof2dot and graphviz. + """ + import sys + + if not self.timings: + return + + stats = self.generate_pstats(output_file, print_raw=True) + print("\n=== Dynamo Profiler (pstats) ===") + stats.stream = sys.stdout # type: ignore[attr-defined] + stats.sort_stats("cumulative").print_stats() + + if output_file: + print(f"\nProfile saved to: {output_file}") + print(f"Visualize with: snakeviz {output_file}") + + if generate_svg: + self.generate_svg(output_file) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/eval_frame.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/eval_frame.py new file mode 100644 index 0000000000000000000000000000000000000000..7ac5841ae06971160885f851e215bdedd223501e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/eval_frame.py @@ -0,0 +1,2965 @@ +# mypy: disable-error-code="method-assign" + +""" +This module implements the core frame evaluation handler for TorchDynamo's compilation system. +The eval frame handler intercepts Python bytecode execution at runtime to enable dynamic +compilation and optimization of PyTorch code. + +Key components defined here: +- Frame evaluation handlers that intercept and analyze Python execution frames +- Guards management for tracking dependencies and invalidating compiled code +- Optimization contexts and decorators (optimize, run_once, disable, etc.) +- Export functionality for saving optimized graphs +- Backend compiler integrations and callback management + +Functions in this file are responsible for modifying the eval frame handler at RUNTIME. +Therefore, all functions in this file are hot and performance-critical. Functions that +only execute at compile time should be placed in torch._dynamo.convert_frame. + +The eval frame handler is the core mechanism that enables TorchDynamo to dynamically +intercept, analyze and optimize PyTorch code during execution. It works by registering +a custom frame evaluation function that gets called for every Python frame, allowing +us to detect PyTorch operations and trigger compilation as needed. +""" + +from __future__ import annotations + +import atexit +import contextlib +import functools +import inspect +import itertools +import logging +import os +import sys +import sysconfig +import textwrap +import threading +import traceback +import types +import unittest +import warnings +import weakref +from collections.abc import Generator, Sized +from dataclasses import dataclass +from enum import Enum +from os.path import dirname, join +from typing import Any, cast, Literal, NamedTuple, TYPE_CHECKING +from unittest.mock import patch + +import sympy + +import torch +import torch.fx +import torch.utils._pytree as pytree +import torch.utils.checkpoint +from torch import _guards + +# see discussion at https://github.com/pytorch/pytorch/issues/120699 +from torch._C._dynamo.eval_frame import ( # noqa: F401 + get_eval_frame_isolate_recompiles_id, + reset_code, + set_code_exec_strategy, + set_eval_frame, + set_eval_frame_isolate_recompiles_id, + set_fullgraph_compiled_frame_count, + set_fullgraph_error_on_nested_compile, + set_guard_complete_hook, + set_guard_error_hook, + set_skip_guard_eval_unsafe, + unsupported, +) +from torch._dispatch.python import enable_python_dispatcher +from torch._dynamo.types import ( + CompilerConfig, + CompilerConfigProvider, + ConvertFrameReturn, + FrameAction, + FrameExecStrategy, +) +from torch._export.utils import _compiling_state_context +from torch._library.opaque_object import is_custom_class +from torch._subclasses.fake_tensor import unset_fake_temporarily +from torch._utils_internal import DISABLE_JUSTKNOBS, justknobs_check, log_export_usage +from torch.export.dynamic_shapes import ( + _combine_args, + _DimHint, + _DimHintType, + _IntWrapper, + _process_dynamic_shapes, + _RelaxedConstraint, + Constraint, +) +from torch.fx import GraphModule, traceback as fx_traceback +from torch.fx.experimental._dynamism import ( + clone_and_convert_to_meta, + track_dynamism_across_examples, +) +from torch.fx.experimental.dynamic_spec import ( + _coerce_to_shapes_spec, + ParamsSpec, + ShapesSpec, +) +from torch.fx.experimental.proxy_tensor import make_fx +from torch.fx.experimental.symbolic_shapes import ( + ConstraintViolationError, + DimDynamic, + ShapeEnv, + StatelessSymbolicContext, +) +from torch.fx.graph import _PyTreeCodeGen, _PyTreeInfo + +from . import config, convert_frame, distributed, external_utils, trace_rules, utils +from .backends.registry import CompilerFn, lookup_backend +from .code_context import code_context +from .exc import ( + CondOpArgsMismatchError, + ShortenTraceback, + UncapturedHigherOrderOpError, + Unsupported, + UserError, + UserErrorType, +) +from .hooks import Hooks +from .mutation_guard import install_generation_tagging_init +from .utils import ( + _get_error_on_graph_break, + _set_error_on_graph_break, + common_constant_types, + compile_times, +) + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Sequence + + from torch._dynamo.package import CompilePackage + from torch._dynamo.repro.after_dynamo import WrapBackendDebug + from torch._subclasses import fake_tensor + from torch.export._trace import _DynamicShapesInput + from torch.fx.node import Argument, Node, Target + + from .types import ( + CacheEntry, + DynamoCallback, + DynamoFrameType, + GuardFail, + GuardFilterEntry, + ) + + +log = logging.getLogger(__name__) + +_next_isolate_recompiles_id = itertools.count() + + +always_optimize_code_objects = utils.ExactWeakKeyDictionary() +null_context = contextlib.nullcontext + + +# See https://github.com/python/typing/pull/240 +class Unset(Enum): + token = 0 + + +cached_backends: dict[int, CompilerFn] = {} + +unset = Unset.token + +_in_optimized_module = False + + +if DISABLE_JUSTKNOBS: + _maybe_set_eval_frame = set_eval_frame +else: + + def _maybe_set_eval_frame(callback: DynamoCallback) -> DynamoCallback: + # A wrapper on set_eval_frame that is guarded by a Justknob. + # Users can disable torchDynamo by setting the JK to False. + if not justknobs_check("pytorch/compiler:enable_compiler_set_eval_frame"): + torch._dynamo.utils.warn_once( + "Dynamo disabled by Justknob: enable_compiler_set_eval_frame, skipping set_eval_frame" + ) + return callback + else: + return set_eval_frame(callback) + + +# The set of valid stance strings accepted by torch.compiler.set_stance. Kept as +# a shared alias so producers (set_stance) and the exhaustive consumer +# (_callback_from_stance) stay in sync at type-check time. +StanceStr = Literal[ + "default", + "eager_then_compile", + "aot_eager_then_compile", + "force_eager", + "eager_on_recompile", + "fail_on_recompile", +] + + +@dataclass +class DynamoStance: + stance: StanceStr = "default" + skip_guard_eval_unsafe: bool = False + backend: str | Callable[..., Any] | None = None + + +_stance = DynamoStance() +_force_eager_nested_compile = threading.local() + + +@contextlib.contextmanager +def _use_eager_on_nested_compile() -> Generator[None, None, None]: + """Run torch.compile wrappers eagerly inside compiler-internal tracing.""" + prior = getattr(_force_eager_nested_compile, "depth", 0) + _force_eager_nested_compile.depth = prior + 1 + try: + yield + finally: + _force_eager_nested_compile.depth = prior + + +def _is_eager_on_nested_compile() -> bool: + return getattr(_force_eager_nested_compile, "depth", 0) > 0 + + +def _set_stance(stance: DynamoStance) -> DynamoStance: + global _stance + + from torch._C._dynamo.eval_frame import get_eval_frame_callback + + callback = get_eval_frame_callback() + + if callback is not False and callback is not None: + raise RuntimeError("attempted to set_stance in a torch.compile region") + + prior = _stance + _stance = stance + return prior + + +_set_stance._dynamo_forbidden = True # type: ignore[attr-defined] + +_EXAMPLE_INPUTS: dict[str, list[Any]] | None = None + + +def get_example_inputs(key: str) -> list[Any]: + global _EXAMPLE_INPUTS + if _EXAMPLE_INPUTS is None: + _EXAMPLE_INPUTS = {} + + if key not in _EXAMPLE_INPUTS: + _EXAMPLE_INPUTS[key] = [] + + return _EXAMPLE_INPUTS[key] + + +@contextlib.contextmanager +def _set_in_optimized_module() -> Generator[None, None, None]: + # Set in dynamo's OptimizedModule forward, to have better coverage than is_compiling(). + # Prevents graph-breaking forward hooks from being registered & traced. + # TODO(pianpwk): subsume this flag with better is_compiling() coverage + global _in_optimized_module + _old_in_optimized_module = ( + _in_optimized_module # do we need this? can we just set it to False after + ) + _in_optimized_module = True + try: + yield + finally: + _in_optimized_module = _old_in_optimized_module + + +def _is_in_optimized_module() -> bool: + global _in_optimized_module + return _in_optimized_module + + +def _callback_from_stance(callback: DynamoCallback) -> DynamoCallback: + if _stance.stance == "default": + # force_backend + if _stance.backend is not None and callback not in (False, None): + callback = _create_wrapped_callback(get_compiler_fn(_stance.backend)) + + return callback + elif _stance.stance == "eager_then_compile": + if callback not in (False, None): + return _create_delayed_compile_callback(callback, _stance.stance) + return callback + elif _stance.stance == "aot_eager_then_compile": + if callback not in (False, None): + return _create_delayed_compile_callback(callback, _stance.stance) + return callback + elif _stance.stance == "force_eager": + # disable + return None + elif _stance.stance == "eager_on_recompile": + # run mode + return False + elif _stance.stance == "fail_on_recompile": + if callback in (False, None): + return callback + + def fail_callback( + frame: DynamoFrameType, *args: Any, **kwargs: Any + ) -> ConvertFrameReturn: + if trace_rules.check(frame.f_code): + return ConvertFrameReturn() + if not convert_frame.has_tensor_in_frame(frame): + return ConvertFrameReturn() + + from torch._C._dynamo.eval_frame import ( + _debug_get_cache_entry_list, + _debug_get_precompile_entries, + ) + from torch._dynamo.guards import get_and_maybe_log_recompilation_reasons + + message = ( + "Detected recompile when torch.compile stance is 'fail_on_recompile'. " + + f"filename: '{frame.f_code.co_filename}', " + + f"function name: '{frame.f_code.co_name}', " + + f"line number: {frame.f_lineno}" + ) + cache_entries = _debug_get_cache_entry_list(frame.f_code) + if cache_entries: + reasons = get_and_maybe_log_recompilation_reasons( + cache_entries, + frame, + innermost_backend(callback), # pyrefly: ignore [bad-argument-type] + skip_logging=True, + ) + if reasons: + failures = textwrap.indent("\n".join(reasons), "- ") + guard_failure_details = ( + f"triggered by the following guard failure(s):\n{failures}" + ) + message += f"\n{textwrap.indent(guard_failure_details, ' ')}" + precompile_entries = _debug_get_precompile_entries(frame.f_code) + if len(precompile_entries) > 0: + message += "\nFailed on the following precompiled guards: " + for entry in precompile_entries: + message += f"\n{entry.guard_manager}{entry.guard_manager.check_verbose(frame.f_locals)}" # type: ignore[attr-defined] + raise RuntimeError(message) + + # to prevent cache miss due to different backend + fail_callback._torchdynamo_orig_backend = callback # type: ignore[attr-defined] + + return fail_callback + else: + raise RuntimeError(f"invalid torch.compile stance '{_stance}'") + + +def _create_wrapped_callback( + compiler_fn: CompilerFn, +) -> convert_frame.CatchErrorsWrapper: + hooks = Hooks() + return convert_frame.catch_errors_wrapper( + convert_frame.convert_frame( # type: ignore[arg-type] + compiler_fn, + hooks, + ), + hooks, + ) + + +def _get_or_add_example_inputs(frame: DynamoFrameType) -> list[Any]: + key = frame.f_code.co_filename + str(frame.f_code.co_firstlineno) + example_inputs = get_example_inputs(key) + + if len(example_inputs) < 2: + example_inputs.append(clone_and_convert_to_meta(frame.f_locals)) + + return example_inputs + + +def _create_delayed_compile_callback( + callback: DynamoCallback, stance: StanceStr +) -> Callable[..., Any]: + def callback_fn(*args: Any, **kwargs: Any) -> convert_frame.ConvertFrameReturn: + frame = args[0] + example_inputs = _get_or_add_example_inputs(frame) + + if len(example_inputs) == 1: + if stance == "eager_then_compile": + return ConvertFrameReturn( + frame_exec_strategy=FrameExecStrategy( + FrameAction.DEFAULT, FrameAction.DEFAULT + ) + ) + elif stance == "aot_eager_then_compile": + aot_eager_fn = get_compiler_fn("aot_eager") + return _create_wrapped_callback(aot_eager_fn)(*args, **kwargs) + + dynamism = track_dynamism_across_examples(example_inputs) + code_context.get_context(frame.f_code)["dynamism"] = dynamism + compiler_fn = callback._torchdynamo_orig_backend._torchdynamo_orig_backend # type: ignore[union-attr] + return _create_wrapped_callback(compiler_fn)(*args, **kwargs) + + # to prevent cache miss due to different backend + callback_fn._torchdynamo_orig_backend = callback # type: ignore[attr-defined] + + return callback_fn + + +def _is_skip_guard_eval_unsafe_stance() -> bool: + return _stance.skip_guard_eval_unsafe + + +def _reset_guarded_backend_cache() -> None: + global cached_backends + for backend in cached_backends.values(): + if hasattr(backend, "reset"): + backend.reset() + cached_backends.clear() + + +DONT_WRAP_FILES = { + # For tracing into fx modules + inspect.getsourcefile(GraphModule), + join(dirname(dirname(__file__)), "onnx/_internal/fx/dynamo_graph_extractor.py"), +} + + +def _debug_get_cache_entry_list( + code: types.CodeType | Callable[..., Any], +) -> list[CacheEntry]: + """ + Given a code object or a callable object, retrieve the cache entries + stored in this code. + """ + if callable(code): + code = code.__code__ + return torch._C._dynamo.eval_frame._debug_get_cache_entry_list(code) + + +def _get_cache_entries_for_region( + code: types.CodeType | Callable[..., Any], + isolate_recompiles_id: int, +) -> list[CacheEntry]: + """ + Return the cache entries for a specific isolate_recompiles region on + ``code``, in LRU order (most-recently-used first). + + Pass ``isolate_recompiles_id=-1`` to get the default (non-isolated) + bucket; pass a region's id (as exposed via + ``opt._isolate_recompiles_id``) to get that region's bucket. + + Returns only entries owned by the requested bucket. During an actual + lookup, isolated regions also fall back read-only to the default + bucket for BC-friendly reuse — this helper does not include those + fallback entries. + """ + if callable(code): + code = code.__code__ + return torch._C._dynamo.eval_frame._get_cache_entries_for_region( + code, isolate_recompiles_id + ) + + +def _get_total_cache_entry_count( + code: types.CodeType | Callable[..., Any], +) -> int: + """Total cache entries across all isolate_recompiles regions for a code object.""" + if callable(code): + code = code.__code__ + return torch._C._dynamo.eval_frame._get_total_cache_entry_count(code) + + +class OptimizedModule(torch.nn.Module): + """ + Wraps the original nn.Module object and later patches its + forward method to optimized self.forward method. + """ + + _torchdynamo_orig_callable: Callable[..., Any] + get_compiler_config: Callable[[], CompilerConfig | None] + + _opt_mod_attributes = { + "_orig_mod", + "dynamo_ctx", + "_torchdynamo_orig_callable", + "_torchdynamo_wrapper_id", + "get_compiler_config", + "forward", + "_forward", + "__dict__", + "named_children_walk", + "_super_module_initialized", + } + + @staticmethod + def _forward_has_skip_rule(mod: torch.nn.Module) -> bool: + return isinstance(mod.forward, types.MethodType) and trace_rules.check( + mod.forward + ) + + @staticmethod + def _should_wrap_module_call_impl(fn: Any) -> bool: + if getattr(fn, "__name__", "") != "_call_impl": + return False + + mod = getattr(fn, "__self__", None) + if not isinstance(mod, torch.nn.Module): + return False + return OptimizedModule._forward_has_skip_rule(mod) + + def __init__(self, mod: torch.nn.Module, dynamo_ctx: _TorchDynamoContext) -> None: + # NOTE: this must go first, because attribute reads/writes of `self` + # uses `_orig_mod`, and sometimes users override `Module.__init__` to + # do attribute reads/writes on `self`. + # + # We also can't use regular setattr because `super().__setattr__` will + # complain for module value before `super().__init__()` + object.__setattr__(self, "_orig_mod", mod) + self._super_module_initialized = False + super().__init__() + self._super_module_initialized = True + + # Installs the params/buffer + self._orig_mod = mod # `super().__setattr__` will register this module + self.dynamo_ctx = dynamo_ctx + self._initialize() + self.training = self._orig_mod.training + + def __len__(self) -> int: + # Proxy the len call to the original module + # pyrefly: ignore [unsafe-overlap] + if isinstance(self._orig_mod, Sized): + return len(self._orig_mod) + # Mimic python's default behavior for objects without a length + raise TypeError(f"{type(self._orig_mod).__name__} does not support len()") + + def _initialize(self) -> None: + # Do this stuff in constructor to lower overhead slightly + if isinstance(self.dynamo_ctx, DisableContext): + # No need to check trace rules + self.forward = self.dynamo_ctx(self._orig_mod.__call__) + elif config.wrap_top_frame or self._forward_has_skip_rule(self._orig_mod): + # This may be a torch.nn.* instance in trace_rules.py which + # won't trigger a frame evaluation workaround to add an extra + # frame we can capture + self.forward = self.dynamo_ctx(external_utils.wrap_inline(self._orig_mod)) + else: + # Invoke hooks outside of dynamo then pickup the inner frame + self.forward = self.dynamo_ctx(self._orig_mod.__call__) + + if inspect.getattr_static(self._orig_mod, "_initialize_hook", None) is not None: + self._forward = self.forward + self.forward = self._call_lazy_check + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + if torch.nn.modules.module._has_any_global_hook(): + warnings.warn( + "Using `torch.compile(module)` when there are global hooks on " + "modules (e.g., from `register_module_forward_hook`); this will" + " cause the hooks to fire an extra time for the " + "`OptimizedModule` created by `torch.compile(module)`. If this " + "causes undesired behavior, please try using `module.compile()`" + ", or use the per-module hooks instead", + stacklevel=2, + ) + with _set_in_optimized_module(): + return super().__call__(*args, **kwargs) + + def _aot_compile(self, inputs: list[torch._dynamo.aot_compile.ModelInput]) -> None: + """ + Experimental: AOT Compile a set of inputs and use that as the forward function + """ + model = self._orig_mod + hooks = self.dynamo_ctx._hooks + if hooks is None: + raise AssertionError("hooks must not be None for AOT compilation") + if not config.enable_aot_compile: + raise RuntimeError( + "AOT Compile is not enabled, please set torch._dynamo.config.enable_aot_compile=True" + ) + if not self.dynamo_ctx.fullgraph: + raise RuntimeError( + "Graph breaks are not supported with aot compile. Please use torch.compile(fullgraph=True)." + ) + + if not callable(self.dynamo_ctx.callback): + raise RuntimeError("aot compile requires a callable dynamo callback.") + + backend = innermost_backend(self.dynamo_ctx.callback) + from torch._dynamo.aot_compile import aot_compile_module + + self.forward = aot_compile_module(model, inputs, hooks, backend) + + def _save_aot_compiled_module(self, path: str | None = None) -> bytes: + if not config.enable_aot_compile: + raise RuntimeError( + "AOT Compile is not enabled, please set torch._dynamo.config.enable_aot_compile=True" + ) + from torch._dynamo.aot_compile import AOTCompiledModel + + if not isinstance(self.forward, AOTCompiledModel): + raise AssertionError( + f"Expected self.forward to be AOTCompiledModel, got {type(self.forward)}" + ) + result: bytes = self.forward.serialize() + if path is not None: + with open(path, "wb") as f: + f.write(result) + return result + + def _load_aot_compiled_module(self, data: bytes) -> None: + if not config.enable_aot_compile: + raise RuntimeError( + "AOT Compile is not enabled, please set torch._dynamo.config.enable_aot_compile=True" + ) + from torch._dynamo.aot_compile import AOTCompiledModel + + compiled_forward = AOTCompiledModel.deserialize(self._orig_mod, data) + if not isinstance(compiled_forward, AOTCompiledModel): + raise AssertionError( + f"Expected compiled_forward to be AOTCompiledModel, got {type(compiled_forward)}" + ) + self.forward = compiled_forward + + def __reduce__( + self, + ) -> tuple[type[OptimizedModule], tuple[torch.nn.Module, _TorchDynamoContext]]: + return (self.__class__, (self._orig_mod, self.dynamo_ctx)) + + def __getstate__(self) -> dict[str, Any]: + state = dict(self.__dict__) + state.pop("forward", None) + state.pop("__call__", None) + return state + + def __setstate__(self, state: dict[str, Any]) -> None: + self.__dict__ = state + self._initialize() + + @property + # pyrefly: ignore [bad-override] + def training(self) -> bool: + return self._orig_mod.training + + @training.setter + def training(self, value: bool) -> None: + # Ignore the `training` mutation in `super().__init__()`, since that's + # setting the default on `nn.Module`, but we are mirroring the + # `training` attr in `self._orig_mod`. + if self._super_module_initialized: + self._orig_mod.training = value + + def __getattr__(self, name: str) -> Any: + if name == "_orig_mod": + return self._modules["_orig_mod"] + return getattr(self._orig_mod, name) + + def __setattr__(self, name: str, value: Any) -> None: + # Allow patching over class attributes + if hasattr(type(self), name): + return super().__setattr__(name, value) + + if name in OptimizedModule._opt_mod_attributes: + return super().__setattr__(name, value) + return setattr(self._orig_mod, name, value) + + def __delattr__(self, name: str) -> None: + # This mirrors `__setattr__` + if hasattr(type(self), name): + return super().__delattr__(name) + + if name in OptimizedModule._opt_mod_attributes: + return super().__delattr__(name) + return delattr(self._orig_mod, name) + + def _call_lazy_check(self, *args: Any, **kwargs: Any) -> Any: + if ( + inspect.getattr_static(self._orig_mod, "_initialize_hook", None) is not None + and inspect.getattr_static(self._orig_mod, "_infer_parameters", None) + is not None + and callable(self._orig_mod._infer_parameters) + ): + # In the case of a lazy module, we want to run + # the pre-hooks which initialize it. + # Afterwards, lazy module deletes its pre-hooks + # to avoid treating it as lazy on subsequent recompile. + self._orig_mod._infer_parameters(self._orig_mod, args, kwargs) + return self._forward(*args, **kwargs) + + def __dir__(self) -> list[str]: + orig_mod_attrs = self._orig_mod.__dir__() + return orig_mod_attrs + [ + attr for attr in super().__dir__() if attr not in orig_mod_attrs + ] + + +def remove_from_cache(f: Any) -> None: + """ + Make sure f.__code__ is not cached to force a recompile + """ + if isinstance(f, types.CodeType): + reset_code(f) + elif hasattr(f, "__code__"): + reset_code(f.__code__) + elif hasattr(getattr(f, "forward", None), "__code__"): + reset_code(f.forward.__code__) + else: + from . import reset # type: ignore[attr-defined] + + reset() + log.warning("could not determine __code__ for %s", f) + + +def nothing() -> None: + pass + + +def always_false() -> bool: + return False + + +def _static_getattr(obj: Any, name: str, default: Any = None) -> Any: + # Not inspect.getattr_static: this runs while the eval frame callback is + # installed, so its Python frames land in Dynamo's frame counters. + try: + return object.__getattribute__(obj, name) + except AttributeError: + return default + + +def innermost_fn(fn: Callable[..., Any]) -> Callable[..., Any]: + """ + In case of nesting of _TorchDynamoContext calls, find the innermost + function. TorchDynamo caches on fn.__code__ object, so its necessary to find + the innermost function to pass on the optimize, run, disable etc. + """ + # Probe statically so these lookups never run a user-defined __getattr__, + # which may not tolerate unknown names. + unaltered_fn = fn + while ( + _static_getattr(unaltered_fn, "_torchdynamo_orig_callable") is not None + # Only follow the chain if _torchdynamo_wrapper_id matches id(fn). + # This prevents following chains in two cases: + # 1. Bound methods: id(bound_method) != id(wrapper_function), so we + # won't unwrap through __func__ and lose the self binding. + # 2. functools.wraps copies: When functools.wraps copies + # _torchdynamo_orig_callable from a wrapped function, the copied + # _torchdynamo_wrapper_id won't match the outer wrapper's id. + and _static_getattr(unaltered_fn, "_torchdynamo_wrapper_id") == id(unaltered_fn) + ): + # pyrefly: ignore [missing-attribute] + unaltered_fn = unaltered_fn._torchdynamo_orig_callable + if not callable(unaltered_fn): + raise AssertionError( + f"A callable function is expected, but {type(unaltered_fn)} is provided." + ) + return unaltered_fn + + +def innermost_backend(fn: Callable[..., Any]) -> Callable[..., Any]: + """ + Unwrap backend wrapper chain via _torchdynamo_orig_backend to find the + innermost backend function. + """ + while hasattr(fn, "_torchdynamo_orig_backend"): + fn = fn._torchdynamo_orig_backend + if not callable(fn): + raise AssertionError( + f"A callable function is expected, but {type(fn)} is provided." + ) + return fn + + +def make_set_enable_dynamic(enable: bool) -> Any: + if not isinstance(enable, bool): + raise AssertionError(f"Expected enable to be a bool, got {type(enable)}") + if enable: + # Assume everything is dynamic by default + return config._make_closure_patcher(assume_static_by_default=False) + else: + return config._make_closure_patcher( + automatic_dynamic_shapes=False, assume_static_by_default=True + ) + + +@contextlib.contextmanager +def set_enable_dynamic(enable: bool) -> Generator[None, None, None]: + cleanup = make_set_enable_dynamic(enable)() + try: + yield + finally: + cleanup() + + +# A thread local storage that serves to store information as Dynamo traces +# through a user provided function. +class DynamoTLS(threading.local): + # Each string is a summary of a frame Dynamo attempted to trace, stored in + # temporal order. + traced_frame_infos: list[str] = [] + + # Accumulated skip reasons during a fullgraph compile_wrapper call. + # Each entry is a formatted string like "fn (file.py:42): reason". + # None when not collecting (fullgraph not active). + skip_reasons: list[str] | None = None + + +dynamo_tls = DynamoTLS() + + +def reset_skip_reasons() -> None: + dynamo_tls.skip_reasons = [] + + +def add_skip_reason(reason: str, frame: DynamoFrameType) -> None: + if dynamo_tls.skip_reasons is not None: + code = frame.f_code + dynamo_tls.skip_reasons.append( + f"{code.co_name} ({code.co_filename}:{code.co_firstlineno}): {reason}" + ) + + +def get_skip_reasons() -> list[str]: + return dynamo_tls.skip_reasons or [] + + +def clear_dynamo_tls() -> None: + dynamo_tls.traced_frame_infos.clear() + dynamo_tls.skip_reasons = None + + +@atexit.register +def _log_traced_frames() -> None: + """ + At program exit, log all of the frames Dynamo has attempted to trace from, + excluding the continuation frames generated by Dynamo. + """ + msg = "\n".join(dynamo_tls.traced_frame_infos) + msg = textwrap.indent(msg, " * ") + msg = f"TorchDynamo attempted to trace the following frames: [\n{msg}\n]" + log.info(msg) + + +def guard_collectives_hook(guard_eval_result: bool) -> bool: + import torch.distributed as dist + from torch._dynamo.utils import dynamo_timed + + # guard_eval_result == True ==> cache hit + if pg := distributed.get_guard_pg(): + with dynamo_timed( + "guard_collective", log_pt2_compile_event=False, log_waitcounter=True + ): + log.debug("guard_collective %s", guard_eval_result) + # TODO: a bit awkward to time, this isn't inside of the dynamo compile region + all_results = [None] * pg.size() + dist.all_gather_object(all_results, guard_eval_result, group=pg) + # True = everyone hit, OK to run + # False = someone missed, force recompile everywhere + res = all(all_results) + log.debug("guard_collective %s -> %s", guard_eval_result, res) + return res + return guard_eval_result + + +_not_set = object() + + +class _TorchDynamoContext: + def __init__( + self, + callback: DynamoCallback, + on_enter: Callable[[], Any] = nothing, + backend_ctx_ctor: Callable[ + [], contextlib.AbstractContextManager[Any] + ] = null_context, + patch_fn: Callable[[], Any] = nothing, + first_ctx: bool = False, + *, + fullgraph: bool = False, + error_on_graph_break: bool | None = None, + export: bool = False, + dynamic: bool | None = None, + compiler_config: CompilerConfig | None = None, + package: CompilePackage | None = None, + hooks: Hooks | None = None, + isolate_recompiles: bool = False, + dynamic_shapes: ShapesSpec | ParamsSpec | dict[str, Any] | None = None, + ) -> None: + super().__init__() + if not (callable(callback) or callback is False or callback is None): + raise AssertionError( + f"callback must be callable, False, or None, got {type(callback)}" + ) + # Normalize the shorthand forms: dict / ParamsSpec / ShapesSpec all + # land here as a ShapesSpec (or None). + dynamic_shapes = _coerce_to_shapes_spec(dynamic_shapes) + self.callback: DynamoCallback = callback + self._backend_ctx_ctor = backend_ctx_ctor + self.prior: Unset | DynamoCallback = unset + self.first_ctx = first_ctx + self.fullgraph = fullgraph + self.error_on_graph_break = error_on_graph_break + self.export = export + self._dynamic = dynamic + self._dynamic_shapes = dynamic_shapes + self.compiler_config = compiler_config + self.cleanup_fns: list[Callable[[], Any]] = [] + self.enter_exit_hooks = [] + self._package = package + self._hooks = hooks + self._isolate_recompiles_id = ( + next(_next_isolate_recompiles_id) if isolate_recompiles else -1 + ) + patch_fn() + + # Save the backends so that we can reset them during torch._dynamo.reset + backend = innermost_backend(callback) # type: ignore[arg-type] + cached_backends.setdefault(id(backend), backend) # type: ignore[arg-type] + + if dynamic is not None and dynamic_shapes is not None: + raise ValueError( + "`dynamic` and `dynamic_shapes` cannot both be set. " + "`dynamic_shapes` controls dynamic behavior." + ) + + if dynamic is not None: + self.enter_exit_hooks.append(make_set_enable_dynamic(dynamic)) + + if dynamic_shapes is not None: + self.enter_exit_hooks.append( + config._make_closure_patcher(_dynamic_shapes_spec=dynamic_shapes) + ) + + if on_enter is not nothing: + # this case is not common + def call_on_enter() -> Callable[[], None]: + on_enter() + return nothing + + self.enter_exit_hooks.append(call_on_enter) + + if backend_ctx_ctor is not contextlib.nullcontext: + # this case is not common + def call_backend_ctx() -> functools.partial[bool | None]: + ctx = backend_ctx_ctor() + ctx.__enter__() + return functools.partial(ctx.__exit__, None, None, None) + + self.enter_exit_hooks.append(call_backend_ctx) + + def __enter__(self) -> None: + if config.raise_on_ctx_manager_usage: + raise RuntimeError( + "torch._dynamo.optimize(...) is used with a context manager. " + "Please refer to https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html " + "to use torch._dynamo.optimize(...) as an annotation/decorator. " + ) + self.prior = set_eval_frame(None) + self.cleanup_fns = [enter() for enter in self.enter_exit_hooks] + self.prior_skip_guard_eval_unsafe = set_skip_guard_eval_unsafe( + _is_skip_guard_eval_unsafe_stance() + ) + _maybe_set_eval_frame(_callback_from_stance(self.callback)) + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: types.TracebackType | None, + ) -> bool | None: + if self.prior is unset: + raise AssertionError("__exit__ called without matching __enter__") + set_eval_frame(None) + set_skip_guard_eval_unsafe(self.prior_skip_guard_eval_unsafe) + for cleanup in self.cleanup_fns: + cleanup() + self.cleanup_fns.clear() + _maybe_set_eval_frame(_callback_from_stance(self.prior)) + self.prior = unset + return None + + def __call__(self, fn: Any) -> Any: + if isinstance(fn, staticmethod): + return staticmethod(self(fn.__func__)) + + # public api for compiler config/options + def get_compiler_config() -> CompilerConfig | None: + return self.compiler_config + + from .package import DynamoCache + + # If self._package is lazily initialized, we should check the dynamo cache now + if config.caching_precompile: + if self._package is not None and not self._package.is_initialized(): + fn_key = fn.forward if isinstance(fn, torch.nn.Module) else fn + result = DynamoCache.load(fn_key) + if result is None: + # Create a fresh CompilePackage + self._package.initialize(fn_key, None, ignore_inlined_sources=False) + else: + try: + self._package.initialize( + fn_key, result.dynamo, ignore_inlined_sources=False + ) + self._package.install(result.backends) + except RuntimeError: + log.warning( + "Failed to load entry from dynamo cache", exc_info=True + ) + self._package.initialize( + fn_key, None, ignore_inlined_sources=False + ) + + fn = innermost_fn(fn) + + def aot_compile(example_inputs: tuple[tuple[Any, ...], dict[str, Any]]) -> Any: + from torch._dynamo.aot_compile import aot_compile_fullgraph + + if torch._inductor.config.force_disable_caches: + raise RuntimeError( + "Cannot precompile with torch._inductor.config.force_disable_caches=True; caching is required." + ) + + if not self.fullgraph: + raise RuntimeError( + "Graph breaks are not supported with aot compile. Please use torch.compile(fullgraph=True)." + ) + + if not callable(self.callback): + raise RuntimeError("aot compile requires a callable dynamo callback.") + + if self._hooks is None: + raise AssertionError("hooks must not be None for AOT compilation") + + return aot_compile_fullgraph( + fn, + example_inputs, + hooks=self._hooks, + backend=innermost_backend(self.callback), + dynamic=self._dynamic, + ) + + # add context containing GraphModule to any GraphModule forward functions + if isinstance(fn, GraphModule): + # add context containing GraphModule to any GraphModule forward functions + code_context.get_context(fn.forward.__code__)["orig_graphmodule"] = ( + weakref.ref(fn) + ) + + # Optimize the forward method of torch.nn.Module object + if isinstance(fn, torch.nn.Module): + if type(fn) is torch.jit._script.RecursiveScriptModule: + raise RuntimeError( + "torch.compile does not support compiling torch.jit.script or " + "torch.jit.freeze models directly.\n\n" + "Workaround: compile the original eager module instead:\n" + " model = torch.nn.Linear(3, 3)\n" + " compiled_model = torch.compile(model) # compile the eager module\n\n" + "torch.jit.script and torch.jit.freeze are deprecated in favor of " + "torch.compile. See https://pytorch.org/docs/main/jit.html for details." + ) + mod = fn + new_mod = OptimizedModule(mod, self) + # Save the function pointer to find the original callable while nesting + # of decorators. + new_mod._torchdynamo_orig_callable = mod.forward + new_mod._torchdynamo_wrapper_id = id(new_mod) + + # when compiling torch.nn.Module, + # provide public api OptimizedModule.get_compiler_config() + # check mod, not new_mod: OptimizedModule.__getattr__ delegates to mod + if inspect.getattr_static(mod, "get_compiler_config", None) is not None: + raise AssertionError( + "new_mod already has a get_compiler_config attribute" + ) + new_mod.get_compiler_config = get_compiler_config + + return new_mod + + if inspect.isclass(fn): + # User has wrapped the class with compile/disable decorator. Apply + # disable to init/call method. + cls_obj = fn + cls_obj.__call__ = self(cls_obj.__call__) + if issubclass(cls_obj, torch.nn.Module): + # NN module variable tracker directly inlines the _call_impl. + cls_obj._call_impl = self(cls_obj._call_impl) + return cls_obj + + if not callable(fn): + raise AssertionError( + f"A callable function is expected, but {type(fn)} is provided." + ) + + # NOTE [Top-level TorchInGraph and polyfilled functions] + # Some callables (e.g. torch.exp) are represented as TorchInGraphFunctionVariable + # when traced inside a frame. When such a function is passed directly to + # torch.compile, we detect it here so we can force it through wrap_inline. + # Similarly, functions registered via substitute_in_graph have a polyfill + # that Dynamo can trace, so they also need wrap_inline. + from .variables import TorchInGraphFunctionVariable + + rule = trace_rules.lookup(fn) + top_level_in_graph = isinstance(rule, type) and issubclass( + rule, TorchInGraphFunctionVariable + ) + has_polyfill = trace_rules.is_polyfilled_callable(fn) + + try: + filename = inspect.getsourcefile(fn) + except TypeError: + filename = None + should_wrap_module_call_impl = OptimizedModule._should_wrap_module_call_impl(fn) + if config.debug_force_nested_calls and filename not in DONT_WRAP_FILES: + fn = external_utils.wrap_inline(fn) + # Create a new code object for `fn` so that functions have different + # recompilation caches. + # Copy hack since deepcopy doesn't actually give a new code object + fn.__code__ = fn.__code__.replace(co_varnames=fn.__code__.co_varnames) # type: ignore[attr-defined] + elif config.wrap_top_frame or ( + ( + # exec/eval'd Python functions also report no source file + # but can be traced directly; wrapping collapses them onto + # wrap_inline's shared `inner` code (#124269). + (filename is None and not inspect.isfunction(fn)) + or trace_rules.check(fn) + or top_level_in_graph + or has_polyfill + ) + and ( + getattr(fn, "__name__", "") + not in ["_call_impl", "_wrapped_call_impl", "_lazy_forward"] + or should_wrap_module_call_impl + ) + and filename not in DONT_WRAP_FILES + ): + # call to a builtin without a frame for us to capture + fn = external_utils.wrap_inline(fn) + + def do_nothing(*arg: Any, **kwargs: Any) -> None: + pass + + callback: Callable[..., Any] = do_nothing + if hasattr(self, "callback"): + callback = self.callback # type: ignore[assignment] + + is_jit_tracing = torch._C._is_tracing + is_fx_symbolic_tracing = torch.fx._symbolic_trace.is_fx_symbolic_tracing + + @functools.wraps(fn) + def compile_wrapper(*args: Any, **kwargs: Any) -> Any: + # NB: function calls here could change global state (e.g. random state) + # and that can result in different behavior between eager and compiled! + # In particular, we don't have control over internal functions like justknobs_check + # called in _maybe_set_eval_frame. + # Unlike in eval_frame_cpp.cpp/convert_frame.py, we don't attempt to restore global state + # due to additional overhead costs. + prior = set_eval_frame(None) + prior_error_on_nested_compile: bool | None = None + fullgraph_count_enabled = False + # Fake propagation and AOT metadata collection execute user + # subclass code under active fake/functional modes. Nested compile + # must run the original function in those regions. Still honor + # explicit/internal requests to compile during FX tracing: HOP export + # depends on its internal compile to preserve HOPs, and some tests + # intentionally enable force_compile_during_fx_trace to get nested + # subgraphs. + if ( + _is_eager_on_nested_compile() + and not config.force_compile_during_fx_trace + ): + from torch._higher_order_ops.utils import _in_hop_compile + + if not _in_hop_compile(): + try: + return fn(*args, **kwargs) + finally: + _maybe_set_eval_frame(prior) + + if self.fullgraph: + prior_error_on_nested_compile = set_fullgraph_error_on_nested_compile( + torch._dynamo.config.error_on_dynamo_callback_in_fullgraph_compiled_code + ) + if not self.export: + fullgraph_count_enabled = set_fullgraph_compiled_frame_count(0) < 0 + if fullgraph_count_enabled: + reset_skip_reasons() + try: + # We shouldn't compile inside kernel invocation. + if tracing_context := torch._guards.TracingContext.try_get(): + if ( + tracing_context.fake_mode is not None + and tracing_context.fake_mode.in_kernel_invocation + ): + return fn(*args, **kwargs) + # Skip nested compile during export (but not HOP internal compile) + # Only skip if there's an active TracingContext (nested), not for top-level export + if ( + torch.compiler.is_exporting() + and not config.force_compile_during_fx_trace + ): + from torch._higher_order_ops.utils import _in_hop_compile + + if not _in_hop_compile(): + if torch._guards.TracingContext.try_get() is not None: + return fn(*args, **kwargs) + # Skip nested compile - just inline the function + if ( + is_fx_symbolic_tracing() + and not config.force_compile_during_fx_trace + ): + if config.error_on_nested_fx_trace: + raise RuntimeError( + "Detected that you are using FX to symbolically trace " + "a dynamo-optimized function. This is not supported at the moment." + ) + else: + return fn(*args, **kwargs) + + if is_jit_tracing(): + raise RuntimeError( + "Detected that you are using FX to torch.jit.trace " + "a dynamo-optimized function. This is not supported at the moment." + ) + + cleanups = [enter() for enter in self.enter_exit_hooks] + prior_skip_guard_eval_unsafe = set_skip_guard_eval_unsafe( + _is_skip_guard_eval_unsafe_stance() + ) + prior_isolate_recompiles_id = set_eval_frame_isolate_recompiles_id( + self._isolate_recompiles_id + ) + prior_error_on_graph_break = None + if not self.fullgraph and self.error_on_graph_break is not None: + current_error_on_graph_break = _get_error_on_graph_break() + if current_error_on_graph_break != self.error_on_graph_break: + prior_error_on_graph_break = current_error_on_graph_break + _set_error_on_graph_break(self.error_on_graph_break) + + # Ensure that if an assertion occurs after graph pushes + # something onto the DynamicLayerStack then we pop it off (the + # constructed graph code isn't guarded with try/finally). + # + # This used to be a context but putting a `with` here is a noticeable + # perf regression (#126293) + saved_dynamic_layer_stack_depth = ( + torch._C._functorch.get_dynamic_layer_stack_depth() + ) + + _maybe_set_eval_frame(_callback_from_stance(callback)) + + # Snapshot the local dispatch key set onto a C++ thread-local + # stack so it can be restored after the compiled call, matching + # the old _ForceDispatchKeyGuard behavior. Keeping the snapshot + # in C++ avoids constructing pybind11 DispatchKeySet / + # context-manager instances on every compiled call. The restore + # runs in the outer finally below (after the inner finally, i.e. + # after pop_dynamic_layer_stack) so the save/restore stack stays + # balanced even if the inner finally itself raises (e.g. the + # fullgraph "found no compiled frames" error). + torch._C._dynamo_save_local_dispatch_key_set() + try: + call_succeeded = False + try: + result = fn(*args, **kwargs) + call_succeeded = True + except (Unsupported, UncapturedHigherOrderOpError, UserError) as e: + if config.verbose: + raise + # strip internal tracebacks from causes + cur_exn: BaseException = e + while cur_exn.__cause__ is not None: + cur_exn.__cause__.with_traceback(None) + cur_exn = cur_exn.__cause__ + + raise e.with_traceback( + None + ) from e.__cause__ # User compiler error + except ShortenTraceback as e: + # Failures in the backend likely don't have useful + # data in the TorchDynamo frames, so we strip them out. + raise e.remove_dynamo_frames() from None # see TORCHDYNAMO_VERBOSE=1 + finally: + # Restore the dynamic layer stack depth if necessary. + set_eval_frame(None) + if fullgraph_count_enabled and call_succeeded: + count = set_fullgraph_compiled_frame_count(-1) + if count == 0 and _stance.stance == "default": + skip_reasons = get_skip_reasons() + msg = "torch.compile with fullgraph=True found no compiled frames." + if skip_reasons: + reasons_str = "\n".join( + f" - {r}" for r in skip_reasons + ) + msg += f" Skipped frames:\n{reasons_str}" + else: + msg += ( + " Compilation was not attempted and no cached compiled" + " code was found." + ) + raise RuntimeError(msg) + if prior_error_on_graph_break is not None: + _set_error_on_graph_break(prior_error_on_graph_break) + if prior_error_on_nested_compile is not None: + set_fullgraph_error_on_nested_compile( + prior_error_on_nested_compile + ) + torch._C._functorch.pop_dynamic_layer_stack_and_undo_to_depth( + saved_dynamic_layer_stack_depth + ) + + set_skip_guard_eval_unsafe(prior_skip_guard_eval_unsafe) + set_eval_frame_isolate_recompiles_id( + prior_isolate_recompiles_id + ) + for cleanup in cleanups: + cleanup() + finally: + # Restore the local dispatch key set snapshotted above. In an + # outer finally so it runs even if the inner finally raised, + # keeping the save/restore stack balanced. + torch._C._dynamo_restore_local_dispatch_key_set() + return result + finally: + if fullgraph_count_enabled: + set_fullgraph_compiled_frame_count(-1) + dynamo_tls.skip_reasons = None + _maybe_set_eval_frame(prior) + + # hooks to properly handle inlining + if self.error_on_graph_break is not None: + compile_wrapper._torchdynamo_inline = ( # type: ignore[attr-defined] + external_utils.wrap_inline_with_error_on_graph_break( + fn, self.error_on_graph_break + ) + ) + else: + compile_wrapper._torchdynamo_inline = fn # type: ignore[attr-defined] + # Save the function pointer to find the original callable while nesting + # of decorators. + compile_wrapper._torchdynamo_orig_callable = fn # type: ignore[attr-defined] + compile_wrapper._torchdynamo_wrapper_id = id(compile_wrapper) # type: ignore[attr-defined] + compile_wrapper._isolate_recompiles_id = self._isolate_recompiles_id # type: ignore[attr-defined] + + # when compiling user function instead of nn.Module + # provide public api _fn.get_compiler_config() + if hasattr(compile_wrapper, "get_compiler_config"): + raise AssertionError( + "compile_wrapper already has a get_compiler_config attribute" + ) + compile_wrapper.get_compiler_config = get_compiler_config # type: ignore[attr-defined] + if torch._dynamo.config.enable_aot_compile: + compile_wrapper.aot_compile = aot_compile # type: ignore[attr-defined] + + # If the function is called using torch._dynamo.optimize decorator, we + # should prevent any type of skipping. + if callback not in (None, False): + if not hasattr(fn, "__code__"): + raise RuntimeError( + textwrap.dedent( + """ + + torch._dynamo.optimize is called on a non function object. + If this is a callable class, please wrap the relevant code into a function and optimize the + wrapper function. + + >> class CallableClass: + >> def __init__(self) -> None: + >> super().__init__() + >> self.relu = torch.nn.ReLU() + >> + >> def __call__(self, x): + >> return self.relu(torch.sin(x)) + >> + >> def print_hello(self): + >> print("Hello world") + >> + >> mod = CallableClass() + + If you want to optimize the __call__ function and other code, wrap that up in a function + + >> def wrapper_fn(x): + >> y = mod(x) + >> return y.sum() + + and then optimize the wrapper_fn + + >> opt_wrapper_fn = torch._dynamo.optimize(wrapper_fn) + """ + ) + ) + always_optimize_code_objects[fn.__code__] = True + + return compile_wrapper + + +class OptimizeContext(_TorchDynamoContext): + def __init__( + self, + callback: DynamoCallback, + backend_ctx_ctor: Callable[[], contextlib.AbstractContextManager[Any]], + first_ctx: bool = False, + *, + fullgraph: bool = False, + error_on_graph_break: bool | None = None, + export: bool = False, + dynamic: bool | None = None, + compiler_config: CompilerConfig | None = None, + rebuild_ctx: Callable[[], OptimizeContext | _NullDecorator] | None = None, + package: CompilePackage | None = None, + hooks: Hooks | None = None, + isolate_recompiles: bool = False, + dynamic_shapes: ShapesSpec | ParamsSpec | dict[str, Any] | None = None, + ) -> None: + def on_enter() -> None: + install_generation_tagging_init() + + super().__init__( + callback=callback, + on_enter=on_enter, + backend_ctx_ctor=backend_ctx_ctor, + patch_fn=TorchPatcher.patch, + first_ctx=first_ctx, + fullgraph=fullgraph, + error_on_graph_break=error_on_graph_break, + export=export, + dynamic=dynamic, + compiler_config=compiler_config, + package=package, + hooks=hooks, + isolate_recompiles=isolate_recompiles, + dynamic_shapes=dynamic_shapes, + ) + + if config.compiled_autograd: + _dynamic = self._dynamic + if _dynamic is None: + _dynamic = not torch._dynamo.config.assume_static_by_default + + def call_compiled_autograd() -> functools.partial[bool | None]: + if rebuild_ctx is None: + raise AssertionError( + "rebuild_ctx must not be None for compiled autograd" + ) + compiler_fn = rebuild_ctx() + ctx = torch._dynamo.compiled_autograd._enable( + compiler_fn, + # pyrefly: ignore [bad-argument-type] + dynamic=_dynamic, + ignore_active_disable_ctx=False, + ) + ctx.__enter__() + return functools.partial(ctx.__exit__, None, None, None) + + self.enter_exit_hooks.append(call_compiled_autograd) + + def __call__(self, fn: Any) -> Any: + result = super().__call__(fn) + result._is_torch_compile = True # type: ignore[attr-defined] + return result + + def __reduce__( + self, + ) -> tuple[type[OptimizeContext], tuple[Any, ...], dict[str, Any]]: + return ( + self.__class__, + (self.callback, self._backend_ctx_ctor, self.first_ctx), + { + "export": self.export, + "dynamic": self._dynamic, + "compiler_config": self.compiler_config, + }, + ) + + +class RunOnlyContext(_TorchDynamoContext): + def __init__(self) -> None: + # cudagraph trees relies on generation increment + def on_enter() -> None: + torch._dynamo.mutation_guard.GenerationTracker.generation += 1 + + super().__init__(callback=False, on_enter=on_enter) + + def __reduce__(self) -> tuple[type[RunOnlyContext], tuple[Any, ...]]: + return (self.__class__, ()) + + +class DisableContext(_TorchDynamoContext): + def __init__(self, msg: str | None = None, wrapping: bool = True) -> None: + super().__init__(callback=None) + self.msg = msg + self.wrapping = wrapping + + def __call__(self, fn: Callable[..., Any]) -> Callable[..., Any]: + # Earlier this code was in the base class _TorchDynamoContext. But we + # moved it here to have better code organization. For disable, we just + # want the callback to be None. We don't have to check trace_rules or + # create any wrapper. + fn = innermost_fn(fn) + + if isinstance(fn, torch.nn.Module): + mod = fn + new_mod = OptimizedModule(mod, self) + new_mod._torchdynamo_orig_callable = mod.forward + new_mod._torchdynamo_wrapper_id = id(new_mod) + return new_mod + + if isinstance(fn, type): + # User has wrapped the class with compile/disable decorator. Apply + # disable to init/call method. + cls_obj = fn + # Disable on init is useful for reconstruction of bytecodes where we + # want to prevent Dynamo from tracing into the init function. Check + # test_reconstruction in test_model_output.py. + cls_obj.__init__ = self(cls_obj.__init__) # type: ignore[misc] + cls_obj.__call__ = self(cls_obj.__call__) + if issubclass(cls_obj, torch.nn.Module): + # NN module variable tracker directly inlines the _call_impl. Disable it. + cls_obj._call_impl = self(cls_obj._call_impl) + return cls_obj + + if not callable(fn): + raise AssertionError( + f"A callable function is expected, but {type(fn)} is provided." + ) + + def _fn(*args: Any, **kwargs: Any) -> Any: + # Hot path (e.g. around custom operators); keep it minimal. + prior = set_eval_frame(None) + try: + # disable => self.callback is None; _callback_from_stance(None) is + # None ("off") for most stances but False (run-only) for + # eager_on_recompile. Install only when non-None (skips the + # justknob-guarded _maybe_set_eval_frame on the common path). + callback = _callback_from_stance(self.callback) + if callback is not None: + _maybe_set_eval_frame(callback) + try: + # Only export needs the annotation work. + if torch.compiler.is_exporting(): + fn_name = getattr(fn, "__name__", type(fn).__name__) + # Skip annotation for __torch_dispatch__ (internal detail). + if fn_name != "__torch_dispatch__": + with fx_traceback.annotate( + { + "_torchdynamo_disable": True, + "_torchdynamo_disable_recursive": True, + "_torchdynamo_disable_method": fn_name, + } + ): + return fn(*args, **kwargs) + return fn(*args, **kwargs) + finally: + if callback is not None: + set_eval_frame(None) + finally: + # Restore via _maybe_set_eval_frame so re-installing honors the + # enable_compiler_set_eval_frame killswitch; skip when prior None. + if prior is not None: + _maybe_set_eval_frame(prior) + + # Under some circumstances (e.g. precompile) we can end up calling @disable + # decorator in generated bytecode and trigger recompile. This is due to the + # fact that the old callback from torch.compile() is still active and under + # this circumstance we will trigger a failure with set_stance("fail_on_recompile"). + # Therefore we want to skip calling into any frame in this case. + if self.wrapping: + _fn = functools.wraps(fn)(_fn) + + _fn._torchdynamo_disable = True # type: ignore[attr-defined] + _fn._torchdynamo_disable_msg = self.msg # type: ignore[attr-defined] + + # Save the function pointer to find the original callable while nesting + # of decorators. + _fn._torchdynamo_orig_callable = fn # type: ignore[attr-defined] + _fn._torchdynamo_wrapper_id = id(_fn) # type: ignore[attr-defined] + + _fn._torchdynamo_disable_recursive = True # type: ignore[attr-defined] + + return _fn + + def __reduce__(self) -> tuple[type[DisableContext], tuple[Any, ...]]: + return (self.__class__, ()) + + +def _optimize_catch_errors( + compile_fn: convert_frame.ConvertFrameProtocol, + hooks: Hooks, + backend_ctx_ctor: Callable[ + [], contextlib.AbstractContextManager[Any] + ] = null_context, + fullgraph: bool = False, + error_on_graph_break: bool | None = None, + export: bool = False, + dynamic: bool | None = None, + compiler_config: CompilerConfig | None = None, + rebuild_ctx: Callable[[], OptimizeContext | _NullDecorator] | None = None, + package: CompilePackage | None = None, + isolate_recompiles: bool = False, + dynamic_shapes: ShapesSpec | ParamsSpec | dict[str, Any] | None = None, +) -> OptimizeContext: + return OptimizeContext( + convert_frame.catch_errors_wrapper(compile_fn, hooks), + backend_ctx_ctor=backend_ctx_ctor, + first_ctx=True, + fullgraph=fullgraph, + error_on_graph_break=error_on_graph_break, + export=export, + dynamic=dynamic, + compiler_config=compiler_config, + rebuild_ctx=rebuild_ctx, + package=package, + hooks=hooks, + isolate_recompiles=isolate_recompiles, + dynamic_shapes=dynamic_shapes, + ) + + +def get_compiler_fn( + compiler_fn: str | Callable[..., Any] | None, +) -> WrapBackendDebug: + from .repro.after_dynamo import wrap_backend_debug + + if compiler_fn is None: + # Special case None to avoid crashing in hasattr + compiler_str = None + elif hasattr(compiler_fn, "compiler_name"): + compiler_str = compiler_fn.compiler_name # type: ignore[union-attr] + if not isinstance(compiler_str, str): + raise AssertionError( + f"Expected compiler_name to be a str, got {type(compiler_str)}" + ) + elif isinstance(compiler_fn, str): + compiler_str = compiler_fn + else: + compiler_str = None + compiler_fn = lookup_backend(compiler_fn) # type: ignore[arg-type] + return wrap_backend_debug(compiler_fn, compiler_str) + + +class _NullDecorator(contextlib.nullcontext): # type: ignore[type-arg] + def __call__(self, fn: Callable[..., Any]) -> Callable[..., Any]: + if not callable(fn): + raise AssertionError( + f"A callable function is expected, but {type(fn)} is provided." + ) + return fn + + +# Make dynamo graph to have same input/output spec as user code +def argument_names( + f_sig: inspect.Signature, + args: list[Any] | tuple[Any, ...], + kwargs: dict[str, Any], +) -> list[str]: + def signature_to_fullargspec(sig: inspect.Signature) -> inspect.FullArgSpec: + # Get a list of Parameter objects from the Signature object + params = list(sig.parameters.values()) + # Separate positional arguments, keyword-only arguments and varargs/varkw + args = [ + p.name for p in params if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD + ] + kwonlyargs = [ + p.name for p in params if p.kind == inspect.Parameter.KEYWORD_ONLY + ] + varargs = next( + (p.name for p in params if p.kind == inspect.Parameter.VAR_POSITIONAL), + None, + ) + varkw = next( + (p.name for p in params if p.kind == inspect.Parameter.VAR_KEYWORD), + None, + ) + # Get default values for positional arguments and keyword-only arguments + defaults = tuple( + p.default + for p in params + if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD + and p.default is not inspect.Parameter.empty + ) + kwonlydefaults = { + p.name: p.default + for p in params + if p.kind == inspect.Parameter.KEYWORD_ONLY + and p.default is not inspect.Parameter.empty + } + # Get annotations for parameters and return value + # pyrefly: ignore [implicit-any] + annotations = {} + if sig.return_annotation: + annotations = {"return": sig.return_annotation} + for parameter in params: + annotations[parameter.name] = parameter.annotation + # Return a FullArgSpec object with the extracted attributes + return inspect.FullArgSpec( + args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations + ) + + fullargspec = signature_to_fullargspec(f_sig) + + # 1. Map `args` 1-to-1 to positional arguments in original signature. + input_strs = fullargspec.args[: len(args)] + + if len(args) > len(fullargspec.args): + # 2. If there are more arguments left in `args`, they map to varargs in original + # signature. Assign names as {varargs}_0, {varargs}_1, ... + if fullargspec.varargs is None: + raise AssertionError("More arguments than expected") + input_strs += [ + f"{fullargspec.varargs}_{i}" for i in range(len(args) - len(input_strs)) + ] + elif len(args) < len(fullargspec.args): + # 3. If there are fewer arguments in `args` than `fullargspec.args`, + # it implies these are arguments either with default values, or provided in + # `kwargs`. The former can be safely ignored. Because Dynamo.export does not + # export them as part of the function signature. The latter will be handled + # in the next step. + for unprovided_arg in fullargspec.args[ + len(args) : -len(fullargspec.defaults or []) + ]: + if unprovided_arg not in kwargs: + raise AssertionError(f"Missing argument {unprovided_arg}") + + # 4. Keyword arguments provided in `kwargs`. + input_strs += list(kwargs.keys()) + + # 5. Keyword-only arguments with default values if not provided are not exported + # as part of the function signature. + for kwonly_arg in fullargspec.kwonlyargs: + kwonlydefaults = fullargspec.kwonlydefaults or {} + if kwonly_arg not in kwargs and kwonly_arg not in kwonlydefaults: + raise AssertionError(f"Missing keyword only argument {kwonly_arg}") + + return input_strs + + +def check_if_dynamo_supported() -> None: + if sys.version_info >= (3, 15): + raise RuntimeError("Python 3.15+ not yet supported for torch.compile") + elif sysconfig.get_config_var("Py_GIL_DISABLED") == 1 and sys.version_info < ( + 3, + 13, + 3, + ): + raise RuntimeError( + "torch.compile is not supported on Python < 3.13.3 built with GIL disabled. " + "Please use Python 3.13.3+." + ) + + +def is_dynamo_supported() -> bool: + try: + check_if_dynamo_supported() + return True + except Exception: + return False + + +def check_if_inductor_supported() -> None: + check_if_dynamo_supported() + + +def is_inductor_supported() -> bool: + try: + check_if_inductor_supported() + return True + except Exception: + return False + + +def check_for_incompatible_configs() -> None: + # Some of the configs should be mutually exclusive + if config.suppress_errors and config.fail_on_recompile_limit_hit: + raise AssertionError( + "Dynamo configs suppress_error and fail_on_recompile_limit_hit can not both be active at the same time." + ) + + +def optimize(*args: Any, **kwargs: Any) -> OptimizeContext | _NullDecorator: + def rebuild_ctx() -> OptimizeContext | _NullDecorator: + ca_kwargs_override = config.compiled_autograd_kwargs_override + if ca_kwargs_override: + # NOTE: The process of translating other `torch.compile` kwargs to `torch._dynamo.optimize` kwargs + # is more complicated, we will add it in the future when needed. + if set(ca_kwargs_override.keys()) != {"fullgraph"}: + raise AssertionError( + f"Only `fullgraph` kwarg override is supported for now, but got {ca_kwargs_override.keys()}" + ) + kwargs["nopython"] = ca_kwargs_override["fullgraph"] + return optimize(*args, **kwargs) + + return _optimize(rebuild_ctx, *args, **kwargs) + + +def _optimize( + rebuild_ctx: Callable[[], OptimizeContext | _NullDecorator], + backend: str | Callable[..., Any] = "inductor", + *, + nopython: bool = False, + error_on_graph_break: bool | None = None, + guard_export_fn: Callable[[_guards.GuardsSet], None] | None = None, + guard_fail_fn: Callable[[GuardFail], None] | None = None, + guard_filter_fn: Callable[[Sequence[GuardFilterEntry]], Sequence[bool]] + | None = None, + disable: bool = False, + dynamic: bool | None = None, + package: CompilePackage | None = None, + recompile_limit: int | None = None, + isolate_recompiles: bool = False, + dynamic_shapes: ShapesSpec | ParamsSpec | dict[str, Any] | None = None, +) -> OptimizeContext | _NullDecorator: + """ + The main entrypoint of TorchDynamo. Do graph capture and call + backend() to optimize extracted graphs. + + Args: + backend: One of the two things: + - Either, a function/callable taking a torch.fx.GraphModule and + example_inputs and returning a python callable that runs the + graph faster. + One can also provide additional context for the backend, like + torch.jit.fuser("fuser2"), by setting the backend_ctx_ctor attribute. + See AOTAutogradMemoryEfficientFusionWithContext for the usage. + - Or, a string backend name in `torch._dynamo.list_backends()` + nopython: If True, graph breaks will be errors and there will + be a single whole-program graph. + error_on_graph_break: If not None, the current `error_on_graph_break` setting is set to the given value. + See `torch._dynamo.error_on_graph_break()` for more details on what `error_on_graph_break` means. + + Unlike `nopython=True` (i.e. `fullgraph=True`), there is no guarantee of a single whole-program graph. + If `nopython` is True, `error_on_graph_break` does nothing. + disable: If True, turn this decorator into a no-op + dynamic: If True, upfront compile as dynamic a kernel as possible. If False, + disable all dynamic shapes support (always specialize). If None, automatically + detect when sizes vary and generate dynamic kernels upon recompile. + recompile_limit: Maximum number of recompilations for this region. + If None, uses ``torch._dynamo.config.recompile_limit``. + isolate_recompiles: If True, this compile call gets its own isolated + cache so recompilations are tracked independently from other + compile calls on the same function. + + Example Usage:: + + @torch._dynamo.optimize() + def toy_example(a, b): ... + """ + check_if_dynamo_supported() + check_for_incompatible_configs() + # Note: The hooks object could be global instead of passed around, *however* that would make + # for a confusing API usage and plumbing story wherein we nest multiple .optimize calls. + # There is some prior art around this, w/r/t nesting backend calls are enforced to be the same + # compiler, however, this feels onerous for callback and hooks, and it feels better to give our users an + # easier to understand UX at the cost of a little more plumbing on our end. + hooks = Hooks( + guard_export_fn=guard_export_fn, + guard_fail_fn=guard_fail_fn, + guard_filter_fn=guard_filter_fn, + ) + torch._C._log_api_usage_once("torch._dynamo.optimize") + if ( + disable + or os.environ.get("TORCHDYNAMO_DISABLE", "") == "1" + or (not justknobs_check("pytorch/compiler:enable_dynamo")) + ): + return _NullDecorator() + + if nopython and not config.debug_force_graph_break_on_leaf_return: + return optimize_assert( + backend, + dynamic=dynamic, + hooks=hooks, + rebuild_ctx=rebuild_ctx, + package=package, + recompile_limit=recompile_limit, + isolate_recompiles=isolate_recompiles, + dynamic_shapes=dynamic_shapes, + ) + + backend = get_compiler_fn(backend) + + # Find if backend has any extra context manager + backend_ctx_ctor = getattr(backend, "backend_ctx_ctor", null_context) + + # The backend function is stashed in the callable returned by + # _optimize_catch_errors in the field _torchdynamo_orig_backend. This can + # be used by eval_frame.c to insert a guard on the backend. + + # With CachingPrecompile, instantiate an uninitialized CompilePackage + # which gets initialized by _optimize_catch_errors.__call__ once we have a function + if config.caching_precompile and package is None: + from .package import CompilePackage + + package = CompilePackage(fn=None, dynamo=None, ignore_inlined_sources=False) + + return _optimize_catch_errors( + convert_frame.convert_frame( + backend, + hooks, + package=package, + recompile_limit=recompile_limit, + ), + hooks, + backend_ctx_ctor, + fullgraph=False, + error_on_graph_break=error_on_graph_break + and not config.debug_force_graph_break_on_leaf_return, + dynamic=dynamic, + compiler_config=( + cast(CompilerConfigProvider, backend).get_compiler_config() + if hasattr(backend, "get_compiler_config") + else None + ), + rebuild_ctx=rebuild_ctx, + package=package, + isolate_recompiles=isolate_recompiles, + dynamic_shapes=dynamic_shapes, + ) + + +# TODO(voz): Consider making "explain" output alongside a run / part of a run +@patch("torch._dynamo.symbolic_convert.explain", True) +def explain(f: Callable[..., Any], *extra_args: Any, **extra_kwargs: Any) -> Any: + from .backends.debugging import ExplainOutput + + def inner(*args: Any, **kwargs: Any) -> ExplainOutput: + # TODO(voz): Do we want a decorator for this? + from . import reset # type: ignore[attr-defined] + + reset() + + graphs: list[torch.fx.GraphModule] = [] + break_reasons: list[Any] = [] + op_count: int = 0 + ops_per_graph: list[list[Target]] = [] + out_guards: list[_guards.Guard] = [] + + def dynamo_graph_accumulating_compiler( + gm: torch.fx.GraphModule, example_inputs: Any + ) -> Callable[..., Any]: + from .backends.debugging import _explain_graph_detail + + nonlocal graphs + nonlocal op_count + nonlocal ops_per_graph + nonlocal break_reasons + + gm, graphs, op_count, ops_per_graph, break_reasons = _explain_graph_detail( + gm, graphs, op_count, ops_per_graph, break_reasons + ) + + return gm.forward + + def guard_export_print(guards: Iterable[_guards.Guard]) -> None: + nonlocal out_guards + out_guards.extend(guards) + + opt_f = optimize( + dynamo_graph_accumulating_compiler, + nopython=False, + guard_export_fn=guard_export_print, + )(f) + # TODO(voz): We may have instances of `f` that mutate inputs, we should track sideeffects and reject. + opt_f(*args, **kwargs) + + graph_count = len(graphs) + graph_break_count = graph_count - 1 + compile_time = compile_times(repr="str") + + # TODO(voz): Do we want a decorator for this? + reset() + + return ExplainOutput( + graphs, + graph_count, + graph_break_count, + break_reasons, + op_count, + ops_per_graph, + out_guards, + compile_time, + ) + + if extra_args or extra_kwargs: + warnings.warn( + "explain(f, *args, **kwargs) is deprecated, use explain(f)(*args, **kwargs) instead. " + "If you don't migrate, we may break your explain call in the future if your user defined kwargs " + "conflict with future kwargs added to explain(f).", + FutureWarning, + stacklevel=2, + ) + return inner(*extra_args, **extra_kwargs) + else: + return inner + + +class FlattenInputOutputSignature(torch.fx.Transformer): + def __init__( + self, + m: torch.fx.GraphModule, + flat_args: list[Any], + matched_input_elements_positions: list[int], + flat_results: Sequence[Any], + matched_output_elements_positions: list[int], + example_fake_inputs: list[torch.Tensor], + flat_args_dynamic_dims: list[set[int]], + fake_mode: fake_tensor.FakeTensorMode | None = None, + ) -> None: + super().__init__(m) + + if len(flat_args_dynamic_dims) != len(flat_args): + raise AssertionError( + f"flat_args_dynamic_dims length ({len(flat_args_dynamic_dims)}) " + f"must match flat_args length ({len(flat_args)})" + ) + matched_input_elements_to_fake = { + val: example_fake_inputs[ix] + for ix, val in enumerate(matched_input_elements_positions) + } + + self.new_args = [] + for i in range(len(flat_args)): + arg = super().placeholder(f"arg{i}", (), {}) + if i in matched_input_elements_to_fake: + arg.node.meta["val"] = matched_input_elements_to_fake[i] + else: + # Fill node.meta["val"] with faketensor from the input, + # if it's not found in matched_input_elements_positions + if fake_mode is not None and isinstance(flat_args[i], torch.Tensor): + # TODO(zhxchen17) Also preserve all the user constraints here. + arg.node.meta["val"] = fake_mode.from_tensor( + flat_args[i], + symbolic_context=StatelessSymbolicContext( + dynamic_sizes=[ + ( + DimDynamic.DYNAMIC + if d in flat_args_dynamic_dims[i] + else DimDynamic.STATIC + ) + for d in range(len(flat_args[i].shape)) + ], + constraint_sizes=[None] * len(flat_args[i].shape), + ), + ) + elif isinstance(flat_args[i], _IntWrapper): + arg.node.meta["val"] = flat_args[i].val + else: + arg.node.meta["val"] = flat_args[i] + + self.new_args.append(arg) + self.old_args_gen = (self.new_args[i] for i in matched_input_elements_positions) + self.matched_output_elements_positions = matched_output_elements_positions + self.flat_results = flat_results + + def placeholder( + self, target: Target, args: tuple[Argument, ...], kwargs: dict[str, Any] + ) -> Any: + arg = next(self.old_args_gen) + if "val" in self.current_node.meta: + arg.node.meta["val"] = self.current_node.meta["val"] + if "tensor_dict" in self.current_node.meta: + arg.node.meta["tensor_dict"] = self.current_node.meta["tensor_dict"] + if "example_value" in self.current_node.meta: + # NB: intentionally do not use set_example_value + arg.node.meta["example_value"] = self.current_node.meta["example_value"] + if "unbacked_bindings" in self.current_node.meta: + arg.node.meta["unbacked_bindings"] = self.current_node.meta[ + "unbacked_bindings" + ] + return arg + + def output( + self, target: Target, args: tuple[Argument, ...], kwargs: dict[str, Any] + ) -> Any: + dynamo_result_flat = args[0] + lookup = [*dynamo_result_flat, *self.new_args] # type: ignore[misc] + # pyrefly: ignore [implicit-any] + new_results_flat = [] + for i in range(len(self.flat_results)): + if self.matched_output_elements_positions[i] is not None: + new_results_flat.append( + lookup[self.matched_output_elements_positions[i]] + ) + else: + const_val = self.flat_results[i] + if not isinstance(const_val, tuple(common_constant_types)): + raise AssertionError( + f"Expected const_val to be a common constant type, got {type(const_val)}" + ) + new_results_flat.append(const_val) + return super().output(target, (new_results_flat,), {}) + + def run_node(self, n: Node) -> Any: + self.current_node = n + result_proxy = super().run_node(n) + if "val" in self.current_node.meta: + result_proxy.node.meta["val"] = self.current_node.meta["val"] + if "example_value" in self.current_node.meta: + # NB: intentionally do not use set_example_value + result_proxy.node.meta["example_value"] = self.current_node.meta[ + "example_value" + ] + if "unbacked_bindings" in self.current_node.meta: + result_proxy.node.meta["unbacked_bindings"] = self.current_node.meta[ + "unbacked_bindings" + ] + if self.current_node.op != "output": + result_proxy.node._rename( + getattr(self.current_node, "name", result_proxy.node.name) + ) + return result_proxy + + def transform(self) -> torch.fx.GraphModule: + result_gm = super().transform() + if "dynamo_flat_name_to_original_fqn" in self.module.meta: # type: ignore[operator] + result_gm.meta["dynamo_flat_name_to_original_fqn"] = self.module.meta[ # type: ignore[index] + "dynamo_flat_name_to_original_fqn" # type: ignore[index] + ] + if "dynamo_compile_id" in self.module.meta: # type: ignore[operator] + result_gm.meta["dynamo_compile_id"] = self.module.meta["dynamo_compile_id"] # type: ignore[index] + return result_gm + + +class ExportResult(NamedTuple): + graph_module: torch.fx.GraphModule + guards: _guards.GuardsSet + # NB: Do not add new fields without overriding __iter__; people are + # destructuring so it is BC-breaking + + +# NOTE: this function only supports graphs created by Dynamo's OutputGraph module +def check_signature_rewritable(graph: torch.fx.GraphModule) -> None: + # pyrefly: ignore [implicit-any] + input_errors = [] + for node in graph.graph.find_nodes(op="placeholder"): + # set in OutputGraph._call_user_compiler + if not hasattr(node, "_dynamo_source"): + raise AssertionError("node is missing _dynamo_source attribute") + if not hasattr(graph, "_source_to_user_stacks"): + raise AssertionError("graph is missing _source_to_user_stacks attribute") + + # NOTE: We can safely ignore these type warnings if and only if + # the function is made from OutputGraph (checked in the assertions) + source = node._dynamo_source # type: ignore[attr-defined] + user_stacks = graph._source_to_user_stacks.get(source) # type: ignore[operator, union-attr] + if user_stacks is None: + continue + if len(user_stacks) == 0: + raise AssertionError("user_stacks must not be empty") + # In some cases we may not have a useful stack. Look for a + # useful stack + stack = None + for s in user_stacks: + if len(s) == 0: + continue + stack = s + break + if stack is None: + msg = f"{source.name}, a closed over free variable" + else: + tb = "".join(traceback.format_list(stack)) + extra = "" + if len(user_stacks) > 1: + extra = f"(elided {len(user_stacks) - 1} more accesses)" + msg = f"{source.name}, accessed at:\n{tb}{extra}" + # TODO: option to print ALL of the stack traces at once + input_errors.append(msg) + + if input_errors: + raise UserError( + UserErrorType.INVALID_INPUT, + "Cannot export model which references tensors that are neither " + "buffers/parameters/constants nor are direct inputs. For each tensor, if you'd " + "like this tensor to be an explicit input, add it as a dummy argument " + "to the top-level model definition you are exporting; if you would " + "like its value to be embedded as an exported constant, wrap its access " + "in a function marked with @assume_constant_result.\n\n" + + "\n\n".join(input_errors), + ) + + +def check_user_input_output(flat_values: list[Any], error_type: UserErrorType) -> None: + supported_types = [ + torch.Tensor, + torch.SymInt, + torch.SymFloat, + torch.SymBool, + torch._C.ScriptObject, + _IntWrapper, + ] + list(common_constant_types) + + def is_supported_type(val: Any) -> bool: + return isinstance(val, tuple(supported_types)) or is_custom_class(type(val)) + + value_type = "input" if error_type == UserErrorType.INVALID_INPUT else "output" + # We only check that the outputs are not None. Inputs can be None. + for v in flat_values: + if not is_supported_type(v): + if error_type == UserErrorType.INVALID_INPUT and v is None: + continue + + raise UserError( + error_type, + f"It looks like one of the {value_type}s with type `{type(v)}` " + "is not supported or pytree-flattenable. \n" + f"Exported graphs {value_type}s can only contain the " + f"following supported types: {supported_types}. \n" + "If you are using a custom class object, " + "please register a pytree_flatten/unflatten function " + "using `torch.utils._pytree.register_pytree_node` or " + "`torch.export.register_dataclass`.", + ) + + +def rewrite_signature( + f_sig: inspect.Signature, + graph: torch.fx.GraphModule, + fake_mode: fake_tensor.FakeTensorMode | None, + flat_args: list[Any], + in_spec: pytree.TreeSpec, + example_fake_inputs: list[Any], + graph_captured_input: Iterable[Any], + graph_captured_output: Iterable[Any] | None, + dynamo_traced_result: Any, + flat_args_dynamic_dims: list[set[int]], +) -> torch.fx.GraphModule: + orig_args, orig_kwargs = pytree.tree_unflatten(flat_args, in_spec) + + check_user_input_output(flat_args, UserErrorType.INVALID_INPUT) + flat_results_traced, out_spec_traced = pytree.tree_flatten(dynamo_traced_result) + check_user_input_output(flat_results_traced, UserErrorType.INVALID_OUTPUT) + + def check_optional_input_and_error(f_sig: inspect.Signature) -> None: + # Check if function has optional input. + for name, param in f_sig.parameters.items(): + if param.default is not inspect.Parameter.empty: + import torch._dynamo.graph_break_hints as graph_break_hints + from torch._dynamo.exc import unimplemented + + log.error( + "Parameter %s is optional with a default value of %s", + name, + param.default, + ) + unimplemented( + gb_type="rewrite_signature: cannot trace optional function input", + context="", + explanation=f"Parameter {name} is optional with a default value of {param.default}. This is not supported yet.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + def produce_matching( + debug_type: str, sources: Iterable[Any], candidates: Iterable[Any] + ) -> list[int | None]: + matched_elements_positions: list[int | None] = [] + dict_of_source_vals = {} + for i, val in enumerate(sources): + dict_of_source_vals[id(val)] = i + + for val in candidates: + if isinstance(val, tuple(common_constant_types)): + matched_elements_positions.append(None) + elif id(val) not in dict_of_source_vals: + if debug_type == "inputs": + check_optional_input_and_error(f_sig) + raise AssertionError( + f"Unexpectedly found a {type(val)} in the {debug_type}.\n" + 'Please file an issue along with a paste of the logs from TORCH_LOGS="+export"', + ) + else: + matched_elements_positions.append(dict_of_source_vals[id(val)]) + + return matched_elements_positions + + matched_input_elements_positions = produce_matching( + "inputs", flat_args, graph_captured_input + ) + + if graph_captured_output is None: + raise AssertionError("graph_captured_output must not be None") + matched_output_elements_positions = produce_matching( + "outputs", list(graph_captured_output) + flat_args, flat_results_traced + ) + + new_graph = FlattenInputOutputSignature( + graph, + flat_args, + matched_input_elements_positions, # type: ignore[arg-type] + flat_results_traced, + matched_output_elements_positions, # type: ignore[arg-type] + example_fake_inputs, + flat_args_dynamic_dims, + fake_mode, + ).transform() + + new_graph.graph._codegen = _PyTreeCodeGen( + _PyTreeInfo( + argument_names(f_sig, orig_args, orig_kwargs), + in_spec, + out_spec_traced, + ) + ) + new_graph.recompile() + return new_graph + + +def export( + f: Callable[..., Any], + *extra_args: Any, + aten_graph: bool = False, + pre_dispatch: bool = False, + decomposition_table: dict[torch._ops.OpOverload, Callable[..., Any]] | None = None, + tracing_mode: str = "symbolic", + dynamic_shapes: _DynamicShapesInput = None, + specialize_float: bool = True, + assume_static_by_default: bool = False, + same_signature: bool = True, + disable_constraint_solver: bool = False, + prefer_deferred_runtime_asserts_over_guards: bool = False, + _log_export_usage: bool = True, + constraints: list[Constraint] | None = None, + **extra_kwargs: Any, +) -> Callable[..., ExportResult]: + """ + Export an input function f to a format that can be executed outside of PyTorch using the FX graph. + + Args: + f (callable): A PyTorch function to be exported. + + aten_graph (bool): If True, exports a graph with ATen operators. + If False, exports a graph with Python operators. Default is False. + + pre_dispatch (bool): If True, exports a graph with ATen operators, + but before any logic in the PyTorch dispatcher has run. + This can be useful if you want to apply further transformations on a graph before running it + through autograd, autocast, or any other functionalities that are integrated into the dispatcher. + This flag is only valid if aten_graph=True is set. + Default is False. + + decomposition_table (dict): A dictionary that maps operators to their decomposition functions. + Required if aten_graph or tracing_mode is specified. Default is None. + + tracing_mode (str): If "symbolic", turn on dynamic shapes support. Default is "symbolic". + + dynamic_shapes: + An optional argument where the type should either be: + 1) a dict from argument names of ``f`` to their dynamic shape specifications, + 2) a tuple that specifies dynamic shape specifications for each input in original order. + If you are specifying dynamism on keyword args, you will need to pass them in the order that + is defined in the original function signature. + + The dynamic shape of a tensor argument can be specified as either + (1) a dict from dynamic dimension indices to :func:`Dim` types, where it is + not required to include static dimension indices in this dict, but when they are, + they should be mapped to None; or (2) a tuple / list of :func:`Dim` types or None, + where the :func:`Dim` types correspond to dynamic dimensions, and static dimensions + are denoted by None. Arguments that are dicts or tuples / lists of tensors are + recursively specified by using mappings or sequences of contained specifications. + + **ShapesSpec API.** ``dynamic_shapes`` may also be a + :class:`torch.fx.experimental.dynamic_spec.ShapesSpec` (or its + shorthand :class:`torch.fx.experimental.dynamic_spec.ParamsSpec`) -- + the same spec API exposed via ``dynamic_shapes=`` in + :func:`torch.compile`. See :func:`torch.export.export` for usage + and semantics, and :mod:`torch.fx.experimental.dynamic_spec` for + full details. + + same_signature (bool): If True, rewrite the returned graph's signature to be the same as f. + + disable_constraint_solver (bool): Whether the dim constraint solver must be disabled. + + Returns: + A function that given args and kwargs, returns a tuple of (graph, guards) + Graph: An FX graph representing the execution of the input PyTorch function with the provided arguments and options. + Guards: The guards we accumulated during tracing f above + + Raises: + AssertionError: If decomposition_table is specified without setting aten_graph=True, + or if graph breaks during tracing in export. + + AssertionError: If Dynamo input and output is not consistent with traced input/output. + + Note - this headerdoc was authored by ChatGPT, with slight modifications by the author. + """ + if config.debug_force_graph_break_on_leaf_return: + raise unittest.SkipTest("Cannot force graph break on export") + + # `dynamic_shapes` is overloaded: it accepts the Dim-based dict/tuple/list + # spec, OR the new ShapesSpec/ParamsSpec API. If the latter is passed, we + # route it through dynamo's `dynamic_shapes` mechanism and skip the legacy + # constraint processing. + from torch.fx.experimental.dynamic_spec import ( + _SHAPES_SPEC_VS_DEFERRED_RUNTIME_ASSERTS_MSG, + ) + + dyn_spec: ShapesSpec | ParamsSpec | None = None + if isinstance(dynamic_shapes, (ShapesSpec, ParamsSpec)): + if constraints: + raise ValueError( + "`dynamic_shapes=ShapesSpec(...)` cannot be combined with " + "`constraints`. ShapesSpec controls dynamic behavior on its own." + ) + if prefer_deferred_runtime_asserts_over_guards: + raise ValueError(_SHAPES_SPEC_VS_DEFERRED_RUNTIME_ASSERTS_MSG) + # ParamsSpec is normalized to ShapesSpec downstream in OptimizeContext. + dyn_spec = dynamic_shapes + dynamic_shapes = None + + if _log_export_usage: + log_export_usage(event="export.private_api", flags={"_dynamo"}) + + # Deal with "local variable referenced before assignment" + _f = f + _specialize_float = specialize_float + _assume_static_by_default = assume_static_by_default + _constraints = constraints + + def inner(*args: Any, **kwargs: Any) -> ExportResult: + if not _constraints: + combined_args = _combine_args(_f, args, kwargs) + constraints = _process_dynamic_shapes(combined_args, dynamic_shapes) + else: + constraints = _constraints + + f = _f + specialize_float = _specialize_float + assume_static_by_default = _assume_static_by_default + check_if_dynamo_supported() + torch._C._log_api_usage_once("torch._dynamo.export") + if decomposition_table is not None: + if not aten_graph: + raise AssertionError( + "Specifying a decomposition_table table or tracing mode is illegal without setting aten_graph=True" + ) + if pre_dispatch: + if not aten_graph: + raise AssertionError( + "pre_dispatch=True can only be used when aten_graph=True" + ) + f = innermost_fn(f) + call_to_inspect = f.forward if isinstance(f, torch.nn.Module) else f + original_signature = inspect.signature(call_to_inspect) # type: ignore[arg-type] + graph = None + out_guards = None + graph_captured_input = None + graph_captured_result: tuple[torch.Tensor, ...] | None = None + fake_mode = None + result_traced = None + + def guard_export_print(guards: _guards.GuardsSet) -> None: + nonlocal out_guards + if out_guards is not None: + raise AssertionError( + "whole graph export entails exactly one guard export" + ) + out_guards = guards + + example_inputs: list[Any] = [] + + def dynamo_normalization_capturing_compiler( + gm: torch.fx.GraphModule, inner_example_inputs: list[Any] + ) -> Callable[..., Any]: + nonlocal graph + if graph is not None: + raise AssertionError( + "Tried to emit a second graph during export. Tracing through 'f' must produce a single graph." + ) + graph = gm + + nonlocal fake_mode, example_inputs + # NB: do NOT pass inner_example_inputs here, we are detecting the + # Dynamo allocated fake mode, which should be DISTINCT from a + # potential outer ambient fake mode which the user provided. + # example_inputs is always the user specified inputs, so they + # would have the wrong fake mode attached to them + fake_mode = _guards.detect_fake_mode() + example_inputs = inner_example_inputs + + def result_capturing_wrapper(*graph_inputs: Any) -> Any: + nonlocal graph_captured_result + nonlocal graph_captured_input + + graph_captured_input = graph_inputs + if graph is None: + raise AssertionError( + "graph must not be None in result_capturing_wrapper" + ) + + named_parameters = dict(graph.named_parameters(remove_duplicate=False)) + named_buffers = dict(graph.named_buffers(remove_duplicate=False)) + + ambient_fake_mode = ( + _guards.detect_fake_mode(graph_inputs) + if _guards.detect_fake_mode(graph_inputs) is not None + else fake_mode + ) + + # We reran fake tensor propagation, but we didn't do + # anything with the resulting unbacked SymInts. Drop them + # from the pending list. + # NB: this is wrong if graph_captured_result has + # data-dependent output size! + ignore_fresh_unbacked = null_context() + if ambient_fake_mode is None: + raise AssertionError("ambient_fake_mode must not be None") + if shape_env := ambient_fake_mode.shape_env: + ignore_fresh_unbacked = shape_env.ignore_fresh_unbacked_symbols() # type: ignore[assignment] + + with ( + ambient_fake_mode, + enable_python_dispatcher(), + ignore_fresh_unbacked, + ): + params_and_buffers = { + **named_parameters, + **named_buffers, + } + fake_params_buffers = {} + + for name, value in params_and_buffers.items(): + fake_params_buffers[name] = ambient_fake_mode.from_tensor( + value, static_shapes=True + ) + + from torch._export.non_strict_utils import ( + key_path_to_source, + KeyPath, + ) + + def fakify_with_ambient( + path: KeyPath, t: torch.Tensor | _IntWrapper | Any + ) -> Any: + if isinstance(t, torch.Tensor): + # pyrefly: ignore [missing-attribute] + return ambient_fake_mode.from_tensor(t, static_shapes=True) + elif isinstance(t, _IntWrapper): + if ( + t.dynamism is not None + and isinstance(t.dynamism, _DimHint) + and t.dynamism.type + in ( + _DimHintType.DYNAMIC, + _DimHintType.AUTO, + ) + ): # type: ignore[union-attr] + source = key_path_to_source(path) + symint = ambient_fake_mode.shape_env.create_unspecified_symint_and_symbol( # type: ignore[union-attr] + t.val, source, DimDynamic.DYNAMIC + ) + return symint + else: + return t.val + else: + return t + + fake_graph_inputs = pytree.tree_map_with_path( + fakify_with_ambient, graph_inputs + ) + graph_captured_result = torch.func.functional_call( + graph, + fake_params_buffers, # type: ignore[arg-type] + fake_graph_inputs, # type: ignore[arg-type] + ) + + return graph_captured_result + + return result_capturing_wrapper + + # Note: This is needed by rewrite_signature. We need to put it before + # optimize_assert since user program may mutate the inputs. + flat_args, in_spec = pytree.tree_flatten((args, kwargs)) + + remove_from_cache(f) + constraint_violation_error = None + if tracing_mode != "symbolic": + assume_static_by_default = True + with ( + config.patch( + specialize_int=True, + specialize_float=specialize_float, + assume_static_by_default=assume_static_by_default, + automatic_dynamic_shapes=False, + capture_dynamic_output_shape_ops=True, + capture_scalar_outputs=True, + constant_fold_autograd_profiler_enabled=True, + prefer_deferred_runtime_asserts_over_guards=prefer_deferred_runtime_asserts_over_guards, + # install_free_tensors ensures that params and buffers are still + # added as graph attributes, and makes Dynamo emits graphs that + # follow export pytree-able input requirements + install_free_tensors=config.install_free_tensors_for_export, + ), + _compiling_state_context(), + ): + opt_f = optimize_assert( + dynamo_normalization_capturing_compiler, + hooks=Hooks( + guard_export_fn=guard_export_print, + guard_fail_fn=None, + ), + export=True, + export_constraints=constraints, + dynamic_shapes=dyn_spec, + )(f) + # TODO(voz): We may have instances of `f` that mutate inputs, we should track sideeffects and reject. + try: + result_traced = opt_f(*args, **kwargs) + except ConstraintViolationError as e: + constraint_violation_error = e + remove_from_cache(f) + + if ( + not disable_constraint_solver + and (shape_env := getattr(fake_mode, "shape_env", None)) is not None + and (dim_constraints := shape_env.dim_constraints) is not None + and not isinstance( + call_to_inspect, (torch._ops.OpOverloadPacket, torch._ops.OpOverload) + ) + and not trace_rules.check(call_to_inspect) + ): + dim_constraints.solve() + + forced_specializations = dim_constraints.forced_specializations() + + msg = dim_constraints.prettify_results( + original_signature, + dynamic_shapes, + constraint_violation_error, + forced_specializations, + ) + if constraint_violation_error: + constraint_violation_error.args = ( + constraint_violation_error.args[0] + msg, + ) + else: + if forced_specializations: + constraint_violation_error = ConstraintViolationError(msg) + else: + log.info( + "Summary of dimension constraints:%s", + msg, + ) + + # Error if we have any constraints on static values + + for k in shape_env.var_to_range: + if isinstance(k, sympy.Integer): + constraint_violation_error = ConstraintViolationError( + f"{''.join(traceback.format_list(shape_env.var_to_stack[k]))}\n" + "It appears that you're trying to set a constraint on a " + f"value which we evaluated to have a static value of {k}. " + 'Set TORCH_LOGS="+export" for more information.' + ) + if constraint_violation_error: + raise constraint_violation_error + + if graph is None: + if not same_signature: + raise AssertionError( + "Failed to produce a graph during tracing as no tensor operations were found and same_signature is False." + ) + # If the module does not contain any tensor computation, we would create a graph with inputs and outputs. + # To be consistent with the graph traced by dynamo, `graph` will have only tensor inputs as placeholders + # and tensor outputs as output nodes. non-tensor inputs and outputs will be added when rewriting signature. + # We will also construct the `example_inputs`, `graph_captured_input`, and `graph_captured_result` corresponding + # to `graph`. + example_inputs = [] + graph_captured_input = () + graph_captured_result = () + fake_mode = torch._subclasses.FakeTensorMode( + shape_env=ShapeEnv(), export=True + ) + if out_guards is None: + out_guards = _guards.GuardsSet() + if out_guards is None: # suppress mypy error + raise AssertionError("out_guards must not be None") + parameter_names = list(original_signature.parameters.keys()) + fx_graph = torch.fx.Graph() + for i, name in enumerate(parameter_names): + if torch.is_tensor(flat_args[i]): + node = fx_graph.placeholder(name) + node.meta["val"] = fake_mode.from_tensor( + flat_args[i], static_shapes=True + ) + graph_captured_input = graph_captured_input + (flat_args[i],) + example_inputs.append(flat_args[i]) + fx_graph.output(graph_captured_result) + module = torch.nn.Module() + graph = torch.fx.GraphModule(module, fx_graph) + log.info( + "Failed to capture a graph during tracing as no tensor operations were found.:\n\n%s", + graph.print_readable(print_output=False, colored=True), + ) + else: + if out_guards is None: + raise AssertionError("Failed to produce guards during tracing") + if fake_mode is None: + raise AssertionError("fake_mode must not be None after tracing") + + log.info( + "Dynamo captured graph:\n\n%s", + graph.print_readable(print_output=False, colored=True), + ) + + # This check need to happened before aten_graph + # because placeholder's _source_node attribute is not preserved by make_fx + if same_signature: + check_signature_rewritable(graph) + + # NB: This is mostly hitting the cache; Dynamo already converted these + example_fake_inputs = [ + fake_mode.from_tensor(t) if isinstance(t, torch.Tensor) else t + for t in example_inputs + ] + + if aten_graph: + # Running graph with interpreter is needed for propagating the stack_trace + def graph_with_interpreter(*args: Any) -> Any: + with torch.fx.traceback.preserve_node_meta(): + return torch.fx.Interpreter(graph).run(*args) # type: ignore[arg-type] + + with unset_fake_temporarily(), enable_python_dispatcher(), fake_mode: + try: + graph = make_fx( + graph_with_interpreter, + decomposition_table=decomposition_table, + tracing_mode="real", + _allow_non_fake_inputs=True, + pre_dispatch=pre_dispatch, + _allow_fake_constant=False, + )(*example_fake_inputs) + except CondOpArgsMismatchError as e: + # Wrap the internal error to the user-facing error + raise UserError( # noqa: B904 + UserErrorType.DYNAMIC_CONTROL_FLOW, + str(e), + case_name="cond_operands", + ) + + if graph is None: + raise AssertionError("graph must not be None after tracing") + for node in graph.graph.find_nodes(op="get_attr"): + if isinstance(getattr(graph, node.target), torch.Tensor): # type: ignore[arg-type] + node.meta["val"] = fake_mode.from_tensor( + getattr(graph, node.target), # type: ignore[arg-type] + static_shapes=True, + ) + + if same_signature: + flat_args_dynamic_dims = [ + { + c.dim + for c in (constraints or ()) + if ( + c.t_id == id(x) + and not isinstance(c, _RelaxedConstraint) + and c.constraint_range.vr.lower != c.constraint_range.vr.upper + ) + } + for x in flat_args + ] + graph = rewrite_signature( + original_signature, + graph, + fake_mode, + flat_args, + in_spec, + example_fake_inputs, + graph_captured_input, # type: ignore[arg-type] + graph_captured_result, + result_traced, # type: ignore[possibly-undefined] + flat_args_dynamic_dims, + ) + return ExportResult(graph, out_guards) + + if extra_args or extra_kwargs: + warnings.warn( + "export(f, *args, **kwargs) is deprecated, use export(f)(*args, **kwargs) instead. " + "If you don't migrate, we may break your export call in the future if your user defined kwargs " + "conflict with future kwargs added to export(f).", + FutureWarning, + stacklevel=2, + ) + return inner(*extra_args, **extra_kwargs) # type: ignore[return-value] + else: + return inner + + +def optimize_assert(*args: Any, **kwargs: Any) -> OptimizeContext: + if "rebuild_ctx" in kwargs and kwargs["rebuild_ctx"] is not None: + # called from optimize + rebuild_ctx = kwargs["rebuild_ctx"] + del kwargs["rebuild_ctx"] + else: + + def rebuild_ctx() -> OptimizeContext: + return optimize_assert(*args, **kwargs) + + return _optimize_assert(rebuild_ctx, *args, **kwargs) + + +def _optimize_assert( + rebuild_ctx: Callable[[], OptimizeContext], + backend: str | Callable[..., Any] | None, + *, + hooks: Hooks = Hooks(None, None, None), + export: bool = False, + export_constraints: Any | None = None, + dynamic: bool | None = None, + package: CompilePackage | None = None, + recompile_limit: int | None = None, + isolate_recompiles: bool = False, + dynamic_shapes: ShapesSpec | ParamsSpec | dict[str, Any] | None = None, +) -> OptimizeContext: + """ + Guarantees single-graph capture. + The same as `torch._dynamo.optimize(backend)` but ignores + symbolic_convert.error_on_graph_break setting. + + Used for fullgraph=True and export, since we must always error on graph breaks and ignore + symbolic_convert.error_on_graph_break. Can also be used for testing. + """ + backend = get_compiler_fn(backend) + + # Find if backend has any extra context manager + backend_ctx_ctor = getattr(backend, "backend_ctx_ctor", null_context) + + if config.caching_precompile and package is None: + # Create an uninitialized package that will be set/filled by + # _OptimizeContext.__call__ + # We need to instantiate the object here because the same CompilePackage + # needs to be shared between convert_frame_assert + # and OptimizeContext. + from .package import CompilePackage + + package = CompilePackage(fn=None, dynamo=None, ignore_inlined_sources=False) + + return _optimize_catch_errors( + convert_frame.convert_frame_assert( + backend, + export=export, + export_constraints=export_constraints, + package=package, + recompile_limit=recompile_limit, + ), + hooks, + backend_ctx_ctor, + fullgraph=True, + export=export, + dynamic=dynamic, + rebuild_ctx=rebuild_ctx, + package=package, + isolate_recompiles=isolate_recompiles, + dynamic_shapes=dynamic_shapes, + ) + + +class TorchPatcher: + @staticmethod + @functools.cache + def patch() -> None: + # A better way to disable the following would be decorate the source + # functions with @torch._disable_dynamo. However, this causes issues + # with torch.deploy internally. + from .decorators import disable + + torch.jit.trace = disable( + torch.jit.trace, reason="tracing into TorchScript not fully supported" + ) + torch.jit.trace_module = disable( + torch.jit.trace_module, + reason="tracing into TorchScript not fully supported", + ) + torch.jit._get_trace_graph = disable( + torch.jit._get_trace_graph, + reason="tracing into TorchScript not fully supported", + ) + torch.fx._symbolic_trace.Tracer.trace = disable( + torch.fx._symbolic_trace.Tracer.trace, + reason="tracing into FX not fully supported", + ) + torch.distributions.Distribution.set_default_validate_args(False) + + from torch.optim import ( + adadelta, + adagrad, + adam, + adamax, + adamw, + asgd, + lbfgs, + nadam, + radam, + rmsprop, + rprop, + sgd, + sparse_adam, + ) + + optimizer_modules = { + adadelta, + adagrad, + adam, + adamax, + adamw, + asgd, + lbfgs, + nadam, + radam, + rmsprop, + rprop, + sgd, + sparse_adam, + } + + for opt_mod in optimizer_modules: + opt_name = opt_mod.__name__.split(".")[-1] + fused_fn_name = f"_fused_{opt_name}" + + if hasattr(opt_mod, fused_fn_name): + setattr( + opt_mod, + fused_fn_name, + disable( + getattr(opt_mod, fused_fn_name), + reason="don't trace into fused optimizer", + ), + ) + + optimizer_classes = [ + opt + for opt in torch.optim.__dict__.values() + if inspect.isclass(opt) and issubclass(opt, torch.optim.Optimizer) + ] + + # Note: we don't support sparsity or tracing through backwards + excluded_optimizer_classes = { + torch.optim.SparseAdam, + torch.optim.LBFGS, + } + + for opt in optimizer_classes: + if opt in excluded_optimizer_classes: + opt.step = disable( + opt.step, reason=f"optimizer {opt} step not supported" + ) + + if hasattr(opt, "_init_group"): + opt._init_group = disable( + opt._init_group, reason=f"optimizer {opt} _init_group not supported" + ) + + @staticmethod + def suppress_torch_distributed_warnings( + fn: Callable[..., Any], + ) -> Callable[..., Any]: + def inner_fn(*args: Any, **kwargs: Any) -> Any: + with torch._logging.hide_warnings( + torch._logging._internal.user_warning_filter + ): + return fn(*args, **kwargs) + + return inner_fn + + +def skip_code(code: types.CodeType) -> None: + set_code_exec_strategy( + code, FrameExecStrategy(FrameAction.SKIP, FrameAction.DEFAULT) + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/exc.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/exc.py new file mode 100644 index 0000000000000000000000000000000000000000..0f7cbec1ca41eb96da0baac1489750227cc82675 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/exc.py @@ -0,0 +1,1050 @@ +from __future__ import annotations + + +"""Exception handling and error reporting for TorchDynamo. + +This module provides a comprehensive set of exception classes and utilities for error +handling in TorchDynamo. It includes: + +Base Exceptions: + - TorchDynamoException: Base class for all TorchDynamo-specific exceptions + - Various specialized subclasses for different error scenarios + +User Error Handling: + - UserError: Exceptions for user-facing errors in TorchDynamo usage + - UserErrorType: Enumeration of different categories of user errors + - Formatted error messages with debugging information + +Observed Exceptions: + - Classes for handling exceptions observed during tracing + - Special handling for StopIteration, LookupError, etc. + - Exception state management during compilation + + When an exception is raised inside a ``torch.compile`` region, + TorchDynamo does **not** immediately propagate it to the caller. + Instead, Dynamo symbolically traces the exception so that + ``try``/``except`` blocks inside the compiled function can be + captured in the FX graph and reasoned about statically. + + Common Python exception types are wrapped in ``ObservedException`` + subclasses (e.g. ``StopIteration`` → ``ObservedUserStopIteration``, + ``KeyError`` → ``ObservedKeyError``). The full mapping is defined in + ``observed_exception_map``. For exception types not present in that + map, :func:`get_dynamo_observed_exception` creates a new + ``ObservedException`` subclass dynamically at tracing time. + + If an observed exception is **not caught** inside the compiled region + it propagates out and is re-raised as the original exception type in + eager mode, preserving the original traceback for the user. + + .. note:: + This behaviour means that exception-based control flow (e.g. + ``StopIteration`` from a custom iterator, ``KeyError`` from a + dict access) is generally supported inside ``torch.compile`` + regions. However, raising or catching exceptions that depend on + *data-dependent* conditions may still cause a graph break because + Dynamo cannot statically determine which branch will be taken at + compile time. + +Error Formatting: + - Stack trace filtering and formatting + - Error message augmentation + - Debugging utilities for error reporting +""" + +import json +import logging +import re +import sys +import textwrap +import types +import typing +from enum import auto, Enum +from functools import lru_cache +from pathlib import Path +from traceback import format_exc, format_list, FrameSummary, StackSummary +from typing import Any, NoReturn, TYPE_CHECKING + +import torch._guards +from torch._utils_internal import get_file_path_2 + +from . import config +from .utils import counters + + +if TYPE_CHECKING: + from torch._dynamo.variables import VariableTracker + from torch._guards import CompileId + + from .output_graph import DynamoTracerOutput + from .symbolic_convert import InstructionTranslatorBase + from .types import DynamoFrameType, FrameExecStrategy + + +def exportdb_error_message(case_name: str) -> str: + return ( + "For more information about this error, see: " + + "https://pytorch.org/docs/main/generated/exportdb/index.html#" + + case_name.replace("_", "-") + ) + + +log = logging.getLogger(__name__) +graph_breaks_log = torch._logging.getArtifactLogger(__name__, "graph_breaks") + + +_EXCEPTION_STATE_ATTRS_TO_DROP = frozenset( + ( + "_torch_dynamo_tracer_output", + "first_useful_frame", + "frame_exec_strategy", + ) +) + + +def _safe_exception_args(args: tuple[Any, ...]) -> tuple[Any, ...]: + return args + + +class _SerializedException(RuntimeError): + _dynamo_original_exception_type: str + + def __init__(self, exc: BaseException) -> None: + super().__init__(str(exc)) + self._dynamo_original_exception_type = ( + f"{type(exc).__module__}.{type(exc).__qualname__}" + ) + + +def _safe_inner_exception(exc: BaseException) -> _SerializedException: + return _SerializedException(exc) + + +def _safe_exception_state(state: dict[str, Any]) -> dict[str, Any]: + result: dict[str, Any] = {} + for name, value in state.items(): + if name in _EXCEPTION_STATE_ATTRS_TO_DROP or isinstance(value, types.FrameType): + result[name] = None + elif name == "inner_exception" and isinstance(value, BaseException): + result[name] = _safe_inner_exception(value) + else: + result[name] = value + return result + + +def _reconstruct_torch_dynamo_exception( + exc_type: type[TorchDynamoException], args: tuple[Any, ...] +) -> TorchDynamoException: + exc = exc_type.__new__(exc_type) + BaseException.__init__(exc, *args) + return exc + + +class TorchDynamoException(RuntimeError): + """Base exception class for all TorchDynamo-specific exceptions. + + Attributes: + _torch_dynamo_tracer_output: Optional tracer output attached to the exception + frame_exec_strategy: Optional frame execution strategy to control how convert_frame + should handle this exception. When set, convert_frame will use this strategy + instead of the default behavior. This allows exceptions to signal specific + execution strategies (e.g., SKIP, RUN_ONLY) without requiring separate + exception types for control flow. + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self._torch_dynamo_tracer_output: DynamoTracerOutput | None = None + self.frame_exec_strategy: FrameExecStrategy | None = None + + def __reduce__(self) -> tuple[Any, ...]: + return ( + _reconstruct_torch_dynamo_exception, + (type(self), _safe_exception_args(self.args)), + self.__getstate__(), + ) + + def __getstate__(self) -> dict[str, Any]: + return _safe_exception_state(self.__dict__) + + def __setstate__(self, state: dict[str, Any] | None, /) -> None: + if state is not None: + self.__dict__.update(state) + + +class InternalTorchDynamoError(TorchDynamoException): + pass + + +class ResumePrologueTracingError(TorchDynamoException): + pass + + +class RestartAnalysis(TorchDynamoException): + restart_reason: str | None + + def __init__(self, *args: Any, restart_reason: str | None = None) -> None: + self.restart_reason = restart_reason + super().__init__(*args) + + +class SpeculationRestartAnalysis(RestartAnalysis): + pass + + +class AutogradGradRestartAnalysis(RestartAnalysis): + """Raised when autograd.grad consumed grad_fns that are returned. + + On restart, autograd.grad will graph break instead of being traced. + """ + + +class RequiresGradRestartAnalysis(RestartAnalysis): + """Raised when a source-less requires_grad_() intermediate leaks as output. + + On restart, requires_grad_() will graph break instead of being traced, + preserving partial acceleration for code before the call. + """ + + +class UnspecializeRestartAnalysis(RestartAnalysis): + pass + + +class CompileCollectiveRestartAnalysis(RestartAnalysis): + pass + + +class TensorifyScalarRestartAnalysis(RestartAnalysis): + pass + + +# Used (primarily for backends) to skip tracing the current frame +# and all future invocations of it. +# NOTE: this does NOT cause a graph break, and thus no graph break messages +# will be issued! +class SkipFrame(TorchDynamoException): + pass + + +class TorchRuntimeError(TorchDynamoException): + def __init__(self, msg: str, real_stack: StackSummary | None = None) -> None: + super().__init__(msg) + self.msg = msg + self.real_stack = ( + real_stack + if real_stack is not None + else torch._guards.TracingContext.extract_stack() + ) + + +class InvalidBackend(TorchDynamoException): + def __init__(self, name: str, suggestions: list[str] | None = None) -> None: + msg = f"Invalid backend: {name!r}" + msg += ( + f", did you mean: {', '.join(map(repr, suggestions))}?" + if suggestions + else "." + ) + msg += " See `torch._dynamo.list_backends()` for available backends." + super().__init__(msg) + + +class ResetRequired(TorchDynamoException): + def __init__(self) -> None: + super().__init__( + textwrap.dedent( + """ + Must call `torch._dynamo.reset()` before changing backends. Detected two calls to + `torch.compile()` with a different backend compiler arguments. + """ + ) + ) + + +class ShortenTraceback(TorchDynamoException): + def __init__( + self, *args: Any, first_useful_frame: types.FrameType | None, **kwargs: Any + ) -> None: + super().__init__(*args, **kwargs) + self.first_useful_frame = first_useful_frame + + def remove_dynamo_frames(self) -> typing.Self: + tb = self.__traceback__ + if self.first_useful_frame is None or tb is None or config.verbose: + return self + while tb.tb_frame is not self.first_useful_frame: + tb = tb.tb_next + if tb is None: + raise AssertionError("internal error, please report a bug") + return self.with_traceback(tb) + + +class BackendCompilerFailed(ShortenTraceback): + def __init__( + self, + backend_fn: Any, + inner_exception: Exception, + first_useful_frame: types.FrameType | None, + ) -> None: + self.backend_name = getattr(backend_fn, "__name__", "?") + self.inner_exception = inner_exception + msg = f"backend={self.backend_name!r} raised:\n{type(inner_exception).__name__}: {inner_exception}" + super().__init__(msg, first_useful_frame=first_useful_frame) + + +# NOTE: important invariant! Almost any exception handler that handles Unsupported +# should NOT suppress the exception if skip_frame is set! +# skip_frame is used by symbolic_convert.py to bubble up Unsupported exceptions to convert_frame to cause +# a frame skip. Once the Unsupported exn is in convert_frame, we will always skip, so skip_frame +# won't be checked +class Unsupported(TorchDynamoException): + def __init__( + self, + msg: str, + # TODO: make this argument required once we remove Unsupported subclasses + gb_type: str = "", + skip_frame: bool = False, + *, + case_name: str | None = None, + real_stack: StackSummary | None = None, + ) -> None: + super().__init__(msg) + if not real_stack: + real_stack = torch._guards.TracingContext.extract_stack() + self.real_stack = real_stack + self.msg = msg + self.skip_frame = skip_frame + self.category: str | None = None + self.add_to_stats() + self.gb_type: str | None = gb_type + self.logged = False + + def remove_from_stats(self) -> None: + if self.category is None: + raise AssertionError("category must be set before removing from stats") + counters[self.category][self.msg] -= 1 + if counters[self.category][self.msg] <= 0: + del counters[self.category][self.msg] + + def add_to_stats(self, category: str = "unimplemented") -> None: + self.category = category + counters[category][self.msg] += 1 + + +class UnknownPropertiesDuringBackwardTrace(TorchDynamoException): + pass + + +class RecompileError(TorchDynamoException): + pass + + +class InfiniteGeneratorError(TorchDynamoException): + # Raised when the number of yielded values is greater than MAX_ITERATOR_LIMIT + pass + + +class CondOpArgsMismatchError(TorchDynamoException): + """ + Internal error from cond() due to arguments mismatch. + """ + + +class UserErrorType(Enum): + DYNAMIC_CONTROL_FLOW = auto() + ANTI_PATTERN = auto() + STANDARD_LIBRARY = auto() + CONSTRAINT_VIOLATION = auto() + DYNAMIC_DIM = auto() + INVALID_INPUT = auto() + INVALID_OUTPUT = auto() + UNSUPPORTED_ALIASED_MUTATED_DYNAMIC_INPUTS = auto() + + +class UserError(TorchDynamoException): + def __init__( + self, error_type: UserErrorType, msg: str, case_name: str | None = None + ) -> None: + """ + Type of errors that would be valid in Eager, but not supported in TorchDynamo. + The error message should tell user about next actions. + + error_type: Type of user error + msg: Actionable error message + case_name: (Optional) Unique name (snake case) for the usage example in exportdb. + """ + if case_name is not None: + if not isinstance(case_name, str): + raise AssertionError(f"case_name must be a str, got {type(case_name)}") + if msg.endswith("."): + msg += " " + else: + msg += "\n" + msg += exportdb_error_message(case_name) + super().__init__(msg) + self.real_stack = torch._guards.TracingContext.extract_stack() + self.skip_frame = False + self.logged = False + self.error_type = error_type + self.msg = msg + self.message = msg + + +# debug exception thrown when tracing torch._dynamo.step_unsupported() +class StepUnsupported(TorchDynamoException): + def __init__(self, msg: str, real_stack: StackSummary | None = None) -> None: + super().__init__(msg) + self.msg = msg + if not real_stack: + real_stack = torch._guards.TracingContext.extract_stack() + self.real_stack = real_stack + self.logged = False + + +class UnsafeScriptObjectError(TorchDynamoException): + pass + + +class UncapturedHigherOrderOpError(TorchDynamoException): + def __init__(self, msg: str, real_stack: StackSummary | None = None) -> None: + super().__init__(msg) + self.msg = msg + self.real_stack = ( + real_stack + if real_stack is not None + else torch._guards.TracingContext.extract_stack() + ) + + +# TODO: I'm a little uncertain about what error classification we should have +# for this. This is potentially a user error, but regressions in +# specialization in PyTorch proper could also trigger this problem +class FailOnRecompileLimitHit(Exception): + pass + + +class PackageError(TorchDynamoException): + pass + + +class ObservedException(TorchDynamoException): + # An exception observed during the tracing. This exception is used by Dynamo to handle exceptions. + def __init__( + self, *args: Any, real_stack: StackSummary | None = None, **kwargs: Any + ) -> None: + super().__init__(*args, **kwargs) + self.real_stack: StackSummary = ( + real_stack + if real_stack is not None + else torch._guards.TracingContext.extract_stack() + ) + + +class ObservedUserStopIteration(ObservedException): + # An UserStopIteration exception observed during the Dynamo tracing (e.g Dynamo tracing __next__) + value: Any | None + + # Reference `StopIteration_init` in CPython + # https://github.com/python/cpython/blob/3.11/Objects/exceptions.c#L568-L584 + def __init__( + self, *args: Any, real_stack: StackSummary | None = None, **kwargs: Any + ) -> None: + super().__init__("unhandled `raise StopIteration`", real_stack=real_stack) + if len(args) > 0: + self.value = args[0] + else: + self.value = None + + +class ObservedLookupError(ObservedException): + # A LookupError exception to be raised from inside Dynamo tracing. This can happen on __getitem__ + pass + + +class ObservedIndexError(ObservedLookupError): + # An IndexError exception to be raised from inside Dynamo tracing. This can happen on list __getitem__ + pass + + +class ObservedKeyError(ObservedLookupError): + # A KeyError exception to be raised from inside Dynamo tracing. This can happen on dict __getitem__ + pass + + +class ObservedGeneratorExit(ObservedException): + pass + + +class ObservedAttributeError(ObservedException): + # An AttributeError exception to be raised from inside Dynamo tracing. This can happen on user defined object __getattr__ + pass + + +class ObservedRuntimeError(ObservedException): + # A RuntimeError exception to be raised from inside Dynamo tracing. This can happen on generator.throw(..) method + pass + + +class ObservedNotImplementedError(ObservedException): + pass + + +class ObservedTypeError(ObservedException): + # A TypeError exception to be raised from inside Dynamo tracing. This can happen on generator.send(..) method + pass + + +class FakeTensorObservedException(ObservedException): + pass + + +observed_exception_map = { + StopIteration: ObservedUserStopIteration, + LookupError: ObservedLookupError, + IndexError: ObservedIndexError, + GeneratorExit: ObservedGeneratorExit, + KeyError: ObservedKeyError, + AttributeError: ObservedAttributeError, + RuntimeError: ObservedRuntimeError, + NotImplementedError: ObservedNotImplementedError, + TypeError: ObservedTypeError, +} + + +class UnhandledDescriptorError(NotImplementedError): + """Raised by object_generic_getattr when a descriptor type is not + recognized by _resolve_descriptor_get. Subclasses NotImplementedError + so callers that catch NotImplementedError (e.g., generic_getattr's + graph-break fallback) still work, but callers that want to + distinguish unhandled descriptors from other NotImplementedErrors can + catch this specifically. + """ + + +class TritonUnavailableError(RuntimeError): + """ + Raised by DeviceInterface.raise_if_triton_unavailable to signal that a + device cannot run Triton (e.g. no Triton backend was built for it). + + Subclasses RuntimeError so existing callers that catch RuntimeError keep + working, while callers that only want to react to Triton unavailability - + such as has_triton() - can catch this specific type instead of swallowing + every RuntimeError, which would hide unrelated bugs. + """ + + +def get_dynamo_observed_exception(exc_type: type[Exception]) -> type[ObservedException]: + if exc_type not in observed_exception_map: + name = getattr(exc_type, "__name__", str(exc_type)) + observed_exception_map[exc_type] = type( # type: ignore[assignment] + f"Observed{name}Error", (ObservedException,), {} + ) + # pyrefly: ignore [bad-index] + return observed_exception_map[exc_type] + + +def raise_observed_exception( + exc_type: type[Exception], + tx: InstructionTranslatorBase, + *, + args: list[VariableTracker] | list[str] | None = None, + kwargs: dict[str, VariableTracker] | None = None, +) -> NoReturn: + from .variables.builder import SourcelessBuilder + + if args: + args_ = [ + SourcelessBuilder.create(tx, arg) if isinstance(arg, str) else arg + for arg in args + ] + else: + args_: list[VariableTracker] = [] + + # CPython here raises an exception. Since there is no python code, we have to manually setup the exception + # stack and raise the exception. + exception_vt = SourcelessBuilder.create(tx, exc_type).call_function( + tx, args_, kwargs or {} + ) + tx.do_raise(exception_vt, None) + + +def raise_type_error(tx: InstructionTranslatorBase, msg: str) -> NoReturn: + """Raise a TypeError as an observed exception during tracing.""" + raise_observed_exception(TypeError, tx, args=[msg]) + + +def raise_value_error(tx: InstructionTranslatorBase, msg: str) -> NoReturn: + """Raise a ValueError as an observed exception during tracing.""" + raise_observed_exception(ValueError, tx, args=[msg]) + + +def handle_observed_exception(tx: Any) -> None: + # This is essentially exception handling code, equivalent of this pseudo code + # + # try: + # ... somebody raising StopIteration + # except StopIteration + # pass + # + # If this was going through the python code, we would have called exception_handler method, but FOR_ITER + # handles the exception completely in CPython. For example for 3.11, the resulting bytecode is + # + # + # 6 46 LOAD_GLOBAL 2 (StopIteration) + # 58 RAISE_VARARGS 1 + # >> 60 PUSH_EXC_INFO + + # 7 62 LOAD_GLOBAL 2 (StopIteration) + # 74 CHECK_EXC_MATCH + # 76 POP_JUMP_FORWARD_IF_FALSE 3 (to 84) + # 78 POP_TOP + + # 8 80 POP_EXCEPT + # + + # Fortunately this translates to a simple pop from the exn_vt_stack + tx.exn_vt_stack.clear_current_exception() + + +# These exceptions are ok to fallback to eager/graph_break. +exceptions_allowed_to_be_fallback = ( + torch._subclasses.fake_tensor.DataDependentOutputException, + torch._subclasses.fake_tensor.DynamicOutputShapeException, + torch._subclasses.fake_tensor.UnsupportedOperatorException, + torch._subclasses.fake_tensor.UnsupportedFakeTensorException, + torch._subclasses.fake_tensor.UnsupportedMutationAliasingException, +) + + +def unimplemented_with_warning( + e: Exception, + code: types.CodeType, + *, + gb_type: str, + context: str, + explanation: str, + hints: list[str], +) -> NoReturn: + # This function calls unimplemented internally and eventually graph breaks + # or falls to eager. unimplemented itself does not print any user warnings, + # i.e., its very silent. This helper function is intended when an error is + # encountered in the torch.compile stack which is worth showing as warning + # to the user. For example, if AOT Autograd backend fails with a fake tensor + # exception, its ok to fallback to eager but not silently. Here, we can use + # this function to log the message and the stack trace. + graph_break_msg = format_error_msg_verbose(e, code) + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "dynamo_graph_break_reason", + "encoding": "string", + }, + payload_fn=lambda: graph_break_msg, + ) + graph_breaks_log.debug("%s", graph_break_msg) + _unimplemented = unimplemented + # to prevent a graph break registry entry + _unimplemented( + gb_type=gb_type, + context=context, + explanation=explanation, + hints=hints, + from_exc=e, + log_warning=True, + ) + + +def format_graph_break_message( + gb_type: str, + context: str, + explanation: str, + hints: list[str], +) -> str: + explanation = textwrap.indent(explanation, " ").lstrip() + hints_str = "\n".join( + " Hint: " + textwrap.indent(hint, " ").lstrip() for hint in hints + ) + context = textwrap.indent(context, " ").lstrip() + + msg = f"""\ +{gb_type} + Explanation: {explanation} +{hints_str} + + Developer debug context: {context}""" + documentation_link = get_gbid_documentation_link(gb_type) + + if documentation_link: + msg += f"\n\n For more details about this graph break, please visit: {documentation_link}" + + return msg + + +@lru_cache(maxsize=1) +def _load_gb_type_to_gb_id_map() -> dict[str, Any]: + """ + Loads the gb_type to gb_id map from the graph break registry from JSON file with caching. + + Includes historical gb_type (mapping behavior of duplicate gb_types with different gb_ids is undefined). + """ + try: + script_dir = Path(__file__).resolve().parent + registry_path = get_file_path_2( + "", str(script_dir), "graph_break_registry.json" + ) + with open(registry_path) as f: + registry = json.load(f) + except Exception: + log.exception("Error accessing the registry file") + # pyrefly: ignore [implicit-any] + registry = {} + + mapping = {} + for k, v in registry.items(): + for entry in v: + mapping[entry["Gb_type"]] = k + + return mapping + + +def get_gbid_documentation_link(gb_type: str) -> str | None: + """ + Retrieves the GBID documentation link for a given graph break type. + + Args: + gb_type: The graph break type to look up. + + Returns: + A string containing the documentation URL if found, otherwise None. + """ + GRAPH_BREAK_SITE_URL = ( + "https://meta-pytorch.github.io/compile-graph-break-site/gb/" # @lint-ignore + ) + + gb_type_to_gb_id_map = _load_gb_type_to_gb_id_map() + + if gb_type in gb_type_to_gb_id_map: + return ( + f"{GRAPH_BREAK_SITE_URL}gb{gb_type_to_gb_id_map[gb_type].lstrip('GB')}.html" + ) + + return None + + +_NOTHING = object() + + +def unimplemented( + *, + gb_type: str, + context: str, + explanation: str, + hints: list[str], + from_exc: Any = _NOTHING, + log_warning: bool = False, + skip_frame: bool = False, +) -> NoReturn: + """ + Called within dynamo to cause a graph break. + Args: + gb_type: Context-free graph break type. It should be a short string without any + information specific to the tracing context (i.e. no dynamically-generated strings) + context: Developer context for the graph break. It can contain tracing context/dynamic strings. + explanation: User-facing context-dependent explanation for the graph break. Can be dynamic. + hints: List of user-facing hints for the graph break. + """ + + msg = format_graph_break_message(gb_type, context, explanation, hints) + + if log_warning: + log.warning(msg) + if from_exc is not _NOTHING: + past_real_stack = None + if hasattr(from_exc, "real_stack"): + past_real_stack = from_exc.real_stack + if isinstance(from_exc, Unsupported): + msg = f"{from_exc.msg}\n\n*** While handling this graph break, another graph break occurred: ***\n\n{msg}" + # noqa: GB_REGISTRY + raise Unsupported(msg, gb_type, skip_frame, real_stack=past_real_stack) + # noqa: GB_REGISTRY + raise Unsupported( + msg, gb_type, skip_frame, real_stack=past_real_stack + ) from from_exc + # noqa: GB_REGISTRY + raise Unsupported(msg, gb_type, skip_frame) + + +# KeyError has special handling for its args +# see https://github.com/python/cpython/blob/3.11/Objects/exceptions.c#L2534 for details +class KeyErrorMsg: + def __init__(self, value: Any) -> None: + self.value = value + + def __str__(self) -> str: + return str(self.value) + + def __repr__(self) -> str: + return self.__str__() + + +def augment_exc_message_with_hop_name(exc: Exception, msg: str) -> str: + # Add HOP context right after before the explanation if present; + # otherwise after the message + if hasattr(exc, "_hop_name"): + lines = msg.partition("\n Explanation:") + msg = ( + f"{lines[0]}\n Higher Order Operator: {exc._hop_name}{lines[1]}{lines[2]}" # type: ignore[attr-defined] + ) + + return msg + + +def augment_exc_message(exc: Exception, msg: str = "\n", export: bool = False) -> None: + import traceback + + exc.innermost_user_frame_summary = None # type: ignore[attr-defined] + + real_stack = get_real_stack(exc) + if real_stack is not None and len(real_stack) > 0: + exc.innermost_user_frame_summary = real_stack[-1] # type: ignore[attr-defined] + msg += f"\nfrom user code:\n {''.join(traceback.format_list(real_stack))}" + + if config.replay_record_enabled and hasattr(exc, "record_filename"): + msg += ( + f"\nLast frame execution written to {exc.record_filename}. To run only this frame while debugging, run\ + torch._dynamo.replay('{exc.record_filename}').\n" + ) + + if not config.verbose and hasattr(exc, "real_stack"): + msg += ( + "\nSet TORCHDYNAMO_VERBOSE=1 for the internal stack trace " + "(please do this especially if you're reporting a bug to PyTorch). " + 'For even more developer context, set TORCH_LOGS="+dynamo"\n' + ) + + if hasattr(exc, "inner_exception") and hasattr( + exc.inner_exception, "minifier_path" + ): + if hasattr(exc.inner_exception, "buck_command"): + msg += ( + f"\nMinifier script written to {exc.inner_exception.minifier_path}. Run " + f"this buck command to find the smallest traced graph " + f"which reproduces this error: {exc.inner_exception.buck_command}\n" + ) + else: + msg += ( + f"\nMinifier script written to {exc.inner_exception.minifier_path}. Run " + "this script to find the smallest traced graph which reproduces this error.\n" + ) + + old_msg = "" if len(exc.args) == 0 else str(exc.args[0]) + + old_msg = augment_exc_message_with_hop_name(exc, old_msg) + + if isinstance(exc, KeyError): + exc.args = (KeyErrorMsg(old_msg + msg),) + exc.args[1:] + else: + new_msg = old_msg + msg + exc.args = (new_msg,) + exc.args[1:] + + +def get_exc_message( + e: Exception, compile_id: CompileId +) -> tuple[str | None, int | None]: + filename = None + lineno = None + if e.innermost_user_frame_summary is not None: # type: ignore[attr-defined] + filename = e.innermost_user_frame_summary.filename # type: ignore[attr-defined] + lineno = e.innermost_user_frame_summary.lineno # type: ignore[attr-defined] + e.compile_id = compile_id # type: ignore[attr-defined] + return filename, lineno + + +def _extract_stack_with_positions() -> StackSummary: + # traceback.extract_stack() does not populate colno/end_colno on + # FrameSummary, even though the data is available on live frames via + # f_lasti + co_positions(). This means traceback.format_list() never + # renders caret annotations for stacks captured this way. We do it + # manually here so that "stack above dynamo" frames get carets. + stack = StackSummary() + frame = sys._getframe(1) + while frame is not None: + code = frame.f_code + # colno/end_colno kwargs were added to FrameSummary in 3.11 + kwargs: dict[str, Any] = {} + if sys.version_info >= (3, 11) and frame.f_lasti >= 0: + positions = list(code.co_positions()) + idx = frame.f_lasti // 2 + if idx < len(positions): + _, _, kwargs["colno"], kwargs["end_colno"] = positions[idx] + stack.append( + FrameSummary( + code.co_filename, + frame.f_lineno, + code.co_name, + lookup_line=False, + **kwargs, + ) + ) + frame = frame.f_back + stack.reverse() + return stack + + +def get_stack_above_dynamo() -> StackSummary: + return filter_stack(_extract_stack_with_positions()) + + +def get_real_stack( + exc: Exception, frame: DynamoFrameType | None = None +) -> StackSummary | None: + real_stack = getattr(exc, "real_stack", None) + if real_stack is None: + return None + + # NB: it's possible for real_stack to be []; we still attempt to + # report a stack anyway because the stack_above_dynamo may still + # be useful for debugging + + if frame is not None: + # NB: frame is PyInterpreterFrame on Python 3.11 and later, + # not a TRUE frame object. You can't actually feed it + # to traceback because it doesn't have enough information. + # To solve this problem, we technically should just materialize + # the frame, the same way _PyFrame_GetFrameObject would do + # (but we cannot actually do this, because this populates + # frame_obj field, which default eval frame doesn't like). + # + # Fortunately, in this case, we can hack it: there's no need + # to actually use the truly top frame, we can just extract + # from where we are right now and rely on filter_stack to + # get rid of all the dynamo frames. For ease of testing + # we apply this behavior to ALL Python versions + stack_above_dynamo = get_stack_above_dynamo() + else: + stack_above_dynamo = StackSummary() + + return StackSummary.from_list(stack_above_dynamo + real_stack) + + +# filter out all frames after entering dynamo +def filter_stack(stack: StackSummary) -> StackSummary: + user_stack = StackSummary() + for frame in stack: + if frame.filename is None: + continue + if "convert_frame" in frame.filename: + break + if "eval_frame" in frame.filename or ( + frame.line and "torch._dynamo.optimize(" in frame.line + ): + continue + user_stack.append(frame) + + return user_stack + + +def remove_resume_prefix(name: str) -> str: + from .resume_execution import TORCH_DYNAMO_RESUME_IN_PREFIX + + match = re.match(f"{TORCH_DYNAMO_RESUME_IN_PREFIX}_(\\w+)_at_\\d+", name) + if match: + return match.group(1) + return name + + +def collapse_resume_frames(stack: StackSummary | list[FrameSummary]) -> StackSummary: + """ + When we graph break, we create a resume function and make a regular Python call + to it, which gets intercepted by Dynamo. This behavior is normally shown in the + traceback, which can be confusing to a user. So we can filter out resume frames + for better traceback clarity. + + Example: + File "..." line 3, in f + + File "..." line 5, in torch_dynamo_resume_in_f_at_80 + + File "..." line 10, in torch_dynamo_resume_in_f_at_120 + + + becomes + File "..." line 10, in f + + """ + + new_stack = StackSummary() + for frame in stack: + if frame.filename is None: + continue + name = remove_resume_prefix(frame.name) + if new_stack and name and new_stack[-1].name == name: + new_stack[-1] = frame + frame.name = name + else: + frame.name = name + new_stack.append(frame) + + return new_stack + + +def format_error_msg_verbose( + exc: Exception, + code: types.CodeType, + record_filename: str | None = None, + frame: DynamoFrameType | None = None, +) -> str: + msg = ( + f"WON'T CONVERT {code.co_name} {code.co_filename} line {code.co_firstlineno}\n" + ) + msg += "=" * 10 + " TorchDynamo Stack Trace " + "=" * 10 + "\n" + msg += format_exc() + real_stack = get_real_stack(exc, frame) + if real_stack is not None: + msg += ( + "\n" + + "=" * 10 + + " The above exception occurred while processing the following code " + + "=" * 10 + + "\n\n" + ) + msg += "".join(format_list(real_stack)) + msg += "\n" + msg += "=" * 10 + + return msg + + +def format_frame_info(code: types.CodeType) -> str: + return ( + f"{getattr(code, 'co_name', '')} " + f"({getattr(code, 'co_filename', '')} " + f"line {getattr(code, 'co_firstlineno', 0)})" + ) + + +def format_skip_frame_message(code: types.CodeType | None, reason: str) -> str: + if code is not None: + frame_info = format_frame_info(code) + return ( + f"torch.compile intentionally decided to skip the frame {frame_info} and fall back to eager.\n" + f"Reason: {reason}" + ) + else: + return ( + f"torch.compile intentionally decided to skip the frame and fall back to eager.\n" + f"Reason: {reason}" + ) + + +def format_error_msg( + exc: Exception, + code: types.CodeType, + record_filename: str | None = None, + frame: DynamoFrameType | None = None, +) -> str: + if config.verbose: + return format_error_msg_verbose(exc, code, record_filename, frame) + return f"WON'T CONVERT {code.co_name} {code.co_filename}\ + line {code.co_firstlineno} \ndue to: \n{format_exc()}" diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/external_utils.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/external_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c054a6e0488280b599dd21c09bf1aff58c10aadf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/external_utils.py @@ -0,0 +1,296 @@ +""" +This module contains utility functions that are explicitly allowed to be called during +TorchDynamo compilation. These functions are carefully vetted to ensure they work +correctly within the TorchDynamo tracing and compilation process. + +Key functionality groups: + +- Compilation State: + Functions for checking compilation state (is_compiling) + +- Function Wrapping: + Utilities for wrapping functions (wrap_inline, wrap_numpy) to work with + TorchDynamo compilation + +- Autograd Hooks: + Functions and classes for handling autograd hooks and backward passes + (call_hook, FakeBackwardCFunction, etc.) + +- Tensor Operations: + Utility functions for tensor operations and transformations +""" + +import functools +import warnings +from collections.abc import Callable +from typing import Any, TYPE_CHECKING, TypeVar +from typing_extensions import deprecated, ParamSpec + +import torch +import torch.utils._pytree as pytree + + +try: + import numpy as np +except ModuleNotFoundError: + np = None # type: ignore[assignment] + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +if TYPE_CHECKING: + # TorchScript does not support `@deprecated` + # This is a workaround to avoid breaking TorchScript + @deprecated( + "`torch._dynamo.external_utils.is_compiling` is deprecated. Use `torch.compiler.is_compiling` instead.", + category=FutureWarning, + ) + def is_compiling() -> bool: + return torch.compiler.is_compiling() + +else: + + def is_compiling() -> bool: + """ + Indicates whether we are tracing/compiling with torch.compile() or torch.export(). + """ + # NOTE: With `@torch.compile(backend="eager")`, torch._dynamo.is_compiling() will get traced + # and return true. torch.compiler.is_compiling() is skipped and will return false. + return torch.compiler.is_compiling() + + +def wrap_inline(fn: Callable[_P, _R]) -> Callable[_P, _R]: + """ + Create an extra frame around fn that is not in skipfiles. + """ + + @functools.wraps(fn) + def inner(*args: _P.args, **kwargs: _P.kwargs) -> _R: + return fn(*args, **kwargs) + + return inner + + +def call_hook( + hook: Callable[..., torch.Tensor | None], *args: Any, **kwargs: Any +) -> torch.Tensor: + """ + Used by compiled autograd to handle hook returning None. + """ + result = hook(*args) + if result is None: + return args[0] + elif kwargs.get("hook_type") == "post_acc_grad_hook": + raise RuntimeError("Tensor post accumulate grad hooks should return None.") + return result + + +def wrap_numpy(f: Callable[_P, _R]) -> Callable[_P, _R]: + r"""Decorator that turns a function from ``np.ndarray``s to ``np.ndarray``s into a function + from ``torch.Tensor``s to ``torch.Tensor``s. + """ + if not np: + return f + + @functools.wraps(f) + def wrap(*args: _P.args, **kwargs: _P.kwargs) -> pytree.PyTree: + args, kwargs = pytree.tree_map_only( + torch.Tensor, lambda x: x.numpy(), (args, kwargs) + ) + out = f(*args, **kwargs) + # pyrefly: ignore [missing-attribute] + return pytree.tree_map_only(np.ndarray, lambda x: torch.as_tensor(x), out) + + return wrap + + +class FakeBackwardCFunction: + def __init__( + self, + real: torch.autograd.function.BackwardCFunction, + saved_tensors: list[torch.Tensor], + ) -> None: + self.real = real + self.saved_tensors = saved_tensors + + def __getattr__(self, name: str) -> Any: + if name == "saved_variables": + warnings.warn( + "'saved_variables' is deprecated; use 'saved_tensors'", + DeprecationWarning, + ) + return self.saved_tensors + + return getattr(self.real, name) + + +def call_backward( + backward_c_function: torch.autograd.function.BackwardCFunction, + saved_tensors: list[torch.Tensor], + *args: Any, +) -> torch.Tensor | tuple[torch.Tensor, ...]: + fake = FakeBackwardCFunction(backward_c_function, saved_tensors) + grads = fake._forward_cls.backward(fake, *args) # type: ignore[attr-defined] + + if not isinstance(grads, tuple): + grads = (grads,) + + return grads + + +def normalize_as_list(x: Any) -> list[Any]: + if isinstance(x, tuple): + return list(x) + elif isinstance(x, list): + return x + return [x] + + +def untyped_storage_size(x: torch.Tensor) -> int: + return x.untyped_storage().size() + + +class FakeCompiledAutogradEngine: + @staticmethod + def queue_callback( + final_callbacks: list[Callable[[], None]], cb: Callable[[], None] + ) -> None: + final_callbacks.append(cb) + + @staticmethod + def exec_final_callbacks(final_callbacks: list[Callable[[], None]]) -> None: + i = 0 + while i < len(final_callbacks): + cb = final_callbacks[i] + cb() + i += 1 + final_callbacks.clear() + + @staticmethod + def _exec_final_callbacks_stub() -> None: + pass + + +def call_hook_from_backward_state( + *args: Any, bw_state: Any, hook_name: str, **kwargs: Any +) -> Any: + return getattr(bw_state, hook_name)(*args, **kwargs) + + +def call_module_hooks_from_backward_state( + _: Any, result: Any, *args: Any, bw_state: Any, hooks_name: str, module_name: str +) -> Any: + module = getattr(bw_state, module_name) + hooks = getattr(bw_state, hooks_name) + for hook in hooks: + new_result = hook(module, result, *args) + if new_result is not None: + result = new_result + return result + + +# used for torch._dynamo.disable(recursive=False) +def get_nonrecursive_disable_wrapper(fn: Callable[_P, _R]) -> Callable[_P, _R]: + # wrap function to get the right error message + # this function is in external_utils so that convert_frame doesn't skip it. + @functools.wraps(fn) + def nonrecursive_disable_wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R: + if torch.compiler.is_exporting(): + raise RuntimeError( + "Non-recursive torch.compiler.disable is not supported with torch.export." + ) + return fn(*args, **kwargs) + + return nonrecursive_disable_wrapper + + +def wrap_dunder_call_ctx_manager(self: Any, func: Callable[_P, _R]) -> Callable[_P, _R]: + """ + Apply self as a ctx manager around a call to func + """ + + # NOTE: do not functools.wraps(func) because we don't ever want this frame to be skipped! + def inner(*args: _P.args, **kwargs: _P.kwargs) -> _R: + with self: + return func(*args, **kwargs) + + return inner + + +# Use only on ints marked dynamic via torch.empty(0, integer) +# Currently only way to mark ints as dynamic: https://github.com/pytorch/pytorch/issues/129623 +def unwrap_maybe_dynamic_int(x: torch.Tensor | int) -> int: + if isinstance(x, torch.Tensor): + # x.size() is expected to be [0, dynamic_int] + return x.size(1) + return x + + +def call_accumulate_grad( + variable: torch.Tensor, + variable_grad: torch.Tensor | None, + grad: torch.Tensor | bool, + has_post_hooks: bool | None = None, +) -> torch.Tensor | None: + if has_post_hooks is None: + # Backward compatibility for graphs captured before current grad became + # an explicit argument. + has_post_hooks = bool(grad) + grad = variable_grad # type: ignore[assignment] + variable_grad = variable.grad + updated_grad = torch._dynamo.compiled_autograd.ops.AccumulateGrad( # type: ignore[attr-defined] + [grad], variable, variable_grad, has_post_hooks + ) + variable.grad = updated_grad[0] + return variable.grad + + +def wrap_inline_with_error_on_graph_break( + fn: Callable[_P, _R], error_on_graph_break: bool +) -> Callable[_P, _R]: + # NB: need multiple definitions in order to prevent `fullgraph` from + # being a freevar of wrapper + # NOTE: do not functools.wraps(fn) because we don't ever want these wrappers to be skipped! + if error_on_graph_break: + + def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R: + with torch._dynamo.error_on_graph_break(True): + return fn(*args, **kwargs) + + else: + + def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R: + with torch._dynamo.error_on_graph_break(False): + return fn(*args, **kwargs) + + return wrapper + + +def filter_out_const_values(tup: tuple[Any, ...], masks: list[bool]) -> tuple[Any, ...]: + """ + masks is a list of bools, where True means the corresponding element in tup + is a const value. Filter out the const values. + """ + out = [] + for mask_idx, mask in enumerate(masks): + if not mask: + out.append(tup[mask_idx]) + return tuple(out) + + +def insert_const_values_with_mask( + tup: tuple[Any, ...], masks: list[bool], values: tuple[Any, ...] +) -> tuple[Any, ...]: + """ + masks and values are of same length. For indices where the mask is True, use + the const_values to fill in. + """ + out = [] + idx = 0 + for mask_idx, mask in enumerate(masks): + if mask: + out.append(values[mask_idx]) + else: + out.append(tup[idx]) + idx += 1 + return tuple(out) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/funcname_cache.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/funcname_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..6aa935cd6749269236e3feb646ba0c7fb8c89b27 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/funcname_cache.py @@ -0,0 +1,74 @@ +""" +This module provides functionality for caching and looking up fully qualified function +and class names from Python source files by line number. + +It uses Python's tokenize module to parse source files and tracks function/class +definitions along with their nesting to build fully qualified names (e.g. 'class.method' +or 'module.function'). The results are cached in a two-level dictionary mapping: + + filename -> (line_number -> fully_qualified_name) + +Example usage: + name = get_funcname("myfile.py", 42) # Returns name of function/class at line 42 + clearcache() # Clear the cache if file contents have changed + +The parsing is done lazily when a file is first accessed. Invalid Python files or +IO errors are handled gracefully by returning empty cache entries. +""" + +import tokenize + + +cache: dict[str, dict[int, str]] = {} + + +def clearcache() -> None: + cache.clear() + + +def _add_file(filename: str) -> None: + try: + with tokenize.open(filename) as f: + tokens = list(tokenize.generate_tokens(f.readline)) + except (OSError, tokenize.TokenError): + cache[filename] = {} + return + + # NOTE: undefined behavior if file is not valid Python source, + # since tokenize will have undefined behavior. + result: dict[int, str] = {} + # current full funcname, e.g. xxx.yyy.zzz + cur_name = "" + cur_indent = 0 + significant_indents: list[int] = [] + + for i, token in enumerate(tokens): + if token.type == tokenize.INDENT: + cur_indent += 1 + elif token.type == tokenize.DEDENT: + cur_indent -= 1 + # possible end of function or class + if significant_indents and cur_indent == significant_indents[-1]: + significant_indents.pop() + # pop the last name + cur_name = cur_name.rpartition(".")[0] + elif ( + token.type == tokenize.NAME + and i + 1 < len(tokens) + and tokens[i + 1].type == tokenize.NAME + and (token.string == "class" or token.string == "def") + ): + # name of class/function always follows class/def token + significant_indents.append(cur_indent) + if cur_name: + cur_name += "." + cur_name += tokens[i + 1].string + result[token.start[0]] = cur_name + + cache[filename] = result + + +def get_funcname(filename: str, lineno: int) -> str | None: + if filename not in cache: + _add_file(filename) + return cache[filename].get(lineno, None) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/functional_export.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/functional_export.py new file mode 100644 index 0000000000000000000000000000000000000000..84be0697c0b189f3c2d2fbd885d68eb0d82ef847 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/functional_export.py @@ -0,0 +1,1104 @@ +from __future__ import annotations + +import inspect +import logging +import sys +import traceback +import types +from collections import namedtuple +from contextlib import nullcontext +from typing import Any, cast, TYPE_CHECKING, TypeVar + +import sympy + +import torch +import torch.fx +import torch.utils._pytree as pytree +from torch._dynamo.convert_frame import CaptureOutput, fullgraph_capture, get_traced_fn +from torch._dynamo.decorators import disable as dynamo_disable +from torch._dynamo.eval_frame import argument_names, check_user_input_output +from torch._dynamo.exc import UserErrorType +from torch._dynamo.source import GetItemSource +from torch._dynamo.utils import dynamo_timed, get_metrics_context +from torch._export.utils import _compiling_state_context +from torch._guards import detect_fake_mode, Source, TracingContext +from torch.export.dynamic_shapes import _RelaxedConstraint, Constraint +from torch.fx.experimental.symbolic_shapes import ( + ConstraintViolationError, + DimDynamic, + StatelessSymbolicContext, +) +from torch.fx.graph import _PyTreeCodeGen, _PyTreeInfo + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Sequence + + from torch._dynamo.output_graph import OutputReturnInfo + from torch._subclasses.fake_tensor import FakeTensorMode + from torch.export._trace import _DynamicShapesInput + from torch.fx import Node + from torch.fx.node import Argument, Target + +from torch.fx.experimental._spec_binding import _bind_spec_to_args +from torch.fx.experimental.dynamic_spec import ( + _coerce_to_shapes_spec, + IntermediateSpec, + ParamsSpec, + ShapesSpec, +) + + +T = TypeVar("T") +log = logging.getLogger(__name__) + + +def post_process_error_msg( + constraint_violation_error: ConstraintViolationError, + func: Callable[..., Any], + args: Any, + kwargs: Any, +) -> ConstraintViolationError: + """ + Because we trace a different callable, the sources are all messed up. + Manually patch them so the error message looks correct. + """ + from torch.export._unlift import _get_input_paths, _replace_sources + + orig_sig = inspect.signature(func) + flat_input_paths = _get_input_paths((args, kwargs), orig_sig) + if constraint_violation_error.args: + constraint_violation_error.args = ( + _replace_sources(constraint_violation_error.args[0], flat_input_paths), + ) + return constraint_violation_error + + +EXPORT_ROOT_REPLACEMENTS = [ + ("__export_root_", "_"), + ("_export_root.", ""), + ("._export_root", ""), +] + + +def clean_export_root_string(text: str) -> str: + """Generic utility to clean export_root patterns from strings.""" + result = text + for pattern, replacement in EXPORT_ROOT_REPLACEMENTS: + result = result.replace(pattern, replacement) + return result + + +def clean_nn_module_stack_and_source_fn( + graph_module: torch.fx.GraphModule, is_inline_builtin: bool = False +) -> torch.fx.GraphModule: + """ + Clean up nn_module_stack metadata by removing export_root references. + + Removes the _export_root module references from nn_module_stack metadata + in graph nodes, which are artifacts from the export process. Fixes two patterns: + + 1. Keys: Removes "__export_root_" and "__modules['_export_root']_" prefixes + - Normal case: "L__self____export_root_child" -> "L__self__child" + - inline_builtin case: Uses numeric ID strings like "140468831433840" + + 2. Values: Removes "._export_root" and "._modules['_export_root']" from child names + e.g., "L['self']._export_root.child" -> "L['self'].child" + e.g., "L['self']._modules['_export_root'].child" -> "L['self'].child" + + Also removes the root export entry "L__self____export_root" entirely. + + Args: + graph_module: The GraphModule to clean up + is_inline_builtin: If True, keys are numeric ID strings and self references + (L['self']) are filtered out + + Returns: + The cleaned GraphModule (modified in-place) + """ + + def _process_nn_module_stack( + nn_module_stack: dict[str, tuple[str, T]], + ) -> dict[str, tuple[str, T]]: + if "L__self____export_root" in nn_module_stack: + del nn_module_stack["L__self____export_root"] + + # Clean up remaining entries + cleaned_stack = {} + for key, (child_name, child_class) in nn_module_stack.items(): + # Clean key by removing export_root patterns + clean_key = clean_export_root_string(key) + + # Clean child_name by removing export_root patterns + clean_name = clean_export_root_string(child_name) + + # Skip self reference for inline builtin case + if is_inline_builtin and clean_name == "L['self']": + continue + + cleaned_stack[clean_key] = (clean_name, child_class) + return cleaned_stack + + def _process_source_fn(source_fn_stack: Iterable[T]) -> Iterable[T]: + cleaned_stack = [] + for item in source_fn_stack: + if isinstance(item, tuple) and len(item) == 2: + name, cls = item + if isinstance(name, str): + clean_name = clean_export_root_string(name) + cleaned_stack.append((clean_name, cls)) + else: + cleaned_stack.append(item) + else: + # pyrefly: ignore [bad-argument-type] + cleaned_stack.append(item) + # pyrefly: ignore [bad-return] + return cleaned_stack + + for node in graph_module.graph.nodes: + if "nn_module_stack" in node.meta: + node.meta["nn_module_stack"] = _process_nn_module_stack( + node.meta["nn_module_stack"].copy() + ) + + source_fn_stack = node.meta.get("source_fn_stack", None) + if source_fn_stack: + node.meta["source_fn_stack"] = _process_source_fn(source_fn_stack.copy()) + + if "dynamo_flat_name_to_original_fqn" in graph_module.meta: + # Clean up flat name to original fqn mapping + clean_name_to_original_fqn = {} + for flat_name, original_fqn in graph_module.meta[ + "dynamo_flat_name_to_original_fqn" + ].items(): + clean_name_to_original_fqn[clean_export_root_string(flat_name)] = ( + clean_export_root_string(original_fqn) + ) + graph_module.meta["dynamo_flat_name_to_original_fqn"] = ( + clean_name_to_original_fqn + ) + + return graph_module + + +def clean_export_root(graph_module: torch.fx.GraphModule) -> None: + """Remove export_root artifacts from FX graph in-place""" + + # Unlike getattr node, call_module can be invoked multiple times + # In those cases, we should fix all invocations of call_module + clean_named_module_map: dict[str, str] = {} + + # Update get_attr nodes in-place + for node in graph_module.graph.nodes: + if node.op == "get_attr": + old_target = node.target + new_target = clean_export_root_string(old_target) + if new_target != old_target: + node.target = new_target + if not hasattr(graph_module, old_target): + raise AssertionError( + f"graph_module missing attribute {old_target!r}" + ) + # Move the parameter to the new name + param = torch.fx.graph_module._get_attr(graph_module, old_target) + torch.fx.graph_module._assign_attr(param, graph_module, new_target) + torch.fx.graph_module._del_attr(graph_module, old_target) + # Dynamo will only have one nested level + if node.op == "call_module": + old_target = node.target + if not isinstance(old_target, str): + raise AssertionError( + f"expected old_target to be str, got {type(old_target)}" + ) + new_target = clean_export_root_string(old_target) + if not isinstance(new_target, str): + raise AssertionError( + f"expected new_target to be str, got {type(new_target)}" + ) + new_name = clean_export_root_string(node.name) + if new_target == old_target: + continue + + # if this module has already been cleaned before, just lookup from map. + if old_target in clean_named_module_map: + node.target = clean_named_module_map[old_target] + node.name = new_name + continue + target = graph_module.get_submodule(old_target) + graph_module.delete_submodule(old_target) + graph_module.add_submodule(new_target, target) + node.target = new_target + node.name = new_name + clean_named_module_map[old_target] = new_target + + +class ModuleToTrace(torch.nn.Module): + def __init__(self, foo: Any, in_spec: Any) -> None: + super().__init__() + self._export_root = foo + self.in_spec = in_spec + + def forward(self, *flat_args: Any) -> ExportTracerOutput: + args, kwargs = pytree.tree_unflatten(flat_args, self.in_spec) + res = self._export_root(*args, **kwargs) + out_flat, out_spec = pytree.tree_flatten(res) + return ExportTracerOutput(out_flat, out_spec) + + +ExportTracerOutput = namedtuple("ExportTracerOutput", ["flat_args", "out_spec"]) + + +# mypy: disable-error-code="no-untyped-def,var-annotated,assignment,index,operator" +class DynamoGraphTransformer(torch.fx.Transformer): + """Graph transformer for dynamo export that flattens inputs/outputs without complex matching.""" + + def __init__( + self, + module: torch.fx.GraphModule, + flat_inputs: list[Any], + flat_args_dynamic_dims: list[set[int]], + graph_input_order: dict[int, int], + graph_output_map: dict[int, OutputReturnInfo], + fake_mode: FakeTensorMode | None = None, + graph_inputs: dict[int, Source | None] | None = None, + ) -> None: + super().__init__(module) + + if len(flat_args_dynamic_dims) != len(flat_inputs): + raise AssertionError( + f"flat_args_dynamic_dims length ({len(flat_args_dynamic_dims)}) " + f"must match flat_inputs length ({len(flat_inputs)})" + ) + + self.flat_inputs = flat_inputs + self.flat_args_dynamic_dims = flat_args_dynamic_dims + self.graph_input_order = graph_input_order + self.graph_output_map = graph_output_map + self.fake_mode = fake_mode + self.graph_inputs = graph_inputs or {} + + # Get original placeholders and output + self.placeholders = [n for n in module.graph.nodes if n.op == "placeholder"] + self.output_node = next(n for n in module.graph.nodes if n.op == "output") + + # Create new flattened input placeholders + self.new_input_nodes: dict[int, torch.fx.Node] = {} + self._create_flattened_inputs() + + # Iterator for replacing old placeholders + self.old_to_new_mapping = {} + self._create_placeholder_mapping() + + def _create_flattened_inputs(self) -> None: + """Create new placeholder nodes for flattened inputs with proper fake tensors.""" + for i in range(len(self.flat_inputs)): + placeholder = super().placeholder(f"arg_{i}", (), {}) + + # Check if this user input (index i) maps to a graph placeholder + if i in self.graph_input_order: + # graph_input_order[i] gives us which graph placeholder this user input corresponds to + graph_placeholder_idx = self.graph_input_order[i] + if graph_placeholder_idx < len(self.placeholders): + orig_placeholder = self.placeholders[graph_placeholder_idx] + # Copy other metadata but not "val" yet + for key, value in orig_placeholder.meta.items(): + if key != "val": + placeholder.node.meta[key] = value + + # Always ensure we have proper "val" metadata from fake tensor + if self.fake_mode is not None and isinstance( + self.flat_inputs[i], torch.Tensor + ): + placeholder.node.meta["val"] = self.fake_mode.from_tensor( + self.flat_inputs[i], + symbolic_context=StatelessSymbolicContext( + dynamic_sizes=[ + ( + DimDynamic.DYNAMIC + if d in self.flat_args_dynamic_dims[i] + else DimDynamic.STATIC + ) + for d in range(len(self.flat_inputs[i].shape)) + ], + constraint_sizes=[None] * len(self.flat_inputs[i].shape), + ), + ) + elif hasattr(self.flat_inputs[i], "val"): # _IntWrapper case + placeholder.node.meta["val"] = self.flat_inputs[i].val + else: + placeholder.node.meta["val"] = self.flat_inputs[i] + + # pyrefly: ignore [unsupported-operation] + self.new_input_nodes[i] = placeholder + + def _create_placeholder_mapping(self) -> None: + """Create mapping from old placeholders to new ones.""" + # graph_input_order maps: user_input_index -> graph_placeholder_index + # We need to create: old_graph_placeholder -> new_user_input_placeholder + for user_input_idx, graph_placeholder_idx in self.graph_input_order.items(): + if graph_placeholder_idx < len(self.placeholders): + old_placeholder = self.placeholders[graph_placeholder_idx] + new_placeholder = self.new_input_nodes[user_input_idx] + self.old_to_new_mapping[old_placeholder] = new_placeholder + + def placeholder( + self, target: Target, args: tuple[Argument, ...], kwargs: dict[str, Any] + ) -> Any: + """Replace old placeholders with new flattened ones.""" + # Return the corresponding new placeholder + if self.current_node in self.old_to_new_mapping: + new_arg = self.old_to_new_mapping[self.current_node] + + # Copy over additional metadata from current node, but don't overwrite "val" + for key in ["tensor_dict", "example_value", "unbacked_bindings"]: + if key in self.current_node.meta: + new_arg.node.meta[key] = self.current_node.meta[key] + + # Only copy "val" if we don't already have a good one + if "val" in self.current_node.meta and "val" not in new_arg.node.meta: + new_arg.node.meta["val"] = self.current_node.meta["val"] + + return new_arg + else: + # Convert captured objects (e.g., opaque objects from closures) to + # get_attr nodes + placeholder_idx = self.placeholders.index(self.current_node) + if placeholder_idx in self.graph_inputs: + source = self.graph_inputs[placeholder_idx] + if not isinstance(source, GetItemSource): + example_val = self.current_node.meta.get( + "val" + ) or self.current_node.meta.get("example_value") + if example_val is not None: + attr_name = f"_captured_{placeholder_idx}" + if isinstance(example_val, torch.Tensor): + self.module.register_buffer(attr_name, example_val) + else: + setattr(self.module, attr_name, example_val) + result = self.tracer.create_proxy("get_attr", attr_name, (), {}) + result.node.meta = self.current_node.meta.copy() + result.node.meta["val"] = example_val + return result + return super().placeholder(target, args, kwargs) + + def output( + self, target: Target, args: Sequence[Any], kwargs: dict[str, Any] + ) -> Any: + """Transform output according to graph_output_map.""" + original_outputs = args[0] + + # Build new output list based on graph_output_map + new_outputs = [] + for i in sorted(self.graph_output_map.keys()): + output_type, val = self.graph_output_map[i] + + if output_type == "graph_out": + new_outputs.append(original_outputs[cast(int, val)]) + elif output_type == "input": + input_idx = cast(GetItemSource, val).index + new_outputs.append(self.new_input_nodes[input_idx]) + elif output_type == "constant": + new_outputs.append(val) + + return super().output(target, (tuple(new_outputs),), {}) + + def run_node(self, n: Node) -> Any: + """Run node transformation and preserve metadata.""" + self.current_node = n + result = super().run_node(n) + + # Copy important metadata + if hasattr(result, "node") and result.node is not n: + for key in ["val", "example_value", "unbacked_bindings"]: + if key in n.meta: + result.node.meta[key] = n.meta[key] + + # Preserve node names (except output) + if n.op != "output" and hasattr(n, "name"): + result.node._rename(n.name) + + return result + + def transform(self) -> torch.fx.GraphModule: + """Perform the graph transformation and copy module metadata.""" + result_gm = super().transform() + + # Copy module metadata like the original implementation + if hasattr(self.module, "meta"): + # pyrefly: ignore [unsupported-operation] + if "dynamo_flat_name_to_original_fqn" in self.module.meta: + # pyrefly: ignore [bad-index] + result_gm.meta["dynamo_flat_name_to_original_fqn"] = self.module.meta[ + # pyrefly: ignore [bad-index] + "dynamo_flat_name_to_original_fqn" + ] + # pyrefly: ignore [unsupported-operation] + if "dynamo_compile_id" in self.module.meta: + # pyrefly: ignore [bad-index] + result_gm.meta["dynamo_compile_id"] = self.module.meta[ + # pyrefly: ignore [bad-index] + "dynamo_compile_id" + ] + + return result_gm + + +def _suggest_or_raise_constraint_violation( + module_to_trace: torch.nn.Module, + orig_callable: Callable[..., Any], + fake_mode: FakeTensorMode | None, + graph_capture_output: CaptureOutput, + args: Any, + kwargs: Any, + dynamic_shapes: dict[str, Any] | tuple[Any] | list[Any] | None, +) -> None: + constraint_violation_error = None + try: + # Check if we have any constraint violations + fn, _ = get_traced_fn(module_to_trace) + graph_capture_output.graph_capture_output.build_guards(fn.__code__) + except ConstraintViolationError as e: + constraint_violation_error = e + + if ( + (shape_env := getattr(fake_mode, "shape_env", None)) is not None + and (dim_constraints := shape_env.dim_constraints) is not None + and not isinstance( + module_to_trace.forward, + torch._ops.OpOverloadPacket | torch._ops.OpOverload, + ) + ): + dim_constraints.solve() + + forced_specializations = dim_constraints.forced_specializations() + + msg = dim_constraints.prettify_results( + inspect.signature(orig_callable), # type: ignore[attr-defined] + dynamic_shapes, + constraint_violation_error, + forced_specializations, + ) + if constraint_violation_error: + if constraint_violation_error.args: + constraint_violation_error.args = ( + constraint_violation_error.args[0] + msg, + ) + else: + constraint_violation_error.args = (msg,) + else: + if forced_specializations: + constraint_violation_error = ConstraintViolationError(msg) + else: + log.info( + "Summary of dimension constraints:%s", + msg, + ) + + # Error if we have any constraints on static values + + for k in shape_env.var_to_range: + if isinstance(k, sympy.Integer): + constraint_violation_error = ConstraintViolationError( + f"{''.join(traceback.format_list(shape_env.var_to_stack[k]))}\n" + "It appears that you're trying to set a constraint on a " + f"value which we evaluated to have a static value of {k}. " + 'Set TORCH_LOGS="+export" for more information.' + ) + if constraint_violation_error: + constraint_violation_error = post_process_error_msg( + constraint_violation_error, orig_callable, args, kwargs + ) + raise constraint_violation_error + + +def _normalize_shuffle_graph(shuffle_gm: torch.fx.GraphModule) -> None: + shuffle_gm.graph.eliminate_dead_code() + shuffle_gm.recompile() + for name, buffer in list(shuffle_gm.named_buffers()): + delattr(shuffle_gm, name) + setattr(shuffle_gm, name, buffer) + + +def normalize_graph_module(gm: torch.fx.GraphModule) -> None: + for node in gm.graph.nodes: + if node.op == "placeholder": + node.meta["val"] = node.meta["example_value"] + + +class InputProcessor: + def __init__( + self, + root: object, + num_args: int, + kwarg_names: list[str], + ) -> None: + self.root = root + self.num_args = num_args + self.kwarg_names = kwarg_names + + def __call__( + self, inputs: tuple[object, ...] + ) -> tuple[tuple[object, ...], dict[str, object]]: + args = inputs + # pyrefly: ignore [implicit-any] + kwargs = {} + if len(args) > self.num_args: + kwargs = dict(zip(self.kwarg_names, args[self.num_args :])) + args = args[: self.num_args] + if self.root is not None: + if isinstance(self.root, torch.fx.GraphModule): + if not isinstance(self.root.graph._codegen, _DynamoBytecodeCodeGen): + raise AssertionError( + f"expected _DynamoBytecodeCodeGen, got {type(self.root.graph._codegen)}" + ) + if not hasattr( + self.root.graph._codegen.dynamo_bytecode_flatten, "input_processor" + ): + raise AssertionError( + "dynamo_bytecode_flatten missing input_processor attribute" + ) + if ( + self.root.graph._codegen.dynamo_bytecode_flatten.input_processor + is not self + ): + raise AssertionError( + "dynamo_bytecode_flatten.input_processor is not self" + ) + args = (self.root, *args) + return args, kwargs + + +class Yield(Exception): + pass + + +class DynamoBytecodeFlatten: + def __init__( + self, + input_processor: InputProcessor, + out: CaptureOutput, + f_globals: dict[str, object], + ) -> None: + self.input_processor = input_processor + self.out = out + self.f_globals = f_globals + self.gm_inputs: tuple[Any, ...] | None = None + + @dynamo_disable(reason="do not trace internal dynamo graph capture") # type: ignore[misc] + def __call__(self, *inputs: object) -> object: + def backend_dummy(*example_inputs: object) -> None: + self.gm_inputs = example_inputs + raise Yield + + args, kwargs = self.input_processor(inputs) + try: + self.out.forward_callable( + compiled_fn=backend_dummy, extra_globals=self.f_globals + )(*args, **kwargs) + except Yield: + if self.gm_inputs is None: + raise AssertionError("gm_inputs must not be None after Yield") from None + return self.gm_inputs + raise RuntimeError + + +class DynamoBytecodeUnflatten: + def __init__( + self, + input_processor: InputProcessor, + out: CaptureOutput, + f_globals: dict[str, object], + ) -> None: + self.input_processor = input_processor + self.out = out + self.f_globals = f_globals + + @dynamo_disable(reason="do not trace internal dynamo graph capture") # type: ignore[misc] + def __call__( + self, flat_outs: Sequence[object], inputs: tuple[object, ...] + ) -> object: + def backend_dummy(*example_inputs: object) -> Sequence[object]: + return flat_outs + + args, kwargs = self.input_processor(inputs) + with torch._C._DisableTorchDispatch(): + results = self.out.forward_callable( + compiled_fn=backend_dummy, extra_globals=self.f_globals + )(*args, **kwargs) + return results + + +def create_fx_graph_from_captured_output( + out: CaptureOutput, mod: Any, args: tuple[Any, ...], kwargs: dict[str, Any] +) -> torch.fx.GraphModule: + if out.backend_input is None: + raise AssertionError("out.backend_input must not be None") + backend_input = out.backend_input + + _, root = torch._dynamo.convert_frame.get_traced_fn(mod) + + flat_real_args = pytree.tree_leaves((args, kwargs)) + torch._dynamo.eval_frame.check_user_input_output( + flat_real_args, UserErrorType.INVALID_INPUT + ) + f_globals = out.graph_capture_output.f_globals + + graph_module = backend_input.graph_module + if isinstance(root, torch.nn.Module): + graph_module._parameters = root._parameters + graph_module._buffers = root._buffers + if not all(not hasattr(graph_module, m) for m in root._modules): + raise AssertionError( + "graph_module already has attributes conflicting with root._modules" + ) + graph_module._modules.update(root._modules) + graph_module._non_persistent_buffers_set = root._non_persistent_buffers_set + if sys.version_info >= (3, 14): + import annotationlib # added in 3.14 + + annotations = annotationlib.get_annotations(torch.nn.Module) + else: + annotations = getattr(torch.nn.Module, "__annotations__", None) + for name, value in root.__dict__.items(): + if annotations and name not in annotations: + graph_module.__dict__[name] = value + graph_module._forward_hooks = root._forward_hooks.copy() + graph_module._forward_pre_hooks = root._forward_pre_hooks.copy() + graph_module._backward_hooks = root._backward_hooks.copy() + graph_module._backward_pre_hooks = root._backward_pre_hooks.copy() + if graph_module._forward_hooks or graph_module._forward_pre_hooks: + # Even forward hooks are traced through, they still capture a bunch + # of state through closure. We need to make sure these data are + # accessible through the captured module (but the hooks should be + # disabled). + if getattr(graph_module, "_wrapped_call", None) is None: + raise AssertionError("graph_module._wrapped_call must not be None") + if not isinstance( + graph_module._wrapped_call, torch.fx.graph_module._WrappedCall + ): + raise AssertionError( + f"expected _WrappedCall, got {type(graph_module._wrapped_call)}" + ) + if graph_module._wrapped_call.cls_call is not None: + raise AssertionError("graph_module._wrapped_call.cls_call must be None") + + def dynamo_wrapped_call(self, *args: object, **kwargs: object) -> object: + if "forward" in self.__dict__: + raise AssertionError("'forward' should not be in self.__dict__") + + fwd_hooks = self._forward_hooks + fwd_pre_hooks = self._forward_pre_hooks + original_forward = type(self).forward + + def patched_forward(self, *args: object, **kwargs: object) -> object: + self._forward_hooks = fwd_hooks + self._forward_pre_hooks = fwd_pre_hooks + return original_forward(self, *args, **kwargs) + + try: + self.forward = types.MethodType(patched_forward, self) + # pyrefly: ignore [implicit-any] + self._forward_hooks = {} + # pyrefly: ignore [implicit-any] + self._forward_pre_hooks = {} + # pyrefly: ignore [invalid-argument] + return super(type(self), self).__call__(*args, **kwargs) + finally: + self.__dict__.pop("forward") + self._forward_hooks = fwd_hooks + self._forward_pre_hooks = fwd_pre_hooks + + # pyrefly: ignore [bad-assignment] + graph_module._wrapped_call.cls_call = dynamo_wrapped_call + + root = graph_module if isinstance(root, torch.nn.Module) else root + input_processor = InputProcessor(root, len(args), list(kwargs.keys())) + dynamo_bytecode_flatten = DynamoBytecodeFlatten(input_processor, out, f_globals) + dynamo_bytecode_unflatten = DynamoBytecodeUnflatten(input_processor, out, f_globals) + + graph_module.graph._codegen = _DynamoBytecodeCodeGen( + argument_names(inspect.signature(mod), args, kwargs), + dynamo_bytecode_flatten, + dynamo_bytecode_unflatten, + ) # type: ignore[attr-defined] + normalize_graph_module(graph_module) + if hasattr(graph_module, "_dynamo_bytecode_flatten"): + raise AssertionError( + "graph_module already has _dynamo_bytecode_flatten attribute" + ) + if hasattr(graph_module, "_dynamo_bytecode_unflatten"): + raise AssertionError( + "graph_module already has _dynamo_bytecode_unflatten attribute" + ) + # pyrefly: ignore [bad-argument-type] + graph_module._dynamo_bytecode_flatten = dynamo_bytecode_flatten + # pyrefly: ignore [bad-argument-type] + graph_module._dynamo_bytecode_unflatten = dynamo_bytecode_unflatten + delattr(graph_module, "_param_name_to_source") + graph_module.recompile() + graph_module.meta["module_call_specs"] = ( + out.graph_capture_output.output_graph.export_metadata.module_call_spec + ) + if out.backend_input is None: + raise AssertionError("out.backend_input must not be None for fake_mode") + graph_module.meta["fake_mode"] = out.backend_input.fake_mode # type: ignore[attr-defined] + graph_module.meta["fake_mode"].allow_non_fake_inputs = True + tracing_context = TracingContext(graph_module.meta["fake_mode"]) + tracing_context.tensor_to_context = out.backend_input.tensor_to_context # type: ignore[attr-defined] + graph_module.meta["tracing_context"] = tracing_context + return graph_module + + +class _DynamoBytecodeCodeGen(torch.fx.graph.CodeGen): + def __init__( + self, + orig_arg_names: list[str], + dynamo_bytecode_flatten: DynamoBytecodeFlatten, + dynamo_bytecode_unflatten: DynamoBytecodeUnflatten, + ) -> None: + super().__init__() + self.orig_arg_names = orig_arg_names + self.dynamo_bytecode_flatten = dynamo_bytecode_flatten + self.dynamo_bytecode_unflatten = dynamo_bytecode_unflatten + self.wrap_tuple = False + self._inputs: tuple[Any, ...] | None = None + + def process_inputs(self, *inputs: Any) -> Any: + self._inputs = inputs + results = self.dynamo_bytecode_flatten(*inputs) + fake_mode = detect_fake_mode() + if fake_mode is not None and pytree.tree_any( + lambda x: isinstance(x, torch.Tensor) and not fake_mode.is_our_fake(x), + results, + ): + # Bytecode replay can recover tensors captured from module + # attributes as extra FX placeholder values. These tensors are not + # visible in AOTAutograd's user-facing call signature, so allow the + # active FakeTensorMode to convert them at dispatch time. This must + # remain enabled for AOT's backward trace too, since autograd can + # save the recovered tensors from the forward. + fake_mode.allow_non_fake_inputs = True + return results + + def process_outputs(self, outputs: Any) -> Any: + if self._inputs is None: + raise AssertionError("process_outputs called before process_inputs") + results = self.dynamo_bytecode_unflatten(outputs, self._inputs) + if self.wrap_tuple: + results = (results,) + self._inputs = None + return results + + def gen_fn_def( + self, + free_vars: list[str], + maybe_return_annotation: str, + *, + expanded_def: bool = False, + ) -> str: + fn_args = self.orig_arg_names + has_orig_self = (fn_args[0] == "self") if len(fn_args) > 0 else False + if has_orig_self: + free_vars.insert(0, "self") + # Rename any non-first `self` in fn_args to a unique name. The base + # CodeGen.gen_fn_def prepends `"self"` for the GraphModule's bound- + # method receiver whenever fn_args[0] != "self", which collides with + # a schema param literally named `self` (e.g. `aten.where.self(Tensor + # cond, Tensor self, Tensor other)` -> `def forward(self, cond, self, + # other)` -> `SyntaxError: duplicate argument 'self' in function + # definition`). Both the function-def arg list (via super().gen_fn_def) + # and the body binding (via gen_var_bindings) reference fn_args, so + # the rename is consistent end-to-end. + fn_args = list(fn_args) + first_pos = 1 if has_orig_self else 0 + for i in range(first_pos, len(fn_args)): + if fn_args[i] == "self": + new_name = "self_" + while new_name in fn_args: + new_name += "_" + fn_args[i] = new_name + fn_definition = super().gen_fn_def( + fn_args[:], maybe_return_annotation, expanded_def=expanded_def + ) + + if len(free_vars) > 0: # pytree has placeholders in it + fn_definition += self.gen_var_bindings(fn_args, free_vars, expanded_def) + return fn_definition + + def gen_var_bindings( + self, fn_args: list[str], free_vars: list[str], expanded_def: bool + ) -> str: + without_annotation = [x.split(":")[0].split("#")[0] for x in free_vars] + if len(fn_args) == 0: + fn_signature = "" + elif len(fn_args) == 1: + fn_signature = f"{fn_args[0]}, " + else: + fn_signature = f"{', '.join(fn_args)}" + return f""" + _fn_args = ({fn_signature}) + {", ".join(without_annotation)}, = self._dynamo_bytecode_flatten(*_fn_args)""" + + def generate_output( + self, + output_args: torch.fx.node.Argument, + *, + descs: object | None = None, + repr_fn: Any | None = None, + ) -> str: + if repr_fn is None: + repr_fn = repr + # pyrefly: ignore [not-iterable] + returned = f"self._dynamo_bytecode_unflatten(({', '.join([repr_fn(a) for a in output_args])},), _fn_args)" + if self.wrap_tuple: + returned = f"({returned},)" + return f"return {returned}" + + +def dynamo_graph_capture_for_export( + fn: Callable[..., Any], + constraints: list[Constraint] | None = None, +) -> Callable[..., Any]: + if isinstance(fn, torch._ops.OpOverload): + + def default_annotation(arg: torch.Argument) -> str: + if arg.has_default_value(): + return f"={arg.default_value!r}" + return "" + + has_kwarg_only = False + arg_list = [] + for arg in fn._schema.arguments: + if arg.kwarg_only and not has_kwarg_only: + has_kwarg_only = True + arg_list.append("*") + arg_list.append(arg.name + default_annotation(arg)) + func_str = f""" +def op_overload_wrapper({", ".join(arg_list)}): + return op({", ".join([f"{arg.name}={arg.name}" for arg in fn._schema.arguments])}) +""" + out = {} + exec(func_str, {"op": fn}, out) + fn = out["op_overload_wrapper"] # type: ignore[assignment] + + def inner(*args: Any, **kwargs: Any) -> Any: + if torch._dynamo.config.install_free_tensors: + raise AssertionError("install_free_tensors must be False") + with ( + _compiling_state_context(), + torch._dynamo.config.patch( + replay_side_effects=False, side_effect_replay_policy="warn" + ), + get_metrics_context(), + dynamo_timed("fullgraph_capture"), + ): + out = fullgraph_capture( + fn, + args, + kwargs, + constraints=constraints, + ) + graph_module = create_fx_graph_from_captured_output(out, fn, args, kwargs) + return graph_module + + return inner + + +def _dynamo_graph_capture_for_export( + mod: Callable[..., Any], + *, + constraints: list[Constraint] | None = None, + dynamic_shapes: _DynamicShapesInput = None, +) -> Callable[..., torch.fx.GraphModule]: + """ + Improved dynamo graph capture using transformer approach with proper fake tensor handling. + + This function creates a capture instance that handles: + 1. PyTree flattening/unflattening with proper input ordering + 2. Dynamo graph capture with export-specific context + 3. FX graph transformation for export compatibility + 4. Proper fake tensor metadata preservation + 5. Dynamic dimension constraint handling + + Notable improvements over manual approach: + - Uses FX Transformer for cleaner graph manipulation + - Properly handles fake tensor metadata and dynamic dimensions + - Preserves all necessary metadata for export + - More robust error handling and edge case management + + TODO: + 1. Are we actually gonna run the bytecode? + 2. Need to attach guards + """ + + _constraints = constraints + + def inner(*args: Any, **kwargs: Any) -> torch.fx.GraphModule: + # This sets the is_exporting flag when building guards. + with _compiling_state_context(): + # Only a ShapesSpec/ParamsSpec object opts into the new spec API. + # A bare dict/tuple in export's `dynamic_shapes` is now bound to + # the Dim export API. + # TODO: inspect dictionary leaves and enable dict for ParamsSpec + # here too, like make_fx and compile. + user_spec: ShapesSpec | None = None + if isinstance(dynamic_shapes, (ShapesSpec, ParamsSpec)): + user_spec = _coerce_to_shapes_spec(dynamic_shapes) + flattened_spec: ShapesSpec | None = None + if user_spec is not None: + # _bind_spec_to_args also flattens (args, kwargs) for us. + leaf_specs, flat_inputs, in_spec = _bind_spec_to_args( + mod, args, kwargs, user_spec + ) + flattened_spec = ShapesSpec( + # leaf_specs is list[LeafSpec]; cast around list invariance + # (ParamsSpec wants list[IntermediateSpec]). + ParamsSpec({"*args": cast(list[IntermediateSpec], leaf_specs)}), + assumptions=user_spec._assumptions or None, + ) + else: + flat_inputs, in_spec = pytree.tree_flatten((args, kwargs)) + check_user_input_output(flat_inputs, UserErrorType.INVALID_INPUT) + module_to_trace = ModuleToTrace(mod, in_spec) + orig_callable = mod.forward if isinstance(mod, torch.nn.Module) else mod + + constraints: list[Constraint] | None = _constraints + + from . import reset # type: ignore[attr-defined] + + reset() + + dynamo_config_ctx = torch._dynamo.config.patch( + specialize_int=True, + specialize_float=True, + assume_static_by_default=True, + automatic_dynamic_shapes=False, + capture_dynamic_output_shape_ops=True, + capture_scalar_outputs=True, + constant_fold_autograd_profiler_enabled=True, + log_graph_in_out_metadata=True, + # install_free_tensors ensures that params and buffers are still + # added as graph attributes, and makes Dynamo emits graphs that + # follow export pytree-able input requirements In future, if we + # fully rely on bytecode for the runtime, we can turn this flag + # off. + install_free_tensors=torch._dynamo.config.install_free_tensors_for_export, + ) + + # If a user spec was supplied, re-key it to the intermediate + # ModuleToTrace.forward(*flat_args) layout and expose via + # ``torch._dynamo.config._dynamic_shapes_spec`` for the variable + # builder. + shapes_spec_in_use = user_spec is not None + shapes_spec_ctx = nullcontext() + if flattened_spec is not None: + shapes_spec_ctx = torch._dynamo.config.patch( + _dynamic_shapes_spec=flattened_spec + ) + + with ( + get_metrics_context(), + dynamo_timed("fullgraph_capture"), + dynamo_config_ctx, + shapes_spec_ctx, + ): + out = fullgraph_capture( + module_to_trace, + tuple(flat_inputs), + constraints=_constraints, + _is_export_deprecated_do_not_use=True, + ) + + if out.graph_capture_output.output_graph is None: + raise AssertionError( + "output_graph must not be None after fullgraph_capture" + ) + + example_inputs: list[Any] = [] + if out.backend_input is not None: + graph = out.backend_input.graph_module + fake_mode = out.backend_input.fake_mode + example_inputs = out.backend_input.example_inputs + else: + graph = torch.fx.GraphModule(torch.nn.Module(), torch.fx.Graph()) + graph.graph.output(None) + graph.recompile() + fake_mode = None + + # ShapesSpec is unbacked based, constraint violations are not + # relevant. + if not shapes_spec_in_use: + _suggest_or_raise_constraint_violation( + module_to_trace, + orig_callable, + fake_mode, + out, + args, + kwargs, + dynamic_shapes, # type: ignore[arg-type] + ) + + # Extract export metadata from the new location + export_metadata = out.graph_capture_output.output_graph.export_metadata + graph_inputs = export_metadata.graph_input_idx_to_local_source + graph_output_map = export_metadata.output_return_type + out_spec = export_metadata.out_spec + module_call_spec = export_metadata.module_call_spec + + # Compute dynamic dimensions for each input based on constraints + flat_args_dynamic_dims = [ + { + c.dim + for c in (constraints or ()) + if ( + c.t_id == id(x) + and not isinstance(c, _RelaxedConstraint) + and c.constraint_range.vr.lower != c.constraint_range.vr.upper + ) + } + for x in flat_inputs + ] + + # Create input order mapping from dynamo's internal order to user order + # Only process inputs that come from function arguments (GetItemSource). + # Skip inputs that come from other sources like closures (e.g., captured + # opaque objects like DeviceMesh). + graph_input_order: dict[int, int] = {} + for inp in graph_inputs: + source = graph_inputs[inp] + if isinstance(source, torch._dynamo.source.GetItemSource): + graph_input_order[source.index] = len(graph_input_order) + + for real_idx, graph_idx in graph_input_order.items(): + flat_inputs[real_idx] = example_inputs[graph_idx] + + # Use FX transformer to rebuild the graph cleanly + transformed_graph = DynamoGraphTransformer( + graph, + flat_inputs, + flat_args_dynamic_dims, + graph_input_order, + graph_output_map, + fake_mode, + graph_inputs, + ).transform() + + # Set up PyTree codegen for proper input/output handling + transformed_graph.graph._codegen = _PyTreeCodeGen( + _PyTreeInfo( + argument_names(inspect.signature(orig_callable), args, kwargs), # type: ignore[attr-defined, arg-type] + in_spec, + out_spec, + ) + ) + transformed_graph.recompile() + + clean_nn_module_stack_and_source_fn(transformed_graph, True) + clean_export_root(transformed_graph) + + transformed_graph.meta["module_call_specs"] = module_call_spec + transformed_graph.meta["fake_mode"] = fake_mode + + return transformed_graph + + return inner diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_break_hints.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_break_hints.py new file mode 100644 index 0000000000000000000000000000000000000000..b04f37b3bbc48800cb96b896d5036b97c2ba0ca1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_break_hints.py @@ -0,0 +1,32 @@ +USER_ERROR = [ + "Your code may result in an error when running in eager. " + "Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. " + 'You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance("force_eager")`. ' +] +DYNAMO_BUG = [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch.", +] +DIFFICULT = [ + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance.", +] +FUNDAMENTAL = [ + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through " + "your code. Consider finding a workaround.", +] +SUPPORTABLE = [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you " + "encounter this graph break often and it is causing performance issues.", +] +CAUSED_BY_EARLIER_GRAPH_BREAK = [ + "This graph break may have been caused by an earlier graph break. Resolving the earlier graph break may resolve this one.", +] +INFERENCE_MODE = [ + "Avoid using `tensor.is_inference()` and `torch.is_inference_mode_enabled()` in your compile code. " + "This is primarily used in conjunction with `torch.inference_mode`. Consider using `torch.no_grad` instead " + "because `torch.no_grad` leads to same improvements as `inference_mode` when `torch.compile` is used.", +] +SPARSE_TENSOR = [ + "Sparse tensor operations are not yet fully supported in torch.compile with fullgraph=True. " + "Consider using fullgraph=False to allow graph breaks, or move sparse tensor creation " + "outside the compiled region.", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_break_registry.json b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_break_registry.json new file mode 100644 index 0000000000000000000000000000000000000000..bbfc54b899106b40990908625f6487467122c3da --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_break_registry.json @@ -0,0 +1,6431 @@ +{ + "GB0000": [ + { + "Gb_type": "All __torch_function__ overrides returned NotImplemented due to TypeError from user code", + "Context": "fn={fn}, args={args}, kwargs={kwargs}", + "Explanation": "All __torch_function__ overrides for function {fn} returned NotImplemented", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0001": [ + { + "Gb_type": "Argument of `as_subclass` must be a non-dispatcher-style tensor subclass", + "Context": "{self}.as_subclass({cls})", + "Explanation": "Currently not supported", + "Hints": [ + "Avoid this call or move it outside `torch.compile` region", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Argument of `as_subclass` must be a non-dispatcher-style tensor subclass", + "Context": "{self}.as_subclass({cls})", + "Explanation": "Currently not supported", + "Hints": [ + "Avoid this call or move it outside `torch.compile` regione", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0002": [ + { + "Gb_type": "Assertion failed on symbolic shapes", + "Context": "str(sym_expr)", + "Explanation": "", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0003": [ + { + "Gb_type": "Attempt to trace generator", + "Context": "", + "Explanation": "Generators cannot be compiled directly with `torch.compile`.", + "Hints": [ + "Call a generator from inside of a non-generator Python function and ", + "compile that function instead.", + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB0004": [ + { + "Gb_type": "Attempted super().__delattr__() on an object without mutation tracking", + "Context": "call_method {self} {name}", + "Explanation": "Dynamo needs to track mutations on an object before `super().__delattr__` can be used on it. But the object ({self.objvar}) doesn't have attribute mutation tracking enabled.", + "Hints": [ + "Ensure the object is tracked by Dynamo's side effect system.", + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB4774": [ + { + "Gb_type": "torch.map: f mutates pos_args", + "Context": "pos_args={pos_args_mutated}", + "Explanation": "map only supports in-place mutation of xs (each iteration sees a storage-disjoint slice). pos_args are loop-invariant: every iteration sees the same tensor, so a mutation makes iterations depend on each other, breaking map's independence contract and introducing a data race under any parallel lowering. Use scan or while_loop if sequential buffer updates are required.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB2861": [ + { + "Gb_type": "Untraceable C tp_hash", + "Context": "hash_impl {self}", + "Explanation": "{cls.__name__} defines a C __hash__ that Dynamo cannot trace into.", + "Hints": [ + "Use torch._dynamo.allow_c_slot({cls.__name__}) to ", + "register it as safe if its slots are pure and ", + "deterministic.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Untraceable C tp_hash", + "Context": "hash_impl {self}", + "Explanation": "{cls.__name__} defines a C __hash__ that Dynamo cannot trace into.", + "Hints": [ + "Use torch._dynamo.allow_c_hash({cls.__name__}) to ", + "register it as safe if its __hash__ is pure and ", + "deterministic.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Untraceable C tp_hash", + "Context": "hash_impl {self}", + "Explanation": "{cls.__name__} defines a C __hash__ that Dynamo cannot trace into.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0005": [ + { + "Gb_type": "Attempted to a str() method implemented in C/C++", + "Context": "", + "Explanation": "{type(arg.value)} has a C/C++ based str method. This is not supported.", + "Hints": [ + "Write the str method in Python" + ] + } + ], + "GB0006": [ + { + "Gb_type": "Attempted to call a super() attribute that is not a function or method", + "Context": "call_method {self} {name}", + "Explanation": "Dynamo does not know how to trace the call `super().{name}()` because `super().{name}` is not a function or method attribute.", + "Hints": [ + "Ensure the attribute accessed via `super()` is a standard method or function." + ] + } + ], + "GB0007": [ + { + "Gb_type": "Attempted to call function marked as skipped", + "Context": "module: {module_name}, qualname: {qualname}, skip reason: {reason}", + "Explanation": "explanation", + "Hints": [] + } + ], + "GB0008": [ + { + "Gb_type": "Attempted to inline function marked as skipped", + "Context": "qualname: {fn_qualname}, name: {func.get_name()}, filename: `{func.get_filename()}`, skip reason: {result.reason}", + "Explanation": "Dynamo developers have intentionally marked that the function `{fn_qualname}` should not be traced.", + "Hints": [] + } + ], + "GB0009": [ + { + "Gb_type": "Attempted to inline function marked as skipped (SkipFunctionVariable)", + "Context": "Attempted to inline a SkipFunctionVariable {func}", + "Explanation": "Attempted to inline a function that was previously determined to be marked as intentionally skipped.", + "Hints": [] + } + ], + "GB0010": [ + { + "Gb_type": "Attempted to read a deleted variable", + "Context": "item: {item}, name: {name}", + "Explanation": "", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0871": [ + { + "Gb_type": "Non-constant __hash__ return", + "Context": "hash_impl {self}", + "Explanation": "__hash__ returned a non-constant {type(result).__name__}.", + "Hints": [ + "Ensure that your custom __hash__ function returns an integer.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0011": [ + { + "Gb_type": "Attempted to read undefined local variable", + "Context": "LOAD_FAST {name}", + "Explanation": "Could not find a local variable with name `{name}`", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB2019": [ + { + "Gb_type": "Unsupported autograd.Function context `mark_dirty`", + "Context": "call_method {self} {name}", + "Explanation": "Dynamo only supports tracing ctx.mark_dirty inside autograd.Function.apply.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0012": [ + { + "Gb_type": "Attempted to read undefined local variable (implicit)", + "Context": "LOAD_FAST {name}", + "Explanation": "Could not find an implicit local variable with name `{name}`", + "Hints": [ + "This happens in dict/list comprehensions", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0013": [ + { + "Gb_type": "Attempted to represent unregistered RemovableHandle", + "Context": "", + "Explanation": "Dynamo attempted to build a representation of a torch.utils.hooks.RemovableHandle, which is not supported. This happens because the RemovableHandle was created in another frame.", + "Hints": [] + } + ], + "GB0014": [ + { + "Gb_type": "Attempted to wrap RNN, GRU, or LSTM", + "Context": "str(value)", + "Explanation": "Dynamo does not support RNN, GRU, or LSTM.", + "Hints": [ + "Set torch._dynamo.config.allow_rnn=True to enable experimental support for RNN, GRU, and LSTM in Dynamo", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Attempted to wrap RNN, GRU, or LSTM", + "Context": "str(value)", + "Explanation": "Dynamo does not support RNN, GRU, or LSTM.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0015": [ + { + "Gb_type": "Attempted to wrap sparse Tensor", + "Context": "", + "Explanation": "torch.compile does not support sparse Tensors", + "Hints": [ + "Sparse tensor operations are not yet fully supported in torch.compile with fullgraph=True. Consider using fullgraph=False to allow graph breaks, or move sparse tensor creation outside the compiled region." + ] + } + ], + "GB0016": [ + { + "Gb_type": "Attempted to wrap strided NestedTensor", + "Context": "", + "Explanation": "torch.compile does not support strided NestedTensor", + "Hints": [] + } + ], + "GB0017": [ + { + "Gb_type": "Attempted to wrap torch._higher_order_ops.invoke_subgraph", + "Context": "", + "Explanation": "Directly using invoke_subgraph is not supported. Use nested_compile_region", + "Hints": [] + } + ], + "GB0018": [ + { + "Gb_type": "Attempted to wrap unbacked SymInt", + "Context": "", + "Explanation": "Unbacked SymInt input is not supported yet.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0019": [ + { + "Gb_type": "AutogradFunctionContextVariable escaped Dynamo-traced region", + "Context": "", + "Explanation": "We cannot reconstruct a torch.autograd.Function's context object.", + "Hints": [] + } + ], + "GB0020": [ + { + "Gb_type": "BUILD_STRING key conflict", + "Context": "format_string_parts: {format_string_parts}, kwargs: {kwargs}, part.sym_kwargs: {part.sym_kwargs}", + "Explanation": "Failed to build format string due to key conflict", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0021": [ + { + "Gb_type": "BUILD_STRING type error", + "Context": "str(part)", + "Explanation": "Format string part type is not correct - expected constant or format string.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0022": [ + { + "Gb_type": "Bad import result", + "Context": "typestr(value)", + "Explanation": "Import result is not a Python module.", + "Hints": [] + } + ], + "GB1273": [ + { + "Gb_type": "Unsupported attribute assignment on traceback object", + "Context": "call_setattr {self} {attr}", + "Explanation": "Dynamo does not support setting the attribute '{attr}' on tracked traceback objects. Only `tb_next` is supported.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0023": [ + { + "Gb_type": "Builtin `operator.*` comparison with constant `self` failed", + "Context": "call_method {self} {name} {args} {kwargs}", + "Explanation": "\"Failed to compare {self} with {other}, \" + f\"because {other} is not a Python constant or its mutation check fails.\"", + "Hints": [] + } + ], + "GB0024": [ + { + "Gb_type": "CLEANUP_THROW with StopIteration", + "Context": "", + "Explanation": "Received StopIteration when handling generator.throw/close. This is not supported.", + "Hints": [] + } + ], + "GB0025": [ + { + "Gb_type": "Call to `torch._dynamo.graph_break()`", + "Context": "Called `torch._dynamo.graph_break()` with args `{args}`, kwargs `{kwargs}`", + "Explanation": "User-inserted graph break. Message: {graph_break_msg}", + "Hints": [ + "Remove the `torch._dynamo.graph_break()` call." + ] + } + ], + "GB7054": [ + { + "Gb_type": "backward() with non-leaf tensor", + "Context": "backward(inputs=[...]) with non-leaf tensor: {var}", + "Explanation": "backward(inputs=[...]) with non-leaf tensors is not yet supported.", + "Hints": [ + "Only pass leaf tensors (parameters, graph inputs) to backward(inputs=...)" + ] + }, + { + "Gb_type": "backward() with non-leaf tensor", + "Context": "backward(inputs=[...]) with non-leaf tensor", + "Explanation": "backward(inputs=[...]) with non-leaf tensors is not yet supported.", + "Hints": [ + "Only pass leaf tensors (parameters, graph inputs) to backward(inputs=...)" + ] + } + ], + "GB0026": [ + { + "Gb_type": "Calling subclass default constructor with more than tensor argument", + "Context": "{self.value}(args={args}, kwargs={kwargs})", + "Explanation": "Currently not supported", + "Hints": [ + "Avoid this constructor call or move it outside ", + "`torch.compile` region", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Calling subclass default constructor with more than tensor argument", + "Context": "{self.value}(args={args}, kwargs={kwargs})", + "Explanation": "Currently not supported", + "Hints": [ + "Avoid this constructor call or move it outside ", + "`torch.compile` regione", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0027": [ + { + "Gb_type": "Cannot check Tensor object identity without its fake value", + "Context": "str(fake_tensor)", + "Explanation": "TensorVariable is missing a fake example_value.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0028": [ + { + "Gb_type": "Caught non-Exception value", + "Context": "str(exc_instance)", + "Explanation": "Except expects to receive an object of Exception type but received {exc_instance}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0029": [ + { + "Gb_type": "Compilation of intermediate hooks requires compiled autograd", + "Context": "var_getattr {self} {name}", + "Explanation": "Dynamo must be in compiled_autograd to register hooks.", + "Hints": [ + "Consider using torch.autograd.Function with a custom backward() method instead of register_hook()." + ] + } + ], + "GB0030": [ + { + "Gb_type": "ComptimeContext graph break", + "Context": "msg", + "Explanation": "Manually triggered ComptimeContext graph break with message {msg}.", + "Hints": [] + } + ], + "GB0031": [ + { + "Gb_type": "Custom __getattribute__ in nn.Module attribute access", + "Context": "tp_getattro_impl {self} {name}", + "Explanation": "Dynamo could not trace through the custom `__getattribute__` method on this `nn.Module`.", + "Hints": [ + "Simplify your `__getattribute__` implementation, ", + "or replace it with a targeted `@property`.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Custom __getattribute__ in nn.Module attribute access", + "Context": "getattro_impl {self} {name}", + "Explanation": "Dynamo could not trace through the custom `__getattribute__` method on this `nn.Module`.", + "Hints": [ + "Simplify your `__getattribute__` implementation, ", + "or replace it with a targeted `@property`.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Custom __getattribute__ in nn.Module attribute access", + "Context": "var_getattr {self} {name}", + "Explanation": "Dynamo could not trace through the custom `__getattribute__` method on this `nn.Module`.", + "Hints": [ + "Simplify your `__getattribute__` implementation, ", + "or replace it with a targeted `@property`.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Custom __getattribute__ in nn.Module attribute access", + "Context": "var_getattr {self} {name}", + "Explanation": "Dynamo does not support checking key existence on `nn.Module` instances that have a custom `__getattribute__` method defined.", + "Hints": [ + "Avoid defining `__getattribute__` in your module.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0032": [ + { + "Gb_type": "Custom __getattribute__ in nn.Module dict key check", + "Context": "has_key_in_generic_dict {self} {key}", + "Explanation": "Dynamo does not support checking key existence on `nn.Module` instances that have a custom `__getattribute__` method defined.", + "Hints": [ + "Avoid defining `__getattribute__` in your module.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0033": [ + { + "Gb_type": "Data dependent operator", + "Context": "str(cause.func)", + "Explanation": "Operator `{cause.func}` has a non-Tensor output whose value is dependent on the data of Tensor inputs.", + "Hints": [] + } + ], + "GB0034": [ + { + "Gb_type": "Data-dependent assertion failed (cannot compile partial graph)", + "Context": "value: {value}", + "Explanation": "Dynamo has determined when encountering a data-dependent assert failure that it should not compile the partial graph.", + "Hints": [ + "Use `torch._assert()` to raise a hard AssertionError when the check fails. ", + "This error will propagate back the user code ", + "that called the compiled function (i.e. Dynamo will not trace any exception handling).", + "Remove the assert statement.", + "Move the assert statement outside of any context managers in order to graph break with ", + "partial graph compilation (if fullgraph=False).", + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB0035": [ + { + "Gb_type": "Data-dependent branching with non-constant __bool__", + "Context": "value: {value}, result: {result}", + "Explanation": "Attempted to perform data-dependent branching on a user-defined object with non-constant truthiness.", + "Hints": [] + }, + { + "Gb_type": "Data-dependent branching with non-constant __bool__", + "Context": "method: {x}, result: {result}", + "Explanation": "Attempted to perform data-dependent branching on a user-defined object with a __bool__ method that did not return a constant.", + "Hints": [] + } + ], + "GB0036": [ + { + "Gb_type": "Dynamic shape operator", + "Context": "str(cause.func)", + "Explanation": "Operator `{cause.func}`'s output shape depends on input Tensor data.", + "Hints": [ + "Enable tracing of dynamic shape operators with ", + "`torch._dynamo.config.capture_dynamic_output_shape_ops = True`" + ] + } + ], + "GB6999": [ + { + "Gb_type": "unsupported variable type for __dict__ access", + "Context": "VariableTracker type: {type(vt)}", + "Explanation": "Dynamo does not know how to get __dict__ from {type(vt)}", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB2444": [ + { + "Gb_type": "MAKE_CELL on a free variable name", + "Context": "MAKE_CELL {inst.argval}", + "Explanation": "An inlined comprehension creates a cell whose name `{inst.argval}` is also a free variable of the enclosing function.", + "Hints": [ + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance." + ] + } + ], + "GB0037": [ + { + "Gb_type": "Dynamic shape operator (no meta kernel)", + "Context": "str(cause.func)", + "Explanation": "Operator `{cause.func}` does not have a meta kernel that supports dynamic output shapes", + "Hints": [ + "Please report an issue to PyTorch" + ] + } + ], + "GB0038": [ + { + "Gb_type": "Dynamic slicing with Tensor arguments", + "Context": "SliceVariable start: {start}, stop: {stop}, step: {step}", + "Explanation": "Creating slices with Tensor arguments is not supported. e.g. `l[:x]`, where `x` is a 1-element tensor.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0039": [ + { + "Gb_type": "Dynamo recompile limit exceeded", + "Context": "Limit type: {limit_type}", + "Explanation": "Dynamo attempted to recompile the code object too many times, exceeding the {limit_type} cache size limit (currently set to {getattr(config, limit_type)}). Excessive recompilations can degrade performance due to the compilation overhead of each recompilation.", + "Hints": [ + "To monitor recompilations, enable TORCH_LOGS=recompiles. ", + "If recompilations are expected, consider ", + "increasing torch._dynamo.config.{limit_type} to an appropriate value.", + "See {troubleshooting_url} for tips on dealing with recompilations." + ] + }, + { + "Gb_type": "Dynamo cache limit exceeded", + "Context": "Limit type: {limit_type}", + "Explanation": "Dynamo attempted to recompile the code object too many times, exceeding the {limit_type} cache size limit.Giving up on compiling as the compile time tradeoff is likely not worth the performance gain.", + "Hints": [] + } + ], + "GB0040": [ + { + "Gb_type": "Encountered aliasing during higher order op tracing", + "Context": "context", + "Explanation": "Higher order ops do not support aliasing. Found in {name}", + "Hints": [ + "Replace `return input` with `return input.clone()` to avoid aliasing.", + "Consider using the debug context to change user code to avoid aliasing.", + "Please open an issue." + ] + }, + { + "Gb_type": "Encountered aliasing during higher order op tracing", + "Context": "context", + "Explanation": "Higher order ops do not support aliasing. Found in {source_target.name}", + "Hints": [ + "Replace `return input` with `return input.clone()` to avoid aliasing.", + "Consider using the debug context to change user code to avoid aliasing.", + "Please open an issue." + ] + } + ], + "GB0041": [ + { + "Gb_type": "Encountered input mutation during higher order op tracing", + "Context": "context", + "Explanation": "Higher order ops do not support input mutation. Found in {name}", + "Hints": [ + "Consider using the debug context to change user code to avoid mutation.", + "Please open an issue." + ] + }, + { + "Gb_type": "Encountered input mutation during higher order op tracing", + "Context": "context", + "Explanation": "Higher order ops do not support input mutation. Found in {source_target.name}", + "Hints": [ + "Consider using the debug context to change user code to avoid mutation.", + "Please open an issue." + ] + } + ], + "GB0042": [ + { + "Gb_type": "Encountered non user function variable during invoke_subgraph HOP tracing", + "Context": "str(fn_vt)", + "Explanation": "invoke_subgraph does not support non user function variable", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0043": [ + { + "Gb_type": "Encountered non-PT2-compliant op", + "Context": "", + "Explanation": "msg + + err_epilogue", + "Hints": [] + } + ], + "GB0044": [ + { + "Gb_type": "Encountered strided NestedTensor in automatic dynamic dim determination", + "Context": "", + "Explanation": "torch.compile does not support strided NestedTensor", + "Hints": [] + } + ], + "GB0045": [ + { + "Gb_type": "Encountered tensor.is_inference() during tracing", + "Context": "", + "Explanation": "tensor.is_inference() is not supported", + "Hints": [ + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB0046": [ + { + "Gb_type": "Encountered torch.is_inference_mode_enabled during tracing", + "Context": "", + "Explanation": "torch.is_inference_mode_enabled() is not supported", + "Hints": [ + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB0047": [ + { + "Gb_type": "Encountered unconverted argument when attempting to inline", + "Context": "func: {func}, arg: {v}", + "Explanation": "An argument to an inlined function was not successfully converted to a VariableTracker.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB5696": [ + { + "Gb_type": "Comprehension graph break with extra stack values", + "Context": "", + "Explanation": "Cannot use comprehension optimization when there are extra values on the stack and variables need to be passed to the resume function.", + "Hints": [] + } + ], + "GB0048": [ + { + "Gb_type": "Error getting associated real value", + "Context": "call_id {self}", + "Explanation": "Dynamo encountered an error while trying to get the associated real value.", + "Hints": [] + } + ], + "GB0049": [ + { + "Gb_type": "Error when attempting to resolve op packet", + "Context": "", + "Explanation": "str(e)", + "Hints": [] + } + ], + "GB0050": [ + { + "Gb_type": "Exception with bad expected type", + "Context": "str(expected_exc_types)", + "Explanation": "`except ...` has unsupported type {expected_exc_types}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB4880": [ + { + "Gb_type": "missing_mp_subscript", + "Context": "mp_subscript_impl not defined for {type(self).__name__}", + "Explanation": "Dynamo does not yet support subscripting '{self.python_type_name()}'.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB9741": [ + { + "Gb_type": "skip frame due to being in functorh mode", + "Context": "", + "Explanation": "torch.compile cannot be run in context: {functorch_subclass_name}. Skipping frame.", + "Hints": [] + }, + { + "Gb_type": "skip frame due to being in functorch mode", + "Context": "", + "Explanation": "torch.compile cannot be run in context: {functorch_subclass_name}. Skipping frame.", + "Hints": [] + } + ], + "GB7000": [ + { + "Gb_type": "graph break in loop", + "Context": "frame skipped: {format_frame_info(code)}", + "Explanation": "torch.compile detected a graph break in a for/while loop. Skipping the frame and falling back to eager, as graph breaks in loops are not supported.", + "Hints": [ + "This graph break may have been caused by an earlier graph break. Resolving the earlier graph break may resolve this one." + ] + } + ], + "GB3326": [ + { + "Gb_type": "invalid ptr argument for create_tma_descriptor", + "Context": "args = {args}, kwargs = {kwargs}", + "Explanation": "Expected `ptr` argument of `create_{self.rank}d_tma_descriptor`to be from a `.data_ptr()` call, represented internally by `DataPtrVariable`", + "Hints": [ + "`torch.compile` may fail to internally represent result of `.data_ptr()` ", + "with `DataPtrVariable` due to a graph break between the `.data_ptr()` call and ", + "`create_{self.rank}d_tma_descriptor`. Please ensure there were no graph breaks ", + "between these two calls." + ] + } + ], + "GB4297": [ + { + "Gb_type": "Call to `torch._dynamo.skip_frame()`", + "Context": "Called `torch._dynamo.skip_frame()` with args `{args}`, kwargs `{kwargs}`. Skipping frame {format_frame_info(tx.f_code)}.", + "Explanation": "User-inserted skip frame. Message: {skip_frame_msg}", + "Hints": [ + "Remove the `torch._dynamo.skip_frame()` call." + ] + } + ], + "GB0051": [ + { + "Gb_type": "Exception with non-type expectation", + "Context": "str(expected_type)", + "Explanation": "`except ...` expects a non-type: {expected_type}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0052": [ + { + "Gb_type": "Excessive RestartAnalysis() calls", + "Context": "", + "Explanation": "Dynamo attempted to trace the same frame 100+ times. Giving up on compiling as the compile time tradeoff is likely not worth the performance gain.", + "Hints": [] + } + ], + "GB8593": [ + { + "Gb_type": "flex_gemm: unexpected kwargs", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "flex_gemm internal HOP expects positional args only.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB7072": [ + { + "Gb_type": "flex_gemm: improper args/kwargs", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "flex_gemm expects 5 positional arguments: gemm_op, body_fn, args, kwargs, kernel_options. args is expected to be list/tuple and kwargs/kernel_options are expected to be dicts.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0053": [ + { + "Gb_type": "FSDP with use_orig_params=False", + "Context": "", + "Explanation": "Dynamo only supports FSDP with use_orig_params=True", + "Hints": [] + } + ], + "GB5195": [ + { + "Gb_type": "elementwise_dtypes unsupported arg type", + "Context": "str(arg)", + "Explanation": "elementwise_dtypes requires tensor or constant arguments, got {type(arg).__name__}", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0054": [ + { + "Gb_type": "Failed to construct Enum variable", + "Context": "value: {value_vt}, allowed enum values: {list(cls_type)}", + "Explanation": "Attempted to construct an Enum value that is non-constant (e.g. int, string) or is not an acceptable value for the Enum. Acceptable values for Enum `{cls_type}`: {list(cls_type)}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0055": [ + { + "Gb_type": "Failed to convert args/kwargs to proxy", + "Context": "call_function args: {typestr(*args)} {typestr(*list(kwargs.values()))}", + "Explanation": "Missing `as_proxy()` implementation for some arg/kwarg.", + "Hints": [] + } + ], + "GB0056": [ + { + "Gb_type": "Failed to mutate tensor data attribute", + "Context": "setattr({obj}, {name}, {val})", + "Explanation": "Dynamo only supports mutating `.data` of tensor created outside `torch.compile` region", + "Hints": [ + "Don't mutate `.data` on this tensor, or move ", + "the mutation out of `torch.compile` region" + ] + }, + { + "Gb_type": "Failed to mutate tensor data attribute", + "Context": "setattr({obj}, {name}, {val})", + "Explanation": "Dynamo only supports mutating `.data` of tensor created outside `torch.compile` region", + "Hints": [ + "Don't mutate `.data` on this tensor, or move ", + "the mutation out of `torch.compile` region" + ] + } + ], + "GB0057": [ + { + "Gb_type": "Failed to raise exception", + "Context": "str(exc)", + "Explanation": "Attempted to raise a non-Exception type/value.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB7299": [ + { + "Gb_type": "_autograd_grad with lost grad_fn linkage", + "Context": "outputs lost autograd linkage during tracing", + "Explanation": "_autograd_grad() received tensors whose grad_fn was lost during tracing - this silently produces zero gradients.", + "Hints": [ + "Compile the full transform instead of the returned ", + "closure: torch.compile(lambda x: torch.func.vjp(f, x))", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0058": [ + { + "Gb_type": "Failed to set tensor attribute", + "Context": "setattr({obj}, {name}, {val})", + "Explanation": "Dynamo doesn't support setting these tensor attributes", + "Hints": [ + "Don't mutate attribute '{name}' on tensors, or ", + "move the mutation out of `torch.compile` region" + ] + }, + { + "Gb_type": "Failed to set tensor attribute", + "Context": "setattr({obj}, {name}, {val})", + "Explanation": "Dynamo doesn't support setting these tensor attributes", + "Hints": [ + "Don't mutate attribute '{name}' on tensors, or ", + "move the mutation out of `torch.compile` region" + ] + } + ], + "GB0059": [ + { + "Gb_type": "Failed to trace builtin operator", + "Context": "builtin {fn.__name__} {arg_types} {has_kwargs}", + "Explanation": "Dynamo does not know how to trace builtin operator `{fn.__name__}` with argument types {real_arg_types} (has_kwargs {has_kwargs})", + "Hints": [ + "Avoid calling builtin `{fn.__name__}` with argument types {real_arg_types}. ", + "Consider using an equivalent alternative function/method to `{fn.__name__}`.", + "If you are attempting to call a logging function (e.g. `print`), ", + "you can try adding it to `torch._dynamo.config.reorderable_logging_functions`.", + "Please report an issue to PyTorch." + ] + } + ], + "GB6270": [ + { + "Gb_type": "Unhandled tensor method", + "Context": "call_method {self} {name} {args} {kwargs}", + "Explanation": "Tensor method `{name}` is not defined on {check_type.__name__} and does not have an explicit handler in TensorVariable.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB8656": [ + { + "Gb_type": "Opaque object with custom __getattr__ not supported", + "Context": "{real_obj_type.__name__} with custom __getattr__", + "Explanation": "Dynamo does not support opaque objects types with custom __getattr__ methods", + "Hints": [] + } + ], + "GB0061": [ + { + "Gb_type": "Failed to unpack object for BUILD_LIST_UNPACK", + "Context": "str(seq)", + "Explanation": "{seq} cannot be unpacked into a list for the BUILD_LIST_UNPACK bytecode (`[*x, *y, ...]`).", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB4197": [ + { + "Gb_type": "Unsupported Tensor.share_memory_() call", + "Context": "call_method {self} share_memory_", + "Explanation": "Dynamo does not support Tensor.share_memory_() which modifies tensor storage for IPC", + "Hints": [ + "Move share_memory_() call outside the compiled region. ", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0062": [ + { + "Gb_type": "Failed to unpack object for UNPACK_EX", + "Context": "str(seq)", + "Explanation": "{seq} cannot be unpacked into a list for the UNPACK_EX bytecode.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0063": [ + { + "Gb_type": "Failed to unpack object for UNPACK_SEQUENCE", + "Context": "str(seq)", + "Explanation": "{seq} cannot be unpacked into a list for the UNPACK_SEQUENCE bytecode (i.e. `a, b, c = d`).", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0064": [ + { + "Gb_type": "Fake tensor propagation exception", + "Context": "str(e.reason)", + "Explanation": "msg", + "Hints": [] + } + ], + "GB2736": [ + { + "Gb_type": "builtin isinstance() with custom type check on tensor", + "Context": "isinstance({arg}, {isinstance_type})", + "Explanation": "Dynamo cannot soundly trace arbitrary custom __instancecheck__ or __subclasscheck__ hooks on tensor values because the hook may read external mutable state.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB4636": [ + { + "Gb_type": "Call to `torch._dynamo.step_unsupported()`", + "Context": "", + "Explanation": "User-inserted step_unsupported.", + "Hints": [ + "Remove the `torch._dynamo.step_unsupported()` call." + ] + } + ], + "GB0065": [ + { + "Gb_type": "Graph break in inlined function", + "Context": "", + "Explanation": "Graph breaks in an inlined call are not supported.", + "Hints": [] + } + ], + "GB0066": [ + { + "Gb_type": "Graph break under GenericContextWrappingVariable", + "Context": "Active generic context managers: {self.active_generic_context_managers}", + "Explanation": "Attempted to graph break in an active context manager(s) that doesn't support graph breaking.", + "Hints": [ + "Move the offending context manager(s) to outside the compiled region.", + "This graph break may have been caused by an earlier graph break. Resolving the earlier graph break may resolve this one." + ] + } + ], + "GB0067": [ + { + "Gb_type": "HOP: Unsafe side effect", + "Context": "Attempted to mutate {item}", + "Explanation": "Mutating a variable from outside the scope of this HOP is not supported.", + "Hints": [ + "If the HOP is activation checkpointing (torch.utils.checkpoint.checkpoint), this points to a ", + "side effect in forward method. Eager activation checkpointing replays that side-effect while ", + "recomputing the forward in the backward. If you are ok with side-effect not replayed in the ", + "backward, try setting `torch._dynamo.config.skip_fwd_side_effects_in_bwd_under_checkpoint = True`" + ] + }, + { + "Gb_type": "HOP: Unsafe side effect", + "Context": "Attempted to mutate {item}", + "Explanation": "Mutating a variable from outside the scope of this HOP is not supported.", + "Hints": [ + "If the HOP is activation checkpointing, try setting ", + "`torch._dynamo.config.skip_fwd_side_effects_in_bwd_under_checkpoint = True`" + ] + }, + { + "Gb_type": "HigherOrderOperator: Mutating a variable not in the current scope (SideEffects)", + "Context": "", + "Explanation": "This is not supported.", + "Hints": [] + } + ], + "GB9493": [ + { + "Gb_type": "C-implemented special method without VariableTracker model", + "Context": "name={name}, type={self.python_type_name()}, attr={type_attr}", + "Explanation": "'{self.python_type_name()}' implements '{name}' in C and Dynamo has no model for it.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0068": [ + { + "Gb_type": "Illegal method invocation in strict mode", + "Context": "call_method {self} {name} {args} {kwargs}", + "Explanation": "Dynamo currently does not support this method ({name}) invocation in strict mode.", + "Hints": [] + } + ], + "GB0069": [ + { + "Gb_type": "Import failure", + "Context": "module_name: {module_name}, fromlist: {fromlist}, level={level}", + "Explanation": "Failure when attempting to import.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0070": [ + { + "Gb_type": "Indexing list with non-scalar tensor", + "Context": "call_method {self} {name} {args} {kwargs}", + "Explanation": "Attempted to index list-like object with tensor with > 1 element.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0071": [ + { + "Gb_type": "Inline attempt with __self__", + "Context": "str(func)", + "Explanation": "Attempted to inline a function with the `__self__` attribute. Dynamo is expected to decompose method calls into function calls with a `self` argument.", + "Hints": [] + } + ], + "GB0072": [ + { + "Gb_type": "Inplace op on input tensor", + "Context": "", + "Explanation": "Attempted to trace an inplace view op on input tensor {typestr(self.value)}.", + "Hints": [ + "Ensure you do not modify input tensor in place.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB7230": [ + { + "Gb_type": "iter() with no arguments", + "Context": "iter()", + "Explanation": "iter() requires at least one argument", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + }, + { + "Gb_type": "iter() with no arguments", + "Context": "iter()", + "Explanation": "iter() requires at least one argument", + "Hints": [] + } + ], + "GB0073": [ + { + "Gb_type": "Invoking an nn.Module inside a HigherOrderOperator", + "Context": "", + "Explanation": "This is not supported.", + "Hints": [] + } + ], + "GB0074": [ + { + "Gb_type": "Invoking an nn.Module inside a higher order operator", + "Context": "Higher order op name: {self.source_target}", + "Explanation": "This is not supported.", + "Hints": [] + } + ], + "GB2069": [ + { + "Gb_type": "Comprehension analysis failed: ambiguous result store", + "Context": "store_targets={store_targets}, iterator_vars={iterator_vars}", + "Explanation": "Expected exactly one comprehension result assignment.", + "Hints": [] + } + ], + "GB6012": [ + { + "Gb_type": "Cannot trace user-defined __len__", + "Context": "{self.python_type_name()}.__len__()", + "Explanation": "Dynamo cannot trace len() on {self.python_type_name()} because the __len__ method is either not traceable (e.g., defined in C or built-in) or returns a non-constant value.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0075": [ + { + "Gb_type": "LOAD_BUILD_CLASS bytecode not supported", + "Context": "", + "Explanation": "Dynamo does not support tracing classes that are defined in the compiled region.", + "Hints": [ + "Move the class definition out of the compiled region or set `torch._dynamo.config.enable_trace_load_build_class=True`.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0076": [ + { + "Gb_type": "LOAD_FAST_CHECK on uninitialized variable", + "Context": "inst.argval", + "Explanation": "Attempted to load uninitialized local variable {inst.argval}", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0077": [ + { + "Gb_type": "Length mismatch when unpacking object for UNPACK_SEQUENCE", + "Context": "expected length: {inst.argval}, actual: {len(val)}", + "Explanation": "{seq} unpacked to a list for the UNPACK_SEQUENCE bytecode (i.e. `a, b, c = d`) with unexpected length.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0078": [ + { + "Gb_type": "Limitation of `nonstrict_trace", + "Context": "{self}", + "Explanation": "msg", + "Hints": [ + "make sure definition of {fn_name} is outside ", + "`torch.compile` region" + ] + } + ], + "GB3775": [ + { + "Gb_type": "nb_int_impl not implemented", + "Context": "{type(self).__name__} has nb_int slot but no nb_int_impl override", + "Explanation": "The type {self.python_type_name()} has an nb_int C slot but the corresponding VariableTracker doesn't implement nb_int_impl.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0079": [ + { + "Gb_type": "Missing CALL_INTRINSIC_1 handler", + "Context": "CALL_INTRINSIC_1 operand: {inst.argval}", + "Explanation": "No handler implemented for CALL_INTRINSIC_1 {inst.argval} instruction.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0755": [ + { + "Gb_type": "nb_negative_impl not implemented", + "Context": "{type(self).__name__} has nb_negative slot but no nb_negative_impl override", + "Explanation": "The type {self.python_type_name()} has an nb_negative C slot but the corresponding VariableTracker doesn't implement nb_negative_impl.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB7596": [ + { + "Gb_type": "Indexing torch.Size with non-scalar tensor", + "Context": "get_item_dyn {self} {arg}", + "Explanation": "Attempted to index torch.Size with a tensor that is not a scalar constant.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0080": [ + { + "Gb_type": "Missing FakeTensor example value", + "Context": "str(node)", + "Explanation": "`FakeTensor` example value was required for {node} but not available.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0081": [ + { + "Gb_type": "Missing attribute when running call_method node", + "Context": "", + "Explanation": "make_error_message(\"attribute not defined\")", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + }, + { + "Gb_type": "Missing attribute when running call_method node", + "Context": "", + "Explanation": "make_error_message(\"attribute not defined\")", + "Hints": [] + } + ], + "GB0082": [ + { + "Gb_type": "Missing bytecode handler", + "Context": "{opname} with args {args}", + "Explanation": "Dynamo does not know how to handle the bytecode instruction `{opname}`.", + "Hints": [ + "Do not trace code that produces the `{opname}` bytecode instruction ", + "(see https://docs.python.org/3/library/dis.html for bytecode semantics).", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0083": [ + { + "Gb_type": "Module-level backwards hooks require compiled autograd.", + "Context": "", + "Explanation": "", + "Hints": [ + "Enable compiled autograd by setting torch._dynamo.config.compiled_autograd = True." + ] + } + ], + "GB0084": [ + { + "Gb_type": "Non-constant attribute given to `super().__delattr__()`", + "Context": "call_method {self} {name}", + "Explanation": "Dynamo requires the attribute name passed to `super().__delattr__(...)` to be a constant (string).", + "Hints": [ + "Ensure the attribute name is a string literal or a constant variable." + ] + } + ], + "GB0085": [ + { + "Gb_type": "Non-function or method in subclass of torch.autograd.Function", + "Context": "call_apply {self} {args} {kwargs}", + "Explanation": "Dynamo requires the `forward` attribute of a `torch.autograd.Function` subclass to be a standard Python function or method. Found type `{type(fn).__name__}` instead.", + "Hints": [ + "Ensure the `forward` method is defined as a regular ", + "function or instance method." + ] + } + ], + "GB0086": [ + { + "Gb_type": "Not a Python constant", + "Context": "guard_as_python_constant {self}", + "Explanation": "Failed to convert {self} into a Python constant.", + "Hints": [] + } + ], + "GB0087": [ + { + "Gb_type": "NotImplementedError/UnsupportedFakeTensorException when running FX node", + "Context": "", + "Explanation": "make_error_message(e)", + "Hints": [] + } + ], + "GB0088": [ + { + "Gb_type": "Observed exception", + "Context": "raised exception {curr_exc.debug_repr()}", + "Explanation": "observed_exn_gb_explanation", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + }, + { + "Gb_type": "Observed exception", + "Context": "raised exception {curr_exc.python_type_name()}({curr_exc.args})", + "Explanation": "observed_exn_gb_explanation", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0089": [ + { + "Gb_type": "Observed exception (EXCEPT_HANDLER)", + "Context": "str(raised_exception)", + "Explanation": "observed_exn_gb_explanation + \" This graph break is unexpected.\"", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0090": [ + { + "Gb_type": "Operator does not support running with fake tensors", + "Context": "unsupported operator: {cause.func}", + "Explanation": "", + "Hints": [ + "{import_suggestion}see ", + "https://docs.google.com/document/d/1GgvOe7C8_NVOMLOCwDaYV1mXXyHMXY7ExoewHqooxrs/edit#heading=h.64r4npvq0w0", + " for how to fix" + ] + } + ], + "GB0091": [ + { + "Gb_type": "Read uninitialized cell", + "Context": "str(cellvar)", + "Explanation": "Attempted to read a cell variable that has not been populated yet.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0092": [ + { + "Gb_type": "Reconstruction failure", + "Context": "str(value)", + "Explanation": "Dynamo has no bytecode reconstruction implemented for sourceless variable {value}.", + "Hints": [ + "If Dynamo is attempting to trace a return statement and your code is attempting to return a variable ", + "that Dynamo cannot reconstruct, then remove it from the return statement.", + "Report an issue to PyTorch if you need reconstrtuction support. Note that objects that don't have ", + "reconstruction rules may be fundamentally unreconstructable.", + "This graph break may have been caused by an earlier graph break. Resolving the earlier graph break may resolve this one." + ] + } + ], + "GB0093": [ + { + "Gb_type": "Reconstruction failure: source.reconstruct not implemented", + "Context": "str(source)", + "Explanation": "Dynamo has no bytecode reconstruction implemented for {type(source)} variable {source}.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0094": [ + { + "Gb_type": "SEND with bad type", + "Context": "TOS type: {typestr(receiver)}", + "Explanation": "Attempted to SEND with unsupported type {typestr(receiver)}.", + "Hints": [] + }, + { + "Gb_type": "SEND with bad type", + "Context": "TOS type: {typestr(tos)}", + "Explanation": "Attempted to SEND with unsupported type {typestr(tos)}.", + "Hints": [] + } + ], + "GB0095": [ + { + "Gb_type": "Set Exception object `__traceback__` attribute to not-`None`", + "Context": "call_setattr {self} {name}", + "Explanation": "Dynamo does not support setting the attribute '__traceback__' on tracked exception objects to anything other than None.", + "Hints": [ + "Avoid setting '__traceback__' on exception objects ", + "within traced code, or set it to None." + ] + } + ], + "GB5173": [ + { + "Gb_type": "Tensor device mismatch", + "Context": "{op} {node.target}", + "Explanation": "str(cause)", + "Hints": [ + "Move inputs, parameters, and buffers to the same device." + ] + } + ], + "GB0096": [ + { + "Gb_type": "Should not compile partial graph (STORE_ATTR)", + "Context": "", + "Explanation": "Dynamo has determined when encountering an unsupported STORE_ATTR instruction (i.e. `obj.attr = val`) that it should not compile the partial graph.", + "Hints": [] + } + ], + "GB5748": [ + { + "Gb_type": "autograd.grad with external GradientEdge", + "Context": "context", + "Explanation": "torch.autograd.grad() cannot be used with GradientEdge inputs passed from outside the compiled region. The GradientEdge contains a reference to an autograd node that was created before torch.compile started tracing, so Dynamo cannot trace through its computation.", + "Hints": [ + "Move the autograd.grad() call outside the torch.compile region.", + "Or use tensor inputs directly instead of GradientEdge objects.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "autograd.grad with external GradientEdge", + "Context": "", + "Explanation": "torch.autograd.grad() cannot be used with GradientEdge inputs passed from outside the compiled region. The GradientEdge contains an autograd node that was created outside the compiled region boundary.", + "Hints": [ + "Move the autograd.grad() call outside the torch.compile region.", + "Or use tensor inputs directly instead of GradientEdge objects.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0097": [ + { + "Gb_type": "Side effect on existing deque with limited maxlen", + "Context": "", + "Explanation": "This is not supported.", + "Hints": [ + "Don't use a deque with `maxlen` specified." + ] + } + ], + "GB0098": [ + { + "Gb_type": "Skip calling `torch.compiler.disable()`d function", + "Context": "str(self.value)", + "Explanation": "Skip calling function `{self.value}` since it was wrapped with `torch.compiler.disable` (reason: {msg})", + "Hints": [ + "Remove the `torch.compiler.disable` call" + ] + } + ], + "GB0099": [ + { + "Gb_type": "Skip inlining `torch.compiler.disable()`d function", + "Context": "str(func.get_function())", + "Explanation": "Skip inlining function {func.get_function()} since it was wrapped with `torch.compiler.disable` (reason: {msg})", + "Hints": [ + "Remove the `torch.compiler.disable` call" + ] + } + ], + "GB0100": [ + { + "Gb_type": "Storing Tensor hook handle in globals", + "Context": "name", + "Explanation": "This is not supported.", + "Hints": [] + } + ], + "GB0101": [ + { + "Gb_type": "Storing Tensor hook handle in globals (inline call)", + "Context": "inst.argval", + "Explanation": "This is not supported.", + "Hints": [] + } + ], + "GB0102": [ + { + "Gb_type": "Strict mode banned op", + "Context": "tp_getattro_impl {self} {name}", + "Explanation": "Getattr invocation '{name}' in strict mode is not supported.", + "Hints": [ + "Remove `{name}` from the list of banned ops by ", + "setting `torch._dynamo.config._autograd_backward_strict_mode_banned_ops`." + ] + }, + { + "Gb_type": "Strict mode banned op", + "Context": "getattro_impl {self} {name}", + "Explanation": "Getattr invocation '{name}' in strict mode is not supported.", + "Hints": [ + "Remove `{name}` from the list of banned ops by ", + "setting `torch._dynamo.config._autograd_backward_strict_mode_banned_ops`." + ] + }, + { + "Gb_type": "Strict mode banned op", + "Context": "var_getattr {self} {name}", + "Explanation": "Getattr invocation '{name}' in strict mode is not supported.", + "Hints": [ + "Remove `{name}` from the list of banned ops by ", + "setting `torch._dynamo.config._autograd_backward_strict_mode_banned_ops`." + ] + } + ], + "GB0103": [ + { + "Gb_type": "Tensor subclass overridden method call", + "Context": "{name}", + "Explanation": "`torch.compile` currently can't trace this", + "Hints": [ + "Avoid calling {name} of tensor subclass in torch.compile region", + "Renaming method `{name}` of type {self.class_type}", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0104": [ + { + "Gb_type": "Tensor with grad_fn()", + "Context": "tp_getattro_impl {self} grad_fn", + "Explanation": "Dynamo does not support tracing tensors with a grad_fn directly.", + "Hints": [] + }, + { + "Gb_type": "Tensor with grad_fn()", + "Context": "getattro_impl {self} grad_fn", + "Explanation": "Dynamo does not support tracing tensors with a grad_fn directly.", + "Hints": [] + }, + { + "Gb_type": "Tensor with grad_fn()", + "Context": "var_getattr {self} grad_fn", + "Explanation": "Dynamo does not support tracing tensors with a grad_fn directly.", + "Hints": [] + } + ], + "GB0105": [ + { + "Gb_type": "Tensor.numpy() with trace_numpy=False", + "Context": "call_method {self} numpy", + "Explanation": "`Tensor.numpy()` was called, but the `trace_numpy` configuration was manually disabled.", + "Hints": [ + "Set `torch._dynamo.config.trace_numpy = True` to allow ", + "Dynamo to trace through NumPy." + ] + } + ], + "GB0106": [ + { + "Gb_type": "Tensor.numpy() without NumPy installed", + "Context": "call_method {self} numpy", + "Explanation": "`Tensor.numpy()` was called, but the NumPy library is not available in the current environment.", + "Hints": [ + "Ensure NumPy is installed in your Python environment." + ] + } + ], + "GB0107": [ + { + "Gb_type": "Tensor.random_ op", + "Context": "Tensor.random_(args={args}, kwargs={kwargs})", + "Explanation": "This is currently not supported.", + "Hints": [ + "Use the out-of-place version of this op", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Tensor.random_ op", + "Context": "Tensor.{name}(args={args}, kwargs={kwargs})", + "Explanation": "This is currently not supported.", + "Hints": [ + "Use the out-of-place version of this op", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0108": [ + { + "Gb_type": "Tensor.retain_grad() with AOTDispatcher", + "Context": "tp_getattro_impl {self} retain_grad", + "Explanation": "`Tensor.retain_grad()` does not work with AOTDispatcher.", + "Hints": [] + }, + { + "Gb_type": "Tensor.retain_grad() with AOTDispatcher", + "Context": "getattro_impl {self} retain_grad", + "Explanation": "`Tensor.retain_grad()` does not work with AOTDispatcher.", + "Hints": [] + }, + { + "Gb_type": "Tensor.retain_grad() with AOTDispatcher", + "Context": "var_getattr {self} retain_grad", + "Explanation": "`Tensor.retain_grad()` does not work with AOTDispatcher.", + "Hints": [] + } + ], + "GB0109": [ + { + "Gb_type": "Tensor.tolist() with non-integer tensor", + "Context": "call_method {self} to_list", + "Explanation": "Dynamo currently does not support tracing `tolist()` on non-integer tensors.", + "Hints": [ + "Ensure the input tensor to `tolist()` is an integer ", + "type (e.g., int8, int16, int32, int64)." + ] + } + ], + "GB0110": [ + { + "Gb_type": "Tensor.uniform_ op called with `from` keyword", + "Context": "Tensor.uniform_(args={args}, kwargs={kwargs})", + "Explanation": "This is currently not supported.", + "Hints": [ + "Avoid using the `from` keyword.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Tensor.uniform_ op called with `from` keyword", + "Context": "Tensor.{name}(args={args}, kwargs={kwargs})", + "Explanation": "This is currently not supported.", + "Hints": [ + "Avoid using the `from` keyword.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0111": [ + { + "Gb_type": "TypeError from user code", + "Context": "call_function({self.value}, {args}, {kwargs})", + "Explanation": "msg", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0112": [ + { + "Gb_type": "TypeError when making fake tensor call", + "Context": "TypeError {node.target}: {cause}", + "Explanation": "", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + }, + { + "Gb_type": "TypeError when making fake tensor call", + "Context": "TypeError {node.target}: {cause}", + "Explanation": "", + "Hints": [] + } + ], + "GB0113": [ + { + "Gb_type": "Unable to resolve super getattr", + "Context": "", + "Explanation": "Dynamo failed to trace attribute `{name}` accessed via `super()` (for type `{self.typevar}` and object `{self.objvar}`) because the resolved attribute type is not supported.", + "Hints": [ + "Ensure the attribute exists in the parent class.", + "Check the arguments passed to `super()`." + ] + } + ], + "GB0114": [ + { + "Gb_type": "Unexpected failure during itertools.accumulate() iteration", + "Context": "call_function {self} {args} {kwargs}", + "Explanation": "Unexpected failure in invoking function during accumulate. Failed running func {func}({item}{acc})", + "Hints": [ + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance." + ] + } + ], + "GB0115": [ + { + "Gb_type": "Unexpected failure during itertools.groupby() iteration", + "Context": "call_function {self} {args} {kwargs}", + "Explanation": "Unexpected failure in invoking function during groupby", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB4778": [ + { + "Gb_type": "nested function with non-constructible closure in output", + "Context": "as_python_constant for out_spec {out_spec}", + "Explanation": "Cannot return a nested function with closure from a compiled function. Dynamo failed to construct the function defined in the compiled region with closure objects.", + "Hints": [ + "Define the function at module scope instead of inside another function ", + "Ensure that all closure variables are constants." + ] + }, + { + "Gb_type": "nested function with closure in output", + "Context": "as_python_constant for out_spec", + "Explanation": "Cannot return a nested function with closure from a compiled function. Dynamo cannot reconstruct the function.", + "Hints": [ + "Define the function at module scope instead of inside another function" + ] + } + ], + "GB1752": [ + { + "Gb_type": "Missing tp_iteritem", + "Context": "_tp_iteritem on {self.python_type_name()}", + "Explanation": "Dynamo does not support virtual iteration on {self.python_type_name()}. Add tp_iteritem_impl to this VariableTracker subclass.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB6441": [ + { + "Gb_type": "unsupported torch.cuda.MemPool attribute", + "Context": "torch.cuda.MemPool.{name}", + "Explanation": "Dynamo only supports reading torch.cuda.MemPool.id.", + "Hints": [] + } + ], + "GB0116": [ + { + "Gb_type": "Unexpected type in sourceless builder", + "Context": "{value_type.__module__}.{value_type.__qualname__}", + "Explanation": "SourcelessBuilder.create does not know how to wrap {value_type}", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0117": [ + { + "Gb_type": "Unhandled args for method", + "Context": "call_method {self} {name} {args} {kwargs}", + "Explanation": "Dynamo encountered an error while calling the method `{name}`.", + "Hints": [] + } + ], + "GB7650": [ + { + "Gb_type": "torch.Generator method", + "Context": "torch.Generator.{name}", + "Explanation": "torch.Generator.{name}() is a stateful RNG operation that cannot be soundly traced in the FX graph.", + "Hints": [ + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB0118": [ + { + "Gb_type": "Unimplemented next() call", + "Context": "next({self})", + "Explanation": "This abstract method must be implemented", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB1576": [ + { + "Gb_type": "COW tensor check on Python tensor subclass", + "Context": "torch._C._is_cow_tensor on Python tensor subclass", + "Explanation": "Dynamo cannot safely evaluate COW state for Python tensor subclasses because their storage semantics are controlled by __torch_dispatch__.", + "Hints": [ + "Avoid checking COW state on tensor subclasses inside ", + "torch.compile regions." + ] + } + ], + "GB0119": [ + { + "Gb_type": "Uninitialized nn.Module", + "Context": "typestr(value)", + "Explanation": "Attempted to trace an uninitialized nn.Module of type {typestr(value)}.", + "Hints": [ + "Ensure your nn.Module instance has called `super().__init__()`.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0120": [ + { + "Gb_type": "Unreachable sub-generator code", + "Context": "", + "Explanation": "Should only be encountered while implementing generator support.", + "Hints": [] + } + ], + "GB0121": [ + { + "Gb_type": "UnspecializedNNModuleVariable missing method", + "Context": "call_method: {self} {name} {args} {kwargs}", + "Explanation": "Dynamo does not support tracing method {name} of nn.Module {self.value}", + "Hints": [ + "Dynamo does not really define unspecialized nn.Module very well.", + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance." + ] + } + ], + "GB0122": [ + { + "Gb_type": "Unsupported SourceType", + "Context": "MutationType.__init__ {self} {typ}", + "Explanation": "Dynamo does not support the type `{typ}`", + "Hints": [ + "This branch is not supposed to be reachable.", + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0123": [ + { + "Gb_type": "Unsupported Tensor.backward() call", + "Context": "call_method {self} backward {gradient} {retain_graph} {create_graph} {inputs}", + "Explanation": "Dynamo currently does not support tracing `Tensor.backward()` when trace_autograd_ops is off.", + "Hints": [ + "Set torch._dynamo.trace_autograd_ops=True" + ] + }, + { + "Gb_type": "Unsupported Tensor.backward() call", + "Context": "call_method {self} backward {gradient} {retain_graph} {create_graph} {inputs}", + "Explanation": "Dynamo currently does not support tracing `Tensor.backward()`.", + "Hints": [ + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB5976": [ + { + "Gb_type": "Data pointer comparison", + "Context": "tp_richcompare_impl {self} {op} {other}", + "Explanation": "Dynamo can only trace data pointer comparisons when it can prove both operands have the same data pointer.", + "Hints": [] + }, + { + "Gb_type": "Data pointer comparison", + "Context": "richcompare_impl {self} {op} {other}", + "Explanation": "Dynamo can only trace data pointer comparisons when it can prove both operands have the same data pointer.", + "Hints": [] + }, + { + "Gb_type": "Data pointer comparison", + "Context": "call_method {self} {name} {args} {kwargs}", + "Explanation": "Dynamo can only trace data pointer comparisons when it can prove both operands have the same data pointer.", + "Hints": [] + } + ], + "GB4695": [ + { + "Gb_type": "torch.jit.script/freeze modules unsupported", + "Context": "str(value)", + "Explanation": "Dynamo does not support tracing into torch.jit.script or torch.jit.freeze modules because they execute in the TorchScript runtime, not Python. Replace the ScriptModule submodule with the original eager nn.Module.", + "Hints": [ + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB0124": [ + { + "Gb_type": "Unsupported Tensor.item() call with capture_scalar_outputs=False", + "Context": "call_method {self} item {args} {kwargs}", + "Explanation": "Dynamo does not support tracing `Tensor.item()` with config.capture_scalar_outputs=False.", + "Hints": [ + "Set `torch._dynamo.config.capture_scalar_outputs = True` ", + "or `export TORCHDYNAMO_CAPTURE_SCALAR_OUTPUTS=1` ", + "to include these operations in the captured graph." + ] + } + ], + "GB0125": [ + { + "Gb_type": "Unsupported Tensor.requires_grad_() call", + "Context": "call_method {self} requires_grad_", + "Explanation": "Dynamo does not support changes to a Tensor's `requires_grad` through calling `requires_grad_()`.", + "Hints": [] + } + ], + "GB0126": [ + { + "Gb_type": "Unsupported Tensor.resize_() call", + "Context": "call_method {self} resize_ {args} {kwargs}", + "Explanation": "Dynamo currently does not support tracing `Tensor.resize_()`.", + "Hints": [] + } + ], + "GB9528": [ + { + "Gb_type": "Attempted to reconstruct a nested function with closure which is not supported", + "Context": "str(self.fn_name)", + "Explanation": "Shouldn't reconstruct {str(self.fn_name)}, a nested function with closure", + "Hints": [ + "Define the function at module level" + ] + } + ], + "GB0127": [ + { + "Gb_type": "Unsupported Tensor.resize_as_() call", + "Context": "call_method {self} resize_as_ {args} {kwargs}", + "Explanation": "Dynamo currently does not support tracing `Tensor.resize_as_()`.", + "Hints": [] + } + ], + "GB9186": [ + { + "Gb_type": "using `torch.autograd.grad` with `torch._dynamo.config.trace_autograd_ops=False`", + "Context": "trace_autograd_ops={config.trace_autograd_ops}", + "Explanation": "Attempted to call `torch.autograd.grad` with config `torch._dynamo.config.trace_autograd_ops` set to `False`.", + "Hints": [ + "Change `torch._dynamo.config.trace_autograd_ops` to `True`." + ] + } + ], + "GB0128": [ + { + "Gb_type": "Unsupported Tensor.set_() call", + "Context": "call_method {self} set_ {args} {kwargs}", + "Explanation": "Dynamo currently does not support tracing `Tensor.set_()` overloads that include more than one argument.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0129": [ + { + "Gb_type": "Unsupported Tensor.sparse_resize_() call", + "Context": "call_method {self} sparse_resize_ {args} {kwargs}", + "Explanation": "Dynamo currently does not support tracing `Tensor.sparse_resize_()`.", + "Hints": [] + } + ], + "GB0130": [ + { + "Gb_type": "Unsupported Tensor.sparse_resize_and_clear_() call", + "Context": "call_method {self} sparse_resize_and_clear_ {args} {kwargs}", + "Explanation": "Dynamo currently does not support tracing `Tensor.sparse_resize_and_clear_()`.", + "Hints": [] + } + ], + "GB0131": [ + { + "Gb_type": "Unsupported __setitem__/__setattr__/__delitem__/__delattr__ inline attempt", + "Context": "code name: {code.co_name}, args: {args}", + "Explanation": "Attempted to inline {code.co_name} where first argument (self) is not a user-defined object.", + "Hints": [] + }, + { + "Gb_type": "Unsupported __setitem__/__setattr__ inline attempt", + "Context": "code name: {code.co_name}, args: {args}", + "Explanation": "Attempted to inline {code.co_name} where first argument (self) is not a user-defined object.", + "Hints": [] + } + ], + "GB4413": [ + { + "Gb_type": "HOP: Non-nullified side effect", + "Context": "Attribute '{name}' was not restored to its original value", + "Explanation": "Attribute '{name}' on an outer-scope object was changed from {original} to {current} inside a higher-order op subgraph. Dynamo only supports mutations that are undone before the subgraph exits (e.g., context managers that save/restore a flag). If you intentionally want this side effect, move the mutation outside of the higher-order op.", + "Hints": [ + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + }, + { + "Gb_type": "HOP: Non-nullified side effect", + "Context": "Attribute '{name}' was not restored to its original value", + "Explanation": "A variable from an outer scope was mutated inside a higher-order op subgraph and not restored to its original value. This is not supported. If using a context manager, ensure it fully restores the original state on exit.", + "Hints": [ + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB0132": [ + { + "Gb_type": "Unsupported `func` in itertools.accumulate", + "Context": "call_function {self} {args} {kwargs}", + "Explanation": "Dynamo does not know how to get the function to use for itertools.accumulate. itertools.accumulate expects the `func` as the second argument or as a keyword argument.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB4026": [ + { + "Gb_type": "triton.set_allocator not supported", + "Context": "triton.set_allocator called inside compiled region", + "Explanation": "triton.set_allocator is not supported inside torch.compile. It modifies global Triton allocator state and cannot be traced.", + "Hints": [ + "Move triton.set_allocator() outside of the torch.compile region ", + "(call it before the compiled function)." + ] + } + ], + "GB0133": [ + { + "Gb_type": "Unsupported arguments for itertools.accumulate", + "Context": "call_function {self} {args} {kwargs}", + "Explanation": "Dynamo does not know how to trace itertools.accumulate with args: {args} and kwargs: {kwargs}. itertools.accumulate expects an iterable, an optional binary function for accumulation, and an optional initial value to set the starting state.", + "Hints": [ + "Make sure the arguments to itertools.accumulate are correct.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0134": [ + { + "Gb_type": "Unsupported arguments for itertools.groupby", + "Context": "call_function {self} {args} {kwargs}", + "Explanation": "Dynamo does not know how to trace itertools.groupby with args: {args} and kwargs: {kwargs}. itertools.groupby expects an iterable to group and an optional key function to determine groupings.", + "Hints": [ + "Make sure the arguments to itertools.groupby are correct.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0135": [ + { + "Gb_type": "Unsupported attribute assignment on Exception object", + "Context": "call_setattr {self} {attr}", + "Explanation": "Dynamo does not support setting the attribute '{attr}' on tracked exception objects. Only `__context__`, `__cause__`, `__suppress_context__`, and `__traceback__` are supported.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Unsupported attribute assignment on Exception object", + "Context": "call_setattr {self} {name}", + "Explanation": "Dynamo does not support setting the attribute '{name}' on tracked exception objects. Only `__context__`, `__cause__`, `__suppress_context__`, and `__traceback__` are supported.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0136": [ + { + "Gb_type": "Unsupported attribute for range() object", + "Context": "var_getattr {self} {name}", + "Explanation": "Expected attribute to be one of {','.join(fields)} but got {name}", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0137": [ + { + "Gb_type": "Unsupported attribute for slice() object", + "Context": "tp_getattro_impl {self} {name}", + "Explanation": "Expected attribute to be one of {','.join(fields)} but got {name}", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + }, + { + "Gb_type": "Unsupported attribute for slice() object", + "Context": "getattro_impl {self} {name}", + "Explanation": "Expected attribute to be one of {','.join(fields)} but got {name}", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + }, + { + "Gb_type": "Unsupported attribute for slice() object", + "Context": "var_getattr {self} {name}", + "Explanation": "Expected attribute to be one of {','.join(fields)} but got {name}", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0138": [ + { + "Gb_type": "Unsupported autograd.Function context `save_for_backward`", + "Context": "call_method {self} {name}", + "Explanation": "Dynamo requires the `saved_tensors` attribute to be initialized on the `autograd.Function` context object.", + "Hints": [ + "Ensure that the `saved_tensors` attribute is properly ", + "initialized before calling `save_for_backward`. ", + "`save_for_backward` only supported on a newly constructed `torch.autograd.function.FunctionCtx`." + ] + } + ], + "GB0139": [ + { + "Gb_type": "Unsupported autograd.Function context method", + "Context": "call_method {self} {name}", + "Explanation": "Dynamo does not support calling the method `{name}` on `autograd.Function` context objects. Supported methods are `__setattr__`, `save_for_backward`, `mark_dirty` and `mark_non_differentiable`.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0140": [ + { + "Gb_type": "Unsupported autograd.Function method", + "Context": "call_method {self} {name}", + "Explanation": "Dynamo does not support calling the method `{name}` directly on the `torch.autograd.Function` instance. Supported methods include `apply`, `backward`, static methods, and class methods.", + "Hints": [ + "Ensure the method is decorated with `@staticmethod` ", + "or `@classmethod` if it's meant to be called on the class." + ] + } + ], + "GB1380": [ + { + "Gb_type": "Illegal __getitem__ invocation in strict mode", + "Context": "mp_subscript_impl {self} {key}", + "Explanation": "Dynamo currently does not support __getitem__ invocation in strict mode.", + "Hints": [] + } + ], + "GB4240": [ + { + "Gb_type": "unsupported __getitem__", + "Context": "mp_subscript_impl {self} {key}", + "Explanation": "Dynamo does not know how to handle __getitem__ on {self}", + "Hints": [] + } + ], + "GB0141": [ + { + "Gb_type": "Unsupported call_id() without source", + "Context": "call_id {self}", + "Explanation": "call_id() not supported for sourceless TensorVariable.", + "Hints": [] + } + ], + "GB0142": [ + { + "Gb_type": "Unsupported context manager", + "Context": "Attempted SETUP_WITH/BEFORE_WITH/LOAD_SPECIAL on {ctx}", + "Explanation": "Dynamo does not know how to enter a `{ctx.python_type_name()}` context manager.", + "Hints": [ + "Avoid using the unsupported context manager.", + "If the context manager seems like it should be supported (e.g. torch.set_grad_enabled), then ", + "it may be the case that it was created outside the compiled region, which Dynamo does not support. ", + "Supported context managers can cross graph break boundaries only if they are local non-closure ", + "variables, or are intermediate values.", + "File an issue to PyTorch. Simple context managers can potentially be supported, ", + "but note that context managers can't be supported in general" + ] + }, + { + "Gb_type": "Unsupported context manager", + "Context": "Attempted SETUP_WITH/BEFORE_WITH on {ctx}", + "Explanation": "Dynamo does not know how to enter a `{ctx.python_type_name()}` context manager.", + "Hints": [ + "Avoid using the unsupported context manager.", + "If the context manager seems like it should be supported (e.g. torch.set_grad_enabled), then ", + "it may be the case that it was created outside the compiled region, which Dynamo does not support. ", + "Supported context managers can cross graph break boundaries only if they are local non-closure ", + "variables, or are intermediate values.", + "File an issue to PyTorch. Simple context managers can potentially be supported, ", + "but note that context managers can't be supported in general" + ] + } + ], + "GB1075": [ + { + "Gb_type": "torch.scan: combine_fn mutates init or xs", + "Context": "init={init_part}, xs={xs_part}", + "Explanation": "scan only supports in-place mutation of additional_inputs (loop-invariant tensors). init is the *initial* carry only -- from step 1 on the driver feeds combine_fn's returned carry, so an in-place write to init would only affect step 0. xs[t] is a fresh, storage-disjoint slice each step, so a mutation cannot be observed by step t+1. Update the carry via the combine_fn return value; for in-place lifted buffers use additional_inputs.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0998": [ + { + "Gb_type": "source-less COW tensor check", + "Context": "torch._C._is_cow_tensor on source-less tensor", + "Explanation": "Dynamo cannot safely guard COW state for an intermediate tensor without a source.", + "Hints": [ + "Avoid checking COW state on intermediate tensors inside ", + "torch.compile regions." + ] + } + ], + "GB0143": [ + { + "Gb_type": "Unsupported conversion for slice assignment", + "Context": "call_method {self} {name} {args}", + "Explanation": "Missing dynamo support for converting {value} into a list for slice assignment.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0144": [ + { + "Gb_type": "Unsupported custom jvp", + "Context": "call_apply {self} {args} {kwargs}", + "Explanation": "Dynamo does not support tracing `torch.autograd.Function` subclasses that define a custom `jvp` method.", + "Hints": [ + "Remove the custom `jvp` method if possible.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0145": [ + { + "Gb_type": "Unsupported custom vjp", + "Context": "call_apply {self} {args} {kwargs}", + "Explanation": "Dynamo does not support tracing `torch.autograd.Function` subclasses that define a custom `vjp` method.", + "Hints": [ + "Remove the custom `vjp` method if possible.", + "Use standard `backward` instead if applicable.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0146": [ + { + "Gb_type": "Unsupported event method", + "Context": "str(name)", + "Explanation": "Dynamo doesn't support tracing the {method_name} method. We currently support wait, record, synchronize, and query.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0147": [ + { + "Gb_type": "Unsupported function call", + "Context": "call_function {self} {args} {kwargs}", + "Explanation": "Dynamo does not know how to trace the function `{self.debug_repr()}`", + "Hints": [ + "Avoid calling `{self.debug_repr()}` in your code.", + "Please report an issue to PyTorch." + ] + } + ], + "GB0148": [ + { + "Gb_type": "Unsupported function call (delayed)", + "Context": "source: {self.source}", + "Explanation": "Dynamo determined that a graph break should occur when calling `{name}`. Reason: {self.msg}", + "Hints": [] + }, + { + "Gb_type": "Unsupported function call (delayed)", + "Context": "source: {self.source}", + "Explanation": "Dynamo determined that a graph break should occur when calling `{self.source.name}`. Reason: {self.msg}", + "Hints": [] + } + ], + "GB9672": [ + { + "Gb_type": "unsupported type.__dict__['{attr_name}'].__get__ call", + "Context": "call_function {self}, args: {args}, kwargs: {kwargs}", + "Explanation": "`torch.compile` only supports calling type.__dict__['{attr_name}'].__get__ on a single constant argument (i.e. a type).", + "Hints": [ + "Make sure your call to type.__dict__['{attr_name}'].__get__ only has ", + "one positional argument (no keyword arguments).", + "Make sure the argument to type.__dict__['{attr_name}'].__get__ is a constant ", + "(i.e. type). For example, `object`, `int`, `MyCustomClass`.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0149": [ + { + "Gb_type": "Unsupported functorch tracing attempt", + "Context": "", + "Explanation": "msg", + "Hints": [] + } + ], + "GB0150": [ + { + "Gb_type": "Unsupported hasattr call", + "Context": "call_obj_hasattr {self} {name}", + "Explanation": "Dynamo does not know how to trace the function `{self.debug_repr()}`", + "Hints": [ + "Avoid calling `hasattr({self.__class__.__name__}, {name})` in your code.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB8587": [ + { + "Gb_type": "COW tensor check after COW-state-changing op", + "Context": "torch._C._is_cow_tensor after _lazy_clone", + "Explanation": "Dynamo cannot safely fold a COW state check after an op in the current graph may have changed that tensor's COW state.", + "Hints": [ + "Move the COW state check before _lazy_clone or outside ", + "the torch.compile region." + ] + } + ], + "GB0151": [ + { + "Gb_type": "Unsupported inspect call", + "Context": "inspect_parameter_names {self}", + "Explanation": "Dynamo does not know how to trace the function `{self.debug_repr()}`", + "Hints": [] + } + ], + "GB0152": [ + { + "Gb_type": "Unsupported key type for itertools.groupby", + "Context": "call_function {self} {args} {kwargs}", + "Explanation": "Dynamo does not know how to trace itertools.groupby with key type: {str(type(key))}. We only support grouping keys that are constants (int, float, str, etc.)", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0153": [ + { + "Gb_type": "Unsupported key type for nn.Module.__getitem__", + "Context": "mp_subscript_impl: {self} {key}", + "Explanation": "Dynamo does not support getitem on `nn.Module` with non-constant key.", + "Hints": [] + }, + { + "Gb_type": "Unsupported key type for nn.Module.__getitem__", + "Context": "call_method: {self} {name} {args} {kwargs}", + "Explanation": "Dynamo does not support getitem on `nn.Module` with non-constant key.", + "Hints": [] + } + ], + "GB4411": [ + { + "Gb_type": "missing sq_contains", + "Context": "sq_contains_impl not implemented for {self.python_type_name()}", + "Explanation": "Dynamo does not know how to check if `{item.debug_repr()}` is in `{self.debug_repr()}`.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "missing sq_contains", + "Context": "sq_contains not implemented for {self.python_type_name()}", + "Explanation": "Dynamo does not know how to check if `{item.debug_repr()}` is in `{self.debug_repr()}`.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0154": [ + { + "Gb_type": "Unsupported kwargs for itertools.accumulate", + "Context": "call_function {self} {args} {kwargs}", + "Explanation": "Expected kwargs: 'initial', 'func', but got {','.join(set(kwargs.keys()) - {'initial', 'func'})}", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0155": [ + { + "Gb_type": "Unsupported kwargs for itertools.groupby", + "Context": "call_function {self} {args} {kwargs}", + "Explanation": "Expected kwargs: 'key', but got {','.join(set(kwargs.keys()) - {'key'})}", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB9522": [ + { + "Gb_type": "hasattr() on unsupported type", + "Context": "hasattr({obj}, {attr})", + "Explanation": "hasattr() is not supported on type {obj.python_type_name()}", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "hasattr() on unsupported type", + "Context": "hasattr({obj}, {attr})", + "Explanation": "hasattr() is not supported on type {type(obj).__name__}", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB2412": [ + { + "Gb_type": "Unsupported attribute", + "Context": "attr_unsupported {vt} {name}", + "Explanation": "{type(vt).__name__} does not support attribute '{name}'", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0156": [ + { + "Gb_type": "Unsupported method call", + "Context": "call_method {self} {name} {args} {kwargs}", + "Explanation": "Dynamo does not know how to trace method `{name}` of class `{self.python_type_name()}`", + "Hints": [] + } + ], + "GB0157": [ + { + "Gb_type": "Unsupported ndarray attribute access", + "Context": "tp_getattro_impl {self} {name}", + "Explanation": "Dynamo currently does not support tracing `ndarray.{name}`.", + "Hints": [] + }, + { + "Gb_type": "Unsupported ndarray attribute access", + "Context": "getattro_impl {self} {name}", + "Explanation": "Dynamo currently does not support tracing `ndarray.{name}`.", + "Hints": [] + }, + { + "Gb_type": "Unsupported ndarray attribute access", + "Context": "var_getattr {self} {name}", + "Explanation": "Dynamo currently does not support tracing `ndarray.{name}`.", + "Hints": [] + } + ], + "GB0158": [ + { + "Gb_type": "Unsupported ndarray method call", + "Context": "call_method {self} {name} {args} {kwargs}", + "Explanation": "`ndarray.{name}()` is not modelled in `torch._numpy`.", + "Hints": [] + } + ], + "GB0159": [ + { + "Gb_type": "Unsupported ndarray.__version__ access", + "Context": "tp_getattro_impl {self} {name}", + "Explanation": "Dynamo currently does not support tracing `ndarray.{name}`.", + "Hints": [] + }, + { + "Gb_type": "Unsupported ndarray.__version__ access", + "Context": "getattro_impl {self} {name}", + "Explanation": "Dynamo currently does not support tracing `ndarray.{name}`.", + "Hints": [] + }, + { + "Gb_type": "Unsupported ndarray.__version__ access", + "Context": "var_getattr {self} {name}", + "Explanation": "Dynamo currently does not support tracing `ndarray.{name}`.", + "Hints": [] + } + ], + "GB0160": [ + { + "Gb_type": "Unsupported next() call", + "Context": "next({self})", + "Explanation": "Dynamo does not know how to trace calling `next()` on variable `{self}`.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0161": [ + { + "Gb_type": "Unsupported nn.Module attribute type", + "Context": "nn.Module subclass: {typestr(base)}, name: {name}, attribute type: {typestr(subobj)}", + "Explanation": "Dynamo does not support tracing nn.Module attributes of type `{typestr(subobj)}`", + "Hints": [ + "Refactor your code so that `{name}` (type `{typestr(subobj)}`) is not an attribute of `{typestr(base)}`", + "Currently supported attribute types are methods, classmethods, staticmethods, ", + "properties, constants, and tensors.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0162": [ + { + "Gb_type": "Unsupported super().__init__() call", + "Context": "call_method {self} {name} {args} {kwargs}", + "Explanation": "Dynamo encountered a super().__init__() call on {objvar} that resolved to a `torch.nn.Module.__init__()` call that we cannot trace.", + "Hints": [ + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance." + ] + } + ], + "GB2533": [ + { + "Gb_type": "reconstructing @contextmanager object", + "Context": "object: {value}", + "Explanation": "Returning a @contextmanager object from a compiled function is not supported.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB7312": [ + { + "Gb_type": "failed to bind arguments when attempting to inline", + "Context": "func='{func.get_name()}' {func.get_filename()}:{func.get_code().co_firstlineno}; args = {[arg.python_type() for arg in args]}; kwargs = {kwargs}", + "Explanation": "Argument mismatch when attempting to trace function {func.get_name()}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB4841": [ + { + "Gb_type": "Unsupported python_type() call", + "Context": "{obj} does not implement python_type()", + "Explanation": "This VariableTracker does not implement python_type(), which is required for object protocol operations.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB8335": [ + { + "Gb_type": "Generator reconstruction with mutations", + "Context": "mutating object: {item}", + "Explanation": "Cannot reconstruct a generator with variable mutations. Dynamo needs to fully exhaust the generator, which may cause unintended variable modifications.", + "Hints": [ + "Remove mutations from the generator.", + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB2549": [ + { + "Gb_type": "infinite generator detected", + "Context": "", + "Explanation": "Dynamo traced the YIELD_VALUE bytecode too many times. This could mean that we have attempted to trace an infinite generator.", + "Hints": [ + "If you are sure that your generator is not infinite, please report a bug at {PT2_ISSUE_TRACKER_URL}.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB1177": [ + { + "Gb_type": "nn.Module mutation in HigherOrderOp", + "Context": "nn.Module: {obj}", + "Explanation": "Inplace modifying nn.Module params/buffers inside HigherOrderOps is not allowed.", + "Hints": [ + "Remove the mutation or move it outside of the HigherOrderOp.", + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB6210": [ + { + "Gb_type": "leaf_function: nn.Module argument without source", + "Context": "module type: {type(arg.value).__name__}", + "Explanation": "leaf_function received an nn.Module argument that cannot be traced back to its origin. This typically happens when the module is created dynamically inside the compiled region.", + "Hints": [ + "Ensure the nn.Module is created outside the compiled function ", + "and passed as an argument.", + "If the module is a class attribute, access it via self.module_name." + ] + } + ], + "GB7637": [ + { + "Gb_type": "non-string key in object __dict__", + "Context": "key={key_value}", + "Explanation": "Dynamo expects object __dict__ keys to be strings.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB5904": [ + { + "Gb_type": "unsupported __getitem__ (sq_item)", + "Context": "sq_item_impl {self} {key}", + "Explanation": "Dynamo does not know how to handle sq_item on {self}", + "Hints": [] + } + ], + "GB0163": [ + { + "Gb_type": "Unsupported tensor subclass attribute access", + "Context": "{name}", + "Explanation": "`torch.compile` currently can't trace this", + "Hints": [ + "Avoid accessing {name} of tensor subclass in torch.compile region", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0164": [ + { + "Gb_type": "Unsupported tensor subclass overridden attribute access", + "Context": "{name}", + "Explanation": "`torch.compile` only support tracing certain types of overridden tensor subclass attributes", + "Hints": [ + "Avoid accessing {name} of tensor subclass in torch.compile region", + "Renaming attribute `{name}` of type {self.class_type}", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0569": [ + { + "Gb_type": "repr() on tensor", + "Context": "repr() on {self.python_type_name()}", + "Explanation": "Tensor repr requires actual runtime values which are not available during tracing.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0165": [ + { + "Gb_type": "Unsupported torch._C._ImperativeEngine method", + "Context": "call_method {self} {name}", + "Explanation": "Dynamo only supports the `queue_callback` method on a torch._C._ImperativeEngine instance, but found: `{name}`.", + "Hints": [] + } + ], + "GB6276": [ + { + "Gb_type": "Comprehension analysis failed: No END_FOR", + "Context": "", + "Explanation": "Could not find END_FOR instruction in comprehension bytecode.", + "Hints": [] + } + ], + "GB9898": [ + { + "Gb_type": "Comprehension analysis failed: No matches", + "Context": "pre_store_ops={pre_store_ops}, store_targets={store_targets}, iterator_vars={iterator_vars}", + "Explanation": "Comprehension does not match any known bytecode pattern.", + "Hints": [] + }, + { + "Gb_type": "Comprehension analysis failed: No matches", + "Context": "pre_store_ops={pre_store_ops}, post_store_op={post_store_op}", + "Explanation": "Comprehension does not match any known bytecode pattern.", + "Hints": [] + } + ], + "GB0166": [ + { + "Gb_type": "Unsupported torch._C._ImperativeEngine.queue_callback()", + "Context": "call_method {self} {name}", + "Explanation": "queue_callback() is only supported when Compiled Autograd is enabled with fullgraph=True.", + "Hints": [] + } + ], + "GB0167": [ + { + "Gb_type": "Variadic function call with bad args/kwargs type", + "Context": "args type: {typestr(argsvars)}, kwargs type: {typestr(kwargsvars)}", + "Explanation": "Expected args to be a list and kwargs to be a dict", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0168": [ + { + "Gb_type": "Variadic function call with bad flags", + "Context": "flags: {inst.argval}", + "Explanation": "Attempted to call a variadic function (CALL_FUNCTION_EX) with bad flags {inst.argval}", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB7694": [ + { + "Gb_type": "torch.switch: unsupported branch return type (constant)", + "Context": "str(ret_val)", + "Explanation": "Constants returned from branches must be int or None.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0169": [ + { + "Gb_type": "Write to immutable cell", + "Context": "cellvar: {cellvar}, value: {value}", + "Explanation": "Dynamo doesn't support writing to immutable/sourceless cell variables.", + "Hints": [ + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance." + ] + } + ], + "GB0170": [ + { + "Gb_type": "Data-dependent branching", + "Context": "attempted to jump with {value}", + "Explanation": "\"Detected data-dependent branching (e.g. `if my_tensor.sum() > 0:`). \" \"Dynamo does not support tracing dynamic control flow.\" + trace_info", + "Hints": [] + }, + { + "Gb_type": "Data-dependent branching", + "Context": "attempted to jump with {value}", + "Explanation": "Detected data-dependent branching (e.g. `if my_tensor.sum() > 0:`). Dynamo does not support tracing dynamic control flow.", + "Hints": [ + "Use `torch.cond` to express dynamic control flow.", + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + }, + { + "Gb_type": "Data-dependent branching", + "Context": "attempted to jump with {value}", + "Explanation": "_explanation", + "Hints": [ + "Use `torch.cond` to express dynamic control flow.", + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + }, + { + "Gb_type": "Data-dependent branching", + "Context": "attempted to jump with {value}", + "Explanation": "_explanation", + "Hints": [] + }, + { + "Gb_type": "_gb_type", + "Context": "attempted to jump with {value}", + "Explanation": "_explanation", + "Hints": [] + } + ], + "GB0171": [ + { + "Gb_type": "assert with non-string message", + "Context": "str(args)", + "Explanation": "Dynamo only supports asserts with string messages", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0172": [ + { + "Gb_type": "async_op=True for distributed collectives", + "Context": "{self.fn}, args={args}, kwargs={kwargs}", + "Explanation": "`torch.compile` doesn't support `async_op=True for {self.fn}", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0173": [ + { + "Gb_type": "backward_state does not support export", + "Context": "", + "Explanation": "Compiled autograd doesn't work with `torch.export`.", + "Hints": [] + } + ], + "GB0174": [ + { + "Gb_type": "bad args to builtin cast()", + "Context": "got args {args} {kwargs}", + "Explanation": "Dynamo expects exactly 2 args to builtin cast().", + "Hints": [ + "Ensure your call to cast() has exactly 2 arguments." + ] + } + ], + "GB0175": [ + { + "Gb_type": "builtin isinstance() cannot determine type of argument", + "Context": "isinstance({arg}, {isinstance_type_var})", + "Explanation": "Dynamo doesn't have a rule to determine the type of argument {arg}", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + }, + { + "Gb_type": "builtin isinstance() cannot determine type of argument", + "Context": "isinstance({arg}, {isinstance_type})", + "Explanation": "Dynamo doesn't have a rule to determine the type of argument {arg}", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0176": [ + { + "Gb_type": "call_id() without associated real value", + "Context": "call_id {self}", + "Explanation": "Dynamo could not find an associated real value for the tensor.", + "Hints": [] + } + ], + "GB0177": [ + { + "Gb_type": "can't handle functions not implemented in python ", + "Context": "{fn}", + "Explanation": "Dynamo can only handle functions defined in python", + "Hints": [ + "Move usage of this function out of `torch.compile` region", + "Avoid using `tensor.is_inference()` and `torch.is_inference_mode_enabled()` in your compile code. This is primarily used in conjunction with `torch.inference_mode`. Consider using `torch.no_grad` instead because `torch.no_grad` leads to same improvements as `inference_mode` when `torch.compile` is used." + ] + } + ], + "GB0178": [ + { + "Gb_type": "constant fold exception", + "Context": "attempted to run function {fn} with arguments {args}", + "Explanation": "Encountered exception when attempting to constant fold.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0179": [ + { + "Gb_type": "copy.deepcopy()", + "Context": "copy.deepcopy({x})", + "Explanation": "Dynamo does not support copy.deepcopy()", + "Hints": [ + "Avoid calling copy.deepcopy()", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0180": [ + { + "Gb_type": "dataclass fields failure", + "Context": "obj: {obj}; variable type: {type(obj)}", + "Explanation": "Dataclass fields handling fails for {obj}. Expected it to be a user-defined object.", + "Hints": [] + } + ], + "GB0181": [ + { + "Gb_type": "dtype mismatch between tensor and its gradient", + "Context": "tensor dtype: {value.dtype}; grad dtype: {grad_str}", + "Explanation": "Inconsistent dtype between tensor and its gradient. This can happen in FSDP and crashes meta tensor creation.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "dtype mismatch between tensor and its gradient", + "Context": "tensor dtype: {value.dtype}; grad dtype: {safe_grad(value).dtype}", + "Explanation": "Inconsistent dtype between tensor and its gradient. This can happen in FSDP and crashes meta tensor creation.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0182": [ + { + "Gb_type": "failed to broadcast when attempting Tensor comparison op", + "Context": "{op.__name__}({left}, {right})", + "Explanation": "Dynamo was unable to broad cast the arguments {left}, {right} when attempting to trace the comparison op {op.__name__}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0183": [ + { + "Gb_type": "failed to call dict.fromkeys()", + "Context": "{user_cls.__name__}.fromkeys(): {args} {kwargs}", + "Explanation": "Failed to call {user_cls.__name__}.fromkeys() because arguments could not be automatically converted to a list, or some dict key is not hashable.", + "Hints": [ + "Manually convert the argument to a list.", + "Ensure all keys are hashable." + ] + } + ], + "GB7489": [ + { + "Gb_type": "Unsupported argument type in tensor method call", + "Context": "call_method {self} {name} {args} {kwargs}", + "Explanation": "Dynamo could not create a proxy for an argument in the call to Tensor.{name}(). This usually means an unsupported type was passed as an argument to a tensor method.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB3840": [ + { + "Gb_type": "leaf_function without fake_fn", + "Context": "fn={fn}", + "Explanation": "The leaf_function decorator requires a fake_fn to be provided, but none was found on the decorated function.", + "Hints": [ + "Ensure the function is decorated with @leaf_function(fake_fn)" + ] + } + ], + "GB0184": [ + { + "Gb_type": "failed to call str() on user defined object", + "Context": "str(arg)", + "Explanation": "User defined object has no __str__ or __repr__ method", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB9648": [ + { + "Gb_type": "Missing tp_richcompare_impl override", + "Context": "tp_richcompare_impl {self} {op}", + "Explanation": "{type(self).__name__} does not implement tp_richcompare_impl. Add a tp_richcompare_impl override to {type(self).__name__}.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + }, + { + "Gb_type": "Missing richcompare_impl override", + "Context": "richcompare_impl {self} {op}", + "Explanation": "{type(self).__name__} does not implement richcompare_impl. Add a richcompare_impl override to {type(self).__name__}.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0185": [ + { + "Gb_type": "failed to convert numpy.ndarray to Tensor", + "Context": "str(value)", + "Explanation": "Exception encountered when attempting to convert numpy.ndarray to Tensor", + "Hints": [] + } + ], + "GB0186": [ + { + "Gb_type": "functools.partial() with non-literal keyword", + "Context": "non-literal keyword: {k}", + "Explanation": "functools.partial() expects literal/string keywords", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB2483": [ + { + "Gb_type": "tp_str_impl not implemented", + "Context": "{type(self).__name__} has no tp_str_impl override for {self.python_type_name()}", + "Explanation": "Dynamo does not implement __str__ for {self.python_type_name()} in {type(self).__name__}.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "str_impl not implemented", + "Context": "{type(self).__name__} has no str_impl override for {self.python_type_name()}", + "Explanation": "Dynamo does not implement __str__ for {self.python_type_name()} in {type(self).__name__}.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0187": [ + { + "Gb_type": "functools.wraps", + "Context": "{fn}", + "Explanation": "`torch.compile` can't trace `functools.wraps` on functions defined outside the compile region", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB1319": [ + { + "Gb_type": "Reconstruct user defined class without a source", + "Context": "Class: {var.python_type().__name__}", + "Explanation": "Cannot reconstruct an instance of {var.python_type().__name__} that escapes the compiled region. This happens when the class is defined dynamically (e.g., inside the compiled function) and the class object itself has no source that can be reconstructed. To fix this, move the class definition outside the compiled function or prevent the object from escaping the compiled region.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB5491": [ + { + "Gb_type": "Failed to mutate tensor data attribute across devices with different shape/strides", + "Context": "setattr({obj}, {name}, {val})", + "Explanation": "Dynamo only supports cross-device `.data` mutation when shape and strides match", + "Hints": [ + "Don't mutate `.data` on this tensor, or move ", + "the mutation out of `torch.compile` region" + ] + } + ], + "GB0188": [ + { + "Gb_type": "getattr with no source", + "Context": "tp_getattro_impl {self} {name}", + "Explanation": "Dynamo does not know how to access an attribute on an `nn.Module` instance that lacks a source. This is usually an internal error in Dynamo.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + }, + { + "Gb_type": "getattr with no source", + "Context": "getattro_impl {self} {name}", + "Explanation": "Dynamo does not know how to access an attribute on an `nn.Module` instance that lacks a source. This is usually an internal error in Dynamo.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + }, + { + "Gb_type": "getattr with no source", + "Context": "var_getattr {self} {name}", + "Explanation": "Dynamo does not know how to access an attribute on an `nn.Module` instance that lacks a source. This is usually an internal error in Dynamo.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0189": [ + { + "Gb_type": "getattr() on nn.Module with pending mutation", + "Context": "getattr({self}, {name})", + "Explanation": "Intentionally graph breaking on getattr() on a nn.Module with a pending mutation", + "Hints": [] + }, + { + "Gb_type": "getattr() on nn.Module with pending mutation", + "Context": "getattr({obj}, {name}, {default})", + "Explanation": "Intentionally graph breaking on getattr() on a nn.Module with a pending mutation", + "Hints": [] + } + ], + "GB0190": [ + { + "Gb_type": "getattr() with non-constant name argument", + "Context": "getattr({obj}, {name_var}, {default})", + "Explanation": "getattr() with non-constant name argument is not supported", + "Hints": [ + "Ensure the name argument of getattr() is a string" + ] + } + ], + "GB0191": [ + { + "Gb_type": "id() with unsupported args", + "Context": "str(args)", + "Explanation": "Dynamo doesn't know how to trace id() call with args {args}", + "Hints": [ + "Supported args are Tensors, and functions/nn.Modules/user-defined objects ", + "from outside the compiled region.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB1042": [ + { + "Gb_type": "backward() with in-graph created tensor", + "Context": "backward(inputs=[...]) with in-graph created tensor: {var}", + "Explanation": "backward(inputs=[...]) with tensors created inside the compiled function is not yet supported.", + "Hints": [ + "Only pass tensors that are inputs to the compiled function or captured from outside" + ] + } + ], + "GB0192": [ + { + "Gb_type": "input iterator to itertools.cycle has too many items", + "Context": "next({self})", + "Explanation": "Has reached internal Dynamo max iterator limit: {MAX_ITERATOR_LIMIT}", + "Hints": [] + } + ], + "GB0193": [ + { + "Gb_type": "invalid call to builtin op handler", + "Context": "invalid args to {self_handler}: {args} {kwargs}", + "Explanation": "Encountered TypeError when trying to handle op {fn.__name__}", + "Hints": [ + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance." + ] + } + ], + "GB0194": [ + { + "Gb_type": "isinstance() called on user defined object with C extensions", + "Context": "isinstance({arg}, {isinstance_type})", + "Explanation": "User-defined object with C extensions can have torch.Tensor attributes; intentionally graph breaking.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0195": [ + { + "Gb_type": "issubclass() with non-constant arguments", + "Context": "issubclass({left_ty}, {right_ty})", + "Explanation": "issubclass() with non-constant arguments not supported.", + "Hints": [ + "Make sure your arguments are types.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0196": [ + { + "Gb_type": "key not found in dict", + "Context": "Key {arg.value}", + "Explanation": "msg", + "Hints": [ + "Check if the key exists in the dictionary before accessing it.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB1739": [ + { + "Gb_type": "Unsupported member type on OpaqueObject", + "Context": "value={real_obj}, attr={name}, member_type={member_type}", + "Explanation": "Member type '{member_type}' is not supported for this operation.", + "Hints": [] + } + ], + "GB0197": [ + { + "Gb_type": "list elements are pointing to the list itself", + "Context": "", + "Explanation": "Dynamo does not support lists whose items reference to itself", + "Hints": [ + "Avoid using self referential list" + ] + } + ], + "GB0198": [ + { + "Gb_type": "mapping proxy affected by dictionary mutation", + "Context": "Source: {self.source}, Dict mutation detected", + "Explanation": "msg", + "Hints": [ + "Avoid modifying dictionaries that might be referenced by mapping proxy objects", + "Or avoid using the mapping proxy objects after modifying its underlying dictionary" + ] + } + ], + "GB0199": [ + { + "Gb_type": "mapping proxy cannot be reconstructed", + "Context": "Source: {self.source}", + "Explanation": "msg", + "Hints": [ + "Use a mapping proxy constructed in the same `torch.compile` region.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB9192": [ + { + "Gb_type": "Unsupported kwargs for itertools.zip_longest", + "Context": "call_function {self} {args} {kwargs}", + "Explanation": "Expected kwargs: 'fillvalue', but got {','.join(set(kwargs.keys()) - {'fillvalue'})}", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0200": [ + { + "Gb_type": "missing BUILD_SET handler", + "Context": "", + "Explanation": "Missing BUILD_SET bytecode handler (for testing purposes).", + "Hints": [] + } + ], + "GB6215": [ + { + "Gb_type": "Unresolved GetAttrVariable comparison", + "Context": "tp_richcompare_impl {self} {op}", + "Explanation": "Cannot compare {self} because the attribute could not be resolved to a concrete value.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Unresolved GetAttrVariable comparison", + "Context": "richcompare_impl {self} {op}", + "Explanation": "Cannot compare {self} because the attribute could not be resolved to a concrete value.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB8843": [ + { + "Gb_type": "Opaque object member with method-type USE_REAL returned a reference-type opaque object.", + "Context": "Opaque object type: {real_obj_type}. Method name: '{name}'", + "Explanation": "To properly guard reference-type opaque objects, we must lift them as inputs to the graph. In order to do this, they must all have a source, meaning they come from a global value or are an attribute of an input.", + "Hints": [ + "Register member '{name}' with MemberType.INLINED in ", + "register_custom_class({real_obj_type}, members=...)." + ] + }, + { + "Gb_type": "Opaque object member with method-type USE_REAL returned a reference-type opaque object.", + "Context": "Opaque object type: {value_type}. Method name: '{name}'", + "Explanation": "To properly guard reference-type opaque objects, we must lift them as inputs to the graph. In order to do this, they must all have a source, meaning they come from a global value or are an attribute of an input.", + "Hints": [ + "Register member '{name}' with MemberType.INLINED in ", + "register_custom_class({value_type}, members=...)." + ] + } + ], + "GB0201": [ + { + "Gb_type": "namedtuple construction", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "`torch.compile` only support certain input types for namedtuple", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0202": [ + { + "Gb_type": "non-const argument in nn.Module method", + "Context": "call_method: {self} {name} {args} {kwargs}", + "Explanation": "Dynamo does not support calling method `{name}` of ``nn.Module`` {module} with non-constant arguments.", + "Hints": [] + } + ], + "GB4393": [ + { + "Gb_type": "issubclass() with unsupported arguments", + "Context": "issubclass({derived}, {cls})", + "Explanation": "Arguments to issubclass() must be backed by python values.", + "Hints": [ + "Make sure your arguments are types.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0203": [ + { + "Gb_type": "non-const keys in dict_keys", + "Context": "non-const keys: {[k for k in value if not ConstantVariable.is_literal(k)]}", + "Explanation": "Dynamo expects dict_keys keys to be constants.", + "Hints": [ + "Ensure your dict_keys keys are constants (e.g. int, float, strings)" + ] + } + ], + "GB0204": [ + { + "Gb_type": "non-const keys in mappingproxy", + "Context": "non-const keys: {[k for k in value.keys() if not ConstantVariable.is_literal(k)]}", + "Explanation": "Dynamo expects mappingproxy keys to be constants.", + "Hints": [ + "Ensure your mappingproxy keys are constants (e.g. int, float, strings)" + ] + } + ], + "GB0205": [ + { + "Gb_type": "proxy not set", + "Context": "as_proxy {self}", + "Explanation": "Dynamo requires the autograd.Function context to be initialized with a proxy.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB6183": [ + { + "Gb_type": "torch.map: f mutates a captured tensor", + "Context": "freevars={freevars_mutated}", + "Explanation": "map only supports in-place mutation of xs. A tensor captured from the enclosing scope (lifted parameter) is loop-invariant: every iteration sees the same tensor, so a mutation makes iterations depend on each other, breaking map's independence contract and introducing a data race under any parallel lowering. Pass the buffer through xs, or use scan / while_loop if sequential buffer updates are required.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB9198": [ + { + "Gb_type": "Attempted to call repr() method implemented in C/C++", + "Context": "", + "Explanation": "{type(arg.value)} has a C/C++ based repr method. This is not supported.", + "Hints": [ + "Write the repr method in Python" + ] + } + ], + "GB0206": [ + { + "Gb_type": "setattr() on Tensor.requires_grad", + "Context": "setattr({obj}, {name}, {val})", + "Explanation": "setattr() on Tensor.requires_grad not supported. Mutating requires_grad can introduce a new leaf from non-leaf or vice versa in the middle of the graph, which AOTAutograd does not currently know how to handle.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0207": [ + { + "Gb_type": "sort with non-constant keys", + "Context": "str(self.key)", + "Explanation": "Cannot perform sort whose key comparison is not a compile-time constant. Key type: {self.key.python_type()}. Most notably, we cannot sort with Tensor or SymInt keys, but we can sort ints.", + "Hints": [ + "Use something else as the key.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "sort with non-constant keys", + "Context": "str(first_non_constant_key)", + "Explanation": "Cannot perform sort with non-constant key. First non-constant key type: {python_type}. Most notably, we cannot sort with Tensor or SymInt keys, but we can sort ints.", + "Hints": [ + "Use something else as the key." + ] + } + ], + "GB0208": [ + { + "Gb_type": "torch.* op returned non-Tensor", + "Context": "example_value type: {typestr(example_value)}; op: {proxy.node.op}; target: {proxy.node.target}", + "Explanation": "torch.* ops that return a non-Tensor cannot be traced into the Dynamo FX graph output", + "Hints": [] + } + ], + "GB2520": [ + { + "Gb_type": "assume_constant_result argument conversion failed", + "Context": "function {name}, variable type {type(x).__name__}", + "Explanation": "Cannot convert argument of type {type(x).__name__} to a Python constant for function {name} marked with torch._dynamo.assume_constant_result. The variable tracker does not support constant conversion.", + "Hints": [ + "Remove torch._dynamo.assume_constant_result from this function", + "Ensure all arguments passed to the function can be converted to constants" + ] + } + ], + "GB0781": [ + { + "Gb_type": "unsupported __setitem__ (sq_ass_item)", + "Context": "sq_ass_item_impl {self} {key} {value}", + "Explanation": "Dynamo does not know how to handle sq_ass_item on {self}", + "Hints": [] + } + ], + "GB0209": [ + { + "Gb_type": "torch.autograd._unsafe_preserve_version_counter escaped from compiled region", + "Context": "str(self)", + "Explanation": "Dynamo doesn't support compiling a region that returns a torch.autograd._unsafe_preserve_version_counter context manager.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0210": [ + { + "Gb_type": "torch.distributed package is not available!", + "Context": "", + "Explanation": "The PyTorch package doesn't include torch.distributed when building from source.", + "Hints": [ + "Set USE_DISTRIBUTED=1 to enable it when building PyTorch from source." + ] + } + ], + "GB2977": [ + { + "Gb_type": "wrap_jit_function: missing _torchdynamo_inline", + "Context": "type: {type(value).__name__}", + "Explanation": "Dynamo expected a JIT function with a _torchdynamo_inline attribute, but the object does not have one.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0211": [ + { + "Gb_type": "torch.nn.Module with a non-function custom __getattr__", + "Context": "tp_getattro_impl {self} {name}", + "Explanation": "Dynamo detected a nn.Module object with a custom `__getattr__` method, but this method is not a standard Python function (e.g., it might be implemented in C/C++). Dynamo cannot currently trace into such non-standard `__getattr__` methods.", + "Hints": [ + "Avoid using objects with non-standard __getattr__ methods ", + "within the compiled region. If possible, implement ", + "__getattr__ as a standard Python function.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "torch.nn.Module with a non-function custom __getattr__", + "Context": "getattro_impl {self} {name}", + "Explanation": "Dynamo detected a nn.Module object with a custom `__getattr__` method, but this method is not a standard Python function (e.g., it might be implemented in C/C++). Dynamo cannot currently trace into such non-standard `__getattr__` methods.", + "Hints": [ + "Avoid using objects with non-standard __getattr__ methods ", + "within the compiled region. If possible, implement ", + "__getattr__ as a standard Python function.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "torch.nn.Module with a non-function custom __getattr__", + "Context": "var_getattr {self} {name}", + "Explanation": "Dynamo detected a nn.Module object with a custom `__getattr__` method, but this method is not a standard Python function (e.g., it might be implemented in C/C++). Dynamo cannot currently trace into such non-standard `__getattr__` methods.", + "Hints": [ + "Avoid using objects with non-standard __getattr__ methods ", + "within the compiled region. If possible, implement ", + "__getattr__ as a standard Python function.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0212": [ + { + "Gb_type": "torch.profiler object escaped from compiled region", + "Context": "str(self)", + "Explanation": "Dynamo doesn't support compiling a region that returns a torch.profiler context manager.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0213": [ + { + "Gb_type": "unimplemented builtin op on tensor arguments", + "Context": "partial tensor op: {self} {args} {kwargs}", + "Explanation": "Dynamo does not know how to trace builtin operator {self.fn} with tensor arguments", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0214": [ + { + "Gb_type": "unsupported SymNode comparison op", + "Context": "{op.__name__}({left}, {right})", + "Explanation": "Dynamo does not support the comparison op {op.__name__} with SymNode arguments {left}, {right}", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0215": [ + { + "Gb_type": "unsupported Tensor comparison op", + "Context": "{op.__name__}({left}, {right})", + "Explanation": "Dynamo does not support the comparison op {op.__name__} with Tensor arguments {left}, {right}", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0216": [ + { + "Gb_type": "unsupported grid type for triton hop check_grid", + "Context": "grid type = {type(grid)}", + "Explanation": "`torch.compile` only supports list-like grid for check_grid", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB9458": [ + { + "Gb_type": "sq_repeat_impl not implemented", + "Context": "{type(self).__name__} has sq_repeat slot but no sq_repeat_impl override", + "Explanation": "The type {self.python_type_name()} has an sq_repeat C slot but the corresponding VariableTracker doesn't implement sq_repeat_impl.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB9561": [ + { + "Gb_type": "sq_inplace_repeat_impl not implemented", + "Context": "{type(self).__name__} has sq_inplace_repeat slot but no sq_inplace_repeat_impl override", + "Explanation": "The type {self.python_type_name()} has an sq_inplace_repeat C slot but the corresponding VariableTracker doesn't implement sq_inplace_repeat_impl.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0217": [ + { + "Gb_type": "unsupported hasattr operation", + "Context": "Class {cls}", + "Explanation": "msg", + "Hints": [ + "Consider using a regular dictionary instead", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0218": [ + { + "Gb_type": "unsupported index(Tensor)", + "Context": "", + "Explanation": "Dynamo does not support tracing builtin index() on a Tensor", + "Hints": [] + } + ], + "GB0219": [ + { + "Gb_type": "Backend compiler exception", + "Context": "Backend: {name}\nException:{str(e)}\nTraceback:\n{self.root_tx.format_frame_summary()}", + "Explanation": "Backend compiler `{name}` failed with {str(e)}. Adding a graph break.", + "Hints": [ + "Report an issue to the backend compiler repo." + ] + } + ], + "GB0220": [ + { + "Gb_type": "Failed to mutate tensor data attribute to different dtype", + "Context": "setattr({obj}, {name}, {val})", + "Explanation": "Dynamo only supports mutating `.data` of tensor to a new one with the same dtype", + "Hints": [ + "Don't mutate `.data` on this tensor, or move ", + "the mutation out of `torch.compile` region" + ] + }, + { + "Gb_type": "Failed to mutate tensor data attribute to different dtype", + "Context": "setattr({obj}, {name}, {val})", + "Explanation": "Dynamo only supports mutating `.data` of tensor to a new one with the same dtype", + "Hints": [ + "Don't mutate `.data` on this tensor, or move ", + "the mutation out of `torch.compile` region" + ] + } + ], + "GB4271": [ + { + "Gb_type": "__class__ assignment on user-defined object", + "Context": "object={self}, value={value}", + "Explanation": "Dynamo does not support reassigning __class__ on user-defined objects.", + "Hints": [ + "Move the __class__ assignment outside of the torch.compile region." + ] + } + ], + "GB0221": [ + { + "Gb_type": "non-generator contextlib.contextmanager", + "Context": "str(self.vt.get_code())", + "Explanation": "Cannot compile function decorated with `@contextlib.contextmanager` that is not a generator, i.e. does not use `yield`", + "Hints": [ + "Use `yield` in the function body instead of `return`.", + "Remove the `@contextlib.contextmanager` decorator." + ] + } + ], + "GB0222": [ + { + "Gb_type": "Attempted to wrap a set with tensors", + "Context": "Python set containing torch.Tensor elements", + "Explanation": "Dynamo cannot trace sets of tensors. To get a stable ordering, Dynamo needs to convert the set into a list and the order might not be stable if the set contains tensors.", + "Hints": [ + "Use a dictionary where the keys are tensors.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB2669": [ + { + "Gb_type": "Comprehension graph break in resume function with captured variables", + "Context": "str(analysis.captured_vars)", + "Explanation": "Cannot use comprehension optimization inside a resume function when there are captured variables. This can cause issues with deeply nested source chains.", + "Hints": [] + } + ], + "GB0223": [ + { + "Gb_type": "torch.compile call with > 1 args", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "Attempted to call `torch.compile` with > 1 args. Dynamo does not support this.", + "Hints": [ + "Remove the torch.compile call or its additional args.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0224": [ + { + "Gb_type": "Attempted to call torch in-graph function on only torch.SymInt arguments", + "Context": "fn={self.value}, args={args}, kwargs={kwargs}", + "Explanation": "Attempted to call {str(self.value)} (that should be put in the FX graph) on only torch.SymInt arguments. Dynamo does not support this.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0225": [ + { + "Gb_type": "Attempted to use tensor creation function with requires_grad=True", + "Context": "fn={self.value}, args={args}, kwargs={kwargs}", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "Create the tensor outside the compiled region.", + "Do not set `requires_grad=True`.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0226": [ + { + "Gb_type": "`torch.nn.Parameter()` with unsupported data type", + "Context": "data={data}", + "Explanation": "Called `torch.nn.Parameter()` with non-Tensor argument.", + "Hints": [ + "Ensure the argument to `torch.nn.Parameter()` is a `torch.Tensor`.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0227": [ + { + "Gb_type": "Attempted to use torch.nn.Parameter constructor with tensor subclass", + "Context": "str(data)", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0228": [ + { + "Gb_type": "`torch.nn.Parameter`: cannot convert to traceable tracable", + "Context": "", + "Explanation": "convert_tracable_parameter is set to False.", + "Hints": [ + "Check usage of context manager: do_not_convert_to_tracable_parameter", + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance." + ] + } + ], + "GB0229": [ + { + "Gb_type": "Unexpected type of data placeholder op for parameter construction", + "Context": "data_node.op={data_node.op}", + "Explanation": "Data node op should be placeholder or get_attr.", + "Hints": [ + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance." + ] + } + ], + "GB0230": [ + { + "Gb_type": "Attempted to use torch.use_deterministic_algorithms(warn_only=True)", + "Context": "mode={mode}, warn_only={warn_only}", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "Remove param warn_only in function call torch.use_deterministic_algorithms.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB9760": [ + { + "Gb_type": "torch.switch: improper operands contents", + "Context": "str(operands)", + "Explanation": "Expected `operands` to be a list/tuple of pytrees that only consists of tensor leaves.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0231": [ + { + "Gb_type": "call `torch.from_numpy` with `torch._dynamo.config.trace_numpy=False`", + "Context": "trace_numpy={config.trace_numpy}", + "Explanation": "Attempted to call `torch.from_numpy` with config `torch._dynamo.config.trace_numpy` set to `False`.", + "Hints": [ + "Change `torch._dynamo.config.trace_numpy` to `True`." + ] + } + ], + "GB6890": [ + { + "Gb_type": "Missing hash_impl override", + "Context": "hash_impl {self}", + "Explanation": "{type(self).__name__} wraps {type(real_val).__name__} which has a non-default tp_hash. Add a hash_impl override to {type(self).__name__}.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB4749": [ + { + "Gb_type": "Hashability mismatch", + "Context": "raise_unhashable {arg}", + "Explanation": "Dynamo thinks {arg_type.__name__} is unhashable, but its __hash__ is not None. This likely indicates a missing or incorrect is_hashable() override.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0232": [ + { + "Gb_type": "`torch.from_numpy` with NumPy unavailable", + "Context": "", + "Explanation": "Attempted to call `torch.numpy` but NumPy could not be imported.", + "Hints": [ + "Check NumPy version and installation in your environment.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB7151": [ + { + "Gb_type": "generator function over a skipped function", + "Context": "str(self.vt)", + "Explanation": "Cannot trace a generator whose underlying function is skipped by Dynamo (e.g. defined in a skip-listed module), since its body cannot be symbolically traced.", + "Hints": [ + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB0233": [ + { + "Gb_type": "Attempted to use strided NestedTensor", + "Context": "layout={layout}", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "Change layout=torch.jagged.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0234": [ + { + "Gb_type": "Attempted to pop from empty torch function mode stack", + "Context": "", + "Explanation": "Called `torch._C._pop_torch_function_stack` when torch function mode stack is empty.", + "Hints": [ + "Do not pop from empty torch function mode stack.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0235": [ + { + "Gb_type": "`torch.nn.Parameter` with non-constant Tensor attributes", + "Context": "data={data}", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "Ensure the Tensor argument's shape, dtype, and device are correct.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0808": [ + { + "Gb_type": "vectorcall_maybe on C method descriptor", + "Context": "name={name}, type={self.python_type_name()}, method={method}", + "Explanation": "Cannot trace special method '{name}' implemented in C on user-defined type '{self.python_type_name()}'.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB6025": [ + { + "Gb_type": "Failed to trace list()", + "Context": "list({arg_types})", + "Explanation": "Dynamo does not know how to construct a list from argument types {arg_types}", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0236": [ + { + "Gb_type": "Invalid input type for nonstrict_trace-ed function", + "Context": "Encountered input of type <{type_name}>.", + "Explanation": "For `nonstrict_trace`-ed functions, only basic types (e.g., torch.Tensor, int, float) or pytree containers of those are allowed as inputs. The provided argument contains an unsupported type.", + "Hints": [ + "Use one of the following to register the type with pytree:\n", + "* `torch.utils._pytree.register_constant`\n", + "* `torch.utils._pytree.register_dataclass`\n", + "* `torch.utils._pytree.register_pytree_node`" + ] + } + ], + "GB0237": [ + { + "Gb_type": "non-constant `requires_grad` argument to `torch.nn.Parameter`", + "Context": "requires_grad={requires_grad}", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "Change `requires_grad` to be a bool.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0238": [ + { + "Gb_type": "Input marked with `pytree.register_constant` constructed in the `torch.compile` region", + "Context": "Input={input_spec_vt}, offending type <{type_name}>.", + "Explanation": "Calling a `nonstrict_trace`-ed function with an input that contains an object of type <{type_name}>, which was marked with `pytree.register_constant`. However, the object was constructed _inside_ the `torch.compile` region. This is not supported.", + "Hints": [ + "Construct the object _outside_ the `torch.compile` region, or submit an issue to GitHub.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0467": [ + { + "Gb_type": "setattr() on unsupported type", + "Context": "setattr({obj}, {name_var}, {val})", + "Explanation": "setattr() is not supported on type {obj.python_type_name()}", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "setattr() on unsupported type", + "Context": "setattr({obj}, {name_var}, {val})", + "Explanation": "setattr() is not supported on type {type(obj).__name__}", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0239": [ + { + "Gb_type": "Invalid use of pytree_flatten with nonstrict_trace-ed function", + "Context": "Input={input_spec_vt}, offending type <{type_name}>.", + "Explanation": "Calling a `nonstrict_trace`-ed function where one of the inputs has been registered with a `pytree_flatten` that places an object of type <{type_name}> into the context.", + "Hints": [ + "Modifying the `pytree_flatten` to avoid placing the object into the context.", + "Apply one of the following to <{type_name}>:\n", + "* `torch.utils._pytree.register_constant`\n", + "* `torch.utils._pytree.register_dataclass`\n", + "* `torch.utils._pytree.register_pytree_node`", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0240": [ + { + "Gb_type": "Shape mismatch with out= list of tensor variants", + "Context": "fn={self.value}, args={args}, kwargs={kwargs}", + "Explanation": "Shape mismatch when calling {self.value} with `out=`. Provided `out=` shape: {saved_out_shape}. Actual shape: {fake_out.shape}.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0241": [ + { + "Gb_type": "Attempted to call op with non-contiguous `out=` list of tensors", + "Context": "self.value={self.value}, args={args}, kwargs={kwargs}", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB8949": [ + { + "Gb_type": "STORE_GLOBAL in non-module globals", + "Context": "name", + "Explanation": "Dynamo cannot safely replay global writes for an inlined function whose globals dict is not the registered module __dict__.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0242": [ + { + "Gb_type": "Attempted to call op with non-contiguous `out=` tensor", + "Context": "self.value={self.value}, args={args}, kwargs={kwargs}", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0243": [ + { + "Gb_type": "Attempted to use `torch.nn.modules.utils._ntuple` with unsupported argument type", + "Context": "value={value}", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "Change use of _ntuple with argument as constant or tensor." + ] + } + ], + "GB0244": [ + { + "Gb_type": "Attempted to use `torch.nn.Parameter()` with export", + "Context": "", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "Do not use `torch.nn.Parameter()` with export.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0245": [ + { + "Gb_type": "Attempted to use `nested_tensor` with non-list input", + "Context": "tensor_list={tensor_list}", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "Change `nested_tensor` with list input.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0246": [ + { + "Gb_type": "Attempted to use `torch.nn.functional.one_hot` with data-dependent output shape", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "Explicitly set the `num_classes` param of the function call ", + "`torch.nn.functional.one_hot` to something other than -1." + ] + } + ], + "GB0247": [ + { + "Gb_type": "Shape mismatch with out= tensor variant", + "Context": "fn={self.value}, args={args}, kwargs={kwargs}", + "Explanation": "Shape mismatch when calling {self.value} with `out=`. Provided `out=` shape: {saved_out_shapes}. Actual shape: {fake_out.shape}.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0811": [ + { + "Gb_type": "missing tp_iter", + "Context": "tp_iter_impl not implemented for {self.python_type_name()}", + "Explanation": "Dynamo does not know how to iterate over `{self.debug_repr()}`.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0248": [ + { + "Gb_type": "improper torch.get_device_module arguments", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "torch.get_device_module accepts 1 optional argument `device`", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB3069": [ + { + "Gb_type": "Custom op missing fake impl during tracing", + "Context": "{node.target}", + "Explanation": "A custom operator was defined and register_fake'd inside the compiled function, then called before the register_fake side effect was applied.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0249": [ + { + "Gb_type": "bad device argument to torch.accelerator.current_stream", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "Expected valid string/torch.device argument ('cpu', 'cuda', etc.)", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + }, + { + "Gb_type": "bad device argument to torch.get_device_module", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "Expected valid string/torch.device argument ('cpu', 'cuda', etc.)", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + }, + { + "Gb_type": "bad device argument to torch.accelerator.current_stream", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "Expected valid string/torch.device argument ('cpu', 'cuda', etc.)", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + }, + { + "Gb_type": "bad device argument to torch.get_device_module", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "Expected valid string/torch.device argument ('cpu', 'cuda', etc.)", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0250": [ + { + "Gb_type": "ndarray.astype(object)", + "Context": "call_method {self} {name} {args} {kwargs}", + "Explanation": "`ndarray.astype('O')` or `ndarray.astype(object)` is not supported by torch.compile, as there is no equivalent to object type in torch.Tensor. This will be executed eagerly.", + "Hints": [ + "This graph break is fundamental - it is unlikely that Dynamo will ever be able to trace through your code. Consider finding a workaround." + ] + } + ], + "GB0251": [ + { + "Gb_type": "Unsupported output type for nonstrict_trace-ed function", + "Context": "Function: {fn.__name__}", + "Explanation": "For `nonstrict_trace`-ed functions, only basic types (e.g., torch.Tensor, int, list) are allowed as output. The result of this call contains an unsupported type.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0252": [ + { + "Gb_type": "could not find name in object's mro", + "Context": "name={name}, object type={type(self.value)}, mro={type(self.value).__mro__}", + "Explanation": "Could not find name `{name}` in mro {type(self.value).__mro__}", + "Hints": [ + "Ensure the name `{name}` is defined somewhere in {self.value}'s type hierarchy.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB9860": [ + { + "Gb_type": "P2POp mutation", + "Context": "object={self}, name={name}, value={value}", + "Explanation": "Dynamo does not support mutating torch.distributed.P2POp instances.", + "Hints": [ + "Construct a new torch.distributed.P2POp instead of mutating an existing one inside torch.compile." + ] + } + ], + "GB0253": [ + { + "Gb_type": "call_method on generator", + "Context": "object={self.value}, method={name}, args={args}, kwargs={kwargs}", + "Explanation": "Detected a method call to a user-defined generator object. This is not fully supported.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "call_method on generator", + "Context": "object={self.value}, method={name}, args={args}, kwargs={kwargs}", + "Explanation": "Detected a method call to a user-defined generator object. This is not fully supported.", + "Hints": [ + "Set `torch._dynamo.config.enable_faithful_generator_behavior = False`. Note that this ", + "may cause silent incorrectness, since we will eagerly unpack generators instead of lazily ", + "evaluating them." + ] + } + ], + "GB0254": [ + { + "Gb_type": "non-const setattr name on user-defined object", + "Context": "object={self}, name={name}, value={value}", + "Explanation": "Detected a call to `setattr` of a user-defined object with a non-constant name.", + "Hints": [ + "Ensure that the name is a string." + ] + } + ], + "GB0255": [ + { + "Gb_type": "attempted to call sourceless user-defined object as a method", + "Context": "object={self.value}, function={func}, args={args}, kwargs={kwargs}", + "Explanation": "Dynamo does not support this.", + "Hints": [ + "Ensure the user-defined object {self.value} is constructed outside the compiled region." + ] + } + ], + "GB0256": [ + { + "Gb_type": "User-defined object with non-function __getattr__", + "Context": "object={self.value}, name={name}, getattr_fn={getattr_fn}", + "Explanation": "Found a non-function __getattr__ {getattr_fn} from a user-defined object {self.value} when attempting to getattr `{name}`", + "Hints": [ + "Ensure the object's __getattr__ is a function type." + ] + } + ], + "GB0257": [ + { + "Gb_type": "TypedDict with optional keys", + "Context": "str(self.value)", + "Explanation": "Dynamo does not support tracing TypedDict with optional keys", + "Hints": [ + "Avoid using TypedDict with optional keys", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "TypedDict with optional keys", + "Context": "str(self.value)", + "Explanation": "Dynamo does not support tracing TypedDict with optional keys", + "Hints": [ + "Avoid using TypedDict with optional keys", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0258": [ + { + "Gb_type": "collections.deque() with bad arguments", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "Detected call to collections.deque() with bad arguments.", + "Hints": [ + "Fix the call to collections.deque().", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0259": [ + { + "Gb_type": "collections.deque() with bad iterable argument", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "Call to collections.deque() has an iterable argument that Dynamo cannot convert to a list.", + "Hints": [ + "Use a simpler sequence type that Dynamo can convert to a list ", + "(e.g. list, tuple, list iterator, etc.)", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0260": [ + { + "Gb_type": "missing args to functools.partial", + "Context": "", + "Explanation": "functools.partial requires at least one argument", + "Hints": [ + "Fix the functools.partial call.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0261": [ + { + "Gb_type": "User-defined object method with non-function __func__", + "Context": "object={self.value}, name={name}, method={dynamic_subobj}, method.__self__={dynamic_subobj.__self__}, method.__func__={dynamic_subobj.__func__}", + "Explanation": "Method {dynamic_subobj} (name={name}) of user-defined object {self.value} has a __func__ ({dynamic_subobj.__func__}) that is not a function type.", + "Hints": [ + "Ensure that the method's __func__ is a function type." + ] + } + ], + "GB4927": [ + { + "Gb_type": "autograd.grad consumed returned tensor's grad_fn", + "Context": "Leaked output tensors: {leaked_str}", + "Explanation": "torch.autograd.grad() consumes grad_fns that are needed by tensors returned from this compiled function. This would cause 'backward through graph a second time' errors.\n The following returned tensors have consumed grad_fns: {leaked_str}", + "Hints": [ + "Detach the problematic tensor(s) before returning: e.g. `{leaked[0]}.detach()`", + "Call .detach() on the tensor before returning.", + "If you need to backward through the returned tensor, use retain_graph=True in autograd.grad()." + ] + }, + { + "Gb_type": "autograd.grad consumed returned tensor's grad_fn", + "Context": "", + "Explanation": "torch.autograd.grad() consumes grad_fns that are needed by tensors returned from this compiled function. This would cause 'backward through graph a second time' errors.", + "Hints": [ + "If you don't need to backward through the returned tensor, ", + "call .detach() before returning: `return loss.detach()`", + "If you need to backward through the returned tensor, use retain_graph=True in autograd.grad()." + ] + }, + { + "Gb_type": "autograd.grad consumed returned tensor's grad_fn", + "Context": "", + "Explanation": "torch.autograd.grad() consumes grad_fns that are needed by tensors returned from this compiled function. This would cause 'backward through graph a second time' errors.", + "Hints": [ + "If you don't need to backward through the returned tensor, call .detach() before returning: `return loss.detach()`", + "If you need to backward through the returned tensor, use retain_graph=True in autograd.grad()." + ] + } + ], + "GB6663": [ + { + "Gb_type": "autograd.grad with unsupported argument type", + "Context": "got {type(var).__name__}", + "Explanation": "torch.autograd.grad() received an argument of type {type(var).__name__} which is not supported. Expected tensor or sequence of tensors.", + "Hints": [ + "Ensure outputs and inputs arguments are tensors or sequences of tensors." + ] + } + ], + "GB1381": [ + { + "Gb_type": "autograd.grad with already consumed grad_fn", + "Context": "double consumed grad_fns: {len(double_consumed)}", + "Explanation": "torch.autograd.grad() is trying to consume grad_fns that were already consumed by a previous autograd.grad() call. This would cause 'backward through graph a second time' errors at runtime.", + "Hints": [ + "Use retain_graph=True in the first autograd.grad() call if you ", + "need to compute gradients through the same graph multiple times." + ] + } + ], + "GB6297": [ + { + "Gb_type": "autograd.Function.apply: duplicate tensor input", + "Context": "", + "Explanation": "Dynamo does not support tracing autograd.Function.apply when the same tensor is passed to multiple forward inputs.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0262": [ + { + "Gb_type": "unsupported contextlib.* API", + "Context": "{self.value}", + "Explanation": "{self.value} not supported. This may be due to its use of context-specific operations that are not supported in Dynamo yet (i.e. Exception handling)", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0263": [ + { + "Gb_type": "attempted to trace contextlib.contextmanager", + "Context": "args={args}", + "Explanation": "Tracing contextlib.contextmanager is disabled.", + "Hints": [ + "Set torch._dynamo.config.enable_trace_contextlib = True" + ] + } + ], + "GB0264": [ + { + "Gb_type": "Attempted to use `torch.nn.Parameter()` constructor with Dynamo", + "Context": "", + "Explanation": "Dynamo does not support this", + "Hints": [ + "Try to construct `torch.nn.Parameter()` outside the compiled region.", + "If this is not possible, turn `graph_break_on_nn_param_ctor` off", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB9840": [ + { + "Gb_type": "Can't extract message from torch._check*()", + "Context": "str(message_vt)", + "Explanation": "The message argument of torch._check*() must be a string, None, or a function.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Can't extract message from torch._check*()", + "Context": "str(message_vt)", + "Explanation": "The message argument of torch._check*() must be a string, None, or a function defined within the torch.compile region.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Can't extract message from torch._check*()", + "Context": "str(message_vt)", + "Explanation": "The message argument of torch._check*() must be a function defined within the torch.compile region.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB9158": [ + { + "Gb_type": "Can't convert torch._check*() message closure", + "Context": "str(message_vt)", + "Explanation": "The message argument of torch._check*() must be a function whose closure variables are Python constants.", + "Hints": [ + "Remove closure variables that reference non-constant values, e.g. ", + "remove references to tensor `x` in `lambda: f'{x} failed check'`", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB5849": [ + { + "Gb_type": "non-constant key in object __dict__", + "Context": "key={key.vt}", + "Explanation": "Dynamo expects object __dict__ replacement keys to be constants.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB3241": [ + { + "Gb_type": "C-level descriptor delete on user-defined object", + "Context": "object={self}, name={name_str}, descriptor={descriptor}", + "Explanation": "Dynamo does not yet model this C-level descriptor deleter for user-defined objects.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0265": [ + { + "Gb_type": "FakeScriptObject missing method implementation", + "Context": "value={self.value}, method={name}", + "Explanation": "TorchScript object {self.value} doesn't define the method {name}.", + "Hints": [ + "Ensure the method {name} is implemented in {self.value}.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0266": [ + { + "Gb_type": "Weird method call on TorchScript object", + "Context": "value={self.value}, method={name}", + "Explanation": "This particular method call ({name}) is not supported (e.g. calling `__setattr__`). Most method calls to TorchScript objects should be supported.", + "Hints": [ + "Avoid calling this method." + ] + } + ], + "GB0267": [ + { + "Gb_type": "Attempted to access non-callable attribute of TorchScript object", + "Context": "value={self.value}, method={name}", + "Explanation": "Attribute accesses of TorchScript objects to non-callable attributes are not supported.", + "Hints": [ + "Use method calls instead of attribute access." + ] + } + ], + "GB0268": [ + { + "Gb_type": "Unsupported kwargs for itertools.product", + "Context": "call_function {self} {args} {kwargs}", + "Explanation": "Expected kwargs: 'repeat', but got {','.join(set(kwargs.keys()) - {'repeat'})}", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB6017": [ + { + "Gb_type": "executorch_call_delegate: first arg not supported", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "executorch_call_delegate expects the first argument to be a nn.Module (got {args[0]})", + "Hints": [] + } + ], + "GB0269": [ + { + "Gb_type": "Forced graph break on leaf function", + "Context": "", + "Explanation": "Forced graph break on non-inlining function for nested graph break testing purposes", + "Hints": [ + "Set torch._dynamo.config.debug_force_graph_break_on_leaf_return = False" + ] + }, + { + "Gb_type": "Forced graph break on leaf function", + "Context": "", + "Explanation": "Forced graph break for nested graph break testing purposes", + "Hints": [ + "Set torch._dynamo.config.debug_force_graph_break_on_leaf_return = False" + ] + } + ], + "GB0270": [ + { + "Gb_type": "unimplemented builtin op vars() with no arguments", + "Context": "vars: {self} {args}", + "Explanation": "Dynamo does not know how to trace builtin operator {self.fn} with no arguments", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0271": [ + { + "Gb_type": "Class attribute mutation when the __dict__ was already materialized", + "Context": "str(self.value)", + "Explanation": "Dynamo does not support tracing mutations on a class when its __dict__ is materialized", + "Hints": [] + }, + { + "Gb_type": "Class attribute mutation when the __dict__ was already materialized", + "Context": "str(self.value)", + "Explanation": "Dynamo does not support tracing mutations on a class when its __dict__ is materialized", + "Hints": [] + } + ], + "GB0272": [ + { + "Gb_type": "Failed to make weakref to User Object when storing by ID", + "Context": "user_objected: {obj}", + "Explanation": "Object does not allow us to make a weakref to it", + "Hints": [] + }, + { + "Gb_type": "Failed to make weakref to User Object", + "Context": "user_objected: {obj}", + "Explanation": "Object does not allow us to make a weakref to it", + "Hints": [] + } + ], + "GB0273": [ + { + "Gb_type": "Keyword args passed to exception constructor", + "Context": "{self} with kwargs {init_kwargs}", + "Explanation": "Dynamo does not know how to handle keyword args passed to an exception constructor", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0682": [ + { + "Gb_type": "Non-constant GetAttrVariable hash", + "Context": "hash_impl {self}", + "Explanation": "Cannot hash {self} because Dynamo doesn't know how to represent the type of the getattr() result, which is not a constant.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0274": [ + { + "Gb_type": "Attempted to reconstruct context manager's __enter__ method", + "Context": "str(self.ctx)", + "Explanation": "Attempted to reconstruct context manager {type_str} while tracing `with ...:`", + "Hints": [ + "It is likely there is a graph break while tracing `with ctx:` ", + "but outside the actual `ctx.__enter__()` method. ", + "`torch.compile` does not expect this to happen.", + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0275": [ + { + "Gb_type": "torch._dynamo.step_unsupported() with empty checkpoint", + "Context": "", + "Explanation": "traced torch._dynamo.step_unsupported(), but there is no checkpoint to step_graph_break from. This graph break is used for debugging only.", + "Hints": [ + "Remove the torch._dynamo.step_unsupported() call.", + "Include at least one checkpoint: (1) include at least 2 ops and (2) make sure there is some ", + "line of code that is not in a try/with block, and has an empty Python stack.", + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB2473": [ + { + "Gb_type": "torch.cuda.use_mem_pool graph break", + "Context": "str(self)", + "Explanation": "Dynamo doesn't support graph breaks inside torch.cuda.use_mem_pool.", + "Hints": [] + } + ], + "GB4996": [ + { + "Gb_type": "torch.cuda.use_mem_pool with non-constant device", + "Context": "device={device}", + "Explanation": "Dynamo requires the device argument to torch.cuda.use_mem_pool to be a Python constant.", + "Hints": [] + } + ], + "GB6604": [ + { + "Gb_type": "Missing CALL_INTRINSIC_2 handler", + "Context": "CALL_INTRINSIC_2 operand: {inst.argval}", + "Explanation": "No handler implemented for CALL_INTRINSIC_2 {inst.argval} instruction.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0276": [ + { + "Gb_type": "Failed to make weakref to User Object", + "Context": "user_object: {value}", + "Explanation": "Object does not allow us to make a weakref to it", + "Hints": [] + } + ], + "GB0277": [ + { + "Gb_type": "Attempted to wrap sparse Tensor with VariableTracker", + "Context": "context", + "Explanation": "torch.compile does not support sparse Tensors with VariableTracker", + "Hints": [ + "Sparse tensor operations are not yet fully supported in torch.compile with fullgraph=True. Consider using fullgraph=False to allow graph breaks, or move sparse tensor creation outside the compiled region." + ] + } + ], + "GB0278": [ + { + "Gb_type": "Unsupported dict type for fromkeys()", + "Context": "{user_cls.__name__}.fromkeys(): {args} {kwargs}", + "Explanation": "Failed to call {user_cls.__name__}.fromkeys() because {user_cls.__name__} is not any type of dict, OrderedDict, or defaultdict", + "Hints": [ + "Ensure {user_cls.__name__} is a type of dict, OrderedDict, or defaultdict." + ] + } + ], + "GB6622": [ + { + "Gb_type": "list_richcompare_nonconst", + "Context": "element comparison produced {type(eq_result).__name__}", + "Explanation": "Cannot determine list/tuple comparison at compile time when element comparison produces a non-constant result.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB5565": [ + { + "Gb_type": "list_richcompare_ordering_symbolic", + "Context": "lexicographic ordering with symbolic element comparison", + "Explanation": "Cannot determine list/tuple ordering at compile time when element comparison is symbolic.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB5017": [ + { + "Gb_type": "missing tp_init", + "Context": "tp_init_impl not implemented for {self.python_type_name()}", + "Explanation": "Dynamo does not know how to trace __init__ on `{self.debug_repr()}`.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0279": [ + { + "Gb_type": "torch.fx.traceback.annotate escaped from compiled region", + "Context": "str(self)", + "Explanation": "Dynamo doesn't support graph break on torch.fx.traceback.annotate.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB7324": [ + { + "Gb_type": "returning intermediate with requires_grad_()", + "Context": "graph output depends on source-less requires_grad_()", + "Explanation": "msg", + "Hints": [ + "If you only need the tensor values without gradients, ", + "call .detach() before returning.", + "Consume the gradient inside the compiled function ", + "(call backward() and use .grad), ", + "or move requires_grad_() outside torch.compile." + ] + } + ], + "GB0280": [ + { + "Gb_type": "1-arg super not implemented", + "Context": "", + "Explanation": "Dynamo failed to trace attribute `{name}` accessed via `super()` (for type `{self.typevar}` and object `{self.objvar}`) because one-argument of super() is not supported.", + "Hints": [ + "Use two-argument super(type, object_or_type)." + ] + } + ], + "GB3383": [ + { + "Gb_type": "Pydantic dataclass constructor", + "Context": "{self.value}", + "Explanation": "Dynamo graph breaks on pydantic dataclass constructors because validation mutates the instance outside traced bytecode.", + "Hints": [] + } + ], + "GB0281": [ + { + "Gb_type": "Invalid or non-const argument in nn.Module __getitem__", + "Context": "mp_subscript_impl: {self} {key}", + "Explanation": "Dynamo does not support calling method `__getitem__` of ``nn.Module`` {module} with a non-constant or non-(str, int) key.", + "Hints": [ + "Use constant arguments of type str or int for __getitem__" + ] + }, + { + "Gb_type": "Invalid or non-const argument in nn.Module __getitem__", + "Context": "call_method: {self} {name} {args} {kwargs}", + "Explanation": "Dynamo does not support calling method `{name}` of ``nn.Module`` {module} with a non-constant or non-(str, int) key.", + "Hints": [ + "Use constant arguments of type str or int for __getitem__" + ] + } + ], + "GB7685": [ + { + "Gb_type": "Attribute not found on opaque class", + "Context": "class={self.value}, attr={name}", + "Explanation": "The attribute '{name}' does not exist on opaque class {self.value}.", + "Hints": [ + "Ensure '{name}' is a valid attribute of {type(self.value)}." + ] + } + ], + "GB9567": [ + { + "Gb_type": "Unsupported descriptor on opaque class", + "Context": "class={self.value}, attr={name}, descriptor={type_name}", + "Explanation": "The attribute '{name}' is a descriptor of type '{type_name}' which is not supported.", + "Hints": [ + "Only staticmethod, property, and pybind11_static_property are supported.", + "Consider accessing this attribute outside of the compiled region." + ] + } + ], + "GB0282": [ + { + "Gb_type": "Placement with custom __getattr__ not supported", + "Context": "{value_type.__name__} with custom __getattr__", + "Explanation": "Dynamo does not support Placement types with custom __getattr__ methods", + "Hints": [ + "Use Placement types without custom __getattr__ methods", + "Move the Placement usage outside the compiled region" + ] + } + ], + "GB0283": [ + { + "Gb_type": "Failed to make weakref to graph-created external object", + "Context": "user_object: {example_value}", + "Explanation": "Object does not allow us to make a weakref to it", + "Hints": [] + } + ], + "GB0284": [ + { + "Gb_type": "cannot resume from torch._dynamo.step_unsupported()", + "Context": "", + "Explanation": "traced torch._dynamo.step_unsupported(), but Dynamo is instructed to error on graph break. This graph break is used for debugging only.", + "Hints": [ + "Remove the torch._dynamo.step_unsupported() call.", + "Make sure fullgraph=False and error_on_graph_break=False.", + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0285": [ + { + "Gb_type": "unsupported arguments to torch.accelerator.current_stream", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "torch.accelerator.current_stream accepts one optional argument `device`", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0286": [ + { + "Gb_type": "bad device argument to torch.get_device_module", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "Expected valid string/torch.device argument ('cpu', 'cuda', etc.)", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0287": [ + { + "Gb_type": "unsupported type.__dict__['__annotations__'].__get__ call", + "Context": "call_function {self}, args: {args}, kwargs: {kwargs}", + "Explanation": "`torch.compile` only supports calling type.__dict__['__annotations__'].__get__ on a single constant argument (i.e. a type).", + "Hints": [ + "Make sure your call to type.__dict__['__annotations__'] only has ", + "one positional argument (no keyword arguments).", + "Make sure the argument to type.__dict__['__annotations__'] is a constant ", + "(i.e. type). For example, `object`, `int`, `MyCustomClass`.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB4818": [ + { + "Gb_type": "call to a callable object with no traceable __call__", + "Context": "object={self.value}", + "Explanation": "Dynamo could not trace a Python `__call__` method on this object.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0288": [ + { + "Gb_type": "Can't extract message from torch._check()", + "Context": "str(message_vt)", + "Explanation": "The second argument of torch._check() must be a function defined within the torch.compile region that does not reference a non-local variable.", + "Hints": [ + "Make sure the message function is defined in the torch.compile region.", + "Remove any closure variables, e.g. ", + "remove references to closure variable `x` in `lambda: f'{x} failed check'`", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0289": [ + { + "Gb_type": "unsupported method call on `typing` variable", + "Context": "typing variable: {self.value}, method name: {name}, args: {args}, kwargs: {kwargs}", + "Explanation": "`torch.compile` does not support method call `{name}` on `typing` variable f{self.value}.", + "Hints": [ + "Avoid calling the {name} method on {self.value}.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB4372": [ + { + "Gb_type": "autograd_function_kwonly_args", + "Context": "forward() has keyword-only args: {set(kwargs) - set(self.fn_cls.forward.__code__.co_varnames)}", + "Explanation": "autograd.Function.apply does not support keyword-only arguments in forward().", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0290": [ + { + "Gb_type": "attempted to trace numpy.* function as a method", + "Context": "numpy function: {self.value}, args: {args}, kwargs: {kwargs}", + "Explanation": "Tracing numpy.* functions as methods is not supported.", + "Hints": [ + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance." + ] + } + ], + "GB7906": [ + { + "Gb_type": "Missing len_impl", + "Context": "len({type(self).__name__})", + "Explanation": "Dynamo does not support len() on {type(self).__name__}. Add len_impl to this VariableTracker subclass.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0291": [ + { + "Gb_type": "logging.Logger method not supported for non-export cases", + "Context": "method: {self.value}.{name}, args: {args}, kwargs: {kwargs}", + "Explanation": "For non-export cases, logging.Logger methods are only supported if the logger has a source and the method is registered as reorderable.", + "Hints": [ + "If you do not need this logging side effect, add the exact method being called to `torch._dynamo.config.ignore_logging_functions`. Dynamo will skip the call and return `None`.", + "For example, for `logger.{name}(...)`, use `torch._dynamo.config.ignore_logging_functions.add(logger.{name})`. If `{name}` is defined on the logger class, add the class method `{logger_cls_name}.{name}` to ignore this method for all instances of that class.", + "Dynamo does not trace into logging.Logger method bodies, so only the method you call directly (`{name}`) is checked against the ignore set. Ignoring a method that `{name}` calls internally has no effect.", + "If you need the log side effect to run, then you can try one of (1) create the logger outside the compiled region and add the method to `torch._dynamo.config.reorderable_logging_functions` (e.g. `torch._dynamo.config.reorderable_logging_functions.add(logger.{name})`) so that it runs after the compiled region, as long as it is called without kwargs and its arguments are tensors, constants, or string formatters, (2) `torch._higher_order_ops.print(...)`, (3) wrap the logging call in a custom op (marked as mutable), or (4) preserve the logging contents and move the logging call outside the compiled region." + ] + }, + { + "Gb_type": "logging.Logger method not supported for non-export cases", + "Context": "method: {self.value}.{name}, args: {args}, kwargs: {kwargs}", + "Explanation": "logging.Logger methods are not supported for non-export cases.", + "Hints": [ + "If you do not need this logging side effect, add the exact method being called to `torch._dynamo.config.ignore_logging_functions`. Dynamo will skip the call and return `None`.", + "For example, for `logger.{name}(...)`, use `torch._dynamo.config.ignore_logging_functions.add(logger.{name})`. If `{name}` is defined on the logger class, add the class method `{logger_cls_name}.{name}` to ignore this method for all instances of that class.", + "Dynamo does not trace into logging.Logger method bodies, so only the method you call directly (`{name}`) is checked against the ignore set. Ignoring a method that `{name}` calls internally has no effect.", + "If you need the log side effect to run, then you can try one of (1) `torch._higher_order_ops.print(...)`, (2) wrap the logging call in a custom op (marked as mutable), or (3) preserve the logging contents and move the logging call outside the compiled region." + ] + }, + { + "Gb_type": "logging.Logger method not supported for non-export cases", + "Context": "method: {self.value}.{name}, args: {args}, kwargs: {kwargs}", + "Explanation": "logging.Logger methods are not supported for non-export cases.", + "Hints": [ + "Add the logging method to `torch._dynamo.config.ignore_logging_functions`." + ] + }, + { + "Gb_type": "logging.Logger method not supported for non-export cases", + "Context": "method: {self.value}.{name}, args: {args}, kwargs: {kwargs}", + "Explanation": "logging.Logger methods are not supported for non-export cases.", + "Hints": [ + "Add the logging method to `torch._dynamo.config.ignore_logger_methods." + ] + } + ], + "GB0292": [ + { + "Gb_type": "constant-like method call with unsupported return type", + "Context": "{self._error_prefix}.{name}(*{args}, **{kwargs}) returned {result}", + "Explanation": "Attempted to call {self._error_prefix}.{name}, got unsupported return value {result}.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0293": [ + { + "Gb_type": "attempted to trace numpy function with config.trace_numpy=False", + "Context": "numpy function: {self.value}, args: {args}, kwargs: {kwargs}", + "Explanation": "Attempted to trace numpy function {self.value} while `torch._dynamo.config.trace_numpy` was set to False.", + "Hints": [ + "Set `torch._dynamo.config.trace_numpy` to True to trace numpy functions." + ] + } + ], + "GB0294": [ + { + "Gb_type": "attempted to trace numpy function unsupported by PyTorch", + "Context": "numpy function: {self.value}, args: {args}, kwargs: {kwargs} (corresponding torch function: {func})", + "Explanation": "Can't find numpy numpy function {self.value} in torch._numpy.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0295": [ + { + "Gb_type": "cannot reconstruct NullVariable in Python < 3.11", + "Context": "", + "Explanation": "Attempted to generate PUSH_NULL instruction in Python < 3.11; where this instruction does not exist.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0296": [ + { + "Gb_type": "attempted to reorder a debugging function that can't actually be reordered", + "Context": "fn: {self.value}, args: {args}, kwargs: {kwargs}", + "Explanation": "`torch.compile` can only reorder functions that are called without keyword arguments and whose arguments are Tensors, constants, or string formatters.", + "Hints": [ + "Avoid calling the logging function {self.value} with args that are not supported." + ] + }, + { + "Gb_type": "attempted to reorder a debugging function that can't actually be reordered", + "Context": "fn: {self.value}, args: {args}, kwargs: {kwargs}", + "Explanation": "`torch.compile` can only reorder functions where the arguments are Tensors, constants, or string formatters.", + "Hints": [ + "Avoid calling the logging function {self.value} with args that are not supported." + ] + } + ], + "GB2464": [ + { + "Gb_type": "autograd.Function.apply: mark_dirty input not returned", + "Context": "", + "Explanation": "Dynamo only supports ctx.mark_dirty when each dirty input is also returned from forward.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0297": [ + { + "Gb_type": "random.Random() with improper arguments", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "random.Random() with > 1 arg or with kwargs is not supported.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0298": [ + { + "Gb_type": "attempted to trace torch._numpy.random function with config.use_numpy_random_stream=True", + "Context": "numpy function: {self.value}, args: {args}, kwargs: {kwargs} (corresponding torch function: {func})", + "Explanation": "Attempted to trace {self.value} when `torch._dynamo.config.use_numpy_random_stream` is set to True.", + "Hints": [ + "Set `torch._dynamo.config.use_numpy_random_stream` to False.", + "Avoid calling {self.value}." + ] + } + ], + "GB0299": [ + { + "Gb_type": "constant-like method call with non-constant args", + "Context": "{self._error_prefix}.{name}(*{args}, **{kwargs})", + "Explanation": "Attempted to call {self._error_prefix}.{name} with non-constant args.", + "Hints": [ + "Ensure that the args to the method call are constant (int, str, etc.)." + ] + } + ], + "GB0300": [ + { + "Gb_type": "numpy function that produces a const collection type encountered non-const arguments", + "Context": "numpy function: {self.value}, args: {args}, kwargs: {kwargs} (corresponding torch function: {func})", + "Explanation": "numpy function {self.value} that produces a const collection type (e.g. np.dtype, np.iinfo/np.finfo) received arguments that are not constant.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB9300": [ + { + "Gb_type": "P2P compilation disabled for batch_isend_irecv", + "Context": "{self.fn}", + "Explanation": "P2P compilation is disabled.", + "Hints": [ + "Set TORCHDYNAMO_ENABLE_P2P_COMPILATION=1 to enable." + ] + } + ], + "GB5282": [ + { + "Gb_type": "COW tensor check after mutation", + "Context": "torch._C._is_cow_tensor after tensor mutation", + "Explanation": "Dynamo cannot safely fold a COW state check after the tensor's state may have changed inside the compiled frame.", + "Hints": [ + "Move the COW state check before tensor mutations or ", + "outside the torch.compile region." + ] + } + ], + "GB2696": [ + { + "Gb_type": "P2P compilation disabled for isend/irecv", + "Context": "{self.fn}", + "Explanation": "P2P compilation is disabled.", + "Hints": [ + "Set TORCHDYNAMO_ENABLE_P2P_COMPILATION=1 to enable." + ] + } + ], + "GB9277": [ + { + "Gb_type": "unsupported function.__get__ call", + "Context": "call_function {self}, args: {args}, kwargs: {kwargs}", + "Explanation": "Dynamo only supports function.__get__(func, obj[, cls]) where func is a user-defined function.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB1750": [ + { + "Gb_type": "P2P compilation disabled for P2POp construction", + "Context": "torch.distributed.P2POp", + "Explanation": "P2P compilation is disabled.", + "Hints": [ + "Set TORCHDYNAMO_ENABLE_P2P_COMPILATION=1 to enable." + ] + } + ], + "GB3343": [ + { + "Gb_type": "Cannot reconstruct P2POpVariable", + "Context": "P2POpVariable.reconstruct", + "Explanation": "P2POpVariable does not support reconstruction.", + "Hints": [] + } + ], + "GB0301": [ + { + "Gb_type": "HOP: non torch.Tensor leaf", + "Context": "args types: {[type(a.realize()) for a in args]}", + "Explanation": "Expected all leaves to be of torch.Tensor type.", + "Hints": [] + } + ], + "GB0302": [ + { + "Gb_type": "HOP: non-callable variable", + "Context": "arg name: {arg_name}, func_var type: {str(func_var)}", + "Explanation": "{arg_name} should be a callable but is of type {str(func_var)}.", + "Hints": [] + } + ], + "GB0303": [ + { + "Gb_type": "torch.while_loop: improper args/kwargs", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "torch.while_loop expects 4 positional arguments (got {len(args)}) and no keyword arguments (got {len(kwargs)}) Usage: while_loop(cond_fn, body_fn, operands)", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0304": [ + { + "Gb_type": "torch.while_loop: improper additional_inputs", + "Context": "str(additional_inputs)", + "Explanation": "Expected additional_inputs to be a list/tuple but got {additional_inputs.python_type()}", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0305": [ + { + "Gb_type": "invalid set_subgraph_inputs and sub_kwargs settings", + "Context": "set_subgraph_inputs: {set_subgraph_inputs}, sub_kwargs: {sub_kwargs}", + "Explanation": "`sub_kwargs` cannot be used when `set_subgraph_inputs` is not set to 'automatic'.", + "Hints": [ + "Use `set_subgraph_inputs='automatic'` when passing `sub_kwargs`.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB7510": [ + { + "Gb_type": "nb_positive_impl not implemented", + "Context": "{type(self).__name__} has nb_positive slot but no nb_positive_impl override", + "Explanation": "The type {self.python_type_name()} has an nb_positive C slot but the corresponding VariableTracker doesn't implement nb_positive_impl.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0306": [ + { + "Gb_type": "unsupported HigherOrderOperator", + "Context": "str(value)", + "Explanation": "Unable to create higher order operator variable for {value.__name__}.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0307": [ + { + "Gb_type": "unsupported HigherOrderOperator function call", + "Context": "str(self.value)", + "Explanation": "Unable to trace calling higher order operator variable for {self.value.__name__}.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0308": [ + { + "Gb_type": "torch.while_loop: unsupported cond_fn return type", + "Context": "str(cond_r)", + "Explanation": "Expected cond_fn to return a scalar tensor or a bool but got {cond_r_meta.shape}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB4608": [ + { + "Gb_type": "richcompare identity fallback undetermined", + "Context": "generic_richcompare({v}, {w}, {op})", + "Explanation": "Cannot determine object identity for comparison fallback.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "richcompare identity fallback undetermined", + "Context": "generic_richcompare({lhs}, {rhs}, {op})", + "Explanation": "Cannot determine object identity for comparison fallback.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB9316": [ + { + "Gb_type": "Comparison on compile-time-only id or hash value", + "Context": "FakeIdVariable({self.value}) {op} {type(other).__name__}", + "Explanation": "Cannot compare a compile-time-only id() or hash() value. The comparison will run eagerly.", + "Hints": [ + "Avoid comparing id() or hash() of objects created inside ", + "the compiled region against other values.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB1220": [ + { + "Gb_type": "Untraceable C tp_richcompare", + "Context": "tp_richcompare_impl {self} {op}", + "Explanation": "{cls.__name__} defines a C comparison method that Dynamo cannot trace into.", + "Hints": [ + "Use torch._dynamo.allow_c_slot({cls.__name__}) to ", + "register it as safe if its comparison methods are pure ", + "and deterministic.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "Untraceable C tp_richcompare", + "Context": "richcompare_impl {self} {op}", + "Explanation": "{cls.__name__} defines a C comparison method that Dynamo cannot trace into.", + "Hints": [ + "Use torch._dynamo.allow_c_slot({cls.__name__}) to ", + "register it as safe if its comparison methods are pure ", + "and deterministic.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0309": [ + { + "Gb_type": "torch.cond: improper args/kwargs", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "torch.cond expects 4 positional arguments (got {len(args)}) and no keyword arguments (got {len(kwargs)}) Usage: cond(pred, cond_fn, body_fn, operands)", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB2078": [ + { + "Gb_type": "Attempted to access unregistered member on an OpaqueObject", + "Context": "value={real_obj}, attr={name}", + "Explanation": "Member '{name}' is not registered for this opaque object type.", + "Hints": [ + "Register '{name}' with a MemberType in register_custom_class(members=...)." + ] + }, + { + "Gb_type": "Attempted to access unregistered member on an OpaqueObject", + "Context": "value={self.value}, attr={name}", + "Explanation": "Member '{name}' is not registered for this opaque object type.", + "Hints": [ + "Register '{name}' with a MemberType in register_custom_class(members=...)." + ] + } + ], + "GB5458": [ + { + "Gb_type": "Custom metaclass with __getattribute__", + "Context": "type({self.value}) = {metacls}", + "Explanation": "Dynamo does not trace attribute access on classes whose metaclass overrides __getattribute__", + "Hints": [] + } + ], + "GB0310": [ + { + "Gb_type": "torch.cond: improper predicate", + "Context": "str(pred)", + "Explanation": "Expected `pred` to be a bool or a boolean tensor with a single item but got {str(type(pred))} with original python type {str(pred.python_type())}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0311": [ + { + "Gb_type": "torch.cond: improper operands", + "Context": "str(operands)", + "Explanation": "Expected `operands` to be a list/tuple but got {operands.python_type()}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0312": [ + { + "Gb_type": "torch.cond: improper operands contents", + "Context": "str(operands)", + "Explanation": "Expected `operands` to be a list/tuple of pytrees that only consists of tensor leaves.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0313": [ + { + "Gb_type": "torch.cond: differing branch outputs", + "Context": "true_spec: {true_spec.treespec}, false_spec: {false_spec.treespec}, same_spec: {same_spec}", + "Explanation": "Expected branches to return the same pytree structure.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0314": [ + { + "Gb_type": "HOP body output unsupported", + "Context": "non-tensor outputs: {non_tensor_output}", + "Explanation": "HigherOrderOperator body's output must consist of tensors or ints/bools only but got {out.python_type()}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB4315": [ + { + "Gb_type": "RuntimeError when making fake tensor call", + "Context": "", + "Explanation": "msg", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB2922": [ + { + "Gb_type": "RuntimeError when trying to get real value from fx.Node", + "Context": "", + "Explanation": "", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB6735": [ + { + "Gb_type": "torch.library.wrap_triton call with > 1 args", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "Attempted to call `wrap_triton`/`capture_triton` with > 1 args. Dynamo does not support this.", + "Hints": [ + "Remove the wrap_triton/capture_triton call or its additional args.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "torch.library.wrap_triton call with > 1 args", + "Context": "args={args}, kwargs={kwargs}", + "Explanation": "Attempted to call `torch.library.wrap_triton` or `torch._library.capture_triton` with > 1 args. Dynamo does not support this.", + "Hints": [ + "Remove the wrap_triton/capture_triton call or its additional args.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0315": [ + { + "Gb_type": "torch.associative_scan: improper xs", + "Context": "str(xs)", + "Explanation": "Expected xs to be a list/tuple but got {xs.python_type()}", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB9625": [ + { + "Gb_type": "traceback.tb_lasti not supported", + "Context": "{self} accessing 'tb_lasti'", + "Explanation": "Dynamo does not support accessing the tb_lasti attribute of traceback objects.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0316": [ + { + "Gb_type": "torch.associative_scan: improper additional_inputs", + "Context": "str(additional_inputs)", + "Explanation": "Expected additional_inputs to be a list/tuple but got {additional_inputs.python_type()}", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0317": [ + { + "Gb_type": "torch.associative_scan: zero-sized tensor", + "Context": "str(xs_vars[0])", + "Explanation": "associative_scan() operator doesn't support zero-sized tensors during tracing.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0318": [ + { + "Gb_type": "torch.associative_scan: combine_fn improper number of leaves", + "Context": "str(_combine_treespec.as_python_constant())", + "Explanation": "combine_fn needs to produce one pytree for the output but combine_fn produces the pytree {_combine_treespec.as_python_constant()}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0319": [ + { + "Gb_type": "torch.associative_scan: mismatched input/output tree structure", + "Context": "xs: {xs_treespec.as_python_constant()}, output: {_combine_treespec.as_python_constant()}", + "Explanation": "The tree structure of the xs and the outs of the combine_fn are expected to be identical, but got xs: {xs_treespec.as_python_constant()} vs output: {_combine_treespec.as_python_constant()}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0320": [ + { + "Gb_type": "torch.scan: improper xs", + "Context": "str(xs)", + "Explanation": "Expected xs to be a list/tuple but got {xs.python_type()}", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB6815": [ + { + "Gb_type": "ContextVar mutation not supported", + "Context": "ContextVar('{self.cv_obj.name}').{name}()", + "Explanation": "ContextVar.{name}() is not yet supported inside torch.compile. Move the .{name}() call outside the compiled region.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB6066": [ + { + "Gb_type": "ContextVar.get() with non-constant default", + "Context": "ContextVar('{self.cv_obj.name}').get(...)", + "Explanation": "ContextVar.get() default argument must be a compile-time constant inside torch.compile.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0321": [ + { + "Gb_type": "torch.scan: improper init", + "Context": "str(init)", + "Explanation": "Expected init to be a list/tuple with at least one element but got {init.python_type()}", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0322": [ + { + "Gb_type": "torch.scan: no init leaves", + "Context": "", + "Explanation": "Expected init leaves.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB4399": [ + { + "Gb_type": "untraceable user-defined __str__", + "Context": "Could not trace __str__ override for {type(self.value).__name__}", + "Explanation": "Dynamo could not safely trace this user-defined __str__ override.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB1297": [ + { + "Gb_type": "Reconstruction failure (self-referential)", + "Context": "str(self)", + "Explanation": "Dynamo tried to reconstruct sourceless variable {self}, but it is self-referential. Dynamo must manually implement reconstruction rules for self-referentiable sourceless variables.", + "Hints": [ + "If Dynamo is attempting to trace a return statement and your code is attempting to return a variable ", + "that Dynamo cannot reconstruct, then remove it from the return statement.", + "Remove the self-reference in the variable. A self-referring list, for example, is `l = []; l.append(l)`.", + "Report an issue to PyTorch if you need self-referential reconstrtuction support.", + "This graph break may have been caused by an earlier graph break. Resolving the earlier graph break may resolve this one." + ] + } + ], + "GB1501": [ + { + "Gb_type": "sparse_grad_accumulate_grad", + "Context": "accumulate_grad_ with sparse gradient", + "Explanation": "Sparse gradients are not supported in compiled autograd", + "Hints": [] + } + ], + "GB1724": [ + { + "Gb_type": "autograd.grad with non-constant dict key", + "Context": "non-constant key in {arg_name}", + "Explanation": "autograd.grad/backward dict inputs must have constant keys.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB4234": [ + { + "Gb_type": "nb_invert_impl not implemented", + "Context": "{type(self).__name__} has nb_invert slot but no nb_invert_impl override", + "Explanation": "The type {self.python_type_name()} has an nb_invert C slot but the corresponding VariableTracker doesn't implement nb_invert_impl.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0323": [ + { + "Gb_type": "torch.scan: improper additional_inputs", + "Context": "str(additional_inputs)", + "Explanation": "Expected additional_inputs to be a list/tuple but got {additional_inputs.python_type()}", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0324": [ + { + "Gb_type": "torch.scan: zero-sized tensor", + "Context": "str(xs_vars[0])", + "Explanation": "associative_scan() operator doesn't support zero-sized tensors during tracing.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB1140": [ + { + "Gb_type": "_autograd_grad with unsupported argument type", + "Context": "got {type(var).__name__}", + "Explanation": "_autograd_grad() received an argument of type {type(var).__name__} which is not supported. Expected tensor or sequence of tensors.", + "Hints": [ + "Ensure outputs and inputs arguments are tensors or sequences of tensors." + ] + } + ], + "GB0325": [ + { + "Gb_type": "torch.map: kwargs not supported", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "torch.map expects no keyword arguments (got {len(kwargs)})", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0326": [ + { + "Gb_type": "torch.map: improper inputs", + "Context": "str(sample_shape)", + "Explanation": "torch.map doesn't support scalar or non-zero sized tensors during tracing.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB8435": [ + { + "Gb_type": "missing_mp_subscript_impl", + "Context": "mp_subscript_impl not defined for {type(self).__name__}", + "Explanation": "'{self.python_type_name()}' subscript is not yet supported by Dynamo.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB8977": [ + { + "Gb_type": "Invalid call to __build_class__", + "Context": "Non-constant args to __build_class__: {args} {kwargs}", + "Explanation": "Cannot trace class definition: the class body function is unsupported or the base class argument are not compile-time constants", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0327": [ + { + "Gb_type": "executorch_call_delegate: kwargs not supported", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "executorch_call_delegate expects no keyword arguments (got {len(kwargs)})", + "Hints": [] + } + ], + "GB0328": [ + { + "Gb_type": "torch.func.functional_call capture is disabled", + "Context": "", + "Explanation": "torch.func.functional_call capture is disabled", + "Hints": [ + "Set `torch._dynamo.config.inline_inbuilt_nn_modules=True` to enable." + ] + } + ], + "GB9548": [ + { + "Gb_type": "nb_absolute_impl not implemented", + "Context": "{type(self).__name__} has nb_absolute slot but no nb_absolute_impl override", + "Explanation": "The type {self.python_type_name()} has an nb_absolute C slot but the corresponding VariableTracker doesn't implement nb_absolute_impl.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0329": [ + { + "Gb_type": "WrapHigherOrderVariable: kwargs unexpected", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "kwargs should have been flattened into lifted args.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0330": [ + { + "Gb_type": "wrap_with_set_grad_enabled: unexpected kwargs", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "wrap_with_set_grad_enabled expects no keyword arguments (got {len(kwargs)}).", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0331": [ + { + "Gb_type": "wrap_with_set_grad_enabled: non-constant grad_enabled", + "Context": "str(grad_enabled)", + "Explanation": "wrap_with_set_grad_enabled expects grad_enabled argument to be a constant.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0332": [ + { + "Gb_type": "wrap_with_set_grad_enabled: unexpected freevars", + "Context": "str(body_lifted_freevars)", + "Explanation": "wrap_with_set_grad_enabled expects no freevars.", + "Hints": [] + } + ], + "GB8165": [ + { + "Gb_type": "torch.switch: improper args/kwargs", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "torch.switch expects 3 positional arguments (got {len(args)}) and no keyword arguments (got {len(kwargs)}) Usage: switch(index, branches, operands)", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB9509": [ + { + "Gb_type": "torch.switch: improper index", + "Context": "str(index)", + "Explanation": "Expected index to be an int or a tensor with a single item but got {str(type(index))} with original python type {str(index.python_type())}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB8206": [ + { + "Gb_type": "torch.switch: improper operands", + "Context": "str(operands)", + "Explanation": "Expected operands to be a list/tuple but got {operands.python_type()}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB5884": [ + { + "Gb_type": "torch.switch: improper branches", + "Context": "str(branches)", + "Explanation": "Expected branches to be a list/tuple of callables.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB4307": [ + { + "Gb_type": "torch.switch: empty branches", + "Context": "str(branches)", + "Explanation": "Expected at least one branch.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB7020": [ + { + "Gb_type": "COW tensor check during export", + "Context": "torch._C._is_cow_tensor during export", + "Explanation": "Dynamo cannot safely export COW-state-dependent control flow because COW state is not represented in the exported graph.", + "Hints": [ + "Avoid checking COW state inside torch.export regions." + ] + } + ], + "GB7905": [ + { + "Gb_type": "COW tensor check on FakeTensor", + "Context": "torch._C._is_cow_tensor on FakeTensor", + "Explanation": "Dynamo cannot safely evaluate COW state from a FakeTensor because COW state is not represented in FakeTensor metadata.", + "Hints": [ + "Avoid checking COW state on FakeTensors inside ", + "torch.compile regions." + ] + }, + { + "Gb_type": "COW tensor check on FakeTensor", + "Context": "torch._C._is_cow_tensor on FakeTensor", + "Explanation": "Dynamo cannot safely evaluate COW state from a FakeTensor because COW state is not represented in FakeTensor metadata.", + "Hints": [ + "Avoid checking COW state inside torch.export regions." + ] + } + ], + "GB5687": [ + { + "Gb_type": "min/max with non-constant key", + "Context": "str(keyval)", + "Explanation": "Cannot compute {self.fn.__name__}() whose key comparison is not a compile-time constant. Key type: {keyval.python_type()}. Most notably, Tensor or SymInt keys are unsupported, but ints work.", + "Hints": [ + "Use something else as the key.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB9203": [ + { + "Gb_type": "torch.switch: differing branch outputs", + "Context": "branch{i}: {spec_a.treespec}, branch{i + 1}: {spec_b.treespec}, same_spec: {same_spec}", + "Explanation": "Expected branches to return the same pytree structure.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0333": [ + { + "Gb_type": "wrap_with_autocast: unexpected kwargs", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "wrap_with_autocast expects no keyword arguments (got {len(kwargs)}).", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0334": [ + { + "Gb_type": "wrap_with_autocast: unexpected freevars", + "Context": "str(body_lifted_freevars)", + "Explanation": "wrap_with_autocast expects no freevars.", + "Hints": [] + } + ], + "GB0335": [ + { + "Gb_type": "hints_wrapper: improper args/kwargs", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "hints_wrapper expects 3 positional arguments (got {len(args)}) and 1 keyword argument (got {len(kwargs)}). Usage: hints_wrapper(body_fn, args, kwargs, hints=...). args is expected to be list/tuple and kwargs is expected to be a dict.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0336": [ + { + "Gb_type": "out_dtype: unexpected kwargs", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "out_dtype expects no keyword arguments (got {len(kwargs)}).", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0337": [ + { + "Gb_type": "strict_mode: unexpected kwargs", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "strict_mode higher order op expects no keyword arguments (got {len(kwargs)}).", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0338": [ + { + "Gb_type": "invoke_subgraph: kwargs unexpected", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "kwargs should have been flattened into lifted args.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0339": [ + { + "Gb_type": "torch.while_loop: infinite loop detected", + "Context": "str(cond_r)", + "Explanation": "Infinite loop detected because while_loop's cond_fn always returns the same value {pred}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB1824": [ + { + "Gb_type": "torch.switch: unsupported branch return type", + "Context": "str(ret_val)", + "Explanation": "Expected branches to return a possibly nested pytree of tensor or constant int/None leaves.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0340": [ + { + "Gb_type": "torch.cond: unsupported branch return type", + "Context": "str(ret_val)", + "Explanation": "Expected branches to return a possibly nested pytree of tensors or constant ints.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0341": [ + { + "Gb_type": "torch.associative_scan: improper args", + "Context": "args: {args}", + "Explanation": "torch.associative_scan expects 2 positional arguments (got {len(args)}) Usage: associative_scan(combine_fn, xs)", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0342": [ + { + "Gb_type": "torch.scan: improper combine_fn", + "Context": "str(combine_fn_var)", + "Explanation": "Expected combine_fn to be wrapped as functools.partial in scan user-facing api or a graph module if we're re-exporting but got {combine_fn_var.python_type()}.", + "Hints": [ + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance." + ] + } + ], + "GB0343": [ + { + "Gb_type": "torch.scan: improper combine_fn number of returns", + "Context": "str(combine_result_vars)", + "Explanation": "Expect combine_fn to return a tuple (next_carry, y) but got {combine_result_vars}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB4501": [ + { + "Gb_type": "Reconstruction of FakeIdVariable", + "Context": "str(self.value)", + "Explanation": "A fake id produced by id() on a compile-time container cannot be reconstructed across a graph break.", + "Hints": [ + "Avoid using id() on containers in code that may graph-break." + ] + } + ], + "GB7786": [ + { + "Gb_type": "missing_mp_ass_subscript", + "Context": "mp_ass_subscript_impl not defined for {self.python_type_name()}", + "Explanation": "Dynamo does not yet support item assignment on '{self.python_type_name()}'.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB4198": [ + { + "Gb_type": "Attempted to copy.deepcopy a tensor", + "Context": "copy.deepcopy({self})", + "Explanation": "Dynamo does not support copy.deepcopy() on tensors.", + "Hints": [ + "Avoid calling copy.deepcopy() on tensors inside compiled regions." + ] + } + ], + "GB0344": [ + { + "Gb_type": "wrap_with_autocast: expected constant arg", + "Context": "str(args)", + "Explanation": "wrap_with_autocast expects device_type, dtype, enabled, and cache_enabled arguments to be constants.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB0345": [ + { + "Gb_type": "strict_mode: improper args", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "strict_mode higher order op expects flat inputs (list/tuple/dict/set)", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + }, + { + "Gb_type": "strict_mode: improper args", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "strict_mode higher order op expects flat inputs (list/tuple/dict)", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB7502": [ + { + "Gb_type": "Unsupported user-defined object construction during side-effect tracking", + "Context": "class={user_cls}, base={base_cls}, error={exc}", + "Explanation": "Dynamo could not construct an example object for side-effect replay using the class __new__ method.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB3697": [ + { + "Gb_type": "C-level descriptor setattr on user-defined object", + "Context": "object={self}, name={name_str}, descriptor={descriptor}", + "Explanation": "Dynamo does not yet model this C-level descriptor setter for user-defined objects.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB2404": [ + { + "Gb_type": "Unsupported object.__new__ user-defined class construction", + "Context": "class={self.value}, error={exc}", + "Explanation": "Dynamo could not construct an example object for side-effect replay using object.__new__.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0346": [ + { + "Gb_type": "autograd.Function.apply: non-function or method forward", + "Context": "str(fn)", + "Explanation": "Expected {method_name} to be a function or method.", + "Hints": [] + }, + { + "Gb_type": "autograd.Function.apply: non-function or method forward", + "Context": "str(self.fwd_graph)", + "Explanation": "Expected forward function to be a function or method.", + "Hints": [] + } + ], + "GB0347": [ + { + "Gb_type": "autograd.Function.apply: _materialize_non_diff_grads mutation", + "Context": "", + "Explanation": "Mutations to autograd.Function.ctx._materialize_non_diff_grads are not supported.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0348": [ + { + "Gb_type": "autograd.Function.apply: non-function or method backward", + "Context": "str(self.bwd_graph)", + "Explanation": "Expected backward function to be a function or method.", + "Hints": [] + } + ], + "GB8887": [ + { + "Gb_type": "NamedTupleVariable.__setattr__ bad args", + "Context": "{len(args)} args and {len(kwargs)} kwargs", + "Explanation": "Expected exactly 2 positional args for __setattr__.", + "Hints": [] + } + ], + "GB0349": [ + { + "Gb_type": "cannot unwrap variable for check_meta_consistency", + "Context": "str(var)", + "Explanation": "Expected {var} to be TensorVariable, SymNodeVariable, or ConstantVariable", + "Hints": [] + } + ], + "GB3006": [ + { + "Gb_type": "tp_as_number slot not implemented", + "Context": "{tp_slot_name}({self.python_type_name()}, {other.python_type_name()}, reverse={reverse})", + "Explanation": "The type {self.python_type_name()} does not implement the {tp_slot_name}", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0350": [ + { + "Gb_type": "torch.cond: unsupported branch return type (constant non-int)", + "Context": "str(ret_val)", + "Explanation": "Constants returned from branches must be ints.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0351": [ + { + "Gb_type": "HOP body taking non-Tensor as input", + "Context": "str(sub_args)", + "Explanation": "{description} with body that accepts non-Tensors as input. Got type {a.python_type()} at index {idx}.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0352": [ + { + "Gb_type": "autograd.Function.apply: non-function or method backward (2)", + "Context": "str(self.bwd_fn)", + "Explanation": "Expected backward function to be a function or method.", + "Hints": [] + }, + { + "Gb_type": "autograd.Function.apply: non-function or method backward (2)", + "Context": "str(self.bwd_graph)", + "Explanation": "Expected backward function to be a function or method.", + "Hints": [] + } + ], + "GB0353": [ + { + "Gb_type": "rewrite_signature: cannot trace optional function input", + "Context": "", + "Explanation": "Parameter {name} is optional with a default value of {param.default}. This is not supported yet.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB4347": [ + { + "Gb_type": "Missing tp_iternext", + "Context": "next({self.python_type_name()})", + "Explanation": "Dynamo does not support next() on {self.python_type_name()}. Add tp_iternext_impl to this VariableTracker subclass.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0354": [ + { + "Gb_type": "failed to find name in frame builtins", + "Context": "", + "Explanation": "Failed to find name `{argval}` in frame's builtins.", + "Hints": [ + "This is likely to be a Dynamo bug. Please report an issue to PyTorch." + ] + } + ], + "GB7444": [ + { + "Gb_type": "register_hook with stride-dependent code", + "Context": "Hook accesses grad metadata (e.g. is_contiguous)", + "Explanation": "register_hook callbacks that branch on gradient metadata are not supported because grad properties are unknown at trace time.", + "Hints": [] + } + ], + "GB0355": [ + { + "Gb_type": "non-single Tensor return unsupported", + "Context": "api: {api}, ret: {ret}", + "Explanation": "{api} over function that returns something other than one Tensor.", + "Hints": [] + } + ], + "GB7968": [ + { + "Gb_type": "repr() on non-constant list-like", + "Context": "repr() on {type(self).__name__} with non-constant elements", + "Explanation": "Dynamo could not safely evaluate repr() for this list-like object because one or more elements are not Python constants.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB1584": [ + { + "Gb_type": "repr() on nested function with non-constructible closure", + "Context": "repr() on nested function {self.fn_name.as_python_constant()}: {e}", + "Explanation": "Dynamo could not safely evaluate repr() for this nested function because it could not reconstruct its closure as Python constants.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB5380": [ + { + "Gb_type": "repr() on non-constant set", + "Context": "repr() on {type(self).__name__} with non-constant elements", + "Explanation": "Dynamo could not safely evaluate repr() for this set because one or more elements are not Python constants.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB6053": [ + { + "Gb_type": "tp_repr_impl not implemented", + "Context": "{type(self).__name__} has tp_repr slot but no tp_repr_impl override", + "Explanation": "The type {self.python_type_name()} has a tp_repr C slot but the corresponding VariableTracker doesn't implement tp_repr_impl.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "repr_impl not implemented", + "Context": "{type(self).__name__} has tp_repr slot but no repr_impl override", + "Explanation": "The type {self.python_type_name()} has a tp_repr C slot but the corresponding VariableTracker doesn't implement repr_impl.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB8315": [ + { + "Gb_type": "repr() on non-constant dict", + "Context": "repr() on {type(self).__name__} with non-constant keys or values", + "Explanation": "Dynamo could not safely evaluate repr() for this dict-like object because one or more keys or values are not Python constants.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB1275": [ + { + "Gb_type": "repr() on non-constant dict view", + "Context": "repr() on {type(self).__name__} with non-constant backing dict", + "Explanation": "Dynamo could not safely evaluate repr() for this dict view because its backing dict could not be materialized as a Python constant.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB2852": [ + { + "Gb_type": "untraceable user-defined __repr__", + "Context": "Could not trace __repr__ override for {type(self.value).__name__}", + "Explanation": "Dynamo could not safely trace this user-defined __repr__ override.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0459": [ + { + "Gb_type": "repr() on non-constant defaultdict", + "Context": "repr() on defaultdict with non-constant default_factory or values", + "Explanation": "Dynamo could not safely evaluate repr() for this defaultdict because its default_factory or contents are not Python constants.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0356": [ + { + "Gb_type": "failed to handle argument for FlexAttentionBackward HOP", + "Context": "args: {args}, kwargs: {kwargs}", + "Explanation": "Missing Dynamo support for FlexAttentionBackward HOP argument.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB7425": [ + { + "Gb_type": "Comprehension with captured tensor not in local slot", + "Context": "", + "Explanation": "Cannot use comprehension optimization when a captured tensor variable is not stored in its expected local slot.", + "Hints": [] + } + ], + "GB0357": [ + { + "Gb_type": "UnspecializedNNModuleVariable wrapped around ScriptModules unsupported", + "Context": "str(value)", + "Explanation": "ScriptModules aren't supported in UnspecializedNNModuleVariable because their .forward function isn't a static member of their type.", + "Hints": [ + "This graph break may be difficult to debug. Please report an issue to PyTorch for assistance." + ] + } + ], + "GB8985": [ + { + "Gb_type": "requires_grad_() intermediate leaked as output", + "Context": "call_method {self} requires_grad_", + "Explanation": "An intermediate tensor with requires_grad_() called on it (or a tensor derived from it) is returned from the compiled region. Graph breaking here to preserve partial acceleration.", + "Hints": [ + "Call .detach() before returning if you only need values.", + "Consume the gradient inside the compiled function ", + "(call backward() and use .grad), ", + "or move requires_grad_() outside torch.compile." + ] + } + ], + "GB0358": [ + { + "Gb_type": "optimizer: pending mutation on parameter", + "Context": "variable: {variable}, parameter: {p}", + "Explanation": "Pending mutations on a parameter (e.g. due to using closure) require a graph break.", + "Hints": [] + } + ], + "GB0359": [ + { + "Gb_type": "unsupported torch._C._SDPAParams attribute", + "Context": "name: {name}", + "Explanation": "Unable to fetch attribute {name} from torch._C._SDPAParams.", + "Hints": [ + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + } + ], + "GB0360": [ + { + "Gb_type": "torch.fx.experimental.symbolic_shapes.guard_scalar branch not supported", + "Context": "expr: {expr}", + "Explanation": "Expected `expr` to be a symbolic variable or constant.", + "Hints": [] + } + ], + "GB7286": [ + { + "Gb_type": "nb_float_impl not implemented", + "Context": "{type(self).__name__} has nb_float slot but no nb_float_impl override", + "Explanation": "The type {self.python_type_name()} has an nb_float C slot but the corresponding VariableTracker doesn't implement nb_float_impl.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0361": [ + { + "Gb_type": "triton kernel unsupported feature", + "Context": "", + "Explanation": "Encountered triton kernel unsupported feature: {msg}", + "Hints": [] + } + ], + "GB0362": [ + { + "Gb_type": "Attempted to access attributes/methods on an OpaqueObject", + "Context": "value={self.value}, attr={name}", + "Explanation": "Attribute/method access of OpaqueObjects is not supported.", + "Hints": [ + "Use custom operators instead of direct attribute/method access." + ] + } + ], + "GB9137": [ + { + "Gb_type": "non-constant typing subscript", + "Context": "TypingVariable[{key}]", + "Explanation": "Cannot subscript typing construct {self.value} with a non-constant key.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0363": [ + { + "Gb_type": "An opaque object was created in the middle of the program.", + "Context": "Opaque object type: {self.value}.", + "Explanation": "Opaque objects cannot be created inside the torch.compile region. They must be created before entering the compiled function.", + "Hints": [ + "Please create the opaque object before calling torch.compile ", + "and pass it in as an argument or as a global variable." + ] + }, + { + "Gb_type": "An opaque object was created in the middle of the program.", + "Context": "Opaque object types: {self.value}", + "Explanation": "Opaque objects cannot be created inside the torch.compile region. They must be created before entering the compiled function.", + "Hints": [ + "Please create the opaque object before calling torch.compile ", + "and pass it in as an argument or as a global variable." + ] + } + ], + "GB0364": [ + { + "Gb_type": "User-defined object with overridden __hash__", + "Context": "hashing object of type={type(obj)} and variable tracker {vt}", + "Explanation": "Found a user-defined object {vt} with overridden __hash__ when attempting to hash it", + "Hints": [ + "Dynamo does not support hashing user-defined objects with overridden __hash__", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0365": [ + { + "Gb_type": "Dynamo cannot determine whether the underlying object is hashable", + "Context": "is_python_hashable {self}", + "Explanation": "Dynamo does not know whether the underlying python object for {self} is hashable", + "Hints": [ + "Consider using a different type of object as the dictionary key instead of {type_self}.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0366": [ + { + "Gb_type": "Dynamo cannot determine the hash of an object", + "Context": "get_python_hash {self}", + "Explanation": "Dynamo does not know the hash of the underlying python object for {self}", + "Hints": [ + "Consider using a different type of object as the dictionary key instead of {self.python_type()}.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0442": [ + { + "Gb_type": "backward() with empty inputs", + "Context": "backward(inputs=[...]) resulted in no valid leaf tensors", + "Explanation": "backward(inputs=[...]) requires at least one valid leaf tensor.", + "Hints": [ + "Ensure at least one tensor in inputs is a leaf (requires_grad=True, no grad_fn)" + ] + } + ], + "GB0367": [ + { + "Gb_type": "Dynamo cannot determine the equality comparison of an object", + "Context": "is_python_equal {self}", + "Explanation": "Dynamo does not know the equality comparison of the underlying python object for {self}", + "Hints": [ + "Consider using a different type of object as the dictionary key instead of {self.python_type()}.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0368": [ + { + "Gb_type": "Frozen dataclass with __post_init__", + "Context": "dataclass={dataclass_cls.__name__}", + "Explanation": "Cannot reconstruct frozen dataclass with __post_init__ method, as it may have side effects that would be incorrectly replayed.", + "Hints": [ + "Remove the __post_init__ method from the frozen dataclass.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0369": [ + { + "Gb_type": "Frozen dataclass with missing field", + "Context": "dataclass={dataclass_cls.__name__}, field={field.name}", + "Explanation": "Cannot reconstruct frozen dataclass: field '{field.name}' was not tracked during tracing.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0370": [ + { + "Gb_type": "record_function escaped from compiled region", + "Context": "str(self)", + "Explanation": "Dynamo doesn't support graph break inside record_function region.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB3934": [ + { + "Gb_type": "missing sq_concat", + "Context": "sq_concat not defined for {type(self).__name__}", + "Explanation": "Dynamo does not yet support concatenating '{self.python_type_name()}' and '{other.python_type_name()}'", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB2544": [ + { + "Gb_type": "missing sq_inplace_concat", + "Context": "sq_inplace_concat not defined for {type(self).__name__}", + "Explanation": "Dynamo does not yet support inplace concat of '{self.python_type_name()}' and '{other.python_type_name()}'", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0371": [ + { + "Gb_type": "autograd.grad with output that requires grad", + "Context": "context", + "Explanation": "The compiled function uses torch.autograd.grad() and returns a tensor that still requires gradients and is connected to the autograd.grad() computation. This would cause aot_autograd to attempt 'backward through graph a second time', which is not supported.", + "Hints": [ + "Call .detach() on the output tensor before returning it from the compiled function.", + "For example: `return loss.detach(), grads` instead of `return loss, grads`.", + "Or set create_graph=False in autograd.grad() if you don't need higher-order gradients.", + "Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance(\"force_eager\")`. " + ] + }, + { + "Gb_type": "autograd.grad with output that requires grad", + "Context": "", + "Explanation": "The compiled function uses torch.autograd.grad() and returns a tensor that still requires gradients. This may cause aot_autograd to attempt 'backward through graph a second time', which is not supported.", + "Hints": [ + "Call .detach() on the output tensor before returning it from the compiled function.", + "For example: `return loss.detach(), grads` instead of `return loss, grads`.", + "Or set create_graph=False in autograd.grad() if you don't need higher-order gradients." + ] + } + ], + "GB0372": [ + { + "Gb_type": "autograd.grad with external grad_fn", + "Context": "context", + "Explanation": "torch.autograd.grad() cannot trace through the autograd graph because it's output depends on a tensor that was created outside the compiled region and has a grad_fn attached. The autograd graph extends beyond the compiled region boundary, which Dynamo cannot trace.", + "Hints": [ + "If you don't need gradients to flow back to the original tensor outside ", + "the compiled region, detach the input: `tensor.detach().requires_grad_(True)`.", + "Otherwise, move the autograd.grad() call outside the compiled region.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "autograd.grad with external grad_fn", + "Context": "context", + "Explanation": "torch.autograd.grad() cannot trace through the autograd graph because the '{arg_name}' argument depends on a tensor that was created outside the compiled region and has a grad_fn attached. The autograd graph extends beyond the compiled region boundary, which Dynamo cannot trace.", + "Hints": [ + "Detach the input tensor before passing to the compiled function: ", + "`tensor.detach().requires_grad_(True)` to make it a leaf tensor.", + "Or call `.detach()` on the tensor before using it in autograd.grad().", + "Or move the autograd.grad() call outside the compiled region.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + }, + { + "Gb_type": "autograd.grad with external grad_fn", + "Context": "", + "Explanation": "torch.autograd.grad() cannot be used when the compiled function receives tensors with grad_fn created outside the compiled region. The autograd graph cannot extend beyond the compiled region boundary.", + "Hints": [ + "Detach the input tensor before passing to the compiled function: `tensor.detach().requires_grad_(True)` to make it a leaf tensor.", + "Or move the autograd.grad() call outside the compiled region.", + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0373": [ + { + "Gb_type": "autograd.grad with compiled autograd", + "Context": "compiled_autograd is currently enabled", + "Explanation": "torch.autograd.grad() inside torch.compile is not supported when compiled autograd is enabled. These two features have conflicting requirements for how the autograd graph is traced.", + "Hints": [ + "Disable compiled autograd by removing the compiled_autograd context manager.", + "Or move the autograd.grad() call outside the torch.compile region.", + "Or restructure your code so autograd.grad() and compiled_autograd don't overlap." + ] + }, + { + "Gb_type": "autograd.grad with compiled autograd", + "Context": "torch.autograd.grad()", + "Explanation": "torch.autograd.grad() inside torch.compile is not supported when compiled autograd is enabled. These two features have conflicting requirements for how the autograd graph is traced.", + "Hints": [ + "Disable compiled autograd by removing the compiled_autograd context manager.", + "Or move the autograd.grad() call outside the torch.compile region." + ] + } + ], + "GB0374": [ + { + "Gb_type": "Sparse tensor creation not supported", + "Context": "function: {fn_name}", + "Explanation": "torch.compile does not support sparse tensor creation functions like {fn_name}. Sparse tensors require specialized handling that is not yet implemented in the compiler.", + "Hints": [ + "Sparse tensor operations are not yet fully supported in torch.compile with fullgraph=True. Consider using fullgraph=False to allow graph breaks, or move sparse tensor creation outside the compiled region." + ] + } + ], + "GB0375": [ + { + "Gb_type": "Attempted to wrap a dual tensor input", + "Context": "", + "Explanation": "torch.compile does not support input tensors that carry a forward-mode AD tangent; compiled code would silently drop the tangent.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ], + "GB0376": [ + { + "Gb_type": "Call to `torch._dynamo.disable()`", + "Context": "Called `torch._dynamo.disable()` with args `{args}`, kwargs `{kwargs}`", + "Explanation": "`torch._dynamo.disable()` was called inside a compiled region. This API disables compilation when used as a decorator or wrapper outside the compiled region.", + "Hints": [ + "Move the `torch._dynamo.disable()` call outside the compiled function and apply it to the function that should run eagerly.", + "Use `torch._dynamo.graph_break()` to intentionally insert a graph break at this point." + ] + } + ], + "GB0377": [ + { + "Gb_type": "Call to `torch.compiler.disable()`", + "Context": "Called `torch.compiler.disable()` with args `{args}`, kwargs `{kwargs}`", + "Explanation": "`torch.compiler.disable()` was called inside a compiled region. This API disables compilation when used as a decorator or wrapper outside the compiled region.", + "Hints": [ + "Move the `torch.compiler.disable()` call outside the compiled function and apply it to the function that should run eagerly.", + "Use `torch._dynamo.graph_break()` to intentionally insert a graph break at this point." + ] + } + ], + "GB9899": [ + { + "Gb_type": "unsupported attribute of tracked type", + "Context": "{vt.python_type_name()}.{name} on {vt}", + "Explanation": "Dynamo does not support accessing `{name}` on `{vt.python_type_name()}` objects.", + "Hints": [ + "It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues." + ] + } + ] +} diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_bytecode_inputs.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_bytecode_inputs.py new file mode 100644 index 0000000000000000000000000000000000000000..a8575bc939fd02ff507d25d96602f1066f454335 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_bytecode_inputs.py @@ -0,0 +1,116 @@ +import weakref +from collections.abc import Callable +from typing import Any + +from torch._dynamo.source import Source + + +PyCodegen = Any + +# This file is to handle types that we don't want to support +# as explicit FX graph inputs. This uses a sidetable which +# we populate in bytecode and is loaded during graph execution + +# We use a dynamo-generated index as a level of indirection +# this allows us to register objects externally in pre-graph bytecode that we want +# to pass to the graph, but not support their types as graph inputs +index_to_bytecode_constructor: dict[int, Callable[[PyCodegen], None]] = {} + +index_to_external_object_weakref: dict[int, weakref.ReferenceType[Any]] = {} + +keep_alive: list[Any] = [] + + +def has_user_objects() -> bool: + return bool(index_to_bytecode_constructor) + + +def stash_graph_created_object(obj: Any) -> Any: + keep_alive.append(obj) + return obj + + +CURRENT_STREAM_INDEX = 0 + + +def set_external_object_by_index(index: int, value: Any) -> None: + """Update an entry in the external object registry at runtime.""" + keep_alive.append(value) + index_to_external_object_weakref[index] = weakref.ref(value) + + +def get_external_object_by_index(index: int) -> Any: + if index not in index_to_external_object_weakref: + raise AssertionError("Index not registered in index_to_user_object_weakref") + obj = index_to_external_object_weakref[index]() + if obj is None: + raise AssertionError("User object is no longer alive") + return index_to_external_object_weakref[index]() + + +def store_user_object_weakrefs(*args: Any) -> None: + global index_to_external_object_weakref + index_to_external_object_weakref.clear() + index_to_external_object_weakref.update( + {i: weakref.ref(arg) for i, arg in enumerate(args)} + ) + + +def reset_user_object_tracking() -> None: + index_to_bytecode_constructor.clear() + index_to_external_object_weakref.clear() + keep_alive.clear() + + +def register_graph_created_object( + example_value: Any, construct_fn: Callable[[int, PyCodegen], None] +) -> int: + global index_to_bytecode_constructor + global keep_alive + keep_alive.append(example_value) + index = len(index_to_bytecode_constructor) + index_to_bytecode_constructor[index] = lambda cg: construct_fn(index, cg) + try: + index_to_external_object_weakref[index] = weakref.ref(example_value) + except TypeError as e: + from .exc import unimplemented + + unimplemented( + gb_type="Failed to make weakref to graph-created external object", + context=f"user_object: {example_value}", + explanation="Object does not allow us to make a weakref to it", + hints=[], + from_exc=e, + ) + return index + + +# Register a user object to be used in the graph +def register_user_object(value: Any, source: Source) -> int: + global index_to_bytecode_constructor + index = len(index_to_bytecode_constructor) + index_to_bytecode_constructor[index] = lambda cg: cg(source) + try: + index_to_external_object_weakref[index] = weakref.ref(value) + except TypeError as e: + from .exc import unimplemented + + unimplemented( + gb_type="Failed to make weakref to User Object", + context=f"user_object: {value}", + explanation="Object does not allow us to make a weakref to it", + hints=[], + from_exc=e, + ) + return index + + +# Register a callback so invoke_leaf_function can retrieve nn.Module instances at runtime. +# We use a callback pattern instead of having invoke_leaf_function import get_external_object_by_index +# directly, because higher-order ops should not depend on dynamo (dynamo depends on them, not vice versa). +from torch._higher_order_ops.invoke_leaf_function import ( + set_leaf_function_module_retriever, +) + + +set_leaf_function_module_retriever(get_external_object_by_index) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_deduplication.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_deduplication.py new file mode 100644 index 0000000000000000000000000000000000000000..84d254b882c9550a31db70c34f3c33122df8dc8c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_deduplication.py @@ -0,0 +1,633 @@ +""" +This module implements graph deduplication functionality for TorchDynamo's optimization pipeline. +Graph deduplication identifies identical subgraphs in the computational graph and merges them +to reduce redundancy and improve performance. The process involves analyzing regions of the graph, +identifying structurally equivalent regions, and replacing them with a single shared implementation. +This optimization is particularly effective for models with repeated patterns or similar computational +structures across different parts of the network. +""" + +import logging +import operator +from collections import defaultdict, deque +from collections.abc import Generator, Iterable + +import torch +import torch.fx +from torch._dynamo import config +from torch.multiprocessing.reductions import StorageWeakRef +from torch.utils._ordered_set import OrderedSet + +from .graph_region_tracker import Node, Region +from .graph_utils import _detect_cycles, _get_flat_args, _get_flat_args_unique + + +# Represents an index into the region +# to select a node and then +# an index into that node's +# flattened arguments +UsageIndex = tuple[int, int] + +log = logging.getLogger(__name__) + +last_node_to_additional_deps: dict[Node, OrderedSet[Node]] | None = None + + +def apply_graph_deduplication(output_graph) -> dict[str, torch.fx.GraphModule]: # type: ignore[no-untyped-def] + """ + This is the main entry point for applying the graph deduplication pass. \ +Deduplication occurs in two phases: + 1. Subgraph creation: + Subgraph creation works by taking one representative region from each region \ +group and creating a subgraph from it, which will then be used to replace all regions \ +in the group. This is implemented by first copying all nodes of the region to the new \ +subgraph and then finding all inputs which are not within the region and creating placeholders \ +for them. For the outputs, all regions in a region group need to be scanned to ensure the \ +largest set of outputs is found, and then an output node is created which returns \ +a tuple of all outputs. + + 2. Graph replacement: + To replace each region with the extracted subgraph, the node index in the region \ +and argument index within the node's flattened args and kwargs are recorded once during \ +subgraph creation. This allows us to determine which (external to the region) nodes and \ +in which order these nodes are passed as inputs. For the outputs, getitem nodes are created \ +for each output, and all nodes in the region with external outputs are replaced by the proper \ +getitem node. Finally, all original nodes are erased (there should be no uses of these \ +left in the graph). + +The deduplication mutates the output_graph argument in place. + +Returns a mapping of nodes to their subgraph output replacement node to remap outputs +when they are created in output_graph. + """ + + duplicated_region_groups = output_graph.region_tracker.get_identical_regions( + output_graph.graph + ) + node_to_mutated_arg_positions = ( + output_graph.region_tracker.node_to_mutated_arg_positions + ) + node_to_additional_deps = _populate_additional_deps( + output_graph.graph, output_graph.region_tracker.node_to_mutated_arg_positions + ) + + sub_gms: dict[str, torch.fx.GraphModule] = {} + + for region_group in duplicated_region_groups: + inds_with_external_users = _get_all_output_indices(region_group) + region = region_group[0] + ( + subgraph, + external_node_usages, + node_usage_to_tuple_elems, + ind_to_tuple_spec, + ) = _create_subgraph(region, inds_with_external_users) + + # Ignore regions with no args for now, could they possibly be evaluated at compile time? + if not list(external_node_usages): + continue + + sub_gm = torch.fx.GraphModule(output_graph.nn_modules, subgraph) + subgraph_name = output_graph.install_subgraph("subgraph", sub_gm) + sub_gms[subgraph_name] = sub_gm + with output_graph.graph.inserting_before(): + get_subgraph_node = output_graph.graph.create_node( + "get_attr", subgraph_name, (), {} + ) + + for region in region_group: + _replace_region_with_subgraph( + output_graph.graph, + region, + get_subgraph_node, + external_node_usages, + node_usage_to_tuple_elems, + ind_to_tuple_spec, + inds_with_external_users, + subgraph_name, + node_to_additional_deps, + node_to_mutated_arg_positions, + ) + + # This is to expose the updated node_to_additional_deps to tests + global last_node_to_additional_deps + last_node_to_additional_deps = node_to_additional_deps + + _stable_topological_sort( + output_graph.graph, + node_to_additional_deps, + ) + return sub_gms + + +def _replace_region_with_subgraph( + graph: torch.fx.Graph, + region: Region, + get_subgraph_node: Node, + external_node_usages: Iterable[OrderedSet[UsageIndex]], + node_usage_to_tuple_elems: dict[UsageIndex, OrderedSet[int]], + ind_to_tuple_spec: dict[int, dict[tuple[int, ...], int]], + inds_with_external_users: list[int], + subgraph_name: str, + node_to_additional_deps: dict[Node, OrderedSet[Node]], + node_to_mutated_arg_positions: dict[Node, OrderedSet[int]], +) -> None: + sub_args = [] + flattened_getitem_nodes: OrderedSet[Node] = OrderedSet() + for usages in external_node_usages: + usage = next(iter(usages)) + node_ind, usage_ind = usage + node = region[node_ind] + flattened_args_kwargs = _get_flat_args(node, {}) + for user_ind, node_usage_ind in usages: + user = region[user_ind] + if user in node_to_mutated_arg_positions: + if node_usage_ind in node_to_mutated_arg_positions[user]: + log.debug( + "NYI: Failed to substitute region %s due to mutation", region + ) + return + if usage in node_usage_to_tuple_elems: + tuple_elems = [region[i] for i in node_usage_to_tuple_elems[usage]] + flattened_getitem_nodes.update(tuple_elems) + sub_args.extend(tuple_elems) + else: + sub_args.append(flattened_args_kwargs[usage_ind]) + + # Input/Output aliasing not supported in HOPs today + # Note: we should use the nodes in the original graph (the region here) + # because we use the original traced example values for this check + if _has_aliasing( + region, sub_args, inds_with_external_users, flattened_getitem_nodes + ): + return + + invoke_args = (get_subgraph_node, subgraph_name, *sub_args) + + invoke_subgraph_node = graph.create_node( + "call_function", + torch.ops.higher_order.invoke_subgraph, + invoke_args, # type: ignore[arg-type] + {}, + ) + + ind = 0 + flattened_output_nodes: OrderedSet[Node] = OrderedSet() + for external_user_ind in inds_with_external_users: + node = region[external_user_ind] + if _is_tuple_node(node): + tuple_spec = ind_to_tuple_spec[external_user_ind] + flattened_output_nodes.update( + _replace_tuple_outputs( + node, ind, tuple_spec, invoke_subgraph_node, graph + ) + ) + ind += len(tuple_spec) + else: + subgraph_output = graph.create_node( + "call_function", operator.getitem, (invoke_subgraph_node, ind), {} + ) + node.replace_all_uses_with(subgraph_output, propagate_meta=True) + ind += 1 + + # Erase in reverse topological order + for node in reversed(region): + if node in flattened_getitem_nodes: + # Don't erase these, since they will still be used + continue + + if node not in flattened_output_nodes: + graph.erase_node(node) + + # Remove any nodes with additional deps + # This is safe; we've guaranteed that there is + # no input mutation, so all additional deps + # will be internal to the subgraph + node_to_additional_deps.pop(node, None) + for deps in node_to_additional_deps.values(): + try: + deps.remove(node) + deps.add(invoke_subgraph_node) + except KeyError: + pass + + if config.graph_deduplication_lint: + print(_detect_cycles(graph, node_to_additional_deps)) + _stable_topological_sort(graph, node_to_additional_deps) + graph.lint() + + +def _get_external_inputs( + region: Region, +) -> dict[Node, OrderedSet[UsageIndex]]: + external_node_to_usages = defaultdict[Node, OrderedSet[UsageIndex]](OrderedSet) + region_unique = set(region) + for node_ind, node in enumerate(region): + flattened_args_kwargs = _get_flat_args(node, {}) + for arg_ind, in_node in enumerate(flattened_args_kwargs): + if isinstance(in_node, Node) and in_node not in region_unique: + # in_node may occur in multiple nodes' flat_args + # track this so we can check if the arg is mutated + # Previously, we only needed to track one occurrence + # to be able to map that node to a placeholder + external_node_to_usages[in_node].add((node_ind, arg_ind)) + + return external_node_to_usages + + +def _get_all_output_indices(regions: list[Region]) -> list[int]: + # Scan all regions to get the set of all possible output nodes indices in the region + # perhaps we can record this information during region creation for more efficiency? + inds_with_external_users: set[int] = set() + for region in regions: + _get_inds_with_external_users(region, inds_with_external_users) + + return sorted(inds_with_external_users) + + +def _get_inds_with_external_users(region: Region, inds_unique: set[int]) -> None: + for ind, node in enumerate(region): + for user in node.users: + if user not in region: + if ind not in inds_unique: + inds_unique.add(ind) + + +def _create_subgraph( + region: Region, + inds_with_external_users: list[int], +) -> tuple[ + torch.fx.Graph, + list[OrderedSet[UsageIndex]], + dict[UsageIndex, OrderedSet[int]], + dict[int, dict[tuple[int, ...], int]], +]: + subgraph: torch.fx.Graph = torch.fx.Graph() + external_input_to_usages = _get_external_inputs(region) + external_node_usages = list[OrderedSet[UsageIndex]]() + region_to_subgraph_node = {} + flattened_getitem_nodes: OrderedSet[Node] = OrderedSet() + node_usage_to_tuple_elems: dict[UsageIndex, OrderedSet[int]] = {} + + for node, usage_indices in external_input_to_usages.items(): + # We don't handle tuples as inputs today + if _is_tuple_node(node): + # If a node is a tuple we will possibly create multiple placeholders for them + # and track which nodes we won't copy into the subgraph because they are flattened away + # Later, when replacing each region with this subgraph, we will create a getitem node + # externally which will perform the flattening on the outer nodes. + flattened_node_indices = _get_flattened_node_indices(node, region) + for ind in flattened_node_indices: + placeholder = subgraph.placeholder( + f"supgraph_input_{node.name}_flattened_{ind}" + ) + region_to_subgraph_node[region[ind]] = placeholder + flattened_getitem_nodes.add(region[ind]) + node_usage_to_tuple_elems[next(iter(usage_indices))] = ( + flattened_node_indices + ) + else: + placeholder = subgraph.placeholder(f"subgraph_input_{node.name}") + region_to_subgraph_node[node] = placeholder + + external_node_usages.append(usage_indices) + + def map_arg(node: Node) -> Node: + if node in region_to_subgraph_node: + return region_to_subgraph_node[node] + else: + return node + + def copy_to_subgraph(node: Node) -> Node: + subgraph_node = subgraph.node_copy(node, lambda old: map_arg(old)) + region_to_subgraph_node[node] = subgraph_node + return subgraph_node + + output_list = [] + ind_to_tuple_spec = {} + for ind, node in enumerate(region): + if node not in flattened_getitem_nodes: + subgraph_node = copy_to_subgraph(node) + if ind in inds_with_external_users: + # flatten tuple outputs by generating a getitem node tree + if _is_tuple_node(node): + getitem_nodes, ind_to_tuple_spec[ind] = _create_getitem_nodes( + node, subgraph_node, subgraph + ) + output_list.extend(getitem_nodes) + else: + output_list.append(subgraph_node) + + subgraph.output(tuple(output_list)) + + return subgraph, external_node_usages, node_usage_to_tuple_elems, ind_to_tuple_spec + + +def _stable_topological_sort_impl( + graph: torch.fx.Graph, + node_to_additional_deps: dict[Node, OrderedSet[Node]], + do_sort: bool = True, + region: OrderedSet[Node] | None = None, +) -> bool: + # Nodes are in exactly one of these four collections: + + # - Nodes in `pending` are waiting to be processed (in reverse order): + pending = list(reversed(region or graph.nodes)) + + # - Nodes in `ready` have been processed and are already in the correct + # order. When sorting a region, nodes outside the region are + # implicitly ready (filtered out in the waiting_for check below). + ready: set[Node] = set() + + # - `waiting` is a mapping from a dependency to nodes which depend on that + # dependency. + waiting = defaultdict(list) + + # - `outputs` are always at the end of the graph + outputs = OrderedSet[Node]() + + has_additional_deps = bool(node_to_additional_deps) + + # The cursor indicates the last processed node so we can add new nodes + # after it. + cursor = None + while pending: + node = pending.pop() + + if node.op == "output": + outputs.add(node) + if node.users: + raise AssertionError("output nodes should have no users") + continue + + # node._input_nodes is maintained by FX and already contains the + # unique set of input nodes — avoid rebuilding it via map_arg. + if has_additional_deps: + deps = _get_flat_args_unique(node, node_to_additional_deps) + else: + deps = node._input_nodes + + last_unready = None + for x in deps: + if x not in ready and (region is None or x in region): + last_unready = x + if last_unready is not None: + # We have unprocessed input nodes. Wait for the last unready + # arg so an already sorted list will only recheck this node once. + waiting[last_unready].append(node) + else: + ready.add(node) + if cursor and cursor.next is not node and do_sort: + cursor.append(node) + cursor = node + # Mark the nodes that have been waiting for this node to finish as + # ready to check again. + pending.extend(reversed(waiting.pop(node, ()))) + + ready.update(outputs) + expected_len = len(region) if region is not None else len(graph.nodes) + return not waiting and len(ready) == expected_len + + +def _stable_topological_sort( + graph: torch.fx.Graph, + node_to_additional_deps: dict[Node, OrderedSet[Node]], +) -> None: + if not _stable_topological_sort_impl(graph, node_to_additional_deps): + raise AssertionError("stable topological sort failed") + + +def _stable_topological_sort_region( + graph: torch.fx.Graph, + region: OrderedSet[Node], +) -> None: + if not _stable_topological_sort_impl(graph, {}, region=region): + raise AssertionError("stable topological sort of region failed") + + +def _has_cycle( + graph: torch.fx.Graph, + node_to_additional_deps: dict[Node, OrderedSet[Node]], +) -> bool: + return not _stable_topological_sort_impl( + graph, node_to_additional_deps, do_sort=False + ) + + +def _populate_additional_deps( + graph: torch.fx.Graph, node_to_mutated_arg_positions: dict[Node, OrderedSet[int]] +) -> dict[Node, OrderedSet[Node]]: + node_to_additional_deps: dict[Node, OrderedSet[Node]] = defaultdict(OrderedSet) + _add_mutation_dependencies(node_to_mutated_arg_positions, node_to_additional_deps) + _add_global_state_dependencies(graph, node_to_additional_deps) + return node_to_additional_deps + + +def _add_global_state_dependencies( + graph: torch.fx.Graph, node_to_additional_deps: dict[Node, OrderedSet[Node]] +) -> None: + import torch.amp + + all_nodes = list(graph.nodes) + + # These are targets of the nodes which need to stay in the same relative place in the graph + global_state_targets = {torch.amp._enter_autocast, torch.amp._exit_autocast} + all_nodes_dep_on: list[Node] = [] + + def prev_cur_nodes( + all_nodes: list[Node], + ) -> Generator[tuple[list[Node], Node], None, None]: + prev_nodes: list[Node] = [] + next_nodes = list(reversed(all_nodes)) + + while next_nodes: + cur_node = next_nodes.pop() + yield prev_nodes, cur_node + prev_nodes.append(cur_node) + + for prev_nodes, cur_node in prev_cur_nodes(all_nodes): + args_unique = _get_flat_args_unique(cur_node, {}) + new_deps = [n for n in all_nodes_dep_on if n not in args_unique] + + if new_deps: + additional_deps = node_to_additional_deps[cur_node] + additional_deps.update(new_deps) + + if cur_node.target in global_state_targets: + additional_deps = node_to_additional_deps[cur_node] + additional_deps.update(n for n in prev_nodes if n not in args_unique) + all_nodes_dep_on.append(cur_node) + + +def _add_mutation_dependencies( + node_to_mutated_arg_positions: dict[Node, OrderedSet[int]], + node_to_additional_deps: dict[Node, OrderedSet[Node]], +) -> None: + for node, indices in node_to_mutated_arg_positions.items(): + flat_args_kwargs = _get_flat_args(node, {}) + + # for all mutated args, + # add dependency on usages which occur after node to ensure + # node will always be ordered before them + # also add node as a dependency on usages which + # occur before node to ensure node is ordered after them + for index in indices: + mutated_arg = flat_args_kwargs[index] + for user in mutated_arg.users: + if user is node: + continue + + elif user < node: + node_to_additional_deps[node].add(user) + + elif user > node: + node_to_additional_deps[user].add(node) + + +def _has_aliasing( + region: Region, + inputs: list[Node], + inds_with_external_users: list[int], + flattened_getitem_nodes: OrderedSet[Node], +) -> bool: + input_storages: dict[StorageWeakRef, Node] = dict() + for node in inputs: + if node in flattened_getitem_nodes: + continue + example_value = node.meta["example_value"] + if isinstance(example_value, torch.Tensor): + storage = StorageWeakRef(example_value._typed_storage()) + if storage in input_storages: + # input-input aliasing + log.debug( + "NYI: Failed to substitute region %s due to input-output aliasing detected at nodes %s, %s", + region, + input_storages[storage], + node, + ) + return True + input_storages[storage] = node + output_storages: dict[StorageWeakRef, Node] = dict() + for i in inds_with_external_users: + out_node = region[i] + if out_node in flattened_getitem_nodes: + continue + if out_node: + example_value = out_node.meta["example_value"] + if isinstance(example_value, list): + raise AssertionError("expected example_value to not be a list") + if isinstance(example_value, torch.Tensor): + storage = StorageWeakRef(example_value._typed_storage()) + if storage in output_storages: + # output-output aliasing + log.debug( + "NYI: Failed to substitute region %s due to output-output aliasing detected at nodes %s, %s", + region, + output_storages[storage], + out_node, + ) + return True + output_storages[storage] = out_node + intersected_storages = input_storages.keys() & output_storages.keys() + if len(intersected_storages) > 0: + # input-output aliasing + aliased = [ + (input_storages[s], output_storages[s]) for s in intersected_storages + ] + aliased = ", ".join([f"{i} and {o}" for i, o in aliased]) + log.debug( + "NYI: Failed to substitute region %s due to input-output aliasing detected at nodes %s", + region, + aliased, + ) + return True + return False + + +def _is_tuple_node(node: Node) -> bool: + return isinstance(node.meta["example_value"], tuple) + + +def _get_children_getitems(node: Node) -> Generator[Node, None, None]: + for user in node.users: + if user.target is operator.getitem and isinstance(user.args[1], int): + yield user + + +def _get_flattened_node_indices(node: Node, region: Region) -> OrderedSet[int]: + """Returns an ordered set of indices, each representing a node in the region which will be flattened""" + flattened_node_to_ind = {n: i for i, n in enumerate(region)} + node_indices: OrderedSet[int] = OrderedSet() + queue = deque(_get_children_getitems(node)) + while queue: + cur_node = queue.popleft() + if any(user in region for user in cur_node.users): + node_indices.add(flattened_node_to_ind[cur_node]) + for child in _get_children_getitems(cur_node): + queue.append(child) + return node_indices + + +def _create_getitem_nodes( + node: Node, subgraph_tuple_node: Node, subgraph: torch.fx.Graph +) -> tuple[list[Node], dict[tuple[int, ...], int]]: + tup = node.meta["example_value"] + if not isinstance(tup, tuple): + raise AssertionError("_get_getitem_children expects tuple") + + getitem_nodes: list[Node] = [] + queue = deque([(e, (i,), subgraph_tuple_node) for i, e in enumerate(tup)]) + path_to_output_index = {} + + while queue: + cur_elem, path, parent = queue.popleft() + + with subgraph.inserting_after(parent): + new_getitem_node = subgraph.create_node( + "call_function", operator.getitem, (parent, path[-1]), {} + ) + new_getitem_node.meta["example_value"] = cur_elem + + path_to_output_index[path] = len(getitem_nodes) + getitem_nodes.append(new_getitem_node) + + if isinstance(cur_elem, tuple): + queue.extend( + [(e, path + (i,), new_getitem_node) for i, e in enumerate(cur_elem)] # type: ignore[arg-type,misc] + ) + + return getitem_nodes, path_to_output_index # type: ignore[return-value] + + +def _replace_tuple_outputs( + node: Node, + output_index: int, + tuple_spec: dict[tuple[int, ...], int], + invoke_subgraph_node: Node, + graph: torch.fx.Graph, +) -> OrderedSet[Node]: + if not _is_tuple_node(node): + raise AssertionError("_replace_tuple_outputs expects a tuple node") + + queue = deque((c, (c.args[1],)) for c in _get_children_getitems(node)) + erased_nodes: OrderedSet[Node] = OrderedSet() + while queue: + cur_node, path = queue.pop() + + for c in _get_children_getitems(cur_node): + queue.append((c, path + (c.args[1],))) # type: ignore[return-value, arg-type] + + with graph.inserting_after(invoke_subgraph_node): + subgraph_output = graph.create_node( + "call_function", + operator.getitem, + (invoke_subgraph_node, output_index + tuple_spec[path]), # type: ignore[index] + {}, + ) + cur_node.replace_all_uses_with(subgraph_output, propagate_meta=True) + graph.erase_node(cur_node) + erased_nodes.add(cur_node) + + graph.erase_node(node) + erased_nodes.add(node) + return erased_nodes diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_id_filter.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_id_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..c5349d53a44f7e578dfc6f604ad5732f3efce796 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_id_filter.py @@ -0,0 +1,474 @@ +# mypy: disallow-untyped-defs + +from __future__ import annotations + +import functools +import logging +import re +import warnings +from typing import Any, Generic, TYPE_CHECKING, TypeVar + + +if TYPE_CHECKING: + from collections.abc import Callable + + from torch._guards import CompileId + + +log = logging.getLogger(__name__) + + +class GraphIdFilter: + """ + A filter for matching graph IDs based on various conditions. + Supports individual IDs, ranges, and comparison operators. + """ + + def __init__(self, filter_str: str) -> None: + self._explicit_ids: frozenset[int] = frozenset() + self._conditions: list[tuple[str, int]] = [] + self._parse(filter_str) + + def _parse(self, filter_str: str) -> None: + if not filter_str or not filter_str.strip(): + return + + explicit_ids: set[int] = set() + conditions: list[tuple[str, int]] = [] + + # Pattern for comparison operators (>=, >, <=, <) followed by a number + cmp_pattern = re.compile(r"^(>=|>|<=|<)(\d+)$") + # Pattern for ranges like "10-20" + range_pattern = re.compile(r"^(\d+)-(\d+)$") + + for part in filter_str.split(","): + part = part.strip() + if not part: + continue + + if match := cmp_pattern.match(part): + conditions.append((match.group(1), int(match.group(2)))) + elif match := range_pattern.match(part): + start, end = int(match.group(1)), int(match.group(2)) + explicit_ids.update(range(start, end + 1)) + else: + try: + explicit_ids.add(int(part)) + except ValueError: + log.warning("Invalid graph ID filter: %s", part) + + self._explicit_ids = frozenset(explicit_ids) + self._conditions = conditions + + def __contains__(self, graph_id: int) -> bool: + """Check if the given graph ID matches this filter.""" + if graph_id in self._explicit_ids: + return True + + for op, val in self._conditions: + if op == ">" and graph_id > val: + return True + elif op == ">=" and graph_id >= val: + return True + elif op == "<" and graph_id < val: + return True + elif op == "<=" and graph_id <= val: + return True + + return False + + def __repr__(self) -> str: + # pyrefly: ignore [implicit-any] + parts = [] + if self._explicit_ids: + parts.append(f"ids={sorted(self._explicit_ids)}") + if self._conditions: + parts.append(f"conditions={self._conditions}") + return f"GraphIdFilter({', '.join(parts) if parts else 'empty'})" + + +T = TypeVar("T") + + +class _GraphRouterBase(Generic[T]): + """ + Base class for routing graphs to different values based on their IDs. + + The router parses a configuration string with rules in the format: + "filter1:value1;filter2:value2;..." + + Rules are evaluated in order, and the first matching rule wins. + """ + + def __init__(self, config_str: str, rule_type: str) -> None: + self._rules: list[tuple[GraphIdFilter, T]] = [] + self._values: list[T | None] = [] + self._overflow_value: T | None = None + self._rule_type = rule_type + self._parse(config_str) + self._precompute() + + def _parse_value_str(self, value_str: str) -> T | None: + """Parse a value string into the appropriate type. Returns None to skip.""" + raise NotImplementedError + + def _parse(self, config_str: str) -> None: + if not config_str or not config_str.strip(): + return + + rule_strs = config_str.split(";") + for rule_str in rule_strs: + rule_str = rule_str.strip() + if not rule_str: + continue + + colon_idx = rule_str.find(":") + if colon_idx == -1: + log.warning( + "Invalid %s override rule (missing ':'): %s", + self._rule_type, + rule_str, + ) + continue + + filter_str = rule_str[:colon_idx].strip() + value_str = rule_str[colon_idx + 1 :].strip() + + if not filter_str or not value_str: + log.warning("Invalid %s override rule: %s", self._rule_type, rule_str) + continue + + value = self._parse_value_str(value_str) + if value is not None: + self._rules.append((GraphIdFilter(filter_str), value)) + + def _precompute(self) -> None: + if not self._rules: + return + + # Find max ID from explicit IDs and comparison thresholds + max_id = 0 + for f, _ in self._rules: + if f._explicit_ids: + max_id = max(max_id, *f._explicit_ids) + for _, val in f._conditions: + max_id = max(max_id, val) + + # Pre-compute values for IDs 0 to max_id + for i in range(max_id + 1): + self._values.append(self._match_rules(i)) + + # For IDs > max_id, the result is constant (only unbounded conditions apply) + self._overflow_value = self._match_rules(max_id + 1) + + def _match_rules(self, graph_id: int) -> T | None: + for f, value in self._rules: + if graph_id in f: + return value + return None + + def get_value_for_graph(self, graph_id: int) -> T | None: + """Get the value for a given graph ID. Returns None if no rule matches.""" + if graph_id < len(self._values): + return self._values[graph_id] + return self._overflow_value + + def is_empty(self) -> bool: + """Check if no rules are configured.""" + return len(self._rules) == 0 + + +class GraphBackendRouter(_GraphRouterBase[Any]): + """ + Routes graphs to different backends based on their IDs. + + The router parses a configuration string with rules in the format: + "filter1:backend1;filter2:backend2;..." + + If a graph ID matches multiple rules with different backends, a ValueError + is raised. + + Examples: + "0-5:eager;>5:inductor" - IDs 0-5 use eager, rest use inductor + ">10:aot_eager" - IDs > 10 use aot_eager + "<=3:eager;4-10:aot_eager" - IDs 0-3 use eager, 4-10 use aot_eager + + Supported backends include "eager", "aot_eager", "aot_eager_decomp_partition", + "inductor", and any other registered backend. + """ + + def __init__(self, config_str: str) -> None: + self._backend_names: dict[int, str] = {} + super().__init__(config_str, "backend") + + def _parse_value_str(self, value_str: str) -> Any | None: + """Look up a backend by name.""" + from .backends.registry import lookup_backend + from .eval_frame import cached_backends + + backend = lookup_backend(value_str) + + # Register the backend so its reset() is called during torch._dynamo.reset() + if backend is None: + raise AssertionError("Invalid override backend: " + value_str) + cached_backends.setdefault(id(backend), backend) + self._backend_names[id(backend)] = value_str + return backend + + def _match_rules(self, graph_id: int) -> Any | None: + """Match rules with conflict detection for overlapping filters.""" + matches = {id(backend): backend for f, backend in self._rules if graph_id in f} + if len(matches) > 1: + names = [self._backend_names[bid] for bid in matches] + raise ValueError( + f"Conflicting backend override for graph {graph_id}: matched {names}" + ) + if matches: + return next(iter(matches.values())) + return None + + def __repr__(self) -> str: + if not self._rules: + return "GraphBackendRouter(empty)" + return f"GraphBackendRouter({self._rules})" + + +class GraphConfigRouter(_GraphRouterBase[dict[str, Any]]): + """ + Routes graphs to different inductor configs based on their IDs. + + The router parses a configuration string with rules in the format: + "filter1:config1;filter2:config2;..." + + All matching rules are aggregated: configs from all matching rules are merged + into a single dict. Conflicting keys (same key, different value) raise an error. + Config format is "key=value" or "key1=value1,key2=value2" for multiple settings. + + Examples: + "0-5:triton.cudagraph_skip_dynamic_graphs=False" + ">10:triton.cudagraphs=False,triton.cudagraph_trees=False" + + With "0:a=1;>=0:b=2", graph 0 gets {"a": 1, "b": 2} (both rules match). + With "0:a=1;>=0:a=2", graph 0 raises an error (conflicting values for "a"). + With "0:a=1;>=0:a=1", graph 0 gets {"a": 1} (same value is not a conflict). + """ + + def __init__(self, config_str: str) -> None: + super().__init__(config_str, "config") + + @staticmethod + def _parse_scalar_value(value_str: str) -> Any: + """Parse a string value into the appropriate Python type.""" + value_str = value_str.strip() + if value_str.lower() == "true": + return True + if value_str.lower() == "false": + return False + if value_str.lower() == "none": + return None + try: + if "." in value_str: + return float(value_str) + return int(value_str) + except ValueError: + return value_str + + def _match_rules(self, graph_id: int) -> dict[str, Any] | None: + """Aggregate configs from all matching rules. Conflicts raise an error.""" + result: dict[str, Any] = {} + for f, value in self._rules: + if graph_id in f: + for k, v in value.items(): + if k in result and result[k] != v: + raise ValueError( + f"Conflicting config override for graph {graph_id}: " + f"key '{k}' has value {result[k]!r} and {v!r}" + ) + result[k] = v + return result if result else None + + def _parse_value_str(self, value_str: str) -> dict[str, Any] | None: + """Parse a config string like 'key1=val1,key2=val2' into a dict.""" + result: dict[str, Any] = {} + for item in value_str.split(","): + item = item.strip() + if not item: + continue + if "=" not in item: + log.warning("Invalid config item (missing '='): %s", item) + continue + key, value = item.split("=", 1) + result[key.strip()] = self._parse_scalar_value(value) + return result if result else None + + def __repr__(self) -> str: + if not self._rules: + return "GraphConfigRouter(empty)" + return f"GraphConfigRouter({self._rules})" + + +def _get_override_for_compile_id( + compile_id: CompileId | None, + config_str: str, + create_router: Callable[[str], _GraphRouterBase[T]], + label: str, +) -> T | None: + """ + Get the override value for a given CompileId. + + Returns the value from the router, or None if no override applies. + """ + if compile_id is None or not config_str: + return None + + graph_id = compile_id.frame_id + if graph_id is None: + return None + + router = create_router(config_str) + value = router.get_value_for_graph(graph_id) + if value is not None: + log.info("Overriding %s: %s", label, value) + return value + + +@functools.lru_cache +def _create_backend_router(config_str: str) -> GraphBackendRouter: + """Create and cache GraphBackendRouter instances based on config string.""" + return GraphBackendRouter(config_str) + + +@functools.lru_cache +def _validate_backend_names(config_str: str) -> str | None: + """Return an error message if any backend name is invalid, else None.""" + if not config_str or not config_str.strip(): + return None + from .backends.registry import lookup_backend + + for rule_str in config_str.split(";"): + rule_str = rule_str.strip() + if not rule_str or ":" not in rule_str: + continue + backend_name = rule_str[rule_str.find(":") + 1 :].strip() + if not backend_name: + continue + try: + lookup_backend(backend_name) + except Exception: + return ( + f"TORCH_COMPILE_OVERRIDE_BACKENDS: " + f"'{backend_name}' is not a valid backend, " + f"see `torch._dynamo.list_backends()` for available backends" + ) + return None + + +@functools.lru_cache +def _validate_inductor_config_keys(config_str: str) -> str | None: + """Return an error message if any config key is invalid, else None.""" + router = GraphConfigRouter(config_str) + from torch._inductor import config + + for _, config_dict in router._rules: + for key in config_dict: + if not hasattr(config, key): + return ( + f"TORCH_COMPILE_OVERRIDE_INDUCTOR_CONFIGS: " + f"'{key}' is not a valid torch._inductor.config option" + ) + return None + + +@functools.lru_cache +def _validate_dynamo_config_keys(config_str: str) -> str | None: + """Return an error message if any config key is invalid, else None.""" + router = GraphConfigRouter(config_str) + from torch._dynamo import config + + for _, config_dict in router._rules: + for key in config_dict: + if not hasattr(config, key): + return ( + f"TORCH_COMPILE_OVERRIDE_DYNAMO_CONFIGS: " + f"'{key}' is not a valid torch._dynamo.config option" + ) + return None + + +@functools.lru_cache +def _create_inductor_config_router(config_str: str) -> GraphConfigRouter: + """Create and cache GraphConfigRouter for inductor config overrides.""" + return GraphConfigRouter(config_str) + + +@functools.lru_cache +def _create_dynamo_config_router(config_str: str) -> GraphConfigRouter: + """Create and cache GraphConfigRouter for dynamo config overrides. + + Warns that dynamo config overrides are keyed by frame ID and some configs + can affect graph breaks, which may shift frame IDs. + """ + router = GraphConfigRouter(config_str) + if not router.is_empty(): + warnings.warn( + "TORCH_COMPILE_OVERRIDE_DYNAMO_CONFIGS is set. Dynamo config overrides are " + "keyed by frame ID. Some dynamo configs can affect graph breaks, " + "which may alter the number of frames and shift frame IDs, causing " + "overrides to target the wrong graphs.", + ) + return router + + +def get_backend_override_for_compile_id( + compile_id: CompileId | None, + config_str: str, +) -> Any: + """ + Get the backend override for a given CompileId. + + Returns the backend function to use, or None if no override applies. + """ + return _get_override_for_compile_id( + compile_id, + config_str, + _create_backend_router, + "torch.compile backend", + ) + + +def get_inductor_config_override_for_compile_id( + compile_id: CompileId | None, + config_str: str, +) -> dict[str, Any] | None: + """ + Get the inductor config override for a given CompileId. + + Returns a dict of config patches to apply, or None if no override applies. + """ + return _get_override_for_compile_id( + compile_id, + config_str, + _create_inductor_config_router, # type: ignore[arg-type] + "inductor config", + ) + + +def get_dynamo_config_override_for_compile_id( + compile_id: CompileId | None, + config_str: str, +) -> dict[str, Any] | None: + """ + Get the dynamo config override for a given CompileId. + + Returns a dict of config patches to apply, or None if no override applies. + """ + return _get_override_for_compile_id( + compile_id, + config_str, + _create_dynamo_config_router, # type: ignore[arg-type] + "dynamo config", + ) + + +# Keep old name for backwards compatibility +_create_router = _create_backend_router diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_region_tracker.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_region_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..325840dcdd8e6d700b3a41d99b05195c9cdf949c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_region_tracker.py @@ -0,0 +1,507 @@ +""" +This module provides functionality for tracking and managing regions in computational graphs. +It supports graph optimization by identifying and grouping similar regions based on their +structure and behavior. The module implements algorithms for: + +1. Tracking nodes and their relationships in the computational graph +2. Identifying identical or similar regions across the graph +3. Managing graph regions for optimization purposes +4. Supporting deduplication and other graph transformation passes + +The core functionality revolves around the GraphRegionTracker class which maintains +mappings between nodes and their duplicates, enabling efficient graph analysis and +optimization operations. +""" + +from __future__ import annotations + +import copyreg +import io +import logging +import math +import operator +import pickle +from collections import defaultdict, deque +from dataclasses import fields +from typing import Any, TYPE_CHECKING, TypeVar + +import torch._logging +import torch.fx +from torch._subclasses.fake_tensor import FakeTensor +from torch.utils._ordered_set import OrderedSet +from torch.utils._pytree import tree_flatten + +from .graph_utils import _get_flat_args_unique + + +T = TypeVar("T") + + +if TYPE_CHECKING: + from collections.abc import Callable + + from .symbolic_convert import InstructionTranslatorBase + + +Node = torch.fx.Node +Region = list[Node] +IdenticalNodes = list[Node] +GlobalStateKey = tuple[ + bool, + bool, + int, + tuple[bool, bool], + tuple[bool, bool], + torch.dtype, + bool, + bool, + bool, + bool, +] + +log = logging.getLogger(__name__) +graph_expansion_log = torch._logging.getArtifactLogger( + __name__, "graph_region_expansion" +) + + +def debug_log(msg: str, *args) -> None: # type: ignore[no-untyped-def] + graph_expansion_log.debug(msg, *args) + + +def _extract_tensor_metadata_for_node_hash( + x: torch.Tensor, +) -> tuple[Callable[[T], T], tuple[Any, ...]]: + from torch._inductor.codecache import _ident, extract_tensor_metadata_for_cache_key + + out = [] + metadata = extract_tensor_metadata_for_cache_key(x) + for field in fields(metadata): + out.append(getattr(metadata, field.name)) + + return (_ident, tuple(out)) + + +class NodeHashException(Exception): + pass + + +class InputPickler(pickle.Pickler): + def __init__(self) -> None: + from torch._inductor.codecache import _ident + + stream = io.BytesIO() + self._stream = stream + super().__init__(stream) + self.dispatch_table = copyreg.dispatch_table.copy() + self.dispatch_table.update( + { + FakeTensor: _extract_tensor_metadata_for_node_hash, + torch.SymInt: lambda x: (_ident, (str(x),)), + torch.SymBool: lambda x: (_ident, (str(x),)), + torch.SymFloat: lambda x: (_ident, (str(x),)), + } + ) + self.fast = True + + def dumps(self, obj: Any) -> bytes: + """ + Pickle an object and return a byte string. + """ + try: + self.dump(obj) + return self._stream.getvalue() + except (TypeError, AttributeError) as e: + raise NodeHashException from e + finally: + self._stream.seek(0) + self._stream.truncate(0) + + +def _extract_args(arg: Any) -> Any: + if isinstance(arg, Node): + return arg.meta.get("example_value") + elif isinstance(arg, (torch.Tensor, int)): + return arg + else: + return None + + +def _normalize_args( + node: Node, +) -> tuple[tuple[str, ...], tuple[Any | None, ...]]: + flat_args, _ = tree_flatten(node.args) + sorted_kwargs = sorted(node.kwargs.items(), key=operator.itemgetter(0)) + sorted_keys = tuple(sorted(node.kwargs.keys())) + flat_kwargs, _ = tree_flatten(sorted_kwargs) + all_args = flat_args + flat_kwargs + return (sorted_keys, tuple(_extract_args(arg) for arg in all_args)) + + +def _sort_with_ref_region( + index_to_rank: dict[int, int], regions: list[list[Any]] +) -> None: + # sort topologically + # we need to handle edge cases where some nodes have no dependencies + # so first we map each node to its ranking + ref_region = regions[0] + sorted_indices = sorted(range(len(ref_region)), key=lambda i: index_to_rank[i]) + for region in regions: + region[:] = [region[i] for i in sorted_indices] + + +def get_global_state_key() -> GlobalStateKey: + return ( + torch.is_grad_enabled(), + torch.is_inference_mode_enabled(), + torch.get_num_threads(), + torch._C._get_cublas_allow_fp16_reduced_precision_reduction(), + torch._C._get_cublas_allow_bf16_reduced_precision_reduction(), + torch.get_default_dtype(), + torch.are_deterministic_algorithms_enabled(), + torch._C._get_cublas_allow_tf32(), + torch.is_deterministic_algorithms_warn_only_enabled(), + torch._C._autograd._saved_tensors_hooks_is_enabled(), # type: ignore[attr-defined] + ) + + +# This is typical BFS with the caveat +# that a node's children need to be explicitly +# added with the add_children() method +# The flow is yield a node and check if it's valid for all regions +# if not valid, discard and continue onto the next node +# Note: this iterates backward through the graph by looking at args/kwargs +# of a node +class BackwardBfsArgIter: + def __init__(self, origin: Node) -> None: + self._cur: Node | None = origin + self._queue: deque[Node | None] = deque() + + @staticmethod + def create(origin: Node) -> BackwardBfsArgIter: + it = BackwardBfsArgIter(origin) + it.add_children(origin) + # pop the origin node, since it is the origin of + # the region and does not need to be considered for addition + if not it.next(): + raise AssertionError("expected origin node to be popped from iterator") + return it + + def next(self) -> Node | None: + ret = self._cur + if not self._queue: + self._cur = None + else: + self._cur = self._queue.popleft() + return ret + + def peek(self) -> Node | None: + return self._cur + + def add_children(self, node: Node) -> None: + flat_args = _get_flat_args_unique(node, {}) + for arg in flat_args: + if isinstance(arg, Node): + self._append(arg) + + def _append(self, arg: Node) -> None: + if self._cur is None: + self._cur = arg + else: + self._queue.append(arg) + + def __str__(self) -> str: + return f"BackwardBfsArgIter(cur={self._cur}, queue={self._queue})" + + +class GraphRegionTracker: + """ + GraphRegionTracker tracks each node added to the output graph and generates a key based on the source location, + instruction pointer, input shapes, and global state at the time the node is inserted into the graph. Nodes with + the same key are grouped together in a list of identical nodes (the value of node_to_duplicates). + + hash_to_duplicates: Dict[str, IdenticalNodes] - A dictionary mapping the key to a list of identical nodes + node_to_duplicates: Dict[Node, IdenticalNodes] - A dictionary mapping a node to the list of identical nodes it belongs to + input_pickler: InputPickler - An instance of InputPickler used to generate a node hash + """ + + def __init__(self) -> None: + self.hash_to_duplicates: dict[str, IdenticalNodes] = defaultdict(list) + self.node_to_duplicates: dict[Node, IdenticalNodes] = {} + # Note: position is in flattened args/kwargs list + self.node_to_mutated_arg_positions: dict[Node, OrderedSet[int]] = {} + self.input_pickler = InputPickler() + + def _hash_node( + self, filename: str, lineno: int, instruction_pointer: int | None, node: Node + ) -> str: + from torch._inductor.codecache import sha256_hash + + key = ( + get_global_state_key(), + filename, + lineno, + instruction_pointer, + _normalize_args(node), + ) + return sha256_hash(self.input_pickler.dumps(key)) + + def _is_identical(self, n0: Node, n1: Node) -> bool: + return ( + n0 in self.node_to_duplicates + and n1 in self.node_to_duplicates + and self.node_to_duplicates[n0] is self.node_to_duplicates[n1] + and n0 is not n1 + ) + + def track_node(self, tx: InstructionTranslatorBase, node: Node) -> None: + """ + The main entry point for tracking a node. This function will hash the node argument and group + nodes with the same hash together. It updates the hash_to_duplicates and node_to_duplicates dictionaries + to track the new node. + """ + try: + if ( + node not in self.node_to_duplicates + ): # don't allow nodes to be added twice + duplicates = self.hash_to_duplicates[ + self._hash_node( + tx.f_code.co_filename, tx.lineno, tx.instruction_pointer, node + ) + ] + duplicates.append(node) + self.node_to_duplicates[node] = duplicates + except NodeHashException as e: + log.debug("Unable to hash node %s with exception %s", node, e) + + def track_node_mutations( + self, + node: Node, + flat_args_kwargs: list[Any], + id_to_initial_version: dict[int, int], + ) -> None: + """ + This function tracks which argument positions are mutated by the given node. Subgraph HOP does not support + input mutations today so we will skip regions which have inputs that are mutated. + """ + mutated_arg_positions = OrderedSet[int]() + for i, arg in enumerate(flat_args_kwargs): + val_id = id(arg) + if ( + val_id in id_to_initial_version + and id_to_initial_version[val_id] != arg._version + ): + mutated_arg_positions.add(i) + + if mutated_arg_positions: + self.node_to_mutated_arg_positions[node] = mutated_arg_positions + + def add_node_mutation( + self, + node: Node, + arg_pos: int, + ) -> None: + if node in self.node_to_mutated_arg_positions: + self.node_to_mutated_arg_positions[node].add(arg_pos) + else: + self.node_to_mutated_arg_positions[node] = OrderedSet([arg_pos]) + + def get_identical_regions(self, graph: torch.fx.Graph) -> list[list[Region]]: + """ + This function is responsible for extracting the largest regions of identical nodes from the given graph. + **Note**: This function assumes the nodes that have been tracked with track_node are in the provided graph argument. + + The algorithm proceeds as follows: + The nodes tracked via track_node above are organized into region groups. The initial region groups look like this: + [[IdenticalNode1], [IdenticalNode2], [IdenticalNode3]] and each sublist is called a region. For each region group + (starting at the topologically latest region group), the inner regions are gradually expanded one node at time from + the flattened args and kwargs of the node in each region provided that for all regions in the group, the nodes being + added are also identical (ie have the same key computed by track_node). This is checked by verifying that the two + nodes have the same identical node list in node_to_duplicates. + """ + topological_ranking = {node: i for i, node in enumerate(graph.nodes)} + region_groups_with_rank = [] + # needed to detect if replacing a region will create cycles + node_to_recursive_ancestors = _populate_recursive_ancestor_map(graph) + + # Create region groups; a region group is a group + # of regions that are all identical. In this initial state + # each region in the group is a single node, and we discard + # groups that are only a single region. + # We track the topological ranking to start with groups later in the graph + # the reason for this is that we will necessarily create the largest groups first. + for group in self.hash_to_duplicates.values(): + if len(group) > 1: + # pyrefly: ignore [implicit-any] + region_group = [] + min_rank = math.inf + + for node in group: + # some nodes aren't in the topo ranking? + if node in topological_ranking: + min_rank = min(min_rank, topological_ranking[node]) + region_group.append([node]) + + if len(region_group) > 1: + region_groups_with_rank.append((region_group, min_rank)) + + region_groups_with_rank.sort(key=lambda rg: -rg[1]) + region_groups = [rg for rg, _ in region_groups_with_rank] + + # We start from regions later in the graph and expand them earlier + # as a result, we will create the largest regions first and they won't + # overlap. + seen_nodes: set[Node] = set() + for region_group in region_groups: + fully_expand_region_group( + region_group, + seen_nodes, + node_to_recursive_ancestors, + self._is_identical, + ) + # sort topologically + # we need to handle edge cases where some nodes have no dependencies + # so first we map each node to its ranking, + ref_region = region_group[0] + index_to_rank = { + index: topological_ranking[n] for index, n in enumerate(ref_region) + } + _sort_with_ref_region(index_to_rank, region_group) + + return [ + region_group for region_group in region_groups if len(region_group[0]) > 1 + ] + + def __str__(self) -> str: + return f"GraphRegionTracker(hash_to_duplicates={self.hash_to_duplicates}, node_to_duplicates={self.node_to_duplicates})" + + +class RegionWrapper: + """Holds state for regions e.g. ancestors and new candidate nodes for consideration""" + + def __init__( + self, region: Region, node_to_recursive_ancestors: dict[Node, set[Node]] + ) -> None: + if len(region) != 1: + raise AssertionError("all regions should start with one node") + node = region[0] + self.node_to_recursive_ancestors = node_to_recursive_ancestors + self.iter = BackwardBfsArgIter.create(node) + self.nodes_unique = OrderedSet([node]) + self.ancestors = set(node_to_recursive_ancestors[node]) + self.region = region + + def next_candidate(self) -> Node | None: + return self.iter.next() + + def will_inclusion_create_cycle(self, node: Node) -> bool: + external_users = [user for user in node.users if user not in self.nodes_unique] + for user in external_users: + if user in self.ancestors: + return True + + return False + + def add(self, node: Node) -> None: + self.nodes_unique.add(node) + self.region.append(node) + self.iter.add_children(node) + self.ancestors.update(self.node_to_recursive_ancestors[node]) + + +def fully_expand_region_group( + regions: list[Region], + seen_nodes: set[Node], + node_to_recursive_ancestors: dict[Node, set[Node]], + is_identical_fn: Callable[[Node, Node], bool], +) -> None: + debug_log("--------------------------------------------------") + debug_log("expanding new region group: %s", regions) + + # All regions should start with 1 node + if not all(len(region) == 1 for region in regions): + raise AssertionError("all regions should start with one node") + region_wrappers = [ + RegionWrapper(region, node_to_recursive_ancestors) for region in regions + ] + + nodes_to_add = OrderedSet[Node]() + current_node = region_wrappers[0].next_candidate() + + # No children + if current_node is None: + return + + # Loop incrementally adding new nodes to each region + # regions are only expanded if the node to add is valid + # for ALL regions + while current_node: + add_to_all_regions = not region_wrappers[0].will_inclusion_create_cycle( + current_node + ) + nodes_to_add.clear() + nodes_to_add.add(current_node) + for region_wrapper in region_wrappers[1:]: + candidate = region_wrapper.next_candidate() + + debug_log("--------------------") + debug_log( + "considering candidate: %s, cur_node: %s", candidate, current_node + ) + + if not candidate or not add_to_all_regions: + add_to_all_regions = False + continue + + debug_log( + "candidate in previously claimed nodes?: %s", candidate in seen_nodes + ) + debug_log("is_identical: %s", is_identical_fn(candidate, current_node)) + + add_to_all_regions &= ( + candidate not in seen_nodes + and candidate not in nodes_to_add + and candidate.op != "placeholder" + and candidate.op != "get_attr" + and is_identical_fn(candidate, current_node) + and not region_wrapper.will_inclusion_create_cycle(candidate) + ) + nodes_to_add.add(candidate) + + debug_log(f"add_to_all_regions: {add_to_all_regions}") + debug_log("--------------------") + + if add_to_all_regions: + if len(region_wrappers) != len(nodes_to_add): + raise AssertionError( + "Number of nodes to add must equal the number of regions" + ) + for region_wrapper, node in zip(region_wrappers, nodes_to_add): + region_wrapper.add(node) + debug_log("adding %s's children", node) + debug_log("%s %s", node.args, list(node.kwargs.items())) + seen_nodes.add(node) + + current_node = region_wrappers[0].next_candidate() + + # Ensure regions are sorted in topological order + for region in regions: + region.reverse() + + debug_log("end expand new region group: %s", regions) + debug_log("--------------------------------------------------") + + +def _populate_recursive_ancestor_map(graph: torch.fx.Graph) -> dict[Node, set[Node]]: + node_to_recursive_ancestors: dict[Node, set[Node]] = {} + for node in graph.nodes: + node_to_recursive_ancestors[node] = set() + for node in graph.nodes: + all_args = _get_flat_args_unique(node, {}) + for arg in all_args: + if isinstance(arg, Node): + node_to_recursive_ancestors[node].update( + node_to_recursive_ancestors[arg] + ) + node_to_recursive_ancestors[node].add(arg) + return node_to_recursive_ancestors diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_utils.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..68aea6f96e102b8d0f4808ffeacd4fa95f4cd023 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/graph_utils.py @@ -0,0 +1,117 @@ +from typing import Any + +import torch +from torch.fx import Graph, map_arg, Node +from torch.utils._ordered_set import OrderedSet +from torch.utils._pytree import tree_flatten + + +# flattens with support for slices +# Note: a better way to do this would +# be register/unregister slices as pytree nodes +# but there is no unregister API in the pytorch +# pytree impl +def _get_flat_args( + node: Node, node_to_additional_deps: dict[Node, OrderedSet[Node]] +) -> list[Node]: + args = list[Any]() + map_arg((node.args, node.kwargs), args.append) + if node in node_to_additional_deps: + args.extend(node_to_additional_deps[node]) + return args + + +def _get_flat_args_unique( + node: Node, node_to_additional_deps: dict[Node, OrderedSet[Node]] +) -> OrderedSet[Node]: + args = OrderedSet[Node]() + map_arg((node.args, node.kwargs), args.add) + if node in node_to_additional_deps: + args.update(node_to_additional_deps[node]) + return args + + +def _detect_cycles( + graph: Graph, node_to_additional_deps: dict[Node, OrderedSet[Node]] +) -> str: + # States: 0=Unvisited, 1=Visiting, 2=Visited(Safe) + state: dict[Node, int] = {} + + for root in reversed(graph.nodes): + if root in state: + continue + + # Stack holds (current_node, children_iterator). + # Using an iterator allows us to pause and resume processing a node's children. + stack = [(root, iter(_get_flat_args_unique(root, node_to_additional_deps)))] + state[root] = 1 # Visiting + + while stack: + parent, children = stack[-1] + + try: + child = next(children) + + if not isinstance(child, Node): + continue + + child_state = state.get(child, 0) + + if child_state == 1: + # Back-edge: child is on the current DFS path -> cycle + cycle_path = [node for node, _ in stack] + [child] + return f"cycle detected in path: {cycle_path}" + + if child_state == 0: + state[child] = 1 + stack.append( + ( + child, + iter(_get_flat_args_unique(child, node_to_additional_deps)), + ) + ) + # child_state == 2 means already verified safe; skip. + + except StopIteration: + # All children processed — mark safe and pop. + stack.pop() + state[parent] = 2 + + return "no cycle detected" + + +def _graph_device_type(graph: Graph | None) -> str: + if graph is None: + return "cpu" + + def _device_type(x: Any) -> str: + if isinstance(x, torch.device): + return x.type + if isinstance(x, torch.Tensor): + return x.device.type + return "cpu" + + def _flatten_meta(node: Node, key: str) -> list[Any]: + if key not in node.meta: + return [] + flat, _ = tree_flatten(node.meta[key]) + return flat + + for node in graph.nodes: + for key in ("val", "example_value"): + for obj in _flatten_meta(node, key): + return _device_type(obj) + + # Check for device conversions + if node.op == "call_method": + for gpu in ["cuda", "xpu"]: + if node.target == gpu: + return gpu + if node.target == "to" and gpu in node.args: + return gpu + + # Check args/kwargs for non-CPU device specs + flat_args, _ = tree_flatten((node.args, node.kwargs)) + for obj in flat_args: + return _device_type(obj) + return "cpu" diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/guards.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/guards.py new file mode 100644 index 0000000000000000000000000000000000000000..af820ad0862d5e9a5e33415602d52f04b5a0b1a4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/guards.py @@ -0,0 +1,5783 @@ +""" +Core guard system for Dynamo that detects when compiled code needs to be recompiled due to +changes in program state. Guards are conditions that must remain true for previously-compiled +code to be valid for reuse. + +This module provides the infrastructure for creating, managing and checking guards, including: +- Guard creation and composition +- Guard state management and invalidation +- Guard checking and failure handling +- Utilities for guard optimization and debugging +- Integration with Dynamo's compilation caching + +The guard system is critical for Dynamo's ability to efficiently reuse compiled code while +maintaining correctness by detecting when recompilation is necessary due to changes in +program state, tensor properties, or control flow. +""" + +from __future__ import annotations + +import ast +import builtins +import collections +import dataclasses +import enum +import functools +import importlib +import inspect +import io +import itertools +import logging +import math +import pickle +import sys +import textwrap +import traceback +import types +import warnings +import weakref +from contextlib import contextmanager +from copy import deepcopy +from inspect import currentframe +from typing import Any, cast, NamedTuple, NoReturn, TYPE_CHECKING +from typing_extensions import LiteralString, TypeAliasType, TypeVar +from weakref import ReferenceType + +import torch +import torch.overrides +import torch.utils._device +from torch._C._dynamo.eval_frame import code_framelocals_names +from torch._C._dynamo.guards import ( + check_obj_id, + check_type_id, + ClosureGuardAccessor, + CodeGuardAccessor, + dict_version, + DictGetItemGuardAccessor, + DictGuardManager, + FuncDefaultsGuardAccessor, + FuncKwDefaultsGuardAccessor, + GetAttrGuardAccessor, + GetGenericDictGuardAccessor, + GuardAccessor, + GuardDebugInfo, + GuardManager, + install_no_tensor_aliasing_guard, + install_object_aliasing_guard, + install_storage_overlapping_guard, + install_symbolic_shape_guard, + LeafGuard, + profile_guard_manager, + RelationalGuard, + RootGuardManager, + TupleGetItemGuardAccessor, + TypeDictGuardAccessor, + TypeGuardAccessor, + TypeMROGuardAccessor, +) +from torch._dynamo.source import ( + get_global_source_name, + get_local_source_name, + IndexedSource, + is_from_flatten_script_object_source, + is_from_local_source, + is_from_optimizer_source, + is_from_skip_guard_source, + is_from_unspecialized_builtin_nn_module_source, + TensorProperty, + TensorPropertySource, +) +from torch._dynamo.utils import CompileEventLogger, get_metrics_context +from torch._guards import ( + CompileContext, + CompileId, + DuplicateInputs, + Guard, + GuardBuilderBase, + GuardEnvExpr, + GuardSource, + Source, + StorageOverlap, +) +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import get_opaque_obj_info, is_opaque_constant_type +from torch._logging import structured +from torch._utils_internal import justknobs_check +from torch.fx.experimental.symbolic_shapes import ( + _CppShapeGuardsHelper, + _ShapeGuardsHelper, + EqualityConstraint, + is_symbolic, + SYMPY_INTERP, +) +from torch.utils import _pytree as pytree +from torch.utils._indented_buffer import IndentedBuffer +from torch.utils._ordered_set import OrderedSet +from torch.utils._traceback import format_frame, report_compile_source_on_error +from torch.utils.weak import TensorWeakRef + +from . import config, convert_frame, exc +from .eval_frame import set_guard_error_hook +from .source import ( + AttrProxySource, + AttrSource, + CallFunctionNoArgsSource, + CallMethodItemSource, + CellContentsSource, + ChainedSource, + ClosureSource, + CodeSource, + ConstantSource, + ConstDictKeySource, + ContextVarGetSource, + CurrentStreamSource, + DataclassFieldsSource, + DefaultsSource, + DictGetItemSource, + DictSubclassGetItemSource, + DynamicScalarSource, + FlattenScriptObjectSource, + FloatTensorSource, + FSDPNNModuleSource, + GenericAttrSource, + GetItemSource, + GlobalSource, + GlobalStateSource, + GlobalWeakRefSource, + GradSource, + ImportSource, + ListGetItemSource, + LocalSource, + NamedTupleFieldsSource, + NNModuleSource, + NonSerializableSetGetItemSource, + NumpyTensorSource, + OptimizerSource, + ScriptObjectQualifiedNameSource, + ShapeEnvSource, + SubclassAttrListSource, + TorchFunctionModeStackSource, + TupleIteratorGetItemSource, + TypeDictSource, + TypeMROSource, + TypeSource, + UnspecializedBuiltinNNModuleSource, + UnspecializedNNModuleSource, + UnspecializedParamBufferSource, + UnwrapCollectiveTensorSource, + WeakRefCallSource, +) +from .types import ( # noqa: F401 + CacheEntry, + DynamoFrameType, + ExtraState, + GuardedCode, + GuardFail, + GuardFilterEntry, + GuardFn, +) +from .utils import ( + builtin_dict_keys, + common_constant_types, + dataclass_fields, + dict_keys, + get_current_stream, + get_torch_function_mode_stack, + get_torch_function_mode_stack_at, + guard_failures, + istype, + key_is_id, + key_to_id, + normalize_count_iter, + normalize_range_iter, + orig_code_map, + set_getitem, + tuple_iterator_getitem, + tuple_iterator_len, + verify_guard_fn_signature, +) + + +if TYPE_CHECKING: + from collections.abc import Callable + + GuardCheckGetMetadataFn = Callable[[Guard, Any], Any] + GuardCheckEvalFn = Callable[[Any, Any], bool] + + +guard_manager_testing_hook_fn: Callable[[Any, Any, Any], Any] | None = None +_COUNT_ITERATOR_TYPE = type(itertools.count()) + +try: + import numpy as np +except ModuleNotFoundError: + np = None # type: ignore[assignment] + + +if TYPE_CHECKING: + from collections.abc import Generator, KeysView, Sequence, Sized + + from sympy import Symbol + + from torch._C import DispatchKeySet + from torch._dynamo.output_graph import OutputGraphCommon, OutputGraphGuardsState + from torch._dynamo.package import SerializedCode + from torch.utils._python_dispatch import TraceableWrapperSubclass + +T = TypeVar("T") +log = logging.getLogger(__name__) +guards_log = torch._logging.getArtifactLogger(__name__, "guards") +recompiles_log = torch._logging.getArtifactLogger(__name__, "recompiles") +recompiles_verbose_log = torch._logging.getArtifactLogger( + __name__, "recompiles_verbose" +) +verbose_guards_log = torch._logging.getArtifactLogger(__name__, "verbose_guards") + + +def _sequence_length(value: object) -> int: + if isinstance(value, set): + return set.__len__(value) + if isinstance(value, frozenset): + return frozenset.__len__(value) + return len(cast("Sized", value)) + + +_COW_TENSOR_UNSUPPORTED = object() + + +def _try_is_cow_tensor(value: object) -> bool | object: + if not isinstance(value, torch.Tensor): + return _COW_TENSOR_UNSUPPORTED + if torch._C._dispatch_keys(value).has(torch._C.DispatchKey.Python): + return _COW_TENSOR_UNSUPPORTED + return torch._C._is_cow_tensor(value) # pyrefly: ignore[missing-attribute] + + +def _cow_tensor_matches(value: object, expected: object) -> bool: + if not isinstance(expected, bool): + return False + actual = _try_is_cow_tensor(value) + return actual is not _COW_TENSOR_UNSUPPORTED and actual == expected + + +dunder_attrs_assumed_constants = ( + "__defaults__", + "__kwdefaults__", + "__code__", + "__closure__", + "__annotations__", + "__func__", + "__mro__", +) + + +def get_framelocals_idx(code: types.CodeType, var_name: str) -> int: + # Refer to index in the frame's localsplus directly. + # NOTE: name order for a code object doesn't change. + # NOTE: we need to find the LAST matching index because <= 3.10 contains + # duplicate names in the case of cells: a name can be both local and cell + # and will take up 2 slots of the frame's localsplus. The correct behavior + # is to refer to the cell, which has a higher index. + framelocals_names_reversed = code_framelocals_names_reversed_cached(code) + framelocals_idx = ( + len(framelocals_names_reversed) - framelocals_names_reversed.index(var_name) - 1 + ) + return framelocals_idx + + +class IndentedBufferWithPrefix(IndentedBuffer): + def prefix(self) -> str: + return "| " * (self._indent * self.tabwidth) + + def writeline(self, line: str, skip_prefix: bool = False) -> None: # type: ignore[override] + if skip_prefix: + super().writeline(line) + else: + super().writeline("+- " + line) + + +class GuardManagerWrapper: + """ + A helper class that contains the root guard manager. An instance of this + class is stored in the Dynamo cache entry, so that the cache entry can + access the RootGuardManager stored in the "root" attribute and directly call + the check_nopybind from C++. + """ + + def __init__( + self, + root: RootGuardManager | None = None, + local_state: Any | None = None, + ) -> None: + if root is None: + self.root = RootGuardManager() + else: + self.root = root + + if local_state is not None: + self.root.set_local_state(local_state) + + self.diff_guard_root: RootGuardManager | None = None + self.closure_vars: dict[str, Any] | None = None + self.args: list[str] | None = None + self.code_parts: list[str] = [] + self.verbose_code_parts: list[str] | None = None + self.global_scope: dict[str, Any] | None = None + self.guard_fail_fn: Callable[[GuardFail], None] | None = None + self.cache_entry: CacheEntry | None = None + self.extra_state: ExtraState | None = None + self.id_matched_objs: dict[str, ReferenceType[object]] = {} + self.no_tensor_aliasing_sources: list[str] = [] + + self.printed_relational_guards: set[RelationalGuard] = set() + + self.diff_guard_sources: OrderedSet[str] = OrderedSet() + + @contextmanager + def _preserve_printed_relational_guards(self) -> Generator[None, None, None]: + self.printed_relational_guards = set() + try: + yield + finally: + self.printed_relational_guards = set() + + # TODO: clarify what fn and attributes guard manager has to get the right things here + def collect_diff_guard_sources(self) -> OrderedSet[str]: + # At the time of finalize, we have only marked guard managers with + # TENSOR_MATCH guards as diff guard managers. So, we do a tree traversal + # and collect all the nodes in the tree (branches) that lead to tensor + # guards. + + # After a recompilation, some of guard managers will have a fail_count > + # 0, so we collect them as well. Later on, we accumulate the diff guard + # sources for all the guard managers. + + def visit_dict_manager(node: DictGuardManager) -> bool: + is_diff_guard_node = ( + node.get_source() in self.diff_guard_sources or node.fail_count() > 0 + ) + for _idx, (key_mgr, val_mgr) in sorted( + node.get_key_value_managers().items() + ): + is_diff_guard_node |= visit(key_mgr) | visit(val_mgr) + + if is_diff_guard_node: + self.diff_guard_sources.add(node.get_source()) + + return is_diff_guard_node + + def visit_manager(node: GuardManager) -> bool: + if isinstance(node, DictGuardManager): + raise AssertionError( + f"Expected non-DictGuardManager node, got {type(node)}" + ) + + is_diff_guard_node = ( + node.get_source() in self.diff_guard_sources or node.fail_count() > 0 + ) + for child_mgr in node.get_child_managers(): + is_diff_guard_node |= visit(child_mgr) + + if is_diff_guard_node: + self.diff_guard_sources.add(node.get_source()) + + return is_diff_guard_node + + def visit(node: GuardManager) -> bool: + if node is None: + return False + if isinstance(node, DictGuardManager): + return visit_dict_manager(node) + return visit_manager(node) + + visit(self.root) + + return self.diff_guard_sources + + def finalize(self) -> None: + if config.use_recursive_dict_tags_for_guards and justknobs_check( + "pytorch/compiler:use_recursive_dict_tags_for_guards" + ): + self.find_tag_safe_roots() + self.prepare_diff_guard_manager() + + def prepare_diff_guard_manager(self) -> None: + self.collect_diff_guard_sources() + self.populate_diff_guard_manager() + + def find_tag_safe_roots(self) -> None: + """ + Identify ``tag safe nodes`` and ``tag safe roots`` within a guard tree. + + ----------------------------------------------------------------------- + tag safe node + ----------------------------------------------------------------------- + A *tag safe node* is a ``GuardManager`` whose guarded value satisfies one + of the following conditions: + + 1. Immutable value - The value is intrinsically immutable according to + ``is_immutable_object``. Tensors are considered immutable. To ensure + that symbolic guards run, we also check that the GuardManager has no + accessors. + + 2. Nested tag safe dictionary - The value is a ``dict`` whose keys and + values are all tag safe nodes (checked recursively). Such dictionaries + allow entire nested structures to be skipped once their identity tag + matches. + + 3. Pure ``nn.Module`` - The value is an ``nn.Module`` whose sole + accessor is ``GetGenericDictGuardAccessor``—i.e., it only exposes its + ``__dict__`` and nothing else that could mutate between runs. + + For every tag safe node, verifying the identity/tag of just the top-level + dictionary is enough to guarantee the entire subtree is unchanged, enabling + a *fast-path* guard check. + + ----------------------------------------------------------------------- + tag safe root + ----------------------------------------------------------------------- + A ``tag safe root`` is a tag safe node whose parent is not tag safe. + These boundary nodes mark the points where guard evaluation can safely + prune traversal: if a tag-safe root's dictionary tag matches, the entire + subtree beneath it is skipped. + + One strong requirement for tag safe root is for the guarded object to + support weakref. Refer to more details in the Recursive dict tag + matching note. In short, we need to save the weakref of the object on + first invocation, and check if it is still valid in later iterations, to + apply recursive dict tag optimizations. `dict` objects do NOT support + weakref. Therefore, as of now, we only mark nn module related guard + managers as tag safe roots. + + Algorithm + --------- + The search runs in post-order traversal + + 1. Visit leaves and classify them as tag safe or not. + 2. Propagate tag-safety upward: a parent dictionary becomes tag safe only if + all of its children are already tag-safe. + 3. Propagate tag-safe-rootness upward: if the whole subtree is tag safe, + the current node becomes the new tag safe root, otherwise propagate the + subtree tag safe roots. + 4. Collect every tag safe node and, by inspecting parent tags, label the + subset that are tag safe roots. + """ + + def check_tag_safety( + node: GuardManager, accepted_accessors: tuple[type[GuardAccessor], ...] + ) -> bool: + accessors = node.get_accessors() + child_mgrs = node.get_child_managers() + return all( + isinstance(accessor, accepted_accessors) and mgr.is_tag_safe() + for accessor, mgr in zip(accessors, child_mgrs) + ) + + def visit_dict_manager(node: DictGuardManager) -> list[GuardManager]: + # Just recurse through the key and value dict managers and check if + # all of them are tag safe nodes. + if not issubclass(node.get_type_of_guarded_value(), dict): + raise AssertionError( + f"Expected dict subclass, got {node.get_type_of_guarded_value()}" + ) + + tag_safe_roots = [] + is_subtree_tag_safe = True + + # Recurse to get the tag safe roots from subtree. + for _idx, (key_mgr, val_mgr) in sorted( + node.get_key_value_managers().items() + ): + if key_mgr is not None: + visit(key_mgr) + if val_mgr is not None: + tag_safe_roots.extend(visit(val_mgr)) + + for key_mgr, val_mgr in node.get_key_value_managers().values(): + if key_mgr: + is_subtree_tag_safe &= key_mgr.is_tag_safe() + + if val_mgr: + is_subtree_tag_safe &= val_mgr.is_tag_safe() + + if is_subtree_tag_safe: + node.mark_tag_safe() + return tag_safe_roots + + def visit_manager(node: GuardManager) -> list[GuardManager]: + if isinstance(node, DictGuardManager): + raise AssertionError( + f"Expected non-DictGuardManager node, got {type(node)}" + ) + + # Collect the subtree tag safe roots + tag_safe_roots = [] + for child_mgr in node.get_child_managers(): + tag_safe_roots.extend(visit(child_mgr)) + + if node.is_guarded_value_immutable(): + # If the node guards a tensor, mark it tag safe only if there + # are no accessors. Presence of accessors means presence of + # symbolic shape guards. + if issubclass(node.get_type_of_guarded_value(), torch.Tensor): + if node.has_no_accessors() and not node.has_object_aliasing_guard(): + node.mark_tag_safe() + elif any( + a.repr() == "PythonLambdaGuardAccessor" + for a in node.get_accessors() + ): + # PythonLambdaGuardAccessor produces ephemeral objects + # (e.g., ___from_numpy converts np.float64 to a temporary + # tensor). These must not be stashed by the tag-safe + # recording pass since they are freed after each check. + pass + else: + node.mark_tag_safe() + elif issubclass(node.get_type_of_guarded_value(), dict): + accessors = node.get_accessors() + child_mgrs = node.get_child_managers() + is_subtree_tag_safe = all( + isinstance(accessor, DictGetItemGuardAccessor) and mgr.is_tag_safe() + for accessor, mgr in zip(accessors, child_mgrs) + ) + if is_subtree_tag_safe: + node.mark_tag_safe() + elif issubclass(node.get_type_of_guarded_value(), torch.nn.Module): + is_subtree_tag_safe = check_tag_safety( + node, (GetGenericDictGuardAccessor, TypeGuardAccessor) + ) + if is_subtree_tag_safe: + node.mark_tag_safe() + # Return the current node as tag safe root, discarding the + # subtree tag safe roots. + return [ + node, + ] + elif ( + node.get_type_of_guarded_value() + in ( + types.FunctionType, + types.MethodType, + staticmethod, + classmethod, + ) + and config.assume_dunder_attributes_remain_unchanged + ): + # Assumption: callers will not reassign the attributes + # func.__code__, func.__closure__, func.__defaults__, or func.__kwdefaults__. + # Mutating the objects those attributes point to is fine; + # rebinding the attribute itself is not. + # Example ─ allowed: foo.__defaults__[0].bar = 99 + # forbidden: foo.__defaults__ = (3, 4) + is_subtree_tag_safe = check_tag_safety( + node, + ( + CodeGuardAccessor, + ClosureGuardAccessor, + FuncDefaultsGuardAccessor, + FuncKwDefaultsGuardAccessor, + GetAttrGuardAccessor, + ), + ) + + for accessor in node.get_accessors(): + if isinstance(accessor, GetAttrGuardAccessor): + is_subtree_tag_safe &= ( + accessor.get_attr_name() in dunder_attrs_assumed_constants + ) + + if is_subtree_tag_safe: + node.mark_tag_safe() + elif issubclass(node.get_type_of_guarded_value(), types.CellType): + is_subtree_tag_safe = check_tag_safety(node, (GetAttrGuardAccessor,)) + + is_subtree_tag_safe &= all( + isinstance(accessor, GetAttrGuardAccessor) + and accessor.get_attr_name() == "cell_contents" + for accessor in node.get_accessors() + ) + if is_subtree_tag_safe: + node.mark_tag_safe() + elif ( + issubclass(node.get_type_of_guarded_value(), tuple) + and node.get_source().endswith(dunder_attrs_assumed_constants) + and config.assume_dunder_attributes_remain_unchanged + ): + # We trust tuples obtained from a function's __closure__ or + # __defaults__. Any *other* tuple-valued attribute can be + # silently replaced—for example: + # + # foo.bar = (1, 2) # original + # foo.bar = (3, 4) # rebinding that our dict-tag optimisation won't see + # + # Therefore only tuples from __closure__ / __defaults__ participate in the + # recursive-dict-tag optimization; all others are ignored. + is_subtree_tag_safe = check_tag_safety( + node, (TupleGetItemGuardAccessor,) + ) + if is_subtree_tag_safe: + node.mark_tag_safe() + elif issubclass(node.get_type_of_guarded_value(), type): + is_subtree_tag_safe = check_tag_safety( + node, (TypeDictGuardAccessor, TypeMROGuardAccessor) + ) + if is_subtree_tag_safe: + node.mark_tag_safe() + + return tag_safe_roots + + def visit(node: GuardManager) -> list[GuardManager]: + if node is None: + return [] + if isinstance(node, DictGuardManager): + return visit_dict_manager(node) + return visit_manager(node) + + tag_safe_roots = visit(self.root) + for node in tag_safe_roots: + if issubclass(node.get_type_of_guarded_value(), torch.nn.Module): + node.mark_tag_safe_root() + + def populate_diff_guard_manager(self) -> None: + self.diff_guard_root = self.clone_with_chosen_sources(self.diff_guard_sources) + + # Ensure that C++ side points to the updated diff guard manager. + # When a new GuardManagerWrapper is created, it does not have a + # cache_entry attribute, so it relies on the CacheEntry constructor to + # set the diff_guard_root in C++. But once it is saved in the Dynamo + # cache, C++ side adds a cache_entry attribute. On recompiles, this + # cache_entry is visible, so we update the C++ side to point to the + # update guard manager. + if self.cache_entry: + self.cache_entry.update_diff_guard_root_manager() + + def clone_with_chosen_sources( + self, chosen_sources: OrderedSet[str] + ) -> RootGuardManager: + def filter_fn(node_mgr: GuardManager) -> bool: + return node_mgr.get_source() in chosen_sources + + return self.root.clone_manager(filter_fn) + + def get_guard_lines(self, guard: LeafGuard) -> list[str]: + guard_name = guard.__class__.__name__ + parts = guard.verbose_code_parts() + parts = [guard_name + ": " + part for part in parts] + return parts + + def get_manager_line( + self, guard_manager: GuardManager, accessor_str: str | None = None + ) -> str: + source = guard_manager.get_source() + t = guard_manager.__class__.__name__ + s = t + ": source=" + source + if accessor_str: + s += ", " + accessor_str + s += f", type={guard_manager.get_type_of_guarded_value()}" + s += f", tag_safe=({guard_manager.is_tag_safe()}, {guard_manager.is_tag_safe_root()})" + return s + + def construct_dict_manager_string( + self, mgr: DictGuardManager, body: IndentedBufferWithPrefix + ) -> None: + for idx, (key_mgr, val_mgr) in sorted(mgr.get_key_value_managers().items()): + body.writeline(f"KeyValueManager pair at index={idx}") + with body.indent(): + if key_mgr: + body.writeline(f"KeyManager: {self.get_manager_line(key_mgr)}") + self.construct_manager_string(key_mgr, body) + + if val_mgr: + body.writeline(f"ValueManager: {self.get_manager_line(val_mgr)}") + self.construct_manager_string(val_mgr, body) + + def construct_manager_string( + self, mgr: GuardManager, body: IndentedBufferWithPrefix + ) -> None: + with body.indent(): + for guard in mgr.get_leaf_guards(): + if isinstance(guard, RelationalGuard): + if guard not in self.printed_relational_guards: + self.printed_relational_guards.add(guard) + + body.writelines(self.get_guard_lines(guard)) + else: + body.writelines( + [ + guard.__class__.__name__, + ] + ) + else: + body.writelines(self.get_guard_lines(guard)) + + # This works for both DictGuardManager and SubclassedDictGuardManager + if isinstance(mgr, DictGuardManager): + self.construct_dict_manager_string(mgr, body) + + # General case of GuardManager/RootGuardManager + for accessor, child_mgr in zip( + mgr.get_accessors(), mgr.get_child_managers() + ): + body.writeline( + self.get_manager_line(child_mgr, f"accessed_by={accessor.repr()}") + ) + self.construct_manager_string(child_mgr, body) + + def __str__(self) -> str: + with self._preserve_printed_relational_guards(): + body = IndentedBufferWithPrefix() + body.tabwidth = 1 + body.writeline("", skip_prefix=True) + body.writeline("TREE_GUARD_MANAGER:", skip_prefix=True) + body.writeline("RootGuardManager") + self.construct_manager_string(self.root, body) + if hasattr(self.root, "get_epilogue_lambda_guards"): + for guard in self.root.get_epilogue_lambda_guards(): + body.writelines(self.get_guard_lines(guard)) + return body.getvalue() + + def check(self, x: Any) -> bool: + # Only needed for debugging purposes. + return self.root.check(x) + + def check_verbose(self, x: Any) -> GuardDebugInfo: + # Only needed for debugging purposes. + return self.root.check_verbose(x) + + def populate_code_parts_for_debugging(self) -> None: + # This should be called when the guard manager is fully populated + relational_guards_seen = set() + + def get_code_parts(leaf_guard: LeafGuard) -> list[str]: + code_parts = [] + for verbose_code_part in leaf_guard.verbose_code_parts(): + code_part = verbose_code_part.split("#")[0].rstrip() + code_parts.append(code_part) + return code_parts + + def visit(mgr: GuardManager) -> None: + nonlocal relational_guards_seen + for guard in mgr.get_leaf_guards(): + if isinstance(guard, RelationalGuard): + if guard not in relational_guards_seen: + self.code_parts.extend(get_code_parts(guard)) + relational_guards_seen.add(guard) + else: + self.code_parts.extend(get_code_parts(guard)) + + for child_mgr in mgr.get_child_managers(): + visit(child_mgr) + + visit(self.root) + + +def from_numpy(a: Any) -> torch.Tensor: + # If not numpy array, piggy back on e.g. tensor guards to check type + # Re-enable torch function since we disable it on leaf guards + # we need it to properly construct the tensor if a default device is set + with torch.overrides._enable_torch_function(): + # pyrefly: ignore [missing-attribute] + return torch.as_tensor(a) if isinstance(a, (np.generic, np.ndarray)) else a + + +_async_collective_tensor_type: type | None = None + + +def unwrap_async_collective_tensor(x: torch.Tensor) -> torch.Tensor: + # Backing callable for UnwrapCollectiveTensorSource: yield an + # AsyncCollectiveTensor's inner tensor and leave everything else unchanged, + # so a graph traced on an ACT input is guarded against the unwrapped tensor. + # Runs on the guard-eval hot path, so memoize the ACT type once resolved. + global _async_collective_tensor_type + if _async_collective_tensor_type is None: + from torch._functorch._aot_autograd.utils import ( + get_loaded_async_collective_tensor_type, + ) + + _async_collective_tensor_type = get_loaded_async_collective_tensor_type() + if ( + _async_collective_tensor_type is not None + and type(x) is _async_collective_tensor_type + ): + return x.elem # type: ignore[attr-defined] + return x + + +# For user stack printing +@functools.cache +def uninteresting_files() -> set[str]: + import torch._dynamo.external_utils + import torch._dynamo.polyfills + + mods = [torch._dynamo.external_utils, torch._dynamo.polyfills] + + from torch._dynamo.polyfills.loader import POLYFILLED_MODULES + + # pyrefly: ignore [bad-argument-type] + mods.extend(POLYFILLED_MODULES) + + return {inspect.getfile(m) for m in mods} + + +_CLOSURE_VARS: dict[str, object] | None = None + + +def _get_closure_vars() -> dict[str, object]: + global _CLOSURE_VARS + if _CLOSURE_VARS is None: + _CLOSURE_VARS = { + "___check_type_id": check_type_id, + "___check_obj_id": check_obj_id, + "___odict_getitem": collections.OrderedDict.__getitem__, + "___key_to_id": key_to_id, + "___dict_version": dict_version, + "___dict_contains": lambda a, b: dict.__contains__(b, a), + "___tuple_iterator_len": tuple_iterator_len, + "___normalize_count_iter": normalize_count_iter, + "___normalize_range_iter": normalize_range_iter, + "___tuple_iterator_getitem": tuple_iterator_getitem, + "___set_getitem": set_getitem, + "___dataclass_fields": dataclass_fields, + "___namedtuple_fields": lambda x: x._fields, + "___get_torch_function_mode_stack_at": get_torch_function_mode_stack_at, + "___get_current_stream": get_current_stream, + "___cow_tensor_matches": _cow_tensor_matches, + "__math_isnan": math.isnan, + "__numpy_isnan": None if np is None else np.isnan, + "inf": float("inf"), + "__load_module": importlib.import_module, + "utils_device": torch.utils._device, + "device": torch.device, + "___from_numpy": from_numpy, + "___unwrap_async_collective_tensor": unwrap_async_collective_tensor, + "___as_tensor": torch._as_tensor_fullprec, + "torch": torch, + "inspect": inspect, + } + return _CLOSURE_VARS + + +def _ast_unparse(node: ast.AST) -> str: + return ast.unparse(node).replace("\n", "") + + +strip_function_call = torch._C._dynamo.strip_function_call + + +def _safe_type_repr(t: type[Any]) -> str: + return type.__repr__(t) + + +def get_verbose_code_part(code_part: str, guard: Guard | None) -> str: + extra = "" + if guard is not None: + if guard.user_stack: + for fs in reversed(guard.user_stack): + if fs.filename not in uninteresting_files(): + extra = f" # {format_frame(fs, line=True)}" + if len(extra) > 1024: + # For fx graphs, the line can be very long in case of + # torch.stack ops, where many inputs are set to None + # after the operation. This increases the size of the + # guards log file. In such cases, do not print the line + # contents. + extra = f" # {format_frame(fs)}" + break + elif guard.stack: + summary = guard.stack.summary() + if len(summary) > 0: + extra = f" # {format_frame(summary[-1])}" + else: + extra = " # " + return f"{code_part:<60}{extra}" + + +def get_verbose_code_parts( + code_parts: str | list[str], + guard: Guard | None, + recompile_hint: str | None = None, +) -> list[str]: + if not isinstance(code_parts, list): + code_parts = [code_parts] + + verbose_code_parts = [ + get_verbose_code_part(code_part, guard) for code_part in code_parts + ] + + # For CellContentsSource (or any source with a CellContentsSource ancestor), + # add a hint explaining which closure variable is being checked. + # This helps users understand which closure variable caused the guard failure. + if guard is not None: + closure_hint = _get_closure_var_hint(guard.originating_source) + if closure_hint: + recompile_hint = ( + f"{closure_hint}, {recompile_hint}" if recompile_hint else closure_hint + ) + + if recompile_hint: + verbose_code_parts = [ + f"{part} (HINT: {recompile_hint})" for part in verbose_code_parts + ] + + return verbose_code_parts + + +def _get_closure_var_hint(source: Source | None) -> str | None: + """ + Walk up the source chain to find a CellContentsSource ancestor. + Returns a hint like 'guard on "varname".attr' or None if not found. + """ + if source is None: + return None + + full_name = source.name + current: Source | None = source + while current is not None: + if isinstance(current, CellContentsSource) and current.freevar_name: + # Compute the path suffix by comparing names + # e.g., full_name="x.__closure__[0].cell_contents.scale" + # current.name="x.__closure__[0].cell_contents" + # suffix=".scale" + path_suffix = full_name[len(current.name) :] + return f'guard on "{current.freevar_name}"{path_suffix}' + current = current.base if isinstance(current, ChainedSource) else None + return None + + +def convert_int_to_concrete_values(dim: Any) -> int | None: + if dim is None: + return None + if not is_symbolic(dim): + return dim + else: + if not isinstance(dim, torch.SymInt): + raise AssertionError(f"Expected torch.SymInt, got {type(dim)}") + return dim.node.maybe_as_int() + + +def convert_to_concrete_values(size_or_stride: Sequence[Any]) -> list[int | None]: + return [convert_int_to_concrete_values(dim) for dim in size_or_stride] + + +def get_tensor_guard_code_part( + value: torch.Tensor, + name: str, + sizes: list[int | None], + strides: list[int | None], + pytype: type, + dispatch_keys: DispatchKeySet, +) -> str: + dispatch_key = ( + dispatch_keys | torch._C._dispatch_tls_local_include_set() + ) - torch._C._dispatch_tls_local_exclude_set() + dtype = value.dtype + device_index = value.device.index + requires_grad = value.requires_grad + guard_str = ( + f"check_tensor({name}, {pytype.__qualname__}, {dispatch_key}, {dtype}, " + f"device={device_index}, requires_grad={requires_grad}, size={sizes}, stride={strides})" + ) + return guard_str + + +def get_key_index(dct: dict[Any, Any], key: object) -> int: + # Ensure that we call dict.keys and not value.keys (which can call + # overridden keys method). In the C++ guards, we relied on PyDict_Next + # to traverse the dictionary, which uses the internal data structure and + # does not call the overridden keys method. + return list(builtin_dict_keys(dct)).index(key) + + +def get_key_index_source(source: Any, index: Any) -> str: + return f"list(dict.keys({source}))[{index}]" + + +def raise_local_type_error(obj: object) -> NoReturn: + raise TypeError( + f"Type {type(obj)} for object {obj} cannot be saved " + + "into torch.compile() package since it's defined in local scope. " + + "Please define the class at global scope (top level of a module)." + ) + + +def should_optimize_getattr_on_nn_module(value: object) -> bool: + return isinstance(value, torch.nn.Module) + + +@dataclasses.dataclass(frozen=True) +class NNModuleAttrAccessorInfo: + # Represents where is the attr name is present in the nn module attribute + # access + + # Tells that the attribute can be accessed via __dict__ + present_in_generic_dict: bool = False + + # Either the actual name or _parameters/_buffers/_modules + l1_key: str | None = None + + # Actual parameter/buffer/submodule name + l2_key: str | None = None + + +def getitem_on_dict_manager( + source: DictGetItemSource | DictSubclassGetItemSource, + base_guard_manager: DictGuardManager, + base_example_value: Any, + example_value: Any, + guard_manager_enum: GuardManagerType, +) -> GuardManager: + base_source_name = source.base.name + if isinstance(source.index, ConstDictKeySource): + index = source.index.index + else: + if not isinstance(base_example_value, dict): + raise AssertionError(f"Expected dict, got {type(base_example_value)}") + index = get_key_index(base_example_value, source.index) + + key_source = get_key_index_source(base_source_name, index) + + # Ensure that we call dict.keys and not value.keys (which can call + # overridden keys method). In the C++ guards, we relied on PyDict_Next + # to traverse the dictionary, which uses the internal data structure and + # does not call the overridden keys method. + key_example_value = list(builtin_dict_keys(base_example_value))[index] + if isinstance(key_example_value, (int, str)): + value_source = f"{base_source_name}[{key_example_value!r}]" + else: + value_source = f"{base_source_name}[{key_source}]" + if not isinstance(source.index, ConstDictKeySource): + # We have to insert a key manager guard here + # TODO - source debug string is probably wrong here. + base_guard_manager.get_key_manager( + index=index, + source=key_source, + example_value=source.index, + guard_manager_enum=GuardManagerType.GUARD_MANAGER, + ).add_equals_match_guard( + source.index, [f"{key_source} == {key_example_value!r}"], None + ) + + return base_guard_manager.get_value_manager( + index=index, + source=value_source, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + + +def match_on_id_for_tensor(guard: Guard) -> bool: + source = guard.originating_source + # For numpy tensors, always use TENSOR_MATCH because __from_numpy leads + # to a new tensor every time and therefore id differs. + if isinstance(source, NumpyTensorSource): + return False + + if guard.is_specialized_nn_module(): + return True + + return source.is_dict_key() and not isinstance(source, GradSource) + + +# The ready to eval generated code (possibly multiple parts) for a guard, plus +# the original guard object that created it for provenance +@dataclasses.dataclass +class GuardCodeList: + code_list: list[str] + guard: Guard + + +class GuardManagerType(enum.Enum): + GUARD_MANAGER = 1 + DICT_GUARD_MANAGER = 2 + + +@functools.cache +def code_framelocals_names_reversed_cached(code: types.CodeType) -> list[str]: + return list(reversed(code_framelocals_names(code))) + + +class GuardCheckSpec(NamedTuple): + """Lightweight guard evaluation for subgraph reuse during tracing. + + WHY IS THIS NEEDED? + Normal guards are collected during tracing, installed via GuardBuilder, and + evaluated in C++ at runtime. GuardCheckSpec serves a different purpose: we + want to evaluate a guard *during tracing* to check whether a previously + traced partial subgraph can be reused. The guard is collected during the + first trace of subgraph and then evaluated with a new source value before we + begin tracing the second subgraph. + + Existing C++ guards don't satisfy this need because they're designed for + runtime evaluation, not mid-trace comparisons with different source values. + + NB - This separate spec table *increases maintenance burden*, but each + handler is small and the number of guard types is finite, so it's tractable. + + get_metadata_fn: (guard, value) -> metadata — captures the minimum + information from the guarded value at build time. + eval_fn: (value, metadata) -> bool — re-evaluates the guard at lookup + time using a fresh value and the previously saved metadata. + """ + + get_metadata_fn: GuardCheckGetMetadataFn + eval_fn: GuardCheckEvalFn + + +SKIP_GUARD = object() + + +# Used by TENSOR_MATCH guard check spec +def extract_tensor_metadata(t: torch.Tensor) -> tuple[Any, ...]: + return (t.shape, t.stride(), t.dtype, t.device, t.requires_grad) + + +def _subclass_metadata_contains_tensor(metadata: Any) -> bool: + if isinstance(metadata, torch.Tensor): + return True + + node_type = pytree._get_node_type(metadata) + if node_type not in pytree.SUPPORTED_NODES: + return False + + if isinstance(metadata, collections.abc.Mapping): + for key in metadata: + if _subclass_metadata_contains_tensor(key): + return True + + children, _ = pytree.SUPPORTED_NODES[node_type].flatten_fn(metadata) + for child in children: + if _subclass_metadata_contains_tensor(child): + return True + return False + + +def _validate_default_subclass_metadata_guard(metadata: Any, cls: type[Any]) -> None: + if not _subclass_metadata_contains_tensor(metadata): + return + + raise exc.InternalTorchDynamoError( + f"Tensor subclass {cls.__module__}.{cls.__qualname__} returned Tensor " + "metadata from __tensor_flatten__() but does not define " + "__metadata_guard__. Dynamo's default tensor subclass metadata guard " + "uses Python equality, which is not valid for Tensor metadata. Move " + "tensor values to the inner tensor names returned by " + "__tensor_flatten__(), or define a classmethod __metadata_guard__" + "(original_metadata, current_metadata) to compare tensor metadata " + "explicitly." + ) + + +# Used by TENSOR_SUBCLASS_METADATA_MATCH guard check spec. +# Unlike check_dtensor_spec below, this pair is only reached at trace time: +# TENSOR_SUBCLASS_METADATA_MATCH has its own inlined metadata_checker closure +# for the C++ path, so narrowing with a typing.cast is free here. +def extract_subclass_metadata(guard: Any, value: object) -> tuple[Any, ...]: + cls = type(value) + has_custom_guard = hasattr(value, "__metadata_guard__") + metadata = cast("TraceableWrapperSubclass", value).__tensor_flatten__()[1] + if not has_custom_guard: + _validate_default_subclass_metadata_guard(metadata, cls) + metadata = deepcopy(metadata) + return (metadata, cls, has_custom_guard) + + +# Used by TENSOR_SUBCLASS_METADATA_MATCH guard check spec +def check_subclass_metadata(value: object, metadata: tuple[Any, ...]) -> bool: + saved_metadata, cls, has_custom_guard = metadata + subclass_metadata = cast("TraceableWrapperSubclass", value).__tensor_flatten__()[1] + if has_custom_guard: + return cls.__metadata_guard__(saved_metadata, subclass_metadata) + return subclass_metadata == saved_metadata + + +# Used by DTENSOR_SPEC_MATCH guard check spec +def extract_dtensor_spec(guard: Any, value: object) -> Any: + return deepcopy(value) + + +# Used by DTENSOR_SPEC_MATCH guard check spec +def check_dtensor_spec(value: object, metadata: Any) -> bool: + # DTENSOR_SPEC_MATCH's lambda guard calls this on every guard evaluation, + # so narrow with a suppression rather than a typing.cast, which would be a + # real call on the check path. + # pyrefly: ignore[missing-attribute] + return value._check_equals(metadata, skip_shapes=True) + + +# Used by OPAQUE_OBJ_GUARD_FN_MATCH guard check spec +def extract_opaque_obj(guard: Any, value: object) -> Any: + opaque_info = get_opaque_obj_info(type(value)) + if not opaque_info or not opaque_info.guard_fn: + return None + return deepcopy(opaque_info.guard_fn(value)) + + +# Used by OPAQUE_OBJ_GUARD_FN_MATCH guard check spec +def check_opaque_obj(value: object, metadata: Any) -> bool: + if metadata is None: + return True + opaque_info = get_opaque_obj_info(type(value)) + if not opaque_info or not opaque_info.guard_fn: + return metadata is None + return opaque_info.guard_fn(value) == metadata + + +# Used by CLOSURE_MATCH guard check spec +def extract_closure(guard: Any, value: object) -> Any: + if type(value) is types.FunctionType and hasattr(value, "__code__"): + return value.__code__ + return id(value) + + +# Used by CLOSURE_MATCH guard check spec +def check_closure(value: object, metadata: Any) -> bool: + if type(value) is types.FunctionType and hasattr(value, "__code__"): + return value.__code__ is metadata + return id(value) == metadata + + +def _constant_subclass_base_value(value: object) -> Any: + """Extract the base constant value from a constant subclass instance.""" + from .variables.user_defined import _CONSTANT_BASE_TYPES + + for t in _CONSTANT_BASE_TYPES: + if isinstance(value, t): + return t(value) # pyrefly: ignore[bad-argument-type] + raise TypeError(f"Not a constant subclass: {type(value)}") + + +def _guard_create_fn_keyword(guard: Guard, name: str) -> Any: + """Read a keyword bound into a guard's create_fn functools.partial.""" + create_fn = guard.create_fn + if not isinstance(create_fn, functools.partial): + raise TypeError(f"Guard create_fn is not a functools.partial: {create_fn}") + return create_fn.keywords[name] + + +def register_guard_check_spec( + get_metadata_fn: GuardCheckGetMetadataFn, + eval_fn: GuardCheckEvalFn, +): + """Attach a GuardCheckSpec to a guard method for auto-dispatch.""" + handler = GuardCheckSpec(get_metadata_fn=get_metadata_fn, eval_fn=eval_fn) + + def decorator(fn): + fn.guard_check_spec = handler + return fn + + return decorator + + +def skip_guard_check_spec(fn): + """Mark a guard method as skipped during auto-cache dispatch.""" + fn.guard_check_spec = SKIP_GUARD + return fn + + +class UnsupportedGuardCheckSpec: + """Sentinel for guards with no check spec yet. + + Raises NotImplementedError if get_metadata_fn/eval_fn are accidentally called. + """ + + def __init__(self, name: str) -> None: + self._name = name + + @property + def get_metadata_fn(self): + raise NotImplementedError(f"Guard check spec not implemented for {self._name}") + + @property + def eval_fn(self): + raise NotImplementedError(f"Guard check spec not implemented for {self._name}") + + +def unsupported_guard_check_spec(fn): + """Mark a guard method as unsupported for auto-cache dispatch.""" + fn.guard_check_spec = UnsupportedGuardCheckSpec(fn.__name__) + return fn + + +class GuardBuilder(GuardBuilderBase): + def __init__( + self, + f_code: types.CodeType, + id_ref: Callable[[object, str], int], + source_ref: Callable[[Source], str], + lookup_weakrefs: Callable[[object], weakref.ref[object] | None], + local_scope: dict[str, object], + global_scope: dict[str, object], + guard_manager: GuardManagerWrapper, + check_fn_manager: CheckFunctionManager, + save_guards: bool = False, + runtime_global_scope: dict[str, object] | None = None, + guard_filter_fn: Callable[[Sequence[GuardFilterEntry]], Sequence[bool]] + | None = None, + ) -> None: + self.f_code = f_code + self.id_ref = id_ref + self.source_ref = source_ref + self.lookup_weakrefs = lookup_weakrefs + self.scope: dict[str, dict[str, object]] = {"L": local_scope, "G": global_scope} + self.src_get_value_cache: dict[Source, object] = {} + self.runtime_global_scope = runtime_global_scope or global_scope + self.scope["__builtins__"] = builtins.__dict__.copy() + for ( + name, + package_module, + ) in torch.package.package_importer._package_imported_modules.items(): + name = name.replace(">", "_").replace("<", "_").replace(".", "_dot_") + # Write the package module into the scope so that we can import it + self.scope["__builtins__"][name] = package_module + # Write the demangled name to the scope so that we can use it + self.scope[name] = package_module + self.guard_manager = guard_manager + + self.argnames: list[str] = [] + # Code is python expression strings generated for each guard + self.code: list[GuardCodeList] = [] + # shape_env_code is only used by builder and is used for + # shape env code. This exists only because we need to make sure + # shape env guards get run after tensor match guards (since the + # tensor match guards make sure we actually have tensors) + self.shape_env_code: list[GuardCodeList] = [] + + # Collect the guard managers and debug info to insert no tensor aliasing + # guards. + self.no_tensor_aliasing_names: list[str] = [] + self.no_tensor_aliasing_guard_managers: list[GuardManager] = [] + + self.check_fn_manager: CheckFunctionManager = check_fn_manager + + self.guard_tree_values: dict[int, Any] = {} + self.save_guards = save_guards + self.guard_filter_fn = guard_filter_fn + + # Collect the ids of dicts which need key order guarding. source_name is + # not sufficient because for nn modules, we can have different sources + # to access the same object - self._module["param"] is same as + # self.param. + self.key_order_guarded_dict_ids = set() + if self.check_fn_manager.output_graph is None: + raise AssertionError("check_fn_manager.output_graph must not be None") + for source in self.check_fn_manager.output_graph.guard_on_key_order: + dict_obj = self.get(source) + self.key_order_guarded_dict_ids.add(id(dict_obj)) + + # Keep track of weak references of objects with ID_MATCH guard. This + # info is stored alongside optimized_code and guard_manager and is used to + # limit the number of cache entries with same ID_MATCH'd object. + self.id_matched_objs: dict[str, ReferenceType[object]] = {} + + # Save the guard managers to avoid repeatedly traversing sources. + self._cached_guard_managers: dict[str, GuardManager] = {} + self._cached_duplicate_input_guards: set[tuple[str, str]] = set() + self.object_aliasing_guard_codes: list[tuple[str, str]] = [] + self.guard_nn_modules = config.guard_nn_modules and justknobs_check( + "pytorch/compiler:guard_nn_modules" + ) + self.already_added_code_parts: OrderedSet[str] = OrderedSet() + + def guard_on_dict_keys_and_ignore_order( + self, example_value: dict[Any, Any], guard: Guard + ) -> None: + dict_mgr = self.get_guard_manager(guard) + if isinstance(dict_mgr, DictGuardManager): + raise NotImplementedError( + "Not expecting a DictGuardManager. Seems like Dynamo incorrectly " + f"added the dict to tx.output.guard_on_key_order for {guard.name}" + ) + + # Iterate over the dicts and install a dict_getitem_manager. + dict_source = guard.originating_source.name + + # Ensure that we call dict.keys and not value.keys (which can call + # overridden keys method). In the C++ guards, we relied on PyDict_Next + # to traverse the dictionary, which uses the internal data structure and + # does not call the overridden keys method. + for key in builtin_dict_keys(example_value): + value = example_value[key] + value_source = DictGetItemSource(guard.originating_source, index=key) + guard_manager_enum = self.get_guard_manager_type( + value_source, example_value + ) + dict_mgr.dict_getitem_manager( + key=key, + source=f"{dict_source}[{key!r}]", + example_value=value, + guard_manager_enum=guard_manager_enum, + ) + + def guard_on_dict_keys_and_order(self, value: dict[Any, Any], guard: Guard) -> None: + # Add key managers for the DictGuardManager. Then add either an + # ID_MATCH or EQUALS_MATCH guard on the key. + dict_mgr = self.get_guard_manager(guard) + if not isinstance(dict_mgr, DictGuardManager): + raise NotImplementedError( + "Expecting a DictGuardManager. Seems like Dynamo forgot " + f"to set the right guard manager enum for {guard.name}" + ) + if not isinstance(dict_mgr, DictGuardManager): + raise AssertionError(f"Expected DictGuardManager, got {type(dict_mgr)}") + + # Ensure that we call dict.keys and not value.keys (which can call + # overridden keys method). In the C++ guards, we relied on PyDict_Next + # to traverse the dictionary, which uses the internal data structure and + # does not call the overridden keys method. + for idx, key in enumerate(builtin_dict_keys(value)): + key_source = get_key_index_source(guard.name, idx) + key_manager = dict_mgr.get_key_manager( + index=idx, + source=key_source, + example_value=key, + guard_manager_enum=GuardManagerType.GUARD_MANAGER, + ) + if key_is_id(key): + # Install ID_MATCH guard + id_val = self.id_ref(key, key_source) + key_manager.add_id_match_guard( + id_val, + get_verbose_code_parts( + f"__check_obj_id({key_source}, {id_val})", guard + ), + guard.user_stack, + ) + else: + # Install EQUALS_MATCH guard + key_manager.add_equals_match_guard( + key, + get_verbose_code_parts(f"{key_source} == {key!r}", guard), + guard.user_stack, + ) + + @staticmethod + def _get_generic_dict_manager_example_value(example_value: Any) -> Any | None: + # due to a bug in 3.13.0 (introduced by https://github.com/python/cpython/pull/116115, + # reported in https://github.com/python/cpython/issues/125608, + # fixed by https://github.com/python/cpython/pull/125611), we cannot take + # advantage of __dict__ versions to speed up guard checks. + if ( + config.issue_3_13_0_warning + and sys.version_info >= (3, 13) + and sys.version_info < (3, 13, 1) + ): + warnings.warn( + "Guards may run slower on Python 3.13.0. Consider upgrading to Python 3.13.1+.", + RuntimeWarning, + ) + return None + return example_value + + def getattr_on_nn_module( + self, + source: AttrSource, + base_guard_manager: GuardManager, + base_example_value: Any, + example_value: Any, + base_source_name: str, + source_name: str, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: + """ + This tries to avoid calling the expensive nn module custom getattr method by + checking if the attribute is accessible via __dict__. For attributes that + are not accessible via __dict__ (like descriptors), we fallback to + PyObject_GetAttr. + + There are two cases that we optimize for + 1) attributes present directly in __dict__, e.g training. + 2) parameters/buffers/modules - they can be accessed via _parameters, + _buffers, _modules keys in __dict__. For example, mod.linear can be + accessed as mod.__dict__["_parameters"]["linear"] + + The most common and expensive case for nn module guards is of type + mod.submod1.submod2.submod3.training. We avoid the python getattr of nn + modules by going through the __dict__. + """ + + def getitem_on_dict_mgr( + mgr: GuardManager, + key: Any, + source_name: str, + base_example_value: Any, + example_value: Any, + guard_manager_enum: GuardManagerType, + ) -> GuardManager: + if isinstance(mgr, DictGuardManager): + # Case where the user code relies on key order, e.g., + # named_parameters + index = get_key_index(base_example_value, key) + + # Install the key manager and add equals match guard + key_source = f"list(dict.keys({source_name}))[{index!r}]" + mgr.get_key_manager( + index=index, + source=key_source, + example_value=key, + guard_manager_enum=GuardManagerType.GUARD_MANAGER, + ).add_equals_match_guard(key, [f"{key_source} == {key!r}"], None) + + # Install the value manager + return mgr.get_value_manager( + index=index, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + else: + return mgr.dict_getitem_manager( + key=key, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + + attr_name = source.member + mod_dict = base_example_value.__dict__ + + all_class_attribute_names: set[str] = set() + for x in inspect.getmro(base_example_value.__class__): + all_class_attribute_names.update(x.__dict__.keys()) + + accessor_info = NNModuleAttrAccessorInfo(False, None, None) + + if attr_name in mod_dict: + accessor_info = NNModuleAttrAccessorInfo(True, attr_name, None) + elif "_parameters" in mod_dict and attr_name in mod_dict["_parameters"]: + accessor_info = NNModuleAttrAccessorInfo(True, "_parameters", attr_name) + elif "_buffers" in mod_dict and attr_name in mod_dict["_buffers"]: + accessor_info = NNModuleAttrAccessorInfo(True, "_buffers", attr_name) + elif ( + attr_name not in all_class_attribute_names + and "_modules" in mod_dict + and attr_name in mod_dict["_modules"] + ): + # Check test_attr_precedence test - instance attributes always take precedence unless its an nn.Module. + accessor_info = NNModuleAttrAccessorInfo(True, "_modules", attr_name) + + if not accessor_info.present_in_generic_dict: + # The attribute can be accessed by __getattribute__ call, so rely on + # PyObject_GetAttr + return base_guard_manager.getattr_manager( + attr=source.member, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + else: + if not accessor_info.l1_key: + raise AssertionError("accessor_info.l1_key must not be empty") + l1_key = accessor_info.l1_key + l2_key = accessor_info.l2_key + + # Set source strings for debug info + mod_dict_source = f"{base_source_name}.__dict__" + l1_source_name = l2_source_name = None + l1_value = l2_value = None + l1_guard_manager_enum = l2_guard_manager_enum = None + if l2_key: + l1_source = AttrSource(source.base, l1_key) + l1_source_name = l1_source.name + l1_value = mod_dict[l1_key] + # do not guard on key order for _parameters etc unless the user code + # actually needs the key order (e.g. calling named_parameters) + l1_guard_manager_enum = self.get_guard_manager_type(l1_source, l1_value) + + l2_source_name = source_name + l2_value = example_value + l2_guard_manager_enum = self.get_guard_manager_type( + source, example_value + ) + else: + l1_source_name = source_name + l1_value = example_value + l1_guard_manager_enum = self.get_guard_manager_type( + source, example_value + ) + + # Get __dict__ accessor. No need to guard on dict key order, so use base + # Guard Manager + mod_generic_dict_manager = base_guard_manager.get_generic_dict_manager( + source=mod_dict_source, + example_value=self._get_generic_dict_manager_example_value(mod_dict), + guard_manager_enum=GuardManagerType.GUARD_MANAGER, + ) + + l1_mgr = getitem_on_dict_mgr( + mgr=mod_generic_dict_manager, + key=l1_key, + source_name=l1_source_name, + base_example_value=mod_dict, + example_value=l1_value, + guard_manager_enum=l1_guard_manager_enum, + ) + + if l2_key: + if l2_source_name is None or l2_guard_manager_enum is None: + raise AssertionError( + "l2_source_name and l2_guard_manager_enum must not be None" + ) + return getitem_on_dict_mgr( + mgr=l1_mgr, + key=l2_key, + source_name=l2_source_name, + base_example_value=l1_value, + example_value=l2_value, + guard_manager_enum=l2_guard_manager_enum, + ) + return l1_mgr + + def requires_key_order_guarding(self, source: Source) -> bool: + source_name = source.name + if source_name == "": + return False + obj_id = id(self.get(source)) + return obj_id in self.key_order_guarded_dict_ids + + def get_guard_manager_type( + self, + source: Source, + example_value: KeysView[Any] + | set[Any] + | frozenset[Any] + | dict[Any, Any] + | None, + ) -> GuardManagerType: + guard_manager_enum = GuardManagerType.GUARD_MANAGER + if self.requires_key_order_guarding(source): + # Fix this if condition + if isinstance(example_value, dict_keys): + guard_manager_enum = GuardManagerType.DICT_GUARD_MANAGER + elif isinstance(example_value, (set, frozenset)): + # we don't need to guard on key order for set/frozenset + # but the if above will be true for these types as set is + # implemented using a dict in Dynamo + guard_manager_enum = GuardManagerType.GUARD_MANAGER + else: + if not isinstance(example_value, dict): + raise AssertionError(f"Expected dict, got {type(example_value)}") + guard_manager_enum = GuardManagerType.DICT_GUARD_MANAGER + return guard_manager_enum + + def manager_guards_on_keys(self, mgr_enum: GuardManagerType) -> bool: + return mgr_enum == GuardManagerType.DICT_GUARD_MANAGER + + def get_global_guard_manager(self) -> GuardManager: + return self.guard_manager.root.globals_dict_manager( + f_globals=self.runtime_global_scope, + source="G", + example_value=self.scope["G"], + guard_manager_enum=GuardManagerType.GUARD_MANAGER, + ) + + def get_guard_manager_from_source(self, source: Source) -> GuardManager: + root_guard_manager = self.guard_manager.root + + example_value = None + source_name = source.name + + if source_name != "" and source_name in self._cached_guard_managers: + return self._cached_guard_managers[source_name] + + if source_name != "": + example_value = self.get(source) + self.guard_tree_values[id(example_value)] = example_value + + guard_manager_enum = self.get_guard_manager_type(source, example_value) + + # Get base manager related information + base_source_name = None + base_example_value = None + base_guard_manager = None + base_guard_manager_enum = GuardManagerType.GUARD_MANAGER + if isinstance(source, ChainedSource): + base_source_name = source.base.name + base_example_value = self.get(source.base) + base_guard_manager = self.get_guard_manager_from_source(source.base) + base_guard_manager_enum = self.get_guard_manager_type( + source.base, base_example_value + ) + + # Use istype instead of isinstance to check for exact type of source. + if istype(source, LocalSource): + framelocals_idx = get_framelocals_idx(self.f_code, source.local_name) + out = root_guard_manager.framelocals_manager( + key=(source.local_name, framelocals_idx), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, GlobalSource): + # Global manager accepts a dict but it is not a DictGuardManager + # because globals dict is big and we typically guard on a very + # selected items on globals. + out = self.get_global_guard_manager().dict_getitem_manager( + key=source.global_name, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, GlobalWeakRefSource): + out = self.get_global_guard_manager().global_weakref_manager( + global_name=source.global_name, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, GlobalStateSource): + # Don't do anything here. We guard on global state completely in + # C++. So just return the root mgr. + return root_guard_manager + elif istype(source, ShapeEnvSource): + return root_guard_manager + elif istype(source, TypeSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.type_manager( + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, TypeDictSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.type_dict_manager( + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, TypeMROSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.type_mro_manager( + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype( + source, + ( + OptimizerSource, + NNModuleSource, + UnspecializedNNModuleSource, + UnspecializedBuiltinNNModuleSource, + FSDPNNModuleSource, + ), + ): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager + elif istype(source, ImportSource): + module = importlib.import_module(source.module_name) + out = root_guard_manager.lambda_manager( + python_lambda=lambda _, m=module: m, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, TorchFunctionModeStackSource): + out = root_guard_manager.lambda_manager( + python_lambda=lambda _: get_torch_function_mode_stack_at( + source._get_index() + ), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, CurrentStreamSource): + out = root_guard_manager.lambda_manager( + python_lambda=lambda _: get_current_stream(source.device), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, GradSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.grad_manager( + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, GenericAttrSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.generic_getattr_manager( + attr=source.member, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype( + source, (AttrSource, CellContentsSource, UnspecializedParamBufferSource) + ): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + if not isinstance(source, AttrSource): + raise AssertionError(f"Expected AttrSource, got {type(source)}") + if should_optimize_getattr_on_nn_module(base_example_value): + if not base_source_name: + raise AssertionError("base_source_name must not be empty") + out = self.getattr_on_nn_module( + source, + base_guard_manager, + base_example_value, + example_value, + base_source_name, + source_name, + guard_manager_enum, + ) + else: + out = base_guard_manager.getattr_manager( + attr=source.member, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, (DictGetItemSource, DictSubclassGetItemSource)): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + if not isinstance(base_example_value, (dict, collections.OrderedDict)): + raise AssertionError( + f"Expected dict or OrderedDict, got {type(base_example_value)}" + ) + if not isinstance(source, (DictGetItemSource, DictSubclassGetItemSource)): + raise AssertionError( + f"Expected DictGetItemSource or DictSubclassGetItemSource, got {type(source)}" + ) + if isinstance(base_guard_manager, DictGuardManager): + if not self.manager_guards_on_keys(base_guard_manager_enum): + raise AssertionError("DictGuardManager must guard on keys") + out = getitem_on_dict_manager( + source, + base_guard_manager, + base_example_value, + example_value, + guard_manager_enum, + ) + else: + if isinstance(source.index, ConstDictKeySource): + raise RuntimeError( + "Expecting clean index here. Likely Dynamo forgot to mark" + " a dict as guard_on_key_order" + ) + out = base_guard_manager.dict_getitem_manager( + key=source.index, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, TensorPropertySource): + out = getattr( + base_guard_manager, + f"tensor_property_{source.prop.name.lower()}_manager", + )( + idx=source.idx, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, IndexedSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + + out = base_guard_manager.indexed_manager( + idx=source.idx, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, ListGetItemSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.list_getitem_manager( + key=source.index, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, GetItemSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + if isinstance(base_example_value, (dict, collections.OrderedDict)): + raise AssertionError("Use DictGetItemSource") + if isinstance(base_example_value, list) and not source.index_is_slice: + out = base_guard_manager.list_getitem_manager( + key=source.index, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif isinstance(base_example_value, tuple) and not source.index_is_slice: + out = base_guard_manager.tuple_getitem_manager( + key=source.index, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + else: + index = source.index + if source.index_is_slice: + index = source.unpack_slice() + out = base_guard_manager.getitem_manager( + key=index, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, DefaultsSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + if not base_source_name: + raise AssertionError("base_source_name must not be empty") + if not callable(base_example_value): + raise AssertionError("base_example_value must be callable") + if not source.is_kw: + out = base_guard_manager.func_defaults_manager( + source=base_source_name, + example_value=base_example_value.__defaults__, + guard_manager_enum=GuardManagerType.GUARD_MANAGER, + ).getitem_manager( + key=source.idx_key, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + else: + # kwdefauts is a dict, so use a DictGuardManager + kwdefaults = base_example_value.__kwdefaults__ + if base_source_name is None: + raise AssertionError("base_source_name must not be None") + kw_source = base_source_name + ".__kwdefaults__" + + # kwdefaults is a dict. No need to guard on dict order. + dict_mgr = base_guard_manager.func_kwdefaults_manager( + source=kw_source, + example_value=kwdefaults, + guard_manager_enum=GuardManagerType.GUARD_MANAGER, + ) + if isinstance(dict_mgr, DictGuardManager): + raise AssertionError("Expected non-DictGuardManager for kwdefaults") + + out = dict_mgr.dict_getitem_manager( + key=source.idx_key, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, NumpyTensorSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.lambda_manager( + python_lambda=from_numpy, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, SubclassAttrListSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.lambda_manager( + python_lambda=lambda x: x.__tensor_flatten__()[0], + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, UnwrapCollectiveTensorSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.lambda_manager( + python_lambda=unwrap_async_collective_tensor, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, FlattenScriptObjectSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.lambda_manager( + python_lambda=lambda x: x.__obj_flatten__(), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, ScriptObjectQualifiedNameSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.lambda_manager( + python_lambda=lambda x: x._type().qualified_name(), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, AttrProxySource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.lambda_manager( + python_lambda=lambda x: x.get_base(), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, CallMethodItemSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.lambda_manager( + python_lambda=lambda x: x.item(), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, ContextVarGetSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + if source.has_default: + default_val = source.default_value + out = base_guard_manager.lambda_manager( + python_lambda=lambda x, d=default_val: x.get(d), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + else: + out = base_guard_manager.lambda_manager( + python_lambda=lambda x: x.get(), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, FloatTensorSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.lambda_manager( + python_lambda=lambda x: torch._as_tensor_fullprec(x), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, TupleIteratorGetItemSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.tuple_iterator_getitem_manager( + index=source.index, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif isinstance(source, ConstDictKeySource): + if not isinstance(base_guard_manager, DictGuardManager): + raise AssertionError( + "ConstDictKeySource can only work on DictGuardManager" + ) + out = base_guard_manager.get_key_manager( + index=source.index, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, NonSerializableSetGetItemSource): + if not base_guard_manager: + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.set_getitem_manager( + index=source.index, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, WeakRefCallSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.weakref_call_manager( + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, CallFunctionNoArgsSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.call_function_no_args_manager( + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, DataclassFieldsSource): + if not base_guard_manager: + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.lambda_manager( + python_lambda=lambda x: dataclass_fields(x), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, NamedTupleFieldsSource): + if not base_guard_manager: + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.lambda_manager( + python_lambda=lambda x: x._fields, + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, CodeSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.code_manager( + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, ClosureSource): + if not base_guard_manager: # to make mypy happy + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.closure_manager( + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + elif istype(source, DynamicScalarSource): + if not base_guard_manager: + raise AssertionError("base_guard_manager must not be None") + out = base_guard_manager.lambda_manager( + python_lambda=lambda x: int(x), + source=source_name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + else: + raise AssertionError( + f"missing guard manager builder {source} - {source.name}" + ) + + self._cached_guard_managers[source.name] = out + return out + + def get_guard_manager(self, guard: Guard) -> GuardManager: + return self.get_guard_manager_from_source(guard.originating_source) + + def add_python_lambda_leaf_guard_to_root( + self, + code_parts: list[str], + verbose_code_parts: list[str], + closure_vars: dict[str, object] | None = None, + is_epilogue: bool = True, + ) -> None: + if closure_vars is None: + closure_vars = _get_closure_vars() + # Adds a lambda leaf guard to the root guard manager. It wraps the + # code_parts in a function object which is then passed on to the leaf + # guard. + make_guard_fn_args = ", ".join(closure_vars.keys()) + _guard_body, pycode = build_guard_function(code_parts, make_guard_fn_args) + out: dict[str, Any] = {} + globals_for_guard_fn = {"G": self.scope["G"]} + guards_log.debug("Python shape guard function:\n%s", pycode) + exec(pycode, globals_for_guard_fn, out) + guard_fn = out["___make_guard_fn"](*closure_vars.values()) + if is_epilogue: + # Epilogue guards are run after all the other guards have finished. + # If epilogue guards contain a getattr or getitem access, one of the + # other guards would fail preventing the epilogue guards to run. + self.guard_manager.root.add_epilogue_lambda_guard( + guard_fn, + verbose_code_parts, + None, + ) + else: + self.guard_manager.root.add_lambda_guard(guard_fn, verbose_code_parts, None) + + # Warning: use this with care! This lets you access what the current + # value of the value you are guarding on is. You probably don't want + # to actually durably save this value though (because it's specific + # to this frame!) Instead, you should be reading out some property + # (like its type) which is what you permanently install into the + # guard code. + def get( + self, + guard_or_source: Guard | Source, + closure_vars: dict[str, Any] | None = None, + ) -> Any: + if isinstance(guard_or_source, Source): + src = guard_or_source + else: + src = guard_or_source.originating_source + if closure_vars is None: + closure_vars = _get_closure_vars() + ret = src.get_value(self.scope, closure_vars, self.src_get_value_cache) + return ret + + # Registers the usage of the source name referenced by the + # string (or stored in the Guard) as being guarded upon. It's important + # to call this before generating some code that makes use of 'guard', + # because without this call, we won't actually bind the variable + # you reference in the actual guard closure (oops!) + def arg_ref(self, guard: str | Guard) -> str: + name: str + if isinstance(guard, str): + name = guard + else: + name = guard.name + base = strip_function_call(name) + if base not in self.argnames: + is_valid = torch._C._dynamo.is_valid_var_name(base) + if is_valid: + if is_valid == 2: + log.warning("invalid var name: %s", guard) + self.argnames.append(base) + + return name + + def _guard_on_attribute( + self, + guard: Guard, + attr_name: str, + guard_fn: Callable[[GuardBuilderBase, Guard], Any], + ) -> None: + if attr_name == "__code__": + attr_source = CodeSource(guard.originating_source) + else: + attr_source = AttrSource(guard.originating_source, attr_name) # type: ignore[assignment] + # Copy the stack info + new_guard = Guard( + attr_source, guard_fn, stack=guard.stack, user_stack=guard.user_stack + ) + new_guard.create(self) + + # Note: the order of the guards in this file matters since we sort guards on the same object by lineno + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: ( + _guard_create_fn_keyword(guard, "attr"), + hasattr(value, _guard_create_fn_keyword(guard, "attr")), + ), + eval_fn=lambda value, metadata: hasattr(value, metadata[0]) == metadata[1], + ) + def HASATTR(self, guard: Guard, attr: str | None = None) -> None: + if attr is None: + raise AssertionError("attr must not be None for HASATTR guard") + source = guard.originating_source + if isinstance(source, NNModuleSource): + source = source.base + + ref = self.arg_ref(guard) + val = hasattr(self.get(guard), attr) + code = None + if val: + code = f"hasattr({ref}, {attr!r})" + else: + code = f"not hasattr({ref}, {attr!r})" + + if code in self.already_added_code_parts: + return + + self._set_guard_export_info( + guard, [code], provided_guarded_object=self.get(guard) + ) + + base_manager = self.get_guard_manager_from_source(source) + if val: + # Just install a getattr manager. GetAttrGuardAccessor itself + # acts as hasattr guard. + attr_source = AttrSource(source, attr) + example_value = self.get(attr_source) + base_example_value = self.get(guard) + guard_manager_enum = self.get_guard_manager_type(attr_source, example_value) + + # if the base value is nn.Module, check if we can speedup the + # guard by going through __dict__ attrs. + if should_optimize_getattr_on_nn_module(base_example_value): + self.getattr_on_nn_module( + attr_source, + base_manager, + base_example_value, + example_value, + source.name, + attr_source.name, + guard_manager_enum, + ) + else: + base_manager.getattr_manager( + attr=attr, + source=guard.name, + example_value=example_value, + guard_manager_enum=guard_manager_enum, + ) + else: + base_manager.add_no_hasattr_guard( + attr, get_verbose_code_parts(code, guard), guard.user_stack + ) + self.already_added_code_parts.add(code) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: _guard_create_fn_keyword(guard, "attr"), + eval_fn=lambda value, metadata: metadata not in value.__dict__, + ) + def NOT_PRESENT_IN_GENERIC_DICT( + self, guard: Guard, attr: str | None = None + ) -> None: + if attr is None: + raise AssertionError( + "attr must not be None for NOT_PRESENT_IN_GENERIC_DICT guard" + ) + ref = self.arg_ref(guard) + val = self.get(guard) + + base_manager = self.get_guard_manager(guard) + + code = f"not ___dict_contains({attr!r}, {ref}.__dict__)" + if code in self.already_added_code_parts: + return + + mod_dict_source = f"{guard.name}.__dict__" + mod_generic_dict_manager = base_manager.get_generic_dict_manager( + source=mod_dict_source, + example_value=self._get_generic_dict_manager_example_value(val.__dict__), + guard_manager_enum=GuardManagerType.GUARD_MANAGER, + ) + + mod_generic_dict_manager.add_dict_contains_guard( + False, + attr, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + self.already_added_code_parts.add(code) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: type(value), + eval_fn=lambda value, metadata: type(value) is metadata, + ) + def TYPE_MATCH(self, guard: Guard) -> None: + # ___check_type_id is same as `id(type(x)) == y` + value = self.get(guard) + if ( + isinstance( # noqa: ISINSTANCE_FAKE_TENSOR + value, torch._subclasses.FakeTensor + ) + and value.pytype + ): + t = value.pytype + else: + t = type(value) + + if t.__qualname__ != t.__name__: + # Type match guards must be local scope, this is + # raised in self.serialize_guards + guard._unserializable = True + + obj_id = self.id_ref(t, f"type({guard.name})") + type_repr = _safe_type_repr(t) + code = f"___check_type_id({self.arg_ref(guard)}, {obj_id}), type={type_repr}" + self._set_guard_export_info(guard, [code]) + + self.get_guard_manager(guard).add_type_match_guard( + obj_id, + get_verbose_code_parts( + code, guard, recompile_hint=f"type {t.__qualname__}" + ), + guard.user_stack, + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: type( + value.real_obj if isinstance(value, FakeScriptObject) else value + ), + eval_fn=lambda value, metadata: type( + value.real_obj if isinstance(value, FakeScriptObject) else value + ) + is metadata, + ) + def FAKE_SCRIPT_TYPE_MATCH(self, guard: Guard) -> None: + # Like TYPE_MATCH, but for sources that may resolve to either a + # FakeScriptObject (during outer AOTAutograd tracing) or the + # underlying real opaque object (at runtime). The C++ leaf guard + # unwraps FakeScriptObject before comparing types. + value = self.get(guard) + if isinstance(value, FakeScriptObject): + t = type(value.real_obj) + else: + t = type(value) + + if t.__qualname__ != t.__name__: + guard._unserializable = True + + obj_id = self.id_ref(t, f"type({guard.name})") + type_repr = _safe_type_repr(t) + code = f"___check_fake_script_type({self.arg_ref(guard)}, {obj_id}), type={type_repr}" + self._set_guard_export_info(guard, [code]) + + self.get_guard_manager(guard).add_fake_script_type_match_guard( + FakeScriptObject, + obj_id, + get_verbose_code_parts( + code, guard, recompile_hint=f"type {t.__qualname__}" + ), + guard.user_stack, + ) + + # Dict versions change on any mutation, so a version captured during one + # trace is meaningless for a later subgraph reuse check. + @unsupported_guard_check_spec + def DICT_VERSION(self, guard: Guard) -> None: + # ___check_dict_version is same as `dict_version(x) == y` + ref = self.arg_ref(guard) + val = self.get(guard) + version = dict_version(self.get(guard)) + code = f"___dict_version({ref}) == {version}" + self._set_guard_export_info(guard, [code]) + + # TODO(anijain2305) - Delete this when DictGuardManager uses tags + # for dicts. + self.get_guard_manager(guard).add_dict_version_guard( + val, get_verbose_code_parts(code, guard), guard.user_stack + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: _guard_create_fn_keyword(guard, "key"), + eval_fn=lambda value, metadata: metadata in value, + ) + def DICT_CONTAINS(self, guard: Guard, key: str) -> None: + dict_ref = self.arg_ref(guard) + + code = f"___dict_contains({key!r}, {dict_ref})" + if code in self.already_added_code_parts: + return + self._set_guard_export_info(guard, [code]) + + self.get_guard_manager(guard).add_dict_contains_guard( + True, + key, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + self.already_added_code_parts.add(code) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: _guard_create_fn_keyword(guard, "key"), + eval_fn=lambda value, metadata: metadata not in value, + ) + def DICT_NOT_CONTAINS(self, guard: Guard, key: str) -> None: + dict_ref = self.arg_ref(guard) + + code = f"not ___dict_contains({key!r}, {dict_ref})" + if code in self.already_added_code_parts: + return + self._set_guard_export_info(guard, [code]) + + self.get_guard_manager(guard).add_dict_contains_guard( + False, + key, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + self.already_added_code_parts.add(code) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: _guard_create_fn_keyword(guard, "key"), + eval_fn=lambda value, metadata: metadata in value, + ) + def SET_CONTAINS(self, guard: Guard, key: object) -> None: + set_ref = self.arg_ref(guard) + item = key + + code = f"set.__contains__({set_ref}, {item!r})" + if code in self.already_added_code_parts: + return + + self._set_guard_export_info(guard, [code]) + + self.get_guard_manager(guard).add_set_contains_guard( + True, + item, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + self.already_added_code_parts.add(code) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: _guard_create_fn_keyword(guard, "key"), + eval_fn=lambda value, metadata: metadata not in value, + ) + def SET_NOT_CONTAINS(self, guard: Guard, key: object) -> None: + set_ref = self.arg_ref(guard) + item = key + + code = f"not set.__contains__({set_ref}, {item!r})" + if code in self.already_added_code_parts: + return + + self._set_guard_export_info(guard, [code]) + + self.get_guard_manager(guard).add_set_contains_guard( + False, + item, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + self.already_added_code_parts.add(code) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: value, + eval_fn=lambda value, metadata: value == metadata, + ) + def BOOL_MATCH(self, guard: Guard) -> None: + # checks val == True or val == False + ref = self.arg_ref(guard) + val = self.get(guard) + if not istype(val, bool): + raise AssertionError(f"Expected bool, got {type(val)}") + code = [f"{ref} == {val!r}"] + self._set_guard_export_info(guard, code) + + if val: + self.get_guard_manager(guard).add_true_match_guard( + get_verbose_code_parts(code, guard), guard.user_stack + ) + else: + self.get_guard_manager(guard).add_false_match_guard( + get_verbose_code_parts(code, guard), guard.user_stack + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: _try_is_cow_tensor(value), + eval_fn=lambda value, metadata: _cow_tensor_matches(value, metadata), + ) + def COW_TENSOR_MATCH(self, guard: Guard) -> None: + expected = _try_is_cow_tensor(self.get(guard)) + if not isinstance(expected, bool): + raise AssertionError("COW_TENSOR_MATCH requires a plain Tensor") + + def guard_fn(x: object) -> bool: + return _cow_tensor_matches(x, expected) + + code = f"___cow_tensor_matches({self.arg_ref(guard)}, {expected!r})" + self._set_guard_export_info(guard, [code]) + self.get_guard_manager(guard).add_lambda_guard( + guard_fn, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: None, + eval_fn=lambda value, metadata: value is None, + ) + def NONE_MATCH(self, guard: Guard) -> None: + # checks `val is None` + ref = self.arg_ref(guard) + val = self.get(guard) + if val is not None: + raise AssertionError(f"Expected None, got {type(val)}") + code = [f"{ref} is None"] + self._set_guard_export_info(guard, code) + + self.get_guard_manager(guard).add_none_match_guard( + get_verbose_code_parts(code, guard), guard.user_stack + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: value, + eval_fn=lambda value, metadata: value is metadata, + ) + def ID_MATCH(self, guard: Guard, recompile_hint: str | None = None) -> None: + # TODO - Run a CI with the following uncommented to find the remaining places + # val = self.get(guard) + # if inspect.isclass(val): + # raise AssertionError(f"{guard.name} is a class, use CLASS_MATCH guard") + # if inspect.ismodule(val): + # raise AssertionError(f"{guard.name} is a module, use MODULE_MATCH guard") + return self.id_match_unchecked(guard, recompile_hint) + + def id_match_unchecked( + self, guard: Guard, recompile_hint: str | None = None + ) -> None: + # ___check_obj_id is same as `id(x) == y` + if isinstance(guard.originating_source, TypeSource): + # optional optimization to produce cleaner/faster guard code + return self.TYPE_MATCH( + Guard(guard.originating_source.base, GuardBuilder.TYPE_MATCH) # type: ignore[arg-type] + ) + + ref = self.arg_ref(guard) + val = self.get(guard) + id_val = self.id_ref(val, guard.name) + type_repr = _safe_type_repr(val if inspect.isclass(val) else type(val)) + code = f"___check_obj_id({ref}, {id_val}), type={type_repr}" + self._set_guard_export_info(guard, [code], provided_func_name="ID_MATCH") + self.get_guard_manager(guard).add_id_match_guard( + id_val, + get_verbose_code_parts(code, guard, recompile_hint), + guard.user_stack, + ) + + # Keep track of ID_MATCH'd objects. This will be used to modify the + # cache size logic + if isinstance(guard.originating_source, LocalSource): + # TODO(anijain2305) - This is currently restricted to nn.Module objects + # because many other ID_MATCH'd objects fail - like DeviceMesh. + # Increase the scope of ID_MATCH'd objects. + if isinstance(val, torch.nn.Module): + local_name = guard.originating_source.local_name + weak_id = self.lookup_weakrefs(val) + if weak_id is not None: + self.id_matched_objs[local_name] = weak_id + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: None, + eval_fn=lambda value, metadata: value is not None, + ) + def NOT_NONE_MATCH(self, guard: Guard, value: object | None = None) -> None: + ref = self.arg_ref(guard) + val = self.get(guard) + if not isinstance(val, torch.Tensor): + raise AssertionError(f"Expected torch.Tensor, got {type(val)}") + code = f"{ref} is not None" + self._set_guard_export_info(guard, [code]) + + self.get_guard_manager(guard).add_not_none_guard( + get_verbose_code_parts(code, guard), guard.user_stack + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: value.raw_repr(), + eval_fn=lambda value, metadata: value.raw_repr() == metadata, + ) + def DISPATCH_KEY_SET_MATCH(self, guard: Guard) -> None: + ref = self.arg_ref(guard) + val = self.get(guard) + if not isinstance(val, torch._C.DispatchKeySet): + raise AssertionError(f"Expected DispatchKeySet, got {type(val)}") + code_parts = f"{ref}.raw_repr() == {val!r}.raw_repr()" + + self.get_guard_manager(guard).add_dispatch_key_set_guard( + val, + get_verbose_code_parts(code_parts, guard), + guard.user_stack, + ) + + # Global state guard — not source-specific, checked separately at runtime. + @skip_guard_check_spec + def DUAL_LEVEL(self, guard: Guard) -> None: + # Invalidate dual level if current dual level is different than the one + # in the fx graph + if self.check_fn_manager.output_graph is None: + raise AssertionError("check_fn_manager.output_graph must not be None") + dual_level = self.check_fn_manager.output_graph.dual_level + code = [f"torch.autograd.forward_ad._current_level == {dual_level}"] + self._set_guard_export_info(guard, code) + self.guard_manager.root.add_dual_level_match_guard( + dual_level, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + + # Global state guard — not source-specific, checked separately at runtime. + @skip_guard_check_spec + def FUNCTORCH_STACK_MATCH(self, guard: Guard) -> None: + # Invalidate functorch code if current level is different than + # the one when FX graph was generated + if self.check_fn_manager.output_graph is None: + raise AssertionError("check_fn_manager.output_graph must not be None") + cis = self.check_fn_manager.output_graph.functorch_layers + states = [ci.get_state() for ci in cis] + code = [f"torch._functorch.pyfunctorch.compare_functorch_state({states})"] + self._set_guard_export_info(guard, code) + + # TODO(anijain2305) - Consider this moving this guard to C++ + compare_fn = torch._functorch.pyfunctorch.compare_functorch_state + + def fn(x: object) -> bool: + return compare_fn(states) + + self.guard_manager.root.add_lambda_guard( + fn, get_verbose_code_parts(code, guard), guard.user_stack + ) + + # Global state guard — not source-specific, checked separately at runtime. + @skip_guard_check_spec + def AUTOGRAD_SAVED_TENSORS_HOOKS(self, guard: Guard) -> None: + get_hooks = torch._functorch._aot_autograd.utils.top_saved_tensors_hooks + are_inline_hooks = ( + torch._functorch._aot_autograd.utils.saved_tensors_hooks_are_inlineable + ) + + def hooks_ids_fn( + hooks: tuple[Callable[[torch.Tensor], Any], Callable[[Any], torch.Tensor]], + ) -> tuple[int, ...] | None: + if not are_inline_hooks(hooks): + return None + + return tuple(map(id, hooks)) + + guard_hooks_ids = hooks_ids_fn(get_hooks()) + + code = [ + f"torch._functorch.aot_autograd.utils.top_saved_tensors_hooks ids == {guard_hooks_ids}" + ] + self._set_guard_export_info(guard, code) + + def fn(x: object) -> bool: + return guard_hooks_ids == hooks_ids_fn(get_hooks()) + + self.guard_manager.root.add_lambda_guard( + fn, get_verbose_code_parts(code, guard), guard.user_stack + ) + + @register_guard_check_spec( + get_metadata_fn=extract_subclass_metadata, + eval_fn=check_subclass_metadata, + ) + def TENSOR_SUBCLASS_METADATA_MATCH(self, guard: Guard) -> None: + value = self.get(guard) + + # Deepcopying SymInts result in an error from copying FakeTensors. + # Instead we just always assume the metadata is the same. + class _AnyCompare: + def __eq__(self, other: object) -> bool: + return True + + def __ne__(self, other: object) -> bool: + return False + + metadata = value.__tensor_flatten__()[1] + has_custom_guard = hasattr(value, "__metadata_guard__") + if has_custom_guard: + verify_guard_fn_signature(value) + cls = type(value) + else: + _validate_default_subclass_metadata_guard(metadata, type(value)) + + original_metadata = deepcopy( + pytree.tree_map_only(torch.SymInt, lambda _: _AnyCompare(), metadata) + ) + # Either arm runs on every guard evaluation, so they narrow the opaque + # guarded value with a suppression rather than a typing.cast, which + # would be a real call on the check path. + if has_custom_guard: + + def metadata_checker(x: object) -> bool: + return cls.__metadata_guard__( + original_metadata, + x.__tensor_flatten__()[1], # pyrefly: ignore[missing-attribute] + ) + + else: + + def metadata_checker(x: object) -> bool: + # pyrefly: ignore[missing-attribute] + return x.__tensor_flatten__()[1] == original_metadata + + global_name = f"___check_metadata_{id(metadata_checker)}_c{CompileContext.current_compile_id()}" + self.get_guard_manager(guard).add_lambda_guard( + metadata_checker, + get_verbose_code_parts(global_name, guard), + guard.user_stack, + ) + + @register_guard_check_spec( + get_metadata_fn=extract_dtensor_spec, + eval_fn=check_dtensor_spec, + ) + def DTENSOR_SPEC_MATCH(self, guard: Guard) -> None: + # Copied from DTensor __metadata_guard__ + # TODO - Consider moving this to C++ if stable + expected = extract_dtensor_spec(guard, self.get(guard)) + + def guard_fn(x: object) -> bool: + return check_dtensor_spec(x, expected) + + code = f"__dtensor_spec_{id(guard_fn)}" + self.get_guard_manager(guard).add_lambda_guard( + guard_fn, get_verbose_code_parts(code, guard), guard.user_stack + ) + + @register_guard_check_spec( + get_metadata_fn=extract_opaque_obj, + eval_fn=check_opaque_obj, + ) + def OPAQUE_OBJ_GUARD_FN_MATCH(self, guard: Guard) -> None: + """Guard on the values returned by the opaque object's guard_fn.""" + + value = self.get(guard) + original_values = extract_opaque_obj(guard, value) + + if original_values is None: + return + + def opaque_guard_checker(x: object) -> bool: + return check_opaque_obj(x, original_values) + + global_name = f"___check_opaque_guard_fn_{id(opaque_guard_checker)}_c{CompileContext.current_compile_id()}" + self.get_guard_manager(guard).add_lambda_guard( + opaque_guard_checker, + get_verbose_code_parts(global_name, guard), + guard.user_stack, + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: value, + eval_fn=lambda value, metadata: value == metadata, + ) + def EQUALS_MATCH(self, guard: Guard, recompile_hint: str | None = None) -> None: + ref = self.arg_ref(guard) + val = self.get(guard) + if np: + np_types: tuple[type[Any], ...] = ( + np.int8, + np.int16, + np.int32, + np.int64, + np.uint8, + np.uint16, + np.uint32, + np.uint64, + np.float16, + np.float32, + np.float64, + ) + else: + np_types = () + + ok_mutable_types = (list, set) + + ok_types = tuple( + common_constant_types + | { + type, + tuple, + frozenset, + slice, + range, + dict_keys, + torch.Size, + torch.Stream, + torch.cuda.streams.Stream, + *np_types, + *ok_mutable_types, + } + ) + + if torch.distributed.is_available(): + from torch.distributed.device_mesh import _MeshLayout, DeviceMesh + from torch.distributed.tensor.placement_types import ( + _StridedShard, + Partial, + Replicate, + Shard, + ) + + ok_types = ok_types + ( + Shard, + Replicate, + Partial, + DeviceMesh, + _StridedShard, + _MeshLayout, + ) + + from torch.export.dynamic_shapes import _IntWrapper + + ok_types = ok_types + (_IntWrapper,) + + import torch.utils._pytree as pytree + + if not ( + isinstance(val, ok_types) + or pytree.is_constant_class(type(val)) + or is_opaque_constant_type(type(val)) + ): + raise AssertionError(f"Unexpected type {type(val)}") + + # Special case for nan because float("nan") == float("nan") evaluates to False + if istype(val, float) and math.isnan(val): + code = [f"(type({ref}) is float and __math_isnan({ref}))"] + self._set_guard_export_info(guard, code) + + self.get_guard_manager(guard).add_float_is_nan_guard( + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + return + + # Python math library doesn't support complex nan, so we need to use numpy + # pyrefly: ignore [missing-attribute] + if istype(val, complex) and np.isnan(val): + code = [f"(type({ref}) is complex and __numpy_isnan({ref}))"] + self._set_guard_export_info(guard, code) + + self.get_guard_manager(guard).add_complex_is_nan_guard( + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + return + + # Construct a debug string to put into the c++ equals match guard. + code = [f"{ref} == {val!r}"] + if istype(val, ok_mutable_types): + # C++ guards perform a pointer equality check to speedup guards, but the assumption is that the object + # is immutable. For a few corner cases like sets and lists, we make a deepcopy to purposefully fail the + # pointer equality check. + val = deepcopy(val) + + verbose_code_parts = get_verbose_code_parts(code, guard) + if recompile_hint: + verbose_code_parts = [ + f"{part} (HINT: {recompile_hint})" for part in verbose_code_parts + ] + + self.get_guard_manager(guard).add_equals_match_guard( + val, verbose_code_parts, guard.user_stack + ) + self._set_guard_export_info(guard, code) + return + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: value, + eval_fn=lambda value, metadata: value == metadata, + ) + def CONSTANT_MATCH(self, guard: Guard) -> None: + val = self.get(guard) + if istype(val, bool): + self.BOOL_MATCH(guard) + elif val is None: + self.NONE_MATCH(guard) + elif istype(val, types.CodeType): + self.ID_MATCH(guard) + else: + self.EQUALS_MATCH(guard) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: _constant_subclass_base_value(value), + eval_fn=lambda value, metadata: _constant_subclass_base_value(value) + == metadata, + ) + def CONSTANT_SUBCLASS_MATCH(self, guard: Guard) -> None: + """Guard for subclasses of constant types (int, float, str, etc.). + + Extracts the base value using the base type's converter (e.g., + int.__int__) to avoid calling user-overridden __eq__. + """ + from .variables.user_defined import _CONSTANT_BASE_TYPES + + val = self.get(guard) + ref = self.arg_ref(guard) + + # Find the constant base type + base_type = None + for t in _CONSTANT_BASE_TYPES: + if isinstance(val, t): + base_type = t + break + if base_type is None: + raise AssertionError(f"No constant base type found for {type(val)}") + + base_value = base_type(val) + code = [f"{base_type.__name__}({ref}) == {base_value!r}"] + + def check_fn(x: object) -> bool: + # Mirrors _constant_subclass_base_value: base_type is a union of + # int/float/str, none of which typecheck against an opaque arg, + # but x is an instance of base_type by construction. + return base_type(x) == base_value # pyrefly: ignore[bad-argument-type] + + self.get_guard_manager(guard).add_lambda_guard( + check_fn, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: value, + eval_fn=lambda value, metadata: value is metadata, + ) + def NN_MODULE(self, guard: Guard) -> None: + # don't support this in serialization because it uses unsupported ID_MATCH + self.ID_MATCH(guard, "[inline-inbuilt-nn-modules-candidate]") + val = self.get(guard) + if hasattr(val, "training"): + if not istype(val.training, bool): + raise AssertionError( + f"Expected val.training to be bool, got {type(val.training)}" + ) + if not self.guard_nn_modules: + # If guard_nn_modules is true, we will guard on the right set of guards + self._guard_on_attribute(guard, "training", GuardBuilder.CONSTANT_MATCH) # type: ignore[arg-type] + else: + exc.unimplemented( + gb_type="Attempted to guard on uninitialized nn.Module", + context="", + explanation="Attempted to setup an NN_MODULE guard on uninitialized " + f"nn.Module subclass `{type(val)}`.", + hints=[ + "Ensure the `nn.Module` subclass instance has called `super().__init__()`.", + ], + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: value, + eval_fn=lambda value, metadata: value is metadata, + ) + def FUNCTION_MATCH(self, guard: Guard) -> None: + """things like torch.add and user defined functions""" + # don't support this in serialization because it uses unsupported ID_MATCH + return self.ID_MATCH(guard) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: value, + eval_fn=lambda value, metadata: value is metadata, + ) + def CLASS_MATCH(self, guard: Guard) -> None: + """Equals ID_MATCH on classes - better readability than directly calling ID_MATCH""" + val = self.get(guard) + if not inspect.isclass(val): + raise AssertionError( + f"{guard.name} is not a class, but CLASS_MATCH is used" + ) + self.id_match_unchecked(guard) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: value, + eval_fn=lambda value, metadata: value is metadata, + ) + def MODULE_MATCH(self, guard: Guard) -> None: + """Equals ID_MATCH on modules - better readability than directly calling ID_MATCH""" + val = self.get(guard) + if not inspect.ismodule(val): + raise AssertionError( + f"{guard.name} is not a module, but MODULE_MATCH is used" + ) + self.id_match_unchecked(guard) + + @register_guard_check_spec( + get_metadata_fn=extract_closure, + eval_fn=check_closure, + ) + def CLOSURE_MATCH(self, guard: Guard) -> None: + """matches a closure by __code__ id.""" + # don't support this in serialization because it uses unsupported FUNCTION_MATCH + val = self.get(guard) + # Strictly only want user-defined functions + if type(val) is types.FunctionType and hasattr(val, "__code__"): + # No explicit HASATTR guard needed for __code__ — the getattr + # accessor installed by CONSTANT_MATCH implicitly guards hasattr. + self._guard_on_attribute(guard, "__code__", GuardBuilder.CONSTANT_MATCH) # type: ignore[arg-type] + else: + self.FUNCTION_MATCH(guard) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: value, + eval_fn=lambda value, metadata: value is metadata, + ) + def BUILTIN_MATCH(self, guard: Guard) -> None: + if self.save_guards: + # Record which builtin variables are used for pruning later. + if isinstance(guard.originating_source, DictGetItemSource): + self.check_fn_manager.used_builtin_vars.add( + guard.originating_source.index + ) + return self.id_match_unchecked(guard) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: _sequence_length(value), + eval_fn=lambda value, metadata: _sequence_length(value) == metadata, + ) + def SEQUENCE_LENGTH(self, guard: Guard) -> None: + # This guard is used to check length of PySequence objects like list, + # tuple, collections.deque etc + ref = self.arg_ref(guard) + value = self.get(guard) + length = _sequence_length(value) + + if not isinstance(value, dict): + # C++ DICT_LENGTH checks for type + self.TYPE_MATCH(guard) + + code = [] + if isinstance(value, set): + code.append(f"set.__len__({ref}) == {length}") + elif isinstance(value, frozenset): + code.append(f"frozenset.__len__({ref}) == {length}") + elif length == 0: + code.append(f"not {ref}") + else: + code.append(f"len({ref}) == {length}") + + self._set_guard_export_info(guard, code) + if isinstance(value, dict): + self.get_guard_manager(guard).add_dict_length_check_guard( + length, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + else: + self.get_guard_manager(guard).add_length_check_guard( + length, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: tuple_iterator_len(value), + eval_fn=lambda value, metadata: tuple_iterator_len(value) == metadata, + ) + def TUPLE_ITERATOR_LEN(self, guard: Guard) -> None: + ref = self.arg_ref(guard) + value = self.get(guard) + t = type(value) + + code = [] + code.append(f"___tuple_iterator_len({ref}) == {tuple_iterator_len(value)}") + self._set_guard_export_info(guard, code) + + t = type(value) + obj_id = self.id_ref(t, f"type({guard.name})") + + self.get_guard_manager(guard).add_tuple_iterator_length_guard( + tuple_iterator_len(value), + obj_id, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: normalize_range_iter(value), + eval_fn=lambda value, metadata: normalize_range_iter(value) == metadata, + ) + def RANGE_ITERATOR_MATCH(self, guard: Guard) -> None: + ref = self.arg_ref(guard) + value = self.get(guard) + t = type(value) + + code = [] + normalized_range_iter = normalize_range_iter(value) + code.append(f"___normalize_range_iter({ref}) == {normalized_range_iter}") + self._set_guard_export_info(guard, code) + + t = type(value) + obj_id = self.id_ref(t, f"type({guard.name})") + + start, stop, step = normalized_range_iter + self.get_guard_manager(guard).add_range_iterator_match_guard( + start, + stop, + step, + obj_id, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: (type(value), normalize_count_iter(value)), + eval_fn=lambda value, metadata: ( + type(value) is metadata[0] and normalize_count_iter(value) == metadata[1] + ), + ) + def COUNT_ITERATOR_MATCH(self, guard: Guard) -> None: + ref = self.arg_ref(guard) + value = self.get(guard) + count_type = type(value) + normalized_count_iter = normalize_count_iter(value) + + def guard_fn(x: object) -> bool: + return ( + type(x) is count_type + and normalize_count_iter(x) == normalized_count_iter + ) + + code = [f"___normalize_count_iter({ref}) == {normalized_count_iter}"] + self._set_guard_export_info(guard, code) + self.get_guard_manager(guard).add_lambda_guard( + guard_fn, get_verbose_code_parts(code, guard), guard.user_stack + ) + + # Multi-source guard (two inputs aliasing) — not expressible as a + # single source → value check. + # TODO(voz): Deduplicate w/ AOTAutograd dupe input guards + @skip_guard_check_spec + def DUPLICATE_INPUT(self, guard: Guard, source_b: Source) -> None: + if is_from_skip_guard_source( + guard.originating_source + ) or is_from_skip_guard_source(source_b): + return + + if self.save_guards: + if name := get_local_source_name(source_b): + self.check_fn_manager.additional_used_local_vars.add(name) + if name := get_global_source_name(source_b): + self.check_fn_manager.additional_used_global_vars.add(name) + + ref_a = self.arg_ref(guard) + ref_b = self.arg_ref(source_b.name) + + if is_from_optimizer_source( + guard.originating_source + ) or is_from_optimizer_source(source_b): + return + + # Check that the guard has not been inserted already + key = (ref_a, ref_b) + if key in self._cached_duplicate_input_guards: + return + + self._cached_duplicate_input_guards.add((ref_a, ref_b)) + self._cached_duplicate_input_guards.add((ref_b, ref_a)) + + code = [f"{ref_b} is {ref_a}"] + self._set_guard_export_info(guard, code) + + if config.use_lamba_guard_for_object_aliasing: + # Save the code part so that we can install a lambda guard at the + # end. Read the Note - On Lambda guarding of object aliasing - to + # get more information. + code_part = code[0] + verbose_code_part = get_verbose_code_parts(code_part, guard)[0] + self.object_aliasing_guard_codes.append((code_part, verbose_code_part)) + else: + install_object_aliasing_guard( + self.get_guard_manager(guard), + self.get_guard_manager_from_source(source_b), + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: None, + eval_fn=lambda value, metadata: value is not None, + ) + def WEAKREF_ALIVE(self, guard: Guard) -> None: + code = [f"{self.arg_ref(guard)} is not None"] + + self._set_guard_export_info(guard, code) + self.get_guard_manager(guard).add_not_none_guard( + get_verbose_code_parts(code, guard), guard.user_stack + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: list(value.keys()), + eval_fn=lambda value, metadata: list(value.keys()) == metadata, + ) + def MAPPING_KEYS_CHECK(self, guard: Guard) -> None: + """Guard on the key order of types.MappingProxyType object""" + ref = self.arg_ref(guard) + value = self.get(guard) + + code = [] + code.append(f"list({ref}.keys()) == {list(value.keys())}") + self._set_guard_export_info(guard, code) + self.get_guard_manager(guard).add_mapping_keys_guard( + value, code, guard.user_stack + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: list(dict.keys(value)), + eval_fn=lambda value, metadata: list(dict.keys(value)) == metadata, + ) + def DICT_KEYS_MATCH(self, guard: Guard) -> None: + """Insert guard to check that the keys of a dict are same""" + ref = self.arg_ref(guard) + value = self.get(guard) + + # SUPPORTED_NODES normally uses DICT_VERSION (PEP 509) as an O(1) fast + # path. That guard cannot be serialized, so when saving we fall through + # to keys-match and stick the choice on the Guard. Load rebuilds with + # save_guards=False but sees the pickled flag, so it keeps keys-match + # instead of re-promoting to DICT_VERSION. + if value is torch.utils._pytree.SUPPORTED_NODES: + if self.save_guards: + guard._force_dict_keys_match = True + if not guard._force_dict_keys_match: + self.DICT_VERSION(guard) + return + + self.SEQUENCE_LENGTH(guard) + + code = [] + # Ensure that we call dict.keys and not value.keys (which can call + # overridden keys method). In the C++ guards, we relied on PyDict_Next + # to traverse the dictionary, which uses the internal data structure and + # does not call the overridden keys method. + code.append(f"list(dict.keys({ref})) == {list(builtin_dict_keys(value))!r}") + self._set_guard_export_info(guard, code) + + if self.requires_key_order_guarding(guard.originating_source): + self.guard_on_dict_keys_and_order(value, guard) + else: + self.guard_on_dict_keys_and_ignore_order(value, guard) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: None, + eval_fn=lambda value, metadata: len(value) == 0, + ) + def EMPTY_NN_MODULE_HOOKS_DICT(self, guard: Guard) -> None: + """Special guard to skip guards on empty hooks. This is controlled by skip_nnmodule_hook_guards""" + if config.skip_nnmodule_hook_guards: + # This is unsafe if you add/remove a hook on nn module variable + return + self.SEQUENCE_LENGTH(guard) + + # Global state guard — not source-specific, checked separately at runtime. + @skip_guard_check_spec + def GRAD_MODE(self, guard: Guard) -> None: + pass # we always guard on this via GlobalStateGuard() + + # Global state guard — not source-specific, checked separately at runtime. + @skip_guard_check_spec + def DETERMINISTIC_ALGORITHMS(self, guard: Guard) -> None: + pass # we always guard on this via GlobalStateGuard() + + # Global state guard — not source-specific, checked separately at runtime. + @skip_guard_check_spec + def FSDP_TRAINING_STATE(self, guard: Guard) -> None: + pass # we always guard on this via GlobalStateGuard() + + # Global state guard — not source-specific, checked separately at runtime. + @skip_guard_check_spec + def GLOBAL_STATE(self, guard: Guard) -> None: + output_graph = self.check_fn_manager.output_graph + if output_graph is None: + raise AssertionError("output_graph must not be None") + global_state = output_graph.global_state_guard + self.check_fn_manager.global_state = global_state + + code = [ + f"___check_global_state() against {self.check_fn_manager.global_state.__getstate__()}" + ] + + self.guard_manager.root.add_global_state_guard( + global_state, code, guard.user_stack + ) + + # Global state guard — not source-specific, checked separately at runtime. + @skip_guard_check_spec + def TORCH_FUNCTION_STATE(self, guard: Guard) -> None: + if self.check_fn_manager.torch_function_mode_stack is None: + raise AssertionError("torch_function_mode_stack must not be None") + self.check_fn_manager.torch_function_mode_stack_check_fn = ( + make_torch_function_mode_stack_guard( + self.check_fn_manager.torch_function_mode_stack + ) + ) + self.guard_manager.root.add_torch_function_mode_stack_guard( + self.check_fn_manager.torch_function_mode_stack, + ["___check_torch_function_mode_stack()"], + guard.user_stack, + ) + + # Global state guard — not source-specific, checked separately at runtime. + @skip_guard_check_spec + def DEFAULT_DEVICE(self, guard: Guard) -> None: + """Guard on CURRENT_DEVICE per torch.utils._device""" + if guard.source is not GuardSource.GLOBAL: + raise AssertionError(f"Expected GuardSource.GLOBAL, got {guard.source}") + + if self.check_fn_manager.output_graph is None: + raise AssertionError("check_fn_manager.output_graph must not be None") + code = [ + f"utils_device.CURRENT_DEVICE == {self.check_fn_manager.output_graph.current_device!r}" + ] + self._set_guard_export_info(guard, code) + + self.get_guard_manager(guard).add_default_device_guard( + get_verbose_code_parts(code, guard), guard.user_stack + ) + + @skip_guard_check_spec + def SHAPE_ENV(self, guard: Guard) -> None: + from torch._dynamo.output_graph import OutputGraphCommon + + if guard.name != "": + raise AssertionError(f"Expected empty guard name, got {guard.name!r}") + output_graph = self.check_fn_manager.output_graph + if output_graph is None: + raise AssertionError("output_graph must not be None") + if self.check_fn_manager.shape_code_parts is not None: + shape_code_parts = self.check_fn_manager.shape_code_parts + python_code_parts = shape_code_parts.python_code_parts + verbose_code_parts = shape_code_parts.verbose_code_parts + if shape_code_parts.cpp_code_parts is not None: + cpp_code_parts = shape_code_parts.cpp_code_parts + python_fallback = shape_code_parts.python_fallback + else: + # Let's handle ShapeEnv guards. To do this, we will resolve + # shape variables to sources from tracked_fakes. This must happen after + # tensor checks. + # NB: self.output_graph can be None in the debug_nops tests + if not isinstance(output_graph, OutputGraphCommon): + raise AssertionError( + f"Expected OutputGraphCommon, got {type(output_graph)}" + ) + if output_graph.shape_env is None: + raise AssertionError("output_graph.shape_env must not be None") + fs = output_graph.shape_env.tracked_fakes or [] + input_contexts = [a.symbolic_context for a in fs] + + def get_sources(t_id: int, dim: int) -> list[Source]: + # Looks up base sources mapped to a tensor id and uses them to create + # sources for the corresponding tensor dimension. + return [ + TensorPropertySource(source, TensorProperty.SIZE, dim) + # pyrefly: ignore [missing-attribute] + for source in output_graph.tracked_fakes_id_to_source[t_id] + ] + + if output_graph.export_constraints: + names: dict[str, tuple[int, int]] = {} + source_pairs: list[tuple[Source, Source]] = [] + derived_equalities: list[ # type: ignore[type-arg] + # pyrefly: ignore [implicit-any] + tuple[Source, Source | Symbol, Callable] + ] = [] + phantom_symbols: dict[str, Symbol] = {} + relaxed_sources: set[Source] = set() + for constraint in output_graph.export_constraints: # type: ignore[attr-defined] + if constraint.t_id in output_graph.tracked_fakes_id_to_source: + torch.export.dynamic_shapes._process_equalities( + constraint, + get_sources, + output_graph.shape_env, + names, + source_pairs, + derived_equalities, + phantom_symbols, + relaxed_sources, + ) + else: + log.warning("Untracked tensor used in export constraints") + equalities_inputs = EqualityConstraint( + source_pairs=source_pairs, + derived_equalities=derived_equalities, + phantom_symbols=list(phantom_symbols.values()), + relaxed_sources=relaxed_sources, + warn_only=False, + ) + else: + equalities_inputs = None + + def _get_code_parts(langs: tuple[str, ...]) -> list[_ShapeGuardsHelper]: + # pyrefly: ignore [missing-attribute] + return output_graph.shape_env.produce_guards_verbose( + [a.fake for a in fs], # type: ignore[misc] + [a.source for a in fs], + input_contexts=input_contexts, # type: ignore[arg-type] + equalities_inputs=equalities_inputs, + source_ref=self.source_ref, + # Export keeps static. + # pyrefly: ignore [missing-attribute] + ignore_static=(not output_graph.export), + langs=langs, + ) + + if config.enable_cpp_symbolic_shape_guards: + try: + # For exporting we need the python code parts + python_code_parts, verbose_code_parts, cpp_code_parts = ( + _get_code_parts(("python", "verbose_python", "cpp")) # type: ignore[assignment] + ) + python_fallback = False + except OverflowError: + # Cannot use int64_t + python_fallback = True + python_code_parts, verbose_code_parts = _get_code_parts( + ("python", "verbose_python") + ) + else: + python_fallback = True + python_code_parts, verbose_code_parts = _get_code_parts( + ("python", "verbose_python") + ) + + # When exporting, we may work with the shape constraints some more in + # postprocessing, so don't freeze yet + if not output_graph.export: + output_graph.shape_env.freeze() + + if self.save_guards: + # For SHAPE_ENV we want to skip serializing the entire ShapeEnv so instead + # we directly serialize the generated code here. + maybe_cpp_code_parts = locals().get("cpp_code_parts") + if maybe_cpp_code_parts is not None and not isinstance( + maybe_cpp_code_parts, _CppShapeGuardsHelper + ): + raise AssertionError( + f"Expected None or _CppShapeGuardsHelper, got {type(maybe_cpp_code_parts)}" + ) + maybe_shape_env_sources = ( + [] + if maybe_cpp_code_parts is None + else list(maybe_cpp_code_parts.source_to_symbol.keys()) + ) + self.check_fn_manager.shape_code_parts = ShapeCodeParts( + python_code_parts=python_code_parts, + verbose_code_parts=verbose_code_parts, + cpp_code_parts=maybe_cpp_code_parts, + python_fallback=python_fallback, + shape_env_sources=maybe_shape_env_sources, + ) + + for code in python_code_parts.exprs: + self._set_guard_export_info(guard, [code]) + + # Make ShapeEnv guards available for testing. + if compile_context := CompileContext.try_get(): + compile_context.shape_env_guards.extend(verbose_code_parts.exprs) + + int_source_to_symbol = [] + float_source_to_symbol = [] + + if not python_fallback: + if not cpp_code_parts: # type: ignore[possibly-undefined] + raise AssertionError( + "cpp_code_parts must be set when not using python_fallback" + ) + code_parts, source_to_symbol = ( + # pyrefly: ignore [unbound-name] + cpp_code_parts.exprs, + # pyrefly: ignore [unbound-name, missing-attribute] + cpp_code_parts.source_to_symbol, + ) + + if not code_parts: + return + + for source, symbol in source_to_symbol.items(): + if isinstance(source, ConstantSource): + python_fallback = True + else: + example_value = self.get( + source, + closure_vars={**SYMPY_INTERP, **_get_closure_vars()}, + ) + if isinstance(example_value, int): + int_source_to_symbol.append((source, symbol)) + elif isinstance(example_value, float): + float_source_to_symbol.append((source, symbol)) + else: + # SymInts/SymFloats go through python guard as we only support + # int64_t/double in C++ guards for now. + python_fallback = True + + if not python_fallback: + import ctypes + + from torch._inductor.codecache import CppCodeCache + + if not cpp_code_parts: # type: ignore[possibly-undefined] + raise AssertionError( + "cpp_code_parts must be set when not using python_fallback" + ) + code_parts, source_to_symbol = ( + # pyrefly: ignore [unbound-name] + cpp_code_parts.exprs, + # pyrefly: ignore [unbound-name, missing-attribute] + cpp_code_parts.source_to_symbol, + ) + + source_to_symbol = dict(int_source_to_symbol + float_source_to_symbol) + try: + guard_managers = [ + self.get_guard_manager_from_source(IndexedSource(source, i)) + for i, source in enumerate(source_to_symbol) + ] + + int_symbols_str = ", ".join( + f"{symbol} = int_values[{i}]" + for i, (_, symbol) in enumerate(int_source_to_symbol) + ) + float_symbols_str = ", ".join( + f"{symbol} = float_values[{i}]" + for i, (_, symbol) in enumerate(float_source_to_symbol) + ) + + if int_symbols_str: + int_symbols_str = f"int64_t {int_symbols_str};" + if float_symbols_str: + float_symbols_str = f"double {float_symbols_str};" + + func_str = textwrap.dedent( + f""" + #include + #include + #include + #include + + #if defined(_MSC_VER) + # define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport) + #else + # define EXTERN_DLL_EXPORT extern "C" + #endif + + EXTERN_DLL_EXPORT int8_t guard(int64_t *int_values, double *float_values) {{ + {int_symbols_str} + {float_symbols_str} + return ({") && (".join(code_parts)}); + }} + """ + ) + guards_log.debug( + "C++ shape guard function: %s %s", + func_str, + verbose_code_parts.exprs, + ) + clib = CppCodeCache.load(func_str) + cguard = ctypes.cast(clib.guard, ctypes.c_void_p).value + if not cguard: + raise AssertionError("Failed to load C++ shape guard function") + except torch._inductor.exc.InvalidCxxCompiler: + # No valid C++ compiler to compile the shape guard + pass + else: + install_symbolic_shape_guard( + guard_managers, + len(int_source_to_symbol), + len(float_source_to_symbol), + cguard, + clib, + verbose_code_parts.exprs, + guard.user_stack, + ) + return + + # Install all the symbolic guards in one python lambda guard. These are run + # at the very end of the RootGuardManager via epilogue guards. + # TODO(anijain2305,williamwen42) - Consider moving this to C++. + if python_code_parts.exprs: + self.add_python_lambda_leaf_guard_to_root( + python_code_parts.exprs, + verbose_code_parts.exprs, + closure_vars={**SYMPY_INTERP, **_get_closure_vars()}, + ) + + @register_guard_check_spec( + get_metadata_fn=lambda guard, value: extract_tensor_metadata(value), + eval_fn=lambda value, metadata: ( + isinstance(value, torch.Tensor) + and extract_tensor_metadata(value) == metadata + ), + ) + def TENSOR_MATCH(self, guard: Guard, value: Any | None = None) -> None: + if config._unsafe_skip_fsdp_module_guards and guard.is_fsdp_module(): + return + # For tensors that are part of the Dynamo extracted Fx graph module, an + # ID_MATCH suffices. + if match_on_id_for_tensor(guard): + self.ID_MATCH(guard) + else: + if isinstance(value, TensorWeakRef): + value = value() + + value = value if value is not None else self.get(guard) + + pytype = type(value) + dispatch_keys = torch._C._dispatch_keys(value) + if isinstance( # noqa: ISINSTANCE_FAKE_TENSOR + value, torch._subclasses.FakeTensor + ): + if value.pytype is not None: + pytype = value.pytype + if value.dispatch_keys is not None: + dispatch_keys = value.dispatch_keys + + if not isinstance(value, torch.Tensor): + raise AssertionError(f"Expected torch.Tensor, got {type(value)}") + + if config.log_compilation_metrics and isinstance(value, torch.nn.Parameter): + metrics_context = get_metrics_context() + if metrics_context.in_progress(): + metrics_context.increment("param_numel", value.numel()) + metrics_context.increment("param_bytes", value.nbytes) + metrics_context.increment("param_count", 1) + + tensor_name = self.arg_ref(guard) + # [Note - On Export Tensor Guards] + # + # In eager mode, tensor guards are evaluated through C++, in guards.cpp + # see [Note - On Eager Tensor Guards] for more info. + # + # In export mode, we instead maintain parallel logic between C++ and python + # here, with an exception of checking the dispatch key - with the idea that a dispatch key + # is an entirely runtime notion that would make no sense to keep in an exported graph. + # + # Now, this idea is okay, but to paraphrase @ezyang, this mental model is sufficient for now, although + # not entirely true. + # For example, suppose one of the input tensors had the negative dispatch key. + # You should end up with a graph that is specialized for tensors that have a negative dispatch key. + # If you allow a Tensor that does NOT have this bit set, you will accidentally run it "as if" it were negated. + # Now, negative key only shows up for complex numbers, and most likely, the exported to target doesn't + # support this feature at all, but the point stands that :some: tensor state only shows up on dispatch key. + # TODO(voz): Either populate a dispatch_key check into the guards, or error on users passing in an unsupported + # subset of keys during export. + # + # The list of tensor fields and calls we care about can be found in `terms` below. + # TODO(voz): We are missing storage offset in all our tensor guards? + code: list[str] = [] + if self.check_fn_manager.output_graph is None: + raise AssertionError("check_fn_manager.output_graph must not be None") + if self.check_fn_manager.output_graph.export: + self.TYPE_MATCH(guard) + terms = [ + "dtype", + "device", + "requires_grad", + "ndimension", + ] + + for term in terms: + term_src = AttrSource(guard.originating_source, term) + if term == "ndimension": + term = "ndimension()" + term_src = CallFunctionNoArgsSource(term_src) + real_value = self.get(term_src) + if istype(real_value, (torch.device, torch.dtype)): + # copy pasted from EQUALS_MATCH + code.append(f"str({tensor_name}.{term}) == {str(real_value)!r}") + else: + code.append(f"{tensor_name}.{term} == {real_value}") + else: + guard_manager = self.get_guard_manager(guard) + + # skip_no_tensor_aliasing_guards_on_parameters bring + # unsoundness. If you compile a function with two different + # parameters, but later on you pass on same tensor as two + # different outputs (aliasing), Dynamo will not detect this. + # But we deliberately take this soundness hit because this + # usecase is quite rare and there is substantial reduction in + # guard overhead. + # For numpy tensors, since those are ephemeral, we don't have to + # insert aliasing guards on them + if not ( + config.skip_no_tensor_aliasing_guards_on_parameters + and ( + istype(value, torch.nn.Parameter) + or is_from_unspecialized_builtin_nn_module_source( + guard.originating_source + ) + ) + ) and not isinstance(guard.originating_source, NumpyTensorSource): + # Keep track of all the tensor guard managers to insert + # NoAliasing check at the end. + self.no_tensor_aliasing_names.append(tensor_name) + self.no_tensor_aliasing_guard_managers.append(guard_manager) + + output_graph = self.check_fn_manager.output_graph + metadata = output_graph.input_source_to_sizes_strides[ + guard.originating_source + ] + size = convert_to_concrete_values(metadata["size"]) + stride = convert_to_concrete_values(metadata["stride"]) + + verbose_code_parts = get_verbose_code_parts( + get_tensor_guard_code_part( + value, + tensor_name, + size, + stride, + pytype, + dispatch_keys, + ), + guard, + ) + user_stack = guard.user_stack + guard_manager.add_tensor_match_guard( + value, + size, # type: ignore[arg-type] + stride, # type: ignore[arg-type] + tensor_name, + verbose_code_parts, + user_stack, + pytype, + dispatch_keys, + ) + + # We consider TENSOR_MATCH guard to be important enough to be + # included in diff guard manager by default. + if not isinstance(value, torch.nn.Parameter): + self.guard_manager.diff_guard_sources.add(guard.name) + + if guard.source is None: + raise AssertionError("guard.source must not be None") + + # [Note: Dimension Marking Guards] + # Guards for user explicit dynamism (mark_dynamic, mark_unbacked, mark_static..). + # + # Marking APIs express additive constraints: mark_dynamic(x, [0]) means + # "ensure dim 0 is dynamic" — it says nothing about other dims. If you + # want a dim to NOT be dynamic, explicitly mark it static (or unbacked). + # + # Guard semantics (subset matching): + # - Compiled WITH attribute, runtime HAS attribute → runtime markings + # must be a SUBSET of compiled markings. This means the compiled graph + # can satisfy the requested marking. + # - Compiled WITH attribute, runtime NO attribute → pass (unspecified = don't care) + # - Compiled WITHOUT attribute, runtime HAS attribute → recompile (new marking) + # + # Passing an empty list [] to any marking API is a no-op (same as not calling + # the function at all). Calls are additive. + # + # Examples: + # 1. Compile with mark_dynamic(x, [0,1]), call with mark_dynamic(x, [0]) → no recompile (subset) + # 2. Compile with mark_dynamic(x, [0]), call with mark_dynamic(x, [0,1]) → recompile (not a subset) + # 3. Compile with mark_dynamic(x, [0]), call with plain tensor → no recompile (unspecified = don't care) + # 4. Compile with plain tensor, call with mark_dynamic(x, [0]) → recompile (new marking added) + # + # _dynamo_weak_dynamic_indices vs _dynamo_propagated_dynamic_indices: + # _dynamo_weak_dynamic_indices is the user-facing attribute, set via + # maybe_mark_dynamic(), and guarded on like the other dimension marking + # attributes above. + # _dynamo_propagated_dynamic_indices is a compiler-internal attribute set by + # AOTAutograd's mark_dynamo_propagated_dynamic_indices() to propagate dynamism across + # graph breaks. It is NOT guarded on. When AOTAutograd discovers that an + # output dimension is symbolic, it stamps this attribute on the output tensor + # so that Dynamo treats those dims as weakly dynamic when the tensor appears + # as input to a subsequent graph. Using a separate unguarded attribute avoids + # spurious guard failures when the compiler mutates an input tensor's + # attributes through an input-aliased output. + # + # Collect dimension marking guard info for a single C++ guard. + dim_marking_attrs = ( + "_dynamo_dynamic_indices", + "_dynamo_weak_dynamic_indices", + "_dynamo_unbacked_indices", + "_dynamo_strict_unbacked_indices", + "_dynamo_static_indices", + ) + + expected_attrs: dict[str, set[int]] = {} + absent_attrs: list[str] = [] + for attr_name in dim_marking_attrs: + if hasattr(value, attr_name): + expected_attrs[attr_name] = getattr(value, attr_name) + code_part = f"((getattr({tensor_name}, '{attr_name}', set()).issubset({getattr(value, attr_name)!r})) if hasattr({tensor_name}, '{attr_name}') else True)" + code.append(code_part) + else: + absent_attrs.append(attr_name) + code_part = f"hasattr({tensor_name}, '{attr_name}') == False" + code.append(code_part) + + # Dependent attributes: checked only when _dynamo_unbacked_indices is present. + dependent_attrs: dict[str, tuple[dict[int, Any] | None, str]] = {} + dep_attr_names = ("_dynamo_shape_ids", "_dynamo_unbacked_bounds") + gate_attr = "_dynamo_unbacked_indices" + if hasattr(value, gate_attr): + for attr_name in dep_attr_names: + attr_value = getattr(value, attr_name, None) + dependent_attrs[attr_name] = (attr_value, gate_attr) + code_part = f"((getattr({tensor_name}, '{attr_name}', None) == {attr_value!r}) if hasattr({tensor_name}, '{gate_attr}') else True)" + code.append(code_part) + + # Install a single C++ guard for all dimension marking attributes. + if expected_attrs or absent_attrs or dependent_attrs: + self.get_guard_manager(guard).add_dimension_marking_guard( + expected_attrs, + absent_attrs, + dependent_attrs, + get_verbose_code_parts(code, guard), + guard.user_stack, + ) + + if len(code) > 0: + self._set_guard_export_info(guard, code) + + # A util that in the case of export, adds data onto guards + def _set_guard_export_info( + self, + guard: Guard, + code_list: list[str], + provided_guarded_object: object | None = None, + provided_func_name: str | None = None, + ) -> None: + # WARNING: It is important that cur_frame/caller do NOT stay in + # the current frame, because they will keep things live longer + # than they should. See TestMisc.test_release_module_memory + cur_frame = currentframe() + if cur_frame is None: + raise AssertionError("currentframe() returned None") + caller = cur_frame.f_back + del cur_frame + if caller is None: + raise AssertionError("caller frame must not be None") + func_name = provided_func_name or caller.f_code.co_name + del caller + # We use func_name for export, so might as well get a nice defensive check out of it + if func_name not in self.__class__.__dict__: + raise AssertionError( + f"_produce_guard_code must be called from inside GuardedCode. Called from {func_name}" + ) + + # Not all guards have names, some can be installed globally (see asserts on HAS_GRAD) + if provided_guarded_object is None: + name = guard.name + guarded_object = None if not name else self.get(guard) + else: + guarded_object = provided_guarded_object + + guarded_object_type = ( + weakref.ref(type(guarded_object)) if guarded_object is not None else None + ) + obj_ref = None + # Not necessary to have weakref for Enum type, but there is a bug that + # makes hasattr(guarded_object.__class__, "__weakref__") return True. + supports_weakref = ( + getattr(guarded_object.__class__, "__weakrefoffset__", 0) != 0 + ) + # See D64140537 for why we are checking for tuple. + if supports_weakref and not isinstance( + guarded_object, (enum.Enum, tuple, weakref.ProxyTypes) + ): + obj_ref = weakref.ref(guarded_object) + + guard.set_export_info( + func_name, + guarded_object_type, + code_list, + obj_ref, + ) + + +# Common Sub-Expression Elimination for Python expressions. +# +# There are 2 steps to this pass: +# 1. Count the frequency of each sub-expression (i.e. inner +# node in the AST tree) +# +# 2. Replace those that occur more than once by a fresh variable 'v'. +# 'v' will be defined in the 'preface' list (output argument to +# 'NodeTransformer') +# +# NB: the use of 'ast.unparse' while visiting the nodes makes this pass +# quadratic on the depth of the tree. +# +# NB: this pass creates a new variable for each AST node that is repeated +# more than 'USE_THRESHOLD'. e.g. if 'a.b.c.d' is used 10 times, 'a.b.c' +# and 'a.b' are also used 10 times. So, there will be a new variable for +# each of them. +class PyExprCSEPass: + # Maximum number of times a given expression can be used without being + # replaced by a fresh variable. + USE_THRESHOLD = 1 + + # Ad-Hoc: AST nodes this pass focuses on. + ALLOWED_NODE_TYPES = (ast.Attribute, ast.Call, ast.Subscript) + + @dataclasses.dataclass + class Config: + expr_count: dict[str, int] + expr_to_name: dict[str, str] + + class ExprCounter(ast.NodeVisitor): + def __init__(self, config: PyExprCSEPass.Config) -> None: + self._config = config + + def visit(self, node: ast.AST) -> None: + if isinstance(node, PyExprCSEPass.ALLOWED_NODE_TYPES): + self._config.expr_count[_ast_unparse(node)] += 1 + super().visit(node) + + class Replacer(ast.NodeTransformer): + def __init__( + self, + config: PyExprCSEPass.Config, + gen_name: Callable[[], str], + ) -> None: + super().__init__() + self._config = config + self._gen_name = gen_name + self.preface: list[str] = [] + + def visit(self, node: ast.AST) -> Any: + if isinstance(node, PyExprCSEPass.ALLOWED_NODE_TYPES): + expr = _ast_unparse(node) + + # Replacement only occurs if a given expression is used more + # than once. + if self._config.expr_count[expr] > PyExprCSEPass.USE_THRESHOLD: + if expr not in self._config.expr_to_name: + # Parent 'visit' is called so that we CSE the inner expressions first. + # + # The resulting expression is used as right-hand-side of the variable + # assignment. i.e. we are CSE-ing the children before the parents. + # + # Indexing still uses the old 'node', since that's what was counted + # by the 'NodeVisitor'. + node_ = super().visit(node) + expr_ = _ast_unparse(node_) + var_name = self._gen_name() + self.preface.append(f"{var_name} = {expr_}") + self._config.expr_to_name[expr] = var_name + else: + var_name = self._config.expr_to_name[expr] + return ast.Name(var_name, ast.Load()) + + return super().visit(node) + + def __init__(self) -> None: + self._counter = 0 + self._config = self.Config( + expr_count=collections.defaultdict(lambda: 0), expr_to_name={} + ) + + def _new_var(self, prefix: str = "_var") -> str: + name = f"{prefix}{self._counter}" + self._counter += 1 + return name + + def count(self, exprs: list[str]) -> None: + counter = self.ExprCounter(self._config) + for e in exprs: + try: + counter.visit(ast.parse(e)) + except SyntaxError as ex: + log.exception("Failed to visit expr at line %s.\n%s", ex.lineno, e) + raise + + def replace(self, expr: str) -> tuple[list[str], str]: + replacer = self.Replacer(self._config, self._new_var) + new_node = replacer.visit(ast.parse(expr)) + return replacer.preface, _ast_unparse(new_node) + + +def must_add_nn_module_guards(guard: Guard) -> bool: + # For config.guard_nn_modules=False, we can skip all the guards that + # originate from inside of nn module except for a few categories. + return ( + # Guard for defaults + isinstance(guard.originating_source, DefaultsSource) + # Guard using dict tags if the config flag is set + or ( + config.guard_nn_modules_using_dict_tags + and guard.create_fn is GuardBuilder.NN_MODULE + ) + ) + + +class DeletedGuardManagerWrapper(GuardManagerWrapper): + def __init__(self, reason: str) -> None: + super().__init__() + self.invalidation_reason = reason + + def populate_diff_guard_manager(self) -> None: + self.diff_guard_root = None + + +@dataclasses.dataclass +class ShapeCodeParts: + python_code_parts: _ShapeGuardsHelper + verbose_code_parts: _ShapeGuardsHelper + cpp_code_parts: _CppShapeGuardsHelper | None + python_fallback: bool + shape_env_sources: list[Source] + + +@dataclasses.dataclass +class GuardsState: + output_graph: OutputGraphGuardsState + shape_code_parts: ShapeCodeParts | None + local_state: Any | None = None + + +class _Missing: + def __init__(self, reason: str | None = None) -> None: + self._reason = reason + + def __repr__(self) -> str: + return f"_Missing({self._reason})" + + def __str__(self) -> str: + return f"_Missing({self._reason})" + + # Sometimes _Missing object is used as the callable with functools.partial, + # so we add a dummy __call__ here to bypass TypeError from partial(). + def __call__(self, *args: Any, **kwargs: Any) -> Any: + return _Missing() + + +@functools.cache +def _get_unsupported_types() -> tuple[type, ...]: + # We only do ID_MATCH on C objects which is already banned from guards serialization. + ret: tuple[type, ...] = ( + torch._C.Stream, + weakref.ReferenceType, + ) + try: + ret += (torch._C._distributed_c10d.ProcessGroup,) + except AttributeError: + pass + return ret + + +class GuardsStatePickler(pickle.Pickler): + def __init__( + self, + guard_tree_values: dict[int, Any], + empty_values: dict[int, Any], + missing_values: dict[int, Any], + *args: Any, + **kwargs: Any, + ) -> None: + super().__init__(*args, **kwargs) + self.fake_mode = torch._subclasses.FakeTensorMode() + self.tensor_converter = torch._subclasses.fake_tensor.FakeTensorConverter() + self.guard_tree_values = guard_tree_values + self.empty_values = empty_values + self.missing_values = missing_values + + @classmethod + def _unpickle_module(cls, state: Any) -> torch.nn.Module: + mod = torch.nn.Module() + mod.__setstate__(state) + return mod + + @classmethod + def _unpickle_tensor( + cls, + meta_tensor: torch.Tensor, + device: torch.device, + pytype: type, + dispatch_keys_raw: int, + grad: torch.Tensor, + ) -> torch.Tensor: + fake_mode = torch._subclasses.FakeTensorMode() + tensor_converter = torch._subclasses.fake_tensor.FakeTensorConverter() + ret = tensor_converter.from_meta_and_device( + fake_mode, + meta_tensor, + device, + pytype, + torch._C.DispatchKeySet.from_raw_repr(dispatch_keys_raw), + ) + ret.grad = grad + return ret + + @classmethod + def _unpickle_traceable_wrapper_subclass( + cls, + meta_tensor: torch.Tensor, + device: torch.device, + pytype: type, + dispatch_keys_raw: int, + ctx: Any, + inner_data: list[tuple[str, Any]], + ) -> torch.Tensor: + inner_tensors = dict(inner_data) + + outer_size, outer_stride = meta_tensor.shape, meta_tensor.stride() + # Use the recorded pytype, not type(meta_tensor): a transparent wrapper + # subclass (e.g. AsyncCollectiveTensor) whose __torch_dispatch__ desugars + # ops to its inner tensor makes torch.empty_like() return a plain Tensor, + # so meta_tensor loses the subclass type and Tensor.__tensor_unflatten__ + # does not exist. + out = pytype.__tensor_unflatten__( # type: ignore[attr-defined] + inner_tensors, ctx, outer_size, outer_stride + ) + out.pytype = pytype + out.dispatch_keys = torch._C.DispatchKeySet.from_raw_repr(dispatch_keys_raw) + return out + + @classmethod + def _unpickle_python_module(cls, alias: str) -> types.ModuleType: + return importlib.import_module(alias) + + @classmethod + def _unpickle_dispatch_key_set(cls, raw_repr: int) -> torch._C.DispatchKeySet: + return torch._C.DispatchKeySet.from_raw_repr(raw_repr) + + @classmethod + def _unpickle_functorch_interpreter( + cls, json: bytes + ) -> torch._C._functorch.CInterpreter: + return torch._C._functorch.CInterpreter.deserialize(json) + + @classmethod + def _unpickle_mapping_proxy( + cls, d: dict[Any, Any] + ) -> types.MappingProxyType[Any, Any]: + return types.MappingProxyType(d) + + @classmethod + def _unpickle_dict_keys(cls, elems: list[Any]) -> Any: + return dict.fromkeys(elems).keys() + + @classmethod + def _unpickle_count_iter(cls, item: int, step: int) -> itertools.count[int]: + return itertools.count(item, step) + + @classmethod + def _unpickle_fsdp_module_type( + cls, original_type: type[torch.nn.Module] + ) -> type[torch.nn.Module]: + return torch.distributed.fsdp._fully_shard._fully_shard.get_cls_to_fsdp_cls()[ + original_type + ] + + @classmethod + def _unpickle_ddp_module( + cls, state: dict[str, Any] + ) -> torch.nn.parallel.DistributedDataParallel: + ty = torch.nn.parallel.DistributedDataParallel + ddp = ty.__new__(ty) + torch.nn.Module.__setstate__(ddp, state) + return ddp + + @classmethod + def _unpickle_c_op(cls, name: str) -> Any: + return getattr(torch.ops._C, name) + + @classmethod + def _unpickle_op(cls, namespace: str, opname: str, overloadname: str) -> Any: + return getattr(getattr(getattr(torch.ops, namespace), opname), overloadname) + + @classmethod + def _unpickle_bound_method(cls, func: Any, base: Any) -> Any: + return types.MethodType(func, base) + + @staticmethod + def _unpickle_sdp_backend(name: str) -> torch.nn.attention.SDPBackend: + # Reconstruct from the Python-facing enum namespace + return getattr(torch.nn.attention.SDPBackend, name) + + @classmethod + def _unpickle_cell(cls, val: Any) -> Any: + def _() -> Any: + return val + + if _.__closure__ is None: + raise AssertionError("Closure must not be None when unpickling cell") + return _.__closure__[0] + + @classmethod + def _unpickle_named_tuple_type( + cls, name: str, fields: tuple[str, ...] + ) -> type[NamedTuple]: + # pyrefly: ignore [bad-return] + return collections.namedtuple(name, fields) + + @classmethod + def _unpickle_code(cls, serialized_code: SerializedCode) -> types.CodeType: + from torch._dynamo.package import SerializedCode + + return SerializedCode.to_code_object(serialized_code) + + @classmethod + def _unpickle_nested_function( + cls, + code: types.CodeType, + module: str, + qualname: str, + argdefs: tuple[object, ...] | None, + closure: tuple[types.CellType, ...] | None, + ) -> types.FunctionType: + f_globals = importlib.import_module(module).__dict__ + return types.FunctionType(code, f_globals, qualname, argdefs, closure) + + # pyrefly: ignore [bad-override] + def reducer_override( + self, obj: Any + ) -> tuple[Callable[..., Any], tuple[Any, ...]] | Any: + import sympy + + if id(obj) in self.empty_values: + return type(obj).__new__, (type(obj),) + + if inspect.iscode(obj): + from torch._dynamo.package import SerializedCode + + return type(self)._unpickle_code, (SerializedCode.from_code_object(obj),) + + if id(obj) in self.missing_values: + return _Missing, ("missing values",) + + if isinstance(obj, torch.Tensor) and obj.device.type != "meta": + from torch.utils._python_dispatch import is_traceable_wrapper_subclass + + if id(obj) not in self.guard_tree_values: + return _Missing, ("tensor guard tree",) + + if is_traceable_wrapper_subclass(obj): + # inner_data is a list of tuples of: + # (inner attr name, unpickle func, tuple of func inputs) + # This supports traceable wrapper subclass inner tensors. + inner_data = [] + attrs, ctx = obj.__tensor_flatten__() + # recursively call for inner tensor components + for attr in attrs: + inner = getattr(obj, attr) + if isinstance(inner, torch.Tensor): + self.guard_tree_values[id(inner)] = inner + inner_data.append((attr, inner)) + + return type(self)._unpickle_traceable_wrapper_subclass, ( + torch.empty_like(obj, device="meta"), + obj.device, + type(obj), + torch._C._dispatch_keys(obj).raw_repr(), + ctx, + inner_data, + ) + + # For FakeTensors, use pytype if set, otherwise default to + # torch.Tensor. This is important for cross-compilation where + # we compile with fake tensors but run with real tensors. + pytype = type(obj) + if isinstance( # noqa: ISINSTANCE_FAKE_TENSOR + obj, torch._subclasses.FakeTensor + ): + pytype = obj.pytype if obj.pytype is not None else torch.Tensor + + return type(self)._unpickle_tensor, ( + torch.empty_like(obj, device="meta", requires_grad=obj.requires_grad), + obj.device, + pytype, + torch._C._dispatch_keys(obj).raw_repr(), + obj.grad, + ) + + elif isinstance(obj, torch.nn.Module): + if id(obj) not in self.guard_tree_values: + return _Missing, ("module guard tree",) + + for attr in obj.__dict__.values(): + if isinstance(attr, (torch.Tensor, torch.nn.Module)): + continue + if id(attr) in self.guard_tree_values: + continue + if callable(attr): + continue + self.missing_values[id(attr)] = attr + + # DDP module is a special case because it tries to restore unneeded + # data in custom __setstate__. We cannot skip ddp module because it + # is often a toplevel module. + if isinstance(obj, torch.nn.parallel.DistributedDataParallel): + return type(self)._unpickle_ddp_module, (obj.__getstate__(),) + + if type(obj).__qualname__ == type(obj).__name__: + return NotImplemented + if obj.__class__.__getstate__ == torch.nn.Module.__getstate__: + return type(self)._unpickle_module, (obj.__getstate__(),) + + elif inspect.ismodule(obj): + return type(self)._unpickle_python_module, (obj.__name__,) + + elif isinstance(obj, torch._C.DispatchKeySet): + return type(self)._unpickle_dispatch_key_set, (obj.raw_repr(),) + + elif isinstance(obj, torch._C._functorch.CInterpreter): + return type(self)._unpickle_functorch_interpreter, (obj.serialize(),) + + elif ( + inspect.isclass(obj) + and issubclass(obj, sympy.Function) + and hasattr(obj, "_torch_handler_name") + ): + if not hasattr(obj, "_torch_unpickler"): + raise AssertionError( + f"sympy Function subclass {obj} must have _torch_unpickler attribute" + ) + return obj._torch_unpickler, (obj._torch_handler_name,) + + elif ( + inspect.isclass(obj) + and issubclass(obj, tuple) + and hasattr(obj, "_fields") + and obj.__qualname__ != obj.__name__ + ): + return type(self)._unpickle_named_tuple_type, (obj.__name__, obj._fields) + + elif isinstance(obj, torch.SymInt): + raise RuntimeError(f"Cannot serialize SymInt {obj} (node: {obj.node})") + + elif isinstance(obj, types.MappingProxyType): + return type(self)._unpickle_mapping_proxy, (obj.copy(),) + + elif type(obj) is _COUNT_ITERATOR_TYPE: + item, step = normalize_count_iter(obj) + if item is not NotImplemented and step is not NotImplemented: + return type(self)._unpickle_count_iter, (item, step) + + elif isinstance(obj, torch._dynamo.utils.dict_keys): + return type(self)._unpickle_dict_keys, (list(obj),) + + elif isinstance( + obj, torch._ops.OpOverloadPacket + ) and obj._qualified_op_name.startswith("_C::"): + return type(self)._unpickle_c_op, (obj.__name__,) + + elif isinstance(obj, torch._ops.OpOverload): + return type(self)._unpickle_op, ( + obj.namespace, + obj._opname, + obj._overloadname, + ) + + elif ( + obj.__class__.__module__ == "builtins" + and obj.__class__.__name__ == "PyCapsule" + ): + # Skipping PyCapsule since there isn't much to be guarded about them. + return _Missing, ("capsule",) + + elif isinstance(obj, _get_unsupported_types()): + return _Missing, ("unsupported",) + + elif inspect.isfunction(obj): + if "" in obj.__qualname__: + return type(self)._unpickle_nested_function, ( + obj.__code__, + obj.__module__, + obj.__qualname__, + obj.__defaults__, + obj.__closure__, + ) + if obj.__module__ in sys.modules: + f = sys.modules[obj.__module__] + for name in obj.__qualname__.split("."): + f = getattr(f, name, None) # type: ignore[assignment] + if f is not obj: + return _Missing, ("fqn mismatch",) + elif inspect.ismethod(obj): + func = obj.__func__ + method_self = obj.__self__ + inner_func = getattr(method_self, func.__name__) + if inspect.ismethod(inner_func): + inner_func = inner_func.__func__ + if func is not inner_func: + return type(self)._unpickle_bound_method, (func, method_self) + + elif isinstance(obj, type((lambda x: lambda: x)(0).__closure__[0])): # type: ignore[index] # noqa: PLC3002 + return type(self)._unpickle_cell, (obj.cell_contents,) + + if hasattr(torch.distributed, "distributed_c10d") and isinstance( + obj, torch.distributed.distributed_c10d.Work + ): + if id(obj) not in self.guard_tree_values: + return _Missing, ("distributed_c10d.Work",) + + if isinstance(obj, torch.nn.attention.SDPBackend): + return type(self)._unpickle_sdp_backend, (obj.name,) + + if type(obj).__qualname__ != type(obj).__name__ and not isinstance(obj, tuple): + raise torch._dynamo.exc.PackageError( + f"Type {type(obj)} for object {obj} cannot be saved " + + "into torch.compile() package since it's defined in local scope. " + + "Please define the class at global scope (top level of a module)." + ) + + if ( + inspect.isclass(obj) + and hasattr(torch.distributed, "fsdp") + and issubclass(obj, torch.distributed.fsdp._fully_shard.FSDPModule) + ): + if obj is not torch.distributed.fsdp._fully_shard.FSDPModule: + original_type = obj.__mro__[2] + if not issubclass(original_type, torch.nn.Module): + raise AssertionError( + f"Expected nn.Module subclass, got {original_type}" + ) + if ( + original_type + not in torch.distributed.fsdp._fully_shard._fully_shard.get_cls_to_fsdp_cls() + ): + raise AssertionError( + f"{original_type} not found in FSDP cls-to-fsdp-cls mapping" + ) + return type(self)._unpickle_fsdp_module_type, (original_type,) + + return NotImplemented + + +def make_guard_filter_entry(guard: Guard, builder: GuardBuilder) -> GuardFilterEntry: + MISSING = object() + name = strip_local_scope(guard.name) + if name == "": + has_value = False + value = MISSING + else: + try: + # Guard evaluation is expected to fail when we guard on + # things like "not hasattr(x, 'foo')". In cases like this, + # we don't have a well defined value because such thing + # doesn't exist. + value = builder.get(guard) + has_value = True + except: # noqa: E722 + value = MISSING + has_value = False + is_global = get_global_source_name(guard.originating_source) is not None + return GuardFilterEntry( + name=name, + has_value=has_value, + value=value, + guard_type=guard.create_fn_name(), + derived_guard_types=(tuple(guard.guard_types) if guard.guard_types else ()), + is_global=is_global, + orig_guard=guard, + ) + + +def pickle_guards_state( + state: GuardsState, + builder: GuardBuilder, +) -> bytes: + buf = io.BytesIO() + empty_values = {} + missing_values = {} + guard_tree_values = builder.guard_tree_values + + leaves = pytree.tree_leaves(state.output_graph.local_scope) + for leaf in leaves: + if inspect.ismethod(leaf) and hasattr(leaf, "__self__"): + base = leaf.__self__ + if id(base) not in guard_tree_values: + try: + type(base).__new__(type(base)) + empty_values[id(base)] = base + except: # noqa: E722 + pass + elif id(leaf) not in guard_tree_values: + # TODO See if we have lift this branch as the first one. + # Prune more objects in pytree hierarchy. + missing_values[id(leaf)] = leaf + pickler = GuardsStatePickler(guard_tree_values, empty_values, missing_values, buf) + + if all( + torch.compiler.keep_portable_guards_unsafe( + [ + make_guard_filter_entry(guard, builder) + for guard in state.output_graph.guards + ] + ) + ): + # Prune more values in AOT precompile when complex pickling structure is not needed. + state.output_graph.guard_on_key_order = set() + state.output_graph.global_scope = {} + + try: + pickler.dump(state) + except AttributeError as e: + raise torch._dynamo.exc.PackageError(str(e)) from e + return buf.getvalue() + + +# NB: Naively, you'd expect this to only be a function that produces +# the callable that constitutes the guard. However, there is some +# delicate handling for invalidating this check function when the +# locals/globals get invalidated, so there's some extra state +# we have to hold in this manager class. +class CheckFunctionManager: + def __init__( + self, + f_code: types.CodeType, + output_graph: OutputGraphCommon, + cache_entries: list[CacheEntry] | None = None, + guard_fail_fn: Callable[[GuardFail], None] | None = None, + guard_filter_fn: Callable[[Sequence[GuardFilterEntry]], Sequence[bool]] + | None = None, + shape_code_parts: ShapeCodeParts | None = None, + runtime_global_scope: dict[str, Any] | None = None, + save_guards: bool = False, + strict_error: bool = False, + guard_build_local_state: Any | None = None, + ) -> None: + guards = output_graph.guards if output_graph else None + self._weakrefs: dict[int, ReferenceType[object]] = {} + + existing_diff_guard_sources = ( + update_diff_guard_managers_for_existing_cache_entries(cache_entries or []) + ) + self.output_graph: OutputGraphCommon | None = output_graph + if self.output_graph is None: + raise AssertionError("output_graph must not be None") + + # Only used for serialization. + self.shape_code_parts = shape_code_parts + + # NB: Until we trace device contexts, we need to use the stack recorded at the beginning of tracing + # in case a set default device call was made in the graph. + self.torch_function_mode_stack = ( + output_graph.torch_function_mode_stack if output_graph else None + ) + self.used_builtin_vars: OrderedSet[str] = OrderedSet() + self.additional_used_local_vars: OrderedSet[str] = OrderedSet() + self.additional_used_global_vars: OrderedSet[str] = OrderedSet() + self.runtime_global_scope = runtime_global_scope + self.guard_build_local_state = guard_build_local_state + self.global_state: torch._C._dynamo.guards.GlobalStateGuard | None = None + self.torch_function_mode_stack_check_fn: Callable[[], bool] | None = None + + if not justknobs_check("pytorch/compiler:guard_nn_modules"): + log.warning("guard_nn_modules is turned off using justknobs killswitch") + + # TODO Be more explicit about the behavior for the users. + if torch._dynamo.config.caching_precompile: + _guard_filter_fn = guard_filter_fn or (lambda gs: [True for g in gs]) + + def guard_filter_fn(guards: Sequence[GuardFilterEntry]) -> Sequence[bool]: + ret = [] + for keep, g in zip(_guard_filter_fn(guards), guards): + if not keep: + ret.append(False) + elif ( + g.guard_type + in ( + "ID_MATCH", + "CLOSURE_MATCH", + "WEAKREF_ALIVE", + "DICT_VERSION", + ) + or "ID_MATCH" in g.derived_guard_types + or "DICT_VERSION" in g.derived_guard_types + ): + log.warning( + "%s guard on %s is dropped with caching_precompile=True.", + g.guard_type, + g.orig_guard.name, + ) + ret.append(False) + else: + ret.append(True) + return ret + + sorted_guards = sorted(guards or (), key=Guard.sort_key) + + # Disable __torch_function__ dispatch during guard construction so + # modes with mutable state aren't triggered. We exit the context + # before the guard sanity check so GlobalStateGuard.check() sees + # the true runtime state. + with torch._C.DisableTorchFunction(): + if guard_filter_fn: + # If we're filtering guards, we need to build it an extra time first + # because filtering depends on the builder/guard_manager results + builder, guard_manager = self.build_guards( + sorted_guards, + existing_diff_guard_sources, + f_code, + output_graph, + False, + ) + + filter_results = guard_filter_fn( + [make_guard_filter_entry(guard, builder) for guard in sorted_guards] + ) + if len(filter_results) != len(sorted_guards): + raise AssertionError( + f"filter_results length ({len(filter_results)}) != " + f"sorted_guards length ({len(sorted_guards)})" + ) + if not all(type(x) is bool for x in filter_results): + raise AssertionError("All filter_results entries must be bool") + sorted_guards = [ + guard for i, guard in enumerate(sorted_guards) if filter_results[i] + ] + + # Redo the guards because filtering relies on the results from the last guard builder. + builder, guard_manager = self.build_guards( + sorted_guards, + existing_diff_guard_sources, + f_code, + output_graph, + save_guards, + guard_filter_fn=guard_filter_fn, + ) + + self.guard_manager = guard_manager + self.compile_check_fn(builder, sorted_guards, guard_fail_fn) + + # Keep track of weak references of objects with ID_MATCH guard. This + # info is stored alongside optimized_code and guard_manager and is used to + # limit the number of cache entries with same ID_MATCH'd object. + # TODO(anijain2305) - Currently this information is stored as an attr on + # the guard_manager itself to avoid changing CacheEntry data structure in + # eval_frame.c. In future, we should probably replace guard_manager with a + # queryable data structure such that this information is already present + # in some form. + self.guard_manager.id_matched_objs = builder.id_matched_objs + + guards_log.debug("%s", self.guard_manager) + self.guard_manager.id_matched_objs = builder.id_matched_objs + + # Check that the guard returns True. False means that we will always + # recompile. + # TODO(anijain2305, ydwu4) - Skipping export because of following test + # python -s test/dynamo/test_export.py -k test_export_with_symbool_inputs + latency = 0.0 + + # Non-strict tracing can compile with fake inputs whose unbacked sizes + # cannot be used to evaluate guards eagerly. Keep the runtime guards, + # but skip this same-frame sanity check in that tracing context. + if ( + not output_graph.skip_guards_check + and not output_graph.export + and not torch.compiler._is_non_strict_tracing() + ): + if not self.guard_manager.check(output_graph.local_scope): + reasons = get_guard_fail_reason_helper( + self.guard_manager, + output_graph.local_scope, + CompileContext.current_compile_id(), + backend=None, # no need to set this because we are trying to find the offending guard entry + ) + raise AssertionError( + "Guard failed on the same frame it was created. This is a bug - please create an issue." + f"Guard fail reason: {reasons}" + ) + + if guard_manager_testing_hook_fn is not None: + guard_manager_testing_hook_fn( + self.guard_manager, output_graph.local_scope, builder + ) + + # NB for developers: n_iters is chosen to be 1 to prevent excessive + # increase in compile time. We first do a cache flush to measure the + # guard latency more accurately. This cache flush is expensive. + # Note - If you are working on a guard optimization, it might be a + # good idea to increase this number for more stability during + # development. + latency = profile_guard_manager( + self.guard_manager.root, output_graph.local_scope, 1 + ) + guards_log.debug("Guard eval latency = %s us", f"{latency:.2f}") + # Note: We use `increment_toplevel` instead of `compilation_metric` + # here. This is because, in scenarios where `torch._dynamo.reset` + # is invoked, the same frame ID and compile ID may be reused during + # a new compilation cycle. This behavior causes issues with + # `compilation_metric`, as it expects the metric field to be empty. + # Ideally, we would overwrite the existing entry in such cases, but + # we currently lack an API to support overwriting metrics. However, + # since these situations are rare and typically impractical to + # account for, we simply increment at the toplevel instead. + CompileEventLogger.increment_toplevel("guard_latency_us", int(latency)) + + self.guards_state: bytes | None = None + if save_guards: + from torch._dynamo.output_graph import OutputGraphCommon + + if not isinstance(self.output_graph, OutputGraphCommon): + raise AssertionError( + f"Expected OutputGraphCommon, got {type(self.output_graph)}" + ) + try: + self.guards_state = self.serialize_guards( + builder, sorted_guards, self.output_graph + ) + except exc.PackageError as e: + if torch._dynamo.config.strict_precompile or strict_error: + raise e + self.output_graph.bypass_package( + f"Guard evaluation failed: {str(e)}", + traceback=traceback.format_exc().split("\n"), + ) + + # TODO: don't do the string rep, do something more structured here + torch._logging.trace_structured( + "dynamo_cpp_guards_str", + payload_fn=lambda: f"{self.guard_manager}\nGuard latency = {latency:.2f} us", + ) + # NB - We have to very careful of cleaning up here. Because of the + # invalidate function, we can create a weakref finalizer that keeps + # `self` alive for very long. Sometimes by mistake, we can run + # invalidate for a type/object (check id_ref method) that Python can + # leak by design, preventing us from calling the finalizer. In that + # case, the `self` will be alive even though the cache entry will be + # deleted (check invalidate method), which can cause a memory leak, + # e.g., not setting output_graph = None can keep hold of nn_modules. + self._weakrefs.clear() + self.output_graph = None + + UNSUPPORTED_SERIALIZATION_GUARD_TYPES: tuple[LiteralString, ...] = ( + "DICT_VERSION", + "NN_MODULE", + "ID_MATCH", + "FUNCTION_MATCH", + "CLASS_MATCH", + "MODULE_MATCH", + "CLOSURE_MATCH", + "WEAKREF_ALIVE", + ) + + def serialize_guards( + self, + builder: GuardBuilder, + sorted_guards: list[Guard], + output_graph: OutputGraphCommon, + ) -> bytes: + # We check whether our list of guards are serializable here + for guard in sorted_guards: + guard_type = guard.create_fn_name() + derived_guard_types = tuple(guard.guard_types) if guard.guard_types else () + # BUILTIN_MATCH calls TYPE_MATCH sometimes, so we need to check both for + # a chance that the guard is unserializable + if guard_type in ("TYPE_MATCH", "BUILTIN_MATCH"): + if guard._unserializable: + # Only call builder.get again if we know we're going to throw + obj = builder.get(guard) + raise_local_type_error(obj) + elif ( + guard_type in CheckFunctionManager.UNSUPPORTED_SERIALIZATION_GUARD_TYPES + ): + raise torch._dynamo.exc.PackageError( + f"{guard_type} guard cannot be serialized." + ) + elif failed := next( + ( + i + for i in derived_guard_types + if i in CheckFunctionManager.UNSUPPORTED_SERIALIZATION_GUARD_TYPES + ), + None, + ): + # Just raise the first failed guard name + raise torch._dynamo.exc.PackageError( + f"{failed} guard cannot be serialized." + ) + + builtins_dict_name = output_graph.name_of_builtins_dict_key_in_fglobals or "" + used_global_vars = set() + used_local_vars = set() + + def prune_variable(source: Source) -> None: + if name := get_global_source_name(source): + if not isinstance(name, str): + raise AssertionError(f"Expected str, got {type(name)}") + # Leave out the builtins dict key, as we will special handle + # it later because the guarded code rarely use the entire + # builtin dict in the common case. + if name != builtins_dict_name: + used_global_vars.add(name) + elif name := get_local_source_name(source): + if not isinstance(name, str): + raise AssertionError(f"Expected str, got {type(name)}") + used_local_vars.add(name) + + output_graph_guards_state = output_graph.dump_guards_state() + # Only serialize the global variables that are actually used in guards. + for guard in sorted_guards: + if isinstance(guard.originating_source, ShapeEnvSource): + if not self.shape_code_parts: + raise AssertionError( + "shape_code_parts must be set for ShapeEnvSource guards" + ) + for source in self.shape_code_parts.shape_env_sources: + prune_variable(source) + else: + prune_variable(guard.originating_source) + + for source in output_graph.guard_on_key_order: + prune_variable(source) + + def normalize_create_fn(x: Callable[..., None]) -> Callable[..., None]: + if isinstance(x, functools.partial): + + def _ref(x: Any) -> Any: + if isinstance(x, (TensorWeakRef, weakref.ref)): + return x() + return x + + new_args = tuple(_ref(a) for a in x.args) + new_keywords = {k: _ref(v) for k, v in x.keywords.items()} + return functools.partial(x.func, *new_args, **new_keywords) + + return x + + global_scope_state = { + k: v + for k, v in output_graph_guards_state.global_scope.items() + if k in used_global_vars or k in self.additional_used_global_vars + } + global_scope_state[builtins_dict_name] = { + k: v + # pyrefly: ignore [missing-attribute] + for k, v in output_graph_guards_state.global_scope[ + builtins_dict_name + ].items() # type: ignore[attr-defined] + if k in self.used_builtin_vars + } + output_graph_guards_state = dataclasses.replace( + output_graph_guards_state, + local_scope={ + k: v + for k, v in output_graph_guards_state.local_scope.items() + if k in used_local_vars or k in self.additional_used_local_vars + }, + global_scope=global_scope_state, + _guards=torch._guards.GuardsSet( + OrderedSet( + dataclasses.replace( + guard, + obj_weakref=None, + guarded_class_weakref=None, + create_fn=normalize_create_fn(guard.create_fn), + ) + for guard in sorted_guards + ) + ), + input_source_to_sizes_strides=pytree.tree_map( + convert_int_to_concrete_values, + output_graph_guards_state.input_source_to_sizes_strides, + ), + skip_guards_check=True, + ) + guards_state = GuardsState( + output_graph=output_graph_guards_state, + shape_code_parts=self.shape_code_parts, + local_state=self.guard_manager.root.get_local_state(), + ) + + return pickle_guards_state(guards_state, builder) + + def build_guards( + self, + sorted_guards: list[Guard], + existing_diff_guard_sources: OrderedSet[str], + f_code: types.CodeType, + output_graph: OutputGraphGuardsState, + save_guards: bool, + guard_filter_fn: Callable[[Sequence[GuardFilterEntry]], Sequence[bool]] + | None = None, + ) -> tuple[GuardBuilder, GuardManagerWrapper]: + guard_manager = GuardManagerWrapper(local_state=self.guard_build_local_state) + guard_manager.diff_guard_sources = existing_diff_guard_sources + + w_builder = None + + def source_ref(source: Source) -> str: + guard_source = source.guard_source + if guard_source is GuardSource.CONSTANT: + # No need to track constants + return source.name + if not w_builder: + raise AssertionError("w_builder must be set before calling source_ref") + r_builder = w_builder() + if r_builder is None: + raise AssertionError("GuardBuilder has been garbage collected") + return r_builder.arg_ref(source.name) + + builder = GuardBuilder( + f_code, + self.id_ref, + source_ref, + self.lookup_weakrefs, + output_graph.local_scope, + output_graph.global_scope, + guard_manager, + self, + save_guards, + runtime_global_scope=self.runtime_global_scope, + guard_filter_fn=guard_filter_fn, + ) + + # Break retain cycle. See test_release_scope_memory + def cleanup_builder(weak_b: weakref.ref[GuardBuilder]) -> None: + b = weak_b() + if b: + b.scope = None # type: ignore[assignment] + + # Break retain cycle. See test_release_input_memory + w_builder = weakref.ref(builder, cleanup_builder) + + guard_on_nn_modules = config.guard_nn_modules and justknobs_check( + "pytorch/compiler:guard_nn_modules" + ) + + for guard in sorted_guards: + # guard_types/code_list are per-build export info, but they + # accumulate on the shared Guard objects across builds. Reset them + # so results from a previous build (e.g. the pre-filtering build or + # an earlier non-save CheckFunctionManager) don't leak into this + # build; serialize_guards relies on them to detect unserializable + # guards, and a non-save build may derive different guards (e.g. + # DICT_VERSION for SUPPORTED_NODES) than a save build. + guard.guard_types = None + guard.code_list = None + + if ( + not guard_on_nn_modules + and guard.is_specialized_nn_module() + # Default func args must be guarded on. + # TODO: we could make use of 'DefaultsSource' and offer a .guard.is_defaults() API + and "__defaults__" not in guard.name + and "__kwdefaults__" not in guard.name + and (config.skip_nnmodule_hook_guards or "hooks" not in guard.name) + ): + continue + + guard.create(builder) + return builder, guard_manager + + def compile_check_fn( + self, + builder: GuardBuilder, + guards_out: list[Guard], + guard_fail_fn: Callable[[GuardFail], None] | None, + ) -> None: + # see parallel handling of ".0" / "___implicit0" in _eval_frame.c + largs = builder.argnames + largs += ["**___kwargs_ignored"] + + guards_log.debug("GUARDS:") + + # pyrefly: ignore [implicit-any] + code_parts = [] + verbose_code_parts = [] + structured_guard_fns: list[Callable[[], dict[str, Any]]] = [] + + # Add compile id info in the guard manager for debugging purpose + self.guard_manager.root.attach_compile_id( + str(CompileContext.current_compile_id()) + ) + + # Clear references to torch_function modes held in the list + self.torch_function_mode_stack = None + + def add_code_part( + code_part: str, guard: Guard | None, log_only: bool = False + ) -> None: + verbose_code_part = get_verbose_code_part(code_part, guard) + guards_log.debug("%s", verbose_code_part) + + structured_guard_fns.append( + lambda: { + "code": code_part, + "stack": ( + structured.from_traceback(guard.stack.summary()) + if guard and guard.stack + else None + ), + "user_stack": ( + structured.from_traceback(guard.user_stack) + if guard and guard.user_stack + else None + ), + } + ) + + if verbose_guards_log.isEnabledFor(logging.DEBUG): + maybe_stack = "" + maybe_user_stack = "" + if guard is not None: + if guard.stack: + maybe_stack = f"\nStack:\n{''.join(guard.stack.format())}" + if guard.user_stack: + maybe_user_stack = ( + f"\nUser stack:\n{''.join(guard.user_stack.format())}" + ) + verbose_guards_log.debug( + "Guard: %s%s%s", + code_part, + maybe_stack, + maybe_user_stack, + ) + + if not log_only: + code_parts.append(code_part) + verbose_code_parts.append(verbose_code_part) + + seen = set() + for gcl in builder.code: + for code in gcl.code_list: + if code not in seen: + # If Cpp guard manager is enabled, we don't need to add to + # code_parts. + add_code_part(code, gcl.guard, True) + seen.add(code) + + no_tensor_aliasing_names = builder.no_tensor_aliasing_names + check_tensors_fn = None + check_tensors_verbose_fn = None + + if len(no_tensor_aliasing_names) > 1: + # Install tensor aliasing guard. TENSOR_MATCH guards are already + # installed for cpp guard manager. + install_no_tensor_aliasing_guard( + builder.no_tensor_aliasing_guard_managers, + no_tensor_aliasing_names, + ["check_no_aliasing(" + ", ".join(no_tensor_aliasing_names) + ")"], + None, + ) + + # Note - On Lambda guarding of object aliasing + # We previously installed object-aliasing guards as relational guards, + # but that undermined the recursive-dict guard optimization: placing the + # aliasing guard at a leaf prevented the parent dict node from + # qualifying as a recursive-dict guard root. Because aliasing guards are + # rare, we now emit them as epilogue guards via a small Python lambda. + # This repeats the access in Python—adding a bit of work—but the + # overhead is outweighed by the gains from enabling recursive-dict guard + # optimization. + if ( + config.use_lamba_guard_for_object_aliasing + and builder.object_aliasing_guard_codes + ): + aliasing_code_parts, aliasing_verbose_code_parts = map( + list, zip(*builder.object_aliasing_guard_codes) + ) + builder.add_python_lambda_leaf_guard_to_root( + aliasing_code_parts, aliasing_verbose_code_parts + ) + + aotautograd_guards: list[GuardEnvExpr] = ( + self.output_graph.aotautograd_guards if self.output_graph else [] + ) + + # TODO(anijain2305) - There is a duplicate logic in Dynamo to find + # aliased input tensors. So most probably we don't need this here. + # Revisit. + for guard in aotautograd_guards: + if isinstance(guard, DuplicateInputs): + source_a = guard.input_source_a + source_b = guard.input_source_b + code_part = f"{source_a.name} is {source_b.name}" + install_object_aliasing_guard( + builder.get_guard_manager_from_source(source_a), + builder.get_guard_manager_from_source(source_b), + [code_part], + None, + ) + add_code_part(code_part, None, True) + elif isinstance(guard, StorageOverlap): + overlapping_guard_managers = [ + builder.get_guard_manager_from_source(s) + for s in guard.overlapping_sources + ] + non_overlapping_guard_managers = [ + builder.get_guard_manager_from_source(s) + for s in guard.non_overlapping_sources + ] + code_part = ( + """check_overlapping(""" + f"""overlapping=[{", ".join(s.name for s in guard.overlapping_sources)}], """ + f"""non_overlapping=[{", ".join(s.name for s in guard.non_overlapping_sources)}])""" + ) + install_storage_overlapping_guard( + overlapping_guard_managers, + non_overlapping_guard_managers, + [code_part], + None, + ) + add_code_part(code_part, None, True) + else: + raise RuntimeError(f"Unknown GuardEnvExpr: {guard}") + + # TODO: the "guard" here is actually just the top level SHAPE_ENV + # which is useless. Get ShapeEnv to pass in more provenance. + for gcl in builder.shape_env_code: + for code in gcl.code_list: + # Shape env guards are already added for CPP guard manager in + # SHAPE_ENV implementation. + add_code_part(code, gcl.guard, True) + + # OK, all done generating guards + if structured_guard_fns: + torch._logging.trace_structured( + "dynamo_guards", payload_fn=lambda: [f() for f in structured_guard_fns] + ) + + if convert_frame.initial_global_state is None: + # we should only hit this case in NopTests() + check_global_state = convert_frame.GlobalStateGuard().check + else: + check_global_state = getattr(self.global_state, "check", None) + closure_vars = { + "___check_tensors": check_tensors_fn, + "___check_tensors_verbose": check_tensors_verbose_fn, + "___check_global_state": check_global_state, + "___check_torch_function_mode_stack": self.torch_function_mode_stack_check_fn, + **SYMPY_INTERP, + **_get_closure_vars(), + } + + self.guard_manager.finalize() + + globals_for_guard_fn = {"G": builder.scope["G"]} + # Guard manager construction is complete. Ensure we did not miss to + # insert a guard in cpp guard manager. + if len(code_parts) != 0: + raise AssertionError( + f"Expected all code_parts to be consumed, but {len(code_parts)} remain" + ) + + self.guard_manager.closure_vars = closure_vars + self.guard_manager.args = largs + self.guard_manager.populate_code_parts_for_debugging() + self.guard_manager.verbose_code_parts = verbose_code_parts + # Grab only G, but preserve "G" because guards access it as "G" + self.guard_manager.global_scope = globals_for_guard_fn + self.guard_manager.guard_fail_fn = guard_fail_fn + # will be populated by a non-owning reference to CacheEntry/ExtraState + # when the CacheEntry is constructed + self.guard_manager.cache_entry = None + self.guard_manager.extra_state = None + self.guard_manager.no_tensor_aliasing_sources = no_tensor_aliasing_names + + def invalidate(self, obj_str: str) -> None: + # Some tests reveal that CheckFunctionManager has no attribute + # guard_manager, but this case should not be of any concern. + # This case doesn't seem easy to repro. + if ( + hasattr(self, "guard_manager") + and not isinstance(self.guard_manager, DeletedGuardManagerWrapper) + and (cache_entry := self.guard_manager.cache_entry) is not None + and (extra_state := self.guard_manager.extra_state) is not None + ): + if not isinstance(cache_entry, CacheEntry): + raise AssertionError(f"Expected CacheEntry, got {type(cache_entry)}") + + if not isinstance(extra_state, ExtraState): + raise AssertionError(f"Expected ExtraState, got {type(extra_state)}") + reason = f"Cache line invalidated because {obj_str} got deallocated" + deleted_guard_manager = DeletedGuardManagerWrapper(reason) + + extra_state.invalidate(cache_entry, deleted_guard_manager) + self.guard_manager = deleted_guard_manager + + def id_ref(self, obj: object, obj_str: str) -> int: + """add a weakref, return the id""" + try: + if id(obj) not in self._weakrefs: + # We will clear the _weakrefs dict at the end of __init__ + # function, which will delete the callbacks as well. Therefore, + # we are using a finalizer which is kept alive. + self._weakrefs[id(obj)] = weakref.ref(obj) + weakref.finalize( + obj, functools.partial(self.invalidate, obj_str=obj_str) + ) + except TypeError: + pass # cannot weakref bool object + return id(obj) + + def lookup_weakrefs(self, obj: object) -> weakref.ref[object] | None: + """Lookup the _weakrefs created in id_ref function for ID_MATCH'd objects""" + if id(obj) in self._weakrefs: + return self._weakrefs[id(obj)] + return None + + +def build_guard_function(code_parts: list[str], closure_args: str) -> tuple[str, str]: + from torch.utils._indented_buffer import IndentedBuffer + + csepass = PyExprCSEPass() + try: + csepass.count(code_parts) + + def replace(expr: str) -> tuple[list[str], str]: + return csepass.replace(expr) + + except RecursionError: + # If we hit recursion limits during CSE analysis, fall back to a no-op replace function + # This can happen with extremely complex guard expressions + def replace(expr: str) -> tuple[list[str], str]: + return [], expr + + # Generate the inner body of the guard function. + # i.e. if-chain of the guard expressions. + guard_body = IndentedBuffer() + for expr in code_parts: + preface, expr = replace(expr) + guard_body.writelines(preface) + guard_body.writeline(f"if not ({expr}):") + with guard_body.indent(): + guard_body.writeline("return False") + + # Wrap the inner body into the actual guard function. + guard = IndentedBuffer() + guard.writeline("def guard(L):") + with guard.indent(): + guard.splice(guard_body) + guard.writeline("return True") + + # Wrap the whole guard function into another function + # with the closure variables. + make_guard_fn = IndentedBuffer() + make_guard_fn.writeline(f"def ___make_guard_fn({closure_args}):") + with make_guard_fn.indent(): + make_guard_fn.splice(guard) + make_guard_fn.writeline("return guard") + + return guard_body.getvalue(), make_guard_fn.getvalue() + + +def is_recompiles_enabled() -> bool: + return torch._logging._internal.log_state.is_artifact_enabled("recompiles") + + +def is_recompiles_verbose_enabled() -> bool: + return torch._logging._internal.log_state.is_artifact_enabled("recompiles_verbose") + + +# this will only be used if cpp guards are disabled +def make_torch_function_mode_stack_guard( + initial_stack: list[torch.overrides.TorchFunctionMode], +) -> Callable[[], bool]: + types = [type(x) for x in initial_stack] + + def check_torch_function_mode_stack() -> bool: + cur_stack = get_torch_function_mode_stack() + + if len(cur_stack) != len(types): + return False + + for ty, mode in zip(types, cur_stack): + if ty is not type(mode): + return False + + return True + + return check_torch_function_mode_stack + + +Scope = TypeAliasType("Scope", dict[str, object]) + + +def recompilation_reason_for_no_tensor_aliasing_guard( + guard_manager: GuardManagerWrapper, scope: Scope +) -> list[str]: + if guard_manager.global_scope is None: + raise AssertionError("guard_manager.global_scope must not be None") + global_scope = dict(guard_manager.global_scope) + ids_to_source = collections.defaultdict(list) + for tensor_source in guard_manager.no_tensor_aliasing_sources: + global_scope["__compile_source__"] = tensor_source + tensor_id = id(eval(tensor_source, global_scope, scope)) + ids_to_source[tensor_id].append(tensor_source) + + duplicate_tensors = [ + f"{ids_to_source[key]}" for key in ids_to_source if len(ids_to_source[key]) > 1 + ] + + reason = ", ".join(duplicate_tensors) + return [f"Duplicate tensors found: {reason}"] + + +def strip_local_scope(s: str) -> str: + """ + Replace occurrences of L[...] with just the inner content. + Handles both single and double quotes. + + This is to generate user friendly recompilation messages. + """ + import re + + pattern = r"L\[\s*['\"](.*?)['\"]\s*\]" + return re.sub(pattern, r"\1", s) + + +def format_user_stack_trace( + user_stack: traceback.StackSummary | None, +) -> str: + """ + Format the user stack trace for display in guard failure messages. + + Returns a formatted string representation of the stack trace, + or an empty string if no user stack is available. + """ + if user_stack is None or len(user_stack) == 0: + return "" + + lines: list[str] = [] + for frame in user_stack: + filename = frame.filename + lineno = frame.lineno + name = frame.name + source_line = frame.line.strip() if frame.line else "" + lines.append(f' File "{filename}", line {lineno}, in {name}') + if source_line: + lines.append(f" {source_line}") + return "\n".join(lines) + + +def describe_backend(backend: Callable[..., object] | None) -> str: + """Return a human-readable string describing a backend callable for debugging.""" + if backend is None: + return "None" + + # _TorchCompileWrapper is the internal wrapper created by torch.compile(). + # It has structured fields that are more informative than generic introspection. + from torch import _TorchCompileWrapper + + if isinstance(backend, _TorchCompileWrapper): + details = f"compiler={backend.compiler_name!r}, dynamic={backend.dynamic!r}" + if backend.kwargs: + details += f", kwargs={backend.kwargs!r}" + return f"_TorchCompileWrapper({details}) (id={id(backend):#x})" + + actual = backend + prefix = "" + if isinstance(actual, functools.partial): + prefix = "functools.partial wrapping " + actual = actual.func + + qualname = getattr(actual, "__qualname__", None) + module = getattr(actual, "__module__", None) + + if qualname and module: + name = f"{module}.{qualname}" + elif qualname: + name = qualname + elif hasattr(actual, "__name__"): + name = actual.__name__ + else: + name = type(actual).__name__ + + code = getattr(actual, "__code__", None) + location = ( + f" defined at {code.co_filename}:{code.co_firstlineno}" + if code is not None + else "" + ) + + return f"{prefix}{name}{location} (id={id(backend):#x})" + + +def get_guard_fail_reason_helper( + guard_manager: GuardManagerWrapper, + f_locals: dict[str, object], + compile_id: CompileId | None, + backend: Callable[..., object] | None, +) -> str: + """ + Return the reason why `guard_manager` failed. + Updates `guard_failures` with the generated reason. + Only the first failed check of guard_manager is reported. + """ + + if guard_manager.global_scope is None: + raise AssertionError("guard_manager.global_scope must not be None") + if guard_manager.closure_vars is None: + raise AssertionError("guard_manager.closure_vars must not be None") + scope = {"L": f_locals, "G": guard_manager.global_scope["G"]} + scope.update(guard_manager.closure_vars) + reasons: list[str] = [] + + cache_entry_backend = None + if guard_manager.cache_entry: + cache_entry_backend = guard_manager.cache_entry.backend + + no_tensor_aliasing_check_failed = False + + verbose_code_parts: list[str] = [] + guard_debug_info = guard_manager.check_verbose(f_locals) + user_stack_str = "" + + # For test_export_with_map_cond, the check_verbose fail even without the + # C++ guard manager. We need to fix the issue to remove the comment. + # assert not guard_debug_info.result + if not guard_debug_info.result: + verbose_code_parts = guard_debug_info.verbose_code_parts + # verbose_code_parts is either the actual reason (e.g. in case of + # TENSOR_MATCH) or it could be a list of verbose_code_part that we + # passed to the leaf guard at construction time. If its a list, we + # walk through this list and find the guard that failed. This is + # very important for symbolic shape guards which are currently + # installed as a lambda guard and can encompass a long list of code_parts. + + if len(verbose_code_parts) == 1: + if "Duplicate tensor found" in verbose_code_parts[0]: + no_tensor_aliasing_check_failed = True + else: + reasons = verbose_code_parts + verbose_code_parts = [] + + # Format user stack trace if available and recompile logging is enabled + if guard_debug_info.user_stack: + user_stack_str = format_user_stack_trace(guard_debug_info.user_stack) + elif cache_entry_backend != backend: + # None of the guard entries failed - a backend match issue + cached_desc = describe_backend(cache_entry_backend) + new_desc = describe_backend(backend) + reason = ( + f"BACKEND_MATCH failure: torch.compile detected different backend callables." + f" Cached backend: {cached_desc}." + f" New backend: {new_desc}." + " If this is unexpected, wrap your backend in functools.partial (or reuse the" + " same cached backend) to avoid creating a new backend function each time." + " More details: https://github.com/pytorch/pytorch/issues/168373" + ) + reasons.append(reason) + else: + # Unexpected recompilation - points to a bug + reason = ( + "Unexpected recompilation: runtime guards failed even though they passed" + " during recompilation-reason analysis." + " Please open an issue with a minimal repro:" + " https://github.com/pytorch/pytorch" + ) + reasons.append(reason) + + if no_tensor_aliasing_check_failed: + reasons = recompilation_reason_for_no_tensor_aliasing_guard( + guard_manager, scope + ) + else: + for part in verbose_code_parts: + global_scope = dict(guard_manager.global_scope) + global_scope["__compile_source__"] = part + with report_compile_source_on_error(): + try: + fail_reason = eval(part, global_scope, scope) + except Exception: + if is_recompiles_verbose_enabled(): + continue + else: + raise + # Only ___check_tensors knows how to return a fancy fail reason; + # for everything else we just report the code that failed + + if isinstance(fail_reason, bool) and not fail_reason: + fail_reason = part + if isinstance(fail_reason, str): + reasons.append(fail_reason) + if not is_recompiles_verbose_enabled(): + break + + # Build reason string - simple format for normal logging + # Use singular "reason" when there's only one, plural "reasons" for multiple + if len(reasons) == 1: + reason_str = f"{compile_id}: {reasons[0]}" + else: + reason_str = f"{compile_id}: " + "; ".join(reasons) + if user_stack_str: + reason_str += f"\nUser stack trace:\n{user_stack_str}" + return strip_local_scope(reason_str) + + +def get_guard_fail_reason( + guard_manager: GuardManagerWrapper, + code: types.CodeType, + f_locals: dict[str, object], + compile_id: CompileId, + backend: Callable[..., object], + skip_logging: bool = False, +) -> str: + if isinstance(guard_manager, DeletedGuardManagerWrapper): + return f"{compile_id}: {guard_manager.invalidation_reason}" + reason_str = get_guard_fail_reason_helper( + guard_manager, f_locals, compile_id, backend + ) + if skip_logging: + return reason_str + guard_failures[orig_code_map[code]].append(reason_str) + + try: + if guard_manager.guard_fail_fn is not None: + guard_manager.guard_fail_fn( + GuardFail(reason_str or "unknown reason", orig_code_map[code]) + ) + except Exception: + log.exception( + "Failure in guard_fail_fn callback - raising here will cause a NULL Error on guard eval", + ) + + return reason_str + + +def get_and_maybe_log_recompilation_reasons( + cache_entries: list[CacheEntry], + frame: DynamoFrameType, + backend: Callable[..., object], + skip_logging: bool = False, +) -> list[str]: + """ + Return the list of guard failure reasons using cache entries. + Logs the recompilation reason if `recompiles` logging is enabled. + Raises a RecompileError if `config.error_on_recompile` is enabled. + """ + # pyrefly: ignore [implicit-any] + reasons = [] + for cache_entry in cache_entries: + reason = get_guard_fail_reason( + cache_entry.guard_manager, + cache_entry.code, + frame.f_locals, + cache_entry.compile_id, + backend, + skip_logging, + ) + if reason: + reasons.append(reason) + + code = frame.f_code + + if skip_logging: + return reasons + # at least one of "recompiles" or "recompiles_verbose" is enabled + do_recompiles_log = is_recompiles_enabled() or is_recompiles_verbose_enabled() + + if do_recompiles_log or config.error_on_recompile: + if is_recompiles_verbose_enabled(): + failures = "\n\n".join( + f"guard {i} failures:\n" + textwrap.indent(reason, "- ") + for i, reason in enumerate(reasons) + ) + else: + failures = textwrap.indent("\n".join(reasons), "- ") + guard_failure_details = ( + f"triggered by the following guard failure(s):\n{failures}" + ) + message = ( + f"Recompiling function {code.co_name} in {code.co_filename}:{code.co_firstlineno}\n" + f"{textwrap.indent(guard_failure_details, ' ')}" + ) + if do_recompiles_log: + if is_recompiles_verbose_enabled(): + recompiles_verbose_log.debug(message) + else: + recompiles_log.debug(message) + if config.error_on_recompile: + raise exc.RecompileError(message) + + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "recompile_reasons", + "encoding": "json", + }, + payload_fn=lambda: reasons[0] if len(reasons) == 1 else reasons, + ) + + return reasons + + +def update_diff_guard_managers_for_existing_cache_entries( + cache_entries: list[CacheEntry], +) -> OrderedSet[str]: + # On the first pass, go through the cache entries and accumulate the diff + # guard sources. Different guard managers can fail with different sources. + # So, we collect all of them first. + acc_diff_guard_sources: OrderedSet[str] = OrderedSet() + for cache_entry in cache_entries: + acc_diff_guard_sources.update( + cache_entry.guard_manager.collect_diff_guard_sources() + ) + + # On the second pass, set the diff_guard_sources for each cache line to the + # accumulated value. And the re-populate the diff guard manager. + for cache_entry in cache_entries: + cache_entry.guard_manager.diff_guard_sources = acc_diff_guard_sources + cache_entry.guard_manager.populate_diff_guard_manager() + + # return the accumulated sources to set up the new cache line. + return acc_diff_guard_sources + + +def guard_error_hook( + guard_manager: GuardFn, + code: types.CodeType, + f_locals: dict[str, object], + index: int, + last: bool, +) -> None: + print( + f"ERROR RUNNING GUARDS {code.co_name} {code.co_filename}:{code.co_firstlineno}" + ) + print("lambda " + ", ".join(guard_manager.args) + ":") + print(" ", " and\n ".join(guard_manager.code_parts)) + + print(guard_manager) + + local_scope = {"L": f_locals, **guard_manager.closure_vars} + for guard in guard_manager.code_parts: + try: + eval(guard, guard_manager.global_scope, local_scope) + except: # noqa: E722 + print(f"Malformed guard:\n{guard}") + + +set_guard_error_hook(guard_error_hook) + + +def unique(seq: Sequence[T]) -> Generator[T, None, None]: + seen = set() + for x in seq: + if x not in seen: + yield x + seen.add(x) + + +def make_dupe_guard( + obj_source: Source, dupe_source: Source | None +) -> functools.partial[Any] | None: + # Note - we may end up in a situation where we invoke something like + # def fn(x, y) + # with fn(x, x) + # Prior to the addition of tracking to all relevant objects, we would handle this just fine by + # eagerly re-entering VB and rewrapping inputs, correctly creating graphargs and placeholders. However, + # with tracking on inputs, duplicate inputs or aliased relationships may end up getting erased here - + # In the fn(x, x) example call above look like a graph with a single input. + # In order to ensure that we do not reuse fn(x, x) for fn(x, y), we create a duplicate input guard. + + # Note - we may not have a source, that is fine, it just means we had an object that is safe to have + # leave unsourced - like a local list created and discharged entirely within a local scope. + if dupe_source and dupe_source != obj_source: + ser_source_is_local = is_from_local_source(dupe_source) + source_is_local = is_from_local_source(obj_source) + if is_from_flatten_script_object_source( + dupe_source + ) or is_from_flatten_script_object_source(obj_source): + raise exc.UnsafeScriptObjectError( + f"{obj_source.name} is aliasing {dupe_source.name}. This is not supported." + f" Please do a clone for corresponding input." + ) + + # Note - both must be local, or global, or we will run afoul of a lack of merging in how we currently + # reconcile guards builder scopes in compile_check_fn. This technically means we miss a guard here, + # so maybe we should do this refactor before we land this... + # TODO(voz): Combine local and global guard builders. + if ser_source_is_local == source_is_local: + # Note - this is a little aggressive - these being duplicate input does not always matter. + # However, this should always be a sound guard to add here. + return functools.partial(GuardBuilder.DUPLICATE_INPUT, source_b=dupe_source) + return None + + +def install_guard(*guards: Guard, skip: int = 0) -> None: + """ + Add dynamo guards to the current tracing context. + + Args: + guards: guard(s) to add + skip: number of stack frames to ignore for debug stack trace + """ + from torch._guards import TracingContext + + guards_context = TracingContext.get().guards_context + if guards_context.skip_install: + return + + collect_debug_stack = guards_log.isEnabledFor( + logging.DEBUG + ) or verbose_guards_log.isEnabledFor(logging.DEBUG) + add = guards_context.dynamo_guards.add + for guard in guards: + if not isinstance(guard, Guard): + raise AssertionError(f"Expected Guard, got {type(guard)}") + if is_from_skip_guard_source(guard.originating_source): + continue + add(guard, collect_debug_stack=collect_debug_stack, skip=skip + 1) + + +# --------------------------------------------------------------------------- +# Guard check spec dispatch table — built by scanning GuardBuilder methods +# for the guard_check_spec attribute set by the decorators above. +GUARD_VALUE_DISPATCH: dict[str, GuardCheckSpec | object] = { + name: handler + for name in dir(GuardBuilder) + if (handler := getattr(getattr(GuardBuilder, name), "guard_check_spec", None)) + is not None +} + +# Validate that every guard method has an explicit guard_check_spec. +# Guard methods are identified by: uppercase name, callable, and first +# non-self parameter is 'guard'. +MISSING_GUARD_SPECS = [ + _name + for _name in dir(GuardBuilder) + if _name[0].isupper() + and not _name.startswith("_") + and callable(_method := getattr(GuardBuilder, _name, None)) + and len(_params := list(inspect.signature(_method).parameters)) >= 2 + and _params[1] == "guard" + and not hasattr(_method, "guard_check_spec") +] +if MISSING_GUARD_SPECS: + raise RuntimeError( + f"GuardBuilder methods missing guard_check_spec decorator: " + f"{', '.join(MISSING_GUARD_SPECS)}. Use @register_guard_check_spec, " + f"@skip_guard_check_spec, or @unsupported_guard_check_spec." + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/hooks.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..a3074f5916592807c9d7d503f310e61a9868d5b4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/hooks.py @@ -0,0 +1,26 @@ +"""Hook system for Dynamo's guard functionality. + +This module provides a way to register callback functions that are triggered during +guard-related operations. + +The Hooks class manages two types of hook functions: +- guard_export_fn: Called when guards need to be exported, taking a GuardsSet as input +- guard_fail_fn: Called when a guard check fails, taking a GuardFail object as input +These hooks enable customization of guard export and failure handling behaviors. +""" + +import dataclasses +from collections.abc import Callable, Sequence + +from torch._guards import GuardsSet + +from .types import GuardFail, GuardFilterEntry + + +@dataclasses.dataclass +class Hooks: + guard_export_fn: Callable[[GuardsSet], None] | None = None + guard_fail_fn: Callable[[GuardFail], None] | None = None + guard_filter_fn: Callable[[Sequence[GuardFilterEntry]], Sequence[bool]] | None = ( + None + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/logging.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..74862962adaa10f294408fd8dbe172dcdc71d743 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/logging.py @@ -0,0 +1,73 @@ +"""Logging utilities for Dynamo and Inductor. + +This module provides specialized logging functionality including: +- Step-based logging that prepends step numbers to log messages +- Progress bar management for compilation phases +- Centralized logger management for Dynamo and Inductor components + +The logging system helps track the progress of compilation phases and provides structured +logging output for debugging and monitoring. +""" + +import itertools +import logging +from collections.abc import Callable +from typing import Any + +from torch.hub import _Faketqdm, tqdm + + +# Disable progress bar by default, not in dynamo config because otherwise get a circular import +disable_progress = True + + +# Return all loggers that torchdynamo/torchinductor is responsible for +def get_loggers() -> list[logging.Logger]: + return [ + logging.getLogger("torch.fx.experimental.symbolic_shapes"), + logging.getLogger("torch._dynamo"), + logging.getLogger("torch._inductor"), + ] + + +# Creates a logging function that logs a message with a step # prepended. +# get_step_logger should be lazily called (i.e. at runtime, not at module-load time) +# so that step numbers are initialized properly. e.g.: + +# @functools.cache +# def _step_logger(): +# return get_step_logger(logging.getLogger(...)) + +# def fn(): +# _step_logger()(logging.INFO, "msg") + +_step_counter = itertools.count(1) + +# Update num_steps if more phases are added: Dynamo, AOT, Backend +# This is very inductor centric +# _inductor.utils.has_triton() gives a circular import error here + +if not disable_progress: + try: + import triton # noqa: F401 + + num_steps = 3 + except ImportError: + num_steps = 2 + pbar = tqdm(total=num_steps, desc="torch.compile()", delay=0) + + +def get_step_logger(logger: logging.Logger) -> Callable[..., None]: + if not disable_progress: + pbar.update(1) + if not isinstance(pbar, _Faketqdm): + pbar.set_postfix_str(f"{logger.name}") + + step = next(_step_counter) + + def log(level: int, msg: str, **kwargs: Any) -> None: + if "stacklevel" not in kwargs: + kwargs["stacklevel"] = 2 + logger.log(level, "Step %s: %s", step, msg, **kwargs) + + return log diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/metrics_context.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/metrics_context.py new file mode 100644 index 0000000000000000000000000000000000000000..db17f21ee5cc7d5a8d6504c5c77148b63cc6192e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/metrics_context.py @@ -0,0 +1,252 @@ +"""Metrics collection and management system for Dynamo. + +This module provides context managers for gathering and reporting metrics during +compilation and runtime. + +It includes two main components: +- MetricsContext: A context manager for collecting metrics during compilation, supporting + nested contexts and various metric types (counters, sets, key-value pairs) +- RuntimeMetricsContext: A specialized context for runtime metrics collection that doesn't + require explicit context management + +The metrics system enables comprehensive monitoring and analysis of both compilation and +execution performance. +""" + +from __future__ import annotations + +import heapq +import logging +import time +from collections.abc import Callable +from typing import Any, TYPE_CHECKING, TypeAlias +from typing_extensions import Self + + +if TYPE_CHECKING: + from collections.abc import Iterator + +from torch.utils._traceback import CapturedTraceback + + +log = logging.getLogger(__name__) + + +class TopN: + """ + Helper to record a list of metrics, keeping only the top N "most expensive" elements. + """ + + def __init__(self, at_most: int = 25) -> None: + self.at_most = at_most + self.heap: list[tuple[int, Any]] = [] + + def add(self, key: Any, val: int) -> None: + # Push if we haven't reached the max size, else push and pop the smallest + fn = heapq.heappush if len(self.heap) < self.at_most else heapq.heappushpop + fn(self.heap, (val, key)) + + def __len__(self) -> int: + return len(self.heap) + + def __iter__(self) -> Iterator[tuple[Any, int]]: + return ((key, val) for val, key in sorted(self.heap, reverse=True)) + + +OnExitType: TypeAlias = Callable[ + [int, int, dict[str, Any], type[BaseException] | None, BaseException | None], + None, +] + + +class MetricsContext: + def __init__(self, on_exit: OnExitType) -> None: + """ + Use this class as a contextmanager to create a context under which to accumulate + a set of metrics, e.g., metrics gathered during a compilation. On exit of the + contextmanager, call the provided 'on_exit' function and pass a dictionary of + all metrics set during the lifetime of the contextmanager. + """ + self._on_exit = on_exit + self._metrics: dict[str, Any] = {} + self._start_time_ns: int = 0 + self._level: int = 0 + self._edits: list[tuple[CapturedTraceback, set[str]]] = [] + + def __enter__(self) -> Self: + """ + Initialize metrics recording. + """ + if self._level == 0: + # In case of recursion, track at the outermost context. + self._metrics = {} + self._start_time_ns = time.time_ns() + + self._level += 1 + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + _traceback: Any, + ) -> None: + """ + At exit, call the provided on_exit function. + """ + self._level -= 1 + if self._level < 0: + raise AssertionError("MetricsContext level cannot become negative") + if self._level == 0: + try: + end_time_ns = time.time_ns() + self._on_exit( + self._start_time_ns, end_time_ns, self._metrics, exc_type, exc_value + ) + except Exception: + log.exception("Unexpected exception logging compilation metrics") + + def in_progress(self) -> bool: + """ + True if we've entered the context. + """ + return self._level > 0 + + def increment(self, metric: str, value: int) -> None: + """ + Increment a metric by a given amount. + """ + if self._level == 0: + raise RuntimeError(f"Cannot increment {metric} outside of a MetricsContext") + if metric not in self._metrics: + self._metrics[metric] = 0 + self._metrics[metric] += value + + def _render_edits(self, pred: set[str]) -> str: + return "\n\n" + "\n\n".join( + "Previous Traceback:\n" + "".join(e.format()) + for e, k in self._edits + if k & pred + ) + + def set(self, metric: str, value: Any, overwrite: bool = False) -> None: + """ + Set a metric to a given value. Raises if the metric has been assigned previously + in the current context. + """ + if self._level == 0: + raise RuntimeError(f"Cannot set {metric} outside of a MetricsContext") + if metric in self._metrics and not overwrite: + raise RuntimeError( + self._render_edits({metric}) + + f"\n\nRuntimeError: Metric '{metric}' has already been set in the current context " + "(see above for current and previous traceback)." + ) + self._edits.append((CapturedTraceback.extract(skip=1), {metric})) + self._metrics[metric] = value + + def set_key_value(self, metric: str, key: str, value: Any) -> None: + """ + Treats a given metric as a dictionary and set the k and value within it. + Note that the metric must be a dictionary or not present. + + We allow this to be called multiple times (i.e. for features, it's not uncommon + for them to be used multiple times within a single compilation). + """ + if self._level == 0: + raise RuntimeError(f"Cannot set {metric} outside of a MetricsContext") + if metric not in self._metrics: + self._metrics[metric] = {} + self._metrics[metric][key] = value + + def update(self, values: dict[str, Any], overwrite: bool = False) -> None: + """ + Set multiple metrics directly. This method does NOT increment. Raises if any + metric has been assigned previously in the current context and overwrite is + not set to True. + """ + if self._level == 0: + raise RuntimeError("Cannot update metrics outside of a MetricsContext") + existing = self._metrics.keys() & values.keys() + if existing and not overwrite: + raise RuntimeError( + self._render_edits(set(values.keys())) + + f"\n\nRuntimeError: Metric(s) {existing} have already been set in the current context. " + "(see above for current and previous traceback)." + ) + self._edits.append((CapturedTraceback.extract(skip=1), set(values.keys()))) + self._metrics.update(values) + + def update_outer(self, values: dict[str, Any]) -> None: + """ + Update, but only when at the outermost context. + """ + if self._level == 0: + raise RuntimeError("Cannot update metrics outside of a MetricsContext") + if self._level == 1: + self.update(values) + + def add_to_set(self, metric: str, value: Any) -> None: + """ + Records a metric as a set() of values. + """ + if self._level == 0: + raise RuntimeError(f"Cannot add {metric} outside of a MetricsContext") + if metric not in self._metrics: + self._metrics[metric] = set() + self._metrics[metric].add(value) + + def add_top_n(self, metric: str, key: Any, val: int) -> None: + """ + Records a metric as a TopN set of values. + """ + if self._level == 0: + return + if metric not in self._metrics: + self._metrics[metric] = TopN() + self._metrics[metric].add(key, val) + + +class RuntimeMetricsContext: + def __init__(self, on_exit: OnExitType) -> None: + """ + Similar to MetricsContext, but used to gather the runtime metrics that are + decoupled from compilation, where there's not a natural place to insert a + context manager. + """ + self._on_exit = on_exit + self._metrics: dict[str, Any] = {} + self._start_time_ns: int = 0 + + def increment( + self, metric: str, value: int, extra: dict[str, Any] | None = None + ) -> None: + """ + Increment a metric by a given amount. + """ + if not self._metrics: + # Start timing on the first entry + self._start_time_ns = time.time_ns() + if metric not in self._metrics: + self._metrics[metric] = 0 + self._metrics[metric] += value + + if extra: + for k, v in extra.items(): + if k not in self._metrics and v is not None: + self._metrics[k] = v + + def finish(self) -> None: + """ + Call the on_exit function with the metrics gathered so far and reset. + """ + if self._metrics: + try: + end_time_ns = time.time_ns() + self._on_exit( + self._start_time_ns, end_time_ns, self._metrics, None, None + ) + except Exception: + log.exception("Unexpected exception logging runtime metrics") + finally: + self._metrics = {} diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/mutation_guard.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/mutation_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..5e4f6abbe066057146231c3d243639446cdf4a0a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/mutation_guard.py @@ -0,0 +1,162 @@ +"""Mutation tracking and dynamic module detection system for Dynamo. + +This module provides mechanisms to track and respond to mutations in PyTorch modules +and detect dynamically created or modified modules. + +Key components: +- MutationTracker: Tracks mutations to objects and invalidates associated cached code +- GenerationTracker: Tracks module creation timing to identify dynamic instances +- Patching system for nn.Module to detect mutations and dynamic creation + +The system ensures that Dynamo's optimizations remain valid by detecting and responding +to runtime changes in module state and structure. +""" + +import functools +import inspect +import weakref +from collections.abc import MutableMapping +from typing import Any + +import torch.nn +from torch.nn import Module + +from . import config +from .utils import ExactWeakKeyDictionary, nn_module_has_global_hooks + + +unpatched_nn_module_init = torch.nn.Module.__init__ + + +class MutationTracker: + db: ExactWeakKeyDictionary = ExactWeakKeyDictionary() + + def __init__(self) -> None: + self.mutation_count: int = 0 + self.watchers: list[weakref.ReferenceType[Any]] = [] + + def on_mutation(self, name: str) -> None: + self.mutation_count += 1 + tmp = self.watchers + self.watchers = [] + for ref in tmp: + guarded = ref() + if guarded is not None: + guarded.invalidate(ref) + + def track(self, guarded_code: Any) -> None: + self.watchers.append(weakref.ref(guarded_code)) + + +def watch(obj: Any, guarded_code: Any) -> None: + """invalidate guarded_code when obj is mutated""" + ensure_patched(type(obj)) + + if obj not in MutationTracker.db: + MutationTracker.db[obj] = MutationTracker() + tracker = MutationTracker.db[obj] + tracker.track(guarded_code) + + +def ensure_patched(cls: Any) -> None: + if getattr(cls, "___needs_mutation_patch", True): + cls.___needs_mutation_patch = False + original_setattr = cls.__setattr__ + + @functools.wraps(original_setattr) + def custom_setattr(self: Any, key: str, value: Any) -> None: + try: + MutationTracker.db[self].on_mutation(key) + except KeyError: + pass + return original_setattr(self, key, value) + + cls.__setattr__ = custom_setattr + + +class GenerationTracker: + generation: int = 0 + dynamic_classes: ExactWeakKeyDictionary = ExactWeakKeyDictionary() + generation_values: ExactWeakKeyDictionary = ExactWeakKeyDictionary() + + @classmethod + def tag(cls, obj: Any) -> None: + cls.generation_values[obj] = cls.generation + + @staticmethod + def mark_class_dynamic(cls: type[torch.nn.Module]) -> None: + if not issubclass(cls, torch.nn.Module): + raise AssertionError(f"Expected a torch.nn.Module subclass, got {cls}") + GenerationTracker.dynamic_classes[cls] = True + + @classmethod + def get_generation_value(cls, obj: Any) -> int: + if obj not in cls.generation_values: + return -1 + return cls.generation_values[obj] + + @classmethod + def check(cls, obj: Any) -> bool: + return ( + obj in cls.generation_values + and cls.generation_values[obj] == cls.generation + ) + + @classmethod + def clear(cls) -> None: + cls.generation = 0 + cls.dynamic_classes = ExactWeakKeyDictionary() + cls.generation_values = ExactWeakKeyDictionary() + + +def is_dynamic_nn_module(obj: Any, is_export: bool) -> bool: + """Check for nn.Modules() created dynamically or mutated""" + if isinstance(obj, torch.nn.Module) and ( + "forward" in obj.__dict__ or isinstance(obj, (dict, MutableMapping)) + ): + # A monkey patched `.forward` indicates something wacky is going on + # Similarly a nn module also subclassed as a dict is unusual. + return True + try: + return inspect.getattr_static(obj, "torchdynamo_force_dynamic") + except AttributeError: + pass + if isinstance(obj, torch.nn.Module) and ( + not is_export or config.install_free_tensors + ): + return True + + if isinstance(obj, torch.nn.Module) and nn_module_has_global_hooks(): + return True + dyn = GenerationTracker.dynamic_classes.get(type(obj)) or GenerationTracker.check( + obj + ) + return dyn + + +def install_generation_tagging_init() -> None: + """ + Monkey patch torch.nn.Module.__init__ and torch.nn.Module.__setstate__ + so we can detect nn.Module instances created dynamically inside forward methods. + """ + + if getattr(Module, "___needs_generation_tag_patch", True): + init = Module.__init__ + + def patched_init(self: Module, *args: Any, **kwargs: Any) -> None: + init(self, *args, **kwargs) + GenerationTracker.tag(self) + + Module.__init__ = patched_init # type: ignore[method-assign] + + setstate = Module.__setstate__ + + def patched_setstate(self: Module, state: Any) -> None: + setstate(self, state) + GenerationTracker.tag(self) + + Module.__setstate__ = patched_setstate # type: ignore[method-assign] + + Module.___needs_generation_tag_patch = False # type: ignore[attr-defined] + + GenerationTracker.generation += 1 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/output_graph.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/output_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..b46ab6ae4b3608510fb542b413550ed1dfd90cbd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/output_graph.py @@ -0,0 +1,4861 @@ +""" +Core graph building functionality for PyTorch's Dynamo system. This module contains +the essential components for constructing and managing FX graphs during compilation: + +- OutputGraph: Manages the overall graph construction and compilation process. It owns + a SubgraphTracer and handles graph compilation, execution, and state management. + OutputGraph also manages features like graph deduplication, symbolic shape handling, + and tracking of side effects. + +- SubgraphTracer: Handles the actual FX graph construction by tracing Python code. + It supports advanced features like higher-order operators through nested tracers, + lifting of free variables, and handling of symbolic shapes. + +The module supports key Dynamo features including: +- Higher-order operators through nested SubgraphTracers +- Graph deduplication for optimization +- Symbolic shape handling and propagation +- Side effect tracking and management +- Guard insertion and management +""" + +import collections +import contextlib +import copy +import dataclasses +import functools +import inspect +import itertools +import logging +import operator +import re +import sys +import time +import traceback +import types +import warnings +import weakref +from collections.abc import Callable, Generator, Sequence +from dataclasses import dataclass, field as dc_field +from types import CodeType +from typing import ( + Any, + cast, + Literal, + NamedTuple, + Optional, + TYPE_CHECKING, + TypedDict, + Union, +) +from typing_extensions import NotRequired, ParamSpec, TypeVar + +import sympy + +import torch._guards +import torch._logging +import torch.distributed as dist +import torch.nn +import torch.utils._pytree as pytree +from torch import fx, Tensor +from torch._C._dynamo import guards +from torch._dynamo.exc import ShortenTraceback, TensorifyScalarRestartAnalysis +from torch._guards import ( + CompileContext, + CompileId, + GlobalContextCheckpointState, + Source, + tracing, + TracingContext, +) +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import is_custom_class +from torch._subclasses.fake_tensor import FakeTensor +from torch._utils_internal import signpost_event +from torch.export.dynamic_shapes import _ConstraintTarget +from torch.fx._lazy_graph_module import _make_graph_module # type: ignore[attr-defined] +from torch.fx.experimental._backward_state import BackwardState +from torch.fx.experimental.symbolic_shapes import ( + free_symbols, + guard_scalar, + is_symbolic, + ShapeEnv, + Specialization, + uninteresting_files, +) +from torch.fx.node import Target +from torch.fx.passes.runtime_assert import insert_deferred_runtime_asserts +from torch.utils._ordered_set import OrderedSet +from torch.utils._python_dispatch import is_traceable_wrapper_subclass + +from . import config, exc, logging as torchdynamo_logging, variables +from .backends.registry import CompiledFn, CompilerFn +from .bytecode_transformation import ( + create_binary_slice, + create_binary_subscr, + create_build_tuple, + create_call_function, + create_dup_top, + create_instruction, + create_load_const, + create_rot_n, + create_swap, + Instruction, + make_compiled_fn_name, + unique_id, +) +from .code_context import code_context +from .codegen import PyCodegen +from .current_scope_id import enter_new_scope +from .device_interface import get_interface_for_device +from .exc import ( + BackendCompilerFailed, + exceptions_allowed_to_be_fallback, + SkipFrame, + unimplemented, + unimplemented_with_warning, +) +from .graph_bytecode_inputs import has_user_objects, index_to_bytecode_constructor +from .graph_deduplication import apply_graph_deduplication +from .graph_id_filter import ( + get_backend_override_for_compile_id, + get_inductor_config_override_for_compile_id, +) +from .graph_region_tracker import GraphRegionTracker +from .guards import GuardBuilder, install_guard +from .mutation_guard import is_dynamic_nn_module +from .side_effects import AttributeMutationExisting, SideEffects, ValueMutationExisting +from .source import ( + _get_source_debug_name, + AttrSource, + BackwardStateSource, + ConstantSource, + DictGetItemSource, + GetItemSource, + GlobalStateSource, + is_constant_source, + is_from_local_source, + LocalSource, + NumpyTensorSource, + ParamBufferSource, + ShapeEnvSource, + SyntheticLocalSource, + TensorProperty, + TensorPropertySource, +) +from .utils import ( + _extract_tensor_dict, + _get_cudagraph_override, + checkpoint_params, + CleanupHook, + clone_inputs, + compilation_time_metrics, + count_calls, + counters, + dynamo_timed, + get_chromium_event_logger, + get_instruction_source_311, + get_locals_to_steal, + get_static_address_type, + get_unique_name_wrt, + graph_break_reasons, + increment_op_count, + istype, + lazy_format_graph_code, + LazyString, + nn_module_proxy, + same, + set_example_value, +) +from .variables.builder import ( + BackwardStateGraphArg, + GraphArg, + TrackedFake, + wrap_fx_proxy, +) +from .variables.ctx_manager import ContextWrappingVariable +from .variables.functions import ClosureConversionError, VariableTracker +from .variables.lists import BaseListVariable +from .variables.misc import NullVariable +from .variables.nn_module import NNModuleVariable +from .variables.tensor import ( + NumpyNdarrayVariable, + SymNodeVariable, + UnspecializedPythonVariable, +) +from .variables.torch_function import TensorWithTFOverrideVariable +from .variables.user_defined import UserDefinedDictVariable + + +if TYPE_CHECKING: + from torch._dynamo.dynamo_profiler import DynamoProfilerState + from torch._dynamo.package import CompilePackage + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + from torch._dynamo.variables.functions import LocalGeneratorObjectVariable + from torch._inductor import _CudagraphAnnotation + from torch.multiprocessing.reductions import StorageWeakRef + +log = logging.getLogger(__name__) +graph_tabular_log = torch._logging.getArtifactLogger(__name__, "graph") +graph_code_log = torch._logging.getArtifactLogger(__name__, "graph_code") +graph_sizes_log = torch._logging.getArtifactLogger(__name__, "graph_sizes") +trace_call_log = torch._logging.getArtifactLogger(__name__, "trace_call") + +RootGuardManager = guards.RootGuardManager + +TensorMetadataDim = int | torch.SymInt | None +TensorMetadataSequence = Sequence[TensorMetadataDim] +OutputReturnKind = Literal["graph_out", "input", "constant"] + + +class SizesStridesInfo(TypedDict): + size: TensorMetadataSequence + stride: TensorMetadataSequence + values_size: NotRequired[TensorMetadataSequence] + values_stride: NotRequired[TensorMetadataSequence] + + +class CodeOptions(TypedDict): + co_argcount: int + co_posonlyargcount: int + co_kwonlyargcount: int + co_nlocals: int + co_stacksize: int + co_flags: int + co_code: bytes + co_consts: tuple[object, ...] + co_names: tuple[str, ...] + co_varnames: tuple[str, ...] + co_filename: str + co_name: str + co_qualname: NotRequired[str] + co_firstlineno: int + co_linetable: bytes + co_exceptiontable: NotRequired[bytes] + co_freevars: tuple[str, ...] + co_cellvars: tuple[str, ...] + + +class OutputReturnInfo(NamedTuple): + kind: OutputReturnKind + value: object + + +# Capture fn pointer at import time +# This is to guard against trying to mark the iterated tensors +# as static in case user overrides fn ptr +og_module_named_buffers_fn_ptr = torch.nn.Module.named_buffers +og_module_named_parameters_fn_ptr = torch.nn.Module.named_parameters + + +def _wrap_with_inductor_config( + compiler_fn: Any, config_patches: dict[str, Any] +) -> Callable[..., Any]: + """ + Wrap a compiler function to apply inductor config patches during compilation. + + Passes config_patches as a keyword argument so that compile_fx can + propagate them to backward compilation via its inner_compile wrapping. + """ + + def wrapped(gm: Any, example_inputs: Any) -> Any: + return compiler_fn(gm, example_inputs, config_patches=config_patches) + + # Preserve function metadata for logging + wrapped.__name__ = getattr(compiler_fn, "__name__", "") + wrapped.__wrapped__ = compiler_fn # type: ignore[attr-defined] + return wrapped + + +@dataclass(frozen=True) +class AliasingInfo: + has_aliasing: bool + msg: str + + +@dataclass(frozen=True) +class MutationInfo: + has_mutation: bool + msg: str + mutated_input_indices: tuple[int, ...] = () + + +def collect_reachable_grad_fns( + tensors_with_sources: list[tuple[torch.Tensor, str | None]], + stop_at: set[torch.autograd.graph.Node] | None = None, +) -> set[torch.autograd.graph.Node]: + """Collect all grad_fns reachable from tensors' autograd graphs. + + Performs a DFS traversal and collects all visited grad_fns. + Optionally stops traversal nodes in stop_at set. This signals the + autograd.grad boundary. + + Args: + tensors_with_sources: List of (tensor, source_name) tuples to start search from. + stop_at: Optional set of grad_fns where traversal should stop (excluded from result). + + Returns: + Set of all reachable grad_fns. + """ + if stop_at is None: + stop_at = set() + + visited: set[torch.autograd.graph.Node] = set() + stack: list[torch.autograd.graph.Node] = [] + + for tensor, _ in tensors_with_sources: + if isinstance(tensor, torch.Tensor): + grad_fn = tensor.grad_fn + if grad_fn is not None: + stack.append(grad_fn) + + while stack: + node = stack.pop() + if node in visited: + continue + # Stop traversal at stop_at nodes and don't include them + # in consumed grad_fn list. + if node in stop_at: + continue + visited.add(node) + for next_fn, _ in node.next_functions: + if next_fn is not None: + stack.append(next_fn) + return visited + + +@functools.cache +def _step_logger() -> Any: + return torchdynamo_logging.get_step_logger(log) + + +@dataclass +class GraphCompileReason: + """Stores why a given output graph was compiled; i.e. what caused the graph break.""" + + reason: str + user_stack: list[traceback.FrameSummary] + + # Indicates if this was a graph break reason due to graph break. + graph_break: bool = True + + def __post_init__(self) -> None: + if self.graph_break: + graph_break_reasons.append(self) + + +def _get_gen_rand_values_fn(random_calls: Any) -> Callable[[], list[Any]]: + def _gen_rand_values() -> list[Any]: + return [fn(*args, **kwargs) for fn, args, kwargs in random_calls] + + return _gen_rand_values + + +class FakeRootModule(torch.nn.Module): + """Trick the constructor of fx.GraphModule""" + + def __init__(self, nn_modules: dict[str, torch.nn.Module]) -> None: + super().__init__() + for k, v in nn_modules.items(): + setattr(self, k, v) + + def __repr__(self) -> str: + return "FakeRootModule(...)" + + def add_nn_modules(self, nn_modules: dict[str, torch.nn.Module]) -> None: + for k, v in nn_modules.items(): + setattr(self, k, v) + + +class WrapperBackend: + def __init__(self, backend: CompilerFn) -> None: + self.backend: CompilerFn = backend + + def __call__( + self, gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] + ) -> CompiledFn: + self.restore = checkpoint_params(gm) + self.gm = gm + copy_gm = copy.deepcopy(self.gm) + self.candidate = self.backend(copy_gm, example_inputs) + + if self.candidate is None or self.candidate is self.gm.forward: + return self.gm.forward + + if not config.verify_correctness: + return self.candidate + + # if verify_correctness=True + try: + correct = self.gm.forward(*clone_inputs(example_inputs)) + result = self.candidate(*clone_inputs(example_inputs)) + + # TODO: replace `same` function with the one in testing + if same(correct, result): + return self.candidate + + raise RuntimeError(f"incorrect results of backend {self}") + + except Exception: + log.exception("error in verify_correctness") + raise + finally: + self.restore() + + +Scope = dict[str, object] + + +@dataclass +class BytecodeTracingTimings: + """Accumulated wall-clock time (ns) for major components during Dynamo + bytecode tracing that are not related to variable trackers. Each field + is an int accumulator that gets bumped via ``time.time_ns()`` in the + corresponding hot-path wrapper. To add a new timer, add a field here + and wire up the wrapper in the relevant function.""" + + get_fake_value_ns: int = 0 + create_proxy_ns: int = 0 + wrap_to_fake_tensor_and_record_ns: int = 0 + variable_builder_call_ns: int = 0 + + def report_and_reset(self) -> None: + """Flush accumulated timings to the bytecode_tracing chromium event + and to compilation_time_metrics, then reset all counters.""" + chromium_log = get_chromium_event_logger() + # pyrefly: ignore [implicit-any] + event_data = {} + for f in dataclasses.fields(self): + ns_val = getattr(self, f.name) + if ns_val > 0: + key = f.name.removesuffix("_ns") + event_data[f"{key}_time_s"] = ns_val / 1e9 + compilation_time_metrics.setdefault(key, []).append(ns_val / 1e9) + setattr(self, f.name, 0) + if event_data: + chromium_log.try_add_event_data("bytecode_tracing", **event_data) + + +@dataclass +class OutputGraphGuardsState: + """ + A base class containing fields that are considered "persistent" when we + want to save all the important state for reconstrucing guards in a different + process. Normally we don't need to add states here, but we may have to when + the information is needed to serialize the guards, so the fields here are + supposed to be serializable as a requirement. + """ + + local_scope: Scope + global_scope: Scope + # This records the initial torch function mode stack for guarding + torch_function_mode_stack: list[torch.overrides.TorchFunctionMode] + guard_on_key_order: set[Source] + # Map from graph input's `Source` to sizes / strides metadata + input_source_to_sizes_strides: dict[Source, SizesStridesInfo] + dual_level: int + functorch_layers: list[torch._functorch.pyfunctorch.FuncTorchInterpreter] + current_device: torch.device | None + global_state_guard: torch._C._dynamo.guards.GlobalStateGuard + _guards: torch._guards.GuardsSet + _aotautograd_guards: list[torch._guards.GuardEnvExpr] + + # Whether or not the guards should be checked for correctness + + export: bool = False + skip_guards_check: bool = False + export_constraints: bool = False + name_of_builtins_dict_key_in_fglobals: str | None = None + + @property + def shape_env(self) -> ShapeEnv: + raise AssertionError(f"shape_env shouldn't be accessed from {type(self)}") + + @property + def guards(self) -> torch._guards.GuardsSet: + return self._guards + + @property + def aotautograd_guards(self) -> list[torch._guards.GuardEnvExpr]: + return self._aotautograd_guards + + def dump_guards_state(self) -> "OutputGraphGuardsState": + # Dump a serializable version of self without extras + return OutputGraphGuardsState( + local_scope=self.local_scope, + global_scope=self.global_scope, + torch_function_mode_stack=self.torch_function_mode_stack, + guard_on_key_order=self.guard_on_key_order, + input_source_to_sizes_strides=self.input_source_to_sizes_strides, + dual_level=self.dual_level, + functorch_layers=self.functorch_layers, + current_device=self.current_device, + global_state_guard=self.global_state_guard, + name_of_builtins_dict_key_in_fglobals=self.name_of_builtins_dict_key_in_fglobals, + export=self.export, + export_constraints=self.export_constraints, + _guards=self.guards, + _aotautograd_guards=self.aotautograd_guards, + skip_guards_check=self.skip_guards_check, + ) + + +@dataclass +class StackLocalsMetadata: + """ + Stores metadata for a frame's stack and locals for the purposes of building resume functions + """ + + num_stack: int = 0 # number of stack elements, minus removed NULLs + locals_names: dict[str, int] = dc_field( + default_factory=dict + ) # order of locals codegen'd to the stack + stack_null_idxes: list[int] = dc_field(default_factory=list) + locals_null_keys: list[str] = dc_field(default_factory=list) + stack_ctx_args: list[tuple[int, tuple[object, ...]]] = dc_field( + default_factory=list + ) + stack_ctx_idxes_orig: list[int] = dc_field(default_factory=list) + locals_ctx_args: list[tuple[str, tuple[object, ...]]] = dc_field( + default_factory=list + ) + + +# TODO we should expand this to make it work for atribtrary in/out +@dataclass +class ExportMetaData: + # maps graph input index to its' source which is later + # used in export to map to correct user input. In its' flat form, + # just looks like GetItem(base=LocalSource("foo", idx=0)) + graph_input_idx_to_local_source: dict[int, Source | None] = dc_field( + default_factory=dict + ) + # maps user output idx to what type of output it is. There are 3 options: + # 1) graph out + # 2) user input + # 3) constants + output_return_type: dict[int, OutputReturnInfo] = dc_field(default_factory=dict) + # output spec of the traced function + out_spec: torch.utils._pytree.TreeSpec | torch.utils._pytree.LeafSpec = ( + torch.utils._pytree._LEAF_SPEC + ) + module_call_spec: dict[ + str, + dict[str, torch.utils._pytree.TreeSpec | torch.utils._pytree.LeafSpec], + ] = dc_field(default_factory=dict) + + +def _canonical_key(node: fx.Node, canonical_idx: dict[fx.Node, int]) -> object: + """Canonical heap key for Dynamo output graph nodes. + + Placeholders are sorted by grapharg source name; all other ops delegate + to the shared ``_canonical_node_key``. + """ + if node.op == "placeholder": + grapharg = node.meta.get("grapharg") + if grapharg is not None and grapharg.source is not None: + source_name = grapharg.source.name + else: + source_name = "" + return (0, source_name) + from torch.fx.passes.canonicalize import _canonical_node_key + + return _canonical_node_key(node, canonical_idx) + + +def _canonicalize_graph(graph: fx.Graph) -> None: + """Canonicalize a Dynamo output graph's node order and names. + + Delegates to ``torch.fx.passes.canonicalize.canonicalize_graph`` with + Dynamo-specific key generation and barrier detection. + """ + from torch.fx.passes.canonicalize import _is_safe_to_reorder, canonicalize_graph + + canonicalize_graph(graph, _canonical_key, _is_safe_to_reorder) + + +def get_builtins_dict(global_scope: Scope) -> dict[str, Any]: + # f_globals["__builtins__"] can be a dict or a module. This is an + # implementation detail - + # https://docs.python.org/3/library/builtins.html. + + # This makes guarding on any builtin messy because the guard check_fn + # has to check if the __builtins__ is a module or dict, and then access + # by either using getattr or getitem respectively. + + # To solve this problem, we insert a new entry in f_globals which points + # to the builtins __dict__ and then we guard any builtin on this dict. + # To avoid any collision with the pre-existing keys, we use the + # install_global to give us a unique dict key. + + f_builtins = global_scope["__builtins__"] + if not isinstance(f_builtins, dict): + f_builtins = f_builtins.__dict__ + return f_builtins + + +class OutputGraphCommon(OutputGraphGuardsState): + """ + A minimal interface for full graph capture. It is intended to be + the target of any tracer that feeds into backends. + + Currently dynamo's OutputGraph is the only known implementation + of this interface, used by (aot) precompile and (strict) export. + Importantly, that implementation also contains many other fields + that are using during tracing but not included in this interface + because they are not used once tracing is complete. + + It should be safe to assume that (caching) precompile also uses + this interface. + + In the future, we want make_fx, used by (non-strict) export, to + also implement this interface. + + The serializable part of this interface is OutputGraphGuardsState. + We do not need to serialize other parts; however it will pay to + be disciplined about what those other parts are, especially since + we want other tracers to be able to meaningfully implement them, + and we should generally try to cut them down when possible. + """ + + def __init__( + self, + output_graph_guards_state: OutputGraphGuardsState, + import_sources: dict[str, str] | None = None, + shape_env: ShapeEnv | None = None, + export_metadata: ExportMetaData | None = None, + tracked_fakes_id_to_source: dict[int, list[Source]] | None = None, + output_pycode: list[list[str] | None] | None = None, + ) -> None: + super().__init__( + output_graph_guards_state.local_scope, + output_graph_guards_state.global_scope, + output_graph_guards_state.torch_function_mode_stack, + output_graph_guards_state.guard_on_key_order, + output_graph_guards_state.input_source_to_sizes_strides, + output_graph_guards_state.dual_level, + output_graph_guards_state.functorch_layers, + output_graph_guards_state.current_device, + output_graph_guards_state.global_state_guard, + output_graph_guards_state._guards, + output_graph_guards_state._aotautograd_guards, + output_graph_guards_state.export, + output_graph_guards_state.skip_guards_check, + output_graph_guards_state.export_constraints, + output_graph_guards_state.name_of_builtins_dict_key_in_fglobals, + ) + + self.import_sources = import_sources or {} + # The following fields are currently known to be used by clients. + # In particular, we need: + # - shape_env, for building guards + # - export_metadata, for un/flattening inputs and outputs + # - tracked_fakes_id_to_source, for processing tensor dim constraints + self._shape_env = shape_env or ShapeEnv() # private for inheritance + self.export_metadata = export_metadata or ExportMetaData() + self.tracked_fakes_id_to_source: dict[int, list[Source]] = ( + tracked_fakes_id_to_source or {} + ) + self.output_pycode = output_pycode or [] + + @property + def shape_env(self) -> ShapeEnv: + return self._shape_env + + def bypass_package(self, reason: str = "", **kwargs: Any) -> None: + # NOTE: currently there are no tests for this but it is reachable + # when building guards, so technically necessary to include here. + # It is unclear whether we should include packaging altogether. + raise NotImplementedError + + +class OutputGraph(OutputGraphCommon): + """ + Wrapper class to hold outputs of InstructionTranslator. Mainly the + generated fx.Graph. + + OutputGraph is 1:1 with a frame being processed. Each frame is associated + with some root InstructionTranslator. When user code calls a function, + we construct a InliningInstructionTranslator that continues to write into + the root InstructionTranslator's OutputGraph. + """ + + side_effects: SideEffects + + def __init__( + self, + code_options: CodeOptions, + compiler_fn: CompilerFn | None, + root_tx: "InstructionTranslatorBase", + export: bool, + export_constraints: Sequence[_ConstraintTarget], + frame_state: Any, + local_scope: Scope, + global_scope: Scope, + f_code: CodeType, + torch_function_mode_stack: list[torch.overrides.TorchFunctionMode], + package: Optional["CompilePackage"], + one_graph: bool = False, + ) -> None: + OutputGraphGuardsState.__init__( + self, + local_scope, + global_scope, + torch_function_mode_stack, + guard_on_key_order=set(), + input_source_to_sizes_strides={}, + dual_level=torch.autograd.forward_ad._current_level, + functorch_layers=torch._functorch.pyfunctorch.retrieve_all_functorch_interpreters(), + current_device=torch.utils._device.CURRENT_DEVICE, + # initial_global_state is only None during NopTest. + global_state_guard=torch._dynamo.convert_frame.initial_global_state + or torch._C._dynamo.guards.GlobalStateGuard(), + # These are set by @property instead, just initialize them as blank + _guards=torch._guards.GuardsSet(), + _aotautograd_guards=[], + ) + self.tracers = [SubgraphTracer(self, is_export=export)] + # Map from graph input's `Source` to its `VariableTracker` to + # de-duplicate graph inputs by source and reuse the tracker + self.input_source_to_var: dict[Source, VariableTracker] = {} + # List of TensorVariables that are leaf tensors created in-graph + # (e.g., nn.Parameter via tracable_create_parameter). These need to be + # tracked separately from input_source_to_var for backward() auto-detection. + self.leaf_var_creation_order: list[VariableTracker] = [] + self.export = export + self.export_constraints = export_constraints # type: ignore[assignment] + self.frame_state = frame_state + self.cleanup_hooks: list[Callable[[], Any]] = [] + # compile_id is an id number for the current torch.compile + self.compile_id: int = next(_compile_id_counter) + # Set of globals installed via install_global* APIs + self.installed_globals: set[str] = set() + + # TODO: maybe should just pass the entire f_code in here? Not + # sure... + self.co_fields = { + "co_name": f_code.co_name, + "co_filename": f_code.co_filename, + "co_firstlineno": f_code.co_firstlineno, + } + + # The cudagraph annotation is normally set while tracing an + # `override_cudagraphs` context manager / decorator within this + # frame (see CudagraphOverrideVariable). Seed it here from any + # runtime-active override so a callee compiled as a separate frame + # (e.g. because it contains a graph break and cannot be inlined) + # inherits the override that lives lexically in a caller's frame. + # NOTE: we intentionally do not guard on the override state, so the + # override is sticky per code object (first compile wins): a function + # reached both inside and outside an override keeps whichever override + # was active when it first compiled. + self.cudagraph_annotation: _CudagraphAnnotation | None = None + if (_override := _get_cudagraph_override()) is not None: + from torch._inductor import _CudagraphAnnotation as _CGA + + self.cudagraph_annotation = _CGA(fwd=_override[0], bwd=_override[1]) + + self.region_tracker = GraphRegionTracker() + self._emit_debugger_breakpoint: bool = False + self._shallow_copy_placeholder_snapshots: dict[torch.fx.Node, torch.Tensor] = {} + + # tracked_fakes says where any tensor that was wrapped to fake came + # from. It is similar to GraphArg, in that all GraphArgs will get + # will get added to TrackedFakes, but TrackedFakes also contains + # GraphArgs that got pruned, and things like Tensor attributes which + # aren't explicit graph inputs. Used by shape guard + self.tracked_fakes: list[TrackedFake] = [] + + shape_env = ShapeEnv( + # Reference Cycle! + # Share a reference to the list of TrackedFake. + # + # ShapeEnv needs this in order to be able to reproduce the call + # to produce_guards at an arbitrary time point. That is because + # TrackedFake instances may have its metadata changed throughout + # the program execution. + tracked_fakes=self.tracked_fakes, + # We want to allow capture scalar outputs and allow_dynamic_output_shape_ops when fullgraph=True + allow_scalar_outputs=one_graph or config.capture_scalar_outputs, + allow_dynamic_output_shape_ops=one_graph + or config.capture_dynamic_output_shape_ops, + prefer_deferred_runtime_asserts_over_guards=config.prefer_deferred_runtime_asserts_over_guards, + co_fields=self.co_fields, + ) + + # In export mode, we force the shape_env to strictly disallow any constraining + # of the user marked dynamic dims + import torch._functorch.config as _config + + with _config.patch(fake_tensor_allow_unsafe_data_ptr_access=False): + fake_mode = torch._subclasses.FakeTensorMode( + shape_env=shape_env, + # TODO (tmanlaibaatar) Remove this once we always lift params and buffers + allow_non_fake_inputs=bool(self.export), + export=self.export, + ) + self.tracing_context: TracingContext = TracingContext(fake_mode) + self.tracing_context.traced_code.append(f_code) + self.tracing_context.cudagraph_annotation = self.cudagraph_annotation + self.traced_code = self.tracing_context.traced_code + self.dynamo_compile_id: CompileId | None = CompileContext.current_compile_id() + self.init_ambient_guards() + + # Wire ShapesSpec.assumptions BEFORE any input is processed. Each + # assumption is appended to `_shape_spec_pending_assumptions`; + if config._dynamic_shapes_spec is not None: + from torch.fx.experimental.symbolic_shapes import _wire_spec_assumptions + + _wire_spec_assumptions(self.shape_env, config._dynamic_shapes_spec) + + # Map each tensor id to a list of sources. This is necessary because + # tensor ids cannot be recovered from tracked fakes (in general). + # We use this map to interpret (i.e., check for violations of) constraints, + # specifically equality constraints, which have shared tensor ids in them. + # This map should also be generally useful, e.g., for (de)serialization. + self.tracked_fakes_id_to_source: dict[int, list[Source]] = ( + collections.defaultdict(list) + ) + # Stores the full fqn of a param or buffer to the relevant source. + self.param_name_to_source: dict[str, Source] | None = {} + self.side_effects = SideEffects(self) + # Generators created while tracing this frame. Tracked here (not on + # SideEffects) because SideEffects is cloned/swapped during HOP + # speculation and graph-break restore; the OutputGraph is the single + # instance that lives for the whole frame. Closed in compile_subgraph. + self.local_generators: list[LocalGeneratorObjectVariable] = [] + # Cached variable trackers. This makes symbolic analysis of LOAD_GLOBAL + # and LOAD_ATTR for same python objects free. + self.variable_tracker_cache: dict[Source, VariableTracker] = {} + # Cache for sources resolved via MRO walk, keyed by id(obj). + # When the same descriptor (e.g. property) is reached from multiple + # subclasses, we reuse the first source to avoid redundant guards. + # We thought of rolling this in variable_tracker_cache but here + # different sources point to the same object, we also don't want it to + # go through the side effects cache because even though these objects + # are same, we don't want OBJECT_ALIASING guards on them. For these + # objects, we have DICT_CONTAINS absent guards on the mro walk, so there + # is no need of the OBJECT_ALIASING guards. + self.mro_source_cache: dict[tuple[int, str], DictGetItemSource] = {} + # Tracks (id(klass), attr_name) pairs that already have a + # DICT_CONTAINS absent guard installed during MRO walks. When + # multiple subclasses share the same intermediate MRO class, we + # only need to guard the absence once per (class, attr) pair. + self.guarded_mro_absent_keys: set[tuple[int, str]] = set() + # Cache for inspect.signature results: function -> VariableTracker + self.signature_cache: dict[Any, VariableTracker] = {} + self.unique_var_id = itertools.count() + self.code_options: CodeOptions = cast(CodeOptions, dict(code_options)) + self.output_instructions: list[Instruction] = [] + self.output_pycode: list[list[str] | None] = [] + # used to track nodes that are added between calls of copy_graphstate + # and restore_graphstate + self.timestamp = 0 + + # Maps stream id (id(stream_value)) → user stack trace for input + # mutations on that stream. Used to error when an event records on a + # stream that already has an input mutation (the epilogue copy_() + # wouldn't be captured). We key by id() of the underlying + # torch.Stream so we can peek lazy variables without realizing them. + self._input_mutation_streams: dict[int, traceback.StackSummary] = {} + self._last_checked_input_versions: dict[int, int] | None = None + + # A list of register_finalizer_fns to apply to the output graph module + self.register_finalizer_fns: list[Callable[[fx.GraphModule], None]] = [] + + # Not checkpointed + self.compiler_fn: CompilerFn | None = compiler_fn + self.root_tx = root_tx + + # Profiler state for tracking function trace timings + self.profiler_state: DynamoProfilerState | None = None + + self.package = package + # Given a source, what are the user stacks of all locations that + # accessed it? + # + # For efficiency, we only populate this: + # - During export, and + # - If the source could potentially lead to a spurious export input + # + # Feel free to populate this more frequently if other use-cases arise, + # but be aware that we have to generate full stacks for each + # recording! + self.source_to_user_stacks: dict[Source, list[traceback.StackSummary]] = {} + + self._current_tx: list[InstructionTranslatorBase] = [] + self.cleanups: list[CleanupHook] = [] + self.should_exit = False + self.unspec_variable_map: dict[str, UnspecializedPythonVariable] = {} + + # This returns false if TF Overall (both mode and subclass) is disabled OR that TF Mode stack is empty + self.torch_function_mode_enabled = torch._C._is_torch_function_mode_enabled() + + # Used to wrap the compiled graph at runtime with + # DisableTorchFunctionSubclass to prevent double dispatch. + self.torch_function_subclass_inlined = False + + # Tracks if the output graph has a user defined allowed function in the + # graph. This is used later to determine if we should fallback to eager + # for certain exceptions. THe idea is that if the user has applied + # allow_in_graph, they would like to see the error instead of falling + # back for backend errors. + self.has_user_defined_allowed_in_graph = False + + # Tracks ALL grad_fn nodes that are consumed by torch.autograd.grad(outputs, inputs). + # This is the set of all nodes reachable from outputs' grad_fns, excluding inputs' grad_fns + # (since autograd.grad stops at inputs without consuming them). + # Used to detect returning tensors connected to consumed grad_fns (would cause + # "backward through graph a second time" error in aot_autograd). + self.autograd_grad_consumed_grad_fns: set[torch.autograd.graph.Node] = set() + + # Tracks a list of called ops that were not tagged with "pt2_compliant_tag". + # This information is useful for logging. + self.non_compliant_ops: set[torch._ops.OpOverload] = set({}) + + # Tracks a list of called custom ops that were tagged with "pt2_compliant_tag". + # This information is useful for logging. + self.compliant_custom_ops: set[torch._ops.OpOverload] = set({}) + + # We save the global torch state here to be restored in case of graph + # breaks. The relevant issue is seen here + # https://github.com/pytorch/pytorch/pull/100570#issuecomment-1543427086 + # where inlining of a function changes the global state (because of the + # presence of torch.no_grad) and there is a graph break. + self.save_global_state() + + # Tracks the original FQNs of the constant tensors from the original graph, + # i.e. buffers and parameters. + self.dynamo_flat_name_to_original_fqn: dict[str, str] = {} + + # All calls to random() are replaced with a single call to __gen_rand_values + # functions that returns a tuple of random values for each original call. + # random_calls tracks calls to random() and random_values_var stores the name of + # the variable that stores __gen_rand_values results. + self.random_calls: list[ + tuple[Callable[..., object], tuple[object, ...], dict[str, object]] + ] = [] + self.random_values_var: Any = None + + # Bytecode to insert right before we call the graph + self.pregraph_bytecode: list[Instruction] = [] + + # Maps SyntheticLocalSource → (fn, args, arg_sources) for hoisted + # graph inputs created by synthetic_graph_input, so invoke_subgraph + # reuse can recreate them on cache hit. arg_sources allows stamp-out + # to resolve new ctor arg values via source replacement. + self.synthetic_source_ctor_info: dict[ + SyntheticLocalSource, + tuple[ + Callable[..., Any], tuple[Any, ...], tuple[Source | None, ...] | None + ], + ] = {} + + # Use to pass values to backward hooks when using compiled autograd + self.backward_state: dict[str, VariableTracker] = {} + self.backward_state_proxy: torch.fx.Proxy | None = None + self.backward_state_var: str | None = None + + # pyrefly: ignore [bad-override] + self.name_of_builtins_dict_key_in_fglobals: str = ( + self.install_builtins_dict_in_fglobals() + ) + + self.compiler_trace_stack = contextlib.ExitStack() + + self.bytecode_tracing_timings = BytecodeTracingTimings() + + # These are the ambient, currently-global saved_tensor_hooks stashed in autograd, + # that are set for the entire duration of the compiled region. + # This is an invariant today because we graph break on the saved_tensor_hook + # context manager inside a compiled region + self.saved_tensors_hooks_subgraph_names: list[str] | None = ( + self.maybe_install_saved_tensors_hooks_subgraphs() + ) + + # mangled alias -> module fqn name + self.import_sources: dict[str, str] = {} + + self.export_metadata = ExportMetaData() + + # Set of inlined unspecialized modules names to generate the + # dynamo_flat_name_to_original_fqn mapping. + self.used_inlined_inbuilt_modules_names: OrderedSet[str] = OrderedSet() + + self.attr_source_cache: dict[tuple[Source, str], AttrSource] = {} + self._cached_replayed_side_effect_source_refs: tuple[str, ...] | None = None + + def track_generator(self, gen: "LocalGeneratorObjectVariable") -> None: + self.local_generators.append(gen) + + def close_local_generators(self, tx: "InstructionTranslatorBase") -> None: + from .symbolic_convert import temporarely_allow_writes_to_output_graph + + with temporarely_allow_writes_to_output_graph(tx): + for gen in list(self.local_generators): + gen.call_method(tx, "close", [], {}) + + def get_replayed_side_effect_source_refs( + self, *, populate_export_metadata: bool = False + ) -> list[str]: + """Return Python-side effect sources that Dynamo replays outside the FX graph.""" + if ( + not populate_export_metadata + and not self.side_effects.id_to_variable + and self._cached_replayed_side_effect_source_refs is not None + ): + return list(self._cached_replayed_side_effect_source_refs) + + from torch.export._trace import _ExportModuleSpecTrackerDict + + potential_side_effects = [] + for var in self.side_effects._get_modified_vars(): + if hasattr(var, "mutation_type"): + mut_type = var.mutation_type + # Skip codegen-specific mutations that never materialize as + # externally visible Python side effects. + if isinstance( + mut_type, (AttributeMutationExisting, ValueMutationExisting) + ): + if isinstance(var, UserDefinedDictVariable) and isinstance( + var.value, _ExportModuleSpecTrackerDict + ): + if populate_export_metadata: + if var._base_vt is None: + raise AssertionError("var._base_vt must not be None") + for ( + k, + v, + ) in ( + var._base_vt.items.items() # pyrefly: ignore[missing-attribute] + ): + # pyrefly: ignore [implicit-any] + specs = {} + # pyrefly: ignore[missing-attribute] + for k_spec, val in v.items.items(): + specs[k_spec.vt.as_python_constant()] = ( + val.as_python_constant() + ) + if ["in_spec", "out_spec"] != list(specs.keys()): + raise AssertionError( + f"Expected specs keys to be ['in_spec', 'out_spec'], got {list(specs.keys())}" + ) + self.export_metadata.module_call_spec[ + # pyrefly: ignore[missing-attribute] + k.vt.as_python_constant() + ] = specs + # export uses tracepoint pass to dump submodule inp/out spec + # into global state, so we filter it here + if not ( + isinstance(var, UserDefinedDictVariable) + and isinstance(var.value, _ExportModuleSpecTrackerDict) + ): + potential_side_effects.append(var) + + return [_get_source_debug_name(var.source) for var in potential_side_effects] + + def get_chained_attr_source(self, base: Source, path: str) -> AttrSource: + parts = path.split(".") + key = (base, parts[0]) + if key not in self.attr_source_cache: + self.attr_source_cache[key] = AttrSource(base, parts[0]) + result = self.attr_source_cache[key] + for part in parts[1:]: + key = (result, part) + if key not in self.attr_source_cache: + self.attr_source_cache[key] = AttrSource(result, part) + result = self.attr_source_cache[key] + return result + + def get_chained_param_buffer_source( + self, base: Source, path: str + ) -> "ParamBufferSource": + parts = path.rsplit(".", 1) + if len(parts) == 1: + return ParamBufferSource(base, path) + intermediate_base = self.get_chained_attr_source(base, parts[0]) + return ParamBufferSource(intermediate_base, parts[1]) + + def mark_bytecode_tracing_start(self) -> None: + self.compiler_trace_stack.enter_context( + dynamo_timed( + "bytecode_tracing", + log_pt2_compile_event=True, + ) + ) + # Start profiler timing for the root function + if config.dynamo_profiler: + from torch._dynamo.dynamo_profiler import DynamoProfilerState + + if self.profiler_state is None: + self.profiler_state = DynamoProfilerState() + code = self.root_tx.f_code + self.profiler_state.push( + code.co_name, + code.co_filename, + code.co_firstlineno, + time.time_ns(), + ) + + def mark_bytecode_tracing_stop(self) -> None: + self.bytecode_tracing_timings.report_and_reset() + self.compiler_trace_stack.close() + # Record profiler timing for the root function and dump stats + if config.dynamo_profiler and self.profiler_state is not None: + from torch._dynamo.dynamo_profiler import FunctionTraceTiming + + stack_entry = self.profiler_state.pop() + trace_end_ns = time.time_ns() + if stack_entry is not None: + cumtime_ns = trace_end_ns - stack_entry.start_time_ns + tottime_ns = cumtime_ns - stack_entry.child_time_ns + timing = FunctionTraceTiming( + func_name=stack_entry.func_name, + filename=stack_entry.filename, + firstlineno=stack_entry.firstlineno, + cumtime_ns=cumtime_ns, + tottime_ns=tottime_ns, + bytecode_count=len(self.root_tx.f_code.co_code), + inline_depth=0, + caller_func_name=None, + caller_filename=None, + caller_firstlineno=None, + is_primitive_call=stack_entry.is_primitive_call, + call_stack=(), + ) + self.profiler_state.record_timing(timing) + + # Dump profiler stats + output_file = None + if isinstance(config.dynamo_profiler, str): + output_file = config.dynamo_profiler + self.profiler_state.dump_stats(output_file) + + def install_builtins_dict_in_fglobals(self) -> str: + f_builtins = get_builtins_dict(self.global_scope) + return self.install_global("__builtins_dict__", f_builtins) + + def add_backward_state_hook( + self, hook: VariableTracker, prefix: str = "hook" + ) -> tuple[str, torch.fx.Proxy]: + name = f"{prefix}{len(self.backward_state)}" + if name in self.backward_state: + raise AssertionError( + f"backward_state hook name '{name}' already registered" + ) + self.backward_state[name] = hook + return name, self.get_backward_state_proxy() + + def get_backward_state_proxy(self) -> torch.fx.Proxy: + if self.backward_state_proxy is None: + if self.export: + unimplemented( + gb_type="backward_state does not support export", + context="", + explanation="Compiled autograd doesn't work with `torch.export`.", + hints=[], + ) + example_value = BackwardState() + self.backward_state_proxy = self.root_tracer.create_graph_input( + "dynamo_backward_state", + type(example_value), + example_value, + source=BackwardStateSource(), + ) + self.backward_state_proxy.node.meta["grapharg"] = BackwardStateGraphArg() + self.backward_state_var = self.new_var() + return self.backward_state_proxy + + # This gets its own helper function so guards DEBUG logs are more informative + def init_ambient_guards(self) -> None: + # Register a SHAPE_ENV guard to make sure we setup shape guards + # that show up in ShapeEnv + self.guards.add(ShapeEnvSource().make_guard(GuardBuilder.SHAPE_ENV)) + + self.guards.add( + GlobalStateSource().make_guard(GuardBuilder.DETERMINISTIC_ALGORITHMS) + ) + + self.guards.add(GlobalStateSource().make_guard(GuardBuilder.GRAD_MODE)) + + self.guards.add(GlobalStateSource().make_guard(GuardBuilder.DEFAULT_DEVICE)) + + self.guards.add(GlobalStateSource().make_guard(GuardBuilder.GLOBAL_STATE)) + self.guards.add( + GlobalStateSource().make_guard(GuardBuilder.TORCH_FUNCTION_STATE) + ) + + ci = torch._C._functorch.peek_interpreter_stack() + if ci is not None: + self.guards.add( + GlobalStateSource().make_guard(GuardBuilder.FUNCTORCH_STACK_MATCH) + ) + if not torch._dynamo.compiled_autograd.in_compiled_autograd_region: + self.guards.add( + GlobalStateSource().make_guard( + GuardBuilder.AUTOGRAD_SAVED_TENSORS_HOOKS + ) + ) + + def maybe_install_saved_tensors_hooks_subgraphs(self) -> list[str] | None: + if torch._dynamo.compiled_autograd.in_compiled_autograd_region: + return None + + get_hooks = torch._functorch._aot_autograd.utils.top_saved_tensors_hooks + are_inline_hooks = ( + torch._functorch._aot_autograd.utils.saved_tensors_hooks_are_inlineable + ) + hooks = get_hooks() + if not are_inline_hooks(hooks): + return None + + # If GraphModule provided by user contains fx.wrap, + # We can only rely on user provided cache hash in this case. + # If user did not provide cache hash - then we always bypass cache. + + pack_gm, unpack_gm = hooks + pack_subgraph_name = self.install_subgraph( + "saved_tensors_hooks_pack", + torch.fx.GraphModule(self.nn_modules, pack_gm.graph), + ) + unpack_subgraph_name = self.install_subgraph( + "saved_tensors_hooks_unpack", + torch.fx.GraphModule(self.nn_modules, unpack_gm.graph), + ) + if pack_subgraph_name != "saved_tensors_hooks_pack_0": + raise AssertionError( + f"Expected pack_subgraph_name to be 'saved_tensors_hooks_pack_0', got '{pack_subgraph_name}'" + ) + if unpack_subgraph_name != "saved_tensors_hooks_unpack_0": + raise AssertionError( + f"Expected unpack_subgraph_name to be 'saved_tensors_hooks_unpack_0', got '{unpack_subgraph_name}'" + ) + return [pack_subgraph_name, unpack_subgraph_name] + + def synthetic_graph_input( + self, + fn: Callable[..., Any], + args: tuple[Any, ...], + ctor_arg_sources: tuple[Source | None, ...] | None = None, + ) -> VariableTracker: + """ + call fn(*args) before the graph runs and turn the result into a fake input. + """ + example_value = fn(*args) + varname = self.new_var() + cg = PyCodegen(self.root_tx) + cg.add_push_null( + lambda: cg.load_import_from( + fn.__module__, + fn.__name__, + ) + ) + if ctor_arg_sources: + cg.foreach( + src if src is not None else variables.ConstantVariable.create(val) + for val, src in zip(args, ctor_arg_sources) + ) + else: + cg.foreach(map(variables.ConstantVariable.create, args)) + cg.call_function(len(args), False) + cg.store(varname) + self.pregraph_bytecode.extend(cg.get_instructions()) + source = SyntheticLocalSource(varname) + self.synthetic_source_ctor_info[source] = (fn, args, ctor_arg_sources) + result = VariableTracker.build(self.root_tx, example_value, source) + # Realize the VT because we will delete the guards on it in the next line. + result = result.realize() + TracingContext.get().guards_context.dynamo_guards.remove_guards_with_source( + source + ) + return result + + def add_cleanup_hook(self, fn: Callable[[], Any]) -> None: + self.cleanup_hooks.append(fn) + + def call_cleanup_hooks(self) -> None: + for hook in reversed(self.cleanup_hooks): + hook() + self.cleanup_hooks.clear() + + @property + def root_tracer(self) -> "SubgraphTracer": + return self.tracers[0] + + @property + def current_tracer(self) -> "SubgraphTracer": + return self.tracers[-1] + + def is_root_tracer(self) -> bool: + # Helper to tell if we are inside the higher order operator tracing. + return len(self.tracers) == 1 + + def check_input_mutation_on_current_stream( + self, tx: "InstructionTranslatorBase" + ) -> None: + """Record which stream index has input mutations by comparing current + tensor versions against the versions captured at graph input creation.""" + if not hasattr(tx, "symbolic_stream_state"): + return + if not tx.symbolic_stream_state.in_stream_context(): + return + + tracer = self.root_tracer + if self._last_checked_input_versions is None: + self._last_checked_input_versions = dict( + enumerate(tracer._input_versions_at_beginning) + ) + + cur_stream_index = tx.symbolic_stream_state.cur_stream_id() + input_idx = 0 + for node in tracer.graph.nodes: + if node.op != "placeholder": + break + example_value = node.meta.get("example_value") + if not isinstance(example_value, torch.Tensor): + continue + prev_version = self._last_checked_input_versions.get(input_idx) + cur_version = example_value._version + if prev_version is not None and cur_version > prev_version: + if cur_stream_index not in self._input_mutation_streams: + self._input_mutation_streams[cur_stream_index] = ( + TracingContext.extract_stack() + ) + self._last_checked_input_versions[input_idx] = cur_version + input_idx += 1 + + _EVENT_INPUT_MUTATION_FIX = ( + "To fix this, either:\n" + " 1. Move the input mutation after the event.record() call.\n" + " 2. Record the event outside the compiled region:\n" + " compiled_fn(x)\n" + " event.record(stream) # after torch.compile returns\n" + " 3. Insert a graph break before recording:\n" + " torch._dynamo.graph_break()\n" + " event.record(stream)\n" + " 4. Record the event on a stream that has no input mutations." + ) + + def check_event_record_after_input_mutation(self, stream_index: int) -> None: + """Error if an event is being recorded on a stream that already has + an input mutation. Called at record time so ordering is naturally + respected — records before mutations won't trigger this.""" + if stream_index not in self._input_mutation_streams: + return + + mutation_stack = self._input_mutation_streams[stream_index] + record_stack = TracingContext.extract_stack() + + msg = ( + "An event was recorded on a stream where a graph input was " + "previously mutated. The input mutation is applied via copy_() " + "in the runtime epilogue after the graph executes, so the event " + "would not capture the mutation, leading to incorrect " + "synchronization.\n\n" + "Input mutation occurred here:\n" + f"{''.join(mutation_stack.format())}\n" + "Event record occurred here:\n" + f"{''.join(record_stack.format())}\n" + self._EVENT_INPUT_MUTATION_FIX + ) + raise RuntimeError(msg) + + @property + def graph(self) -> torch.fx.Graph: + return self.current_tracer.graph + + # TODO(rzou): can delete after we refactor speculate_subgraph to use nested GraphTracer. + @graph.setter + def graph(self, value: torch.fx.Graph) -> None: + self.current_tracer.graph = value + + @property + def input_name_to_proxy(self) -> dict[str, fx.Proxy]: + return self.current_tracer.input_name_to_proxy + + @property + def real_value_cache(self) -> dict[fx.Node, torch.Tensor]: + return self.current_tracer.real_value_cache + + @property + def bound_symbols(self) -> dict[sympy.Symbol, Union[torch.fx.Proxy, "LazyProxy"]]: + return self.current_tracer.bound_symbols + + # If you are here, and you're looking for create_graph_input, + # to avoid ambiguity, please call one of the following: + # - self.current_tracer.create_graph_input + # - self.root_tracer.create_graph_input + # See NOTE [HigherOrderOperator tracing design] for more context. + + def create_proxy(self, *args: Any, **kwargs: Any) -> torch.fx.Proxy: + return self.current_tracer.create_proxy(*args, **kwargs) + + def create_node(self, *args: Any, **kwargs: Any) -> torch.fx.Node: + return self.current_tracer.create_node(*args, **kwargs) + + def remove_node(self, *args: Any, **kwargs: Any) -> None: + return self.current_tracer.remove_node(*args, **kwargs) + + @contextlib.contextmanager + def subtracer( + self, + source_target: Target | None, + prior_tracer: Optional["SubgraphTracer"], + description: str | None = None, + ) -> Generator["SubgraphTracer", None, None]: + new_scope_ctx = enter_new_scope() + try: + if prior_tracer: + # Lineage MUST stay preserved + if prior_tracer.parent is not self.current_tracer: + raise AssertionError( + "prior_tracer.parent must be the current tracer to preserve lineage" + ) + new_scope_ctx.__enter__() + tracer = ( + prior_tracer + if prior_tracer + else SubgraphTracer( + self, + parent=self.current_tracer, + source_target=source_target, + is_export=self.current_tracer.is_export, + description=description, + ) + ) + self.tracers.append(tracer) + yield tracer + finally: + new_scope_ctx.__exit__(None, None, None) + self.tracers.pop() + + @property + def output(self) -> "OutputGraph": + return self + + @property + def fake_mode(self) -> torch._subclasses.FakeTensorMode: + if self.tracing_context.fake_mode is None: + raise AssertionError("tracing_context.fake_mode must not be None") + return self.tracing_context.fake_mode + + @property + def shape_env(self) -> ShapeEnv: + if self.tracing_context.fake_mode is None: + raise AssertionError("tracing_context.fake_mode must not be None") + if self.tracing_context.fake_mode.shape_env is None: + raise AssertionError("tracing_context.fake_mode.shape_env must not be None") + return self.tracing_context.fake_mode.shape_env + + @property + def guards(self) -> torch._guards.GuardsSet: + return self.tracing_context.guards_context.dynamo_guards + + @property + def nn_modules(self) -> dict[str, Any]: + return self.tracing_context.module_context.nn_modules + + @property + def aotautograd_guards(self) -> list[torch._guards.GuardEnvExpr]: + return self.tracing_context.guards_context.aotautograd_guards + + def save_global_state( + self, out: dict[str, tuple[Callable[..., Any], bool]] | None = None + ) -> None: + """ + Saves to out if it is provided. Else saves to the tracing context's global_state. + """ + global_state = cast( + dict[str, tuple[Callable[..., Any], bool]], + ( + out + if out is not None + else self.tracing_context.global_context.global_state + ), + ) + + global_state["grad_enabled"] = (torch.set_grad_enabled, torch.is_grad_enabled()) + + gpu_type = ( + acc.type if (acc := torch.accelerator.current_accelerator()) else "cuda" + ) + global_state["autocast_enabled"] = ( + functools.partial(torch.set_autocast_enabled, gpu_type), + torch.is_autocast_enabled(gpu_type), + ) + global_state["autocast_cpu_enabled"] = ( + functools.partial(torch.set_autocast_enabled, "cpu"), + torch.is_autocast_enabled("cpu"), + ) + global_state["autocast_gpu_dtype"] = ( # type:ignore[assignment] + functools.partial(torch.set_autocast_dtype, gpu_type), + torch.get_autocast_dtype(gpu_type), + ) + global_state["autocast_cpu_dtype"] = ( # type:ignore[assignment] + functools.partial(torch.set_autocast_dtype, "cpu"), + torch.get_autocast_dtype("cpu"), + ) + global_state["autocast_cache_enabled"] = ( + torch.set_autocast_cache_enabled, + torch.is_autocast_cache_enabled(), + ) + + def push_tx(self, tx: "InstructionTranslatorBase") -> None: + self._current_tx.append(tx) + + def pop_tx(self) -> "InstructionTranslatorBase": + return self._current_tx.pop() + + @property + def current_tx(self) -> "InstructionTranslatorBase": + return self.root_tx if not self._current_tx else self._current_tx[-1] + + def resolve_source_value(self, source: Source) -> Any: + """ + Resolve the runtime value a Source points to using root_tx's frame. + + Useful to inspect the python object associated with the source during + debugging. Will also be used by invoke subgraph caching later on. + """ + return source.get_value( + {"G": self.root_tx.f_globals, "L": self.root_tx.f_locals}, + {}, + {}, # type: ignore[arg-type] + ) + + def count_calls(self) -> int: + return count_calls(self.graph) + + def is_empty_graph(self) -> bool: + return len(list(self.graph.nodes)) == 0 + + def has_outputs(self) -> bool: + return len([x for x in self.graph.nodes if x.op == "output"]) > 0 + + def get_submodule(self, keys: str) -> torch.nn.Module | Any: + if not keys: + raise AssertionError("keys must be a non-empty string") + obj: torch.nn.Module | dict[str, torch.nn.Module] = self.nn_modules + for k in keys.split("."): + if isinstance(obj, dict): + obj = obj[k] + else: + obj = getattr(obj, k) + return obj + + def new_var(self, name: str = "tmp") -> str: + existing = set(self.code_options["co_varnames"]) + # In common case, this will be O(1) + while True: + var = f"{name}_{next(self.unique_var_id)}" + if var not in existing: + self.code_options["co_varnames"] += (var,) + return var + + def update_co_names(self, name: str) -> None: + """Ensure self.code_options.co_names contains name""" + if name not in self.code_options["co_names"]: + self.code_options["co_names"] += (name,) + + @staticmethod + def module_key_name(*names: Any) -> str: + # create a new unique name + name = "_".join(map(str, names)) + # Strip _buffers[..]/_parameters[..]/_modules[..] names + name = re.sub( + r"\._(?:modules|parameters|buffers)\[(['\"])([^'\"\]]+)\1\]", r".\2", name + ) + # Replace getattr(a, b) with a.b + name = re.sub( + r"getattr\(\s*([^,]+?)\s*,\s*(['\"])([^'\"]+)\2\s*\)", r"\1.\3", name + ) + # Strip the guard lookup L/G access + name = re.sub(r"^[GL]\['?(.*?)'?\]$", r"\1", name) + # e.g. replace abc.xyz[123].qkv with abc.xyz_123.qkv + name = re.sub(r"\[(\d+)\]", r"_\g<1>", name) + # e.g. replace abc.xyz_123.qkv with abc_xyz_123_qkv + name = re.sub(r"[^a-zA-Z0-9]", "_", name) + + if not name or not name[0].isalpha(): + name = "sub" + name + + return name + + def register_static_attr_and_return_proxy( + self, attr_prefix: str, attr_value: Any + ) -> fx.Proxy: + # Check if the module already exists, if it does, return the already + # added proxy. This is important for executorch tests. + if isinstance(attr_value, torch.nn.Module): + for name, mod in self.nn_modules.items(): + if mod is attr_value: + proxy = self.create_proxy("get_attr", name, (), {}) + return proxy + + attr_name = get_unique_name_wrt(attr_prefix, self.nn_modules) + # TODO `nn_modules` has been historically overloaded to store a lot more + # than just nn module objects, fix that. + self.nn_modules[attr_name] = attr_value + proxy = self.create_proxy("get_attr", attr_name, (), {}) + set_example_value(proxy.node, attr_value) + return proxy + + def register_attr_or_module( + self, + target: torch.nn.Module | torch.Tensor | Any, + *names: Any, + **options: Any, + ) -> VariableTracker: + if is_dynamic_nn_module(target, self.export): + # Instead of returning UnspecializedNNModuleVariable, call + # VariableTracker.build so that it is tracked for mutation. + return VariableTracker.build(self.current_tx, target, **options) + + options = dict(options) + if "source" not in options: + raise AssertionError("'source' must be provided in options") + source = options["source"] + if isinstance(source, ParamBufferSource): + raise AssertionError( + f"source must not be a ParamBufferSource, got {source}" + ) + + if isinstance(target, torch.Tensor): + tracer = self.current_tracer + if not self.is_root_tracer(): + # For higher order ops, we don't want to insert the get_attr in + # innermost graph. Instead, we want to raise the params/buffers + # as inputs to the higher-order graph, and register them as + # get_attrs in the root tracer. + + # Note that Dynamo will still call lift_tracked_freevar_to_input + # when these inputs are encountered for the inner graph. The + # only difference is what happens at the root tracer for + # nn.Parameters vs free inputs. The free inputs are registered + # as placeholders in the root graph, whereas the nn.Parameters + # are registered as get_attr nodes in the root graph. + tracer = self.root_tracer + + def wrap_name(module_key: str) -> VariableTracker: + if self.param_name_to_source is None: + raise AssertionError("param_name_to_source must not be None") + self.param_name_to_source[module_key] = source + + # Check if the attr has already been registered. This can happen + # when two different sources point to the same tensor. + if self.root_tx is None: + raise AssertionError("root_tx must not be None") + if target in self.root_tx.output.side_effects: + return self.root_tx.output.side_effects[target] + + if get_static_address_type(target) == "guarded" and not isinstance( + source, NumpyTensorSource + ): + install_guard(source.make_guard(GuardBuilder.ID_MATCH)) + elif not is_constant_source(source): + install_guard(source.make_guard(GuardBuilder.TENSOR_MATCH)) + + vt = wrap_fx_proxy( + self.root_tx, + tracer.create_proxy("get_attr", module_key, (), {}), + example_value=target, + **options, + ) + + # Track the object so to avoid duplicate registration in case of + # different sources pointing to the same tensor object. + vt = self.root_tx.output.side_effects.track_object_existing(target, vt) + + if "tensor_dict" in vt.as_proxy().node.meta: + raise AssertionError( + "'tensor_dict' already exists in proxy node meta" + ) + # pyrefly: ignore [bad-argument-type] + vt.as_proxy().node.meta["tensor_dict"] = _extract_tensor_dict(target) + + return vt + + elif isinstance(target, torch.nn.Module): + if not isinstance(target, torch.nn.Module): + raise AssertionError( + f"target must be a torch.nn.Module, got {type(target)}" + ) + + if source: + install_guard(source.make_guard(GuardBuilder.NN_MODULE)) + + def wrap_name(module_key: str) -> VariableTracker: + # pyrefly: ignore [bad-argument-type] + return NNModuleVariable(type(target), module_key, target, **options) + + else: + # This is Dynamo created graph module, e.g., graph module coming + # from higher order ops. NNModuleVariable tracker can't be + # sourceless, so let's return a unspecializedNNModule variable + # tracker. + def wrap_name(module_key: str) -> VariableTracker: + # pyrefly: ignore[bad-argument-type] + return variables.UnspecializedNNModuleVariable(target, **options) + + elif isinstance(target, (torch.SymInt, torch.SymFloat)): + # HACKY CODE REGION BEGIN + # WE ARE PIGGYBACKING ON EXISTING INFRA TO REGISTER ATTRS + # This ultimately gets written to self.nn_modules, which is unfortunate + # Attrs that are tensors and symints and such need to be migrated to have their + # own storage + # alas, this is like this for now + + def wrap_name(module_key: str) -> VariableTracker: + return SymNodeVariable.create( + self.root_tx, + self.create_proxy("get_attr", module_key, (), {}), + sym_num=target, + **options, + ) + + # HACKY CODE REGION END + elif is_custom_class(type(target)): + # HACKY CODE REGION BEGIN + # Same as SymInt/SymFloat above: piggybacking on self.nn_modules + # to store opaque objects as graph attributes. + + tracer = self.current_tracer + if not self.is_root_tracer(): + tracer = self.root_tracer + + def wrap_name(module_key: str) -> VariableTracker: + fake_script_obj = torch._library.fake_class_registry.maybe_to_fake_obj( + self.fake_mode, target + ) + proxy = tracer.create_proxy("get_attr", module_key, (), {}) + set_example_value(proxy.node, fake_script_obj) + return torch._dynamo.variables.script_object.CustomClassObjectVariable.create( + proxy, fake_script_obj, tx=self.root_tx, **options + ) + + # HACKY CODE REGION END + + else: + + def wrap_name(module_key: str) -> VariableTracker: + self.output.update_co_names(module_key) + self.global_scope[module_key] = target + return VariableTracker.build( + self, # type: ignore[arg-type] + target, + ConstantSource(source_name=module_key), + ) + + for k, v in self.nn_modules.items(): + if v is target: + # it already exists + return wrap_name(k) + + name = OutputGraph.module_key_name(*names) + name = get_unique_name_wrt(name, self.nn_modules, self.global_scope) + self.nn_modules[name] = target + if isinstance(target, torch.nn.Module): + + def register_leaf_name(leaf_name: str) -> None: + if self.param_name_to_source is None: + raise AssertionError("param_name_to_source must not be None") + new_source = self.get_chained_param_buffer_source(source, leaf_name) + new_name = f"{name}.{leaf_name}" + self.param_name_to_source[new_name] = new_source + if isinstance(source, LocalSource): + self.dynamo_flat_name_to_original_fqn[ + OutputGraph.module_key_name(new_source.name) + ] = leaf_name + + # annoying, but there are cases when we do not have parameters + # see test_nn_moduledict_contains + if hasattr(target, "_parameters"): + for leaf_name, _ in target.named_parameters(): + register_leaf_name(leaf_name) + if hasattr(target, "_buffers"): + for leaf_name, _ in target.named_buffers(): + register_leaf_name(leaf_name) + + return wrap_name(name) + + def handle_aliases_for_stolen_lists( + self, tx: "InstructionTranslatorBase" + ) -> tuple[list[Instruction], dict[Source, Source]]: + # If list inputs are stolen, but still needed after the function call, create aliases to keep them alive + maybe_gm = self.local_scope.get("self") + stolen_list_names = get_locals_to_steal(maybe_gm) + if not stolen_list_names: + return [], {} + + alias_insts = [] + needs_alias: dict[str, list[VariableTracker]] = {} + + queue = [ + *tx.stack, + *tx.symbolic_locals.values(), + *self.side_effects.store_attr_mutations.keys(), + ] + + while queue: + x = queue.pop() + if isinstance(x, BaseListVariable): + if not isinstance(x.items, list): + raise AssertionError(f"x.items must be a list, got {type(x.items)}") + queue += x.items + continue + + if not ( + ( + x not in self.side_effects.store_attr_mutations + or isinstance(x.mutation_type, AttributeMutationExisting) + ) + and isinstance(x.source, GetItemSource) + and isinstance(x.source.base, LocalSource) + and x.source.base.local_name in stolen_list_names + ): + continue + + stolen_name = x.source.base.local_name + if stolen_name not in needs_alias: + needs_alias[stolen_name] = [] + needs_alias[stolen_name].append(x) + + # pyrefly: ignore [implicit-any] + visited = {} + overridden_sources: dict[Source, Source] = {} + for arg in self.graphargs: + if not ( + isinstance(arg._example, list) + and isinstance(arg.source, LocalSource) + and arg.source.local_name in needs_alias + ): + continue + + # arg is a list that will be cleared by the compiled function + list_name = arg.source.local_name + if list_name not in self.code_options["co_varnames"]: + raise AssertionError(f"'{list_name}' not found in co_varnames") + for x in needs_alias[list_name]: + # Skip if already handled. + if x.source in overridden_sources: + continue + + # A small codegen optimization because we might have different + # VariableTrackers that share the same source. + if x.source is None: + raise AssertionError("x.source must not be None") + list_idx = x.source.index # type: ignore[attr-defined] + if list_idx not in visited: + alias_name = self.new_var( + f"{list_name}_ref" + ) # self.new_var already adds unique id suffix + + visited[list_idx] = alias_name + # bytecode of `alias_name = list_name[list_idx]` + alias_insts.extend( + [ + create_instruction("LOAD_FAST", argval=list_name), + create_load_const(list_idx), + create_binary_subscr(), + create_instruction("STORE_FAST", argval=alias_name), + ] + ) + + # operate on alias, handled by suffix codegen + if x.source is None: + raise AssertionError("x.source must not be None") + old_source = x.source + overridden_sources[old_source] = LocalSource(visited[list_idx]) + + # NOTE: we need `overridden_sources` because (1) we want to codegen for + # these list items to use the new local source, but (2) we want to avoid + # updating `source` in place because that might break invariants in + # other parts of Dynamo like guards. + return alias_insts, overridden_sources + + def _get_stack_values_to_restore( + self, tx: "InstructionTranslatorBase", stack_pops: int + ) -> tuple[list[VariableTracker], StackLocalsMetadata]: + """ + Gets the stack + locals values belonging to tx that need to be restored. + + Also prunes dead tx locals and realizes all VTs in the tx's stack. + + NullVariables in stack/locals will NOT be restored, unless they are the top `stack_pops` + elements of the stack - it is expected that the next instruction to run will pop the top + `stack_pops` elements of the stack, so we should codegen NULLs. + + Returns: + - stack_values: stack and locals values that need to be restored + - meta: locations of NULLs and ContextWrappingVariables in the stack/locals + (ignores the top `stack_pops` values on the stack) + """ + tx.prune_dead_locals() + + stack_values = [] + meta = StackLocalsMetadata() + + def ctx_exit_check(var: VariableTracker) -> None: + if type.__instancecheck__(variables.WithExitFunctionVariable, var): + raise AssertionError( + "Attempted to reconstruct WithExitFunctionVariable outside the stack" + ) + + # realize any unrealized tensor VTs in case they + # need to be added to self.nn_modules as attributes + for i, value in enumerate(tx.stack): + # Allow lazy constants through for values being returned (top of stack) + allow_lazy_constant = len(tx.stack) - i <= stack_pops + variables.LazyVariableTracker.realize_all( + value, allow_lazy_constant=allow_lazy_constant + ) + # Do not allow non-stack WithExitFunctionVariable reconstructions + if not isinstance(value, variables.WithExitFunctionVariable): + VariableTracker.visit(ctx_exit_check, value) + # ignore top `stack_pops` values on the stack + if allow_lazy_constant: + stack_values.append(value) + continue + if isinstance(value, NullVariable): + meta.stack_null_idxes.append(i) + else: + stack_values.append(value) + if isinstance(value, ContextWrappingVariable): + target_values = ( + () if value.target_values is None else tuple(value.target_values) + ) + # NOTE: track index in stack after NULLs have been removed + meta.stack_ctx_args.append((len(stack_values) - 1, target_values)) + meta.stack_ctx_idxes_orig.append(i) + + meta.num_stack = len(stack_values) + + # Cells are codegen'd by codegen_cells from the symbolic_cellvars + # registry. A symbolic_locals entry whose name is also a cell/free var + # is either the cell itself (shared slot) or a colliding fast local + # (e.g. an inlined comprehension iteration variable shadowing a + # nonlocal); both are skipped here, consistent with resume argname + # generation in create_call_resume_at. + cell_and_freevars = set(tx.cellvars() + tx.freevars()) + + # NB: Typically (i.e., for graph compile from RETURN_VALUE), + # symbolic_locals will be empty at this point, as prune_dead_locals + # will clear out all of symbolic_locals because RETURN_VALUE is the + # last instruction and no more locals are used. The fanciness here + # is only needed for partial graphs. + # NOTE: All cell and free variables are represented as CellVariable, + # so checks for NULLs and context managers in the case of codegen'ing resume + # functions will not be performed on them. This is expected behavior. + for k, v in tx.symbolic_locals.items(): + # Do not reconstruct WithExitFunctionVariable! + VariableTracker.visit(ctx_exit_check, v) + # Note! this explicitly uses .local_name for matching + # Failure to do so will cause spurious registrations in val_to_names. + # This will in turn result in spurious variables showing up in the graph. + # This was very tricky to debug. For an example, dump the graph at call_user_compiler + # while running test_subgraphs.py + # Do not include top-frame unmodified locals here - otherwise, the compiled graph may + # erroneously include them as part of the return. We manually codegen them afterward. + if ( + isinstance(v.source, LocalSource) + and v.source.local_name == k + and tx is self.root_tx + ): + continue + # Do not load cell/free vars (real cells are handled by + # codegen_cells; a colliding fast local sharing a cell's name is + # skipped to match resume argname generation). + if k in cell_and_freevars: + continue + # Do not load variable if it is NULL. + if sys.version_info >= (3, 12): + # NOTE: do not use isinstance, since it realizes lazy VT's + # Continuation function will load the NULL for v. + if type.__instancecheck__(NullVariable, v): + meta.locals_null_keys.append(k) + continue + else: + # A variable should never be NULL in < 3.12 + if type.__instancecheck__(NullVariable, v): + raise AssertionError( + "variable should never be NULL in Python < 3.12" + ) + meta.locals_names[k] = len(meta.locals_names) + if isinstance(v, ContextWrappingVariable): + target_values = ( + () if v.target_values is None else tuple(v.target_values) + ) + meta.locals_ctx_args.append((k, target_values)) + stack_values.append(v) + + return stack_values, meta + + def compile_subgraph( + self, + tx: "InstructionTranslatorBase", + reason: GraphCompileReason, + stack_pops: int = 0, + ) -> list[StackLocalsMetadata]: + """ + Compiles the current subgraph, with inputs w.r.t. self.root_tx, and codegens: + - Call the compiled subgraph + - Apply side effects + - Codegen stack and locals + - Store the locals + + Python does not allow NULL to be an arg to a function, so we do not codegen NULLs on the stack, + unless the value is one of the top `stack_pops` values on the stack (these values are expected to be + popped immediately after this generated code. The prologue of the resume function is expected to restore + any dropped NULLs. + + Returns stack indices and locals keys where we dropped NULLs, and where we found inactive context manager objects. + """ + + if self.root_tx is None: + raise AssertionError("root_tx must not be None") + + # Finalize shapes_spec wiring: errors if any spec assumption/derived + # check still has unbound IntVar dependencies (i.e. an IntVar + # appears in an expression but never as a bare-IntVar input slot). + if config._dynamic_shapes_spec is not None: + from torch.fx.experimental.symbolic_shapes import _finalize_spec_wiring + + _finalize_spec_wiring(self.shape_env) + + if not config.nested_graph_breaks: + # expect to only compile 1 frame + if self.root_tx is not tx: + raise AssertionError( + "root_tx must be tx when nested_graph_breaks is disabled" + ) + + # bytecode tracing has finished. Pop the context manager for dynamo_timed + self.mark_bytecode_tracing_stop() + + self.compile_subgraph_reason = reason + self.should_exit = True + + log.debug("COMPILING GRAPH due to %s", reason) + + # prefix instructions (Python 3.11+) + prefix_insts: list[Instruction] = [] + if sys.version_info >= (3, 11): + for inst in self.root_tx.prefix_insts: + if inst.opname == "COPY_FREE_VARS": + prefix_insts.append( + create_instruction( + "COPY_FREE_VARS", + arg=len(self.root_tx.code_options["co_freevars"]), + ) + ) + else: + inst_copy = copy.copy(inst) + # Prefix instructions are copied without the original + # exception table range; generated bytecode owns a new body. + inst_copy.exn_tab_entry = None + prefix_insts.append(inst_copy) + + # stack values and restore vars for each frame are pushed in reverse order + # i.e. last element corresponds to root frame (1), + # first element corresponds to current frame (N) + all_stack_values = [] + # pyrefly: ignore [implicit-any] + all_stack_locals_metas = [] + cur_tx: InstructionTranslatorBase | None = tx + while cur_tx is not None: + # this should have been checked by the caller + if not all(block.can_restore() for block in cur_tx.block_stack): + raise AssertionError( + "all blocks in cur_tx.block_stack must be restorable" + ) + + stack_values, meta = self._get_stack_values_to_restore( + cur_tx, stack_pops if cur_tx is tx else 0 + ) + all_stack_values.append(stack_values) + all_stack_locals_metas.append(meta) + + # Exit from all context manager variables to make sure global state is restored + for block in reversed(cur_tx.block_stack): + block.exit(cur_tx, is_graph_break=reason.graph_break) + + cur_tx = cur_tx.parent + + # "Garbage collect the heap". + self.side_effects.prune_dead_object_new(tx) + + self.add_output_instructions(prefix_insts) + + if self._emit_debugger_breakpoint: + from .bytecode_transformation import create_breakpoint + + self.add_output_instructions(create_breakpoint()) + self._emit_debugger_breakpoint = False + + if self.pregraph_bytecode and self.export: + raise AssertionError("export does not support pregraph_bytecode") + self.add_output_instructions(self.pregraph_bytecode) + + alias_insts, overridden_sources = self.handle_aliases_for_stolen_lists( + self.root_tx + ) + self.add_output_instructions(alias_insts) + + self.cleanup_graph() + + # Use nn.Module "proxies" in the constructed GraphModule so that + # the resulting GM does not hold additional strong references to the original modules. + # This prevents a strong ref cycle where Dynamo created code holds on to references + # to modules that also have Dynamo code cache invalidation checks. + # When cache invalidation runs, the generated GM will be invalidated, which also deletes + # the proxies. + nn_modules_proxies = { + name: nn_module_proxy(mod) for name, mod in self.nn_modules.items() + } + root = FakeRootModule(nn_modules_proxies) + + from .decorators import disable + + # to handle random calls + if len(self.random_calls) > 0: + random_calls_instructions = [] + self.random_values_var = self.new_var("random_values") + rand_fn = disable( + _get_gen_rand_values_fn(self.random_calls), + reason="do not trace into Dynamo rng recovery function", + ) + rand_fn_name = self.install_global("__gen_rand_values", rand_fn) + codegen = PyCodegen( + self.root_tx, root, overridden_sources=overridden_sources + ) + random_calls_instructions.extend( + codegen.load_function_name(rand_fn_name, True) + ) + random_calls_instructions.extend(create_call_function(0, False)) + random_calls_instructions.append( + codegen.create_store(self.random_values_var), + ) + self.add_output_instructions(random_calls_instructions) + + # Codegen stack convention before the unsupported instruction + # NOTE: in these comment blocks, "locals" EXCLUDE free and cell vars. + # NOTE: stack/locals/cells must be codegen'd BEFORE the unsupported instruction, since the latter + # can arbitrarily mutate the former. + # [frame N cells, .., frame 1 cells], + # [ + # frame N locals, + # frame N-1 stack + locals, + # ..., + # frame 1 stack + locals, + # ], frame N stack + + # see symbolic_convert.py for + # codegen stack convention after the unsupported instruction + # NOTE: cells will be loaded into continuation functions directly by symbolic_convert + + # this determines the order that values are codegen'd to the stack + stack_values_flat = [val for vals in all_stack_values for val in vals] + stored_graph_output_var = False + graph_output_var = None + + # call compiled fx graph and codegen all values - stack and locals + can_use_fast_path = ( + self.root_tx is tx # single frame + and stack_values_flat + and all( + not isinstance( + v, + ( + UnspecializedPythonVariable, + NumpyNdarrayVariable, + TensorWithTFOverrideVariable, + ), + ) + and not (isinstance(v, SymNodeVariable) and v.python_type() is float) + for v in stack_values_flat + ) + and all(x.is_tensor() for x in stack_values_flat) + and len(set(stack_values_flat)) == len(stack_values_flat) + and self.side_effects.is_empty() + and not tx.debug_locals + and not self.backward_state + and not all_stack_locals_metas[-1].stack_null_idxes + and not all_stack_locals_metas[-1].locals_null_keys + ) + + # Generators that don't escape the frame must still have their finally + # blocks run at frame exit (CPython does this via tp_finalize on GC). + if can_use_fast_path and self.local_generators: + self.close_local_generators(tx) + can_use_fast_path = self.side_effects.is_empty() + + if can_use_fast_path: + # optimization to generate better code in a common case + + # codegen cells + # no side effects, so no new cells created - no need to call side_effects.codegen_save_tempvars + cell_cg = PyCodegen(self.root_tx) + self.codegen_cells(tx, cell_cg) + instructions, pycode = self.compile_and_call_fx_graph( + tx, list(reversed(stack_values_flat)), root + ) + self.add_output_instructions( + [ + # load in reverse since UNPACK_SEQUENCE will reverse + *instructions, + *cell_cg.get_instructions(), + *create_swap(2), + create_instruction("UNPACK_SEQUENCE", arg=len(stack_values_flat)), + ], + pycode=pycode, + ) + # function output will be moved to the correct places below + else: + graph_output_var = self.new_var("graph_out") + # load stack values in a flat manner - we will codegen bytecode to place them correctly + # according to our convention above + pass1 = PyCodegen( + self.root_tx, + root, + graph_output_var, + overridden_sources=overridden_sources, + ) + self.codegen_suffix(tx, stack_values_flat, pass1, False) + + # Close all generators opened while tracing. Needs to be done after + # pass1, as PyCodegen might try to reconstruct the generator, which + # sets LocalGeneratorObjectVariable.remaining_items + self.close_local_generators(tx) + + # Use `pass1.uses` to selectively cache multi-user variables into a + # temporary local source. This (a). speeds up loading VTs with long + # chained source, and (b). avoids redundantly saving single-user VT + # into a temporary local. + tempvars = {} # type: ignore[var-annotated] + for val, count in pass1.uses.items(): + # If it's already a local source, no need to cache it + if count > 1 and not istype(val, (SyntheticLocalSource, LocalSource)): + tempvars[val] = None + pass2 = PyCodegen( + self.root_tx, + root, + graph_output_var, + tempvars=tempvars, + overridden_sources=overridden_sources, + ) + self.codegen_suffix(tx, stack_values_flat, pass2, True) + + if ( + torch._dynamo.config.log_graph_in_out_metadata + and stack_values_flat + and len(stack_values_flat) == 1 + ): + vt = stack_values_flat[0] + if ( + isinstance(vt, torch._dynamo.variables.NamedTupleVariable) + and vt.tuple_cls + is torch._dynamo.functional_export.ExportTracerOutput + ): + flat_returns = vt.items[0] + out_spec = vt.items[1] + if not isinstance( + flat_returns, torch._dynamo.variables.ListVariable + ): + raise AssertionError("flat_returns must be a ListVariable") + + vt_to_graph_out_idx: dict[VariableTracker, int] = {} + for value in pass2.graph_outputs.values(): + if not isinstance( + value, torch._dynamo.codegen.GraphOutputEntry + ): + raise AssertionError( + f"graph output value must be a GraphOutputEntry, got {type(value)}" + ) + variable: VariableTracker = value.variable + vt_to_graph_out_idx[variable] = value.index + + output_return_type = self.export_metadata.output_return_type + for idx, vt in enumerate(flat_returns.items): + if vt in vt_to_graph_out_idx: + output_return_type[idx] = OutputReturnInfo( + "graph_out", vt_to_graph_out_idx[vt] + ) + elif ( + vt.source is not None + and (source := getattr(vt.source, "base", None)) # type: ignore[assignment] + and getattr(source, "is_input", False) + ): + output_return_type[idx] = OutputReturnInfo( + "input", vt.source + ) + elif vt.is_python_constant(): + output_return_type[idx] = OutputReturnInfo( + "constant", vt.as_python_constant() + ) + else: + raise AssertionError( + f"Encountered unrecognized type {vt} at output {idx}" + ) + try: + self.export_metadata.out_spec = out_spec.as_python_constant() + except ClosureConversionError as e: + unimplemented( + gb_type="nested function with non-constructible closure in output", + context=f"as_python_constant for out_spec {out_spec}", + explanation=( + "Cannot return a nested function with closure from a compiled function. " + "Dynamo failed to construct the function defined in the compiled region with closure objects." + ), + hints=[ + "Define the function at module scope instead of inside another function ", + "Ensure that all closure variables are constants.", + ], + from_exc=e, + ) + + output = [] + subgraph_pycode = None + if count_calls(self.graph) != 0 or len(pass2.graph_outputs) != 0: + instructions, subgraph_pycode = self.compile_and_call_fx_graph( + tx, pass2.graph_output_vars(), root + ) + output.extend(instructions) + + if len(pass2.graph_outputs) != 0: + output.append(pass2.create_store(graph_output_var)) + stored_graph_output_var = True + else: + output.append(create_instruction("POP_TOP")) + else: + # NB: Important to run compiler collective even when there is + # a graph break + self.run_compiler_collective() + self.add_output_instructions(output, pycode=subgraph_pycode) + self.add_output_instructions( + pass2.get_instructions(), pycode=pass2.get_pycode() + ) + + # store all stack and locals for each frame + # current state of the stack: + # all cells, + # *(frame N stack), *(frame N locals), + # ..., + # *(frame 1 stack), *(frame 1 locals) + + self.add_output_instructions( + [ + create_instruction( + "BUILD_LIST", + arg=len(stack_values_flat) - all_stack_locals_metas[0].num_stack, + ), + ] + ) + + # current state of the stack: + # all cells, + # *(frame N stack), [ + # *(frame N locals), + # *(frame N-1 stack), *(frame N-1 locals), + # ... + # *(frame 1 stack), *(frame 1 locals), + # ] + # iterate current frame (N) to root frame (1) + # sliding window over frame stack/locals + start_idx = 0 + end_idx = 0 + for i, meta in enumerate(all_stack_locals_metas): + # do not pack frame N's stack into the value list + n_vals = len(meta.locals_names) + if i != 0: + n_vals += meta.num_stack + if n_vals == 0: + self.add_output_instructions( + [ + create_instruction("BUILD_LIST", arg=0), + *create_swap(2), + ] + ) + # [], stack_values_flat + else: + end_idx += n_vals + self.add_output_instructions( + [ + create_dup_top(), + *create_binary_slice(start_idx, end_idx), + *create_swap(2), + ] + ) + start_idx += n_vals + # stack_values_flat[x:y], stack_values_flat + + # add root frame's unmodified locals here + if i == len(all_stack_locals_metas) - 1: + root_cg = PyCodegen(self.root_tx) + unmodified_locals_names: dict[str, int] = {} + for k, v in self.root_tx.symbolic_locals.items(): + if isinstance(v.source, LocalSource) and v.source.local_name == k: + root_cg.append_output(root_cg.create_load(k)) + unmodified_locals_names[k] = len(meta.locals_names) + len( + unmodified_locals_names + ) + self.add_output_instructions( + root_cg.get_instructions() + + [ + create_instruction( + "BUILD_LIST", arg=len(unmodified_locals_names) + ), + # arg=2 because we already swapped the locals list back + create_instruction("LIST_EXTEND", arg=2), + ] + ) + meta.locals_names.update(unmodified_locals_names) + + # *(frame N stack), metas[0] stack + locals, ..., metas[i] stack + locals, stack_values_flat + + # current state of the stack: + # all cells, + # *(frame N stack), + # frame N locals, + # frame N-1 stack, frame N-1 locals, + # ... + # frame 1 stack, frame 1 locals, + # stack_values_flat + # + + self.add_output_instructions( + [ + create_instruction("POP_TOP"), + create_instruction("BUILD_LIST", arg=len(all_stack_locals_metas)), + *create_rot_n(all_stack_locals_metas[0].num_stack + 1), + ] + ) + + # final state of the stack before running the unsupported bytecode: + # all cells, + # [ + # [frame N locals], + # [frame N-1 stack + locals], + # ..., + # [frame 1 stack + locals], + # ], *(frame N stack) + + if graph_output_var and stored_graph_output_var: + self.add_output_instructions( + [create_instruction("DELETE_FAST", argval=graph_output_var)] + ) + + if torch._dynamo.config.side_effect_replay_policy in ["warn", "error"]: + side_effect_refs = self.get_replayed_side_effect_source_refs( + populate_export_metadata=True + ) + if side_effect_refs: + if torch._dynamo.config.side_effect_replay_policy == "warn": + warnings.warn( + f"While compiling, we found certain side effects happened in the model.forward. " + f"Here are the list of potential sources you can double check: {side_effect_refs}" + ) + else: + raise RuntimeError( + f"While compiling, we found certain side effects happened in the model.forward. " + f"Here are the list of potential sources you can double check: {side_effect_refs}" + ) + + return all_stack_locals_metas + + def codegen_cells(self, tx: "InstructionTranslatorBase", cg: PyCodegen) -> None: + # no need to codegen if reason.graph_break is False (since we won't resume) + if self.compile_subgraph_reason.graph_break: + tx_cnt = 0 + cur_tx: InstructionTranslatorBase | None = tx + while cur_tx is not None: + # NOTE: we generate cells in the same order as resume_execution.py: sorted freevars + cellvars + # Emitting `LOAD_FAST/LOAD_CLOSURE` with names in `co_freevars` + # requires that in the generated bytecode, these cells would keep + # their original local names, which we ensure via + # `CellVariable.local_name`. + freevars = tuple(sorted(cur_tx.cell_and_freevars())) + for cell in freevars: + if cur_tx is self.root_tx: # root frame + cg.append_output(cg.create_load_closure(cell)) + else: # nested frame + if not cur_tx.post_prune_cell_and_freevars: + raise AssertionError( + "cur_tx.post_prune_cell_and_freevars must be set for nested frames" + ) + var = cur_tx.post_prune_cell_and_freevars[cell] + if isinstance(var, NullVariable): + raise AssertionError("Can't codegen null cell") + cg(var) + cg.append_output(create_build_tuple(len(freevars))) + cur_tx = cur_tx.parent + tx_cnt += 1 + cg.append_output(create_instruction("BUILD_LIST", arg=tx_cnt)) + else: + cg.append_output(create_instruction("BUILD_LIST", arg=0)) + + def codegen_suffix( + self, + tx: "InstructionTranslatorBase", + stack_values: list[VariableTracker], + cg: PyCodegen, + log_side_effects: bool, + ) -> None: + # NOTE: `codegen_save_tempvars` must run first to update `source` fields + # for variables with `AttributeMutationNew`, as they don't implement + # `reconstruct` themselves. + self.side_effects.codegen_save_tempvars(cg) + if self.backward_state: + if self.export: + raise AssertionError("backward_state is not supported in export mode") + for name, val in self.backward_state.items(): + cg(val) + if self.backward_state_var is None: + raise AssertionError( + "backward_state_var must not be None when backward_state is set" + ) + cg.append_output(cg.create_load(self.backward_state_var)) + cg.store_attr(name) + if config.replay_side_effects: + self.side_effects.codegen_hooks(cg) + + # TODO get debug_locals working for nested graph breaks + # Return variables used for logging at the end + for debug_var, args in tx.debug_locals: + cg.add_push_null(lambda: cg(debug_var)) + for arg in args: + cg(arg) + cg.extend_output(create_call_function(len(args), False)) + cg.extend_output([create_instruction("POP_TOP")]) + + # codegen cells before we apply side effects + self.codegen_cells(tx, cg) + + cg.restore_stack(stack_values, value_from_source=not tx.export) + self.side_effects.codegen_update_mutated(cg, log_side_effects) + + def cleanup_graph(self) -> None: + """ + Remove "creation_timestamp" from node meta + + Remove this pattern from the graph: + torch._C._set_grad_enabled(False) + torch._C._set_grad_enabled(True) + """ + if not self.should_exit: + raise AssertionError("should_exit must be True before cleanup_graph") + nodes = list(self.graph.nodes) + for node in nodes: + node.meta.pop("creation_timestamp", None) + + grad_enabled = torch.is_grad_enabled() + for node1, node2 in itertools.pairwise(nodes): + if ( + node1.target is torch._C._set_grad_enabled + and tuple(node1.args) == (not grad_enabled,) + and not node1._erased + ): + grad_enabled = node1.args[0] + if ( + node2.target is torch._C._set_grad_enabled + and tuple(node2.args) == (not grad_enabled,) + and not node2._erased + ): + grad_enabled = node2.args[0] + self.graph.erase_node(node1) + self.graph.erase_node(node2) + + def bypass_package(self, reason: str = "", **kwargs: Any) -> None: + """ + Do not save this output graph to the CompilePackage + """ + if not self.package: + return + if torch._dynamo.config.strict_precompile: + raise torch._dynamo.exc.PackageError( + "Detected a package bypass: %s", reason + ) + log.warning("Detected a package bypass: %s", reason) + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "precompile_cache_bypass", + "encoding": "json", + }, + payload_fn=lambda: { + # precede with underscore so it always appear first in JSON in tlparse + "_reason": reason, + **kwargs, + }, + ) + self.package.bypass_current_entry() + self.package = None + + def get_graph_sizes_structured(self) -> dict[str, list[int | str]]: + ret: dict[str, list[int | str]] = {} + for node in self.graph.nodes: + example_value = node.meta.get("example_value", None) + if torch._subclasses.fake_tensor.is_fake_tensor(example_value): + size = example_value.shape + ret[node.name] = [s if isinstance(s, int) else repr(s) for s in size] + return ret + + def get_graph_sizes(self, name: str) -> str: + graph_sizes_str = "TRACED GRAPH TENSOR SIZES\n" + graph_sizes_str += f"===== {name} =====\n" + for node in self.graph.nodes: + example_value = node.meta.get("example_value", None) + if torch._subclasses.fake_tensor.is_fake_tensor(example_value): + size = example_value.shape + graph_sizes_str += f"{node.name}: {tuple(size)}\n" + concrete_size = [] + has_symint = False + for sz in size: + if isinstance(sz, int): + concrete_size.append(sz) + elif isinstance(sz, torch.SymInt): + has_symint = True + concrete_size.append(sz.node.hint) + else: + break + else: + if has_symint: + graph_sizes_str += ( + f"{node.name} (concrete): {tuple(concrete_size)}\n" + ) + return graph_sizes_str + + @contextlib.contextmanager + def restore_global_state(self) -> Any: + """ + Momentarily restores the global state to what it was prior to tracing the current output + """ + prior_global_state = self.tracing_context.global_context.copy_graphstate() + current_global_state: dict[str, tuple[Any, bool]] = {} + self.save_global_state(out=current_global_state) + try: + # Set to state prior to tracing the graph + self.tracing_context.global_context.restore_graphstate(prior_global_state) + yield + finally: + # Reset to state at the current time (e.g. before calling the user compiler) + self.tracing_context.global_context.restore_graphstate( + GlobalContextCheckpointState(current_global_state) + ) + + def run_compiler_collective(self) -> None: + tx = self.root_tx + if tx is None: + raise AssertionError("root_tx must not be None") + if (ds := tx.distributed_state) is not None and ds.all_states is None: + compile_pg = ds.compile_pg + + log.info("compiler_collective %s", ds.local_state) + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "compiler_collective", + "encoding": "string", + }, + payload_fn=lambda: ds.local_state.render(), + ) + device_types = compile_pg._device_types + if len(device_types) != 1: + raise AssertionError( + "Expect only one device type but got {}".format( + "+".join(device_types) + ) + ) + with ( + get_interface_for_device(device_types.pop()).device( # type: ignore[attr-defined] + compile_pg.rank() % torch.accelerator.device_count() + ), + dynamo_timed("compiler_collective", log_pt2_compile_event=True), + ): + all_states: list[Any] = [None] * compile_pg.size() + + dist.all_gather_object(all_states, ds.local_state, group=compile_pg) + + ds.all_states = all_states + # Clear speculation log, because are tracing may diverge due to + # this information from the compiler collective + tx.speculation_log.clear() + raise exc.CompileCollectiveRestartAnalysis + + def _validate_outputs_safe_for_autograd_nodes( + self, rv: list["VariableTracker"], tx: "InstructionTranslatorBase" + ) -> None: + """ + Validate that if torch.autograd.grad is used in the graph and outputs + require grad, we trigger AutogradGradRestartAnalysis only if the output is connected + to the autograd.grad computation. + + rv here refers to list of variables that are being returned from dynamo graph. + + See Note [Tracing autograd.grad in dynamo] + """ + if not self.autograd_grad_consumed_grad_fns: + return + + from .variables.tensor import TensorVariable + + for var in rv: + if not isinstance(var, TensorVariable) or not var.requires_grad: + continue + + fake_tensor = var.as_proxy().node.meta.get("example_value") + if not torch._subclasses.fake_tensor.is_fake_tensor(fake_tensor): + raise AssertionError( + f"expected example_value to be a FakeTensor, got {type(fake_tensor)}" + ) + if fake_tensor.grad_fn is None: + continue + + # Traverse the entire autograd graph of the returned tensor to check + # if any node was consumed by autograd.grad + reachable_grad_fns = collect_reachable_grad_fns([(fake_tensor, None)]) + if reachable_grad_fns & self.autograd_grad_consumed_grad_fns: + # Record info about the leaked tensor for the error message + tensor_name = str(var.source) if var.source else var.proxy.node.name + tx.speculation_log.autograd_grad_leaked_tensors.append(tensor_name) + + if tx.speculation_log.autograd_grad_leaked_tensors: + # Set the flag to graph break at autograd.grad on retry + tx.speculation_log.graph_break_on_autograd_grad = True + raise exc.AutogradGradRestartAnalysis( + restart_reason="autograd.grad consumed grad_fns of returned tensors" + ) + + def _check_requires_grad_intermediate_outputs( + self, rv: list["VariableTracker"], tx: "InstructionTranslatorBase" + ) -> None: + """Skip frame if a source-less requires_grad_() intermediate leaks as output. + + AOTAutograd's functionalization drops requires_grad_() on intermediates, + so returning them (or tensors derived from them) produces wrong results. + We detect this via FX graph reachability: find the requires_grad_() nodes + for source-less intermediates, then check if any output is downstream. + """ + from .variables.tensor import TensorVariable + + # Collect FX nodes for source-less requires_grad_() intermediates + tainted_nodes: set[torch.fx.Node] = set() + for v in self.leaf_var_creation_order: + if isinstance(v, TensorVariable) and not v.source: + tainted_nodes.add(v.as_proxy().node) + + if not tainted_nodes: + return + + # Propagate taint forward through the FX graph + for node in self.graph.nodes: + if node in tainted_nodes: + continue + if any(inp in tainted_nodes for inp in node.all_input_nodes): + tainted_nodes.add(node) + + # Check leaked outputs: tainted + requires_grad means the output + # carries autograd state that AOTAutograd would silently drop. + # Detached outputs (requires_grad=False) are fine — no autograd to lose. + for var in rv: + if ( + isinstance(var, TensorVariable) + and var.requires_grad + and var.as_proxy().node in tainted_nodes + ): + msg = ( + "An intermediate tensor that had requires_grad_() called " + "on it (or a tensor derived from it) is being returned " + "from the compiled region. AOTAutograd's functionalization " + "drops the requires_grad_() effect on graph outputs, " + "producing wrong results. If you only need the tensor " + "values without gradients, call .detach() before returning." + ) + if tx.one_graph: + unimplemented( + gb_type="returning intermediate with requires_grad_()", + context="graph output depends on source-less requires_grad_()", + explanation=msg, + hints=[ + "If you only need the tensor values without gradients, " + "call .detach() before returning.", + "Consume the gradient inside the compiled function " + "(call backward() and use .grad), " + "or move requires_grad_() outside torch.compile.", + ], + ) + else: + tx.speculation_log.graph_break_on_requires_grad_ = True + raise exc.RequiresGradRestartAnalysis( + restart_reason="source-less requires_grad_() intermediate leaked as output" + ) + + def compile_and_call_fx_graph( + self, + tx: "InstructionTranslatorBase", + rv: list[VariableTracker], + root: FakeRootModule, + ) -> tuple[list[Instruction], list[str] | None]: + """ + Generate code from self.graph and return the Instruction()s to + call that generated code. + + Code is generated w.r.t. self.root_tx. + tx is only used for preserving GraphModule metadata + + Returns a tuple of (instructions, pycode) where pycode is a string + representation of the generated Python code if generate_pycode_prologue + is enabled, otherwise None. + """ + with torch._guards.TracingContext.clear_frame(): + from .decorators import disable + + if not self.should_exit: + raise AssertionError( + "should_exit must be True before call_user_compiler" + ) + + self.run_compiler_collective() + if count_calls(self.graph) == 0 and len(rv) == 0: + return [], None + + name = make_compiled_fn_name() + + if not isinstance(rv, list): + raise AssertionError(f"rv must be a list, got {type(rv)}") + if not isinstance(root, FakeRootModule): + raise AssertionError(f"root must be a FakeRootModule, got {type(root)}") + + # Error on source-less requires_grad_() outputs. + # Must run before autograd validation since detaching resolves the + # "consumed grad_fn" conflict for backward-consumed intermediates. + self._check_requires_grad_intermediate_outputs(rv, tx) + + # Check if autograd.grad is used with outputs that require grad + # This would cause double backward issues in aot_autograd + self._validate_outputs_safe_for_autograd_nodes(rv, tx) + + output_node = self.create_node( + "output", + "output", + (self.current_tracer.create_arg(tuple(x.as_proxy() for x in rv)),), + {}, + ) + sub_gms = self.dedup_pass() + root.add_nn_modules(sub_gms) # type: ignore[arg-type] + + self.current_tracer._maybe_preserve_original_meta(tx, output_node) + if not config.do_not_emit_runtime_asserts: + # There is a rare scenario where codegen_suffix adds a new entry + # to self.nn_modules while `root` knows only about the + # nn_modules at the time of its creation. This causes failures + # while creating the graph module because self.graph and root + # are out of sync. This only happens for `get_attr` nodes, so + # here we clean up the get_attr nodes that are unused. + with dynamo_timed("insert_deferred_runtime_asserts"): + for attr in dir(root): + subgraph = getattr(root, attr) + if isinstance(subgraph, fx.GraphModule): + insert_deferred_runtime_asserts( + subgraph, + self.shape_env, + name, + export=self.export, + ) + self.remove_unused_get_attr_nodes() + insert_deferred_runtime_asserts( + fx.GraphModule(root, self.graph), + self.shape_env, + name, + export=self.export, + ) + # NB: deferred runtime asserts can keep graphargs live, so make sure + # those are inserted before pruning + self.remove_unused_graphargs() + ncalls = count_calls(self.graph) + counters["stats"]["calls_captured"] += ncalls + + self.remove_tensorify_specialized_graphargs() + + # free a bit of memory + self.real_value_cache.clear() + + # CA backward graphs have side-effecting ops (call_accumulate_grad, + # call_hook) that is_impure() doesn't flag, and a fixed positional + # placeholder layout that must not be reordered. + # + # Export canonicalizes in torch.export._trace._produce_aten_artifact + # so both strict and non-strict export produce the same node order. + if ( + config.canonicalize_output_graph_node_order + and not self.export + and not torch.compiler.is_exporting() + and not torch._dynamo.compiled_autograd.in_compiled_autograd_region + ): + _canonicalize_graph(self.graph) + + gm = _make_graph_module(root, self.graph) + + from .dce_extra_outputs import dce_hop_extra_outputs + + dce_hop_extra_outputs(gm) + + # Saved tensors hooks are not used by the graph. + # GraphModule by default only copies used in the graph submodules. + # Copying them into the result graph manually. + if self.saved_tensors_hooks_subgraph_names: + for subgraph_name in self.saved_tensors_hooks_subgraph_names: + setattr(gm, subgraph_name, getattr(root, subgraph_name)) + + for register_finalizer in self.register_finalizer_fns: + register_finalizer(gm) + + if next(gm.parameters(), None) is not None: + # If dynamo produces a graph with parameters, skip package stuff + # Bypass output graph + self.bypass_package( + "Graph contains named parameters due to static addresses.", + gm=gm.print_readable( + print_output=False, include_stride=True, include_device=True + ), + ) + + if self.package is not None: + gm._backend_id = name # pyrefly: ignore[bad-argument-type] + + # pyrefly: ignore[bad-argument-type] + gm.compile_subgraph_reason = self.compile_subgraph_reason + # pyrefly: ignore[bad-argument-type] + gm.meta["dynamo_flat_name_to_original_fqn"] = ( + self.dynamo_flat_name_to_original_fqn.copy() + ) + gm.meta["dynamo_compile_id"] = self.dynamo_compile_id + gm.meta["backend_id"] = name + + if self.cudagraph_annotation is not None: + gm.meta["cudagraph_annotation"] = self.cudagraph_annotation + + graph_code_log.debug( + "%s", + lazy_format_graph_code( + name, gm, include_stride=True, include_device=True, colored=True + ), + ) + torch._logging.trace_structured( + "dynamo_output_graph", + lambda: {"sizes": self.get_graph_sizes_structured()}, + payload_fn=lambda: gm.print_readable( + print_output=False, include_stride=True, include_device=True + ), + ) + self.call_cleanup_hooks() + old_fake_mode = self.tracing_context.fake_mode + if old_fake_mode is None: + raise AssertionError("old_fake_mode must not be None") + # Store old_fake_mode so it can be cleared at end of compile + self._old_fake_mode = old_fake_mode + if not self.export: + import torch._functorch.config as _config + + with _config.patch(fake_tensor_allow_unsafe_data_ptr_access=False): + # TODO(voz): The way export uses gm, and fake tensors, is not supported with us resetting + + # Why create a new FakeTensorMode? + # + # The reason this needs to be done is because when we do Dynamo tracing, fake + # tensors can have their metadata mutated. Thus, the fake tensor we allocated + # for any given tensor may no longer be valid for the beginning trace of the + # graph. Nor is it convenient to "clone" the input tensors before mutating them, + # since you have to preserve aliasing. So we just reconstruct the FakeTensorMode + # from scratch when we go to AOTAutograd. But the ShapeEnv must be preserved as + # Dynamo made decisions about what is dynamic or not / guards from the user code + # that is not in graph. + backend_fake_mode = torch._subclasses.FakeTensorMode( + shape_env=old_fake_mode.shape_env, + ) + # TODO(voz): Ostensibly, this should be scoped and + # restore back to old_fake_mode, but doing so currently violates + # a lot of fake_tensor ownership assumptions and runs afoul of detect_fake_mode + self.tracing_context.fake_mode = backend_fake_mode + + example_inputs = self.example_inputs() + + # Restore placeholder metadata mutated by + # in-graph shallow_copy_data_. + if self._shallow_copy_placeholder_snapshots: + placeholders = gm.graph.find_nodes(op="placeholder") + placeholder_to_idx = {n: i for i, n in enumerate(placeholders)} + for node, snapshot in self._shallow_copy_placeholder_snapshots.items(): + node.meta["example_value"] = snapshot + idx = placeholder_to_idx[node] + example_inputs[idx].fake_device = snapshot.fake_device # type: ignore[union-attr] + + gm.graph.lint() + with self.restore_global_state(): + compiled_fn = self.call_user_compiler(gm, example_inputs) + + from torch.fx._lazy_graph_module import _LazyGraphModule + + if isinstance(compiled_fn, _LazyGraphModule) or ( + isinstance(getattr(compiled_fn, "__self__", None), _LazyGraphModule) + and compiled_fn.__name__ == "_lazy_forward" # type: ignore[attr-defined] + ): + # Since dynamo will run the forward method for the GraphModule shortly + # anyways, it does not hurt to do the real recompilation here if + # this is a _LazyGraphModule. This makes it easier for dynamo to + # optimize a _LazyGraphModule. + + lazy_gm = ( + compiled_fn + if isinstance(compiled_fn, _LazyGraphModule) + else compiled_fn.__self__ # type: ignore[attr-defined] + ) + + _LazyGraphModule.force_recompile(lazy_gm) + + if not isinstance(compiled_fn, _LazyGraphModule): + # replace compiled_fn with the real forward method + compiled_fn = lazy_gm.forward + + if not self.export: + # Run after every non-export backend compile, not only the + # registered backends covered by convert_frame weakref cleanup. + # Backends have already consumed the graph, so non-CPU Dynamo + # tracing constants no longer need to keep real tensors alive. + old_fake_mode.fake_tensor_converter.clear_non_cpu_constants() + + if self.package is not None: + self.package.add_backend_id(name, compiled_fn) + + # If __torch_function__ subclass dispatch was inlined during + # tracing, wrap the compiled graph to disable __torch_function__ + # at runtime, preventing double dispatch (the C++ dispatcher + # would otherwise re-trigger __torch_function__ on subclass + # inputs that the graph already handles). + if self.torch_function_subclass_inlined: + real_compiled_fn = compiled_fn + + def _tf_disabled_wrapper(*args, **kwargs): + with torch._C.DisableTorchFunctionSubclass(): + return real_compiled_fn(*args, **kwargs) + + compiled_fn = _tf_disabled_wrapper + + compiled_fn = disable( + compiled_fn, reason="do not trace Dynamo-compiled graph" + ) + + counters["stats"]["unique_graphs"] += 1 + if old_fake_mode.shape_env is None: + raise AssertionError("old_fake_mode.shape_env must not be None") + if specializations := old_fake_mode.shape_env.specializations: + specialization_guards = [] + specialization_cache: dict[Specialization, Callable[[Any], Any]] = {} + sources = [a.source for a in self.graphargs] + for specialization in specializations: + source_index = sources.index(specialization.source) + check_fn_source = inspect.getsource(specialization.check_fn).strip() + # Required because the LABDA_GUARD API requires a root guard manager + unused_root_guard_manager = RootGuardManager() + check_fn = guards.LAMBDA_GUARD( # type: ignore[attr-defined] + unused_root_guard_manager, + specialization.check_fn, + [check_fn_source], + None, # user_stack + ) + + log.debug( + "Compiling backend specialized graph with specialization=%s", + check_fn_source, + ) + + specialization_guards.append( + ( + functools.partial( + lambda idx, args, check_fn=check_fn: check_fn( + args[idx] + ), + source_index, + ), + specialization, + ) + ) + + @torch._dynamo.disable(reason="do not trace Dynamo-compiled graph") # type: ignore[misc] + def specialized_dispatch(*args: Any, **kwargs: Any) -> Any: + for check_fn, specialization in specialization_guards: + if check_fn(args): + if specialization in specialization_cache: + return specialization_cache[specialization]( + *args, **kwargs + ) + + with self.shape_env.patch_source_specialization( + specialization.source, specialization.check_fn + ): + # Modify gm so AOTAutogradCache key changes per specialization + gm.meta["specialization"] = specialization + example_inputs: list[Tensor] = list(args) + with tracing(self.tracing_context): + specialization_cache[specialization] = ( + self.call_user_compiler(gm, example_inputs) + ) + + return specialization_cache[specialization](*args, **kwargs) + return compiled_fn(*args, **kwargs) + + # This is safe because we pre-process name to be unique + self.install_global_unsafe(name, specialized_dispatch) + else: + # This is safe because we pre-process name to be unique + self.install_global_unsafe(name, compiled_fn) + + if self.root_tx is None: + raise AssertionError("root_tx must not be None") + cg = PyCodegen(self.root_tx) + + if has_user_objects(): + # NB: This is where we store possible user objects before running the graph + # index_to_user_object_weakref is the function used in the graph to translate + # the dynamo-generated index into the actual object passed to the compiled function. + # We generate bytecode to store all user objects at the proper index in the below + # call. + cg.add_push_null( + lambda: cg.load_import_from( + torch._dynamo.graph_bytecode_inputs.__name__, + "store_user_object_weakrefs", + ) + ) + + tmp_vars = [] + for constructor in index_to_bytecode_constructor.values(): + constructor(cg) + var_name = ( + self.new_var() + ) # keep alive any user objects for the rest of the frame + # TODO: we could omit this for objects we create but shouldn't be too much overhead for now + cg.store(var_name) + tmp_vars.append(var_name) + + for var_name in tmp_vars: + cg.append_output(cg.create_load(var_name)) + + cg.call_function(len(index_to_bytecode_constructor), False) + cg.pop_top() + + for idx, arg in enumerate(self.graphargs): + self.export_metadata.graph_input_idx_to_local_source[idx] = arg.source + + cg.make_call_generated_code(name) + + return cg.get_instructions(), cg.get_pycode() + + @property + def placeholders(self) -> list[fx.Node]: + return self.graph.find_nodes(op="placeholder") + + @property + def graphargs(self) -> list[GraphArg]: + return [node.meta["grapharg"] for node in self.placeholders] + + def call_user_compiler( + self, gm: fx.GraphModule, example_inputs: list[Tensor] + ) -> CompiledFn: + with dynamo_timed( + "OutputGraph.call_user_compiler", + phase_name="backend_compile", + log_pt2_compile_event=True, + log_waitcounter=True, + waitcounter_name_override="compile_aot_autograd", + dynamo_compile_column_us="aot_autograd_cumulative_compile_time_us", + ): + return self._call_user_compiler(gm, example_inputs) + + def _call_user_compiler( + self, gm: fx.GraphModule, example_inputs: list[Tensor] + ) -> CompiledFn: + if self.compiler_fn is None: + raise AssertionError("compiler_fn must not be None") + tot = 0 + placeholders = [] + for node in gm.graph.nodes: + if node.op in ("call_function", "call_method", "call_module"): + tot += 1 + if node.op == "placeholder": + placeholders.append(node) + increment_op_count(tot) + for pl in placeholders: + if not hasattr(pl, "_dynamo_source"): + arg = pl.meta["grapharg"] + # TODO: Why isn't this stored in meta :think: + # NOTE: can't move these into meta: https://github.com/pytorch/pytorch/issues/141640 + pl._dynamo_source = arg.source + + # NOTE: can't move these into meta: https://github.com/pytorch/pytorch/issues/141640 + gm._param_name_to_source = self.param_name_to_source # type: ignore[assignment] + gm._source_to_user_stacks = self.source_to_user_stacks # type: ignore[assignment] + + # Check for per-graph backend override (for debugging/bisecting) + compiler_fn = ( + get_backend_override_for_compile_id( + self.dynamo_compile_id, config.debug_backend_override + ) + or self.compiler_fn + ) + + # Check for per-graph inductor config override (for debugging/bisecting) + inductor_config_override = get_inductor_config_override_for_compile_id( + self.dynamo_compile_id, config.debug_inductor_config_override + ) + if inductor_config_override: + compiler_fn = _wrap_with_inductor_config( + compiler_fn, inductor_config_override + ) + + name = ( + compiler_fn.__name__ + if hasattr(compiler_fn, "__name__") + else "" + ) + from torch._higher_order_ops.passes.inline_invoke_subgraph import ( + inline_invoke_subgraph, + inline_single_use_invoke_subgraph, + ) + + if config.inline_invoke_subgraph: + gm = inline_invoke_subgraph(gm) + elif config.inline_single_use_invoke_subgraph: + gm = inline_single_use_invoke_subgraph(gm) + + try: + _step_logger()(logging.INFO, f"calling compiler function {name}") + if config.verify_correctness: + compiler_fn = WrapperBackend(compiler_fn) + compiled_fn = compiler_fn(gm, example_inputs) + _step_logger()(logging.INFO, f"done compiler function {name}") + if not callable(compiled_fn): + raise AssertionError("compiler_fn did not return callable") + except (TensorifyScalarRestartAnalysis, ShortenTraceback, IndexError): + # Re-raise IndexError so dim out-of-range errors from tensor ops + # propagate to the user as IndexError, not BackendCompilerFailed. + raise + except exceptions_allowed_to_be_fallback as e: + if self.has_user_defined_allowed_in_graph: + raise BackendCompilerFailed( + self.compiler_fn, e, inspect.currentframe() + ).with_traceback(e.__traceback__) from None + unimplemented_with_warning( + e, + self.root_tx.f_code, + gb_type="Backend compiler exception", + context=f"Backend: {name}\nException:{str(e)}\nTraceback:\n{self.root_tx.format_frame_summary()}", + explanation=f"Backend compiler `{name}` failed with {str(e)}. Adding a graph break.", + hints=[ + "Report an issue to the backend compiler repo.", + ], + ) + except SkipFrame: + # The backend compiler has requested that we skip the frame, instead of + # aborting execution. + raise + except Exception as e: + raise BackendCompilerFailed( + self.compiler_fn, e, inspect.currentframe() + ).with_traceback(e.__traceback__) from None + + signpost_event( + "dynamo", + "OutputGraph.call_user_compiler", + { + **self.co_fields, + "op_count": tot, + "node_count": len(gm.graph.nodes), + "input_count": len(placeholders), + }, + ) + + # pyrefly: ignore [bad-return] + return compiled_fn + + def dedup_pass(self) -> dict[str, torch.fx.GraphModule]: + if torch._dynamo.config.use_graph_deduplication: + return apply_graph_deduplication(self) + else: + return {} + + def install_subgraph(self, name: str, sub_gm: torch.fx.GraphModule) -> str: + next_name = get_unique_name_wrt(name, self.nn_modules, requires_suffix=True) + sub_gm.__name__ = next_name # type: ignore[assignment] + sub_gm.torchdynamo_force_dynamic = False # type: ignore[assignment] + # This graph module is not present in the user space, so it can't be + # accessed by a source. Set source=None. + self.register_attr_or_module(sub_gm, next_name, source=None) + return next_name + + def example_inputs(self) -> list[torch.Tensor]: + result = [arg.example for arg in self.graphargs] + # pyrefly: ignore[bad-return] + return result + + def remove_unused_get_attr_nodes(self) -> None: + for node in sorted(self.graph.find_nodes(op="get_attr"), reverse=True): + if len(list(node.users)) == 0: + self.remove_node(node) + + def remove_unused_graphargs(self) -> None: + # NB: It's OK to drop GraphArg for symbols that ended up being + # specialized iff they are not used in runtime assertions. You don't + # even have to make a guard for it, because ShapeEnv produce_guards + # operates on tracked_fakes, which never gets pruned. + # That being said, you'll get marginally better generated + # guard code if you promote the guard into a Dynamo guard (since that + # allows for the guard to be done using C++ guards.) If we get + # ShapeEnv guards to go into C++ guards, this will stop being a thing + # though! + + if not self.should_exit: + raise AssertionError("should_exit must be True before finalize") + + # Miniature DCE pass, but only for obviously trivial operations + def is_static_true(b_node: fx.node.Argument) -> bool: + if b_node is True: + return True + if not isinstance(b_node, fx.Node): + return False + b = b_node.meta.get("example_value") + if b is None: + return False + if b is True: + return True + if ( + isinstance(b, torch.SymBool) + and (r := b.node.maybe_as_bool()) is not None + ): + return r + # TODO: We can also technically remove all cases when the input + # doesn't have unbacked inputs, since it's all in the ShapeEnv + return False + + def is_symnode_arg(a: fx.node.Argument) -> bool: + from torch.fx.experimental.sym_node import SymTypes + + if isinstance(a, (int, float, bool)): + return True + if isinstance(a, fx.Node): + return isinstance(a.meta.get("example_value"), SymTypes) + return False + + # NB: We assume that you cannot do mutations on int/float/bool, + # because they are immutable types, and therefore is always safe to + # DCE. + def is_symnode_compute_node(node: fx.Node) -> bool: + from torch.fx.experimental.sym_node import SymTypes + + if node.op != "call_function": + return False + # TODO: I don't think it's possible to have a bare int/float here? + if not isinstance(node.meta.get("example_value"), SymTypes): + return False + # TODO: This will bail here if you ever end up with a more complicated + # computation function, like sum(list_of_ints), even though it + # should be DCE'able + if not all(is_symnode_arg(a) for a in node.args): + return False + if not all(is_symnode_arg(a) for a in node.kwargs.values()): + return False + return True + + from torch.fx.experimental.symbolic_shapes import is_accessor_node + + for node in reversed(list(self.graph.nodes)): + if len(list(node.users)) == 0: + if ( + node.op == "get_attr" + or (node.op == "call_function" and node.target is operator.getitem) + or ( + node.op == "call_function" + and node.target is torch._check + and is_static_true(node.args[0]) + ) + or is_symnode_compute_node(node) + or is_accessor_node(node) + ): + self.remove_node(node) + + def placeholder_binds_symbol(node: fx.Node) -> sympy.Symbol | None: + arg = node.meta["grapharg"] + example = arg.example + if isinstance(example, torch.SymInt) and isinstance( + example.node.expr, sympy.Symbol + ): + return example.node.expr + return None + + def remove_unused(node: fx.Node) -> None: + log.debug("REMOVE UNUSED GRAPHARG %s", node.meta["grapharg"].source.name) + # I'm not really sure why you need to delete these from the + # node since the node is going to get removed + del node.meta["grapharg"] + self.remove_node(node) + self.real_value_cache.pop(node, None) + + used_symbols: set[sympy.Symbol] = set() + + def update_used_symbols( + used_symbols: set[sympy.Symbol], fake: torch.SymInt | torch.Tensor + ) -> None: + used_symbols |= free_symbols(fake) + + recheck_placeholders = [] + for node in self.placeholders: + binds_symbol = placeholder_binds_symbol(node) is not None + # Don't delete symbol bindings yet + if binds_symbol: + if not node.users: + recheck_placeholders.append(node) + else: + if not node.users and not isinstance( + node.meta["grapharg"], BackwardStateGraphArg + ): + remove_unused(node) + else: + # Register the free symbols as uses + arg = node.meta["grapharg"] + if isinstance(arg, BackwardStateGraphArg): + continue + if isinstance(node.meta["grapharg"].example, torch.ScriptObject): + real_script_obj = node.meta["grapharg"].example + fake_script_obj = node.meta["grapharg"].example_strong_ref + if not torch._library.fake_class_registry.tracing_with_real( + real_script_obj + ): + flat_dict = dict(real_script_obj.__obj_flatten__()) # type: ignore[attr-defined] + for attr in flat_dict: + fake_attr_val = getattr( + fake_script_obj.wrapped_obj, attr + ) + pytree.tree_map_only( + (torch.SymInt, torch.Tensor), + lambda t: update_used_symbols(used_symbols, t), + fake_attr_val, + ) + continue + if is_custom_class(type(node.meta["grapharg"].example)): + continue + fake = ( + arg.fake_tensor if arg.fake_tensor is not None else arg.example + ) + update_used_symbols(used_symbols, fake) + + # After removing unused graphargs, prune unused binds_symbol + for node in recheck_placeholders: + symbol = placeholder_binds_symbol(node) + if symbol is not None: + if symbol not in used_symbols: + remove_unused(node) + else: + # Make sure we delete later occurrences of the same symbol + used_symbols.remove(symbol) + + def remove_tensorify_specialized_graphargs(self) -> None: + # This is a pretty interesting function. Basically we have this problem + # where our compiler tends to choke when we have unused inputs. The way + # we support dynamic float arguments is by doing a joint fx pass and + # tensorifying away as many symfloats as we can. For the remaining symfloats + # we have no choice but to specialize... HOWEVER at that point in time + # we can no longer remove graph inputs. So our sledgehammer solution is to + # save the state of what inputs we should have specialized in dynamo and + # restart analysis. This function incorporates this "view from the future" + # state and specializes inputs that we know we won't be able to tensorify + # away in the joint pass. In principle we shouldn't choke on unused inputs + # and so this shouldn't be necessary. In practice CUDA graphs choke on + # unused inputs so we need this for now. + + # Import here to prevent circular import + from torch._dynamo.symbolic_convert import TensorifyState + + for node in self.graph.nodes: + example_value = node.meta.get("example_value") + if ( + isinstance(example_value, FakeTensor) # noqa: ISINSTANCE_FAKE_TENSOR + and example_value.item_memo is not None + and hasattr(example_value.item_memo.node._expr, "name") + and all(u.target == "item" for u in node.users) + and TensorifyState.should_specialize( + # We use _expr instead of expr b/c we want the symbol not the replacement + example_value.item_memo.node._expr.name + ) + ): + for u in list(node.users): + u.replace_all_uses_with(guard_scalar(example_value.item_memo)) + self.remove_node(u) + self.remove_node(node) + + def add_output_instructions( + self, prefix: list[Instruction], pycode: list[str] | None = None + ) -> None: + """ + We call this on the creation of a new compiled subgraph that is inserted + before user code. + An optional pycode argument can be passed to add python codegen along with + the bytecode. The generated python code should match the bytecode behavior + from the `prefix` argument. + """ + self.output_instructions.extend(prefix) + if not isinstance(pycode, (list, type(None))): + raise AssertionError("pycode must be a list of python code or None") + self.output_pycode.append(pycode) + self.should_exit = True + + def install_resume_function_global( + self, + name: str, + code: types.CodeType, + f_globals: dict[str, Any], + ) -> None: + """Install a resume function as a global. + + When the code has freevars, installs a factory that creates the + function with correct globals and closure (since MAKE_FUNCTION + inherits the current frame's globals, which is wrong for resume + functions from inlined frames). Otherwise installs the function + directly. + """ + if code.co_freevars: + + def _make_fn( + closure: tuple[types.CellType, ...], + ) -> types.FunctionType: + return types.FunctionType(code, f_globals, name, None, closure) + + self.install_global_unsafe(name, _make_fn) + else: + self.install_global_unsafe( + name, + types.FunctionType(code, f_globals, name), + ) + + def install_global_unsafe(self, name: str, value: Any) -> None: + """ + WARNING: prefer the safer `install_global_by_id/install_global`. + torch.compile instances should be independent of each other; + one footgun is to have one instance depend on the existence of + a global installed by another instance. This can happen if we mangle + a global the same way across both instances. + """ + if name in self.installed_globals: + raise AssertionError(f"global '{name}' is already installed") + self.installed_globals.add(name) + self.cleanups.append(CleanupHook.create(self.global_scope, name, value)) + + def install_global_by_id(self, prefix: str, value: Any) -> str: + """ + Installs a global if it hasn't been installed already. + This is determined by (prefix, id(value)) pair. + + Returns the name of the newly installed global. + """ + # NB: need self.compile_id to distinguish this global + # from another global created in a different torch.compile instance + name = f"{prefix}_{id(value)}_c{self.compile_id}" + if name in self.installed_globals: + return name + self.install_global_unsafe(name, value) + return name + + def install_global(self, prefix: str, value: Any) -> str: + """ + Installs a global, generating a unique name for it. + + Returns the name of the newly installed global. + """ + # NB: unique_id is unique, even across torch.compile instances + name = unique_id(prefix) + self.install_global_unsafe(name, value) + return name + + def cleanup(self) -> None: + # There is a reference cycle between tracer and OutputGraph, causing + # some of the tensor objects to be held alive for longer than necessary. + self.root_tx = None # type: ignore[assignment] + self.local_generators.clear() + self.nn_modules.clear() + self.used_inlined_inbuilt_modules_names.clear() + self.param_name_to_source = None + + for node in self.graph.nodes: + if "grapharg" in node.meta: + del node.meta["grapharg"] + self.real_value_cache.clear() + self.input_name_to_proxy.clear() + self._cached_replayed_side_effect_source_refs = tuple( + self.get_replayed_side_effect_source_refs() + ) + self.side_effects.clear() + self.variable_tracker_cache.clear() + self.mro_source_cache.clear() + self.guarded_mro_absent_keys.clear() + self.signature_cache.clear() + self.register_finalizer_fns.clear() + self.dynamo_flat_name_to_original_fqn.clear() + self.tracing_context.clear() + self.input_source_to_var.clear() + self.leaf_var_creation_order.clear() + self.unspec_variable_map.clear() + self.backward_state.clear() + + def add_graph_finalizer( + self, register_finalizer: Callable[[fx.GraphModule], None] + ) -> None: + self.register_finalizer_fns.append(register_finalizer) + + def example_value_from_input_node(self, node: torch.fx.Node) -> Any: + """Extract the non-fake example tensor""" + if node.op == "placeholder": + return node.meta["grapharg"].example + if node.op != "get_attr": + raise AssertionError(f"expected node.op to be 'get_attr', got '{node.op}'") + return self.nn_modules[node.target] # type: ignore[index] + + def add_fqn_info_for_inlined_modules( + self, inlined_module: torch.nn.Module, source: Source + ) -> None: + name = OutputGraph.module_key_name(source.name) + name = get_unique_name_wrt( + name, self.used_inlined_inbuilt_modules_names, self.global_scope + ) + self.used_inlined_inbuilt_modules_names.add(name) + + def register_leaf_name(leaf_name: str) -> None: + if self.param_name_to_source is None: + raise AssertionError("param_name_to_source must not be None") + new_source = self.get_chained_param_buffer_source(source, leaf_name) + new_name = f"{name}.{leaf_name}" + self.param_name_to_source[new_name] = new_source + if isinstance(source, LocalSource): + self.dynamo_flat_name_to_original_fqn[ + OutputGraph.module_key_name(new_source.name) + ] = leaf_name + + # annoying, but there are cases when we do not have parameters + # see test_nn_moduledict_contains + if hasattr(inlined_module, "_parameters"): + if ( + callable(inlined_module.named_parameters) + and inlined_module.named_parameters.__func__ # type: ignore[attr-defined] + is og_module_named_parameters_fn_ptr + ): + for leaf_name, _ in inlined_module.named_parameters(): + register_leaf_name(leaf_name) + if hasattr(inlined_module, "_buffers"): + if ( + callable(inlined_module.named_buffers) + and inlined_module.named_buffers.__func__ # type: ignore[attr-defined] + is og_module_named_buffers_fn_ptr + ): + for leaf_name, _ in inlined_module.named_buffers(): + register_leaf_name(leaf_name) + + +class DynamoTracerOutput: + error_on_graph_break: bool + is_tracing_resume_prologue: bool + output_graph: OutputGraph | None + # output_graph_for_cleanup is set even when there's an error, to allow + # cleanup of graph nodes to break reference cycles + output_graph_for_cleanup: OutputGraph | None + closure: tuple[Any, ...] | None + f_globals: dict[str, Any] + + def __init__( + self, tracer: "InstructionTranslatorBase", error: Any | None = None + ) -> None: + self.error_on_graph_break = tracer.error_on_graph_break + self.is_tracing_resume_prologue = tracer.is_tracing_resume_prologue + self.closure = tracer.closure + self.f_globals = tracer.f_globals + self.output_graph_for_cleanup = tracer.output + if error: + self.output_graph = None + else: + self.output_graph = tracer.output + + def _cleanup_output_graph(self) -> None: + output_graph = self.output_graph_for_cleanup + if output_graph: + # Lazy import to avoid a circular import (convert_frame imports + # output_graph at module load time). + from .convert_frame import _clear_fake_mode_weakrefs + + # A discarded restart/skip attempt fakified real tensors and built + # guards on them, leaving weakrefs on the real params that block + # torch.utils.swap_tensors after compile (issue #186796): guard + # create_fn partials hold a TensorWeakRef, and tensor_to_context / + # the describer memos / grapharg examples hold WeakIdRef/weakref. + # The end-of-compile clear_compile_context_weakrefs only clears the + # final attempt's tracing_context, never these discarded attempts, + # and never touches guards. Unlike that final clear (which is gated + # by config.invalidate_compile_context_weakrefs), the discard-path + # clear is unconditional: a discarded attempt has no consumers, so + # dropping its weakrefs can never break anything downstream. + # Drop grapharg examples first, before clearing nodes drops the meta. + for node in output_graph.graph.nodes: + if "grapharg" in node.meta: + del node.meta["grapharg"] + for tracer in output_graph.tracers: + tracer.graph._clear_nodes() + output_graph.guards.clear() + tc = output_graph.tracing_context + tc.tensor_to_context.clear() + # Clear the describer weakrefs from both the current tracing_context + # fake_mode and the _old_fake_mode saved during compile: on a + # backend-raised restart (e.g. TensorifyScalarRestartAnalysis), + # tracing_context.fake_mode has already been swapped to a fresh + # empty backend fake_mode, so the real-param weakrefs live on + # _old_fake_mode instead. + _clear_fake_mode_weakrefs(tc.fake_mode) + if hasattr(output_graph, "_old_fake_mode"): + _clear_fake_mode_weakrefs(output_graph._old_fake_mode) + # Also clear tracked_fakes to break the + # FakeTensorMode -> ShapeEnv -> TrackedFake -> FakeTensor cycle. + if tc.fake_mode and tc.fake_mode.shape_env: + tc.fake_mode.shape_env.tracked_fakes = None + + +err_epilogue = ( + "With the current config, we will graph break " + "(and fall back to eager-mode PyTorch) on all ops " + "that have do not have the 'pt2_compliant_tag'. " + "Please see the following doc for how to mark this op as PT2 compliant " + "https://pytorch.org/tutorials/advanced/custom_ops_landing_page.html" +) + + +def check_pt2_compliant_op( + output_graph: OutputGraph, kind: str, target: Any, args: Any, kwargs: Any +) -> None: + if kind != "call_function": + return + + def encountered_compliant_op(target: torch._ops.OpOverload) -> None: + if target.namespace in {"prim", "prims", "aten"}: + return + output_graph.compliant_custom_ops.add(target) + + def encountered_non_compliant_op(target: torch._ops.OpOverload, msg: str) -> None: + output_graph.non_compliant_ops.add(target) + if config.only_allow_pt2_compliant_ops: + unimplemented( + gb_type="Encountered non-PT2-compliant op", + context="", + explanation=msg + " " + err_epilogue, + hints=[], + ) + + if isinstance(target, torch._ops.OpOverload): + if torch.Tag.pt2_compliant_tag in target.tags: + encountered_compliant_op(target) + return + encountered_non_compliant_op( + target, + f"Encountered the torch.ops.OpOverload {target} that is not PT2 compliant.", + ) + return + + if isinstance(target, torch._ops.OpOverloadPacket): + overloads = tuple(target.overloads()) + # Optimization: Overload resolution is expensive. + # If there's only one overload, we know what it will resolve to. + if len(overloads) == 1: + op = getattr(target, overloads[0]) + if torch.Tag.pt2_compliant_tag in op.tags: + encountered_compliant_op(op) + return + encountered_non_compliant_op( + op, + f"Encountered the non-overloaded " + f"torch.ops.OpOverloadPacket {target} " + f"that is not PT2 compliant. ", + ) + return + + args, kwargs = torch._dynamo.utils.get_fake_values_from_nodes( + output_graph.current_tx, (args, kwargs), False + ) + try: + overload = torch._C._jit_resolve_packet( + target._qualified_op_name, *args, **kwargs + ) + except RuntimeError as e: + unimplemented( + gb_type="Error when attempting to resolve op packet", + context="", + explanation=str(e), + hints=[], + ) + + op = getattr(target, overload) + if torch.Tag.pt2_compliant_tag in op.tags: + encountered_compliant_op(op) + else: + encountered_non_compliant_op( + op, + f"Encountered the torch.ops.OpOverloadPacket {target} " + f"which resolves to the overload ({overload}) that is " + f"not PT2 compliant.", + ) + + +_compile_id_counter = itertools.count() + +P = ParamSpec("P") +R = TypeVar("R") + + +class LazyProxy: + def __init__( + self, + tracer: "SubgraphTracer", + fn: Callable[P, R], + *args: P.args, + **kwargs: P.kwargs, + ) -> None: + self.tracer = tracer + # pyrefly: ignore [invalid-type-var] + self.fn = fn + self.args = args + self.kwargs = kwargs + + def __call__(self) -> Any: + return self.fn(*self.args, **self.kwargs) + + +class SubgraphTracer(fx.Tracer): + """ + Holds an FX graph that is being traced. OutputGraph owns a SubgraphTracer + and the separation of responsibilities is that SubgraphTracer is + responsible for building the graph while OutputGraph is responsible for + compiling and executing the graph. + """ + + def __init__( + self, + output_graph: "OutputGraph", + parent: Optional["SubgraphTracer"] = None, + is_export: bool = False, + source_target: Target | None = None, + description: str | None = None, + ) -> None: + super().__init__() + self.output_graph = weakref.proxy(output_graph) + self.graph = torch.fx.Graph() + + # See note [Export inputs must be explicitly passed in] + self.is_export = is_export + # Map from graph input name to its placeholder proxy object, where the + # map's keys give all current placeholder node names and can be used to + # create unique node names + self.input_name_to_proxy: dict[str, fx.Proxy] = {} + # Node => computed real value (see utils.get_real_value) + self.real_value_cache: dict[fx.Node, torch.Tensor] = {} + + # SubgraphTracers can be nested. See NOTE [HigherOrderOperator tracing design] + self.parent = parent + self.source_target = source_target + self.description = description + # A dict mapping previously free variables (Proxy objects) + # to new Proxy objects that wrap inputs to this subgraph. + # + # This dict maps proxies in outer graphs to placeholders in current graph. + # It serves two purposes: + # - Proxies are associated with VariableTrackers. If we see + # the same VariableTracker twice (and it is a free variable), + # then we want to use the same Proxy in the current subgraph to + # record the tracing. + # - If we are tracing a HigherOrderOperator's body_fn, then we + # need to keep track of what free variables were lifted so we can + # rewrite the HigherOrderOperator call using the traced body_fn. + # Dicts maintain the order of args for the HigherOrderOperator call. + self.lifted_freevars: dict[fx.Proxy, fx.Proxy] = {} + + # map basic symbols (unbacked and unbacked) to their bound proxies. + # There are only two cases where bound_symbols will be recorded: + # 1. when we create_graph_input for a backed SymInt that's basic symbol + # 2. when we track_produced_symints for intermediate results + # bound_symbols always map the symbol to the proxy whose + # tracer is the current tracer that's readily accessible in current tracer's graph. + self.bound_symbols: dict[sympy.Symbol, torch.fx.Proxy | LazyProxy] = {} + + # Maps _DynamicScalar object ids to allocated SymInt nodes, for symbol reuse + self.dynamic_scalar_nodes: dict[int, torch.SymInt] = {} + + self.prev_inst = None + # True if we want to allow externally visible side-effects (doesn't throw error on their existence) + # during this tracer's tracing. This is currently only used by experimental AC out-of-tree + # via torch._dynamo.utils._disable_side_effect_safety_checks_for_current_subtracer. + # Note: Externally visible side-effects are allowed if this flag OR the above flag is True. + self.unsafe_allow_externally_visible_side_effects = False + self.traced_with_externally_visible_side_effects = False + # True if we want to allow side effects by returning them as extra outputs from the subgraph. + # This is set when enable_side_effects_in_hop=True for HOPs like invoke_subgraph + # and checkpoint (when skip_fwd_side_effects_in_bwd_under_checkpoint config is True). + self.allow_side_effects_in_hop = False + # User code stack at the point where an externally-visible side effect + # was first detected and allowed (not raised). None means no side + # effect; non-None means one occurred. + self.side_effect_stack: traceback.StackSummary | None = None + # All sources accessed via VariableBuilder (and cell loads) during + # this subtracer's trace. Used by invoke_subgraph reuse to collect + # guards and detect mutations on captured variables. + self.traced_sources: OrderedSet[Source] = OrderedSet() + + # True if this tracer is currently tracing (reconstructing) into a Python generator + self.is_reconstructing_generator = False + + self.debug_level: int = parent.debug_level + 1 if parent is not None else 0 + + self._cur_code = None + self._orig_gm_meta: list[Any] | None = None + self._orig_gm_lineno_map: dict[int, int | None] | None = None + self._orig_gm_firstlineno: int | None = None + # Each SubgraphTracer is associated with a source target, which indicates + # which operator this subgraph is attached to. We compute a source_fn_stack + # based on the source target. For the root tracer, it's set to []. + # This is useful for debugging and transforming the exported graph. + if self.parent is None: + self.source_fn_stack: list[Any] = [] + elif source_target is None: + self.source_fn_stack = self.parent.source_fn_stack[:] + else: + self.source_fn_stack = self.parent.source_fn_stack + [ + (self.graph._target_to_str(source_target), source_target) + ] + + # This is used to create a unique name for the placeholder + self._used_names: OrderedSet[str] = OrderedSet() + # Stores the versions of the input tensors at the time they are inserted + # as placeholders in the graph. This is used to track input mutation. + self._input_versions_at_beginning: list[int] = [] + if torch.is_inference_mode_enabled(): + raise RuntimeError( + "Inference mode is supposed to be disabled during compilation. Please open an issue." + ) + + self.tracked_proxyable_vt: OrderedSet[VariableTracker] = OrderedSet() + + def record_proxyable_vt(self, vt: VariableTracker) -> None: + self.tracked_proxyable_vt.add(vt) + + # preserve original meta if it is available + def _maybe_preserve_original_meta( + self, tx: "InstructionTranslatorBase", node: fx.Node + ) -> None: + if ( + self._orig_gm_meta + and self._orig_gm_lineno_map + and self._orig_gm_firstlineno + ): + lineno = tx.current_instruction.starts_line + node_idx = None + if lineno is not None: + node_idx = self._orig_gm_lineno_map.get( + lineno - self._orig_gm_firstlineno, None + ) + if node_idx is not None: + meta = self._orig_gm_meta[node_idx] + for field in fx.proxy._COPY_META_FIELDS: + if field in meta: + node.meta[field] = meta[field] + if "stack_trace" in meta: + node.meta["stack_trace"] = meta["stack_trace"] + + def create_proxy( + self, + kind: str, + target: Any, + args: Any, + kwargs: Any, + name: str | None = None, + type_expr: Any | None = None, + proxy_factory_fn: Callable[[fx.Node], fx.Proxy] | None = None, + ) -> fx.Proxy: + _t0 = time.time_ns() + try: + return self._create_proxy( + kind, target, args, kwargs, name, type_expr, proxy_factory_fn + ) + finally: + self.output_graph.bytecode_tracing_timings.create_proxy_ns += ( + time.time_ns() - _t0 + ) + + def _create_proxy( + self, + kind: str, + target: Any, + args: Any, + kwargs: Any, + name: str | None = None, + type_expr: Any | None = None, + proxy_factory_fn: Callable[[fx.Node], fx.Proxy] | None = None, + ) -> fx.Proxy: + # NOTE: [Nested SubgraphTracer and free_variable handling] + # -------------------------------------------------------- + # Read NOTE [HigherOrderOperator tracing design] first. + # + # Let's say we're in the middle of introspecting the body of a possibly + # nested HigherOrderOperator, and we see a free variable. + # + # There are two cases: + # 1. We see a free variable that is already tracked by Dynamo. + # 2. We see a free variable that has not been tracked by Dynamo + # + # In case 1, we call `maybe_lift_tracked_freevar_to_input` (below) + # which will lift the freevar to be an input of this subgraph + # and also recursively lift it to be an input on the parent(s). + # + # In case 2, before the call to `create_proxy`, the InstructionTranslator + # will see the freevar when it gets loaded by Python bytecode. + # E.g. for Python 3.11 the bytecodes that may do this are LOAD_DEREF or + # LOAD_GLOBAL. + # There, the InstructionTranslator asks Dynamo to begin tracking the + # freevar by building a new Variable. + # Building a new Variable automatically lifts the freevar to be an + # input of the root SubgraphTracer. + # + # The implications for the code below are: + # - We will always be in Case 1 when we get to this code. + # - Any "free variable" we encounter here is guaranteed to already be + # bound, that is, it is either a graph input of the root graph, or + # some local variable of the root graph or a subgraph. + # - The additional work we need to do here is *only* that we need to + # lift this free variable into inputs (recursively) of each nested + # higher-order-op subgraph until we hit the subgraph where the free + # variable is bound + if self.parent is not None: + flat_args, tree_spec = pytree.tree_flatten((args, kwargs)) + new_flat_args = [] + for arg in flat_args: + maybe_new_arg = self.maybe_lift_tracked_freevar_to_input(arg) + new_flat_args.append(maybe_new_arg) + + args, kwargs = pytree.tree_unflatten(new_flat_args, tree_spec) + + rv = super().create_proxy( + kind, + target, + args, + kwargs, + name, + type_expr, + proxy_factory_fn, # type: ignore[arg-type] + ) + + # append stack trace to fx node + tx = self.output_graph.current_tx + + # log detailed location of line of code in 3.11 + if sys.version_info >= (3, 11) and kind in ( + "call_function", + "call_method", + "call_module", + ): + cur_inst = tx.current_instruction + if ( + cur_inst is not self.prev_inst + and cur_inst.positions is not None + and cur_inst.positions.lineno is not None + ): + tx_code = tx.f_code + header = tx.get_line_of_code_header(lineno=cur_inst.positions.lineno) + + def get_trace_call_log_str() -> str: + line = get_instruction_source_311(tx_code, cur_inst).rstrip() + return f"TRACE FX call {rv.node.name} from {header}\n{line}" + + trace_call_log.debug("%s", LazyString(get_trace_call_log_str)) + self.prev_inst = cur_inst + + # update reference to original meta if we're tracing a new code object + is_retracing = False + if tx.f_code is not self._cur_code: + orig_graphmodule_maybe = code_context.get_context(tx.f_code).get( + "orig_graphmodule", lambda: None + )() + if isinstance(orig_graphmodule_maybe, torch.fx.GraphModule): + is_retracing = True + self._orig_gm_meta = [ + nd.meta for nd in orig_graphmodule_maybe.graph.nodes + ] + self._orig_gm_lineno_map = orig_graphmodule_maybe._lineno_map + self._orig_gm_firstlineno = ( + orig_graphmodule_maybe.forward.__code__.co_firstlineno + ) + else: + self._orig_gm_meta = None + self._orig_gm_lineno_map = None + self._orig_gm_firstlineno = None + nn_module_stack = tx.nn_module_stack + if nn_module_stack: + rv.node.meta["nn_module_stack"] = nn_module_stack.copy() + + if kind in {"call_function", "call_method"}: + stack = (rv.node.name, target) + if nn_module_stack: + # Current codebase assumes that the nn_module_stack has the + # builtin modules in the stack. + current_nn_module = list(rv.node.meta["nn_module_stack"].values())[-1][ + 1 + ] + if current_nn_module.__module__.startswith( + ("torch.nn.modules", "torch.ao.") + ) and not current_nn_module.__module__.startswith( + "torch.nn.modules.container" + ): + stack = (rv.node.name, current_nn_module) + + rv.node.meta["source_fn_stack"] = self.source_fn_stack + [stack] + elif kind == "call_module": + if self.parent is not None: + unimplemented( + gb_type="Invoking an nn.Module inside a higher order operator", + context=f"Higher order op name: {self.source_target}", + explanation="This is not supported.", + hints=[], + ) + # For modules we store the class + rv.node.meta["source_fn_stack"] = self.source_fn_stack + [ + ( + rv.node.name, + next( + ty + for k, (_, ty) in rv.node.meta["nn_module_stack"].items() + if k.split("@")[0] == target + ), + ) + ] + + self._maybe_preserve_original_meta(tx, rv.node) + + if not is_retracing: + if "nn_module_stack" not in rv.node.meta: + nn_module_stack = tx.nn_module_stack + if nn_module_stack: + rv.node.meta["nn_module_stack"] = nn_module_stack.copy() + + if "source_fn_stack" not in rv.node.meta: + if kind in {"call_function", "call_method"}: + rv.node.meta["source_fn_stack"] = self.source_fn_stack + [ + (rv.node.name, target) + ] + elif kind == "call_module": + if self.parent is not None: + unimplemented( + gb_type="Invoking an nn.Module inside a HigherOrderOperator", + context="", + explanation="This is not supported.", + hints=[], + ) + # For modules we store the class + rv.node.meta["source_fn_stack"] = self.source_fn_stack + [ + ( + rv.node.name, + rv.node.meta["nn_module_stack"][target][1], + ) + ] + + if "stack_trace" not in rv.node.meta: + frame_summaries: list[traceback.FrameSummary] = [] + while tx: + # Avoid frame summaries from inside the torch/nn/modules. This ensures that we keep the stack trace of + # the user code. + if not tx.is_co_filename_from_nn_modules(): + frame_summaries.append(tx.frame_summary()) + tx = getattr(tx, "parent", None) + + filtered_frame_summaries = [ + frame + for frame in frame_summaries + if frame.filename not in uninteresting_files() + ] + + # Reverse the frame_summaries, such that the innermost frame is at the last + filtered_frame_summaries.reverse() + + # official from_list stub doesn't have new-style type + msgs = traceback.StackSummary.from_list(filtered_frame_summaries).format() + rv.node.stack_trace = "".join(msgs) + + if ( + torch._dynamo.config.use_graph_deduplication + or torch._dynamo.config.track_nodes_for_deduplication + ): + self.output_graph.region_tracker.track_node( + self.output_graph.current_tx, rv.node + ) + return rv + + def create_node( + self, + kind: str, + target: Target, + args: Any = None, + kwargs: Any = None, + name: str | None = None, + type_expr: Any | None = None, + ) -> fx.Node: + check_pt2_compliant_op(self.output_graph, kind, target, args, kwargs) + if self.parent is not None: + flat_args = pytree.arg_tree_leaves(*args, **kwargs) + for arg in flat_args: + if not isinstance(arg, torch.fx.Node): + continue + if arg.graph != self.graph: + raise AssertionError( + "create_node using arg not from this SubgraphTracer" + ) + + node = super().create_node(kind, target, args, kwargs, name, type_expr) + node.meta["creation_timestamp"] = self.output_graph.timestamp + self._used_names.add(node.name) + return node + + # Note: we did not override erase_node since + # we call self.graph.erase_node elsewhere + def remove_node(self, node: fx.Node) -> None: + if len(node.users) > 0: + user_graph_nodes: list[torch.fx.Node] = [] + for user in node.users: + # For the case where user.graph == self.graph, that is a real bug and will raise + # properly. + if user.graph != self.graph: + # This is a nested graph, which needs to be deleted. + # If we do not do this, we will raise on attempting to remove this. + # As we only get here during restoration cleanup, this is sound. + user_graph_nodes.extend(reversed(list(user.graph.nodes))) + for other_graph_node in user_graph_nodes: + other_graph_node.graph.erase_node(other_graph_node) + self.graph.erase_node(node) + self.input_name_to_proxy.pop(node.name, None) + + # when before=True, we will insert this input before the most recent + # inserted proxy. This is a hack to get around an ordering problem, + # where we first insert a tensor argument, and then insert bindings + # for SymInts that may occur in the tensor argument. + # Remove this if https://github.com/pytorch/pytorch/issues/99007 gets + # fixed. + def create_graph_input( + self, + name: str, + type_expr: Any, + example_value: Any, + before: bool = False, + source: Source | None = None, + ) -> fx.Proxy: + if isinstance(example_value, torch.Tensor): + self._input_versions_at_beginning.append(example_value._version) + log.debug( + "create_graph_input %s %s %s at debug_level %s before=%s", + name, + source.name if source is not None else "(none)", + example_value, + self.debug_level, + before, + ) + if source is None: + if self.parent is None: + raise AssertionError( + f"you are required to provide a source for inputs {name} example_val {example_value} on the root tracer" + ) + + # Note [Export inputs must be explicitly passed in] + # In eager, we are generally OK with adding graph inputs whenever we + # want, because we take care of writing the bytecode that knows how + # to source all the inputs. + # + # In export, this is bad, because you want a self-contained export + # object which only depends on the inputs you explicitly passed to it. + # So we are a bit more strict about what sources can become inputs + # in export + if self.is_export and self.parent is None: + if source is None: + raise AssertionError( + "source must not be None for export root tracer inputs" + ) + if not is_from_local_source(source, only_allow_input=True): + self.output_graph.source_to_user_stacks.setdefault(source, []).append( + TracingContext.extract_stack() + ) + + # _used_names contains the names of all the nodes in the graph, + # including intermediates. This ensures that we do not have a name + # collision. + name = get_unique_name_wrt(name, self._used_names) + if self.input_name_to_proxy: + prev_name = next(reversed(self.input_name_to_proxy)) + node = self.input_name_to_proxy[prev_name].node + if before: + ctx = self.graph.inserting_before(node) + else: + ctx = self.graph.inserting_after(node) + else: + ctx = self.graph.inserting_before(None) + with ctx: + proxy = self.create_proxy("placeholder", name, (), {}, type_expr=type_expr) + set_example_value(proxy.node, example_value) + if self.input_name_to_proxy and before: + k, v = self.input_name_to_proxy.popitem() + self.input_name_to_proxy[name] = proxy + self.input_name_to_proxy[k] = v + else: + self.input_name_to_proxy[name] = proxy + + # For placeholder nodes, `name` is passed as a str to the target, + # and then torch.fx decides the node.name. So, record the `target` + # name as well in the _used_names to prevent any collision. + self._used_names.add(name) + + # NOTE: [Auto lift basic free symbols when create_graph_input] + # There are two sources of basic symbols: + # + # - They can come from inputs, e.g. when an input tensor is specified as dynamic. We handle + # this case by intercepting at create_graph_input. Whenever we call create_graph_input, we + # try to also lift the basic symbols in example values as graph input. + # + # 1. When create_graph_input for a tensor that has symbolic shapes, + # we look for basic symbols in its size and stride, we check if the symbol is bound + # in current graph (i.e. bound_symbols), if it's not bound, we'll create a placeholder + # for it then recursively check its parent, creates ph if not bound at parent until. + # reachting the top-level, where we require a source is attached to the proxy. + # + # 2. When create_graph_input for a tensor that contains compound exprs, + # for example, if an input to subgraph takes size [s1+s2//8], we'll look for the + # the free basic symbols in the sizes and lift all of them following 1. + # + # 3. When create_graph_input for a symint. The following invariants hold: + # a. if symint's expr is a basic symbol, we only lift it once. + # b. if symint's expr is compuned, we lift the expr as a single input. We won't lift The basic symbols + # in the compuned expr are NOT lifted. Because if the basic symbols are used inside the subgraph + # they will be lifted according to 3.a + # + # - They can come from intermediate results: + # For example, data-dependent operators such as t.item(), t.nonzero(), where basic symbols + # might be created. For this purpose, we track the basic symbols of intermediate results + # immediately after they're created at wrap_fx_proxy with track_produced_symints. Notice + # that for basic symbols that're already tracked by create_graph_input, we won't track it again. + # + # Also see NOTE: [Export inputs must be explicitly passed in] + is_strict_export = self.is_export + # Use is_exporting() (not is_compiling()) to detect non-strict + # export. is_compiling() is now also True during regular + # torch.compile sessions, but only export sets is_exporting(). + is_non_strict_export = torch.compiler.is_exporting() + if not is_strict_export and not is_non_strict_export: + if isinstance(example_value, torch.Tensor): + self._lift_basic_symbols(example_value, source) + elif isinstance(example_value, (list, tuple)): + for i, e in enumerate(example_value): + if not isinstance(e, torch.Tensor): + continue + + e_source = None + if source: + e_source = GetItemSource( + base=source, + index=i, + index_is_slice=False, + ) + + self._lift_basic_symbols(e, e_source) + + # Bound the symbol to ph if example_value is a SymInt with basic symbol. + if isinstance(example_value, torch.SymInt) and isinstance( + example_value.node.expr, sympy.Symbol + ): + self.bound_symbols[example_value.node.expr] = proxy + return proxy + + # See NOTE: [Nested SubgraphTracer and free_variable handling] for more details + def lift_tracked_freevar_to_input(self, proxy: fx.Proxy) -> LazyProxy | fx.Proxy: + # You're doing something wrong if we are the root SubgraphTracer because + # Dynamo adds tensors to graph inputs before creating a proxy for them. + if self.parent is None: + raise AssertionError( + "lift_tracked_freevar_to_input should not be called on root SubgraphTracer" + ) + + example_value = proxy.node.meta["example_value"] + + # To avoid lifting the same symbol twice, we check whether basic symbols has been tracked. + # For example, the basic symbols may have already been lifted for current subgraph when + # we automatically lift basic symbols in the sizes/strides of a tensor t. + # Suppose parent graph calls sz = t.size()[0], it creates + # a proxy in parent and the subgraph accesses sz via closure. sz's proxy is not tracked + # in current sub-tracer so we may lift the same symbol twice. + if ( + isinstance(example_value, torch.SymInt) + and example_value.node.expr in self.bound_symbols + ): + return self.bound_symbols[example_value.node.expr] + + # Proxies are associated with VariableTracker. + # It is possible that we've already lifted the Proxy to be an input. + # If that is the case, just return the already lifted Proxy. + if proxy in self.lifted_freevars: + return self.lifted_freevars[proxy] + + # We first lift proxy to parent's graph then lift to current graph's input + # so that when we bind symints of the sizes in current graph, those symints + # would already be lifted as inputs to parent graph. + if proxy.tracer != self.parent: + self.parent.lift_tracked_freevar_to_input(proxy) + + # Wrapper subclasses (e.g. DTensor) from dynamo-disabled regions may not + # have had track_produced_symints called, causing _lift_basic_symbols to + # hit "Source of 'sN' is None" when lifting inner tensor symbols. + if ( + isinstance(example_value, torch.Tensor) + and is_traceable_wrapper_subclass(example_value) + and proxy.tracer is self.parent + ): + self.parent.track_produced_symints(example_value, proxy) + + example_value = proxy.node.meta["example_value"] + type_expr = ( + type(example_value.real_obj) + if isinstance(example_value, FakeScriptObject) + else type(example_value) + ) + new_proxy = self.create_graph_input(proxy.node.name, type_expr, example_value) + self.lifted_freevars[proxy] = new_proxy + return new_proxy + + def maybe_lift_tracked_freevar_to_input(self, arg: Any) -> Any: + """ + If arg is a free variable, then lift it to be an input. + Returns the new lifted arg (if arg was a freevar), else the + original arg. + """ + if not isinstance(arg, torch.fx.Proxy): + # Note: arg can be a python built-in slice type e.g. + # x[:max_seq] is represented as get_item(t, (slice(None, max_seq, None))) + # we need to also look into the slice variable itself to lift the + # proxies there. + if isinstance(arg, slice): + return slice( + *( + self.maybe_lift_tracked_freevar_to_input(sub_arg) + for sub_arg in (arg.start, arg.stop, arg.step) + ) + ) + else: + return arg + elif arg.tracer == self: + return arg + return self.lift_tracked_freevar_to_input(arg) + + # See NOTE: [Auto lift basic free symbols when create_graph_input] for overall design + # You MUST call this API every time when creating a proxy in wrap_fx_proxy for a call + # that produced symints or tensors with unbacked symint shapes. + # This function is used to track the symints with its proxies created during + # dynamo tracing so that subgraph knows how to bind a symbol input with parent's proxy. + # LazyProxy are created for tensor shapes that're unbacked so that we don't create proxies + # for symbols that're not going to be used, the LazyProxy will be turned into a proxy + # when it's lifted as input to subgraph. + def track_produced_symints( + self, example_value: Any, e_proxy: LazyProxy | torch.fx.Proxy + ) -> None: + # When binding the symbols in an example_value, we bind the symbols + # to the proxy's associated Tracer instead of current tracer. + # This is because: + # 1. We may be calling wrap_tensors during speculate_subgraph because + # the variables are lazily realized. The proxy are top-level phs but + # current tracer is a subtracer. + # 2. For autograd.Function, we trace the backward graph with a new tracer + # whose parent is the forward tracer, but we're using all the proxies created + # in forward tracer to trace the backward. + # For example, forward calls save_for_backward for a input tensor t. + # Backward calls t.tolist(). In this case, all the proxies that backward tracer + # sees are from parent tracer (i.e. the forward tracer). (e.g. t[0].item()) + # See test_validate_outputs_unbacked for repro on 2. + tracer = e_proxy.tracer + if not isinstance(tracer, SubgraphTracer): + raise AssertionError(f"tracer must be a SubgraphTracer, got {type(tracer)}") + + def need_bind(s: Any) -> bool: + from torch.fx.experimental.symbolic_shapes import is_symbolic + + return ( + is_symbolic(s) + and isinstance(s.node.expr, sympy.Symbol) + and s.node.expr not in self.bound_symbols + ) + + def _proxy_with_example_value( + example_value: Any, *args: Any, **kwargs: Any + ) -> fx.Proxy: + # We need to insert proxy for creating sym_size/sym_stride/sym_storage right after e_proxy + nonlocal e_proxy + e_proxy = e_proxy() if isinstance(e_proxy, LazyProxy) else e_proxy + if not isinstance(e_proxy, torch.fx.Proxy): + raise AssertionError( + f"e_proxy must be an fx.Proxy, got {type(e_proxy)}" + ) + with tracer.graph.inserting_after(e_proxy.node): + proxy = tracer.create_proxy(*args, **kwargs) + set_example_value(proxy.node, example_value) + return proxy + + if isinstance(example_value, torch.Tensor): + for i, s in enumerate(example_value.size()): + if need_bind(s): + log.debug( + "track_produced_symints %s for %s.size()[%s] at debug_level %s", + s, + e_proxy, + i, + tracer.debug_level, + ) + lazy_proxy = LazyProxy( + tracer, + _proxy_with_example_value, + s, + "call_function", + torch.ops.aten.sym_size.int, + (e_proxy, i), + {}, + type_expr=type(s), + ) + self.track_produced_symints(s, lazy_proxy) + + storage_offset = example_value.storage_offset() + if need_bind(storage_offset): + log.debug( + "track_produced_symints %s for %s.storage_offset() at debug_level %s", + storage_offset, + e_proxy, + tracer.debug_level, + ) + lazy_proxy = LazyProxy( + tracer, + _proxy_with_example_value, + storage_offset, + "call_function", + torch.ops.aten.sym_storage_offset, + (e_proxy,), + {}, + type_expr=type(storage_offset), + ) + self.track_produced_symints(storage_offset, lazy_proxy) + + if example_value.layout is torch.strided: + for i, s in enumerate(example_value.stride()): + if need_bind(s): + log.debug( + "track_produced_symints %s for %s.stride()[%s] at debug_level %s", + s, + e_proxy, + i, + tracer.debug_level, + ) + lazy_proxy = LazyProxy( + tracer, + _proxy_with_example_value, + s, + "call_function", + torch.ops.aten.sym_stride.int, + (e_proxy, i), + {}, + type_expr=type(s), + ) + self.track_produced_symints(s, lazy_proxy) + + elif example_value.layout is torch.sparse_coo: + self.track_produced_symints(example_value._indices(), e_proxy) + self.track_produced_symints(example_value._values(), e_proxy) + elif example_value.layout in {torch.sparse_csr, torch.sparse_bsr}: + self.track_produced_symints(example_value.crow_indices(), e_proxy) + self.track_produced_symints(example_value.col_indices(), e_proxy) + elif example_value.layout in {torch.sparse_csc, torch.sparse_bsc}: + self.track_produced_symints(example_value.ccol_indices(), e_proxy) + self.track_produced_symints(example_value.row_indices(), e_proxy) + if is_traceable_wrapper_subclass(example_value): + attrs, ctx = example_value.__tensor_flatten__() + for attr in attrs: + inner_t = getattr(example_value, attr) + self.track_produced_symints(inner_t, getattr(e_proxy, attr)) + elif isinstance(example_value, torch.SymInt): + if need_bind(example_value): + expr = example_value.node.expr + tracer.bound_symbols[expr] = e_proxy + + # See Note [Auto lift basic free symbols when create_graph_input] + def _lift_basic_symbols( + self, example_value: torch.SymInt | torch.Tensor, src: Source | None + ) -> None: + # The before arg is for inserting symints in the sizes/strides of a tensor + # before the tensor. This ordering ensures that when we look at the tensor's + # symbols, they're already lifted/tracked. E.g. this assumption is used + # in insert_deferred_runtime_asserts. + def _lift_symbols_in_symint( + s: int | torch.SymInt, + source: Source | None, + before: bool = False, + ) -> None: + if not is_symbolic(s): + return + + if not isinstance(s, torch.SymInt): + raise AssertionError(f"s must be a SymInt, got {type(s)}") + self_to_be_bound = self.lookup_unbound_symbols(s) + if len(self_to_be_bound) == 0: + return + + # For subgraph + if self.parent is not None: + # Recursively lift symbols in symint until top-level. + self.parent._lift_basic_symbols(s, source) + for s0 in self_to_be_bound: + parent_proxy = self.parent.bound_symbols[s0] + example_val = parent_proxy.node.meta["example_value"] # type: ignore[union-attr] + if not isinstance(example_val, torch.SymInt): + raise AssertionError( + f"example_val must be a SymInt, got {type(example_val)}" + ) + ph = self.create_graph_input( + str(s0), + type(example_val), + example_val, + before=before, + source=source, + ) + log.debug( + "_lift_symbols_in_symint %s from %s at debug_level %s", + s0, + source.name if source is not None else "subgraph inputs", + self.debug_level, + ) + self.lifted_freevars[parent_proxy] = ph # type: ignore[index] + # For root_tracer: + else: + if len(self_to_be_bound) != 1: + raise AssertionError( + f"For root tracer, we only expect to bind basic symbols (compound symbols " + f"should be cached before) but got unbound symbols {self_to_be_bound} in {s}" + ) + if source is None: + raise AssertionError( + f"Source of '{s}' is None when lifting it to input of top-level. If it's an unbacked symbol, " + "this could be because it's not tracked with lazy_bind_unbacked_symbols. " + f"Otherwise, should provide a source when create_graph_input for `{s}` at root tracer." + ) + s0 = next(iter(self_to_be_bound)) + ph = self.create_graph_input( + str(s0), + type(s), + s, + before=before, + source=source, + ) + log.debug( + "_lift_symbols_in_symint %s from %s at debug_level %s", + s, + source.name if source is not None else "subgraph inputs", + self.debug_level, + ) + ph.node.meta["grapharg"] = GraphArg( + source, + s, + pass_arg_as_tensor=False, + fake_tensor=None, + is_tensor=False, + ) + + if isinstance(example_value, torch.Tensor): + for i, s in enumerate(example_value.size()): + _lift_symbols_in_symint( + s, + ( + TensorPropertySource(src, TensorProperty.SIZE, i) + if src is not None + else None + ), + before=True, + ) + if example_value.layout is torch.strided: + for i, s in enumerate(example_value.stride()): + _lift_symbols_in_symint( + s, + ( + TensorPropertySource(src, TensorProperty.STRIDE, i) + if src is not None + else None + ), + before=True, + ) + _lift_symbols_in_symint( + example_value.storage_offset(), + ( + TensorPropertySource(src, TensorProperty.STORAGE_OFFSET) + if src is not None + else None + ), + before=True, + ) + elif example_value.layout is torch.sparse_coo: + self._lift_basic_symbols(example_value._indices(), src) + self._lift_basic_symbols(example_value._values(), src) + elif example_value.layout in {torch.sparse_csr, torch.sparse_bsr}: + self._lift_basic_symbols(example_value.crow_indices(), src) + self._lift_basic_symbols(example_value.col_indices(), src) + elif example_value.layout in {torch.sparse_csc, torch.sparse_bsc}: + self._lift_basic_symbols(example_value.ccol_indices(), src) + self._lift_basic_symbols(example_value.row_indices(), src) + if is_traceable_wrapper_subclass(example_value): + attrs, ctx = example_value.__tensor_flatten__() + for attr in attrs: + inner_t = getattr(example_value, attr) + self._lift_basic_symbols( + inner_t, AttrSource(src, attr) if src is not None else None + ) + elif isinstance(example_value, torch.SymInt): + _lift_symbols_in_symint( + example_value, + src, + ) + + # Lookup the proxy in current tracer for each symbol in expressions of s, + # See Note [Auto lift basic free symbols when create_graph_input] + def lookup_unbound_symbols(self, s: torch.SymInt) -> list[sympy.Symbol]: + free_symbols = s.node.expr.free_symbols + if len(free_symbols) == 0: + return [] + + to_be_bound = [] + for s0 in free_symbols: + if s0 not in self.bound_symbols: + to_be_bound.append(s0) + continue + + proxy = self.bound_symbols[s0] + if isinstance(proxy, LazyProxy): + proxy = proxy() + self.bound_symbols[s0] = proxy + if not isinstance(proxy, torch.fx.Proxy) or proxy.tracer is not self: + raise AssertionError( + f"The proxy of symbol {s0} doesn't belong to current tracer." + ) + # Sort the symbols so that we can have a deterministic lifting order + return sorted(to_be_bound, key=lambda s: s.name) + + def has_input_mutation(self) -> MutationInfo: + input_versions_at_beginning = self._input_versions_at_beginning + input_nodes = [] + tensor_placeholder_indices = [] + + input_versions_at_end = [] + for placeholder_idx, node in enumerate(self.graph.nodes): + if node.op == "placeholder": + example_value = node.meta["example_value"] + if isinstance(example_value, torch.Tensor): + input_versions_at_end.append(example_value._version) + input_nodes.append(node) + tensor_placeholder_indices.append(placeholder_idx) + else: + break + + mutated_inputs = [ + i + for i, (v1, v2) in enumerate( + zip(input_versions_at_beginning, input_versions_at_end) + ) + if v1 != v2 + ] + + if mutated_inputs: + mutated_nodes = [input_nodes[i] for i in mutated_inputs] + mutated_input_indices = tuple( + tensor_placeholder_indices[i] for i in mutated_inputs + ) + msg = f"Input mutation detected at {mutated_nodes}" + return MutationInfo(True, msg, mutated_input_indices) + + return MutationInfo(False, "", ()) + + def has_aliasing(self) -> AliasingInfo: + from torch._dynamo.variables.higher_order_ops import get_tensor_storages + from torch._higher_order_ops.utils import _collect_fake_inputs + + input_storages: dict[StorageWeakRef, torch.fx.Node] = dict() + + for node in self.graph.nodes: + if node.op == "placeholder": + example_value = _collect_fake_inputs([node])[0] + if isinstance(example_value, torch.Tensor): + for storage in get_tensor_storages(example_value): + if storage in input_storages: + # input-input aliasing + msg = f"Input-to-input aliasing detected at nodes {input_storages[storage]} and {node}" + return AliasingInfo(True, msg) + input_storages[storage] = node + else: + break + + output_storages: dict[StorageWeakRef, torch.fx.Node] = dict() + out_nodes = self.graph.find_nodes(op="output")[0] + for out_node in pytree.tree_leaves(out_nodes.args[0]): + if out_node: + example_value = _collect_fake_inputs([out_node])[0] + if isinstance(example_value, list): + raise AssertionError("example_value must not be a list") + if isinstance(example_value, torch.Tensor): + for storage in get_tensor_storages(example_value): + if storage in output_storages: + # output-output aliasing + msg = f"Output-to-output aliasing detected at nodes {output_storages[storage]} and {out_node}" + return AliasingInfo(True, msg) + output_storages[storage] = out_node + + intersected_storages = input_storages.keys() & output_storages.keys() + if len(intersected_storages) > 0: + # input-output aliasing + aliased = [ + (input_storages[s], output_storages[s]) for s in intersected_storages + ] + aliased = ", ".join([f"{i} and {o}" for i, o in aliased]) + msg = f"Input-to-output aliasing detected at nodes {aliased}" + return AliasingInfo(True, msg) + + return AliasingInfo(False, "") + + +# NOTE: [HigherOrderOperator tracing design] +# Ignoring HigherOrderOperators for a moment, +# OutputGraph represents the graph being built by Dynamo that may be compiled +# and executed. It holds a root SubgraphTracer where the FX graph is built. +# +# HigherOrderOperators are operators that take functions as their arguments. +# When Dynamo encounters a HigherOrderOperator, then it attempts to introspect +# the function passed to it (call this the "body function"), capture it into a +# GraphModule, and rewrite the call to the HigherOrderOperator to use the +# GraphModule. +# +# The way we handle the capture of body functions is through having +# (possibly nested) SubgraphTracers, one per body function. +# +# Mechanically, we do the introspection by: +# - Creating a new SubgraphTracer via OutputGraph.subtracer +# - Executing the body function. +# This constructs the graph of the body function in the new SubgraphTracer +# while modifying the state of the OutputGraph. For example: +# - the OutputGraph can receive new GraphArgs (if we discover any new +# untracked Tensors) +# - side effects from the body function get accumulated into +# OutputGraph.side_effects +# - guards produced by the body function get accumulated into OutputGraph.guards +# +# The traced function has some special properties that make it easier for us +# to transform later down the line: +# - we lift all free variables to being inputs. +# +# If the introspection fails (due to the existence of graph breaks), then +# we roll back the current OutputGraph state and graph break on the +# HigherOrderOperator. diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/package.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/package.py new file mode 100644 index 0000000000000000000000000000000000000000..03a1007b465273a932913de8059263ae6b096e4c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/package.py @@ -0,0 +1,1299 @@ +""" +This module provides the infrastructure for creating and managing compile package +for torch.compile. We mainly have two abstractions here: + - CompilePackage: Overarching data structure for store and lookup a list of compiled codes. + - CodeCacheEntry: Data structure for a single code being compiled by torch.compile. +The caching behavior is always under user control explicitly so that a stronger guarantee can +be provided about cache hit for a specific compiled model. Users can load the compile package +from a different process or host. +""" + +import abc +import ast +import contextlib +import dataclasses +import functools +import hashlib +import importlib +import inspect +import itertools +import json +import logging +import os +import pickle +import platform +import shutil +import sys +import types +from collections.abc import Callable, Generator, Iterator +from contextlib import nullcontext +from typing import Any, NewType, Optional, TYPE_CHECKING, Union +from typing_extensions import Never + +import torch +from torch._dynamo.exc import PackageError +from torch._dynamo.graph_utils import _graph_device_type +from torch.utils.weak import WeakIdKeyDictionary + +from .bytecode_transformation import ( + COMPILED_FN_PREFIX, + get_code_keys, + is_compiled_fn_name, +) +from .utils import CleanupHook, counters, dynamo_timed, increment_frame + + +logger = logging.getLogger(__name__) + + +if TYPE_CHECKING: + from .guards import GuardManagerWrapper, GuardsState + + +_CODE_CACHE = WeakIdKeyDictionary() + + +def _code_cache(fn: Callable[..., Any]) -> Callable[..., Any]: + def _( + cls: type[Any], code: Union["SerializedCode", types.CodeType] + ) -> Union["SerializedCode", types.CodeType]: + if code in _CODE_CACHE: + return _CODE_CACHE[code] + res = fn(cls, code) + _CODE_CACHE[code] = res + return res + + return _ + + +@dataclasses.dataclass(frozen=True) +class SerializedCode: + co_argcount: int + co_posonlyargcount: int + co_kwonlyargcount: int + co_nlocals: int + co_stacksize: int + co_flags: int + co_code: bytes + co_consts: tuple[Any, ...] + co_names: tuple[str, ...] + co_varnames: tuple[str, ...] + co_filename: str + co_name: str + co_firstlineno: int + co_cellvars: tuple[str, ...] + co_freevars: tuple[str, ...] + co_linetable: bytes | None = None + co_qualname: str | None = None + co_exceptiontable: bytes | None = None + co_lnotab: str | None = None + + @classmethod + @_code_cache + def from_code_object(cls, code: types.CodeType) -> "SerializedCode": + kwargs = {key: getattr(code, key) for key in get_code_keys()} + kwargs["co_consts"] = tuple( + cls.from_code_object(c) if isinstance(c, types.CodeType) else c + for c in kwargs["co_consts"] + ) + return cls(**kwargs) + + @classmethod + @_code_cache + def to_code_object(cls, serialized_code: "SerializedCode") -> types.CodeType: + kwargs = {key: getattr(serialized_code, key) for key in get_code_keys()} + kwargs["co_consts"] = tuple( + cls.to_code_object(c) if isinstance(c, SerializedCode) else c + for c in kwargs["co_consts"] + ) + return types.CodeType( + *kwargs.values(), + ) + + +@dataclasses.dataclass +class _GuardedCodeCacheEntry: + """ + Contains the serializable information associated with a single compilation in dynamo. + To restore an execution of compiled code, we will need to serialize the following data: + - Dynamo bytecode for mapping Python inputs/outputs. + - Dynamo guards. + """ + + guards_state: bytes + dynamo_code: SerializedCode + + +def load_guards_state(guards_state: bytes) -> Any: + try: + import torch.distributed.fsdp._fully_shard._fully_shard as _fully_shard + + ctx = _fully_shard.disable_fsdp_module_new_init() + except ImportError: + ctx = nullcontext() # type: ignore[assignment] + with ctx: + return pickle.loads(guards_state) + + +def load_guard_manager( + guards_state: "GuardsState", + target_code: types.CodeType, + runtime_global_scope: Any, +) -> "GuardManagerWrapper": + from .output_graph import OutputGraphCommon + + return torch._dynamo.guards.CheckFunctionManager( + target_code, + OutputGraphCommon(guards_state.output_graph), + shape_code_parts=guards_state.shape_code_parts, + runtime_global_scope=runtime_global_scope, + guard_build_local_state=getattr(guards_state, "local_state", None), + ).guard_manager + + +_BackendId = NewType("_BackendId", str) # __compiled_fn +_FunctionId = NewType("_FunctionId", str) # __resume_at + + +def _backend_ids_from_code(code: types.CodeType) -> Iterator[_BackendId]: + for name in code.co_names: + if is_compiled_fn_name(name): + yield _BackendId(name) + for const in code.co_consts: + if isinstance(const, types.CodeType): + yield from _backend_ids_from_code(const) + + +@dataclasses.dataclass(frozen=True) +class InlinedSource: + module: str + firstlineno: int + lastlineno: int + checksum: str + content: str + + +@functools.cache +def _get_module_content(module: types.ModuleType) -> str: + return inspect.getsource(module) + + +@dataclasses.dataclass +class SourceInfo: + inlined_sources: set[InlinedSource] + + def add_code(self, code: types.CodeType) -> None: + module = inspect.getmodule(code) + if module is None: + return + sourcelines, firstlineno = inspect.getsourcelines(code) + lastlineno = firstlineno + len(sourcelines) + source = "".join(sourcelines) + if source != "".join(_get_sourcelines(module, firstlineno, lastlineno)): + raise AssertionError( + f"Source mismatch for {module.__name__} " + f"(line {firstlineno}-{lastlineno})" + ) + self.inlined_sources.add( + InlinedSource( + module=module.__name__, + firstlineno=firstlineno, + lastlineno=lastlineno, + checksum=_hash_source(source), + content=_get_module_content(module), + ) + ) + + +@dataclasses.dataclass +class _DynamoCodeCacheEntry: + """ + Contains the serializable information associated with a single code object + in dynamo. To restore an execution of compiled code, we will need the following + ingredients: + 1. The "original" code object, which serves as the entry point for eager + execution, i.e. the code only executed when there's no cache entry hit. + 2. The python module name this code object belongs to, for identifying the + enclosing global scope to inject compiled and resume functions. + 3. A list of function names that pointing to this code object. There could be + multiple function objects pointing to the same code such as recursive functions. + 4. A list of guarded code that eval frame dispatches to. + 5. A list of imported module objects unioned from all compiled branches. + 6. A list of "backends" (compiled fx graph) unioned from all compiled branches. + 7. A string path used to access the original code object users defined. + A code object can be accessed by "{python_module}.{function_name}.{code_source}" . + 8. A boolean flag indicating whether the function is installed to global scope. + 9. A boolean flag indicating whether the function has a compile id. + 10. Whether or not this code entry was bypassed + """ + + python_code: SerializedCode + python_module: str + function_names: list[_FunctionId] + guarded_codes: list[_GuardedCodeCacheEntry] + import_sources: dict[str, str] + backend_ids: list[_BackendId] + code_source: str | None + install_to_global: bool + has_compile_id: bool = False + bypassed: bool = False + + +def _lookup_code(entry: _DynamoCodeCacheEntry) -> types.CodeType: + if len(entry.function_names) != 1: + raise AssertionError( + f"Expected exactly one function name, got {len(entry.function_names)}" + ) + fn: Any = sys.modules[entry.python_module] + parts = entry.function_names[0].split(".") + for part in parts: + fn = getattr(fn, part) + if entry.code_source: + parts = entry.code_source.split(".") + for part in parts: + if part.endswith("]"): + index_begin = part.rfind("[") + if not isinstance(index_begin, int): + raise AssertionError( + f"Expected int for index_begin, got {type(index_begin)}" + ) + if index_begin < 0: + raise AssertionError( + f"Expected non-negative index_begin, got {index_begin}" + ) + attr = getattr(fn, part[:index_begin], None) + if attr is None: + raise PackageError(f"Cannot find source for code entry {entry}") + fn = attr[ast.literal_eval(part[index_begin + 1 : -1])] + else: + fn = getattr(fn, part) + else: + raise PackageError(f"Cannot find source for code entry {entry}") + if not isinstance(fn, types.CodeType): + raise AssertionError( + f"Expected CodeType, got {type(fn)} for code entry {entry}" + ) + return fn + + +def _raise_resolution_error(code: types.CodeType, scope: Any) -> Never: + raise PackageError( + f"Cannot resolve a fully qualified name for {code}. Lookup scope: {scope}" + ) + + +def _get_code_source(code: types.CodeType) -> tuple[str, str]: + """ + Given a code object, return a fully qualified name which will be used as + a serialized handle to access the code object from the new process. + This is normally a straightforward process, but there are some corner cases: + 1. When a function is defined with decorator, then this function will be captured + inside a closure with the wrapper object. + 2. When a function is defined as a nested function, then the code object will be + stored on the co_consts field of the parent code object by Python compiler. + This function handles all of the corner cases above. + """ + + module = inspect.getmodule(code) + if module is None: + raise PackageError(f"Cannot find module for code {code}") + + toplevel: Any = module + if sys.version_info >= (3, 11): + parts = code.co_qualname.split(".") + + for part in parts: + if not hasattr(toplevel, part): + _raise_resolution_error(code, toplevel) + toplevel = getattr(toplevel, part) + if inspect.isfunction(toplevel) or inspect.ismethod(toplevel): + break + seen = set() + + def _find_code_source(obj: Any) -> str | None: + nonlocal toplevel + nonlocal seen + if obj in seen: + return None + + seen.add(obj) + + if inspect.iscode(obj): + if obj is code: + return "" + + for i, const in enumerate(obj.co_consts): + if (res := _find_code_source(const)) is not None: + return f".co_consts[{i}]{res}" + + if inspect.ismethod(obj): + if (res := _find_code_source(obj.__func__)) is not None: + toplevel = obj + return f".__func__{res}" + + if inspect.isfunction(obj): + if (res := _find_code_source(obj.__code__)) is not None: + toplevel = obj + return f".__code__{res}" + if obj.__closure__ is not None: + for i, cell in enumerate(obj.__closure__): + try: + cell_contents = cell.cell_contents + except ValueError: + continue + if not ( + inspect.isfunction(cell_contents) + or inspect.iscode(cell_contents) + or inspect.ismethod(cell_contents) + ): + continue + if (res := _find_code_source(cell_contents)) is not None: + toplevel = obj + return f".__closure__[{i}].cell_contents{res}" + + if sys.version_info < (3, 11): + if inspect.ismodule(obj): + for value in obj.__dict__.values(): + if not ( + inspect.isfunction(value) + or inspect.isclass(value) + or inspect.ismethod(value) + ): + continue + if (res := _find_code_source(value)) is not None: + return res + + if inspect.isclass(obj): + for name in itertools.chain(obj.__dict__.keys(), dir(obj)): + try: + value = getattr(obj, name) + except AttributeError: + continue + if not ( + inspect.isfunction(value) + or inspect.isclass(value) + or inspect.ismethod(value) + ): + continue + if (res := _find_code_source(value)) is not None: + if value.__name__ != name: + _raise_resolution_error(code, toplevel) + return res + return None + + code_source = _find_code_source(toplevel) + if code_source is None: + _raise_resolution_error(code, toplevel) + return toplevel.__qualname__, code_source.strip(".") + + +@dataclasses.dataclass(frozen=True) +class SystemInfo: + """ + System information including Python, PyTorch, and GPU details. + This information is used to ensure compiled artifacts can only be loaded + with compatible system configurations. + """ + + python_version: str + torch_version: str + toolkit_version: str | None + triton_version: tuple[int, int] | None + gpu_name: str | None + CHECK_GPUS = ("cuda", "xpu") + + @classmethod + def current(cls) -> "SystemInfo": + """Create a SystemInfo instance with current system information.""" + # Get GPU name if CUDA or XPU is available + gpu_name = None + from torch.utils._triton import get_triton_version + + gpu_name, toolkit_version = None, None + for device_type in cls.CHECK_GPUS: + if getattr(torch, device_type).is_available(): + try: + gpu_name = getattr(torch, device_type).get_device_name() + toolkit_version = getattr(torch.version, device_type) + break + except Exception: + pass + + return cls( + python_version=platform.python_version(), + torch_version=torch.__version__, + toolkit_version=toolkit_version, + triton_version=get_triton_version((0, 0)), + gpu_name=gpu_name, + ) + + def check_compatibility( + self, other: "SystemInfo", device_type: str = "cpu" + ) -> None: + """ + Check if this SystemInfo is compatible with another SystemInfo. + Raises RuntimeError if incompatible. + """ + if self.python_version != other.python_version: + raise RuntimeError( + f"Compile package was created with a different Python version: {self.python_version}" + ) + + if self.torch_version != other.torch_version: + raise RuntimeError( + f"Compile package was created with a different PyTorch version: {self.torch_version}" + ) + if device_type in self.CHECK_GPUS: + if not getattr(torch, device_type).is_available(): + raise RuntimeError(f"{device_type} is not available") + + if self.toolkit_version != other.toolkit_version: + raise RuntimeError( + f"Compile package was created with a different toolkit version: {self.toolkit_version}" + ) + + if ( + other.triton_version != (0, 0) + and self.triton_version != other.triton_version + ): + raise RuntimeError( + f"Compile package was created with a different Triton version: {self.triton_version}" + ) + + # Check GPU name if CUDA/XPU was used + if other.gpu_name is not None and self.gpu_name != other.gpu_name: + raise RuntimeError( + f"Compile package was created with different GPU: " + f"cached={self.gpu_name}, current={other.gpu_name}" + ) + + +@dataclasses.dataclass +class _DynamoCacheEntry: + codes: list[_DynamoCodeCacheEntry] + source_info: SourceInfo + device_type: str + system_info: SystemInfo = dataclasses.field(default_factory=SystemInfo.current) + fn_name: str | None = None + fn_first_lineno: str | None = None + + @property + def backend_ids(self) -> set[_BackendId]: + return {backend_id for code in self.codes for backend_id in code.backend_ids} + + def check_versions(self) -> None: + """Check if the current system is compatible with the system used to create this cache entry.""" + current_system_info = SystemInfo.current() + self.system_info.check_compatibility(current_system_info, self.device_type) + + def debug_info(self) -> dict[str, Any]: + if len(self.codes) == 0: + raise AssertionError("Expected at least one code entry") + return { + "num_codes": str(len(self.codes)), + "fn_name": self.fn_name, + "fn_first_lineno": self.fn_first_lineno, + "device_type": self.device_type, + "backend_ids": list(self.backend_ids), + } + + +from torch.compiler._cache import ( + CacheArtifact, + CacheArtifactFactory, + CacheArtifactRecorder, +) + + +@CacheArtifactFactory.register +class PrecompileCacheArtifact(CacheArtifact): + def populate_cache(self) -> None: + DynamoCache._write_to_local_cache(self.content, self.key) + + @staticmethod + def type() -> str: + return "precompile" + + +@dataclasses.dataclass +class PrecompileCacheEntry: + """ + A full cache entry for caching precompile, for a toplevel torch.compile. + Consists of a _DynamoCacheEntry, which contains all the dynamo related contents, + and a set of backends content. In general, the backend content here will always + be of type precompile_context.BackendCacheArtifact + """ + + dynamo: _DynamoCacheEntry + backends: dict[_BackendId, Any] + + @staticmethod + def from_cache_entry( + cache_entry: _DynamoCacheEntry, backends: dict[_BackendId, Any] + ) -> Optional["PrecompileCacheEntry"]: + backend_content: dict[_BackendId, Any] = {} + + for code in cache_entry.codes: + for backend_id in code.backend_ids: + if backend_id not in backends: + logger.warning("Backend not found") + debug_str = json.dumps( + { + "entry": cache_entry.debug_info(), + "missing_backend": backend_id, + } + ) + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "dynamo_cache_bypass", + "encoding": "json", + }, + payload_fn=lambda: debug_str, + expect_trace_id=False, + ) + code.bypassed = True + break + else: + backend_content[backend_id] = backends[backend_id] + + return PrecompileCacheEntry(dynamo=cache_entry, backends=backend_content) + + +def _hash_source(source: str) -> str: + sha256_hash = hashlib.sha256() + sha256_hash.update(source.encode()) + return sha256_hash.hexdigest() + + +def _get_sourcelines( + m: types.ModuleType, firstlineno: int, lastlineno: int +) -> list[str]: + return inspect.getsourcelines(m)[0][firstlineno - 1 : lastlineno - 1] + + +def _hash_sourcelines(m: types.ModuleType, firstlineno: int, lastlineno: int) -> str: + return _hash_source("".join(_get_sourcelines(m, firstlineno, lastlineno))) + + +def _compile_frame_context( + code: types.CodeType, +) -> contextlib.AbstractContextManager[None]: + from torch._dynamo.convert_frame import get_compile_id, log_dynamo_start + from torch._guards import compile_context, CompileContext + + # Each code represents a new compile frame + # recompiles on the same frame are all saved + # under the same cache entry, so we don't have recompile ids + # i.e. If cold start had 0/0, 0/1, 1/0, 1/1, these would be + # collapsed into 0/0, 1/0 on warm. + # pyrefly: ignore [deprecated] + @contextlib.contextmanager + def _ctx() -> Iterator[None]: + increment_frame() + compile_id = get_compile_id(frame_state={}) + with ( + compile_context(CompileContext(compile_id)), + dynamo_timed( + "_compile.compile_inner", + phase_name="entire_frame_compile", + dynamo_compile_column_us="dynamo_cumulative_compile_time_us", + # TODO: save all relevant compilation metrics + metadata={ + "frame_key": str(torch._dynamo.utils.curr_frame), + "co_name": code.co_name, + "co_filename": code.co_filename, + "co_firstlineno": code.co_firstlineno, + }, + ), + ): + log_dynamo_start(code) + yield + + return _ctx() + + +class CompilePackage: + """ + CompilePackage is considered a low level component and should not be directly exposed to + end users. It has the following interface: + + 1. `CompilePackage.__init__()` which optionally takes previously serialized dynamo states. + a. when `dynamo` argument is None, it will construct a brand new CompilePackage object. + b. when `dynamo` argument is not None, it will load a pre-compiled dynamo state. + 2. `package.save()` which dumps the dynamo and backend states to a DynamoCacheEntry object. + 3. `package.install(backends) which will handle all the side-effectful global scope + updates with compiled functions and resume functions. + """ + + def __init__( + self, + fn: Callable[..., Any] | None, + dynamo: _DynamoCacheEntry | None = None, + ignore_inlined_sources: bool = False, + ) -> None: + self._innermost_fn = None + self._codes: dict[types.CodeType, _DynamoCodeCacheEntry] = {} + + self._current_entry: _DynamoCodeCacheEntry | None = None + self._installed_globals: dict[types.ModuleType, list[str]] = {} + # device_type that model compiled with. + self._device_type = "cpu" + + # For debugging/testing purpose only. + self._cached_backends: dict[_BackendId, Any] = {} + self._source_info: SourceInfo = SourceInfo(inlined_sources=set()) + self._resume_codes: set[types.CodeType] = set() + self._initialized = False + if fn is not None: + self.initialize(fn, dynamo, ignore_inlined_sources) + self.uninstall() + self.validate() + + def is_initialized(self) -> bool: + return self._initialized + + def initialize( + self, + fn: Any, + dynamo: _DynamoCacheEntry | None = None, + ignore_inlined_sources: bool = False, + ) -> None: + from .eval_frame import innermost_fn + + if self._initialized: + raise AssertionError("CompilePackage is already initialized") + self._source_info = SourceInfo(inlined_sources=set()) + self._innermost_fn = innermost_fn(fn) # type: ignore[assignment] + if self._innermost_fn is None: + raise AssertionError("innermost_fn returned None") + if dynamo is not None: + if not isinstance(dynamo, _DynamoCacheEntry): + raise AssertionError(f"Expected _DynamoCacheEntry, got {type(dynamo)}") + dynamo.check_versions() + if not ignore_inlined_sources: + for code in dynamo.source_info.inlined_sources: + m = importlib.import_module(code.module) + checksum = _hash_sourcelines(m, code.firstlineno, code.lastlineno) + if checksum != code.checksum: + raise RuntimeError( + f"Source code changes detected for {code.module} (line {code.firstlineno} - line {code.lastlineno})" + ) + + self._source_info = dynamo.source_info + + main, *codes = dynamo.codes + self._codes = {self._innermost_fn.__code__: main} + for code in codes: + self._codes[SerializedCode.to_code_object(code.python_code)] = code + else: + self._add_function( + self._innermost_fn.__code__, self._innermost_fn.__module__ + ) + self._initialized = True + + def _add_function( + self, + python_code: types.CodeType, + python_module: str, + function_name: _FunctionId | None = None, + code_source: str | None = None, + install_to_global: bool = False, + ) -> None: + if python_code not in self._codes: + code = _DynamoCodeCacheEntry( + python_code=SerializedCode.from_code_object(python_code), + python_module=python_module, + function_names=[], + guarded_codes=[], + import_sources={}, + backend_ids=[], + code_source=code_source, + install_to_global=install_to_global, + ) + self._codes[python_code] = code + else: + code = self._codes[python_code] + if code.python_module != python_module: + raise AssertionError( + f"python_module mismatch: {code.python_module} != {python_module}" + ) + if code.install_to_global != install_to_global: + raise AssertionError( + f"install_to_global mismatch: {code.install_to_global} != {install_to_global}" + ) + if code.code_source != code_source: + raise AssertionError( + f"code_source mismatch: {code.code_source} != {code_source}" + ) + + if function_name is not None: + code.function_names.append(function_name) + + @property + def cached_backends(self) -> dict[_BackendId, Any]: + return self._cached_backends + + @functools.cached_property + def source_id(self) -> str: + if self._innermost_fn is None: + raise AssertionError("_innermost_fn is not set") + return CompilePackage.source_id_from_fn(self._innermost_fn) + + def _add_user_function(self, code: types.CodeType) -> None: + function_name, code_source = _get_code_source(code) + module = inspect.getmodule(code) + if module is None: + raise PackageError(f"Cannot find module for code {code}") + self._add_function( + code, + module.__name__, + function_name=_FunctionId(function_name), + code_source=code_source, + ) + + @contextlib.contextmanager + def code_context(self, code: types.CodeType) -> Generator[None, None, None]: + if self._current_entry is not None: + raise AssertionError("_current_entry is already set in code_context") + + # Sometimes user code cannot be inlined in dynamo resulting in extra user code + # being compiled. We should record these as when they are actually invoked. + if code not in self._codes: + self._add_user_function(code) + + entry = self._codes[code] + self._current_entry = entry + try: + yield + finally: + entry.has_compile_id = True + self._current_entry = None + + def add_guarded_code( + self, + guards_state: bytes, + dynamo_code: types.CodeType, + ) -> None: + if self._current_entry is None: + raise AssertionError("_current_entry is not set in add_guarded_code") + if self._current_entry.bypassed: + return + guarded_code_entry = _GuardedCodeCacheEntry( + guards_state=guards_state, + dynamo_code=SerializedCode.from_code_object(dynamo_code), + ) + self._current_entry.guarded_codes.append(guarded_code_entry) + for backend_id in _backend_ids_from_code(dynamo_code): + self._add_backend_id(backend_id) + + def add_inlined_source(self, sources: list[types.CodeType]) -> None: + if self._current_entry is None: + raise AssertionError("_current_entry is not set in add_inlined_source") + if self._current_entry.bypassed: + return + for code in sources: + if code in self._resume_codes: + continue + self._source_info.add_code(code) + + def update_device_type(self, graph: torch.fx.Graph | None) -> None: + self._device_type = _graph_device_type(graph) + + def bypass_current_entry(self) -> None: + if self._current_entry is None: + raise AssertionError("_current_entry is not set in bypass_current_entry") + self._current_entry.bypassed = True + + def add_resume_function( + self, + python_code: types.CodeType, + python_module: str, + function_name: str, + ) -> None: + self._add_function( + python_code, + python_module, + function_name=_FunctionId(function_name), + install_to_global=True, + ) + self._resume_codes.add(python_code) + + def add_import_source(self, alias: str, module_name: str) -> None: + if self._current_entry is None: + raise AssertionError("_current_entry is not set in add_import_source") + self._current_entry.import_sources[alias] = module_name + + def _add_backend_id( + self, backend_id: _BackendId, backend: Any | None = None + ) -> None: + if self._current_entry is None: + raise AssertionError("_current_entry is not set in add_backend_id") + if backend_id not in self._current_entry.backend_ids: + self._current_entry.backend_ids.append(backend_id) + if backend is not None: + self._cached_backends[backend_id] = backend + + def add_backend_id(self, backend_id: str, backend: Any | None = None) -> None: + if not backend_id.startswith(f"{COMPILED_FN_PREFIX}_"): + raise AssertionError( + f"backend_id must start with '{COMPILED_FN_PREFIX}_', got '{backend_id}'" + ) + self._add_backend_id(_BackendId(backend_id), backend) + + def validate(self) -> None: + if self._current_entry is not None: + raise AssertionError("_current_entry should be None during validate") + if self._innermost_fn is None: + raise AssertionError("_innermost_fn is not set during validate") + if not self._initialized: + raise AssertionError("CompilePackage is not initialized during validate") + if next(iter(self._codes)) is not self._innermost_fn.__code__: + raise AssertionError( + "First code entry does not match _innermost_fn.__code__" + ) + + def _install_global(self, module: types.ModuleType, name: str, value: Any) -> None: + # A pre-reset compile in this process may still own `name` via a + # CleanupHook that hasn't fired yet. We're taking over the binding now, + # so that hook must not delete it once its code object is collected. + CleanupHook.disown(module.__dict__, name) + module.__dict__[name] = value + self._installed_globals.setdefault(module, []).append(name) + + def uninstall(self) -> None: + from torch._C._dynamo.eval_frame import _reset_precompile_entries + + if self._innermost_fn is None: + raise AssertionError("_innermost_fn is not set in uninstall") + for module, names in self._installed_globals.items(): + for name in names: + module.__dict__.pop(name, None) + + self._installed_globals = {} + + _reset_precompile_entries(self._innermost_fn.__code__) + + def install(self, backends: dict[_BackendId, Any]) -> None: + """ + Sync the package states to the compiled function. This includes the following actions: + 1. Clean up the previously installed states. + 2. Install the compiled functions to global scopes. + 3. Install the precompiled cache entries to ExtraStates on the code object. + """ + from torch._C._dynamo.eval_frame import _load_precompile_entry + + from .convert_frame import input_codes + from .output_graph import get_builtins_dict + + self.uninstall() + for code, entry in self._codes.items(): + context = ( + _compile_frame_context(code) + if entry.has_compile_id + else contextlib.nullcontext() + ) + with context: + module = sys.modules[entry.python_module] + for alias, module_name in entry.import_sources.items(): + self._install_global( + module, alias, importlib.import_module(module_name) + ) + target_code = code + if entry.install_to_global: + for function_name in entry.function_names: + if code.co_freevars: + # Resume functions with freevars need a factory + # that takes a closure tuple, matching + # install_resume_function_global in output_graph.py. + f_globals = module.__dict__ + fn_name = function_name + + def _make_fn( + closure: tuple[types.CellType, ...], + _code: types.CodeType = code, + _globals: dict[str, Any] = f_globals, + _name: str = fn_name, + ) -> types.FunctionType: + return types.FunctionType( + _code, _globals, _name, None, closure + ) + + self._install_global(module, function_name, _make_fn) + else: + fn = types.FunctionType( + code, module.__dict__, function_name + ) + self._install_global(module, function_name, fn) + if entry.code_source: + target_code = _lookup_code(entry) + + if entry.bypassed: + # If the entry is bypassed, do not install backends + # or guarded codes. + continue + + input_codes.add(target_code) + for backend_id in entry.backend_ids: + if backend_id not in backends: + raise RuntimeError( + f"Backend {backend_id} is not found in the given backends" + ) + with dynamo_timed( + "after_deserialization", phase_name="backend_compile" + ): + backend = backends[backend_id].after_deserialization() + self._install_global( + module, + backend_id, + torch._dynamo.disable(backend), + ) + + if len(entry.guarded_codes) == 0: + # Dynamo generates empty graph for trivial functions, should just skip them + # in these cases. + torch._dynamo.eval_frame.skip_code(target_code) + + for guarded_code in entry.guarded_codes: + with dynamo_timed("precompile_load_guards"): + guards_state = load_guards_state(guarded_code.guards_state) + runtime_global_scope = sys.modules[entry.python_module].__dict__ + # The installed builtins dict might be absent from the runtime + # while loading guards. Populate it if it's missing. + if ( + builtin_dict_name + := guards_state.output_graph.name_of_builtins_dict_key_in_fglobals + ): + # A pre-reset compile's CleanupHook may still own this + # name even when we're about to leave its value alone + # below (same dict object every compile in this + # module), so it must not delete it once collected. + CleanupHook.disown(runtime_global_scope, builtin_dict_name) + builtins_dict = get_builtins_dict(runtime_global_scope) + if builtin_dict_name in runtime_global_scope: + if ( + runtime_global_scope[builtin_dict_name] + is not builtins_dict + ): + raise AssertionError( + f"Builtins dict mismatch for key '{builtin_dict_name}'" + ) + else: + runtime_global_scope[builtin_dict_name] = builtins_dict + if not isinstance(guards_state, torch._dynamo.guards.GuardsState): + raise AssertionError( + f"Expected GuardsState, got {type(guards_state)}" + ) + with dynamo_timed("precompile_build_guards"): + guard_manager = load_guard_manager( + guards_state, target_code, runtime_global_scope + ) + _load_precompile_entry( + target_code, + guard_manager, + SerializedCode.to_code_object(guarded_code.dynamo_code), + ) + + def cache_entry(self) -> _DynamoCacheEntry: + self.validate() + if self._innermost_fn is None: + raise AssertionError("_innermost_fn is not set in cache_entry") + return _DynamoCacheEntry( + codes=list(self._codes.values()), + source_info=self._source_info, + device_type=self._device_type, + fn_name=self._innermost_fn.__qualname__, + fn_first_lineno=self._innermost_fn.__code__.co_firstlineno, + ) + + @staticmethod + def source_id_from_fn(fn: Callable[..., Any]) -> str: + from .eval_frame import innermost_fn + + innermost_fn_ = innermost_fn(fn) + + sha256_hash = hashlib.sha256() + sha256_hash.update(innermost_fn_.__qualname__.encode()) + sha256_hash.update(str(innermost_fn_.__code__.co_firstlineno).encode()) + return sha256_hash.hexdigest() + + +_Backends = dict[_BackendId, Any] + + +class DynamoStore(abc.ABC): + """ + A DynamoStore tracks active CompilePackages, and provides methods to store and retrieve them. + + This is an abstract base class for different storage implementations. + """ + + def record_package(self, package: CompilePackage) -> None: + """ + Records a package to PrecompileContext, so that it can be serialized later. + """ + from torch._dynamo.precompile_context import PrecompileContext + + cache_entry = package.cache_entry() + PrecompileContext.record_dynamo_cache_entry( + cache_entry=cache_entry, key=package.source_id + ) + + def record_eager_backend(self, backend_id: _BackendId, backend: Any) -> None: + """ + Records eager fx graphs to PrecompileContext for testing purposes. + """ + from torch._dynamo.precompile_context import ( + EagerCacheArtifact, + PrecompileContext, + ) + + result = EagerCacheArtifact(key=backend_id, content=backend) + PrecompileContext.record_artifact(result) + + @abc.abstractmethod + def clear(self) -> None: ... + + @abc.abstractmethod + def write( + self, + cache_entry: PrecompileCacheEntry, + path: str, + ) -> None: + """ + Abstract method to write dynamo cache entry and backends to storage. + + Args: + dynamo: The dynamo cache entry to write + backends: Dictionary of backend content to write + path: Path or key to identify where to write the data + """ + ... + + def save_cache_entry(self, cache_entry: _DynamoCacheEntry, key: str) -> None: + """ + Saves a package to a given path. Grabs backends from PrecompileContext. + """ + from torch._dynamo.precompile_context import ( + BackendCacheArtifact, + PrecompileContext, + ) + + backend_content: _Backends = {} + for backend_id in cache_entry.backend_ids: + serialized_backend = PrecompileContext.serialize_artifact_by_key(backend_id) + if serialized_backend is None: + raise RuntimeError( + f"Backend {backend_id} is not found in the given backends" + ) + if not isinstance(serialized_backend, BackendCacheArtifact): + raise AssertionError( + f"Expected BackendCacheArtifact, got {type(serialized_backend)}" + ) + backend_content[backend_id] = serialized_backend + + entry = PrecompileCacheEntry(cache_entry, backend_content) + + self.write(entry, key) + + def save_package(self, package: CompilePackage, key: str) -> None: + """ + Saves a package to a given path. Grabs backends from PrecompileContext. + """ + self.record_package(package) + cache_entry = package.cache_entry() + self.save_cache_entry(cache_entry, key) + + @abc.abstractmethod + def read(self, path: str) -> PrecompileCacheEntry: + """ + Abstract method to read dynamo cache entry and backends from storage. + + Args: + path: Path or key to identify where to read the data from + + Returns: + A tuple containing (dynamo_cache_entry, backend_content) + """ + ... + + def load_cache_entry(self, key: str) -> PrecompileCacheEntry: + from torch._dynamo.precompile_context import ( + BackendCacheArtifact, + PrecompileContext, + ) + + precompile_entry = self.read(key) + for backend in precompile_entry.backends.values(): + if not isinstance(backend, BackendCacheArtifact): + raise AssertionError( + f"Expected BackendCacheArtifact, got {type(backend)}" + ) + PrecompileContext.record_artifact(backend) + + return precompile_entry + + def load_package( + self, fn: Any, key: str + ) -> tuple[CompilePackage, dict[_BackendId, Any]]: + """ + Loads a package from a given path and returns it plus a list of deserialized backends + """ + entry = self.load_cache_entry(key) + package = CompilePackage(fn, entry.dynamo) + return package, entry.backends + + +class InMemoryDynamoStore(DynamoStore): + """ + A DynamoStore implementation that keeps state about CompilePackages in memory. + """ + + def __init__(self) -> None: + self.packages: dict[str, PrecompileCacheEntry] = {} + + def clear(self) -> None: + self.packages.clear() + + def write( + self, + cache_entry: PrecompileCacheEntry, + path: str, + ) -> None: + """ + Store the dynamo cache entry and backends in memory instead of writing to disk. + """ + self.packages[path] = cache_entry + + def read(self, path: str) -> PrecompileCacheEntry: + """ + Read dynamo cache entry and backends from memory. + """ + if path not in self.packages: + raise RuntimeError(f"No package found with key {path}") + + return self.packages[path] + + +class DiskDynamoStore(DynamoStore): + """ + A DynamoStore implementation that keeps state about CompilePackages on disk. + """ + + def __init__(self, path_prefix: str = "") -> None: + """ + Initialize a DiskDynamoStore with a path prefix. + + Args: + path_prefix: Prefix directory for where to put CompilePackages on disk + """ + self._path_prefix = path_prefix + + def path_prefix(self) -> str: + return self._path_prefix + + def clear(self) -> None: + """ + Clear all CompilePackages from disk. + """ + if self.path_prefix(): + shutil.rmtree(self.path_prefix(), ignore_errors=True) + + def write( + self, + cache_entry: PrecompileCacheEntry, + path: str, + ) -> None: + """ + Write dynamo cache entry and backends to disk. + """ + try: + pickled_content: bytes = pickle.dumps(cache_entry) + CacheArtifactRecorder(PrecompileCacheArtifact.type(), path).record( + pickled_content + ) + self._write_to_local_cache(pickled_content, path) + except Exception as e: + raise RuntimeError(f"Failed to save package to {path}: {e}") from e + + def _write_to_local_cache(self, pickled_content: bytes, path: str) -> None: + from torch._inductor.codecache import write_atomic + + path = os.path.join(self.path_prefix(), path) if self.path_prefix() else path + try: + os.makedirs(path, exist_ok=True) + write_atomic(os.path.join(path, "entry"), pickled_content) + except Exception as e: + raise RuntimeError(f"Failed to save package to {path}: {e}") from e + + def read(self, path: str) -> PrecompileCacheEntry: + """ + Read dynamo cache entry and backends from disk. + """ + path = os.path.join(self.path_prefix(), path) if self.path_prefix() else path + try: + with open(os.path.join(path, "entry"), "rb") as f: + pickled_content = f.read() + entry = pickle.loads(pickled_content) + return entry + except Exception as e: + raise RuntimeError(f"Failed to load package from path {path}: {e}") from e + + +class DiskDynamoCache(DiskDynamoStore): + """ + Special DiskDynamoStore which adds some helper functions for automatically + tracking paths of packages + """ + + def save(self, package: CompilePackage) -> None: + """ + Saves a package to a given path. Grabs backends from PrecompileContext. + """ + key = package.source_id + logger.info("Saving CompilePackage for %s", package.source_id) + super().save_package(package, key) + + def load(self, fn: Callable[..., Any]) -> PrecompileCacheEntry | None: + """ + Loads a package from a given path and returns it plus a list of deserialized backends + """ + key = CompilePackage.source_id_from_fn(fn) + logger.info("Loading CompilePackage for %s", key) + path = os.path.join(self.path_prefix(), key) + if os.path.exists(path): + try: + result = super().load_cache_entry(key) + counters["dynamo_cache"]["dynamo_cache_hit"] += 1 + return result + except Exception: + counters["dynamo_cache"]["dynamo_cache_error"] += 1 + logger.warning("Failed to load package from path %s", exc_info=True) + return None + logger.info("No package found for %s", key) + counters["dynamo_cache"]["dynamo_cache_miss"] += 1 + return None + + def load_and_install_package(self, fn: Callable[..., Any]) -> CompilePackage | None: + """ + Load directly into a package and install backends + """ + results = self.load(fn) + if results is None: + return None + else: + package = CompilePackage(fn, results.dynamo) + package.install(results.backends) + return package + + def path_prefix(self) -> str: + return os.path.join(cache_dir(), "dynamo") + + +def cache_dir() -> str: + from torch._inductor.runtime.cache_dir_utils import cache_dir + + return cache_dir() + + +DynamoCache = DiskDynamoCache(os.path.join(cache_dir(), "dynamo")) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/pgo.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/pgo.py new file mode 100644 index 0000000000000000000000000000000000000000..1437a3e931fb37718d244436bbdad4d5e93e79dc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/pgo.py @@ -0,0 +1,1093 @@ +""" +Profile Guided Optimization (PGO) implementation for Dynamo. + +This module provides functionality for caching and managing code state profiles +that guide optimization decisions in Dynamo. It implements both local and remote +caching mechanisms for storing profile information across runs, handles profile +merging across distributed ranks, and manages the lifecycle of profile data +during compilation. The profiles track dynamic vs static properties of tensors +and help Dynamo make better specialization decisions. +""" + +from __future__ import annotations + +import base64 +import copy +import dataclasses +import enum +import functools +import logging +import os +import pickle +import re +import zlib +from collections import defaultdict +from typing import TYPE_CHECKING, TypeVar +from typing_extensions import override, Self + +import torch._dynamo.config +import torch._utils_internal +import torch.compiler.config +import torch.distributed as dist +from torch._dynamo.utils import ( + CompileEventLogger, + dynamo_timed, + set_feature_use, + warn_once, +) +from torch._environment import is_fbcode +from torch._logging._internal import trace_structured_artifact +from torch.compiler._cache import ( + CacheArtifact, + CacheArtifactFactory, + CacheArtifactRecorder, +) +from torch.utils._ordered_set import OrderedSet + + +if TYPE_CHECKING: + import types + + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + from torch._inductor.remote_cache import JsonDataTy, RemoteCache + + +class ReservedWorkflowIdUserError(ValueError): + pass + + +log = logging.getLogger(__name__) +symbolic_shape_log = logging.getLogger("torch.fx.experimental.symbolic_shapes") + +LOCK_TIMEOUT = 10 + +# How does in memory representation work? Concretely, this module is +# responsible for holding GLOBAL state representing the state it holds, no +# other copies permitted. So we retire frame_state entirely and store it +# here. This should be reset when Dynamo is reset. We never GC information +# (similar to how the filesystem doesn't get cleaned up except by tmp +# cleaner), so the expectation is the information is relatively cheap and we +# don't mind leaking it. + + +# How exactly did we design the cache key? Here are some of the questions: +# +# - JOB_ID: Do we have a unique identifier for the "training run" (such that +# it stays the same if we're running the same code, and changes if we're +# running something different). +# +# - RANK: Are we sharing the cache across ranks, or does each rank get +# an individual cache? +# +# We choose to require job_id for PGO cache. This is to prevent +# situations where unrelated invocations of PyTorch unpredictably cause +# changes to each other's behavior. With a job_id, at least you know there +# is some "state" associated with it. (State dict might be another way to +# tell if a run is related or not.) You can opt-in to YOLO everything +# aliases everything by passing a shared job_id for all your invocations. +# +# We choose to NOT share PGO cache across ranks. With no RANK_SHARING, there +# is never contention between runs, so we can leisurely update a bundle with +# information we need. Because we are grouped by job_id, we can have a single +# consolidated bundle for everything (or not; maybe worry about O(n^2) IO if +# we updated every compile--let's just instrument this.) Can even take a +# filelock for extra safety (expect no contention); expect 50ns overhead from +# uncontended filelock. +# +# If we did share ranks, everyone is storming to modify the same cache files. +# We can do this by having folks atomic write to a CAS-store and then having +# readers do on-the-fly merging (this can be implemented in remote using +# prefix iteration). As an optional optimization, one rank can be elected to +# handling bundling post facto (ideally, this is done async, after quiescence, +# without compiler collective need to wait for everyone to finish writing +# their bits.) Not sure how you can avoid a listdir because if some rank shows +# up with some new entries we need to pull them in ASAP (unless you want to +# delay bundling). +# +# But compiler collectives fill a similar niche: compilers chat with each +# other so rank 0 has collected everything. So elect rank 0 only to write the +# bundle. Don't even need CAS-store atomic write; just one rank writing an +# updating bundles. The point is that use compiler collectives to share +# profiles across ranks, but use the PGO cache to persist profiles per rank +# across attempts. No need to have one mechanism to do everything. + + +@functools.cache +def _hash_containing_file(filepath: str) -> str: + # if the file does not exist we consider filepath to be the hash. + if not os.path.exists(filepath): + return filepath + + with open(filepath, "rb") as file: + content = file.read() + crc32_value = zlib.crc32(content) + hash = format(crc32_value & 0xFFFFFFFF, "08x") + return hash + + +def _get_closure_content(content: types.CellType) -> object: + if callable(content) and hasattr(content, "__code__"): + return content.__code__ + return None + + +def _get_cell_hash_content(content: types.CellType) -> object: + # Safely extract cell contents without blowing up the entire tuple hash + try: + return _get_closure_content(content.cell_contents) + except ValueError: + return None + + +@dataclasses.dataclass(frozen=True) +class CodeId: + filename: str + firstlineno: int + name: str + # When a job restart, the code can be copied to a different path than the previous attempt. In that case + # self.filename will have a different value, we do not want to consider those differences. Instead we + # hash the content of the file and use it as an identifier of the file. + # + # self.filename is kept in the object to give readable information/pointer to the actual file, in a local + # code state it will refer to the first seen file path. + file_hash: str + closure_hash: int | None = None + + # Exclude file name. + def __eq__(self, other: object) -> bool: + if not isinstance(other, CodeId): + return False + return ( + self.file_hash == other.file_hash + and self.firstlineno == other.firstlineno + and self.name == other.name + and self.closure_hash == other.closure_hash + ) + + # Ensure if two CodeIds are the same, then they have the same hash by excluding filename. + def __hash__(self) -> int: + return hash((self.file_hash, self.name, self.firstlineno, self.closure_hash)) + + def __str__(self) -> str: + return f"hash({self.file_hash}){self.filename}:{self.firstlineno}:{self.name}" + + @staticmethod + def make( + code: types.CodeType, closure: tuple[types.CellType, ...] | None = None + ) -> CodeId: + closure_hash = None + if closure: + closure_hash = hash(tuple(_get_cell_hash_content(c) for c in closure)) + + return CodeId( + code.co_filename, + code.co_firstlineno, + code.co_name, + _hash_containing_file(code.co_filename), + closure_hash, + ) + + +@dataclasses.dataclass +class CodeState: + automatic_dynamic: defaultdict[str, FrameStateSizeEntry] = dataclasses.field( + default_factory=lambda: defaultdict(FrameStateSizeEntry) + ) + + +_INIT_CODE_STATE: defaultdict[CodeId, CodeState] | None = None +_CODE_STATE: defaultdict[CodeId, CodeState] | None = None +_LOGGED_DYNAMIC_ALLOWLIST: bool = False +_KNOWN_DYNAMIC_SOURCES: set[str] = set() + + +@dataclasses.dataclass(frozen=True) +class InferStride: + """ + Denotes the quantity stride[dim] * size[dim], which is what the stride would + be for the next physical dimension that results in a contiguous layout. + + For example, given size = [2, 3], stride = [3, 1], we can replace this with + stride = [InferStride(1), 1], because InferStride(1) = stride[1] * size[1] = 1 * 3 = 3 + + Indirecting the representation in this way is important for the join operation + on strides as if we join [2, 3][3, 1] and [2, 4][4, 1], + we don't want [2, None][None, 1] which would get eventually symbolized into + [2, s0][s1, 1] (notice that the relationship between s0 and s1 is broken). + If we instead rewrite the expressions as InferStride so we have [2, 3][InferStride(1), 1] + and [2, 4][InferStride(1), 1] we now join to [2, None][InferStride(1), 1] will + result in [2, s0][s0, 1], as desired. + """ + + dim: int + + +_T = TypeVar("_T") + + +class AutoUnset(enum.Enum): + """ + The identity element of our semilattice, a generic "don't know" element that + is always subsumed when we get more information. + """ + + token = 0 + + +auto_unset = AutoUnset.token + + +class AutoDynamic(enum.Enum): + """ + The top element of our (bounded) semilattice, whenever you merge this with + any other element you always get it again + """ + + token = 0 + + +auto_dynamic = AutoDynamic.token + + +@dataclasses.dataclass +class FrameStateSizeEntry: + scalar: int | AutoDynamic | AutoUnset = dataclasses.field(default=auto_unset) + # NB: We don't have cases where we have a known dimensionality but + # we know NOTHING about the individual sizes + size: AutoDynamic | AutoUnset | tuple[int | AutoDynamic, ...] = dataclasses.field( + default=auto_unset + ) + stride: AutoDynamic | AutoUnset | tuple[int | AutoDynamic | InferStride, ...] = ( + dataclasses.field(default=auto_unset) + ) + excluded_sizes: tuple[int | None, ...] | None = dataclasses.field( + default=None, compare=False + ) + excluded_scalar: int | None = dataclasses.field(default=None, compare=False) + + def render(self) -> str: + # Special cases + def render_single(s: int | AutoDynamic | AutoUnset | InferStride) -> str: + if s is auto_dynamic: + return "?" + elif s is auto_unset: + # This basically shouldn't happen, this is for debugging + return "auto unset" + elif isinstance(s, InferStride): + return f"S({s.dim})" + else: + return str(s) + + def render_tuple(ss: tuple[int | AutoDynamic | InferStride, ...]) -> str: + return "[" + ", ".join(render_single(s) for s in ss) + "]" + + # Common cases + if self.size is auto_dynamic and self.stride is auto_dynamic: + if self.scalar is auto_dynamic: + return "fully dynamic scalar or tensor" + else: + return f"scalar {self.scalar}" + elif self.scalar is auto_dynamic: + if isinstance(self.size, tuple) and isinstance(self.stride, tuple): + return f"tensor size={render_tuple(self.size)} stride={render_tuple(self.stride)}" + + # Fallback + return f"unusual {repr(self)}" + + def __post_init__(self) -> None: + if isinstance(self.scalar, torch.SymInt): + raise AssertionError(self.scalar) + if isinstance(self.size, tuple): + for s in self.size: + if isinstance(s, torch.SymInt): + raise AssertionError(s) + if isinstance(self.stride, tuple): + for s1 in self.stride: + if isinstance(s1, torch.SymInt): + raise AssertionError(s1) + + def is_size_dynamic(self, dim: int) -> bool: + if self.size is auto_dynamic: + return True + if self.size is auto_unset: + return False + return self.size[dim] is auto_dynamic + + def is_stride_dynamic(self, dim: int) -> bool: + # At the moment, dynamic strides is a bit buggy. Good test case + # here is `PYTORCH_TEST_WITH_DYNAMO=1 python test/test_autograd.py + # TestAutograd.test_gradcheck_jacobian_mismatch` + # + # This if statement preserves historical behavior, which is that we + # ONLY make strides dynamic if the size is exactly static everywhere. + # We could potentially relax this but in general we should be very + # careful about when to infer dynamic strides. + # + # Actually, the existing algorithm is already somewhat problematic. + # Suppose a tensor that is sometimes: + # f32[2, 3, 5][15, 5, 1] and other times + # f32[2, 3, 5][5, 10, 1] (specifically, dim 0 and 1 are physically transposed). + # If we infer strides should be (DYNAMIC, DYNAMIC, 1). But this is + # silly: we really should have just guarded on dim order. + if not ( + isinstance(self.size, tuple) and all(type(s) is int for s in self.size) + ): + return False + if self.stride is auto_dynamic: + return True + if self.stride is auto_unset: + return False + return self.stride[dim] is auto_dynamic + + @staticmethod + def _munge_symint(xs: tuple[int, ...]) -> tuple[AutoDynamic | int, ...]: + return tuple(auto_dynamic if isinstance(x, torch.SymInt) else x for x in xs) + + @classmethod + def make_scalar(cls, x: int) -> FrameStateSizeEntry: + return FrameStateSizeEntry(scalar=x, size=auto_dynamic, stride=auto_dynamic) + + @classmethod + def make_tensor( + cls, size: tuple[int, ...], stride: tuple[int, ...] + ) -> FrameStateSizeEntry: + return FrameStateSizeEntry( + scalar=auto_dynamic, + size=cls._munge_symint(size), + stride=cls._munge_symint(stride), + ) + + @classmethod + def make_size(cls, size: tuple[int, ...]) -> FrameStateSizeEntry: + return FrameStateSizeEntry( + scalar=auto_unset, + size=cls._munge_symint(size), + stride=auto_unset, + ) + + @staticmethod + def _merge_atom(x: _T, y: _T) -> AutoDynamic | _T: + if x is auto_unset: + return y + if y is auto_unset: + return x + if x is auto_dynamic or y is auto_dynamic or x != y: + return auto_dynamic + return x + + @classmethod + def _merge_atom_tup( + cls, + xs: AutoDynamic | AutoUnset | tuple[_T, ...], + ys: AutoDynamic | AutoUnset | tuple[_T, ...], + ) -> AutoDynamic | AutoUnset | tuple[AutoDynamic | _T, ...]: + if xs is auto_unset: + return ys + if ys is auto_unset: + return xs + if xs is auto_dynamic or ys is auto_dynamic: + return auto_dynamic + if len(xs) != len(ys): + return auto_dynamic + return tuple(cls._merge_atom(x, y) for x, y in zip(xs, ys)) + + def __ior__(self, other: Self) -> Self: + # Record current static sizes before merge. For dims that become + # dynamic, the exclusion guard will reject these values so inputs + # fall through to the earlier, more specialized cache entry. + # Already-dynamic dims become None and are ignored by the guard. + # When no dim transitions, clear stale excluded_sizes so later + # compilations don't inherit exclusions from earlier transitions. + new_size = self._merge_atom_tup(self.size, other.size) + if isinstance(self.size, tuple): + if new_size != self.size: + self.excluded_sizes = tuple( + s if type(s) is int else None for s in self.size + ) + elif self.excluded_sizes is not None: + self.excluded_sizes = None + self.size = new_size + # Same idea for scalars: record the static value about to become dynamic. + # Re-derive like excluded_sizes: only set when transitioning from a + # concrete int, clear when already dynamic. + if ( + type(self.scalar) is int + and type(other.scalar) is int + and self.scalar != other.scalar + ): + self.excluded_scalar = self.scalar + elif self.scalar is auto_dynamic and self.excluded_scalar is not None: + self.excluded_scalar = None + self.scalar = self._merge_atom(self.scalar, other.scalar) + self.stride = self._merge_atom_tup(self.stride, other.stride) + return self + + +def update_automatic_dynamic( + tx: InstructionTranslatorBase, + name: str, + entry: FrameStateSizeEntry, + *, + is_unspecialized_nn_module: bool = False, +) -> FrameStateSizeEntry: + code_id = CodeId.make(tx.f_code, tx.closure) + frame_state = get_code_state()[code_id] + if torch._dynamo.config.automatic_dynamic_shapes: + is_update = name in frame_state.automatic_dynamic + mut_entry = frame_state.automatic_dynamic[name] + old_entry = copy.copy(mut_entry) + mut_entry |= entry + + # Do some logs (damn, I spend more code logging than I do actually doing + # the updates lol) + if is_update and old_entry.scalar != mut_entry.scalar: + symbolic_shape_log.info( + "marking %s as dynamic (from automatic dynamic/PGO)", + name, + ) + log.debug( + "automatic dynamic int %s val %s != %s", + name, + entry.scalar, + old_entry.scalar, + ) + CompileEventLogger.instant( + "automatic_dynamic", + { + "name": name, + "dim_changed": "scalar", + "reason": "scalar change", + "cached": str(old_entry.scalar), + "new": str(entry.scalar), + }, + ) + if is_unspecialized_nn_module: + log.info( + "%s is converted to a symbolic integer. It is an attribute of a " + "user defined nn module class. If you wish to keep it static, you can " + "mark the nn module class as `torch._dynamo.mark_static`.", + name, + ) + + def log_tup( + tup_name: str, short_reason: str, long_reason: str, i: int | None = None + ) -> None: + entry_tup = ( + getattr(entry, tup_name) if i is None else getattr(entry, tup_name)[i] + ) + old_entry_tup = ( + getattr(old_entry, tup_name) + if i is None + else getattr(old_entry, tup_name)[i] + ) + symbolic_shape_log.info( + "marking %s as dynamic (from automatic dynamic/PGO)", + name, + ) + log.debug( + "automatic dynamic %s %s %s %s != %s", + tup_name, + name, + short_reason, + # NB: We used to only report len(...) here for dim mismatch + entry_tup, + old_entry_tup, + ) + CompileEventLogger.instant( + "automatic_dynamic", + { + "name": name, + "dim_changed": "all" if i is None else i, + "reason": long_reason, + "cached": str(old_entry_tup), + "new": str(entry_tup), + }, + ) + + if is_update and old_entry.size != mut_entry.size: + if isinstance(old_entry.size, tuple) and isinstance(entry.size, tuple): + if len(old_entry.size) != len(entry.size): + log_tup("size", "dim", "dimensionality change") + else: + for i in range(len(entry.size)): + if old_entry.size[i] != entry.size[i]: + log_tup("size", f"size({i})", "size change", i) + else: + log_tup("size", "other", "other") + + if is_update and old_entry.stride != mut_entry.stride: + if isinstance(old_entry.stride, tuple) and isinstance(entry.stride, tuple): + if len(old_entry.stride) != len(entry.stride): + log_tup("stride", "dim", "dimensionality change") + else: + for i in range(len(entry.stride)): + if old_entry.stride[i] != entry.stride[i]: + log_tup("stride", f"stride({i})", "stride change", i) + else: + log_tup("stride", "other", "other") + else: + old_entry = frame_state.automatic_dynamic[name] + log.debug( + "automatic dynamic is off, overwriting int %s val %s -> %s", + name, + old_entry.scalar, + entry.scalar, + ) + frame_state.automatic_dynamic[name] = entry + mut_entry = entry + + return mut_entry + + +def process_automatic_dynamic( + tx: InstructionTranslatorBase, + name: str, + entry: FrameStateSizeEntry, + *, + is_unspecialized_nn_module: bool = False, +) -> FrameStateSizeEntry: + if (st := tx.distributed_state) is None: + return update_automatic_dynamic( + tx, + name, + entry, + is_unspecialized_nn_module=is_unspecialized_nn_module, + ) + elif st.all_states is None: + # Preflight, always pretend as if it's static. The point here + # is we want to get through the preflight quickly, and static + # will run faster. The preexisting frame state will get + # applied anyway after we do compiler collectives. + # TODO: I'm not sure if we should just bong the entire pgo + # state here, it kind of depends if we're going to have other + # things that talk in compiler collective. Also, the PGO + # state, if we've already inferred something is automatic + # dynamic, will have lost the actual input sizes, which might + # be useful for debugging purposes (e.g., observing 0/1 + # specialization). Bonging the entire PGO state here would + # let us delete this logic here; the compiler collective + # would just directly update_automatic_dynamic + st.local_state.automatic_dynamic[name] = entry + return entry + else: + # Apply the updates. NB: all_states includes the local state + # too. + res = None + for sub_state in st.all_states: + if name in sub_state.automatic_dynamic: + res = update_automatic_dynamic( + tx, + name, + sub_state.automatic_dynamic[name], + is_unspecialized_nn_module=is_unspecialized_nn_module, + ) + if res is None: + raise AssertionError( + "expected at least one matching automatic_dynamic entry across ranks" + ) + return res + + +def format_cache_key(key: str) -> str: + # NB: We always use global rank for keys, even though they are overkill + # for local only cache + rank = None + if dist.is_available() and dist.is_initialized(): + rank = dist.get_rank() + + tag = torch.compiler.config.cache_key_tag + return f"{key}:{rank}:{tag}" + + +def get_cache_key() -> str | None: + # TODO: info versions of these logs that log only once + if torch.compiler.config.force_disable_caches: + warn_once( + "dynamo_pgo force disabled by torch.compiler.config.force_disable_caches" + ) + return None + + # NB: We namespace the cache keys so that only user-specified job id + # can alias with each other. + if (r := torch.compiler.config.job_id) is not None: + if r.startswith("mast:"): + raise ReservedWorkflowIdUserError( + "torch.compiler.config.job_id with prefix 'mast:' is reserved for " + "automatically generated job id associated with a specific MAST job " + "name and version." + ) + return format_cache_key(r) + + if (name_version := torch._utils_internal.get_mast_job_name_version()) is not None: + mast_job_name, mast_job_version = name_version + return format_cache_key(f"mast:{mast_job_name}:{mast_job_version}") + + return None + + +def get_extra_cache_key(sticky_key: str) -> str | None: + if torch.compiler.config.force_disable_caches: + warn_once( + "dynamo_pgo force disabled by torch.compiler.config.force_disable_caches" + ) + return None + + return format_cache_key(sticky_key) + + +# This solely controls local PGO +def code_state_path(cache_key: str) -> str | None: + if not torch._dynamo.config.automatic_dynamic_local_pgo: + log.debug("automatic_dynamic_local_pgo not enabled") + return None + + from torch._inductor.runtime.runtime_utils import cache_dir + + code_state_key = re.sub(r'[<>:"/\\|?*]', "_", f"code_state_{cache_key}.pkl") + return os.path.join(cache_dir(), "dynamo", code_state_key) + + +def should_use_remote_dynamo_pgo_cache() -> bool: + if torch.compiler.config.force_disable_caches: + return False + + if (r := torch._dynamo.config.automatic_dynamic_remote_pgo) is not None: + return r + + if not is_fbcode(): + return False + + if torch._utils_internal.is_fb_unit_test(): + return False + + try: + from torch._inductor.fb.remote_cache import REMOTE_CACHE_VERSION + except ModuleNotFoundError: + return False + + return REMOTE_CACHE_VERSION >= torch._utils_internal.justknobs_getval_int( + "pytorch/remote_cache:dynamo_pgo_version" + ) + + +def get_remote_cache() -> RemoteCache[JsonDataTy] | None: + from torch._inductor.remote_cache import create_cache + + if not should_use_remote_dynamo_pgo_cache(): + return None + + return create_cache( + "dynamo-pgo", + is_fbcode(), + "FbRemoteDynamoPGOCache", + "RemoteDynamoPGOCache", + ) + + +def _collect_dynamic_sources(code_state: CodeState) -> OrderedSet[str]: + dynamic_sources: OrderedSet[str] = OrderedSet() + for src, fs in code_state.automatic_dynamic.items(): + dynamic = False + if isinstance(fs.size, tuple): + dynamic = auto_dynamic in fs.size # type: ignore[operator] + elif fs.scalar == auto_dynamic: + dynamic = True + if dynamic: + dynamic_sources.add(src) + return dynamic_sources + + +def _collect_missing_sources(all_sources: OrderedSet[str]) -> OrderedSet[str]: + from torch._dynamo.variables.builder import is_dynamic_source + + global _KNOWN_DYNAMIC_SOURCES + missing_sources: OrderedSet[str] = OrderedSet() + for src in all_sources: + if src in _KNOWN_DYNAMIC_SOURCES: + continue + elif is_dynamic_source(src): + _KNOWN_DYNAMIC_SOURCES.add(src) + continue + missing_sources.add(src) + return missing_sources + + +def log_frame_dynamic_whitelist(f_code: types.CodeType) -> None: + global _KNOWN_DYNAMIC_SOURCES + code_id = CodeId.make(f_code, None) + frame_state = get_code_state()[code_id] + all_dynamic_sources = _collect_dynamic_sources(frame_state) + frame_whitelist = ",".join(all_dynamic_sources) + missing_whitelist = ",".join(_collect_missing_sources(all_dynamic_sources)) + if frame_whitelist: + with dynamo_timed(name := "pgo.dynamic_whitelist", log_pt2_compile_event=True): + CompileEventLogger.pt2_compile( + name, + recompile_dynamic_whitelist=frame_whitelist, + missing_dynamic_whitelist=missing_whitelist, + ) + + +def _log_size_mismatch_recompile() -> None: + global _LOGGED_DYNAMIC_ALLOWLIST + if not _LOGGED_DYNAMIC_ALLOWLIST: + torch._utils_internal.add_mlhub_insight( + category="dynamic_shapes_analysis", + insight="Dynamic shape recompilation detected", + insight_description="PGO detected a recompilation due to dynamic shapes. \ + Please follow the instruction from the action link to reduce \ + recompilation overhead.", + ) + # add mlhub insight only once per rank + _LOGGED_DYNAMIC_ALLOWLIST = True + + +def render_code_state(cs: defaultdict[CodeId, CodeState]) -> str: + code_state_str = "\n".join( + f"{k}:\n" + + "\n".join( + f" {src}: {fs.render()}" for src, fs in v.automatic_dynamic.items() + ) + for k, v in cs.items() + ) + dynamic_sources: OrderedSet[str] = OrderedSet() + for state in cs.values(): + dynamic_sources.update(_collect_dynamic_sources(state)) + if dynamic_sources: + code_state_str += ( + "\n\nPGO detected a recompilation due to dynamic shapes. " + "To reduce shape recompilations by compiling dynamically to start, " + f'set environment variable TORCH_COMPILE_DYNAMIC_SOURCES="{",".join(dynamic_sources)}"' + ) + return code_state_str + + +@CacheArtifactFactory.register +class PGOCacheArtifact(CacheArtifact): + @override + def populate_cache(self) -> None: + meta = write_local_impl( + self._rewrite_cache_key_for_mega_cache(self.key), self.content + ) + if meta is None: + raise AssertionError( + "write_local_impl returned None during PGO cache population" + ) + + @override + @staticmethod + def type() -> str: + return "pgo" + + @staticmethod + def _rewrite_cache_key_for_mega_cache(original_key: str) -> str: + """ + The PGO cache artifact key for a MAST job contains the job name and the version. + When we want to use the cache artifact on a different MAST job, we need to + update the key to use the new MAST job's name and version. + """ + if not original_key.startswith("mast:"): + # if original_key is overridden, then don't change it + return original_key + if (new_key := get_cache_key()) is not None: + return new_key + return original_key + + +def hit(key: str, ty: str) -> defaultdict[CodeId, CodeState]: + global _INIT_CODE_STATE + if not isinstance(_CODE_STATE, defaultdict): + raise AssertionError( + f"expected _CODE_STATE to be a defaultdict, got {type(_CODE_STATE)}" + ) + log.info("get_code_state %s hit %s, %d entries", key, ty, len(_CODE_STATE)) + trace_structured_artifact( + f"get_{ty}_code_state", + "string", + lambda: render_code_state(_CODE_STATE), # type: ignore[arg-type] + ) + set_feature_use("pgo", True) + _INIT_CODE_STATE = copy.deepcopy(_CODE_STATE) + return _CODE_STATE + + +def get_local_code_state(cache_key: str) -> defaultdict[CodeId, CodeState] | None: + global _CODE_STATE + path = code_state_path(cache_key) + if path is not None and os.path.exists(path): + with dynamo_timed( + name := "pgo.get_local_code_state", log_pt2_compile_event=True + ): + CompileEventLogger.pt2_compile(name, cache_key=cache_key) + # Read lock not necessary as we always write atomically write to + # the actual location + with open(path, "rb") as f: + try: + content = f.read() + _CODE_STATE = pickle.loads(content) + CompileEventLogger.pt2_compile(name, cache_size_bytes=f.tell()) + except Exception: + log.warning( + "get_code_state failed while reading %s", path, exc_info=True + ) + else: + CacheArtifactRecorder(PGOCacheArtifact.type(), cache_key).record( + content + ) + return hit(path, "local") + return None + + +def lookup_remote_cache_entry( + remote_cache: RemoteCache[JsonDataTy], + cache_key: str, + event_name: str | None = None, +) -> defaultdict[CodeId, CodeState] | None: + code_state = None + try: + cache_data = remote_cache.get(cache_key) + except Exception: + log.warning("get_code_state failed remote read on %s", cache_key, exc_info=True) + else: + if cache_data is not None: + try: + if not isinstance(cache_data, dict): + raise AssertionError( + f"expected cache_data to be a dict, got {type(cache_data)}" + ) + data = cache_data["data"] + if not isinstance(data, str): + raise AssertionError( + f"expected cache_data['data'] to be a str, got {type(data)}" + ) + payload = base64.b64decode(data) + if event_name is not None: + CompileEventLogger.pt2_compile( + event_name, cache_size_bytes=len(payload) + ) + code_state = pickle.loads(payload) + except Exception: + log.warning( + "get_code_state failed parsing remote result on %s", + cache_key, + exc_info=True, + ) + else: + CacheArtifactRecorder(PGOCacheArtifact.type(), cache_key).record( + payload + ) + else: + log.info("get_code_state remote miss on %s", cache_key) + return code_state + + +def get_remote_code_state(cache_key: str) -> defaultdict[CodeId, CodeState] | None: + global _CODE_STATE + remote_cache = get_remote_cache() + if remote_cache is not None: + with dynamo_timed( + name := "pgo.get_remote_code_state", + log_pt2_compile_event=True, + dynamo_compile_column_us="pgo_get_remote_code_state_time_us", + ): + CompileEventLogger.pt2_compile(name, cache_key=cache_key) + code_state = lookup_remote_cache_entry(remote_cache, cache_key, name) + if code_state is not None: + _CODE_STATE = code_state + return hit(cache_key, "remote") + return None + + +def get_extra_remote_code_state(cache_key: str) -> None: + """ + Reads an additional PGO profile from the given cache key, and merges it with the default PGO profile. + """ + global _CODE_STATE + if _CODE_STATE is None: + raise AssertionError( + "_CODE_STATE must be initialized before reading extra remote code state" + ) + + remote_cache = get_remote_cache() + if remote_cache is not None: + with dynamo_timed( + name := "pgo.get_extra_remote_code_state", + log_pt2_compile_event=True, + dynamo_compile_column_us="pgo_get_remote_code_state_time_us", + ): + CompileEventLogger.pt2_compile(name, cache_key=cache_key) + code_state = lookup_remote_cache_entry(remote_cache, cache_key) + log.info( + "get_extra_code_state %s hit, %d entries", + cache_key, + len(code_state) if code_state is not None else 0, + ) + if code_state is not None: + if _CODE_STATE: + raise AssertionError( + "expected _CODE_STATE to be empty before merging extra remote state" + ) + _CODE_STATE = code_state + # log to tlparse + trace_structured_artifact( + "get_extra_remote_code_state", + "string", + lambda: render_code_state(code_state), + ) + + +def get_code_state() -> defaultdict[CodeId, CodeState]: + global _CODE_STATE, _INIT_CODE_STATE + if _CODE_STATE is not None: + return _CODE_STATE + + # Initialize it (even if we don't look up profile) + _CODE_STATE = defaultdict(CodeState) + + cache_key = get_cache_key() + if cache_key is None: + return _CODE_STATE + + # Attempt local + local_code_state = get_local_code_state(cache_key) + + # Attempt remote + if local_code_state is None: + get_remote_code_state(cache_key) + + # Attempt additional remote if neither local/default remote succeeded + if ( + not _CODE_STATE + and (sticky_read := torch.compiler.config.pgo_extra_read_key) is not None + ): + extra_read_key = get_extra_cache_key(sticky_read) + if extra_read_key is not None: + get_extra_remote_code_state(extra_read_key) + + log.info("get_code_state using default") + + if _CODE_STATE is None: + raise AssertionError("_CODE_STATE should have been initialized above") + return _CODE_STATE + + +def put_code_state() -> None: + if _CODE_STATE is None: + log.info("put_code_state: never initialized, will not write") + return + + if _CODE_STATE == _INIT_CODE_STATE: + log.info("put_code_state: no change, skipping") + return + + cache_key = get_cache_key() + if cache_key is None: + log.info("put_code_state: no cache key, skipping") + return + + put_local_code_state(cache_key) + put_remote_code_state(cache_key) + if (sticky_write := torch.compiler.config.pgo_extra_write_key) is not None: + extra_write_key = get_extra_cache_key(sticky_write) + if extra_write_key is not None: + put_remote_code_state(extra_write_key) + + +def write_local_impl(cache_key: str, pickled_code: bytes) -> tuple[str, int] | None: + path = code_state_path(cache_key) + + if path is None: + return None + + # If the user isn't misusing our API, we should have exclusive access to + # this directory. But it's not too hard + + tmp_path = path + ".tmp" + lock_path = path + ".lock" + # We /mostly/ don't need the lock but the tmp file could be clobbered + # TODO: use a safe tempfile create to eliminate lock + from torch.utils._filelock import FileLock + + os.makedirs(os.path.dirname(path), exist_ok=True) + + with FileLock(lock_path, timeout=LOCK_TIMEOUT): + with open(tmp_path, "wb") as f: + f.write(pickled_code) + size = f.tell() + os.replace(tmp_path, path) + return path, size + + +def put_local_code_state(cache_key: str) -> None: + with dynamo_timed(name := "pgo.put_local_code_state", log_pt2_compile_event=True): + CompileEventLogger.pt2_compile(name, cache_key=cache_key) + if _CODE_STATE is None: + raise AssertionError( + "_CODE_STATE must be initialized before writing local code state" + ) + + pickled_code = pickle.dumps(_CODE_STATE) + + CacheArtifactRecorder(PGOCacheArtifact.type(), cache_key).record(pickled_code) + + meta = write_local_impl(cache_key, pickled_code) + if meta is None: + log.info("put_code_state: local cache disabled") + return + path, size = meta + + CompileEventLogger.pt2_compile(name, cache_size_bytes=size) + log.info("put_code_state: wrote local %s, %d entries", path, len(_CODE_STATE)) + trace_structured_artifact( + "put_local_code_state", + "string", + lambda: render_code_state(_CODE_STATE), + ) + + +def put_remote_code_state(cache_key: str, extra_code_state: bool = False) -> None: + event_name = ( + "put_remote_code_state" + if not extra_code_state + else "put_extra_remote_code_state" + ) + with dynamo_timed( + name := f"pgo.{event_name}", + log_pt2_compile_event=True, + dynamo_compile_column_us="pgo_put_remote_code_state_time_us", + ): + CompileEventLogger.pt2_compile(name, cache_key=cache_key) + if _CODE_STATE is None: + raise AssertionError( + "_CODE_STATE must be initialized before writing remote code state" + ) + + remote_cache = get_remote_cache() + + if remote_cache is None: + log.info("%s: remote cache disabled", event_name) + return + + content = pickle.dumps(_CODE_STATE) + CompileEventLogger.pt2_compile(name, cache_size_bytes=len(content)) + cache_data: JsonDataTy = { + "data": base64.b64encode(content).decode("ascii"), + } + remote_cache.put(cache_key, cache_data) + log.info( + "%s: wrote remote %s, %d entries", event_name, cache_key, len(_CODE_STATE) + ) + # TODO: don't log this multiple times + trace_structured_artifact( + event_name, + "string", + lambda: render_code_state(_CODE_STATE), + ) + + +# NB: this does NOT reset the cached code state on disk +def reset_code_state() -> None: + global _CODE_STATE, _INIT_CODE_STATE, _LOGGED_DYNAMIC_ALLOWLIST + _CODE_STATE = None + _INIT_CODE_STATE = None + _LOGGED_DYNAMIC_ALLOWLIST = False diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__init__.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d4a07c009d4ccaef660505a55bf12cb2c9588cb7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__init__.py @@ -0,0 +1,569 @@ +""" +Python polyfills for common builtins. +""" + +# NOTE: 1. Please do not import any submodule in the directory here to avoid circular imports. +# 2. While adding a new polyfill module, also add it to POLYFILLED_MODULE_NAMES in loader.py. +# Add it in the TYPE_CHECKING block below as well. + +import types +from collections import OrderedDict +from collections.abc import Callable, Hashable, Iterable, Iterator, Mapping, Sequence +from itertools import repeat as _repeat +from operator import eq, ge, gt, le, lt, ne +from typing import Any, TYPE_CHECKING, TypeGuard, TypeVar +from typing_extensions import TypeIs + +import torch + + +T = TypeVar("T") +U = TypeVar("U") +C = TypeVar("C") + + +if TYPE_CHECKING: + from ..utils import dict_keys + + # Load by torch._dynamo.polyfills.loader + # See also the POLYFILLED_MODULE_NAMES in torch/_dynamo/polyfills/loader.py + # Put the submodules here to avoid circular imports + from . import ( + _collections as _collections, + builtins as builtins, + functools as functools, + io as io, + itertools as itertools, + operator as operator, + os as os, + pytree as pytree, + struct as struct, + sys as sys, + torch_c_nn as torch_c_nn, + traceback as traceback, + ) + +from torch.overrides import BaseTorchFunctionMode + + +# These classes handle support for TorchFunctionModes across +# graph breaks +# Today the TorchFunctionMode enter (for the classes we support) +# simply pushes the mode onto the stack. Since after this occurs +# the stack is mutated, and we replay these mutations, we don't need +# any cleanup logic to be run once the graph break occurs, we simply replay +# these mutations to ensure at the graph break the torch function mode stack is correct +# and reconstruct the torch function mode stack normally +# when we compile the resume function on the other side of the break. +# However, to ensure we exit properly +# in the resume function, we need to re-enter the contexts as we do other contexts. +# These contexts do nothing on enter, but provide the correct exit logic to ensure +# the stack state is correct. +class NoEnterTorchFunctionMode(BaseTorchFunctionMode): + def __enter__(self) -> None: + pass + + +# Used by WrappedUserFunctionVariable and similar to inline decorated function +# calls with bytecode backing. Without this, the context enter/exit happens in +# Python-level VT code, so a nested graph break inside `fn` would skip applying +# the context in the compiled fn/resume. By inlining through this polyfill, the +# `with` statement has real bytecode that the resume function can continue from. +def _fn_with_ctx(ctx: Any, fn: Callable[..., T], *args: Any, **kwargs: Any) -> T: + with ctx: + return fn(*args, **kwargs) + + +def index( + iterator: Iterator[T], item: T, start: int = 0, end: int | None = None +) -> int: + from itertools import islice + + for i, elem in islice(enumerate(iterator), start, end): + if elem is item or elem == item: + return i + # This will not run in dynamo + raise ValueError(f"{item} is not in {type(iterator)}") + + +def repeat(item: T, count: int) -> Iterator[T]: + for _ in range(count): + yield item + + +def radians(x: float) -> float: + import math + + return math.pi / 180.0 * x + + +def impl_IS_MAPPING(a: object) -> TypeIs[Mapping[Any, Any]]: + return isinstance(a, Mapping) + + +def impl_MATCH_SEQUENCE(a: object) -> TypeGuard[Sequence[Any]]: + return isinstance(a, Sequence) and not isinstance(a, (str, bytes, bytearray)) + + +def _match_class_attr(obj: object, name: str, seen: set[str]) -> object: + if name in seen: + raise TypeError(f"{type(obj)} got multiple sub-patterns for attribute {name}") + + attr = getattr(obj, name) + seen.add(name) + return attr + + +def impl_MATCH_CLASS( + subject: object, cls: type, nargs: int, kwargs: tuple[str, ...] +) -> tuple[object, ...] | None: + if not isinstance(cls, type): + raise TypeError("called match pattern must be a class") + + if not isinstance(subject, cls): + return None + + typ = type(subject) + match_self = False + match_args = () + + attrs = [] + seen = set() + + if nargs: + if hasattr(typ, "__match_args__"): + match_args = typ.__match_args__ + + if not isinstance(match_args, tuple): + raise TypeError( + f"{typ}.__match_args__ must be a tuple, (got {type(match_args)})" + ) + + for name in match_args[:nargs]: + if not isinstance(name, str): + raise TypeError( + f"__match_args__ elements must be strings (got {type(name)})" + ) + attrs.append(_match_class_attr(subject, name, seen)) + else: + # We should somehow check if the type has TPFLAGS_MATCH_SELF set + # match_self is only true if TPFLAGS_MATCH_SELF is set, but there is + # no way to check for it directly in Python. So we assume it is set + # if there are no __match_args__ + match_self = True + attrs.append(subject) + + allowed = 1 if match_self else len(match_args) + if allowed < nargs: + raise TypeError( + f"accepts {allowed} positional sub-patterns ({nargs} given)" + ) + + for name in kwargs: + attrs.append(_match_class_attr(subject, name, seen)) + + return tuple(attrs) + + +def impl_MATCH_KEYS(obj: Mapping[T, U], keys: tuple[T, ...]) -> tuple[U, ...] | None: + if not isinstance(obj, Mapping): + raise AssertionError(f"Expected a Mapping, got {type(obj)}") + if all(key in obj for key in keys): + return tuple(obj[key] for key in keys) + else: + return None + + +def impl_CONTAINS_OP_fallback(a: T, b: Iterable[T]) -> bool: + # performs fallback "a in b" + # CPython: PySequence_Contains → _PySequence_IterSearch → PyObject_GetIter + # PyObject_GetIter itself falls back to PySequence_GetItem when tp_iter is NULL. + if hasattr(b, "__iter__"): + for x in b: + if x == a: + return True + return False + if hasattr(b, "__getitem__"): + i = 0 + while True: + try: + if b.__getitem__(i) == a: + return True + i += 1 + except IndexError: + return False + raise TypeError(f"argument of type {type(b)} is not iterable") + + +def accumulate_grad( + x: torch.Tensor, + variable_grad: torch.Tensor | None, + new_grad: torch.Tensor | None, +) -> torch.Tensor | None: + # polyfills according to the Gradient Layout Contract + if new_grad is None: + return variable_grad + new_grad_strided = torch.empty_like(x) + new_grad_strided.copy_(new_grad) + if variable_grad is None: + return new_grad_strided + elif variable_grad.is_sparse and not new_grad_strided.is_sparse: + return new_grad_strided + variable_grad + elif torch.is_grad_enabled(): + return variable_grad + new_grad_strided + else: + variable_grad.add_(new_grad_strided) + return variable_grad + + +def accumulate_grad_no_alias( + x: torch.Tensor, + variable_grad: torch.Tensor | None, + new_grad: torch.Tensor | None, +) -> torch.Tensor | None: + # Mirrors inductor::accumulate_grad_: same gradient layout logic as + # accumulate_grad, but the returned grad must not alias any input. + if new_grad is None: + if variable_grad is None: + return None + return variable_grad.clone() + new_grad_strided = torch.empty_like(x) + new_grad_strided.copy_(new_grad) + if variable_grad is None: + return new_grad_strided + elif variable_grad.is_sparse and not new_grad_strided.is_sparse: + return new_grad_strided + variable_grad + elif torch.is_grad_enabled(): + return variable_grad + new_grad_strided + else: + result = variable_grad.clone() + result.add_(new_grad_strided) + return result + + +# This mirrors +# https://github.com/python/cpython/blob/a1c52d1265c65bcf0d9edf87e143843ad54f9b8f/Objects/listobject.c#L3352-L3413 +def list_cmp( + op: Callable[[Any, Any], bool], left: Sequence[T], right: Sequence[T] +) -> bool: + """emulate `(1,2,3) > (1,2)` etc""" + + # Optimization: For equality, short-circuit if lengths differ + # This avoids iterating through elements and triggering guards on SymInts + left_len = len(left) + right_len = len(right) + + if op is eq and left_len != right_len: + return False + if op is ne and left_len != right_len: + return True + + # Apply `op` to the first pair that differ + for a, b in zip(left, right): + if a != b: + return op(a, b) + + # No more pairs to compare, so compare sizes. + return op(left_len, right_len) + + +def dict___eq__(d: dict[T, U], other: dict[T, U]) -> bool: + if (len(d) != len(other)) or (d.keys() != other.keys()): + return False + + if all(isinstance(a, OrderedDict) for a in (d, other)): + return list(d.items()) == list(other.items()) + + # CPython's dict_equal uses PyObject_RichCompareBool for value + # comparison, which has an identity shortcut (if v is w, eq is True). + # This matters for NaN: {k: nan} == {k: nan} is True when same nan. + for k, v in d.items(): + ov = other[k] + if v is not ov and v != ov: + return False + + return True + + +def dictview_richcompare( + op: Callable[[Any, Any], bool], self: Iterable[T], other: Iterable[T] +) -> bool: + """Mirrors dictview_richcompare for dict_keys/dict_items vs set/frozenset. + + https://github.com/python/cpython/blob/e76aa128fe/Objects/dictobject.c#L5952-L6010 + Uses len() and ``in`` so that Dynamo traces through sq_length/sq_contains. + """ + len_self = len(self) # type: ignore[arg-type] + len_other = len(other) # type: ignore[arg-type] + + if op is eq: + if len_self != len_other: + return False + return all(item in other for item in self) + if op is ne: + if len_self != len_other: + return True + return not all(item in other for item in self) + if op is lt: + if len_self >= len_other: + return False + return all(item in other for item in self) + if op is le: + if len_self > len_other: + return False + return all(item in other for item in self) + if op is gt: + if len_self <= len_other: + return False + return all(item in self for item in other) + # ge + if len_self < len_other: + return False + return all(item in self for item in other) + + +def assert_dict_equal( + self_: Any, d1: dict[T, U], d2: dict[T, U], msg: str | None = None +) -> None: + self_.assertTrue(d1 == d2, msg) + + +def assert_multi_line_equal( + self_: Any, first: T, second: T, msg: str | None = None +) -> None: + return self_.assertTrue(first == second, msg) + + +# The original impl. uses difflib +def assert_sequence_equal( + self_: Any, + seq1: Sequence[T], + seq2: Sequence[T], + msg: str | None = None, + seq_type: type[Any] | None = None, +) -> None: + return self_.assertTrue(seq1 == seq2, msg) + + +def getattr_and_trace(*args: Any, **kwargs: Any) -> Any: + wrapper_obj = args[0] + attr_name = args[1] + fn = getattr(wrapper_obj, attr_name) + return fn(*args[2:], **kwargs) + + +def getattr_and_trace_no_nested_graph_breaks(*args: Any, **kwargs: Any) -> Any: + with torch._dynamo.disable_nested_graph_breaks(): + return getattr_and_trace(*args, **kwargs) + + +def mapping_get(obj: Mapping[T, U], key: T, value: U | None = None, /) -> U | None: + try: + return obj.__getitem__(key) + except KeyError: + return value + + +def instantiate_user_defined_class_object( + cls: type[T], /, *args: Any, **kwargs: Any +) -> T: + obj = cls.__new__(cls, *args, **kwargs) + + # Only call __init__ if the object's type is a subclass of cls. + # CPython uses PyType_IsSubtype(Py_TYPE(obj), type) at the C level, which does NOT + # go through metaclass __instancecheck__. Using isinstance() here would be wrong + # for classes with custom __instancecheck__ (e.g. torch.ByteStorage). + # Reference: https://github.com/python/cpython/blob/3.12/Objects/typeobject.c#L1670-L1673 + if issubclass(type(obj), cls): + obj.__init__(*args, **kwargs) + return obj + + +def mutable_mapping_update( + self, + data: Mapping[T, U] | Iterable[tuple[T, U]] = (), + /, + **kwargs: Any, +) -> None: + if isinstance(data, Mapping): + # Merge standard mapping with PyMapping_Items + for key, value in data.items(): + self[key] = value + # FIXME: Enabling the `elif`-branch below needs too many `VariableClass.call_obj_hasattr` changes. + # >>> class Foo: + # ... def __init__(self): + # ... self.keys = lambda: ['a', 'b', 'c'] # not required to be a method + # ... + # ... def __getitem__(self, key): + # ... return 0 + # ... + # >>> dict(Foo()) + # {'a': 0, 'b': 0, 'c': 0} + # + # > This is a rare case, so we comment it out for now. + # + # elif hasattr(data, "keys"): + # # Merge mapping-like object with PyMapping_Keys + PyObject_GetItem + # for key in data.keys(): + # self[key] = data[key] + else: + if not isinstance(data, Iterable): + raise TypeError(f"{type(data).__name__!r} object is not iterable") + # Likely a sequence of pairs + for key, value in data: + self[key] = value + + if kwargs: + for key, value in kwargs.items(): + self[key] = value + + +# Used with something like dict(obj) +def construct_dict( + cls: type[T], + data: Mapping[object, object] | Iterable[tuple[object, object]] = (), + /, + **kwargs: Any, +) -> T: + self = cls.__new__(cls) + mutable_mapping_update(self, data, **kwargs) + return self + + +def foreach_map_fn(*args: Any) -> Any: + op = args[0] + new_args: list[Any] = [] + at_least_one_list = False + for arg in args[1:]: + if not isinstance(arg, (list, tuple)): + new_args.append(_repeat(arg)) + else: + at_least_one_list = True + new_args.append(arg) + + # Just apply op once to args if there are no lists + if not at_least_one_list: + return op(*args[1:]) + + out = [] + for unpacked in zip(*new_args): + out.append(op(*unpacked)) + + return out + + +def foreach_lerp_inplace( + self, + end: list[torch.Tensor] | tuple[torch.Tensor, ...], + weight: float | int | torch.Tensor, +) -> None: + # Decompose lerp via addcmul_ for FMA. Uses the same dual-formula + # approach as CUDA's native lerp to get bitwise identical results: + # |w| < 0.5 (low): fma(w, diff, start) + # |w| >= 0.5 (high): fma(-(1-w), diff, end) + # For tensor weights (e.g. 0-dim tensor from tensor betas in Adam) the + # low formula is always used because the native lerp_scalar lowering + # would crash on float(weight) for symbolic expressions. + diff = torch._foreach_sub(end, self) + if isinstance(weight, torch.Tensor): + # Select base and weight for the dual formula before a single addcmul: + # low (|w| < 0.5): fma(w, diff, self) + # high (|w| >= 0.5): fma(-(1-w), diff, end) + mask = weight.abs() >= 0.5 + neg_omw = -(1.0 - weight) + w = torch.where(mask, neg_omw, weight) + bases = [torch.where(mask, e, s) for s, e in zip(self, end)] + w_list = [w] * len(diff) + torch._foreach_addcmul_(bases, w_list, diff) + for s, b in zip(self, bases): + s.copy_(b) + else: + abs_weight = weight if weight >= 0 else -weight + if abs_weight >= 0.5: + # High formula: end + (-(1-w)) * diff → fma(-(1-w), diff, end) + # Compute 1-w in target dtype to match CUDA rounding. + d0 = self[0] + neg_omw = -(1.0 - torch.tensor(weight, dtype=d0.dtype, device=d0.device)) + neg_omw_list = [neg_omw] * len(diff) + for s, e in zip(self, end): + s.copy_(e) + torch._foreach_addcmul_(self, neg_omw_list, diff) + else: + # Low formula: start + w * diff → fma(w, diff, start) + weights = [torch.full_like(d, weight) for d in diff] + torch._foreach_addcmul_(self, weights, diff) + return self + + +def foreach_pow_scalar( + scalar: Any, exps: Sequence[bool | complex | float | int] +) -> tuple[torch.Tensor, ...]: + return torch._foreach_pow([scalar for _ in exps], exps) + + +def predicate(obj: object) -> bool: + # This will cause the rest of dynamo to handle the if statement correctly, so we don't have to rewrite it here. + # We can't just use bool() here since we can't trace into that in general. + if obj: + return True + return False + + +def group_tensors_by_device_and_dtype( + tensorlistlist: list[list[torch.Tensor | None]], with_indices: bool = False +) -> dict[tuple[torch.device, torch.dtype], tuple[list[list[Any]], list[int]]]: + """Pure Python implementation of torch._C._group_tensors_by_device_and_dtype. + + Groups tensors by their device and dtype. This is useful before sending + tensors off to a foreach implementation, which requires tensors to be on + one device and dtype. + + Args: + tensorlistlist: A list of lists of tensors (tensors can be None). + with_indices: If True, track original indices in the output. + + Returns: + A dict mapping (device, dtype) tuples to (grouped_tensorlistlist, indices). + """ + # Result dict: (device, dtype) -> (list of lists, indices) + result: dict[ + tuple[torch.device, torch.dtype], tuple[list[list[Any]], list[int]] + ] = {} + + if not tensorlistlist or not tensorlistlist[0]: + return result + + num_lists = len(tensorlistlist) + num_tensors = len(tensorlistlist[0]) + + for idx in range(num_tensors): + # Find the first non-None tensor at this index to get device and dtype + first_tensor = None + for tlist in tensorlistlist: + if tlist is not None and idx < len(tlist) and tlist[idx] is not None: + first_tensor = tlist[idx] + break + + if first_tensor is None: + # All tensors at this index are None, skip + continue + + key = (first_tensor.device, first_tensor.dtype) + + if key not in result: + # Initialize empty lists for each tensorlist + result[key] = ([[] for _ in range(num_lists)], []) + + grouped_lists, indices = result[key] + + # Add tensors from each list at this index + for list_idx, tlist in enumerate(tensorlistlist): + if tlist is not None and idx < len(tlist): + grouped_lists[list_idx].append(tlist[idx]) + else: + grouped_lists[list_idx].append(None) + + if with_indices: + indices.append(idx) + + return result diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..427a271f493224a80e4fa50483c765b61b3784dc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/_collections.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/_collections.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a521932add5a2c2f90f69612298fe2b8411b3d5d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/_collections.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/builtins.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/builtins.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42eb6c0cd04663940666c8af2c68bfd7a5f5bd89 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/builtins.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/copy.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/copy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c0cd8c79e92be21ffa4f01710f99fc37600542d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/copy.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/functools.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/functools.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55f99e07a24906f350d8c928bf678167abcad553 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/functools.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/fx.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/fx.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f52bd963aaddb86c54bdf80673ce83cd4c3e16c6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/fx.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/heapq.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/heapq.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5cac9ad868d12ad4f923990bbf0d77a871f5b1b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/heapq.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/io.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/io.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c0724ce358f75dcd33a49b0ef184401f1a735dd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/io.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/itertools.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/itertools.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8ec188d25e5e014c2bb2a13ff5146495a5b0d67 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/itertools.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/loader.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/loader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..342a416d47488d1281a595a17468060caca4866f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/loader.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/operator.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/operator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e8eafc3d4e2d6e4995a921e8b1864554aeb9ffa Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/operator.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/os.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/os.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c48f9bc2822c0b4d819cdb12aad93765a7f90823 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/os.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/pytree.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/pytree.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b88403211efb488b7a468d1214f44e76db530b2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/pytree.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/struct.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/struct.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52de6d27ab44551b1c8e15d7ad296b79f072d94b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/struct.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/sys.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/sys.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5163b6312420c765ea1abdadf4c241578357f4e1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/sys.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/tensor.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/tensor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf0515c87021bd7877e5adb7c0737bab9c88bace Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/tensor.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/torch_c_nn.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/torch_c_nn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56276131af86b3dfb5c8acfc5a48e651611fcd16 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/torch_c_nn.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/traceback.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/traceback.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7cbd9729f9538ad0acb0add6622d6f0d5386fad Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/__pycache__/traceback.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/_collections.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/_collections.py new file mode 100644 index 0000000000000000000000000000000000000000..9773635ae30587b06bb9f6b82c003392767b3873 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/_collections.py @@ -0,0 +1,33 @@ +""" +Python polyfills for builtins +""" + +from collections.abc import Iterable, MutableMapping +from typing import TypeVar + +from ..decorators import substitute_in_graph + + +__all__ = [] + + +T = TypeVar("T") + + +try: + import _collections # type: ignore[import-not-found] + + @substitute_in_graph(_collections._count_elements) + def _count_elements( + mapping: MutableMapping[T, int], + iterable: Iterable[T], + ) -> None: + "Tally elements from the iterable." + mapping_get = mapping.get + for elem in iterable: + mapping[elem] = mapping_get(elem, 0) + 1 + + __all__.append("_count_elements") + +except ImportError: + pass diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/builtins.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/builtins.py new file mode 100644 index 0000000000000000000000000000000000000000..5e7e4befc47014af1565bb8143de3792aa4d3852 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/builtins.py @@ -0,0 +1,181 @@ +""" +Python polyfills for builtins +""" + +from __future__ import annotations + +import builtins +import functools +import operator +import sys +import typing +from collections.abc import Callable +from typing import TYPE_CHECKING, TypeVar + +from ..decorators import substitute_in_graph + + +if TYPE_CHECKING: + from collections.abc import Iterable + + +__all__ = [ + "all", + "any", + "cast", + "enumerate", + "sum", +] + + +_T = TypeVar("_T") + + +@substitute_in_graph(builtins.all, can_constant_fold_through=True) +def all(iterable: Iterable[object], /) -> bool: + for elem in iterable: + if not elem: + return False + return True + + +@substitute_in_graph(builtins.any, can_constant_fold_through=True) +def any(iterable: Iterable[object], /) -> bool: + for elem in iterable: + if elem: + return True + return False + + +@substitute_in_graph(builtins.enumerate, is_embedded_type=True) # type: ignore[arg-type] +def enumerate(iterable: Iterable[_T], start: int = 0) -> Iterable[tuple[int, _T]]: + if not isinstance(start, int): + raise TypeError( + f"{type(start).__name__!r} object cannot be interpreted as an integer" + ) + + for x in iterable: + yield start, x + start += 1 + + +@substitute_in_graph(builtins.sum, can_constant_fold_through=True) # type: ignore[arg-type] +def sum(iterable: Iterable[_T], /, start: _T = 0) -> _T: # type: ignore[assignment] + return functools.reduce(operator.add, iterable, start) + + +# TODO(guilhermeleobas): Implement this iterator as a VariableTracker to see if +# it is faster than tracing through it +class _CallableIterator: + def __init__(self, fn, sentinel): # type: ignore[no-untyped-def] + self.fn = fn + self.sentinel = sentinel + self.exhausted = False + + def __iter__(self): # type: ignore[no-untyped-def] + return self + + def __next__(self): # type: ignore[no-untyped-def] + if self.exhausted: + raise StopIteration + + # The iterator created in this case will call object with no arguments + # for each call to its __next__() method; + r = self.fn() + + # CPython calliter_iternext (Objects/iterobject.c) re-reads it_callable / + # it_sentinel after the call returns. If a reentrant next() exhausted + # this iterator during fn() (gh-101892), it_sentinel is now NULL, so the + # sentinel comparison is skipped and StopIteration is raised regardless + # of the returned value. + if self.exhausted: + raise StopIteration + + # If the value returned is equal to sentinel, StopIteration will be raised + if r == self.sentinel: + self.exhausted = True + raise StopIteration + + # otherwise the value will be returned. + return r + + +class _SequenceIterator: + def __init__(self, iterable) -> None: + self.iterable = iterable + self.index = 0 + self.exhausted = False + + def __iter__(self) -> _SequenceIterator: + return self + + def __next__(self) -> object: + if self.exhausted: + raise StopIteration + + # CPython iter_iternext (Objects/iterobject.c): the index counter is a + # Py_ssize_t, so once it reaches PY_SSIZE_T_MAX (sys.maxsize) it cannot + # advance and every subsequent next() raises OverflowError. + if self.index == sys.maxsize: + raise OverflowError("iter index too large") + + try: + result = self.iterable.__getitem__(self.index) + self.index += 1 + return result + except (IndexError, StopIteration): + self.exhausted = True + raise StopIteration from None + + def __setstate__(self, state) -> None: + # CPython iter_setstate (Objects/iterobject.c): a negative index is + # clamped to 0, and the state is only applied while the iterator is + # live (it_seq != NULL), i.e. not yet exhausted. + if not self.exhausted: + self.index = max(state, 0) + + +def sequence_iterator(iterable) -> Iterable[object]: + if hasattr(iterable, "__getitem__"): + return _SequenceIterator(iterable) + raise TypeError(f"'{type(iterable)}' object is not iterable") + + +class _ReversedSequenceIterator: + # Mirrors CPython's reversed object (Objects/enumobject.c). Walks the + # sequence backwards via __getitem__, starting from len(seq) - 1. + def __init__(self, seq) -> None: + self.seq = seq + self.index = len(seq) - 1 + + def __iter__(self) -> _ReversedSequenceIterator: + return self + + def __next__(self) -> object: + if self.index < 0: + raise StopIteration + try: + result = self.seq[self.index] + except (IndexError, StopIteration): + self.index = -1 + raise StopIteration from None + self.index -= 1 + return result + + +def reversed_sequence_iterator(seq) -> Iterable[object]: + return _ReversedSequenceIterator(seq) + + +def callable_iterator(fn, sentinel, /): + # If the second argument, sentinel, is given, then object must be a + # callable object. + if not isinstance(fn, Callable): # type: ignore[arg-type] + raise TypeError("iter(v, w): v must be a callable") + + return _CallableIterator(fn, sentinel) + + +@substitute_in_graph(typing.cast, can_constant_fold_through=True) +def cast(typ: type, val: _T) -> _T: # type: ignore[type-var] + return val diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/copy.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/copy.py new file mode 100644 index 0000000000000000000000000000000000000000..b1210708ed8b694775b46f0cf6d58a36d476cfdf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/copy.py @@ -0,0 +1,65 @@ +""" +Python polyfills for copy +""" + +from __future__ import annotations + +from typing import TypeVar + +from ..decorators import substitute_in_graph + + +__all__ = [ + "reduce_ex_user_defined_object", +] + +T = TypeVar("T") + + +@substitute_in_graph(object.__reduce_ex__, skip_signature_check=True) # type: ignore[arg-type] +def reduce_ex_user_defined_object(obj: T, protocol: int, /) -> tuple: # type: ignore[type-arg] + """Traceable polyfill for object.__reduce_ex__ (protocol >= 2). + + Mirrors CPython's reduce_newobj (Objects/typeobject.c): builds the __new__ + arguments from __getnewargs_ex__/__getnewargs__, selects + copyreg.__newobj_ex__ vs __newobj__ based on whether kwargs are present, and + computes the pickle state (__getstate__ if overridden, else __dict__ if the + object has one, else None). copy._reconstruct rebuilds the object via + cls.__new__(cls, *args) and applies the state. + + This must not assume the object has a __dict__: tuple/slots objects such as + namedtuples have __slots__ = () and no __dict__, and reduce to + (copyreg.__newobj__, (cls, *values), None, None, None). + """ + import copyreg + + cls = type(obj) + + args: tuple # type: ignore[type-arg] + kwargs: dict # type: ignore[type-arg] + if hasattr(cls, "__getnewargs_ex__"): + args, kwargs = obj.__getnewargs_ex__() # type: ignore[attr-defined] + elif hasattr(cls, "__getnewargs__"): + args = obj.__getnewargs__() # type: ignore[attr-defined] + kwargs = {} + else: + args = () + kwargs = {} + + if kwargs: + func = copyreg.__newobj_ex__ # pyrefly: ignore[missing-attribute] + newargs = (cls, args, kwargs) + else: + func = copyreg.__newobj__ # pyrefly: ignore[missing-attribute] + newargs = (cls, *args) + + default_getstate = getattr(object, "__getstate__", None) + if getattr(cls, "__getstate__", None) is not default_getstate: + state = obj.__getstate__() + else: + try: + state = obj.__dict__ + except AttributeError: + state = None + + return (func, newargs, state, None, None) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/functools.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/functools.py new file mode 100644 index 0000000000000000000000000000000000000000..f48c7fb3a29276ee28ca7558379d25bb8c9ee89d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/functools.py @@ -0,0 +1,73 @@ +""" +Python polyfills for functools +""" + +import functools +from collections.abc import Callable, Iterable +from functools import _initial_missing # type: ignore[attr-defined] +from typing import Any, TypeVar + +from ..decorators import substitute_in_graph + + +__all__ = ["cmp_to_key", "reduce"] + + +_T = TypeVar("_T") +_U = TypeVar("_U") + + +class _KeyWrapper: + def __init__(self, mycmp: Callable[[Any, Any], int], obj: Any) -> None: + self.mycmp = mycmp + self.obj = obj + + def __lt__(self, other: "_KeyWrapper") -> bool: + return self.mycmp(self.obj, other.obj) < 0 + + def __gt__(self, other: "_KeyWrapper") -> bool: + return self.mycmp(self.obj, other.obj) > 0 + + def __eq__(self, other: object) -> bool: + return self.mycmp(self.obj, other.obj) == 0 # type: ignore[attr-defined] + + def __le__(self, other: "_KeyWrapper") -> bool: + return self.mycmp(self.obj, other.obj) <= 0 + + def __ge__(self, other: "_KeyWrapper") -> bool: + return self.mycmp(self.obj, other.obj) >= 0 + + __hash__ = None # type: ignore[assignment] + + +# Reference: https://docs.python.org/3/library/functools.html#functools.cmp_to_key +@substitute_in_graph(functools.cmp_to_key, skip_signature_check=True) +def cmp_to_key(mycmp: Callable[[Any, Any], int]) -> Callable[[Any], _KeyWrapper]: + return functools.partial(_KeyWrapper, mycmp) + + +# Reference: https://docs.python.org/3/library/functools.html#functools.reduce +@substitute_in_graph(functools.reduce) +def reduce( + function: Callable[[_U, _T], _U], + iterable: Iterable[_T], + initial: _U = _initial_missing, # type: ignore[assignment] + /, +) -> _U: + it = iter(iterable) + + value: _U + if initial is _initial_missing: + try: + value = next(it) # type: ignore[assignment] + except StopIteration: + raise TypeError( + "reduce() of empty iterable with no initial value", + ) from None + else: + value = initial + + for element in it: + value = function(value, element) + + return value diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/fx.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/fx.py new file mode 100644 index 0000000000000000000000000000000000000000..5a5ed97e0899d94fc4478de5acfa7879f5560ab2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/fx.py @@ -0,0 +1,41 @@ +from collections.abc import Callable +from typing import Any + +from torch._C import _fx_map_aggregate, _fx_map_arg +from torch.fx.immutable_collections import immutable_dict, immutable_list +from torch.fx.node import Node + +from ..decorators import substitute_in_graph + + +@substitute_in_graph(_fx_map_arg, can_constant_fold_through=True) +def map_arg(a: Any, fn: Callable[[Node], Any]) -> Any: + return map_aggregate(a, lambda x: fn(x) if isinstance(x, Node) else x) + + +@substitute_in_graph(_fx_map_aggregate, can_constant_fold_through=True) +def map_aggregate(a: Any, fn: Callable[[Any], Any]) -> Any: + result: Any + if isinstance(a, tuple): + it = (map_aggregate(elem, fn) for elem in a) + # Support NamedTuple (if it has `_fields`) by repacking into original type. + result = type(a)(*it) if hasattr(a, "_fields") else tuple(it) + elif isinstance(a, list): + result = immutable_list([map_aggregate(elem, fn) for elem in a]) + elif isinstance(a, dict): + result = immutable_dict([(k, map_aggregate(v, fn)) for k, v in a.items()]) + elif isinstance(a, slice): + result = slice( + map_aggregate(a.start, fn), + map_aggregate(a.stop, fn), + map_aggregate(a.step, fn), + ) + else: + result = fn(a) + return result + + +__all__ = [ + "map_arg", + "map_aggregate", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/heapq.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/heapq.py new file mode 100644 index 0000000000000000000000000000000000000000..feddb5723614f581fdd232a162feaf00a3ca2fae --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/heapq.py @@ -0,0 +1,119 @@ +""" +Python polyfills for heapq +""" + +from __future__ import annotations + +import heapq +import importlib +import sys +from typing import TYPE_CHECKING, TypeVar + +from ..decorators import substitute_in_graph + + +if TYPE_CHECKING: + from types import ModuleType + + +_T = TypeVar("_T") + + +# Partially copied from CPython test/support/import_helper.py +# https://github.com/python/cpython/blob/bb8791c0b75b5970d109e5557bfcca8a578a02af/Lib/test/support/import_helper.py +def _save_and_remove_modules(names: set[str]) -> dict[str, ModuleType]: + orig_modules = {} + prefixes = tuple(name + "." for name in names) + for modname in list(sys.modules): + if modname in names or modname.startswith(prefixes): + orig_modules[modname] = sys.modules.pop(modname) + return orig_modules + + +def import_fresh_module(name: str, blocked: list[str]) -> ModuleType: + # Keep track of modules saved for later restoration as well + # as those which just need a blocking entry removed + names = {name, *blocked} + orig_modules = _save_and_remove_modules(names) + for modname in blocked: + sys.modules[modname] = None # type: ignore[assignment] + + try: + return importlib.import_module(name) + finally: + _save_and_remove_modules(names) + sys.modules.update(orig_modules) + + +# Import the pure Python heapq module, blocking the C extension +py_heapq = import_fresh_module("heapq", blocked=["_heapq"]) + + +__all__ = [ + "_heapify_max", + "_heappop_max", + "_heapreplace_max", + "heapify", + "heappop", + "heappush", + "heappushpop", + "heapreplace", + "merge", + "nlargest", + "nsmallest", +] + + +@substitute_in_graph(heapq._heapify_max) +def _heapify_max(heap: list[_T], /) -> None: + return py_heapq._heapify_max(heap) + + +@substitute_in_graph(heapq._heappop_max) # type: ignore[attr-defined] +def _heappop_max(heap: list[_T]) -> _T: + return py_heapq._heappop_max(heap) + + +@substitute_in_graph(heapq._heapreplace_max) # type: ignore[attr-defined] +def _heapreplace_max(heap: list[_T], item: _T) -> _T: + return py_heapq._heapreplace_max(heap, item) + + +@substitute_in_graph(heapq.heapify) +def heapify(heap: list[_T], /) -> None: + return py_heapq.heapify(heap) + + +@substitute_in_graph(heapq.heappop) +def heappop(heap: list[_T], /) -> _T: + return py_heapq.heappop(heap) + + +@substitute_in_graph(heapq.heappush) +def heappush(heap: list[_T], item: _T) -> None: + return py_heapq.heappush(heap, item) + + +@substitute_in_graph(heapq.heappushpop) +def heappushpop(heap: list[_T], item: _T) -> _T: + return py_heapq.heappushpop(heap, item) + + +@substitute_in_graph(heapq.heapreplace) +def heapreplace(heap: list[_T], item: _T) -> _T: + return py_heapq.heapreplace(heap, item) + + +@substitute_in_graph(heapq.merge) # type: ignore[arg-type] +def merge(*iterables, key=None, reverse=False): # type: ignore[no-untyped-def] + return py_heapq.merge(*iterables, key=key, reverse=reverse) + + +@substitute_in_graph(heapq.nlargest) # type: ignore[arg-type] +def nlargest(n, iterable, key=None): # type: ignore[no-untyped-def] + return py_heapq.nlargest(n, iterable, key=key) + + +@substitute_in_graph(heapq.nsmallest) # type: ignore[arg-type] +def nsmallest(n, iterable, key=None): # type: ignore[no-untyped-def] + return py_heapq.nsmallest(n, iterable, key=key) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/io.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/io.py new file mode 100644 index 0000000000000000000000000000000000000000..a75e062f46e4682cab4421d1ac4ef5fc8997ea1b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/io.py @@ -0,0 +1,30 @@ +""" +Python polyfills for _io +""" + +from __future__ import annotations + +import _io + +import sys +import warnings + +from ..decorators import substitute_in_graph + + +__all__ = ["text_encoding"] + + +# Copied from Lib/_pyio.py in the standard library +# pyrefly: ignore [bad-argument-type] +@substitute_in_graph(_io.text_encoding, can_constant_fold_through=True) +def text_encoding(encoding: str | None, stacklevel: int = 2, /) -> str: + if encoding is None: + encoding = "utf-8" if sys.flags.utf8_mode else "locale" + if sys.flags.warn_default_encoding: + warnings.warn( + "'encoding' argument not specified.", + EncodingWarning, + stacklevel + 1, + ) + return encoding diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/itertools.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/itertools.py new file mode 100644 index 0000000000000000000000000000000000000000..9db422c7f66428d4f285da521c5d12adacfb2248 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/itertools.py @@ -0,0 +1,374 @@ +""" +Python polyfills for itertools +""" + +from __future__ import annotations + +import itertools +import operator +import sys +from collections.abc import Callable +from typing import overload, TYPE_CHECKING, TypeAlias, TypeVar + +from ..decorators import substitute_in_graph + + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator + + +__all__ = [ + "accumulate", + "combinations", + "combinations_with_replacement", + "compress", + "cycle", + "dropwhile", + "filterfalse", + "islice", + "pairwise", + "permutations", + "starmap", + "takewhile", + "tee", +] + +if sys.version_info >= (3, 12): + __all__.append("batched") + + +_T = TypeVar("_T") +_U = TypeVar("_U") +_Predicate: TypeAlias = Callable[[_T], object] +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.accumulate +@substitute_in_graph(itertools.accumulate, is_embedded_type=True) # type: ignore[arg-type] +def accumulate( + iterable: Iterable[_T], + func: Callable[[_T, _T], _T] | None = None, + *, + initial: _T | None = None, +) -> Iterator[_T]: + # call iter outside of the generator to match cpython behavior + iterator = iter(iterable) + if func is None: + func = operator.add + + def _accumulate(iterator: Iterator[_T]) -> Iterator[_T]: + total = initial + if total is None: + try: + total = next(iterator) + except StopIteration: + return + + yield total + for element in iterator: + total = func(total, element) + yield total + + return _accumulate(iterator) + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.combinations +@substitute_in_graph(itertools.combinations, is_embedded_type=True) # type: ignore[arg-type] +def combinations(iterable: Iterable[_T], r: int, /) -> Iterator[tuple[_T, ...]]: + pool = tuple(iterable) + n = len(pool) + + if r < 0: + raise ValueError("r must be non-negative") + + def _combinations() -> Iterator[tuple[_T, ...]]: + if r > n: + return + + indices = list(range(r)) + yield tuple(pool[i] for i in indices) + + while True: + for i in reversed(range(r)): + if indices[i] != i + n - r: + break + else: + return + + indices[i] += 1 + for j in range(i + 1, r): + indices[j] = indices[j - 1] + 1 + + yield tuple(pool[i] for i in indices) + + return _combinations() + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.compress +@substitute_in_graph(itertools.compress, is_embedded_type=True) # type: ignore[arg-type] +def compress(data: Iterable[_T], selectors: Iterable[_U], /) -> Iterator[_T]: + return (datum for datum, selector in zip(data, selectors) if selector) + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.cycle +@substitute_in_graph(itertools.cycle, is_embedded_type=True) # type: ignore[arg-type] +def cycle(iterable: Iterable[_T]) -> Iterator[_T]: + iterator = iter(iterable) + + def _cycle(iterator: Iterator[_T]) -> Iterator[_T]: + # pyrefly: ignore [implicit-any] + saved = [] + for element in iterable: + yield element + saved.append(element) + + while saved: + for element in saved: + yield element + + return _cycle(iterator) + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.dropwhile +@substitute_in_graph(itertools.dropwhile, is_embedded_type=True) # type: ignore[arg-type] +def dropwhile(predicate: _Predicate[_T], iterable: Iterable[_T], /) -> Iterator[_T]: + # dropwhile(lambda x: x < 5, [1, 4, 6, 3, 8]) -> 6 3 8 + if not callable(predicate): + raise TypeError(f"'{type(predicate).__name__}' object is not callable") + + iterator = iter(iterable) + for x in iterator: + if not predicate(x): + yield x + break + + yield from iterator + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.takewhile +@substitute_in_graph(itertools.takewhile, is_embedded_type=True) # type: ignore[arg-type] +def takewhile(predicate: _Predicate[_T], iterable: Iterable[_T], /) -> Iterator[_T]: + # takewhile(lambda x: x<5, [1,4,6,3,8]) → 1 4 + if not callable(predicate): + raise TypeError(f"'{type(predicate).__name__}' object is not callable") + + for x in iterable: + if not predicate(x): + break + yield x + + +@overload +def starmap( + function: Callable[[], _U], + iterable: Iterable[tuple[()]], + /, +) -> itertools.starmap[_U]: ... + + +@overload +def starmap( + function: Callable[[_T], _U], + iterable: Iterable[tuple[_T]], + /, +) -> itertools.starmap[_U]: ... + + +@overload +def starmap( + function: Callable[[_T, _T1], _U], + iterable: Iterable[tuple[_T, _T1]], + /, +) -> itertools.starmap[_U]: ... + + +@overload +def starmap( + function: Callable[[_T, _T1, _T2], _U], + iterable: Iterable[tuple[_T, _T1, _T2]], + /, +) -> itertools.starmap[_U]: ... + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.starmap +@substitute_in_graph(itertools.starmap, is_embedded_type=True) # type: ignore[arg-type] +# pyrefly: ignore [implicit-any] +def starmap(function: Callable[..., _T], iterable: Iterable, /) -> Iterable[_T]: + # starmap(pow, [(2,5), (3,2), (10,3)]) → 32 9 1000 + if not callable(function): + raise TypeError(f"'{type(function).__name__}' object is not callable") + + for args in iterable: + yield function(*args) + + +@substitute_in_graph(itertools.filterfalse, is_embedded_type=True) # type: ignore[arg-type] +def filterfalse(function: _Predicate[_T], iterable: Iterable[_T], /) -> Iterator[_T]: + it = iter(iterable) + if function is None: + return filter(operator.not_, it) + else: + return filter(lambda x: not function(x), it) + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.islice +@substitute_in_graph(itertools.islice, is_embedded_type=True) # type: ignore[arg-type] +def islice(iterable: Iterable[_T], /, *args: int | None) -> Iterator[_T]: + s = slice(*args) + start = 0 if s.start is None else s.start + stop = s.stop + step = 1 if s.step is None else s.step + if start < 0 or (stop is not None and stop < 0) or step <= 0: + raise ValueError( + "Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize.", + ) + + if stop is None: + # TODO: use indices = itertools.count() and merge implementation with the else branch + # when we support infinite iterators + next_i = start + for i, element in enumerate(iterable): + if i == next_i: + yield element + next_i += step + else: + indices = range(max(start, stop)) + next_i = start + for i, element in zip(indices, iterable): + if i == next_i: + yield element + next_i += step + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.pairwise +@substitute_in_graph(itertools.pairwise, is_embedded_type=True) # type: ignore[arg-type] +def pairwise(iterable: Iterable[_T], /) -> Iterator[tuple[_T, _T]]: + a = None + first = True + for b in iterable: + if first: + first = False + else: + yield a, b # type: ignore[misc] + a = b + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.permutations +@substitute_in_graph(itertools.permutations, is_embedded_type=True) # type: ignore[arg-type] +def permutations( + iterable: Iterable[_T], r: int | None = None, / +) -> Iterator[tuple[_T, ...]]: + pool = tuple(iterable) + n = len(pool) + r = n if r is None else r + + if r < 0: + raise ValueError("r must be non-negative") + + def _permutations() -> Iterator[tuple[_T, ...]]: + if r > n: + return + + indices = list(range(n)) + cycles = list(range(n, n - r, -1)) + yield tuple(pool[i] for i in indices[:r]) + + while n: + for i in reversed(range(r)): + cycles[i] -= 1 + if cycles[i] == 0: + indices[i:] = indices[i + 1 :] + indices[i : i + 1] + cycles[i] = n - i + else: + j = cycles[i] + indices[i], indices[-j] = indices[-j], indices[i] + yield tuple(pool[i] for i in indices[:r]) + break + else: + return + + return _permutations() + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.tee +@substitute_in_graph(itertools.tee) +def tee(iterable: Iterable[_T], n: int = 2, /) -> tuple[Iterator[_T], ...]: + iterator = iter(iterable) + shared_link = [None, None] + + def _tee(link) -> Iterator[_T]: # type: ignore[no-untyped-def] + try: + while True: + if link[1] is None: + link[0] = next(iterator) + link[1] = [None, None] + value, link = link + yield value + except StopIteration: + return + + return tuple(_tee(shared_link) for _ in range(n)) + + +# Reference: https://docs.python.org/3/library/itertools.html#itertools.combinations_with_replacement +@substitute_in_graph(itertools.combinations_with_replacement, is_embedded_type=True) # type: ignore[arg-type] +def combinations_with_replacement( + iterable: Iterable[_T], r: int, / +) -> Iterator[tuple[_T, ...]]: + if r < 0: + raise ValueError("r must be non-negative") + + pool = tuple(iterable) + n = len(pool) + + def _combinations_with_replacement() -> Iterator[tuple[_T, ...]]: + if r == 0: + yield () + return + if n == 0: + return + + indices = [0] * r + yield tuple(pool[i] for i in indices) + while True: + for i in range(r - 1, -1, -1): + if indices[i] != n - 1: + break + else: + return + indices[i:] = [indices[i] + 1] * (r - i) + yield tuple(pool[i] for i in indices) + + return _combinations_with_replacement() + + +if sys.version_info >= (3, 12): + # Reference: https://docs.python.org/3/library/itertools.html#itertools.batched + @substitute_in_graph(itertools.batched, is_embedded_type=True) # type: ignore[arg-type] + def batched(*args, **kwargs) -> Iterator[tuple[_T, ...]]: # type: ignore[no-untyped-def] + if len(args) != 2: + raise TypeError( + f"batched takes exactly 2 positional arguments({len(args)} given)" + ) + if kwargs.keys() - {"strict"}: + unexpected = next(iter(kwargs.keys() - {"strict"})) + raise TypeError( + f"batched() got an unexpected keyword argument '{unexpected}'" + ) + + iterable, n = args + strict = kwargs.get("strict", False) + n = operator.index(n) + if n < 1: + raise ValueError("n must be at least one") + + iterator = iter(iterable) + + def _batched(iterator: Iterator[_T]) -> Iterator[tuple[_T, ...]]: + while batch := tuple(islice(iterator, n)): + if strict and len(batch) != n: + raise ValueError("batched(): incomplete batch") + yield batch + + return _batched(iterator) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/loader.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/loader.py new file mode 100644 index 0000000000000000000000000000000000000000..9defe564e45fb843db3113ac6fc7ff5e9ca8ddcf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/loader.py @@ -0,0 +1,49 @@ +# Used to load and initialize polyfill handlers when importing torch._dynamo +# Please add a new import when adding a new polyfill module. + +import importlib +from typing import TYPE_CHECKING + +import torch.utils._pytree as python_pytree + +from .. import polyfills, trace_rules + + +if TYPE_CHECKING: + from types import ModuleType + + +# See also the TYPE_CHECKING block in torch/_dynamo/polyfills/__init__.py +POLYFILLED_MODULE_NAMES: tuple[str, ...] = ( + "_collections", + "builtins", + "copy", + "functools", + "io", + "itertools", + "operator", + "os", + "struct", + "sys", + "fx", + "tensor", + "torch_c_nn", + "traceback", +) +if python_pytree._cxx_pytree_dynamo_traceable: + POLYFILLED_MODULE_NAMES += ("pytree",) + +POLYFILLED_MODULES: tuple["ModuleType", ...] = tuple( + importlib.import_module(f".{submodule}", package=polyfills.__name__) + for submodule in POLYFILLED_MODULE_NAMES +) + + +# Unregister the builtin functions from _builtin_function_ids to let them to be +# dispatched with the appropriate VariableTracker type. Otherwise, they will be +# dispatched with BuiltinVariable if present in _builtin_function_ids. +for polyfill_module in POLYFILLED_MODULES: + for polyfill_name in polyfill_module.__all__: + polyfill_handler = getattr(polyfill_module, polyfill_name) + original_fn = polyfill_handler.__torch_dynamo_original__ + trace_rules._builtin_function_ids.remove(id(original_fn)) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/operator.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/operator.py new file mode 100644 index 0000000000000000000000000000000000000000..9b0eb3e64ae73724ab1996c8dc7fbd4dfb5c020d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/operator.py @@ -0,0 +1,132 @@ +""" +Python polyfills for operator +""" + +from __future__ import annotations + +import operator +from typing import Any, overload, TYPE_CHECKING, TypeVar +from typing_extensions import TypeVarTuple, Unpack + +from ..decorators import substitute_in_graph + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Sequence + + +# Most unary and binary operators are handled by BuiltinVariable (e.g., `pos`, `add`) +__all__ = ["attrgetter", "concat", "countOf", "iconcat", "itemgetter", "methodcaller"] + + +_T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_Ts = TypeVarTuple("_Ts") +_U = TypeVar("_U") +_U1 = TypeVar("_U1") +_U2 = TypeVar("_U2") +_Us = TypeVarTuple("_Us") + + +@overload +# pyrefly: ignore [inconsistent-overload] +def attrgetter(attr: str, /) -> Callable[[Any], _U]: ... + + +@overload +# pyrefly: ignore [inconsistent-overload] +def attrgetter( + attr1: str, attr2: str, /, *attrs: str +) -> Callable[[Any], tuple[_U1, _U2, Unpack[_Us]]]: ... + + +# Reference: https://docs.python.org/3/library/operator.html#operator.attrgetter +@substitute_in_graph(operator.attrgetter, is_embedded_type=True) # type: ignore[arg-type,misc] +def attrgetter(*attrs: str) -> Callable[[Any], Any | tuple[Any, ...]]: + if len(attrs) == 0: + raise TypeError("attrgetter expected 1 argument, got 0") + + if any(not isinstance(attr, str) for attr in attrs): + raise TypeError("attribute name must be a string") + + def resolve_attr(obj: Any, attr: str) -> Any: + for name in attr.split("."): + obj = getattr(obj, name) + return obj + + if len(attrs) == 1: + attr = attrs[0] + + def getter(obj: Any) -> Any: + return resolve_attr(obj, attr) + + else: + + def getter(obj: Any) -> tuple[Any, ...]: # type: ignore[misc] + return tuple(resolve_attr(obj, attr) for attr in attrs) + + return getter + + +# Reference: https://docs.python.org/3/library/operator.html#operator.concat +@substitute_in_graph(operator.concat, can_constant_fold_through=True) # type: ignore[arg-type] +def concat(a: Sequence[_T], b: Sequence[_T2], /) -> Sequence[_T | _T2]: + return a + b # type: ignore[operator] + + +# Reference: https://docs.python.org/3/library/operator.html#operator.countOf +@substitute_in_graph(operator.countOf, can_constant_fold_through=True) # type: ignore[arg-type,misc] +def countOf(a: Iterable[_T], b: _T, /) -> int: + return sum(it is b or it == b for it in a) + + +# Reference: https://docs.python.org/3/library/operator.html#operator.iconcat +@substitute_in_graph(operator.iconcat) # type: ignore[arg-type] +def iconcat(a: Sequence[_T], b: Sequence[_T2], /) -> Sequence[_T | _T2]: + a += b # type: ignore[operator] + return a # type: ignore[return-value] + + +@overload +# pyrefly: ignore [inconsistent-overload] +def itemgetter(item: _T, /) -> Callable[[Any], _U]: ... + + +@overload +# pyrefly: ignore [inconsistent-overload] +def itemgetter( + item1: _T1, item2: _T2, /, *items: Unpack[_Ts] +) -> Callable[[Any], tuple[_U1, _U2, Unpack[_Us]]]: ... + + +# Reference: https://docs.python.org/3/library/operator.html#operator.itemgetter +@substitute_in_graph(operator.itemgetter, is_embedded_type=True) # type: ignore[arg-type,misc] +def itemgetter(*items: Any) -> Callable[[Any], Any | tuple[Any, ...]]: + if len(items) == 0: + raise TypeError("itemgetter expected 1 argument, got 0") + + if len(items) == 1: + item = items[0] + + def getter(obj: Any) -> Any: + return obj[item] + + else: + + def getter(obj: Any) -> tuple[Any, ...]: # type: ignore[misc] + return tuple(obj[item] for item in items) + + return getter + + +# Reference: https://docs.python.org/3/library/operator.html#operator.methodcaller +@substitute_in_graph(operator.methodcaller, is_embedded_type=True) # type: ignore[arg-type] +def methodcaller(name: str, /, *args: Any, **kwargs: Any) -> Callable[[Any], Any]: + if not isinstance(name, str): + raise TypeError("method name must be a string") + + def caller(obj: Any) -> Any: + return getattr(obj, name)(*args, **kwargs) + + return caller diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/os.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/os.py new file mode 100644 index 0000000000000000000000000000000000000000..595b7f3636a0ec6d19f0df78fe7c49babe080435 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/os.py @@ -0,0 +1,37 @@ +""" +Python polyfills for os +""" + +from __future__ import annotations + +import os +from typing import AnyStr + +from ..decorators import substitute_in_graph + + +__all__ = ["fspath"] + + +# Copied from os.py in the standard library +# pyrefly: ignore [bad-argument-type] +@substitute_in_graph(os.fspath, can_constant_fold_through=True) +def fspath(path: AnyStr | os.PathLike[AnyStr]) -> AnyStr: + if isinstance(path, (str, bytes)): + return path + + path_type = type(path) + try: + path_repr = path_type.__fspath__(path) # type: ignore[arg-type] + except AttributeError: + if hasattr(path_type, "__fspath__"): + raise + raise TypeError( + f"expected str, bytes or os.PathLike object, not {path_type.__name__}", + ) from None + if isinstance(path_repr, (str, bytes)): + return path_repr # type: ignore[return-value] + raise TypeError( + f"expected {path_type.__name__}.__fspath__() to return str or bytes, " + f"not {type(path_repr).__name__}", + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/pytree.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/pytree.py new file mode 100644 index 0000000000000000000000000000000000000000..64eea6c7caaecda70209efcf52d84ed2959c0a89 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/pytree.py @@ -0,0 +1,823 @@ +# Owner(s): ["module: pytree"] + +""" +Python polyfills for torch.utils.pytree +""" + +from __future__ import annotations + +from collections import deque +from dataclasses import dataclass, field +from typing import Any, TYPE_CHECKING, TypeVar + +import optree +import optree._C +import optree.utils +from optree import ( + is_namedtuple, + is_namedtuple_class, + is_namedtuple_instance, + is_structseq, + is_structseq_class, + is_structseq_instance, + namedtuple_fields, + structseq_fields, +) + +import torch.utils._cxx_pytree as cxx_pytree # noqa: F401 # load the C++ extension module +import torch.utils._pytree as python_pytree +from torch.utils._pytree import BUILTIN_TYPES, STANDARD_DICT_TYPES + +from ..decorators import substitute_in_graph + + +if TYPE_CHECKING: + import builtins + from collections.abc import Callable, Iterable, Mapping + from typing_extensions import Self, TypeIs + + from torch.utils._cxx_pytree import PyTree + + +__all__ = [ + "is_namedtuple", + "is_namedtuple_class", + "is_namedtuple_instance", + "is_structseq", + "is_structseq_class", + "is_structseq_instance", + "namedtuple_fields", + "structseq_fields", + "treespec_leaf", + "treespec_tuple", + "treespec_dict", + "tree_is_leaf", + "tree_iter", + "tree_leaves", + "tree_flatten", + "tree_flatten_with_path", + "tree_structure", + "tree_unflatten", +] + + +_T = TypeVar("_T") +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") + + +@substitute_in_graph( + optree._C.is_dict_insertion_ordered, + can_constant_fold_through=True, +) +def _(*args: Any, **kwargs: Any) -> bool: + # In namespace 'torch', the dictionary is always traversed in insertion order. + # This function returns True. + raise ValueError( + "Should not be called directly " + "because the original function will be called in the constant fold path." + ) + + +__name = "" +for __name, __func in ( + ("is_namedtuple", is_namedtuple), + ("is_namedtuple_class", is_namedtuple_class), + ("is_namedtuple_instance", is_namedtuple_instance), + ("is_structseq", is_structseq), + ("is_structseq_class", is_structseq_class), + ("is_structseq_instance", is_structseq_instance), + ("namedtuple_fields", namedtuple_fields), + ("structseq_fields", structseq_fields), +): + globals()[__name] = substitute_in_graph( + __func, # type: ignore[arg-type] + can_constant_fold_through=True, + )(__func.__python_implementation__) # type: ignore[attr-defined] + del __func +del __name + + +@substitute_in_graph(optree.tree_is_leaf, can_constant_fold_through=True) # type: ignore[arg-type] +def tree_is_leaf( + tree: PyTree, + /, + is_leaf: Callable[[PyTree], bool] | None = None, + *, + none_is_leaf: bool = False, + namespace: str = "", +) -> bool: + if (tree is None and none_is_leaf) or (is_leaf is not None and is_leaf(tree)): + return True + if optree.register_pytree_node.get(type(tree), namespace=namespace) is None: + return True + return False + + +@substitute_in_graph(optree.tree_iter, can_constant_fold_through=False) # type: ignore[arg-type] +def tree_iter( + tree: PyTree, + /, + is_leaf: Callable[[PyTree], bool] | None = None, + *, + none_is_leaf: bool = False, + namespace: str = "", +) -> Iterable[Any]: + stack = [tree] + while stack: + node = stack.pop() + if tree_is_leaf( + node, + is_leaf=is_leaf, + none_is_leaf=none_is_leaf, + namespace=namespace, + ): + yield node + continue + + children, *_ = optree.tree_flatten_one_level( + node, + is_leaf=is_leaf, + none_is_leaf=none_is_leaf, + namespace=namespace, + ) + stack.extend(reversed(children)) + + +@substitute_in_graph(optree.tree_leaves, can_constant_fold_through=True) # type: ignore[arg-type] +def tree_leaves( + tree: PyTree, + /, + is_leaf: Callable[[PyTree], bool] | None = None, + *, + none_is_leaf: bool = False, + namespace: str = "", +) -> list[Any]: + return list( + tree_iter( + tree, + is_leaf=is_leaf, + none_is_leaf=none_is_leaf, + namespace=namespace, + ) + ) + + +class _Asterisk(str): + __slots__ = () + + def __new__(cls) -> Self: + return super().__new__(cls, "*") + + def __repr__(self) -> str: + return "*" # no quotes + + +_asterisk = _Asterisk() +del _Asterisk + + +@dataclass(frozen=True, repr=False, eq=False, unsafe_hash=False, slots=True) +class PyTreeSpec: + """Analog for :class:`optree.PyTreeSpec` in Python.""" + + _children: tuple[PyTreeSpec, ...] + _type: builtins.type | None + _metadata: Any + _entries: tuple[Any, ...] + _unflatten_func: Callable[[Any | None, Iterable[PyTree]], PyTree] | None + none_is_leaf: bool + namespace: str + + num_nodes: int = field(init=False) + num_leaves: int = field(init=False) + num_children: int = field(init=False) + + def __post_init__(self, /) -> None: + if self._type is None: + if len(self._children) != 0: + raise AssertionError("Leaf node must have no children") + if self._metadata is not None: + raise AssertionError("Leaf node must have no metadata") + if self._entries != (): + raise AssertionError("Leaf node must have no entries") + if self._unflatten_func is not None: + raise AssertionError("Leaf node must have no unflatten_func") + num_nodes = 1 + num_leaves = 1 + num_children = 0 + else: + if not callable(self._unflatten_func): + raise AssertionError( + "Non-leaf node must have a callable unflatten_func" + ) + num_nodes = 1 + num_leaves = 0 + for child in self._children: + num_nodes += child.num_nodes + num_leaves += child.num_leaves + num_children = len(self._children) + + object.__setattr__(self, "num_nodes", num_nodes) + object.__setattr__(self, "num_leaves", num_leaves) + object.__setattr__(self, "num_children", num_children) + + def __repr__(self, /) -> str: + def helper(treespec: PyTreeSpec) -> str: + if treespec.is_leaf(): + if treespec.type is not None: + raise AssertionError("Leaf treespec must have type None") + return _asterisk + + if treespec.type is None: + raise AssertionError("Non-leaf treespec must have a type") + if not callable(treespec._unflatten_func): + raise AssertionError( + "Non-leaf treespec must have a callable unflatten_func" + ) + children_representations = [ + helper(subspec) for subspec in treespec._children + ] + if ( + treespec.type in BUILTIN_TYPES + or (treespec.type is type(None) and not self.none_is_leaf) + or optree.is_namedtuple_class(treespec.type) + or optree.is_structseq_class(treespec.type) + ): + return treespec._unflatten_func( + treespec._metadata, + children_representations, + ) + return ( + f"CustomTreeNode({treespec.type.__name__}[{treespec._metadata!r}], " + f"[{', '.join(children_representations)}])" + ) + + inner = [ + str(helper(self)), + *(["NoneIsLeaf"] if self.none_is_leaf else []), + f"namespace={self.namespace!r}", + ] + return f"PyTreeSpec({', '.join(inner)})" + + def __len__(self, /) -> int: + return self.num_leaves + + def __eq__(self, other: Any, /) -> bool: + if not isinstance(other, PyTreeSpec): + return NotImplemented + if ( + self.none_is_leaf != other.none_is_leaf + or self.num_nodes != other.num_nodes + or self.num_leaves != other.num_leaves + or self._type is not other._type + or self._metadata != other._metadata + ): + return False + # A namespace mismatch is ignored if either side has an empty namespace, mirroring optree's + # `PyTreeSpec::EqualTo` (src/treespec/richcomparison.cpp). + if self.namespace and other.namespace and self.namespace != other.namespace: + return False + return self._children == other._children + + def __hash__(self, /) -> int: + node_type = self._type + if node_type in STANDARD_DICT_TYPES: + # Dict metadata is the (unhashable) list of keys; hash the keys instead. + node_data: Any = tuple(self._entries) + elif ( + node_type is None + or node_type in BUILTIN_TYPES + or optree.is_namedtuple_class(node_type) + or optree.is_structseq_class(node_type) + ): + node_data = self._metadata + else: + # Custom node metadata may be unhashable; hash the node type only, mirroring optree's + # `PyTreeSpec::HashValueImpl` (src/treespec/hashing.cpp). + node_data = None + # `namespace` is intentionally excluded: `__eq__` treats an empty namespace as a wildcard, + # so specs that compare equal must hash the same. + return hash( + ( + self.none_is_leaf, + node_type, + self.num_leaves, + self.num_nodes, + node_data, + self._children, + ) + ) + + @property + def type(self, /) -> builtins.type | None: + return self._type + + def is_leaf(self, /) -> bool: + return self.num_nodes == 1 and self.num_leaves == 1 + + def paths(self, /) -> list[tuple[Any, ...]]: + def helper(treespec: PyTreeSpec, path_prefix: list[Any]) -> None: + if treespec.is_leaf(): + paths.append(path_prefix) + return + + for entry, subspec in zip( + treespec._entries, + treespec._children, + strict=True, + ): + helper(subspec, path_prefix + [entry]) + + paths: list[list[Any]] = [] + helper(self, []) + return [tuple(path) for path in paths] + + def accessors(self, /) -> list[optree.PyTreeAccessor]: + def helper( + treespec: PyTreeSpec, + entry_path_prefix: list[optree.PyTreeEntry], + ) -> None: + if treespec.is_leaf(): + entry_paths.append(entry_path_prefix) + return + + node_type = treespec.type + if node_type is None: + raise AssertionError("Non-leaf treespec must have a type") + handler = optree.register_pytree_node.get( + node_type, namespace=treespec.namespace + ) + if handler is None: + raise AssertionError(f"No pytree handler registered for {node_type}") + kind: optree.PyTreeKind = handler.kind + path_entry_type: type[optree.PyTreeEntry] = handler.path_entry_type + + for entry, subspec in zip( + treespec._entries, + treespec._children, + strict=True, + ): + helper( + subspec, + entry_path_prefix + [path_entry_type(entry, node_type, kind)], + ) + + entry_paths: list[list[optree.PyTreeEntry]] = [] + helper(self, []) + return [optree.PyTreeAccessor(path) for path in entry_paths] + + def children(self, /) -> list[PyTreeSpec]: + return list(self._children) + + def child(self, index: int, /) -> PyTreeSpec: + return self._children[index] + + def entries(self, /) -> list[Any]: + return list(self._entries) + + def entry(self, index: int, /) -> Any: + return self._entries[index] + + def flatten_up_to(self, tree: PyTree, /) -> list[PyTree]: + def helper( + treespec: PyTreeSpec, + node: PyTree, + subtrees: list[PyTree], + ) -> None: + if treespec.is_leaf(): + subtrees.append(node) + return + + node_type = type(node) + if treespec.type not in BUILTIN_TYPES: + # Always require custom node types to match exactly + if node_type != treespec.type: + raise ValueError( + f"Type mismatch; " + f"expected {treespec.type!r}, but got {node_type!r}.", + ) + + children, metadata, *_ = optree.tree_flatten_one_level( + node, + none_is_leaf=self.none_is_leaf, + namespace=self.namespace, + ) + if len(children) != treespec.num_children: + raise ValueError( + f"Node arity mismatch; " + f"expected {treespec.num_children}, but got {len(children)}.", + ) + if metadata != treespec._metadata: + raise ValueError( + f"Node context mismatch for custom node type {treespec.type!r}.", + ) + else: + # For builtin dictionary types, we allow some flexibility + # Otherwise, we require exact matches + both_standard_dict = ( + treespec.type in STANDARD_DICT_TYPES + and node_type in STANDARD_DICT_TYPES + ) + if not both_standard_dict and node_type != treespec.type: + raise ValueError( + f"Node type mismatch; " + f"expected {treespec.type!r}, but got {node_type!r}.", + ) + if len(node) != treespec.num_children: + raise ValueError( + f"Node arity mismatch; " + f"expected {treespec.num_children}, but got {len(node)}.", + ) + + if both_standard_dict: + # dictionary types are compatible with each other + expected_keys = treespec.entries() + got_key_set = set(node) + expected_key_set = set(expected_keys) + if got_key_set != expected_key_set: + missing_keys = expected_key_set.difference(got_key_set) + extra_keys = got_key_set.difference(expected_key_set) + message = "" + if missing_keys: + message += f"; missing key(s): {missing_keys}" + if extra_keys: + message += f"; extra key(s): {extra_keys}" + raise ValueError(f"Node keys mismatch{message}.") + children = [node[key] for key in expected_keys] + else: + # node_type is treespec.type + children, metadata, *_ = optree.tree_flatten_one_level( + node, + none_is_leaf=self.none_is_leaf, + namespace=self.namespace, + ) + if ( + node_type is not deque # ignore mismatch of `maxlen` for deque + ) and metadata != treespec._metadata: + raise ValueError( + f"Node metadata mismatch for node type {treespec.type!r}; " + f"expected {treespec._metadata!r}, but got {metadata!r}.", # namedtuple type mismatch + ) + + for subtree, subspec in zip(children, treespec._children, strict=True): + helper(subspec, subtree, subtrees) + + subtrees: list[PyTree] = [] + helper(self, tree, subtrees) + return subtrees + + def unflatten(self, leaves: Iterable[Any], /) -> PyTree: + if not isinstance(leaves, (list, tuple)): + leaves = list(leaves) + if len(leaves) != self.num_leaves: + raise ValueError( + f"treespec.unflatten(leaves): `leaves` has length {len(leaves)} " + f"but the spec refers to a pytree that holds {self.num_leaves} " + f"items ({self}).", + ) + if self.is_leaf(): + return leaves[0] + + # Recursively unflatten the children + start = 0 + end = 0 + subtrees = [] + for subspec in self._children: + end += subspec.num_leaves + subtrees.append(subspec.unflatten(leaves[start:end])) + start = end + + if not callable(self._unflatten_func): + raise AssertionError("Non-leaf node must have a callable unflatten_func") + return self._unflatten_func(self._metadata, subtrees) + + +def _is_pytreespec_instance(obj: Any, /) -> TypeIs[PyTreeSpec | python_pytree.TreeSpec]: + return isinstance(obj, (PyTreeSpec, python_pytree.TreeSpec)) + + +@substitute_in_graph( # type: ignore[arg-type] + optree.treespec_leaf, + # We need to disable constant folding here because we want the function to reference the + # PyTreeSpec class defined above, not the one in the C++ module. + can_constant_fold_through=False, +) +def treespec_leaf( + *, + none_is_leaf: bool = False, + namespace: str = "", # unused +) -> PyTreeSpec: + return PyTreeSpec( + (), + None, + None, + (), + None, + none_is_leaf=none_is_leaf, + namespace="", + ) + + +@substitute_in_graph( # type: ignore[arg-type] + optree.treespec_tuple, + # We need to disable constant folding here because we want the function to reference the + # PyTreeSpec class defined above, not the one in the C++ module. + can_constant_fold_through=False, +) +def treespec_tuple( + iterable: Iterable[PyTreeSpec] = (), + /, + *, + none_is_leaf: bool = False, + namespace: str = "", +) -> PyTreeSpec: + children = tuple(iterable) + if any(not _is_pytreespec_instance(child) for child in children): + raise ValueError(f"Expected a tuple of PyTreeSpecs, got: {children!r}.") + if any(child.none_is_leaf != none_is_leaf for child in children): + raise ValueError( + "All children PyTreeSpecs must have the same `none_is_leaf` value " + f"as the parent; expected {none_is_leaf}, got: {children!r}.", + ) + if any(child.namespace not in (namespace, "") for child in children): + raise ValueError( + "All children PyTreeSpecs must have the same `namespace` value " + f"as the parent; expected {namespace!r}, got: {children!r}.", + ) + handler = optree.register_pytree_node.get(tuple, namespace=namespace) + if handler is None: + raise AssertionError("No pytree handler registered for tuple") + return PyTreeSpec( + tuple(children), + tuple, + None, + tuple(range(len(children))), + handler.unflatten_func, + none_is_leaf=none_is_leaf, + namespace=namespace, + ) + + +@substitute_in_graph( # type: ignore[arg-type] + optree.treespec_dict, + # We need to disable constant folding here because we want the function to reference the + # PyTreeSpec class defined above, not the one in the C++ module. + can_constant_fold_through=False, +) +def treespec_dict( + mapping: Mapping[Any, PyTreeSpec] | Iterable[tuple[Any, PyTreeSpec]] = (), + /, + *, + none_is_leaf: bool = False, + namespace: str = "", + **kwargs: PyTreeSpec, +) -> PyTreeSpec: + dct = dict(mapping, **kwargs) + if any(not _is_pytreespec_instance(child) for child in dct.values()): + raise ValueError(f"Expected a dictionary of TreeSpecs, got: {dct!r}.") + if any(child.none_is_leaf != none_is_leaf for child in dct.values()): + raise ValueError( + "All children PyTreeSpecs must have the same `none_is_leaf` value " + f"as the parent; expected {none_is_leaf}, got: {dct!r}.", + ) + if any(child.namespace not in (namespace, "") for child in dct.values()): + raise ValueError( + "All children PyTreeSpecs must have the same `namespace` value " + f"as the parent; expected {namespace!r}, got: {dct!r}.", + ) + + ( + children, + metadata, + entries, + unflatten_func, + ) = optree.tree_flatten_one_level( # type: ignore[assignment,var-annotated] + dct, # type: ignore[arg-type] + none_is_leaf=none_is_leaf, + namespace=namespace, + ) + return PyTreeSpec( + tuple(children), # type: ignore[arg-type] + dict, + metadata, + entries, + unflatten_func, # type: ignore[arg-type] + none_is_leaf=none_is_leaf, + namespace=namespace, + ) + + +@substitute_in_graph( # type: ignore[arg-type] + optree.tree_flatten, + # We need to disable constant folding here because we want the function to reference the + # PyTreeSpec class defined above, not the one in the C++ module. + can_constant_fold_through=False, +) +def tree_flatten( + tree: PyTree, + /, + is_leaf: Callable[[PyTree], bool] | None = None, + *, + none_is_leaf: bool = False, + namespace: str = "", +) -> tuple[list[Any], PyTreeSpec]: + def helper(node: PyTree, leaves: list[Any]) -> PyTreeSpec: + if tree_is_leaf( + node, + is_leaf=is_leaf, + none_is_leaf=none_is_leaf, + namespace=namespace, + ): + leaves.append(node) + return PyTreeSpec( + (), + None, + None, + (), + None, + none_is_leaf=none_is_leaf, + namespace="", + ) + + ( + children, + metadata, + entries, + unflatten_func, + ) = optree.tree_flatten_one_level( + node, + is_leaf=is_leaf, + none_is_leaf=none_is_leaf, + namespace=namespace, + ) + + # Recursively flatten the children + subspecs = tuple(helper(child, leaves) for child in children) + return PyTreeSpec( + subspecs, + type(node), + metadata, + entries, + unflatten_func, # type: ignore[arg-type] + none_is_leaf=none_is_leaf, + namespace=namespace, + ) # type: ignore[arg-type] + + leaves: list[Any] = [] + treespec = helper(tree, leaves) + return leaves, treespec + + +@substitute_in_graph( # type: ignore[arg-type] + optree._C.flatten, + # We need to disable constant folding here because we want the function to reference the + # PyTreeSpec class defined above, not the one in the C++ module. + can_constant_fold_through=False, +) +def _C_flatten( + tree: PyTree, + /, + leaf_predicate: Callable[[PyTree], bool] | None = None, + none_is_leaf: bool = False, + namespace: str = "", +) -> tuple[list[Any], PyTreeSpec]: + return tree_flatten( # type: ignore[return-value] + tree, + is_leaf=leaf_predicate, + none_is_leaf=none_is_leaf, + namespace=namespace, + ) + + +@substitute_in_graph( # type: ignore[arg-type] + optree.tree_flatten_with_path, + # We need to disable constant folding here because we want the function to reference the + # PyTreeSpec class defined above, not the one in the C++ module. + can_constant_fold_through=False, +) +def tree_flatten_with_path( + tree: PyTree, + /, + is_leaf: Callable[[PyTree], bool] | None = None, + *, + none_is_leaf: bool = False, + namespace: str = "", +) -> tuple[list[tuple[Any, ...]], list[Any], PyTreeSpec]: + leaves, treespec = tree_flatten( + tree, + is_leaf=is_leaf, + none_is_leaf=none_is_leaf, + namespace=namespace, + ) + return treespec.paths(), leaves, treespec # type: ignore[return-value] + + +@substitute_in_graph( # type: ignore[arg-type] + optree._C.flatten_with_path, + # We need to disable constant folding here because we want the function to reference the + # PyTreeSpec class defined above, not the one in the C++ module. + can_constant_fold_through=False, +) +def _C_flatten_with_path( + tree: PyTree, + /, + leaf_predicate: Callable[[PyTree], bool] | None = None, + none_is_leaf: bool = False, + namespace: str = "", +) -> tuple[list[tuple[Any, ...]], list[Any], PyTreeSpec]: + return tree_flatten_with_path( # type: ignore[return-value] + tree, + is_leaf=leaf_predicate, + none_is_leaf=none_is_leaf, + namespace=namespace, + ) + + +@substitute_in_graph( # type: ignore[arg-type] + optree.tree_structure, + # We need to disable constant folding here because we want the function to reference the + # PyTreeSpec class defined above, not the one in the C++ module. + can_constant_fold_through=False, +) +def tree_structure( + tree: PyTree, + /, + is_leaf: Callable[[PyTree], bool] | None = None, + *, + none_is_leaf: bool = False, + namespace: str = "", +) -> PyTreeSpec: + return tree_flatten( # type: ignore[return-value] + tree, + is_leaf=is_leaf, + none_is_leaf=none_is_leaf, + namespace=namespace, + )[1] + + +@substitute_in_graph( # type: ignore[arg-type] + optree.tree_unflatten, + # We need to disable constant folding here because we want the function to reference the + # PyTreeSpec class defined above, not the one in the C++ module. + can_constant_fold_through=False, +) +def tree_unflatten(treespec: PyTreeSpec, leaves: Iterable[Any]) -> PyTree: + if not _is_pytreespec_instance(treespec): + raise TypeError( + f"Expected `treespec` to be an instance of " + f"PyTreeSpec but got item of type {type(treespec)}." + ) + return treespec.unflatten(leaves) + + +_none_registration = optree.register_pytree_node.get(type(None)) +if _none_registration is None: + raise AssertionError("No pytree handler registered for NoneType") + + +@substitute_in_graph( # type: ignore[arg-type] + _none_registration.unflatten_func, + can_constant_fold_through=True, + skip_signature_check=True, +) +def none_unflatten(_: None, children: Iterable[_T], /) -> None: + if len(list(children)) != 0: + raise ValueError("Expected no children.") + return None + + +with optree.dict_insertion_ordered(False, namespace="torch"): + _dict_registration = optree.register_pytree_node.get(dict) + if _dict_registration is None: + raise AssertionError("No pytree handler registered for dict") + + +@substitute_in_graph( # type: ignore[arg-type] + _dict_registration.flatten_func, + can_constant_fold_through=True, + skip_signature_check=True, +) +def dict_flatten( + dct: dict[_KT, _VT], / +) -> tuple[list[_VT], tuple[list[_KT], list[_KT]], tuple[_KT, ...]]: + sorted_keys = optree.utils.total_order_sorted(dct) + values = [dct[key] for key in sorted_keys] + original_keys = list(dct) + return values, (original_keys, sorted_keys), tuple(sorted_keys) + + +@substitute_in_graph( # type: ignore[arg-type] + _dict_registration.unflatten_func, + can_constant_fold_through=True, + skip_signature_check=True, +) +def dict_unflatten( + metadata: tuple[list[_KT], list[_KT]], + values: Iterable[_VT], + /, +) -> dict[_KT, _VT]: + original_keys, sorted_keys = metadata + d = dict.fromkeys(original_keys) + d.update(zip(sorted_keys, values, strict=True)) + return d # type: ignore[return-value] diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/struct.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/struct.py new file mode 100644 index 0000000000000000000000000000000000000000..4077a7f05788e3c32dba6bba09f3c15eb603db64 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/struct.py @@ -0,0 +1,27 @@ +""" +Python polyfills for struct +""" + +from __future__ import annotations + +import struct +from typing import Any +from typing_extensions import Buffer + +from ..decorators import substitute_in_graph + + +__all__ = [ + "pack", + "unpack", +] + + +@substitute_in_graph(struct.pack, can_constant_fold_through=True) # type: ignore[arg-type] +def pack(format: bytes | str, /, *v: Any) -> bytes: + return struct.pack(format, *v) + + +@substitute_in_graph(struct.unpack, can_constant_fold_through=True) # type: ignore[arg-type] +def unpack(format: bytes | str, buffer: Buffer, /) -> tuple[Any, ...]: + return struct.unpack(format, buffer) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/sys.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/sys.py new file mode 100644 index 0000000000000000000000000000000000000000..d04a8b2febc64a1f4d340f1e7c337c7ac6876054 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/sys.py @@ -0,0 +1,39 @@ +""" +Python polyfills for sys +""" + +from __future__ import annotations + +import sys + +from ..decorators import substitute_in_graph + + +__all__ = [ + "intern", + "getrecursionlimit", +] + + +# pyrefly: ignore [bad-argument-type] +@substitute_in_graph(sys.intern, can_constant_fold_through=True) +def intern(string: str, /) -> str: + return string + + +@substitute_in_graph(sys.getrecursionlimit, can_constant_fold_through=True) +def getrecursionlimit() -> int: + return sys.getrecursionlimit() + + +if sys.version_info >= (3, 11): + + @substitute_in_graph(sys.get_int_max_str_digits, can_constant_fold_through=True) + def get_int_max_str_digits() -> int: + return sys.get_int_max_str_digits() + + @substitute_in_graph(sys.set_int_max_str_digits, can_constant_fold_through=True) + def set_int_max_str_digits(maxdigits: int) -> None: + sys.set_int_max_str_digits(maxdigits) + + __all__ += ["get_int_max_str_digits", "set_int_max_str_digits"] diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/tensor.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..0fcad636200414e4cc0aa67fa0600463e5a9e1d4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/tensor.py @@ -0,0 +1,51 @@ +from typing import Any + +import torch + +from ..decorators import substitute_in_graph + + +@substitute_in_graph( # type: ignore[arg-type] + torch.Tensor._make_subclass +) +def make_subclass( + cls: type[Any], data: torch.Tensor, requires_grad: bool = False, **kwargs: Any +) -> Any: + with torch._C.DisableTorchFunctionSubclass(): + # This is a rough approximation of `THPVariable_make_subclass`. It should + # suffice for most of Dynamo tracing purposes. + # https://github.com/pytorch/pytorch/blob/ccfde4dadfa3c342076a1ee387017f84dd4ad2f7/torch/csrc/autograd/python_variable.cpp#L597-L650 + if len(kwargs) != 0: + raise AssertionError( + "_make_subclass only supports requires_grad as keyword arg" + ) + data = data.detach() + + # Avoid unnecessary `requires_grad` mutation, which isn't supported in Dynamo. + if data.requires_grad != requires_grad: + data.requires_grad = requires_grad + + # Dynamo can't yet handle upcasting to base tensor type via `as_subclass`. + if cls is torch.Tensor: + return torch.Tensor(data) + + # Calling `as_subclass` because + # 1. Dynamo knows how to handle it + # 2. the C impls match at this point -- both `THPVariable_make_subclass` and + # `THPVariable_as_subclass` calls `THPVariable_NewWithVar`. + return data.as_subclass(cls) + + +@substitute_in_graph( # type: ignore[arg-type] + torch.Tensor.__new__ +) +def tensor_pynew( + cls: type[Any], data: torch.Tensor, requires_grad: bool = False, **kwargs: Any +) -> Any: + return make_subclass(cls, data, requires_grad, **kwargs) + + +__all__ = [ + "make_subclass", + "tensor_pynew", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/torch_c_nn.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/torch_c_nn.py new file mode 100644 index 0000000000000000000000000000000000000000..c2258adac4cd3c636172a822e0683caf5c2ede74 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/torch_c_nn.py @@ -0,0 +1,121 @@ +""" +Polyfills for torch._C._nn functions. +""" + +from typing import Any + +import torch +from torch.overrides import _is_torch_function_mode_enabled, _pop_mode_temporarily + +from ..decorators import substitute_in_graph + + +@substitute_in_graph(torch._C._nn._parse_to, skip_signature_check=True) +def _parse_to_polyfill( + *args: Any, **kwargs: Any +) -> tuple[torch.device, torch.dtype, bool, torch.memory_format]: + """ + Polyfill for torch._C._nn._parse_to that parses arguments to nn.Module.to(). + + Signature mirrors torch._C._nn._parse_to which accepts: + - to(device) - device as string or torch.device + - to(dtype) - dtype as torch.dtype + - to(tensor) - extracts device and dtype from tensor + - to(device=..., dtype=..., non_blocking=..., memory_format=...) + + Returns: + tuple: (device, dtype, non_blocking, memory_format) + """ + # Check for __torch_function__ mode and dispatch using handle_torch_function pattern + if _is_torch_function_mode_enabled(): + with _pop_mode_temporarily() as mode: + result = mode.__torch_function__( + torch._C._nn._parse_to, tuple(), args, kwargs or {} + ) + if result is not NotImplemented: + return result + + # Default implementation + device = None + dtype = None + non_blocking = False + memory_format = None + + # Handle positional arguments + if len(args) == 1: + arg = args[0] + # Check if it's a tensor + if isinstance(arg, torch.Tensor): + device = arg.device + dtype = arg.dtype + # Check if it's a dtype + elif isinstance(arg, torch.dtype): + dtype = arg + # Check if it's a device (string or torch.device) + elif isinstance(arg, (str, torch.device)): + device = torch.device(arg) if isinstance(arg, str) else arg + else: + raise TypeError( + f"to() received an invalid combination of arguments. Got: {type(arg)}" + ) + elif len(args) > 1: + raise TypeError( + f"to() received too many positional arguments. Got {len(args)}, expected at most 1" + ) + + # Handle keyword arguments + if "device" in kwargs: + device_arg = kwargs["device"] + if device_arg is not None: + device = ( + torch.device(device_arg) if isinstance(device_arg, str) else device_arg + ) + + if "dtype" in kwargs: + dtype = kwargs["dtype"] + + if "non_blocking" in kwargs: + non_blocking = kwargs["non_blocking"] + + if "memory_format" in kwargs: + memory_format = kwargs["memory_format"] + + # pyrefly: ignore[bad-return] + return (device, dtype, non_blocking, memory_format) + + +@substitute_in_graph(torch.__future__.get_swap_module_params_on_conversion) +def get_swap_module_params_on_conversion_polyfill() -> bool: + """ + Polyfill for torch.__future__.get_swap_module_params_on_conversion. + + Returns the actual value from the underlying global variable. + """ + # Access the module's global variable directly to avoid recursion + import torch.__future__ as torch_future + + return torch_future._swap_module_params_on_conversion + + +@substitute_in_graph(torch._has_compatible_shallow_copy_type) +def _has_compatible_shallow_copy_type_polyfill( + input: torch.Tensor, from_: torch.Tensor +) -> bool: + """ + Polyfill for torch._has_compatible_shallow_copy_type. + + Checks if two tensors have compatible types for shallow copying. + The C++ implementation checks if input's TensorImpl has compatible shallow copy type + with from_'s key_set. We approximate this by checking if both tensors are the same type. + """ + # Check if both tensors are the same type (handles both regular tensors and subclasses) + # This is more permissive than checking exact torch.Tensor type equality + # but properly handles subclasses by allowing same-type shallow copies + return type(input) is type(from_) + + +__all__ = [ + "_parse_to_polyfill", + "get_swap_module_params_on_conversion_polyfill", + "_has_compatible_shallow_copy_type_polyfill", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/traceback.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/traceback.py new file mode 100644 index 0000000000000000000000000000000000000000..f44f59ad0c444e9da3f4b218ac2c4b5be9e6276d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/polyfills/traceback.py @@ -0,0 +1,39 @@ +""" +Python polyfills for traceback +""" + +import traceback +from traceback import StackSummary +from types import TracebackType + +from ..decorators import substitute_in_graph + + +__all__ = ["extract_tb", "clear_frames"] + + +@substitute_in_graph(traceback.extract_tb, can_constant_fold_through=True) +def extract_tb(tb: TracebackType | None, limit: int | None = None) -> StackSummary: + if tb is None: + return traceback.StackSummary.from_list([]) + # pyrefly: ignore [implicit-any] + frame_summary = [] + while tb is not None: + if limit: + if len(frame_summary) < limit: + frame_summary.append( + # pyrefly: ignore[missing-attribute] + tb.frame_summary + ) + else: + break + else: + frame_summary.append(tb.frame_summary) # pyrefly: ignore[missing-attribute] + tb = tb.tb_next + return traceback.StackSummary.from_list(frame_summary) + + +@substitute_in_graph(traceback.clear_frames, can_constant_fold_through=True) +def clear_frames(tb: TracebackType | None) -> None: + # no-op + return None diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/precompile_context.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/precompile_context.py new file mode 100644 index 0000000000000000000000000000000000000000..5a1f31f1a54b7a388083b12422cbb3196a75d4b5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/precompile_context.py @@ -0,0 +1,232 @@ +import copy +import json +import logging +from abc import abstractmethod +from collections import defaultdict +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any, Generic, TypeVar + +import torch +from torch._dynamo.package import ( + _BackendId, + _DynamoCacheEntry, + DynamoCache, + PrecompileCacheEntry, +) + + +""" +Classes and implementations related to precompile +""" + +T = TypeVar("T") +logger = logging.getLogger(__name__) + + +@dataclass +class BackendCacheArtifact(Generic[T]): + """ + Represents a single serializable backend artifact from a dynamo backend. + Each BackendCacheArtifact has a key associated with it along with some + serializable content. + + Example implementation: + + class MyPrecompileCacheArtifact(PrecompileCacheArtifact[MySerializableType]): + my_field: int + + def after_deserialization(self) -> MySerializableType: + result = pickle.loads(self.content) + # Do some extra work post deserialization + result.my_post_deserialization_function(self.my_field) + return result + """ + + key: str + content: Any + + @abstractmethod + def after_deserialization(self) -> T: + """ + Code to be run after reading raw byte contents from disk. + Generally converts self.content from raw bytes back into its original form. + """ + ... + + def edit_contents(self, edit_fn: Callable[..., Any]) -> None: + """ + Edit the contents of the artifact. + """ + self.content = edit_fn(self.content) + + +class EagerCacheArtifact(BackendCacheArtifact[Any]): + def after_deserialization(self) -> Any: + return self.content + + +class BypassDynamoCacheEntry(Exception): + pass + + +class PrecompileContext: + """ + PrecompileContext is a special CacheArtifactManager for handling precompilation + It uses the same interface as CacheArtifactManager, but handles deserialization differently: instead + of placing each artifact into respective caches, it will stitch all the cache artifacts for a single key + together and place it into a global Precompile Cache. + + PrecompileContext has two main portions: dynamo_cache_entries and backend_cache_artifacts. + When saving, PrecompileContext.serialize() will serialize all dynamo cache entries along with any PrecompileCacheArtifacts that + are needed to save those dynamo cache entries. + + The following artifact types are supported by PrecompileContext: + - BundledAOTAutogradCacheArtifact + + """ + + # Protected by the compile_lock + # _backend_artifacts_by_key organizes results by the key of each artifact. + # Each object here must be serializable + _backend_artifacts_by_key: dict[_BackendId, BackendCacheArtifact[Any]] = {} + + # On call to `serialize()`, all cache artifacts in _dynamo_cache_entries are converted + # into DynamoCacheArtifacts and added to _new_cache_artifacts for serialization + _dynamo_cache_entries: dict[str, _DynamoCacheEntry] = {} + + @classmethod + def clear(cls) -> None: + cls._backend_artifacts_by_key.clear() + cls._dynamo_cache_entries.clear() + + @classmethod + def record_artifact( + cls, + artifact: BackendCacheArtifact[Any], + ) -> None: + """ + Records a backend artifact to be used with dynamo cache entries + """ + # Temporarily disable all dispatch modes (including FakeTensorMode) during + # deepcopy to avoid issues with cloning fake tensors (e.g., device mesh + # with meta tensors that fail when cloning due to device mismatches) + from torch.utils._mode_utils import no_dispatch + + with no_dispatch(): + cls._backend_artifacts_by_key[_BackendId(artifact.key)] = copy.deepcopy( + artifact + ) + + @classmethod + def record_dynamo_cache_entry( + cls, cache_entry: _DynamoCacheEntry, key: str + ) -> None: + cls._dynamo_cache_entries[key] = cache_entry + + @classmethod + def edit_artifact(cls, key: str, edit_fn: Callable[..., Any]) -> None: + """ + Edit the content of an existing artifact + """ + if key not in cls._backend_artifacts_by_key: + raise AssertionError(f"Key {key} not found in artifacts") + artifact = cls._backend_artifacts_by_key[_BackendId(key)] + artifact.edit_contents(edit_fn) + + @classmethod + def serialize_artifact_by_key(cls, key: str) -> BackendCacheArtifact[Any] | None: + """ + Return the backend cache artifact with the associated key + """ + return cls._backend_artifacts_by_key.get(_BackendId(key), None) + + @staticmethod + def dump_debug_info( + dynamo_entries: dict[str, _DynamoCacheEntry], + backend_artifacts: dict[_BackendId, BackendCacheArtifact[Any]], + ) -> dict[str, Any]: + """ + Return a JSON serializable debug dump of all entries in the precompile context + Called in serialize before serialization, and in populate_caches after deserialization + """ + # Print debug information + debug_info: defaultdict[str, list[Any]] = defaultdict(list) + for key, cache_entry in dynamo_entries.items(): + info = cache_entry.debug_info() + info["key"] = key + debug_info["dynamo"].append(info) + + for artifact in backend_artifacts.values(): + debug_info["backends"].append(artifact.key) + + return debug_info + + @classmethod + def save_to_dynamo_cache(cls) -> dict[str, Any]: + precompile_cache_entries, debug_info = cls.create_cache_entries() + for key, entry in precompile_cache_entries.items(): + DynamoCache.write(entry, key) + return debug_info + + @classmethod + def create_cache_entries( + cls, + ) -> tuple[dict[str, PrecompileCacheEntry], dict[str, Any]]: + """ + Grabs all the cache entries in the precompile context and + stitches them together into full PrecompileCacheEntries. + """ + dynamo_entries = cls._dynamo_cache_entries + backend_artifacts = cls._backend_artifacts_by_key + + num_artifacts = len(dynamo_entries) + + debug_info = PrecompileContext.dump_debug_info( + dynamo_entries, backend_artifacts + ) + debug_str = json.dumps( + { + "num_entries": num_artifacts, + "artifacts": debug_info, + }, + ) + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "dynamo_cache_entries", + "encoding": "json", + }, + payload_fn=lambda: debug_str, + expect_trace_id=False, + ) + + precompile_cache_entries = {} + + for key, cache_entry in dynamo_entries.items(): + try: + result = PrecompileCacheEntry.from_cache_entry( + cache_entry, backend_artifacts + ) + if result is not None: + precompile_cache_entries[key] = result + except Exception as e: + logger.warning("Failed to create cache entry %s", key, exc_info=True) + + error = e + data = json.dumps( + { + "key": key, + "error": str(error), + } + ) + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "dynamo_cache_exception", + "encoding": "json", + }, + payload_fn=lambda: data, + ) + continue + return precompile_cache_entries, debug_info diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/profiler.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..d1edd1ea9cfadede4d4337fd626e0df5151e8a9e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/profiler.py @@ -0,0 +1,177 @@ +""" +Dynamo profiling implementation. + +This module provides profiling functionality for Dynamo, including: +- ProfileMetrics: Class for collecting and aggregating performance metrics like + execution time, operator counts, and fusion statistics +- ProfileResult: Class for analyzing and reporting profiling results +- Utilities for tracking missed/uncaptured operations +- Functions for instrumenting FX graphs with profiling capabilities + +The profiler helps measure and optimize the performance of Dynamo-compiled code +by tracking both captured and total operations, timing, and graph statistics. +""" + +from __future__ import annotations + +import dataclasses +import os +from typing import Any +from typing_extensions import Self + +import torch + +from .utils import print_once + + +@dataclasses.dataclass +class ProfileMetrics: + microseconds: float = 0.0 + operators: int = 0 + fusions: int = 0 + graphs: int = 0 + + def __iadd__(self, other: Self) -> Self: + self.microseconds += other.microseconds + self.operators += other.operators + self.fusions += other.fusions + return self + + def __add__(self, other: ProfileMetrics) -> ProfileMetrics: + if not isinstance(other, ProfileMetrics): + raise AssertionError(f"Expected ProfileMetrics, got {type(other)}") + return ProfileMetrics( + self.microseconds + other.microseconds, + self.operators + other.operators, + self.fusions + other.fusions, + ) + + def __truediv__(self, other: Any) -> ProfileMetrics: + if isinstance(other, int): + other = ProfileMetrics(other, other, other) + return ProfileMetrics( + self.microseconds / max(1, other.microseconds), + # pyrefly: ignore [bad-argument-type] + self.operators / max(1, other.operators), + # pyrefly: ignore [bad-argument-type] + self.fusions / max(1, other.fusions), + ) + + def __str__(self) -> str: + return f"{self.operators:4.0%} ops {self.microseconds:4.0%} time" + + def tocsv(self) -> list[float]: + return [self.operators, self.microseconds] + + +class ProfileResult: + def __init__( + self, captured: ProfileMetrics, total: ProfileMetrics, unique_graphs: int + ) -> None: + self.captured: ProfileMetrics = captured or ProfileMetrics() + self.total: ProfileMetrics = total or ProfileMetrics() + self.unique_graphs: int = unique_graphs + + def __iadd__(self, other: Self) -> Self: + self.captured += other.captured + self.total += other.total + self.unique_graphs += other.unique_graphs + return self + + def percent(self) -> ProfileMetrics: + return self.captured / self.total + + def __str__(self) -> str: + return ( + f"{self.unique_graphs:2} graphs {self.captured.graphs:2} graph calls " + f"{self.captured.operators:4}/{self.total.operators:4} = " + + str(self.percent()) + ) + + def tocsv(self) -> list[Any]: + return [ + self.unique_graphs, + self.captured.graphs, + self.captured.operators, + self.total.operators, + ] + self.percent().tocsv() + + +def should_print_missing() -> bool: + return os.environ.get("TORCHDYNAMO_PRINT_MISSING") == "1" + + +def print_missing(stack: list[str]) -> None: + if any("/torch/autograd/profiler.py" in x for x in stack): + return + stack = [ + x for x in stack if ("> ".join(stack[-3:])) + + +class Profiler: + unique_graphs: int = 0 + + def __init__(self) -> None: + self.prof = torch.profiler.profile( + activities=[torch.profiler.ProfilerActivity.CPU], + with_stack=should_print_missing(), + ) + + def results(self) -> ProfileResult: + captured_regions = 0 + captured_ops = 0 + captured_microseconds = 0 + total_ops = 0 + total_microseconds = 0 + + last_op_end_time = -1 + captured_region_end_time = -1 + events = sorted(self.prof.events(), key=lambda x: x.time_range.start) + for e in events: + if e.name == "TORCHDYNAMO": + captured_region_end_time = e.time_range.end + captured_regions += 1 + # ignore `handle = torch.zeros(1)` in record_function.__init__() + total_ops -= 1 + elif e.time_range.start >= last_op_end_time: + last_op_end_time = e.time_range.end + if e.time_range.end <= captured_region_end_time: + captured_ops += 1 + captured_microseconds += e.time_range.elapsed_us() + elif should_print_missing(): + print_missing(e.stack) + total_ops += 1 + total_microseconds += e.time_range.elapsed_us() + else: + pass # ops recursively called from other ops (ignored) + + unique_graphs = Profiler.unique_graphs + Profiler.unique_graphs = 0 + # we counted one extra op that is part of the profiler setup code + total_ops -= 1 + + return ProfileResult( + captured=ProfileMetrics( + microseconds=captured_microseconds, + operators=captured_ops, + fusions=captured_ops - captured_regions, + graphs=captured_regions, + ), + total=ProfileMetrics( + microseconds=total_microseconds, + operators=total_ops, + fusions=total_ops - 1, + ), + unique_graphs=unique_graphs, + ) + + +def fx_insert_profiling(gm: torch.fx.GraphModule, example_inputs: list[Any]) -> Any: + def _wrapped(*args: Any) -> Any: + with torch.profiler.record_function("TORCHDYNAMO"): + return gm.forward(*args) + + Profiler.unique_graphs += 1 + return _wrapped diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/replay_record.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/replay_record.py new file mode 100644 index 0000000000000000000000000000000000000000..7bb414b5aab2f47ab2b0fe2b63ed7e54375494f4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/replay_record.py @@ -0,0 +1,143 @@ +from __future__ import annotations + + +""" +Python execution state recording and replay functionality. + +This module provides mechanisms for capturing and replaying Python execution state: + +- ModuleRecord: Tracks module access patterns and attribute usage +- DummyModule: Lightweight module substitute for replay +- ExecutionRecord: Manages execution context including globals, locals and builtins +- ExecutionRecorder: Records variable states and module access during execution + +The module enables serialization and reproduction of Python execution environments, +particularly useful for debugging and testing frameworks that need to capture +and recreate specific program states. +""" + +import dataclasses +from dataclasses import field +from types import CellType, CodeType, ModuleType +from typing import Any, cast, IO, TYPE_CHECKING +from typing_extensions import Self + +from torch.utils._import_utils import import_dill + + +if TYPE_CHECKING: + from io import BufferedReader, BufferedWriter + + from .output_graph import CodeOptions + + +dill = import_dill() + + +@dataclasses.dataclass +class ModuleRecord: + module: ModuleType + accessed_attrs: dict[str, Any] = field(default_factory=dict) + + +@dataclasses.dataclass +class DummyModule: + name: str + is_torch: bool = False + value: object = None + + @property + def __name__(self) -> str: + return self.name + + +@dataclasses.dataclass +class ExecutionRecord: + code: CodeType + closure: tuple[CellType] + globals: dict[str, Any] = field(default_factory=dict) + locals: dict[str, Any] = field(default_factory=dict) + builtins: dict[str, Any] = field(default_factory=dict) + # The replay record starts empty and gets populated by the translator before use. + code_options: CodeOptions = field(default_factory=lambda: cast("CodeOptions", {})) + + def dump(self, f: IO[str] | BufferedWriter) -> None: + if dill is None: + raise AssertionError("replay_record requires `pip install dill`") + dill.dump(self, f) + + @classmethod + def load(cls, f: IO[bytes] | BufferedReader) -> Self: + if dill is None: + raise AssertionError("replay_record requires `pip install dill`") + return dill.load(f) + + +@dataclasses.dataclass +class ExecutionRecorder: + LOCAL_MOD_PREFIX = "___local_mod_" + + code: CodeType + closure: tuple[CellType] + globals: dict[str, Any] = field(default_factory=dict) + locals: dict[str, Any] = field(default_factory=dict) + builtins: dict[str, Any] = field(default_factory=dict) + # The recorder starts empty and gets populated by the translator before use. + code_options: CodeOptions = field(default_factory=lambda: cast("CodeOptions", {})) + name_to_modrec: dict[str, ModuleRecord] = field(default_factory=dict) + + def add_local_var(self, name: str, var: Any) -> None: + if isinstance(var, ModuleType): + self.locals[name] = self._add_mod(var) + else: + self.locals[name] = var + + def add_global_var(self, name: str, var: Any) -> None: + if isinstance(var, ModuleType): + self.globals[name] = self._add_mod(var) + else: + self.globals[name] = var + + def add_local_mod(self, name: str, mod: ModuleType) -> None: + if not isinstance(mod, ModuleType): + raise AssertionError(f"Expected ModuleType, got {type(mod)}") + self.add_global_var(name, mod) + + def record_module_access(self, mod: ModuleType, name: str, val: Any) -> None: + if isinstance(val, ModuleType): + self.name_to_modrec[mod.__name__].accessed_attrs[name] = self._add_mod(val) + return + + if mod.__name__ in self.name_to_modrec: + self.name_to_modrec[mod.__name__].accessed_attrs[name] = val + + def get_record(self) -> ExecutionRecord: + return ExecutionRecord( + self.code, + self.closure, + ExecutionRecorder._resolve_modules(self.globals), + ExecutionRecorder._resolve_modules(self.locals), + self.builtins.copy(), + self.code_options.copy(), + ) + + def _add_mod(self, mod: ModuleType) -> ModuleRecord: + if mod.__name__ not in self.name_to_modrec: + self.name_to_modrec[mod.__name__] = ModuleRecord(mod) + + return self.name_to_modrec[mod.__name__] + + @classmethod + def _resolve_modules(cls, vars: dict[str, Any]) -> dict[str, Any]: + def resolve_module(var: Any) -> Any: + if not isinstance(var, ModuleRecord): + return var + + dummy_mod = DummyModule(var.module.__name__) + for attr_name, attr_value in var.accessed_attrs.items(): + attr_value = resolve_module(attr_value) + dummy_mod.__setattr__(attr_name, attr_value) + + return dummy_mod + + return {k: resolve_module(v) for k, v in vars.items()} diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__init__.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5f46acd36db4fbef5c6080443fd67e67bfcc9a38 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__init__.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from typing import Protocol + + +class ReproOptions(Protocol): + """ + Read-only view of the argparse Namespace threaded through the repro_* + entrypoints in after_aot.py and after_dynamo.py. + + argparse populates the Namespace dynamically, so a Protocol (rather than a + concrete class) is the pragmatic fit: it documents the attributes those + functions actually read without asserting how the Namespace is built. Not + every attribute is populated for every subcommand -- e.g. after_dynamo + never sets tracing_mode -- but each repro_* function only reads the subset + that its own subparser defines. + """ + + # Shared across the after_aot and after_dynamo subparsers. + command: str + accuracy: str + save_dir: str | None + + # after_aot-only attributes. + tracing_mode: str | None + check_str: str | None + isolate: bool + offload_to_disk: bool + skip_saving_eager_intermediates: bool + skip_sanity: bool + max_granularity: int | None + stable_hash: bool + skip_saving_inductor_intermediates: bool + skip_saving_float64_intermediates: bool + skip_check_deterministic: bool + + # after_dynamo-only attributes. + backend: str | None + autocast: bool + only_fwd: bool diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bb0b5ed7ea405462d32dee24d558c0d5853c5b6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/after_aot.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/after_aot.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..825d7554d86d1b7f83587817058978daf086f209 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/after_aot.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/after_dynamo.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/after_dynamo.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ad87c81d3086a54ccfe5276ee61c234ebe4526f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/after_dynamo.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/aoti.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/aoti.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbedebe5c73ecffb63d57a70fac0ed3b8c0e2853 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/__pycache__/aoti.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/after_aot.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/after_aot.py new file mode 100644 index 0000000000000000000000000000000000000000..263a469da5dbb615afd91ce28e626a36bc8753a9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/after_aot.py @@ -0,0 +1,1755 @@ +""" +Utilities for reproducing and debugging issues in PyTorch's Dynamo AOT compilation. + +This module provides tools and infrastructure for: +1. Generating minimal reproducible test cases ("repros") from failing compilations +2. Analyzing accuracy issues between eager and compiled execution +3. Minifying large models/inputs to isolate problematic patterns +4. Debugging compiler errors and accuracy divergences + +The main components include: +- Repro generation: Creates standalone Python files that reproduce compiler issues +- Minification: Reduces large graphs to minimal failing examples +- Accuracy analysis: Compares compiled vs eager execution, with fp64 reference +- Debug tools: Dumps graph state, tracks intermediates, analyzes divergences + +This is primarily used by PyTorch developers and researchers to debug issues in +the Dynamo AOT compilation pipeline, particularly for the Inductor backend. +""" + +from __future__ import annotations + +import argparse +import ast +import copy +import functools +import io +import logging +import os +import shutil +import subprocess +import sys +import textwrap +import types +import typing +import uuid +from importlib import import_module +from tempfile import TemporaryFile +from typing import Any, IO, TYPE_CHECKING, TypedDict +from typing_extensions import Unpack + +import sympy + + +try: + import triton.language as tl + from triton.runtime.autotuner import Autotuner, Heuristics + from triton.runtime.jit import JITFunction + + TritonConstexpr = tl.constexpr +except ImportError: + + class Autotuner: # type: ignore[no-redef] + pass + + class JITFunction: # type: ignore[no-redef] + pass + + class Heuristics: # type: ignore[no-redef] + pass + + class TritonConstexpr: # type: ignore[no-redef] + pass + + +import torch +import torch.fx as fx +import torch.nn as nn +from torch._dynamo.debug_utils import ( + _cuda_system_info_comment, + AccuracyError, + backend_accuracy_fails, + BuckTargetWriter, + cast_to_fp64, + extra_deps, + extra_imports, + generate_config_string, + generate_env_vars_string, + helper_for_dump_minify, + InputReader, + InputWriter, + MAX_CONSTANT_NUMEL_INLINE, + minifier_dir, + NNModuleToString, + NopInputReader, + same_two_models, +) +from torch._dynamo.utils import clone_inputs, counters, same +from torch._environment import is_fbcode +from torch._higher_order_ops.triton_kernel_wrap import kernel_side_table +from torch._inductor.cpp_builder import normalize_path_separator +from torch._library.fake_class_registry import FakeScriptObject +from torch._ops import OpOverload +from torch.fx.experimental.proxy_tensor import make_fx +from torch.fx.experimental.symbolic_shapes import ( + fx_placeholder_targets, + has_free_symbols, +) +from torch.hub import tqdm + +from .. import config + + +def _find_repeat_interleave_constraints( + gm: torch.fx.GraphModule, +) -> list[tuple[str, str]]: + """ + Find repeat_interleave operations with output_size constraints. + + Returns list of (repeats_placeholder_name, output_size_placeholder_name) pairs. + These represent constraints where sum(repeats) must equal output_size. + """ + constraints = [] + for node in gm.graph.nodes: + if ( + node.op != "call_function" + or "repeat_interleave" not in str(node.target) + or not node.args + ): + continue + + output_size_node = node.kwargs.get("output_size") + repeats_node = node.args[0] + + # Both must be FX nodes (not constants) and direct placeholders + if ( + isinstance(repeats_node, torch.fx.Node) + and isinstance(output_size_node, torch.fx.Node) + and repeats_node.op == "placeholder" + and output_size_node.op == "placeholder" + ): + constraints.append((str(repeats_node.target), str(output_size_node.target))) + + return constraints + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + from torch._inductor.compile_fx import _CompileFxCallable, _CompileFxKwargs + from torch._inductor.output_code import OutputCode + from torch._inductor.utils import InputType + + from . import ReproOptions + + +log = logging.getLogger(__name__) + + +inductor_config = import_module("torch._inductor.config") + + +class GroupInfo(TypedDict): + size: int + rank: int + + +def _extract_distributed_info( + gm: torch.fx.GraphModule, +) -> dict[str, GroupInfo]: + """ + Extract process group information from distributed ops in the graph. + + Returns a dict mapping group names to dicts with 'size' and 'rank' keys. + Example: {'tp': {'size': 4, 'rank': 0}, 'dp': {'size': 2, 'rank': 0}} + """ + from torch.distributed import GroupName + from torch.fx.operator_schemas import normalize_function + + group_info: dict[str, GroupInfo] = {} + + for node in gm.graph.nodes: + if node.op != "call_function": + continue + if not isinstance(node.target, OpOverload): + continue + if node.target.namespace not in {"_c10d_functional", "c10d_functional"}: + continue + + opt_args_kwargs = normalize_function( + node.target, + args=node.args, + kwargs=node.kwargs, + normalize_to_only_use_kwargs=True, + ) + if opt_args_kwargs is None: + continue + _, kwargs = opt_args_kwargs + + group_name_ = kwargs.get("group_name") + if not isinstance(group_name_, str): + continue + group_name = typing.cast(GroupName, group_name_) + + if group_name in group_info: + continue + + from torch.distributed.distributed_c10d import ( + _get_group_size_by_name, + _resolve_process_group, + ) + + group_size = _get_group_size_by_name(group_name) + pg = _resolve_process_group(group_name) + rank = pg.rank() + group_info[group_name] = {"size": group_size, "rank": rank} + + return group_info + + +def setup_fake_process_groups( + group_info: dict[str, GroupInfo], +) -> None: + """ + Set up fake process groups for repro execution. + + Args: + group_info: dict mapping group_name -> {'size': group_size, 'rank': rank} + """ + import torch.distributed as dist + from torch.testing._internal.distributed.fake_pg import FakeStore + + if not group_info: + return + + world_size = max(info["size"] for info in group_info.values()) + + global_rank = 0 + for info in group_info.values(): + if info["size"] == world_size: + global_rank = info["rank"] + break + + store = FakeStore() + dist.init_process_group( + backend="fake", + rank=global_rank, + world_size=world_size, + store=store, + ) + + default_pg = dist.distributed_c10d._get_default_group() + torch._C._distributed_c10d._unregister_all_process_groups() + + for group_name, info in group_info.items(): + group_size = info["size"] + if group_size == world_size: + # pyrefly: ignore[bad-argument-type] + torch._C._distributed_c10d._register_process_group(group_name, default_pg) + else: + ranks = list(range(group_size)) + new_pg = dist.new_group(ranks) + # pyrefly: ignore[bad-argument-type] + torch._C._distributed_c10d._register_process_group(group_name, new_pg) + + +def generate_standalone_repro( + gm: torch.fx.GraphModule, + args: Sequence[Any], + *, + save_path: str | None = None, +) -> str: + """ + Generate a self-contained repro script from an FX graph. + """ + buf = io.StringIO() + save_graph_repro(buf, gm, args, "inductor", save_dir=None) + repro = buf.getvalue() + + if save_path is not None: + with open(save_path, "w") as f: + f.write(repro) + log.info("Saved standalone repro to %s", save_path) + + return repro + + +use_buck = is_fbcode() + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# MAIN ENTRY POINT +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def wrap_compiler_debug( + unconfigured_compiler_fn: _CompileFxCallable, + compiler_name: str, +) -> _CompileFxCallable: + """ + Minifier for Fx Graph modules after Aot Autograd has finished. We wrap both + forward and backward call separately with the backend compiler_fn - like + inductor or nvfuser. Intercepting after Aot Autograd presents neat + abstraction, where all the params are lifted as graph inputs, making it easy + to save the graph as a string. + """ + + @functools.wraps(unconfigured_compiler_fn) + def debug_wrapper( + gm: torch.fx.GraphModule, + example_inputs: Sequence[InputType], + compile_region_name: str | None = None, + **kwargs: Unpack[_CompileFxKwargs], + ) -> OutputCode: + from torch._subclasses import FakeTensorMode + + compiler_fn = functools.partial( + unconfigured_compiler_fn, + compile_region_name=compile_region_name, + **kwargs, + ) + + from torch._functorch.aot_autograd import get_aot_graph_name + + graph_name = get_aot_graph_name() + + # TODO: why do we need to deepcopy the original graph? + orig_graph = copy.deepcopy(gm.graph) + if config.repro_after not in ("dynamo", "aot", None): + raise AssertionError( + f"repro_after must be 'dynamo', 'aot', or None, got {config.repro_after!r}" + ) + + try: + # Call the compiler_fn - which is either aot_autograd or inductor + # with fake inputs + inner_compiled_fn = compiler_fn(gm, example_inputs) + except Exception: + # TODO: Failures here are troublesome because no real inputs, + # need a different serialization strategy + if config.repro_after == "aot": + if config.repro_level == 1: + dump_compiler_graph_state( + fx.GraphModule(gm, orig_graph), + example_inputs, + compiler_name, + ) + elif config.repro_level == 2: + dump_to_minify( + fx.GraphModule(gm, orig_graph), + example_inputs, + compiler_name, + ) + log.error("CompilerError") + raise + + # We may run regular PyTorch compute that may trigger Dynamo, do NOT + # recursively attempt to accuracy minify in that case! + def deferred_for_real_inputs( + real_inputs: Sequence[InputType], **_kwargs: object + ) -> Any: + # This is a bit obscure: if we recursively try to accuracy minify + # the SAME function, this would trigger. But most of the time + # we should never hit this branch + if _kwargs: + raise AssertionError(f"Unexpected kwargs: {_kwargs}") + if config.repro_after != "aot": + if isinstance(inner_compiled_fn, str): + raise AssertionError("inner_compiled_fn should not be a string") + return inner_compiled_fn(real_inputs) + with config.patch(repro_after=None): + return inner_debug_fn(real_inputs) + + def inner_debug_fn(real_inputs: Sequence[InputType]) -> Any: + """ + Aot Autograd fw_compiler and bw_compiler can have fake tensors. So, + example_inputs can be fake tensors. We can call compiler_fn (which is + inductor or nvfuser) with fake tensors but the actually compiled_fn + should be called with real tensors. Therefore, the actual invocation + is deferred. + """ + # Copy the tensor attrs like shape, stride etc by converting to Fake Tensor + # because inductor clears the tensor list in its codegen. And example_inputs + # are available only for the first invocation. + fake_mode = FakeTensorMode() + copy_tensor_attrs = [ + fake_mode.from_tensor(x) if isinstance(x, torch.Tensor) else x + for x in real_inputs + ] + if config.repro_level == 3: + # Always dump the original module in case we have segfaults + dump_to_minify( + fx.GraphModule(gm, orig_graph), real_inputs, compiler_name + ) + + if config.repro_level == 4: + if compiler_name != "inductor": + raise NotImplementedError( + "Accuracy minification is supported for inductor only" + ) + failed = not same_two_models( + gm, + inner_compiled_fn, # type: ignore[arg-type] + real_inputs, + only_fwd=True, + ignore_non_fp=config.repro_ignore_non_fp, + ) + + if failed: + log.warning( + "Accuracy failed for the AOT Autograd graph %s", graph_name + ) + dump_compiler_graph_state( + fx.GraphModule(gm, orig_graph), + real_inputs, + f"{compiler_name}_accuracy", + ) + dump_to_minify( + fx.GraphModule(gm, orig_graph), + real_inputs, + f"{compiler_name}_accuracy", + ) + raise AccuracyError("Bad accuracy detected") + else: + # Call the compiled function with real inputs + return inner_compiled_fn(real_inputs) # type: ignore[operator] + else: + try: + # Call the compiled function with real inputs + out = inner_compiled_fn(real_inputs) # type: ignore[operator] + # sync cuda kernels to ensure IMA detection + if ( + any( + isinstance(arg, torch.Tensor) and arg.device.type != "cpu" + for arg in example_inputs + ) + and torch.accelerator.is_available() + ): + torch.accelerator.synchronize() + return out + except Exception: + if config.repro_level == 1: + dump_compiler_graph_state( + fx.GraphModule(gm, orig_graph), + copy_tensor_attrs, + compiler_name, + ) + elif config.repro_level == 2: + dump_to_minify( + fx.GraphModule(gm, orig_graph), + copy_tensor_attrs, + compiler_name, + ) + raise + + if config.repro_after == "aot": + compiled_fn = deferred_for_real_inputs + compiled_fn._boxed_call = True # type: ignore[attr-defined] + return compiled_fn # type: ignore[return-value] + else: + return inner_compiled_fn + + return debug_wrapper + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# DUMP REPROS +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def maybe_fbcode_instructions() -> str: + if is_fbcode(): + extra_deps_formatted = "\n".join([f' "{dep}",' for dep in extra_deps]) + if len(extra_deps_formatted) > 0: + extra_deps_formatted = "\n" + extra_deps_formatted + return f"""\ +\"\"\" +To run this script in fbcode: +- Create a directory (//scripts/{{your_unixname}}/repro) +- Put this file in scripts/{{your_unixname}}/repro/fx_graph_runnable.py +- Add a TARGETS file that looks like the following +- `buck2 run //scripts/{{your_unixname}}/repro:repro` + +NOTE: you may need additional deps to actually be able to run the script. +``` +# Contents of TARGETS file +load("@fbcode_macros//build_defs:python_binary.bzl", "python_binary") + +python_binary( + name = "repro", + main_src = "fx_graph_runnable.py", + deps = [ + "//caffe2:torch",{extra_deps_formatted} + ], +) +``` +\"\"\" +""" + else: + return "" + + +def generate_custom_triton_kernel(kernel: Any) -> str: + res = "" + if isinstance(kernel, Autotuner): + # pyrefly: ignore [missing-attribute] + if isinstance(kernel.fn, Heuristics): + res += "ERROR: Repro will not work as intended, " + res += "triton.runtime.autotuner.Heuristics is not currently supported\n" + return res + + config_strs = [] + # pyrefly: ignore [missing-attribute] + for kernel_config in kernel.configs: + config_strs.append(f"""triton.Config( + {str(kernel_config.kwargs)}, + num_warps={kernel_config.num_warps}, + num_stages={kernel_config.num_stages}, + )""") + + config_str = ",".join(config_strs) + res += textwrap.dedent(f""" + @triton.autotune( + configs=[ + {config_str} + ], + key=[] + ) + """).strip() + + # pyrefly: ignore [missing-attribute] + src_code = kernel.src if isinstance(kernel, JITFunction) else kernel.fn.src + res += "\n@triton.jit\n" + res += src_code + res += "\n" + + return res + + +def generate_compiler_repro_string( + gm: torch.fx.GraphModule, + args: Sequence[Any], + *, + stable_output: bool = False, + save_dir: str | None = None, + stable_hash: bool = False, + has_distributed_ops: bool = False, +) -> str: + if save_dir is not None: + save_dir = normalize_path_separator(save_dir) + # Add distributed imports if needed + distributed_imports = "" + if has_distributed_ops: + distributed_imports = textwrap.dedent( + """ +import torch.distributed as dist +from torch.testing._internal.distributed.fake_pg import FakeStore + """ + ).strip() + + triton_imports = "" + + if len(kernel_side_table.id_to_kernel) > 0: + triton_imports = textwrap.dedent( + """ +import triton +import triton.language as tl + """ + ).strip() + + model_str = textwrap.dedent( + f""" +{generate_env_vars_string(stable_output=stable_output)} +import torch +from torch import tensor, device +import torch.fx as fx +from torch._dynamo.testing import rand_strided +import math +from math import inf +import torch._inductor.inductor_prims +{distributed_imports} +{triton_imports} + +{generate_config_string(stable_output=stable_output)} + +isolate_fails_code_str = None + +{extra_imports} + +{maybe_fbcode_instructions()} + """ + ) + model_str += textwrap.dedent( + """ +if "__compile_source__" in globals(): + import inspect as __after_aot_inspect + import linecache as __after_aot_linecache + __after_aot_filename = __after_aot_inspect.currentframe().f_code.co_filename + __after_aot_linecache.cache[__after_aot_filename] = ( + len(__compile_source__), + None, + __compile_source__.splitlines(True), + __after_aot_filename, + ) +""" + ) + if not stable_output: + model_str += f"# torch version: {torch.version.__version__}\n" + if hasattr(torch.version, "cuda"): + model_str += f"# torch cuda version: {torch.version.cuda}\n" + if hasattr(torch.version, "git_version"): + model_str += f"# torch git version: {torch.version.git_version}\n\n\n" + model_str += _cuda_system_info_comment() + + kernel_side_table_prefix = ( + "torch._higher_order_ops.triton_kernel_wrap.kernel_side_table" + ) + + def get_fn_name(kernel: Any) -> str: + fn: Any = kernel if isinstance(kernel, JITFunction) else kernel.fn + return fn.__name__.split(".")[-1] + + def get_triton_import_line(name: str, val: Any) -> str | None: + # User-defined Triton kernels are serialized from their source, not from + # their original Python module. If the source references a global + # imported from Triton, such as `from triton.language.extra import + # libdevice`, the standalone repro must recreate that import. + if name in ("triton", "tl"): + return None + + if isinstance(val, types.ModuleType): + module_name = val.__name__ + if module_name == "triton" or module_name.startswith("triton."): + return f"import {module_name} as {name}" + return None + + module_name = getattr(val, "__module__", None) + object_name = getattr(val, "__name__", None) + if ( + isinstance(module_name, str) + and (module_name == "triton" or module_name.startswith("triton.")) + and isinstance(object_name, str) + ): + if name == object_name: + return f"from {module_name} import {object_name}" + return f"from {module_name} import {object_name} as {name}" + + return None + + def write_kernel_dependencies( + kernel: Any, + written_constexpr_vars: set[str], + written_nested_kernels: set[str], + written_triton_imports: set[str], + ) -> str: + """Write out global triton imports, tl.constexpr vars, and nested kernels.""" + result = "" + jit_fn = kernel if isinstance(kernel, JITFunction) else kernel.fn + if not getattr(jit_fn, "fn", None) or not getattr(jit_fn, "src", None): + return result + + fn_globals = getattr(jit_fn.fn, "__globals__", {}) + src = jit_fn.src + full_src = src if src.strip().startswith("def ") else "def " + src + + referenced_names: set[str] = set() + called_names: set[str] = set() + for node in ast.walk(ast.parse(full_src)): + if isinstance(node, ast.Name): + referenced_names.add(node.id) + if isinstance(node, ast.Call) and isinstance(node.func, ast.Name): + called_names.add(node.func.id) + + # Only recreate globals that are safe and useful for a standalone + # Triton repro: imports anchored in the Triton package and simple + # constants. Other user globals remain unsupported here. + for name in sorted(referenced_names): + if name in written_constexpr_vars: + continue + val = fn_globals.get(name) + + import_line = get_triton_import_line(name, val) + if import_line is not None: + if import_line not in written_triton_imports: + result += import_line + "\n" + written_triton_imports.add(import_line) + continue + + if isinstance(val, TritonConstexpr) and getattr(val, "value", None): + result += f"{name} = tl.constexpr({val.value})\n" + elif isinstance(val, (int, float, str, bool)): + result += f"{name} = {val!r}\n" + else: + continue + written_constexpr_vars.add(name) + + # Write out nested kernel dependencies + for name in called_names: + val = fn_globals.get(name) + if not isinstance(val, JITFunction) or val is jit_fn: + continue + nested_fn_name = get_fn_name(val) + if nested_fn_name in written_nested_kernels: + continue + # Mark as written before recursing to prevent cycles + written_nested_kernels.add(nested_fn_name) + result += write_kernel_dependencies( + val, + written_constexpr_vars, + written_nested_kernels, + written_triton_imports, + ) + result += generate_custom_triton_kernel(val) + + return result + + written_nested_kernels: set[str] = set() + written_constexpr_vars: set[str] = set() + written_triton_imports: set[str] = { + "import triton", + "import triton.language as tl", + } + + model_str += f"{kernel_side_table_prefix}.reset_table()\n" + + for idx in kernel_side_table.id_to_kernel: + kernel = kernel_side_table.get_kernel(idx) + + try: + model_str += write_kernel_dependencies( + kernel, + written_constexpr_vars, + written_nested_kernels, + written_triton_imports, + ) + fn_name = get_fn_name(kernel) + + unique_name = f"{fn_name}_{idx}" + + kernel_code = generate_custom_triton_kernel(kernel) + kernel_code = kernel_code.replace( + f"def {fn_name}(", f"def {unique_name}(", 1 + ) + model_str += kernel_code + model_str += f"{kernel_side_table_prefix}.add_kernel({unique_name})\n" + except AttributeError as e: + model_str += "ERROR: Repro will not work as intended, " + model_str += f"User defined triton kernel exception: {e}\n" + + if len(kernel_side_table.constant_args) > 0: + model_str += f"{kernel_side_table_prefix}.constant_args={kernel_side_table.constant_args}\n" + + # This string is also emitted as a best-effort trace artifact during + # normal compilation, so unsupported modules must not mask compile errors. + model_str += NNModuleToString.convert(gm, allow_unsafe_repr=True) + + writer = InputWriter(save_dir, stable_hash=stable_hash) + # pyrefly: ignore [implicit-any] + used_syms = {} + + # Extract from graph placeholders and their corresponding arguments + placeholder_targets = fx_placeholder_targets(gm) + for placeholder, arg in zip(placeholder_targets, args): + if isinstance(arg, (int, torch.SymInt)): + writer.symint(placeholder, arg) + elif isinstance(arg, torch.Tensor): + # TODO: improve these names with FQN + writer.tensor(placeholder, arg) + elif arg is None: + writer.const(placeholder) + elif isinstance(arg, FakeScriptObject): + writer.opaque(placeholder, arg.script_class_name) + elif isinstance(arg, torch._C.Generator): + writer.generator(placeholder, arg) + else: + writer.unsupported(placeholder, arg) + + # Extract symbolic variables from the same arguments + + if ( + isinstance(arg, torch.SymInt) + # By checking sympy.Symbol, we are excluding any symbolic expressions. + # TODO: we may need to solve expressions to extract symbol definitions. + and isinstance(arg.node.expr, sympy.Symbol) + and arg.node.hint is not None + ): + used_syms[str(arg.node)] = arg.node.hint + elif isinstance(arg, torch.Tensor): + # Extract symbolic variables from tensor shapes and strides + for dim in arg.shape: + if ( + isinstance(dim, torch.SymInt) + and isinstance(dim.node.expr, sympy.Symbol) + and dim.node.hint is not None + ): + used_syms[str(dim.node)] = dim.node.hint + for stride in arg.stride(): + if ( + isinstance(stride, torch.SymInt) + and isinstance(stride.node.expr, sympy.Symbol) + and stride.node.hint is not None + ): + used_syms[str(stride.node)] = stride.node.hint + # Extract symbols from storage nbytes (can be a symbolic expression) + storage = arg.untyped_storage() + nbytes = storage.nbytes() + if isinstance(nbytes, torch.SymInt): + expr = nbytes.node.expr + shape_env = nbytes.node.shape_env + for sym in expr.free_symbols: + sym_name = str(sym) + if sym_name not in used_syms and shape_env is not None: + hint = shape_env.backed_var_to_val.get(sym) + if hint is not None: + used_syms[sym_name] = int(hint) + # Add symbolic variable definitions to the top of the generated code + if used_syms: + hint_lines = "\n".join( + f"{name} = {hint}" for name, hint in sorted(used_syms.items()) + ) + model_str = f"{hint_lines}\n\n{model_str}" + + # Add fixup code for repeat_interleave constraints + # When inputs are regenerated randomly, sum(repeats) != output_size + # This fixup adjusts the repeats tensor to satisfy the constraint + constraints = _find_repeat_interleave_constraints(gm) + if constraints: + placeholder_to_idx = {name: idx for idx, name in enumerate(placeholder_targets)} + for repeats_name, output_size_name in constraints: + repeats_idx = placeholder_to_idx.get(repeats_name) + output_size_idx = placeholder_to_idx.get(output_size_name) + if repeats_idx is not None and output_size_idx is not None: + # Guard with hasattr since NopInputReader doesn't have args + writer._lines.append( + "# Fixup: ensure sum(repeats) == output_size for repeat_interleave" + ) + writer._lines.append("if hasattr(reader, 'args'):") + writer._lines.append(f" _repeats = reader.args[{repeats_idx}]") + writer._lines.append( + f" _output_size = reader.args[{output_size_idx}]" + ) + writer._lines.append( + " if isinstance(_repeats, torch.Tensor) and _repeats.dtype == torch.int64:" + ) + writer._lines.append(" _n = _repeats.numel()") + writer._lines.append(" _repeats.fill_(_output_size // _n)") + writer._lines.append(" _repeats[:_output_size % _n] += 1") + + load_args_lines = writer.lines() + load_args_code = "\n".join(load_args_lines) + model_str += load_args_code + "\n" + + model_str += "mod = Repro()\n" + return model_str + + +def save_graph_repro( + fd: IO[Any], + gm: torch.fx.GraphModule, + args: Sequence[Any], + compiler_name: str, + *, + stable_output: bool = False, + save_dir: str | None = None, + command: str = "run", + accuracy: str | bool | None = None, + tracing_mode: str | None = None, + check_str: str | None = None, + stable_hash: bool = False, +) -> None: + if any( + isinstance(arg, torch.fx.experimental._backward_state.BackwardState) + for arg in args + ): + fd.write( + "Repro is not generated due to existence of BackwardState in graph input" + ) + return + + if save_dir is not None: + save_dir = normalize_path_separator(save_dir) + + # Extract distributed info from the graph + distributed_info = _extract_distributed_info(gm) + has_distributed_ops = len(distributed_info) > 0 + + fd.write( + generate_compiler_repro_string( + gm, + args, + stable_output=stable_output, + save_dir=save_dir, + stable_hash=stable_hash, + has_distributed_ops=has_distributed_ops, + ) + ) + if accuracy is None: + accuracy = "_accuracy" in compiler_name + if tracing_mode is None: + tracing_mode = "real" + if any( + has_free_symbols(a) for a in args if not isinstance(a, FakeScriptObject) + ): + tracing_mode = "symbolic" + fd.write("if __name__ == '__main__':\n") + fd.write(" from torch._dynamo.repro.after_aot import run_repro\n") + + # Add distributed initialization before run_repro if needed + if has_distributed_ops: + fd.write( + " from torch._dynamo.repro.after_aot import setup_fake_process_groups\n" + ) + fd.write(f" setup_fake_process_groups({distributed_info!r})\n") + + fd.write( + f" with torch.no_grad():\n" + f" run_repro(mod, load_args, accuracy={accuracy!r}, command={command!r}, " + f"save_dir={save_dir!r}, tracing_mode={tracing_mode!r}, check_str={check_str!r})\n" + f" # To run it separately, do \n" + f" # mod, args = run_repro(mod, load_args, accuracy={accuracy!r}, command='get_args', " + f"save_dir={save_dir!r}, tracing_mode={tracing_mode!r}, check_str={check_str!r})\n" + f" # mod(*args)" + ) + + # Add distributed cleanup after run_repro + if has_distributed_ops: + fd.write("\n dist.destroy_process_group()\n") + + +def dump_compiler_graph_state( + gm: torch.fx.GraphModule, + args: Sequence[Any], + compiler_name: str, + *, + accuracy: str | bool | None = None, +) -> None: + subdir = os.path.join(minifier_dir(), "checkpoints") + if not os.path.exists(subdir): + os.makedirs(subdir, exist_ok=True) + file_name = os.path.join(subdir, f"{len(gm.graph.nodes)}.py") + log.warning( + "Writing checkpoint with %s nodes to %s", len(gm.graph.nodes), file_name + ) + with open(file_name, "w") as fd: + save_graph_repro( + fd, gm, args, compiler_name, save_dir=subdir, accuracy=accuracy + ) + curdir = os.getcwd() + repro_path = os.path.join(curdir, "repro.py") + try: + shutil.copyfile(file_name, repro_path) + log.warning("Copying repro file for convenience to %s", repro_path) + if use_buck: + BuckTargetWriter(file_name).write() + except OSError: + log.warning("No write permissions for %s", repro_path) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# DUMP MINIFIER +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def dump_to_minify( + gm: torch.fx.GraphModule, args: Sequence[Any], compiler_name: str +) -> None: + out = io.StringIO() + # TODO: factor this out + subdir = os.path.join(minifier_dir(), "checkpoints") + if not os.path.exists(subdir): + os.makedirs(subdir, exist_ok=True) + save_graph_repro(out, gm, args, compiler_name, save_dir=subdir, command="minify") + return helper_for_dump_minify(out.getvalue()) + + +def isolate_fails( + fx_g: torch.fx.GraphModule, + args: Sequence[Any], + compiler_name: str, + env: dict[str, Any] | None = None, + save_dir: str | None = None, + accuracy: bool | str | None = None, + tracing_mode: str | None = None, + check_str: str | None = None, +) -> bool: + if env is None: + env = {} + subdir = os.path.join(os.getcwd(), "isolate") + if not os.path.exists(subdir): + os.makedirs(subdir, exist_ok=True) + file_name = os.path.join(subdir, f"{str(uuid.uuid4())[:5]}.py") + with open(file_name, "w") as fd: + save_graph_repro( + fd, + fx_g, + args, + compiler_name, + save_dir=save_dir, + command="minifier-query", + accuracy=accuracy, + tracing_mode=tracing_mode, + check_str=check_str, + ) + # with open(file_name, "r") as fd: + # print(fd.read()) + new_env = os.environ.copy() + new_env = {**new_env, **env} + if use_buck: + cmd = BuckTargetWriter(file_name).write(print_msg=False) + else: + cmd = [sys.executable, file_name] + with ( + TemporaryFile() as stdout, + TemporaryFile() as stderr, + subprocess.Popen( + cmd, + cwd=subdir, + stdout=stdout, + stderr=stderr, + env=new_env, + ) as p, + ): + p.wait() + + stdout.seek(0) + stderr.seek(0) + print( + textwrap.indent(stdout.read().decode("utf-8"), prefix=">> "), + file=sys.stdout, + ) + print( + textwrap.indent(stderr.read().decode("utf-8"), prefix=">> "), + file=sys.stderr, + ) + # print(f"Isolated test failed - {file_name}") + return p.returncode != 0 + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# MINIFIER TOOLS +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def inductor_fails( + fx_g: torch.fx.GraphModule, args: Sequence[Any], check_str: str | None = None +) -> bool: + has_gpu = any( + isinstance(arg, torch.Tensor) and arg.device.type != "cpu" for arg in args + ) + + def sync() -> None: + if has_gpu and torch.accelerator.is_available(): + # Ensures that segfaults are surfaced + torch.accelerator.synchronize() + + from torch._inductor.compile_fx import compile_fx_inner + + try: + result = fx_g(*args) + if not isinstance(result, (tuple, list)): + raise AssertionError( + f"Expected result to be a tuple or list, got {type(result)}" + ) + if any(isinstance(x, (tuple, list)) for x in result): + raise AssertionError("Result should not contain nested tuples or lists") + except Exception: + return False + + sync() + + try: + compile_args = _get_compile_args(fx_g, args) + compile_mod = compile_fx_inner(fx_g, compile_args) + if isinstance(compile_mod, str): + raise AssertionError("compile_fx_inner should not return a string") + compile_mod(args) + sync() + except Exception as e: + if check_str is not None and check_str not in repr(e): + return False + print(repr(e)) + return True + return False + + +def inductor_accuracy_fails( + fx_g: torch.fx.GraphModule, + args: Sequence[Any], + check_str: str | None = None, + *, + require_fp64: bool = False, + ignore_non_fp: bool = False, +) -> bool: + from torch._inductor.compile_fx import compile_fx_inner + + def _compile_with_symbolic_args( + gm: torch.fx.GraphModule, inputs: list[Any] + ) -> torch.fx.GraphModule: + return compile_fx_inner(gm, _get_compile_args(gm, inputs)) # type: ignore[return-value] + + return backend_aot_accuracy_fails( + fx_g, + args, # type: ignore[arg-type] + _compile_with_symbolic_args, # type: ignore[arg-type] + require_fp64=require_fp64, + ignore_non_fp=ignore_non_fp, + ) + + +backend_aot_accuracy_fails = functools.partial(backend_accuracy_fails, only_fwd=True) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# REPRO MAIN +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def _build_symbolic_wrapper( + mod: nn.Module, + args: list[Any], + symint_exprs: dict[int, str], +) -> tuple[nn.Module, list[Any]] | None: + """Build a wrapper module that preserves symbolic relationships. + + Returns (wrapper_module, wrapper_args) where wrapper_args has carrier + tensors in place of free-symbol symints, and the wrapper's forward() + extracts SymInts from carrier.size(0), computes derived expressions, + and delegates to the inner module. + + Returns None if the expressions don't contain free/derived structure + (nothing to do). + """ + import re + + free_sym_re = re.compile(r"^s\d+$") + free_positions: dict[int, str] = {} + derived_positions: dict[int, str] = {} + + for idx, expr_str in symint_exprs.items(): + if free_sym_re.fullmatch(expr_str): + free_positions[idx] = expr_str + else: + derived_positions[idx] = expr_str + + if not free_positions: + return None + + # Order: carrier tensors first, then all non-symint args in original order + free_order = sorted(free_positions.keys()) + free_sym_names = [free_positions[i] for i in free_order] + + # Precompile derived expressions + derived_compiled = { + idx: compile(expr_str, f"", "eval") + for idx, expr_str in derived_positions.items() + } + + n_args = len(args) + + class _SymIntWrapper(nn.Module): + def __init__(self, inner: nn.Module) -> None: + super().__init__() + self.inner = inner + + def forward(self, *flat_args: Any) -> Any: + carriers = flat_args[: len(free_order)] + other = flat_args[len(free_order) :] + + syms: dict[str, Any] = {} + for i, sym_name in enumerate(free_sym_names): + syms[sym_name] = carriers[i].size(0) + + for idx, code in sorted(derived_compiled.items()): + derived_positions[idx] # keep reference + syms[f"_derived_{idx}"] = eval(code, {"__builtins__": {}}, syms) + + other_iter = iter(other) + rebuilt = [] + for i in range(n_args): + if i in free_positions: + rebuilt.append(syms[free_positions[i]]) + elif i in derived_positions: + rebuilt.append(syms[f"_derived_{i}"]) + else: + rebuilt.append(next(other_iter)) + + return self.inner(*rebuilt) + + # Build wrapper args: carriers + non-symint args + wrapper_args: list[Any] = [] + for i in free_order: + hint = int(args[i]) if not isinstance(args[i], int) else args[i] + device = "cpu" + for a in args: + if isinstance(a, torch.Tensor) and a.is_cuda: + device = a.device + break + wrapper_args.append(torch.empty(hint, dtype=torch.int8, device=device)) + + for i, arg in enumerate(args): + if i not in free_positions and i not in derived_positions: + wrapper_args.append(arg) + + return _SymIntWrapper(mod), wrapper_args + + +def repro_common( + options: ReproOptions, mod: nn.Module, load_args: Any +) -> tuple[torch.fx.GraphModule, list[Any]]: + # Invariant for graphs we generate with the repro script + if any(mod.named_parameters()): + raise AssertionError("Repro graph should not have any parameters") + for n, b in mod.named_buffers(): + if b.numel() > MAX_CONSTANT_NUMEL_INLINE: + log.warning( + "Constant %s was not serialized, generated random data instead. " + "If you think this is affecting you, please comment on " + "https://github.com/pytorch/pytorch/issues/100468", + n, + ) + + if not hasattr(load_args, "_version"): + log.warning( + "load_args does not have a _version attribute, please file a bug to PyTorch " + "and describe how you generate this repro script" + ) + else: + if load_args._version > 0: + log.warning( + "load_args is version %s, but this version of PyTorch only supports " + "version 0. We will try to run it anyway but there may be an incompatibility; " + "if so, try upgrading your version of PyTorch.", + load_args._version, + ) + + nop_reader = NopInputReader() + load_args(nop_reader) + + with tqdm(desc="Loading inputs", total=nop_reader.total) as pbar: + input_reader = InputReader(save_dir=options.save_dir, pbar=pbar) + load_args(input_reader) + args = input_reader.args + + # Turn mod into a GraphModule the slow way + # TODO: speed this up + # NOTE: symint_exprs (from reader.symint(val, expr=...)) are preserved + # in the repro script for documentation. A future improvement could use + # _build_symbolic_wrapper to reconstruct algebraic relationships between + # free and derived symints, but the arg reordering is fragile across + # different graph structures so we skip it for now. + mod = make_fx(mod, tracing_mode=options.tracing_mode)(*args) # type: ignore[arg-type] + + # pyrefly: ignore [bad-assignment] + torch._inductor.config.generate_intermediate_hooks = True + + return mod, args + + +def _get_compile_args(mod: torch.fx.GraphModule, args: Sequence[Any]) -> Sequence[Any]: + """Extract FakeTensor/SymInt args from the traced graph for compilation. + + When repro_common traces with tracing_mode='symbolic', the resulting + GraphModule's placeholder nodes carry FakeTensor/SymInt metadata. + compile_fx_inner needs these (not the concrete args) so that Inductor + generates proper symbolic-size bindings in the output code. + + For tracing_mode='real', concrete args are fine — we must NOT extract + FakeTensor metadata because different nodes may have FakeTensors from + different FakeTensorModes, causing a FakeTensorMode mismatch assertion + in Inductor. We detect symbolic tracing by checking for SymInt values, + which only exist when tracing_mode='symbolic'. + """ + placeholders = [n for n in mod.graph.nodes if n.op == "placeholder"] + if not placeholders: + return args + # Only extract metadata if the graph was traced with symbolic mode. + # SymInt values in placeholder metadata are the reliable indicator — + # FakeTensors appear in both real and symbolic modes, but only symbolic + # tracing creates SymInts for integer inputs. + has_symint = any(isinstance(n.meta.get("val"), torch.SymInt) for n in placeholders) + if not has_symint: + return args + return [n.meta.get("val", a) for n, a in zip(placeholders, args)] + + +ACCURACY_FAILS: dict[str, Callable[[torch.fx.GraphModule, Any], bool]] = { + "": inductor_fails, + # This might look inverted but it's not. strict_accuracy means "we will + # minify any time we see anything that diverges", whereas accuracy is more + # conservative, and will only minify if there is a meaningful fp64 + # divergence + "accuracy": functools.partial( + inductor_accuracy_fails, require_fp64=True, ignore_non_fp=True + ), + "strict_accuracy": inductor_accuracy_fails, +} + + +def repro_minifier_query(options: ReproOptions, mod: nn.Module, load_args: Any) -> None: + mod, args = repro_common(options, mod, load_args) + fail_fn = functools.partial( + ACCURACY_FAILS[options.accuracy], + check_str=options.check_str, # type: ignore[call-arg] + ) + if fail_fn(mod, args): + sys.exit(1) + else: + sys.exit(0) + + +def repro_minify(options: ReproOptions, mod: nn.Module, load_args: Any) -> None: + from functorch.compile import minifier + + mod, args = repro_common(options, mod, load_args) + compiler_name = "inductor_accuracy" if options.accuracy != "" else "inductor" + + favored_device = 1 if torch.cuda.device_count() >= 2 else 0 + env_variables = {"CUDA_VISIBLE_DEVICES": str(favored_device)} + + module_fails: Any + if options.isolate: + module_fails = functools.partial( + isolate_fails, + env=env_variables, + compiler_name=compiler_name, + save_dir=options.save_dir, + accuracy=options.accuracy, + tracing_mode=options.tracing_mode, + ) + else: + module_fails = ACCURACY_FAILS[options.accuracy] + + with config.patch(repro_after=None): + minifier( + mod, + args, + module_fails=functools.partial(module_fails, check_str=options.check_str), + dump_state=functools.partial( + dump_compiler_graph_state, compiler_name=compiler_name + ), + save_dir=options.save_dir, + offload_to_disk=options.offload_to_disk, + skip_offload=options.skip_saving_eager_intermediates, + skip_sanity=options.skip_sanity, + max_granularity=options.max_granularity, + ) + + +def repro_analyze(options: ReproOptions, mod: nn.Module, load_args: Any) -> None: + from torch._inductor.compile_fx import compile_fx_inner + from torch._inductor.hooks import intermediate_hook + + mod, args = repro_common(options, mod, load_args) + + # TODO: The logic for cloning inputs/models here is intentionally + # modeled off of run_fwd_maybe_bwd, but arguably it is better not to + # clone inputs (as you are doubling your effective GPU memory usage). + # It is certainly faster though! It probably makes sense to let the + # user specify the offload strategy. + + compile_mod = copy.deepcopy(mod) + compile_args = _get_compile_args(compile_mod, args) + with tqdm(desc="Compiling"): + compiled = compile_fx_inner(compile_mod, compile_args) + total = counters["inductor"]["intermediate_hooks"] + + known_names = set() + + def save_hook(name: str, val: Any) -> None: + known_names.add(name) + if not options.skip_saving_inductor_intermediates: + writer.write_tensor(os.path.join("inductor", name), val) + pbar.update(1) # type: ignore[has-type] + + # analyze stores and re-reads intermediates on disk, so a save_dir is + # required; --no-save-dir (save_dir=None) is invalid for this subcommand. + save_dir = options.save_dir + if save_dir is None: + raise RuntimeError("analyze requires a save_dir; do not pass --no-save-dir") + writer = torch.utils._content_store.ContentStoreWriter( + save_dir, stable_hash=options.stable_hash + ) + reader = torch.utils._content_store.ContentStoreReader(save_dir) + + new_args = clone_inputs(args) + with ( + intermediate_hook(save_hook), + tqdm(desc="Saving inductor intermediates", total=total) as pbar, + ): + if isinstance(compiled, str): + raise AssertionError("compile_fx_inner should not return a string") + compiled(new_args) # type: ignore[arg-type] + if new_args: + raise AssertionError("new_args should be empty after compiled() call") + + def compare_tuples(tuple1: tuple[Any], tuple2: tuple[Any]) -> str | None: + diff_indices = [i for i in range(len(tuple1)) if tuple1[i] != tuple2[i]] + diff_values = [(tuple1[i], tuple2[i]) for i in diff_indices] + + if not diff_values: + return None + else: + return " and ".join(f"{a} != {b}" for a, b in diff_values) + + def check_hook(name: str, val: Any) -> None: + meta = writer.compute_tensor_metadata(val) + meta2 = reader.read_tensor_metadata(os.path.join("inductor", name)) + reason = compare_tuples(meta, meta2) + if reason is not None: + pbar.write(f"NONDETERMINISTIC INDUCTOR at {name} ({reason})") + pbar.update(1) + + if not options.skip_check_deterministic: + new_args = clone_inputs(args) + with ( + intermediate_hook(check_hook), + tqdm(desc="Checking inductor determinism", total=total) as pbar, + ): + compiled(new_args) # type: ignore[arg-type] + if new_args: + raise AssertionError("new_args should be empty after compiled() call") + + class WriterInterp(fx.Interpreter): + def __init__(self, mod: torch.nn.Module, subdir: str) -> None: + super().__init__(mod) + self.subdir = subdir + + def run_node(self, n: torch.fx.Node) -> Any: + r = super().run_node(n) + name = n.name + if name in known_names: + pbar.update(1) + writer.write_tensor(os.path.join(self.subdir, name), r) + return r + + # NB: the module cast doesn't actually do anything, since there are no + # parameters/buffers on the module + if not options.skip_saving_float64_intermediates: + new_mod, new_args = cast_to_fp64(copy.deepcopy(mod), clone_inputs(args)) # type: ignore[arg-type] + with tqdm(desc="Saving float64 intermediates", total=total) as pbar: + WriterInterp(new_mod, "float64").boxed_run(new_args) + if new_args: + raise AssertionError("new_args should be empty after boxed_run() call") + + class ExactReaderInterp(fx.Interpreter): + def run_node(self, n: torch.fx.Node) -> Any: + r = super().run_node(n) + name = n.name + if name in known_names: + meta = writer.compute_tensor_metadata(r) + meta2 = reader.read_tensor_metadata(os.path.join("float64", name)) + reason = compare_tuples(meta, meta2) + if reason is not None: + pbar.write(f"NONDETERMINISTIC FLOAT64 at {name} ({reason})") + pbar.update(1) + return r + + # TODO: check eager determinism + + if not options.skip_check_deterministic: + new_mod, new_args = cast_to_fp64(copy.deepcopy(mod), clone_inputs(args)) # type: ignore[arg-type] + with tqdm(desc="Checking float64 determinism", total=total) as pbar: + ExactReaderInterp(new_mod).boxed_run(new_args) + if new_args: + raise AssertionError("new_args should be empty after boxed_run() call") + + # Now that we've saved everything, interp through the eager graph + # and do comparisons + class ReaderInterp(fx.Interpreter): + def run_node(self, n: torch.fx.Node) -> Any: + r = super().run_node(n) + name = n.name + if name in known_names: + inductor = reader.read_tensor(os.path.join("inductor", name)) + float64 = reader.read_tensor(os.path.join("float64", name)) + logged = False + + def log_error(msg: str, *args: Any) -> None: + nonlocal logged + logged = True + pbar.write(f"DIVERGED at {name}: {msg % args}") + + if not same( + r, + inductor, + float64, + tol=torch._dynamo.config.repro_tolerance, + equal_nan=True, + log_error=log_error, + ): + if not logged: + raise AssertionError("Divergence detected but not logged") + pbar.update(1) + return r + + with tqdm(desc="Checking divergence", total=total) as pbar: + ReaderInterp(mod).boxed_run(args) + if args: + raise AssertionError("args should be empty after boxed_run() call") + + +def repro_get_args( + options: ReproOptions, mod: nn.Module, load_args: Any +) -> tuple[torch.fx.GraphModule, list[Any]]: + mod, args = repro_common(options, mod, load_args) + return mod, args + + +def repro_run(options: ReproOptions, mod: nn.Module, load_args: Any) -> None: + from torch._inductor.compile_fx import compile_fx_inner + + mod, args = repro_common(options, mod, load_args) + + compile_mod = copy.deepcopy(mod) + compile_args = _get_compile_args(compile_mod, args) + compiled = compile_fx_inner(compile_mod, compile_args) + if isinstance(compiled, str): + raise AssertionError("compile_fx_inner should not return a string") + + if options.accuracy != "": + # We don't really respect --accuracy vs --strict-accuracy here, it + # seems counterintuitive + if not same_two_models( + mod, + compiled, # type: ignore[arg-type] + args, + only_fwd=True, + ignore_non_fp=config.repro_ignore_non_fp, + ): + raise AccuracyError("Bad accuracy detected") + else: + compiled(list(args)) + if ( + any( + isinstance(arg, torch.Tensor) and arg.device.type != "cpu" + for arg in args + ) + and torch.accelerator.is_available() + ): + torch.accelerator.synchronize() # ensure segfaults are surfaced + + +# TODO: lazily load the inputs or something, rather than cloning them +def run_repro( + mod: nn.Module, + load_args: Any, + *, + command: str = "run", + accuracy: bool | str = "", + save_dir: str | None = None, + tracing_mode: str | None = None, + patch_code: str | None = None, + check_str: str | None = None, + **kwargs: Any, +) -> Any: + for k in kwargs: + log.warning( + "Unrecognized kwarg %s; perhaps this repro was made on a newer version of PyTorch", + k, + ) + + if accuracy is True: + accuracy = "accuracy" + elif accuracy is False: + accuracy = "" + + if patch_code is not None: + log.warning( + "patch_code no longer works on this version of PyTorch, silently ignoring" + ) + + parser = argparse.ArgumentParser( + description=f"""\ +An after_aot repro script, typically triggering a bug in PyTorch Inductor. +When run with no arguments, this script defaults to running '{command}'. +Extra flags may be available; to find out more, try '{command} --help'. +There are also alternate subcommands available, see below. + +default settings on this script: + {accuracy=} + {tracing_mode=} + {save_dir=} + {check_str=} +""", + formatter_class=argparse.RawTextHelpFormatter, + ) + + def common_flags(parser: argparse.ArgumentParser) -> None: + accuracy_group = parser.add_mutually_exclusive_group() + accuracy_group.add_argument( + "--no-accuracy", + dest="accuracy", + action="store_const", + const="", + default=accuracy, + help="do not test accuracy, just run the module and see if it errors", + ) + accuracy_group.add_argument( + "--accuracy", + action="store_const", + const="accuracy", + default=accuracy, + help="""\ +test if the RMSE between the compiled module and the fp64 reference is greater +than eager and the fp64 reference. This is usually more reliable than the +standard allclose test, as we expect numeric differences from compiling, often +improving accuracy over eager. RMSE test allows for compiled module to +diverge greatly from eager, as long as this divergence moves it closer to the +'true' mathematical value of the network. Caveats: (1) double precision can +still suffer from rounding error, so it is not a perfect reference (see for +example 'Herbie: Automatically Improving Floating Point Accuracy') for +approaches that detect the necessary working precision and compute it in +arbitrary precision floating point; unfortunately, this is not practical for +tensor computation; (2) if there are not enough samples in the output being +compared, we may get unlucky and have an unlucky greater RMSE than eager; this +could be overcome by applying a more rigorous statistical test at some +p-value, which we leave for future work. +""", + ) + accuracy_group.add_argument( + "--strict-accuracy", + dest="accuracy", + action="store_const", + const="strict_accuracy", + default=accuracy, + help="""\ +by default, when doing accuracy minification we will reject reductions which +change the divergence from a floating point divergence to an integral/boolean +divergence. This is because some operations like ReLU involve temporarily +sharp boundaries that smooth out again afterwards; without requiring +divergence on floating point, the minifier will often fixate on divergent +boolean tensor even though this is not the true source of the divergence. +However, rejecting these reductions makes it more difficult for the minifier +to make progress. Using this option will let the minifier progress for ALL +divergences--you just might not end up with a useful repro in the end.""", + ) + + parser.add_argument( + "--save-dir", + type=str, + default=save_dir, + metavar="DIR", + help="directory where saved inputs live", + ) + parser.add_argument( + "--no-save-dir", + dest="save_dir", + action="store_const", + const=None, + help="don't use any directory for saved inputs", + ) + parser.add_argument( + "--tracing-mode", + type=str, + metavar="{real,fake,symbolic}", + default=tracing_mode, + help="how to trace the repro module into a GraphModule with metadata", + ) + + subparsers = parser.add_subparsers( + dest="command", metavar="{run,minify,analyze}", required=True + ) + + parser_run = subparsers.add_parser( + "run", + help="just run the repro", + ) + common_flags(parser_run) + + parser_minify = subparsers.add_parser( + "minify", help="run the minifier on the repro" + ) + common_flags(parser_minify) + parser_get_args = subparsers.add_parser("get_args", help="get the args") + common_flags(parser_get_args) + parser_minify_isolate = parser_minify.add_mutually_exclusive_group() + parser_minify_isolate.add_argument( + "--isolate", + action="store_true", + default=True, + help="run in separate processes to avoid interference (default)", + ) + parser_minify_isolate.add_argument( + "--no-isolate", + dest="isolate", + action="store_false", + help="speed up by running all compilation in same process", + ) + parser_minify.add_argument( + "--skip-saving-eager-intermediates", + action="store_true", + help="skip saving eager intermediates on --minify", + ) + # TODO: make this an option for --analyze too + parser_minify.add_argument( + "--offload-to-disk", + action="store_true", + help="during minification, offload delta debugging intermediates to disk. Use if you're OOMing", + ) + parser_minify.add_argument( + "--skip-sanity", + action="store_true", + help="skip sanity check at beginning of minification on original graph", + ) + parser_minify.add_argument( + "--max-granularity", + type=int, + default=None, + help="start at this granularity and work down; must be power of 2", + ) + parser_minify.add_argument( + "--check-str", + type=str, + default=check_str, + help="require minified program to fail with error containing this string", + ) + + parser_analyze = subparsers.add_parser( + "analyze", help="run the accuracy analyzer on the repro" + ) + common_flags(parser_analyze) + parser_analyze.add_argument( + "--skip-saving-inductor-intermediates", + action="store_true", + help="skip saving inductor intermediates on --analyze", + ) + parser_analyze.add_argument( + "--skip-saving-float64-intermediates", + action="store_true", + help="skip saving float64 intermediates", + ) + parser_analyze.add_argument( + "--skip-check-deterministic", + action="store_true", + help="skip checking that the network is deterministic", + ) + parser_analyze.add_argument( + "--stable-hash", + action="store_true", + help="use SHA-1 checksum instead of fast (but possibly unsound) hash", + ) + + # Run the repro in the context of minification, inverting exit code meaning + parser_minifier_query = subparsers.add_parser( + "minifier-query", + ) + common_flags(parser_minifier_query) + parser_minifier_query.add_argument( + "--check-str", + type=str, + default=check_str, + help="require minified program to fail with error containing this string", + ) + + args = None + if len(sys.argv) <= 1: + args = [command, *sys.argv[1:]] + + options = typing.cast("ReproOptions", parser.parse_args(args)) + COMMAND_FNS = { + "minify": repro_minify, + "analyze": repro_analyze, + "minifier-query": repro_minifier_query, + "run": repro_run, + "get_args": repro_get_args, + } + return COMMAND_FNS[options.command](options, mod, load_args) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/after_dynamo.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/after_dynamo.py new file mode 100644 index 0000000000000000000000000000000000000000..7c5b2d232a613880c4c1a0d97975fb484b693291 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/after_dynamo.py @@ -0,0 +1,672 @@ +""" +Utilities for reproducing and debugging issues in Dynamo after graph capture. + +This file provides tools and infrastructure for debugging problems that occur +after Dynamo has captured the graph but before/during backend compilation. +Key components include: + +- Minification tools to reduce large graphs to minimal failing examples +- Accuracy testing to validate compiled graph outputs match eager mode +- Repro generation to create standalone reproduction scripts +- Debug backends for capturing and analyzing failures +- Utilities for saving/loading graph states and inputs + +The tools here focus specifically on the post-graph-capture stage, making them +useful for debugging backend compilation issues, AOTAutograd problems, and +accuracy discrepancies between compiled and eager execution. +""" + +import argparse +import copy +import functools +import logging +import os +import shutil +import sys +import textwrap +from collections.abc import Callable, Sequence +from importlib import import_module +from typing import Any, cast + +import torch +import torch.fx as fx +from torch._dynamo.debug_utils import ( + AccuracyError, + backend_accuracy_fails, + BUCK_CMD_PREFIX, + BuckTargetWriter, + extra_imports, + generate_config_string, + generate_env_vars_string, + helper_for_dump_minify, + InputReader, + InputWriter, + minifier_dir, + NNModuleToString, + NopInputReader, + run_fwd_maybe_bwd, + same_two_models, +) +from torch.fx.experimental.symbolic_shapes import fx_placeholder_targets +from torch.hub import tqdm + +from .. import config +from ..backends.registry import CompilerFn, lookup_backend, register_debug_backend +from ..debug_utils import clone_inputs_retaining_gradness +from ..types import CompilerConfigProvider +from . import ReproOptions + + +log = logging.getLogger(__name__) + + +inductor_config = import_module("torch._inductor.config") +use_buck = inductor_config.is_fbcode() + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# MAIN ENTRY POINT +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def _accuracy_fails( + gm: torch.fx.GraphModule, + example_inputs: Sequence[Any], + compiler_fn: Callable[[torch.fx.GraphModule, list[Any]], torch.fx.GraphModule], +) -> bool: + return backend_accuracy_fails( + gm, + example_inputs, + compiler_fn, + only_fwd=config.repro_forward_only, + ignore_non_fp=config.repro_ignore_non_fp, + ) + + +class WrapBackendDebug: + def __init__( + self, unconfigured_compiler_fn: CompilerFn, compiler_name: str | None + ) -> None: + functools.wraps(unconfigured_compiler_fn)(self) + self._torchdynamo_orig_backend = unconfigured_compiler_fn + self._compiler_name = compiler_name + if hasattr(unconfigured_compiler_fn, "__name__"): + self.__name__ = unconfigured_compiler_fn.__name__ + if hasattr(unconfigured_compiler_fn, "compiler_name"): + self.__name__ = unconfigured_compiler_fn.compiler_name # type: ignore[attr-defined] + if hasattr(unconfigured_compiler_fn, "get_compiler_config"): + self.get_compiler_config = cast( + CompilerConfigProvider, unconfigured_compiler_fn + ).get_compiler_config + + def __call__( + self, gm: torch.fx.GraphModule, example_inputs: list[Any], **kwargs: Any + ) -> torch.fx.GraphModule: + compiler_fn = functools.partial(self._torchdynamo_orig_backend, **kwargs) + if config.repro_after not in ("dynamo", "aot", None): + raise AssertionError( + f"repro_after must be 'dynamo', 'aot', or None, got {config.repro_after!r}" + ) + + if config.repro_after == "dynamo": + + def add_paths(exc: Exception) -> None: + exc.minifier_path = os.path.join(minifier_dir(), "minifier_launcher.py") # type: ignore[attr-defined] + if use_buck: + exc.buck_command = " ".join( # type: ignore[attr-defined] + BUCK_CMD_PREFIX + + [BuckTargetWriter(exc.minifier_path).cmd_line_path] # type: ignore[attr-defined] + ) + + if config.repro_level == 3: + dump_to_minify_after_dynamo(gm, example_inputs, self._compiler_name) + + # Check for either accuracy (level 4) or other type of failures. + if config.repro_level == 4: + # Check Accuracy + compiled_gm = compiler_fn(copy.deepcopy(gm), example_inputs) + if _accuracy_fails(gm, example_inputs, compiler_fn): # type: ignore[arg-type] + log.warning( + "Accuracy failed for the TorchDynamo produced graph. Creating script to minify the error." + ) + dump_to_minify_after_dynamo( + fx.GraphModule(gm, copy.deepcopy(gm.graph)), + example_inputs, + self._compiler_name, + ) + exc = AccuracyError("Bad accuracy detected.") + add_paths(exc) + raise exc + else: + try: + compiled_gm = compiler_fn(copy.deepcopy(gm), example_inputs) + run_fwd_maybe_bwd(compiled_gm, example_inputs) # type: ignore[arg-type] + except Exception as exc: + log.warning( + "Compiled Fx GraphModule failed. Creating script to minify the error." + ) + if config.repro_level == 1: + dump_state_fn = functools.partial( + dump_backend_state, compiler_name=self._compiler_name + ) + dump_state_fn( + fx.GraphModule(gm, copy.deepcopy(gm.graph)), example_inputs + ) + elif config.repro_level == 2: + dump_to_minify_after_dynamo( + fx.GraphModule(gm, copy.deepcopy(gm.graph)), + example_inputs, + self._compiler_name, + ) + add_paths(exc) + raise + else: + compiled_gm = compiler_fn(gm, example_inputs) + + return compiled_gm # type: ignore[return-value] + + +def wrap_backend_debug( + unconfigured_compiler_fn: CompilerFn, compiler_name: str | None +) -> WrapBackendDebug: + """ + A minifier decorator that wraps the TorchDynamo produced Fx graph modules. + As opposed to wrap_compiler_debug, this wrapper intercepts at the + TorchDynamo produced Fx Graph Module. This makes it backend-agnostic to some + level, e.g., it is useful for minifying issues related to Aot Autograd + tracing. If an error is found, we minify and save the minified repro in + repro.tar.gz. + """ + return WrapBackendDebug(unconfigured_compiler_fn, compiler_name) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# REPRO DUMPERS +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def generate_dynamo_fx_repro_string( + gm: torch.fx.GraphModule, + args: Sequence[Any], + compiler_name: str | None, + check_accuracy: bool = False, + *, + stable_output: bool = False, + save_dir: str | None = None, + command: str = "run", +) -> str: + """ + Generate a repro string for backend-agnostic minified version. + """ + + model_str = NNModuleToString.convert(gm) + + # TODO: Figure out why torch.compile'd hash isn't work on this codepath + writer = InputWriter(save_dir, stable_hash=True) + for placeholder, arg in zip(fx_placeholder_targets(gm), args): + if isinstance(arg, (int, torch.SymInt)): + writer.symint(placeholder, arg) + elif isinstance(arg, torch.Tensor): + # TODO: improve these names with FQN + writer.tensor(placeholder, arg) + else: + raise TypeError(f"arg is neither SymInt/int nor torch.Tensor, {arg}") + load_args = "\n".join(writer.lines()) + + return textwrap.dedent( + f""" +{generate_env_vars_string(stable_output=stable_output)} +import math +from math import inf +import torch +from torch import tensor, device +import torch.fx as fx +import torch._dynamo +from torch._dynamo.testing import rand_strided +from torch._dynamo.debug_utils import run_fwd_maybe_bwd + +{generate_config_string(stable_output=stable_output)} + +{extra_imports} + +{model_str} +mod = Repro() + +{load_args} + +if __name__ == '__main__': + from torch._dynamo.repro.after_dynamo import run_repro + run_repro(mod, load_args, accuracy={check_accuracy!r}, command={command!r}, + save_dir={save_dir!r}, autocast={torch.is_autocast_enabled()!r}, backend={compiler_name!r}) +""" + ) + + +def dump_backend_repro_as_file( + gm: torch.fx.GraphModule, + args: Sequence[Any], + compiler_name: str | None, + check_accuracy: bool = False, +) -> None: + """ + Saves the repro to a repro.py file + """ + curdir = os.getcwd() + subdir = os.path.join(os.getcwd(), "checkpoints") + if not os.path.exists(subdir): + os.makedirs(subdir, exist_ok=True) + file_name = os.path.join(subdir, f"minified_{len(gm.graph.nodes)}_nodes.py") + log.warning( + "Writing checkpoint with %s nodes to %s", len(gm.graph.nodes), file_name + ) + + with open(file_name, "w") as fd: + fd.write( + generate_dynamo_fx_repro_string( + gm, args, compiler_name, check_accuracy, save_dir=subdir + ) + ) + latest_repro = os.path.join(curdir, "repro.py") + log.warning("Copying %s to %s for convenience", file_name, latest_repro) + + if use_buck: + BuckTargetWriter(latest_repro).write() + + shutil.copyfile(file_name, latest_repro) + + +def dump_backend_state( + gm: torch.fx.GraphModule, + args: Sequence[Any], + compiler_name: str | None, + check_accuracy: bool = False, +) -> None: + """ + Dumps the dynamo graph to repro the issue. + 1) It tries to convert Fx GraphModule to a string. If we can, it writes to a + repro.py file. + 2) If we can't convert Fx GraphModule to a string, we use to_folder to save + the module and save a tar file. + """ + if not NNModuleToString.can_convert_to_string(gm): + raise AssertionError("GraphModule cannot be converted to string") + return dump_backend_repro_as_file(gm, args, compiler_name, check_accuracy) + # return dump_backend_repro_as_tarfile(gm, args, compiler_name) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# MINIFIER DUMPER +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def dump_to_minify_after_dynamo( + gm: torch.fx.GraphModule, args: Sequence[Any], compiler_name: str | None +) -> None: + # TODO: factor this out + subdir = os.path.join(minifier_dir(), "checkpoints") + if not os.path.exists(subdir): + os.makedirs(subdir, exist_ok=True) + helper_for_dump_minify( + generate_dynamo_fx_repro_string( + gm, + args, + compiler_name, + check_accuracy=config.repro_level == 4, + save_dir=subdir, + command="minify", + ) + ) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# MINIFIER BACKENDS +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +@register_debug_backend # type: ignore[arg-type] +def dynamo_minifier_backend( + gm: fx.GraphModule, example_inputs: Sequence[Any], compiler_name: str | None +) -> fx.GraphModule: + from functorch.compile import minifier + + compiler_fn = lookup_backend(compiler_name) # type: ignore[arg-type] + + # TODO: It's inconsistent to pass SymInt inputs but REAL tensors. + # We should pass ints and look at the GraphModule placeholders + # to resolve them to SymInt (if necessary) + example_inputs = [ + i.node.hint if isinstance(i, torch.SymInt) else i for i in example_inputs + ] + + try: + compiled_gm = compiler_fn(gm, example_inputs) + run_fwd_maybe_bwd(compiled_gm, example_inputs) # type: ignore[arg-type] + raise ValueError("No issue was detected") + except Exception as exc: + orig_failure = str(exc) + log.warning( + "Compiled Fx GraphModule failed. Creating script to minify the error." + ) + dump_state_fn = functools.partial( + dump_backend_state, compiler_name=compiler_name + ) + dump_state_fn(fx.GraphModule(gm, copy.deepcopy(gm.graph)), example_inputs) + fails_fn = functools.partial( + backend_fails, + compiler_fn=compiler_fn, + orig_failure=orig_failure, + ) + minifier( + gm, + example_inputs, + module_fails=fails_fn, + dump_state=dump_state_fn, + ) + return gm + + +@register_debug_backend # type: ignore[arg-type] +def dynamo_accuracy_minifier_backend( + gm: fx.GraphModule, example_inputs: Sequence[Any], compiler_name: str | None +) -> fx.GraphModule: + from functorch.compile import minifier + + compiler_fn = lookup_backend(compiler_name) # type: ignore[arg-type] + + # Set the eval mode to remove randomness. + gm.eval() + + # Check Accuracy + if _accuracy_fails(gm, example_inputs, compiler_fn): # type: ignore[arg-type] + log.warning("Accuracy failed for the TorchDynamo produced graph") + dump_state_fn = functools.partial( + dump_backend_state, compiler_name=compiler_name, check_accuracy=True + ) + fails_fn = functools.partial( + _accuracy_fails, + compiler_fn=compiler_fn, # type: ignore[arg-type] + ) + dump_state_fn(fx.GraphModule(gm, copy.deepcopy(gm.graph)), example_inputs) + minifier( + gm, + example_inputs, + module_fails=fails_fn, + dump_state=dump_state_fn, + ) + else: + log.error("Input graph does not fail accuracy testing") + return gm + + +def backend_fails( + gm: fx.GraphModule, + example_inputs: Sequence[Any], + compiler_fn: CompilerFn, + orig_failure: Sequence[Any], +) -> bool: + """ + Minifier uses this function to identify if the minified graph module fails + with the same error. + + One caveat is that minifier can potentially go into a wrong direction when + the resulting graph module fails for a different reason. To avoid this, we + save the string for the original exception and check similarity between new + and old exception. They can be somewhat different in some cases, when the + exception string depends on the failing node information. So, we have a + loose similarity metric to guide the minifier path. + """ + from difflib import SequenceMatcher + + try: + # Run the original gm to check eager validity + run_fwd_maybe_bwd(gm, clone_inputs_retaining_gradness(example_inputs)) + compiled_gm = compiler_fn(gm, example_inputs) # type: ignore[arg-type] + run_fwd_maybe_bwd(compiled_gm, clone_inputs_retaining_gradness(example_inputs)) # type: ignore[arg-type] + except Exception as e: + new_failure = str(e) + if SequenceMatcher(None, orig_failure, new_failure).ratio() > 0.5: + return True + return False + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# REPRO MAIN +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def run_load_args( + options: ReproOptions, mod: torch.nn.Module, load_args: Any +) -> list[Any]: + if not hasattr(load_args, "_version"): + log.warning( + "load_args does not have a _version attribute, please file a bug to PyTorch " + "and describe how you generate this repro script" + ) + else: + if load_args._version > 0: + log.warning( + "load_args is version %s, but this version of PyTorch only supports " + "version 0. We will try to run it anyway but there may be an incompatibility; " + "if so, try upgrading your version of PyTorch.", + load_args._version, + ) + + nop_reader = NopInputReader() + load_args(nop_reader) + + with tqdm(desc="Loading inputs", total=nop_reader.total) as pbar: + input_reader = InputReader(save_dir=options.save_dir, pbar=pbar) + load_args(input_reader) + args = input_reader.args + + return args + + +def repro_minify(options: ReproOptions, mod: torch.nn.Module, load_args: Any) -> None: + # Setup debug minifier compiler + if not options.accuracy: + compiler_fn = lookup_backend("dynamo_minifier_backend") + else: + compiler_fn = lookup_backend("dynamo_accuracy_minifier_backend") + + if options.backend is None: + raise RuntimeError( + "Compiler name is None - this likely means that a custom compiler " + "was called by torchdynamo. Please remove this error, import your " + "custom compiler function, and replace the backend=None " + "line in run_repro to backend=" + ) + + dynamo_minifier_backend = functools.partial( + compiler_fn, + compiler_name=options.backend, # type: ignore[call-arg] + ) + opt_mod = torch._dynamo.optimize(dynamo_minifier_backend)(mod) + + args = run_load_args(options, mod, load_args) + device_type = next( + ( + a.device.type + for a in args + if isinstance(a, torch.Tensor) and a.device.type != "cpu" + ), + "cpu", + ) + with torch.amp.autocast(device_type, enabled=options.autocast): + opt_mod(*args) + + +def repro_run(options: ReproOptions, mod: torch.nn.Module, load_args: Any) -> None: + opt_mod = torch._dynamo.optimize(options.backend)(mod) + + if options.accuracy != "": + mod.eval() + opt_mod.eval() # type: ignore[union-attr] + + args = run_load_args(options, mod, load_args) + device_type = next( + ( + a.device.type + for a in args + if isinstance(a, torch.Tensor) and a.device.type != "cpu" + ), + "cpu", + ) + with torch.amp.autocast(device_type, enabled=options.autocast): + # TODO: disable clone + if not same_two_models(mod, mod, args): # type: ignore[arg-type] + raise AssertionError("Eager itself failed") + if not same_two_models( + mod, # type: ignore[arg-type] + opt_mod, # type: ignore[arg-type] + args, + only_fwd=config.repro_forward_only, + ignore_non_fp=config.repro_ignore_non_fp, + ): + raise AccuracyError("Dynamo failed") + else: + args = run_load_args(options, mod, load_args) + device_type = next( + ( + a.device.type + for a in args + if isinstance(a, torch.Tensor) and a.device.type != "cpu" + ), + "cpu", + ) + with torch.amp.autocast(device_type, enabled=options.autocast): + run_fwd_maybe_bwd(mod, args, only_fwd=options.only_fwd, disable_clone=True) # type: ignore[arg-type] + del args + + args = run_load_args(options, mod, load_args) + run_fwd_maybe_bwd( + opt_mod, # type: ignore[arg-type] + args, + only_fwd=options.only_fwd, + disable_clone=True, # type: ignore[arg-type] + ) + + +def run_repro( + mod: torch.nn.Module, + load_args: Any, + *, + command: str = "run", + accuracy: bool | str = "", + save_dir: str | None = None, + autocast: bool = False, + backend: str = "inductor", + **kwargs: Any, +) -> None: + for k in kwargs: + log.warning( + "Unrecognized kwarg %s; perhaps this repro was made on a newer version of PyTorch", + k, + ) + + if accuracy is True: + accuracy = "accuracy" + elif accuracy is False: + accuracy = "" + + parser = argparse.ArgumentParser( + description=f"""\ +An after_dynamo repro script, typically triggering a bug in Dynamo or +AOTAutograd. When run with no arguments, this script defaults to running +'{command}'. Extra flags may be available; to find out more, try '{command} +--help'. There are also alternate subcommands available, see below. + +default settings on this script: + {accuracy=} + {save_dir=} +""", + formatter_class=argparse.RawTextHelpFormatter, + ) + + def common_flags(parser: argparse.ArgumentParser) -> None: + accuracy_group = parser.add_mutually_exclusive_group() + accuracy_group.add_argument( + "--no-accuracy", + dest="accuracy", + action="store_const", + const="", + default=accuracy, + help="do not test accuracy, just run the module and see if it errors", + ) + accuracy_group.add_argument( + "--accuracy", + action="store_const", + const="accuracy", + default=accuracy, + help="test accuracy", + ) + parser.add_argument( + "--save-dir", + type=str, + default=save_dir, + metavar="DIR", + help="directory where saved inputs live", + ) + parser.add_argument( + "--no-save-dir", + dest="save_dir", + action="store_const", + const=None, + help="don't use any directory for saved inputs", + ) + parser.add_argument( + "--no-isolate", + dest="isolate", + action="store_false", + default=False, + help="no isolate (doesn't do anything for after_dynamo)", + ) + parser.add_argument( + "--autocast", + default=autocast, + action="store_true", + help="use torch.amp.autocast", + ) + parser.add_argument( + "--no-autocast", + dest="autocast", + action="store_false", + help="don't use torch.amp.autocast", + ) + parser.add_argument( + "--backend", + type=str, + default=backend, + metavar="BACKEND", + help="torch.compile backend to use", + ) + + subparsers = parser.add_subparsers( + dest="command", metavar="{run,minify}", required=True + ) + + parser_run = subparsers.add_parser( + "run", + help="just run the repro", + ) + common_flags(parser_run) + parser_run.add_argument( + "--only-fwd", + action="store_true", + help="don't run backwards compilation for testing", + ) + + parser_minify = subparsers.add_parser( + "minify", help="run the minifier on the repro" + ) + common_flags(parser_minify) + + args = None + if len(sys.argv) <= 1: + args = [command, *sys.argv[1:]] + + options = cast(ReproOptions, parser.parse_args(args)) + COMMAND_FNS = { + "minify": repro_minify, + "run": repro_run, + } + COMMAND_FNS[options.command](options, mod, load_args) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/aoti.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/aoti.py new file mode 100644 index 0000000000000000000000000000000000000000..1ab8b76e82585ffef7a79ccc19b32171aa3df132 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/repro/aoti.py @@ -0,0 +1,669 @@ +""" +Utilities for debugging and reproducing issues in Ahead of Time with Inductor (AOTI) compilation. + +This file provides tools and utilities for: +- Generating minimal reproducible test cases (minification) +- Handling exported programs and graph modules +- Creating debug repros for AOTI compilation issues +- Supporting both accuracy testing and error reproduction +- Managing configuration and environment for repro cases + +The main components include: +- Minification tools to reduce test cases while preserving errors +- Repro generation utilities for exported programs +- Error handling specific to AOTI compilation +- Command-line interface for running and managing repros +""" + +import argparse +import functools +import io +import logging +import os +import re +import shutil +import sys +import textwrap +from collections.abc import Sequence +from importlib import import_module +from typing import Any, IO + +import torch +from torch._dynamo.debug_utils import ( + _cuda_system_info_comment, + BuckTargetWriter, + extra_imports, + generate_config_string, + generate_env_vars_string, + helper_for_dump_minify, + InputReader, + minifier_dir, + NNModuleToString, + NopInputReader, +) +from torch.export import ExportedProgram +from torch.hub import tqdm + + +log = logging.getLogger(__name__) + + +inductor_config = import_module("torch._inductor.config") +use_buck = inductor_config.is_fbcode() + + +class AOTIMinifierError(Exception): + def __init__(self, original_exception: str | Exception) -> None: + additional_message = "This error is caused by a bug in the AOTI minifier, please report a bug to PyTorch" + full_message = f"{additional_message}: {str(original_exception)}" + super().__init__(full_message) + self.original_exception = original_exception + + +def dump_to_minify( + exported_program: ExportedProgram, + compiler_name: str, + command: str = "minify", + options: dict[str, Any] | None = None, +) -> None: + """ + If command is "minify": + Dump exported_program to `debug_dir/minifier/minifier_launcher.py`, with minify command. + If command is "run": + Dump exported_program to `cwd/repro.py`, with run command. + """ + if command not in ["minify", "run"]: + raise AssertionError(f"command must be 'minify' or 'run', got {command!r}") + + subdir = os.path.join(minifier_dir(), "checkpoints") + if not os.path.exists(subdir): + os.makedirs(subdir, exist_ok=True) + + if command == "minify": + out = io.StringIO() + save_graph_repro_ep( + out, + compiler_name, + exported_program=exported_program, + save_dir=subdir, + command="minify", + config_patches=options, + ) + return helper_for_dump_minify(out.getvalue()) + else: + curdir = os.getcwd() + file_name = os.path.join(curdir, "repro.py") + try: + with open(file_name, "w") as fd: + save_graph_repro_ep( + fd, + compiler_name, + exported_program=exported_program, + config_patches=options, + save_dir=subdir, + command="run", + module_in_comment=True, + ) + log.warning("Writing repro file to %s", file_name) + if use_buck: + BuckTargetWriter(file_name).write() + except OSError: + log.warning("No write permissions for %s", file_name) + + +def get_module_string(gm: torch.fx.GraphModule) -> str: + def _convert_to_comment(s_: str) -> str: + s = s_.split("\n") + if len(s) == 1: + return "# " + s_ + first = s.pop(0) + for i in range(len(s)): + line = s[i] + if line.strip() != "": + s[i] = "# " + line + else: + s[i] = "" + s = "\n".join(s) + s = first + "\n" + s + return s + + module_string = NNModuleToString.convert(gm, allow_unsafe_repr=True) + return _convert_to_comment(module_string) + + +def save_graph_repro_ep( + fd: IO[Any], + compiler_name: str, + *, + exported_program: ExportedProgram | None = None, + gm: torch.nn.Module | None = None, + args: tuple[Any] | None = None, + config_patches: dict[str, str] | None = None, + stable_output: bool = False, + save_dir: str | None = None, + command: str = "run", + accuracy: str | bool | None = None, + check_str: str | None = None, + module_in_comment: bool = False, + strict: bool = False, +) -> None: + # Save graph for reproducing the error. + # Either exported_program or gm will be saved, depending on which one is defined. + # Only one of exported_program and gm should be defined. + + if exported_program is None and gm is None: + raise AOTIMinifierError("One of exported_program and gm must be defined") + if exported_program is not None and gm is not None: + raise AOTIMinifierError("Only one of exported_program and gm can be defined") + if gm is not None and args is None: + raise AOTIMinifierError("If gm is defined, args should also be defined") + + if exported_program is None: + if gm is None: + raise AssertionError("gm must not be None when exported_program is None") + if args is None: + raise AssertionError("args must not be None when exported_program is None") + exported_program = torch.export.export(gm, args, strict=strict) + elif gm is None: + gm = exported_program.module(check_guards=False) + + # save a graph preview using gm + module_string = get_module_string(gm) # type: ignore[arg-type] + fd.write(module_string) + + # save a graph repro using exported_program + fd.write( + generate_compiler_repro_exported_program( + exported_program, + options=config_patches, + stable_output=stable_output, + save_dir=save_dir, + ) + ) + if accuracy is None: + accuracy = "_accuracy" in compiler_name + fd.write("if __name__ == '__main__':\n") + fd.write(" from torch._dynamo.repro.aoti import run_repro\n") + fd.write( + f" with torch.no_grad():\n" + f" run_repro(exported_program, config_patches=config_patches, accuracy={accuracy!r}, command={command!r}, " + f"save_dir={save_dir!r}, check_str={check_str!r})\n" + ) + + +def dump_compiler_graph_state( + gm: torch.fx.GraphModule, + args: Sequence[Any], + compiler_name: str, + *, + config_patches: dict[str, str] | None = None, + accuracy: str | bool | None = None, + strict: bool = False, +) -> None: + subdir = os.path.join(minifier_dir(), "checkpoints") + if not os.path.exists(subdir): + os.makedirs(subdir, exist_ok=True) + file_name = os.path.join(subdir, f"{len(gm.graph.nodes)}.py") + log.warning( + "Writing checkpoint with %s nodes to %s", len(gm.graph.nodes), file_name + ) + with open(file_name, "w") as fd: + save_graph_repro_ep( + fd, + compiler_name, + gm=gm, + args=tuple(args), + config_patches=config_patches, + save_dir=subdir, + accuracy=accuracy, + module_in_comment=True, + strict=strict, + ) + curdir = os.getcwd() + repro_path = os.path.join(curdir, "repro.py") + try: + shutil.copyfile(file_name, repro_path) + log.warning("Copying repro file for convenience to %s", repro_path) + if use_buck: + BuckTargetWriter(file_name).write() + except OSError: + log.warning("No write permissions for %s", repro_path) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# DUMP REPROS +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def generate_compiler_repro_exported_program( + exported_program: ExportedProgram, + *, + options: dict[str, str] | None = None, + stable_output: bool = False, + save_dir: str | None = None, +) -> str: + model_str = textwrap.dedent( + f""" +{generate_env_vars_string(stable_output=stable_output)} +import torch +import torch._inductor.inductor_prims + +{generate_config_string(stable_output=stable_output)} + +isolate_fails_code_str = None + +{extra_imports} + + """ + ) + if not stable_output: + model_str += f"# torch version: {torch.version.__version__}\n" + if hasattr(torch.version, "cuda"): + model_str += f"# torch cuda version: {torch.version.cuda}\n" + if hasattr(torch.version, "git_version"): + model_str += f"# torch git version: {torch.version.git_version}\n\n\n" + model_str += _cuda_system_info_comment() + if save_dir: + ep_path = os.path.join(save_dir, "exported_program.pt2") + else: + ep_path = "exported_program.pt2" + torch.export.save(exported_program, ep_path) + + model_str += f"exported_program = torch.export.load('{ep_path}')\n" + model_str += "# print(exported_program.graph)\n" + model_str += f"config_patches={options}\n" + return model_str + + +def repro_load_args(load_args: Any, save_dir: str | None) -> tuple[Any]: + if not hasattr(load_args, "_version"): + log.warning( + "load_args does not have a _version attribute, please file a bug to PyTorch " + "and describe how you generate this repro script" + ) + else: + if load_args._version > 0: + log.warning( + "load_args is version %s, but this version of PyTorch only supports " + "version 0. We will try to run it anyway but there may be an incompatibility; " + "if so, try upgrading your version of PyTorch.", + load_args._version, + ) + + nop_reader = NopInputReader() + load_args(nop_reader) + + with tqdm(desc="Loading inputs", total=nop_reader.total) as pbar: + input_reader = InputReader(save_dir=save_dir, pbar=pbar) + load_args(input_reader) + args = input_reader.args + + return tuple(args) + + +def repro_common( + options: Any, exported_program: ExportedProgram +) -> tuple[torch.fx.GraphModule, Any, Any]: + # pyrefly: ignore [bad-assignment] + torch._inductor.config.generate_intermediate_hooks = True + mod = exported_program.module(check_guards=False) + args, kwargs = exported_program.example_inputs + return mod, args, kwargs # type: ignore[return-value] + + +def repro_get_args( + options: Any, + exported_program: ExportedProgram, + config_patches: dict[str, Any] | None, +) -> tuple[torch.fx.GraphModule, Any, Any]: + mod, args, kwargs = repro_common(options, exported_program) + return mod, args, kwargs + + +def repro_run( + options: Any, + exported_program: ExportedProgram, + config_patches: dict[str, Any] | None, +) -> None: + from torch._inductor import _aoti_compile_and_package_inner + + gm, args, kwargs = repro_common(options, exported_program) + + from torch.cuda import synchronize + + _aoti_compile_and_package_inner( + gm, + args, + kwargs, + load_and_run=True, + check_accuracy=options.accuracy, + inductor_configs=config_patches, + ) + + need_sync = False + + for arg in args: + if isinstance(arg, torch.Tensor) and arg.is_cuda: + need_sync = True + break + + if need_sync: + synchronize() # ensure segfaults are surfaced + + +def export_for_aoti_minifier( + gm: torch.nn.Module, + tuple_inputs: tuple[Any], + strict: bool = False, + skip_export_error: bool = True, +) -> torch.nn.Module | None: + # Some graphs cannot be used for AOTI/export (illegal graphs), these should be + # considered as graphs that don't fail in the minifier, so the minifier keeps searching. + # In these cases, we return None. Otherwise, we return the exported graph module. + # This won't affect the minifier result because the minifier is only responsible for catching + # errors in AOTI, not export. + # + # Please add to this list of illegal graphs if you change the implementation here. + # - graph output is not allowed by export + # + # If skip_export_error=True, then the errors in export will not be raised, and the minifier + # will keep exploring and ignore this graph. + from torch._dynamo.exc import UserError, UserErrorType + + try: + ep = torch.export.export(gm, tuple_inputs, strict=strict) + gm = ep.module(check_guards=False) + return gm + except Exception as e: + if skip_export_error: + return None + if isinstance(e, UserError) and e.error_type == UserErrorType.INVALID_OUTPUT: + # graph output is not allowed by export when strict=True + return None + if isinstance(e, RuntimeError): + # graph output is not allowed by export when strict=False + pattern = r"Found .* in output, which is not a known type\." + if re.search(pattern, str(e)) is not None: + return None + raise AOTIMinifierError(e) from e + # we should never reach here + # pyrefly: ignore [unreachable] + return None + + +def repro_minify( + options: Any, + exported_program: ExportedProgram, + config_patches: dict[str, Any] | None, +) -> None: + from functorch.compile import minifier + from torch._inductor import _aoti_compile_and_package_inner + from torch._inductor.compile_fx import _aoti_flatten_inputs + + mod, args, kwargs = repro_common(options, exported_program) + + # update serialized_in_spec and serialized_out_spec + flat_example_inputs, inductor_configs = _aoti_flatten_inputs( + mod, args, kwargs, options=config_patches + ) + compiler_name = "aot_inductor" + if options.minifier_export_mode not in ["dynamo", "python"]: + raise AssertionError( + f"minifier_export_mode must be 'dynamo' or 'python', got {options.minifier_export_mode!r}" + ) + strict = options.minifier_export_mode == "dynamo" + skip_export_error = options.skip_export_error + + from torch.cuda import synchronize + + need_sync = False + + for arg in args: + if isinstance(arg, torch.Tensor) and arg.is_cuda: + need_sync = True + break + + def module_fails( + gm: torch.fx.GraphModule, + flat_example_inputs: list[Any], + check_str: str | None = None, + ) -> bool: + # Need to export first so the in_spec and out_spec are populated + tuple_inputs = tuple(flat_example_inputs) + # pyrefly: ignore [bad-assignment] + gm = export_for_aoti_minifier( + gm, tuple_inputs, strict=strict, skip_export_error=skip_export_error + ) + + # Some graphs cannot be used for AOTI/export (illegal graphs), these should be + # considered as graphs that don't fail in the minifier, so the minifier keeps searching. + if gm is None: + return False + + if not isinstance(gm, torch.fx.GraphModule): + raise AssertionError(f"Expected torch.fx.GraphModule, got {type(gm)}") + + try: + _aoti_compile_and_package_inner( + gm, + tuple_inputs, + load_and_run=True, + check_accuracy=options.accuracy, + inductor_configs=inductor_configs, + ) + if need_sync: + synchronize() # ensure segfaults are surfaced + return False + except Exception as e: + if check_str is not None and check_str not in repr(e): + return False + return True + + minifier( + mod, + flat_example_inputs, + module_fails=functools.partial(module_fails, check_str=options.check_str), + dump_state=functools.partial( + dump_compiler_graph_state, + compiler_name=compiler_name, + config_patches=config_patches, + accuracy=options.accuracy, + strict=strict, + ), + save_dir=options.save_dir, + offload_to_disk=options.offload_to_disk, + skip_offload=options.skip_saving_eager_intermediates, + skip_sanity=options.skip_sanity, + max_granularity=options.max_granularity, + ) + + +def run_repro( + exported_program: ExportedProgram, + *, + config_patches: dict[str, str] | None = None, + command: str = "run", + accuracy: bool | str = "", + save_dir: str | None = None, + tracing_mode: str | None = None, + check_str: str | None = None, + minifier_export_mode: str = "python", + skip_export_error: bool = True, + **more_kwargs: Any, +) -> Any: + for k in more_kwargs: + log.warning( + "Unrecognized kwarg %s; perhaps this repro was made on a newer version of PyTorch", + k, + ) + + if accuracy is True: + accuracy = "accuracy" + elif accuracy is False: + accuracy = "" + + parser = argparse.ArgumentParser( + description=f"""\ +An AOTI repro script, typically triggering a bug in PyTorch AOTInductor. +When run with no arguments, this script defaults to running '{command}'. +Extra flags may be available; to find out more, try '{command} --help'. +There are also alternate subcommands available, see below. + +default settings on this script: + {accuracy=} + {tracing_mode=} + {save_dir=} + {check_str=} +""", + formatter_class=argparse.RawTextHelpFormatter, + ) + + def common_flags(parser: argparse.ArgumentParser) -> None: + accuracy_group = parser.add_mutually_exclusive_group() + accuracy_group.add_argument( + "--no-accuracy", + dest="accuracy", + action="store_const", + const="", + default=accuracy, + help="do not test accuracy, just run the module and see if it errors", + ) + accuracy_group.add_argument( + "--accuracy", + action="store_const", + const="accuracy", + default=accuracy, + help="""\ +test if the RMSE between the compiled module and the fp64 reference is greater +than eager and the fp64 reference. This is usually more reliable than the +standard allclose test, as we expect numeric differences from compiling, often +improving accuracy over eager. RMSE test allows for compiled module to +diverge greatly from eager, as long as this divergence moves it closer to the +'true' mathematical value of the network. Caveats: (1) double precision can +still suffer from rounding error, so it is not a perfect reference (see for +example 'Herbie: Automatically Improving Floating Point Accuracy') for +approaches that detect the necessary working precision and compute it in +arbitrary precision floating point; unfortunately, this is not practical for +tensor computation; (2) if there are not enough samples in the output being +compared, we may get unlucky and have an unlucky greater RMSE than eager; this +could be overcome by applying a more rigorous statistical test at some +p-value, which we leave for future work. +""", + ) + accuracy_group.add_argument( + "--strict-accuracy", + dest="accuracy", + action="store_const", + const="strict_accuracy", + default=accuracy, + help="""\ +by default, when doing accuracy minification we will reject reductions which +change the divergence from a floating point divergence to a integral/boolean +divergence. This is because some operations like ReLU involve temporarily +sharp boundaries that smooth out again afterwards; without requiring +divergence on floating point, the minifier will often fixate on divergent +boolean tensor even though this is not the true source of the divergence. +However, rejecting these reductions makes it more difficult for the minifier +to make process. Using this option will let the minifier progress for ALL +divergences--you just might not end up with a useful repro in the end.""", + ) + + parser.add_argument( + "--save-dir", + type=str, + default=save_dir, + metavar="DIR", + help="directory where saved inputs live", + ) + parser.add_argument( + "--no-save-dir", + dest="save_dir", + action="store_const", + const=None, + help="don't use any directory for saved inputs", + ) + + subparsers = parser.add_subparsers( + dest="command", metavar="{run,minify}", required=True + ) + + parser_run = subparsers.add_parser( + "run", + help="just run the repro", + ) + common_flags(parser_run) + + parser_minify = subparsers.add_parser( + "minify", help="run the minifier on the repro" + ) + common_flags(parser_minify) + parser_get_args = subparsers.add_parser("get_args", help="get the args") + common_flags(parser_get_args) + parser_minify.add_argument( + "--skip-saving-eager-intermediates", + action="store_true", + help="skip saving eager intermediates on --minify", + ) + parser_minify.add_argument( + "--offload-to-disk", + action="store_true", + help="during minification, offload delta debugging intermediates to disk. Use if you're OOMing", + ) + parser_minify.add_argument( + "--skip-sanity", + action="store_true", + help="skip sanity check at beginning of minification on original graph", + ) + parser_minify.add_argument( + "--max-granularity", + type=int, + default=None, + help="start at this granularity and work down; must be power of 2", + ) + parser_minify.add_argument( + "--check-str", + type=str, + default=check_str, + help="require minified program to fail with error containing this string", + ) + parser_minify.add_argument( + "--minifier-export-mode", + type=str, + default=minifier_export_mode, + help=( + "The export mode used in minifier, either dynamo or python." + "`dynamo` corresponds to strict=True, and `python` corresponds to strict=False." + ), + ) + parser_minify.add_argument( + "--skip-export-error", + type=bool, + default=skip_export_error, + help="Skip intermediate graphs that cannot be exported.", + ) + + # Run the repro in the context of minification, inverting exit code meaning + parser_minifier_query = subparsers.add_parser( + "minifier-query", + ) + common_flags(parser_minifier_query) + parser_minifier_query.add_argument( + "--check-str", + type=str, + default=check_str, + help="require minified program to fail with error containing this string", + ) + + args = None + if len(sys.argv) <= 1: + args = [command, *sys.argv[1:]] + + options = parser.parse_args(args) + COMMAND_FNS = { + "minify": repro_minify, + "run": repro_run, + "get_args": repro_get_args, + } + return COMMAND_FNS[options.command]( + options, exported_program, config_patches=config_patches + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/resume_execution.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/resume_execution.py new file mode 100644 index 0000000000000000000000000000000000000000..2cbcda514b2d36088b16dda4ca8ea2cf9255d8c5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/resume_execution.py @@ -0,0 +1,784 @@ +""" +This module provides functionality for resuming Python execution at specific points in code, +primarily used by PyTorch Dynamo for control flow handling and optimization. It implements +bytecode transformation and execution state management to enable: + +- Resuming execution at arbitrary points in Python bytecode +- Managing context managers and their state across execution boundaries +- Transforming and generating new code objects with preserved execution state +- Supporting Python 3.11+ exception handling and block management +- Restoring torch function mode stacks and other execution context + +The module is critical for PyTorch Dynamo's ability to optimize code while preserving +Python semantics and execution state. +""" + +from __future__ import annotations + +import copy +import dataclasses +import sys +from typing import Any, cast, TYPE_CHECKING + +from .bytecode_transformation import ( + add_push_null, + bytecode_from_template, + create_binary_subscr, + create_call_function, + create_call_function_ex, + create_instruction, + create_jump_absolute, + create_load_const, + Instruction, + overwrite_instruction, + transform_code_object, + unique_id, +) +from .utils import ExactWeakKeyDictionary + + +if TYPE_CHECKING: + import types + from collections.abc import Callable, Iterable + from contextlib import AbstractContextManager + + from .output_graph import CodeOptions + + +# taken from code.h in cpython +CO_OPTIMIZED = 0x0001 +CO_NEWLOCALS = 0x0002 +CO_VARARGS = 0x0004 +CO_VARKEYWORDS = 0x0008 +CO_NESTED = 0x0010 +CO_GENERATOR = 0x0020 +CO_NOFREE = 0x0040 +CO_COROUTINE = 0x0080 +CO_ITERABLE_COROUTINE = 0x0100 +CO_ASYNC_GENERATOR = 0x0200 + +# trace_rules.py import this constant for consistency +TORCH_DYNAMO_RESUME_IN_PREFIX = "torch_dynamo_resume_in" +IS_TRACING_RESUME_PROLOGUE_VARNAME = "__is_tracing_resume_prologue" + + +# If is_resume - this codegen is for a resume function +def _initial_push_null(insts: list[Instruction]) -> None: + if sys.version_info >= (3, 11): + insts.append(create_instruction("PUSH_NULL")) + if sys.version_info < (3, 13): + insts.append(create_instruction("SWAP", arg=2)) + + +# Generates bytecode from template and splits the code where LOAD_FAST dummy is present. +def _bytecode_from_template_with_split( + template: Callable[..., Any], + stack_index: int, + varname_map: dict[str, Any] | None = None, +) -> tuple[list[Instruction], list[Instruction]]: + template_code = bytecode_from_template(template, varname_map=varname_map) + template_code.append(create_instruction("POP_TOP")) + + # adjust exception table entry depth + for inst in template_code: + if inst.exn_tab_entry: + inst.exn_tab_entry.depth += stack_index + + # search for LOAD_FAST dummy and replace it with 2 NOPs (we can break up the bytecode between them) + dummy_idx, dummy_inst = next( + ( + (i, inst) + for i, inst in enumerate(template_code) + if inst.opname in ("LOAD_FAST", "LOAD_FAST_BORROW") + and inst.argval == "dummy" + ), + (None, None), + ) + if dummy_idx is None: + raise AssertionError("LOAD_FAST dummy instruction not found in template code") + if dummy_inst is None: + raise AssertionError("LOAD_FAST dummy instruction instance is None") + + # replace LOAD_FAST dummy with first NOP marking exception area + overwrite_instruction(dummy_inst, [create_instruction("NOP")]) + + # POP_TOP follows LOAD_FAST dummy - replace with NOP marking end of exception area + if template_code[dummy_idx + 1].opname != "POP_TOP": + raise AssertionError( + f"Expected POP_TOP after LOAD_FAST dummy, got {template_code[dummy_idx + 1].opname}" + ) + overwrite_instruction(template_code[dummy_idx + 1], [create_instruction("NOP")]) + + return template_code[: dummy_idx + 1], template_code[dummy_idx + 1 :] + + +def _try_except_tf_mode_template(dummy: Any) -> None: + # NOTE: Make sure this name matches what is generated by symbolic_convert:import_source + # on torch._dynamo.utils. + # pyrefly: ignore [unknown-name] + global __import_torch_dot__dynamo_dot_utils + try: + dummy + except: + __import_torch_dot__dynamo_dot_utils._pop_torch_function_stack() # type: ignore[name-defined] + raise + + +@dataclasses.dataclass(frozen=True) +class ReenterWith: + stack_index: int + target_values: tuple[Any, ...] | None = None + + def try_except_torch_function_mode( + self, code_options: CodeOptions, cleanup: list[Instruction] + ) -> list[Instruction]: + """ + Codegen based off of: + try: + (rest) + except: + (pop the torch function mode that was pushed for this context) + raise + """ + setup_try_except, epilogue = _bytecode_from_template_with_split( + _try_except_tf_mode_template, + self.stack_index, + ) + cleanup[:] = epilogue + cleanup + + return setup_try_except + + # If we do not want to destroy the stack, we can do the same thing as a + # `SETUP_WITH` block, only that we store the context manager in a local_symbol + def try_finally( + self, code_options: CodeOptions, cleanup: list[Instruction] + ) -> list[Instruction]: + """ + Codegen based off of: + load args + enter context + try: + (rest) + finally: + exit context + """ + # NOTE: we assume that TOS is a context manager CLASS! + # pyrefly: ignore [implicit-any] + load_args = [] + if self.target_values: + load_args = [create_load_const(val) for val in self.target_values] + ctx_name = unique_id(f"___context_manager_{self.stack_index}") + if ctx_name not in code_options["co_varnames"]: + code_options["co_varnames"] += (ctx_name,) + for name in ["__enter__", "__exit__"]: + if name not in code_options["co_names"]: + code_options["co_names"] += (name,) + + create_ctx: list[Instruction] = [] + _initial_push_null(create_ctx) + create_ctx.extend( + [ + *load_args, + *create_call_function(len(load_args), False), + create_instruction("STORE_FAST", argval=ctx_name), + ] + ) + + def _template(ctx: AbstractContextManager[Any], dummy: Any) -> None: + ctx.__enter__() + try: + dummy + finally: + ctx.__exit__(None, None, None) + + setup_try_finally, epilogue = _bytecode_from_template_with_split( + _template, self.stack_index, varname_map={"ctx": ctx_name} + ) + cleanup[:] = epilogue + cleanup + return create_ctx + setup_try_finally + + def __call__( + self, code_options: dict[str, Any], cleanup: list[Instruction] + ) -> tuple[list[Instruction], Instruction | None]: + """ + Codegen based off of: + with ctx(args): + (rest) + """ + # NOTE: we assume that TOS is a context manager CLASS! + # pyrefly: ignore [implicit-any] + load_args = [] + if self.target_values: + load_args = [create_load_const(val) for val in self.target_values] + + create_ctx: list[Instruction] = [] + # Do not push NULL in Python 3.14+ since the NULL should be on the symbolic stack. + if sys.version_info < (3, 14): + _initial_push_null(create_ctx) + create_ctx.extend( + [ + *load_args, + *create_call_function(len(load_args), False), + ] + ) + + def _template(ctx: AbstractContextManager[Any], dummy: Any) -> None: + with ctx: + dummy + + setup_with, epilogue = _bytecode_from_template_with_split( + _template, self.stack_index + ) + cleanup[:] = epilogue + cleanup + + load_fast_ctx_inst = next( + ( + inst + for inst in setup_with + if inst.opname in ("LOAD_FAST", "LOAD_FAST_BORROW") + and inst.argval == "ctx" + ), + None, + ) + if load_fast_ctx_inst is None: + raise AssertionError("LOAD_FAST ctx instruction not found in setup_with") + # ctx already loaded on stack before the template - no need to LOAD_FAST + overwrite_instruction(load_fast_ctx_inst, [create_instruction("NOP")]) + + # 3.11+ only + push_exc_info_gen = ( + inst for inst in epilogue if inst.opname == "PUSH_EXC_INFO" + ) + push_exc_info_inst = next(push_exc_info_gen, None) + # expect only 1 PUSH_EXC_INFO in epilogue + if next(push_exc_info_gen, None) is not None: + raise AssertionError("Expected only 1 PUSH_EXC_INFO in epilogue") + + return create_ctx + setup_with, push_exc_info_inst + + +@dataclasses.dataclass +class ResumeFunctionMetadata: + code: types.CodeType + instructions: list[Instruction] = dataclasses.field(default_factory=list) + # Python 3.11+ fields + # NOTE: Python 3.11 removed blocks, but for our purposes, a "block" consists + # of instructions of all exception table entries that have the same target. + + # map from PUSH_EXC_INFO's in the prefix to original block target offset + prefix_block_target_offset_remap: list[int] = dataclasses.field( + default_factory=list + ) + # per-offset map from new block target offsets to original block target offsets + block_target_offset_remap: dict[tuple[int, int], dict[int, int]] = ( + dataclasses.field(default_factory=dict) + ) + + +def _filter_iter( + l1: Iterable[Any], + l2: Iterable[Any], + cond: Callable[[Any, Any], bool], +) -> list[Any]: + """ + Two-pointer conditional filter. + e.g. _filter_iter(insts, sorted_offsets, lambda i, o: i.offset == o) + returns the instructions with offsets in sorted_offsets + """ + it = iter(l2) + res: list[Instruction] = [] + try: + cur = next(it) + for val in l1: + if cond(val, cur): + res.append(val) + cur = next(it) + except StopIteration: + pass + return res + + +def _load_tuple_and_call(tup: tuple[Any, ...]) -> list[Instruction]: + insts: list[Instruction] = [] + _initial_push_null(insts) + insts.extend(create_load_const(val) for val in tup) + insts.extend(create_call_function(len(tup), False)) + return insts + + +class ContinueExecutionCache: + cache = ExactWeakKeyDictionary() + generated_code_metadata = ExactWeakKeyDictionary() + + @classmethod + def lookup( + cls, code: types.CodeType, lineno: int, init_offset: int, *key: Any + ) -> types.CodeType: + if code not in cls.cache: + cls.cache[code] = {} + key = tuple(key) + if key not in cls.cache[code]: + cls.cache[code][key] = cls.generate(code, lineno, init_offset, *key) + return cls.cache[code][key] + + @classmethod + def generate( + cls, + code: types.CodeType, + lineno: int, + init_offset: int, + resume_offset: int, + setup_fn_target_offsets: tuple[int, ...], # only used in Python 3.11+ + nstack: int, + argnames: tuple[str, ...], + argnames_null: tuple[str, ...], + setup_fns: tuple[ReenterWith, ...], + handle_inactive_ctx: bool, + stack_ctx_vars: tuple[tuple[int, tuple[Any, ...]], ...], + argnames_ctx_vars: tuple[tuple[str, tuple[Any, ...]], ...], + null_idxes: tuple[int, ...], + # mainly used to ensure distinct code objects per stack trace, + # which prevents excessive recompilation of inner frames + nested_code_objs: tuple[types.CodeType], + # Are we currently graph breaking on an instruction that doesn't push + # its result to the stack? If so, and we are not the leaf resume, then we need to pop + # the result of calling the next resume function. + pop_nested_resume_result: bool, + ) -> types.CodeType: + if resume_offset is None: + raise AssertionError("resume_offset must not be None") + if code.co_flags & ( + CO_GENERATOR | CO_COROUTINE | CO_ITERABLE_COROUTINE | CO_ASYNC_GENERATOR + ): + raise AssertionError( + "Cannot generate resume function for generator, coroutine, or async generator" + ) + if not (code.co_flags & CO_OPTIMIZED): + raise AssertionError("Code object must have CO_OPTIMIZED flag set") + if code in ContinueExecutionCache.generated_code_metadata: + return cls.generate_based_on_original_code_object( + code, + lineno, + init_offset, + resume_offset, + setup_fn_target_offsets, + nstack, + argnames, + argnames_null, + setup_fns, + handle_inactive_ctx, + stack_ctx_vars, + argnames_ctx_vars, + null_idxes, + nested_code_objs, + pop_nested_resume_result, + ) + + is_py311_plus = sys.version_info >= (3, 11) + meta = ResumeFunctionMetadata(code) + + def update( + instructions: list[Instruction], code_options: dict[str, Any] + ) -> None: + meta.instructions = copy.deepcopy(instructions) + + args = ["__nested_resume_fns", "__nested_frame_values"] + args += [f"___stack{i}" for i in range(nstack)] + args.extend(v for v in argnames if v not in args) + freevars = tuple(code_options["co_cellvars"] or []) + tuple( + code_options["co_freevars"] or [] + ) + freevars = tuple(sorted(freevars)) + code_options["co_name"] = ( + f"{TORCH_DYNAMO_RESUME_IN_PREFIX}_{code_options['co_name']}_at_{lineno}" + ) + if is_py311_plus: + qualified_path = code_options["co_qualname"].rsplit(".", maxsplit=1) + if len(qualified_path) == 1: + code_options["co_qualname"] = code_options["co_name"] + else: + if len(qualified_path) != 2: + raise AssertionError( + f"Expected qualified path to have 2 parts, got {len(qualified_path)}" + ) + module_name, co_name = qualified_path + code_options["co_qualname"] = ( + f"{module_name}.{TORCH_DYNAMO_RESUME_IN_PREFIX}_{co_name}_at_{lineno}" + ) + code_options["co_firstlineno"] = lineno + code_options["co_cellvars"] = () + code_options["co_freevars"] = freevars + code_options["co_argcount"] = len(args) + code_options["co_posonlyargcount"] = 0 + code_options["co_kwonlyargcount"] = 0 + code_options["co_varnames"] = tuple( + args + + [v for v in argnames_null if v not in args] + + [v for v in code_options["co_varnames"] if v not in args] + + [IS_TRACING_RESUME_PROLOGUE_VARNAME] + ) + code_options["co_flags"] = code_options["co_flags"] & ~( + CO_VARARGS | CO_VARKEYWORDS + ) + target = next(i for i in instructions if i.offset == resume_offset) + + prefix = [] + if is_py311_plus: + if freevars: + prefix.append( + create_instruction("COPY_FREE_VARS", arg=len(freevars)) + ) + prefix.append(create_instruction("RESUME", arg=0)) + + # Set is_tracing_resume_prologue to prevent graph breaks. + # This doesn't really do anything at runtime, but dynamo will trace this + # and will know that we're in a resume function prologue. + prefix.extend( + [ + create_instruction("LOAD_CONST", argval=True), + create_instruction( + "STORE_FAST", argval=IS_TRACING_RESUME_PROLOGUE_VARNAME + ), + ] + ) + + cleanup: list[Instruction] = [] + hooks = {fn.stack_index: fn for fn in setup_fns} + hook_target_offsets = { + fn.stack_index: setup_fn_target_offsets[i] + for i, fn in enumerate(setup_fns) + } + offset_to_inst = {inst.offset: inst for inst in instructions} + # map old hook targets to new targets generated by the hook + # pyrefly: ignore [implicit-any] + old_hook_target_remap = {} + stack_i = 0 + null_i = 0 + stack_ctx_vars_d = dict(stack_ctx_vars) # type: ignore[var-annotated,arg-type] + for i in range(nstack + len(null_idxes)): + if null_i < len(null_idxes) and null_idxes[null_i] == i: + prefix.append(create_instruction("PUSH_NULL")) + null_i += 1 + else: + prefix.append( + create_instruction("LOAD_FAST", argval=f"___stack{stack_i}") + ) + if handle_inactive_ctx and stack_i in stack_ctx_vars_d: + # NOTE: we assume that current stack var is a context manager CLASS! + # Load args for context variable and construct it + prefix.extend(_load_tuple_and_call(stack_ctx_vars_d[stack_i])) + stack_i += 1 + + if i in hooks: + hook = hooks.pop(i) + hook_insts, exn_target = hook(code_options, cleanup) + prefix.extend(hook_insts) + if is_py311_plus: + hook_target_offset = hook_target_offsets.pop(i) + old_hook_target = offset_to_inst[hook_target_offset] + meta.prefix_block_target_offset_remap.append(hook_target_offset) + old_hook_target_remap[old_hook_target] = exn_target + + if is_py311_plus: + # reverse the mapping since targets of later/nested contexts are inserted + # into the mapping later, but show up earlier in the prefix. + meta.prefix_block_target_offset_remap = list( + reversed(meta.prefix_block_target_offset_remap) + ) + + if hooks: + raise AssertionError(f"Unprocessed hooks remaining: {hooks}") + + # NOTE: we assume that local var is a context manager CLASS! + # initialize inactive context vars in argnames + if handle_inactive_ctx: + for name, vals in argnames_ctx_vars: + prefix.append(create_instruction("LOAD_FAST", argval=name)) + prefix.extend(_load_tuple_and_call(vals)) + prefix.append(create_instruction("STORE_FAST", argval=name)) + + # 3.12+: store NULL into variables that were NULL + if argnames_null: + if sys.version_info < (3, 12): + raise AssertionError( + f"argnames_null requires Python 3.12+, got {sys.version_info}" + ) + for v in argnames_null: + if v in args: + raise AssertionError( + f"argnames_null variable {v!r} should not be in args" + ) + prefix.extend( + [ + create_instruction("PUSH_NULL"), + create_instruction("STORE_FAST", argval=v), + ] + ) + + # Call nested resume function + if nested_code_objs: + prefix.extend( + [ + # set up __nested_resume_fns[-1] call + *add_push_null( + [ + create_instruction( + "LOAD_FAST", argval="__nested_resume_fns" + ), + create_instruction("LOAD_CONST", argval=-1), + create_binary_subscr(), + ] + ), + # del __nested_resume_fns[-1] + create_instruction("LOAD_FAST", argval="__nested_resume_fns"), + create_instruction("LOAD_CONST", argval=-1), + create_instruction("DELETE_SUBSCR"), + # load [__nested_resume_fns, __nested_frame_values] + create_instruction("LOAD_FAST", argval="__nested_resume_fns"), + create_instruction("LOAD_FAST", argval="__nested_frame_values"), + create_instruction("BUILD_LIST", arg=2), + # load __nested_frame_values[-1] + create_instruction("LOAD_FAST", argval="__nested_frame_values"), + create_instruction("LOAD_CONST", argval=-1), + create_binary_subscr(), + # create [ + # __nested_resume_fns, + # __nested_frame_values, + # *__nested_frame_values[-1], + # ] + create_instruction("LIST_EXTEND", arg=1), + # del __nested_frame_values[-1] + create_instruction("LOAD_FAST", argval="__nested_frame_values"), + create_instruction("LOAD_CONST", argval=-1), + create_instruction("DELETE_SUBSCR"), + # delete __nested values + create_instruction("DELETE_FAST", argval="__nested_resume_fns"), + create_instruction( + "DELETE_FAST", argval="__nested_frame_values" + ), + # Set is_tracing_resume_prologue back to allow graph breaks + # in the nested resume + create_instruction("LOAD_CONST", argval=False), + create_instruction( + "STORE_FAST", argval=IS_TRACING_RESUME_PROLOGUE_VARNAME + ), + # finish the call + *create_call_function_ex(False, False), + ] + ) + if pop_nested_resume_result: + # pop the result of calling the nested resume function + prefix.append(create_instruction("POP_TOP")) + else: + # Set is_tracing_resume_prologue back to allow graph breaks after the jump + prefix.extend( + [ + create_instruction("LOAD_CONST", argval=False), + create_instruction( + "STORE_FAST", argval=IS_TRACING_RESUME_PROLOGUE_VARNAME + ), + ] + ) + + prefix.append(create_jump_absolute(target)) + + # because the line number table monotonically increases from co_firstlineno + # remove starts_line for any instructions before the graph break instruction + # this will ensure the instructions after the break have the correct line numbers + for inst in instructions: + if inst.offset == target.offset: + break + inst.starts_line = None + if sys.version_info >= (3, 11): + inst.positions = None + + if cleanup: + prefix.extend(cleanup) + prefix.extend(cls.unreachable_codes(code_options)) + + # remap original instructions' exception table entries + if old_hook_target_remap: + # pyrefly: ignore [unbound-name] + if not is_py311_plus: + raise AssertionError("old_hook_target_remap requires Python 3.11+") + for inst in instructions: + if ( + inst.exn_tab_entry + and inst.exn_tab_entry.target in old_hook_target_remap + ): + inst.exn_tab_entry.target = old_hook_target_remap[ # type: ignore[assignment] + inst.exn_tab_entry.target + ] + + # TODO(jansel): add dead code elimination here + instructions[:] = prefix + instructions + + new_code, _ = transform_code_object(code, update) + ContinueExecutionCache.generated_code_metadata[new_code] = meta + return new_code + + @staticmethod + def unreachable_codes(code_options: dict[str, Any]) -> list[Instruction]: + """Codegen a `raise None` to make analysis work for unreachable code""" + return [ + create_load_const(None), + create_instruction("RAISE_VARARGS", arg=1), + ] + + @classmethod + def generate_based_on_original_code_object( + cls, + code: types.CodeType, + lineno: int, + init_offset: int, + resume_offset: int, + setup_fn_target_offsets: tuple[int, ...], + *args: Any, + ) -> types.CodeType: + """ + This handles the case of generating a resume into code generated + to resume something else. We want to always generate starting + from the original code object so that if control flow paths + converge we only generated 1 resume function (rather than 2^n + resume functions). + """ + + meta: ResumeFunctionMetadata = ContinueExecutionCache.generated_code_metadata[ + code + ] + + def find_orig_offset(cur_offset: int) -> int: + orig_offset = -1 + + def find_orig_offset_transform( + instructions: list[Instruction], code_options: dict[str, Any] + ) -> None: + nonlocal orig_offset + (target,) = (i for i in instructions if i.offset == cur_offset) + # match the functions starting at the last instruction as we have added a prefix + new_target_tuple = tuple( + i2 + for i1, i2 in zip( + reversed(instructions), reversed(meta.instructions) + ) + if i1 is target + ) + + if not new_target_tuple: + # Instruction with cur_offset in instructions was not found + # in the original code - orig_offset left as -1. + # Caller expected to handle this case. + return + + if len(new_target_tuple) != 1: + raise AssertionError( + f"Expected exactly 1 matching target, got {len(new_target_tuple)}" + ) + new_target = new_target_tuple[0] + + if target.opcode != new_target.opcode: + raise AssertionError( + f"Opcode mismatch: target has {target.opcode}, " + f"new_target has {new_target.opcode}" + ) + if new_target.offset is None: + raise AssertionError("new_target.offset must not be None") + orig_offset = new_target.offset + + transform_code_object(code, find_orig_offset_transform) + return orig_offset + + orig_init_offset = find_orig_offset(init_offset) + # It is fine if the initial instruction is not found in the original code; + # this means we graph broke in the prefix, which only happens with nested graph breaks. + # We should not be running into ambiguous graph break issues here. + orig_resume_offset = find_orig_offset(resume_offset) + if orig_resume_offset <= -1: + raise AssertionError( + "resume instruction not found in original code - this is a bug." + ) + + if sys.version_info >= (3, 11): + # setup_fn_target_offsets currently contains the target offset of + # each setup_fn, based on `code`. When we codegen the resume function + # based on the original code object, `meta.code`, the offsets in + # setup_fn_target_offsets must be based on `meta.code` instead. + offset_key = (orig_init_offset, orig_resume_offset) + # NOTE: we key by offset_key since the same resume function may graph + # break in multiple places and we need different block_target_offset_remap's + # for each graph break location. Keying by orig_resume_offset may not be enough + # if 2 graph breaks on different initial offsets resume on the same instruction + # (although this is rare and not tested anywhere). + if offset_key not in meta.block_target_offset_remap: + block_target_offset_remap = meta.block_target_offset_remap[ + offset_key + # pyrefly: ignore [implicit-any] + ] = {} + + def remap_block_offsets( + instructions: list[Instruction], code_options: dict[str, Any] + ) -> None: + # NOTE: each prefix block generates exactly one PUSH_EXC_INFO, + # so we can tell which block a prefix PUSH_EXC_INFO belongs to, + # by counting. Then we can use meta.prefix_block_target_offset_remap + # to determine where in the original code the PUSH_EXC_INFO offset + # replaced. + prefix_blocks: list[Instruction] = [] + for inst in instructions: + # NOTE meta.prefix_block_target_offset_remap is based off of how we codegen'd + # context managers at the prefix/prologue of the resume function. It is the same for + # every graph break in the same resume function, so we do not need to recompute + # for each graph break (unlike for meta.block_target_offset_remap) + if len(prefix_blocks) == len( + meta.prefix_block_target_offset_remap + ): + break + if inst.opname == "PUSH_EXC_INFO": + prefix_blocks.append(inst) + + # remap block target offsets for blocks generated in the resume prefix + for inst, o in zip( + prefix_blocks, meta.prefix_block_target_offset_remap + ): + block_target_offset_remap[cast(int, inst.offset)] = o + + # current bytecode targets are after the prefix PUSH_EXC_INFO's + cur_start_offset = ( + cast(int, prefix_blocks[-1].offset) if prefix_blocks else -1 + ) + # get the remaining block target offsets of the current bytecode + cur_inst_offsets = sorted( + n for n in setup_fn_target_offsets if n > cur_start_offset + ) + targets = _filter_iter( + instructions, cur_inst_offsets, lambda inst, o: inst.offset == o + ) + # The original code and resume code should have matching suffixes. + # Match the post-prefix block target offsets of the current resume code + # and the original code. + orig_targets = reversed( + _filter_iter( + zip(reversed(instructions), reversed(meta.instructions)), + reversed(targets), + lambda v1, v2: v1[0] is v2, + ) + ) + for orig, cur in zip(orig_targets, targets): + block_target_offset_remap[cur.offset] = orig[1].offset + + transform_code_object(code, remap_block_offsets) + + # if offset_key or offset is not in setup_fn_target_offsets, it is an error + # that needs to be fixed + setup_fn_target_offsets = tuple( + meta.block_target_offset_remap[offset_key][n] + for n in setup_fn_target_offsets + ) + return ContinueExecutionCache.lookup( + meta.code, + lineno, + orig_init_offset, + orig_resume_offset, + setup_fn_target_offsets, + *args, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/side_effects.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/side_effects.py new file mode 100644 index 0000000000000000000000000000000000000000..e7f366dadc852f3c69cfc1df91c0d63f59150ced --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/side_effects.py @@ -0,0 +1,2120 @@ +""" +Side effect tracking and management for TorchDynamo's compilation system. + +This module provides infrastructure for tracking and managing side effects that occur +during symbolic execution, including: + +- Tracking mutations to objects, attributes, and variables +- Managing context changes (cell variables, global namespace modifications) +- Handling aliasing and object identity preservation +- Managing stack frame state and local variable changes +- Tracking function calls with side effects + +Key classes: +- SideEffects: Main container for tracking all side effects during execution +- MutableSideEffects: Specialization for mutable object tracking +- AttributeMutation/ValueMutation: Track specific types of mutations +- Various specialized side effect classes for different scenarios + +The side effect system ensures that mutations performed during symbolic execution +are properly replayed during runtime, maintaining the correctness of compiled code +while enabling optimizations where safe. +""" + +import collections +import contextlib +import dataclasses +import enum +import inspect +import logging +import textwrap +import traceback +import weakref +from collections.abc import Callable, Generator, MutableMapping +from types import CellType +from typing import Any, TYPE_CHECKING + +import torch +import torch.nn +from torch._dynamo.variables.misc import AutogradFunctionContextVariable +from torch._library.utils import RegistrationHandle +from torch.utils._ordered_set import OrderedSet +from torch.utils._pytree import is_structseq_class + +from . import config, graph_break_hints, utils, variables +from .bytecode_transformation import ( + bytecode_from_template, + create_call_function, + create_call_method, + create_instruction, + Instruction, +) +from .codegen import PyCodegen +from .exc import collapse_resume_frames, get_stack_above_dynamo, unimplemented +from .source import AttrSource, GlobalSource, LocalCellSource, Source, TempLocalSource +from .utils import ( + is_frozen_dataclass, + is_namedtuple_cls, + is_pybind11_enum_member, + nn_module_new, + object_new, +) +from .variables.base import ( + AttributeMutation, + AttributeMutationExisting, + AttributeMutationNew, + AttrMutationKind, + is_side_effect_safe, + ValueMutationExisting, + ValueMutationNew, + VariableTracker, +) +from .variables.user_defined import FrozenDataClassVariable + + +if TYPE_CHECKING: + from torch._dynamo.output_graph import OutputGraph + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + from torch._dynamo.variables.lists import ListVariable + + +side_effects_log = torch._logging.getArtifactLogger(__name__, "side_effects") + + +@dataclasses.dataclass(frozen=True) +class SideEffectReplayContext: + side_effects: "SideEffects" + codegen: PyCodegen + var: VariableTracker + suffixes: list[list[Instruction]] + log: Callable[[VariableTracker], None] + + +SideEffectReplayMatcher = Callable[[SideEffectReplayContext], bool] +SideEffectReplayCodegen = Callable[[SideEffectReplayContext], None] +SideEffectReplayHandlerDecorator = Callable[ + [SideEffectReplayCodegen], SideEffectReplayCodegen +] + + +@dataclasses.dataclass(frozen=True) +class SideEffectReplayHandler: + name: str + matcher: SideEffectReplayMatcher + codegen: SideEffectReplayCodegen + priority: int = 0 + + +class _SideEffectReplayRegistry: + def __init__(self) -> None: + self.handlers: list[SideEffectReplayHandler] = [] + + def register_handler(self, handler: SideEffectReplayHandler) -> RegistrationHandle: + self.handlers.append(handler) + + def deregister() -> None: + self.handlers.remove(handler) + + return RegistrationHandle(deregister) + + def lookup_handler( + self, ctx: SideEffectReplayContext + ) -> SideEffectReplayHandler | None: + matches = [handler for handler in self.handlers if handler.matcher(ctx)] + if not matches: + return None + matches.sort(key=lambda handler: handler.priority, reverse=True) + top = matches[0] + if len(matches) > 1 and matches[1].priority == top.priority: + names = [ + handler.name for handler in matches if handler.priority == top.priority + ] + raise RuntimeError( + f"Ambiguous side effect replay handler for " + f"{type(ctx.var).__name__}: {names}" + ) + return top + + +_side_effect_replay_registry = _SideEffectReplayRegistry() + + +def _register_side_effect_replay_handler( + handler: SideEffectReplayHandler, +) -> RegistrationHandle: + return _side_effect_replay_registry.register_handler(handler) + + +def register_side_effect_replay_handler( + *, + name: str, + matcher: SideEffectReplayMatcher, + priority: int = 0, +) -> SideEffectReplayHandlerDecorator: + def decorator( + codegen: SideEffectReplayCodegen, + ) -> SideEffectReplayCodegen: + _register_side_effect_replay_handler( + SideEffectReplayHandler( + name=name, + matcher=matcher, + codegen=codegen, + priority=priority, + ) + ) + return codegen + + return decorator + + +def _manual_dict_setitem( + dict_from: dict[Any, Any], dict_to: dict[Any, Any], mro_index: int +) -> None: + # Carefully calls the dict or OrderedDict `clear` or `__setitem__`. We have + # to be careful because we don't want to trigger the user defined object + # setitem or clear. The mro_index is used to find the dict/OrderedDict from + # the class mro. + dict_class = type(dict_to).__mro__[mro_index] + dict_class.clear(dict_to) # type: ignore[attr-defined] + for k, v in dict_from.items(): + dict_class.__setitem__(dict_to, k, v) # type: ignore[index] + + +def _manual_list_update(list_from: list[Any], list_to: list[Any]) -> None: + list.clear(list_to) + list.extend(list_to, list_from) + + +def _manual_deque_update(deque_from: Any, deque_to: Any) -> None: + # Call the deque methods directly, not any overridden subclass methods. + # deque_to keeps its (read-only) maxlen, so extend re-applies eviction. + collections.deque.clear(deque_to) + collections.deque.extend(deque_to, deque_from) + + +class SideEffects: + """ + Maintain records of mutations and provide methods to apply them during code generation. + + Handles tracking and applying side effects during PyTorch Dynamo compilation, + maintaining Python semantics by managing mutations, attribute modifications, + and other side effects that occur during program execution. + + Key responsibilities: + - Tracks mutations to Python objects, lists, and dictionaries that need to be + applied after an FX graph is run. + - Manages attribute modifications and deletions + - Handles tensor hooks and backward pass state + - Tracks cell variable mutations and global variable changes + - Ensures correct ordering and application of side effects after graph execution + + This ensures that optimized code behaves identically to the original Python code with + respect to object mutations and other side effects. + """ + + id_to_variable: dict[int, VariableTracker] + store_attr_mutations: dict[VariableTracker, dict[str, VariableTracker]] + attr_mutation_kinds: dict[VariableTracker, dict[str, AttrMutationKind]] + keepalive: list[object] + # Maps variable tracker to list of user stacks (StackSummary objects, formatted lazily) + mutation_user_stacks: dict[VariableTracker, list[traceback.StackSummary]] + + def __init__( + self, + output_graph: "OutputGraph", + id_to_variable: dict[int, VariableTracker] | None = None, + store_attr_mutations: dict[VariableTracker, dict[str, VariableTracker]] + | None = None, + attr_mutation_kinds: dict[VariableTracker, dict[str, AttrMutationKind]] + | None = None, + mutation_user_stacks: dict[VariableTracker, list[traceback.StackSummary]] + | None = None, + keepalive: list[object] | None = None, + save_for_backward: list[ + tuple[AutogradFunctionContextVariable, list[VariableTracker]] + ] + | None = None, + tensor_hooks: dict[ + int, + tuple[ + "variables.TensorVariable", + VariableTracker, + "variables.RemovableHandleVariable", + str, + ], + ] + | None = None, + ) -> None: + super().__init__() + self.output_graph_weakref = weakref.ref(output_graph) + self.id_to_variable = id_to_variable or {} + self.store_attr_mutations = store_attr_mutations or {} + self.attr_mutation_kinds = attr_mutation_kinds or {} + self.mutation_user_stacks = mutation_user_stacks or {} + self.keepalive = keepalive or [] + self.save_for_backward = save_for_backward or [] + self.tensor_hooks = tensor_hooks or {} + # Used by MappingProxyVariable to graph break in case of any mutated + # dict + self._has_existing_dict_mutation = False + # Track Compiled Autograd final callbacks that must be called at the end of Compiled Autograd backward graph. + # Only applicable if this graph is created from Dynamo tracing in Compiled Autograd. + self.ca_final_callbacks_var: ListVariable | None = None + + # Tracks VariableTracker objects whose mutations can be skipped. + # For normal mutated variables, Dynamo generates code to replay/reconstruct + # the mutations after graph execution. However, variables in this set have + # their mutations ignored - the mutations happen during + # execution but don't need to be replayed in the generated code. + # Used for temporary mutations in contexts like torch.func.functional_call, + # where module parameters/buffers are modified but later restored. + self.ignore_mutation_on_these_variables: set[VariableTracker] = set() + # Sources mutated during tracing: AttrSource for attribute + # mutations, var.source for value mutations (list/dict/etc). + self.mutated_sources: OrderedSet[Source] = OrderedSet() + + # Deferred side-effect checking for nullified attribute mutations. + # Maps (vt_id, attr_name) → (original_value, current_value). + # On validation, we check original == current. + self.deferred_attr_mutations: dict[tuple[int, str], tuple[object, object]] = {} + + def ignore_mutations_on(self, var: VariableTracker) -> None: + """Mutations to this variable will be executed but not tracked, + typically used for temporary mutations that are later restored.""" + self.ignore_mutation_on_these_variables.add(var) + + def stop_ignoring_mutations_on(self, var: VariableTracker) -> None: + """Remove a variable from the skip mutation set, restoring normal mutation tracking.""" + if var in self.ignore_mutation_on_these_variables: + self.ignore_mutation_on_these_variables.remove(var) + + @contextlib.contextmanager + def defer_side_effect_checks(self) -> Generator[None, None, None]: + """Defer outer-scope attribute mutation checks until tracing completes. + + Context managers that flip-flop a flag (set on enter, restore on exit) + produce no net side effect. Instead of failing immediately, we track + original and current values, then validate they match after tracing. + + Note: this context only validates that mutations were nullified — it + does NOT roll back store_attr_mutations. Callers must restore + side_effects separately (e.g., via prev_side_effects pattern) to + discard the mutations after the HOP. + """ + saved = self.deferred_attr_mutations + self.deferred_attr_mutations = {} + try: + yield + self.validate_deferred_attr_mutations() + finally: + self.deferred_attr_mutations = saved + + def snapshot_attr_mutation( + self, item: VariableTracker, name: str, value: VariableTracker + ) -> bool: + """Record an attribute mutation for deferred validation. + + Returns True if successfully deferred, False if we cannot read the + original value (tp_getattro_impl raises NotImplementedError) or the + original is not a python constant — caller should fall back to + check_allowed_side_effect. + """ + key = (id(item), name) + if not value.is_python_constant(): + raise AssertionError( + "value must be a python constant (guaranteed by caller store_attr)" + ) + current = value.as_python_constant() + if key in self.deferred_attr_mutations: + original = self.deferred_attr_mutations[key][0] + else: + output_graph = self.output_graph_weakref() + if output_graph is None: + raise AssertionError("output_graph weakref is dead") + tx = output_graph.current_tx + try: + original_vt = item.tp_getattro_impl(tx, name) # type: ignore[arg-type] + except NotImplementedError: + return False + if not original_vt.is_python_constant(): + return False + original = original_vt.as_python_constant() + self.deferred_attr_mutations[key] = (original, current) + return True + + def validate_deferred_attr_mutations(self) -> None: + """Check that all deferred attribute mutations were nullified.""" + for (_, name), (original, current) in self.deferred_attr_mutations.items(): + if original != current: + unimplemented( + gb_type="HOP: Non-nullified side effect", + context=f"Attribute '{name}' was not restored to its original value", + explanation=f"Attribute '{name}' on an outer-scope object was " + f"changed from {original!r} to {current!r} inside a " + "higher-order op subgraph. Dynamo only supports mutations " + "that are undone before the subgraph exits (e.g., context " + "managers that save/restore a flag). If you intentionally " + "want this side effect, move the mutation outside of the " + "higher-order op.", + hints=[*graph_break_hints.FUNDAMENTAL], + ) + + def _capture_user_stack(self, key: VariableTracker) -> None: + """Capture the current user stack from the instruction translator.""" + if config.side_effect_replay_policy == "silent": + return + if key not in self.mutation_user_stacks: + self.mutation_user_stacks[key] = [] + self.mutation_user_stacks[key].append( + torch._guards.TracingContext.extract_stack() + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, SideEffects): + raise AssertionError(f"Expected SideEffects, got {type(other)}") + # NB: do NOT test keepalive + return ( + self.id_to_variable == other.id_to_variable + and self.store_attr_mutations == other.store_attr_mutations + and self.attr_mutation_kinds == other.attr_mutation_kinds + and self.save_for_backward == other.save_for_backward + and self.tensor_hooks == other.tensor_hooks + ) + + def diff(self, other: "SideEffects") -> str | None: + if self.id_to_variable != other.id_to_variable: + sk_itv = self.id_to_variable.keys() + ok_itv = other.id_to_variable.keys() + if sk_itv != ok_itv: + return f"id_to_variable keys: {sk_itv} != {ok_itv}" + # Feel free to augment this with more fancy diffing logic + # if needed for debugging + return "id_to_variable: unknown diff" + elif self.store_attr_mutations != other.store_attr_mutations: + sk_sam = self.store_attr_mutations.keys() + ok_sam = other.store_attr_mutations.keys() + if sk_sam != ok_sam: + return f"store_attr_mutations keys: {sk_sam} != {ok_sam}" + return "store_attr_mutations: unknown diff" + elif self.attr_mutation_kinds != other.attr_mutation_kinds: + return "attr_mutation_kinds: unknown diff" + elif self.save_for_backward != other.save_for_backward: + return "save_for_backward" + elif self.tensor_hooks != other.tensor_hooks: + return "tensor_hooks" + else: + return None + + def clone(self) -> "SideEffects": + """Create a shallow copy""" + ref = self.output_graph_weakref() + if ref is None: + raise AssertionError("output_graph weakref is dead during clone") + return self.__class__( + output_graph=ref, + id_to_variable=dict(self.id_to_variable), + store_attr_mutations={ + k: dict(v) for k, v in self.store_attr_mutations.items() + }, + attr_mutation_kinds={ + k: dict(v) for k, v in self.attr_mutation_kinds.items() + }, + mutation_user_stacks=self.mutation_user_stacks, + keepalive=list(self.keepalive), + save_for_backward=self.save_for_backward, + tensor_hooks=self.tensor_hooks, + ) + + def __contains__(self, item: object) -> bool: + return id(item) in self.id_to_variable + + def __getitem__(self, item: object) -> VariableTracker: + return self.id_to_variable[id(item)] + + def should_allow_externally_visible_side_effects_in_subtracer(self) -> bool: + output_graph = self.output_graph_weakref() + return bool( + output_graph + and output_graph.current_tx.output.current_tracer.unsafe_allow_externally_visible_side_effects + ) + + def should_allow_side_effects_in_hop(self) -> bool: + output_graph = self.output_graph_weakref() + return bool( + output_graph + and output_graph.current_tx.output.current_tracer.allow_side_effects_in_hop + ) + + def is_reconstructing_generator(self) -> bool: + output_graph = self.output_graph_weakref() + + return bool( + output_graph + and output_graph.current_tx.output.current_tracer.is_reconstructing_generator + ) + + def _maybe_record_side_effect(self, item: VariableTracker) -> None: + """Record the first externally-visible side effect on the current tracer.""" + if item.mutation_type is not None and not is_side_effect_safe( + item.mutation_type + ): + output_graph = self.output_graph_weakref() + if output_graph: + tracer = output_graph.current_tx.output.current_tracer + if tracer.side_effect_stack is None: + tracer.side_effect_stack = ( + torch._guards.TracingContext.extract_stack() + ) + + def check_allowed_side_effect(self, item: VariableTracker) -> bool: + from torch._dynamo.variables.misc import AutogradFunctionContextVariable + + # People do things like self.dim = dim inside autograd.Function. + # These are benign. + if isinstance(item, AutogradFunctionContextVariable): + return True + if self.should_allow_externally_visible_side_effects_in_subtracer(): + self._maybe_record_side_effect(item) + return True + if self.should_allow_side_effects_in_hop(): + self._maybe_record_side_effect(item) + return True + if self.is_reconstructing_generator(): + # This is missing the case where one mutates a tensor. See + # test_generator.py::test_reconstruct_generator_tensor_mutation + unimplemented( + gb_type="Generator reconstruction with mutations", + context=f"mutating object: {item}", + explanation="Cannot reconstruct a generator with variable mutations. " + "Dynamo needs to fully exhaust the generator, which may cause " + "unintended variable modifications.", + hints=[ + "Remove mutations from the generator.", + *graph_break_hints.FUNDAMENTAL, + ], + ) + if item.mutation_type is None: + raise AssertionError( + f"mutation_type is None for {item} in check_allowed_side_effect" + ) + if not is_side_effect_safe(item.mutation_type): + unimplemented( + gb_type="HOP: Unsafe side effect", + context=f"Attempted to mutate {item}", + explanation="Mutating a variable from outside the scope of this HOP is not supported.", + hints=[ + "If the HOP is activation checkpointing (torch.utils.checkpoint.checkpoint), this points to a " + "side effect in forward method. Eager activation checkpointing replays that side-effect while " + "recomputing the forward in the backward. If you are ok with side-effect not replayed in the " + "backward, try setting `torch._dynamo.config.skip_fwd_side_effects_in_bwd_under_checkpoint = True`", + ], + ) + return False + + def store_attr( + self, + item: VariableTracker, + name: str, + value: VariableTracker, + mutation_kind: AttrMutationKind = AttrMutationKind.GENERIC_SETATTR, + mutated_source: Source | None = None, + ) -> None: + if not self.is_attribute_mutation(item): + raise AssertionError( + f"Expected attribute mutation for {item} in store_attr" + ) + # For constant attribute mutations on outer-scope objects, defer + # the side-effect check and validate after tracing that the + # mutation was nullified (value restored to original). + deferred = False + if ( + isinstance(item.mutation_type, AttributeMutationExisting) + and not is_side_effect_safe(item.mutation_type) + and not isinstance(item, AutogradFunctionContextVariable) + and not self.should_allow_side_effects_in_hop() + and not self.should_allow_externally_visible_side_effects_in_subtracer() + and value.is_python_constant() + ): + deferred = self.snapshot_attr_mutation(item, name, value) + if not deferred: + self.check_allowed_side_effect(item) + if item not in self.store_attr_mutations: + self.store_attr_mutations[item] = {} + if item not in self.attr_mutation_kinds: + self.attr_mutation_kinds[item] = {} + self.store_attr_mutations[item][name] = value + self.attr_mutation_kinds[item][name] = mutation_kind + # Capture user stack for this mutation + self._capture_user_stack(item) + if mutated_source is not None: + self.mutated_sources.add(mutated_source) + else: + item_source = getattr(item, "source", None) + if item_source is not None: + self.mutated_sources.add(AttrSource(item_source, name)) + + def store_instance_dict_attr( + self, item: VariableTracker, name: str, value: VariableTracker + ) -> None: + # `obj.__dict__` ordering is observable (e.g. list(obj.__dict__)). When a + # key is re-added after being deleted, CPython appends it at the end + # rather than reusing its old slot. store_attr_mutations is an + # insertion-ordered dict, so a plain re-store of an existing key would + # keep the stale position; drop the deleted entry first so the new value + # re-inserts at the end. + if not isinstance(value, variables.DeletedVariable): + existing = self.store_attr_mutations.get(item, {}).get(name) + if isinstance(existing, variables.DeletedVariable): + # store_attr always writes both maps together, so the + # attr_mutation_kinds entry is guaranteed present here; use del + # for both to surface any invariant violation. + del self.store_attr_mutations[item][name] + del self.attr_mutation_kinds[item][name] + self.store_attr(item, name, value, AttrMutationKind.INSTANCE_DICT) + + def get_attr_mutation_kind( + self, item: VariableTracker, name: str + ) -> AttrMutationKind: + if name not in self.store_attr_mutations.get(item, ()): + return AttrMutationKind.GENERIC_SETATTR + if name not in self.attr_mutation_kinds.get(item, ()): + raise AssertionError(f"Missing attribute mutation kind for {item}.{name}") + return self.attr_mutation_kinds[item][name] + + def load_attr( + self, + item: VariableTracker, + name: str, + deleted_ok: bool = False, + check: bool = False, + ) -> VariableTracker: + if check: + if not self.is_attribute_mutation(item): + raise AssertionError( + f"Expected attribute mutation for {item} in load_attr" + ) + result = self.store_attr_mutations[item][name] + if not deleted_ok and isinstance(result, variables.DeletedVariable): + unimplemented( + gb_type="Attempted to read a deleted variable", + context=f"item: {item}, name: {name}", + explanation="", + hints=[*graph_break_hints.USER_ERROR], + ) + return result + + def store_cell(self, cellvar: VariableTracker, value: VariableTracker) -> None: + if cellvar.is_immutable(): + unimplemented( + gb_type="Write to immutable cell", + context=f"cellvar: {cellvar}, value: {value}", + explanation="Dynamo doesn't support writing to immutable/sourceless cell variables.", + hints=[*graph_break_hints.DIFFICULT], + ) + if not isinstance(cellvar, variables.CellVariable): + raise AssertionError( + f"Expected CellVariable, got {type(cellvar)} in store_cell" + ) + if not isinstance(value, variables.VariableTracker): + raise AssertionError( + f"Expected VariableTracker, got {type(value)} in store_cell" + ) + self.store_attr(cellvar, "cell_contents", value) + + def load_cell(self, cellvar: VariableTracker) -> VariableTracker: + if not isinstance(cellvar, variables.CellVariable): + raise AssertionError( + f"Expected CellVariable, got {type(cellvar)} in load_cell" + ) + # Track the cell_contents source during subgraph tracing so that + # mutations (e.g. nonlocal counter = 3) are detected by the reuse + # mechanism via set intersection with mutated_sources. + output_graph = self.output_graph_weakref() + if output_graph: + cell_source = getattr(cellvar, "source", None) + if cell_source is not None: + output_graph.current_tx.output.current_tracer.traced_sources.add( + AttrSource(cell_source, "cell_contents") + ) + if self.has_pending_mutation_of_attr(cellvar, "cell_contents"): + return self.load_attr(cellvar, "cell_contents", check=False) + if cellvar.pre_existing_contents: + return cellvar.pre_existing_contents + unimplemented( + gb_type="Read uninitialized cell", + context=str(cellvar), + explanation="Attempted to read a cell variable that has not been populated yet.", + hints=[*graph_break_hints.USER_ERROR], + ) + + def load_global(self, gvar: VariableTracker, name: str) -> VariableTracker: + if not isinstance(gvar, variables.VariableTracker): + raise AssertionError( + f"Expected VariableTracker, got {type(gvar)} in load_global" + ) + # This path serves the read out of side effects, bypassing + # VariableBuilder, so record the source here the way load_cell does -- + # otherwise a subgraph reading a rebound global has no traced source to + # intersect with mutated_sources and is wrongly considered reusable. + output_graph = self.output_graph_weakref() + if output_graph: + output_graph.current_tx.output.current_tracer.traced_sources.add( + GlobalSource(name) + ) + return self.load_attr(gvar, name) + + def store_global( + self, gvar: VariableTracker, name: str, value: VariableTracker + ) -> None: + if not isinstance(gvar, variables.VariableTracker): + raise AssertionError( + f"Expected VariableTracker for gvar, got {type(gvar)} in store_global" + ) + if not isinstance(value, variables.VariableTracker): + raise AssertionError( + f"Expected VariableTracker for value, got {type(value)} in store_global" + ) + # gvar is a per-global sentinel holder whose own source already names + # the global, so store_attr's default AttrSource(item.source, name) + # would name a nonexistent `G.G`. Record the source readers actually + # use, so mutated_sources intersects with traced_sources. + self.store_attr(gvar, name, value, mutated_source=GlobalSource(name)) + + @staticmethod + def cls_supports_mutation_side_effects(cls: type) -> bool: + return inspect.getattr_static(cls, "__getattribute__", None) in ( + object.__getattribute__, + dict.__getattribute__, + set.__getattribute__, + frozenset.__getattribute__, + int.__getattribute__, + str.__getattribute__, + list.__getattribute__, + tuple.__getattribute__, + collections.deque.__getattribute__, + BaseException.__getattribute__, + ) + + def is_attribute_mutation(self, item: VariableTracker) -> bool: + return isinstance(item.mutation_type, AttributeMutation) + + def has_pending_mutation(self, item: VariableTracker) -> bool: + return self.is_attribute_mutation(item) and bool( + self.store_attr_mutations.get(item) + ) + + def has_pending_mutation_of_attr( + self, + item: VariableTracker, + name: str, + mutation_kinds: AttrMutationKind | tuple[AttrMutationKind, ...] | None = None, + ) -> bool: + if not ( + self.is_attribute_mutation(item) + and name in self.store_attr_mutations.get(item, ()) + ): + return False + if mutation_kinds is None: + return True + mutation_kind = self.get_attr_mutation_kind(item, name) + if isinstance(mutation_kinds, AttrMutationKind): + return mutation_kind is mutation_kinds + return mutation_kind in mutation_kinds + + def is_modified(self, item: VariableTracker) -> bool: + if item.is_immutable(): + return False + if isinstance(item.mutation_type, (AttributeMutationNew, ValueMutationNew)): + return True + + if isinstance(item, variables.UserDefinedObjectVariable): + # Checks if the underlying dict or tuple vt has been modified + return item in self.store_attr_mutations or item.is_base_vt_modified(self) + + if self.is_attribute_mutation(item): + return item in self.store_attr_mutations + if item.mutation_type is None: + raise AssertionError(f"mutation_type is None for {item} in is_modified") + return item.mutation_type.is_modified # type: ignore[attr-defined] + + def _track_obj( + self, + item: object, + variable: VariableTracker, + mutation_type_cls: type = ValueMutationExisting, + ) -> VariableTracker: + """Start tracking an existing or new variable for mutation""" + if id(item) in self.id_to_variable: + raise AssertionError( + f"{variable} is already tracked for mutation. This could be " + "because you are not using VariableBuilder to construct " + "the variable tracker. " + f"Source of new object: {variable.source}. " + f"Source of previously tracked object: {self.id_to_variable[id(item)].source}." + ) + + variable.mutation_type = mutation_type_cls() + self.id_to_variable[id(item)] = variable + self.keepalive.append(item) + return variable + + track_mutable = _track_obj + + def track_object_existing( + self, + item: object, + variable: VariableTracker, + ) -> VariableTracker: + # TODO: Modify this API so that we preserve type info of + # variable + return self._track_obj( + item, + variable, + mutation_type_cls=AttributeMutationExisting, + ) + + def track_attribute_mutation_new(self, variable: VariableTracker) -> None: + """Register a sourceless VT (e.g. a synthetic exception) as a new + attribute-mutation object so its attribute mutations are codegen'd. + Keyed by the VT's id since there is no backing Python object.""" + if id(variable) in self.id_to_variable: + return + variable.mutation_type = AttributeMutationNew() + self.id_to_variable[id(variable)] = variable + self.keepalive.append(variable) + + def track_object_new( + self, + cls_source: Source | None, + user_cls: Any, + variable_cls: Any, + options: dict[str, Any], + ) -> VariableTracker: + obj = object_new(user_cls) + variable = variable_cls( + obj, + mutation_type=AttributeMutationNew(cls_source), + **options, + ) + self.id_to_variable[id(obj)] = variable + self.keepalive.append(obj) + return variable + + def get_variable_cls(self, user_cls: type) -> type: + from torch.overrides import TorchFunctionMode + + from .variables.ctx_manager import GenericContextWrappingVariable + from .variables.torch_function import TorchFunctionModeVariable + from .variables.user_defined import is_generic_ctx_manager_cls + + variable_cls: type[variables.UserDefinedObjectVariable] = ( + variables.UserDefinedObjectVariable + ) + if issubclass( + user_cls, TorchFunctionMode + ) and TorchFunctionModeVariable.is_supported_torch_function_mode(user_cls): + variable_cls = TorchFunctionModeVariable + elif is_generic_ctx_manager_cls(user_cls): + variable_cls = GenericContextWrappingVariable + elif issubclass(user_cls, torch.nn.Module): + variable_cls = variables.UnspecializedNNModuleVariable + elif issubclass(user_cls, collections.defaultdict): + variable_cls = variables.DefaultDictVariable + elif issubclass(user_cls, dict): + # Includes collections.OrderedDict and its subclasses; the + # UserDefinedDictVariable picks an OrderedDict-backed store. + variable_cls = variables.UserDefinedDictVariable + elif issubclass(user_cls, (set, frozenset)): + variable_cls = variables.UserDefinedSetVariable + elif issubclass(user_cls, tuple): + if is_namedtuple_cls(user_cls): + variable_cls = variables.UserDefinedTupleVariable.get_vt_cls(user_cls) + else: + variable_cls = variables.UserDefinedTupleVariable + elif issubclass(user_cls, list): + variable_cls = variables.UserDefinedListVariable + elif issubclass(user_cls, collections.deque): + variable_cls = variables.UserDefinedDequeVariable + elif issubclass(user_cls, MutableMapping): + variable_cls = variables.MutableMappingVariable + elif is_frozen_dataclass(user_cls): + variable_cls = FrozenDataClassVariable + elif issubclass(user_cls, BaseException): + variable_cls = variables.UserDefinedExceptionObjectVariable + elif issubclass( + user_cls, + variables.user_defined._CONSTANT_BASE_TYPES, + ): + variable_cls = variables.UserDefinedConstantVariable + elif variables.InspectVariable.is_matching_class(user_cls): + variable_cls = variables.InspectVariable + if not issubclass(variable_cls, variables.UserDefinedObjectVariable): + raise AssertionError( + f"Expected subclass of UserDefinedObjectVariable, got {variable_cls}" + ) + return variable_cls + + def get_example_value( + self, + base_cls_vt: VariableTracker, + cls_vt: VariableTracker, + init_args: list[VariableTracker], + ) -> Any: + user_cls = cls_vt.value # type: ignore[attr-defined] + if issubclass(user_cls, torch.nn.Module): + # TODO(anijain2305) - Is it possible to remove this specialization? + obj = nn_module_new(user_cls) + else: + if isinstance(base_cls_vt, variables.BuiltinVariable): + base_cls = base_cls_vt.fn + elif isinstance(base_cls_vt, variables.DictBuiltinVariable): + base_cls = dict + elif isinstance(base_cls_vt, variables.ListBuiltinVariable): + base_cls = list + elif isinstance(base_cls_vt, variables.UserDefinedClassVariable): + base_cls = base_cls_vt.value + else: + raise RuntimeError(f"Unexpected base_cls_vt {base_cls_vt}") + + if not variables.UserDefinedClassVariable.is_supported_new_method( + base_cls.__new__ + ): + raise AssertionError(f"Unsupported __new__ method for {base_cls}") + if is_structseq_class(user_cls): + # Structseq tp_new requires a sequence argument and rejects + # tuple.__new__, so create a dummy with None placeholders. + obj = user_cls([None] * user_cls.n_fields) + elif init_args and issubclass( + user_cls, + variables.user_defined._CONSTANT_BASE_TYPES, + ): + example_args = [arg.as_python_constant() for arg in init_args] + try: + obj = base_cls.__new__( # pyrefly: ignore[bad-specialization] + user_cls, *example_args + ) + except Exception: + # __new__ can raise (e.g., exceeding int str digit limits). + # Fall back to creating without args — the example value is + # only used for tracing, not for correctness. + obj = base_cls.__new__( # pyrefly: ignore[bad-specialization] + user_cls + ) + else: + try: + obj = base_cls.__new__(user_cls) + except TypeError as exc: + # Backstop for direct construction paths that bypass the + # UserDefinedClassVariable object.__new__ preflight. + unimplemented( + gb_type="Unsupported user-defined object construction during side-effect tracking", + context=f"class={user_cls}, base={base_cls}, error={exc}", + explanation=( + "Dynamo could not construct an example object for " + "side-effect replay using the class __new__ method." + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + return obj + + def track_new_user_defined_object( + self, + base_cls_vt: VariableTracker, + cls_vt: VariableTracker, + init_args: list[VariableTracker], + *, + tx: "InstructionTranslatorBase | None" = None, + ) -> VariableTracker: + """ + Creates a UserDefinedObjectVariable (or its subclass) variable tracker + and mark it for attribute mutation tracking. + + Also records the variable trackers to call __new__ method on + reconstruction. Roughly, the reconstruction looks like this + base_cls_vt.__new__(user_cls, *init_args) + """ + cls_source = cls_vt.source + user_cls = cls_vt.value # type: ignore[attr-defined] + variable_cls = self.get_variable_cls(user_cls) + obj = self.get_example_value(base_cls_vt, cls_vt, init_args) + + kwargs: dict[str, Any] = {} + if tx is not None: + kwargs["tx"] = tx + variable = variable_cls( + obj, + cls_source=cls_vt.source, + base_cls_vt=base_cls_vt, + init_args=init_args, + mutation_type=AttributeMutationNew(cls_source), + **kwargs, + ) + self.id_to_variable[id(obj)] = variable + self.keepalive.append(obj) + return variable + + def track_cell_new( + self, + ) -> VariableTracker: + obj = object() + variable = variables.CellVariable( + mutation_type=AttributeMutationNew(), + ) + self.id_to_variable[id(obj)] = variable + self.keepalive.append(obj) + return variable + + def track_cell_existing( + self, source: Source | None, cell: CellType, contents: VariableTracker + ) -> VariableTracker: + variable = variables.CellVariable( + # We don't support mutation to cell without source because we need + # source to properly codegen the mutations. + mutation_type=None if source is None else AttributeMutationExisting(), + pre_existing_contents=contents, + source=source, + ) + self.id_to_variable[id(cell)] = variable + self.keepalive.append(cell) + return variable + + def track_global_existing(self, source: Source, item: object) -> VariableTracker: + variable = variables.NewGlobalVariable( + mutation_type=AttributeMutationExisting(), + source=source, + ) + self.id_to_variable[id(item)] = variable + self.keepalive.append(item) + return variable + + def track_save_for_backward( + self, ctx: VariableTracker, args: list[VariableTracker] + ) -> None: + if not isinstance(ctx, variables.AutogradFunctionContextVariable): + raise AssertionError( + f"Expected AutogradFunctionContextVariable, got {type(ctx)}" + ) + self.save_for_backward.append((ctx, args)) + + def track_runahead_tensor_and_symvar_side_effects( + self, other: "SideEffects" + ) -> None: + # In higher order ops we want to keep track of tensors seen in the + # speculate_subgraph so that we don't lift them again as a new input in + # other speculate_subgraph or in the root tracer. + for other_item in other.keepalive: + other_id = id(other_item) + other_variable = other.id_to_variable[other_id] + if other_id not in self.id_to_variable and isinstance( + other_variable, (variables.TensorVariable, variables.SymNodeVariable) + ): + self.track_object_existing(other_item, other_variable) + + def prune_dead_object_new(self, tx: "InstructionTranslatorBase") -> None: + # Avoid VT cycles from e.g., recursive function. + visited: set[VariableTracker] = set() + live_new_objects: set[VariableTracker] = set() + + def visit(var: VariableTracker) -> None: + if var in visited: + return + visited.add(var) + # Object may have been mutated, store this mutation. + if isinstance(var.mutation_type, AttributeMutationNew): + live_new_objects.add(var) + # It's possible that we have mutated the value of this variable + # to be another one. The new value is in store_attr_mutations. + # Also recurse through the new value to detect alive AttributeMutationNew. + if var in self.store_attr_mutations: + VariableTracker.visit( + visit, # noqa: F821 + self.store_attr_mutations[var], + ) + + def is_live(var: VariableTracker) -> bool: + if isinstance(var.mutation_type, AttributeMutationNew): + return var in live_new_objects + return True + + pre_existing_vars = [ + var + for var in self.id_to_variable.values() + if not isinstance(var.mutation_type, AttributeMutationNew) + ] + + # The only live side effects come from returns (tx.stack), any intermediates + # during a graph break (tx.symbolic_locals), and mutation on pre-existing variables. + # Recursively visit Variables and see if any of them have been mutated. + init_live_vars = [] + # gather stack/symbolic_locals for all tx's up the chain + cur_tx: InstructionTranslatorBase | None = tx + while cur_tx is not None: + init_live_vars.extend([cur_tx.stack, cur_tx.symbolic_locals]) + if cur_tx.parent is not None: + # for non-root tx'es, also keep the cells/freevars alive so they get codegen'd properly + # TODO see if we could prune dead cells - cell pruning information needs to be forwarded + # to the resume function creation as well. + if cur_tx.post_prune_cell_and_freevars is None: + raise AssertionError( + "post_prune_cell_and_freevars is None for non-root tx" + ) + init_live_vars.append(cur_tx.post_prune_cell_and_freevars) + cur_tx = cur_tx.parent + + # Generators tracked for close-on-exit have their close() called in + # compile_subgraph after pruning. + gen_reachable_new: set[VariableTracker] = set() + + def visit_gen(var: VariableTracker) -> None: + if isinstance(var.mutation_type, AttributeMutationNew): + gen_reachable_new.add(var) + + # Pass side_effects so the walk follows store_attr_mutations, and share + # one cache across all generators to dedup shared subiterators. + gen_visit_cache: dict[int, Any] = {} + for gen in tx.output.local_generators: + gen_tracer = gen.inline_tracer + VariableTracker.visit( + visit_gen, + [gen_tracer.stack, gen_tracer.symbolic_locals], + gen_visit_cache, + self, + ) + + VariableTracker.visit( + visit, + # TODO track from all possible sources. + init_live_vars + + [ + pre_existing_vars, + tx.output.backward_state, + self.tensor_hooks, + ], + ) + # Manually release the self-referential function, which indirectly + # captures certain `VariableTracker` and affects parts of PT test/logic + # that are sensitive to when certain objects get released. + del visit + + # NB: cell variable handling is tricky. + # cell variables must stay alive if any NestedUserFunctionVariable + # are live. "visit"-ing the NestedUserFunctionVariable visits + # the .closures field, from which we will see if we need to keep + # any mutations to cell variables alive. + + self.id_to_variable = { + k: v for k, v in self.id_to_variable.items() if is_live(v) + } + self.store_attr_mutations = { + k: v + for k, v in self.store_attr_mutations.items() + if is_live(k) or k in gen_reachable_new + } + self.attr_mutation_kinds = { + k: v + for k, v in self.attr_mutation_kinds.items() + if is_live(k) or k in gen_reachable_new + } + + def mutation(self, var: VariableTracker) -> None: + if var in self.ignore_mutation_on_these_variables: + return + + self.check_allowed_side_effect(var) + # Capture user stack for this mutation + self._capture_user_stack(var) + + if isinstance(var.mutation_type, ValueMutationExisting): + var.mutation_type.is_modified = True + if var.source is not None: + self.mutated_sources.add(var.source) + if var.source and isinstance(var, variables.ConstDictVariable): + self._has_existing_dict_mutation = True + + def has_existing_dict_mutation(self) -> bool: + return self._has_existing_dict_mutation + + def _get_modified_vars(self) -> list[VariableTracker]: + return [var for var in self.id_to_variable.values() if self.is_modified(var)] + + def codegen_save_tempvars(self, cg: PyCodegen) -> None: + # We must codegen modified VT to their source by default, so that + # mutation and aliasing are properly accounted for. + # + # Since newly constructed objects don't have a source, we manually + # codegen their construction and store them to a newly assigned local + # source. Note that `ValueMutationNew` isn't tracked by SideEffects. + for var in self._get_modified_vars(): + if not isinstance(var.mutation_type, AttributeMutationNew): + if var.source is None: + raise AssertionError( + f"Expected source for modified var {var} " + "with non-new mutation type" + ) + continue + + # Namedtuples/structseqs with no pending mutations should skip + # codegen_save_tempvars so that restore_stack handles them. In + # export, restore_stack uses value_from_source=False which makes + # child tensors become graph outputs. If we processed them here, + # add_cache would assign a TempLocalSource and restore_stack would + # load from cache with value_from_source=True, hiding the tensors + # from export. + if isinstance( + var, + (variables.NamedTupleVariable, variables.StructSequenceVariable), + ) and not self.has_pending_mutation(var): + continue + + # Sourceless enum members registered with AttributeMutationNew + # don't need __new__-based tempvar reconstruction -- they are + # reconstructible as constants. + if ( + var.is_python_constant() + and isinstance(var.mutation_type, AttributeMutationNew) + and isinstance(var, variables.UserDefinedObjectVariable) + and ( + isinstance( + var.value, + ( + enum.Enum, + torch.DispatchKey, + torch._C._functorch.TransformType, + ), + ) + or is_pybind11_enum_member(var.value) + ) + ): + continue + + if isinstance(var, variables.CellVariable): + # Cells created in the root frame are created either by + # `MAKE_CELL` or by them being in `co_cellvars`, so we only emit + # `make_cell` for the non-root-frame cells here. + # TODO generalize this so we never need to call `make_cell`. + if var.local_name is None: + cg.add_push_null( + lambda: cg.load_import_from(utils.__name__, "make_cell") + ) + cg.extend_output(create_call_function(0, False)) + cg.add_cache(var) + var.source = TempLocalSource(cg.tempvars[var]) # type: ignore[attr-defined] + elif var.source is None: + var.source = LocalCellSource(var.local_name) + elif var.is_tensor(): + # NOTE: for historical reasons we never assigned local sources + # to newly constructed tensor object, so we keep it that way. + # They are always loaded from output of the fx graph, so one can + # think of it as having a "OutputGraphSource" for codegen + # purposes. + # + # However, tensor subclass objects are different, because the + # reconstruction logic in `PyCodegen` loads the data tensor from + # graph output and then calls `as_subclass`, meaning we must + # assign a source to it to ensure we only reconstruct one + # subclass instance. + if isinstance( + var, variables.torch_function.TensorWithTFOverrideVariable + ): + # Don't codegen from temp source assigned from the 1st pass. + cg(var, allow_cache=False) + cg.add_cache(var) + # `add_cache` generates STORE and consumes TOS, but we never + # cleared it. TODO move this call into `add_cache` + cg.clear_tos() + var.source = TempLocalSource(cg.tempvars[var]) + elif isinstance(var, variables.AutogradFunctionContextVariable): + unimplemented( + gb_type="AutogradFunctionContextVariable escaped Dynamo-traced region", + context="", + explanation="We cannot reconstruct a torch.autograd.Function's context object.", + hints=[], + ) + elif isinstance(var, variables.ExceptionVariable): + # Exceptions cannot be built via object.__new__ (CPython rejects + # it), so reconstruct() constructs by calling the type. Cache + # the result so later references load the single instance; any + # __dict__ attributes replay in codegen_update_mutated. + var.reconstruct(cg) + cg.add_cache(var) + var.source = TempLocalSource(cg.tempvars[var]) + else: + # Reconstruct the bytecode for + # base_cls.__new__(user_cls, *args) + if isinstance(var, variables.UserDefinedObjectVariable): + + def load_new_method() -> None: + # pyrefly: ignore [missing-attribute] + if var.base_cls_vt is None: + raise AssertionError( + "base_cls_vt is None in load_new_method" + ) + cg(var.base_cls_vt) # type: ignore[attr-defined] + cg.extend_output([cg.create_load_attr("__new__")]) + + cg.add_push_null(load_new_method) + else: + cg.add_push_null( + lambda: cg.load_import_from(utils.__name__, "object_new") + ) + if var.mutation_type.cls_source is None: + unimplemented( + gb_type="Reconstruct user defined class without a source", + context=f"Class: {var.python_type().__name__}", + explanation=( + f"Cannot reconstruct an instance of {var.python_type().__name__} " + "that escapes the compiled region. This happens when the class is " + "defined dynamically (e.g., inside the compiled function) and the " + "class object itself has no source that can be reconstructed. " + "To fix this, move the class definition outside the compiled function " + "or prevent the object from escaping the compiled region." + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + cg(var.mutation_type.cls_source) + + # Generate the args to the __new__ method + for arg in var.init_args: # type: ignore[attr-defined] + cg(arg) + + # Call the __new__ method + cg.extend_output(create_call_function(1 + len(var.init_args), False)) # type: ignore[attr-defined] + + cg.add_cache(var) + var.source = TempLocalSource(cg.tempvars[var]) + + # For frozen dataclasses, we must emit object.__setattr__ + # immediately after __new__ — before any other code can + # access the object. The suffix-based codegen in + # codegen_update_mutated runs too late: if intervening code + # calls __repr__ (e.g. f-strings), the attributes won't be + # set yet. + if ( + isinstance(var, variables.FrozenDataClassVariable) + and var in self.store_attr_mutations + ): + for name, value in self.store_attr_mutations[var].items(): + cg.load_import_from("builtins", "object") + cg.load_method("__setattr__") + cg(var.source) + cg(variables.ConstantVariable(name)) + cg(value) + cg.extend_output( + [*create_call_method(3), create_instruction("POP_TOP")] + ) + + for ctx, args in self.save_for_backward: + cg(ctx.source) + cg.load_method("save_for_backward") + for arg in args: + cg(arg) + cg.extend_output( + [ + *create_call_method(len(args)), + create_instruction("POP_TOP"), + ] + ) + + def register_hook( + self, + tensor: "variables.TensorVariable", + hook: VariableTracker, + handle: "variables.RemovableHandleVariable", + name: str, + ) -> None: + if not tensor.is_tensor(): + raise AssertionError( + f"Expected tensor variable, got {type(tensor)} in register_hook" + ) + if not isinstance(hook, variables.VariableTracker): + raise AssertionError(f"Expected VariableTracker for hook, got {type(hook)}") + if not isinstance(handle, variables.RemovableHandleVariable): + raise AssertionError( + f"Expected RemovableHandleVariable, got {type(handle)}" + ) + if not handle.is_mutable(): + raise AssertionError("handle must be mutable in register_hook") + if not hasattr(torch.Tensor, name): + raise AssertionError(f"torch.Tensor has no attribute '{name}'") + idx = len(self.tensor_hooks.keys()) + # duplicate index possible because of self.remove_hook() + while idx in self.tensor_hooks: + idx += 1 + self.tensor_hooks[idx] = (tensor, hook, handle, name) + if handle.idx: + raise AssertionError(f"handle.idx should be falsy, got {handle.idx}") + handle.idx = idx + + def remove_hook(self, idx: int) -> None: + del self.tensor_hooks[idx] + + def codegen_hooks(self, cg: PyCodegen) -> None: + for ( + tensor, + hook, + handle, + name, + ) in self.tensor_hooks.values(): + # Note: [On tensor.register_hook] + # + # register_hook on a tensor, AKA backward hooks, have slightly nuanced differences in how they are implemented + # when it comes to hooks on objects with sources (inputs, params) vs objects without sources (intermediaries). + # + # For tensors with a source, we bypass direct inclusion of register_hook calls in the graph. + # Instead, these are tracked and stashed as a global variable, enabling their association with tensors in + # the residuals. During dynamo's frame creation, these hooks are invoked seamlessly on known reconstructible/fetch-able + # tensors. Because a source indicates knowledge of this object outside the torch compile region, and + # because we are running residuals firmly before .backward() can be run, it is sound to invoke + # `register_hook` on a known tensor. + # + # For tensors without a source, we support a limited subset of hooks. Global functions only, and + # compiled_autograd must be enabled or we will graph break. + # + # Handling the Handle: When a user retains the register_hook result in a handle, we intercept the + # STORE_FAST operation to record the user-designated local variable name. This ensures the reconstructed + # bytecode retains this name. If no handle is defined, we simply pop the generated value to keep the + # stack intact. + # + # Dynamo Tensor Hooks Workflow: + # - Functions passed to register_hook are lifted globally. + # - For tensors with sources: + # - In the "side_effects" phase of codegen, we iterate over tensors with hooks to: + # - Generate the tensor. + # - Issue a register_hook call on the tensor, linking to the globally stored function. + # - Incorporate a handle if one was established in the eager phase. + # - For tensors without sources: + # - We don't generate any instructions for registering a hook. + # - Handles from intermediary hooks are NYI. + # - We produce a call function that utilizes the trace_wrapped higher order op, closing over it. + # - We then manually insert the call function above into the graph. + # - The handle's exact user-specified name, "user_code_variable_name", is discerned and associated during STORE_FAST. + if not tensor.source: + raise AssertionError( + "Hooks on non input tensors NYI - should not get here" + ) + + def gen_fn() -> None: + cg(tensor) + cg.extend_output([cg.create_load_attr(name)]) + + cg.add_push_null(gen_fn) + cg(hook) + cg.extend_output(create_call_function(1, False)) + + # Adding the handle to the cache means RemovableHandleVariable().reconstruct() will + # be associated with the return value of register_hook(). This consumes the top of stack. + cg.add_cache(handle) + + def get_ca_final_callbacks_var(self) -> "variables.ListVariable": + from .variables.base import ValueMutationNew + + if self.ca_final_callbacks_var is None: + self.ca_final_callbacks_var = variables.ListVariable( + [], mutation_type=ValueMutationNew() + ) + + return self.ca_final_callbacks_var + + def _format_side_effect_message(self, var: VariableTracker) -> str: + """Format a side effect log message with user stack.""" + if config.side_effect_replay_policy == "silent": + raise AssertionError( + "_format_side_effect_message should not be called " + "when side_effect_replay_policy is 'silent'" + ) + locations = self.mutation_user_stacks.get(var, []) + description = f"Mutating object of type {var.python_type_name()}" + source_info = " (no source)" + if var.source is not None: + if isinstance(var.source, TempLocalSource): + source_info = " (source: created in torch.compile region)" + elif isinstance(var, variables.CellVariable) and var.local_name is not None: + source_info = f" (source: {var.local_name})" + elif isinstance( + var, variables.torch_function.TorchFunctionModeStackVariable + ): + source_info = " (source: torch function mode stack mutation)" + else: + # NOTE: NotImplementedError from var.source.name is a bug and must be fixed! + source_info = f" (source name: {var.source.name})" + + if locations: + # Format and dedupe stacks using tuple representation for efficiency + seen = set() + unique_formatted_stacks: list[str] = [] + stack_above_dynamo = collapse_resume_frames(get_stack_above_dynamo()) + for stack in locations: + # Use tuple of frame info for fast deduplication + # Include position info (colno, end_lineno, end_colno) to distinguish + # multiple mutations on the same line (when available in Python 3.11+) + stack_tuple = tuple( + ( + f.filename, + f.lineno, + f.name, + f.line, + getattr(f, "colno", None), + getattr(f, "end_lineno", None), + getattr(f, "end_colno", None), + ) + for f in stack + ) + if stack_tuple not in seen: + seen.add(stack_tuple) + stack_augmented = collapse_resume_frames(stack_above_dynamo + stack) + unique_formatted_stacks.append( + "".join(traceback.format_list(stack_augmented)) + ) + formatted_lines: str = "\n********\n\n".join(unique_formatted_stacks) + log_str = f"{description}{source_info}\n\n{textwrap.indent(formatted_lines, ' ')}" + else: + log_str = ( + f"{description}{source_info} (unable to find user stacks for mutations)" + ) + + return log_str + + def _emit_side_effect_messages(self, side_effect_messages: list[str]) -> None: + if not side_effect_messages: + return + + for msg in side_effect_messages: + side_effects_log.debug(msg) + + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "dynamo_side_effects", + "encoding": "string", + }, + payload_fn=lambda: "\n\n========================================\n\n".join( + side_effect_messages + ), + ) + + def codegen_update_mutated( + self, cg: PyCodegen, log_side_effects: bool = False + ) -> None: + side_effect_messages: list[str] = [] + + # NOTE: should only be called once per VT - only if a side effect actually gets codegen'd! + def _maybe_log_side_effect(var: VariableTracker) -> None: + if config.side_effect_replay_policy != "silent" and log_side_effects: + msg = self._format_side_effect_message(var) + side_effect_messages.append(msg) + + suffixes: list[list[Instruction]] = [] + for var in self._get_modified_vars(): + # When replay_side_effects=False, only update variables with TempLocalSource + if not config.replay_side_effects and not isinstance( + var.source, TempLocalSource + ): + continue + + ctx = SideEffectReplayContext( + side_effects=self, + codegen=cg, + var=var, + suffixes=suffixes, + log=_maybe_log_side_effect, + ) + handler = _side_effect_replay_registry.lookup_handler(ctx) + if handler is None: + raise AssertionError(type(var)) + handler.codegen(ctx) + + # do all the actual mutations at the very end to handle dependencies + for suffix in reversed(suffixes): + cg.extend_output(suffix) + + # Send batched structured trace for all side effects in this compilation + if log_side_effects and side_effect_messages: + self._emit_side_effect_messages(side_effect_messages) + + def log_side_effects_summary(self) -> None: + if config.side_effect_replay_policy == "silent": + return + if not side_effects_log.isEnabledFor(logging.DEBUG): + return + for var in self._get_modified_vars(): + msg = self._format_side_effect_message(var) + side_effects_log.debug(msg) + + def is_empty(self) -> bool: + return not ( + any(map(self.is_modified, self.id_to_variable.values())) + or self.tensor_hooks + or self.save_for_backward + or self.tensor_hooks + ) + + def clear(self) -> None: + self.keepalive.clear() + self.id_to_variable.clear() + + +@register_side_effect_replay_handler( + name="list_mutation", + matcher=lambda ctx: isinstance(ctx.var, variables.ListVariable), + priority=90, +) +def _codegen_list_mutation(ctx: SideEffectReplayContext) -> None: + cg = ctx.codegen + var = ctx.var + if not isinstance(var, variables.ListVariable): + raise AssertionError(type(var)) + # old[:] = new + cg(var, allow_cache=False) # Don't codegen via source + cg(var.source) # type: ignore[attr-defined] + cg.extend_output( + [ + cg.create_load_const(None), + cg.create_load_const(None), + create_instruction("BUILD_SLICE", arg=2), + ] + ) + ctx.suffixes.append([create_instruction("STORE_SUBSCR")]) + ctx.log(var) + + +@register_side_effect_replay_handler( + name="deque_mutation", + matcher=lambda ctx: isinstance(ctx.var, variables.lists.DequeVariable), + priority=80, +) +def _codegen_deque_mutation(ctx: SideEffectReplayContext) -> None: + cg = ctx.codegen + var = ctx.var + if not isinstance(var, variables.lists.DequeVariable): + raise AssertionError(type(var)) + # For limited maxlen, the order of operations matter for side effect, but we + # currently don't track the order, so no support. + if not var.maxlen.is_constant_none(): + unimplemented( + gb_type="Side effect on existing deque with limited maxlen", + context="", + explanation="This is not supported.", + hints=[ + "Don't use a deque with `maxlen` specified.", + ], + ) + + # old.extend(new), this runs last + cg(var.source) + cg.load_method("extend") + cg(var, allow_cache=False) # Don't codegen via source + ctx.suffixes.append( + [ + *create_call_method(1), + create_instruction("POP_TOP"), + ] + ) + + # old.clear(), this runs first + cg(var.source) + cg.load_method("clear") + ctx.suffixes.append( + [ + *create_call_method(0), + create_instruction("POP_TOP"), + ] + ) + ctx.log(var) + + +@register_side_effect_replay_handler( + name="const_dict_or_set_mutation", + matcher=lambda ctx: isinstance( + ctx.var, (variables.ConstDictVariable, variables.SetVariable) + ), + priority=70, +) +def _codegen_const_dict_or_set_mutation(ctx: SideEffectReplayContext) -> None: + cg = ctx.codegen + var = ctx.var + if not isinstance(var, (variables.ConstDictVariable, variables.SetVariable)): + raise AssertionError(type(var)) + # Reconstruct works as follow: + # (1) Skip codegen if there are no new items + # (2) codegen(...) each pair of key/value + # (3) create a new dictionary with the pairs of key/values above + # (4) clear the original dictionary + # + only if a key was removed from the input dict + # (5) update the original dictionary with the dict created in (2) + if var.has_new_items(): + cg(var.source) # type: ignore[attr-defined] + cg.load_method("update") + cg(var, allow_cache=False) # Don't codegen via source + + if var.should_reconstruct_all: + cg(var.source) # type: ignore[attr-defined] + cg.load_method("clear") + + ctx.suffixes.append( + [ + *create_call_method(1), # update + create_instruction("POP_TOP"), + ] + ) + + if var.should_reconstruct_all: + # clear will appear before "update" as the suffixes are applied in + # reverse order. + ctx.suffixes.append( + [ + *create_call_method(0), # clear + create_instruction("POP_TOP"), + ] + ) + ctx.log(var) + + +@register_side_effect_replay_handler( + name="torch_function_mode_stack_mutation", + matcher=lambda ctx: isinstance( + ctx.var, variables.torch_function.TorchFunctionModeStackVariable + ), + priority=60, +) +def _codegen_torch_function_mode_stack_mutation( + ctx: SideEffectReplayContext, +) -> None: + cg = ctx.codegen + var = ctx.var + if not isinstance(var, variables.torch_function.TorchFunctionModeStackVariable): + raise AssertionError(type(var)) + cg.add_push_null( + lambda: cg.load_import_from(utils.__name__, "set_torch_function_mode_stack") + ) + + cg.foreach(var.symbolic_stack) + cg.append_output(create_instruction("BUILD_LIST", arg=len(var.symbolic_stack))) + cg.call_function(1, False) + cg.append_output(create_instruction("POP_TOP")) + ctx.log(var) + + +@register_side_effect_replay_handler( + name="cell_mutation", + matcher=lambda ctx: isinstance(ctx.var, variables.CellVariable) + and ctx.var.local_name is not None, + priority=50, +) +def _codegen_cell_mutation(ctx: SideEffectReplayContext) -> None: + cg = ctx.codegen + var = ctx.var + if not isinstance(var, variables.CellVariable): + raise AssertionError(type(var)) + if var.local_name is None: + raise AssertionError("cell mutation local name must be set") + # Emit more readable and performant bytecode. + # TODO generalize this for cells created during inlining. + if var in ctx.side_effects.store_attr_mutations: + contents_var = ctx.side_effects.load_cell(var) + cg(contents_var) + ctx.suffixes.append([cg.create_store_deref(var.local_name)]) + ctx.log(var) + + +def _codegen_user_defined_dict_mutation(ctx: SideEffectReplayContext) -> None: + cg = ctx.codegen + var = ctx.var + if not isinstance(var, variables.UserDefinedDictVariable): + raise AssertionError(type(var)) + # Do dict related update manually here. The store_attr mutations will be + # applied later. + varname_map = {} + for name in _manual_dict_setitem.__code__.co_varnames: + varname_map[name] = cg.tx.output.new_var() + + try: + mro_index = type(var.value).__mro__.index(collections.OrderedDict) + except ValueError: + mro_index = type(var.value).__mro__.index(dict) + + cg.extend_output( + [ + create_instruction("LOAD_CONST", argval=mro_index), + create_instruction("STORE_FAST", argval=varname_map["mro_index"]), + ] + ) + + cg(var.source) # type: ignore[attr-defined] + cg.extend_output( + [ + create_instruction("STORE_FAST", argval=varname_map["dict_to"]), + ] + ) + + # Reconstruct all items - _manual_dict_setitem clears dict_to first, so we + # need every key/value, not just the ones that differ from original_items. + var._base_vt.should_reconstruct_all = True # type: ignore[union-attr] + cg(var._base_vt, allow_cache=False) # Don't codegen via source + cg.extend_output( + [ + create_instruction("STORE_FAST", argval=varname_map["dict_from"]), + ] + ) + + dict_update_insts = bytecode_from_template( + _manual_dict_setitem, varname_map=varname_map + ) + + ctx.suffixes.append( + [ + *dict_update_insts, + create_instruction("POP_TOP"), + ] + ) + ctx.log( + var._base_vt # pyrefly: ignore[bad-argument-type] + ) + + +def _codegen_user_defined_list_mutation(ctx: SideEffectReplayContext) -> None: + cg = ctx.codegen + var = ctx.var + if not isinstance(var, variables.UserDefinedListVariable): + raise AssertionError(type(var)) + # Update the list to the updated items. Be careful in calling the list + # methods and not the overridden methods. + varname_map = {} + for name in _manual_list_update.__code__.co_varnames: + varname_map[name] = cg.tx.output.new_var() + + cg(var.source) # type: ignore[attr-defined] + cg.extend_output( + [ + create_instruction("STORE_FAST", argval=varname_map["list_to"]), + ] + ) + + cg(var._base_vt, allow_cache=False) # Don't codegen via source + cg.extend_output( + [ + create_instruction("STORE_FAST", argval=varname_map["list_from"]), + ] + ) + + list_update_insts = bytecode_from_template( + _manual_list_update, varname_map=varname_map + ) + + ctx.suffixes.append( + [ + *list_update_insts, + create_instruction("POP_TOP"), + ] + ) + ctx.log( + var._base_vt # pyrefly: ignore[bad-argument-type] + ) + + +def _codegen_user_defined_deque_mutation(ctx: SideEffectReplayContext) -> None: + cg = ctx.codegen + var = ctx.var + if not isinstance(var, variables.UserDefinedDequeVariable): + raise AssertionError(type(var)) + # Update the deque to the updated items. Be careful in calling the deque + # methods and not the overridden methods. + varname_map = {} + for name in _manual_deque_update.__code__.co_varnames: + varname_map[name] = cg.tx.output.new_var() + + cg(var.source) # type: ignore[attr-defined] + cg.extend_output( + [ + create_instruction("STORE_FAST", argval=varname_map["deque_to"]), + ] + ) + + cg(var._base_vt, allow_cache=False) # Don't codegen via source + cg.extend_output( + [ + create_instruction("STORE_FAST", argval=varname_map["deque_from"]), + ] + ) + + deque_update_insts = bytecode_from_template( + _manual_deque_update, varname_map=varname_map + ) + + ctx.suffixes.append( + [ + *deque_update_insts, + create_instruction("POP_TOP"), + ] + ) + ctx.log( + var._base_vt # pyrefly: ignore[bad-argument-type] + ) + + +def _skip_attribute_mutation_replay(var: VariableTracker) -> bool: + # FrozenDataClassVariable attributes were emitted in codegen_save_tempvars + # right after __new__. Skip here to avoid double-emitting. + if isinstance(var.mutation_type, AttributeMutationNew) and isinstance( + var, variables.FrozenDataClassVariable + ): + return True + + # Sourceless enum members: mutations (like _inverted_ caching) already + # happened on the real object during tracing. + return ( + var.is_python_constant() + and isinstance(var.mutation_type, AttributeMutationNew) + and isinstance(var, variables.UserDefinedObjectVariable) + and ( + isinstance( + var.value, + ( + enum.Enum, + torch.DispatchKey, + torch._C._functorch.TransformType, + ), + ) + or is_pybind11_enum_member(var.value) + ) + ) + + +@register_side_effect_replay_handler( + name="attribute_mutation", + matcher=lambda ctx: ctx.side_effects.is_attribute_mutation(ctx.var), + priority=40, +) +def _codegen_attribute_mutation(ctx: SideEffectReplayContext) -> None: + cg = ctx.codegen + var = ctx.var + side_effects = ctx.side_effects + if _skip_attribute_mutation_replay(var): + return + + if ( + isinstance(var, variables.UserDefinedDictVariable) + and side_effects.is_modified( + var._base_vt # pyrefly: ignore[bad-argument-type] + ) + and var._base_vt.has_new_items() # type: ignore[union-attr] + ): + _codegen_user_defined_dict_mutation(ctx) + elif isinstance( + var, variables.UserDefinedListVariable + ) and side_effects.is_modified( + var._base_vt # pyrefly: ignore[bad-argument-type] + ): + _codegen_user_defined_list_mutation(ctx) + elif isinstance( + var, variables.UserDefinedDequeVariable + ) and side_effects.is_modified( + var._base_vt # pyrefly: ignore[bad-argument-type] + ): + _codegen_user_defined_deque_mutation(ctx) + + # Applying mutations involves two steps: 1) Push all reconstructed objects + # onto the stack. 2) Call STORE_ATTR to apply the mutations. + # + # Dynamo must ensure that mutations are applied in the same order as in the + # original program. Therefore, two reverse operations occur below. + # + # The first reverse operation concerns `suffixes`. We apply suffixes in + # reverse order due to the way Python handles the stack. In Step 1, we push + # all reconstructed objects onto the stack, but the item at the top of the + # stack refers to the last attribute in the mutation order. If not fixed, + # this will apply the mutations of attributes in the reverse order. To + # account for this reversal, we iterate through the mutable attributes in + # reverse order. + side_effect_occurred = False + for name, value in reversed(side_effects.store_attr_mutations.get(var, {}).items()): + mutation_kind = side_effects.get_attr_mutation_kind(var, name) + if isinstance(var, variables.NewGlobalVariable): + cg.tx.output.update_co_names(name) + cg(value) + if not isinstance(var.source, GlobalSource): # type: ignore[attr-defined] + raise AssertionError( + f"Expected GlobalSource for NewGlobalVariable, " + f"got {type(var.source)}" # type: ignore[attr-defined] + ) + ctx.suffixes.append([create_instruction("STORE_GLOBAL", argval=name)]) + side_effect_occurred = True + elif isinstance(value, variables.DeletedVariable): + if ( + isinstance(var, variables.UserDefinedObjectVariable) + and mutation_kind is AttrMutationKind.INSTANCE_DICT + ): + original_dict = getattr(getattr(var, "value", None), "__dict__", {}) + # If the key only existed in the traced instance dict, the + # add/delete sequence is a replay no-op. + if name in original_dict: + cg.add_push_null( + lambda: cg.load_import_from( + utils.__name__, + "object_delattr_ignore_descriptor", + ) + ) + cg(var.source) # type: ignore[attr-defined] + cg(variables.ConstantVariable(name)) + ctx.suffixes.append( + [ + *create_call_function(2, False), + create_instruction("POP_TOP"), + ] + ) + side_effect_occurred = True + # GENERIC_SETATTR deletions on UDOV fall through to the normal + # DELETE_ATTR path below so descriptor semantics are preserved + # during replay. + elif isinstance(var.mutation_type, AttributeMutationExisting) and hasattr( + getattr(var, "value", None), name + ): + cg.tx.output.update_co_names(name) + cg(var.source) + ctx.suffixes.append([create_instruction("DELETE_ATTR", argval=name)]) + side_effect_occurred = True + elif ( + isinstance(var, variables.UserDefinedObjectVariable) + and mutation_kind is AttrMutationKind.INSTANCE_DICT + ): + cg.add_push_null( + lambda: cg.load_import_from( + utils.__name__, "object_setattr_ignore_descriptor" + ) + ) + cg(var.source) # type: ignore[attr-defined] + cg(variables.ConstantVariable(name)) + cg(value) + ctx.suffixes.append( + [ + *create_call_function(3, False), + create_instruction("POP_TOP"), + ] + ) + side_effect_occurred = True + elif ( + isinstance(var, variables.UserDefinedObjectVariable) + and var.needs_slow_setattr() + ): + # __setattr__ is defined on this object, so call object.__setattr__ + # directly. + cg.load_import_from("builtins", "object") + cg.load_method("__setattr__") + cg(var.source) # type: ignore[attr-defined] + cg(variables.ConstantVariable(name)) + cg(value) + ctx.suffixes.append([*create_call_method(3), create_instruction("POP_TOP")]) + side_effect_occurred = True + else: + cg.tx.output.update_co_names(name) + cg(value) + cg(var) + ctx.suffixes.append([create_instruction("STORE_ATTR", argval=name)]) + side_effect_occurred = True + + if side_effect_occurred: + ctx.log(var) + + +@register_side_effect_replay_handler( + name="list_iterator_mutation", + matcher=lambda ctx: isinstance(ctx.var, variables.ListIteratorVariable), + priority=30, +) +def _codegen_list_iterator_mutation(ctx: SideEffectReplayContext) -> None: + cg = ctx.codegen + var = ctx.var + if not isinstance(var, variables.ListIteratorVariable): + raise AssertionError(type(var)) + for _ in range(var.index): + cg.add_push_null(lambda: cg.load_import_from(utils.__name__, "iter_next")) + cg(var.source) # type: ignore[attr-defined] + cg.call_function(1, False) + cg.pop_top() + ctx.log(var) + + +@register_side_effect_replay_handler( + name="count_iterator_mutation", + matcher=lambda ctx: isinstance(ctx.var, variables.CountIteratorVariable), + priority=20, +) +def _codegen_count_iterator_mutation(ctx: SideEffectReplayContext) -> None: + cg = ctx.codegen + var = ctx.var + if not isinstance(var, variables.CountIteratorVariable): + raise AssertionError(type(var)) + for _ in range(var.advance_count): + cg.add_push_null(lambda: cg.load_import_from(utils.__name__, "iter_next")) + cg(var.source) # type: ignore[attr-defined] + cg.call_function(1, False) + cg.pop_top() + ctx.log(var) + + +@register_side_effect_replay_handler( + name="random_mutation", + matcher=lambda ctx: isinstance(ctx.var, variables.RandomVariable), + priority=10, +) +def _codegen_random_mutation(ctx: SideEffectReplayContext) -> None: + cg = ctx.codegen + var = ctx.var + if not isinstance(var, variables.RandomVariable): + raise AssertionError(type(var)) + + def gen_fn() -> None: + cg(var.source) # type: ignore[attr-defined] + cg.load_attr("setstate") + + cg.add_push_null(gen_fn) + cg(var.wrap_state(var.random.getstate())) + + ctx.suffixes.append( + [ + *create_call_function(1, False), # setstate + create_instruction("POP_TOP"), + ] + ) + ctx.log(var) + + +@contextlib.contextmanager +def allow_side_effects_in_hop( + tx: "InstructionTranslatorBase", +) -> Generator[None, None, None]: + """Context manager to temporarily allow side effects with extra outputs. + + This is used for special cases (like FSDP functions) that need to perform + side effects even when the general policy is to disallow them. + """ + orig_val = tx.output.current_tracer.allow_side_effects_in_hop + try: + tx.output.current_tracer.allow_side_effects_in_hop = True + yield + finally: + tx.output.current_tracer.allow_side_effects_in_hop = orig_val + + +@contextlib.contextmanager +def allow_externally_visible_side_effects_in_subtracer( + tx: "InstructionTranslatorBase", +) -> Generator[None, None, None]: + orig_val = tx.output.current_tracer.unsafe_allow_externally_visible_side_effects + try: + tx.output.current_tracer.unsafe_allow_externally_visible_side_effects = True + tx.output.current_tracer.traced_with_externally_visible_side_effects = True + yield + finally: + tx.output.current_tracer.unsafe_allow_externally_visible_side_effects = orig_val + + +@contextlib.contextmanager +def disallow_side_effects_in_generator( + tx: "InstructionTranslatorBase", +) -> Generator[None, None, None]: + orig_val = tx.output.current_tracer.is_reconstructing_generator + try: + tx.output.current_tracer.is_reconstructing_generator = True + yield + finally: + tx.output.current_tracer.is_reconstructing_generator = orig_val diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/source.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/source.py new file mode 100644 index 0000000000000000000000000000000000000000..ee3005a8400865006c45c6c20846ac01b124e94b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/source.py @@ -0,0 +1,1440 @@ +""" +This module provides Source classes that track the origins of values in PyTorch Dynamo. +Sources represent where values come from (e.g. local variables, globals, attributes) and +are used for guard generation and code reconstruction during compilation. + +The module includes specialized sources for: +- Local variables and synthetic locals +- Global variables and constants +- Object attributes and method calls +- NN module specialization (specialized vs unspecialized) +- Random values and tensor properties +- Default argument handling +- FSDP (Fully Sharded Data Parallel) modules + +Sources play a key role in Dynamo's guard system by tracking value origins for +guard generation, and in code reconstruction by providing methods to rebuild +the code needed to recreate values. +""" + +import dataclasses +import enum +import functools +from collections.abc import Callable +from typing import Any, TYPE_CHECKING + +from torch import device as device_type +from torch._guards import ( + ChainedSource, + dataclass_with_cached_hash, + Guard, + GuardSource, + Source, +) + +from . import utils +from .bytecode_transformation import ( + create_binary_subscr, + create_build_tuple, + create_call_function, +) + + +if TYPE_CHECKING: + from .codegen import PyCodegen + +# It shouldn't be supported to construct an NNModuleVariable inside an FSDP module, +# so those cases are omitted intentionally + +# represents nn.Modules tracked with NNModuleVariable (specialized is implicit in the variable name) +_GUARD_SOURCE_SPECIALIZED_NN_MODULE = { + GuardSource.LOCAL: GuardSource.LOCAL_SPECIALIZED_NN_MODULE, + GuardSource.GLOBAL: GuardSource.GLOBAL_SPECIALIZED_NN_MODULE, + GuardSource.LOCAL_SPECIALIZED_NN_MODULE: GuardSource.LOCAL_SPECIALIZED_NN_MODULE, + GuardSource.GLOBAL_SPECIALIZED_NN_MODULE: GuardSource.GLOBAL_SPECIALIZED_NN_MODULE, + # Just to ensure that guard_source() works + GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE, + GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.LOCAL_FSDP_MODULE: GuardSource.LOCAL_FSDP_MODULE, + GuardSource.GLOBAL_FSDP_MODULE: GuardSource.GLOBAL_FSDP_MODULE, +} + +# represents nn.Modules tracked with UnspecializedNNModuleVariable +_GUARD_SOURCE_UNSPECIALIZED_NN_MODULE = { + GuardSource.LOCAL: GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE, + GuardSource.GLOBAL: GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE, + GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE, + # this happens for an UnspecializedNNModule submodule on a NNModuleVariable + GuardSource.LOCAL_SPECIALIZED_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE, + GuardSource.GLOBAL_SPECIALIZED_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE, + # Just to ensure that guard_source() works + GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.LOCAL_FSDP_MODULE: GuardSource.LOCAL_FSDP_MODULE, + GuardSource.GLOBAL_FSDP_MODULE: GuardSource.GLOBAL_FSDP_MODULE, +} + +# represents nn.Modules tracked with UnspecializedBuiltinNNModuleVariable +_GUARD_SOURCE_UNSPECIALIZED_BUILTIN_NN_MODULE = { + GuardSource.LOCAL: GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.GLOBAL: GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.LOCAL_SPECIALIZED_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.GLOBAL_SPECIALIZED_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + # Just to ensure that guard_source() works + GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.LOCAL_FSDP_MODULE: GuardSource.LOCAL_FSDP_MODULE, + GuardSource.GLOBAL_FSDP_MODULE: GuardSource.GLOBAL_FSDP_MODULE, +} + +_GUARD_SOURCE_FSDP_MODULE = { + GuardSource.LOCAL: GuardSource.LOCAL_FSDP_MODULE, + GuardSource.GLOBAL: GuardSource.GLOBAL_FSDP_MODULE, + GuardSource.LOCAL_SPECIALIZED_NN_MODULE: GuardSource.LOCAL_FSDP_MODULE, + GuardSource.GLOBAL_SPECIALIZED_NN_MODULE: GuardSource.GLOBAL_FSDP_MODULE, + GuardSource.LOCAL_FSDP_MODULE: GuardSource.LOCAL_FSDP_MODULE, + GuardSource.GLOBAL_FSDP_MODULE: GuardSource.GLOBAL_FSDP_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE: GuardSource.LOCAL_FSDP_MODULE, + GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE: GuardSource.GLOBAL_FSDP_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.LOCAL_FSDP_MODULE, + GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.GLOBAL_FSDP_MODULE, +} + + +def is_constant_source(source: Source) -> bool: + if isinstance(source, ConstantSource): + return True + try: + if source.guard_source == GuardSource.CONSTANT: + return True + except NotImplementedError: + pass + + return False + + +def _get_source_debug_name(source: Source | None) -> str: + if source is None: + return "" + else: + try: + return source.name + except NotImplementedError: + return "" + + +def _esc_str(s: Any, apply_repr: bool = False) -> str: + """ + Escapes curly brackets for format strings. + e.g. "frozenset({0})" becomes "frozenset({{0}})". + This is used by _name_template for example, because it's + expected to return a format string, but we may wish to include + strings that should not be accidentally formatted. + """ + if apply_repr: + s = repr(s) + else: + s = str(s) + return s.replace("{", "{{").replace("}", "}}") + + +@dataclass_with_cached_hash(frozen=True) +class LocalSource(Source): + local_name: str + + # Whether this local is an input to the root frame. + is_input: bool = False + + # Whether we know this input is dynamic (based on example_inputs) + # For non tensors, we simply look at the first index of the tuple + dynamism: frozenset[str] | None = None + + # Whether the item at this source is the _content_ of a cell that is + # dereferenced from the root frame, i.e., it's a part of the `co_cellvars` + # or `co_freevars`. + is_derefed_cell_contents: bool = False + + # Whether this local is the function's varargs (``*args``) parameter. + # Set from ``co_flags & CO_VARARGS`` at frame-entry time. Element accesses + # like ``args[N]`` produce a ``GetItemSource`` whose base has this flag. + # Useful for distinguishing ``*args`` from a regular list-typed input. + # ``repr=False`` so the vast majority of locals (which are not varargs) do + # not get a noisy ``is_varargs=False`` in every debug string. + is_varargs: bool = dataclasses.field(default=False, repr=False) + + # Whether this local is the function's varkw (``**kwargs``) parameter. + # Set from ``co_flags & CO_VARKEYWORDS`` at frame-entry time. Element + # accesses like ``kwargs["k"]`` produce a ``DictGetItemSource`` whose base + # has this flag. ``repr=False`` for the same reason as ``is_varargs``. + is_varkw: bool = dataclasses.field(default=False, repr=False) + + def reconstruct(self, codegen: "PyCodegen") -> None: + if self.is_derefed_cell_contents: + codegen.load_deref(self.local_name) + else: + codegen.append_output(codegen.create_load(self.local_name)) + + def reconstruct_pycode(self, codegen: "PyCodegen") -> str: + return self.local_name + + @property + def guard_source(self) -> GuardSource: + return GuardSource.LOCAL + + @functools.cached_property + def _name_template(self) -> str: + return f"L[{_esc_str(self.local_name, apply_repr=True)}]" + + +@dataclass_with_cached_hash(frozen=True) +class TempLocalSource(Source): + # like LocalSource, but cannot be guarded on + local_name: str + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.append_output(codegen.create_load(self.local_name)) + + @property + def guard_source(self) -> GuardSource: + return GuardSource.TEMP_LOCAL + + @property + def _name_template(self) -> str: + raise NotImplementedError( + "Cannot create guard on TempLocalSource - this is an internal Dynamo bug. Please file an issue on GitHub." + ) + + +@dataclass_with_cached_hash(frozen=True) +class SyntheticLocalSource(Source): + local_name: str + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.append_output(codegen.create_load(self.local_name)) + + @property + def guard_source(self) -> GuardSource: + return GuardSource.SYNTHETIC_LOCAL + + @functools.cached_property + def _name_template(self) -> str: + return f"SYNTHETIC_LOCAL[{_esc_str(self.local_name, apply_repr=True)}]" + + +@dataclass_with_cached_hash(frozen=True) +class RandomValueSource(Source): + random_call_index: int + + @property + def guard_source(self) -> GuardSource: + return GuardSource.RANDOM_VALUE + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.append_output(codegen.create_load(codegen.tx.output.random_values_var)) + codegen.append_output(codegen.create_load_const(self.random_call_index)) + codegen.append_output(create_binary_subscr()) + + @functools.cached_property + def _name_template(self) -> str: + return f"random_value_{_esc_str(self.random_call_index)}" + + +@dataclass_with_cached_hash(frozen=True) +class GlobalSource(Source): + global_name: str + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.append_output(codegen.create_load_global(self.global_name, add=True)) + + def reconstruct_pycode(self, codegen: "PyCodegen") -> str: + return self.global_name + + @property + def guard_source(self) -> GuardSource: + return GuardSource.GLOBAL + + @functools.cached_property + def _name_template(self) -> str: + return f"G[{_esc_str(self.global_name, apply_repr=True)}]" + + +@dataclass_with_cached_hash(frozen=True) +class GlobalWeakRefSource(Source): + global_name: str + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.append_output( + codegen.create_load_global(self.global_name, add=True) + ) + ) + codegen.extend_output(create_call_function(0, False)) + + @property + def guard_source(self) -> GuardSource: + return GuardSource.GLOBAL + + @functools.cached_property + def _name_template(self) -> str: + return f"G[{_esc_str(self.global_name, apply_repr=True)}]()" + + +@dataclass_with_cached_hash(frozen=True) +class WeakRefCallSource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen(self.base)) + codegen.extend_output(create_call_function(0, False)) + + @property + def _name_template(self) -> str: + return "{0}()" + + +@dataclass_with_cached_hash(frozen=True) +class CallFunctionNoArgsSource(WeakRefCallSource): + pass + + +@dataclass_with_cached_hash(frozen=True) +class AttrSource(ChainedSource): + member: str + + def __post_init__(self) -> None: + if not self.base: + raise AssertionError( + "Can't construct an AttrSource without a valid base source" + ) + if "." in self.member: + raise AssertionError( + f"AttrSource member must not contain '.', got {self.member!r}. " + "Use OutputGraph.get_chained_attr_source() for dotted paths." + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + codegen.extend_output(codegen.create_load_attrs(self.member)) + + def reconstruct_pycode(self, codegen: "PyCodegen") -> str: + base = self.base.reconstruct_pycode(codegen) + if self.member.isidentifier(): + return f"{base}.{self.member}" + else: + return f"getattr({base}, {self.member!r})" + + @functools.cached_property + def _name_template(self) -> str: + if not self.member.isidentifier(): + return f"getattr({{0}}, {_esc_str(self.member, apply_repr=True)})" + return f"{{0}}.{_esc_str(self.member)}" + + +@dataclass_with_cached_hash(frozen=True) +class CellContentsSource(AttrSource): + """ + Source for closure cell contents that also stores the freevar name. + This allows guard failure messages to show which variable the closure cell refers to. + """ + + freevar_name: str = dataclasses.field(default="") + + def __post_init__(self) -> None: + if not self.base: + raise AssertionError( + "Can't construct a CellContentsSource without a valid base source" + ) + if self.member != "cell_contents": + raise AssertionError( + "CellContentsSource should only be used for cell_contents" + ) + + +@dataclass_with_cached_hash(frozen=True) +class GenericAttrSource(ChainedSource): + member: str + + def __post_init__(self) -> None: + if not self.base: + raise AssertionError( + "Can't construct a GenericAttrSource without a valid base source" + ) + if "." in self.member: + raise AssertionError( + f"GenericAttrSource member must not contain '.', got {self.member!r}. " + "Use OutputGraph.get_chained_attr_source() for dotted paths." + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + codegen.extend_output(codegen.create_load_attrs(self.member)) + + @functools.cached_property + def _name_template(self) -> str: + return ( + f"object.__getattribute__({{0}}, {_esc_str(self.member, apply_repr=True)})" + ) + + +# Represents obj.__dict__ where obj is a type object +@dataclass_with_cached_hash(frozen=True) +class TypeDictSource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + codegen.extend_output(codegen.create_load_attrs("__dict__")) + + @property + def _name_template(self) -> str: + # type(ob).__dict__ can return a proxy of the dict. But in the C++ + # guard accessor, we use type->tp_dict which is a dict. So, + # forcefully pass a dict object to ensure that the GuardManager + # registers that it's working on a dict object. + return "dict({0}.__dict__)" + + +# Represents obj.__mro__ where object is type object +@dataclass_with_cached_hash(frozen=True) +class TypeMROSource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + codegen.extend_output(codegen.create_load_attrs("__mro__")) + + @property + def _name_template(self) -> str: + return "{0}.__mro__" + + +@dataclass_with_cached_hash(frozen=True) +class LocalCellSource(Source): + """ + Conceptually, this class is `LocalSource` for cell objects implicitly + generated by Python (e.g., captured variables). + """ + + local_name: str + + def reconstruct(self, codegen: "PyCodegen") -> None: + # Although `LOAD_FAST` and `LOAD_CLOSURE` have the same semantics, + # Dynamo's bytecode transformation differentiates them slightly, so we + # always emit `LOAD_CLOSURE` here. + codegen.append_output(codegen.create_load_closure(self.local_name)) + + # All the other methods are intentionally unimplemented because e.g., a + # local cell object should never be used for guards. + + +# Represents obj.__code__ where object is type object +@dataclass_with_cached_hash(frozen=True) +class CodeSource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + codegen.extend_output(codegen.create_load_attrs("__code__")) + + @property + def _name_template(self) -> str: + return "{0}.__code__" + + +# Represents obj.__closure__ where object is type object +@dataclass_with_cached_hash(frozen=True) +class ClosureSource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + codegen.extend_output(codegen.create_load_attrs("__closure__")) + + @property + def _name_template(self) -> str: + return "{0}.__closure__" + + +# Represents tensor.grad source. It could be represented by AttrSource as well. +# But, we could access grad field on tensor directly in C++ without going +# through the Python bytecodes. Therefore, we use a separate source for grad +# field. +@dataclass_with_cached_hash(frozen=True) +class GradSource(ChainedSource): + member: str = "grad" + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + codegen.extend_output(codegen.create_load_attrs(self.member)) + + @functools.cached_property + def _name_template(self) -> str: + return f"{{0}}.{_esc_str(self.member)}" + + +@dataclass_with_cached_hash(frozen=True) +class ParamBufferSource(AttrSource): + @functools.cached_property + def guard_source(self) -> GuardSource: + return _GUARD_SOURCE_SPECIALIZED_NN_MODULE[self.base.guard_source] + + +# Special AttrSource to differentiate module._buffers or module._parameters +@dataclass_with_cached_hash(frozen=True) +class UnspecializedParamBufferSource(AttrSource): + pass + + +# This source is intended to be used in places where a source is needed but it is expected +# that the symbol will be simplified out later on. Symbols with ephemeral sources are +# prioritized to be simplified out when e.g. compared against a symbol without an ephemeral +# source. Guarding on this source is an error. +# +# Example: During subclass view fake-ification, any close-over ViewFunc state should be +# symbolicized / fake-ified to avoid invalid specialization during view replay. This source +# is useful for symbols utilized in the middle of the view chain that are not expected to be +# present within the final view shape metadata. +@dataclass_with_cached_hash(frozen=True) +class EphemeralSource(Source): + desc: str | None = None + + @property + def guard_source(self) -> GuardSource: + return GuardSource.EPHEMERAL + + @functools.cached_property + def _name_template(self) -> str: + desc = ": " + self.desc if self.desc is not None else "" + return f"" + + def make_guard(self, fn: Callable[..., Any]) -> Guard: + raise NotImplementedError + + def is_ephemeral(self) -> bool: + return True + + +@dataclass_with_cached_hash(frozen=True) +class SkipGuardSource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + self.base.reconstruct(codegen) + + @property + def _name_template(self) -> str: + return "{0}" + + +class TensorProperty(enum.Enum): + SIZE = 0 + STRIDE = 1 + STORAGE_OFFSET = 2 + + def method_name(self) -> str: + if self is TensorProperty.SIZE: + return "size" + elif self is TensorProperty.STRIDE: + return "stride" + elif self is TensorProperty.STORAGE_OFFSET: + return "storage_offset" + else: + raise AssertionError(f"unhandled {_esc_str(self)}") + + +@dataclass_with_cached_hash(frozen=True) +class TensorPropertySource(ChainedSource): + prop: TensorProperty + idx: int | None = None # None for STORAGE_OFFSET + + def __post_init__(self) -> None: + if self.base is None: + raise AssertionError("TensorPropertySource base must not be None") + if self.prop is TensorProperty.STORAGE_OFFSET: + if self.idx is not None: + raise AssertionError( + "idx must be None for STORAGE_OFFSET TensorProperty" + ) + else: + if self.idx is None: + raise AssertionError( + f"idx must not be None for {self.prop} TensorProperty" + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from( + utils.__name__, f"call_{_esc_str(self.prop.method_name())}" + ) + ) + codegen(self.base) + + if self.idx is not None: + codegen.append_output(codegen.create_load_const(self.idx)) + codegen.extend_output( + create_call_function(2 if self.idx is not None else 1, False) + ) + + @functools.cached_property + def _name_template(self) -> str: + if self.prop is TensorProperty.SIZE: + return f"{{0}}.size()[{_esc_str(self.idx)}]" + elif self.prop is TensorProperty.STRIDE: + return f"{{0}}.stride()[{_esc_str(self.idx)}]" + elif self.prop is TensorProperty.STORAGE_OFFSET: + if self.idx is not None: + raise AssertionError( + "idx must be None for STORAGE_OFFSET TensorProperty" + ) + return "{0}.storage_offset()" + else: + raise AssertionError(f"unhandled {_esc_str(self.prop)}") + + +@dataclass_with_cached_hash(frozen=True) +class IndexedSource(ChainedSource): + idx: int + + def __post_init__(self) -> None: + if self.base is None: + raise AssertionError("IndexedSource base must not be None") + + def reconstruct(self, codegen: "PyCodegen") -> None: + raise NotImplementedError + + @functools.cached_property + def _name_template(self) -> str: + return f"({_esc_str(self.idx)}, {{0}})" + + +@dataclass_with_cached_hash(frozen=True) +class NegateSource(ChainedSource): + def __post_init__(self) -> None: + if self.base is None: + raise AssertionError("NegateSource base must not be None") + + def reconstruct(self, codegen: "PyCodegen") -> None: + raise NotImplementedError + + @property + def _name_template(self) -> str: + # NB: use method call so that function stripping regexes work + return "{0}.__neg__()" + + +@dataclass_with_cached_hash(frozen=True) +class ConvertIntSource(ChainedSource): + def __post_init__(self) -> None: + if self.base is None: + raise AssertionError("ConvertIntSource base must not be None") + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + + @property + def _name_template(self) -> str: + return "cast_symbool_to_symint_guardless({0})" + + +@dataclass_with_cached_hash(frozen=True) +class DynamicScalarSource(ChainedSource): + is_int: bool + + def __post_init__(self) -> None: + if self.base is None: + raise AssertionError("DynamicScalarSource base must not be None") + + def reconstruct(self, codegen: "PyCodegen") -> None: + # Integer casting at reconstruction helps reduce the amount of DynamicInts returned + # to the user, in favor of plain ints. + # For example, a compiled region that only does int arithmetic could return a + # DynamicInt without the casting here. + codegen.add_push_null(lambda: codegen.load_import_from("builtins", "int")) + codegen(self.base) + codegen.extend_output(create_call_function(1, False)) + + @property + def _name_template(self) -> str: + return "int({0})" + + +@dataclass_with_cached_hash(frozen=True) +class FlattenScriptObjectSource(ChainedSource): + def __post_init__(self) -> None: + if self.base is None: + raise AssertionError("FlattenScriptObjectSource base must not be None") + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + + @property + def _name_template(self) -> str: + return "{0}.__obj_flatten__()" + + +@dataclass_with_cached_hash(frozen=True) +class ScriptObjectQualifiedNameSource(ChainedSource): + def __post_init__(self) -> None: + if self.base is None: + raise AssertionError( + "ScriptObjectQualifiedNameSource base must not be None" + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + + @property + def _name_template(self) -> str: + return "{0}._type().qualified_name()" + + +class AttrProxySource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + + @property + def _name_template(self) -> str: + return "{0}.get_base()" + + +@dataclass_with_cached_hash(frozen=True) +class DefaultsSource(ChainedSource): + idx_key: int | str + is_kw: bool = False + field: str = dataclasses.field(init=False, repr=False, compare=False) + _name: str = dataclasses.field(init=False, repr=False, compare=False) + + def __post_init__(self) -> None: + if not self.base: + raise AssertionError( + "Base must be a valid source in order to properly track and guard this Defaults to its origin." + ) + if self.is_kw: + if not isinstance(self.idx_key, str): + raise AssertionError( + f"idx_key must be a str for keyword defaults, got {type(self.idx_key)}" + ) + object.__setattr__(self, "field", "__kwdefaults__") + object.__setattr__( + self, + "_name", + f"{{0}}.{_esc_str(self.field)}['{_esc_str(self.idx_key)}']", + ) + else: + if not isinstance(self.idx_key, int): + raise AssertionError( + f"idx_key must be an int for positional defaults, got {type(self.idx_key)}" + ) + object.__setattr__(self, "field", "__defaults__") + object.__setattr__( + self, "_name", f"{{0}}.{_esc_str(self.field)}[{_esc_str(self.idx_key)}]" + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + codegen.extend_output(codegen.create_load_attrs(self.field)) + codegen.append_output(codegen.create_load_const(self.idx_key)) + codegen.append_output(create_binary_subscr()) + + @functools.cached_property + def _name_template(self) -> str: + return self._name + + +@dataclass_with_cached_hash(frozen=True) +class GetItemSource(ChainedSource): + index: Any + index_is_slice: bool = False + + def __post_init__(self) -> None: + if self.base is None: + raise AssertionError("GetItemSource base must not be None") + if isinstance(self.index, slice): + # store the hashable version of the slice so the whole GetItemSource is hashable + super().__setattr__("index", self.index.__reduce__()) + super().__setattr__("index_is_slice", True) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + if self.index_is_slice: + codegen.append_output(codegen.create_load_const(self.unpack_slice())) + else: + codegen.append_output(codegen.create_load_const(self.index)) + codegen.append_output(create_binary_subscr()) + + def unpack_slice(self) -> slice: + if not self.index_is_slice: + raise AssertionError("unpack_slice called but index is not a slice") + slice_class, slice_args = self.index + return slice_class(*slice_args) + + @functools.cached_property + def _name_template(self) -> str: + # Index can be of following types + # 1) index is a slice - example 1:4 + # 2) index is a constant - example string, integer + if isinstance(self.index, Source): + raise AssertionError( + f"GetItemSource index must not be a Source, got {type(self.index)}" + ) + if self.index_is_slice: + return f"{{0}}[{_esc_str(self.unpack_slice(), apply_repr=True)}]" + else: + return f"{{0}}[{_esc_str(self.index, apply_repr=True)}]" + + +@dataclass_with_cached_hash(frozen=True) +class ConstDictKeySource(ChainedSource): + index: Any + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from(utils.__name__, "dict_keys_getitem") + ) + codegen(self.base) + codegen.append_output(codegen.create_load_const(self.index)) + codegen.extend_output(create_call_function(2, False)) + + @functools.cached_property + def _name_template(self) -> str: + # The list creation will be CSE'd by PyExprCSEPass + return f"list(dict.keys({{0}}))[{_esc_str(self.index, apply_repr=True)}]" + + def is_dict_key(self) -> bool: + return True + + +@dataclass_with_cached_hash(frozen=True) +class NonSerializableSetGetItemSource(ChainedSource): + index: int + + def __post_init__(self) -> None: + from .variables import ConstantVariable + + if not ConstantVariable.is_literal(self.index): + raise AssertionError( + f"NonSerializableSetGetItemSource index must be a literal, got {self.index!r}" + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from(utils.__name__, "set_getitem") + ) + codegen(self.base) + codegen.append_output(codegen.create_load_const(self.index)) + codegen.extend_output(create_call_function(2, False)) + + def get_value( + self, + globals: dict[str, Any], + locals: dict[str, Any], + cache: dict[Source, Any], + ) -> Any: + if self in cache: + return cache[self] + value = utils.set_getitem( + self.base.get_value(globals, locals, cache), self.index + ) + cache[self] = value + return value + + @functools.cached_property + def _name_template(self) -> str: + # set ordering might not be stable + return f"___set_getitem({{0}}, {_esc_str(self.index, apply_repr=True)})" + + def is_dict_key(self) -> bool: + return False + + +# Used to access an item from the dictionary +@dataclass_with_cached_hash(frozen=True) +class DictGetItemSource(ChainedSource): + # Key to access in the dictionary. It can be one of the following types + # 1) ConstDictKeySource + # 2) constant - like string, integer + index: Any + + def __post_init__(self) -> None: + from .variables import ConstantVariable + + if not isinstance( + self.index, ConstDictKeySource + ) and not ConstantVariable.is_literal(self.index): + raise AssertionError( + f"DictGetItemSource index must be a ConstDictKeySource or literal, got {self.index!r}" + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + # Load dict + codegen(self.base) + + # Load key + if isinstance(self.index, Source): + codegen(self.index) + else: + codegen.append_output(codegen.create_load_const(self.index)) + codegen.append_output(create_binary_subscr()) + + def reconstruct_pycode(self, codegen: "PyCodegen") -> str: + base = self.base.reconstruct_pycode(codegen) + if isinstance(self.index, ConstDictKeySource): + index = self.index.reconstruct_pycode(codegen) + else: + index = repr(self.index) + return f"{base}[{index}]" + + @functools.cached_property + def _name_template(self) -> str: + if isinstance(self.index, ConstDictKeySource): + return f"{{0}}[{_esc_str(self.index.name)}]" + else: + return f"{{0}}[{_esc_str(self.index, apply_repr=True)}]" + + +# Same as DictGetItemSource but used for dict.__getitem__ calls to ensure that +# torch.compile does not run the overridden __getitem__ method +@dataclass_with_cached_hash(frozen=True) +class DictSubclassGetItemSource(ChainedSource): + # Key to access in the dictionary. It can be one of the following types + # 1) ConstDictKeySource + # 2) constant - like string, integer + index: Any + + def __post_init__(self) -> None: + from .variables import ConstantVariable + + if not isinstance( + self.index, ConstDictKeySource + ) and not ConstantVariable.is_literal(self.index): + raise AssertionError( + f"DictSubclassGetItemSource index must be a ConstDictKeySource or literal, got {self.index!r}" + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + # reconstruct dict.__getitem__(dct, key) + + # Load dict.__getitem__ + codegen.add_push_null( + lambda: codegen.load_import_from(utils.__name__, "dict_getitem") + ) + + # Load dict + codegen(self.base) + + # Load key + if isinstance(self.index, Source): + codegen(self.index) + else: + codegen.append_output(codegen.create_load_const(self.index)) + + codegen.extend_output(create_call_function(2, False)) + + @functools.cached_property + def _name_template(self) -> str: + if isinstance(self.index, ConstDictKeySource): + return f"dict.__getitem__({{0}}, {_esc_str(self.index.name)})" + else: + return f"{{0}}[{_esc_str(self.index, apply_repr=True)}]" + + +@dataclass_with_cached_hash(frozen=True) +class ListGetItemSource(GetItemSource): + """ + Same as GetItemSource with reconstruct and name overridden to be list specific. + """ + + def reconstruct(self, codegen: "PyCodegen") -> None: + # Reconstruct list.__getitem__(lst, index) to avoid any side effects + # from possibly overridden __getitem__. + + # Load list.__getitem__ + codegen.add_push_null( + lambda: codegen.load_import_from(utils.__name__, "list_getitem") + ) + + # Load the list + codegen(self.base) + + # Load the index + if self.index_is_slice: + raise RuntimeError( + "List[slice] is a temporary object and should not have a source" + ) + else: + codegen.append_output(codegen.create_load_const(self.index)) + + codegen.extend_output(create_call_function(2, False)) + + @functools.cached_property + def _name_template(self) -> str: + # Index can be of following types + # 1) index is a slice - example 1:4 + # 2) index is a constant - example string, integer + if isinstance(self.index, Source): + raise AssertionError( + f"ListGetItemSource index must not be a Source, got {type(self.index)}" + ) + if self.index_is_slice: + raise RuntimeError( + "List[slice] is a temporary object and should not have a source" + ) + else: + return f"list.__getitem__({{0}}, {_esc_str(self.index, apply_repr=True)})" + + +@dataclass_with_cached_hash(frozen=True) +class TupleIteratorGetItemSource(GetItemSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from(utils.__name__, "tuple_iterator_getitem") + ) + codegen(self.base) + codegen.append_output(codegen.create_load_const(self.index)) + codegen.extend_output(create_call_function(2, False)) + + @functools.cached_property + def _name_template(self) -> str: + return ( + f"___tuple_iterator_getitem({{0}}, {_esc_str(self.index, apply_repr=True)})" + ) + + +@dataclass_with_cached_hash(frozen=True) +class NamedTupleFieldsSource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + codegen.extend_output(codegen.create_load_attrs("_fields")) + + @property + def _name_template(self) -> str: + return "___namedtuple_fields({0})" + + +@dataclass_with_cached_hash(frozen=True) +class DataclassFieldsSource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from(utils.__name__, "dataclass_fields") + ) + codegen(self.base) + codegen.extend_output(create_call_function(1, False)) + + @property + def _name_template(self) -> str: + return "___dataclass_fields({0})" + + +@dataclass_with_cached_hash(frozen=True) +class TypeSource(ChainedSource): + def __post_init__(self) -> None: + if self.base is None: + raise AssertionError("TypeSource base must not be None") + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen.load_import_from("builtins", "type")) + codegen(self.base) + codegen.extend_output(create_call_function(1, False)) + + @property + def _name_template(self) -> str: + return "type({0})" + + +@dataclass_with_cached_hash(frozen=True) +class OptimizerSource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + + @property + def _name_template(self) -> str: + return "{0}" + + +@dataclass_with_cached_hash(frozen=True) +class NNModuleSource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.base) + + def reconstruct_pycode(self, codegen: "PyCodegen") -> str: + return self.base.reconstruct_pycode(codegen) + + @functools.cached_property + def guard_source(self) -> GuardSource: + return _GUARD_SOURCE_SPECIALIZED_NN_MODULE[self.base.guard_source] + + @property + def _name_template(self) -> str: + return "{0}" + + +@dataclass_with_cached_hash(frozen=True) +class UnspecializedNNModuleSource(NNModuleSource): + @functools.cached_property + def guard_source(self) -> GuardSource: + return _GUARD_SOURCE_UNSPECIALIZED_NN_MODULE[self.base.guard_source] + + +@dataclass_with_cached_hash(frozen=True) +class UnspecializedBuiltinNNModuleSource(UnspecializedNNModuleSource): + @functools.cached_property + def guard_source(self) -> GuardSource: + return _GUARD_SOURCE_UNSPECIALIZED_BUILTIN_NN_MODULE[self.base.guard_source] + + +@dataclass_with_cached_hash(frozen=True) +class FSDPNNModuleSource(NNModuleSource): + @functools.cached_property + def guard_source(self) -> GuardSource: + return _GUARD_SOURCE_FSDP_MODULE[self.base.guard_source] + + +@dataclass_with_cached_hash(frozen=True) +class GlobalStateSource(Source): + @property + def _name_template(self) -> str: + return "" + + @property + def guard_source(self) -> GuardSource: + return GuardSource.GLOBAL + + +@dataclass_with_cached_hash(frozen=True) +class ImportSource(Source): + """Points to an imported module - used instead of GlobalSource + in case the user has overridden the module name in their local namespace""" + + module_name: str + + @functools.cached_property + def _name_template(self) -> str: + return f"__import__('{self.module_name}')" + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.extend_output( + [ + codegen.create_load_const(0), # level + create_build_tuple(0), # fromlist + codegen.create_import_name(self.module_name), + ] + ) + + @property + def guard_source(self) -> GuardSource: + return GuardSource.GLOBAL + + +@dataclass_with_cached_hash(frozen=True) +class TorchFunctionModeStackSource(Source): + ind: int + + @functools.cached_property + def _name_template(self) -> str: + return f"___get_torch_function_mode_stack_at({_esc_str(self._get_index())})" + + def _get_index(self) -> int: + from .variables.torch_function import TorchFunctionModeStackVariable + + return TorchFunctionModeStackVariable.get_mode_index(self.ind) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from( + utils.__name__, "get_torch_function_mode_stack_at" + ) + ) + codegen.extend_output([codegen.create_load_const(self._get_index())]) + codegen.extend_output(create_call_function(1, False)) + + @property + def guard_source(self) -> GuardSource: + return GuardSource.GLOBAL + + +@dataclass_with_cached_hash(frozen=True) +class ConstantSource(Source): + source_name: str + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.append_output(codegen.create_load_global(self.source_name, add=False)) + + @property + def guard_source(self) -> GuardSource: + return GuardSource.CONSTANT + + @functools.cached_property + def _name_template(self) -> str: + return self.source_name + + def make_guard(self, fn: Any) -> Any: + raise NotImplementedError + + +@dataclass_with_cached_hash(frozen=True) +class NumpyTensorSource(ChainedSource): + @property + def _name_template(self) -> str: + return "___from_numpy({0})" + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen.load_import_from("torch", "as_tensor")) + codegen(self.base) + codegen.extend_output(create_call_function(1, False)) + + +@dataclass_with_cached_hash(frozen=True) +class SubclassAttrListSource(ChainedSource): + @property + def _name_template(self) -> str: + return "{0}.__tensor_flatten__()[0]" + + +# Guard-only source that yields the inner tensor of an AsyncCollectiveTensor +# (ACT) and the base value unchanged for a plain Tensor. Used to guard on the +# unwrapped tensor so a graph traced on an ACT can be reused when the resolved +# plain Tensor is passed at runtime. See +# torch._dynamo.variables.builder.VariableBuilder.wrap_tensor. +@dataclass_with_cached_hash(frozen=True) +class UnwrapCollectiveTensorSource(ChainedSource): + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from( + "torch._dynamo.guards", "unwrap_async_collective_tensor" + ) + ) + codegen(self.base) + codegen.extend_output(create_call_function(1, False)) + + @property + def _name_template(self) -> str: + return "___unwrap_async_collective_tensor({0})" + + +# NB: We don't expect you to actually ever generate guards against this +# source, it is ephemeral +@dataclass_with_cached_hash(frozen=True) +class FloatTensorSource(ChainedSource): + @property + def _name_template(self) -> str: + return "___as_tensor({0})" + + +@dataclass_with_cached_hash(frozen=True) +class CallMethodItemSource(ChainedSource): + @property + def _name_template(self) -> str: + return "{0}.item()" + + +@dataclass_with_cached_hash(frozen=True) +class ContextVarGetSource(ChainedSource): + has_default: bool = False + default_value: Any = None + + def reconstruct(self, codegen: "PyCodegen") -> None: + def load_get_method(): + codegen(self.base) + codegen.extend_output(codegen.create_load_attrs("get")) + + codegen.add_push_null(load_get_method) + if self.has_default: + codegen.append_output(codegen.create_load_const(self.default_value)) + codegen.extend_output(create_call_function(1, False)) + else: + codegen.extend_output(create_call_function(0, False)) + + @functools.cached_property + def _name_template(self) -> str: + if self.has_default: + return f"{{0}}.get({_esc_str(self.default_value, apply_repr=True)})" + return "{0}.get()" + + +# This is a synthetic source that is associated with the singleton +# shape env guard we always register for all frames. We get the actual +# guard contents from the ambient ShapeEnv +@dataclass_with_cached_hash(frozen=True) +class ShapeEnvSource(Source): + @property + def _name_template(self) -> str: + return "" + + @property + def guard_source(self) -> GuardSource: + return GuardSource.SHAPE_ENV + + +@dataclass_with_cached_hash(frozen=True) +class CurrentStreamSource(Source): + device: device_type + + @functools.cached_property + def _name_template(self) -> str: + return f"___get_current_stream(torch.device('{_esc_str(self.device.type)}', {_esc_str(self.device.index)}))" + + def reconstruct(self, codegen: "PyCodegen") -> None: + num_args = 1 + codegen.add_push_null( + lambda: codegen.load_import_from(utils.__name__, "get_current_stream") + ) + codegen.add_push_null(lambda: codegen.load_import_from("torch", "device")) + codegen.extend_output([codegen.create_load_const(self.device.type)]) + if self.device.index is not None: + num_args += 1 + codegen.extend_output([codegen.create_load_const(self.device.index)]) + codegen.extend_output(create_call_function(num_args, False)) + codegen.extend_output(create_call_function(1, False)) + + @property + def guard_source(self) -> GuardSource: + return GuardSource.GLOBAL + + +@dataclass_with_cached_hash(frozen=True) +class BackwardStateSource(Source): + @property + def _name_template(self) -> str: + return "" + + @property + def guard_source(self) -> GuardSource: + return GuardSource.BACKWARD_STATE + + +@functools.lru_cache +def get_local_source_name( + source: Source, *, only_allow_input: bool = False +) -> str | None: + if isinstance(source, ChainedSource): + return get_local_source_name(source.base, only_allow_input=only_allow_input) + if not isinstance(source, LocalSource): + return None + if only_allow_input and not source.is_input: + return None + return source.local_name + + +@functools.lru_cache +def is_from_local_source(source: Source, *, only_allow_input: bool = False) -> bool: + return get_local_source_name(source, only_allow_input=only_allow_input) is not None + + +@functools.lru_cache +def is_from_global_source(source: Source) -> bool: + return get_global_source_name(source) is not None + + +@functools.lru_cache +def get_global_source_name(source: Source | None) -> str | None: + if isinstance(source, ChainedSource): + return get_global_source_name(source.base) + if not isinstance(source, GlobalSource): + return None + return source.global_name + + +@functools.lru_cache +def is_from_nonlocal_source(source: Source) -> bool: + if isinstance(source, ChainedSource): + return is_from_nonlocal_source(source.base) + return ( + isinstance(source, LocalSource) + and source.is_derefed_cell_contents + and not source.is_input + ) + + +@functools.lru_cache +def is_from_closure_source(source: Source) -> bool: + if isinstance(source, ClosureSource): + return True + if isinstance(source, ChainedSource): + return is_from_closure_source(source.base) + return False + + +@functools.lru_cache +def is_from_source(source: Source, target: Source) -> bool: + if source == target: + return True + if isinstance(source, ChainedSource): + return is_from_source(source.base, target) + return False + + +@functools.lru_cache +def is_from_unspecialized_nn_module_source(source: Source) -> bool: + if isinstance(source, UnspecializedNNModuleSource): + return True + if isinstance(source, ChainedSource): + return is_from_unspecialized_nn_module_source(source.base) + return False + + +@functools.lru_cache +def is_from_unspecialized_builtin_nn_module_source(source: Source) -> bool: + if isinstance(source, UnspecializedBuiltinNNModuleSource): + return True + if isinstance(source, ChainedSource): + return is_from_unspecialized_builtin_nn_module_source(source.base) + return False + + +@functools.lru_cache +def is_from_unspecialized_param_buffer_source(source: Source) -> bool: + if isinstance(source, UnspecializedParamBufferSource): + return True + if isinstance(source, ChainedSource): + return is_from_unspecialized_param_buffer_source(source.base) + return False + + +@functools.lru_cache +def is_from_flatten_script_object_source(source: Source) -> bool: + if isinstance(source, FlattenScriptObjectSource): + return True + elif isinstance(source, ChainedSource): + return is_from_flatten_script_object_source(source.base) + return False + + +@functools.lru_cache +def is_from_optimizer_source(source: Source) -> bool: + if isinstance(source, OptimizerSource): + return True + if isinstance(source, ChainedSource): + return is_from_optimizer_source(source.base) + return False + + +# TODO: can probably write a generic "test this on everything in the chain" +# helper +@functools.lru_cache +def is_from_defaults(source: Source) -> bool: + if isinstance(source, DefaultsSource): + return True + + # Accessed with func.__kwdefaults__["foo"] + if ( + isinstance(source, DictGetItemSource) + and isinstance(source.base, AttrSource) + and source.base.member == "__kwdefaults__" + ): + return True + + # Accessed with func.__defaults__[0] + if ( + isinstance(source, GetItemSource) + and isinstance(source.base, AttrSource) + and source.base.member == "__defaults__" + ): + return True + + if isinstance(source, ChainedSource): + return is_from_defaults(source.base) + return False + + +@functools.lru_cache +def is_from_skip_guard_source(source: Source) -> bool: + if isinstance(source, SkipGuardSource): + return True + + if isinstance(source, ChainedSource): + return is_from_skip_guard_source(source.base) + + return False diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/symbolic_convert.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/symbolic_convert.py new file mode 100644 index 0000000000000000000000000000000000000000..44623bdd4a08c50adce9feaa4da79689d387efd2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/symbolic_convert.py @@ -0,0 +1,6627 @@ +""" +Core module responsible for converting Python bytecode into TorchDynamo's symbolic execution format. + +This module implements the bytecode-level tracing system that allows TorchDynamo to analyze +and transform Python code. It converts Python bytecode instructions into a symbolic format +that tracks the flow of tensors and other values through the program. + +Key components: +- InstructionTranslatorBase: Base class for converting bytecode to symbolic execution +- InstructionTranslator: Main translator for function bytecode +- InliningInstructionTranslator: Handles inlining of called functions +- SpeculationLog: Manages state for speculative execution and rollback + +The symbolic conversion process handles: +- Control flow (loops, conditionals, etc.) +- Function inlining and call stack management +- Tracking of program values and side effects +- Graph breaks and resumption points +- Exception handling and stack frame management + +This is a core part of TorchDynamo's tracing system that enables ahead-of-time +optimization of PyTorch programs. +""" + +from __future__ import annotations + +import _warnings + +import contextlib +import copy +import dataclasses +import dis +import functools +import importlib +import inspect +import itertools +import linecache +import logging +import operator +import re +import sys +import threading +import time +import traceback +import types +import weakref +from collections import defaultdict, deque +from typing import Any, cast, NoReturn, TYPE_CHECKING, TypeAlias, TypeVar +from typing_extensions import TypeIs + +import torch +import torch._logging +from torch._dynamo.dynamo_profiler import DynamoProfilerState, FunctionTraceTiming +from torch._dynamo.exc import ( + FakeTensorObservedException, + get_dynamo_observed_exception, + ObservedException, + TensorifyScalarRestartAnalysis, +) +from torch._guards import InlinedCodeCache, tracing, TracingContext +from torch._logging.structured import dump_file +from torch.fx.experimental.symbolic_shapes import guard_bool +from torch.utils._functools import cache_method + +from . import ( + config, + exc, + graph_break_hints, + logging as torchdynamo_logging, + trace_rules, + variables, +) +from .bytecode_analysis import ( + get_indexof, + JUMP_OPNAMES, + livevars_analysis, + propagate_line_nums, +) +from .bytecode_transformation import ( + cleaned_instructions, + create_binary_slice, + create_call_function, + create_call_function_ex, + create_copy, + create_dup_top, + create_instruction, + create_jump_absolute, + create_rot_n, + create_swap, + get_call_callable_depth, + get_code_keys, + Instruction, + is_generator, + is_jump_absolute, + unique_id, +) +from .code_context import code_context +from .codegen import PyCodegen +from .comprehension_graph_break import maybe_setup_comprehension_speculation +from .exc import ( + augment_exc_message_with_hop_name, + BackendCompilerFailed, + collapse_resume_frames, + format_frame_info, + get_stack_above_dynamo, + raise_observed_exception, + raise_value_error, + ResumePrologueTracingError, + StepUnsupported, + unimplemented, + Unsupported, + UserError, +) +from .funcname_cache import get_funcname +from .guards import GuardBuilder, install_guard +from .output_graph import ( + CodeOptions, + GraphCompileReason, + OutputGraph, + StackLocalsMetadata, +) +from .polyfills import ( + impl_IS_MAPPING, + impl_MATCH_CLASS, + impl_MATCH_KEYS, + impl_MATCH_SEQUENCE, +) +from .replay_record import DummyModule, ExecutionRecorder +from .resume_execution import ( + ContinueExecutionCache, + IS_TRACING_RESUME_PROLOGUE_VARNAME, + ReenterWith, +) +from .source import ( + AttrSource, + DictGetItemSource, + GlobalSource, + GlobalWeakRefSource, + LocalCellSource, + LocalSource, + SkipGuardSource, + Source, +) +from .trace_rules import is_builtin_constant, is_forbidden +from .utils import ( + _get_error_on_graph_break, + counters, + FrameState, + get_fake_value, + get_instruction_source_311, + get_metrics_context, + graph_break_dup_warning_checker, + istype, + LazyString, + proxy_args_kwargs, + PySendResult, + unpack_iterable, +) +from .variables.base import SourceLocation, typestr, ValueMutationNew, VariableTracker +from .variables.builder import FrameStateSizeEntry, VariableBuilder, wrap_fx_proxy +from .variables.builtin import BuiltinVariable, DictBuiltinVariable +from .variables.constant import ConstantVariable +from .variables.ctx_manager import ( + ContextWrappingVariable, + GenericContextWrappingVariable, + WithEnterFunctionVariable, + WithExitFunctionVariable, +) +from .variables.dicts import ConstDictVariable +from .variables.functions import ( + BaseUserFunctionVariable, + CO_VARARGS, + CO_VARKEYWORDS, + LocalGeneratorFunctionVariable, + LocalGeneratorObjectVariable, + NestedUserFunctionVariable, + SkipFunctionVariable, + UserFunctionVariable, +) +from .variables.iter import MAX_ITERATOR_LIMIT +from .variables.lazy import LazyVariableTracker +from .variables.lists import ( + BaseListVariable, + ListIteratorVariable, + ListVariable, + SliceVariable, + TupleVariable, +) +from .variables.misc import ( + CellVariable, + NullVariable, + PythonModuleVariable, + TracebackVariable, + UnknownVariable, +) +from .variables.nn_module import NNModuleVariable, UnspecializedNNModuleVariable +from .variables.object_protocol import ( + generic_delitem, + generic_getattr, + generic_getiter, + generic_is_true, + generic_setitem, + pyiter_send, + pysequence_contains, +) +from .variables.sets import SetVariable +from .variables.streams import SymbolicStreamState +from .variables.tensor import supported_comparison_ops, SymNodeVariable, TensorVariable +from .variables.torch_function import ( + SymbolicTorchFunctionState, + TorchFunctionModeVariable, +) +from .variables.user_defined import ( + RemovableHandleVariable, + UserDefinedClassVariable, + UserDefinedExceptionClassVariable, + UserDefinedExceptionObjectVariable, + UserDefinedObjectVariable, +) + + +if TYPE_CHECKING: + from collections.abc import Callable, Generator + + from torch._subclasses.fake_tensor import FakeTensorMode + + from .package import CompilePackage + +log = logging.getLogger(__name__) +graph_break_log = torch._logging.getArtifactLogger(__name__, "graph_breaks") +trace_call_log = torch._logging.getArtifactLogger(__name__, "trace_call") +trace_source_log = torch._logging.getArtifactLogger(__name__, "trace_source") +trace_bytecode_log = torch._logging.getArtifactLogger(__name__, "trace_bytecode") +tls = threading.local() +compare_op_handlers: dict[str, Any] = { + k: BuiltinVariable(v).call_function for k, v in supported_comparison_ops.items() +} +handle_contains = BuiltinVariable(operator.contains).call_function +handle_not = BuiltinVariable(operator.not_).call_function +compare_op_handlers["in"] = lambda tx, args, _: handle_contains( + tx, [*reversed(args)], {} +) +compare_op_handlers["not in"] = lambda tx, args, _: handle_not( + tx, [handle_contains(tx, [*reversed(args)], {})], {} +) + +ExceptionVals: TypeAlias = ( + variables.ExceptionVariable | UserDefinedExceptionObjectVariable +) + +ExceptionTypes: TypeAlias = ( + variables.BuiltinVariable | UserDefinedExceptionClassVariable +) + + +@functools.cache +def _import_module(name: str) -> types.ModuleType: + """ + Import the named module and cache the result. importlib.import_module() + seems to do some filesystem checking to validate the name so not caching + this can be slow. + """ + return importlib.import_module(name) + + +def _registered_module_for_globals( + module_name: object, f_globals: dict[str, Any] +) -> tuple[str, types.ModuleType] | None: + if not isinstance(module_name, str) or module_name.startswith("namedtuple_"): + return None + + if "torch_package" in module_name: + module = torch.package.package_importer._package_imported_modules.get( + module_name + ) + else: + module = sys.modules.get(module_name) + + if isinstance(module, types.ModuleType) and module.__dict__ is f_globals: + return module_name, module + + return None + + +@dataclasses.dataclass +class SpeculationEntry: + filename: str + lineno: int + instruction_pointer: int + inst: Instruction # for debugging only + _failed: bool = False + # TX error_on_graph_break setting at the time of failure + error_on_graph_break: bool | None = None + reason: GraphCompileReason | None = None + + def fail_and_restart_analysis(self, error_on_graph_break: bool) -> None: + """ + Start tracing of the current frame over again, and don't take this branch. + """ + self._failed = True + self.error_on_graph_break = error_on_graph_break + if self.reason is not None: + restart_reason = self.reason.reason + else: + restart_reason = "Unknown fail_and_restart_analysis" + raise exc.SpeculationRestartAnalysis(restart_reason=restart_reason) + + def failed(self, tx: InstructionTranslatorBase) -> bool: + if self._failed: + if self.error_on_graph_break is None: + raise AssertionError( + "expected self.error_on_graph_break is not None to be true" + ) + tx.error_on_graph_break = self.error_on_graph_break + return True + return False + + +@dataclasses.dataclass +class SpeculationLog: + """ + SpeculationLog replaces the prior copy_graphstate/restore_graphstate + checkpointing. Rather than saving/restoring state, we restart the + dynamo conversion process over from the beginning -- but when we + hit the start of the speculation that failed, we instead generate + a graph break. + """ + + entries: list[SpeculationEntry] = dataclasses.field(default_factory=list) + index: int = 0 + # If True, graph break at autograd.grad instead of tracing it. + # Set when we detect that autograd.grad consumed grad_fns that are returned. + graph_break_on_autograd_grad: bool = False + # Names of output tensors whose grad_fns were consumed by autograd.grad. + autograd_grad_leaked_tensors: list[str] = dataclasses.field(default_factory=list) + # If True, graph break at requires_grad_() on source-less intermediates + # instead of tracing it. Set when we detect that such an intermediate + # leaks as a graph output with requires_grad=True. + graph_break_on_requires_grad_: bool = False + + def restart(self) -> None: + self.index = 0 + + def clear(self) -> None: + self.entries.clear() + self.index = 0 + + def next( + self, filename: str, lineno: int, instruction_pointer: int, inst: Instruction + ) -> SpeculationEntry: + """ + Lookup or create a SpeculationEntry() that is shared across + RestartAnalysis calls. Args are used only for debug checks. + """ + if len(self.entries) == self.index: + self.entries.append( + SpeculationEntry(filename, lineno, instruction_pointer, inst) + ) + entry = self.entries[self.index] + prev_entry_msg = "" + if self.index != 0: + prev_entry = self.entries[self.index - 1] + prev_entry_msg = ( + f"Previous instruction: {prev_entry.filename}:{prev_entry.lineno}" + f"({prev_entry.inst.opname} @ {prev_entry.instruction_pointer})\n" + ) + if not ( + entry.instruction_pointer == instruction_pointer + and entry.filename == filename + and entry.lineno == lineno + ): + raise SpeculationLogDivergence( + f""" +SpeculationLog diverged at index {self.index} (log had {len(self.entries)} entries): +- Expected: {entry.filename}:{entry.lineno} ({entry.inst.opname} at ip={entry.instruction_pointer}) +- Actual: {filename}:{lineno} ({inst.opname} at ip={instruction_pointer}) +{prev_entry_msg} +There are two usual reasons why this may have occurred: +- When Dynamo analysis restarted, the second run took a different path than + the first. If this occurred, the previous instruction is the critical instruction that + behaved differently. +- Speculation entries are only added under certain conditions (as seen in + step()), e.g., there must exist operators in the graph; those conditions may + have changed on restart. + +If this divergence was intentional, clear the speculation log before restarting (do NOT +do this for graph breaks, you will infinite loop). + +Otherwise, please submit a bug report, ideally including the contents of TORCH_LOGS=+dynamo +""" + ) + self.index += 1 + return entry + + +@dataclasses.dataclass +class LocalState: + automatic_dynamic: dict[str, FrameStateSizeEntry] = dataclasses.field( + default_factory=dict + ) + + def render(self) -> str: + return "\n".join( + f"{k}: {v.render()}" for k, v in self.automatic_dynamic.items() + ) + + +# Mutable box that is shared across restarts +@dataclasses.dataclass +class DistributedState: + compile_pg: Any + local_state: LocalState + all_states: list[LocalState] | None = None + + +class TensorifyState: + # These are the set of string symfloats names (eg. "zf0") that we collect + # from the tensorify_python_scalars.py joint fx pass to inform us about + # which float inputs we should specialize when we restart analysis. + force_specializations: set[str] = set() + + @classmethod + def specialize(cls, index: str) -> None: + cls.force_specializations.add(index) + + @classmethod + def should_specialize(cls, index: str) -> bool: + return index in cls.force_specializations + + @classmethod + def clear(cls) -> None: + cls.force_specializations.clear() + + @classmethod + def empty(cls) -> bool: + return len(cls.force_specializations) == 0 + + +@functools.cache +def _step_logger() -> Callable[..., None]: + return torchdynamo_logging.get_step_logger(log) + + +@contextlib.contextmanager +def save_and_restart_speculation_log( + tx: InstructionTranslatorBase, +) -> Generator[None, None, None]: + # When reconstructing a generator after a graph break, we advance it until + # it is fully exhausted. This process adds new entries to the speculation + # log that were not previously observed. Without temporarily clearing the + # speculation log, this could lead to a divergence error. + + entries = tx.speculation_log.entries + index = tx.speculation_log.index + try: + tx.speculation_log.entries = [] + tx.speculation_log.index = 0 + yield + finally: + tx.speculation_log.entries = entries + tx.speculation_log.index = index + + +@contextlib.contextmanager +def temporarely_allow_writes_to_output_graph( + tx: InstructionTranslatorBase, +) -> Generator[None, None, None]: + try: + tmp = tx.output.should_exit + tx.output.should_exit = False + yield + finally: + tx.output.should_exit = tmp + + +@dataclasses.dataclass +class BlockStackEntry: + # Current instruction that pushes something to block_stack + inst: Instruction + target: Instruction | None + stack_index: int + with_context: ContextWrappingVariable | GenericContextWrappingVariable | None = None + + def can_restore(self) -> bool: + return self.with_context is not None + + def resume_fn(self) -> ReenterWith: + if self.stack_index is None: + raise AssertionError("expected self.stack_index is not None to be true") + if ( + self.with_context + and hasattr(self.with_context, "target_values") + and self.with_context.target_values + ): + return ReenterWith( + self.stack_index - 1, tuple(self.with_context.target_values) + ) + else: + return ReenterWith(self.stack_index - 1) + + def exit( + self, tx: InstructionTranslatorBase, is_graph_break: bool + ) -> VariableTracker | None: + if self.with_context is None: + raise AssertionError("expected self.with_context is not None to be true") + if ( + is_graph_break and self.with_context.exit_on_graph_break() + ) or not is_graph_break: + return self.with_context.exit(tx) # type: ignore[arg-type] + return None + + +class SpeculationLogDivergence(AssertionError): + pass + + +class ReturnValueOp(Exception): + pass + + +class YieldValueOp(Exception): + """ + Signal to the symbolic tracer to stop and return control flow to the + caller + """ + + +def stack_op(fn: Callable[..., object]) -> Callable[..., Any]: + nargs = len(inspect.signature(fn).parameters) + fn_var = BuiltinVariable(fn) + + @functools.wraps(fn) + def impl(self: InstructionTranslator, inst: Instruction) -> None: + self.push(fn_var.call_function(self, self.popn(nargs), {})) + + return impl + + +def is_stdlib(mod: object) -> bool: + if not isinstance(mod, types.ModuleType): + return False + return mod.__name__.split(".")[0] in sys.stdlib_module_names + + +@functools.cache +def get_assert_bytecode_sequence(with_msg: bool) -> list[str]: + if with_msg: + + def fn(x: Any) -> None: + assert x, "msg" # noqa: S101 # function is to recognize assert statements in user code + else: + + def fn(x: Any) -> None: + assert x # noqa: S101 # function is to recognize assert statements in user code + + insts = [inst.opname for inst in dis.get_instructions(fn)] + + # expect to find POP_JUMP_[FORWARD_]IF_TRUE + begin_idx = next(i for i, inst in enumerate(insts) if inst.startswith("POP_JUMP")) + end_idx = insts.index("RAISE_VARARGS") + + return insts[begin_idx + 1 : end_idx + 1] + + +def _detect_and_normalize_assert_statement( + self: InstructionTranslatorBase, + truth_fn: Callable[[object], bool], + push: bool, +) -> bool: + # Detect if this jump instruction is assert and normalize the assert + # by pushing dummy error message when nothing is given. + # + # Python 3.9-3.13 assertion is in following format (minus small differences) + # 18 POP_JUMP_IF_TRUE 28 + # 20 LOAD_ASSERTION_ERROR + # 22 LOAD_CONST 3 ('Assert message') -> optional instruction + # 24 CALL_FUNCTION 1 -> optional instruction + # 26 RAISE_VARARGS + + if (truth_fn is not operator.truth) or push: + return False + + if not isinstance(self.instruction_pointer, int): + raise AssertionError( + "expected isinstance(self.instruction_pointer, int) to be true" + ) + current_instruction_pointer = self.instruction_pointer + + for with_msg in (False, True): + assert_insts = get_assert_bytecode_sequence(with_msg) + cur_insts = self.instructions[ + current_instruction_pointer : current_instruction_pointer + + len(assert_insts) + ] + cur_insts = [inst.opname for inst in cur_insts] + if cur_insts == assert_insts: + if with_msg: + load_const_idx = assert_insts.index("LOAD_CONST") + error_msg = self.instructions[ + current_instruction_pointer + load_const_idx + ].argval + else: + error_msg = "assertion error" + self.push(VariableTracker.build(self, error_msg)) + return True + + return False + + +explain = False + + +# [NOTE] graph break handling in symbolic_convert +# There are 4 possible graph break cases that InstructionTranslatorBase handles: +# 1. Regular graph breaks from CALL, BINARY_SUBSCR, etc. (implemented by break_graph_if_unsupported) +# 2. Data-dependent condition graph breaks (implemented by generic_jump) +# 4. All other unhandled graph breaks - unsupported step graph breaks (implemented in InstructionTranslatorBase.step) +# +# Graph breaks are handled in the following manner: +# 1. The Unsupported exception is caught. If we cannot compile a partial graph (should_compile_partial_graph() is False), +# then propagate the exception upward. For unsupported step graph breaks, the condition to abort partial compilation is +# more restrictive (see InstructionTranslatorBase.step). +# 2. If the Unsupported exception escapes symbolic_convert.py, then we are done. +# Otherwise, we want to attempt partial compilation. +# Log the graph break via log_graph_break. If we're handling a data-dependent graph break (type 2.), then we can immediately +# codegen the compiled graph and resume function and we're done. This is because the jump instruction we graph break on is +# limited in how it can manipulate Python state (say, in comparison, to CALL, which can modify Python state arbitrarily). +# Otherwise, we need to restart compilation. We need to restart because by processing the unsupported instruction, +# we may have modified the VariableTrackers, and we need all of our VariableTrackers to be in the state BEFORE tracing the +# unsupported instruction. +# 3. During the first compilation, we updated a speculation log, indicating points in the code that we can resume from. +# On the second compilation, we will stop tracing at the first speculation log that fails. Then we compile the partial +# graph and resume function. +# +# Logging invariants: +# 1. No logs need to be made if Unsupported escapes symbolic_convert.py. Python's default exception printing will +# print out all of the necessary information and no partial compilation will be attempted. +# 2. log_graph_break should be called as soon as Unsupported is caught and we determined we want to partial compile. +# This always happens on the first compilation, NOT the restart handling this graph +# 3. Any compile_subgraph call should be preceded immediately by a log in the form of "... triggered compile". + + +def get_node_source_info(n: torch.fx.Node) -> str: + """Extract the innermost user source location from an FX node's stack trace.""" + st = n.meta.get("stack_trace", "") or getattr(n, "stack_trace", "") + if not st: + return "" + trace_lines = st.strip().split("\n") + last_file_idx = -1 + for i, line in enumerate(trace_lines): + if line.strip().startswith("File "): + last_file_idx = i + if last_file_idx < 0: + return "" + file_line = trace_lines[last_file_idx].strip() + code = "" + if last_file_idx + 1 < len(trace_lines): + code = trace_lines[last_file_idx + 1].strip() + return f"{file_line}" + (f", code: {code}" if code else "") + + +def format_tensor_computation_trace(value: VariableTracker, max_lines: int = 20) -> str: + """Walk the FX graph backwards from a TensorVariable to show how it was + computed, with user source locations. Graph inputs (placeholders) are always + shown first, followed by operations in dataflow order ending at the branch + condition.""" + if not isinstance(value, TensorVariable): + return "" + try: + node = value.proxy.node + + # Collect operations and placeholders separately so placeholders (root + # cause) always appear first regardless of traversal order. + op_blocks: list[list[str]] = [] + placeholder_blocks: list[list[str]] = [] + visited: set[str] = set() + + def fmt_arg(a: object) -> str: + return a.name if isinstance(a, torch.fx.Node) else repr(a) + + def walk(n: torch.fx.Node) -> None: + if n.name in visited: + return + visited.add(n.name) + source = get_node_source_info(n) + + if n.op == "placeholder": + block = [] + if source: + block.append(f"# {source}") + block.append(f"{n.name}: graph input ({n.target})") + placeholder_blocks.append(block) + return + + if n.op == "call_function" and len(op_blocks) < max_lines: + target_name = getattr(n.target, "__name__", str(n.target)) + args_str = ", ".join(fmt_arg(a) for a in n.args) + block = [] + if source: + block.append(f"# {source}") + block.append(f"{n.name} = {target_name}({args_str})") + op_blocks.append(block) + + for a in n.args: + if isinstance(a, torch.fx.Node): + walk(a) + + walk(node) + + if not op_blocks and not placeholder_blocks: + return "" + + # Placeholders first (root cause), then ops in dataflow order (reversed + # from the DFS collection order) ending at the branch condition. + all_lines: list[str] = [] + for block in placeholder_blocks + list(reversed(op_blocks)): + all_lines.extend(block) + all_lines.append("") + + return ( + "\n\n The branch condition involves a tensor computed as follows:\n" + + "\n".join(f" {line}" for line in all_lines) + ) + except Exception: + log.debug("format_tensor_computation_trace failed", exc_info=True) + return "" + + +def generic_jump( + truth_fn: Callable[[object], bool], push: bool +) -> Callable[[InstructionTranslatorBase, Instruction], None]: + def raise_jump_graph_break(value: VariableTracker) -> NoReturn: + trace_info = format_tensor_computation_trace(value) + hints: list[str] = [] + if isinstance(value, TensorVariable): + try: + node = value.proxy.node + example = node.meta.get("example_value") + if ( + example is not None + and example.dim() == 0 + and example.dtype + in ( + torch.int32, + torch.int64, + ) + ): + hints.append( + "The branch condition uses a scalar integer tensor. " + "Consider rewriting the computation to use plain Python " + "ints (e.g. use int attributes instead of tensor buffers) " + "so the condition becomes a shape guard instead of " + "data-dependent branching." + ) + if ( + example is not None + and example.dim() == 0 + and example.dtype == torch.bool + ): + hints.append( + "For the common pattern `if tensor_cond: x = transform(x)` " + "(e.g. clamping inf/nan values), consider making the code " + "branchless by always applying the transform. Operations like " + "torch.clamp, torch.nan_to_num, and torch.where are typically " + "no-ops on well-behaved inputs and compile without graph breaks." + ) + # Detect boolean reductions (any/all) which are a telltale sign + # of `tensor.any() or other_tensor.any()` patterns. + # node.target is a str for call_method nodes (e.g. tensor.any()) + # and a callable for call_function nodes (e.g. torch.any()). + target_name = getattr(node.target, "__name__", None) or ( + node.target if isinstance(node.target, str) else None + ) + if target_name in ("any", "all", "bitwise_and", "bitwise_or"): + hints.append( + "Note: Python `or`/`and` between tensor expressions (e.g. " + "`tensor.any() or other_tensor.any()`) triggers implicit bool " + "conversion. Use `torch.logical_or`/`torch.logical_and` or the " + "`|`/`&` operators instead." + ) + except Exception: + pass + hints.extend(graph_break_hints.FUNDAMENTAL) + hints.append("Use `torch.cond` to express dynamic control flow.") + unimplemented( + gb_type="Data-dependent branching", + context=f"attempted to jump with {value}", + explanation="Detected data-dependent branching (e.g. `if my_tensor.sum() > 0:`). " + "Dynamo does not support tracing dynamic control flow." + trace_info, + hints=hints, + ) + + def jump_graph_break( + self: InstructionTranslatorBase, + inst: Instruction, + value: VariableTracker, + extra_msg: str = "", + ) -> None: + if not self.should_compile_partial_graph(): + raise AssertionError( + "expected self.should_compile_partial_graph() to be true" + ) + + exc = None + try: + raise_jump_graph_break(value) + except (Unsupported, UserError) as e: + exc = e + + if exc is None: + raise AssertionError("expected exc is not None to be true") + + # compile a partial subgraph prefix then skip the rest of user code + if self.maybe_has_backedge(): + self.raise_loop_graph_break(self.f_code, exc) + + self.log_graph_break( + self.code_options, + reason=str(exc), + exc=exc, + ) + + self.push(value) + log.debug("generic_jump triggered compile") + all_stack_locals_metadata = self.output.compile_subgraph( + self, + reason=GraphCompileReason( + f"generic_jump {typestr(value)}{extra_msg}", [self.frame_summary()] + ), + stack_pops=1, + ) + self.pop() + + if_next = self.create_call_resume_at( + self.next_instruction, + all_stack_locals_metadata, + ) + if push: + self.push(value) + if inst.target is None: + raise AssertionError("expected inst.target is not None to be true") + if_jump = self.create_call_resume_at( + inst.target, + all_stack_locals_metadata, + ) + + if sys.version_info >= (3, 13): + # 3.13 requires stack[-1] to be bool type + self.output.add_output_instructions([create_instruction("TO_BOOL")]) + + jump_inst = create_instruction(inst.opname, target=if_jump[0]) + # For inlined frames, use the root frame's current instruction + # positions so the output code maps to the correct source line. + positions_inst = ( + self.output.root_tx.current_instruction if self.parent is not None else inst + ) + jump_inst.copy_positions(positions_inst) + self.output.add_output_instructions([jump_inst] + if_next + if_jump) + + def inner(self: InstructionTranslatorBase, inst: Instruction) -> None: + value: VariableTracker = self.pop() + if ( + config.rewrite_assert_with_torch_assert + and sys.flags.optimize == 0 + and _detect_and_normalize_assert_statement(self, truth_fn, push) + ): + error_msg: VariableTracker = self.pop() + # Skip over things like `assert True` + if value.is_python_constant(): + if bool(value.as_python_constant()): + return self.jump(inst) + elif self.should_compile_partial_graph(): + jump_graph_break(self, inst, value) + return + else: + unimplemented( + gb_type="Data-dependent assertion failed (cannot compile partial graph)", + context=f"value: {value}", + explanation="Dynamo has determined when encountering a data-dependent assert failure " + "that it should not compile the partial graph.", + hints=[ + *graph_break_hints.FUNDAMENTAL, + "Use `torch._assert()` to raise a hard AssertionError when the check fails. " + "This error will propagate back the user code " + "that called the compiled function (i.e. Dynamo will not trace any exception handling).", + "Remove the assert statement.", + "Move the assert statement outside of any context managers in order to graph break with " + "partial graph compilation (if fullgraph=False).", + ], + ) + + # TODO maybe should respect DtoH sync intention of users later?? + # Manually insert torch._assert_async instead of python assert and jump over + # assert related instructions as we don't need them anymore. + + # if we see Tensor as assert statement, no need to call scalar_tensor + if value.is_tensor(): + self.output.create_proxy( + "call_function", + torch._assert_async, + *proxy_args_kwargs((value, error_msg), {}), + ) + self.jump(inst) + return + + if isinstance(value, SymNodeVariable): + # if the assertion is normal shape expression. + # just install guard and bail out. + sym_expr = value.sym_num + if not isinstance(sym_expr, torch.SymBool): + sym_expr = sym_expr != 0 + + result = torch.fx.experimental.symbolic_shapes.expect_true(sym_expr) + if not result: + unimplemented( + gb_type="Assertion failed on symbolic shapes", + context=str(sym_expr), + explanation="", + hints=[*graph_break_hints.USER_ERROR], + ) + self.jump(inst) + return + + scalar_to_tensor_proxy = self.output.create_proxy( + "call_function", torch.scalar_tensor, *proxy_args_kwargs((value,), {}) + ) + + scalar_to_tensor = wrap_fx_proxy( + self, + scalar_to_tensor_proxy, + example_value=get_fake_value(scalar_to_tensor_proxy.node, self), + ) + + self.output.create_proxy( + "call_function", + torch._assert_async, + *proxy_args_kwargs((scalar_to_tensor, error_msg), {}), + ) + self.jump(inst) + return + + if value.is_python_constant(): + # ConstDictVariable is optimized to be very lazy about insertion of + # guards, so we have to manually insert a SEQUENCE_LENGTH guard + # here. + if isinstance(value, ConstDictVariable) and value.source: + install_guard(value.source.make_guard(GuardBuilder.SEQUENCE_LENGTH)) + if truth_fn(value.as_python_constant()): + if push: + self.push(value) + self.jump(inst) + elif value.is_tensor() and self.should_compile_partial_graph(): + jump_graph_break(self, inst, value) + elif isinstance(value, NNModuleVariable): + # Equivalent of "self.nn_module is not None" + mod = self.output.get_submodule(value.module_key) + if truth_fn(mod): + if push: + self.push(value) + self.jump(inst) + elif isinstance(value, UserDefinedObjectVariable): + result = generic_is_true(self, value) # type: ignore[arg-type] + if result.is_python_constant(): + if truth_fn(result.as_python_constant()): + if push: + self.push(value) + self.jump(inst) + elif isinstance(result, SymNodeVariable): + if truth_fn(result.evaluate_expr()): + if push: + self.push(value) + self.jump(inst) + else: + unimplemented( + gb_type="Data-dependent branching with non-constant __bool__", + context=f"value: {value}, result: {result}", + explanation="Attempted to perform data-dependent branching on a user-defined " + "object with non-constant truthiness.", + hints=[], + ) + elif isinstance(value, SymNodeVariable): + try: + # if the user is branching on a SymBool, guard on it + # if the user has code like: + # if size: + # ... + # then they are just testing truthiness: guard that the expr != 0 + if isinstance(value.sym_num, torch.SymBool): + eval_result = value.evaluate_expr(self.output) + else: + eval_result = guard_bool(value.sym_num != 0) + except exc.UserError as e: + if self.should_compile_partial_graph(): + return jump_graph_break(self, inst, value, extra_msg=f"\n{e}") + raise + if truth_fn(eval_result): + if push: + self.push(value) + self.jump(inst) + elif not value.is_tensor(): + result = generic_is_true(self, value) # type: ignore[arg-type] + if truth_fn(result): + if push: + self.push(value) + self.jump(inst) + elif isinstance(value, variables.BackwardHookVariable): + if truth_fn(True): + if push: + self.push(value) + self.jump(inst) + else: + from .source import is_constant_source + + if value.source is not None and is_constant_source(value.source): + if truth_fn(value.get_real_value()): # type: ignore[attr-defined] + if push: + self.push(value) + self.jump(inst) + else: + raise_jump_graph_break(value) + + return inner + + +def _reconstruct_block_stack( + tx: InstructionTranslatorBase, cg: PyCodegen, cleanup: list[Instruction] +) -> None: + """Generates bytecode to restore the block stack for running the unsupported instruction + in the compiled bytecode.""" + # Reconstruct the context variable CLASS in the block stack + all_txes: list[InstructionTranslatorBase] = [] + cur_tx: InstructionTranslatorBase | None = tx + while cur_tx is not None: + all_txes.append(cur_tx) + cur_tx = cur_tx.parent + for tx in reversed(all_txes): + for b in tx.block_stack: + # Don't exit any modes we have entered -- + # output bytecode will push/pop the tf mode stack, + # so we only need a try/except to pop on exception. + if isinstance(b.with_context, TorchFunctionModeVariable): + cg.extend_output( + b.resume_fn().try_except_torch_function_mode( + cg.code_options, cleanup + ) + ) + continue + if b.with_context is None: + raise AssertionError("expected b.with_context is not None to be true") + if not isinstance(b.with_context, (ContextWrappingVariable)): + raise AssertionError( + "expected isinstance(b.with_context, (ContextWrappingVariable)) to be true" + ) + b.with_context.reconstruct_type(cg) + cg.extend_output(b.resume_fn().try_finally(cg.code_options, cleanup)) + + +def _make_warnings_warn_wrapper(filename: str, lineno: int) -> Callable[..., Any]: + """Create a wrapper for warnings.warn that reports the given source location. + + When warnings.warn (stacklevel=1) inspects its caller frame, it sees the + wrapper's code object -- whose co_filename and line table point to the + original leaf-frame location. This preserves Python's per-location + warning dedup even when the call is inlined into a different frame by + nested graph breaks. + """ + import warnings + + # Use a lambda so all bytecode is on one line and co_firstlineno + # equals the body line (no off-by-one vs a multi-line def). + wrapper: Callable[..., Any] = lambda *args, **kwargs: warnings.warn(*args, **kwargs) # noqa: E731 + wrapper.__code__ = wrapper.__code__.replace( + co_filename=filename, + co_firstlineno=lineno, + ) + return wrapper + + +# NOTE: for the purposes of nested graph breaks, break_graph_if_unsupported only works on instructions +# with 0 or 1 outputs. If you wish to support bytecodes with 2+ outputs, either rewrite the instruction +# into a sequence of simpler instructions, or file an issue for consultation. +# There is an additional requirement that if the instruction causes a function call, e.g. STORE_ATTR, +# nothing should happen to the result of the function call. +def break_graph_if_unsupported( + *, push: bool, msg_prefix: str +) -> Callable[ + [Callable[..., None]], Callable[[InstructionTranslatorBase, Instruction], None] +]: + def decorator( + inner_fn: Callable[..., None], + ) -> Callable[[InstructionTranslatorBase, Instruction], None]: + @functools.wraps(inner_fn) + def wrapper(self: InstructionTranslatorBase, inst: Instruction) -> None: + prev_push = self.current_instruction_push + self.current_instruction_push = push + speculation = self.speculate() + if speculation.failed(self): + # no need to restore current_instruction_push if speculation failed + if speculation.reason is None: + raise AssertionError( + "expected speculation.reason is not None to be true" + ) + return handle_graph_break(self, inst, speculation.reason) + try: + return inner_fn(self, inst) + except (Unsupported, UserError) as excp: + if self.active_generic_context_managers: + # raise original graph break if fullgraph/error_on_graph_break=True + if self.one_graph or self.error_on_graph_break: + raise + + # We don't support graph break under GenericContextWrappingVariable, + # If there is, we roll back to the checkpoint and fall back. + if isinstance(excp, Unsupported): + excp.remove_from_stats() + unimplemented( + gb_type="Graph break under GenericContextWrappingVariable", + context=f"Active generic context managers: {self.active_generic_context_managers}", + explanation="Attempted to graph break in an active context manager(s) that doesn't support graph breaking.", + hints=[ + "Move the offending context manager(s) to outside the compiled region.", + *graph_break_hints.CAUSED_BY_EARLIER_GRAPH_BREAK, + ], + from_exc=excp, + ) + + if getattr(excp, "skip_frame", False): + raise + + if not self.should_compile_partial_graph(): + raise + + if self.maybe_has_backedge(): + self.raise_loop_graph_break(self.f_code, excp) + + self.log_graph_break( + self.code_options, + reason=f"{msg_prefix}:\n\n{str(excp)}", + exc=excp, + ) + + if isinstance(excp, Unsupported): + excp.remove_from_stats() + excp.add_to_stats("graph_break") + speculation.reason = GraphCompileReason( + getattr(excp, "msg", str(excp)), + getattr(excp, "real_stack", [self.frame_summary()]), + ) + finally: + self.current_instruction_push = prev_push + speculation.fail_and_restart_analysis(self.error_on_graph_break) + + def handle_graph_break( + self: InstructionTranslatorBase, + inst: Instruction, + reason: GraphCompileReason, + ) -> None: + if ( + sys.version_info >= (3, 11) + and sys.version_info < (3, 12) + and inst.opname == "CALL" + ): + # stack effect for PRECALL + CALL is split between the two instructions + stack_effect = dis.stack_effect( + dis.opmap["PRECALL"], inst.arg + ) + dis.stack_effect(dis.opmap["CALL"], inst.arg) + else: + stack_effect = dis.stack_effect(inst.opcode, inst.arg) + + # When warnings.warn is called from an inlined frame, replace + # it on the symbolic stack before compile_subgraph so the codegen + # naturally reconstructs the wrapper via LOAD_GLOBAL. + if self.parent is not None: + self._maybe_replace_warnings_warn_on_stack(inst) + + log.debug("%s triggered compile", inst.opname) + all_stack_locals_metadata = self.output.compile_subgraph( + self, reason=reason, stack_pops=int(push) - stack_effect + ) + cg = PyCodegen(self.output.root_tx) + cleanup: list[Instruction] = [] + _reconstruct_block_stack(self, cg, cleanup) + self.output.add_output_instructions(cg.get_instructions()) + del cg + + # For inlined frames, use the root frame's current instruction + # positions so the output code maps to the correct source line. + # The output code is always for the root function, so line numbers + # from inlined child frames would be wrong. + positions_inst = ( + self.output.root_tx.current_instruction + if self.parent is not None + else inst + ) + + if sys.version_info >= (3, 11) and inst.opname == "CALL": + kw_names = ( + self.kw_names.as_python_constant() + if self.kw_names is not None + else () + ) + if len(kw_names) > 0: + # KW_NAMES no longer used in 3.13 + if not (sys.version_info < (3, 13)): + raise AssertionError( + "expected sys.version_info < (3, 13) to be true" + ) + self.output.add_output_instructions( + [create_instruction("KW_NAMES", argval=kw_names)] + ) + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + call_insts = create_call_function(inst.arg, False) + call_insts[-1].copy_positions(positions_inst) + self.output.add_output_instructions(call_insts) + else: + # copy instruction, but without exception table data + if inst.target is not None: + raise AssertionError("expected inst.target is None to be true") + inst_copy = copy.copy(inst) + inst_copy.exn_tab_entry = None + inst_copy.copy_positions(positions_inst) + self.output.add_output_instructions([inst_copy]) + + self.output.add_output_instructions(cleanup) + + self.popn(int(push) - stack_effect) + if push: + self.push(UnknownVariable()) + self.output.add_output_instructions( + self.create_call_resume_at( + self.next_instruction, + all_stack_locals_metadata, + ) + ) + + return wrapper + + return decorator + + +class BytecodeDispatchTableMeta(type): + """Installs a `cls.dispatch_table` on every subclass to speed up calls to self.OPCODE()""" + + def __init__(cls: type, name: str, bases: Any, dct: Any) -> None: + super().__init__(name, bases, dct) # type: ignore[misc] + + def _missing(opname: str, *args: Any) -> None: + unimplemented( + gb_type="Missing bytecode handler", + context=f"{opname} with args {args}", + explanation=f"Dynamo does not know how to handle the bytecode instruction `{opname}`.", + hints=[ + f"Do not trace code that produces the `{opname}` bytecode instruction " + "(see https://docs.python.org/3/library/dis.html for bytecode semantics).", + *graph_break_hints.SUPPORTABLE, + ], + ) + + dispatch_table = { + op: getattr(cls, opname, functools.partial(_missing, opname)) + for opname, op in dis.opmap.items() + } + cls.dispatch_table = [dispatch_table.get(i) for i in range(2**8)] + + +def pyexception_class_check(val: VariableTracker) -> TypeIs[ExceptionTypes]: + # Mirror's CPython PyExceptionClass_Check + # https://github.com/python/cpython/blob/60403a5409ff2c3f3b07dd2ca91a7a3e096839c7/Include/pyerrors.h#L60-L62 + if isinstance(val, variables.BuiltinVariable): + return issubclass(val.fn, BaseException) + return isinstance(val, UserDefinedExceptionClassVariable) + + +def pyexception_instance_check(val: VariableTracker) -> TypeIs[ExceptionVals]: + # Mirror's CPython PyExceptionInstance_Check + # https://github.com/python/cpython/blob/60403a5409ff2c3f3b07dd2ca91a7a3e096839c7/Include/pyerrors.h#L64-L65 + return isinstance( + val, (variables.ExceptionVariable, UserDefinedExceptionObjectVariable) + ) + + +def pyerr_given_exception_match(err: VariableTracker, exc: type[BaseException]) -> bool: + # Mirror's PyErr_GivenExceptionMatch + if pyexception_class_check(err): + return issubclass(err.fn, exc) + if pyexception_instance_check(err): + return issubclass(err.exc_type, exc) + return False + + +def pygen_fetch_stopiteration_value(val: ExceptionVals) -> VariableTracker: + # Mirror's CPython PyGen_FetchStopIterationValue + if issubclass(val.exc_type, StopIteration): + return val.args[0] if val.args else ConstantVariable.create(None) + return ConstantVariable.create(None) + + +@dataclasses.dataclass +class Segment: + """ + One frame's slice of the exception stack, mirroring CPython's + `_PyErr_StackItem` (`gi_exc_state`). + + CPython represents the exc_state as a linked list of `_PyErr_StackItem`s, + where each item contains the exception type, value, and traceback for the + frame. We simulate this with a linked list of `Segment`s, where each + `Segment` is a list of `ExceptionVals` + """ + + items: list[ExceptionVals] = dataclasses.field(default_factory=list) + prev: Segment | None = dataclasses.field(default=None) + + +@dataclasses.dataclass +class ExceptionStack: + """ + Exception stack that it is shared among all InstructionTranslator instances + """ + + # Exception handling in CPython is a bit confusing and some of the bytecode + # have a slightly different behavior than what is documented. While reading + # the documentation, is important to notice that the terms "current exception" + # and "stack" sometimes refers to a C variable with the same name and the + # exception stack, respectively. + # + # The lifetime of an exception is (Python 3.11+): + # + tx._raise_exception_variable(...) := sets the current_exception variable + # + PUSH_EXC_INFO := pushes the current_exception to the *exception stack* + # + POP_EXCEPT := pops TOS from the *exception stack* + + _exc_stack: Segment = dataclasses.field(default_factory=Segment) + _current_exception: ExceptionVals | None = dataclasses.field(default=None) + + def push_segment(self, segment: Segment) -> None: + """Make `segment` the head, linking it to the current head (resume).""" + segment.prev = self._exc_stack + self._exc_stack = segment + + def pop_segment(self) -> Segment: + """Restore the head to the segment below (suspend).""" + segment = self._exc_stack + if segment.prev is None: + raise AssertionError("cannot pop the base exception segment") + self._exc_stack = segment.prev + segment.prev = None + return segment + + def clear_current_exception(self) -> None: + self._current_exception = None + + def set_raised_exception(self, val: ExceptionVals) -> None: + # Mirrors CPython's PyErr_SetRaisedException + self._current_exception = val + + def get_topmost_exception(self) -> ExceptionVals: + if not len(self): + raise AssertionError("expected len(self.exn_vt_stack) to be true") + return self.__getitem__(-1) + + def move_current_exception_to_stack(self) -> None: + if self._current_exception is None: + raise AssertionError( + "expected self._current_exception is not None to be true" + ) + self.append(self._current_exception) + self.clear_current_exception() + + def get_raised_exception(self) -> ExceptionVals: + # Mirrors CPython's PyErr_GetRaisedException() + if self._current_exception is None: + raise AssertionError( + "expected self._current_exception is not None to be true" + ) + return self._current_exception + + def _set_context_recursive( + self, val: ExceptionVals, prev_idx: int + ) -> ExceptionVals: + if (ctx := val.__context__) and not ctx.is_constant_none(): # type: ignore[union-attr] + return val + if len(self) + prev_idx > 0: + prev = self[prev_idx] + self._set_context_recursive(prev, prev_idx - 1) + if prev is not val: + val.set_context(prev) # type: ignore[union-attr, arg-type] + return val + + def _break_context_reference_cycle(self, val: ExceptionVals) -> None: + # See test_exceptions::test_raise_does_not_create_context_chain_cycle + # Based on https://github.com/python/cpython/blob/e635bf2e49797ecb976ce45a67fce2201a25ca68/Python/errors.c#L207-L228 + # As noted on CPython, this is O(chain length) but the context chains + # are usually very small + o = slow_o = val + slow_update_toggle = False # floyd's algorithm for detecting cycle + while True: + context = o.__context__ # type: ignore[union-attr] + if context.is_constant_none(): + break + + if context is val: + o.set_context(ConstantVariable.create(None)) # type: ignore[union-attr, arg-type] + break + + o = context # type: ignore[assignment] + if o is slow_o: + # pre-existing cycle - all exceptions on the path were + # visited and checked + break + + if slow_update_toggle: + # visited all exceptions + slow_o = slow_o.__context__ # type: ignore[union-attr, assignment] + slow_update_toggle = not slow_update_toggle + + def _set_context_and_break_context_reference_cycle( + self, val: ExceptionVals + ) -> None: + # set Exception.__context__ + self._set_context_recursive(val, len(self) - 1) + self._break_context_reference_cycle(val) + + def pop(self) -> ExceptionVals: + return self._exc_stack.items.pop() + + def append(self, val: ExceptionVals) -> None: + self._exc_stack.items.append(val) + + def __len__(self) -> int: + n = 0 + segment: Segment | None = self._exc_stack + while segment is not None: + n += len(segment.items) + segment = segment.prev + return n + + def __getitem__(self, index: int) -> ExceptionVals: + # Global indexing over the segment chain: `prev` segments (lower) + # concatenated with the head segment (upper), so `[-1]` falls through + # to the caller when the head segment is empty. + n = len(self) + if index < 0: + index += n + if not 0 <= index < n: + raise IndexError("exception stack index out of range") + segment = self._exc_stack + base = n - len(segment.items) + while index < base: + if segment.prev is None: + raise AssertionError("expected segment.prev to not be None") + segment = segment.prev + base -= len(segment.items) + return segment.items[index - base] + + def __str__(self) -> str: + return f"{self._exc_stack=} - {self._current_exception=}" + + __repr__ = __str__ + + +class InstructionTranslatorBase( + metaclass=BytecodeDispatchTableMeta, +): + output: OutputGraph + symbolic_locals: dict[str, VariableTracker] + # Registry of this frame's cells (cellvars + freevars), recorded at frame + # setup. `symbolic_locals` models localsplus slot contents, which + # fast-local ops may legitimately clobber (LOAD_FAST_AND_CLEAR in inlined + # comprehensions evicts a merged cell slot; a comprehension iteration + # variable shadowing an enclosing `nonlocal` reuses the cell's name for a + # distinct fast slot). The registry survives such slot traffic so cell + # lookups and cell codegen at a graph break never depend on what the slot + # happens to hold. See `_cellvar` for the resolution rule. + symbolic_cellvars: dict[str, VariableTracker] + symbolic_globals: dict[str, VariableTracker] + symbolic_torch_function_state: SymbolicTorchFunctionState + symbolic_stream_state: SymbolicStreamState + post_prune_cell_and_freevars: dict[str, VariableTracker] | None + stack: list[VariableTracker] + instruction_pointer: int | None + current_instruction: Instruction + current_instruction_push: bool + block_stack: list[BlockStackEntry] + lineno: int + kw_names: ConstantVariable | None + accept_prefix_inst: bool + prefix_insts: list[Instruction] + inline_depth: int + inconsistent_side_effects: bool + current_speculation: SpeculationEntry | None + dispatch_table: list[Any] + exn_vt_stack: ExceptionStack + exec_recorder: ExecutionRecorder | None + strict_checks_fn: Callable[[VariableTracker], bool] | None + start_point: int | None + # Does this function make no inlined function calls? + has_no_inlined_calls: bool + parent: InstructionTranslatorBase | None + # Does this tx currently have a child tx tracing? + # Used to correctly implement should_compile_partial_graph + is_child_tracer_active: bool + debug_locals: list[tuple[VariableTracker, list[VariableTracker]]] + package: CompilePackage | None + latest_bytecode_queue: deque[str] + # Store the latest bytecode before graph_break() call by user + + def mark_inconsistent_side_effects(self) -> None: + """ + InstructionTranslator has encountered instructions which may cause + dynamo to see a different version of history from eager + See: https://github.com/pytorch/pytorch/issues/110765 + """ + self.inconsistent_side_effects = True + + def maybe_has_backedge(self) -> bool: + # This function employs a heuristic. It does not reliably detect a backedge. + # The heuristic is straightforward: starting from the current instruction and + # continuing to the end, if any jump instruction targets an instruction before + # the current one, there might be a backedge. + + # Python 3.12 introduced changes to bytecode that group common paths in + # blockstacks (with or try...else) and allow for early returns. Consequently, + # there can be multiple RETURN_VALUE instructions. Another heuristic is to + # halt detection upon encountering the first RETURN_VALUE or RETURN_CONST. + + # These heuristics can result in both false positives and negatives, but + # in either case, the Dynamo code remains valid. For false positives + # (where an edge is incorrectly marked as a backedge), Dynamo will + # graph break with a frame skip instead of potentially applying optimizations. For + # false negatives (where an edge that should be marked as a backedge + # isn't), multiple graphs may be generated if there's a break in the + # graph during a for loop. In general, its better to have fewer false + # negatives so that Dynamo does not skip the whole frame. + + # If any parent tx has a backedge, then return True + cur_tx: InstructionTranslatorBase | None = self + while cur_tx is not None: + cur_offset = cur_tx.current_instruction.offset + if cur_tx.instruction_pointer is None: + raise AssertionError( + "expected cur_tx.instruction_pointer is not None to be true" + ) + for inst in cur_tx.instructions[cur_tx.instruction_pointer :]: + if inst.opname in ("RETURN_VALUE", "RETURN_CONST"): + break + if inst.opname in JUMP_OPNAMES: + jump_offset = inst.argval + if jump_offset < cur_offset: + return True + cur_tx = cur_tx.parent + return False + + def cellvars(self) -> tuple[str, ...]: + return self.code_options["co_cellvars"] + + def freevars(self) -> tuple[str, ...]: + return self.code_options["co_freevars"] + + def new_pycode_varname(self, prefix: str) -> str: + """Generate a fresh, unique pycode-local variable name for the given prefix.""" + name = f"__{prefix}{next(self._pycode_varname_counter[prefix])}" + self._pycode_last_varname[prefix] = name + return name + + def reset_pycode_varname_counter(self, prefix: str) -> None: + self._pycode_varname_counter[prefix] = itertools.count(0) + + def get_pycode_last_varname(self, prefix: str) -> str: + """Return the most recently generated pycode varname for the given prefix.""" + return self._pycode_last_varname[prefix] + + def cell_and_freevars(self) -> tuple[str, ...]: + if not hasattr(self, "_cell_and_freevars"): + self._cell_and_freevars = self.cellvars() + self.freevars() + return self._cell_and_freevars + + def _register_cells(self) -> None: + # Record this frame's cells in the symbolic_cellvars registry. A free + # var that shares its name with a fast local occupies a second, + # distinct localsplus slot in CPython (e.g. an inlined comprehension + # iteration variable shadowing an enclosing `nonlocal`); it is removed + # from symbolic_locals so fast-local ops on the name can't touch it. + # Cellvars that match a fast local are merged into one slot by CPython, + # so they (and non-colliding cells) stay in symbolic_locals as slot + # contents too. Idempotent: re-registering is a no-op. + fastlocals = set(self.f_code.co_varnames) + for name in self.cell_and_freevars(): + if name in self.symbolic_locals: + self.symbolic_cellvars[name] = self.symbolic_locals[name] + for name in self.f_code.co_freevars: + if name in fastlocals: + self.symbolic_locals.pop(name, None) + + def prune_dead_locals(self) -> None: + # keep cell and freevar references alive + self.post_prune_cell_and_freevars = { + name: self._cellvar(name) for name in self.cell_and_freevars() + } + # Only keep the locals that must remain on the stack. + reads = livevars_analysis(self.instructions, self.current_instruction) + # inspect.signature() renames ".N" to "implicitN" for comprehension + # iterator variables because dotted names aren't valid identifiers. + # Normalize reads to match symbolic_locals keys. + normalized_reads = set() + for r in reads: + normalized_reads.add(r.replace(".", "implicit") if r.startswith(".") else r) + self.symbolic_locals = { + k: v for k, v in self.symbolic_locals.items() if k in normalized_reads + } + + def call_function( + self, + fn: VariableTracker, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> None: + if not isinstance(fn, VariableTracker): + raise AssertionError("expected isinstance(fn, VariableTracker) to be true") + if not isinstance(args, list): + raise AssertionError("expected isinstance(args, list) to be true") + if not isinstance(kwargs, dict): + raise AssertionError("expected isinstance(kwargs, dict) to be true") + if not all( + isinstance(x, VariableTracker) + for x in itertools.chain(args, kwargs.values()) + ): + raise AssertionError( + "expected all( isinstance(x, VariableTracker) for x in itertools.chain(args, kwargs.values()) ) to be true" + ) + inner_fn = None + if hasattr(fn, "value"): + inner_fn = fn.value + if hasattr(fn, "fn"): + inner_fn = fn.fn + if inner_fn is not None and callable(inner_fn) and is_forbidden(inner_fn): + raise AssertionError(f"Attempt to trace forbidden callable {inner_fn}") + self.push(fn.call_function(self, args, kwargs)) # type: ignore[arg-type] + + def inline_generator_function( + self, + fn: BaseUserFunctionVariable, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + """ + Redirect the call to the generator "call_function" + """ + if not isinstance(fn, LocalGeneratorFunctionVariable): + fn = LocalGeneratorFunctionVariable(fn) + return fn.call_function(self, args, kwargs) # type: ignore[arg-type] + + def inline_user_function_return( + self, + fn: BaseUserFunctionVariable, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + allow_nested_graph_breaks: bool = False, + ) -> Any: + """ + A call to some user defined function by inlining it. + """ + if is_generator(fn.get_code()): + return self.inline_generator_function(fn, args, kwargs) + else: + return InliningInstructionTranslator.inline_call( + self, + fn, + args, + kwargs, + allow_nested_graph_breaks=allow_nested_graph_breaks, + ) + + def get_line_of_code_header(self, lineno: int | None = None) -> str: + if lineno is None: + lineno = self.lineno + inline_depth_str = ( + f" (inline depth: {self.inline_depth})" if self.inline_depth > 0 else "" + ) + funcname = get_funcname(self.f_code.co_filename, lineno) + funcname_str = "" if funcname is None else f" ({funcname})" + return f"{self.f_code.co_filename}:{lineno} in {self.f_code.co_name}{funcname_str}{inline_depth_str}" + + def get_log_starts_line_log_str(self) -> str: + log_str = f"TRACE starts_line {self.get_line_of_code_header()}\n" + line = linecache.getline(self.f_code.co_filename, self.lineno).rstrip() + log_str += f" {line}" + return log_str + + def starts_line(self, lineno: int) -> None: + if self.lineno == lineno: + return + self.lineno = lineno + TracingContext.set_current_loc( + self.f_code.co_filename, lineno, self.f_code.co_name + ) + + if self.is_trace_source_log_enabled: + trace_source_log.debug("%s", LazyString(self.get_log_starts_line_log_str)) + + def step(self) -> bool: + """Process exactly one instruction, return False we should exit""" + self.error_on_graph_break = _get_error_on_graph_break() + + ip = self.instruction_pointer + if ip is None: + return False + self.current_instruction = inst = self.instructions[ip] + self.instruction_pointer = ip + 1 + + if inst.starts_line: + self.starts_line(inst.starts_line) + + tc = TracingContext.try_get() + if tc is not None: + tc.loc_in_frame_positions = inst.positions + + if ( + not self.stack + and self.should_compile_partial_graph() + and self.is_non_empty_graph() + ): + self.current_speculation = self.speculate() + if self.current_speculation.failed(self): + self.step_graph_break(inst) + return False + + if self.is_trace_bytecode_log_enabled: + trace_bytecode_log.debug( + "TRACE %s %s %s", inst.opname, inst.argval, repr(self.stack) + ) + + # Store the latest 20 bytecode execution for the process, + # Used repr for byte processing and limiting the length to 2048 + if config.verbose: + try: + stack_repr = repr(self.stack) + except ValueError: + # Handle large integers that exceed sys.int_info.str_digits_check_threshold + stack_repr = "" + self.latest_bytecode_queue.append( + f"TRACE {inst.opname} {repr(inst.argval)} {stack_repr}" + ) + + self.update_block_stack(inst) + + try: + self.dispatch_table[inst.opcode](self, inst) + return not self.output.should_exit + except TensorifyScalarRestartAnalysis: + raise + except exc.ObservedException as e: + self.exception_handler(e) + return True + except (ReturnValueOp, YieldValueOp): + return False + except (Unsupported, UserError, StepUnsupported) as e: + # More restrictive condition than should_compile_partial_graph: + # if this condition is true, then we SHOULD NOT attempt to find + # a previous checkpoint to resume from and try to resume - we should + # immediately error out. + # The condition is more restrictive because, it may be possible to resume significantly earlier + # in the code (the most recent speculation point). This happens, for example, in the case + # of a graph break in a try block. + if ( + self.one_graph + or self.error_on_graph_break + or self.is_tracing_resume_prologue + or getattr(e, "skip_frame", False) + ): + if isinstance(e, StepUnsupported): + unimplemented( + gb_type="cannot resume from torch._dynamo.step_unsupported()", + context="", + explanation="traced torch._dynamo.step_unsupported(), but Dynamo is instructed " + "to error on graph break. This graph break is used for debugging only.", + hints=[ + "Remove the torch._dynamo.step_unsupported() call.", + "Make sure fullgraph=False and error_on_graph_break=False.", + *graph_break_hints.DYNAMO_BUG, + ], + ) + raise + if self.current_speculation is None: + log.debug("empty checkpoint - cannot resume from graph break") + if isinstance(e, StepUnsupported): + unimplemented( + gb_type="torch._dynamo.step_unsupported() with empty checkpoint", + context="", + explanation="traced torch._dynamo.step_unsupported(), but there is no checkpoint " + "to step_graph_break from. This graph break is used for debugging only.", + hints=[ + "Remove the torch._dynamo.step_unsupported() call.", + "Include at least one checkpoint: (1) include at least 2 ops and (2) make sure there is some " + "line of code that is not in a try/with block, and has an empty Python stack.", + *graph_break_hints.DYNAMO_BUG, + ], + skip_frame=True, + ) + e.skip_frame = True + raise + reason = ( + "Encountered graph break that we cannot resume from. " + "Compiling up to the previous resumable state, " + "then skipping the rest of the function. " + f"Graph break encountered:\n\n{str(e)}" + ) + self.log_graph_break( + self.code_options, + reason=reason, + exc=e, + ) + + self.current_speculation.fail_and_restart_analysis(self.error_on_graph_break) + return False + + if sys.version_info >= (3, 11): + + def update_block_stack(self, inst: Instruction) -> None: + # 3.11+ no longer uses a block stack, but we still keep track of one + # so that we know which contexts are currently active. + # For our purposes, all exception table entries with the same target + # are considered to be part of the same "block". + # NOTE: we only keep track of with blocks that are not contained in try blocks. + # This is because we will not create continuation functions on graph breaks in try blocks, + # but we may for with blocks. We do not push blocks here since + # with blocks are pushed when handling BEFORE_WITH. + entry = inst.exn_tab_entry + if entry: + # Detect when we have exited the top with block. + # The with blocks on the block stack are not enclosed in try + # blocks, so a with block's cleanup code should be in the + # previous with block (if any). + if ( + len(self.block_stack) >= 2 + and entry.target is not self.block_stack[-1].target + and entry.target is self.block_stack[-2].target + ): + # exit the current block + self.block_stack.pop() + else: + # no longer in any block + # It is possible for NOPs to be between two instructions + # in the same block, but the NOPs are not covered by an + # exception table entry. In this case, assume that we + # are still in the same block. + # In 3.12+, JUMP_BACKWARD might also not be covered by + # an exception table entry, so we also assume that we + # are still in the same block. It is probably safe to do + # this in 3.11, even though we haven't encountered this case before. + # In 3.14+, NOT_TAKEN might also not be covered by an exn table entry. + if self.block_stack and inst.opname not in ( + "NOP", + "JUMP_BACKWARD", + "NOT_TAKEN", + ): + # If we really escape from a block and the current + # instruction is not in another block, then there + # should be no other nested blocks that we are in. + if len(self.block_stack) != 1: + raise AssertionError( + "expected len(self.block_stack) == 1 to be true" + ) + self.block_stack.pop() + + else: + + def update_block_stack(self, inst: Instruction) -> None: + pass + + @property + def next_instruction(self) -> Instruction: + if self.instruction_pointer is None: + raise AssertionError( + "expected self.instruction_pointer is not None to be true" + ) + return self.instructions[self.instruction_pointer] + + def step_graph_break(self, continue_inst: Instruction) -> None: + # generate code from checkpoint + if self.output.output_instructions: + raise AssertionError( + "expected not self.output.output_instructions to be true" + ) + if self.current_speculation is None: + raise AssertionError( + "expected self.current_speculation is not None to be true" + ) + # NOTE: adding an assert here since it seems like the only place + # where we call step_graph_break right now is when the stack is empty, + # so let's enforce that for now. + if self.stack: + raise AssertionError("expected not self.stack to be true") + # NOTE: if we support non-empty self.stack in the future, the `stack_pops` argument + # below should be set to the stack length to ensure that the stack is codegen'd + # for the rest of the function. + log.debug("step triggered compile") + all_stack_locals_metadata = self.output.compile_subgraph( + self, + reason=GraphCompileReason("step_unsupported", [self.frame_summary()]), + ) + # current frame state + # cells, + # [ + # frame N locals, + # frame N-1 stack + locals, + # ..., + # frame 1 stack + locals, + # ], + if self.parent: + from .eval_frame import skip_code + + # nested graph break + if not config.nested_graph_breaks: + raise AssertionError("expected config.nested_graph_breaks to be true") + cg = PyCodegen(self.output.root_tx) + + # codegen cells and frame values only for frame N + cg.extend_output( + [ + *create_copy(2), + cg.create_load_const(0), + cg.create_binary_subscr(), + create_instruction("BUILD_LIST", arg=1), + *create_copy(2), + cg.create_load_const(0), + cg.create_binary_subscr(), + create_instruction("BUILD_LIST", arg=1), + ] + ) + # No need to fix stack, since stack is assumed to be empty here. + # Do NOT handle_inactive_ctx because we will be skipping this resume code. + leaf_resume_code, leaf_resume_name = self.create_resume( + 0, continue_inst, all_stack_locals_metadata[0], [], cg, True, False + ) + skip_code(leaf_resume_code) + + cleanup: list[Instruction] = [] + _reconstruct_block_stack(self.parent, cg, cleanup) + + # current frame state + # cells, + # [ + # frame N locals, + # frame N-1 stack + locals, + # ..., + # frame 1 stack + locals, + # ], [frame N cells], [frame N locals], + self.codegen_call_resume([leaf_resume_code], [leaf_resume_name], cg) + + cg.extend_output(cleanup) + + # current frame state + # cells, + # [ + # frame N locals, + # frame N-1 stack + locals, + # ..., + # frame 1 stack + locals, + # ], leaf_resume result + + # pop frame N cells and locals + cg.extend_output( + [ + *create_copy(2), + cg.create_load_const(0), + create_instruction("DELETE_SUBSCR"), + *create_copy(3), + cg.create_load_const(0), + create_instruction("DELETE_SUBSCR"), + ] + ) + + # current frame state + # cells, frame_values, leaf_resume result + # extract frame N-1 stack + num_stack = all_stack_locals_metadata[1].num_stack + cg.extend_output( + [ + *create_copy(2), + cg.create_load_const(0), + cg.create_binary_subscr(), + *create_binary_slice(0, num_stack), + ] + ) + + # current frame state + # cells, frame_values, leaf_resume result, frame N-1 stack + # add the leaf_resume result to frame N-1 stack + cg.extend_output( + [ + *create_swap(2), + *cg.create_list_append(), + ] + ) + self.parent.push(UnknownVariable()) + all_stack_locals_metadata[1].num_stack += 1 + + # current frame state + # cells, frame_values, frame N-1 stack + leaf_resume result + # remove frame N-1 stack from frame_values + if num_stack > 0: + cg.extend_output( + # frame_values[0] = frame_values[0][num_stack:] + [ + *create_copy(2), + cg.create_load_const(0), + cg.create_binary_subscr(), + *create_binary_slice(num_stack, None), + *create_copy(3), + cg.create_load_const(0), + create_instruction("STORE_SUBSCR"), + ] + ) + + # current frame state + # cells, frame_values, frame N-1 stack + leaf_resume result + # unpack the stack (need to unpack twice since UNPACK_SEQUENCE unpacks in reverse order) + cg.extend_output( + [ + create_instruction("UNPACK_SEQUENCE", arg=num_stack + 1), + create_instruction("BUILD_LIST", arg=num_stack + 1), + create_instruction("UNPACK_SEQUENCE", arg=num_stack + 1), + ] + ) + + # call the remaining resume functions + # current frame state + # [frame N-1 cells, ..., frame 1 cells], + # [ + # frame N-1 locals, + # frame N-2 stack + locals, + # ..., + # frame 1 stack + locals, + # ], *(frame N-1 stack), leaf_resume result + self.output.add_output_instructions( + cg.get_instructions() + + self.parent.create_call_resume_at( + self.parent.next_instruction, all_stack_locals_metadata[1:] + ) + ) + else: + # NOTE: if WithExitFunctionVariable is reconstructed here, then the generated bytecode will be wrong. + # However, we don't expect this to happen since WithExitFunctionVariable can only be present on the stack, + # which must be empty in step graph breaks. + # If we do decide to support step graph breaks with WithExitFunctionVariable in the future, we should + # either call a skipped resume function as in the nested step graph break case, or reconstruct the + # proper context manager object from the class (like what we used to do historically in variables/ctx_manager.py). + + # pop cells + self.output.add_output_instructions( + [ + *create_swap(2), + create_instruction("POP_TOP"), + ] + ) + # load locals from frame values + cg = PyCodegen(self.output.root_tx) + self.output.add_output_instructions( + [ + cg.create_load_const(-1), + cg.create_binary_subscr(), + ] + ) + for local, idx in all_stack_locals_metadata[-1].locals_names.items(): + self.output.add_output_instructions( + [ + create_dup_top(), + cg.create_load_const(idx), + cg.create_binary_subscr(), + cg.create_store(local), + ] + ) + self.output.add_output_instructions( + [ + create_instruction("POP_TOP"), + create_jump_absolute(continue_inst), + *self.instructions, + ] + ) + + def run_ctx_mgr(self) -> Any: + # NB: Don't push the top level frame summary; set_current_loc will + # take care of it. However, DO make sure we attach real_stack to + # exceptions + return TracingContext.current_frame(None) + + def run(self) -> None: + with self.run_ctx_mgr(): + dump_file(self.f_code.co_filename) + try: + self.output.push_tx(self) + self.start_point = self.instruction_pointer + try: + while self.step(): + pass + except Exception as e: + if self.is_tracing_resume_prologue: + raise ResumePrologueTracingError( + "Error while tracing through a Dynamo-generated resume function prologue. " + "Errors are not allowed when tracing resume function prologues.\n" + f"{type(e).__qualname__}: {str(e)}" + ).with_traceback(e.__traceback__) from None + raise + except TensorifyScalarRestartAnalysis: + raise + except BackendCompilerFailed: + raise + except RuntimeError as e: + # If the root tx fails to handle the graph break, then the caller (convert_frame) + # will skip the frame and fall back to eager. + # This code path happens e.g. for bytecodes we don't support + # or when we are unable to resume from a graph break. + if ( + isinstance(e, (Unsupported, UserError)) + and isinstance(self, InstructionTranslator) + and not self.error_on_graph_break + and not self.one_graph + ): + # log graph break if we won't error + reason = ( + "Failed to handle graph break gracefully. " + "Skipping the function and falling back to eager. " + f"Graph break encountered:\n\n{str(e)}" + ) + self.log_graph_break( + self.code_options, + reason=reason, + exc=e, + ) + + if not isinstance(e, exc.RestartAnalysis): + self.output.side_effects.log_side_effects_summary() + + if hasattr(e, "msg") and "Data-dependent" in e.msg: + readable_graph = torch.fx.GraphModule( + self.output.nn_modules, self.output.graph + ).print_readable( + print_output=False, include_stride=True, include_device=True + ) + e.partial_fx_graph = readable_graph # type: ignore[attr-defined] + raise + + raise + except Exception as e: + if self.exec_recorder: + e.exec_record = self.exec_recorder.get_record() # type: ignore[attr-defined] + if not isinstance(e, exc.RestartAnalysis): + self.output.side_effects.log_side_effects_summary() + + raise + finally: + self.output.pop_tx() + # Cleanup the outputGraph to delete the held tensors. We perform the + # cleanup only for InstructionTranslator and not + # InliningInstructionTranslator. The InliningInstructionTranslator + # mutates the output object and is restored to original state if + # there was an exception. + if isinstance(self, InstructionTranslator): + self.output.cleanup() + + # Note that this call maybe redundant if compile_subgraph is + # called. This is ok, because calling exit stack close() + # twice is not an issue (second stop is a no op). + self.output.mark_bytecode_tracing_stop() + + def push(self, val: VariableTracker) -> None: + if not isinstance(val, VariableTracker): + raise AssertionError(f"push expects VariableTracker, got {typestr(val)}") + if val.source_location is None: + inst = self.current_instruction + if inst.positions is not None and inst.positions.lineno is not None: + val.set_source_location( + SourceLocation( + filename=self.f_code.co_filename, + lineno=inst.positions.lineno, + end_lineno=inst.positions.end_lineno, + col_offset=inst.positions.col_offset, + end_col_offset=inst.positions.end_col_offset, + ) + ) + elif inst.starts_line is not None: + val.set_source_location( + SourceLocation( + filename=self.f_code.co_filename, + lineno=inst.starts_line, + ) + ) + self.stack.append(val) + + def push_many(self, vals: list[VariableTracker]) -> None: + for val in vals: + self.push(val) + + def pop(self) -> VariableTracker: + return self.stack.pop() + + def popn(self, n: int) -> list[VariableTracker]: + return [*reversed([self.pop() for _ in range(n)])] + + def LOAD_FAST(self, inst: Instruction) -> None: + name = inst.argval + if self.exec_recorder and name in self.f_locals: + self.exec_recorder.add_local_var(name, self.f_locals[name]) + + try: + self.push(self.symbolic_locals[name].unwrap()) + except KeyError: + if name.startswith("."): + try: + # This happens in dict/list comprehensions + new_name = name.replace(".", "implicit") + self.push(self.symbolic_locals[new_name]) + except KeyError: + unimplemented( + gb_type="Attempted to read undefined local variable (implicit)", + context=f"LOAD_FAST {name}", + explanation=f"Could not find an implicit local variable with name `{name}`", + hints=[ + "This happens in dict/list comprehensions", + *graph_break_hints.USER_ERROR, + ], + ) + else: + unimplemented( + gb_type="Attempted to read undefined local variable", + context=f"LOAD_FAST {name}", + explanation=f"Could not find a local variable with name `{name}`", + hints=[*graph_break_hints.USER_ERROR], + ) + + # for continuation functions + if name.startswith("__stack"): + self.symbolic_locals.pop(name) + + def _cellvar(self, name: str) -> VariableTracker: + # The localsplus slot is authoritative while it holds a cell (a + # mid-function MAKE_CELL from an inlined comprehension can replace a + # merged cell slot's cell with a fresh one). Fall back to the registry + # when the slot doesn't hold a cell: either the name is a colliding + # free var that never lives in symbolic_locals, or the cell was + # temporarily evicted by LOAD_FAST_AND_CLEAR. + var = self.symbolic_locals.get(name) + # __instancecheck__ to avoid realizing lazy vts + if var is not None and type.__instancecheck__(CellVariable, var): + return var + return self.symbolic_cellvars[name] + + def LOAD_DEREF(self, inst: Instruction) -> None: + if inst.argval not in self.cell_and_freevars(): + raise AssertionError( + "expected inst.argval in self.cell_and_freevars() to be true" + ) + cell = self._cellvar(inst.argval) + contents_var = self.output.side_effects.load_cell(cell) + self.push(contents_var) + + if self.exec_recorder and inst.argval in self.f_locals: + self.exec_recorder.add_local_var(inst.argval, self.f_locals[inst.argval]) + + def STORE_FAST(self, inst: Instruction) -> None: + name = inst.argval + loaded_vt = self.pop() + loaded_vt.set_name_hint(name) + self.symbolic_locals[name] = loaded_vt + if name == IS_TRACING_RESUME_PROLOGUE_VARNAME: + val = loaded_vt.as_python_constant() + if type(val) is not bool: + raise AssertionError("expected type(val) is bool to be true") + self.is_tracing_resume_prologue = val + + def DELETE_FAST(self, inst: Instruction) -> None: + var = self.symbolic_locals.get(inst.argval) + if isinstance(var, TensorVariable): + self._maybe_emit_sync_dealloc(var) + del self.symbolic_locals[inst.argval] + + def _maybe_emit_sync_dealloc(self, var: TensorVariable) -> None: + from .variables.streams import get_current_stream, new_event + + device = var.device + if device is None or device.type not in ("cuda", "xpu"): + return + + node = var.proxy.node + alloc_stream = node.meta.get("custom", {}).get("stream", None) + + users = set(node.users.keys()) + if not users: + return + last_user = None + for n in self.output.graph.nodes: + if n in users: + last_user = n + if last_user is None or last_user.op == "output": + return + + last_use_stream = last_user.meta.get("custom", {}).get("stream", None) + if alloc_stream == last_use_stream: + return + + if alloc_stream is None: + alloc_stream = get_current_stream(device) + if last_use_stream is None: + last_use_stream = get_current_stream(device) + + event_idx = new_event() + self.output.create_proxy( + "call_function", + torch.ops.streams.record_event, + (event_idx, last_use_stream), + {}, + ) + self.output.create_proxy( + "call_function", + torch.ops.streams.sync_dealloc, + (event_idx, alloc_stream, var.as_proxy()), + {}, + ) + + def STORE_DEREF(self, inst: Instruction) -> None: # type: ignore[override] + if inst.argval not in self.cell_and_freevars(): + raise AssertionError( + "expected inst.argval in self.cell_and_freevars() to be true" + ) + cell = self._cellvar(inst.argval) + val = self.pop() + self.output.side_effects.store_cell(cell, val) + + if not isinstance(cell, CellVariable): + raise AssertionError( + "expected isinstance(cell, CellVariable) to be true" + ) # tame mypy + if cell.local_name is not None: + val.set_name_hint(cell.local_name) # type: ignore[attr-defined] + + def LOAD_CLOSURE(self, inst: Instruction) -> None: + # LOAD_CLOSURE pushes the cell object itself. + self.push(self._cellvar(inst.argval)) + + def _load_const(self, inst: Instruction) -> VariableTracker: + i = inst.arg + if i is None: + return ConstantVariable.create(value=inst.argval) # type: ignore[return-value] + val = self._constants_cache[i] + if not val: + self._constants_cache[i] = ConstantVariable.create(value=inst.argval) # type: ignore[call-overload] + val = self._constants_cache[i] + if val is None: + raise AssertionError("expected val is not None to be true") + return val + + def LOAD_CONST(self, inst: Instruction) -> None: + self.push(self._load_const(inst)) + + def _load_global(self, inst: Instruction) -> None: + name = inst.argval + + if self.exec_recorder: + if name in self.f_globals: + self.exec_recorder.add_global_var(name, self.f_globals[name]) + else: + if name not in self.f_builtins: + raise AssertionError("expected name in self.f_builtins to be true") + self.exec_recorder.builtins[name] = self.f_builtins[name] + + if name not in self.f_globals: + return self.load_builtin(inst) + + if name in self.symbolic_globals: + variable = self.output.side_effects[self.symbolic_globals[name]] + self.push(self.output.side_effects.load_global(variable, name)) + return + + value = self.f_globals[name] + self.push(VariableTracker.build(self, value, GlobalSource(name))) + + @functools.cached_property + def nn_modules_globals_vt(self) -> VariableTracker: + module_name = "torch.nn.modules.module" + module_source = self.import_source(module_name) + fglobals_value = _import_module(module_name) + return VariableTracker.build(self, fglobals_value, module_source) + + def LOAD_GLOBAL(self, inst: Instruction) -> None: + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + if sys.version_info >= (3, 11) and sys.version_info < (3, 13) and inst.arg % 2: + self.PUSH_NULL(inst) + self._load_global(inst) + if sys.version_info >= (3, 13) and inst.arg % 2: + self.PUSH_NULL(inst) + + def STORE_GLOBAL(self, inst: Instruction) -> None: + value = self.pop() + name = inst.argval + source = GlobalSource(name) + if name not in self.symbolic_globals: + self.symbolic_globals[name] = object() # type: ignore[assignment] # sentinel object + variable = self.output.side_effects.track_global_existing( + source, self.symbolic_globals[name] + ) + if isinstance(value, RemovableHandleVariable): + unimplemented( + gb_type="Storing Tensor hook handle in globals", + context=name, + explanation="This is not supported.", + hints=[], + ) + self.output.side_effects.store_global(variable, name, value) + + # Cache note: This cache only exists for the duration of this + # InstructionTranslator - so it should be safe to do. + @cache_method + def import_source(self, module_name: str) -> GlobalSource: + """Create an alias to a module for use in guards""" + if "torch_package" in module_name: + value = torch.package.package_importer._package_imported_modules[ + module_name + ] + alias = ( + module_name.replace(">", "_").replace("<", "_").replace(".", "_dot_") + ) + else: + value = _import_module(module_name) + alias = f"__import_{module_name.replace('.', '_dot_')}" + + if self.package is not None: + self.package.add_import_source(alias, module_name) + self.output.import_sources[alias] = module_name + f_globals = self.output.global_scope + if not (alias not in f_globals or f_globals[alias] is value): + raise AssertionError( + "expected alias not in f_globals or f_globals[alias] is value to be true" + ) + f_globals[alias] = value + self.output.update_co_names(alias) + return GlobalSource(alias) + + def resolve_name(self, name: str, package: str, level: int) -> str: + """ + Copied from the Cpython implementation of __import__ + Resolve a relative module name to an absolute one. + https://github.com/python/cpython/blob/5a094f0255eea1db58fb2cf14c200971e64ec36e/Lib/importlib/_bootstrap.py#L902 + """ + bits = package.rsplit(".", level - 1) + if len(bits) < level: + raise ImportError("attempted relative import beyond top-level package") + base = bits[0] + return f"{base}.{name}" if name else base + + def calc_package(self) -> str: + """ + Copied from the Cpython implementation of __import__ + https://github.com/python/cpython/blob/5a094f0255eea1db58fb2cf14c200971e64ec36e/Lib/importlib/_bootstrap.py#L1090 + """ + package = self.f_globals.get("__package__") + spec = self.f_globals.get("__spec__") + if package is not None: + if spec is not None and package != spec.parent: + log.warning( + "__package__ != __spec__.parent (%r != %r)", + package, + spec.parent, + stacklevel=3, + ) + return package + elif spec is not None: + return spec.parent + else: + log.warning( + "can't resolve package from __spec__ or __package__, " + "falling back on __name__ and __path__", + stacklevel=3, + ) + package = self.f_globals["__name__"] + if "__path__" not in self.f_globals: + package = package.rpartition(".")[0] + return package + + def IMPORT_NAME(self, inst: Instruction) -> None: + level, fromlist = self.popn(2) + level = level.as_python_constant() + fromlist = fromlist.as_python_constant() + module_name = inst.argval + + # Are we replaying? if so, load recorded module + recorded_name = ( + f"{ExecutionRecorder.LOCAL_MOD_PREFIX}_{level}_{fromlist}_{module_name}" + ) + if recorded_name in self.f_globals: + value = self.f_globals[recorded_name] + source = GlobalSource(recorded_name) + else: + try: + value = __import__( + module_name, + fromlist=fromlist, + level=level, + globals=self.f_globals, + ) + except ImportError: + unimplemented( + gb_type="Import failure", + context=f"module_name: {module_name}, fromlist: {fromlist}, level={level}", + explanation="Failure when attempting to import.", + hints=[*graph_break_hints.USER_ERROR], + ) + + if level != 0: + pkg = self.calc_package() + module_name = self.resolve_name(module_name, pkg, level) + + # For __import__, when the name variable is of the form package.module, + # normally, the top-level package (the name up till the first dot) is + # returned, not the module named by module_name. However, when a + # non-empty fromlist argument is given, the module named by name is + # returned. Therefore, we set the source correctly here. + if not fromlist: + top_level_module_name = module_name.partition(".")[0] + source = self.import_source(top_level_module_name) + else: + source = self.import_source(module_name) + + if self.exec_recorder: + # pyrefly: ignore [unbound-name] + self.exec_recorder.add_local_mod(recorded_name, value) + + # pyrefly: ignore [unbound-name] + if isinstance(value, (types.ModuleType, DummyModule)): + # pyrefly: ignore [unbound-name, bad-argument-type] + self.push(PythonModuleVariable(value, source=source)) + else: + unimplemented( + gb_type="Bad import result", + # pyrefly: ignore [unbound-name] + context=typestr(value), + explanation="Import result is not a Python module.", + hints=[], + ) + + # fb internal 3.12 opcode + EAGER_IMPORT_NAME = IMPORT_NAME + + def IMPORT_FROM(self, inst: Instruction) -> None: + self.DUP_TOP(inst) + self._load_attr(inst.argval) + + # Cache note: This cache only exists for the duration of this + # InstructionTranslator - so it should be safe to do. + @cache_method + def load_builtin_from_argval(self, argval: Any) -> VariableTracker: + if argval not in self.f_builtins: + # Name is neither a global nor a builtin: matches CPython raising + # NameError with `name` set to the missing identifier. + raise_observed_exception( + NameError, + self, + args=[f"name '{argval}' is not defined"], + kwargs={"name": ConstantVariable.create(argval)}, + ) + val = self.f_builtins[argval] + + if callable(val): + builtins_source = GlobalSource( + self.output.name_of_builtins_dict_key_in_fglobals + ) + var_source = DictGetItemSource(builtins_source, argval) + return VariableTracker.build(self, val, var_source) + else: + if not is_builtin_constant(val): + raise AssertionError("expected is_builtin_constant(val) to be true") + return VariableTracker.build(self, val) + + def load_builtin(self, inst: Instruction) -> None: + self.push(self.load_builtin_from_argval(inst.argval)) + + def jump(self, inst: Instruction | BlockStackEntry) -> None: + if self.instruction_pointer is None: + raise AssertionError( + "expected self.instruction_pointer is not None to be true" + ) + if self.start_point is None: + raise AssertionError("expected self.start_point is not None to be true") + if inst.target is None: + raise AssertionError("expected inst.target is not None to be true") + get_metrics_context().increment( + "ir_count", self.instruction_pointer - self.start_point + ) + self.instruction_pointer = self.indexof[inst.target] + self.start_point = self.instruction_pointer + + JUMP_FORWARD = jump + JUMP_ABSOLUTE = jump + + POP_JUMP_IF_FALSE = generic_jump(operator.not_, False) + POP_JUMP_IF_TRUE = generic_jump(operator.truth, False) + JUMP_IF_FALSE_OR_POP = generic_jump(operator.not_, True) + JUMP_IF_TRUE_OR_POP = generic_jump(operator.truth, True) + + def SETUP_LOOP(self, inst: Instruction) -> None: + # only exists in python<=3.7 + if inst.target is None: + raise AssertionError("expected inst.target is not None to be true") + self.block_stack.append(BlockStackEntry(inst, inst.target, len(self.stack))) + + def SETUP_EXCEPT(self, inst: Instruction) -> None: + # only exists in python<=3.7 + if inst.target is None: + raise AssertionError("expected inst.target is not None to be true") + self.block_stack.append(BlockStackEntry(inst, inst.target, len(self.stack))) + + def POP_BLOCK(self, inst: Instruction) -> None: + self.block_stack.pop() + + def SETUP_WITH(self, inst: Instruction) -> None: + self.setup_or_before_with(inst) + + def SETUP_FINALLY(self, inst: Instruction) -> None: + if inst.target is None: + raise AssertionError("expected inst.target is not None to be true") + self.block_stack.append(BlockStackEntry(inst, inst.target, len(self.stack))) + + def FOR_ITER(self, inst: Instruction) -> None: + # in 3.15+, make sure TOS remains a null + if sys.version_info >= (3, 15): + null = self.pop() + it = self.pop().realize() + self.push(it) + if sys.version_info >= (3, 15): + self.push(null) + try: + val = it.next_variable(self) + self.push(val) + except ( + StopIteration, + exc.ObservedUserStopIteration, + exc.ObservedIndexError, + ) as e: + if isinstance(e, (exc.ObservedUserStopIteration, exc.ObservedIndexError)): + exc.handle_observed_exception(self) + + if sys.version_info >= (3, 12): + # CPython 3.12 actually jumps to the instruction after the END_FOR + # and performs the action of END_FOR as part of FOR_ITER. We jump + # to the END_FOR and run it, so we need to make sure 2 values are + # on the stack for it to pop. + self.push(ConstantVariable.create(None)) + else: + # pop the iterator in Python < 3.12 + self.pop() + self.jump(inst) + + def _create_exception_instance( + self, val: ExceptionTypes | ExceptionVals + ) -> ExceptionVals: + if pyexception_class_check(val): + # Create the instance of the exception type + # https://github.com/python/cpython/blob/3.11/Python/ceval.c#L6547-L6549 + type_name = val.python_type_name() + val = val.call_function(self, [], {}) # type: ignore[arg-type] + + if not issubclass(val.python_type(), BaseException): + exc.raise_type_error( + self, + f"calling {type_name} should have returned an instance of BaseException, not {val.python_type_name()}", + ) + if not pyexception_instance_check(val): + exc.raise_type_error( + self, + "exceptions must derive from BaseException", + ) + return val + + def set_exception_obj( + self, exception: ExceptionTypes, value: VariableTracker | None + ) -> ExceptionVals: + # Mirrors CPython PyErr_SetObject + # Note: This function is here rather than in ExceptionStack because we + # need an InstructionTranslator instance to create the exception instance + + # TODO(dynamo-team): check if exception is a subclass of BaseException + + # This function handles construction, normalization, implicit + # __context__ chaining and traceback attach. + # if value is specified, it can be either an exception instance or args + # to exception ctor + + if ( + value + and pyexception_instance_check(value) + and issubclass(value.exc_type, exception.fn) + ): + instance = value + else: + instance = exception.call_function(self, [value] if value else [], {}) + + if not isinstance(instance, ExceptionVals): + raise AssertionError("expected instance to be an instance of ExceptionVals") + + self._attach_traceback_to_exception(instance) + self.exn_vt_stack._set_context_and_break_context_reference_cycle(instance) + self.exn_vt_stack.set_raised_exception(instance) + return instance + + def _attach_traceback_to_exception(self, exc: ExceptionVals) -> None: + # based on CPython's PyTraceBack_Here impl + frame_summary = self.frame_summary() + tb = exc.tp_getattro_impl( + # pyrefly: ignore [bad-argument-type] + self, + "__traceback__", + ) + if not isinstance(tb, (ConstantVariable, TracebackVariable)): + raise AssertionError( + "expected isinstance( tb, (ConstantVariable, TracebackVariable) ) to be true" + ) # make pyrefly happy + new_tb = TracebackVariable.from_frame_summary(frame_summary, tb) + exc.call_method( + self, # type: ignore[bad-argument-type] + "__setattr__", + [VariableTracker.build(self, "__traceback__"), new_tb], + {}, + ) + + def _raise_observed_exception(self, exc_: ExceptionVals) -> NoReturn: + # Propagate `exc_` as an ObservedException to unwind the tracer to the + # handler, preserving the original raise location via python_stack. + observed_exception_type = get_dynamo_observed_exception(exc_.exc_type) # type: ignore[attr-defined, union-attr] + python_stack = getattr(exc_, "python_stack", None) + raise observed_exception_type( + f"raised exception {exc_.debug_repr()}", real_stack=python_stack + ) + + def do_raise( + self, + val: VariableTracker | None, + cause: VariableTracker | None, + ) -> NoReturn: + # Mirrors CPython's `do_raise` + # https://github.com/python/cpython/blob/704c4c79e8485c20fb59cea1acec005f365a4fca/Python/ceval.c#L1900 + + # User can raise exception in 3 ways + # 1) raise + # 2) raise + # 3) raise + + # bare raise + if val is None: + # reraise the exception on top of the exception stack + if not len(self.exn_vt_stack): + exc.raise_observed_exception( + RuntimeError, self, args=["No active exception to reraise"] + ) + val = self.exn_vt_stack.get_topmost_exception() + self.exn_vt_stack.set_raised_exception(val) + self._raise_observed_exception(val) + + # normalize type/value + if pyexception_class_check(val): + type_ = val + value = self._create_exception_instance(val) + elif pyexception_instance_check(val): + value = val + type_ = VariableTracker.build(self, val.python_type()) + else: + # not something we can raise + exc.raise_type_error(self, "exceptions must derive from BaseException") + + # normalize cause (`raise from `) + if cause: + if pyexception_class_check(cause): + fixed_cause = self._create_exception_instance(cause) + elif pyexception_instance_check(cause) or cause.is_constant_none(): + fixed_cause = cause + else: + exc.raise_type_error( + self, + "exception causes must derive from BaseException", + ) + value.call_method( + self, + "__setattr__", + [ConstantVariable.create("__cause__"), fixed_cause], + {}, + ) + + # Capture the python_stack when the exception is first raised. + # This preserves the original exception location even if the exception + # is later re-raised (e.g., in context manager cleanup). + # ExceptionVariable and UserDefinedExceptionObjectVariable both have + # a python_stack attribute. + if getattr(value, "python_stack", None) is None: + value.python_stack = torch._guards.TracingContext.extract_stack() # type: ignore[union-attr] + + exc_instance = self.set_exception_obj(type_, value) + self._raise_observed_exception(exc_instance) + + def RAISE_VARARGS(self, inst: Instruction) -> None: + if inst.arg == 0: + # bare raise; do_raise reraises the exception on top of the stack, + # or reports "No active exception to reraise" if the stack is empty + self.do_raise(None, None) + elif inst.arg == 1: + # raise TOS + val = self.stack[-1] # type: ignore[assignment] + self.do_raise(val, None) + else: + # raise .. from ... + cause = self.pop() + val = self.pop() # type: ignore[assignment] + self.do_raise(val, cause) + + def CLEANUP_THROW(self, inst: Instruction) -> None: + # https://github.com/python/cpython/pull/96010 + tos = self.stack[-1] + if not isinstance(tos, ExceptionVals): + raise AssertionError("expected isinstance(tos, ExceptionVals) to be true") + if issubclass(tos.exc_type, StopIteration): + self.popn(3) + self.push(ConstantVariable.create(None)) + self.push(tos.args[0] if tos.args else ConstantVariable.create(None)) + else: + self.RERAISE(inst) + + def RERAISE(self, inst: Instruction) -> None: + # https://docs.python.org/3/library/dis.html#opcode-RERAISE + # Re-raises the exception currently on top of the stack. If oparg is + # non-zero, pops an additional value from the stack which is used to + # set f_lasti of the current frame. + + if sys.version_info >= (3, 11): + # Re-raise the exception on top of the stack. + val = self.pop() + if not pyexception_instance_check(val): + raise AssertionError( + "expected _exception_instance_check(val) to be true" + ) + if inst.argval: + # RERAISE 1 + _ = self.pop() + self.exn_vt_stack.set_raised_exception(val) + else: + # RERAISE 0 + self.push(val) + self.exn_vt_stack.set_raised_exception(val) + self._raise_observed_exception(val) + else: + _exc = self.pop() + val = self.pop() + _tb = self.pop() + if not pyexception_instance_check(val): + raise AssertionError( + "expected _exception_instance_check(val) to be true" + ) + self.exn_vt_stack.set_raised_exception(val) + self._raise_observed_exception(val) + + def WITH_EXCEPT_START(self, inst: Instruction) -> None: + args: list[VariableTracker] = [] + if sys.version_info >= (3, 11): + fn_loc = 4 if sys.version_info < (3, 14) else 5 + # At the top of the stack are 4 values: + # - TOP = exc_info() + # - SECOND = previous exception + # - THIRD: lasti of exception in exc_info() + # - FOURTH: the context.__exit__ bound method + # We call FOURTH(type(TOP), TOP, GetTraceback(TOP)). + # Then we push the __exit__ return value. + # In Python 3.14+, there is a NULL placed between the context.__exit__ bound method and the lasti, + # that is, fn is now the 5th from TOS. + if not (len(self.stack) >= fn_loc): + raise AssertionError("expected len(self.stack) >= fn_loc to be true") + fn = self.stack[-fn_loc] + val = self.stack[-1] + if not pyexception_instance_check(val): + raise AssertionError( + "expected _exception_instance_check(val) to be true" + ) + typ = BuiltinVariable(val.exc_type) # type: ignore[attr-defined, union-attr] + tb = val.tp_getattro_impl( + # pyrefly: ignore[bad-argument-type] + self, + "__traceback__", + ) + if sys.version_info >= (3, 14): + if not isinstance(self.stack[-4], NullVariable): + args.append(self.stack[-4]) + else: + if not (len(self.stack) >= 7): + raise AssertionError("expected len(self.stack) >= 7 to be true") + fn = self.stack[-7] + val = self.stack[-2] + if not pyexception_instance_check(val): + raise AssertionError( + "expected _exception_instance_check(val) to be true" + ) + typ = BuiltinVariable(val.exc_type) # type: ignore[attr-defined] + + tb = val.tp_getattro_impl(self, "__traceback__") + + args += [typ, val, tb] + self.call_function(fn, args, {}) + + def exception_handler(self, raised_exception: ObservedException) -> None: + observed_exn_gb_explanation = ( + "Dynamo found no exception handler at the top-level compiled function " + "when encountering an exception. Exception will propagate outside the compiled region." + ) + + def bubble_exception_to_interpreter() -> None: + # Bubble the exception to the interpreter + if isinstance(raised_exception, FakeTensorObservedException): + from .exc import format_graph_break_message + + msg = format_graph_break_message( + "RuntimeError when making fake tensor call", + "", + str(raised_exception), + [*graph_break_hints.USER_ERROR], + ) + e = exc.TorchRuntimeError( + msg, getattr(raised_exception, "real_stack", None) + ) + raise e.with_traceback(raised_exception.__traceback__) from None + + curr_exc = self.exn_vt_stack.get_raised_exception() + dynamo_exc = exc.get_dynamo_observed_exception(curr_exc.python_type()) + if not isinstance(raised_exception, dynamo_exc): + raise AssertionError( + "expected isinstance(raised_exception, dynamo_exc) to be true" + ) # sanity check + unimplemented( + gb_type="Observed exception", + context=f"raised exception {curr_exc.debug_repr()}", + explanation=observed_exn_gb_explanation, + hints=[ + *graph_break_hints.USER_ERROR, + *graph_break_hints.SUPPORTABLE, + ], + from_exc=raised_exception, + ) + + if sys.version_info >= (3, 11): + exn_tab_entry = self.current_instruction.exn_tab_entry + if exn_tab_entry: + # Implementation is based on https://github.com/python/cpython/blob/3.11/Objects/exception_handling_notes.txt + + # 1) pop values from the stack until it matches the stack depth + # for the handler + while len(self.stack) > exn_tab_entry.depth: + self.pop() + + # 2) if 'lasti' is true, then push the offset that the exception was raised at + if exn_tab_entry.lasti: + self.push( + VariableTracker.build(self, self.current_instruction.offset) + ) + + # 3) push the exception to the stack + self.push(self.exn_vt_stack.get_raised_exception()) + + # 4) jump to the handler + self.jump(exn_tab_entry) # type: ignore[arg-type] + else: + # No handler found. Bubble the exception to the parent + # instruction translator. We use special exception for this. + self.stack.clear() + + # attach traceback to the exception and set it as current exception + curr_exc = self.exn_vt_stack.get_raised_exception() + self._attach_traceback_to_exception(curr_exc) + + if type(self) is InstructionTranslator: + bubble_exception_to_interpreter() + raise raised_exception + else: + if len(self.block_stack): + # base implementation - https://github.com/python/cpython/blob/3.10/Python/ceval.c#L4455 + + block_stack_entry = self.block_stack.pop() + + while block_stack_entry.inst.opname == "EXCEPT_HANDLER": + # https://github.com/python/cpython/blob/3.10/Python/ceval.c#L1456 + self.popn(3) + self.exn_vt_stack.pop() + if len(self.block_stack) == 0: + # No handler found in this frame. Bubble the exception to the parent + # instruction translator. + self.stack.clear() + if type(self) is InstructionTranslator: + bubble_exception_to_interpreter() + + raise raised_exception + block_stack_entry = self.block_stack.pop() + + exception_var = self.exn_vt_stack.get_raised_exception() + self.exn_vt_stack.move_current_exception_to_stack() + + # 1) pop values from the stack until it matches the stack depth + # for the handler + while len(self.stack) > block_stack_entry.stack_index: + self.pop() + + # Push a dummy block stack entry of EXCEPT_HANDLER + # https://github.com/python/cpython/blob/3.10/Python/ceval.c#L1456 + except_handler_inst = Instruction(int(1e6), "EXCEPT_HANDLER", None, 0) + self.block_stack.append( + BlockStackEntry(except_handler_inst, None, len(self.stack)) + ) + + # Push old exception + if len(self.exn_vt_stack) >= 2: + old_exception = self.exn_vt_stack[-2] + + # Push the old exception on to stack - tb, value, type + # Traceback is currently mapped to UnknownVariable + self.push(variables.UnknownVariable()) + self.push(old_exception) + + self.push(variables.BuiltinVariable(old_exception.exc_type)) + else: + # Push empty exception tb, value, type + self.push(ConstantVariable.create(None)) + self.push(ConstantVariable.create(None)) + self.push(ConstantVariable.create(None)) + + # Push new exception - tb, val, type + # Traceback is currently mapped to UnknownVariable + self.push(variables.UnknownVariable()) + self.push(exception_var) + + self.push(variables.BuiltinVariable(exception_var.exc_type)) + + # Jump to target + self.jump(block_stack_entry) + else: + # No handler found. Bubble the exception to the parent + # instruction translator. We use special exception for this. + self.stack.clear() + if type(self) is InstructionTranslator: + bubble_exception_to_interpreter() + raise raised_exception + + def PUSH_EXC_INFO(self, inst: Instruction) -> None: + # https://docs.python.org/3/library/dis.html#opcode-PUSH_EXC_INFO + # Pops a value from the stack. Pushes the current exception to the top + # of the stack. Pushes the value originally popped back to the stack. + # + # The behavior of this opcode in CPython is a bit different than what it + # is described. It pops a value from the stack, pushes the top of the + # exception stack to the interpreter stack and moves the + # "current exception" to the exception stack. + # + # As an example, suppose the stack is in the following state: + # + stack = [..., ConstantVariable(1), ConstantVariable(2)] + # + current_exception = TypeError + # + exception_stack = [ValueError] + # + # After PUSH_EXC_INFO is executed + # + stack = [..., ConstantVariable(1), ValueError, ConstantVariable(2)] + # + current_exception = None + # + exception_stack = [ValueError, TypeError] + + val = self.pop() + if len(self.exn_vt_stack) == 0: + prev_exc: VariableTracker = ConstantVariable.create(None) + else: + prev_exc = self.exn_vt_stack[-1] + self.push(prev_exc) + self.push(val) + self.exn_vt_stack.move_current_exception_to_stack() + + def POP_EXCEPT(self, inst: Instruction) -> None: + if sys.version_info >= (3, 11): + _ = self.pop() + # This exception is handled and therefore we can clear the error indicator + if not len(self.exn_vt_stack): + raise AssertionError("expected len(self.exn_vt_stack) to be true") + self.exn_vt_stack.pop() + else: + if not (len(self.block_stack) > 0): + raise AssertionError("expected len(self.block_stack) > 0 to be true") + if self.block_stack[-1].inst.opname != "EXCEPT_HANDLER": + raise AssertionError( + "Bug in Dynamo tracing of exception handling." + "Top of the block stack is not EXCEPT_HANDLER." + ) + self.block_stack.pop() + + self.popn(3) + + # This exception is handled and therefore we can clear the error indicator + if not len(self.exn_vt_stack): + raise AssertionError("expected len(self.exn_vt_stack) to be true") + self.exn_vt_stack.pop() + + def check_if_exc_matches(self) -> bool: + if not (len(self.stack) >= 2): + raise AssertionError("expected len(self.stack) >= 2 to be true") + expected_exc_types = self.pop() + if sys.version_info >= (3, 11): + # CHECK_EXC_MATCH (which is used from 3.11 onwards) does not pop. + # This is the description from the disassembly doc + # + # Performs exception matching for ``except``. Tests whether the ``STACK[-2]`` + # is an exception matching ``STACK[-1]``. Pops ``STACK[-1]`` and pushes the boolean + # result of the test. + exc_instance = self.stack[-1] + else: + # This is used prior to 3.11 via opcode JUMP_IF_NOT_EXC_MATCH + # There is no documentation but here is the code pointer that does 2 pops + # https://github.com/python/cpython/blob/3.10/Python/ceval.c#L3650-L3665 + exc_instance = self.stack.pop() + + # Users can check exception in 3 ways + # 1) except NotImplementedError --> BuiltinVariable + # 2) except CustomException --> UserDefinedExceptionClassVariable + # 3) except (NotImplementedError, AttributeError) -> TupleVariable + + if not isinstance( + expected_exc_types, + ( + BuiltinVariable, + TupleVariable, + UserDefinedExceptionClassVariable, + UserDefinedExceptionObjectVariable, + ), + ): + unimplemented( + gb_type="Exception with bad expected type", + context=str(expected_exc_types), + explanation=f"`except ...` has unsupported type {expected_exc_types}.", + hints=[*graph_break_hints.USER_ERROR], + ) + + if sys.version_info >= (3, 11): + if not pyexception_instance_check(exc_instance): + unimplemented( + gb_type="Caught non-Exception value", + context=str(exc_instance), + explanation=f"Except expects to receive an object of Exception type but received {exc_instance}.", + hints=[*graph_break_hints.USER_ERROR], + ) + + if isinstance(expected_exc_types, TupleVariable): + expected_types = expected_exc_types.items + else: + expected_types = [ + expected_exc_types, + ] + + for expected_type in expected_types: + if not isinstance( + expected_type, + ( + BuiltinVariable, + UserDefinedExceptionObjectVariable, + UserDefinedExceptionClassVariable, + ), + ): + unimplemented( + gb_type="Exception with non-type expectation", + context=str(expected_type), + explanation=f"`except ...` expects a non-type: {expected_type}.", + hints=[*graph_break_hints.USER_ERROR], + ) + if pyexception_instance_check(exc_instance) and issubclass( + exc_instance.exc_type, # type: ignore[union-attr] + expected_type.fn, # type: ignore[attr-defined] + ): + return True + elif isinstance(exc_instance, variables.BuiltinVariable) and issubclass( + exc_instance.fn, + # pyrefly: ignore [invalid-argument] + expected_type.fn, + ): + return True + + return False + + def CHECK_EXC_MATCH(self, inst: Instruction) -> None: + self.push(VariableTracker.build(self, self.check_if_exc_matches())) + + def JUMP_IF_NOT_EXC_MATCH(self, inst: Instruction) -> None: + if not self.check_if_exc_matches(): + self.jump(inst) + + @break_graph_if_unsupported( + push=True, + msg_prefix="Encountered graph break when attempting to trace COMPARE_OP: a comparison operation, e.g. a == b", + ) + def COMPARE_OP(self, inst: Instruction) -> None: + if inst.argval == "exception match": + self.CHECK_EXC_MATCH(inst) + else: + self.push(compare_op_handlers[inst.argval](self, self.popn(2), {})) + + def GET_ITER(self, inst: Instruction) -> None: + # This is intentionally different from cpython 3.15+. Cpython creates virtual iterators for certain types + # (i.e. lists/tuples), represented on the stack by the iterable + an integer index. Other types call the + # builtin iter and are represented by iterator + null. We could mimic this in dynamo, but it becomes + # problematic for resuming from graph breaks in list comprehensions. Cpython uses tagged ints (not PyObject) to + # represent the index, and we can only restore boxed ints, which creates an invalid stack state. So instead of + # trying, we just always create a true iterator. + self.push(generic_getiter(self, self.pop())) + if sys.version_info >= (3, 15): + self.push(NullVariable()) + + @break_graph_if_unsupported( + push=True, + msg_prefix="Encountered graph break when attempting to trace CALL_FUNCTION: a call to a regular function, e.g. f(x, y)", + ) + def CALL_FUNCTION(self, inst: Instruction) -> None: + args = self.popn(inst.argval) + fn = self.pop() + self.call_function(fn, args, {}) + + @break_graph_if_unsupported( + push=True, + msg_prefix="Encountered graph break when attempting to trace CALL_FUNCTION_EX: a variadic function call, e.g. f(*args)", + ) + def CALL_FUNCTION_EX(self, inst: Instruction) -> None: + kwargsvars: VariableTracker + if inst.argval == 0: + kwargsvars = ConstDictVariable({}) + argsvars = self.pop() + elif inst.argval == 1 or sys.version_info >= (3, 14): + # Python 3.14+ removed the argval and replaced it with a possibly NULL kwargs + kwargsvars = self.pop() + if isinstance(kwargsvars, NullVariable): + kwargsvars = ConstDictVariable({}) + argsvars = self.pop() + else: + unimplemented( + gb_type="Variadic function call with bad flags", + context=f"flags: {inst.argval}", + explanation=f"Attempted to call a variadic function (CALL_FUNCTION_EX) with bad flags {inst.argval}", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + + if sys.version_info >= (3, 13): + # 3.13 swapped null and callable + null = self.pop() + if not isinstance(null, NullVariable): + raise AssertionError( + "expected isinstance(null, NullVariable) to be true" + ) + + fn = self.pop() + + if sys.version_info >= (3, 11) and sys.version_info < (3, 13): + null = self.pop() + if not isinstance(null, NullVariable): + raise AssertionError( + "expected isinstance(null, NullVariable) to be true" + ) + + if not isinstance( + argsvars, + BaseListVariable, + ): + argsvars = TupleVariable(unpack_iterable(self, argsvars)) + + # Unpack for cases like fn(**obj) where obj is a map + if isinstance(kwargsvars, UserDefinedObjectVariable): + kwargsvars = DictBuiltinVariable.call_custom_dict(self, dict, kwargsvars) # type: ignore[arg-type] + + # pyrefly: ignore [unbound-name] + if not isinstance(argsvars, BaseListVariable) or not isinstance( + # pyrefly: ignore [unbound-name] + kwargsvars, + ConstDictVariable, + ): + unimplemented( + gb_type="Variadic function call with bad args/kwargs type", + # pyrefly: ignore [unbound-name] + context=f"args type: {typestr(argsvars)}, kwargs type: {typestr(kwargsvars)}", + explanation="Expected args to be a list and kwargs to be a dict", + hints=[*graph_break_hints.USER_ERROR], + ) + + # Map to a dictionary of str -> VariableTracker + # pyrefly: ignore [bad-assignment, unbound-name] + kwargsvars = kwargsvars.keys_as_python_constant() + # pyrefly: ignore [bad-argument-type, unbound-name] + self.call_function(fn, argsvars.items, kwargsvars) + + @break_graph_if_unsupported( + push=True, + msg_prefix="Encountered graph break when attempting to trace CALL_FUNCTION_KW: " + "a function call with keyword arguments, e.g. f(x=True)", + ) + def CALL_FUNCTION_KW(self, inst: Instruction) -> None: + argnames = self.pop() + args = self.popn(inst.argval) + fn = self.pop() + if not isinstance(argnames, TupleVariable): + raise AssertionError( + "expected isinstance(argnames, TupleVariable) to be true" + ) + if not argnames.is_python_constant(): + raise AssertionError("expected argnames.is_python_constant() to be true") + argnames = argnames.as_python_constant() + args, kwargs_list = args[: -len(argnames)], args[-len(argnames) :] + kwargs = dict(zip(argnames, kwargs_list)) + if len(kwargs) != len(argnames): + raise AssertionError("expected len(kwargs) == len(argnames) to be true") + self.call_function(fn, args, kwargs) + + def LOAD_METHOD_SUPER(self, inst: Instruction) -> None: + self.CALL_FUNCTION(dataclasses.replace(inst, argval=2)) + arg = inst.argval[0] + argval = self.code_options["co_names"][arg] + if sys.version_info < (3, 11): + self._load_attr(argval) + else: + self.LOAD_METHOD(dataclasses.replace(inst, argval=argval)) + + def LOAD_ATTR_SUPER(self, inst: Instruction) -> None: + self.CALL_FUNCTION(dataclasses.replace(inst, argval=2)) + arg = inst.argval[0] + argval = self.code_options["co_names"][arg] + self._load_attr(argval) + + def LOAD_METHOD(self, inst: Instruction) -> None: + self._load_attr(inst.argval) + obj = self.pop() + if sys.version_info >= (3, 13): + self.push(obj) + self.PUSH_NULL(inst) + elif sys.version_info >= (3, 11): + # always follow the NULL + fn convention, since if obj + # is actually a method, self is already bound to it, so it + # doesn't need to be passed in as an arg. + self.PUSH_NULL(inst) + self.push(obj) + else: + raise AssertionError( + "LOAD_METHOD should have been rewritten to LOAD_ATTR. We should never reach here." + ) + + def CALL_METHOD(self, inst: Instruction) -> None: + raise AssertionError( + "CALL_METHOD should have been rewritten to CALL_FUNCTION. This function should never be called." + ) + + def _load_attr(self, attr: Any) -> None: + obj = self.pop().realize() + try: + result = generic_getattr(self, obj, attr) + except Unsupported: + if not obj.is_python_constant(): + raise + source = AttrSource(obj.source, attr) if obj.source else None + result = VariableTracker.build( + self, getattr(obj.as_python_constant(), attr), source=source + ) + self.push(result) + + def LOAD_ATTR(self, inst: Instruction) -> None: + if sys.version_info >= (3, 12): + if inst.arg is None or inst.arg % 2 != 0: + raise AssertionError( + "LOAD_ATTR method variant should have been normalized by " + "remove_load_attr_method_variant in cleaned_instructions" + ) + self._load_attr(inst.argval) + + @break_graph_if_unsupported( + push=False, + msg_prefix="Encountered graph break when attempting to trace STORE_ATTR: storing an object's attribute, e.g. x.attr = y", + ) + def STORE_ATTR(self, inst: Instruction) -> None: + val, obj = self.popn(2) + VariableTracker.build(self, setattr).call_function( + self, # type: ignore[arg-type] + [obj, VariableTracker.build(self, inst.argval), val], + {}, + ) + + def DELETE_ATTR(self, inst: Instruction) -> None: + obj = self.pop() + self._maybe_sync_dealloc_attr(obj, inst.argval) + VariableTracker.build(self, delattr).call_function( + self, # type: ignore[arg-type] + [obj, VariableTracker.build(self, inst.argval)], + {}, + ) + + def _maybe_sync_dealloc_attr(self, obj: VariableTracker, name: str) -> None: + # Only check side_effects — a pure dict lookup with no observable + # side effects. We intentionally avoid tp_getattro_impl here because it + # can trigger __getattr__, add graph nodes, or cause graph breaks. + if self.output.side_effects.has_pending_mutation_of_attr(obj, name): + attr_var = self.output.side_effects.load_attr(obj, name) + if isinstance(attr_var, TensorVariable): + self._maybe_emit_sync_dealloc(attr_var) + + @staticmethod + def codegen_return_with_pops( + inst: Instruction, num_stack: int + ) -> list[Instruction]: + """ + Debug CPython expects the stack to be empty after the return. + Calling compile_subgraph will push cells and frame values to TOS. + This function will pop those 2 values from the stack before actually returning. + + Expects the stack to be: + cells, frame values, current frame stack (0 or 1 values) + + Pops cells and frame values, leaving the current frame stack as TOS. + A return instruction is included. + """ + insts = [] + # NOTE: Debug CPython expects the stack to be empty after the return. + # Expect the current stack to be in the state + # cells, frame values, current frame stack (0 or 1 values) + if not (num_stack <= 1): + raise AssertionError("expected num_stack <= 1 to be true") + if num_stack == 1: + insts.extend(create_swap(3)) + return_inst = ( + create_instruction("RETURN_VALUE") + if inst.opname == "RETURN_VALUE" + else create_instruction("RETURN_CONST", argval=inst.argval) + ) + insts.extend( + [create_instruction("POP_TOP"), create_instruction("POP_TOP"), return_inst] + ) + return insts + + def create_resume( + self, + idx: int, + resume_inst: Instruction, + meta: StackLocalsMetadata, + resume_codes: list[types.CodeType], + cg: PyCodegen, + is_leaf: bool, + handle_inactive_ctx: bool, + ) -> tuple[types.CodeType, str]: + """ + Creates the resume function for the frame corresponding to `self`. + + Expects the TOS to be: + [frame N cells, ..., frame 1 cells], + [ + frame N stack + locals, + ..., + frame 1 stack + locals + ] + + Some additional codegen may happen to prepare the frame stack + locals values for the generated resume function: + - inactive context variables in the stack and locals will be replaced by their types + - if the frame is a leaf frame, prune dead locals + + Regardless of codegen, the stack will be left in the same state as before. + + Args: + - idx: depth of this frame: 0 corresponds to the leaf frame (frame N), N-1 to the root frame (frame 1). + - resume_inst: the instruction that this frame should resume at + - meta: metadata for this frame returned from OutputGraph.compile_subgraph + - resume_codes: nested resume code objects generated from previous create_resume calls. + - cg: codegen object to output to + - is_leaf: True if `self` corresponds to the leaf frame. + - handle_inactive_ctx: If True, handles inactive context variables as described above. This is necessary + iff the resume function is traced + """ + # Handle inactive context variables. + # The resume function assumes that context variables are the class, NOT the object. + # e.g. torch.set_grad_enabled(True) will be reconstructed as torch.set_grad_enabled + # NOTE: if the unsupported instruction modifies the inactive context variable, it may + # result in silent incorrectness! + if handle_inactive_ctx: + for (j, _), j_orig in zip(meta.stack_ctx_args, meta.stack_ctx_idxes_orig): + # Replace the stack var with the context class + ctx = cast(ContextWrappingVariable, self.stack[j_orig]) + # frames[idx][j] = reconstructed_ctx + cg.append_output(create_dup_top()) + ctx.reconstruct_type(cg) + cg.extend_output( + [ + *create_swap(2), + cg.create_load_const(idx), + cg.create_binary_subscr(), + cg.create_load_const(j), + create_instruction("STORE_SUBSCR"), + ] + ) + + for name, _ in meta.locals_ctx_args: + # Replace the local with the context class + ctx = cast(ContextWrappingVariable, self.symbolic_locals[name]) + # frames[idx][meta.num_stack +meta.locals_names[name]] = reconstructed_ctx + cg.append_output(create_dup_top()) + ctx.reconstruct_type(cg) + cg.extend_output( + [ + *create_swap(2), + cg.create_load_const(idx), + cg.create_binary_subscr(), + cg.create_load_const(meta.num_stack + meta.locals_names[name]), + create_instruction("STORE_SUBSCR"), + ] + ) + + # If the resume instruction is a jump absolute, then resume + # at the target instead. This handles the case where we + # graph break again in a nested function before jump-resuming + # this frame. + if is_jump_absolute(resume_inst): + if not resume_inst.target: + raise AssertionError("expected resume_inst.target to be true") + resume_inst = resume_inst.target + + resume_name = unique_id(f"__resume_at_{resume_inst.offset}") + + # More locals may have been pruned in the current/leaf frame + # after the unsupported instruction (e.g. branch). + # There should not be any pruning in the other frames since + # the current instruction there should be a CALL. + if is_leaf: + reads = livevars_analysis(self.instructions, resume_inst) + # inspect.signature() renames ".N" to "implicitN" for comprehension + # iterator variables. Build a mapping to emit the bytecode name + # (.0) in argnames so the resume function's co_varnames matches + # the bytecode instructions. + implicit_to_bytecode: dict[str, str] = {} + for name in self.f_code.co_varnames: + if name.startswith("."): + implicit_to_bytecode[name.replace(".", "implicit")] = name + all_argnames = tuple( + implicit_to_bytecode.get(k, k) + for k in self.symbolic_locals + if implicit_to_bytecode.get(k, k) in reads + and k not in self.cell_and_freevars() + ) + argnames_null_set = { + implicit_to_bytecode.get(k, k) for k in meta.locals_null_keys + } + argnames = tuple(k for k in all_argnames if k not in argnames_null_set) + argnames_null = tuple(k for k in all_argnames if k in argnames_null_set) + + # codegen filter for current frame's locals + # current stack state: frames + cg.extend_output( + [ + create_dup_top(), + cg.create_load_const(idx), + cg.create_binary_subscr(), + create_dup_top(), + ] + ) + bytecode_to_implicit = {v: k for k, v in implicit_to_bytecode.items()} + for arg in argnames: + # current stack state: frames, frames[i], *(prev locals), frames[i] + locals_key = bytecode_to_implicit.get(arg, arg) + cg.extend_output( + [ + create_dup_top(), + cg.create_load_const( + meta.num_stack + meta.locals_names[locals_key] + ), + cg.create_binary_subscr(), + *create_swap(2), + ], + ) + # current stack state: frames, frames[i], *(frame i live locals), frames[i] + cg.extend_output( + [ + create_instruction("POP_TOP"), + create_instruction("BUILD_LIST", arg=len(argnames)), + *create_swap(2), + # frames, frames i live locals, frames[i] + *create_binary_slice(meta.num_stack, None, True), + # frames[i][num_stack:] = frame i live locals + ] + ) + # current stack state: frames + else: + argnames = tuple(meta.locals_names.keys()) + argnames_null = tuple(meta.locals_null_keys) + + if sys.version_info < (3, 12): + if len(argnames_null) != 0: + raise AssertionError("variables should not be NULL in < 3.12") + + # compile_subgraph did not codegen any NULLs, + # so we should not count NullVariables + stack_len = len(self.stack) - len(meta.stack_null_idxes) + + if self.current_instruction.offset is None: + raise AssertionError( + "expected self.current_instruction.offset is not None to be true" + ) + new_code: types.CodeType = ContinueExecutionCache.lookup( + self.f_code, + self.lineno, + self.current_instruction.offset, + resume_inst.offset, + # pyre: ignore[missing-attribute] + tuple(b.target.offset for b in self.block_stack), + stack_len, + argnames, + argnames_null, + tuple(b.resume_fn() for b in self.block_stack), + handle_inactive_ctx, + tuple(meta.stack_ctx_args), + tuple(meta.locals_ctx_args), + tuple(meta.stack_null_idxes), + tuple(resume_codes), + not self.current_instruction_push, + ) + + # Add original GraphModule context to the resume function to handle + # the case of a graph break while tracing a GraphModule + orig_graphmodule_maybe = code_context.get_context(self.f_code).get( + "orig_graphmodule", lambda: None + )() + if orig_graphmodule_maybe is not None: + code_context.get_context(new_code)["orig_graphmodule"] = weakref.ref( + orig_graphmodule_maybe + ) + + # add resume function to the global scope + self.output.install_resume_function_global( + resume_name, new_code, self.f_globals + ) + if self.package is not None: + self.package.add_resume_function( + new_code, self.f_globals["__name__"], resume_name + ) + + counters["resumes"][new_code.co_name] += 1 + + return new_code, resume_name + + def _maybe_replace_warnings_warn_on_stack(self, inst: Instruction) -> None: + """Replace warnings.warn on the symbolic stack with a wrapper that + preserves the leaf frame's source location for warning dedup. + + When nested graph breaks inline a warnings.warn call into the root + frame's bytecode, the root frame's line numbers defeat Python's + per-location warning dedup. This replaces the SkipFunctionVariable + for warnings.warn on the symbolic stack before compile_subgraph, so + the codegen naturally reconstructs the wrapper via LOAD_GLOBAL. + """ + if inst.arg is None: + return + + try: + depth = get_call_callable_depth(inst.opname, inst.arg) + except ValueError: + return + + callable_idx = len(self.stack) - depth + callable_var = self.stack[callable_idx] + if not ( + isinstance(callable_var, SkipFunctionVariable) + and callable_var.value is _warnings.warn + ): + return + + leaf_filename = self.f_code.co_filename + leaf_lineno = inst.positions.lineno if inst.positions else inst.starts_line + if leaf_lineno is None: + return + + wrapper = _make_warnings_warn_wrapper(leaf_filename, leaf_lineno) + wrapper_name = self.output.install_global("__warnings_warn_wrapper", wrapper) + self.stack[callable_idx] = SkipFunctionVariable( + wrapper, source=GlobalSource(wrapper_name) + ) + + def create_call_resume_at( + self, + inst: Instruction, + all_stack_locals_metadata: list[StackLocalsMetadata], + ) -> list[Instruction]: + """ + Codegen all resume function(s) from the frame stack starting at `self`, call them, + and return the result. + Assumes that the unsupported instruction has already been run. + + Expects the TOS to be: + [ + frame N locals, + frame N-1 stack + locals, + ..., + frame 1 stack + locals + ], *(frame N stack (post-unsupported instruction)) + + Leaves the result of calling the resume functions on the stack and returns it + (empty stack after return). + + Args: + - inst: the instruction of the current (deepest) frame to resume at + - all_stack_locals_metadata: metadata returned from OutputGraph.compile_subgraph - contains + metadata such as local names, NULL positions, stack length, etc. + """ + + self.instruction_pointer = None + + cg = PyCodegen(self.output.root_tx) + + # NOTE: We do not need to codegen frames whose resume instruction is RETURN_VALUE + # We could also do something similar for RETURN_CONST, but a lot more code is necessary + # since we would need to track RETURN_CONST values and inject the constant in the right places. + + # Filter out tx'es that are resuming on RETURN_*. + txes: list[InstructionTranslatorBase] = [] + idxes: list[int] = [] + resume_insts: list[Instruction] = [] + cur_tx: InstructionTranslatorBase | None = self + idx = 0 + while cur_tx is not None: + if cur_tx is self: + resume_inst = inst + else: + resume_inst = cur_tx.next_instruction + if resume_inst.opname != "RETURN_VALUE": + txes.append(cur_tx) + idxes.append(idx) + resume_insts.append(resume_inst) + + cur_tx = cur_tx.parent + idx += 1 + + current_num_stack = len(self.stack) - len( + all_stack_locals_metadata[0].stack_null_idxes + ) + + # Every tx is returning - no need to call a resume function. + if not txes: + # Pop everything but TOS, then return the TOS. + # Frame N's stack must have length >= 1 since it's about to RETURN_VALUE. + # Frame N actually should have stack length == 1, because debug CPython expects + # empty stacks after return, but there is no guarantee written down anywhere. + if not (current_num_stack >= 1): + raise AssertionError("expected current_num_stack >= 1 to be true") + cg.extend_output(create_swap(current_num_stack + 2)) + for _ in range(current_num_stack + 1): + cg.append_output(create_instruction("POP_TOP")) + cg.append_output(create_instruction("RETURN_VALUE")) + + return cg.get_instructions() + + # Let frame k be the deepest frame where the resume function is not RETURN_VALUE + # - If k == N, then the frame N stack is prepended to the frame N locals. + # - If k != N, then frame N's TOS is added to frame k's stack. + + # Rearrange the TOS to be compatible with create_resume and codegen_call_resume: + # [ + # frame N stack + locals, + # ..., + # frame 1 stack + locals + # ] + + # create the stack values that should be moved + if txes[0] is self: + # Frame N is non-returning, pack all of frame N's stack to + # be moved to frame N's frame values + cg.append_output(create_instruction("BUILD_LIST", arg=current_num_stack)) + # frame N stack is not yet on the frame N's frame values + stack_insert_idx = 0 + all_stack_locals_metadata[0].num_stack = current_num_stack + else: + # Frame N is returning. Let frame k be the deepest non-returning frame. + # Add frame N's TOS to frame k's stack. + # pop frame N stack except TOS + cg.extend_output(create_swap(current_num_stack)) + for _ in range(current_num_stack - 1): + cg.append_output(create_instruction("POP_TOP")) + cg.append_output(create_instruction("BUILD_LIST", arg=1)) + # frame k stack is already on frame k's frame values + stack_insert_idx = all_stack_locals_metadata[idxes[0]].num_stack + all_stack_locals_metadata[idxes[0]].num_stack += 1 + txes[0].push(UnknownVariable()) + + # move the predetermined stack value(s) to the deepest non-returning frame + cg.extend_output( + [ + *create_copy(2), + # frame_values, return_const, frame_values + cg.create_load_const(idxes[0]), + cg.create_binary_subscr(), + *create_binary_slice(stack_insert_idx, stack_insert_idx, True), + # frame_values[idxes[0]][stack_insert_idx:stack_insert_idx] = frame N stack/[return_const/TOS] + # frame_values left on top of stack + ] + ) + + # filter out frame values of skipped tx'es + filter_insts = [] + for idx in idxes: + filter_insts.extend( + [ + create_dup_top(), + cg.create_load_const(idx), + cg.create_binary_subscr(), + *create_swap(2), + ] + ) + # TOS: cells, frame_values[idxes[0]], ..., frame_values[idxes[...]], frame_values + filter_insts.extend( + [ + create_instruction("POP_TOP"), + create_instruction("BUILD_LIST", arg=len(idxes)), + ] + ) + # TOS: cells, filtered frame_values + + cg.extend_output(filter_insts) + # filter out cells of skipped tx'es using the same instructions in filter_insts, + # but with cells as TOS instead of frame values + cg.extend_output( + [ + *create_swap(2), + *copy.deepcopy(filter_insts), + *create_swap(2), + ] + ) + # TOS: filtered cells, filtered frame_values + + resume_codes: list[types.CodeType] = [] + resume_names = [] + for i, cur_tx in enumerate(txes): + resume_code, resume_name = cur_tx.create_resume( + i, + resume_insts[i], + all_stack_locals_metadata[idxes[i]], + resume_codes, + cg, + cur_tx is self, + True, + ) + resume_codes.append(resume_code) + resume_names.append(resume_name) + + self.codegen_call_resume(resume_codes, resume_names, cg) + cg.append_output(create_instruction("RETURN_VALUE")) + + return cg.get_instructions() + + @staticmethod + def codegen_call_resume( + resume_codes: list[types.CodeType], resume_names: list[str], cg: PyCodegen + ) -> None: + """ + Calls the provided resume functions. + + Expects the TOS to be in the state: + [frame N cells, ..., frame 1 cells], + [ + frame N stack + locals, + frame N-1 stack + locals, + ..., + frame 1 stack + locals + ] + + Pops the cells and frame values, leaving the result of calling the resume functions on TOS. + + Args: + - resume_codes: list of resume function code objects to call + - resume_names: list of the corresponding names of the resume functions + - cg: PyCodegen object to output instructions to + """ + # NOTE: We will load cells as we load resume functions + + # load resume functions except the root's + cg.extend_output(create_copy(2)) + for i, (name, code) in enumerate(zip(resume_names, resume_codes)): + if i == len(resume_names) - 1: + break + # stack: cells, frames, *(resume 1, ...), cells + if code.co_freevars: + cg.extend_output( + [ + create_dup_top(), + cg.create_load_const(i), + cg.create_binary_subscr(), + ] + ) + # Call the factory function (stored under resume_name) to + # create the resume function with correct globals and closure. + cg.extend_output( + [ + cg.create_load_global(name, add=True), + *create_swap(2), + *create_call_function(1, push_null=True), + ] + ) + else: + cg.extend_output(cg.load_function_name(name, False, 0)) + cg.extend_output(create_swap(2)) + cg.extend_output( + [ + create_instruction("POP_TOP"), + create_instruction("BUILD_LIST", arg=len(resume_codes) - 1), + ] + ) + + # stack: cells, frames, [resume 1, ..., resume N - 1] + # load root resume function + cg.extend_output(create_swap(3)) + if resume_codes[-1].co_freevars: + cg.extend_output( + [ + cg.create_load_const(-1), + cg.create_binary_subscr(), + ] + ) + # Call the factory function to create the resume function with + # correct globals and closure. + cg.extend_output( + [ + cg.create_load_global(resume_names[-1], add=True), + *create_swap(2), + *create_call_function(1, push_null=True), + ] + ) + cg.extend_output( + [ + *create_rot_n(3), + ] + ) + else: + cg.extend_output( + [ + create_instruction("POP_TOP"), + *cg.load_function_name(resume_names[-1], False), + *create_rot_n(3), + ] + ) + + # resume 1, [resume N, ..., resume 2], frames + + # load top level-frame; final stack state should be: + # first resume function (+ NULL), + # [ + # [resume N, ..., resume 2], + # [ + # frame N stack + locals, + # ..., + # frame 2 stack + locals, + # ], *(frame 1 stack + locals) + # ] + cg.extend_output( + [ + create_dup_top(), + create_dup_top(), + # frames, frames, frames + cg.create_load_const(-1), + cg.create_binary_subscr(), + # frames, frames, frames[-1] + *create_swap(2), + # frames, frames[-1], frames + cg.create_load_const(-1), + create_instruction("DELETE_SUBSCR"), + ] + ) + + # TOS: resume 1, remaining resumes, frames (popped), frame 1 stack + locals + cg.extend_output( + [ + *create_rot_n(3), + create_instruction("BUILD_LIST", arg=2), + *create_swap(2), + # [resumes, frames (popped)], frame 1 stack + locals + create_instruction("LIST_EXTEND", arg=1), + ] + ) + + # TOS: resume 1, [remaining resumes, frames, *(frame 1 stack + locals)] + cg.extend_output(create_call_function_ex(False, True)) + + def should_compile_partial_graph(self) -> bool: + if sys.version_info >= (3, 11): + # Do not compile if current instruction's block is not the top with block + entry = self.current_instruction.exn_tab_entry + if entry and ( + not self.block_stack or entry.target is not self.block_stack[-1].target + ): + return False + return ( + all(b.can_restore() for b in self.block_stack) + and not self.one_graph + # Only the leaf tracer's error_on_graph_break should be used + and (self.is_child_tracer_active or not self.error_on_graph_break) + and not self.is_tracing_resume_prologue + and not self.active_generic_context_managers + and not self.skip_one_hop_torch_function_depth + # Do not allow nested graph breaks in HOPs + and self.output.current_tracer.parent is None + ) + + @break_graph_if_unsupported( + push=False, + msg_prefix="Encountered graph break when attempting to trace STORE_SUBSCR: trying to store subscript, e.g. x[key] = y", + ) + def STORE_SUBSCR(self, inst: Instruction) -> None: + val, obj, key = self.popn(3) + generic_setitem(self, obj, key, val) + + def DELETE_SUBSCR(self, inst: Instruction) -> None: + obj, key = self.popn(2) + # Check for tensor items using side-effect-free internal lookups + # only. We avoid call_method("__getitem__") because it can execute + # user code and add unwanted graph nodes. + self._maybe_sync_dealloc_subscr(obj, key) + generic_delitem(self, obj, key) + + def _maybe_sync_dealloc_subscr( + self, obj: VariableTracker, key: VariableTracker + ) -> None: + from .variables.dicts import ConstDictVariable + from .variables.lists import BaseListVariable + + # TODO(dynamo-team): Refactor this to use sq_item / mp_ass_subscript + + item_var = None + try: + if isinstance(obj, BaseListVariable): + item_var = obj.getitem_const( + self, # pyrefly: ignore [bad-argument-type] + key, + ) + elif isinstance(obj, ConstDictVariable): + item_var = obj.maybe_getitem_const(key) + except Exception: + pass + if isinstance(item_var, TensorVariable): + self._maybe_emit_sync_dealloc(item_var) + + def BUILD_TUPLE(self, inst: Instruction) -> None: + items = self.popn(inst.argval) + self.push(TupleVariable(items)) + + def BUILD_SLICE(self, inst: Instruction) -> None: + items = self.popn(inst.argval) + self.push(SliceVariable(items, tx=self)) # type: ignore[arg-type] + + def _can_speculate_comprehension_nested(self) -> bool: + """Check if comprehension speculation is allowed in nested context. + + For the base class (non-inlined), this always returns False. + """ + return False + + def BUILD_LIST(self, inst: Instruction) -> None: + if maybe_setup_comprehension_speculation(self, inst): + return + + items = self.popn(inst.argval) + self.push(VariableTracker.build(self, items)) + + def BUILD_SET(self, inst: Instruction) -> None: + if config.inject_BUILD_SET_unimplemented_TESTING_ONLY: + unimplemented( + gb_type="missing BUILD_SET handler", + context="", + explanation="Missing BUILD_SET bytecode handler (for testing purposes).", + hints=[], + ) + items = self.popn(inst.argval) + new_set = SetVariable(items, mutation_type=ValueMutationNew()) + self.push(new_set) + + def BUILD_LIST_UNPACK(self, inst: Instruction, cls: type = ListVariable) -> None: + seqs = self.popn(inst.argval) + items = [] + for seq in seqs: + try: + items.extend(unpack_iterable(self, seq)) + except NotImplementedError: + unimplemented( + gb_type="Failed to unpack object for BUILD_LIST_UNPACK", + context=str(seq), + explanation=f"{seq} cannot be unpacked into a list for the BUILD_LIST_UNPACK " + "bytecode (`[*x, *y, ...]`).", + hints=[*graph_break_hints.USER_ERROR], + ) + self.push(cls(items, mutation_type=ValueMutationNew())) + + def BUILD_TUPLE_UNPACK(self, inst: Instruction) -> None: + self.BUILD_LIST_UNPACK(inst, cls=TupleVariable) + + BUILD_TUPLE_UNPACK_WITH_CALL = BUILD_TUPLE_UNPACK + + def BUILD_MAP(self, inst: Instruction) -> None: + if maybe_setup_comprehension_speculation(self, inst): + return + + items = self.popn(inst.argval * 2) + d = dict(zip(items[::2], items[1::2])) + self.push(VariableTracker.build(self, d)) + + def BUILD_MAP_UNPACK(self, inst: Instruction) -> None: + items = self.popn(inst.argval) + # ensure everything is a dict + items = [ + VariableTracker.build(self, dict).call_function(self, [x], {}) + for x in items + ] # type: ignore[arg-type] + result: dict[Any, Any] = {} + for x in items: + if not isinstance(x, ConstDictVariable): + raise AssertionError( + "expected isinstance(x, ConstDictVariable) to be true" + ) + result.update(x.items) + self.push( + VariableTracker.build( + self, + result, + ) + ) + + BUILD_MAP_UNPACK_WITH_CALL = BUILD_MAP_UNPACK + + def BUILD_CONST_KEY_MAP(self, inst: Instruction) -> None: + keys = self.pop() + values = self.popn(inst.argval) + if not isinstance(keys, TupleVariable): + raise AssertionError("expected isinstance(keys, TupleVariable) to be true") + if not keys.is_python_constant(): + raise AssertionError("expected keys.is_python_constant() to be true") + + keys = unpack_iterable(self, keys) + if len(keys) != len(values): + raise AssertionError("expected len(keys) == len(values) to be true") + + self.push( + VariableTracker.build( + self, + dict(zip(keys, values)), + ) + ) + + def MAP_ADD(self, inst: Instruction) -> None: + k, v = self.popn(2) + if not (inst.argval > 0): + raise AssertionError("expected inst.argval > 0 to be true") + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + obj = self.stack[-inst.arg].realize() + if not isinstance(obj, ConstDictVariable): + raise AssertionError( + "expected isinstance(obj, ConstDictVariable) to be true" + ) + generic_setitem(self, obj, k, v) + + def SET_ADD(self, inst: Instruction) -> None: + v = self.pop() + if not (inst.argval > 0): + raise AssertionError("expected inst.argval > 0 to be true") + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + obj = self.stack[-inst.arg] + if not isinstance(obj, SetVariable): + raise AssertionError("expected isinstance(obj, SetVariable) to be true") + if not obj.is_mutable(): + raise AssertionError("expected obj.is_mutable() to be true") + obj.call_method(self, "add", [v], {}) # type: ignore[arg-type] + + def SET_UPDATE(self, inst: Instruction) -> None: + v = self.pop() + if not (inst.argval > 0): + raise AssertionError("expected inst.argval > 0 to be true") + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + obj = self.stack[-inst.arg] + if not isinstance(obj, SetVariable): + raise AssertionError("expected isinstance(obj, SetVariable) to be true") + if not obj.is_mutable(): + raise AssertionError("expected obj.is_mutable() to be true") + obj.call_method(self, "update", [v], {}) # type: ignore[arg-type] + + def LIST_APPEND(self, inst: Instruction) -> None: + v = self.pop() + if not (inst.argval > 0): + raise AssertionError("expected inst.argval > 0 to be true") + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + obj = self.stack[-inst.arg].realize() + if not isinstance(obj, ListVariable): + raise AssertionError("expected isinstance(obj, ListVariable) to be true") + if not obj.is_mutable(): + raise AssertionError("expected obj.is_mutable() to be true") + self.output.side_effects.mutation(obj) + obj.items.append(v) + + def MAKE_FUNCTION(self, inst: Instruction) -> None: + flags = inst.arg + if sys.version_info < (3, 11): + fn_name = self.pop() + code = self.pop() + if sys.version_info >= (3, 11): + # MAKE_FUNCTION behavior actually changed in 3.11, see + # https://github.com/python/cpython/pull/93189/ + if not hasattr(code.value, "co_qualname"): # type: ignore[attr-defined] + raise AssertionError( + 'expected hasattr(code.value, "co_qualname") to be true' + ) + fn_name = VariableTracker.build(self, code.value.co_qualname) # type: ignore[attr-defined] + defaults = None + closure = None + annotations = None + kwdefaults = None + + if sys.version_info < (3, 13): + # in 3.13, this is handled in SET_FUNCTION_ATTRIBUTE + if flags is not None: + if flags & 0x08: + closure = self.pop() + if flags & 0x04: + annotations = self.pop() + if flags & 0x02: + kwdefaults = self.pop() + if flags & 0x01: + defaults = self.pop() + + fn = NestedUserFunctionVariable( + fn_name, + code, + self.f_globals, + defaults, + kwdefaults, + closure, + ) + if annotations: + if not isinstance(annotations, TupleVariable): + raise AssertionError( + "expected isinstance(annotations, TupleVariable) to be true" + ) + # Convert the attribute to a dictionary before assigning it + # https://github.com/python/cpython/blob/28fb13cb33d569720938258db68956b5f9c9eb40/Objects/funcobject.c#L574-L594 + items = annotations.items + ann = ConstDictVariable( + dict(zip(items[::2], items[1::2], strict=True)), + mutation_type=ValueMutationNew(), + ) + fn.annotations = ann + self.push(fn) + + def UNPACK_SEQUENCE(self, inst: Instruction) -> None: + seq = self.pop() + val = unpack_iterable(self, seq) + if len(val) < inst.argval: + raise_value_error( + self, + f"not enough values to unpack (expected {inst.argval}, got {len(val)})", + ) + if len(val) > inst.argval: + raise_value_error( + self, + f"too many values to unpack (expected {inst.argval})", + ) + for i in reversed(val): + self.push(i) + + def UNPACK_EX(self, inst: Instruction) -> None: + if not (0 <= inst.argval <= 0xFFFF): + raise AssertionError("expected 0 <= inst.argval <= 0xFFFF to be true") + prefix = inst.argval & 0xFF # low byte + suffix = inst.argval >> 8 # high byte + seq = self.pop() + if iterator := generic_getiter(self, seq): # type: ignore[bad-argument-type] + vals = unpack_iterable(self, iterator) + if len(vals) < prefix + suffix: + raise_value_error( + self, + f"not enough values to unpack (expected at least {prefix + suffix}, got {len(vals)})", + ) + vals_prefix = vals[:prefix] + vals_list = vals[prefix : len(vals) - suffix] + vals_suffix = vals[len(vals) - suffix :] + for item in reversed(vals_suffix): + self.push(item) + self.push(ListVariable(vals_list, mutation_type=ValueMutationNew())) + for item in reversed(vals_prefix): + self.push(item) + else: + unimplemented( + gb_type="Failed to unpack object for UNPACK_EX", + context=str(seq), + explanation=f"{seq} cannot be unpacked into a list for the UNPACK_EX bytecode.", + hints=[*graph_break_hints.USER_ERROR], + ) + + @break_graph_if_unsupported( + push=False, msg_prefix="Encountered intentional debugging graph break" + ) + def graph_break_on_leaf_function(self, inst: Instruction) -> None: + if self.has_no_inlined_calls: + unimplemented( + gb_type="Forced graph break on leaf function", + context="", + explanation="Forced graph break on non-inlining function for " + "nested graph break testing purposes", + hints=[ + "Set torch._dynamo.config.debug_force_graph_break_on_leaf_return = False", + ], + ) + + def NOP(self, inst: Instruction) -> None: + # Dynamo-specific testing behavior + if inst.argval == "GRAPH_BREAK_IF_LEAF": + self.graph_break_on_leaf_function(inst) + + def POP_TOP(self, inst: Instruction) -> None: + self.pop() + + def ROT_TWO(self, inst: Instruction) -> None: + a = self.pop() + b = self.pop() + self.push(a) + self.push(b) + + def ROT_THREE(self, inst: Instruction) -> None: + a = self.pop() + b = self.pop() + c = self.pop() + self.push(a) + self.push(c) + self.push(b) + + def ROT_FOUR(self, inst: Instruction) -> None: + a = self.pop() + b = self.pop() + c = self.pop() + d = self.pop() + self.push(a) + self.push(d) + self.push(c) + self.push(b) + + def DUP_TOP(self, inst: Instruction) -> None: + a = self.pop() + self.push(a) + self.push(a) + + def DUP_TOP_TWO(self, inst: Instruction) -> None: + a = self.pop() + b = self.pop() + self.push(b) + self.push(a) + self.push(b) + self.push(a) + + def _convert_value(self, value: VariableTracker, flag: int) -> VariableTracker: + if flag == 1: + return VariableTracker.build(self, str).call_function(self, [value], {}) # type: ignore[arg-type] + elif flag == 2: + return VariableTracker.build(self, repr).call_function(self, [value], {}) # type: ignore[arg-type] + elif flag == 3: + return VariableTracker.build(self, ascii).call_function(self, [value], {}) # type: ignore[arg-type] + return value + + def _format_value(self, fmt_spec: VariableTracker, flags: int) -> None: + value = self.pop() + if isinstance(value, SymNodeVariable): + from torch._dynamo.variables.lazy import ( + LazySymNodeFormatString, + LazyVariableTracker, + ) + + value = LazyVariableTracker.create( + LazySymNodeFormatString(value, fmt_spec), source=None + ) + self.push(value) + return + + value = self._convert_value(value, flags & 0x03) + + # For plain f"{obj}" (no conversion, empty format spec, default + # __format__), eagerly evaluate str() via generic_str to capture + # the current symbolic state. This avoids deferring to + # StringFormatVariable whose reconstruct runs before mutations + # are replayed in the epilogue. + # Skip when __format__ is overridden since format(obj, "") may + # differ from str(obj) in that case. + if ( + (flags & 0x03) == 0 + and fmt_spec.is_python_constant() + and fmt_spec.as_python_constant() == "" + ): + realized = value.realize() + try: + py_type = realized.python_type() + except NotImplementedError: + py_type = None + if py_type is not None and py_type.__format__ is object.__format__: + try: + from .variables.object_protocol import generic_str + + str_result = generic_str(self, realized) + self.push(str_result) + return + except Unsupported: + if self.output.should_exit: + raise + + fmt_var = VariableTracker.build( + self, "{:" + fmt_spec.as_python_constant() + "}" + ) + + self.call_function(BuiltinVariable(str.format), [fmt_var, value], {}) + + def FORMAT_VALUE(self, inst: Instruction) -> None: + flags = inst.arg + if flags is None: + raise AssertionError("expected flags is not None to be true") + if (flags & 0x04) == 0x04: + fmt_spec = self.pop() + else: + fmt_spec = VariableTracker.build(self, "") + return self._format_value(fmt_spec, flags) + + def BUILD_STRING(self, inst: Instruction) -> None: + format_string_parts: list[str] = [] + args: list[VariableTracker] = [] + kwargs: dict[str, VariableTracker] = {} + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + for part in self.popn(inst.arg): + if part.is_python_constant(): + format_string_parts.append("{}") + args.append(part) + elif isinstance(part, variables.StringFormatVariable): + format_string_parts.append(part.format_string) + args.extend(part.sym_args) + if set(kwargs.keys()) & set(part.sym_kwargs.keys()): + unimplemented( + gb_type="BUILD_STRING key conflict", + context=f"format_string_parts: {format_string_parts}, kwargs: {kwargs}, part.sym_kwargs: {part.sym_kwargs}", + explanation="Failed to build format string due to key conflict", + hints=[*graph_break_hints.USER_ERROR], + ) + kwargs.update(part.sym_kwargs) + else: + unimplemented( + gb_type="BUILD_STRING type error", + context=str(part), + explanation="Format string part type is not correct - expected constant or format string.", + hints=[*graph_break_hints.USER_ERROR], + ) + self.push( + variables.StringFormatVariable.create( + "".join(format_string_parts), args, kwargs + ) + ) + + def IS_OP(self, inst: Instruction) -> None: + if not (inst.argval == 0 or inst.argval == 1): + raise AssertionError( + "expected inst.argval == 0 or inst.argval == 1 to be true" + ) + argval = "is" if inst.argval == 0 else "is not" + self.push(compare_op_handlers[argval](self, self.popn(2), {})) + + def CONTAINS_OP(self, inst: Instruction) -> None: + if not (inst.argval == 0 or inst.argval == 1): + raise AssertionError( + "expected inst.argval == 0 or inst.argval == 1 to be true" + ) + left, right = self.popn(2) + op = inst.argval + self.push(pysequence_contains(self, right, left)) # type: ignore[bad-argument-type] + if op == 1: + self.UNARY_NOT(inst) + + def LIST_EXTEND(self, inst: Instruction) -> None: + v = self.pop() + if not (inst.argval > 0): + raise AssertionError("expected inst.argval > 0 to be true") + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + obj = self.stack[-inst.arg] + if not isinstance(obj, ListVariable): + raise AssertionError("expected isinstance(obj, ListVariable) to be true") + if not obj.is_mutable(): + raise AssertionError("expected obj.is_mutable() to be true") + obj.call_method(self, "extend", [v], {}) # type: ignore[arg-type] + + def LIST_TO_TUPLE(self, inst: Instruction) -> None: + self.push( + VariableTracker.build(self, tuple).call_function(self, [self.pop()], {}) + ) # type: ignore[arg-type] + + def STOPITERATION_ERROR(self, inst: Instruction) -> None: + # wrap the generator body in a try: ... except StopIteration: ... which + # converts the StopIteration into a RuntimeError + # https://peps.python.org/pep-0479/ + # https://github.com/python/cpython/pull/99006 + # https://github.com/python/cpython/commit/28187141cc34063ef857976ddbca87ba09a882c2 + val = self.stack[-1] + if not pyexception_instance_check(val): + raise AssertionError( + f"expected _exception_instance_check(val) to be true, got {val}" + ) + if val.exc_type is StopIteration: # type: ignore[union-attr] + new_val = VariableTracker.build(self, RuntimeError).call_function( + self, # type: ignore[arg-type] + [VariableTracker.build(self, "generator raised StopIteration")], + {}, + ) + new_val.call_method( + self, + "__setattr__", + [VariableTracker.build(self, "__context__"), val], + {}, + ) + new_val.call_method( + self, "__setattr__", [VariableTracker.build(self, "__cause__"), val], {} + ) + self.stack[-1] = new_val + + def DICT_MERGE(self, inst: Instruction) -> None: + v = self.pop() + if not (inst.argval > 0): + raise AssertionError("expected inst.argval > 0 to be true") + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + obj = self.stack[-inst.arg].realize() + if not isinstance(obj, ConstDictVariable): + raise AssertionError( + "expected isinstance(obj, ConstDictVariable) to be true" + ) + if not obj.is_mutable(): + raise AssertionError("expected obj.is_mutable() to be true") + obj.call_method(self, "update", [v], {}) # type: ignore[arg-type] + + DICT_UPDATE = DICT_MERGE + + def GEN_START(self, inst: Instruction) -> None: + self.pop() + + def GET_LEN(self, inst: Instruction) -> None: + tos = self.stack[-1] + if tos.is_python_constant(): + self.push(VariableTracker.build(self, len(tos.as_python_constant()))) + else: + self.push(tos.call_method(self, "__len__", [], {})) + + def MATCH_MAPPING(self, inst: Instruction) -> None: + """ + If STACK[-1] is an instance of collections.abc.Mapping, push True. + Otherwise, push False + """ + tos = self.stack[-1] + self.push( + self.inline_user_function_return( + VariableTracker.build(self, impl_IS_MAPPING), + [tos], + {}, + ) + ) + + def MATCH_SEQUENCE(self, inst: Instruction) -> None: + tos = self.stack[-1] + self.push( + self.inline_user_function_return( + VariableTracker.build(self, impl_MATCH_SEQUENCE), + [tos], + {}, + ) + ) + + def MATCH_CLASS(self, inst: Instruction) -> None: + subject, cls, names = self.popn(3) + arg = VariableTracker.build(self, inst.arg) + self.push( + self.inline_user_function_return( + VariableTracker.build(self, impl_MATCH_CLASS), + [subject, cls, arg, names], + {}, + ) + ) + + if sys.version_info < (3, 11): + # for versions < 3.11, also push the boolean result + tos = self.stack[-1] + self.push(VariableTracker.build(self, not istype(tos, ConstantVariable))) + + def MATCH_KEYS(self, inst: Instruction) -> None: + keys = self.stack[-1] + obj = self.stack[-2] + + if not isinstance(keys, TupleVariable): + raise AssertionError("expected isinstance(keys, TupleVariable) to be true") + + self.push( + self.inline_user_function_return( + VariableTracker.build(self, impl_MATCH_KEYS), [obj, keys], {} + ) + ) + + if sys.version_info < (3, 11): + # for versions < 3.11, also push the boolean result + tos = self.stack[-1] + self.push(VariableTracker.build(self, not istype(tos, ConstantVariable))) + + def LOAD_ASSERTION_ERROR(self, inst: Instruction) -> None: + self.push(self.load_builtin_from_argval("AssertionError")) + + def LOAD_BUILD_CLASS(self, inst: Instruction) -> None: + self.push(self.load_builtin_from_argval("__build_class__")) + + UNARY_POSITIVE = stack_op(operator.pos) + UNARY_NEGATIVE = stack_op(operator.neg) + UNARY_NOT = stack_op(operator.not_) + UNARY_INVERT = stack_op(operator.invert) + + BINARY_POWER = stack_op(operator.pow) + BINARY_MULTIPLY = stack_op(operator.mul) + BINARY_MATRIX_MULTIPLY = stack_op(operator.matmul) + BINARY_FLOOR_DIVIDE = stack_op(operator.floordiv) + BINARY_TRUE_DIVIDE = stack_op(operator.truediv) + BINARY_MODULO = stack_op(operator.mod) + BINARY_REMAINDER = stack_op(operator.mod) + BINARY_ADD = stack_op(operator.add) + BINARY_SUBTRACT = stack_op(operator.sub) + + BINARY_SUBSCR = break_graph_if_unsupported( + push=True, + msg_prefix="Encountered graph break when attempting to trace BINARY_SUBSCR: a binary subscript, e.g. x[attr]", + )(stack_op(operator.getitem)) + BINARY_LSHIFT = stack_op(operator.lshift) + BINARY_RSHIFT = stack_op(operator.rshift) + BINARY_AND = stack_op(operator.and_) + BINARY_OR = stack_op(operator.or_) + BINARY_XOR = stack_op(operator.xor) + + INPLACE_POWER = stack_op(operator.ipow) + INPLACE_MULTIPLY = stack_op(operator.imul) + INPLACE_MATRIX_MULTIPLY = stack_op(operator.imatmul) + INPLACE_FLOOR_DIVIDE = stack_op(operator.ifloordiv) + INPLACE_TRUE_DIVIDE = stack_op(operator.itruediv) + INPLACE_MODULO = stack_op(operator.imod) + INPLACE_REMAINDER = stack_op(operator.imod) + INPLACE_ADD = stack_op(operator.iadd) + INPLACE_SUBTRACT = stack_op(operator.isub) + INPLACE_LSHIFT = stack_op(operator.ilshift) + INPLACE_RSHIFT = stack_op(operator.irshift) + INPLACE_AND = stack_op(operator.iand) + INPLACE_XOR = stack_op(operator.ixor) + INPLACE_OR = stack_op(operator.ior) + + # 3.11 opcodes + def RESUME(self, inst: Instruction) -> None: + if inst.arg == 0: + self.append_prefix_inst(inst) + self.accept_prefix_inst = False + elif sys.version_info >= (3, 15) and inst.arg == 4: + # https://github.com/python/cpython/blob/f31a89bb901067dd105b00cfa90523cf7ffdbbdd/Include/internal/pycore_opcode_utils.h#L90 + self.append_prefix_inst(inst) + else: + if self.accept_prefix_inst: + raise AssertionError("expected not self.accept_prefix_inst to be true") + + if sys.version_info >= (3, 11): + + def BINARY_OP(self, inst: Instruction) -> None: + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + return _binary_op_lookup[inst.arg](self, inst) + + def PRECALL(self, inst: Instruction) -> None: + pass + + def KW_NAMES(self, inst: Instruction) -> None: + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + kw_names = self.code_options["co_consts"][inst.arg] + if not isinstance(kw_names, tuple): + raise AssertionError("expected isinstance(kw_names, tuple) to be true") + for name in kw_names: + if not isinstance(name, str): + raise AssertionError("expected isinstance(name, str) to be true") + if self.kw_names is not None: + raise AssertionError("expected self.kw_names is None to be true") + self.kw_names = ConstantVariable.create(value=kw_names) # type: ignore[assignment] + + def PUSH_NULL(self, inst: Instruction) -> None: + self.push(NullVariable()) + + def _call(self, inst: Instruction, call_kw: bool = False) -> None: + # see https://docs.python.org/3.11/library/dis.html#opcode-CALL + # for convention + if call_kw: + # TOS is kw_names for CALL_KW instruction + if not (sys.version_info >= (3, 13)): + raise AssertionError("expected sys.version_info >= (3, 13) to be true") + kw_names = self.pop() + if not isinstance(kw_names, TupleVariable): + raise AssertionError( + "expected isinstance(kw_names, TupleVariable) to be true" + ) + if not kw_names.is_python_constant(): + raise AssertionError( + "expected kw_names.is_python_constant() to be true" + ) + kw_names = kw_names.as_python_constant() + else: + kw_names = self.kw_names.value if self.kw_names else () + + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + contents = self.popn(inst.arg + 2) + if sys.version_info >= (3, 13): + # NULL and callable swapped + fn = contents[0] + args = [] if isinstance(contents[1], NullVariable) else [contents[1]] + else: + if isinstance(contents[0], NullVariable): + fn = contents[1] + # pyrefly: ignore [implicit-any] + args = [] + else: + fn = contents[0] + args = [contents[1]] + + if kw_names: + args = args + contents[2 : -len(kw_names)] + + kwargs_list = contents[-len(kw_names) :] + + kwargs = dict(zip(kw_names, kwargs_list)) + + if len(kwargs) != len(kw_names): + raise AssertionError("expected len(kwargs) == len(kw_names) to be true") + else: + args = args + contents[2:] + # pyrefly: ignore [implicit-any] + kwargs = {} + + try: + # if call_function fails, need to set kw_names to None, otherwise + # a subsequent call may have self.kw_names set to an old value + self.call_function(fn, args, kwargs) + finally: + self.kw_names = None + + @break_graph_if_unsupported( + push=True, + msg_prefix="Encountered graph break when attempting to trace CALL: a function call, e.g. f(x, y)", + ) + def CALL(self, inst: Instruction) -> None: + self._call(inst) + + def COPY(self, inst: Instruction) -> None: + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + self.push(self.stack[-inst.arg]) + + def SWAP(self, inst: Instruction) -> None: + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + self.stack[-1], self.stack[-inst.arg] = self.stack[-inst.arg], self.stack[-1] + + JUMP_BACKWARD = jump + JUMP_BACKWARD_NO_INTERRUPT = jump + + POP_JUMP_FORWARD_IF_TRUE = generic_jump(operator.truth, False) + POP_JUMP_BACKWARD_IF_TRUE = generic_jump(operator.truth, False) + POP_JUMP_FORWARD_IF_FALSE = generic_jump(operator.not_, False) + POP_JUMP_BACKWARD_IF_FALSE = generic_jump(operator.not_, False) + + def CACHE(self, inst: Instruction) -> None: + pass + + def BEFORE_WITH(self, inst: Instruction) -> None: + self.setup_or_before_with(inst) + + def enter_ctx( + self, + ctx: ContextWrappingVariable | GenericContextWrappingVariable, + inst: Instruction, + ) -> VariableTracker: + if ( + isinstance(ctx, GenericContextWrappingVariable) + and not ctx.supports_graph_breaks() + ): + self.active_generic_context_managers.append(ctx) + + if sys.version_info >= (3, 11): + # See update_block_stack/create_resume for block stack details. + # Only push a block if the current instruction's block is a + # with block that is not nested in a try block - that is, the current + # instruction's block target is the same as the top block's target. + if inst.exn_tab_entry and ( + not self.block_stack + or inst.exn_tab_entry.target is not self.block_stack[-1].target + ): + target = None + else: + if self.next_instruction.exn_tab_entry is None: + raise AssertionError( + "expected self.next_instruction.exn_tab_entry is not None to be true" + ) + target = self.next_instruction.exn_tab_entry.target + else: + target = inst.target + + if target: + if isinstance(self, InstructionTranslator) or config.nested_graph_breaks: + self.block_stack.append( + BlockStackEntry(inst, target, len(self.stack), ctx) + ) + else: + self.block_stack.append(BlockStackEntry(inst, target, len(self.stack))) + + return ctx.enter(self) # type: ignore[arg-type] + + @staticmethod + def unsupported_ctx_graph_break(ctx: VariableTracker) -> NoReturn: + unimplemented( + gb_type="Unsupported context manager", + context=f"Attempted SETUP_WITH/BEFORE_WITH/LOAD_SPECIAL on {ctx}", + explanation=f"Dynamo does not know how to enter a `{ctx.python_type_name()}` context manager.", + hints=[ + "Avoid using the unsupported context manager.", + "If the context manager seems like it should be supported (e.g. torch.set_grad_enabled), then " + "it may be the case that it was created outside the compiled region, which Dynamo does not support. " + "Supported context managers can cross graph break boundaries only if they are local non-closure " + "variables, or are intermediate values.", + "File an issue to PyTorch. Simple context managers can potentially be supported, " + "but note that context managers can't be supported in general", + ], + ) + + def setup_or_before_with(self, inst: Instruction) -> None: + ctx = self.pop() + if not isinstance( + ctx, (ContextWrappingVariable, GenericContextWrappingVariable) + ): + self.unsupported_ctx_graph_break(ctx) + + # Need this redundant check for mypy + if not isinstance( + ctx, (ContextWrappingVariable, GenericContextWrappingVariable) + ): + raise AssertionError( + "expected isinstance( ctx, (ContextWrappingVariable, GenericContextWrappingVariable) ) to be true" + ) + + self.push(WithExitFunctionVariable(ctx, inst.target)) + self.push(self.enter_ctx(ctx, inst)) + + def append_prefix_inst(self, inst: Instruction) -> None: + if not self.accept_prefix_inst: + raise AssertionError("expected self.accept_prefix_inst to be true") + self.prefix_insts.append(inst) + + def MAKE_CELL(self, inst: Instruction) -> None: + if sys.version_info >= (3, 12) and not self.accept_prefix_inst: + # In 3.12+, MAKE_CELL is no longer necessarily a prefix instruction. + # It can be generated by inlined comprehensions. + # A mid-function MAKE_CELL replaces the slot's contents with a + # fresh cell (the frame-entry cell was saved on the stack by a + # preceding LOAD_FAST_AND_CLEAR and is restored by the + # comprehension epilogue). Only the slot is updated: the + # symbolic_cellvars registry keeps the frame-entry cell, and + # `_cellvar` prefers the slot while it holds a cell. + if inst.argval in self.f_code.co_freevars: + # The name refers to three localsplus slots at once (fast + # local + comprehension cell + free var, e.g. `nonlocal i` + # with `[lambda: i for i in ...]`). Dynamo tracks locals by + # name and cannot model two same-named cells; tracing on + # would silently target the wrong cell. + unimplemented( + gb_type="MAKE_CELL on a free variable name", + context=f"MAKE_CELL {inst.argval}", + explanation="An inlined comprehension creates a cell whose name " + f"`{inst.argval}` is also a free variable of the enclosing function.", + hints=[*graph_break_hints.DIFFICULT], + ) + if not isinstance(self.symbolic_locals[inst.argval], NullVariable): + raise AssertionError( + "expected isinstance(self.symbolic_locals[inst.argval], NullVariable) to be true" + ) + self.symbolic_locals[inst.argval] = ( + self.output.side_effects.track_cell_new() + ) + else: + self.append_prefix_inst(inst) + + def COPY_FREE_VARS(self, inst: Instruction) -> None: + self.append_prefix_inst(inst) + + def RETURN_GENERATOR(self, inst: Instruction) -> None: + self.append_prefix_inst(inst) + + # 3.12 opcodes + # BINARY/STORE_SLICE opcodes are broken down into + # BUILD_SLICE 2 and BINARY/STORE_SUBSCR + + def END_FOR(self, inst: Instruction) -> None: + if sys.version_info >= (3, 13): + self.pop() + else: + self.popn(2) + + # Decrement comprehension depth if exiting a comprehension layer + if sys.version_info >= (3, 12): + current_ip = self.indexof[inst] + if current_ip in self._comprehension_end_for_ips: + self._comprehension_end_for_ips.discard(current_ip) + self._comprehension_depth -= 1 + + def LOAD_FAST_CHECK(self, inst: Instruction) -> None: + if istype(self.symbolic_locals.get(inst.argval, None), NullVariable): + unimplemented( + gb_type="LOAD_FAST_CHECK on uninitialized variable", + context=inst.argval, + explanation=f"Attempted to load uninitialized local variable {inst.argval}", + hints=[*graph_break_hints.USER_ERROR], + ) + self.LOAD_FAST(inst) + + def LOAD_FAST_AND_CLEAR(self, inst: Instruction) -> None: + if inst.argval not in self.symbolic_locals: + self.push(NullVariable()) + else: + self.LOAD_FAST(inst) + self.symbolic_locals[inst.argval] = NullVariable() + + def LOAD_SUPER_ATTR(self, inst: Instruction) -> None: + self.CALL_FUNCTION(dataclasses.replace(inst, argval=2)) + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + if inst.arg & 1: + self.LOAD_METHOD(inst) + else: + self._load_attr(inst.argval) + + def CALL_INTRINSIC_1(self, inst: Instruction) -> None: + if inst.argval == 3: + # INTRINSIC_STOPITERATION_ERROR + self.STOPITERATION_ERROR(inst) + elif inst.argval == 5: + # INTRINSIC_UNARY_POSITIVE + self.UNARY_POSITIVE(inst) + elif inst.argval == 6: + # INTRINSIC_LIST_TO_TUPLE + items = unpack_iterable(self, self.pop()) + self.push(TupleVariable(items)) + elif inst.argval == 7: + # INTRINSIC_TYPEVAR + v = self.pop().as_python_constant() + tv = variables.TypingVariable(TypeVar(v)) + self.push(tv) + else: + unimplemented( + gb_type="Missing CALL_INTRINSIC_1 handler", + context=f"CALL_INTRINSIC_1 operand: {inst.argval}", + explanation=f"No handler implemented for CALL_INTRINSIC_1 {inst.argval} instruction.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def CALL_INTRINSIC_2(self, inst: Instruction) -> None: + arg2 = self.pop() + arg1 = self.pop() + if inst.argval == 4: + # INTRINSIC_SET_FUNCTION_TYPE_PARAMS + # same as => arg1.__type_params__ = arg2 + if not isinstance(arg1, BaseUserFunctionVariable): + raise AssertionError( + "expected isinstance(arg1, BaseUserFunctionVariable) to be true" + ) + arg1.call_method( + self, # pyrefly: ignore[bad-argument-type] + "__setattr__", + [ConstantVariable.create("__type_params__"), arg2], + {}, + ) + self.push(arg1) + else: + unimplemented( + gb_type="Missing CALL_INTRINSIC_2 handler", + context=f"CALL_INTRINSIC_2 operand: {inst.argval}", + explanation=f"No handler implemented for CALL_INTRINSIC_2 {inst.argval} instruction.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def END_SEND(self, inst: Instruction) -> None: + tos = self.pop() + self.pop() + if sys.version_info >= (3, 15): + self.pop() + self.push(tos) + + # 3.13 opcodes + # fused instructions LOAD_FAST_LOAD_FAST, STORE_FAST_STORE_FAST, STORE_FAST_LOAD_FAST + # are broken down. + @break_graph_if_unsupported( + push=True, + msg_prefix="Encountered graph break when attempting to trace CALL_KW: " + "a function call with keyword arguments, e.g. f(x=True)", + ) + def CALL_KW(self, inst: Instruction) -> None: + self._call(inst, call_kw=True) + + def TO_BOOL(self, inst: Instruction) -> None: + # TO_BOOL only precedes a conditional jump or UNARY_NOT (see compile.c in CPython) + # So we can skip this instruction as long as we remember to codegen a TO_BOOL + # before conditional jumps/UNARY_NOT. + if self.next_instruction.opname not in ( + "POP_JUMP_IF_TRUE", + "POP_JUMP_IF_FALSE", + "UNARY_NOT", + ): + raise AssertionError( + 'expected self.next_instruction.opname in ( "POP_JUMP_IF_TRUE", "POP_JUMP_IF_FALSE", "UNARY_NOT", ) to be true' + ) + + def SET_FUNCTION_ATTRIBUTE(self, inst: Instruction) -> None: + flags = inst.arg + if flags is None: + raise AssertionError("expected flags is not None to be true") + fn = self.pop() + if not isinstance(fn, NestedUserFunctionVariable): + raise AssertionError( + "expected isinstance(fn, NestedUserFunctionVariable) to be true" + ) + attr = self.pop() + + if flags & 0x10: + if not (sys.version_info >= (3, 14)): + raise AssertionError("expected sys.version_info >= (3, 14) to be true") + + # maybe use Format.VALUE_WITH_FAKE_GLOBALS instead? + # https://docs.python.org/3/library/annotationlib.html#annotationlib.Format.VALUE_WITH_FAKE_GLOBALS + attr = attr.call_function(self, [VariableTracker.build(self, 1)], {}) + fn.annotations = attr + elif flags & 0x08: + fn.closure = attr + elif flags & 0x04: + if not isinstance(attr, TupleVariable): + raise AssertionError( + "expected isinstance(attr, TupleVariable) to be true" + ) + # Convert the attribute to a dictionary before assigning it + # https://github.com/python/cpython/blob/28fb13cb33d569720938258db68956b5f9c9eb40/Objects/funcobject.c#L574-L594 + items = attr.items + ann = ConstDictVariable( + dict(zip(items[::2], items[1::2], strict=True)), + mutation_type=ValueMutationNew(), + ) + fn.annotations = ann + elif flags & 0x02: + fn.kwdefaults = attr + elif flags & 0x01: + fn.defaults = attr + + self.push(fn) + + def CONVERT_VALUE(self, inst: Instruction) -> None: + if inst.arg is None: + raise AssertionError("expected inst.arg is not None to be true") + self.push(self._convert_value(self.pop(), inst.arg)) + + def FORMAT_SIMPLE(self, inst: Instruction) -> None: + self._format_value(VariableTracker.build(self, ""), 0) + + def FORMAT_WITH_SPEC(self, inst: Instruction) -> None: + self._format_value(self.pop(), 0) + + # 3.14 opcodes + LOAD_FAST_BORROW = LOAD_FAST + NOT_TAKEN = NOP + + def POP_ITER(self, inst: Instruction) -> None: + self.pop() + if sys.version_info >= (3, 15): + self.pop() + + # See + # https://github.com/python/cpython/blob/805e3368d6d07e58430654d1365283924fdf4143/Python/ceval.c#L559 + # for the LOAD_SPECIAL table - make sure it matches for Python 3.14+ + _load_special_names = ( + "__enter__", + "__exit__", + "__aenter__", + "__aexit__", + ) + + def LOAD_SPECIAL(self, inst: Instruction) -> None: + if not isinstance(inst.arg, int): + raise AssertionError("expected LOAD_SPECIAL arg to be set to int") + attr = self._load_special_names[inst.arg] + if attr in ("__enter__", "__exit__"): + ctx = self.pop() + if not isinstance( + ctx, (ContextWrappingVariable, GenericContextWrappingVariable) + ): + self.unsupported_ctx_graph_break(ctx) + + # Need this redundant check for mypy + if not isinstance( + ctx, (ContextWrappingVariable, GenericContextWrappingVariable) + ): + raise AssertionError( + "expected isinstance( ctx, (ContextWrappingVariable, GenericContextWrappingVariable) ) to be true" + ) + if attr == "__enter__": + self.push(WithEnterFunctionVariable(ctx)) + self.PUSH_NULL(inst) + else: + # WithExitFunctionVariable doesn't really do anything with target for 3.11+ + self.push(WithExitFunctionVariable(ctx, None)) + self.PUSH_NULL(inst) + else: + # Implementation is similar to LOAD_METHOD for 3.13+ + self._load_attr(attr) + obj = self.pop() + self.push(obj) + self.PUSH_NULL(inst) + + def LOAD_SMALL_INT(self, inst: Instruction) -> None: + self.push(VariableTracker.build(self, inst.argval)) + + # See + # https://github.com/python/cpython/blob/f31a89bb901067dd105b00cfa90523cf7ffdbbdd/Python/pylifecycle.c#L881 + # for the common constants - make sure it matches for Python 3.14+. + _common_constants = ( + AssertionError, + NotImplementedError, + tuple, + all, + any, + list, + set, + None, + "", + True, + False, + -1, + ) + + def LOAD_COMMON_CONSTANT(self, inst: Instruction) -> None: + if not isinstance(inst.arg, int): + raise AssertionError("expected LOAD_COMMON_CONSTANT arg to be set to int") + self.push(VariableTracker.build(self, self._common_constants[inst.arg])) + + def is_non_empty_graph(self) -> bool: + if self.output.count_calls() > 1: + # perf optimization only + self.is_non_empty_graph = lambda: True # type: ignore[method-assign] + return True + return False + + def format_frame_summary( + self, additional_stack_frames: list[Any] | None = None + ) -> str: + if additional_stack_frames is None: + additional_stack_frames = [] + return "".join( + traceback.format_list( + [self.frame_summary()] + list(reversed(additional_stack_frames)) + ) + ) + + def frame_summary(self) -> traceback.FrameSummary: + positions = self.current_instruction.positions + # colno/end_colno kwargs were added to FrameSummary in 3.11 + kwargs: dict[str, Any] = {} + if sys.version_info >= (3, 11) and positions is not None: + kwargs["colno"] = positions.col_offset + kwargs["end_colno"] = positions.end_col_offset + return traceback.FrameSummary( + getattr(self.f_code, "co_filename", ""), + self.lineno, + getattr(self.f_code, "co_name", ""), + lookup_line=False, + **kwargs, + ) + + def is_co_filename_from_nn_modules(self) -> bool: + filename = getattr(self.f_code, "co_filename", "") + nn_modules_pattern = re.compile(r".*torch/nn/modules.*") + return nn_modules_pattern.match(filename) is not None + + def store_global_weakref_by_id(self, prefix: str, value: Any) -> str: + global_name = self.output.install_global_by_id(prefix, weakref.ref(value)) + install_guard( + GlobalWeakRefSource(global_name).make_guard(GuardBuilder.WEAKREF_ALIVE) + ) + return global_name + + @property + def fake_mode(self) -> FakeTensorMode | None: + return self.output.tracing_context.fake_mode + + @contextlib.contextmanager + def strict_translation_mode( + self, check_fn: Callable[[VariableTracker], bool] + ) -> Any: + """ + Strict mode is enabled on a per-VariableTracker level depending on the return value of check_fn(node). + """ + prior = self.strict_checks_fn + self.strict_checks_fn = check_fn + try: + yield + finally: + self.strict_checks_fn = prior + + def speculate(self) -> SpeculationEntry: + if self.instruction_pointer is None: + raise AssertionError( + "expected self.instruction_pointer is not None to be true" + ) + if not (self.instruction_pointer > 0): + raise AssertionError("expected self.instruction_pointer > 0 to be true") + return self.speculation_log.next( + self.f_code.co_filename, + self.lineno, + self.instruction_pointer - 1, + self.instructions[self.instruction_pointer - 1], + ) + + def _make_frame_loc( + self, filename: str, lineno: int | None, fallback_lineno: int + ) -> tuple[str, int]: + if lineno is None or lineno < 0: + return (filename, fallback_lineno) + return (filename, lineno) + + def _get_frame_loc_chain( + self, frame_loc: tuple[str, int] + ) -> tuple[tuple[str, int], ...]: + frame_loc_chain_list: list[tuple[str, int]] = [] + + if config.nested_graph_breaks: + current_tx: InstructionTranslatorBase | None = self.parent + while current_tx is not None: + parent_frame_loc = self._make_frame_loc( + current_tx.f_code.co_filename, + current_tx.lineno, + current_tx.f_code.co_firstlineno, + ) + frame_loc_chain_list.append(parent_frame_loc) + current_tx = current_tx.parent + + frame_loc_chain_list.reverse() + frame_loc_chain_list.append(frame_loc) + return tuple(frame_loc_chain_list) + + def _format_stack_source_attribution(self) -> str: + """Format bytecode source locations for stack values involved in a graph break.""" + seen: set[SourceLocation] = set() + parts: list[str] = [] + for vt in self.stack: + source_location = vt.source_location + if source_location is None: + continue + if source_location in seen: + continue + seen.add(source_location) + parts.append( + f" {vt!r} originated from:\n{source_location.format().rstrip()}" + ) + + if not parts: + return "" + return "Stack variable source attribution:\n" + "\n".join(parts) + + def log_graph_break( + self, + code_options: CodeOptions, + reason: str, + exc: Unsupported | UserError | StepUnsupported, + ) -> None: + if exc.logged: + return + + user_stack = getattr(exc, "real_stack", None) + + if user_stack is None: + user_stack = torch._guards.TracingContext.extract_stack() + + try: + if config.nested_graph_breaks and self.parent is not None: + frame_loc = self._make_frame_loc( + self.f_code.co_filename, + self.lineno, + self.f_code.co_firstlineno, + ) + else: + frame_loc = self._make_frame_loc( + user_stack[-1].filename, + user_stack[-1].lineno, + 0, + ) + except IndexError: + # first instruction + frame_loc = ( + code_options["co_filename"], + code_options["co_firstlineno"], + ) + frame_loc_chain = self._get_frame_loc_chain(frame_loc) + stack_above_dynamo_formatted = "" + if config.verbose: + stack_above_dynamo = get_stack_above_dynamo() + stack_above_dynamo_formatted = "".join( + traceback.format_list(stack_above_dynamo) + ) + else: + user_stack = get_stack_above_dynamo() + user_stack # type: ignore[assignment] + user_stack = collapse_resume_frames(user_stack) + user_stack_formatted = "".join(traceback.format_list(user_stack)) + + # Add HOP context after the first line of reason if present + if exc is not None: + reason = augment_exc_message_with_hop_name(exc, reason) + + stack_source_attribution = self._format_stack_source_attribution() + user_stack_trace_parts = [ + f"Graph break in user code at {frame_loc[0]}:{frame_loc[1]}", + f"Graph Break Reason: {reason}", + ] + if stack_source_attribution: + user_stack_trace_parts.extend(["", stack_source_attribution]) + user_stack_trace_parts.extend(["", "User code traceback:"]) + user_stack_trace = "\n".join(user_stack_trace_parts) + "\n" + + if config.verbose: + user_stack_trace += ( + f"{stack_above_dynamo_formatted}\n" + "========== most recent `torch.compile` tracing attempt started here ==========\n\n" + f"{user_stack_formatted}\n" + "NOTE: the most recent `torch.compile` tracing attempt might not be where you applied `torch.compile`! " + "This is due to how graph breaks are implemented - the optimized code object returned by Dynamo will call another " + "Dynamo-generated resume function and tracing is re-enabled by calling the resume function as a normal Python " + "function, which Dynamo intercepts as a top-level frame.\n" + ) + else: + user_stack_trace += str(user_stack_formatted) + + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "dynamo_graph_break_reason", + "encoding": "string", + }, + payload_fn=lambda: f"{user_stack_trace}\n{traceback.format_exc()}", + ) + + # torch._dynamo.explain() formats this a little nicer, and presents a slightly + # more actionable user code pointer + gb_type = exc.gb_type if isinstance(exc, Unsupported) else type(exc) + if ( + graph_break_log.isEnabledFor(logging.DEBUG) + and not explain + and graph_break_dup_warning_checker.add((gb_type, frame_loc_chain)) # type: ignore[arg-type] + ): + # This log line MUST contain the string "Graph break in user code", + # This log line is exercised from + # python test/dynamo/test_exc.py -k test_graph_break_log + if config.verbose: + user_stack_trace += ( + "\nMost recent bytecode instructions traced (max 20):\n" + ) + user_stack_trace += "\n".join(self.latest_bytecode_queue) + "\n" + + graph_break_log.debug( + user_stack_trace, + ) + else: + # This log line MUST not contain the string "Graph break in user code", + # exercised by + # python test/dynamo/test_misc.py -k test_duplicate_graph_break_log + graph_break_log.debug( + "Graph break (user stack suppressed due to duplicate graph break) in user code at %s:%s\nGraph Break Reason: %s", + frame_loc[0], + frame_loc[1], + reason, + ) + + exc.logged = True + + @staticmethod + def raise_loop_graph_break( + code: types.CodeType, exc: Unsupported | UserError + ) -> NoReturn: + unimplemented( + gb_type="graph break in loop", + context=f"frame skipped: {format_frame_info(code)}", + explanation="torch.compile detected a graph break in a for/while loop. " + "Skipping the frame and falling back to eager, as graph breaks in loops are not supported.", + hints=[*graph_break_hints.CAUSED_BY_EARLIER_GRAPH_BREAK], + from_exc=exc, + skip_frame=True, + ) + + def __init__( + self, + output: OutputGraph, + instructions: list[Instruction], + f_locals: dict[str, Any], + f_globals: dict[str, Any], + f_builtins: dict[str, Any], + code_options: CodeOptions, + symbolic_locals: dict[str, VariableTracker], + symbolic_globals: dict[str, VariableTracker], + symbolic_torch_function_state: SymbolicTorchFunctionState, + symbolic_stream_state: SymbolicStreamState, + f_code: types.CodeType, + export: bool, + inline_depth: int, + speculation_log: SpeculationLog, + exn_vt_stack: ExceptionStack, + distributed_state: DistributedState | None, + # This determines whether to use the execution recorder. + closure: tuple[types.CellType] | None = None, + package: CompilePackage | None = None, + # Pre-computed indexof for cache reuse + indexof: dict[Instruction, int] | None = None, + ) -> None: + super().__init__() + self.speculation_log = speculation_log + self.distributed_state = distributed_state + + # Mutable state checkpointed by copy_graphstate() + self.output = output + self.symbolic_locals = symbolic_locals + self.symbolic_cellvars = {} + self.symbolic_globals = symbolic_globals + self.symbolic_torch_function_state = symbolic_torch_function_state + self.symbolic_stream_state = symbolic_stream_state + # used to keep cell/freevars alive after pruning symbolic_locals (prune_dead_locals) + # in order to generate any nested closures + self.post_prune_cell_and_freevars = None + self.stack: list[VariableTracker] = [] + self.instruction_pointer = 0 + self.start_point = None + self.current_instruction = create_instruction("NOP") + self.current_instruction_push = True + self.block_stack = [] + # states before SETUP_WITH for checkpointing and fallback + self.active_generic_context_managers: list[GenericContextWrappingVariable] = [] + self.skip_one_hop_torch_function_depth: int = 0 + self.lineno = -1 + self.kw_names = None + self.accept_prefix_inst = True + self.prefix_insts = [] + self.exn_vt_stack = exn_vt_stack + self.latest_bytecode_queue = deque(maxlen=20) + self._comprehension_depth = 0 + self._comprehension_end_for_ips: set[int] = set() + # Per-prefix counters for generating fresh pycode-local variable names. + self._pycode_varname_counter: defaultdict[str, itertools.count[int]] = ( + defaultdict(lambda: itertools.count(0)) + ) + # Per-prefix record of the most recently generated pycode varname. + self._pycode_last_varname: dict[str, str] = {} + + # Properties of the input/output code + self.instructions: list[Instruction] = instructions + self.indexof: dict[Instruction, int] = ( + indexof if indexof is not None else get_indexof(self.instructions) + ) + self.f_locals: dict[str, Any] = ( + f_locals # needed for recording accessed locals for replay + ) + self.f_globals: dict[str, Any] = f_globals + self.f_builtins: dict[str, Any] = f_builtins + self.code_options: CodeOptions = code_options + self.f_code: types.CodeType = f_code + self.closure = closure + # Inlined frames receive a fully-populated symbolic_locals (cells + # included); register their cells now. Root frames populate + # symbolic_locals after super().__init__ and register there. + self._register_cells() + + # Execution record for replaying errors + if closure is not None and config.replay_record_enabled: + self.exec_recorder = ExecutionRecorder( + code=f_code, + closure=closure, + code_options=code_options, + ) + else: + self.exec_recorder = None + # Stack of module being parsed, current nn.module is at the end of ordered dict. + # The first field of tuple is the fully qualified name of current module + # in original hierarchy. The second field is the type of current nn.module + self.nn_module_stack: dict[str, tuple[str, type[Any]]] = {} + self.num_calls: dict[str, int] = {} + # Flag to indicate whether tracing is used for export. + self.export = export + # NOTE: one_graph is used for export/fullgraph=True to always force errors on graph breaks. + # To toggle erroring/resuming on graph breaks during fullgraph=False compile, self.error_on_graph_break + # is used instead. Every step(), its value is updated to the global tls.error_on_graph_break. + # We mirror this value since cleanup may (correctly) inadvertently change tls.error_on_graph_break. + # This assumes that we cannot both trace a change to tls.error_on_graph_break and graph break on + # the same instruction. + self.one_graph = False + self.error_on_graph_break = False + # Also do not graph break when tracing resume function prologues + self.is_tracing_resume_prologue = False + + self.current_speculation = None + + self.strict_checks_fn = None + + self.has_no_inlined_calls = True + self.parent = None + self.is_child_tracer_active = False + self.debug_locals = [] + + self.package = package + + from .resume_execution import ( + CO_ASYNC_GENERATOR, + CO_COROUTINE, + CO_GENERATOR, + CO_ITERABLE_COROUTINE, + ) + + # This isn't really the right place to push None. But since we treat RETURN_GENERATOR as a no-op for + # non-generator frames, there needs to be something on the stack since the first instruction will be POP_TOP, + # which would error out with an empty stack + push_types = CO_COROUTINE | CO_ITERABLE_COROUTINE | CO_ASYNC_GENERATOR + if sys.version_info < (3, 11): + push_types |= CO_GENERATOR + if f_code.co_flags & (push_types): + self.push(BuiltinVariable(None)) + + self.inline_depth = inline_depth + self.inconsistent_side_effects = False + self._constants_cache: list[ConstantVariable | SliceVariable | None] = [ + None + ] * len(f_code.co_consts) + + self.is_trace_bytecode_log_enabled: bool | None = ( + trace_bytecode_log.isEnabledFor(logging.DEBUG) + ) + self.is_trace_source_log_enabled: bool | None = trace_source_log.isEnabledFor( + logging.DEBUG + ) + linecache.lazycache(f_code.co_filename, f_globals) + + +class InstructionTranslator(InstructionTranslatorBase): + @staticmethod + def current_tx() -> InstructionTranslator: + return tls.current_tx + + @contextlib.contextmanager + def set_current_tx(self) -> Any: + prior = getattr(tls, "current_tx", None) + tls.current_tx = self + try: + yield + finally: + if prior is not None: + tls.current_tx = prior + elif hasattr(tls, "current_tx"): + del tls.current_tx + + def __init__( + self, + instructions: list[Instruction], + f_code: types.CodeType, + f_locals: dict[str, Any], + f_globals: dict[str, Any], + f_builtins: dict[str, Any], + closure: tuple[Any, ...] | None, + torch_function_mode_stack: Any, + code_options: CodeOptions, + compiler_fn: Any, + one_graph: bool, + export: bool, + export_constraints: Any, + frame_state: Any, + speculation_log: SpeculationLog, + exn_vt_stack: ExceptionStack, + distributed_state: DistributedState | None, + package: CompilePackage | None, + ) -> None: + _step_logger()( + logging.INFO, + f"torchdynamo start tracing {f_code.co_name} {code_options['co_filename']}:{code_options['co_firstlineno']}", + ) + super().__init__( + output=OutputGraph( + code_options, + compiler_fn, + self, + export, + export_constraints, + frame_state, + local_scope=f_locals, + global_scope=f_globals, + f_code=f_code, + torch_function_mode_stack=torch_function_mode_stack, + one_graph=one_graph, + package=package, + ), + instructions=instructions, + f_locals=f_locals, + f_globals=f_globals, + f_builtins=f_builtins, + closure=closure, + code_options=code_options, + symbolic_locals={}, # set below + # A global var is inserted only after a STORE_GLOBAL happens to it + symbolic_globals={}, + symbolic_torch_function_state=None, # type: ignore[arg-type] # set below + symbolic_stream_state=None, # type: ignore[arg-type] # set below + f_code=f_code, + export=export, + inline_depth=0, + speculation_log=speculation_log, + exn_vt_stack=exn_vt_stack, + distributed_state=distributed_state, + package=package, + ) + + self._throw_if_in_functorch() + + # as soon as we create the tracing context we should keep it active, so any calls + # into dynamo apis can rely on finding it + with tracing(self.output.tracing_context), self.set_current_tx(): + self.one_graph: bool = one_graph + self.export = export + if self.export: + if not self.one_graph: + raise AssertionError( + "Export without one graph - something has gone wrong." + ) + + self.symbolic_locals = {} + # Populate `symbolic_locals` with non-cell variables. + cell_and_freevars: set[str] = set(self.cell_and_freevars()) + + # Identify the names of `*args` / `**kwargs` parameters (if any) + # via the function's `co_flags`. The varargs param (if present) + # comes immediately after `co_argcount + co_kwonlyargcount` + # entries in `co_varnames`; the varkw param comes right after. + varargs_name: str | None = None + varkw_name: str | None = None + _vararg_idx = f_code.co_argcount + f_code.co_kwonlyargcount + if f_code.co_flags & CO_VARARGS: + varargs_name = f_code.co_varnames[_vararg_idx] + _vararg_idx += 1 + if f_code.co_flags & CO_VARKEYWORDS: + varkw_name = f_code.co_varnames[_vararg_idx] + + # Skip inputs never read anywhere in the function: they cannot + # affect the graph or any resume suffix, so guards on them are + # wasteful. Export mode must keep all locals because realize_all() + # below needs them. locals()/vars() are handled in _call_frame_locals_snapshot + # which adds pruned entries back from tx.f_locals on demand. + if export: + function_live_names: set[str] | None = None + else: + function_live_names = livevars_analysis( + self.instructions, self.instructions[0] + ) + + dynamism = code_context.get_context(f_code).get("dynamism", None) + for name, value in f_locals.items(): + if name not in cell_and_freevars: + if ( + function_live_names is not None + and name not in function_live_names + and name != varargs_name + and name != varkw_name + ): + continue + local_dynamism = None + if dynamism: + local_dynamism = frozenset(dynamism.get(name, {}).items()) + var = LazyVariableTracker.create( + value, + LocalSource( + name, + is_input=True, + dynamism=local_dynamism, + is_varargs=(name == varargs_name), + is_varkw=(name == varkw_name), + ), + tx=self, + ) + self.symbolic_locals[name] = var + + # Populate `symbolic_locals` with cells created by this frame, + # effectively implementing the `MAKE_CELL` instructions. + side_effects = self.output.side_effects + for name in self.cellvars(): + if name in f_locals: + # This models cells that are also function inputs. + value = f_locals[name] + # NOTE: root frame inputs that are captured by a nested + # function become special cell objects -- they exist in + # `f_locals` as contents of the cells, rather than the cells + # objects themselves. + # + # In Dynamo, we choose to represent such input cell objects + # as newly created (rather than pre-existing) cell objects, + # because + # + # 1. The reason for representing a pre-existing cell object + # is to emit guard or codegen mutations. However, local + # cells should never be used for guards. Moreover, at this + # point these input cell objects should've never been + # accessed by anyone else, since Dynamo intercepts the frame + # right after its evaluation starts, i.e., right after these + # cell objects are created. So they should have no external + # reference, meaning no mutation needs to be propagated. + # + # 2. This conveniently allows codegen to prune away + # mutations to these cells, unless they escape the frame. + contents_source = LocalSource( + name, + is_input=True, + is_derefed_cell_contents=True, + ) + contents_var: VariableTracker = LazyVariableTracker.create( + value, contents_source, tx=self + ) + cell_var = side_effects.track_cell_new() + side_effects.store_cell(cell_var, contents_var) + else: + cell_var = side_effects.track_cell_new() + cell_var.local_name = name # type: ignore[attr-defined] + self.symbolic_locals[name] = cell_var + + # Populate `symbolic_locals` with cells captured by this frame, + # effectively implementing the `COPY_FREE_VARS` instruction. + if closure is None: + raise AssertionError("expected closure is not None to be true") + for name, cell in zip(self.freevars(), closure): + cell_source = LocalCellSource(name) + contents_source = LocalSource(name, is_derefed_cell_contents=True) + try: + contents_var = LazyVariableTracker.create( + cell.cell_contents, contents_source, tx=self + ) + except ValueError: + # Cell has not yet been assigned + contents_var = variables.DeletedVariable() + cell_var = side_effects.track_cell_existing( + cell_source, cell, contents_var + ) + cell_var.local_name = name # type: ignore[attr-defined] + self.symbolic_locals[name] = cell_var + + # symbolic_locals is now fully populated; register the frame's + # cells (base __init__ ran before this population). + self._register_cells() + + self.symbolic_torch_function_state = SymbolicTorchFunctionState( + torch_function_mode_stack, + skip_next=False, + ) + + self.symbolic_stream_state = SymbolicStreamState() + + if export: + # export gets confused if we never realize unused inputs + # in export mode just eagerly realize everything + self.symbolic_locals = variables.LazyVariableTracker.realize_all( + self.symbolic_locals + ) + self.symbolic_cellvars = variables.LazyVariableTracker.realize_all( + self.symbolic_cellvars + ) + + def _throw_if_in_functorch(self) -> None: + # Fallback to eager in case of a graph break inside vmap + eager = torch._dynamo.lookup_backend("eager") + compiler_fn = inspect.getattr_static( + self.output.compiler_fn, "compiler_fn", self.output.compiler_fn + ) + ci = torch._C._functorch.peek_interpreter_stack() + forbidden_keys = ( + torch._C._functorch.TransformType.Vmap, + torch._C._functorch.TransformType.Grad, + torch._C._functorch.TransformType.Jvp, + ) + + if ci is not None and ci.key() in forbidden_keys and compiler_fn is not eager: + name = ci.key().name.lower() + msg = ( + "If you are reaching here, it means dynamo failed for one of the following reasons:\n" + # Calling a torch.compiled function + f"- Calling torch.func.{name}(compiled_fn) function from eager mode is not supported. " + f"Ensure that torch.func.{name} is also wrapped within a torch.compile function. " + "For more information, see PyTorch issue #128711.\n" + # if it reaches here, it means Dynamo failed to inline a functorch function + f"- torch.func.{name}(fn) requires the function to be inlined by dynamo" + ) + unimplemented( + gb_type="Unsupported functorch tracing attempt", + context="", + explanation=msg, + hints=[], + ) + + def get_example_value(self, source: Source) -> Any: + if isinstance(source, LocalSource): + return self.f_locals[source.local_name] + if isinstance(source, GlobalSource): + return self.f_globals[source.global_name] + raise KeyError + + def symbolic_locals_contain_module_class(self) -> bool: + for v in self.symbolic_locals.values(): + if isinstance(v, UserDefinedClassVariable) and issubclass( + v.as_python_constant(), torch.nn.Module + ): + return True + return False + + def replace_tos_if_return_is_generator(self) -> None: + if ( + len(self.stack) + and (tos := self.stack[-1]) + and isinstance(tos, LocalGeneratorObjectVariable) + ): + self.stack[-1] = ListIteratorVariable( + unpack_iterable(self, tos), + mutation_type=ValueMutationNew(), + ) + + def _return(self, inst: Instruction) -> None: + self.replace_tos_if_return_is_generator() + if self.instruction_pointer is None: + raise AssertionError( + "expected self.instruction_pointer is not None to be true" + ) + if self.start_point is None: + raise AssertionError("expected self.start_point is not None to be true") + get_metrics_context().increment( + "ir_count", self.instruction_pointer - self.start_point + ) + + if ( + not config.allow_empty_graphs + and self.output.count_calls() == 0 + and not self.inconsistent_side_effects + and not self.symbolic_locals_contain_module_class() + and not self.export + and not self.one_graph + and not self.error_on_graph_break + and not self.is_tracing_resume_prologue + ): + raise exc.SkipFrame( + "No ops traced for the FX graph. `torch.compile` will skip the frame and fall back to eager.\n" + f"Frame info: {format_frame_info(self.f_code)}" + ) + + self.instruction_pointer = None + _step_logger()( + logging.INFO, + f"torchdynamo done tracing {self.f_code.co_name} ({inst.opname})", + ) + log.debug("return triggered compile") + all_stack_locals_metadata = self.output.compile_subgraph( + self, + reason=GraphCompileReason( + "return_value", [self.frame_summary()], graph_break=False + ), + # the value to be returned + stack_pops=1 if inst.opname == "RETURN_VALUE" else 0, + ) + # check that our stack/locals meta are correct: + # we should only be tracing 1 frame, and there should not be any NULLs on the stack + if len(all_stack_locals_metadata) != 1: + raise AssertionError( + "expected len(all_stack_locals_metadata) == 1 to be true" + ) + if all_stack_locals_metadata[0].stack_null_idxes: + raise AssertionError( + "expected not all_stack_locals_metadata[0].stack_null_idxes to be true" + ) + self.output.add_output_instructions( + self.codegen_return_with_pops(inst, all_stack_locals_metadata[0].num_stack), + [f"__ret = {self.get_pycode_last_varname('stack')}"] + if config.generate_pycode + else None, + ) + raise ReturnValueOp + + def RETURN_VALUE(self, inst: Instruction) -> None: + self._return(inst) + + def RETURN_CONST(self, inst: Instruction) -> None: + self._return(inst) + + +if sys.version_info >= (3, 11): + _binary_op_lookup = [ + getattr( + InstructionTranslator, + opname[3:] if "INPLACE" in opname else f"BINARY_{opname[3:]}", + ) + for opname, _ in dis._nb_ops # type: ignore[attr-defined] + ] + + +@contextlib.contextmanager +def profile_inline_call( + output: OutputGraph, + code: types.CodeType, + get_inline_depth: Callable[[], int], +) -> Generator[None, None, None]: + """ + Context manager for profiling inline calls. + + Args: + output: The OutputGraph containing profiler_state + code: The code object being inlined (for timing metadata) + get_inline_depth: Callable that returns inline_depth (called after work completes) + + Yields: + None (profiling happens around the with block) + """ + if not config.dynamo_profiler: + yield + return + + if output.profiler_state is None: + output.profiler_state = DynamoProfilerState() + + caller_info = output.profiler_state.get_current_caller() + call_stack = output.profiler_state.get_call_stack() + + output.profiler_state.push( + code.co_name, code.co_filename, code.co_firstlineno, time.time_ns() + ) + + trace_success = False + try: + yield + trace_success = True + finally: + stack_entry = output.profiler_state.pop() + trace_end_ns = time.time_ns() + + if trace_success and stack_entry is not None: + inline_depth = get_inline_depth() + cumtime_ns = trace_end_ns - stack_entry.start_time_ns + tottime_ns = cumtime_ns - stack_entry.child_time_ns + + timing = FunctionTraceTiming( + func_name=stack_entry.func_name, + filename=stack_entry.filename, + firstlineno=stack_entry.firstlineno, + cumtime_ns=cumtime_ns, + tottime_ns=tottime_ns, + bytecode_count=len(code.co_code), + inline_depth=inline_depth, + caller_func_name=caller_info[0] if caller_info else None, + caller_filename=caller_info[1] if caller_info else None, + caller_firstlineno=caller_info[2] if caller_info else None, + is_primitive_call=stack_entry.is_primitive_call, + call_stack=call_stack, + ) + output.profiler_state.record_timing(timing) + output.profiler_state.add_child_time(cumtime_ns) + + +class InliningInstructionTranslator(InstructionTranslatorBase): + """Trace and inline a called method""" + + symbolic_result: VariableTracker | None + # pyrefly: ignore [bad-override] + parent: InstructionTranslatorBase + + @classmethod + def inline_call( + cls, + parent: Any, + func: BaseUserFunctionVariable, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + allow_nested_graph_breaks: bool = False, + ) -> VariableTracker: + tracer = None + with profile_inline_call( + parent.output, func.get_code(), lambda: parent.inline_depth + 1 + ): + tracer = cls.build_inline_tracer( + parent, + func, + args, + kwargs, + allow_nested_graph_breaks=allow_nested_graph_breaks, + ) + return tracer.inline_call_() + + @staticmethod + def check_inlineable( + func: BaseUserFunctionVariable, + ) -> trace_rules.SkipResult: + if func.has_self(): + unimplemented( + gb_type="Inline attempt with __self__", + context=str(func), + explanation="Attempted to inline a function with the `__self__` attribute. " + "Dynamo is expected to decompose method calls into function calls with a `self` argument.", + hints=[], + ) + + if isinstance(func, UserFunctionVariable) and inspect.getattr_static( + func.get_function(), "_torchdynamo_disable", False + ): + msg = inspect.getattr_static( + func.get_function(), "_torchdynamo_disable_msg", None + ) + unimplemented( + gb_type="Skip inlining `torch.compiler.disable()`d function", + context=str(func.get_function()), + explanation=f"Skip inlining function {func.get_function()} since it was wrapped " + f"with `torch.compiler.disable` (reason: {msg})", + hints=[ + "Remove the `torch.compiler.disable` call", + ], + ) + + result = trace_rules.check_verbose(func, is_inlined_call=True) + if result.skipped: + from torch._dynamo.variables.misc import produce_trampoline_autograd_apply + + # _origin marks this as coming from an internal dynamo known function that is safe to + # trace through. + if ( + hasattr(func, "fn") + and hasattr(func.fn, "_origin") + and func.fn._origin is produce_trampoline_autograd_apply + ): + # Known sound + return trace_rules.SkipResult( + False, "allowlist in dynamo known function" + ) + fn_qualname = func.fn.__qualname__ if hasattr(func, "fn") else "" + hints = [ + f"Avoid calling the function `{fn_qualname}`.", + ] + if "_dynamo" not in func.get_filename(): + hints += [ + f"Apply `@torch._dynamo.dont_skip_tracing` to the function `{fn_qualname}` " + "to force tracing into the function. " + "More graph breaks may occur as a result of attempting to trace into the function.", + "Please file an issue to PyTorch.", + ] + unimplemented( + gb_type="Attempted to inline function marked as skipped", + context=f"qualname: {fn_qualname}, name: {func.get_name()}, " + f"filename: `{func.get_filename()}`, skip reason: {result.reason}", + explanation=f"Dynamo developers have intentionally marked that the function `{fn_qualname}` " + "should not be traced.", + hints=hints, + ) + + return result + + @staticmethod + def build_inline_tracer( + parent: Any, + func: BaseUserFunctionVariable, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + allow_nested_graph_breaks: bool = False, + ) -> InliningInstructionTranslator: + if not isinstance( + func, + ( + UserFunctionVariable, + NestedUserFunctionVariable, + LocalGeneratorFunctionVariable, + ), + ): + raise AssertionError( + "expected isinstance( func, ( UserFunctionVariable, NestedUserFunctionVariable, LocalGeneratorFunctionVariable, ), ) to be true" + ) + code: types.CodeType = func.get_code() + result = None + tracing_ctx = parent.output.tracing_context + + # Check if we have already identified this function to be inline-able. + # The exception is dont_skip_tracing flag which affects the inline + # behavior. If the flag is True, don't rely on previous results. + if not config.dont_skip_tracing and tracing_ctx: + if previous_result := tracing_ctx.previously_inlined_functions.get( + code, None + ): + result = previous_result + + if result is None: + result = InliningInstructionTranslator.check_inlineable(func) + if result.skipped is not False: + raise AssertionError("expected result.skipped is False to be true") + + if not config.dont_skip_tracing and tracing_ctx: + tracing_ctx.previously_inlined_functions[code] = result + + sub_locals = None + try: + sub_locals = func.bind_args(parent, args, kwargs) + except variables.functions.BindArgsTypeError as e: + exc.raise_type_error(parent, msg=e.args[0]) + + if sub_locals is None: + raise AssertionError("expected sub_locals is not None to be true") + + for v in itertools.chain(sub_locals.values()): + if not isinstance(v, VariableTracker): + unimplemented( + gb_type="Encountered unconverted argument when attempting to inline", + context=f"func: {func}, arg: {v}", + explanation="An argument to an inlined function was not successfully converted to a VariableTracker.", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + + if code.co_name in ( + "__setitem__", + "__setattr__", + "__delitem__", + "__delattr__", + ) and not ( + args + and isinstance( + args[0], + ( + variables.UserDefinedObjectVariable, + variables.UserDefinedClassVariable, + ), + ) + ): + unimplemented( + gb_type="Unsupported __setitem__/__setattr__/__delitem__/__delattr__ inline attempt", + context=f"code name: {code.co_name}, args: {args}", + explanation=f"Attempted to inline {code.co_name} where first argument (self) is not a user-defined object.", + hints=[], + ) + + suffix = "" + # TODO: mlazos, add support for enabling multiple artifact logs + # with a single alias + if torch._logging._internal.log_state.is_artifact_enabled("bytecode"): + suffix = f"\n{dis.Bytecode(code).dis()}" + if sys.version_info >= (3, 11): + cur_inst = parent.current_instruction + parent_code = parent.f_code + + def get_trace_call_log_str() -> str: + header = parent.get_line_of_code_header( + lineno=cur_inst.positions.lineno + ) + line = get_instruction_source_311(parent_code, cur_inst).rstrip() + return f"TRACE inlined call {code.co_name} from {header}\n{line}" + + trace_call_log.debug("%s", LazyString(get_trace_call_log_str)) + log.debug("INLINING %s%s, %s", code, suffix, result.reason) + + # Detect inline GraphModule calls in order to propagate node metadata, + # by checking if the first argument (self) is a variable tracking a GraphModule. + # For unrealized lazy VTs, use peek_type to skip non-Module args + # without realizing them (which would install unnecessary guards). + if args: + arg0 = args[0] + should_check = True + if isinstance(arg0, LazyVariableTracker) and not arg0.is_realized(): + if issubclass(arg0.peek_type(), torch.nn.Module): + arg0 = arg0.realize() + else: + should_check = False + + if should_check: + if isinstance(arg0, NNModuleVariable): + module = parent.output.get_submodule(arg0.module_key) + if isinstance(module, torch.fx.GraphModule): + code_context.get_context(module.forward.__code__)[ + "orig_graphmodule" + ] = weakref.ref(module) + elif isinstance(arg0, UnspecializedNNModuleVariable): + module = arg0.value + if isinstance(module, torch.fx.GraphModule): + code_context.get_context(module.forward.__code__)[ + "orig_graphmodule" + ] = weakref.ref(module) + + if isinstance(func, SkipFunctionVariable): + raise AssertionError( + "expected not isinstance(func, SkipFunctionVariable) to be true" + ) + tracer: InliningInstructionTranslator + if is_generator(code): + tracer = InliningGeneratorInstructionTranslator( + parent, + code, + sub_locals, + parent.symbolic_globals, + parent.symbolic_torch_function_state, + parent.symbolic_stream_state, + func, + allow_nested_graph_breaks=allow_nested_graph_breaks, + ) + else: + tracer = InliningInstructionTranslator( + parent, + code, + sub_locals, + parent.symbolic_globals, + parent.symbolic_torch_function_state, + parent.symbolic_stream_state, + func, + allow_nested_graph_breaks=allow_nested_graph_breaks, + ) + return tracer + + def inline_call_(self) -> VariableTracker: + parent = self.parent + parent.has_no_inlined_calls = False + parent.is_child_tracer_active = True + code = self.f_code + + strict_ctx: Any = contextlib.nullcontext() + if parent.strict_checks_fn: + strict_ctx = self.strict_translation_mode(parent.strict_checks_fn) + + try: + with strict_ctx: + self.run() + except exc.ObservedException as e: + msg = f"Observed exception DURING INLING {code} : {e}" + log.debug(msg) + # bubble up the exception to the parent frame. + raise + except (Unsupported, UserError) as e: + # If this graph break has skip_frame set, unset it + # since it refers to the current frame and not the parent. + e.skip_frame = False + raise + except Exception: + log.debug("FAILED INLINING %s", code) + raise + finally: + # Pass inlined tx's error_on_graph_break to parent. + # Deals with the case where the parent's error_on_graph_break is True + # while the inlined tx's error_on_graph_break was set to False. + parent.error_on_graph_break = self.error_on_graph_break + parent.is_child_tracer_active = False + + if self.output.should_exit: + # graph break + return ConstantVariable.create(None) # return dummy variable + + if self.symbolic_result is None: + raise AssertionError("expected self.symbolic_result is not None to be true") + + if self.f_globals is parent.f_globals: + # Merge symbolic_globals back if parent and child are in the same namespace + parent.symbolic_globals.update(self.symbolic_globals) + + parent.inconsistent_side_effects |= self.inconsistent_side_effects + + log.debug("DONE INLINING %s", code) + self.output.tracing_context.traced_code.append(code) + + if ( + is_generator(code) + and isinstance(self, InliningGeneratorInstructionTranslator) + and self.frame_state == FrameState.FRAME_CLEARED + ): + # When the generator returns None, we raise StopIteration + # pyrefly: ignore [implicit-any] + args = [] + if not self.symbolic_result.is_constant_none(): + args = [self.symbolic_result] + exc.raise_observed_exception(StopIteration, self, args=args) + else: + return self.symbolic_result + + def __init__( + self, + parent: InstructionTranslatorBase, + code: types.CodeType, + symbolic_locals: dict[str, VariableTracker], + symbolic_globals: dict[str, VariableTracker], + symbolic_torch_function_state: SymbolicTorchFunctionState, + symbolic_stream_state: SymbolicStreamState, + funcvar: BaseUserFunctionVariable | LocalGeneratorObjectVariable, + allow_nested_graph_breaks: bool = False, + ) -> None: + f_globals = funcvar.get_globals() + f_builtins = f_globals["__builtins__"] + if not isinstance(f_builtins, dict): + f_builtins = f_builtins.__dict__ + + # Get the cached code data. This cache combines instructions, indexof, and + # code_options to avoid recomputing them for frequently-inlined functions. + tracing_ctx = parent.output.tracing_context + cached = tracing_ctx.inlined_code_cache.get(code) if tracing_ctx else None + + if cached is not None: + instructions = cached.instructions + indexof = cached.indexof + code_options = cached.code_options + else: + instructions = cleaned_instructions(code) + propagate_line_nums(instructions) + indexof = get_indexof(instructions) + code_options = cast( + CodeOptions, {k: getattr(code, k) for k in get_code_keys()} + ) + if tracing_ctx: + tracing_ctx.inlined_code_cache[code] = InlinedCodeCache( + instructions=instructions, + indexof=indexof, + code_options=code_options, + ) + + super().__init__( + output=parent.output, + f_locals={}, + f_globals=f_globals, + f_builtins=f_builtins, + symbolic_locals=symbolic_locals, + symbolic_globals=symbolic_globals, + symbolic_torch_function_state=symbolic_torch_function_state, + symbolic_stream_state=symbolic_stream_state, + instructions=instructions, + code_options=code_options, + f_code=code, + export=parent.export, + inline_depth=parent.inline_depth + 1, + speculation_log=parent.speculation_log, + exn_vt_stack=parent.exn_vt_stack, + distributed_state=parent.distributed_state, + package=parent.package, + indexof=indexof, + ) + self.funcvar = funcvar + self.parent = parent + self.num_calls = parent.num_calls + self.symbolic_result = None + self.nn_module_stack = parent.nn_module_stack.copy() + self.one_graph = parent.one_graph + self._allow_nested_graph_breaks = allow_nested_graph_breaks + + @property + def fake_mode(self) -> FakeTensorMode | None: + return self.parent.fake_mode + + def run_ctx_mgr(self) -> Any: + return TracingContext.current_frame(self.parent.frame_summary()) + + def _can_speculate_comprehension_nested(self) -> bool: + """Check if comprehension speculation is allowed in this inlined context. + + Unlike should_compile_partial_graph(), this skips the exception table entry check. + """ + if not config.nested_graph_breaks: + return False + if not self._allow_nested_graph_breaks: + return False + if not self.funcvar.should_allow_nested_graph_breaks(): + return False + if not self.parent.should_compile_partial_graph(): + return False + return True + + def should_compile_partial_graph(self) -> bool: + if config.nested_graph_breaks: + if not self._allow_nested_graph_breaks: + return False + if not self.funcvar.should_allow_nested_graph_breaks(): + return False + if not self.parent.should_compile_partial_graph(): + return False + return super().should_compile_partial_graph() + return False # inlining functions is all-or-nothing + + def create_call_resume_at( + self, + inst: Instruction, + all_stack_locals_metadata: list[StackLocalsMetadata], + ) -> list[Instruction]: + if config.nested_graph_breaks: + return super().create_call_resume_at(inst, all_stack_locals_metadata) + unimplemented( + gb_type="Graph break in inlined function", + context="", + explanation="Graph breaks in an inlined call are not supported.", + hints=[], + ) + + def RETURN_VALUE(self, inst: Instruction) -> None: + self.symbolic_result = self.pop() + self.instruction_pointer = None + raise ReturnValueOp + + def RETURN_CONST(self, inst: Instruction) -> None: + self.symbolic_result = self._load_const(inst) + self.instruction_pointer = None + raise ReturnValueOp + + def get_globals_source_and_value( + self, name: str + ) -> tuple[Any, VariableTracker, Source]: + registered_module = _registered_module_for_globals( + self.f_globals.get("__name__"), self.f_globals + ) + if registered_module is not None: + module_name, fglobals_value = registered_module + module_source = self.import_source(module_name) + # Don't use lazy vt because we will do a setattr afterwards + # TODO: fix InstructionTranslator -> InstructionTranslatorBase + # pyrefly: ignore[bad-argument-type] + fglobals_vt = VariableBuilder(self, module_source)(fglobals_value) + global_source = AttrSource(module_source, name) + else: + globals_name = self.output.install_global_by_id( + "___unnamed_scope", self.f_globals + ) + globals_source = GlobalSource(globals_name) + fglobals_value = self.f_globals # type: ignore[assignment] + # Don't use lazy vt because we will do a setattr afterwards + # pyrefly: ignore[bad-argument-type] + fglobals_vt = VariableBuilder(self, globals_source)(fglobals_value) + global_source = DictGetItemSource(globals_source, name) # type: ignore[assignment] + + if is_stdlib(fglobals_value): + # Users don't inplace mutate a stdlib attribute (like inspect, + # collections), skip guards that originate from the stdlib modules. + global_source = SkipGuardSource(global_source) # type: ignore[assignment] + + return fglobals_value, fglobals_vt, global_source + + def _load_global(self, inst: Instruction) -> None: + name = inst.argval + if name not in self.f_globals: + return self.load_builtin(inst) + + if self.output.global_scope is self.f_globals: + # If the global scope matches that of the root frame, use handler in + # root frame instruction translator, to enforce consistency. + super()._load_global(inst) + else: + _, fglobals_vt, global_source = self.get_globals_source_and_value(name) + if self.output.side_effects.has_pending_mutation_of_attr(fglobals_vt, name): + self.push(self.output.side_effects.load_attr(fglobals_vt, name)) + else: + value = self.f_globals[name] + self.push(VariableTracker.build(self, value, global_source)) + + def STORE_GLOBAL(self, inst: Instruction) -> None: + if self.output.global_scope is self.f_globals: + # If the global scope matches that of the root frame, use handler in + # root frame instruction translator, to enforce consistency. + super().STORE_GLOBAL(inst) + else: + value = self.pop() + if isinstance(value, RemovableHandleVariable): + unimplemented( + gb_type="Storing Tensor hook handle in globals (inline call)", + context=inst.argval, + explanation="This is not supported.", + hints=[], + ) + name = inst.argval + _fglobals_value, fglobals_vt, global_source = ( + self.get_globals_source_and_value(name) + ) + if isinstance(global_source, DictGetItemSource): + unimplemented( + gb_type="STORE_GLOBAL in non-module globals", + context=name, + explanation=( + "Dynamo cannot safely replay global writes for an inlined " + "function whose globals dict is not the registered module " + "__dict__." + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + self.output.side_effects.store_attr(fglobals_vt, name, value) + + +class InliningGeneratorInstructionTranslator(InliningInstructionTranslator): + generated_items: list[VariableTracker] + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.generated_items = [] + self.frame_state = FrameState.FRAME_CREATED + self.gi_exc_state = Segment() + + @contextlib.contextmanager + def link_gi_exc_state(self): + try: + self.exn_vt_stack.push_segment(self.gi_exc_state) + yield + finally: + self.exn_vt_stack.pop_segment() + + @contextlib.contextmanager + def temporarily_set_frame_state(self, state: FrameState): + saved_frame_state = self.frame_state + try: + self.frame_state = state + yield + finally: + self.frame_state = saved_frame_state + + def inline_call_(self) -> VariableTracker: + with profile_inline_call(self.output, self.f_code, lambda: self.inline_depth): + return super().inline_call_() + + def should_compile_partial_graph(self) -> bool: + # resuming on graph break on inlined generator not supported + return False + + def YIELD_VALUE(self, inst: Instruction) -> None: + top = self.pop() + self.generated_items.append(top) + prev = self.instructions[self.indexof[inst] - 1].opname + if inst.opname == "YIELD_FROM" or prev == "SEND": + self.frame_state = FrameState.FRAME_SUSPENDED_YIELD_FROM + else: + self.frame_state = FrameState.FRAME_SUSPENDED + if len(self.generated_items) > MAX_ITERATOR_LIMIT: + raise exc.InfiniteGeneratorError + self.symbolic_result = top + # Stop tracing + raise YieldValueOp + + def GET_YIELD_FROM_ITER(self, inst: Instruction) -> None: + tos = self.stack[-1] + if not isinstance(tos, ListIteratorVariable): + self.pop() + res = VariableTracker.build(self, iter).call_function(self, [tos], {}) # type: ignore[arg-type] + self.push(res) + + def RETURN_GENERATOR(self, inst: Instruction) -> None: + self.symbolic_result = self.funcvar + raise ReturnValueOp + + def RETURN_VALUE(self, inst: Instruction) -> None: + self.frame_state = FrameState.FRAME_CLEARED + return super().RETURN_VALUE(inst) + + def RETURN_CONST(self, inst: Instruction) -> None: + self.frame_state = FrameState.FRAME_CLEARED + return super().RETURN_CONST(inst) + + def YIELD_FROM(self, inst: Instruction) -> None: + # https://github.com/python/cpython/blob/1790e584142b5db070b74bc64777ad14e26608c2/Python/ceval.c#L2581 + if not sys.version_info[:2] == (3, 10): + raise AssertionError("Python 3.10 specific") + + if not (len(self.stack) >= 2): + raise AssertionError("expected len(self.stack) >= 2 to be true") + val = self.pop() + receiver = self.stack[-1] + + gen_status = None + try: + result = pyiter_send(self, receiver, val) + except exc.ObservedUserStopIteration: + gen_status = PySendResult.PYGEN_RETURN + raised = self.exn_vt_stack.get_raised_exception() + result = pygen_fetch_stopiteration_value(raised) + exc.handle_observed_exception(self) + except exc.ObservedException: + # PYGEN_ERROR + gen_status = PySendResult.PYGEN_ERROR + raise + else: + # PYGEN_NEXT + gen_status = PySendResult.PYGEN_NEXT + + if gen_status == PySendResult.PYGEN_RETURN: + self.pop() + self.push(result) + else: + # gen_status == PYGEN_NEXT + # Repeat the YIELD_FROM instruction in the next eval loop + if isinstance(self.instruction_pointer, int): + if not (self.instruction_pointer > 0): + raise AssertionError( + "expected self.instruction_pointer > 0 to be true" + ) + self.instruction_pointer -= 1 + else: + raise AssertionError( + "expected isinstance(self.instruction_pointer, int) to be true" + ) + self.push(result) + # Add the value to yield into generated_items and replace the top of the stack with None + self.YIELD_VALUE(inst) + + def SEND(self, inst: Instruction) -> None: + if not (len(self.stack) >= 2): + raise AssertionError("expected len(self.stack) >= 2 to be true") + + val = self.pop() + if sys.version_info >= (3, 15): + receiver = self.stack[-2] + else: + receiver = self.stack[-1] + + try: + val = pyiter_send(self, receiver, val) + except exc.ObservedUserStopIteration: + # To implement SEND, we have to look at the implementation + # when the iterator returns StopIteration. This translates to this code + # 3.11: https://github.com/python/cpython/blob/3.11/Python/ceval.c#L2613-L2619 + # 3.12: https://github.com/python/cpython/blob/3.12/Python/bytecodes.c#L863-L866 + # The implementation is different in 3.11 and 3.12. In 3.12, we rely + # on END_SEND to clean up. In 3.11, SEND does the cleanup as well. + ex = self.exn_vt_stack.get_raised_exception() + val = pygen_fetch_stopiteration_value(ex) + self.exn_vt_stack.clear_current_exception() + if sys.version_info < (3, 12): + self.pop() # Python 3.12 uses new opcode END_SEND + self.push(val) + self.jump(inst) + else: + self.push(val) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/tensor_version_op.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/tensor_version_op.py new file mode 100644 index 0000000000000000000000000000000000000000..6a9bc8cf9b2a267046e91dd2923faf6174a1018e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/tensor_version_op.py @@ -0,0 +1,71 @@ +"""This module implements tensor version operations for Dynamo tracing. + +It provides primitives for handling tensor versioning during tracing, particularly in the +context of functionalization where version operations are handled eagerly on fake tensors. + +When we functionalize _tensor_version + _unsafe_set_version_counter, the ops disappear from +the traced graph. We run them eagerly on the fake tensors used for tracing, in order to get +past asserts that would fail in autograd. + +Why is this ok? +1) Versions on functional tensors do not make any sense since you cannot mutate a functional + tensor. +2) The whole point of version munging is to trick autograd into doing what we want, and after + AotAutograd there is no longer any need for these ops. + +Note this is similar to how no_grad is handled. +""" + +from contextlib import AbstractContextManager +from typing import Any + +import torch +from torch import SymInt +from torch._prims import _make_prim, RETURN_TYPE +from torch._subclasses import FakeTensorMode +from torch._subclasses.functional_tensor import FunctionalTensorMode + + +_tensor_version = _make_prim( + schema="_tensor_version(Tensor self) -> SymInt", + return_type=RETURN_TYPE.NEW, + meta=torch.ops.aten._version.default, + impl_aten=torch.ops.aten._version.default, + doc="Traceable unbacked SymInt version of torch.Tensor._version", +) + + +@_tensor_version.py_impl(FakeTensorMode) # type: ignore[misc] +def _tensor_version_fake(fake_mode: FakeTensorMode, self_tensor: Any) -> SymInt: + """ + The initial dynamo capture of _tensor_version + _unsafe_set_version_counter turns the + `._version` into an unbacked SymInt so that we don't need to specialize on the `._version` + of input tensors to the graph. + """ + if fake_mode.shape_env is None: + raise AssertionError("fake_mode.shape_env must not be None") + return fake_mode.shape_env.create_unbacked_symint() + + +_unsafe_set_version_counter = _make_prim( + schema="_unsafe_set_version_counter(Tensor[] tensors, SymInt[] versions) -> ()", + return_type=RETURN_TYPE.NEW, + meta=lambda self, version: None, + impl_aten=torch._C._autograd._unsafe_set_version_counter, + doc="Traceable+SymInt version of torch._C._autograd._unsafe_set_version_counter", +) +torch.fx.node.has_side_effect(_unsafe_set_version_counter) + + +@_tensor_version.py_impl(FunctionalTensorMode) # type: ignore[misc] +def _tensor_version_functional(mode: FunctionalTensorMode, self: Any) -> int: + return self._version + + +@_unsafe_set_version_counter.py_impl(FunctionalTensorMode) # type: ignore[misc] +def _unsafe_set_version_counter_functional( + ctx: AbstractContextManager[Any], + tensors: tuple[torch.Tensor, ...], + versions: tuple[int, ...], +) -> None: + torch._C._autograd._unsafe_set_version_counter(tensors, versions) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/test_case.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/test_case.py new file mode 100644 index 0000000000000000000000000000000000000000..2fc7ec8df5a4aa32010f799dab7b4f62c4881bda --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/test_case.py @@ -0,0 +1,258 @@ +"""Testing utilities for Dynamo, providing a specialized TestCase class and test running functionality. + +This module extends PyTorch's testing framework with Dynamo-specific testing capabilities. +It includes: +- A custom TestCase class that handles Dynamo-specific setup/teardown +- Test running utilities with dependency checking +- Automatic reset of Dynamo state between tests +- Proper handling of gradient mode state +""" + +import contextlib +import importlib +import inspect +import logging +import os +import re +import sys +import unittest +from collections.abc import Callable +from typing import Any + +import torch +import torch.testing +from torch._dynamo import polyfills +from torch._logging._internal import trace_log +from torch.testing._internal.common_utils import ( # type: ignore[attr-defined] + IS_WINDOWS, + TEST_WITH_CROSSREF, + TEST_WITH_TORCHDYNAMO, + TestCase as TorchTestCase, +) + +from . import config, utils + + +log = logging.getLogger(__name__) + + +def run_tests(needs: str | tuple[str, ...] = ()) -> None: + from torch.testing._internal.common_utils import run_tests + + if TEST_WITH_TORCHDYNAMO or TEST_WITH_CROSSREF: + return # skip testing + + if ( + not torch.xpu.is_available() + and IS_WINDOWS + and os.environ.get("TORCHINDUCTOR_WINDOWS_TESTS", "0") == "0" + ): + return + + if isinstance(needs, str): + needs = (needs,) + for need in needs: + if need == "cuda": + if not torch.cuda.is_available(): + return + else: + try: + importlib.import_module(need) + except ImportError: + return + + run_tests() + + +class TestCase(TorchTestCase): + _exit_stack: contextlib.ExitStack + + @classmethod + def tearDownClass(cls) -> None: + cls._exit_stack.close() + super().tearDownClass() + + @classmethod + def setUpClass(cls) -> None: + super().setUpClass() + cls._exit_stack = contextlib.ExitStack() # type: ignore[attr-defined] + cls._exit_stack.enter_context( # type: ignore[attr-defined] + config.patch( + raise_on_ctx_manager_usage=True, + suppress_errors=False, + log_compilation_metrics=False, + canonicalize_output_graph_node_order=True, + ), + ) + + def setUp(self) -> None: + self._prior_is_grad_enabled = torch.is_grad_enabled() + self._prior_nested_graph_breaks = config.nested_graph_breaks + config.nested_graph_breaks = True + super().setUp() + utils.counters.clear() + self.handler = logging.NullHandler() + trace_log.addHandler(self.handler) + + def tearDown(self) -> None: + trace_log.removeHandler(self.handler) + for k, v in utils.counters.items(): + log.debug("%s %s", k, v.most_common()) + utils.counters.clear() + torch._C._autograd._saved_tensors_hooks_enable() + super().tearDown() + if self._prior_is_grad_enabled is not torch.is_grad_enabled(): + log.warning("Running test changed grad mode") + torch.set_grad_enabled(self._prior_is_grad_enabled) + config.nested_graph_breaks = self._prior_nested_graph_breaks + + def before_cuda_memory_leak_check(self) -> None: + super().before_cuda_memory_leak_check() + utils.counters.clear() + + def assertEqual(self, x: Any, y: Any, *args: Any, **kwargs: Any) -> None: # type: ignore[override] + if config.debug_disable_compile_counter: + if isinstance(x, utils.CompileCounterInt) or isinstance( + y, utils.CompileCounterInt + ): + return + # skip checks like self.assertEqual(len(counters["graph_break"]), 1) + if ( + (cur_frame := inspect.currentframe()) + and (upper_frame := cur_frame.f_back) + and (upper_code := inspect.getframeinfo(upper_frame).code_context) + and "counters" in upper_code[0] + ): + return + return super().assertEqual(x, y, *args, **kwargs) + + def assertExpectedInline(self, *args: Any, **kwargs: Any) -> None: # type: ignore[override] + if config.debug_disable_compile_counter: + return + kwargs["skip"] = kwargs.get("skip", 0) + 1 + return super().assertExpectedInline(*args, **kwargs) + + +class CPythonTestCase(TestCase): + """ + Test class for CPython tests located in "test/cpython/v{Py_version}/*". + + This class enables specific features that are disabled by default, such as + tracing through unittest methods. + """ + + _stack: contextlib.ExitStack + dynamo_strict_nopython = True + + # Restore original unittest methods to simplify tracing CPython test cases. + assertEqual = unittest.TestCase.assertEqual # type: ignore[assignment] + assertNotEqual = unittest.TestCase.assertNotEqual # type: ignore[assignment] + assertTrue = unittest.TestCase.assertTrue + assertFalse = unittest.TestCase.assertFalse + assertIs = unittest.TestCase.assertIs + assertIsNot = unittest.TestCase.assertIsNot + assertIsNone = unittest.TestCase.assertIsNone + assertIsNotNone = unittest.TestCase.assertIsNotNone + assertIn = unittest.TestCase.assertIn + assertNotIn = unittest.TestCase.assertNotIn + assertIsInstance = unittest.TestCase.assertIsInstance + assertNotIsInstance = unittest.TestCase.assertNotIsInstance + assertAlmostEqual = unittest.TestCase.assertAlmostEqual + assertNotAlmostEqual = unittest.TestCase.assertNotAlmostEqual + assertGreater = unittest.TestCase.assertGreater + assertGreaterEqual = unittest.TestCase.assertGreaterEqual + assertLess = unittest.TestCase.assertLess + assertLessEqual = unittest.TestCase.assertLessEqual + assertRegex = unittest.TestCase.assertRegex + assertNotRegex = unittest.TestCase.assertNotRegex + assertCountEqual = unittest.TestCase.assertCountEqual + assertMultiLineEqual = polyfills.assert_multi_line_equal + assertSequenceEqual = polyfills.assert_sequence_equal + assertListEqual = unittest.TestCase.assertListEqual + assertTupleEqual = unittest.TestCase.assertTupleEqual + assertSetEqual = unittest.TestCase.assertSetEqual + # pyrefly: ignore [bad-override] + assertDictEqual = polyfills.assert_dict_equal + # pyrefly: ignore [bad-override] + assertRaises = unittest.TestCase.assertRaises + # pyrefly: ignore [bad-override] + assertRaisesRegex = unittest.TestCase.assertRaisesRegex + assertWarns = unittest.TestCase.assertWarns + assertWarnsRegex = unittest.TestCase.assertWarnsRegex + assertLogs = unittest.TestCase.assertLogs + fail = unittest.TestCase.fail + failureException = unittest.TestCase.failureException + + def compile_fn( + self, + fn: Callable[..., Any], + backend: str | Callable[..., Any], + nopython: bool, + ) -> Callable[..., Any]: + # We want to compile only the test function, excluding any setup code + # from unittest + + method = getattr(self, self._testMethodName) + method = torch._dynamo.optimize(backend, error_on_graph_break=nopython)(method) + + setattr(self, self._testMethodName, method) + return fn + + def _dynamo_test_key(self) -> str: + suffix = super()._dynamo_test_key() + test_cls = self.__class__ + test_file = inspect.getfile(test_cls).split(os.sep)[-1].split(".")[0] + py_ver = re.search(r"/v([\d_]+)/", inspect.getfile(test_cls)) + if py_ver: + py_ver = py_ver.group().strip(os.sep).replace("_", "").lstrip("v") # type: ignore[assignment] + else: + return suffix + return f"CPython{py_ver}-{test_file}-{suffix}" + + @classmethod + def tearDownClass(cls) -> None: + cls._stack.close() + super().tearDownClass() + + @classmethod + def setUpClass(cls) -> None: + # Skip test if python versions doesn't match + search_path = inspect.getfile(cls) + + cpython_test_regex = ( + re.escape(os.path.join("cpython") + os.path.sep) + r"v(\d)_(\d{2})" + ) + + m = re.search(cpython_test_regex, search_path) + if m: + test_py_ver = tuple(map(int, m.groups())) + py_ver = sys.version_info[:2] + if py_ver != test_py_ver: + expected = ".".join(map(str, test_py_ver)) + got = ".".join(map(str, py_ver)) + raise unittest.SkipTest( + f"Test requires Python {expected} but got Python {got}" + ) + else: + raise unittest.SkipTest( + f"Test requires a specific Python version but not found in path {inspect.getfile(cls)}" + ) + + super().setUpClass() + cls._stack = contextlib.ExitStack() # type: ignore[attr-defined] + cls._stack.enter_context( # type: ignore[attr-defined] + config.patch( + enable_trace_unittest=True, + enable_trace_load_build_class=True, + ), + ) + + @contextlib.contextmanager + def subTest(self, *args, **kwargs): + # pytest 9.x addSubTest uses typing._GenericAlias calls that + # Dynamo cannot trace. Use a no-op subTest instead. + yield + + # pyrefly: ignore [implicit-any] + def wrap_with_policy(self, method_name: str, policy: Callable) -> None: + pass diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/test_dont_skip_tracing_functions.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/test_dont_skip_tracing_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..1edce5ff857fb2c0e35f4ac5debc42291a9d073e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/test_dont_skip_tracing_functions.py @@ -0,0 +1,40 @@ +""" +Functions used to test torch._dynamo.dont_skip_tracing. +This file is located in torch/_dynamo so that it is skipped by trace rules. +There is a special rule in trace_rules that doesn't skip this file when +dont_skip_tracing is active. +""" + +import torch + + +def f1(x: torch.Tensor) -> torch.Tensor: + return x + 1 + + +def f2(x: torch.Tensor) -> torch.Tensor: + return x + 1 + + +def f3(x: torch.Tensor) -> torch.Tensor: + return f2(x) + + +def f4(x: torch.Tensor) -> torch.Tensor: + x = f5(x, 1) + x = torch._dynamo.dont_skip_tracing(f6)(x) + x = f5(x, 8) + return x + + +def f5(x: torch.Tensor, n: int) -> torch.Tensor: + if torch.compiler.is_compiling(): + return x + n + return x + + +def f6(x: torch.Tensor) -> torch.Tensor: + x = f5(x, 2) + torch._dynamo.graph_break() + x = f5(x, 4) + return x diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/test_minifier_common.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/test_minifier_common.py new file mode 100644 index 0000000000000000000000000000000000000000..a61daba11d36fa8566b9f5640cf27b425daf3039 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/test_minifier_common.py @@ -0,0 +1,336 @@ +"""Common utilities for testing Dynamo's minifier functionality. + +This module provides the base infrastructure for running minification tests in Dynamo. +It includes: +- MinifierTestResult: A dataclass for storing and processing minifier test results +- MinifierTestBase: A base test class with utilities for: + - Running tests in isolated environments + - Managing temporary directories and configurations + - Executing minifier launcher scripts + - Running and validating reproduction scripts + - Supporting both compile-time and runtime error testing + +The minifier helps reduce failing Dynamo compilations to minimal reproductions. +""" + +import dataclasses +import io +import logging +import os +import re +import shutil +import subprocess +import sys +import tempfile +import traceback +from collections.abc import Sequence +from typing import Any +from unittest.mock import patch + +import torch +import torch._dynamo +import torch._dynamo.test_case +from torch._dynamo.trace_rules import _as_posix_path +from torch.utils._traceback import report_compile_source_on_error + + +def _decode_subprocess_output(output: bytes) -> str: + return output.decode("utf-8", errors="replace") + + +@dataclasses.dataclass +class MinifierTestResult: + minifier_code: str + repro_code: str + + def _get_module(self, t: str) -> str: + match = re.search(r"class Repro\(torch\.nn\.Module\):\s+([ ].*\n| *\n)+", t) + if match is None: + raise AssertionError("failed to find module") + r = match.group(0) + r = re.sub(r"\s+$", "\n", r, flags=re.MULTILINE) + r = re.sub(r"\n{3,}", "\n\n", r) + return r.strip() + + def get_exported_program_path(self) -> str | None: + # Extract the exported program file path from AOTI minifier's repro.py + # Regular expression pattern to match the file path + pattern = r'torch\.export\.load\(\s*["\'](.*?)["\']\s*\)' + # Search for the pattern in the text + match = re.search(pattern, self.repro_code) + # Extract and print the file path if a match is found + if match: + file_path = match.group(1) + return file_path + return None + + def minifier_module(self) -> str: + return self._get_module(self.minifier_code) + + def repro_module(self) -> str: + return self._get_module(self.repro_code) + + +class MinifierTestBase(torch._dynamo.test_case.TestCase): + DEBUG_DIR = tempfile.mkdtemp() + + @classmethod + def setUpClass(cls) -> None: + super().setUpClass() + if not os.path.exists(cls.DEBUG_DIR): + cls.DEBUG_DIR = tempfile.mkdtemp() + cls._exit_stack.enter_context( # type: ignore[attr-defined] + torch._dynamo.config.patch(debug_dir_root=cls.DEBUG_DIR) + ) + # These configurations make new process startup slower. Disable them + # for the minification tests to speed them up. + cls._exit_stack.enter_context( # type: ignore[attr-defined] + torch._inductor.config.patch( + { + # https://github.com/pytorch/pytorch/issues/100376 + "pattern_matcher": False, + # multiprocess compilation takes a long time to warmup + "compile_threads": 1, + # https://github.com/pytorch/pytorch/issues/100378 + "cpp.vec_isa_ok": False, + } + ) + ) + + @classmethod + def tearDownClass(cls) -> None: + if os.getenv("PYTORCH_KEEP_TMPDIR", "0") != "1": + shutil.rmtree(cls.DEBUG_DIR) + else: + print(f"test_minifier_common tmpdir kept at: {cls.DEBUG_DIR}") + cls._exit_stack.close() # type: ignore[attr-defined] + + def _gen_codegen_fn_patch_code(self, device: str, bug_type: str) -> str: + if bug_type not in ("compile_error", "runtime_error", "accuracy"): + raise AssertionError( + f"bug_type must be one of compile_error, runtime_error, accuracy, got {bug_type!r}" + ) + return f"""\ +{torch._dynamo.config.codegen_config()} +{torch._inductor.config.codegen_config()} +torch._inductor.config.{"cpp" if device == "cpu" else "triton"}.inject_relu_bug_TESTING_ONLY = {bug_type!r} +""" + + def _maybe_subprocess_run( + self, args: Sequence[Any], *, isolate: bool, cwd: str | None = None + ) -> subprocess.CompletedProcess[bytes]: + from torch._inductor.cpp_builder import normalize_path_separator + + if not isolate: + if len(args) < 2: + raise AssertionError(f"expected at least 2 args, got {args}") + if args[0] != "python3": + raise AssertionError(f"expected args[0] to be 'python3', got {args}") + if args[1] == "-c": + if len(args) != 3: + raise AssertionError( + f"expected exactly 3 args for -c mode, got {args}" + ) + code = args[2] + args = ["-c"] + else: + if len(args) < 2: + raise AssertionError(f"expected at least 2 args, got {args}") + with open(args[1]) as f: + # Need normalize path of the code. + code = normalize_path_separator(f.read()) + args = args[1:] + + # WARNING: This is not a perfect simulation of running + # the program out of tree. We only interpose on things we KNOW we + # need to handle for tests. If you need more stuff, you will + # need to augment this appropriately. + + # NB: Can't use save_config because that will omit some fields, + # but we must save and reset ALL fields + dynamo_config = torch._dynamo.config.get_config_copy() + inductor_config = torch._inductor.config.get_config_copy() + try: + stderr = io.StringIO() + log_handler = logging.StreamHandler(stderr) + log = logging.getLogger("torch._dynamo") + log.addHandler(log_handler) + try: + prev_cwd = _as_posix_path(os.getcwd()) + if cwd is not None: + cwd = _as_posix_path(cwd) + os.chdir(cwd) + with patch("sys.argv", args), report_compile_source_on_error(): + exec(code, {"__name__": "__main__", "__compile_source__": code}) + rc = 0 + except Exception: + rc = 1 + traceback.print_exc(file=stderr) + finally: + log.removeHandler(log_handler) + if cwd is not None: + os.chdir(prev_cwd) # type: ignore[possibly-undefined] + # Make sure we don't leave buggy compiled frames lying + # around + torch._dynamo.reset() + finally: + torch._dynamo.config.load_config(dynamo_config) + torch._inductor.config.load_config(inductor_config) + + # TODO: return a more appropriate data structure here + return subprocess.CompletedProcess( + args, + rc, + b"", + stderr.getvalue().encode("utf-8"), + ) + else: + if cwd is not None: + cwd = _as_posix_path(cwd) + return subprocess.run(args, capture_output=True, cwd=cwd, check=False) + + # Run `code` in a separate python process. + # Returns the completed process state and the directory containing the + # minifier launcher script, if `code` outputted it. + def _run_test_code( + self, code: str, *, isolate: bool + ) -> tuple[subprocess.CompletedProcess[bytes], str | Any]: + proc = self._maybe_subprocess_run( + ["python3", "-c", code], isolate=isolate, cwd=self.DEBUG_DIR + ) + + print("test stdout:", _decode_subprocess_output(proc.stdout)) + stderr = _decode_subprocess_output(proc.stderr) + print("test stderr:", stderr) + repro_dir_match = re.search(r"(\S+)minifier_launcher.py", stderr) + if repro_dir_match is not None: + return proc, repro_dir_match.group(1) + return proc, None + + # Runs the minifier launcher script in `repro_dir` + def _run_minifier_launcher( + self, + repro_dir: str, + isolate: bool, + *, + minifier_args: Sequence[Any] = (), + repro_after: str | None = None, + ) -> tuple[subprocess.CompletedProcess[bytes], str]: + self.assertIsNotNone(repro_dir) + launch_file = _as_posix_path(os.path.join(repro_dir, "minifier_launcher.py")) + with open(launch_file) as f: + launch_code = f.read() + + self.assertTrue(os.path.exists(launch_file)) + + args = ["python3", launch_file, "minify", *minifier_args] + if not isolate and repro_after != "aot_inductor": + # AOTI minifier doesn't have --no-isolate flag. + # Everything in AOTI minifier is in no-isolate mode. + args.append("--no-isolate") + launch_proc = self._maybe_subprocess_run(args, isolate=isolate, cwd=repro_dir) + print("minifier stdout:", _decode_subprocess_output(launch_proc.stdout)) + stderr = _decode_subprocess_output(launch_proc.stderr) + print("minifier stderr:", stderr) + + self.assertNotIn("Input graph did not fail the tester", stderr) + + return launch_proc, launch_code + + # Runs the repro script in `repro_dir` + def _run_repro( + self, repro_dir: str, *, isolate: bool = True + ) -> tuple[subprocess.CompletedProcess[bytes], str]: + self.assertIsNotNone(repro_dir) + repro_file = _as_posix_path(os.path.join(repro_dir, "repro.py")) + with open(repro_file) as f: + repro_code = f.read() + + self.assertTrue(os.path.exists(repro_file)) + + repro_proc = self._maybe_subprocess_run( + ["python3", repro_file], isolate=isolate, cwd=repro_dir + ) + print("repro stdout:", _decode_subprocess_output(repro_proc.stdout)) + print("repro stderr:", _decode_subprocess_output(repro_proc.stderr)) + return repro_proc, repro_code + + # Template for testing code. + # `run_code` is the code to run for the test case. + # `patch_code` is the code to be patched in every generated file; usually + # just use this to turn on bugs via the config + def _gen_test_code(self, run_code: str, repro_after: str, repro_level: int) -> str: + repro_after_line = "" + if repro_after == "aot_inductor": + repro_after_line = ( + "torch._inductor.config.aot_inductor.dump_aoti_minifier = True" + ) + elif repro_after: + repro_after_line = f"""\ +torch._dynamo.config.repro_after = "{repro_after}" + """ + return f"""\ +import torch +import torch._dynamo +import torch._inductor +{_as_posix_path(torch._dynamo.config.codegen_config())} +{_as_posix_path(torch._inductor.config.codegen_config())} +{repro_after_line} +torch._dynamo.config.repro_level = {repro_level} +torch._inductor.config.aot_inductor.repro_level = {repro_level} +torch._dynamo.config.debug_dir_root = "{_as_posix_path(self.DEBUG_DIR)}" +{run_code} +""" + + # Runs a full minifier test. + # Minifier tests generally consist of 3 stages: + # 1. Run the problematic code + # 2. Run the generated minifier launcher script + # 3. Run the generated repro script + # + # If possible, you should run the test with isolate=False; use + # isolate=True only if the bug you're testing would otherwise + # crash the process + def _run_full_test( + self, + run_code: str, + repro_after: str, + expected_error: str | None, + *, + isolate: bool, + minifier_args: Sequence[Any] = (), + ) -> MinifierTestResult | None: + if isolate: + repro_level = 3 + elif expected_error is None or expected_error == "AccuracyError": + repro_level = 4 + else: + repro_level = 2 + test_code = self._gen_test_code(run_code, repro_after, repro_level) + print("running test", file=sys.stderr) + test_proc, repro_dir = self._run_test_code(test_code, isolate=isolate) + if expected_error is None: + # Just check that there was no error + self.assertEqual(test_proc.returncode, 0) + + self.assertIsNone(repro_dir) + return None + # NB: Intentionally do not test return code; we only care about + # actually generating the repro, we don't have to crash + + self.assertIn(expected_error, _decode_subprocess_output(test_proc.stderr)) + + self.assertIsNotNone(repro_dir) + print("running minifier", file=sys.stderr) + _minifier_proc, minifier_code = self._run_minifier_launcher( + repro_dir, + isolate=isolate, + minifier_args=minifier_args, + repro_after=repro_after, + ) + print("running repro", file=sys.stderr) + repro_proc, repro_code = self._run_repro(repro_dir, isolate=isolate) + + self.assertIn(expected_error, _decode_subprocess_output(repro_proc.stderr)) + self.assertNotEqual(repro_proc.returncode, 0) + return MinifierTestResult(minifier_code=minifier_code, repro_code=repro_code) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/testing.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/testing.py new file mode 100644 index 0000000000000000000000000000000000000000..a69303583afc14f5e55370d1b528f9662863c6f9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/testing.py @@ -0,0 +1,613 @@ +"""Testing utilities and infrastructure for Dynamo. + +This module provides a comprehensive set of testing utilities including: +- Test result collection and validation +- Graph manipulation and comparison tools +- Test case management and execution helpers +- Specialized test decorators for different Python versions and features +- RNG state management +- Compilation counting and monitoring +- Debug utilities for bytecode transformation + +The utilities in this module are used across Dynamo's test suite to ensure +consistent testing patterns and proper test isolation. +""" + +import contextlib +import dis +import functools +import logging +import os.path +import random +import re +import sys +import types +import unittest +from collections.abc import Callable, Generator, Sequence +from typing import Any, overload, TypeVar +from typing_extensions import ParamSpec +from unittest.mock import patch + +import torch +from torch import fx +from torch._dynamo.backends.debugging import aot_eager +from torch._dynamo.output_graph import OutputGraph + +from . import config, eval_frame, optimize_assert, reset +from .bytecode_transformation import ( + create_instruction, + debug_checks, + is_generator, + transform_code_object, +) +from .guards import CheckFunctionManager, CompileId, GuardedCode +from .types import ConvertFrameReturn, DynamoFrameType, wrap_guarded_code +from .utils import CompileCounterInt, same + + +np: types.ModuleType | None = None +try: + import numpy as np +except ModuleNotFoundError: + np = None + + +unsupported = eval_frame.unsupported +three = 3 + +log = logging.getLogger(__name__) + +_P = ParamSpec("_P") + + +def clone_me(x: torch.Tensor | None) -> torch.Tensor | None: + if x is None: + return None + return x.detach().clone().requires_grad_(x.requires_grad) + + +def remove_optimized_module_prefix(name: str) -> str: + return re.sub(r"^_orig_mod[.]", "", name) + + +def extract_graph_and_tracker(fn, *args, **kwargs): # type: ignore[no-untyped-def] + from torch._dynamo.symbolic_convert import InstructionTranslator + + gm = None + region_tracker = None + + def extract_graph_backend(_gm, *args, **kwargs): # type: ignore[no-untyped-def] + nonlocal gm + nonlocal region_tracker + gm = _gm + region_tracker = InstructionTranslator.current_tx().output.region_tracker + return _gm + + torch.compile(backend=extract_graph_backend, fullgraph=True)(fn)(*args, **kwargs) + return gm.graph, region_tracker # type: ignore[union-attr] + + +def extract_graph(fn, *args, **kwargs): # type: ignore[no-untyped-def] + backend = AotEagerAndRecordGraphs() + result = torch.compile(backend=backend)(fn)(*args, **kwargs) + return result, backend.graphs, backend.fw_graphs, backend.bw_graphs + + +def collect_results( + model: torch.nn.Module, prediction: Any, loss: Any, example_inputs: Any +) -> list[Any]: + results = [] + results.append(prediction) + results.append(loss) + # if isinstance(loss, torch.Tensor) and loss.item() > 1: + # log.warning( + # f"High loss value alert - {loss:.2f}. Can result in unstable gradients." + # ) + + grads = {} + params = {} + for name, param in model.named_parameters(): + if isinstance(model, eval_frame.OptimizedModule): + name = remove_optimized_module_prefix(name) + param_copy = param + grad = param.grad + # Treat None and zero grad as same + if param.grad is None: + grad = torch.zeros_like(param) + grads[name + ".grad"] = grad + params[name] = param_copy + results.append(grads) + results.append(params) + buffers = {} + for name, buffer in model.named_buffers(): + if isinstance(model, eval_frame.OptimizedModule): + name = remove_optimized_module_prefix(name) + buffers[name] = buffer + results.append(buffers) + for example in example_inputs: + if isinstance(example, (tuple, list)): + results.extend(inp.grad for inp in example if isinstance(inp, torch.Tensor)) + else: + if isinstance(example, torch.Tensor): + results.append(example.grad) + return results + + +def requires_bwd_pass(out: Any) -> bool: + if isinstance(out, torch.Tensor): + return out.requires_grad + elif isinstance(out, (list, tuple)): + return any(requires_bwd_pass(x) for x in out) + elif out is None: + return False + elif isinstance(out, int): + return False + raise NotImplementedError("Don't know how to reduce", type(out)) + + +@overload +def reduce_to_scalar_loss(out: torch.Tensor) -> torch.Tensor: ... + + +@overload +def reduce_to_scalar_loss( + out: list[Any] | tuple[Any, ...] | dict[Any, Any], +) -> float: ... + + +def reduce_to_scalar_loss(out: Any) -> torch.Tensor | float: + """Reduce the output of a model to get scalar loss""" + if isinstance(out, torch.Tensor): + # Mean does not work on integer tensors + return out.sum() / out.numel() + elif isinstance(out, (list, tuple)): + return sum(reduce_to_scalar_loss(x) for x in out) / len(out) + elif type(out).__name__ in ( + "MaskedLMOutput", + "Seq2SeqLMOutput", + "CausalLMOutputWithCrossAttentions", + ): + return reduce_to_scalar_loss(out.logits) + elif type(out).__name__ == "SquashedNormal": + return out.mean.sum() + elif isinstance(out, dict): + return sum(reduce_to_scalar_loss(value) for value in out.values()) / len( + out.keys() + ) + raise NotImplementedError("Don't know how to reduce", type(out)) + + +def debug_dir() -> str: + path = os.path.join(os.path.dirname(__file__), "../debug") + if not os.path.exists(path): + os.mkdir(path) + return path + + +def debug_dump(name: str, code: types.CodeType, extra: str = "") -> None: + with open(os.path.join(debug_dir(), name), "w") as fd: + fd.write( + f"{dis.Bytecode(code).info()}\n\n{dis.Bytecode(code).dis()}\n\n{extra}\n" + ) + + +def debug_insert_nops( + frame: DynamoFrameType, cache_size: int, hooks: Any, _: Any, *, skip: int = 0 +) -> ConvertFrameReturn: + """used to debug jump updates""" + + def insert_nops(instructions: list[Any], code_options: Any) -> None: + instructions.insert(0, create_instruction("NOP")) + instructions.insert(0, create_instruction("NOP")) + + metrics_context = torch._dynamo.utils.get_metrics_context() + with torch._dynamo.utils.dynamo_timed("debug_insert_nops"), metrics_context: + if is_generator(frame.f_code): + return ConvertFrameReturn() + + debug_checks(frame.f_code) + code, _ = transform_code_object(frame.f_code, insert_nops) + graph = OutputGraph( + # The nop-insertion path does not inspect code object attributes. + code_options={}, # type: ignore[arg-type] + compiler_fn=None, + root_tx=None, # type: ignore[arg-type] + export=False, + export_constraints=[], + frame_state={"_id": 0}, + # TODO: shouldn't this be f_locals/f_globals from frame? + local_scope=locals(), + global_scope=globals(), + f_code=frame.f_code, + torch_function_mode_stack=[], + package=None, + ) + + return wrap_guarded_code( + GuardedCode( + code, + CheckFunctionManager(frame.f_code, graph).guard_manager, # type: ignore[arg-type] + CompileId(frame_id=0, frame_compile_id=0), + ) + ) + + +class CompileCounter: + def __init__(self) -> None: + self.frame_count: int | CompileCounterInt = 0 + self.clear() + + def __call__( + self, gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] + ) -> Callable[..., Any]: + self.frame_count += 1 + for node in gm.graph.nodes: + if "call" in node.op: + self.op_count += 1 + return gm.forward + + def clear(self) -> None: + if config.debug_disable_compile_counter: + self.frame_count = CompileCounterInt(0) + else: + self.frame_count = 0 + self.op_count = 0 + + +class CompileCounterWithBackend: + def __init__(self, backend: str) -> None: + self.frame_count: int | CompileCounterInt = 0 + self.backend = backend + self.graphs: list[torch.fx.GraphModule] = [] + self.clear() + + def __call__( + self, gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] + ) -> Callable[..., Any]: + from .backends.registry import lookup_backend + + self.frame_count += 1 + for node in gm.graph.nodes: + if "call" in node.op: + self.op_count += 1 + self.graphs.append(gm) + return lookup_backend(self.backend)(gm, example_inputs) + + def clear(self) -> None: + if config.debug_disable_compile_counter: + self.frame_count = CompileCounterInt(0) + else: + self.frame_count = 0 + self.op_count = 0 + self.graphs = [] + + +# Equivalent to backend="eager", but also records graphs that +# we can assert on +class EagerAndRecordGraphs: + def __init__(self) -> None: + self.graphs: list[torch.fx.GraphModule] = [] + + def __call__( + self, gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] + ) -> Callable[..., Any]: + self.graphs.append(gm) + return gm.forward + + +class AotEagerAndRecordGraphs: + def __init__(self) -> None: + self.graphs: list[torch.fx.GraphModule] = [] + self.fw_graphs: list[torch.fx.GraphModule] = [] + self.bw_graphs: list[torch.fx.GraphModule] = [] + + def __call__( + self, gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] + ) -> Callable[..., Any]: + self.graphs.append(gm) + + def fw_compiler( + gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] + ) -> Callable[..., Any]: + self.fw_graphs.append(gm) + return gm.forward + + def bw_compiler( + gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor] + ) -> Callable[..., Any]: + self.bw_graphs.append(gm) + return gm.forward + + return aot_eager( + gm, + example_inputs, + fw_compiler=fw_compiler, + bw_compiler=bw_compiler, + ) + + +class InductorAndRecordGraphs: + def __init__(self) -> None: + self.graphs: list[torch.fx.GraphModule] = [] + self.inductor_graphs: list[torch.fx.GraphModule] = [] + + def __call__(self, gm, example_inputs): # type: ignore[no-untyped-def] + import torch._inductor.compile_fx as compile_fx_mod + + self.graphs.append(gm) + + old_compile_fx_inner = compile_fx_mod._compile_fx_inner + + def patched(*args, **kwargs): # type: ignore[no-untyped-def] + self.inductor_graphs.append(args[0]) + return old_compile_fx_inner(*args, **kwargs) + + with patch.object(compile_fx_mod, "_compile_fx_inner", new=patched): + return compile_fx_mod.compile_fx(gm, example_inputs) + + +def strip_comment(code: str) -> str: + return re.sub(r"(?m)^ *#.*\n?", "", code) + + +def remove_trailing_space(code: str) -> str: + return "\n".join([line.rstrip() for line in code.split("\n")]) + + +def _squash_blank_lines(code: str) -> str: + lines = code.split("\n") + result: list[str] = [] + saw_blank = False + for line in lines: + if line.strip() == "": + if saw_blank: + continue + saw_blank = True + else: + saw_blank = False + result.append(line) + return "\n".join(result) + + +def normalize_gm(gm_str: str) -> str: + # strip comments as comments have path to files which may differ from + # system to system. + stripped = strip_comment(gm_str) + no_trailing = remove_trailing_space(stripped) + return _squash_blank_lines(no_trailing) + + +def empty_line_normalizer(code: str) -> str: + """ + Normalize code: remove empty lines. + """ + normal_code = re.sub(r"[\r\n]+", "\n", code) + return normal_code + + +def standard_test( + self: Any, + fn: Callable[..., Any], + nargs: int, + expected_ops: int | None = None, + expected_ops_dynamic: int | None = None, + expected_frame_count: int = 1, +) -> None: + if not config.assume_static_by_default and expected_ops_dynamic is not None: + expected_ops = expected_ops_dynamic + + actual = CompileCounter() + + args1 = [torch.randn(10, 10) for _ in range(nargs)] + args2 = [torch.randn(10, 10) for _ in range(nargs)] + correct1 = fn(*args1) + correct2 = fn(*args2) + reset() + opt_fn = optimize_assert(actual)(fn) + val1a = opt_fn(*args1) + val2a = opt_fn(*args2) + val1b = opt_fn(*args1) + val2b = opt_fn(*args2) + reset() + self.assertTrue(same(val1a, correct1)) + self.assertTrue(same(val1b, correct1)) + self.assertTrue(same(val2a, correct2)) + self.assertTrue(same(val2b, correct2)) + self.assertEqual(actual.frame_count, expected_frame_count) + if expected_ops is not None: + self.assertEqual(actual.op_count, expected_ops) + + +def dummy_fx_compile( + gm: fx.GraphModule, example_inputs: list[torch.Tensor] +) -> Callable[..., Any]: + return gm.forward + + +def format_speedup( + speedup: float, + pvalue: float, + is_correct: bool = True, + pvalue_threshold: float = 0.1, +) -> str: + if not is_correct: + return "ERROR" + if pvalue > pvalue_threshold: + return f"{speedup:.3f}x SAME" + return f"{speedup:.3f}x p={pvalue:.2f}" + + +def rand_strided( + size: Sequence[int], + stride: Sequence[int], + dtype: torch.dtype = torch.float32, + device: str | torch.device = "cpu", + extra_size: int = 0, +) -> torch.Tensor: + needed_size = extra_size + if all(s > 0 for s in size): + # only need to allocate if all sizes are non-zero + needed_size += ( + sum((shape - 1) * stride for shape, stride in zip(size, stride)) + 1 + ) + if dtype.is_floating_point: + if dtype == torch.float4_e2m1fn_x2: + buffer = torch.randint( + 0, 256, (needed_size,), dtype=torch.uint8, device=device + ).view(torch.float4_e2m1fn_x2) + elif dtype.itemsize == 1: + """ + normal distribution kernel is not implemented for fp8.. + Workaround that by creating a fp16 tensor and then cast. + """ + buffer = torch.randn(needed_size, dtype=torch.float16, device=device).to( + dtype=dtype + ) + else: + buffer = torch.randn(needed_size, dtype=dtype, device=device) + else: + buffer = torch.zeros(size=[needed_size], dtype=dtype, device=device) + return torch.as_strided(buffer, size, stride) + + +_T = TypeVar("_T") + + +def check_dynamic_shape_capture() -> bool: + # This also mirrors config from `test/dynamo/test_dynamic_shapes.py:make_dynamic_cls` + return not config.assume_static_by_default + + +def _make_fn_with_patches(fn: Callable[_P, _T], *patches: Any) -> Callable[_P, _T]: + @functools.wraps(fn) + def _fn(*args: _P.args, **kwargs: _P.kwargs) -> _T: + with contextlib.ExitStack() as stack: + for module, attr, val in patches: + stack.enter_context(patch.object(module, attr, val)) + + return fn(*args, **kwargs) + + return _fn + + +def make_test_cls_with_patches( + cls: type, + cls_prefix: str, + fn_suffix: str, + *patches: Any, + xfail_prop: str | None = None, + decorator: Callable[[Callable[..., Any]], Callable[..., Any]] = lambda x: x, +) -> type: + DummyTestClass = type(f"{cls_prefix}{cls.__name__}", cls.__bases__, {}) + DummyTestClass.__qualname__ = DummyTestClass.__name__ + + for name in dir(cls): + if name.startswith("test_"): + fn = getattr(cls, name) + if not callable(fn): + setattr(DummyTestClass, name, getattr(cls, name)) + continue + new_name = f"{name}{fn_suffix}" + new_fn = _make_fn_with_patches(fn, *patches) + new_fn.__name__ = new_name + if xfail_prop is not None and hasattr(fn, xfail_prop): + new_fn = unittest.expectedFailure(new_fn) + setattr(DummyTestClass, new_name, decorator(new_fn)) + # NB: Doesn't handle slots correctly, but whatever + elif not hasattr(DummyTestClass, name): + setattr(DummyTestClass, name, getattr(cls, name)) + + return DummyTestClass + + +# test Python 3.11+ specific features +def skipIfNotPy311(fn: Callable[_P, _T]) -> Callable[_P, _T]: + if sys.version_info >= (3, 11): + return fn + # pyrefly: ignore [bad-return, bad-argument-type] + return unittest.skip(fn) + + +def skipIfNotPy312(fn: Callable[_P, _T]) -> Callable[_P, _T]: + if sys.version_info >= (3, 12): + return fn + return unittest.skip("Requires Python 3.12+")(fn) + + +def skipIfOnlyNotPy312(fn: Callable[_P, _T]) -> Callable[_P, _T]: + if sys.version_info >= (3, 13) or sys.version_info < (3, 12): + return unittest.skip("Requires Python 3.12")(fn) + return fn + + +def xfailIfPy312(fn: Callable[_P, _T]) -> Callable[_P, _T]: + if sys.version_info >= (3, 12): + return unittest.expectedFailure(fn) + return fn + + +def skipIfPy312(fn: Callable[_P, _T]) -> Callable[_P, _T]: + if sys.version_info >= (3, 12): + return unittest.skip("Not supported in Python 3.12+")(fn) + return fn + + +# Controls tests generated in test/inductor/test_torchinductor_dynamic_shapes.py +# and test/dynamo/test_dynamic_shapes.py +def expectedFailureDynamic(fn: Callable[_P, _T]) -> Callable[_P, _T]: + fn._expected_failure_dynamic = True # type: ignore[attr-defined] + return fn + + +# Controls tests generated in test/inductor/test_torchinductor_codegen_dynamic_shapes.py +def expectedFailureCodegenDynamic(fn: Callable[_P, _T]) -> Callable[_P, _T]: + fn._expected_failure_codegen_dynamic = True # type: ignore[attr-defined] + return fn + + +# Controls test generated in test/inductor/test_cpp_wrapper.py +def expectedFailureDynamicWrapper(fn: Callable[_P, _T]) -> Callable[_P, _T]: + fn._expected_failure_dynamic_wrapper = True # type: ignore[attr-defined] + return fn + + +def reset_rng_state(use_xla: bool = False) -> None: + torch.manual_seed(1337) + random.seed(1337) + if np: + np.random.seed(1337) + if use_xla: + import torch_xla.core.xla_model as xm + + xm.set_rng_state(1337, str(xm.xla_device())) + + +def _skipped_function_for_test_reconstruct( + f: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs +) -> _T: + return f(*args, **kwargs) + + +_testing_invoke_subgraph_inductor_compile_captured_gms = None + + +@contextlib.contextmanager +def _testing_capture_invoke_subgraph_inductor_compile_gms() -> Generator[ + list[torch.fx.GraphModule] +]: + """ + Context manager to capture graph modules compiled by invoke_subgraph_inductor_compile. + + Usage: + with _testing_capture_invoke_subgraph_inductor_compile_gms() as captured_gms: + # code that triggers invoke_subgraph_inductor_compile + pass + # captured_gms will contain the list of captured graph modules + """ + global _testing_invoke_subgraph_inductor_compile_captured_gms + # pyrefly: ignore [implicit-any] + _testing_invoke_subgraph_inductor_compile_captured_gms = [] + try: + yield _testing_invoke_subgraph_inductor_compile_captured_gms + finally: + _testing_invoke_subgraph_inductor_compile_captured_gms = None diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/trace_rules.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/trace_rules.py new file mode 100644 index 0000000000000000000000000000000000000000..b72b316d99512e76306ffecc4e5c7b1c78975da6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/trace_rules.py @@ -0,0 +1,4276 @@ +""" +Tracing rules and policies for TorchDynamo compilation decisions. + +This module defines the rules that govern what code TorchDynamo should trace and compile +versus what should be executed eagerly. It contains functions and classes that determine: + +- Which modules, functions, and objects should be skipped during tracing +- Which parts of the code should cause graph breaks +- How to handle different Python libraries and third-party packages +- Rules for determining when to inline functions vs calling them eagerly + +Key components: +- Skip rules: Functions that return True if an object should be skipped during tracing +- Inlining rules: Policies for when to inline function calls during compilation +- Library-specific handling: Special cases for popular Python packages +- Performance heuristics: Rules that balance compilation overhead vs runtime benefits + +These rules are critical for TorchDynamo's ability to automatically determine +compilation boundaries and optimize PyTorch programs effectively. +""" + +import abc +import builtins +import contextlib +import copy +import dataclasses +import functools +import importlib +import inspect +import linecache +import operator +import os +import random +import re +import sys +import types +import typing +import unittest +from collections import defaultdict +from collections.abc import Callable, Iterator +from pathlib import Path +from typing import Any + +import torch +import torch._inductor.test_operators +import torch.distributed +import torch.utils._content_store +from torch._environment import is_fbcode +from torch.utils import _config_module + +from . import config +from .resume_execution import TORCH_DYNAMO_RESUME_IN_PREFIX +from .utils import ( + getfile, + hashable, + is_lru_cache_wrapped_function, + NP_SUPPORTED_MODULES, + unwrap_if_wrapper, +) +from .variables import ( + BuiltinVariable, + DictBuiltinVariable, + FunctionalCallVariable, + FunctorchHigherOrderVariable, + GetAttrBuiltinVariable, + HasAttrBuiltinVariable, + InspectSignatureVariable, + IterBuiltinVariable, + ListBuiltinVariable, + LocalGeneratorFunctionVariable, + LocalGeneratorObjectVariable, + NestedUserFunctionVariable, + PolyfilledFunctionVariable, + PyTreeGetNodeTypeFunctionVariable, + PyTreeTreeIsLeafFunctionVariable, + ReparametrizeModuleCallVariable, + SetAttrBuiltinVariable, + SkipFunctionVariable, + SparseTensorCreationSkipVariable, + TorchInGraphFunctionVariable, + UserFunctionVariable, + UserMethodVariable, +) +from .variables.base import VariableTracker + + +np: types.ModuleType | None = None +try: + import numpy as np +except ModuleNotFoundError: + pass + + +""" +A note on skip/inline rules: + +Dynamo consults this file to determine whether function should be inlined or skipped. + +A skip applies at the frame boundary, meaning dynamo either triggers a graph break +at the beginning of the frame or attempts to trace/inline the whole frame. When skipping +a frame, recursively called frames are still traced by dynamo unless also skipped. + +Skipfiles (skipped at the file level instead of function level) still apply on a +frame-by-frame boundary as dynamo traces, but apply to all functions in that file. + +@skip is a helper decorator that can be applied to your function to cause it to be +included here. + +Dynamo skip/inline rules & priorities are defined as follows: +* Inline is the default behavior and will be used unless explicitly skipped. +* Dynamo has two SKIPLIST: BUILTIN_SKIPLIST and THIRDPARTY_SKIPLIST. + * BUILTIN_SKIPLIST contains builtin python modules, such as abc, collections, etc. + * THIRDPARTY_SKIPLIST contains common third party libraries, such as numpy, pandas, etc. +* Functions in these two SKIPLISTs are always skipped, except: + * They have explicitly defined rule in `manual_torch_name_rule_map`; + * The corresponding python module has been put into MOD_INLINELIST. +* PyTorch(torch) is in the BUILTIN_SKIPLIST by default, but there are many cases + where we want inline the functions under torch namespace. + We should specify inline for the functions in `manual_torch_name_rule_map` or + put the corresponding python module into MOD_INLINELIST to make dynamo inline them. +* If you call functions under skipped modules/files, Dynamo will wrap these functions + as SkipFunctionVariable. There are a few functions(e.g, collections.OrderedDict) that + we have special handling at SkipFunctionVariable.call_function. + +Overall: *_INLINELIST has precedence over *_SKIPLIST has precedence over DEFAULT (inline) + +To figure out what the behavior is, check the following list in order: +* `manual_torch_name_rule_map` (Inline if YES) +* MOD_INLINELIST (Inline if YES) +* BUILTIN_SKIPLIST & THIRDPARTY_SKIPLIST (Skip if YES) +* MOD_SKIPLIST (Skip if YES) +* Inline by default + +In general, if you want to force inline a function or module, please consider adding +the function's python module to MOD_INLINELIST first. +Use the `manual_torch_name_rule_map` only when there are other functions under the same module that +you don't want to inline them. +""" + +""" +Map of function objects to their tracing rules (Dynamo variables). +* TorchInGraphFunctionVariable: The functions should be put into the FX graph or can be constant folded. E.g., + - torch.add: should be put into the FX graph. + - torch.is_floating_point: constant folded. +* SkipFunctionVariable: The objects should be skipped from tracing. +* UserFunctionVariable: The functions should be inlined. + +For developers: If you add/remove a torch level API, it may trigger failures from +test/dynamo/test_trace_rules.py:test_torch_name_rule_map_updated. To fix the failures: +If you are adding a new torch level API or Dynamo implementation: +* Add the name with the corresponding tracing rule to this map + if you are adding a new in graph function or Dynamo implementation for an existing function. +* Remove the object name from test/dynamo/test_trace_rules.ignored_c_binding_in_graph_function_names if it's there. + +If you are removing an existing torch level API: +* Remove the entry represented the API from this map or test/dynamo/test_trace_rules.ignored_c_binding_in_graph_function_names + depends on where it is. + + +""" +manual_torch_name_rule_map: dict[ + str, + type[TorchInGraphFunctionVariable] + | type[SkipFunctionVariable] + | type[UserFunctionVariable], +] = { + "torch.onnx.is_in_onnx_export": TorchInGraphFunctionVariable, + "torch.onnx.operators.shape_as_tensor": TorchInGraphFunctionVariable, + "torch.overrides.is_tensor_like": TorchInGraphFunctionVariable, + "torch._C._skip_one_hop_torch_function": TorchInGraphFunctionVariable, + "torch.jit.is_scripting": TorchInGraphFunctionVariable, + "torch.jit.is_tracing": TorchInGraphFunctionVariable, + "torch.jit.annotate": TorchInGraphFunctionVariable, + "torch.distributed.is_available": TorchInGraphFunctionVariable, + "torch.distributed.is_initialized": TorchInGraphFunctionVariable, + "torch.distributed.get_rank": TorchInGraphFunctionVariable, + "torch.distributed.get_world_size": TorchInGraphFunctionVariable, + "torch.distributed.tensor._api.DTensor#from_local": TorchInGraphFunctionVariable, + "torch.distributed.device_mesh.DeviceMesh#__init__": SkipFunctionVariable, + "torch/distributed/device_mesh.py#_create_sub_mesh": SkipFunctionVariable, + "torch.distributed.distributed_c10d._get_group_size_by_name": TorchInGraphFunctionVariable, + "torch.distributed.distributed_c10d._resolve_group_name_by_ranks_and_tag": TorchInGraphFunctionVariable, + "torch.distributed.distributed_c10d._get_group_tag": TorchInGraphFunctionVariable, + "torch.distributed.distributed_c10d.get_process_group_ranks": TorchInGraphFunctionVariable, + "torch.distributed.destroy_process_group": SkipFunctionVariable, + "torch._utils.is_compiling": TorchInGraphFunctionVariable, + "torch._utils._chunk_or_narrow_cat": UserFunctionVariable, + "torch._utils._maybe_view_chunk_cat": UserFunctionVariable, + "torch.fx._symbolic_trace.is_fx_tracing": TorchInGraphFunctionVariable, + "torch.fx._symbolic_trace.is_fx_symbolic_tracing": TorchInGraphFunctionVariable, + "torch.mps.is_available": TorchInGraphFunctionVariable, + "torch.mtia.is_available": TorchInGraphFunctionVariable, + "torch._dynamo.external_utils.is_compiling": TorchInGraphFunctionVariable, + "torch._dynamo.utils._disable_side_effect_safety_checks_for_current_subtracer": UserFunctionVariable, + "torch.compiler.is_compiling": TorchInGraphFunctionVariable, + "torch.compiler.is_dynamo_compiling": TorchInGraphFunctionVariable, + "torch.compiler.is_exporting": TorchInGraphFunctionVariable, + "torch._C._is_cow_tensor": TorchInGraphFunctionVariable, + "torch._dynamo.eval_frame._is_in_optimized_module": TorchInGraphFunctionVariable, + "torch._C._to_dlpack": SkipFunctionVariable, + "torch._C._group_tensors_by_device_and_dtype": TorchInGraphFunctionVariable, + "torch.to_dlpack": SkipFunctionVariable, + "torch._check": TorchInGraphFunctionVariable, + "torch._check_with": TorchInGraphFunctionVariable, + "torch._check_index": TorchInGraphFunctionVariable, + "torch._check_value": TorchInGraphFunctionVariable, + "torch._check_type": TorchInGraphFunctionVariable, + "torch._check_not_implemented": TorchInGraphFunctionVariable, + "torch._check_tensor_all_with": TorchInGraphFunctionVariable, + "torch._check_tensor_all": TorchInGraphFunctionVariable, + "torch._dynamo.decorators.override_optimization_hint": TorchInGraphFunctionVariable, + # We graph break on RNG state setters or getters like + # `torch.get_rng_state`, `torch.set_rng_state`, and + # `torch.Generator.manual_seed`. These functions are not aten + # operations and therefore they are completely ignored by the AOT + # dispatcher. As a result, the AOT graph does not have these setter + # or getter functions, producing an incorrect graph when it comes + # to rng states. + "torch.get_rng_state": SkipFunctionVariable, + "torch.cuda.get_rng_state": SkipFunctionVariable, + "torch.set_rng_state": SkipFunctionVariable, + "torch.cuda.set_rng_state": SkipFunctionVariable, + "torch.cuda.manual_seed": SkipFunctionVariable, + "torch.cuda.manual_seed_all": SkipFunctionVariable, + "torch.xpu.manual_seed": SkipFunctionVariable, + "torch.xpu.manual_seed_all": SkipFunctionVariable, + "torch.cuda.random.manual_seed": SkipFunctionVariable, + "torch.cuda.random.manual_seed_all": SkipFunctionVariable, + "torch.xpu.random.manual_seed": SkipFunctionVariable, + "torch.xpu.random.manual_seed_all": SkipFunctionVariable, + # https://github.com/pytorch/pytorch/issues/107187 + "torch.manual_seed": SkipFunctionVariable, + # https://github.com/pytorch/pytorch/issues/93501 + "torch.nn.utils.rnn.pack_padded_sequence": SkipFunctionVariable, + # https://github.com/pytorch/pytorch/issues/162374 + "torch.nn.utils.rnn.pad_packed_sequence": SkipFunctionVariable, + "torch.nn.Parameter": TorchInGraphFunctionVariable, + "torch.nn.Buffer": TorchInGraphFunctionVariable, + "torch.backends.cuda.SDPAParams": TorchInGraphFunctionVariable, + "torch._nested_tensor_from_mask": SkipFunctionVariable, + "torch.nested._internal.nested_tensor.nested_from_padded": TorchInGraphFunctionVariable, + "torch.nested.nested_tensor_from_jagged": UserFunctionVariable, + "torch.nested.nested_tensor_from_padded": UserFunctionVariable, + # torch.fx map utils + "torch.fx.node.map_aggregate": UserFunctionVariable, + "torch.fx.node.map_arg": UserFunctionVariable, + "torch.fx.immutable_collections._no_mutation": UserFunctionVariable, + "torch.fx.immutable_collections._immutable_list_flatten": UserFunctionVariable, + "torch.fx.immutable_collections._immutable_list_unflatten": UserFunctionVariable, + "torch.fx.immutable_collections._immutable_dict_flatten": UserFunctionVariable, + "torch.fx.immutable_collections._immutable_dict_unflatten": UserFunctionVariable, + # symbol operators implemented in Python + "torch.sym_not": TorchInGraphFunctionVariable, + "torch.sym_float": TorchInGraphFunctionVariable, + "torch.sym_int": TorchInGraphFunctionVariable, + "torch.sym_max": TorchInGraphFunctionVariable, + "torch.sym_min": TorchInGraphFunctionVariable, + "torch.sym_sqrt": TorchInGraphFunctionVariable, + "torch.sym_ite": TorchInGraphFunctionVariable, + "torch.sym_sum": TorchInGraphFunctionVariable, + "torch.sym_fresh_size": UserFunctionVariable, + "torch.Tensor#_make_wrapper_subclass": SkipFunctionVariable, + "torch.Tensor#__init__": SkipFunctionVariable, + "torch.Tensor#split": TorchInGraphFunctionVariable, + "torch.cuda.set_device": SkipFunctionVariable, + "torch.cuda.current_device": TorchInGraphFunctionVariable, + "torch.autograd.grad": TorchInGraphFunctionVariable, + "torch.autograd.grad_mode._enter_inference_mode": TorchInGraphFunctionVariable, + "torch.autograd.grad_mode._exit_inference_mode": TorchInGraphFunctionVariable, + "torch.autograd.backward": SkipFunctionVariable, + "torch.distributions.constraints.is_dependent": SkipFunctionVariable, + "torch.jit.isinstance": SkipFunctionVariable, + "torch._C.set_anomaly_enabled": SkipFunctionVariable, + "torch._C.set_autocast_cpu_dtype": SkipFunctionVariable, + "torch._C.set_autocast_cpu_enabled": SkipFunctionVariable, + "torch._C.set_autocast_gpu_dtype": SkipFunctionVariable, + "torch._C.set_autocast_ipu_dtype": SkipFunctionVariable, + "torch._C.set_autocast_ipu_enabled": SkipFunctionVariable, + "torch._C.set_autocast_xla_dtype": SkipFunctionVariable, + "torch._C.set_autocast_xla_enabled": SkipFunctionVariable, + "torch.resize_as_": SkipFunctionVariable, + "torch._functorch.predispatch._add_batch_dim": TorchInGraphFunctionVariable, + "torch._functorch.predispatch._remove_batch_dim": TorchInGraphFunctionVariable, + "torch.resize_as_sparse_": SkipFunctionVariable, + "torch.get_default_device": TorchInGraphFunctionVariable, + # functorch/vmap + "torch._functorch.vmap._check_int_or_none": UserFunctionVariable, + "torch._functorch.vmap._check_out_dims_is_int_or_int_pytree": UserFunctionVariable, + "torch._functorch.vmap._check_randomness_arg": UserFunctionVariable, + "torch._functorch.vmap._chunked_vmap": UserFunctionVariable, + "torch._functorch.vmap._concat_chunked_outputs": UserFunctionVariable, + "torch._functorch.vmap._create_batched_inputs": UserFunctionVariable, + "torch._functorch.vmap._flat_vmap": UserFunctionVariable, + "torch._functorch.vmap._flatten_chunks_output": UserFunctionVariable, + "torch._functorch.vmap._get_chunked_inputs": UserFunctionVariable, + "torch._functorch.vmap._get_name": UserFunctionVariable, + "torch._functorch.vmap._maybe_remove_batch_dim": UserFunctionVariable, + "torch._functorch.vmap._num_outputs": UserFunctionVariable, + "torch._functorch.vmap._process_batched_inputs": UserFunctionVariable, + "torch._functorch.vmap._unwrap_batched": UserFunctionVariable, + "torch._functorch.vmap._validate_and_get_batch_size": UserFunctionVariable, + "torch._functorch.vmap.doesnt_support_saved_tensors_hooks": UserFunctionVariable, + "torch._functorch.vmap.get_chunk_sizes": UserFunctionVariable, + # lazy_load_decompositions uses a lock that is not supported yet in dynamo + # "torch._functorch.vmap.lazy_load_decompositions": UserFunctionVariable, + "torch._functorch.vmap.restore_vmap": UserFunctionVariable, + "torch._functorch.apis.vmap": UserFunctionVariable, + "torch._functorch.vmap.unwrap_batched": UserFunctionVariable, + "torch._functorch.vmap.vmap_impl": FunctorchHigherOrderVariable, + "torch._functorch.vmap.wrap_batched": UserFunctionVariable, + # functorch/grad + "torch._functorch.eager_transforms.grad_impl": FunctorchHigherOrderVariable, + "torch._functorch.apis.grad_and_value": UserFunctionVariable, + "torch._functorch.eager_transforms._as_tuple": UserFunctionVariable, + "torch._functorch.eager_transforms._check_unique_non_empty": UserFunctionVariable, + "torch._functorch.eager_transforms._create_differentiable": UserFunctionVariable, + "torch._functorch.eager_transforms._slice_argnums": UserFunctionVariable, + "torch._functorch.eager_transforms._undo_create_differentiable": UserFunctionVariable, + "torch._functorch.eager_transforms._validate_and_wrap_argnum": UserFunctionVariable, + "torch._functorch.eager_transforms._validate_and_wrap_argnums": UserFunctionVariable, + "torch._functorch.eager_transforms._wrap_all_tensors": UserFunctionVariable, + "torch._functorch.eager_transforms._wrap_tensor_for_grad": UserFunctionVariable, + # functorch/jacrev + "torch._functorch.eager_transforms.jacrev": FunctorchHigherOrderVariable, + "torch._functorch.eager_transforms.error_if_complex": UserFunctionVariable, + "torch._functorch.eager_transforms._chunked_standard_basis_for_": UserFunctionVariable, + "torch._functorch.eager_transforms._safe_zero_index": UserFunctionVariable, + # functorch/vjp + "torch._functorch.eager_transforms.vjp": FunctorchHigherOrderVariable, + "torch._functorch.eager_transforms._vjp_with_argnums": UserFunctionVariable, + "torch._functorch.eager_transforms.assert_non_empty_tensor_output": UserFunctionVariable, + # functorch/jvp + "torch._functorch.eager_transforms._jvp_with_argnums": UserFunctionVariable, + "torch._functorch.eager_transforms.jvp": FunctorchHigherOrderVariable, + "torch._functorch.eager_transforms._replace_args": UserFunctionVariable, + "torch._functorch.eager_transforms.safe_unpack_dual": UserFunctionVariable, + "torch._functorch.eager_transforms.assert_non_empty_list_of_tensors": UserFunctionVariable, + "torch._functorch.eager_transforms.assert_output_is_tensor_or_tensors": UserFunctionVariable, + "torch.autograd.forward_ad.enter_dual_level": UserFunctionVariable, + "torch.autograd.forward_ad.exit_dual_level": UserFunctionVariable, + "torch.autograd.forward_ad.make_dual": UserFunctionVariable, + "torch.autograd.forward_ad.unpack_dual": UserFunctionVariable, + "torch.autograd.graph.region_activation_memory_budget": UserFunctionVariable, + # functorch/linearize + "torch._functorch.eager_transforms.linearize": FunctorchHigherOrderVariable, + # functorch/jacfwd + "torch._functorch.eager_transforms.jacfwd": FunctorchHigherOrderVariable, + "torch._functorch.eager_transforms._construct_standard_basis_for": UserFunctionVariable, + "torch._functorch.eager_transforms.safe_unflatten": UserFunctionVariable, + # functorch/hessian + "torch._functorch.eager_transforms.hessian": FunctorchHigherOrderVariable, + # functional_call + "torch._functorch.functional_call.functional_call": FunctionalCallVariable, + "torch.nn.utils.stateless._groupby_tensor": TorchInGraphFunctionVariable, + "torch.nn.utils.stateless._reparametrize_module": ReparametrizeModuleCallVariable, + # functorch/deprecated + "torch._functorch.deprecated.jvp": UserFunctionVariable, + "torch._functorch.deprecated.hessian": UserFunctionVariable, + "torch._functorch.deprecated.jacfwd": UserFunctionVariable, + "torch._functorch.deprecated.jacrev": UserFunctionVariable, + "torch._functorch.deprecated.grad": UserFunctionVariable, + "torch._functorch.deprecated.grad_and_value": UserFunctionVariable, + "torch._functorch.deprecated.vjp": UserFunctionVariable, + # functorch/C++ bindings + "torch._C._functorch._wrap_for_grad": TorchInGraphFunctionVariable, + "torch._C._functorch._unwrap_for_grad": TorchInGraphFunctionVariable, + "torch._C._functorch._unwrap_batched": TorchInGraphFunctionVariable, + "torch._C._functorch.current_level": TorchInGraphFunctionVariable, + "torch._C._functorch.maybe_current_level": TorchInGraphFunctionVariable, + "torch._C._functorch.is_batchedtensor": TorchInGraphFunctionVariable, + "torch._C._functorch.peek_interpreter_stack": TorchInGraphFunctionVariable, + "torch._C._functorch.unwrap_if_dead": TorchInGraphFunctionVariable, + "torch._functorch.predispatch._vmap_increment_nesting": TorchInGraphFunctionVariable, + "torch._functorch.predispatch._vmap_decrement_nesting": TorchInGraphFunctionVariable, + "torch._functorch.predispatch._jvp_increment_nesting": TorchInGraphFunctionVariable, + "torch._functorch.predispatch._jvp_decrement_nesting": TorchInGraphFunctionVariable, + "torch._functorch.predispatch._unwrap_for_grad": TorchInGraphFunctionVariable, + "torch._functorch.predispatch._make_dual": TorchInGraphFunctionVariable, + "torch._functorch.predispatch._unpack_dual": TorchInGraphFunctionVariable, + "torch._functorch.predispatch._enter_dual_level": TorchInGraphFunctionVariable, + "torch._functorch.predispatch._exit_dual_level": TorchInGraphFunctionVariable, + # everything else + "torch._functorch.pyfunctorch.coerce_cinterpreter": TorchInGraphFunctionVariable, + "torch._higher_order_ops.triton_kernel_wrap.do_prune_configs": UserFunctionVariable, + "torch._higher_order_ops.foreach_map.foreach_map": UserFunctionVariable, + "torch._constrain_as_size": UserFunctionVariable, + "torch._tensor._convert": UserFunctionVariable, + "torch.jit._unwrap_optional": UserFunctionVariable, + "torch.backends.mha.get_fastpath_enabled": UserFunctionVariable, + "torch._dynamo.dont_skip_tracing": UserFunctionVariable, + "torch._dynamo.mark_static": UserFunctionVariable, + "torch._dynamo.nonstrict_trace": UserFunctionVariable, + "torch._dynamo.bytecode_debugger.breakpoint": UserFunctionVariable, + "torch._dynamo.patch_dynamo_config": UserFunctionVariable, + "torch._dynamo.disable_nested_graph_breaks": UserFunctionVariable, + "torch._dynamo.error_on_graph_break": UserFunctionVariable, + "torch._dynamo.override_cudagraphs": UserFunctionVariable, + "torch.fx.experimental.symbolic_shapes.guard_size_oblivious": TorchInGraphFunctionVariable, + "torch.fx.experimental.symbolic_shapes.is_nested_int": UserFunctionVariable, + "torch.fx.experimental.symbolic_shapes.guarding_hint_or_throw": TorchInGraphFunctionVariable, + "torch.fx.experimental.symbolic_shapes.optimization_hint": TorchInGraphFunctionVariable, + "torch.fx.experimental.symbolic_shapes.guard_or_true": TorchInGraphFunctionVariable, + "torch.fx.experimental.symbolic_shapes.guard_or_false": TorchInGraphFunctionVariable, + "torch.fx.experimental.symbolic_shapes.statically_known_true": TorchInGraphFunctionVariable, + "torch.fx.experimental.symbolic_shapes.statically_known_false": TorchInGraphFunctionVariable, + "torch.fx.experimental.symbolic_shapes.sym_and": TorchInGraphFunctionVariable, + "torch.fx.experimental.symbolic_shapes.sym_or": TorchInGraphFunctionVariable, + "torch.fx.experimental.symbolic_shapes.guard_scalar": TorchInGraphFunctionVariable, + "torch.fx.experimental.symbolic_shapes.has_static_value": TorchInGraphFunctionVariable, + "torch.fx.experimental.symbolic_shapes.has_free_unbacked_symbols": TorchInGraphFunctionVariable, + "torch.cuda._get_device_properties": TorchInGraphFunctionVariable, + "torch.utils.hooks.BackwardHook": TorchInGraphFunctionVariable, + "torch.set_default_device": UserFunctionVariable, + "torch.sparse_bsc_tensor": SparseTensorCreationSkipVariable, + "torch.sparse_bsr_tensor": SparseTensorCreationSkipVariable, + "torch.sparse_csc_tensor": SparseTensorCreationSkipVariable, + "torch.sparse_csr_tensor": SparseTensorCreationSkipVariable, + "torch.sparse_compressed_tensor": SparseTensorCreationSkipVariable, + "torch._C._autograd._unsafe_set_version_counter": TorchInGraphFunctionVariable, + "torch.xpu.get_rng_state": SkipFunctionVariable, + "torch.xpu.set_rng_state": SkipFunctionVariable, + "torch.library.wrap_triton": TorchInGraphFunctionVariable, + "torch._library.capture_triton": TorchInGraphFunctionVariable, + # avoid skipping user defined modules in distributed unit tests + "torch/testing/_internal/common_fsdp.py#forward": UserFunctionVariable, + f"torch/testing/_internal/common_fsdp.py#{TORCH_DYNAMO_RESUME_IN_PREFIX}": UserFunctionVariable, + "torch/testing/_internal/distributed/_tensor/common_dtensor.py#forward": UserFunctionVariable, + f"torch/testing/_internal/distributed/_tensor/common_dtensor.py#{TORCH_DYNAMO_RESUME_IN_PREFIX}": UserFunctionVariable, + "torch/testing/_internal/common_distributed.py#forward": UserFunctionVariable, + f"torch/testing/_internal/common_distributed.py#{TORCH_DYNAMO_RESUME_IN_PREFIX}": UserFunctionVariable, + "torch.utils._pytree._get_node_type": PyTreeGetNodeTypeFunctionVariable, + "torch.utils._pytree.tree_is_leaf": PyTreeTreeIsLeafFunctionVariable, + # torch.utils._python_dispatch is in MOD_INLINELIST; override so the handler + # in variables/torch.py fires instead of graph-breaking on _len_torch_dispatch_stack. + "torch.utils._python_dispatch._get_current_dispatch_mode_stack": TorchInGraphFunctionVariable, + "torch._utils_internal.justknobs_check": UserFunctionVariable, + "inspect.signature": InspectSignatureVariable, +} + +# Keep this in sync with the stateful generator methods exposed from +# torch/csrc/Generator.cpp. +_GENERATOR_METHODS_THAT_GRAPH_BREAK = ( + "clone_state", + "get_offset", + "get_state", + "graphsafe_get_state", + "graphsafe_set_state", + "initial_seed", + "manual_seed", + "seed", + "set_offset", + "set_state", +) + +for generator_prefix in ("torch.default_generator", "torch._C.Generator"): + for method_name in _GENERATOR_METHODS_THAT_GRAPH_BREAK: + manual_torch_name_rule_map[f"{generator_prefix}#{method_name}"] = ( + SkipFunctionVariable + ) + + +# In graph functions (including constant folding) that are C bindings +torch_c_binding_in_graph_functions = dict.fromkeys( + [ + "math.acos", + "math.acosh", + "math.asin", + "math.asinh", + "math.atan", + "math.atan2", + "math.atanh", + "math.ceil", + "math.comb", + "math.copysign", + "math.cos", + "math.cosh", + "math.degrees", + "math.dist", + "math.erf", + "math.erfc", + "math.exp", + "math.expm1", + "math.fabs", + "math.factorial", + "math.floor", + "math.fmod", + "math.frexp", + "math.fsum", + "math.gamma", + "math.gcd", + "math.hypot", + "math.isclose", + "math.isfinite", + "math.isinf", + "math.isnan", + "math.isqrt", + "math.lcm", + "math.ldexp", + "math.lgamma", + "math.log", + "math.log10", + "math.log1p", + "math.log2", + "math.modf", + "math.nextafter", + "math.perm", + "math.pow", + "math.prod", + "math.radians", + "math.remainder", + "math.sin", + "math.sinh", + "math.tan", + "math.tanh", + "math.trunc", + "math.ulp", + "torch._adaptive_avg_pool2d", + "torch._adaptive_avg_pool3d", + "torch._add_batch_dim", + "torch._add_relu_", + "torch._add_relu", + "torch._addmm_activation", + "torch._aminmax", + "torch._amp_foreach_non_finite_check_and_unscale_", + "torch._amp_update_scale_", + "torch._assert_async", + "torch._assert_tensor_metadata", + "torch._batch_norm_impl_index", + "torch._C._accelerator_getAccelerator", + "torch._C._accelerator_getDeviceIndex", + "torch._C._accelerator_getStream", + "torch._C._accelerator_getAllocatorSettings", + "torch._C._accelerator_setAllocatorSettings", + "torch._C._accelerator_setStream", + "torch._C._accelerator_synchronizeDevice", + "torch._C._activate_gpu_trace", + "torch._C._add_cached_tensor", + "torch._C._add_docstr", + "torch._C._are_functorch_transforms_active", + "torch._C._autograd_init", + "torch._C._autograd._saved_tensors_hooks_disable", + "torch._C._autograd._saved_tensors_hooks_enable", + "torch._C._awaitable_nowait", + "torch._C._awaitable_wait", + "torch._C._awaitable", + "torch._C._backport_for_mobile_from_buffer_to_buffer", + "torch._C._backport_for_mobile_from_buffer", + "torch._C._backport_for_mobile_to_buffer", + "torch._C._backport_for_mobile", + "torch._C._broadcast_coalesced", + "torch._C._broadcast_out", + "torch._C._broadcast", + "torch._C._c10d_init", + "torch._C._calculate_package_version_based_on_upgraders", + "torch._C._can_use_flash_attention", + "torch._C._can_use_mem_efficient_attention", + "torch._C._can_use_cudnn_attention", + "torch._C._check_onnx_proto", + "torch._C._check_sparse_tensor_invariants", + "torch._C._collect_all", + "torch._C._commit_update", + "torch._C._compile_graph_to_code_table", + "torch._C._construct_CUDA_Tensor_From_Storage_And_Metadata", + "torch._C._construct_storage_from_data_pointer", + "torch._C._conv_determine_backend_memory_format", + "torch._C._cpu._init_amx", + "torch._C._cpu._get_cpu_capability", + "torch._C._crash_if_aten_asan", + "torch._C._crash_if_csrc_asan", + "torch._C._crash_if_csrc_ubsan", + "torch._C._crash_if_debug_asserts_fail", + "torch._C._crash_if_vptr_ubsan", + "torch._C._create_function_from_graph", + "torch._C._create_function_from_trace_with_dict", + "torch._C._create_function_from_trace", + "torch._C._create_graph_by_tracing", + "torch._C._create_module_with_type", + "torch._C._create_object_with_type", + "torch._C._cuda_attach_out_of_memory_observer", + "torch._C._cuda_beginAllocateCurrentStreamToPool", + "torch._C._cuda_canDeviceAccessPeer", + "torch._C._cuda_changeCurrentAllocator", + "torch._C._cuda_checkPoolLiveAllocations", + "torch._C._cuda_clearCublasWorkspaces", + "torch._C._cuda_cudaCachingAllocator_raw_alloc", + "torch._C._cuda_cudaCachingAllocator_raw_delete", + "torch._C._cuda_cudaHostAllocator", + "torch._C._cuda_customAllocator", + "torch._C._cuda_emptyCache", + "torch._C._cuda_endAllocateToPool", + "torch._C._cuda_exchangeDevice", + "torch._C._cuda_get_conv_benchmark_empty_cache", + "torch._C._cuda_get_cudnn_benchmark_limit", + "torch._C._cuda_get_sync_debug_mode", + "torch._C._cuda_getAllocator", + "torch._C._cuda_getAllocatorBackend", + "torch._C._cuda_getArchFlags", + "torch._C._cuda_getCheckpointState", + "torch._C._cuda_getCompiledVersion", + "torch._C._cuda_getCurrentBlasHandle", + "torch._C._cuda_getCurrentSolverHandle", + "torch._C._cuda_getCurrentRawStream", + "torch._C._cuda_getCurrentStream", + "torch._C._cuda_getDefaultStream", + "torch._C._cuda_getDevice", + "torch._C._cuda_getDeviceCount", + "torch._C._cuda_hasPrimaryContext", + "torch._C._cuda_hostMemoryStats", + "torch._C._cuda_init", + "torch._C._cuda_ipc_collect", + "torch._C._cuda_isCurrentStreamCapturing", + "torch._C._cuda_isHistoryEnabled", + "torch._C._cuda_isInBadFork", + "torch._C._cuda_jiterator_compile_and_launch_kernel", + "torch._C._cuda_maybeExchangeDevice", + "torch._C._cuda_memorySnapshot", + "torch._C._cuda_memoryStats", + "torch._C._cuda_record_memory_history_legacy", + "torch._C._cuda_record_memory_history", + "torch._C._cuda_releasePool", + "torch._C._cuda_resetAccumulatedHostMemoryStats", + "torch._C._cuda_resetAccumulatedMemoryStats", + "torch._C._cuda_resetPeakHostMemoryStats", + "torch._C._cuda_resetPeakMemoryStats", + "torch._C._cuda_set_cudnn_benchmark_limit", + "torch._C._cuda_set_sync_debug_mode", + "torch._C._cuda_setCheckpointPoolState", + "torch._C._cuda_setDevice", + "torch._C._cuda_setMemoryFraction", + "torch._C._cuda_setStream", + "torch._C._cuda_sleep", + "torch._C._cuda_synchronize", + "torch._C._cudnn_set_conv_benchmark_empty_cache", + "torch._C._cudnn.getCompileVersion", + "torch._C._cudnn.getRuntimeVersion", + "torch._C._cudnn.getVersionInt", + "torch._C._current_autograd_node", + "torch._C._current_graph_task_execution_order", + "torch._C._current_graph_task_id", + "torch._C._cxx_flags", + "torch._C._debug_get_fusion_group_inlining", + "torch._C._debug_only_are_vmap_fallback_warnings_enabled", + "torch._C._debug_only_display_vmap_fallback_warnings", + "torch._C._debug_set_autodiff_subgraph_inlining", + "torch._C._debug_set_fusion_group_inlining", + "torch._C._demangle", + "torch._C._disabled_torch_dispatch_impl", + "torch._C._dispatch_call_boxed", + "torch._C._dispatch_check_all_invariants", + "torch._C._dispatch_check_invariants", + "torch._C._dispatch_dump_table", + "torch._C._dispatch_dump", + "torch._C._dispatch_find_dangling_impls", + "torch._C._dispatch_find_schema_or_throw", + "torch._C._dispatch_get_all_op_names", + "torch._C._dispatch_get_backend_keyset_from_autograd", + "torch._C._dispatch_get_registrations_for_dispatch_key", + "torch._C._dispatch_has_backend_fallback", + "torch._C._dispatch_has_computed_kernel_for_dispatch_key", + "torch._C._dispatch_has_kernel_for_any_dispatch_key", + "torch._C._dispatch_has_kernel_for_dispatch_key", + "torch._C._dispatch_has_kernel", + "torch._C._dispatch_is_alias_key", + "torch._C._dispatch_is_included_in_alias", + "torch._C._dispatch_isTensorSubclassLike", + "torch._C._dispatch_key_for_device", + "torch._C._dispatch_key_name", + "torch._C._dispatch_key_parse", + "torch._C._dispatch_key_set", + "torch._C._dispatch_keys", + "torch._C._dispatch_keyset_full_after", + "torch._C._dispatch_keyset_full", + "torch._C._dispatch_keyset_to_string", + "torch._C._dispatch_library", + "torch._C._dispatch_num_backends", + "torch._C._dispatch_print_registrations_for_dispatch_key", + "torch._C._dispatch_pystub", + "torch._C._dispatch_set_report_error_callback", + "torch._C._dispatch_tls_is_dispatch_key_excluded", + "torch._C._dispatch_tls_is_dispatch_key_included", + "torch._C._dispatch_tls_local_exclude_set", + "torch._C._dispatch_tls_local_include_set", + "torch._C._dispatch_tls_set_dispatch_key_excluded", + "torch._C._dispatch_tls_set_dispatch_key_included", + "torch._C._dist_autograd_init", + "torch._C._dump_local_tls_set", + "torch._C._dump_upgraders_map", + "torch._C._enable_mobile_interface_call_export", + "torch._C._enter_dual_level", + "torch._C._error_if_any_worker_fails", + "torch._C._exit_dual_level", + "torch._C._export_operator_list", + "torch._C._export_opnames", + "torch._C._faulty_agent_init", + "torch._C._fft.fft_fft", + "torch._C._fft.fft_fft2", + "torch._C._fft.fft_fftfreq", + "torch._C._fft.fft_fftn", + "torch._C._fft.fft_fftshift", + "torch._C._fft.fft_hfft", + "torch._C._fft.fft_hfft2", + "torch._C._fft.fft_hfftn", + "torch._C._fft.fft_ifft", + "torch._C._fft.fft_ifft2", + "torch._C._fft.fft_ifftn", + "torch._C._fft.fft_ifftshift", + "torch._C._fft.fft_ihfft", + "torch._C._fft.fft_ihfft2", + "torch._C._fft.fft_ihfftn", + "torch._C._fft.fft_irfft", + "torch._C._fft.fft_irfft2", + "torch._C._fft.fft_irfftn", + "torch._C._fft.fft_rfft", + "torch._C._fft.fft_rfft2", + "torch._C._fft.fft_rfftfreq", + "torch._C._fft.fft_rfftn", + "torch._C._free_And_Remove_DeleterFn", + "torch._C._freeze_module", + "torch._C._from_dlpack", + "torch._C._functionality_to_backend_keys", + "torch._C._functionalization_reapply_views_tls", + "torch._C._functorch._grad_decrement_nesting", + "torch._C._functorch._grad_increment_nesting", + "torch._C._functorch.get_dynamic_layer_stack_depth", + "torch._C._functorch.set_inplace_requires_grad_allowed", + "torch._functorch.utils.unwrap_dead_wrappers", + "torch._C._fuse_to_static_module", + "torch._C._gather_out", + "torch._C._gather", + "torch._C._generate_upgraders_graph", + "torch._C._get_autograd_fallback_mode", + "torch._C._get_backcompat_broadcast_warn", + "torch._C._get_backcompat_keepdim_warn", + "torch._C._get_blas_preferred_backend", + "torch._C._get_caught_jit_exception_class_name", + "torch._C._get_caught_jit_exception_original_msg", + "torch._C._get_constant_bool_symnode", + "torch._C._get_cpp_backtrace", + "torch._C._get_cpu_capability", + "torch._C._get_cublas_allow_bf16_reduced_precision_reduction", + "torch._C._get_cublas_allow_fp16_reduced_precision_reduction", + "torch._C._get_cublas_allow_tf32", + "torch._C._get_cudnn_allow_tf32", + "torch._C._get_cudnn_benchmark", + "torch._C._get_miopen_immediate", + "torch._C._get_cudnn_deterministic", + "torch._C._get_cudnn_enabled", + "torch._C._get_custom_class_python_wrapper", + "torch._C._get_default_device", + "torch._C._get_deterministic_algorithms_warn_only", + "torch._C._get_deterministic_algorithms", + "torch._C._get_deterministic_fill_uninitialized_memory", + "torch._C._get_dispatch_mode", + "torch._C._get_dispatch_stack_at", + "torch._C._get_file_format", + "torch._C._get_flash_sdp_enabled", + "torch._C._get_float32_matmul_precision", + "torch._C._get_function_stack_at", + "torch._C._get_graph_executor_optimize", + "torch._C._get_linalg_preferred_backend", + "torch._C._get_rocm_fa_preferred_backend", + "torch._C._get_math_sdp_enabled", + "torch._C._get_math_sdp_allow_fp16_bf16_reduction", + "torch._C._get_max_operator_version", + "torch._C._get_mem_efficient_sdp_enabled", + "torch._C._get_mkldnn_enabled", + "torch._C._get_cudnn_sdp_enabled", + "torch._C._get_overrideable_sdp_enabled", + "torch._C._set_sdp_use_cudnn", + "torch._C._get_mobile_model_contained_types_from_buffer", + "torch._C._get_mobile_model_contained_types", + "torch._C._get_model_bytecode_version_from_buffer", + "torch._C._get_model_bytecode_version", + "torch._C._get_model_extra_files_from_buffer", + "torch._C._get_model_extra_files", + "torch._C._get_model_ops_and_info_from_buffer", + "torch._C._get_model_ops_and_info", + "torch._C._get_module_info_from_flatbuffer", + "torch._C._get_nnpack_enabled", + "torch._C._get_obj_in_tls", + "torch._C._get_operation_overload", + "torch._C._get_operator_version_map", + "torch._C._get_privateuse1_backend_name", + "torch._C._get_qengine", + "torch._C._get_schema", + "torch._C._get_sm_carveout_experimental", + "torch._C._get_nested_int", + "torch._C._get_tensor_metadata", + "torch._C._get_tracing_state", + "torch._C._get_upgrader_ranges", + "torch._C._get_upgraders_entry_map", + "torch._C._get_upgraders_map_size", + "torch._C._get_value_trace", + "torch._C._get_version_calculator_flag", + "torch._C._get_warnAlways", + "torch._C._graph_pool_handle", + "torch._C._hack_do_not_use_clone_module_with_class", + "torch._C._has_distributed", + "torch._C._has_Standard_Deleter", + "torch._C._has_storage", + "torch._C._has_tensorexpr_cpp_tests", + "torch._C._run_tensorexpr_cpp_tests", + "torch._C._has_torch_function_unary", + "torch._C._has_torch_function_variadic", + "torch._C._has_torch_function", + "torch._C._import_ir_module_from_package", + "torch._C._increment_version", + "torch._C._infer_size", + "torch._C._init_names", + "torch._C._initExtension", + "torch._C._is_alias_of", + "torch._C._is_any_autocast_enabled", + "torch._C._is_autocast_available", + "torch._C._is_cached_tensor", + "torch._C._is_flash_attention_available", + "torch._C._is_fwd_grad_enabled", + "torch._C._is_key_in_tls", + "torch._C._is_multithreading_enabled", + "torch._C._is_torch_function_enabled", + "torch._C._is_torch_function_mode_enabled", + "torch._C._is_torch_function_all_disabled", + "torch._C._is_tracing", + "torch._C._is_view_replay_enabled", + "torch._C._is_xnnpack_enabled", + "torch._C._itt.is_available", + "torch._C._itt.mark", + "torch._C._itt.rangePop", + "torch._C._itt.rangePush", + "torch._C._ivalue_debug_python_object", + "torch._C._ivalue_tags_match", + "torch._C._jit_assert_is_instance", + "torch._C._jit_can_fuse_on_cpu_legacy", + "torch._C._jit_can_fuse_on_cpu", + "torch._C._jit_can_fuse_on_gpu", + "torch._C._jit_cat_wo_conditionals", + "torch._C._jit_check_alias_annotation", + "torch._C._jit_clear_class_registry", + "torch._C._jit_debug_fuser_num_cached_kernel_specs", + "torch._C._jit_debug_module_iterators", + "torch._C._jit_decay_packed_param_input_types", + "torch._C._jit_decomposition_graph_for_node", + "torch._C._jit_differentiate", + "torch._C._jit_erase_non_input_shape_information", + "torch._C._jit_flatten", + "torch._C._jit_fuser_get_fused_kernel_code", + "torch._C._jit_get_all_schemas", + "torch._C._jit_get_custom_class_schemas", + "torch._C._jit_get_emit_hooks", + "torch._C._jit_get_inline_everything_mode", + "torch._C._jit_get_logging_option", + "torch._C._jit_get_num_profiled_runs", + "torch._C._jit_get_operation", + "torch._C._jit_get_schemas_for_operator", + "torch._C._jit_get_te_cuda_pointwise_block_count", + "torch._C._jit_get_te_cuda_pointwise_block_size", + "torch._C._jit_get_te_cuda_pointwise_loop_levels", + "torch._C._jit_get_te_generate_block_code", + "torch._C._jit_get_te_must_use_llvm_cpu", + "torch._C._jit_get_tracer_state_warn", + "torch._C._jit_has_cpp_tests", + "torch._C._jit_init", + "torch._C._jit_interpret_graph", + "torch._C._jit_is_onnx_log_enabled", + "torch._C._jit_is_script_object", + "torch._C._jit_llga_enabled", + "torch._C._jit_nvfuser_can_be_enabled", + "torch._C._jit_nvfuser_clear_comparison_callback", + "torch._C._jit_nvfuser_enabled", + "torch._C._jit_nvfuser_horizontal_mode", + "torch._C._jit_nvfuser_set_comparison_callback", + "torch._C._jit_nvfuser_single_node_mode", + "torch._C._jit_object_is_non_holding", + "torch._C._jit_onnx_convert_pattern_from_subblock", + "torch._C._jit_onnx_create_full_scope_name", + "torch._C._jit_onnx_list_model_parameters", + "torch._C._jit_onnx_log", + "torch._C._jit_opt_conditionals", + "torch._C._jit_override_can_fuse_on_cpu_legacy", + "torch._C._jit_override_can_fuse_on_cpu", + "torch._C._jit_override_can_fuse_on_gpu", + "torch._C._jit_pass_autocast", + "torch._C._jit_pass_batch_mm", + "torch._C._jit_pass_canonicalize_graph_fuser_ops", + "torch._C._jit_pass_canonicalize", + "torch._C._jit_pass_complete_shape_analysis", + "torch._C._jit_pass_concat_frozen_linear", + "torch._C._jit_pass_constant_loop_unrolling", + "torch._C._jit_pass_constant_pooling", + "torch._C._jit_pass_constant_propagation_immutable_types", + "torch._C._jit_pass_constant_propagation", + "torch._C._jit_pass_convert_frozen_ops_to_mkldnn", + "torch._C._jit_pass_create_autodiff_subgraphs", + "torch._C._jit_pass_create_functional_graphs", + "torch._C._jit_pass_cse", + "torch._C._jit_pass_custom_pattern_based_rewrite_graph", + "torch._C._jit_pass_custom_pattern_based_rewrite", + "torch._C._jit_pass_dbr_quant_remove_redundant_aliases", + "torch._C._jit_pass_dce_allow_deleting_nodes_with_side_effects", + "torch._C._jit_pass_dce", + "torch._C._jit_pass_decompose_ops", + "torch._C._jit_pass_dedup_module_uses", + "torch._C._jit_pass_erase_number_types", + "torch._C._jit_pass_erase_shape_information", + "torch._C._jit_pass_filter_non_tensor_arguments", + "torch._C._jit_pass_fixup_onnx_controlflow_node", + "torch._C._jit_pass_fold_convbn", + "torch._C._jit_pass_fold_frozen_conv_add_or_sub", + "torch._C._jit_pass_fold_frozen_conv_bn", + "torch._C._jit_pass_fold_frozen_conv_mul_or_div", + "torch._C._jit_pass_fold_frozen_linear_bn", + "torch._C._jit_pass_fold_prepacking_ops", + "torch._C._jit_pass_functional_to_inplace_activation", + "torch._C._jit_pass_fuse_add_relu", + "torch._C._jit_pass_fuse_addmm", + "torch._C._jit_pass_fuse_clamp_w_prepacked_linear_conv", + "torch._C._jit_pass_fuse_frozen_conv_add_relu", + "torch._C._jit_pass_fuse_linear", + "torch._C._jit_pass_fuse_quantized_add_relu", + "torch._C._jit_pass_fuse_tensorexprs", + "torch._C._jit_pass_fuse", + "torch._C._jit_pass_inline_fork_wait", + "torch._C._jit_pass_inline_functional_graphs", + "torch._C._jit_pass_inline", + "torch._C._jit_pass_inplace_to_functional_activation", + "torch._C._jit_pass_insert_observer_method_for_ondevice_ptq", + "torch._C._jit_pass_insert_observers", + "torch._C._jit_pass_insert_prepack_unpack", + "torch._C._jit_pass_insert_prepacked_ops", + "torch._C._jit_pass_insert_quant_dequant_for_ondevice_ptq", + "torch._C._jit_pass_insert_quant_dequant", + "torch._C._jit_pass_integer_value_refinement", + "torch._C._jit_pass_lint", + "torch._C._jit_pass_loop_unrolling", + "torch._C._jit_pass_lower_all_tuples", + "torch._C._jit_pass_lower_graph", + "torch._C._jit_pass_metal_fold_prepacking_ops", + "torch._C._jit_pass_metal_fuse_clamp_w_prepacked_conv", + "torch._C._jit_pass_metal_insert_prepacked_ops", + "torch._C._jit_pass_metal_optimize_for_mobile", + "torch._C._jit_pass_onnx_assign_output_shape", + "torch._C._jit_pass_onnx_assign_scoped_names_for_node_and_value", + "torch._C._jit_pass_onnx_autograd_function_process", + "torch._C._jit_pass_onnx_block", + "torch._C._jit_pass_onnx_cast_all_constant_to_floating", + "torch._C._jit_pass_onnx_clear_scope_records", + "torch._C._jit_pass_onnx_constant_fold", + "torch._C._jit_pass_onnx_deduplicate_initializers", + "torch._C._jit_pass_onnx_eliminate_unused_items", + "torch._C._jit_pass_onnx_eval_peephole", + "torch._C._jit_pass_onnx_function_extraction", + "torch._C._jit_pass_onnx_function_substitution", + "torch._C._jit_pass_onnx_graph_shape_type_inference", + "torch._C._jit_pass_onnx_lint", + "torch._C._jit_pass_onnx_node_shape_type_inference", + "torch._C._jit_pass_onnx_peephole", + "torch._C._jit_pass_onnx_preprocess_caffe2", + "torch._C._jit_pass_onnx_preprocess", + "torch._C._jit_pass_onnx_quantization_insert_permutes", + "torch._C._jit_pass_onnx_remove_inplace_ops_for_onnx", + "torch._C._jit_pass_onnx_remove_print", + "torch._C._jit_pass_onnx_scalar_type_analysis", + "torch._C._jit_pass_onnx_set_dynamic_input_shape", + "torch._C._jit_pass_onnx_track_scope_attributes", + "torch._C._jit_pass_onnx_unpack_quantized_weights", + "torch._C._jit_pass_onnx", + "torch._C._jit_pass_optimize_for_inference", + "torch._C._jit_pass_optimize_for_mobile", + "torch._C._jit_pass_optimize_frozen_graph", + "torch._C._jit_pass_pattern_based_rewrite", + "torch._C._jit_pass_peephole_list_idioms", + "torch._C._jit_pass_peephole", + "torch._C._jit_pass_prepare_division_for_onnx", + "torch._C._jit_pass_propagate_device", + "torch._C._jit_pass_propagate_dtype", + "torch._C._jit_pass_propagate_shapes_on_graph_and_build_compute", + "torch._C._jit_pass_propagate_shapes_on_graph", + "torch._C._jit_pass_quant_finalize_for_ondevice_ptq", + "torch._C._jit_pass_quant_finalize", + "torch._C._jit_pass_quant_fusion", + "torch._C._jit_pass_refine_integer_values", + "torch._C._jit_pass_refine_tuple_types", + "torch._C._jit_pass_remove_dropout", + "torch._C._jit_pass_remove_expands", + "torch._C._jit_pass_remove_inplace_ops", + "torch._C._jit_pass_remove_mutation", + "torch._C._jit_pass_replace_old_ops_with_upgraders", + "torch._C._jit_pass_replicate_dequantize", + "torch._C._jit_pass_run_decompositions", + "torch._C._jit_pass_specialize_autogradzero", + "torch._C._jit_pass_swap_functional_linear", + "torch._C._jit_pass_transform_conv1d_to_conv2d", + "torch._C._jit_pass_transpose_frozen_linear", + "torch._C._jit_pass_vulkan_fold_prepacking_ops", + "torch._C._jit_pass_vulkan_fuse_clamp_w_prepacked_conv", + "torch._C._jit_pass_vulkan_insert_prepacked_ops", + "torch._C._jit_pass_vulkan_optimize_for_mobile", + "torch._C._jit_register_decomposition_for_schema", + "torch._C._jit_register_shape_compute_graph_for_node", + "torch._C._jit_resolve_packet", + "torch._C._jit_run_cpp_tests", + "torch._C._jit_script_class_compile", + "torch._C._jit_script_compile_overload", + "torch._C._jit_script_compile", + "torch._C._jit_script_interface_compile", + "torch._C._jit_set_autocast_mode", + "torch._C._jit_set_bailout_depth", + "torch._C._jit_set_emit_hooks", + "torch._C._jit_set_fusion_strategy", + "torch._C._jit_set_inline_everything_mode", + "torch._C._jit_set_llga_enabled", + "torch._C._jit_set_logging_option", + "torch._C._jit_set_logging_stream", + "torch._C._jit_set_num_profiled_runs", + "torch._C._jit_set_nvfuser_enabled", + "torch._C._jit_set_nvfuser_guard_mode", + "torch._C._jit_set_nvfuser_horizontal_mode", + "torch._C._jit_set_nvfuser_single_node_mode", + "torch._C._jit_set_nvfuser_skip_node_kind", + "torch._C._jit_set_onnx_log_enabled", + "torch._C._jit_set_onnx_log_output_stream", + "torch._C._jit_set_profiling_executor", + "torch._C._jit_set_profiling_mode", + "torch._C._jit_set_symbolic_shapes_test_mode", + "torch._C._jit_set_te_cuda_pointwise_block_count", + "torch._C._jit_set_te_cuda_pointwise_block_size", + "torch._C._jit_set_te_cuda_pointwise_loop_levels", + "torch._C._jit_set_te_generate_block_code", + "torch._C._jit_set_te_must_use_llvm_cpu", + "torch._C._jit_set_texpr_dynamic_shape_enabled", + "torch._C._jit_set_texpr_fuser_enabled", + "torch._C._jit_set_texpr_reductions_enabled", + "torch._C._jit_set_tracer_state_warn", + "torch._C._jit_set_utf8_decoding_ignore", + "torch._C._jit_shape_compute_graph_for_node", + "torch._C._jit_symbolic_shapes_test_mode_enabled", + "torch._C._jit_texpr_dynamic_shape_enabled", + "torch._C._jit_texpr_fallback_allowed", + "torch._C._jit_texpr_fuser_enabled", + "torch._C._jit_texpr_reductions_enabled", + "torch._C._jit_texpr_set_fallback_allowed", + "torch._C._jit_to_backend_selective", + "torch._C._jit_to_backend", + "torch._C._jit_to_static_module", + "torch._C._jit_trace_graph", + "torch._C._jit_trace_module", + "torch._C._jit_tree_views.FalseLiteral", + "torch._C._jit_tree_views.NoneLiteral", + "torch._C._jit_tree_views.TrueLiteral", + "torch._C._jit_try_infer_type", + "torch._C._jit_unflatten", + "torch._C._last_executed_optimized_graph", + "torch._C._len_torch_dispatch_stack", + "torch._C._len_torch_function_stack", + "torch._C._linalg._linalg_eigvals", + "torch._C._linalg.linalg_cholesky_ex", + "torch._C._linalg.linalg_cholesky", + "torch._C._linalg.linalg_cond", + "torch._C._linalg.linalg_cross", + "torch._C._linalg.linalg_det", + "torch._C._linalg.linalg_diagonal", + "torch._C._linalg.linalg_eig", + "torch._C._linalg.linalg_eigh", + "torch._C._linalg.linalg_eigvals", + "torch._C._linalg.linalg_eigvalsh", + "torch._C._linalg.linalg_householder_product", + "torch._C._linalg.linalg_inv_ex", + "torch._C._linalg.linalg_inv", + "torch._C._linalg.linalg_ldl_factor_ex", + "torch._C._linalg.linalg_ldl_factor", + "torch._C._linalg.linalg_ldl_solve", + "torch._C._linalg.linalg_lstsq", + "torch._C._linalg.linalg_lu_factor_ex", + "torch._C._linalg.linalg_lu_factor", + "torch._C._linalg.linalg_lu_solve", + "torch._C._linalg.linalg_lu", + "torch._C._linalg.linalg_matmul", + "torch._C._linalg.linalg_matrix_exp", + "torch._C._linalg.linalg_matrix_norm", + "torch._C._linalg.linalg_matrix_power", + "torch._C._linalg.linalg_matrix_rank", + "torch._C._linalg.linalg_matrix_sqrth", + "torch._C._linalg.linalg_multi_dot", + "torch._C._linalg.linalg_norm", + "torch._C._linalg.linalg_pinv", + "torch._C._linalg.linalg_polar", + "torch._C._linalg.linalg_qr", + "torch._C._linalg.linalg_slogdet", + "torch._C._linalg.linalg_solve_ex", + "torch._C._linalg.linalg_solve_triangular", + "torch._C._linalg.linalg_solve", + "torch._C._linalg.linalg_svd", + "torch._C._linalg.linalg_svdvals", + "torch._C._linalg.linalg_tensorinv", + "torch._C._linalg.linalg_tensorsolve", + "torch._C._linalg.linalg_vander", + "torch._C._linalg.linalg_vecdot", + "torch._C._linalg.linalg_vector_norm", + "torch._C._llvm_enabled", + "torch._C._load_for_lite_interpreter_from_buffer", + "torch._C._load_for_lite_interpreter", + "torch._C._load_jit_module_from_bytes", + "torch._C._load_jit_module_from_file", + "torch._C._load_mobile_module_from_bytes", + "torch._C._load_mobile_module_from_file", + "torch._C._log_api_usage_metadata", + "torch._C._log_api_usage_once", + "torch._C._logging_set_logger", + "torch._C._meta_in_tls_dispatch_include", + "torch._C._mps_acquireEvent", + "torch._C._mps_currentAllocatedMemory", + "torch._C._mps_deviceSynchronize", + "torch._C._mps_driverAllocatedMemory", + "torch._C._mps_recommendedMaxMemory", + "torch._C._mps_elapsedTimeOfEvents", + "torch._C._mps_emptyCache", + "torch._C._mps_get_default_generator", + "torch._C._mps_is_available", + "torch._C._mps_is_in_bad_fork", + "torch._C._mps_is_on_macos_13_or_newer", + "torch._C._mps_profilerStartTrace", + "torch._C._mps_profilerStopTrace", + "torch._C._mps_queryEvent", + "torch._C._mps_recordEvent", + "torch._C._mps_releaseEvent", + "torch._C._mps_setMemoryFraction", + "torch._C._mps_synchronizeEvent", + "torch._C._mps_waitForEvent", + "torch._C._multiprocessing_init", + "torch._C._nccl_all_gather", + "torch._C._nccl_all_reduce", + "torch._C._nccl_broadcast", + "torch._C._nccl_init_rank", + "torch._C._nccl_reduce_scatter", + "torch._C._nccl_reduce", + "torch._C._nccl_unique_id", + "torch._C._nccl_version_suffix", + "torch._C._nccl_version", + "torch._C._nested.nested_tensor", + "torch._C._nested.nested_to_padded_tensor", + "torch._C._new_symbolic_shape_symbol", + "torch._C._nn_module_to_mobile", + "torch._C._nn._conv_depthwise2d", + "torch._C._nn._pad_circular", + "torch._C._nn._pad_enum", + "torch._C._nn._test_ambiguous_defaults", + "torch._C._nn._test_optional_filled_intlist", + "torch._C._nn._test_optional_floatlist", + "torch._C._nn._test_optional_intlist", + "torch._C._nn._test_string_default", + "torch._C._nn._test_warn_in_autograd", + "torch._C._nn._upsample_bicubic2d_aa", + "torch._C._nn._upsample_bilinear2d_aa", + "torch._C._nn._upsample_lanczos2d_aa", + "torch._C._nn._upsample_nearest_exact1d", + "torch._C._nn._upsample_nearest_exact2d", + "torch._C._nn._upsample_nearest_exact3d", + "torch._C._nn.adaptive_avg_pool2d", + "torch._C._nn.adaptive_avg_pool3d", + "torch._C._nn.adaptive_max_pool2d", + "torch._C._nn.adaptive_max_pool3d", + "torch._C._nn.avg_pool2d", + "torch._C._nn.avg_pool3d", + "torch._C._nn.binary_cross_entropy", + "torch._C._nn.col2im", + "torch._C._nn.conv_depthwise3d", + "torch._C._nn.cross_entropy_loss", + "torch._C._nn.elu_", + "torch._C._nn.elu", + "torch._C._nn.flatten_dense_tensors", + "torch._C._nn.fractional_max_pool2d", + "torch._C._nn.fractional_max_pool3d", + "torch._C._nn.gelu_", + "torch._C._nn.gelu", + "torch._C._nn.glu", + "torch._C._nn.hardsigmoid_", + "torch._C._nn.hardsigmoid", + "torch._C._nn.hardswish_", + "torch._C._nn.hardswish", + "torch._C._nn.hardtanh_", + "torch._C._nn.hardtanh", + "torch._C._nn.huber_loss", + "torch._C._nn.im2col", + "torch._C._nn.l1_loss", + "torch._C._nn.leaky_relu_", + "torch._C._nn.leaky_relu", + "torch._C._nn.linear", + "torch._C._nn.log_sigmoid", + "torch._C._nn.max_pool2d_with_indices", + "torch._C._nn.max_pool3d_with_indices", + "torch._C._nn.max_unpool2d", + "torch._C._nn.max_unpool3d", + "torch._C._nn.mish_", + "torch._C._nn.mish", + "torch._C._nn.mkldnn_linear", + "torch._C._nn.mkldnn_reorder_conv2d_weight", + "torch._C._nn.mkldnn_reorder_conv3d_weight", + "torch._C._nn.mse_loss", + "torch._C._nn.multi_margin_loss", + "torch._C._nn.multilabel_margin_loss", + "torch._C._nn.nll_loss_nd", + "torch._C._nn.nll_loss", + "torch._C._nn.nll_loss2d", + "torch._C._nn.one_hot", + "torch._C._nn.pad_sequence", + "torch._C._nn.pad", + "torch._C._nn.reflection_pad1d", + "torch._C._nn.reflection_pad2d", + "torch._C._nn.reflection_pad3d", + "torch._C._nn.relu6_", + "torch._C._nn.relu6", + "torch._C._nn.replication_pad1d", + "torch._C._nn.replication_pad2d", + "torch._C._nn.replication_pad3d", + "torch._C._nn.rrelu_with_noise_", + "torch._C._nn.rrelu_with_noise", + "torch._C._nn.scaled_dot_product_attention", + "torch._C._nn.silu_", + "torch._C._nn.silu", + "torch._C._nn.slow_conv_dilated2d", + "torch._C._nn.slow_conv_dilated3d", + "torch._C._nn.slow_conv_transpose2d", + "torch._C._nn.slow_conv_transpose3d", + "torch._C._nn.slow_conv3d", + "torch._C._nn.smooth_l1_loss", + "torch._C._nn.soft_margin_loss", + "torch._C._nn.softplus", + "torch._C._nn.softshrink", + "torch._C._nn.thnn_conv2d", + "torch._C._nn.unflatten_dense_tensors", + "torch._C._nn.upsample_bicubic2d", + "torch._C._nn.upsample_bilinear2d", + "torch._C._nn.upsample_linear1d", + "torch._C._nn.upsample_nearest1d", + "torch._C._nn.upsample_nearest2d", + "torch._C._nn.upsample_nearest3d", + "torch._C._nn.upsample_trilinear3d", + "torch._C._non_sym_sizes", + "torch._C._overlaps", + "torch._C._parallel_info", + "torch._C._parse_dispatch_key", + "torch._C._parse_source_def", + "torch._C._pop_torch_dispatch_stack", + "torch._C._pop_torch_function_stack", + "torch._C._propagate_and_assign_input_shapes", + "torch._C._propagate_shapes", + "torch._C._propagate_xla_data", + "torch._C._push_on_torch_dispatch_stack", + "torch._C._push_on_torch_function_stack", + "torch._C._quantize_ondevice_ptq_dynamic", + "torch._C._register_py_class_for_device", + "torch._C._remove_cached_tensor", + "torch._C._remove_worker_pids", + "torch._C._rename_privateuse1_backend", + "torch._C._replace_", + "torch._C._replace_overloaded_method_decl", + "torch._C._resolve_type_from_object", + "torch._C._resolve_type", + "torch._C._rocm_is_backward_pass", + "torch._C._rpc_init", + "torch._C._run_emit_module_hook", + "torch._C._save_jit_module_to_bytes", + "torch._C._save_jit_module", + "torch._C._save_mobile_module_to_bytes", + "torch._C._save_mobile_module", + "torch._C._save_parameters", + "torch._C._scatter_out", + "torch._C._scatter", + "torch._C._select_conv_backend", + "torch._C._select_batch_norm_backend", + "torch._C._set_autograd_fallback_mode", + "torch._C._set_backcompat_broadcast_warn", + "torch._C._set_backcompat_keepdim_warn", + "torch._C._set_blas_preferred_backend", + "torch._C._set_cached_tensors_enabled", + "torch._C._set_check_sparse_tensor_invariants", + "torch._C._set_conj", + "torch._C._set_cublas_allow_bf16_reduced_precision_reduction", + "torch._C._set_cublas_allow_fp16_reduced_precision_reduction", + "torch._C._set_cublas_allow_tf32", + "torch._C._set_cudnn_allow_tf32", + "torch._C._set_cudnn_benchmark", + "torch._C._set_cudnn_deterministic", + "torch._C._set_cudnn_enabled", + "torch._C._set_default_dtype", + "torch._C._set_default_mobile_cpu_allocator", + "torch._C._set_default_tensor_type", + "torch._C._set_deterministic_algorithms", + "torch._C._set_deterministic_fill_uninitialized_memory", + "torch._C._set_dispatch_mode", + "torch._C._set_float32_matmul_precision", + "torch._C._set_fwd_grad_enabled", + "torch._C._set_grad_enabled", + "torch._C._set_graph_executor_optimize", + "torch._C._set_linalg_preferred_backend", + "torch._C._set_rocm_fa_preferred_backend", + "torch._C._set_meta_in_tls_dispatch_include", + "torch._C._set_mkldnn_enabled", + "torch._C._set_multithreading_enabled", + "torch._C._set_neg", + "torch._C._set_nnpack_enabled", + "torch._C._set_print_stack_traces_on_fatal_signal", + "torch._C._set_qengine", + "torch._C._set_sdp_use_flash", + "torch._C._set_sdp_use_math", + "torch._C._set_math_sdp_allow_fp16_bf16_reduction", + "torch._C._set_sdp_use_mem_efficient", + "torch._C._set_sdp_use_overrideable", + "torch._C._set_should_use_format_with_string_table", + "torch._C._set_sm_carveout_experimental", + "torch._C._set_storage_access_error_msg", + "torch._C._set_tensor_metadata", + "torch._C._set_tracing_state", + "torch._C._set_value_trace", + "torch._C._set_view_replay_enabled", + "torch._C._set_warnAlways", + "torch._C._set_worker_pids", + "torch._C._set_worker_signal_handlers", + "torch._C._should_allow_numbers_as_tensors", + "torch._C._show_config", + "torch._C._sparse._sparse_addmm", + "torch._C._sparse._sparse_log_softmax", + "torch._C._sparse._sparse_mm_reduce_impl", + "torch._C._sparse._sparse_mm", + "torch._C._sparse._sparse_softmax", + "torch._C._sparse._spdiags", + "torch._C._sparse.sparse_sampled_addmm", + "torch._C._special.special_airy_ai", + "torch._C._special.special_bessel_j0", + "torch._C._special.special_bessel_j1", + "torch._C._special.special_bessel_y0", + "torch._C._special.special_bessel_y1", + "torch._C._special.special_chebyshev_polynomial_t", + "torch._C._special.special_chebyshev_polynomial_u", + "torch._C._special.special_chebyshev_polynomial_v", + "torch._C._special.special_chebyshev_polynomial_w", + "torch._C._special.special_digamma", + "torch._C._special.special_entr", + "torch._C._special.special_erf", + "torch._C._special.special_erfc", + "torch._C._special.special_erfcx", + "torch._C._special.special_erfinv", + "torch._C._special.special_exp2", + "torch._C._special.special_expit", + "torch._C._special.special_expm1", + "torch._C._special.special_gammainc", + "torch._C._special.special_gammaincc", + "torch._C._special.special_gammaln", + "torch._C._special.special_hermite_polynomial_h", + "torch._C._special.special_hermite_polynomial_he", + "torch._C._special.special_i0", + "torch._C._special.special_i0e", + "torch._C._special.special_i1", + "torch._C._special.special_i1e", + "torch._C._special.special_laguerre_polynomial_l", + "torch._C._special.special_legendre_polynomial_p", + "torch._C._special.special_log_ndtr", + "torch._C._special.special_log_softmax", + "torch._C._special.special_log1p", + "torch._C._special.special_logit", + "torch._C._special.special_logsumexp", + "torch._C._special.special_modified_bessel_i0", + "torch._C._special.special_modified_bessel_i1", + "torch._C._special.special_modified_bessel_k0", + "torch._C._special.special_modified_bessel_k1", + "torch._C._special.special_multigammaln", + "torch._C._special.special_ndtr", + "torch._C._special.special_ndtri", + "torch._C._special.special_polygamma", + "torch._C._special.special_psi", + "torch._C._special.special_round", + "torch._C._special.special_scaled_modified_bessel_k0", + "torch._C._special.special_scaled_modified_bessel_k1", + "torch._C._special.special_shifted_chebyshev_polynomial_t", + "torch._C._special.special_shifted_chebyshev_polynomial_u", + "torch._C._special.special_shifted_chebyshev_polynomial_v", + "torch._C._special.special_shifted_chebyshev_polynomial_w", + "torch._C._special.special_sinc", + "torch._C._special.special_softmax", + "torch._C._special.special_spherical_bessel_j0", + "torch._C._special.special_xlog1py", + "torch._C._special.special_xlogy", + "torch._C._special.special_zeta", + "torch._C._stash_obj_in_tls", + "torch._C._storage_id", + "torch._C._storage_Use_Count", + "torch._C._supported_qengines", + "torch._C._te.abs", + "torch._C._te.acos", + "torch._C._te.annotate_input_shapes", + "torch._C._te.asin", + "torch._C._te.atan", + "torch._C._te.atan2", + "torch._C._te.ceil", + "torch._C._te.Compute", + "torch._C._te.Compute2", + "torch._C._te.construct_codegen", + "torch._C._te.cos", + "torch._C._te.cosh", + "torch._C._te.erf", + "torch._C._te.erfc", + "torch._C._te.exp", + "torch._C._te.expm1", + "torch._C._te.fixup_missing_shape_info", + "torch._C._te.floor", + "torch._C._te.fmod", + "torch._C._te.frac", + "torch._C._te.ifThenElse", + "torch._C._te.is_graph_compilable", + "torch._C._te.isnan", + "torch._C._te.lgamma", + "torch._C._te.log", + "torch._C._te.log10", + "torch._C._te.log1p", + "torch._C._te.log2", + "torch._C._te.lower", + "torch._C._te.make_shapes_symbolic", + "torch._C._te.pow", + "torch._C._te.Reduce", + "torch._C._te.remainder", + "torch._C._te.remove_graph_output", + "torch._C._te.remove_unused_self_argument", + "torch._C._te.replace_list_output_with_tuple", + "torch._C._te.round", + "torch._C._te.rsqrt", + "torch._C._te.sigmoid", + "torch._C._te.simplify", + "torch._C._te.sin", + "torch._C._te.sinh", + "torch._C._te.sqrt", + "torch._C._te.tan", + "torch._C._te.tanh", + "torch._C._te.trim_graph", + "torch._C._te.trunc", + "torch._C._tensor_impl_raw_handle", + "torch._C._test_only_add_entry_to_op_version_map", + "torch._C._test_only_populate_upgraders", + "torch._C._test_only_remove_entry_to_op_version_map", + "torch._C._test_only_remove_upgraders", + "torch._C._to_functionality_key", + "torch._C._tracer_set_force_outplace", + "torch._C._tracer_set_get_unique_name_fn", + "torch._C._tracer_warn_use_python", + "torch._C._unset_default_mobile_cpu_allocator", + "torch._C._unset_dispatch_mode", + "torch._C._valgrind_supported_platform", + "torch._C._valgrind_toggle_and_dump_stats", + "torch._C._valgrind_toggle", + "torch._C._verbose.mkl_set_verbose", + "torch._C._verbose.mkldnn_set_verbose", + "torch._C._vmapmode_decrement_nesting", + "torch._C._vmapmode_increment_nesting", + "torch._C._warn_deprecation", + "torch._C._warn", + "torch._C._will_engine_execute_node", + "torch._C._wrap_tensor_impl", + "torch._C._xpu_emptyCache", + "torch._C._xpu_getArchFlags", + "torch._C._xpu_getCurrentStream", + "torch._C._xpu_getCurrentRawStream", + "torch._C._xpu_getDeviceCount", + "torch._C._xpu_getDevice", + "torch._C._xpu_getMemoryInfo", + "torch._C._xpu_getStreamFromExternal", + "torch._C._xpu_isInBadFork", + "torch._C._xpu_init", + "torch._C._xpu_memoryStats", + "torch._C._xpu_resetAccumulatedMemoryStats", + "torch._C._xpu_resetPeakMemoryStats", + "torch._C._xpu_setStream", + "torch._C._xpu_synchronize", + "torch._C.autocast_decrement_nesting", + "torch._C.autocast_increment_nesting", + "torch._C.clear_autocast_cache", + "torch._C.fork", + "torch._C.get_autocast_cpu_dtype", + "torch._C.get_autocast_dtype", + "torch._C.get_autocast_gpu_dtype", + "torch._C.get_autocast_ipu_dtype", + "torch._C.get_autocast_xla_dtype", + "torch._C.get_default_dtype", + "torch._C.get_num_interop_threads", + "torch._C.get_num_threads", + "torch._C.import_ir_module_from_buffer", + "torch._C.import_ir_module", + "torch._C.init_num_threads", + "torch._C.is_anomaly_check_nan_enabled", + "torch._C.is_anomaly_enabled", + "torch._C.is_autocast_cache_enabled", + "torch._C.is_autocast_cpu_enabled", + "torch._C.is_autocast_enabled", + "torch._C.is_autocast_ipu_enabled", + "torch._C.is_autocast_xla_enabled", + "torch._C.is_grad_enabled", + "torch._C.is_inference_mode_enabled", + "torch._C.merge_type_from_type_comment", + "torch._C.parse_ir", + "torch._C.parse_schema", + "torch._C.parse_type_comment", + "torch._C.set_autocast_cache_enabled", + "torch._C.set_autocast_enabled", + "torch._C.unify_type_list", + "torch._C.wait", + "torch._cast_Byte", + "torch._cast_Char", + "torch._cast_Double", + "torch._cast_Float", + "torch._cast_Half", + "torch._cast_Int", + "torch._cast_Long", + "torch._cast_Short", + "torch._choose_qparams_per_tensor", + "torch._chunk_cat", + "torch._coalesce", + "torch._compute_linear_combination", + "torch._conj_copy", + "torch._conj_physical", + "torch._conj", + "torch._convert_indices_from_coo_to_csr", + "torch._convert_indices_from_csr_to_coo", + "torch._convert_weight_to_int4pack", + "torch._convert_weight_to_int4pack_for_cpu", + "torch._convolution_mode", + "torch._convolution", + "torch._copy_from_and_resize", + "torch._copy_from", + "torch._cslt_compress", + "torch._cslt_sparse_mm", + "torch._ctc_loss", + "torch._cudnn_ctc_loss", + "torch._cudnn_init_dropout_state", + "torch._cudnn_rnn_flatten_weight", + "torch._cudnn_rnn", + "torch._cufft_clear_plan_cache", + "torch._cufft_get_plan_cache_max_size", + "torch._cufft_get_plan_cache_size", + "torch._cufft_set_plan_cache_max_size", + "torch._cummax_helper", + "torch._cummin_helper", + "torch._debug_has_internal_overlap", + "torch._dim_arange", + "torch._dirichlet_grad", + "torch._disable_functionalization", + "torch._dyn_quant_matmul_4bit", + "torch._dyn_quant_pack_4bit_weight", + "torch._efficientzerotensor", + "torch._embedding_bag_forward_only", + "torch._embedding_bag", + "torch._empty_affine_quantized", + "torch._empty_per_channel_affine_quantized", + "torch._enable_functionalization", + "torch._euclidean_dist", + "torch._fake_quantize_learnable_per_channel_affine", + "torch._fake_quantize_learnable_per_tensor_affine", + "torch._fake_quantize_per_tensor_affine_cachemask_tensor_qparams", + "torch._fft_c2c", + "torch._fft_c2r", + "torch._fft_r2c", + "torch._fill_mem_eff_dropout_mask_", + "torch._foobar", + "torch._foreach_abs_", + "torch._foreach_abs", + "torch._foreach_acos_", + "torch._foreach_acos", + "torch._foreach_add_", + "torch._foreach_add", + "torch._foreach_addcdiv_", + "torch._foreach_addcdiv", + "torch._foreach_addcmul_", + "torch._foreach_addcmul", + "torch._foreach_asin_", + "torch._foreach_asin", + "torch._foreach_atan_", + "torch._foreach_atan", + "torch._foreach_ceil_", + "torch._foreach_ceil", + "torch._foreach_clamp_max_", + "torch._foreach_clamp_max", + "torch._foreach_clamp_min_", + "torch._foreach_clamp_min", + "torch._foreach_clone", + "torch._foreach_copy_", + "torch._foreach_cos_", + "torch._foreach_cos", + "torch._foreach_cosh_", + "torch._foreach_cosh", + "torch._foreach_div_", + "torch._foreach_div", + "torch._foreach_erf_", + "torch._foreach_erf", + "torch._foreach_erfc_", + "torch._foreach_erfc", + "torch._foreach_exp_", + "torch._foreach_exp", + "torch._foreach_expm1_", + "torch._foreach_expm1", + "torch._foreach_floor_", + "torch._foreach_floor", + "torch._foreach_frac_", + "torch._foreach_frac", + "torch._foreach_lerp_", + "torch._foreach_lerp", + "torch._foreach_lgamma_", + "torch._foreach_lgamma", + "torch._foreach_log_", + "torch._foreach_log", + "torch._foreach_log10_", + "torch._foreach_log10", + "torch._foreach_log1p_", + "torch._foreach_log1p", + "torch._foreach_log2_", + "torch._foreach_log2", + "torch._foreach_maximum_", + "torch._foreach_maximum", + "torch._foreach_minimum_", + "torch._foreach_minimum", + "torch._foreach_mul_", + "torch._foreach_mul", + "torch._foreach_neg_", + "torch._foreach_neg", + "torch._foreach_norm", + "torch._foreach_pow_", + "torch._foreach_pow", + "torch._foreach_reciprocal_", + "torch._foreach_reciprocal", + "torch._foreach_round_", + "torch._foreach_round", + "torch._foreach_sigmoid_", + "torch._foreach_sigmoid", + "torch._foreach_rsqrt_", + "torch._foreach_rsqrt", + "torch._foreach_sign_", + "torch._foreach_sign", + "torch._foreach_sin_", + "torch._foreach_sin", + "torch._foreach_sinh_", + "torch._foreach_sinh", + "torch._foreach_sqrt_", + "torch._foreach_sqrt", + "torch._foreach_sub_", + "torch._foreach_sub", + "torch._foreach_tan_", + "torch._foreach_tan", + "torch._foreach_tanh_", + "torch._foreach_tanh", + "torch._foreach_trunc_", + "torch._foreach_trunc", + "torch._foreach_zero_", + "torch._freeze_functional_tensor", + "torch._from_functional_tensor", + "torch._functional_assert_async", + "torch._functional_sym_constrain_range_for_size", + "torch._functional_sym_constrain_range", + "torch._functionalize_are_all_mutations_hidden_from_autograd", + "torch._functionalize_commit_update", + "torch._functionalize_enable_reapply_views", + "torch._functionalize_has_data_mutation", + "torch._functionalize_has_metadata_mutation", + "torch._functionalize_is_multi_output_view", + "torch._functionalize_mark_mutation_hidden_from_autograd", + "torch._functionalize_replace", + "torch._functionalize_sync", + "torch._functionalize_was_storage_changed", + "torch._fused_adagrad_", + "torch._fused_adam_", + "torch._fused_adamw_", + "torch._fused_dropout", + "torch._fused_moving_avg_obs_fq_helper", + "torch._fused_sdp_choice", + "torch._fw_primal_copy", + "torch._grid_sampler_2d_cpu_fallback", + "torch._grouped_mm", + "torch._histogramdd_bin_edges", + "torch._histogramdd_from_bin_cts", + "torch._histogramdd_from_bin_tensors", + "torch._index_put_impl_", + "torch._indices_copy", + "torch._int_mm", + "torch._is_all_true", + "torch._is_any_true", + "torch._is_functional_tensor", + "torch._is_zerotensor", + "torch._linalg_check_errors", + "torch._linalg_det", + "torch._linalg_eigh", + "torch._linalg_eigvals", + "torch._linalg_slogdet", + "torch._linalg_solve_ex", + "torch._linalg_svd", + "torch._log_softmax_backward_data", + "torch._log_softmax", + "torch._logcumsumexp", + "torch._lstm_mps", + "torch._lu_with_info", + "torch._make_dep_token", + "torch._make_dual_copy", + "torch._make_dual", + "torch._make_per_channel_quantized_tensor", + "torch._make_per_tensor_quantized_tensor", + "torch._masked_scale", + "torch._masked_softmax", + "torch._mirror_autograd_meta_to", + "torch._mixed_dtypes_linear", + "torch._mkldnn_reshape", + "torch._mkldnn_transpose_", + "torch._mkldnn_transpose", + "torch._mps_convolution_transpose", + "torch._mps_convolution", + "torch._native_batch_norm_legit_no_training", + "torch._native_batch_norm_legit", + "torch._native_multi_head_attention", + "torch._neg_view_copy", + "torch._neg_view", + "torch._nested_from_padded_and_nested_example", + "torch._nested_from_padded_tensor", + "torch._nested_tensor_from_mask_left_aligned", + "torch._nested_tensor_from_tensor_list", + "torch._nested_tensor_softmax_with_shape", + "torch._nested_view_from_buffer_copy", + "torch._nested_view_from_buffer", + "torch._nnpack_available", + "torch._nnpack_spatial_convolution", + "torch._pack_padded_sequence", + "torch._pad_packed_sequence", + "torch._pin_memory", + "torch._prelu_kernel", + "torch._propagate_xla_data", + "torch._remove_batch_dim", + "torch._reshape_alias_copy", + "torch._reshape_from_tensor", + "torch._resize_output_", + "torch._rowwise_prune", + "torch._sample_dirichlet", + "torch._saturate_weight_to_fp16", + "torch._scaled_dot_product_attention_math", + "torch._scaled_dot_product_efficient_attention", + "torch._scaled_dot_product_flash_attention", + "torch._scaled_dot_product_flash_attention_for_cpu", + "torch._scaled_dot_product_cudnn_attention", + "torch._scaled_mm", + "torch._scaled_mm_v2", + "torch._scaled_grouped_mm", + "torch._scaled_grouped_mm_v2", + "torch._shape_as_tensor", + "torch._sobol_engine_draw", + "torch._sobol_engine_ff_", + "torch._sobol_engine_initialize_state_", + "torch._sobol_engine_scramble_", + "torch._softmax_backward_data", + "torch._softmax", + "torch._sparse_broadcast_to_copy", + "torch._sparse_broadcast_to", + "torch._sparse_csr_prod", + "torch._sparse_csr_sum", + "torch._sparse_log_softmax_backward_data", + "torch._sparse_semi_structured_addmm", + "torch._sparse_semi_structured_linear", + "torch._sparse_semi_structured_mm", + "torch._sparse_softmax_backward_data", + "torch._sparse_sparse_matmul", + "torch._sparse_sum", + "torch._stack", + "torch._standard_gamma_grad", + "torch._standard_gamma", + "torch._test_autograd_multiple_dispatch_view_copy", + "torch._test_autograd_multiple_dispatch_view", + "torch._test_autograd_multiple_dispatch", + "torch._test_check_tensor", + "torch._test_functorch_fallback", + "torch._test_serialization_subcmul", + "torch._to_cpu", + "torch._to_functional_tensor", + "torch._to_sparse_semi_structured", + "torch._transform_bias_rescale_qkv", + "torch._transformer_encoder_layer_fwd", + "torch._trilinear", + "torch._triton_multi_head_attention", + "torch._triton_scaled_dot_attention", + "torch._unique", + "torch._unique2", + "torch._unpack_dual", + "torch._unsafe_index_put", + "torch._unsafe_index", + "torch._unsafe_masked_index_put_accumulate", + "torch._unsafe_masked_index", + "torch._use_cudnn_ctc_loss", + "torch._use_cudnn_rnn_flatten_weight", + "torch._values_copy", + "torch._weight_int4pack_mm", + "torch._weight_int4pack_mm_for_cpu", + "torch._weight_int4pack_mm_with_scales_and_zeros", + "torch._weight_int8pack_mm", + "torch._weight_norm_interface", + "torch._weight_norm", + "torch.abs_", + "torch.abs", + "torch.absolute", + "torch.acos_", + "torch.acos", + "torch.acosh_", + "torch.acosh", + "torch.adaptive_avg_pool1d", + "torch.adaptive_max_pool1d", + "torch.add", + "torch.addbmm", + "torch.addcdiv", + "torch.addcmul", + "torch.addmm", + "torch.addmv_", + "torch.addmv", + "torch.addr", + "torch.adjoint", + "torch.affine_grid_generator", + "torch.alias_copy", + "torch.all", + "torch.allclose", + "torch.alpha_dropout_", + "torch.alpha_dropout", + "torch.amax", + "torch.amin", + "torch.aminmax", + "torch.angle", + "torch.any", + "torch.arange", + "torch.arccos_", + "torch.arccos", + "torch.arccosh_", + "torch.arccosh", + "torch.arcsin_", + "torch.arcsin", + "torch.arcsinh_", + "torch.arcsinh", + "torch.arctan_", + "torch.arctan", + "torch.arctan2", + "torch.arctanh_", + "torch.arctanh", + "torch.argmax", + "torch.argmin", + "torch.argsort", + "torch.argwhere", + "torch.as_strided_", + "torch.as_strided_copy", + "torch.as_strided_scatter", + "torch.as_strided", + "torch.as_tensor", + "torch.asarray", + "torch.asin_", + "torch.asin", + "torch.asinh_", + "torch.asinh", + "torch.atan_", + "torch.atan", + "torch.atan2", + "torch.atanh_", + "torch.atanh", + "torch.avg_pool1d", + "torch.baddbmm", + "torch.bartlett_window", + "torch.batch_norm_backward_elemt", + "torch.batch_norm_backward_reduce", + "torch.batch_norm_elemt", + "torch.batch_norm_gather_stats_with_counts", + "torch.batch_norm_gather_stats", + "torch.batch_norm_stats", + "torch.batch_norm_update_stats", + "torch.batch_norm", + "torch.bernoulli", + "torch.bilinear", + "torch.binary_cross_entropy_with_logits", + "torch.bincount", + "torch.binomial", + "torch.bitwise_and", + "torch.bitwise_left_shift", + "torch.bitwise_not", + "torch.bitwise_or", + "torch.bitwise_right_shift", + "torch.bitwise_xor", + "torch.blackman_window", + "torch.bmm", + "torch.broadcast_to", + "torch.bucketize", + "torch.can_cast", + "torch.cat", + "torch.ccol_indices_copy", + "torch.ceil_", + "torch.ceil", + "torch.celu_", + "torch.celu", + "torch.channel_shuffle", + "torch.cholesky_inverse", + "torch.cholesky_solve", + "torch.choose_qparams_optimized", + "torch.chunk", + "torch.clamp_", + "torch.clamp_max_", + "torch.clamp_max", + "torch.clamp_min_", + "torch.clamp_min", + "torch.clamp", + "torch.clip_", + "torch.clip", + "torch.clone", + "torch.col_indices_copy", + "torch.column_stack", + "torch.combinations", + "torch.complex", + "torch.concat", + "torch.concatenate", + "torch.conj_physical_", + "torch.conj_physical", + "torch.conj", + "torch.constant_pad_nd", + "torch.conv_tbc", + "torch.conv_transpose1d", + "torch.conv_transpose2d", + "torch.conv_transpose3d", + "torch.conv1d", + "torch.conv2d", + "torch.conv3d", + "torch.convolution", + "torch.copysign", + "torch.corrcoef", + "torch.cos_", + "torch.cos", + "torch.cosh_", + "torch.cosh", + "torch.cosine_embedding_loss", + "torch.cosine_similarity", + "torch.count_nonzero", + "torch.cov", + "torch.cross", + "torch.crow_indices_copy", + "torch.ctc_loss", + "torch.cudnn_affine_grid_generator", + "torch.cudnn_batch_norm", + "torch.cudnn_convolution_add_relu", + "torch.cudnn_convolution_relu", + "torch.cudnn_convolution_transpose", + "torch.cudnn_convolution", + "torch.cudnn_grid_sampler", + "torch.cudnn_is_acceptable", + "torch.cummax", + "torch.cummin", + "torch.cumprod", + "torch.cumsum", + "torch.cumulative_trapezoid", + "torch.deg2rad_", + "torch.deg2rad", + "torch.dequantize", + "torch.det", + "torch.detach_", + "torch.detach_copy", + "torch.detach", + "torch.diag_embed", + "torch.diag", + "torch.diagflat", + "torch.diagonal_copy", + "torch.diagonal_scatter", + "torch.diagonal", + "torch.diff", + "torch.digamma", + "torch.dist", + "torch.div", + "torch.divide", + "torch.dot", + "torch.dropout_", + "torch.dropout", + "torch.dsmm", + "torch.dsplit", + "torch.dstack", + "torch.embedding_bag", + "torch.embedding_renorm_", + "torch.embedding", + "torch.empty_like", + "torch.empty_permuted", + "torch.empty_quantized", + "torch.empty_strided", + "torch.empty", + "torch.eq", + "torch.equal", + "torch.erf_", + "torch.erf", + "torch.erfc_", + "torch.erfc", + "torch.erfinv", + "torch.exp_", + "torch.exp", + "torch.exp2_", + "torch.exp2", + "torch.expand_copy", + "torch.expm1_", + "torch.expm1", + "torch.eye", + "torch.fake_quantize_per_channel_affine", + "torch.fake_quantize_per_tensor_affine", + "torch.fbgemm_linear_fp16_weight_fp32_activation", + "torch.fbgemm_linear_fp16_weight", + "torch.fbgemm_linear_int8_weight_fp32_activation", + "torch.fbgemm_linear_int8_weight", + "torch.fbgemm_linear_quantize_weight", + "torch.fbgemm_pack_gemm_matrix_fp16", + "torch.fbgemm_pack_quantized_matrix", + "torch.feature_alpha_dropout_", + "torch.feature_alpha_dropout", + "torch.feature_dropout_", + "torch.feature_dropout", + "torch.fill_", + "torch.fill", + "torch.fix_", + "torch.fix", + "torch.flatten", + "torch.flip", + "torch.fliplr", + "torch.flipud", + "torch.float_power", + "torch.floor_", + "torch.floor_divide", + "torch.floor", + "torch.fmax", + "torch.fmin", + "torch.fmod", + "torch.frac_", + "torch.frac", + "torch.frexp", + "torch.frobenius_norm", + "torch.from_file", + "torch.from_numpy", + "torch.frombuffer", + "torch.full_like", + "torch.full", + "torch.fused_moving_avg_obs_fake_quant", + "torch.gather", + "torch.gcd_", + "torch.gcd", + "torch.ge", + "torch.geqrf", + "torch.ger", + "torch.get_device", + "torch.get_device_module", + "torch.gradient", + "torch.greater_equal", + "torch.greater", + "torch.grid_sampler_2d", + "torch.grid_sampler_3d", + "torch.grid_sampler", + "torch.group_norm", + "torch.gru_cell", + "torch.gru", + "torch.gt", + "torch.hamming_window", + "torch.hann_window", + "torch.hardshrink", + "torch.hash_tensor", + "torch.heaviside", + "torch.hinge_embedding_loss", + "torch.histc", + "torch.histogram", + "torch.histogramdd", + "torch.hsmm", + "torch.hsplit", + "torch.hspmm", + "torch.hstack", + "torch.hypot", + "torch.i0_", + "torch.i0", + "torch.igamma", + "torch.igammac", + "torch.imag", + "torch.index_add", + "torch.index_copy", + "torch.index_fill", + "torch.index_put_", + "torch.index_put", + "torch.index_reduce", + "torch.index_select", + "torch.indices_copy", + "torch.inner", + "torch.instance_norm", + "torch.int_repr", + "torch.inverse", + "torch.is_complex", + "torch.is_conj", + "torch.is_distributed", + "torch.is_floating_point", + "torch.is_inference", + "torch.is_neg", + "torch.is_nonzero", + "torch.is_same_size", + "torch.is_signed", + "torch.is_vulkan_available", + "torch.isclose", + "torch.isfinite", + "torch.isin", + "torch.isinf", + "torch.isnan", + "torch.isneginf", + "torch.isposinf", + "torch.isreal", + "torch.istft", + "torch.kaiser_window", + "torch.kl_div", + "torch.kron", + "torch.kthvalue", + "torch.layer_norm", + "torch.lcm_", + "torch.lcm", + "torch.ldexp_", + "torch.ldexp", + "torch.le", + "torch.lerp", + "torch.less_equal", + "torch.less", + "torch.lgamma", + "torch.linspace", + "torch.log_", + "torch.log_softmax", + "torch.log", + "torch.log10_", + "torch.log10", + "torch.log1p_", + "torch.log1p", + "torch.log2_", + "torch.log2", + "torch.logaddexp", + "torch.logaddexp2", + "torch.logcumsumexp", + "torch.logdet", + "torch.logical_and", + "torch.logical_not", + "torch.logical_or", + "torch.logical_xor", + "torch.logit_", + "torch.logit", + "torch.logspace", + "torch.logsumexp", + "torch.lstm_cell", + "torch.lstm", + "torch.lt", + "torch.lu_solve", + "torch.lu_unpack", + "torch.margin_ranking_loss", + "torch.masked_fill", + "torch.masked_scatter", + "torch.masked_select", + "torch.matmul", + "torch.matrix_exp", + "torch.matrix_power", + "torch.max_pool1d_with_indices", + "torch.max_pool1d", + "torch.max_pool2d", + "torch.max_pool3d", + "torch.max", + "torch.maximum", + "torch.mean", + "torch.median", + "torch.min", + "torch.minimum", + "torch.miopen_batch_norm", + "torch.miopen_convolution_add_relu", + "torch.miopen_convolution_relu", + "torch.miopen_convolution_transpose", + "torch.miopen_convolution", + "torch.miopen_depthwise_convolution", + "torch.miopen_rnn", + "torch.mkldnn_adaptive_avg_pool2d", + "torch.mkldnn_convolution", + "torch.mkldnn_linear_backward_weights", + "torch.mkldnn_max_pool2d", + "torch.mkldnn_max_pool3d", + "torch.mkldnn_rnn_layer", + "torch.mm", + "torch.mode", + "torch.moveaxis", + "torch.movedim", + "torch.msort", + "torch.mul", + "torch.multinomial", + "torch.multiply", + "torch.mv", + "torch.mvlgamma", + "torch.nan_to_num_", + "torch.nan_to_num", + "torch.nanmean", + "torch.nanmedian", + "torch.nanquantile", + "torch.nansum", + "torch.narrow_copy", + "torch.narrow", + "torch.native_batch_norm", + "torch.native_channel_shuffle", + "torch.native_dropout", + "torch.native_group_norm", + "torch.native_layer_norm", + "torch.native_norm", + "torch.ne", + "torch.neg_", + "torch.neg", + "torch.negative_", + "torch.negative", + "torch.nextafter", + "torch.nonzero_static", + "torch.nonzero", + "torch.norm_except_dim", + "torch.normal", + "torch.not_equal", + "torch.nuclear_norm", + "torch.numel", + "torch.ones_like", + "torch.ones", + "torch.orgqr", + "torch.ormqr", + "torch.outer", + "torch.pairwise_distance", + "torch.pdist", + "torch.permute_copy", + "torch.permute", + "torch.pinverse", + "torch.pixel_shuffle", + "torch.pixel_unshuffle", + "torch.poisson_nll_loss", + "torch.poisson", + "torch.polar", + "torch.polygamma", + "torch.positive", + "torch.pow", + "torch.prelu", + "torch._print", + "torch.prod", + "torch.promote_types", + "torch.put", + "torch.q_per_channel_axis", + "torch.q_per_channel_scales", + "torch.q_per_channel_zero_points", + "torch.q_scale", + "torch.q_zero_point", + "torch.quantile", + "torch.quantize_per_channel", + "torch.quantize_per_tensor_dynamic", + "torch.quantize_per_tensor", + "torch.quantized_batch_norm", + "torch.quantized_gru_cell", + "torch.quantized_lstm_cell", + "torch.quantized_max_pool1d", + "torch.quantized_max_pool2d", + "torch.quantized_max_pool3d", + "torch.quantized_rnn_relu_cell", + "torch.quantized_rnn_tanh_cell", + "torch.rad2deg_", + "torch.rad2deg", + "torch.rand_like", + "torch.rand", + "torch.randint_like", + "torch.randint", + "torch.randn_like", + "torch.randn", + "torch.randperm", + "torch.range", + "torch.ravel", + "torch.real", + "torch.reciprocal_", + "torch.reciprocal", + "torch.relu_", + "torch.relu", + "torch.remainder", + "torch.renorm", + "torch.repeat_interleave", + "torch.reshape", + "torch.resolve_conj", + "torch.resolve_neg", + "torch.result_type", + "torch.rms_norm", + "torch.rnn_relu_cell", + "torch.rnn_relu", + "torch.rnn_tanh_cell", + "torch.rnn_tanh", + "torch.roll", + "torch.rot90", + "torch.round_", + "torch.round", + "torch.row_indices_copy", + "torch.row_stack", + "torch.rrelu_", + "torch.rrelu", + "torch.rsqrt_", + "torch.rsqrt", + "torch.rsub", + "torch.saddmm", + "torch.scalar_tensor", + "torch.scatter_add", + "torch.scatter_reduce", + "torch.scatter", + "torch.searchsorted", + "torch.segment_reduce", + "torch.select_copy", + "torch.select_scatter", + "torch.select", + "torch.selu_", + "torch.selu", + "torch.set_autocast_dtype", + "torch.sgn", + "torch.sigmoid_", + "torch.sigmoid", + "torch.sign", + "torch.signal.windows.windows.sqrt", + "torch.signbit", + "torch.sin_", + "torch.sin", + "torch.sinc_", + "torch.sinc", + "torch.sinh_", + "torch.sinh", + "torch.slice_copy", + "torch.slice_scatter", + "torch.slogdet", + "torch.smm", + "torch.softmax", + "torch.sort", + "torch.split_copy", + "torch.split_with_sizes_copy", + "torch.split_with_sizes", + "torch.spmm", + "torch.sqrt_", + "torch.sqrt", + "torch.square_", + "torch.square", + "torch.squeeze_copy", + "torch.squeeze", + "torch.sspaddmm", + "torch.stack", + "torch.std_mean", + "torch.std", + "torch.sub", + "torch.subtract", + "torch.sum", + "torch.svd", + "torch.swapaxes", + "torch.swapdims", + "torch.sym_constrain_range_for_size", + "torch.sym_constrain_range", + "torch.t_copy", + "torch.t", + "torch.take_along_dim", + "torch.take", + "torch.tan_", + "torch.tan", + "torch.tanh_", + "torch.tanh", + "torch.tensor_split", + "torch.tensor", + "torch.threshold_", + "torch.threshold", + "torch.tile", + "torch.topk", + "torch.trace", + "torch.transpose_copy", + "torch.transpose", + "torch.trapezoid", + "torch.trapz", + "torch.triangular_solve", + "torch.tril_indices", + "torch.tril", + "torch.triplet_margin_loss", + "torch.triu_indices", + "torch.triu", + "torch.true_divide", + "torch.trunc_", + "torch.trunc", + "torch.unbind_copy", + "torch.unbind", + "torch.unflatten", + "torch.unfold_copy", + "torch.unsafe_chunk", + "torch.unsafe_split_with_sizes", + "torch.unsafe_split", + "torch.unsqueeze_copy", + "torch.unsqueeze", + "torch.values_copy", + "torch.vander", + "torch.var_mean", + "torch.var", + "torch.vdot", + "torch.view_as_complex_copy", + "torch.view_as_complex", + "torch.view_as_real_copy", + "torch.view_as_real", + "torch.view_copy", + "torch.vsplit", + "torch.vstack", + "torch.where", + "torch.xlogy_", + "torch.xlogy", + "torch.zero_", + "torch.zeros", + "torch.zeros_like", + "torch._fused_sgd_", + "torch.slice_inverse", + "torch._assert_scalar", + "torch._functional_assert_scalar", + "torch.xpu._get_device_properties", + ], + TorchInGraphFunctionVariable, +) + + +if sys.version_info >= (3, 11): + torch_c_binding_in_graph_functions["math.exp2"] = TorchInGraphFunctionVariable + torch_c_binding_in_graph_functions["math.cbrt"] = TorchInGraphFunctionVariable + +if sys.version_info >= (3, 13): + torch_c_binding_in_graph_functions["math.fma"] = TorchInGraphFunctionVariable + +# In graph functions (including constant folding) that are not C bindings +# NOTE: [Cacheability of in-graph torch functions] +# Functions in this list have the property that graphs containing them are safe to cache/serialize. +# serialize given only the information in the graph. I.e, either: +# - Your function does not access or close over global state, or +# - Your function closes over global state, but this state is guarded by dynamo, either +# through constant folding or other mechanisms +# If your function needs a custom special handler (via @register on TorchInGraphFunctionVariable), +# or captures global state, please add it to manual_torch_name_rule_map instead +torch_non_c_binding_in_graph_functions = dict.fromkeys( + [ + "torch.__future__.get_overwrite_module_params_on_conversion", + "torch.__future__.set_overwrite_module_params_on_conversion", + "torch.__getattr__", + "torch._assert", + "torch._check_is_size", + "torch._compile._disable_dynamo", + "torch._functorch.apis.chunk_vmap", + "torch._functorch.batch_norm_replacement.batch_norm_without_running_stats", + "torch._functorch.batch_norm_replacement.replace_all_batch_norm_modules_", + "torch._functorch.deprecated.combine_state_for_ensemble", + "torch._functorch.deprecated.functionalize", + "torch._functorch.deprecated.get_warning", + "torch._functorch.deprecated.make_functional_with_buffers", + "torch._functorch.deprecated.make_functional", + "torch._functorch.deprecated.setup_docs", + "torch._functorch.deprecated.warn_deprecated", + "torch._functorch.eager_transforms._any_differentiable", + "torch._functorch.eager_transforms._autograd_grad", + "torch._functorch.eager_transforms._set_tensor_requires_grad", + "torch._functorch.eager_transforms._is_differentiable", + "torch._functorch.eager_transforms._maybe_unwrap_functional_tensor", + "torch._functorch.eager_transforms._maybe_wrap_functional_tensor", + "torch._functorch.eager_transforms._unwrap_all_tensors_from_functional", + "torch._functorch.eager_transforms._wrap_all_tensors_to_functional", + "torch._functorch.eager_transforms.assert_flat_tuple_of_tensors", + "torch._functorch.eager_transforms.functionalize", + "torch._functorch.eager_transforms.lazy_dynamo_disable", + "torch._functorch.eager_transforms.noop", + "torch._functorch.utils.enable_single_level_autograd_function", + "torch._functorch.utils.exposed_in", + "torch._functorch.predispatch.lazy_load_decompositions", + "torch._functorch.predispatch._vmap_increment_nesting", + "torch._functorch.predispatch._vmap_decrement_nesting", + "torch._functorch.predispatch._add_batch_dim", + "torch._functorch.predispatch._remove_batch_dim", + "torch._functorch.predispatch._unwrap_for_grad", + "torch._functorch.predispatch._make_dual", + "torch._functorch.predispatch._unpack_dual", + "torch._guards.compile_context", + "torch._guards.detect_fake_mode", + "torch._guards.tracing", + "torch._higher_order_ops.map._has_potential_branch_input_alias", + "torch._higher_order_ops.map._has_potential_branch_input_mutation", + "torch._higher_order_ops.map._stack_pytree", + "torch._higher_order_ops.map._unstack_pytree", + "torch._higher_order_ops.map.create_fw_bw_graph", + "torch._higher_order_ops.map.map_autograd", + "torch._higher_order_ops.map.map_dense", + "torch._higher_order_ops.map.map_fake_tensor_mode", + "torch._higher_order_ops.map.map_functionalize", + "torch._higher_order_ops.map.map_proxy_torch_dispatch_mode", + "torch._higher_order_ops.map.map_wrapper", + "torch._higher_order_ops.map.trace_map", + "torch._higher_order_ops.out_dtype.elementwise_dtypes", + "torch._higher_order_ops.out_dtype.is_int_mm", + "torch._higher_order_ops.out_dtype.out_dtype_dense", + "torch._higher_order_ops.out_dtype.out_dtype_fake_tensor_mode", + "torch._higher_order_ops.out_dtype.out_dtype_fallback", + "torch._higher_order_ops.out_dtype.out_dtype_func", + "torch._higher_order_ops.out_dtype.out_dtype_proxy", + "torch._higher_order_ops.out_dtype.trace_out_dtype", + "torch._higher_order_ops.utils.autograd_not_implemented_inner", + "torch._higher_order_ops.utils.autograd_not_implemented", + "torch._linalg_utils._symeig", + "torch._linalg_utils.basis", + "torch._linalg_utils.bform", + "torch._linalg_utils.eig", + "torch._linalg_utils.get_floating_dtype", + "torch._linalg_utils.is_sparse", + "torch._linalg_utils.lstsq", + "torch._linalg_utils.matmul", + "torch._linalg_utils.matrix_rank", + "torch._linalg_utils.qform", + "torch._linalg_utils.solve", + "torch._linalg_utils.symeig", + "torch._load_global_deps", + "torch._lowrank._svd_lowrank", + "torch._lowrank.get_approximate_basis", + "torch._lowrank.pca_lowrank", + "torch._lowrank.svd_lowrank", + "torch._preload_cuda_deps", + "torch._register_device_module", + "torch._utils._dummy_type", + "torch._utils._flatten_dense_tensors", + "torch._utils._unflatten_dense_tensors", + "torch._weights_only_unpickler._get_allowed_globals", + "torch._weights_only_unpickler.load", + "torch.accelerator.current_accelerator", + "torch.accelerator.current_device_index", + "torch.accelerator.current_stream", + "torch.accelerator.device_count", + "torch.accelerator.is_available", + "torch.accelerator.set_stream", + "torch.accelerator.synchronize", + "torch.amp.autocast_mode.autocast_decorator", + "torch.amp.autocast_mode.custom_bwd", + "torch.amp.autocast_mode.custom_fwd", + "torch.are_deterministic_algorithms_enabled", + "torch.atleast_1d", + "torch.atleast_2d", + "torch.atleast_3d", + "torch.autograd._calculate_shape", + "torch.autograd._is_checkpoint_valid", + "torch.autograd._profiler_enabled", + "torch.autograd._make_grads", + "torch.autograd._register_py_tensor_class_for_device", + "torch.autograd._tensor_or_tensors_to_tuple", + "torch.autograd.forward_ad._maybe_load_decompositions", + "torch.autograd.function._iter_filter", + "torch.autograd.function._iter_jit_values", + "torch.autograd.function._iter_None_tensors", + "torch.autograd.function._iter_tensors_permissive", + "torch.autograd.function._iter_tensors", + "torch.autograd.function._jit_unwrap_structured", + "torch.autograd.function._map_tensor_data", + "torch.autograd.function._nested_map", + "torch.autograd.function._unflatten", + "torch.autograd.function.once_differentiable", + "torch.autograd.function.traceable", + "torch.autograd.functional._as_tuple_nocheck", + "torch.autograd.functional._as_tuple", + "torch.autograd.functional._autograd_grad", + "torch.autograd.functional._check_requires_grad", + "torch.autograd.functional._construct_standard_basis_for", + "torch.autograd.functional._fill_in_zeros", + "torch.autograd.functional._grad_postprocess", + "torch.autograd.functional._grad_preprocess", + "torch.autograd.functional._jacfwd", + "torch.autograd.functional._tuple_postprocess", + "torch.autograd.functional._validate_v", + "torch.autograd.functional.hessian", + "torch.autograd.functional.hvp", + "torch.autograd.functional.jacobian", + "torch.autograd.functional.jvp", + "torch.autograd.functional.vhp", + "torch.autograd.functional.vjp", + "torch.autograd.graph._get_sid", + "torch.autograd.graph._get_tid", + "torch.autograd.graph.allow_mutation_on_saved_tensors", + "torch.autograd.graph.get_gradient_edge", + "torch.autograd.graph.increment_version", + "torch.autograd.graph.register_multi_grad_hook", + "torch.autograd.variable", + "torch.backends.__allow_nonbracketed_mutation", + "torch.backends.cpu.get_cpu_capability", + "torch.backends.cuda.can_use_efficient_attention", + "torch.backends.cuda.can_use_flash_attention", + "torch.backends.cuda.can_use_cudnn_attention", + "torch.backends.cuda.enable_flash_sdp", + "torch.backends.cuda.enable_math_sdp", + "torch.backends.cuda.allow_fp16_bf16_reduction_math_sdp", + "torch.backends.cuda.enable_mem_efficient_sdp", + "torch.backends.cuda.flash_sdp_enabled", + "torch.backends.cuda.is_built", + "torch.backends.cuda.is_flash_attention_available", + "torch.backends.cuda.math_sdp_enabled", + "torch.backends.cuda.fp16_bf16_reduction_math_sdp_allowed", + "torch.backends.cuda.mem_efficient_sdp_enabled", + "torch.backends.cuda.cudnn_sdp_enabled", + "torch.backends.cuda.enable_cudnn_sdp", + "torch.backends.cuda.preferred_blas_library", + "torch.backends.cuda.preferred_linalg_library", + "torch.backends.cuda.preferred_rocm_fa_library", + "torch.backends.cuda.sdp_kernel", + "torch.backends.cudnn._init", + "torch.backends.cudnn.flags", + "torch.backends.cudnn.is_acceptable", + "torch.backends.cudnn.is_available", + "torch.backends.cudnn.set_flags", + "torch.backends.cudnn.version", + "torch.backends.disable_global_flags", + "torch.backends.flags_frozen", + "torch.backends.mkl.is_available", + "torch.backends.mkldnn.flags", + "torch.backends.mkldnn.is_available", + "torch.backends.mkldnn.set_flags", + "torch.backends.mps._init", + "torch.backends.mps.is_available", + "torch.backends.mps.is_built", + "torch.backends.mps.is_macos13_or_newer", + "torch.backends.openmp.is_available", + "torch.backends.quantized._get_qengine_id", + "torch.backends.quantized._get_qengine_str", + "torch.block_diag", + "torch.broadcast_tensors", + "torch.cartesian_prod", + "torch.cdist", + "torch.chain_matmul", + "torch.compile", + "torch.compiled_with_cxx11_abi", + "torch.cpu._init_amx", + "torch.cpu.get_capabilities", + "torch.cpu.current_device", + "torch.cpu.current_stream", + "torch.cpu.device_count", + "torch.cpu.is_available", + "torch.cpu.set_device", + "torch.cpu.stream", + "torch.cpu.synchronize", + "torch.cuda._check_capability", + "torch.cuda._check_cubins", + "torch.cuda._device_count_amdsmi", + "torch.cuda._device_count_nvml", + "torch.cuda._get_amdsmi_handler", + "torch.cuda._get_amdsmi_device_index", + "torch.cuda._get_device", + "torch.cuda._get_generator", + "torch.cuda._get_nvml_device_index", + "torch.cuda._get_pynvml_handler", + "torch.cuda._get_rng_state_offset", + "torch.cuda._is_compiled", + "torch.cuda._lazy_call", + "torch.cuda._lazy_init", + "torch.cuda._memory_viz._block_extra_legacy", + "torch.cuda._memory_viz._block_extra", + "torch.cuda._memory_viz._format_size", + "torch.cuda._memory_viz._format_viz", + "torch.cuda._memory_viz._frame_filter", + "torch.cuda._memory_viz._frame_fmt", + "torch.cuda._memory_viz._frames_fmt", + "torch.cuda._memory_viz._profile_to_snapshot", + "torch.cuda._memory_viz._report_free", + "torch.cuda._memory_viz._write_blocks", + "torch.cuda._memory_viz.calc_active", + "torch.cuda._memory_viz.compare", + "torch.cuda._memory_viz.format_flamegraph", + "torch.cuda._memory_viz.memory", + "torch.cuda._memory_viz.profile_plot", + "torch.cuda._memory_viz.segment_plot", + "torch.cuda._memory_viz.segments", + "torch.cuda._memory_viz.segsum", + "torch.cuda._memory_viz.trace_plot", + "torch.cuda._memory_viz.trace", + "torch.cuda._nvml_based_avail", + "torch.cuda._parse_visible_devices", + "torch.cuda._raw_device_count_amdsmi", + "torch.cuda._raw_device_count_nvml", + "torch.cuda._raw_device_uuid_amdsmi", + "torch.cuda._raw_device_uuid_nvml", + "torch.cuda._register_triton_kernels", + "torch.cuda._set_rng_state_offset", + "torch.cuda._set_stream_by_id", + "torch.cuda._sleep", + "torch.cuda._transform_uuid_to_ordinals", + "torch.cuda._utils._get_device_index", + "torch.cuda.amp.autocast_mode._cast", + "torch.cuda.amp.autocast_mode.custom_bwd", + "torch.cuda.amp.autocast_mode.custom_fwd", + "torch.cuda.amp.common.amp_definitely_not_available", + "torch.amp.grad_scaler._refresh_per_optimizer_state", + "torch.cuda.can_device_access_peer", + "torch.cuda.check_error", + "torch.cuda.clock_rate", + "torch.cuda.cudart", + "torch.cuda.current_blas_handle", + "torch.cuda.current_solver_handle", + "torch.cuda.current_stream", + "torch.cuda.default_stream", + "torch.cuda.device_count", + "torch.cuda.device_memory_used", + "torch.cuda.get_arch_list", + "torch.cuda.get_device_capability", + "torch.cuda.get_device_name", + "torch.cuda.get_device_properties", + "torch.cuda.get_gencode_flags", + "torch.cuda.get_sync_debug_mode", + "torch.cuda.synchronize", + "torch.cuda.graphs.graph_pool_handle", + "torch.cuda.graphs.is_current_stream_capturing", + "torch.cuda.graphs.make_graphed_callables", + "torch.cuda.init", + "torch.cuda.ipc_collect", + "torch.cuda.is_available", + "torch.cuda.is_bf16_supported", + "torch.cuda.is_initialized", + "torch.cuda.jiterator._create_jit_fn", + "torch.cuda.jiterator._create_multi_output_jit_fn", + "torch.cuda.memory_usage", + "torch.cuda.memory._dump_snapshot", + "torch.cuda.memory._get_current_allocator", + "torch.cuda.memory._host_allocator", + "torch.cuda.memory._record_memory_history_impl", + "torch.cuda.memory._record_memory_history_legacy", + "torch.cuda.memory._record_memory_history", + "torch.cuda.memory._save_memory_usage", + "torch.cuda.memory._save_segment_usage", + "torch.cuda.memory._set_allocator_settings", + "torch.cuda.memory._snapshot", + "torch.cuda.memory.caching_allocator_alloc", + "torch.cuda.memory.caching_allocator_delete", + "torch.cuda.memory.caching_allocator_enable", + "torch.cuda.memory.change_current_allocator", + "torch.cuda.memory.empty_cache", + "torch.cuda.memory.get_allocator_backend", + "torch.cuda.memory.get_per_process_memory_fraction", + "torch.cuda.memory.host_memory_stats_as_nested_dict", + "torch.cuda.memory.host_memory_stats", + "torch.cuda.memory.list_gpu_processes", + "torch.cuda.memory.max_memory_allocated", + "torch.cuda.memory.max_memory_cached", + "torch.cuda.memory.max_memory_reserved", + "torch.cuda.memory.mem_get_info", + "torch.cuda.memory.memory_allocated", + "torch.cuda.memory.memory_cached", + "torch.cuda.memory.memory_reserved", + "torch.cuda.memory.memory_snapshot", + "torch.cuda.memory.memory_stats_as_nested_dict", + "torch.cuda.memory.memory_stats", + "torch.cuda.memory.memory_summary", + "torch.cuda.memory.reset_accumulated_host_memory_stats", + "torch.cuda.memory.reset_accumulated_memory_stats", + "torch.cuda.memory.reset_max_memory_allocated", + "torch.cuda.memory.reset_max_memory_cached", + "torch.cuda.memory.reset_peak_host_memory_stats", + "torch.cuda.memory.reset_peak_memory_stats", + "torch.cuda.memory.set_per_process_memory_fraction", + "torch.cuda.nccl._check_sequence_type", + "torch.cuda.nccl.all_gather", + "torch.cuda.nccl.all_reduce", + "torch.cuda.nccl.broadcast", + "torch.cuda.nccl.init_rank", + "torch.cuda.nccl.is_available", + "torch.cuda.nccl.reduce_scatter", + "torch.cuda.nccl.reduce", + "torch.cuda.nccl.unique_id", + "torch.cuda.nccl.version", + "torch.cuda.nvtx.mark", + "torch.cuda.nvtx.range_end", + "torch.cuda.nvtx.range_pop", + "torch.cuda.nvtx.range_push", + "torch.cuda.nvtx.range_start", + "torch.cuda.nvtx.range", + "torch.cuda.power_draw", + "torch.cuda.profiler.init", + "torch.cuda.profiler.profile", + "torch.cuda.profiler.start", + "torch.cuda.profiler.stop", + "torch.cuda.random.get_rng_state_all", + "torch.cuda.random.initial_seed", + "torch.cuda.random.seed_all", + "torch.cuda.random.seed", + "torch.cuda.random.set_rng_state_all", + "torch.cuda.set_stream", + "torch.cuda.set_sync_debug_mode", + "torch.cuda.stream", + "torch.cuda.temperature", + "torch.cuda.utilization", + "torch.einsum", + "torch.functional._check_list_size", + "torch.functional._consecutive_return_counts", + "torch.functional._consecutive_return_inverse_false", + "torch.functional._consecutive_return_inverse_true", + "torch.functional._consecutive_return_inverse", + "torch.functional._consecutive_return_output", + "torch.functional._lu_impl", + "torch.functional._lu_no_infos", + "torch.functional._lu_with_infos", + "torch.functional._meshgrid", + "torch.functional._return_counts", + "torch.functional._return_inverse_false", + "torch.functional._return_inverse_true", + "torch.functional._return_inverse", + "torch.functional._return_output", + "torch.functional._unique_consecutive_impl", + "torch.functional._unique_impl", + "torch.functional._unravel_index", + "torch.functional.broadcast_shapes", + "torch.functional.lu", + "torch.functional.unique", + "torch.functional.unravel_index", + "torch.futures.collect_all", + "torch.futures.wait_all", + "torch.fx.experimental.const_fold.split_const_subgraphs", + "torch.fx.experimental.proxy_tensor.make_fx", + "torch.get_deterministic_debug_mode", + "torch.get_float32_matmul_precision", + "torch.is_deterministic_algorithms_warn_only_enabled", + "torch.is_storage", + "torch.is_tensor", + "torch.is_warn_always_enabled", + "torch.masked._ops._any", + "torch.masked._ops._apply_docstring_templates", + "torch.masked._ops._canonical_dim", + "torch.masked._ops._combine_input_and_mask", + "torch.masked._ops._generate_docstring", + "torch.masked._ops._input_mask", + "torch.masked._ops._output_mask", + "torch.masked._ops._reduction_identity", + "torch.masked._ops._sparse_coo_flatten_indices", + "torch.masked._ops._sparse_coo_scatter_reduction_helper", + "torch.masked._ops._sparse_coo_where", + "torch.masked._ops._sparse_csr_segment_reduction_helper", + "torch.masked._ops._sparse_csr_where", + "torch.masked._ops._std_var", + "torch.masked._ops._where", + "torch.masked._ops.amax", + "torch.masked._ops.amin", + "torch.masked._ops.argmax", + "torch.masked._ops.argmin", + "torch.masked._ops.corresponding_real_dtype", + "torch.masked._ops.cumprod", + "torch.masked._ops.cumsum", + "torch.masked._ops.log_softmax", + "torch.masked._ops.logaddexp", + "torch.masked._ops.logsumexp", + "torch.masked._ops.mean", + "torch.masked._ops.median", + "torch.masked._ops.norm", + "torch.masked._ops.normalize", + "torch.masked._ops.prod", + "torch.masked._ops.softmax", + "torch.masked._ops.softmin", + "torch.masked._ops.std", + "torch.masked._ops.sum", + "torch.masked._ops.var", + "torch.meshgrid", + "torch.mps._get_default_mps_generator", + "torch.mps.current_allocated_memory", + "torch.mps.driver_allocated_memory", + "torch.mps.empty_cache", + "torch.mps.get_rng_state", + "torch.mps.manual_seed", + "torch.mps.profiler.profile", + "torch.mps.profiler.start", + "torch.mps.profiler.stop", + "torch.mps.seed", + "torch.mps.set_per_process_memory_fraction", + "torch.mps.set_rng_state", + "torch.mps.synchronize", + "torch.nested._internal.nested_tensor.buffer_from_jagged", + "torch.nested._internal.nested_tensor.get_tensor_symint", + "torch.nested._internal.nested_tensor.is_expandable_to", + "torch.nested._internal.nested_tensor.jagged_from_list", + "torch.nested._internal.nested_tensor.jagged_from_tensor_and_lengths", + "torch.nested._internal.nested_tensor.nested_view_from_values_offsets", + "torch.nested._internal.nested_tensor.nested_view_from_values_offsets_lengths", + "torch.nested.as_nested_tensor", + "torch.nested.narrow", + "torch.nested.nested_tensor", + "torch.nn._reduction.get_enum", + "torch.nn._reduction.legacy_get_enum", + "torch.nn._reduction.legacy_get_string", + "torch.nn.factory_kwargs", + "torch.nn.functional.adaptive_avg_pool2d", + "torch.nn.functional.adaptive_avg_pool3d", + "torch.nn.functional.adaptive_max_pool1d_with_indices", + "torch.nn.functional.adaptive_max_pool1d", + "torch.nn.functional.adaptive_max_pool2d_with_indices", + "torch.nn.functional.adaptive_max_pool2d", + "torch.nn.functional.adaptive_max_pool3d_with_indices", + "torch.nn.functional.adaptive_max_pool3d", + "torch.nn.functional.affine_grid", + "torch.nn.functional.alpha_dropout", + "torch.nn.functional.assert_int_or_pair", + "torch.nn.functional.batch_norm", + "torch.nn.functional.binary_cross_entropy_with_logits", + "torch.nn.functional.binary_cross_entropy", + "torch.nn.functional.celu", + "torch.nn.functional.cosine_embedding_loss", + "torch.nn.functional.cross_entropy", + "torch.nn.functional.ctc_loss", + "torch.nn.functional.dropout", + "torch.nn.functional.dropout1d", + "torch.nn.functional.dropout2d", + "torch.nn.functional.dropout3d", + "torch.nn.functional.elu", + "torch.nn.functional.embedding_bag", + "torch.nn.functional.embedding", + "torch.nn.functional.feature_alpha_dropout", + "torch.nn.functional.fold", + "torch.nn.functional.fractional_max_pool2d_with_indices", + "torch.nn.functional.fractional_max_pool2d", + "torch.nn.functional.fractional_max_pool3d_with_indices", + "torch.nn.functional.fractional_max_pool3d", + "torch.nn.functional.gaussian_nll_loss", + "torch.nn.functional.glu", + "torch.nn.functional.grid_sample", + "torch.nn.functional.group_norm", + "torch.nn.functional.gumbel_softmax", + "torch.nn.functional.hardsigmoid", + "torch.nn.functional.hardswish", + "torch.nn.functional.hardtanh", + "torch.nn.functional.hinge_embedding_loss", + "torch.nn.functional.huber_loss", + "torch.nn.functional.instance_norm", + "torch.nn.functional.interpolate", + "torch.nn.functional.kl_div", + "torch.nn.functional.l1_loss", + "torch.nn.functional.layer_norm", + "torch.nn.functional.leaky_relu", + "torch.nn.functional.local_response_norm", + "torch.nn.functional.log_softmax", + "torch.nn.functional.lp_pool1d", + "torch.nn.functional.lp_pool2d", + "torch.nn.functional.margin_ranking_loss", + "torch.nn.functional.max_pool1d_with_indices", + "torch.nn.functional.max_pool1d", + "torch.nn.functional.max_pool2d_with_indices", + "torch.nn.functional.max_pool2d", + "torch.nn.functional.max_pool3d_with_indices", + "torch.nn.functional.max_pool3d", + "torch.nn.functional.max_unpool1d", + "torch.nn.functional.max_unpool2d", + "torch.nn.functional.max_unpool3d", + "torch.nn.functional.mish", + "torch.nn.functional.mse_loss", + "torch.nn.functional.multi_head_attention_forward", + "torch.nn.functional.multi_margin_loss", + "torch.nn.functional.multilabel_margin_loss", + "torch.nn.functional.multilabel_soft_margin_loss", + "torch.nn.functional.nll_loss", + "torch.nn.functional.normalize", + "torch.nn.functional.poisson_nll_loss", + "torch.nn.functional.relu", + "torch.nn.functional.relu6", + "torch.nn.functional.rrelu", + "torch.nn.functional.selu", + "torch.nn.functional.sigmoid", + "torch.nn.functional.silu", + "torch.nn.functional.smooth_l1_loss", + "torch.nn.functional.soft_margin_loss", + "torch.nn.functional.softmax", + "torch.nn.functional.softmin", + "torch.nn.functional.softsign", + "torch.nn.functional.tanh", + "torch.nn.functional.tanhshrink", + "torch.nn.functional.triplet_margin_loss", + "torch.nn.functional.unfold", + "torch.nn.functional.upsample_bilinear", + "torch.nn.functional.upsample_nearest", + "torch.nn.functional.upsample", + "torch.nn.grad._pair", + "torch.nn.grad._single", + "torch.nn.grad._triple", + "torch.nn.grad.conv1d_input", + "torch.nn.grad.conv1d_weight", + "torch.nn.grad.conv2d_input", + "torch.nn.grad.conv2d_weight", + "torch.nn.grad.conv3d_input", + "torch.nn.grad.conv3d_weight", + "torch.nn.modules.activation._is_make_fx_tracing", + "torch.nn.modules.utils._list_with_default", + "torch.nn.modules.utils._ntuple", + "torch.nn.modules.utils._quadruple", + "torch.nn.modules.utils._reverse_repeat_tuple", + "torch.nn.modules.utils.consume_prefix_in_state_dict_if_present", + "torch.nn.parameter.is_lazy", + "torch.norm", + "torch.quantization.default_eval_fn", + "torch.random._seed_custom_device", + "torch.random.fork_rng", + "torch.random.initial_seed", + "torch.random.seed", + "torch.return_types.pytree_register_structseq", + "torch.set_default_dtype", + "torch.set_default_tensor_type", + "torch.set_deterministic_debug_mode", + "torch.set_float32_matmul_precision", + "torch.set_warn_always", + "torch.signal.windows.windows._add_docstr", + "torch.signal.windows.windows._window_function_checks", + "torch.signal.windows.windows.bartlett", + "torch.signal.windows.windows.blackman", + "torch.signal.windows.windows.cosine", + "torch.signal.windows.windows.exponential", + "torch.signal.windows.windows.gaussian", + "torch.signal.windows.windows.general_cosine", + "torch.signal.windows.windows.general_hamming", + "torch.signal.windows.windows.hamming", + "torch.signal.windows.windows.hann", + "torch.signal.windows.windows.kaiser", + "torch.signal.windows.windows.merge_dicts", + "torch.signal.windows.windows.nuttall", + "torch.signal.windows.windows.parse_kwargs", + "torch.sparse.semi_structured.to_sparse_semi_structured", + "torch.sparse.sum", + "torch.split", + "torch.stft", + "torch.sym_float", + "torch.sym_int", + "torch.sym_ite", + "torch.sym_max", + "torch.sym_min", + "torch.sym_not", + "torch.tensordot", + "torch.unique_consecutive", + "torch.use_deterministic_algorithms", + "torch.xpu._get_device", + "torch.xpu._get_generator", + "torch.xpu._get_rng_state_offset", + "torch.xpu._is_compiled", + "torch.xpu._lazy_call", + "torch.xpu._lazy_init", + "torch.xpu._set_rng_state_offset", + "torch.xpu._set_stream_by_id", + "torch.xpu._utils._get_device_index", + "torch.xpu.current_device", + "torch.xpu.current_stream", + "torch.xpu.device_count", + "torch.xpu.get_arch_list", + "torch.xpu.get_device_capability", + "torch.xpu.get_device_name", + "torch.xpu.get_device_properties", + "torch.xpu.get_gencode_flags", + "torch.xpu.get_stream_from_external", + "torch.xpu.init", + "torch.xpu.is_available", + "torch.xpu.is_bf16_supported", + "torch.xpu.is_initialized", + "torch.xpu.memory.empty_cache", + "torch.xpu.memory.max_memory_allocated", + "torch.xpu.memory.max_memory_reserved", + "torch.xpu.memory.mem_get_info", + "torch.xpu.memory.memory_allocated", + "torch.xpu.memory.memory_reserved", + "torch.xpu.memory.memory_stats_as_nested_dict", + "torch.xpu.memory.memory_stats", + "torch.xpu.memory.reset_accumulated_memory_stats", + "torch.xpu.memory.reset_peak_memory_stats", + "torch.xpu.random.initial_seed", + "torch.xpu.random.seed_all", + "torch.xpu.random.seed", + "torch.xpu.set_stream", + "torch.xpu.stream", + "torch.xpu.synchronize", + ], + TorchInGraphFunctionVariable, +) + + +torch_name_rule_map = [ + manual_torch_name_rule_map, + torch_c_binding_in_graph_functions, + torch_non_c_binding_in_graph_functions, +] + + +""" +Generate the torch object - Dynamo tracing rule (the wrapping variable) map. +""" + + +@functools.cache +def get_torch_obj_rule_map() -> dict[Any, type["VariableTracker"]]: + d: dict[Any, type[VariableTracker]] = {} + for m in torch_name_rule_map: + for k, v in m.items(): # type: ignore[attr-defined] + if ".py#" not in k: + obj = load_object(k) + else: + torch_dir = _module_dir(torch) + if torch_dir is None: + continue + obj = torch_dir + k[len("torch/") :] + if obj is not None: + if is_lru_cache_wrapped_function(obj): + obj = obj.__wrapped__ + if obj in d and d[obj] != v: + raise AssertionError( + f"Duplicate torch object {obj} with different rules: {v}, {d[obj]}" + ) + else: + d[obj] = v + return d + + +def _load_obj_from_str(fully_qualified_name: str) -> Any: + module, obj_name = fully_qualified_name.rsplit(".", maxsplit=1) + return getattr(importlib.import_module(module), obj_name) + + +""" +Load string represented torch objects. +""" + + +def load_object(name: str) -> Any: + try: + x = name.split("#") + if len(x) == 2: + obj = _load_obj_from_str(x[0]) + val = getattr(obj, x[1]) + else: + if len(x) != 1: + raise AssertionError(f"Invalid obj name {name}") + val = _load_obj_from_str(x[0]) + val = unwrap_if_wrapper(val) + except (AttributeError, ImportError): + val = None + return val + + +""" +Get all torch.Tensor methods which are allowed to be in graph functions. +""" + + +@functools.cache +def get_tensor_method() -> frozenset[Any]: + disallowed_tensor_methods = {"__new__", "_make_wrapper_subclass", "_make_subclass"} + s = set() + for name in dir(torch.Tensor): + method = getattr(torch.Tensor, name) + if ( + isinstance( + method, + ( + types.MethodDescriptorType, + types.WrapperDescriptorType, + types.BuiltinFunctionType, + ), + ) + and name not in disallowed_tensor_methods + ): + s.add(method) + for name, method in torch._C.TensorBase.__dict__.items(): + if ( + isinstance( + method, + ( + types.MethodDescriptorType, + types.WrapperDescriptorType, + types.BuiltinFunctionType, + ), + ) + and name not in disallowed_tensor_methods + ): + s.add(method) + + # mlazos: these are functions which we handle specially in TensorVariable + s.add(torch.Tensor.__contains__) # type: ignore[arg-type] + s.add(torch.Tensor.register_hook) # type: ignore[arg-type] + return frozenset(s) + + +""" +Return if a torch object is ATen op or torch.Tensor method. +""" + + +def is_aten_op_or_tensor_method(obj: object) -> bool: + return obj in get_tensor_method() or isinstance( + obj, + (torch._ops.OpOverloadPacket, torch._ops.OpOverload), + ) + + +class FunctionIdSet: + """ + Track a set of `id()`s of objects which are either allowed or not + allowed to go into the generated FX graph. Use to test for torch.*, + numpy.*, builtins.*, etc. + + Support user modification to permit customization of what can be + added to the graph and what will cause a graph break. + """ + + function_ids: set[int] | None = None + function_names: dict[int, str] | None = None + + def __init__( + self, lazy_initializer: Callable[[], dict[int, str] | set[int]] + ) -> None: + self.lazy_initializer = lazy_initializer + + def __call__(self) -> set[int]: + if self.function_ids is None: + value = self.lazy_initializer() + if isinstance(value, dict): + self.function_ids = set(value.keys()) + self.function_names = value + else: + if not isinstance(value, set): + raise AssertionError( + f"expected lazy_initializer to return a dict or set, got {type(value)}" + ) + self.function_ids = value + return self.function_ids + + def get_name(self, idx: int, default: str) -> str: + self() # lazy init + if self.function_names is None: + raise AssertionError( + "function_names is None; lazy_initializer returned a set, not a dict" + ) + return self.function_names.get(idx, default) + + def add(self, idx: int) -> None: + function_ids = self() # lazy init + function_ids.add(idx) + + def remove(self, idx: int) -> None: + function_ids = self() + if idx in function_ids: + function_ids.remove(idx) + + def __contains__(self, idx: int) -> bool: + return idx in self() + + +@FunctionIdSet +def _allowed_callable_ids() -> dict[int, str]: + rv: dict[int, str] = {} + return rv + + +@FunctionIdSet +def _leaf_function_ids() -> dict[int, str]: + rv: dict[int, str] = {} + return rv + + +@FunctionIdSet +def _disallowed_callable_ids() -> dict[int, str]: + rv: dict[int, str] = {} + return rv + + +@FunctionIdSet +def _nonstrict_trace_callable_ids() -> dict[int, str]: + rv: dict[int, str] = {} + return rv + + +@FunctionIdSet +def _builtin_function_ids() -> dict[int, str]: + # See also torch/_dynamo/polyfills/loader.py, which removes items in _builtin_function_ids + rv = { + id(v): f"builtins.{k}" + for k, v in builtins.__dict__.items() + if not k.startswith("_") and callable(v) + } + rv.update( + { + id(v): f"operator.{k}" + for k, v in operator.__dict__.items() + if not k.startswith("_") and callable(v) + } + ) + rv[id(builtins.__build_class__)] = "builtins.__build_class__" + return rv + + +@FunctionIdSet +def _polyfilled_function_ids() -> set[int]: + # See also @torch._dynamo.decorators.substitute_in_graph(...), which adds items in _polyfilled_function_ids + return set() + + +@FunctionIdSet +def _numpy_function_ids() -> dict[int, str]: + unsupported_funcs = { + "seed", + "ranf", + "get_bit_generator", + "RandomState", + "set_bit_generator", + "sample", + } + + def is_supported(k: str, v: Any, mod: Any) -> bool: + if not callable(v): + return False + if not getattr(v, "__module__", None): + return True + if v.__module__ == mod.__name__: + return True + if ( + v.__module__ == "numpy.random.mtrand" + and mod.__name__ == "numpy.random" + and k not in unsupported_funcs + ): + return True + return False + + rv = {} + for mod in NP_SUPPORTED_MODULES: + for k, v in mod.__dict__.items(): + if is_supported(k, v, mod): + rv[id(v)] = f"{mod.__name__}.{k}" + return rv + + +@FunctionIdSet +def _builtin_constant_ids() -> dict[int, str]: + """ + Collects constant builtins by eliminating callable items. + """ + rv = { + id(v): f"builtins.{k}" + for k, v in builtins.__dict__.items() + if not k.startswith("_") and not callable(v) + } + return rv + + +_lazy_module_init: dict[str, list[Callable[[], None]]] = defaultdict(list) + + +def add_module_init_func(name: str, init_func: Callable[[], None]) -> None: + """Register a module without eagerly importing it""" + # If the module is already imported, eagerly run init + if "." in name: + raise AssertionError(f"Expected a root module name, but got {name}") + if name in _lazy_module_init: + raise AssertionError(f"Module init function already registered for {name}") + _lazy_module_init[name].append(init_func) + + +def _maybe_init_lazy_module(obj: object) -> None: + module = getattr(obj, "__module__", None) + if module is None: + return + + base_module = module.split(".")[0] + init_funcs = _lazy_module_init.pop(base_module, None) + if init_funcs is not None: + for fn in init_funcs: + fn() + + +def is_callable_allowed(obj: object) -> bool: + _maybe_init_lazy_module(obj) + return id(obj) in _allowed_callable_ids + + +def is_nonstrict_trace_callable(obj: object) -> bool: + _maybe_init_lazy_module(obj) + return id(obj) in _nonstrict_trace_callable_ids + + +def is_leaf_function(obj: object) -> bool: + _maybe_init_lazy_module(obj) + return id(obj) in _leaf_function_ids + + +def is_callable_disallowed(obj: object) -> bool: + _maybe_init_lazy_module(obj) + return id(obj) in _disallowed_callable_ids + + +def is_forbidden(obj: object) -> bool: + _maybe_init_lazy_module(obj) + return inspect.getattr_static(obj, "_dynamo_forbidden", False) + + +def is_builtin_callable(obj: object) -> bool: + # See also torch/_dynamo/polyfills/loader.py, which removes items in _builtin_function_ids + return id(obj) in _builtin_function_ids + + +def is_builtin_constant(obj: object) -> bool: + return id(obj) in _builtin_constant_ids + + +def is_polyfilled_callable(obj: object) -> bool: + # See also @torch._dynamo.decorators.substitute_in_graph(...), which adds items in _polyfilled_function_ids + return id(obj) in _polyfilled_function_ids + + +def is_numpy(obj: object) -> bool: + if np is None: + return False + return isinstance(obj, (np.ndarray, np.generic)) or id(obj) in _numpy_function_ids + + +def is_numpy_dtype(obj: object) -> bool: + if np is None: + return False + return isinstance(obj, np.dtype) + + +def is_numpy_type_info(obj: object) -> bool: + if np is None: + return False + return isinstance(obj, (np.finfo, np.iinfo)) + + +BUILTIN_SKIPLIST = ( + abc, + copy, + importlib, + random, + re, + linecache, +) + +# Builtin modules that should be skipped at the top-level (PEP 523 frame +# evaluation) but inlined when called from code dynamo is already tracing. +# For example, copy.deepcopy should be inlined when the user calls it inside +# a compiled function, but copy module frames should be skipped when they +# appear as top-level frames (e.g. called internally by autograd). +BUILTIN_INLINE_WHEN_CALLED: set[str] = set() + +# third party libraries skiplist is defined by str, because users may not use these libraries. +# we should use lazy import & skip in the future. +THIRDPARTY_SKIPLIST = ( + "fx2trt_oss", + "hypothesis", + "networkx", + "numpy", + "onnx", + "onnxruntime", + "onnx_tf", + "pandas", + "sklearn", + "tabulate", + "tensorflow", + "tensorrt", + "torch2trt", + "tqdm", + "tree", + "tvm", + "xarray", +) + + +def _as_posix_path(path: str) -> str: + posix_path = Path(os.path.normpath(path)).as_posix() + # os.path.normpath and pathlib.Path remove trailing slash, so we need to add it back + if path.endswith((os.path.sep, "/")): + posix_path += "/" + return posix_path + + +def _strip_init_py(s: str) -> str: + suffix = "__init__.py" + s = s.removesuffix(suffix) + return _as_posix_path(s) + + +def _module_dir(m: types.ModuleType) -> str | None: + # Protect against a module not exporting __file__ - this can happen for + # frozen modules, for example. + file = getattr(m, "__file__", None) + return file and _strip_init_py(file) + + +# These are legacy workarounds, don't add new modules to this list. +# Please use the MOD_INLINELIST instead to force inline functions under particular modules. +# +# NB: The only thing that is different about MOD_INLINELIST and LEGACY_MOD_INLINELIST +# is the behavior of a function f2 in the module when called by a function f1 +# in a module in MOD_SKIPLIST (see MOD_SKIPLIST for more details) +# +# LEGACY_MOD_INLINELIST is the same thing as Dynamo's behavior on a module that +# is not in any *_INLINELIST or *_SKIPLIST. +# That being said, we prefer people to add things to MOD_INLINELIST over +# LEGACY_MOD_INLINELIST because it is less likely to break existing tests. +LEGACY_MOD_INLINELIST = { + "torch._dynamo.external_utils", + "torch._export.db.examples", + "torch._export.wrappers", + "torch._functorch.apis", + "torch._functorch.deprecated", + "torch._library.fake_class_registry", + "torch.utils._typing_utils", + "torch.nn.attention.flex_attention", + "torch.ao.quantization.stubs", + "torch.ao.quantization.pt2e.export_utils", + "torch.ao.quantization.pt2e.qat_utils", + "torch.ao.quantization.pt2e.representation.rewrite", + "torch.ao.quantization.pt2e.utils", + "torch.ao.quantization.quantizer.xnnpack_quantizer", + "torch.export.unflatten", +} + +if torch.distributed.is_available(): + LEGACY_MOD_INLINELIST |= { + "torch.distributed.tensor._api", + "torch.distributed.tensor.device_mesh", + "torch.distributed.device_mesh", + "torch.distributed.algorithms._checkpoint.checkpoint_wrapper", + "torch.distributed.tensor.parallel._data_parallel_utils", + "torch.distributed.tensor.parallel._utils", + "torch.distributed.tensor.parallel.style", + # we have to add replicate to LEGACY_MOD_INLINELIST to ensure + # the forward_hook won't be ignored. + "torch.distributed._composable.replicate", + } + +# Force inline functions under these modules, even they are in *_SKIPLIST. +# We are using python module name instead of file or directory object to avoid circular dependency. +# Please keep this sorted alphabetically. +# +# Btw, it is not "ideal" for something to be in MOD_INLINELIST. If Dynamo +# fully supports a module, then the ideal case is that it is not in +# any *_INLINELIST or *_SKIPLIST: then, the behavior of Dynamo is that +# it will always inline into functions in the module. +MOD_INLINELIST = [ + "torch._decomp", + "torch._dynamo._trace_wrapped_higher_order_op", + "torch._dynamo.compiled_autograd", + "torch._dynamo.comptime", + "torch._dynamo.polyfills", + "torch._dynamo.test_case", + "torch._export.non_strict_utils", + "torch._functorch._aot_autograd.subclass_parametrization", + "torch._functorch.autograd_function", + "torch._functorch.eager_transforms", + "torch._functorch.functional_call", + "torch._functorch.pyfunctorch", + "torch._functorch.vmap", + "torch._inductor.test_operators", + "torch._library.autograd", + "torch._library.custom_ops", + "torch._ops", + "torch._prims", + "torch._refs", + "torch._tensor", + "torch.amp.autocast_mode", + "torch.ao.nn", + "torch.ao.quantization.fx._decomposed", + "torch.autograd.function", + "torch.backends.cuda", + "torch.cuda.amp.autocast_mode", + "torch.distributions", + "torch.export._patches", + "torch.export._tree_utils", + "torch.export._unlift", + "torch.export._wrapper_utils", + "torch.fx._pytree", + "torch.fx._symbolic_trace", + "torch.fx.experimental.proxy_tensor", + "torch.fx.passes.shape_prop", + "torch.fx.traceback", + "torch.nn", + "torch.overrides", + "torch.random", + "torch.return_types", + "torch.sparse", + "torch.testing", + "torch.utils._content_store", + "torch.utils._contextlib", + "torch.utils._cxx_pytree", + "torch.utils._device", + "torch.utils._foreach_utils", + "torch.utils._ordered_set", + "torch.utils._python_dispatch", + "torch.utils._pytree", + "torch.utils.hooks", +] +if sorted(set(MOD_INLINELIST)) != MOD_INLINELIST: + raise AssertionError("MOD_INLINELIST must be sorted with no duplicates") +MOD_INLINELIST = set(MOD_INLINELIST) + + +if torch.distributed.is_available(): + MOD_INLINELIST.add("torch.distributed") + +# Modules in MOD_INLINELIST where nested graph breaks should be suppressed. +# These are large internal modules that are inlined for correctness but whose +# internal operations are not worth compiling as separate NGB subgraphs. +NGB_SUPPRESS_INLINELIST: set[str] = set() + +if torch.distributed.is_available(): + NGB_SUPPRESS_INLINELIST.add("torch.distributed") + +if not NGB_SUPPRESS_INLINELIST <= MOD_INLINELIST: + raise AssertionError( + "NGB_SUPPRESS_INLINELIST entries must also be in MOD_INLINELIST: " + f"{NGB_SUPPRESS_INLINELIST - MOD_INLINELIST}" + ) + + +# By default, all functions under these modules are skipped. +# All the other knobs +# (torch_name_rule_map, MOD_INLINELIST, LEGACY_MOD_INLINELIST) +# take precedence over this list; e.g. if a function is in +# MOD_INLINELIST and MOD_SKIPLIST, then it will be inlined. +# See "A note on skip/inline rules" for more details. +# +# The skip is NOT recursive. If a function f1 in a module in MOD_SKIPLIST +# calls out to another function f2 in some other module, then Dynamo's +# behavior (skip/inline) depends on what we've marked f2 as: +# - if f2 is a function in a module in MOD_SKIPLIST, then we skip f2 +# - if f2 is a function in a module in MOD_INLINELIST, then we skip f2 +# - if f2 is a function in a module in LEGACY_MOD_INLINELIST, then we inline f2 +# - if f2 is a function in a module not in any *_LIST, then we inline f2 +MOD_SKIPLIST = [ + "torch._VF", + "torch.__future__", + "torch.__init__", + "torch._awaits", + "torch._classes", + "torch._compile", + "torch._custom_op", + "torch._custom_ops", + "torch._decomp", + "torch._dispatch", + "torch._dynamo", + "torch._export", + "torch._functorch", + "torch._guards", + "torch._higher_order_ops.effects", + "torch._higher_order_ops.torchbind", + "torch._higher_order_ops.wrap", + "torch._inductor", + "torch._jit_internal", + "torch._lazy", + "torch._library", + "torch._linalg_utils", + "torch._lobpcg", + "torch._logging", + "torch._lowrank", + "torch._meta_registrations", + "torch._numpy", + "torch._ops", + "torch._prims", + "torch._prims_common", + "torch._python_dispatcher", + "torch._refs", + "torch._strobelight", + "torch._subclasses", + "torch._tensor", + "torch._tensor_str", + "torch._thread_safe_fork", + "torch._utils", + "torch._utils_internal", + "torch._vmap_internals", + "torch._weights_only_unpickler", + "torch.accelerator", + "torch.amp", + "torch.ao", + "torch.autograd", + "torch.backends", + "torch.compiler", + "torch.contrib", + "torch.cpu", + "torch.cuda", + "torch.distributed", + "torch.distributions", + "torch.export", + "torch.fb", + "torch.fft", + "torch.functional", + "torch.futures", + "torch.fx", + "torch.hub", + "torch.jit", + "torch.library", + "torch.linalg", + "torch.masked", + "torch.monitor", + "torch.mps", + "torch.mtia", + "torch.multiprocessing", + "torch.nested", + "torch.nn", + "torch.onnx", + "torch.overrides", + "torch.package", + "torch.profiler", + "torch.quantization", + "torch.quasirandom", + "torch.random", + "torch.serialization", + "torch.signal", + "torch.sparse", + "torch.special", + "torch.storage", + "torch.testing", + "torch.types", + "torch.utils", + "torch.xpu", +] + +if sorted(set(MOD_SKIPLIST)) != MOD_SKIPLIST: + raise AssertionError("MOD_SKIPLIST must be sorted with no duplicates") +MOD_SKIPLIST = set(MOD_SKIPLIST) + + +@functools.cache +def get_legacy_mod_inlinelist() -> set[str]: + torch_dir = _module_dir(torch) + if torch_dir is None: + return set() + inlinelist = { + _as_posix_path(torch_dir + m[len("torch.") :].replace(".", "/")) + for m in LEGACY_MOD_INLINELIST + } + return inlinelist + + +@functools.cache +def get_mod_inlinelist() -> set[str]: + torch_dir = _module_dir(torch) + if torch_dir is None: + return set() + inlinelist = { + _as_posix_path(torch_dir + m[len("torch.") :].replace(".", "/")) + for m in MOD_INLINELIST + } + return inlinelist + + +@functools.cache +def get_mod_skiplist() -> set[str]: + torch_dir = _module_dir(torch) + if torch_dir is None: + return set() + skiplist = { + _as_posix_path(torch_dir + m[len("torch.") :].replace(".", "/")) + for m in MOD_SKIPLIST + } + return skiplist + + +# skip some standard python builtin libs +SKIP_DIRS = [ + "", + _as_posix_path(_config_module.__file__), + "triton/backends", +] +SKIP_DIRS.extend(map(_as_posix_path, filter(None, map(_module_dir, BUILTIN_SKIPLIST)))) + +BUILTIN_INLINE_WHEN_CALLED.update( + filter(None, (_module_dir(copy), _as_posix_path(_config_module.__file__))) +) + +SKIP_DIRS_RE = re.compile(r"match nothing^") + +# Skip fbcode paths(including torch.package paths) containing +# one of the following strings. +FBCODE_SKIP_DIRS: set[str] = set() + +FBCODE_SKIP_DIRS_RE = re.compile(f".*({'|'.join(map(re.escape, FBCODE_SKIP_DIRS))})") + +# Remove this after fbcode is fully migrated to tracing through torchrec. +FBCODE_SKIP_TORCHREC_DIRS = { + "torchrec/distributed", + "torchrec/fb/distributed", + "caffe2/torch/fb/sparsenn/pooled_embeddings_modules.py", +} + +FBCODE_SKIP_TORCHREC_DIRS_RE = re.compile( + f".*({'|'.join(re.escape(_as_posix_path(d)) for d in FBCODE_SKIP_TORCHREC_DIRS)})" +) + +# TODO(yanboliang, anijain2305) - There are a few concerns that we should +# resolve +# 1) Audit if torchrec/distributed is even required in FBCODE_SKIPS_DIR +# 2) To inline just one file but skip others in a directory, we could use +# manual_torch_name_rule_map but this one is hard because FBCODE can add unusual +# names like torch_package. +# So, this is a stop gap solution till then. +FBCODE_INLINE_FILES_IN_SKIPPED_DIRS = { + "torchrec/distributed/types.py", +} +FBCODE_INLINE_FILES_IN_SKIPPED_DIRS_RE = re.compile( + f".*({'|'.join(re.escape(_as_posix_path(d)) for d in FBCODE_INLINE_FILES_IN_SKIPPED_DIRS)})" +) + +# torch.optim is a special case, +# we usually want to inline it, but the directory +# structure does not match the module structure +# and we want to skip the functions in optim/lr_scheduler.py +# this has precedence over all other rules in check_file +FORCE_SKIP_FILES = {f"{_module_dir(torch)}optim/lr_scheduler.py"} + + +def _recompile_re() -> None: + global SKIP_DIRS_RE + SKIP_DIRS_RE = re.compile( + rf"^[^\s<]*({'|'.join(re.escape(_as_posix_path(d)) for d in SKIP_DIRS)})" + ) + + +def add(import_name: str) -> None: + if isinstance(import_name, types.ModuleType): + return add(import_name.__name__) + if not isinstance(import_name, str): + raise AssertionError( + f"expected import_name to be a str, got {type(import_name)}" + ) + from importlib.util import find_spec + + module_spec = find_spec(import_name) + if not module_spec: + return + origin = module_spec.origin + if origin is None: + return + SKIP_DIRS.append(_strip_init_py(origin)) + _recompile_re() + + +@dataclasses.dataclass +class SkipResult: + skipped: bool + reason: str | None + + +def check_file(filename: str | None, is_inlined_call: bool = False) -> SkipResult: + """Should skip this file?""" + if filename is None: + return SkipResult( + True, "cannot determine source file (likely a C extension or builtin)" + ) + filename = _as_posix_path(filename) + if filename in FORCE_SKIP_FILES: + return SkipResult(True, f"file is force-skipped ({filename})") + + for d in get_legacy_mod_inlinelist(): + if filename.startswith(d): + return SkipResult(False, f"file matches LEGACY_MOD_INLINELIST ({d})") + if is_inlined_call and is_torch_inline_allowed(filename): + return SkipResult(False, f"file matches MOD_INLINELIST ({filename})") + if is_inlined_call and any( + filename.startswith(d) for d in BUILTIN_INLINE_WHEN_CALLED + ): + return SkipResult( + False, f"file matches BUILTIN_INLINE_WHEN_CALLED ({filename})" + ) + if ( + is_fbcode() + and FBCODE_SKIP_DIRS + and bool(FBCODE_SKIP_DIRS_RE.match(filename)) + and not bool(FBCODE_INLINE_FILES_IN_SKIPPED_DIRS_RE.match(filename)) + ): + return SkipResult(True, "file matches FBCODE_SKIP_DIRS") + + if ( + is_fbcode() + and config.skip_torchrec + and FBCODE_SKIP_TORCHREC_DIRS + and bool(FBCODE_SKIP_TORCHREC_DIRS_RE.match(filename)) + and not bool(FBCODE_INLINE_FILES_IN_SKIPPED_DIRS_RE.match(filename)) + ): + return SkipResult(True, "file matches FBCODE_SKIP_TORCHREC_DIRS") + + unittest_dir = _module_dir(unittest) + if ( + unittest_dir is not None + and filename.startswith(unittest_dir) + and not torch._dynamo.config.enable_trace_unittest + ): + return SkipResult(True, "file is in unittest directory") + + if bool(SKIP_DIRS_RE.match(filename)): + matched_dir = next((d for d in SKIP_DIRS if filename.startswith(d)), filename) + return SkipResult(True, f"file is under skip directory ({matched_dir})") + + for d in get_mod_skiplist(): + if filename.startswith(d): + return SkipResult(True, f"file matches MOD_SKIPLIST ({d})") + return SkipResult(False, "inlined by default") + + +@dataclasses.dataclass +class FunctionInfo: + py_obj: object | None + name: str | None + filename: str + code: types.CodeType | None + + +""" +This is the main entry point to determine whether an object (function) should be inlined or skipped. +Let's illustrate the logic with an example: + @torch.compile + def f1(x, y): + ...... + f2(x, y) + ...... + + def f2(x, y): + ...... + f3(x, y) + ...... + + def f3(x, y): + ...... + +There are mainly three call sites of check/check_verbose: +* The compile region entrance (like function f1), the corresponding code is located at eval_frame.py. +* When tracing the recursively called functions (like function f2 and f3). + * Dynamo decides inline/skip every time it encounters a new recursively function call, and the call site + is in InliningInstructionTranslator.check_inlineable of symbolic_convert.py. + * If f2 is skipped by Dynamo, when evaluating the frame of f3, Dynamo need the inline/skip check again + and the call site is in catch_errors_wrapper.catch_errors of convert_frame.py. +* For global variables and function arguments, Dynamo needs to decide if they are wrapped as SkipFunctionVariable in builder.py. + +`is_inlined_call` is used to indicate if the current function call is inlined (f2 is inlined call if it passes check) +or not (f3 is not inlined call if f2 is skipped). Inside of the `check_verbose` function, there are more rules +to be checked if this `is_inlined_call`. +The reason to have this flag is that if the upper level function call (e.g, f2) is skipped, +we don't want to inline the lower level function call (e.g, f3) by default. +""" + +_force_inline_flag = False + + +# pyrefly: ignore [deprecated] +@contextlib.contextmanager +def _force_inline() -> Iterator[None]: + """ + A context manager used within the dynamo codebase that forces a function + and nested function calls to be inlined during dynamo tracing. + + When active, check_verbose() will skip all inline/skip decision logic and + always return SkipResult(False, ...), meaning functions will be inlined. + + See _make_inlined() in utils.py which uses this to ensure that + a python function is fully traced to produce the needed variable trackers. + """ + global _force_inline_flag + old_val = _force_inline_flag + try: + _force_inline_flag = True + yield + finally: + _force_inline_flag = old_val + + +def check_verbose( + obj: object, is_inlined_call: bool = False, frame: Any | None = None +) -> SkipResult: + if _force_inline_flag: + return SkipResult( + False, + "don't skip because we're inside _force_inline() context", + ) + + # For eval frame callback (not inlined calls), allow tracing inbuilt + # nn.Module.forward methods when the module has hooks. Any hook can cause + # a graph break (via @torch._dynamo.disable, print, unsupported ops, etc.), + # which skips the entire _call_impl frame. By allowing forward to be traced, + # Dynamo can capture the module's operations in a new graph after the break. + if ( + not is_inlined_call + and frame is not None + and isinstance(obj, types.CodeType) + and obj.co_name == "forward" + ): + from .utils import nnmodule_has_hooks + + module = frame.f_locals.get("self") + if ( + module is not None + and isinstance(module, torch.nn.Module) + and module.__class__.__module__.startswith(("torch.nn.", "torch.ao.")) + and nnmodule_has_hooks(module, check_forward_hooks=True) + ): + return SkipResult( + False, + "inbuilt nn.Module.forward allowed - module has hooks", + ) + + if isinstance( + obj, + ( + UserFunctionVariable, + UserMethodVariable, + NestedUserFunctionVariable, + LocalGeneratorFunctionVariable, + LocalGeneratorObjectVariable, + ), + ): + try: + py_obj = obj.get_function() + except NotImplementedError: + py_obj = None + fi = FunctionInfo(py_obj, obj.get_name(), obj.get_filename(), obj.get_code()) + elif isinstance(obj, types.CodeType): + fi = FunctionInfo(None, obj.co_name, obj.co_filename, obj) + elif isinstance(obj, (types.FunctionType, types.MethodType)): + filename = getfile(obj) + if filename is None: + raise AssertionError(f"getfile returned None for function/method {obj}") + fi = FunctionInfo( + obj, + obj.__name__, + filename, + obj.__code__, # type: ignore[union-attr] # FIXME Add MethodType.__code__ to typeshed + ) + else: + filename = getfile(obj) + if filename is None: + raise AssertionError(f"getfile returned None for {type(obj)}") + fi = FunctionInfo(obj, None, filename, None) + + # typing.cast is a polyfilled no-op, but unlike C builtins it has a code + # object that PEP 523 can intercept as a standalone frame after a graph + # break. Skip it at the top level to avoid installing unnecessary guards. + if fi.code is not None and fi.code is typing.cast.__code__: + return SkipResult(True, "typing.cast is a no-op, skip at top level") + + # Consulte the central trace rules defined in torch._dynamo.trace_rules. + reasons: set[str] = set() + rule = lookup_inner(fi.py_obj, fi.name, fi.filename, is_inlined_call, reasons) + if rule is None: + raise AssertionError( + f"lookup_inner returned None for {fi.name} in {fi.filename}" + ) + if issubclass( + rule, + ( + UserFunctionVariable, + LocalGeneratorFunctionVariable, + PolyfilledFunctionVariable, + ), + ): + return SkipResult(False, reasons.pop()) + elif issubclass(rule, TorchInGraphFunctionVariable): + return SkipResult(False, reasons.pop()) + else: + if rule != SkipFunctionVariable: + raise AssertionError(f"expected SkipFunctionVariable, got {rule}") + return SkipResult(True, reasons.pop()) + + +def check(obj: object, is_inlined_call: bool = False, frame: Any | None = None) -> bool: + return check_verbose(obj, is_inlined_call, frame).skipped + + +def get_skip_reason(obj: object) -> str: + """Compute a descriptive skip reason for a callable. Only called on graph break.""" + if is_callable_disallowed(obj): + return _disallowed_callable_ids.get_name(id(obj), repr(obj)) + + filename = getfile(obj) + if filename is not None: + skip_result = check_file(filename) + if skip_result.reason is not None: + return skip_result.reason + + module = getattr(obj, "__module__", None) or "" + return ( + f"cannot determine source file for {module} (likely a C extension or builtin)" + ) + + +# skip common third party libs +for _name in THIRDPARTY_SKIPLIST: + add(_name) + +_recompile_re() + + +def is_torch_inline_allowed(filename: str) -> bool: + return any(filename.startswith(d) for d in get_mod_inlinelist()) + + +@functools.cache +def get_ngb_suppress_inlinelist() -> set[str]: + torch_dir = _module_dir(torch) + if torch_dir is None: + return set() + return { + _as_posix_path(torch_dir + m[len("torch.") :].replace(".", "/")) + for m in NGB_SUPPRESS_INLINELIST + } + + +def is_ngb_suppressed_inline(filename: str) -> bool: + return any(filename.startswith(d) for d in get_ngb_suppress_inlinelist()) + + +@functools.cache +def dynamo_dir() -> str | None: + import torch._dynamo + + return _module_dir(torch._dynamo) + + +def is_torch(filename: str) -> bool: + dynamo_path = dynamo_dir() + if dynamo_path is not None and filename.startswith(dynamo_path): + return False + torch_path = _module_dir(torch) + return torch_path is not None and filename.startswith(torch_path) + + +""" +Main entry point for looking up the trace rule (the Dynamo variable) for a given callable object. +""" + +BUILTIN_CALLABLES = { + dict: DictBuiltinVariable, + getattr: GetAttrBuiltinVariable, + hasattr: HasAttrBuiltinVariable, + iter: IterBuiltinVariable, + list: ListBuiltinVariable, + setattr: SetAttrBuiltinVariable, +} + + +def lookup_callable(obj: Callable[..., Any]) -> type[VariableTracker] | None: + if not hashable(obj): + return None + # Custom allow/disallow in graph takes precedence over the general lookup. + if is_callable_disallowed(obj): + return SkipFunctionVariable + if is_callable_allowed(obj): + return TorchInGraphFunctionVariable + if is_polyfilled_callable(obj): + return PolyfilledFunctionVariable + if obj in BUILTIN_CALLABLES: + return BUILTIN_CALLABLES[obj] + if is_builtin_callable(obj): + return BuiltinVariable + return None + + +""" +Main entry point for looking up the trace rule (the Dynamo variable) for a given function object. +E.g, the lookup result of `torch.sin` is `TorchInGraphFunctionVariable`. +""" + + +def lookup(obj: object) -> type[VariableTracker] | None: + return lookup_inner(obj) + + +# also takes config.dont_skip_tracing into account +def lookup_inner( + obj: object, + name: str | None = None, + filename: str | None = None, + is_direct_call: bool = True, + reasons: None | set[str] = None, +) -> type[VariableTracker] | None: + result = _lookup_inner( + obj, + name=name, + filename=filename, + is_direct_call=is_direct_call, + reasons=reasons, + ) + # There are still some modules we should absolutely NOT trace into - e.g. most of torch._dynamo, + # as this can result in really weird tracing behaviors. + # Note that if a torch._dynamo function is already not skipped (e.g. functions in external_utils.py), + # then this branch does not apply. + if config.dont_skip_tracing and result is SkipFunctionVariable: + if filename is None: + filename = getfile(obj) + if filename is None: + raise AssertionError( + f"getfile returned None for {type(obj)} in dont_skip_tracing path" + ) + filename = _as_posix_path(filename) + torch_dir = _module_dir(torch) + if torch_dir is not None: + dynamo_path = _as_posix_path(torch_dir) + "_dynamo" + if filename.startswith(dynamo_path) and not filename.endswith( + "test_dont_skip_tracing_functions.py" + ): + return SkipFunctionVariable + if reasons is not None: + reasons.add( + "Attempted skip but we are ignoring skips due to torch._dynamo.config.dont_skip_tracing" + ) + return UserFunctionVariable + return result + + +def _lookup_inner( + obj: object, + name: str | None = None, + filename: str | None = None, + is_direct_call: bool = True, + reasons: set[str] | None = None, +) -> type[VariableTracker] | None: + # Step 1: lookup obj's tracing rule in `torch_name_rule_map`. + # The rules defined in `torch_name_rule_map` mainly includes two parts: + # - Manually defined rules for any functions. + # - The list of torch in graph functions. + try: + can_hash = hashable(obj) + except Exception: + can_hash = False + if not can_hash: + if reasons is not None: + reasons.add("obj is not hashable") + return None + if obj is not None: + if is_aten_op_or_tensor_method(obj): + return TorchInGraphFunctionVariable + rule = get_torch_obj_rule_map().get(obj, None) + if rule is not None: + if reasons is not None: + reasons.add("get_torch_obj_rule_map") + return rule + elif name is not None and filename is not None and not is_direct_call: + if name.startswith(TORCH_DYNAMO_RESUME_IN_PREFIX): + rule = get_torch_obj_rule_map().get( + filename + "#" + TORCH_DYNAMO_RESUME_IN_PREFIX, None + ) + else: + rule = get_torch_obj_rule_map().get(filename + "#" + name, None) + if rule is not None: + if reasons is not None: + reasons.add("get_torch_obj_rule_map") + return rule + elif name == "": + if reasons is not None: + reasons.add("inlining frame from list comprehension") + return UserFunctionVariable + + # Step 2: lookup obj's tracing rule by function name. + if is_direct_call: + if name == "patched_init": + if reasons is not None: + reasons.add("func name is patched_init") + return SkipFunctionVariable + elif name == "__torch_function__" or ( + obj and getattr(obj, "__name__", None) == "__torch_function__" + ): + if reasons is not None: + reasons.add("func name is __torch_function__") + return UserFunctionVariable + + if not is_direct_call: + if name == "__getattr__": + # is_direct_call = False indicates that this is the top-level frame + # being traced (i.e., it is not inlined and not called from + # InliningInstructionTranslator). Tracing __getattr__ at the top + # level is unlikely because we inline it for + # UserDefinedObjectVariable. This scenario occurs only for + # UnspecializedNNModuleVariable, where Dynamo directly calls + # __getattr__ during trace time, generating LOAD_ATTR bytecode + # without going through the underlying __getattr__ data structures. + # When this optimized bytecode is executed, Dynamo is triggered + # again on the __getattr__ call. Therefore, we skip Dynamo tracing + # in this case. + if reasons is not None: + reasons.add( + "Tracing __getattr__ as the top level frame, unsuitable for tracing." + ) + return SkipFunctionVariable + + # Step 3: lookup obj's tracing rule by filename. + if filename is None: + filename = getfile(obj) + + skip_result = check_file(filename, is_direct_call) + if reasons is not None and skip_result.reason is not None: + reasons.add(skip_result.reason) + if skip_result.skipped: + return SkipFunctionVariable + else: + return UserFunctionVariable + + +def clear_lru_cache() -> None: + torch._dynamo.trace_rules.get_torch_obj_rule_map.cache_clear() + torch._dynamo.trace_rules.get_tensor_method.cache_clear() + torch._dynamo.trace_rules.get_legacy_mod_inlinelist.cache_clear() + torch._dynamo.trace_rules.get_mod_inlinelist.cache_clear() + torch._dynamo.trace_rules.get_ngb_suppress_inlinelist.cache_clear() + torch._dynamo.trace_rules.dynamo_dir.cache_clear() diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/types.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/types.py new file mode 100644 index 0000000000000000000000000000000000000000..54171fb981ba81121f378b49fc600aef1e56bc93 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/types.py @@ -0,0 +1,149 @@ +"""This module contains the core type definitions and protocols used throughout Dynamo. + +The types defined here fall into several categories: +- Guard related types (GuardFn, GuardFail, GuardedCode): Used for tracking and managing guards that protect compiled code +- Frame and cache types (FrameState, CacheEntry): Used for managing interpreter frame state and caching +- Callback protocols (DynamoCallbackFn): Define the interface for frame evaluation callbacks +- Hook protocols (DynamoGuardHook, ProfilerStartHook, ProfilerEndHook, BytecodeHook): Define various hook points for + instrumentation and customization + +These types provide the foundational interfaces that enable Dynamo's dynamic compilation and optimization system, +ensuring type safety and clear contracts between different components of the system. +""" + +import dataclasses +import types +from collections.abc import Callable, Mapping +from typing import Any, NamedTuple, Protocol, runtime_checkable + +# CacheEntry has a `guard_manager` field for the guard, and a `code` field for the code object. +from torch._C._dynamo.eval_frame import ( + _CacheEntry as CacheEntry, + _ExtraState as ExtraState, + _FrameAction as FrameAction, + _FrameExecStrategy as FrameExecStrategy, + _PyInterpreterFrame as DynamoFrameType, +) +from torch._guards import CompileId, Guard + + +# We use a dict to store additional data per frame. +FrameState = dict[Any, Any] + + +class GuardFail(NamedTuple): + # A string repr of the piece of failed guard code we eval-ed + reason: str + # A code object where we failed a guard + orig_code: types.CodeType + + +@dataclasses.dataclass(frozen=True) +class GuardFilterEntry: + name: str + has_value: bool + value: object + guard_type: str + derived_guard_types: tuple[str, ...] + is_global: bool + orig_guard: Guard + + +class GuardFn(Protocol): + closure_vars: dict[str, object] + args: list[str] + code_parts: list[str] + verbose_code_parts: list[str] + global_scope: dict[str, object] + guard_fail_fn: Callable[[GuardFail], None] | None + cache_entry: CacheEntry | None + extra_state: ExtraState | None + + # maps locals of user function to bool + def __call__(self, f_locals: dict[str, object]) -> bool: ... + + +@dataclasses.dataclass +class GuardedCode: + code: types.CodeType + guard_manager: GuardFn + compile_id: CompileId + trace_annotation: str = "Unknown" + + +@dataclasses.dataclass +class ConvertFrameReturn: + # default return is no compiled code (i.e. `return None`): + # strategy is to skip non-recursively, for all future intercepted frames too + + # eval frame execution strategy for this frame + frame_exec_strategy: FrameExecStrategy = dataclasses.field( + default_factory=lambda: FrameExecStrategy(FrameAction.SKIP, FrameAction.DEFAULT) + ) + # also apply frame_exec strategy to future frames with same code + apply_to_code: bool = True + guarded_code: GuardedCode | None = None + skip_reason: str | None = None + + +def wrap_guarded_code(guarded_code: GuardedCode) -> ConvertFrameReturn: + return ConvertFrameReturn( + frame_exec_strategy=FrameExecStrategy(FrameAction.DEFAULT, FrameAction.DEFAULT), + guarded_code=guarded_code, + ) + + +class DynamoCallbackFn(Protocol): + def __call__( + self, + frame: DynamoFrameType, + cache_entry: CacheEntry | None, + frame_state: FrameState, + ) -> ConvertFrameReturn: ... + + +DynamoCallback = DynamoCallbackFn | None | bool + + +CompilerConfig = Mapping[str, Any] + + +@runtime_checkable +class CompilerConfigProvider(Protocol): + def get_compiler_config(self) -> CompilerConfig | None: ... + + +class DynamoGuardHook(Protocol): + def __call__( + self, + guard_manager: GuardFn, + code: types.CodeType, + f_locals: dict[str, object], + index: int, + last: bool, + ) -> None: ... + + +class DynamoGuardCompleteHook(Protocol): + def __call__( + self, + cache_hit: bool, + ) -> bool: ... + + +class ProfilerStartHook(Protocol): + def __call__( + self, + name: str, + # TODO(whc) how do I annotate a _RecordFunction here? + ) -> Any: ... + + +class ProfilerEndHook(Protocol): + def __call__(self, record: Any) -> None: ... + + +class BytecodeHook(Protocol): + def __call__( + self, code: types.CodeType, new_code: types.CodeType + ) -> types.CodeType | None: ... diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/utils.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0b02c3db4fcccb64707fa79ff23539a6ee02c9dd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/utils.py @@ -0,0 +1,6019 @@ +""" +Utility functions and classes used throughout the TorchDynamo system. + +This module contains a collection of helper utilities used by various parts of Dynamo for: +- Performance metrics collection and reporting +- Compilation timing and debugging +- Graph manipulation and tensor operations +- Runtime guards and checks +- Common data structure operations +- Testing and development tools + +This is an internal module that provides shared functionality used across the Dynamo codebase. +""" + +from __future__ import annotations + +import atexit +import collections +import contextlib +import copy +import dataclasses +import datetime +import dis +import enum +import functools +import gc +import importlib +import inspect +import itertools +import json +import linecache +import logging +import math +import operator +import os +import re +import sys +import textwrap +import threading +import time +import traceback +import types +import typing +import uuid +import warnings +import weakref +from collections import Counter, OrderedDict +from contextlib import AbstractContextManager, contextmanager +from dataclasses import is_dataclass +from functools import lru_cache +from types import CodeType, MethodWrapperType +from typing import ( + Any, + cast, + ClassVar, + Generic, + Literal, + NoReturn, + overload, + TypeAlias, + TypeGuard, + TypeVar, +) +from typing_extensions import ParamSpec, TypeIs + +import torch +import torch._functorch.config +import torch.fx.experimental.symbolic_shapes +import torch.utils._pytree as pytree +from torch import fx +from torch._C import ( + _instruction_counter, + _len_torch_function_stack, + _pop_torch_function_stack, + _push_on_torch_function_stack, +) +from torch._dispatch.python import enable_python_dispatcher +from torch._dynamo.metrics_context import MetricsContext, RuntimeMetricsContext +from torch._guards import CompileId, Source, TracingContext +from torch._subclasses.meta_utils import is_sparse_compressed +from torch._utils_internal import ( + justknobs_check, + log_chromium_event_internal, + log_compilation_event, + record_chromium_event_internal, + signpost_event, +) +from torch.fx._utils import _format_graph_code, lazy_format_graph_code +from torch.monitor import _WaitCounter +from torch.nn.modules.lazy import LazyModuleMixin +from torch.utils._ordered_set import OrderedSet +from torch.utils._python_dispatch import is_traceable_wrapper_subclass +from torch.utils._triton import has_triton, has_triton_package +from torch.utils.hooks import RemovableHandle + +from .graph_utils import _get_flat_args + + +if typing.TYPE_CHECKING: + from collections.abc import ( + Callable, + Container, + Generator, + ItemsView, + Iterable, + Iterator, + KeysView, + Mapping, + Sequence, + ValuesView, + ) + + from torch._dynamo.bytecode_transformation import Instruction + from torch._dynamo.replay_record import ExecutionRecord + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + from torch._dynamo.variables.base import VariableTracker + from torch._prims_common import DeviceLikeType + from torch._subclasses import FakeTensorMode + + +try: + import numpy as np +except ModuleNotFoundError: + np = None # type: ignore[assignment] + +try: + import torch._logging + import torch._numpy as tnp + from torch._guards import detect_fake_mode # noqa: F401 + from torch._logging import LazyString + + from . import config + + # NOTE: Make sure `NP_SUPPORTED_MODULES` and `NP_TO_TNP_MODULE` are in sync. + if np: + NP_SUPPORTED_MODULES: tuple[types.ModuleType, ...] = ( + np, + np.fft, + np.linalg, + np.random, + ) + + NP_TO_TNP_MODULE = { + np: tnp, + np.fft: tnp.fft, + np.linalg: tnp.linalg, + np.random: tnp.random, + } + else: + NP_SUPPORTED_MODULES = () + + # pyrefly: ignore [implicit-any] + NP_TO_TNP_MODULE = {} + from torch._subclasses.fake_tensor import is_fake +except ImportError: + pass + + +T = TypeVar("T") +T1 = TypeVar("T1") +T2 = TypeVar("T2") +T3 = TypeVar("T3") +T4 = TypeVar("T4") +T5 = TypeVar("T5") +T6 = TypeVar("T6") +T7 = TypeVar("T7") +T8 = TypeVar("T8") +T9 = TypeVar("T9") +T10 = TypeVar("T10") +R = TypeVar("R") +_P = ParamSpec("_P") + +unpatched_nn_module_getattr = torch.nn.Module.__getattr__ +unpatched_nn_module_call = torch.nn.Module.__call__ +unpatched_nn_module_call_impl = torch.nn.Module._call_impl + +counters: collections.defaultdict[str, Counter[str]] = collections.defaultdict( + collections.Counter +) +optimus_scuba_log: dict[str, Any] = {} +troubleshooting_url = "https://docs.pytorch.org/docs/main/user_guide/torch_compiler/compile/programming_model.recompilation.html" +nnmodule_doc_url = "https://docs.pytorch.org/docs/main/user_guide/torch_compiler/torch.compiler_nn_module.html" +nnmodule_doc_url_msg = f"See {nnmodule_doc_url} for more information and limitations." +log = logging.getLogger(__name__) + +# profiling compilation time by function +compilation_time_metrics: dict[str, list[float]] = {} + +# This supports calculate_time_spent(), which reports cumulative times +# across the process for any "phase" populated by dynamo_timed. Reset if +# reset_frame_count() is called. +cumulative_time_spent_ns: dict[str, float] = collections.defaultdict(float) + +timer_counter = itertools.count() + + +# Abstraction on top of counters. +class ReInplaceTrigger(enum.Enum): + AUTO_FUNC_V1 = 1 + AUTO_FUNC_V2 = 2 + TRITON_OPS = 3 + + +class ReinplaceCounters: + _values: collections.defaultdict[str, int] = collections.defaultdict(int) + + # Track sizes of known not re-inplaced tensors (exclude dynamic shapes). + @classmethod + def add_missed_bytes(cls, trigger: ReInplaceTrigger, bytes: int) -> None: + if bytes != 0: + cls._values[f"missed_bytes_{trigger.name}"] += bytes + + # Track number of not re-inplaced tensors. + @classmethod + def add_missed_opportunities(cls, trigger: ReInplaceTrigger, count: int) -> None: + if count != 0: + cls._values[f"missed_tensors_{trigger.name}"] += count + + @classmethod + def clear(cls) -> None: + cls._values.clear() + + @classmethod + def get_total_missed(cls) -> int: + sum = 0 + for trigger in ReInplaceTrigger: + sum += cls._values.get(f"missed_tensors_{trigger.name}", 0) + return sum + + @classmethod + def get_total_missed_bytes(cls) -> int: + sum = 0 + for trigger in ReInplaceTrigger: + sum += cls._values.get(f"missed_bytes_{trigger.name}", 0) + return sum + + @classmethod + def log(cls) -> None: + # if not empty log. + if cls._values: + signpost_event("inductor", "reinplace_counters", cls._values) + + +def tabulate( + rows: list[tuple[str, Any]] | list[list[Any]], + headers: tuple[str, ...] | list[str], +) -> str: + try: + import tabulate + + return tabulate.tabulate(rows, headers=headers) + except ImportError: + return "\n".join( + ", ".join(map(str, row)) for row in itertools.chain([headers], rows) + ) + + +curr_frame = 0 + + +# Note: Called for you by dynamo - you almost never ever want to invoke this yourself. +def increment_frame() -> None: + global curr_frame + curr_frame = curr_frame + 1 + + +# Note: Called for you by dynamo - you almost never ever want to invoke this yourself. +def reset_frame_count() -> None: + global curr_frame + cumulative_time_spent_ns.clear() + compilation_time_metrics.clear() + curr_frame = 0 + + +_recompile_user_contexts: list[Callable[[], str]] | None = None + + +def register_hook_for_recompile_user_context(hook: Callable[[], str]) -> None: + """ + Register a hook to be called when a recompile is triggered. The hook + should return a string describing user contexts that are not available + to the compiler, such as the current training epoch. This is useful for + debugging and data analysis for recompile. For data retention purposes, + the user context string is capped at 256 characters. + """ + global _recompile_user_contexts + if _recompile_user_contexts is None: + _recompile_user_contexts = [] + _recompile_user_contexts.append(hook) + + +def get_hook_for_recompile_user_context() -> list[Callable[[], str]] | None: + return _recompile_user_contexts + + +def reset_recompile_user_contexts() -> None: + """Clear any registered recompile user-context hooks (test helper).""" + global _recompile_user_contexts + _recompile_user_contexts = None + + +op_count = 0 + + +def increment_op_count(cnt: int) -> None: + global op_count + op_count += cnt + + +# Get the total time in seconds for each "phase" +# For example, {'entire_frame_compile':8.574629999999999, 'backend_compile':5.26806} +def calculate_time_spent() -> dict[str, float]: + total_by_key = {} + for phase, timing in cumulative_time_spent_ns.items(): + total_by_key[phase] = timing / 1e9 + + total_by_key["total_wall_time"] = total_by_key.get( + "entire_frame_compile", 0 + ) + total_by_key.get("entire_backward_compile", 0) + return total_by_key + + +# Print a report of time spent so far +# Ex: +# TIMING: +# entire_frame_compile:8.574629999999999 +# backend_compile:5.26806 +def print_time_report() -> None: + total_by_key = calculate_time_spent() + + out = "TIMING:" + for key, value in total_by_key.items(): + out = f"{out} {key}:{round(value, 5)}" + + print(out) + + +# Use the following singleton to capture and log CompilationMetrics. Entering the context +# manager allocates a new record to be logged when it exits. (You should not need to use +# this directly unless you introduce a new code path where compilation metrics would be +# gathered). While compiling, use the setters or timer in MetricsContext to update fields +# in the current context. For example: +# +# To set a single field once (use overwrite=True to overwrite): +# get_metrics_context().set("metric_name", value) +# +# To set multiple fields at once (use overwrite=True to overwrite): +# get_metrics_context().update({"name1": val1, "name2": val2}) +# +# To increment an integer field: +# get_metrics_context().increment("metric_name", value) +# +# To record execution time, MetricsContext works with dynamo_timed: +# def foo(...): +# # Updates the "metric_us" field. +# with dynamo_timed("metric", dynamo_compile_column_us="metric_us") +# ... +# +_metrics_context_tls = threading.local() + + +def get_metrics_context() -> MetricsContext: + if not hasattr(_metrics_context_tls, "metrics_context"): + _metrics_context_tls.metrics_context = MetricsContext( + on_exit=record_compilation_metrics + ) + return _metrics_context_tls.metrics_context + + +def get_runtime_metrics_context() -> RuntimeMetricsContext: + if not hasattr(_metrics_context_tls, "runtime_metrics_context"): + _metrics_context_tls.runtime_metrics_context = RuntimeMetricsContext( + on_exit=record_compilation_metrics + ) + return _metrics_context_tls.runtime_metrics_context + + +class CompileEventLogLevel(enum.Enum): + """ + Enum that loosely corresponds with a "log level" of a given event. + + CHROMIUM_EVENT: Logs only to tlparse. + COMPILE_EVENT: Logs to tlparse + PT2 Compile Events + COMPILATION_METRIC: Logs to tlparse, PT2 Compile Events, and dynamo_compile + """ + + CHROMIUM = 1 + PT2_COMPILE = 2 + COMPILATION_METRIC = 3 + + +class CompileEventLogger: + """ + Helper class for representing adding metadata(i.e. columns) to various compile events. + Use CompileEventLogger to add event data to: + - Chromium events + - PT2 Compile Events + - CompilationMetrics + + This should be used in conjunction with dynamo_timed() and metrics contexts, which create + timed spans and events. CompileEventLogger uses three log levels (described in CompileEventLogLevel), + where each log level logs to all sources below it in the hierarchy. + + Example usages: + - I want to log to an existing chromium event within dynamo timed: + with dynamo_timed("my_event"): + CompileEventLogger.chromium("my_event", foo=bar) + + - I want to log my event to both chromium + pt2_compile_events: + with dynamo_timed("my_event", log_pt2_compile_event=True): + CompileEventLogger.pt2_compile("my_event", foo=bar) + + - I want to add information to dynamo events and dynamo_compile + CompileEventLogger.compilation_metric(foo=bar) + """ + + @staticmethod + def log_instant_event( + event_name: str, + metadata: dict[str, Any], + time_ns: int | None = None, + log_level: CompileEventLogLevel = CompileEventLogLevel.CHROMIUM, + ) -> None: + if time_ns is None: + time_ns = time.time_ns() + chromium_log = get_chromium_event_logger() + if log_level == CompileEventLogLevel.CHROMIUM: + log_pt2_compile_event = False + elif log_level == CompileEventLogLevel.PT2_COMPILE: + log_pt2_compile_event = True + else: + raise RuntimeError( + "Cannot log instant event at COMPILATION_METRIC level. Please choose one of CHROMIUM_EVENT or COMPILE_EVENT" + ) + chromium_log.log_instant_event( + event_name, time_ns, metadata, log_pt2_compile_event + ) + + @staticmethod + def add_data( + event_name: str, + log_level: CompileEventLogLevel, + overwrite: bool = False, + **metadata: object, + ) -> None: + """ + Centralized API for adding data to various events + Log an event to a toplevel "dynamo" event or metrics context + depending on log level. + """ + chromium_log = get_chromium_event_logger() + pt2_compile_substack = chromium_log.get_pt2_compile_substack() + + if log_level == CompileEventLogLevel.CHROMIUM: + chromium_log.add_event_data(event_name, **metadata) + elif log_level == CompileEventLogLevel.PT2_COMPILE: + pt2_compile_substack = chromium_log.get_pt2_compile_substack() + if event_name not in pt2_compile_substack: + raise RuntimeError( + "Error: specified log level PT2_COMPILE, but the event %s" + " is not logged to pt2_compile_events. Make sure the event is active and you passed " + "log_pt2_compile_event=True to dynamo_timed", + event_name, + ) + chromium_log.add_event_data(event_name, **metadata) + else: + if log_level != CompileEventLogLevel.COMPILATION_METRIC: + raise AssertionError( + f"Expected log_level to be COMPILATION_METRIC, got {log_level}" + ) + top_event = chromium_log.get_outermost_event() + + if event_name != top_event: + raise RuntimeError( + "Log level is COMPILATION_METRIC, but event_name isn't the toplevel event. " + "CompilationMetrics must be logged to the toplevel event. Consider using `log_toplevel_event_data` directly." + ) + metrics_context = get_metrics_context() + if not metrics_context.in_progress(): + raise RuntimeError( + "No metrics context is in progress. Please only call this function within a metrics context." + ) + + # TODO: should we assert that the keys of metadata are in CompilationMetrics? + metrics_context.update(metadata, overwrite) + chromium_log.add_event_data(event_name, **metadata) + + @staticmethod + def add_toplevel( + log_level: CompileEventLogLevel, overwrite: bool = False, **metadata: object + ) -> None: + """ + Syntactic sugar for logging to the toplevel event + """ + top_event = get_chromium_event_logger().get_outermost_event() + if top_event is None: + raise RuntimeError( + "No toplevel event active. Please only call this function within a dynamo_timed context." + ) + CompileEventLogger.add_data(top_event, log_level, overwrite, **metadata) + + @staticmethod + def increment( + event_name: str, log_level: CompileEventLogLevel, key: str, value: int + ) -> None: + """ + Increments an existing field, or adds it + """ + chromium_log = get_chromium_event_logger() + if ( + log_level == CompileEventLogLevel.CHROMIUM + or log_level == CompileEventLogLevel.PT2_COMPILE + ): + chromium_log.increment(event_name, key, value) + else: + if log_level != CompileEventLogLevel.COMPILATION_METRIC: + raise AssertionError( + f"Expected log_level to be COMPILATION_METRIC, got {log_level}" + ) + top_event = chromium_log.get_outermost_event() + if event_name != top_event: + raise RuntimeError( + "Log level is COMPILATION_METRIC, but event_name isn't the toplevel event. " + "CompilationMetrics must be logged to the toplevel event. Consider using `increment_toplevel` directly." + ) + + metrics_context = get_metrics_context() + if not metrics_context.in_progress(): + raise RuntimeError( + "No metrics context is in progress. Please only call this function within a metrics context/dynamo_timed." + ) + + metrics_context.increment(key, value) + chromium_log.increment(event_name, key, value) + + @staticmethod + def increment_toplevel( + key: str, + value: int = 1, + log_level: CompileEventLogLevel = CompileEventLogLevel.COMPILATION_METRIC, + ) -> None: + """ + Increments a value on the toplevel metric. By default, logs to metric. + """ + chromium_log = get_chromium_event_logger() + top_event = chromium_log.get_outermost_event() + if top_event is None: + raise RuntimeError( + "No toplevel event active. Please only call this function within a metrics context/dynamo_timed." + ) + CompileEventLogger.increment(top_event, log_level, key, value) + + @staticmethod + def add_to_set( + event_name: str, log_level: CompileEventLogLevel, key: str, value: Any + ) -> None: + """ + Add metadata to a set of values with key . Creates a set if it doesn't exist. + """ + chromium_log = get_chromium_event_logger() + if ( + log_level == CompileEventLogLevel.CHROMIUM + or log_level == CompileEventLogLevel.PT2_COMPILE + ): + chromium_log.add_to_set(event_name, key, value) + else: + if log_level != CompileEventLogLevel.COMPILATION_METRIC: + raise AssertionError( + f"Expected log_level to be COMPILATION_METRIC, got {log_level}" + ) + top_event = chromium_log.get_outermost_event() + if event_name != top_event: + raise RuntimeError( + "Log level is COMPILATION_METRIC, but event_name isn't the toplevel event. " + "CompilationMetrics must be logged to the toplevel event. Consider using `add_to_set_metric` directly." + ) + + metrics_context = get_metrics_context() + if not metrics_context.in_progress(): + raise RuntimeError( + "No metrics context is in progress. Please only call this function within a metrics context/dynamo_timed." + ) + + metrics_context.add_to_set(key, value) + chromium_log.add_to_set(event_name, key, value) + + @staticmethod + def add_to_set_toplevel( + key: str, + value: Any, + log_level: CompileEventLogLevel = CompileEventLogLevel.COMPILATION_METRIC, + ) -> None: + """ + Same as add to set, just does it automatically to the toplevel event instead of having to explicitly name it. + Defaults to COMPILATION_METRIC log level. + """ + chromium_log = get_chromium_event_logger() + top_event = chromium_log.get_outermost_event() + if top_event is None: + raise RuntimeError( + "No toplevel event active. Please only call this function within a metrics context/dynamo_timed." + ) + CompileEventLogger.add_to_set(top_event, log_level, key, value) + + # Helper functions that are syntactic sugar + + @staticmethod + def chromium(event_name: str, **metadata: object) -> None: + """ + Add to in chromium. Each key/value of metadata will appear in the chromium trace. + should be the name of a timed event span passed to `dynamo_timed`. + """ + CompileEventLogger.add_data( + event_name, CompileEventLogLevel.CHROMIUM, overwrite=False, **metadata + ) + + @staticmethod + def pt2_compile(event_name: str, **metadata: object) -> None: + """ + Add to in chromium and PT2 Compile Events. + Each key/value of metadata will appear in the chromium trace. Each kwarg name becomes + a column in PT2 Compile Events, with the corresponding kwarg value. + should be the name of a timed event span passed to `dynamo_timed`, + with log_to_pt2_compile_events=True. + """ + CompileEventLogger.add_data( + event_name, CompileEventLogLevel.PT2_COMPILE, overwrite=False, **metadata + ) + + @staticmethod + def add_record_function_data(event_name: str, **metadata: object) -> None: + """ + Add record function data to the profiler event. + + This emits profiler event data so compilation events show up in stack profilers + like the PyTorch profiler. + + Args: + event_name: Name of the event to record + **metadata: Additional metadata to attach to the record function + """ + if torch.autograd.profiler._is_profiler_enabled and metadata: + metadata_str = ", ".join(f"{k}={v}" for k, v in metadata.items()) + with torch.autograd.profiler.record_function( + f"{event_name}_data: {metadata_str}" + ): + pass + + @staticmethod + def compilation_metric(overwrite: bool = False, **metadata: object) -> None: + """ + Add to the CompilationMetrics context. Also logs to PT2 Compile Events + and chromium. + Each key/value of metadata will appear in the chromium trace. Each kwarg name becomes + a column in PT2 Compile Events and Dynamo Compile, with the corresponding kwarg value. + """ + CompileEventLogger.add_toplevel( + CompileEventLogLevel.COMPILATION_METRIC, overwrite, **metadata + ) + + @staticmethod + def instant( + event_name: str, metadata: dict[str, Any], time_ns: int | None = None + ) -> None: + """ + Log an instant event to chromium logs with name at time . The `args` field in + Perfetto will point to metadata. should be a value obtained from time.time_ns(). + """ + CompileEventLogger.log_instant_event( + event_name, metadata, time_ns, CompileEventLogLevel.CHROMIUM + ) + + @staticmethod + def try_add_pt2_compile(event_name: str, **metadata: object) -> None: + """ + Adds to an existing pt2_compile event, but silently returns if the event doesn't exist + or ChromiumEventLogger is not initialized. + This function is syntactic sugar for chromium_event_logger().try_add_event_data. + """ + if not chromium_event_log_active(): + return + chromium_log = get_chromium_event_logger() + chromium_log.try_add_event_data(event_name, **metadata) + + @staticmethod + def try_(method_fn: Callable[_P, Any], *args: _P.args, **kwargs: _P.kwargs) -> None: + """ + Special function that quietly runs a given method, returning if CHROMIUM_EVENT_LOG is None or metrics context is not set + """ + if not chromium_event_log_active(): + return + metrics_context = get_metrics_context() + if not metrics_context.in_progress(): + return + method_fn(*args, **kwargs) + + +_dynamo_timed_tls = threading.local() + + +@contextmanager +def compile_time_record_function(name: str) -> Generator[Any, None, None]: + """ + A context manager for compile-time profiling that uses _RecordFunctionFast + for lower overhead than torch.profiler.record_function. + + This is intended for use during compilation (dynamo, inductor, etc.) where + we want profiling support but with minimal overhead. Moreover, we do not + want the record_function call inside torch.compile to be dispatched. + + Args: + name: The name of the record function event that will appear in profiles. + """ + if torch.autograd.profiler._is_profiler_enabled: + rf = torch._C._profiler._RecordFunctionFast(name) + rf.__enter__() + try: + yield + finally: + rf.__exit__(None, None, None) + else: + yield + + +@contextmanager +def dynamo_timed( + key: str, + # TODO(masneral): Deprecate this param. + phase_name: str | None = None, + log_pt2_compile_event: bool = False, + metadata: dict[str, object] | None = None, + dynamo_compile_column_us: str | None = None, + compile_id: CompileId | None = None, + is_backward: bool | None = None, + log_waitcounter: bool = False, + waitcounter_name_override: str | None = None, +) -> Generator[Any, None, None]: + """ + dynamo_timed is a context manager + By wrapping a function in dynamo_timed, we can get a few things: + + 1) Optionally log timings to pt2_compile_events. + 2) Optionally log timings to CompilationMetrics (dynamo_compile). + 3) Optionally log chromium events. + 4) Optionally increment a WaitCounter. + 5) Store a record in compilation_time_metrics + For example: + + def _foo(...): + with dynamo_timed("_foo"): + ... + + Would show up as an entry in our timing dict: + OrderedDict([('_foo', [0.083690, 0.23949, 3.1425e-05])]) + This is extremely useful for granular debugging. + + Although it is tempting to use dynamo_timed as a decorator, please do not. + In its decorator form it makes cProfile traces less useful as dynamo_timed + suddenly becomes a bottleneck for lots of function calls (as only one parent + pointer is recorded). + + Params: + - key: key into compile_time_metrics. If phase_name is not provided, this is + also the event name used for pt2_compile_events logs and chromium events. + - phase_name: Optional override for the event name. + - log_pt2_compile_event: Whether to log a pt2 compile event internally. + - metadata: Extra metadata to put in pt2_compile_events. + - dynamo_compile_column_us: If provided, updates the specified CompilationMetrics + field to be logged to dyname_compile column. We expect all columns to be _us; + therefore, the field name must end with "_us". + - compile_id: In the typical case, this parameter should not be needed. Use to + supply the compile_id for those cases where we want to log a compile_id where + it's not naturally available, e.g., for runtime autotuning. + - is_backward: Specify forward/backward directly when not available in a + CompileContext, e.g., during runtime autotuning. + that support it. + - log_waitcounter: If set, we'll log a waitcounter of the form "pytorch.dynamo_timed.{key}" + """ + if phase_name: + event_name = phase_name + fn_name = key + else: + event_name = key + fn_name = None + + if key not in compilation_time_metrics: + compilation_time_metrics[key] = [] + + metrics = compilation_time_metrics[key] + event_metadata = {} + if metadata: + event_metadata.update(metadata) + if fn_name: + event_metadata.update({"fn_name": fn_name}) + if is_backward is not None: + event_metadata.update({"is_backward": is_backward}) + + chromium_log: ChromiumEventLogger = get_chromium_event_logger() + start_ns = time.time_ns() + chromium_log.log_event_start( + event_name, start_ns, event_metadata, log_pt2_compile_event, compile_id + ) + + cx_mgrs: list[typing.Any] = [compile_time_record_function(f"{key} (dynamo_timed)")] + if log_waitcounter: + wc_name = waitcounter_name_override or key + cx_mgrs.append(_WaitCounter(f"pytorch.wait_counter.{wc_name}").guard()) + + is_compile_time = torch._guards.CompileContext.current_compile_id() is not None + if dynamo_compile_column_us: + # We're standardizing on microseconds for dynamo_compile timings. + if not dynamo_compile_column_us.endswith("_us"): + raise AssertionError( + f"dynamo_compile_column_us must end with '_us', got {dynamo_compile_column_us!r}" + ) + + # Track nested dynamo_timed calls that update CompilationMetrics so we can + # bump a total duration only for the outermost metric. + if not hasattr(_dynamo_timed_tls, "depth"): + _dynamo_timed_tls.depth = 0 + _dynamo_timed_tls.depth += 1 + + # The corresponding WaitCounters that we bump for all overheads + if _dynamo_timed_tls.depth == 1: + cx_mgrs.append(_WaitCounter("pytorch.wait_counter.dynamo_compile").guard()) + if not is_compile_time: + runtime_wc = "pytorch.wait_counter.compile_runtime_overheads" + cx_mgrs.append(_WaitCounter(runtime_wc).guard()) + + try: + with contextlib.ExitStack() as stack: + for cx in cx_mgrs: + stack.enter_context(cx) + yield + finally: + end_ns = time.time_ns() + time_spent_ns = end_ns - start_ns + metrics.append(time_spent_ns / 1e9) + chromium_log.log_event_end( + event_name, end_ns, {}, start_ns, log_pt2_compile_event, compile_id + ) + if dynamo_compile_column_us: + # TODO: the events that we capture in calculate_time_spent() seem a little + # arbitrary. Currently, it's only those fields that are present in + # CompilationMetrics (but note that we accumulate by the associated event + # name, not the field name in CompilationMetrics). Do we want to keep it + # this way? + cumulative_time_spent_ns[event_name] += time_spent_ns + + # Bump the total duration for every outer event. + _dynamo_timed_tls.depth -= 1 + is_outer_event = _dynamo_timed_tls.depth == 0 + + duration_us = time_spent_ns // 1000 + if is_compile_time: + metrics_context = get_metrics_context() + if metrics_context.in_progress(): + metrics_context.increment(dynamo_compile_column_us, duration_us) + if is_outer_event: + metrics_context.increment("duration_us", duration_us) + else: + runtime_context = get_runtime_metrics_context() + runtime_context.increment(dynamo_compile_column_us, duration_us) + if is_outer_event: + extra = { + "compile_id": compile_id, + "is_runtime": True, + "is_forward": not is_backward, + } + runtime_context.increment("duration_us", duration_us, extra) + + +@overload +def compile_times(repr: Literal["str"], aggregate: bool = False) -> str: ... + + +@overload +# pyrefly: ignore [inconsistent-overload] +def compile_times( + repr: Literal["csv"], aggregate: bool = False +) -> tuple[list[str], list[object]]: ... + + +def compile_times( # type: ignore[misc] + repr: str = "str", aggregate: bool = False +) -> str | None | tuple[list[str], list[str]]: + """ + Get metrics about torchdynamo frontend/backend compilation times. + + Accumulates information from functions tagged with `dynamo_timed`. + + repr='str' returns a printable string for user interaction, and 'csv' + returns headers, rows which can be logged for output + + aggregate causes values from multiple compilations (e.g. split graphs) + to be accumulated into one value. If false, expect more than one value + per metric. + """ + + def fmt_fn(values: list[float], item_fn: Callable[[float], str] = str) -> str: + if aggregate: + return item_fn(sum(values)) + return ", ".join(map(item_fn, values)) + + if repr == "str": + rows = [ + (k, fmt_fn(compilation_time_metrics[k], item_fn=lambda x: f"{x:.4f}")) + for k in compilation_time_metrics + ] + out = "TorchDynamo compilation metrics:\n" + out += tabulate(rows, headers=("Function", "Runtimes (s)")) + return out + elif repr == "csv": + values = [ + fmt_fn(v, item_fn=lambda x: f"{x:.6f}") + for v in compilation_time_metrics.values() + ] + headers = list(compilation_time_metrics.keys()) + return headers, values + return None + + +@atexit.register +def dump_compile_times() -> None: + log.info(compile_times(repr="str", aggregate=True)) + + +tensortype_to_dtype = { + torch.FloatTensor: (torch.float32, torch.float), + torch.DoubleTensor: (torch.float64, torch.double), + torch.HalfTensor: (torch.float16, torch.half), + torch.BFloat16Tensor: (torch.bfloat16,), + torch.ByteTensor: (torch.uint8,), + torch.CharTensor: (torch.int8,), + torch.LongTensor: (torch.int64, torch.long), + torch.IntTensor: (torch.int32, torch.int), + torch.ShortTensor: (torch.int16, torch.short), + torch.BoolTensor: (torch.bool,), +} + + +class DuplicateWarningChecker: + def __init__(self, maxsize: int = 4096) -> None: + self.maxsize = maxsize + self.reset() + + def reset(self) -> None: + self.set: OrderedDict[Any, Any] = OrderedDict() + + def add(self, key: str | tuple[object, object]) -> bool: + if key in self.set: + self.set.move_to_end(key, last=True) + if not config.verbose: + return False + else: + self.set[key] = None + while len(self.set) > self.maxsize: + self.set.popitem(last=False) + return True + + +graph_break_dup_warning_checker = DuplicateWarningChecker() + + +def setup_compile_debug() -> contextlib.ExitStack: + compile_debug = os.environ.get("TORCH_COMPILE_DEBUG", "0") == "1" + + if compile_debug: + return add_file_handler() + + return contextlib.ExitStack() + + +def reset_graph_break_dup_checker() -> None: + graph_break_dup_warning_checker.reset() + + +# Matches ANSI escape sequences (CSI) +ANSI_ESCAPE_PATTERN = re.compile( + r""" + \x1B # ESC + \[ # [ + [0-?]* # Parameter bytes + [ -/]* # Intermediate bytes + [@-~] # Final byte + """, + re.VERBOSE, +) + + +class StripAnsiFormatter(logging.Formatter): + """Logging formatter that strips ANSI escape codes.""" + + def format(self, record: logging.LogRecord) -> str: + msg = super().format(record) + return ANSI_ESCAPE_PATTERN.sub("", msg) + + +def add_file_handler() -> contextlib.ExitStack: + log_path = os.path.join(get_debug_dir(), "torchdynamo") + os.makedirs(log_path, exist_ok=True) + + log_file_handler = logging.FileHandler(os.path.join(log_path, "debug.log")) + log_file_handler.setFormatter(StripAnsiFormatter("%(message)s")) + logger = logging.getLogger("torch._dynamo") + logger.addHandler(log_file_handler) + + exitstack = contextlib.ExitStack() + exitstack.callback(lambda: logger.removeHandler(log_file_handler)) + return exitstack + + +def setup_log_file() -> contextlib.ExitStack: + exitstack = contextlib.ExitStack() + if config.log_file_name is not None: + log_file_handler = logging.FileHandler(config.log_file_name) + for logger in torch._logging._internal.get_loggers(): + logger.addHandler(log_file_handler) + exitstack.callback(lambda: logger.removeHandler(log_file_handler)) + return exitstack + + return exitstack + + +def gen_record_file_name(exc: Exception, code: CodeType) -> str: + return f"{get_debug_dir()}/error_recordings/\ +{code.co_name}_{type(exc).__name__}_{code.co_firstlineno}.rec" + + +def write_record_to_file(filename: str, exec_record: ExecutionRecord) -> None: + try: + if os.path.exists(filename): + log.warning( + "Unable to write execution record %s; file already exists.", filename + ) + else: + os.makedirs(os.path.dirname(filename), exist_ok=True) + with open(filename, "wb") as f: + exec_record.dump(f) + except Exception: + log.exception("Unable to write execution record %s", filename) + + +def count_calls(g: fx.Graph) -> int: + c = 0 + for n in g.nodes: + if "call" in n.op: + c += 1 + return c + + +def identity(x: T) -> T: + return x + + +def hashable(x: object) -> bool: + try: + hash(x) + return True + except TypeError: + return False + # cannot hash writable memoryview object + except ValueError: + return False + + +def nothing(*args: Any, **kwargs: Any) -> None: + pass + + +class ExactWeakKeyDictionary: + """Similar to weakref.WeakKeyDictionary, but use `is`/`id` rather than `==` to compare equality""" + + def __init__(self) -> None: + self.values: dict[int, Any] = {} + self.refs: dict[int, weakref.ReferenceType[Any]] = {} + + def __getitem__(self, key: Any) -> Any: + return self.values[id(key)] + + def get(self, key: Any, default: Any = None) -> Any: + return self.values.get(id(key), default) + + def __contains__(self, key: Any) -> bool: + return id(key) in self.values + + def __setitem__(self, key: Any, value: Any) -> None: + idx = id(key) + if idx not in self.refs: + self.refs[idx] = weakref.ref(key, lambda ref: self._remove_id(idx)) + self.values[idx] = value + + def _remove_id(self, idx: int) -> None: + if idx in self.values: + del self.values[idx] + if idx in self.refs: + del self.refs[idx] + + def clear(self) -> None: + self.refs.clear() + self.values.clear() + + +@overload +def istype(obj: object, allowed_types: type[T]) -> TypeIs[T]: ... + + +# This can be simplified once TypeVarTuple objects can be expanded into TypeIs. +@overload +def istype( + obj: object, allowed_types: tuple[type[T1], type[T2]] +) -> TypeIs[T1 | T2]: ... + + +@overload +def istype( + obj: object, allowed_types: tuple[type[T1], type[T2], type[T3]] +) -> TypeIs[T1 | T2 | T3]: ... + + +@overload +def istype( + obj: object, allowed_types: tuple[type[T1], type[T2], type[T3], type[T4]] +) -> TypeIs[T1 | T2 | T3 | T4]: ... + + +@overload +def istype( + obj: object, allowed_types: tuple[type[T1], type[T2], type[T3], type[T4], type[T5]] +) -> TypeIs[T1 | T2 | T3 | T4 | T5]: ... + + +@overload +def istype( + obj: object, + allowed_types: tuple[type[T1], type[T2], type[T3], type[T4], type[T5], type[T6]], +) -> TypeIs[T1 | T2 | T3 | T4 | T5 | T6]: ... + + +@overload +def istype( + obj: object, + allowed_types: tuple[ + type[T1], type[T2], type[T3], type[T4], type[T5], type[T6], type[T7] + ], +) -> TypeIs[T1 | T2 | T3 | T4 | T5 | T6 | T7]: ... + + +@overload +def istype( + obj: object, + allowed_types: tuple[ + type[T1], type[T2], type[T3], type[T4], type[T5], type[T6], type[T7], type[T8] + ], +) -> TypeIs[T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8]: ... + + +@overload +def istype( + obj: object, + allowed_types: tuple[ + type[T1], + type[T2], + type[T3], + type[T4], + type[T5], + type[T6], + type[T7], + type[T8], + type[T9], + ], +) -> TypeIs[T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9]: ... + + +@overload +def istype( + obj: object, + allowed_types: tuple[ + type[T1], + type[T2], + type[T3], + type[T4], + type[T5], + type[T6], + type[T7], + type[T8], + type[T9], + type[T10], + ], +) -> TypeIs[T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9 | T10]: ... + + +@overload +def istype( + obj: object, allowed_types: tuple[type, ...] | list[type] | set[type] +) -> bool: ... + + +def istype(obj: object, allowed_types: Any) -> bool: + """isinstance() without subclasses""" + if isinstance(allowed_types, (tuple, list, set)): + return type(obj) in allowed_types + return type(obj) is allowed_types + + +_builtin_final_typing_classes: tuple[Any, ...] = tuple() +if sys.version_info >= (3, 12): + # Some typing classes moved to C in 3.12, + # which no longer have the _Final mixin. + # Check for consistency e.g. here: + # https://github.com/python/cpython/blob/f2b82b3b3b1f8c7a81e84df35ee921e44517cf32/Lib/typing.py#L32 + _builtin_final_typing_classes = ( + typing.ParamSpecArgs, + typing.ParamSpecKwargs, + typing.ParamSpec, + typing.TypeVar, + typing.TypeVarTuple, + typing.TypeAliasType, + ) + + +def get_inputs_devices( + inputs: collections.abc.Sequence[object], + model: torch.fx.GraphModule, +) -> list[torch.device | None]: + all_inputs = pytree.tree_flatten(inputs)[0] + [ + node.meta["val"] for node in list(model.graph.nodes) if "val" in node.meta + ] + devices: list[torch.device | None] = list( + OrderedSet([i.device for i in all_inputs if hasattr(i, "device")]) + ) + return [ + i for i in devices if (isinstance(i, torch.device) and i.type != "meta") + ] + [None] + + +if sys.version_info >= (3, 14): + _builtin_final_typing_classes += (typing.Union,) + + +def is_typing(value: object) -> bool: + # _Final catches most of typing classes: + # - Any + # - Callable + # - Union (Python < 3.14) + # ... + # + # NB: we intentionally ignore classes that inherit from Generic, since they + # can be used as both TypingVariable as well as UserDefinedClassVariable. + if sys.version_info >= (3, 12) and isinstance(value, _builtin_final_typing_classes): + return True + return ( + isinstance(value, (types.UnionType, typing._Final)) # type: ignore[attr-defined] + or value is typing.Generic + or value is typing.Union + ) + + +def is_numpy_int_type(value: object) -> bool: + if not np: + return False + + return istype( + value, + ( + np.int8, + np.int16, + np.int32, + np.int64, + np.uint8, + np.uint16, + np.uint32, + np.uint64, + ), + ) + + +def is_numpy_float_type(value: object) -> bool: + if not np: + return False + + return istype( + value, + ( + np.float16, + np.float32, + np.float64, + ), + ) + + +_unpack_fast_types_cache: tuple[type, ...] | None = None + + +def _unpack_fast_types() -> tuple[type, ...]: + # Builtin iterables whose elements we can get directly via + # unpack_var_sequence, skipping the generic iter/getiter/iternext protocol + # (a bottleneck for large iterables). Built lazily since `variables` is a + # circular import at module load. + global _unpack_fast_types_cache + if _unpack_fast_types_cache is None: + from . import variables + + _unpack_fast_types_cache = ( + variables.ConstDictVariable, + variables.DictViewVariable, + variables.MappingProxyVariable, + variables.DequeVariable, + variables.ListVariable, + variables.ListIteratorVariable, + variables.RangeVariable, + variables.SetVariable, + variables.TensorVariable, + variables.TupleVariable, + ) + return _unpack_fast_types_cache + + +def unpack_iterable( + tx: InstructionTranslatorBase, iterable: VariableTracker +) -> list[VariableTracker]: + if isinstance(iterable, _unpack_fast_types()): + # unpack_var_sequence returns a fresh list, so hand it back directly: + # no generator, no per-element callback, single allocation. + return iterable.unpack_var_sequence(tx) + return list(lazily_unpack(tx, iterable)) + + +def unpack_and_apply_fn( + tx: InstructionTranslatorBase, + iterable: VariableTracker, + apply_fn, +) -> None: + for item in lazily_unpack(tx, iterable): + apply_fn(item) + + +def lazily_unpack( + tx: InstructionTranslatorBase, + iterable: VariableTracker, +): + from .exc import handle_observed_exception, ObservedUserStopIteration + from .variables.object_protocol import generic_getiter, pyiter_next + + if isinstance(iterable, _unpack_fast_types()): + yield from iterable.unpack_var_sequence(tx) + return + + iterator = generic_getiter(tx, iterable) # type: ignore[bad-argument-type] + while True: + try: + yield pyiter_next(tx, iterator) # type: ignore[bad-argument-type] + except ObservedUserStopIteration: + handle_observed_exception(tx) + break + + +@overload +def is_lru_cache_wrapped_function( + value: Callable[..., T], +) -> TypeGuard[functools._lru_cache_wrapper[T]]: ... + + +@overload +def is_lru_cache_wrapped_function( + value: Any, +) -> TypeGuard[functools._lru_cache_wrapper[Any]]: ... + + +def is_lru_cache_wrapped_function( + value: Any, +) -> bool: + return isinstance(value, functools._lru_cache_wrapper) and is_function( + inspect.getattr_static(value, "__wrapped__") + ) + + +_lru_cache_wrappers_allowed_to_trace_without_warning: weakref.WeakSet[ + functools._lru_cache_wrapper[Any] +] = weakref.WeakSet() + + +def allow_lru_cache_wrapper_trace_without_warning( + value: functools._lru_cache_wrapper[Any], +) -> None: + _lru_cache_wrappers_allowed_to_trace_without_warning.add(value) + + +def is_lru_cache_wrapper_trace_without_warning_allowed(value: object) -> bool: + return value in _lru_cache_wrappers_allowed_to_trace_without_warning + + +_FuncTypes: TypeAlias = ( + types.FunctionType + | types.BuiltinFunctionType + | types.MethodDescriptorType + | types.WrapperDescriptorType +) + + +def is_function_or_wrapper( + value: Any, +) -> TypeIs[_FuncTypes | torch._ops.OpOverloadPacket | torch._ops.OpOverload]: + return is_function(value) or isinstance( + value, (torch._ops.OpOverloadPacket, torch._ops.OpOverload) + ) + + +def is_function( + value: Any, +) -> TypeIs[_FuncTypes]: + return isinstance( + value, + ( + types.FunctionType, + types.BuiltinFunctionType, + types.MethodDescriptorType, + types.WrapperDescriptorType, + ), + ) + + +cmp_name_to_op_mapping = { + "__eq__": operator.eq, + "__ne__": operator.ne, + "__lt__": operator.lt, + "__le__": operator.le, + "__gt__": operator.gt, + "__ge__": operator.ge, +} + + +cmp_name_to_op_str_mapping = { + "__eq__": "==", + "__ne__": "!=", + "__lt__": "<", + "__le__": "<=", + "__gt__": ">", + "__ge__": ">=", +} + + +def is_wrapper_or_member_descriptor( + value: Any, +) -> TypeIs[ + types.GetSetDescriptorType + | types.MethodDescriptorType + | types.WrapperDescriptorType + | types.MemberDescriptorType + | types.MethodWrapperType +]: + return isinstance( + value, + ( + # set up by PyGetSetDef + types.GetSetDescriptorType, + # set by PyMethodDef, e.g. list.append + types.MethodDescriptorType, + # slots - list.__add__ + types.WrapperDescriptorType, + # set up by PyMemberDef + types.MemberDescriptorType, + # wrapper over C functions + types.MethodWrapperType, + ), + ) + + +def tracked_repr(tx: InstructionTranslatorBase, vt: VariableTracker) -> str: + from .variables.object_protocol import generic_repr + + return generic_repr(tx, vt).as_python_constant() + + +def _item_debug_repr(vt: VariableTracker) -> str: + if vt.is_python_constant(): + return repr(vt.as_python_constant()) + return vt.debug_repr() + + +def unwrap_if_wrapper(fn: Any) -> Any: + return unwrap_with_attr_name_if_wrapper(fn)[0] + + +def unwrap_with_attr_name_if_wrapper(fn: Any) -> tuple[Any, str | None]: + # TODO(anijain2305) - Investigate if we can get rid of this function + # unpack @torch._dynamo.optimize()(fn) wrapped function + if is_function(fn) and inspect.getattr_static(fn, "_torchdynamo_inline", False): + fn = inspect.getattr_static(fn, "_torchdynamo_inline", fn) + attr_name = "_torchdynamo_inline" + else: + attr_name = None + return fn, attr_name + + +def is_numpy_ndarray(value: Any) -> TypeGuard[np.ndarray]: # type: ignore[type-arg] + if not np: + return False + + return istype(value, np.ndarray) + + +def istensor(obj: Any) -> bool: + """Check of obj is a tensor""" + tensor_list: tuple[type, ...] = ( + torch.Tensor, + torch.nn.Parameter, + *config.traceable_tensor_subclasses, + ) + tensor_list = tensor_list + (torch._subclasses.FakeTensor,) + return istype(obj, tensor_list) + + +def is_lazy_module(mod: Any) -> bool: + return isinstance(mod, LazyModuleMixin) + + +@functools.lru_cache(4096) +def print_once(*args: Any) -> None: + print(*args) + + +def make_cell(val: Any = None) -> types.CellType: + """Some black magic to create a cell object that usually only exists in a closure""" + x = val + + def f() -> Any: + return x + + if f.__closure__ is None: + raise AssertionError("Expected f to have a closure, but f.__closure__ is None") + if len(f.__closure__) != 1: + raise AssertionError( + f"Expected f.__closure__ to have exactly 1 element, got {len(f.__closure__)}" + ) + return f.__closure__[0] + + +def proxy_args_kwargs(args: Any, kwargs: Any) -> tuple[tuple[Any, ...], dict[str, Any]]: + try: + proxy_args = tuple(arg.as_proxy() for arg in args) + proxy_kwargs = {key: arg.as_proxy() for key, arg in kwargs.items()} + return proxy_args, proxy_kwargs + except NotImplementedError as e: + from .exc import unimplemented + from .variables.base import typestr + + unimplemented( + gb_type="Failed to convert args/kwargs to proxy", + context=f"call_function args: {typestr(*args)} {typestr(*list(kwargs.values()))}", + explanation="Missing `as_proxy()` implementation for some arg/kwarg.", + hints=[], + from_exc=e, + ) + + +def to_int_ms(v: float | None) -> int | None: + return None if v is None else int(v * 1000) + + +# float64 timestamp has a quarter microsecond precision in 2024, so while +# this is suboptimal we shouldn't meaningfully lose precision +def to_int_us(v: float | None) -> int | None: + return None if v is None else int(v * 1_000_000) + + +# Version field added to every log. Increment to make it easier to distinguish new +# vs. old entries when you make a substantive change to how the logs are populated. +LOG_FORMAT_VERSION = 3 + + +@dataclasses.dataclass +class CompilationMetrics: + compile_id: str | None = None + frame_key: str | None = None + co_name: str | None = None + co_filename: str | None = None + co_firstlineno: int | None = None + cache_size: int | None = None + accumulated_cache_size: int | None = None + guard_count: int | None = None + shape_env_guard_count: int | None = None + graph_op_count: int | None = None + graph_node_count: int | None = None + graph_input_count: int | None = None + start_time: float | None = None + entire_frame_compile_time_s: float | None = None + backend_compile_time_s: float | None = None + inductor_compile_time_s: float | None = None + code_gen_time_s: float | None = None + fail_type: str | None = None + fail_reason: str | None = None + fail_user_frame_filename: str | None = None + fail_user_frame_lineno: int | None = None + non_compliant_ops: set[str] | None = None + compliant_custom_ops: set[str] | None = None + restart_reasons: set[str] | None = None + dynamo_time_before_restart_s: float | None = None + stack_trace: list[str] | None = None + exception_stack_trace: list[str] | None = None + graph_node_shapes: str | None = None + # Sometimes, we will finish analyzing a frame but conclude we don't want + # to install any guarded code. True means we actually decided to install + # a compiled frame + has_guarded_code: bool | None = None + remote_cache_time_saved_s: float | None = None + structured_logging_overhead_s: float | None = None + config_suppress_errors: bool | None = None + config_inline_inbuilt_nn_modules: bool | None = None + specialize_float: bool | None = None + dynamo_config: str | None = None + compiler_config: str | None = None + is_forward: bool | None = None + num_triton_bundles: int | None = None + remote_fx_graph_cache_get_time_ms: int | None = None + remote_fx_graph_cache_put_time_ms: int | None = None + start_time_us: int | None = None + duration_us: int | None = None + dynamo_cumulative_compile_time_us: int | None = None + aot_autograd_cumulative_compile_time_us: int | None = None + inductor_cumulative_compile_time_us: int | None = None + inductor_code_gen_cumulative_compile_time_us: int | None = None + triton_compile_time_us: int | None = None + runtime_cudagraphify_time_us: int | None = None + runtime_triton_autotune_time_us: int | None = None + dynamo_compile_time_before_restart_us: int | None = None + distributed_ephemeral_timeout_us: int | None = None + structured_logging_overhead_us: int | None = None + remote_fx_graph_cache_get_time_us: int | None = None + remote_fx_graph_cache_put_time_us: int | None = None + backward_cumulative_compile_time_us: int | None = None + end_time_us: int | None = None + pre_grad_pass_time_us: int | None = None + post_grad_pass_time_us: int | None = None + joint_graph_pass_time_us: int | None = None + log_format_version: int = LOG_FORMAT_VERSION + inductor_config: str | None = None + remote_cache_version: int | None = None + inductor_fx_remote_cache_hit_count: int | None = 0 + inductor_fx_remote_cache_miss_count: int | None = 0 + inductor_fx_remote_cache_backend_type: str | None = None + inductor_fx_remote_cache_hit_keys: str | None = None + inductor_fx_remote_cache_miss_keys: str | None = None + inductor_fx_local_cache_hit_count: int | None = 0 + inductor_fx_local_cache_miss_count: int | None = 0 + aotautograd_remote_cache_hit_count: int | None = 0 + aotautograd_remote_cache_miss_count: int | None = 0 + aotautograd_local_cache_hit_count: int | None = 0 + aotautograd_local_cache_miss_count: int | None = 0 + cuda_version: str | None = None + triton_version: str | None = None + feature_usage: dict[str, bool] | None = None + compile_time_autotune_time_us: int | None = None + is_runtime: bool | None = False + gc_time_us: int | None = None + tensorify_float_attempt: bool | None = None + tensorify_float_success: bool | None = None + tensorify_float_failure: set[str] | None = None + guard_latency_us: float | None = None + recompile_reason: str | None = None + num_graph_breaks: int | None = None + triton_kernel_compile_times_us: str | None = None + ir_count: int | None = None + cudagraph_skip_reason: str | None = None + python_version: str | None = None + pgo_put_remote_code_state_time_us: int | None = None + pgo_get_remote_code_state_time_us: int | None = None + # The number of elements within parameters. This is classically what people + # think of when they think of parameters in a ML model. + param_numel: int | None = None + # The number of elements counted by bytes - i.e. a float32 is 4 bytes + # per element. + param_bytes: int | None = None + # The number of parameters counted by fields. This is mostly a proxy for + # the number of distinct type of params. + param_count: int | None = None + recompile_user_contexts: set[str] | None = None + inline_inbuilt_nn_modules_candidate: bool | None = False + pytorch_version: str | None = None + inductor_provenance: set[str] | None = None + functorch_config: str | None = None + + @classmethod + def create(cls, metrics: dict[str, Any]) -> CompilationMetrics: + """ + Factory method to create a CompilationMetrics from a dict of fields. + Includes the logic to add legacy fields and any pre-processing, e.g., + we transform some fields to comma-separated strings for scuba logging. + """ + + def us_to_s(metric: int | None) -> float | None: + return metric / 1e6 if metric is not None else None + + def us_to_ms(metric: int | None) -> int | None: + return metric // 1000 if metric is not None else None + + def collection_to_str(metric: Any | None) -> str | None: + def safe_str(item: Any) -> str: + try: + return str(item) + except Exception: + return "" + + if metric is None: + return None + + if not isinstance(metric, (set, list)): + return "" + + return ",".join(safe_str(item) for item in sorted(metric)) + + def collection_to_json_str(metric: Any | None) -> str | None: + if metric is None: + return None + try: + return json.dumps(list(metric)) + except Exception: + return "" + + # TODO: The following are legacy fields, populated from the fields that replace + # them. Remove these when we decide we can really deprecate them. + legacy_metrics = { + "start_time": us_to_s(metrics.get("start_time_us")), + "entire_frame_compile_time_s": us_to_s( + metrics.get("dynamo_cumulative_compile_time_us") + ), + "backend_compile_time_s": us_to_s( + metrics.get("aot_autograd_cumulative_compile_time_us") + ), + "inductor_compile_time_s": us_to_s( + metrics.get("inductor_cumulative_compile_time_us") + ), + "code_gen_time_s": us_to_s( + metrics.get("inductor_code_gen_cumulative_compile_time_us") + ), + "remote_cache_time_saved_s": us_to_s( + metrics.get("distributed_ephemeral_timeout_us") + ), + "remote_fx_graph_cache_get_time_ms": us_to_ms( + metrics.get("remote_fx_graph_cache_get_time_us") + ), + "remote_fx_graph_cache_put_time_ms": us_to_ms( + metrics.get("remote_fx_graph_cache_put_time_us") + ), + "structured_logging_overhead_s": us_to_s( + metrics.get("structured_logging_overhead_us") + ), + } + + all_metrics = {**legacy_metrics, **metrics} + + # Processing before logging: + all_metrics["inductor_fx_remote_cache_hit_keys"] = collection_to_str( + all_metrics.get("inductor_fx_remote_cache_hit_keys") + ) + all_metrics["inductor_fx_remote_cache_miss_keys"] = collection_to_str( + all_metrics.get("inductor_fx_remote_cache_miss_keys") + ) + all_metrics["triton_kernel_compile_times_us"] = collection_to_json_str( + all_metrics.get("triton_kernel_compile_times_us") + ) + compile_id = all_metrics.get("compile_id") + all_metrics["compile_id"] = str(compile_id) if compile_id else None + + # pyrefly: ignore [bad-argument-type] + return cls(**all_metrics) + + +DEFAULT_COMPILATION_METRICS_LIMIT = 64 + + +_compilation_metrics: collections.deque[CompilationMetrics] = collections.deque( + maxlen=DEFAULT_COMPILATION_METRICS_LIMIT +) + + +def add_compilation_metrics_to_chromium(c: CompilationMetrics) -> None: + """ + These are the common fields in CompilationMetrics that existed before + metrics_context, and aren't set by MetricsContext.set(). We add the subset + of them that make sense in `dynamo`/toplevel events in PT2 Compile Events + directly. + + If you're tempted to add to this list, consider using CompileEventLogger.compilation_metric() + instead, which will automatically also add it to tlparse and PT2 Compile Events. + TODO: Get rid of this function and replace it with CompileEventLogger directly instead. + """ + event_logger = get_chromium_event_logger() + event_name = event_logger.get_outermost_event() + if not event_name: + return + event_logger.add_event_data( + event_name=event_name, + frame_key=c.frame_key, + co_name=c.co_name, + co_filename=c.co_filename, + co_firstlineno=c.co_firstlineno, + cache_size=c.cache_size, + accumulated_cache_size=c.accumulated_cache_size, + guard_count=c.guard_count, + shape_env_guard_count=c.shape_env_guard_count, + graph_op_count=c.graph_op_count, + graph_node_count=c.graph_node_count, + graph_input_count=c.graph_input_count, + fail_type=c.fail_type, + fail_reason=c.fail_reason, + fail_user_frame_filename=c.fail_user_frame_filename, + fail_user_frame_lineno=c.fail_user_frame_lineno, + # Sets aren't JSON serializable + non_compliant_ops=( + list(c.non_compliant_ops) if c.non_compliant_ops is not None else None + ), + compliant_custom_ops=( + list(c.compliant_custom_ops) if c.compliant_custom_ops is not None else None + ), + restart_reasons=( + list(c.restart_reasons) if c.restart_reasons is not None else None + ), + dynamo_time_before_restart_s=c.dynamo_time_before_restart_s, + has_guarded_code=c.has_guarded_code, + dynamo_config=c.dynamo_config, + ) + + +def _get_dynamo_config_for_logging() -> str | None: + def clean_for_json(d: dict[str, Any]) -> dict[str, Any]: + blocklist = { + "TYPE_CHECKING", + "log_file_name", + "verbose", + "repro_after", + "repro_level", + "repro_forward_only", + "repro_tolerance", + "repro_ignore_non_fp", + "same_two_models_use_fp64", + "base_dir", + "debug_dir_root", + "_save_config_ignore", + "log_compilation_metrics", + "inject_BUILD_SET_unimplemented_TESTING_ONLY", + "_autograd_backward_strict_mode_banned_ops", + "reorderable_logging_functions", + "ignore_logger_methods", + "ignore_logging_functions", + "traceable_tensor_subclasses", + "nontraceable_tensor_subclasses", + "_custom_ops_profile", + } + + return { + key: ( + sorted(value) + if isinstance(value, set) + else value.to_jsonable() + if hasattr(value, "to_jsonable") + else value + ) + for key, value in d.items() + if key not in blocklist + } + + config_dict = clean_for_json(config.get_config_copy()) + return json.dumps(config_dict, sort_keys=True) + + +def _compiler_config_for_logging() -> str | None: + def clean_for_json(d: dict[str, Any]) -> dict[str, Any]: + blocklist = { + "TYPE_CHECKING", + } + + return { + key: sorted(value) if isinstance(value, set) else value + for key, value in d.items() + if key not in blocklist + } + + if not torch.compiler.config: + return None + + try: + compiler_config_copy = torch.compiler.config.get_config_copy() # type: ignore[attr-defined] + except (TypeError, AttributeError): + return "Compiler Config cannot be pickled" + + config_dict = clean_for_json(compiler_config_copy) + return json.dumps(config_dict, sort_keys=True) + + +def _scrubbed_inductor_config_for_logging() -> str | None: + """ + Method to parse and scrub uninteresting configs from inductor config + """ + + # TypeSafeSerializer for json.dumps() + # Skips complex types as values in config dict + class TypeSafeSerializer(json.JSONEncoder): + def default(self, o: Any) -> Any: + try: + return super().default(o) + except Exception: + return "Value is not JSON serializable" + + keys_to_scrub: set[Any] = set() + inductor_conf_str = None + inductor_config_copy = None + + if torch._inductor.config: + try: + inductor_config_copy = torch._inductor.config.get_config_copy() + except (TypeError, AttributeError, RuntimeError, AssertionError): + inductor_conf_str = "Inductor Config cannot be pickled" + + if inductor_config_copy is not None: + try: + for key, val in inductor_config_copy.items(): + if not isinstance(key, str): + keys_to_scrub.add(key) + # Convert set() to list for json.dumps() + if isinstance(val, set): + inductor_config_copy[key] = list(val) + # Evict unwanted keys + for key in keys_to_scrub: + del inductor_config_copy[key] + # Stringify Inductor config + inductor_conf_str = json.dumps( + inductor_config_copy, + cls=TypeSafeSerializer, + skipkeys=True, + sort_keys=True, + ) + except Exception: + # Don't crash because of runtime logging errors + inductor_conf_str = "Inductor Config is not JSON serializable" + return inductor_conf_str + + +def _functorch_config_for_logging() -> str | None: + """Serialize functorch config (AOT autograd settings) for Scuba logging.""" + if not justknobs_check("pytorch/dynamo:log_functorch_config"): + return None + + try: + functorch_config_copy = torch._functorch.config.get_config_copy() + except (TypeError, AttributeError, RuntimeError, AssertionError): + return None + + try: + blocklist = { + "TYPE_CHECKING", + "_save_config_ignore", + } + clean = { + k: (list(v) if isinstance(v, set) else v) + for k, v in functorch_config_copy.items() + if k not in blocklist and isinstance(k, str) + } + return json.dumps(clean, sort_keys=True, default=str) + except Exception: + return "Functorch Config is not JSON serializable" + + +def record_compilation_metrics( + start_time_ns: int, + end_time_ns: int, + metrics: dict[str, Any], + exc_type: type[BaseException] | None, + exc_value: BaseException | None, +) -> None: + if torch._inductor.utils.should_use_remote_fx_graph_cache(): + try: + from torch._inductor.fb.remote_cache import REMOTE_CACHE_VERSION + + remote_cache_version = REMOTE_CACHE_VERSION + inductor_fx_remote_cache_backend_type = "_ManifoldCache" + except ModuleNotFoundError: + remote_cache_version = None + inductor_fx_remote_cache_backend_type = None + else: + inductor_fx_remote_cache_backend_type = None + remote_cache_version = None + + # Populate the compile_id from the metrics context if it's set. Otherwise, + # look for it in the current compile context. + compile_id = metrics.get("compile_id") + if not compile_id: + compile_id = torch._guards.CompileContext.current_compile_id() + + common_metrics = { + "compile_id": compile_id, + "start_time_us": start_time_ns // 1000, + "end_time_us": end_time_ns // 1000, + "fail_type": exc_type.__qualname__ if exc_type else None, + "fail_reason": str(exc_value) if exc_value else None, + "structured_logging_overhead_us": to_int_us( + torch._logging.get_structured_logging_overhead() + ), + "dynamo_config": _get_dynamo_config_for_logging(), + "config_suppress_errors": config.suppress_errors, + "config_inline_inbuilt_nn_modules": True, + "inductor_config": _scrubbed_inductor_config_for_logging(), + "compiler_config": _compiler_config_for_logging(), + "cuda_version": torch.version.cuda, + "triton_version": triton.__version__ if has_triton() else "", + "remote_cache_version": remote_cache_version, + "inductor_fx_remote_cache_backend_type": inductor_fx_remote_cache_backend_type, + "python_version": sys.version, + "pytorch_version": torch.__version__, + "functorch_config": _functorch_config_for_logging(), + } + + compilation_metrics = CompilationMetrics.create({**common_metrics, **metrics}) + _compilation_metrics.append(compilation_metrics) + + name = "compilation_metrics" + if compilation_metrics.is_forward is False: + name = "bwd_" + name + if compilation_metrics.is_runtime is True: + name = name + "_runtime" + + torch._logging.trace_structured( + name, + lambda: { + k: list(v) if isinstance(v, set) else v + for k, v in dataclasses.asdict(compilation_metrics).items() + }, + # NB: Because compilation metrics *includes* the logging overhead time, + # we can't both *measure* the logging overhead of compilation metrics + # without making it inconsistent with compilation metrics itself, so + # we ignore the (hopefully small) time spent logging compilation metrics + record_logging_overhead=False, + # These may be runtime logs, e.g., runtime autotunning, so we provide + # the CompileId from the compilation metrics in case it's not available + # in the current trace. + compile_id=compile_id, + ) + + # If there's a chromium event in flight, add the CompilationMetrics to it. + add_compilation_metrics_to_chromium(compilation_metrics) + + # Finally log the compilation metrics. + if config.log_compilation_metrics: + log_compilation_event(compilation_metrics) + + +def set_compilation_metrics_limit(new_size: int) -> None: + global _compilation_metrics + while len(_compilation_metrics) > new_size: + _compilation_metrics.popleft() + new_deque = collections.deque(_compilation_metrics, maxlen=new_size) + _compilation_metrics = new_deque + + +def clear_compilation_metrics() -> None: + global _compilation_metrics + _compilation_metrics.clear() + + +def get_compilation_metrics() -> list[CompilationMetrics]: + return list(_compilation_metrics) + + +class ChromiumEventLogger: + """Logs chromium events to structured logs. tlparse will concatenate these into a perfetto UI link. + + Also emits RecordFunction calls to torch.profiler when enabled. + + See https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview#heading=h.yr4qxyxotyw for + a specification of the Chromium Event JSON format. + """ + + def get_stack(self) -> list[str]: + """ + The main event stack, with every chromium event. + Logged to tlparse. + """ + if hasattr(self.tls, "stack"): + return self.tls.stack + else: + self.tls.stack = [] + return self.tls.stack + + def get_outermost_event(self) -> str | None: + """ + Get the outermost event name (i.e. the longest running event) + or None if the stack is empty. + """ + stack = self.get_stack() + return stack[0] if stack else None + + def get_pt2_compile_substack(self) -> list[str]: + """ + A smaller subset of the main stack that gets used to log + PT2 Compile Events internally. + """ + if hasattr(self.tls, "pt2_compile_substack"): + return self.tls.pt2_compile_substack + else: + self.tls.pt2_compile_substack = [] + return self.tls.pt2_compile_substack + + def get_event_data(self) -> dict[str, Any]: + if not hasattr(self.tls, "event_data"): + self.tls.event_data = {} + return self.tls.event_data + + def get_record_functions(self) -> dict[str, AbstractContextManager[None]]: + if not hasattr(self.tls, "record_functions"): + self.tls.record_functions = {} + return self.tls.record_functions + + def __init__(self) -> None: + self.tls = threading.local() + + from . import config + + # Generate a unique id for this logger, which we can use in scuba to filter down + # to a single python run. + if config.pt2_compile_id_prefix: + self.id_ = f"{config.pt2_compile_id_prefix}-{uuid.uuid4()}" + else: + self.id_ = str(uuid.uuid4()) + + # TODO: log to init/id tlparse after I add support for it + log.info("ChromiumEventLogger initialized with id %s", self.id_) + + def try_add_event_data(self, event_name: str, **kwargs: Any) -> None: + """ + Same as add_event_data, but will silently not log if the event isn't in the stack. + """ + if event_name not in self.get_stack(): + return + self.add_event_data(event_name, **kwargs) + + def add_event_data( + self, + event_name: str, + **kwargs: Any, + ) -> None: + """ + Adds additional metadata info to an in-progress event + This metadata is recorded in the END event + """ + if event_name not in self.get_stack(): + raise RuntimeError( + f"Event {repr(event_name)} not in {self.get_stack()}. " + "Cannot add metadata to events that aren't in progress. " + "Please make sure the event has started and hasn't ended." + ) + event_data = self.get_event_data() + if event_name not in event_data: + event_data[event_name] = {} + event_data[event_name].update(kwargs) + + def increment(self, event_name: str, key: str, value: int) -> None: + """ + Increment an integer event data field by the given amount + """ + if event_name not in self.get_stack(): + raise RuntimeError( + f"Event {repr(event_name)} not in {self.get_stack()}. " + "Cannot add metadata to events that aren't in progress. " + "Please make sure the event has started and hasn't ended." + ) + + event_data = self.get_event_data() + if event_name not in event_data: + event_data[event_name] = {} + if key not in event_data[event_name]: + event_data[event_name][key] = 0 + event_data[event_name][key] += value + + def add_to_set( + self, + event_name: str, + key: str, + value: Any, + ) -> None: + """ + Add a value to a set within a event_name's metadata if it exists + """ + if event_name not in self.get_stack(): + raise RuntimeError( + f"Event {repr(event_name)} not in {self.get_stack()}. " + "Cannot add metadata to events that aren't in progress. " + "Please make sure the event has started and hasn't ended." + ) + event_data = self.get_event_data() + if event_name not in event_data: + event_data[event_name] = {} + if key not in event_data[event_name]: + event_data[event_name][key] = set() + event_data[event_name][key].add(value) + + def log_event_start( + self, + event_name: str, + time_ns: int, + metadata: dict[str, Any], + log_pt2_compile_event: bool = False, + compile_id: CompileId | None = None, + ) -> None: + """ + Logs the start of a single event. + :param str event_name Name of event to appear in trace + :param time_ns Timestamp in nanoseconds + :param metadata: Any extra metadata associated with this event + :param log_pt2_compile_event: If True, log to pt2_compile_events + :param compile_id: Explicit compile_id (rather than using the current context) + """ + compile_id = compile_id or torch._guards.CompileContext.current_compile_id() + metadata["compile_id"] = str(compile_id) + self._log_timed_event( + event_name, + time_ns, + "B", + metadata, + ) + self.get_stack().append(event_name) + # Add metadata from start event + self.add_event_data(event_name, **metadata) + if log_pt2_compile_event: + self.get_pt2_compile_substack().append(event_name) + + # Emit profiler event so compilation events show up in stock PyTorch profiler + if torch.autograd.profiler._is_profiler_enabled: + rf = torch._C._profiler._RecordFunctionFast(event_name) + rf.__enter__() + self.get_record_functions()[event_name] = rf + + # Add metadata to the profiler event if present + if metadata: + CompileEventLogger.add_record_function_data(event_name, **metadata) + + def _reset_to_state( + self, + stack_depth: int, + pt2_compile_substack_depth: int, + event_data_keys: set[str], + record_function_keys: set[str], + ) -> None: + stack = self.get_stack() + del stack[stack_depth:] + substack = self.get_pt2_compile_substack() + del substack[pt2_compile_substack_depth:] + event_data = self.get_event_data() + for event_name in list(event_data): + if event_name not in event_data_keys: + del event_data[event_name] + # Clean up any lingering record functions (shouldn't happen in normal operation) + record_functions = self.get_record_functions() + for event_name, rf in list(record_functions.items()): + if event_name not in record_function_keys: + rf.__exit__(None, None, None) + del record_functions[event_name] + + def reset(self) -> None: + # We do this on every compile in case a compile crashes or restarts and + # we haven't cleared the stack. + self._reset_to_state(0, 0, set(), set()) + + def log_event_end( + self, + event_name: str, + time_ns: int, + metadata: dict[str, Any], + start_time_ns: int, + log_pt2_compile_event: bool, + compile_id: CompileId | None = None, + ) -> None: + """ + Logs the end of a single event. This function should only be + called after log_event_start with the same event_name. + :param event_name: Name of event to appear in trace + :param time_ns: Timestamp in nanoseconds + :param metadata: Any extra metadata associated with this event + :param start_time_ns: The start time timestamp in nanoseconds + :param log_pt_compile_event: If True, log to pt2_compile_events + :param compile_id: Explicit compile_id (rather than using the current context) + """ + compile_id = compile_id or torch._guards.CompileContext.current_compile_id() + metadata["compile_id"] = str(compile_id) + + # Grab metadata collected during event span + all_event_data = self.get_event_data() + if event_name in all_event_data: + event_metadata = all_event_data[event_name] + del all_event_data[event_name] + else: + # pyrefly: ignore [implicit-any] + event_metadata = {} + # Add the passed in metadata + event_metadata.update(metadata) + + event = self._log_timed_event( + event_name, + time_ns, + "E", + event_metadata, + ) + + def pop_stack(stack: list[str]) -> None: + while event_name != stack[-1]: + # If the event isn't the most recent one to end, pop + # off the stack until it is. + # Since event_name in self.stack, this pop is always safe + log.warning( + "ChromiumEventLogger: Detected overlapping events, fixing stack" + ) + stack.pop() + + event_stack = self.get_stack() + # These stack health checks currently never happen, + # but they're written this way to future proof any weird event + # overlaps in the future. + if event_name not in event_stack: + # Something went wrong, we never called start on this event, + # or it was skipped due to overlapping events below + log.warning("ChromiumEventLogger: Start event not in stack, ignoring") + return + + pop_stack(event_stack) + + if log_pt2_compile_event: + pt2_compile_substack = self.get_pt2_compile_substack() + pop_stack(pt2_compile_substack) + log_chromium_event_internal( + event, pt2_compile_substack, self.id_, start_time_ns + ) + # Pop actual event off of stack + pt2_compile_substack.pop() + + # Finally pop the actual event off the stack + event_stack.pop() + + # End profiler event so compilation events show up in stock PyTorch profiler + record_functions = self.get_record_functions() + if event_name in record_functions: + rf = record_functions.pop(event_name) + rf.__exit__(None, None, None) + + def _log_timed_event( + self, + event_name: str, + time_ns: int, + phase: str, + metadata: dict[str, Any] | None = None, + ) -> dict[str, Any]: + """ + Logs a timed event in chromium format. See log_event_start, log_event_end, etc. + """ + event = { + "name": event_name, + "ts": time_ns / 1000, # Chromium events are in micro seconds + "args": metadata, + "ph": phase, + # These categories are needed in all chromium traces + "cat": "dynamo_timed", + "tid": 0, + "pid": 0, # pid should be specified on all logs, we don't personally care about the actual process id + } + torch._logging.trace_structured( + "chromium_event", + payload_fn=lambda: event, + suppress_context=False, + expect_trace_id=False, # Not every chromium event will have a trace_id + ) + record_chromium_event_internal(event) + return event + + def log_instant_event( + self, + event_name: str, + time_ns: int, + metadata: dict[str, Any] | None = None, + # By default, an instant event isn't logged internally, only to structured logging. + log_pt2_compile_event: bool = False, + ) -> None: + """ + Log an instant event with no associated duration. + :param str event_name: Name of event to appear in trace + :param int time_ns Timestamp in nanoseconds + :param Optional[Dict[str, Any]] metadata: Any extra metadata associated with this event + :param str cname optional color for the arrow in the trace + """ + if metadata is None: + metadata = {} + compile_id = str(torch._guards.CompileContext.current_compile_id()) + metadata["compile_id"] = compile_id + event = { + "name": event_name, + "ts": time_ns / 1000, + "args": metadata, + "ph": "i", + # These categories are needed in all chromium traces + "cat": "dynamo_timed", + "tid": 0, + "pid": 0, + "s": "p", # We use "process" level instant events so they all appear on the same row in the trace. + } + torch._logging.trace_structured( + "chromium_event", + payload_fn=lambda: event, + suppress_context=False, + expect_trace_id=True, + ) + if log_pt2_compile_event: + # Log an instant event with the same start and end time + log_chromium_event_internal( + event, self.get_pt2_compile_substack(), self.id_, time_ns + ) + + +CHROMIUM_EVENT_LOG: ChromiumEventLogger | None = None + + +def get_chromium_event_logger() -> ChromiumEventLogger: + global CHROMIUM_EVENT_LOG + if CHROMIUM_EVENT_LOG is None: + CHROMIUM_EVENT_LOG = ChromiumEventLogger() + return CHROMIUM_EVENT_LOG + + +def chromium_event_log_active() -> bool: + global CHROMIUM_EVENT_LOG + return CHROMIUM_EVENT_LOG is not None + + +@contextmanager +def chromium_event_timed( + event_name: str, + reset_event_log_on_exit: bool = False, + log_pt2_compile_event: bool = False, +) -> Generator[Any, None, None]: + """ + Context manager that creates a chromium start and end event. Chromium event + logging is integrated with dynamo_timed, so you probably want to use that + instead. Use this context manager only if you want to avoid dynamo_timed. + """ + chromium_event_log = get_chromium_event_logger() + reset_state: tuple[int, int, set[str], set[str]] | None = None + if reset_event_log_on_exit: + reset_state = ( + len(chromium_event_log.get_stack()), + len(chromium_event_log.get_pt2_compile_substack()), + set(chromium_event_log.get_event_data()), + set(chromium_event_log.get_record_functions()), + ) + chromium_start_time = time.time_ns() + chromium_event_log.log_event_start( + event_name, + chromium_start_time, + {}, + log_pt2_compile_event, + ) + try: + yield + finally: + chromium_event_log.log_event_end( + event_name, + time.time_ns(), + {}, + chromium_start_time, + log_pt2_compile_event, + ) + if reset_state is not None: + chromium_event_log._reset_to_state(*reset_state) + + +# (id(scope), name) -> the token of whichever hook currently owns that +# binding. A value comparison isn't enough here: CompilePackage.install() can +# re-materialize a name like __builtins_dict__ with the *same* object a +# pre-reset hook already installed, so an identity-of-value check would still +# let the stale hook delete it. A token makes ownership explicit instead. +_cleanup_owners: dict[tuple[int, str], object] = {} + + +@dataclasses.dataclass +class CleanupHook: + """Remove a global variable when hook is called""" + + scope: dict[str, Any] + name: str + token: object = dataclasses.field(compare=False, repr=False) + + def __call__(self, *args: Any) -> None: + # Make sure we're not shutting down + if CleanupManager is not None: + CleanupManager.count -= 1 + # Hooks fire when the owning code object is collected, which can happen + # after something else has taken over this name -- CompilePackage.install() + # reinstalls precompiled state under names a pre-reset compile still + # owns. Only clean up while nothing has claimed the name out from under us. + key = (id(self.scope), self.name) + if _cleanup_owners.pop(key, None) is not self.token: + return + # During interpreter shutdown the scope's module __dict__ may already + # have been cleared, so the name can be gone. Use pop to avoid a + # KeyError surfacing as an "Exception ignored in weakref callback". + self.scope.pop(self.name, None) + + @staticmethod + def create(scope: dict[str, Any], name: str, val: Any) -> CleanupHook: + if name in scope: + raise AssertionError(f"Name {name!r} already exists in scope") + CleanupManager.count += 1 + scope[name] = val + token = object() + _cleanup_owners[(id(scope), name)] = token + return CleanupHook(scope, name, token) + + @staticmethod + def disown(scope: dict[str, Any], name: str) -> None: + """Invalidate whichever hook currently owns (scope, name), so that if + its code object outlives this call, firing later is a no-op instead of + deleting a binding something else has since taken over.""" + _cleanup_owners.pop((id(scope), name), None) + + +class CleanupManager(ExactWeakKeyDictionary): + count = 0 + instance: ClassVar[CleanupManager] + + def _remove_id(self, idx: int) -> None: + for hook in self.values[idx]: + hook() + super()._remove_id(idx) + + +CleanupManager.instance = CleanupManager() + + +def clone_tensor(x: torch.Tensor) -> torch.Tensor: + """Clone the tensor and its gradient""" + y = x.clone().requires_grad_(x.requires_grad) + if x.is_leaf and x.grad is not None: + y.grad = x.grad.clone() + return y + + +def _copy_dynamo_attr(src: torch.Tensor, dst: torch.Tensor, attr: str) -> None: + """Copy a single dynamo attribute from src to dst, or remove it from dst + if src doesn't have it. Uses .copy() for container types (set, dict) to + avoid shared references between src and dst, and assigns directly for + primitive types like bool (e.g., _has_dynamo_dim_marking).""" + if hasattr(src, attr): + val = getattr(src, attr) + setattr(dst, attr, val.copy() if hasattr(val, "copy") else val) + elif hasattr(dst, attr): + delattr(dst, attr) + + +def copy_dynamo_tensor_attributes(src: torch.Tensor, dst: torch.Tensor) -> None: + """ + Copy dynamo-specific tensor attributes from src to dst. + These attributes are used for dynamic shape marking and must be preserved + when cloning or casting tensors. If src doesn't have an attribute but dst does, + the attribute is removed from dst. + """ + _copy_dynamo_attr(src, dst, "_dynamo_dynamic_indices") + _copy_dynamo_attr(src, dst, "_dynamo_unbacked_indices") + _copy_dynamo_attr(src, dst, "_dynamo_hint_overrides") + _copy_dynamo_attr(src, dst, "_dynamo_shape_ids") + _copy_dynamo_attr(src, dst, "_dynamo_strict_unbacked_indices") + _copy_dynamo_attr(src, dst, "_dynamo_weak_dynamic_indices") + _copy_dynamo_attr(src, dst, "_dynamo_propagated_dynamic_indices") + _copy_dynamo_attr(src, dst, "_has_dynamo_dim_marking") + + +def clone_input(x: torch.Tensor, *, dtype: torch.dtype | None = None) -> torch.Tensor: + """copy while preserving strides""" + # TODO: this is questionable + if is_fake(x): + # this func fails on fake tensors in __torch_dispatch__ + return x + + def is_pinned_cpu_tensor(x: torch.Tensor) -> bool: + return ( + x.device.type == "cpu" + and not is_traceable_wrapper_subclass(x) + and x.is_pinned() + ) + + def torch_clone(x: torch.Tensor) -> torch.Tensor: + y = torch.clone(x) + if is_pinned_cpu_tensor(x): + y = y.pin_memory() + if x.is_leaf: + y.requires_grad_(x.requires_grad) + if x.is_leaf and x.grad is not None: + y.grad = clone_input(x.grad, dtype=dtype) + copy_dynamo_tensor_attributes(x, y) + return y + + with torch.no_grad(): + if x.device.type == "xla": + # Access data_ptr() for a xla tensor will cause crash + return torch_clone(x) + + # Handle sparse storage (no stride). + if x.layout is torch.sparse_coo: + return torch.sparse_coo_tensor( + torch_clone(x._indices()), + torch_clone(x._values()), + x.shape, + is_coalesced=x.is_coalesced(), + ) + elif is_sparse_compressed(x): + if x.layout in {torch.sparse_csr, torch.sparse_bsr}: + compressed_indices = x.crow_indices() + plain_indices = x.col_indices() + else: + compressed_indices = x.ccol_indices() + plain_indices = x.row_indices() + return torch.sparse_compressed_tensor( + torch_clone(compressed_indices), + torch_clone(plain_indices), + torch_clone(x.values()), + x.shape, + layout=x.layout, + ) + elif is_traceable_wrapper_subclass(x): + # Questionable - but this is required to not fail executorch related + # torchao tests. + return torch_clone(x) + + needed_size = sum( + (shape - 1) * stride for shape, stride in zip(x.size(), x.stride()) + ) + if x.is_quantized: + result = torch.empty_quantized((needed_size + 32,), x) + else: + result = torch.empty( + needed_size + 32, + dtype=dtype or x.dtype, + device=x.device, + pin_memory=is_pinned_cpu_tensor(x), + ) + cache_line_offset = ( + (x.data_ptr() - result.data_ptr()) % 32 + ) // x.element_size() + result.as_strided_(x.size(), x.stride(), cache_line_offset) + try: + result.copy_(x.clone()) + if x.is_leaf: + result.requires_grad_(x.requires_grad) + if x.is_leaf and x.grad is not None: + result.grad = clone_input(x.grad, dtype=dtype) + except RuntimeError: + # RuntimeError: unsupported operation: more than one element of the written-to + # tensor refers to a single memory location. Please clone() the tensor before + # performing the operation. + return torch_clone(x) + copy_dynamo_tensor_attributes(x, result) + return result + + +@overload +def clone_inputs( + example_inputs: dict[str, T | tuple[T, ...]], +) -> dict[str, list[T]]: ... + + +@overload +def clone_inputs(example_inputs: Sequence[T]) -> list[T]: ... + + +def clone_inputs(example_inputs: Any) -> Any: + res: dict[str, Any] | list[Any] + if type(example_inputs) is dict: + res = dict(example_inputs) + for key, value in res.items(): + if isinstance(value, tuple): + res[key] = clone_inputs(value) + else: + if not isinstance(value, torch.Tensor): + raise AssertionError( + f"Expected value to be a torch.Tensor, got {type(value)}" + ) + res[key] = clone_input(value) + return res + + res = list(example_inputs) + for i in range(len(res)): + if isinstance(res[i], torch.Tensor): + res[i] = clone_input(res[i]) + return res + + +def skip_frame_if_in_functorch_mode(val: torch.Tensor) -> None: + try: + val.data_ptr() # will throw for functorch tensors + except RuntimeError as e: + from .exc import unimplemented + + # This will be GradTrackingTensor/BatchedTensor/etc + functorch_subclass_name = re.sub(r"\(.*", "", repr(val)) + + unimplemented( + gb_type="skip frame due to being in functorh mode", + context="", + explanation=f"torch.compile cannot be run in context: {functorch_subclass_name}. Skipping frame.", + hints=[], + from_exc=e, + skip_frame=True, + ) + + +@contextmanager +def preserve_rng_state() -> Generator[None, None, None]: + disable_functorch = torch._C._DisableFuncTorch + disable_current_modes = torch.utils._python_dispatch._disable_current_modes + with disable_current_modes(), disable_functorch(): + rng_state = torch.clone(torch.random.get_rng_state()) + skip_frame_if_in_functorch_mode(rng_state) + if torch.cuda.is_available(): + cuda_rng_state = torch.clone(torch.cuda.get_rng_state()) + if torch.xpu.is_available(): + xpu_rng_state = torch.clone(torch.xpu.get_rng_state()) + try: + yield + finally: + with torch.utils._python_dispatch._disable_current_modes(): + torch.random.set_rng_state(rng_state) + if torch.cuda.is_available(): + torch.cuda.set_rng_state(cuda_rng_state) # type: ignore[possibly-undefined] + if torch.xpu.is_available(): + torch.xpu.set_rng_state(xpu_rng_state) # type: ignore[possibly-undefined] + + +def is_jit_model( + model0: Any, +) -> TypeIs[ + torch.jit._trace.TopLevelTracedModule + | torch.jit._script.RecursiveScriptModule + | torch.jit.ScriptFunction[Any, Any] + | torch.jit.ScriptModule +]: + return isinstance( + model0, + ( + torch.jit._trace.TopLevelTracedModule, + torch.jit._script.RecursiveScriptModule, + torch.jit.ScriptFunction, + torch.jit.ScriptModule, + ), + ) + + +def torchscript(model: Any, example_inputs: Any, verbose: bool = False) -> Any: + if is_jit_model(model): + # already done? + return model + + try: + return torch.jit.trace(model, example_inputs) + except Exception: + try: + return torch.jit.script(model) + except Exception: + if verbose: + log.exception("jit error") + else: + log.error("Both torch.jit.trace and torch.jit.script failed") + return None + + +def getfile(obj: object) -> str | None: + try: + # inspect.getfile is typed to accept only a narrow union of callable + # and module-like objects, but at runtime it accepts any object and + # raises TypeError for unsupported ones, which this function catches. + return inspect.getfile(obj) # type: ignore[arg-type] + except (TypeError, OSError): + return None + + +def is_namedtuple(obj: object) -> bool: + """Test if an object is a namedtuple or a torch.return_types.* quasi-namedtuple""" + return is_namedtuple_cls(type(obj)) + + +def is_namedtuple_cls(cls: object) -> bool: + """Test if an object is a namedtuple or a (torch.return_types|torch.autograd.forward_ad).* quasi-namedtuple""" + if not isinstance(cls, type): + return False + try: + if issubclass(cls, tuple): + module = getattr(cls, "__module__", None) + if module in ("torch.return_types", "torch.autograd.forward_ad"): + return True + if isinstance(getattr(cls, "_fields", None), tuple) and callable( + getattr(cls, "_make", None) + ): + # The subclassing style namedtuple can have an extra base `typing.Generic` + bases = tuple(t for t in cls.__bases__ if t is not Generic) + if bases == (tuple,): + # This is a namedtuple type directly created by `collections.namedtuple(...)` + return True + if bases and any( + ( + # Subclass of namedtuple + is_namedtuple_cls(t) + # For subclasses of namedtuple, the __new__ method should not be customized + and cls.__new__ is t.__new__ + ) + for t in bases + ): + return True + except TypeError: + pass + return False + + +@functools.lru_cache(1) +def namedtuple_fields(cls: type) -> tuple[str, ...]: + """Get the fields of a namedtuple or a torch.return_types.* quasi-namedtuple""" + if cls is slice: + return ("start", "stop", "step") + + if not issubclass(cls, tuple): + raise AssertionError(f"Expected cls to be a subclass of tuple, got {cls}") + if hasattr(cls, "_fields"): + # normal namedtuples + return cls._fields + + @dataclasses.dataclass + class Marker: + index: int + + # frustrating ones e.g. torch.return_types.max + if cls.__module__ != "torch.return_types": + raise AssertionError( + f"Expected cls.__module__ to be 'torch.return_types', got {cls.__module__!r}" + ) + obj = cls(map(Marker, range(cls.n_fields))) # type: ignore[attr-defined] + fields: dict[str, int] = {} + for name in dir(obj): + if name[0] != "_" and isinstance(getattr(obj, name), Marker): + fields[name] = getattr(obj, name).index + if len(fields) != cls.n_fields: # type: ignore[attr-defined] + raise AssertionError( + f"Expected {cls.n_fields} fields, got {len(fields)}" # type: ignore[attr-defined] + ) + return tuple(sorted(fields, key=fields.get)) # type: ignore[arg-type] + + +def checkpoint_params(gm: torch.fx.GraphModule) -> Callable[[], None]: + with torch.no_grad(): + rng_state = torch.clone(torch.random.get_rng_state()) + if torch.cuda.is_available(): + cuda_rng_state = torch.clone(torch.cuda.get_rng_state()) + saved_state = [ + (param, param._version, torch.clone(param)) + # pyrefly: ignore [bad-argument-type] + for param in itertools.chain(gm.parameters(), gm.buffers()) + ] + + def restore() -> None: + with torch.no_grad(): + torch.random.set_rng_state(rng_state) + if torch.cuda.is_available(): + torch.cuda.set_rng_state(cuda_rng_state) + for param, version, original_value in saved_state: + if param._version != version: + param.copy_(original_value) + + return restore + + +def timed( + model: Any, example_inputs: Iterable[Any], times: int = 1 +) -> tuple[Any, float]: + if torch.accelerator.is_available(): + synchronize = torch.accelerator.synchronize + else: + synchronize = nothing + + synchronize() + gc.collect() + torch.manual_seed(1337) + t0 = time.perf_counter() + for _ in range(times): + result = model(*example_inputs) + synchronize() + t1 = time.perf_counter() + return result, t1 - t0 # type: ignore[possibly-undefined] + + +def check_is_cuda(gm: torch.fx.GraphModule, example_inputs: Iterable[Any]) -> bool: + return all(x.is_cuda for x in itertools.chain(example_inputs, gm.parameters(True))) + + +@lru_cache(32) +def rot_n_helper(n: int) -> Callable[..., Any]: + if n <= 1: + raise AssertionError(f"Expected n > 1, got {n}") + vars = [f"v{i}" for i in range(n)] + rotated = reversed(vars[-1:] + vars[:-1]) + fn = eval(f"lambda {','.join(vars)}: ({','.join(rotated)})") + fn.__name__ = f"rot_{n}_helper" + return fn + + +common_constant_types: set[type] = { + int, + float, + complex, + bool, + str, + bytes, + type(None), + Ellipsis.__class__, + NotImplemented.__class__, + types.CodeType, + # Commonly used immutable types from torch. + torch.device, + torch.dtype, + torch.memory_format, + torch.layout, + torch.finfo, + torch.iinfo, + torch.nn.attention.SDPBackend, + torch.cuda._CudaDeviceProperties, + # Pytree key types (frozen dataclasses used in tree_map_with_path) + torch.utils._pytree.SequenceKey, + torch.utils._pytree.MappingKey, + torch.utils._pytree.GetAttrKey, +} + +if has_triton_package(): + import triton + + common_constant_types.add(triton.language.dtype) + +""" + Difference between is_safe_constant and common_constant_types. + * common_constant_types: Constants would be wrapped by VariableBuilder.wrap_literal + as ConstantVariable. + * is_safe_constant: Constants can be loaded by LOAD_CONST bytecode. +""" + + +def is_safe_constant(v: object) -> bool: + if istype(v, (tuple, frozenset)): + return all(map(is_safe_constant, v)) + return isinstance( + v, + ( + enum.Enum, + type, + torch.Size, + typing._GenericAlias, # type: ignore[attr-defined] + types.GenericAlias, + ), + ) or istype( + v, + common_constant_types | {slice}, + ) + + +@functools.cache +def common_constants() -> set[int]: + return { + # We zero-one specialize shapes, so specialize these constants + # too + 0, + 1, + } + + +def is_torch_sym(value: object) -> TypeGuard[torch.SymBool | torch.SymInt]: + return isinstance(value, (torch.SymBool, torch.SymInt)) and not isinstance( + value.node, torch.nested._internal.nested_int.NestedIntNode + ) + + +def is_int_specialization_case(value: Any, source: Any) -> bool: + from .source import is_from_defaults + + return not TracingContext.get().force_unspec_int_unbacked_size_like and ( + # Assume integers from global variables want to be specialized + not source.guard_source.is_local() + # Assume that integers that came from NN modules want to be + # specialized (as we don't expect users to be changing the + # NN modules on the fly), unless explicitly disabled + or ( + source.guard_source.is_specialized_nn_module() + and not config.allow_unspec_int_on_nn_module + ) + or ( + source.guard_source.is_unspecialized_builtin_nn_module() + and not config.allow_unspec_int_on_nn_module + ) + or ( + source.guard_source.is_unspecialized_nn_module() + and not config.allow_unspec_int_on_nn_module + ) + or is_from_defaults(source) + # TODO: Delete this condition when rollout is done. NB: this + # condition never evaluates True in open source + or ( + not justknobs_check("pytorch/dynamo:enable_unspecialize_zero_one_plain_int") + and value in common_constants() + ) + ) + + +def specialize_symnode(arg: Any) -> Any: + from .variables import ConstantVariable, LazyVariableTracker, SymNodeVariable + from .variables.lazy import ComputedLazyConstantVariable + + # Guard and specialize + if isinstance(arg, LazyVariableTracker): + if not arg.is_realized() and not isinstance(arg, ComputedLazyConstantVariable): + # Find if the arg would be realized as SymNodeVariable later on. If yes, + # realize it and specialize. Else return the arg. + + source = arg.original_source() + value = arg.original_value() + + is_symnode_vt = is_torch_sym(value) or ( + not config.specialize_int + and type(value) is int + and not is_int_specialization_case(value, source) + ) + + if not is_symnode_vt: + return arg + + # Realize to get the underlying variable (handles both realized and unrealized) + arg = arg.realize() + + if isinstance(arg, SymNodeVariable): + return ConstantVariable.create(arg.evaluate_expr()) + return arg + + +def guard_if_dyn(arg: Any) -> Any: + from .variables import VariableTracker + + arg = specialize_symnode(arg) + + if isinstance(arg, VariableTracker) and arg.is_python_constant(): + return arg.as_python_constant() + + return arg + + +def check_constant_args(args: Iterable[Any], kwargs: Mapping[Any, Any]) -> bool: + return all(x.is_python_constant() for x in itertools.chain(args, kwargs.values())) + + +def check_unspec_python_args(args: Iterable[Any], kwargs: Mapping[Any, Any]) -> bool: + from .variables import VariableTracker + from .variables.tensor import UnspecializedPythonVariable + + unspec_count = 0 + for x in itertools.chain(args, kwargs.values()): + if isinstance(x, UnspecializedPythonVariable): + unspec_count += 1 + elif not (isinstance(x, VariableTracker) and x.is_python_constant()): + return False + return unspec_count > 0 + + +def check_unspec_or_constant_args( + args: Iterable[Any], kwargs: Mapping[Any, Any] +) -> bool: + # A fused version of: + # return check_constant_args(args, kwargs) or check_unspec_python_args(args, kwargs) + from .variables.tensor import UnspecializedPythonVariable + + for x in itertools.chain(args, kwargs.values()): + if not (x.is_python_constant() or isinstance(x, UnspecializedPythonVariable)): + return False + return True + + +def check_numpy_ndarray_args(args: Iterable[Any], kwargs: Mapping[Any, Any]) -> bool: + from .variables.tensor import NumpyNdarrayVariable + + return any( + isinstance(x, NumpyNdarrayVariable) + for x in itertools.chain(args, kwargs.values()) + ) + + +dict_keys: type[KeysView[Any]] = type({}.keys()) +dict_values: type[ValuesView[Any]] = type({}.values()) +dict_items: type[ItemsView[Any, Any]] = type({}.items()) +odict_values: type[ValuesView[Any]] = type(OrderedDict().values()) +# pyrefly: ignore [bad-assignment] +tuple_iterator: type[Iterator[Any]] = type(iter(())) +# pyrefly: ignore [bad-assignment] +range_iterator: type[Iterator[Any]] = type(iter(range(0))) +tuple_iterator_len = tuple_iterator.__length_hint__ # type: ignore[attr-defined] +deque_iterator = type(iter(collections.deque())) +deque_rev_iterator = type(reversed(collections.deque())) +object_new = object.__new__ +dict_new = dict.__new__ +dict_methods = { + method + for method in itertools.chain(dict.__dict__.values(), OrderedDict.__dict__.values()) + if callable(method) +} +set_methods = {method for method in set.__dict__.values() if callable(method)} +frozenset_methods = { + method for method in frozenset.__dict__.values() if callable(method) +} +base_exception_methods = { + method for method in BaseException.__dict__.values() if callable(method) +} +exception_methods = { + method for method in Exception.__dict__.values() if callable(method) +} + + +tuple_new = tuple.__new__ +tuple_methods = {method for method in tuple.__dict__.values() if callable(method)} +list_methods = {method for method in list.__dict__.values() if callable(method)} +list_getitem = list.__getitem__ + +deque_methods = { + method for method in collections.deque.__dict__.values() if callable(method) +} + +str_methods = {method for method in str.__dict__.values() if callable(method)} + +# EnumType is the metaclass for Enum classes +enum_type_methods = { + method for method in type(enum.Enum).__dict__.values() if callable(method) +} + +K = TypeVar("K") +V = TypeVar("V") + + +def builtin_dict_keys(d: dict[K, V]) -> KeysView[K]: + # Avoids overridden keys method of the dictionary + if not isinstance(d, dict): + raise AssertionError(f"Expected d to be a dict, got {type(d)}") + return dict.keys(d) + + +def get_items_from_dict(obj: dict[K, V]) -> Iterable[tuple[K, V | Any]]: + # Get items without calling the user defined __getitem__ or keys method. + if not isinstance(obj, dict): + raise AssertionError(f"Expected obj to be a dict, got {type(obj)}") + if istype(obj, (dict, OrderedDict)): + return obj.items() + elif isinstance(obj, OrderedDict): + return [(k, OrderedDict.__getitem__(obj, k)) for k in OrderedDict.keys(obj)] + else: + return [(k, dict.__getitem__(obj, k)) for k in dict.keys(obj)] + + +def enumerate_items_with_dict_position( + obj: dict[K, V], +) -> Iterable[tuple[int, K, V | Any]]: + """Enumerate dict items yielding (dict_keys_position, key, value). + + For OrderedDicts where move_to_end/prepend has been used, the OrderedDict + iteration order can differ from dict.keys() order. We iterate in + OrderedDict order (correct execution semantics) but return each key's + dict.keys() position so that ConstDictKeySource indices stay consistent + with PyDict_Next / C++ DictGuardManager. + """ + items = get_items_from_dict(obj) + if isinstance(obj, OrderedDict): + key_to_pos = {k: i for i, k in enumerate(dict.keys(obj))} + return ((key_to_pos[k], k, v) for k, v in items) + return ((i, k, v) for i, (k, v) in enumerate(items)) + + +def nn_module_new(cls: Any) -> Any: + obj = object_new(cls) + torch.nn.Module.__init__(obj) + return obj + + +def product(it: Iterable[T]) -> int: + return functools.reduce(operator.mul, it, 1) + + +def tuple_iterator_getitem(it: Any, index: int) -> Any: + _, (obj,), start = it.__reduce__() + return obj[start + index] + + +def dataclass_fields(cls: Any) -> Any: + return torch._dynamo.disable(dataclasses.fields)(cls) + + +iter_next = next + + +def normalize_count_iter(count_iter: Iterator[Any]) -> tuple[Any, Any]: + try: + _, args = count_iter.__reduce__() + except TypeError: + # Python 3.14 no longer pickles itertools.count, so fall back to the + # repr and only recover literal arguments. Non-literal arguments still + # fall back to user-defined handling via the NotImplemented sentinel. + import ast + + count_repr = repr(count_iter) + if not count_repr.startswith("count(") or not count_repr.endswith(")"): + return (NotImplemented, NotImplemented) + try: + args = ast.literal_eval(f"({count_repr[6:-1]},)") + except (SyntaxError, ValueError): + return (NotImplemented, NotImplemented) + if not isinstance(args, tuple) or not 1 <= len(args) <= 2: + return (NotImplemented, NotImplemented) + if len(args) == 1: + return (args[0], 1) + return (args[0], args[1]) + + +def normalize_range_iter(range_iter: Any) -> tuple[int, int, int]: + _, (range_obj,), maybe_idx = range_iter.__reduce__() + # In 3.12+, `maybe_idx` could be None, and `range_obj.start` would've been + # already incremented by the current index. + # The index (maybe_idx) is the number of steps taken so far. To get the + # correct start value, one must add (maybe_idx * step) to the original + # start. See: + # https://github.com/python/cpython/blob/ea77feecbba389916af8f90b2fc77f07910a2963/Objects/rangeobject.c#L885-L899 + start = range_obj.start + (maybe_idx or 0) * range_obj.step + stop = range_obj.stop + step = range_obj.step + return (start, stop, step) + + +def to_subclass(t: Any, cls: type) -> Any: + return t.as_subclass(cls) + + +dict_getitem = dict.__getitem__ + + +@torch.fx.wrap +def dict_keys_getitem(d: dict[Any, Any], n: int) -> Any: + # Use dict.keys() to match the iteration order of PyDict_Next used by + # the C++ DictGuardManager and by ConstDictKeySource._name_template. + # pyrefly: ignore [bad-argument-type] + return next(itertools.islice(dict.keys(d), n, n + 1)) + + +def set_base_iter(s: Iterable[T]) -> Iterator[T]: + if isinstance(s, set): + return set.__iter__(s) + if isinstance(s, frozenset): + return frozenset.__iter__(s) + return iter(s) + + +def set_getitem(s: set[T], n: int) -> T: + # Set ordering might not be stable. For set/frozenset subclasses, use the + # base iterator so guard reconstruction observes the internal set contents. + try: + return next(itertools.islice(set_base_iter(s), n, n + 1)) + except StopIteration: + raise IndexError("set index out of range") from None + + +def enum_repr(value: Any, local: bool) -> str: + # enum class can override __str__ method. Use __class__ and name attribute + # to extract the class name and key name. + name = value.__class__.__name__ + val = value.name + scope = "L" if local else "G" + local_name = f'{scope}["{name}"].{val}' + return local_name + + +def set_example_value(node: torch.fx.Node, example_value: Any) -> None: + # NB: example_value is a bit of a misnomer, because this is always a fake + # tensor of some sort. Furthermore, these example values serve as the + # runtime state of Dynamo tracing, which means if metadata mutation + # occurs, the example_value gets directly updated (so you can't rely on + # this to accurately reflect what the state of the value was at the time + # the program was traced). + node.meta["example_value"] = example_value + fake_mode = TracingContext.get().fake_mode + if fake_mode is None: + raise AssertionError("fake_mode must not be None") + shape_env = fake_mode.shape_env + if ( + symbol_to_path + := torch.fx.experimental.symbolic_shapes.compute_unbacked_bindings( + shape_env, example_value + ) + ): + node.meta["unbacked_bindings"] = symbol_to_path + + +def _get_fake_tensor(vt: VariableTracker) -> Any: + fake_tensor = vt.as_proxy().node.meta.get("example_value") + if not is_fake(fake_tensor): + from . import graph_break_hints + from .exc import unimplemented + + unimplemented( + gb_type="Cannot check Tensor object identity without its fake value", + context=str(fake_tensor), + explanation="TensorVariable is missing a fake example_value.", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + return fake_tensor + + +def slice_length(s: slice, seq_len: int) -> int: + start, stop, step = s.indices(seq_len) + return max(0, (stop - start + (step - (1 if step > 0 else -1))) // step) + + +def raise_args_mismatch( + tx: InstructionTranslatorBase, + name: str, + expect: str = "", + actual: str = "", +) -> NoReturn: + from torch._dynamo.exc import raise_observed_exception + + msg_str = ( + f"wrong number of arguments or keyword arguments for {name}() call.\n" + f" Expect: {expect}\n" + f" Actual: {actual}" + ) + + raise_observed_exception( + TypeError, + tx, + args=[msg_str], + ) + + +def check_positional( + tx: InstructionTranslatorBase, + funcname: str, + nargs: int, + min_args: int, + max_args: int, +) -> None: + # Mirrors CPython _PyArg_CheckPositional (Python/getargs.c): enforce + # min_args <= nargs <= max_args with CPython's exact TypeError text. Used + # for METH_FASTCALL methods, whose positional count MethodFlags (derived + # from ml_flags) cannot check. + from torch._dynamo.exc import raise_type_error + + if nargs < min_args: + rel = "" if min_args == max_args else "at least " + s = "" if min_args == 1 else "s" + raise_type_error( + tx, f"{funcname} expected {rel}{min_args} argument{s}, got {nargs}" + ) + if nargs > max_args: + rel = "" if min_args == max_args else "at most " + s = "" if max_args == 1 else "s" + raise_type_error( + tx, f"{funcname} expected {rel}{max_args} argument{s}, got {nargs}" + ) + + +def no_positional( + tx: InstructionTranslatorBase, funcname: str, args: list[VariableTracker] +) -> None: + # Mirrors CPython _PyArg_NoPositional (Python/getargs.c). + from torch._dynamo.exc import raise_type_error + + if args: + raise_type_error(tx, f"{funcname}() takes no positional arguments") + + +def no_keywords( + tx: InstructionTranslatorBase, funcname: str, kwargs: dict[str, VariableTracker] +) -> None: + # Mirrors CPython _PyArg_NoKeywords / _PyArg_NoKwnames (Python/getargs.c). + # For methods reached via tp_methods, MethodFlags already rejects kwargs; + # use this only where MethodFlags does not run (e.g. tp_init constructors). + from torch._dynamo.exc import raise_type_error + + if kwargs: + raise_type_error(tx, f"{funcname}() takes no keyword arguments") + + +def iter_contains( + items: Iterable[VariableTracker], + search: VariableTracker, + tx: InstructionTranslatorBase, +) -> VariableTracker: + from .variables import ConstantVariable + from .variables.object_protocol import generic_richcompare_bool + + items = list(items) + # CPython's list_contains/set_contains use PyObject_RichCompareBool(item, + # search, Py_EQ) with an identity shortcut. The constant fast path is only + # valid when every element is a constant too; a non-constant element earlier + # in the sequence has an __eq__ that must be honored in order (it may match, + # or raise), so fall through to the per-element richcompare loop otherwise. + if search.is_python_constant() and all(x.is_python_constant() for x in items): + search_val = search.as_python_constant() + found_const = any( + x.as_python_constant() is search_val or x.as_python_constant() == search_val + for x in items + ) + return ConstantVariable.create(found_const) + found: VariableTracker | None = None + for x in items: + check = generic_richcompare_bool(tx, x, search, "__eq__") + if check.is_constant_match(True): + return check + if check.is_constant_match(False): + continue + if found is None: + found = check + else: + from torch._dynamo.variables.builder import SourcelessBuilder + + found = SourcelessBuilder.create(tx, operator.or_).call_function( + tx, [check, found], {} + ) + if found is None: + found = ConstantVariable.create(False) + return found + + +def key_is_id( + k: Any, +) -> TypeIs[torch.Tensor | torch.nn.Module | MethodWrapperType]: + """Returns whether it indexes dictionaries using its id""" + return isinstance(k, (torch.Tensor, torch.nn.Module, MethodWrapperType)) + + +def key_to_id(value: Any) -> list[Any]: + return [id(k) if key_is_id(k) else k for k in value] + + +def const_repr(x: Any, *, local: Any) -> str: + from .trace_rules import is_builtin_callable + + if isinstance(x, (list, tuple)): + elems_repr = ",".join(const_repr(s, local=local) for s in x) + if isinstance(x, list): + return f"[{elems_repr}]" + else: + if not isinstance(x, tuple): + raise AssertionError(f"Expected x to be a tuple, got {type(x)}") + if len(x) == 1: + return f"({elems_repr},)" + else: + return f"({elems_repr})" + elif isinstance(x, enum.Enum): + # To workaround repr(Enum) returning invalid global reference before python 3.11 + # by calling enum_repr and removing quotes to render enum in guard code. + return enum_repr(x, local=local).replace("'", "") + elif is_builtin_callable(x): + return x.__name__ + elif isinstance(x, type): + + def fullname(o: Any) -> str: + klass = o.__class__ + module = klass.__module__ + if module == "builtins": + return klass.__qualname__ # avoid outputs like 'builtins.str' + return module + "." + klass.__qualname__ + + return fullname(x) + else: + return f"{x!r}" + + +def dict_keys_repr(const_keys: Any, *, local: Any) -> str: + keys_str = ",".join(const_repr(s, local=local) for s in const_keys) + return "[" + keys_str + "]" + + +GLOBAL_KEY_PREFIX = "__dict_key" + + +from torch._subclasses import UnsupportedFakeTensorException + + +def get_safe_global_name(tx: InstructionTranslatorBase, root: str, obj: Any) -> str: + # The global_mangled_class_name should be different for different + # invocations of torch.compile. Otherwise, we can run into a situation + # where multiple torch.compile invocations reuse the same global name, + # but the global's lifetime is tied to the first invocation (and + # may be deleted when the first torch.compile invocation is deleted) + # We mangle it based off of the output_graph's id. + return f"{root}_{id(obj)}_c{tx.output.compile_id}" + + +def is_in(item: T, *containers: Container[T]) -> bool: + for container in containers: + if item in container: + return True + return False + + +def get_unique_name_wrt( + prefix: str, *containers: Any, requires_suffix: bool = False +) -> str: + """ + Return a name that starts with `prefix` and is not in any of the + `containers` (e.g., map, set). + """ + if not requires_suffix and not is_in(prefix, *containers): + return prefix + + for i in itertools.count(): + candidate = f"{prefix}_{i}" + if not is_in(candidate, *containers): + return candidate + + raise AssertionError("unreachable") + + +def wrap_fake_exception(fn: Callable[[], Any]) -> Any: + try: + return fn() + except UnsupportedFakeTensorException as e: + from .exc import unimplemented + + msg = f"Encountered exception ({e.reason}) during fake tensor propagation." + log.warning(msg) + unimplemented( + gb_type="Fake tensor propagation exception", + context=str(e.reason), + explanation=msg, + hints=[], + from_exc=e, + ) + + +def deepcopy_to_fake_tensor( + obj: Any, fake_mode: torch._subclasses.fake_tensor.FakeTensorMode +) -> Any: + with torch._subclasses.fake_tensor.FakeCopyMode(fake_mode): + return wrap_fake_exception(lambda: copy.deepcopy(obj)) + + +def rmse(ref: torch.Tensor, res: torch.Tensor) -> torch.Tensor: + """ + Calculate root mean squared error + """ + return torch.sqrt(torch.mean(torch.square(ref - res))) + + +def bitwise_same(ref: Any, res: Any, equal_nan: bool = False) -> bool: + return same( + ref, + res, + tol=0.0, + equal_nan=equal_nan, + ) + + +def same( + ref: Any, + res: Any, + fp64_ref: Any = None, + cos_similarity: bool = False, + tol: float = 1e-4, + equal_nan: bool = False, + exact_dtype: bool = True, + relax_numpy_equality: bool = False, + ignore_non_fp: bool = False, + log_error: Callable[..., None] = log.error, + use_larger_multiplier_for_smaller_tensor: bool = False, + force_max_multiplier: bool = False, + use_iou_for_bool: bool = False, + iou_threshold: float = 0.99, +) -> bool: + """Check correctness to see if ref and res match""" + if fp64_ref is None: + fp64_ref = ref + if isinstance( + ref, (list, tuple, collections.deque, torch.nn.ParameterList, torch.Size) + ): + if not isinstance(res, (list, tuple, collections.deque)): + raise AssertionError(f"type mismatch {type(ref)} {type(res)}") + if len(ref) != len(res): + log_error("Length mismatch") + return False + return len(ref) == len(res) and all( + same( + ai, + bi, + fp64_refi, + cos_similarity, + tol, + equal_nan, + exact_dtype, + relax_numpy_equality, + ignore_non_fp, + log_error=log_error, + use_larger_multiplier_for_smaller_tensor=use_larger_multiplier_for_smaller_tensor, + force_max_multiplier=force_max_multiplier, + use_iou_for_bool=use_iou_for_bool, + iou_threshold=iou_threshold, + ) + for ai, bi, fp64_refi in zip(ref, res, fp64_ref) + ) + elif type(ref).__name__ == "QuestionAnsweringModelOutput": + # This skips checking accuracy for start_logits/end_logits. + # Tentatively, start_logits/end_logits appear to be very prone to + # inaccuracies and is somewhat subsumed by checking the loss. + return same( + ref.loss, + res.loss, + fp64_ref.loss, + cos_similarity, + tol, + equal_nan, + exact_dtype, + relax_numpy_equality, + ignore_non_fp, + log_error=log_error, + use_larger_multiplier_for_smaller_tensor=use_larger_multiplier_for_smaller_tensor, + force_max_multiplier=force_max_multiplier, + use_iou_for_bool=use_iou_for_bool, + iou_threshold=iou_threshold, + ) + elif isinstance(ref, dict): + if not isinstance(res, dict): + raise AssertionError(f"Expected res to be a dict, got {type(res)}") + if set(ref.keys()) != set(res.keys()): + raise AssertionError( + f"keys mismatch {set(ref.keys())} == {set(res.keys())}" + ) + for k in sorted(ref.keys()): + if not ( + same( + ref[k], + res[k], + fp64_ref[k], + cos_similarity=cos_similarity, + tol=tol, + equal_nan=equal_nan, + exact_dtype=exact_dtype, + relax_numpy_equality=relax_numpy_equality, + ignore_non_fp=ignore_non_fp, + log_error=log_error, + use_larger_multiplier_for_smaller_tensor=use_larger_multiplier_for_smaller_tensor, + force_max_multiplier=force_max_multiplier, + use_iou_for_bool=use_iou_for_bool, + iou_threshold=iou_threshold, + ) + ): + log_error("Accuracy failed for key name %s", k) + return False + return True + elif isinstance(ref, set): + if not isinstance(res, set): + raise AssertionError(f"Expected res to be a set, got {type(res)}") + if set(ref) != set(res): + raise AssertionError(f"elements mismatch {set(ref)} == {set(res)}") + return True + elif isinstance(ref, (torch.Tensor, float)): + if torch._subclasses.fake_tensor.is_fake_tensor(ref): + raise AssertionError("ref should not be a FakeTensor") + if torch._subclasses.fake_tensor.is_fake_tensor(res): + raise AssertionError("res should not be a FakeTensor") + + def to_tensor(t: Any) -> torch.Tensor: + return t if isinstance(t, torch.Tensor) else torch.tensor(t) + + ref, res, fp64_ref = (to_tensor(val) for val in (ref, res, fp64_ref)) + + if ref.is_sparse: + if not res.is_sparse: + raise AssertionError("Expected res to be sparse since ref is sparse") + ref = ref.to_dense() + res = res.to_dense() + if not isinstance(res, torch.Tensor): + raise AssertionError(f"type mismatch {type(ref)} {type(res)}") + if exact_dtype: + if ref.dtype != res.dtype: + log_error("dtype mismatch %s, %s", ref.dtype, res.dtype) + return False + if ref.dtype == torch.bool: + if ignore_non_fp: + return True + if use_iou_for_bool: + # Use IoU (Intersection over Union) metric for boolean mask comparison. + # This is useful for segmentation models where small floating-point + # differences get thresholded into boolean masks. + intersection = (ref & res).sum().float() + union = (ref | res).sum().float() + if union == 0: + # Both masks are empty + return bool(intersection == 0) + iou = (intersection / union).item() + if iou < iou_threshold: + log_error( + "IoU accuracy failed: %.4f < %.2f (intersection=%d, union=%d, ref_sum=%d, res_sum=%d, shape=%s)", + iou, + iou_threshold, + int(intersection.item()), + int(union.item()), + int(ref.sum().item()), + int(res.sum().item()), + list(ref.shape), + ) + return False + return True + # triton stores bool as int8, so add this for more accurate checking + r = torch.allclose( + ref.to(dtype=torch.uint8), + res.to(dtype=torch.uint8), + atol=tol, + rtol=tol, + equal_nan=equal_nan, + ) + if not r: + log_error("Accuracy failed: uint8 tensor did not match") + return r + + if cos_similarity: + ref = ref.flatten().to(torch.float32) + res = res.flatten().to(torch.float32) + if torch.allclose(ref, res, atol=tol, rtol=tol, equal_nan=True): + # early exit that handles zero/nan better + # cosine_similarity(zeros(10), zeros(10), dim=0) is 0 + return True + score = torch.nn.functional.cosine_similarity(ref, res, dim=0, eps=1e-6) + if score < 0.99: + log.warning("Similarity score=%s", score.detach().cpu().item()) + return bool(score >= 0.99) + else: + if not exact_dtype: + ref = ref.to(res.dtype) + + # First try usual allclose + if torch.allclose(ref, res, atol=tol, rtol=tol, equal_nan=equal_nan): + return True + + # Check error from fp64 version + if fp64_ref.dtype == torch.float64: + # Fix a corner case that res and fp64_ref does not contains NaN and match (with loose tolerance) + # while the ref contains NaN. In this case, RMSE should not match any ways. + # But res is 'BETTER' than ref so we count it pass. + # + # This happens for Super_SloMo when loop ordering after fusion is enabled: + # https://gist.github.com/shunting314/11f235c70f7db0d52718d26f4a701cab + loose_tol = 1e-2 * 4 + if ( + not fp64_ref.isnan().any() + and not res.isnan().any() + and ref.isnan().any() + and torch.allclose( + fp64_ref.to(dtype=res.dtype), + res, + atol=loose_tol, + rtol=loose_tol, + equal_nan=equal_nan, + ) + ): + return True + ref_error = rmse(fp64_ref, ref).item() + # ref unable to produce this with stable numerics in this precision, ignore + if math.isnan(ref_error): + log.warning( + "Found nan in reference. Consider running in higher precision." + ) + + res_error = rmse(fp64_ref, res).item() + + def get_multiplier() -> float: + # In some particular cases, we expect high difference in results. + # At the moment one of these cases is inductor freezing bfloat16 convolution const folding. + # In this case, the res_error is at least one order of magnitude higher. + if force_max_multiplier: + return 10.0 + # In the case of using AMP (Automatic Mixed Precision), certain models have + # failed the benchmark's correctness check. However, the end-to-end model's + # accuracy when comparing AMP with FP32 is within a difference of less than 0.1%. + # Thus, it's possible that the correctness check failures for these models are + # false alarms. We use multiplier of 3 instead of 2 to avoid these false alarms. + multiplier = ( + 3.0 if res.dtype in (torch.float16, torch.bfloat16) else 2.0 + ) + + if use_larger_multiplier_for_smaller_tensor and ( + fp64_ref.numel() <= 10 + ): + multiplier = 10.0 + elif use_larger_multiplier_for_smaller_tensor and ( + fp64_ref.numel() <= 500 + ): + multiplier = 8.0 + elif ( + fp64_ref.numel() < 1000 + or (ref.ndim == 4 and ref.shape[-1] == ref.shape[-2] == 1) + # large tol means a benchmark has been specified as REQUIRE_HIGHER_TOLERANCE + or tol >= 2 * 1e-2 + ): + # In the presence of noise, noise might dominate our error + # metric for smaller tensors. + # Similarly, for 1x1 kernels, there seems to be high noise with amp. + multiplier = 3.0 + return multiplier + + multiplier = get_multiplier() + + passes_test = res_error <= (multiplier * ref_error + tol / 10.0) + if ( + not passes_test + and equal_nan + and math.isnan(ref_error) + and math.isnan(res_error) + # Some unit test for the accuracy minifier relies on + # returning false in this case. + and not torch._inductor.config.cpp.inject_relu_bug_TESTING_ONLY + ): + passes_test = True + if not passes_test: + log_error( + "RMSE (res-fp64): %.5f, (ref-fp64): %.5f and shape=%s. res.dtype: %s, multiplier: %f, tol: %f" + ", use_larger_multiplier_for_smaller_tensor: %d", + res_error, + ref_error, + res.size(), + res.dtype, + multiplier, + tol, + use_larger_multiplier_for_smaller_tensor, + ) + return passes_test + + if ignore_non_fp: + return True + + log_error("Accuracy failed: allclose not within tol=%s", tol) + return False + elif isinstance(ref, (str, int, type(None), bool, torch.device)): + if ignore_non_fp: + return True + r = ref == res + if not r: + log_error("Accuracy failed (%s): %s != %s", type(ref), ref, res) + return r + elif is_numpy_int_type(ref) or is_numpy_float_type(ref): + if relax_numpy_equality and not ( + is_numpy_int_type(res) or is_numpy_float_type(res) + ): + ref = ref.item() + r = (type(ref) is type(res)) and (ref == res) + if not r: + log_error("Accuracy failed (numpy): %s != %s", ref, res) + return r + elif is_numpy_ndarray(ref): + return (type(ref) is type(res)) and same( + torch.as_tensor(ref), + torch.as_tensor(res), + fp64_ref, + cos_similarity=cos_similarity, + tol=tol, + equal_nan=equal_nan, + exact_dtype=exact_dtype, + relax_numpy_equality=relax_numpy_equality, + ignore_non_fp=ignore_non_fp, + log_error=log_error, + use_larger_multiplier_for_smaller_tensor=use_larger_multiplier_for_smaller_tensor, + force_max_multiplier=force_max_multiplier, + use_iou_for_bool=use_iou_for_bool, + iou_threshold=iou_threshold, + ) + elif type(ref).__name__ in ( + "MaskedLMOutput", + "Seq2SeqLMOutput", + "CausalLMOutputWithCrossAttentions", + "LongformerMaskedLMOutput", + "Instances", + "SquashedNormal", + "Boxes", + "Normal", + "TanhTransform", + "Foo", + "Variable", + ): + if type(ref) is not type(res): + raise AssertionError(f"type mismatch {type(ref)} {type(res)}") + return all( + same( + getattr(ref, key), + getattr(res, key), + getattr(fp64_ref, key), + cos_similarity=cos_similarity, + tol=tol, + equal_nan=equal_nan, + exact_dtype=exact_dtype, + relax_numpy_equality=relax_numpy_equality, + ignore_non_fp=ignore_non_fp, + log_error=log_error, + use_larger_multiplier_for_smaller_tensor=use_larger_multiplier_for_smaller_tensor, + force_max_multiplier=force_max_multiplier, + use_iou_for_bool=use_iou_for_bool, + iou_threshold=iou_threshold, + ) + for key in ref.__dict__ + ) + else: + raise RuntimeError(f"unsupported type: {type(ref).__name__}") + + +def format_func_info(code: CodeType) -> str: + short_filename = code.co_filename.split("/")[-1] + return f"'{code.co_name}' ({short_filename}:{code.co_firstlineno})" + + +@contextlib.contextmanager +def disable_cache_limit() -> Generator[None, None, None]: + prior = config.recompile_limit + # pyrefly: ignore [bad-assignment] + config.recompile_limit = sys.maxsize + prior_acc_limit = config.accumulated_recompile_limit + # pyrefly: ignore [bad-assignment] + config.accumulated_recompile_limit = sys.maxsize + + try: + yield + finally: + config.recompile_limit = prior + config.accumulated_recompile_limit = prior_acc_limit + + +# map from transformed code back to original user code +orig_code_map = ExactWeakKeyDictionary() + +# keep a record of code_obj -> list of guard failure reasons for logging +guard_failures: collections.defaultdict[Any, list[Any]] = collections.defaultdict(list) + +# Keep a record of graph break reasons for logging +graph_break_reasons: list[torch._dynamo.output_graph.GraphCompileReason] = [] + +# keep record of compiled code, if we are in "error if recompile" +# to track code that dynamo has compiled previously +seen_code_map = ExactWeakKeyDictionary() + + +# return same dir unless user changes config between calls +@functools.cache +def _get_debug_dir(root_dir: str) -> str: + dir_name = ( + "run_" + + datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S_%f") + # use pid to avoid conflicts among ranks + + "-pid_" + + str(os.getpid()) + ) + return os.path.join(root_dir, dir_name) + + +def get_debug_dir() -> str: + debug_root = config.debug_dir_root + return _get_debug_dir(debug_root) + + +def extract_fake_example_value(node: torch.fx.Node, required: bool = True) -> Any: + if "example_value" in node.meta and is_fake(node.meta["example_value"]): + return node.meta["example_value"] + elif required: + from torch._dynamo.exc import unimplemented + + from . import graph_break_hints + + unimplemented( + gb_type="Missing FakeTensor example value", + context=str(node), + explanation=f"`FakeTensor` example value was required for {node} but not available.", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + else: + return None + + +def ensure_graph_fake(e: Any, tx: InstructionTranslatorBase) -> Any: + from torch._subclasses.fake_tensor import maybe_get_fake_mode + + if maybe_get_fake_mode(e) is not tx.fake_mode: + raise AssertionError( + f"Expected fake mode of e to be tx.fake_mode, got {maybe_get_fake_mode(e)} vs {tx.fake_mode}" + ) + return e + + +def get_fake_values_from_nodes( + tx: InstructionTranslatorBase, nodes: Any, allow_non_graph_fake: bool +) -> Any: + def visit(n: torch.fx.Node) -> Any: + if n.op == "call_function" and "example_value" not in n.meta: + # fake tensor validity is checked inside get_fake_value using + # ensure_graph_fake + return get_fake_value(n, tx, allow_non_graph_fake) + + elif n.op == "get_attr" and "example_value" not in n.meta: + if n.target not in tx.output.nn_modules: + raise AssertionError( + f"Expected n.target {n.target!r} to be in tx.output.nn_modules" + ) + gm = tx.output.nn_modules[n.target] # type: ignore[index] + if not isinstance(gm, torch.fx.GraphModule): + raise AssertionError( + f"Expected gm to be a torch.fx.GraphModule, got {type(gm)}" + ) + return gm + + out = n.meta["example_value"] + if not allow_non_graph_fake and isinstance(out, torch.Tensor): + return ensure_graph_fake(out, tx) + return out + + return torch.fx.node.map_arg(nodes, visit) + + +def get_concrete_sizes_from_symints(msg: str, fake_mode: FakeTensorMode | None) -> str: + """ + Replace symbolic size expressions (like 's0', 's94') in error messages + with their concrete runtime values for better readability. + + Example: "size (s94)" -> "size (s94: hint= 10)" if s94's value is 10. + """ + import re + + from sympy.core.numbers import Integer + + if fake_mode is None: + return msg + + pattern = r"\(s(\d+)\)" + if fake_mode.shape_env is None: + raise AssertionError("fake_mode.shape_env must not be None") + shape_env = fake_mode.shape_env + backed_var_to_val = shape_env.backed_var_to_val + + def replace_sym(match: Any) -> str: + sym_name = f"s{match.group(1)}" + val = next( + (v for k, v in backed_var_to_val.items() if k.name == sym_name), + None, + ) + if isinstance(val, (int, Integer)): + return f"({sym_name}: hint = {str(val)})" + return match.group(0) + + msg = re.sub(pattern, replace_sym, msg) + return msg + + +def _wrap_graph_break_with_torch_runtime_err(gb_fn: Callable[[], NoReturn]) -> NoReturn: + from .exc import TorchRuntimeError, Unsupported + + try: + gb_fn() + except Unsupported as e: + exc = TorchRuntimeError(str(e), getattr(e, "real_stack", None)) + raise exc.with_traceback(e.__traceback__) from None + raise AssertionError("should be unreachable") + + +def _custom_op_fake_impl_pending(tx: InstructionTranslatorBase, target: Any) -> bool: + """True if ``target`` is a custom op whose ``register_fake`` ran earlier in + this trace -- i.e. its ``_abstract_fn`` has a pending (not-yet-applied) + attribute mutation. Distinguishes an op defined+register_fake'd inside the + compiled function (recoverable via graph break) from a genuinely + unregistered op (should hard-error with actionable guidance). + + Only detects the ``CustomOpDef.register_fake`` method form (a tracked + pending ``_abstract_fn`` store on ``tx.output.side_effects``); other forms + (e.g. an op with no ``CustomOpDef``, or a definition inside a HOP body whose + mutation lives in a subtracer) fall through to the hard error, preserving + pre-existing behavior.""" + if not isinstance(target, torch._ops.OpOverload): + return False + from torch._library.custom_ops import _maybe_get_opdef + + opdef = _maybe_get_opdef(target) + if opdef is None: + return False + side_effects = tx.output.side_effects + vt = side_effects.id_to_variable.get(id(opdef)) + if vt is None: + return False + return side_effects.has_pending_mutation_of_attr(vt, "_abstract_fn") + + +def get_fake_value( + node: torch.fx.Node, + tx: InstructionTranslatorBase, + allow_non_graph_fake: bool = False, +) -> Any: + _t0 = time.time_ns() + try: + return _get_fake_value_impl(node, tx, allow_non_graph_fake) + finally: + tx.output.bytecode_tracing_timings.get_fake_value_ns += time.time_ns() - _t0 + + +def _get_fake_value_impl( + node: torch.fx.Node, + tx: InstructionTranslatorBase, + allow_non_graph_fake: bool = False, +) -> Any: + """ + Run the computation represented by `node` using fake tensors and return the result. + + allow_non_graph_fake: whether to allow the return result to be: + 1. non-fake or 2. fake that is not created by this instance of Dynamo. + If `True`, you must be prepared to deal with such return values, ideally + by further wrapping them as this graph's fakes. + """ + from torch.utils._sympy.value_ranges import ValueRangeError + + from . import graph_break_hints + from .exc import unimplemented, Unsupported, UserError, UserErrorType + + op = node.op + + # FX Node should always return the same fake value + if "example_value" in node.meta and is_fake(node.meta["example_value"]): + return node.meta["example_value"] + + args, kwargs = get_fake_values_from_nodes( + tx, (node.args, node.kwargs), allow_non_graph_fake + ) + + if ( + torch._dynamo.config.use_graph_deduplication + or torch._dynamo.config.track_nodes_for_deduplication + ): + flat_args_kwargs = get_fake_values_from_nodes( + tx, _get_flat_args(node, {}), allow_non_graph_fake + ) + id_to_initial_version = { + id(arg): arg._version for arg in flat_args_kwargs if is_fake(arg) + } + else: + # pyrefly: ignore [implicit-any] + flat_args_kwargs = [] + # pyrefly: ignore [implicit-any] + id_to_initial_version = {} + + nnmodule = None + fake_mode = tx.fake_mode + if fake_mode is None: + raise AssertionError("fake_mode must not be None") + if op == "call_method" and len(args) > 0 and isinstance(args[0], torch.nn.Module): + # If the first argument is nn.Module, should copy to fake mode. + args = (deepcopy_to_fake_tensor(args[0], fake_mode),) + tuple(args[1:]) + + if op == "call_module": + nnmodule = tx.output.nn_modules[node.target] # type: ignore[index] + + if ( + is_lazy_module(nnmodule) + and inspect.getattr_static(nnmodule, "_initialize_hook", None) is not None + ): + # In the case of a lazy module, we want to run + # the pre-hooks which initialize it. + # Afterwards, lazy module deletes its pre-hooks + # to avoid treating it as lazy on subsequent recompile. + nnmodule._infer_parameters(nnmodule, args) + + # no matter it's lazy module or not, we should copy to fake mode. + nnmodule = deepcopy_to_fake_tensor(nnmodule, fake_mode) + + if node.name in ["interpolate", "is_integer", "wrapped_gradient"] or any( + isinstance(a, complex) for a in args + ): + # We need to specialize symfloats for now. Eventually we should do a tensorify pass in dynamo. + args = tuple( + ( + float(arg) + if isinstance(arg, torch.SymFloat) and arg.node.hint is not None + else arg + ) + for arg in args + ) + + try: + from torch._dynamo.eval_frame import _use_eager_on_nested_compile + + with fake_mode, enable_python_dispatcher(), _use_eager_on_nested_compile(): + ret_val = wrap_fake_exception( + lambda: run_node(tx.output, node, args, kwargs, nnmodule) + ) + except Unsupported: + raise + except RuntimeError as e: + cause: BaseException = e + if e.__cause__ is not None: + cause = e.__cause__ + + if isinstance( + cause, torch._subclasses.fake_tensor.DataDependentOutputException + ): + # capture_scalar_outputs only works for these ops right now + # see torch/_subclasses/fake_impls.py + if cause.func in ( + torch.ops.aten.item.default, + torch.ops.aten._local_scalar_dense.default, + ): + # does this actually get triggered? + hints = [ + "Enable tracing of data-dependent output operators with " + "`torch._dynamo.config.capture_scalar_outputs = True`", + ] + else: + hints = [ + "Consider wrapping the operator into a PyTorch-understood custom operator " + "(see https://pytorch.org/tutorials/advanced/custom_ops_landing_page.html)", + ] + unimplemented( + gb_type="Data dependent operator", + context=str(cause.func), + explanation=f"Operator `{cause.func}` has a non-Tensor output " + "whose value is dependent on the data of Tensor inputs.", + hints=hints, + from_exc=cause, + ) + elif isinstance( + cause, torch._subclasses.fake_tensor.DynamicOutputShapeException + ): + if not torch._dynamo.config.capture_dynamic_output_shape_ops: + unimplemented( + gb_type="Dynamic shape operator", + context=str(cause.func), + explanation=f"Operator `{cause.func}`'s output shape depends on input Tensor data.", + hints=[ + "Enable tracing of dynamic shape operators with " + "`torch._dynamo.config.capture_dynamic_output_shape_ops = True`", + ], + from_exc=cause, + ) + else: + unimplemented( + gb_type="Dynamic shape operator (no meta kernel)", + context=str(cause.func), + explanation=f"Operator `{cause.func}` does not have a meta kernel that supports dynamic output shapes", + hints=[ + "Please report an issue to PyTorch", + ], + from_exc=cause, + ) + elif isinstance( + cause, torch._subclasses.fake_tensor.UnsupportedOperatorException + ): + op = cause.func # type: ignore[assignment] + import_suggestion = "" + if isinstance(op, torch._ops.OpOverload): + maybe_pystub = torch._C._dispatch_pystub( + op._schema.name, op._schema.overload_name + ) + if maybe_pystub is not None: + module, ctx = maybe_pystub + import_suggestion = ( + f"It's possible that the support was implemented in " + f"module `{module}` and you may need to `import {module}`" + f"({ctx}), otherwise " + ) + unimplemented( + gb_type="Operator does not support running with fake tensors", + context=f"unsupported operator: {cause.func}", + explanation="", + hints=[ + f"{import_suggestion}see " + "https://docs.google.com/document/d/1GgvOe7C8_NVOMLOCwDaYV1mXXyHMXY7ExoewHqooxrs/edit#heading=h.64r4npvq0w0" + " for how to fix", + ], + from_exc=cause, + ) + elif isinstance( + cause, torch.fx.experimental.symbolic_shapes.GuardOnDataDependentSymNode + ): + raise UserError( + UserErrorType.CONSTRAINT_VIOLATION, + str(cause), + case_name="constrain_as_size_example", + ) from cause + elif isinstance( + cause, torch._subclasses.fake_tensor.FakeTensorDeviceMismatchError + ): + _wrap_graph_break_with_torch_runtime_err( + lambda: unimplemented( + gb_type="Tensor device mismatch", + context=f"{op} {node.target}", + explanation=str(cause), + hints=["Move inputs, parameters, and buffers to the same device."], + from_exc=cause, + ) + ) + raise AssertionError("should not be reachable") from None + elif isinstance(cause, ValueRangeError): + raise UserError(UserErrorType.CONSTRAINT_VIOLATION, e.args[0]) from e + elif isinstance(cause, TypeError) and "argument" in str(cause): + unimplemented( + gb_type="TypeError when making fake tensor call", + context=f"TypeError {node.target}: {cause}", + explanation="", + hints=[*graph_break_hints.USER_ERROR], + from_exc=cause, + ) + elif "no fake impl registered" in str(cause) and _custom_op_fake_impl_pending( + tx, node.target + ): + # A custom op was defined and register_fake'd inside the compiled + # function, then called. Under nested graph breaks Dynamo traces + # into the inlined op definition, so register_fake's mutation of + # _abstract_fn is recorded as a pending side effect rather than run + # eagerly; it is not yet applied to the real op when the op is called + # here, so its fake kernel raises "no fake impl registered". (Without + # nested graph breaks the definition graph-breaks and the op is fully + # registered before the call, so this path is not hit.) Graph break: + # the definition (and register_fake) run eagerly and the op call + # itself falls back to eager -- it is not captured into the resumed + # graph. Unlike the generic RuntimeError below this is recoverable, + # so do NOT wrap it as a hard TorchRuntimeError. + # NB: gated on a pending _abstract_fn mutation so a genuinely + # unregistered op still hard-errors below with actionable guidance. + unimplemented( + gb_type="Custom op missing fake impl during tracing", + context=f"{node.target}", + explanation="A custom operator was defined and register_fake'd " + "inside the compiled function, then called before the " + "register_fake side effect was applied.", + hints=[*graph_break_hints.SUPPORTABLE], + from_exc=cause, + ) + msg = get_concrete_sizes_from_symints(str(e), fake_mode) + from .exc import ( + FakeTensorObservedException, + ObservedException, + raise_observed_exception, + ) + + if not node.users: + tx.output.graph.erase_node(node) + try: + raise_observed_exception(RuntimeError, tx, args=[msg]) + except ObservedException as e: + raise FakeTensorObservedException(msg, real_stack=e.real_stack) from None + + if not allow_non_graph_fake: + _ = pytree.tree_map_only( + torch.Tensor, + functools.partial(ensure_graph_fake, tx=tx), + ret_val, # type: ignore[unbound-name] + ) + + if ( + torch._dynamo.config.use_graph_deduplication + or torch._dynamo.config.track_nodes_for_deduplication + ): + tx.output.region_tracker.track_node_mutations( + node, + flat_args_kwargs, + id_to_initial_version, + ) + + return ret_val + + +_current_node = threading.local() + + +def get_current_node() -> torch.fx.Node | None: + return getattr(_current_node, "value", None) + + +@contextmanager +def set_current_node(node: torch.fx.Node) -> Generator[None, None, None]: + old = get_current_node() + _current_node.value = node + try: + yield + finally: + _current_node.value = old + + +def run_node( + tracer: Any, node: torch.fx.Node, args: Any, kwargs: Any, nnmodule: Any +) -> Any: + """ + Runs a given node, with the given args and kwargs. + + Behavior is dictated by a node's op. + + run_node is useful for extracting real values out of nodes. + See get_real_value for more info on common usage. + + Note: The tracer arg is only used for 'get_attr' ops + Note: The nnmodule arg is only used for 'call_module' ops + + Nodes that are not call_function, call_method, call_module, or get_attr will + raise an AssertionError. + """ + op = node.op + + with set_current_node(node): + + def make_error_message(e: Any) -> str: + return ( + f"Dynamo failed to run FX node with fake tensors: {op} {node.target}(*{args}, **{kwargs}): got " + + repr(e) + ) + + from .exc import Unsupported + + try: + if op == "call_function": + return node.target(*args, **kwargs) # type: ignore[operator] + elif op == "call_method": + if not hasattr(args[0], node.target): # type: ignore[arg-type] + from . import graph_break_hints + from .exc import unimplemented + + unimplemented( + gb_type="Missing attribute when running call_method node", + context="", + explanation=make_error_message("attribute not defined"), + hints=[*graph_break_hints.USER_ERROR], + ) + return getattr(args[0], node.target)(*args[1:], **kwargs) # type: ignore[arg-type] + elif op == "call_module": + if nnmodule is None: + raise AssertionError("nnmodule must not be None for call_module op") + return nnmodule(*args, **kwargs) + elif op == "get_attr": + return tracer.output_graph.get_submodule(node.target) + elif op == "placeholder": + if "example_value" not in node.meta: + raise AssertionError( + "Expected 'example_value' in node.meta for placeholder op" + ) + return node.meta["example_value"] + + except (NotImplementedError, UnsupportedFakeTensorException) as e: + # NB: mimic how wrap_fake_exception does it + from . import graph_break_hints + from .exc import unimplemented + + hints = [*graph_break_hints.USER_ERROR] + if isinstance(e, NotImplementedError): + hints += [ + "If the op is a custom op, did you implement a fake tensor implementation? " + "(e.g. with `@my_custom_op.register_fake`)", + "If the op is a PyTorch op, please file an issue to PyTorch.", + ] + + unimplemented( + gb_type="NotImplementedError/UnsupportedFakeTensorException when running FX node", + context="", + explanation=make_error_message(e), + hints=hints, + from_exc=e, + ) + except Unsupported: + raise + except IndexError: + # Re-raise IndexError from tensor dim validation (e.g. canonicalize_dim, + # maybe_wrap_dim) so it reaches the user as IndexError, not RuntimeError. + # This is intentionally broad: an internal Dynamo indexing bug would also + # propagate this way, but such bugs are rare and the traceback is preserved. + raise + except Exception as e: + raise RuntimeError(make_error_message(e)).with_traceback( + e.__traceback__ + ) from e + + raise AssertionError(op) + + +def get_real_value(node: torch.fx.Node, tracer: Any) -> Any: + """ + Run the actual computation represented by `node` and return the result. + This will execute any dependent nodes in the graph as well. + """ + from . import graph_break_hints + from .exc import unimplemented + + cache = tracer.real_value_cache + if node in cache: + return cache[node] + + op = node.op + args, kwargs = torch.fx.node.map_arg( # type: ignore[misc] + (node.args, node.kwargs), + lambda n: get_real_value(n, tracer), + ) + + if op == "placeholder" and "grapharg" in node.meta: + return node.meta["grapharg"].example + + if op == "call_module": + nn_module = tracer.output_graph.nn_modules[node.target] + if not is_lazy_module(nn_module): + nn_module = copy.deepcopy(nn_module) + else: + # In the case of a lazy module, we want to run + # the pre-hooks which initialize it + nn_module(*args, **kwargs) + else: + nn_module = None + + try: + real_value = run_node(tracer, node, args, kwargs, nn_module) + cache[node] = real_value + except RuntimeError as e: + exn = e # to make typing happy for the lambda + _wrap_graph_break_with_torch_runtime_err( + lambda: unimplemented( + gb_type="RuntimeError when trying to get real value from fx.Node", + context="", + explanation="", + hints=[*graph_break_hints.USER_ERROR], + from_exc=exn, + ) + ) + raise AssertionError("should not be reachable") from None + return real_value + + +def assert_no_fake_params_or_buffers(gm: torch.nn.Module) -> None: + from torch._subclasses.fake_tensor import FakeTensorConfig, is_fake + + def stack_or_hint(t: Any) -> str: + if FakeTensorConfig.debug: + import traceback + + return f"FAKE TENSOR CREATION TRACEBACK: \n {traceback.format_list(t._debug_trace)}" + else: + return "Enable TORCH_FAKE_TENSOR_DEBUG=1 to get creation stack traces on fake tensors." + + for name, buffer in gm.named_buffers(): + if is_fake(buffer): + raise AssertionError( + f"Unexpected fake buffer {name} {stack_or_hint(buffer)}" + ) + for name, param in gm.named_parameters(): + if is_fake(param): + raise AssertionError(f"Unexpected fake param {name} {stack_or_hint(param)}") + + +def fqn(obj: Any) -> str: + """ + Returns the fully qualified name of the object. + """ + return f"{obj.__module__}.{obj.__qualname__}" + + +def ifdynstaticdefault(count1: Any, count2: Any) -> Any: + if torch._dynamo.config.assume_static_by_default: + return count1 + else: + return count2 + + +def import_submodule(mod: types.ModuleType) -> None: + """ + Ensure all the files in a given submodule are imported + """ + for filename in sorted(os.listdir(os.path.dirname(cast(str, mod.__file__)))): + if filename.endswith(".py") and filename[0] != "_": + importlib.import_module(f"{mod.__name__}.{filename[:-3]}") + + +def object_has_getattribute(value: object) -> bool: + return class_has_getattribute(type(value)) + + +def object_setattr_ignore_descriptor(obj: Any, name: str, value: Any) -> None: + # Mirror the instance-dict update path in _PyObject_GenericSetAttrWithDict: + # https://github.com/python/cpython/blob/v3.13.0/Objects/object.c#L1679-L1741 + try: + d = object.__getattribute__(obj, "__dict__") + except AttributeError: + if not isinstance(obj, threading.local): + raise + # threading.local stores attributes in a per-thread C-backed dict that + # object.__getattribute__ cannot see. CPython passes that dict directly + # to _PyObject_GenericSetAttrWithDict: + # https://github.com/python/cpython/blob/v3.13.0/Modules/_threadmodule.c#L1707-L1730 + d = threading.local.__getattribute__(obj, "__dict__") + d[name] = value + + +def object_delattr_ignore_descriptor(obj: Any, name: str) -> None: + # Same path as object_setattr_ignore_descriptor with a NULL value. + # https://github.com/python/cpython/blob/v3.13.0/Objects/object.c#L1679-L1741 + try: + d = object.__getattribute__(obj, "__dict__") + except AttributeError: + if not isinstance(obj, threading.local): + raise + d = threading.local.__getattribute__(obj, "__dict__") + del d[name] + + +def class_has_getattribute(cls: type) -> bool: + try: + if isinstance( + inspect.getattr_static(cls, "__getattribute__"), + types.FunctionType, + ): + return True + except AttributeError: + pass + return False + + +def get_custom_getattr( + value: Any, ignore_nn_module_getattr: bool = False +) -> Any | None: + try: + getattr_fn = inspect.getattr_static(type(value), "__getattr__") + except AttributeError: + getattr_fn = None + if ignore_nn_module_getattr and getattr_fn is torch.nn.Module.__getattr__: + # ignore this case of getattr + getattr_fn = None + return getattr_fn + + +class TensorStaticReason(enum.Enum): + PARAMETER = 2 + NOT_TENSOR = 4 + NN_MODULE_PROPERTY = 5 + + +def tensor_static_reason_to_message(reason: TensorStaticReason) -> str: + if reason == TensorStaticReason.PARAMETER: + return "mark_dynamic on parameter, parameters are always static today." + if reason == TensorStaticReason.NOT_TENSOR: + return "mark_dynamic on a non tensor, how did this happen?" + if reason == TensorStaticReason.NN_MODULE_PROPERTY: + return "tensor is static because it is nn module associated." + raise AssertionError(f"Illegal reason {reason}") + + +def tensor_always_has_static_shape( + tensor: torch.Tensor | Any, + is_tensor: bool, + tensor_source: Source, +) -> tuple[bool, TensorStaticReason | None]: + """ + Given a tensor, source, and is_tensor flag, determine if a shape should be static. + + Args: + tensor - the real tensor to evaluate, parameters force a static shape. + is_tensor - internal dynamo check, essentially "is_tensor": target_cls is TensorVariable, + tensors not in a TensorVariable for whatever reason are forced static. + + Returns a tuple, where the first element is the bool of whether or not this tensor should have a static shape. + The second element is a TensorStaticReason, useful for passing to tensor_static_reason_to_message if needed. + """ + from .source import is_from_unspecialized_param_buffer_source + + if ( + tensor_source.guard_source.is_specialized_nn_module() + or tensor_source.guard_source.is_unspecialized_builtin_nn_module() + ) and config.force_nn_module_property_static_shapes: + return True, TensorStaticReason.NN_MODULE_PROPERTY + + if ( + type(tensor) is torch.nn.Parameter + or is_from_unspecialized_param_buffer_source(tensor_source) + ) and config.force_parameter_static_shapes: + return True, TensorStaticReason.PARAMETER + if not is_tensor: + return True, TensorStaticReason.NOT_TENSOR + return False, None + + +def lazy_format_graph_tabular(fn_name: str, gm: torch.fx.GraphModule) -> Any: + def inner() -> str: + try: + from tabulate import tabulate # TODO: Check that this is installed + except ImportError: + return ( + "Tabulate module missing, please install tabulate to log the graph in tabular format, logging code instead:\n" + + str(lazy_format_graph_code(fn_name, gm)) + ) + + node_specs = [ + [n.op, n.name, n.target, n.args, n.kwargs] for n in gm.graph.nodes + ] + graph_str = tabulate( + node_specs, headers=["opcode", "name", "target", "args", "kwargs"] + ) + return _format_graph_code(fn_name, gm.forward.__code__.co_filename, graph_str) + + return LazyString(inner) + + +def format_bytecode( + prefix: str, name: str, filename: str, line_no: int, code: Any +) -> str: + return f"{prefix} {name} {filename} line {line_no} \n{dis.Bytecode(code).dis()}\n" + + +forward_hook_names = [ + "_forward_pre_hooks", + "_forward_pre_hooks_with_kwargs", + "_forward_hooks_with_kwargs", + "_forward_hooks", +] +backward_hook_names = ["_backward_pre_hooks", "_backward_hooks"] +state_dict_hook_names = [ + "_state_dict_pre_hooks", + "_state_dict_hooks", + "_load_state_dict_pre_hooks", + "_load_state_dict_post_hooks", +] +all_hook_names = forward_hook_names + backward_hook_names + state_dict_hook_names + + +def nn_module_has_global_hooks() -> bool: + # This is limited to backward hooks for now because NNModuleVariable + # supports fwd hooks underneath. + return bool( + len(torch.nn.modules.module._global_backward_hooks) + or len(torch.nn.modules.module._global_backward_pre_hooks) + ) + + +def nn_module_get_all_hooks( + mod: torch.nn.Module, + check_forward_hooks: bool = False, + check_backward_hooks: bool = False, + check_state_dict_hooks: bool = False, +) -> list[Any]: + """ + Sometimes its useful to differentiate between types of hooks such as forward/backward/pre + hooks executed during module.__call__, and state_dict hooks which are executed separately. + """ + hook_dicts_to_check = [] + check_all_hooks = ( + not check_forward_hooks + and not check_backward_hooks + and not check_state_dict_hooks + ) + if check_forward_hooks or check_all_hooks: + hook_dicts_to_check.extend(forward_hook_names) + if check_backward_hooks or check_all_hooks: + hook_dicts_to_check.extend(backward_hook_names) + if check_state_dict_hooks: + hook_dicts_to_check.extend(state_dict_hook_names) + + all_hooks = [] + for hook_dict_name in hook_dicts_to_check: + hooks = getattr(mod, hook_dict_name, []) + for hook_name in hooks: + hook = hooks[hook_name] + + all_hooks.append(hook) + return all_hooks + + +def nnmodule_has_hooks( + mod: torch.nn.Module, + check_forward_hooks: bool = False, + check_backward_hooks: bool = False, + check_state_dict_hooks: bool = False, +) -> bool: + """ + Helper function to check if a module has any hooks attached to it. + """ + hooks = nn_module_get_all_hooks( + mod, + check_forward_hooks=check_forward_hooks, + check_backward_hooks=check_backward_hooks, + check_state_dict_hooks=check_state_dict_hooks, + ) + return bool(hooks) + + +def to_numpy_helper(value: Any) -> Any: + """Convert tensor and tnp.ndarray to numpy.ndarray.""" + if is_fake(value): + return value + if isinstance(value, tnp.ndarray): + return to_numpy_helper(value.tensor) + elif isinstance(value, torch.Tensor): + return value.numpy(force=True) + elif isinstance(value, (tuple, list)): + return type(value)(to_numpy_helper(obj) for obj in value) + else: + return value + + +def numpy_to_tensor(value: Any) -> Any: + """Convert tnp.ndarray to tensor, leave other types intact. If a list/tuple, loop through it to convert.""" + if np is None: + raise AssertionError("numpy must be available (np is None)") + if isinstance(value, np.ndarray): + return torch.as_tensor(value) + if isinstance(value, tnp.ndarray): + return value.tensor + elif isinstance(value, (tuple, list)): + return type(value)(numpy_to_tensor(obj) for obj in value) + else: + return value + + +class numpy_to_tensor_wrapper(Generic[_P, R]): + def __init__(self, f: Callable[_P, R]) -> None: + self.f = f + self.__name__ = "wrapped_" + self.f.__name__ + + def __repr__(self) -> str: + return f">" + + def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> Any: + out = self.f(*args, **kwargs) + return numpy_to_tensor(out) + + +def numpy_attr_wrapper(obj: Any, name: str) -> Any: + if isinstance(obj, tnp.ndarray): + out = getattr(obj, name) + return numpy_to_tensor(out) + elif isinstance(obj, torch.Tensor): + out = getattr(tnp.ndarray(obj), name) + return numpy_to_tensor(out) + + +class numpy_method_wrapper: + """Convert obj from torch.Tensor to tnp.ndarray and call method. Then convert result back to torch.Tensor.""" + + def __init__(self, method: str) -> None: + self.method = method + self.__name__ = "wrapped_" + self.method + + def __repr__(self) -> str: + return f">" + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + obj = args[0] + if isinstance(obj, torch.Tensor): + obj = tnp.ndarray(obj) + method_callable = getattr(obj, self.method) + out = method_callable(*args[1:], **kwargs) + return numpy_to_tensor(out) + + +class numpy_operator_wrapper(Generic[_P, R]): + """Implements dunder methods for tnp.ndarray via functions from the operator library""" + + def __init__(self, op: Callable[..., Any]) -> None: + self.op = op + self.__name__ = f"wrapped_{op.__name__}" + + def __repr__(self) -> str: + return f">" + + def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> Any: + if kwargs: + raise AssertionError(f"Expected no kwargs, got {kwargs}") + + # pyrefly: ignore [bad-assignment] + args = ( + tnp.ndarray(arg) if isinstance(arg, torch.Tensor) else arg for arg in args + ) + out = self.op(*args) + return numpy_to_tensor(out) + + +@functools.lru_cache(maxsize=1) +def _torch_numpy_callable_id_map() -> dict[int, tuple[Callable[..., Any], Any, str]]: + result: dict[int, tuple[Callable[..., Any], Any, str]] = {} + for np_mod, tnp_mod in NP_TO_TNP_MODULE.items(): + module = np_mod.__name__ + for name, tnp_callable in tnp_mod.__dict__.items(): + if not callable(tnp_callable): + continue + + np_callable = getattr(np_mod, name, None) + if not callable(np_callable): + continue + + result[id(tnp_callable)] = ( + tnp_callable, + np_callable, + f"{module}.{name}", + ) + return result + + +@functools.lru_cache(maxsize=1024) +def _torch_numpy_callable_cache_key_by_id( + obj_id: int, +) -> tuple[Callable[..., Any], str] | None: + tnp_callable, np_callable, cache_key = _torch_numpy_callable_id_map()[obj_id] + + module, _, name = cache_key.rpartition(".") + # Random functions depend on global RNG state, so they are not safe to + # identify only by their canonical NumPy path in an AOTAutograd cache key. + if module == "numpy.random" or module.startswith("numpy.random."): + return None + + try: + if np_callable is not getattr(importlib.import_module(module), name): + return None + except (AttributeError, ImportError): + return None + + return (tnp_callable, cache_key) + + +def _torch_numpy_callable_cache_key(obj: Callable[..., Any]) -> str | None: + obj_id = id(obj) + # Arbitrary Python callables can be short-lived, so do not cache misses by + # id; a later object may reuse the same id. + if obj_id not in _torch_numpy_callable_id_map(): + return None + + entry = _torch_numpy_callable_cache_key_by_id(obj_id) + if entry is None: + return None + + tnp_callable, cache_key = entry + if obj is not tnp_callable: + return None + + return cache_key + + +def is_safe_numpy_wrapper(obj: object) -> bool: + return numpy_wrapper_cache_key(obj) is not None + + +def numpy_wrapper_cache_key(obj: Any) -> tuple[str, str] | None: + if type(obj) is not numpy_to_tensor_wrapper: + return None + + key = _torch_numpy_callable_cache_key(obj.f) + if key is None: + return None + + return (type(obj).__qualname__, key) + + +def defake(x: Any) -> Any: + from torch._subclasses.fake_tensor import is_fake_tensor + + if not is_fake_tensor(x): + return x + size: torch._prims_common.ShapeType + stride: torch._prims_common.StrideType + if x._has_symbolic_sizes_strides: + # optimization_hint is appropriate here because defake only needs a + # plausible concrete shape to allocate a real tensor; it does not need + # to install guards. For unbacked symbols the heuristic fallback is fine. + size = [ + torch.fx.experimental.symbolic_shapes.optimization_hint(s) for s in x.size() + ] + stride = [ + torch.fx.experimental.symbolic_shapes.optimization_hint(s) + for s in x.stride() + ] + else: + size = x.size() + stride = x.stride() + y = torch.empty_strided( + size, + stride, + dtype=x.dtype, + device=x.device, + requires_grad=x.requires_grad, + ) + y.zero_() + return y + + +def _disable_side_effect_safety_checks_for_current_subtracer( + fn: Callable[_P, R], *args: _P.args, **kwargs: _P.kwargs +) -> R: + return fn(*args, **kwargs) + + +def is_utils_checkpoint(obj: object) -> bool: + # Lazy import to avoid circular dependencies + import torch.utils.checkpoint + + return obj is torch.utils.checkpoint.checkpoint + + +def is_invoke_subgraph(obj: object) -> bool: + from torch._higher_order_ops.invoke_subgraph import invoke_subgraph_placeholder + + return obj is invoke_subgraph_placeholder + + +def build_invoke_subgraph_variable(**options: Any) -> Any: + from .variables.higher_order_ops import TorchHigherOrderOperatorVariable + + return TorchHigherOrderOperatorVariable.make( + torch._higher_order_ops.invoke_subgraph, + **options, + ) + + +def build_checkpoint_variable(**options: Any) -> Any: + import torch._higher_order_ops.wrap as higher_order_ops + + from .variables.higher_order_ops import TorchHigherOrderOperatorVariable + + # TODO - This is a temporary situation where we have two versions of + # checkpointing implementation. We will converge on one and remove the other. + activation_checkpoint_op: torch._ops.HigherOrderOperator = ( + higher_order_ops.tag_activation_checkpoint + ) + if torch._functorch.config.functionalize_rng_ops: + activation_checkpoint_op = higher_order_ops.wrap_activation_checkpoint + + return TorchHigherOrderOperatorVariable.make( + activation_checkpoint_op, + **options, + ) + + +def is_compile_supported(device_type: DeviceLikeType) -> Any: + from .eval_frame import is_dynamo_supported + + type = torch.device(device_type).type + compile_supported = is_dynamo_supported() + if type == "cpu": + pass + elif type in ["cuda", "xpu", "mtia"] and compile_supported: + compile_supported = has_triton() + else: + compile_supported = False + return compile_supported + + +# The following 3.11 source code functions are adapted from +# https://github.com/python/cpython/blob/v3.11.4/Lib/traceback.py +# in order to output source code corresponding to bytecode in 3.11+. +# We need our own versions since we want to support multiline expressions. +def _fix_offset(str: str, offset: int) -> int: + """ + Convert byte offset `offset` of `str` into character offset. + Byte offset is used for 3.11+ instruction column data. + Takes things like unicode characters into consideration. + + Unchanged from CPython implementation. + """ + as_utf8 = str.encode("utf-8") + return len(as_utf8[:offset].decode("utf-8", errors="replace")) + + +@dataclasses.dataclass +class _Anchors: + # inclusive + left_end_lineno: int + left_end_offset: int + right_start_lineno: int + # exclusive + right_start_offset: int + + +def _extract_anchors_from_expr(segment: str) -> _Anchors | None: + """ + Given source code `segment` corresponding to a bytecode + instruction, determine: + - for binary ops, the location of the binary op + - for indexing, the location of the brackets. + `segment` is expected to be a valid Python expression + """ + if sys.version_info < (3, 11): + raise AssertionError(f"Python >= 3.11 required, got {sys.version_info}") + + import ast + + tree: Any | None = None + try: + # Without brackets, `segment` is parsed as a statement. + # We expect an expression, so wrap `segment` in + # brackets to handle multi-line expressions. + tree = ast.parse("(\n" + segment + "\n)") + except SyntaxError: + return None + if tree is None: + raise AssertionError("ast.parse returned None unexpectedly") + + if len(tree.body) != 1: + return None + + lines = segment.split("\n") + + # get character index given byte offset + def normalize(lineno: int, offset: int) -> int: + return _fix_offset(lines[lineno], offset) + + # Gets the next valid character index in `lines`, if + # the current location is not valid. Handles empty lines. + def next_valid_char(lineno: int, col: int) -> tuple[int, int]: + while lineno < len(lines) and col >= len(lines[lineno]): + col = 0 + lineno += 1 + if lineno >= len(lines): + raise AssertionError( + f"lineno {lineno} out of range (len(lines)={len(lines)})" + ) + if col >= len(lines[lineno]): + raise AssertionError( + f"col {col} out of range (len(lines[{lineno}])={len(lines[lineno])})" + ) + return lineno, col + + # Get the next valid character index in `lines`. + def increment(lineno: int, col: int) -> tuple[int, int]: + col += 1 + lineno, col = next_valid_char(lineno, col) + if lineno >= len(lines): + raise AssertionError( + f"lineno {lineno} out of range (len(lines)={len(lines)})" + ) + if col >= len(lines[lineno]): + raise AssertionError( + f"col {col} out of range (len(lines[{lineno}])={len(lines[lineno])})" + ) + return lineno, col + + # Get the next valid character at least on the next line + def nextline(lineno: int, col: int) -> tuple[int, int]: + col = 0 + lineno += 1 + lineno, col = next_valid_char(lineno, col) + if lineno >= len(lines): + raise AssertionError( + f"lineno {lineno} out of range (len(lines)={len(lines)})" + ) + if col >= len(lines[lineno]): + raise AssertionError( + f"col {col} out of range (len(lines[{lineno}])={len(lines[lineno])})" + ) + return lineno, col + + statement = tree.body[0] + if isinstance(statement, ast.Expr): + expr = statement.value + if isinstance(expr, ast.BinOp): + # ast gives locations for BinOp subexpressions, e.g. + # ( left_expr ) + ( right_expr ) + # left^^^^^ right^^^^^ + # -2 since end_lineno is 1-indexed and because we added an extra + # bracket to `segment` when calling ast.parse + cur_lineno = cast(int, expr.left.end_lineno) - 2 + if expr.left.end_col_offset is None: + raise AssertionError("expr.left.end_col_offset must not be None") + cur_col = normalize(cur_lineno, expr.left.end_col_offset) + cur_lineno, cur_col = next_valid_char(cur_lineno, cur_col) + + # Heuristic to find the operator character. + # The original CPython implementation did not look for ), \, or #, + # leading to incorrect anchor location, e.g. + # (x) + (y) + # ~~^~~~~~~ + while (ch := lines[cur_lineno][cur_col]).isspace() or ch in ")\\#": + if ch in "\\#": + cur_lineno, cur_col = nextline(cur_lineno, cur_col) + else: + cur_lineno, cur_col = increment(cur_lineno, cur_col) + + # binary op is 1 or 2 characters long, on the same line + right_col = cur_col + 1 + if ( + right_col < len(lines[cur_lineno]) + and not (ch := lines[cur_lineno][right_col]).isspace() + and ch not in "\\#" + ): + right_col += 1 + # right_col can be invalid since it is exclusive + + return _Anchors(cur_lineno, cur_col, cur_lineno, right_col) + elif isinstance(expr, ast.Subscript): + # ast gives locations for value and slice subexpressions, e.g. + # ( value_expr ) [ slice_expr ] + # value^^^^^ slice^^^^^ + # subscript^^^^^^^^^^^^^^^^^^^^ + # find left bracket (first '[' after value) + left_lineno = cast(int, expr.value.end_lineno) - 2 + if expr.value.end_col_offset is None: + raise AssertionError("expr.value.end_col_offset must not be None") + left_col = normalize(left_lineno, expr.value.end_col_offset) + left_lineno, left_col = next_valid_char(left_lineno, left_col) + while lines[left_lineno][left_col] != "[": + left_lineno, left_col = increment(left_lineno, left_col) + # find right bracket (final character of expression) + right_lineno = cast(int, expr.end_lineno) - 2 + if expr.end_col_offset is None: + raise AssertionError("expr.end_col_offset must not be None") + right_col = normalize(right_lineno, expr.end_col_offset) + return _Anchors(left_lineno, left_col, right_lineno, right_col) + elif isinstance(expr, ast.Call): + # ( func_expr ) (args, kwargs) + # func^^^^^ + # call^^^^^^^^^^^^^^^^^^^^^^^^ + # find left bracket (first '(' after func) + left_lineno = cast(int, expr.func.end_lineno) - 2 + if expr.func.end_col_offset is None: + raise AssertionError("expr.func.end_col_offset must not be None") + left_col = normalize(left_lineno, expr.func.end_col_offset) + left_lineno, left_col = next_valid_char(left_lineno, left_col) + while lines[left_lineno][left_col] != "(": + left_lineno, left_col = increment(left_lineno, left_col) + # find right bracket (final character of expression) + right_lineno = cast(int, expr.end_lineno) - 2 + if expr.end_col_offset is None: + raise AssertionError("expr.end_col_offset must not be None") + right_col = normalize(right_lineno, expr.end_col_offset) + return _Anchors(left_lineno, left_col, right_lineno, right_col) + + return None + + +def format_source_range( + filename: str, + lineno: int | None, + end_lineno: int | None = None, + col_offset: int | None = None, + end_col_offset: int | None = None, + *, + function_name: str = "", +) -> str: + if lineno is None: + return "" + + last_lineno = end_lineno if end_lineno is not None else lineno + source_lines = [ + linecache.getline(filename, current_lineno).rstrip() + for current_lineno in range(lineno, last_lineno + 1) + ] + if not any(source_lines): + return "" + + if ( + sys.version_info >= (3, 13) + and end_lineno is not None + and end_lineno != lineno + and col_offset is not None + and end_col_offset is not None + ): + # Keep single-line ranges on Dynamo's manual path. The stdlib traceback + # formatter is useful for multiline spans on 3.13+, but for single-line + # spans it can emit version-specific mixed `~`/`^` markers or omit the + # marker line entirely for comments. + frame_summary = traceback.FrameSummary( + filename, + lineno, + function_name, + end_lineno=end_lineno, + colno=col_offset, + end_colno=end_col_offset, + ) + result = traceback.format_list([frame_summary])[0] + result = "\n".join(result.splitlines()[1:]) + source_lines_dedent = textwrap.dedent("\n".join(source_lines)).splitlines() + if not source_lines_dedent: + return result + indent_len = len(source_lines[0]) - len(source_lines_dedent[0]) + indent = source_lines[0][:indent_len] + return textwrap.indent(textwrap.dedent(result), indent) + + first_line = source_lines[0] + if end_lineno is None or col_offset is None or end_col_offset is None: + return first_line + + start_offset = _fix_offset(first_line, col_offset) + segment = "" + markers: list[str] = [] + + if end_lineno == lineno: + end_offset = _fix_offset(first_line, end_col_offset) + segment = first_line[start_offset:end_offset] + markers.append(" " * start_offset + "~" * (end_offset - start_offset)) + else: + segment = first_line[start_offset:] + "\n" + markers.append(" " * start_offset + "~" * (len(first_line) - start_offset)) + last_line = source_lines[-1] + end_offset = _fix_offset(last_line, end_col_offset) + for line in source_lines[1:-1]: + segment += line + "\n" + num_spaces = len(line) - len(line.lstrip()) + markers.append(" " * num_spaces + "~" * (len(line) - num_spaces)) + segment += last_line[:end_offset] + num_spaces = len(last_line) - len(last_line.lstrip()) + markers.append(" " * num_spaces + "~" * (end_offset - num_spaces)) + + anchors: _Anchors | None = None + try: + anchors = _extract_anchors_from_expr(segment) + except AssertionError: + pass + + if anchors is None: + markers = [marker.replace("~", "^") for marker in markers] + else: + mutable_markers: list[list[str]] = [list(marker) for marker in markers] + + if anchors.left_end_lineno == 0: + anchors.left_end_offset += start_offset + if anchors.right_start_lineno == 0: + anchors.right_start_offset += start_offset + + for marker_lineno in range(len(markers)): + for col in range(len(mutable_markers[marker_lineno])): + if marker_lineno < anchors.left_end_lineno: + continue + if ( + marker_lineno == anchors.left_end_lineno + and col < anchors.left_end_offset + ): + continue + if ( + marker_lineno == anchors.right_start_lineno + and col >= anchors.right_start_offset + ): + continue + if marker_lineno > anchors.right_start_lineno: + continue + if mutable_markers[marker_lineno][col] == "~": + mutable_markers[marker_lineno][col] = "^" + + markers = ["".join(marker) for marker in mutable_markers] + + result = "" + for line, marker in zip(source_lines, markers): + result += line + "\n" + result += marker + "\n" + return result + + +def get_instruction_source_311(code: types.CodeType, inst: Instruction) -> str: + """ + Python 3.11+ only. Returns lines of source code (from code object `code`) + corresponding to `inst`'s location data, and underlines relevant code to `inst`. + + Example: CALL on `g`: + f(g( + ^^ + h(x))) + ^^^^^ + + We need our own implementation in < 3.13 since `format_frame_summary` in + Python's `traceback` module doesn't handle multi-line expressions + (and their anchor extraction code is not completely correct). + """ + if not hasattr(inst, "positions"): + raise AssertionError("inst must have a 'positions' attribute") + if inst.positions is None: + raise AssertionError("inst.positions must not be None") + return format_source_range( + code.co_filename, + inst.positions.lineno, + inst.positions.end_lineno, + inst.positions.col_offset, + inst.positions.end_col_offset, + function_name=code.co_name, + ) + + +# The two flavors of mark_static_address: "guarded" recompiles when the data_ptr +# changes, "unguarded" re-records cudagraphs instead. Set in decorators.py. +StaticInputType = Literal["guarded", "unguarded"] + + +def get_static_address_type(t: Any) -> StaticInputType | None: + if isinstance(t, torch.Tensor): + return getattr(t, "_dynamo_static_input_type", None) + + return None + + +def is_rng_state_getter_or_setter(value: object) -> bool: + getters = ( + # The following two functions are not identical, so don't remove anyone! + torch._C.Generator.get_state, + torch.default_generator.get_state, + torch.get_rng_state, + torch.cuda.get_rng_state, + ) + setters = ( + torch._C.Generator.set_state, + torch.default_generator.set_state, + torch.set_rng_state, + torch.cuda.set_rng_state, + ) + return value in (*setters, *getters) + + +def is_tensor_base_attr_getter(value: object) -> bool: + return ( + isinstance(value, types.MethodWrapperType) + and value.__name__ == "__get__" + and hasattr(value.__self__, "__objclass__") + and value.__self__.__objclass__ is torch._C._TensorBase # type: ignore[attr-defined] + ) + + +def is_tensor_getset_descriptor(name: str) -> bool: + try: + attr = inspect.getattr_static(torch.Tensor, name) + return type(attr) is types.GetSetDescriptorType + except AttributeError: + return False + + +def is_torch_class(cls: type) -> bool: + """Check if cls is defined in torch or a torch submodule. + + Torch-internal C-level descriptors (e.g. torch.Tensor.unsqueeze_) need + to go through VariableTracker.build / trace_rules so they get the right + VT (TorchInGraphFunctionVariable), which has guards like + inplace-view-on-input-tensor detection. This helper identifies classes + whose descriptors should take that path instead of descriptor VTs. + """ + module = getattr(cls, "__module__", None) + return module is not None and (module == "torch" or module.startswith("torch.")) + + +def is_torch_function_object(value: object) -> bool: + return hasattr(value, "__torch_function__") + + +def has_torch_function(vt: VariableTracker) -> bool: + # This emulates + # https://github.com/pytorch/pytorch/blob/8d81806211bc3c0ee6c2ef235017bacf1d775a85/torch/csrc/utils/disable_torch_function.cpp#L315-L323 + from torch._dynamo.variables import UserDefinedObjectVariable + from torch._dynamo.variables.torch_function import TensorWithTFOverrideVariable + + # Note on lazy vars: The value will either be realized or not throughout the course of execution + # if the value has a torch function, it will eventually be realized so we can realize it here + # if the value does not have a torch function, it may or may not be realized + # if it is realized it will be used and guards will be installed properly + # if it is not used, guards won't be installed, and it doesn't matter + # if the value has a torch function or not, so we should *not* realize it. + # NB: We technically know that if is_realized is False, LazyVariableTracker has the peek_value method + # but mypy does not unfortunately + if vt.is_realized() or ( + hasattr(vt, "peek_value") and hasattr(vt.peek_value(), "__torch_function__") + ): + func = None + if isinstance(vt, TensorWithTFOverrideVariable): + func = getattr(vt.class_type, "__torch_function__", None) + + elif isinstance(vt, UserDefinedObjectVariable): + func = getattr(vt.value, "__torch_function__", None) + + return func not in (None, torch._C._disabled_torch_function_impl) + + return False + + +# see note [Tensor Fakification and Symbol Caching] +def to_fake_tensor( + t: torch.Tensor, fake_mode: torch._subclasses.fake_tensor.FakeTensorMode +) -> Any: + symbolic_context = None + source = None + if tracing_context := torch._guards.TracingContext.try_get(): + if t in tracing_context.tensor_to_context: + symbolic_context = tracing_context.tensor_to_context[t] + source = symbolic_context.tensor_source + + return fake_mode.from_tensor( + t, static_shapes=False, symbolic_context=symbolic_context, source=source + ) + + +# NB: this works for both classes and instances +def is_frozen_dataclass(value: object) -> bool: + # value may be either a dataclass instance or a dataclass type; both are + # accepted by getattr_static, so the class_has_getattribute call is safe + # even though it is annotated to take a type. + return bool( + not object_has_getattribute(value) + and not class_has_getattribute(value) # type: ignore[arg-type] + and is_dataclass(value) + and hasattr(value, "__dataclass_params__") + and hasattr(value.__dataclass_params__, "frozen") + and value.__dataclass_params__.frozen + ) + + +def get_first_attr(obj: Any, *attrs: str) -> Any: + """ + Return the first available attribute or throw an exception if none is present. + """ + for attr in attrs: + if hasattr(obj, attr): + return getattr(obj, attr) + + raise AssertionError(f"{obj} does not has any of the attributes: {attrs}") + + +@contextlib.contextmanager +def maybe_enable_compiled_autograd( + should_enable: bool, fullgraph: bool = True, dynamic: bool = True +) -> Generator[Any, None, None]: + if not should_enable: + yield + else: + + def compiler_fn(gm: Any) -> Any: + def inner_compiler(gm_: Any, example_inputs_: Any) -> Any: + torch._dynamo.utils.counters["compiled_autograd"]["compiles"] += 1 + return torch._inductor.compile(gm_, example_inputs_) + + return torch.compile( + gm, backend=inner_compiler, fullgraph=fullgraph, dynamic=dynamic + ) + + with torch._dynamo.compiled_autograd._enable(compiler_fn) as ctx: + yield ctx + + +def invalid_removeable_handle() -> RemovableHandle: + # need a subclass so weakref works + class Invalid(dict): # type: ignore[type-arg] + pass + + return RemovableHandle(Invalid()) + + +# Returns a "proxy" (new object with the same class and dict) for (non-GraphModule) nn.Module's. +# Attribute changes to the original object/proxy will be reflected in the other. +# This is useful for cases where we want a keep-alive reference to a module without increasing +# its reference count. +def nn_module_proxy(mod: Any) -> Any: + if not isinstance(mod, torch.nn.Module): + return mod + if isinstance(mod, torch.fx.GraphModule): + # Dynamo-generated GM's shouldn't contain user-created GM's + return mod + proxy = mod.__class__.__new__(mod.__class__) + proxy.__dict__ = mod.__dict__ + return proxy + + +class GmWrapper(torch.nn.Module): + def __init__( + self, gm: torch.fx.GraphModule, unflatten_fn: Callable[[list[Any]], Any] + ) -> None: + super().__init__() + self.gm = gm + self.unflatten_fn = unflatten_fn + + def forward(self, *args: Any) -> Any: + # pyrefly: ignore [redefinition] + args: list[Any] = list(args) + return self.gm(*self.unflatten_fn(args)) + + +def flatten_graph_inputs( + gm: torch.fx.GraphModule, inputs: Any, compile_gm: Callable[[Any, Any], Any] +) -> Callable[..., Any]: + """ + Mutate inputs so that they are flat and wrap gm such that it + accepts those inputs. This is needed for graphs that take + bumpy inputs. + """ + inputs_idx_to_clear = [ + i + for i, node in enumerate(gm.graph.nodes) + if node.op == "placeholder" and node.meta.get("steal_arg", False) + ] + + if torch._dynamo.compiled_autograd.in_compiled_autograd_region: + # fast path, avoid pytree overhead + # compiled autograd inputs are always a list of tensors, maybe followed by symints + if inputs_idx_to_clear != [0]: + raise AssertionError( + f"Expected inputs_idx_to_clear == [0], got {inputs_idx_to_clear}" + ) + if not isinstance(inputs[0], list): + raise AssertionError( + f"Expected inputs[0] to be a list, got {type(inputs[0])}" + ) + boxed_inputs_count = len(inputs[0]) + + def flatten_fn(args: Any) -> Any: + return args[0] + list(args[1:]) + + def unflatten_fn(flat_args: Any) -> Any: + return (flat_args[:boxed_inputs_count], *flat_args[boxed_inputs_count:]) + + compiled_fn = compile_gm(GmWrapper(gm, unflatten_fn), flatten_fn(inputs)) + else: + # slow path, don't know inputs structure + flat_inputs, spec = pytree.tree_flatten(inputs) + unflatten_fn = functools.partial(pytree.tree_unflatten, treespec=spec) + compiled_fn = compile_gm(GmWrapper(gm, unflatten_fn), flat_inputs) + # note this doesn't check the spec, assuming it is the same + flatten_fn = pytree.arg_tree_leaves + + def wrapper(*args: Any) -> Any: + flat_args = flatten_fn(args) + + # flat_args is a new list, so we need to clear references from the old list + for i in inputs_idx_to_clear: + args[i].clear() + + # this call is boxed to avoid increasing refcount until we reach aot_module_simplified forward + return compiled_fn(flat_args) + + return wrapper + + +def get_locals_to_steal(maybe_gm: Any) -> list[Any]: + if not isinstance(maybe_gm, torch.fx.GraphModule) or not hasattr(maybe_gm, "meta"): + return [] + return maybe_gm.meta.get("locals_to_steal", []) + + +def set_locals_to_steal(gm: torch.fx.GraphModule, locals_to_steal: list[Any]) -> None: + gm.meta["locals_to_steal"] = locals_to_steal + + +class Lit: + def __init__(self, s: str) -> None: + self.s = s + + def __repr__(self) -> str: + return self.s + + +warn_once_cache: set[str] = set() + + +def warn_once(msg: str, stacklevel: int = 1) -> None: + # Dynamo causes all warnings.warn (in user code and in Dynamo code) to print all the time. + # https://github.com/pytorch/pytorch/issues/128427. + # warn_once is a workaround: if the msg has been warned on before, then we will not + # warn again. + # NB: it's totally ok to store a cache of all the strings: this is what warnings.warn does as well. + if msg in warn_once_cache: + return + warn_once_cache.add(msg) + warnings.warn(msg, stacklevel=stacklevel + 1) + + +def strip_color_from_string(text: str) -> str: + # This regular expression matches ANSI escape codes + ansi_escape = re.compile(r"\x1B[@-_][0-?]*[ -/]*[@-~]") + return ansi_escape.sub("", text) + + +@contextlib.contextmanager +def _disable_saved_tensors_hooks_during_tracing() -> Generator[None, None, None]: + # See NOTE: [Deferring tensor pack/unpack hooks until runtime] + try: + prior = torch._C._autograd._saved_tensors_hooks_set_tracing(True) + yield + finally: + torch._C._autograd._saved_tensors_hooks_set_tracing(prior) + + +def is_parameter_freezing() -> bool: + return torch._inductor.config.freezing and not torch.is_grad_enabled() + + +def get_torch_function_mode_stack() -> list[Any]: + return [ + get_torch_function_mode_stack_at(i) for i in range(_len_torch_function_stack()) + ] + + +def get_torch_function_mode_stack_at(ind: int) -> Any: + if ind < 0: + raise AssertionError(f"Expected ind >= 0, got {ind}") + if ind >= _len_torch_function_stack(): + raise AssertionError( + f"Expected ind < _len_torch_function_stack() ({_len_torch_function_stack()}), got {ind}" + ) + return torch._C._get_function_stack_at(ind) + + +def set_torch_function_mode_stack(stack: list[Any]) -> None: + for _ in range(_len_torch_function_stack()): + _pop_torch_function_stack() + + for mode in stack: + _push_on_torch_function_stack(mode) + + +def clear_torch_function_mode_stack() -> None: + for _ in range(_len_torch_function_stack()): + _pop_torch_function_stack() + + +def get_current_stream(device: torch.device) -> torch.Stream: + return torch.accelerator.current_stream(device) + + +# call from C dynamo in order to inspect values in pdb +def _breakpoint_for_c_dynamo(*args: Any) -> None: + breakpoint() + + +def verify_guard_fn_signature(value: Any) -> None: + fn = value.__metadata_guard__ + sig = inspect.signature(fn) + if len(sig.parameters) != 2: + from .exc import InternalTorchDynamoError + + raise InternalTorchDynamoError( + "Tensor subclass method __metadata_guard__ must take exactly two subclass metadata arguments" + ) + if fn.__self__ != value.__class__: + from .exc import InternalTorchDynamoError + + raise InternalTorchDynamoError( + "Tensor subclass method __metadata_guard__ must be a classmethod" + ) + + +def does_not_override_dict_iter_methods(user_cls: Any) -> bool: + return ( + user_cls.items in (dict.items, OrderedDict.items) + and user_cls.values in (dict.values, OrderedDict.values) + and user_cls.keys in (dict.keys, OrderedDict.keys) + and user_cls.__iter__ in (dict.__iter__, OrderedDict.__iter__) + ) + + +# Helper functions below are to prevent TorchDynamo to prevent tracing of +# __torch_function__ calls triggered on tensor properties in the pre graph +# bytecode. +@torch._disable_dynamo +def call_size(x: Any, i: int) -> int: + return x.size(i) + + +@torch._disable_dynamo +def call_stride(x: Any, i: int) -> int: + return x.stride(i) + + +@torch._disable_dynamo +def call_storage_offset(x: Any) -> int: + return x.storage_offset() + + +# Helper function to extract relevant parts of a tensor's __dict__ to store in node meta. +# To avoid ref cycles, it's important that no tensors are present here, so leave those out. +def _extract_tensor_dict(t: torch.Tensor) -> dict[str, Any]: + KEYS_TO_COPY = [ + "_dynamo_static_input_type", + "tag", + ] + + tensor_dict = { + key: copy.copy(t.__dict__[key]) for key in KEYS_TO_COPY if key in t.__dict__ + } + + return tensor_dict + + +def build_stream(args: tuple[Any], kwargs: dict[Any, Any]) -> torch.Stream: + return torch._C.Stream(*args, **kwargs) + + +def build_event(args: tuple[Any], kwargs: dict[Any, Any]) -> torch.Event: + return torch._C.Event(*args, **kwargs) + + +class FrameState(enum.Enum): + FRAME_CREATED = -3 + FRAME_SUSPENDED = -2 + FRAME_SUSPENDED_YIELD_FROM = -1 + FRAME_EXECUTING = 0 + FRAME_COMPLETED = 1 + FRAME_CLEARED = 4 + + +class PySendResult(enum.Enum): + PYGEN_RETURN = 0 + PYGEN_ERROR = -1 + PYGEN_NEXT = 1 + + +class CompileTimeInstructionCounter: + _counter: int = 0 + _id: int = -1 + _depth = 0 + + @classmethod + def start(cls) -> None: + cls._depth = cls._depth + 1 + if cls._depth == 1: + cls._id = _instruction_counter.start() + + @classmethod + def end(cls) -> None: + cls._depth = cls._depth - 1 + if cls._depth == 0: + cls._counter += _instruction_counter.end(cls._id) + cls._id = -1 + + @classmethod + def clear(cls) -> None: + cls._counter = 0 + + @classmethod + def value(cls) -> int: + return cls._counter + + @classmethod + @contextmanager + def record(cls) -> Generator[None, None, None]: + try: + if config.record_compile_time_instruction_count: + cls.start() + yield + finally: + if config.record_compile_time_instruction_count: + cls.end() + + +class CompileCounterInt(int): + def __add__(self, other: Any) -> CompileCounterInt: + return CompileCounterInt(super().__add__(other)) + + +def set_feature_use(feature: str, usage: bool) -> None: + """ + Records whether we are using a feature + Generally a feature is a JK. + """ + # Note that sometimes (tests etc...) we're not in a context which we can record into + if get_metrics_context().in_progress(): + get_metrics_context().set_key_value("feature_usage", feature, usage) + + +OptimizeDDPMode = Literal[ + "ddp_optimizer", + "python_reducer", + "python_reducer_without_compiled_forward", + "no_optimization", +] + +_ddp_optimization_mode: tuple[OptimizeDDPMode, ...] = ( + "ddp_optimizer", + "python_reducer", # experimental mode + "python_reducer_without_compiled_forward", + "no_optimization", +) + + +def get_optimize_ddp_mode() -> OptimizeDDPMode: + optimize_ddp = config.optimize_ddp + if isinstance(optimize_ddp, bool): + mode = "ddp_optimizer" if optimize_ddp else "no_optimization" + elif isinstance(optimize_ddp, str): + mode = optimize_ddp + else: + raise ValueError( + f"Invalid dynamo config optimize_ddp type {type(optimize_ddp)=}" + ) + + if mode not in _ddp_optimization_mode: + raise AssertionError(f"Invalid dynamo config optimize_ddp value {mode=}") + return cast("OptimizeDDPMode", mode) + + +@contextmanager +def maybe_disable_inference_mode() -> Generator[None, None, None]: + """ + Disables torch.inference_mode for the compilation (still on at runtime). + This simplifies the compile stack where we can assume that inference_mode + will always be off. + + Since inference_mode is equivalent to no_grad + some optimizations (version + counts etc), we turn on no_grad here. The other optimizations are not + relevant to torch.compile. + """ + is_inference_mode_on = ( + config.fake_tensor_disable_inference_mode and torch.is_inference_mode_enabled() + ) + if is_inference_mode_on: + with ( + torch.inference_mode(False), + torch.no_grad(), + ): + yield + else: + yield + + +@contextmanager +def maybe_disable_inference_mode_for_fake_prop() -> Generator[None, None, None]: + """ + Turns off tracking of inference_mode for fake tensor propagation. With this + context manager, when a real tensor is converted to fake tensor, the fake + tensor looses its inference-ness. + """ + if config.fake_tensor_disable_inference_mode: + with torch._subclasses.meta_utils.disable_inference_mode_for_fake_prop(): + yield + else: + yield + + +def is_node_meta_valid(node: torch.fx.Node | None) -> bool: + return node is None or "example_value" in node.meta or "val" in node.meta + + +# If True, enforce fullgraph=True - raise errors on graph break +_error_on_graph_break = False + + +def _get_error_on_graph_break() -> bool: + return _error_on_graph_break + + +def _set_error_on_graph_break(value: bool) -> None: + global _error_on_graph_break + _error_on_graph_break = value + + +@functools.lru_cache(1) +def _is_tensorify_enabled() -> bool: + if (env := os.getenv("TENSORIFY_PYTHON_SCALARS")) is not None: + return env not in ("0", "FALSE") + return justknobs_check("pytorch/compiler:tensorify_python_scalars") + + +@torch._disable_dynamo +def record_pregraph_bytecode_enter() -> AbstractContextManager[None]: + cm: AbstractContextManager[None] = ( + torch._C._profiler._RecordFunctionFast("Pregraph bytecode") + if torch.autograd.profiler._is_profiler_enabled + else contextlib.nullcontext() + ) + cm.__enter__() + return cm + + +@torch._disable_dynamo +def record_pregraph_bytecode_exit(cm: AbstractContextManager[None]) -> None: + cm.__exit__(None, None, None) + + +# Active `torch._dynamo.override_cudagraphs` override, set/restored at RUNTIME by +# CudagraphOverrideContextManager.__enter__/__exit__ (mirrors _error_on_graph_break +# above). This lets the override follow the dynamic call stack: a callee that +# cannot be inlined (e.g. it contains a graph break) is compiled as a separate +# frame and would otherwise not inherit the override, which lives lexically in a +# caller's `with` block / decorator. OutputGraph seeds its cudagraph_annotation +# from this value. None means no override is active; otherwise it is the +# (fwd, bwd) pair. NOTE: we intentionally do not guard on this, so the override +# is sticky per code object (first compile wins) for functions reached both +# inside and outside it. +_cudagraph_override: tuple[bool | None, bool | None] | None = None + + +def _get_cudagraph_override() -> tuple[bool | None, bool | None] | None: + return _cudagraph_override + + +def _set_cudagraph_override(value: tuple[bool | None, bool | None] | None) -> None: + global _cudagraph_override + _cudagraph_override = value + + +# Returns a set of code objects present traced in the current TracingContext, or None +# if there is no current TracingContext. +def get_traced_code() -> list[CodeType] | None: + from torch._guards import TracingContext + + return TracingContext.get_traced_code() + + +def is_pybind11_enum_member(value: object) -> bool: + """Check if value is a pybind11 enum member (with stable hash and eq). + + Pybind11 enums have __members__ on their type. Unlike Python's enum.Enum, + pybind11 injects __hash__ and __eq__ directly into the type's __dict__, + which trips raise_on_overridden_hash. But these are safe: members have + deterministic hash and equality, same as Python enums. + + Note: pybind11 doesn't always return the singleton for enum values (e.g. + a C++ function returning an enum may construct a new Python wrapper), so + we check by name membership rather than identity. + """ + t = type(value) + members = getattr(t, "__members__", None) + if members is None: + return False + name = getattr(value, "name", None) + return name is not None and name in members + + +def _make_inlined( + tx: InstructionTranslatorBase, f: Callable[..., Any] +) -> Callable[..., VariableTracker]: + if not callable(f): + raise AssertionError("Expect f to be a python callable.") + + def inline_call( + *args: VariableTracker, **kwargs: VariableTracker + ) -> VariableTracker: + from torch._dynamo.trace_rules import _force_inline + from torch._dynamo.variables.functions import UserFunctionVariable + + with _force_inline(): + return tx.inline_user_function_return( + UserFunctionVariable(f), + list(args), + dict(kwargs), + ) + + return inline_call diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__init__.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cb9365c44e2a74ca41c2b3cea210fae40fe769e7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__init__.py @@ -0,0 +1,305 @@ +""" +This package implements variable tracking and symbolic execution capabilities for Dynamo, +which are essential for converting Python code into FX graphs. It provides a comprehensive +set of variable types that handle different Python constructs during tracing. + +Each variable type (like BuiltinVariable, TensorVariable, NNModuleVariable, etc.) is responsible +for tracking and symbolically executing operations on specific Python objects. This enables +Dynamo to: +- Track the flow of values through Python code +- Maintain correct semantics during graph conversion +- Handle complex Python features like context managers, iterators, and custom objects +- Support both eager and symbolic execution modes + +The VariableTracker base class provides the foundation for all variable types, with each +subclass implementing specific behavior for different Python constructs. This modular design +allows Dynamo to accurately trace and optimize Python code while preserving its semantics. +""" + +from .base import VariableTracker +from .builtin import ( + BaseBuiltinVariable, + BuiltinVariable, + DictBuiltinVariable, + GetAttrBuiltinVariable, + HasAttrBuiltinVariable, + IterBuiltinVariable, + ListBuiltinVariable, + SetAttrBuiltinVariable, +) +from .constant import ConstantVariable +from .ctx_manager import ( + AcceleratorDeviceIndexVariable, + CatchWarningsCtxManagerVariable, + ContextWrappingVariable, + CUDADeviceVariable, + CudagraphOverrideVariable, + DisabledSavedTensorsHooksVariable, + DualLevelContextManager, + DynamoConfigPatchVariable, + ErrorOnGraphBreakVariable, + FSDPParamGroupUseTrainingStateVariable, + FxTracebackAnnotateVariable, + GenericContextWrappingVariable, + get_device_context_manager, + GradIncrementNestingCtxManagerVariable, + GradInplaceRequiresGradCtxManagerVariable, + GradModeVariable, + InferenceModeVariable, + JvpIncrementNestingCtxManagerVariable, + register_device_context_manager, + SDPAKernelVariable, + SetFwdGradEnabledContextManager, + TemporarilyPopInterpreterStackCtxManagerVariable, + VmapIncrementNestingCtxManagerVariable, + WithEnterFunctionVariable, + WithExitFunctionVariable, + XPUDeviceVariable, +) +from .dicts import ( + ConstDictVariable, + DictItemsVariable, + DictViewVariable, + DunderDictVariable, + MappingProxyVariable, + NNModuleHooksDictVariable, + OrderedDictVariable, +) +from .distributed import BackwardHookVariable, DistributedVariable +from .functions import ( + BaseUserFunctionVariable, + BoundBuiltinMethodVariable, + ClassMethodDescriptorVariable, + ClassMethodVariable, + CollectionsNamedTupleFunction, + CreateTMADescriptorExperimentalVariable, + CreateTMADescriptorStableVariable, + FunctionDecoratedByContextlibContextManagerVariable, + FunctoolsPartialVariable, + GetSetDescriptorVariable, + InspectSignatureVariable, + LocalGeneratorFunctionVariable, + LocalGeneratorObjectVariable, + MemberDescriptorVariable, + MethodDescriptorVariable, + MethodWrapperVariable, + NestedUserFunctionVariable, + PolyfilledFunctionVariable, + PropertyVariable, + PyTreeGetNodeTypeFunctionVariable, + PyTreeTreeIsLeafFunctionVariable, + SkipFunctionVariable, + SparseTensorCreationSkipVariable, + StaticMethodVariable, + TMADescriptorExperimentalVariable, + TMADescriptorStableVariable, + TritonSetAllocatorVariable, + TupleGetterVariable, + UserFunctionVariable, + UserMethodVariable, + WrapperDescriptorVariable, + WrapperUserFunctionVariable, + WrapperUserMethodVariable, +) +from .higher_order_ops import ( + FunctionalCallVariable, + FunctorchHigherOrderVariable, + ReparametrizeModuleCallVariable, + TorchHigherOrderOperatorVariable, +) +from .iter import ( + ChainVariable, + CountIteratorVariable, + FilterVariable, + IteratorVariable, + ItertoolsVariable, + MapVariable, + RepeatIteratorVariable, + ZipLongestVariable, + ZipVariable, +) +from .lazy import LazyConstantVariable, LazyVariableTracker +from .lists import ( + BaseListVariable, + DequeVariable, + ListIteratorVariable, + ListVariable, + RangeVariable, + SliceVariable, + TupleIteratorVariable, + TupleVariable, +) +from .memory import CUDAMemPoolContextVariable, CUDAMemPoolVariable +from .misc import ( + AttributeErrorVariable, + AutogradFunctionContextVariable, + AutogradFunctionVariable, + CallMethodVariable, + CellVariable, + ContextVarVariable, + DeletedVariable, + ExceptionVariable, + GetAttrVariable, + LambdaVariable, + NameErrorVariable, + NewGlobalVariable, + NumpyVariable, + ObjectVariable, + PythonModuleVariable, + RandomClassVariable, + RandomVariable, + StopIterationVariable, + StringFormatVariable, + SuperVariable, + TracebackVariable, + TypingVariable, + UnknownVariable, + WeakRefVariable, +) +from .nn_module import ( + FSDPManagedNNModuleVariable, + NNModuleVariable, + UnspecializedBuiltinNNModuleVariable, + UnspecializedNNModuleVariable, +) +from .optimizer import OptimizerVariable +from .sdpa import SDPAParamsVariable +from .sets import ( + DictKeySetVariable, + FrozensetVariable, + OrderedSetClassVariable, + OrderedSetVariable, + SetVariable, +) +from .streams import ( + CudaStreamVariable, + EventVariable, + StreamContextVariable, + StreamVariable, +) +from .tensor import ( + DataPtrVariable, + FakeItemVariable, + NumpyNdarrayVariable, + SymNodeVariable, + TensorVariable, + UnspecializedPythonVariable, + UntypedStorageVariable, +) +from .torch import TorchCtxManagerClassVariable, TorchInGraphFunctionVariable +from .user_defined import ( + DefaultDictVariable, + FrozenDataClassVariable, + InspectVariable, + MutableMappingVariable, + NamedTupleVariable, + RemovableHandleVariable, + StructSequenceVariable, + UserDefinedClassVariable, + UserDefinedConstantVariable, + UserDefinedDequeVariable, + UserDefinedDictVariable, + UserDefinedExceptionClassVariable, + UserDefinedExceptionObjectVariable, + UserDefinedListVariable, + UserDefinedObjectVariable, + UserDefinedSetVariable, + UserDefinedTupleVariable, + UserDefinedVariable, +) + + +__all__ = [ + "AcceleratorDeviceIndexVariable", + "AttributeErrorVariable", + "AutogradFunctionContextVariable", + "AutogradFunctionVariable", + "BackwardHookVariable", + "BaseBuiltinVariable", + "BaseListVariable", + "CallMethodVariable", + "BuiltinVariable", + "CatchWarningsCtxManagerVariable", + "CellVariable", + "ConstantVariable", + "ConstDictVariable", + "ContextVarVariable", + "ContextWrappingVariable", + "ChainVariable", + "CountIteratorVariable", + "CreateTMADescriptorExperimentalVariable", + "CreateTMADescriptorStableVariable", + "CUDADeviceVariable", + "CUDAMemPoolContextVariable", + "CUDAMemPoolVariable", + "CudagraphOverrideVariable", + "DataPtrVariable", + "DefaultDictVariable", + "DeletedVariable", + "DictBuiltinVariable", + "DictKeySetVariable", + "DynamoConfigPatchVariable", + "ErrorOnGraphBreakVariable", + "FakeItemVariable", + "get_device_context_manager", + "GetAttrBuiltinVariable", + "GetAttrVariable", + "GradModeVariable", + "HasAttrBuiltinVariable", + "InspectSignatureVariable", + "InspectVariable", + "IterBuiltinVariable", + "IteratorVariable", + "ItertoolsVariable", + "LambdaVariable", + "LazyConstantVariable", + "LazyVariableTracker", + "ListBuiltinVariable", + "ListIteratorVariable", + "ListVariable", + "MappingProxyVariable", + "NameErrorVariable", + "NamedTupleVariable", + "NestedUserFunctionVariable", + "NewGlobalVariable", + "NNModuleVariable", + "NumpyNdarrayVariable", + "NumpyVariable", + "OptimizerVariable", + "OrderedDictVariable", + "PolyfilledFunctionVariable", + "PythonModuleVariable", + "RangeVariable", + "register_device_context_manager", + "RemovableHandleVariable", + "RepeatIteratorVariable", + "SDPAParamsVariable", + "SetAttrBuiltinVariable", + "SkipFunctionVariable", + "SliceVariable", + "StopIterationVariable", + "StringFormatVariable", + "StructSequenceVariable", + "SuperVariable", + "TemporarilyPopInterpreterStackCtxManagerVariable", + "TensorVariable", + "TMADescriptorExperimentalVariable", + "TMADescriptorStableVariable", + "TorchCtxManagerClassVariable", + "TorchInGraphFunctionVariable", + "TupleVariable", + "UnknownVariable", + "UnspecializedNNModuleVariable", + "UnspecializedPythonVariable", + "UntypedStorageVariable", + "UserDefinedClassVariable", + "UserDefinedObjectVariable", + "UserDefinedTupleVariable", + "UserFunctionVariable", + "UserMethodVariable", + "VariableTracker", + "WithEnterFunctionVariable", + "WithExitFunctionVariable", + "XPUDeviceVariable", + "ZipLongestVariable", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..805e01b236bccd7bc7fd626e8a5b0a9d883233ce Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/base.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36ee2e7ecdaec92ffbd8500f76649e6c27145054 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/base.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:70f9efb0286944e7520b5ae573532a35dd34664240c6074edd2d740bd6330cda +size 123472 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/builder.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/builder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02a94e84ebb2d4e9ba4d0ed1ccb2ba76e1cf601f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/builder.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0326ded5876d765eebda6e94bb8501e1cd036acc1f6fc71ebe8f1ee63e1de598 +size 219618 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/builtin.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/builtin.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35a9fdd44dd3a3f31d55e60a4684d19f6ee838b8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/builtin.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:95d11903461bf5ba134a73ad2a9f3dd45b56c537b853ef1d6709a10668b09586 +size 160274 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/constant.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/constant.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5db20e6cbb48687bf4c24e5b1c20caa83f2d81b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/constant.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/ctx_manager.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/ctx_manager.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb8f0fd7171ca53071b60af08aa1c17a02984c52 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/ctx_manager.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/dicts.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/dicts.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffc6650c9923921e73fbe53f1414f3cac2ce1447 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/dicts.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/distributed.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/distributed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f08de1583765311df20a7fc1ca31a45beb3a88bb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/distributed.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/functions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/functions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fe92828d206a85d0e46b541454ce534968b7894 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/functions.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b8b9daa526baf5ef1d229b4c140afcdde38ce352a01ceebaa3fe5d63c3eee89b +size 223177 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/hashable.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/hashable.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85259819a2a2a333a26fdc8db9591a64066612b3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/hashable.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/higher_order_ops.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/higher_order_ops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd4c1e56944078c88d49d38751322ed5973fd53d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/higher_order_ops.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:64c5ec296c4e69b8c6c81b0c1051d4593318fed2c8af43d213a21000fc73521f +size 215312 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/invoke_subgraph.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/invoke_subgraph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14a6bc23b8061c6db81e19099986b421e8f1c804 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/invoke_subgraph.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/iter.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/iter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbaf548ab00576c19a61ce5fb9d1c6fd9688cc02 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/iter.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/lazy.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/lazy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a4dc7ce932600a68e193fba2ed5ce329628b08b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/lazy.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/lists.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/lists.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55f8154b35f50d145035ad363e44b3b340d42b0f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/lists.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b745bf291763be6631163828375b980a648ae03a7a57192e5ab2d595392bf0f5 +size 110362 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/memory.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/memory.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eedb2535bdee181d6ee1b5d0a041305440c2cb3e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/memory.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/misc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/misc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7fbb9025015ad4d7f5329683b92061866f92198 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/misc.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:538278a9fd7610aaf26c1566fc28bf6a94a12a96816324edc61dd08cc770b62b +size 140960 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/nn_module.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/nn_module.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0910ee409d1f42b1d855d0d82c812dd802f701b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/nn_module.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/object_protocol.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/object_protocol.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4edf8c98df0551b86ff2021cc3db6916f0af9a0a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/object_protocol.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/optimizer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/optimizer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddf7903d0a73365a7b3911b200b182117bec2e8b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/optimizer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/script_object.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/script_object.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62644a7bac28ba56fca15a09c83d62e8155593e8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/script_object.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/sdpa.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/sdpa.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b16b86160e19364fcc02e9cdb4c8bcd3c8a8c706 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/sdpa.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/sets.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/sets.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f56c7792d92c31f91cb2cbba1b1d3216d9568db9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/sets.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/streams.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/streams.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a4ebf3b14c22b86f3834eacef78553d0307e8fc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/streams.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/tensor.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/tensor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16ad179cf18b2ecec4c122036e3d65c41585da32 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/tensor.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4cf7763405a27012040523cf3d360910fdd90866ce956a02ff9bfc6832e251e7 +size 146945 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/torch.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/torch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..325bcfce37b82a80b112858e373cf3c0ee02c48e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/torch.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cbdaf197c9a83af9ffefccc8326de530520b6a2aaca71f09bb2f8a8965b8871c +size 196999 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/torch_function.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/torch_function.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..259075a6f41eccd97bdca2aaefa47df1fd8f4ea4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/torch_function.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/user_defined.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/user_defined.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1537071f481b45926ab1b1c2b7f3abaddd052c30 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/__pycache__/user_defined.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1d3fbc383f26fd1150552ce68b5cbe1a117dde4f09982ee3b5bdfe2e871de404 +size 221496 diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/base.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/base.py new file mode 100644 index 0000000000000000000000000000000000000000..485e7966610c80dc25f2928607807872e4200173 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/base.py @@ -0,0 +1,3330 @@ +""" +Core variable tracking functionality for Dynamo. This module defines the fundamental +classes and systems used to track and manage variables during Dynamo's operation. + +The module provides: +1. VariableTracker - The base class for tracking variables during compilation +2. MutationType system - Classes for tracking and managing mutations to variables +3. Source type management - Utilities for tracking variable origins and scope +4. Variable state management - Tools for managing variable state and transformations + +These components form the foundation of Dynamo's variable handling system, +enabling accurate tracking and transformation of Python code into optimized +computations. +""" + +from __future__ import annotations + +import collections +import dataclasses +import functools +import inspect +import logging +import textwrap +from collections.abc import Callable, ItemsView, KeysView, ValuesView +from contextvars import ContextVar +from enum import Enum, IntFlag +from typing import Any, NamedTuple, NoReturn, TYPE_CHECKING, TypeAlias + +from torch._C._dynamo import ( + get_type_slots, + has_slot, + PyMappingSlots, + PyNumberSlots, + PySequenceSlots, + PyTypeSlots, +) + +from .. import graph_break_hints, variables +from ..current_scope_id import current_scope_id +from ..exc import ( + ObservedAttributeError, + raise_observed_exception, + raise_type_error, + unimplemented, + Unsupported, +) +from ..guards import GuardBuilder, install_guard +from ..source import AttrSource, Source +from ..utils import format_source_range, istype + + +_RICHCOMPARE_OPS = frozenset( + {"__eq__", "__ne__", "__lt__", "__le__", "__gt__", "__ge__"} +) + + +if TYPE_CHECKING: + from torch._guards import Guard + from torch.fx.proxy import Node + + from ..codegen import PyCodegen + from ..side_effects import SideEffects + from ..symbolic_convert import InstructionTranslatorBase + from .constant import ConstantVariable + from .functions import UserFunctionVariable + + +log = logging.getLogger(__name__) + + +@dataclasses.dataclass(frozen=True) +class SourceLocation: + """Source position of the bytecode instruction that generated a VariableTracker.""" + + filename: str + lineno: int + end_lineno: int | None = None + col_offset: int | None = None + end_col_offset: int | None = None + + def format(self) -> str: + result = f' File "{self.filename}", line {self.lineno}\n' + source = format_source_range( + self.filename, + self.lineno, + self.end_lineno, + self.col_offset, + self.end_col_offset, + ) + if source: + result += textwrap.indent(source.rstrip("\n"), " ") + "\n" + return result + + +# Tracks active method calls on VariableTracker instances to detect self-referential +# calls (e.g., as_python_constant on a list that contains itself). Maps +# (id(instance), id(original_method)) tuples to track which calls are in progress. +# We use id(original_method) rather than the method name string so that super() +# delegation within a class hierarchy (e.g. CustomClassObjectVariable.as_python_constant +# calling UserDefinedObjectVariable.as_python_constant) is not a false positive. +_vt_active_calls: ContextVar[set[tuple[int, int]] | None] = ContextVar( + "_vt_active_calls", default=None +) + + +class SourceType(Enum): + """ + This Enum divides VariableTracker into 2 cases, depending on the variable + it represents: + - already existed that Dynamo began tracking while introspection (Existing) + - is a new variable that is created during Dynamo introspection (New) + + In general, we have these invariants: + 1. for `VariableTracker` associated with `Existing`, its `source` field must not be None. + 2. for `VariableTracker` associated with `New`, most of the time its + `source` field is None, except for cases like side effect codegen for + `AttributeMutationNew`, during which we generate a + `LocalSource('tmp...')` for such variable, to facilitate codegen. + """ + + Existing = 0 + New = 1 + + +class MutationType: + """ + Base class for Variable.mutation_type. It encodes information about + 1. The type of mutation Dynamo allows on the variable. + 2. Whether the value represented by this variable already existed before + Dynamo tracing. + """ + + def __init__(self, typ: SourceType) -> None: + # In HigherOrderOperator tracing, we need to distinguish + # between MutationTypes inside the HigherOrderOperator and + # ones outside it. For example, it is not safe to mutate + # `a` in the following example because it was constructed + # in a different scope. + # + # def f(x): + # a = 1 + # def g(x): + # nonlocal a + # a = 2 + # return x + # return wrap(g, x) + a + # + # We use self.scope to distinguish this. + # scope == 0: The object was an existing variable + # scope == 1: The object was created while Dynamo + # was introspecting a function + # (and no HigherOrderOps were involved) + # scope >= 2: The object was created through + # Dynamo introspection of a HigherOrderOp. + # The exact number corresponds to the level + # of nested HigherOrderOps. + if typ is SourceType.Existing: + self.scope = 0 + elif typ is SourceType.New: + self.scope = current_scope_id() + else: + unimplemented( + gb_type="Unsupported SourceType", + context=f"MutationType.__init__ {self} {typ}", + explanation=f"Dynamo does not support the type `{typ}`", + hints=[ + "This branch is not supposed to be reachable.", + *graph_break_hints.DYNAMO_BUG, + ], + ) + + +class AttrMutationKind(Enum): + # Replay through STORE_ATTR/DELETE_ATTR, preserving descriptor-aware + # setattr/delattr semantics. Used for slots, getset descriptors, and other + # ordinary attribute writes that should not bypass descriptors. + GENERIC_SETATTR = 0 + # Replay a direct object.__dict__ mutation while bypassing descriptors. + INSTANCE_DICT = 1 + + +class ValueMutationNew(MutationType): + """ + This case of VariableTracker.mutation_type marker indicates + 1. Dynamo allows mutation on the value itself (rather than its attributes). + 2. The value is created by the bytecode Dynamo is tracing through. + + For instance, Dynamo could model a newly created list with this marker, + indicating that while we need to model mutations to this list, we don't have + to emit bytecode for these mutations if the list doesn't escape into the + Python world. + """ + + def __init__(self) -> None: + super().__init__(SourceType.New) + + def __hash__(self) -> int: + return id(self) + + def __eq__(self, other: object) -> bool: + return self is other + + +class ValueMutationExisting(MutationType): + """ + This case of VariableTracker.mutation_type marker indicates + 1. Dynamo allows mutation on the value itself (rather than its attributes). + 2. The value exists before Dynamo tracing started. + + For instance, Dynamo could model a pre-existing list with this marker, + indicating that if we encounter mutations to this list, we need to buffer + and re-apply those mutations after the graph runs, since the list might be + used afterwards in Python. + """ + + # A flag to indicate whether mutation happened on the associated + # `VariableTracker`. This enables SideEffects to accurately and quickly + # filter out which pre-existing values it needs to generate mutation for. + is_modified: bool + + def __init__(self, is_modified: bool = False) -> None: + super().__init__(SourceType.Existing) + self.is_modified = is_modified + + +class AttributeMutation(MutationType): + """ + This case of VariableTracker.mutation_type marker indicates that Dynamo + allows mutation on the value's attributes. + """ + + +class AttributeMutationExisting(AttributeMutation): + """ + This case of VariableTracker.mutation_type marker indicates + 1. Dynamo allows mutation on the value's attributes. + 2. The value exists before Dynamo tracing started. + + For instance, Dynamo could model a pre-existing object with this marker, + indicating that if we encounter mutations to this object, we need to buffer + then re-apply those mutations after the graph runs, since the object might + be used afterwards in Python. + """ + + def __init__(self) -> None: + super().__init__(SourceType.Existing) + + +class AttributeMutationNew(AttributeMutation): + """ + This case of VariableTracker.mutation_type marker indicates + 1. Dynamo allows mutation on the value's attributes. + 2. The value is created by the bytecode Dynamo is tracing through. + + For instance, Dynamo could model a newly created object with this marker, + indicating that while we need to model mutations to this object, we don't + have to emit bytecode for these mutations if the object doesn't escape into + the Python world. + """ + + def __init__(self, cls_source: Source | None = None) -> None: + super().__init__(SourceType.New) + self.cls_source = cls_source + + +def _is_top_level_scope(scope_id: int) -> bool: + return scope_id == 1 + + +def is_side_effect_safe(m: MutationType) -> bool: + scope_id = current_scope_id() + + # In the top-level scope (if no HigherOrderOperators are involved), + # we are allowed to modify variables created in this scope as well + # as existing variables. + if _is_top_level_scope(scope_id): + return True + # Otherwise, only allow local mutation of variables created in the current scope + return m.scope == scope_id + + +def maybe_get_python_type(obj: VariableTracker) -> type: + try: + return obj.python_type() + except NotImplementedError: + unimplemented( + gb_type="Unsupported python_type() call", + context=f"{obj} does not implement python_type()", + explanation="This VariableTracker does not implement python_type(), " + "which is required for object protocol operations.", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + +class NO_SUCH_SUBOBJ: + """Sentinel indicating no concrete Python object is available.""" + + +class MethodFlags(IntFlag): + """Calling convention for a `Method` handler, mirroring CPython's + PyMethodDef ml_flags. `call_method` enforces arity from these before + invoking the handler, centralizing the raise_args_mismatch boilerplate.""" + + VARARGS = 1 # any positional args; kwargs rejected unless KEYWORDS is set + KEYWORDS = 2 # kwargs allowed (combine with VARARGS) + NOARGS = 4 # exactly zero args and zero kwargs + O = 8 # exactly one positional arg, no kwargs + + +def _check_method_arity( + vt: VariableTracker, + tx: InstructionTranslatorBase, + name: str, + flags: MethodFlags, + args: Any, + kwargs: Any, +) -> None: + # Centralized arity check for a tp_methods handler, driven by MethodFlags, + # raising the same TypeErrors CPython raises for builtin methods. Shared by + # Method and callers that run the handler directly (e.g. tensor.py). + n = len(args) + qualname = f"{vt.python_type_name()}.{name}" + if kwargs and not (flags & MethodFlags.KEYWORDS): + raise_type_error(tx, f"{qualname}() takes no keyword arguments") + if flags & (MethodFlags.NOARGS | MethodFlags.O): + if flags & MethodFlags.NOARGS and args: + raise_type_error(tx, f"{qualname}() takes no arguments ({n} given)") + if flags & MethodFlags.O and n != 1: + raise_type_error(tx, f"{qualname}() takes exactly one argument ({n} given)") + + +# CPython PyMethodDef.ml_flags bits (Include/methodobject.h); MethodFlags above +# deliberately mirrors the low four so the mapping is near-identity. +_METH_VARARGS, _METH_KEYWORDS, _METH_NOARGS, _METH_O, _METH_FASTCALL = 1, 2, 4, 8, 0x80 + + +@functools.cache +def _flags_from_ml_flags(python_type: type, name: str) -> MethodFlags: + """Arity convention for `python_type.name`, read from its CPython + PyMethodDef.ml_flags. Falls back to VARARGS|KEYWORDS when python_type has no + such attribute or it carries no ml_flags (slot wrappers, pure-Python + functions).""" + import torch + + default = MethodFlags.VARARGS | MethodFlags.KEYWORDS + fn = getattr(python_type, name, None) + ml = None if fn is None else torch._C._dynamo.eval_frame.get_method_ml_flags(fn) + if ml is None: + return default + flags = MethodFlags(0) + if ml & _METH_NOARGS: + flags |= MethodFlags.NOARGS + if ml & _METH_O: + flags |= MethodFlags.O + if ml & (_METH_VARARGS | _METH_FASTCALL): + flags |= MethodFlags.VARARGS + if ml & _METH_KEYWORDS: + flags |= MethodFlags.KEYWORDS + return flags or default + + +def _derive_method_flags(vt: VariableTracker, name: str) -> MethodFlags: + """Resolve the arity flags for method `name` from the VT's arity-reference + type (see VariableTracker.method_flags_type).""" + return _flags_from_ml_flags(vt.method_flags_type(), name) + + +@dataclasses.dataclass(slots=True) +class Method: + """Declarative entry in a VariableTracker's `tp_methods` table, analogous + to CPython's PyMethodDef. + + Handlers have signature `(self, tx, args, kwargs)` and return the result + VariableTracker, or None to decline the call (the equivalent of the old + `super().call_method` fall-through) so `call_method` continues to the + object-protocol dispatch below. The method name is the tp_methods key this + entry is stored under; its arity convention is derived + on demand from that method's ml_flags (see _derive_method_flags).""" + + handler: Callable[..., VariableTracker | None] + + def __call__( + self, + vt: VariableTracker, + tx: InstructionTranslatorBase, + name: str, + args: Any, + kwargs: Any, + ) -> VariableTracker | None: + flags = _derive_method_flags(vt, name) + _check_method_arity(vt, tx, name, flags, args, kwargs) + return self.handler(vt, tx, args, kwargs) + + +@dataclasses.dataclass(slots=True) +class GetSet: + """`tp_getset` entry, analogous to CPython's PyGetSetDef. `getter` + `(self, tx) -> VT | None` (None declines); `setter` + `(self, tx, value) -> VT | None`, None for read-only.""" + + getter: Callable[..., VariableTracker | None] + setter: Callable[..., VariableTracker | None] | None = None + + +@dataclasses.dataclass(slots=True) +class Member: + """`tp_members` entry, analogous to CPython's PyMemberDef. Same shape as + GetSet; a distinct type so members and getsets never share a class.""" + + getter: Callable[..., VariableTracker | None] + setter: Callable[..., VariableTracker | None] | None = None + + +def getset_read( + accessor: Callable[[Any], VariableTracker], +) -> Callable[..., VariableTracker]: + """Getter for a GetSet/Member whose value is an already-built VT.""" + return lambda self, tx: accessor(self) + + +def getset_build( + accessor: Callable[[Any], Any], +) -> Callable[..., VariableTracker]: + """Getter that builds a VT from the raw value returned by `accessor`.""" + return lambda self, tx: VariableTracker.build(tx, accessor(self)) + + +def unsupported_attr(name: str) -> Callable[..., VariableTracker | None]: + def graph_break( + vt: VariableTracker, tx: InstructionTranslatorBase + ) -> VariableTracker | None: + unimplemented( + gb_type="Unsupported attribute", + context=f"attr_unsupported {vt} {name}", + explanation=f"{type(vt).__name__} does not support attribute '{name}'", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + + return graph_break + + +# This helps users of `as_python_constant` to catch unimplemented error with +# more information; it inherits `NotImplementedError` for backward +# compatibility reasons. +class AsPythonConstantNotImplementedError(NotImplementedError): + vt: VariableTracker + + def __init__(self, vt: VariableTracker, msg: str | None = None) -> None: + msg = f"{vt} is not a constant" if msg is None else msg + super().__init__(msg) + self.vt = vt + + +# --------------------------------------------------------------------------- +# SLOTDEFS: Dynamo's analog of CPython's static slotdefs[] table +# (Objects/typeobject.c). One global table, shared by every type, mapping a +# dunder name to the VariableTracker method that implements it (``impl``, the +# slotdefs "function" column) and a ``wrapper`` that adapts a generic call into +# the right impl invocation (the slotdefs "wrapper" column: arity + operand +# order). CPython also stores a slot offset per entry; Dynamo does not need it +# -- dispatch only cares which impl to call, and MRO lookup already tells us +# whether a name resolves. Per-VT variation is which impl method is overridden; +# the table itself never varies. Lives here alongside the ``*_impl`` methods it +# names so mapping and implementations stay together; consumers (call_method +# here, getattro in object_protocol) both read it without an import cycle. +# --------------------------------------------------------------------------- + + +def _wrap_unaryfunc( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 0: + raise_type_error(tx, f"expected 0 arguments, got {len(args)}") + return func(self, tx) + + +def _wrap_binaryfunc( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 1: + raise_type_error(tx, f"expected 1 argument, got {len(args)}") + other = args[0] + return func(self, tx, other) + + +def _wrap_binaryfunc_r( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # Reflected binary op (``__radd__``): same impl, operands from the right. + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 1: + raise_type_error(tx, f"expected 1 argument, got {len(args)}") + other = args[0] + return func(self, tx, other, reverse=True) + + +def _wrap_ternaryfunc( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # __pow__ is binary or ternary: ``x.__pow__(y)`` or ``x.__pow__(y, z)`` (mod). + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) not in (1, 2): + raise_type_error(tx, f"expected 1 or 2 arguments, got {len(args)}") + z = args[1] if len(args) == 2 else None + return func(self, tx, args[0], z) + + +def _wrap_ternaryfunc_r( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # Reflected __rpow__: operands from the right. + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) not in (1, 2): + raise_type_error(tx, f"expected 1 or 2 arguments, got {len(args)}") + z = args[1] if len(args) == 2 else None + return func(self, tx, args[0], z, reverse=True) + + +def _wrap_sq_setitem( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + from .object_protocol import getindex + + if len(args) != 2: + raise_type_error(tx, f"expected 2 arguments, got {len(args)}") + [arg, value] = args + i = getindex(tx, self, arg) + return func(self, tx, i, value) + + +def _wrap_sq_item( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + from .object_protocol import getindex + + if len(args) != 1: + raise_type_error(tx, f"expected 1 argument, got {len(args)}") + + [arg] = args + i = getindex(tx, self, arg) + return func(self, tx, i) + + +def _wrap_indexargfunc( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + from .object_protocol import pynumber_as_ssize_t + + if len(args) != 1: + raise_type_error(tx, f"expected 1 argument, got {len(args)}") + + [o] = args + i = pynumber_as_ssize_t(tx, o, err=OverflowError) + return func(self, tx, i) + + +def _wrap_objobjargproc( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 2: + raise_type_error(tx, f"expected 2 arguments, got {len(args)}") + [key, value] = args + return func(self, tx, key, value) + + +def _wrap_delitem( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 1: + raise_type_error(tx, f"expected 1 argument, got {len(args)}") + [key] = args + return func(self, tx, key, None) + + +def _wrap_sq_delitem( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + from .object_protocol import getindex + + if len(args) != 1: + raise_type_error(tx, f"expected 1 argument, got {len(args)}") + [arg] = args + i = getindex(tx, self, arg) + return func(self, tx, i, None) + + +def _wrap_objobjproc( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # sq_contains via __contains__: one arg, impl returns a bool. + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 1: + raise_type_error(tx, f"expected 1 argument, got {len(args)}") + [other] = args + return func(self, tx, other) + + +def _make_richcmp( + op: str, +) -> Callable[ + [ + VariableTracker, + InstructionTranslatorBase, + Callable[..., VariableTracker], + list[VariableTracker], + dict[str, VariableTracker], + ], + VariableTracker, +]: + # tp_richcompare via __lt__/.../__ge__: one impl, op baked per dunder. + def wrapper( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 1: + raise_type_error(tx, f"expected 1 argument, got {len(args)}") + return func(self, tx, args[0], op) + + return wrapper + + +richcmp_lt = _make_richcmp("__lt__") +richcmp_le = _make_richcmp("__le__") +richcmp_eq = _make_richcmp("__eq__") +richcmp_ne = _make_richcmp("__ne__") +richcmp_gt = _make_richcmp("__gt__") +richcmp_ge = _make_richcmp("__ge__") + + +def wrap_call( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # tp_call via __call__: variadic (kwargs handled by the call_method branch). + return func(self, tx, args, kwargs) + + +def _wrap_init( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # tp_init via __init__: variadic, forwards kwargs (e.g. dict(a=1), + # defaultdict(list, d, c=3)). + return func(self, tx, args, kwargs) + + +def _wrap_setattr( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # tp_setattro via __setattr__: (name, value). + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 2: + raise_type_error(tx, f"expected 2 arguments, got {len(args)}") + return func(self, tx, args[0], args[1]) + + +def _wrap_delattr( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # tp_setattro via __delattr__: (name,). + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 1: + raise_type_error(tx, f"expected 1 argument, got {len(args)}") + return func(self, tx, args[0]) + + +def _wrap_getattro( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # tp_getattro via __getattribute__: impl takes the attribute name as a str. + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 1: + raise_type_error(tx, f"expected 1 argument, got {len(args)}") + return func(self, tx, args[0].as_python_constant()) + + +def _wrap_descr_get( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # tp_descr_get via __get__(obj, owner=None): owner defaults to type(obj). + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) not in (1, 2): + raise_type_error(tx, f"expected 1 or 2 arguments, got {len(args)}") + obj = args[0] + owner = args[1] if len(args) > 1 else obj.tp_getattro_impl(tx, "__class__") + return func(self, tx, obj, owner) + + +def _wrap_descr_set( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # tp_descr_set via __set__(obj, value): 2 args. + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 2: + raise_type_error(tx, f"expected 2 arguments, got {len(args)}") + return func(self, tx, args[0], args[1]) + + +def _wrap_descr_delete( + self: VariableTracker, + tx: InstructionTranslatorBase, + func: Callable[..., VariableTracker], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # tp_descr_set via __delete__(obj): value=None signals delete (CPython + # passes value==NULL to the shared tp_descr_set slot). + if kwargs: + raise_type_error(tx, "this method takes no keyword arguments") + if len(args) != 1: + raise_type_error(tx, f"expected 1 argument, got {len(args)}") + return func(self, tx, args[0], None) + + +class SlotGroup(Enum): + """A CPython slot group. The value is the group's index into + get_type_slots()'s 4-tuple.""" + + SEQUENCE = 0 + MAPPING = 1 + NUMBER = 2 + TYPE = 3 + + +@dataclasses.dataclass(frozen=True) +class Slot: + """A CPython type slot: the name of the VariableTracker method implementing + the slot function. + """ + + impl: str + + def __call__( + self, + vt: VariableTracker, + tx: InstructionTranslatorBase, + *args: Any, + **kwargs: Any, + ) -> VariableTracker: + return getattr(type(vt), self.impl)(vt, tx, *args, **kwargs) + + +class PyNumberMethods(NamedTuple): + nb_bool: Slot | None + nb_index: Slot | None + nb_int: Slot | None + nb_float: Slot | None + nb_negative: Slot | None + nb_positive: Slot | None + nb_absolute: Slot | None + nb_invert: Slot | None + nb_add: Slot | None + nb_inplace_add: Slot | None + nb_subtract: Slot | None + nb_inplace_subtract: Slot | None + nb_multiply: Slot | None + nb_inplace_multiply: Slot | None + nb_remainder: Slot | None + nb_inplace_remainder: Slot | None + nb_power: Slot | None + nb_inplace_power: Slot | None + nb_lshift: Slot | None + nb_inplace_lshift: Slot | None + nb_rshift: Slot | None + nb_inplace_rshift: Slot | None + nb_and: Slot | None + nb_inplace_and: Slot | None + nb_xor: Slot | None + nb_inplace_xor: Slot | None + nb_or: Slot | None + nb_inplace_or: Slot | None + nb_floor_divide: Slot | None + nb_inplace_floor_divide: Slot | None + nb_true_divide: Slot | None + nb_inplace_true_divide: Slot | None + nb_divmod: Slot | None + nb_matrix_multiply: Slot | None + nb_inplace_matrix_multiply: Slot | None + + +class PySequenceMethods(NamedTuple): + sq_length: Slot | None + sq_concat: Slot | None + sq_repeat: Slot | None + sq_item: Slot | None + sq_ass_item: Slot | None + sq_contains: Slot | None + sq_inplace_concat: Slot | None + sq_inplace_repeat: Slot | None + + +class PyMappingMethods(NamedTuple): + mp_length: Slot | None + mp_subscript: Slot | None + mp_ass_subscript: Slot | None + + +class PyTypeObject(NamedTuple): + tp_repr: Slot | None + tp_hash: Slot | None + tp_call: Slot | None + tp_str: Slot | None + tp_getattro: Slot | None + tp_setattro: Slot | None + tp_richcompare: Slot | None + tp_iter: Slot | None + tp_iternext: Slot | None + tp_descr_get: Slot | None + tp_descr_set: Slot | None + tp_init: Slot | None + tp_as_number: PyNumberMethods + tp_as_sequence: PySequenceMethods + tp_as_mapping: PyMappingMethods + + +# The tp_ slot fields of PyTypeObject (everything but the sub-struct pointers). +_TYPE_FIELDS = tuple(f for f in PyTypeObject._fields if not f.startswith("tp_as_")) + +# Per group: C slot bit -> struct field name, keyed via the enum's UPPERCASE name. +_BIT_FIELD: dict[SlotGroup, dict[int, str]] = { + SlotGroup.NUMBER: { + getattr(PyNumberSlots, f.upper()): f for f in PyNumberMethods._fields + }, + SlotGroup.SEQUENCE: { + getattr(PySequenceSlots, f.upper()): f for f in PySequenceMethods._fields + }, + SlotGroup.MAPPING: { + getattr(PyMappingSlots, f.upper()): f for f in PyMappingMethods._fields + }, + SlotGroup.TYPE: {getattr(PyTypeSlots, f.upper()): f for f in _TYPE_FIELDS}, +} + + +# The actual slot function (a VariableTracker method) each struct field dispatches to +_SLOT_FN: dict[SlotGroup, dict[str, str]] = { + SlotGroup.NUMBER: {f: f"{f}_impl" for f in PyNumberMethods._fields}, + SlotGroup.SEQUENCE: {f: f"{f}_impl" for f in PySequenceMethods._fields}, + SlotGroup.MAPPING: {f: f"{f}_impl" for f in PyMappingMethods._fields}, + SlotGroup.TYPE: { + **{f: f"{f}_impl" for f in _TYPE_FIELDS}, + "tp_call": "call_function", + "tp_hash": "hash_impl", + }, +} + +# _SLOT_FN must name a slot fn for exactly each struct field. +for _group, _fns in _SLOT_FN.items(): + if set(_fns) != set(_BIT_FIELD[_group].values()): + raise AssertionError(f"{_group.name}: _SLOT_FN fields != struct fields") + + +def _fill(group: SlotGroup, masks: tuple[int, int, int, int]) -> dict[str, Any]: + # {field -> Slot(slot fn) if the type fills the slot, else None} + mask = masks[group.value] + fn_map = _SLOT_FN[group] + return { + field: Slot(fn_map[field]) if has_slot(mask, bit) else None + for bit, field in _BIT_FIELD[group].items() + } + + +@functools.cache +def _tp_type(obj_type: type) -> PyTypeObject: + # obj_type's whole slot table (PyTypeObject-like). Independent of _tp_dict's + # cross-group collapse, so a type with both sq_length and mp_length shows up in + # both the sequence and mapping views (as CPython's separate sub-structs do). + masks = get_type_slots(obj_type) + return PyTypeObject( + tp_as_number=PyNumberMethods(**_fill(SlotGroup.NUMBER, masks)), + tp_as_sequence=PySequenceMethods(**_fill(SlotGroup.SEQUENCE, masks)), + tp_as_mapping=PyMappingMethods(**_fill(SlotGroup.MAPPING, masks)), + **_fill(SlotGroup.TYPE, masks), + ) + + +WrapperType: TypeAlias = Callable[ + [ + "VariableTracker", + "InstructionTranslatorBase", + Callable[..., "VariableTracker"], + list["VariableTracker"], + dict[str, "VariableTracker"], + ], + "VariableTracker", +] + + +@dataclasses.dataclass(frozen=True) +class SlotDef: + """One slotdefs entry: dunder name -> (impl method, call wrapper). + + ``impl`` is the VariableTracker method implementing the behavior; ``wrapper`` + adapts a generic ``(self, tx, args)`` call to it (arity + operand order). A + reflected op reuses the forward impl with ``_wrap_binaryfunc_r``; an in-place + op is a plain binary call into its own ``nb_inplace_*`` impl -- so no + reverse/inplace flags are needed. + + ``group`` is the CPython slot group (``SlotGroup``) the entry lives in and + ``slot`` is the bit within it; together they decide whether a real type + implements the slot. + """ + + name: str + impl: str + group: SlotGroup + slot: int + wrapper: WrapperType + + def __call__( + self, + vt: VariableTracker, + tx: InstructionTranslatorBase, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + """Call the impl via the wrapper, passing self, tx, and args.""" + func = getattr(type(vt), self.impl) + return self.wrapper(vt, tx, func, args, kwargs) + + +def SQSLOT(name: str, impl: str, slot: int, wrapper: WrapperType) -> SlotDef: + return SlotDef(name, impl, SlotGroup.SEQUENCE, slot, wrapper) + + +def MPSLOT(name: str, impl: str, slot: int, wrapper: WrapperType) -> SlotDef: + return SlotDef(name, impl, SlotGroup.MAPPING, slot, wrapper) + + +def NBSLOT(name: str, impl: str, slot: int, wrapper: WrapperType) -> SlotDef: + return SlotDef(name, impl, SlotGroup.NUMBER, slot, wrapper) + + +def TPSLOT(name: str, impl: str, slot: int, wrapper: WrapperType) -> SlotDef: + return SlotDef(name, impl, SlotGroup.TYPE, slot, wrapper) + + +# The declarative slot table (mirrors CPython's static slotdefs[] array). Each +# entry: dunder name, impl method, ``group`` + ``slot`` (which slot sub-struct +# and bit -- reflected ops share the forward slot's group/slot), and wrapper +# (call shape). +_SLOTDEFS: list[SlotDef] = [ + # SlotDef("__getattribute__", ), + # SlotDef("__getattr__", ), + # SlotDef("__setattr__", ), + # SlotDef("__delattr__", ), + TPSLOT("__repr__", "tp_repr_impl", PyTypeSlots.TP_REPR, _wrap_unaryfunc), + # TPSLOT("__hash__", "tp_hash_impl", PyTypeSlots.TP_HASH, _wrap_unaryfunc), + TPSLOT("__call__", "call_function", PyTypeSlots.TP_CALL, wrap_call), + TPSLOT("__str__", "tp_str_impl", PyTypeSlots.TP_STR, _wrap_unaryfunc), + TPSLOT( + "__getattribute__", + "tp_getattro_impl", + PyTypeSlots.TP_GETATTRO, + _wrap_getattro, + ), + TPSLOT( + "__getattr__", + "tp_getattro_impl", + PyTypeSlots.TP_GETATTRO, + _wrap_getattro, + ), + # This needs one to model tp_setattro first + PyObject_GenericSetAttr / PyObject_GenericDelAttr + # TPSLOT( + # "__setattr__", + # "setattro_impl", + # PyTypeSlots.TP_SETATTRO, + # _wrap_setattr, + # ), + # TPSLOT( + # "__delattr__", + # "delattro_impl", + # PyTypeSlots.TP_SETATTRO, + # _wrap_delattr, + # ), + TPSLOT( + "__lt__", + "tp_richcompare_impl", + PyTypeSlots.TP_RICHCOMPARE, + richcmp_lt, + ), + TPSLOT( + "__le__", + "tp_richcompare_impl", + PyTypeSlots.TP_RICHCOMPARE, + richcmp_le, + ), + TPSLOT( + "__eq__", + "tp_richcompare_impl", + PyTypeSlots.TP_RICHCOMPARE, + richcmp_eq, + ), + TPSLOT( + "__ne__", + "tp_richcompare_impl", + PyTypeSlots.TP_RICHCOMPARE, + richcmp_ne, + ), + TPSLOT( + "__gt__", + "tp_richcompare_impl", + PyTypeSlots.TP_RICHCOMPARE, + richcmp_gt, + ), + TPSLOT( + "__ge__", + "tp_richcompare_impl", + PyTypeSlots.TP_RICHCOMPARE, + richcmp_ge, + ), + TPSLOT("__iter__", "tp_iter_impl", PyTypeSlots.TP_ITER, _wrap_unaryfunc), + TPSLOT( + "__next__", + "tp_iternext_impl", + PyTypeSlots.TP_ITERNEXT, + _wrap_unaryfunc, + ), + TPSLOT( + "__get__", + "tp_descr_get_impl", + PyTypeSlots.TP_DESCR_GET, + _wrap_descr_get, + ), + TPSLOT( + "__set__", + "tp_descr_set_impl", + PyTypeSlots.TP_DESCR_SET, + _wrap_descr_set, + ), + TPSLOT( + "__delete__", + "tp_descr_set_impl", + PyTypeSlots.TP_DESCR_SET, + _wrap_descr_delete, + ), + TPSLOT("__init__", "tp_init_impl", PyTypeSlots.TP_INIT, _wrap_init), + # SlotDef("__new__", ...), # missing + # SlotDef("__del__", ...), # missing + # SlotDef("__buffer__", ...), # missing + # SlotDef("__release_buffer__", ...), # missing + # SlotDef("__await__", ...), # missing + # SlotDef("__aiter__", ...), # missing + # SlotDef("__anext__", ...), # missing + NBSLOT( + "__add__", + "nb_add_impl", + PyNumberSlots.NB_ADD, + _wrap_binaryfunc, + ), + NBSLOT( + "__radd__", + "nb_add_impl", + PyNumberSlots.NB_ADD, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__sub__", + "nb_subtract_impl", + PyNumberSlots.NB_SUBTRACT, + _wrap_binaryfunc, + ), + NBSLOT( + "__rsub__", + "nb_subtract_impl", + PyNumberSlots.NB_SUBTRACT, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__mul__", + "nb_multiply_impl", + PyNumberSlots.NB_MULTIPLY, + _wrap_binaryfunc, + ), + NBSLOT( + "__rmul__", + "nb_multiply_impl", + PyNumberSlots.NB_MULTIPLY, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__mod__", + "nb_remainder_impl", + PyNumberSlots.NB_REMAINDER, + _wrap_binaryfunc, + ), + NBSLOT( + "__rmod__", + "nb_remainder_impl", + PyNumberSlots.NB_REMAINDER, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__divmod__", + "nb_divmod_impl", + PyNumberSlots.NB_DIVMOD, + _wrap_binaryfunc, + ), + NBSLOT( + "__rdivmod__", + "nb_divmod_impl", + PyNumberSlots.NB_DIVMOD, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__pow__", + "nb_power_impl", + PyNumberSlots.NB_POWER, + _wrap_ternaryfunc, + ), + NBSLOT( + "__rpow__", + "nb_power_impl", + PyNumberSlots.NB_POWER, + _wrap_ternaryfunc_r, + ), + NBSLOT( + "__neg__", + "nb_negative_impl", + PyNumberSlots.NB_NEGATIVE, + _wrap_unaryfunc, + ), + NBSLOT( + "__pos__", + "nb_positive_impl", + PyNumberSlots.NB_POSITIVE, + _wrap_unaryfunc, + ), + NBSLOT( + "__abs__", + "nb_absolute_impl", + PyNumberSlots.NB_ABSOLUTE, + _wrap_unaryfunc, + ), + NBSLOT( + "__bool__", + "nb_bool_impl", + PyNumberSlots.NB_BOOL, + _wrap_unaryfunc, + ), + NBSLOT( + "__invert__", + "nb_invert_impl", + PyNumberSlots.NB_INVERT, + _wrap_unaryfunc, + ), + NBSLOT( + "__lshift__", + "nb_lshift_impl", + PyNumberSlots.NB_LSHIFT, + _wrap_binaryfunc, + ), + NBSLOT( + "__rlshift__", + "nb_lshift_impl", + PyNumberSlots.NB_LSHIFT, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__rshift__", + "nb_rshift_impl", + PyNumberSlots.NB_RSHIFT, + _wrap_binaryfunc, + ), + NBSLOT( + "__rrshift__", + "nb_rshift_impl", + PyNumberSlots.NB_RSHIFT, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__and__", + "nb_and_impl", + PyNumberSlots.NB_AND, + _wrap_binaryfunc, + ), + NBSLOT( + "__rand__", + "nb_and_impl", + PyNumberSlots.NB_AND, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__xor__", + "nb_xor_impl", + PyNumberSlots.NB_XOR, + _wrap_binaryfunc, + ), + NBSLOT( + "__rxor__", + "nb_xor_impl", + PyNumberSlots.NB_XOR, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__or__", + "nb_or_impl", + PyNumberSlots.NB_OR, + _wrap_binaryfunc, + ), + NBSLOT( + "__ror__", + "nb_or_impl", + PyNumberSlots.NB_OR, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__int__", + "nb_int_impl", + PyNumberSlots.NB_INT, + _wrap_unaryfunc, + ), + NBSLOT( + "__float__", + "nb_float_impl", + PyNumberSlots.NB_FLOAT, + _wrap_unaryfunc, + ), + NBSLOT( + "__iadd__", + "nb_inplace_add_impl", + PyNumberSlots.NB_INPLACE_ADD, + _wrap_binaryfunc, + ), + NBSLOT( + "__isub__", + "nb_inplace_subtract_impl", + PyNumberSlots.NB_INPLACE_SUBTRACT, + _wrap_binaryfunc, + ), + NBSLOT( + "__imul__", + "nb_inplace_multiply_impl", + PyNumberSlots.NB_INPLACE_MULTIPLY, + _wrap_binaryfunc, + ), + NBSLOT( + "__imod__", + "nb_inplace_remainder_impl", + PyNumberSlots.NB_INPLACE_REMAINDER, + _wrap_binaryfunc, + ), + NBSLOT( + "__ipow__", + "nb_inplace_power_impl", + PyNumberSlots.NB_INPLACE_POWER, + _wrap_binaryfunc, + ), + NBSLOT( + "__ilshift__", + "nb_inplace_lshift_impl", + PyNumberSlots.NB_INPLACE_LSHIFT, + _wrap_binaryfunc, + ), + NBSLOT( + "__irshift__", + "nb_inplace_rshift_impl", + PyNumberSlots.NB_INPLACE_RSHIFT, + _wrap_binaryfunc, + ), + NBSLOT( + "__iand__", + "nb_inplace_and_impl", + PyNumberSlots.NB_INPLACE_AND, + _wrap_binaryfunc, + ), + NBSLOT( + "__ixor__", + "nb_inplace_xor_impl", + PyNumberSlots.NB_INPLACE_XOR, + _wrap_binaryfunc, + ), + NBSLOT( + "__ior__", + "nb_inplace_or_impl", + PyNumberSlots.NB_INPLACE_OR, + _wrap_binaryfunc, + ), + NBSLOT( + "__floordiv__", + "nb_floor_divide_impl", + PyNumberSlots.NB_FLOOR_DIVIDE, + _wrap_binaryfunc, + ), + NBSLOT( + "__rfloordiv__", + "nb_floor_divide_impl", + PyNumberSlots.NB_FLOOR_DIVIDE, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__truediv__", + "nb_true_divide_impl", + PyNumberSlots.NB_TRUE_DIVIDE, + _wrap_binaryfunc, + ), + NBSLOT( + "__rtruediv__", + "nb_true_divide_impl", + PyNumberSlots.NB_TRUE_DIVIDE, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__ifloordiv__", + "nb_inplace_floor_divide_impl", + PyNumberSlots.NB_INPLACE_FLOOR_DIVIDE, + _wrap_binaryfunc, + ), + NBSLOT( + "__itruediv__", + "nb_inplace_true_divide_impl", + PyNumberSlots.NB_INPLACE_TRUE_DIVIDE, + _wrap_binaryfunc, + ), + NBSLOT( + "__index__", + "nb_index_impl", + PyNumberSlots.NB_INDEX, + _wrap_unaryfunc, + ), + NBSLOT( + "__matmul__", + "nb_matrix_multiply_impl", + PyNumberSlots.NB_MATRIX_MULTIPLY, + _wrap_binaryfunc, + ), + NBSLOT( + "__rmatmul__", + "nb_matrix_multiply_impl", + PyNumberSlots.NB_MATRIX_MULTIPLY, + _wrap_binaryfunc_r, + ), + NBSLOT( + "__imatmul__", + "nb_inplace_matrix_multiply_impl", + PyNumberSlots.NB_INPLACE_MATRIX_MULTIPLY, + _wrap_binaryfunc, + ), + # Mapping + MPSLOT( + "__len__", + "mp_length_impl", + PyMappingSlots.MP_LENGTH, + _wrap_unaryfunc, + ), + MPSLOT( + "__getitem__", + "mp_subscript_impl", + PyMappingSlots.MP_SUBSCRIPT, + _wrap_binaryfunc, + ), + MPSLOT( + "__setitem__", + "mp_ass_subscript_impl", + PyMappingSlots.MP_ASS_SUBSCRIPT, + _wrap_objobjargproc, + ), + MPSLOT( + "__delitem__", + "mp_ass_subscript_impl", + PyMappingSlots.MP_ASS_SUBSCRIPT, + _wrap_delitem, + ), + # Sequence + SQSLOT( + "__len__", + "sq_length_impl", + PySequenceSlots.SQ_LENGTH, + _wrap_unaryfunc, + ), + SQSLOT( + "__add__", + "sq_concat_impl", + PySequenceSlots.SQ_CONCAT, + _wrap_binaryfunc, + ), + SQSLOT( + "__mul__", + "sq_repeat_impl", + PySequenceSlots.SQ_REPEAT, + _wrap_indexargfunc, + ), + SQSLOT( + "__rmul__", + "sq_repeat_impl", + PySequenceSlots.SQ_REPEAT, + _wrap_indexargfunc, + ), + SQSLOT( + "__getitem__", + "sq_item_impl", + PySequenceSlots.SQ_ITEM, + _wrap_sq_item, + ), + SQSLOT( + "__setitem__", + "sq_ass_item_impl", + PySequenceSlots.SQ_ASS_ITEM, + _wrap_sq_setitem, + ), + SQSLOT( + "__delitem__", + "sq_ass_item_impl", + PySequenceSlots.SQ_ASS_ITEM, + _wrap_sq_delitem, + ), + SQSLOT( + "__contains__", + "sq_contains_impl", + PySequenceSlots.SQ_CONTAINS, + _wrap_objobjproc, + ), + SQSLOT( + "__iadd__", + "sq_inplace_concat_impl", + PySequenceSlots.SQ_INPLACE_CONCAT, + _wrap_binaryfunc, + ), + SQSLOT( + "__imul__", + "sq_inplace_repeat_impl", + PySequenceSlots.SQ_INPLACE_REPEAT, + _wrap_indexargfunc, + ), +] + + +@functools.cache +def _compute_slotdefs(obj_type: type) -> dict[str, SlotDef]: + masks = get_type_slots(obj_type) + d: dict[str, SlotDef] = {} + for sd in _SLOTDEFS: + if sd.name in d: + continue + if has_slot(masks[sd.group.value], sd.slot): + d[sd.name] = sd + return d + + +class VariableTrackerMeta(type): + all_subclasses: list[type] = [] + + def __new__( + mcs: type, name: str, bases: tuple[type, ...], attrs: dict[str, Any] + ) -> type: + # Determine which metaclass to use based on the class attributes + # Classes with _no_implicit_realize = True should NOT implicitly realize + # (they need standard isinstance behavior to avoid infinite recursion) + # Check if any base class has _no_implicit_realize set, or if it's in attrs + no_implicit_realize = attrs.get("_no_implicit_realize", False) or any( + getattr(base, "_no_implicit_realize", False) for base in bases + ) + if no_implicit_realize or name == "VariableTracker": + # Use base VariableTrackerMeta (no custom __instancecheck__) + return super().__new__(VariableTrackerMeta, name, bases, attrs) + else: + # Use ImplicitRealizingVariableTrackerMeta for all other subclasses + return super().__new__( + ImplicitRealizingVariableTrackerMeta, name, bases, attrs + ) + + def __init__( + cls: type, name: str, bases: tuple[type, ...], attrs: dict[str, Any] + ) -> None: + super().__init__(name, bases, attrs) # type: ignore[misc] + VariableTrackerMeta.all_subclasses.append(cls) + + +class ImplicitRealizingVariableTrackerMeta(VariableTrackerMeta): + def __instancecheck__(self, instance: object) -> bool: + """Make isinstance work with LazyVariableTracker""" + if instancecheck(LazyVariableTracker, instance): + return instance.lazy_isinstance(self) # pyrefly: ignore[missing-attribute] + return instancecheck(self, instance) + + +class VariableTracker(metaclass=VariableTrackerMeta): + """ + Base class for tracked locals and stack values + + VariableTracker instances are immutable and should be copied in + order to change them. + + Prefer the factory function VariableTracker.build() over VariableTracker.__init__(). + """ + + # The CPython type(s) this VT is designed to represent. + # Single type or tuple of types. None means no static CPython type mapping + # (e.g., dynamic types like UserDefinedObjectVariable, or Dynamo-internal VTs). + _cpython_type: type | tuple[type, ...] | None = None + + # Declarative named-method table (analogous to CPython's tp_methods): maps a + # method name to a Method describing its handler and calling convention. + # `call_method` consults this before the object-protocol (tp_slot) dispatch. + # Lookup walks the class MRO (see `_lookup_tp_table`), so a subclass table + # adds to (rather than replaces) the entries it inherits, with the + # most-derived class winning on name collisions. + tp_methods: dict[str, Method] = {} + # Declarative attribute tables, split to match CPython: tp_getset holds the + # PyGetSetDef attributes, tp_members the PyMemberDef ones. + tp_getset: dict[str, GetSet] = {} + tp_members: dict[str, Member] = {} + + def _lookup_tp_table(self, name: str, *table_attrs: str) -> Any: + """Resolve *name* in the given declarative tables across the class MRO. + + Mirrors CPython method/getset/member inheritance: each class contributes + its own table entries into its own tp_dict, and lookup walks the MRO with + the most-derived class winning. A subclass table therefore *adds* to + (rather than replaces) the entries it inherits. Within a class the tables + are consulted in the order given. + """ + for klass in type(self).__mro__: + d = klass.__dict__ + for attr in table_attrs: + table = d.get(attr) + if table is not None and name in table: + return table[name] + return None + + def lookup_tp_getset_member(self, name: str) -> GetSet | Member | None: + return self._lookup_tp_table(name, "tp_getset", "tp_members") + + def lookup_tp_method(self, name: str) -> Method | None: + return self._lookup_tp_table(name, "tp_methods") + + def method_flags_type(self) -> type: + """Type whose CPython ml_flags define this VT's tp_methods arities + (see _derive_method_flags). Defaults to python_type(); a VT whose + python_type() is a pure-Python stand-in without C ml_flags (e.g. + OrderedSet) overrides this to the builtin whose method arities it + mirrors, so MethodFlags still enforces arity.""" + return maybe_get_python_type(self) + + # fields to leave unmodified in apply() + _nonvar_fields = { + "value", + "guards", + "source", + "source_location", + "mutation_type", + "parents_tracker", + "user_code_variable_name", + "dict_vt", + } + + # Lazily-created view of the instance __dict__, backed by the side effects table + dict_vt: variables.DunderDictVariable | None = None + + def clone(self, **kwargs: Any) -> VariableTracker: + """Shallow copy with some (optional) changes""" + args = dict(self.__dict__) + args.update(kwargs) + return self.__class__(**args) + + @classmethod + def visit( + cls, + fn: Callable[[VariableTracker], None], + value: Any, + cache: dict[int, Any] | None = None, + side_effects: SideEffects | None = None, + ) -> None: + """ + Walk value and call fn on all the VariableTracker instances. + + When side_effects is provided, also walks attributes stored in + store_attr_mutations (e.g. dataclass fields set during tracing + that aren't in the VT's __dict__). + + Implemented with an explicit worklist rather than recursion so that + deeply chained structures (e.g. the ~N-node buffer built by + itertools.tee over a long iterable) do not overflow the Python stack. + Children are pushed in reverse so they are popped in their original + order, matching the pre-order DFS the previous recursive version + produced (callers rely on the visitation order, e.g. for graph output + ordering). + """ + if cache is None: + cache = {} + + worklist = [value] + while worklist: + cur = worklist.pop() + idx = id(cur) + if idx in cache: + continue + # save `cur` to keep it alive and ensure id() isn't reused + cache[idx] = cur + + children: list[Any] + if isinstance(cur, VariableTracker): + cur = cur.unwrap() + fn(cur) + cur = cur.unwrap() # calling fn() might have realized it + nonvars = cur._nonvar_fields + children = [ + subvalue + for key, subvalue in cur.__dict__.items() + if key not in nonvars + ] + if ( + side_effects is not None + and cur in side_effects.store_attr_mutations + ): + children.extend(side_effects.store_attr_mutations[cur].values()) + elif istype(cur, (list, tuple)): + children = list(cur) + elif istype(cur, (dict, collections.OrderedDict)): + children = list(cur.values()) + else: + continue + worklist.extend(reversed(children)) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}()" + + def debug_repr(self) -> str: + # Intended to be overridden to provide more info + try: + return repr(self.as_python_constant()) + except NotImplementedError: + return repr(self) + + def python_type(self) -> type: + """ + Abstract method to be implemented by subclasses of VariableTracker. + + This method should return the type represented by the instance of the subclass. + The purpose is to provide a standardized way to retrieve the Python type information + of the variable being tracked. + + Returns: + type: The Python type (such as int, str, list, etc.) of the variable tracked by + the subclass. If the type cannot be determined or is not relevant, + leaving it undefined or invoking super() is always sound. + + Note: + This is an abstract method and may be overridden in subclasses. + + Example: + class SetVariable(VariableTracker): + def python_type(self): + return set + + Raises: + NotImplementedError: If the method is not implemented in a subclass. + """ + try: + return type(self.as_python_constant()) + except NotImplementedError: + raise NotImplementedError(f"{self} has no type") from None + + def python_type_name(self) -> str: + """ + Return the type name for the Python type this VariableTracker represents. + + Mirrors CPython's tp_name slot (PyTypeObject.tp_name). In Python 3.10+, + type.__name__ matches CPython's tp_name exactly (e.g., "list", "NoneType"). + + Note: There are no external callers outside torch._dynamo that rely on this. + Internal uses should prefer this over hardcoded type name strings. + """ + try: + return self.python_type().__name__ + except NotImplementedError: + return "" + + def python_qualified_name(self) -> str: + """ + Equivalent to _PyType_GetFullyQualifiedName + + See https://github.com/python/cpython/blob/v3.15.0b4/Objects/typeobject.c#L1658 + """ + try: + type_ = self.python_type() + except NotImplementedError: + return "" + # Direct attribute access is safe here because type objects use the getset protocol, which will only return str + # (and not execute user code) + mod = type_.__module__ + qn = type_.__qualname__ + if mod not in ("__main__", "builtins"): + return f"{mod}.{qn}" + else: + return qn + + def as_python_constant(self) -> Any: + """For constants""" + raise AsPythonConstantNotImplementedError(self) + + def guard_as_python_constant(self) -> Any: + """Similar to as_python_constant(), but add ID_MATCH guards to try to force things to become constants""" + try: + return self.as_python_constant() + except NotImplementedError: + unimplemented( + gb_type="Not a Python constant", + context=f"guard_as_python_constant {self}", + explanation=f"Failed to convert {self} into a Python constant.", + hints=[], + ) + + def is_python_constant(self) -> bool: + try: + self.as_python_constant() + return True + except NotImplementedError: + return False + + def nb_bool_impl(self, tx: InstructionTranslatorBase) -> VariableTracker | None: + # Mirrors CPython's tp_as_number->nb_bool slot. + # https://github.com/python/cpython/blob/c09ccd9c429/Objects/object.c#L2135-L2158 + # + # Returns None when the type has no nb_bool, causing generic_is_true to + # fall through to length check, then truthy default. + return None + + def is_hashable(self) -> bool: + """Whether the underlying Python object is hashable. + + Defaults to True — in CPython, all objects are hashable unless the type + explicitly sets __hash__ = None (PyObject_HashNotImplemented). + https://github.com/python/cpython/blob/e76aa128fe/Objects/typeobject.c#L7288 + + Subclasses override to return False for unhashable types (list, dict, + set, etc.). This is a fast, side-effect-free check used by + HashableTracker and __contains__ before attempting to hash. + """ + return True + + def hash_impl(self, tx: InstructionTranslatorBase) -> tuple[int, bool]: + """Default tp_hash: object.__hash__ = PyObject_GenericHash (identity hash). + + PyObject_GenericHash: https://github.com/python/cpython/blob/e76aa128fe/Python/pyhash.c#L143-L147 + Assigned on object: https://github.com/python/cpython/blob/e76aa128fe/Objects/typeobject.c#L7288 + + Returns (hash_value, is_fake). is_fake=True means the hash depends on + a sourceless object's identity and must not escape into output bytecode. + + VT subclasses override this for types with their own C tp_hash. + UserDefinedObjectVariable.hash_impl handles the MRO walk for custom + Python __hash__, builtin-inherited C hash, and unknown C tp_hash. + """ + # object.__hash__ = Py_HashPointer(obj) — identity hash. + if self.source: + real_val = tx.output.resolve_source_value(self.source) + if type(real_val).__hash__ is not object.__hash__: + unimplemented( + gb_type="Missing hash_impl override", + context=f"hash_impl {self}", + explanation=f"{type(self).__name__} wraps " + f"{type(real_val).__name__} which has a non-default " + f"tp_hash. Add a hash_impl override to " + f"{type(self).__name__}.", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + # object.__hash__ = id(obj), so the hash is identity-based. + # Return is_fake=True so the hash is only usable internally + # (dict keys, set membership) and doesn't escape into bytecode + # — avoids installing an ID_MATCH guard just for hashing. + # TODO when LazyConstants are fully landed, we can use them here instead. + return hash(real_val), True + # Sourceless: no real object to hash — fake id. + return id(self), True + + def tp_richcompare_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + op: str, + ) -> VariableTracker: + """Per-VT tp_richcompare slot. Subclasses must override. + + Analogous to CPython's tp_richcompare function pointer on PyTypeObject. + Returns ConstantVariable(NotImplemented) when the type does not handle + the comparison (signaling do_richcompare to try the other operand). + + Called from two paths: + - call_method("__eq__") calls tp_richcompare_impl directly (like CPython's + a.__eq__(b) calling tp_richcompare without do_richcompare). + - generic_richcompare calls tp_richcompare_impl as part of the 4-step + do_richcompare algorithm (subclass priority, forward, reflected, + fallback). + """ + unimplemented( + gb_type="Missing tp_richcompare_impl override", + context=f"tp_richcompare_impl {self} {op}", + explanation=f"{type(self).__name__} does not implement " + f"tp_richcompare_impl. Add a tp_richcompare_impl override to " + f"{type(self).__name__}.", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + + def is_constant_match(self, *values: Any) -> bool: + """ + Check if this variable is a python constant matching one of the given values. + + Examples: + var.is_constant_match(None) # True if var is constant None + var.is_constant_match(True, False) # True if var is constant True or False + var.is_constant_match(NotImplemented) # True if var is constant NotImplemented + """ + return False + + def is_constant_none(self) -> bool: + """Check if this variable is a constant None value.""" + return False + + def make_guard(self, fn: Callable[..., Any]) -> Guard: + if self.source: + return self.source.make_guard(fn) + raise NotImplementedError + + def const_getattr(self, tx: InstructionTranslatorBase, name: str) -> Any: + """getattr(self, name) returning a python constant""" + raise NotImplementedError + + def is_symnode_like(self) -> bool: + """Return True for values that can participate in SymNode operations""" + return False + + def is_tensor(self) -> bool: + """Return True for TensorVariable instances""" + return False + + def get_handler_type_for_dispatch(self) -> type[VariableTracker]: + """Return the VariableTracker type to use for builtin handler dispatch. + + This is used by BuiltinVariable to look up the appropriate handler for + a given set of arguments. Most VariableTrackers just return their own + type, but LazyConstantVariable returns ConstantVariable since it can + be treated as a constant for most builtin operations. + + Subclasses that override this should install appropriate guards to + ensure the dispatched handler remains valid. + """ + return type(self) + + def get_value_for_setattr(self) -> object | None: + """Return the wrapped Python object for generic STORE_ATTR mutation, + or None to decline. Only override for VTs with __dict__ and + standard __setattr__.""" + return None + + def lookup_instance_dict( + self, tx: InstructionTranslatorBase, name: str + ) -> VariableTracker | None: + """Look up *name* in the instance __dict__ (tp_dictoffset equivalent). + + Returns a VT if the attribute exists in the instance dict, None if + the attribute is absent or the VT has no instance dict at all. + UDOV overrides to check self.value.__dict__ + side effects. + """ + return None + + def call_getattr_fallback( + self, tx: InstructionTranslatorBase, name: str + ) -> VariableTracker | None: + """Call __getattr__ fallback (step 6 of GenericGetAttr). + + Returns a VT if the type defines __getattr__ and it succeeds, + None otherwise. The base returns None (most types have no + __getattr__). UDOV overrides to walk the MRO for __getattr__. + """ + return None + + def tp_getattro_impl( + self, tx: InstructionTranslatorBase, name: str + ) -> VariableTracker: + """Default attribute access via object_generic_getattr. + + Tries the MRO-based descriptor protocol first (PyObject_GenericGetAttr), + falls back to const_getattr for VTs without a known python_type or + when the descriptor protocol hits an unhandled type. + """ + # tp_getset/tp_members are data descriptors: resolve ahead of the + # object-protocol walk. A getter returning None declines. + getset = self.lookup_tp_getset_member(name) + if getset is not None: + result = getset.getter(self, tx) + if result is not None: + return result + + # object.__class__: one shared getset on `object` rather than per-VT. + if name == "__class__": + return VariableTracker.build(tx, self.python_type()) + + try: + py_type = self.python_type() + except NotImplementedError: + py_type = None + + if py_type is not None: + from .object_protocol import ( + _UnhandledDescriptorError, + object_generic_getattr, + ) + + try: + return object_generic_getattr(tx, self, name) + except _UnhandledDescriptorError: + pass + + value = self.const_getattr(tx, name) + if not variables.ConstantVariable.is_literal(value): + raise NotImplementedError + source = self.source and AttrSource(self.source, name) + if source and not self.is_python_constant(): + # Skip guards on const getattr objects like __code__.co_argcount + install_guard(source.make_guard(GuardBuilder.CONSTANT_MATCH)) + return variables.ConstantVariable.create(value, source=source) + + def get_dict_vt( + self, tx: InstructionTranslatorBase + ) -> variables.DunderDictVariable: + # Callers gate this on the object actually having an instance __dict__ + # (e.g. the per-VT `__dict__` attribute branches). If a VT without a + # real instance dict reaches here, DunderDictVariable's example-value + # lookup graph-breaks rather than fabricating a bogus dict. + if self.dict_vt is None: + self.dict_vt = variables.DunderDictVariable.create(tx, self) + return self.dict_vt + + def is_proxy(self) -> bool: + try: + self.as_proxy() + return True + except NotImplementedError: + return False + + def as_proxy(self) -> Any: + raise NotImplementedError(str(self)) + + def maybe_fx_node(self) -> Node | None: + try: + proxy = self.as_proxy() + import torch.fx + + if isinstance(proxy, torch.fx.Proxy): + return proxy.node + return None + except NotImplementedError: + return None + + def _contains_self_reference(self) -> bool: + """Check if this variable references itself (directly or indirectly).""" + found_self = False + + def check(vt: VariableTracker) -> None: + nonlocal found_self + if vt is self: + found_self = True + + # unwrap first iteration - otherwise we can't detect if we revisit self + for key, subvalue in self.__dict__.items(): + if key not in self._nonvar_fields: + VariableTracker.visit(check, subvalue) + + return found_self + + def reconstruct(self, codegen: PyCodegen) -> None: + raise NotImplementedError + + def reconstruct_pycode(self, codegen: PyCodegen) -> str: + raise NotImplementedError(f"reconstruct_pycode not implemented for {self}") + + def unpack_var_sequence( + self, tx: InstructionTranslatorBase + ) -> list[VariableTracker]: + raise NotImplementedError + + def _hasattr_check_side_effects( + self, tx: InstructionTranslatorBase, name: str + ) -> ConstantVariable | None: + """If *name* has a pending mutation, return the hasattr result; else None.""" + if tx.output.side_effects.has_pending_mutation_of_attr(self, name): + value = tx.output.side_effects.load_attr(self, name, deleted_ok=True) + return variables.ConstantVariable.create( + not isinstance(value, variables.DeletedVariable) + ) + return None + + def call_obj_hasattr( + self, tx: InstructionTranslatorBase, name: str + ) -> ConstantVariable: + """Dynamo's hasattr(): try tp_getattro_impl, catch AttributeError. + + Mirrors CPython's PyObject_HasAttr (via PyObject_GetOptionalAttr): + call tp_getattro, suppress AttributeError via PyErr_Clear, return + True/False. + https://github.com/python/cpython/blob/848cb25624ab44c9fef2966c777419376b65af1b/Objects/object.c#L1346 + """ + result = self._hasattr_check_side_effects(tx, name) + if result is not None: + return result + + try: + self.tp_getattro_impl(tx, name) + return variables.ConstantVariable.create(True) + except ObservedAttributeError: + tx.exn_vt_stack.clear_current_exception() + return variables.ConstantVariable.create(False) + except (NotImplementedError, Unsupported): + pass + + unimplemented( + gb_type="Unsupported hasattr call", + context=f"call_obj_hasattr {self} {name}", + explanation=f"Dynamo does not know how to trace the function `{self.debug_repr()}`", + hints=[ + f"Avoid calling `hasattr({self.__class__.__name__}, {name})` in your code.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + def tp_iter_impl(self, tx: InstructionTranslatorBase) -> VariableTracker: + """ + Implements PyObject_GetIter semantics (tp_iter slot). + Subclasses override this to support iteration. + """ + # PyObject_GetIter: https://github.com/python/cpython/blob/3.13/Objects/abstract.c#L2847-L2870 + # TODO: raise TypeError instead - Make sure the jit tests for ScriptDict/ScriptList works with + # this change + unimplemented( + gb_type="missing tp_iter", + context=f"tp_iter_impl not implemented for {self.python_type_name()}", + explanation=f"Dynamo does not know how to iterate over `{self.debug_repr()}`.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def tp_init_impl( + self, + tx: InstructionTranslatorBase, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + """tp_init slot (__init__). VTs override to initialize instances.""" + unimplemented( + gb_type="missing tp_init", + context=f"tp_init_impl not implemented for {self.python_type_name()}", + explanation=f"Dynamo does not know how to trace __init__ on `{self.debug_repr()}`.", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + + def call_function( + self, + tx: InstructionTranslatorBase, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Reaching this base fallback means no subclass handled the call. If the + # object's type has no tp_call slot, it is genuinely not callable, so + # mirror CPython's PyObject_Call TypeError. Otherwise the type is + # callable in principle but unsupported by Dynamo -> graph break. + from .object_protocol import pycallable_check + + try: + obj_type = self.python_type() + except NotImplementedError: + obj_type = None + if obj_type is not None and not pycallable_check(obj_type): + raise_type_error(tx, f"'{self.python_type_name()}' object is not callable") + unimplemented( + gb_type="Unsupported function call", + context=f"call_function {self} {args} {kwargs}", + explanation=f"Dynamo does not know how to trace the function `{self.debug_repr()}`", + hints=[ + f"Avoid calling `{self.debug_repr()}` in your code.", + "Please report an issue to PyTorch.", + ], + ) + + def sq_length_impl(self, tx: InstructionTranslatorBase) -> VariableTracker: + """Called when sq_length is not implemented.""" + raise_observed_exception( + TypeError, + tx, + args=[f"object of type '{self.python_type_name()}' has no len()"], + ) + + def mp_length_impl(self, tx: InstructionTranslatorBase) -> VariableTracker: + """Called when mp_length is not implemented.""" + raise_observed_exception( + TypeError, + tx, + args=[f"object of type '{self.python_type_name()}' has no len()"], + ) + + def mp_subscript_impl( + self, + tx: InstructionTranslatorBase, + key: VariableTracker, + ) -> VariableTracker: + # PyObject_GetItem: https://github.com/python/cpython/blob/62a6e898e01/Objects/abstract.c#L155-L206 + # generic_getitem handles dispatch and raises TypeError for non-subscriptable + # objects. This base fallback fires for types with mp_subscript at the + # C level but no Dynamo override yet. + unimplemented( + gb_type="missing_mp_subscript", + context=f"mp_subscript_impl not defined for {type(self).__name__}", + explanation=f"Dynamo does not yet support subscripting '{self.python_type_name()}'.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def sq_item_impl( + self, + tx: InstructionTranslatorBase, + key: VariableTracker, + ) -> VariableTracker: + # PyObject_GetItem Branch 2: tp_as_sequence->sq_item + # https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L168-L181 + # Key has already been converted to int via nb_index_impl by generic_getitem. + unimplemented( + gb_type="unsupported __getitem__ (sq_item)", + context=f"sq_item_impl {self} {key}", + explanation=f"Dynamo does not know how to handle sq_item on {self}", + hints=[], + ) + + def sq_contains_impl( + self, tx: InstructionTranslatorBase, item: VariableTracker + ) -> VariableTracker: + """Called when sq_contains is not implemented.""" + unimplemented( + gb_type="missing sq_contains", + context=f"sq_contains_impl not implemented for {self.python_type_name()}", + explanation=f"Dynamo does not know how to check if `{item.debug_repr()}` is in `{self.debug_repr()}`.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def mp_ass_subscript_impl( + self, + tx: InstructionTranslatorBase, + key: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + unimplemented( + gb_type="missing_mp_ass_subscript", + context=f"mp_ass_subscript_impl not defined for {self.python_type_name()}", + explanation=f"Dynamo does not yet support item assignment on '{self.python_type_name()}'.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def sq_ass_item_impl( + self, + tx: InstructionTranslatorBase, + key: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + unimplemented( + gb_type="unsupported __setitem__ (sq_ass_item)", + context=f"sq_ass_item_impl {self} {key} {value}", + explanation=f"Dynamo does not know how to handle sq_ass_item on {self}", + hints=[], + ) + + def sq_concat_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """Sequence concatenation via + operator (sq_concat slot).""" + unimplemented( + gb_type="missing sq_concat", + context=f"sq_concat not defined for {type(self).__name__}", + explanation=f"Dynamo does not yet support concatenating '{self.python_type_name()}' and '{other.python_type_name()}'", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def sq_inplace_concat_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """In-place sequence concatenation via += operator (sq_inplace_concat slot).""" + unimplemented( + gb_type="missing sq_inplace_concat", + context=f"sq_inplace_concat not defined for {type(self).__name__}", + explanation=f"Dynamo does not yet support inplace concat of '{self.python_type_name()}' and '{other.python_type_name()}'", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def call_method( + self, + tx: InstructionTranslatorBase, + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Declarative named-method dispatch (tp_methods). A handler returning + # None declines the call and falls through to the object-protocol + # (tp_slot) dispatch below, mirroring the old super().call_method path. + method = self.lookup_tp_method(name) + if method is not None: + result = method(self, tx, name, args, kwargs) + if result is not None: + return result + + slotdef = self._slotdefs.get(name) + if slotdef is not None: + return slotdef(self, tx, args, kwargs) + + if name == "__hash__" and not args and not kwargs: + from .object_protocol import generic_hash + + return generic_hash(tx, self) + + if name == "__subclasscheck__" and len(args) == 1 and not kwargs: + if (self_py := self.as_python_constant()) and ( + derived_py := args[0].as_python_constant() + ): + if ( + inspect.getattr_static(self_py, "__subclasscheck__", None) + is type.__subclasscheck__ + ): + return variables.ConstantVariable.create( + issubclass(derived_py, self_py) + ) + # __reduce_ex__ is a C builtin (object.__reduce_ex__) that Dynamo + # cannot trace into. Constant-fold it for VTs backed by a real + # Python object so that copy.deepcopy can trace through. + if ( + name == "__reduce_ex__" + and len(args) == 1 + and not kwargs + and self.is_python_constant() + ): + protocol = args[0].as_python_constant() + return VariableTracker.build( + tx, self.as_python_constant().__reduce_ex__(protocol) + ) + + hints = [ + f"Avoid calling `{self.python_type_name()}.{name}` in your code.", + "Please report an issue to PyTorch.", + ] + # additional hint for method calls on improperly constructed iterators + if isinstance(self, variables.UserDefinedObjectVariable) and name in ( + "__iter__", + "__next__", + ): + if isinstance(self.value, (KeysView, ItemsView, ValuesView)): + hints.append( + "Consider moving the creation of dict view object (e.g. `dict.keys()`, `dict.items()`,) " + "to the compiled region, instead of passing it as an input to the compiled region." + ) + hints.append( + "Dynamo does not fully support tracing builtin iterators (e.g. `map`, `zip`, `enumerate`) " + "passed in from uncompiled to compiled regions (e.g. `torch.compile(fn)(enumerate(...))`). " + "This can happen unintentionally if a previous graph break happens with a builtin iterator " + "in the local scope." + ) + hints.append( + "List/dict comprehensions in Python <= 3.11 result in implicit function calls, which Dynamo " + "cannot trace as a top level frame. Possible workarounds are (1) use a loop instead of a comprehension, " + "(2) fix any graph breaks in the function above the comprehension, (3) wrap the comprehension in a " + "function, or (4) use Python 3.12+." + ) + unimplemented( + gb_type="Unsupported method call", + context=f"call_method {self} {name} {args} {kwargs}", + explanation=f"Dynamo does not know how to trace method `{name}` of class `{self.python_type_name()}`", + hints=hints, + ) + + def call_tree_map( + self, + tx: InstructionTranslatorBase, + tree_map_fn: UserFunctionVariable, + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + """Performance optimization to implement optree.tree_map faster than tracing it""" + is_leaf_var = tree_map_kwargs.get("is_leaf") + if is_leaf_var is not None and not is_leaf_var.is_constant_none(): + pred_result = is_leaf_var.call_function(tx, [self], {}) + try: + leaf_decision = pred_result.as_python_constant() + except NotImplementedError: + return self._tree_map_fallback( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + ) + if leaf_decision: + return map_fn.call_function(tx, [self, *rest], {}) + + return self.call_tree_map_branch( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + ) + + def call_tree_map_branch( + self, + tx: InstructionTranslatorBase, + tree_map_fn: UserFunctionVariable, + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + """Emulate optree.tree_map without is_leaf/none_is_leaf checks (handled above)""" + return self._tree_map_fallback( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + ) + + def _tree_map_fallback( + self, + tx: InstructionTranslatorBase, + tree_map_fn: UserFunctionVariable, + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + tree_map_fn_copy = tree_map_fn.clone() + tree_map_fn_copy._maybe_call_tree_map_fastpath = lambda *args, **kwargs: None # type: ignore[missing-attribute] + log.debug( + "tree_map fastpath fallback triggered for %s (rest=%s, kwargs=%s)", + self, + rest, + tree_map_kwargs, + ) + return tree_map_fn_copy.call_function( + tx, + [map_fn, self, *rest], + tree_map_kwargs, + ) + + def call_tree_map_with_path( + self, + tx: InstructionTranslatorBase, + tree_map_fn: UserFunctionVariable, + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + keypath: tuple[Any, ...], + ) -> VariableTracker: + """Performance optimization to implement tree_map_with_path faster than tracing it""" + is_leaf_var = tree_map_kwargs.get("is_leaf") + if is_leaf_var is not None and not is_leaf_var.is_constant_none(): + pred_result = is_leaf_var.call_function(tx, [self], {}) + try: + leaf_decision = pred_result.as_python_constant() + except NotImplementedError: + return self._tree_map_with_path_fallback( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + keypath, + ) + if leaf_decision: + keypath_var = variables.TupleVariable( + [VariableTracker.build(tx, k) for k in keypath] + ) + return map_fn.call_function(tx, [keypath_var, self, *rest], {}) + + return self.call_tree_map_with_path_branch( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + keypath, + ) + + def call_tree_map_with_path_branch( + self, + tx: InstructionTranslatorBase, + tree_map_fn: UserFunctionVariable, + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + keypath: tuple[Any, ...], + ) -> VariableTracker: + """Handle tree_map_with_path for leaf nodes (default behavior)""" + keypath_var = variables.TupleVariable( + [VariableTracker.build(tx, k) for k in keypath] + ) + return map_fn.call_function(tx, [keypath_var, self, *rest], {}) + + def _tree_map_with_path_fallback( + self, + tx: InstructionTranslatorBase, + tree_map_fn: UserFunctionVariable, + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + keypath: tuple[Any, ...], + ) -> VariableTracker: + tree_map_fn_copy = tree_map_fn.clone() + tree_map_fn_copy._maybe_call_tree_map_fastpath = lambda *args, **kwargs: None # type: ignore[missing-attribute] + log.debug( + "tree_map_with_path fastpath fallback triggered for %s (rest=%s, kwargs=%s, keypath=%s)", + self, + rest, + tree_map_kwargs, + keypath, + ) + return tree_map_fn_copy.call_function( + tx, + [map_fn, self, *rest], + tree_map_kwargs, + ) + + def set_name_hint(self, name: str) -> None: + pass + + def set_source_location(self, source_location: SourceLocation) -> None: + self.source_location = source_location + + def realize(self) -> VariableTracker: + """Used by LazyVariableTracker to build the real VariableTracker""" + return self + + def unwrap(self) -> VariableTracker: + """Used by LazyVariableTracker to return the real VariableTracker if it already exists""" + return self + + def is_realized(self) -> bool: + """Used by LazyVariableTracker to indicate an unrealized node""" + return True + + def tp_iternext_impl(self, tx: InstructionTranslatorBase) -> VariableTracker: + """ + Implements tp_iternext slot semantics. + Subclasses override this to support next(). Reaching this base is a + bug — it means tp_iternext is missing for that VariableTracker subclass. + """ + unimplemented( + gb_type="Missing tp_iternext", + context=f"next({self.python_type_name()})", + explanation=( + f"Dynamo does not support next() on {self.python_type_name()}." + " Add tp_iternext_impl to this VariableTracker subclass." + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def next_variable(self, tx: InstructionTranslatorBase) -> VariableTracker: + return self.tp_iternext_impl(tx) + + def is_strict_mode(self, tx: InstructionTranslatorBase) -> bool: + return bool(tx.strict_checks_fn and tx.strict_checks_fn(self)) + + def is_mutable(self) -> bool: + """Whether Dynamo allows mutation on this variable.""" + return not self.is_immutable() + + def is_immutable(self) -> bool: + """Whether Dynamo bans mutation on this variable.""" + return self.mutation_type is None + + @staticmethod + def build( + tx: InstructionTranslatorBase, + value: Any, + source: Source | None = None, + realize: bool = False, + ) -> Any: + """Create a new VariableTracker from a value and optional Source""" + if source is None: + return builder.SourcelessBuilder.create(tx, value) + elif realize: + return builder.VariableBuilder(tx, source)(value) + elif type(value) in variables.LazyConstantVariable.supported_types: + # Use LazyConstantVariable for primitives to enable deferred + # guard installation - constants that are just passed through + # won't cause recompilation when their values change. + return variables.LazyConstantVariable.create(value, source) + else: + return variables.LazyVariableTracker.create(value, source, tx=tx) + + def get_id(self, tx: InstructionTranslatorBase) -> int | None: + """Return id() of the underlying Python object, or None if unavailable. + + The base implementation uses source resolution for sourceful VTs. + Subclasses override for special cases (e.g. NNModuleVariable uses + get_submodule, ConstantVariable handles singletons). + + Returns None for sourceless VTs — callers use FakeIdVariable in + that case (see generic_id in object_protocol.py). + """ + if self.source: + return id(tx.output.resolve_source_value(self.source)) + return None + + def get_id_guard_type(self) -> Callable[..., Any] | None: + if self.source: + return GuardBuilder.ID_MATCH + return None + + def get_real_python_backed_value(self) -> object: + """Return the Python object this VT wraps, for `is` comparison. + + Returns NO_SUCH_SUBOBJ if no concrete Python object is available. + """ + + try: + return self.as_python_constant() + except NotImplementedError: + return NO_SUCH_SUBOBJ + + def nb_index_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + """Mirrors CPython's PyNumber_Index / nb_index slot. + + https://github.com/python/cpython/blob/c09ccd9c429/Objects/abstract.c#L1411-L1450 + + The base implementation raises TypeError, matching CPython's behavior + when tp_as_number->nb_index is NULL (_PyIndex_Check fails). + """ + raise_observed_exception( + TypeError, + tx, + args=[ + f"'{self.python_type_name()}' object cannot be interpreted as an integer" + ], + ) + + def tp_repr_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + """Mirrors CPython's tp_repr slot. + + https://github.com/python/cpython/blob/v3.13.3/Objects/object.c#L745-L778 + + Called when type_implements_tp_repr returns True for this type. + Subclasses override to provide the actual repr implementation. + """ + unimplemented( + gb_type="tp_repr_impl not implemented", + context=f"{type(self).__name__} has tp_repr slot but no tp_repr_impl override", + explanation=f"The type {self.python_type_name()} has a tp_repr C slot but " + "the corresponding VariableTracker doesn't implement tp_repr_impl.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def tp_str_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + """Dynamo hook for VariableTrackers with dedicated str behavior. + Subclasses override this for the per-type str result; generic_str() + handles dispatch and repr fallback. + """ + unimplemented( + gb_type="tp_str_impl not implemented", + context=f"{type(self).__name__} has no tp_str_impl override for {self.python_type_name()}", + explanation=f"Dynamo does not implement __str__ for {self.python_type_name()} " + f"in {type(self).__name__}.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def nb_int_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + """Mirrors CPython's tp_as_number->nb_int slot. + + Called when type_implements_nb_int returns True for this type. + Subclasses override to provide the actual conversion. + """ + unimplemented( + gb_type="nb_int_impl not implemented", + context=f"{type(self).__name__} has nb_int slot but no nb_int_impl override", + explanation=f"The type {self.python_type_name()} has an nb_int C slot but " + "the corresponding VariableTracker doesn't implement nb_int_impl.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def nb_float_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + """Mirrors CPython's tp_as_number->nb_float slot. + + Called when type_implements_nb_float returns True for this type. + Subclasses override to provide the actual conversion. + """ + unimplemented( + gb_type="nb_float_impl not implemented", + context=f"{type(self).__name__} has nb_float slot but no nb_float_impl override", + explanation=f"The type {self.python_type_name()} has an nb_float C slot but " + "the corresponding VariableTracker doesn't implement nb_float_impl.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def _nb_slot_not_implemented( + self, + tp_slot_name: str, + other: VariableTracker, + reverse: bool = False, + ): + unimplemented( + gb_type="tp_as_number slot not implemented", + context=f"{tp_slot_name}({self.python_type_name()}, {other.python_type_name()}, reverse={reverse})", + explanation=f"The type {self.python_type_name()} does not implement the {tp_slot_name}", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def nb_lshift_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_lshift slot. Default: returns NotImplemented. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__rlshift__`` instead of ``__lshift__``). + """ + return variables.ConstantVariable(NotImplemented) + + def nb_inplace_lshift_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_lshift slot. Default: returns NotImplemented.""" + return variables.ConstantVariable(NotImplemented) + + def nb_rshift_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_rshift slot. Default: returns NotImplemented. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__rrshift__`` instead of ``__rshift__``). + """ + return variables.ConstantVariable(NotImplemented) + + def nb_inplace_rshift_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_rshift slot. Default: returns NotImplemented.""" + return variables.ConstantVariable(NotImplemented) + + def nb_and_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_and slot. Default: returns NotImplemented. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__rand__`` instead of ``__and__``). + """ + return variables.ConstantVariable(NotImplemented) + + def nb_inplace_and_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_and slot. Default: returns NotImplemented.""" + return variables.ConstantVariable(NotImplemented) + + def nb_xor_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_xor slot. Default: returns NotImplemented. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__rxor__`` instead of ``__xor__``). + """ + return variables.ConstantVariable(NotImplemented) + + def nb_inplace_xor_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_xor slot. Default: returns NotImplemented.""" + return variables.ConstantVariable(NotImplemented) + + def nb_floor_divide_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_floor_divide slot. Default: returns NotImplemented. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__rfloordiv__`` instead of ``__floordiv__``). + """ + return variables.ConstantVariable(NotImplemented) + + def nb_inplace_floor_divide_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_floor_divide slot. Default: returns NotImplemented.""" + return variables.ConstantVariable(NotImplemented) + + def nb_true_divide_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_true_divide slot. Default: returns NotImplemented. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__rtruediv__`` instead of ``__truediv__``). + """ + return variables.ConstantVariable(NotImplemented) + + def nb_inplace_true_divide_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_true_divide slot. Default: returns NotImplemented.""" + return variables.ConstantVariable(NotImplemented) + + def nb_remainder_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_remainder slot. Default: returns NotImplemented. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__rmod__`` instead of ``__mod__``). + """ + return variables.ConstantVariable(NotImplemented) + + def nb_inplace_remainder_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_remainder slot. Default: returns NotImplemented.""" + return variables.ConstantVariable(NotImplemented) + + def nb_divmod_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_divmod slot. Default: returns NotImplemented. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__rdivmod__`` instead of ``__divmod__``). divmod has no + in-place form. + """ + return variables.ConstantVariable(NotImplemented) + + def nb_power_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + z: VariableTracker | None, + reverse: bool = False, + ) -> VariableTracker: + return variables.ConstantVariable(NotImplemented) + + def nb_power_z_impl( + self, + tx: InstructionTranslatorBase, + v: VariableTracker, + w: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_power slot when self is the modulus (z) operand. + + ``v`` is the base, ``w`` is the exponent, ``self`` is the modulus. + """ + return variables.ConstantVariable(NotImplemented) + + def nb_inplace_power_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + z: VariableTracker | None, + ) -> VariableTracker: + return variables.ConstantVariable(NotImplemented) + + def nb_multiply_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_multiply slot. Default: graph-breaks. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__rmul__`` instead of ``__mul__``). The base default + graph-breaks so unmigrated VTs surface loudly; ``binary_op1`` only + invokes this on types whose CPython type advertises the slot. + """ + return self._nb_slot_not_implemented("nb_multiply_impl", other, reverse=reverse) + + def nb_inplace_multiply_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_multiply slot. Default: graph-breaks.""" + return self._nb_slot_not_implemented("nb_inplace_multiply_impl", other) + + def nb_matrix_multiply_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_matrix_multiply slot. Default: graph-breaks. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__rmatmul__`` instead of ``__matmul__``). + """ + return self._nb_slot_not_implemented( + "nb_matrix_multiply_impl", other, reverse=reverse + ) + + def nb_inplace_matrix_multiply_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_matrix_multiply slot. Default: graph-breaks.""" + return self._nb_slot_not_implemented("nb_inplace_matrix_multiply_impl", other) + + def sq_repeat_impl( + self, + tx: InstructionTranslatorBase, + count: VariableTracker, + ) -> VariableTracker: + """tp_as_sequence->sq_repeat slot. + + Implements sequence repetition (e.g. ``[1, 2] * 3``). ``count`` is + an int VariableTracker already produced by ``nb_index_impl``. + """ + unimplemented( + gb_type="sq_repeat_impl not implemented", + context=f"{type(self).__name__} has sq_repeat slot but no sq_repeat_impl override", + explanation=f"The type {self.python_type_name()} has an sq_repeat C slot but " + "the corresponding VariableTracker doesn't implement sq_repeat_impl.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def sq_inplace_repeat_impl( + self, + tx: InstructionTranslatorBase, + count: VariableTracker, + ) -> VariableTracker: + """tp_as_sequence->sq_inplace_repeat slot.""" + unimplemented( + gb_type="sq_inplace_repeat_impl not implemented", + context=f"{type(self).__name__} has sq_inplace_repeat slot but no sq_inplace_repeat_impl override", + explanation=f"The type {self.python_type_name()} has an sq_inplace_repeat C slot but " + "the corresponding VariableTracker doesn't implement sq_inplace_repeat_impl.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def nb_or_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_or slot. Default: returns NotImplemented. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__ror__`` instead of ``__or__``). + """ + return variables.ConstantVariable(NotImplemented) + + def nb_inplace_or_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_or slot. Default: returns NotImplemented.""" + return variables.ConstantVariable(NotImplemented) + + def nb_negative_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + """Mirrors CPython's tp_as_number->nb_negative slot. + + Called when type_implements_nb_negative returns True for this type. + Subclasses override to provide the actual negation. + """ + unimplemented( + gb_type="nb_negative_impl not implemented", + context=f"{type(self).__name__} has nb_negative slot but no nb_negative_impl override", + explanation=f"The type {self.python_type_name()} has an nb_negative C slot but " + "the corresponding VariableTracker doesn't implement nb_negative_impl.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def nb_positive_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + """Mirrors CPython's tp_as_number->nb_positive slot. + + Called when type_implements_nb_positive returns True for this type. + Subclasses override to provide the actual positive. + """ + unimplemented( + gb_type="nb_positive_impl not implemented", + context=f"{type(self).__name__} has nb_positive slot but no nb_positive_impl override", + explanation=f"The type {self.python_type_name()} has an nb_positive C slot but " + "the corresponding VariableTracker doesn't implement nb_positive_impl.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def nb_add_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_add slot. Default: graph break. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__radd__`` instead of ``__add__``). + """ + # We need to return NotImplemented here because of sq_concat + return variables.ConstantVariable(NotImplemented) + + def nb_inplace_add_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_add slot. Default: graph break.""" + # We need to return NotImplemented here because of sq_inplace_concat + return variables.ConstantVariable(NotImplemented) + + def nb_subtract_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + """tp_as_number->nb_subtract slot. Default: graph break. + + ``reverse=True`` means self is the right-hand operand (CPython would + look up ``__rsub__`` instead of ``__sub__``). + """ + return variables.ConstantVariable(NotImplemented) + + def nb_inplace_subtract_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + ) -> VariableTracker: + """tp_as_number->nb_inplace_subtract slot. Default: graph break.""" + return variables.ConstantVariable(NotImplemented) + + def nb_absolute_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + """Mirrors CPython's tp_as_number->nb_absolute slot. + + Called when type_implements_nb_absolute returns True for this type. + Subclasses override to provide the actual absolute value. + """ + unimplemented( + gb_type="nb_absolute_impl not implemented", + context=f"{type(self).__name__} has nb_absolute slot but no nb_absolute_impl override", + explanation=f"The type {self.python_type_name()} has an nb_absolute C slot but " + "the corresponding VariableTracker doesn't implement nb_absolute_impl.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def nb_invert_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + """Mirrors CPython's tp_as_number->nb_invert slot. + + Called when type_implements_nb_invert returns True for this type. + Subclasses override to provide the actual bitwise inversion. + """ + unimplemented( + gb_type="nb_invert_impl not implemented", + context=f"{type(self).__name__} has nb_invert slot but no nb_invert_impl override", + explanation=f"The type {self.python_type_name()} has an nb_invert C slot but " + "the corresponding VariableTracker doesn't implement nb_invert_impl.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def __init__( + self, + *, + source: Source | None = None, + mutation_type: MutationType | None = None, + source_location: SourceLocation | None = None, + dict_vt: variables.DunderDictVariable | None = None, + ) -> None: + super().__init__() + self.source = source + self.source_location = source_location + self.mutation_type = mutation_type + # Carried so clone() round-trips the cached __dict__ view. + self.dict_vt = dict_vt + + # NOTE sometimes mutation_type is set afterwards for implementation + # convenience, we don't validate those cases at the moment. + if mutation_type is not None: + if isinstance(mutation_type, (ValueMutationNew, AttributeMutationNew)): + # If this fails, it's either + # 1. one mistakenly passed in a source + # 2. `mutation_type` is incorrect + if source is not None: + raise AssertionError( + "source must be None for ValueMutationNew/AttributeMutationNew" + ) + else: + if not isinstance( + mutation_type, (ValueMutationExisting, AttributeMutationExisting) + ): + raise AssertionError( + f"Expected ValueMutationExisting or AttributeMutationExisting, " + f"got {type(mutation_type)}" + ) + # If this fails, it's either + # 1. one forgot to pass in a source + # 2. `mutation_type` is incorrect + if source is None: + raise AssertionError( + "source must not be None for ValueMutationExisting/AttributeMutationExisting" + ) + + @property + def tp_type(self) -> PyTypeObject: + return _tp_type(maybe_get_python_type(self)) + + @property + def tp_as_number(self) -> PyNumberMethods: + return _tp_type(maybe_get_python_type(self)).tp_as_number + + @property + def tp_as_sequence(self) -> PySequenceMethods: + return _tp_type(maybe_get_python_type(self)).tp_as_sequence + + @property + def tp_as_mapping(self) -> PyMappingMethods: + return _tp_type(maybe_get_python_type(self)).tp_as_mapping + + @property + def tp_iter(self) -> Slot | None: + return _tp_type(maybe_get_python_type(self)).tp_iter + + @property + def tp_iternext(self) -> Slot | None: + return _tp_type(maybe_get_python_type(self)).tp_iternext + + @property + def tp_str(self) -> Slot | None: + return _tp_type(maybe_get_python_type(self)).tp_str + + @property + def tp_repr(self) -> Slot | None: + return _tp_type(maybe_get_python_type(self)).tp_repr + + @property + def _slotdefs(self): + return _compute_slotdefs(maybe_get_python_type(self)) + + def __init_subclass__(cls, **kwargs: Any) -> None: + """ + Wraps all subclasses' `as_python_constant` and `reconstruct` so that it cannot be + called twice in the same call chain - i.e. self-referential objects. + For `as_python_constant` - self-referential objects are NOT treated as constants. + For `reconstruct` - we will graph break. The graph break can be avoided if the VT subclass + can generate and cache itself before recursively `reconstruct`ing - see ListVariable for an example. + """ + super().__init_subclass__(**kwargs) + + def as_python_constant_failure(self) -> NoReturn: + raise AsPythonConstantNotImplementedError( + self, msg=f"{self} is self-referential" + ) + + VariableTracker._add_call_once_guard( + cls, "as_python_constant", as_python_constant_failure + ) + + def reconstruct_failure(self) -> NoReturn: + unimplemented( + gb_type="Reconstruction failure (self-referential)", + context=str(self), + explanation=f"Dynamo tried to reconstruct sourceless variable {self}, but it is self-referential. " + "Dynamo must manually implement reconstruction rules for self-referentiable sourceless variables.", + hints=[ + "If Dynamo is attempting to trace a return statement and your code is attempting to return a variable " + "that Dynamo cannot reconstruct, then remove it from the return statement.", + "Remove the self-reference in the variable. A self-referring list, for example, is `l = []; l.append(l)`.", + *graph_break_hints.CAUSED_BY_EARLIER_GRAPH_BREAK, + "Report an issue to PyTorch if you need self-referential reconstrtuction support.", + ], + ) + + VariableTracker._add_call_once_guard(cls, "reconstruct", reconstruct_failure) + + @staticmethod + def _add_call_once_guard( + cls: type[VariableTracker], + method: str, + callback: Callable[[VariableTracker], Any], + ) -> None: + original_method = getattr(cls, method) + + if original_method is getattr(VariableTracker, method) or hasattr( + original_method, "_call_once_guarded" + ): + return + + @functools.wraps(original_method) + def guarded_method(self, *args: Any, **kwargs: Any) -> VariableTracker: + active = _vt_active_calls.get() + if active is None: + active = set() + _vt_active_calls.set(active) + + key = (id(self), id(original_method)) + if key in active: + callback(self) + + active.add(key) + try: + return original_method(self, *args, **kwargs) + finally: + active.discard(key) + + guarded_method._call_once_guarded = True # pyrefly: ignore[missing-attribute] + setattr(cls, method, guarded_method) + + +def typestr(*objs: object) -> str: + if len(objs) == 1: + (obj,) = objs + if isinstance(obj, VariableTracker): + return str(obj) + else: + return type(obj).__name__ + else: + return " ".join(map(typestr, objs)) + + +instancecheck = type.__instancecheck__ + + +_CPYTHON_BASE_URL = "https://github.com/python/cpython/blob/v3.13.0/" + + +def print_cpython_to_vt_mapping() -> None: + """Print the mapping from CPython types to Dynamo VariableTracker classes. + + Reads _cpython_type from each VT subclass (own attribute only, not inherited). + """ + # Ensure all VT modules are imported so all_subclasses is complete + from . import ( # noqa: F401 + builtin, + constant, + ctx_manager, + dicts, + distributed, + functions, + higher_order_ops, + iter, + lazy, + lists, + misc, + nn_module, + streams, + tensor, + torch, + torch_function, + user_defined, + ) + + mapping: dict[type, list[type]] = {} + for vt_cls in VariableTrackerMeta.all_subclasses: + cpython_type = vt_cls.__dict__.get("_cpython_type") + if cpython_type is None: + continue + types = cpython_type if isinstance(cpython_type, tuple) else (cpython_type,) + for t in types: + mapping.setdefault(t, []).append(vt_cls) + + for py_type, vt_classes in sorted(mapping.items(), key=lambda x: x[0].__qualname__): + for vt_cls in vt_classes: + print( + f"{py_type.__module__}.{py_type.__qualname__:30s} -> {vt_cls.__name__}" + ) + + +from . import builder +from .lazy import LazyVariableTracker diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/builder.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..d6514d90222035697e73538b0ea88b4dea4b7e15 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/builder.py @@ -0,0 +1,5374 @@ +""" +This module contains classes and utilities for building variable trackers in Dynamo. +Variable trackers are used to convert Python values into symbolic representations +that can be traced and transformed during graph capture. + +The key classes are: + +- VariableBuilder: Handles source-tracked objects that need guards and proper + reconstruction in the output graph. Used for inputs, module attributes, etc. + +- SourcelessBuilder: Handles ephemeral objects created during tracing that don't + need source tracking or guards. Used for temporary lists, intermediate values, etc. + +Variable trackers enable Dynamo to track the flow of values through the program, +maintain guards for dynamic properties, and reconstruct values in the output graph. +The builders in this module handle converting Python values into appropriate +VariableTracker instances based on their type and usage context. +""" + +import abc +import builtins +import collections +import contextlib +import contextvars +import copy +import dataclasses +import enum +import functools +import importlib.machinery +import inspect +import itertools +import logging +import math +import operator +import random +import re +import sys +import time +import types +import typing +import weakref +from collections.abc import Callable, MutableMapping +from types import ModuleType +from typing import Any, cast, NamedTuple, NoReturn, overload, TYPE_CHECKING, Union + +import sympy + +import torch +from torch import SymInt +from torch._custom_class_base import CustomClassBase +from torch._dispatch.python import enable_python_dispatcher +from torch._dynamo.graph_bytecode_inputs import ( + CURRENT_STREAM_INDEX, + get_external_object_by_index, + register_user_object, +) +from torch._dynamo.utils import ( + get_metrics_context, + is_int_specialization_case, + is_torch_sym, + normalize_count_iter, + set_feature_use, +) +from torch._functorch._aot_autograd.utils import is_async_collective_tensor_type +from torch._guards import TracingContext +from torch._higher_order_ops.flat_apply import flat_apply +from torch._higher_order_ops.torchbind import call_torchbind +from torch._library.opaque_object import ( + is_custom_class, + is_opaque_constant_type, + is_opaque_symbolic_type, + should_hoist, +) +from torch._ops import HigherOrderOperator, OpOverload, OpOverloadPacket +from torch._subclasses.fake_tensor import ( + FakeTensor, + FakeTensorMode, + is_fake, + is_fake_tensor, + maybe_get_fake_mode, +) +from torch._subclasses.meta_utils import is_sparse_any, safe_grad +from torch._utils_internal import justknobs_check +from torch.fx.experimental._backward_state import BackwardState +from torch.fx.experimental._dynamism import normalize_source_name +from torch.fx.experimental.dynamic_spec import ( + DictSpec, + IntermediateSpec, + IntVar, + LeafSpec, + ObjectSpec, + SeqSpec, + ShapesSpec, + TensorSpec, +) +from torch.fx.experimental.sym_node import _DynamicScalar, DynamicInt +from torch.fx.experimental.symbolic_shapes import ( + _constrain_range_for_size, + _nested_int_aware_sort, + _symbolic_context_from_shapes_spec, + _wire_spec_slot, + _wire_tensor_spec_dims, + DimDynamic, + RelaxedUnspecConstraint, + StatefulSymbolicContext, + SubclassSymbolicContext, + SymbolicContext, + SymIntSymbolicContext, + TrackedFake, +) +from torch.fx.immutable_collections import immutable_dict, immutable_list +from torch.nn.utils._expanded_weights import ExpandedWeight +from torch.utils._ordered_set import OrderedSet +from torch.utils._python_dispatch import ( + is_traceable_wrapper_subclass, + is_traceable_wrapper_subclass_type, +) +from torch.utils._sympy.value_ranges import ValueRanges +from torch.utils.weak import TensorWeakRef + +from .. import config, graph_break_hints, mutation_guard, replay_record, trace_rules +from ..device_interface import get_registered_device_interfaces +from ..exc import InternalTorchDynamoError, raise_observed_exception, unimplemented +from ..guards import GuardBuilder, install_guard, make_dupe_guard +from ..pgo import ( + auto_dynamic, + auto_unset, + FrameStateSizeEntry, + InferStride, + process_automatic_dynamic, +) +from ..side_effects import SideEffects +from ..source import ( + AttrProxySource, + AttrSource, + CallMethodItemSource, + ChainedSource, + ConstDictKeySource, + ConvertIntSource, + CurrentStreamSource, + DictGetItemSource, + DictSubclassGetItemSource, + DynamicScalarSource, + FloatTensorSource, + GetItemSource, + GradSource, + is_constant_source, + is_from_closure_source, + is_from_global_source, + is_from_nonlocal_source, + is_from_optimizer_source, + is_from_unspecialized_nn_module_source, + ListGetItemSource, + LocalSource, + NNModuleSource, + NonSerializableSetGetItemSource, + NumpyTensorSource, + OptimizerSource, + RandomValueSource, + SkipGuardSource, + Source, + SubclassAttrListSource, + TupleIteratorGetItemSource, + UnspecializedBuiltinNNModuleSource, + UnspecializedNNModuleSource, + UnspecializedParamBufferSource, + UnwrapCollectiveTensorSource, +) +from ..utils import ( + _extract_tensor_dict, + build_checkpoint_variable, + build_invoke_subgraph_variable, + clone_input, + common_constant_types, + dict_keys, + enumerate_items_with_dict_position, + get_fake_value, + get_locals_to_steal, + get_static_address_type, + is_frozen_dataclass, + is_function, + is_function_or_wrapper, + is_invoke_subgraph, + is_lru_cache_wrapped_function, + is_namedtuple, + is_parameter_freezing, + is_pybind11_enum_member, + is_torch_class, + is_typing, + is_utils_checkpoint, + is_wrapper_or_member_descriptor, + istype, + namedtuple_fields, + odict_values, + proxy_args_kwargs, + range_iterator, + set_base_iter, + set_example_value, + tensor_always_has_static_shape, + tuple_iterator, + tuple_iterator_getitem, + tuple_iterator_len, + unwrap_with_attr_name_if_wrapper, + wrap_fake_exception, +) +from .base import ( + AttributeMutationExisting, + AttributeMutationNew, + typestr, + ValueMutationExisting, + ValueMutationNew, + VariableTracker, + VariableTrackerMeta, +) +from .builtin import BuiltinVariable +from .constant import ConstantVariable +from .ctx_manager import ( + AutocastModeVariable, + CudagraphOverrideVariable, + DynamoConfigPatchVariable, + ErrorOnGraphBreakVariable, + NullContextVariable, + PreserveVersionContextVariable, + RecordFunctionVariable, +) +from .dicts import ConstDictVariable, MappingProxyVariable, OrderedDictVariable +from .distributed import WorldMetaClassVariable +from .functions import ( + BoundBuiltinMethodVariable, + CollectionsNamedTupleFunction, + CollectiveFunctionRewriteVariable, + CreateTMADescriptorExperimentalVariable, + CreateTMADescriptorStableVariable, + FunctoolsPartialVariable, + GetSetDescriptorVariable, + LocalGeneratorFunctionVariable, + MemberDescriptorVariable, + MethodWrapperVariable, + SysFunctionVariable, + TritonKernelVariable, + TritonSetAllocatorVariable, + UserFunctionVariable, + WrapperUserFunctionVariable, +) +from .higher_order_ops import ( + LocalMapWrappedHigherOrderVariable, + TorchHigherOrderOperatorVariable, +) +from .iter import CountIteratorVariable, ItertoolsVariable +from .lazy import LazyConstantVariable, LazyVariableTracker +from .lists import ( + BaseListVariable, + DequeVariable, + ListIteratorVariable, + ListVariable, + RangeVariable, + SizeVariable, + SliceVariable, + TupleIteratorVariable, + TupleVariable, +) +from .memory import CUDAMemPoolVariable +from .misc import ( + AutogradEngineVariable, + AutogradFunctionContextVariable, + AutogradFunctionVariable, + ComptimeVariable, + ConstantLikeVariable, + DebuggingVariable, + DelayGraphBreakVariable, + GetAttrVariable, + IgnoredFunctionVariable, + LambdaVariable, + LoggingLoggerVariable, + NumpyDTypeVariable, + NumpyVariable, + ObjectVariable, + PythonModuleVariable, + RandomClassVariable, + RandomVariable, + SavedTensorBox, + StringFormatVariable, + TypingVariable, + WeakRefVariable, +) + + +if sys.version_info >= (3, 15): + from .misc import SentinelVariable + +from .nn_module import ( + FSDPManagedNNModuleVariable, + UnspecializedBuiltinNNModuleVariable, + UnspecializedNNModuleVariable, +) +from .optimizer import OptimizerVariable +from .script_object import CustomClassObjectVariable, CustomClassVariable +from .sdpa import SDPAParamsVariable +from .sets import ( + DictKeySetVariable, + FrozensetVariable, + OrderedSetClassVariable, + OrderedSetVariable, + SetVariable, +) +from .streams import EventVariable, StreamContextVariable, StreamVariable +from .tensor import ( + NumpyNdarrayVariable, + supported_const_comparison_op_values, + SymNodeVariable, + TensorSpecializedProps, + TensorSubclassVariable, + TensorVariable, + UnspecializedPythonVariable, +) +from .torch import ( + DispatchKeySetVariable, + FuncTorchInterpreterVariable, + TorchCtxManagerClassVariable, + TorchInGraphFunctionVariable, +) +from .torch_function import ( + TensorWithTFOverrideVariable, + torch_function_mode_stack_state_mgr, + TorchFunctionModeVariable, +) +from .user_defined import ( + DefaultDictVariable, + FrozenDataClassVariable, + InspectVariable, + IntWrapperVariable, + KeyedJaggedTensorVariable, + MutableMappingVariable, + SourcelessGraphModuleVariable, + UserDefinedClassVariable, + UserDefinedConstantVariable, + UserDefinedDequeVariable, + UserDefinedDictVariable, + UserDefinedExceptionClassVariable, + UserDefinedListVariable, + UserDefinedObjectVariable, + UserDefinedSetVariable, + UserDefinedTupleVariable, +) + + +try: + import numpy as np +except ModuleNotFoundError: + np: ModuleType = None # type: ignore[assignment] + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + +log = logging.getLogger(__name__) +static_inputs_log = torch._logging.getArtifactLogger( + __name__, "cudagraph_static_inputs" +) +symbolic_shape_log = logging.getLogger("torch.fx.experimental.symbolic_shapes") +from typing import TypeVar + + +# Placeholder for a VariableTracker to be used in proxy +# creation so that we don't type erase +VTTypeAlias = TypeVar("VTTypeAlias") +T = TypeVar("T") + +DimList = list + + +def safe_has_grad(t: object) -> bool: + with torch._logging.hide_warnings(torch._logging._internal.safe_grad_filter): + return hasattr(t, "grad") + + +@dataclasses.dataclass(frozen=True) +class _LocalToken: + """Root token: a top-level function-argument access.""" + + name: str + is_varargs: bool = False + is_varkw: bool = False + + +@dataclasses.dataclass(frozen=True) +class _AttrToken: + """Attribute access (``obj.name``).""" + + name: str + + +@dataclasses.dataclass(frozen=True) +class _SubscriptToken: + """Subscript access (``obj[key]``). + + Emitted for ``dict`` key lookups (matched against ``DictSpec`` entries). + The key may be ``int`` or ``str`` — both are valid dict keys. + """ + + key: int | str + + +_AccessToken = _LocalToken | _AttrToken | _SubscriptToken +_AccessPath = list[_AccessToken] + + +def _format_access_path(tokens: _AccessPath) -> str: + """Format an access path as a Python source-like string for error messages. + + Examples: + [_LocalToken("xs")] -> "xs" + [_LocalToken("cfg"), _SubscriptToken("x")] -> "cfg['x']" + [_LocalToken("m"), _AttrToken("weight")] -> "m.weight" + [_SubscriptToken(0)] -> "[0]" + [_AttrToken("weight")] -> ".weight" + """ + parts: list[str] = [] + for tok in tokens: + match tok: + case _LocalToken(name=name): + parts.append(name) + case _AttrToken(name=name): + parts.append(f".{name}") + case _SubscriptToken(key=key): + parts.append(f"[{key!r}]") + case _: + raise RuntimeError( + f"_format_access_path: unexpected token {tok!r} " + f"of type {type(tok).__name__}" + ) + return "".join(parts) if parts else "" + + +def _source_to_access_path(source: Source) -> _AccessPath | None: + """Translate a dynamo ``Source`` chain into a flat ``_AccessPath``. + + Walks ``source.base`` from leaf to root, then reverses so the path + reads root-first. The returned path always starts with a single + ``_LocalToken`` (the input arg) followed by zero or more access + tokens, each of which is either an ``_AttrToken`` (attribute + access) or a ``_SubscriptToken`` (``dict[key]`` access with an + ``int`` or ``str`` key). + + Returns ``None`` for sources that we know we can't represent them + in shapes specs. + """ + path: list[_AccessToken] = [] + cur: Source = source + while not isinstance(cur, LocalSource): + if isinstance(cur, NNModuleSource): + # ``NNModuleSource`` is a guard-semantics marker, not an + # access step — transparently unwrap. + cur = cur.base + continue + # ``self.weight`` → dynamo emits + # ``DictGetItemSource(UnspecializedParamBufferSource(_, + # '_parameters'), 'weight')``. Collapse that pair into a single + # attr token. + if isinstance(cur, DictGetItemSource) and isinstance( + cur.base, UnspecializedParamBufferSource + ): + path.append(_AttrToken(cur.index)) + cur = cur.base.base + continue + # Plain ``dict[key]`` access. + if isinstance(cur, DictGetItemSource) and isinstance(cur.index, (int, str)): + path.append(_SubscriptToken(cur.index)) + cur = cur.base + continue + # Integer subscript (e.g. *args[i] or list[i]). + if isinstance(cur, GetItemSource) and type(cur.index) is int: + path.append(_SubscriptToken(cur.index)) + cur = cur.base + continue + if isinstance(cur, AttrSource): + path.append(_AttrToken(cur.member)) + cur = cur.base + continue + return None + if not cur.is_input: + return None + path.append( + _LocalToken(cur.local_name, is_varargs=cur.is_varargs, is_varkw=cur.is_varkw) + ) + path.reverse() + return path + + +def _walk_spec( + current_spec: IntermediateSpec, + full_path: _AccessPath, + start_index: int, +) -> LeafSpec: + """Walk down a spec tree starting at ``current_spec``, consuming each + token in ``full_path[start_index:]`` in order. Returns the leaf spec at + the end of the walk, or ``None`` if a key/field along the way wasn't + specified by the user. Raises on type-mismatch. + + ``full_path`` is the original access path (including any prefix already + consumed by the caller before reaching ``current_spec``); ``start_index`` + is the offset in ``full_path`` where the walk begins. + """ + + def _mismatch_error( + at_idx: int, spec: IntermediateSpec, suffix: str = "" + ) -> RuntimeError: + return RuntimeError( + f"shapes_spec walk: while processing source " + f"{_format_access_path(full_path)!r}, at " + f"{_format_access_path(full_path[:at_idx])!r} " + f"the spec is {type(spec).__name__}{suffix}" + ) + + for idx in range(start_index, len(full_path)): + token = full_path[idx] + if current_spec is None: + # Under-specified: a previous descent (DictSpec key lookup or + # ObjectSpec field lookup) returned None because the user didn't + # provide a spec for this entry. Treat as static. + return None + match current_spec: + case ObjectSpec(): + if not isinstance(token, _AttrToken): + raise _mismatch_error(idx, current_spec) + current_spec = current_spec._fields.get(token.name) + case DictSpec(): + if not isinstance(token, _SubscriptToken): + raise _mismatch_error(idx, current_spec) + current_spec = current_spec._entries.get(token.key) + case SeqSpec(): + if not isinstance(token, _SubscriptToken) or not isinstance( + token.key, int + ): + raise _mismatch_error(idx, current_spec) + + if token.key < 0: + raise RuntimeError( + "dynamo should have normalized the index to be non-negative" + ) + # Out-of-range index: unspecified -> treat as static (None), + if token.key < len(current_spec): + current_spec = current_spec._entries[token.key] + else: + current_spec = None + case _: + # leaf spec (TensorSpec / IntVar / int / None) but path still + # has tokens. + raise _mismatch_error( + idx, + current_spec, + ", but the source has further access past it", + ) + if not isinstance(current_spec, LeafSpec): + # The walk consumed all source tokens but landed on a container + # in the source. + raise _mismatch_error( + len(full_path), + current_spec, + ", but the source has no further access past it", + ) + return current_spec + + +def lookup_spec_from_dynamo_source( + source: Source, shapes_spec: ShapesSpec | None +) -> LeafSpec: + """Look up the LeafSpec at the access path derived from ``source`` in ``params``. + Returns ``None`` if the source isn't covered. + """ + if shapes_spec is None or shapes_spec._params is None: + return None + path = _source_to_access_path(source) + if not path or not isinstance(path[0], _LocalToken): + return None + params = shapes_spec._params + root = path[0] + if root.is_varargs: + # ``*args`` element access: root is the varargs local, next token must + # be an int subscript. A varargs local is always followed by a + # subscript token in ``_source_to_access_path``; anything else means + # the chain was mis-tokenized. + if not isinstance(path[1], _SubscriptToken): + raise RuntimeError( + f"Expected _SubscriptToken after *args local at path " + f"{path!r}, got {type(path[1]).__name__}" + ) + key = path[1].key + if type(key) is not int: + raise RuntimeError( + f"Unexpected non-int subscript for *args access at path " + f"{path!r}: {type(key).__name__}({key!r})" + ) + if params._varargs is None or not (0 <= key < len(params._varargs)): + return None + return _walk_spec(params._varargs[key], full_path=path, start_index=2) + if root.is_varkw: + # ``**kwargs`` element access: root is the varkw local, next token must + # be a str subscript. A varkw local is always followed by a subscript + # token in ``_source_to_access_path``; anything else means the chain + # was mis-tokenized. + if not isinstance(path[1], _SubscriptToken): + raise RuntimeError( + f"Expected _SubscriptToken after **kwargs local at path " + f"{path!r}, got {type(path[1]).__name__}" + ) + key = path[1].key + if not isinstance(key, str): + raise RuntimeError( + f"Unexpected non-str subscript for **kwargs access at path " + f"{path!r}: {type(key).__name__}({key!r})" + ) + if params._varkw is None or key not in params._varkw: + return None + + return _walk_spec(params._varkw[key], full_path=path, start_index=2) + # Regular named arg: seed at the named-arg root and descend the rest. + + current_spec: IntermediateSpec = params._named_args.get(root.name) + return _walk_spec(current_spec, full_path=path, start_index=1) + + +def bound_builtin_method_descriptor(value: Any) -> Any | None: + if not isinstance(value, types.BuiltinMethodType): + return None + + method_self = value.__self__ + # BuiltinMethodType also covers module-level C functions like len and + # torch.add. Keep those on the existing function/trace-rule path. + if method_self is None or isinstance(method_self, types.ModuleType): + return None + + # random.Random methods mutate RNG state. Existing random handling either + # records RandomValueSource calls from a RandomVariable, or graph-breaks for + # pre-bound module helpers like random.random. + if isinstance(method_self, random.Random): + return None + + owner = method_self if isinstance(method_self, type) else type(method_self) + + # Torch-internal bound methods already have dedicated Dynamo paths. Do not + # route them through the generic bound-builtin descriptor VT, which changes + # graph break boundaries for calls like Tensor.mul(...). + if is_torch_class(owner): + return None + + # BoundBuiltinMethodVariable needs the descriptor that created this bound + # method. For class-bound methods, look on the class object itself (e.g. + # dict.fromkeys); for instance-bound methods, look on type(self). + return inspect.getattr_static(owner, value.__name__, None) + + +class _missing: + pass + + +@dataclasses.dataclass +class GraphArg: + source: Source | None + # TODO: storing a SymInt here but not a FakeTensor is a pretty strange + # thing to do. Probably should have example (which stores an int) and + # fake_example + _example: Any + # When True, this indicates that this GraphArg is a Python quantity (e.g., + # a float or int) which we pass to the FX graph as a Tensor. This + # controls how we codegen calls into the Dynamo graph: we will call + # torch.as_tensor on the quantity before passing it in. + # + # Note that we typically do not pass dynamic integers as tensors, because + # they will most frequently just be used for size computation. But this + # is a policy decision that we can change our mind on; in particular, when + # an int comes from a random number generator (e.g., random.randint), we + # DO pass it as a tensor. + # + # It's also worth noting that our current tracing rules for + # pass_arg_as_tensor as subtly broken: we just pun the variable as a + # 0d scalar Tensor and pray that the semantics are the same. Which they + # often are, but not necessarily. ezyang(May 2024) plans to fix this + # soon. + pass_arg_as_tensor: bool + fake_tensor: torch._subclasses.fake_tensor.FakeTensor | None + # UnspecializedPythonVariable often masquerades as a tensor. + # We MUST NOT generate shape guard code + # that actually tries to access tensor properties on these values. + # is_tensor lets us tell if this graph arg actually is a tensor + # or not. + is_tensor: bool = True + # Sometimes, the Tensor we pass to example is freshly allocated (smh). + # Then we cannot only keep a weak reference to it. This lets you + # stash a strong reference too. + example_strong_ref: torch.Tensor | torch.SymInt | None = None + + def __setattr__(self, name: str, value: Any) -> None: + # Use object.__setattr__ to bypass Dynamo's STORE_ATTR interception. + # This is needed because when PYTORCH_TEST_WITH_DYNAMO=1, even internal + # GraphArg creation can be traced, and with replay_side_effects=False, + # normal STORE_ATTR bytecode only records mutations without applying them. + object.__setattr__(self, name, value) + + @property + def example(self) -> torch.Tensor | torch.SymInt | BackwardState | None: + if isinstance(self._example, TensorWeakRef): + r = self._example() + if r is None: + raise AssertionError("TensorWeakRef expired unexpectedly") + return r + else: + return self._example + + def __post_init__(self) -> None: + if isinstance(self._example, torch.Tensor): + self._example = TensorWeakRef(self._example) + if not is_fake(self.fake_tensor): + raise AssertionError("fake_tensor must be a FakeTensor") + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.source) + + def reconstruct_pycode(self, codegen) -> str: + if self.source is None: + raise AssertionError( + "Expecting GraphArg to have source during python codegen." + ) + return self.source.reconstruct_pycode(codegen) + + def erase(self) -> None: + self._example = None + self.example_strong_ref = None + + def __eq__(self, other: object) -> bool: + if not isinstance(other, GraphArg): + return False + if self.source is None: + return other.source is None + else: + if other.source is None: + return False + return self.source.name == other.source.name + + +class BackwardStateGraphArg(GraphArg): + def __init__(self) -> None: + super().__init__( + source=None, + _example=BackwardState(), + pass_arg_as_tensor=False, + fake_tensor=None, + is_tensor=False, + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + if not codegen.tx.output.backward_state_var: + raise AssertionError("backward_state_var must be set on output") + codegen.add_push_null( + lambda: codegen.load_import_from(BackwardState.__module__, "BackwardState") + ) + codegen.call_function(0, False) + codegen.dup_top() + codegen.store(codegen.tx.output.backward_state_var) + + +# All class-based iterators in itertools +# NOTE: use id() because some objects are not hashable, it will raise error during lookup +ITERTOOLS_TYPE_IDS: frozenset[int] = frozenset( + id(member) + for name, member in vars(itertools).items() + if not name.startswith("_") and inspect.isclass(member) +) +# Will be updated later in substitute_in_graph in torch/_dynamo/polyfills/itertools.py +ITERTOOLS_POLYFILLED_TYPE_IDS: set[int] = set() + +# Capture fn pointer at import time +# This is to guard against trying to mark the iterated tensors +# as static in case user overrides fn ptr +og_module_named_buffers_fn_ptr = torch.nn.Module.named_buffers +og_module_named_parameters_fn_ptr = torch.nn.Module.named_parameters + + +def _is_dim_dynamic_from_source_dynamism( + source: Source, normalized_source_name: str, dim: int +) -> bool: + if isinstance(source, ChainedSource): + source = source.get_base() + if not isinstance(source, LocalSource) or source.dynamism is None: + return False + + source_dynamism: dict[str, tuple[bool, ...]] = dict( + typing.cast(Any, source.dynamism) + ) + dim_dynamism = source_dynamism.get(normalized_source_name) + return dim_dynamism is not None and dim < len(dim_dynamism) and dim_dynamism[dim] + + +class VariableBuilder: + """Wrap a python value in a VariableTracker() instance""" + + def __init__( + self, + tx: "InstructionTranslatorBase", + source: Source, + allow_lazy_constant: bool = True, + ) -> None: + if source is None: + raise AssertionError( + "Consider SourcelessBuilder for ephemeral objects, usually objects created locally." + ) + if TracingContext.try_get() is None: + raise AssertionError("Expected active TracingContext") + super().__init__() + self.tx = tx + self.source = source + self.name = source.name + # allow_lazy_constant controls whether LazyConstantVariable can be returned + # for int/float/bool/str. Set to False when called from LazyCache.realize() + # to prevent double-wrapping (LazyVariableTracker containing LazyConstantVariable). + self.allow_lazy_constant = allow_lazy_constant + + def __call__(self, value: object) -> VariableTracker: + _t0 = time.time_ns() + try: + return self._call_impl(value) + finally: + self.tx.output.bytecode_tracing_timings.variable_builder_call_ns += ( + time.time_ns() - _t0 + ) + + def _call_impl(self, value: object) -> VariableTracker: + self.tx.output.current_tracer.traced_sources.add(self.source) + if value in self.tx.output.side_effects: + side_effect_result = self.tx.output.side_effects[value] + dup_guard = make_dupe_guard(self.source, side_effect_result.source) + if dup_guard: + self.install_guards(dup_guard) + + if isinstance(value, torch.nn.Module) and isinstance( + side_effect_result, UnspecializedNNModuleVariable + ): + # This means that two nn module instances with different sources + # have the same id. NN modules are somewhat special objects, + # because we have to track their nn_module_stack for ease of + # use. But if we don't do anything, we will just return the + # older variable tracker with the older nn_module_stack. So, + # lets return the old variable tracker but update its + # nn_module_stack + side_effect_result.set_nn_module_stack_source(self.source) + return side_effect_result + + cached_vt = self.tx.output.variable_tracker_cache.get(self.source) + if cached_vt: + # If allow_lazy_constant=False but the cached VT is a lazy variable, + # we need to rebuild to get a non-lazy version. This happens when + # LazyConstantVariable.realize() calls VariableBuilder. + if self.allow_lazy_constant or not isinstance( + cached_vt, LazyVariableTracker + ): + return cached_vt + + vt = self._wrap(value) + + if vt.source is None: + vt.source = self.source + + def _is_deduplicable_sym_variable(value: Any, vt: VariableTracker) -> bool: + # Constants like 0, 1, 2, etc. can be unspecialized as SymNodeVariables sometimes, but we + # should NOT track them. If we use a single SymNodeVariable instance to track them + # across multiple uses, then guards created for one usage will incorrectly apply to + # all other usages of that constant, leading to unnecessary recompilations. + return ( + is_torch_sym(value) or isinstance(value, _DynamicScalar) + ) and isinstance(vt, SymNodeVariable) + + if ( + ( + self._can_lift_attrs_to_inputs(vt) + or _is_deduplicable_sym_variable(value, vt) + ) + and value not in self.tx.output.side_effects + and not is_wrapper_or_member_descriptor(value) + ): + vt = self.tx.output.side_effects.track_object_existing(value, vt) + + # Skip caching for JVP_NESTING source because + # JvpIncrementNestingCtxManagerVariable hides global JVP mutation from + # Dynamo, resulting in stale value. We attempted a fix in + # https://github.com/pytorch/pytorch/pull/174329 but it exposed other + # issues. This only affects cache hit rate, NOT correctness. + if "JVP_NESTING" not in self.source.name: + self.tx.output.variable_tracker_cache[self.source] = vt + return vt + + def _can_lift_attrs_to_inputs(self, vt: VariableTracker) -> bool: + return type(vt) in { + TensorVariable, + TensorWithTFOverrideVariable, + UserDefinedObjectVariable, + NumpyNdarrayVariable, + CustomClassObjectVariable, + } + + def get_source(self) -> Source: + return self.source + + def install_guards(self, *guards: Callable[..., Any]) -> dict[str, Any] | None: + source = self.get_source() + try: + tmp = [source.make_guard(guard) for guard in guards] + except NotImplementedError: + return None + install_guard(*tmp, skip=1) + return {} + + @classmethod + def _type_dispatch(cls) -> dict[object, Callable[..., Any]]: + return cls._type_dispatch_impl(config.trace_numpy) + + @classmethod + @functools.cache + def _type_dispatch_impl(cls, trace_numpy: bool) -> dict[object, Callable[..., Any]]: + # NB: Careful not to close over self to avoid ref cycle from lru_cache + entries = [ + ( + ( + torch.Tensor, + torch.nn.Parameter, + torch._subclasses.FakeTensor, + torch._subclasses.functional_tensor.FunctionalTensor, + ), + cls.wrap_tensor, + ), + ( + (tuple, list, odict_values, collections.deque, torch.Size), + cls.wrap_listlike, + ), + (itertools.count, cls.wrap_itertools_count), + (tuple_iterator, cls.wrap_tuple_iterator), + (range_iterator, cls.wrap_range_iterator), + ((slice, range), cls.wrap_slice_range), + (tuple(common_constant_types), cls.wrap_literal), + ((re.Pattern, re.Match), cls.wrap_regex_pattern), + (weakref.ReferenceType, cls.wrap_weakref), + (torch.utils.hooks.RemovableHandle, cls.wrap_removable_handle), + (torch.jit.ScriptFunction, cls.wrap_jit_function), + (types.MappingProxyType, cls.wrap_mapping_proxy), + ] + + if trace_numpy and np: + # pyrefly: ignore [bad-argument-type] + entries.append((np.ndarray, cls.wrap_numpy_ndarray)) + + # pyrefly: ignore [implicit-any] + result = {} + for ts, fn in entries: + for t in ts if isinstance(ts, tuple) else (ts,): + if t in result: + raise AssertionError(f"Duplicate type dispatch entry for {t}") + result[t] = fn + + return result + + def wrap_regex_pattern( + self, value: re.Pattern[Any] | re.Match[Any] + ) -> ConstantLikeVariable: + # TODO(jansel): something like a REPR_MATCH might be more robust here + self.install_guards(GuardBuilder.ID_MATCH) + return ConstantLikeVariable(value) + + def wrap_weakref(self, value: weakref.ReferenceType[Any]) -> WeakRefVariable: + self.install_guards(GuardBuilder.TYPE_MATCH) + return WeakRefVariable.build(self.tx, value, source=self.source) + + def wrap_removable_handle( + self, value: torch.utils.hooks.RemovableHandle + ) -> NoReturn: + # This means that the removable handle was created in some other frame. + # Our current infra requires the hook to be registered and removed in + # the same frame. So graph break. + # Related test - PYTORCH_TEST_WITH_DYNAMO=1 python test/test_autograd.py -k TestAutograd.test_hooks + unimplemented( + gb_type="Attempted to represent unregistered RemovableHandle", + context="", + explanation="Dynamo attempted to build a representation of a torch.utils.hooks.RemovableHandle, " + "which is not supported. This happens because the RemovableHandle was created in another frame.", + hints=[], + ) + + def wrap_jit_function(self, value: Any) -> WrapperUserFunctionVariable: + if not hasattr(value, "_torchdynamo_inline"): + unimplemented( + gb_type="wrap_jit_function: missing _torchdynamo_inline", + context=f"type: {type(value).__name__}", + explanation="Dynamo expected a JIT function with a _torchdynamo_inline attribute, " + "but the object does not have one.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + self.install_guards(GuardBuilder.TYPE_MATCH) + return WrapperUserFunctionVariable( + value, + "_torchdynamo_inline", + source=self.source, + mutation_type=AttributeMutationExisting(), + ) + + def wrap_mapping_proxy(self, value: Any) -> VariableTracker: + self.install_guards(GuardBuilder.TYPE_MATCH) + # This might be suboptimal compared to dict guards. But mappingproxy is + # not very common, so its ok to guard on all keys. + self.install_guards(GuardBuilder.MAPPING_KEYS_CHECK) + all_const = all(ConstantVariable.is_literal(k) for k in value) + + if not all_const: + unimplemented( + gb_type="non-const keys in mappingproxy", + context=f"non-const keys: {[k for k in value.keys() if not ConstantVariable.is_literal(k)]}", # noqa: SIM118 + explanation="Dynamo expects mappingproxy keys to be constants.", + hints=[ + "Ensure your mappingproxy keys are constants (e.g. int, float, strings)", + ], + ) + + def build_key_value(k: Any, v: Any) -> tuple[VariableTracker, VariableTracker]: + key = ConstantVariable.create(k) + source_key = k + + source_value = GetItemSource(self.get_source(), source_key) + res_value = LazyVariableTracker.create(v, source_value, tx=self.tx) + + return key, res_value + + items = dict(build_key_value(k, v) for k, v in value.items()) + + # Create a dict_vt to be used in the mapping proxy variable + dict_vt = ConstDictVariable(items, source=None) + result = MappingProxyVariable(dict_vt, source=self.source) + return self.tx.output.side_effects.track_mutable(value, result) + + @classmethod + @functools.cache + def _id_dispatch( + cls, + ) -> dict[int, Callable[["VariableBuilder", Any], VariableTracker]]: + from ..comptime import comptime + + entries = [ + (comptime, lambda self, value: ComptimeVariable()), + ( + dataclasses.fields, + lambda self, value: LambdaVariable( + _dataclasses_fields_lambda, + source=self.source, + **self.install_guards(GuardBuilder.CLOSURE_MATCH), + ), + ), + ] + + # pyrefly: ignore [implicit-any] + result = {} + for ts, fn in entries: + for t in ts if isinstance(ts, (tuple, list)) else (ts,): + if t in result: + raise AssertionError(f"Duplicate id dispatch entry for {t}") + result[id(t)] = fn + + return result + + def _wrap(self, value: Any) -> VariableTracker: + # import here to avoid circular dependencies + from torch.utils._triton import ( + has_triton, + has_triton_experimental_host_tma, + has_triton_tensor_descriptor_host_tma, + ) + + from ..decorators import ( + CudagraphOverrideContextManager, + DynamoConfigPatchProxy, + ErrorOnGraphBreakDecoratorContextManager, + ) + + if has_triton(): + from triton.runtime.autotuner import Autotuner + from triton.runtime.jit import JITFunction + else: + + class JITFunction: + pass + + class Autotuner: + pass + + # default implementations, in case we don't have triton (or the wrong triton version) + def create_1d_tma_descriptor() -> None: + pass + + def create_2d_tma_descriptor() -> None: + pass + + class TensorDescriptor: + @staticmethod + def from_tensor() -> None: + pass + + def set_allocator() -> None: + pass + + if has_triton_experimental_host_tma(): + from triton.tools.experimental_descriptor import ( + create_1d_tma_descriptor, + create_2d_tma_descriptor, + ) + if has_triton_tensor_descriptor_host_tma(): + from triton.tools.tensor_descriptor import TensorDescriptor + if has_triton(): + import triton as triton_mod + + if hasattr(triton_mod, "set_allocator"): + set_allocator = triton_mod.set_allocator + + # Handle exact type() match + type_dispatch = self._type_dispatch().get(type(value)) + if type_dispatch is not None: + return type_dispatch(self, value) + + # Handle exact id() match + id_dispatch = self._id_dispatch().get(id(value)) + if id_dispatch is not None: + return id_dispatch(self, value) + + # Everything else (NB: order matters!) + if ( + isinstance(value, torch.Tensor) + and type(value) + not in ( + # These torch-native subclasses have overly restrictive + # `__torch_function__` which prevents Dynamo from reading their + # tensor attributes like `is_nested` or calling methods like + # `_is_view`. + torch.nn.parameter.UninitializedBuffer, + torch.nn.parameter.UninitializedParameter, + ExpandedWeight, + ) + and type(value) not in config.nontraceable_tensor_subclasses + ): + if ( + type(value).__torch_dispatch__ is torch.Tensor.__torch_dispatch__ + or is_traceable_wrapper_subclass(value) + ): + return self.wrap_tensor(value) + + if isinstance(value, torch.profiler.record_function): + self.install_guards(GuardBuilder.ID_MATCH) + return RecordFunctionVariable(value) + if is_namedtuple(value): + self.install_guards(GuardBuilder.SEQUENCE_LENGTH) + output: list[VariableTracker] = [ + LazyVariableTracker.create( + getattr(value, name), + source=AttrSource(self.source, name), + tx=self.tx, + ) + for name in namedtuple_fields(type(value)) + ] + + tuple_vt = TupleVariable( + output, + source=self.source, + mutation_type=ValueMutationExisting(), + ) + result = UserDefinedTupleVariable.get_vt_cls(type(value))( + value, + source=self.source, + tuple_vt=tuple_vt, + ) + return self.tx.output.side_effects.track_object_existing(value, result) + elif istype(value, (dict, collections.defaultdict, collections.OrderedDict)): + self.install_guards(GuardBuilder.TYPE_MATCH) + all_const = all(ConstantVariable.is_literal(k) for k in value) + + # For all_const, we don't have to guard on anything yet. We guard on + # keys lazily by adding a dict_getitem entry for each accessed key. + # For cases where we need to guard on all keys, we lazily put guards + # during the dict call_method (check dicts.py) + if not all_const: + # Guard on the key order + # This is not ideal, i.e., there is no need to guard on the key + # order. But we guard on the key order because of the complexity + # + # 1) For non-constant objects, we can't save the key in the + # guard context because it can be memory heavy. We can add + # weakrefs but this complicates the accesses. + # + # 2) For non-constant objects, we also have to guard on the keys + # (like TENSOR_MATCH on tensor). We might also have guards on + # the attributes of the keys (like tensor.grad). To make this + # work in tree structure is complicated. + # + # So, instead we guard on the key order. While guarding on key + # order, we just save the indices and use it to access keys and + # values. Indices are cheap to save. + self.tx.output.guard_on_key_order.add(self.source) + + # We need all the keys to be hashable. We do this within the + # HashableTracker class in hashable.py + def build_key_value( + i: Any, k: Any, v: Any + ) -> tuple[VariableTracker, VariableTracker]: + base = self.get_source() + if all_const: + key = ConstantVariable.create(k) + source_key = k + else: + source_key = ConstDictKeySource(base, i) + key = LazyVariableTracker.create(k, source_key, tx=self.tx) + source_value = DictGetItemSource(base, source_key) + res_value = LazyVariableTracker.create(v, source_value, tx=self.tx) + + return key, res_value + + result = dict( + build_key_value(i, k, v) + for i, k, v in enumerate_items_with_dict_position(value) + ) + + if istype(value, collections.defaultdict): + factory_source = AttrSource(self.source, "default_factory") + dict_vt = ConstDictVariable( + result, # type: ignore[arg-type] + mutation_type=ValueMutationExisting(), + source=self.source, + ) + result = DefaultDictVariable( + value, + default_factory=VariableBuilder(self.tx, factory_source)( + value.default_factory + ), + dict_vt=dict_vt, + source=self.source, + ) + return self.tx.output.side_effects.track_object_existing(value, result) + elif istype(value, collections.OrderedDict): + result = OrderedDictVariable( + result, # type: ignore[arg-type] + source=self.source, + ) + else: + result = ConstDictVariable( + result, # type: ignore[arg-type] + source=self.source, + ) + + return self.tx.output.side_effects.track_mutable(value, result) + elif isinstance(value, torch.nn.Module): + return self.wrap_module(value) + elif ConstantVariable.is_literal(value): # non-atomic literals + return self.wrap_literal(value) + elif isinstance(value, torch.overrides.TorchFunctionMode): + var = TorchFunctionModeVariable(value, source=self.source) + self.tx.output.side_effects.track_object_existing(value, var) + return var + elif istype(value, (set, OrderedSet)): + if any(isinstance(x, torch.Tensor) for x in value): + unimplemented( + gb_type="Attempted to wrap a set with tensors", + context="Python set containing torch.Tensor elements", + explanation=( + "Dynamo cannot trace sets of tensors. To get a stable ordering, " + "Dynamo needs to convert the set into a list and the order might not be " + "stable if the set contains tensors." + ), + hints=[ + "Use a dictionary where the keys are tensors.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + self.install_guards(GuardBuilder.TYPE_MATCH) + self.install_guards(GuardBuilder.SEQUENCE_LENGTH) + set_var_cls = SetVariable + + if istype(value, OrderedSet): + # Guard on the internal dict of OrderedSet + internal_dict_source = AttrSource(self.source, "_dict") + install_guard( + internal_dict_source.make_guard(GuardBuilder.DICT_KEYS_MATCH) + ) + self.tx.output.guard_on_key_order.add(internal_dict_source) + set_var_cls = OrderedSetVariable + + # The list gives a ordering for the set items. The ordering is based + # on the Python hash and it is not related to object ordering inside + # the set object. The order being incorrect at runtime will lead to + # a recompilation. + L = list(value) if istype(value, OrderedSet) else list(set_base_iter(value)) + items = [ + LazyVariableTracker.create( + v, + source=NonSerializableSetGetItemSource(self.source, i), + tx=self.tx, + ) + for i, v in enumerate(L) + ] + result = set_var_cls(items, source=self.source) + return self.tx.output.side_effects.track_object_existing(value, result) + elif istype(value, frozenset) and all( + ( + # For DBR quantization, we could get a frozenset of torch funcs. + (type(x) is types.BuiltinMethodType and x.__module__ == "torch") + or + # Another commonly used frozenset of types. + x in torch.utils._pytree.BUILTIN_TYPES + or + # For activation checkpointing, we could get a frozenset of torch ops. + isinstance(x, (OpOverload, OpOverloadPacket)) + ) + for x in value + ): + # For the limited cases of frozenset here, we know the items won't + # change across runs, so we can safely create sourceless VTs for + # them and guard on the frozenset contents via EQUALS_MATCH. + # TODO support source for sets and remove the special logics here. + items = [SourcelessBuilder.create(self.tx, v) for v in value] + self.install_guards(GuardBuilder.EQUALS_MATCH) + return FrozensetVariable(items, source=self.source) + elif isinstance( + value, + (enum.Enum, torch.DispatchKey, torch._C._functorch.TransformType), + ) or is_pybind11_enum_member(value): + self.install_guards(GuardBuilder.ID_MATCH) + return UserDefinedObjectVariable(value, source=self.source) + elif DebuggingVariable.is_reorderable_logging_function(value): + # Put this above builtin_callable so that print() can be handled + # along with other builtin debugging functions + self.install_guards(GuardBuilder.BUILTIN_MATCH) + return DebuggingVariable(value, source=self.source) + elif callable(value) and any( + value is fn for fn in torch._dynamo.config.ignore_logging_functions + ): + # Treat ignored functions as full no-ops + self.install_guards(GuardBuilder.ID_MATCH) + return IgnoredFunctionVariable(value, source=self.source) + elif isinstance(value, logging.Logger): + self.install_guards(GuardBuilder.TYPE_MATCH) + return LoggingLoggerVariable(value, source=self.source) + elif is_utils_checkpoint(value): + return build_checkpoint_variable(source=self.source) + elif is_invoke_subgraph(value): + return build_invoke_subgraph_variable(source=self.source) + elif LocalMapWrappedHigherOrderVariable.should_wrap_in_hop(value): + return LocalMapWrappedHigherOrderVariable.build(source=self.source) + elif isinstance(value, functools.partial): + func_src = AttrSource(self.get_source(), "func") + func_obj = VariableBuilder(self.tx, func_src)(value.func) + + args = [] + args_source = AttrSource(self.get_source(), "args") + for i, arg in enumerate(value.args): + args.append( + VariableBuilder(self.tx, GetItemSource(args_source, i))(arg) + ) + + keywords = {} + keywords_source = AttrSource(self.get_source(), "keywords") + for k, v in value.keywords.items(): + if not ConstantVariable.is_literal(k): + unimplemented( + gb_type="functools.partial() with non-literal keyword", + context=f"non-literal keyword: {k}", + explanation="functools.partial() expects literal/string keywords", + hints=[*graph_break_hints.USER_ERROR], + ) + keywords[k] = VariableBuilder( + self.tx, DictGetItemSource(keywords_source, k) + )(v) + + install_guard( + self.get_source().make_guard(GuardBuilder.TYPE_MATCH), + keywords_source.make_guard(GuardBuilder.DICT_KEYS_MATCH), + args_source.make_guard(GuardBuilder.SEQUENCE_LENGTH), + ) + # Preserve cache_hash for SAC context_fn caching + original_cache_hash = getattr(value, "cache_hash", None) + return FunctoolsPartialVariable( + func_obj, args, keywords, original_cache_hash=original_cache_hash + ) + elif is_typing(value): + # typing.List, typing.Mapping, etc. + self.install_guards(GuardBuilder.ID_MATCH) + return TypingVariable( + value, + source=self.source, + ) + elif np is not None and isinstance(value, np.generic): + # numpy array scalars: convert to 0D arrays + return self.wrap_numpy_ndarray(np.asarray(value)) + elif trace_rules.is_numpy(value): + if not np: + raise AssertionError("numpy must be available for numpy tracing") + if istype(value, types.MethodType): + # Don't guard on cython functions as they don't change ids + if inspect.isfunction(value.__func__): + install_guard( + AttrSource(self.source, "__func__").make_guard( + GuardBuilder.CLOSURE_MATCH + ) + ) + elif inspect.isclass(value): + self.install_guards(GuardBuilder.CLASS_MATCH) + elif inspect.isfunction(value): + self.install_guards(GuardBuilder.CLOSURE_MATCH) + elif callable(value): + self.install_guards(GuardBuilder.ID_MATCH) + else: + self.install_guards(GuardBuilder.TYPE_MATCH) + return NumpyVariable(value, source=self.source) + elif trace_rules.is_numpy_dtype(value): + self.install_guards(GuardBuilder.ID_MATCH) + return NumpyDTypeVariable(value, source=self.source) + elif trace_rules.is_numpy_type_info(value): + if isinstance(value, np.iinfo): + self.install_guards(GuardBuilder.TYPE_MATCH) + dt_source = AttrSource(self.source, "dtype") + install_guard(dt_source.make_guard(GuardBuilder.ID_MATCH)) + else: + self.install_guards(GuardBuilder.ID_MATCH) + return ConstantLikeVariable(value, source=self.source) + # NB: These can't be put in type_dispatch, they have to run later + elif CollectiveFunctionRewriteVariable.can_rewrite(value): + self.install_guards(GuardBuilder.CLOSURE_MATCH) + return CollectiveFunctionRewriteVariable.create( + self.tx, + value, + source=self.source, + ) + elif istype(value, torch.autograd.function.FunctionMeta): + self.install_guards(GuardBuilder.CLASS_MATCH) + return AutogradFunctionVariable( + value, + source=self.source, + ) + elif isinstance(value, torch.autograd.function.FunctionCtx): + actual_saved_tensors = None + try: + # type: ignore[attr-defined] + actual_saved_tensors = value.saved_tensors + except RuntimeError: + pass + + saved_tensors = [] + guards = [self.source.make_guard(GuardBuilder.TYPE_MATCH)] + if isinstance(actual_saved_tensors, tuple): + saved_tensors_source = AttrSource(self.source, "saved_tensors") + guards.append( + saved_tensors_source.make_guard(GuardBuilder.SEQUENCE_LENGTH) + ) + for i, v in enumerate(actual_saved_tensors): + saved_tensors.append( + VariableBuilder( + self.tx, GetItemSource(saved_tensors_source, i) + )(v) + ) + install_guard(*guards) + + return self.tx.output.side_effects.track_object_existing( + value, + AutogradFunctionContextVariable( + value, + source=self.source, + saved_tensors=SavedTensorBox(saved_tensors), + ), + ) + elif ( + isinstance(value, types.MethodType) + and istype( + getattr(value, "__self__", None), torch.autograd.function.FunctionMeta + ) + and getattr(value, "__name__", "") == "apply" + and value == getattr(value.__self__, "apply", None) + ): + # handle aliased autograd function `apply` calls + install_guard( + AttrSource(self.get_source(), "__func__").make_guard( + GuardBuilder.CLOSURE_MATCH + ) + ) + return GetAttrVariable( + AutogradFunctionVariable( + value.__self__, + source=AttrSource(self.source, member="__self__"), + ), + "apply", + py_type=type(value), + ) + elif ( + isinstance(value, types.MethodType) + and value.__name__ in ("shuffle", "sample", "seed") + and isinstance(value.__self__, random.Random) + and RandomVariable.is_supported_random_obj(value.__self__) + ): + # Module-level random.shuffle/random.sample/random.seed are methods + # bound to the module-global random.Random instance. The + # scalar-returning helpers (random.random/randint/randrange/uniform) + # already have a dedicated RandomValueSource path in + # UserDefinedObjectVariable; these return sequences or mutate the RNG + # state instead, so route them through RandomVariable to model the + # RNG state rather than skipping into the random module. + random_self = value.__self__ + obj_source = self.source and AttrSource(self.source, "__self__") + obj_vt = VariableTracker.build(self.tx, random_self, obj_source) + return GetAttrVariable(obj_vt, value.__name__, py_type=type(value)) + elif ( + isinstance(value, types.BuiltinMethodType) + and isinstance(value.__self__, random.Random) + and RandomVariable.is_supported_random_obj(value.__self__) + and value in UserDefinedObjectVariable._supported_random_functions() + ): + # Module-level random.random is a C builtin method bound to the + # module-global random.Random instance (unlike randint/randrange/ + # uniform, which are Python-level methods). Route it through + # UserDefinedObjectVariable so its call_random_fn / RandomValueSource + # path models the RNG value instead of skipping into the C builtin. + self.install_guards(GuardBuilder.FUNCTION_MATCH) + return UserDefinedObjectVariable(value, source=self.source) + elif isinstance(value, torch._C._ImperativeEngine): + self.install_guards(GuardBuilder.ID_MATCH) + return AutogradEngineVariable(value, source=self.source) + elif ( + value + is torch._dynamo.external_utils.FakeCompiledAutogradEngine._exec_final_callbacks_stub + ): + self.install_guards(GuardBuilder.CLOSURE_MATCH) + return LambdaVariable( + lambda: UserFunctionVariable( + torch._dynamo.external_utils.FakeCompiledAutogradEngine.exec_final_callbacks, + ).call_function( + self.tx, + [self.tx.output.side_effects.get_ca_final_callbacks_var()], + {}, + ) + ) + elif isinstance(value, DynamoConfigPatchProxy): + return DynamoConfigPatchVariable(value.changes) + elif isinstance(value, ErrorOnGraphBreakDecoratorContextManager): + return ErrorOnGraphBreakVariable(value.error_on_graph_break) + elif isinstance(value, CudagraphOverrideContextManager): + return CudagraphOverrideVariable(value.fwd, value.bwd) + elif callable(value) and trace_rules.lookup_callable(value) is not None: + if trace_rules.is_callable_allowed(value): + self.tx.output.has_user_defined_allowed_in_graph = True + # type: ignore[attr-defined] + return trace_rules.lookup_callable(value).create_with_source( + value, source=self.source + ) + elif np and isinstance(value, np.number): + return self.wrap_unspecialized_primitive(value) + elif isinstance(value, HigherOrderOperator): + if value is torch._higher_order_ops.invoke_subgraph: + unimplemented( + gb_type="Attempted to wrap torch._higher_order_ops.invoke_subgraph", + context="", + explanation="Directly using invoke_subgraph is not supported. Use nested_compile_region", + hints=[], + ) + self.install_guards(GuardBuilder.TYPE_MATCH) + return TorchHigherOrderOperatorVariable.make(value, source=self.source) + elif isinstance(value, torch.cuda.StreamContext): + self.install_guards(GuardBuilder.ID_MATCH) + stream_source = AttrSource(self.source, "stream") + stream_var = VariableBuilder(self.tx, stream_source)(value.stream) + # type: ignore[arg-type] + return StreamContextVariable.create(self.tx, stream_var) + elif isinstance(value, torch.Stream): + self.install_guards(GuardBuilder.TYPE_MATCH) + if isinstance(self.source, CurrentStreamSource): + # Reuse the index pre-allocated in SymbolicStreamState.__init__ + index = CURRENT_STREAM_INDEX + else: + index = register_user_object(value, self.source) + stream_proxy = self.tx.output.create_proxy( + "call_function", get_external_object_by_index, (index,), {} + ) + set_example_value(stream_proxy.node, value) + var = StreamVariable( + stream_proxy, value, source=self.source, user_object_index=index + ) + return self.tx.output.side_effects.track_object_existing(value, var) + elif isinstance(value, torch.cuda.MemPool): + self.install_guards(GuardBuilder.TYPE_MATCH) + index = register_user_object(value, self.source) + mempool_proxy = self.tx.output.create_proxy( + "call_function", get_external_object_by_index, (index,), {} + ) + set_example_value(mempool_proxy.node, value) + var = CUDAMemPoolVariable( + mempool_proxy, value, source=self.source, user_object_index=index + ) + return self.tx.output.side_effects.track_object_existing(value, var) + elif isinstance(value, (torch._C._SDPAParams)): + self.install_guards(GuardBuilder.TYPE_MATCH) + return SDPAParamsVariable.create(self.tx, value, self.source) + elif isinstance(value, torch._functorch.pyfunctorch.FuncTorchInterpreter): + self.install_guards(GuardBuilder.ID_MATCH) + return FuncTorchInterpreterVariable(value) + elif isinstance(value, torch.Event): + self.install_guards(GuardBuilder.TYPE_MATCH) + index = register_user_object(value, self.source) + event_proxy = self.tx.output.create_proxy( + "call_function", + get_external_object_by_index, + (index,), + {}, + ) + set_example_value(event_proxy.node, value) + return EventVariable( + event_proxy, + value, + index, + source=self.source, + ) + elif ( + istype(value, contextlib.nullcontext) + and inspect.getattr_static(value, "enter_result", None) is None + ): + self.install_guards(GuardBuilder.TYPE_MATCH) + return NullContextVariable(source=self.source) + elif KeyedJaggedTensorVariable.is_matching_object(value): + self.install_guards(GuardBuilder.TYPE_MATCH) + result = KeyedJaggedTensorVariable(value, source=self.source) + # TODO: this doing it manually is bad + return self.tx.output.side_effects.track_object_existing(value, result) + elif isinstance(value, torch.optim.Optimizer): + self.install_guards(GuardBuilder.ID_MATCH) + self.source = OptimizerSource(self.source) + return OptimizerVariable( + value, + source=self.source, + mutation_type=AttributeMutationExisting(), + ) + elif isinstance(value, torch.DispatchKeySet): + self.install_guards(GuardBuilder.DISPATCH_KEY_SET_MATCH) + return DispatchKeySetVariable(value) + elif WorldMetaClassVariable.is_group_member_type(value): + return WorldMetaClassVariable(value, source=self.source) + elif value is OrderedSet: + self.install_guards(GuardBuilder.ID_MATCH) + return OrderedSetClassVariable() + elif ( + id(value) in ITERTOOLS_TYPE_IDS + and id(value) not in ITERTOOLS_POLYFILLED_TYPE_IDS + ): + self.install_guards(GuardBuilder.CLASS_MATCH) + return ItertoolsVariable(value, source=self.source) + elif isinstance(value, _DynamicScalar): + is_int = isinstance(value, DynamicInt) + source = DynamicScalarSource(self.source, is_int) + if id(value) in self.tx.output.root_tracer.dynamic_scalar_nodes: + # If we've already seen this dynamic scalar, reuse the existing + # SymInt/SymFloat node. + node = self.tx.output.root_tracer.dynamic_scalar_nodes[id(value)] + else: + sym = self.tx.output.shape_env.create_unspecified_symbol( + value.real, # type: ignore[attr-defined] + source=source, + dynamic_dim=DimDynamic.DYNAMIC, + ) + node = self.tx.output.shape_env.create_symintnode( + sym, + hint=value.real, # type: ignore[attr-defined] + source=source, + ) + if not isinstance(node, SymInt): + raise AssertionError(f"Expected SymInt, got {type(node)}") + + # Bind to graph input + sym_node_proxy = self.tx.output.root_tracer.create_graph_input( + re.sub(r"[^a-zA-Z0-9]+", "_", self.name), + type(node), + node, + source=source, + ) + sym_node_proxy.node.meta["grapharg"] = GraphArg( + source, + node, + False, + None, + is_tensor=False, + example_strong_ref=node, + ) + sym_expr = node.node.expr + if not isinstance(sym_expr, sympy.Symbol): + raise AssertionError(f"{sym_expr} is not a basic Symbol.") + self.tx.output.tracked_fakes.append(TrackedFake(node, source, None)) + return SymNodeVariable.create(self.tx, sym_node_proxy, node) + elif is_torch_sym(value): + # Note: this doesn't handle nested symints. + # For SymBool input, we reuse the infra for SymInt by simulating SymBool with a SymInt in dynamo. + + # Concretely, + # 1. We create a SymInt in dynamo's shape_env, whose source is constructed as ConvertIntSource(self.source). + # so that guards on the SymInts can be effectively applied on the original SymBool in user program. + # 2. We create a SymBool based on the SymInt in dynamo's ShapeEnv. Because the original user program + # depends on the value being a SymBool. This allows dynamo to interpret the user's program correctly. + source = ( + self.source + if isinstance(value, torch.SymInt) + else ConvertIntSource(self.source) + ) + new_symint = None + if value.node.has_hint(): + new_symint = ( + self.tx.output.shape_env.create_unspecified_symint_and_symbol( + int(value.node.hint), # type: ignore[bad-argument-type] + source, + dynamic_dim=DimDynamic.DYNAMIC, + ) + ) + else: + if isinstance(value, torch.SymBool): + # We need to create an unbacked symint to replace the unbacked symbool. + new_symint = self.tx.output.shape_env.create_unbacked_symint() + else: + shape_env = self.tx.output.shape_env + if not torch.compiler._is_non_strict_tracing(): + # TODO: Need to enable this for Dynamo after broader + # verification. See + # test_raw_unbacked_symint_input_graph_breaks_outside_non_strict. + unimplemented( + gb_type="Attempted to wrap unbacked SymInt", + context="", + explanation="Unbacked SymInt input is not supported yet.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + if value.node.shape_env is shape_env: + # SymInt already belongs to this ShapeEnv; no + # transfer needed, reuse it directly. + new_symint = value + else: + new_expr = shape_env._transfer_foreign_expr_as_unbacked( + value, source=source + ) + new_symint = shape_env.create_symintnode( + new_expr, hint=None, source=source + ) + if new_symint is None: + raise AssertionError("new_symint must not be None after wrapping") + if not isinstance(new_symint, SymInt): + raise AssertionError(f"Expected SymInt, got {type(new_symint)}") + sym_node_proxy = self.tx.output.root_tracer.create_graph_input( + re.sub(r"[^a-zA-Z0-9]+", "_", self.name), + type(new_symint), + new_symint, + source=source, + ) + + sym_node_proxy.node.meta["grapharg"] = GraphArg( + source, + new_symint, + False, + None, + is_tensor=False, + example_strong_ref=new_symint, + ) + sym_expr = new_symint.node.expr + if isinstance(sym_expr, sympy.Symbol): + self.tx.output.tracked_fakes.append( + TrackedFake(new_symint, source, None) + ) + + tracing_symint = ( + new_symint if isinstance(value, torch.SymInt) else new_symint == 1 + ) # cast it back to symbool for tracing + return SymNodeVariable(sym_node_proxy, tracing_symint) + + elif isinstance(value, (JITFunction, Autotuner)): + self.install_guards(GuardBuilder.ID_MATCH) + return TritonKernelVariable( + value, + None, # No kernel idx provided + None, # No grid provided + source=self.source, + ) + elif value is create_1d_tma_descriptor: + return CreateTMADescriptorExperimentalVariable(rank=1) + elif value is create_2d_tma_descriptor: + return CreateTMADescriptorExperimentalVariable(rank=2) + elif value is TensorDescriptor.from_tensor: + return CreateTMADescriptorStableVariable() + elif value is set_allocator: + return TritonSetAllocatorVariable(value) + elif isinstance(value, torch.amp.autocast_mode.autocast): + if isinstance(value, torch.amp.autocast_mode._UnmanagedAutocast): + return self.wrap_user_defined(value) + else: + self.install_guards(GuardBuilder.ID_MATCH) + return AutocastModeVariable( + target_values=[ + value.device, + value.fast_dtype, + value._enabled, + value._cache_enabled, + ], + source=self.source, + ) + elif TorchCtxManagerClassVariable.is_matching_cls(value): + if inspect.isclass(value): + self.install_guards(GuardBuilder.CLASS_MATCH) + elif inspect.isfunction(value): + self.install_guards(GuardBuilder.CLOSURE_MATCH) + return TorchCtxManagerClassVariable(value, source=self.source) + elif inspect.getattr_static(value, "__script_if_tracing_wrapper", False): + self.install_guards(GuardBuilder.TYPE_MATCH) + return WrapperUserFunctionVariable( + value, + "__original_fn", + source=self.source, + mutation_type=AttributeMutationExisting(), + ) + elif is_lru_cache_wrapped_function(value): + self.install_guards(GuardBuilder.TYPE_MATCH) + return WrapperUserFunctionVariable( + value, + "__wrapped__", + source=self.source, + mutation_type=AttributeMutationExisting(), + ) + elif value is sys.exc_info or ( + sys.version_info >= (3, 11) and value is sys.exception + ): + return SysFunctionVariable(value, source=self.source) + elif is_function_or_wrapper(value) and inspect.getattr_static( + value, "_torchdynamo_inline", False + ): + self.install_guards(GuardBuilder.TYPE_MATCH) + return WrapperUserFunctionVariable( + value, + "_torchdynamo_inline", + source=self.source, + mutation_type=AttributeMutationExisting(), + ) + elif value is collections.namedtuple: + self.install_guards(GuardBuilder.ID_MATCH) + return CollectionsNamedTupleFunction(value, source=self.source) + elif (descriptor := bound_builtin_method_descriptor(value)) is not None: + self.install_guards(GuardBuilder.ID_MATCH) + method_self = value.__self__ + obj_source = self.source and AttrSource(self.source, "__self__") + obj_vt = VariableTracker.build(self.tx, method_self, obj_source) + return BoundBuiltinMethodVariable(descriptor, obj_vt, source=self.source) + elif is_function(value) and value in (float.fromhex, float.hex): + self.install_guards(GuardBuilder.ID_MATCH) + return GetAttrVariable( + BuiltinVariable(float, source=self.source), + value.__name__, + py_type=type(value), + ) + elif is_function_or_wrapper(value): + value, attr_name = unwrap_with_attr_name_if_wrapper(value) + # For these wrappers, Dynamo points to the wrapped function, + # so source needs to be updated as well. + if attr_name is not None: + self.source = AttrSource(self.source, attr_name) + # type: ignore[attr-defined] + return trace_rules.lookup(value).create_with_source( + value, source=self.source + ) + elif value is random.Random: + self.install_guards(GuardBuilder.ID_MATCH) + return RandomClassVariable(source=self.source) + elif istype(value, random.Random) and RandomVariable.is_supported_random_obj( + value + ): + self.install_guards(GuardBuilder.TYPE_MATCH) + result = RandomVariable(value, source=self.source) + self.tx.output.side_effects.track_mutable(value, result) + return result + # Don't use istype, since some python modules are not subclasses of types.ModuleType directly. + # E.g, type(torch.ops) -> , + # type(torch.backends.cudnn) -> + elif isinstance(value, (types.ModuleType, replay_record.DummyModule)): + from torch.utils import _config_module + + if isinstance(value, _config_module.ConfigModule): + self.install_guards(GuardBuilder.MODULE_MATCH) + return UserDefinedObjectVariable(value, source=self.source) + self.install_guards(GuardBuilder.MODULE_MATCH) + result = PythonModuleVariable( + # type: ignore[arg-type] + value, + source=self.source, + ) + self.tx.output.side_effects.track_object_existing(value, result) + return result + elif ( + istype(value, types.GeneratorType) + and inspect.getgeneratorstate(value) == inspect.GEN_CREATED + ): + self.install_guards(GuardBuilder.ID_MATCH) + code = value.gi_code + frame = value.gi_frame + if frame is None: + raise AssertionError("GEN_CREATED implies a live frame") + frame_locals = frame.f_locals + closure = tuple(types.CellType(frame_locals[n]) for n in code.co_freevars) + fn = types.FunctionType(code, frame.f_globals, closure=closure) + args = [ + VariableTracker.build(self.tx, frame_locals[n]) + for n in code.co_varnames[: code.co_argcount] + ] + genfn = LocalGeneratorFunctionVariable(VariableTracker.build(self.tx, fn)) + return genfn.call_function(self.tx, args, {}) + elif isinstance(value, contextvars.ContextVar): + from .misc import ContextVarVariable + + self.install_guards(GuardBuilder.ID_MATCH) + return ContextVarVariable( + cv_obj=value, + source=self.source, + ) + elif isinstance(value, types.GetSetDescriptorType): + # GetSet descriptors are C functions attached to an attribute lookup + # using PyGetSetDef. Python, on attribute lookup, can decide to + # create a new object on the fly, and therefore the `id` of the + # descriptors is not guaranteed to be same for different attribute + # accesses. Since these are unlikely to change during the program + # execution, we can skip guarding on them. + return GetSetDescriptorVariable(value) + elif isinstance(value, types.MemberDescriptorType): + return MemberDescriptorVariable(value) + elif isinstance(value, types.MethodWrapperType): + # Method-wrappers are written in C, and they are not guaranteed to + # return the same object on attribute lookup. Therefore, we cannot + # insert a ID_MATCH guard here. method-wrappers are very + # unlikely to change, so its ok to skip the guard here. + descriptor = inspect.getattr_static(type(value.__self__), value.__name__) + if not isinstance(descriptor, types.WrapperDescriptorType): + raise AssertionError( + f"expected WrapperDescriptorType, got {type(descriptor)}" + ) + obj_source = self.source and AttrSource(self.source, "__self__") + obj_vt = VariableTracker.build(self.tx, value.__self__, obj_source) + return MethodWrapperVariable(descriptor, obj_vt) + elif issubclass(type(value), type) and issubclass(value, BaseException): + # match user defined exceptions + self.install_guards(GuardBuilder.ID_MATCH) + return UserDefinedExceptionClassVariable(value) + elif issubclass(type(value), type): + if value in ( + torch.utils.hooks.BackwardHook, + torch.nn.Parameter, + torch.nn.Buffer, + torch.backends.cuda.SDPAParams, + ): + # TODO(jansel): combine this case with the one above + # type: ignore[attr-defined] + return trace_rules.lookup(value).create_with_source( + value, source=self.source + ) + if value is torch.autograd._unsafe_preserve_version_counter: + self.install_guards(GuardBuilder.CLASS_MATCH) + return PreserveVersionContextVariable.constructor(self.tx) + if ( + # `value` must be a strict subclass of `torch.Tensor` + issubclass(value, torch.Tensor) + and value is not torch.Tensor + # `TensorSubclassVariable` is not for subclass that overrides + # `torch_dispatch`. + and value.__torch_dispatch__ is torch.Tensor.__torch_dispatch__ + # `TensorSubclassVariable` would lead to construction of + # `TensorWithTFOverrideVariable`, but we don't want that for + # traceable wrapper subclasses (we wrap those subclass instances + # into `TensorVariable`). + and not is_traceable_wrapper_subclass_type(value) + ): + return TensorSubclassVariable(value, source=self.source) + + if not is_from_closure_source(self.source): + # For closure source, the variable comes from LOAD_SUPER_ATTR, + # which calls self.__class__. This is internal Cpython + # implementation, and it is rare for the user to modify + # self.__class__ manually. + # For other cases, this is a userdefined class, so install an + # ID_MATCH even if its a global variable. + self.install_guards(GuardBuilder.CLASS_MATCH) + + if isinstance(value, type) and issubclass(value, enum.Enum): + return UserDefinedClassVariable( + value, + source=self.source, + ) + + if is_custom_class(value): + return CustomClassVariable( + value, + source=self.source, + ) + + result = UserDefinedClassVariable( + value, + source=self.source, + ) + + # Only track user-defined classes for mutation, not torch + # internals. Tracking torch classes (e.g. RemovableHandle) causes + # side effects like next_id increments to be replayed incorrectly, + # and source chains through C-level descriptors break guard + # evaluation. + mod = getattr(value, "__module__", None) or "" + if mod != "torch" and not mod.startswith(("torch.", "torch_")): + if value not in self.tx.output.side_effects: + return self.tx.output.side_effects.track_object_existing( + value, result + ) + return result + + elif type(value) is torch._C.Generator: + # Generator is registered as an opaque reference type for make_fx + # tracing, but in dynamo we handle it as a regular object so that + # trace_rules-based graph breaks (e.g. initial_seed, manual_seed) + # work gracefully — allowing dynamo to compile code before and + # after the generator call. CustomClassObjectVariable's tp_getattro_impl + # and call_method are decorated with @_raise_hard_error_if_graph_break, + # which turns any graph break into a hard error that falls back to + # eager for the entire function. Generator methods intentionally + # graph-break (they mutate/read RNG state), so they need the + # UserDefinedObjectVariable path which supports graceful graph breaks. + return self.wrap_user_defined(value) + elif CustomClassObjectVariable.is_matching_cls(type(value)): + from ..source import ( + FlattenScriptObjectSource, + ScriptObjectQualifiedNameSource, + ) + + # Unwrap FakeScriptObject to the underlying real object so the + # rest of this branch (guards, graph inputs, etc.) operates on + # the real opaque object type. + if isinstance(value, torch._library.fake_class_registry.FakeScriptObject): + value = value.real_obj + + # type: ignore[arg-type] + if torch._library.fake_class_registry.tracing_with_real(value): + proxy = self.tx.output.root_tracer.create_graph_input( + re.sub(r"[^a-zA-Z0-9]+", "_", self.name), + type(value), + value, + source=self.source, + ) + + # setting is_unspecialized=False to not insert a as_tensor call in reconstruct by default + # setting example to be real value because these example values will be used + # as example_inputs for user compiler. + proxy.node.meta["grapharg"] = GraphArg( + self.source, + value, + False, + None, + False, + value, # type: ignore[arg-type] + ) + return CustomClassObjectVariable.create( + proxy, + value, + source=self.source, + tx=self.tx, + ) + + if is_opaque_constant_type(type(value)): + # Value-type: guard on equality (will use __eq__) + self.install_guards(GuardBuilder.CONSTANT_MATCH) + elif is_opaque_symbolic_type(type(value)): + # Symbolic-type: guard only on type, and registered guard_fn. + # Use FAKE_SCRIPT_TYPE_MATCH because at runtime the source may + # resolve to either a FakeScriptObject (during outer + # AOTAutograd tracing) or the underlying real opaque object. + self.install_guards(GuardBuilder.FAKE_SCRIPT_TYPE_MATCH) + self.install_guards(GuardBuilder.OPAQUE_OBJ_GUARD_FN_MATCH) + elif not hasattr(value, "__obj_flatten__"): + # This exists to allow a smoother transition. + # The implications are: + # The script objects won't be tracked as proxies. + # Methods on these objects won't show up in the graph. + # The original script object might be mutated. + return self.wrap_user_defined(value) + else: + # Install the guards on the fully qualified name of the script object + LazyVariableTracker.realize_all( + VariableBuilder( + self.tx, ScriptObjectQualifiedNameSource(self.source) + )( + value._type().qualified_name() # type: ignore[attr-defined] + ) + ) + # Install the guards on the content of the script object by setting the source + # to be FlattenScriptObjectSource, which calls __obj_flatten__() to get the contents. + LazyVariableTracker.realize_all( + VariableBuilder(self.tx, FlattenScriptObjectSource(self.source))( + value.__obj_flatten__() + ) + ) + + fake_script_obj = torch._library.fake_class_registry.maybe_to_fake_obj( + self.tx.output.fake_mode, value + ) + if is_opaque_constant_type(type(value)) and not should_hoist(type(value)): + fake_script_obj = value + proxy = value + + elif config.install_free_tensors and ( + is_from_global_source(self.source) + or is_from_nonlocal_source(self.source) + or is_from_unspecialized_nn_module_source(self.source) + ): + return self.tx.output.register_attr_or_module( + value, self.name, source=self.source + ) + + else: + proxy = self.tx.output.root_tracer.create_graph_input( + re.sub(r"[^a-zA-Z0-9]+", "_", self.name), + type(value), + fake_script_obj, + source=self.source, + ) + # setting is_unspecialized=False to not insert a as_tensor call in reconstruct by default + # setting example to be real value because these example values will be used + # as example_inputs for user compiler. + proxy.node.meta["grapharg"] = GraphArg( + self.source, + value, # type: ignore[arg-type] + False, + None, + False, + fake_script_obj, # type: ignore[arg-type] + ) + + return CustomClassObjectVariable.create( + proxy, # pyrefly: ignore[bad-argument-type] + fake_script_obj, + source=self.source, + tx=self.tx, + ) + elif ( + isinstance(value, (dict, collections.OrderedDict)) + and type(value).__new__ is dict.__new__ + ): + # Construct a dict_vt that will reside inside the UserDefinedDictVariable + self.install_guards(GuardBuilder.TYPE_MATCH) + self.install_guards(GuardBuilder.SEQUENCE_LENGTH) + + # Guard on the key order + self.tx.output.guard_on_key_order.add(self.source) + + # We need all the keys to be hashable. We do this within the + # HashableTracker class in hashable.py + def build_key_value( + i: Any, k: Any, v: Any + ) -> tuple[VariableTracker, VariableTracker]: + base = self.get_source() + source_key = ConstDictKeySource(base, i) + key = LazyVariableTracker.create(k, source_key, tx=self.tx) + + source_value = DictSubclassGetItemSource(base, source_key) + res_value = LazyVariableTracker.create(v, source_value, tx=self.tx) + + return key, res_value + + result = dict( + build_key_value(i, k, v) + for i, k, v in enumerate_items_with_dict_position(value) + ) + + dict_vt_cls = ( + OrderedDictVariable + if isinstance(value, collections.OrderedDict) + else ConstDictVariable + ) + dict_vt = dict_vt_cls( + result, + mutation_type=ValueMutationExisting(), + source=self.source, + ) + # Force this to reconstruct on mutation to keep the reconstruction + # bytecode simple + dict_vt.should_reconstruct_all = True + + result = UserDefinedDictVariable(value, dict_vt=dict_vt, source=self.source) + return self.tx.output.side_effects.track_object_existing(value, result) + elif isinstance(value, tuple): + self.install_guards(GuardBuilder.TYPE_MATCH) + self.install_guards(GuardBuilder.SEQUENCE_LENGTH) + + # NB - Be careful in not triggering user code. Guards also work on + # the underlying tuple data structure. + output = [ + LazyVariableTracker.create( + tuple.__getitem__(value, i), + source=GetItemSource(self.get_source(), i), + tx=self.tx, + ) + for i in range(tuple.__len__(value)) + ] + + tuple_vt = TupleVariable( + output, # type: ignore[arg-type] + source=self.source, + mutation_type=ValueMutationExisting(), + ) + result = UserDefinedTupleVariable( + value, tuple_vt=tuple_vt, source=self.source + ) + return self.tx.output.side_effects.track_object_existing(value, result) + elif isinstance(value, list): + self.install_guards(GuardBuilder.TYPE_MATCH) + self.install_guards(GuardBuilder.SEQUENCE_LENGTH) + + # NB - Be careful in not triggering user code. Guards also work on + # the underlying list data structure. + output = [ + LazyVariableTracker.create( + list.__getitem__(value, i), + source=ListGetItemSource(self.get_source(), i), + tx=self.tx, + ) + for i in range(list.__len__(value)) + ] + list_vt = ListVariable( + output, # type: ignore[arg-type] + source=self.source, + mutation_type=ValueMutationExisting(), + ) + result = UserDefinedListVariable(value, list_vt=list_vt, source=self.source) + return self.tx.output.side_effects.track_object_existing(value, result) + elif isinstance(value, collections.deque): + self.install_guards(GuardBuilder.TYPE_MATCH) + self.install_guards(GuardBuilder.SEQUENCE_LENGTH) + # maxlen is baked into the DequeVariable as a constant, so guard on + # it to recompile if a same-typed deque with a different maxlen + # appears. + install_guard( + AttrSource(self.source, "maxlen").make_guard(GuardBuilder.EQUALS_MATCH) + ) + + output = [ + LazyVariableTracker.create( + collections.deque.__getitem__(value, i), + source=GetItemSource(self.get_source(), i), + tx=self.tx, + ) + for i in range(collections.deque.__len__(value)) + ] + deque_vt = DequeVariable( + output, # type: ignore[arg-type] + maxlen=ConstantVariable.create(value.maxlen), + source=self.source, + mutation_type=ValueMutationExisting(), + ) + result = UserDefinedDequeVariable( + value, deque_vt=deque_vt, source=self.source + ) + return self.tx.output.side_effects.track_object_existing(value, result) + elif isinstance(value, (set, frozenset)): + self.install_guards(GuardBuilder.TYPE_MATCH) + self.install_guards(GuardBuilder.SEQUENCE_LENGTH) + + L = list(set_base_iter(value)) + output = [ + LazyVariableTracker.create( + list.__getitem__(L, i), + source=NonSerializableSetGetItemSource(self.get_source(), i), + tx=self.tx, + ) + for i in range(list.__len__(L)) + ] + if isinstance(value, set): + set_vt_cls = SetVariable + else: + if not isinstance(value, frozenset): + raise AssertionError(f"Expected frozenset, got {type(value)}") + set_vt_cls = FrozensetVariable + + set_vt = set_vt_cls( + output, source=self.source, mutation_type=ValueMutationExisting() + ) + result = UserDefinedSetVariable(value, set_vt=set_vt, source=self.source) + return self.tx.output.side_effects.track_object_existing(value, result) + elif issubclass(type(value), MutableMapping): + self.install_guards(GuardBuilder.TYPE_MATCH) + result = MutableMappingVariable(value, source=self.source) + return self.tx.output.side_effects.track_object_existing(value, result) + elif is_frozen_dataclass(value): + self.install_guards(GuardBuilder.TYPE_MATCH) + result = FrozenDataClassVariable(value, source=self.source) + return self.tx.output.side_effects.track_object_existing(value, result) + elif isinstance(value, dict_keys): + if all(ConstantVariable.is_literal(k) for k in value): + # If the dict_keys object is passed from outside the compile region, it must either be passed along with + # the corresponding dict object or treated as a set (when only the keys are passed into the compiled region). + # - If it is passed along with the dict, the dict object itself is already guarded. + # - If only the dict_keys object is passed, we add EQUALS_MATCH and SEQUENCE_LENGTH guards + # to ensure it remains unchanged across multiple runs. + items = [SourcelessBuilder.create(self.tx, v) for v in value] + install_guard( + self.get_source().make_guard(GuardBuilder.SEQUENCE_LENGTH), + self.get_source().make_guard(GuardBuilder.EQUALS_MATCH), + ) + return DictKeySetVariable(items, source=self.source) + else: + unimplemented( + gb_type="non-const keys in dict_keys", + context=f"non-const keys: {[k for k in value if not ConstantVariable.is_literal(k)]}", + explanation="Dynamo expects dict_keys keys to be constants.", + hints=[ + "Ensure your dict_keys keys are constants (e.g. int, float, strings)", + ], + ) + elif IntWrapperVariable.is_matching_object(value): + from torch.export.dynamic_shapes import _DimHintType + + if value.dynamism is None or value.dynamism.type == _DimHintType.STATIC: + return self.wrap_symint(value.val) + elif value.dynamism.type == _DimHintType.DYNAMIC: + log.debug( + "%s marked %s via IntWrapper", + self.source.name, + DimDynamic.DYNAMIC, + ) + return self.wrap_symint( + value.val, + dynamism=DimDynamic.DYNAMIC, + context=SymIntSymbolicContext( + constraint=RelaxedUnspecConstraint(warn_only=False) + ), + ) + elif value.dynamism.type == _DimHintType.AUTO: + log.debug( + "%s marked %s via IntWrapper", + self.source.name, + DimDynamic.DYNAMIC, + ) + return self.wrap_symint(value.val, dynamism=DimDynamic.DYNAMIC) + else: + raise RuntimeError(f"Undefined dynamism {value.dynamism}") + elif istype(value, object): + self.install_guards(GuardBuilder.TYPE_MATCH) + return ObjectVariable(value, source=self.source) + elif ( + sys.version_info >= (3, 15) + and type(value) is builtins.sentinel # pyrefly: ignore [missing-attribute] + ): + self.install_guards(GuardBuilder.ID_MATCH) + return SentinelVariable(value, source=self.source) + else: + return self.wrap_user_defined(value) + + def wrap_user_defined(self, value: Any) -> VariableTracker: + from .ctx_manager import GenericContextWrappingVariable + from .user_defined import _CONSTANT_BASE_TYPES, is_generic_ctx_manager_cls + + self.install_guards(GuardBuilder.TYPE_MATCH) + if InspectVariable.is_matching_object(value): + # Skip guards on inspect related variable trackers because they are + # not important for recompiles (something else will also change to + # cause recompiles) and can cause a large number of OBJECT_ALIASING + # guards. + result = InspectVariable(value, source=SkipGuardSource(self.source)) + elif ( + isinstance(value, _CONSTANT_BASE_TYPES) + and type(value) not in common_constant_types + ): + self.install_guards(GuardBuilder.CONSTANT_SUBCLASS_MATCH) + result = UserDefinedConstantVariable(value, source=self.source) + elif is_generic_ctx_manager_cls(type(value)): + # A generic context manager built inside the compiled region (via + # SideEffects.get_variable_cls) must wrap the same way when it is + # reconstructed from a source across a graph break, so a `with` on + # the reconstructed object can still be entered. + result = GenericContextWrappingVariable(value, source=self.source) + else: + result = UserDefinedObjectVariable(value, source=self.source) + if not SideEffects.cls_supports_mutation_side_effects(type(value)): + # don't allow STORE_ATTR mutation with custom __setattr__ + return result + return self.tx.output.side_effects.track_object_existing(value, result) + + def wrap_listlike( + self, value: Union[tuple[Any, ...], list[Any], odict_values, NamedTuple] + ) -> VariableTracker: + if config.specialize_int and type(value) is torch.Size: + self.install_guards(GuardBuilder.CONSTANT_MATCH) + return ConstantVariable.create(value=value) + + # One can index a tensor with a list/tuple. Therefore, we need to + # have a stricter match. + self.install_guards(GuardBuilder.SEQUENCE_LENGTH) + + # Tuples are immutable objects, so we should mark its items static. This + # avoids wrapping of tuple items as symints. This helps for nn module + # attributes like conv2d strides, dilations. + if ( + istype(value, tuple) + and all(ConstantVariable.is_literal(item) for item in value) + and self.source.guard_source.is_unspecialized_nn_module() + ): + self.install_guards(GuardBuilder.CONSTANT_MATCH) + return TupleVariable([ConstantVariable.create(item) for item in value]) + + output = [ + LazyVariableTracker.create( + item, + source=GetItemSource(self.get_source(), i), + tx=self.tx, + ) + for i, item in enumerate(value) + ] + + maybe_gm = self.tx.output.local_scope.get("self") + if isinstance( + self.source, LocalSource + ) and self.source.local_name in get_locals_to_steal(maybe_gm): + # The input tensor list to dynamo from compiled autograd may contain activations + # which are freed as they are used in inductor. Dynamo's default behavior is to + # lift all tensors to the graph inputs, but this will cause dynamo to hold an + # extra reference to the activation tensors and increase peak memory usage. + # To allow freeing ASAP, we keep the list as graph argument to the dynamo output + # graph, and unpack it locally. + # e.g. instead of `def forward(self, L_inputs_0_, L_inputs_1_, ...):`, we have + # `def forward(self, L_inputs_):` + source = self.source + if not isinstance(value, list): + raise AssertionError(f"Expected list for steal_arg, got {type(value)}") + tensor_list_proxy = self.tx.output.root_tracer.create_graph_input( + re.sub(r"[^a-zA-Z0-9]+", "_", self.name), + type(value), + value, + source=source, + ) + tensor_list_proxy.node.meta["steal_arg"] = True + + list_variable = wrap_fx_proxy_cls( + target_cls=TensorVariable, + tx=self.tx, + proxy=tensor_list_proxy, + example_value=value, + subclass_type=None, + source=source, + ) + + # Apply relevant logic from `VariableTracker.build(value[i])` + # (except for the `create_graph_input` stuff). + guards = [] + # type: ignore[attr-defined] + for i, tensor_variable in enumerate(list_variable.items): + source_i = GetItemSource(base=source, index=i, index_is_slice=False) + # access unpacked tensor from this list instead of from a lifted arg + self.tx.output.input_source_to_var[source_i] = tensor_variable + tensor_variable.proxy.node.meta["tensor_dict"] = _extract_tensor_dict( + value[i] + ) + guard = functools.partial( + GuardBuilder.TENSOR_MATCH, value=TensorWeakRef(value[i]) + ) + guards.append(source_i.make_guard(guard)) + + install_guard(*guards, skip=1) + + grapharg = GraphArg( + source, + value, + pass_arg_as_tensor=False, + fake_tensor=None, + is_tensor=False, + ) + tensor_list_proxy.node.meta["grapharg"] = grapharg + + # The following is very important for maintaining the "python object + # <==> variable tracker" 1-to-1 mapping, which is mainly handled via + # `side_effects`. Note that constructing `tensor_variable` above + # already adds it to graph arg, but we never registered it with + # `side_effects`. The preemptive `realize` calls here basically + # does that registration (at the end of `self.__call__`). + # + # A slightly cleaner alternative is to register the + # `tensor_variable`s above with `side_effects` directly, and just + # return the `list_variable`, but that breaks some tensor-subclass + # related tests like `test_inputs_aliasing_bytecode_stack_restore`, + # because `tensor_variable` is constructed via + # `handle_traced_output`, which doesn't really expect/handle tensor + # subclass. + # + # Eventually, we expect to fix remove all of these by having Dynamo + # auto-boxing inputs to the compiled graph, see + # https://github.com/pytorch/pytorch/issues/153701. + for vt in output: + vt.realize() + # type: ignore[arg-type] + result = BaseListVariable.cls_for_instance(value)(output, source=self.source) + if istype(value, (list, collections.deque)): + return self.tx.output.side_effects.track_mutable(value, result) + return result + + def wrap_tuple_iterator(self, value: tuple_iterator) -> VariableTracker: + self.install_guards(GuardBuilder.TUPLE_ITERATOR_LEN) + output = [ + VariableBuilder(self.tx, TupleIteratorGetItemSource(self.get_source(), i))( + tuple_iterator_getitem(value, i) + ) + for i in range(tuple_iterator_len(value)) + ] + result = TupleIteratorVariable(output, source=self.source) + return self.tx.output.side_effects.track_mutable(value, result) + + def wrap_range_iterator(self, value: range_iterator) -> VariableTracker: + self.install_guards(GuardBuilder.RANGE_ITERATOR_MATCH) + # Get all the values from the range iterator; no need to install guards + # on items since `RANGE_ITERATOR_MATCH` guarantees the same items. + items: list[VariableTracker] = [ + ConstantVariable.create(v) for v in copy.deepcopy(value) + ] + result = ListIteratorVariable(items, source=self.source) + return self.tx.output.side_effects.track_mutable(value, result) + + def wrap_itertools_count(self, value: Any) -> VariableTracker: + current_item, step = normalize_count_iter(value) + if not ( + ConstantVariable.is_literal(current_item) + and ConstantVariable.is_literal(step) + ): + return self.wrap_user_defined(value) + + self.install_guards(GuardBuilder.COUNT_ITERATOR_MATCH) + result = CountIteratorVariable( + ConstantVariable.create(current_item), + ConstantVariable.create(step), + source=self.source, + ) + return self.tx.output.side_effects.track_mutable(value, result) + + def wrap_slice_range(self, value: slice | range) -> SliceVariable | RangeVariable: + items = [ + VariableBuilder(self.tx, AttrSource(self.get_source(), k))( + getattr(value, k) + ) + for k in ("start", "stop", "step") + ] + self.install_guards(GuardBuilder.TYPE_MATCH) + if isinstance(value, slice): + return SliceVariable(items, self.tx, source=self.source) + else: + return RangeVariable(items, source=self.source) + + def mark_static_input(self, value: torch.Tensor, guard: bool) -> None: + from ..decorators import mark_static_address + + static_inputs_log.debug( + "Marking static input %s, id: %s)", self.source.name, id(value) + ) + mark_static_address(value, guard=guard) + + # Check if we've seen this tensor before and update graph metadata if needed + # As long as this runs before AOT this is sound + if value in self.tx.output.side_effects: + var = self.tx.output.side_effects[value] + # A tensor-subclass parameter (e.g. under torch.nn.utils.parametrize) + # can be tracked as a UserDefinedObjectVariable, which has no graph + # proxy node to annotate. mark_static_address above still marks it, + # so only stamp the metadata when there is a real tensor proxy node. + if isinstance(var, TensorVariable): + var.proxy.node.meta["tensor_dict"]["_dynamo_static_input_type"] = ( + value._dynamo_static_input_type # type: ignore[attr-defined] + ) + + def wrap_module(self, value: torch.nn.Module) -> VariableTracker: + from ..eval_frame import OptimizedModule + + if len(value.__dict__) == 0: + unimplemented( + gb_type="Uninitialized nn.Module", + context=typestr(value), + explanation=f"Attempted to trace an uninitialized nn.Module of type {typestr(value)}.", + hints=[ + *graph_break_hints.USER_ERROR, + "Ensure your nn.Module instance has called `super().__init__()`.", + ], + ) + if istype(value, OptimizedModule): + # Check if the optimized module was disabled + if inspect.getattr_static(value.forward, "_torchdynamo_disable", False): + # This bytecode is mostly of kind LOAD_ATTR or LOAD_METHOD. If + # we graph break here, Dynamo does not know how to create + # continuation functions for such bytecodes. So, we delay the + # graph break to CALL_FUNCTION. + msg = inspect.getattr_static( + value.forward, "_torchdynamo_disable_msg", None + ) + return DelayGraphBreakVariable( + source=self.source, + msg=f"Optimized `nn.Module` is wrapped with `torch.compiler.disable` (reason: {msg})", + ) + + self.install_guards(GuardBuilder.TYPE_MATCH) + self.source = AttrSource(self.source, "_orig_mod") + return self.wrap_module(value._orig_mod) + + if type(value) is torch.jit._script.RecursiveScriptModule: + unimplemented( + gb_type="torch.jit.script/freeze modules unsupported", + context=str(value), + explanation="Dynamo does not support tracing into torch.jit.script or " + "torch.jit.freeze modules because they execute in the TorchScript " + "runtime, not Python. Replace the ScriptModule submodule with the " + "original eager nn.Module.", + hints=[ + *graph_break_hints.FUNDAMENTAL, + ], + ) + + if ( + isinstance(value, (torch.nn.RNN, torch.nn.GRU, torch.nn.LSTM)) + and not config.allow_rnn + ): + unimplemented( + gb_type="Attempted to wrap RNN, GRU, or LSTM", + context=str(value), + explanation="Dynamo does not support RNN, GRU, or LSTM.", + hints=[ + "Set torch._dynamo.config.allow_rnn=True to enable experimental support for RNN, GRU, and LSTM in Dynamo", + *graph_break_hints.SUPPORTABLE, + ], + ) + + if inspect.getattr_static(value, "_is_fsdp_managed_module", False): + # See note [Dynamo treats FSDP wrapped modules as UnspecializedNNModule] + # in fully_sharded_data_parallel.py for more information + + # we can't do this assert inside FSDP constructor, + # since we don't know yet whether dynamo will be used + if not inspect.getattr_static(value, "_fsdp_use_orig_params", False): + unimplemented( + gb_type="FSDP with use_orig_params=False", + context="", + explanation="Dynamo only supports FSDP with use_orig_params=True", + hints=[], + ) + + # Note on FSDP guarding + # Eager FSDP already assumes (requires, but without enforcement) + # that users don't mutate their model parameters/structure after + # FSDP wrapping, because FSDP wouldn't notice or update its + # FlatParams. + # + # Therefore, torch.compile can skip guarding on params or submodule + # structure of fsdp_managed modules, by using FSDPNNModuleSource as + # the guard source. This behavior is gated on + # config.skip_fsdp_guards. + self.install_guards(GuardBuilder.TYPE_MATCH) + result = FSDPManagedNNModuleVariable(value, source=self.get_source()) + if not SideEffects.cls_supports_mutation_side_effects(type(value)): + # don't allow STORE_ATTR mutation with custom __setattr__ + return result + return self.tx.output.side_effects.track_object_existing(value, result) + elif mutation_guard.is_dynamic_nn_module(value, self.tx.export): + # created dynamically, don't specialize on it + + # Note [Tracing a torch.compiled function] + # when make_fx tracing a compiled function, we need + if isinstance(value, torch.fx.experimental.proxy_tensor._AttrProxy): + # type: ignore[attr-defined] + value = value.get_base() + self.source = AttrProxySource(self.source) + + freezing = is_parameter_freezing() + + # Guard against the case where user may overwrite named parameters + # / named buffers + # NOTE: This is not likely to happen but worth guarding to avoid + # exception + if ( + callable(value.named_parameters) + # type: ignore[attr-defined] + and value.named_parameters.__func__ is og_module_named_parameters_fn_ptr + ): + try: # catch TypeErrors in named_parameters() from unserializable nn modules + # type: ignore[attr-defined] + for _, p in value.named_parameters(): + self.mark_static_input(p, guard=freezing) + except TypeError as e: + raise_observed_exception(type(e), self.tx, args=list(e.args)) + + if ( + callable(value.named_buffers) + # type: ignore[attr-defined] + and value.named_buffers.__func__ is og_module_named_buffers_fn_ptr + ): + try: # catch TypeErrors in named_parameters() from unserializable nn modules + # type: ignore[attr-defined] + for _, b in value.named_buffers(): + self.mark_static_input(b, guard=freezing) + except TypeError as e: + raise_observed_exception(type(e), self.tx, args=list(e.args)) + + if freezing: + # we need to add the module to tracing context + # in order to allow its params to get invalidated + # this will get cleaned up once compile ends + self.tx.output.nn_modules[self.name] = value + + if ( + value.__module__.startswith(("torch.nn.modules", "torch.ao.")) + and not value.__module__.startswith("torch.nn.modules.container") + ) or getattr(value.__class__, "_dynamo_marked_static", False): + new_source = self.source + if not self.tx.output.export or config.install_free_tensors: + new_source = UnspecializedBuiltinNNModuleSource(self.source) + result = UnspecializedBuiltinNNModuleVariable(value, source=new_source) + install_guard(new_source.make_guard(GuardBuilder.TYPE_MATCH)) + else: + new_source = self.source + if not self.tx.output.export or config.install_free_tensors: + new_source = UnspecializedNNModuleSource(self.source) + result = UnspecializedNNModuleVariable(value, source=new_source) + install_guard(new_source.make_guard(GuardBuilder.TYPE_MATCH)) + + self.tx.output.add_fqn_info_for_inlined_modules(value, self.source) + + if not SideEffects.cls_supports_mutation_side_effects(type(value)): + # don't allow STORE_ATTR mutation with custom __setattr__ + return result + return self.tx.output.side_effects.track_object_existing(value, result) + elif issubclass( + value.__class__, torch.nn.parallel.distributed.DistributedDataParallel + ): + self.install_guards(GuardBuilder.TYPE_MATCH) + return UnspecializedNNModuleVariable(value, source=self.get_source()) + else: + return self.tx.output.register_attr_or_module( + value, + self.name, + source=self.get_source(), + # Guards are added inside register_attr_or_module + ) + + def wrap_literal(self, value: object) -> VariableTracker: + # NOTE: DynamicInt (subclass of int) and SymInt inputs never reach here + # because ConstantVariable.is_literal() rejects non-exact types. + # They are handled later in __call__ and always treated as dynamic. + if type(value) is int: + # Check for user-provided spec from shapes_spec. + if config._dynamic_shapes_spec is not None: + int_spec = lookup_spec_from_dynamo_source( + self.source, config._dynamic_shapes_spec + ) + if int_spec is None: + # shapes_spec is set but this int has no spec → force static + self.install_guards(GuardBuilder.CONSTANT_MATCH) + return ConstantVariable.create(value=value, source=self.source) + elif isinstance(int_spec, int): + # Explicit static value — verify the actual matches. + if value != int_spec: + raise ValueError( + f"shapes_spec declared {self.source.name} as static " + f"with value {int_spec}, but got {value} at trace time" + ) + self.install_guards(GuardBuilder.CONSTANT_MATCH) + return ConstantVariable.create(value=value, source=self.source) + elif isinstance(int_spec, (IntVar, torch.SymInt)): + result = self.wrap_symint(value, dynamism=DimDynamic.UNBACKED) + sym_val = result.sym_num # type: ignore[attr-defined] + _wire_spec_slot(int_spec, sym_val) + return result + else: + raise ValueError( + f"shapes_spec for {self.source.name}: unexpected value " + f"{int_spec!r} (expected int, IntVar, or None)" + ) + + if is_dynamic_source(self.source.name): + log.debug( + "%s marked dynamic via dynamic-sources list", self.source.name + ) + return self.wrap_symint(value, dynamism=DimDynamic.DYNAMIC) + + if is_dynamic_value(value): + log.debug( + "%s marked dynamic via dynamic-values list (value=%s)", + self.source.name, + value, + ) + return self.wrap_symint(value, dynamism=DimDynamic.DYNAMIC) + + if is_unbacked_source(self.source.name): + log.debug( + "%s marked unbacked via unbacked-sources list", self.source.name + ) + return self.wrap_symint(value, dynamism=DimDynamic.UNBACKED) + + if not config.specialize_int: + # unspecializing int by default, but still + # specialize for the following conditions + if is_int_specialization_case(value, self.source): + recompile_hint = None + if ( + self.source.guard_source.is_unspecialized_builtin_nn_module() + or self.source.guard_source.is_unspecialized_nn_module() + ): + # This means that it is an integer from a NN module. + # Dynamo considers nn module int attributes to be static + # (a good heuristic). But a user might want to mark the + # int attribute to be a symint, so track this integer + # for recompilation later. + recompile_hint = ( + "torch.compile considers integer attributes of the nn.Module to be static. " + "If you are observing recompilation, you might want to make this integer dynamic " + "using torch._dynamo.config.allow_unspec_int_on_nn_module = True, or convert this " + "integer into a tensor." + ) + + process_automatic_dynamic( + self.tx, + self.source.name, + FrameStateSizeEntry.make_scalar(value), + is_unspecialized_nn_module=self.source.guard_source.is_unspecialized_nn_module(), + ) + self.install_guards( + functools.partial( + GuardBuilder.EQUALS_MATCH, recompile_hint=recompile_hint + ) + ) + return ConstantVariable.create(value=value, source=self.source) + + return self._wrap_lazy_constant(value, self._wrap_symint_for_lazy) + + return self._wrap_lazy_constant(value) + elif type(value) is float: + if not isinstance(value, float): + raise AssertionError(f"Expected float, got {type(value)}") + if not config.specialize_float: + return self._wrap_lazy_constant(value, self._wrap_symfloat_for_lazy) + + return self._wrap_lazy_constant(value) + elif type(value) in (bool, str): + if not isinstance(value, (bool, str)): + raise AssertionError(f"Expected bool or str, got {type(value)}") + return self._wrap_lazy_constant(value) + else: + self.install_guards(GuardBuilder.CONSTANT_MATCH) + result = ConstantVariable.create(value=value, source=self.source) + if isinstance(value, (list, set)): + return self.tx.output.side_effects.track_mutable(value, result) + return result + + def _wrap_symint_for_lazy(self, value: int) -> VariableTracker: + return self.wrap_symint(value) + + def _wrap_symfloat_for_lazy(self, value: float) -> VariableTracker: + return self.wrap_symfloat(value) + + @overload + def _wrap_lazy_constant( + self, + value: int, + wrap_fn: Callable[[int], VariableTracker], + ) -> VariableTracker: ... + + @overload + def _wrap_lazy_constant( + self, + value: float, + wrap_fn: Callable[[float], VariableTracker], + ) -> VariableTracker: ... + + @overload + def _wrap_lazy_constant( + self, + value: int | float | bool | str, + wrap_fn: None = None, + ) -> VariableTracker: ... + + def _wrap_lazy_constant( + self, + value: int | float | bool | str, + wrap_fn: Callable[[Any], VariableTracker] | None = None, + ) -> VariableTracker: + """Wrap a primitive constant, deferring guard installation if allowed.""" + if not self.allow_lazy_constant: + if wrap_fn is not None: + return wrap_fn(value) + self.install_guards(GuardBuilder.CONSTANT_MATCH) + return ConstantVariable.create(value=value, source=self.source) + return LazyConstantVariable.create(value, source=self.source) + + def assert_not_wrapped_by_this_graph(self, value: torch.Tensor) -> None: + if is_fake(value) and maybe_get_fake_mode(value) is self.tx.fake_mode: + raise InternalTorchDynamoError( + "Cannot wrap a Tensor that has already been", + "wrapped by this instance of Dynamo", + ) + + def wrap_tensor(self, value: torch.Tensor) -> VariableTracker: + source = self.get_source() + + # We cannot already be tracking the tensor, which implies + # it would have already been wrapped + if value in self.tx.output.side_effects: + raise AssertionError("Tensor is already tracked in side effects") + + is_static_input = get_static_address_type(value) is not None + + # When a shapes_spec is provided for this tensor, we must skip the + # fast paths below that would freeze the tensor as a graph constant. + # Those paths bypass _automatic_dynamic where the spec is applied. + # Without this check, specifying TensorSpec on an nn.Parameter would + # be silently ignored. + # At tensor builder callsites, shapes_spec for this source can only be TensorSpec or None. + _tensor_spec = cast( + TensorSpec | None, + lookup_spec_from_dynamo_source(source, config._dynamic_shapes_spec), + ) + _has_spec = _tensor_spec is not None + + if ( + not _has_spec + and not is_static_input + and ( + isinstance(value, torch.nn.Parameter) + # mark tensor attributes of nn modules static + or (source and source.guard_source.is_unspecialized_nn_module()) + ) + ): + self.mark_static_input(value, guard=is_parameter_freezing()) + is_static_input = True + + # Install any tensors which are "free" variables; that is: + # 1. Globals + # 2. NonLocals + # 3. tensors that are attributes of nn module + should_install_free_tensor = config.install_free_tensors and ( + is_from_global_source(source) + or is_from_nonlocal_source(source) + or is_from_unspecialized_nn_module_source(source) + ) + + make_graph_attribute = is_static_input and ( + is_parameter_freezing() or torch._dynamo.config.prepare_freezing + ) + + if not _has_spec and ( + should_install_free_tensor + or ( + (source.guard_source.is_specialized_nn_module() or make_graph_attribute) + and not source.guard_source.is_fsdp_module() + ) + ): + self.assert_not_wrapped_by_this_graph(value) + return self.tx.output.register_attr_or_module( + value, self.name, source=source + ) + + if get_static_address_type(value) == "guarded": + # If it's a guarded tensor, we can install the parameter directly + # into the Fx graph instead of lifting it as an input. Lifting + # offers no benefit, such as regional compilation, since we still + # guard on the tensor's ID. Moreover, installing it in the Fx graph + # eliminates the pre-graph bytecode required to extract the tensor + # from locals/globals, reducing overhead. This can lead to + # significant cost savings, especially for optimizers handling many + # tensors. + self.install_guards(GuardBuilder.ID_MATCH) + self.assert_not_wrapped_by_this_graph(value) + return self.tx.output.register_attr_or_module( + value, self.name, source=source + ) + + if is_constant_source(source): + self.assert_not_wrapped_by_this_graph(value) + return self.tx.output.register_attr_or_module( + value, + re.sub(r"[^a-zA-Z0-9]+", "_", self.name), + source=source, + # Guards are added inside register_attr_or_module + ) + + # NB: this just says we accessed a tensor from the same source again + # (e.g., a tensor lives in a global foo, and we LOAD_GLOBAL it twice). + # This is distinct from two distinct sources mapping to the same + # Tensor (per id())! No guard is necessary here. See below for the + # other case. + is_duplicate_tensor = source in self.tx.output.input_source_to_var + if is_duplicate_tensor: + return self.tx.output.input_source_to_var[source] + + options = {} + subclass_type = infer_subclass_type(value) + if subclass_type is not None: + self.install_guards(GuardBuilder.TYPE_MATCH) + + if get_static_address_type(value) == "guarded": + self.install_guards(GuardBuilder.ID_MATCH) + + # By this point, we should have deduplicated all tensors + self.assert_not_wrapped_by_this_graph(value) + + if ( + isinstance(value, torch.Tensor) + and value.is_nested + and not isinstance(value, torch.nested._internal.nested_tensor.NestedTensor) + ): + unimplemented( + gb_type="Attempted to wrap strided NestedTensor", + context="", + explanation="torch.compile does not support strided NestedTensor", + hints=[], + ) + + # TODO(pearu,sparse-team) - Add the corresponding SPARSE_TENSOR_MATCH guards + if ( + isinstance(value, torch.Tensor) + and is_sparse_any(value) + and (not self.tx.export or not config.capture_sparse_compute) + ): + # A hot fix for sparse tensors + torch.compile. Support for + # export + sparsity is being added but we need to create + # SPARSE_TENSOR_GUARDS for guards to work properly. + unimplemented( + gb_type="Attempted to wrap sparse Tensor", + context="", + explanation="torch.compile does not support sparse Tensors", + hints=[*graph_break_hints.SPARSE_TENSOR], + ) + + if ( + isinstance(value, torch.Tensor) + and torch._C._functorch.peek_interpreter_stack() is None + ): + try: + tangent = torch.autograd.forward_ad.unpack_dual(value).tangent + except RuntimeError: + tangent = None + if tangent is not None: + unimplemented( + gb_type="Attempted to wrap a dual tensor input", + context="", + explanation="torch.compile does not support input tensors that " + "carry a forward-mode AD tangent; compiled code would silently " + "drop the tangent.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + if ( + safe_has_grad(value) + and safe_grad(value) is not None + # type: ignore[attr-defined] + and value.dtype != safe_grad(value).dtype + ): + safe_grad_val = safe_grad(value) + grad_str = str(safe_grad_val.dtype) if safe_grad_val is not None else "None" + unimplemented( + gb_type="dtype mismatch between tensor and its gradient", + context=f"tensor dtype: {value.dtype}; grad dtype: {grad_str}", + explanation="Inconsistent dtype between tensor and its gradient. " + "This can happen in FSDP and crashes meta tensor creation.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + # tx.output has multiple tracers if we're introspecting HigherOrderOperator. + # When we've discovered an untracked tensor, then we actually need + # to get Dynamo to track the tensor (which is what this function does) + # and put it as a graph input on the root tracer. Later on, + # if the input is actually used in the body of the HigherOrderOperator, + # then the relevant SubgraphTracer will lift it to being an input of + # the subgraph. + # See NOTE [HigherOrderOperator tracing design] for more details. + + example_value = wrap_to_fake_tensor_and_record( + value, tx=self.tx, is_tensor=True, source=source, tensor_spec=_tensor_spec + ) + + tensor_proxy = self.tx.output.root_tracer.create_graph_input( + re.sub(r"[^a-zA-Z0-9]+", "_", self.name), + type(value), + example_value, + source=source, + ) + cache_real_value_when_export(self.tx, tensor_proxy, value) + + tensor_variable = wrap_fx_proxy( + tx=self.tx, + proxy=tensor_proxy, + example_value=example_value, + subclass_type=subclass_type, + source=source, + **options, + ) + + # Track input tensors for attribute mutation, matching how + # handle_traced_output tracks intermediate tensors with AttributeMutationNew. + # This enables setattr on input tensors (e.g. tensor.custom_attr = val) + # without graph breaking. + self.tx.output.side_effects.track_object_existing(value, tensor_variable) + + if value._is_view(): + # If value is a view, add its base tensor to the tracked fakes list. + # This is so we are able to access the correct source for its symbolic + # shape values, in case we need them. + wrap_to_fake_tensor_and_record( + value._base, + tx=self.tx, + source=AttrSource(source, "_base"), + is_tensor=True, + ) + + guard_type = GuardBuilder.TENSOR_MATCH + + if isinstance(source, GradSource) and is_from_optimizer_source(source): + guard_type = GuardBuilder.NOT_NONE_MATCH + + is_dtensor = torch.distributed.is_available() and isinstance( + value, torch.distributed.tensor.DTensor + ) + + # An AsyncCollectiveTensor (ACT) flattens to a single inner tensor whose + # metadata mirrors the wrapper, and the AOTAutograd runtime wrapper + # unwraps ACT inputs before the compiled graph. So a graph traced on an + # ACT is equivalent to one traced on its resolved plain Tensor. Guard on + # the unwrapped inner tensor (via UnwrapCollectiveTensorSource) instead + # of the ACT-locked type/metadata guards, so the ACT class no longer + # forces a recompile when the runtime value alternates between an + # un-awaited ACT and an awaited Tensor. Type-introspecting code stays + # sound because observation sites reinstall the class guard on demand + # (see BuiltinVariable.call_isinstance and TensorVariable.var_getattr). + # Caveat: ACT-only member access (e.g. w.wait()) is not a class-observation + # channel and does not reinstall the guard, so such code reuses the + # ACT-traced graph for a resolved plain Tensor. It stays numerically + # correct (ACT desugars ops to the inner tensor), but a compiled region + # can succeed where eager would raise AttributeError on the plain Tensor; + # that only bites user code already broken in eager on the resolved input. + is_polymorphic_act = not is_dtensor and is_async_collective_tensor_type( + type(value) + ) + + if not is_dtensor and not is_polymorphic_act: + # We guard on the _local_tensor and the _spec, and therefore we don't + # have to guard on the outer DTensor. + self.install_guards( + functools.partial( + guard_type, + value=( + value + if isinstance(source, NumpyTensorSource) + else TensorWeakRef(value) + ), + ) + ) + + # We install TYPE_MATCH guards for traceable wrapper subclass object, + # and recursively install corresponding guard for each inner attribute. + if is_traceable_wrapper_subclass(value): + # Tensor subclass guards are very expensive because they are + # implemented in Python. Since DTensor is PyTorch-maintained class, + # we can skip a lot of these guards. + if is_dtensor: + self.install_guards(GuardBuilder.TYPE_MATCH) + + inner_attrs = value.__tensor_flatten__()[0] + if inner_attrs != ["_local_tensor", "device_mesh"]: + raise RuntimeError( + "Expecting DTensor inner attrs to be ['_local_tensor', 'device_mesh']" + ) + + flattening_ctx = value.__tensor_flatten__()[1] + if not ( + len(flattening_ctx) == 4 + and flattening_ctx[0] == value._spec.placements + and flattening_ctx[1] == value._spec.tensor_meta + and flattening_ctx[2] == value._spec.shard_order + and flattening_ctx[3] == value.requires_grad + ): + raise RuntimeError( + "Expecting DTensor flattening ctx to be (placements, tensor_meta, shard_order, requires_grad)" + ) + # Guard on the dtensor spec + install_guard( + AttrSource(self.source, "_spec").make_guard( + GuardBuilder.DTENSOR_SPEC_MATCH + ) + ) + # Move this to C++ + install_guard( + AttrSource(self.source, "requires_grad").make_guard( + GuardBuilder.EQUALS_MATCH + ) + ) + elif is_polymorphic_act: + # Guard only on the unwrapped inner tensor (inner_source below). + # Installing no type/metadata guard on the ACT wrapper is what + # lets the resolved plain Tensor reuse this cache entry. + pass + else: + self.install_guards(GuardBuilder.TENSOR_SUBCLASS_METADATA_MATCH) + self.install_guards(GuardBuilder.TYPE_MATCH) + install_guard( + SubclassAttrListSource(source).make_guard(GuardBuilder.EQUALS_MATCH) + ) + + attrs, _ = value.__tensor_flatten__() + if is_polymorphic_act and attrs != ["elem"]: + # The unwrap accessor below assumes ACT's single inner tensor. + # Unreachable today (ACT always flattens to ["elem"]); if that + # ever changes we fail hard rather than misguard -- the wrapper's + # type/metadata guards were already skipped above, so there is no + # safe fallback left at this point. + raise RuntimeError( + f"Expected AsyncCollectiveTensor to flatten to ['elem'], " + f"got {attrs}" + ) + for attr in attrs: + inner_value = getattr(value, attr) + # FakeScriptObject wraps the real opaque object during + # fake-mode tracing; unwrap before the type check. + inner_type = type(inner_value) + if isinstance( + inner_value, + torch._library.fake_class_registry.FakeScriptObject, + ): + inner_type = type(inner_value.real_obj) + if not isinstance( + inner_value, torch.Tensor + ) and not is_opaque_symbolic_type(inner_type): + raise RuntimeError( + f"{type(inner_value).__name__!r} found in tensor attrs of " + f"{type(value).__name__}.__tensor_flatten__(). " + "Only tensors and reference-type opaques are allowed " + "in tensor attrs." + ) + if is_polymorphic_act: + # ACT flattens to the single attr "elem"; guard it through + # an unwrap accessor so a plain Tensor at runtime (the + # resolved collective) matches the same guard. + inner_source = UnwrapCollectiveTensorSource(self.source) + else: + inner_source = AttrSource(self.source, attr) + LazyVariableTracker.realize_all( + VariableBuilder(self.tx, inner_source)(inner_value) + ) + + self.tx.output.input_source_to_var[source] = tensor_variable + if "tensor_dict" in tensor_proxy.node.meta: + raise AssertionError("tensor_dict already exists in tensor_proxy node meta") + tensor_proxy.node.meta["tensor_dict"] = _extract_tensor_dict(value) + + # Note: this information is conveyed via subclass_type now + # type: ignore[attr-defined] + fake_tensor_value = tensor_variable.proxy.node.meta["example_value"] + if maybe_get_fake_mode(fake_tensor_value) is not self.tx.fake_mode: + raise InternalTorchDynamoError("Wrapped Tensor must be this graph's fake") + + grapharg = GraphArg(source, value, False, fake_tensor_value) + tensor_proxy.node.meta["grapharg"] = grapharg + return tensor_variable + + def wrap_numpy_ndarray(self, value: Any) -> VariableTracker: + if np is None: + raise AssertionError("numpy must be available to wrap ndarray") + if not isinstance(value, np.ndarray): + raise AssertionError(f"Expected np.ndarray, got {type(value)}") + + source = NumpyTensorSource(self.get_source()) + + from torch._numpy import _util + + readonly = not value.flags.writeable + if readonly: + try: + value.flags.writeable = True + except ValueError: + # One can not easily make nditer elements writable, + # but warning is not the end of the world + if not isinstance(value.base, np.nditer): + raise AssertionError( + f"Expected np.nditer base, got {type(value.base)}" + ) from None + tensor_value = None + with torch_function_mode_stack_state_mgr.temp_restore_stack(): + try: + tensor_value = _util._try_convert_to_tensor(value) + if readonly: + from torch._prims_common import clone_preserve_strides + + tensor_value = clone_preserve_strides(tensor_value) + except NotImplementedError as e: + # failed to convert to tensor, graph break + unimplemented( + gb_type="failed to convert numpy.ndarray to Tensor", + context=str(value), + explanation="Exception encountered when attempting to convert numpy.ndarray to Tensor", + hints=[], + from_exc=e, + ) + if tensor_value is None: + raise AssertionError("Failed to convert numpy ndarray to tensor") + + # We do this because we want the full behavior of guarding the numpy ndarray as if it were + # a tensor. It's a little annoying to make a VT to throw out, but there's so many side effects here + # that there's not another great way to do this atm. + # This creates the right graphargs, as well as registration for guards in tensor names and shape env. + LazyVariableTracker.realize_all(VariableBuilder(self.tx, source)(tensor_value)) + example_value = wrap_to_fake_tensor_and_record( + tensor_value, + tx=self.tx, + is_tensor=False, + source=source, + ) + proxy = self.tx.output.root_tracer.create_graph_input( + re.sub(r"[^a-zA-Z0-9]+", "_", self.name), + type(tensor_value), + example_value, + source=source, + ) + cache_real_value_when_export(self.tx, proxy, tensor_value) + options = {"source": source} + numpy_ndarray_variable = wrap_fx_proxy_cls( + target_cls=NumpyNdarrayVariable, + tx=self.tx, + proxy=proxy, + example_value=example_value, + subclass_type=None, + **options, + ) + + self.tx.output.input_source_to_var[source] = numpy_ndarray_variable + # type: ignore[attr-defined] + example_value = numpy_ndarray_variable.proxy.node.meta["example_value"] + + # pass_arg_as_tensor should be true because we are wrapping a np.ndarray as argument input, and it needs to be + # converted to a tensor. + grapharg = GraphArg( + source, + tensor_value, + pass_arg_as_tensor=True, + fake_tensor=example_value, + is_tensor=True, + example_strong_ref=tensor_value, + ) + proxy.node.meta["grapharg"] = grapharg + + # TODO - Why do we need to set the source of the np ndarray vt back to + # original source. Many tests fails. + numpy_ndarray_variable.source = self.source + + return numpy_ndarray_variable + + def wrap_symint( + self, + value: int, + dynamism: DimDynamic | None = None, + context: SymIntSymbolicContext | None = None, + ) -> VariableTracker: + if type(value) is not int: + raise AssertionError(f"Expected exact int type, got {type(value)}") + + if self.name in self.tx.output.unspec_variable_map: + return self.tx.output.unspec_variable_map[self.name] + + shape_env = self.tx.output.shape_env + frame_state_entry: FrameStateSizeEntry | None = None + if TracingContext.get().force_unspec_int_unbacked_size_like: + wrapped_value = shape_env.create_unbacked_symint() + _constrain_range_for_size(wrapped_value) + self.tx.output.tracked_fakes.append( + TrackedFake(wrapped_value, self.source, None) + ) + + # NB: We do not do float. For motivation, see + # https://docs.google.com/document/d/1INSCdYu1PxXcr43HrD82OudeEuS-qxQe1yZmLg2wy6A/edit + # but the general idea is that we generate kernels that can + # take unspecialized floats and use them in sizevar computation + elif not is_constant_source(self.get_source()): + if dynamism is None and torch._dynamo.config.specialize_int: + # If specialize_int is False, also return + # a constant (but this should have been handled + # in the caller, TBH). But if `dynamism` is set, then actually + # turn it into a symint + self.install_guards(GuardBuilder.CONSTANT_MATCH) + return ConstantVariable.create(value=value, source=self.source) + + name = self.source.name + + frame_state_entry = process_automatic_dynamic( + self.tx, + name, + FrameStateSizeEntry.make_scalar(value), + is_unspecialized_nn_module=self.source.guard_source.is_unspecialized_nn_module(), + ) + + # TODO: This should be dynamic, as we in general do not + # know if bare integers are actually going to be sizevars + # and it is inappropriate to eagerly duck size them with + # real sizevars + normalized_source_name = normalize_source_name(self.source.name) + + if dynamism is not None: + dynamic_dim = dynamism + elif ( + config.automatic_dynamic_shapes + and frame_state_entry.scalar is auto_dynamic + ): + set_feature_use("dynamo.automatic_dynamic_shapes", True) + dynamic_dim = get_automatic_dynamic_shapes_mark_as() + elif ( + _is_dim_dynamic_from_source_dynamism( + self.source, normalized_source_name, 0 + ) + ) or not config.assume_static_by_default: + symbolic_shape_log.info( + "marking %s as dynamic (from assume_static_by_default = False)", + name, + ) + dynamic_dim = DimDynamic.DYNAMIC + else: # assume_static_by_default + # TODO: dynamic_dim = DimDynamic.STATIC should work but + # for some reason it doesn't + if frame_state_entry.scalar is auto_dynamic: + set_feature_use("dynamo.automatic_dynamic_shapes", False) + self.install_guards(GuardBuilder.CONSTANT_MATCH) + return ConstantVariable.create(value=value) + + excluded_scalar = ( + frame_state_entry.excluded_scalar + if config.automatic_dynamic_exclusion_guard + and frame_state_entry is not None + else None + ) + wrapped_value = shape_env.create_unspecified_symint_and_symbol( + value, + source=self.source, + dynamic_dim=dynamic_dim, + excluded_value=excluded_scalar, + ) + if not isinstance(wrapped_value, SymInt): + raise AssertionError(f"Expected SymInt, got {type(wrapped_value)}") + + self.tx.output.tracked_fakes.append( + TrackedFake(wrapped_value, self.source, context) + ) + else: + if not is_constant_source(self.get_source()): + raise AssertionError( + f"Expected constant source, got {self.get_source()}" + ) + # TODO: Do I actually need guard for constant source? + self.install_guards(GuardBuilder.CONSTANT_MATCH) + return ConstantVariable.create(value=value, source=self.source) + + if isinstance(self.get_source(), RandomValueSource): + raise AssertionError( + "RandomValueSource is not supported for symint wrapping" + ) + install_guard(self.get_source().make_guard(GuardBuilder.TYPE_MATCH)) + + options = {"source": self.get_source()} + + proxy = self.tx.output.root_tracer.create_graph_input( + re.sub(r"[^a-zA-Z0-9]+", "_", self.name), + type(wrapped_value), + wrapped_value, + source=self.get_source(), + ) + + sym_expr = wrapped_value.node.expr + if not isinstance(sym_expr, sympy.Symbol): + raise AssertionError(f"{sym_expr} is not a basic Symbol.") + self.tx.output.root_tracer.bound_symbols[sym_expr] = proxy + unspec_var = SymNodeVariable.create(self.tx, proxy, wrapped_value, **options) + # type: ignore[assignment] + self.tx.output.unspec_variable_map[self.name] = unspec_var + + if not is_constant_source(self.get_source()): + proxy.node.meta["grapharg"] = GraphArg( + self.get_source(), + wrapped_value, + pass_arg_as_tensor=False, + fake_tensor=None, + is_tensor=False, + example_strong_ref=wrapped_value, + ) + + return unspec_var + + def wrap_symfloat(self, value: float) -> VariableTracker: + # SymFloat wrapping is special. We first wrap it in the same way we + # do an unspecialized primitive, and then we item() it into a + # SymFloat. Removal of the item() call is left to a later FX pass, + # mostly because that pass is more easily done after we have lowered + # to ATen ops. (Dynamo doesn't do decomposition right now). + + if self.name in self.tx.output.unspec_variable_map: + return self.tx.output.unspec_variable_map[self.name] + + frame_state_entry = process_automatic_dynamic( + self.tx, + self.source.name, + # type: ignore[arg-type] + FrameStateSizeEntry.make_scalar(value), + is_unspecialized_nn_module=self.source.guard_source.is_unspecialized_nn_module(), + ) + + # NB: we specialize on nan input, because our guard modeling in + # ShapeEnv cannot deal with nan + if ( + torch._dynamo.config.specialize_float + or is_constant_source(self.get_source()) + or math.isnan(value) + or math.isinf(value) + # We don't support cudagraphs for now. Without this cudagraphs + # break because they expect all cuda inputs but our tensorified + # float will be a f64[] cpu tensor. Fixes the following test + # when specialize_float=False + # python test/inductor/test_compiled_optimizers.py CompiledOptimizerTests.test_rmsprop_weight_decay_maximize_capturable_cuda + or torch._inductor.config.triton.cudagraphs + or justknobs_check("pytorch/compiler:unspecialize_float_killswitch", False) + or ( + config.assume_static_by_default + and frame_state_entry.scalar is not auto_dynamic + ) + ): + self.install_guards(GuardBuilder.CONSTANT_MATCH) + return ConstantVariable.create(value=value, source=self.source) + + # NB: At the point we've gotten here, we don't assume static by + # default. Since we have a guard mechanism, there isn't really any + # downside to trying to be dynamic for float all the time. Unlike + # ints, this won't make codegen perf worse. Modest cost to compile + # time. + + wrapped_value = torch.tensor(value, dtype=torch.float64) + + # We don't support specializing floats for grad checking tensors + # See https://github.com/pytorch/pytorch/pull/140828 for more + # context. + if torch._C._functorch.is_gradtrackingtensor(wrapped_value): + self.install_guards(GuardBuilder.CONSTANT_MATCH) + return ConstantVariable.create(value=value, source=self.source) + + # TODO: Switch RandomValueSource over to use this, this is more + # accurate + if isinstance(self.get_source(), RandomValueSource): + raise AssertionError( + "RandomValueSource is not supported for symfloat wrapping" + ) + install_guard(self.get_source().make_guard(GuardBuilder.TYPE_MATCH)) + + # The FloatTensorSource here is just for pedantic correctness: if you + # guard against an UnspecializedPythonVariable, you need to guard + # against the tensor-ified version of the local, otherwise it's not a + # Tensor. However, we never let the UnspecializedPythonVariable escape + # here, so there should never actually be any guards against this + # source. + source = FloatTensorSource(self.get_source()) + options = {"source": source, "raw_value": value} + + # TODO: Maybe the tensor-ification should be built into the source, + # rather than by special pattern match + example_value = wrap_to_fake_tensor_and_record( + wrapped_value, tx=self.tx, is_tensor=False, source=source + ) + proxy = self.tx.output.root_tracer.create_graph_input( + re.sub(r"[^a-zA-Z0-9]+", "_", self.name), + type(wrapped_value), + example_value, + source=source, + ) + cache_real_value_when_export(self.tx, proxy, wrapped_value) + + unspec_var = wrap_fx_proxy_cls( + UnspecializedPythonVariable, + tx=self.tx, + proxy=proxy, + example_value=example_value, + subclass_type=None, + **options, + ) + if not isinstance(unspec_var, UnspecializedPythonVariable): + raise AssertionError( + f"Expected UnspecializedPythonVariable, got {type(unspec_var)}" + ) + self.tx.output.unspec_variable_map[self.name] = unspec_var + + if self.tx.export and not isinstance(self.get_source(), LocalSource): + raise AssertionError( + f"Dynamo attempts to add additional input during export: value={wrapped_value}, source={self.get_source()}" + ) + fake_tensor_value = None + example_value = unspec_var.proxy.node.meta["example_value"] + if not is_fake(example_value): + raise AssertionError( + f"Expected fake tensor example_value, got {type(example_value)}" + ) + + fake_tensor_value = example_value + # type: ignore[attr-defined] + if fake_tensor_value.fake_mode is not self.tx.fake_mode: + raise AssertionError( + f"fake mode ({fake_tensor_value.fake_mode}) from fake tensor metadata doesn't match mode" + "({self.tx.fake_mode}) from InstructionTranslator" + ) + + # There's something a bit incoherent about pass_arg_as_tensor, + # specifically regarding sources. + # + # Specifically, suppose we have "x: float" local argument. We + # eventually end up with an UnspecializedPythonVariable denoting + # torch.as_tensor(x)... but it's source is still L['x'] (which if you + # accessed it directly is a float!) So you gotta be careful when + # setting up your guards, because it's still going to be a float at + # this point, the conversion happens only precisely at the point we're + # actually calling the FX graph. This happens to be what we want for + # shape guard generation, but it's kind of unintuitive. + proxy.node.meta["grapharg"] = GraphArg( + self.get_source(), + wrapped_value, + pass_arg_as_tensor=True, + # type: ignore[arg-type] + fake_tensor=fake_tensor_value, + is_tensor=False, + example_strong_ref=wrapped_value, + ) + + # Directly do item to bypass capture_scalar_outputs + r = wrap_fx_proxy( + self.tx, + self.tx.output.create_proxy( + "call_method", + "item", + *proxy_args_kwargs([unspec_var], {}), + ), + ) + # type: ignore[attr-defined] + self.tx.output.tracked_fakes.append(TrackedFake(r.sym_num, self.source, None)) + + get_metrics_context().set("tensorify_float_attempt", True, overwrite=True) + + return r + + def wrap_unspecialized_primitive(self, value: Any) -> VariableTracker: + if self.name in self.tx.output.unspec_variable_map: + return self.tx.output.unspec_variable_map[self.name] + + wrapped_value = torch.tensor(value) + if not isinstance(self.get_source(), RandomValueSource): + install_guard(self.get_source().make_guard(GuardBuilder.TYPE_MATCH)) + + options = {"source": self.get_source()} + options.update({"raw_value": value}) + + example_value = wrap_to_fake_tensor_and_record( + wrapped_value, tx=self.tx, is_tensor=False, source=self.get_source() + ) + proxy = self.tx.output.root_tracer.create_graph_input( + re.sub(r"[^a-zA-Z0-9]+", "_", self.name), + type(wrapped_value), + example_value, + source=self.get_source(), + ) + cache_real_value_when_export(self.tx, proxy, wrapped_value) + + unspec_var = wrap_fx_proxy_cls( + UnspecializedPythonVariable, + tx=self.tx, + proxy=proxy, + example_value=example_value, + subclass_type=None, + **options, + ) + # type: ignore[assignment] + self.tx.output.unspec_variable_map[self.name] = unspec_var + if not is_constant_source(self.get_source()): + if self.tx.export and not isinstance(self.get_source(), LocalSource): + raise AssertionError( + f"Dynamo attempts to add additional input during export: value={wrapped_value}, source={self.get_source()}" + ) + fake_tensor_value = None + if unspec_var.is_python_constant(): + # TODO: when can this happen? + example_value = unspec_var.as_python_constant() + else: + # type: ignore[attr-defined] + example_value = unspec_var.proxy.node.meta["example_value"] + if not is_fake(example_value): + raise AssertionError( + f"Expected fake tensor example_value, got {type(example_value)}" + ) + + fake_tensor_value = example_value + # type: ignore[attr-defined] + if fake_tensor_value.fake_mode is not self.tx.fake_mode: + raise AssertionError( + f"fake mode ({fake_tensor_value.fake_mode}) from fake tensor metadata doesn't match mode" + "({self.tx.fake_mode}) from InstructionTranslator" + ) + + proxy.node.meta["grapharg"] = GraphArg( + self.get_source(), + wrapped_value, + pass_arg_as_tensor=True, + # type: ignore[arg-type] + fake_tensor=fake_tensor_value, + is_tensor=False, + example_strong_ref=wrapped_value, + ) + return unspec_var + + +def _dataclasses_fields_lambda(obj: VariableTracker) -> TupleVariable: + value = None + if isinstance(obj, UserDefinedObjectVariable): + value = obj.value + else: + unimplemented( + gb_type="dataclass fields failure", + context=f"obj: {obj}; variable type: {type(obj)}", + explanation=f"Dataclass fields handling fails for {obj}. Expected it to be a user-defined object.", + hints=[], + ) + if value is None: + raise AssertionError("dataclasses.fields requires a non-None value") + items = [] + # type: ignore[arg-type] + for field in dataclasses.fields(value): + source = None + if obj.source: + base_src = AttrSource(obj.source, "__dataclass_fields__") + source = DictGetItemSource(base_src, field.name) + items.append(UserDefinedObjectVariable(field, source=source)) + # pyrefly: ignore [bad-argument-type] + return TupleVariable(items) + + +def _clone_input(value: Any, fake_mode: FakeTensorMode | None) -> Any: + if isinstance(value, torch.Tensor): + # tensor subclasses will not be converted to FakeTensors and need to be cloned + if not ( + is_fake_tensor(value) + or ( + # Is functional tensor fakeified by this instance of Dynamo + torch._is_functional_tensor(value) + and maybe_get_fake_mode(value) is fake_mode + ) + or value.is_nested + ): + # NB: ensure strides are preserved + value = clone_input(value) + + return value + + +def wrap_fx_proxy( + tx: "InstructionTranslatorBase", + proxy: Any, + example_value: Any | None = None, + subclass_type: type | None = None, + **options: Any, +) -> VariableTracker: + kwargs = { + "tx": tx, + "proxy": proxy, + "example_value": example_value, + "subclass_type": subclass_type, + **options, + } + if subclass_type is None: + # pyrefly: ignore[bad-argument-type] + return wrap_fx_proxy_cls(target_cls=TensorVariable, **kwargs) + else: + # pyrefly: ignore[bad-argument-type] + result = wrap_fx_proxy_cls(target_cls=TensorWithTFOverrideVariable, **kwargs) + # type: ignore[attr-defined] + result.install_global(tx) + return result + + +def cache_real_value_when_export( + tx: "InstructionTranslatorBase", proxy: Any, example_value: Any +) -> None: + if tx.export: + # The legacy behavior for real value cache with subclasses was + # to perform a clone WITHOUT preserving the subclass. It's + # not entirely clear this is what you actually want though. + with torch._C.DisableTorchFunctionSubclass(): + proxy.tracer.real_value_cache[proxy.node] = _clone_input( + example_value, tx.fake_mode + ) + + +# Note: Unfortunate split due to some gross classes existing that subclass TensorVariable +# Should be compositional instead +# +# This is a horribly complicated function that does too many things, to +# explain what it does, let's first talk about the classic usage wrap_fx_proxy +# for a TensorVariable. There are two primary modes of use: +# +# 1. Wrapping a pre-existing Tensor. In this case, example_value is set +# to the pre-existing Tensor. (Note that this example_value will NOT +# be the final example_value we put into node.meta['example_value'], +# instead it is converted into a fake tensor using +# wrap_to_fake_tensor_and_record and registered as a graph input.) +# +# 2. "Wrapping" the result of some Tensor operation Dynamo traced over. In +# this case, example_value is None (and we are going to figure it out +# ourselves using FakeTensors, via get_fake_value, which will run +# the operation represented by the (singular!) FX node referenced by +# the passed in proxy.) +# +# The expectation is you end up with a Tensor output, and everything is +# straightforwardly traced into the graph. +# +# In all cases, the returned `TensorVariable` subclass will have an `example_value` +# and that `example_value` must be a `FakeTensor` produced by the currently running +# instance of Dynamo. +# +# Upon closer inspection, you may notice that there are a slurry of non-Tensor +# output cases in handle_traced_output. What gives? Well, we sometimes trace operations into the +# graph that don't involve tensors. +# +# * Some operators return tuples; we need to recursively handle their +# contents +# +# * Some operators have side effects that will affect subsequent AOTAutograd +# tracing but don't otherwise return anything. +# +# * Some operators return symbolic ints/floats/bools which can go in the +# graph and be traced (but only if they're actually symbolic! If they're +# static you don't want to put them in the graph, which means you +# shouldn't call this function.) +# +# The common theme is that you only use this function WHEN YOU ARE TRACING +# SOMETHING INTO THE GRAPH. This is sort of obvious, because you can't call +# this function without a proxy. +def wrap_fx_proxy_cls( + target_cls: type[VTTypeAlias], + tx: "InstructionTranslatorBase", + proxy: Any, + example_value: Any | None = None, + subclass_type: type | None = None, + **options: Any, +) -> VTTypeAlias: + if example_value is None: + out: VTTypeAlias = _wrap_fx_proxy( + target_cls, tx, proxy, example_value, subclass_type, **options + ) + elif isinstance(example_value, torch.Tensor): + out = _wrap_fx_preexisting_tensor( + target_cls, tx, proxy, example_value, subclass_type, **options + ) + else: + # This will skip tracing an op and recursively reinvoke wrap_fx_proxy_cls on supported + # data structures. In essence this just handles tracing some other value which may + # contain Fake Tensors or is otherwise proxyable. + # pyrefly: ignore[bad-assignment] + out = handle_traced_output( + example_value, tx, proxy, options, subclass_type, target_cls + ) + + if ( + isinstance( + out, + ( + torch._dynamo.variables.TensorVariable, + torch._dynamo.variables.SymNodeVariable, + ), + ) + and proxy.node.op != "placeholder" + ): + tx.output.current_tracer.record_proxyable_vt(out) + return out + + +# This is 1 above (wrapping a preexisting tensor) +def _wrap_fx_preexisting_tensor( + target_cls: type[VTTypeAlias], + tx: "InstructionTranslatorBase", + proxy: torch.fx.Proxy, + tensor: torch.Tensor, + subclass_type: type | None = None, + **options: Any, +) -> VTTypeAlias: + from ..symbolic_convert import InstructionTranslatorBase + + if not isinstance(tensor, torch.Tensor): + raise AssertionError( + f"_wrap_fx_preexisting_tensor expected tensor, got {type(tensor)}" + ) + + if not isinstance(tx, InstructionTranslatorBase): + raise AssertionError(f"Expected InstructionTranslatorBase, got {type(tx)}") + if "guards" in options and options["guards"] is not None: + tx.output.guards.update(options["guards"]) + + # Placeholders always carry example_value in node.meta. + # non-placeholders always have no example_value in node.meta + if proxy.node.op == "placeholder": + if "example_value" not in proxy.node.meta: + raise AssertionError( + f"placeholder {proxy} doesn't have 'example_value' in node.meta" + ) + else: + if "example_value" in proxy.node.meta: + raise AssertionError(f"{proxy.node.meta['example_value']}") + + # See NOTE: [Deferring tensor pack/unpack hooks until runtime] + with torch._dynamo.utils._disable_saved_tensors_hooks_during_tracing(): + # Handle recursive calls here + if maybe_get_fake_mode(tensor) is tx.fake_mode: + pass + else: + cache_real_value_when_export(tx, proxy, tensor) + if tx.export: + # The legacy behavior for real value cache with subclasses was + # to perform a clone WITHOUT preserving the subclass. It's + # not entirely clear this is what you actually want though. + with torch._C.DisableTorchFunctionSubclass(): + # type: ignore[attr-defined] + proxy.tracer.real_value_cache[proxy.node] = _clone_input( + tensor, tx.fake_mode + ) + # NB: If we're ignoring subclass, then the expectation is you will + # take the returned TensorVariable and wrap it into a more + # accurate TensorVariable that is able to track subclass-ness; + # otherwise this is wrong! + kwargs = { + "is_tensor": target_cls + in (TensorVariable, TensorWithTFOverrideVariable), + } + if "source" not in options: + raise AssertionError("source must be provided in options") + if options["source"] is None: + raise AssertionError("source must not be None in options") + kwargs["source"] = options["source"] + # pyrefly: ignore [missing-argument] + tensor = wrap_to_fake_tensor_and_record(tensor, tx=tx, **kwargs) + + if tensor.device.type != "meta" and ( + maybe_get_fake_mode(tensor) is not tx.fake_mode + ): + raise InternalTorchDynamoError( + "`tensor` needs to be a `FakeTensor`" + f"wrapped by this instance of Dynamo. Found: {tensor}" + ) + + return construct_tensor_variable( + target_cls, tx, proxy, tensor, subclass_type, options + ) + + +# This is 2 in the above comment (wrapping the output of a traced op) +def _wrap_fx_proxy( + target_cls: type[VTTypeAlias], + tx: "InstructionTranslatorBase", + proxy: torch.fx.Proxy, + example_value: Any | None = None, + subclass_type: type | None = None, + **options: Any, +) -> VTTypeAlias: + from ..symbolic_convert import InstructionTranslatorBase + + if not isinstance(tx, InstructionTranslatorBase): + raise AssertionError(f"Expected InstructionTranslatorBase, got {type(tx)}") + if "guards" in options and options["guards"] is not None: + tx.output.guards.update(options["guards"]) + + if "example_value" in proxy.node.meta: + raise AssertionError(f"{proxy.node.meta['example_value']}") + + # See NOTE: [Deferring tensor pack/unpack hooks until runtime] + with torch._dynamo.utils._disable_saved_tensors_hooks_during_tracing(): + # with preserve_rng_state(): + # only allow_non_graph_fake in this instance because we handle the non-fake + # cases properly below. + example_value = get_fake_value(proxy.node, tx, allow_non_graph_fake=True) + + # pyrefly: ignore[bad-return] + return handle_traced_output( + # type: ignore[arg-type] + example_value, + tx, + proxy, + options, + subclass_type, + target_cls, + ) + + +# This handles wrapping of the output of an op traced into the graphs +def handle_traced_output( + example_value: Any, + tx: "InstructionTranslatorBase", + proxy: torch.fx.Proxy, + options: dict[str, Any], + subclass_type: type | None, + target_cls: type[VTTypeAlias], +) -> VariableTracker: + import torch._functorch.vmap + import torch._subclasses.fake_tensor + import torch._utils + + if isinstance(example_value, torch.Tensor): + # Check if the result is a sparse tensor - + # We generally don't support sparse tensor so better to graph break here + if is_sparse_any(example_value) and ( + not tx.export or not config.capture_sparse_compute + ): + # Avoid calling str() on FakeTensors with unbacked symints as it triggers + # _tensor_str machinery which can cause GuardOnDataDependentSymNode errors + context = f"sparse tensor with layout={example_value.layout}, shape={example_value.shape}" + unimplemented( + gb_type="Attempted to wrap sparse Tensor with VariableTracker", + context=context, + explanation="torch.compile does not support sparse Tensors with VariableTracker", + hints=[*graph_break_hints.SPARSE_TENSOR], + ) + var = construct_tensor_variable( + target_cls, tx, proxy, example_value, subclass_type, options + ) + # NOTE: [Side effect tracking for newly constructed tensor] + # For newly constructed objects that have mutable attributes, we usually + # construct their VariableTracker via `track_object_new`, but since + # tensor variable construction is a bit different, we handle them + # specially here. This ensures that codegen will actually generate the + # attribute mutations on this tensor. + # + # NOTE we pass a dummy object as the `item` argument to avoid + # constructing a dummy _tensor_ object. The object isn't used for + # newly constructed VTs anyways. + if not isinstance(var, VariableTracker): + raise AssertionError(f"Expected VariableTracker, got {type(var)}") + tx.output.side_effects._track_obj( + proxy, var, mutation_type_cls=AttributeMutationNew + ) + return var + elif ( + hasattr(proxy.node.target, "__name__") + and proxy.node.target.__name__ == "set_state" + # type: ignore[attr-defined] + and isinstance(proxy.node.target.__self__, torch._C.Generator) + or proxy.node.target is torch.random.set_rng_state + ): + if type(proxy.node.target) is str: + raise AssertionError("proxy.node.target must not be a string") + # pyrefly: ignore[bad-argument-type] + return TorchInGraphFunctionVariable(proxy.node.target) + elif ( + proxy.node.target is torch._C._DisableFuncTorch + or proxy.node.target is torch.cuda._is_in_bad_fork + ): + return UserDefinedObjectVariable(example_value) + elif istype(example_value, torch.Size) and all( + isinstance(x, int) for x in example_value + ): + sizes = [ConstantVariable.create(x) for x in example_value] + return SizeVariable(sizes, **options) + elif isinstance(example_value, (tuple, list)): + set_example_value(proxy.node, example_value) + unpacked = [] + for i, val in enumerate(example_value): + if val is None: + # nn.MultiheadAttention() can return None, see issue #175 + unpacked.append( + ConstantVariable.create(None, **options), + ) + else: + proxy_i = proxy.tracer.create_proxy( + kind="call_function", + target=operator.getitem, + args=(proxy, i), + kwargs={}, + ) + + if "source" in options: + # This path should only trigger for list stealing, so it's + # safe to use `GetItemSource`. + if not isinstance(example_value, list): + raise AssertionError( + f"Expected list for source path, got {type(example_value)}" + ) + source = options["source"] + options_i = options.copy() + options_i["source"] = GetItemSource( + base=source, + index=i, + index_is_slice=False, + ) + else: + # use the same options object as parent + options_i = options + + # WARNING: this assumes the same target_cls as this tuple/list call + unpacked.append( + # pyrefly: ignore [bad-argument-type] + wrap_fx_proxy_cls( + # pyrefly: ignore[bad-argument-type] + target_cls=target_cls, + tx=tx, + proxy=proxy_i, + example_value=val, + **options_i, + ) + ) + if isinstance(example_value, torch.Size): + # NB: Keep the old proxy around. See SizeVariable for an + # explanation why + return SizeVariable(unpacked, proxy, **options) + elif istype(example_value, tuple): + return TupleVariable(unpacked, **options) + elif istype(example_value, (list, immutable_list)): + return ListVariable(unpacked, **options) + else: + if not is_namedtuple(example_value): + raise AssertionError( + f"expected namedtuple or structseq but got {type(example_value)}" + ) + tuple_vt = TupleVariable( + unpacked, + mutation_type=options.get("mutation_type", ValueMutationNew()), + ) + return UserDefinedTupleVariable.get_vt_cls(type(example_value))( + example_value, + tuple_vt=tuple_vt, + **options, # type: ignore[arg-type] + ) + elif example_value is None or proxy.node.target is torch.manual_seed: + return ConstantVariable.create(None, **options) + elif isinstance(example_value, (torch.SymInt, torch.SymFloat, torch.SymBool)): + tx.output.current_tracer.track_produced_symints(example_value, proxy) + set_example_value(proxy.node, example_value) + return SymNodeVariable.create(tx, proxy, example_value, **options) + elif ( + isinstance(example_value, torch.Stream) + and proxy.node.target is get_external_object_by_index + ) or proxy.node.target in [ + device_interface.current_stream + for _, device_interface in get_registered_device_interfaces() + ]: + set_example_value(proxy.node, example_value) + index = None + if proxy.node.target is get_external_object_by_index: + index = proxy.node.args[0] + # type: ignore[arg-type] + return StreamVariable(proxy, example_value, index, **options) + elif ( + isinstance(example_value, torch.Event) + and proxy.node.target is get_external_object_by_index + ) or proxy.node.target in [ + device_interface.current_stream + for _, device_interface in get_registered_device_interfaces() + ]: + index = None + if proxy.node.target is get_external_object_by_index: + index = proxy.node.args[0] + set_example_value(proxy.node, example_value) + # type: ignore[arg-type] + return EventVariable(proxy, example_value, index, **options) + elif ( + inspect.isclass(proxy.node.target) + and issubclass(proxy.node.target, torch.Event) + ) or proxy.node.target in [ + device_interface.Event + for _, device_interface in get_registered_device_interfaces() + ]: + set_example_value(proxy.node, example_value) + return EventVariable(proxy, example_value, None, **options) + elif proxy.node.target == "query" and proxy.node.op == "call_method": + set_example_value(proxy.node, example_value) + return ConstantVariable(example_value, **options) + elif ( + example_value is not None + and isinstance(example_value, torch.Event) + and proxy.node.target == "record_event" + and proxy.node.op == "call_method" + ): + set_example_value(proxy.node, example_value) + return EventVariable(proxy, example_value, None, **options) + elif isinstance(example_value, int) and ( + proxy.node.target + in [ + torch.sym_int, + torch.sym_max, + torch.sym_min, + getattr, + operator.getitem, + torch._utils._element_size, + torch.seed, + operator.mod, + torch._functorch.vmap._validate_and_get_batch_size, + torch._functorch.predispatch._vmap_increment_nesting, + torch._functorch.predispatch._vmap_decrement_nesting, + # some mac builds are missing torch.distributed.get_rank() + getattr(torch.distributed, "get_rank", _missing), + getattr(torch.distributed, "get_world_size", _missing), + # This always wants to be in the graph, even if the constraint + # results in a constant int + torch._constrain_as_size, + ] + or ( + # TODO: this is a little sus, because we didn't check what the self is + proxy.node.op == "call_method" and proxy.node.target == "bit_length" + ) + ): + set_example_value(proxy.node, example_value) + return ConstantVariable.create(example_value, **options) + elif isinstance(example_value, torch.backends.cuda.SDPAParams): + from .sdpa import SDPAParamsVariable + + set_example_value(proxy.node, example_value) + return SDPAParamsVariable(proxy, **options) + elif isinstance(example_value, bool) and ( + proxy.node.target + in [ + torch._C._are_functorch_transforms_active, + torch._C._functorch.is_batchedtensor, + torch.backends.cuda.is_flash_attention_available, + torch.backends.cuda.can_use_flash_attention, + torch.backends.cuda.can_use_efficient_attention, + torch._C._get_cudnn_sdp_enabled, + torch._C._get_flash_sdp_enabled, + torch._C._get_mem_efficient_sdp_enabled, + torch._C._get_math_sdp_enabled, + torch._C._get_overrideable_sdp_enabled, + torch._C._is_autocast_available, + "is_integer", + ] + + list(supported_const_comparison_op_values.keys()) + ): + set_example_value(proxy.node, example_value) + return ConstantVariable.create(example_value, **options) + elif isinstance(example_value, (int, float, bool)) and ( + proxy.node.target is call_torchbind + or proxy.node.target is flat_apply + or (proxy.node.op == "call_method" and proxy.node.target == "item") + ): + set_example_value(proxy.node, example_value) + return ConstantVariable.create(example_value, **options) + elif isinstance(example_value, float) or proxy.node.target in ["hex", "__round__"]: + set_example_value(proxy.node, example_value) + return ConstantVariable.create(example_value, **options) + elif isinstance(example_value, torch._library.fake_class_registry.FakeScriptObject): + # example_value is already a FakeScriptObject (e.g. returned by getitem + # on a container whose fake kernel returns a FakeScriptObject). No need + # to convert it — just wrap the proxy directly. + return CustomClassObjectVariable.create( + proxy, + example_value, + tx=tx, + ) + elif is_custom_class(type(example_value)): + # This is for handling opaque objects in custom ops + if is_opaque_constant_type(type(example_value)): + return CustomClassObjectVariable.create( + example_value, # pyrefly: ignore[bad-argument-type] + example_value, + tx=tx, + ) + fake_script_obj = torch._library.fake_class_registry.maybe_to_fake_obj( + tx.output.fake_mode, example_value + ) + return CustomClassObjectVariable.create( + proxy, + fake_script_obj, + tx=tx, + ) + else: + unimplemented( + gb_type="torch.* op returned non-Tensor", + context=f"example_value type: {typestr(example_value)}; op: {proxy.node.op}; target: {proxy.node.target}", + explanation="torch.* ops that return a non-Tensor cannot be traced into the Dynamo FX graph output", + hints=[], + ) + + +def infer_subclass_type(value: T) -> type[T] | None: + if type(value) in ( + torch.Tensor, + torch.nn.Parameter, + torch._subclasses.fake_tensor.FakeTensor, + torch._subclasses.functional_tensor.FunctionalTensor, + ) or is_traceable_wrapper_subclass(value): + # Ordinarily, we would fakeify a tensor so that it can get dynamic + # shapes and be computed on without triggering actual operations. + # However, how can we fakeify a tensor subclass? Ordinary + # inheritance (nor multiple inheritance) won't work. + # + # Instead, our plan is to *manually simulate* the tensor subclass + # inheriting from a fake tensor with dynamo. This means our + # data representation for a tensor subclass will be a fake tensor + # + tensor subclass type + any extra data the subclass may have + # been storing on the tensor. Because all Python accesses are + # mediated through TensorWithTFOverrideVariable, we can ensure + # that we dispatch differently, e.g., according to + # __torch_function__ + # + # To simplify things for now, the __dict__ tracking bits haven't + # been implemented yet, but they can be added into this design at + # a later point in time. + return None + else: + return type(value) + + +def get_specialized_props( + target_cls: Any, + tx: "InstructionTranslatorBase", + example_value: Any, + subclass_type: type | None, +) -> TensorSpecializedProps: + specialized_props = target_cls.specialize(example_value) + # TODO: not sure about this fake mode test + if ( + is_fake_tensor(example_value) + and maybe_get_fake_mode(example_value) is tx.fake_mode + ): + if subclass_type: + tensor_type = subclass_type + elif isinstance(example_value, torch.nn.Parameter): + tensor_type = torch.nn.Parameter + elif isinstance(example_value, torch.nn.Buffer): + tensor_type = torch.nn.Buffer + else: + tensor_type = torch.Tensor + specialized_props["class_type"] = tensor_type + + return specialized_props + + +def construct_tensor_variable( + target_cls: type[VTTypeAlias], + tx: "InstructionTranslatorBase", + proxy: torch.fx.Proxy, + example_value: Any, + subclass_type: type | None, + options: dict[str, Any], +) -> VTTypeAlias: + """ + Actually construct a tensor variable after all the pre-processing from + wrapping a pre-existing or newly created tensor value. + """ + # NB: In most (all?) cases, this does not actually do a clone. + # (WARNING: this means that if we mutate metadata on the fake + # tensor, the stored example value will update too!) + example_value = _clone_input(example_value, tx.fake_mode) + set_example_value(proxy.node, example_value) + # We bind the unbacked symints in sizes/trdies of tensor lazily. + # So that subgraphs can access the unbacked symbol's proxy in parent graph + # when lifting unbacked symbols of input tensors to subgraph inputs. + # We do it lazily because the tensor may not be used in subgraphs. + if proxy.node.op != "placeholder": + tx.output.current_tracer.track_produced_symints(example_value, proxy) + options.update(get_specialized_props(target_cls, tx, example_value, subclass_type)) + # pyrefly: ignore [bad-argument-count] + return target_cls(proxy, **options) + + +def get_automatic_dynamic_shapes_mark_as() -> DimDynamic: + if config.automatic_dynamic_shapes_mark_as == "dynamic": + return DimDynamic.DYNAMIC + elif config.automatic_dynamic_shapes_mark_as == "unbacked": + return DimDynamic.UNBACKED + else: + raise ValueError( + f"invalid automatic_dynamic_shapes_mark_as = {config.automatic_dynamic_shapes_mark_as}" + ) + + +# Each entry is (pattern, dim) where dim is None for "all dims" or an int +# for a single dim. The optional ":N" suffix on a source list entry restricts +# the match to dim N of the matched tensor. List the same source multiple +# times (e.g. "L['x']:0, L['x']:2") to target multiple specific dims. +_DYNAMIC_SOURCES: list[tuple[str, int | None]] | None = None +_DYNAMIC_SOURCES_CONFIG_HASH: int | None = None + +_DIM_SUFFIX_RE: re.Pattern[str] = re.compile(r"^(.+):(\d+)$") + + +def _parse_source_entry(entry: str) -> tuple[str, int | None]: + """Parse a source list entry into (pattern, dim). + + Entries may end with an optional ``:N`` suffix where ``N`` is a literal + non-negative integer (the dim portion is not part of the name regex). + """ + m = _DIM_SUFFIX_RE.match(entry) + if m: + return m.group(1), int(m.group(2)) + return entry, None + + +def get_dynamic_sources() -> list[tuple[str, int | None]]: + global _DYNAMIC_SOURCES, _DYNAMIC_SOURCES_CONFIG_HASH + + current_hash = hash(torch.compiler.config.dynamic_sources) + + # If we have already calculated the sources and the config hasn't changed, return cached result + if _DYNAMIC_SOURCES is not None and _DYNAMIC_SOURCES_CONFIG_HASH == current_hash: + return _DYNAMIC_SOURCES + + # Config has changed or first time, (re)calculate the sources + _DYNAMIC_SOURCES = [ + _parse_source_entry(s) + for s in torch.compiler.config.dynamic_sources.replace(" ", "").split(",") + if s + ] + _DYNAMIC_SOURCES_CONFIG_HASH = current_hash + + return _DYNAMIC_SOURCES + + +def is_dynamic_source(source_name: str, dim: int | None = None) -> bool: + """Check whether ``source_name`` is in the dynamic-sources list. + + If ``dim`` is None, returns True if any entry matches the source + name (regardless of any per-dim qualifier). This is the right semantics for + callers that ask "is this source dynamic at all?" (e.g. the static-shapes + early return, or non-tensor int sources which have no dim). + + If ``dim`` is given, returns True only when a matching entry either has no + dim qualifier ("all dims dynamic") or its dim qualifier equals ``dim``. + """ + dynamic_sources = get_dynamic_sources() + for pattern, pat_dim in dynamic_sources: + if pattern == source_name or re.match(pattern, source_name): + if dim is None or pat_dim is None or pat_dim == dim: + pretty = pattern if pat_dim is None else f"{pattern}:{pat_dim}" + log.debug( + "%s was marked dynamic due to dynamic-sources entry: %s", + source_name, + pretty, + ) + symbolic_shape_log.info( + "%s was marked dynamic due to dynamic-sources entry: %s", + source_name, + pretty, + ) + return True + return False + + +def record_automatic_dynamic( + tx: "InstructionTranslatorBase", name: str, e: torch.Tensor +) -> FrameStateSizeEntry: + # This mimics stride inference algorithm in _create_symbolic_sizes_strides_storage_offset + ex_size = e.size() + if not is_sparse_any(e): + ex_stride = e.stride() + dim = e.dim() + + stride = [None] * dim + pending = [(ex_stride[i], -i) for i in range(dim)] + pending.sort(key=_nested_int_aware_sort) + candidates = {} + for i_stride, neg_i in pending: + i = -neg_i + # pyrefly: ignore [unsupported-operation] + stride[i] = candidates.get(i_stride, i_stride) + # pyrefly: ignore [no-matching-overload] + candidates.setdefault(i_stride * ex_size[i], InferStride(i)) + else: + # pyrefly: ignore [implicit-any] + stride = [] + + return process_automatic_dynamic( + # type: ignore[arg-type]ks + tx, + name, + # type: ignore[arg-type] + FrameStateSizeEntry.make_tensor(tuple(ex_size), tuple(stride)), + ) + + +# Same per-dim suffix syntax as _DYNAMIC_SOURCES: optional ":N" restricts the +# match to dim N of the matched tensor. +_UNBACKED_SOURCES: list[tuple[str, int | None]] | None = None +_UNBACKED_SOURCES_CONFIG_HASH: int | None = None + + +def get_unbacked_sources() -> list[tuple[str, int | None]]: + global _UNBACKED_SOURCES, _UNBACKED_SOURCES_CONFIG_HASH + + current_hash = hash(torch.compiler.config.unbacked_sources) + + # If we have already calculated the sources and the config hasn't changed, return cached result + if _UNBACKED_SOURCES is not None and _UNBACKED_SOURCES_CONFIG_HASH == current_hash: + return _UNBACKED_SOURCES + + # Config has changed or first time, (re)calculate the sources + _UNBACKED_SOURCES = [ + _parse_source_entry(s) + for s in torch.compiler.config.unbacked_sources.replace(" ", "").split(",") + if s + ] + _UNBACKED_SOURCES_CONFIG_HASH = current_hash + + return _UNBACKED_SOURCES + + +def is_unbacked_source(source_name: str, dim: int | None = None) -> bool: + """Check whether ``source_name`` is in the unbacked-sources list. + + See :func:`is_dynamic_source` for the ``dim`` argument semantics. + """ + unbacked_sources = get_unbacked_sources() + for pattern, pat_dim in unbacked_sources: + if pattern == source_name or re.match(pattern, source_name): + if dim is None or pat_dim is None or pat_dim == dim: + log.debug( + "%s was marked unbacked due to unbacked-sources entry: %s", + source_name, + pattern if pat_dim is None else f"{pattern}:{pat_dim}", + ) + return True + return False + + +# Cache for the parsed `torch.compiler.config.dynamic_values` config. +_DYNAMIC_VALUES: set[int] | None = None +_DYNAMIC_VALUES_CONFIG_HASH: int | None = None + + +def get_dynamic_values() -> set[int]: + global _DYNAMIC_VALUES, _DYNAMIC_VALUES_CONFIG_HASH + + current_hash = hash(torch.compiler.config.dynamic_values) + + if _DYNAMIC_VALUES is not None and _DYNAMIC_VALUES_CONFIG_HASH == current_hash: + return _DYNAMIC_VALUES + + _DYNAMIC_VALUES = { + int(s) + for s in torch.compiler.config.dynamic_values.replace(" ", "").split(",") + if s + } + _DYNAMIC_VALUES_CONFIG_HASH = current_hash + + return _DYNAMIC_VALUES + + +def is_dynamic_value(value: int) -> bool: + """Return True if ``value`` matches an entry in the dynamic-values list.""" + dynamic_values = get_dynamic_values() + if not dynamic_values: + return False + if isinstance(value, bool): + raise TypeError( + f"is_dynamic_value got a bool ({value}); callers must pass an int" + ) + return value in dynamic_values + + +# Performs automatic dynamic dim determination. +# Returns a SymbolicContext +def _automatic_dynamic( + e: Any, + tx: "InstructionTranslatorBase", + source: Source, + static_shapes: bool, + outer_only: bool = False, + tensor_spec: TensorSpec | None = None, +) -> SymbolicContext: + # strided NT not supported + if e.is_nested and not isinstance( + e, torch.nested._internal.nested_tensor.NestedTensor + ): + unimplemented( + gb_type="Encountered strided NestedTensor in automatic dynamic dim determination", + context="", + explanation="torch.compile does not support strided NestedTensor", + hints=[], + ) + + name = source.name + prior_policy = tx.output.tracing_context.tensor_to_context.get(e, None) + shape_env_to_source_to_symbol_cache = ( + prior_policy.shape_env_to_source_to_symbol_cache if prior_policy else {} + ) + + # Get base context if the tensor is a view + view_base_context: SymbolicContext | None = None + if e._is_view(): + base_source = AttrSource(source, "_base") + view_base_context = _automatic_dynamic(e._base, tx, base_source, static_shapes) + + if is_traceable_wrapper_subclass(e) and not outer_only: + # Get symbolic context for outer tensor + outer_context = _automatic_dynamic( + e, tx, source, static_shapes, outer_only=True + ) + if not isinstance(outer_context, StatefulSymbolicContext): + raise AssertionError( + f"Expected StatefulSymbolicContext, got {type(outer_context)}" + ) + + # Get symbolic contexts for inner tensors + inner_contexts = {} # mapping from attr -> symbolic context + attrs, _ = type(e).__tensor_flatten__(e) + for attr in attrs: + match getattr(e, attr): + case torch.Tensor() as inner_value: + inner_source = AttrSource(source, attr) + inner_contexts[attr] = _automatic_dynamic( + inner_value, tx, inner_source, static_shapes + ) + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + + return SubclassSymbolicContext( + dynamic_sizes=outer_context.dynamic_sizes, + dynamic_strides=outer_context.dynamic_strides, + constraint_sizes=outer_context.constraint_sizes, + constraint_strides=outer_context.constraint_strides, + view_base_context=view_base_context, + tensor_source=outer_context.tensor_source, + shape_env_to_source_to_symbol_cache=outer_context.shape_env_to_source_to_symbol_cache, + inner_contexts=inner_contexts, + track_outer_size_stride=not isinstance( + e, torch.nested._internal.nested_tensor.NestedTensor + ), + ) + + # We preserve the dynamism of inputs. For example, when users call + # make_fx(torch.cond, tracing_mode="symbolic")(*args), inputs have SymInt sizes. + from torch.fx.experimental.symbolic_shapes import has_guarding_hint, is_nested_int + + if any(isinstance(s, SymInt) and not is_nested_int(s) for s in e.size()): + + def _classify_symint(s: Any) -> DimDynamic: + if not isinstance(s, SymInt): + return DimDynamic.STATIC + if not has_guarding_hint(s): + return DimDynamic.UNBACKED + return DimDynamic.DYNAMIC + + return StatefulSymbolicContext( + dynamic_sizes=[_classify_symint(s) for s in e.size()], + dynamic_strides=[DimDynamic.INFER_STRIDE] * e.dim(), + constraint_sizes=[None] * e.dim(), + constraint_strides=[None] * e.dim(), + view_base_context=view_base_context, + tensor_source=source, + shape_env_to_source_to_symbol_cache=shape_env_to_source_to_symbol_cache, + ) + + # Fast path: when the tensor must be static (and not in the dynamic-source + # whitelist), short-circuit to a fully-STATIC StatefulSymbolicContext. + # Important: this must run BEFORE record_automatic_dynamic so that PGO + # frame_state is not polluted by sizes of tensors we are forcing static + # (e.g. nn.Parameter shapes when force_parameter_static_shapes=True). + # Otherwise PGO would later "learn" those dims as dynamic and bypass the + # progressive PGO warm-up that consumers (e.g. test_pgo_dynamic_params) rely on. + if ( + config._dynamic_shapes_spec is None + and static_shapes + and not is_dynamic_source(name) + ): + return StatefulSymbolicContext( + dynamic_sizes=[DimDynamic.STATIC] * e.dim(), + dynamic_strides=[DimDynamic.INFER_STRIDE] * e.dim(), + constraint_sizes=[None] * e.dim(), + constraint_strides=[None] * e.dim(), + view_base_context=view_base_context, + tensor_source=source, + shape_env_to_source_to_symbol_cache=shape_env_to_source_to_symbol_cache, + ) + + # Prep for automatic dynamic + frame_state_entry = record_automatic_dynamic(tx, name, e) + + # TODO: index export_constraints ahead of time so we don't have to + # do a linear scan every time here + t_id = id(e) + # pyrefly: ignore [implicit-any] + dim2constraint = {} + + def update_dim2constraint( + dim: int, constraint_range: "StrictMinMaxConstraint", name: str + ) -> None: + if dim in dim2constraint: + from torch.fx.experimental.symbolic_shapes import StrictMinMaxConstraint + + old_constraint_range, old_name = dim2constraint[dim] + new_constraint_range = StrictMinMaxConstraint( + vr=constraint_range.vr & old_constraint_range.vr, + warn_only=False, + ) + # It is possible for (non-None) old_name and name to be different + # but this will only happen the corresponding Dims can be derived equal. + new_name = old_name or name + dim2constraint[dim] = new_constraint_range, new_name + else: + dim2constraint[dim] = constraint_range, name + + from torch.export.dynamic_shapes import _RelaxedConstraint + + if tx.output.export_constraints is not None: + # type: ignore[iterable] + for constraint in tx.output.export_constraints: + if isinstance(constraint, _RelaxedConstraint): + continue + if constraint.t_id == t_id: + update_dim2constraint( + constraint.dim, constraint.constraint_range, constraint.name + ) + + if config._dynamic_shapes_spec is not None: + return _symbolic_context_from_shapes_spec( + e, + source, + tensor_spec, + view_base_context, + shape_env_to_source_to_symbol_cache, + ) + + dynamic_sizes = [] + dynamic_strides = [] + constraint_sizes = [] + constraint_strides = [] + specialize_on = [] + + for i in range(e.dim()): + # NB: mark dynamic has precedence over static + marked_strict_unbacked = i in getattr(e, "_dynamo_strict_unbacked_indices", ()) + marked_unbacked = i in getattr(e, "_dynamo_unbacked_indices", ()) + marked_dynamic = i in getattr(e, "_dynamo_dynamic_indices", ()) + if marked_dynamic: + symbolic_shape_log.info("marking %s as dynamic (from mark_dynamic)", name) + marked_weak_dynamic = i in getattr( + e, "_dynamo_weak_dynamic_indices", () + ) or i in getattr(e, "_dynamo_propagated_dynamic_indices", ()) + marked_static = i in getattr(e, "_dynamo_static_indices", ()) + + specialize_on.append(getattr(e, "_specialize_on", {}).get(i, [])) + + # Reflect the user directive in the frame_state + # For dynamic, apply None always + + normalized_source_name = normalize_source_name(source.name) + + if marked_dynamic or ( + _is_dim_dynamic_from_source_dynamism(source, normalized_source_name, i) + ): + # TODO: This can be batched + # TODO: Doing this here is kind of sus, maybe better to set this + # up when we initially created the FrameStateSizeEntry to bong + # into the mutable state + log.debug("automatic dynamic %s marked dynamic", name) + mark_size = [auto_unset] * e.dim() + # pyrefly: ignore [unsupported-operation] + mark_size[i] = auto_dynamic + # pyrefly: ignore [bad-argument-type] + frame_state_entry |= FrameStateSizeEntry.make_size(size=mark_size) + + # NB: both static and dynamic have precedence over + automatic_dynamic_size = ( + config.automatic_dynamic_shapes and frame_state_entry.is_size_dynamic(i) + ) + # NB: previously, if size was dynamic, we wouldn't make its stride + # dynamic. But now, because of InferStride concept, we will properly + # not make stride dynamic even if it's wobbling + automatic_dynamic_stride = ( + config.automatic_dynamic_shapes and frame_state_entry.is_stride_dynamic(i) + ) + + if is_dynamic_source(name, i): + log.debug("%s dim %d marked dynamic via dynamic-sources list", name, i) + automatic_dynamic_size = True + + if is_dynamic_value(e.size(i)): + log.debug( + "%s dim %d marked dynamic via dynamic-values list (value=%s)", + name, + i, + e.size(i), + ) + automatic_dynamic_size = True + + if is_unbacked_source(name, i): + log.debug("%s dim %d marked unbacked via unbacked-sources list", name, i) + automatic_dynamic_size = True + + automatic_dynamic = automatic_dynamic_size or automatic_dynamic_stride + + # We will process constraints first, as they will imply that we + # have a dynamic dimension + # Precedence: export constraints > eager constraints + constraint = dim2constraint.get(i) + if constraint is None: + constraint_size = None + constraint_stride = None + if marked_dynamic and not config.allow_ignore_mark_dynamic: + # constraint_stride is deliberaly kept None because no easy way to provide value ranges for mark dynamic + constraint_stride = None + if hasattr(e, "_dynamo_dynamic_range"): + dim_range = [ + dr for dr in e._dynamo_dynamic_range if dr.dim == i + ].pop() + if dim_range.min is None and dim_range.max is None: + constraint_size = RelaxedUnspecConstraint(warn_only=False) + else: + from torch.fx.experimental.symbolic_shapes import ( + StrictMinMaxConstraint, + ) + + constraint_size = StrictMinMaxConstraint( + vr=ValueRanges(lower=dim_range.min, upper=dim_range.max), + warn_only=False, + ) + else: + constraint_size = RelaxedUnspecConstraint(warn_only=False) + elif marked_strict_unbacked: + constraint_size = RelaxedUnspecConstraint(warn_only=False) + elif not marked_static and automatic_dynamic: + set_feature_use("dynamo.automatic_dynamic_shapes", True) + if automatic_dynamic_size: + constraint_size = RelaxedUnspecConstraint(warn_only=True) + if automatic_dynamic_stride: + constraint_stride = RelaxedUnspecConstraint(warn_only=True) + else: + if not marked_static and not config.automatic_dynamic_shapes: + set_feature_use("dynamo.automatic_dynamic_shapes", False) + constraint_size = None + constraint_stride = None + else: + constraint_size, name_ = constraint + constraint_stride = None + dim_name = f"{name}.size()[{i}]" + tx.output.shape_env.source_name_to_debug_name[dim_name] = name_ + constraint_sizes.append(constraint_size) + constraint_strides.append(constraint_stride) + + if marked_unbacked or is_unbacked_source(name, i): + dynamic_size = DimDynamic.UNBACKED + elif ( + constraint_size is not None + or marked_dynamic + or marked_weak_dynamic + or is_nested_int(e.size()[i]) + ): + # NB: We could assert static_shapes is False here, but it + # seems better to allow the user to override symbolic_context in this + # case + if automatic_dynamic: + dynamic_size = get_automatic_dynamic_shapes_mark_as() + else: + dynamic_size = DimDynamic.DYNAMIC + elif static_shapes or config.assume_static_by_default or marked_static: + dynamic_size = DimDynamic.STATIC + else: + # TODO: When does this show up? + if not config.assume_static_by_default: + symbolic_shape_log.info( + "marking %s as dynamic (from assume_static_by_default = False)", + name, + ) + dynamic_size = DimDynamic.DUCK + + if constraint_stride is not None: + dynamic_stride = DimDynamic.DYNAMIC + else: + dynamic_stride = DimDynamic.INFER_STRIDE + + dynamic_sizes.append(dynamic_size) + dynamic_strides.append(dynamic_stride) + + return StatefulSymbolicContext( + dynamic_sizes=dynamic_sizes, + dynamic_strides=dynamic_strides, + constraint_sizes=constraint_sizes, + # pyrefly: ignore [bad-argument-type] + constraint_strides=constraint_strides, + specialize_on=specialize_on, + view_base_context=view_base_context, + tensor_source=source, + shape_env_to_source_to_symbol_cache=shape_env_to_source_to_symbol_cache, + shape_ids=getattr(e, "_dynamo_shape_ids", None), + unbacked_bounds=getattr(e, "_dynamo_unbacked_bounds", None), + excluded_sizes=frame_state_entry.excluded_sizes, + ) + + +# See note [Tensor Fakification and Symbol Caching] +def wrap_to_fake_tensor_and_record( + e: Any, + tx: "InstructionTranslatorBase", + *, + source: Source | None, + is_tensor: bool, + parent_context: Any | None = None, + tensor_spec: TensorSpec | None = None, +) -> Any: + _t0 = time.time_ns() + try: + return _wrap_to_fake_tensor_and_record_impl( + e, + tx, + source=source, + is_tensor=is_tensor, + parent_context=parent_context, + tensor_spec=tensor_spec, + ) + finally: + tx.output.bytecode_tracing_timings.wrap_to_fake_tensor_and_record_ns += ( + time.time_ns() - _t0 + ) + + +def _wrap_to_fake_tensor_and_record_impl( + e: Any, + tx: "InstructionTranslatorBase", + *, + source: Source | None, + is_tensor: bool, + parent_context: Any | None = None, + tensor_spec: TensorSpec | None = None, +) -> Any: + if ( + type(e) in (torch.Tensor, torch.nn.Parameter, FakeTensor) + or isinstance(e, torch.Tensor) + or is_traceable_wrapper_subclass(e) + ): + if source is None: + raise AssertionError("source must not be None for tensor wrapping") + static_shapes, _reason = tensor_always_has_static_shape( + e, + is_tensor, + tensor_source=source, + ) + + if not parent_context: + symbolic_context = _automatic_dynamic( + e, tx, source, static_shapes, tensor_spec=tensor_spec + ) + else: + # Parent contexts are passed in when we are recursively creating + # fake tensors for subclasses. A better design would be not to create a + # parent/child relationship, but to recursively call _automatic_dynamic + # as we recursively call wrap_to_fake_tensor_and_record. This runs + # into bugs around how meta_utils knows and works to create fake tensors + # with tensor subclasses. Ideally, dynamo would drive both the recursive + # wrap_to_fake_tensor_and_record and _automatic_dynamic policy creation. + if not isinstance(source, AttrSource): + raise AssertionError( + f"Expected AttrSource for parent context, got {type(source)}" + ) + inner_context_name = source.member + symbolic_context = parent_context.inner_contexts[inner_context_name] + + log.debug( + "wrap_to_fake %s %s %s %s", + source.name, + tuple(e.shape), + symbolic_context, + type(e), + ) + + # Note [enable_python_dispatcher in dynamo] + # Dynamo disables itself when it runs fake tensor prop, which means that tensor subclasses + # have no way to know (purely based off of global state) if they are currently being run under compile or not. + # we use enable_python_dispatcher mainly to tweak the DispatchKeyState so that subclass authors + # can check it to know if they are running in an eager context or not + with enable_python_dispatcher(): + if tx.fake_mode is None: + raise AssertionError("tx.fake_mode must not be None") + fake_e = wrap_fake_exception( + lambda: tx.fake_mode.from_tensor( + e, # type: ignore[arg-type] + source=source, + symbolic_context=symbolic_context, + ) + ) + if tensor_spec is not None: + _wire_tensor_spec_dims(tensor_spec, fake_e) + if ( + source is not None + and isinstance(fake_e, FakeTensor) # noqa: ISINSTANCE_FAKE_TENSOR + and (sym_val := fake_e.item_memo) is not None + ): + # Match the peephole in FakeTensorConverter.from_real_tensor that + # strips FloatTensorSource before calling create_symbol. Without + # this, the tracked fake source name won't match source_to_var and + # produce_guards_verbose will report "(unknown source)". + if isinstance(source, FloatTensorSource): + item_source = source.base + else: + item_source = CallMethodItemSource(source) + tx.output.tracked_fakes.append( + TrackedFake(sym_val, item_source, symbolic_context) + ) + + if is_traceable_wrapper_subclass(fake_e): + attrs, _ = fake_e.__tensor_flatten__() + for attr in attrs: + fake_inner = getattr(fake_e, attr) + inner = getattr(e, attr) + inner_source = AttrSource(source, attr) + wrap_to_fake_tensor_and_record( + inner, + tx, + source=inner_source, + is_tensor=isinstance(fake_inner, torch.Tensor), + parent_context=symbolic_context, + ) + + tx.output.tracing_context.tensor_to_context[e] = symbolic_context + if is_sparse_any(fake_e): + # TODO: for TensorGuards, this eventually may need more + # fields for the size/stride of any other constituents + values = fake_e._values() if fake_e.is_sparse else fake_e.values() + tx.output.input_source_to_sizes_strides[source] = { + "size": fake_e.size(), + # TODO: revise this, but for now this stride instead of () + # avoids SegFault with PYTORCH_TEST_WITH_DYNAMO=1 + "stride": (1,) * fake_e.ndim, + "values_size": values.size(), + "values_stride": values.stride(), + } + else: + tx.output.input_source_to_sizes_strides[source] = { + "size": fake_e.size(), + "stride": fake_e.stride(), + } + + if ( + is_tensor + and not (static_shapes and source.is_specialized_nn_module()) + and not is_constant_source(source) + ): + tx.output.tracked_fakes.append( + TrackedFake(fake_e, source, symbolic_context) + ) + tx.output.tracked_fakes_id_to_source[id(e)].append(source) + + return fake_e + else: + return e + + +class SourcelessBuilder: + """ + Like builder, but stateless and does not require a source. Useful for simple type->VT objects, or objects + that are being created/evaporated during inlining (ex: consider a locally made list of tensors we then iterate over + .), such a list should not show up as an artifact from inputs, nor in reconstruction, nor in the graph. However, + there may be reasons to represent it as a ListVariable internally. + + NOTE - Objects produced here are born UNGUARDED due to the nature of sources! + + NOTE - This class is very new! It will have some rough edges, but it was created to stem the bleeding of giant + if/else type->VariableTracker trees that were cropping up all over dynamo. + """ + + def __init__(self) -> None: + raise AssertionError("Use SourcelessBuilder.create()") + + @overload + @staticmethod + def create( + tx: "InstructionTranslatorBase", + value: type[set[Any]] + | type[dict[Any, Any]] + | type[tuple[Any, ...]] + | type[list[Any]], + ) -> BuiltinVariable: ... + + @overload + @staticmethod + def create(tx: "InstructionTranslatorBase", value: list[Any]) -> ListVariable: ... + + @overload + @staticmethod + def create( + tx: "InstructionTranslatorBase", value: tuple[Any, ...] + ) -> TupleVariable: ... + + @overload + @staticmethod + def create( + tx: "InstructionTranslatorBase", value: bool | int | float | str + ) -> ConstantVariable: ... + + @overload + @staticmethod + def create(tx: "InstructionTranslatorBase", value: Any) -> VariableTracker: ... + + @staticmethod + def create(tx: "InstructionTranslatorBase", value: Any) -> VariableTracker: + value_type = type(value) + # type: ignore[attr-defined] + fast_handler = SourcelessBuilder._type_handlers.get(value_type) + if fast_handler: + return fast_handler(tx, value) + + if isinstance(value, VariableTracker): + # This is always valid to call, and useful for recursive calls. + return value + elif ( + is_opaque_constant_type(type(value)) + and not isinstance(value, enum.Enum) + and not is_pybind11_enum_member(value) + ): + return CustomClassObjectVariable.create(value, value, tx=tx) + elif is_opaque_symbolic_type(type(value)): + # This is for handling opaque objects in custom ops + fake_script_obj = torch._library.fake_class_registry.maybe_to_fake_obj( + tx.output.fake_mode, value + ) + return CustomClassObjectVariable.create( + value, # pyrefly: ignore[bad-argument-type] + fake_script_obj, + tx=tx, + ) + # type: ignore[attr-defined] + elif isinstance(value, dataclasses._HAS_DEFAULT_FACTORY_CLASS): + return UserDefinedObjectVariable(value) + elif ConstantVariable.is_literal(value): + return ConstantVariable.create(value) + elif callable(value) and trace_rules.lookup_callable(value) is not None: + if trace_rules.is_callable_allowed(value): + tx.output.has_user_defined_allowed_in_graph = True + # pyrefly: ignore[not-callable, bad-argument-count] + return trace_rules.lookup_callable(value)(value) + elif callable(value) and UserDefinedClassVariable.is_supported_new_method( + value + ): + # NamedTuple._make uses an alias of tuple.__new__ + # pyrefly: ignore[not-callable, bad-argument-count, missing-attribute] + obj = trace_rules.lookup_callable(value.__self__)(value.__self__) + return GetAttrVariable(obj, "__new__", py_type=type(value)) + elif is_function_or_wrapper(value): + # pyrefly: ignore[not-callable, bad-argument-count] + return trace_rules.lookup(value)(value) + elif isinstance( + value, + (enum.Enum, torch.DispatchKey, torch._C._functorch.TransformType), + ) or is_pybind11_enum_member(value): + existing = tx.output.side_effects.id_to_variable.get(id(value)) + if existing is not None: + return existing + return tx.output.side_effects.track_mutable( + value, + UserDefinedObjectVariable(value), + AttributeMutationNew, + ) + elif isinstance(value, (type, abc.ABCMeta)): + if issubclass(type(value), type) and issubclass(value, BaseException): + return UserDefinedExceptionClassVariable(value) + return UserDefinedClassVariable(value) + elif isinstance(value, types.MethodWrapperType): + descriptor = inspect.getattr_static(type(value.__self__), value.__name__) + if not isinstance(descriptor, types.WrapperDescriptorType): + raise AssertionError( + f"expected WrapperDescriptorType, got {type(descriptor)}" + ) + return MethodWrapperVariable( + descriptor, SourcelessBuilder.create(tx, value.__self__) + ) + elif isinstance(value, types.MethodType): + if isinstance(value.__self__, (type, abc.ABCMeta)): + # value is a classmethod + if getattr(value.__self__, value.__func__.__name__) != value: + raise AssertionError( + f"Classmethod lookup mismatch: {value.__func__.__name__} on {value.__self__}" + ) + cls_obj_vt = SourcelessBuilder.create(tx, value.__self__) + try: + # pyrefly: ignore[bad-argument-type] + return cls_obj_vt.tp_getattro_impl(tx, value.__func__.__name__) + except NotImplementedError: + pass # failthrough to unimplemented branch + else: + # Instance method — look up the VT for __self__ via side effects + obj_vt = tx.output.side_effects.id_to_variable.get(id(value.__self__)) + if obj_vt is not None: + return torch._dynamo.variables.UserMethodVariable( + value.__func__, obj_vt + ) + elif isinstance(value, torch.fx.graph_module.GraphModule): + return SourcelessGraphModuleVariable(value) + elif isinstance( + value, (importlib.machinery.ModuleSpec, torch.utils._pytree.TreeSpec) + ): + return UserDefinedObjectVariable(value) + elif isinstance(value, (re.Pattern, re.Match)): + return ConstantLikeVariable(value) + elif isinstance(value, torch._dynamo.variables.lazy.LazySymNodeFormatString): + try: + return ConstantVariable.create(str(value)) + # If we cannot create due to error in str() call, we should + # try explicitly for string format variable + except ( + torch._dynamo.exc.UserError, + torch.fx.experimental.symbolic_shapes.GuardOnDataDependentSymNode, + ): + return StringFormatVariable.create( + value.fmt_var.as_python_constant(), + [value.sym_node_var], + {}, + ) + elif isinstance(value, type(torch._higher_order_ops.flex_attention_backward)): + return torch._dynamo.variables.higher_order_ops.FlexAttentionBackwardHighOrderVariable( + value + ) + elif isinstance( + value, + ( + types.GenericAlias, + types.UnionType, + # `typing.Any | X` (and `typing.Union[...]`) evaluates to a + # `typing._UnionGenericAlias` on Python <= 3.10, not a + # `types.UnionType` + typing._UnionGenericAlias, # type: ignore[attr-defined] + ), + ): + return TypingVariable(value) + elif is_namedtuple(value): + output = [ + SourcelessBuilder.create(tx, getattr(value, name)) + for name in namedtuple_fields(type(value)) + ] + tuple_vt = TupleVariable(output, mutation_type=ValueMutationNew()) + return UserDefinedTupleVariable.get_vt_cls(type(value))( + value, tuple_vt=tuple_vt + ) + elif ( + isinstance(value, torch.SymInt) + and value.node.expr in tx.output.bound_symbols + ): + proxy = tx.output.bound_symbols[value.node.expr] + return SymNodeVariable.create(tx, proxy) + elif isinstance(value, slice): + items = [ + SourcelessBuilder.create(tx, getattr(value, k)) + for k in ("start", "stop", "step") + ] + return SliceVariable(items, tx) # pyrefly: ignore[bad-argument-type] + elif isinstance(value, torch.nn.parallel.distributed.DistributedDataParallel): + return UnspecializedNNModuleVariable(value) + elif istype(value, object): + return ObjectVariable(value) + elif ( + sys.version_info >= (3, 15) + and type(value) is builtins.sentinel # pyrefly: ignore [missing-attribute] + ): + return SentinelVariable(value) + unimplemented( + gb_type="Unexpected type in sourceless builder", + context=f"{value_type.__module__}.{value_type.__qualname__}", + explanation=f"SourcelessBuilder.create does not know how to wrap {value_type}", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + + @staticmethod + def wrap_constant_literal(value: object) -> VariableTracker: + if not ConstantVariable.is_literal(value): + raise AssertionError(f"Expected literal value, got {type(value)}") + return ConstantVariable.create(value=value) + + @staticmethod + def make_type_handlers() -> dict[ + type, Callable[["InstructionTranslatorBase", Any], VariableTracker] + ]: + create = SourcelessBuilder.create + handlers: dict[ + type, Callable[[InstructionTranslatorBase, Any], VariableTracker] + ] = {} + for t in common_constant_types: + handlers[t] = lambda tx, value: ConstantVariable(value) + handlers[set] = lambda tx, value: SetVariable( + [create(tx, x) for x in value], mutation_type=ValueMutationNew() + ) + handlers[OrderedSet] = lambda tx, value: OrderedSetVariable( + [create(tx, x) for x in value], mutation_type=ValueMutationNew() + ) + handlers[dict] = lambda tx, value: ConstDictVariable( + {create(tx, k): create(tx, v) for k, v in value.items()}, + mutation_type=ValueMutationNew(), + ) + handlers[list] = lambda tx, value: ListVariable( + [create(tx, x) for x in value], mutation_type=ValueMutationNew() + ) + handlers[tuple] = lambda tx, value: TupleVariable( + [create(tx, x) for x in value] + ) + handlers[torch.Size] = lambda tx, value: SizeVariable( + [create(tx, x) for x in value] + ) + handlers[collections.OrderedDict] = lambda tx, value: OrderedDictVariable( + {create(tx, k): create(tx, v) for k, v in value.items()}, + mutation_type=ValueMutationNew(), + ) + # immutable_dict is a dict subclass; represent it as a plain dict VT. + handlers[immutable_dict] = handlers[dict] + handlers[immutable_list] = handlers[list] + # Sourceless MappingProxyType object can be encountered while tracing + # type.__dict__["__dict__"].__get__ + handlers[types.MappingProxyType] = lambda tx, value: MappingProxyVariable( + ConstDictVariable( + {create(tx, k): create(tx, v) for k, v in value.items()}, + mutation_type=ValueMutationNew(), + ), + ) + handlers[types.GetSetDescriptorType] = ( + lambda tx, value: GetSetDescriptorVariable(value) + ) + handlers[types.MemberDescriptorType] = ( + lambda tx, value: MemberDescriptorVariable(value) + ) + handlers[inspect.Parameter] = lambda tx, value: UserDefinedObjectVariable( + value, mutation_type=ValueMutationNew() + ) + handlers[random.Random] = lambda tx, value: RandomClassVariable() + handlers[types.ModuleType] = lambda tx, value: PythonModuleVariable(value) + + handlers[torch.DispatchKeySet] = lambda tx, value: DispatchKeySetVariable( + value, mutation_type=ValueMutationNew() + ) + handlers[torch._functorch.pyfunctorch.FuncTorchInterpreter] = ( + lambda tx, value: FuncTorchInterpreterVariable( + value, mutation_type=ValueMutationNew() + ) + ) + + handlers[torch.distributions.constraints._Real] = ( + lambda tx, value: UserDefinedObjectVariable( + value, mutation_type=ValueMutationNew() + ) + ) + handlers[torch.distributions.constraints._Interval] = ( + lambda tx, value: UserDefinedObjectVariable( + value, mutation_type=ValueMutationNew() + ) + ) + handlers[torch.distributions.constraints.Constraint] = ( + lambda tx, value: UserDefinedObjectVariable( + value, mutation_type=ValueMutationNew() + ) + ) + + def passthrough(tx: "InstructionTranslatorBase", value: T) -> T: + return value + + for cls in VariableTrackerMeta.all_subclasses: + handlers[cls] = passthrough + return handlers + + +SourcelessBuilder._type_handlers = SourcelessBuilder.make_type_handlers() + + +class SourcelessUserDefinedObjectBuilder: + """ + SourceLessBuilder does not return a UserDefinedObjectVariable, but in some + cases it might be ok to return UserDefinedObjects. In such case, use this + builder. + """ + + def __init__(self) -> None: + raise AssertionError("Use SourcelessUserDefinedObjectBuilder.create()") + + @staticmethod + def create(tx: "InstructionTranslatorBase", value: Any) -> VariableTracker: + value_type = type(value) + if issubclass(value_type, MutableMapping): + return MutableMappingVariable(value, mutation_type=ValueMutationNew()) + elif isinstance(value, torch.nn.Module): + return UnspecializedNNModuleVariable( + value, mutation_type=ValueMutationNew() + ) + else: + return UserDefinedObjectVariable(value, mutation_type=ValueMutationNew()) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/builtin.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/builtin.py new file mode 100644 index 0000000000000000000000000000000000000000..e81ae0d93385538feaf8327f3d2bb50e49b5397a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/builtin.py @@ -0,0 +1,3860 @@ +""" +Built-in function and type variable tracking for TorchDynamo's symbolic execution. + +This module contains variable tracker classes for Python built-in functions, types, +and operations during graph compilation. It handles symbolic execution of: + +- Built-in functions (len, getattr, isinstance, etc.) +- Type constructors (int, float, str, list, dict, etc.) +- Built-in operators and methods +- Special Python constructs (super, hasattr, etc.) + +Key classes: +- BuiltinVariable: Tracks built-in functions and handles their execution +- TypeVariable: Manages type constructor calls and type checking +- SuperVariable: Handles super() calls in class hierarchies + +These variable trackers ensure that built-in Python operations are correctly +handled during symbolic execution, either by executing them directly when safe +or by creating appropriate graph nodes when needed. +""" + +import abc +import ast +import builtins +import contextlib +import functools +import inspect +import itertools +import logging +import math +import operator +import sys +import types +import typing +from collections import defaultdict, OrderedDict +from collections.abc import Callable, Iterable, Sequence +from typing import Any, NoReturn, TYPE_CHECKING + +import torch +from torch.overrides import BaseTorchFunctionMode +from torch.utils._python_dispatch import is_traceable_wrapper_subclass + +from .. import graph_break_hints, polyfills, variables +from ..exc import ( + handle_observed_exception, + ObservedAttributeError, + ObservedTypeError, + ObservedUserStopIteration, + raise_observed_exception, + raise_type_error, + raise_value_error, + unimplemented, + Unsupported, + UserError, + UserErrorType, +) +from ..guards import GuardBuilder, install_guard +from ..source import ( + AttrSource, + GetItemSource, + GlobalSource, + is_constant_source, + LocalSource, + Source, + TypeSource, +) +from ..utils import ( + check_constant_args, + check_numpy_ndarray_args, + check_unspec_or_constant_args, + check_unspec_python_args, + dict_methods, + extract_fake_example_value, + get_fake_value, + is_tensor_getset_descriptor, + istype, + numpy_operator_wrapper, + proxy_args_kwargs, + raise_args_mismatch, + str_methods, + tensortype_to_dtype, + unpack_iterable, +) +from .base import ( + AsPythonConstantNotImplementedError, + GetSet, + Member, + ValueMutationNew, + VariableTracker, +) +from .constant import ConstantVariable, FakeIdVariable +from .dicts import ( + ConstDictVariable, + DictItemsVariable, + DictKeysVariable, + DictViewVariable, + OrderedDictVariable, +) +from .hashable import is_hashable +from .lists import BaseListVariable, ListVariable, TupleIteratorVariable, TupleVariable +from .misc import CellVariable, NullVariable, StringFormatVariable +from .object_protocol import ( + _NO_DEFAULT, + binary_iop, + binary_op, + generic_delitem, + generic_getattr, + generic_getitem, + generic_getiter, + generic_hash, + generic_is_true, + generic_issubclass, + generic_repr, + generic_richcompare, + generic_setitem, + generic_size, + generic_str, + maybe_get_python_type, + pycallable_check, + pyiter_check, + pylong_from_base, + pynumber_absolute, + pynumber_add, + pynumber_float, + pynumber_index, + pynumber_inplace_add, + pynumber_inplace_matrix_multiply, + pynumber_inplace_multiply, + pynumber_int, + pynumber_invert, + pynumber_matrix_multiply, + pynumber_multiply, + pynumber_negative, + pynumber_positive, + pynumber_tobase, + pysequence_check, + pysequence_contains, + python_constant_richcompare_impl, + ternary_iop, + ternary_op, + type_implements_mp_length, + type_implements_sq_length, + vt_identity_compare, +) +from .sets import FrozensetVariable, SetVariable +from .tensor import ( + FakeItemVariable, + supported_comparison_ops, + SymNodeVariable, + TensorVariable, + UnspecializedPythonVariable, +) +from .user_defined import UserDefinedObjectVariable, UserDefinedVariable + + +if TYPE_CHECKING: + # Cyclic dependency... + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + +log = logging.getLogger(__name__) + + +IN_PLACE_DESUGARING_MAP = { + operator.iadd: operator.add, + operator.isub: operator.sub, + operator.imul: operator.mul, + operator.ifloordiv: operator.floordiv, + operator.itruediv: operator.truediv, + operator.imod: operator.mod, + operator.imatmul: operator.imatmul, + operator.ilshift: operator.lshift, + operator.irshift: operator.rshift, + operator.ipow: operator.pow, + operator.iand: operator.and_, + operator.ior: operator.or_, + operator.ixor: operator.xor, +} + +_BUILTIN_CONSTANT_FOLDABLE_METHODS: dict[type, frozenset[str]] = { + int: frozenset({"__new__", "from_bytes"}), + bool: frozenset({"__new__", "from_bytes"}), + float: frozenset({"fromhex", "hex"}), +} +if sys.version_info >= (3, 14): + _BUILTIN_CONSTANT_FOLDABLE_METHODS[complex] = frozenset({"from_number"}) + + +_HandlerCallback = Callable[ + ["InstructionTranslatorBase", typing.Any, typing.Any], VariableTracker | None +] +_TrackersType = type[VariableTracker] | tuple[type[VariableTracker], ...] +_OPERATOR_TO_DUNDER: dict[Callable[..., Any], str] = { + operator.eq: "__eq__", + operator.ne: "__ne__", + operator.lt: "__lt__", + operator.le: "__le__", + operator.gt: "__gt__", + operator.ge: "__ge__", +} + + +bin_ops = ( + operator.pow, + operator.mul, + operator.matmul, + operator.floordiv, + operator.truediv, + operator.mod, + operator.add, + operator.lt, + operator.gt, + operator.ge, + operator.le, + operator.ne, + operator.eq, + operator.sub, + operator.ipow, + operator.imul, + operator.imatmul, + operator.ifloordiv, + operator.itruediv, + operator.imod, + operator.iadd, + operator.isub, +) + +bin_int_ops = ( + operator.and_, + operator.or_, + operator.xor, + operator.iand, + operator.ixor, + operator.ior, +) + +un_int_ops = (operator.invert,) + +tensor_and_int_ops = ( + operator.lshift, + operator.rshift, + operator.ilshift, + operator.irshift, + operator.getitem, +) + +un_ops = ( + operator.abs, + operator.pos, + operator.neg, + operator.not_, # Note: this has a local scalar dense call + operator.length_hint, +) + +_SET_LIKE_OP_SUPPORT: tuple[type[VariableTracker], ...] = ( + DictItemsVariable, + DictKeysVariable, + SetVariable, + UserDefinedObjectVariable, +) + +BUILTIN_TO_TENSOR_FN_MAP: dict[Callable[..., Any], Callable[..., Any]] = {} + +# These functions represent the r* versions of the above ops +# Basically, if __add__(1, Tensor) is called, it is translated +# to __radd__(Tensor, 1). +# In the builtin var, we check if there is a tensor in the first args position, +# if not, we swap the args and use the r* version of the op. +BUILTIN_TO_TENSOR_RFN_MAP: dict[Callable[..., Any], Callable[..., Any]] = {} + +# Sentinel for `inspect.getattr_static` lookups that must distinguish +# "attribute absent" from "attribute is None" (e.g. `__reversed__ = None` +# opt-out). +_MISSING_SENTINEL = object() + +_COMPUTED_LAZY_CONSTANT_OPS: frozenset[Callable[..., Any]] = frozenset( + [ + operator.add, + operator.sub, + operator.mul, + ] +) + + +def _try_computed_lazy_constant( + fn: Callable[..., Any], args: list[VariableTracker] +) -> VariableTracker | None: + """Build a ComputedLazyConstantVariable for fn(*args), or None to fall back.""" + from .lazy import ComputedLazyConstantVariable, LazyConstantVariable + + fn = IN_PLACE_DESUGARING_MAP.get(fn, fn) + if fn not in _COMPUTED_LAZY_CONSTANT_OPS or len(args) != 2: + return None + any_unrealized = False + for arg in args: + if ( + isinstance(arg, (LazyConstantVariable, ComputedLazyConstantVariable)) + and not arg.is_realized() + ): + any_unrealized = True + elif not isinstance(arg, ConstantVariable): + return None + if not any_unrealized: + return None + return ComputedLazyConstantVariable.create(fn, args) + + +def populate_builtin_to_tensor_fn_map() -> None: + global BUILTIN_TO_TENSOR_FN_MAP + if len(BUILTIN_TO_TENSOR_FN_MAP) > 0: + # Only populate once; after there are elements present no need to + # repopulate + return + most_recent_func: Callable[..., Any] | None = None + + class GetMethodMode(BaseTorchFunctionMode): + """ + Mode to extract the correct methods from torch function invocations + (Used to get the correct torch.Tensor methods from builtins) + """ + + def __torch_function__( + self, + func: Callable[..., Any], + types: Any, + args: Sequence[Any] = (), + kwargs: dict[str, Any] | None = None, + ) -> Any: + kwargs = kwargs or {} + nonlocal most_recent_func + most_recent_func = func + return func(*args, **kwargs) + + inp0 = torch.ones(1) + inp1 = torch.ones(1) + inp0_int = torch.ones(1, dtype=torch.int32) + inp1_int = torch.ones(1, dtype=torch.int32) + with GetMethodMode(): + setups_and_oplists: list[tuple[Callable[..., Any], Iterable[Any]]] = [ + (lambda o: o(inp0), un_ops), + (lambda o: o(inp0_int), un_int_ops), + (lambda o: o(inp0, inp1), bin_ops), + (lambda o: o(inp0_int, inp1_int), bin_int_ops), + (lambda o: o(inp0_int, 0), tensor_and_int_ops), + ] + for setup_fn, op_list in setups_and_oplists: + for op in op_list: + setup_fn(op) + if most_recent_func is None: + raise AssertionError( + f"most_recent_func is None after setup for op {op}" + ) + BUILTIN_TO_TENSOR_FN_MAP[op] = most_recent_func + + # gather the reverse functions + rsetups_and_oplists: list[tuple[Callable[..., Any], Iterable[Any]]] = [ + ( + lambda o: o(1, inp1), + bin_ops, + ), # Get r* ops, (ex. __sub__(int, Tensor) -> __rsub__(Tensor, int)) + (lambda o: o(1, inp1_int), bin_int_ops), + (lambda o: o(0, inp0_int), tensor_and_int_ops), + ] + + rskips = {operator.matmul, operator.imatmul, operator.getitem} + for setup_fn, op_list in rsetups_and_oplists: + for op in op_list: + if op in rskips: + continue + setup_fn(op) + if most_recent_func is None: + raise AssertionError( + f"most_recent_func is None after setup for reverse op {op}" + ) + if most_recent_func != BUILTIN_TO_TENSOR_FN_MAP[op]: + BUILTIN_TO_TENSOR_RFN_MAP[op] = most_recent_func + + +class BaseBuiltinVariable(VariableTracker): + """ + Common base class for all builtin variable trackers (BuiltinVariable, + DictBuiltinVariable, IterBuiltinVariable, and future specialized builtins). + + Provides shared implementations for guard installation, hasattr tracing, + and Python-level hashability/equality. + + Specialized subclasses (e.g. DictBuiltinVariable) set `_fn` as a class + attribute. BuiltinVariable stores the callable on the instance as `self.fn` + and overrides as_python_constant / reconstruct / tp_getattro_impl accordingly. + """ + + _fn: Any = None + + # Type attribute readers shared by BaseBuiltinVariable and BuiltinVariable. + # Each reader declines (returns None) when the wrapped callable is not a type, + # letting getattro_impl fall through to its dynamic getattr handling. + # CPython classification (Objects/typeobject.c): + # __bases__ -> type_getsets[] type_get_bases (getset) + # __base__ -> type_members[] {T_OBJECT, offsetof(tp_base), Py_READONLY} + # __flags__ -> type_members[] {T_ULONG, offsetof(tp_flags), Py_READONLY} + def _type_get_bases( + self: "BaseBuiltinVariable", tx: "InstructionTranslatorBase" + ) -> "VariableTracker | None": + fn = self.as_python_constant() + if not isinstance(fn, type): + return None + source = self.source and AttrSource(self.source, "__bases__") + items = [ + VariableTracker.build(tx, b, source and GetItemSource(source, i)) + for i, b in enumerate(fn.__bases__) + ] + return variables.TupleVariable(items, source=source) + + def _type_get_base( + self: "BaseBuiltinVariable", tx: "InstructionTranslatorBase" + ) -> "VariableTracker | None": + fn = self.as_python_constant() + if not isinstance(fn, type): + return None + source = self.source and AttrSource(self.source, "__base__") + return VariableTracker.build(tx, fn.__base__, source) + + def _type_get_flags( + self: "BaseBuiltinVariable", tx: "InstructionTranslatorBase" + ) -> "VariableTracker | None": + fn = self.as_python_constant() + if not isinstance(fn, type): + return None + source = self.source and AttrSource(self.source, "__flags__") + return VariableTracker.build(tx, fn.__flags__, source) + + tp_getset = {"__bases__": GetSet(_type_get_bases, None)} + tp_members = { + "__base__": Member(_type_get_base, None), + "__flags__": Member(_type_get_flags, None), + } + + @classmethod + def create_with_source(cls, value: Any, source: Source) -> "BaseBuiltinVariable": + install_guard(source.make_guard(GuardBuilder.BUILTIN_MATCH)) + return cls(source=source) + + def as_python_constant(self) -> Any: + return self._fn + + def reconstruct(self, codegen: "PyCodegen") -> None: + name = self.as_python_constant().__name__ + if name in codegen.tx.f_globals: + raise AssertionError("shadowed global") + codegen.append_output(codegen.create_load_global(name, add=True)) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + # Declarative type-attribute dispatch, mirroring the consultation at the + # top of VariableTracker.getattro_impl. Inlined here because this + # override keeps its own GetAttrVariable fallback instead of delegating + # to super(). + fn = self.as_python_constant() + source = self.source and AttrSource(self.source, name) + attr = getattr(fn, name, None) + return variables.GetAttrVariable( + self, name, py_type=type(attr) if attr is not None else None, source=source + ) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + return VariableTracker.build(tx, hasattr(self.as_python_constant(), name)) # type: ignore[return-value] + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # CPython meth_hash: https://github.com/python/cpython/blob/e76aa128fe/Objects/methodobject.c#L319 + return hash(self.as_python_constant()), False + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + return python_constant_richcompare_impl(self, tx, other, op) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "__str__" and len(args) == 1 and not kwargs: + arg = args[0] + if self.as_python_constant() is object: + return generic_repr(tx, arg) + if self.as_python_constant() is type: + if isinstance(arg, variables.UserDefinedClassVariable): + return VariableTracker.build(tx, type.__str__(arg.value)) + if arg.is_python_constant() and isinstance( + arg.as_python_constant(), type + ): + return VariableTracker.build( + tx, type.__str__(arg.as_python_constant()) + ) + return generic_str(tx, arg) + if name == "__repr__" and len(args) == 1 and not kwargs: + arg = args[0] + if self.as_python_constant() is object and isinstance( + arg, variables.UserDefinedObjectVariable + ): + return VariableTracker.build(tx, object.__repr__(arg.value)) + if self.as_python_constant() is type: + if isinstance(arg, variables.UserDefinedClassVariable): + return VariableTracker.build(tx, type.__repr__(arg.value)) + if arg.is_python_constant() and isinstance( + arg.as_python_constant(), type + ): + return VariableTracker.build( + tx, type.__repr__(arg.as_python_constant()) + ) + return generic_repr(tx, arg) + return super().call_method(tx, name, args, kwargs) + + +def _uses_custom_classinfo_check( + type_info: Any, + *, + use_instancecheck: bool = True, + use_subclasscheck: bool = True, +) -> bool: + if isinstance(type_info, tuple): + return any(_uses_custom_classinfo_check(item) for item in type_info) + if isinstance(type_info, types.UnionType): + return any( + _uses_custom_classinfo_check(item) for item in typing.get_args(type_info) + ) + if typing.get_origin(type_info) is typing.Union: + typing_union_uses_instancecheck = sys.version_info >= (3, 12) + return any( + _uses_custom_classinfo_check( + item, + use_instancecheck=typing_union_uses_instancecheck, + use_subclasscheck=True, + ) + for item in typing.get_args(type_info) + ) + if isinstance(type_info, type): + if type_info in tensortype_to_dtype: + return False + + type_info_meta = type(type_info) + instancecheck = getattr(type_info_meta, "__instancecheck__", None) + subclasscheck = getattr(type_info_meta, "__subclasscheck__", None) + if ( + instancecheck is type.__instancecheck__ + and subclasscheck is type.__subclasscheck__ + ): + return False + + if issubclass(type_info, torch.Tensor) and ( + type_info_meta.__module__, + type_info_meta.__qualname__, + ) in { + ("torch.nn.parameter", "_ParameterMeta"), + ("torch.nn.parameter", "_BufferMeta"), + ("torch.distributed.fsdp._flat_param", "_FlatParameterMeta"), + }: + return False + + return ( + use_instancecheck + and instancecheck is not type.__instancecheck__ + and instancecheck is not abc.ABCMeta.__instancecheck__ + ) or ( + use_subclasscheck + and subclasscheck is not type.__subclasscheck__ + and subclasscheck is not abc.ABCMeta.__subclasscheck__ + ) + return False + + +class BuiltinVariable(BaseBuiltinVariable): + """ + A VariableTracker that represents a built-in value (functions and operators). + A lot of the code here assumes it will be a function object. + + The BuiltinVariable class wraps Python built-in functions (like len, isinstance, etc.) + and operators (like +, -, *, etc.) to enable symbolic execution during tracing. This allows + Dynamo to properly handle these operations when converting Python code to FX graphs while + maintaining correct semantics and enabling optimizations. + """ + + _SENTINEL = object() + _nonvar_fields = { + "fn", + *VariableTracker._nonvar_fields, + } + + # __name__ -> type_getsets[] type_get_name (getset). Unlike the type-attribute + # readers on BaseBuiltinVariable, BuiltinVariable exposes __name__ for any + # wrapped callable (not just types), so it never declines. + def _builtin_type_get_name( + self: "BuiltinVariable", tx: "InstructionTranslatorBase" + ) -> "VariableTracker | None": + source = self.source and AttrSource(self.source, "__name__") + return VariableTracker.build(tx, self.fn.__name__, source) + + tp_getset = { + "__name__": GetSet(_builtin_type_get_name, None), + } + + @classmethod + def create_with_source(cls, value: Any, source: Source) -> "BuiltinVariable": + install_guard(source.make_guard(GuardBuilder.BUILTIN_MATCH)) + return cls(value, source=source) + + @staticmethod + @functools.cache + def _constant_fold_functions() -> set[Callable[..., Any]]: + fns: set[Callable[..., Any]] = { + abs, + all, + any, + ascii, + bin, + bool, + callable, + chr, + complex, + divmod, + float, + format, + getattr, + hex, + int, + len, + max, + min, + oct, + ord, + pow, + repr, + round, + str, + str.format, + sum, + type, + operator.abs, + operator.pos, + operator.neg, + operator.not_, + operator.truth, + operator.invert, + operator.pow, + operator.mul, + operator.matmul, + operator.floordiv, + operator.truediv, + operator.mod, + operator.add, + operator.sub, + operator.getitem, + operator.length_hint, + operator.lshift, + operator.rshift, + operator.and_, + operator.or_, + operator.xor, + operator.ipow, + operator.imul, + operator.imatmul, + operator.ifloordiv, + operator.itruediv, + operator.imod, + operator.iadd, + operator.isub, + operator.ilshift, + operator.irshift, + operator.iand, + operator.ixor, + operator.ior, + operator.index, + } + from .tensor import supported_comparison_ops + + fns.update(supported_comparison_ops.values()) + fns.update(x for x in math.__dict__.values() if isinstance(x, type(math.sqrt))) + return fns + + def can_constant_fold_through(self) -> bool: + return self.fn in self._constant_fold_functions() + + @staticmethod + @functools.cache + def _fx_graph_functions() -> set[Callable[..., Any]]: + fns = { + operator.abs, + operator.pos, + operator.neg, + operator.not_, + operator.invert, + operator.pow, + operator.mul, + operator.matmul, + operator.floordiv, + operator.truediv, + operator.mod, + operator.add, + operator.lt, + operator.gt, + operator.ge, + operator.le, + operator.ne, + operator.eq, + operator.sub, + operator.length_hint, + operator.lshift, + operator.rshift, + operator.and_, + operator.or_, + operator.xor, + operator.ipow, + operator.imul, + operator.imatmul, + operator.ifloordiv, + operator.itruediv, + operator.getitem, + operator.imod, + operator.iadd, + operator.isub, + operator.ilshift, + operator.irshift, + operator.iand, + operator.ixor, + operator.ior, + } + return fns # type: ignore[return-value] + + @staticmethod + @functools.cache + def _binops() -> dict[ + Callable[..., object], tuple[list[str], Callable[..., object]] + ]: + # function -> ([forward name, reverse name, in-place name], in-place op) + fns: dict[Callable[..., object], tuple[list[str], Callable[..., object]]] = { + # NB: The follow binary operators are not supported for now, since the + # corresponding magic methods aren't defined on SymInt / SymFloat: + # operator.matmul + # divmod + # operator.and_ + # operator.or_ + } + return fns + + @staticmethod + @functools.cache + def _binop_handlers() -> dict[ + Callable[..., object], + list[ + tuple[ + tuple[ + type[VariableTracker], + _TrackersType, + ], + _HandlerCallback, + ] + ], + ]: + # Multiple dispatch mechanism defining custom binop behavior for certain type + # combinations. Handlers are attempted in order, and will be used if the type checks + # match. They are expected to have the signature: + # fn(tx, arg0: VariableTracker, arg1: VariableTracker) -> VariableTracker + from .functions import BaseUserFunctionVariable + from .nn_module import NNModuleVariable + from .tensor import supported_const_comparison_ops + from .torch import BaseTorchVariable + + # Override table contains: op_fn -> [list of handlers] + op_handlers: dict[Any, list[Any]] = {} + for ( + op, + (magic_method_names, in_place_op), + ) in BuiltinVariable._binops().items(): + op_handlers[op] = [] + op_handlers[in_place_op] = [] + + forward_name, reverse_name, inplace_name = magic_method_names + + # User-defined args (highest precedence) + def user_defined_handler( + tx: "InstructionTranslatorBase", + a: VariableTracker, + b: VariableTracker, + *, + forward_name: str = forward_name, + reverse_name: str = reverse_name, + ) -> VariableTracker: + # Manually handle reversing logic if needed (e.g. call __radd__) + + # TODO: If we expand this to handle tensor args, we need to manually + # handle cases like this: + # + # class A(int): + # def __radd__(self, other): + # print("woof") + # torch.randn(3) + A(3) + # + # In this example, A.__radd__() is not called -> nothing is printed, because + # Tensor.__add__ only does a subtype test against int, ignoring the subclass. + # To be fully correct, we should not call A.__radd__() here, and there may be + # other cases to reason about and add exceptions for. + if isinstance(a, UserDefinedVariable): + return a.call_method(tx, forward_name, [b], {}) + else: + return b.call_method(tx, reverse_name, [a], {}) + + op_handlers[op].append( + ((UserDefinedVariable, VariableTracker), user_defined_handler) + ) + op_handlers[op].append( + ((VariableTracker, UserDefinedVariable), user_defined_handler) + ) + + def user_defined_inplace_handler( + tx: "InstructionTranslatorBase", + a: VariableTracker, + b: VariableTracker, + *, + forward_name: str = inplace_name, + ) -> VariableTracker: + return a.call_method(tx, forward_name, [b], {}) + + op_handlers[in_place_op].append( + ((UserDefinedVariable, VariableTracker), user_defined_inplace_handler) + ) + op_handlers[in_place_op].append( + ((VariableTracker, UserDefinedVariable), user_defined_inplace_handler) + ) + + # Dynamic shape args + def dynamic_handler( + tx: "InstructionTranslatorBase", + a: VariableTracker, + b: VariableTracker, + *, + fn: Callable[..., Any] = op, + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", fn, *proxy_args_kwargs([a, b], {}) + ), + ) + + op_handlers[op].append( + ((SymNodeVariable, VariableTracker), dynamic_handler) + ) + op_handlers[op].append( + ((VariableTracker, SymNodeVariable), dynamic_handler) + ) + + # NB: Prefer out-of-place op when calling in-place op to generate valid graph + op_handlers[in_place_op].append( + ((SymNodeVariable, VariableTracker), dynamic_handler) + ) + op_handlers[in_place_op].append( + ((VariableTracker, SymNodeVariable), dynamic_handler) + ) + + # Special cases - lower precedence but still prefer these over constant folding + + def create_cmp_op_handlers( + op: Callable[..., Any], + ) -> list[tuple[tuple[_TrackersType, _TrackersType], _HandlerCallback]]: + def compare_by_value( + tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker: + try: + return VariableTracker.build(tx, op(a.value, b.value)) # type: ignore[attr-defined] + except TypeError as exc: + raise_observed_exception( + type(exc), + tx, + args=list(exc.args), + ) + + result: list[ + tuple[ + tuple[ + _TrackersType, + _TrackersType, + ], + _HandlerCallback, + ] + ] = [((ConstantVariable, ConstantVariable), compare_by_value)] + + if op in _OPERATOR_TO_DUNDER: + # For constants, speedup the comparison instead of going + # through generic_richcompare. Removing this line causes + # major regression for pr time benchmark - add_loop_eager. + result = [ + ((ConstantVariable, ConstantVariable), compare_by_value), + ] + + op_var = BuiltinVariable(op) + # Special handling of SymNode variable + result.extend( + [ + ( + (SymNodeVariable, VariableTracker), + op_var._comparison_with_symnode, + ), + ( + (VariableTracker, SymNodeVariable), + op_var._comparison_with_symnode, + ), + ] + ) + + # COMPARE_OP (a == b) dispatches through generic_richcompare, + # which implements do_richcompare via tp_richcompare_impl slots. + # See object_protocol.py for details. + dunder = _OPERATOR_TO_DUNDER[op] + + def handler( + tx: "InstructionTranslatorBase", + a: VariableTracker, + b: VariableTracker, + ) -> VariableTracker: + return generic_richcompare(tx, a, b, dunder) + + result.append(((VariableTracker, VariableTracker), handler)) + return result + + result = [((ConstantVariable, ConstantVariable), compare_by_value)] + + if op in supported_const_comparison_ops.values() and op.__name__.startswith( + "is_" + ): + # Tensor is None, List is not None, etc + none_result = op(object(), None) + + def never( + tx: "InstructionTranslatorBase", + a: VariableTracker, + b: VariableTracker, + ) -> VariableTracker: + return VariableTracker.build(tx, none_result) + + obj_op_none = never + none_op_obj = never + + types_that_are_never_none = ( + TensorVariable, + SymNodeVariable, + NNModuleVariable, + BaseListVariable, + UserDefinedVariable, + BaseUserFunctionVariable, + ConstDictVariable, + BaseTorchVariable, + ) + result.extend( + [ + ( + (types_that_are_never_none, ConstantVariable), + obj_op_none, + ), + ( + (ConstantVariable, types_that_are_never_none), + none_op_obj, + ), + ] + ) + + op_var = BuiltinVariable(op) + result.extend( + [ + ( + (TensorVariable, VariableTracker), + op_var._comparison_with_tensor, + ), + ( + (VariableTracker, TensorVariable), + op_var._comparison_with_tensor, + ), + ( + (SymNodeVariable, VariableTracker), + op_var._comparison_with_symnode, + ), + ( + (VariableTracker, SymNodeVariable), + op_var._comparison_with_symnode, + ), + ] + ) + + def handle_is( + tx: "InstructionTranslatorBase", + left: VariableTracker, + right: VariableTracker, + ) -> VariableTracker | None: + result = vt_identity_compare(left, right) + if result is None: + return None + is_same = result.as_python_constant() + return VariableTracker.build( + tx, is_same if op.__name__ == "is_" else not is_same + ) + + result.append(((VariableTracker, VariableTracker), handle_is)) # type: ignore[arg-type] + + return result + + for op in supported_comparison_ops.values(): + if not callable(op): + raise AssertionError(f"comparison op {op} is not callable") + if op in op_handlers: + raise AssertionError(f"duplicate handler for op {op}") + op_handlers[op] = create_cmp_op_handlers(op) + + return op_handlers + + @staticmethod + def _find_binop_handler( + op: Callable[..., Any], a_type: type[VariableTracker], b_type: type + ) -> list[_HandlerCallback] | None: + handlers = BuiltinVariable._binop_handlers().get(op) + if handlers is None: + return None + + matches = [] + for (type1, type2), handler in handlers: + if issubclass(a_type, type1) and issubclass(b_type, type2): + matches.append(handler) + return matches + + def can_insert_in_graph(self) -> bool: + return self.fn in self._fx_graph_functions() + + # Builtins that have been promoted to their own VT classes. Creating a + # BuiltinVariable for these is a bug; use the specialized class instead. + MUST_USE_SPECIALIZED: frozenset[Any] = frozenset( + {dict, getattr, hasattr, iter, list, setattr} + ) + + def __init__(self, fn: Any, **kwargs: Any) -> None: + if fn in self.MUST_USE_SPECIALIZED: + raise AssertionError( + f"Use the specialized VT class for {fn!r}, not BuiltinVariable. " + f"E.g. DictBuiltinVariable for dict." + ) + super().__init__(**kwargs) + self.fn = fn + + def __repr__(self) -> str: + if self.fn is None: + name = "None" + else: + name = self.fn.__name__ + + return f"{self.__class__.__name__}({name})" + + def as_python_constant(self) -> Any: + return self.fn + + def get_real_python_backed_value(self) -> Any: + return self.fn + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # BuiltinVariable wraps built-in types like list, tuple, dict. + # type(self.fn).__or__(self.fn, other_val) delegates to CPython's + # _Py_union_type_or for type unions (e.g. list | tuple). + # https://github.com/python/cpython/blob/v3.13.0/Objects/typeobject.c#L6028-L6030 (type_as_number.nb_or = _Py_union_type_or) + # https://github.com/python/cpython/blob/3.13/Objects/unionobject.c#L162 (_Py_union_type_or) + if not isinstance(self.fn, type): + return VariableTracker.build(tx, NotImplemented) + try: + other_val = other.as_python_constant() + except NotImplementedError: + return VariableTracker.build(tx, NotImplemented) + # pyrefly: ignore[bad-argument-count] + result = type(self.fn).__or__(self.fn, other_val) + if result is NotImplemented: + return VariableTracker.build(tx, NotImplemented) + return VariableTracker.build(tx, result) + + def as_proxy(self) -> Any: + DTYPE = { + bool: torch.bool, + int: torch.int64, + float: torch.float64, + } + if self.fn in DTYPE: + return DTYPE[self.fn] + return super().as_proxy() + + def reconstruct(self, codegen: "PyCodegen") -> None: + name = self.fn.__name__ + if self.fn.__module__ != "builtins": + raise AssertionError(f"Expected builtins module, got {self.fn.__module__}") + if name in codegen.tx.f_globals: + raise AssertionError("shadowed global") + codegen.append_output(codegen.create_load_global(name, add=True)) + + def constant_args(self, *args: VariableTracker, **kwargs: VariableTracker) -> bool: + return check_constant_args(args, kwargs) + + def tensor_args(self, *args: VariableTracker) -> bool: + any_tensor = False + for arg in args: + if isinstance(arg, variables.GetAttrVariable): + return False + any_tensor = any_tensor or arg.is_tensor() + return any_tensor + + def tensor_args_type(self, arg_types: list[type]) -> bool: + any_tensor = False + for arg_type in arg_types: + if issubclass(arg_type, variables.GetAttrVariable): + return False + any_tensor = any_tensor or issubclass(arg_type, variables.TensorVariable) + return any_tensor + + def python_and_tensor_constant_only( + self, *args: VariableTracker, **kwargs: VariableTracker + ) -> bool: + tensor_args = [] + non_tensor_args = [] + for i in itertools.chain(args, kwargs.values()): + if i.is_tensor(): + tensor_args.append(i) + else: + non_tensor_args.append(i) + return all( + is_constant_source(t.source) if t.source is not None else False + for t in tensor_args + ) and self.constant_args(*non_tensor_args) + + @staticmethod + def unwrap_unspec_args_kwargs( + args: list[VariableTracker], kwargs: dict[str, VariableTracker] + ) -> tuple[list[Any], dict[str, Any]]: + return [x.as_python_constant() for x in args], { + k: v.as_python_constant() for k, v in kwargs.items() + } + + def has_constant_handler( + self, args: list[VariableTracker], kwargs: dict[str, VariableTracker] + ) -> bool: + return self.can_constant_fold_through() and check_unspec_or_constant_args( + args, kwargs + ) + + @staticmethod + def _make_handler( + fn: Callable[..., Any], arg_types: list[type], has_kwargs: bool + ) -> Callable[ + [ + "InstructionTranslatorBase", + list[VariableTracker], + dict[str, VariableTracker], + ], + VariableTracker | None, + ]: + from .lazy import ( + ComputedLazyConstantVariable, + LazyConstantVariable, + LazyVariableTracker, + ) + + obj = BuiltinVariable(fn) + handlers: list[_HandlerCallback] = [] + + lazy_constant_types = (LazyConstantVariable, ComputedLazyConstantVariable) + lazy_types = [t for t in arg_types if issubclass(t, LazyVariableTracker)] + if lazy_types: + if not all(issubclass(t, lazy_constant_types) for t in lazy_types): + # Realize non-constant lazy args and re-dispatch. Any + # lazy constant args are kept and handled on the + # second dispatch through the branch below. + return lambda tx, args, kwargs: obj.call_function( + tx, + [ + a.realize() + if isinstance(a, LazyVariableTracker) + and not isinstance(a, lazy_constant_types) + else a + for a in args + ], + kwargs, + ) + + # Only lazy constant types. Install type guards + # and resolve the dispatch type. If the resolved type is + # ConstantVariable (the common case), delegate to a handler + # built for ConstantVariable. Otherwise (e.g. specialize_int= + # False turned the int into a SymNodeVariable), realize and + # re-dispatch so the correct handler is used. + inner_handler = BuiltinVariable._make_handler( + fn, + [ + ConstantVariable if issubclass(t, lazy_constant_types) else t + for t in arg_types + ], + has_kwargs, + ) + + def lazy_constant_handler( + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker | None: + if not kwargs: + result = _try_computed_lazy_constant(fn, args) + if result is not None: + return result + for a in args: + if isinstance(a, lazy_constant_types): + if a.get_handler_type_for_dispatch() is not ConstantVariable: + return obj.call_function( + tx, + [ + v.realize() + if isinstance(v, lazy_constant_types) + else v + for v in args + ], + kwargs, + ) + return inner_handler(tx, args, kwargs) + + return lazy_constant_handler + + if inspect.isclass(fn) and ( + issubclass(fn, BaseException) + # GeneratorExit doesn't inherit from Exception + # >>> issubclass(GeneratorExit, Exception) + # False + or fn is GeneratorExit + ): + + def create_exception_class_object( + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if fn is AssertionError and not all( + x.is_python_constant() and isinstance(x.as_python_constant(), str) + for x in args + ): + unimplemented( + gb_type="assert with non-string message", + context=str(args), + explanation="Dynamo only supports asserts with string messages", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + if fn is StopIteration: + return variables.StopIterationVariable(fn, args, kwargs) + elif fn is AttributeError: + return variables.AttributeErrorVariable(fn, args, kwargs) + elif fn is NameError: + return variables.NameErrorVariable(fn, args, kwargs) + return variables.ExceptionVariable(fn, args, kwargs) + + return create_exception_class_object + + if obj.can_insert_in_graph() and not ( + fn is operator.getitem + and ( + len(arg_types) != 2 + or not issubclass(arg_types[0], variables.TensorVariable) + ) + ): + if obj.tensor_args_type(arg_types): + return obj._handle_insert_op_in_graph + elif has_kwargs: + # need runtime check for kwargs + handlers.append(obj._handle_insert_op_in_graph) + + # Handle binary ops (e.g. __add__ / __radd__, __iadd__, etc.) + # NB: Tensor args are handled above and not here + if len(arg_types) == 2 and not has_kwargs: + # Try to find a handler for the arg types; otherwise, fall through to constant handler + binop_handlers = BuiltinVariable._find_binop_handler(fn, *arg_types) + if not binop_handlers: + pass + elif len(binop_handlers) == 1: + (binop_handler,) = binop_handlers + handlers.append(lambda tx, args, _: binop_handler(tx, *args)) + else: + + def call_binop_handlers( + tx: "InstructionTranslatorBase", args: Any, _: Any + ) -> Any: + # pyrefly: ignore [not-iterable] + for fn in binop_handlers: + rv = fn(tx, *args) + if rv: + return rv + return None + + handlers.append(call_binop_handlers) + + self_handler = getattr(obj, f"call_{fn.__name__}", None) + if self_handler: + + def call_self_handler( + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker | None: + try: + # pyrefly: ignore [not-callable] + return self_handler(tx, *args, **kwargs) + except TypeError: + # Check if binding is bad. inspect signature bind is expensive. + # So check only when handler call fails. + try: + # pyrefly: ignore [bad-argument-type] + inspect.signature(self_handler).bind(tx, *args, **kwargs) + except TypeError as e: + has_constant_handler = obj.has_constant_handler(args, kwargs) + if not has_constant_handler: + log.warning( + "incorrect arg count %s %s and no constant handler", + self_handler, + e, + ) + unimplemented( + gb_type="invalid call to builtin op handler", + context=f"invalid args to {self_handler}: {args} {kwargs}", + explanation=f"Encountered TypeError when trying to handle op {fn.__name__}", + hints=[*graph_break_hints.DIFFICULT], + ) + else: + raise + except Unsupported as exc: + has_constant_handler = obj.has_constant_handler(args, kwargs) + if not has_constant_handler: + raise + # Actually, we will handle this just fine + exc.remove_from_stats() + return None + + handlers.append(call_self_handler) + + if obj.can_constant_fold_through(): + if ( + all(issubclass(x, ConstantVariable) for x in arg_types) + and not has_kwargs + ): + + def constant_fold_handler( + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker | None: + # fast path + try: + res = fn( + *[x.as_python_constant() for x in args], + ) + except Exception as exc: + raise_observed_exception( + type(exc), + tx, + args=list(exc.args), + ) + except AsPythonConstantNotImplementedError as exc: + unimplemented( + gb_type="constant fold exception", + context=f"attempted to run function {fn} with arguments {args}", + explanation="Encountered exception when attempting to constant fold.", + hints=[*graph_break_hints.DYNAMO_BUG], + from_exc=exc, + ) + return VariableTracker.build(tx, res) + + else: + + def constant_fold_handler( + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker | None: + # path with a runtime check + if check_unspec_or_constant_args(args, kwargs): + try: + res = fn( + *[x.as_python_constant() for x in args], + **{ + k: v.as_python_constant() for k, v in kwargs.items() + }, + ) + except AsPythonConstantNotImplementedError as exc: + unimplemented( + gb_type="constant fold exception", + context=f"attempted to run function {fn} with arguments {args}", + explanation="Encountered exception when attempting to constant fold.", + hints=[*graph_break_hints.DYNAMO_BUG], + from_exc=exc, + ) + except Exception as exc: + raise_observed_exception( + type(exc), + tx, + args=list(exc.args), + ) + return VariableTracker.build(tx, res) + return None + + handlers.append(constant_fold_handler) + + def call_unimplemented(args: list[VariableTracker]) -> None: + real_arg_types = [arg.python_type_name() for arg in args] + unimplemented( + gb_type="Failed to trace builtin operator", + context=f"builtin {fn.__name__} {arg_types} {has_kwargs}", + explanation=f"Dynamo does not know how to trace builtin operator `{fn.__name__}` " + f"with argument types {real_arg_types} (has_kwargs {has_kwargs})", + hints=[ + f"Avoid calling builtin `{fn.__name__}` with argument types {real_arg_types}. " + f"Consider using an equivalent alternative function/method to `{fn.__name__}`.", + "If you are attempting to call a logging function (e.g. `print`), " + "you can try adding it to `torch._dynamo.config.reorderable_logging_functions`.", + "Please report an issue to PyTorch.", + ], + ) + + if len(handlers) == 0: + return lambda tx, args, kwargs: call_unimplemented(args) + elif len(handlers) == 1: + (handler,) = handlers + + def builtin_dispatch( + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker | None: + rv = handler(tx, args, kwargs) + if rv: + return rv + call_unimplemented(args) + return rv + + else: + + def builtin_dispatch( + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker | None: + rv = None + for fn in handlers: + rv = fn(tx, args, kwargs) + if rv: + return rv + call_unimplemented(args) + return rv + + return builtin_dispatch + + @staticmethod + def _constant_eval_numeric_expr(node: ast.AST) -> bool: + allowed_nodes = ( + ast.Expression, + ast.Constant, + ast.UnaryOp, + ast.BinOp, + ast.UAdd, + ast.USub, + ast.Invert, + ast.Add, + ast.Sub, + ast.Mult, + ast.Div, + ast.FloorDiv, + ast.Mod, + ast.BitOr, + ast.BitXor, + ast.BitAnd, + ) + return all( + isinstance(child, allowed_nodes) + and ( + not isinstance(child, ast.Constant) + or isinstance(child.value, (bool, int, float, complex)) + ) + for child in ast.walk(node) + ) + + @staticmethod + def _constant_eval_result( + tx: "InstructionTranslatorBase", tree: ast.Expression, filename: str + ) -> VariableTracker | None: + if any(isinstance(child, ast.Call) for child in ast.walk(tree)): + return None + ast.fix_missing_locations(tree) + try: + result = ast.literal_eval(tree) + except ValueError: + if not BuiltinVariable._constant_eval_numeric_expr(tree): + return None + try: + result = eval( + compile(tree, filename, "eval"), + {"__builtins__": {}}, + {}, + ) + except Exception as exc: + raise_observed_exception(type(exc), tx, args=list(exc.args)) + return VariableTracker.build(tx, result) + + def call_eval( + self, + tx: "InstructionTranslatorBase", + source: VariableTracker, + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + if args or kwargs: + return None + if not source.is_python_constant(): + return None + source_str = source.as_python_constant() + if not isinstance(source_str, str): + return None + + try: + tree = ast.parse(source_str.strip(), mode="eval") + except SyntaxError as exc: + raise_observed_exception(SyntaxError, tx, args=[exc.msg]) + + return self._constant_eval_result(tx, tree, "") + + def call_vars( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if kwargs: + raise_type_error(tx, "vars() takes no keyword arguments") + if len(args) == 0: + return self._call_frame_locals_snapshot(tx) + if len(args) != 1: + raise_type_error(tx, f"vars expected at most 1 argument, got {len(args)}") + # vars(obj) is obj.__dict__ if __dict__ is present else TypeError + try: + return args[0].tp_getattro_impl(tx, "__dict__") + except ObservedAttributeError: + raise_observed_exception(TypeError, tx) + + def call_locals( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + if len(args) != 0: + raise_observed_exception(TypeError, tx) + return self._call_frame_locals_snapshot(tx) + + @staticmethod + def _call_frame_locals_snapshot(tx: "InstructionTranslatorBase") -> VariableTracker: + from .builder import VariableBuilder + + frame_local_names = set(tx.f_code.co_varnames) | set(tx.cell_and_freevars()) + cell_and_freevars = set(tx.cell_and_freevars()) + frame_locals = {} + # symbolic_cellvars registers all of the frame's cells. Cells are listed first so that a colliding fast local of + # the same name shadows the cell, matching CPython (except for 3.12, which is backwards): the two share a name + # but not a localsplus slot, and the fast slot wins while it holds a value (an empty one is skipped below, + # leaving the cell contents visible). + if sys.version_info[:2] == (3, 12): + its = (tx.symbolic_locals.items(), tx.symbolic_cellvars.items()) + else: + its = (tx.symbolic_cellvars.items(), tx.symbolic_locals.items()) + + for name, value in itertools.chain(*its): + if name not in frame_local_names: + continue + # Match on CellVariable, not name: a colliding fast local shares a + # cell's name but is not itself a cell. + if type.__instancecheck__(CellVariable, value): + value = tx.output.side_effects.load_cell(value) + if type.__instancecheck__(NullVariable, value) or isinstance( + value, variables.DeletedVariable + ): + continue + frame_locals[ConstantVariable.create(name)] = value + # Include locals pruned from symbolic_locals by the unused-input optimisation. + # locals()/vars() observes the entire namespace, so build VTs (installing + # guards) for any pruned entry that still has a runtime value. + for name in frame_local_names: + if name in frame_locals or name in cell_and_freevars: + continue + if name not in tx.f_locals: + continue + vt = VariableBuilder(tx, LocalSource(name))(tx.f_locals[name]) + frame_locals[ConstantVariable.create(name)] = vt + return ConstDictVariable( + frame_locals, + mutation_type=ValueMutationNew(), + ) + + def _handle_insert_op_in_graph( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker | None: + from .builder import wrap_fx_proxy, wrap_fx_proxy_cls + + if kwargs and not self.tensor_args(*args, *kwargs.values()): + return None + + # insert handling for torch function here + from .builder import SourcelessBuilder + from .torch_function import can_dispatch_torch_function, dispatch_torch_function + + global BUILTIN_TO_TENSOR_RFN_MAP, BUILTIN_TO_TENSOR_FN_MAP + if can_dispatch_torch_function(tx, args, kwargs): + # Only remap the fn to tensor methods if we aren't exporting + # export serde does not handle method descriptors today + if not tx.export: + # Ensure the builtin maps are populated before accessing them + populate_builtin_to_tensor_fn_map() + # Use sourceless builder, we built the map ourselves + if not args[0].is_tensor(): + if self.fn in BUILTIN_TO_TENSOR_RFN_MAP: + func = BUILTIN_TO_TENSOR_RFN_MAP[self.fn] + else: + func = BUILTIN_TO_TENSOR_FN_MAP[self.fn] + + tmp = args[0] + # swap args and call reverse version of func + args[0] = args[1] # type: ignore[index] + args[1] = tmp # type: ignore[index] + else: + func = BUILTIN_TO_TENSOR_FN_MAP[self.fn] + else: + func = self.fn + + fn_var = SourcelessBuilder.create(tx, func) + + return dispatch_torch_function(tx, fn_var, args, kwargs) + + fn = self.fn + try: + # Constant fold for constant tensor and python constants + if self.python_and_tensor_constant_only(*args, **kwargs): + from ..bytecode_transformation import unique_id + from .functions import invoke_and_store_as_constant + + return invoke_and_store_as_constant( + tx, fn, unique_id(fn.__name__), args, kwargs + ) + + if fn in IN_PLACE_DESUGARING_MAP and isinstance( + args[0], variables.ConstantVariable + ): + # In-place operators like += usually mustate tensor + # values, but in the edge case of immutable values they + # re-bind the variable. + # + # The easiest way to keep the graph consistent in this + # scenario is to de-sugar eagerly. + fn = IN_PLACE_DESUGARING_MAP[fn] + args = [args[0], args[1]] # type: ignore[assignment] + + if fn is operator.getitem: + if kwargs: + raise_type_error( + tx, "_operator.getitem() takes no keyword arguments" + ) + if len(args) != 2: + raise_type_error( + tx, f"getitem expected 2 arguments, got {len(args)}" + ) + if isinstance(args[1], SymNodeVariable): + # Standard indexing will force specialization due to + # __index__. Rewrite as a regular torch op which will + # trace fine + fn = torch.select + args = [ + args[0], + variables.VariableTracker.build(tx, 0), + args[1], + ] # type: ignore[assignment] + + # Interaction between ndarray and tensors: + # We prefer the tensor op whenever there are tensors involved + # NB: Use exact type check here - NumpyNdarrayVariable is a TensorVariable + # subclass but should NOT trigger the tensor path + if check_numpy_ndarray_args(args, kwargs) and not any( + type(arg) is TensorVariable for arg in args + ): + proxy = tx.output.create_proxy( + "call_function", + numpy_operator_wrapper(fn), + *proxy_args_kwargs(args, kwargs), + ) + + return wrap_fx_proxy_cls(variables.NumpyNdarrayVariable, tx, proxy) + + if ( + fn in _OPERATOR_TO_DUNDER + and len(args) == 2 + and any( + not isinstance(a, (variables.TensorVariable, SymNodeVariable)) + for a in args + ) + ): + return generic_richcompare( + tx, args[0], args[1], _OPERATOR_TO_DUNDER[fn] + ) + + proxy = tx.output.create_proxy( + "call_function", + fn, + *proxy_args_kwargs(args, kwargs), + ) + if any(isinstance(arg, FakeItemVariable) for arg in args): + return wrap_fx_proxy_cls( + FakeItemVariable, + tx, + proxy, + ) + elif check_unspec_python_args(args, kwargs): + _args, _kwargs = self.unwrap_unspec_args_kwargs(args, kwargs) + raw_value = fn(*_args, **_kwargs) + + need_unwrap = any( + x.need_unwrap + for x in itertools.chain(args, kwargs.values()) + if isinstance(x, variables.UnspecializedPythonVariable) + ) + + return wrap_fx_proxy_cls( + UnspecializedPythonVariable, + tx, + proxy, + raw_value=raw_value, + need_unwrap=need_unwrap, + ) + elif all(isinstance(x, SymNodeVariable) for x in args): + return SymNodeVariable.create(tx, proxy, None) + else: + # Work around for vision_maskrcnn due to precision difference + # specialize the dividend when float divide by tensor + if fn is operator.truediv and isinstance( + args[0], variables.UnspecializedPythonVariable + ): + args = list(args) + args[0] = args[0].as_python_constant() + return wrap_fx_proxy(tx, proxy) + + except NotImplementedError: + unimplemented( + gb_type="unimplemented builtin op on tensor arguments", + context=f"partial tensor op: {self} {args} {kwargs}", + explanation=f"Dynamo does not know how to trace builtin operator {self.fn} with tensor arguments", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + call_function_handler_cache: dict[ + tuple[object, ...], + Callable[ + [ + "InstructionTranslatorBase", + list[VariableTracker], + dict[str, VariableTracker], + ], + VariableTracker, + ], + ] = {} + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if self.fn is object and not args and not kwargs: + # object() -> a fresh opaque instance, wrapped as ObjectVariable to + # match how SourcelessBuilder wraps bare `object` instances. Falling + # through to the constant handler cannot build a VT from object(). + from .builder import SourcelessBuilder + + return SourcelessBuilder.create(tx, object()) + + key: tuple[object, ...] + if kwargs: + kwargs = {k: v.realize() for k, v in kwargs.items()} + key = (self.fn, *(type(x) for x in args), True) + else: + key = (self.fn, *(type(x) for x in args)) + + handler = self.call_function_handler_cache.get(key) + if not handler: + self.call_function_handler_cache[key] = handler = self._make_handler( # type: ignore[assignment] + self.fn, [type(x) for x in args], bool(kwargs) + ) + if handler is None: + raise AssertionError( + f"No handler found for {self.fn} with args {[type(x) for x in args]}" + ) + return handler(tx, args, kwargs) # type: ignore[return-value] + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if self.fn is object and name == "__setattr__": + if len(args) != 3: + raise AssertionError( + f"object.__setattr__ expects 3 args, got {len(args)}" + ) + if len(kwargs) != 0: + raise AssertionError( + f"object.__setattr__ expects no kwargs, got {len(kwargs)}" + ) + obj, name_var, val = args + obj = obj.realize() + if ( + isinstance(obj, UserDefinedObjectVariable) + and tx.output.side_effects.is_attribute_mutation(obj) + and name_var.is_python_constant() + ): + return obj.method_setattr_standard(tx, name_var, val) + + if name == "__new__": + # Supported __new__ methods + if self.fn is object and len(args) == 1: + if len(kwargs) != 0: + raise AssertionError( + f"object.__new__ expects no kwargs, got {len(kwargs)}" + ) + return tx.output.side_effects.track_new_user_defined_object( + self, + args[0], + args[1:], + tx=tx, + ) + + if self.fn is tuple and len(args) == 2 and not kwargs: + if isinstance(args[0], BuiltinVariable) and args[0].fn is tuple: + init_args = unpack_iterable(tx, args[1]) + return variables.TupleVariable( + init_args, mutation_type=ValueMutationNew() + ) + + return tx.output.side_effects.track_new_user_defined_object( + self, + args[0], + args[1:], + tx=tx, + ) + + if name in _BUILTIN_CONSTANT_FOLDABLE_METHODS.get(self.fn, ()): + if all(a.is_python_constant() for a in args) and all( + v.is_python_constant() for v in kwargs.values() + ): + try: + fn = getattr(self.fn, name) + res = fn( + *(a.as_python_constant() for a in args), + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ) + return VariableTracker.build(tx, res) + except Exception as e: + raise_observed_exception( + type(e), + tx, + args=list(e.args), + ) + + if self.fn is object and name == "__init__": + # object.__init__ is a no-op + return variables.ConstantVariable.create(None) + + if self.fn in (set, frozenset, list, tuple): + if isinstance(args[0], variables.UserDefinedObjectVariable): + if args[0]._base_vt is None: + raise AssertionError( + "UserDefinedObjectVariable._base_vt must not be None" + ) + return args[0]._base_vt.call_method(tx, name, args[1:], kwargs) + else: + return args[0].call_method(tx, name, args[1:], kwargs) + + if ( + name in ("__eq__", "__ne__", "__lt__", "__le__", "__gt__", "__ge__") + and len(args) == 2 + and not kwargs + and isinstance(self.fn, type) + and args[0].is_python_constant() + and args[1].is_python_constant() + ): + # Unbound rich-comparison dunder, e.g. complex.__eq__(1+1j, 2). + # Invoke only the left type's slot on the constants, mirroring + # CPython (returns NotImplemented rather than falling back to the + # reflected operation when the operands are incompatible). + lval = args[0].as_python_constant() + if isinstance(lval, self.fn): + return ConstantVariable.create( + getattr(self.fn, name)(lval, args[1].as_python_constant()) + ) + + if self.fn is str and len(args) >= 1: + resolved_fn = getattr(self.fn, name, None) + if resolved_fn in str_methods: + # Only delegate to ConstantVariable, not other types that happen to be constants + if isinstance(args[0], ConstantVariable): + return args[0].call_method(tx, name, args[1:], kwargs) + + if self.fn is float and len(args) >= 1: + # Only delegate to ConstantVariable, not other types that happen to be constants + if isinstance(args[0], ConstantVariable): + return VariableTracker.build( + tx, getattr(float, name)(args[0].as_python_constant()) + ) + + if name == "__len__" and len(args) == 1 and not kwargs: + # type.__len__(instance) → len(instance) + # e.g. list.__len__(my_list) → len(my_list) + return generic_size(tx, args[0]) + + if name == "__str__" and len(args) == 1 and not kwargs: + return super().call_method(tx, name, args, kwargs) + + if name == "__repr__" and len(args) == 1 and not kwargs: + return super().call_method(tx, name, args, kwargs) + + if name == "__iter__" and len(args) == 1 and not kwargs: + # type.__iter__(instance) → iter(instance) + # e.g., tuple.__iter__(my_tuple) → iter(my_tuple) + # For builtin types called on user-defined subclasses, use the base iterator + return generic_getiter(tx, args[0]) + + if name == "__neg__" and len(args) == 1 and not kwargs: + # type.__neg__(instance) → neg(instance) + # e.g., int.__neg__(4) → neg(4) + return pynumber_negative(tx, args[0]) + + if name == "__pos__" and len(args) == 1 and not kwargs: + # type.__pos__(instance) → pos(instance) + # e.g., int.__pos__(4) → pos(4) + return pynumber_positive(tx, args[0]) + + if name == "__abs__" and len(args) == 1 and not kwargs: + # type.__abs__(instance) → abs(instance) + # e.g., int.__abs__(-4) → abs(-4) + return pynumber_absolute(tx, args[0]) + + if name == "__invert__" and len(args) == 1 and not kwargs: + # type.__invert__(instance) → ~instance + # e.g., int.__invert__(4) → ~4 + return pynumber_invert(tx, args[0]) + + if name == "__hash__" and len(args) == 1 and not kwargs: + arg = args[0] + if ( + isinstance(arg, variables.UserDefinedConstantVariable) + and arg._base_vt is not None + ): + return generic_hash(tx, arg._base_vt) + + return super().call_method(tx, name, args, kwargs) + + def call_int( + self, + tx: "InstructionTranslatorBase", + arg: VariableTracker, + base: VariableTracker | None = None, + ) -> VariableTracker | None: + if base is None: + return pynumber_int(tx, arg) + return pylong_from_base(tx, arg, base) + + def call_float( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker | None: + return pynumber_float(tx, arg) + + def call_bin( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker | None: + return pynumber_tobase(tx, arg, 2) + + def call_oct( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker | None: + return pynumber_tobase(tx, arg, 8) + + def call_hex( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker | None: + return pynumber_tobase(tx, arg, 16) + + def call_bool( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker | None: + # Emulate PyBool_Type.tp_vectorcall which boils down to PyObject_IsTrue. + return generic_is_true(tx, arg) + + def call_hash( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + return generic_hash(tx, arg) + + def call_repr( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker | None: + return generic_repr(tx, arg) + + def call_str( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker | None: + return generic_str(tx, arg) + + def call___build_class__(self, tx, *args, **kwargs): + def fail(args, kwargs) -> NoReturn: + unimplemented( + gb_type="Invalid call to __build_class__", + context=f"Non-constant args to __build_class__: {args} {kwargs}", + explanation="Cannot trace class definition: the class body function is unsupported or the base class argument are not compile-time constants", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + if not torch._dynamo.config.enable_trace_load_build_class: + fail(args, kwargs) + + try: + if isinstance(args[0], variables.NestedUserFunctionVariable): + fn = args[0].get_function(allow_sourced_cells=True) + else: + fn = args[0].get_function() + except NotImplementedError: + fail(args, kwargs) + + if check_constant_args(args[1:], kwargs): + r = builtins.__build_class__( + fn, # type: ignore[possibly-undefined] + *[a.as_python_constant() for a in args[1:]], + ) + return VariableTracker.build(tx, r) + else: + fail(args, kwargs) + + def _call_min_max( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + key: VariableTracker | None = None, + default: VariableTracker | None = None, + ) -> VariableTracker | None: + name = self.fn.__name__ + if len(args) == 0: + raise_type_error(tx, f"{name} expected at least 1 argument, got 0") + + # `default` is keyword-only and only valid with a single iterable arg. + positional = len(args) > 1 + if positional and default is not None: + raise_type_error( + tx, + f"Cannot specify a default for {name}() with multiple positional arguments", + ) + + if key is not None and key.is_constant_none(): + key = None + + items = list(args) if positional else unpack_iterable(tx, args[0]) + + if len(items) == 0: + if default is not None: + return default + raise_value_error(tx, f"{name}() iterable argument is empty") + + if key is None: + return self._call_min_max_seq(tx, items) + return self._call_min_max_seq_with_key(tx, items, key) + + def _call_min_max_seq( + self, tx: "InstructionTranslatorBase", items: list[VariableTracker] + ) -> VariableTracker: + if len(items) <= 0: + raise AssertionError("_call_min_max_seq requires at least one item") + if len(items) == 1: + return items[0] + + return functools.reduce(functools.partial(self._call_min_max_binary, tx), items) # type: ignore[arg-type,return-value] + + def _call_min_max_seq_with_key( + self, + tx: "InstructionTranslatorBase", + items: list[VariableTracker], + key: VariableTracker, + ) -> VariableTracker: + # Mirror CPython builtin_min_max: compare on key(item) but return the + # original element, keeping the first extremal element on ties (only + # replace on a strict comparison). Like list.sort, comparisons are done + # through Dynamo and must fold to a compile-time constant, so Tensor and + # SymInt keys graph break. + keyvals = [key.call_function(tx, [item], {}) for item in items] + best_item, best_key = items[0], keyvals[0] + for item, keyval in zip(items[1:], keyvals[1:]): + left, right = (best_key, keyval) if self.fn is max else (keyval, best_key) + cmp = BuiltinVariable(operator.lt).call_function(tx, [left, right], {}) + if not cmp.is_python_constant(): + unimplemented( + gb_type="min/max with non-constant key", + context=str(keyval), + explanation=( + f"Cannot compute {self.fn.__name__}() whose key comparison is " + f"not a compile-time constant. Key type: {keyval.python_type()}. " + f"Most notably, Tensor or SymInt keys are unsupported, but ints work." + ), + hints=[ + "Use something else as the key.", + *graph_break_hints.SUPPORTABLE, + ], + ) + if cmp.as_python_constant(): + best_item, best_key = item, keyval + return best_item + + def _call_min_max_binary( + self, + tx: "InstructionTranslatorBase", + a: VariableTracker | None, + b: VariableTracker | None, + ) -> VariableTracker | None: + if a is None or b is None: + # a or b could be none if we reduce and _call_min_max_binary failed + # to return something + return None + if self.tensor_args(a, b): + if not a.is_tensor(): + a, b = b, a + if not a.is_tensor(): + raise AssertionError( + "Expected at least one tensor argument for min/max" + ) + + # result of an item call is a scalar convert to a tensor + if isinstance(a, FakeItemVariable): + a = variables.TorchInGraphFunctionVariable(torch.tensor).call_function( + tx, [a], {} + ) + + # Dynamic input does not get resolved, rather, gets stored as call_function + if isinstance(a, SymNodeVariable) or isinstance(b, SymNodeVariable): + from .builder import wrap_fx_proxy_cls + + return wrap_fx_proxy_cls( + type(a), + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.fn, + *proxy_args_kwargs([a, b], {}), + ), + ) + + # convert min/max to torch ops + if b.is_python_constant(): + fn: VariableTracker + if isinstance(a, variables.NumpyNdarrayVariable): + import numpy as np + + fn = variables.NumpyVariable(np.clip) + else: + fn = variables.TorchInGraphFunctionVariable(torch.clamp) + kwargs = {"min": b} if (self.fn is max) else {"max": b} + result = fn.call_function(tx, [a], kwargs) + else: + if isinstance(a, variables.NumpyNdarrayVariable): + import numpy as np + + np_fn = {max: np.maximum, min: np.minimum}[self.fn] + fn = variables.NumpyVariable(np_fn) + else: + torch_fn = {max: torch.maximum, min: torch.minimum}[self.fn] + fn = variables.TorchInGraphFunctionVariable(torch_fn) + result = fn.call_function(tx, [a, b], {}) + + # return unspec if both a, b are unspec or const + if all( + isinstance( + i, + ( + variables.UnspecializedPythonVariable, + variables.ConstantVariable, + ), + ) + for i in [a, b] + ): + if any(isinstance(val, FakeItemVariable) for val in [a, b]): + # type: ignore[arg-type] + return variables.FakeItemVariable.from_tensor_variable(result) + + if b.is_python_constant(): + raw_b = b.as_python_constant() + else: + raw_b = b.raw_value # type: ignore[attr-defined] + if self.fn is max: + raw_res = max(a.raw_value, raw_b) # type: ignore[attr-defined] + else: + raw_res = min(a.raw_value, raw_b) # type: ignore[attr-defined] + + need_unwrap = any( + x.need_unwrap + for x in [a, b] + if isinstance(x, variables.UnspecializedPythonVariable) + ) + return variables.UnspecializedPythonVariable.from_tensor_variable( + result, # type: ignore[arg-type] + raw_res, + need_unwrap, + ) + # otherwise return tensor + else: + return result + elif isinstance(a, SymNodeVariable) or isinstance(b, SymNodeVariable): + py_fn = torch.sym_max if self.fn is max else torch.sym_min + proxy = tx.output.create_proxy( + "call_function", py_fn, *proxy_args_kwargs([a, b], {}) + ) + return SymNodeVariable.create(tx, proxy, None) + elif isinstance(a, ConstantVariable) and isinstance(b, ConstantVariable): + value = self.fn( + a.as_python_constant(), + b.as_python_constant(), + ) + return VariableTracker.build(tx, value) + return None + + call_min = _call_min_max + call_max = _call_min_max + + def call_abs( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + return pynumber_absolute(tx, arg) + + def call_pos( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + return pynumber_positive(tx, arg) + + def call_index( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + # Specialize SymNodeVariable to a constant first, matching CPython's + # PyNumber_Index which forces a concrete int. + return pynumber_index(tx, arg) + + def call_round( + self, + tx: "InstructionTranslatorBase", + arg: VariableTracker, + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + from .builder import SourcelessBuilder + + # Call arg.__round__() + round_method = SourcelessBuilder.create(tx, getattr).call_function( + tx, [arg, VariableTracker.build(tx, "__round__")], {} + ) + return round_method.call_function(tx, list(args), kwargs) + + def call_range( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if kwargs: + raise_type_error(tx, "range() takes no keyword arguments") + if len(args) == 0: + raise_type_error(tx, "range expected at least 1 argument, got 0") + if len(args) > 3: + raise_type_error(tx, f"range expected at most 3 arguments, got {len(args)}") + args = tuple(pynumber_index(tx, arg) for arg in args) + return variables.RangeVariable(list(args)) + + def _dynamic_args(self, *args: VariableTracker, **kwargs: VariableTracker) -> bool: + return any(isinstance(x, SymNodeVariable) for x in args) or any( + isinstance(x, SymNodeVariable) for x in kwargs.values() + ) + + def call_slice( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + if not 1 <= len(args) < 4: + raise_type_error(tx, f"slice expected at least 1 argument, got {len(args)}") + return variables.SliceVariable(list(args), tx) + + def _dyn_proxy( + self, tx: "InstructionTranslatorBase", *args: Any, **kwargs: Any + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", self.fn, *proxy_args_kwargs(args, kwargs) + ), + ) + + def call_tuple( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + # ref: https://github.com/python/cpython/blob/main/Objects/abstract.c#L2004-L2078 + if kwargs: + raise_type_error( + tx, + f"{self.fn.__name__}() takes no keyword arguments", + ) + if len(args) == 0: + return TupleVariable([], mutation_type=ValueMutationNew()) + elif len(args) > 1: + raise_type_error( + tx, + f"{self.fn.__name__} expected at most 1 argument, got {len(args)}", + ) + + obj = args[0] + if isinstance(obj, TupleVariable) and obj.python_type() is tuple: + return obj + + items = unpack_iterable(tx, args[0]) + return TupleVariable(items, mutation_type=ValueMutationNew()) + + def call_callable( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + # PyCallable_Check: callable(x) is type(x)->tp_call != NULL. Dispatch on + # the arg's Python type slot rather than enumerating callable VTs. + # callable() is the only handler for this builtin, so always return a + # result (or graph break via maybe_get_python_type) -- never None, which + # would signal "try another handler" that does not exist. + return variables.ConstantVariable.create( + pycallable_check(maybe_get_python_type(arg)) + ) + + def call_cast( + self, _: Any, *args: VariableTracker, **kwargs: VariableTracker + ) -> VariableTracker | None: + if len(args) == 2: + return args[1] + + unimplemented( + gb_type="bad args to builtin cast()", + context=f"got args {args} {kwargs}", + explanation="Dynamo expects exactly 2 args to builtin cast().", + hints=["Ensure your call to cast() has exactly 2 arguments."], + ) + + def call_dir( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker | None: + if isinstance(arg, variables.UserDefinedClassVariable): + return VariableTracker.build(tx, dir(arg.value)) + if isinstance(arg, BuiltinVariable): + return VariableTracker.build(tx, dir(arg.fn)) + # Enable specialized VTs for constants to work with dir() + if arg.is_python_constant(): + return VariableTracker.build(tx, dir(arg.as_python_constant())) + return None + + def call_set( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/main/Objects/setobject.c#L2708-L2735 + # CPython set_init rejects keywords before unpacking positional args, so + # set(a=1) and set().__init__(a=1) both raise regardless of arg count. + if kwargs: + raise_type_error( + tx, + "set() takes no keyword arguments", + ) + if len(args) == 0: + return variables.SetVariable(set(), mutation_type=ValueMutationNew()) + elif len(args) > 1: + raise_type_error( + tx, + f"set expected at most 1 argument, got {len(args)}", + ) + + s = SetVariable([], mutation_type=ValueMutationNew()) + s.call_method(tx, "update", [args[0]], kwargs) + return s + + def call_frozenset( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if kwargs: + raise_type_error( + tx, + "frozenset() takes no keyword arguments", + ) + if len(args) == 0: + return variables.FrozensetVariable(set(), mutation_type=ValueMutationNew()) + elif len(args) > 1: + raise_type_error( + tx, + f"frozenset expected at most 1 argument, got {len(args)}", + ) + + if istype(args[0], variables.FrozensetVariable): + # CPython: frozenset(existing_frozenset) returns the same object. + return args[0] + + # Reuse existing HashableTracker keys from a set/frozenset/dict operand + # instead of re-hashing, mirroring CPython's set_update_internal fast + # path (do-not-rehash-dict-keys). + if isinstance(args[0], (variables.SetVariable, variables.ConstDictVariable)): + items = list(args[0].items.keys()) + else: + items = unpack_iterable(tx, args[0]) + fs = FrozensetVariable(items, mutation_type=ValueMutationNew()) + return fs + + def call_zip( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.3/Python/bltinmodule.c#L2822-L2887 + if kwargs: + if not (len(kwargs) == 1 and "strict" in kwargs): + raise_args_mismatch( + tx, + "zip", + "1 kwargs (`strict`)", + f"{len(kwargs)} kwargs", + ) + strict = kwargs.pop("strict", ConstantVariable.create(False)) + items = [] + for arg in args: + items.append(generic_getiter(tx, arg)) + iter_args = TupleVariable(items, mutation_type=ValueMutationNew()) + return variables.ZipVariable( + iter_args, + strict=strict.as_python_constant(), + mutation_type=ValueMutationNew(), + ) + + def call_len( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if kwargs: + raise_type_error(tx, "len() takes no keyword arguments") + if len(args) != 1: + raise_type_error( + tx, f"len() takes exactly one argument ({len(args)} given)" + ) + return generic_size(tx, args[0]) + + def call_length_hint( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + # ref: PyObject_LengthHint (Objects/abstract.c): try __len__, then + # __length_hint__, falling back to the supplied default for either a + # missing slot or a TypeError raised by the slot. + if kwargs or not (1 <= len(args) <= 2): + raise_type_error( + tx, f"length_hint expected 1 or 2 arguments, got {len(args)}" + ) + obj = args[0] + default = args[1] if len(args) == 2 else ConstantVariable.create(0) + + obj_type = maybe_get_python_type(obj) + + if type_implements_sq_length(obj_type) or type_implements_mp_length(obj_type): + return generic_size(tx, obj) + + if getattr(obj_type, "__length_hint__", None) is None: + return default + try: + return obj.call_method(tx, "__length_hint__", [], {}) + except ObservedTypeError: + handle_observed_exception(tx) + return default + + def call_getitem( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if kwargs: + raise_type_error(tx, "_operator.getitem() takes no keyword arguments") + if len(args) != 2: + raise_type_error(tx, f"getitem expected 2 arguments, got {len(args)}") + return generic_getitem(tx, args[0], args[1]) + + def call_setitem( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if kwargs: + raise_type_error(tx, "_operator.setitem() takes no keyword arguments") + if len(args) != 3: + raise_type_error(tx, f"setitem expected 3 arguments, got {len(args)}") + return generic_setitem(tx, args[0], args[1], args[2]) + + def call_delitem( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if kwargs: + raise_type_error(tx, "_operator.delitem() takes no keyword arguments") + if len(args) != 2: + raise_type_error(tx, f"delitem expected 2 arguments, got {len(args)}") + return generic_delitem(tx, args[0], args[1]) + + def call_isinstance( + self, + tx: "InstructionTranslatorBase", + arg: VariableTracker, + isinstance_type_var: VariableTracker, + ) -> VariableTracker: + try: + arg_type = arg.python_type() + except NotImplementedError: + unimplemented( + gb_type="builtin isinstance() cannot determine type of argument", + context=f"isinstance({arg}, {isinstance_type_var})", + explanation=f"Dynamo doesn't have a rule to determine the type of argument {arg}", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + isinstance_type = isinstance_type_var.as_python_constant() + # An AsyncCollectiveTensor (ACT) input's tensor-class guard is relaxed + # (see VariableBuilder.wrap_tensor): the cache entry does not discriminate + # ACT from the resolved plain Tensor. isinstance() observes the class and + # is constant-folded below, so reinstall the class guard -- but only when + # the result would actually differ between the ACT and the resolved + # Tensor. isinstance(w, ACT) discriminates and must recompile; + # isinstance(w, torch.Tensor) is True for both and must stay reusable. + if isinstance(arg, variables.TensorVariable) and arg.source is not None: + from torch._functorch._aot_autograd.utils import ( + is_async_collective_tensor_type, + ) + + if is_async_collective_tensor_type(arg_type): + check_types = ( + isinstance_type + if isinstance(isinstance_type, tuple) + else (isinstance_type,) + ) + # Guard if any checked type distinguishes ACT from torch.Tensor, + # or conservatively if a checked entry is not a plain class. + if any( + not isinstance(ty, type) + or issubclass(arg_type, ty) != issubclass(torch.Tensor, ty) + for ty in check_types + ): + install_guard(arg.source.make_guard(GuardBuilder.TYPE_MATCH)) + if isinstance(arg, variables.TensorVariable) and arg.dtype is not None: + if _uses_custom_classinfo_check(isinstance_type): + unimplemented( + gb_type="builtin isinstance() with custom type check on tensor", + context=f"isinstance({arg}, {isinstance_type})", + explanation="Dynamo cannot soundly trace arbitrary custom " + "__instancecheck__ or __subclasscheck__ hooks on tensor " + "values because the hook may read external mutable state.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def _tensor_isinstance( + tensor_var: VariableTracker, tensor_type: Any + ) -> bool: + def check_type(ty: Any) -> bool: + if ty not in tensortype_to_dtype: + example_val = arg.as_proxy().node.meta["example_value"] + if ( + is_traceable_wrapper_subclass(example_val) + and ty is torch.nn.parameter.Parameter + ): + # N.B: we are calling isinstance directly on the example value. + # torch.nn.Parameter has a meta-class that overrides __isinstance__, + # the isinstance check here allows us to invoke that logic. + return isinstance(example_val, ty) + else: + return issubclass(arg.python_type(), ty) + + dtypes = tensortype_to_dtype[ty] + # pyrefly: ignore [missing-attribute] + return arg.dtype in dtypes + + if type(tensor_type) is tuple: + return any(check_type(ty) for ty in tensor_type) + else: + return check_type(tensor_type) + + return VariableTracker.build(tx, _tensor_isinstance(arg, isinstance_type)) + # UserDefinedObject with C extensions can have torch.Tensor attributes, + # so break graph. + if isinstance(arg, variables.UserDefinedObjectVariable) and isinstance( + arg.value, types.MemberDescriptorType + ): + unimplemented( + gb_type="isinstance() called on user defined object with C extensions", + context=f"isinstance({arg}, {isinstance_type})", + explanation="User-defined object with C extensions can have torch.Tensor " + "attributes; intentionally graph breaking.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + # handle __instancecheck__ defined in user class + if ( + isinstance(arg, variables.UserDefinedObjectVariable) + and "__instancecheck__" in isinstance_type.__class__.__dict__ + ): + return VariableTracker.build( + tx, + isinstance_type.__class__.__instancecheck__(isinstance_type, arg.value), + ) + + if isinstance(arg, variables.UserDefinedExceptionClassVariable): + # pyrefly: ignore [unbound-name] + return VariableTracker.build(tx, isinstance(arg_type, isinstance_type)) + + isinstance_type_tuple: tuple[type, ...] + if isinstance(isinstance_type, type) or callable( + # E.g. isinstance(obj, typing.Sequence) + getattr(isinstance_type, "__instancecheck__", None) + ): + isinstance_type_tuple = (isinstance_type,) + elif isinstance(isinstance_type, types.UnionType): + isinstance_type_tuple = typing.get_args(isinstance_type) + elif isinstance(isinstance_type, tuple) and all( + isinstance(tp, type) or callable(getattr(tp, "__instancecheck__", None)) + for tp in isinstance_type + ): + isinstance_type_tuple = isinstance_type + else: + raise_observed_exception( + TypeError, + tx, + args=[ + "isinstance() arg 2 must be a type, a tuple of types, or a union" + ], + ) + + try: + # NB: `isinstance()` does not call `__subclasscheck__` but use `__instancecheck__`. + # But usually `isinstance(obj, type_info)` and `issubclass(type(obj), type_info)` gives + # the same result. + # WARNING: This might run arbitrary user code `__subclasscheck__` and we did not trace + # through it. This is a limitation of the current implementation. + # Usually `__subclasscheck__` and `__instancecheck__` can be constant fold through, it + # might not be a big issue and we trade off it for performance. + val = issubclass(arg_type, isinstance_type_tuple) + except TypeError: + val = arg_type in isinstance_type_tuple + return VariableTracker.build(tx, val) + + def call_issubclass( + self, + tx: "InstructionTranslatorBase", + left_ty: VariableTracker, + right_ty: VariableTracker, + ) -> VariableTracker: + """Checks if first arg is subclass of right arg""" + return generic_issubclass(tx, left_ty, right_ty) + + def call_super( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker: + return variables.SuperVariable(a, b) + + def call_next( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if kwargs: + raise_type_error(tx, "next() takes no keyword arguments") + if len(args) == 0: + raise_type_error(tx, "next expected at least 1 argument, got 0") + if len(args) > 2: + raise_type_error(tx, f"next expected at most 2 arguments, got {len(args)}") + arg = args[0] + if not pyiter_check(maybe_get_python_type(arg)): + raise_type_error( + tx, f"'{arg.python_type_name()}' object is not an iterator" + ) + try: + return arg.next_variable(tx) + except ObservedUserStopIteration: + if len(args) == 2: + return args[1] + raise + + def call_map( + self, + tx: "InstructionTranslatorBase", + fn: VariableTracker, + *seqs: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if len(seqs) == 0: + raise_observed_exception( + TypeError, + tx, + args=["map() must have at least two arguments."], + ) + + strict = ConstantVariable.create(False) + if kwargs: + if sys.version_info >= (3, 14): + if not (len(kwargs) == 1 and "strict" in kwargs): + raise_args_mismatch( + tx, + "map", + "1 kwargs (`strict`)", + f"{len(kwargs)} kwargs", + ) + strict = kwargs.pop("strict", ConstantVariable.create(False)) + else: + raise_args_mismatch( + tx, + "map", + "0 kwargs", + f"{len(kwargs)} kwargs", + ) + + iterables = [generic_getiter(tx, seq) for seq in seqs] + iter_args = TupleVariable(iterables, mutation_type=ValueMutationNew()) + return variables.MapVariable( + fn, + iter_args, + strict=strict.as_python_constant(), + mutation_type=ValueMutationNew(), + ) + + def call_filter( + self, tx: "InstructionTranslatorBase", fn: VariableTracker, seq: VariableTracker + ) -> VariableTracker: + return variables.FilterVariable( + fn, + generic_getiter(tx, seq), + mutation_type=ValueMutationNew(), + ) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + # Declarative type-attribute dispatch (__name__, __bases__, __base__, + # __flags__), mirroring the consultation at the top of + # VariableTracker.getattro_impl. Inlined because this override keeps its + # own object / GetAttrVariable handling below instead of delegating. + source = self.source and AttrSource(self.source, name) + if self.fn is object: + # for object, we can just directly read the attribute + try: + value = getattr(self.fn, name) + except AttributeError: + raise_observed_exception(AttributeError, tx) + if not callable(value): + return VariableTracker.build(tx, value, source) + attr = getattr(self.fn, name, None) + return variables.GetAttrVariable( + self, name, py_type=type(attr) if attr is not None else None, source=source + ) + + def call_delattr( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + name_var: VariableTracker, + ) -> VariableTracker: + return obj.call_method(tx, "__delattr__", [name_var], {}) + + def call_type( + self, tx: "InstructionTranslatorBase", obj: VariableTracker + ) -> VariableTracker: + try: + py_type = obj.python_type() + except NotImplementedError as error: + raise UserError( + UserErrorType.INVALID_INPUT, + str(error), + case_name="unknown_python_type", + ) from None + + source = obj.source and TypeSource(obj.source) + if ( + source is None + and isinstance(obj, variables.UserDefinedObjectVariable) + and obj.cls_source + ): + source = obj.cls_source + if py_type is torch.Tensor: + # In some cases torch isn't available in globals + name = tx.output.install_global_by_id("", torch) + source = AttrSource(GlobalSource(name), "Tensor") + + return VariableTracker.build(tx, py_type, source) + + def call_reversed( + self, tx: "InstructionTranslatorBase", obj: VariableTracker + ) -> VariableTracker: + # Mirrors CPython's builtin_reversed_impl (Python/enumobject.c) + # https://github.com/python/cpython/blob/60403a5409ff2c3f3b07dd2ca91a7a3e096839c7/Objects/enumobject.c#L353-L395 + # 1. Look up __reversed__ via _PyObject_LookupSpecial. If found, call it. + # 2. Else require PySequence_Check (sq_item). If absent, TypeError. + # 3. Else build a reverse sequence iterator over __len__ + __getitem__. + + obj_type = maybe_get_python_type(obj) + + # Type-level __reversed__ lookup, mirrors _PyObject_LookupSpecial. + # getattr_static skips descriptors / metaclass. CPython treats + # `__reversed__ = None` on the type as an explicit opt-out, raising + # TypeError even if the sequence protocol would otherwise work. + reversed_attr = inspect.getattr_static( + obj_type, "__reversed__", _MISSING_SENTINEL + ) + if reversed_attr is None: + raise_type_error(tx, f"'{obj_type.__name__}' object is not reversible") + if reversed_attr is not _MISSING_SENTINEL: + return obj.call_method(tx, "__reversed__", [], {}) + + if not pysequence_check(obj_type): + raise_type_error(tx, "argument to reversed() must be a sequence") + + return variables.UserFunctionVariable( + polyfills.builtins.reversed_sequence_iterator + ).call_function(tx, [obj], {}) + + def call_sorted( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + if not isinstance(obj, variables.TensorVariable): + list_var = variables.ListVariable( + unpack_iterable(tx, obj), + mutation_type=ValueMutationNew(), + ) + list_var.call_method(tx, "sort", [], kwargs) + return list_var + return None + + def call_neg( + self, tx: "InstructionTranslatorBase", a: VariableTracker + ) -> VariableTracker: + return pynumber_negative(tx, a) + + def call_invert( + self, tx: "InstructionTranslatorBase", a: VariableTracker + ) -> VariableTracker: + return pynumber_invert(tx, a) + + def call_format( + self, + tx: "InstructionTranslatorBase", + _format_string: VariableTracker, + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + format_string = _format_string.as_python_constant() + format_string = str(format_string) + return StringFormatVariable.create(format_string, list(args), kwargs) + + def call_id( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + if len(args) != 1: + raise_observed_exception( + TypeError, + tx, + args=[f"id() takes exactly one argument ({len(args)} given)"], + ) + arg = args[0] + + real_id = arg.get_id(tx) + if real_id is not None: + if arg.source: + guard_type = arg.get_id_guard_type() + if guard_type is not None: + install_guard(arg.source.make_guard(guard_type)) + return VariableTracker.build(tx, real_id) + + return FakeIdVariable(id(arg)) + + def call_deepcopy( + self, tx: "InstructionTranslatorBase", x: VariableTracker + ) -> VariableTracker: + unimplemented( + gb_type="copy.deepcopy()", + context=f"copy.deepcopy({x})", + explanation="Dynamo does not support copy.deepcopy()", + hints=[ + "Avoid calling copy.deepcopy()", + *graph_break_hints.SUPPORTABLE, + ], + ) + + def _comparison_with_tensor( + self, + tx: "InstructionTranslatorBase", + left: VariableTracker, + right: VariableTracker, + ) -> VariableTracker: + from .builder import wrap_fx_proxy_cls + from .tensor import supported_tensor_comparison_op_values + + op = self.fn + + if op in [operator.is_, operator.is_not]: + is_result = ( + left.is_tensor() + and right.is_tensor() + and id(extract_fake_example_value(left.as_proxy().node)) + == id(extract_fake_example_value(right.as_proxy().node)) + ) + if op is operator.is_: + return VariableTracker.build(tx, is_result) + else: + return VariableTracker.build(tx, not is_result) + + if op not in supported_tensor_comparison_op_values: + unimplemented( + gb_type="unsupported Tensor comparison op", + context=f"{op.__name__}({left}, {right})", + explanation=f"Dynamo does not support the comparison op {op.__name__} " + f"with Tensor arguments {left}, {right}", + hints=[*graph_break_hints.SUPPORTABLE], + ) + if ( + isinstance(left, TensorVariable) + and isinstance(right, TensorVariable) + and (left.size and right.size) is not None + and left.size != right.size + ): + try: + torch.broadcast_shapes(left.size, right.size) + except RuntimeError: + # not broadcastable, can't be compared + unimplemented( + gb_type="failed to broadcast when attempting Tensor comparison op", + context=f"{op.__name__}({left}, {right})", + explanation=f"Dynamo was unable to broad cast the arguments {left}, {right} " + f"when attempting to trace the comparison op {op.__name__}.", + hints=[*graph_break_hints.USER_ERROR], + ) + tensor_cls = left if left.is_tensor() else right + proxy = tx.output.create_proxy( + "call_function", op, (left.as_proxy(), right.as_proxy()), {} + ) + return wrap_fx_proxy_cls( + type(tensor_cls), # handle Ndarrays and Tensors + tx, + proxy, + ) + + def _comparison_with_symnode( + self, + tx: "InstructionTranslatorBase", + left: VariableTracker, + right: VariableTracker, + ) -> VariableTracker: + from .tensor import supported_tensor_comparison_op_values + + op = self.fn + + if op not in supported_tensor_comparison_op_values: + unimplemented( + gb_type="unsupported SymNode comparison op", + context=f"{op.__name__}({left}, {right})", + explanation=f"Dynamo does not support the comparison op {op.__name__} " + f"with SymNode arguments {left}, {right}", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + # SymNodes are numeric (int/float/bool). The non-SymNode operand + # must be a type that can participate in a traced numeric comparison. + # Anything else (classes, DataPtrVariable, etc.) is a different type + # entirely — the comparison result is known at compile time. + non_symnode = right if isinstance(left, SymNodeVariable) else left + if not isinstance( + non_symnode, (SymNodeVariable, ConstantVariable, TensorVariable) + ): + # pyrefly: ignore [bad-argument-type] + return VariableTracker.build(tx, op(object(), None)) + + proxy = tx.output.create_proxy( + "call_function", op, (left.as_proxy(), right.as_proxy()), {} + ) + return SymNodeVariable.create( + tx, + proxy, + sym_num=None, + ) + + def call_xor( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_op(tx, a, b, "nb_xor", "^") + + def call_ixor( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_iop(tx, a, b, "nb_inplace_xor", "nb_xor", "^=") + + def call_mul( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return pynumber_multiply(tx, a, b) + + def call_imul( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return pynumber_inplace_multiply(tx, a, b) + + def call_matmul( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return pynumber_matrix_multiply(tx, a, b) + + def call_imatmul( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return pynumber_inplace_matrix_multiply(tx, a, b) + + def call_sub( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_op(tx, a, b, "nb_subtract", "-") + + def call_isub( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_iop(tx, a, b, "nb_inplace_subtract", "nb_subtract", "-=") + + def call_add( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return pynumber_add(tx, a, b) + + def call_iadd( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return pynumber_inplace_add(tx, a, b) + + def call_and_( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_op(tx, a, b, "nb_and", "&") + + def call_iand( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_iop(tx, a, b, "nb_inplace_and", "nb_and", "&=") + + def call_or_( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_op(tx, a, b, "nb_or", "|") + + def call_ior( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_iop(tx, a, b, "nb_inplace_or", "nb_or", "|=") + + def call_lshift( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_op(tx, a, b, "nb_lshift", "<<") + + def call_ilshift( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_iop(tx, a, b, "nb_inplace_lshift", "nb_lshift", "<<=") + + def call_rshift( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_op(tx, a, b, "nb_rshift", ">>") + + def call_irshift( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_iop(tx, a, b, "nb_inplace_rshift", "nb_rshift", ">>=") + + def call_floordiv( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_op(tx, a, b, "nb_floor_divide", "//") + + def call_ifloordiv( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_iop(tx, a, b, "nb_inplace_floor_divide", "nb_floor_divide", "//=") + + def call_truediv( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_op(tx, a, b, "nb_true_divide", "/") + + def call_itruediv( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_iop(tx, a, b, "nb_inplace_true_divide", "nb_true_divide", "/=") + + def call_mod( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_op(tx, a, b, "nb_remainder", "%") + + def call_imod( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + return binary_iop(tx, a, b, "nb_inplace_remainder", "nb_remainder", "%=") + + def call_divmod( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker | None: + # PyNumber_Divmod dispatches through the nb_divmod slot with no + # in-place form. https://github.com/python/cpython/blob/3.13/Objects/abstract.c#L1056 + return binary_op(tx, a, b, "nb_divmod", "divmod()") + + def call_pow( + self, + tx: "InstructionTranslatorBase", + a: VariableTracker, + b: VariableTracker, + c: VariableTracker | None = None, + ) -> VariableTracker | None: + return ternary_op(tx, a, b, c, "nb_power", "** or pow()") + + def call_ipow( + self, + tx: "InstructionTranslatorBase", + a: VariableTracker, + b: VariableTracker, + c: VariableTracker | None = None, + ) -> VariableTracker | None: + return ternary_iop(tx, a, b, c, "nb_inplace_power", "nb_power", "**=") + + def call_not_( + self, tx: "InstructionTranslatorBase", a: VariableTracker + ) -> VariableTracker | None: + if isinstance(a, SymNodeVariable): + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.not_, *proxy_args_kwargs([a], {}) + ), + sym_num=None, + ) + + # Unwrap the underlying ConstDictVariable + if isinstance(a, DictViewVariable): + a = a.dv_dict + if isinstance(a, (ListVariable, ConstDictVariable, SetVariable)): + return VariableTracker.build(tx, len(a.items) == 0) + if isinstance(a, UserDefinedObjectVariable): + bool_result = self.call_bool(tx, a) + return VariableTracker.build(tx, not bool_result.value) # type: ignore[missing-attribute] + + return None + + def call_contains( + self, tx: "InstructionTranslatorBase", a: VariableTracker, b: VariableTracker + ) -> VariableTracker: + return pysequence_contains(tx, a, b) + + +class DictBuiltinVariable(BaseBuiltinVariable): + """Variable tracker for the `dict` builtin constructor.""" + + _fn = dict + + def __init__(self, value: type = dict, **kwargs: Any) -> None: + if value is not dict: + raise AssertionError(f"DictBuiltinVariable value must be dict, got {value}") + super().__init__(**kwargs) + + def __repr__(self) -> str: + return "DictBuiltinVariable()" + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return DictBuiltinVariable.call_custom_dict(tx, dict, *args, **kwargs) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "__new__": + if args: + # dict.__new__ (tp_new) ignores extra args — only the first + # arg (the type) matters. Pass init_args=[] so reconstruction + # emits base_cls.__new__(cls) without extras. + # https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c#L4735-L4768 + dict_vt = ConstDictVariable({}, mutation_type=ValueMutationNew()) + if isinstance(args[0], DictBuiltinVariable): + return dict_vt + return tx.output.side_effects.track_new_user_defined_object( + self, + args[0], + [], + tx=tx, + ) + + if name == "fromkeys": + return DictBuiltinVariable.call_custom_dict_fromkeys( + tx, dict, *args, **kwargs + ) + + resolved_fn = getattr(dict, name, None) + if resolved_fn is not None and resolved_fn in dict_methods: + if isinstance(args[0], variables.UserDefinedDictVariable): + if args[0]._base_vt is None: + raise AssertionError( + "UserDefinedDictVariable._base_vt must not be None for dict method dispatch" + ) + return args[0]._base_vt.call_method(tx, name, args[1:], kwargs) + elif isinstance(args[0], ConstDictVariable): + return args[0].call_method(tx, name, args[1:], kwargs) + + return super().call_method(tx, name, args, kwargs) + + @staticmethod + def call_custom_dict( + tx: "InstructionTranslatorBase", + user_cls: type, + /, + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + args_list = list(args) + return tx.inline_user_function_return( + VariableTracker.build(tx, polyfills.construct_dict), + [VariableTracker.build(tx, user_cls), *args_list], + kwargs, + ) + + @staticmethod + def call_custom_dict_fromkeys( + tx: "InstructionTranslatorBase", + user_cls: type, + /, + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if user_cls not in {dict, OrderedDict, defaultdict}: + unimplemented( + gb_type="Unsupported dict type for fromkeys()", + context=f"{user_cls.__name__}.fromkeys(): {args} {kwargs}", + explanation=f"Failed to call {user_cls.__name__}.fromkeys() because " + f"{user_cls.__name__} is not any type of dict, OrderedDict, or defaultdict", + hints=[ + f"Ensure {user_cls.__name__} is a type of dict, OrderedDict, or defaultdict.", + ], + ) + if kwargs: + # Only `OrderedDict.fromkeys` accepts `value` passed by keyword + if ( + user_cls is not OrderedDict + or len(args) != 1 + or len(kwargs) != 1 + or "value" not in kwargs + ): + raise_args_mismatch( + tx, + f"{user_cls.__name__}.fromkeys", + "1 args and 1 kwargs (`value`)", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + args = (*args, kwargs.pop("value")) + if len(args) == 0: + raise_args_mismatch( + tx, + f"{user_cls.__name__}.fromkeys", + "at least 1 args", + f"{len(args)} args", + ) + if len(args) == 1: + args = (*args, ConstantVariable.create(None)) + if len(args) != 2: + raise_args_mismatch( + tx, + f"{user_cls.__name__}.fromkeys", + "2 args", + f"{len(args)} args", + ) + + arg, value = args + + def _make_result( + items: dict[VariableTracker, VariableTracker], + ) -> VariableTracker: + if user_cls is OrderedDict: + return OrderedDictVariable(items, mutation_type=ValueMutationNew()) + elif user_cls is defaultdict: + from .builder import SourcelessBuilder + from .user_defined import DefaultDictVariable + + result = tx.output.side_effects.track_new_user_defined_object( + SourcelessBuilder.create(tx, dict), + SourcelessBuilder.create(tx, defaultdict), + [], + tx=tx, + ) + if not isinstance(result, DefaultDictVariable): + raise AssertionError( + f"Expected DefaultDictVariable, got {type(result)}" + ) + result._base_vt = ConstDictVariable( + items, mutation_type=ValueMutationNew() + ) + return result + else: + return ConstDictVariable(items, mutation_type=ValueMutationNew()) + + # Reuse the operand's existing HashableTracker keys instead of + # re-wrapping (and thus re-hashing) the underlying VTs, mirroring + # CPython's do-not-rehash-dict-keys behavior when building a dict from + # an existing set/frozenset/dict. + if isinstance(arg, (variables.SetVariable, ConstDictVariable)): + # HashableTracker keys are accepted by ConstDictVariable.__init__. + return _make_result(dict.fromkeys(arg.items.keys(), value)) # type: ignore[arg-type] + if isinstance(arg, dict): + arg_list = [VariableTracker.build(tx, k) for k in arg] + return _make_result(dict.fromkeys(arg_list, value)) + elif iterator := generic_getiter(tx, arg): + keys = unpack_iterable(tx, iterator) + if all(is_hashable(v) for v in keys): + return _make_result(dict.fromkeys(keys, value)) + + unimplemented( + gb_type="failed to call dict.fromkeys()", + context=f"{user_cls.__name__}.fromkeys(): {args} {kwargs}", + explanation=f"Failed to call {user_cls.__name__}.fromkeys() because " + "arguments could not be automatically converted to a list, " + "or some dict key is not hashable.", + hints=[ + "Manually convert the argument to a list.", + "Ensure all keys are hashable.", + ], + ) + + +class IterBuiltinVariable(BaseBuiltinVariable): + """Variable tracker for the `iter` builtin.""" + + _fn = iter + + def __init__(self, value: Any = iter, **kwargs: Any) -> None: + if value is not iter: + raise AssertionError(f"IterBuiltinVariable value must be iter, got {value}") + super().__init__(**kwargs) + + def __repr__(self) -> str: + return "IterBuiltinVariable()" + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Python/bltinmodule.c#L1666-L1682 + + if not args: + raise_observed_exception( + TypeError, + tx, + args=["iter expected at least 1 argument, got 0"], + ) + + if len(args) == 1: + return generic_getiter(tx, args[0]) + else: + return variables.UserFunctionVariable( + polyfills.builtins.callable_iterator + ).call_function(tx, args, kwargs) + + +class GetAttrBuiltinVariable(BaseBuiltinVariable): + """Variable tracker for the `getattr` builtin.""" + + _fn = getattr + + def __init__(self, value: Any = getattr, **kwargs: Any) -> None: + if value is not getattr: + raise AssertionError( + f"GetAttrBuiltinVariable value must be getattr, got {value}" + ) + super().__init__(**kwargs) + + def __repr__(self) -> str: + return "GetAttrBuiltinVariable()" + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .lazy import LazyVariableTracker + + if any(isinstance(a, LazyVariableTracker) for a in args): + args = [ + a.realize() if isinstance(a, LazyVariableTracker) else a for a in args + ] + try: + return self._call_getattr(tx, args, kwargs) + except Unsupported: + # Replicate the constant-fold fallback from BuiltinVariable._make_handler: + # if all args are python constants, evaluate getattr() directly rather + # than propagating a graph break from tp_getattro_impl. + if not check_unspec_or_constant_args(args, kwargs): + raise + try: + result = getattr(*[a.as_python_constant() for a in args]) + except AttributeError: + raise_observed_exception(AttributeError, tx) + raise + except AsPythonConstantNotImplementedError: + raise + except Exception as exc: + raise_observed_exception(type(exc), tx, args=list(exc.args)) + raise + return VariableTracker.build(tx, result) + + def _call_getattr( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + obj = args[0] + name_var = args[1] + default = args[2] if len(args) > 2 else _NO_DEFAULT + + if not name_var.is_python_constant(): + unimplemented( + gb_type="getattr() with non-constant name argument", + context=f"getattr({obj}, {name_var}, {default})", + explanation="getattr() with non-constant name argument is not supported", + hints=["Ensure the name argument of getattr() is a string"], + ) + + name = name_var.as_python_constant() + return generic_getattr(tx, obj, name, default) + + +class HasAttrBuiltinVariable(BaseBuiltinVariable): + """Variable tracker for the `hasattr` builtin.""" + + _fn = hasattr + + def __init__(self, value: Any = hasattr, **kwargs: Any) -> None: + if value is not hasattr: + raise AssertionError( + f"HasAttrBuiltinVariable value must be hasattr, got {value}" + ) + super().__init__(**kwargs) + + def __repr__(self) -> str: + return "HasAttrBuiltinVariable()" + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: Sequence[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .lazy import LazyVariableTracker + + if any(isinstance(a, LazyVariableTracker) for a in args): + args = [ + a.realize() if isinstance(a, LazyVariableTracker) else a for a in args + ] + if len(args) != 2 or kwargs: + raise_observed_exception(TypeError, tx) + obj, attr = args + if not attr.is_python_constant(): + raise_observed_exception(TypeError, tx) + result = obj.call_obj_hasattr(tx, attr.as_python_constant()) + if result is None: + unimplemented( + gb_type="hasattr() on unsupported type", + context=f"hasattr({obj}, {attr})", + explanation=f"hasattr() is not supported on type {obj.python_type_name()}", + hints=[*graph_break_hints.SUPPORTABLE], + ) + return result + + +class SetAttrBuiltinVariable(BaseBuiltinVariable): + """Variable tracker for the `setattr` builtin.""" + + _fn = setattr + + def __init__(self, value: Any = setattr, **kwargs: Any) -> None: + if value is not setattr: + raise AssertionError( + f"SetAttrBuiltinVariable value must be setattr, got {value}" + ) + super().__init__(**kwargs) + + def __repr__(self) -> str: + return "SetAttrBuiltinVariable()" + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: Sequence[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .lazy import LazyVariableTracker + + if any(isinstance(a, LazyVariableTracker) for a in args): + args = [ + a.realize() if isinstance(a, LazyVariableTracker) else a for a in args + ] + if len(args) != 3 or kwargs: + raise_observed_exception(TypeError, tx) + obj, name_var, val = args + result = self._call_setattr(tx, obj, name_var, val) + if result is not None: + return result + unimplemented( + gb_type="setattr() on unsupported type", + context=f"setattr({obj}, {name_var}, {val})", + explanation=f"setattr() is not supported on type {obj.python_type_name()}", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def _call_setattr( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + name_var: VariableTracker, + val: VariableTracker, + ) -> VariableTracker | None: + if isinstance( + obj, + ( + variables.DefaultDictVariable, + variables.UserDefinedObjectVariable, + variables.NestedUserFunctionVariable, + variables.ExceptionVariable, + variables.TracebackVariable, + variables.DequeVariable, + ), + ): + return obj.call_method(tx, "__setattr__", [name_var, val], {}) + elif ( + not tx.output.side_effects.is_attribute_mutation(obj) + and obj.source is not None + and (underlying := obj.get_value_for_setattr()) is not None + and hasattr(underlying, "__dict__") + and name_var.is_python_constant() + ): + tx.output.side_effects.track_object_existing(underlying, obj) + name = name_var.as_python_constant() + tx.output.side_effects.store_attr(obj, name, val) + return val + elif ( + tx.output.side_effects.is_attribute_mutation(obj) + and name_var.is_python_constant() + ): + name = name_var.as_python_constant() + if obj.is_tensor(): + from .builder import wrap_fx_proxy + + if name == "requires_grad": + # TODO(azahed98): Make it work properly + unimplemented( + gb_type="setattr() on Tensor.requires_grad", + context=f"setattr({obj}, {name}, {val})", + explanation="setattr() on Tensor.requires_grad not supported. " + "Mutating requires_grad can introduce a new leaf from non-leaf or vice versa in " + "the middle of the graph, which AOTAutograd does not currently know how to handle.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + elif name == "data": + # [Note: set_data_on_scoped_tensor] + if obj.source is None: + unimplemented( + gb_type="Failed to mutate tensor data attribute", + context=f"setattr({obj}, {name}, {val})", + explanation="Dynamo only supports mutating `.data`" + " of tensor created outside `torch.compile` region", + hints=[ + "Don't mutate `.data` on this tensor, or move " + "the mutation out of `torch.compile` region", + ], + ) + elif obj.dtype != val.dtype: # type: ignore[attr-defined] + unimplemented( + gb_type="Failed to mutate tensor data attribute to different dtype", + context=f"setattr({obj}, {name}, {val})", + explanation="Dynamo only supports mutating `.data`" + " of tensor to a new one with the same dtype", + hints=[ + "Don't mutate `.data` on this tensor, or move " + "the mutation out of `torch.compile` region", + ], + ) + elif obj.device != val.device: # type: ignore[attr-defined] + obj_fake = get_fake_value(obj.as_proxy().node, tx) + val_fake = get_fake_value(val.as_proxy().node, tx) + if ( + obj_fake.dtype != val_fake.dtype + or obj_fake.shape != val_fake.shape + or obj_fake.stride() != val_fake.stride() + ): + unimplemented( + gb_type="Failed to mutate tensor data attribute across devices with different shape/strides", + context=f"setattr({obj}, {name}, {val})", + explanation="Dynamo only supports cross-device `.data`" + " mutation when shape and strides match", + hints=[ + "Don't mutate `.data` on this tensor, or move " + "the mutation out of `torch.compile` region", + ], + ) + + # Remove the old reference in tracked fakes - if we don't + # do this, .data value size/shape differences cause + # tracked fakes to produce incorrect guards. Sound + # because the TensorVariable from shallow_copy_data_ + # below is new and gets installed in tracked fakes. + to_remove = [ + tf for tf in tx.output.tracked_fakes if tf.source == obj.source + ] + for tf in to_remove: + tx.output.tracked_fakes.remove(tf) + + # Snapshot the placeholder before + # shallow_copy_data_ mutates it. Record the node + # and snapshot so compile_and_call_fx_graph can + # restore the correct metadata before passing the + # graph to the backend. + input_node = obj.as_proxy().node + if input_node.op == "placeholder": + ev = input_node.meta.get("example_value") + if ev is not None and hasattr(ev, "fake_mode"): + from torch._subclasses.fake_impls import fast_detach + + snapshot = fast_detach(ev.fake_mode, ev) + tx.output._shallow_copy_placeholder_snapshots.setdefault( + input_node, snapshot + ) + + with dynamo_disable_grad(tx), torch.no_grad(): + out = wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", + torch.ops.aten.shallow_copy_data_, + *proxy_args_kwargs([obj, val], {}), + ), + ) + + return out + elif name in ("_grad", "grad"): + # NOTE: [Tensor "grad" and "_grad" attr] + # _grad and grad share the same setter/getter, see + # THPVariable_properties, and here we make sure setting one + # enables reading `val` from the other, by routing all + # read/write to `grad`. + name = "grad" + elif is_tensor_getset_descriptor(name): + # Attribute like `torch.Tensor.real` has special setters we + # don't yet support; it's not as simple adding an entry to + # the side effect mapping. + unimplemented( + gb_type="Failed to set tensor attribute", + context=f"setattr({obj}, {name}, {val})", + explanation="Dynamo doesn't support setting these tensor attributes", + hints=[ + f"Don't mutate attribute '{name}' on tensors, or " + "move the mutation out of `torch.compile` region", + ], + ) + + tx.output.side_effects.store_attr(obj, name, val) + return val + elif isinstance(obj, variables.NNModuleVariable): + if not tx.output.is_root_tracer(): + unimplemented( + gb_type="nn.Module mutation in HigherOrderOp", + context=f"nn.Module: {obj}", + explanation="Inplace modifying nn.Module params/buffers inside HigherOrderOps is not allowed.", + hints=[ + "Remove the mutation or move it outside of the HigherOrderOp.", + *graph_break_hints.FUNDAMENTAL, + ], + ) + if name_var.is_python_constant() and isinstance( + val, variables.TensorVariable + ): + assigning_fake_val = get_fake_value(val.as_proxy().node, tx) + + try: + getattr_var = obj.tp_getattro_impl( + tx, name_var.as_python_constant() + ) + except (AttributeError, ObservedAttributeError): + getattr_var = None + + if getattr_var is not None and getattr_var.is_tensor(): + # get_fake_val will get the same fake tensor + existing_fake_attr = get_fake_value(getattr_var.as_proxy().node, tx) + + # same tensor identity, setattr is a no-op + mod_setattr = inspect.getattr_static(obj.module_type, "__setattr__") + if ( + existing_fake_attr is assigning_fake_val + and mod_setattr is torch.nn.Module.__setattr__ + ): + return getattr_var + + obj.convert_to_unspecialized(tx) + return None + + +class ListBuiltinVariable(BaseBuiltinVariable): + """Variable tracker for the `list` builtin constructor.""" + + _fn = list + + def __init__(self, value: type = list, **kwargs: Any) -> None: + if value is not list: + raise AssertionError(f"ListBuiltinVariable value must be list, got {value}") + super().__init__(**kwargs) + + def __repr__(self) -> str: + return "ListBuiltinVariable()" + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/listobject.c#L1265-L1287 + if kwargs: + raise_type_error( + tx, + "list() takes no keyword arguments", + ) + if len(args) == 0: + return ListVariable([], mutation_type=ValueMutationNew()) + elif len(args) > 1: + raise_type_error( + tx, + f"list expected at most 1 argument, got {len(args)}", + ) + + obj = args[0] + if obj.source and not is_constant_source(obj.source): + if isinstance(obj, TupleIteratorVariable): + install_guard(obj.source.make_guard(GuardBuilder.TUPLE_ITERATOR_LEN)) + elif not isinstance( + obj, + (variables.IteratorVariable, variables.LocalGeneratorObjectVariable), + ): + if isinstance( + obj, + ( + ConstDictVariable, + variables.OrderedSetVariable, + variables.DictKeySetVariable, + ), + ): + tx.output.guard_on_key_order.add(obj.source) + if isinstance(obj, variables.MappingProxyVariable): + install_guard( + obj.source.make_guard(GuardBuilder.MAPPING_KEYS_CHECK) + ) + elif not isinstance(obj, variables.UnspecializedNNModuleVariable): + install_guard(obj.source.make_guard(GuardBuilder.SEQUENCE_LENGTH)) + + lst = ListVariable([], mutation_type=ValueMutationNew()) + lst.call_method(tx, "extend", [args[0]], {}) + return lst + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "__new__": + if len(args) == 1 and not kwargs: + list_vt = ListVariable([], mutation_type=ValueMutationNew()) + if isinstance(args[0], ListBuiltinVariable): + return list_vt + return tx.output.side_effects.track_new_user_defined_object( + self, + args[0], + args[1:], + tx=tx, + ) + + return super().call_method(tx, name, args, kwargs) + + +# pyrefly: ignore [deprecated] +@contextlib.contextmanager +def dynamo_disable_grad(tx: "InstructionTranslatorBase") -> typing.Iterator[None]: + from . import GradModeVariable + + gmv = GradModeVariable.create(tx, False) + try: + gmv.enter(tx) + yield + finally: + gmv.exit(tx) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/constant.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/constant.py new file mode 100644 index 0000000000000000000000000000000000000000..8d555f40c7cfd9169d7b780cd1c5fa66d3d7a34c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/constant.py @@ -0,0 +1,1031 @@ +""" +Constant variable tracking in Dynamo. + +This module is fundamental to Dynamo's ability to track and propagate constant +values during compilation, ensuring proper handling of Python literals and +maintaining type safety through the compilation process. +""" + +from __future__ import annotations + +import enum +import operator +from collections.abc import Iterable +from typing import Any, Literal, overload, TYPE_CHECKING + +import torch +from torch._dynamo.source import GetItemSource + +from .. import graph_break_hints, variables +from ..exc import raise_observed_exception, raise_type_error, unimplemented +from ..utils import ( + common_constant_types, + istype, + np, + raise_args_mismatch, + unpack_iterable, +) +from .base import ValueMutationNew, VariableTracker + + +if TYPE_CHECKING: + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + from .functions import UserFunctionVariable + + +class ConstantVariable(VariableTracker): + """ + Variable tracker for Python literals and basic immutable types, with automatic + routing support for collection types (lists, tuples, sets, etc.). + + The create() method intelligently constructs appropriate variable types for + nested collections. + """ + + # PyLong_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L6585 + # PyFloat_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c#L1880 + # PyBool_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/boolobject.c#L171 + # PyUnicode_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/unicodeobject.c#L14931 + # PyBytes_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/bytesobject.c#L3017 + # PyComplex_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/complexobject.c#L1099 + # _PyNone_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/object.c#L2022 + _cpython_type = (int, float, str, bytes, bool, type(None), complex, type(...)) + + @overload + @staticmethod + def create(value: None) -> ConstantVariable: ... + + @overload + @staticmethod + def create(value: bool) -> ConstantVariable: ... + + @overload + @staticmethod + def create(value: Any, **kwargs: Any) -> VariableTracker: ... + + @staticmethod + def create(value: Any, **kwargs: Any) -> VariableTracker: + """ + Create a `ConstantVariable` based on the given value, and supports + automatic routing for collection types like `tuple` (in which case we'd + create `ConstantVariable` for the leaf items). + + NOTE: the caller must install the proper guards if needed; most often + the guard will be `CONSTANT_MATCH`. + """ + # Return pre-allocated sentinels for None/True/False when there are + # no extra kwargs (source, etc.) that would differentiate the instance. + if not kwargs: + match value: + case None: + return CONSTANT_VARIABLE_NONE + case True: + return CONSTANT_VARIABLE_TRUE + case False: + return CONSTANT_VARIABLE_FALSE + + source = kwargs.get("source") + + # Routing for supported collection literals. + if isinstance(value, set): + items = [ConstantVariable.create(x) for x in value] + return variables.SetVariable(items, **kwargs) # type: ignore[arg-type] + elif isinstance(value, frozenset): + items = [ConstantVariable.create(x) for x in value] + return variables.FrozensetVariable(items, **kwargs) # type: ignore[arg-type] + elif isinstance(value, slice): + slice_args = (value.start, value.stop, value.step) + slice_args_vars: list[VariableTracker] = [ + ConstantVariable.create(arg) for arg in slice_args + ] + return variables.SliceVariable(slice_args_vars, **kwargs) + elif isinstance(value, (list, tuple)): + items = [] + for i, x in enumerate(value): + item_source = GetItemSource(source, i) if source else None + items.append( + ConstantVariable.create( + x, + source=item_source, + ) + ) + return variables.BaseListVariable.cls_for(type(value))(items, **kwargs) + + return ConstantVariable(value, **kwargs) + + def __init__(self, value: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + if not ConstantVariable.is_base_literal(value): + raise AssertionError( + f"Cannot construct `ConstantVariable` for value of type {type(value)}.\n" + "\n" + "This failure likely due to PyTorch-internal use of `ConstantVariable` on\n" + "non-literal python values, please try using `VariableTracker.build` instead. If\n" + "you believe it's a necessary and legitimate use case (the value is immutable and\n" + "can't easily be represented with another `VariableTracker` class), please add\n" + "its type to `common_constant_types`." + ) + if np is not None and isinstance(value, np.number): + self.value = value.item() + else: + self.value = value + + def as_proxy(self) -> Any: + return self.value + + def __repr__(self) -> str: + return f"ConstantVariable({type(self.value).__name__}: {repr(self.value)})" + + def as_python_constant(self) -> Any: + return self.value + + def is_python_constant(self) -> Literal[True]: + return True + + def tp_repr_impl(self, tx: InstructionTranslatorBase) -> VariableTracker: + return ConstantVariable.create(repr(self.value)) + + def is_symnode_like(self) -> bool: + return isinstance(self.value, (int, bool)) + + def is_constant_match(self, *values: Any) -> bool: + return self.value in values + + def is_constant_none(self) -> bool: + return self.value is None + + @property + def items(self) -> list[VariableTracker]: + """ + Need this when adding a BaseListVariable and a ConstantVariable together. + Happens in detectron2. + """ + try: + return [ConstantVariable.create(x) for x in self.value] + except TypeError as e: + raise NotImplementedError from e + + def getitem_const( + self, tx: InstructionTranslatorBase, arg: VariableTracker + ) -> VariableTracker: + # bytes_subscript: https://github.com/python/cpython/blob/62a6e898e017c9878490544f6a227b8a187a949c/Objects/bytesobject.c#L1732 + # unicode_subscript: https://github.com/python/cpython/blob/62a6e898e017c9878490544f6a227b8a187a949c/Objects/unicodeobject.c#L13738 + if isinstance(self.value, (str, bytes)): + from .lists import SliceVariable + from .object_protocol import maybe_get_python_type, pyindex_check + + # _PyIndex_Check first, then slice, mirroring unicode_subscript / + # bytes_subscript. + if pyindex_check(maybe_get_python_type(arg)): + arg = arg.nb_index_impl(tx) + elif isinstance(arg, SliceVariable): + return ConstantVariable.create(self.value[arg.as_index_slice(tx)]) + else: + raise_type_error( + tx, + f"{self.python_type_name()} indices must be integers, " + f"not {arg.python_type_name()}", + ) + return ConstantVariable.create( + self.value[arg.as_python_constant()], + ) + + def sq_item_impl( + self, tx: InstructionTranslatorBase, key: VariableTracker + ) -> VariableTracker: + # unicode_getitem: https://github.com/python/cpython/blob/62a6e898e01/Objects/unicodeobject.c#L13777 + # bytes_item: https://github.com/python/cpython/blob/62a6e898e01/Objects/bytesobject.c#L319 + # CPython's sq_item takes Py_ssize_t (already int from generic_getitem's + # nb_index_impl). Unlike mp_subscript, sq_item never handles slices. + index = key.as_python_constant() + try: + return ConstantVariable.create(self.value[index]) + except IndexError as e: + raise_observed_exception(IndexError, tx, args=list(e.args)) + + @staticmethod + def is_base_literal(obj: object) -> bool: + return type(obj) in common_constant_types + + @staticmethod + def is_literal(obj: object, cache: dict[int, object] | None = None) -> bool: + if cache is None: + cache = {} + if id(obj) in cache: + # no-op if there is a cyclical reference + return True + if type(obj) in (list, tuple, set, frozenset, torch.Size): + cache[id(obj)] = obj + return all(ConstantVariable.is_literal(x, cache) for x in obj) # type: ignore[attr-defined] + return ConstantVariable.is_base_literal(obj) + + def unpack_var_sequence( + self, tx: InstructionTranslatorBase | None + ) -> list[VariableTracker]: + try: + return [ConstantVariable.create(x) for x in self.as_python_constant()] + except TypeError as e: + raise NotImplementedError from e + + def hash_impl(self, tx: InstructionTranslatorBase) -> tuple[int, bool]: + """Dynamo tracing rule for long_hash, float_hash, unicode_hash, etc.""" + return hash(self.value), False + + def tp_richcompare_impl( + self, tx: InstructionTranslatorBase, other: VariableTracker, op: str + ) -> VariableTracker: + from .object_protocol import python_constant_richcompare_impl + + return python_constant_richcompare_impl(self, tx, other, op) + + def tp_str_impl(self, tx: InstructionTranslatorBase) -> VariableTracker: + return ConstantVariable.create(str(self.value)) + + def len_impl(self, tx: InstructionTranslatorBase) -> VariableTracker: + """Generic len for any constant value (sequence or mapping).""" + try: + return ConstantVariable.create(len(self.value)) + except TypeError as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + + def sq_length_impl(self, tx: InstructionTranslatorBase) -> VariableTracker: + """Sequence length - delegates to len_impl for constants.""" + return self.len_impl(tx) + + def mp_length_impl(self, tx: InstructionTranslatorBase) -> VariableTracker: + """Mapping length - delegates to len_impl for constants.""" + return self.len_impl(tx) + + def const_getattr( + self, tx: InstructionTranslatorBase, name: str + ) -> VariableTracker: + if not hasattr(self.value, name): + raise_observed_exception(AttributeError, tx, args=[name]) + member = getattr(self.value, name) + if callable(member): + raise NotImplementedError + return member + + def sq_contains_impl(self, tx: InstructionTranslatorBase, item: VariableTracker): + """Sequence contains for constants.""" + if item.is_python_constant(): + search = item.as_python_constant() + try: + result = search in self.value + return ConstantVariable.create(result) + except TypeError as e: + raise_observed_exception( + type(e), + tx, + args=list(e.args), + ) + return super().sq_contains_impl(tx, item) + + def tp_iter_impl(self, tx: InstructionTranslatorBase) -> VariableTracker: + from .lists import ListIteratorVariable + + if isinstance(self.value, Iterable): + try: + return ListIteratorVariable( + [ConstantVariable.create(c) for c in self.value], + mutation_type=ValueMutationNew(), + ) + except NotImplementedError: + pass + return super().tp_iter_impl(tx) + + def call_method( + self, + tx: InstructionTranslatorBase, + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .tensor import SymNodeVariable + + if name == "format" and istype(self.value, str): + return variables.BuiltinVariable(str.format).call_function( + tx, + [self, *args], + kwargs, + ) + elif name == "join" and istype(self.value, str): + if kwargs or len(args) != 1: + raise_args_mismatch( + tx, + name, + "1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + arg_unpacked = unpack_iterable(tx, args[0]) + try: + arg_const = [x.as_python_constant() for x in arg_unpacked] + return ConstantVariable.create(self.value.join(arg_const)) + except NotImplementedError: + return super().call_method(tx, name, args, kwargs) + + if any(isinstance(x, SymNodeVariable) for x in args): + # Promote to SymNodeVariable for operations involving dynamic shapes. + return variables.SymNodeVariable.create( + tx, self.as_proxy(), self.value + ).call_method(tx, name, args, kwargs) + + try: + const_args = [a.as_python_constant() for a in args] + const_kwargs = {k: v.as_python_constant() for k, v in kwargs.items()} + except NotImplementedError: + return super().call_method(tx, name, args, kwargs) + + if name == "__iter__": + return self.tp_iter_impl(tx) + + if isinstance(self.value, str) and name in str.__dict__: + method = getattr(self.value, name) + try: + result = method(*const_args, **const_kwargs) + except Exception as e: + raise_observed_exception(type(e), tx) + # str.split/rsplit/splitlines return a fresh caller-owned list; + # mark it mutable so in-place ops (.sort(), shuffle, etc.) are tracked. + if name in ("split", "rsplit", "splitlines"): + return ConstantVariable.create(result, mutation_type=ValueMutationNew()) + return ConstantVariable.create(result) + elif isinstance(self.value, (float, int)) and hasattr(self.value, name): + if not (args or kwargs): + try: + return ConstantVariable.create(getattr(self.value, name)()) + except (OverflowError, ValueError) as exc: + raise_observed_exception( + type(exc), + tx, + args=list(exc.args), + ) + if ( + hasattr(operator, name) + and len(args) == 1 + and args[0].is_python_constant() + ): + add_target = const_args[0] + op = getattr(operator, name) + if isinstance( + add_target, (torch.SymBool, torch.SymFloat, torch.SymInt) + ): + # Addition between a non sym and sym makes a sym + proxy = tx.output.create_proxy( + "call_function", op, (self.value, add_target), {} + ) + return SymNodeVariable.create(tx, proxy, add_target) + else: + try: + return ConstantVariable.create(op(self.value, add_target)) + except Exception as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + elif isinstance(self.value, bytes) and name == "decode": + method = getattr(self.value, name) + return ConstantVariable.create(method(*const_args, **const_kwargs)) + elif type(self.value) is complex and name in complex.__dict__: + method = getattr(self.value, name) + try: + return ConstantVariable.create(method(*const_args, **const_kwargs)) + except Exception as e: + raise_observed_exception(type(e), tx) + + if name == "__round__" and len(args) == 1 and args[0].is_python_constant(): + try: + return ConstantVariable.create( + round(self.value, args[0].as_python_constant()) + ) + except Exception as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + return super().call_method(tx, name, args, kwargs) + + def call_tree_map( + self, + tx: InstructionTranslatorBase, + tree_map_fn: UserFunctionVariable, + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if self.value is None: + none_is_leaf_var = tree_map_kwargs.get("none_is_leaf") + if none_is_leaf_var is not None: + try: + none_is_leaf = bool(none_is_leaf_var.as_python_constant()) + except NotImplementedError: + return self._tree_map_fallback( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + ) + else: + tree_map_module = getattr( + getattr(tree_map_fn, "fn", None), "__module__", "" + ) + # torch.utils._pytree and torch.utils._cxx_pytree treat None as a leaf + # by default, while optree keeps it as an internal node unless + # none_is_leaf=True is provided. + none_is_leaf = not tree_map_module.startswith("optree") + if none_is_leaf: + return map_fn.call_function(tx, [self, *rest], {}) + else: + for other in rest: + if not other.is_constant_none(): + return self._tree_map_fallback( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + ) + return self.clone() + if isinstance(self.value, (int, float, bool, complex, str, bytes, torch.dtype)): + return map_fn.call_function(tx, [self, *rest], {}) + return super().call_tree_map( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + ) + + def reconstruct_pycode(self, codegen) -> str: + return repr(self.value) + + def get_id(self, tx: InstructionTranslatorBase) -> int | None: + # Singletons have guaranteed stable identity across the process lifetime. + if self.value is None or self.value is True or self.value is False: + return id(self.value) + # Sourceful constants resolve via source like any other sourceful VT. + # Sourceless non-singleton constants (e.g. literal 42 in compiled code) + # get FakeIdVariable — CPython interning of small ints/strings is an + # implementation detail users shouldn't rely on. + return super().get_id(tx) + + def get_real_python_backed_value(self) -> object: + return self.value + + def nb_index_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + # CPython: int and bool define nb_index (returns self for int, + # int(self) for bool). All other constant types do not. + from .object_protocol import type_implements_nb_index + + if type_implements_nb_index(type(self.value)): + return ConstantVariable.create(operator.index(self.value)) + return super().nb_index_impl(tx) + + def nb_int_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + # CPython: int defines nb_int (long_long, returns copy). + # bool inherits nb_int from int via slot inheritance. + # float defines nb_int (truncates toward zero via PyLong_FromDouble). + return ConstantVariable.create(int(self.value)) + + def nb_float_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + # CPython: float defines nb_float (float_float, returns copy). + # int defines nb_float (long_float, converts to float). + # bool inherits nb_float from int via slot inheritance. + return ConstantVariable.create(float(self.value)) + + def _nb_binary_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + op: Any, + type_check: Any, + reverse: bool, + ) -> VariableTracker: + # Shared body for ConstantVariable's binary nb_* slots. Mirrors the + # CPython contract: if the type doesn't implement the slot, return + # NotImplemented so dispatch can try the reverse slot; otherwise run + # ``op(v, w)`` and re-raise arithmetic exceptions as observed. + if not type_check(type(self.value)): + return ConstantVariable.create(NotImplemented) + if not other.is_python_constant(): + return ConstantVariable.create(NotImplemented) + self_, other_ = (other, self) if reverse else (self, other) + v, w = self_.as_python_constant(), other_.as_python_constant() + try: + result = op(v, w) + except (TypeError, ValueError, OverflowError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + if result is NotImplemented: + return ConstantVariable.create(NotImplemented) + return VariableTracker.build(tx, result) + + def nb_lshift_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython: only int defines nb_lshift; bool inherits via slot inheritance. + # https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L5489 (long_lshift) + from .object_protocol import type_implements_nb_lshift + + return self._nb_binary_impl( + tx, other, operator.lshift, type_implements_nb_lshift, reverse + ) + + def nb_rshift_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython: only int defines nb_rshift; bool inherits via slot inheritance. + # https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L5526 (long_rshift) + from .object_protocol import type_implements_nb_rshift + + return self._nb_binary_impl( + tx, other, operator.rshift, type_implements_nb_rshift, reverse + ) + + def nb_floor_divide_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython: int and float define nb_floor_divide; bool inherits int's. + # complex does NOT (complex floor division raises TypeError). + # https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L4057 (long_floor_div) + # https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c#L660 (float_floor_div) + if not isinstance(self.value, (int, float)): + return ConstantVariable.create(NotImplemented) + if not other.is_python_constant(): + return ConstantVariable.create(NotImplemented) + self_, other_ = (other, self) if reverse else (self, other) + v, w = self_.as_python_constant(), other_.as_python_constant() + try: + return VariableTracker.build(tx, v // w) + except (TypeError, ValueError, ZeroDivisionError, OverflowError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + + def nb_true_divide_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython: int, float, and complex define nb_true_divide; bool inherits int's. + # https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L4146 (long_true_divide) + # https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c#L618 (float_div) + # https://github.com/python/cpython/blob/v3.13.0/Objects/complexobject.c#L518 (complex_div) + if not isinstance(self.value, (int, float, complex)): + return ConstantVariable.create(NotImplemented) + if not other.is_python_constant(): + return ConstantVariable.create(NotImplemented) + self_, other_ = (other, self) if reverse else (self, other) + v, w = self_.as_python_constant(), other_.as_python_constant() + try: + return VariableTracker.build(tx, v / w) + except (TypeError, ValueError, ZeroDivisionError, OverflowError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + + def nb_remainder_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython: int and float define nb_remainder (bool inherits int's); complex + # does NOT. str/bytes/bytearray define nb_remainder for %-formatting. + # https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L4116 (long_mod) + # https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c#L640 (float_rem) + # https://github.com/python/cpython/blob/v3.13.0/Objects/unicodeobject.c#L15170 (unicode_mod) + if not isinstance(self.value, (int, float, str, bytes, bytearray)): + return ConstantVariable.create(NotImplemented) + if not other.is_python_constant(): + return ConstantVariable.create(NotImplemented) + self_, other_ = (other, self) if reverse else (self, other) + v, w = self_.as_python_constant(), other_.as_python_constant() + try: + return VariableTracker.build(tx, v % w) + except (TypeError, ValueError, ZeroDivisionError, OverflowError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + + def nb_divmod_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython: int and float define nb_divmod (bool inherits int's); complex + # does NOT. Returns a (quotient, remainder) tuple. + # https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L4126 (long_divmod) + # https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c#L680 (float_divmod) + if not isinstance(self.value, (int, float)): + return ConstantVariable.create(NotImplemented) + if not other.is_python_constant(): + return ConstantVariable.create(NotImplemented) + self_, other_ = (other, self) if reverse else (self, other) + v, w = self_.as_python_constant(), other_.as_python_constant() + try: + return VariableTracker.build(tx, divmod(v, w)) + except (TypeError, ValueError, ZeroDivisionError, OverflowError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + + def nb_or_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython: int, frozenset, and type all define nb_or. + # https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L5606 (long_or) + # https://github.com/python/cpython/blob/v3.13.0/Objects/setobject.c#L1319 (set_or) + # https://github.com/python/cpython/blob/v3.13.0/Objects/typeobject.c#L6028-L6030 (type_as_number.nb_or) + # bool inherits int's nb_or via slot inheritance. + from .object_protocol import type_implements_nb_or + + return self._nb_binary_impl( + tx, other, operator.or_, type_implements_nb_or, reverse + ) + + def nb_subtract_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython: int, float, and complex define nb_subtract; bool inherits int's. + # https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L3819-L3824 (long_sub_method) + # https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c#L598-L606 (float_sub) + # https://github.com/python/cpython/blob/v3.13.0/Objects/complexobject.c#L494-L503 (COMPLEX_BINOP(sub, diff)) + from .object_protocol import type_implements_nb_subtract + + return self._nb_binary_impl( + tx, other, operator.sub, type_implements_nb_subtract, reverse + ) + + def nb_multiply_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # int, float, and complex all define nb_multiply (bool inherits int's slot). + # https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L4242-L4260 (long_mul) + # https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c#L608-L616 (float_mul) + # https://github.com/python/cpython/blob/v3.13.0/Objects/complexobject.c#L506 (complex_mul) + # str/bytes/bytearray do NOT have nb_multiply — they go through sq_repeat, + # so this method should not see them as ``self``. + from .object_protocol import type_implements_nb_multiply + + if not other.is_python_constant(): + return ConstantVariable.create(NotImplemented) + other_val = other.as_python_constant() + # CPython's nb_multiply (e.g. long_mul, float_mul) returns NotImplemented + # whenever the other operand isn't numeric — sequence repetition is + # then handled by PyNumber_Multiply's sq_repeat fallback. We mirror that + # here because ``operator.mul`` performs the full protocol (including + # sq_repeat) and would incorrectly short-circuit the dispatch. + if not isinstance(other_val, (int, float, complex)): + return ConstantVariable.create(NotImplemented) + return self._nb_binary_impl( + tx, other, operator.mul, type_implements_nb_multiply, reverse + ) + + def sq_repeat_impl( + self, + tx: InstructionTranslatorBase, + count: VariableTracker, + ) -> VariableTracker: + # Only str / bytes are reachable via ConstantVariable since list, tuple, + # bytearray have their own VTs. ``count`` was already validated as an + # index by pysequence_repeat -> nb_index_impl. + # https://github.com/python/cpython/blob/v3.13.0/Objects/unicodeobject.c#L12371 (unicode_repeat) + # https://github.com/python/cpython/blob/v3.13.0/Objects/bytesobject.c#L1448 (bytes_repeat) + if not isinstance(self.value, (str, bytes)): + raise AssertionError("Expected str or bytes in sq_repeat_impl") + n = count.as_python_constant() + try: + return ConstantVariable.create(self.value * n) + except (MemoryError, OverflowError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + + def nb_and_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython: int, frozenset, and type all define nb_and. + # https://github.com/python/cpython/blob/3.13/Objects/longobject.c#L5574 (long_and) + # https://github.com/python/cpython/blob/3.13/Objects/setobject.c#L1506-L1518 (set_and) + # bool inherits int's nb_and via slot inheritance. + from .object_protocol import type_implements_nb_and + + return self._nb_binary_impl( + tx, other, operator.and_, type_implements_nb_and, reverse + ) + + def nb_xor_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython: int and frozenset define nb_xor. + # https://github.com/python/cpython/blob/3.13/Objects/longobject.c#L5587 (long_xor) + # https://github.com/python/cpython/blob/3.13/Objects/setobject.c#L1984-L1990 (set_xor) + # bool inherits int's nb_xor via slot inheritance. + from .object_protocol import type_implements_nb_xor + + return self._nb_binary_impl( + tx, other, operator.xor, type_implements_nb_xor, reverse + ) + + def nb_negative_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + # int: https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L5179-L5189 + # float: https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c#L839-L849 + # complex: https://github.com/python/cpython/blob/v3.13.0/Objects/complexobject.c#L569-L575 + # bool inherits nb_negative from int via slot inheritance. + return ConstantVariable.create(-self.value) + + def nb_positive_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + # int: https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L5619 (long_long) + # float: https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c#L1114 (float_float) + # complex: https://github.com/python/cpython/blob/v3.13.0/Objects/complexobject.c#L578 (complex_pos) + # bool inherits nb_positive from int via slot inheritance. + return ConstantVariable.create(+self.value) + + def nb_add_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython: int, float, and complex define nb_add; bool inherits int's. + # https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L3800 (long_add) + # https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c#L559 (float_add) + # https://github.com/python/cpython/blob/v3.13.0/Objects/complexobject.c#L720 (COMPLEX_BINOP(add, sum)) + from .object_protocol import type_implements_nb_add + + return self._nb_binary_impl( + tx, other, operator.add, type_implements_nb_add, reverse + ) + + def nb_power_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + z: VariableTracker | None, + reverse: bool = False, + ) -> VariableTracker: + # CPython: int, float, and complex all define nb_power (bool inherits int's). + # https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c (long_pow) + # https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c (float_pow) + # https://github.com/python/cpython/blob/v3.13.0/Objects/complexobject.c (complex_pow) + + if z is not None: + z = z.as_python_constant() + + if not other.is_python_constant(): + return ConstantVariable.create(NotImplemented) + + self_, other_ = (other, self) if reverse else (self, other) + v, w = ( + self_.as_python_constant(), + other_.as_python_constant(), + ) + + try: + return VariableTracker.build(tx, pow(v, w, z)) + except TypeError: + return ConstantVariable.create(NotImplemented) + except (ValueError, ZeroDivisionError, OverflowError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + + def nb_power_z_impl( + self, + tx: InstructionTranslatorBase, + v: VariableTracker, + w: VariableTracker, + ) -> VariableTracker: + if not isinstance(self.value, int): + return ConstantVariable.create(NotImplemented) + if not v.is_python_constant() or not w.is_python_constant(): + return ConstantVariable.create(NotImplemented) + v_val, w_val = v.as_python_constant(), w.as_python_constant() + if not isinstance(v_val, int) or not isinstance(w_val, int): + return ConstantVariable.create(NotImplemented) + try: + return VariableTracker.build(tx, pow(v_val, w_val, self.value)) + except (TypeError, ValueError, ZeroDivisionError, OverflowError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + + def nb_absolute_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + # int: https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L5184-L5190 + # float: https://github.com/python/cpython/blob/v3.13.0/Objects/floatobject.c#L847-L850 + # complex: https://github.com/python/cpython/blob/v3.13.0/Objects/complexobject.c#L588-L600 + # _Py_c_abs can set errno=ERANGE on overflow, which complex_abs + # converts to OverflowError("absolute value too large"). + # bool inherits nb_absolute from int via slot inheritance. + try: + return ConstantVariable.create(abs(self.value)) + except OverflowError as e: + raise_observed_exception(OverflowError, tx, args=list(e.args)) + + def nb_invert_impl( + self, + tx: InstructionTranslatorBase, + ) -> VariableTracker: + # int: https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L5163-L5177 + # long_invert implements ~x as -(x+1). + # bool inherits nb_invert from int via slot inheritance. + return ConstantVariable.create(~self.value) + + +CONSTANT_VARIABLE_NONE = ConstantVariable(None) +CONSTANT_VARIABLE_TRUE = ConstantVariable(True) +CONSTANT_VARIABLE_FALSE = ConstantVariable(False) + + +class FakeValueKind(enum.Enum): + ID = "id" + HASH = "hash" + + +class FakeIdVariable(VariableTracker): + """A compile-time-only id or hash value that can be used as a dict key but + cannot be reconstructed across graph breaks. + + When dynamo evaluates ``id(x)`` or ``hash(x)`` on a variable tracker that + has no corresponding runtime object, we mint a fake integer. The ``kind`` + field tracks which builtin produced the value so that same-kind comparisons + (e.g. ``id(a) != id(b)``) can be resolved at compile time while cross-kind + comparisons graph-break. + """ + + # PyLong_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L6585 + _cpython_type = int + + _nonvar_fields = { + "kind", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, value: int, *, kind: FakeValueKind = FakeValueKind.ID, **kwargs: Any + ) -> None: + super().__init__(**kwargs) + self.value = value + self.kind = kind + + def as_python_constant(self) -> int: + return self.value + + def is_python_constant(self) -> bool: + return False + + def python_type(self) -> type: + return int + + def hash_impl(self, tx: InstructionTranslatorBase) -> tuple[int, bool]: + return hash(self.value), True + + def tp_repr_impl(self, tx: InstructionTranslatorBase) -> VariableTracker: + # Mirrors int.__repr__: the value is an int, so str()/repr() yield its + # decimal string. The distinct-but-compile-time-only identity carried by + # the fake id is preserved in the resulting string, matching how + # FakeIdVariable already resolves same-kind id()/hash() comparisons. + return ConstantVariable.create(repr(self.value)) + + def tp_richcompare_impl( + self, tx: InstructionTranslatorBase, other: VariableTracker, op: str + ) -> VariableTracker: + if ( + isinstance(other, FakeIdVariable) + and self.kind == other.kind + and op in ("__eq__", "__ne__") + ): + result = ( + (self.value == other.value) + if op == "__eq__" + else (self.value != other.value) + ) + return ConstantVariable.create(result) + unimplemented( + gb_type="Comparison on compile-time-only id or hash value", + context=f"FakeIdVariable({self.value}) {op} {type(other).__name__}", + explanation="Cannot compare a compile-time-only id() or hash() " + "value. The comparison will run eagerly.", + hints=[ + "Avoid comparing id() or hash() of objects created inside " + "the compiled region against other values.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + # Arithmetic on a fake id/hash (e.g. ``id(self) & 0x7fffffff`` inside a + # custom __hash__) stays compile-time-only: CPython computes int op int, + # but the operand is a fake address so the result must not be baked into + # the graph. We mirror int's nb_* slots and return another fake int. + def _operand_int(self, other: VariableTracker) -> int | None: + if isinstance(other, FakeIdVariable): + return other.value + if other.is_python_constant(): + val = other.as_python_constant() + if isinstance(val, int): + return val + return None + + def _nb_binary_impl( + self, + tx: InstructionTranslatorBase, + other: VariableTracker, + op: Any, + reverse: bool, + ) -> VariableTracker: + other_val = self._operand_int(other) + if other_val is None: + return ConstantVariable.create(NotImplemented) + lhs, rhs = (other_val, self.value) if reverse else (self.value, other_val) + try: + result = op(lhs, rhs) + except (TypeError, ValueError, OverflowError, ZeroDivisionError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + return FakeIdVariable(result) + + def nb_add_impl(self, tx, other, reverse=False): # type: ignore[no-untyped-def] + return self._nb_binary_impl(tx, other, operator.add, reverse) + + def nb_subtract_impl(self, tx, other, reverse=False): # type: ignore[no-untyped-def] + return self._nb_binary_impl(tx, other, operator.sub, reverse) + + def nb_multiply_impl(self, tx, other, reverse=False): # type: ignore[no-untyped-def] + return self._nb_binary_impl(tx, other, operator.mul, reverse) + + def nb_floor_divide_impl(self, tx, other, reverse=False): # type: ignore[no-untyped-def] + return self._nb_binary_impl(tx, other, operator.floordiv, reverse) + + def nb_remainder_impl(self, tx, other, reverse=False): # type: ignore[no-untyped-def] + return self._nb_binary_impl(tx, other, operator.mod, reverse) + + def nb_and_impl(self, tx, other, reverse=False): # type: ignore[no-untyped-def] + return self._nb_binary_impl(tx, other, operator.and_, reverse) + + def nb_or_impl(self, tx, other, reverse=False): # type: ignore[no-untyped-def] + return self._nb_binary_impl(tx, other, operator.or_, reverse) + + def nb_xor_impl(self, tx, other, reverse=False): # type: ignore[no-untyped-def] + return self._nb_binary_impl(tx, other, operator.xor, reverse) + + def nb_lshift_impl(self, tx, other, reverse=False): # type: ignore[no-untyped-def] + return self._nb_binary_impl(tx, other, operator.lshift, reverse) + + def nb_rshift_impl(self, tx, other, reverse=False): # type: ignore[no-untyped-def] + return self._nb_binary_impl(tx, other, operator.rshift, reverse) + + def nb_negative_impl(self, tx): # type: ignore[no-untyped-def] + return FakeIdVariable(-self.value) + + def nb_positive_impl(self, tx): # type: ignore[no-untyped-def] + return FakeIdVariable(+self.value) + + def nb_absolute_impl(self, tx): # type: ignore[no-untyped-def] + return FakeIdVariable(abs(self.value)) + + def nb_invert_impl(self, tx): # type: ignore[no-untyped-def] + return FakeIdVariable(~self.value) + + def nb_int_impl(self, tx): # type: ignore[no-untyped-def] + return FakeIdVariable(int(self.value), kind=self.kind) + + def nb_index_impl(self, tx): # type: ignore[no-untyped-def] + return FakeIdVariable(self.value, kind=self.kind) + + def reconstruct(self, codegen: Any) -> None: + unimplemented( + gb_type="Reconstruction of FakeIdVariable", + context=str(self.value), + explanation=( + "A fake id produced by id() on a compile-time container " + "cannot be reconstructed across a graph break." + ), + hints=[ + "Avoid using id() on containers in code that may graph-break.", + ], + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/ctx_manager.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/ctx_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..4364c03e1d08306ea367150e96682bceb604115a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/ctx_manager.py @@ -0,0 +1,1880 @@ +""" +This file contains a collection of context manager classes used by Dynamo for tracking +and managing various PyTorch runtime states during graph compilation. These context +managers handle different aspects of PyTorch's execution environment, including: + +- Autograd states (grad mode, inference mode) +- CUDA streams and events +- Profiling contexts +- Deterministic algorithms +- Forward/backward AD modes +- SDPA (Scaled Dot Product Attention) kernels +- FSDP (Fully Sharded Data Parallel) states +- AMP (Automatic Mixed Precision) autocast states + +The context managers ensure proper state transitions during graph compilation by +tracking enter/exit points and managing cleanup operations. They help maintain +consistency between eager execution and compiled graph behavior by capturing and +restoring state changes. +""" + +import contextlib +import inspect +import logging +import types +import warnings +from collections.abc import Callable, Sequence, Sized +from contextlib import AbstractContextManager, ExitStack +from typing import Any, TYPE_CHECKING + +import torch._C +from torch._dynamo import config +from torch._guards import Guard +from torch._logging import warning_once + +from .. import graph_break_hints, variables +from ..bytecode_transformation import create_call_function +from ..exc import unimplemented +from ..guards import GuardBuilder, install_guard +from ..source import AttrSource, GlobalStateSource +from ..utils import _get_error_on_graph_break, _set_error_on_graph_break +from .base import VariableTracker +from .functions import ( + NestedUserFunctionVariable, + SkipFunctionVariable, + UserFunctionVariable, + UserMethodVariable, + WrappedNestedUserFunctionVariable, + WrappedSkipFunctionVariable, + WrappedUserFunctionVariable, + WrappedUserMethodVariable, +) +from .user_defined import UserDefinedObjectVariable + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + +log = logging.getLogger(__name__) + + +class ContextWrappingVariable(VariableTracker): + _nonvar_fields = { + "cm_obj", + "target_values", + "initial_values", + "state", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, target_values: Any, initial_values: Any | None = None, **kwargs: Any + ) -> None: + super().__init__(**kwargs) + self.target_values = target_values + self.initial_values = initial_values + # target_values must be None or a Sequence for reconstruct / _call_func + # etc. to work properly. + if not (target_values is None or isinstance(target_values, Sequence)): + raise TypeError( + "ContextWrappingVariable.target_values must be None or a " + f"Sequence, got {type(target_values).__name__}" + ) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + if hasattr(self, "_call_func"): + self._call_func(tx, self.target_values) + self.set_cleanup_hook(tx) + return variables.ConstantVariable.create(None) + + def set_cleanup_hook( + self, tx: "InstructionTranslatorBase", fn: Callable[..., Any] | None = None + ) -> None: + if fn is None: + + def fn() -> None: + if hasattr(self, "_call_func"): + self._call_func(tx, self.initial_values) + + self.cleanup_fn: Callable[..., Any] | None = fn + tx.output.add_cleanup_hook(self.cleanup) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup_assert() + return variables.ConstantVariable.create(None) + + def reconstruct_type(self, codegen: "PyCodegen") -> None: + codegen( + AttrSource(codegen.tx.import_source(self.module_name()), self.fn_name()) + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: self.reconstruct_type(codegen)) + target_values = self.target_values + if not target_values: + target_values = () + codegen.extend_output([codegen.create_load_const(val) for val in target_values]) + codegen.extend_output(create_call_function(len(target_values), False)) + + def module_name(self) -> str: + raise NotImplementedError("module_name called on base") + + def fn_name(self) -> str: + raise NotImplementedError("fn_name called on base") + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if len(args) != 1: + raise AssertionError(f"expected exactly 1 arg, got {len(args)}") + if not isinstance( + args[0], + ( + NestedUserFunctionVariable, + SkipFunctionVariable, + UserMethodVariable, + UserFunctionVariable, + ), + ): + raise AssertionError(f"expected a function variable, got {type(args[0])}") + + if isinstance(args[0], NestedUserFunctionVariable): + return WrappedNestedUserFunctionVariable(args[0], self) + elif isinstance(args[0], SkipFunctionVariable): + return WrappedSkipFunctionVariable(args[0], self) + elif isinstance(args[0], UserMethodVariable): + return WrappedUserMethodVariable(args[0], self) + elif isinstance(args[0], UserFunctionVariable): + return WrappedUserFunctionVariable(args[0], self) + else: + raise AssertionError("Unexpected arg type") + + def supports_graph_breaks(self) -> bool: + return True + + def exit_on_graph_break(self) -> bool: + return True + + def cleanup(self) -> None: + if self.cleanup_fn is not None: + self.cleanup_fn() + self.cleanup_fn = None + + def cleanup_assert(self) -> None: + if not self.cleanup_fn: + raise AssertionError("multiple exits?") + self.cleanup() + + +class GenericContextWrappingVariable(UserDefinedObjectVariable): + # Some methods in ContextWrappingVariable assumes the arguments are + # python constants. Which might not always be the case here. + def __init__(self, cm_obj: AbstractContextManager[Any], **kwargs: Any) -> None: + if cm_obj is None: + raise AssertionError("cm_obj must not be None") + super().__init__( + value=cm_obj, + value_type=cm_obj.__class__, + **kwargs, + ) + self.cm_obj = cm_obj + + def module_name(self) -> str: + return self.cm_obj.__module__ + + def fn_name(self) -> str: + return type(self.cm_obj).__name__ + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + source = None if self.source is None else AttrSource(self.source, "__enter__") + return variables.UserMethodVariable( + self.cm_obj.__enter__.__func__, # type: ignore[attr-defined] + self, + source=source, + ).call_function(tx, [], {}) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + source = None if self.source is None else AttrSource(self.source, "__exit__") + x = variables.UserMethodVariable( + self.cm_obj.__exit__.__func__, # type: ignore[attr-defined] + self, + source=source, + ).call_function(tx, list(args), {}) + tx.active_generic_context_managers.pop() + return x + + def supports_graph_breaks(self) -> bool: + return False + + def exit_on_graph_break(self) -> bool: + return True + + +class RecordFunctionVariable(GenericContextWrappingVariable): + def __init__(self, cm_obj: torch.profiler.record_function, **kwargs: Any) -> None: + super().__init__(cm_obj, **kwargs) + args = [variables.ConstantVariable.create(cm_obj.name)] + record_kwargs = {} + if cm_obj.args: + record_kwargs["args"] = variables.ConstantVariable.create(cm_obj.args) + self.record_fn = variables.torch.ProfilerRecordFunctionContextVariable.create( + func=type(self.cm_obj), record_args=args, record_kwargs=record_kwargs + ) + + def enter(self, tx): + tx.active_generic_context_managers.append(self) + return self.record_fn.enter(tx) + + def exit(self, tx, *args): + tx.active_generic_context_managers.pop() + return self.record_fn.exit(tx, *args) + + +class RepararametrizeModuleContextVariable(GenericContextWrappingVariable): + def __init__(self, ctx_manager_vt: ContextWrappingVariable, mod: Any) -> None: + self.cm_vt = ctx_manager_vt + self.mod = mod + # We don't call super().__init__() because we're delegating most methods to cm_vt + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # Custom enter implementation with side effects. Additionally, do not + # worry about side effects for the hop, as they cancel each other out. + with torch._dynamo.variables.higher_order_ops.dynamo_allow_side_effects_in_hop( + tx + ): + self.old_parameters_var = self.mod.tp_getattro_impl( + tx, "_parameters" + ).realize() + self.old_buffer_var = self.mod.tp_getattro_impl(tx, "_buffers").realize() + tx.output.side_effects.ignore_mutations_on(self.old_parameters_var) + tx.output.side_effects.ignore_mutations_on(self.old_buffer_var) + return self.cm_vt.enter(tx) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + # Custom enter implementation with side effects. Additionally, do not + # worry about side effects for the hop, as they cancel each other out. + with torch._dynamo.variables.higher_order_ops.dynamo_allow_side_effects_in_hop( + tx + ): + x = self.cm_vt.exit(tx, *args) + tx.output.side_effects.stop_ignoring_mutations_on(self.old_buffer_var) + tx.output.side_effects.stop_ignoring_mutations_on(self.old_parameters_var) + return x + + # Forward all other method calls to self.cm_vt + def __getattr__(self, name: str) -> Any: + # This will be called for any attribute not explicitly defined in this class + return getattr(self.cm_vt, name) + + +class GradInplaceRequiresGradCtxManagerVariable(ContextWrappingVariable): + """represents torch grad requires grad""" + + @staticmethod + def create( + tx: "InstructionTranslatorBase", target_values: Any, **kwargs: Any + ) -> "GradInplaceRequiresGradCtxManagerVariable": + return GradInplaceRequiresGradCtxManagerVariable( + target_values=target_values, + initial_values=None, + **kwargs, + ) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + [enabled] = self.target_values + self.prev_state = torch._C._functorch.get_inplace_requires_grad_allowed() + torch._C._functorch.set_inplace_requires_grad_allowed(enabled) + self.set_cleanup_hook( + tx, + lambda: torch._C._functorch.set_inplace_requires_grad_allowed( + self.prev_state + ), + ) + self.proxy = tx.output.create_node( + "call_function", + torch._C._functorch.set_inplace_requires_grad_allowed, + (enabled,), + {}, + ) + return variables.ConstantVariable.create(None) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup() + tx.output.create_node( + "call_function", + torch._C._functorch.set_inplace_requires_grad_allowed, + (self.prev_state,), + {}, + ) + return variables.ConstantVariable.create(None) + + +class TemporarilyPopInterpreterStackCtxManagerVariable(ContextWrappingVariable): + """represents torch._functorch.pyfunction.temporarily_pop_interpreter_stack()""" + + @staticmethod + def create( + tx: "InstructionTranslatorBase", target_values: Any, **kwargs: Any + ) -> "TemporarilyPopInterpreterStackCtxManagerVariable": + return TemporarilyPopInterpreterStackCtxManagerVariable( + target_values=target_values, + initial_values=None, + **kwargs, + ) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + self.saved = torch._C._functorch.pop_dynamic_layer_stack() + self.set_cleanup_hook( + tx, + lambda: torch._C._functorch.push_dynamic_layer_stack(self.saved), + ) + self.proxy = tx.output.create_node( + "call_function", + torch._C._functorch.pop_dynamic_layer_stack, + (), + {}, + ) + return variables.ConstantVariable.create(None) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup() + tx.output.create_node( + "call_function", + torch._C._functorch.push_dynamic_layer_stack, + (self.proxy,), + {}, + ) + return variables.ConstantVariable.create(None) + + +class JvpIncrementNestingCtxManagerVariable(ContextWrappingVariable): + """represents torch.func.jvp increment/decrement nesting""" + + # A guard is needed as the grad level is baked into the torch FX graph + # This is fine if jvp is only called from within the function + # being compiled. But the FX graph may be invalid in the case of a jvp + # call from eager that calls the compiled function, as the jvp levels + # may be different. + _guards_singleton = Guard(GlobalStateSource(), GuardBuilder.FUNCTORCH_STACK_MATCH) # type: ignore[arg-type] + + @staticmethod + def create( + tx: "InstructionTranslatorBase", **kwargs: Any + ) -> "JvpIncrementNestingCtxManagerVariable": + var = JvpIncrementNestingCtxManagerVariable( + target_values=None, + initial_values=None, + **kwargs, + ) + return var + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + install_guard(self._guards_singleton) + jvp_level = torch._functorch.eager_transforms.enter_jvp_nesting() + self.set_cleanup_hook( + tx, lambda: torch._functorch.eager_transforms.exit_jvp_nesting() + ) + self.proxy = tx.output.create_node( + "call_function", + torch._functorch.predispatch._jvp_increment_nesting, + (), + {}, + ) + return variables.VariableTracker.build(tx, jvp_level) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup() + tx.output.create_node( + "call_function", torch._functorch.predispatch._jvp_decrement_nesting, (), {} + ) + return variables.ConstantVariable.create(None) + + +class SetFwdGradEnabledContextManager(ContextWrappingVariable): + """represents torch.autograd.forward_ad._set_fwd_grad_enabled() to enable/disable fwd grad""" + + @staticmethod + def create( + tx: "InstructionTranslatorBase", target_values: Any, **kwargs: Any + ) -> "SetFwdGradEnabledContextManager": + return SetFwdGradEnabledContextManager( + target_values=target_values, + initial_values=None, + **kwargs, + ) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + [mode] = self.target_values + self.prev_state = torch._C._is_fwd_grad_enabled() + torch._C._set_fwd_grad_enabled(mode) + self.set_cleanup_hook( + tx, + lambda: torch._C._set_fwd_grad_enabled(self.prev_state), + ) + self.proxy = tx.output.create_node( + "call_function", + torch._C._set_fwd_grad_enabled, + (mode,), + {}, + ) + return variables.ConstantVariable.create(None) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup() + tx.output.create_node( + "call_function", + torch._C._set_fwd_grad_enabled, + (self.prev_state,), + {}, + ) + return variables.ConstantVariable.create(None) + + def python_type(self) -> type: + return torch.autograd.forward_ad._set_fwd_grad_enabled + + +class DualLevelContextManager(ContextWrappingVariable): + """Represents torch.autograd.forward_ad.dual_level ctx manager""" + + _guards_singleton = Guard(GlobalStateSource(), GuardBuilder.DUAL_LEVEL) # type: ignore[arg-type] + + @staticmethod + def create( + tx: "InstructionTranslatorBase", **kwargs: Any + ) -> "DualLevelContextManager": + return DualLevelContextManager( + target_values=None, + initial_values=None, + **kwargs, + ) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + install_guard(self._guards_singleton) + self.new_level = torch.autograd.forward_ad.enter_dual_level() + self.set_cleanup_hook( + tx, lambda: torch.autograd.forward_ad.exit_dual_level(level=self.new_level) + ) + self.proxy = tx.output.create_node( + "call_function", + torch._functorch.predispatch._enter_dual_level, + (), + {}, + ) + return variables.VariableTracker.build(tx, self.new_level) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup() + tx.output.create_node( + "call_function", + torch._functorch.predispatch._exit_dual_level, + (), + {"level": self.new_level}, + ) + return variables.ConstantVariable.create(None) + + def python_type(self) -> type: + return torch.autograd.forward_ad.dual_level + + +class GradIncrementNestingCtxManagerVariable(ContextWrappingVariable): + """represents torch.func.grad increment/decrement nesting""" + + # A guard is needed as the grad level is baked into the torch FX graph + # This is fine if grad is only called from within the function + # being compiled. But the FX graph may be invalid in the case of a grad + # call from eager that calls the compiled function, as the grad levels + # may be different. + _guards_singleton = Guard(GlobalStateSource(), GuardBuilder.FUNCTORCH_STACK_MATCH) # type: ignore[arg-type] + + @staticmethod + def create( + tx: "InstructionTranslatorBase", **kwargs: Any + ) -> "GradIncrementNestingCtxManagerVariable": + var = GradIncrementNestingCtxManagerVariable( + target_values=None, + initial_values=None, + **kwargs, + ) + return var + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + install_guard(self._guards_singleton) + grad_level = torch._C._functorch._grad_increment_nesting() + self.set_cleanup_hook(tx, lambda: torch._C._functorch._grad_decrement_nesting()) + self.proxy = tx.output.create_node( + "call_function", + torch._C._functorch._grad_increment_nesting, + (), + {}, + ) + return variables.VariableTracker.build(tx, grad_level) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup() + tx.output.create_node( + "call_function", torch._C._functorch._grad_decrement_nesting, (), {} + ) + return variables.ConstantVariable.create(None) + + +class CatchWarningsCtxManagerVariable(ContextWrappingVariable): + """Delay a call to warnings.catch_warnings""" + + @staticmethod + def create( + tx: "InstructionTranslatorBase", catch_warnings_args: dict[str, VariableTracker] + ) -> "CatchWarningsCtxManagerVariable": + return CatchWarningsCtxManagerVariable( + catch_warnings_args=catch_warnings_args, + target_values=None, + initial_values=None, + ) + + def __init__( + self, + catch_warnings_args: dict[str, VariableTracker], + target_values: Any | None = None, + initial_values: Any | None = None, + **kwargs: Any, + ) -> None: + if not isinstance(catch_warnings_args, dict): + raise AssertionError( + f"catch_warnings_args must be a dict, got {catch_warnings_args}" + ) + super().__init__( + target_values=target_values, initial_values=initial_values, **kwargs + ) + self.catch_warnings_args = catch_warnings_args + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + kwargs = { + k: v.as_python_constant() for k, v in self.catch_warnings_args.items() + } + ctx_val = warnings.catch_warnings(**kwargs) + self.set_cleanup_hook(tx, lambda: ctx_val.__exit__(None, None, None)) + return variables.VariableTracker.build(tx, ctx_val.__enter__()) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from("warnings", "catch_warnings") + ) + codegen.foreach(self.catch_warnings_args.values()) + keys = tuple(self.catch_warnings_args.keys()) + codegen.extend_output(codegen.create_call_function_kw(len(keys), keys, False)) + + def python_type(self) -> type: + return warnings.catch_warnings + + +class VmapIncrementNestingCtxManagerVariable(ContextWrappingVariable): + """represents torch VMap increment/decrement nesting""" + + # A guard is needed as the vmap level is baked into the torch FX graph + # generated. This is fine if vmap is only called from within the function + # being compiled. But the FX graph may be invalid in the case of a vmap + # call from eager that calls the compiled function, as the vmap levels + # may be different. + _guards_singleton = Guard(GlobalStateSource(), GuardBuilder.FUNCTORCH_STACK_MATCH) # type: ignore[arg-type] + + @staticmethod + def create( + tx: "InstructionTranslatorBase", + target_values: list[VariableTracker], + **kwargs: Any, + ) -> "VmapIncrementNestingCtxManagerVariable": + var = VmapIncrementNestingCtxManagerVariable( + target_values=target_values, + initial_values=None, + **kwargs, + ) + return var + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + install_guard(self._guards_singleton) + batch_size, randomness = self.target_values + if isinstance(batch_size, variables.SymNodeVariable): + batch_size_value = batch_size.sym_num + else: + batch_size_value = batch_size.as_python_constant() + randomness = randomness.as_python_constant() + vmap_level = torch._C._functorch._vmap_increment_nesting( + batch_size_value, randomness + ) + self.set_cleanup_hook(tx, lambda: torch._C._functorch._vmap_decrement_nesting()) + self.proxy = tx.output.create_proxy( + "call_function", + torch._functorch.predispatch._vmap_increment_nesting, + (batch_size.as_proxy(), randomness), + {}, + ) + return variables.VariableTracker.build(tx, vmap_level) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup() + tx.output.create_node( + "call_function", + torch._functorch.predispatch._vmap_decrement_nesting, + (), + {}, + ) + return variables.ConstantVariable.create(None) + + +class GradModeVariable(ContextWrappingVariable): + """represents torch.{no_grad,enable_grad,set_grad_mode}()""" + + _guards_singleton = Guard(GlobalStateSource(), GuardBuilder.GRAD_MODE) # type: ignore[arg-type] + + @staticmethod + def create( + tx: "InstructionTranslatorBase", + target_value: Any, + initialized: bool = False, + **kwargs: Any, + ) -> "GradModeVariable": + var = GradModeVariable( + target_values=[target_value], + initial_values=[torch.is_grad_enabled()], + **kwargs, + ) + if initialized: + var._call_func(tx, var.target_values) + return var + + def __init__( + self, + target_values: Any, + initial_values: Sequence[bool] | None = None, + initialized: bool = True, + **kwargs: Any, + ) -> None: + super().__init__( + target_values=target_values, initial_values=initial_values, **kwargs + ) + install_guard(self._guards_singleton) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + self._call_func(tx, self.target_values) + return variables.ConstantVariable.create(None) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self._call_func(tx, self.initial_values) + return variables.ConstantVariable.create(None) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + self._call_func(tx, self.initial_values) # undo eager initialization + return super().call_function(tx, args, kwargs) + + def _call_func(self, tx: "InstructionTranslatorBase", values: Any) -> None: + if len(values) != 1: + raise AssertionError(f"expected 1 value, got {len(values)}") + value = values[0] + # Coalesce grad mode mutations + if torch.is_grad_enabled() != value: + tx.output.create_node( + "call_function", torch._C._set_grad_enabled, (value,), {} + ) + torch._C._set_grad_enabled(value) + + def module_name(self) -> str: + return "torch" + + def fn_name(self) -> str: + return "set_grad_enabled" + + def python_type(self) -> type: + return torch.set_grad_enabled + + +class InferenceModeVariable(ContextWrappingVariable): + @staticmethod + def create( + tx: "InstructionTranslatorBase", target_value: Any, **kwargs: Any + ) -> "InferenceModeVariable": + var = InferenceModeVariable( + [target_value], initial_values=torch.is_inference_mode_enabled(), **kwargs + ) + return var + + def __init__( + self, + target_values: Any, + initial_values: bool | None = None, + **kwargs: Any, + ) -> None: + if initial_values is None: + # This must be called here since function defaults are evaluated at import time + initial_values = torch.is_inference_mode_enabled() + super().__init__( + target_values=target_values, initial_values=initial_values, **kwargs + ) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup_assert() + tx.output.create_node( + "call_function", + torch.autograd.grad_mode._exit_inference_mode, + (self.proxy,), + {}, + ) + return variables.ConstantVariable.create(None) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + disabled_inference_mode_forcibly = False + if ( + torch._dynamo.config.fake_tensor_disable_inference_mode + and self.target_values[0] + ): + # Do not set the inference mode because we keep it off during + # compilation. Set the grad_enabled to False to reflect the relevant + # part of inference_mode to torch.compile. + disabled_inference_mode_forcibly = True + prior = torch.is_grad_enabled() + torch._C._set_grad_enabled(False) + else: + ctx = torch.autograd.grad_mode._enter_inference_mode(*self.target_values) + + def cleanup_hook() -> None: + if disabled_inference_mode_forcibly: + torch._C._set_grad_enabled(prior) + else: + torch.autograd.grad_mode._exit_inference_mode(ctx) + + self.set_cleanup_hook(tx, cleanup_hook) + self.proxy = tx.output.create_node( + "call_function", + torch.autograd.grad_mode._enter_inference_mode, + (*self.target_values,), + {}, + ) + return variables.ConstantVariable.create(None) + + def module_name(self) -> str: + return "torch" + + def fn_name(self) -> str: + return "inference_mode" + + def python_type(self) -> type: + return torch.inference_mode + + +class GenericDeviceVariable(ContextWrappingVariable): + """Abstract base for device context managers that swap the active device index.""" + + _exchange_fn: Any + _maybe_exchange_fn: Any + _get_device_index_fn: Any + + @classmethod + def create( + cls, tx: "InstructionTranslatorBase", device: Any, **kwargs: Any + ) -> "GenericDeviceVariable": + return cls( + target_values=[cls._get_device_index_fn(device, optional=True)], + initial_values=None, + **kwargs, + ) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup_assert() + tx.output.create_node( + "call_function", + self._maybe_exchange_fn, + (self.proxy,), + {}, + ) + return variables.ConstantVariable.create(False) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + prev_idx = self._exchange_fn(*self.target_values) + self.set_cleanup_hook(tx, lambda: self._maybe_exchange_fn(prev_idx)) + self.proxy = tx.output.create_node( + "call_function", + self._exchange_fn, + (*self.target_values,), + {}, + ) + return variables.ConstantVariable.create(None) + + def module_name(self) -> str: + raise NotImplementedError + + def fn_name(self) -> str: + return "device" + + def python_type(self) -> type: + raise NotImplementedError + + +class CUDADeviceVariable(GenericDeviceVariable): + """represents torch.cuda.device""" + + _exchange_fn = staticmethod(torch.cuda._exchange_device) + _maybe_exchange_fn = staticmethod(torch.cuda._maybe_exchange_device) + _get_device_index_fn = staticmethod(torch.cuda._get_device_index) + + def module_name(self) -> str: + return "torch.cuda" + + def python_type(self) -> type: + return torch.cuda.device + + +class XPUDeviceVariable(GenericDeviceVariable): + """represents torch.xpu.device""" + + _exchange_fn = staticmethod(torch.xpu._exchange_device) + _maybe_exchange_fn = staticmethod(torch.xpu._maybe_exchange_device) + _get_device_index_fn = staticmethod(torch.xpu._get_device_index) + + def module_name(self) -> str: + return "torch.xpu" + + def python_type(self) -> type: + return torch.xpu.device + + +class AcceleratorDeviceIndexVariable(GenericDeviceVariable): + """represents torch.accelerator.device_index""" + + _exchange_fn = staticmethod(torch._C._accelerator_exchangeDevice) + _maybe_exchange_fn = staticmethod(torch._C._accelerator_maybeExchangeDevice) + _get_device_index_fn = staticmethod(lambda device, **kwargs: device) + + def module_name(self) -> str: + return "torch.accelerator" + + def fn_name(self) -> str: + return "device_index" + + def python_type(self) -> type: + return torch.accelerator.device_index + + +_device_context_manager_map: dict[type, type[GenericDeviceVariable]] = { + torch.cuda.device: CUDADeviceVariable, + torch.xpu.device: XPUDeviceVariable, + torch.accelerator.device_index: AcceleratorDeviceIndexVariable, +} + + +def register_device_context_manager( + device_context: type, variable_cls: type[GenericDeviceVariable] +) -> None: + """Register a Dynamo variable class for a device context manager type. + + Raises ``ValueError`` if ``device_context`` is already registered. + """ + if device_context in _device_context_manager_map: + raise ValueError( + f"Device context {device_context} already has a registered context manager" + ) + _device_context_manager_map[device_context] = variable_cls + + +def get_device_context_manager( + device_context: type, +) -> type[GenericDeviceVariable] | None: + """Return the Dynamo variable class for ``device_context``, or ``None`` if not registered.""" + return _device_context_manager_map.get(device_context) + + +class TorchFunctionDisableVariable(ContextWrappingVariable): + """represents whether torch function overrides are enabled or not""" + + _guards_singleton = Guard(GlobalStateSource(), GuardBuilder.TORCH_FUNCTION_STATE) # type: ignore[arg-type] + + @staticmethod + def create( + tx: "InstructionTranslatorBase", **kwargs: Any + ) -> "TorchFunctionDisableVariable": + var = TorchFunctionDisableVariable( + tx, + target_values=[], + initial_values=[], + **kwargs, + ) + return var + + def __init__( + self, + tx: "InstructionTranslatorBase", + target_values: Sized, + initial_values: Sized | None = None, + only_subclass: bool = True, + **kwargs: Any, + ) -> None: + if len(target_values) != 0: + raise AssertionError(f"expected 0 target_values, got {len(target_values)}") + if initial_values is None: + raise AssertionError("initial_values must not be None") + if len(initial_values) != 0: + raise AssertionError( + f"expected 0 initial_values, got {len(initial_values)}" + ) + self.only_subclass = only_subclass + self.initial_torch_function_subclass_enabled = ( + tx.symbolic_torch_function_state.torch_function_subclass_enabled + ) + self.initial_torch_function_mode_enabled = ( + tx.symbolic_torch_function_state.torch_function_mode_enabled + ) + + super().__init__( + target_values=target_values, initial_values=initial_values, **kwargs + ) + install_guard(self._guards_singleton) + + def set_cleanup_hook( + self, + tx: "InstructionTranslatorBase", + fn: Callable[..., Any] | None = None, + ) -> None: + if fn is None: + + def fn() -> None: + tx.symbolic_torch_function_state.torch_function_subclass_enabled = ( + self.initial_torch_function_subclass_enabled + ) + if not self.only_subclass: + tx.symbolic_torch_function_state.torch_function_mode_enabled = ( + self.initial_torch_function_mode_enabled + ) + + self.cleanup_fn = fn + tx.output.add_cleanup_hook(self.cleanup) + + def _call_func(self, tx: "InstructionTranslatorBase", values: Sized) -> None: + if len(values) != 0: + raise AssertionError(f"expected 0 values, got {len(values)}") + tx.symbolic_torch_function_state.torch_function_subclass_enabled = False + if not self.only_subclass: + tx.symbolic_torch_function_state.torch_function_mode_enabled = False + + def module_name(self) -> str: + return "torch._C" + + def fn_name(self) -> str: + if self.only_subclass: + return "DisableTorchFunctionSubclass" + return "DisableTorchFunction" + + def python_type(self) -> type: + if self.only_subclass: + return torch._C.DisableTorchFunctionSubclass # pyrefly: ignore[bad-return] + return torch._C.DisableTorchFunction # pyrefly: ignore[bad-return] + + +class DisabledSavedTensorsHooksVariable(ContextWrappingVariable): + """represents torch.autograd.graph.disable_saved_tensors_hook.""" + + @staticmethod + def create( + tx: "InstructionTranslatorBase", target_value: str | None, **kwargs: Any + ) -> "DisabledSavedTensorsHooksVariable": + var = DisabledSavedTensorsHooksVariable( + target_values=[target_value], + initial_values=[ + torch._C._autograd._saved_tensors_hooks_get_disabled_error_message() + ], + **kwargs, + ) + var._call_func(tx, [target_value]) + var.set_cleanup_hook(tx) + return var + + def __init__( + self, + target_values: Sequence[str | None], + initial_values: Sequence[str | None] | None = None, + **kwargs: Any, + ) -> None: + super().__init__( + target_values=target_values, initial_values=initial_values, **kwargs + ) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return variables.ConstantVariable.create(None) + + def _call_func( + self, tx: "InstructionTranslatorBase", values: Sequence[str | None] + ) -> None: + if len(values) != 1: + raise AssertionError(f"expected 1 value, got {len(values)}") + value = values[0] + if value is not None: + # Disable `saved_tensors_hooks` with message (`value`) + # OR + # we are exiting this context and restoring the previous message. + tx.output.create_node( + "call_function", + torch._C._autograd._saved_tensors_hooks_disable, + (value,), + {}, + ) + torch._C._autograd._saved_tensors_hooks_disable(value) + else: + # We are exiting this context and if prev_message was None, we re-enable `saved_tensors_hooks`. + tx.output.create_node( + "call_function", torch._C._autograd._saved_tensors_hooks_enable, (), {} + ) + torch._C._autograd._saved_tensors_hooks_enable() + + def module_name(self) -> str: + return "torch.autograd.graph" + + def fn_name(self) -> str: + return "disable_saved_tensors_hooks" + + def python_type(self) -> type: + return contextlib._GeneratorContextManager + + +class AutocastModeVariable(ContextWrappingVariable): + @staticmethod + def create( + func: torch.amp.autocast_mode.autocast, + args: Sequence[Any], + kwargs: dict[str, Any], + ) -> "AutocastModeVariable": + if func not in [ + torch.amp.autocast_mode.autocast, + torch.cuda.amp.autocast, + torch.cpu.amp.autocast, + ]: + raise AssertionError(f"unexpected autocast function: {func}") + # device_type : str, + # dtype : Optional[_dtype] = None, + # enabled : bool = True, + # cache_enabled : Optional[bool] = None):cache_enabled + bound_args = inspect.signature(func).bind(*args, **kwargs) + bound_args.apply_defaults() + target_values = [] + kwargs.clear() + + for key in ["device_type", "dtype", "enabled", "cache_enabled"]: + if key == "device_type" and func in [ + torch.cuda.amp.autocast, + torch.cpu.amp.autocast, + ]: + # pyrefly: ignore [unnecessary-comparison] + arg = "cuda" if func is torch.cuda.amp.autocast else "cpu" + else: + arg = bound_args.arguments[key] + if isinstance(arg, VariableTracker): + target_values.append(arg.as_python_constant()) + else: + target_values.append(arg) + + var = AutocastModeVariable(target_values, initial_values=None, **kwargs) + return var + + def __init__( + self, + target_values: Sequence[Any], + initial_values: Any | None = None, + **kwargs: Any, + ) -> None: + super().__init__( + target_values=target_values, initial_values=initial_values, **kwargs + ) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup_assert() + tx.output.create_node( + "call_function", torch.amp._exit_autocast, (self.proxy,), {} + ) + return variables.ConstantVariable.create(None) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + ctx = torch.amp._enter_autocast(*self.target_values) + self.set_cleanup_hook(tx, lambda: torch.amp._exit_autocast(ctx)) + self.proxy = tx.output.create_node( + "call_function", torch.amp._enter_autocast, (*self.target_values,), {} + ) + return variables.ConstantVariable.create(None) + + def module_name(self) -> str: + return "torch.amp.autocast_mode" + + def fn_name(self) -> str: + return "autocast" + + def python_type(self) -> type: + return torch.amp.autocast_mode.autocast + + +class NullContextVariable(ContextWrappingVariable): + """ + This class represents Python contextlib.nullcontext. + """ + + def __init__( + self, enter_result: VariableTracker | None = None, **kwargs: Any + ) -> None: + self.enter_result = enter_result + super().__init__(target_values=(), **kwargs) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + if self.enter_result is None: + return variables.ConstantVariable.create(None) + return self.enter_result + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + return variables.ConstantVariable.create(None) + + def module_name(self) -> str: + return "contextlib" + + def fn_name(self) -> str: + return "nullcontext" + + def python_type(self) -> type: + return contextlib.nullcontext + + +class ProfilerContextVariable(ContextWrappingVariable): + """ + This class represents a set of torch profiler context objects, where Dynamo + ignores all the side-effects in the __init__, __enter__ and __exit__ methods + by treating the object mostly as a `contextlib.nullcontext`, except for edge + cases like the `__enter__` method which returns the object itself rather + than `None`, per implementation of the torch objects. + """ + + def __init__(self, **kwargs: Any) -> None: + super().__init__(target_values=None, **kwargs) + + def python_type(self) -> type: + return torch.profiler.profile + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + return variables.ConstantVariable.create(None) + + def module_name(self) -> str: + return "contextlib" + + def fn_name(self) -> str: + return "nullcontext" + + def reconstruct(self, codegen: "PyCodegen") -> None: + unimplemented( + gb_type="torch.profiler object escaped from compiled region", + context=str(self), + explanation="Dynamo doesn't support compiling a region that returns a torch.profiler context manager.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + +class ProfilerRecordFunctionContextVariable(ContextWrappingVariable): + """ + This class represents torch profiler context objects. + + For record_function: emits torch.ops.profiler._record_function_enter_new + to the graph on enter, and torch.ops.profiler._record_function_exit on exit. + But if emit_profiler_ops=False, behaves like nullcontext. + + For profile: behaves like nullcontext, ignoring all side-effects. + """ + + _nonvar_fields = { + "emit_profiler_ops", + *ContextWrappingVariable._nonvar_fields, + } + + @staticmethod + def create( + func: Any, + record_args: list[VariableTracker], + record_kwargs: "dict[str, VariableTracker]", + **kwargs: Any, + ) -> "ProfilerRecordFunctionContextVariable": + target_values = None + if config.capture_profiler_record_function: + # Extract name and args for record_function + # record_function(name: str, args: Optional[str] = None) + name = ( + record_args[0].as_python_constant() + if record_args + else record_kwargs.get( + "name", variables.ConstantVariable.create("unknown") + ).as_python_constant() + ) + record_args_const = None + if len(record_args) > 1: + record_args_const = record_args[1].as_python_constant() + elif "args" in record_kwargs: + record_args_const = record_kwargs["args"].as_python_constant() + target_values = [name, record_args_const] + else: + warning_once(log, "Profiler record function %s will be ignored", func) + return ProfilerRecordFunctionContextVariable( + target_values=target_values, + initial_values=None, + **kwargs, + ) + + def __init__( + self, + target_values: Any = None, + initial_values: Any | None = None, + **kwargs: Any, + ) -> None: + super().__init__( + target_values=target_values, initial_values=initial_values, **kwargs + ) + + def python_type(self) -> type: + return torch.autograd.profiler.record_function + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + if config.capture_profiler_record_function: + name, args = self.target_values + # Create the profiler entry node in the graph + self.proxy = tx.output.create_node( + "call_function", + torch.ops.profiler._record_function_enter_new, + (name, args), + {}, + ) + return self + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + if config.capture_profiler_record_function: + # Create the profiler exit node in the graph + tx.output.create_node( + "call_function", + torch.ops.profiler._record_function_exit._RecordFunction, + (self.proxy,), + {}, + ) + return variables.ConstantVariable.create(None) + + def module_name(self) -> str: + return ( + "torch.autograd.profiler" + if config.capture_profiler_record_function + else "contextlib" + ) + + def fn_name(self) -> str: + return ( + "record_function" + if config.capture_profiler_record_function + else "nullcontext" + ) + + def reconstruct_type(self, codegen: "PyCodegen") -> None: + # This will be called if we try to reconstruct the record_function type + # when there's a graph break. The _set_error_on_graph_break(True) in enter() + # will cause the graph break to raise an error before we get here. + if config.capture_profiler_record_function: + unimplemented( + gb_type="record_function escaped from compiled region", + context=str(self), + explanation="Dynamo doesn't support graph break inside record_function region.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + else: + # If capture is disabled, allow reconstruction (behaves like nullcontext) + super().reconstruct_type(codegen) + + +class PreserveVersionContextVariable(ContextWrappingVariable): + """ + Wraps torch.autograd._unsafe_preserve_version_counter + """ + + @staticmethod + def _create_lambda_from_tensors( + tx: "InstructionTranslatorBase", + tensors: VariableTracker, + ) -> "PreserveVersionContextVariable": + if tensors.is_tensor(): + versions = variables.TupleVariable( + [x.tp_getattro_impl(tx, "_version") for x in [tensors]] + ) + tensors_tuple = variables.TupleVariable([tensors]) + else: + if not isinstance(tensors, variables.TupleVariable): + raise AssertionError( + f"tensors must be a TupleVariable, got {type(tensors)}" + ) + versions = variables.TupleVariable( + [x.tp_getattro_impl(tx, "_version") for x in tensors.items] + ) + tensors_tuple = tensors + return PreserveVersionContextVariable(tensors_tuple, versions) + + @staticmethod + def constructor(tx: "InstructionTranslatorBase") -> VariableTracker: + return variables.LambdaVariable( + lambda tensors: PreserveVersionContextVariable._create_lambda_from_tensors( + tx, tensors + ) + ) + + def __init__( + self, + tensors: VariableTracker, + prev_versions: VariableTracker, + **kwargs: Any, + ) -> None: + kwargs.setdefault("target_values", None) + super().__init__(**kwargs) + self.tensors = tensors + self.prev_versions = prev_versions + # The context manager accepts Union[Tensor, Tuple[Tensor]] + if self.tensors.is_tensor(): + self.tensors = variables.TupleVariable([self.tensors]) + if self.prev_versions.is_symnode_like(): + self.prev_versions = variables.TupleVariable([self.prev_versions]) + + def python_type(self) -> type: + return torch.autograd.grad_mode._unsafe_preserve_version_counter + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return variables.ConstantVariable.create(None) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + from ..tensor_version_op import _unsafe_set_version_counter + + return variables.TorchInGraphFunctionVariable( + _unsafe_set_version_counter + ).call_function(tx, [self.tensors, self.prev_versions], {}) + + def reconstruct(self, codegen: "PyCodegen") -> None: + unimplemented( + gb_type="torch.autograd._unsafe_preserve_version_counter escaped from compiled region", + context=str(self), + explanation=( + "Dynamo doesn't support compiling a region that returns " + "a torch.autograd._unsafe_preserve_version_counter context manager." + ), + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + +class FSDPParamGroupUseTrainingStateVariable(ContextWrappingVariable): + _guards_singleton = Guard(GlobalStateSource(), GuardBuilder.FSDP_TRAINING_STATE) # type: ignore[arg-type] + + @staticmethod + def create( + tx: "InstructionTranslatorBase", + param_group_var: Any, + target_value: Any, + **kwargs: Any, + ) -> "FSDPParamGroupUseTrainingStateVariable": + var = FSDPParamGroupUseTrainingStateVariable( + param_group_var=param_group_var, + target_values=[target_value], + initial_values=[param_group_var.value._training_state], + **kwargs, + ) + return var + + def __init__( + self, + param_group_var: Any, + target_values: Sequence[Any], + initial_values: Sequence[Any] | None = None, + **kwargs: Any, + ) -> None: + super().__init__( + target_values=target_values, initial_values=initial_values, **kwargs + ) + self.param_group_var = param_group_var + install_guard(self._guards_singleton) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + self._call_func(tx, self.target_values) + return variables.ConstantVariable.create(None) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self._call_func(tx, self.initial_values) # type: ignore[arg-type] + return variables.ConstantVariable.create(None) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # undo eager initialization + self._call_func(tx, self.initial_values) # type: ignore[arg-type] + return super().call_function(tx, args, kwargs) + + def _call_func( + self, tx: "InstructionTranslatorBase", values: Sequence[Any] + ) -> None: + if len(values) != 1: + raise AssertionError(f"expected 1 value, got {len(values)}") + value = values[0] + if self.param_group_var.value._training_state != value: + self.param_group_var.call_method( + tx, + "__setattr__", + ( + variables.VariableTracker.build(tx, "_training_state"), + variables.VariableTracker.build(tx, value), + ), + {}, + ) + self.param_group_var.value._training_state = value + + def module_name(self) -> str: + return "torch.distributed.fsdp._fully_shard._fsdp_param_group.FSDPParamGroup" + + def fn_name(self) -> str: + return "use_training_state" + + +class SDPAKernelVariable(ContextWrappingVariable): + """represents torch.nn.attention.sdpa_kernel""" + + @staticmethod + def create( + tx: "InstructionTranslatorBase", + backends: Any, + set_priority: bool = False, + **kwargs: Any, + ) -> "SDPAKernelVariable": + if isinstance(backends, torch.nn.attention.SDPBackend): + backends = [backends] + var = SDPAKernelVariable( + target_values=backends, + initial_values=None, + set_priority=set_priority, + **kwargs, + ) + return var + + def __init__( + self, + target_values: list[torch.nn.attention.SDPBackend], + initial_values: Any = None, + set_priority: bool = False, + **kwargs: Any, + ) -> None: + super().__init__( + target_values=target_values, initial_values=initial_values, **kwargs + ) + self.set_priority = set_priority + + @staticmethod + def _backends_to_nodes( + tx: "InstructionTranslatorBase", + backends: list[Any], + ) -> list[Any]: + # convert to/from string in order to bake the backend into FX graph + nodes = [ + tx.output.create_node( + "call_function", + torch.nn.attention._backend_from_string, + (backend.name,), + {}, + ) + for backend in backends + ] + return nodes + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + self.prev_backends = torch.nn.attention._cur_sdpa_kernel_backends( + with_priority=self.set_priority + ) + self.set_cleanup_hook( + tx, + lambda: torch.nn.attention._sdpa_kernel( + self.prev_backends, set_priority=self.set_priority + ), + ) + torch.nn.attention._sdpa_kernel( + self.target_values, set_priority=self.set_priority + ) + arg = self._backends_to_nodes(tx, self.target_values) + tx.output.create_node( + "call_function", + torch.nn.attention._sdpa_kernel, + (arg, bool(self.set_priority)), + {}, + ) + return variables.ConstantVariable.create(None) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + self.cleanup_assert() + arg = self._backends_to_nodes(tx, self.prev_backends) + tx.output.create_node( + "call_function", + torch.nn.attention._sdpa_kernel, + (arg, bool(self.set_priority)), + {}, + ) + return variables.ConstantVariable.create(None) + + def module_name(self) -> str: + return "torch.nn.attention" + + # use a private version of sdpa_kernel that accepts variadic arguments + # since dynamo reconstructs the contents of target_values one-by-one + def fn_name(self) -> str: + return "_sdpa_kernel_variadic" + + def python_type(self) -> type: + return contextlib._GeneratorContextManager + + +class FxTracebackAnnotateVariable(ContextWrappingVariable): + """ + fx.traceback.annotate is a context manager that allows users to annotate the + fx graph nodes with custom metadata. In the context of Dynamo, we don't have + to trace the body of the context manager. Instead we want to directly run + the body of the context manager, so the Dynamo created Fx graphs have the + right custom metadata. This variable tracker just runs __enter__ and + __exit__ method (instead of tracing). + """ + + _nonvar_fields = { + "annotation", + *ContextWrappingVariable._nonvar_fields, + } + + def __init__( + self, annotation: dict[str, Any], initial_values: Any = None, **kwargs: Any + ) -> None: + self.annotation = annotation + super().__init__(target_values=(), initial_values=initial_values, **kwargs) + + def enter( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + # Run the annotation ctx manager in eager. Also ensure that + # preserve_node_meta context manager is setup. This is important to pass + # on the metadata to the create_proxy nodes. + stack = ExitStack() + stack.enter_context(torch.fx.traceback.annotate(self.annotation)) + stack.enter_context(torch.fx.traceback.preserve_node_meta()) + self.set_cleanup_hook(tx, lambda: stack.close()) + return variables.ConstantVariable.create(None) + + def module_name(self) -> str: + return "torch.fx.traceback" + + def fn_name(self) -> str: + return "annotate" + + def python_type(self) -> type: + return contextlib._GeneratorContextManager + + def reconstruct_type(self, codegen: "PyCodegen") -> None: + unimplemented( + gb_type="torch.fx.traceback.annotate escaped from compiled region", + context=str(self), + explanation="Dynamo doesn't support graph break on torch.fx.traceback.annotate.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + +class DynamoConfigPatchVariable(ContextWrappingVariable): + """represents torch._dynamo.patch_dynamo_config""" + + # NOTE: no need to guard on dynamo config because dynamo config should not affect soundness + # (though it may affect tracing behavior) + def __init__(self, target_values: dict[str, Any], **kwargs: Any) -> None: + target_values_tuple = tuple(target_values.items()) + super().__init__( + target_values=(target_values_tuple,), initial_values=None, **kwargs + ) + # pyrefly: ignore [implicit-any] + initial_values_dict = {} + for key, _ in target_values_tuple: + initial_values_dict[key] = torch._dynamo.config.__getattr__(key) # type: ignore[attr-defined] + self.initial_values = (tuple(initial_values_dict.items()),) + + def _call_func(self, tx: "InstructionTranslatorBase", values: Any) -> None: + if len(values) != 1: + raise AssertionError(f"expected 1 value, got {len(values)}") + value = values[0] + # manually patch dynamo config + for key, val in value: + torch._dynamo.config.__setattr__(key, val) # type: ignore[attr-defined] + # No need to keep track of global side effects because + # dynamo will properly restore this context manager for + # unsupported instructions and continuation functions. + # Dynamo config also should not affect the semantics of the compiled graph. + + def module_name(self) -> str: + return "torch._dynamo" + + def fn_name(self) -> str: + return "patch_dynamo_config" + + def python_type(self) -> type: + from torch._dynamo.decorators import DynamoConfigPatchProxy + + return DynamoConfigPatchProxy + + +class ErrorOnGraphBreakVariable(ContextWrappingVariable): + """represents torch._dynamo.error_on_graph_break""" + + def __init__(self, error_on_graph_break: bool, **kwargs: Any) -> None: + super().__init__( + target_values=(error_on_graph_break,), + initial_values=(_get_error_on_graph_break(),), + **kwargs, + ) + + def _call_func( + self, tx: "InstructionTranslatorBase", values: Sequence[bool] + ) -> None: + if len(values) != 1: + raise AssertionError(f"expected 1 value, got {len(values)}") + _set_error_on_graph_break(values[0]) + + def module_name(self) -> str: + return "torch._dynamo" + + def fn_name(self) -> str: + return "error_on_graph_break" + + def python_type(self) -> type: + from torch._dynamo.decorators import ErrorOnGraphBreakDecoratorContextManager + + return ErrorOnGraphBreakDecoratorContextManager + + +class CudagraphOverrideVariable(ContextWrappingVariable): + """represents torch._dynamo.override_cudagraphs""" + + def __init__(self, fwd: bool | None, bwd: bool | None, **kwargs: Any) -> None: + super().__init__( + target_values=(fwd, bwd), + initial_values=None, # Captured in enter() + **kwargs, + ) + + def enter(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + # Capture current annotation before overwriting + prev = tx.output.cudagraph_annotation + if prev is not None: + self.initial_values = (prev.fwd, prev.bwd) + else: + self.initial_values = (None,) + return super().enter(tx) + + def _call_func( + self, tx: "InstructionTranslatorBase", values: tuple[Any, ...] + ) -> None: + from torch._inductor import _CudagraphAnnotation + + if len(values) == 1 and values[0] is None: + # Restoring to no annotation + tx.output.cudagraph_annotation = None + tx.output.tracing_context.cudagraph_annotation = None + else: + if len(values) != 2: + raise AssertionError(f"expected 2 values, got {len(values)}") + fwd, bwd = values + annotation = _CudagraphAnnotation(fwd=fwd, bwd=bwd) + tx.output.cudagraph_annotation = annotation + tx.output.tracing_context.cudagraph_annotation = annotation + + def module_name(self) -> str: + return "torch._dynamo" + + def fn_name(self) -> str: + return "override_cudagraphs" + + def python_type(self) -> type: + from torch._dynamo.decorators import CudagraphOverrideContextManager + + return CudagraphOverrideContextManager + + def exit_on_graph_break(self) -> bool: + # Annotation persists until graph is compiled; each resume function + # will reconstruct the context manager and call enter() again + return False + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> "VariableTracker": + # Override to NOT call cleanup here. The cleanup will happen in + # call_cleanup_hooks() during compile_subgraph, which is AFTER + # the annotation is copied to gm.meta. + return variables.ConstantVariable.create(None) + + +class WithEnterFunctionVariable(VariableTracker): + def __init__( + self, + ctx: ContextWrappingVariable | GenericContextWrappingVariable, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.ctx = ctx + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def python_type(self) -> type: + return types.MethodType + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if args: + raise AssertionError( + "WithEnterFunctionVariable.call_function expects no args" + ) + if kwargs: + raise AssertionError( + "WithEnterFunctionVariable.call_function expects no kwargs" + ) + # NOTE: we assume that the instruction immediately after the current CALL instruction + # is the first instruction of the block. + + return tx.enter_ctx(self.ctx, tx.current_instruction) + + def reconstruct(self, codegen: "PyCodegen") -> None: + try: + type_str = f"{self.ctx.module_name()}.{self.ctx.fn_name()}" + except NotImplementedError: + type_str = str(type(self.ctx)) + unimplemented( + gb_type="Attempted to reconstruct context manager's __enter__ method", + context=str(self.ctx), + explanation=f"Attempted to reconstruct context manager {type_str} while tracing `with ...:`", + hints=[ + "It is likely there is a graph break while tracing `with ctx:` " + "but outside the actual `ctx.__enter__()` method. " + "`torch.compile` does not expect this to happen.", + *graph_break_hints.DIFFICULT, + *graph_break_hints.DYNAMO_BUG, + ], + ) + + +class WithExitFunctionVariable(VariableTracker): + _nonvar_fields = { + "target", + *VariableTracker._nonvar_fields, + } + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def __init__( + self, + ctx: ContextWrappingVariable | GenericContextWrappingVariable, + target: Any, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if not isinstance( + ctx, (ContextWrappingVariable, GenericContextWrappingVariable) + ): + raise AssertionError( + f"ctx must be a ContextWrappingVariable or GenericContextWrappingVariable, got {type(ctx)}" + ) + self.ctx = ctx + self.target = target + + def python_type(self) -> type: + return types.MethodType + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if kwargs: + raise AssertionError( + "WithExitFunctionVariable.call_function expects no kwargs" + ) + return self.ctx.exit(tx, *args) + + def reconstruct(self, codegen: "PyCodegen") -> None: + # Note here we reconstruct the context manager rather than the + # exit function. The handler generated by BlockStackEntry + # will re-enter the context in the resume function. + self.ctx.reconstruct_type(codegen) # type: ignore[union-attr] diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/dicts.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/dicts.py new file mode 100644 index 0000000000000000000000000000000000000000..8a3d143b249dd21c99ff10be47814748307c95f4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/dicts.py @@ -0,0 +1,1767 @@ +""" +Dictionary-related variable tracking classes for PyTorch Dynamo. + +This module implements variable tracking for different types of dictionary-like objects: +- Regular Python dictionaries (dict) +- Ordered dictionaries (collections.OrderedDict) +- Default dictionaries (collections.defaultdict) +- Dictionary views (keys and values) + +These classes are responsible for tracking dictionary operations during graph compilation, +maintaining proper guards for dictionary mutations and key existence checks. They handle +dictionary creation, modification, key/value access, and view operations while ensuring +correct behavior in the compiled code through appropriate guard installation. + +The implementation uses a special HashableTracker wrapper to handle +dictionary keys while preserving proper aliasing semantics. Set-related classes live +in sets.py. +""" + +import collections +import functools +import sys +import types +from collections.abc import Callable, Iterator +from typing import Any, cast, TYPE_CHECKING, Union + +from torch.utils._pytree import MappingKey + +from .. import graph_break_hints, polyfills, variables +from ..bytecode_transformation import ( + create_call_function, + create_call_method, + create_dup_top, + create_instruction, +) +from ..exc import raise_observed_exception, raise_type_error, unimplemented +from ..guards import GuardBuilder, install_guard +from ..source import ( + AttrSource, + DictGetItemSource, + is_constant_source, + is_from_local_source, +) +from ..utils import ( + _item_debug_repr, + cmp_name_to_op_mapping, + dict_items, + dict_keys, + dict_values, + istype, + raise_args_mismatch, + tracked_repr, + unpack_iterable, +) +from .base import ( + AttributeMutationExisting, + AttributeMutationNew, + AttrMutationKind, + Method, + NO_SUCH_SUBOBJ, + ValueMutationNew, + VariableTracker, +) +from .constant import ConstantVariable +from .hashable import HashableTracker, is_hashable, raise_unhashable +from .object_protocol import ( + _is_method_type, + generic_getitem, + generic_richcompare_bool, + mro_lookup, +) + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + from .functions import UserFunctionVariable + + +# [Adding a new supported class within the keys of ConstDictVariable] +# - Implement hash_impl(self, tx) on the VariableTracker subclass (or rely on the +# base class default which uses get_real_python_backed_value()) +# - Implement tp_richcompare_impl() for key equality + + +def pydict_check(obj: VariableTracker) -> bool: + # This is a simplified version of the CPython's PyDict_Check function: + return issubclass(obj.python_type(), dict) + + +def _is_set_or_dictview(obj: VariableTracker) -> bool: + """PyAnySet_Check(other) || PyDictViewSet_Check(other)""" + try: + t = obj.python_type() + except NotImplementedError: + return False + return issubclass(t, (set, frozenset, dict_keys, dict_items)) + + +class ConstDictVariable(VariableTracker): + # PyDict_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c#L4825 + _cpython_type = dict + + CONTAINS_GUARD = GuardBuilder.DICT_CONTAINS + NOT_CONTAINS_GUARD = GuardBuilder.DICT_NOT_CONTAINS + + _nonvar_fields = { + "_checking_python_constant", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + items: dict[VariableTracker, VariableTracker], + **kwargs: Any, + ) -> None: + # .clone() pass these arguments in kwargs but they're recreated a few + # lines below + if "original_items" in kwargs: + kwargs.pop("original_items") + if "should_reconstruct_all" in kwargs: + kwargs.pop("should_reconstruct_all") + if "_checking_python_constant" in kwargs: + kwargs.pop("_checking_python_constant") + + super().__init__(**kwargs) + + Hashable = HashableTracker + + # Keys will just be HashableTrackers when cloning, in any other case they'll be VariableTrackers + if not all( + isinstance(x, (VariableTracker, Hashable)) + and isinstance(v, VariableTracker) + for x, v in items.items() + ): + raise AssertionError( + "All keys must be VariableTracker or HashableTracker " + "and all values must be VariableTracker" + ) + + def make_hashable( + key: Union[VariableTracker, "HashableTracker"], + ) -> "HashableTracker": + return key if isinstance(key, Hashable) else Hashable(key) + + items_cls = cast(type, self._cpython_type) + self.items = items_cls({make_hashable(x): v for x, v in items.items()}) + # need to reconstruct everything if the dictionary is an intermediate value + # or if a pop/delitem was executed + self.should_reconstruct_all = ( + not is_from_local_source(self.source) if self.source else True + ) + self.original_items = items.copy() + # Re-entrancy guard for is_python_constant against self-referential + # dicts (d[k] = d, directly or via an OrderedDict/defaultdict wrapper + # whose _base_vt is this instance). Both forms re-enter this same + # instance's is_python_constant, so a per-instance flag suffices. + self._checking_python_constant = False + + def as_proxy(self) -> dict[Any, Any]: + return {k.vt.as_proxy(): v.as_proxy() for k, v in self.items.items()} + + def debug_repr(self) -> str: + items: list[str] = [] + for k, v in self.items.items(): + key_str = _item_debug_repr(k.vt) + val_str = _item_debug_repr(v) + items.append(f"{key_str}: {val_str}") + return "{" + ", ".join(items) + "}" + + def is_python_constant(self) -> bool: + # Avoid the base implementation, which probes as_python_constant() and + # thus rebuilds a real dict, re-hashing the keys (wrong for keys with a + # side-effecting __hash__). Check element constness directly instead. + # Re-entrancy guard: a self-referential dict (d[k] = d, directly or via + # an OrderedDict/defaultdict wrapper delegating to this _base_vt) would + # otherwise recurse forever. A cyclic dict is not a flat python + # constant; return False so reconstruct handles the cycle. + if self._checking_python_constant: + return False + self._checking_python_constant = True + try: + return all( + k.vt.is_python_constant() and v.is_python_constant() + for k, v in self.items.items() + ) + finally: + self._checking_python_constant = False + + def as_python_constant(self) -> dict[Any, Any]: + return { + k.vt.as_python_constant(): v.as_python_constant() + for k, v in self.items.items() + } + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + items = [ + f"{tracked_repr(tx, key.vt)}: {tracked_repr(tx, value)}" + for key, value in self.items.items() + ] + return VariableTracker.build(tx, "{" + ", ".join(items) + "}") + + def keys_as_python_constant(self) -> dict[Any, VariableTracker]: + self.install_dict_keys_match_guard() + return {k.vt.as_python_constant(): v for k, v in self.items.items()} + + def python_type(self) -> type: + return cast(type, self._cpython_type) + + def __contains__(self, vt: VariableTracker) -> bool: + if not isinstance(vt, VariableTracker): + raise AssertionError(f"Expected VariableTracker, got {type(vt)}") + # Use is_hashable as a side-effect-free pre-check. We can't catch + # ObservedTypeError from HashableTracker because it modifies + # tx.exn_vt_stack as a side effect. + if not is_hashable(vt): + return False + key = HashableTracker(vt) + return key in self.items and not isinstance( + self.items[key], variables.DeletedVariable + ) + + def call_tree_map_branch( + self, + tx: "InstructionTranslatorBase", + tree_map_fn: "UserFunctionVariable", + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + other_dicts: list[ConstDictVariable] = [] + for candidate in rest: + candidate = candidate.realize() + if not isinstance(candidate, ConstDictVariable) or len( + candidate.items + ) != len(self.items): + return self._tree_map_fallback( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs + ) + other_dicts.append(candidate) + + new_items_hashed = type(self.items)() + for key_tracker, value in self.items.items(): + sibling_leaves: list[VariableTracker] = [] + for candidate in other_dicts: + try: + sibling_leaves.append(candidate.items[key_tracker]) + except KeyError: + return self._tree_map_fallback( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs + ) + new_items_hashed[key_tracker] = value.call_tree_map( + tx, + tree_map_fn, + map_fn, + sibling_leaves, + tree_map_kwargs, + ) + + updated_original_items = { + key_tracker.vt: new_items_hashed[key_tracker] + for key_tracker in new_items_hashed + } + + return self.clone( + items=new_items_hashed, + original_items=updated_original_items, + should_reconstruct_all=True, + source=None, + mutation_type=ValueMutationNew(), + ) + + def call_tree_map_with_path_branch( + self, + tx: "InstructionTranslatorBase", + tree_map_fn: "UserFunctionVariable", + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + keypath: tuple[Any, ...], + ) -> VariableTracker: + other_dicts: list[ConstDictVariable] = [] + for candidate in rest: + candidate = candidate.realize() + if not isinstance(candidate, ConstDictVariable) or len( + candidate.items + ) != len(self.items): + return self._tree_map_with_path_fallback( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs, keypath + ) + other_dicts.append(candidate) + + new_items_hashed = type(self.items)() + for key_tracker, value in self.items.items(): + sibling_leaves: list[VariableTracker] = [] + for candidate in other_dicts: + try: + sibling_leaves.append(candidate.items[key_tracker]) + except KeyError: + return self._tree_map_with_path_fallback( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs, keypath + ) + key_const = key_tracker.vt.as_python_constant() + child_keypath = keypath + (MappingKey(key_const),) + new_items_hashed[key_tracker] = value.call_tree_map_with_path( + tx, + tree_map_fn, + map_fn, + sibling_leaves, + tree_map_kwargs, + child_keypath, + ) + + updated_original_items = { + key_tracker.vt: new_items_hashed[key_tracker] + for key_tracker in new_items_hashed + } + + return self.clone( + items=new_items_hashed, + original_items=updated_original_items, + should_reconstruct_all=True, + source=None, + mutation_type=ValueMutationNew(), + ) + + def len(self) -> int: + return sum( + not isinstance(x, variables.DeletedVariable) for x in self.items.values() + ) + + def has_new_items(self) -> bool: + return self.should_reconstruct_all or any( + self.is_new_item(self.original_items.get(key.vt), value) + for key, value in self.items.items() + ) + + def is_new_item( + self, value: VariableTracker | None, other: VariableTracker + ) -> bool: + # compare the id of the realized values if both values are not lazy VTs + if value and value.is_realized() and other.is_realized(): + return id(value.realize()) != id(other.realize()) + return id(value) != id(other) + + def reconstruct_kvs_into_new_dict(self, codegen: "PyCodegen") -> None: + # Build a dictionary that contains the keys and values. + num_args = 0 + for key, value in self.items.items(): + # We can safely call realize() here as it won't introduce any new guards + item = self.original_items.get(key.vt) + if self.is_new_item(item, value) or self.should_reconstruct_all: + codegen(key.vt) + codegen(value) + num_args += 1 + codegen.append_output(create_instruction("BUILD_MAP", arg=num_args)) + + def reconstruct(self, codegen: "PyCodegen") -> None: + if self._contains_self_reference(): + codegen.extend_output( + [ + create_instruction("BUILD_MAP", arg=0), + create_dup_top(), + ] + ) + codegen.add_cache(self) + self.reconstruct_kvs_into_new_dict(codegen) + codegen.append_output(create_instruction("DICT_UPDATE", arg=1)) + else: + # Non-self-referential: use simple codegen + self.reconstruct_kvs_into_new_dict(codegen) + + def reconstruct_pycode(self, codegen) -> str: + if self._contains_self_reference(): + raise NotImplementedError + return f"{{{', '.join(f'{k.vt.reconstruct_pycode(codegen)}: {v.reconstruct_pycode(codegen)}' for k, v in self.items.items())}}}" + + def getitem_const_raise_exception_if_absent( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + key = HashableTracker(arg) + if key not in self.items: + raise_observed_exception(KeyError, tx, args=[arg]) + return self.items[key] + + def getitem_const( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + key = HashableTracker(arg) + if key not in self.items: + msg = f"Dictionary key {arg.value} not found during tracing" # type: ignore[attr-defined] + unimplemented( + gb_type="key not found in dict", + context=f"Key {arg.value}", # type: ignore[attr-defined] + explanation=msg, + hints=[ + "Check if the key exists in the dictionary before accessing it.", + *graph_break_hints.USER_ERROR, + ], + ) + return self.items[key] + + def maybe_getitem_const(self, arg: VariableTracker) -> VariableTracker | None: + key = HashableTracker(arg) + if key not in self.items: + return None + return self.items[key] + + def realize_key_vt(self, arg: VariableTracker) -> None: + # Realize the LazyVT on a particular index + if arg not in self: + raise AssertionError(f"Key {arg} not found in dict") + key = HashableTracker(arg) + index = tuple(self.items.keys()).index(key) + original_key_vt = tuple(self.original_items.keys())[index] + if isinstance(original_key_vt, variables.LazyVariableTracker): + original_key_vt.realize() + + def install_dict_keys_match_guard(self) -> None: + if self.source: + install_guard(self.make_guard(GuardBuilder.DICT_KEYS_MATCH)) + + def install_dict_contains_guard( + self, tx: "InstructionTranslatorBase", args: list[VariableTracker] + ) -> None: + # Key guarding - These are the cases to consider + # 1) The dict has been mutated. In this case, we would have already + # inserted a DICT_KEYS_MATCH guard, so we can skip. + # + # 2) args[0].source is None. This happens for const keys. Here, we + # have to insert the DICT_CONTAINS guard. + # + # 3) args[0].source is not None. This can happen for non-const VTs. + # 3a) contains=True. In this case, we can access the lazyVT from + # original_items and selectively realize it. + # 3b) contains=False. There is no easy way to selectively apply this + # DICT_NOT_CONTAINS guard because our guard are represented via trees. + # Be conservative and add DICT_KEYS_MATCH guard. + + if not self.source: + return + + if tx.output.side_effects.is_modified(self): + return + + contains = args[0] in self + if args[0].source is None and args[0].is_python_constant(): + guard_fn = ( + type(self).CONTAINS_GUARD if contains else type(self).NOT_CONTAINS_GUARD + ) + install_guard( + self.make_guard( + functools.partial( + guard_fn, + key=args[0].as_python_constant(), + ) + ) + ) + elif args[0].source: + if contains: + self.realize_key_vt(args[0]) + else: + self.install_dict_keys_match_guard() + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # dict_subscript: https://github.com/python/cpython/blob/62a6e898e01/Objects/dictobject.c#L3673-L3706 + # Unhashable key check happens inside HashableTracker (hash_impl → TypeError). + return self.getitem_const_raise_exception_if_absent(tx, key) + + def sq_contains_impl( + self, tx: "InstructionTranslatorBase", item: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c#L4657-L4668 + if not is_hashable(item): + raise_type_error(tx, f"unhashable type: '{item.python_type_name()}'") + self.install_dict_contains_guard(tx, [item]) + contains = item in self + return VariableTracker.build(tx, contains) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + from .iter import DictIterator + + if self.source and not is_constant_source(self.source): + install_guard(self.make_guard(GuardBuilder.DICT_KEYS_MATCH)) + tx.output.guard_on_key_order.add(self.source) + return DictIterator(self.items.keys()) + + def tp_init_impl( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from . import DictBuiltinVariable + + temp_dict_vt = DictBuiltinVariable.call_custom_dict(tx, dict, *args, **kwargs) + tx.output.side_effects.mutation(self) + self.items.update(temp_dict_vt.items) # type: ignore[attr-defined] + return ConstantVariable.create(None) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # NB - Both key and value are LazyVariableTrackers in the beginning. So, + # we have to insert guards when a dict method is accessed. For this to + # be simple, we are conservative and overguard. We skip guard only for + # get/__getitem__ because the key guard will be inserted by the + # corresponding value VT. For __contains__, we add a DICT_CONTAINS + # guard. But for all the other methods, we insert the DICT_KEYS_MATCH + # guard to be conservative. + Hashable = HashableTracker + + if name == "items": + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + self.install_dict_keys_match_guard() + if self.source: + tx.output.guard_on_key_order.add(self.source) + return DictItemsVariable(self) + elif name == "keys": + if len(args): + raise_args_mismatch(tx, name, "0 args", f"{len(args)} args") + self.install_dict_keys_match_guard() + if self.source: + tx.output.guard_on_key_order.add(self.source) + return DictKeysVariable(self) + elif name == "__reversed__": + # dict.__reversed__: reverse insertion-order key iterator. + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c (dict___reversed___impl) + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + self.install_dict_keys_match_guard() + if self.source: + tx.output.guard_on_key_order.add(self.source) + reversed_keys = [k.vt for k in reversed(list(self.items.keys()))] + return variables.ListIteratorVariable( + reversed_keys, mutation_type=ValueMutationNew() + ) + elif name == "values": + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + self.install_dict_keys_match_guard() + if self.source: + tx.output.guard_on_key_order.add(self.source) + if args or kwargs: + raise_observed_exception(TypeError, tx) + return DictValuesVariable(self) + elif name == "copy": + self.install_dict_keys_match_guard() + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + return self.clone( + items=self.items.copy(), mutation_type=ValueMutationNew(), source=None + ) + elif name == "get": + if len(args) not in (1, 2): + raise_args_mismatch(tx, name, "1 or 2 args", f"{len(args)} args") + + if args[0] not in self: + self.install_dict_contains_guard(tx, args) + if len(args) == 1: + # if default is not given, return None + return ConstantVariable.create(None) + return args[1] + # Key guarding - Nothing to do. + return self.getitem_const(tx, args[0]) + elif name == "pop" and self.is_mutable(): + if len(args) not in (1, 2): + raise_args_mismatch(tx, name, "1 or 2 args", f"{len(args)} args") + + if args[0] not in self: + # missing item, return the default value. Install no DICT_CONTAINS guard. + self.install_dict_contains_guard(tx, args) + if len(args) == 1: + # if default is not given, raise KeyError + raise_observed_exception(KeyError, tx) + return args[1] + + self.should_reconstruct_all = True + tx.output.side_effects.mutation(self) + return self.items.pop(Hashable(args[0])) + elif name == "popitem" and self.is_mutable(): + # dict.popitem() takes no args. OrderedDict.popitem(last=) is + # handled by OrderedDictVariable.call_method. + if len(args): + raise_args_mismatch(tx, name) + + if not self.items: + raise_observed_exception( + KeyError, + tx, + args=[ + "popitem(): dictionary is empty", + ], + ) + + k, v = self.items.popitem() + self.should_reconstruct_all = True + tx.output.side_effects.mutation(self) + + return variables.TupleVariable([k.vt, v]) + elif name == "clear": + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + self.should_reconstruct_all = True + tx.output.side_effects.mutation(self) + self.items.clear() + return ConstantVariable.create(None) + elif name == "update" and self.is_mutable(): + # Mirrors CPython PyDict_Merge: if arg has keys(), iterate keys and + # __getitem__; else treat arg as iterable of (key, value) pairs. + # kwargs are always merged on top. + # ref: https://github.com/python/cpython/blob/60403a5409ff2c3f3b07dd2ca91a7a3e096839c7/Objects/dictobject.c#L3571 + self.install_dict_keys_match_guard() + if len(args) > 1: + raise_args_mismatch(tx, name, "at most 1 args", f"{len(args)} args") + if args or kwargs: + tx.output.side_effects.mutation(self) + if args: + other = args[0] + if isinstance(other, ConstDictVariable): + # NB - Guard on all the keys of the other dict to ensure + # correctness. + other.install_dict_keys_match_guard() + self.items.update(other.items) + elif ( + isinstance( + other, + (variables.UserDefinedObjectVariable, MappingProxyVariable), + ) + and other.call_obj_hasattr(tx, "keys").as_python_constant() + ): + keys = other.call_method(tx, "keys", [], {}) + for key in unpack_iterable(tx, keys): + self.items[Hashable(key)] = generic_getitem(tx, other, key) + else: + for idx, item in enumerate(unpack_iterable(tx, other)): + pair = unpack_iterable(tx, item) + if len(pair) != 2: + raise_observed_exception( + ValueError, + tx, + args=[ + "dictionary update sequence element " + f"#{idx} has length {len(pair)}; 2 is required" + ], + ) + self.items[Hashable(pair[0])] = pair[1] + for k, v in kwargs.items(): + self.items[Hashable(VariableTracker.build(tx, k))] = v + return ConstantVariable.create(None) + elif name == "setdefault" and self.is_mutable(): + if len(args) not in (1, 2): + raise_args_mismatch( + tx, + name, + "1 or 2 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + + self.install_dict_keys_match_guard() + if kwargs or len(args) > 2: + raise_args_mismatch( + tx, + name, + "at most 2 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + value = self.maybe_getitem_const(args[0]) + if value is not None: + return value + else: + if len(args) == 1: + x = ConstantVariable.create(None) + else: + x = args[1] + tx.output.side_effects.mutation(self) + self.items[Hashable(args[0])] = x + return x + else: + return super().call_method(tx, name, args, kwargs) + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase" + ) -> list[VariableTracker]: + self.install_dict_keys_match_guard() + return [x.vt for x in self.items] + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/dictobject.c#L4643-L4658 + self_, other_ = (other, self) if reverse else (self, other) + if pydict_check(self_) and pydict_check(other_): + new = self_.call_method(tx, "copy", [], {}) + new.call_method(tx, "update", [other_], {}) + return new + return ConstantVariable.create(NotImplemented) + + def nb_inplace_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/dictobject.c#L4660-L4667 + self.call_method(tx, "update", [other], {}) + return self + + def mp_ass_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c (dict_ass_sub) + if not self.is_mutable(): + return super().mp_ass_subscript_impl(tx, key, value) + + # value=None signals delete (CPython NULL sentinel). + if not is_hashable(key): + raise_unhashable(key, tx) + self.install_dict_keys_match_guard() + hkey = HashableTracker(key) + tx.output.side_effects.mutation(self) + if value is None: + if hkey not in self.items: + raise_observed_exception(KeyError, tx, args=[key.as_python_constant()]) + self.should_reconstruct_all = True + del self.items[hkey] + else: + self.items[hkey] = value + return ConstantVariable.create(None) + + def mp_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + """Mapping length for dict objects.""" + self.install_dict_keys_match_guard() + return VariableTracker.build(tx, len(self.items)) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + # dict not allow setting arbitrary attributes. OrderedDict and + # defaultdict allow arbitrary setattr, but not deletion of default attrs + cls = self.python_type() + if any( + cls is t for t in (dict, collections.OrderedDict, collections.defaultdict) + ): + if hasattr(cls, name): + return ConstantVariable.create(True) + if cls is dict: + return ConstantVariable.create(False) + + msg = f"hasattr on {cls} is not supported" + unimplemented( + gb_type="unsupported hasattr operation", + context=f"Class {cls}", + explanation=msg, + hints=[ + "Consider using a regular dictionary instead", + *graph_break_hints.SUPPORTABLE, + ], + ) + + def clone(self, **kwargs: Any) -> VariableTracker: + self.install_dict_keys_match_guard() + return super().clone(**kwargs) + + def is_hashable(self) -> bool: + return False + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + from ..exc import raise_type_error + + raise_type_error(tx, f"unhashable type: '{self.python_type_name()}'") + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + # dict_richcompare: https://github.com/python/cpython/blob/e76aa128fe/Objects/dictobject.c#L4198 + # Only supports eq/ne; returns NotImplemented for ordering. + from .builder import SourcelessBuilder + from .user_defined import UserDefinedDictVariable + + if op not in ("__eq__", "__ne__"): + return ConstantVariable.create(NotImplemented) + if not isinstance(other, ConstDictVariable): + # Unwrap UserDefinedDictVariable to its base ConstDictVariable. + # This is correct because CPython's dict_equal operates on the + # internal C struct directly (ma_used, dk_entries, _Py_dict_lookup) + # -- it never calls __getitem__ or __len__ on dict subclasses. + # https://github.com/python/cpython/blob/e76aa128fe/Objects/dictobject.c#L4125-L4185 + if isinstance(other, UserDefinedDictVariable): + if other._base_vt is None: + raise AssertionError("expected _base_vt to be set") + other = other._base_vt + else: + return ConstantVariable.create(NotImplemented) + eq_result = SourcelessBuilder.create(tx, polyfills.dict___eq__).call_function( + tx, [self, other], {} + ) + if op == "__ne__": + return VariableTracker.build(tx, not eq_result.as_python_constant()) + return eq_result + + def tp_getattro_impl(self, tx: "InstructionTranslatorBase", name: str): + if name == "__class__": + return VariableTracker.build(tx, self.python_type()) + # DictGuardManager does not support getattr_manager for plain dicts, + # so AttrSource chains through a dict source break guard creation. + # Return CallMethodVariable directly for methods, bypassing the + # MRO walk in object_generic_getattr that would create that chain. + type_attr = mro_lookup(self.python_type(), name) + if type_attr is not NO_SUCH_SUBOBJ and _is_method_type(type_attr): + return variables.CallMethodVariable(self, name) + return super().tp_getattro_impl(tx, name) + + +class OrderedDictVariable(ConstDictVariable): + _cpython_type = collections.OrderedDict + + # OrderedDict-exclusive C methods, declared like CPython's odict tp_methods. + # move_to_end is odict-only; popitem honors last= (vs dict's LIFO popitem). + # OrderedDict exposes no tp_getset / tp_members. + # https://github.com/python/cpython/blob/v3.13.0/Objects/odictobject.c + + def move_to_end( + self: "OrderedDictVariable", + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + self.install_dict_keys_match_guard() + tx.output.side_effects.mutation(self) + if args[0] not in self: + raise_observed_exception(KeyError, tx) + + last = True + if len(args) == 2 and args[0].is_python_constant(): + last = args[1].as_python_constant() + if "last" in kwargs and kwargs["last"].is_python_constant(): + last = kwargs["last"].as_python_constant() + + self.items.move_to_end(HashableTracker(args[0]), last=last) + return ConstantVariable.create(None) + + def popitem( + self: "OrderedDictVariable", + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if not self.items: + raise_observed_exception( + KeyError, tx, args=["popitem(): dictionary is empty"] + ) + + last = True + if len(args) == 1 and args[0].is_python_constant(): + last = args[0].as_python_constant() + if "last" in kwargs and kwargs["last"].is_python_constant(): + last = kwargs["last"].as_python_constant() + + k, v = self.items.popitem(last=last) + self.should_reconstruct_all = True + tx.output.side_effects.mutation(self) + return variables.TupleVariable([k.vt, v]) + + tp_methods = { + "move_to_end": Method(move_to_end), + "popitem": Method(popitem), + } + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Consult tp_methods before ConstDictVariable's own dispatch, whose + # bare-dict popitem() branch would otherwise shadow the OrderedDict + # popitem(last=) handler. + method = self.lookup_tp_method(name) + if method is not None: + result = method(self, tx, name, args, kwargs) + if result is not None: + return result + return super().call_method(tx, name, args, kwargs) + + def as_python_constant(self) -> "collections.OrderedDict[Any, Any]": + return collections.OrderedDict(super().as_python_constant()) + + @staticmethod + def _ordered_dict_repr(items: list[tuple[str, str]]) -> str: + if not items: + return "OrderedDict()" + if sys.version_info >= (3, 12): + return ( + "OrderedDict({" + + ", ".join(f"{key}: {value}" for key, value in items) + + "})" + ) + return ( + "OrderedDict([" + + ", ".join(f"({key}, {value})" for key, value in items) + + "])" + ) + + def debug_repr(self) -> str: + items = [(k.vt.debug_repr(), v.debug_repr()) for k, v in self.items.items()] + return self._ordered_dict_repr(items) + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # Python < 3.12 uses the historical list-of-pairs form, while 3.12+ + # uses dict-style formatting. + items = [ + (tracked_repr(tx, key.vt), tracked_repr(tx, value)) + for key, value in self.items.items() + ] + return VariableTracker.build(tx, self._ordered_dict_repr(items)) + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # OrderedDict.__or__/__ror__ preserve the OrderedDict type, unlike + # dict.__or__ which returns a plain dict for a subclass operand. + # ref: https://github.com/python/cpython/blob/3.13/Lib/collections/__init__.py#L327-L339 + if not issubclass(other.python_type(), dict): + return ConstantVariable.create(NotImplemented) + if reverse: + new = VariableTracker.build(tx, self.python_type()).call_function( + tx, [other], {} + ) + new.call_method(tx, "update", [self], {}) + else: + new = self.call_method(tx, "copy", [], {}) + new.call_method(tx, "update", [other], {}) + return new + + def reconstruct(self, codegen: "PyCodegen") -> None: + # emit `OrderedDict(constructed_dict)` + codegen.add_push_null( + lambda: codegen.extend_output( + [ + codegen.create_load_python_module(collections), + codegen.create_load_attr("OrderedDict"), + ] + ) + ) + if self._contains_self_reference(): + codegen.extend_output( + [ + *create_call_function(0, False), + create_dup_top(), + ] + ) + codegen.add_cache(self) + + codegen.append_output(create_dup_top()) + codegen.load_method("update") + self.reconstruct_kvs_into_new_dict(codegen) + codegen.extend_output( + [ + *create_call_method(1), + create_instruction("POP_TOP"), + ] + ) + else: + self.reconstruct_kvs_into_new_dict(codegen) + codegen.extend_output(create_call_function(1, False)) + + def reconstruct_pycode(self, codegen) -> str: + raise NotImplementedError + + +class MappingProxyVariable(VariableTracker): + # PyDictProxy_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/descrobject.c#L1995 + _cpython_type = types.MappingProxyType + + # proxies to the original dict_vt + def __init__(self, dv_dict: ConstDictVariable, **kwargs: Any) -> None: + super().__init__(**kwargs) + if not isinstance(dv_dict, ConstDictVariable): + raise AssertionError(f"Expected ConstDictVariable, got {type(dv_dict)}") + self.dv_dict = dv_dict + + def python_type(self) -> type: + return types.MappingProxyType + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # mappingproxy.__hash__ delegates to the underlying dict, which + # raises TypeError. Mirror that behavior. + return self.dv_dict.hash_impl(tx) + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase" + ) -> list[VariableTracker]: + return self.dv_dict.unpack_var_sequence(tx) + + def reconstruct(self, codegen: "PyCodegen") -> None: + # load types.MappingProxyType + if self.source: + msg = ( + f"Preexisting MappingProxyVariable (source: {self.source}) cannot be reconstructed " + "because the connection to the original dict will be lost." + ) + unimplemented( + gb_type="mapping proxy cannot be reconstructed", + context=f"Source: {self.source}", + explanation=msg, + hints=[ + "Use a mapping proxy constructed in the same `torch.compile` region.", + *graph_break_hints.SUPPORTABLE, + ], + ) + codegen.add_push_null( + lambda: codegen.extend_output( + [ + codegen.create_load_python_module(types), + codegen.create_load_attr("MappingProxyType"), + ] + ) + ) + codegen(self.dv_dict) + codegen.extend_output(create_call_function(1, False)) + + def _check_mutation_guard(self, tx: "InstructionTranslatorBase") -> None: + if self.source and tx.output.side_effects.has_existing_dict_mutation(): + msg = ( + "A dict has been modified while we have an existing mappingproxy object. " + "A mapping proxy object, as the name suggest, proxies a mapping " + "object (usually a dict). If the original dict object mutates, it " + "is reflected in the proxy object as well. For an existing proxy " + "object, we do not know the original dict it points to. Therefore, " + "for correctness we graph break when there is dict mutation and we " + "are trying to access a proxy object." + ) + + unimplemented( + gb_type="mapping proxy affected by dictionary mutation", + context=f"Source: {self.source}, Dict mutation detected", + explanation=msg, + hints=[ + "Avoid modifying dictionaries that might be referenced by mapping proxy objects", + "Or avoid using the mapping proxy objects after modifying its underlying dictionary", + ], + ) + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # mappingproxy_getitem: https://github.com/python/cpython/blob/62a6e898e01/Objects/descrobject.c#L1052-L1056 + # TODO(follow-up): add tests for invalid key type, missing key + self._check_mutation_guard(tx) + return self.dv_dict.mp_subscript_impl(tx, key) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + self._check_mutation_guard(tx) + return self.dv_dict.call_method(tx, name, args, kwargs) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.dv_dict.tp_iter_impl(tx) + + def sq_contains_impl( + self, tx: "InstructionTranslatorBase", item: VariableTracker + ) -> VariableTracker: + # https://github.com/python/cpython/blob/60403a5409ff/Objects/descrobject.c#L1087-L1095 + return self.dv_dict.sq_contains_impl(tx, item) + + def mp_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.dv_dict.mp_length_impl(tx) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + # mappingproxy_richcompare delegates to the underlying mapping: + # https://github.com/python/cpython/blob/60403a5409ff/Objects/descrobject.c#L1231-L1236 + from .object_protocol import generic_richcompare + + return generic_richcompare(tx, self.dv_dict, other, op) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + if self.python_type() is types.MappingProxyType: + return VariableTracker.build(tx, name in types.MappingProxyType.__dict__) + return super().call_obj_hasattr(tx, name) + + +class NNModuleHooksDictVariable(OrderedDictVariable): + # Special class to avoid adding any guards on the nn module hook ids. + # nn.Module hook dicts are OrderedDict, so back storage/reconstruct with it. + def install_dict_keys_match_guard(self) -> None: + pass + + def install_dict_contains_guard( + self, tx: "InstructionTranslatorBase", args: list[VariableTracker] + ) -> None: + pass + + +class DictViewVariable(VariableTracker): + """ + Models _PyDictViewObject + + This is an "abstract" class. Subclasses will override kv and the items method + """ + + kv: str | None = None + + def __init__(self, dv_dict: ConstDictVariable, **kwargs: Any) -> None: + super().__init__(**kwargs) + if self.kv not in ("keys", "values", "items"): + raise AssertionError( + f"Expected kv to be 'keys', 'values', or 'items', got {self.kv!r}" + ) + if not isinstance(dv_dict, ConstDictVariable): + raise AssertionError(f"Expected ConstDictVariable, got {type(dv_dict)}") + self.dv_dict = dv_dict + + @property + def view_items(self) -> Any: + if self.kv is None: + raise AssertionError("kv must not be None") + return getattr(self.dv_dict.items, self.kv)() + + def is_hashable(self) -> bool: + return False + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + from ..exc import raise_type_error + + raise_type_error(tx, f"unhashable type: '{self.python_type_name()}'") + + @property + def view_items_vt(self) -> list[VariableTracker]: + # Returns an iterable of the unpacked items + # Implement in the subclasses + raise NotImplementedError + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase" + ) -> list[VariableTracker]: + return self.view_items_vt + + def reconstruct(self, codegen: "PyCodegen") -> None: + if self.kv is None: + raise AssertionError("kv must not be None for reconstruct") + codegen(self.dv_dict) + codegen.load_method(self.kv) + codegen.call_method(0) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + if self.kv is None: + raise AssertionError("kv must not be None for call_obj_hasattr") + if name in self.python_type().__dict__: + return ConstantVariable.create(True) + return ConstantVariable.create(False) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + # dictview_mapping getset returns a read-only mappingproxy of the + # underlying dict for dict_keys/values/items. + # https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c#L5032-L5040 + if name == "mapping": + return MappingProxyVariable(self.dv_dict) + return super().tp_getattro_impl(tx, name) + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + if self.kv == "keys": + items = ", ".join(tracked_repr(tx, key.vt) for key in self.view_items) + elif self.kv == "values": + items = ", ".join(tracked_repr(tx, value) for value in self.view_items) + else: # items + items = ", ".join( + f"({tracked_repr(tx, key.vt)}, {tracked_repr(tx, value)})" + for key, value in self.view_items + ) + return VariableTracker.build(tx, f"{self.python_type_name()}([{items}])") + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "__reversed__": + # dict_keys/values/items __reversed__: reverse insertion order. + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + if self.dv_dict.source and not is_constant_source(self.dv_dict.source): + tx.output.guard_on_key_order.add(self.dv_dict.source) + return variables.ListIteratorVariable( + list(reversed(self.view_items_vt)), + mutation_type=ValueMutationNew(), + ) + return super().call_method(tx, name, args, kwargs) + + def sq_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + """Sequence length for dict view objects.""" + return VariableTracker.build(tx, len(self.view_items)) + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c#L6142-L6155 (dictviews_or) + s = VariableTracker.build(tx, set).call_function(tx, [self], {}) + s.call_method(tx, "update", [other], {}) + return s + + def nb_subtract_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c#L6036 (dictviews_sub) + self_, other_ = (other, self) if reverse else (self, other) + s = VariableTracker.build(tx, set).call_function(tx, [self_], {}) + s.call_method(tx, "difference_update", [other_], {}) + return s + + def nb_and_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/dictobject.c#L6105-L6188 (_PyDictView_Intersect) + s = VariableTracker.build(tx, set).call_function(tx, [self], {}) + s.call_method(tx, "intersection_update", [other], {}) + return s + + def nb_xor_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/dictobject.c#L6305-L6325 (dictviews_xor) + s = VariableTracker.build(tx, set).call_function(tx, [self], {}) + s.call_method(tx, "symmetric_difference_update", [other], {}) + return s + + +class DictKeysVariable(DictViewVariable): + # PyDictKeys_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c#L6365 + _cpython_type = dict_keys + + kv = "keys" + + @property + def set_items(self) -> set[VariableTracker]: + return set(self.view_items) + + @property + def view_items_vt(self) -> list[VariableTracker]: + # Returns an iterable of the unpacked items + return [x.vt for x in self.view_items] + + def python_type(self) -> type: + return dict_keys + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + from .iter import DictKeysIterator + + if self.dv_dict.source and not is_constant_source(self.dv_dict.source): + tx.output.guard_on_key_order.add(self.dv_dict.source) + return DictKeysIterator(self.dv_dict.items) + + def debug_repr(self) -> str: + if not self.view_items: + return "dict_keys([])" + else: + items: list[str] = [] + for k in self.view_items: + key_str = _item_debug_repr(k.vt) + items.append(key_str) + return "dict_keys([" + ", ".join(items) + "])" + + def sq_contains_impl( + self, tx: "InstructionTranslatorBase", item: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c#L5998-L6005 + return self.dv_dict.sq_contains_impl(tx, item) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + # dictview_richcompare: accepts set/frozenset and dict_keys/dict_items. + # https://github.com/python/cpython/blob/e76aa128fe/Objects/dictobject.c#L5952-L6010 + # Uses a polyfill with len() and ``in`` so that Dynamo traces through + # sq_length/sq_contains, matching CPython's use of PyObject_Size and + # PySequence_Contains. + from .builder import SourcelessBuilder + + if not _is_set_or_dictview(other): + return ConstantVariable.create(NotImplemented) + return SourcelessBuilder.create( + tx, polyfills.dictview_richcompare + ).call_function( + tx, + [ + SourcelessBuilder.create(tx, cmp_name_to_op_mapping[op]), + self, + other, + ], + {}, + ) + + +class DictValuesVariable(DictViewVariable): + # PyDictValues_Type: https://github.com/python/cpython/blob/e76aa128fe/Objects/dictobject.c#L6615 + _cpython_type = dict_values + + # dict_values is hashable (identity hash), unlike dict_keys/dict_items. + # + # CPython only inherits tp_hash from the base when BOTH tp_richcompare + # AND tp_hash are NULL on the type + # (https://github.com/python/cpython/blob/e76aa128fe/Objects/typeobject.c#L7665-L7679). + # dict_keys/dict_items set tp_richcompare (for set-like comparisons), + # so their tp_hash is NOT inherited — it stays NULL, and + # type_ready_set_hash sets it to PyObject_HashNotImplemented (unhashable) + # (https://github.com/python/cpython/blob/e76aa128fe/Objects/typeobject.c#L8066-L8085). + # dict_values does NOT set tp_richcompare + # (https://github.com/python/cpython/blob/e76aa128fe/Objects/dictobject.c#L6630), + # so it inherits object's tp_hash (PyObject_GenericHash) — hashable. + # + # Override DictViewVariable.hash_impl to restore the base identity hash. + kv = "values" + + # dict.values() do not implement tp_as_number + nb_or_impl = None # type: ignore[bad-override] + nb_inplace_or_impl = None # type: ignore[bad-override] + nb_subtract_impl = None # type: ignore[bad-override] + nb_inplace_subtract_impl = None # type: ignore[bad-override] + nb_and_impl = None # type: ignore[bad-override] + nb_inplace_and_impl = None # type: ignore[bad-override] + nb_xor_impl = None # type: ignore[bad-override] + nb_inplace_xor_impl = None # type: ignore[bad-override] + + def is_hashable(self) -> bool: + return True + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + return super(DictViewVariable, self).hash_impl(tx) + + @property + def view_items_vt(self) -> list[VariableTracker]: + return list(self.view_items) + + def python_type(self) -> type: + return dict_values + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + from .iter import DictValuesIterator + + if self.dv_dict.source and not is_constant_source(self.dv_dict.source): + tx.output.guard_on_key_order.add(self.dv_dict.source) + return DictValuesIterator(self.dv_dict.items) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + # dict_values has no tp_richcompare (inherits object's). + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def debug_repr(self) -> str: + if not self.view_items: + return "dict_values([])" + else: + items: list[str] = [] + for v in self.view_items: + val_str = _item_debug_repr(v) + items.append(val_str) + return "dict_values([" + ", ".join(items) + "])" + + +class DictItemsVariable(DictViewVariable): + # PyDictItems_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c#L6477 + _cpython_type = dict_items + + kv = "items" + + @property + def set_items(self) -> set["HashableTracker"]: + return { + HashableTracker(variables.TupleVariable([k.vt, v])) + for k, v in self.view_items + } + + @property + def view_items_vt(self) -> list[VariableTracker]: + # Returns an iterable of the unpacked items + return [variables.TupleVariable([k.vt, v]) for k, v in self.view_items] + + def python_type(self) -> type: + return dict_items + + def debug_repr(self) -> str: + if not self.view_items: + return "dict_items([])" + else: + items: list[str] = [] + for k, v in self.view_items: + key_str = _item_debug_repr(k.vt) + val_str = _item_debug_repr(v) + items.append(f"({key_str}, {val_str})") + return "dict_items([" + ", ".join(items) + "])" + + def sq_contains_impl( + self, tx: "InstructionTranslatorBase", item: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/dictobject.c#L6433-L6451 + from ..utils import iter_contains + + if not is_hashable(item): + raise_type_error(tx, f"unhashable type: '{item.python_type_name()}'") + + # Fast path: if item is a known (key, value) pair, use O(1) dict lookup. + if isinstance(item, variables.TupleVariable) and len(item.items) == 2: + key, val = item.items + key_ht = HashableTracker(key) + if key_ht not in self.dv_dict.items: + return VariableTracker.build(tx, False) + stored = self.dv_dict.items[key_ht] + # dictitems_contains: PyObject_RichCompareBool(found, value, Py_EQ) + # on the stored value, so a value whose __eq__ raises propagates. + return generic_richcompare_bool(tx, stored, val, "__eq__") + + return iter_contains(self.view_items_vt, item, tx) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + # dictview_richcompare: accepts set/frozenset and dict_keys/dict_items. + # https://github.com/python/cpython/blob/e76aa128fe/Objects/dictobject.c#L5952-L6010 + # Uses a polyfill with len() and ``in`` so that Dynamo traces through + # sq_length/sq_contains, matching CPython's use of PyObject_Size and + # PySequence_Contains. + from .builder import SourcelessBuilder + + if not _is_set_or_dictview(other): + return ConstantVariable.create(NotImplemented) + return SourcelessBuilder.create( + tx, polyfills.dictview_richcompare + ).call_function( + tx, + [ + SourcelessBuilder.create(tx, cmp_name_to_op_mapping[op]), + self, + other, + ], + {}, + ) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + from .iter import DictItemsIterator + + if self.dv_dict.source and not is_constant_source(self.dv_dict.source): + tx.output.guard_on_key_order.add(self.dv_dict.source) + return DictItemsIterator(self.dv_dict.items) + + +kV = HashableTracker | str + + +class SideEffectsProxyDict(collections.abc.MutableMapping[kV, VariableTracker]): + """ + A proxy dict that allows us to track mutations to the dict using side + effects table as storage. + """ + + @staticmethod + def get_example_value_dict(vt: VariableTracker) -> dict[str, object]: + if istype(vt, variables.NestedUserFunctionVariable): + # NestedUserFunctionVariable is created with MAKE_FUNCTION and its + # __dict__ starts empty. Any mutation will actually be recorded in + # the side effects table. + return {} + elif isinstance(vt, variables.LocalGeneratorFunctionVariable): + return SideEffectsProxyDict.get_example_value_dict(vt.vt) + elif istype(vt, variables.ExceptionVariable): + # Synthetic exceptions created during tracing have no backing + # Python object; their __dict__ starts empty and any custom + # attribute is recorded in the side effects table. + return {} + else: + value = vt.get_real_python_backed_value() + if value is not NO_SUCH_SUBOBJ: + if isinstance(vt, variables.UserDefinedObjectVariable): + return vt._getattr_static("__dict__") # type: ignore[bad-return] + else: + return object.__getattribute__(value, "__dict__") + else: + unimplemented( + gb_type="unsupported variable type for __dict__ access", + context=f"VariableTracker type: {type(vt)}", + explanation=f"Dynamo does not know how to get __dict__ from {type(vt)}", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + @staticmethod + def get_value___dict__( + tx: "InstructionTranslatorBase", vt: VariableTracker + ) -> dict[str, VariableTracker]: + # GENERIC_SETATTR on "__dict__" means the whole instance dict was + # replaced through the __dict__ getset descriptor (obj.__dict__ = ...). + # Per-key obj.__dict__[name] mutations are tracked as INSTANCE_DICT. + if isinstance( + vt, variables.UserDefinedObjectVariable + ) and tx.output.side_effects.has_pending_mutation_of_attr( + vt, "__dict__", AttrMutationKind.GENERIC_SETATTR + ): + dict_vt = tx.output.side_effects.load_attr(vt, "__dict__") + if isinstance(dict_vt, ConstDictVariable): + result = {} + for key, value in dict_vt.items.items(): + try: + key_value = key.vt.as_python_constant() + except NotImplementedError: + unimplemented( + gb_type="non-constant key in object __dict__", + context=f"key={key.vt}", + explanation="Dynamo expects object __dict__ replacement keys to be constants.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + if not isinstance(key_value, str): + unimplemented( + gb_type="non-string key in object __dict__", + context=f"key={key_value!r}", + explanation="Dynamo expects object __dict__ keys to be strings.", + hints=[*graph_break_hints.USER_ERROR], + ) + result[key_value] = value + return result + # Other replacement forms are not materialized here yet. Leave + # them on the normal example-value path until Dynamo models their + # contents explicitly. + + example_value_dict = SideEffectsProxyDict.get_example_value_dict(vt) + + return { + key: VariableTracker.build( + tx, + value, + source=vt.source + and DictGetItemSource(AttrSource(vt.source, "__dict__"), key), + ) + for key, value in example_value_dict.items() + } + + def __init__(self, item: VariableTracker, tx: "InstructionTranslatorBase") -> None: + self.item = item + self.side_effects = tx.output.side_effects + self.item_dict = self.get_value___dict__(tx, item) + + def _maybe_unwrap_key(self, key: kV) -> str: + Hasher = HashableTracker + return key.vt.as_python_constant() if istype(key, Hasher) else key + + def side_effects_table(self) -> dict[str, VariableTracker]: + return { + name: value + for name, value in self.side_effects.store_attr_mutations.get( + self.item, {} + ).items() + if self.side_effects.has_pending_mutation_of_attr( + self.item, name, AttrMutationKind.INSTANCE_DICT + ) + } + + def __getitem__(self, key: kV) -> VariableTracker: + name = self._maybe_unwrap_key(key) + if self.side_effects.has_pending_mutation_of_attr( + self.item, name, AttrMutationKind.INSTANCE_DICT + ): + return self.side_effects.load_attr(self.item, name, deleted_ok=True) + return self.item_dict[name] + + def __setitem__(self, key: kV, value: VariableTracker) -> None: + # Find a way to not hash the key using HashableTracker. CPython's + # instance __dict__ accepts arbitrary hashable keys when set via the + # mapping API (only attribute access via setattr requires str), and + # instance-dict mutations replay with object_setattr_ignore_descriptor + # (a plain __dict__ store), so a non-str constant key is fine. + name = self._maybe_unwrap_key(key) + self.side_effects.store_instance_dict_attr(self.item, name, value) + + def __delitem__(self, key: kV) -> None: + name = self._maybe_unwrap_key(key) + self.side_effects.store_instance_dict_attr( + self.item, name, variables.DeletedVariable() + ) + + def __contains__(self, key: kV) -> bool: # type: ignore[bad-override] + name = self._maybe_unwrap_key(key) + if self.side_effects.has_pending_mutation_of_attr( + self.item, name, AttrMutationKind.INSTANCE_DICT + ): + value = self.side_effects.load_attr(self.item, name, deleted_ok=True) + return not isinstance(value, variables.DeletedVariable) + return name in self.item_dict + + def __len__(self) -> int: + return sum(1 for _ in self) + + def __iter__(self) -> Iterator[HashableTracker]: + Hasher = HashableTracker + d = self.side_effects_table() + for k, v in d.items(): + if isinstance(v, variables.DeletedVariable): + continue + yield Hasher(ConstantVariable.create(k)) + + for k, v in self.item_dict.items(): + if k not in d: + yield Hasher(ConstantVariable.create(k)) + + +class DunderDictVariable(ConstDictVariable): + """represents object.__dict__""" + + @classmethod + def create( + cls, + tx: "InstructionTranslatorBase", + vt: VariableTracker, + ) -> "DunderDictVariable": + mutation = AttributeMutationExisting() if vt.source else AttributeMutationNew() + source = vt.source and AttrSource(vt.source, "__dict__") + + return cls( + vt, + tx=tx, + mutation_type=mutation, + source=source, + ) + + def __init__( + self, + vt: VariableTracker, + tx: "InstructionTranslatorBase", + **kwargs: Any, + ) -> None: + super().__init__({}, **kwargs) + self.items = SideEffectsProxyDict(vt, tx) + + def setitem(self, name: str, value: VariableTracker) -> None: + self.items[name] = value + + def delitem(self, name: str) -> None: + if not self.contains(name): + raise KeyError(name) + del self.items[name] + + def getitem(self, name: str) -> VariableTracker: + return self.items[name] + + def contains(self, name: str) -> bool: + return name in self.items + + def getitem_or_default( + self, + name: str, + default: Callable[[], VariableTracker], + ) -> VariableTracker: + if self.contains(name): + return self.getitem(name) + else: + value = default() + self.items[name] = value + return value + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "copy": + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + return ConstDictVariable( + dict(self.items), mutation_type=ValueMutationNew(), source=None + ) + return super().call_method(tx, name, args, kwargs) + + # Mutations to __dict__ are tracked through side effects (SideEffectsProxyDict), + # so we don't need to install guards. Guard installation is overridden to no-op. + def install_dict_keys_match_guard(self) -> None: + pass + + def install_dict_contains_guard( + self, tx: "InstructionTranslatorBase", args: list[VariableTracker] + ) -> None: + pass diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/distributed.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..d0dcc3ea592f17a1a4e698fd2bfc4e4b96568cfc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/distributed.py @@ -0,0 +1,282 @@ +""" +Distributed computing variable tracking classes for PyTorch Dynamo. + +This module implements variable tracking for distributed computing components: +- Process Groups (for collective communication) +- Device Meshes (for distributed tensor sharding) +- Placement Types (for specifying distribution strategies) +- Distributed Tensors and their operations +- Backward hooks for distributed module operations + +These classes are responsible for tracking distributed operations during graph +compilation while maintaining proper guards and handling distributed-specific +behaviors. They ensure correct handling of distributed components like process +groups, device meshes, and placement strategies while preserving proper semantics +for distributed tensor operations in the compiled code. + +The implementation provides special handling for distributed package availability +checks and proper tracking of distributed state and operations across processes. +""" + +import functools +import inspect +from typing import Any, TYPE_CHECKING + +import torch +from torch.fx.experimental._backward_state import BackwardState + +from .. import compiled_autograd +from .._trace_wrapped_higher_order_op import trace_wrapped +from ..exc import unimplemented +from ..external_utils import call_module_hooks_from_backward_state +from ..guards import GuardBuilder, install_guard +from ..source import AttrSource +from .base import GetSet, Method, VariableTracker + + +if TYPE_CHECKING: + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + +class DistributedVariable(VariableTracker): + """ + The base distributed variable that encapsulates common methods + for the distributed objects (i.e. ProcessGroup, DeviceMesh, etc.). + Concrete distributed objects could inherit this class and add object + specific logic. + + i.e. It provides the check on the distributed package existence + and hold the tracking value for the corresponding distributed object. + """ + + def __init__(self, value: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + if not DistributedVariable.is_available(): + unimplemented( + gb_type="torch.distributed package is not available!", + context="", + explanation="The PyTorch package doesn't include torch.distributed when building from source.", + hints=[ + "Set USE_DISTRIBUTED=1 to enable it when building PyTorch from source." + ], + ) + self.value = value + + def python_type(self) -> type: + return type(self.value) + + @staticmethod + def is_available() -> bool: + # check if the distributed package is available or not + return torch.distributed.is_available() + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + return hash(self.value), False + + def tp_richcompare_impl(self, tx, other, op): + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + +def is_from_local(value: object) -> bool: + if not DistributedVariable.is_available(): + return False + from torch.distributed.tensor import DTensor + + return inspect.isfunction(value) and value is DTensor.from_local + + +def is_constant_pg_functions(value: object) -> bool: + if not DistributedVariable.is_available(): + return False + + from torch.distributed.distributed_c10d import ( + _get_group_size_by_name, + _get_group_tag, + _rank_not_in_group, + _resolve_group_name_by_ranks_and_tag, + get_process_group_ranks, + ) + + constant_processgroup_functions = [ + _get_group_size_by_name, + _get_group_tag, + _rank_not_in_group, + get_process_group_ranks, + _resolve_group_name_by_ranks_and_tag, + ] + + return inspect.isfunction(value) and value in constant_processgroup_functions + + +class WorldMetaClassVariable(DistributedVariable): + """ + Tracks torch.distributed.GroupMember and torch.distributed.group, which are + instances of the metaclass _WorldMeta. + """ + + @classmethod + def is_group_member_type(cls, value: object) -> bool: + if not cls.is_available(): + return False + + from torch.distributed.distributed_c10d import _WorldMeta + + return type(value) is _WorldMeta + + def python_type(self) -> type: + return type(self.value) + + # dynamo-internal getset (not real CPython descriptors): _WorldMeta + # exposes the WORLD and NON_GROUP_MEMBER process-group sentinels. + def _world_getset(self, tx: "InstructionTranslatorBase") -> VariableTracker: + if not self.source: + raise AssertionError( + "WorldMetaClassVariable requires a source for WORLD attribute" + ) + source = AttrSource(base=self.source, member="WORLD") + install_guard(source.make_guard(GuardBuilder.ID_MATCH)) + return VariableTracker.build(tx, self.value.WORLD, source) + + def _non_group_member_getset( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker: + if not self.source: + raise AssertionError( + "WorldMetaClassVariable requires a source for NON_GROUP_MEMBER attribute" + ) + source = AttrSource(base=self.source, member="NON_GROUP_MEMBER") + install_guard(source.make_guard(GuardBuilder.ID_MATCH)) + return VariableTracker.build(tx, self.value.NON_GROUP_MEMBER, source) + + tp_getset = { + "WORLD": GetSet(_world_getset, None), + "NON_GROUP_MEMBER": GetSet(_non_group_member_getset, None), + } + + +class BackwardHookVariable(VariableTracker): + """ + Handles torch.utils.hooks.BackwardHook for module-level backward + hooks. + """ + + @staticmethod + def create( + tx: "InstructionTranslatorBase", + module: VariableTracker, + user_hooks: VariableTracker, + user_pre_hooks: VariableTracker, + ) -> "BackwardHookVariable": + if not compiled_autograd.compiled_autograd_enabled: + unimplemented( + gb_type="Module-level backwards hooks require compiled autograd.", + context="", + explanation="", + hints=[ + "Enable compiled autograd by setting torch._dynamo.config.compiled_autograd = True." + ], + ) + + def _in_graph_bw_hooks( + bw_state: BackwardState, + ) -> torch.utils.hooks.BackwardHook: + """ + Rather than installing the user hooks in the graph (which + don't survive AotAutograd), we install hooks that will call + trace_wrapped in the backward pass that CompiledAutograd + can turn into actual hook calls. + """ + return torch.utils.hooks.BackwardHook( + None, + ( + functools.partial( + trace_wrapped, + fn=call_module_hooks_from_backward_state, + bw_state=bw_state, + hooks_name=user_hooks_name, + module_name=module_name, + ), + ), + ( + functools.partial( + trace_wrapped, + fn=call_module_hooks_from_backward_state, + bw_state=bw_state, + hooks_name=user_pre_hooks_name, + module_name=module_name, + ), + ), + ) + + module_name, bw_state_proxy = tx.output.add_backward_state_hook(module, "mod") + user_pre_hooks_name, _ = tx.output.add_backward_state_hook(user_pre_hooks) + user_hooks_name, _ = tx.output.add_backward_state_hook(user_hooks) + proxy = tx.output.create_proxy( + "call_function", + _in_graph_bw_hooks, + (bw_state_proxy,), + {}, + ) + proxy.node.meta["example_value"] = torch.utils.hooks.BackwardHook(None, (), ()) + return BackwardHookVariable(proxy, module, user_hooks, user_pre_hooks) + + def __init__( + self, + proxy: torch.fx.Proxy, + module: VariableTracker, + user_hooks: VariableTracker, + user_pre_hooks: VariableTracker, + **options: Any, + ) -> None: + super().__init__(**options) + self.proxy = proxy + self.module = module + self.user_hooks = user_hooks + self.user_pre_hooks = user_pre_hooks + + def as_proxy(self) -> torch.fx.Proxy: + return self.proxy + + def python_type(self) -> type: + return torch.utils.hooks.BackwardHook + + def setup_input_hook( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self._setup_hook(tx, "setup_input_hook", *args, **kwargs) + + def setup_output_hook( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self._setup_hook(tx, "setup_output_hook", *args, **kwargs) + + tp_methods = { + "setup_input_hook": Method(setup_input_hook), + "setup_output_hook": Method(setup_output_hook), + } + + def _setup_hook( + self, + tx: "InstructionTranslatorBase", + hook_method_name: str, + args: VariableTracker, + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_method", + hook_method_name, + (self.as_proxy(), args.as_proxy()), + {}, + ), + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/functions.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/functions.py new file mode 100644 index 0000000000000000000000000000000000000000..1202d8e11bde3d75cc50096a354fe28efb4bc5bd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/functions.py @@ -0,0 +1,4899 @@ +""" +Function-related variable tracking classes for Dynamo's symbolic execution. + +This module contains classes that track different types of functions during graph +compilation, including: +- User-defined functions and methods +- Built-in functions and methods +- Wrapped functions (e.g. from decorators) +- Special function types (e.g. functools.partial) +- Triton kernels and related function types + +These classes are responsible for: +- Tracking function calls and their arguments +- Managing function closures and cell variables +- Handling function attributes and special methods +- Maintaining guards for function identity and closure contents +- Supporting function inlining and specialization +- Enabling proper symbolic execution of different function types + +The variable trackers here work together with the rest of Dynamo to enable +accurate graph capture while handling Python's various function-related behaviors. +""" + +import _collections # type: ignore[import-not-found] +import builtins +import collections +import functools +import importlib.metadata +import importlib.util +import inspect +import itertools +import logging +import os +import re +import sys +import traceback +import types +import typing +from collections.abc import Callable, Sequence +from types import CellType, FunctionType +from typing import Any, cast, Literal, Optional, TYPE_CHECKING, TypeVar +from typing_extensions import Never +from weakref import WeakKeyDictionary + +import torch +from torch._dynamo.exc import get_stack_above_dynamo +from torch._guards import Source +from torch.utils._pytree import is_namedtuple_class + +from .. import config, graph_break_hints, polyfills, variables +from ..bytecode_transformation import create_call_function, create_rot_n, is_generator +from ..exc import ( + format_frame_info, + get_dynamo_observed_exception, + InfiniteGeneratorError, + ObservedException, + ObservedGeneratorExit, + ObservedUserStopIteration, + raise_observed_exception, + raise_type_error, + raise_value_error, + StepUnsupported, + unimplemented, + Unsupported, +) +from ..guards import GuardBuilder, install_guard +from ..source import ( + AttrSource, + CellContentsSource, + ClosureSource, + ConstantSource, + DefaultsSource, + GetItemSource, + ImportSource, + SkipGuardSource, + TypeMROSource, + TypeSource, +) +from ..utils import ( + check_constant_args, + check_unspec_or_constant_args, + FrameState, + identity, + is_function, + is_lru_cache_wrapper_trace_without_warning_allowed, + is_tensor_base_attr_getter, + is_wrapper_or_member_descriptor, + istype, + make_cell, + unpack_iterable, +) +from .base import ( + AsPythonConstantNotImplementedError, + AttributeMutationNew, + GetSet, + getset_build, + getset_read, + Member, + Method, + NO_SUCH_SUBOBJ, + ValueMutationNew, + VariableTracker, +) +from .constant import ConstantVariable +from .user_defined import UserDefinedObjectVariable + + +try: + from torch.distributed.fsdp._fully_shard import _fsdp_param_group +except ModuleNotFoundError: + _fsdp_param_group = None # type: ignore[assignment] + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.symbolic_convert import ( + InliningGeneratorInstructionTranslator, + InliningInstructionTranslator, + InstructionTranslatorBase, + ) + from torch._dynamo.variables.ctx_manager import ContextWrappingVariable + from torch._higher_order_ops.triton_kernel_wrap import ( + TritonGridType, + TritonKernelType, + ) + + from .lists import BaseListVariable, ListVariable + from .tensor import TensorVariable + + +_F = TypeVar("_F", bound=Callable[..., Any]) +CO_VARARGS = 0x04 +CO_VARKEYWORDS = 0x08 +_SUPPORTED_TREE_MAP_KWARGS = frozenset({"namespace", "none_is_leaf", "is_leaf"}) +_TREE_MAP_ONLY_SUPPORTED_KWARGS = frozenset({"is_leaf"}) + +PT2_ISSUE_TRACKER_URL = "https://github.com/pytorch/pytorch/issues/new?&labels=oncall%3A+pt2&projects=&template=pt2-bug-report.yml" + +# Module-level cache keyed by the function object +_spec_cache: WeakKeyDictionary[Any, Any] = WeakKeyDictionary() + + +# Raised when get_function() cannot convert a nested function to a Python function. +class ClosureConversionError(NotImplementedError): + pass + + +@functools.lru_cache +def get_pytree_SUPPORTED_NODES_source() -> AttrSource: + # Cached, so callers are responsible for installing the ID_MATCH guard on the + # embedded ImportSource("torch") themselves. + return AttrSource( + AttrSource(AttrSource(ImportSource("torch"), "utils"), "_pytree"), + "SUPPORTED_NODES", + ) + + +class FunctionSpec: + def __init__(self, func: FunctionType) -> None: + code = func.__code__ + vn = code.co_varnames + + self.posonly_count = code.co_posonlyargcount + self.arg_count = code.co_argcount + self.kwonly_count = code.co_kwonlyargcount + + self.posonly_names = vn[: self.posonly_count] + self.pos_or_kw_names = vn[self.posonly_count : self.arg_count] + self.all_pos_names = self.posonly_names + self.pos_or_kw_names + self.kwonly_names = vn[self.arg_count : self.arg_count + self.kwonly_count] + + off = self.arg_count + self.kwonly_count + self.varargs_name = vn[off] if code.co_flags & CO_VARARGS else None + off += 1 if self.varargs_name else 0 + self.varkw_name = vn[off] if code.co_flags & CO_VARKEYWORDS else None + + def update_defaults(self, func: FunctionType) -> None: + # Defaults can change from function call to function call. So re-update + # them on every call. + self.defaults = func.__defaults__ or () + self.kwdefaults = func.__kwdefaults__ or {} + + # Map positional-default names → their index in self.defaults + self.pos_default_map = dict( + zip(self.all_pos_names[-len(self.defaults) :], range(len(self.defaults))) + ) + + +def _get_spec(func: FunctionType) -> FunctionSpec: + spec = _spec_cache.get(func) + if spec is None: + spec = FunctionSpec(func) + _spec_cache[func] = spec + return spec + + +class BindArgsTypeError(TypeError): + pass + + +def bind_args_cached( + func: FunctionType, + tx: "InstructionTranslatorBase", + fn_source: Source | None, + args: Sequence[Any], + kwargs: dict[str, Any], +) -> dict[str, VariableTracker]: + spec = _get_spec(func) + + # Fast path: simple positional-only, no defaults, no varargs/varkw + # This is the common case for small utility functions called repeatedly. + if ( + len(args) == spec.arg_count + and not func.__defaults__ + and not kwargs + and not spec.varargs_name + and not spec.varkw_name + and not spec.kwonly_names + ): + return { + name: wrap_bound_arg(tx, args[i]) + for i, name in enumerate(spec.all_pos_names) + } + + # Full path with all features + spec.update_defaults(func) + ba = {} + rem_kw = dict(kwargs) + guarded_pos_defaults_len = False + + # 1) Bind all positional (pos-only + pos-or-kw) + for i, name in enumerate(spec.all_pos_names): + if i < len(args): + ba[name] = wrap_bound_arg(tx, args[i]) + elif name in rem_kw and ( + # `kwargs` can have the same key as a pos-only arg `name`. + # If this case happens, we should not consume the `name` here and + # keep it in `kwargs`: + # >>> def fn(a, /, **kwargs): return (a, kwargs) + # >>> fn(1, a=2) + # (1, {'a': 2}) + name not in spec.posonly_names + ): + ba[name] = wrap_bound_arg(tx, rem_kw.pop(name)) + elif name in spec.pos_default_map: + idx = spec.pos_default_map[name] + if fn_source and not guarded_pos_defaults_len: + # The parameter-to-default mapping depends on __defaults__ + # length; guard it without wrapping every default value. + install_guard( + AttrSource(fn_source, "__defaults__").make_guard( + GuardBuilder.SEQUENCE_LENGTH + ) + ) + guarded_pos_defaults_len = True + default_source = None + if fn_source and not ( + ConstantVariable.is_literal(spec.defaults[idx]) + and config.skip_guards_on_constant_func_defaults + ): + default_source = DefaultsSource(fn_source, idx) + ba[name] = wrap_bound_arg(tx, spec.defaults[idx], default_source) + else: + raise BindArgsTypeError(f"missing required positional argument: {name}") + + # 2) *args + extra = args[len(spec.all_pos_names) :] + if spec.varargs_name: + ba[spec.varargs_name] = wrap_bound_arg(tx, tuple(extra)) + elif extra: + raise BindArgsTypeError( + f"Too many positional arguments: got {len(args)}, expected {len(spec.all_pos_names)}" + ) + + # 3) Keyword-only + for name in spec.kwonly_names: + if name in rem_kw: + ba[name] = wrap_bound_arg(tx, rem_kw.pop(name)) + elif name in spec.kwdefaults: + kwdefault_source = None + if fn_source: + kwdefault_source = DefaultsSource(fn_source, name, is_kw=True) + ba[name] = wrap_bound_arg(tx, spec.kwdefaults[name], kwdefault_source) + else: + raise BindArgsTypeError(f"Missing required keyword-only argument: {name}") + + # 4) **kwargs + if spec.varkw_name: + ba[spec.varkw_name] = wrap_bound_arg(tx, rem_kw) + elif rem_kw: + raise BindArgsTypeError(f"Unexpected keyword arguments: {list(rem_kw)}") + + return ba + + +def wrap_bound_arg( + tx: "InstructionTranslatorBase", val: Any, source: Source | None = None +) -> VariableTracker: + # Source propagation is best effort since not every object we encounter has a source to begin with. + if isinstance(val, VariableTracker): + return val + elif not source: + return VariableTracker.build(tx, val) + else: + # Create a lazy variable to avoid guarding on __defaults__ unless really + # needed. + return variables.LazyVariableTracker.create(val, source, tx=tx) + + +def wrap_args_kwargs(tx: "InstructionTranslatorBase", result: dict[str, Any]) -> None: + for k, v in list(result.items()): + if isinstance(v, (tuple, dict)): + # args/kwargs + result[k] = wrap_bound_arg(tx, v) + + +def init_cellvars( + parent: "InstructionTranslatorBase", + result: dict[str, VariableTracker], + code: types.CodeType, +) -> None: + """ + Update `result` to add mapping from local name to new cells created + directly by `code`, or update SideEffects in `parent` if a local cell is + already in `result` (cell argument). + """ + side_effects = parent.output.side_effects + + for name in code.co_cellvars: + new_cell = side_effects.track_cell_new() + if name in result: + # This handles when a function argument is a cell (e.g., captured by + # a nested func). See `MAKE_CELL` bytecode for more info. + side_effects.store_cell(new_cell, result.pop(name)) + result[name] = new_cell + + +def _create_nested_fn( + code: types.CodeType, + f_globals: dict[str, Any], + name: str, + defaults: tuple[object, ...] | None, + closure: tuple[CellType] | None, + kwdefaults: dict[str, Any] | None, + annotations: dict[str, Any] | None, +) -> types.FunctionType: + from types import FunctionType + + func = FunctionType(code, f_globals, name, defaults, closure) + func.__kwdefaults__ = kwdefaults + + if isinstance(annotations, tuple): + from itertools import pairwise + + annotations = dict(pairwise(annotations)) + + # TypeError: __annotations__ must be set to a dict object + if not (annotations is None or isinstance(annotations, dict)): + raise AssertionError( + f"annotations must be None or a dict, got {type(annotations)}" + ) + func.__annotations__ = annotations # type: ignore[assignment] + + return func + + +fn_known_dunder_attrs = { + "__annotations__", + "__builtins__", + "__closure__", + "__code__", + "__defaults__", + "__doc__", + "__globals__", + "__kwdefaults__", + "__name__", + "__module__", +} + + +def fn_getattro_impl( + tx: "InstructionTranslatorBase", fn: object, source: Source | None, name: str +) -> VariableTracker: + source = source and AttrSource(source, name) + + if source and name == "__annotations__": + # We get a large number of silly guards from annotations from inspect + # module. Changing annotations is rare, and it impacting the extracted + # graph is even rarer. So skip guards. + source = SkipGuardSource(source) + + subobj = None + try: + subobj = inspect.getattr_static(fn, name) + except AttributeError: + # function does not have a __getattr__ or __getattribute__ method, + # so we can safely assume that this attribute is absent + raise_observed_exception(AttributeError, tx) + + # Special handling for known dunder attributes + # TODO(guilhermeleobas): this check should go through fn.__dict__ first as + # functools.partial can override it + if name in fn_known_dunder_attrs: + subobj = getattr(fn, name) + if source: + return variables.LazyVariableTracker.create(subobj, source, tx=tx) + return VariableTracker.build(tx, subobj) + + +class BaseUserFunctionVariable(VariableTracker): + # funcobject.c func_annotations: a dedicated slot, NOT a __dict__ entry. + # Materialized per-instance once accessed/assigned. + annotations: "VariableTracker | None" = None + + def tp_richcompare_impl(self, tx, other, op): + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def self_args(self) -> list[VariableTracker]: + return [] + + def get_source(self) -> Source | None: + return self.source + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + # ref: https://github.com/python/cpython/blob/v3.13.3/Objects/funcobject.c + return VariableTracker.build(tx, repr(self.as_python_constant())) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "__setattr__": + if args[0].is_constant_match("__annotations__"): + self.annotations = args[1] + return ConstantVariable.create(None) + return self.get_dict_vt(tx).call_method( + tx, "__setitem__", list(args), kwargs + ) + elif name == "__delattr__": + if args[0].is_constant_match("__annotations__"): + self.annotations = None + return ConstantVariable.create(None) + return self.get_dict_vt(tx).call_method(tx, "__delitem__", list(args), {}) + return super().call_method(tx, name, list(args), kwargs) + + def get_filename(self) -> str: + return self.get_code().co_filename + + def get_name(self) -> str: + return self.get_code().co_name + + def get_qualname(self) -> str: + if sys.version_info >= (3, 11): + return self.get_code().co_qualname + else: + return self.get_name() + + def get_doc(self) -> str | None: + # stored in code.co_consts[0] + return self.get_code().co_consts[0] + + def get_globals(self) -> dict[str, Any]: + raise NotImplementedError + + def get_code(self) -> types.CodeType: + raise NotImplementedError + + def has_self(self) -> bool: + raise NotImplementedError + + def get_function(self) -> types.FunctionType: + raise NotImplementedError + + def get_module(self) -> str: + return self.get_globals()["__name__"] + + def _get_defaults(self, tx: "InstructionTranslatorBase") -> VariableTracker: + d = getattr(self, "defaults", None) + return d if d is not None else ConstantVariable.create(None) + + def _get_named_attr( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + fn_dict = self.get_dict_vt(tx) + if fn_dict.contains(name): + return fn_dict.getitem(name) + val = getattr(self, f"get_{name[2:-2]}")() + return ConstantVariable.create( + val, source=self.source and AttrSource(self.source, name) + ) + + def _get_annotations(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # func_get_annotations lazily creates and stores an empty dict. The dict + # is a fresh value (ValueMutationNew), so it must carry no source. + if self.annotations is None: + self.annotations = variables.ConstDictVariable( + {}, mutation_type=ValueMutationNew() + ) + return self.annotations + + def _get_type_params(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.get_dict_vt(tx).getitem_or_default( + "__type_params__", + lambda: variables.TupleVariable([], mutation_type=ValueMutationNew()), + ) + + def _get_kwdefaults(self, tx: "InstructionTranslatorBase") -> VariableTracker: + d = getattr(self, "kwdefaults", None) + return d if d is not None else ConstantVariable.create(None) + + def _get_closure(self, tx: "InstructionTranslatorBase") -> VariableTracker: + c = getattr(self, "closure", None) + return c if c is not None else ConstantVariable.create(None) + + tp_getset = { + "__defaults__": GetSet(_get_defaults, None), + "__kwdefaults__": GetSet(_get_kwdefaults, None), + "__name__": GetSet(lambda s, tx: s._get_named_attr(tx, "__name__")), + "__qualname__": GetSet(lambda s, tx: s._get_named_attr(tx, "__qualname__")), + "__code__": GetSet(lambda s, tx: s._get_named_attr(tx, "__code__")), + "__dict__": GetSet(lambda s, tx: s.get_dict_vt(tx)), + "__annotations__": GetSet(_get_annotations), + "__type_params__": GetSet(_get_type_params), + } + tp_members = { + "__doc__": Member(lambda s, tx: s._get_named_attr(tx, "__doc__")), + "__module__": Member(lambda s, tx: s._get_named_attr(tx, "__module__")), + "__closure__": Member(_get_closure), + } + + def lookup_instance_dict( + self, tx: "InstructionTranslatorBase", name: str + ) -> "VariableTracker | None": + # Arbitrary attributes set on a function object live in its __dict__ + # (tp_dictoffset). Resolve them at the instance-dict step so getattr + # finds them before call_getattr_fallback (which raises). Known dunder + # slots are handled earlier via tp_getset/tp_members and never reach here. + try: + fn = self.get_function() + except NotImplementedError: + return None + fn_dict = getattr(fn, "__dict__", None) + if not fn_dict or name not in fn_dict: + return None + source = self.get_source() + source = AttrSource(source, name) if source is not None else None + if source is not None: + return variables.LazyVariableTracker.create(fn_dict[name], source, tx=tx) + return VariableTracker.build(tx, fn_dict[name]) + + def call_getattr_fallback( + self, tx: "InstructionTranslatorBase", name: str + ) -> "VariableTracker | None": + # Functions have no __getattr__; reaching the fallback means the + # attribute genuinely does not exist (CPython + # _PyObject_GenericGetAttrWithDict step 7 raises AttributeError). + raise_observed_exception(AttributeError, tx, args=[name]) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Ignore patch_track_step_called from torch/optim/lr_scheduler.py - it just patches + # the optimizer.step method and we don't need to trace it + if ( + self.get_name() == "patch_track_step_called" + and self.get_filename().endswith("torch/optim/lr_scheduler.py") + ): + return ConstantVariable.create(None) + return tx.inline_user_function_return( + self, + [*self.self_args(), *args], + kwargs, + allow_nested_graph_breaks=True, + ) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + se_result = self._hasattr_check_side_effects(tx, name) + if se_result is not None: + return se_result + + result = False + + if name in fn_known_dunder_attrs or name == "__dict__": + result = True + else: + try: + result = hasattr(self.get_function(), name) # type: ignore[attr-defined] + except NotImplementedError: + result = False + return VariableTracker.build(tx, result) + + def closure_vars( + self, tx: "InstructionTranslatorBase" + ) -> dict[str, VariableTracker]: + return {} + + # Override to set whether or not nested graph breaks should be allowed + # if we create an inlining tx for this BaseUserFunctionVariable. + # See symbolic_convert.py for where this function is called. + def should_allow_nested_graph_breaks(self) -> bool: + return True + + +class UserFunctionVariable(BaseUserFunctionVariable): + """Some unsupported user-defined global function""" + + # PyFunction_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/funcobject.c#L1046 + _cpython_type = types.FunctionType + + _nonvar_fields = { + "fn", + "is_constant", + *BaseUserFunctionVariable._nonvar_fields, + } + + _TREE_MAP_MODULES = frozenset( + { + "optree", + "optree.ops", + "torch.utils._pytree", + "torch.utils._cxx_pytree", + } + ) + + @classmethod + def create_with_source(cls, value: Any, source: Any) -> "UserFunctionVariable": + install_guard(source.make_guard(GuardBuilder.CLOSURE_MATCH)) + return cls(value, source=source) + + def get_value_for_setattr(self) -> object | None: + return self.fn + + def __init__( + self, + fn: types.FunctionType | torch.jit.ScriptFunction, # type: ignore[type-arg] + is_constant: bool = False, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if getattr(fn, "_dynamo_marked_constant", False): + # This method should be treated as a constant for the purposes of compilation + self.is_constant = True + else: + self.is_constant = False + + # TODO putting this here to avoid duplication, because we could hit this + # from several paths (e.g., SuperVariable or `tp_getattro_impl`s). + if not isinstance(fn, (types.FunctionType, torch.jit.ScriptFunction)): + unimplemented( + gb_type="can't handle functions not implemented in python ", + context=f"{fn}", + explanation="Dynamo can only handle functions defined in python", + hints=[ + "Move usage of this function out of `torch.compile` region", + *graph_break_hints.INFERENCE_MODE, + ], + ) + # TODO(anijain2305) - Replace directly calling UserFunctionVariable with + # VariableBuilder, which handles the wrapping of _torchdynamo_inline. + # unpack @torch._dynamo.optimize()(fn) wrapped function + fn = inspect.getattr_static(fn, "_torchdynamo_inline", fn) + self.fn = fn + + def as_python_constant(self) -> Any: + if istype(self, UserFunctionVariable): + return self.fn + # subclasses (such as methods) usually aren't a constant + return super().as_python_constant() + + def reconstruct_pycode(self, codegen): + if self.source: + return self.source.reconstruct_pycode(codegen) + raise NotImplementedError( + "Python codegen not implemented for sourceless UserFunctionVariable" + ) + + def get_real_python_backed_value(self) -> Any: + if istype(self, UserFunctionVariable): + return self.fn + return super().get_real_python_backed_value() + + def self_args(self) -> list[VariableTracker]: + return [] + + def get_function(self) -> types.FunctionType: + return self.fn + + def get_code(self) -> types.CodeType: + return self.fn.__code__ + + def python_type(self) -> type: + return types.FunctionType + + def has_self(self) -> bool: + return getattr(self.fn, "__self__", None) is not None + + def get_globals(self) -> dict[str, Any]: + return self.fn.__globals__ + + def should_allow_nested_graph_breaks(self) -> bool: + from torch._dynamo.trace_rules import ( + BUILTIN_INLINE_WHEN_CALLED, + is_ngb_suppressed_inline, + ) + + filename = self.get_filename() + if any(filename.startswith(d) for d in BUILTIN_INLINE_WHEN_CALLED): + return False + if is_ngb_suppressed_inline(filename): + return False + return True + + def get_source(self) -> Source: + source = self.source + + if source and isinstance(self, variables.UserMethodVariable): + source = self.source_fn # type: ignore[assignment] + return source # type: ignore[return-value] + + def bind_args( + self, + parent: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> dict[str, VariableTracker]: + """ + Assume `args` and `kwargs` are VariableTracker arguments for a call to + this function, create new bindings for initial locals. + """ + if self.is_constant: + raise AssertionError( + "bind_args should not be called on a constant function" + ) + + fn: types.FunctionType = self.fn + + if not isinstance(fn, FunctionType): + raise TypeError("Only supports regular Python functions.") + root_tx = parent.output.root_tx + + source = self.get_source() + result = bind_args_cached(fn, root_tx, source, args, kwargs) # type: ignore[arg-type] + + init_cellvars(parent, result, fn.__code__) + closure = self.fn.__closure__ or () + if len(closure) != len(self.fn.__code__.co_freevars): + raise AssertionError( + f"closure length {len(closure)} does not match " + f"co_freevars length {len(self.fn.__code__.co_freevars)}" + ) + for idx, name, cell in zip( + itertools.count(), self.fn.__code__.co_freevars, closure + ): + # TODO refactor these 3 branches. + side_effects = parent.output.side_effects + if cell in side_effects: + cell_var = side_effects[cell] + + elif source: + closure_cell = GetItemSource(ClosureSource(source), idx) + closure_cell_contents = CellContentsSource( + closure_cell, "cell_contents", freevar_name=name + ) + try: + contents_var = VariableTracker.build( + parent, cell.cell_contents, closure_cell_contents + ) + except ValueError: + # Cell has not yet been assigned + contents_var = variables.DeletedVariable() + cell_var = side_effects.track_cell_existing( + closure_cell, cell, contents_var + ) + + else: + # TODO figure out why source isn't available here, and whether + # we can fix that and remove this branch. + try: + contents_var = VariableTracker.build(parent, cell.cell_contents) + except ValueError: + # Cell has not yet been assigned + contents_var = variables.DeletedVariable() + cell_var = side_effects.track_cell_existing(None, cell, contents_var) + + result[name] = cell_var + + return result + + # func.__get__ binds the function to an instance via the tp_descr_get slot + # wrapper. https://github.com/python/cpython/blob/v3.13.0/Objects/funcobject.c#L1119 + def _get_dunder_get(self, tx: "InstructionTranslatorBase") -> VariableTracker: + source = self.get_source() + source = AttrSource(source, "__get__") if source is not None else None + return VariableTracker.build(tx, self.fn.__get__, source) + + def _fn_getattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + return fn_getattro_impl(tx, self.fn, self.get_source(), name) + + # A real function object backs this VT, so resolve the function slots by + # reflecting on it (fn_getattro_impl) rather than via the synthesized + # get_*-based tables inherited from BaseUserFunctionVariable (which assume + # synthesized fields like self.defaults). These win over the base entries + # under MRO-merge resolution. __dict__ inherits the base getset (get_dict_vt). + tp_getset = { + "__get__": GetSet(_get_dunder_get, None), + "__name__": GetSet(lambda s, tx: s._fn_getattr(tx, "__name__")), + "__qualname__": GetSet(lambda s, tx: s._fn_getattr(tx, "__qualname__")), + "__code__": GetSet(lambda s, tx: s._fn_getattr(tx, "__code__")), + "__defaults__": GetSet(lambda s, tx: s._fn_getattr(tx, "__defaults__")), + "__kwdefaults__": GetSet(lambda s, tx: s._fn_getattr(tx, "__kwdefaults__")), + "__annotations__": GetSet(lambda s, tx: s._fn_getattr(tx, "__annotations__")), + "__type_params__": GetSet(lambda s, tx: s._fn_getattr(tx, "__type_params__")), + } + tp_members = { + "__doc__": Member(lambda s, tx: s._fn_getattr(tx, "__doc__")), + "__module__": Member(lambda s, tx: s._fn_getattr(tx, "__module__")), + "__closure__": Member(lambda s, tx: s._fn_getattr(tx, "__closure__")), + } + + def tp_descr_get_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + owner: VariableTracker, + ) -> VariableTracker: + # Mirrors func_descr_get which calls PyMethod_New to bind + # the function to an instance. + # https://github.com/python/cpython/blob/3.13/Objects/funcobject.c#L1119 + source = obj.source and AttrSource(obj.source, self.fn.__name__) + return UserMethodVariable(self.fn, obj, source_fn=self.source, source=source) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Handle patch_dynamo_config call + if self.fn is torch._dynamo.patch_dynamo_config: + try: + args_const = [arg.as_python_constant() for arg in args] + kwargs_const = { + key: val.as_python_constant() for key, val in kwargs.items() + } + changes = torch._dynamo.patch_dynamo_config( + *args_const, **kwargs_const + ).changes + return variables.DynamoConfigPatchVariable(changes) + except AsPythonConstantNotImplementedError as e: + raise RuntimeError( + "Cannot convert patch_dynamo_config args/kwargs to constants. " + "Please fix your call to patch_dynamo_config by using simpler inputs. " + f"args: {args}, kwargs: {kwargs}" + ) from e + elif self.fn is torch._dynamo.error_on_graph_break: + try: + bound = inspect.signature(self.fn).bind(*args, **kwargs) + error_on_graph_break = bound.arguments[ + "error_on_graph_break" + ].as_python_constant() + if not isinstance(error_on_graph_break, bool): + raise AssertionError( + f"error_on_graph_break must be a bool, got {type(error_on_graph_break)}" + ) + return variables.ErrorOnGraphBreakVariable(error_on_graph_break) + except Exception as e: + raise RuntimeError( + "Improper error_on_graph_break() call. Please fix your call to error_on_graph_break(). " + f"args: {args}, kwargs: {kwargs}" + ) from e + elif self.fn is torch._dynamo.override_cudagraphs: + try: + bound = inspect.signature(self.fn).bind(*args, **kwargs) + bound.apply_defaults() + fwd = bound.arguments["fwd"] + bwd = bound.arguments["bwd"] + if isinstance(fwd, VariableTracker): + fwd = fwd.as_python_constant() + if isinstance(bwd, VariableTracker): + bwd = bwd.as_python_constant() + return variables.CudagraphOverrideVariable(fwd, bwd) + except Exception as e: + raise RuntimeError( + "Improper override_cudagraphs() call. Please fix your call to override_cudagraphs(). " + f"args: {args}, kwargs: {kwargs}" + ) from e + elif self.fn is torch._dynamo.bytecode_debugger.breakpoint: + tx.output._emit_debugger_breakpoint = True + return variables.ConstantVariable.create(None) + # Handle a `nonstrict_trace(fn)` call + elif self.fn is torch._dynamo.nonstrict_trace: + bound = inspect.signature(self.fn).bind(*args, **kwargs) + fn_var = bound.args[0] + if not isinstance(fn_var, BaseUserFunctionVariable): + typ = fn_var.python_type() + msg = f"`nonstrict_trace` expects a callable, but got value of type <{typ.__name__}>" + unimplemented( + gb_type="TypeError from user code", + context=f"call_function({self.value}, {args}, {kwargs})", # type: ignore[attr-defined] + explanation=msg, + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + if not isinstance(fn_var, UserFunctionVariable): + fn_name = fn_var.get_name() + msg = f"Applying `nonstrict_trace` to function <{fn_name}>; however, `nonstrict_trace` currently requires the function to be defined outside `torch.compile` region." + unimplemented( + gb_type="Limitation of `nonstrict_trace", + context=f"{self}", + explanation=msg, + hints=[ + f"make sure definition of {fn_name} is outside ", + "`torch.compile` region", + ], + ) + + fn = fn_var.fn + return variables.TorchInGraphFunctionVariable( + fn, kind=variables.torch.AllowInGraphKind.NONSTRICT_TRACE + ) + + if self.is_constant: + return invoke_and_store_as_constant( + tx, self.fn, self.get_name(), args, kwargs + ) + + if ( + not tx.output.current_tracer.unsafe_allow_externally_visible_side_effects + and self.fn + is torch._dynamo.utils._disable_side_effect_safety_checks_for_current_subtracer + ): + with torch._dynamo.side_effects.allow_externally_visible_side_effects_in_subtracer( + tx + ): + return super().call_function(tx, args, kwargs) + + if ( + getattr(tx.output.current_tracer, "description", None) + == "torch.utils.checkpoint.checkpoint" + and not tx.output.current_tracer.allow_side_effects_in_hop + ): + try: + from torch.distributed.fsdp._fully_shard._fsdp_state import FSDPState + except Exception: + FSDPState = None # type: ignore[assignment, misc] + if FSDPState is not None and self.fn in [ + FSDPState._pre_forward, + FSDPState._post_forward, + ]: + with torch._dynamo.side_effects.allow_side_effects_in_hop(tx): + return super().call_function(tx, args, kwargs) + + tree_map_result = self._maybe_call_tree_map_fastpath(tx, args, kwargs) + if tree_map_result is not None: + return tree_map_result + + return super().call_function(tx, args, kwargs) + + def _maybe_call_tree_map_fastpath( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker | None: + rewrite = self._rewrite_tree_map_only_call(tx, args, kwargs) + if rewrite is not None: + tree_map_fn, tree_map_args, tree_map_kwargs = rewrite + else: + tree_map_fn = self + tree_map_args = args + tree_map_kwargs = kwargs + + is_tree_map = ( + isinstance(tree_map_fn, UserFunctionVariable) + and tree_map_fn._is_tree_map_function() + ) + is_tree_map_with_path = ( + isinstance(tree_map_fn, UserFunctionVariable) + and tree_map_fn._is_tree_map_with_path_function() + ) + + if not (is_tree_map or is_tree_map_with_path): + return None + if {*tree_map_kwargs} - _SUPPORTED_TREE_MAP_KWARGS: + return None + if len(tree_map_args) < 2: + return None + + map_fn = tree_map_args[0] + first_tree = tree_map_args[1] + rest = tree_map_args[2:] + + # The tree_map fast path doesn't create an InliningIT for tree_map, + # so NGB resume functions would miss the tree_map continuation. + with torch._dynamo.disable_nested_graph_breaks(): + if is_tree_map_with_path: + return first_tree.call_tree_map_with_path( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + keypath=(), + ) + else: + return first_tree.call_tree_map( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + ) + + def _is_tree_map_function(self) -> bool: + return ( + getattr(self.fn, "__name__", None) == "tree_map" + and getattr(self.fn, "__module__", None) in self._TREE_MAP_MODULES + ) + + def _is_tree_map_with_path_function(self) -> bool: + return ( + getattr(self.fn, "__name__", None) == "tree_map_with_path" + and getattr(self.fn, "__module__", None) in self._TREE_MAP_MODULES + ) + + def _is_tree_map_only_function(self) -> bool: + return ( + getattr(self.fn, "__name__", None) == "tree_map_only" + and getattr(self.fn, "__module__", None) in self._TREE_MAP_MODULES + ) + + def _rewrite_tree_map_only_call( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> ( + tuple[ + "UserFunctionVariable", + list[VariableTracker], + dict[str, VariableTracker], + ] + | None + ): + if not self._is_tree_map_only_function(): + return None + + if len(args) != 3: + return None + if {*kwargs} - _TREE_MAP_ONLY_SUPPORTED_KWARGS: + return None + + type_selector, map_fn, tree_arg = args + allowed_types = self._extract_tree_map_only_types(type_selector) + if allowed_types is None: + return None + + tree_map_callable = self._lookup_tree_map_function() + if tree_map_callable is None: + return None + + wrapped_map_fn = TreeMapOnlyFunctionVariable( + allowed_types, + map_fn, + source=getattr(map_fn, "source", None), + ) + tree_map_variable = VariableTracker.build(tx, tree_map_callable) + return tree_map_variable, [wrapped_map_fn, tree_arg], dict(kwargs) + + def _lookup_tree_map_function(self) -> types.FunctionType | None: + module_name = getattr(self.fn, "__module__", None) + if not module_name: + return None + module = sys.modules.get(module_name) + if module is None: + return None + tree_map = getattr(module, "tree_map", None) + if isinstance(tree_map, types.FunctionType): + return tree_map + return None + + def _extract_tree_map_only_types( + self, selector: VariableTracker + ) -> tuple[type, ...] | None: + if not selector.is_python_constant(): + return None + try: + raw_value = selector.as_python_constant() + except NotImplementedError: + return None + + flattened = self._flatten_type_spec(raw_value) + if not flattened: + return None + if not all(isinstance(typ, type) for typ in flattened): + return None + return tuple(dict.fromkeys(flattened)) + + def _flatten_type_spec(self, value: Any) -> list[type] | None: + if isinstance(value, type): + return [value] + if isinstance(value, tuple): + collected: list[type] = [] + for entry in value: + flat = self._flatten_type_spec(entry) + if flat is None: + return None + collected.extend(flat) + return collected + union_type = getattr(types, "UnionType", None) + if union_type is not None and isinstance(value, union_type): + collected = [] + for entry in typing.get_args(value): + flat = self._flatten_type_spec(entry) + if flat is None: + return None + collected.extend(flat) + return collected + return None + + +class InspectSignatureVariable(UserFunctionVariable): + """ + Variable tracker for inspect.signature with caching support. + + inspect.Signature is expensive to trace. When inspect.signature is called + repeatedly on the same function during tracing, we cache the result to avoid + retracing the signature construction each time. Although this is different + from CPython behavior, it is safe to do so because inspect.signature does + not change across different calls to the same function. + """ + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Fast path: cache results for repeated calls on the same function + if len(args) == 1 and not kwargs: + target_arg = args[0] + cache_key = None + + if isinstance(target_arg, (UserFunctionVariable, UserMethodVariable)): + cache_key = target_arg.get_function() + + if cache_key is not None: + if cache_key in tx.output.signature_cache: + return tx.output.signature_cache[cache_key] + + result = super().call_function(tx, args, kwargs) + tx.output.signature_cache[cache_key] = result + return result + + return super().call_function(tx, args, kwargs) + + +class TreeMapOnlyFunctionVariable(BaseUserFunctionVariable): + _nonvar_fields = { + "allowed_types", + *BaseUserFunctionVariable._nonvar_fields, + } + + def __init__( + self, + allowed_types: tuple[type, ...], + map_fn: VariableTracker, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.allowed_types = allowed_types + self.map_fn = map_fn + + def python_type(self) -> type: + return FunctionType + + def _matches_allowed_type(self, node: VariableTracker) -> bool: + try: + node_type = node.python_type() + except NotImplementedError: + return False + return any(issubclass(node_type, allowed) for allowed in self.allowed_types) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if not args: + return self.map_fn.call_function(tx, args, kwargs) + leaf = args[0] + if self._matches_allowed_type(leaf): + return self.map_fn.call_function(tx, args, kwargs) + if len(args) != 1 or kwargs: + # Defer to the original map function so we fall back to normal + # tracing instead of triggering a graph break. + return self.map_fn.call_function(tx, args, kwargs) + return leaf + + +class LocalGeneratorObjectVariable(VariableTracker): + # PyGen_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/genobject.c#L814 + _cpython_type = types.GeneratorType + + def __init__( + self, + code: types.CodeType, + f_globals: dict[str, Any], + inline_tracer: "InliningGeneratorInstructionTranslator", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.code = code + self.f_globals = f_globals + self.inline_tracer = inline_tracer + self.remaining_items: list[VariableTracker] = [] + inline_tracer.output.track_generator(self) + + def get_code(self) -> types.CodeType: + return self.code + + def get_filename(self) -> str: + return self.get_code().co_filename + + def get_name(self) -> str: + return self.get_code().co_name + + def get_function(self) -> Never: + raise NotImplementedError("get_function") + + def has_self(self) -> bool: + return False + + def __name__(self) -> str: + return self.get_name() + + def __str__(self) -> str: + return f"{self.__class__.__name__}({self.get_name()})" + + __repr__ = __str__ + + def reconstruct(self, codegen: "PyCodegen") -> None: + from torch._dynamo.side_effects import disallow_side_effects_in_generator + from torch._dynamo.symbolic_convert import ( + save_and_restart_speculation_log, + temporarely_allow_writes_to_output_graph, + ) + + tx = codegen.tx + save = save_and_restart_speculation_log(tx) + disallow = disallow_side_effects_in_generator(tx) + temp = temporarely_allow_writes_to_output_graph(tx) + + with save, disallow, temp: + if not self._frame_state_finished(): + self.remaining_items = unpack_iterable(tx, self) # type: ignore[bad-argument-type] + variables.ListIteratorVariable(self.remaining_items).reconstruct(codegen) + + def get_globals(self) -> dict[str, Any]: + return self.f_globals + + def python_type(self) -> type: + return types.GeneratorType + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + # Generators have no tp_richcompare: identity for ==/!=, TypeError for + # ordering. + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def pygen_yf(self) -> VariableTracker | None: + if self.inline_tracer.frame_state == FrameState.FRAME_SUSPENDED_YIELD_FROM: + if sys.version_info >= (3, 15): + ind = -2 + else: + ind = -1 + return self.inline_tracer.stack[ind] + return None + + def gen_send_ex2( + self, + tx: "InstructionTranslatorBase", + arg: VariableTracker, + exc: bool, + ) -> VariableTracker: + # https://github.com/python/cpython/blob/f31a89bb901067dd105b00cfa90523cf7ffdbbdd/Objects/genobject.c#L259 + tracer = self.inline_tracer + + if ( + tracer.frame_state == FrameState.FRAME_CREATED + and not arg.is_constant_none() + ): + raise_type_error( + tx, + "can't send non-None value to a just-started generator", + ) + + if tracer.frame_state == FrameState.FRAME_EXECUTING: + raise_value_error(tx, "generator already executing") + + if self._frame_state_finished(): + raise_observed_exception(StopIteration, tx) + + tracer.frame_state = FrameState.FRAME_EXECUTING + + try: + # Hierarchically, tx can be seen as the parent of the inline tracer + # created on call_function. Any exception needs to be propagated to tx + # for Dynamo to behave correctly + tracer.push(arg) + with self.inline_tracer.link_gi_exc_state(): + if exc: + self.throw_pending() + return tracer.inline_call_() + except ObservedUserStopIteration: + # PEP 479: pre-3.12 has no STOPITERATION_ERROR opcode, so convert a + # StopIteration that escapes the generator body to RuntimeError here + # at the frame boundary. https://github.com/python/cpython/pull/99006 + # A normal return sets FRAME_CLEARED and raises a synthetic + # StopIteration to signal exhaustion; that one must stay a + # StopIteration, so only convert when the body was still executing. + was_executing = tracer.frame_state == FrameState.FRAME_EXECUTING + tracer.frame_state = FrameState.FRAME_COMPLETED + if sys.version_info < (3, 12) and was_executing: + # Match CPython's _PyErr_FormatFromCause: set __context__ and + # __cause__ directly rather than pushing onto the exception + # stack (which must stay balanced -- genobject.c pops the + # generator's gi_exc_state before the conversion runs, so the + # caller's stack is left unchanged). do_raise sets __cause__; + # set __context__ first so set_exception_obj's implicit chaining + # leaves it untouched. + prev = tracer.exn_vt_stack.get_raised_exception() + rt = VariableTracker.build(tx, RuntimeError).call_function( + tx, + [VariableTracker.build(tx, "generator raised StopIteration")], + {}, + ) + rt.call_method( + tx, + "__setattr__", + [ConstantVariable.create("__context__"), prev], + {}, + ) + tx.do_raise(rt, prev) + raise + except ObservedException: + # An exception propagating out of the generator frame finishes it, + # mirroring CPython setting gi_frame_state = FRAME_CLEARED. + tracer.frame_state = FrameState.FRAME_CLEARED + raise + except InfiniteGeneratorError: + # test/dynamo/test_misc.py::test_iterator_limit + unimplemented( + gb_type="infinite generator detected", + context="", + explanation="Dynamo traced the YIELD_VALUE bytecode too many times. This could mean " + "that we have attempted to trace an infinite generator.", + hints=[ + f"If you are sure that your generator is not infinite, please report a bug at {PT2_ISSUE_TRACKER_URL}.", + *graph_break_hints.USER_ERROR, + ], + ) + except Unsupported as e: + torch._dynamo.eval_frame.skip_code(self.get_code()) + e.skip_frame = True + if not tx.one_graph and not tx.error_on_graph_break: + e.msg += "\n\nSkipping frame due to graph break in a generator's next() call." + raise + + def gen_send_ex( + self, + tx: "InstructionTranslatorBase", + arg: VariableTracker, + exc: bool, + ) -> VariableTracker: + # rule of thumb for gen_send_ex2: + # - PYGEN_RETURN => No exception raised + # - PYGEN_ERROR => Exception raised + # - PYGEN_NEXT => yielded - frame suspended + # gen_send_ex raises StopIteration if gen_send_ex2 returns PYGEN_RETURN + result = self.gen_send_ex2(tx, arg, exc) + if self._frame_state_suspended(): + # PYGEN_NEXT + return result + else: + # PYGEN_RETURN + if result.is_constant_none(): + raise_observed_exception(StopIteration, tx) + else: + raise_observed_exception(StopIteration, tx, args=[result]) + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.3/Objects/genobject.c#L832 + return self.gen_send_ex2(tx, ConstantVariable.create(None), False) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + if name in self.python_type().__dict__: + return ConstantVariable.create(True) + return ConstantVariable.create(False) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.3/Objects/genobject.c#L831 + return self + + # no nested graph breaks in generators + def should_allow_nested_graph_breaks(self) -> Literal[False]: + return False + + def _setup_exception( + self, tx: "InstructionTranslatorBase", exc: VariableTracker + ) -> None: + # Set up the exception to be raised in the generator frame + from torch._dynamo.symbolic_convert import ExceptionTypes, ExceptionVals + + # Instantiate if an exception type was passed (builtin or user-defined). + if not isinstance(exc, (ExceptionTypes, ExceptionVals)): + raise TypeError( + f"Expected an exception type or instance, got {exc.python_type_name()}" + ) + val = tx._create_exception_instance(exc) + if not isinstance(val, ExceptionVals): + raise AssertionError(f"Expected an exception variable, got {val}") + self.inline_tracer.exn_vt_stack.set_raised_exception(val) + + def _frame_state_created(self) -> bool: + return self.inline_tracer.frame_state == FrameState.FRAME_CREATED + + def _frame_state_finished(self) -> bool: + return self.inline_tracer.frame_state in { + FrameState.FRAME_COMPLETED, + FrameState.FRAME_CLEARED, + } + + def _frame_state_suspended(self) -> bool: + return self.inline_tracer.frame_state in { + FrameState.FRAME_SUSPENDED, + FrameState.FRAME_SUSPENDED_YIELD_FROM, + } + + def gen_send( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Sends a value into the generator function. Returns the next value + # yielded by the generator, or raises StopIteration if the generator + # exits without yielding another value + return self.gen_send_ex(tx, args[0], False) + + def gen_close( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # * Raises a GeneratorExit at the point where the generator function was paused. + # * If the generator function catches the exception and returns a + # value, this value is returned from close() - Python 3.13+ + # * If the generator function is already closed, or raises GeneratorExit + # (by not catching the exception), close() returns None. + # * If the generator yields a value, a RuntimeError is raised. + # * If the generator raises any other exception, it is propagated to the caller. + # * If the generator has already exited due to an exception or normal + # exit, close() returns None and has no other effect. + + # Return None if close is called on a just-started generator + # See test GeneratorCloseCpythonTests::test_close_not_started + + tracer = self.inline_tracer + if self._frame_state_created(): + tracer.frame_state = FrameState.FRAME_COMPLETED + return ConstantVariable.create(None) + + if self._frame_state_finished(): + return ConstantVariable.create(None) + + err = False + yf = self.pygen_yf() + if yf: + with tracer.temporarily_set_frame_state(FrameState.FRAME_EXECUTING): + try: + yf.call_method(tx, "close", [], {}) + except ObservedException: + err = True + + if err is False: + self._setup_exception(tx, VariableTracker.build(tx, GeneratorExit)) + + try: + self.gen_send_ex(tx, ConstantVariable.create(None), True) + except ObservedGeneratorExit as e: + # Drop the traceback to break the exception -> traceback -> frame -> + # (raised_exception, self) reference cycle. Otherwise the generator's + # inline_tracer (and the OutputGraph it points at) survives until + # cyclic GC instead of being freed by refcount at frame exit. + e.__traceback__ = None + return ConstantVariable.create(None) + except ObservedUserStopIteration: + # generator returned a value while closing. gen_send_ex() raises + # StopIteration with the value returned + curr_exc = tracer.exn_vt_stack.get_raised_exception() + if not isinstance(curr_exc, variables.ExceptionVariable): + # make pyrefly happy + raise AssertionError( + f"Expected current exception to be an ExceptionVariable, got {curr_exc}" + ) from None + if curr_exc.args: + return curr_exc.args[0] + else: + # if it reaches here, the generator yielded a value while closing + raise_observed_exception( + RuntimeError, + tx, + args=["generator ignored GeneratorExit"], + ) + return ConstantVariable.create(None) + + def throw_pending(self) -> None: + tracer = self.inline_tracer + curr_exc = tracer.exn_vt_stack.get_raised_exception() + observed = get_dynamo_observed_exception(curr_exc.python_type())() + curr_type = VariableTracker.build(tracer, curr_exc.exc_type) + tracer.set_exception_obj(curr_type, curr_exc) + tracer.exception_handler(observed) + + def gen_throw( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # * Raises an exception at the point where the generator was paused, and + # returns the next value yielded by the generator. + # * If the generator exits without yielding, raise StopIteration + # * If the generator function does not catch the passed-in exception, + # or raises a different exception, then that exception propagates to the caller. + def throw_here(): + self._setup_exception(tx, arg) + return self.gen_send_ex(tx, ConstantVariable.create(None), True) + + from torch._dynamo.symbolic_convert import pyerr_given_exception_match + + arg = args[1] if len(args) > 1 else args[0] + yf = self.pygen_yf() + tracer = self.inline_tracer + + if yf: + # CPython has an extra flag for handling async generators + if pyerr_given_exception_match(arg, GeneratorExit): + try: + # CPython uses gen_close_iter here + with tracer.temporarily_set_frame_state(FrameState.FRAME_EXECUTING): + yf.call_method(tx, "close", [], {}) + except ObservedException: + pass + return throw_here() + + try: + with tracer.temporarily_set_frame_state(FrameState.FRAME_EXECUTING): + return yf.call_method(tx, "throw", [arg], {}) + except ObservedException: + return self.gen_send_ex(tx, ConstantVariable.create(None), True) + + return throw_here() + + tp_methods = { + "send": Method(gen_send), + "close": Method(gen_close), + "throw": Method(gen_throw), + } + + +class ContextlibContextManagerLocalGeneratorObjectVariable( + LocalGeneratorObjectVariable +): + """ + .. note:: + + This is only used when the function is annotated with @contextlib.contextmanager + + It is a special case of a generator function as we do not allow return a context manager + from a torch.compile function. + """ + + +class LocalGeneratorFunctionVariable(BaseUserFunctionVariable): + """functions that behaves like iterators + + .. note:: + + This is a wrapper around (Nested)UserFunctionVariable + """ + + def python_type(self) -> type: + return types.FunctionType + + def __init__( + self, + vt: BaseUserFunctionVariable, + *, + generator_cls: type = LocalGeneratorObjectVariable, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.vt = vt + self.generator_cls = generator_cls + + def __getattr__(self, name: str) -> Any: + if name in self.__class__.__dict__: + return getattr(self, name) + return getattr(self.vt, name) + + # These need to be explicit so the custom __getattr__ doesn't fall back to the unimplemented base class version + def get_code(self) -> types.CodeType: + return self.vt.get_code() + + def get_globals(self) -> dict[str, Any]: + return self.vt.get_globals() + + def has_self(self) -> bool: + return self.vt.has_self() + + def _build_inline_tracer( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> "InliningInstructionTranslator": + from torch._dynamo.symbolic_convert import InliningInstructionTranslator + + return InliningInstructionTranslator.build_inline_tracer( + tx, + self, + args, + kwargs, + ) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if isinstance(self.vt, SkipFunctionVariable): + unimplemented( + gb_type="generator function over a skipped function", + context=str(self.vt), + explanation="Cannot trace a generator whose underlying function is skipped by Dynamo " + "(e.g. defined in a skip-listed module), since its body cannot be symbolically traced.", + hints=[*graph_break_hints.FUNDAMENTAL], + ) + if not is_generator(self.vt.get_code()): + unimplemented( + gb_type="non-generator contextlib.contextmanager", + context=str(self.vt.get_code()), + explanation="Cannot compile function decorated with `@contextlib.contextmanager` that is not a generator" + ", i.e. does not use `yield`", + hints=[ + "Use `yield` in the function body instead of `return`.", + "Remove the `@contextlib.contextmanager` decorator.", + ], + ) + + inline_tracer = self._build_inline_tracer(tx, list(args), kwargs) + code = self.vt.get_code() + f_globals = self.vt.get_globals() + + if sys.version_info >= (3, 11): + inline_tracer.inline_call_() + # calling a generator returns a generator object + return self.generator_cls( + code, + f_globals, + inline_tracer, # type: ignore[arg-type] + source=self.source, + ) + + def get_real_python_backed_value(self) -> object: + return self.vt.get_real_python_backed_value() + + +class FunctionDecoratedByContextlibContextManagerVariable( + LocalGeneratorFunctionVariable +): + """ + .. note:: + + This is only used when the function is annotated with @contextlib.contextmanager + """ + + def __init__(self, vt: BaseUserFunctionVariable, **kwargs: Any) -> None: + super().__init__( + vt, + generator_cls=ContextlibContextManagerLocalGeneratorObjectVariable, + **kwargs, + ) + + +class UserMethodVariable(UserFunctionVariable): + """Some unsupported user-defined method""" + + # PyMethod_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/classobject.c#L332 + _cpython_type = types.MethodType + + def __init__( + self, + fn: Callable[..., Any], + obj: VariableTracker, + source_fn: Source | None = None, + **kwargs: Any, + ) -> None: + super().__init__(fn=fn, **kwargs) # type: ignore[arg-type] + self.obj = obj + self.source_fn = source_fn + # Note on source and source_fn + # Be careful with `source` when delegating to UserFunctionVariable + # (base-class) methods. In this __init__, `source` is a *bound method* + # object, but the base class expects the underlying *function* object. + # One way is to simplly use `__func__` to unwrap it. + # + # For recursive dict-tag optimizations, it can be faster to fetch the + # function directly from `cls.__dict__`; that's why we pass on + # `source_fn`. Whenever it is possible to access the function from + # cls.__dict__, we pass that on to `source_fn`. Because bind_args + # operates on the unbound function, most guards should target + # `source_fn` rather than the original `source`. + if source_fn is None and kwargs.get("source") is not None: + self.source_fn = AttrSource(kwargs.get("source"), "__func__") # type: ignore[assignment, arg-type] + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.fn}, {self.obj})" + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # CPython method_hash: hash(self) ^ hash(func) + # https://github.com/python/cpython/blob/e76aa128fe/Objects/classobject.c#L304 + if self.source: + real_val = tx.output.resolve_source_value(self.source) + return hash(real_val), False + # Sourceless: compute method_hash from components. + from .object_protocol import generic_hash_impl + + self_hash, self_fake = generic_hash_impl(tx, self.obj) + func_hash = hash(self.fn) + h = self_hash ^ func_hash + if h == -1: + h = -2 + return h, self_fake + + def self_args(self) -> list[VariableTracker]: + return [self.obj] + + def python_type(self) -> type[types.MethodType]: + return types.MethodType + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # NOTE this is to handle methods annotated by `nonstrict_trace`. + # a `nonstrict_trace`-ed function will be wrapped by + # `VariableTracker.build` and route to `TorchInGraphFunctionVariable`, + # but in the case of method, we manually wrap it with `UserMethodVariable` + # inside `UserDefinedObjectVariable.tp_getattro_impl`. + # + # We might be able to simplify this away by canonicalizing the + # function/method wrapping code paths. + from ..trace_rules import is_leaf_function, is_nonstrict_trace_callable + + if is_nonstrict_trace_callable(self.fn): + call_args = [*self.self_args(), *args] + var = variables.TorchInGraphFunctionVariable( + self.fn, kind=variables.torch.AllowInGraphKind.NONSTRICT_TRACE + ) + return var.call_function(tx, call_args, kwargs) + + if is_leaf_function(self.fn): + call_args = [*self.self_args(), *args] + var = variables.TorchInGraphFunctionVariable( + self.fn, kind=variables.torch.AllowInGraphKind.LEAF_FUNCTION + ) + return var.call_function(tx, call_args, kwargs) + + # For nn.Module methods, redirecting to NNModuleVariable.call_method for optimized solution + # rather than simple inlining. E.g, putting `call_method` op in FX graph for `forward` method + # since we ensure `forward` of allowed modules can be traced by AOT safely. + # Note this is not only for allowed modules, as user customized modules can extend from + # allowed modules but using parent's `forward` method, which is also covered by this branch. + + # If we are tracing the higher order op, we want Dynamo to step inside + # the module call so that Dynamo can see the underlying parameters and + # buffers and raise them as inputs to the graph. The is_root_tracer + # check bypasses the if condition for non-root tracers and directly + # calls the super().call_function at the end, which is basically + # equivalent of inlining the method. + if tx.output.is_root_tracer() and isinstance( + self.obj, variables.NNModuleVariable + ): + module_attr = getattr(self.fn, "__module__", "") + # inline torch.nn.utils.parametrize + if ( + module_attr is not None + and module_attr.startswith("torch.nn.") + and module_attr != "torch.nn.utils.parametrize" + or self.is_constant + ): + return self.obj.call_method( + tx, self.fn.__name__, list(args), kwargs, constant=self.is_constant + ) + elif ( + _fsdp_param_group is not None + and self.fn is _fsdp_param_group.FSDPParamGroup.use_training_state # type: ignore[attr-defined] + ): + return variables.TorchCtxManagerClassVariable(self.fn).call_function( + tx, [self.obj, *args], kwargs + ) + if self.is_constant: + fn = getattr(self.obj.value, self.fn.__name__) # type: ignore[attr-defined] + return invoke_and_store_as_constant(tx, fn, self.get_name(), args, kwargs) + return super().call_function(tx, args, kwargs) + + def _get_func(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # We might have a better way to access the function object, this + # information is stored in self.source_fn, use that to construct the + # variable tracker. + return VariableTracker.build(tx, self.fn, self.source_fn) # type: ignore[arg-type] + + # __self__ / __func__ are read-only members on method objects. + # https://github.com/python/cpython/blob/v3.13.0/Objects/classobject.c#L20-L24 + tp_members = { + "__self__": Member(getset_read(lambda s: s.obj)), + "__func__": Member(_get_func, None), + } + + def get_real_python_backed_value(self) -> Any: + return self.fn + + +class WrappedUserMethodVariable(UserMethodVariable): + def __init__( + self, + wrapped: UserMethodVariable, + context: "ContextWrappingVariable", + **kwargs: Any, + ) -> None: + kwargs.pop("fn", None) + kwargs.pop("obj", None) + super().__init__(wrapped.fn, wrapped.obj, **kwargs) + self.wrapped = wrapped + self.context = context + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if config.nested_graph_breaks: + wrapper_fn = UserFunctionVariable(polyfills._fn_with_ctx) + return wrapper_fn.call_function( + tx, [self.context, self.wrapped] + list(args), kwargs + ) + self.context.enter(tx) + result = super().call_function(tx, args, kwargs) + self.context.exit(tx) + return result + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen(self.context)) # type: ignore[arg-type] + codegen(self.wrapped) + codegen.extend_output(create_call_function(1, False)) + + +class WrappedUserFunctionVariable(UserFunctionVariable): + def __init__( + self, + wrapped: UserFunctionVariable, + context: "ContextWrappingVariable", + **kwargs: Any, + ) -> None: + kwargs.pop("fn", None) + super().__init__(wrapped.fn, **kwargs) + self.wrapped = wrapped + self.context = context + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if config.nested_graph_breaks: + wrapper_fn = UserFunctionVariable(polyfills._fn_with_ctx) + return wrapper_fn.call_function( + tx, [self.context, self.wrapped] + list(args), kwargs + ) + self.context.enter(tx) + result = super().call_function(tx, args, kwargs) + self.context.exit(tx) + return result + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen(self.context)) # type: ignore[arg-type] + codegen(self.wrapped) + codegen.extend_output(create_call_function(1, False)) + + +def invoke_and_store_as_constant( + tx: "InstructionTranslatorBase", + fn: Callable[..., Any], + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + def convert(x: VariableTracker) -> Any: + if x.is_tensor(): + return cast("TensorVariable", x).get_real_value() + if isinstance(x, UserDefinedObjectVariable): + if x.source is not None: + install_guard(x.make_guard(GuardBuilder.ID_MATCH)) + return x.value + try: + return x.as_python_constant() + except AsPythonConstantNotImplementedError: + unimplemented( + gb_type="assume_constant_result argument conversion failed", + context=f"function {name}, variable type {type(x).__name__}", + explanation=f"Cannot convert argument of type {type(x).__name__} to a Python constant " + f"for function {name} marked with torch._dynamo.assume_constant_result. " + f"The variable tracker does not support constant conversion.", + hints=[ + "Remove torch._dynamo.assume_constant_result from this function", + "Ensure all arguments passed to the function can be converted to constants", + ], + ) + + args = [convert(x) for x in args] + kwargs = {k: convert(v) for k, v in kwargs.items()} + res = fn(*args, **kwargs) + return tx.output.register_attr_or_module( + res, + name, + source=ConstantSource(name), + ) + + +class NestedUserFunctionVariable(BaseUserFunctionVariable): + _nonvar_fields = { + "f_globals", + *BaseUserFunctionVariable._nonvar_fields, + } + + def __init__( + self, + fn_name: VariableTracker, + code: VariableTracker, + f_globals: dict[str, Any], + defaults: VariableTracker | None, + kwdefaults: VariableTracker | None, + closure: VariableTracker | None, + # This is present when this function is created by + # `functools.wrap(wrapped_fn)(this_fn)`. + wrapped_fn: VariableTracker | None = None, + **kwargs: Any, + ) -> None: + if kwargs.get("mutation_type") is None: + kwargs.update(mutation_type=AttributeMutationNew()) + super().__init__(**kwargs) + if not isinstance(fn_name.as_python_constant(), str): + raise AssertionError( + f"fn_name must be a str, got {type(fn_name.as_python_constant())}" + ) + if not isinstance(code.as_python_constant(), types.CodeType): + raise AssertionError( + f"code must be a CodeType, got {type(code.as_python_constant())}" + ) + if not isinstance(f_globals, dict): + raise AssertionError(f"f_globals must be a dict, got {type(f_globals)}") + self.fn_name = fn_name + self.code = code + self.f_globals = f_globals + self.defaults = defaults + self.kwdefaults = kwdefaults + self.closure = closure + self.wrapped_fn: VariableTracker | None = wrapped_fn + + def self_args(self) -> list[VariableTracker]: + return [] + + def as_python_constant(self) -> types.FunctionType: + return self.get_function() + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + try: + return super().tp_repr_impl(tx) + except ClosureConversionError as e: + unimplemented( + gb_type="repr() on nested function with non-constructible closure", + context=f"repr() on nested function {self.fn_name.as_python_constant()}: {e}", + explanation="Dynamo could not safely evaluate repr() for this " + "nested function because it could not reconstruct its closure " + "as Python constants.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def get_code(self) -> types.CodeType: + return self.code.as_python_constant() + + def python_type(self) -> type[types.FunctionType]: + return types.FunctionType + + def get_function( + self, + _converting: set[int] | None = None, + *, + allow_sourced_cells: bool = False, + ) -> types.FunctionType: + # _converting is used a way to break cycles when + # two nested_functions refer to each other. + from .base import AsPythonConstantNotImplementedError + + self_id = id(self) + if _converting is None: + _converting = set() + if self_id in _converting: + raise ClosureConversionError( + "cycle detected in mutually recursive closures" + ) + _converting.add(self_id) + try: + return self._get_function_impl(_converting, allow_sourced_cells) + except AsPythonConstantNotImplementedError as e: + raise ClosureConversionError( + "failed to convert closure cell to Python constant" + ) from e + finally: + _converting.discard(self_id) + + def is_python_constant(self) -> bool: + try: + self.as_python_constant() + return True + except (NotImplementedError, Unsupported): + return False + + def _get_function_impl( + self, _converting: set[int], allow_sourced_cells: bool + ) -> types.FunctionType: + closure_cells = None + if self.closure: + from torch._dynamo.symbolic_convert import InstructionTranslator + + tx = InstructionTranslator.current_tx() + cells = [] + + for cell_var in self.closure.items: # type: ignore[attr-defined] + # Get the cell contents from side_effects or pre_existing_contents + # load_cell will replay the side-effects + cell_contents = tx.output.side_effects.load_cell(cell_var) + + # Check for self-referential closure (function capturing itself for recursion) + # For example: + # def outer(): + # def helper(n): + # if n <= 0: + # return 0 + # return n + helper(n - 1) # helper calls itself + # return helper + if cell_contents is self: + raise ClosureConversionError("self-referential nested function") + + # If the cell contents is a NestedUserFunctionVariable, call get_function + # directly to properly propagate the _converting set for cycle detection + if isinstance(cell_contents, NestedUserFunctionVariable): + value = cell_contents.get_function( + _converting, + allow_sourced_cells=allow_sourced_cells, + ) + cells.append(make_cell(value)) + continue + + try: + value = cell_contents.as_python_constant() + cells.append(make_cell(value)) + continue + except (NotImplementedError, Unsupported): + if not allow_sourced_cells: + raise ClosureConversionError( + "failed to convert closure cell to Python constant" + ) from None + + # Non-constant closure cell (e.g. a class defined in a compiled + # region closing over a real object such as a TestCase + # instance). Only allow source-backed objects that have not + # been mutated during the trace, and pin their identity with + # an ID_MATCH guard. Materialize a real cell from the backing + # object and register it in side_effects mapping back to the + # traced VT, so that when methods of the built class are + # later inlined, bind_args reuses the original VT (preserving + # its source, guards, and identity) via load_cell. Only the + # __build_class__ path opts in; as_python_constant + # conversions must stay strict. + if not ( + isinstance(cell_contents, UserDefinedObjectVariable) + and cell_contents.source is not None + and not tx.output.side_effects.is_modified(cell_contents) + ): + raise ClosureConversionError( + "failed to convert closure cell to Python constant" + ) + value = cell_contents.guard_as_python_constant() + cell = make_cell(value) + tx.output.side_effects.track_cell_existing(None, cell, cell_contents) + cells.append(cell) + closure_cells = tuple(cells) + + func = types.FunctionType( + self.code.as_python_constant(), + self.f_globals, + self.fn_name.as_python_constant(), + argdefs=None, + closure=closure_cells, + ) + if self.defaults: + func.__defaults__ = self.defaults.as_python_constant() + if self.kwdefaults: + func.__kwdefaults__ = self.kwdefaults.as_python_constant() + if self.annotations: + annotations = self.annotations.as_python_constant() + if isinstance(annotations, tuple): + from itertools import pairwise + + annotations = dict(pairwise(annotations)) + + # TypeError: __annotations__ must be set to a dict object + if not isinstance(annotations, dict): + raise AssertionError( + f"annotations must be a dict, got {type(annotations)}" + ) + func.__annotations__ = annotations + return func + + def has_closure(self) -> bool: + return self.closure is not None + + def const_getattr(self, tx: "InstructionTranslatorBase", name: str) -> Any: + if name == "__name__": + return self.get_name() + if name == "__code__": + return self.get_code() + if name == "__defaults__": + d = getattr(self, "defaults", None) + return d.as_python_constant() if d else None + return super().const_getattr(tx, name) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + if name == "__code__": + return VariableTracker.build(tx, hasattr(self, "code")) + if name == "__defaults__": + return VariableTracker.build(tx, hasattr(self, "defaults")) + vt = ConstantVariable.create(name) + if vt in self.get_dict_vt(tx): + return ConstantVariable.create(True) + return super().call_obj_hasattr(tx, name) + + def has_self(self) -> bool: + return False + + def get_globals(self) -> dict[str, Any]: + return self.f_globals + + def bind_args( + self, + parent: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> dict[str, VariableTracker]: + code = self.get_code() + func = types.FunctionType( + code, + self.f_globals, + self.fn_name.as_python_constant(), + tuple(self.defaults.items) if self.defaults else None, # type: ignore[attr-defined] + tuple(make_cell(None) for _ in range(len(self.get_code().co_freevars))), + ) + if self.kwdefaults: + func.__kwdefaults__ = self.kwdefaults.keys_as_python_constant() # type: ignore[missing-attribute] + try: + bound = inspect.signature(func).bind(*args, **kwargs) + bound.apply_defaults() + except TypeError as e: + raise BindArgsTypeError(e.args[0]) from e + result = dict(bound.arguments.items()) + wrap_args_kwargs(parent.output.root_tx, result) # type: ignore[arg-type] + init_cellvars(parent, result, code) + + for idx, name in enumerate(code.co_freevars): + if name in result: + raise AssertionError(f"free variable {name!r} already in result") + cell = self.closure.items[idx] # type: ignore[attr-defined, union-attr] + result[name] = cell + + return result + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from(__name__, "_create_nested_fn") + ) + codegen(self.code) + codegen.extend_output([codegen.create_load_const_unchecked(self.f_globals)]) + codegen(ConstantVariable.create(self.code.value.co_name)) # type: ignore[attr-defined] + + if self.defaults: + codegen(self.defaults) + else: + codegen.extend_output([codegen.create_load_const(None)]) + + if self.closure: + codegen(self.closure) + else: + codegen.extend_output([codegen.create_load_const(None)]) + + if self.kwdefaults: + codegen(self.kwdefaults) + else: + codegen.extend_output([codegen.create_load_const(None)]) + + if self.annotations is not None: + try: + annotations = self.annotations.as_python_constant() + codegen.extend_output( + [codegen.create_load_const_unchecked(annotations)] + ) + except NotImplementedError: + codegen(self.annotations) + else: + codegen.extend_output([codegen.create_load_const(None)]) + + codegen.extend_output(create_call_function(7, False)) + + if self.wrapped_fn: + codegen.add_push_null( + lambda: codegen.load_import_from("functools", "wraps") + ) + codegen(self.wrapped_fn) + codegen.extend_output(create_call_function(1, False)) + codegen.extend_output(create_rot_n(2)) + codegen.extend_output(create_call_function(1, True)) + + # codegen attributes + tx = codegen.tx + if tx.output.side_effects.has_pending_mutation(self): + for name, value in tx.output.side_effects.store_attr_mutations[ + self + ].items(): + codegen.dup_top() + codegen(value) + codegen.extend_output(create_rot_n(2)) + codegen.store_attr(name) + + +class WrappedNestedUserFunctionVariable(NestedUserFunctionVariable): + def __init__( + self, + wrapped: NestedUserFunctionVariable, + context: "ContextWrappingVariable", + **kwargs: Any, + ) -> None: + kwargs.pop("fn_name", None) + kwargs.pop("code", None) + kwargs.pop("f_globals", None) + kwargs.pop("defaults", None) + kwargs.pop("kwdefaults", None) + kwargs.pop("annotations", None) + kwargs.pop("closure", None) + kwargs.pop("wrapped_fn", None) + super().__init__( + wrapped.fn_name, + wrapped.code, + wrapped.f_globals, + wrapped.defaults, + wrapped.kwdefaults, + wrapped.closure, + wrapped.wrapped_fn, + ) + self.annotations = wrapped.annotations + self.wrapped = wrapped + self.context = context + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if config.nested_graph_breaks: + wrapper_fn = UserFunctionVariable(polyfills._fn_with_ctx) + return wrapper_fn.call_function( + tx, [self.context, self.wrapped] + list(args), kwargs + ) + self.context.enter(tx) + result = super().call_function(tx, args, kwargs) + self.context.exit(tx) + return result + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen(self.context)) + codegen(self.wrapped) + codegen.extend_output(create_call_function(1, False)) + + +RE_CONSTANT_FOLD_FNS = { + re.search, + re.match, + re.fullmatch, + re.compile, + re.sub, + re.subn, + re.split, + re.findall, + re.escape, +} + + +class SkipFunctionVariable(VariableTracker): + _nonvar_fields = { + "value", + "reason", + *VariableTracker._nonvar_fields, + } + + def __init__(self, value: Any, reason: str | None = None, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + self.reason = reason + + def get_value_for_setattr(self) -> object | None: + mod = getattr(self.value, "__module__", None) or "" + if mod == "torch" or mod.startswith(("torch.", "torch_")): + return None + return self.value + + def tp_richcompare_impl(self, tx, other, op): + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def as_python_constant(self) -> Any: + return self.value + + def get_real_python_backed_value(self) -> Any: + return self.value + + @classmethod + def create_with_source(cls, value: Any, source: Source) -> "SkipFunctionVariable": + # Use closure match guard (i.e. guard on __code__ object instead of + # function id) to avoid guarding on nested functions. + if inspect.getattr_static(value, "_torchdynamo_disable", False): + # For torch._dynamo.disable function, ensure that the original + # function is guarded. Otherwise, the else branch will guard on the + # _dynamo.disable.__code__ + guard_on_source = source + guard_on_value = value + + while inspect.getattr_static( + guard_on_value, "_torchdynamo_orig_callable", False + ): + guard_on_value = guard_on_value._torchdynamo_orig_callable + guard_on_source = AttrSource( + guard_on_source, "_torchdynamo_orig_callable" + ) + + guard_on_source.make_guard(GuardBuilder.CLOSURE_MATCH) + elif inspect.isbuiltin(value): + # Bound builtin methods (e.g. obj.__reduce_ex__) are created fresh + # on every attribute access, so their id() is unstable. Skip the + # id-based BUILTIN_MATCH guard for them — the type guard on + # the owner object is sufficient. + if not hasattr(value, "__self__") or isinstance( + value.__self__, types.ModuleType + ): + install_guard(source.make_guard(GuardBuilder.BUILTIN_MATCH)) + elif not is_wrapper_or_member_descriptor(value): + # These descriptors are not guaranteed to return the same object on + # attribute lookup. They are unlikely to be changed, so we can skip + # guarding them. + install_guard(source.make_guard(GuardBuilder.CLOSURE_MATCH)) + return cls(value, source=source) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # importlib functions are frozen builtins that Dynamo cannot trace + # into. They are deterministic for a given package name, so + # constant-fold them when all args are constants. + if self.value in (importlib.util.find_spec, importlib.metadata.version) and all( + a.is_python_constant() for a in args + ): + return VariableTracker.build( + tx, self.value(*(a.as_python_constant() for a in args)) + ) + + if ( + self.value in RE_CONSTANT_FOLD_FNS + and all(a.is_python_constant() for a in args) + and all(v.is_python_constant() for v in kwargs.values()) + ): + result = self.value( + *(a.as_python_constant() for a in args), + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ) + return VariableTracker.build(tx, result) + + def unimplemented_direct_disable_call(api_name: str) -> Never: + # The registry linter keys off this helper name and records concrete + # entries from the call sites below. Use an alias here so the + # parameterized helper body is not recorded as a generic + # `{api_name}` entry. + _unimplemented = unimplemented + _unimplemented( + gb_type=f"Call to `{api_name}()`", + context=f"Called `{api_name}()` with args `{args}`, kwargs `{kwargs}`", + explanation=f"`{api_name}()` was called inside a compiled region. " + "This API disables compilation when used as a decorator or wrapper " + "outside the compiled region.", + hints=[ + f"Move the `{api_name}()` call outside the compiled function and apply it to the function that should run eagerly.", + "Use `torch._dynamo.graph_break()` to intentionally insert a graph break at this point.", + ], + ) + + if self.value is torch._dynamo.disable: + unimplemented_direct_disable_call("torch._dynamo.disable") + elif self.value is torch.compiler.disable: + unimplemented_direct_disable_call("torch.compiler.disable") + elif inspect.getattr_static(self.value, "_torchdynamo_disable", False): + msg = inspect.getattr_static(self.value, "_torchdynamo_disable_msg", None) + unimplemented( + gb_type="Skip calling `torch.compiler.disable()`d function", + context=str(self.value), + explanation=f"Skip calling function `{self.value}` since it was wrapped " + f"with `torch.compiler.disable` (reason: {msg})", + hints=[ + "Remove the `torch.compiler.disable` call", + ], + ) + elif self.value is torch._dynamo.graph_break: + graph_break_msg = kwargs.get("msg") + if graph_break_msg: + graph_break_msg = graph_break_msg.as_python_constant() + unimplemented( + gb_type="Call to `torch._dynamo.graph_break()`", + context=f"Called `torch._dynamo.graph_break()` with args `{args}`, kwargs `{kwargs}`", + explanation=f"User-inserted graph break. Message: {graph_break_msg}", + hints=[ + "Remove the `torch._dynamo.graph_break()` call.", + ], + ) + elif self.value is torch._dynamo.skip_frame: + skip_frame_msg = kwargs.get("msg") + if skip_frame_msg: + skip_frame_msg = skip_frame_msg.as_python_constant() + else: + skip_frame_msg = "" + unimplemented( + gb_type="Call to `torch._dynamo.skip_frame()`", + context=f"Called `torch._dynamo.skip_frame()` with args `{args}`, kwargs `{kwargs}`. " + f"Skipping frame {format_frame_info(tx.f_code)}.", + explanation=f"User-inserted skip frame. Message: {skip_frame_msg}", + hints=[ + "Remove the `torch._dynamo.skip_frame()` call.", + ], + skip_frame=True, + ) + elif self.value is torch._dynamo.step_unsupported: + try: + unimplemented( + gb_type="Call to `torch._dynamo.step_unsupported()`", + context="", + explanation="User-inserted step_unsupported.", + hints=[ + "Remove the `torch._dynamo.step_unsupported()` call.", + ], + ) + except Unsupported as e: + raise StepUnsupported(e.msg) from None + elif self.value is types.FunctionType.__get__: + # function.__get__(func, obj[, cls]) produces a bound method. + # This is called by inspect._descriptor_get when resolving + # descriptors during inspect.signature(). + # Note that function.__get__ does not use the 3rd argument. The + # reason it still has the 3rd argument is because descriptors follow + # a function signature that takes 3 arguments, and other descriptors + # (not function.__get__) can use the 3rd argument. + if len(args) in (2, 3) and not kwargs: + func_var = args[0] + obj_var = args[1] + if isinstance(func_var, UserFunctionVariable): + return UserMethodVariable( + func_var.fn, obj_var, source_fn=func_var.source + ) + unimplemented( + gb_type="unsupported function.__get__ call", + context=f"call_function {self}, args: {args}, kwargs: {kwargs}", + explanation="Dynamo only supports function.__get__(func, obj[, cls]) " + "where func is a user-defined function.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + else: + if config.dont_skip_tracing: + from .builder import SourcelessBuilder + + # re-build the function, attempting to not skip + rebuilt_fn = SourcelessBuilder.create(tx, self.value) + # if we still get SkipFunctionVariable, then we *really* should skip this function + if not isinstance(rebuilt_fn, SkipFunctionVariable): + return rebuilt_fn.call_function(tx, args, kwargs) + qualname = getattr(self.value, "__qualname__", "") + module_or = getattr(self.value, "__module__", None) + module_name = "" if module_or is None else str(module_or) + try: + path = inspect.getfile(self.value) + explanation = ( + f"Dynamo developers have intentionally marked that the function `{qualname}` " + f"in file `{path}` should not be traced." + ) + hints = [ + f"Avoid calling the function `{qualname}`.", + ] + # TODO improve trace_rules reasoning to provide better hints. + # How do we tell that a function/file should NOT be removed from skip files? + # Do a very basic check for now. + if "_dynamo" not in path: + hints += [ + f"Apply `@torch._dynamo.dont_skip_tracing` to the function `{qualname}` " + "to force tracing into the function. " + "More graph breaks may occur as a result of attempting to trace into the function.", + "Please file an issue to PyTorch.", + ] + except TypeError: + known_python_builtin_modules = {"_abc", "_warnings"} + if module_or in known_python_builtin_modules: + explanation = ( + f"Dynamo does not know how to trace the Python builtin " + f"`{module_name}.{qualname}`." + ) + hints = [ + "If you are attempting to call a logging function (e.g. `_warnings.warn`), " + "you can try adding it to `torch._dynamo.config.reorderable_logging_functions`.", + "Please file an issue on GitHub " + "so the PyTorch team can add support for it. ", + ] + elif module_or is not None and module_or.startswith("optree"): + explanation = f"Dynamo cannot trace optree C/C++ function {module_name}.{qualname}." + hints = [ + " Consider using torch.utils._pytree - " + "https://github.com/pytorch/pytorch/blob/main/torch/utils/_pytree.py" + ] + # also warn on it because most users won't see the graph break message + torch._dynamo.utils.warn_once(explanation + "\n" + "\n".join(hints)) + else: + explanation = ( + f"Dynamo does not know how to trace the builtin `{module_name}.{qualname}.` " + f"This function is either a Python builtin (e.g. _warnings.warn) " + f"or a third-party C/C++ Python extension (perhaps created with pybind)." + ) + hints = [ + "If it is a Python builtin, please file an issue on GitHub " + "so the PyTorch team can add support for it and see the next case for a workaround.", + "If it is a third-party C/C++ Python extension, please " + "either wrap it into a PyTorch-understood custom operator " + "(see https://pytorch.org/tutorials/advanced/custom_ops_landing_page.html " + "for more details) or, if it is traceable, use " + "`torch.compiler.allow_in_graph`.", + ] + # also warn on it because most users won't see the graph break message + torch._dynamo.utils.warn_once(explanation + "\n" + "\n".join(hints)) + if qualname == "allow_in_graph": + explanation = ( + "torch.compiler.allow_in_graph (or torch._dynamo.allow_in_graph) " + "was called inside a compiled region. Dynamically annotating functions " + "inside a compiled region is not supported." + ) + hints = [ + "Apply @torch.compiler.allow_in_graph as a decorator before compilation, " + "not inside the compiled function.", + ] + if self.reason: + reason = self.reason + else: + from ..trace_rules import get_skip_reason + + reason = get_skip_reason(self.value) + unimplemented( + gb_type="Attempted to call function marked as skipped", + context=f"module: {module_name}, qualname: {qualname}, skip reason: {reason}", + explanation=explanation, + hints=hints, + ) + + def reconstruct_pycode(self, codegen): + if self.source: + return self.source.reconstruct_pycode(codegen) + raise NotImplementedError( + "Python codegen not implemented for sourceless SkipFunctionVariable" + ) + + +class WrappedSkipFunctionVariable(SkipFunctionVariable): + def __init__( + self, + wrapped: SkipFunctionVariable, + context: "ContextWrappingVariable", + **kwargs: Any, + ) -> None: + kwargs.pop("value", None) + kwargs.pop("reason", None) + super().__init__(wrapped.value, reason=wrapped.reason, **kwargs) + self.wrapped = wrapped + self.context = context + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if config.nested_graph_breaks: + wrapper_fn = UserFunctionVariable(polyfills._fn_with_ctx) + return wrapper_fn.call_function( + tx, [self.context, self.wrapped] + list(args), kwargs + ) + self.context.enter(tx) + result = super().call_function(tx, args, kwargs) + self.context.exit(tx) + return result + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen(self.context)) + codegen(self.wrapped) + codegen.extend_output(create_call_function(1, False)) + + +class WrapperUserFunctionVariable(BaseUserFunctionVariable): + """ + Used to represent a wrapper object that contains the actual callable as an + attribute. For example, torch.jit.script/trace have the original function at + their _torchdynamo_inline attribute. Similarly, functions with + __script_if_tracing_wrapper have the original attr at "__original_fn". + """ + + def python_type(self) -> type: + return types.FunctionType + + def __init__(self, wrapper_obj: Any, attr_to_trace: str, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.wrapper_obj = wrapper_obj + self.attr_to_trace = attr_to_trace + + def get_module(self) -> str: + return self.wrapper_obj.__module__ + + def get_name(self) -> str: + return self.wrapper_obj.__name__ + + def get_code(self) -> types.CodeType: + return self.get_function().__code__ + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if name == self.attr_to_trace: + val = getattr(self.wrapper_obj, self.attr_to_trace) + source = self.source and AttrSource(self.source, name) + return VariableTracker.build(tx, val, source) + return super().tp_getattro_impl(tx, name) + + def get_function(self): + return getattr(self.wrapper_obj, self.attr_to_trace) + + def lookup_instance_dict( + self, tx: "InstructionTranslatorBase", name: str + ) -> "VariableTracker | None": + # self.source denotes the wrapper, not the inline target reached via + # attr_to_trace. Resolve instance-dict attrs (e.g. functools.wraps' + # __wrapped__) against the wrapper so the built value matches the source; + # the base impl reflects on get_function() (the inline target), which + # would pair the inline target's value with the wrapper's source and + # yield a self-inconsistent guard (issue: swap/getfullargspec repro). + wrapper_dict = getattr(self.wrapper_obj, "__dict__", None) + if not wrapper_dict or name not in wrapper_dict: + return None + source = self.get_source() + source = AttrSource(source, name) if source is not None else None + if source is not None: + return variables.LazyVariableTracker.create( + wrapper_dict[name], source, tx=tx + ) + return VariableTracker.build(tx, wrapper_dict[name]) + + def self_args(self) -> list[VariableTracker]: + return [] + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if hasattr(self.wrapper_obj, "cache_info"): + target_fn = getattr(self.wrapper_obj, self.attr_to_trace, None) + module_name = getattr(target_fn, "__module__", "") or "" + is_allowed_lru_cache_wrapper = ( + is_lru_cache_wrapper_trace_without_warning_allowed(self.wrapper_obj) + ) + + if ( + module_name.split(".", maxsplit=1)[0] != "torch" + and not is_allowed_lru_cache_wrapper + ): + frame_summary = tx.frame_summary() + filename = os.path.basename(frame_summary.filename) + lineno = frame_summary.lineno + msg = ( + "Dynamo detected a call to a `functools.lru_cache`-wrapped " + f"function at '{filename}:{lineno}'. Dynamo ignores the " + "cache wrapper and directly traces the wrapped function. " + "Silent incorrectness is only a *potential* risk, not " + "something we have observed. " + "Enable TORCH_LOGS=+dynamo for a DEBUG stack trace.\n\n" + "This call originates from:\n" + f"{''.join(traceback.format_list([frame_summary]))}" + ) + + torch._dynamo.utils.warn_once(msg) + + dynamo_logger = torch._dynamo.utils.logging.getLogger("torch._dynamo") + if dynamo_logger.isEnabledFor(logging.DEBUG): + user_stack = torch._guards.TracingContext.extract_stack() + user_stack = get_stack_above_dynamo() + user_stack + frame_loc = (user_stack[-1].filename, user_stack[-1].lineno) + user_stack_formatted = "".join(traceback.format_list(user_stack)) + user_stack_trace = f"call to a lru_cache wrapped function at: {frame_loc[0]}:{frame_loc[1]}\n" + user_stack_trace += str(user_stack_formatted) + dynamo_logger.debug(user_stack_trace) + + all_args = self.self_args() + list(args) + # Inner torch.compile wrapper: disable nested graph breaks to + # preserve the inner compile's semantics (e.g. fullgraph=True). + # Graph breaks inside the inner function should raise Unsupported + # so they're handled by the outer frame, not as nested breaks. + # Skip this for recursive calls to the same compiled function + # (the wrapper's original callable matches the root frame's code). + is_inner_torch_compile = ( + self.attr_to_trace == "_torchdynamo_inline" + and inspect.getattr_static(self.wrapper_obj, "_is_torch_compile", False) + and getattr( + inspect.getattr_static( + self.wrapper_obj, "_torchdynamo_orig_callable", None + ), + "__code__", + None, + ) + is not tx.output.root_tx.f_code + ) + polyfill = ( + polyfills.getattr_and_trace_no_nested_graph_breaks + if is_inner_torch_compile + else polyfills.getattr_and_trace + ) + return VariableTracker.build( + tx, + polyfill, # type: ignore[arg-type] + ).call_function( + tx, + [self, VariableTracker.build(tx, self.attr_to_trace), *all_args], + kwargs, + ) + + def get_real_python_backed_value(self) -> object: + # This VT stands for the wrapper, which is also what self.source + # denotes. The inline target is reached via attr_to_trace and is a + # different object. + return self.wrapper_obj + + +class WrapperUserMethodVariable(WrapperUserFunctionVariable): + """ + Similar to WrapperUserFunctionVariable, but for methods. The only delta is + saving the vt for `self` object of the method which is then used by + WrapperUserFunctionVariable in `call_function` method. + """ + + def python_type(self) -> type: + return types.MethodType + + def __init__( + self, + wrapper_obj: Any, + attr_to_trace: str, + self_obj: VariableTracker, + **kwargs: Any, + ) -> None: + super().__init__(wrapper_obj, attr_to_trace, **kwargs) + self.obj = self_obj + + def self_args(self) -> list[VariableTracker]: + return [self.obj] + + +def _traceable_collective_remaps() -> dict[Any, Any]: + # We can't rely on importing from distributed, since it's not always built + if torch.distributed.is_available(): + from torch.distributed._functional_collectives import ( + traceable_collective_remaps, + ) + + return traceable_collective_remaps + return {} + + +def _traceable_collectives_source( + tx: "InstructionTranslatorBase", fn: Callable[..., Any] +) -> AttrSource: + if not torch.distributed.is_available(): + raise AssertionError("Illegal invocation.") + if fn not in _traceable_collective_remaps().values(): + raise AssertionError(f"{fn} is not a traceable collective remap") + + inner_name = fn.__name__ + path_source = tx.import_source("torch.distributed._functional_collectives") + return AttrSource(path_source, inner_name) + + +class CollectiveFunctionRewriteVariable(UserFunctionVariable): + """ + Some of the torch.distributed.* collective APIs are possible to rewrite to 'traceable' collectives. + + This class provides both a way to check if a function is remappable, and perform the remapping. + + In the case that a function is 'remappable' but only for some combinations of call-time arguments, + we check the args at `call_function` time and fall back to graph-breaking if needed. This is no worse + than status-quo as we currently graph-break on all distributed.* collectives. + """ + + def __init__( + self, + fn: Callable[..., Any], + *, + replacement_var: UserFunctionVariable, + **kwargs: Any, + ) -> None: + super().__init__(fn, **kwargs) # type: ignore[arg-type] + if not isinstance(replacement_var, UserFunctionVariable): + raise AssertionError( + f"replacement_var must be a UserFunctionVariable, got {type(replacement_var)}" + ) + self.replacement_var = replacement_var + + @staticmethod + def create( + tx: "InstructionTranslatorBase", + old_fn: Callable[..., Any], + source: Source, + **options: Any, + ) -> "CollectiveFunctionRewriteVariable": + new_fn, new_source = CollectiveFunctionRewriteVariable.rewrite(tx, old_fn) + return CollectiveFunctionRewriteVariable( + old_fn, + replacement_var=UserFunctionVariable(new_fn, source=new_source, **options), + source=source, + **options, + ) + + @staticmethod + def can_rewrite(variable: Any) -> bool: + return ( + inspect.isfunction(variable) and variable in _traceable_collective_remaps() + ) + + @staticmethod + def rewrite( + tx: "InstructionTranslatorBase", fn: Callable[..., Any] + ) -> tuple[Any, AttrSource]: + new_fn = _traceable_collective_remaps()[fn] + return new_fn, _traceable_collectives_source(tx, new_fn) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # call_function must check any unsupported arguments and graph-break. + # It's safe to assume args/kwargs from orig_fn map 1:1 to args/kwargs of remapped_fn, + # since that's the contract for putting a mapping in `traceable_collective_remaps` + import torch.distributed as dist + from torch.distributed._functional_collectives import REDUCE_OP_TO_STR + + # Merge args into kwargs so positional and keyword args + # can be processed the same way. + signature = inspect.signature(self.fn) + kwargs = dict(signature.bind(*args, **kwargs).arguments) + args = [] + + if "async_op" in kwargs and kwargs["async_op"].as_python_constant(): + unimplemented( + gb_type="async_op=True for distributed collectives", + context=f"{self.fn}, {args=}, {kwargs=}", + explanation=f"`torch.compile` doesn't support `async_op=True for {self.fn}", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + if self.fn == dist.batch_isend_irecv: + if not config.enable_p2p_compilation: + unimplemented( + gb_type="P2P compilation disabled for batch_isend_irecv", + context=f"{self.fn}", + explanation="P2P compilation is disabled.", + hints=[ + "Set TORCHDYNAMO_ENABLE_P2P_COMPILATION=1 to enable.", + ], + ) + + p2p_ops = kwargs["p2p_op_list"] + if not isinstance(p2p_ops, variables.ListVariable): + raise torch._dynamo.exc.InternalTorchDynamoError( + "`P2POp` used incorrectly" + ) + + ops: list[VariableTracker] = list() + peers = list() + tags = list() + tensors = list() + group_var: VariableTracker | None = None + + for item in p2p_ops.items: + if item.python_type() is not dist.P2POp: + raise torch._dynamo.exc.InternalTorchDynamoError( + "`P2POp` used incorrectly" + ) + + op_var = item.tp_getattro_impl(tx, "op") + if op_var.is_python_constant(): + op = op_var.as_python_constant() + if op not in (dist.isend, dist.irecv): + raise torch._dynamo.exc.InternalTorchDynamoError( + f"unexpected P2POp op {op}" + ) + op_var = variables.ConstantVariable.create(op.__name__) + elif hasattr(op_var, "get_name"): + op_var = variables.ConstantVariable.create(op_var.get_name()) + else: + raise torch._dynamo.exc.InternalTorchDynamoError( + f"unexpected P2POp op variable {op_var}" + ) + + ops.append(op_var) + tensors.append(item.tp_getattro_impl(tx, "tensor")) + # batch_p2p_ops expects a group-local rank, which is what + # P2POp.group_peer provides. + peers.append(item.tp_getattro_impl(tx, "group_peer")) + tags.append(item.tp_getattro_impl(tx, "tag")) + if group_var is None: + group_var = item.tp_getattro_impl(tx, "group") + + if group_var is None: + raise AssertionError("group_var must be set from P2POp items") + new_args: list[VariableTracker] = [] + new_kwargs: dict[str, VariableTracker] = { + "op_list": variables.ListVariable(ops), + "peer_list": variables.ListVariable(peers), + "tag_list": variables.ListVariable(tags), + "tensors": variables.ListVariable(tensors), + "group_name": group_var, + } + return self.replacement_var.call_function(tx, new_args, new_kwargs) + + if self.fn in (dist.isend, dist.irecv): + if not config.enable_p2p_compilation: + unimplemented( + gb_type="P2P compilation disabled for isend/irecv", + context=f"{self.fn}", + explanation="P2P compilation is disabled.", + hints=[ + "Set TORCHDYNAMO_ENABLE_P2P_COMPILATION=1 to enable.", + ], + ) + + return self.replacement_var.call_function(tx, args, kwargs) + + if self.fn in ( + dist.all_reduce, + dist.reduce_scatter, + dist.reduce_scatter_single, + # pyrefly: ignore [deprecated] + dist.reduce_scatter_tensor, + # pyrefly: ignore [deprecated] + dist._reduce_scatter_base, + ): + reduce_op_var = kwargs.get("op") + reduce_op = ( + reduce_op_var.value # type: ignore[attr-defined] + if reduce_op_var is not None + else signature.parameters["op"].default + ) + if reduce_op not in REDUCE_OP_TO_STR: + raise ValueError(f"Unsupported all_reduce op: {reduce_op}") + kwargs["op"] = VariableTracker.build(tx, REDUCE_OP_TO_STR[reduce_op]) + return self.replacement_var.call_function(tx, args, kwargs) + + +class CollectionsNamedTupleFunction(UserFunctionVariable): + def as_python_constant(self) -> Any: + return self.fn + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + constant_args = check_constant_args(args, kwargs) + if constant_args: + try: + value = self.fn( + *[x.as_python_constant() for x in args], + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ) + except TypeError as exc: + raise_observed_exception( + type(exc), + tx, + args=list(exc.args), + ) + return variables.UserDefinedClassVariable( + value, + mutation_type=ValueMutationNew(), + ) + unimplemented( + gb_type="namedtuple construction", + context=f"{args=}, {kwargs=}", + explanation="`torch.compile` only support certain input types for namedtuple", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + +class FunctoolsPartialVariable(VariableTracker): + # partial_type_spec: https://github.com/python/cpython/blob/v3.13.0/Modules/_functoolsmodule.c#L538 + _cpython_type = functools.partial + + _nonvar_fields = { + "original_cache_hash", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + func: VariableTracker, + args: list[VariableTracker], + keywords: dict[str, VariableTracker], + original_cache_hash: Any = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.func = func + if not isinstance(args, list): + raise AssertionError(f"args must be a list, got {type(args)}") + self.args = args + if not isinstance(keywords, dict): + raise AssertionError(f"keywords must be a dict, got {type(keywords)}") + self.keywords = keywords + # Store cache_hash from the original partial for SAC context_fn caching + self.original_cache_hash = original_cache_hash + + def tp_richcompare_impl(self, tx, other, op): + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def python_type(self) -> type: + return functools.partial + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen.load_import_from("functools", "partial")) + codegen(self.func) + if self.args: + codegen.foreach(self.args) + if not self.keywords: + codegen.extend_output(create_call_function(len(self.args) + 1, False)) + return + + codegen.foreach(self.keywords.values()) + keys = tuple(self.keywords.keys()) + codegen.extend_output( + codegen.create_call_function_kw(len(keys) + len(self.args) + 1, keys, False) + ) + + def get_function(self) -> Any: + return self.as_python_constant() + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + merged_args = self.args + args + merged_kwargs = {**self.keywords, **kwargs} + return self.func.call_function(tx, merged_args, merged_kwargs) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + # functools.partial uses slots, so attributes are constant + return VariableTracker.build(tx, hasattr(functools.partial(identity), name)) + + # func / args / keywords are read-only members on partial objects. + # https://github.com/python/cpython/blob/v3.13.0/Modules/_functoolsmodule.c#L295-L299 + def _get_func(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.func + + def _get_args(self, tx: "InstructionTranslatorBase") -> VariableTracker: + source = self.source and AttrSource(self.source, "args") + return variables.TupleVariable(self.args, source=source) + + def _get_keywords(self, tx: "InstructionTranslatorBase") -> VariableTracker: + source = self.source and AttrSource(self.source, "keywords") + items = {VariableTracker.build(tx, k): v for k, v in self.keywords.items()} + return variables.ConstDictVariable(items, source=source) + + tp_members = { + "func": Member(_get_func, None), + "args": Member(_get_args, None), + "keywords": Member(_get_keywords, None), + } + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + try: + return super().tp_getattro_impl(tx, name) + except NotImplementedError: + raise_observed_exception(AttributeError, tx, args=[name]) + + def as_python_constant(self) -> Any: + return functools.partial( + self.func.as_python_constant(), + *[arg.as_python_constant() for arg in self.args], + **{k: v.as_python_constant() for k, v in self.keywords.items()}, + ) + + def guard_as_python_constant(self) -> Any: + """Similar to as_python_constant(), but add ID_MATCH guards to try to force things to become constants""" + result = functools.partial( + self.func.guard_as_python_constant(), + *[v.guard_as_python_constant() for v in self.args], + **{k: v.guard_as_python_constant() for k, v in self.keywords.items()}, + ) + # Preserve cache_hash for SAC context_fn caching + if self.original_cache_hash is not None: + result.cache_hash = self.original_cache_hash # type: ignore[missing-attribute] + return result + + +class PolyfilledFunctionVariable(VariableTracker): + _nonvar_fields = { + "fn", + "wrapped_fn", + "traceable_fn", + *VariableTracker._nonvar_fields, + } + + @classmethod + @functools.cache + def _get_polyfill_handlers(cls) -> dict[Callable[..., Any], types.FunctionType]: + return {} + + @classmethod + def create_with_source( + cls, value: Any, source: Source + ) -> "PolyfilledFunctionVariable": + install_guard(source.make_guard(GuardBuilder.CLOSURE_MATCH)) + + return cls(value, source=source) + + def get_value_for_setattr(self) -> object | None: + return self.fn + + def __init__(self, fn: _F, **kwargs: Any) -> None: + super().__init__(**kwargs) + # pyrefly: ignore[invalid-type-var] + self.fn: _F = fn + + handler = self._get_polyfill_handlers().get(fn, fn) + traceable_fn = None + if not callable(handler): + raise AssertionError(f"Polyfill handler {handler} is not callable for {fn}") + for candidate_attr in ( + "__torch_dynamo_polyfill__", # registered polyfill + "__python_implementation__", # self handler from third-party libraries + ): + candidate = getattr(handler, candidate_attr, None) + if candidate: + if not callable(candidate): + raise AssertionError( + f"Polyfill candidate {candidate} is not callable" + ) + traceable_fn = candidate + break + else: + raise RuntimeError( + f"Polyfill handler {handler} does not have a traceable function" + ) + + self.wrapped_fn = handler + # pyrefly: ignore[invalid-type-var] + self.traceable_fn: _F = traceable_fn + + @property + def polyfill_fn(self) -> Callable[..., Any]: + return self.traceable_fn + + def can_constant_fold_through(self) -> bool: + return getattr( + self.wrapped_fn, "__torch_dynamo_can_constant_fold_through__", False + ) + + def get_function(self) -> Any: + return self.as_python_constant() + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if self.can_constant_fold_through() and check_unspec_or_constant_args( + args, kwargs + ): + result = ( + self.fn( # use the original function which is faster than the polyfill + *[x.as_python_constant() for x in args], + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ) + ) + return VariableTracker.build(tx, result) + + # Special case for sum on tuple/list of ints + if ( + self.fn is builtins.sum + and len(args) == 1 + and not kwargs + and isinstance(args[0], (variables.ListVariable, variables.TupleVariable)) + and all( + (x.is_python_constant() and isinstance(x.as_python_constant(), int)) + or (isinstance(x, variables.SymNodeVariable) and x.python_type() is int) + for x in args[0].items + ) + ): + return variables.SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", + torch.sym_sum, + (tuple(a.as_proxy() for a in args[0].items),), + {}, + ), + sym_num=torch.sym_sum( + [ + ( + x.as_python_constant() + if x.is_python_constant() + else x.sym_num # type: ignore[attr-defined] + ) + for x in args[0].items + ] + ), + ) + + traceable_function_variable = VariableTracker.build(tx, self.traceable_fn) + return tx.inline_user_function_return( + traceable_function_variable, + list(args), + dict(kwargs), + ) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "__call__": + return self.call_function(tx, args, kwargs) + + method = getattr(self.fn, name, None) + if not (method or is_function(method)): + raise_type_error(tx, f"Cannot find callable {name} in {self.fn}") + options = {} + if self.source: + options["source"] = AttrSource(self.source, name) + polyfilled_method_variable = PolyfilledFunctionVariable(method, **options) + return polyfilled_method_variable.call_function(tx, args, kwargs) + + def as_python_constant(self) -> Any: + return self.fn + + +class SysFunctionVariable(VariableTracker): + def __init__(self, value: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + def python_type(self) -> type: + return types.BuiltinFunctionType + + def exc_info(self, tx: "InstructionTranslatorBase") -> "variables.TupleVariable": + if len(tx.exn_vt_stack): + exn = tx.exn_vt_stack[-1] + typ = exn.exc_type # type: ignore[union-attr] + tb = exn.tp_getattro_impl(tx, "__traceback__") + items = [VariableTracker.build(tx, typ), exn, tb] + else: + items = [ + ConstantVariable.create(None), + ConstantVariable.create(None), + ConstantVariable.create(None), + ] + return variables.TupleVariable(items) # type: ignore[arg-type] + + def exception(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.exc_info(tx).items[1] + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if self.value is sys.exc_info: + return self.exc_info(tx) + + if self.value is not sys.exception: + raise AssertionError(f"expected sys.exception, got {self.value}") + return self.exception(tx) + + +from torch._higher_order_ops.triton_kernel_wrap import ( + create_tma_experimental_metadata, + create_tma_stable_metadata, + TMADescriptorMetadata, + TritonHOPifier, +) + + +class DynamoTritonHOPifier(TritonHOPifier): + def raise_unsupported(self, msg: str) -> Never: + unimplemented( + gb_type="triton kernel unsupported feature", + context="", + explanation=f"Encountered triton kernel unsupported feature: {msg}", + hints=[], + ) + + def is_callable(self, maybe_callable: VariableTracker) -> bool: + return isinstance( + maybe_callable, (NestedUserFunctionVariable, UserFunctionVariable) + ) + + def get_value(self, val: VariableTracker) -> Any: + return val.value # type: ignore[attr-defined] + + def check_grid(self, grid: "BaseListVariable") -> tuple[torch.fx.proxy.Proxy, ...]: + from .lists import BaseListVariable + + if isinstance(grid, BaseListVariable): + return grid.as_proxy() + else: + unimplemented( + gb_type="unsupported grid type for triton hop check_grid", + context=f"grid type = {type(grid)}", + explanation="`torch.compile` only supports list-like grid for check_grid", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + def call_grid( + self, grid: Any, meta: dict[str, Any], tx: "InstructionTranslatorBase" + ) -> Any: + meta_var = {VariableTracker.build(tx, k): v for k, v in meta.items()} + grid = grid.call_function(tx, [meta_var], {}) + return grid + + # We use this function to wrap call_prune_configs + def call_user_defined_fn( + self, + user_fn: Callable[..., Any], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + tx: Optional["InstructionTranslatorBase"], + variable: Any, + ) -> VariableTracker: + from .builder import SourcelessBuilder + + wrapped_user_function = SourcelessBuilder.create(tx, user_fn) # type: ignore[arg-type] + result = wrapped_user_function.call_function(tx, args, kwargs) + return result + + def wrap_user_defined_obj( + self, + user_obj: Any, + tx: Optional["InstructionTranslatorBase"], + variable: Any, + name: str, + ) -> VariableTracker: + from .builder import VariableBuilder + + if tx is None: + raise AssertionError("tx must not be None") + # Route through VariableBuilder.__call__ so already-tracked mutable + # objects (for example autotuner config lists) are reused instead of + # being registered for mutation twice in the same trace. + wrapped_user_obj = VariableBuilder( + tx, AttrSource(variable.kernel_source, f"{name}") + )(user_obj) + return wrapped_user_obj + + def maybe_unpack_configs( + self, configs: Any, tx: Optional["InstructionTranslatorBase"] + ) -> list[Any]: + # unpack the list of configs + if tx is None: + raise AssertionError("tx must not be None") + configs = unpack_iterable(tx, configs) + + # guard_as_python_constant inserts guards for Dynamo to check if the configs object changed. + configs = [config.guard_as_python_constant() for config in configs] + + return configs + + def maybe_unpack_heuristic_result(self, result: VariableTracker) -> Any: + if not result.is_python_constant(): + self.raise_unsupported( + "@triton.heuristics must return constant values because configs can only contain constant values." + ) + + return result.guard_as_python_constant() + + # We need to override call_getitem here so that we can add the source in the case + # where we call the triton kernel with a grid + def call_getitem( # type: ignore[override] + self, + variable: "TritonKernelVariable", + args: Sequence[Any], + ) -> "TritonKernelVariable": + # __getitem__ should only be called if we don't already have a grid + # Only grid needs to be passed + if variable.grid is not None or len(args) != 1: + self.raise_unsupported( + "Triton kernels should be called with only a single grid" + ) + return type(variable)( + kernel=variable.kernel, + kernel_idx=variable.kernel_idx, + grid=args[0], + kernel_source=variable.kernel_source, + ) + + def call_HOP( + self, + variable: "TritonKernelVariable", + grids: Any, + combined_args: dict[str, Any], + launch_kwargs: tuple[str, ...], + kernel_arg_names: set[str], + tx: "InstructionTranslatorBase", + ) -> ConstantVariable | None: + from .dicts import ConstDictVariable + + # as we can only pass tensors as non-const args in fx graph, + # here we replace TMA descriptors + # (TMADescriptorExperimentalVariable and TMADescriptorStableVariable + # instances) with the underlying tensors, while moving the + # TMA descriptor-related metadata to a separate argument, + # so that we can reconstruct the TMA descriptors downstream + tma_descriptor_metadata: TMADescriptorMetadata = {} + for k in list(combined_args.keys()): + v = combined_args[k] + if isinstance( + v, (TMADescriptorExperimentalVariable, TMADescriptorStableVariable) + ): + tma_descriptor_metadata[k] = v.to_metadata() + combined_args[k] = v.get_tensor() + + combined_args_vt = { + VariableTracker.build(tx, k): v for k, v in combined_args.items() + } + + from torch._higher_order_ops.triton_kernel_wrap import ( + kernel_side_table, + triton_kernel_wrapper_mutation, + ) + + # Combine args and kwargs and pass as a dict so that if user defined triton + # kernel uses variables as 'grid' or 'kernel', it does not conflict with + # parameters of the wrapper function + constant_args = { + k: v.as_python_constant() + for k, v in combined_args.items() + if isinstance(v, VariableTracker) and v.is_python_constant() + } + non_constant_args = { + k: v + for k, v in combined_args_vt.items() + if not (isinstance(v, VariableTracker) and v.is_python_constant()) + } + # launch_kwargs records the names passed as kwargs at the Triton launch + # site. A non-kernel launch kwarg can only be a compiler option, so it + # must be a Python constant before entering the graph. Kernel launch + # kwargs may also be compiler options, but that target-specific check + # happens in Inductor after the triton backend is determined and + # backend.parse_options() is called. + non_const_options: list[str] = [] + for k in launch_kwargs: + if k in kernel_arg_names: + continue + v = combined_args[k] + if not (isinstance(v, VariableTracker) and v.is_python_constant()): + non_const_options.append(k) + if non_const_options: + self.raise_unsupported( + "Triton backend options must be Python constants: " + f"{sorted(non_const_options)!r}." + ) + + for v in non_constant_args.values(): + v = v.realize() + if not (v.is_tensor() or v.is_symnode_like()): + self.raise_unsupported( + f"Unexpected argument type for a Triton kernel: {repr(v)}." + ) + + constant_args_idx = kernel_side_table.add_constant_args(constant_args) + meta = ConstDictVariable(non_constant_args) + tx.output.create_proxy( + "call_function", + triton_kernel_wrapper_mutation, + (), + { + "kernel_idx": variable.kernel_idx, + "constant_args_idx": constant_args_idx, + "grid": grids, + "tma_descriptor_metadata": tma_descriptor_metadata, + "kwargs": meta.as_proxy(), + "launch_kwargs": launch_kwargs, + }, + ) + + return VariableTracker.build( + tx, + None, + ) + + +dynamo_triton_hopifier_singleton = DynamoTritonHOPifier() + + +class TritonKernelVariable(VariableTracker): + grid: "TritonGridType" + kernel: "TritonKernelType" + kernel_idx: int | None + kernel_source: Source | None + + def __init__( + self, kernel: Any, kernel_idx: int | None, grid: Any, **kwargs: Any + ) -> None: + self.kernel_source = kwargs.pop("kernel_source", kwargs.get("source")) + super().__init__(**kwargs) + dynamo_triton_hopifier_singleton.init_variable(self, kernel, kernel_idx, grid) + + def python_type(self) -> type: + return type(self.kernel) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return dynamo_triton_hopifier_singleton.call_triton_kernel( # type: ignore[return-value] + self, args, kwargs, tx + ) + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # Triton kernel[grid] — triton-specific, not a CPython slot. + return dynamo_triton_hopifier_singleton.call_getitem(self, [key]) + + def run( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return dynamo_triton_hopifier_singleton.call_run(self, args, kwargs, tx) # type: ignore[return-value] + + def specialize_symbolic(self, arg: Any) -> Any: + from .constant import ConstantVariable + from .tensor import SymNodeVariable + + # See [Note: Specialize tl.constexpr args in user-defined triton kernels] + if isinstance(arg, SymNodeVariable): + return ConstantVariable.create(arg.evaluate_expr()) + return arg + + tp_methods = {"run": Method(run)} + + +class TMADescriptorExperimentalVariable(VariableTracker): + def __init__( + self, + data_ptr: "variables.DataPtrVariable", + dims: list[VariableTracker], + block_dims: list[VariableTracker], + element_size: VariableTracker, + **kwargs: Any, + ) -> None: + if not isinstance(data_ptr, variables.DataPtrVariable): + raise AssertionError( + f"data_ptr must be a DataPtrVariable, got {type(data_ptr)}" + ) + super().__init__(**kwargs) + self.data_ptr = data_ptr + self.dims = dims + self.block_dims = block_dims + self.element_size = element_size + + def to_metadata(self) -> Any: + return create_tma_experimental_metadata( + [dim.as_proxy() for dim in self.dims], + [dim.as_proxy() for dim in self.block_dims], + self.element_size.as_proxy(), + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from( + "triton.tools.experimental_descriptor", + f"create_{len(self.dims)}d_tma_descriptor", + ) + ) + self.data_ptr.reconstruct(codegen) + args = [*self.dims, *self.block_dims, self.element_size] + codegen.foreach(args) + codegen.call_function(len(args) + 1, False) + + def get_tensor(self) -> VariableTracker: + return self.data_ptr.from_tensor + + +class TMADescriptorStableVariable(VariableTracker): + def __init__( + self, + tensor: "TensorVariable", + block_shape: "ListVariable", + **kwargs: Any, + ) -> None: + if not tensor.is_tensor(): + raise AssertionError("tensor argument must be a tensor") + super().__init__(**kwargs) + self.tensor = tensor + self.block_shape = block_shape + + def to_metadata(self) -> Any: + return create_tma_stable_metadata( + self.block_shape.as_proxy(), + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from( + "triton.tools.tensor_descriptor", + "TensorDescriptor", + ) + ) + codegen.load_method("from_tensor") + self.tensor.reconstruct(codegen) + codegen(self.block_shape) + codegen.call_method(2) + + def get_tensor(self) -> Any: + return self.tensor + + +class CreateTMADescriptorExperimentalVariable(VariableTracker): + def __init__( + self, + rank: int, + **kwargs: Any, + ) -> None: + if rank not in (1, 2): + raise AssertionError(f"rank must be 1 or 2, got {rank}") + super().__init__(**kwargs) + self.rank = rank + + def python_type(self) -> type: + return types.FunctionType + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + ptr = kwargs["ptr"] if "ptr" in kwargs else args[0] + + if not isinstance(ptr, variables.DataPtrVariable): + unimplemented( + gb_type="invalid ptr argument for create_tma_descriptor", + context=f"args = {args}, kwargs = {kwargs}", + explanation=f"Expected `ptr` argument of `create_{self.rank}d_tma_descriptor`" + "to be from a `.data_ptr()` call, represented internally by `DataPtrVariable`", + hints=[ + "`torch.compile` may fail to internally represent result of `.data_ptr()` " + "with `DataPtrVariable` due to a graph break between the `.data_ptr()` call and " + f"`create_{self.rank}d_tma_descriptor`. Please ensure there were no graph breaks " + "between these two calls.", + ], + ) + + if self.rank == 1: + if len(args) + len(kwargs) != 4: + raise_type_error( + tx, + f"TMA metadata rank=1 requires exactly 4 arguments, got {len(args) + len(kwargs)}", + ) + dims = [ + kwargs["dim"] if "dim" in kwargs else args[1], + ] + block_dims = [ + kwargs["block_dim"] if "block_dim" in kwargs else args[2], + ] + else: + if len(args) + len(kwargs) != 6: + raise_type_error( + tx, + f"TMA metadata rank=2 requires exactly 6 arguments, got {len(args) + len(kwargs)}", + ) + dims = [ + kwargs["dim1"] if "dim1" in kwargs else args[1], + kwargs["dim0"] if "dim0" in kwargs else args[2], + ] + block_dims = [ + kwargs["block_dim1"] if "block_dim1" in kwargs else args[3], + kwargs["block_dim0"] if "block_dim0" in kwargs else args[4], + ] + element_size = kwargs["element_size"] if "element_size" in kwargs else args[-1] + + # to make pyrefy happy + if not isinstance(ptr, variables.DataPtrVariable): + raise AssertionError(f"ptr must be a DataPtrVariable, got {type(ptr)}") + + return TMADescriptorExperimentalVariable( + data_ptr=ptr, + dims=dims, + block_dims=block_dims, + element_size=element_size, + ) + + +class CreateTMADescriptorStableVariable(VariableTracker): + def python_type(self) -> type: + return types.FunctionType + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + tensor = kwargs["tensor"] if "tensor" in kwargs else args[0] + block_shape = kwargs["block_shape"] if "block_shape" in kwargs else args[1] + + return TMADescriptorStableVariable( + tensor=tensor, # type: ignore[arg-type] + block_shape=block_shape, # type: ignore[arg-type] + ) + + +class PyTreeGetNodeTypeFunctionVariable(UserFunctionVariable): + """ + `torch.utils._pytree._get_node_type` function is very hot function. We want to special case it to reduce Dynamo tracing time. + + def _get_node_type(tree: Any) -> Any: + node_type = type(tree) + # All namedtuple types are implicitly registered as pytree nodes. + # XXX: Other parts of the codebase expect namedtuple types always return + # `namedtuple` instead of the actual namedtuple type. Even if the type + # is explicitly registered. + if is_namedtuple_class(node_type): + return collections.namedtuple + return node_type + """ + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if len(args) != 1: + raise_type_error( + tx, f"pytree_get_node_type requires exactly 1 argument, got {len(args)}" + ) + type_source = None + if args[0].source: + install_guard(args[0].source.make_guard(GuardBuilder.TYPE_MATCH)) + type_source = TypeSource(args[0].source) + python_type = args[0].python_type() + if is_namedtuple_class(python_type): + collections_source = ImportSource("collections") + install_guard(collections_source.make_guard(GuardBuilder.ID_MATCH)) + type_source = AttrSource(collections_source, "namedtuple") + return VariableTracker.build( + tx, vars(collections)["namedtuple"], type_source + ) + return VariableTracker.build(tx, python_type, source=type_source) + + +class PyTreeTreeIsLeafFunctionVariable(UserFunctionVariable): + """ + `torch.utils._pytree.tree_is_leaf` function is a hot function. We want to special case it to reduce Dynamo tracing time. + + def tree_is_leaf( + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, + ) -> bool: + if is_leaf is not None and is_leaf(tree): + return True + return _get_node_type(tree) not in SUPPORTED_NODES + + When is_leaf is None (the common case), we can optimize by not tracing into the function. + When is_leaf is not None, we fall back to regular tracing since it requires executing user code. + """ + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # tree_is_leaf(tree, is_leaf=None) + if len(args) < 1 or len(args) > 2: + raise_type_error( + tx, f"tree_is_leaf requires 1 or 2 arguments, got {len(args)}" + ) + + # Check if is_leaf parameter is provided + is_leaf = kwargs.get("is_leaf", ConstantVariable.create(None)) + if len(args) == 2: + is_leaf = args[1] + + if not is_leaf.is_constant_none(): + return super().call_function(tx, args, kwargs) + + # Optimize the case where is_leaf is None + # return _get_node_type(tree) not in SUPPORTED_NODES + tree = args[0] + node_type_var = PyTreeGetNodeTypeFunctionVariable( + torch.utils._pytree._get_node_type + ).call_function(tx, [tree], {}) + + # If the SUPPORTED_NODES was seen earlier and mutated, there would be a + # source and that will give us the mutated SUPPORTED_NODES. + # get_pytree_SUPPORTED_NODES_source is cached, so install its + # ImportSource("torch") ID_MATCH guard here. + install_guard(ImportSource("torch").make_guard(GuardBuilder.ID_MATCH)) + supported_nodes_var = VariableTracker.build( + tx, + torch.utils._pytree.SUPPORTED_NODES, + source=get_pytree_SUPPORTED_NODES_source(), + ) + out = supported_nodes_var.call_method(tx, "__contains__", [node_type_var], {}) + return VariableTracker.build(tx, not out.value) + + +class SparseTensorCreationSkipVariable(SkipFunctionVariable): + """ + Skip variable for sparse tensor factory functions with clear messaging regarding lack of support. + """ + + def __init__(self, value: Any, **kwargs: Any) -> None: + reason = "sparse tensor creation is not supported in torch.compile" + super().__init__(value, reason=reason, **kwargs) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .. import graph_break_hints + + fn_name = getattr(self.value, "__name__", str(self.value)) + unimplemented( + gb_type="Sparse tensor creation not supported", + context=f"function: {fn_name}", + explanation=( + f"torch.compile does not support sparse tensor creation functions like {fn_name}. " + "Sparse tensors require specialized handling that is not yet implemented in the compiler." + ), + hints=[*graph_break_hints.SPARSE_TENSOR], + ) + + +def emit_noargs_leaf_function_to_graph( + tx: "InstructionTranslatorBase", + real_impl: Callable[[], None], + name: str, +) -> None: + """Emit an invoke_leaf_function node for a side-effectful function with no + tensor inputs or outputs. + + The function is captured as a closure inside _LeafCallable objects and + registered as a static attribute on the graph module. Because + invoke_leaf_function is registered as EffectType.ORDERED, effect tokens + prevent DCE and maintain execution ordering relative to other ops. + + Use this when Dynamo needs to preserve a pure-side-effect call (like + setting global runtime state) in the compiled graph so that it replays + at the correct position at runtime. + """ + import torch.utils._pytree as pytree + from torch._higher_order_ops.invoke_leaf_function import ( + _LeafCallable, + invoke_leaf_function, + make_leaf_function_wrappers, + ) + + def fake_impl(): + return None + + captured_out_spec: list[pytree.TreeSpec | None] = [None] + wrapped_real, wrapped_fake = make_leaf_function_wrappers( + real_impl, fake_impl, captured_out_spec + ) + + real_callable = _LeafCallable(wrapped_real) + fake_callable = _LeafCallable(wrapped_fake) + input_spec = pytree.tree_flatten(((), {}))[1] + + def make_proxy(attr_name: str, val: Any) -> Any: + proxy = tx.output.register_static_attr_and_return_proxy(attr_name, val) + proxy.node.type = type(val) + return proxy + + invoke_args = ( + make_proxy(f"{name}_real_fn", real_callable), + make_proxy(f"{name}_fake_fn", fake_callable), + make_proxy(f"{name}_input_spec", input_spec), + "", # mutated_flat_indices + ) + tx.output.create_proxy("call_function", invoke_leaf_function, invoke_args, {}) + + +class TritonSetAllocatorVariable(VariableTracker): + """Trace triton.set_allocator as an invoke_leaf_function node in the + graph so that it executes at the right point at runtime, ordered by + effect tokens.""" + + def __init__(self, value: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + def python_type(self) -> type: + return type(self.value) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if len(args) != 1: + raise AssertionError(f"expected exactly 1 arg, got {len(args)}") + if kwargs: + raise AssertionError("unexpected kwargs") + alloc_fn = args[0].as_python_constant() + + # Emit an invoke_leaf_function node so it runs at runtime. + set_allocator = self.value + + def real_impl(): + set_allocator(alloc_fn) + return None + + emit_noargs_leaf_function_to_graph(tx, real_impl, "set_alloc") + + return ConstantVariable.create(None) + + +# --------------------------------------------------------------------------- +# CPython descriptor VTs +# +# Each class mirrors a CPython descriptor type (PyWrapperDescr_Type, +# PyMethodDescr_Type, etc.) and implements tp_descr_get_impl to model +# the descriptor binding step faithfully. +# --------------------------------------------------------------------------- + + +def _check_descriptor_obj_type( + tx: "InstructionTranslatorBase", + descriptor: types.MethodDescriptorType + | types.WrapperDescriptorType + | types.MemberDescriptorType + | types.GetSetDescriptorType, + obj: "VariableTracker", +) -> None: + """Check that obj's type is compatible with descriptor.__objclass__. + + Mirrors CPython's descr_check which raises TypeError when a C descriptor + is bound to an object whose type is not a subtype of the descriptor's + __objclass__. + + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L79-L96 + """ + if obj is None: + return + try: + obj_type = obj.python_type() + except NotImplementedError: + return + if not issubclass(obj_type, descriptor.__objclass__): + raise_type_error( + tx, + f"descriptor '{descriptor.__name__}' for " + f"'{descriptor.__objclass__.__name__}' objects " + f"doesn't apply to a '{obj_type.__name__}' object", + ) + + +# descr_members: __objclass__ and __name__ are PyMemberDef on all descriptor +# types. https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L641-L645 +class WrapperDescriptorVariable(VariableTracker): + """Unbound C slot wrapper (wrapper_descriptor on a type). + + CPython types define behavior through C-level slots on PyTypeObject + (tp_richcompare, sq_length, nb_add, etc.). When these slots are + accessed from Python (e.g. list.__add__), CPython exposes them as + wrapper_descriptor objects (PyWrapperDescr_Type). A wrapper_descriptor + is an unbound descriptor living on the type -- it is not tied to any + instance. + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L867 + + When a wrapper_descriptor is accessed on an instance (e.g. [1,2].__add__), + its tp_descr_get slot (wrapperdescr_get) is invoked, which calls + PyWrapper_New to produce a bound method-wrapper (_PyMethodWrapper_Type). + The tp_descr_get_impl method on this class mirrors that binding step. + """ + + _nonvar_fields = { + "descriptor", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + descriptor: types.WrapperDescriptorType, + owner: VariableTracker, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.descriptor = descriptor + self.owner = owner + + def __repr__(self) -> str: + cls_name = self.descriptor.__objclass__.__name__ + return f"WrapperDescriptorVariable({cls_name}.{self.descriptor.__name__})" + + def python_type(self) -> type: + return types.WrapperDescriptorType + + def as_python_constant(self) -> types.WrapperDescriptorType: + return self.descriptor + + def get_real_python_backed_value(self) -> types.WrapperDescriptorType: + return self.descriptor + + tp_members = { + "__objclass__": Member(getset_build(lambda s: s.descriptor.__objclass__)), + "__name__": Member(getset_build(lambda s: s.descriptor.__name__)), + } + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Unbound call: list.__add__([1,2], [3,4]) -- first arg is self. + # Mirrors wrapperdescr_call which invokes the C slot directly. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L535 + if not args: + raise_type_error( + tx, + f"descriptor '{self.descriptor.__name__}' of " + f"'{self.descriptor.__objclass__.__name__}' object needs an argument", + ) + obj, *rest = args + _check_descriptor_obj_type(tx, self.descriptor, obj) + # Dispatch through the owner (UDCV for the defining class) rather + # than obj.call_method, which would do MRO resolution from type(obj) + # and find Python overrides on subclasses. Routing through the class + # mirrors CPython's wrapperdescr_call which invokes the C slot directly. + return self.owner.call_method( + tx, self.descriptor.__name__, [obj, *rest], kwargs + ) + + def tp_descr_get_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + owner: VariableTracker, + ) -> "MethodWrapperVariable": + # Mirrors wrapperdescr_get which calls PyWrapper_New to produce + # a bound method-wrapper. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L203-L213 + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L1489-L1505 + _check_descriptor_obj_type(tx, self.descriptor, obj) + return MethodWrapperVariable(self.descriptor, obj, source=self.source) + + +class MethodWrapperVariable(VariableTracker): + """Bound method-wrapper (wrapper_descriptor bound to an instance). + + Produced by WrapperDescriptorVariable.tp_descr_get_impl, mirroring + PyWrapper_New which stores a reference to the descriptor and the instance. + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L1450 + """ + + _nonvar_fields = { + "descriptor", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + descriptor: types.WrapperDescriptorType, + obj: VariableTracker, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.descriptor = descriptor + self.obj = obj + + def __repr__(self) -> str: + cls_name = self.descriptor.__objclass__.__name__ + return ( + f"MethodWrapperVariable({cls_name}.{self.descriptor.__name__}, {self.obj})" + ) + + def python_type(self) -> type: + return types.MethodWrapperType + + # A method-wrapper's own dunders come from the descriptor / bound obj and do + # not depend on obj's contents. Resolving them via these tables (consulted + # before the generic getset-descriptor path) avoids forcing self.obj to a + # python constant, which would break e.g. a list holding non-constant items. + tp_getset = { + "__name__": GetSet( + lambda s, tx: ConstantVariable.create(s.descriptor.__name__) + ), + "__qualname__": GetSet( + lambda s, tx: ConstantVariable.create(s.descriptor.__qualname__) + ), + } + tp_members = { + "__self__": Member(lambda s, tx: s.obj), + } + + def get_real_python_backed_value(self) -> types.MethodWrapperType: + return self.as_python_constant() + + def is_python_constant(self) -> bool: + return self.obj.is_python_constant() + + def as_python_constant(self) -> types.MethodWrapperType: + obj_value = self.obj.as_python_constant() + try: + return self.descriptor.__get__(obj_value, type(obj_value)) + except TypeError: + raise AsPythonConstantNotImplementedError(self) from None + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Only materialize the wrapper (which forces self.obj's python constant) + # for the tensor-getter special case; the generic path below dispatches + # via call_method and must not require a constant self.obj (e.g. a set / + # frozenset whose as_python_constant() re-hashes its keys). + if args and isinstance(args[0], variables.TensorVariable): + try: + method_wrapper = self.as_python_constant() + except NotImplementedError: + method_wrapper = None + if method_wrapper is not None and is_tensor_base_attr_getter( + method_wrapper + ): + if not (len(args) == 1 and len(kwargs) == 0): + raise_type_error( + tx, "tensor attribute getter takes exactly one argument" + ) + # Avoid the generic descriptor path's implicit owner lookup, which + # would read __class__ on tensor subclasses during __torch_function__. + descriptor = cast(Any, method_wrapper.__self__) + return args[0].tp_getattro_impl(tx, descriptor.__name__) + + return self.obj.call_method(tx, self.descriptor.__name__, list(args), kwargs) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.obj) + codegen.extend_output(codegen.create_load_attrs(self.descriptor.__name__)) + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + try: + # CPython wrapper_hash: + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L1347 + return hash(self.as_python_constant()), False + except NotImplementedError: + return super().hash_impl(tx) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: "VariableTracker", op: str + ) -> "VariableTracker": + from .object_protocol import python_constant_richcompare_impl + + return python_constant_richcompare_impl(self, tx, other, op) + + +class MethodDescriptorVariable(VariableTracker): + """Unbound C method descriptor (method_descriptor on a type). + + CPython types expose their PyMethodDef-based C methods as + method_descriptor objects (PyMethodDescr_Type) in the type's tp_dict. + For example, list.append and dict.get are method_descriptors. Like + wrapper_descriptors, these are unbound descriptors living on the type. + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L716 + + When a method_descriptor is accessed on an instance (e.g. [].append), + its tp_descr_get slot (method_get) is invoked, which calls + PyCFunction_NewEx to produce a bound builtin_function_or_method + (PyCFunction_Type). The tp_descr_get_impl method mirrors that step. + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L137-L159 + """ + + _nonvar_fields = { + "descriptor", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + descriptor: types.MethodDescriptorType, + owner: VariableTracker, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.descriptor = descriptor + self.owner = owner + + def __repr__(self) -> str: + cls_name = self.descriptor.__objclass__.__name__ + return f"MethodDescriptorVariable({cls_name}.{self.descriptor.__name__})" + + def python_type(self) -> type: + return types.MethodDescriptorType + + def as_python_constant(self) -> types.MethodDescriptorType: + return self.descriptor + + def get_real_python_backed_value(self) -> types.MethodDescriptorType: + return self.descriptor + + tp_members = { + "__objclass__": Member(getset_build(lambda s: s.descriptor.__objclass__)), + "__name__": Member(getset_build(lambda s: s.descriptor.__name__)), + } + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Mirrors methoddescr_call which invokes the C method directly. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L427 + if not args: + raise_type_error( + tx, + f"descriptor '{self.descriptor.__name__}' of " + f"'{self.descriptor.__objclass__.__name__}' object needs an argument", + ) + obj, *rest = args + name = self.descriptor.__name__ + _check_descriptor_obj_type(tx, self.descriptor, obj) + # Dispatch through the owner (UDCV for the defining class) rather + # than obj.call_method, which would do MRO resolution from type(obj) + # and find Python overrides on subclasses. + return self.owner.call_method(tx, name, [obj, *rest], kwargs) + + def tp_descr_get_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + owner: VariableTracker, + ) -> "BoundBuiltinMethodVariable": + # Mirrors method_get which calls PyCFunction_NewEx to produce a + # bound builtin_function_or_method. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L137-L159 + # https://github.com/python/cpython/blob/3.13/Objects/methodobject.c#L40 + _check_descriptor_obj_type(tx, self.descriptor, obj) + return BoundBuiltinMethodVariable(self.descriptor, obj, source=self.source) + + +class BoundBuiltinMethodVariable(VariableTracker): + """Bound builtin_function_or_method (PyCFunction_Type). + + Produced by MethodDescriptorVariable.tp_descr_get_impl (binding a + method_descriptor to an instance, e.g. [].append) or created by the + builder for bound C methods (e.g. frozenset().__contains__, + tuple.__new__). The backing descriptor can be a MethodDescriptorType + or a BuiltinFunctionType (for methods stored directly in type dicts). + https://github.com/python/cpython/blob/3.13/Objects/methodobject.c#L331 + """ + + _nonvar_fields = { + "descriptor", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + descriptor: types.MethodDescriptorType + | types.BuiltinFunctionType + | types.ClassMethodDescriptorType, + obj: VariableTracker, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.descriptor = descriptor + self.obj = obj + + def __repr__(self) -> str: + cls_name = getattr( + getattr(self.descriptor, "__objclass__", None), "__name__", "?" + ) + return f"BoundBuiltinMethodVariable({cls_name}.{self.descriptor.__name__}, {self.obj})" + + def python_type(self) -> type: + return types.BuiltinMethodType + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # meth_hash: https://github.com/python/cpython/blob/e76aa128fe/Objects/methodobject.c#L319 + try: + return hash(self.as_python_constant()), False + except AsPythonConstantNotImplementedError: + return id(self), True + + def tp_richcompare_impl(self, tx, other, op): + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def as_python_constant(self) -> Any: + obj = self.obj.as_python_constant() + if isinstance(self.descriptor, types.ClassMethodDescriptorType): + return self.descriptor.__get__(None, obj) + if hasattr(self.descriptor, "__get__"): + return self.descriptor.__get__(obj) # type: ignore[union-attr] + return getattr(obj, self.descriptor.__name__) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self.obj.call_method(tx, self.descriptor.__name__, list(args), kwargs) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.obj) + codegen.extend_output(codegen.create_load_attrs(self.descriptor.__name__)) + + +class ClassMethodDescriptorVariable(VariableTracker): + """C-level classmethod descriptor (classmethod_descriptor on a type). + + CPython exposes C classmethods defined via PyMethodDef with METH_CLASS + as classmethod_descriptor objects (PyClassMethodDescr_Type). For + example, dict.fromkeys is a classmethod_descriptor. Like + method_descriptor, these live on the type and are unbound. + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L756 + + classmethod_get binds the C method to the class (ignoring obj) via + PyCMethod_New, producing a bound builtin_function_or_method. + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L94-L134 + """ + + _nonvar_fields = { + "descriptor", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + descriptor: types.ClassMethodDescriptorType, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.descriptor = descriptor + + def __repr__(self) -> str: + cls_name = self.descriptor.__objclass__.__name__ + return f"ClassMethodDescriptorVariable({cls_name}.{self.descriptor.__name__})" + + def python_type(self) -> type: + return types.ClassMethodDescriptorType + + def as_python_constant(self) -> types.ClassMethodDescriptorType: + return self.descriptor + + def get_real_python_backed_value(self) -> types.ClassMethodDescriptorType: + return self.descriptor + + tp_members = { + "__objclass__": Member(getset_build(lambda s: s.descriptor.__objclass__)), + "__name__": Member(getset_build(lambda s: s.descriptor.__name__)), + } + + def tp_descr_get_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + owner: VariableTracker, + ) -> BoundBuiltinMethodVariable: + # classmethod_get binds the C method to the class (ignoring obj), + # producing a builtin_function_or_method via PyCMethod_New. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L94-L134 + return BoundBuiltinMethodVariable(self.descriptor, owner, source=self.source) + + +class StaticMethodVariable(VariableTracker): + """staticmethod descriptor wrapping a callable. + + CPython's staticmethod (PyStaticMethod_Type) is a non-data descriptor + whose tp_descr_get (sm_descr_get) simply returns the wrapped callable, + ignoring both obj and type. + https://github.com/python/cpython/blob/3.13/Objects/funcobject.c#L1520 + https://github.com/python/cpython/blob/3.13/Objects/funcobject.c#L1418-L1428 + """ + + _nonvar_fields = { + "descriptor", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + descriptor: staticmethod, # type: ignore[type-arg] + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.descriptor = descriptor + + def __repr__(self) -> str: + func_name = getattr(self.descriptor.__func__, "__name__", "?") + return f"StaticMethodVariable({func_name})" + + def python_type(self) -> type: + return staticmethod + + def as_python_constant(self) -> staticmethod: # type: ignore[type-arg] + return self.descriptor + + def tp_descr_get_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker | None, + owner: VariableTracker, + ) -> VariableTracker: + # sm_descr_get returns sm->sm_callable unconditionally. + # https://github.com/python/cpython/blob/3.13/Objects/funcobject.c#L1418-L1428 + func_source = AttrSource(self.source, "__func__") if self.source else None + return VariableTracker.build(tx, self.descriptor.__func__, func_source) + + +class ClassMethodVariable(VariableTracker): + """classmethod descriptor wrapping a callable. + + CPython's classmethod (PyClassMethod_Type) is a non-data descriptor + whose tp_descr_get (cm_descr_get) creates a bound method of the + wrapped callable bound to the class (via PyMethod_New). + https://github.com/python/cpython/blob/3.13/Objects/funcobject.c#L1314 + https://github.com/python/cpython/blob/3.13/Objects/funcobject.c#L1215-L1227 + """ + + _nonvar_fields = { + "descriptor", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + descriptor: classmethod, # type: ignore[type-arg] + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.descriptor = descriptor + + def __repr__(self) -> str: + func_name = getattr(self.descriptor.__func__, "__name__", "?") + return f"ClassMethodVariable({func_name})" + + def python_type(self) -> type: + return classmethod + + def as_python_constant(self) -> classmethod: # type: ignore[type-arg] + return self.descriptor + + def tp_descr_get_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + owner: VariableTracker, + ) -> VariableTracker: + # cm_descr_get binds the wrapped function to the class. + # https://github.com/python/cpython/blob/3.13/Objects/funcobject.c#L1215-L1227 + func_source = AttrSource(self.source, "__func__") if self.source else None + bound_source = ( + AttrSource(owner.source, self.descriptor.__func__.__name__) + if owner.source + else None + ) + return UserMethodVariable( + self.descriptor.__func__, + owner, + source_fn=func_source, + source=bound_source, + ) + + +class MemberDescriptorVariable(VariableTracker): + """C struct field descriptor (member_descriptor on a type). + + CPython exposes C struct fields defined via PyMemberDef as + member_descriptor objects (PyMemberDescr_Type). These are data + descriptors used by __slots__ and C extension types to provide + direct access to struct members. + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L793 + + member_get reads the field via PyMember_GetOne. + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L162-L180 + """ + + _nonvar_fields = { + "descriptor", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + descriptor: types.MemberDescriptorType, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.descriptor = descriptor + + def __repr__(self) -> str: + cls_name = self.descriptor.__objclass__.__name__ + return f"MemberDescriptorVariable({cls_name}.{self.descriptor.__name__})" + + def python_type(self) -> type: + return types.MemberDescriptorType + + def as_python_constant(self) -> types.MemberDescriptorType: + return self.descriptor + + tp_members = { + "__objclass__": Member(getset_build(lambda s: s.descriptor.__objclass__)), + "__name__": Member(getset_build(lambda s: s.descriptor.__name__)), + } + + def tp_descr_get_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + owner: VariableTracker, + ) -> VariableTracker: + # Mirrors member_get which calls PyMember_GetOne to read the + # C struct field. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L162-L180 + _check_descriptor_obj_type(tx, self.descriptor, obj) + from .object_protocol import _UnhandledDescriptorError + + attr_name = self.descriptor.__name__ + obj_value = obj.get_real_python_backed_value() + if obj_value is NO_SUCH_SUBOBJ: + raise _UnhandledDescriptorError( + f"Cannot resolve member_descriptor '{attr_name}' " + f"on {type(obj).__name__}" + ) + try: + resolved = self.descriptor.__get__(obj_value, type(obj_value)) + except (AttributeError, TypeError): + raise_observed_exception( + AttributeError, + tx, + args=[ + f"'{type(obj_value).__name__}' object has no attribute '{attr_name}'" + ], + ) + result_source = obj.source and AttrSource(obj.source, attr_name) + return VariableTracker.build(tx, resolved, result_source) + + def tp_descr_set_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + # Mirrors member_set (PyMember_SetOne): store into the C struct field. + # STORE_ATTR itself applies the descriptor, so replay via store_attr on + # the target (mirrors the __slots__ path in UserDefinedObjectVariable). + # value is None for __delete__. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L180-L196 + stored = variables.DeletedVariable() if value is None else value + tx.output.side_effects.store_attr(obj, self.descriptor.__name__, stored) + return variables.ConstantVariable.create(None) + + +class GetSetDescriptorVariable(VariableTracker): + """C getter/setter descriptor (getset_descriptor on a type). + + CPython exposes C getter/setter pairs defined via PyGetSetDef as + getset_descriptor objects (PyGetSetDescr_Type). These are data + descriptors used for computed attributes backed by C functions + (e.g. object.__class__, type.__dict__). + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L830 + + getset_get calls the C getter function. + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L183-L197 + """ + + _nonvar_fields = { + "descriptor", + *VariableTracker._nonvar_fields, + } + + def __init__(self, descriptor: types.GetSetDescriptorType, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.descriptor = descriptor + + def __repr__(self) -> str: + cls_name = self.descriptor.__objclass__.__name__ + return f"GetSetDescriptorVariable({cls_name}.{self.descriptor.__name__})" + + def get_real_python_backed_value(self) -> types.GetSetDescriptorType: + return self.descriptor + + def _getset_descriptor_get( + self, tx: "InstructionTranslatorBase" + ) -> "VariableTracker | None": + if self.source is None: + return None + source = AttrSource(self.source, "__get__") + return VariableTracker.build(tx, self.descriptor.__get__, source) + + tp_getset = { + "__get__": GetSet(_getset_descriptor_get, None), + } + + tp_members = { + "__objclass__": Member(getset_build(lambda s: s.descriptor.__objclass__)), + "__name__": Member(getset_build(lambda s: s.descriptor.__name__)), + } + + def is_python_constant(self) -> bool: + return True + + def as_python_constant(self) -> types.GetSetDescriptorType: + return self.descriptor + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: "VariableTracker", op: str + ) -> "VariableTracker": + from .object_protocol import python_constant_richcompare_impl + + return python_constant_richcompare_impl(self, tx, other, op) + + def tp_descr_get_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + owner: VariableTracker, + ) -> VariableTracker: + # Mirrors getset_get which calls the C getter function. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L183-L197 + attr_name = self.descriptor.__name__ + # Try to eagerly call the C getter when we can obtain the + # concrete Python object (UDOV.value, or as_python_constant + # for classes/constants). Fall back to tp_getattro_impl for + # proxy-based VTs like TensorVariable. + _check_descriptor_obj_type(tx, self.descriptor, obj) + obj_value = obj.get_real_python_backed_value() + if obj_value is NO_SUCH_SUBOBJ: + from .object_protocol import _UnhandledDescriptorError + + raise _UnhandledDescriptorError( + f"Cannot resolve getset_descriptor '{attr_name}' " + f"on {type(obj).__name__}" + ) + try: + resolved = self.descriptor.__get__(obj_value, type(obj_value)) + except (AttributeError, TypeError): + raise_observed_exception( + AttributeError, + tx, + args=[ + f"'{type(obj_value).__name__}' object has no attribute '{attr_name}'" + ], + ) + result_source = obj.source and AttrSource(obj.source, attr_name) + if ( + obj.source + and self.descriptor.__objclass__ is type + and attr_name in ("__annotations__", "__dict__", "__mro__") + ): + # Direct descriptor calls still resolve the standard type slot even + # when a metaclass shadows the same attribute. Only attach the + # normal attribute source when runtime attribute lookup agrees. + static_desc = inspect.getattr_static(type(obj_value), attr_name, None) + if static_desc is not self.descriptor: + result_source = None + elif attr_name == "__mro__": + result_source = TypeMROSource(obj.source) + return VariableTracker.build(tx, resolved, result_source) + + +class PropertyVariable(VariableTracker): + """Python property descriptor. + + The property type is a data descriptor with tp_descr_get = + property_descr_get which calls fget(obj) to compute the value. + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L2073 + https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L1660-L1693 + """ + + _nonvar_fields = { + "descriptor", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + descriptor: property, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.descriptor = descriptor + + def __repr__(self) -> str: + fget_name = getattr(self.descriptor.fget, "__name__", "?") + return f"PropertyVariable({fget_name})" + + def python_type(self) -> type: + return property + + def as_python_constant(self) -> property: + return self.descriptor + + def tp_descr_get_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker | None, + owner: VariableTracker, + ) -> VariableTracker: + # Mirrors property_descr_get: if obj is NULL or None, return self. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L1660-L1693 + if obj is None: + return self + fget_source = AttrSource(self.source, "fget") if self.source else None + fget_vt = VariableTracker.build( + tx, self.descriptor.fget, source=fget_source, realize=True + ) + return fget_vt.call_function(tx, [obj], {}) + + +class TupleGetterVariable(VariableTracker): + """_tuplegetter descriptor used by namedtuple for field access. + + _tuplegetter is a C data descriptor that stores an index and returns + self[index] on instance access. When accessed on the class (obj=None), + it returns the descriptor itself. + https://github.com/python/cpython/blob/3.13/Modules/_collectionsmodule.c#L2735 + https://github.com/python/cpython/blob/3.13/Modules/_collectionsmodule.c#L2636-L2663 + """ + + _nonvar_fields = { + "descriptor", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + descriptor: "_collections._tuplegetter", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.descriptor = descriptor + + def __repr__(self) -> str: + _, (idx, doc) = self.descriptor.__reduce__() + return f"TupleGetterVariable(index={idx}, doc={doc!r})" + + def python_type(self) -> type: + return _collections._tuplegetter + + def as_python_constant(self) -> "_collections._tuplegetter": + return self.descriptor + + # _tuplegetter exposes __doc__ as a T_OBJECT member. + # https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c#L2717-L2721 + tp_members = {"__doc__": Member(getset_build(lambda s: s.descriptor.__doc__))} + + def tp_descr_get_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker | None, + owner: VariableTracker, + ) -> VariableTracker: + # https://github.com/python/cpython/blob/3.13/Modules/_collectionsmodule.c#L2636-L2663 + if obj is None: + return self + _, (idx, _) = self.descriptor.__reduce__() + return obj.call_method( + tx, "__getitem__", [variables.ConstantVariable.create(idx)], {} + ) + + def tp_descr_set_impl( + self, + tx: "InstructionTranslatorBase", + obj: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + # _tuplegetter fields are read-only; tuplegetter_descr_set always + # raises AttributeError for both set and delete. + # https://github.com/python/cpython/blob/3.13/Modules/_collectionsmodule.c#L2665-L2673 + msg = "can't delete attribute" if value is None else "can't set attribute" + raise_observed_exception(AttributeError, tx, args=[msg]) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/hashable.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/hashable.py new file mode 100644 index 0000000000000000000000000000000000000000..9bfe3a735b284c0777f958abe0c3e49ba4194fdf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/hashable.py @@ -0,0 +1,235 @@ +""" +Hashability utilities for PyTorch Dynamo variable tracking. + +This module provides the HashableTracker wrapper class and associated utilities +for making VariableTracker instances usable as dictionary keys and set elements +during symbolic execution. Used by both ConstDictVariable and SetVariable. +""" + +from typing import TYPE_CHECKING + +import torch + +from .. import variables +from ..exc import raise_observed_exception +from ..utils import guard_if_dyn, specialize_symnode +from .base import VariableTracker + + +if TYPE_CHECKING: + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + +def raise_unhashable( + arg: VariableTracker, tx: "InstructionTranslatorBase | None" = None +) -> None: + if tx is None: + from torch._dynamo.symbolic_convert import InstructionTranslator + + tx = InstructionTranslator.current_tx() + + try: + arg_type = arg.python_type() + except Exception: + arg_type = None + + # Safety check: if we know the real Python type and it IS hashable, + # our is_hashable() disagrees with CPython. Graph-break rather than + # raising a wrong TypeError. + if arg_type is not None and arg_type.__hash__ is not None: + from .. import graph_break_hints + from ..exc import unimplemented + + unimplemented( + gb_type="Hashability mismatch", + context=f"raise_unhashable {arg}", + explanation=f"Dynamo thinks {arg_type.__name__} is unhashable, " + f"but its __hash__ is not None. This likely indicates a missing " + f"or incorrect is_hashable() override.", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + + type_name = arg_type.__name__ if arg_type is not None else type(arg).__name__ + raise_observed_exception( + TypeError, + tx, + args=[ + f"unhashable type: '{type_name}'", + ], + ) + + +def is_hashable(x: VariableTracker) -> bool: + # LazyVT optimization: check hashability without realizing the VT to avoid + # accidentally inserting guards. + if ( + isinstance(x, variables.LazyVariableTracker) + and not x.is_realized() + and x.is_hashable_lazy() + ): + return True + + return x.is_hashable() + + +class RawHash: + """Wraps a pre-computed hash value to bypass int.__hash__'s modular reduction. + + When building a tuple/frozenset of per-item hashes, using bare ints would + apply long_hash (mod sys.hash_info.modulus), corrupting the values. + Wrapping in RawHash makes tuplehash/frozenset_hash see the original hash. + """ + + __slots__ = ("h",) + + def __init__(self, h: int) -> None: + self.h = h + + def __hash__(self) -> int: + return self.h + + def __eq__(self, other: object) -> bool: + return isinstance(other, RawHash) and self.h == other.h + + +class HashableTracker: + """ + Class that wraps a VariableTracker and makes it hashable. + Note that it's fine to put VTs into dictionaries and sets, but doing so + does not take into account aliasing. + """ + + _MISSING = object() + + def __init__(self, vt: VariableTracker) -> None: + # We specialize SymNodes + vt = specialize_symnode(vt) + + # Fast path for unrealized LazyVariableTrackers: check and hash without + # realizing, to avoid inserting guards. If the fast-path check fails, + # fall through to realize the VT and try the full is_hashable check. + if ( + isinstance(vt, variables.LazyVariableTracker) + and not vt.is_realized() + and vt.is_hashable_lazy() + ): + self._hash = hash(vt.original_value()) + self._hash_is_identity = False + self.vt = vt + return + + # Compute hash via the tp_hash slot (generic_hash_impl). + # For unhashable types, hash_impl raises ObservedTypeError. + from torch._dynamo.symbolic_convert import InstructionTranslator + + from .object_protocol import generic_hash_impl + + tx = InstructionTranslator.current_tx() + # is_fake marks an identity-based hash (e.g. id(fake_tensor)); such VTs + # have no python-constant value, so their key equality is identity. + self._hash, self._hash_is_identity = generic_hash_impl(tx, vt) + self.vt = vt + + @classmethod + def _maybe_constant_torch_size(cls, vt: VariableTracker) -> object: + from .lists import SizeVariable + from .tensor import TensorVariable + + if ( + isinstance(vt, variables.LazyVariableTracker) + and not vt.is_realized() + and isinstance(vt.original_value(), torch.Size) + ): + return vt.original_value() + + if not isinstance(vt, SizeVariable): + return cls._MISSING + + items = [] + for item in vt.items: + if item.is_python_constant(): + items.append(item.as_python_constant()) + continue + + if isinstance(item, TensorVariable): + proxy = getattr(item, "proxy", None) + node = getattr(proxy, "node", None) + meta = getattr(node, "meta", None) if node is not None else None + example_value = ( + meta.get("example_value") if isinstance(meta, dict) else None + ) + constant = getattr(example_value, "constant", None) + + if isinstance(constant, torch.Tensor) and constant.numel() == 1: + items.append(constant.item()) + continue + + return cls._MISSING + + return torch.Size(items) + + def __hash__(self) -> int: + return self._hash + + def __eq__(self, other: object) -> bool: + """ + Checks equality between two HashableTracker instances. + + Mirrors CPython's PyObject_RichCompareBool: routes the comparison + through generic_richcompare_bool so any user-defined __eq__ runs. + + Args: + other: Another HashableTracker instance to compare with + + Returns: + True if the underlying variable trackers are Python-equal, False otherwise + """ + if not isinstance(other, HashableTracker): + return False + if self.vt is other.vt: + return True + + self_constant = self._maybe_constant_torch_size(self.vt) + other_constant = self._maybe_constant_torch_size(other.vt) + if self_constant is not self._MISSING and other_constant is not self._MISSING: + return self_constant == other_constant + + # Tensor keys hash by identity (Tensor.__hash__ is id(self)), so CPython + # only ever compares identical tensors during a dict/set lookup; a + # tensor's elementwise __eq__ is never consulted for membership. Mirror + # that with an identity comparison instead of running __eq__, which would + # otherwise emit a stray elementwise-eq node into the FX graph and + # corrupt the surrounding trace. + from .tensor import TensorVariable + + if isinstance(self.vt, TensorVariable) or isinstance(other.vt, TensorVariable): + return ( + self._hash_is_identity + and other._hash_is_identity + and self._hash == other._hash + ) + + # All other keys: mirror PyObject_RichCompareBool and run the + # comparison through generic_richcompare_bool so any user-defined __eq__ + # runs and its result (or any exception it raises) is observed by the + # traced program. + from ..symbolic_convert import InstructionTranslator + from .object_protocol import generic_richcompare_bool + + tx = InstructionTranslator.current_tx() + + result = generic_richcompare_bool(tx, self.vt, other.vt, op="__eq__") + if result.is_python_constant(): + return bool(result.as_python_constant()) + + if result.is_symnode_like(): + return bool(guard_if_dyn(result)) + + # Comparison did not resolve to a constant (e.g. keys whose __eq__ could + # not be determined). Fall back to identity-based hash equality, which + # mirrors CPython treating such keys as equal only when identical. + return ( + self._hash_is_identity + and other._hash_is_identity + and self._hash == other._hash + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/higher_order_ops.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/higher_order_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..d3548b6282a5b3703ad9c6392cec4dc33df15d61 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/higher_order_ops.py @@ -0,0 +1,6407 @@ +""" +This module contains classes and utilities for handling higher-order operators in Dynamo. +It provides functionality for tracing and transforming control flow constructs like +conditions (torch.cond), loops (torch.while_loop), maps (torch.ops.higher_order.map), +and other higher-order operations. + +The module includes specialized VariableTracker classes for different types of +higher-order operations, along with utilities for: +- Speculating and capturing subgraphs +- Managing control flow +- Handling autograd function applications +- Supporting function transformations +- Processing activation checkpoints + +These classes work together to enable Dynamo to correctly trace and compile code +containing complex control flow patterns and higher-order functions while preserving +their semantic behavior. +""" + +import contextlib +import copy +import functools +import inspect +import itertools +import logging +import traceback +import types +import warnings +from collections import Counter +from collections.abc import Sequence +from dataclasses import dataclass, field +from typing import Any, cast, get_args, Literal, Optional, TYPE_CHECKING, Union + +import torch._C +import torch.fx +import torch.nn +from torch._dispatch.python import enable_python_dispatcher +from torch._dynamo.utils import get_fake_value +from torch._dynamo.variables.constant import ConstantVariable +from torch._dynamo.variables.ctx_manager import RepararametrizeModuleContextVariable +from torch._dynamo.variables.functions import UserFunctionVariable +from torch._dynamo.variables.nn_module import UnspecializedNNModuleVariable +from torch._dynamo.variables.script_object import CustomClassObjectVariable +from torch._dynamo.variables.tensor import SymNodeVariable, TensorVariable +from torch._guards import Source +from torch._higher_order_ops.flex_gemm import FLEX_GEMM_OP_ALIASES +from torch._higher_order_ops.invoke_subgraph import NestedCompileRegionOptions +from torch._ops import HigherOrderOperator +from torch.fx.graph_module import GraphModule +from torch.fx.passes.shape_prop import _extract_tensor_metadata +from torch.fx.proxy import Proxy +from torch.multiprocessing.reductions import StorageWeakRef +from torch.utils import _pytree as pytree +from torch.utils._ordered_set import OrderedSet + +from .. import graph_break_hints, variables +from ..exc import ( + FakeTensorObservedException, + ObservedException, + UncapturedHigherOrderOpError, + unimplemented, + Unsupported, +) +from ..source import AttrSource, DictGetItemSource +from ..utils import proxy_args_kwargs, set_example_value, unpack_iterable +from .base import VariableTracker +from .dicts import ConstDictVariable +from .lazy import LazyVariableTracker +from .lists import ListVariable, TupleVariable +from .sets import SetVariable + + +if TYPE_CHECKING: + from torch._dynamo.output_graph import SubgraphTracer + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode + from . import AutogradFunctionContextVariable + +from collections.abc import Generator, Iterable +from typing import ParamSpec, TypeVar + + +P = ParamSpec("P") +R = TypeVar("R") +HOP_VT_Alias = TypeVar("HOP_VT_Alias", bound="TorchHigherOrderOperatorVariable") + +log = logging.getLogger(__name__) +hc_log = torch._logging.getArtifactLogger(__name__, "hierarchical_compile") + +# How speculate_subgraph constructs subgraph placeholders from sub_args. See +# NOTE [argument `set_subgraph_inputs`] below for the meaning of each value. This +# is the single source of truth for the runtime asserts that validate the value. +SetSubgraphInputs = Literal[ + "automatic", "automatic_with_forced_inputs", "flatten_manual", "manual" +] + + +@dataclass +class OutputSpec: + """ + Contains the treespec of the output of the speculated subgraph, and the + information to mask out the constant values from the output during + flattening and inserting them back during unflattening. Cleaning up + constants from the graph makes the graph simpler for AOTDispatcher and + Inductor. + """ + + treespec: pytree.TreeSpec + # list of True/False to identify the locations of const values in the + # subgraph output. True means that value at that index is a constant. + masks_to_filter_const_values: list[bool] | None = None + # The actual constant values that were present in the subgraph output. Note + # that this is the same length as the mask, we just look at the indices + # where mask is True. + const_values: list[Any] | None = None + # Number of intermediate nodes that are also made subgraph outputs. + num_intermediate_nodes_as_outputs: int = 0 + + def __post_init__(self) -> None: + if ( + self.masks_to_filter_const_values is not None + and self.const_values is not None + ): + if len(self.masks_to_filter_const_values) != len(self.const_values): + raise AssertionError( + "masks_to_filter_const_values and const_values must have the same length" + ) + + +@dataclass(frozen=True) +class SubgraphTracingInfo: + """Properties observed during subgraph tracing. + + Expandable container for metadata collected while tracing a HOP subgraph. + Future additions may include aliasing info, mutation info, etc. + """ + + # User code stack at the point where the first externally-visible side + # effect was detected. None means no side effect was observed. + side_effect_stack: traceback.StackSummary | None = None + # All sources accessed via VariableBuilder during the subgraph trace. + traced_sources: OrderedSet[Any] = field(default_factory=OrderedSet) + + +# This function is a syntax sugar for creating a dummy new subtracer so that +# newly added nodes are added to a separate subgraph in this subtracer instead of affecting +# the main graph. This is useful for creating sample inputs for tracing the subgraph. +# For example, in FlexAttentionHigherOrderVariable, we want to create several scalars +# to trace the score_mod function but we don't want the operators that creates the scalar to +# show up in the graph, we could this function to discard the graph changes. +# Example usage: +# with discard_graph_changes(): +# sample_input= create_sample_inputs() +# speculate_subgraph(tx, f, sample_inputs, {}) +@contextlib.contextmanager +def discard_graph_changes( + tx: "InstructionTranslatorBase", +) -> Generator[None, None, None]: + ctx = tx.output.subtracer("subgraph_wrapper", None) + try: + ctx.__enter__() + yield + finally: + ctx.__exit__(None, None, None) + + +def check_meta_consistency_vt( + vars1: list[VariableTracker], + vars2: list[VariableTracker], + lhs_name: str, + rhs_name: str, + include_contiguity: bool = True, +) -> None: + from torch._higher_order_ops.utils import check_meta_consistency + + def _unwrap_var(var: VariableTracker) -> Any: + if var.is_tensor(): + # pyrefly: ignore[missing-attribute] + return var.proxy.node.meta["example_value"] + elif isinstance(var, SymNodeVariable): + return var.sym_num + elif var.is_python_constant(): + return var.as_python_constant() + else: + unimplemented( + gb_type="cannot unwrap variable for check_meta_consistency", + context=str(var), + explanation=f"Expected {var} to be TensorVariable, SymNodeVariable, or ConstantVariable", + hints=[], + ) + + unwrapped1 = [_unwrap_var(var) for var in vars1] + unwrapped2 = [_unwrap_var(var) for var in vars2] + + return check_meta_consistency( + unwrapped1, + unwrapped2, + lhs_name, + rhs_name, + include_contiguity=include_contiguity, + ) + + +@contextlib.contextmanager +def dynamo_enable_grad( + tx: "InstructionTranslatorBase", enable: bool = True +) -> Generator[None, None, None]: + from . import GradModeVariable + + org_value = torch.is_grad_enabled() + try: + GradModeVariable.create(tx, enable, initialized=True) + yield + finally: + GradModeVariable.create(tx, org_value, initialized=True) + + +@contextlib.contextmanager +def dynamo_allow_side_effects_in_hop( + tx: "InstructionTranslatorBase", +) -> Generator[None, None, None]: + orig_val = tx.output.current_tracer.allow_side_effects_in_hop + try: + tx.output.current_tracer.allow_side_effects_in_hop = True + yield + finally: + tx.output.current_tracer.allow_side_effects_in_hop = orig_val + + +def find_mismatched_vars( + var: Any, types: type | tuple[type, ...], allow_none: bool = False +) -> set[VariableTracker]: + """ + Recursively finds variables whose type is not an instance of the specified types. + Args: + var: The variable to check. + types: A tuple of allowed types. + allow_none (bool): Whether to allow None values. Defaults to False. + Returns: + A set of variables whose type is not an instance of the specified types. + """ + mismatched_vars = set() + if isinstance(var, (list, tuple)): + for item in var: + mismatched_vars.update(find_mismatched_vars(item, types, allow_none)) + elif isinstance(var, (TupleVariable, ListVariable)): + for item in var.items: + mismatched_vars.update(find_mismatched_vars(item, types, allow_none)) + elif isinstance(var, ConstDictVariable): + for value in var.items.values(): + mismatched_vars.update(find_mismatched_vars(value, types, allow_none)) + elif isinstance(var, SetVariable): + for key in var.items: + mismatched_vars.update(find_mismatched_vars(key.vt, types, allow_none)) + else: + if not isinstance(var, types) and not (allow_none and var.is_constant_none()): + mismatched_vars.add(var) + return mismatched_vars + + +def only_consist_of( + var: Any, types: tuple[type, ...], allow_none: bool = False +) -> bool: + mismatch_vars = find_mismatched_vars(var, types, allow_none=allow_none) + return len(mismatch_vars) == 0 + + +# A more read-able syntax sugar for creating a UserFunctionVariable for f +# and run call_function on it. Make it return a function to preserve the calling +# convention of the original f. +from torch._dynamo.utils import _make_inlined + + +def add_call_function( + tx: "InstructionTranslatorBase", + fn: Any, + args: tuple[Any, ...], + kwargs: dict[str, Any], + flat_example_value: Any, + config: NestedCompileRegionOptions | None = None, +) -> VariableTracker: + from .builder import wrap_fx_proxy + + proxy = tx.output.create_proxy( + "call_function", + fn, + args=args, + kwargs=kwargs, + ) + + # Set backend metadata if provided + if config is not None: + if "custom" not in proxy.node.meta: + # pyrefly: ignore [implicit-any] + proxy.node.meta["custom"] = {} + proxy.node.meta["custom"]["nested_region_config"] = config + if proxy.node.target != torch._higher_order_ops.invoke_subgraph: + raise AssertionError( + "Expected proxy node target to be torch._higher_order_ops.invoke_subgraph" + ) + + # Store the invocation as a call + flat_variable = wrap_fx_proxy( + tx=tx, + proxy=proxy, + example_value=flat_example_value, + ) + return flat_variable + + +def overwrite_tensor_vt_requires_grad( + graph_output_vts: Iterable[VariableTracker], flat_variable: VariableTracker +) -> None: + # All outputs of autograd.Function have requires_grad=True. We turn off + # grad_mode in autograd.Function, so our outputs naively have + # requires_grad=False. So we hackily force them back on here. A better + # solution would be to write python code that Dynamo could trace but we + # decided that it wasn't worth it. + # pyrefly: ignore[missing-attribute] + for orig_vt, subgraph_vt in zip(graph_output_vts, flat_variable.items): + if isinstance(orig_vt, variables.TensorVariable): + if not isinstance(subgraph_vt, variables.TensorVariable): + raise AssertionError("Expected subgraph_vt to be a TensorVariable") + orig_vt.requires_grad = subgraph_vt.requires_grad + if orig_vt.requires_grad: + orig_vt.has_grad_fn = True + + +def overwrite_tensor_vt_proxy( + graph_output_vts: Iterable[VariableTracker], flat_variable: VariableTracker +) -> None: + # wrap_fx_proxy creates fresh variable trackers. However, the main program + # after the speculate subgraph can still use the original tensor vts that + # are still pointing to the nodes present in the subgraph. So, we reproxify + # the original tensor vts with the subgraph outputs. This way, whenever the + # outer graph uses an original vt, it uses the subgraph output. + # + # This is critical for maintaining the separation between: + # - `body_r`: The output VT structure that Dynamo continues tracing (may + # contain non-proxyable objects, nested structures, etc.) + # - `graph_output_vts`: Only the tensor/symint VTs that were actual graph + # outputs from speculate_subgraph + # + # By overwriting the proxies of VTs in `body_r` with the proxies from the + # HOP call, we ensure the outer graph correctly references the HOP outputs + # while still allowing `body_r` to contain arbitrary Python objects. + # pyrefly: ignore[missing-attribute] + for orig_vt, subgraph_vt in zip(graph_output_vts, flat_variable.items): + if isinstance( + orig_vt, + ( + variables.SymNodeVariable, + variables.TensorVariable, + CustomClassObjectVariable, + ), + ): + if not ( + subgraph_vt.is_tensor() + or isinstance(subgraph_vt, (SymNodeVariable, CustomClassObjectVariable)) + ): + raise AssertionError( + "Expected subgraph_vt to be a tensor, SymNodeVariable, or CustomClassObjectVariable" + ) + orig_vt.proxy = subgraph_vt.proxy + + +def _call_function_with_auto_output_flattening( + tx: "InstructionTranslatorBase", + fn: Any, + args: tuple[Any, ...], + kwargs: dict[str, Any], + flat_example_value: Any, + body_r: VariableTracker | None, + graph_output_vts: VariableTracker | tuple[VariableTracker, ...], + config: NestedCompileRegionOptions | None = None, +) -> VariableTracker | None: + """ + Create HOP call node and reproxify output VTs for HOPs with auto output semantics. + + This function is used by HOPs with auto output semantics (see speculate_subgraph_with_auto_output_flattening) + to create the actual HOP call in the FX graph and properly handle the output variable trackers. + + The key operation is "reproxifying" - updating the proxies of the original tensor VTs + (from body_r) to point to the HOP call outputs, ensuring the outer graph correctly + references the HOP outputs while allowing body_r to contain arbitrary Python objects. + + Args: + tx: The instruction translator + fn: The HOP function to call + args: Arguments for the HOP call (typically includes the subgraph node) + kwargs: Keyword arguments for the HOP call + flat_example_value: Example value for the HOP output + body_r: The output VT structure that Dynamo continues tracing with (may be None) + graph_output_vts: Tensor/symint VTs that were actual graph outputs + + Returns: + The body_r VT (unchanged), which Dynamo will continue tracing with + """ + + flat_variable = add_call_function(tx, fn, args, kwargs, flat_example_value, config) + if body_r is not None: + # pyrefly: ignore[bad-argument-type] + overwrite_tensor_vt_proxy(graph_output_vts, flat_variable) + return body_r + + +def _call_function_and_unflatten_output( + tx: "InstructionTranslatorBase", + fn: Any, + args: tuple[Any, ...], + kwargs: dict[str, Any], + flat_example_value: Any, + ret_spec: OutputSpec, + body_r: VariableTracker | None, +) -> VariableTracker: + from .builder import SourcelessBuilder, wrap_fx_proxy + + # Store the invocation as a call + flat_variable = wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + fn, + args=args, + kwargs=kwargs, + ), + example_value=flat_example_value, + ) + + # wrap_fx_proxy creates fresh variable trackers. However, the main program + # after the speculate subgraph can still use the original tensor vts that + # are still pointing to the nodes present in the subgraph. So, we reproxify + # the original tensor vts with the subgraph outputs. This way, whenever the + # outer graph uses an original vt, it uses the subgraph output. + if body_r is not None: + # mypy: ignore[attr-defined] + for orig_vt, subgraph_vt in zip(body_r.items, flat_variable.items): + if orig_vt.is_tensor() or isinstance(orig_vt, SymNodeVariable): + if not ( + subgraph_vt.is_tensor() or isinstance(subgraph_vt, SymNodeVariable) + ): + raise AssertionError( + "Expected subgraph_vt to be a tensor or SymNodeVariable" + ) + orig_vt.proxy = subgraph_vt.proxy + + if ret_spec.num_intermediate_nodes_as_outputs: + # The treespec was computed w/o any extra intermediate outputs. At this + # point, it is safe to just get rid of the extra outputs + flat_variable = SourcelessBuilder.create( + tx, + flat_variable.items[ # mypy: ignore[attr-defined] + : -ret_spec.num_intermediate_nodes_as_outputs + ], + ) + + if ret_spec.masks_to_filter_const_values: + from torch._dynamo.external_utils import insert_const_values_with_mask + + # During flattening, we removed the constant values. To ensure Dynamo + # can trace correctly, insert back the constant values in the output. + flat_variable = _make_inlined(tx, insert_const_values_with_mask)( + flat_variable, ret_spec.masks_to_filter_const_values, ret_spec.const_values + ) + + # Transform variable back into a list (previously made into a tuple by + # speculate_subgraph function) so as to respect the pytree API typing. + flat_list_variable = SourcelessBuilder.create(tx, list).call_function( + tx, [flat_variable], {} + ) + return ( + _make_inlined(tx, pytree.tree_unflatten)(flat_list_variable, ret_spec.treespec) + if ret_spec.treespec + else flat_variable + ) + + +def _assert_tensors_nonaliasing(inputs: Any, outputs: Any) -> None: + input_tensor_ids = { + id(t) for t in pytree.tree_leaves(inputs) if isinstance(t, torch.Tensor) + } + output_tensor_ids = { + id(t) for t in pytree.tree_leaves(outputs) if isinstance(t, torch.Tensor) + } + if not input_tensor_ids.isdisjoint(output_tensor_ids): + raise AssertionError("inputs to function body cannot alias outputs") + + +def get_tensor_storages(tensor: torch.Tensor) -> set[StorageWeakRef]: + """ + Get storage references from a tensor. + + Handles regular tensors. Raises NotImplementedError for sparse tensors + and traceable wrapper subclasses. + + Args: + tensor: The tensor to extract storages from + + Returns: + Set of StorageWeakRef objects for the tensor's storage(s) + """ + from torch.multiprocessing.reductions import StorageWeakRef + from torch.utils._python_dispatch import is_traceable_wrapper_subclass + + storages: set[StorageWeakRef] = set() + + if not isinstance(tensor, torch.Tensor): + return storages + + if tensor.is_sparse or tensor.is_sparse_csr: + raise NotImplementedError("get_tensor_storages does not support sparse tensors") + + if is_traceable_wrapper_subclass(tensor): + raise NotImplementedError( + "get_tensor_storages does not support traceable wrapper subclasses" + ) + else: + storages.add(StorageWeakRef(tensor._typed_storage())) + + return storages + + +def subgraph_mutated_input_storages( + subgraph: torch.fx.Graph, mutated_input_indices: Iterable[int] +) -> set[StorageWeakRef]: + """Map subgraph placeholder indices flagged as mutated to their tensor storages. + + Used by HigherOrderVariable subclasses to translate + ``_dynamo_mutated_input_indices`` into a parent-side storage set, + which is then matched against the parent's full input list to recover + the parent-side mutated index list passed as a HOP kwarg. + """ + placeholders = [node for node in subgraph.nodes if node.op == "placeholder"] + storages: set[StorageWeakRef] = set() + for idx in mutated_input_indices: + if idx >= len(placeholders): + raise AssertionError( + f"mutated input index {idx} out of range for {len(placeholders)} placeholders" + ) + placeholder = placeholders[idx] + example_value = placeholder.meta.get( + "example_value", placeholder.meta.get("val", None) + ) + if not isinstance(example_value, torch.Tensor): + raise AssertionError("The mutated input must be a tensor") + storages |= get_tensor_storages(example_value) + return storages + + +def parent_mutated_input_indices( + parent_inputs: Sequence["VariableTracker | Proxy"], + mutated_input_storages: set[StorageWeakRef], +) -> list[int]: + """Walk a HOP's full parent-side input list and return the indices whose + tensor storage matches one of the storages mutated inside any of the + subgraphs. + + If no subgraph mutation was detected, returns the empty list without + inspecting any storages. Some inputs (e.g. BatchedTensor under vmap) + deliberately refuse storage access; we must not trip on those when + there's nothing to match against. + """ + if not mutated_input_storages: + return [] + mutated: list[int] = [] + for idx, inp in enumerate(parent_inputs): + example_value = None + if isinstance(inp, VariableTracker): + if inp.is_tensor(): + example_value = inp.as_proxy().node.meta.get("example_value", None) + else: + if not isinstance(inp, Proxy): + raise AssertionError("Expected inp to be a Proxy") + example_value = inp.node.meta.get("example_value", inp.node.meta.get("val")) + + if isinstance(example_value, torch.Tensor): + for storage in get_tensor_storages(example_value): + if storage in mutated_input_storages: + mutated.append(idx) + break + return mutated + + +class StorageAliasingTracker: + """ + Tracks storage references to detect aliasing between tensors. + + This class encapsulates the logic for collecting storages from tensors + and checking for aliasing conflicts. Used to filter intermediate outputs + that would create input-output or output-output aliasing. + """ + + def __init__(self) -> None: + self.excluded_storages: set[StorageWeakRef] = set() + + def _collect_storages_from_tensor(self, example_value: torch.Tensor) -> None: + self.excluded_storages.update(get_tensor_storages(example_value)) + + def collect_from_inputs(self, tx: "InstructionTranslatorBase") -> None: + """Collect storages from graph input placeholders.""" + from torch._higher_order_ops.utils import _collect_fake_inputs + + for node in tx.output.graph.nodes: + if node.op == "placeholder": + example_value = _collect_fake_inputs([node])[0] + if isinstance(example_value, torch.Tensor): + self._collect_storages_from_tensor(example_value) + else: + break + + def collect_from_outputs(self, graph_output_vts: list[VariableTracker]) -> None: + """Collect storages from existing graph outputs.""" + from torch._higher_order_ops.utils import _collect_fake_inputs + + for vt in graph_output_vts: + proxy = vt.as_proxy() + example_value = _collect_fake_inputs([proxy.node])[0] + if isinstance(example_value, torch.Tensor): + self._collect_storages_from_tensor(example_value) + + def check_and_track(self, proxy_node: Proxy) -> bool: + """ + Check if a tensor can be added as a subgraph output without causing aliasing issues. + + Given a proxy node, extracts its example tensor value and checks if its storage + aliases with any previously tracked storages (from inputs or other outputs). + If there's no aliasing conflict, the tensor's storage is added to the tracked set. + + Args: + proxy_node: An FX proxy node whose example_value is the tensor to check. + + Returns: + True if the tensor doesn't alias with tracked storages (safe to add as output), + False if it aliases (should be filtered out). + """ + from torch._higher_order_ops.utils import _collect_fake_inputs + from torch.multiprocessing.reductions import StorageWeakRef + from torch.utils._python_dispatch import is_traceable_wrapper_subclass + + example_value = _collect_fake_inputs([proxy_node])[0] + + # Non-tensor outputs (e.g., symints) don't have aliasing concerns + if not isinstance(example_value, torch.Tensor): + return True + + # Check if any storage aliases with existing inputs/outputs + tensor_storages = get_tensor_storages(example_value) + if tensor_storages & self.excluded_storages: + return False + + # Track this tensor's storage (for wrapper subclasses, inner storages were already checked) + if not is_traceable_wrapper_subclass(example_value): + if not (example_value.is_sparse or example_value.is_sparse_csr): + self.excluded_storages.add( + StorageWeakRef(example_value._typed_storage()) + ) + + return True + + +def taint_filtered_vt(vt: VariableTracker) -> None: + """Mark a VT as filtered due to aliasing so it raises a clear error if used.""" + original_as_proxy = vt.as_proxy + + def tainted_as_proxy() -> Any: + proxy = original_as_proxy() + raise RuntimeError( + f"An intermediate tensor '{proxy.node.name}' created inside a " + f"higher-order op subgraph aliases an input or output, so it was " + f"not included in the subgraph outputs. However, it is being used " + f"in the outer graph (e.g., via a side effect like list.append). " + f"To fix this, clone the tensor before capturing it " + f"(e.g., use tensor.clone() instead of tensor)." + ) + + vt.as_proxy = tainted_as_proxy # type: ignore[method-assign] + + +def collect_intermediate_outputs( + tx: "InstructionTranslatorBase", + subtracer: "SubgraphTracer", + graph_output_vts: list[VariableTracker], + filter_aliased_intermediates: bool = False, +) -> list[VariableTracker]: + extra_outputs = [] + existing_out_proxies = {vt.as_proxy() for vt in graph_output_vts} + + # Build the aliasing tracker if we're filtering + tracker = None + if filter_aliased_intermediates: + tracker = StorageAliasingTracker() + tracker.collect_from_inputs(tx) + tracker.collect_from_outputs(graph_output_vts) + + for out in subtracer.tracked_proxyable_vt: + proxy = out.as_proxy() + + # Skip if already in output + if proxy in existing_out_proxies: + continue + + # TODO floats are not supported in HOP input/output + if isinstance(out, SymNodeVariable) and out.python_type() is float: + continue + + if not filter_aliased_intermediates: + extra_outputs.append(out) + else: + # Filter out intermediates that alias with inputs or outputs. + # This is needed for HOPs like invoke_subgraph that don't support aliasing. + if tracker is None: + raise AssertionError( + "tracker must not be None for intermediate filtering" + ) + if tracker.check_and_track(proxy.node): + extra_outputs.append(out) + else: + taint_filtered_vt(out) + + return extra_outputs + + +def _check_all_tensorvariable(args: list[VariableTracker]) -> None: + if not all(type(a.realize()) is TensorVariable for a in args): + unimplemented( + gb_type="HOP: non torch.Tensor leaf", + context=f"args types: {[type(a.realize()) for a in args]}", + explanation="Expected all leaves to be of torch.Tensor type.", + hints=[], + ) + + +def _check_supported_callable_arg( + tx: "InstructionTranslatorBase", func_var: VariableTracker, arg_name: str +) -> None: + from .builder import SourcelessBuilder + + is_callable = ( + SourcelessBuilder.create(tx, callable) + .call_function(tx, [func_var], {}) + .as_python_constant() + ) + if not is_callable: + unimplemented( + gb_type="HOP: non-callable variable", + context=f"arg name: {arg_name}, func_var type: {str(func_var)}", + explanation=f"{arg_name} should be a callable but is of type {str(func_var)}.", + hints=[], + ) + + +def _call_while_loop( + self: Union[ + "WhileLoopHigherOrderVariable", "WhileLoopStackOutputHigherOrderVariable" + ], + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + stack_output: bool, + hop_name: str, +) -> VariableTracker: + from torch._higher_order_ops.while_loop import _create_unbacked_symint + + args, kwargs = LazyVariableTracker.realize_all((args, kwargs)) + cond_fn, body_fn, operands, additional_inputs = args + + # Input checks + for i, k in enumerate(["cond_fn", "body_fn", "operands"]): + if v := kwargs.pop(k, None): + if i != len(args): + raise AssertionError( + "did not provide the right number of non-keyword args" + ) + args.append(v) + + if kwargs or len(args) != 4: + unimplemented( + gb_type="torch.while_loop: improper args/kwargs", + context=f"args: {args}, kwargs: {kwargs}", + explanation=f"torch.while_loop expects 4 positional arguments (got {len(args)}) " + f"and no keyword arguments (got {len(kwargs)}) " + "Usage: while_loop(cond_fn, body_fn, operands)", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + # cond_fn and body_fn input check + _check_supported_callable_arg(tx, cond_fn, "cond_fn") + _check_supported_callable_arg(tx, body_fn, "body_fn") + + # operands input check + operands_seq = unpack_iterable(tx, operands) + + # additional_inputs input check + if not isinstance(additional_inputs, (ListVariable, TupleVariable)): + unimplemented( + gb_type="torch.while_loop: improper additional_inputs", + context=str(additional_inputs), + explanation=f"Expected additional_inputs to be a list/tuple but got {additional_inputs.python_type()}", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + additional_inputs_seq = unpack_iterable(tx, additional_inputs) + + with discard_graph_changes(tx): + # Note: this must be run under discard graph changes. + def unspecialize_carried_inputs( + tx: "InstructionTranslatorBase", carry: VariableTracker + ) -> VariableTracker: + # See NOTE [unspecialize int carry with unbacked symints] + if ( + carry.is_python_constant() + and isinstance(carry.as_python_constant(), int) + ) or isinstance(carry, SymNodeVariable): + example_value = _create_unbacked_symint( + tx.output.fake_mode, ignore_fresh_unbacked_symbols=True + ) + proxy = tx.output.current_tracer.create_graph_input( + "unbacked_symint", type(example_value), example_value + ) + return SymNodeVariable.create(tx, proxy, example_value) + else: + # See NOTE [unspecialize constant tensor carry] + if not carry.is_tensor(): + raise AssertionError("Expected carry to be a tensor") + cloned_carry = carry.clone() + # type: ignore[attr-defined] + cloned_carry.proxy.node.meta["example_value"].constant = None + return cloned_carry + + # clone inputs across subgraphs, to avoid unbacked memoization in fake prop + cond_operands_seq = [ + unspecialize_carried_inputs( + tx, + ( + carry.call_method(tx, "clone", args=[], kwargs={}) + if carry.is_tensor() + else carry + ), + ) + for carry in operands_seq + ] + body_operands_seq = [ + unspecialize_carried_inputs( + tx, + ( + carry.call_method(tx, "clone", args=[], kwargs={}) + if carry.is_tensor() + else carry + ), + ) + for carry in operands_seq + ] + + # create cond subgrpahs + ( + (cond_r, _cond_treespec), + cond_graph, + cond_lifted_freevars, + ) = speculate_subgraph( + tx, + cond_fn, + cond_operands_seq + additional_inputs_seq, + {}, + hop_name, + source_target=self.value, + # NOTE [why we cannot use "automatic" for while_loop]: + # The reason is that we want to enforce + # the ordering of inputs and outputs to be consistent and the ordering + # of cond_fn and body_fn to the consistent. + # e.g. suppose we use "automatic" and we have: + # + # def body_fn(ph1, ph2): + # new_a, new_b = ph2.cos(), ph1.sin() + # return new_a, new_b + # + # a, b = torch.randn(3), torch.randn(3) + # new_a, new_b = body_fn(a, b) + # + # Using automatic, the ordering of arguments will be the order that they're + # used. In this example, the capture graph looks like: + # + # def captured_body(ph1, ph2): + # new_a, new_b = ph1.cos(), ph2.add_(1) + # return new_a, new_b + # + # This is fine when we change the calling convention of captured_body to be + # new_a, new_b = captured_body(b, a). + # But for while_loop, the next iteration's input is previous iteration output + # we'll end up feeding captured_body(new_a, new_b) instead. + # So it's best we always enforce the ordering of carried_inputs the same as outputs + # with "flatten_manual". + set_subgraph_inputs="flatten_manual", + supports_input_mutation=self.supports_input_mutation, + supports_aliasing=self.supports_aliasing, + remove_consts_from_outputs=False, + ) + cond_nn_modules = dict(tx.output.nn_modules) + validate_subgraph_output_types(cond_r) + if cond_r.is_tensor(): + cond_r_meta = _extract_tensor_metadata( + # type: ignore[attr-defined] + cond_r.proxy.node.meta["example_value"], + include_contiguity=False, + ) + if cond_r_meta.dtype != torch.bool or cond_r_meta.shape != torch.Size([]): + unimplemented( + gb_type="torch.while_loop: unsupported cond_fn return type", + context=str(cond_r), + explanation=f"Expected cond_fn to return a scalar tensor or a bool but got {cond_r_meta.shape}.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + elif cond_r.is_python_constant(): + # short-circuiting while_loop when cond_fn returns a constant such as 0, 1 True or False + pred = cond_r.as_python_constant() + if pred: + unimplemented( + gb_type="torch.while_loop: infinite loop detected", + context=str(cond_r), + explanation=f"Infinite loop detected because while_loop's cond_fn always returns the same value {pred}.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + else: + return operands + + # create body subgraph + ( + (body_r, body_treespec), + body_graph, + body_lifted_freevars, + ) = speculate_subgraph( + tx, + body_fn, + body_operands_seq + additional_inputs_seq, + {}, + hop_name, + source_target=self.value, + set_subgraph_inputs="flatten_manual", + should_flatten_outputs=True, + supports_input_mutation=self.supports_input_mutation, + supports_aliasing=self.supports_aliasing, + remove_consts_from_outputs=False, + ) + validate_subgraph_output_types(body_r) + cond_mutated_inputs = set(getattr(cond_graph, "_dynamo_mutated_input_indices", ())) + body_mutated_inputs = set(getattr(body_graph, "_dynamo_mutated_input_indices", ())) + + mutated_input_storages = subgraph_mutated_input_storages( + cond_graph, cond_mutated_inputs + ) | subgraph_mutated_input_storages(body_graph, body_mutated_inputs) + + # We set include contiguity=False because we have vmap x HOP tests, where if + # include_contiguity=True will call t.is_contiguous inside of vmap and get an error + # "querying is_contiguous inside of vmap for memory_format other than + # torch.contiguous_format is not yet implemented". This is okay because stride + # is still checked. + check_meta_consistency_vt( + unpack_iterable(tx, body_r), + operands_seq, + "body_fn_output", + "carried_inputs", + include_contiguity=False, + ) + + shared, (cond_unique, body_unique) = _merge_graph_inputs( + [cond_graph, body_graph], + [cond_lifted_freevars, body_lifted_freevars], + ["cond_fn", "body_fn"], + ) + + additional_lifted_inputs = shared + cond_unique + body_unique + all_while_loop_inputs: list[VariableTracker | Proxy] = ( + list(operands_seq) + + list(additional_inputs_seq) + + list(additional_lifted_inputs) + ) + mutated_inputs = parent_mutated_input_indices( + all_while_loop_inputs, mutated_input_storages + ) + + mutated_arg_indices = ",".join(str(i) for i in mutated_inputs) + + body_nn_modules = dict(tx.output.nn_modules) + + cond_gm = torch.fx.GraphModule(cond_nn_modules, cond_graph) + body_gm = torch.fx.GraphModule(body_nn_modules, body_graph) + cond_name = tx.output.install_subgraph("cond_fn", cond_gm) + body_name = tx.output.install_subgraph("body_fn", body_gm) + + cond_node = make_attr(tx, cond_name) + body_node = make_attr(tx, body_name) + + operands_proxy = tuple(operand.as_proxy() for operand in operands_seq) + additional_inputs_proxy = tuple( + [inp.as_proxy() for inp in additional_inputs_seq] + additional_lifted_inputs + ) + p_args = ( + cond_node, + body_node, + operands_proxy, + additional_inputs_proxy, + ) + hop_kwargs = ( + {"mutated_arg_indices": mutated_arg_indices} + if not stack_output and mutated_arg_indices + else {} + ) + return _call_function_and_unflatten_output( + tx, + self.value, + p_args, + hop_kwargs, + None, + body_treespec, + body_r, + ) + + +def are_same_graph_modules( + fn_name: str, a_mod: GraphModule, b_mod: GraphModule, fake_mode: "FakeTensorMode" +) -> bool: + from torch._subclasses._fake_tensor_utils import _CacheKeyState + from torch._subclasses.fake_tensor import extract_tensor_metadata + + # Maps the equivalent nodes from a to b + # pyrefly: ignore [implicit-any] + node_map = {} + + def check_all_args(a_nodes: Iterable[Any], b_nodes: Iterable[Any]) -> bool: + for arg_a, arg_b in zip(a_nodes, b_nodes): + if isinstance(arg_a, torch.fx.Node): + if node_map[arg_a] != arg_b: + return False + elif isinstance(arg_a, slice): + if not isinstance(arg_b, slice): + return False + if not check_all_args( + (arg_a.start, arg_a.stop, arg_a.step), + (arg_b.start, arg_b.stop, arg_b.step), + ): + return False + elif arg_a != arg_b: + # This is a catch-all for everything else. `slice` was a + # surprise but can there be other data structures that can + # contain fx.Nodes in them? + return False + return True + + for a_node, b_node in zip(a_mod.graph.nodes, b_mod.graph.nodes): + if a_node.op != b_node.op: + return False + + if a_node.op == "placeholder": + a_value = a_node.meta["example_value"] + b_value = b_node.meta["example_value"] + + if isinstance(a_value, torch.Tensor): + if not isinstance(b_value, torch.Tensor): + return False + # Extract fake tensor metadata for a and b and then compare + # pyrefly: ignore [implicit-any] + a_result = [] + state = _CacheKeyState(fake_mode.shape_env) + a_metadata = extract_tensor_metadata(a_value) + a_metadata._flatten_into(a_result, fake_mode, state) + + b_result = [] + state = _CacheKeyState(fake_mode.shape_env) + b_metadata = extract_tensor_metadata(b_value) + b_metadata._flatten_into(b_result, fake_mode, state) + if a_result != b_result: + return False + elif isinstance(a_value, torch.SymInt): + if not isinstance(b_value, torch.SymInt): + return False + if a_value is not b_value: + return False + elif a_node.op == "call_function": + if a_node.target is not b_node.target: + return False + a_flat, _ = pytree.tree_flatten((a_node.args, a_node.kwargs)) + b_flat, _ = pytree.tree_flatten((b_node.args, b_node.kwargs)) + if not check_all_args(a_flat, b_flat): + hc_log.debug( + "%s: Graph comparison failed at node (call_function): %s", + fn_name, + a_node, + ) + return False + elif a_node.op == "call_method": + if a_node.target != b_node.target: + return False + a_flat, _ = pytree.tree_flatten((a_node.args, a_node.kwargs)) + b_flat, _ = pytree.tree_flatten((b_node.args, b_node.kwargs)) + if not check_all_args(a_flat, b_flat): + hc_log.debug( + "%s: Graph comparison failed at node (call_method) : %s", + fn_name, + a_node, + ) + return False + elif a_node.op == "output": + a_flat, _ = pytree.tree_flatten((a_node.args, a_node.kwargs)) + b_flat, _ = pytree.tree_flatten((b_node.args, b_node.kwargs)) + if not check_all_args(a_flat, b_flat): + hc_log.debug("%s: Graph comparison failed at the output node", fn_name) + return False + elif a_node.op == "get_attr": + a_attr = getattr(a_mod, a_node.target) + b_attr = getattr(b_mod, b_node.target) + if isinstance(a_attr, torch.fx.GraphModule): + if not isinstance(b_attr, torch.fx.GraphModule): + return False + # This is an example of a HOP inside a HOP + if not are_same_graph_modules(fn_name, a_attr, b_attr, fake_mode): + return False + else: + # TODO - write an example with tensor as a graph attribute in + # the Fx graph + raise NotImplementedError(f"get_attr with {type(a_attr)}") + else: + # TODO - call_module is not supported because Dynamo Fx graph does + # not install a call_module + raise NotImplementedError(f"Graph equivalence check saw a {a_node.op}") + + # Two nodes are equal - add them to them map + node_map[a_node] = b_node + + return True + + +def validate_args_and_maybe_create_graph_inputs( + sub_args: list[VariableTracker], + tracer: "SubgraphTracer", + tx: "InstructionTranslatorBase", + set_subgraph_inputs: SetSubgraphInputs, + description: str, + sub_args_names: Sequence[str] | None = None, +) -> list[Any]: + from . import AutogradFunctionContextVariable + from .builder import SourcelessBuilder, wrap_fx_proxy_cls + + if tracer.parent is None: + raise AssertionError("tracer.parent must not be None") + + if set_subgraph_inputs == "flatten_manual": + flat_args, tree_spec = unpack_iterable( + tx, + _make_inlined(tx, pytree.tree_flatten)( + SourcelessBuilder.create(tx, sub_args) + ), + ) + + flat_inputs = validate_args_and_maybe_create_graph_inputs( + unpack_iterable(tx, flat_args), + tracer, + tx, + set_subgraph_inputs="manual", + description=description, + ) + + return unpack_iterable( + tx, + _make_inlined(tx, pytree.tree_unflatten)( + SourcelessBuilder.create(tx, list(flat_inputs)), tree_spec + ), + ) + else: + if sub_args_names is not None: + # Can be greater if user passes some args as kwargs + if len(sub_args_names) < len(sub_args): + raise AssertionError( + "sub_args_names must have at least as many entries as sub_args" + ) + args = [] + for idx, a in enumerate(sub_args): + if not isinstance(a, VariableTracker): + raise AssertionError("Expected each sub_arg to be a VariableTracker") + new_arg = None + if set_subgraph_inputs == "automatic": + args.append(a) + continue + elif set_subgraph_inputs == "automatic_with_forced_inputs": + if isinstance(a, LazyVariableTracker): + a = a.realize() + if isinstance(a, variables.TensorVariable): + node = a.maybe_fx_node() + if node is None: + raise AssertionError( + "Expected TensorVariable to have an fx node" + ) + example_value = node.meta["example_value"] + arg_name = ( + a.as_proxy().node.name + if sub_args_names is None + else sub_args_names[idx] + ) + new_proxy = tracer.create_graph_input( + arg_name, a.python_type(), example_value + ) + example_value = node.meta.get("example_value", None) + a = wrap_fx_proxy_cls( + target_cls=type(a), + tx=tx, + proxy=new_proxy, + example_value=example_value, + ) + args.append(a) + continue + + if a.is_python_constant(): + # This arg is not used in the body of the higher order op. + # Currently, this new input is added to make the calls + # happy, which expect a fixed number of arguments. In + # future, we can clean this up. + arg_name = ( + "const_unused" + if sub_args_names is None + else f"const_unused_{sub_args_names[idx]}" + ) + tracer.create_graph_input( + arg_name, a.python_type(), a.as_python_constant() + ) + new_arg = a + # Weird special case, we probably want to delete it or fold it + # into the next case (of `a` being placeable into a graph) + elif isinstance(a, AutogradFunctionContextVariable): + example_value = a.as_proxy().node.meta["example_value"] + arg_name = ( + a.as_proxy().node.name + if sub_args_names is None + else sub_args_names[idx] + ) + tracer.create_graph_input(arg_name, a.python_type(), example_value) + new_arg = a + # If `a` can be put into a graph + elif a.maybe_fx_node() is not None: + node = a.maybe_fx_node() + if node is None: + raise AssertionError( + "Expected a non-None fx node after maybe_fx_node() check" + ) + example_value = node.meta.get("example_value", None) + arg_name = node.name if sub_args_names is None else sub_args_names[idx] + new_proxy = tracer.create_graph_input( + arg_name, a.python_type(), example_value + ) + new_arg = wrap_fx_proxy_cls( + target_cls=type(a), + tx=tx, + proxy=new_proxy, + example_value=example_value, + ) + # If `a` cannot be put into a graph + else: + # HOPs work much better if they use speculate_subgraph(set_subgraph_inputs="automatic"). + unimplemented( + gb_type="HOP body taking non-Tensor as input", + context=str(sub_args), + explanation=f"{description} with body that accepts non-Tensors as input. " + f"Got type {a.python_type()} at index {idx}.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + args.append(new_arg) + return args + + +# N-branch generalization of former _merge_graph_inputs. Used by torch.cond (2 branches) +# and torch.switch (N branches): both must produce subgraphs with a unified +# placeholder signature so the higher order op can pass a single operand list. +# +# Returns (shared, unique_per_branch): +# * shared: proxies present in every branch's lifted freevars. For plain +# proxies, "present" means by identity. For get_attr proxies, "present" +# means by node target (branches in separate tracing contexts can produce +# distinct proxies for the same nn module attr); the proxy from the first +# branch is chosen as the canonical representative. +# * unique_per_branch[i]: proxies lifted by branch i, not shared, and not +# already assigned to an earlier branch's unique block. With N > 2 a +# freevar can be lifted by some but not all branches; the first such branch +# claims it, and later branches that also lift it reuse the same placeholder. +# For N == 2 any non-shared freevar is lifted by exactly one branch -> no-op. +# Each block is sorted by node name for determinism. +# +# Side effect: each graph is rewritten in-place so its placeholders follow the +# 1 + N block layout: shared block (no suffix), then one block per branch +# (suffixed with "_") holding that branch's unique freevars. A +# branch graph wires its inner uses to whichever block holds the placeholder +# for the freevar it lifted (its own block, or the earlier branch that +# claimed it); the remaining blocks become unused placeholders for signature +# alignment. +def _merge_graph_inputs( + graphs: list[torch.fx.Graph], + lifted_freevars: list[dict[Proxy, Proxy]], + names: list[str], +) -> tuple[list[Proxy], list[list[Proxy]]]: + n = len(graphs) + if n != len(lifted_freevars) or n != len(names): + raise AssertionError( + "Expected graphs, lifted_freevars and names to have the same length" + ) + if n == 0: + raise AssertionError("Expected at least one graph") + + # Step 1: pick a canonical proxy for every distinct outer freevar across + # branches, deduplicating get_attrs that share a target. A canonical proxy + # is shared iff every branch contributed to it. + get_attr_canonical: dict[Any, Proxy] = {} + per_branch_outer_to_canonical: list[dict[Proxy, Proxy]] = [] + canonical_branch_count: Counter[Proxy] = Counter() + for branch_lifted in lifted_freevars: + outer_to_canonical: dict[Proxy, Proxy] = {} + for outer in branch_lifted: + canonical = outer + if outer.node.op == "get_attr": + target = outer.node.target + canonical = get_attr_canonical.setdefault(target, outer) + outer_to_canonical[outer] = canonical + per_branch_outer_to_canonical.append(outer_to_canonical) + canonical_branch_count.update(set(outer_to_canonical.values())) + + shared_canonical = {c for c, count in canonical_branch_count.items() if count == n} + + # Step 2: derive the shared block and the per-branch unique blocks. Plain + # proxies are the same object across branches, so a single canonical entry + # covers all of them; for shared get_attrs the canonical is the branch-0 + # proxy. A non-shared canonical lifted by multiple branches is assigned + # to the first branch that lifted it. + def _sort_by_name(vars: Iterable[Proxy]) -> list[Proxy]: + return sorted(vars, key=lambda var: var.node.name) + + shared = _sort_by_name(shared_canonical) + claimed_canonical: set[Proxy] = set(shared_canonical) + unique_per_branch: list[list[Proxy]] = [] + for outer_to_canonical in per_branch_outer_to_canonical: + branch_unique = [] + for outer, canonical in outer_to_canonical.items(): + if canonical in claimed_canonical: + continue + branch_unique.append(outer) + claimed_canonical.add(canonical) + unique_per_branch.append(_sort_by_name(branch_unique)) + + # For N branches the merged signature has 1 + N blocks: shared (no suffix) + # then one suffixed block per branch. Within each block proxies are + # ordered by node name for determinism. + def fixup_branch_inps( + graph: torch.fx.Graph, + branch_lifted: dict[Proxy, Proxy], + outer_to_canonical: dict[Proxy, Proxy], + ) -> None: + # Reverse-map canonical -> this branch's outer proxy so we can find the + # old placeholder to replace when emitting the shared block. + canonical_to_branch_outer = {c: o for o, c in outer_to_canonical.items()} + + def _insert_or_replace_phs(new_args: Sequence[Proxy], name_suffix: str) -> None: + for arg in new_args: + new_ph = graph.placeholder(arg.node.name + name_suffix) + new_ph.meta = arg.node.meta + # If this branch lifted `arg` (directly or via a shared + # get_attr target), wire the new placeholder to the existing + # uses and erase the old placeholder. + local_outer = canonical_to_branch_outer.get(arg, arg) + if local_outer in branch_lifted: + old_ph = branch_lifted[local_outer].node + old_ph.replace_all_uses_with(new_ph) + # replace_all_uses_with doesn't clean users. Clean it manually so that we could erase it. + old_ph.users = {} + graph.erase_node(old_ph) + + first_not_ph_node = next( + node for node in graph.nodes if node.op != "placeholder" + ) + with graph.inserting_before(first_not_ph_node): + _insert_or_replace_phs(shared, "") + for other_name, other_unique in zip(names, unique_per_branch): + _insert_or_replace_phs(other_unique, "_" + other_name) + + for graph, branch_lifted, outer_to_canonical in zip( + graphs, lifted_freevars, per_branch_outer_to_canonical + ): + fixup_branch_inps(graph, branch_lifted, outer_to_canonical) + + return shared, unique_per_branch + + +# NOTE: [HigherOrderOperator subgraph input ordering] +# The input ordering of the higher order ops is determined by the order of +# the creation of the placeholder. +# Manually created inputs are created in validate_args_and_maybe_create_graph_inputs before +# speculating subgraph. +# During subgraph speculation, we may lift closured tensors and free symbols as inputs, +# their ordering is determined by the time they are lifted: earlier lifted ones precede later +# lifted ones. +# +# Suppose the placeholders are +# O1, O2, X1, O3, O4, X2, X3, O5 where Xs are lifted phs +# The following code re-order the placeholders to +# O1, O2, O3, O4, O5, X1, X2, X3 +def move_lifted_freevars_phs_to_end( + graph: torch.fx.Graph, lifted_freevars: dict[Proxy, Proxy] +) -> None: + lifted_ph_set = {child_p.node for child_p in lifted_freevars.values()} + + prev_phs = [n for n in graph.nodes if n.op == "placeholder"] + + # No need to reorder when graph doesn't have args or doesn't + # have lifted freevars or all inputs are lifted freevars. + if ( + len(prev_phs) == 0 + or len(lifted_ph_set) == 0 + or len(prev_phs) == len(lifted_ph_set) + ): + return + + # Step 1: find first X1 + for x1 in prev_phs: + if x1 in lifted_ph_set: + break + + if x1 is None: + raise AssertionError("x1 must not be None") + if x1.op != "placeholder": + raise AssertionError("x1.op must be 'placeholder'") + # Step 2: starting from the X1, skip Xs and prepend Os before X1. + cand_x = x1.next + while cand_x is not None and cand_x.op == "placeholder": + if cand_x in lifted_ph_set: + cand_x = cand_x.next + else: + nxt = cand_x.next + cand_x._remove_from_list() + x1.prepend(cand_x) + cand_x = nxt + + # Step 3: assert that all placeholders are in the correct order as . + # in lifted_freevars + after_phs = [node for node in graph.nodes if node.op == "placeholder"][ + -len(lifted_freevars) : + ] + if len(after_phs) != len(lifted_freevars): + raise AssertionError( + "Number of trailing placeholders must match number of lifted_freevars" + ) + for child_proxy, ph in zip(lifted_freevars.values(), after_phs): + if child_proxy.node is not ph: + raise AssertionError( + "The order of placeholders is different from the order of lifted_freevars" + ) + + graph.lint() + + +def check_aliasing_and_input_mutation( + subtracer: "SubgraphTracer", + graph: torch.fx.Graph, + supports_input_mutation: bool, + supports_aliasing: bool, + source_target: Optional["HigherOrderOperator"], +) -> None: + name = source_target.name if source_target else "" + if not supports_input_mutation: + mutation_info = subtracer.has_input_mutation() + if mutation_info.has_mutation: + context = f"{mutation_info.msg} in\n {graph}" + unimplemented( + gb_type="Encountered input mutation during higher order op tracing", + context=context, + explanation=f"Higher order ops do not support input mutation. Found in {name}", + hints=[ + "Consider using the debug context to change user code to avoid mutation.", + "Please open an issue.", + ], + ) + + if not supports_aliasing: + aliasing_info = subtracer.has_aliasing() + if aliasing_info.has_aliasing: + context = f"{aliasing_info.msg} in\n {graph}" + unimplemented( + gb_type="Encountered aliasing during higher order op tracing", + context=context, + explanation=f"Higher order ops do not support aliasing. Found in {name}", + hints=[ + "Replace `return input` with `return input.clone()` to avoid aliasing.", + "Consider using the debug context to change user code to avoid aliasing.", + "Please open an issue.", + ], + ) + + +def trace_hop_function( + f: VariableTracker, + tx: "InstructionTranslatorBase", + subtracer: "SubgraphTracer", + enable_grad: bool | None, + restore_side_effects: bool, + args: list[VariableTracker], + sub_kwargs: dict[str, VariableTracker], +) -> VariableTracker: + # For autograd.Function and other legacy HOPs, we do NOT couple + # restore_side_effects with allow_side_effects_in_hop. + # This preserves the old behavior where: + # - restore_side_effects=False means ctx mutations persist + # - But non-ctx side effects still cause graph breaks (under_activation_checkpoint was False) + enable_side_effects_with_extra_outputs = False + + autograd_ctx = ( + dynamo_enable_grad(tx, enable_grad) + if enable_grad is not None + else contextlib.nullcontext() + ) + side_effects_ctx = ( + dynamo_allow_side_effects_in_hop(tx) + if enable_side_effects_with_extra_outputs + else contextlib.nullcontext() + ) + + # For handling side effects, we can make an argument that we don't + # have to do anything here. The side effects infra does a good job + # of graph breaking if we mutate any nonlocal or global variable + # while subtracing. As a result if tracing succeeds, side effects + # data structure will only contain read-only data structures that + # are put there for tracking purposes. + # But on the other hand, there is an argument that if we ever write + # a new side effect in Dynamo which does not go through the side + # effect infra, we can end up in bad state. + # Therefore we restore the side effects after tracing. The catch is + # that we have to special handle tensor variables. If we have seen a + # nonlocal variable tensor during subtracing, we want to keep a + # track of that tensor, so that later subtracing or the root tracer + # itself does not create a new proxy for the already observed tensor + # variable. + prev_side_effects = None + if restore_side_effects: + prev_side_effects = tx.output.side_effects.clone() + + # When restoring side effects, defer outer-scope mutation checks so + # context managers that flip-flop a flag don't fail immediately. After + # tracing, we validate that all deferred mutations were nullified. + deferred_ctx = ( + tx.output.side_effects.defer_side_effect_checks() + if restore_side_effects + else contextlib.nullcontext() + ) + + with autograd_ctx, side_effects_ctx, deferred_ctx: + output = f.call_function(tx, args, sub_kwargs) + + if restore_side_effects: + new_side_effects = tx.output.side_effects.clone() + if prev_side_effects is None: + raise AssertionError( + "prev_side_effects must not be None when restoring side effects" + ) + prev_side_effects.track_runahead_tensor_and_symvar_side_effects( + new_side_effects + ) + tx.output.side_effects = prev_side_effects + return output + + +def trace_hop_function_with_auto_output_flattening( + f: VariableTracker, + tx: "InstructionTranslatorBase", + subtracer: "SubgraphTracer", + enable_grad: bool | None, + allow_side_effects: bool, + args: list[VariableTracker], + sub_kwargs: dict[str, VariableTracker], +) -> VariableTracker: + autograd_ctx = ( + dynamo_enable_grad(tx, enable_grad) + if enable_grad is not None + else contextlib.nullcontext() + ) + side_effects_ctx = ( + dynamo_allow_side_effects_in_hop(tx) + if allow_side_effects + else contextlib.nullcontext() + ) + + deferred_ctx = ( + tx.output.side_effects.defer_side_effect_checks() + if not allow_side_effects + else contextlib.nullcontext() + ) + + with autograd_ctx, side_effects_ctx, deferred_ctx: + output = f.call_function(tx, args, sub_kwargs) + + return output + + +def get_hop_args( + tx: "InstructionTranslatorBase", + f: VariableTracker, + subtracer: "SubgraphTracer", + sub_args: list[VariableTracker], + sub_kwargs: dict[str, VariableTracker], + set_subgraph_inputs: SetSubgraphInputs, + description: str, +) -> list[VariableTracker]: + sub_args_names = maybe_positional_arg_names(f) + # User mismatch in the number of args. Will eventually lead to an error. + if sub_args_names is not None and len(sub_args_names) < len(sub_args): + sub_args_names = None + args = validate_args_and_maybe_create_graph_inputs( + sub_args, + subtracer, + tx, + set_subgraph_inputs, + description, + sub_args_names, + ) + + validate_args_and_maybe_create_graph_inputs( + sub_kwargs.values(), # type: ignore[arg-type] + subtracer, + tx, + set_subgraph_inputs="automatic", + description=description, + ) + return args + + +# TODO - The eventual goal is to replace +# speculate_subgraph_with_auto_output_flattening with speculate_subgraph or +# merge them two into one. We are following a staged approach because of +# existing implementation complexity for control flow ops. +def speculate_subgraph_with_auto_output_flattening( + tx: "InstructionTranslatorBase", + f: VariableTracker, + sub_args: list[VariableTracker], + sub_kwargs: dict[str, VariableTracker] | None, + description: str, + *, + # source_target is the .value of HigherOrderOpVariable and is the + # target of the proxy that we created for the higherOrderOperator. + source_target: HigherOrderOperator | None = None, + enable_grad: bool | None = None, + # automatic: relies on Dynamo to find the used tensors and lift them as + # inputs. + # + # automatic_with_forced_inputs: relies on the function arg names to create + # a new proxy. Also, it will always INSERT a tensor placeholder as input, + # even though it might not be used in the graph and they will also be in the + # same order as the original function (as opposed to automatic which will + # not insert the unused placeholder and can insert other placeholders in the + # order they are see while tracing). This is useful for autograd.Function + # backward where we do need to account for all the inputs of the backwards + # to be lifted as inputs for making the fwd-bwd graph consistent. + set_subgraph_inputs: SetSubgraphInputs = "automatic", + # If True, exposes intermediates to subgraph outputs to allow later tensor ops to + # access intermediates from the subgraph, this is useful for mutation + allow_side_effects: bool = False, + # Controls whether to filter aliased intermediates when collecting extra outputs. + # This is only relevant when allow_side_effects=True. + # - True: Filter out intermediates that alias with inputs or outputs (strict, for invoke_subgraph) + # - False: Allow aliased intermediates (for checkpoint/autograd.Function which get desugared/inlined) + # + # Example where filtering is needed: + # + # @invoke_subgraph + # def gn(x): + # view = x.view(2, 4) # intermediate that aliases input x + # y = torch.sin(view) + # return torch.cos(view) + # + # def fn(x): + # res = gn(x) + # return res + 4 + # + # In this case, if we don't filter `view`, we would later error because some HOPs + # have strict aliasing checks on inputs/outputs. + # + # This does however introduce a subtle issue when we do something like: + # + # captured = [] + # + # @invoke_subgraph + # def gn(x): + # view = x.view(2, 4) # intermediate that aliases input x + # y = torch.sin(view) + # captured.append(view) + # return torch.cos(view) + # + # def fn(x): + # res = gn(x) + # return res + captured[0] + # + # In this case, we will not replay the side effect on `captured` in the graph, + # which fails with a not-so-nice error. We will address this in a follow-up PR + # because this case is rare. This is not a regression because side effects were + # never supported for invoke_subgraph anyway. + filter_aliased_intermediates: bool = False, + # TODO - supports input_mutation and aliasing should be False by default for strictness + supports_input_mutation: bool = True, + supports_aliasing: bool = True, + # Pass in an originating tracer - this is needed for preserving context + # across fwd-bwd for autograd.Function + tracer: Optional["SubgraphTracer"] = None, +) -> tuple[ + VariableTracker, # output: The VT that Dynamo continues tracing with + torch.fx.Graph, # graph: The FX graph representing the subgraph computation + dict[ + torch.fx.Proxy, torch.fx.Proxy + ], # lifted_freevars: Free variables lifted as inputs + VariableTracker + | tuple[ + VariableTracker, ... + ], # graph_output_vts: Tensor/symint VTs that are actual FX graph outputs + SubgraphTracingInfo, # tracing_info: Properties observed during subgraph tracing +]: + """ + Speculate subgraph for Higher-Order Operators (HOPs) with automatic output flattening. + + ## Automatic output flattening + + For many HOPs, the representation exists only as a container for the + subgraph. In later compiler stages or at runtime, the HOP is desugared and + simply executes the subgraph directly, as if it were inlined. For such hops, + we follow automatic output flattening. + For example: + - invoke_subgraph + - activation checkpointing (torch.utils.checkpoint.checkpoint) + - autograd.Function + - nested_compile_region + + This is in contrast to control flow HOPs which do not follow this desugaring: + - torch.cond (conditional execution based on predicate) + - torch.while_loop (iterative execution) + - torch.map (parallel execution over batch dimension) + + For control flow HOPs, the HOP behavior is fundamentally different from just + running the body function once. + + ## Key Advantage: Disentangling VTs from Graph Outputs + + Desugaring simplify HOP processing by allowing us to disentangle the output + variable trackers (VTs) from the HOP subgraph outputs. This mirrors typical + Dynamo processing where: + - VTs "run ahead" representing the program state for continued tracing + - The graph is a side data structure tracking computation seen so far + + This separation is crucial for HOPs with non-proxyable outputs (e.g., custom + user-defined objects containing tensors). The function may return complex Python + objects for Dynamo to continue tracing, but only the tensor/symint VTs need to + be registered as actual FX graph outputs. + + Example: + class Foo: + def __init__(self, a, b): + self.a = a # tensor + self.b = b # tensor + + def gn(x): + return Foo(torch.sin(x), torch.cos(x)) + + result = some_hop(gn, x) # Returns Foo instance + out = result.a + result.b # Dynamo can continue tracing + + Here, `output` VT is a UserDefinedObjectVariable wrapping Foo, but + `graph_output_vts` contains only the tensor VTs (a and b) that should be + actual FX graph outputs. This allows Dynamo to continue tracing with the + Foo object while the graph only needs to output the constituent tensors. + + ## Return Values + + Unlike `speculate_subgraph`, this function returns: + - output: The VT that Dynamo continues tracing with (may be complex Python objects) + - graph: The FX graph representing the subgraph computation + - lifted_freevars: Free variables lifted as inputs to the subgraph + - graph_output_vts: Only the tensor/symint VTs that are actual FX graph outputs + + The key difference is `graph_output_vts` instead of `treespec`, which gives more + flexibility for handling non-proxyable outputs. + """ + if sub_kwargs is None: + sub_kwargs = {} + + if set_subgraph_inputs not in get_args(SetSubgraphInputs): + raise AssertionError( + "Please use one of the supported set_subgraph_inputs options." + ) + + # See NOTE [Temporary argument `set_subgraph_inputs`] + if sub_kwargs and set_subgraph_inputs != "automatic": + unimplemented( + gb_type="invalid set_subgraph_inputs and sub_kwargs settings", + context=f"set_subgraph_inputs: {set_subgraph_inputs}, sub_kwargs: {sub_kwargs}", + explanation="`sub_kwargs` cannot be used when `set_subgraph_inputs` is not set to 'automatic'.", + hints=[ + "Use `set_subgraph_inputs='automatic'` when passing `sub_kwargs`.", + *graph_break_hints.USER_ERROR, + ], + ) + + try: + with tx.output.subtracer(source_target, tracer, description) as subtracer: + args = get_hop_args( + tx, + f, + subtracer, + list(sub_args), + sub_kwargs, + set_subgraph_inputs, + description, + ) + + # Special case - if users uses + # `traced_with_externally_visible_side_effects`, we still need to + # return the intermediates as outputs. However, this API gets + # triggered during the hop tracing, and we don't know at this point + # of time, if the API will take into effect. To handle this, we have + # a flag traced_with_externally_visible_side_effects (default=False) + # that is set to True anytime + # `traced_with_externally_visible_side_effects` is set. We reset it + # with the old value after the hop is traced out. + old_value = ( + tx.output.current_tracer.traced_with_externally_visible_side_effects + ) + + output = trace_hop_function_with_auto_output_flattening( + f, + tx, + subtracer, + enable_grad, + allow_side_effects, + args, + sub_kwargs, + ) + + # NOTE: [Separation of graph outputs and output VTs] + # In Dynamo (outside of speculate_subgraph), VTs and the graph are + # separate concepts: + # - VTs (VariableTrackers) can "run ahead" and continue Dynamo tracing + # - The graph is just a side data structure tracking computation seen so far + # + # This separation is crucial for HOPs with non-proxyable outputs (e.g., + # custom user-defined objects containing tensors). The function may return + # complex Python objects for Dynamo to continue tracing, but only the + # tensor/symint VTs need to be registered as actual graph outputs. + # + # Example: + # class Foo: + # def __init__(self, a, b): + # self.a = a # tensor + # self.b = b # tensor + # + # def gn(x): + # return Foo(torch.sin(x), torch.cos(x)) + # + # Here, `output` VT is a UserDefinedObjectVariable wrapping Foo, but + # `graph_output_vts` contains only the tensor VTs (a and b) that should + # be actual FX graph outputs. + # Collect only tensor and symint VTs that should be graph outputs. + # We walk the output structure and extract proxyable VTs. + graph_output_vts: list[VariableTracker] = [] + + def visit(vt: VariableTracker) -> None: + if vt.is_tensor() or isinstance( + vt, (SymNodeVariable, CustomClassObjectVariable) + ): + graph_output_vts.append(vt) + + VariableTracker.visit(visit, output, side_effects=tx.output.side_effects) + + # NOTE - [Return subgraph intermediates as subgraph outputs] + # This helps HOPs which allow side effects. Consider the + # following example + # + # def gn(x, z): + # o = torch.matmul(x, x) @ x + # out = x.sin() + # z.append(out) + # return torch.cos(torch.sin(o)) + + # def fn(x): + # z = [] + # out1 = torch.utils.checkpoint.checkpoint( + # gn, + # x, + # z, + # use_reentrant=False, + # ) + # return out1, z[0] + # + # In this example, list `z` is in outer scope and gets appended + # in the subgraph with `out`. But `out` is not an output of the + # subgraph. This can cause issue because later on when the outer + # graph returns `z[0]` it needs to have access to the graph node + # `out`. To solve this problem, we just return all intermediates + # from the subgraph. + + # TODO - Today this is supported only for AC. AC HOP gets + # desugared in AOTDispatcher so even though subgraph has extra + # unused outputs in Dynamo, its ok even if we don't DCE them in + # Dynamo. As AOTDispatcher desugars/inlines the subgraph, the + # subgraph boundary disappears. And even for AC, today this only + # works when the skip_fwd_side_effects_in_bwd_under_checkpoint + # flag is True, i.e., only when we allow side-effects. But, we + # want this to be supported for other Hops as well, specifically + # nested_compile_region and autograd.Function. Today, its safe + # because we error out on seeing a side-effect. + + traced_externally = ( + tx.output.current_tracer.traced_with_externally_visible_side_effects + ) + has_side_effects = ( + subtracer.side_effect_stack is not None or traced_externally + ) + if (allow_side_effects or traced_externally) and has_side_effects: + extra_outputs = collect_intermediate_outputs( + tx, subtracer, graph_output_vts, filter_aliased_intermediates + ) + graph_output_vts = graph_output_vts + extra_outputs + + tx.output.current_tracer.traced_with_externally_visible_side_effects = ( + old_value + ) + + validate_subgraph_output_types(graph_output_vts) + + # The output proxies might not belong to this SubgraphTracer + # (if they are free variables that were never lifted) + # so lift them here. + # output_proxies = output.as_proxy() + if isinstance(graph_output_vts, list): + output_proxies = [a.as_proxy() for a in graph_output_vts] # type: ignore[attr-defined] + output_proxies = pytree.tree_map( + subtracer.maybe_lift_tracked_freevar_to_input, output_proxies + ) + output_proxies = tuple(output_proxies) + else: + output_proxies = output.as_proxy() + output_proxies = pytree.tree_map( + subtracer.maybe_lift_tracked_freevar_to_input, output_proxies + ) + + tx.output.create_node( + "output", + "output", + (subtracer.create_arg((output_proxies,))), + {}, + ) + graph = tx.output.graph + graph.lint() + lifted_freevars = subtracer.lifted_freevars + + if len(lifted_freevars) > 0: + move_lifted_freevars_phs_to_end(graph, lifted_freevars) + + check_aliasing_and_input_mutation( + subtracer, + graph, + supports_input_mutation, + supports_aliasing, + source_target, + ) + # Return both the output VT and the graph output VTs separately: + # - `output`: The VT that Dynamo continues tracing with (may be + # complex Python objects, tuples, dicts, etc.) + # - `graph`: The FX graph representing the subgraph computation + # - `lifted_freevars`: Free variables lifted as inputs to the subgraph + # - `graph_output_vts`: Only the tensor/symint VTs that are actual + # FX graph outputs (basically the vts associated with graph outputs) + # - `tracing_info`: Properties observed during subgraph tracing + tracing_info = SubgraphTracingInfo( + side_effect_stack=subtracer.side_effect_stack, + traced_sources=subtracer.traced_sources, + ) + + return ( + output, + graph, + lifted_freevars, + tuple(graph_output_vts), + tracing_info, + ) + except Unsupported as ex: + f_name = f"{type(f).__name__}" + if isinstance(f, UserFunctionVariable): + f_name = f.get_name() + msg = ( + f"speculate_subgraph: while introspecting {description}, we were unable " + f"to trace function `{f_name}` into a single graph. This means " + f"that Dynamo was unable to prove safety for this API and will " + f"fall back to eager-mode PyTorch, which could lead to a slowdown." + ) + log.info(msg) + log.info(ex) + raise ex + + +# See NOTE [HigherOrderOperator tracing design] for details of the design +def speculate_subgraph( + tx: "InstructionTranslatorBase", + f: VariableTracker, + sub_args: list[VariableTracker], + sub_kwargs: dict[str, VariableTracker] | None, + description: str, + *, + # source_target is the .value of HigherOrderOpVariable and is the + # target of the proxy that we created for the higherOrderOperator. + source_target: HigherOrderOperator | None = None, + always_restore: bool = False, + enable_grad: bool | None = None, + # NOTE [argument `set_subgraph_inputs`] + # set_subgraph_inputs controls what how to construct subgraphs' placeholders from sub_args. + # 1. if your HOP supports arbitrary inputs, use set_subgraph_inputs="automatic" (most recommended). + # 2. if your HOP supports only Tensor and symnode inputs, use set_subgraph_inputs="flatten_manual" (recommended). + # If sub_args contain Pytree structure (e.g. dict/list/tuple/set), the sub_args will be flattened first. + # Then the flattened args are manually set as subgraph's placeholders. + # 3. if your HOP must preserve inputs that are not tensor or symnode as placeholders e.g. AutogradFunctionContextVariable + # use set_subgraph_inputs="manual" (not recommended). We do not recommend it in general because it has the + # restriction that user need to manually control how to create placeholders and VariableTrackers for the args. + set_subgraph_inputs: SetSubgraphInputs = "automatic", + restore_side_effects: bool = True, + should_flatten_outputs: bool = False, + # if should_flatten_outputs is True, `remove_consts_from_outputs` remove the + # const outputs from the subgraph output. + remove_consts_from_outputs: bool = True, + # TODO - supports input_mutation and aliasing should be False by default for strictness + supports_input_mutation: bool = True, + supports_aliasing: bool = True, + # Pass in an originating tracer - this is needed for preserving context + # across fwd-bwd for autograd.Function + tracer: Optional["SubgraphTracer"] = None, +) -> tuple[tuple[VariableTracker, OutputSpec], torch.fx.Graph, dict[Proxy, Proxy]]: + if sub_kwargs is None: + sub_kwargs = {} + + from .builder import SourcelessBuilder + + if set_subgraph_inputs not in get_args(SetSubgraphInputs): + raise AssertionError( + "Please use one of the supported set_subgraph_inputs options." + ) + + # See NOTE [Temporary argument `set_subgraph_inputs`] + if sub_kwargs and set_subgraph_inputs != "automatic": + unimplemented( + gb_type="invalid set_subgraph_inputs and sub_kwargs settings", + context=f"set_subgraph_inputs: {set_subgraph_inputs}, sub_kwargs: {sub_kwargs}", + explanation="`sub_kwargs` cannot be used when `set_subgraph_inputs` is not set to 'automatic'.", + hints=[ + "Use `set_subgraph_inputs='automatic'` when passing `sub_kwargs`.", + *graph_break_hints.USER_ERROR, + ], + ) + + try: + # ensure guards on args get installed in parent subgraph + f, sub_args, sub_kwargs = LazyVariableTracker.realize_all( + (f, sub_args, sub_kwargs), + ) + + with tx.output.subtracer(source_target, tracer, description) as subtracer: + args = get_hop_args( + tx, f, subtracer, sub_args, sub_kwargs, set_subgraph_inputs, description + ) + + output = trace_hop_function( + f, + tx, + subtracer, + enable_grad, + restore_side_effects, + args, + sub_kwargs, + ) + + treespec = None + masks_to_filter_const_values = None + const_values = None + if should_flatten_outputs: + from torch._dynamo.external_utils import filter_out_const_values + + # Flatten the speculated subgraph output. + output, treespec = unpack_iterable( + tx, _make_inlined(tx, pytree.tree_flatten)(output) + ) + + # Actually, transform the list (returned by flatten) into a tuple + # for dynamo consistency. + output = SourcelessBuilder.create(tx, tuple).call_function( + tx, [output], {} + ) + + if remove_consts_from_outputs: + # Filter out the constants and save them into a spec. Filtering + # out constants makes the graph simpler for the backends. We + # need to ensure that after unflattening the constants are + # inserted back at the right positions for the Dynamo tracing to + # continue. This is done by filter_const_spec + output_proxies = output.as_proxy() + masks_to_filter_const_values = pytree.tree_map( + lambda x: not isinstance(x, torch.fx.Proxy), output_proxies + ) + const_values = pytree.tree_map( + lambda x: None if isinstance(x, torch.fx.Proxy) else x, + output_proxies, + ) + output = _make_inlined(tx, filter_out_const_values)( + output, masks_to_filter_const_values + ) + + # TODO - clean up num_intermediate_nodes_as_outputs - we do not need + # after AC moved to auto_output_flattening + num_intermediate_nodes_as_outputs = 0 + # Register output to graph + # Modeled off of compile_and_call_fx_graph + # TODO: support pytree output + # We check always_restore because we don't use the output or side effects of always_restore code, + # like bwd. + if always_restore: + # Nothing left to do here + return ( + ( + output, + OutputSpec( + treespec, # type: ignore[arg-type] + masks_to_filter_const_values, + const_values, + num_intermediate_nodes_as_outputs, + ), + ), + tx.output.graph, + subtracer.lifted_freevars, + ) + else: + validate_subgraph_output_types(output) + + # The output proxies might not belong to this SubgraphTracer + # (if they are free variables that were never lifted) + # so lift them here. + output_proxies = output.as_proxy() + output_proxies = pytree.tree_map( + subtracer.maybe_lift_tracked_freevar_to_input, output_proxies + ) + + tx.output.create_node( + "output", + "output", + (subtracer.create_arg((output_proxies,))), + {}, + ) + graph = tx.output.graph + graph.lint() + lifted_freevars = subtracer.lifted_freevars + + if len(lifted_freevars) > 0: + move_lifted_freevars_phs_to_end(graph, lifted_freevars) + check_aliasing_and_input_mutation( + subtracer, + graph, + supports_input_mutation, + supports_aliasing, + source_target, + ) + mutation_info = subtracer.has_input_mutation() + graph._dynamo_mutated_input_indices = ( # pyrefly: ignore[missing-attribute] + mutation_info.mutated_input_indices + ) + + return ( + ( + output, + OutputSpec( + treespec, # type: ignore[arg-type] + masks_to_filter_const_values, + const_values, + num_intermediate_nodes_as_outputs, + ), + ), + graph, + lifted_freevars, + ) + + except Unsupported as ex: + f_name = f"{type(f).__name__}" + if isinstance(f, UserFunctionVariable): + f_name = f.get_name() + msg = ( + f"speculate_subgraph: while introspecting {description}, we were unable " + f"to trace function `{f_name}` into a single graph. This means " + f"that Dynamo was unable to prove safety for this API and will " + f"fall back to eager-mode PyTorch, which could lead to a slowdown." + ) + log.info(msg) + log.info(ex) + raise ex + + +def make_attr(tx: "InstructionTranslatorBase", name: str) -> Proxy: + node = tx.output.create_proxy( + "get_attr", + name, + (), + {}, + ) + return node + + +def add_hop_context(cls: type[HOP_VT_Alias]) -> type[HOP_VT_Alias]: + """ + Class decorator that adds HOP context to exceptions raised in call_function. + + Requires the class to have _HOP_NAME and _ALLOW_FALLBACK_TO_EAGER set. + """ + + if hasattr(cls.call_method, "_hop_wrapped"): + return cls + + if cls._HOP_NAME is None: + raise TypeError(f"{cls.__name__} must define _HOP_NAME class attribute.") + if cls._ALLOW_FALLBACK_TO_EAGER is None: + raise TypeError( + f"{cls.__name__} must define _ALLOW_FALLBACK_TO_EAGER class attribute." + ) + + original_call_function = cls.call_function + + @functools.wraps(original_call_function) + def wrapped_call_function(self, *args: Any, **kwargs: Any) -> VariableTracker: + try: + return original_call_function(self, *args, **kwargs) + except UncapturedHigherOrderOpError as e: + if not hasattr(e, "_hop_name"): + e._hop_name = self._HOP_NAME # pyrefly: ignore[missing-attribute] + raise + except (Unsupported, ObservedException) as e: + if isinstance(e, FakeTensorObservedException): + raise + # Only tag if not already tagged (reports deepest HOP only) + if hasattr(e, "_hop_name"): + raise + + if self._ALLOW_FALLBACK_TO_EAGER: + # Tag the exception with HOP name for later formatting in exc.py + # NOTE: because nested graph breaks are NOT supported on HOPs, we will + # NEVER log a HOP graph break before running this + e._hop_name = self._HOP_NAME # pyrefly: ignore[missing-attribute] + raise + else: + real_stack = getattr(e, "real_stack", None) + full_msg = ( + "This higher order operator doesn't work unless it is " + "captured completely with torch.compile. Got graph break/error:" + f"\n\n{str(e)}" + ) + exc = UncapturedHigherOrderOpError(full_msg, real_stack) + exc._hop_name = self._HOP_NAME # pyrefly: ignore[missing-attribute] + raise exc.with_traceback(e.__traceback__) from None + + wrapped_call_function._hop_wrapped = True # pyrefly: ignore[missing-attribute] + cls.call_function = wrapped_call_function + return cls + + +class TorchHigherOrderOperatorVariable(VariableTracker): + # Subclasses should set _HOP_NAME to enable automatic HOP context in error messages + _HOP_NAME: str | None = None + # Set to False for HOPs that hard error on graph break (e.g., cond, map, scan); otherwise + # HOPs will fall back to eager. + _ALLOW_FALLBACK_TO_EAGER: bool = True + + def __init_subclass__(cls, **kwargs: Any) -> None: + super().__init_subclass__(**kwargs) + add_hop_context(cls) + + def __init__( + self, value: HigherOrderOperator, source: Source | None = None, **kwargs: Any + ) -> None: + super().__init__(**kwargs) + self.value = value + self.source = source + + @staticmethod + def make( + value: HigherOrderOperator, source: Source | None = None, **kwargs: Any + ) -> "TorchHigherOrderOperatorVariable": + variable_class = _hop_name_to_variable_class.get(value.__name__) + if variable_class is not None: + return variable_class(value, source, **kwargs) + + from torch._higher_order_ops import BaseHOP + + if isinstance(value, BaseHOP): + return BaseHOPVariable(value, source, **kwargs) + unimplemented( + gb_type="unsupported HigherOrderOperator", + context=str(value), + explanation=f"Unable to create higher order operator variable for {value.__name__}.", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + from .object_protocol import python_constant_richcompare_impl + + return python_constant_richcompare_impl(self, tx, other, op) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .torch_function import can_dispatch_torch_function, dispatch_torch_function + + if can_dispatch_torch_function(tx, args, kwargs): + return dispatch_torch_function(tx, self, args, kwargs) + + return self._call_function(tx, args, kwargs) + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + unimplemented( + gb_type="unsupported HigherOrderOperator function call", + context=str(self.value), + explanation=f"Unable to trace calling higher order operator variable for {self.value.__name__}.", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + def as_python_constant(self) -> HigherOrderOperator: + return self.value + + +class CustomFunctionHigherOrderOperatorVariable(TorchHigherOrderOperatorVariable): + """ + Wraps torch._functorch.autograd_function.custom_function_call + """ + + _HOP_NAME = "torch.ops.higher_order.custom_function_call" + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if self.source is None: + raise AssertionError("source must not be None") + return torch._dynamo.variables.UserMethodVariable( + self.value.__call__.__func__, + torch._dynamo.variables.UserDefinedObjectVariable( + self.value, source=self.source + ), + source=AttrSource(self.source, "__call__"), + ).call_function(tx, args, kwargs) + + +class CondHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.cond" + _ALLOW_FALLBACK_TO_EAGER = False + supports_input_mutation = False + supports_aliasing = False + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from . import ListVariable + + self.supports_input_mutation = not torch.is_grad_enabled() + self.supports_aliasing = not torch.is_grad_enabled() + + args, kwargs = LazyVariableTracker.realize_all((args, kwargs)) + + for i, k in enumerate(["pred", "true_fn", "false_fn", "operands"]): + if v := kwargs.pop(k, None): + if i != len(args): + raise AssertionError( + "did not provide the right number of non-keyword args" + ) + args.append(v) + + # TODO(voz): Support fake tensor dispatch for recursive + # ops - see torch/dispatch/_dispatcher.py + if len(args) != 4 or kwargs: + unimplemented( + gb_type="torch.cond: improper args/kwargs", + context=f"args: {args}, kwargs: {kwargs}", + explanation=f"torch.cond expects 4 positional arguments (got {len(args)}) " + f"and no keyword arguments (got {len(kwargs)}) " + "Usage: cond(pred, cond_fn, body_fn, operands)", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + # Specialize into one of the branches since pred is constant + pred, true_fn, false_fn, operands = args + if type(args[0]) is ConstantVariable: + warnings.warn( + "Pred is a Python constant. When used with torch.cond, it specializes on one of the branches." + " If you want torch.cond to preserve two branches, please make the predicate a boolean tensor or a SymBool.", + UserWarning, + ) + if pred.as_python_constant(): + return true_fn.call_function(tx, unpack_iterable(tx, operands), {}) + else: + return false_fn.call_function(tx, unpack_iterable(tx, operands), {}) + + # predicate + if type(pred.realize()) not in ( + ConstantVariable, + TensorVariable, + SymNodeVariable, + ): + unimplemented( + gb_type="torch.cond: improper predicate", + context=str(pred), + explanation="Expected `pred` to be a bool or a boolean tensor with a single item " + f"but got {str(type(pred))} with original python type {str(pred.python_type())}.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + # operands + if not isinstance(operands, (ListVariable, TupleVariable)): + unimplemented( + gb_type="torch.cond: improper operands", + context=str(operands), + explanation="Expected `operands` to be a list/tuple " + f"but got {operands.python_type()}.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + operands_seq = unpack_iterable(tx, operands) + if not only_consist_of( + operands, (TensorVariable, ConstantVariable, SymNodeVariable) + ): + unimplemented( + gb_type="torch.cond: improper operands contents", + context=str(operands), + explanation="Expected `operands` to be a list/tuple of pytrees that only consists of tensor leaves.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + # branches + _check_supported_callable_arg(tx, true_fn, "true_fn") + _check_supported_callable_arg(tx, false_fn, "false_fn") + + # Our strategy for tracing the true/false branches of cond + # are to checkpoint our graphstate, run the true branch, + # roll it back to the checkpoint, and run the false + # branch, and then merge the graphstates. Well, perhaps + # "merge" is too strong a word: we mostly assert that + # the resulting graphstates have to be the same. + # + # We only permit guards to diverge (we union the guards from + # both branches). In particular, this means that side + # effects are NOT permitted inside true/false branches; this + # would be difficult to implement, because of the path + # explosion problem. + + def speculate_branch( + branch: bool, + ) -> tuple[VariableTracker, OutputSpec, torch.fx.Graph, dict[Proxy, Proxy]]: + # NB: 0 is predicate + ix = 1 if branch else 2 + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + # TODO: Support kwargs + ( + (ret_val, ret_spec), + ret_graph, + ret_lifted_freevars, + ) = speculate_subgraph( + tx, + args[ix], + operands_seq, + {}, + self._HOP_NAME, + source_target=self.value, + should_flatten_outputs=True, + # TODO - removing consts from control flow ops need more work + remove_consts_from_outputs=False, + supports_input_mutation=self.supports_input_mutation, + supports_aliasing=self.supports_aliasing, + ) + + # need to ensure we increase epoch so we don't memoize unbacked bindings + # across different subgraphs which can interfere with runtime assertion + # generation. + if tx.fake_mode is None: + raise AssertionError("tx.fake_mode must not be None") + tx.fake_mode.epoch += 1 + + if not only_consist_of(ret_val, (TensorVariable, ConstantVariable)): + unimplemented( + gb_type="torch.cond: unsupported branch return type", + context=str(ret_val), + explanation="Expected branches to return a possibly nested pytree of tensors or constant ints.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + for ret in unpack_iterable(tx, ret_val): + if ret.is_python_constant() and not isinstance( + ret.as_python_constant(), int + ): + unimplemented( + gb_type="torch.cond: unsupported branch return type (constant non-int)", + context=str(ret_val), + explanation="Constants returned from branches must be ints.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + return ret_val, ret_spec, ret_graph, ret_lifted_freevars + + (true_r, true_spec, true_graph, true_lifted_freevars) = speculate_branch(True) + true_nn_modules = dict(tx.output.nn_modules) + + ( + false_r, + false_spec, + false_graph, + false_lifted_freevars, + ) = speculate_branch(False) + false_nn_modules = dict(tx.output.nn_modules) + + same_spec = _make_inlined(tx, pytree.TreeSpec.__eq__)( + true_spec.treespec, false_spec.treespec + ).as_python_constant() + # 3.14: NotImplemented cannot be converted to bool + if same_spec is not NotImplemented and not same_spec: + unimplemented( + gb_type="torch.cond: differing branch outputs", + context=f"true_spec: {true_spec.treespec}, false_spec: {false_spec.treespec}, same_spec: {same_spec}", + explanation="Expected branches to return the same pytree structure.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + shared, (unique_true, unique_false) = _merge_graph_inputs( + [true_graph, false_graph], + [true_lifted_freevars, false_lifted_freevars], + ["true_branch", "false_branch"], + ) + + true_name = tx.output.install_subgraph( + "cond_true", + torch.fx.GraphModule(true_nn_modules, true_graph), + ) + false_name = tx.output.install_subgraph( + "cond_false", + torch.fx.GraphModule(false_nn_modules, false_graph), + ) + + true_node = make_attr(tx, true_name) + false_node = make_attr(tx, false_name) + + p_args = ( + pred.as_proxy(), + true_node, + false_node, + tuple(shared + unique_true + unique_false), + ) + + return _call_function_and_unflatten_output( + tx, + torch.ops.higher_order.cond, + p_args, + {}, + None, + true_spec, + true_r, + ) + + +class SwitchHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.switch" + _ALLOW_FALLBACK_TO_EAGER = False + supports_input_mutation = False + supports_aliasing = False + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: Sequence[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from torch._higher_order_ops.switch import _get_branch + + from . import ListVariable + + self.supports_input_mutation = not torch.is_grad_enabled() + + args, kwargs = LazyVariableTracker.realize_all((args, kwargs)) + + for i, k in enumerate(["index", "branches", "operands"]): + if v := kwargs.pop(k, None): + if i != len(args): + raise AssertionError( + "did not provide the right number of non-keyword args" + ) + args.append(v) + + if len(args) != 3 or kwargs: + unimplemented( + gb_type="torch.switch: improper args/kwargs", + context=f"args: {args}, kwargs: {kwargs}", + explanation=f"torch.switch expects 3 positional arguments (got {len(args)}) " + f"and no keyword arguments (got {len(kwargs)}) " + "Usage: switch(index, branches, operands)", + hints=[*graph_break_hints.USER_ERROR], + ) + + index, branches, operands = args + if type(index) is ConstantVariable: + # Specialize into one of the branches since index is constant. + warnings.warn( + "Index is a Python constant. When used with torch.switch, it specializes on one of the branches." + " If you want torch.switch to preserve the branches, please make the index a tensor or SymInt.", + UserWarning, + ) + idx = index.as_python_constant() + branch_fns = branches.unpack_var_sequence(tx) + return _get_branch(branch_fns, idx).call_function( + tx, operands.unpack_var_sequence(tx), {} + ) + + # index + if type(index.realize()) not in ( + ConstantVariable, + TensorVariable, + SymNodeVariable, + ): + unimplemented( + gb_type="torch.switch: improper index", + context=str(index), + explanation="Expected index to be an int or a tensor with a single item " + f"but got {str(type(index))} with original python type {str(index.python_type())}.", + hints=[*graph_break_hints.USER_ERROR], + ) + + # operands + if not isinstance(operands, (ListVariable, TupleVariable)): + unimplemented( + gb_type="torch.switch: improper operands", + context=str(operands), + explanation=f"Expected operands to be a list/tuple " + f"but got {operands.python_type()}.", + hints=[*graph_break_hints.USER_ERROR], + ) + + operands_seq = operands.unpack_var_sequence(tx) + if not only_consist_of( + operands, (TensorVariable, ConstantVariable, SymNodeVariable) + ): + unimplemented( + gb_type="torch.switch: improper operands contents", + context=str(operands), + explanation="Expected `operands` to be a list/tuple of pytrees that only consists of tensor leaves.", + hints=[*graph_break_hints.USER_ERROR], + ) + + # branches + if not isinstance(branches, (ListVariable, TupleVariable)): + unimplemented( + gb_type="torch.switch: improper branches", + context=str(branches), + explanation="Expected branches to be a list/tuple of callables.", + hints=[*graph_break_hints.USER_ERROR], + ) + + branch_fns = branches.unpack_var_sequence(tx) + if len(branch_fns) == 0: + unimplemented( + gb_type="torch.switch: empty branches", + context=str(branches), + explanation="Expected at least one branch.", + hints=[*graph_break_hints.USER_ERROR], + ) + + for i, branch_fn in enumerate(branch_fns): + _check_supported_callable_arg(tx, branch_fn, f"branch{i}") + + # Our strategy for tracing the branches of switch mirrors cond: each + # branch is speculated in isolation and the resulting graphs are + # merged, asserting the output specs agree. Side effects are not + # permitted inside branches because of the path-explosion problem. + def speculate_branch( + func, + ) -> tuple[VariableTracker, OutputSpec, torch.fx.Graph, dict[Proxy, Proxy]]: + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + ( + (ret_val, ret_spec), + ret_graph, + ret_lifted_freevars, + ) = speculate_subgraph( + tx, + func, + operands_seq, + {}, + self._HOP_NAME, + source_target=self.value, + should_flatten_outputs=True, + remove_consts_from_outputs=False, + supports_input_mutation=self.supports_input_mutation, + supports_aliasing=self.supports_aliasing, + ) + + # need to ensure we increase epoch so we don't memoize unbacked bindings + # across different subgraphs which can interfere with runtime assertion + # generation. + if tx.fake_mode is None: + raise AssertionError("tx.fake_mode must not be None") + tx.fake_mode.epoch += 1 + + if not only_consist_of( + ret_val, (TensorVariable, ConstantVariable), allow_none=True + ): + unimplemented( + gb_type="torch.switch: unsupported branch return type", + context=str(ret_val), + explanation="Expected branches to return a possibly nested pytree of tensor or constant int/None leaves.", + hints=[*graph_break_hints.USER_ERROR], + ) + for ret in ret_val.unpack_var_sequence(tx): + if ret.is_python_constant(): + const = ret.as_python_constant() + # Python floats in branch outputs are blocked upstream by + # validate_subgraph_output_types (shared HOP gate); we + # mirror the whitelist here to keep the error specific to + # torch.switch. bool is implicitly accepted via the int check. + if not (isinstance(const, int) or const is None): + unimplemented( + gb_type="torch.switch: unsupported branch return type (constant)", + context=str(ret_val), + explanation="Constants returned from branches must be int or None.", + hints=[*graph_break_hints.USER_ERROR], + ) + return ret_val, ret_spec, ret_graph, ret_lifted_freevars + + branch_states: list[Any] = [] + branch_nn_modules: list[Any] = [] + for f in branch_fns: + branch_states.append(speculate_branch(f)) + branch_nn_modules.append(dict(tx.output.nn_modules)) + branch_rets, branch_specs, branch_graphs, branch_lifted_freevars = zip( + *branch_states + ) + + for i, (spec_a, spec_b) in enumerate(itertools.pairwise(branch_specs)): + same_spec = _make_inlined(tx, pytree.TreeSpec.__eq__)( + spec_a.treespec, spec_b.treespec + ).as_python_constant() + # 3.14: NotImplemented cannot be converted to bool + if same_spec is not NotImplemented and not same_spec: + unimplemented( + gb_type="torch.switch: differing branch outputs", + context=f"branch{i}: {spec_a.treespec}, branch{i + 1}: {spec_b.treespec}, same_spec: {same_spec}", + explanation="Expected branches to return the same pytree structure.", + hints=[*graph_break_hints.USER_ERROR], + ) + + # Merge lifted freevars across all branches so they all share the same + # placeholder signature. Branches may capture different free variables + # (e.g. different nn module attrs), so we union them and add missing + # placeholders to any branch graph that lacks them. + branch_names_for_merge = [f"branch{i}" for i in range(len(branch_fns))] + shared, unique_per_branch = _merge_graph_inputs( + list(branch_graphs), + list(branch_lifted_freevars), + branch_names_for_merge, + ) + all_lifted = shared + [u for branch in unique_per_branch for u in branch] + + branch_names = [ + tx.output.install_subgraph( + f"switch_branch{i}", + GraphModule(branch_nn_modules[i], graph), + ) + for i, graph in enumerate(branch_graphs) + ] + + branch_nodes = [make_attr(tx, name) for name in branch_names] + + p_args = ( + index.as_proxy(), + branch_nodes, + tuple(all_lifted), + ) + + return _call_function_and_unflatten_output( + tx, + torch.ops.higher_order.switch, + p_args, + {}, + None, + branch_specs[0], + branch_rets[0], + ) + + +class CallTorchbindHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.call_torchbind" + + def __init__( + self, + hop: HigherOrderOperator, + source: Source | None, + script_obj_var: Any, + method_name: str, + ) -> None: + super().__init__(hop, source) + self.script_obj_var = script_obj_var + self.method_name = method_name + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + args, kwargs = LazyVariableTracker.realize_all((args, kwargs)) + + args_proxy = [arg.as_proxy() for arg in args] + kwargs_proxy = {k: v.as_proxy() for k, v in kwargs.items()} + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + args=tuple( + [self.script_obj_var.as_proxy(), self.method_name] + args_proxy + ), + kwargs=kwargs_proxy, + ), + ) + + +def validate_subgraph_output_types( + output: VariableTracker | list[VariableTracker], +) -> None: + """Verify that the output of the subgraph is a tensor, + int, bool, SymBool, or SymInt. + """ + from . import TensorVariable + + if non_tensor_output := find_mismatched_vars( + output, TensorVariable, allow_none=True + ): + for out in non_tensor_output: + if ( + (isinstance(out, SymNodeVariable) and out.python_type() in (int, bool)) + or ( + out.is_python_constant() + and isinstance(out.as_python_constant(), (int, bool)) + ) + or isinstance(out, CustomClassObjectVariable) + ): + continue + unimplemented( + gb_type="HOP body output unsupported", + context=f"non-tensor outputs: {non_tensor_output}", + explanation="HigherOrderOperator body's output must consist of tensors or ints/bools only " + f"but got {out.python_type()}.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + +class WhileLoopHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.while_loop" + _ALLOW_FALLBACK_TO_EAGER = False + supports_input_mutation = False + supports_aliasing = False + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + self.supports_input_mutation = not torch.is_grad_enabled() + return _call_while_loop( + self, tx, args, kwargs, stack_output=False, hop_name=self._HOP_NAME + ) + + +class WhileLoopStackOutputHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.while_loop" + _ALLOW_FALLBACK_TO_EAGER = False + supports_input_mutation = False + supports_aliasing = False + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + return _call_while_loop( + self, tx, args, kwargs, stack_output=True, hop_name=self._HOP_NAME + ) + + +class AssociativeScanHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.associative_scan" + _ALLOW_FALLBACK_TO_EAGER = False + supports_input_mutation = False + supports_aliasing = False + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from torch._higher_order_ops.utils import first_slice_copy + + args, kwargs = LazyVariableTracker.realize_all((args, kwargs)) + + def arg_extractor( + combine_fn: VariableTracker, + xs: VariableTracker, + additional_inputs: VariableTracker, + ) -> tuple[VariableTracker, VariableTracker, VariableTracker]: + return combine_fn, xs, additional_inputs + + combine_fn, xs, additional_inputs = arg_extractor(*args, **kwargs) + + if args[0].python_type() is functools.partial: + # This is the standard case when the user calls the frontend + # and the frontend invokes dynamo + if len(args) != 2: + unimplemented( + gb_type="torch.associative_scan: improper args", + context=f"args: {args}", + explanation=f"torch.associative_scan expects 2 positional arguments (got {len(args)}) " + "Usage: associative_scan(combine_fn, xs)", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + xs_treespec = args[0].keywords["spec"] + + # combine_fn input check + # We need to get the pure combine_fn from the functools.partial + _check_supported_callable_arg( + tx, + combine_fn.keywords["combine_fn"], # type: ignore[attr-defined] + "combine_fn", + ) + else: + # This case is hit during re-tracing, for example in export tests + # In this case, the combine_fn is a callable and not a functools.partial + xs_treespec = _make_inlined(tx, pytree.tree_structure)(xs) + + _check_supported_callable_arg(tx, combine_fn, "combine_fn") + + # xs input check + if not isinstance(xs, (ListVariable, TupleVariable)): + unimplemented( + gb_type="torch.associative_scan: improper xs", + context=str(xs), + explanation=f"Expected xs to be a list/tuple but got {xs.python_type()}", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + xs_vars = unpack_iterable(tx, xs) + _check_all_tensorvariable(xs_vars) + + # additional_inputs input check + if not isinstance(additional_inputs, (ListVariable, TupleVariable)): + unimplemented( + gb_type="torch.associative_scan: improper additional_inputs", + context=str(additional_inputs), + explanation=f"Expected additional_inputs to be a list/tuple but got {additional_inputs.python_type()}", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + additional_inputs_vars = unpack_iterable(tx, additional_inputs) + _check_all_tensorvariable(additional_inputs_vars) + + # Trace the subgraph + # The sub_args is a slice of original input, e.g. if input.size is (3, 4), and scan dim=0 + # the sub_args shape will be (4, ). + with discard_graph_changes(tx): + sub_args = [ + _make_inlined(tx, first_slice_copy)(leaf) + for leaf in itertools.chain(xs_vars, xs_vars) + ] + sub_args_additional_inputs = [ + t.call_method(tx, "clone", args=[], kwargs={}) + for t in additional_inputs_vars + ] + + sub_args = sub_args + sub_args_additional_inputs + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + ( + (combine_result, _combine_spec), + combine_graph, + combine_lifted_freevars, + ) = speculate_subgraph( + tx, + combine_fn, + sub_args, + sub_kwargs={}, + description=self._HOP_NAME, + source_target=self.value, + set_subgraph_inputs="flatten_manual", + supports_input_mutation=self.supports_input_mutation, + supports_aliasing=self.supports_aliasing, + ) + + # Ensure that the output of scan is a flattened list of elements, + # because downstream operations assume that the output of HOPs + # is flattened + output_node = combine_graph.find_nodes(op="output")[0] + output_node.args = (pytree.tree_leaves(output_node.args),) + combine_graph.lint() + + # Collect the results from the combine_fn + results, _combine_treespec = unpack_iterable( + tx, _make_inlined(tx, pytree.tree_flatten)(combine_result) + ) + + # Check whether the combine_fn returns one child tree for the output. + if _combine_treespec.as_python_constant().num_leaves < 1: + unimplemented( + gb_type="torch.associative_scan: combine_fn improper number of leaves", + context=str(_combine_treespec.as_python_constant()), + explanation="combine_fn needs to produce one pytree for the output " + f"but combine_fn produces the pytree {_combine_treespec.as_python_constant()}.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + # Check whether the outs produced by combine_fn has the same treespec as xs + # We need to have this check this way, because in case init is a TreeSpec and carry + # but carry is only a LeafSpec, these two cannot be compared correctly. + if ( + xs_treespec.as_python_constant().is_leaf() + != _combine_treespec.as_python_constant().is_leaf() + ) or not _make_inlined(tx, pytree.TreeSpec.__eq__)( + xs_treespec, _combine_treespec + ).as_python_constant(): + unimplemented( + gb_type="torch.associative_scan: mismatched input/output tree structure", + context=f"xs: {xs_treespec.as_python_constant()}, output: {_combine_treespec.as_python_constant()}", + explanation="The tree structure of the xs and the outs of the combine_fn are expected to be identical, but got " + f"xs: {xs_treespec.as_python_constant()} vs output: {_combine_treespec.as_python_constant()}.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + # We set include contiguity=False because we have vmap x HOP tests, where if + # include_contiguity=True will call t.is_contiguous inside of vmap and get an error + # "querying is_contiguous inside of vmap for memory_format other than + # torch.contiguous_format is not yet implemented". This is okay because stride + # is still checked. + check_meta_consistency_vt( + [_make_inlined(tx, first_slice_copy)(t) for t in xs_vars], + results.items, # type: ignore[attr-defined] + "initial_xs", + "combine_fn_output", + include_contiguity=False, + ) + + combine_gm = torch.fx.GraphModule(dict(tx.output.nn_modules), combine_graph) + combine_freevars_proxy = tuple(combine_lifted_freevars.keys()) + + # Compute the proxies for the input check + proxy_vars_inputcheck = ( + tuple(sarg.as_proxy() for sarg in sub_args) + combine_freevars_proxy + ) + + from torch._higher_order_ops.utils import _maybe_fake_tracing + from torch._inductor.utils import is_pointwise_use + + if tx.fake_mode is None: + raise AssertionError("tx.fake_mode must not be None") + with tx.fake_mode: + sub_args_fake = [ + ( + leaf.node.meta["example_value"].clone() + if hasattr(leaf.node.meta["example_value"], "clone") + else leaf.node.meta["example_value"] + ) + for leaf in pytree.tree_leaves(proxy_vars_inputcheck) + ] + pre_dispatch = False + + fx = _maybe_fake_tracing( + combine_gm, sub_args_fake, pre_dispatch=pre_dispatch + ) + + for node in fx.graph.nodes: + # Check that the combine_fn is pointwise, if combine_mode='pointwise' + if not all( + is_pointwise_use(use) or use.op == "output" for use in node.users + ): + raise RuntimeError( + "For combine_mode='pointwise', the combine_fn needs to be pointwise" + ) + + combine_fn_name = tx.output.install_subgraph( + "associative_scan_combine_fn", combine_gm + ) + + # Compute the proxies + xs_proxy = xs.as_proxy() + combine_freevars_proxy = tuple(combine_lifted_freevars.keys()) + additional_inputs_proxy = additional_inputs.as_proxy() + combine_freevars_proxy + + p_args = ( + make_attr(tx, combine_fn_name), + xs_proxy, + additional_inputs_proxy, + ) + + return _call_function_and_unflatten_output( + tx, + torch.ops.higher_order.associative_scan, + p_args, + {}, + None, + OutputSpec(xs_treespec), # type: ignore[arg-type] + None, + ) + + +class ScanHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.scan" + _ALLOW_FALLBACK_TO_EAGER = False + supports_input_mutation = False + supports_aliasing = False + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from torch._higher_order_ops.scan import _extract_carry_and_out + from torch._higher_order_ops.utils import first_slice_copy + + self.supports_input_mutation = not torch.is_grad_enabled() + + args, kwargs = LazyVariableTracker.realize_all((args, kwargs)) + + # combine_fn input check + def _check_combine_fn_is_normalized(combine_fn_var: VariableTracker) -> bool: + if not isinstance( + combine_fn_var, + ( + variables.nn_module.NNModuleVariable, + variables.nn_module.UnspecializedNNModuleVariable, + variables.FunctoolsPartialVariable, + ), + ): + unimplemented( + gb_type="torch.scan: improper combine_fn", + context=str(combine_fn_var), + explanation="Expected combine_fn to be wrapped as functools.partial in scan user-facing api " + f"or a graph module if we're re-exporting but got {combine_fn_var.python_type()}.", + hints=[ + *graph_break_hints.DIFFICULT, + ], + ) + return isinstance( + combine_fn_var, + ( + variables.nn_module.NNModuleVariable, + variables.nn_module.UnspecializedNNModuleVariable, + ), + ) + + def arg_extractor( + combine_fn: VariableTracker, + init: VariableTracker, + xs: VariableTracker, + additional_inputs: VariableTracker, + ) -> tuple[VariableTracker, VariableTracker, VariableTracker, VariableTracker]: + return combine_fn, init, xs, additional_inputs + + combine_fn, init, xs, additional_inputs = arg_extractor(*args, **kwargs) + init_vars = unpack_iterable(tx, init) + xs_vars = unpack_iterable(tx, xs) + additional_inputs_vars = unpack_iterable(tx, additional_inputs) + + # combine_fn input check + combine_fn_is_normalized = _check_combine_fn_is_normalized(combine_fn) + if combine_fn_is_normalized: + combine_gm = combine_fn.value # type: ignore[attr-defined] + if not isinstance(combine_gm, torch.fx.GraphModule): + raise AssertionError( + f"Expected combine_gm to be a GraphModule, got {combine_fn}, {combine_gm}" + ) + else: + # combine_fn input check + # We need to get the pure combine_fn from the functools.partial + _check_supported_callable_arg( + tx, + combine_fn.keywords["combine_fn"], # type: ignore[attr-defined] + "combine_fn", + ) + # xs input check + if not isinstance(xs, (ListVariable, TupleVariable)): + unimplemented( + gb_type="torch.scan: improper xs", + context=str(xs), + explanation=f"Expected xs to be a list/tuple but got {xs.python_type()}", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + # init input check + if not isinstance(init, (ListVariable, TupleVariable)): + unimplemented( + gb_type="torch.scan: improper init", + context=str(init), + explanation=f"Expected init to be a list/tuple with at least one element but got {init.python_type()}", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + if len(init_vars) == 0: + unimplemented( + gb_type="torch.scan: no init leaves", + context="", + explanation="Expected init leaves.", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + # additional_inputs input check + if not isinstance(additional_inputs, (ListVariable, TupleVariable)): + unimplemented( + gb_type="torch.scan: improper additional_inputs", + context=str(additional_inputs), + explanation=f"Expected additional_inputs to be a list/tuple but got {additional_inputs.python_type()}", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + _check_all_tensorvariable(init_vars) + _check_all_tensorvariable(xs_vars) + _check_all_tensorvariable(additional_inputs_vars) + + with discard_graph_changes(tx): + sub_args_init = [ + ini.call_method(tx, "clone", args=[], kwargs={}) for ini in init_vars + ] + # The sub_args_inp is a slice of original input, e.g. if input.size is (3, 4), and scan dim=0 + # the sub_args_inp shape will be (4, ). + sub_args_inp = [_make_inlined(tx, first_slice_copy)(inp) for inp in xs_vars] + sub_args_additional_inputs = [ + t.call_method(tx, "clone", args=[], kwargs={}) + for t in additional_inputs_vars + ] + + sub_args = sub_args_init + sub_args_inp + sub_args_additional_inputs + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + ( + (combine_result, _combine_spec), + combine_graph, + combine_lifted_freevars, + ) = speculate_subgraph( + tx, + combine_fn, + sub_args, + sub_kwargs={}, + description=self._HOP_NAME, + source_target=self.value, + set_subgraph_inputs="flatten_manual", + supports_input_mutation=self.supports_input_mutation, + supports_aliasing=self.supports_aliasing, + ) + + combine_mutated_inputs = set( + getattr(combine_graph, "_dynamo_mutated_input_indices", ()) + ) + + # Ensure that the output of scan is a flattened list of elements, + # because downstream operations assume that the output of HOPs + # is flattened + output_node = combine_graph.find_nodes(op="output")[0] + output_node.args = (pytree.tree_leaves(output_node.args),) + combine_graph.lint() + combine_freevars_proxy = list(combine_lifted_freevars.keys()) + combine_result_vars = unpack_iterable(tx, combine_result) + + if combine_fn_is_normalized: + carry_vars, out_vars = _extract_carry_and_out( + combine_result_vars, len(init_vars) + ) + else: + if len(combine_result_vars) != 2: + unimplemented( + gb_type="torch.scan: improper combine_fn number of returns", + context=str(combine_result_vars), + explanation=f"Expect combine_fn to return a tuple (next_carry, y) but got {combine_result_vars}.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + carry_tree, out_vars = combine_result_vars + carry_vars, _ = unpack_iterable( + tx, _make_inlined(tx, pytree.tree_flatten)(carry_tree) + ) + carry_vars = unpack_iterable(tx, carry_vars) + out_vars = unpack_iterable( + tx, _make_inlined(tx, pytree.tree_leaves)(out_vars) + ) + + # additional output checking + _combine_spec = OutputSpec( + _make_inlined(tx, pytree.tree_structure)(combine_result) # type: ignore[arg-type] + ) + + check_meta_consistency_vt( + init_vars, + carry_vars, + "init", + "carry", + ) + + # Check meta data of carries and inits. If we pass this stage, we are sure that the init and carries + # have the same tree structure. + # We set include contiguity=False because we have vmap x HOP tests, where if + # include_contiguity=True will call t.is_contiguous inside of vmap and get an error + # "querying is_contiguous inside of vmap for memory_format other than + # torch.contiguous_format is not yet implemented". This is okay because stride + # is still checked. + check_meta_consistency_vt( + init_vars, + carry_vars, + "init", + "carry", + include_contiguity=False, + ) + + xs_proxy = xs.as_proxy() + init_proxy = init.as_proxy() + additional_inputs_proxy = list(additional_inputs.as_proxy()) + list( + combine_freevars_proxy + ) + + # Mutation handling: scan allows in-place writes only to + # additional_inputs (lifted, loop-invariant tensors). Mutations of + # init / xs are unsafe (see ScanOp.gen_schema for the contract) so + # we graph-break here with a precise message. The remaining indices + # are mapped through the parent-side input list to produce a + # comma-joined ``mutated_arg_indices`` kwarg for the HOP call, + # mirroring while_loop. + n_init = len(init_vars) + n_xs = len(xs_vars) + + disallowed = sorted(i for i in combine_mutated_inputs if i < n_init + n_xs) + if disallowed: + init_part = [i for i in disallowed if i < n_init] + xs_part = [i - n_init for i in disallowed if n_init <= i] + unimplemented( + gb_type="torch.scan: combine_fn mutates init or xs", + context=f"init={init_part}, xs={xs_part}", + explanation=( + "scan only supports in-place mutation of additional_inputs " + "(loop-invariant tensors). init is the *initial* carry only -- " + "from step 1 on the driver feeds combine_fn's returned carry, " + "so an in-place write to init would only affect step 0. " + "xs[t] is a fresh, storage-disjoint slice each step, so a " + "mutation cannot be observed by step t+1. Update the carry " + "via the combine_fn return value; for in-place lifted buffers " + "use additional_inputs." + ), + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + # additional_inputs (subgraph indices [n_init+n_xs, ...)) plus any + # lifted freevars (indices >= n_init+n_xs+n_additional). Both are + # carried as additional_inputs at the HOP-call layer. + all_scan_inputs: list[VariableTracker | Proxy] = ( + list(init_vars) + + list(xs_vars) + + list(additional_inputs_vars) + + list(combine_freevars_proxy) + ) + # Build a parent-storage set from the subgraph placeholders that were + # detected as mutated, then re-map through ``all_scan_inputs`` so we + # cover both regular additional_inputs and lifted freevars. + mutated_input_storages = subgraph_mutated_input_storages( + combine_graph, + {i for i in combine_mutated_inputs if i >= n_init + n_xs}, + ) + mutated_inputs = parent_mutated_input_indices( + all_scan_inputs, mutated_input_storages + ) + mutated_arg_indices = ",".join(str(i) for i in mutated_inputs) + + combine_gm = torch.fx.GraphModule(dict(tx.output.nn_modules), combine_graph) + combine_fn_name = tx.output.install_subgraph("scan_combine_fn", combine_gm) + + p_args = ( + make_attr(tx, combine_fn_name), + init_proxy, + xs_proxy, + additional_inputs_proxy, + ) + hop_kwargs = ( + {"mutated_arg_indices": mutated_arg_indices} if mutated_arg_indices else {} + ) + + return _call_function_and_unflatten_output( + tx, + torch.ops.higher_order.scan, + p_args, + hop_kwargs, + None, + _combine_spec, + None, + ) + + +class MapHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.map_impl" + _ALLOW_FALLBACK_TO_EAGER = False + supports_input_mutation = False + supports_aliasing = False + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + self.supports_input_mutation = not torch.is_grad_enabled() + + args, kwargs = LazyVariableTracker.realize_all((args, kwargs)) + + if len(kwargs) > 0: + unimplemented( + gb_type="torch.map: kwargs not supported", + context=f"args: {args}, kwargs: {kwargs}", + explanation=f"torch.map expects no keyword arguments (got {len(kwargs)})", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + _check_supported_callable_arg(tx, args[0], "map_fn") + + # args = f, flat_xs, flat_args + if not isinstance(args[1], (ListVariable, TupleVariable)): + raise AssertionError( + f"Expected args[1] to be a ListVariable or TupleVariable, got {args[1]}" + ) + if not isinstance(args[2], (ListVariable, TupleVariable)): + raise AssertionError( + f"Expected args[2] to be a ListVariable or TupleVariable, got {args[2]}" + ) + unpacked_xs = unpack_iterable(tx, args[1]) + unpacked_args = unpack_iterable(tx, args[2]) + + sample_shape = get_fake_value(unpacked_xs[0].as_proxy().node, tx).size() + + if len(sample_shape) < 1 or sample_shape[0] == 0: + unimplemented( + gb_type="torch.map: improper inputs", + context=str(sample_shape), + explanation="torch.map doesn't support scalar or non-zero sized tensors during tracing.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + # To get the example output from map() we will need to provide at least one sample to + # the loop body. In our case we will always use xs[0], and our map() won't support zero + # sized tensor during tracing. + with discard_graph_changes(tx): + sliced_xs = [ + xs.call_method( + tx, + "select", + args=[VariableTracker.build(tx, 0), VariableTracker.build(tx, 0)], + kwargs={}, + ) + for xs in unpacked_xs + ] + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + + # TODO: Support kwargs + ( + (body_r, body_spec), + body_graph, + body_lifted_freevars, + ) = speculate_subgraph( + tx, + args[0], + [ + *sliced_xs, + *unpacked_args, + ], + {}, + self._HOP_NAME, + source_target=self.value, + set_subgraph_inputs="flatten_manual", + should_flatten_outputs=True, + # TODO - removing consts from control flow ops need more work + remove_consts_from_outputs=False, + supports_input_mutation=self.supports_input_mutation, + supports_aliasing=self.supports_aliasing, + ) + + body_mutated_inputs = set( + getattr(body_graph, "_dynamo_mutated_input_indices", ()) + ) + + # Check all outputs of map are tensors. + # For map, outputting None is OK, thus ignore None values in the check + body_r_vars = unpack_iterable(tx, body_r) + none_mask = [x.is_constant_none() for x in body_r_vars] + _check_all_tensorvariable( + [br for bm, br in zip(none_mask, body_r_vars) if not bm] + ) + + # Mutation handling: map allows in-place writes only to xs + # (each iteration sees a storage-disjoint slice). Mutations of + # pos_args or captured freevars are unsafe (see MapImpl.gen_schema + # for the contract). Placeholder order is [xs, pos_args, freevars]. + n_xs = len(unpacked_xs) + n_pos = len(unpacked_args) + + pos_args_mutated = sorted( + i - n_xs for i in body_mutated_inputs if n_xs <= i < n_xs + n_pos + ) + if pos_args_mutated: + unimplemented( + gb_type="torch.map: f mutates pos_args", + context=f"pos_args={pos_args_mutated}", + explanation=( + "map only supports in-place mutation of xs (each " + "iteration sees a storage-disjoint slice). pos_args " + "are loop-invariant: every iteration sees the same " + "tensor, so a mutation makes iterations depend on each " + "other, breaking map's independence contract and " + "introducing a data race under any parallel lowering. " + "Use scan or while_loop if sequential buffer updates " + "are required." + ), + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + freevars_mutated = sorted( + i - n_xs - n_pos for i in body_mutated_inputs if i >= n_xs + n_pos + ) + if freevars_mutated: + unimplemented( + gb_type="torch.map: f mutates a captured tensor", + context=f"freevars={freevars_mutated}", + explanation=( + "map only supports in-place mutation of xs. A tensor " + "captured from the enclosing scope (lifted parameter) is loop-invariant: " + "every iteration sees the same tensor, so a mutation " + "makes iterations depend on each other, breaking map's " + "independence contract and introducing a data race " + "under any parallel lowering. Pass the buffer through " + "xs, or use scan / while_loop if sequential buffer " + "updates are required." + ), + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + # No storage round-trip needed: aliasing graph-breaks upstream, so the + # mutated subgraph placeholder indices are already the parent xs indices. + mutated_arg_indices = ",".join(str(i) for i in sorted(body_mutated_inputs)) + + body_nn_modules = dict(tx.output.nn_modules) + + body_name = tx.output.install_subgraph( + "map_body", + torch.fx.GraphModule(body_nn_modules, body_graph), + ) + + body_node = make_attr(tx, body_name) + + p_args = ( + body_node, + [xs.as_proxy() for xs in unpacked_xs], + [arg.as_proxy() for arg in unpacked_args] + + list(body_lifted_freevars.keys()), + ) + return _call_function_and_unflatten_output( + tx, + torch.ops.higher_order.map_impl, + p_args, + {"mutated_arg_indices": mutated_arg_indices} if mutated_arg_indices else {}, + None, + body_spec, + body_r, + ) + + +class PrintHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.print" + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + args, kwargs = LazyVariableTracker.realize_all((args, kwargs)) + + args_proxy = [arg.as_proxy() for arg in args] + kwargs_proxy = {k: v.as_proxy() for k, v in kwargs.items()} + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + args=tuple(args_proxy), + kwargs=kwargs_proxy, + ), + ) + + +class ExecutorchCallDelegateHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.executorch_call_delegate" + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + # This is operator for delegation within Executorch which calls a + # specific function in the given lowered module with the given + # operators. The actual operator is defined in the Executorch codebase. + # This is a bad hierarchical violation since + # executorch_call_delegate sits at a higher level than dynamo, but + # there's no real solution to this issue yet. + if len(kwargs) > 0: + unimplemented( + gb_type="executorch_call_delegate: kwargs not supported", + context=f"args: {args}, kwargs: {kwargs}", + explanation=f"executorch_call_delegate expects no keyword arguments (got {len(kwargs)})", + hints=[], + ) + lowered_module, lowered_node = None, None + if isinstance(args[0], variables.NNModuleVariable): + lowered_module = tx.output.get_submodule(args[0].module_key) + lowered_node = make_attr(tx, args[0].module_key) + elif isinstance(args[0], variables.UnspecializedNNModuleVariable): + # This nn module is special sa delegated by executorch. Just + # install it as a attr in the graph. + lowered_module = args[0].value + lowered_node = tx.output.register_static_attr_and_return_proxy( + "delegate", lowered_module + ) + else: + unimplemented( + gb_type="executorch_call_delegate: first arg not supported", + context=f"args: {args}, kwargs: {kwargs}", + explanation=f"executorch_call_delegate expects the first argument to be a nn.Module (got {args[0]})", + hints=[], + ) + + p_args = tuple(arg.as_proxy() for arg in args[1:]) + real_sub_args = pytree.tree_map_only( + torch.fx.Proxy, lambda a: get_fake_value(a.node, tx), p_args + ) + if tx.fake_mode is None: + raise AssertionError("tx.fake_mode must not be None") + with tx.fake_mode: + example_value = lowered_module.original_module.module()(*real_sub_args) # type: ignore[attr-defined] + + # NOTE [Guaranteeing the 1-1 correspondence of FakeTensors and real tensors]: + # executorch modules promise not to alias inputs and outputs. + # Thus, output FakeTensors will correctly not alias input FakeTensors. + _assert_tensors_nonaliasing(real_sub_args, example_value) + + p_args = (lowered_node,) + p_args + + # Store the invocation as a call + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + args=tuple(p_args), + kwargs={}, + ), + example_value=example_value, + ) + + +class FunctorchHigherOrderVariable(UserFunctionVariable): + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return super().call_function(tx, args, kwargs) + + def should_allow_nested_graph_breaks(self) -> bool: + return False + + +class FunctionalCallVariable(FunctorchHigherOrderVariable): + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return super().call_function(tx, args, kwargs) + + +class ReparametrizeModuleCallVariable(FunctorchHigherOrderVariable): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + ctx_manager_vt = super().call_function(tx, args, kwargs) + return RepararametrizeModuleContextVariable(ctx_manager_vt, args[0]) # type: ignore[arg-type] + + +class WrapHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.wrap" + supports_input_mutation = True + supports_aliasing = True + allow_side_effects = False + + def install_subgraph_in_output_graph( + self, + tx: "InstructionTranslatorBase", + fn_vt: VariableTracker, + fn_args_vt: list[VariableTracker], + kwargs: dict[str, VariableTracker], + body_gmod: GraphModule, + attr_name: str = "wrap_body", + ) -> str: + return tx.output.install_subgraph( + f"{attr_name}", + body_gmod, + ) + + def create_wrapped_node( + self, + tx: "InstructionTranslatorBase", + fn_vt: VariableTracker, + fn_args_vt: list[VariableTracker], + kwargs: dict[str, VariableTracker], + description: str, + *, + subgraph_name: str = "wrap_body", + set_subgraph_inputs: Literal[ + "automatic", "automatic_with_forced_inputs" + ] = "automatic", + ) -> tuple[ + tuple[Proxy, ...], + dict[str, VariableTracker], + Any, + VariableTracker, + GraphModule, + str, + VariableTracker | tuple[VariableTracker, ...], + SubgraphTracingInfo, + ]: + # See NOTE [HigherOrderOperator tracing design] for more details + ( + body_r, + body_graph, + body_lifted_freevars, + body_graph_output_vts, + tracing_info, + ) = speculate_subgraph_with_auto_output_flattening( + tx, + fn_vt, + fn_args_vt, + kwargs, + description, + source_target=self.value, + set_subgraph_inputs=set_subgraph_inputs, + allow_side_effects=self.allow_side_effects, + filter_aliased_intermediates=getattr( + self, "filter_aliased_intermediates", False + ), + supports_input_mutation=self.supports_input_mutation, + supports_aliasing=self.supports_aliasing, + ) + + body_gmod = torch.fx.GraphModule(tx.output.nn_modules, body_graph) + body_name = self.install_subgraph_in_output_graph( + tx, + fn_vt, + fn_args_vt, + kwargs, + body_gmod, + attr_name=subgraph_name, + ) + body_node = make_attr(tx, body_name) + + if set_subgraph_inputs == "automatic_with_forced_inputs": + # Forced mode creates placeholders eagerly (in user arg order) and + # rewraps the tensor VTs with child-tracer proxies, so these args + # never go through the freevar lift path. Build the outer p_args + # from fn_args_vt directly, then append any closure captures that + # were auto-lifted during body tracing. + forced_args = tuple(a.as_proxy() for a in fn_args_vt if a.is_tensor()) + lifted_args = forced_args + tuple(body_lifted_freevars) + else: + # With "automatic", all args flow through the freevar lift path. + lifted_args = tuple(body_lifted_freevars) + + proxy_args = (body_node,) + lifted_args + + example_value = pytree.tree_map_only( + torch.fx.Node, + lambda a: a.meta["example_value"], + body_graph.find_nodes(op="output")[0].args[0], + ) + + return ( + proxy_args, + {}, + example_value, + body_r, + body_gmod, + body_name, + body_graph_output_vts, + tracing_info, + ) + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # This flattens the kwargs into lifted args + ( + p_args, + p_kwargs, + _example_value, + body_r, + _, + _, + body_graph_output_vts, + _, + ) = self.create_wrapped_node(tx, args[0], args[1:], kwargs, "wrap") + + if len(p_kwargs) > 0: + unimplemented( + gb_type="WrapHigherOrderVariable: kwargs unexpected", + context=f"args: {args}, kwargs: {kwargs}", + explanation="kwargs should have been flattened into lifted args.", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + return _call_function_with_auto_output_flattening( # type: ignore[return-value] + tx, + self.value, + tuple(p_args), + p_kwargs, + _example_value, + body_r, + body_graph_output_vts, + ) + + +class WrapWithSetGradEnabledHigherOrderVariable(TorchHigherOrderOperatorVariable): + """ + This hop is not exposed to users but is inserted into the graph + after export as a post-processing step. + """ + + _HOP_NAME = "torch.ops.higher_order.wrap_with_set_grad_enabled" + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + args, kwargs = LazyVariableTracker.realize_all((args, kwargs)) + + if kwargs: + unimplemented( + gb_type="wrap_with_set_grad_enabled: unexpected kwargs", + context=f"args: {args}, kwargs: {kwargs}", + explanation=f"wrap_with_set_grad_enabled expects no keyword arguments (got {len(kwargs)}).", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + grad_enabled, fn_var, *rest_args = args + + if not grad_enabled.is_python_constant(): + unimplemented( + gb_type="wrap_with_set_grad_enabled: non-constant grad_enabled", + context=str(grad_enabled), + explanation="wrap_with_set_grad_enabled expects grad_enabled argument to be a constant.", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + _check_supported_callable_arg(tx, fn_var, "enable_grad_fn") + + with torch.set_grad_enabled(grad_enabled.as_python_constant()): + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + ( + (body_r, treespec), + body_graph, + body_lifted_freevars, + ) = speculate_subgraph( + tx, + fn_var, + [*rest_args], + {}, + self._HOP_NAME, + source_target=self.value, + set_subgraph_inputs="manual", + should_flatten_outputs=True, + ) + + if len(body_lifted_freevars) > 0: + unimplemented( + gb_type="wrap_with_set_grad_enabled: unexpected freevars", + context=str(body_lifted_freevars), + explanation="wrap_with_set_grad_enabled expects no freevars.", + hints=[], + ) + + body_gmod = torch.fx.GraphModule(tx.output.nn_modules, body_graph) + body_name = tx.output.install_subgraph( + "wrap_body", + body_gmod, + ) + + body_node = make_attr(tx, body_name) + + proxy_args = tuple( + [ + grad_enabled.as_python_constant(), + body_node, + ] + + [operand.as_proxy() for operand in rest_args] + ) + example_value = pytree.tree_map_only( + torch.fx.Proxy, + lambda a: a.node.meta["example_value"], + body_r.as_proxy(), + ) + return _call_function_and_unflatten_output( + tx, self.value, proxy_args, {}, example_value, treespec, body_r + ) + + +class WrapWithAutocastHigherOrderVariable(TorchHigherOrderOperatorVariable): + """ + This hop is not exposed to users but is inserted into the graph + after export as a post-processing step. + """ + + _HOP_NAME = "torch.ops.higher_order.wrap_with_autocast" + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + args, kwargs = LazyVariableTracker.realize_all((args, kwargs)) + + if kwargs: + unimplemented( + gb_type="wrap_with_autocast: unexpected kwargs", + context=f"args: {args}, kwargs: {kwargs}", + explanation=f"wrap_with_autocast expects no keyword arguments (got {len(kwargs)}).", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + device_type, dtype, enabled, cache_enabled, fn_var, *rest_args = args + + for arg in [device_type, dtype, enabled, cache_enabled]: + if not arg.is_python_constant(): + unimplemented( + gb_type="wrap_with_autocast: expected constant arg", + context=str(args), + explanation="wrap_with_autocast expects device_type, dtype, enabled, " + "and cache_enabled arguments to be constants.", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + _check_supported_callable_arg(tx, fn_var, "autocast") + + python_constants = [ + arg.as_python_constant() + for arg in [device_type, dtype, enabled, cache_enabled] + ] + + with torch.autocast(*python_constants): + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + ( + (body_r, treespec), + body_graph, + body_lifted_freevars, + ) = speculate_subgraph( + tx, + fn_var, + [*rest_args], + {}, + self._HOP_NAME, + source_target=self.value, + set_subgraph_inputs="manual", + should_flatten_outputs=True, + ) + + if len(body_lifted_freevars) > 0: + unimplemented( + gb_type="wrap_with_autocast: unexpected freevars", + context=str(body_lifted_freevars), + explanation="wrap_with_autocast expects no freevars.", + hints=[], + ) + + body_gmod = torch.fx.GraphModule(tx.output.nn_modules, body_graph) + body_name = tx.output.install_subgraph( + "wrap_body", + body_gmod, + ) + + body_node = make_attr(tx, body_name) + + proxy_args = tuple( + [ + *python_constants, + body_node, + ] + + [operand.as_proxy() for operand in rest_args] + ) + example_value = pytree.tree_map_only( + torch.fx.Proxy, + lambda a: a.node.meta["example_value"], + body_r.as_proxy(), + ) + + return _call_function_and_unflatten_output( + tx, self.value, proxy_args, {}, example_value, treespec, body_r + ) + + +class FlexGemmHigherOrderVariable(WrapHigherOrderVariable): + _HOP_NAME = "torch.ops.higher_order.flex_gemm" + _ALLOW_FALLBACK_TO_EAGER = False + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: Sequence[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if kwargs: + unimplemented( + gb_type="flex_gemm: unexpected kwargs", + context=f"args: {args}, kwargs: {kwargs}", + explanation="flex_gemm internal HOP expects positional args only.", + hints=[*graph_break_hints.USER_ERROR], + ) + + if ( + len(args) != 5 + or not isinstance(args[2], (ListVariable, TupleVariable)) + or not isinstance(args[3], ConstDictVariable) + or not isinstance(args[4], ConstDictVariable) + ): + unimplemented( + gb_type="flex_gemm: improper args/kwargs", + context=f"args: {args}, kwargs: {kwargs}", + explanation=( + "flex_gemm expects 5 positional arguments: " + "gemm_op, body_fn, args, kwargs, kernel_options. args is " + "expected to be list/tuple and kwargs/kernel_options are " + "expected to be dicts." + ), + hints=[*graph_break_hints.USER_ERROR], + ) + + _check_supported_callable_arg(tx, args[1], "body_fn") + operands = args[2].unpack_var_sequence(tx) + fn_kwargs = args[3].as_python_constant() + kernel_options = args[4].as_python_constant() + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + ( + p_args, + _, + example_value, + body_r, + _, + _, + body_graph_output_vts, + _, + ) = self.create_wrapped_node( + tx, + args[1], + operands, + {}, + self._HOP_NAME, + subgraph_name="flex_gemm_body", + ) + + body_node = p_args[0] + gemm_op = args[0].as_python_constant() + p_args = ( + FLEX_GEMM_OP_ALIASES.get(gemm_op, gemm_op), + body_node, + tuple(p_args[1:]), + fn_kwargs, + kernel_options, + ) + + return cast( + VariableTracker, + _call_function_with_auto_output_flattening( + tx, + self.value, + p_args, + {}, + example_value, + body_r, + body_graph_output_vts, + ), + ) + + +class HintsWrapperHigherOrderVariable(WrapHigherOrderVariable): + _HOP_NAME = "torch.ops.higher_order.hints_wrapper" + _ALLOW_FALLBACK_TO_EAGER = False + + def install_subgraph_in_output_graph( + self, + tx: "InstructionTranslatorBase", + fn_vt: VariableTracker, + fn_args_vt: list[VariableTracker], + kwargs: dict[str, VariableTracker], + body_gmod: GraphModule, + attr_name: str = "wrap_body", + ) -> str: + return tx.output.install_subgraph( + "hints_wrapper_body", + body_gmod, + ) + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + _check_supported_callable_arg(tx, args[0], "body_fn") + + # inputs + if ( + len(args) != 3 + or not isinstance(args[1], (ListVariable, TupleVariable)) + or not isinstance(args[2], ConstDictVariable) + or len(kwargs) != 1 + or "hints" not in kwargs + ): + unimplemented( + gb_type="hints_wrapper: improper args/kwargs", + context=f"args: {args}, kwargs: {kwargs}", + explanation=f"hints_wrapper expects 3 positional arguments (got {len(args)}) " + f"and 1 keyword argument (got {len(kwargs)}). " + "Usage: hints_wrapper(body_fn, args, kwargs, hints=...). " + "args is expected to be list/tuple and kwargs is expected to be a dict.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + operands = unpack_iterable(tx, args[1]) + fn_kwargs = args[2].as_python_constant() + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + # Use create_wrapped_node from WrapHigherOrderVariable + ( + p_args, + _, + example_value, + body_r, + body_gmod, + _, + body_graph_output_vts, + _, + ) = self.create_wrapped_node( + tx, + args[0], # function + operands, + fn_kwargs, + self._HOP_NAME, + ) + + # hints_wrapper expects (body_node, args, kwargs) as positional args + # So we need to restructure p_args from (body_node, *lifted_args) + # to (body_node, lifted_args_tuple, {}) + body_node = p_args[0] + lifted_args = p_args[1:] + # pyrefly: ignore [implicit-any] + p_args = (body_node, tuple(lifted_args), {}) + + # add hints into p_kwargs + p_kwargs = {} + p_kwargs["hints"] = kwargs["hints"].as_python_constant() + + return _call_function_with_auto_output_flattening( # type: ignore[return-type] + tx, + self.value, + p_args, + p_kwargs, + example_value, + body_r, + body_graph_output_vts, + ) + + +class OutDtypeHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.out_dtype" + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + if len(kwargs) > 0: + unimplemented( + gb_type="out_dtype: unexpected kwargs", + context=f"args: {args}, kwargs: {kwargs}", + explanation=f"out_dtype expects no keyword arguments (got {len(kwargs)}).", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + p_args = tuple(arg.as_proxy() for arg in args) + op = p_args[0] + output_dtype = p_args[1] + fake_sub_args = pytree.tree_map_only( + torch.fx.Proxy, lambda a: a.node.meta["example_value"], p_args[2:] + ) + # This is a simplified implementation of this operator just for tracing. + # Actual implementation may also first promote the arguments + example_value = op(*fake_sub_args).to(dtype=output_dtype) + + # Store the invocation as a call + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + args=tuple(p_args), + kwargs={}, + ), + example_value=example_value, + ) + + +class StrictModeHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.strict_mode" + _ALLOW_FALLBACK_TO_EAGER = False + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + unpacked_sequence = unpack_iterable(tx, args[1]) + # TODO (tmanlaibaatar) support pytree here + for arg in unpacked_sequence: + if isinstance( + arg, (ListVariable, TupleVariable, ConstDictVariable, SetVariable) + ): + unimplemented( + gb_type="strict_mode: improper args", + context=f"args: {args}, kwargs: {kwargs}", + explanation="strict_mode higher order op expects flat inputs (list/tuple/dict/set)", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + if kwargs: + unimplemented( + gb_type="strict_mode: unexpected kwargs", + context=f"args: {args}, kwargs: {kwargs}", + explanation=f"strict_mode higher order op expects no keyword arguments (got {len(kwargs)}).", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must be set") + ( + (ret_val, ret_spec), + ret_graph, + ret_lifted_freevars, + ) = speculate_subgraph( + tx, + args[0], + unpacked_sequence, + {}, + self._HOP_NAME, + source_target=self.value, + should_flatten_outputs=True, + ) + + strict_mode_nn_modules = dict(tx.output.nn_modules) + + strict_mode_name = tx.output.install_subgraph( + "strict_mode_body", + torch.fx.GraphModule(strict_mode_nn_modules, ret_graph), + ) + + strict_mode_node = make_attr(tx, strict_mode_name) + p_args = ( + strict_mode_node, + tuple(ret_lifted_freevars.keys()), + ) + + flat_example_value = pytree.tree_map_only( + torch.fx.Proxy, + lambda a: a.node.meta["example_value"], + ret_val.as_proxy(), + ) + + return _call_function_and_unflatten_output( + tx, + torch.ops.higher_order.strict_mode, + p_args, + {}, + flat_example_value, + ret_spec, + ret_val, + ) + + +class CheckpointHigherOrderVariable(WrapHigherOrderVariable): + _HOP_NAME = "torch.utils.checkpoint.checkpoint" + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.allow_side_effects = ( + torch._dynamo.config.skip_fwd_side_effects_in_bwd_under_checkpoint + ) + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from torch._higher_order_ops.wrap import TagActivationCheckpoint + from torch.utils.checkpoint import noop_context_fn + + context_fn = None + if "context_fn" in kwargs and kwargs["context_fn"] is not noop_context_fn: + ctx = kwargs.pop("context_fn") + if isinstance(ctx, torch._dynamo.variables.UserFunctionVariable): + context_fn = ctx.fn + elif isinstance( + ctx, torch._dynamo.variables.functions.FunctoolsPartialVariable + ): + context_fn = ctx.guard_as_python_constant() + else: + raise NotImplementedError( + f"checkpoint not implemented for {type(ctx)} context_fn" + ) + + checkpoint_kwargs, gmod_kwargs = TagActivationCheckpoint.divide_kwargs(kwargs) + + # Here we use checkpoint_kwargs (and not gmod kwargs). gmod_kwargs are + # already flattened above and managed inside the fx graph. + ( + p_args, + _, + example_value, + _body_r, + checkpointed_gmod, + _, + body_graph_output_vts, + _, + ) = self.create_wrapped_node( + tx, + args[0], + args[1:], + gmod_kwargs, + "torch.utils.checkpoint.checkpoint", + ) + if context_fn is not None: + checkpointed_gmod.meta["_checkpoint_context_fn"] = context_fn + + _, checkpoint_kwargs = proxy_args_kwargs([], checkpoint_kwargs) + + return _call_function_with_auto_output_flattening( # type: ignore[return-value] + tx, + self.value, + p_args, + checkpoint_kwargs, + example_value, + _body_r, + body_graph_output_vts, + ) + + +class DynamoBypassingWrapperHigherOrderVariable(WrapHigherOrderVariable): + _HOP_NAME = "torch.ops.higher_order.dynamo_bypassing_wrapper" + + def __init__(self, hop: HigherOrderOperator, source: Source | None) -> None: + super().__init__(hop, source) + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + func_var = args[0] + + if isinstance(func_var, torch._dynamo.variables.UserFunctionVariable): + func = func_var.fn + elif isinstance( + func_var, torch._dynamo.variables.functions.FunctoolsPartialVariable + ): + func = func_var.as_python_constant() + else: + raise RuntimeError( + f"DynamoBypassingWrapperHigherOrderVariable: Unsupported function {type(func_var)}" + ) + ( + p_args, + _, + example_value, + _body_r, + gmod, + _, + body_graph_output_vts, + _, + ) = self.create_wrapped_node( + tx, + args[1], + args[2:], + kwargs, + str(func), + ) + + # Alternatively, we could've stored only the function's fqn and + # reconstructed, but that requires the function to be a global. + gmod_meta_key = "_dynamo_bypassing_wrapper_fn" + gmod.meta[gmod_meta_key] = func + + return _call_function_with_auto_output_flattening( # type: ignore[return-value] + tx, + self.value, + (gmod_meta_key,) + tuple(p_args), + {}, + example_value, + _body_r, + body_graph_output_vts, + ) + + +class ExportTracepointHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order._export_tracepoint" + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + p_args = tuple(arg.as_proxy() for arg in args) + p_kwargs = {key: arg.as_proxy() for key, arg in kwargs.items()} + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + args=p_args, + kwargs=p_kwargs, + ), + example_value=None, + ) + + +class RunWithRNGStateHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.run_with_rng_state" + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + p_args = tuple(arg.as_proxy() for arg in args) + p_kwargs = {key: arg.as_proxy() for key, arg in kwargs.items()} + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + args=p_args, + kwargs=p_kwargs, + ), + example_value=None, + ) + + +class InlineAsmElementwiseHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "inline_asm_elementwise" + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + p_args = tuple(arg.as_proxy() for arg in args) + p_kwargs = {key: arg.as_proxy() for key, arg in kwargs.items()} + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + args=p_args, + kwargs=p_kwargs, + ), + example_value=None, + ) + + +class AutoFunctionalizeHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.auto_functionalized" + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + p_args = tuple(arg.as_proxy() for arg in args) + p_kwargs = {key: arg.as_proxy() for key, arg in kwargs.items()} + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + args=p_args, + kwargs=p_kwargs, + ), + example_value=None, + ) + + +class FlexAttentionBackwardHighOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.flex_attention_backward" + + @staticmethod + def _uses_pretraced_graphs( + fw_graph: VariableTracker, joint_graph: VariableTracker + ) -> bool: + return not joint_graph.is_constant_none() or isinstance( + fw_graph, UnspecializedNNModuleVariable + ) + + def proxy_submod( + self, tx: "InstructionTranslatorBase", arg: UnspecializedNNModuleVariable + ) -> Proxy: + if not arg.source: # type: ignore[attr-defined] + raise AssertionError("arg.source must be set") + if not isinstance(arg.source.base, DictGetItemSource): # type: ignore[attr-defined] + raise AssertionError("arg.source.base must be a DictGetItemSource") + submod_name = tx.output.install_subgraph(arg.source.base.index, arg.value) # type: ignore[arg-type] + p_submod = make_attr(tx, submod_name) + set_example_value(p_submod.node, arg.value) + return p_submod + + def to_proxy(self, tx: "InstructionTranslatorBase", arg: VariableTracker) -> Any: + if isinstance(arg, UnspecializedNNModuleVariable): + return self.proxy_submod(tx, arg) + elif isinstance(arg, (ListVariable, TupleVariable)): + return arg.python_type()( + self.to_proxy(tx, nested_arg) for nested_arg in arg.items + ) + else: + return arg.as_proxy() + + def create_wrapped_node( + self, + tx: "InstructionTranslatorBase", + query: VariableTracker, + fn: VariableTracker, + fn_name: str, + other_buffers: list[VariableTracker], + ) -> tuple[Proxy, tuple[Proxy, ...], torch.fx.GraphModule]: + from .._trace_wrapped_higher_order_op import TransformGetItemToIndex + + def create_scalar() -> VariableTracker: + return query.call_method( + tx, + "new_empty", + [VariableTracker.build(tx, [])], + {"dtype": VariableTracker.build(tx, torch.int32)}, + ) + + with discard_graph_changes(tx): + bhmn = [create_scalar() for _ in range(4)] + if fn_name == "score_mod": + scores_require_grad: bool = query.requires_grad # type: ignore[attr-defined] + score = query.call_method( + tx, + "new_empty", + [VariableTracker.build(tx, [])], + {"requires_grad": VariableTracker.build(tx, scores_require_grad)}, + ) + new_args = [score, *bhmn, *other_buffers] + else: + if fn_name != "mask_fn": + raise AssertionError("Illegal function name: " + fn_name) + new_args = [*bhmn, *other_buffers] + + with TransformGetItemToIndex(): + ( + (_body_output, _body_spec), + body_graph, + body_lifted_freevars, + ) = speculate_subgraph( + tx, + fn, + new_args, + {}, + description=f"{self._HOP_NAME}: {fn_name}", + source_target=self.value, + set_subgraph_inputs="flatten_manual", + ) + + gm = torch.fx.GraphModule(tx.output.nn_modules, body_graph) + body_name = tx.output.install_subgraph(fn_name, gm) + return make_attr(tx, body_name), tuple(body_lifted_freevars), gm + + @staticmethod + def _buffer_example_value(buffer: VariableTracker) -> Any: + proxy = buffer.as_proxy() + if isinstance(proxy, Proxy): + return proxy.node.meta["example_value"] + return proxy + + def _derive_joint_graph( + self, + tx: "InstructionTranslatorBase", + query: VariableTracker, + fw_graph_gm: torch.fx.GraphModule, + score_mod_other_buffers: TupleVariable, + fw_graph_lifted_args: tuple[Proxy, ...], + ) -> Proxy: + from torch._higher_order_ops.flex_attention import create_fw_bw_graph + + query_example = query.as_proxy().node.meta["example_value"] + example_vals = ( + query_example.new_zeros((), requires_grad=True), + query_example.new_zeros((), dtype=torch.int), + query_example.new_zeros((), dtype=torch.int), + query_example.new_zeros((), dtype=torch.int), + query_example.new_zeros((), dtype=torch.int), + ) + all_buffer_examples = tuple( + self._buffer_example_value(buf) for buf in score_mod_other_buffers.items + ) + tuple(buf.node.meta["example_value"] for buf in fw_graph_lifted_args) + + _, joint_gm = create_fw_bw_graph(fw_graph_gm, example_vals, all_buffer_examples) + joint_gm = cast(GraphModule, joint_gm) + + submod_name = tx.output.install_subgraph("joint_graph", joint_gm) + p_submod = make_attr(tx, submod_name) + set_example_value(p_submod.node, joint_gm) + return p_submod + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + if len(args) != 14: + return self._call_function_fallback(tx, args, kwargs) + + ( + query, + key, + value, + out, + logsumexp, + grad_out, + grad_logsumexp, + fw_graph, + joint_graph, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) = args + + if ( + not isinstance(block_mask, TupleVariable) + or not isinstance(score_mod_other_buffers, TupleVariable) + or not isinstance(mask_mod_other_buffers, TupleVariable) + or len(block_mask.items) < 1 + ): + return self._call_function_fallback(tx, args, kwargs) + + if self._uses_pretraced_graphs(fw_graph, joint_graph): + return self._call_function_fallback(tx, args, kwargs) + + fw_graph_node, fw_graph_lifted_args, fw_graph_gm = self.create_wrapped_node( + tx, query, fw_graph, "score_mod", score_mod_other_buffers.items + ) + + joint_graph_node = self._derive_joint_graph( + tx, + query, + fw_graph_gm, + score_mod_other_buffers, + fw_graph_lifted_args, + ) + + mask_fn = block_mask.items[-1] + if mask_fn.is_python_constant() and mask_fn.as_python_constant() is None: + mask_fn = VariableTracker.build( + tx, + torch.nn.attention.flex_attention.noop_mask, + source=mask_fn.source, + ) + mask_fn_node, mask_fn_lifted_args, _ = self.create_wrapped_node( + tx, query, mask_fn, "mask_fn", mask_mod_other_buffers.items + ) + + proxied_args = [ + query, + key, + value, + out, + logsumexp, + grad_out, + grad_logsumexp, + TupleVariable(block_mask.items[:-1], source=block_mask.source), + scale, + kernel_options, + ] + inp_args, _ = proxy_args_kwargs(proxied_args, {}) + proxied_score_mod_other_buffers = tuple( + self.to_proxy(tx, arg) for arg in score_mod_other_buffers.items + ) + proxied_mask_mod_other_buffers = tuple( + self.to_proxy(tx, arg) for arg in mask_mod_other_buffers.items + ) + + ( + inp_q, + inp_k, + inp_v, + inp_out, + inp_lse, + inp_grad_out, + inp_grad_lse, + inp_block_mask, + inp_scale, + inp_kernel_options, + ) = inp_args + + block_mask_proxy = tuple(inp_block_mask + (mask_fn_node,)) + + with torch.fx.experimental.proxy_tensor.set_original_aten_op(self.value): + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + args=( + inp_q, + inp_k, + inp_v, + inp_out, + inp_lse, + inp_grad_out, + inp_grad_lse, + fw_graph_node, + joint_graph_node, + block_mask_proxy, + inp_scale, + inp_kernel_options, + proxied_score_mod_other_buffers + fw_graph_lifted_args, + proxied_mask_mod_other_buffers + mask_fn_lifted_args, + ), + kwargs={}, + ), + example_value=None, + ) + + def _call_function_fallback( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + p_args, p_kwargs = None, None + try: + p_args = tuple(self.to_proxy(tx, arg) for arg in args) + p_kwargs = {key: self.to_proxy(tx, arg) for key, arg in kwargs.items()} + except (NotImplementedError, Unsupported) as err: + unimplemented( + gb_type="failed to handle argument for FlexAttentionBackward HOP", + context=f"args: {args}, kwargs: {kwargs}", + explanation="Missing Dynamo support for FlexAttentionBackward HOP argument.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + from_exc=err, + ) + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + args=p_args, + kwargs=p_kwargs, + ), + example_value=None, + ) + + +class TraceWrappedHigherOrderOperatorVariable(TorchHigherOrderOperatorVariable): + """ + Handles torch._dynamo._trace_wrapped_higher_order_op.inner_trace + by unwrapping the higher order op and inlining through it. This op + is created by dynamo to survive through AotAutograd, then unwrapped + here in the call to dynamo from compiled autograd. + """ + + _HOP_NAME = "torch._dynamo._trace_wrapped_higher_order_op.inner_trace" + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + kwargs = dict(kwargs) + fn = kwargs.pop("fn") + return fn.call_function(tx, args, kwargs) + + +class FlexAttentionHigherOrderVariable(TorchHigherOrderOperatorVariable): + _HOP_NAME = "torch.ops.higher_order.flex_attention" + + @staticmethod + def normalize_to_args( + args: list[VariableTracker], kwargs: dict[str, VariableTracker] + ) -> list[VariableTracker]: + # input signature is (query, key, value, score_mod, block_mask, *other_buffers), + # block_mask is a tuple, and we don't want to flatten it. + # only flatten kwargs into lists + flat_kwargs = pytree.tree_flatten(kwargs)[0] + + # Combine the flattened lists + all_args = args + flat_kwargs + return all_args + + def create_wrapped_node( + self, + tx: "InstructionTranslatorBase", + query: VariableTracker, + fn: VariableTracker, + fn_name: str, + ) -> tuple[Proxy, tuple[Proxy, ...]]: + from .._trace_wrapped_higher_order_op import TransformGetItemToIndex + + def create_scalar() -> VariableTracker: + return query.call_method( + tx, + "new_empty", + [ + VariableTracker.build(tx, []), + ], + { + "dtype": VariableTracker.build(tx, torch.int32), + }, + ) + + with discard_graph_changes(tx): + bhmn = [create_scalar() for _ in range(4)] + if fn_name == "score_mod": + scores_require_grad: bool = query.requires_grad # type: ignore[attr-defined] + score = query.call_method( + tx, + "new_empty", + [ + VariableTracker.build(tx, []), + ], + {"requires_grad": VariableTracker.build(tx, scores_require_grad)}, + ) + new_args = [score, *bhmn] + else: + if fn_name != "mask_fn": + raise AssertionError("Illegal function name: " + fn_name) + new_args = [*bhmn] + + with TransformGetItemToIndex(): + ( + (_body_output, _body_spec), + body_graph, + body_lifted_freevars, + ) = speculate_subgraph( + tx, + fn, + new_args, + {}, # expect only args no kwargs for now + description=f"{self._HOP_NAME}: {fn_name}", + source_target=self.value, + set_subgraph_inputs="flatten_manual", + ) + + body_name = tx.output.install_subgraph( + fn_name, + torch.fx.GraphModule(tx.output.nn_modules, body_graph), + ) + + body_node = make_attr(tx, body_name) + + # It is possible that the score-mod function captures some free variables that are not + # passed in as arguments. In this case, we need to lift them, which is handled by speculate_subgraph. + # We then need to create proxies for this + the inputs. + + lifted_args = tuple(arg for arg in body_lifted_freevars) + + proxy_args = (body_node, lifted_args) + + return proxy_args + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + ( + query, + key, + value, + score_mod, + block_mask, + scale, + kernel_options, + ) = self.normalize_to_args(list(args), kwargs) + + score_mod_node, score_mod_lifted_args = self.create_wrapped_node( + tx, query, score_mod, "score_mod" + ) + mask_fn = block_mask.items[-1] # type: ignore[attr-defined] + if mask_fn.is_python_constant() and mask_fn.as_python_constant() is None: + mask_fn = VariableTracker.build( + tx, + torch.nn.attention.flex_attention.noop_mask, + source=mask_fn.source, + ) + mask_fn_node, mask_fn_lifted_args = self.create_wrapped_node( + tx, query, mask_fn, "mask_fn" + ) + + proxied_args = [ + query, + key, + value, + TupleVariable(block_mask.items[:-1], source=block_mask.source), # type: ignore[attr-defined] + scale, + kernel_options, + ] + + # Store the invocation as a call + # Norm_kwargs contains the score_function and we don't want to proxy this because + # Proxying user defined functions is not supported. + inp_args, _ = proxy_args_kwargs(proxied_args, {}) + + # Compose the ordered HOO args: + # - inp_args: [query, key, value, block_mask, scale, kernel_options] + # - subgraph node: [score_mod, mask_fn_node] + # - lifted args from tracing subgraph: [score_mod_other_buffers, mask_fn_other_buffers] + _, _, _, inp_arg_block_mask, inp_arg_scale, inp_arg_kernel_options = inp_args + block_mask = tuple(inp_arg_block_mask + (mask_fn_node,)) + with torch.fx.experimental.proxy_tensor.set_original_aten_op(self.value): + proxy = wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + args=inp_args[:3] + + ( + score_mod_node, + block_mask, + inp_arg_scale, + inp_arg_kernel_options, + score_mod_lifted_args, + mask_fn_lifted_args, + ), + kwargs={}, + ), + example_value=None, + ) + return proxy + + +@add_hop_context +class AutogradFunctionApplyVariable(VariableTracker): + _HOP_NAME: str = "autograd.Function" + _ALLOW_FALLBACK_TO_EAGER = True + + def __init__( + self, fwd_fn: Any, bwd_fn: Any, parent_source: Source | None, **kwargs: Any + ) -> None: + super().__init__(**kwargs) + self.fwd_fn = fwd_fn + self.bwd_fn = bwd_fn + self.parent_source = parent_source + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def python_type(self) -> type: + return types.BuiltinMethodType + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + """ + At the highest level, the goal of tracing an autograd.Function is to + essentially emit a new autograd.Function object. To do this, Dynamo + traces fwd and bwd graph and then inserts a AutogradFunctionApply HOP in + the graph that call the traced fwd and bwd graph in the `forward` and + `backward` methods respectively. AOTDispatcher desugars this HOP and + just inlines the hop fwd and bwd into the main graph during its tracing. + + However, the traced forward and backward graphs cannot be directly + placed in the new autograd.Function because autograd.Function has some + requirements. + + a) # fwd graph inputs = # bwd graph outputs + b) # fwd graph outputs = # bwd graph inputs + c) Since the graphs do not have ctx variable, we have to manually return + the saved_tensors from the forward and have additional inputs in the + backward, and wire the connections. + + Unfortunately, reworking the initial traced fwd and bwd graphs to + satisfy the above 3 conditions leads to a very tedious codebase. + + Lets look at an example + + class Foo: + def __init__(self): + self.a = 4 + + class MySin(torch.autograd.Function): + @staticmethod + def forward(ctx, x, foo): + ctx.save_for_backward(x) + return x.sin() + foo.a + + @staticmethod + def backward(ctx, grad): + x, = ctx.saved_tensors + return grad * x.cos() + + We want the resulting graphs to look like: + + # Note that Dynamo lifts the foo_a directly as an input. + def fwd(ctx, x, foo_a): + # (output, saved tensors / attrs) + return (x.sin() + foo_a, (x)) + + # Note that backward graph has None as the second output to match the + # fwd requirements (even though the original backward function has just + # output) + def bwd(ctx, grad, x): + return grad * x.cos(), None + + + To accomplish this, we're going to: + 1. Construct a ctx object + 2. Speculate subgraph forward + 3. Speculate subgraph backward + 4. rewired_bwd_graph_inputs - Use the traced fwd graph as the anchor point, and rewire the backward graph outputs + 5. handle_saved_tensors_wiring - Handle the saved tensors, as mentioned in (c) + """ + + fwd_tracer = torch._dynamo.output_graph.SubgraphTracer( + tx.output, + parent=tx.output.current_tracer, + source_target=self._HOP_NAME, + ) + + ctx = self.prepare_ctx_vt(tx, args, kwargs) + + fwd_fn, fwd_out, fwd_graph, fwd_freevars, fwd_graph_output_vts = ( + self.trace_forward_graph(tx, ctx, fwd_tracer, args, kwargs) + ) + + bwd_args, bwd_out, bwd_graph, bwd_freevars, bwd_graph_output_vts = ( + self.trace_backward_graph(tx, ctx, fwd_tracer, fwd_out, fwd_fn) + ) + + self.rewire_bwd_graph_outputs( + fwd_freevars, bwd_out, bwd_graph, bwd_freevars, args + ) + + fwd_graph, bwd_graph = self.handle_saved_tensors_wiring( + fwd_out, + fwd_graph, + fwd_freevars, + fwd_graph_output_vts, # type: ignore[arg-type] + bwd_graph, + bwd_freevars, + ) + + # If users call ctx.mark_non_differentiable, we should capture these output tensors who + # are marked as non-differentiable and pass them to ApplyTemplate + # at torch._functorch.autograd_function.AutogradFunctionApply for reconstruction. + non_differentiable_idx = [] + if ctx.non_differentiable is not None: + non_differentiable_set = set(ctx.non_differentiable) + if not isinstance(fwd_out, variables.BaseListVariable): + raise AssertionError("Expected fwd_out to be a BaseListVariable") + for i, x in enumerate(fwd_out.items): + if x.is_tensor() and x.as_proxy() in non_differentiable_set: + non_differentiable_idx.append(i) + + dirty_idx: list[int] = [] + if ctx.dirty_tensors is not None: + dirty_tensor_set: set[Proxy] = { + x.as_proxy() for x in ctx.dirty_tensors if x.is_tensor() + } + matched_dirty_tensor_set: set[Proxy] = set() + if fwd_out.is_tensor(): + fwd_out_proxy = fwd_out.as_proxy() + if fwd_out_proxy in dirty_tensor_set: + dirty_idx.append(0) + matched_dirty_tensor_set.add(fwd_out_proxy) + else: + if not isinstance(fwd_out, variables.BaseListVariable): + raise AssertionError("Expected fwd_out to be a BaseListVariable") + for i, x in enumerate(fwd_out.items): + if x.is_tensor(): + x_proxy = x.as_proxy() + if x_proxy in dirty_tensor_set: + dirty_idx.append(i) + matched_dirty_tensor_set.add(x_proxy) + if dirty_tensor_set - matched_dirty_tensor_set: + unimplemented( + gb_type="autograd.Function.apply: mark_dirty input not returned", + context="", + explanation="Dynamo only supports ctx.mark_dirty when each " + "dirty input is also returned from forward.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + # See Note [Activations with no version counter checks in eager] + # Compute which tensors in bwd_freevars came from ctx.save_for_backward. + # This allows AOT autograd to distinguish between tensors saved via + # save_for_backward vs those stashed directly on ctx (e.g., ctx.x = x). + saved_for_backward_idx = [] + if ctx.saved_tensors is not None and len(ctx.saved_tensors.tensors) > 0: + # Build a set of proxies that were passed to save_for_backward + saved_tensor_proxies = OrderedSet() + for tensor_vt in ctx.saved_tensors.tensors: + if tensor_vt.is_tensor(): + saved_tensor_proxies.add(tensor_vt.as_proxy()) + + # bwd_freevars is a dict of outer-graph proxy -> inner-graph proxy + # for all tensors passed from fwd to bwd. Find which indices + # correspond to save_for_backward tensors. + for i, fwd_proxy in enumerate(bwd_freevars.keys()): + if fwd_proxy in saved_tensor_proxies: + saved_for_backward_idx.append(i) + + # Store fwd_body + fwd_nn_modules = tx.output.tracing_context.module_context.copy_graphstate() + fwd_name = tx.output.install_subgraph( + "fwd_body", + torch.fx.GraphModule(fwd_nn_modules.nn_modules, fwd_graph), + ) + fwd_node = make_attr(tx, fwd_name) + + # Store bwd_body + bwd_nn_modules = tx.output.tracing_context.module_context.copy_graphstate() + bwd_name = tx.output.install_subgraph( + "bwd_body", + torch.fx.GraphModule(bwd_nn_modules.nn_modules, bwd_graph), + ) + bwd_node = make_attr(tx, bwd_name) + + p_args = ( + fwd_node, + bwd_node, + *list(fwd_freevars.keys()), + ) + kwargs_for_fn = { + "non_differentiable_idx": non_differentiable_idx, + "saved_for_backward_idx": saved_for_backward_idx, + } + # Preserve the existing HOP call shape for the common no-mark_dirty case. + if dirty_idx: + kwargs_for_fn["dirty_idx"] = dirty_idx + + # Store the invocation as a call + from torch._functorch.autograd_function import autograd_function_apply + + # We use speculate_subgraph to get the fwd graph, but it's always under no grad mode like what eager mode does. + # The fwd outputs (tensor's example_value) need to be inferred from fake tensor prop to get the correct attributes + # (e.g, tensor.requires_grad), which would be used by downstream Dynamo tracing. + # Since there can be other ops like Triton kernels, which depends on python dispatcher, we have to enable it. + # TODO - revisit if we need the python dispatcher + with enable_python_dispatcher(): + with tx.output.fake_mode: + fwd_freevars_args = [_get_fake_value(arg) for arg in fwd_freevars] + + example_value = autograd_function_apply( + tx.output.nn_modules[fwd_node.node.name], + tx.output.nn_modules[bwd_node.node.name], + *fwd_freevars_args, + **kwargs_for_fn, + ) + + flat_variable = add_call_function( + tx, autograd_function_apply, p_args, kwargs_for_fn, example_value + ) + # type: ignore[arg-type] + overwrite_tensor_vt_proxy(fwd_graph_output_vts, flat_variable) + # type: ignore[arg-type] + overwrite_tensor_vt_requires_grad(fwd_graph_output_vts, flat_variable) + return fwd_out + + def prepare_ctx_vt( + self, tx: "InstructionTranslatorBase", args: Any, kwargs: Any + ) -> "AutogradFunctionContextVariable": + from . import AutogradFunctionContextVariable + + ctx = AutogradFunctionContextVariable.create(tx, args, kwargs) + with discard_graph_changes(tx): + # A little hacky, but we need a dummy ctx proxy for speculate_subgraph. + # We should clean this up at some point. + proxy = tx.output.create_proxy( + "call_function", torch.autograd.function.FunctionCtx, (), {} + ) + # type: ignore[attr-defined] + set_example_value(proxy.node, ctx.value) + # type: ignore[attr-defined] + ctx.proxy = proxy + # pyrefly: ignore[bad-return] + return ctx + + def trace_forward_graph( + self, + tx: "InstructionTranslatorBase", + ctx: "AutogradFunctionContextVariable", + fwd_tracer: "SubgraphTracer", + args: Any, + kwargs: Any, + ) -> tuple[ + VariableTracker, + VariableTracker, + torch.fx.Graph, + dict[Proxy, Proxy], + VariableTracker | tuple[VariableTracker, ...], + ]: + """ + Traces the forward method of the autograd.Function object. + """ + from torch._functorch.autograd_function import DynamoAutogradFunctionTraceHelper + + fwd_fn, fwd_args = self.prepare_fn_vt(tx, ctx, "forward", args) + + # autograd.Function forward does a few things like running in no_grad + # mode and also applying view_as for input tensors that are returned as + # outputs. Therefore, we wrap the original forward in a helper that have + # those extra bits for Dynamo to trace. + fwd_fn = _make_inlined(tx, DynamoAutogradFunctionTraceHelper.fwd_trace_helper)( + fwd_fn + ) + + # Speculate subgraph on the fwd + fwd_out, fwd_graph, fwd_freevars, fwd_graph_output_vts, _ = ( + speculate_subgraph_with_auto_output_flattening( + tx, + fwd_fn, + fwd_args, + kwargs, + self._HOP_NAME, + enable_grad=None, + set_subgraph_inputs="automatic", + allow_side_effects=True, + filter_aliased_intermediates=True, + tracer=fwd_tracer, + ) + ) + + # There could be unused inputs in the forward, and Dynamo might not + # capture them. We must lift them as inputs, because even though they + # are not used in forward, we still need to account for their gradients + # in the backward. + for arg in args: + if arg.is_tensor(): + fwd_tracer.maybe_lift_tracked_freevar_to_input(arg.as_proxy()) + + if ctx in tx.output.side_effects.store_attr_mutations: + if ( + "_materialize_non_diff_grads" + in tx.output.side_effects.store_attr_mutations[ctx] + ): + unimplemented( + gb_type="autograd.Function.apply: _materialize_non_diff_grads mutation", + context="", + explanation="Mutations to autograd.Function.ctx._materialize_non_diff_grads are not supported.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + return fwd_fn, fwd_out, fwd_graph, fwd_freevars, fwd_graph_output_vts + + def trace_backward_graph( + self, + tx: "InstructionTranslatorBase", + ctx: "AutogradFunctionContextVariable", + fwd_tracer: "SubgraphTracer", + fwd_out: VariableTracker, + fwd_fn: VariableTracker, + ) -> tuple[ + list[VariableTracker], + VariableTracker, + torch.fx.Graph, + dict[Proxy, Proxy], + VariableTracker | tuple[VariableTracker, ...], + ]: + """ + Traces the backward method of the autograd.Function object. + """ + from . import UserMethodVariable + + # Note that for the forward, we do not restore side effects, because we + # want the later tracing to see the side-effects. But for backward, we + # are just trying to capture the graph, and therefore we must restore + # the side effects. + prev_side_effects = tx.output.side_effects + + # Speculate subgraph on the backward. We make the bwd tracer a child of + # the fwd tracer, because backward may rely on tensors/attrs created in + # the fwd tracer. + bwd_tracer = torch._dynamo.output_graph.SubgraphTracer( + tx.output, + parent=fwd_tracer, + source_target=self._HOP_NAME, + ) + + bwd_args = [] + if fwd_out.is_tensor(): + bwd_args.append(fwd_out) + else: + if not isinstance(fwd_out, variables.BaseListVariable): + raise AssertionError("Expected fwd_out to be a BaseListVariable") + for i in fwd_out.items: + if i.is_tensor(): + bwd_args.append(i) + else: + bwd_args.append(ConstantVariable.create(None)) + + bwd_fn, bwd_args = self.prepare_fn_vt(tx, ctx, "backward", bwd_args) + + def is_strict_for(v: VariableTracker) -> bool: + if v.is_tensor(): + # we can be more lax for stuff from forward + return v.proxy.tracer is not fwd_tracer # type: ignore[attr-defined] + return True + + # automatic_with_forced_inputs relies on the function arg names to + # create a new proxy. Also, it will always INSERT a tensor placeholder + # as input, even though it might not be used in the graph. This allows + # us to make a mapping for the backward graph. + with ( + tx.output.subtracer(fwd_fn, fwd_tracer), # type: ignore[arg-type] + tx.strict_translation_mode(is_strict_for), + ): + try: + bwd_out, bwd_graph, bwd_freevars, bwd_graph_output_vts, _ = ( + speculate_subgraph_with_auto_output_flattening( + tx, + bwd_fn, + bwd_args, + {}, + self._HOP_NAME, + # TODO - revisit if we need enable_grad + enable_grad=False, + set_subgraph_inputs="automatic_with_forced_inputs", + allow_side_effects=False, + tracer=bwd_tracer, + ) + ) + except torch._dynamo.exc.UnknownPropertiesDuringBackwardTrace as e: + # TODO - Do not support this path because of eager + # divergence forced by contiguous calls. Instead suggested + # nonstrict_trace. + from unittest import mock + + bwd_tracer = torch._dynamo.output_graph.SubgraphTracer( + tx.output, + parent=fwd_tracer, + source_target=self._HOP_NAME, + ) + from .._trace_wrapped_higher_order_op import ( + autograd_function_backward_rewritten, + ) + from .builder import SourcelessBuilder + + if isinstance(self.bwd_fn, types.FunctionType): + bwd_fn = SourcelessBuilder.create( + tx, autograd_function_backward_rewritten(self.bwd_fn) + ) + elif isinstance(self.bwd_fn, types.MethodType): + bwd_fn = UserMethodVariable( + autograd_function_backward_rewritten(self.bwd_fn.__func__), + VariableTracker.build(tx, self.bwd_fn.__class__), + ) + else: + unimplemented( + gb_type="autograd.Function.apply: non-function or method backward (2)", + context=str(self.bwd_fn), + explanation="Expected backward function to be a function or method.", + hints=[], + from_exc=e, + ) + + with mock.patch( + "torch._dynamo.config._autograd_backward_strict_mode_conditional_banned_ops", + [], + ): + bwd_out, bwd_graph, bwd_freevars, bwd_graph_output_vts, _ = ( + speculate_subgraph_with_auto_output_flattening( + tx, + bwd_fn, + bwd_args, + {}, + self._HOP_NAME, + enable_grad=False, + set_subgraph_inputs="automatic_with_forced_inputs", + allow_side_effects=False, + tracer=bwd_tracer, + ) + ) + + # Restore the side effects + tx.output.side_effects = prev_side_effects + + return bwd_args, bwd_out, bwd_graph, bwd_freevars, bwd_graph_output_vts + + def rewire_bwd_graph_outputs( + self, + fwd_freevars: dict[Proxy, Proxy], + bwd_out: VariableTracker, + bwd_graph: torch.fx.Graph, + bwd_freevars: dict[Proxy, Proxy], + orig_fwd_args: list[VariableTracker], + ) -> None: + # --------------------------------------------------------------------- + # Forward–Backward Input/Output Alignment + # + # autograd.Function requires that the outputs of backward() correspond + # exactly to the inputs of forward(). Normally this alignment is the + # user’s responsibility. However, when Dynamo synthesizes a new + # autograd.Function for a traced region, Dynamo must perform this + # alignment automatically. + # + # To do this, Dynamo uses the *original* forward call site as the anchor + # that defines how forward inputs map to backward outputs. + # + # --------------------------------------------------------------------- + # Terminology + # + # fwd_freevars / bwd_freevars: + # Maps from *outer-graph proxies* to *inner-graph placeholder + # proxies*. Keys are always outer-graph proxies (these may be actual + # user inputs or intermediate values lifted into the subgraph). + # + # orig_fwd_args: + # VariableTrackers for the forward() inputs. Since these correspond + # to user-exposed arguments, each tracker points to an *outer-graph* + # proxy. + # + # bwd_outs: + # VariableTrackers for the backward() outputs. These usually point to + # *inner-graph* proxies, except for cases where a forward input is + # passed directly through to a backward output—in which case the + # tracker may still refer to an outer-graph proxy. + # + # --------------------------------------------------------------------- + # Goal + # + # To ensure forward–backward consistency, we must rewire the backward + # graph outputs so that they line up with the forward graph inputs. + # + # We build a mapping from outer-graph proxy → inner-graph proxy using + # orig_fwd_args and bwd_outs, then iterate over the fwd_graph inputs to + # determine which backward outputs must be generated (or padded with + # None) to satisfy autograd’s calling convention. + # + # --------------------------------------------------------------------- + # Example + # + # Suppose the forward receives a user-defined object: + # + # @dataclass + # class Weird: + # x: int + # b: torch.Tensor + # c: torch.Tensor + # + # class Foo(torch.autograd.Function): + # @staticmethod + # def forward(ctx, x: torch.Tensor, weird: Weird, z: torch.Tensor): + # ctx.save_for_backward(weird.b, weird.c) + # return weird.b * weird.c * x.clone() + # + # @staticmethod + # def backward(ctx, grad): + # b, c = ctx.saved_tensors + # return grad * b * c, None, grad * 2 + # + # Dynamo lifts the tensor fields of the user-defined object for the trace: + # + # fwd_graph(): + # %l_weird_b : FakeTensor = placeholder[target=l_weird_b] + # %l_weird_c : FakeTensor = placeholder[target=l_weird_c] + # %l_x_ : FakeTensor = placeholder[target=l_x_] + # %l_z_ : FakeTensor = placeholder[target=l_z_] + # ... + # return (outs,) + # + # The initial backward graph: + # + # bwd_graph(): + # %grad : Tensor = placeholder[target=grad] + # %l_weird_b : FakeTensor = placeholder[target=l_weird_b] + # %l_weird_c : FakeTensor = placeholder[target=l_weird_c] + # ... + # return (mul_1, mul_2) + # + # The forward graph has 4 inputs, but the backward graph produces only 2 + # outputs, and their ordering does not match the forward argument order. + # + # So Dynamo rewires the backward graph outputs to align with the forward + # inputs: + # + # bwd_graph(): + # ... + # return (None, None, mul_1, mul_2) + # + # This ensures the synthesized autograd.Function conforms to PyTorch’s + # forward/backward contract. + # --------------------------------------------------------------------- + + def get_bwd_node(vt: VariableTracker) -> torch.fx.Node: + # Backward tensor vt here can be - (1) an intermediate, or (2) input + # to the backward graph. If it is an input to the backward graph, we have to lookup bwd_freevars to get the inner proxy. + return bwd_freevars.get(vt.proxy, vt.proxy).node # type: ignore[attr-defined] + + tensor_args_seen: list[Any] = [] + for arg in orig_fwd_args: + if arg.is_tensor(): + fake_tensor = _get_fake_value(arg) + if any(fake_tensor is seen for seen in tensor_args_seen): + unimplemented( + gb_type="autograd.Function.apply: duplicate tensor input", + context="", + explanation="Dynamo does not support tracing autograd.Function.apply " + "when the same tensor is passed to multiple forward inputs.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + tensor_args_seen.append(fake_tensor) + + # Find the mapping between orig_fwd_args and bwd_out + # pyrefly: ignore [implicit-any] + outer_fwd_proxy_to_bwd_node = {} + if isinstance(bwd_out, variables.BaseListVariable): + bwd_outs = bwd_out.items + for idx, fwd_arg in enumerate(orig_fwd_args): + # We care about tensor args. For non-tensor args, the bwd output returns None. + if fwd_arg.is_tensor(): + bwd_out_at_idx = bwd_outs[idx] + if bwd_out_at_idx.is_tensor(): + # type: ignore[attr-defined] + outer_fwd_proxy_to_bwd_node[fwd_arg.proxy] = get_bwd_node( + bwd_out_at_idx + ) + else: + # backward can return None at the output + if not isinstance(bwd_out_at_idx, variables.ConstantVariable): + raise AssertionError( + "Expected backward output to be a ConstantVariable" + ) + if bwd_out_at_idx.value is not None: + raise AssertionError( + "Expected backward output ConstantVariable to have value None" + ) + # type: ignore[attr-defined] + outer_fwd_proxy_to_bwd_node[fwd_arg.proxy] = None + + elif bwd_out.is_tensor(): + # type: ignore[attr-defined] + outer_fwd_proxy_to_bwd_node[orig_fwd_args[0].proxy] = get_bwd_node(bwd_out) + + # Ideally, we should have walked through the fwd placeholders. But we + # can instead walk through the fwd_freevars, which is a insertion sorted + # dictionary and therefore represents the outer_proxies for the + # placeholder in the same order as that as placeholders. + rewired_bwd_outputs = [ + outer_fwd_proxy_to_bwd_node.get(fwd_proxy) for fwd_proxy in fwd_freevars + ] + + for node in bwd_graph.find_nodes(op="output"): + bwd_graph.erase_node(node) + break + bwd_graph.output(tuple(rewired_bwd_outputs)) + bwd_graph.lint() + + def handle_saved_tensors_wiring( + self, + fwd_out: VariableTracker, + fwd_graph: torch.fx.Graph, + fwd_freevars: dict[Proxy, Proxy], + fwd_graph_body_outputs: list[VariableTracker], + bwd_graph: torch.fx.Graph, + bwd_freevars: dict[Proxy, Proxy], + ) -> tuple[torch.fx.Graph, torch.fx.Graph]: + # --------------------------------------------------------------------- + # Rewiring Forward Outputs to Backward Inputs (and Handling Saved Tensors) + # + # In `rewire_bwd_graph_outputs`, we aligned the *forward inputs* with the + # *backward outputs*. This method performs the complementary task: + # aligning the *forward outputs* with the *backward inputs*, while also + # incorporating all tensors saved via ctx.save_for_backward. + # + # There are two main issues we must resolve: + # + # (1) Forward outputs may contain non-tensor values. + # This means the number of tensors visible in fwd_out may not match + # the number of tensors produced by the traced forward graph. As a + # result, the backward graph’s placeholders may not line up with the + # actual tensor outputs. + # + # (2) The backward graph may require intermediate tensors saved during + # the forward pass (via save_for_backward), but those intermediates + # might not currently be included among the forward graph’s outputs. + # + # Together, these issues mean that the bwd_graph input signature may be + # inconsistent with what fwd_graph outputs, and we need to rewrite both. + # + # Lets look at an example to understand the transformation + # + # class Add(torch.autograd.Function): + # @staticmethod + # def forward(ctx, x, y): + # a = torch.sin(x) + # b = torch.cos(y) + # ctx.save_for_backward(a) + # return Foo(a, b), x * y + + # @staticmethod + # def backward(ctx, grad_a, grad_b): + # (a,) = ctx.saved_tensors + # return grad_b * 2, a * grad_b * 3 + + # Before + # fwd_graph(): + # %l_x_ : torch._subclasses.fake_tensor.FakeTensor [num_users=2] = placeholder[target=l_x_] + # %l_y_ : torch._subclasses.fake_tensor.FakeTensor [num_users=2] = placeholder[target=l_y_] + # .... + # return (a, b, out) + # + # bwd_graph(): + # %grad_b : torch.Tensor [num_users=2] = placeholder[target=grad_b] + # %a : torch._subclasses.fake_tensor.FakeTensor [num_users=1] = placeholder[target=a] + # .... + # return (mul, mul_2) + # + # The problems here: + # (1) fwd_graph has 3 tensor outputs (a, b, out), but bwd_graph has + # only 1 gradient input - grad_b. We need 3. + # + # (2) bwd_graph uses `a` (a saved tensor) as an input, but fwd_graph + # does not currently return `a`. To make `a` available to the + # backward graph, the forward graph must expose it as part of its + # output signature. + # + # After this transformation + # fwd_graph(): + # %l_x_ : torch._subclasses.fake_tensor.FakeTensor [num_users=2] = placeholder[target=l_x_] + # %l_y_ : torch._subclasses.fake_tensor.FakeTensor [num_users=2] = placeholder[target=l_y_] + # ..... + # return ((a, b, out), (a,)) + # bwd_graph(): + # %unused_0 : [num_users=0] = placeholder[target=unused_0] + # %unused_1 : [num_users=0] = placeholder[target=unused_1] + # %grad_b : [num_users=2] = placeholder[target=grad_b] + # %a : [num_users=1] = placeholder[target=a] + # ..... + # return (mul, mul_2) + # + # Key changes: + # + # 1) The forward graph now returns: + # (existing_outputs), (saved_tensors) + # This exposes saved intermediates (`a`) as part of the fwd output + # structure, making them available to backward. + # + # 2) The backward graph input signature is rewritten to: + # (*grads_for_existing_outputs, *saved_tensors) + # This ensures the counts and ordering match the new fwd_graph + # output structure. Placeholders corresponding to tensors whose + # gradients are unused (e.g., `a`, `b`) appear as `%unused_*`. + # + # This alignment ensures that the synthesized autograd.Function follows + # PyTorch’s forward/backward calling convention and that all required + # saved tensors are available to the backward graph. + # --------------------------------------------------------------------- + + # To address Problem (1), we must determine which backward-graph inputs + # correspond to the forward-graph outputs. + # + # We use two facts: + # • `fwd_out` preserves the original forward output order. + # • Backward-graph inputs are also ordered according to the backward() + # method signature, thanks to automatic_with_forced_inputs. + # + # For any forward output that is *not* a tensor, there is no + # corresponding tensor placeholder in the backward graph. During tracing, + # we intentionally inserted a `None` VariableTracker for these positions, + # so the backward graph contains no placeholder for them. + bwd_input_nodes = list(bwd_graph.find_nodes(op="placeholder")) + # pyrefly: ignore [implicit-any] + fwd_vt_to_bwd_node = {} + bwd_idx = 0 + if isinstance(fwd_out, variables.BaseListVariable): + for fwd_vt in fwd_out.items: + if fwd_vt.is_tensor(): + fwd_vt_to_bwd_node[fwd_vt] = bwd_input_nodes[bwd_idx] + bwd_idx += 1 + else: + if fwd_out.is_tensor(): + fwd_vt_to_bwd_node[fwd_out] = bwd_input_nodes[bwd_idx] + bwd_idx += 1 + + rewired_bwd_graph_inputs = [] + for fwd_graph_vt in fwd_graph_body_outputs: + # for tensor vts that were part of a user-defined object (like in + # the above example), we just set None for now. Later, we will use + # these None to insert a unused placeholder. + # type: ignore[arg-type] + rewired_bwd_graph_inputs.append(fwd_vt_to_bwd_node.get(fwd_graph_vt)) + + # To address Problem (2), we must incorporate any tensors that were saved + # (or otherwise smuggled) from the forward pass into the backward graph. + # + # Fortunately, these are easy to identify: they appear in `bwd_freevars`. + # `bwd_freevars` maps outer-graph lifted proxies to inner-graph placeholder + # proxies. Because the backward graph is traced using proxies originating + # from `fwd_out`, any value lifted into the backward graph represents a + # saved/smuggled tensor. + # + # Once we identify these saved tensors, we must also locate their + # corresponding forward-graph proxies so that the forward graph can return + # these tensors as part of its output signature. + extra_fwd_output_nodes = [] + for fwd_proxy, bwd_inner_proxy in bwd_freevars.items(): + # For backward, its easy, just get the node from bwd_inner_proxy + rewired_bwd_graph_inputs.append(bwd_inner_proxy.node) + + # For the fwd_proxy, it could be a proxy from the outer graph, or it + # could be an intermediate. + # First ensure that's its inner fwd proxy + inner_fwd_proxy = fwd_freevars.get(fwd_proxy, fwd_proxy) + extra_fwd_output_nodes.append(inner_fwd_proxy.node) + + # Mechanical steps from here on. We have the extra_fwd_outputs and rewired_bwd_inputs. Lets make the changes. + # Lets change the fwd graph outputs. + # pyrefly: ignore [implicit-any] + fwd_output_nodes = [] + for node in fwd_graph.find_nodes(op="output"): + fwd_output_nodes = node.args[0] + fwd_graph.erase_node(node) + break + + # The signature is now ((*existing_outputs), (*extra_outputs)). Please + # take a look at AutogradFunctionApply where we take the saved_tensors + # out in the forward method to save for backward. + new_fwd_graph_outputs = (fwd_output_nodes, tuple(extra_fwd_output_nodes)) + fwd_graph.output(new_fwd_graph_outputs) + fwd_graph.lint() + + # Now lets change the bwd graph. + new_graph = torch.fx.Graph() + env = {} + + count = itertools.count() + + for node in rewired_bwd_graph_inputs: + if node is None: + new_node = new_graph.placeholder(f"unused_{next(count)}") + else: + new_node = new_graph.placeholder(node.name) + new_node.meta = copy.copy(node.meta) + env[node] = new_node + + for node in bwd_graph.nodes: + if node.op == "placeholder": + if node not in env: + raise AssertionError("Placeholder node not found in env") + else: + env[node] = new_graph.node_copy(node, lambda x: env[x]) + env[node].meta = copy.copy(node.meta) + + new_graph.lint() + return fwd_graph, new_graph + + def prepare_fn_vt( + self, + tx: "InstructionTranslatorBase", + ctx: "AutogradFunctionContextVariable", + method_name: str, + args: list[VariableTracker], + ) -> tuple[VariableTracker, list[VariableTracker]]: + from . import UserMethodVariable + + source = None + if self.parent_source: + source = AttrSource(self.parent_source, member=method_name) + + if method_name == "forward": + fn = self.fwd_fn + else: + fn = self.bwd_fn + + fn_vt, fn_args = None, None + if isinstance(fn, types.FunctionType): + fn_vt = VariableTracker.build(tx, fn, source=source) + fn_args = [ctx, *args] + elif isinstance(fn, types.MethodType): + cls_vt = VariableTracker.build(tx, fn.__class__) + fn_vt = UserMethodVariable( + fn.__func__, + cls_vt, + source=source, + ) + fn_args = [cls_vt, ctx, *args] + else: + unimplemented( + gb_type="autograd.Function.apply: non-function or method forward", + context=str(fn), + explanation=f"Expected {method_name} to be a function or method.", + hints=[], + ) + if fn_vt is None: + raise AssertionError("fn_vt must not be None") + if fn_args is None: + raise AssertionError("fn_args must not be None") + return fn_vt, fn_args + + +def _get_fake_value(x: Union[VariableTracker, Proxy, "FakeTensor"]) -> "FakeTensor": + if isinstance(x, variables.VariableTracker): + return x.as_proxy().node.meta["example_value"] + elif isinstance(x, torch.fx.Proxy): + return x.node.meta["example_value"] + else: + return x + + +def maybe_positional_arg_names(func: VariableTracker) -> list[str] | None: + result = [] + if not hasattr(func, "get_function"): + return None + try: + fn = func.get_function() + except (Unsupported, NotImplementedError): + return None + try: + sig = inspect.signature(fn) + except ValueError: + return None + for name, param in sig.parameters.items(): + if param.kind is inspect.Parameter.VAR_POSITIONAL: + return None + if ( + param.kind is inspect.Parameter.POSITIONAL_ONLY + or param.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD + ): + if name == "self": + # FX graphs can't have a placeholder named self + result.append("self_") + else: + result.append(name) + return result + + +class BaseHOPVariable(WrapHigherOrderVariable): + # Generic fallback for BaseHOP instances not explicitly mapped + # The actual HOP name comes from self.value._name at runtime + _HOP_NAME = "base HOP (name not yet determined)" + supports_input_mutation = False + supports_aliasing = False + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self._HOP_NAME = self.value._name + + def python_type(self) -> type: + return type(self.value) + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + ( + p_args, + p_kwargs, + example_value, + body_r, + _, + _, + body_graph_output_vts, + _, + ) = self.create_wrapped_node( + tx, args[0], args[1:], {}, self.value._name, subgraph_name="subgraph" + ) + if len(p_kwargs) != 0: + raise AssertionError("Expected p_kwargs to be empty") + + p_kwargs = {key: value.as_proxy() for key, value in kwargs.items()} + return _call_function_with_auto_output_flattening( # type: ignore[return-value] + tx, + self.value, + p_args, + p_kwargs, + example_value, + body_r, + body_graph_output_vts, + ) + + +class LocalMapWrappedHigherOrderVariable(WrapHigherOrderVariable): + _HOP_NAME = "torch.ops.higher_order.local_map_hop" + supports_input_mutation = False + supports_aliasing = False + + # Subclasses aren't supported by speculate_subgraph yet + # So this HOP is only usable with plain tensors + _enabled = False + + @classmethod + @contextlib.contextmanager + def enable(cls) -> Generator[None, None, None]: + """Context manager to temporarily enable local map wrapping. + Will be removed when speculate_subgraph supports subclass inputs: + https://github.com/pytorch/pytorch/issues/161456. + + Usage: + with LocalMapWrappedHigherOrderVariable.enable_wrapping(): + # Code where should_wrap_in_hop will return True + pass + """ + old_value = cls._enabled + cls._enabled = True + try: + yield + finally: + cls._enabled = old_value + + @classmethod + def should_wrap_in_hop(cls, value: Any) -> bool: + if not torch.distributed.is_available(): + return False + + from torch.distributed.tensor.experimental._func_map import _local_map_wrapped + + # check is important to avoid subclass dispatch + if type(value) is not type(_local_map_wrapped): + return False + + return value is _local_map_wrapped and cls._enabled + + @staticmethod + # pyrefly: ignore[bad-override] + def build(**options: Any) -> "TorchHigherOrderOperatorVariable": + return TorchHigherOrderOperatorVariable.make( + torch._higher_order_ops.local_map_hop, + **options, + ) + + def python_type(self) -> type: + return type(self.value) + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + """ + Goal of this function is to rewrite local_map usage as a HOP: + local_map(func, ...) -> local_map_hop(gm, ...) + """ + + ( + user_func, + out_placements, + in_placements, + in_grad_placements, + device_mesh, + redistribute_inputs, + enable_spmd_types, + *user_args, + ) = args + + # None placements are used to pass non-Tensors into the local_map function. + # Containers passed this way can not hold tensors. Thus, Dynamo would have inlined + # into them, and we handle None placements by assuming they will be desugared away. + # This will need to be adjusted for dynamic shapes support. + def check_none_last(placements: Sequence[Any | None]) -> int: + seen_none = 0 + for p in placements: + if p is None: + seen_none += 1 + else: + if seen_none != 0: + raise AssertionError( + "Tracing local_map is only currently supported with None placements last." + ) + return seen_none + + inputs_none_placements = check_none_last(in_placements.value) # type: ignore[attr-defined] + output_none_placements = check_none_last(out_placements.value) # type: ignore[attr-defined] + + local_map_kwargs = { + "out_placements": out_placements.value, # type: ignore[attr-defined] + "in_placements": in_placements.value, # type: ignore[attr-defined] + "redistribute_inputs": redistribute_inputs.value, # type: ignore[attr-defined] + "in_grad_placements": in_grad_placements.value, # type: ignore[attr-defined] + "device_mesh": device_mesh.value, # type: ignore[attr-defined] + } + if local_map_kwargs["device_mesh"] is None: + raise AssertionError( + "Not yet implemented, please manually provide a device_mesh to local_map." + ) + mesh = local_map_kwargs["device_mesh"] + + # For Autoparallel, the initial trace is done with global shapes, then we decide model weights sharding, + # and reuse the graph. Since the sharding decision is after the initial trace, we can't trace with local shapes. + # For local_map however, since we specify all placements, we can trace with local shapes. + + # Step 1: Validate the annotated function matches the input_placements (i.e. that it can run in eager) + template = ( + "Expecting {expected} {inputs_or_outputs} to local_map function based on placements" + ", but found {actual}. Please ensure the count matches for eager. " + ) + if len(in_placements.value) != len(user_args): # type: ignore[attr-defined] + raise AssertionError( + template.format( + expected=len(in_placements.value), # type: ignore[attr-defined] + inputs_or_outputs="inputs", + actual=len(user_args), + ) + ) + + from torch._higher_order_ops.local_map import ( + redistribute_fw_inputs, + redistribute_fw_outputs, + ) + + # Step 2: Convert inputs to local shapes + priors = {} + for placements, vt in zip(in_placements.value, user_args): # type: ignore[attr-defined] + if isinstance(vt, variables.lazy.LazyVariableTracker): + vt = variables.lazy.LazyVariableTracker.realize_all(vt) + + if not vt.is_tensor(): + if placements is not None: + raise AssertionError( + "Expected placements to be None for non-tensor input" + ) + continue + + global_tensor = vt.as_proxy().node.meta["example_value"] + # NOTE: We don't support local_map region relying on exact grad_fn information + # This is okay since accessing grad_fn is a graph break. + local_tensor = redistribute_fw_inputs( + (global_tensor,), + (placements,), + mesh, + ) + local_tensor = local_tensor[0] + + priors[vt] = global_tensor + vt.as_proxy().node.meta["example_value"] = local_tensor + # pyrefly: ignore [missing-attribute] + vt.synchronize_attributes(tx) + + # Step 3: Trace local_map subgraph with local tensors + # + # Use "automatic_with_forced_inputs" so subgraph placeholders are + # created eagerly in the user's call-site arg order. Under "automatic", + # Dynamo lifts freevars in first-use order, which diverges between + # static and dynamic shapes (e.g. `x.shape[-1]` early in the body lifts + # `x` first under dynamic shapes but constant-folds under static). The + # forced mode keeps `in_placements` aligned with user args regardless. + ( + p_args, + p_kwargs, + example_value, + body_r, + body_gmod, + body_name, + body_graph_output_vts, + _, + ) = self.create_wrapped_node( + tx, + user_func, + user_args, + kwargs, + self.value._name, + subgraph_name="subgraph", + set_subgraph_inputs="automatic_with_forced_inputs", + ) + + # Step 4: Validate traced graph signature still matches placement information + expected_num_inputs = len(in_placements.value) - inputs_none_placements # type: ignore[attr-defined] + actual_num_inputs = len(body_gmod.graph.find_nodes(op="placeholder")) + expected_num_outputs = len(out_placements.value) - output_none_placements # type: ignore[attr-defined] + if len(body_gmod.graph.find_nodes(op="output")) != 1: + raise AssertionError("Expected exactly one output node in body graph") + actual_num_outputs = len(body_gmod.graph.find_nodes(op="output")[0].args[0]) + + template = ( + "Expecting {expected} {inputs_or_outputs} to local_map function based on placements" + ", but found {actual}. If the count matches for eager, " + "Dynamo may have flattened {inputs_or_outputs} to the function or found additional " + "tensors used via closures. " + "Please adjust the input placements to match what the traced graph sees: \n{gm_str}." + ) + + def make_error_msg(*args: Any) -> str: + expected_num, actual_num, inputs_or_outputs = args + gm_str = body_gmod.print_readable(print_output=False) + return template.format( + expected=expected_num, + inputs_or_outputs=inputs_or_outputs, + actual=actual_num, + gm_str=gm_str, + ) + + if expected_num_inputs != actual_num_inputs: + raise AssertionError( + make_error_msg(expected_num_inputs, actual_num_inputs, "inputs") + ) + if expected_num_outputs != actual_num_outputs: + raise AssertionError( + make_error_msg(expected_num_outputs, actual_num_outputs, "outputs") + ) + + if inputs_none_placements > 0: + expected_input_nodes = [ + arg.as_proxy().node for arg in user_args[:-inputs_none_placements] + ] + else: + expected_input_nodes = [arg.as_proxy().node for arg in user_args] + actual_input_nodes = [proxy.node for proxy in p_args] + if actual_input_nodes[0].op != "get_attr": + raise AssertionError("Expected first actual input node op to be 'get_attr'") + if "subgraph" not in actual_input_nodes[0].target: # type: ignore[attr-defined] + raise AssertionError( + "Expected 'subgraph' in first actual input node target" + ) + if expected_input_nodes != actual_input_nodes[1:]: + raise AssertionError( + "local_map: unexpected argument ordering. Outer HOP args did " + "not match user call-site order " + f"(expected={expected_input_nodes}, actual={actual_input_nodes[1:]}). " + "automatic_with_forced_inputs should have preserved order; " + "please file an issue at https://github.com/pytorch/pytorch/issues." + ) + if len(p_kwargs) != 0: + raise AssertionError("Expected p_kwargs to be empty") + + # Step 5: Install local_map subgraph + p_kwargs = {key: value.as_proxy() for key, value in kwargs.items()} + out = _call_function_with_auto_output_flattening( + tx, + self.value, + p_args, + p_kwargs, + example_value, + body_r, + body_graph_output_vts, + ) + + # Step 6: Restore inputs and outputs to global shapes + for vt, global_tensor in priors.items(): + vt.as_proxy().node.meta["example_value"] = global_tensor + # pyrefly: ignore [missing-attribute] + vt.synchronize_attributes(tx) + + outs = out.items if isinstance(out, TupleVariable) else [out] + if len(outs) != len(out_placements.value): # type: ignore[attr-defined] + raise AssertionError( + "Number of outputs must match number of out_placements" + ) + for placements, vt in zip(out_placements.value, outs): # type: ignore[attr-defined] + if not vt.is_tensor(): # type: ignore[attr-defined] + if placements is not None: + raise AssertionError( + "Expected placements to be None for non-tensor output" + ) + continue + + local_tensor = vt.as_proxy().node.meta["example_value"] # type: ignore[attr-defined] + + # NOTE: We don't support code after the local_map region relying on exact grad_fn information + # This is okay since accessing grad_fn is a graph break. + global_tensor = redistribute_fw_outputs( + (local_tensor,), + (placements,), + mesh, + num_activations=0, # this is not the joint + ) + global_tensor = global_tensor[0] + + vt.as_proxy().node.meta["example_value"] = global_tensor # type: ignore[attr-defined] + vt.synchronize_attributes(tx) # type: ignore[attr-defined] + + # TODO: Figure out how to handle output order diverging from eager + + # Treat as const, so we don't have to deal with Placement types in fx IR + # Guarded with EQUALS_MATCH on local_map call's arguments + body_gmod.meta["local_map_kwargs"] = { + "out_placements": out_placements.value[:expected_num_outputs], # type: ignore[attr-defined] + "in_placements": in_placements.value[:expected_num_inputs], # type: ignore[attr-defined] + "redistribute_inputs": redistribute_inputs.value, # type: ignore[attr-defined] + "in_grad_placements": in_grad_placements.value, # type: ignore[attr-defined] + "device_mesh": device_mesh.value, # type: ignore[attr-defined] + } + if out is None: + raise AssertionError("out must not be None") + return out + + +from .invoke_subgraph import InvokeSubgraphHigherOrderVariable + + +# Map operator names to their corresponding variable for fast TorchHigherOrderOperatorVariable.make() +_hop_name_to_variable_class = { + "cond": CondHigherOrderVariable, + "switch": SwitchHigherOrderVariable, + "while_loop": WhileLoopHigherOrderVariable, + "while_loop_stack_output": WhileLoopStackOutputHigherOrderVariable, + "map_impl": MapHigherOrderVariable, + "executorch_call_delegate": ExecutorchCallDelegateHigherOrderVariable, + "out_dtype": OutDtypeHigherOrderVariable, + "wrap": WrapHigherOrderVariable, + "hints_wrapper": HintsWrapperHigherOrderVariable, + "flex_gemm": FlexGemmHigherOrderVariable, + "flex_attention": FlexAttentionHigherOrderVariable, + "flex_attention_backward": FlexAttentionBackwardHighOrderVariable, + "wrap_activation_checkpoint": CheckpointHigherOrderVariable, + "tag_activation_checkpoint": CheckpointHigherOrderVariable, + "_export_tracepoint": ExportTracepointHigherOrderVariable, + "trace_wrapped": TraceWrappedHigherOrderOperatorVariable, + "strict_mode": StrictModeHigherOrderVariable, + "run_with_rng_state": RunWithRNGStateHigherOrderVariable, + "associative_scan": AssociativeScanHigherOrderVariable, + "scan": ScanHigherOrderVariable, + "call_torchbind": CallTorchbindHigherOrderVariable, + "print": PrintHigherOrderVariable, + "wrap_with_set_grad_enabled": WrapWithSetGradEnabledHigherOrderVariable, + "wrap_with_autocast": WrapWithAutocastHigherOrderVariable, + "dynamo_bypassing_wrapper": DynamoBypassingWrapperHigherOrderVariable, + "auto_functionalized": AutoFunctionalizeHigherOrderVariable, + "auto_functionalized_v2": AutoFunctionalizeHigherOrderVariable, + "inline_asm_elementwise": InlineAsmElementwiseHigherOrderVariable, + "invoke_subgraph": InvokeSubgraphHigherOrderVariable, + "custom_function_call": CustomFunctionHigherOrderOperatorVariable, + "local_map_hop": LocalMapWrappedHigherOrderVariable, +} diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/invoke_subgraph.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/invoke_subgraph.py new file mode 100644 index 0000000000000000000000000000000000000000..4ace18194412831cecefd5e5ce21c355109296b5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/invoke_subgraph.py @@ -0,0 +1,1492 @@ +""" +This module contains the InvokeSubgraphHigherOrderVariable class and its +supporting helpers for subgraph reuse (auto-cache) in Dynamo's invoke_subgraph +higher-order operator. +""" + +import collections +import enum +import logging +import traceback +import types +from dataclasses import dataclass +from typing import Any, cast, NamedTuple, TYPE_CHECKING, TypeGuard + +import torch +import torch._higher_order_ops +from torch._dynamo import graph_break_hints +from torch._dynamo.exc import unimplemented +from torch._dynamo.guards import ( + extract_tensor_metadata, + GUARD_VALUE_DISPATCH, + GuardCheckSpec, + SKIP_GUARD, + UnsupportedGuardCheckSpec, +) +from torch._dynamo.source import SyntheticLocalSource +from torch._dynamo.utils import _make_inlined, unpack_iterable +from torch._dynamo.variables.base import VariableTracker +from torch._dynamo.variables.constant import ConstantVariable +from torch._dynamo.variables.functions import UserFunctionVariable +from torch._dynamo.variables.higher_order_ops import WrapHigherOrderVariable +from torch._dynamo.variables.lists import ListVariable, TupleVariable +from torch._dynamo.variables.nn_module import UnspecializedNNModuleVariable +from torch._dynamo.variables.tensor import SymNodeVariable, TensorVariable +from torch._dynamo.variables.user_defined import UserDefinedObjectVariable +from torch._guards import ( + Guard, + InvokeSubgraphReuseCondition, + InvokeSubgraphReuseEntry, + Source, +) +from torch._higher_order_ops.invoke_subgraph import NestedCompileRegionOptions +from torch.fx.graph_module import GraphModule +from torch.fx.proxy import Proxy +from torch.utils import _pytree as pytree +from torch.utils._ordered_set import OrderedSet + + +if TYPE_CHECKING: + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + from torch._dynamo.variables.higher_order_ops import SubgraphTracingInfo + +log = logging.getLogger(__name__) +hc_log = torch._logging.getArtifactLogger(__name__, "hierarchical_compile") + +# Note: [invoke_subgraph subgraph reuse] +# +# When mark_compile_region wraps a function called N times (e.g. 80 identical +# transformer layers), Dynamo traces the subgraph once and stamps out cached +# copies for subsequent calls. It does safety checks to ensure that a subgraph +# is reusable, if not (e.g. side-effect), it will fallback to tracing the +# next invocation. +# +# HIGH-LEVEL FLOW +# =============== +# User code: model.layers[0](x), model.layers[1](x), ..., model.layers[79](x) +# | | | +# v v v +# +--------------+ +--------------+ +--------------+ +# | First Call | | Second Call | ... | 80th Call | +# +------+-------+ +------+-------+ +------+-------+ +# | | | +# v v v +# +--------------+ +--------------+ +--------------+ +# | Full subgraph| | Cache lookup | | Cache lookup | +# | trace | | (is_reusable) | | (is_reusable) | +# +------+-------+ +------+-------+ +------+-------+ +# | | | +# v v v +# +--------------+ +--------------+ +--------------+ +# | save_reuse_ | | stamp_out_ | | stamp_out_ | +# | entry() | | subgraph() | | subgraph() | +# +--------------+ +--------------+ +--------------+ +# +# WHAT GETS CACHED +# ================ +# After the first trace, save_reuse_entry stores an InvokeSubgraphReuseEntry +# (in _guards.py) containing: +# - body_name/body_gmod: the traced subgraph +# - arg_sources: sources of the original call's arguments +# - subgraph_input_mapping: how each lifted arg maps back to user inputs or captures +# - output_metadata: shape/stride/dtype/device of outputs +# +# Paired with an InvokeSubgraphReuseCondition containing: +# - input_checks: (tag, tensor_metadata) per input +# - guards: (source, handler, expected, guard) tuples +# - treespec: pytree structure of the args +# - traced_sources: sources accessed during the trace +# +# CACHE LOOKUP (is_reusable) +# ========================== +# On subsequent calls: +# 1. Input structure match -- same treespec, tags, tensor metadata. +# 2. Source replacement -- clone each guard's source with a replacement map +# (old: L['self'].layers[0].weight -> new: L['self'].layers[1].weight), +# then evaluate against the new source's runtime value. +# 3. Mutation check -- reject if the subgraph mutated any captured var. +# +# A shared resolve_cache memoizes intermediate source resolution (e.g. +# L['self'].layers is evaluated once and reused across all guards). +# +# STAMP OUT (stamp_out_subgraph) +# ============================== +# On cache hit, reconstruct the argument list using the freevar mapping +# (list[LiftedArgOrigin]): +# +# LiftedUserArg(index) +# User arg (activation / explicit input). +# Looked up from new call's flat proxies. +# +# LiftedCapturedSource(source) +# Sourceful captured var (weight, param, etc). +# Source is cloned with replacement map, resolved via +# VariableBuilder. Deduplicates via input_source_to_var. +# +# LiftedSyntheticObject(ctor_fn, ctor_args, ctor_arg_sources) +# Synthetic object (opaque type with SyntheticLocalSource). +# Reconstructed via synthetic_graph_input with cached constructor info. +# +# SAFETY +# ====== +# In normal Dynamo compilation, safety is enforced at runtime: guards are +# installed during tracing and re-evaluated on every subsequent call against +# real Python objects. Subgraph reuse operates differently — we are in the +# middle of tracing, there are no real Python objects, only VariableTrackers. +# We must answer: what could cause the second invocation of a nested compile +# region to produce a different trace than the first? +# +# VariableTrackers fall into two categories: +# +# 1. Intermediates — values produced during tracing with no originating source +# (e.g. the result of a prior FX op). These can reach a nested compile region +# only via (a) the region's explicit function arguments, or (b) closure +# capture. We do not support nested-function regions that close over tensors, +# so only (a) applies. For explicit arguments, the set of types we support is +# small and well-defined: TensorVariable, SymNodeVariable, and +# ConstantVariable (enum members included). Each has a cheap structural +# comparison (tensor metadata, symnode identity, constant value equality). +# We also snapshot the pytree treespec of the argument list and verify it +# matches on lookup, ensuring the flattened structure is identical. +# A sourceless object -- an nn.Module built during tracing, say -- has +# neither a structural comparison nor guards, so it is not eligible at all. +# +# 2. Sourceful variables — values with a known originating source (e.g. a +# module attribute or a local variable visible in the outer frame). For these +# we collect the guard delta from the first trace, parameterize the guard +# sources by replacing the original arg sources with the new arg sources, and +# re-evaluate the guards by resolving each source against the live f_locals / +# f_globals. The one extra hazard here is mutation: if the outer trace +# mutates a sourceful object between the first and second invocations, the +# cached guards would evaluate against stale values. We therefore also check +# that none of the sources read by the cached subgraph have been mutated in +# the outer SideEffects tracker before accepting a reuse. +# +# - max_reuse_entries (default 8, configurable via nested_compile_region arg) +# caps cache entries per function. Exceeding it raises RuntimeError. +# - Guard failures logged with guard type + user stack trace. +# Enable: TORCH_LOGS='+hierarchical_compile' +# --------------------------------------------------------------------------- +# Auto-cache helpers for invoke_subgraph +# --------------------------------------------------------------------------- + + +class InputTag(enum.Enum): + TENSOR = "tensor" + SYMNODE = "symnode" + CONSTANT = "constant" + OBJECT = "object" + + +class InputFingerprint(NamedTuple): + # (InputTag, VariableTracker) pairs for each leaf input. + flat_vts: list[tuple[InputTag, VariableTracker]] + # 1-1 mapping to flat_vts: source for each leaf, or None if the VT has no source. + arg_sources: list[Source | None] + # True if any leaf VT had an unsupported type for reuse. + has_unknown: bool = False + # TreeSpec from pytree.tree_flatten of the (args, kwargs) structure. + treespec: pytree.TreeSpec | None = None + + +def is_constant_like( + vt: Any, +) -> TypeGuard[ConstantVariable | UserDefinedObjectVariable]: + """Whether a leaf VT is compared by value, via ``vt.value``. + + Enum members are UserDefinedObjectVariable (not ConstantVariable) in + Dynamo, but they are immutable singletons, so value comparison is as + sound as it is for ConstantVariable. + """ + if isinstance(vt, ConstantVariable): + return True + return isinstance(vt, UserDefinedObjectVariable) and isinstance(vt.value, enum.Enum) + + +def classify_vt(vt: Any) -> InputTag | None: + """Return the tag for a leaf VT, or None if unsupported.""" + if isinstance(vt, TensorVariable): + return InputTag.TENSOR + elif isinstance(vt, SymNodeVariable): + return InputTag.SYMNODE + elif is_constant_like(vt): + return InputTag.CONSTANT + elif isinstance(vt, UserDefinedObjectVariable) and vt.source is not None: + # Covers nn.Modules too -- UnspecializedNNModuleVariable is a + # UserDefinedObjectVariable subclass. No metadata is recorded; reuse + # safety comes entirely from re-evaluating the guards installed on this + # object's source and on the sources derived from it. A sourceless + # object has no guards to re-evaluate, so it stays unsupported. + return InputTag.OBJECT + return None + + +def build_input_fingerprint( + tx: "InstructionTranslatorBase", + fn_args_vt: Any, + kwargs: dict[str, Any], +) -> InputFingerprint: + """Build an InputFingerprint by flattening (args, kwargs) via pytree. + + Flattens the argument structure into leaf VTs, classifying each leaf as + tensor/symnode/constant/module. Also records the TreeSpec so that + cache lookups can verify structural equivalence. + + Fast path: when kwargs is empty and all args are already leaf VTs + (tensor/symnode/constant/module), skip the pytree flatten entirely. + """ + # Fast path: flat args, no kwargs — skip pytree machinery. + if not kwargs: + all_leaf = True + for vt in fn_args_vt: + if classify_vt(vt) is None: + all_leaf = False + break + if all_leaf: + return build_fingerprint_fast(fn_args_vt) + + return build_fingerprint_with_pytree(tx, fn_args_vt, kwargs) + + +def build_fingerprint_fast(fn_args_vt: Any) -> InputFingerprint: + """Build fingerprint for the common case of flat leaf args, no kwargs.""" + flat_vts: list[tuple[InputTag, VariableTracker]] = [] + arg_sources: list[Source | None] = [] + for vt in fn_args_vt: + tag = classify_vt(vt) + if tag is None: + raise AssertionError( + f"classify_vt returned None for {type(vt).__name__} in fast path" + ) + flat_vts.append((tag, vt)) + # Always append (even None) to keep positional alignment with flat_vts + # so that source_replacement zip pairing is correct across calls. + arg_sources.append(getattr(vt, "source", None)) + return InputFingerprint(flat_vts, arg_sources) + + +def build_fingerprint_with_pytree( + tx: "InstructionTranslatorBase", + fn_args_vt: Any, + kwargs: dict[str, Any], +) -> InputFingerprint: + """Build fingerprint via pytree flatten for nested/kwargs cases. + + Recurses over the pytree structure natively (untraced), inlining/tracing + only each container node's own ``flatten_fn`` rather than the full + recursive tree_flatten dispatch around it. This is safe because node-type + classification only depends on ``type()``, never on tensor values. + + Note: skipping the traced registry dispatch also means we no longer + install guards on the pytree registry itself, for the plain-function + flatten_fn case (the non-FunctionType fallback below still traces the + full tree_flatten and so still installs them). That's fine either way: + this fingerprint is built fresh from the live registry on every + reuse-lookup (register_pytree_node isn't traceable, so the registry + can't change mid-trace), and reuse is separately gated on treespec/tag + equality. So a registry change between compiles can only make a cached + subgraph ineligible for reuse (has_unknown / treespec mismatch), never + silently wrong. + """ + from torch._dynamo.variables.builder import SourcelessBuilder + + flat_vts: list[tuple[InputTag, VariableTracker]] = [] + arg_sources: list[Source | None] = [] + has_unknown = False + + def add_leaf(vt: VariableTracker) -> None: + nonlocal has_unknown + tag = classify_vt(vt) + if tag is None: + has_unknown = True + else: + flat_vts.append((tag, vt)) + # Always append (even None) to keep positional alignment with flat_vts. + arg_sources.append(getattr(vt, "source", None)) + + def flatten(node_vt: VariableTracker) -> pytree.TreeSpec: + nonlocal has_unknown + try: + node_type = node_vt.python_type() + except NotImplementedError: + has_unknown = True + return pytree.treespec_leaf() + # Keep in sync with pytree._get_node_type. + if pytree.is_namedtuple_class(node_type): + node_type = collections.namedtuple + + if node_type not in pytree.SUPPORTED_NODES: + add_leaf(node_vt) + return pytree.treespec_leaf() + + flatten_fn = pytree.SUPPORTED_NODES[node_type].flatten_fn + if not isinstance(flatten_fn, types.FunctionType): + # _make_inlined only supports plain Python functions (it always + # wraps its argument in a UserFunctionVariable). A flatten_fn + # registered as e.g. a functools.partial, bound method, or + # callable object can't go through it directly. Fall back to + # tracing the full recursive tree_flatten for this subtree, which + # dispatches calls generically and so handles any callable. + leaves_vt, treespec_vt = unpack_iterable( + tx, _make_inlined(tx, pytree.tree_flatten)(node_vt) + ) + for leaf_vt in unpack_iterable(tx, leaves_vt): + add_leaf(leaf_vt) + return treespec_vt.as_python_constant() + + children_vt, context_vt = unpack_iterable( + tx, _make_inlined(tx, flatten_fn)(node_vt) + ) + context = context_vt.as_python_constant() + child_specs = [flatten(child) for child in unpack_iterable(tx, children_vt)] + return pytree.TreeSpec(node_type, context, child_specs) + + container_vt = SourcelessBuilder.create(tx, (list(fn_args_vt), kwargs)) + treespec = flatten(container_vt) + + return InputFingerprint(flat_vts, arg_sources, has_unknown, treespec) + + +def sym_num_key(sym_num: Any) -> Any: + """Key for matching a symbolic input against a cached one. + + Compares the symbolic expression rather than the SymInt object. Each tensor + holds its own SymInt objects, so two arguments carrying the same symbol + (e.g. the atom count threaded through successive layers) are distinct + objects. Equal expressions mean the same value, which is what reuse needs; + distinct symbols still have distinct expressions. + + ``expr`` rather than ``_expr`` on purpose: it has the ShapeEnv's + replacements applied, so a symbol that was specialized keys on the value it + was specialized to. + """ + return sym_num.node.expr + + +def get_flat_proxies(fingerprint: InputFingerprint) -> list[Proxy]: + """Collect deduplicated proxies from tensor/symnode leaves.""" + seen: set[torch.fx.Node] = set() + flat_proxies: list[Proxy] = [] + for tag, vt in fingerprint.flat_vts: + if tag in (InputTag.TENSOR, InputTag.SYMNODE): + proxy = vt.as_proxy() + if proxy.node not in seen: + seen.add(proxy.node) + flat_proxies.append(proxy) + return flat_proxies + + +@dataclass +class LiftedUserArg: + """Lifted arg that came from a user argument (intermediate activation or explicit input).""" + + index: int + + +@dataclass +class LiftedCapturedSource: + """Lifted arg that is a captured variable (e.g. a weight or parameter) with a Source.""" + + source: Any # Source + + +@dataclass +class LiftedSyntheticObject: + """Lifted arg that is a TorchScriptObject with a SyntheticLocalSource.""" + + ctor_fn: Any # Callable + ctor_args: tuple[Any, ...] + ctor_arg_sources: tuple[Any, ...] | None + + +@dataclass +class LiftedBoundSymbol: + """Lifted arg that is a SymInt already bound as a graph input. + + SymInt graph inputs are created during tensor wrapping (not through + VariableBuilder.wrap_symint), so they aren't registered in + unspec_variable_map or variable_tracker_cache. Using LiftedCapturedSource + for these would resolve the source to a concrete Python int via + source.get_value() instead of reusing the existing symbolic proxy. + """ + + expr: Any # sympy.Expr + + +LiftedArgOrigin = ( + LiftedUserArg | LiftedCapturedSource | LiftedSyntheticObject | LiftedBoundSymbol +) + + +def get_fn_code(fn_var: Any) -> types.CodeType | None: + if isinstance(fn_var, UserFunctionVariable): + return fn_var.get_function().__code__ + elif isinstance(fn_var, UnspecializedNNModuleVariable): + return ( + fn_var.value.forward.__func__.__code__ # pyrefly: ignore[missing-attribute] + ) + return None + + +def has_mutated_vars( + tx: "InstructionTranslatorBase", + traced_sources: OrderedSet[Source], +) -> bool: + """Check if any source accessed by the subgraph has been mutated. + + SideEffects.mutated_sources records the exact AttrSource for every + store_attr call. A simple set intersection with traced_sources tells + us whether any source the subgraph read was later written to. + """ + overlap = tx.output.side_effects.mutated_sources & traced_sources + if overlap: + hc_log.debug( + "subgraph_reuse: mutated sources detected -- %s", + overlap, + ) + return True + return False + + +def is_reuse_eligible( + tx: "InstructionTranslatorBase", + body_r: Any, + fingerprint: InputFingerprint, + tracing_info: "SubgraphTracingInfo", + traced_sources: OrderedSet[Source] | None = None, + has_reuse_hash_fn: bool = False, +) -> bool: + """Best-effort check for whether a traced subgraph result can be reused. + + It is possible that a subgraph is morally reusable but does not fall + into the limited support that Dynamo has today. Current limitations: + - The subgraph must not have side effects. + - No sourceful variable accessed by the subgraph may have been + mutated, because guards are snapshotted on source values at trace + time — if the underlying object changed since then, the cached + guards would silently evaluate against stale values. + - Output must be a single tensor, or a tuple/list of plain tensors. + - All flattened inputs must be one of: tensor, symnode, constant + (including enum members), or a sourceful user-defined object + (nn.Modules included) — for sourceless or other input types we + rely on the treespec and tags for structural matching, so only + types with well-defined comparison semantics are supported. + + When ``has_reuse_hash_fn`` is True, side-effect and mutation checks are + skipped because the hash key replaces guards — there are no guards to + go stale from mutations. + """ + if not has_reuse_hash_fn: + if tracing_info.side_effect_stack is not None: + stack_msg = "\n" + "".join( + traceback.format_list(tracing_info.side_effect_stack) + ) + hc_log.debug( + "subgraph_reuse: not eligible -- subgraph has side effects%s", + stack_msg, + ) + return False + + if traced_sources and has_mutated_vars(tx, traced_sources): + return False + + if isinstance(body_r, TensorVariable): + pass + elif isinstance(body_r, (TupleVariable, ListVariable)): + non_tensor = [ + type(item).__name__ + for item in body_r.items + if not isinstance(item, TensorVariable) + ] + if non_tensor: + hc_log.debug( + "subgraph_reuse: not eligible -- output contains non-tensor types: %s", + non_tensor, + ) + return False + else: + hc_log.debug( + "subgraph_reuse: not eligible -- output type %s is not tensor or tuple/list", + type(body_r).__name__, + ) + return False + + if fingerprint.has_unknown: + hc_log.debug( + "subgraph_reuse: not eligible -- unsupported input VT types", + ) + return False + + return True + + +def build_reuse_condition( + tx: "InstructionTranslatorBase", + fingerprint: InputFingerprint, + traced_sources: OrderedSet[Source], +) -> InvokeSubgraphReuseCondition | None: + """Build an InvokeSubgraphReuseCondition from a traced subgraph. + + A reuse condition is a mix of two kinds of checks: + + 1. **Input tag checks** (from flat_vts): For each flattened leaf VT, + we record its tag (InputTag.TENSOR/SYMNODE/CONSTANT/OBJECT) and + metadata (e.g. tensor shape/stride/dtype/device/requires_grad). + At lookup time, the treespec ensures structural equivalence, and + then we compare tags and metadata leaf-by-leaf. + + 2. **Guard checks** (from traced_sources): During the subgraph trace, + every source accessed via VariableBuilder is recorded. We look up + all guards installed on those sources (and on the arg_sources) to + build the set of guards that must be re-evaluated on cache hit. + This is more robust than guard diffing because it catches guards + that were already installed before the subgraph trace began. + + Raise if any guard type is unsupported, as a feedback for compiler + developers to support that guard type. + """ + from torch._guards import InvokeSubgraphReuseCondition + + input_checks: list[tuple[InputTag, object]] = [] + for tag, vt in fingerprint.flat_vts: + if tag == InputTag.TENSOR: + if not isinstance(vt, TensorVariable): + raise AssertionError( + f"expected TensorVariable for TENSOR tag, got {type(vt).__name__}" + ) + example = vt.proxy.node.meta.get("example_value", None) + if example is None: + hc_log.debug( + "subgraph_reuse: cannot build condition -- tensor input has no example_value" + ) + return None + input_checks.append((InputTag.TENSOR, extract_tensor_metadata(example))) + elif tag == InputTag.SYMNODE: + if not isinstance(vt, SymNodeVariable): + raise AssertionError( + f"expected SymNodeVariable for SYMNODE tag, got {type(vt).__name__}" + ) + input_checks.append((InputTag.SYMNODE, sym_num_key(vt.sym_num))) + elif tag == InputTag.CONSTANT: + if not is_constant_like(vt): + raise AssertionError( + f"expected constant-like VT for CONSTANT tag, got {type(vt).__name__}" + ) + # Type is part of the key: `Mode.ADD == 1` and `True == 1` compare + # equal, but an isinstance() check inside the region traces + # differently for each, so value equality alone is not enough. + input_checks.append((InputTag.CONSTANT, (type(vt.value), vt.value))) + elif tag == InputTag.OBJECT: + input_checks.append((InputTag.OBJECT, None)) + else: + raise AssertionError( + f"Unexpected input tag '{tag}' for {type(vt).__name__} -- " + f"is_reuse_eligible should have rejected this" + ) + + # Collect all guards for sources accessed during the subgraph trace + # and for the flattened arg sources. + all_sources = set(traced_sources) + all_sources.update(s for s in fingerprint.arg_sources if s is not None) + all_relevant_guards: set[Guard] = set() + for source in all_sources: + all_relevant_guards.update(tx.output.guards.get_guards_for_source(source)) + + guard_tuples: list[tuple[Source, GuardCheckSpec, object, Guard]] = [] + for guard in all_relevant_guards: + source = guard.originating_source + type_str = guard.create_fn_name() + handler = GUARD_VALUE_DISPATCH.get(type_str) + + if handler is SKIP_GUARD: + continue + + if handler is None or isinstance(handler, UnsupportedGuardCheckSpec): + raise RuntimeError( + f"subgraph_reuse: unsupported guard type '{type_str}' on source '{source.name}'" + ) + + try: + value = tx.output.resolve_source_value(source) + except Exception: + raise RuntimeError( + f"subgraph_reuse: failed to resolve source '{source.name}' for {type_str} guard" + ) from None + + # TODO(anijain2305): vLLM workaround -- skip CONSTANT_MATCH on + # strings. Re-evaluate once vLLM migrates off this pattern. + # if type_str == "CONSTANT_MATCH" and isinstance(value, str): + # continue + + handler = cast(GuardCheckSpec, handler) + expected = handler.get_metadata_fn(guard, value) + guard_tuples.append((source, handler, expected, guard)) + + hc_log.debug("Number of guards %s", len(guard_tuples)) + + return InvokeSubgraphReuseCondition( + input_checks=input_checks, + guards=guard_tuples, + treespec=fingerprint.treespec, + traced_sources=traced_sources, + ) + + +def build_source_replacement( + old_arg_sources: list[Source | None], + new_arg_sources: list[Source | None], +) -> dict[Source, Source]: + """Map old arg sources to new arg sources for remapping captured variable sources.""" + return { + old: new + for old, new in zip(old_arg_sources, new_arg_sources) + if old is not None and new is not None and old != new + } + + +def is_reusable( + tx: "InstructionTranslatorBase", + condition: "InvokeSubgraphReuseCondition", + fingerprint: InputFingerprint, + cached_entry: InvokeSubgraphReuseEntry, +) -> bool: + """Check if a cached subgraph can be reused for the current call. + + Three-phase check: + (1) Verify that intermediates (tensor metadata, symnode types, constant + values) match the cached input_checks — these are lightweight + structural comparisons that don't require source resolution. + (2) Check for mutations on the remapped traced_sources — if any source + the subgraph read has been mutated since the original trace, the + cached guards would evaluate against stale values. + (3) Build a source replacement mapping (old sources → new sources) and + re-evaluate the snapshotted guards under the new sources. + """ + # Structural check: treespec must match first. + if condition.treespec is not None and fingerprint.treespec != condition.treespec: + hc_log.debug( + "subgraph_reuse: reuse failed -- treespec mismatch", + ) + return False + + # Input count, tags, and metadata must match. + # Tensor metadata (shape, stride, dtype, device, requires_grad) is checked + # here because TENSOR_MATCH guards for subgraph inputs typically already + # exist in the outer graph before tracing and thus won't appear in the + # guard delta. + if len(condition.input_checks) != len(fingerprint.flat_vts): + hc_log.debug( + "subgraph_reuse: reuse failed -- input count mismatch: cached %d vs current %d", + len(condition.input_checks), + len(fingerprint.flat_vts), + ) + return False + + for i, ((cached_tag, cached_val), (cur_tag, cur_vt)) in enumerate( + zip(condition.input_checks, fingerprint.flat_vts) + ): + if cached_tag != cur_tag: + hc_log.debug( + "subgraph_reuse: reuse failed -- input %d tag mismatch: cached '%s' vs current '%s'", + i, + cached_tag, + cur_tag, + ) + return False + if cached_tag == InputTag.TENSOR: + if not isinstance(cur_vt, TensorVariable): + raise AssertionError( + f"expected TensorVariable for TENSOR tag, got {type(cur_vt).__name__}" + ) + example = cur_vt.proxy.node.meta.get("example_value", None) + if example is None: + hc_log.debug( + "subgraph_reuse: reuse failed -- input %d tensor has no example_value", + i, + ) + return False + cur_meta = extract_tensor_metadata(example) + if cur_meta != cached_val: + hc_log.debug( + "subgraph_reuse: reuse failed -- input %d tensor metadata mismatch", + i, + ) + return False + elif cached_tag == InputTag.SYMNODE: + if not isinstance(cur_vt, SymNodeVariable): + raise AssertionError( + f"expected SymNodeVariable for SYMNODE tag, got {type(cur_vt).__name__}" + ) + if sym_num_key(cur_vt.sym_num) != cached_val: + hc_log.debug( + "subgraph_reuse: reuse failed -- input %d symnode mismatch: cached '%s' vs current '%s'", + i, + cached_val, + cur_vt.sym_num, + ) + return False + elif cached_tag == InputTag.CONSTANT: + if not is_constant_like(cur_vt): + raise AssertionError( + f"expected constant-like VT for CONSTANT tag, got {type(cur_vt).__name__}" + ) + cached_type, cached_value = cast(tuple[type, Any], cached_val) + if type(cur_vt.value) is not cached_type: + # Not deferred to the source check below: a value guard cannot + # catch a type change that alters the trace (isinstance, etc). + hc_log.debug( + "subgraph_reuse: reuse failed -- input %d constant type " + "mismatch: cached '%s' vs current '%s'", + i, + cached_type, + type(cur_vt.value), + ) + return False + if cur_vt.value != cached_value: + # If both the cached and current arg have sources, source + # replacement in stamp_out will resolve the correct value. + cached_src = ( + cached_entry.arg_sources[i] + if i < len(cached_entry.arg_sources) + else None + ) + new_src = ( + fingerprint.arg_sources[i] + if i < len(fingerprint.arg_sources) + else None + ) + if cached_src is None or new_src is None: + hc_log.debug( + "subgraph_reuse: reuse failed -- input %d constant mismatch " + "with no source to replace: cached '%s' vs current '%s'", + i, + cached_val, + cur_vt.value, + ) + return False + + source_replacement = build_source_replacement( + cached_entry.arg_sources, fingerprint.arg_sources + ) + + # Parameterized source - this function gives you new sources parameterized + # on the arg_sources. For example, if the input to the nested compile region + # is a nn Module layer with source `layers[0]`, then old source + # `layers[0].weight` gets remapped to `layers[1].weight`. This + # parameterization is central in getting the new sources and then running + # guards on them. + def replacement_fn(s: Source) -> Source: + return source_replacement.get(s, s) + + # Check for mutations on remapped traced_sources. + if source_replacement: + remapped = OrderedSet(s.clone(replacement_fn) for s in condition.traced_sources) + else: + remapped = condition.traced_sources + if has_mutated_vars(tx, remapped): + return False + + # If no sources changed, all guards were already checked during the + # original trace and will trivially pass again. + if not source_replacement: + return True + + # Shared resolution context so source.get_value memoizes intermediate + # results (e.g. common base sources) across all guards in this check. + resolve_globals: dict[str, Any] = { + "G": tx.output.root_tx.f_globals, + "L": tx.output.root_tx.f_locals, + } + resolve_locals: dict[str, Any] = {} + resolve_cache: dict[Source, Any] = {} + + for source, handler, expected, guard in condition.guards: + new_source = source.clone(replacement_fn) + # Source unchanged after replacement — guard already passed during + # the original trace, skip re-evaluation. + if new_source == source: + continue + + try: + value = new_source.get_value(resolve_globals, resolve_locals, resolve_cache) + except Exception: + hc_log.debug( + "subgraph_reuse: reuse failed -- cannot resolve source\n" + " guard type: %s\n" + " guard source: %s\n" + " guard source name: %s\n" + " user stack:\n%s", + guard.create_fn_name(), + new_source, + new_source.name, + "".join(guard.user_stack.format()) + if guard.user_stack + else "", + ) + return False + + if not handler.eval_fn(value, expected): + hc_log.debug( + "subgraph_reuse: reuse failed --\n" + " guard type: %s\n" + " guard source: %s\n" + " guard source name: %s\n" + " expected: %s\n" + " got: %s\n" + " user stack:\n%s", + guard.create_fn_name(), + new_source, + new_source.name, + expected, + value, + "".join(guard.user_stack.format()) + if guard.user_stack + else "", + ) + return False + + return True + + +def has_reuse_entries( + tx: "InstructionTranslatorBase", + fn_var: Any, +) -> bool: + """Cheap check: does the cache have any entries for this function?""" + from torch._guards import InvokeSubgraphCache + + invoke_subgraph_cache = tx.output.tracing_context.hop_dispatch_set_cache.get_cache( + torch._higher_order_ops.invoke_subgraph + ) + if not isinstance(invoke_subgraph_cache, InvokeSubgraphCache): + return False + fn_code = get_fn_code(fn_var) + return fn_code is not None and fn_code in invoke_subgraph_cache.subgraph_reuse_cache + + +def find_reuse_match( + tx: "InstructionTranslatorBase", + fn_var: Any, + fingerprint: InputFingerprint, +) -> InvokeSubgraphReuseEntry | None: + from torch._guards import InvokeSubgraphCache + + invoke_subgraph_cache = tx.output.tracing_context.hop_dispatch_set_cache.get_cache( + torch._higher_order_ops.invoke_subgraph + ) + if not isinstance(invoke_subgraph_cache, InvokeSubgraphCache): + return None + fn_code = get_fn_code(fn_var) + if fn_code is None: + return None + + # this evaluator function is called one by one for all the invoke subgraph + # reuse entries - the one that evaluates to True is stamped out in the + # graph. + def evaluator( + cond: "InvokeSubgraphReuseCondition", entry: InvokeSubgraphReuseEntry + ) -> bool: + return is_reusable(tx, cond, fingerprint, entry) + + return invoke_subgraph_cache.find_reuse_entry(fn_code, evaluator) + + +def save_reuse_entry( + tx: "InstructionTranslatorBase", + fn_var: Any, + fingerprint: InputFingerprint, + body_name: str, + body_gmod: torch.fx.GraphModule, + config: NestedCompileRegionOptions | None, + p_args: tuple[Any, ...], + body_r: VariableTracker, + example_value: Any, + max_reuse_entries: int = 8, + condition: "InvokeSubgraphReuseCondition | None" = None, + hash_key: int | None = None, +) -> None: + """Save a traced subgraph into the reuse cache for future cache hits. + + Builds an InvokeSubgraphReuseEntry with the freevar mapping (how each + lifted arg maps back to user inputs or captured variables), output + metadata, and arg sources. On a future cache hit, stamp_out_subgraph + uses this entry to emit a new invoke_subgraph call without re-tracing. + + Exactly one of ``condition`` or ``hash_key`` must be provided. + ``condition`` stores the entry in the guard-based cache (linear scan); + ``hash_key`` stores it in the hash-key cache (O(1) lookup). + """ + from torch._guards import InvokeSubgraphCache + + if not ((condition is None) != (hash_key is None)): + raise AssertionError("Exactly one of condition or hash_key must be provided") + + invoke_subgraph_cache = tx.output.tracing_context.hop_dispatch_set_cache.get_cache( + torch._higher_order_ops.invoke_subgraph + ) + if not isinstance(invoke_subgraph_cache, InvokeSubgraphCache): + return + + fn_code = get_fn_code(fn_var) + if fn_code is None: + return + + subgraph_input_mapping = build_subgraph_input_mapping( + tx, p_args, fingerprint.flat_vts + ) + single_tensor_output = isinstance(body_r, TensorVariable) + + # Count user-visible outputs from body_r. The graph may have additional + # outputs from side-effect intermediates that stamp_out_subgraph must + # not include when reconstructing the user-visible return value. + user_output_vts: list[VariableTracker] = [] + VariableTracker.visit( + lambda vt: user_output_vts.append(vt) + if vt.is_tensor() or isinstance(vt, SymNodeVariable) + else None, + body_r, + ) + num_user_outputs = len(user_output_vts) + + # Cache output tensor metadata so we can construct fresh FakeTensors on + # cache hit without re-running the subgraph. This is safe because + # invoke_subgraph does not support aliasing between inputs and outputs + # (speculate_subgraph will fail if that happens). + # example_value may contain SymInts (e.g. shape values for backward); + # only record metadata for actual tensors. + output_metadata = [ + (t.shape, t.stride(), t.dtype, t.device, t.requires_grad) + for t in example_value + if isinstance(t, torch.Tensor) + ] + + entry = InvokeSubgraphReuseEntry( + body_name=body_name, + body_gmod=body_gmod, + config=config, + subgraph_input_mapping=subgraph_input_mapping, + single_tensor_output=single_tensor_output, + output_metadata=output_metadata, + # Record arg sources so that on cache hit we can build a + # source replacement mapping (old sources → new sources) to + # rewrite captured variable sources for the current invocation. + arg_sources=fingerprint.arg_sources, + num_user_outputs=num_user_outputs, + ) + if condition is not None: + invoke_subgraph_cache.add_reuse_entry( + fn_code, condition, entry, max_reuse_entries + ) + else: + if hash_key is None: + raise AssertionError("hash_key must not be None when condition is None") + invoke_subgraph_cache.add_reuse_entry_by_key( + fn_code, hash_key, entry, max_reuse_entries + ) + + +def trace_reuse_hash_fn( + tx: "InstructionTranslatorBase", + reuse_hash_fn: Any, + fn_args_vt: "list[VariableTracker]", + kwargs: dict[str, VariableTracker], +) -> int: + """Trace the user's reuse_hash_fn to get a constant integer hash key. + + Guards installed during the hash function tracing are skipped — the hash + key itself is the reuse condition, not the guards. + """ + from torch._dynamo.exc import Unsupported + + with tx.output.tracing_context.guards_context.skip_guard_install(): + try: + result = _make_inlined(tx, reuse_hash_fn)(*fn_args_vt, **kwargs) + except Unsupported as e: + raise RuntimeError( + f"reuse_hash_fn must be fully traceable without graph breaks. Got: {e}" + ) from e + + if not isinstance(result, ConstantVariable) or not isinstance(result.value, int): + raise RuntimeError( + f"reuse_hash_fn must return a constant integer, got {result}" + ) + + return result.value + + +def find_reuse_entry_by_key( + tx: "InstructionTranslatorBase", + fn_var: Any, + hash_key: int, +) -> InvokeSubgraphReuseEntry | None: + from torch._guards import InvokeSubgraphCache + + invoke_subgraph_cache = tx.output.tracing_context.hop_dispatch_set_cache.get_cache( + torch._higher_order_ops.invoke_subgraph + ) + if not isinstance(invoke_subgraph_cache, InvokeSubgraphCache): + return None + fn_code = get_fn_code(fn_var) + if fn_code is None: + return None + return invoke_subgraph_cache.find_reuse_entry_by_key(fn_code, hash_key) + + +def stamp_out_subgraph( + tx: "InstructionTranslatorBase", + fingerprint: InputFingerprint, + cached: InvokeSubgraphReuseEntry, +) -> VariableTracker: + """Emit a new invoke_subgraph call by stamping out a cached subgraph. + + Sources in the cached entry are parameterized: they refer to the original + call's sources and must be rewritten to the current call's sources via + source replacement before we can look up or create the corresponding + graph placeholders. + """ + from torch._dynamo.variables.builder import VariableBuilder + from torch._dynamo.variables.higher_order_ops import add_call_function, make_attr + + flat_proxies = get_flat_proxies(fingerprint) + new_arg_sources = fingerprint.arg_sources + + source_replacement = build_source_replacement(cached.arg_sources, new_arg_sources) + + new_lifted_args = [] + # Shared resolution context so get_value memoizes intermediate results + # (e.g. L['self'].layers) across all freevars in this stamp-out. + resolve_globals: dict[str, Any] = { + "G": tx.output.root_tx.f_globals, + "L": tx.output.root_tx.f_locals, + } + resolve_locals: dict[str, Any] = {} + resolve_cache: dict[Source, Any] = {} + + # Find the args for the about-to-be-inserted invoke_subgraph call. + for subgraph_input in cached.subgraph_input_mapping: + if isinstance(subgraph_input, LiftedUserArg): + new_lifted_args.append(flat_proxies[subgraph_input.index]) + elif isinstance(subgraph_input, LiftedBoundSymbol): + from torch._dynamo.output_graph import LazyProxy + + proxy = tx.output.current_tracer.bound_symbols[subgraph_input.expr] + if isinstance(proxy, LazyProxy): + proxy = proxy() + tx.output.current_tracer.bound_symbols[subgraph_input.expr] = proxy + new_lifted_args.append(proxy) + elif isinstance(subgraph_input, LiftedSyntheticObject): + ctor_args = subgraph_input.ctor_args + ctor_arg_sources = subgraph_input.ctor_arg_sources + if ctor_arg_sources and source_replacement: + new_ctor_args = [] + new_ctor_arg_sources = [] + for val, arg_src in zip(ctor_args, ctor_arg_sources): + if arg_src is not None: + new_src = arg_src.clone(lambda s: source_replacement.get(s, s)) + val = new_src.get_value( + resolve_globals, resolve_locals, resolve_cache + ) + arg_src = new_src + new_ctor_args.append(val) + new_ctor_arg_sources.append(arg_src) + ctor_args = tuple(new_ctor_args) + ctor_arg_sources = tuple(new_ctor_arg_sources) + vt = tx.output.synthetic_graph_input( + subgraph_input.ctor_fn, ctor_args, ctor_arg_sources + ) + new_lifted_args.append(vt.as_proxy()) + elif isinstance(subgraph_input, LiftedCapturedSource): + new_source = subgraph_input.source + if source_replacement: + new_source = new_source.clone(lambda s: source_replacement.get(s, s)) + # VariableBuilder deduplicates via input_source_to_var, + # so this reuses existing graph placeholders automatically. + value = new_source.get_value(resolve_globals, resolve_locals, resolve_cache) + vt = VariableBuilder(tx, new_source)(value) + new_lifted_args.append(vt.as_proxy()) + + # Generate fake tensor outputs + if tx.fake_mode is None: + raise AssertionError("tx.fake_mode must not be None for stamp_out_subgraph") + with tx.fake_mode: + example_value = tuple( + torch.empty_strided( + shape, + stride, + dtype=dtype, + device=device, + requires_grad=req_grad, + ) + for shape, stride, dtype, device, req_grad in cached.output_metadata + ) + + # Install the invoke_subgraph call + body_node = make_attr(tx, cached.body_name) + p_args = (body_node, cached.body_name, *new_lifted_args) + flat_variable = add_call_function( + tx, + torch._higher_order_ops.invoke_subgraph, + tuple(p_args), + {}, + example_value, + cached.config, + ) + + # Return only the user-visible outputs. The graph may have extra + # intermediate outputs from side effects (allow_side_effects=True) + # that should not be part of the user-facing return value. + if cached.single_tensor_output: + items = flat_variable.items # pyrefly: ignore[missing-attribute] + if not isinstance(items[0], TensorVariable): + raise AssertionError( + f"Expected tensor output but got {type(items[0]).__name__}" + ) + return items[0] + + items = flat_variable.items # pyrefly: ignore[missing-attribute] + n = cached.num_user_outputs + if n > 0 and n < len(items): + from .builder import SourcelessBuilder + + return SourcelessBuilder.create(tx, tuple(items[:n])) + return flat_variable + + +def build_subgraph_input_mapping( + tx: "InstructionTranslatorBase", + p_args: tuple[Any, ...], + flat_vts: list[tuple[InputTag, VariableTracker]], +) -> list[LiftedArgOrigin]: + """Build a mapping that records the origin of each lifted arg for a subgraph. + + On a cache hit, we stamp out a new invoke_subgraph call and need to + reconstruct its argument list in the correct order. Each lifted arg + (p_args[2:], skipping body_node and body_name) comes from one of: + + - LiftedUserArg: a user argument (intermediate activation or explicit input) + - LiftedCapturedSource: a captured variable (e.g. a weight or parameter) + - LiftedSyntheticObject: a TorchScriptObject with a SyntheticLocalSource + - LiftedBoundSymbol: a SymInt already bound as a graph input + """ + proxy_node_to_idx: dict[torch.fx.Node, int] = {} + idx = 0 + for tag, vt in flat_vts: + if tag in (InputTag.TENSOR, InputTag.SYMNODE): + node = vt.as_proxy().node + if node not in proxy_node_to_idx: + proxy_node_to_idx[node] = idx + idx += 1 + + subgraph_input_mapping: list[LiftedArgOrigin] = [] + for outer_proxy in p_args[2:]: + matched_idx = proxy_node_to_idx.get(outer_proxy.node, -1) + if matched_idx >= 0: + subgraph_input_mapping.append(LiftedUserArg(matched_idx)) + else: + grapharg = outer_proxy.node.meta.get("grapharg", None) + source = grapharg.source if grapharg is not None else None + # SymInt freevars must reuse the existing symbolic proxy rather + # than resolving via source.get_value() (which returns the + # concrete int). They appear as either: + # - placeholder nodes with grapharg.example being a SymInt + # - call_function nodes (e.g. sym_size_int) with no grapharg + # In both cases, store the sympy expression and look it up in + # bound_symbols during stamp-out. + example = ( + grapharg.example + if grapharg is not None + else outer_proxy.node.meta.get("example_value", None) + ) + if isinstance(example, torch.SymInt): + # _expr rather than expr: expr applies the ShapeEnv's + # replacements, so a symbol the region lifted before it was + # specialized comes back as a constant, which bound_symbols has + # no entry for. + subgraph_input_mapping.append(LiftedBoundSymbol(example.node._expr)) + continue + if source is None: + raise AssertionError( + f"Freevar has no source: node.op={outer_proxy.node.op} " + f"node.name={outer_proxy.node.name} -- this likely means a " + f"function argument was not included in the proxy matching" + ) + if isinstance(source, SyntheticLocalSource): + ctor_info = tx.output.synthetic_source_ctor_info.get(source) + if ctor_info is not None: + ctor_fn, ctor_args, ctor_arg_sources = ctor_info + subgraph_input_mapping.append( + LiftedSyntheticObject(ctor_fn, ctor_args, ctor_arg_sources) + ) + continue + subgraph_input_mapping.append(LiftedCapturedSource(source)) + return subgraph_input_mapping + + +class InvokeSubgraphHigherOrderVariable(WrapHigherOrderVariable): + _HOP_NAME = "torch.ops.higher_order.invoke_subgraph" + _ALLOW_FALLBACK_TO_EAGER = False + supports_input_mutation = True + supports_aliasing = False + allow_side_effects = True + # invoke_subgraph is NOT desugared in AOTAutograd, so the HOP input/output + # shouldn't alias. For checkpoint HOP, we inline it so we don't need + # alias analysis as functionalization would just work on the flat graph. + filter_aliased_intermediates = True + + # pyrefly: ignore[bad-override] + def install_subgraph_in_output_graph( + self, + tx: "InstructionTranslatorBase", + fn_vt: VariableTracker, + fn_args_vt: "list[VariableTracker]", + kwargs: dict[str, VariableTracker], + body_gmod: GraphModule, + attr_name: str, + ) -> str: + # Check if the subgraph from speculate_subgraph (body_gmod) and the fake + # inputs have already been seen before. If yes, the subgraph is already + # installed in the output graph and we can just access the subgraph + # using the saved attr name. + + if not isinstance(fn_vt, (UnspecializedNNModuleVariable, UserFunctionVariable)): + unimplemented( + gb_type="Encountered non user function variable during invoke_subgraph HOP tracing", + context=str(fn_vt), + explanation="invoke_subgraph does not support non user function variable", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + invoke_subgraph_cache = ( + tx.output.tracing_context.hop_dispatch_set_cache.get_cache( + torch._higher_order_ops.invoke_subgraph + ) + ) + + if isinstance(fn_vt, UserFunctionVariable): + fn_code = fn_vt.get_function().__code__ + fn_name = fn_vt.get_function().__name__ + else: + if not isinstance(fn_vt, UnspecializedNNModuleVariable): + raise AssertionError( + f"expected UnspecializedNNModuleVariable, got {type(fn_vt).__name__}" + ) + fn_code = fn_vt.value.forward.__func__.__code__ # type: ignore[attr-defined] + fn_name = fn_vt.value.forward.__name__ # type: ignore[attr-defined] + # pyrefly: ignore [implicit-any] + previously_installed_submodules = [] + if invoke_subgraph_cache: + previously_installed_submodules = ( + invoke_subgraph_cache.get_dynamo_installed_submodules(fn_code) + ) + current_mod = body_gmod + # NB - reverse is more likely to cause a hit sooner because first + # graph can have requires_grad=False for a few inputs + for submodule_name in reversed(previously_installed_submodules): + if submodule_name not in tx.output.nn_modules: + raise AssertionError( + f"submodule '{submodule_name}' not found in nn_modules" + ) + previous_mod = tx.output.nn_modules[submodule_name] + if not tx.fake_mode: + raise AssertionError( + "tx.fake_mode must be set for subgraph comparison" + ) + from torch._dynamo.variables.higher_order_ops import ( + are_same_graph_modules, + ) + + if are_same_graph_modules( + fn_name, previous_mod, current_mod, tx.fake_mode + ): + return submodule_name + + body_name = super().install_subgraph_in_output_graph( + tx, fn_vt, fn_args_vt, kwargs, body_gmod, "subgraph" + ) + hc_log.debug( + "%s: Installing subgraph with identifier '%s', bringing total count for '%s' function to %s", + fn_name, + body_name, + fn_name, + len(previously_installed_submodules) + 1, + ) + if invoke_subgraph_cache: + invoke_subgraph_cache.add_dynamo_installed_submodule(fn_code, body_name) + + return body_name + + def _call_function( + self, + tx: "InstructionTranslatorBase", + args: "list[VariableTracker]", + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from torch._dynamo.utils import dynamo_timed + from torch._dynamo.variables.higher_order_ops import ( + _call_function_with_auto_output_flattening, + ) + + fn_var = args[0] + fn_args_vt = args[1:] + + config = None + max_reuse_entries = 8 + reuse_hash_fn = None + if hasattr(fn_var, "get_function"): + try: + fn = fn_var.get_function() + config = getattr(fn, "__marked_compile_region_config__", None) + max_reuse_entries = getattr( + fn, "__marked_compile_region_max_reuse_entries__", 8 + ) + reuse_hash_fn = getattr( + fn, "__marked_compile_region_reuse_hash_fn__", None + ) + except Exception: + log.warning( + "Failed to extract nested_compile_region() config from InvokeSubgraphHigherOrderVariable. ", + exc_info=True, + ) + raise + + # TODO (anijain2305) - Collect issues why this does not work for export, + # and enable if request arises. + reuse = not tx.output.export + + # User-provided reuse_hash_fn path: hash key determines cache lookup. + if reuse and reuse_hash_fn is not None: + with dynamo_timed("invoke_subgraph_reuse_hash_fn"): + hash_key = trace_reuse_hash_fn(tx, reuse_hash_fn, fn_args_vt, kwargs) + + cached = find_reuse_entry_by_key(tx, fn_var, hash_key) + if cached is not None: + hc_log.debug( + "subgraph_reuse: hash key %d hit for '%s', reusing subgraph '%s'", + hash_key, + fn_var, + cached.body_name, + ) + fingerprint = build_input_fingerprint(tx, fn_args_vt, kwargs) + with dynamo_timed("invoke_subgraph_reuse_stamp_out"): + return stamp_out_subgraph(tx, fingerprint, cached) + + # Automatic reuse lookup (guard-based): check fn_code first (cheap) to + # avoid the expensive pytree flatten in build_input_fingerprint on + # the first call when there's nothing in the cache yet. + elif reuse and has_reuse_entries(tx, fn_var): + with dynamo_timed("invoke_subgraph_reuse_lookup"): + fingerprint = build_input_fingerprint(tx, fn_args_vt, kwargs) + match = find_reuse_match( + tx, + fn_var, + fingerprint, + ) + if match is not None: + hc_log.debug( + "subgraph_reuse: cache hit for '%s', reusing subgraph '%s'", + fn_var, + match.body_name, + ) + with dynamo_timed("invoke_subgraph_reuse_stamp_out"): + return stamp_out_subgraph(tx, fingerprint, match) + + if self._HOP_NAME is None: + raise AssertionError("_HOP_NAME must not be None") + with dynamo_timed("invoke_subgraph_trace"): + ( + p_args, + p_kwargs, + example_value, + body_r, + body_gmod, + body_name, + body_graph_output_vts, + tracing_info, + ) = self.create_wrapped_node(tx, fn_var, fn_args_vt, kwargs, self._HOP_NAME) + + if len(p_kwargs) > 0: + unimplemented( + gb_type="invoke_subgraph: kwargs unexpected", + context=f"args: {args}, kwargs: {kwargs}", + explanation="kwargs should have been flattened into lifted args.", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + + # Store config in the body graph module meta + if isinstance(config, NestedCompileRegionOptions): + body_gmod.meta["nested_region_config"] = config + + p_args = ( + p_args[0], + body_name, + *p_args[1:], + ) + + # Subgraph reuse: save entry for future cache hits + if reuse: + fingerprint = build_input_fingerprint(tx, fn_args_vt, kwargs) + if reuse_hash_fn is not None: + traced_sources = tracing_info.traced_sources + if not is_reuse_eligible( + tx, + body_r, + fingerprint, + tracing_info, + traced_sources, + has_reuse_hash_fn=True, + ): + raise RuntimeError( + "reuse_hash_fn was provided but the subgraph is not " + "eligible for reuse. Check the logs with " + "TORCH_LOGS='+hierarchical_compile' for details." + ) + save_reuse_entry( + tx, + fn_var, + fingerprint, + body_name, + body_gmod, + config, + p_args, + body_r, + example_value, + max_reuse_entries, + hash_key=hash_key, # type: ignore[possibly-undefined] + ) + else: + traced_sources = tracing_info.traced_sources + if is_reuse_eligible( + tx, body_r, fingerprint, tracing_info, traced_sources + ): + condition = build_reuse_condition( + tx, + fingerprint, + traced_sources, + ) + if condition is not None: + save_reuse_entry( + tx, + fn_var, + fingerprint, + body_name, + body_gmod, + config, + p_args, + body_r, + example_value, + max_reuse_entries, + condition=condition, + ) + + return _call_function_with_auto_output_flattening( # type: ignore[return-value] + tx, + torch._higher_order_ops.invoke_subgraph, + tuple(p_args), + p_kwargs, + example_value, + body_r, + body_graph_output_vts, + config=config, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/iter.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/iter.py new file mode 100644 index 0000000000000000000000000000000000000000..a485cac42807b254b1a10649174e36a25d8eb0f1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/iter.py @@ -0,0 +1,969 @@ +""" +This module provides iterator-related variable tracking functionality for Dynamo. +It implements variable classes for handling Python iterators and itertools functions +during symbolic execution and tracing. + +The module includes: +- Base iterator variable classes for tracking iterator state +- Implementations of built-in iterators (zip, map, filter) +- Support for itertools functions (product, groupby, count, etc.) +- Mutation tracking and reconstruction capabilities for iterator operations + +These classes integrate with Dynamo's variable tracking system to enable proper +handling of iterator operations during code transformation and optimization. +""" + +import inspect +import itertools +import operator +import sys +from typing import Any, TYPE_CHECKING + +from .. import graph_break_hints, polyfills, variables +from ..bytecode_transformation import ( + create_call_function, + create_call_function_ex, + create_instruction, +) +from ..exc import ( + handle_observed_exception, + ObservedUserStopIteration, + raise_observed_exception, + raise_type_error, + raise_value_error, + unimplemented, +) +from ..utils import raise_args_mismatch, tracked_repr, unpack_iterable +from .base import GetSet, Method, ValueMutationNew, VariableTracker +from .constant import ConstantVariable +from .hashable import HashableTracker +from .object_protocol import generic_getiter, pyiter_next + + +# chain.from_iterable is a method descriptor that creates a new object on each +# attribute access (a is b → False). Capture once at import time for stable +# identity comparisons in ItertoolsVariable.call_function. +_CHAIN_FROM_ITERABLE = itertools.chain.from_iterable + +# repeat(object, times=-1); itertools.repeat has no introspectable signature, so +# declare one to bind args/kwargs. `times` defaults to None to mark the unbounded +# form (CPython's cnt == -1). +_REPEAT_SIGNATURE = inspect.Signature( + [ + inspect.Parameter("object", inspect.Parameter.POSITIONAL_OR_KEYWORD), + inspect.Parameter( + "times", inspect.Parameter.POSITIONAL_OR_KEYWORD, default=None + ), + ] +) + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + +MAX_ITERATOR_LIMIT = 100 * 1024 # 100k + + +def is_iterator_exhausted( + tx: "InstructionTranslatorBase", iterator: VariableTracker +) -> bool: + try: + pyiter_next(tx, iterator) + return False + except ObservedUserStopIteration: + handle_observed_exception(tx) + return True + + +class ItertoolsVariable(VariableTracker): + def __init__(self, value: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + from .object_protocol import python_constant_richcompare_impl + + return python_constant_richcompare_impl(self, tx, other, op) + + def __repr__(self) -> str: + return f"ItertoolsVariable({self.value})" + + def as_python_constant(self) -> Any: + return self.value + + def get_real_python_backed_value(self) -> Any: + return self.value + + def _get_from_iterable( + self, tx: "InstructionTranslatorBase" + ) -> "VariableTracker | None": + # Only itertools.chain has from_iterable; declining (None) falls + # through to the generic protocol for other itertools callables. + if self.value is itertools.chain: + return ItertoolsVariable(_CHAIN_FROM_ITERABLE) + return None + + tp_getset = { + "from_iterable": GetSet(_get_from_iterable), + } + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list["VariableTracker"], + kwargs: "dict[str, VariableTracker]", + ) -> "VariableTracker": + # See also: module `torch._dynamo.polyfills.itertools` + + if self.value is itertools.chain and not kwargs: + # Wrap args in a ListIteratorVariable so sub-iterables are pulled lazily. + # generic_getiter on each sub-iterable is deferred to tp_iternext_impl, + # matching CPython's behavior (iter() on each arg is lazy, not at construction). + source = variables.ListIteratorVariable( + list(args), mutation_type=ValueMutationNew() + ) + return ChainVariable(source, mutation_type=ValueMutationNew()) + elif self.value is _CHAIN_FROM_ITERABLE and not kwargs and len(args) == 1: + # Convert outer iterable to iterator; each sub-iterable converted lazily. + source = generic_getiter(tx, args[0]) + return ChainVariable(source, mutation_type=ValueMutationNew()) + elif self.value is itertools.zip_longest: + fillvalue_vt = kwargs.pop("fillvalue", ConstantVariable.create(None)) + if kwargs: + unimplemented( + gb_type="Unsupported kwargs for itertools.zip_longest", + context=f"call_function {self} {args} {kwargs}", + explanation=f"Expected kwargs: 'fillvalue', but got " + f"{','.join(set(kwargs.keys()) - {'fillvalue'})}", + hints=[*graph_break_hints.USER_ERROR], + ) + iterables = [generic_getiter(tx, arg) for arg in args] + return ZipLongestVariable( + iterables, + fillvalue=fillvalue_vt, + mutation_type=ValueMutationNew(), + ) + elif self.value is itertools.product: + if any(kw != "repeat" for kw in kwargs): + unimplemented( + gb_type="Unsupported kwargs for itertools.product", + context=f"call_function {self} {args} {kwargs}", + explanation=f"Expected kwargs: 'repeat', but got " + f"{','.join(set(kwargs.keys()) - {'repeat'})}", + hints=[*graph_break_hints.USER_ERROR], + ) + + if "repeat" in kwargs: + r = kwargs["repeat"].as_python_constant() + else: + r = 1 + seqs = [unpack_iterable(tx, arg) for arg in args] + items = [ + variables.TupleVariable(list(item)) + for item in itertools.product(*seqs, repeat=r) + ] + return variables.ListIteratorVariable( + items, # type: ignore[arg-type] + mutation_type=ValueMutationNew(), + ) + elif self.value is itertools.groupby: + if any(kw != "key" for kw in kwargs): + unimplemented( + gb_type="Unsupported kwargs for itertools.groupby", + context=f"call_function {self} {args} {kwargs}", + explanation=f"Expected kwargs: 'key', but got " + f"{','.join(set(kwargs.keys()) - {'key'})}", + hints=[*graph_break_hints.USER_ERROR], + ) + + def retrieve_const_key(key: VariableTracker) -> Any: + from ..utils import specialize_symnode + + # Unwrap LazyVariableTracker to get the underlying variable + key = specialize_symnode(key) + if isinstance(key, variables.SymNodeVariable): + return key.evaluate_expr() + elif key.is_python_constant(): + return key.as_python_constant() + else: + unimplemented( + gb_type="Unsupported key type for itertools.groupby", + context=f"call_function {self} {args} {kwargs}", + explanation="Dynamo does not know how to trace " + f"itertools.groupby with key type: {str(type(key))}. " + "We only support grouping keys that are constants (int, float, str, etc.)", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + if len(args) != 1: + unimplemented( + gb_type="Unsupported arguments for itertools.groupby", + context=f"call_function {self} {args} {kwargs}", + explanation="Dynamo does not know how to trace " + f"itertools.groupby with args: {args} and kwargs: {kwargs}. " + "itertools.groupby expects an iterable to group and an " + "optional key function to determine groupings.", + hints=[ + "Make sure the arguments to itertools.groupby are correct.", + *graph_break_hints.SUPPORTABLE, + ], + ) + seq = unpack_iterable(tx, args[0]) + + if "key" in kwargs: + + def keyfunc(x: VariableTracker) -> Any: + return retrieve_const_key( + kwargs.get("key").call_function(tx, [x], {}) # type: ignore[union-attr] + ) + + else: + + def keyfunc(x: VariableTracker) -> Any: + return retrieve_const_key(x) + + result = [] + try: + for k, v in itertools.groupby(seq, key=keyfunc): + result.append( + variables.TupleVariable( + [ + ( + variables.ConstantVariable.create(k) + if variables.ConstantVariable.is_literal(k) + else k + ), + variables.ListIteratorVariable( + list(v), mutation_type=ValueMutationNew() + ), + ], + mutation_type=ValueMutationNew(), + ) + ) + except Exception as e: + unimplemented( + gb_type="Unexpected failure during itertools.groupby() iteration", + context=f"call_function {self} {args} {kwargs}", + explanation="Unexpected failure in invoking function during groupby", + hints=[*graph_break_hints.SUPPORTABLE], + from_exc=e, + ) + return variables.ListIteratorVariable( + result, # type: ignore[arg-type] + mutation_type=ValueMutationNew(), + ) + elif self.value is itertools.repeat: + # ref: repeat_new in itertoolsmodule.c. A user-supplied negative + # `times` is clamped to 0; an absent `times` means unbounded. + try: + bound = _REPEAT_SIGNATURE.bind(*args, **kwargs) + except TypeError: + raise_args_mismatch(tx, "repeat") + item = bound.arguments["object"] + times = bound.arguments.get("times") + if times is None: + return RepeatIteratorVariable(item, mutation_type=ValueMutationNew()) + if not times.is_python_constant(): + return tx.inline_user_function_return( + VariableTracker.build(tx, polyfills.repeat), + [item, times], + {}, + ) + times_val = times.as_python_constant() + if not isinstance(times_val, int): + raise_type_error( + tx, + f"'{times.python_type_name()}' object cannot be interpreted " + "as an integer", + ) + return RepeatIteratorVariable( + item, times=max(times_val, 0), mutation_type=ValueMutationNew() + ) + elif self.value is itertools.count: + # count(start=0, step=1): let Python's own argument binding validate + # the call. Anything it rejects (extra args, duplicate/unknown + # kwargs) falls through to a graph break so eager raises the + # CPython TypeError. + def count_sig(start: Any = 0, step: Any = 1) -> tuple[Any, Any]: + return start, step + + try: + item, step = count_sig(*args, **kwargs) + except TypeError: + return super().call_function(tx, args, kwargs) + return variables.CountIteratorVariable( + item, step, mutation_type=ValueMutationNew() + ) + else: + return super().call_function(tx, args, kwargs) + + +class IteratorVariable(VariableTracker): + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + unimplemented( + gb_type="Unimplemented next() call", + context=f"next({self})", + explanation="This abstract method must be implemented", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> "ConstantVariable": + if name == "__iter__" or name == "__next__": + return variables.ConstantVariable.create(True) + return super().call_obj_hasattr(tx, name) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + """Iterators are their own iterator.""" + return self + + +class ChainVariable(IteratorVariable): + """ + Represents itertools.chain(*iterables) — yields one item per tp_iternext_impl call. + + Uses a source_iterator that yields raw sub-iterables (not yet converted to + iterators). Conversion happens lazily in tp_iternext_impl so that non-iterable + args raise TypeError at iteration time, matching CPython's behavior. + """ + + # ref: https://github.com/python/cpython/blob/3.13/Modules/itertoolsmodule.c#L225-L310 + _cpython_type = itertools.chain + + def __init__( + self, + source_iterator: "VariableTracker", + current: "VariableTracker | None" = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + # source_iterator yields raw sub-iterables; converted lazily per tp_iternext_impl + self.source_iterator = source_iterator + # current sub-iterator (None = not started or just exhausted a sub-iterable) + self.current = current + + def python_type(self) -> type: + return itertools.chain + + def _get_from_iterable(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + return ItertoolsVariable(_CHAIN_FROM_ITERABLE) + + tp_getset = { + "from_iterable": GetSet(_get_from_iterable), + } + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + if not self.is_mutable(): + raise AssertionError("ChainVariable must be mutable for next()") + while True: + if self.current is None: + # Pull next sub-iterable from source (source is always an iterator) + try: + next_raw = pyiter_next(tx, self.source_iterator) + except ObservedUserStopIteration: + handle_observed_exception(tx) + raise_observed_exception(StopIteration, tx) + # Convert sub-iterable to iterator lazily — may raise TypeError + it = generic_getiter(tx, next_raw) + tx.output.side_effects.mutation(self) + self.current = it + try: + return pyiter_next(tx, self.current) + except ObservedUserStopIteration: + handle_observed_exception(tx) + tx.output.side_effects.mutation(self) + self.current = None + + def reconstruct(self, codegen: "PyCodegen") -> None: + # Reconstruct as itertools.chain(current, itertools.chain.from_iterable(source)) + codegen.add_push_null( + lambda: codegen.extend_output( + [ + codegen.create_load_python_module(itertools), + codegen.create_load_attr("chain"), + ] + ) + ) + if self.current is not None: + codegen(self.current) + # chain.from_iterable(source_iterator) for remaining sub-iterables + codegen.add_push_null( + lambda: codegen.extend_output( + [ + codegen.create_load_python_module(itertools), + codegen.create_load_attr("chain"), + codegen.create_load_attr("from_iterable"), + ] + ) + ) + codegen(self.source_iterator) + codegen.extend_output(create_call_function(1, False)) + n_args = (1 if self.current is not None else 0) + 1 + codegen.extend_output(create_call_function(n_args, False)) + + +class RepeatIteratorVariable(IteratorVariable): + # ref: https://github.com/python/cpython/blob/3.13/Modules/itertoolsmodule.c + # repeat carries a `cnt` count: -1 means unbounded; CPython's repeat_new + # clamps a user-supplied negative `times` to 0. We model that with `times` + # (None == unbounded) and a `remaining` counter consumed by next(). + _nonvar_fields = { + "times", + "remaining", + *IteratorVariable._nonvar_fields, + } + + def __init__( + self, + item: VariableTracker, + times: int | None = None, + remaining: int | None = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.item = item + self.times = times + self.remaining = times if remaining is None else remaining + + def python_type(self) -> type: + return itertools.repeat + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Modules/itertoolsmodule.c repeat_next + if self.remaining is None: + return self.item + if not self.is_mutable(): + raise AssertionError("bounded RepeatIteratorVariable must be mutable") + if self.remaining == 0: + raise_observed_exception(StopIteration, tx) + tx.output.side_effects.mutation(self) + self.remaining -= 1 + return self.item + + def repeat_length_hint( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # ref: repeat_len in itertoolsmodule.c (exposed as __length_hint__); + # raises TypeError for the unbounded form ("len() of unsized object"). + # Not a C-level slot, so it lives in tp_methods rather than call_method. + if self.times is None: + raise_type_error(tx, "len() of unsized object") + return ConstantVariable.create(self.remaining) + + tp_methods = { + "__length_hint__": Method(repeat_length_hint), + } + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + item_repr = tracked_repr(tx, self.item) + if self.times is None: + return ConstantVariable.create(f"repeat({item_repr})") + return ConstantVariable.create(f"repeat({item_repr}, {self.remaining})") + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.extend_output( + [ + codegen.create_load_python_module(itertools), + codegen.create_load_attr("repeat"), + ] + ) + ) + codegen(self.item) + if self.times is None: + codegen.extend_output(create_call_function(1, False)) + else: + codegen(ConstantVariable.create(self.remaining)) + codegen.extend_output(create_call_function(2, False)) + + +class CountIteratorVariable(IteratorVariable): + # advance_count tracks how many next() calls were made during tracing, + # used by side_effects.py to replay them on the real iterator post-execution. + _nonvar_fields = { + "advance_count", + *IteratorVariable._nonvar_fields, + } + + def python_type(self) -> type: + return itertools.count + + def __init__( + self, + item: int | VariableTracker = 0, + step: int | VariableTracker = 1, + advance_count: int = 0, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if not isinstance(item, VariableTracker): + item = ConstantVariable.create(item) + if not isinstance(step, VariableTracker): + step = ConstantVariable.create(step) + self.item = item + self.step = step + self.advance_count = advance_count + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Modules/itertoolsmodule.c#L4189-L4216 + if not self.is_mutable(): + raise AssertionError("CountIteratorVariable must be mutable for next()") + old_item = self.item + tx.output.side_effects.mutation(self) + self.item = self.item.call_method(tx, "__add__", [self.step], {}) + self.advance_count += 1 + return old_item + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Modules/itertoolsmodule.c#L4218-L4243 + if not (self.item.is_python_constant() and self.step.is_python_constant()): + return super().tp_repr_impl(tx) + cnt = self.item.as_python_constant() + step = self.step.as_python_constant() + # Suppress step in the repr when it is an integer equal to 1. + if isinstance(step, int) and step == 1: + result = f"count({cnt!r})" + else: + result = f"count({cnt!r}, {step!r})" + return ConstantVariable.create(result) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.extend_output( + [ + codegen.create_load_python_module(itertools), + codegen.create_load_attr("count"), + ] + ) + ) + codegen(self.item) + codegen(self.step) + codegen.extend_output(create_call_function(2, False)) + + +class ZipVariable(IteratorVariable): + """ + Represents zip(*iterables) + """ + + # PyZip_Type: https://github.com/python/cpython/blob/v3.13.0/Python/bltinmodule.c#L3011 + _cpython_type = zip + + _nonvar_fields = { + "strict", + *IteratorVariable._nonvar_fields, + } + + def __init__( + self, + iterable: VariableTracker, + strict: bool = False, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if not isinstance(iterable, variables.TupleVariable): + raise AssertionError(f"Expected a tuple of iterables, got {type(iterable)}") + # can be list[Variable] or VariableTracker (with next_variable implemented) + self.iterable = iterable + self.strict = strict + + def python_type(self) -> type[zip]: # type: ignore[type-arg] + return zip + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.3/Python/bltinmodule.c#L2906-L2994 + if not self.is_mutable(): + raise AssertionError("ZipVariable must be mutable for next()") + tuplesize = len(self.iterable.items) + + if tuplesize == 0: + raise_observed_exception(StopIteration, tx) + + items = [] + for i in range(tuplesize): + it = self.iterable.items[i] + try: + items.append(pyiter_next(tx, it)) + except ObservedUserStopIteration: + if not self.strict: + raise + + if i > 0: + raise_value_error( + tx, f"zip() argument {i} shorter than previous arguments" + ) + + # In strict mode, if any iterable is exhausted, all must be exhausted + for j in range(i + 1, tuplesize): + it_j = self.iterable.items[j] + if is_iterator_exhausted(tx, it_j): + continue + break + else: + # all iterables exhausted, raise StopIteration + raise + + handle_observed_exception(tx) # StopIteration + raise_value_error( + tx, f"zip() argument {i} is longer than previous arguments" + ) + + return variables.TupleVariable(items) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from("builtins", "zip"), call_function_ex=True + ) + codegen(self.iterable) + codegen.extend_output( + [ + codegen.create_load_const("strict"), + codegen.create_load_const(self.strict), + create_instruction("BUILD_MAP", arg=1), + *create_call_function_ex(True, False), + ] + ) + + +class ZipLongestVariable(IteratorVariable): + """ + Represents itertools.zip_longest(*iterables, fillvalue=None) + """ + + # ref: https://github.com/python/cpython/blob/3.13/Modules/itertoolsmodule.c#L2822-L2887 + _cpython_type = itertools.zip_longest + + _nonvar_fields = { + "exhausted", + *IteratorVariable._nonvar_fields, + } + + def __init__( + self, + iterables: "list[VariableTracker]", + fillvalue: "VariableTracker", + exhausted: "list[bool] | None" = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.iterables = iterables + self.fillvalue = fillvalue + self.exhausted = ( + exhausted if exhausted is not None else [False] * len(iterables) + ) + + def python_type(self) -> type: + return itertools.zip_longest + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + # ref: https://github.com/python/cpython/blob/3.13/Modules/itertoolsmodule.c#L2737-L2808 + if not self.is_mutable(): + raise AssertionError("ZipLongestVariable must be mutable for next()") + if all(self.exhausted): + raise_observed_exception(StopIteration, tx) + values = [] + # CPython: when the last active iterator exhausts, return without yielding. + any_active = False + for i, it in enumerate(self.iterables): + if self.exhausted[i]: + values.append(self.fillvalue) + else: + try: + values.append(pyiter_next(tx, it)) + any_active = True + except ObservedUserStopIteration: + handle_observed_exception(tx) + tx.output.side_effects.mutation(self) + self.exhausted[i] = True + values.append(self.fillvalue) + if not any_active: + raise_observed_exception(StopIteration, tx) + return variables.TupleVariable(values) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.extend_output( + [ + codegen.create_load_python_module(itertools), + codegen.create_load_attr("zip_longest"), + ] + ), + call_function_ex=True, + ) + for i, it in enumerate(self.iterables): + if not self.exhausted[i]: + codegen(it) + else: + codegen.add_push_null( + lambda: codegen.append_output( + codegen.create_load_python_module(iter) # type: ignore[arg-type] + ) + ) + codegen.extend_output( + [ + create_instruction("BUILD_TUPLE", arg=0), + *create_call_function(1, False), + ] + ) + codegen.extend_output( + [create_instruction("BUILD_TUPLE", arg=len(self.iterables))] + ) + codegen.extend_output([codegen.create_load_const("fillvalue")]) + codegen(self.fillvalue) + codegen.extend_output( + [ + create_instruction("BUILD_MAP", arg=1), + *create_call_function_ex(True, False), + ] + ) + + +class MapVariable(IteratorVariable): + """ + Represents map(fn, *iterables) + """ + + # PyMap_Type: https://github.com/python/cpython/blob/v3.13.0/Python/bltinmodule.c#L1484 + _cpython_type = map + + _nonvar_fields = { + "strict", + *IteratorVariable._nonvar_fields, + } + + def __init__( + self, + fn: VariableTracker, + iterables: VariableTracker, + strict: bool = False, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.fn = fn + if not isinstance(iterables, variables.TupleVariable): + raise AssertionError( + f"Expected a tuple of iterables, got {type(iterables)}" + ) + self.iterable = iterables + self.strict = strict + + def python_type(self) -> type: + return map + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.3/Python/bltinmodule.c#L1409-L1450 + if not self.is_mutable(): + raise AssertionError("MapVariable must be mutable for next()") + + tuplesize = len(self.iterable.items) + + items = [] + for i in range(tuplesize): + it = self.iterable.items[i] + try: + items.append(pyiter_next(tx, it)) + except ObservedUserStopIteration: + if not self.strict: + raise + + handle_observed_exception(tx) # StopIteration + + if i: + raise_value_error( + tx, + f"map() argument {i + 1} shorter than argument {i}", + ) + + # In strict mode, if any iterable is exhausted, all must be exhausted. + for j in range(1, tuplesize): + it_j = self.iterable.items[j] + if not is_iterator_exhausted(tx, it_j): + raise_value_error( + tx, f"map() argument {j + 1} is longer than argument {j}" + ) + + raise_observed_exception(StopIteration, tx) + + # type: ignore[attr-defined] + return self.fn.call_function(tx, items, {}) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from("builtins", "map"), call_function_ex=True + ) + codegen(variables.TupleVariable([self.fn, *self.iterable.items])) + if self.strict: + if sys.version_info < (3, 14): + raise AssertionError( + "Unexpected bug: map(strict=True) requires Python 3.14+" + ) + codegen.extend_output( + [ + codegen.create_load_const("strict"), + codegen.create_load_const(self.strict), + create_instruction("BUILD_MAP", arg=1), + *create_call_function_ex(True, False), + ] + ) + else: + codegen.extend_output(create_call_function_ex(False, False)) + + +class FilterVariable(IteratorVariable): + """ + Represents filter(fn, iterable) + """ + + # PyFilter_Type: https://github.com/python/cpython/blob/v3.13.0/Python/bltinmodule.c#L630 + _cpython_type = filter + + def __init__( + self, + fn: VariableTracker, + iterable: VariableTracker, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.fn = fn + self.iterable = iterable + + def python_type(self) -> type: + return filter + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.3/Python/bltinmodule.c#L573-L606 + # A do-while loop to find elements that make fn return true + while True: + item = pyiter_next(tx, self.iterable) + if self.fn.is_constant_none(): + res = item + else: + res = self.fn.call_function(tx, [item], {}) + pred_res = variables.UserFunctionVariable( + polyfills.predicate # type: ignore[arg-type] + ).call_function(tx, [res], {}) + if pred_res.as_python_constant(): + return item + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen.load_import_from("builtins", "filter")) + codegen(self.fn) + codegen(self.iterable) + codegen.extend_output(create_call_function(2, False)) + + +class DictViewIterator(IteratorVariable): + """Base class for dict view iterators (keys, values, or items).""" + + _nonvar_fields = { + "view_type", + *IteratorVariable._nonvar_fields, + } + + view_type: str = "keys" + + def __init__( + self, + items: dict[HashableTracker, VariableTracker], + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if self.view_type == "keys": + self._iter = iter(items) + elif self.view_type == "values": + self._iter = iter(items.values()) # type: ignore[bad-assignment] + else: + if self.view_type != "items": + raise AssertionError( + f"Expected view_type 'items', got {self.view_type!r}" + ) + self._iter = iter(items.items()) # type: ignore[bad-assignment] + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # dictiter_iternextitem: https://github.com/python/cpython/blob/v3.13.3/Objects/dictobject.c#L5538-L5578 + # dictiter_iternextkey: https://github.com/python/cpython/blob/v3.13.3/Objects/dictobject.c#L5125-L5144 + # dictiter_iternextvalue: https://github.com/python/cpython/blob/v3.13.3/Objects/dictobject.c#L5248-L5267 + try: + item = next(self._iter) + + if self.view_type == "keys": + return item.vt + elif self.view_type == "values": + return item # type: ignore[bad-return] + else: # items + k, v = item # type: ignore[not-iterable] + return VariableTracker.build(tx, (k.vt, v)) + except (RuntimeError, StopIteration) as e: + raise_observed_exception( + type(e), + tx, + args=[VariableTracker.build(tx, a) for a in e.args], + ) + + def dict_view_iter_length_hint( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # dictiter_len/setiter_len: __length_hint__ returns the number of + # not-yet-consumed elements. self._iter is a live Python iterator over + # the captured items, so its own length hint already reflects any + # next() calls made during tracing. + # Not a C-level slot, so it lives in tp_methods rather than call_method. + return ConstantVariable.create(operator.length_hint(self._iter)) + + tp_methods = { + "__length_hint__": Method(dict_view_iter_length_hint), + } + + def python_type(self) -> type: + if self.view_type == "keys": + return type(iter({})) + elif self.view_type == "values": + return type(iter({}.values())) + else: # items + return type(iter({}.items())) + + +class DictIterator(DictViewIterator): + _cpython_type = type(iter({})) + view_type = "keys" + + +class DictKeysIterator(DictViewIterator): + _cpython_type = type(iter({}.keys())) + view_type = "keys" + + +class DictValuesIterator(DictViewIterator): + _cpython_type = type(iter({}.values())) + view_type = "values" + + +class DictItemsIterator(DictViewIterator): + _cpython_type = type(iter({}.items())) + view_type = "items" + + +class SetIterator(DictViewIterator): + _cpython_type = type(iter(set())) + view_type = "keys" diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/lazy.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/lazy.py new file mode 100644 index 0000000000000000000000000000000000000000..a07fe7e2e1c6f1cc1f5510ad8f49205d95969235 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/lazy.py @@ -0,0 +1,719 @@ +from __future__ import annotations + +import collections +import functools +import inspect +from typing import Any, TYPE_CHECKING + +from .. import config +from ..utils import is_function_or_wrapper +from .base import SourceLocation, VariableTracker, VariableTrackerMeta + + +if TYPE_CHECKING: + from collections.abc import Callable + from typing_extensions import Self + + from ..symbolic_convert import InstructionTranslatorBase + from .tensor import SymNodeVariable + + +class LazyCache: + """Container to cache the real VariableTracker""" + + def __init__(self, value: Any, source: Any) -> None: + if not isinstance(value, LazySymNodeFormatString): + if not source: + raise AssertionError( + "source is required for non-LazySymNodeFormatString values" + ) + self.value = value + self.source = source + self.name_hint: str | None = None + self.source_location: SourceLocation | None = None + self.vt: VariableTracker | None = None + + def realize(self) -> None: + if self.vt is not None: + raise AssertionError("LazyCache.realize() called but vt is already set") + from ..symbolic_convert import InstructionTranslator + from . import builder + + tx = InstructionTranslator.current_tx() + + if isinstance(self.value, LazySymNodeFormatString): + self.vt = builder.SourcelessBuilder.create(tx, self.value) + else: + # Pass allow_lazy_constant=False to prevent VariableBuilder from + # returning LazyConstantVariable, which would cause infinite recursion + # when LazyVariableTracker.realize() returns LazyConstantVariable. + self.vt = builder.VariableBuilder( + tx, self.source, allow_lazy_constant=False + )(self.value) + + if self.name_hint is not None: + self.vt.set_name_hint(self.name_hint) + + if self.source_location is not None and self.vt.source_location is None: + self.vt.set_source_location(self.source_location) + + del self.value + del self.source + del self.name_hint + del self.source_location + + +class ComputedLazyCache: + """Like LazyCache, but for sourceless constants computed from lazy operands.""" + + def __init__( + self, + value: Any, + lazy_vars: list[LazyConstantVariable], + args: list[VariableTracker], + op: Callable[..., Any], + num_nodes: int, + ) -> None: + self.value = value + self.lazy_vars = lazy_vars + self.args = args + self.op = op + self.num_nodes = num_nodes + self.name_hint: str | None = None + self.source_location: SourceLocation | None = None + self.vt: VariableTracker | None = None + + def realize(self) -> None: + if self.vt is not None: + raise AssertionError( + "ComputedLazyCache.realize() called but vt is already set" + ) + from ..symbolic_convert import InstructionTranslator + from .constant import ConstantVariable + from .tensor import SymNodeVariable + + any_symbolic = False + for lazy_var in self.lazy_vars: + if isinstance(lazy_var.realize(), SymNodeVariable): + any_symbolic = True + + if any_symbolic: + # The precomputed constant is stale; recompute symbolically + from .builtin import BuiltinVariable + + tx = InstructionTranslator.current_tx() + realized_args = [arg.realize() for arg in self.args] + self.vt = BuiltinVariable(self.op).call_function(tx, realized_args, {}) + else: + self.vt = ConstantVariable.create(self.value) + + if self.name_hint is not None: + self.vt.set_name_hint(self.name_hint) + if self.source_location is not None and self.vt.source_location is None: + self.vt.set_source_location(self.source_location) + + +class LazyVariableTracker(VariableTracker, metaclass=VariableTrackerMeta): + """ + A structure that defers the creation of the actual VariableTracker + for a given underlying value until it is accessed. + + The `realize` function invokes VariableTracker.build() to produce the real object. + Once a LazyVariableTracker has been realized, internal bookkeeping will + prevent double realization. + + This object should be utilized for processing containers, or objects that + reference other objects where we may not want to take on creating all the + VariableTrackers right away. + """ + + # Flag to prevent implicit realization in isinstance checks (inherited by subclasses) + _no_implicit_realize = True + _nonvar_fields = {"_cache", *VariableTracker._nonvar_fields} + + @staticmethod + def create( + value: Any, + source: Any, + *, + tx: InstructionTranslatorBase | None = None, + **options: Any, + ) -> VariableTracker: + if type(value) in LazyConstantVariable.supported_types: + return LazyConstantVariable.create(value, source, **options) + + # Cache based on source when no extra options are passed + if tx is not None and source is not None and not options: + cache = tx.output.variable_tracker_cache + cached = cache.get(source) + if cached is not None: + return cached + vt = LazyVariableTracker(LazyCache(value, source), source=source) + cache[source] = vt + return vt + + return LazyVariableTracker(LazyCache(value, source), source=source, **options) + + def __init__(self, _cache: LazyCache | ComputedLazyCache, **kwargs: Any) -> None: + if not isinstance(_cache, (LazyCache, ComputedLazyCache)): + raise AssertionError( + f"_cache must be a LazyCache or ComputedLazyCache instance, got {type(_cache).__name__}" + ) + super().__init__(**kwargs) + self._cache = _cache + + def realize(self) -> VariableTracker: + """Force construction of the real VariableTracker""" + if self._cache.vt is None: + self._cache.realize() + if self._cache.vt is None: + raise AssertionError("LazyCache.realize() did not set vt") + return self._cache.vt + + def lazy_isinstance(self, cls: type) -> bool: + """Check isinstance after realizing, used by ImplicitRealizingVariableTrackerMeta""" + return type.__instancecheck__(cls, self.realize()) + + def unwrap(self) -> VariableTracker | Self: + """Return the real VariableTracker if it already exists""" + if self.is_realized(): + if self._cache.vt is None: + raise AssertionError("is_realized() returned True but vt is None") + return self._cache.vt + return self + + def is_realized(self) -> bool: + return self._cache.vt is not None + + def clone(self, **kwargs: Any) -> VariableTracker: + if kwargs.get("_cache", self._cache) is not self._cache: + raise AssertionError( + "cannot clone LazyVariableTracker with a different _cache" + ) + if kwargs.get("source", self.source) is not self.source: + self.realize() + return VariableTracker.clone(self.unwrap(), **kwargs) + + def peek_type(self) -> type[Any]: + if self.is_realized(): + raise AssertionError( + "peek_type() called on an already realized LazyVariableTracker" + ) + return type(self._cache.value) + + def peek_value(self) -> Any: + if self.is_realized(): + raise AssertionError( + "peek_value() called on an already realized LazyVariableTracker" + ) + return self._cache.value + + def set_name_hint(self, name: str) -> None: + if self.is_realized(): + self._cache.vt.set_name_hint(name) # type: ignore[union-attr] + else: + self._cache.name_hint = name + + def set_source_location(self, source_location: SourceLocation) -> None: + self.source_location = source_location + if self.is_realized(): + self._cache.vt.set_source_location(source_location) # type: ignore[union-attr] + else: + self._cache.source_location = source_location + + def __str__(self) -> str: + variable_info = "LazyVariableTracker(" + if self.is_realized(): + variable_info += f"realized: {repr(self.unwrap())})" + else: + variable_info += f"unrealized: {self.peek_type()})" + + return variable_info + + def __getattr__(self, item: str) -> Any: + return getattr(self.realize(), item) + + def get_handler_type_for_dispatch(self) -> type: + """Return the VariableTracker type to use for builtin handler dispatch. + + For regular LazyVariableTracker (not LazyConstantVariable), we return + LazyVariableTracker itself so that _make_handler knows it needs to realize + the arguments before calling the handler. LazyConstantVariable overrides + this to return ConstantVariable since it can stay lazy. + """ + return LazyVariableTracker + + # most methods are auto-generated below, these are the ones we want to exclude + visit = VariableTracker.visit # type: ignore[assignment] + __repr__ = __str__ + + @classmethod + def realize_all( + cls, + value: Any, + cache: dict[int, tuple[Any, Any]] | None = None, + *, + allow_lazy_constant: bool = False, + ) -> Any: + """ + Walk an object and realize all LazyVariableTrackers inside it. + """ + if cache is None: + cache = {} + + idx = id(value) + if idx in cache: + return cache[idx][0] + + value_cls = type(value) + if issubclass(value_cls, LazyVariableTracker): + # Allow LazyConstantVariable and ComputedLazyConstantVariable to + # stay lazy when returning from a frame + keep_lazy = allow_lazy_constant and isinstance( + value, (LazyConstantVariable, ComputedLazyConstantVariable) + ) + if keep_lazy: + if isinstance(value, ComputedLazyConstantVariable): + if value.is_realized(): + result = cls.realize_all( + value.realize(), cache, allow_lazy_constant=True + ) + else: + # Output bytecode recomputes the value; operands only need TYPE_MATCH + for lazy_var in value._cache.lazy_vars: + lazy_var._ensure_type_guard() + result = value + else: + result = value + else: + result = cls.realize_all( + value.realize(), cache, allow_lazy_constant=allow_lazy_constant + ) + elif issubclass(value_cls, VariableTracker): + # update value in-place + result = value + # update cache now to prevent infinite recursion + cache[idx] = (result, value) + value_dict = value.__dict__ + nonvars = value._nonvar_fields + for key in value_dict: + if key not in nonvars: + value_dict[key] = cls.realize_all( + value_dict[key], cache, allow_lazy_constant=allow_lazy_constant + ) + elif value_cls is list: + result = [ + cls.realize_all(v, cache, allow_lazy_constant=allow_lazy_constant) + for v in value + ] + elif value_cls is tuple: + result = tuple( + cls.realize_all(v, cache, allow_lazy_constant=allow_lazy_constant) + for v in value + ) + elif value_cls in (dict, collections.OrderedDict): + result = { + k: cls.realize_all(v, cache, allow_lazy_constant=allow_lazy_constant) + for k, v in list(value.items()) + } + else: + result = value + + # save `value` to keep it alive and ensure id() isn't reused + cache[idx] = (result, value) + return result + + def is_hashable_lazy(self) -> bool: + # Checks that the underlying value is hashable without realizing the VT. + # This is used by the is_hashable() function in hashable.py as a fast + # path for unrealized LazyVTs. + def _helper(value: Any) -> bool: + # TODO: Add support for more types + return ( + inspect.isbuiltin(value) + or issubclass(type(value), type) + or is_function_or_wrapper(value) + ) + + if self.is_realized(): + raise AssertionError( + "is_hashable() called on an already realized LazyVariableTracker" + ) + value = self._cache.value + if isinstance(value, tuple): + return all(_helper(v) for v in value) + return _helper(value) + + def original_value(self) -> Any: + # Returns the value without realizing the VT. + if self.is_realized(): + raise AssertionError( + "original_value() called on an already realized LazyVariableTracker" + ) + return self._cache.value + + def original_source(self) -> Any: + # Returns the source without realizing the VT. + if self.is_realized(): + raise AssertionError( + "original_source() called on an already realized LazyVariableTracker" + ) + # pyrefly: ignore[missing-attribute] + return self._cache.source + + +class LazyConstantVariable(LazyVariableTracker): + """ + A lazy variable tracker for constants (int, float, bool, str) that defers + guarding until the value is actually used in a way that requires it. + + This allows constants that are just passed through (e.g., returned without + being used in control flow or math) to avoid unnecessary recompilation when + their values change. + + Guards are installed lazily: + - TYPE_MATCH guard is installed when type-based methods (python_type, is_tensor, + lazy_isinstance) are called + - CONSTANT_MATCH guard is installed on full realization (e.g., used in control + flow or math), which subsumes any TYPE_MATCH guard + """ + + supported_types = (int, float, bool, str) + _nonvar_fields = { + "_type_guard_installed", + "_type_guard_ref", + "_handler_type", + *LazyVariableTracker._nonvar_fields, + } + + @staticmethod + def create( + value: Any, + source: Any, + **options: Any, + ) -> VariableTracker: + from ..source import is_constant_source + from .constant import ConstantVariable + + if type(value) not in LazyConstantVariable.supported_types: + raise AssertionError( + f"unsupported type {type(value).__name__} for LazyConstantVariable" + ) + if source is None: + raise AssertionError("source must not be None for LazyConstantVariable") + + # If the source doesn't support guards (e.g., ConstantSource), fall back + # to creating a regular ConstantVariable directly + if is_constant_source(source): + return ConstantVariable.create(value, source=source, **options) + + return LazyConstantVariable(LazyCache(value, source), source=source, **options) + + def __init__(self, _cache: LazyCache, **kwargs: Any) -> None: + super().__init__(_cache, **kwargs) + self._type_guard_installed = False + self._type_guard_ref: Any = None + self._handler_type: type | None = None + + def _ensure_type_guard(self) -> None: + """Install TYPE_MATCH guard if not already installed and not realized.""" + if self._type_guard_installed or self.is_realized(): + return + + from ..guards import GuardBuilder, install_guard + + if self.source is None: + raise AssertionError("source must not be None when installing type guard") + guard = self.source.make_guard(GuardBuilder.TYPE_MATCH) + install_guard(guard) + self._type_guard_installed = True + self._type_guard_ref = guard + + def realize(self) -> VariableTracker: + """Force construction of the real VariableTracker.""" + if self.is_realized(): + return super().realize() + + from torch._guards import TracingContext + + from ..guards import GuardBuilder, install_guard + from .constant import ConstantVariable + + if self.source is None: + raise AssertionError( + "source must not be None when realizing LazyConstantVariable" + ) + + result = super().realize() + + # Only remove TYPE_MATCH if we're installing CONSTANT_MATCH + # (which subsumes it). For SymNodeVariable, keep TYPE_MATCH. + if isinstance(result, ConstantVariable): + if self._type_guard_ref is not None: + tracing_context = TracingContext.get() + tracing_context.guards_context.dynamo_guards.inner.discard( + self._type_guard_ref + ) + self._type_guard_ref = None + install_guard(self.source.make_guard(GuardBuilder.CONSTANT_MATCH)) + + return result + + def python_type(self) -> type: + """Return the Python type without triggering realization.""" + if self.is_realized(): + return super().python_type() + self._ensure_type_guard() + return self.peek_type() + + def is_tensor(self) -> bool: + """Primitive constants are never tensors.""" + self._ensure_type_guard() + return False + + def is_constant_none(self) -> bool: + self._ensure_type_guard() + return False + + def _maybe_realize_for_type(self) -> type | None: + """Check if we need to realize to determine the VariableTracker type. + + Returns None if we can determine the type without realization (and installs + TYPE_MATCH guard). Returns the realized type if realization was needed. + + With specialize_int=False or specialize_float=False, ints/floats may become + either ConstantVariable or SymNodeVariable, so we must realize to know. + For bool/str, we always know it will be ConstantVariable. + """ + if self.is_realized(): + return type(self.realize()) + + value_type = self.peek_type() + + # When specialize_int/specialize_float is False, ints/floats may become + # SymNodeVariable. Must realize to determine the actual type. + if not config.specialize_int and value_type is int: + return type(self.realize()) + if not config.specialize_float and value_type is float: + return type(self.realize()) + + # For bool/str, or when specializing ints/floats, we know it will be + # ConstantVariable. Install TYPE_MATCH guard and return None. + self._ensure_type_guard() + return None + + def get_handler_type_for_dispatch(self) -> type: + """Return the VariableTracker type to use for builtin handler dispatch. + + This allows builtins like isinstance() and type() to find the correct + handler without triggering full realization of the lazy constant. + """ + if self._handler_type is not None: + return self._handler_type + + from .constant import ConstantVariable + + realized_type = self._maybe_realize_for_type() + self._handler_type = ( + realized_type if realized_type is not None else ConstantVariable + ) + return self._handler_type + + def lazy_isinstance(self, cls: type) -> bool: + """Check isinstance without triggering realization when possible. + + LazyConstantVariable only wraps primitive types (int, float, bool, str) + which always realize to ConstantVariable, so we can answer isinstance + checks by checking if the target class is ConstantVariable or a parent. + + However, when specialize_int=False or specialize_float=False, integers + and floats may realize to SymNodeVariable instead of ConstantVariable, + so we must fall back to full realization for those cases. + """ + from .constant import ConstantVariable + from .tensor import SymNodeVariable + + # If already realized, delegate to the parent which does the regular check + if self.is_realized(): + return super().lazy_isinstance(cls) + + # LazyConstantVariable can only realize to ConstantVariable or SymNodeVariable. + # If cls is not a parent of either, we can answer False without realization. + if not issubclass(ConstantVariable, cls) and not issubclass( + SymNodeVariable, cls + ): + self._ensure_type_guard() + return False + + realized_type = self._maybe_realize_for_type() + if realized_type is not None: + return issubclass(realized_type, cls) + return issubclass(ConstantVariable, cls) + + +class ComputedLazyConstantVariable(LazyVariableTracker): + """ + Result of a supported op over lazy constant operands. The value is computed + eagerly at trace time but guards are deferred: if never realized, output + bytecode recomputes it from the operands (TYPE_MATCH only); realization + realizes the operands, installing their CONSTANT_MATCH guards. + """ + + _cache: ComputedLazyCache # pyrefly: ignore[bad-override] + + @staticmethod + def create( # pyrefly: ignore[bad-param-name-override, bad-override] + op: Callable[..., Any], + args: list[VariableTracker], + ) -> VariableTracker | None: + """Compute op(*args) eagerly; returns None to fall back to realization.""" + from .constant import ConstantVariable + + max_nodes = config.computed_lazy_constant_max_nodes + if max_nodes <= 0: + return None + + lazy_vars: list[LazyConstantVariable] = [] + num_nodes = 1 + + def get_value(arg: VariableTracker) -> Any: + nonlocal num_nodes + if isinstance(arg, ComputedLazyConstantVariable) and not arg.is_realized(): + lazy_vars.extend(arg._cache.lazy_vars) + num_nodes += arg._cache.num_nodes + return arg._cache.value + if isinstance(arg, LazyConstantVariable) and not arg.is_realized(): + lazy_vars.append(arg) + return arg.peek_value() + return arg.as_python_constant() + + values = [get_value(arg) for arg in args] + # realize/reconstruct recurse through args; unbounded chains overflow the stack + if num_nodes > max_nodes: + return None + try: + value = op(*values) + except Exception: + return None + if not ConstantVariable.is_base_literal(value): + return None + if not lazy_vars: + return ConstantVariable.create(value) + return ComputedLazyConstantVariable( + ComputedLazyCache(value, lazy_vars, list(args), op, num_nodes) + ) + + def __init__(self, _cache: ComputedLazyCache, **kwargs: Any) -> None: + if not isinstance(_cache, ComputedLazyCache): + raise AssertionError( + f"_cache must be a ComputedLazyCache instance, got {type(_cache).__name__}" + ) + super().__init__(_cache, **kwargs) + + def _ensure_operand_type_guards(self) -> None: + # Type queries on the result depend on the operand types + for lazy_var in self._cache.lazy_vars: + lazy_var._ensure_type_guard() + + def python_type(self) -> type: + if self.is_realized(): + return super().python_type() + self._ensure_operand_type_guards() + return type(self._cache.value) + + def is_tensor(self) -> bool: + if self.is_realized(): + return super().is_tensor() + self._ensure_operand_type_guards() + return False + + def _might_realize_symbolic(self) -> bool: + # Mirrors LazyConstantVariable._maybe_realize_for_type + from .tensor import SymNodeVariable + + for lazy_var in self._cache.lazy_vars: + if lazy_var.is_realized(): + if type.__instancecheck__(SymNodeVariable, lazy_var.realize()): + return True + else: + value_type = lazy_var.peek_type() + if value_type is int and not config.specialize_int: + return True + if value_type is float and not config.specialize_float: + return True + return False + + def get_handler_type_for_dispatch(self) -> type: + from .constant import ConstantVariable + + if not self.is_realized() and not self._might_realize_symbolic(): + self._ensure_operand_type_guards() + return ConstantVariable + return type(self.realize()) + + def lazy_isinstance(self, cls: type) -> bool: + from .constant import ConstantVariable + from .tensor import SymNodeVariable + + if self.is_realized(): + return type.__instancecheck__(cls, self.realize()) + if not issubclass(ConstantVariable, cls) and not issubclass( + SymNodeVariable, cls + ): + self._ensure_operand_type_guards() + return False + if self._might_realize_symbolic(): + return type.__instancecheck__(cls, self.realize()) + self._ensure_operand_type_guards() + return issubclass(ConstantVariable, cls) + + def reconstruct(self, codegen: Any) -> None: + from ..bytecode_transformation import create_call_function + + cache = self._cache + codegen.add_push_null( + lambda: codegen.load_import_from("operator", cache.op.__name__) + ) + for arg in cache.args: + codegen(arg) + codegen.extend_output(create_call_function(len(cache.args), False)) + + +class LazySymNodeFormatString: + def __init__( + self, sym_node_variable: SymNodeVariable, fmt_spec_var: VariableTracker + ) -> None: + from .constant import ConstantVariable + + self.sym_node_var = sym_node_variable + self.fmt_var = ConstantVariable.create( + "{:" + fmt_spec_var.as_python_constant() + "}" + ) + + def __repr__(self) -> str: + return str.format( + self.fmt_var.as_python_constant(), + str(self.sym_node_var.evaluate_expr()), + ) + + +def _create_realize_and_forward( + name: str, +) -> Callable[[LazyVariableTracker, Any, Any], Any]: + @functools.wraps(getattr(VariableTracker, name)) + def realize_and_forward( + self: LazyVariableTracker, *args: Any, **kwargs: Any + ) -> Any: + return getattr(self.realize(), name)(*args, **kwargs) + + return realize_and_forward + + +def _populate() -> None: + for name, value in VariableTracker.__dict__.items(): + if name not in LazyVariableTracker.__dict__: + if callable(value): + setattr(LazyVariableTracker, name, _create_realize_and_forward(name)) + + +_populate() diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/lists.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/lists.py new file mode 100644 index 0000000000000000000000000000000000000000..d4a2493f53e72988d6ed7d9ed45ff447a5d99940 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/lists.py @@ -0,0 +1,2529 @@ +""" +Variable tracking implementations for list-like data structures in Dynamo. + +This module provides specialized variable tracking for various collection types: +- Lists and list subclasses (including torch.nn.ModuleList, ParameterList) +- Tuples and named tuples +- Ranges and slices +- Collections.deque +- torch.Size with special proxy handling + +The implementations support both mutable and immutable collections, iteration, +and common sequence operations. Each collection type has a dedicated Variable +class that handles its unique behaviors while integrating with Dynamo's +variable tracking system. +""" + +import collections +import operator +import sys +from typing import Any, Optional, TYPE_CHECKING + +import torch +import torch.fx +from torch.utils._pytree import SequenceKey + +from .. import graph_break_hints, polyfills, variables +from ..bytecode_transformation import ( + create_build_tuple, + create_call_function, + create_call_method, + create_dup_top, + create_instruction, +) +from ..exc import ( + ObservedException, + raise_observed_exception, + raise_type_error, + unimplemented, + Unsupported, +) +from ..source import AttrSource +from ..utils import ( + check_positional, + cmp_name_to_op_mapping, + get_fake_value, + guard_if_dyn, + iter_contains, + odict_values, + raise_args_mismatch, + range_iterator, + set_example_value, + tracked_repr, + unpack_and_apply_fn, + unpack_iterable, +) +from .base import ( + AsPythonConstantNotImplementedError, + GetSet, + Method, + ValueMutationNew, + VariableTracker, +) +from .constant import ConstantVariable +from .functions import UserFunctionVariable +from .iter import IteratorVariable +from .object_protocol import ( + generic_richcompare_bool, + maybe_get_python_type, + pyindex_check, + pylong_as_ssize_t, + pynumber_as_ssize_t, + pynumber_index, + type_implements_nb_index, + vt_is_iterable, +) + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + +def pytuple_checkexact(obj: VariableTracker) -> bool: + return obj.python_type() is tuple + + +def pytuple_check(obj: VariableTracker) -> bool: + return issubclass(obj.python_type(), tuple) + + +def pylist_check(obj: VariableTracker) -> bool: + return issubclass(obj.python_type(), list) + + +def pylist_checkexact(obj: VariableTracker) -> bool: + return obj.python_type() is list + + +def pyslice_check(obj: VariableTracker) -> bool: + return issubclass(obj.python_type(), slice) + + +def _cpython_has_simple_slice_bug() -> bool: + # CPython gh-120384 fixed an array-out-of-bounds crash by moving the + # PySequence_Fast check ahead of the step==1 branch in + # list_ass_subscript, which as a side effect unified the non-iterable + # error message for simple and extended slices. Before this landed, + # simple slices (step is None or 1) raised "can only assign an + # iterable" instead of "must assign iterable to extended slice". + # Verified empirically against real CPython builds: the fix shipped in + # 3.10.20, 3.11.15, and 3.12.5 (3.12.0 is the first 3.12 release, so + # 3.12.0-3.12.4 predate it); 3.13+ never had the bug. + v = sys.version_info + if v[:2] == (3, 10): + return v < (3, 10, 20) + if v[:2] == (3, 11): + return v < (3, 11, 15) + if v[:2] == (3, 12): + return v < (3, 12, 5) + return False + + +class BaseListVariable(VariableTracker): + @staticmethod + def cls_for_instance(obj: Any) -> type["BaseListVariable"]: + return BaseListVariable.cls_for(type(obj)) + + @staticmethod + def cls_for(obj: Any) -> type: + return { + iter: ListIteratorVariable, + list: ListVariable, + slice: SliceVariable, + torch.Size: SizeVariable, + tuple: TupleVariable, + odict_values: ListVariable, + torch.nn.ParameterList: ListVariable, + torch.nn.ModuleList: ListVariable, + collections.deque: DequeVariable, + }[obj] + + def __init__( + self, + items: list[VariableTracker], + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if not isinstance(items, list): + raise AssertionError(f"items must be a list, got {type(items).__name__}") + if not all(isinstance(x, VariableTracker) for x in items): + raise AssertionError("all items must be VariableTracker instances") + self.items: list[VariableTracker] = items + + def _as_proxy(self) -> list[Any]: + return [x.as_proxy() for x in self.items] + + def modified( + self, items: list[VariableTracker], **kwargs: Any + ) -> "BaseListVariable": + return type(self)(items, **kwargs) + + @property + def value(self) -> Any: + return self.as_python_constant() + + def debug_repr_helper(self, prefix: str, suffix: str) -> str: + return prefix + ", ".join(i.debug_repr() for i in self.items) + suffix + + def as_python_constant(self) -> Any: + return self.python_type()([x.as_python_constant() for x in self.items]) + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + return VariableTracker.build(tx, self.debug_repr()) + + def as_proxy(self) -> Any: + if self.python_type() is SizeVariable: + raise AssertionError( + "SizeVariable should not use BaseListVariable.as_proxy" + ) + return self.python_type()(self._as_proxy()) + + def getitem_const( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + if pyindex_check(maybe_get_python_type(arg)): + index = pynumber_as_ssize_t(tx, arg).as_python_constant() + try: + return self.items[index] + except IndexError: + raise_observed_exception( + IndexError, tx, args=["list index out of range"] + ) + elif pyslice_check(arg): + if not isinstance(arg, SliceVariable): + raise AssertionError("Expected arg to be a SliceVariable") + index = arg.as_index_slice(tx) + if index.step == 0: + raise_observed_exception( + ValueError, tx, args=["slice step cannot be zero"] + ) + # Set source to None because slicing a list gives a new local + return self.clone( + items=self.items[index], + source=None, + mutation_type=ValueMutationNew() if self.mutation_type else None, + ) + else: + raise_type_error( + tx, + f"{self.python_type_name()} indices must be integers or slices, " + f"not {arg.python_type_name()}", + ) + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase" + ) -> list[VariableTracker]: + return list(self.items) + + def sq_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + """Sequence length for lists, tuples, and range objects.""" + return VariableTracker.build(tx, len(self.items)) + + mp_length_impl = sq_length_impl + + def sq_contains_impl( + self, tx: "InstructionTranslatorBase", item: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/listobject.c#L635-L652 + + # TODO(dynamo-team): Replace iter_contains by a proper impl. once we + # implement PyObject_RichCompare + return iter_contains(self.items, item, tx) + + def call_tree_map_branch( + self, + tx: "InstructionTranslatorBase", + tree_map_fn: UserFunctionVariable, + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if not isinstance(self, (ListVariable, TupleVariable)): + return self._tree_map_fallback( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs + ) + + other_lists: list[BaseListVariable] = [] + for candidate in rest: + if ( + not isinstance(candidate, BaseListVariable) + or len(candidate.items) != len(self.items) + or self.python_type() != candidate.python_type() + ): + return self._tree_map_fallback( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs + ) + other_lists.append(candidate) + + new_items: list[VariableTracker] = [] + for idx, item in enumerate(self.items): + sibling_leaves = [candidate.items[idx] for candidate in other_lists] + new_items.append( + item.call_tree_map( + tx, + tree_map_fn, + map_fn, + sibling_leaves, + tree_map_kwargs, + ) + ) + + return self.clone( + items=new_items, + source=None, + mutation_type=ValueMutationNew(), + ) + + def call_tree_map_with_path_branch( + self, + tx: "InstructionTranslatorBase", + tree_map_fn: UserFunctionVariable, + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + keypath: tuple[Any, ...], + ) -> VariableTracker: + if not isinstance(self, (ListVariable, TupleVariable)): + return self._tree_map_with_path_fallback( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs, keypath + ) + + other_lists: list[BaseListVariable] = [] + for candidate in rest: + if ( + not isinstance(candidate, BaseListVariable) + or len(candidate.items) != len(self.items) + or self.python_type() != candidate.python_type() + ): + return self._tree_map_with_path_fallback( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs, keypath + ) + other_lists.append(candidate) + + new_items: list[VariableTracker] = [] + for idx, item in enumerate(self.items): + sibling_leaves = [candidate.items[idx] for candidate in other_lists] + child_keypath = keypath + (SequenceKey(idx),) + new_items.append( + item.call_tree_map_with_path( + tx, + tree_map_fn, + map_fn, + sibling_leaves, + tree_map_kwargs, + child_keypath, + ) + ) + + return self.clone( + items=new_items, + source=None, + mutation_type=ValueMutationNew(), + ) + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # list_subscript: https://github.com/python/cpython/blob/62a6e898e01/Objects/listobject.c#L3689-L3710 + return self.getitem_const(tx, key) + + def sq_item_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # list_item: https://github.com/python/cpython/blob/62a6e898e01/Objects/listobject.c#L335-L351 + # tuple_item: https://github.com/python/cpython/blob/62a6e898e01/Objects/tupleobject.c#L421-L430 + # CPython's sq_item takes Py_ssize_t (already int from generic_getitem's + # nb_index_impl). Unlike mp_subscript, sq_item never handles slices. + index = key.as_python_constant() + try: + return self.items[index] + except IndexError: + raise_observed_exception( + IndexError, + tx, + args=[f"{self.python_type_name()} index out of range"], + ) + + def sq_repeat_impl( + self, + tx: "InstructionTranslatorBase", + count: VariableTracker, + ) -> VariableTracker: + n = count.as_python_constant() + if pytuple_checkexact(self) and (n == 1 or not self.items): + return self + try: + new_items = self.items * n + except (MemoryError, OverflowError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + # self.items is a list, so we can't go through VariableTracker.build (which would wrap in a list variable) + kwargs: dict[str, Any] = {} + if issubclass(self.python_type(), list): + kwargs["mutation_type"] = ValueMutationNew() + return type(self)(new_items, **kwargs) + + def _seq_richcompare( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + accepted_type: type, + ) -> VariableTracker: + """Shared list_richcompare / tuplerichcompare core. + + https://github.com/python/cpython/blob/e76aa128fe/Objects/listobject.c#L3352 + https://github.com/python/cpython/blob/e76aa128fe/Objects/tupleobject.c#L821 + CPython operates on the internal C array directly, so we compare + VT items without going through a polyfill. + """ + from .object_protocol import generic_richcompare + from .tensor import SymNodeVariable + + try: + other_type = other.python_type() + except NotImplementedError: + return ConstantVariable.create(NotImplemented) + if not issubclass(other_type, accepted_type): + return ConstantVariable.create(NotImplemented) + + left = self.items + # CPython uses ob_item (the C array) directly, bypassing __iter__. + # For user-defined subclasses (UserDefinedListVariable etc.), + # the items live on the _base_vt. + other_vt = getattr(other, "_base_vt", None) or other + right = other_vt.items # pyrefly: ignore[missing-attribute] + + cmp_op = cmp_name_to_op_mapping[op] + + if cmp_op is operator.eq and len(left) != len(right): + return ConstantVariable.create(False) + if cmp_op is operator.ne and len(left) != len(right): + return ConstantVariable.create(True) + + sym_eq_acc = None + for a, b in zip(left, right): + # CPython uses PyObject_RichCompareBool per element, which has + # an identity shortcut before the full do_richcompare dispatch. + eq_result = generic_richcompare_bool(tx, a, b, "__eq__") + if eq_result.is_python_constant(): + if not eq_result.as_python_constant(): + if cmp_op in (operator.eq, operator.ne): + return ConstantVariable.create(cmp_op is operator.ne) + return generic_richcompare(tx, a, b, op) + elif eq_result.is_symnode_like(): + if cmp_op not in (operator.eq, operator.ne): + # Ordering requires branching on element equality, which + # can't be expressed as a single symbolic expression. + # Specialize: install a guard on the equality result and + # proceed with the concrete value. + eq_bool = guard_if_dyn(eq_result) + if not eq_bool: + return generic_richcompare(tx, a, b, op) + continue + if sym_eq_acc is None: + sym_eq_acc = eq_result + else: + proxy = tx.output.create_proxy( + "call_function", + operator.and_, + (sym_eq_acc.as_proxy(), eq_result.as_proxy()), + {}, + ) + sym_eq_acc = SymNodeVariable.create(tx, proxy, sym_num=None) + else: + unimplemented( + gb_type="list_richcompare_nonconst", + context=f"element comparison produced {type(eq_result).__name__}", + explanation="Cannot determine list/tuple comparison at compile time when element comparison produces a non-constant result.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + if sym_eq_acc is not None: + if cmp_op is operator.ne: + proxy = tx.output.create_proxy( + "call_function", + operator.not_, + (sym_eq_acc.as_proxy(),), + {}, + ) + return SymNodeVariable.create(tx, proxy, sym_num=None) + return sym_eq_acc + + return ConstantVariable.create(cmp_op(len(left), len(right))) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "index": + if not len(args): + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + + try: + # Speedup trace times for constant data structures + items = [item.as_python_constant() for item in self.items] + const_args = [arg.as_python_constant() for arg in args] + const_kwargs = {k: v.as_python_constant() for k, v in kwargs.items()} + try: + return VariableTracker.build( + tx, items.index(*const_args, **const_kwargs) + ) + except ValueError: + raise_observed_exception( + ValueError, + tx, + args=["tuple.index()"], + ) + except AsPythonConstantNotImplementedError: + return tx.inline_user_function_return( + VariableTracker.build(tx, polyfills.index), + [self] + list(args), + kwargs, + ) + elif name == "count": + if len(args) != 1: + raise_args_mismatch( + tx, + name, + "1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + return VariableTracker.build(tx, operator.countOf).call_function( + tx, + [self, args[0]], + kwargs, + ) + elif name == "__reversed__": + # list/tuple/namedtuple __reversed__: reverse iterator over items. + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + return ListIteratorVariable( + list(reversed(self.items)), + mutation_type=ValueMutationNew(), + ) + return super().call_method(tx, name, args, kwargs) + + +class RangeVariable(BaseListVariable): + # PyRange_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/rangeobject.c#L767 + _cpython_type = range + + def __init__(self, items: list[VariableTracker], **kwargs: Any) -> None: + items_to_map = items + start = variables.ConstantVariable.create(0) + stop = None + step = variables.ConstantVariable.create(1) + + if len(items_to_map) == 1: + (stop,) = items_to_map + elif len(items_to_map) == 2: + start, stop = items_to_map + elif len(items_to_map) == 3: + start, stop, step = items_to_map + else: + raise AssertionError + + def maybe_as_int(x: VariableTracker) -> VariableTracker: + return ( + ConstantVariable.create(int(x.as_python_constant())) + if x.is_python_constant() + else x + ) + + # cast each argument to an integer + start = maybe_as_int(start) + step = maybe_as_int(step) + stop = maybe_as_int(stop) + + if stop is None: + raise AssertionError("stop must not be None after parsing range arguments") + super().__init__([start, stop, step], **kwargs) + + def debug_repr(self) -> str: + repr = f"range({self.start()}, {self.stop()}" + if self.step() != 1: + repr += f", {self.step()}" + repr += ")" + return repr + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: range_repr in https://github.com/python/cpython/blob/6280bb547840b609feedb78887c6491af75548e8/Objects/rangeobject.c#L673-L691 + return VariableTracker.build(tx, self.debug_repr()) + + def python_type(self) -> type: + return range + + # range math needs concrete bounds; with assume_static_by_default=False a + # range object's start/stop/step are wrapped as symbolic ints, so specialize + # them (installing a guard) rather than assuming a plain constant. + def start(self) -> int: + return guard_if_dyn(self.items[0]) + + def stop(self) -> int: + return guard_if_dyn(self.items[1]) + + def step(self) -> int: + return guard_if_dyn(self.items[2]) + + def range_length(self) -> int: + lo = self.start() + hi = self.stop() + step = self.step() + + if step == 0: + raise AssertionError("step must not be zero") + if step > 0 and lo < hi: + return 1 + (hi - 1 - lo) // step + elif step < 0 and lo > hi: + return 1 + (lo - 1 - hi) // (0 - step) + else: + return 0 + + def _get_slice_indices(self, length: int, slice: slice) -> list[int]: + step_is_negative = 0 + + if slice.step is None: + step = 1 + step_is_negative = False + else: + step = slice.step + step_is_negative = slice.step < 0 + + # Find lower and upper bounds for start and stop. + if step_is_negative: + lower = -1 + upper = length + lower + else: + lower = 0 + upper = length + + # Compute start + if slice.start is None: + start = upper if step_is_negative else lower + else: + start = slice.start + + if start < 0: + start += length + if start < lower: + start = lower + else: + if start > upper: + start = upper + + # Compute stop. + if slice.stop is None: + stop = lower if step_is_negative else upper + + else: + stop = slice.stop + + if stop < 0: + stop += length + if stop < lower: + stop = lower + else: + if stop > upper: + stop = upper + + return [start, stop, step] + + def apply_index( + self, tx: "InstructionTranslatorBase", index: int + ) -> VariableTracker: + length = self.range_length() + if index < 0: + index = length + index + + if index < 0 or index >= length: + raise_observed_exception( + IndexError, + tx, + args=["range object index out of range"], + ) + + return VariableTracker.build(tx, self.start() + (index * self.step())) + + def apply_slice(self, slice: slice) -> "RangeVariable": + (slice_start, slice_stop, slice_step) = self._get_slice_indices( + self.range_length(), slice + ) + + def compute_item(index: int) -> int: + return self.start() + (index * self.step()) + + sub_step = self.step() * slice_step + sub_start = compute_item(slice_start) + sub_stop = compute_item(slice_stop) + + result = RangeVariable( + [ + variables.ConstantVariable.create(x) + for x in [sub_start, sub_stop, sub_step] + ], + mutation_type=ValueMutationNew() if self.mutation_type else None, + ) + return result + + def as_python_constant(self) -> range: + return range(*[x.as_python_constant() for x in self.items]) + + def getitem_const( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + # range_subscript: https://github.com/python/cpython/blob/62a6e898e01/Objects/rangeobject.c#L729-L748 + arg_type = maybe_get_python_type(arg) + if pyindex_check(arg_type): + i = pynumber_index(tx, arg) + return self.apply_index(tx, i.as_python_constant()) + elif pyslice_check(arg): + if not isinstance(arg, SliceVariable): + raise AssertionError("Expected arg to be a SliceVariable") + return self.apply_slice(arg.as_index_slice(tx)) + raise_type_error( + tx, + f"range indices must be integers or slices, not {arg.python_type_name()}", + ) + + def as_proxy(self) -> range: + return self.python_type()(*self._as_proxy()) + + def unpack_var_sequence( + self, tx: Optional["InstructionTranslatorBase"] = None + ) -> list[VariableTracker]: + rng = range(self.start(), self.stop(), self.step()) + return [variables.ConstantVariable.create(x) for x in rng] + + def sq_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + """Sequence length for range objects.""" + length = self.range_length() + if length > sys.maxsize: + raise_observed_exception(OverflowError, tx) + return VariableTracker.build(tx, length) + + def mp_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.sq_length_impl(tx) + + def reconstruct(self, codegen: "PyCodegen") -> None: + if "range" in codegen.tx.f_globals: + raise AssertionError("'range' must not be shadowed in f_globals") + codegen.add_push_null( + lambda: codegen.append_output(codegen.create_load_python_module(range)) # type: ignore[arg-type] + ) + codegen.foreach(self.items) + codegen.extend_output(create_call_function(3, False)) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + if self.python_type() is range: + return VariableTracker.build(tx, name in range.__dict__) + return super().call_obj_hasattr(tx, name) + + def range_equals(self, other: "RangeVariable") -> bool: + # ref: https://github.com/python/cpython/blob/62a6e898e017c9878490544f6a227b8a187a949c/Objects/rangeobject.c#L514-L553 (range_equals) + r0, r1 = self, other + if r0 is r1: + return True + if r0.range_length() != r1.range_length(): + return False + if r0.range_length() == 0: + return True + if r0.start() != r1.start(): + return False + if r0.range_length() == 1: + return True + return r0.step() == r1.step() + + def range_count(self, x: VariableTracker) -> int: + # Based on CPython + # https://github.com/guilhermeleobas/cpython/blob/baefaa6cba1d69efd2f930cdc56bca682c54b139/Objects/rangeobject.c#L442-L486 + x = x.as_python_constant() + if type(x) not in (bool, int, float): + return 0 + + start, stop, step = self.start(), self.stop(), self.step() + + if step == 0: + return 0 + + in_range = (start <= x < stop) if step > 0 else (stop < x <= start) + + if in_range: + re = ((x - start) % step) == 0 + return int(re) + return 0 + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # range_subscript: https://github.com/python/cpython/blob/62a6e898e01/Objects/rangeobject.c#L729-L748 + return self.getitem_const(tx, key) + + def sq_contains_impl( + self, tx: "InstructionTranslatorBase", item: VariableTracker + ) -> VariableTracker: + # range_contains: https://github.com/python/cpython/blob/60403a5409ff2c3f3b07dd2ca91a7a3e096839c7/Objects/rangeobject.c#L482-L490 + if maybe_get_python_type(item) in (int, bool): + return VariableTracker.build(tx, bool(self.range_count(item))) + return iter_contains(self.unpack_var_sequence(tx), item, tx) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.3/Objects/rangeobject.c#L896-L927 + if not all(var.is_python_constant() for var in self.items): + # Can't represent a `range_iterator` without well defined bounds + return variables.misc.DelayGraphBreakVariable( + msg="Cannot create range_iterator: bounds (start, stop, step) must be fully defined as concrete constants.", + ) + return RangeIteratorVariable( + self.start(), self.stop(), self.step(), self.range_length() + ) + + def sq_item_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # range_item: https://github.com/python/cpython/blob/62a6e898e01/Objects/rangeobject.c#L405-L416 + # CPython's sq_item takes Py_ssize_t (already int from generic_getitem's + # nb_index_impl). Unlike mp_subscript (range_subscript), no slices. + index = key.as_python_constant() + return self.apply_index(tx, index) + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + """range_richcompare: eq/ne via range_equals, NotImplemented for ordering. + + https://github.com/python/cpython/blob/e76aa128fe/Objects/rangeobject.c#L472 + """ + from .builder import SourcelessBuilder + + if op not in ("__eq__", "__ne__"): + return ConstantVariable.create(NotImplemented) + try: + if other.python_type() is not range: + return ConstantVariable.create(NotImplemented) + except NotImplementedError: + return ConstantVariable.create(NotImplemented) + + if isinstance(other, RangeVariable): + cmp = self.range_equals(other) + else: + cmp = False + + if op == "__eq__": + return SourcelessBuilder.create(tx, cmp) + else: + return SourcelessBuilder.create(tx, not cmp) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import SourcelessBuilder + + if name == "count": + return SourcelessBuilder.create(tx, self.range_count(*args)) + elif name == "__reversed__": + # range.__reversed__: range_iterator with reversed bounds. + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/rangeobject.c (range_reverse) + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + length = self.range_length() + start = self.start() + step = self.step() + new_start = start + (length - 1) * step + new_step = -step + return RangeIteratorVariable(new_start, 0, new_step, length) + elif name == "index": + x = args[0].as_python_constant() + start, stop, step = self.start(), self.stop(), self.step() + in_range = (start <= x < stop) if step > 0 else (stop < x <= start) + if in_range and ((x - start) % step) == 0: + return VariableTracker.build(tx, (x - start) // step) + raise_observed_exception( + ValueError, + tx, + args=[f"{x} is not in range"], + ) + return super().call_method(tx, name, args, kwargs) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + fields = ["start", "stop", "step"] + if name in fields: + return self.items[fields.index(name)] + + return super().tp_getattro_impl(tx, name) + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # CPython range_hash: https://github.com/python/cpython/blob/e76aa128fe/Objects/rangeobject.c#L572 + return hash(self.as_python_constant()), False + + +class CommonListMethodsVariable(BaseListVariable): + """ + Implement methods common to List and other List-like things + """ + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .tensor import SymNodeVariable + + if name == "append" and self.is_mutable(): + if kwargs or len(args) != 1: + raise_args_mismatch( + tx, + name, + "1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + (arg,) = args + tx.output.side_effects.mutation(self) + self.items.append(arg) + return ConstantVariable.create(None) + elif name == "extend" and self.is_mutable(): + if kwargs or len(args) != 1: + raise_args_mismatch( + tx, + name, + "1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + + # CPython has a series of checks to optimize list.extend for different data types + # ref: https://github.com/python/cpython/blob/0fd4fd4496c557b68477a99c1c231a5870c91daf/Objects/listobject.c#L1389-L1444 + from .dicts import ConstDictVariable + from .sets import SetVariable + from .user_defined import UserDefinedObjectVariable + + sz = len(self.items) + if isinstance(args[0], (ListVariable, TupleVariable)): + self.items.extend(args[0].items) + elif isinstance(args[0], UserDefinedObjectVariable): + self.items.extend(unpack_iterable(tx, args[0])) + elif isinstance(args[0], (ConstDictVariable, SetVariable)): + items = [item.vt for item in args[0].items] + self.items.extend(items) + elif isinstance(args[0], ConstantVariable): + items = unpack_iterable(tx, args[0]) + self.items.extend(items) + else: + unpack_and_apply_fn( + tx, args[0], lambda item: self.call_method(tx, "append", [item], {}) + ) + + if len(self.items) > sz: + tx.output.side_effects.mutation(self) + return ConstantVariable.create(None) + elif name == "insert" and self.is_mutable(): + if kwargs or len(args) != 2: + raise_args_mismatch( + tx, + name, + "2 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + idx, value = args + if isinstance(idx, SymNodeVariable): + const_idx = idx.evaluate_expr() + else: + const_idx = idx.as_python_constant() + tx.output.side_effects.mutation(self) + # type: ignore[arg-type] + self.items.insert(const_idx, value) + return ConstantVariable.create(None) + elif name == "pop" and self.is_mutable(): + if kwargs or len(args) > 1: + raise_args_mismatch( + tx, + name, + "at most 1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + + if len(self.items) == 0: + raise_observed_exception(IndexError, tx, args=["pop from empty list"]) + + if len(args): + idx = args[0].as_python_constant() + if idx >= len(self.items): + raise_observed_exception( + IndexError, tx, args=["pop index out of range"] + ) + tx.output.side_effects.mutation(self) + return self.items.pop(*[a.as_python_constant() for a in args]) + elif name == "clear" and self.is_mutable(): + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + tx.output.side_effects.mutation(self) + self.items.clear() + return ConstantVariable.create(None) + elif name == "copy": + # List copy() doesn't have args and kwargs + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + items_lst: list[VariableTracker] = list(self.items) + return self.modified(items_lst, mutation_type=ValueMutationNew()) + elif name == "reverse" and self.is_mutable(): + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + self.items.reverse() + tx.output.side_effects.mutation(self) + return ConstantVariable.create(None) + elif name == "remove" and self.is_mutable(): + if kwargs or len(args) != 1: + raise_args_mismatch( + tx, + name, + "1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + + idx = self.call_method(tx, "index", args, kwargs) + self.call_method(tx, "pop", [idx], {}) + return ConstantVariable.create(None) + else: + return super().call_method(tx, name, args, kwargs) + + +class ListVariable(CommonListMethodsVariable): + # PyList_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/listobject.c#L3776 + _cpython_type = list + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + return self._seq_richcompare(tx, other, op, list) + + def python_type(self) -> type: + return list + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(length={len(self.items)})" + + def debug_repr(self) -> str: + return self.debug_repr_helper("[", "]") + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + items = ", ".join(tracked_repr(tx, item) for item in self.items) + return VariableTracker.build(tx, f"[{items}]") + + def reconstruct(self, codegen: "PyCodegen") -> None: + if self._contains_self_reference(): + # Self-referential list: create empty, cache, then extend + codegen.extend_output( + [ + create_instruction("BUILD_LIST", arg=0), + create_dup_top(), + ] + ) + codegen.add_cache(self) + + codegen.foreach(self.items) + codegen.extend_output( + [ + create_instruction("BUILD_LIST", arg=len(self.items)), + create_instruction("LIST_EXTEND", arg=1), + ] + ) + else: + # Non-self-referential: use simple codegen + codegen.foreach(self.items) + codegen.append_output(create_instruction("BUILD_LIST", arg=len(self.items))) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Include/internal/pycore_list.h#L55-L59 + return ListIteratorVariable(self.items, mutation_type=ValueMutationNew()) + + def sq_inplace_repeat_impl( + self, + tx: "InstructionTranslatorBase", + count: VariableTracker, + ) -> VariableTracker: + # list_inplace_repeat: https://github.com/python/cpython/blob/v3.13.13/Objects/listobject.c#L1071 + if not self.is_mutable(): + raise AssertionError( + f"sq_inplace_repeat_impl reached an immutable {type(self).__name__}; " + "every construction site should set mutation_type." + ) + n = count.as_python_constant() + try: + new_items = self.items * n + except (MemoryError, OverflowError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + tx.output.side_effects.mutation(self) + self.items[:] = new_items + return self + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "sort" and self.is_mutable(): + if len(args) != 0: + raise_args_mismatch(tx, name, "0 args", f"{len(args)} args") + key_fn_var = kwargs.pop("key", ConstantVariable.create(None)) + reverse = kwargs.pop( + "reverse", ConstantVariable.create(False) + ).as_python_constant() + if len(kwargs) != 0: + raise_args_mismatch(tx, name, "0 kwargs", f"{len(kwargs)} kwargs") + + tx.output.side_effects.mutation(self) + # CPython's list.sort detaches the list while sorting: reads + # during the sort observe an empty list, items added during the + # sort are discarded, and the mutation raises ValueError after + # the sorted result is installed. + saved = list(self.items) + self.items.clear() + + class _TracedKey: + # Compares through Dynamo so user-defined __lt__ (e.g. from + # functools.cmp_to_key) is traced like CPython's timsort, + # which only ever uses "<". + def __init__(self, key: VariableTracker) -> None: + self.key = key + + def __lt__(self, other: "_TracedKey") -> bool: + result = variables.BuiltinVariable(operator.lt).call_function( + tx, [self.key, other.key], {} + ) + if not result.is_python_constant(): + unimplemented( + gb_type="sort with non-constant keys", + context=str(self.key), + explanation=( + f"Cannot perform sort whose key comparison is not " + f"a compile-time constant. " + f"Key type: {self.key.python_type()}. " + f"Most notably, we cannot sort with Tensor or SymInt " + f"keys, but we can sort ints." + ), + hints=[ + "Use something else as the key.", + *graph_break_hints.SUPPORTABLE, + ], + ) + return bool(result.as_python_constant()) + + try: + if key_fn_var.is_constant_none(): + keys = saved + else: + keys = [key_fn_var.call_function(tx, [x], {}) for x in saved] + + if all(k.is_python_constant() for k in keys): + order = sorted( + range(len(saved)), + key=lambda i: keys[i].as_python_constant(), + reverse=reverse, + ) + else: + order = sorted( + range(len(saved)), + key=lambda i: _TracedKey(keys[i]), + reverse=reverse, + ) + new_items = [saved[i] for i in order] + except Exception as e: + self.items[:] = saved + if isinstance(e, (ObservedException, Unsupported)): + raise + raise_observed_exception(type(e), tx, args=list(e.args)) + modified_during_sort = bool(self.items) + self.items[:] = new_items + if modified_during_sort: + raise_observed_exception( + ValueError, tx, args=["list modified during sort"] + ) + return ConstantVariable.create(None) + return super().call_method(tx, name, args, kwargs) + + def tp_init_impl( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # list___init___impl: clear the list, then extend with the optional + # iterable arg. + # https://github.com/python/cpython/blob/v3.13.0/Objects/listobject.c#L2966-L2986 + if kwargs or len(args) > 1: + raise_args_mismatch( + tx, + "__init__", + "at most 1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + tx.output.side_effects.mutation(self) + self.items.clear() + if len(args) == 1: + self.call_method(tx, "extend", args, {}) + return ConstantVariable.create(None) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if name == "__class__": + source = AttrSource(self.source, name) if self.source else None + class_type = self.python_type() + if class_type is list: + return VariableTracker.build(tx, class_type, source=source) + else: + return VariableTracker.build(tx, class_type, source) + return super().tp_getattro_impl(tx, name) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + if self.python_type() is not list: + return super().call_obj_hasattr(tx, name) + return VariableTracker.build(tx, hasattr([], name)) + + def sq_ass_item_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/listobject.c#L865-L890 (list_ass_item) + if not self.is_mutable(): + return super().sq_ass_item_impl(tx, key, value) + # value=None signals delete (CPython NULL sentinel). + idx = key.nb_index_impl(tx).as_python_constant() + if not (0 <= idx < len(self.items)): + raise_observed_exception( + IndexError, tx, args=["list assignment index out of range"] + ) + try: + if value is None: + self.items.__delitem__(idx) + else: + self.items[idx] = value + except (IndexError, TypeError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + tx.output.side_effects.mutation(self) + return ConstantVariable.create(None) + + def mp_ass_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/listobject.c#L3119-L3150 (list_ass_subscript) + if not self.is_mutable(): + return super().mp_ass_subscript_impl(tx, key, value) + # value=None signals delete (CPython NULL sentinel). + if pyindex_check(key.python_type()): + i = key.nb_index_impl(tx).as_python_constant() + if i < 0: + i += len(self.items) + return self.sq_ass_item_impl(tx, ConstantVariable(i), value) + elif pyslice_check(key): + # CPython runs PySlice_Unpack first, which raises ValueError on + # step==0 before the iterable check. + key_as_const = key.as_python_constant() + if key_as_const.step == 0: + raise_observed_exception( + ValueError, tx, args=["slice step cannot be zero"] + ) + if value is None: + # delete slice + try: + self.items.__delitem__(key_as_const) + except ValueError as exc: + raise_observed_exception( + ValueError, + tx, + args=list(exc.args), + ) + tx.output.side_effects.mutation(self) + else: + # assign slice + # CPython list_ass_subscript runs PySequence_Fast on value + # before the step==1 branch, so this message applies to all + # slice forms. + if not vt_is_iterable(value): + msg = "must assign iterable to extended slice" + step = key_as_const.step + if step in (None, 1) and _cpython_has_simple_slice_bug(): + msg = "can only assign an iterable" + raise_type_error(tx, msg) + + value_unpack = unpack_iterable(tx, value) + try: + self.items[key_as_const] = value_unpack + except ValueError as exc: + raise_observed_exception( + ValueError, + tx, + args=list(exc.args), + ) + tx.output.side_effects.mutation(self) + else: + raise_type_error( + tx, + f"list indices must be integers or slices, not {key.python_type_name()}", + ) + return ConstantVariable.create(None) + + def sq_concat_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + # Implements PySequence_Concat for sequences + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/listobject.c#L725-L773 (list_concat) + if not pylist_check(other): + raise_type_error( + tx, + f"can only concatenate list (not '{other.python_type_name()}') to list", + ) + + items = self.items + unpack_iterable(tx, other) + return ListVariable(items, mutation_type=ValueMutationNew()) + + def sq_inplace_concat_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + # Implements PySequence_InPlaceConcat for sequences + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/listobject.c#L1464-L1472 + self.call_method(tx, "extend", [other], {}) + return self + + def is_hashable(self) -> bool: + return False + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + from ..exc import raise_type_error + + raise_type_error(tx, f"unhashable type: '{self.python_type_name()}'") + + +_deque_state_mutating_methods = frozenset( + { + "append", + "appendleft", + "extend", + "extendleft", + "pop", + "popleft", + "insert", + "remove", + "clear", + } +) + + +# TODO(dynamo-team): Split deque from CommonListMethodsVariable / ListVariable +class DequeVariable(CommonListMethodsVariable): + # deque_spec: https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c#L1866 + # tp_hash = PyObject_HashNotImplemented (unhashable) + _cpython_type = collections.deque + + _nonvar_fields = { + "state", + *CommonListMethodsVariable._nonvar_fields, + } + + # deque exposes a single read-only getset descriptor, maxlen. + tp_getset = { + "maxlen": GetSet(lambda self, tx: self.maxlen, None), + } + + def _rotate( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker | None: + # deque_rotate: https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c#L927 + # rotate(n=1, /) shifts n steps to the right (left if n < 0). n is + # resolved through nb_index. A deque of length <= 1 is a no-op. A + # non-mutable deque declines (returns None) so dispatch falls through + # to the object protocol, matching the old is_mutable() guard. + if not self.is_mutable(): + return None + # deque.rotate is METH_FASTCALL, so the flags derived from ml_flags + # reject kwargs but cannot bound the positional count; deque_rotate + # does that itself with _PyArg_CheckPositional. + check_positional(tx, "rotate", len(args), 0, 1) + n_vt = args[0] if args else ConstantVariable.create(1) + n = n_vt.nb_index_impl(tx).as_python_constant() + length = len(self.items) + if length > 1: + tx.output.side_effects.mutation(self) + k = n % length + if k != 0: + self.items[:] = self.items[-k:] + self.items[:-k] + self.state += 1 + return ConstantVariable.create(None) + + tp_methods = {"rotate": Method(_rotate)} + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + return self._seq_richcompare(tx, other, op, collections.deque) + + def is_hashable(self) -> bool: + return False + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + from ..exc import raise_type_error + + raise_type_error(tx, f"unhashable type: '{self.python_type_name()}'") + + @staticmethod + def validate_maxlen( + tx: "InstructionTranslatorBase", maxlen: VariableTracker + ) -> None: + # deque_init: maxlenobj != Py_None is run through PyLong_AsSsize_t + # https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c#L1729-L1736 + if isinstance(maxlen, ConstantVariable) and maxlen.value is None: + return + if pylong_as_ssize_t(tx, maxlen) < 0: + raise_observed_exception( + ValueError, tx, args=["maxlen must be non-negative"] + ) + + def __init__( + self, + items: list[VariableTracker], + maxlen: VariableTracker | None = None, + **kwargs: Any, + ) -> None: + if maxlen is None: + maxlen = ConstantVariable.create(None) + if not maxlen.is_python_constant(): + raise AssertionError( + f"maxlen must be a constant, got: {maxlen.debug_repr()}" + ) + self.maxlen = maxlen + items = list(items) + if self.maxlen.as_python_constant() is not None: + items = items[-maxlen.as_python_constant() :] + super().__init__(items, **kwargs) + # Mirrors CPython deque->state: bumped on every structural mutation so + # deque iterators can detect mutation during iteration. + self.state = 0 + + def python_type(self) -> type: + return collections.deque + + def sq_item_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # deque_item: https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c#L1888 + # CPython's sq_item takes Py_ssize_t (already int from generic_getitem's + # nb_index_impl). deque has no mp_subscript, so this is the real path. + index = key.as_python_constant() + try: + return self.items[index] + except IndexError: + raise_observed_exception(IndexError, tx, args=["deque index out of range"]) + + def sq_ass_item_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c (deque_ass_item) + if not self.is_mutable(): + return super().sq_ass_item_impl(tx, key, value) + # value=None signals delete (CPython NULL sentinel). + idx = key.nb_index_impl(tx).as_python_constant() + length = len(self.items) + if idx < 0: + idx += length + if not (0 <= idx < length): + raise_observed_exception(IndexError, tx, args=["deque index out of range"]) + tx.output.side_effects.mutation(self) + if value is None: + # deque_ass_item_lock_held bumps deque->state only on the delete + # path (deque_del_item); the set path (Py_SETREF) does not bump. + self.state += 1 + self.items.__delitem__(idx) + else: + self.items[idx] = value + return ConstantVariable.create(None) + + def sq_concat_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + # Implements PySequence_Concat for deque + # ref: https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c#L691-L699 + + if not issubclass(other.python_type(), collections.deque): + raise_type_error( + tx, + f"can only concatenate deque (not '{other.python_type_name()}') to deque", + ) + + return DequeVariable( + self.items + unpack_iterable(tx, other), + maxlen=self.maxlen, + mutation_type=ValueMutationNew(), + ) + + def sq_inplace_concat_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + # Implements PySequence_InPlaceConcat for deque + # ref: https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c#L572-L584 + self.call_method(tx, "extend", [other], {}) + return self + + def sq_inplace_repeat_impl( + self, + tx: "InstructionTranslatorBase", + count: VariableTracker, + ) -> VariableTracker: + # deque_inplace_repeat: https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c#L811 + if not self.is_mutable(): + raise AssertionError( + f"sq_inplace_repeat_impl reached an immutable {type(self).__name__}; " + "every construction site should set mutation_type." + ) + n = count.as_python_constant() + try: + new_items = self.items * n + except (MemoryError, OverflowError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + # A bounded deque drops from the left, keeping the last maxlen items + # (maxlen == 0 yields an empty deque). + maxlen = self.maxlen.as_python_constant() + if maxlen is not None: + new_items = new_items[-maxlen:] if maxlen else new_items[:0] + tx.output.side_effects.mutation(self) + self.items[:] = new_items + return self + + def debug_repr(self) -> str: + if self.maxlen.as_python_constant() is None: + return self.debug_repr_helper("deque([", "])") + return self.debug_repr_helper( + "deque([", "], maxlen=" + self.maxlen.debug_repr() + ")" + ) + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + items = ", ".join(tracked_repr(tx, item) for item in self.items) + if self.maxlen.as_python_constant() is None: + return VariableTracker.build(tx, f"{self.python_type_name()}([{items}])") + return VariableTracker.build( + tx, + f"{self.python_type_name()}([{items}], maxlen={tracked_repr(tx, self.maxlen)})", + ) + + def as_python_constant(self) -> collections.deque[Any]: + return self.python_type()( + [x.as_python_constant() for x in self.items], + maxlen=self.maxlen.as_python_constant(), + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + # To deal with self-referential sets + codegen.add_push_null( + lambda: codegen.append_output( + codegen.create_load_python_module(collections.deque) # type: ignore[arg-type] + ) + ) + codegen.append_output(create_instruction("BUILD_LIST", arg=0)) + codegen(self.maxlen) + codegen.extend_output( + [ + *codegen.create_call_function_kw(2, ("maxlen",), False), + create_dup_top(), + ] + ) + codegen.add_cache(self) + + codegen.append_output(create_dup_top()) + codegen.load_method("extend") + + codegen.foreach(self.items) + codegen.extend_output( + [ + create_instruction("BUILD_LIST", arg=len(self.items)), + *create_call_method(1), + create_instruction("POP_TOP"), + ] + ) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # __init__ resets maxlen, so it must bypass the trailing maxlen clamp + # below (which uses the pre-call maxlen captured here). + if name == "__init__": + return self.tp_init_impl(tx, args, kwargs) + + if name == "__setattr__": + # deque has no __dict__, so every attribute write raises. A name + # backed by a getset descriptor (maxlen) is read-only; anything else + # is simply absent. + attr_name = args[0].as_python_constant() + if self.lookup_tp_getset_member(attr_name) is not None: + msg = ( + f"attribute '{attr_name}' of 'collections.deque' objects " + "is not writable" + ) + else: + msg = ( + f"'collections.deque' object has no attribute '{attr_name}' " + "and no __dict__ for setting new attributes" + ) + raise_observed_exception(AttributeError, tx, args=[msg]) + + if name == "__reversed__": + # deque.__reversed__ returns a _deque_reverse_iterator that snapshots + # the current state and detects mutation during iteration. + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + return DequeReverseIteratorVariable( + list(reversed(self.items)), + self, + self.state, + mutation_type=ValueMutationNew(), + ) + + maxlen = self.maxlen.as_python_constant() + if maxlen is not None: + slice_within_maxlen = slice(-maxlen, None) + else: + slice_within_maxlen = None + + if name in ("copy", "__copy__"): + # deque_copy preserves maxlen: https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c#L890 + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + return DequeVariable( + list(self.items), + maxlen=self.maxlen, + mutation_type=ValueMutationNew(), + ) + + pre_len = len(self.items) + + if name == "extendleft" and self.is_mutable() and len(args) > 0: + if kwargs or len(args) != 1: + raise_args_mismatch( + tx, + name, + "1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + # NOTE this is inefficient, but the alternative is to represent self.items + # as a deque, which is a more intrusive change. + unpack_and_apply_fn( + tx, args[0], lambda item: self.call_method(tx, "appendleft", [item], {}) + ) + slice_within_maxlen = slice(None, maxlen) + result = ConstantVariable.create(None) + elif name == "popleft" and self.is_mutable(): + if kwargs or len(args) > 0: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + tx.output.side_effects.mutation(self) + result, *self.items[:] = self.items + elif name == "appendleft" and len(args) > 0 and self.is_mutable(): + if kwargs or len(args) != 1: + raise_args_mismatch( + tx, + name, + "1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + tx.output.side_effects.mutation(self) + self.items[:] = [args[0], *self.items] + slice_within_maxlen = slice(None, maxlen) + result = ConstantVariable.create(None) + elif name == "insert" and len(args) > 0 and self.is_mutable(): + if kwargs or len(args) != 2: + raise_args_mismatch( + tx, + name, + "2 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + if maxlen is not None and len(self.items) == maxlen: + raise_observed_exception( + IndexError, tx, args=["deque already at its maximum size"] + ) + result = super().call_method(tx, name, args, kwargs) + else: + result = super().call_method(tx, name, args, kwargs) + + # Capture growth before the maxlen clamp: extend/extendleft appended an + # item iff the length grew here (the clamp may shrink it back). + extend_appended = len(self.items) > pre_len + if ( + slice_within_maxlen is not None + and maxlen is not None + and len(self.items) > maxlen + ): + self.items[:] = self.items[slice_within_maxlen] + if name in _deque_state_mutating_methods and self.is_mutable(): + # extend/extendleft with an empty iterable append nothing -> no bump. + if name not in ("extend", "extendleft") or extend_appended: + self.state += 1 + return result + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + if self.python_type() is collections.deque: + return VariableTracker.build(tx, name in collections.deque.__dict__) + return super().call_obj_hasattr(tx, name) + + def tp_init_impl( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # deque_init: https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c#L1810 + # Re-init resets maxlen (to None unless given), clears the deque, + # then extends with the iterable. + if not self.is_mutable(): + return super().tp_init_impl(tx, args, kwargs) + iterable = args[0] if len(args) >= 1 else kwargs.pop("iterable", None) + new_maxlen = ( + args[1] + if len(args) >= 2 + else kwargs.pop("maxlen", ConstantVariable.create(None)) + ) + if len(args) > 2 or kwargs: + raise_args_mismatch(tx, "__init__") + self.validate_maxlen(tx, new_maxlen) + tx.output.side_effects.mutation(self) + self.state += 1 + self.maxlen = new_maxlen + self.items.clear() + if iterable is not None: + self.call_method(tx, "extend", [iterable], {}) + return ConstantVariable.create(None) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.3/Modules/_collectionsmodule.c#L1886-L1904 + return DequeIteratorVariable( + list(self.items), + self, + self.state, + mutation_type=ValueMutationNew(), + ) + + +class TupleVariable(BaseListVariable): + # PyTuple_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/tupleobject.c#L846 + _cpython_type = tuple + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + return self._seq_richcompare(tx, other, op, tuple) + + def python_type(self) -> type[tuple]: # type: ignore[type-arg] + return tuple + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(length={len(self.items)})" + + def debug_repr(self) -> str: + if len(self.items) == 1: + return self.debug_repr_helper("(", ",)") + return self.debug_repr_helper("(", ")") + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + items = ", ".join(tracked_repr(tx, item) for item in self.items) + if len(self.items) == 1: + items += "," + return VariableTracker.build(tx, f"({items})") + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.3/Objects/tupleobject.c#L1101-L1117 + return TupleIteratorVariable(self.items, mutation_type=ValueMutationNew()) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.foreach(self.items) + codegen.append_output(create_build_tuple(len(self.items))) + + def reconstruct_pycode(self, codegen): + if len(self.items) == 0: + return "()" + else: + return f"({', '.join([item.reconstruct_pycode(codegen) for item in self.items])},)" + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if name == "__class__": + source = AttrSource(self.source, name) if self.source else None + class_type = self.python_type() + return VariableTracker.build(tx, class_type, source=source) + return super().tp_getattro_impl(tx, name) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + if self.python_type() is not tuple: + return super().call_obj_hasattr(tx, name) + return VariableTracker.build(tx, hasattr((), name)) + + def sq_concat_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ): + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/tupleobject.c#L441-L486 (tuple_concat) + if len(self.items) == 0 and pytuple_checkexact(other): + return other + + if not pytuple_check(other): + raise_type_error( + tx, + f"can only concatenate tuple (not '{other.python_type_name()}') to tuple", + ) + + return TupleVariable( + self.items + unpack_iterable(tx, other), mutation_type=ValueMutationNew() + ) + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # CPython tuplehash: https://github.com/python/cpython/blob/e76aa128fe/Objects/tupleobject.c#L321 + # Collect per-item hashes and feed them through tuplehash. We wrap + # each hash in RawHash to bypass int.__hash__'s modular reduction, + # so tuplehash sees the original hash values — matching CPython exactly. + from .hashable import RawHash + from .object_protocol import generic_hash_impl + + is_fake = False + raw_hashes = [] + for item in self.items: + h, fake = generic_hash_impl(tx, item) + is_fake = is_fake or fake + raw_hashes.append(RawHash(h)) + return hash(tuple(raw_hashes)), is_fake + + +class SizeVariable(TupleVariable): + """torch.Size(...)""" + + _cpython_type = torch.Size + + _nonvar_fields = { + "proxy", + *TupleVariable._nonvar_fields, + } + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # torch.Size items may be TensorVariables wrapping scalar tensors with + # known constant values (node.meta["example_value"].constant). Extract + # the actual int values so the hash matches eager torch.Size hashing. + from .tensor import TensorVariable + + int_items: list[int] = [] + for item in self.items: + if item.is_python_constant(): + int_items.append(item.as_python_constant()) + continue + if isinstance(item, TensorVariable): + proxy = getattr(item, "proxy", None) + node = getattr(proxy, "node", None) + meta = getattr(node, "meta", None) if node is not None else None + example_value = ( + meta.get("example_value") if isinstance(meta, dict) else None + ) + constant = getattr(example_value, "constant", None) + if isinstance(constant, torch.Tensor) and constant.numel() == 1: + int_items.append(int(constant.item())) + continue + # Can't extract a concrete int — fall back to TupleVariable + return super().hash_impl(tx) + return hash(torch.Size(int_items)), False + + def __init__( + self, + items: list[VariableTracker], + proxy: torch.fx.Proxy | None = None, + **kwargs: Any, + ) -> None: + self.proxy = proxy + super().__init__(items, **kwargs) + + def debug_repr(self) -> str: + return self.debug_repr_helper("torch.Size([", "])") + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + items = ", ".join(tracked_repr(tx, item) for item in self.items) + return VariableTracker.build(tx, f"torch.Size([{items}])") + + def python_type(self) -> type: + return torch.Size + + def as_proxy(self) -> Any: + if self.proxy is not None: + return self.proxy + + # torch.Size needs special handling. Normally, we pun a list-like + # container to directly contain Proxy/Node objects from FX, and FX + # knows to look inside containers (via map_aggregate). But torch.Size + # is weird; although it subclasses from tuple, it doesn't allow + # members which aren't int-like (rejecting Proxy and Node). This + # means we can't use the normal representation trick + # torch.Size([proxy0, proxy1]). I looked into seeing if I could + # relax torch.Size in PyTorch proper, but if torch.Size constructor + # sees a type that it doesn't recognize, it will try to call + # __index__() on it, so there is no BC way to actually change this + # behavior (though it occurs to me that I could have just added a + # YOLO no checking alternate constructor.) + # + # To work around this problem, I represent a torch.Size proxy as + # a straight up proxy, that would have been constructed by taking + # the constituent proxies as arguments. This trick can be generally + # used for any construct that we need a proxy for but we can't + # directly represent as an aggregate; I don't see very many examples + # of this in torchdynamo though! + + # Look for a proxy. If there are none, do the legacy behavior + tracer = None + proxies = self._as_proxy() + for proxy in proxies: + if isinstance(proxy, torch.fx.Proxy): + tracer = proxy.tracer + break + + if tracer is None: + return torch.Size(proxies) + + proxy = tracer.create_proxy("call_function", torch.Size, (proxies,), {}) + set_example_value( + proxy.node, + torch.Size( + [ + p.node.meta["example_value"] if not isinstance(p, int) else p + for p in proxies + ] + ), + ) + return proxy + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen.load_import_from("torch", "Size")) + codegen.foreach(self.items) + build_torch_size = [ + create_build_tuple(len(self.items)), + ] + create_call_function(1, False) + codegen.extend_output(build_torch_size) + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase" + ) -> list[VariableTracker]: + return list(self.items) + + def numel(self, tx: "InstructionTranslatorBase") -> VariableTracker: + from .builder import SourcelessBuilder + from .tensor import SymNodeVariable + + const_result = 1 + # pyrefly: ignore [implicit-any] + sym_sizes = [] + + for v in self.items: + if v.is_python_constant(): + const_result *= v.as_python_constant() + else: + if not isinstance(v, SymNodeVariable): + raise AssertionError( + f"expected SymNodeVariable, got {type(v).__name__}" + ) + # Delay proxy calls until we know it will be necessary + sym_sizes.append(v) + + result = VariableTracker.build(tx, const_result) + if sym_sizes and const_result == 1: + # Skip multiplying by 1 + result, *sym_sizes = sym_sizes + + if not sym_sizes or const_result == 0: + return result + + mul = SourcelessBuilder.create(tx, operator.mul) + for v in sym_sizes: + result = mul.call_function(tx, [result, v], {}) + return result + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # tuple_subscript: https://github.com/python/cpython/blob/62a6e898e01/Objects/tupleobject.c#L877-L930 + try: + key_type = key.python_type() + except NotImplementedError: + key_type = None + if key_type not in (int, bool, slice): + if key_type is not None and not type_implements_nb_index(key_type): + raise_observed_exception( + TypeError, + tx, + args=[ + f"tuple indices must be integers or slices, not {key.python_type_name()}" + ], + ) + key = key.nb_index_impl(tx) + return self.get_item_dyn(tx, key) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "numel": + if args or kwargs: + raise_args_mismatch( + tx, + name, + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + return self.numel(tx) + + return super().call_method(tx, name, args, kwargs) + + def get_item_dyn( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + from .tensor import SymNodeVariable, TensorVariable + + if isinstance(arg, SymNodeVariable): + index = arg.sym_num + elif isinstance(arg, TensorVariable): + value = get_fake_value(arg.as_proxy().node, tx) + if value.constant is None or value.constant.numel() != 1: + unimplemented( + gb_type="Indexing torch.Size with non-scalar tensor", + context=f"get_item_dyn {self} {arg}", + explanation=( + "Attempted to index torch.Size with a tensor that is not a scalar constant." + ), + hints=[*graph_break_hints.USER_ERROR], + ) + index = value.constant.item() + else: + index = arg.as_python_constant() + + if isinstance(index, slice): + return SizeVariable(self.items[index]) + else: + if not isinstance(index, (int, torch.SymInt)): + raise AssertionError( + f"index must be int or SymInt, got {type(index).__name__}" + ) + return self.items[index] + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + return VariableTracker.build(tx, hasattr(torch.Size, name)) + + def sq_concat_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker + ) -> VariableTracker: + """ + Implements torch.Size concatenation via sq_concat protocol. + torch.Size accepts concatenation with any tuple-like object. + Ref: torch/csrc/Size.cpp::THPSize_concat + """ + if not pytuple_check(other): + raise_type_error( + tx, + f"can only concatenate tuple (not '{other.python_type_name()}') to torch.Size", + ) + # Size nb_add uses sq_concat. We do the opposite here because of the reverse keyword + return self.nb_add_impl(tx, other) + + def nb_add_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # NOTE: The python interpreter tries, in order: + # 1. right.nb_add(left, right) (only if right is a subclass of left) + # 2. left.nb_add(left, right) + # 3. right.nb_add(left, right) + # 4. left.sq_concat(right) + # Hence, to support tuple + size -> size, we need to implement nb_add + if not pytuple_check(other): + return ConstantVariable(NotImplemented) + self_, other_ = (other, self) if reverse else (self, other) + a, b = unpack_iterable(tx, self_), unpack_iterable(tx, other_) + return SizeVariable(list(a) + list(b), mutation_type=ValueMutationNew()) + + +class SliceVariable(VariableTracker): + # PySlice_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/sliceobject.c#L689 + _cpython_type = slice + + def __init__( + self, + items: list[VariableTracker], + tx: Optional["InstructionTranslatorBase"] = None, + **kwargs: Any, + ) -> None: + items_to_map = items + start, stop, step = [variables.ConstantVariable.create(None)] * 3 + + if len(items_to_map) == 1: + (stop,) = items_to_map + elif len(items_to_map) == 2: + start, stop = items_to_map + elif len(items_to_map) == 3: + start, stop, step = items_to_map + else: + raise AssertionError + + # Convert TensorVariable to SymIntVariable by calling .item() + # This decomposes a[:t] to u=t.item(); a[:u] at the dynamo level + if start.is_tensor(): + if tx is None: + raise AssertionError( + "tx is required when slice indices are TensorVariables" + ) + start = start.call_method(tx, "item", [], {}) + if stop.is_tensor(): + if tx is None: + raise AssertionError( + "tx is required when slice indices are TensorVariables" + ) + stop = stop.call_method(tx, "item", [], {}) + if step.is_tensor(): + if tx is None: + raise AssertionError( + "tx is required when slice indices are TensorVariables" + ) + step = step.call_method(tx, "item", [], {}) + + self.items = (start, stop, step) + + super().__init__(**kwargs) + + def debug_repr(self) -> str: + return "slice(" + ", ".join(i.debug_repr() for i in self.items) + ")" + + def as_proxy(self) -> slice: + return slice(*[x.as_proxy() for x in self.items]) + + def python_type(self) -> type: + return slice + + def as_python_constant(self) -> slice: + return slice(*[guard_if_dyn(x) for x in self.items]) + + def as_index_slice(self, tx: "InstructionTranslatorBase") -> slice: + # PySlice_Unpack -> evaluate_slice_index: each non-None member is + # coerced through __index__ (nb_index), so user objects with an + # __index__ method are valid slice bounds. + # https://github.com/python/cpython/blob/62a6e898e01/Objects/sliceobject.c#L196-L242 + members = [] + for member in self.items: + if isinstance(member, ConstantVariable) and member.value is None: + members.append(None) + continue + if not pyindex_check(maybe_get_python_type(member)): + raise_type_error( + tx, + "slice indices must be integers or None or have an __index__ method", + ) + members.append(pynumber_index(tx, member).as_python_constant()) + return slice(*members) + + def is_hashable(self) -> bool: + # Slices became hashable in Python 3.12 (CPython slicehash). + return sys.version_info >= (3, 12) + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + if sys.version_info < (3, 12): + raise_type_error(tx, "unhashable type: 'slice'") + # CPython slicehash: https://github.com/python/cpython/blob/e76aa128fe/Objects/sliceobject.c#L667 + s = self.as_python_constant() + try: + h = hash(s) + except TypeError as e: + raise_observed_exception(TypeError, tx, args=[str(e)]) + return h, False + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + """slice_richcompare: delegates all 6 ops to (start, stop, step) tuple comparison. + + https://github.com/python/cpython/blob/e76aa128fe/Objects/sliceobject.c#L667-L686 + """ + from .object_protocol import generic_richcompare + + if not isinstance(other, SliceVariable): + return ConstantVariable.create(NotImplemented) + self_tuple = TupleVariable(list(self.items)) + other_tuple = TupleVariable(list(other.items)) + return generic_richcompare(tx, self_tuple, other_tuple, op) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.foreach(self.items) + codegen.append_output(create_instruction("BUILD_SLICE", arg=len(self.items))) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if name in cmp_name_to_op_mapping or name in ("__hash__", "indices"): + return variables.GetAttrVariable( + self, name, py_type=type(getattr(slice, name)) + ) + fields = ["start", "stop", "step"] + if name not in fields: + unimplemented( + gb_type="Unsupported attribute for slice() object", + context=f"tp_getattro_impl {self} {name}", + explanation=f"Expected attribute to be one of {','.join(fields)} " + f"but got {name}", + hints=[*graph_break_hints.USER_ERROR], + ) + return self.items[fields.index(name)] + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "indices": + if len(args) != 1 or kwargs: + raise_args_mismatch( + tx, + name, + "1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + + length_var = args[0].nb_index_impl(tx) + length = length_var.as_python_constant() + items: list[int | None] = [] + for item in self.items: + if item.is_constant_none(): + items.append(None) + else: + idx_var = item.nb_index_impl(tx) + items.append(idx_var.as_python_constant()) + + try: + result = slice(*items).indices(length) + except (ValueError, TypeError) as e: + raise_observed_exception(type(e), tx, args=list(e.args)) + return VariableTracker.build(tx, result) + + return super().call_method(tx, name, args, kwargs) + + +class ListIteratorVariable(IteratorVariable): + # PyListIter_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/listobject.c#L3842 + _cpython_type = type(iter([])) + + _nonvar_fields = { + "index", + *IteratorVariable._nonvar_fields, + } + + def __init__( + self, items: list[VariableTracker], index: int = 0, **kwargs: Any + ) -> None: + super().__init__(**kwargs) + if not isinstance(items, list): + raise AssertionError(f"items must be a list, got {type(items).__name__}") + # Removing this check as it slows things down too much + # https://github.com/pytorch/pytorch/pull/87533#issuecomment-1287574492 + + # assert all(isinstance(x, VariableTracker) for x in items) + self.items = items + self.index = index + self.is_exhausted = False + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(length={len(self.items)}, index={repr(self.index)})" + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/6280bb547840b609feedb78887c6491af75548e8/Objects/listobject.c#L4110-L4133 + if not self.is_mutable(): + raise AssertionError("ListIteratorVariable must be mutable to iterate") + old_index = self.index + if old_index >= len(self.items) or self.is_exhausted: + self.is_exhausted = True + raise_observed_exception(StopIteration, tx) + + tx.output.side_effects.mutation(self) + self.index += 1 + return self.items[old_index] + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + return VariableTracker.build(tx, hasattr(iter([]), name)) + + def python_type(self) -> type: + return type(iter([])) + + def as_python_constant(self) -> Any: + if self.index > 0: + raise NotImplementedError + return iter([x.as_python_constant() for x in self.items]) + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase" + ) -> list[VariableTracker]: + if self.is_exhausted: + return [] + self.is_exhausted = True + return list(self.items[self.index :]) + + def reconstruct(self, codegen: "PyCodegen") -> None: + # starting in 3.15 GET_ITER creates virtual iterators (see https://github.com/python/cpython/issues/145668), so use builtin iter instead + codegen.add_push_null( + lambda: codegen.append_output(codegen.create_load_python_module(iter)) # type: ignore[arg-type] + ) + if not self.is_exhausted: + remaining_items = self.items[self.index :] + else: + # pyrefly: ignore [implicit-any] + remaining_items = [] + codegen.foreach(remaining_items) + codegen.append_output(create_build_tuple(len(remaining_items))) + codegen.extend_output(create_call_function(1, False)) + + +class TupleIteratorVariable(ListIteratorVariable): + # PyTupleIter_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/tupleobject.c#L1067 + _cpython_type = type(iter(())) + + +class DequeIteratorVariable(ListIteratorVariable): + _cpython_type = type(iter(collections.deque())) + + _nonvar_fields = { + "saved_state", + *ListIteratorVariable._nonvar_fields, + } + + def __init__( + self, + items: list[VariableTracker], + source_deque: "DequeVariable", + saved_state: int, + index: int = 0, + **kwargs: Any, + ) -> None: + super().__init__(items, index=index, **kwargs) + self.source_deque = source_deque + self.saved_state = saved_state + + def _check_mutation(self, tx: "InstructionTranslatorBase") -> None: + if self.source_deque.state != self.saved_state: + raise_observed_exception( + RuntimeError, tx, args=["deque mutated during iteration"] + ) + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + self._check_mutation(tx) + return super().tp_iternext_impl(tx) + + def python_type(self) -> type: + return type(iter(collections.deque())) + + +class DequeReverseIteratorVariable(DequeIteratorVariable): + _cpython_type = type(reversed(collections.deque())) + + def python_type(self) -> type: + return type(reversed(collections.deque())) + + +class RangeIteratorVariable(IteratorVariable): + # PyRangeIter_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/rangeobject.c#L896 + _cpython_type = type(iter(range(0))) + + def __init__( + self, start: int, stop: int, step: int, len_: int, **kwargs: Any + ) -> None: + super().__init__(**kwargs) + self.start = start + self.stop = stop + self.step = step + self.len = len_ + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + """Range iterators are their own iterator.""" + return self + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + if self.python_type() is range_iterator: + ri = iter(range(0)) + return VariableTracker.build(tx, hasattr(ri, name)) + return super().call_obj_hasattr(tx, name) + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.3/Objects/rangeobject.c#L1072-L1091 + if self.len <= 0: + raise_observed_exception(StopIteration, tx) + + self.len -= 1 + current = self.start + self.start += self.step + return VariableTracker.build(tx, current) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "__setstate__": + # rangeiter_setstate clamps the arg against the current remaining + # length, then advances: r->start += arg*step; r->len -= arg. + # ref: https://github.com/python/cpython/blob/v3.13.3/Objects/rangeobject.c#L1093-L1107 + if len(args) != 1 or kwargs: + raise_args_mismatch( + tx, + name, + "1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + arg = args[0].as_python_constant() + index = min(max(arg, 0), self.len) + self.start += index * self.step + self.len -= index + return ConstantVariable.create(None) + elif name == "__length_hint__": + # rangeiter_len: remaining items. + # ref: https://github.com/python/cpython/blob/v3.13.3/Objects/rangeobject.c#L1109-L1115 + return ConstantVariable.create(self.len) + return super().call_method(tx, name, args, kwargs) + + def python_type(self) -> type: + return range_iterator + + def reconstruct(self, codegen: "PyCodegen") -> None: + # starting in 3.15 GET_ITER creates virtual iterators (see https://github.com/python/cpython/issues/145668), so use builtin iter instead + codegen.add_push_null( + lambda: codegen.append_output(codegen.create_load_python_module(iter)) # type: ignore[arg-type] + ) + codegen.add_push_null( + lambda: codegen.append_output(codegen.create_load_python_module(range)) # type: ignore[arg-type] + ) + codegen.append_output(codegen.create_load_const(self.start)) + codegen.append_output(codegen.create_load_const(self.stop)) + codegen.append_output(codegen.create_load_const(self.step)) + codegen.extend_output(create_call_function(3, False)) + codegen.extend_output(create_call_function(1, False)) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/memory.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/memory.py new file mode 100644 index 0000000000000000000000000000000000000000..0edeaca58b6695951026f580215b991922cfd816 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/memory.py @@ -0,0 +1,214 @@ +from contextlib import ExitStack +from typing import Any, TYPE_CHECKING + +import torch +from torch.fx import has_side_effect, Proxy + +from ..bytecode_transformation import create_call_function +from ..exc import raise_type_error, unimplemented +from ..graph_bytecode_inputs import get_external_object_by_index +from ..guards import GuardBuilder, install_guard +from ..source import AttrSource, CallFunctionNoArgsSource, ImportSource +from .base import Member, VariableTracker +from .constant import ConstantVariable +from .ctx_manager import ContextWrappingVariable + + +if TYPE_CHECKING: + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + from ..codegen import PyCodegen + +from torch._library.custom_ops import custom_op + + +def _get_mempool_by_index(index: int) -> torch.cuda.MemPool: + mempool = get_external_object_by_index(index) + if not isinstance(mempool, torch.cuda.MemPool): + raise RuntimeError( + f"use_mem_pool expected a torch.cuda.MemPool object at index {index}" + ) + return mempool + + +def _current_cuda_device_source() -> CallFunctionNoArgsSource: + return CallFunctionNoArgsSource( + AttrSource(AttrSource(ImportSource("torch"), "cuda"), "current_device") + ) + + +# These marker ops are intentional even though Inductor also annotates enclosed +# FX nodes. The annotations tell Inductor which scheduler nodes allocate in a +# user pool, while begin/end keep the pool lifetime visible as ordered FX +# side-effects for non-Inductor backends. +@custom_op("mempool::begin", mutates_args=()) +def begin_mempool(device_index: int, mempool_index: int) -> None: + mempool = _get_mempool_by_index(mempool_index) + torch.cuda.memory._cuda_beginAllocateCurrentThreadToPool(device_index, mempool.id) + + +@begin_mempool.register_fake +def _(device_index: int, mempool_index: int) -> None: + pass + + +has_side_effect(torch.ops.mempool.begin.default) + + +@custom_op("mempool::end", mutates_args=()) +def end_mempool(device_index: int, mempool_index: int) -> None: + mempool = _get_mempool_by_index(mempool_index) + torch.cuda.memory._cuda_endAllocateToPool(device_index, mempool.id) + torch.cuda.memory._cuda_releasePool(device_index, mempool.id) + + +@end_mempool.register_fake +def _(device_index: int, mempool_index: int) -> None: + pass + + +has_side_effect(torch.ops.mempool.end.default) + + +class CUDAMemPoolVariable(VariableTracker): + """Represents a torch.cuda.MemPool object.""" + + def __init__( + self, + proxy: Proxy, + value: torch.cuda.MemPool, + user_object_index: int, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.proxy = proxy + self.value = value + self.user_object_index = user_object_index + + def python_type(self) -> type: + return torch.cuda.MemPool + + def get_real_python_backed_value(self) -> object: + return self.value + + def _id(self, tx: "InstructionTranslatorBase") -> VariableTracker: + if self.source: + install_guard(self.source.make_guard(GuardBuilder.ID_MATCH)) + return ConstantVariable.create(self.value.id) + + tp_members = { + "id": Member(_id), + } + + def as_proxy(self) -> Proxy: + return self.proxy + + def reconstruct(self, codegen: "PyCodegen") -> None: + if self.source: + return super().reconstruct(codegen) + + codegen.add_push_null( + lambda: codegen.load_import_from( + torch._dynamo.graph_bytecode_inputs.__name__, + "get_external_object_by_index", + ) + ) + codegen.append_output(codegen.create_load_const(self.user_object_index)) + codegen.extend_output(create_call_function(1, False)) + + +class CUDAMemPoolContextVariable(ContextWrappingVariable): + """Represents the torch.cuda.use_mem_pool context manager.""" + + def __init__( + self, + mempool: CUDAMemPoolVariable, + device_index: int, + **kwargs: Any, + ) -> None: + self.mempool = mempool + self.device_index = device_index + super().__init__(target_values=(), initial_values=None, **kwargs) + + @staticmethod + def create( + tx: "InstructionTranslatorBase", + mempool: VariableTracker, + device: VariableTracker | None = None, + **kwargs: Any, + ) -> "CUDAMemPoolContextVariable": + if not isinstance(mempool, CUDAMemPoolVariable): + raise_type_error( + tx, + "torch.cuda.use_mem_pool() expected a torch.cuda.MemPool argument", + ) + + if device is None or ( + isinstance(device, ConstantVariable) and device.value is None + ): + install_guard( + _current_cuda_device_source().make_guard(GuardBuilder.EQUALS_MATCH) + ) + device_index = torch.cuda.current_device() + elif device.is_python_constant(): + device_index = torch.cuda._utils._get_device_index( + device.as_python_constant() + ) + else: + unimplemented( + gb_type="torch.cuda.use_mem_pool with non-constant device", + context=f"device={device}", + explanation="Dynamo requires the device argument to torch.cuda.use_mem_pool to be a Python constant.", + hints=[], + ) + + return CUDAMemPoolContextVariable(mempool, device_index, **kwargs) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + stack = ExitStack() + stack.enter_context( + torch.fx.traceback.annotate( + { + "mempool": self.mempool.user_object_index, + "mempool_device": self.device_index, + } + ) + ) + stack.enter_context(torch.fx.traceback.preserve_node_meta()) + self.set_cleanup_hook(tx, lambda: stack.close()) + tx.output.create_proxy( + "call_function", + torch.ops.mempool.begin, + (self.device_index, self.mempool.user_object_index), + {}, + ) + return ConstantVariable.create(None) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + tx.output.create_proxy( + "call_function", + torch.ops.mempool.end, + (self.device_index, self.mempool.user_object_index), + {}, + ) + self.cleanup_assert() + return ConstantVariable.create(None) + + def module_name(self) -> str: + return "torch.cuda" + + def fn_name(self) -> str: + return "use_mem_pool" + + def reconstruct_type(self, codegen: "PyCodegen") -> None: + # Supporting graph breaks safely requires reconstructing the eager + # torch.cuda.use_mem_pool context on the resume path while keeping the + # compiled begin/end marker ops balanced around each compiled segment. + unimplemented( + gb_type="torch.cuda.use_mem_pool graph break", + context=str(self), + explanation="Dynamo doesn't support graph breaks inside torch.cuda.use_mem_pool.", + hints=[], + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/misc.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..59746cba4e47584d601f478939866987358fcfbe --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/misc.py @@ -0,0 +1,3023 @@ +""" +This module contains miscellaneous variable tracker implementations for various Python types +and features used in Dynamo's symbolic execution. These classes help track and propagate +information about different kinds of variables during graph capture. + +Key classes include: +- SuperVariable: Handles super() calls and method resolution +- ExceptionVariable: Tracks exception objects +- RandomVariable: Manages random number generators +- GetAttrVariable: Tracks attribute access +- MethodWrapperVariable: Handles method wrappers +- PythonModuleVariable: Tracks Python modules +- NumpyVariable: Handles numpy functions and types +- StringFormatVariable: Manages string formatting +- DebuggingVariable: Handles print and logging +""" + +import builtins +import contextvars +import dataclasses +import enum +import functools +import inspect +import itertools +import logging +import random +import re +import sys +import traceback +import types +import weakref +from collections.abc import Callable, Sequence +from random import Random +from types import BuiltinFunctionType +from typing import Any, TYPE_CHECKING, TypeGuard, Union + +import torch._C +import torch._numpy as tnp +import torch.utils._pytree as pytree +from torch._dynamo.variables.base import MutationType +from torch._dynamo.variables.lists import TupleVariable +from torch._guards import Source + +from .. import config, graph_break_hints, trace_rules, variables +from ..bytecode_transformation import ( + create_call_function, + create_call_function_ex, + create_instruction, +) +from ..create_parameter_op import do_not_convert_to_tracable_parameter +from ..exc import ( + raise_observed_exception, + raise_type_error, + raise_value_error, + unimplemented, +) +from ..guards import GuardBuilder, install_guard +from ..mutation_guard import unpatched_nn_module_init +from ..source import ( + AttrSource, + GenericAttrSource, + GetItemSource, + TypeMROSource, + TypeSource, + WeakRefCallSource, +) +from ..utils import ( + check_positional, + check_unspec_or_constant_args, + identity, + istype, + no_keywords, + proxy_args_kwargs, + raise_args_mismatch, + unpack_iterable, +) +from .base import ( + AsPythonConstantNotImplementedError, + getset_build, + getset_read, + Member, + Method, + NO_SUCH_SUBOBJ, + VariableTracker, +) +from .constant import ConstantVariable +from .functions import NestedUserFunctionVariable, UserFunctionVariable +from .object_protocol import generic_str +from .user_defined import call_random_fn, is_standard_setattr, UserDefinedObjectVariable + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + +class SuperVariable(VariableTracker): + # PySuper_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/typeobject.c#L11511 + _cpython_type = super + + _nonvar_fields = { + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + typevar: VariableTracker, + objvar: VariableTracker | None = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + # typevar is the first argument to super(). In the case where no argument + # is provided to super(), it is the __class__ object where + # the super() function is being called + self.typevar = typevar + # objvar here must be an instance or subtype of typevar. + # In the case where super() is called without arguments, it is the first argument + # to the current function where super() is called from (self for regular method, + # cls for a classmethod) + self.objvar = objvar + + def python_type(self) -> type: + return builtins.super + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen(variables.BuiltinVariable(super))) + codegen(self.typevar) + if self.objvar is not None: + codegen(self.objvar) + codegen.extend_output(create_call_function(2, False)) + else: + codegen.extend_output(create_call_function(1, False)) + + def _resolved_getattr_and_source( + self, tx: "InstructionTranslatorBase", name: str + ) -> tuple[Any, AttrSource | None]: + if not self.objvar: + unimplemented( + gb_type="1-arg super not implemented", + context="", + explanation=f"Dynamo failed to trace attribute `{name}` accessed " + f"via `super()` (for type `{self.typevar}` and object `{self.objvar}`) " + "because one-argument of super() is not supported.", + hints=[ + "Use two-argument super(type, object_or_type).", + ], + ) + if self.objvar is None: + raise AssertionError("super() requires objvar to be set") + search_type = self.typevar.as_python_constant() + + # The rest of this function does two things: + # - Walk the mro to find where the attribute comes from to be + # able to provide accurate source + # - Call the getattr to get the object + + # Find the class object, where the function lives. + # When objvar is "self", use type(self), when objvar is "cls", use it as-is + type_to_use = self.objvar.python_type() + type_to_use_source: Source | None = ( + TypeSource(self.objvar.source) if self.objvar.source else None + ) + if issubclass(type_to_use, type): + type_to_use = self.objvar.value # type: ignore[attr-defined] + type_to_use_source = self.objvar.source + + source = None + search_mro = type_to_use.__mro__ + + try: + start_index = search_mro.index(search_type) + 1 + except ValueError: + # Corner case where the typevar is not in the mro of the objvar + # https://github.com/python/cpython/blob/3.11/Objects/typeobject.c#L8843-L8844 + return getattr(super(search_type, type_to_use), name), None + # Implemented based on https://github.com/python/cpython/blob/3.11/Objects/typeobject.c#L8812 + # super has its getattro implementation. The key point is that instead of calling getattr, it checks the + # attribute in the class __dict__ + for index in range(start_index, len(search_mro)): + # Don't call getattr, just check the __dict__ of the class + if resolved_getattr := search_mro[index].__dict__.get(name, NO_SUCH_SUBOBJ): + if resolved_getattr is not NO_SUCH_SUBOBJ: + # Equivalent of something like type(L['self']).__mro__[1].attr_name + if type_to_use_source: + source = AttrSource( + GetItemSource(TypeMROSource(type_to_use_source), index), + name, + ) + return resolved_getattr, source + + unimplemented( + gb_type="Unable to resolve super getattr", + context="", + explanation=f"Dynamo failed to trace attribute `{name}` accessed " + f"via `super()` (for type `{self.typevar}` and object `{self.objvar}`) " + "because the resolved attribute type is not supported.", + hints=[ + "Ensure the attribute exists in the parent class.", + "Check the arguments passed to `super()`.", + ], + ) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + # Check if getattr is a constant. If not, delay the actual work by + # wrapping the result in GetAttrVariable. Mostly super is called with a + # method, so most of the work is delayed to call_function. + # + # We could have just implemented a const_getattr. However, super is + # special when it comes to finding sources. Compared to other VTs, super + # requires the attr name to walk the mro and find the actual source (and + # not just AttrSource). + value, source = self._resolved_getattr_and_source(tx, name) + if not variables.ConstantVariable.is_literal(value): + return GetAttrVariable(self, name, py_type=type(value)) + if source: + install_guard(source.make_guard(GuardBuilder.CONSTANT_MATCH)) + return variables.ConstantVariable.create(value, source=source) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + inner_fn, source = self._resolved_getattr_and_source(tx, name) + if self.objvar is None: + raise AssertionError("super() requires objvar to be set for method calls") + # This essentially simulates CPython's `super_getattro`: + # https://github.com/python/cpython/blob/a1c52d1265c65bcf0d9edf87e143843ad54f9b8f/Objects/typeobject.c#L11138-L11168 + # where `inner_fn` is the VT for `res = _super_lookup_descr(...)`. + # + # However, `res`'s type needs to be checked for `tp_descr_get`, and + # applied if it has one. We currently don't have polyfills for all the + # relevant `tp_descr_get`, so we explicitly handle the cases we care + # about here (e.g., note the staticmethod, classmethod cases). + if inner_fn is object.__init__: + return LambdaVariable(identity) + elif inner_fn is torch.nn.Module.__init__: + objvar = self.objvar + from ..side_effects import AttributeMutationNew + + if ( + isinstance(objvar, variables.UserDefinedObjectVariable) + and isinstance(objvar.mutation_type, AttributeMutationNew) + and not (args or kwargs) + ): + with do_not_convert_to_tracable_parameter(): + fn_vt = VariableTracker.build( + tx, unpatched_nn_module_init, source=source + ) + return fn_vt.call_function(tx, [self.objvar] + args, kwargs) + else: + unimplemented( + gb_type="Unsupported super().__init__() call", + context=f"call_method {self} {name} {args} {kwargs}", + explanation="Dynamo encountered a super().__init__() call " + f"on {objvar} that resolved to a `torch.nn.Module.__init__()` " + "call that we cannot trace.", + hints=[*graph_break_hints.DIFFICULT], + ) + elif ( + self.objvar.source + and hasattr(inner_fn, "__name__") + and inner_fn.__name__ == "__new__" + and variables.UserDefinedClassVariable.is_supported_new_method(inner_fn) + ): + user_cls = inner_fn.__self__ + if hasattr(user_cls, "__module__") and user_cls.__module__ == "builtins": + user_cls_vt: VariableTracker = VariableTracker.build(tx, user_cls) + else: + if source is None: + raise AssertionError( + "source must not be None for user-defined class" + ) + user_cls_source = source.member + user_cls_vt = variables.UserDefinedClassVariable( + user_cls, source=user_cls_source + ) + return user_cls_vt.call_method(tx, "__new__", args, kwargs) + elif isinstance(inner_fn, staticmethod) and isinstance( + inner_fn.__func__, types.FunctionType + ): + fn_vt = VariableTracker.build( + tx, inner_fn.__func__, source=source, realize=True + ) + return fn_vt.call_function(tx, args, kwargs) + elif isinstance(inner_fn, classmethod) and isinstance( + inner_fn.__func__, types.FunctionType + ): + if isinstance(self.objvar, variables.UserDefinedClassVariable): + # super().classmethod is called from a classmethod itself. So, + # super was converted to super(__class__, cls) in bytecode and + # therefore we have to propagate the cls. + cls_variable = self.objvar + else: + # current function is an instance method, therefore super was + # converted to super(__class__, self). We have to find + # type(self) to bind the cls to the parent classmethod. + # Note that it can't be the self.typevar because __class__ is + # the class where the method is defined, which could be + # different from type(self) with polymorphism. + cls_source = None + if self.objvar.source: + cls_source = TypeSource(self.objvar.source) + cls_variable = VariableTracker.build( + tx, + self.objvar.value_type, # type: ignore[attr-defined] + cls_source, + ) + if source is None: + raise AssertionError( + "source must not be None for classmethod resolution" + ) + fn_vt = VariableTracker.build( + tx, + inner_fn.__func__, + source=AttrSource(source, "__func__"), + realize=True, + ) + return fn_vt.call_function(tx, [cls_variable, *args], kwargs) + elif isinstance(inner_fn, types.FunctionType): + fn_vt = VariableTracker.build(tx, inner_fn, source=source, realize=True) + return fn_vt.call_function(tx, [self.objvar] + args, kwargs) + elif isinstance(inner_fn, types.MethodType): + return variables.UserMethodVariable( + inner_fn.__func__, self.objvar, source=source + ).call_function(tx, args, kwargs) + elif is_standard_setattr(inner_fn) and isinstance( + self.objvar, UserDefinedObjectVariable + ): + # type: ignore[arg-type] + return self.objvar.method_setattr_standard(tx, *args, **kwargs) + elif inner_fn is object.__delattr__: + attr = args[0] + try: + attr = attr.as_python_constant() + except NotImplementedError as exc: + unimplemented( + gb_type="Non-constant attribute given to `super().__delattr__()`", + context=f"call_method {self} {name}", + explanation="Dynamo requires the attribute name passed to " + "`super().__delattr__(...)` to be a constant (string).", + hints=[ + "Ensure the attribute name is a string literal or a constant variable." + ], + from_exc=exc, + ) + if not tx.output.side_effects.is_attribute_mutation(self.objvar): + unimplemented( + gb_type="Attempted super().__delattr__() on an object without mutation tracking", + context=f"call_method {self} {name}", + explanation="Dynamo needs to track mutations on an object " + "before `super().__delattr__` can be used on it. But the " + f"object ({self.objvar}) doesn't have attribute mutation " + "tracking enabled.", + hints=[ + "Ensure the object is tracked by Dynamo's side effect system.", + *graph_break_hints.DYNAMO_BUG, + ], + ) + if not isinstance(attr, str): + raise AssertionError(f"attr must be a str, got {type(attr)}") + tx.output.side_effects.store_attr( + self.objvar, attr, variables.DeletedVariable() + ) + return variables.ConstantVariable.create(None) + elif ( + isinstance(self.objvar, variables.UserDefinedObjectVariable) + and self.objvar._base_vt is not None + and self.objvar._base_methods is not None + and inner_fn in self.objvar._base_methods + ): + return self.objvar._base_vt.call_method(tx, name, args, kwargs) + elif inner_fn is object.__getattribute__: + attr_name = args[0].value # type: ignore[attr-defined] + # object.__getattribute__ IS PyObject_GenericGetAttr. Delegate + # to the shared implementation so that __dict__, __class__, + # polyfilled C descriptors, etc. are all handled consistently. + if isinstance(self.objvar, UserDefinedObjectVariable): + return self.objvar.generic_getattr(tx, attr_name) + + attr_value = None + try: + attr_value = object.__getattribute__( + self.objvar.value, # pyrefly: ignore[missing-attribute] + attr_name, + ) + except AttributeError: + raise_observed_exception(AttributeError, tx) + + attr_source = None + if self.objvar.source is not None: + attr_source = GenericAttrSource(self.objvar.source, attr_name) + return VariableTracker.build(tx, attr_value, attr_source) + elif inner_fn is torch._C._disabled_torch_function_impl: + # See `THPModule_disable_torch_function` for the C impl. + # The signature of _disabled_torch_function_impl is similar to + # `__torch_function__`, just without the first `cls` argument: + # * (func, types, args, kwargs) + func = args[0] + # pyrefly: ignore [implicit-any] + tf_kwargs = {} + tf_args = args[2].items # type: ignore[attr-defined] + # type: ignore[attr-defined] + for hash_key_vt, value_vt in args[3].items.items(): + key_str = hash_key_vt.vt.as_python_constant() + tf_kwargs[key_str] = value_vt + + tx_old = tx.symbolic_torch_function_state.torch_function_subclass_enabled + tx.symbolic_torch_function_state.torch_function_subclass_enabled = False + try: + return func.call_function(tx, tf_args, tf_kwargs) + finally: + tx.symbolic_torch_function_state.torch_function_subclass_enabled = ( + tx_old + ) + elif ( + isinstance(inner_fn, types.MethodDescriptorType) + and inner_fn in trace_rules.get_tensor_method() + ): + # FunctionType but implementation is in C, we support some of these, + # e.g., tensor ops like `torch.Tensor.to`. + fn_var = VariableTracker.build(tx, inner_fn, source, realize=True) + return fn_var.call_function(tx, [self.objvar] + args, kwargs) + elif isinstance(inner_fn, types.BuiltinFunctionType): + fn_vt = VariableTracker.build(tx, inner_fn, source=source, realize=True) + return fn_vt.call_function(tx, args, kwargs) + + unimplemented( + gb_type="Attempted to call a super() attribute that is " + "not a function or method", + context=f"call_method {self} {name}", + explanation="Dynamo does not know how to trace the call " + f"`super().{name}()` because `super().{name}` is not a " + "function or method attribute.", + hints=[ + "Ensure the attribute accessed via `super()` is a standard method or function.", + ], + ) + + +class FrameSummaryVariable(VariableTracker): + def __init__(self, frame_summary: traceback.FrameSummary, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.frame_summary = frame_summary + + def python_type(self) -> type: + return traceback.FrameSummary + + # traceback.FrameSummary is pure-Python with __slots__ (Lib/traceback.py); + # each slot is exposed as a read-only member_descriptor. + tp_members = { + "lineno": Member(getset_build(lambda s: s.frame_summary.lineno)), + "filename": Member(getset_build(lambda s: s.frame_summary.filename)), + "name": Member(getset_build(lambda s: s.frame_summary.name)), + "line": Member(getset_build(lambda s: s.frame_summary.line)), + } + + +class TracebackVariable(VariableTracker): + def __init__( + self, + frame_summary: FrameSummaryVariable, + tb_next: Union["TracebackVariable", ConstantVariable], + **kwargs: Any, + ) -> None: + # The traceback holds four attributes: + # - tb_frame + # - tb_lineno + # - tb_lasti + # - tb_next + + super().__init__(**kwargs) + self.frame_summary = frame_summary + # the next traceback in the chain + if tb_next is None: + raise AssertionError("tb_next must not be None") + self.tb_next = tb_next + + @classmethod + def from_frame_summary( + cls, + frame_summary: traceback.FrameSummary, + tb_next: Union["TracebackVariable", ConstantVariable], + ) -> "TracebackVariable": + return cls(FrameSummaryVariable(frame_summary), tb_next=tb_next) + + @staticmethod + def is_valid_traceback(obj: VariableTracker) -> bool: + return istype(obj, TracebackVariable) or obj.is_constant_none() + + def extract_tb(self) -> list[traceback.FrameSummary | FrameSummaryVariable]: + if istype(self.tb_next, ConstantVariable): + return [self.frame_summary] + return [self.frame_summary] + self.tb_next.extract_tb() + + def has_reference_cycle(self, tb: VariableTracker) -> bool: + # checks if `tb` is in the chain of tb_next starting from `self` + curr_tb: TracebackVariable | ConstantVariable = self + while istype(curr_tb, TracebackVariable): + if curr_tb is tb: + return True + curr_tb = curr_tb.tb_next + return False + + def python_type(self) -> type[types.TracebackType]: + return types.TracebackType + + def call_setattr( + self, + tx: "InstructionTranslatorBase", + name_var: VariableTracker, + val: VariableTracker, + ) -> VariableTracker: + name = name_var.as_python_constant() + if name == "tb_next": + if not self.is_valid_traceback(val): + raise_observed_exception(TypeError, tx) + if not isinstance(val, (TracebackVariable, ConstantVariable)): + raise AssertionError( + f"tb_next val must be TracebackVariable or ConstantVariable, got {type(val)}" + ) + if self.has_reference_cycle(val) or ( + istype(val, TracebackVariable) and val.has_reference_cycle(self) + ): + raise_observed_exception(ValueError, tx) + self.tb_next = val + return variables.ConstantVariable.create(None) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if name == "tb_next": + return self.tb_next + elif name == "tb_lineno": + return self.frame_summary.tp_getattro_impl(tx, "lineno") + elif name == "frame_summary": + return self.frame_summary + elif name == "tb_lasti": + unimplemented( + gb_type="traceback.tb_lasti not supported", + context=f"{self} accessing 'tb_lasti'", + explanation="Dynamo does not support accessing the tb_lasti attribute of traceback objects.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + return super().tp_getattro_impl(tx, name) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: "VariableTracker", op: str + ) -> "VariableTracker": + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "__setattr__": + return self.call_setattr(tx, *args) + return super().call_method(tx, name, args, kwargs) + + +class ExceptionVariable(VariableTracker): + # _PyExc_BaseException: https://github.com/python/cpython/blob/v3.13.0/Objects/exceptions.c + _cpython_type = BaseException + + # The ExceptionVariable corresponds to the BaseException class in Python + def __init__( + self, + exc_type: Any, + args: list[VariableTracker], + init_kwargs: dict[str, VariableTracker] | None = None, + source: Source | None = None, + mutation_type: MutationType | None = None, + ) -> None: + super().__init__(source=source, mutation_type=mutation_type) + self.exc_type = exc_type + self.args = args + if init_kwargs: + unimplemented( + gb_type="Keyword args passed to exception constructor", + context=f"{self} with kwargs {init_kwargs}", + explanation="Dynamo does not know how to handle keyword args passed to an exception constructor", + hints=[*graph_break_hints.SUPPORTABLE], + ) + # When raising a new exception while another exception is already being + # handled, the new exception's __context__ attribute is automatically + # set to the handled exception. + self.__context__: VariableTracker = ConstantVariable.create(None) + # Set when user raised an exception from another: + # raise ... from ... + self.__cause__: VariableTracker = ConstantVariable.create(None) + # Boolean flag that controls whether the __context__ attribute is set + self.__suppress_context__: VariableTracker = ConstantVariable.create(False) + # Contains the call stack where the exception was raised. + self.__traceback__: VariableTracker = ConstantVariable.create(None) + # The user stack at the time this exception was first raised. + # Used to preserve the original exception location when re-raising. + self.python_stack: traceback.StackSummary | None = None + + def set_context(self, context: VariableTracker) -> None: + self.__context__ = context + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from("builtins", self.exc_type.__name__) + ) + codegen.foreach(self.args) + codegen.call_function(len(self.args), False) + + def codegen_attr(name: str) -> None: + attr = getattr(self, name) + if istype(attr, ConstantVariable): + if attr.value not in (True, False, None): + raise AssertionError( + f"attr.value must be True, False, or None, got {attr}" + ) + else: + codegen.dup_top() + codegen(attr) + codegen.extend_output(codegen.rot_n(2)) + codegen.store_attr(name) + + codegen_attr("__context__") + codegen_attr("__cause__") + codegen_attr("__suppress_context__") + + def python_type(self) -> type: + return self.exc_type + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: "VariableTracker", op: str + ) -> "VariableTracker": + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "__setattr__": + name = args[0].as_python_constant() + val = args[1] + if name == "__context__": + # Constant can be either an Exceptior or None + if not ( + val.is_constant_none() + or isinstance( + val, + ( + variables.ExceptionVariable, + variables.UserDefinedExceptionClassVariable, + variables.UserDefinedExceptionObjectVariable, + ), + ) + ): + raise_type_error( + tx, + "exception context must be None or derive from BaseException", + ) + self.set_context(val) + elif name == "__cause__": + if val.is_constant_none() or isinstance( + val, + ( + variables.BuiltinVariable, + variables.ExceptionVariable, + variables.UserDefinedExceptionClassVariable, + variables.UserDefinedExceptionObjectVariable, + ), + ): + self.__cause__ = val + self.__suppress_context__ = variables.ConstantVariable.create(True) + else: + raise_type_error( + tx, "exception cause must be None or derive from BaseException" + ) + elif name == "__suppress_context__": + if val.is_constant_match(True, False): + self.__suppress_context__ = val + else: + raise_type_error( + tx, "exception cause must be None or derive from BaseException" + ) + elif name == "__traceback__": + if not TracebackVariable.is_valid_traceback(val): + raise_type_error(tx, "__traceback__ must be a traceback or None") + self.__traceback__ = val + elif name == "args": + # CPython coerces any iterable to a tuple (PySequence_Tuple). + self.args = unpack_iterable(tx, val) + else: + # Arbitrary user attribute -> store in the instance __dict__ + # via the side effects table. + se = tx.output.side_effects + if not se.is_attribute_mutation(self): + se.track_attribute_mutation_new(self) + se.store_instance_dict_attr(self, name, val) + return variables.ConstantVariable.create(None) + elif name == "__setstate__": + if len(args) != 1: + raise_type_error( + tx, f"__setstate__() takes exactly one argument ({len(args)} given)" + ) + [state] = args + # BaseException.__setstate__(None) is a documented no-op. + if state.is_constant_none(): + return variables.ConstantVariable.create(None) + if not isinstance(state, variables.ConstDictVariable): + raise_type_error(tx, "state is not a dictionary") + for key, value in state.keys_as_python_constant().items(): + self.call_method( + tx, "__setattr__", [ConstantVariable.create(key), value], {} + ) + return variables.ConstantVariable.create(None) + elif name == "with_traceback": + if len(args) != 1: + raise_type_error( + tx, + f"with_traceback() takes exactly one argument ({len(args)} given)", + ) + [tb] = args + if not TracebackVariable.is_valid_traceback(tb): + raise_type_error(tx, "__traceback__ must be a traceback or None") + self.__traceback__ = tb + return self + else: + return super().call_method(tx, name, args, kwargs) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if name == "__class__": + return VariableTracker.build(tx, self.exc_type) + elif name == "__context__": + return self.__context__ + elif name == "__cause__": + return self.__cause__ + elif name == "__suppress_context__": + return self.__suppress_context__ + elif name == "__traceback__": + return self.__traceback__ + elif name == "args": + return VariableTracker.build( + tx, + tuple(self.args), + source=self.source and AttrSource(self.source, "args"), + ) + try: + # Custom attributes are stored in the side effects instance dict and + # resolved by generic_getattr before reaching here, so a fall-through + # to the generic lookup that finds nothing means the attribute is + # genuinely absent -- match CPython's BaseException tp_getattro + # (PyObject_GenericGetAttr) and raise AttributeError. + return super().tp_getattro_impl(tx, name) + except NotImplementedError: + raise_observed_exception( + AttributeError, + tx, + args=[f"'{self.exc_type.__name__}' object has no attribute '{name}'"], + ) + + def tp_str_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.3/Objects/exceptions.c#L118-L129 + if len(self.args) == 0: + return VariableTracker.build(tx, "") + elif len(self.args) == 1: + return generic_str(tx, self.args[0]) + else: + from . import TupleVariable + + tuple_var = TupleVariable(list(self.args)) + return generic_str(tx, tuple_var) + + def __str__(self) -> str: + return f"{self.__class__.__name__}({self.exc_type})" + + __repr__ = __str__ + + @staticmethod + def _debug_format_arg(arg: VariableTracker) -> str: + try: + return repr(arg.as_python_constant()) + except Exception: + return arg.debug_repr() + + def debug_repr(self) -> str: + args = ", ".join(self._debug_format_arg(arg) for arg in self.args) + return f"{self.python_type_name()}({args})" + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: BaseException_repr in https://github.com/python/cpython/blob/3.13/Objects/exceptions.c#L135-L142 + return VariableTracker.build(tx, self.debug_repr()) + + +class StopIterationVariable(ExceptionVariable): + def __init__( + self, + exc_type: Any, + args: list[VariableTracker], + init_kwargs: dict[str, VariableTracker] | None = None, + source: Source | None = None, + mutation_type: MutationType | None = None, + ) -> None: + self.value = args[0] if args else variables.ConstantVariable.create(None) + super().__init__(exc_type, args, init_kwargs, source, mutation_type) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if name == "value": + return self.value + return super().tp_getattro_impl(tx, name) + + +class _KwargAttrExceptionVariable(ExceptionVariable): + # Base for exceptions whose constructor accepts keyword-only attributes that + # default to None (e.g. NameError's `name`, AttributeError's `name`/`obj`). + # Subclasses list the attribute names in `_kwarg_attrs`; they are popped from + # init_kwargs, exposed via getattr, and restored on reconstruct. + _kwarg_attrs: tuple[str, ...] = () + + def __init__( + self, + exc_type: Any, + args: list[VariableTracker], + init_kwargs: dict[str, VariableTracker] | None = None, + source: Source | None = None, + mutation_type: MutationType | None = None, + ) -> None: + init_kwargs = dict(init_kwargs) if init_kwargs else {} + none = variables.ConstantVariable.create(None) + self._attrs = {name: init_kwargs.pop(name, none) for name in self._kwarg_attrs} + super().__init__(exc_type, args, init_kwargs, source, mutation_type) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if name in self._attrs: + return self._attrs[name] + return super().tp_getattro_impl(tx, name) + + def reconstruct(self, codegen: "PyCodegen") -> None: + super().reconstruct(codegen) + for name, val in self._attrs.items(): + if not (istype(val, ConstantVariable) and val.value is None): + codegen.dup_top() + codegen(val) + codegen.extend_output(codegen.rot_n(2)) + codegen.store_attr(name) + + +class AttributeErrorVariable(_KwargAttrExceptionVariable): + # https://docs.python.org/3/library/exceptions.html#AttributeError + _kwarg_attrs = ("name", "obj") + tp_members = { + "name": Member(getset_read(lambda s: s._attrs["name"])), + "obj": Member(getset_read(lambda s: s._attrs["obj"])), + } + + +class NameErrorVariable(_KwargAttrExceptionVariable): + # https://docs.python.org/3/library/exceptions.html#NameError + _kwarg_attrs = ("name",) + tp_members = {"name": Member(getset_read(lambda s: s._attrs["name"]))} + + +class UnknownVariable(VariableTracker): + """ + It could be anything! + """ + + +class DelayGraphBreakVariable(UnknownVariable): + """ + Used to insert a dummy variable in the stack to do the graph break at CALL_FUNCTION. + """ + + def __init__( + self, + msg: str | None = None, + hints: list[str] | None = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.msg = msg + self.hints = hints or [] + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + name = "" if self.source is None else self.source.name + unimplemented( + gb_type="Unsupported function call (delayed)", + context=f"source: {self.source}", + explanation="Dynamo determined that a graph break should occur " + f"when calling `{name}`. Reason: {self.msg}", + hints=self.hints, + ) + + +class ComptimeVariable(VariableTracker): + """ + This variable is special, it lets you execute arbitrary code at + Dynamo compile time + """ + + def reconstruct(self, codegen: "PyCodegen") -> None: + raise NotImplementedError("comptime is special form") + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + from ..comptime import comptime + + if self.source is None: + raise AssertionError("ComptimeVariable requires a source") + # To support the comptime.print_graph convenience accessors + return VariableTracker.build( + tx, getattr(comptime, name), source=AttrSource(self.source, name) + ) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from ..comptime import ComptimeContext + + # TODO: support an expression form as well + # Second argument is runtime lambda, ignored + if kwargs or len(args) > 2: + raise_args_mismatch( + tx, + "comptime()", + "at most 2 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + fn = args[0] + if isinstance(fn, UserFunctionVariable): + fn.get_function()(ComptimeContext(tx)) + elif isinstance(fn, NestedUserFunctionVariable): + # We have to manually bind the freevars ourselves + code = fn.get_code() + if fn.closure: + raise_type_error( + tx, + f"comptime function must not have free variables, but these variables were free: {code.co_freevars}", + ) + func = types.FunctionType( + code, + fn.f_globals, + fn.fn_name.as_python_constant(), + # type: ignore[attr-defined] + tuple(fn.defaults.items) if fn.defaults else None, + # We could automatically promote free variables into + # ComptimeVar but this is confusing if you access + # a free variable that we actually DO have the runtime + # value for + # tuple(make_cell(ComptimeVar(i)) for i in fn.closure.items) + (), + ) + func(ComptimeContext(tx)) + else: + raise RuntimeError(f"unsupported argument to comptime: {type(fn)}") + + return variables.ConstantVariable.create(None) + + +class CellVariable(VariableTracker): + # PyCell_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/cellobject.c#L151 + _cpython_type = types.CellType + + # If the cell existed before Dynamo tracing started, this will be the + # VariableTracker that represents the cell content. + # + # Note that all mutation to the cell (i.e., its content) will be buffered in + # SideEffects, rather than being reflected here. One can think of + # `CellVariable` as a special case for `UserDefinedObjectVariable`. + pre_existing_contents: VariableTracker | None + + # This is set when this cell can be referenced via `LOAD/STORE_DEREF` in the + # root frame via this name (e.g., the name is in `co_cellvars/co_freevars`). + local_name: str | None = None + + def __init__( + self, pre_existing_contents: VariableTracker | None = None, **kwargs: Any + ) -> None: + super().__init__(**kwargs) + self.pre_existing_contents = pre_existing_contents + + def python_type(self) -> type: + return types.CellType + + +class NewGlobalVariable(VariableTracker): + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + +def produce_trampoline_autograd_apply(fn_cls: Any) -> Callable[..., Any]: + def trampoline_autograd_apply(*args: Any, **kwargs: Any) -> Any: + return fn_cls.apply(*args, **kwargs) + + # type: ignore[attr-defined] + trampoline_autograd_apply._origin = produce_trampoline_autograd_apply + return trampoline_autograd_apply + + +class AutogradFunctionVariable(VariableTracker): + """represents a torch.autograd.Function subclass""" + + _nonvar_fields = { + "fn_cls", + *VariableTracker._nonvar_fields, + } + + def __init__(self, fn_cls: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.fn_cls = fn_cls + + def python_type(self) -> type: + return type + + def _resolve_kwargs( + self, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> list[VariableTracker] | None: + """Resolve kwargs to positional args using forward().__code__. + + Uses co_varnames/co_argcount directly to match the C++ + resolve_kwargs_to_positional in python_function.cpp. + Keyword-only args are not resolved; callers should graph break. + """ + from torch.autograd.function import _is_setup_context_defined + + fn = self.fn_cls.forward + code = fn.__code__ + has_ctx = not _is_setup_context_defined(self.fn_cls.setup_context) + param_offset = 1 if has_ctx else 0 + param_names = list(code.co_varnames[param_offset : code.co_argcount]) + + for name in kwargs: + if name not in param_names: + return None + if param_names.index(name) < len(args): + raise TypeError(f"forward() got multiple values for argument '{name}'") + + max_idx = max( + (param_names.index(name) for name in kwargs), + default=len(args) - 1, + ) + + result: list[VariableTracker] = list(args) + for i in range(len(args), max_idx + 1): + name = param_names[i] + if name in kwargs: + result.append(kwargs[name]) + else: + raise TypeError( + f"forward() missing required argument: '{name}' (position {i})" + ) + return result + + def call_apply( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if kwargs: + resolved = self._resolve_kwargs(args, kwargs) + if resolved is None: + unimplemented( + gb_type="autograd_function_kwonly_args", + context=f"forward() has keyword-only args: {set(kwargs) - set(self.fn_cls.forward.__code__.co_varnames)}", + explanation="autograd.Function.apply does not support keyword-only arguments in forward().", + hints=[*graph_break_hints.SUPPORTABLE], + ) + args = resolved + kwargs = {} + + requires_grad = False + + def visit(vt: VariableTracker) -> None: + nonlocal requires_grad + if vt.is_tensor(): + # type: ignore[attr-defined] + if vt.requires_grad is not False: + requires_grad = True + if isinstance(vt, variables.NNModuleVariable): + if vt.is_training(tx): + requires_grad = True + + VariableTracker.visit(visit, (args, kwargs)) + + if requires_grad and torch.is_grad_enabled(): + source = self.source + + from torch._functorch.autograd_function import ( + autograd_function_forward_rewritten, + ) + from torch.autograd.function import _is_setup_context_defined + + forward_fn = self.fn_cls.forward + + is_setup_ctx_defined = _is_setup_context_defined(self.fn_cls.setup_context) + if is_setup_ctx_defined: + # If setup_context is defined, we generate a new forward function which includes + # the original forward and setup_context function, and trace the new forward function. + forward_fn = autograd_function_forward_rewritten( + self.fn_cls.forward, self.fn_cls.setup_context + ) + # The forward points to a new function now, so we can't use the + # old source. Later on, we guard specifically on + # is_setup_ctx_defined + source = None + + vjp_fn = self.fn_cls.vjp # type: ignore[attr-defined] + if vjp_fn is not torch.autograd.Function.vjp: + unimplemented( + gb_type="Unsupported custom vjp", + context=f"call_apply {self} {args} {kwargs}", + explanation="Dynamo does not support tracing " + "`torch.autograd.Function` subclasses that define " + "a custom `vjp` method.", + hints=[ + "Remove the custom `vjp` method if possible.", + "Use standard `backward` instead if applicable.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + jvp_fn = self.fn_cls.jvp # type: ignore[attr-defined] + if jvp_fn is not torch.autograd.Function.jvp: + unimplemented( + gb_type="Unsupported custom jvp", + context=f"call_apply {self} {args} {kwargs}", + explanation="Dynamo does not support tracing " + "`torch.autograd.Function` subclasses that define " + "a custom `jvp` method.", + hints=[ + "Remove the custom `jvp` method if possible.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + from .higher_order_ops import AutogradFunctionApplyVariable + + if source is None and not is_setup_ctx_defined: + source = AttrSource( + tx.import_source(self.fn_cls.__module__), self.fn_cls.__name__ + ) + apply_source = source and AttrSource(source, member="apply") + val = AutogradFunctionApplyVariable( + forward_fn, + self.fn_cls.backward, + source, + source=apply_source, + ).call_function(tx, args, kwargs) + if self.source and is_setup_ctx_defined: + fwd_src = AttrSource(self.source, "forward") + install_guard(fwd_src.make_guard(GuardBuilder.CLOSURE_MATCH)) + setup_ctx_src = AttrSource(self.source, "setup_context") + install_guard(setup_ctx_src.make_guard(GuardBuilder.CLOSURE_MATCH)) + + return val + + if self.source: + source = AttrSource(self.source, "forward") + else: + source = None + + fn = self.fn_cls.forward + ctx = AutogradFunctionContextVariable.create(tx, args, kwargs) + args = [ctx, *args] + if isinstance(fn, types.FunctionType): + sig = inspect.signature(fn) + if len(args) - 1 == len(sig.parameters): + args = args[1:] # Don't use context + fn_vt = VariableTracker.build(tx, fn, source=source, realize=True) + return fn_vt.call_function(tx, args, kwargs) + elif isinstance(fn, types.MethodType): + return variables.UserMethodVariable( + fn.__func__, + variables.UserDefinedClassVariable(self.fn_cls), + source=source, + ).call_function(tx, args, kwargs) + else: + unimplemented( + gb_type="Non-function or method in subclass of torch.autograd.Function", + context=f"call_apply {self} {args} {kwargs}", + explanation="Dynamo requires the `forward` attribute of a " + "`torch.autograd.Function` subclass to be a standard Python " + f"function or method. Found type `{type(fn).__name__}` instead.", + hints=[ + "Ensure the `forward` method is defined as a regular " + "function or instance method." + ], + ) + + def call_backward( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + fn = self.fn_cls.backward + if ( + type(args[0].value) # type: ignore[attr-defined] + is not torch._dynamo.external_utils.FakeBackwardCFunction + ): + raise AssertionError( + f"Expected FakeBackwardCFunction, got {type(args[0].value)}" + ) + if not isinstance(fn, types.FunctionType): + raise AssertionError(f"Expected FunctionType, got {type(fn)}") + if self.source is None: + raise AssertionError("AutogradFunctionVariable requires a source") + fn_source = AttrSource(self.source, "backward") + fn_vt = VariableTracker.build(tx, fn, source=fn_source, realize=True) + return fn_vt.call_function(tx, args, kwargs) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> "AutogradFunctionVariable": + return AutogradFunctionVariable(self.fn_cls) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + if name == "apply": + if trace_rules.is_callable_allowed(self.fn_cls): + trampoline_autograd_apply = produce_trampoline_autograd_apply( + self.fn_cls + ) + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + trampoline_autograd_apply, + *proxy_args_kwargs(args, kwargs), + ), + ) + else: + return self.call_apply(tx, args, kwargs) + + elif name == "backward": + return self.call_backward(tx, args, kwargs) + else: + source = AttrSource(self.source, name) if self.source is not None else None + try: + obj = inspect.getattr_static(self.fn_cls, name) + except AttributeError: + obj = None + + if isinstance(obj, staticmethod): + func = obj.__get__(self.fn_cls) + traced = trace_rules.lookup(func) + if traced is None: + raise AssertionError(f"trace_rules.lookup returned None for {func}") + if source is not None: + return ( + # type: ignore[attr-defined] + traced.create_with_source(func, source=source).call_function( + tx, args, kwargs + ) + ) + else: + # type: ignore[misc] + return traced(func).call_function(tx, args, kwargs) + elif isinstance(obj, classmethod): + return variables.UserMethodVariable( + obj.__func__, self, source=source + ).call_function(tx, args, kwargs) + else: + unimplemented( + gb_type="Unsupported autograd.Function method", + context=f"call_method {self} {name}", + explanation="Dynamo does not support calling the method " + f"`{name}` directly on the `torch.autograd.Function` " + "instance. Supported methods include `apply`, `backward`, " + "static methods, and class methods.", + hints=[ + "Ensure the method is decorated with `@staticmethod` " + "or `@classmethod` if it's meant to be called on the class.", + ], + ) + + +@dataclasses.dataclass +class SavedTensorBox: + tensors: list[VariableTracker] = dataclasses.field(default_factory=list) + + +class AutogradFunctionContextVariable(UserDefinedObjectVariable): + """ + Tracks an autograd.Function() context using mutation tracking in side_effects.py + """ + + _nonvar_fields = { + "proxy", + "inference", + "saved_tensors", + *UserDefinedObjectVariable._nonvar_fields, + } + + def __init__( + self, + value: Any, + value_type: type | None = None, + inference: bool = False, + saved_tensors: Any | None = None, + non_differentiable: Any | None = None, + dirty_tensors: list[VariableTracker] | None = None, + **kwargs: Any, + ) -> None: + super().__init__(value=value, value_type=value_type, **kwargs) + self.inference = inference + self.saved_tensors = saved_tensors + self.non_differentiable = non_differentiable + self.dirty_tensors = dirty_tensors + + @staticmethod + def create( + tx: "InstructionTranslatorBase", + args: list[VariableTracker] | None = None, + kwargs: dict[str, VariableTracker] | None = None, + ) -> VariableTracker: + out = tx.output.side_effects.track_object_new( + None, + torch.autograd.function.FunctionCtx, + functools.partial( + AutogradFunctionContextVariable, + inference=True, + saved_tensors=SavedTensorBox(), + ), + {}, + ) + if args and not kwargs: + # The real apply() populates ctx.needs_input_grad; mirror it as a + # regular attribute store so reads and user writes both flow + # through the generic side_effects machinery. + # pyrefly: ignore [missing-attribute] + needs_input_grad = tuple(x.is_tensor() and x.requires_grad for x in args) + tx.output.side_effects.store_instance_dict_attr( + out, "needs_input_grad", ConstantVariable.create(needs_input_grad) + ) + return out + + def as_proxy(self) -> Any: + # type: ignore[attr-defined] + if self.proxy is None: + unimplemented( + gb_type="proxy not set", + context=f"as_proxy {self}", + explanation="Dynamo requires the autograd.Function context " + "to be initialized with a proxy.", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + # type: ignore[attr-defined] + return self.proxy + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "__setattr__": + return super().call_method(tx, name, args, kwargs) + elif name == "mark_non_differentiable": + if kwargs: + raise_args_mismatch(tx, name, "0 kwargs", f"{len(kwargs)} kwargs") + self.non_differentiable = proxy_args_kwargs(args, {})[0] + return variables.ConstantVariable.create(None) + elif name == "mark_dirty": + if kwargs: + raise_args_mismatch(tx, name, "0 kwargs", f"{len(kwargs)} kwargs") + if getattr(self, "proxy", None) is None: + unimplemented( + gb_type="Unsupported autograd.Function context `mark_dirty`", + context=f"call_method {self} {name}", + explanation="Dynamo only supports tracing ctx.mark_dirty " + "inside autograd.Function.apply.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + self.dirty_tensors = args + return variables.ConstantVariable.create(None) + + if name != "save_for_backward": + unimplemented( + gb_type="Unsupported autograd.Function context method", + context=f"call_method {self} {name}", + explanation="Dynamo does not support calling the method " + f"`{name}` on `autograd.Function` context objects. Supported " + "methods are `__setattr__`, `save_for_backward`, " + "`mark_dirty` and `mark_non_differentiable`.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + if self.saved_tensors is None: + unimplemented( + gb_type="Unsupported autograd.Function context `save_for_backward`", + context=f"call_method {self} {name}", + explanation="Dynamo requires the `saved_tensors` attribute " + "to be initialized on the `autograd.Function` context object.", + hints=[ + "Ensure that the `saved_tensors` attribute is properly " + "initialized before calling `save_for_backward`. " + "`save_for_backward` only supported on a newly constructed `torch.autograd.function.FunctionCtx`.", + ], + ) + if self.saved_tensors is None: + raise AssertionError( + "saved_tensors must be initialized before save_for_backward" + ) + if not self.inference: + if kwargs or not self.source: + raise_type_error( + tx, "save_for_backward() requires a source and no keyword arguments" + ) + tx.output.side_effects.track_save_for_backward(self, args) + + # In eager mode, multiple calls to .save_for_backward() will overwrite previous calls. + if len(self.saved_tensors.tensors) > 0: + # pyrefly: ignore [implicit-any] + self.saved_tensors.tensors = [] + for arg in args: + self.saved_tensors.tensors.append(arg) + return variables.ConstantVariable.create(None) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if name in ["save_for_backward", "mark_dirty", "mark_non_differentiable"]: + return LambdaVariable( + lambda *args, **kwargs: self.call_method(tx, name, list(args), kwargs) + ) + if name == "dirty_tensors": + if self.dirty_tensors is None: + return variables.ConstantVariable.create(None) + return variables.TupleVariable(list(self.dirty_tensors)) + if name == "saved_tensors" and self.saved_tensors is not None: + return variables.TupleVariable(list(self.saved_tensors.tensors)) + + return super().tp_getattro_impl(tx, name) + + +class AutogradEngineVariable(UserDefinedObjectVariable): + """ + Represents a torch._C._ImperativeEngine instance. + """ + + def __init__( + self, + value: torch._C._ImperativeEngine, + value_type: type[torch._C._ImperativeEngine] | None = None, + **kwargs: Any, + ) -> None: + super().__init__(value=value, value_type=value_type, **kwargs) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "queue_callback": + if torch._dynamo.compiled_autograd.in_compiled_autograd_region: + if not (tx.one_graph or tx.error_on_graph_break): + raise AssertionError( + "queue_callback() is only supported when Compiled Autograd is enabled with fullgraph=True" + ) + # queue_callback is a method-wrapper, no need to insert a guard. + fn_vt = VariableTracker.build( + tx, + torch._dynamo.external_utils.FakeCompiledAutogradEngine.queue_callback, + ) + return fn_vt.call_function( + tx, + (tx.output.side_effects.get_ca_final_callbacks_var(), *args), + kwargs, + ) + else: + unimplemented( + gb_type="Unsupported torch._C._ImperativeEngine.queue_callback()", + context=f"call_method {self} {name}", + explanation="queue_callback() is only supported when " + "Compiled Autograd is enabled with fullgraph=True.", + hints=[], + ) + else: + unimplemented( + gb_type="Unsupported torch._C._ImperativeEngine method", + context=f"call_method {self} {name}", + explanation="Dynamo only supports the `queue_callback` method " + f"on a torch._C._ImperativeEngine instance, but found: `{name}`.", + hints=[], + ) + + +class LambdaVariable(VariableTracker): + # TODO: change to Ts = TypeVarTuple("Ts") for py 3.11+ + def __init__(self, fn: Callable[..., VariableTracker], **kwargs: Any) -> None: + super().__init__(**kwargs) + self.fn = fn + + def python_type(self) -> type: + return types.FunctionType + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self.fn(*args, **kwargs) + + +class GetAttrVariable(VariableTracker): + _nonvar_fields = { + "name", + "py_type", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + obj: VariableTracker, + name: str, + py_type: type | None = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if not isinstance(obj, VariableTracker): + raise AssertionError(f"obj must be a VariableTracker, got {type(obj)}") + if not isinstance(name, str): + raise AssertionError(f"name must be a str, got {type(name)}") + self.obj = obj + self.name = name + self.py_type = py_type # In some cases we know the type (ex. tensor methods) + + def python_type(self) -> type: + if self.py_type is not None: + return self.py_type + else: + return super().python_type() + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.obj}, {self.name})" + + @staticmethod + def create_getattr_proxy(base_proxy: torch.fx.Proxy, attr: str) -> Any: + return getattr(base_proxy, attr) + + def as_proxy(self) -> Any: + return GetAttrVariable.create_getattr_proxy(self.obj.as_proxy(), self.name) + + def as_python_constant(self) -> Any: + constant = self.obj.as_python_constant() + try: + return getattr(constant, self.name) + except AttributeError: + raise NotImplementedError(f"{self} is not a constant") from None + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # GetAttrVariable can wrap various types (bound methods, descriptors, + # etc.) with different C tp_hash. Resolve to the actual value and hash. + try: + val = self.as_python_constant() + except (AsPythonConstantNotImplementedError, NotImplementedError): + from ..exc import unimplemented + + unimplemented( + gb_type="Non-constant GetAttrVariable hash", + context=f"hash_impl {self}", + explanation=f"Cannot hash {self} because Dynamo doesn't know how to represent " + "the type of the getattr() result, which is not a constant.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + return hash(val), False + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> "ConstantVariable": + if ( + isinstance(self.obj, AutogradFunctionVariable) + and self.name == "apply" + and getattr(self.obj.fn_cls, "generate_vmap_rule", False) + ): + return variables.ConstantVariable.create( + hasattr(self.obj.fn_cls.apply, name) + ) + return super().call_obj_hasattr(tx, name) + + def const_getattr(self, tx: "InstructionTranslatorBase", name: str) -> Any: + if not isinstance(self.obj, variables.NNModuleVariable): + raise NotImplementedError + step1 = tx.output.get_submodule(self.obj.module_key) + if self.name not in step1.__dict__: + raise NotImplementedError + step2 = inspect.getattr_static(step1, self.name) + if name not in step2.__dict__: + raise NotImplementedError + return inspect.getattr_static(step2, name) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.obj) + codegen.extend_output(codegen.create_load_attrs(self.name)) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: "VariableTracker", op: str + ) -> "VariableTracker": + from .object_protocol import generic_richcompare + + try: + resolved = self.obj.tp_getattro_impl(tx, self.name) + except NotImplementedError: + resolved = None + if resolved is None or isinstance(resolved, GetAttrVariable): + if self.obj.is_python_constant(): + val = getattr(self.obj.as_python_constant(), self.name) + resolved = VariableTracker.build(tx, val) + else: + unimplemented( + gb_type="Unresolved GetAttrVariable comparison", + context=f"tp_richcompare_impl {self} {op}", + explanation=f"Cannot compare {self} because the attribute " + f"could not be resolved to a concrete value.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + return generic_richcompare(tx, resolved, other, op) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self.obj.call_method(tx, self.name, args, kwargs) + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + if self.name == "__dict__" and hasattr(self.obj, "get_dict_vt"): + return self.obj.get_dict_vt(tx).mp_subscript_impl(tx, key) + return super().mp_subscript_impl(tx, key) + + +class CallMethodVariable(VariableTracker): + """A method bound to a VT instance. + + Returned by object_generic_getattr when the MRO walk finds a method + on a VT that has custom call_method logic. + """ + + _nonvar_fields = { + "method_name", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + obj: VariableTracker, + method_name: str, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.obj = obj + self.method_name = method_name + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.obj}, {self.method_name})" + + def python_type(self) -> type: + try: + return type(self.as_python_constant()) + except (AsPythonConstantNotImplementedError, AttributeError): + return types.MethodType + + def as_python_constant(self) -> Any: + return getattr(self.obj.as_python_constant(), self.method_name) + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + try: + return hash(self.as_python_constant()), False + except AsPythonConstantNotImplementedError: + return id(self), True + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self.obj.call_method(tx, self.method_name, args, kwargs) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.obj) + codegen.extend_output(codegen.create_load_attrs(self.method_name)) + + +class PythonModuleVariable(VariableTracker): + # PyModule_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/moduleobject.c#L1203 + _cpython_type = types.ModuleType + + _nonvar_fields = { + "value", + "is_torch", + *VariableTracker._nonvar_fields, + } + + def __init__(self, value: types.ModuleType, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + self.is_torch = self.value is torch or self.value.__name__.startswith("torch.") + + def python_type(self) -> type[types.ModuleType]: + return types.ModuleType + + def as_python_constant(self) -> types.ModuleType: + return self.value + + def get_real_python_backed_value(self) -> types.ModuleType: + return self.value + + def __repr__(self) -> str: + return f"PythonModuleVariable({self.value})" + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if tx.output.side_effects.has_pending_mutation_of_attr(self, name): + return tx.output.side_effects.load_attr(self, name) + + attr_value = None + if self.is_torch or name not in self.value.__dict__: + try: + attr_value = getattr(self.value, name) + except AttributeError: + raise_observed_exception(AttributeError, tx) + else: + attr_value = self.value.__dict__[name] + + source = self.source and AttrSource(self.source, name) + return VariableTracker.build(tx, attr_value, source) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: "VariableTracker", op: str + ) -> "VariableTracker": + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + +class TypingVariable(VariableTracker): + def __init__(self, value: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # e.g., List[int] → typing.List[int] + if not key.is_python_constant(): + unimplemented( + gb_type="non-constant typing subscript", + context=f"TypingVariable[{key}]", + explanation=f"Cannot subscript typing construct {self.value} with a non-constant key.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + new_typing = self.value[key.as_python_constant()] + return TypingVariable(new_typing) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: "VariableTracker", op: str + ) -> "VariableTracker": + if op in ("__eq__", "__ne__"): + if istype(other, TypingVariable): + result = self.value == other.value + if op == "__ne__": + result = not result + return ConstantVariable.create(result) + return ConstantVariable.create(NotImplemented) + return ConstantVariable.create(NotImplemented) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + unimplemented( + gb_type="unsupported method call on `typing` variable", + context=f"typing variable: {self.value}, method name: {name}, args: {args}, kwargs: {kwargs}", + explanation=f"`torch.compile` does not support method call `{name}` on `typing` variable f{self.value}.", + hints=[ + f"Avoid calling the {name} method on {self.value}.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # GenericAlias types (e.g. Callable[[int], bool]) support __or__ for + # type unions (e.g. Callable[[int], bool] | None). + if not other.is_python_constant(): + return VariableTracker.build(tx, NotImplemented) + other_val = other.as_python_constant() + # pyrefly: ignore[bad-argument-count] + result = type(self.value).__or__(self.value, other_val) + if result is NotImplemented: + return VariableTracker.build(tx, NotImplemented) + return VariableTracker.build(tx, result) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + from .builder import SourcelessBuilder, VariableBuilder + + if tx.output.side_effects.has_pending_mutation_of_attr(self, name): + return tx.output.side_effects.load_attr(self, name) + + value = getattr(self.value, name) + if self.source: + attr_source = AttrSource(self.source, name) + return VariableBuilder(tx, attr_source)(value) + else: + return SourcelessBuilder.create(tx, value) + + def as_python_constant(self) -> Any: + return self.value + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + return hash(self.value), False + + def get_real_python_backed_value(self) -> Any: + return self.value + + def reconstruct(self, codegen: "PyCodegen") -> None: + if not isinstance(self.value, types.GenericAlias): + return super().reconstruct(codegen) + # We're just trying to load the type here. Reconstructing the type from + # scratch is tricky - for a type like `typing.List[int]` we'd need to + # deconstruct the origin and args. The origin for `List[int]` is `list` + # and the args is `(int,)`. When we recombine those we get the parts + # back and need to emit code for: + # + # `typing.List[int]` + # + # But it's # worse than that - what if `typing` isn't in the globals (or + # was loaded like `import typing as _typing ; _typing.List[int]`?) so we + # really need to do something like: + # + # `sys.modules["typing"].List[int]` + # + # Argh - but what if they rewrote the global `int`? So we have to do: + # + # `sys.modules["typing"].List[sys.modules["builtins"].int]` + # + # But where do we get `sys`? What if they never imported it or have + # something ELSE called `sys`? + # + # Let's skip all that noise and just emit it as a simple const. + # + codegen.append_output(codegen.create_load_const(self.value)) + + +@functools.lru_cache(maxsize=1) +def get_np_to_tnp_map() -> dict[types.BuiltinFunctionType, types.FunctionType]: + """ + This generates a mapping from numpy modules to their torch._numpy + modules equivalents. + """ + from ..utils import NP_TO_TNP_MODULE + + np_fn_to_tnp_fn = {} + + for np_mod, tnp_mod in NP_TO_TNP_MODULE.items(): + for fn_name, tnp_fn in tnp_mod.__dict__.items(): + if callable(tnp_fn): + # some internal details do leak from tnp + # which are not part of numpy API. + if np_fn := getattr(np_mod, fn_name, None): + np_fn_to_tnp_fn[np_fn] = tnp_fn + + return np_fn_to_tnp_fn + + +@functools.lru_cache(maxsize=1) +def get_tnp_to_np_map() -> dict[types.FunctionType, types.BuiltinFunctionType]: + """ + This is just the reverse mapping of get_np_to_tnp_map() - mapping from + torch._numpy modules to numpy equivalents. + """ + m = get_np_to_tnp_map() + return {v: k for k, v in m.items()} + + +class NumpyVariable(VariableTracker): + """ + Wrapper around `numpy.*`. Currently, is able to trace a small subset of numpy functions as well as numpy dtypes. + """ + + constant_fold_functions = (tnp.issubdtype,) + + def __init__(self, value: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + def get_real_python_backed_value(self) -> Any: + return self.value + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + # NumpyVariable wraps singleton numpy module attrs (dtypes, ufuncs, + # constants); compare by the backed value for eq/ne, else NotImplemented. + if op not in ("__eq__", "__ne__") or not hasattr(other, "value"): + return ConstantVariable.create(NotImplemented) + result = ( + self.value == other.value if op == "__eq__" else self.value != other.value + ) + return ConstantVariable.create(result) + + @classmethod + def can_constant_fold_through(cls, fn: types.FunctionType) -> bool: + mod = fn.__module__.split(".") + if len(mod) < 2: + raise AssertionError( + f"Expected module path with at least 2 parts, got {mod}" + ) + if mod[:2] != ["torch", "_numpy"]: + raise AssertionError( + f"Expected torch._numpy module, got {'.'.join(mod[:2])}" + ) + return fn in cls.constant_fold_functions + + @classmethod + def get_constant_collection_for_func(cls, fn: types.FunctionType) -> Any: + mod = fn.__module__.split(".") + if len(mod) < 2: + raise AssertionError( + f"Expected module path with at least 2 parts, got {mod}" + ) + if mod[:2] != ["torch", "_numpy"]: + raise AssertionError( + f"Expected torch._numpy module, got {'.'.join(mod[:2])}" + ) + return np_constant_collections_map.get(fn) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if not config.trace_numpy: + unimplemented( + gb_type="attempted to trace numpy function with config.trace_numpy=False", + context=f"numpy function: {self.value}, args: {args}, kwargs: {kwargs}", + explanation=f"Attempted to trace numpy function {self.value} " + "while `torch._dynamo.config.trace_numpy` was set to False.", + hints=[ + "Set `torch._dynamo.config.trace_numpy` to True to trace numpy functions.", + ], + ) + + from ..utils import numpy_to_tensor_wrapper + from .tensor import NumpyNdarrayVariable + + func = get_np_to_tnp_map().get(self.value) + if func is None: + unimplemented( + gb_type="attempted to trace numpy function unsupported by PyTorch", + context=f"numpy function: {self.value}, args: {args}, kwargs: {kwargs} (corresponding torch function: {func})", + explanation=f"Can't find numpy numpy function {self.value} in torch._numpy.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + # We are dealing with a function that produces a const collection type (np.dtype, np.iinfo/np.finfo) + if func is None: + raise AssertionError( + f"Could not find torch._numpy equivalent for {self.value}" + ) + if ( + collection_variable_typ := self.get_constant_collection_for_func(func) + ) is not None: + try: + return collection_variable_typ( + self.value( + *[x.as_python_constant() for x in args], + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ) + ) + except AsPythonConstantNotImplementedError: + unimplemented( + gb_type="numpy function that produces a const collection type encountered non-const arguments", + context=f"numpy function: {self.value}, args: {args}, kwargs: {kwargs} (corresponding torch function: {func})", + explanation=f"numpy function {self.value} that produces a const collection type " + "(e.g. np.dtype, np.iinfo/np.finfo) " + "received arguments that are not constant.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + else: + if ( + func.__module__ == "torch._numpy.random" + and config.use_numpy_random_stream + ): + unimplemented( + gb_type="attempted to trace torch._numpy.random function with config.use_numpy_random_stream=True", + context=f"numpy function: {self.value}, args: {args}, kwargs: {kwargs} (corresponding torch function: {func})", + explanation=f"Attempted to trace {self.value} when `torch._dynamo.config.use_numpy_random_stream` " + "is set to True.", + hints=[ + "Set `torch._dynamo.config.use_numpy_random_stream` to False.", + f"Avoid calling {self.value}.", + ], + ) + + args, kwargs = NumpyNdarrayVariable.patch_args(func.__name__, args, kwargs) + + if self.can_constant_fold_through(func) and ( + check_unspec_or_constant_args(args, kwargs) + ): + # constant fold + return VariableTracker.build( + tx, + self.as_python_constant()( + *[x.as_python_constant() for x in args], + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ), + ) + + # TODO Add all the functions that go from constants to constants to can_constant_fold_through + proxy = tx.output.create_proxy( + "call_function", + numpy_to_tensor_wrapper(func), + *proxy_args_kwargs(args, kwargs), + ) + return NumpyNdarrayVariable.create(tx, proxy) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + unimplemented( + gb_type="attempted to trace numpy.* function as a method", + context=f"numpy function: {self.value}, args: {args}, kwargs: {kwargs}", + explanation="Tracing numpy.* functions as methods is not supported.", + hints=[ + *graph_break_hints.DIFFICULT, + ], + ) + + def as_python_constant(self) -> BuiltinFunctionType: + return self.value + + def as_proxy(self) -> Any: + if config.trace_numpy: + # Can replace with EnumType once we drop 3.10 support + if isinstance(self.value, enum.EnumMeta): + # This is mostly for np._CopyMode + return self.value + if isinstance(self.value, type): + # This handles numpy dtype attributes such as np.float32 + # We return a string as we don't want to serialize non-PyTorch objects in the output FX graph + # In torch/_numpy we normalize strings to their dtypes when the input is a dtype, as NumPy does + return self.value.__name__ + + return super().as_proxy() + + +# Used to keep track of NULLs pushed on the stack for Python 3.11 function calls +class NullVariable(VariableTracker): + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + def __repr__(self) -> str: + return "NullVariable" + + def reconstruct(self, codegen: "PyCodegen") -> None: + if sys.version_info < (3, 11): + unimplemented( + gb_type="cannot reconstruct NullVariable in Python < 3.11", + context="", + explanation="Attempted to generate PUSH_NULL instruction in Python < 3.11; " + "where this instruction does not exist.", + hints=[ + *graph_break_hints.DYNAMO_BUG, + ], + ) + codegen.append_output(create_instruction("PUSH_NULL")) + + def reconstruct_pycode(self, codegen: "PyCodegen") -> str: + return "None" + + +class DeletedVariable(VariableTracker): + """Marker used to implement delattr()""" + + +class StringFormatVariable(VariableTracker): + """ + Represents a call to str.format(), we delay calling format until after the graph. + """ + + _nonvar_fields = {"format_string", *VariableTracker._nonvar_fields} + + def python_type(self) -> type: + return str + + @classmethod + def create( + cls, + format_string: str, + sym_args: list[VariableTracker], + sym_kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if all( + x.is_python_constant() + for x in itertools.chain(sym_args, sym_kwargs.values()) + ): + return variables.ConstantVariable.create( + format_string.format( + *[v.as_python_constant() for v in sym_args], + **{k: v.as_python_constant() for k, v in sym_kwargs.items()}, + ) + ) + return cls(format_string, list(sym_args), dict(sym_kwargs)) + + def __init__( + self, + format_string: str, + sym_args: list[VariableTracker], + sym_kwargs: dict[str, VariableTracker], + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if not isinstance(format_string, str): + raise AssertionError( + f"format_string must be a str, got {type(format_string)}" + ) + self.format_string = format_string + self.sym_args = sym_args + self.sym_kwargs = sym_kwargs + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.format_string!r}, {self.sym_args!r}, {self.sym_kwargs!r})" + + @staticmethod + def _debug_format_arg(arg: VariableTracker) -> object: + try: + return arg.as_python_constant() + except Exception: + return arg.debug_repr() + + def debug_repr(self) -> str: + try: + rendered = self.format_string.format( + *[self._debug_format_arg(arg) for arg in self.sym_args], + **{ + key: self._debug_format_arg(value) + for key, value in self.sym_kwargs.items() + }, + ) + except Exception: + return repr(self) + return repr(rendered) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.extend_output( + [ + codegen.create_load_const(self.format_string), + codegen.create_load_attr("format"), + ] + ), + call_function_ex=True, + ) + codegen(variables.TupleVariable(list(self.sym_args))) + kwargs = { + variables.ConstantVariable.create(k): v for k, v in self.sym_kwargs.items() + } + codegen(variables.ConstDictVariable(kwargs)) + codegen.extend_output(create_call_function_ex(True, False)) + + +class ObjectVariable(VariableTracker): + # PyBaseObject_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/typeobject.c#L7243 + _cpython_type = object + + # placeholder for unknown / opaque values + def __init__(self, value: object, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + def get_real_python_backed_value(self) -> object: + return self.value + + def python_type(self) -> type[object]: + return object + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: "VariableTracker", op: str + ) -> "VariableTracker": + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + +if sys.version_info >= (3, 15): + + class SentinelVariable(VariableTracker): + # Use builtins.sentinel to avoid ruff errors + _cpython_type = builtins.sentinel + + def __init__(self, value: builtins.sentinel, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + def get_real_python_backed_value(self) -> builtins.sentinel: + return self.value + + def python_type(self) -> type[builtins.sentinel]: + return self._cpython_type + + +class DebuggingVariable(VariableTracker): + """ + Represents a call to a debugging function like print(), or something + registered to config.reorderable_logging_functions. + """ + + def __init__(self, value: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + def python_type(self) -> type: + return type(self.value) + + @staticmethod + def is_reorderable_logging_function( + obj: Any, + ) -> TypeGuard[types.FunctionType | types.BuiltinFunctionType]: + return ( + callable(obj) + and isinstance(obj, (types.FunctionType, types.BuiltinFunctionType)) + and obj in torch._dynamo.config.reorderable_logging_functions + ) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if tx.export: + # For export cases, we can just make debugging functions no-ops + return ConstantVariable.create(None) + + if not self.can_reorder_logs(self.value, args, kwargs): + unimplemented( + gb_type="attempted to reorder a debugging function that can't actually be reordered", + context=f"fn: {self.value}, args: {args}, kwargs: {kwargs}", + explanation="`torch.compile` can only reorder functions that are called " + "without keyword arguments and whose arguments are Tensors, constants, " + "or string formatters.", + hints=[ + f"Avoid calling the logging function {self.value} with args that are not supported.", + ], + ) + + tx.debug_locals.append((self, list(args))) + return ConstantVariable.create(None) + + def reconstruct(self, codegen: "PyCodegen") -> None: + if self.source is None: + raise AssertionError( + "DebugLocalVariable requires a source for reconstruction" + ) + return self.source.reconstruct(codegen) + + @staticmethod + def can_reorder_logs(fn: Any, args: Sequence[Any], kwargs: dict[str, Any]) -> bool: + """ + Run some additional checks for what sort of function calls can we + actually reorder. + """ + + # kwargs are dropped by the replay codegen, so refuse rather than lose them + if kwargs: + return False + + allowed_input_types = ( + variables.TensorVariable, + variables.ConstantVariable, + StringFormatVariable, + ) + + flat_args = pytree.tree_leaves(args) + for arg in flat_args: + if not isinstance(arg, allowed_input_types): + return False + + return True + + +class IgnoredFunctionVariable(VariableTracker): + """ + Represents a call to an arbitrary function that should be ignored. + """ + + def __init__(self, value: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + def python_type(self) -> type: + return type(self.value) + + def get_real_python_backed_value(self) -> Any: + return self.value + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return variables.ConstantVariable.create(None) + + +class LoggingLoggerVariable(VariableTracker): + """ + Represents a call to any logging.Logger methods. + """ + + def __init__(self, value: logging.Logger, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + def python_type(self) -> type: + return type(self.value) + + def get_real_python_backed_value(self) -> logging.Logger: + return self.value + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if tx.export: + # For export cases, we can just make logging functions no-ops. + return variables.ConstantVariable.create(None) + + method = getattr(self.value, name, None) + function = getattr(method, "__func__", None) + + # Unified ignore set + ignore_set = torch._dynamo.config.ignore_logging_functions + + if method in ignore_set or function in ignore_set: + return variables.ConstantVariable.create(None) + + reorderable = torch._dynamo.config.reorderable_logging_functions + if self.source and (method in reorderable or function in reorderable): + fn_var = DebuggingVariable(method, source=AttrSource(self.source, name)) + return fn_var.call_function(tx, args, kwargs) + + logger_cls = type(self.value) + logger_cls_name = f"{logger_cls.__module__}.{logger_cls.__qualname__}" + unimplemented( + gb_type="logging.Logger method not supported for non-export cases", + context=f"method: {self.value}.{name}, args: {args}, kwargs: {kwargs}", + explanation="For non-export cases, logging.Logger methods are only supported if the logger " + "has a source and the method is registered as reorderable.", + hints=[ + "If you do not need this logging side effect, add the exact method being called to `torch._dynamo.config.ignore_logging_functions`. Dynamo will skip the call and return `None`.", + f"For example, for `logger.{name}(...)`, use `torch._dynamo.config.ignore_logging_functions.add(logger.{name})`. If `{name}` is defined on the logger class, add the class method `{logger_cls_name}.{name}` to ignore this method for all instances of that class.", + f"Dynamo does not trace into logging.Logger method bodies, so only the method you call directly (`{name}`) is checked against the ignore set. Ignoring a method that `{name}` calls internally has no effect.", + f"If you need the log side effect to run, then you can try one of (1) create the logger outside the compiled region and add the method to `torch._dynamo.config.reorderable_logging_functions` (e.g. `torch._dynamo.config.reorderable_logging_functions.add(logger.{name})`) so that it runs after the compiled region, as long as it is called without kwargs and its arguments are tensors, constants, or string formatters, (2) `torch._higher_order_ops.print(...)`, (3) wrap the logging call in a custom op (marked as mutable), or (4) preserve the logging contents and move the logging call outside the compiled region.", + ], + ) + + +class ConstantLikeVariable(VariableTracker): + """self.value is a compile-time constant, but not a literal""" + + try: + from numpy import ( + dtype as np_dtype, + floating as np_floating, + generic as np_generic, + ) + except ImportError: + # type: ignore[misc, assignment] + np_floating = type("invalid_type", (), {}) + # type: ignore[misc, assignment] + np_dtype = type("invalid_type", (), {}) + + def __init__(self, value: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + @property + def _error_prefix(self) -> str: + """Dynamically compute the prefix from the value's type""" + t = type(self.value) + + # For builtins (int, str, etc.), just return the name + if t.__module__ == "builtins": + return t.__qualname__ + + return f"{t.__module__}.{t.__qualname__}" + + def as_python_constant(self) -> Any: + return self.value + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + return hash(self.value), False + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: "VariableTracker", op: str + ) -> "VariableTracker": + from .object_protocol import python_constant_richcompare_impl + + return python_constant_richcompare_impl(self, tx, other, op) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # pyrefly: ignore [implicit-any] + cargs, ckwargs = [], {} + try: + # we only support constant propagation for methods + cargs = [x.as_python_constant() for x in args] + ckwargs = {k: v.as_python_constant() for k, v in kwargs.items()} + except NotImplementedError: + unimplemented( + gb_type="constant-like method call with non-constant args", + context=f"{self._error_prefix}.{name}(*{args}, **{kwargs})", + explanation=f"Attempted to call {self._error_prefix}.{name} with non-constant args.", + hints=[ + "Ensure that the args to the method call are constant (int, str, etc.).", + ], + ) + + result = getattr(self.value, name)(*cargs, **ckwargs) + + if variables.ConstantVariable.is_literal(result): + return VariableTracker.build(tx, result) + if isinstance(result, re.Match): + return ConstantLikeVariable(result) + + unimplemented( + gb_type="constant-like method call with unsupported return type", + context=f"{self._error_prefix}.{name}(*{args}, **{kwargs}) returned {result}", + explanation=f"Attempted to call {self._error_prefix}.{name}, got unsupported return value {result}.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + result = getattr(self.value, name) + if isinstance(result, self.np_floating): + result = float(result) + if isinstance(result, self.np_dtype): + return NumpyDTypeVariable(result) + if isinstance(result, type) and issubclass(result, self.np_generic): + # things like x.dtype.type + return NumpyVariable(result) + if variables.ConstantVariable.is_literal(result): + return VariableTracker.build(tx, result) + return GetAttrVariable(self, name, py_type=type(result)) + + +class NumpyDTypeVariable(ConstantLikeVariable): + def as_proxy(self) -> str: + """Similar to how numpy dtype descriptors (e.g. np.float32 ) are handled by NumpyVariable: + + np.dtype() objects are serialized as strings, torch._numpy wrappers will normalize to the torch dtype. + This also handles unsupported things nicely (i.e. structured arrays and object arrays). + """ + return self.value.type.__name__ + + +np_constant_collections_map = { + tnp.finfo: ConstantLikeVariable, + tnp.iinfo: ConstantLikeVariable, + tnp.dtype: NumpyDTypeVariable, +} + + +class ContextVarVariable(VariableTracker): + """Wraps a contextvars.ContextVar for Dynamo tracing. + + .get() is resolved at trace time with a guard that re-checks at cache time. + .set() and .reset() graph-break in Phase 1. + """ + + _nonvar_fields = { + "cv_obj", + *VariableTracker._nonvar_fields, + } + + def __init__(self, cv_obj: contextvars.ContextVar[Any], **kwargs: Any) -> None: + super().__init__(**kwargs) + self.cv_obj = cv_obj + + def python_type(self) -> type: + return contextvars.ContextVar + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: "list[VariableTracker]", + kwargs: "dict[str, VariableTracker]", + ) -> "VariableTracker": + if name == "get": + return self._handle_get(tx, args, kwargs) + elif name in ("set", "reset"): + unimplemented( + gb_type="ContextVar mutation not supported", + context=f"ContextVar('{self.cv_obj.name}').{name}()", + explanation=( + f"ContextVar.{name}() is not yet supported inside " + f"torch.compile. Move the .{name}() call outside the " + f"compiled region." + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + return super().call_method(tx, name, args, kwargs) + + def _handle_get( + self, + tx: "InstructionTranslatorBase", + args: "list[VariableTracker]", + kwargs: "dict[str, VariableTracker]", + ) -> "VariableTracker": + from ..source import ContextVarGetSource + from ..utils import is_safe_constant + from .base import NO_SUCH_SUBOBJ + + if kwargs: + raise_observed_exception( + TypeError, tx, args=["ContextVar.get() takes no keyword arguments"] + ) + if len(args) > 1: + raise_observed_exception( + TypeError, + tx, + args=[f"get expected at most 1 argument, got {len(args)}"], + ) + + default_var = args[0] if args else None + has_default = default_var is not None + default_value = None + + if has_default: + default_value = default_var.get_real_python_backed_value() + if default_value is NO_SUCH_SUBOBJ or not is_safe_constant(default_value): + unimplemented( + gb_type="ContextVar.get() with non-constant default", + context=f"ContextVar('{self.cv_obj.name}').get(...)", + explanation=( + "ContextVar.get() default argument must be a " + "compile-time constant inside torch.compile." + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + + value = self._get_value(tx, has_default, default_value) + + if not self.source: + raise AssertionError("ContextVarVariable requires a source for .get()") + value_source = ContextVarGetSource( + base=self.source, + has_default=has_default, + default_value=default_value, + ) + return VariableTracker.build(tx, value, source=value_source) + + def _get_value( + self, + tx: "InstructionTranslatorBase", + has_default: bool, + default_value: Any, + ) -> Any: + if has_default: + return self.cv_obj.get(default_value) + try: + return self.cv_obj.get() + except LookupError: + raise_observed_exception(LookupError, tx, args=[f"{self.cv_obj!r}"]) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> "VariableTracker": + if name == "name": + return ConstantVariable.create(self.cv_obj.name) + return super().tp_getattro_impl(tx, name) + + +class RandomClassVariable(VariableTracker): + """random.Random""" + + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + def python_type(self) -> type: + return type + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> "RandomVariable": + if len(args) > 1 or kwargs: + unimplemented( + gb_type="random.Random() with improper arguments", + context=f"args: {args}, kwargs: {kwargs}", + explanation="random.Random() with > 1 arg or with kwargs is not supported.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + seed = variables.ConstantVariable.create(None) if len(args) == 0 else args[0] + return RandomVariable( + seed=seed, mutation_type=variables.base.ValueMutationNew() + ) + + +class RandomVariable(VariableTracker): + """random.Random() + + Implemented by wrapping a VariableTracker around a random.Random object. + The supported methods for the random.Random object cannot be overridden. + Assumes that random objects behave the same given a set seed or state. + """ + + _cpython_type = random.Random + + _nonvar_fields = { + "random", + *VariableTracker._nonvar_fields, + } + + _supported_fn_names = { + "random", + "randint", + "randrange", + "uniform", + } + + def __init__( + self, + rand: random.Random | None = None, + seed: VariableTracker | None = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + if rand is not None: + if not self.is_supported_random_obj(rand): + raise AssertionError( + "Unsupported random.Random object with overridden methods" + ) + self.random = random.Random() + self.random.setstate(rand.getstate()) + else: + seed = seed.as_python_constant() if seed is not None else None + self.random = random.Random(seed) + + def python_type(self) -> type[random.Random]: + return random.Random + + def as_python_constant(self) -> random.Random: + return self.random + + @staticmethod + def is_supported_random_obj(val: Random) -> bool: + if type(val) is not random.Random: + return False + for name in itertools.chain( + RandomVariable._supported_fn_names, ("seed", "getstate", "setstate") + ): + if not hasattr(val, name): + return False + meth = getattr(val, name) + if inspect.isbuiltin(meth): + # e.g. random.Random.random + if meth != getattr(random.Random, name).__get__(val): + return False + else: + if getattr(meth, "__func__", None) is not getattr(random.Random, name): + return False + return True + + @staticmethod + def check_state(state: tuple[int, tuple[int, ...], float | None]) -> None: + if type(state) is not tuple: + raise AssertionError(f"state must be a tuple, got {type(state)}") + if type(state[0]) is not int: + raise AssertionError(f"state[0] must be an int, got {type(state[0])}") + if type(state[1]) is not tuple: + raise AssertionError(f"state[1] must be a tuple, got {type(state[1])}") + if not all(type(x) is int for x in state[1]): + raise AssertionError("all elements of state[1] must be int") + if state[2] is not None and type(state[2]) is not float: + raise AssertionError( + f"state[2] must be None or float, got {type(state[2])}" + ) + + @staticmethod + def wrap_state(state: tuple[int, tuple[int, ...], float | None]) -> TupleVariable: + RandomVariable.check_state(state) + return variables.TupleVariable( + [ + variables.ConstantVariable.create(state[0]), + variables.TupleVariable( + [variables.ConstantVariable.create(x) for x in state[1]] + ), + variables.ConstantVariable.create(state[2]), + ] + ) + + @staticmethod + def unwrap_state( + state: VariableTracker, + ) -> tuple[int, tuple[int, ...], float | None]: + state_obj = state.as_python_constant() + RandomVariable.check_state(state_obj) + return state_obj + + def seed( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + tx.output.side_effects.mutation(self) + self.random.seed( + *[x.as_python_constant() for x in args], + **{key: val.as_python_constant() for key, val in kwargs.items()}, + ) + return variables.ConstantVariable.create(None) + + def getstate( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self.wrap_state(self.random.getstate()) + + def setstate( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + tx.output.side_effects.mutation(self) + self.random.setstate(self.unwrap_state(args[0])) + return variables.ConstantVariable.create(None) + + def shuffle( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + name = "shuffle" + check_positional(tx, name, len(args), 1, 1) + no_keywords(tx, name, kwargs) + seq = args[0].realize() + tx.output.side_effects.mutation(self) + # shuffle's permutation depends only on the sequence length and the + # RNG state, not on the elements, so shuffle a list of indices to + # both advance the symbolic RNG and obtain the permutation to apply. + if not hasattr(seq, "items"): + raise AssertionError("shuffle only supports ListVariable and TupleVariable") + perm = list(range(len(seq.items))) + self.random.shuffle(perm) + tx.output.side_effects.mutation(seq) + seq.items[:] = [seq.items[i] for i in perm] + return variables.ConstantVariable.create(None) + + def sample( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + name = "sample" + check_positional(tx, name, len(args), 2, 2) + no_keywords(tx, name, kwargs) + elems = unpack_iterable(tx, args[0]) + k = args[1].as_python_constant() + if not isinstance(k, int) or k < 0 or k > len(elems): + raise_value_error( + tx, + "Sample larger than population or is negative", + ) + tx.output.side_effects.mutation(self) + # Like shuffle, sample's selected positions depend only on the + # population length and RNG state, so sample over an index range to + # advance the symbolic RNG and pick the population elements to keep. + indices = self.random.sample(range(len(elems)), k) + return variables.ListVariable( + [elems[i] for i in indices], + mutation_type=variables.base.ValueMutationNew(), + ) + + def _call_random(self, tx, name, args, kwargs): + tx.output.side_effects.mutation(self) + state = self.random.getstate() + + def call_random_meth(*args: Any, **kwargs: Any) -> Any: + r = random.Random() + r.setstate(state) + return getattr(r, name)(*args, **kwargs) + + # self.random state not actually updated by call_random_meth, so update here + # by calling the method + getattr(self.random, name)( + *[x.as_python_constant() for x in args], + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ) + + return call_random_fn(tx, call_random_meth, args, kwargs) + + def _random( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self._call_random(tx, "random", args, kwargs) + + def _randint( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self._call_random(tx, "randint", args, kwargs) + + def _randrange( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self._call_random(tx, "randrange", args, kwargs) + + def _uniform( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self._call_random(tx, "uniform", args, kwargs) + + tp_methods = { + "seed": Method(seed), + "getstate": Method(getstate), + "setstate": Method(setstate), + "shuffle": Method(shuffle), + "sample": Method(sample), + "random": Method(_random), + "randint": Method(_randint), + "randrange": Method(_randrange), + "uniform": Method(_uniform), + } + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.extend_output( + [ + codegen.create_load_python_module(random), + codegen.create_load_attr("Random"), + ] + ) + ) + codegen.call_function(0, False) + # NOTE using add_push_null may result in NULL being duplicated + # so defer the push_null to call_function + codegen.dup_top() + codegen.load_attr("setstate") + codegen(self.wrap_state(self.random.getstate())) + codegen.call_function(1, True) + codegen.pop_top() + + +class WeakRefVariable(VariableTracker): + def python_type(self) -> type: + return weakref.ref + + @staticmethod + # pyrefly: ignore [bad-override, bad-param-name-override] + def build( + tx: "InstructionTranslatorBase", + weakref_value: weakref.ReferenceType[Any], + source: Source | None, + **options: Any, + ) -> "WeakRefVariable": + if source is None: + raise AssertionError("WeakRefVariable.build requires a source") + callback = weakref_value.__callback__ + callback_source = source and AttrSource(source, "__callback__") + callback_vt = VariableTracker.build(tx, callback, callback_source) + referent = weakref_value() + source = source and WeakRefCallSource(source) + referent_vt = VariableTracker.build(tx, referent, source) + options["source"] = source + return WeakRefVariable(referent_vt, callback_vt, **options) + + def __init__( + self, referent_vt: VariableTracker, callback_vt: VariableTracker, **options: Any + ) -> None: + super().__init__(**options) + self.referent_vt = referent_vt + self.callback_vt = callback_vt + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self.referent_vt + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null(lambda: codegen.load_import_from("weakref", "ref")) + codegen(self.referent_vt) + codegen(self.callback_vt) + codegen.extend_output(create_call_function(2, False)) + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # CPython weakref_hash: hash(referent) + # https://github.com/python/cpython/blob/e76aa128fe/Objects/weakrefobject.c#L186 + from .object_protocol import generic_hash_impl + + return generic_hash_impl(tx, self.referent_vt) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: "VariableTracker", op: str + ) -> "VariableTracker": + from .object_protocol import generic_richcompare + + # Weak references only support equality, not ordering. Two weak references + # are equal if the underlying objects are equal. If the underlying object has + # gone away, they are equal if they are identical. + if op not in ("__eq__", "__ne__") or not isinstance(other, WeakRefVariable): + return ConstantVariable.create(NotImplemented) + return generic_richcompare(tx, self.referent_vt, other.referent_vt, op) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/nn_module.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/nn_module.py new file mode 100644 index 0000000000000000000000000000000000000000..4a0dfd62bcfa4a051eeecaff443f4402e302b237 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/nn_module.py @@ -0,0 +1,1649 @@ +""" +This module implements variable tracking for PyTorch nn.Module instances during Dynamo tracing. + +It provides specialized handling for different types of nn.Module instances through several key classes: + +- NNModuleVariable: Handles instance-specific module tracing, specializing on module id() and placing + parameters directly on the torch.fx.GraphModule. This creates one graph per module instance. + +- UnspecializedNNModuleVariable: Provides class-level module tracing, treating nn.Modules like other + user-defined objects and passing parameters as inputs to the FX graph. This creates one graph per + module class. + +- UnspecializedBuiltinNNModuleVariable: Specifically handles built-in PyTorch modules (e.g. nn.Linear) + with appropriate optimizations. + +- FSDPManagedNNModuleVariable: Special handling for FSDP-wrapped modules with modified guarding behavior + and parameter handling. + +The module integrates with Dynamo's broader tracing functionality to handle module method calls, +parameter access, hooks, and other nn.Module behaviors while maintaining proper scoping and guarding +of module state. +""" + +import collections +import functools +import inspect +import itertools +import re +import types +from collections.abc import Iterable +from contextlib import contextmanager, nullcontext +from typing import Any, TYPE_CHECKING + +import torch.nn +from torch._guards import Source + +from .. import graph_break_hints, trace_rules, variables +from ..exc import ( + handle_observed_exception, + ObservedAttributeError, + raise_observed_exception, + raise_type_error, + unimplemented, + UnspecializeRestartAnalysis, + Unsupported, +) +from ..guards import GuardBuilder, install_guard, make_dupe_guard +from ..mutation_guard import GenerationTracker +from ..source import ( + AttrSource, + ConstDictKeySource, + DictGetItemSource, + FSDPNNModuleSource, + GetItemSource, + NNModuleSource, + UnspecializedNNModuleSource, +) +from ..utils import ( + enumerate_items_with_dict_position, + get_custom_getattr, + get_fake_value, + is_lazy_module, + is_namedtuple, + is_safe_constant, + istensor, + istype, + nnmodule_has_hooks, + object_has_getattribute, + proxy_args_kwargs, + raise_args_mismatch, + set_example_value, + unpatched_nn_module_call, + unpatched_nn_module_call_impl, +) +from .base import Method, typestr, ValueMutationNew, VariableTracker +from .functions import invoke_and_store_as_constant +from .lazy import LazyVariableTracker +from .user_defined import UserDefinedObjectVariable + + +if TYPE_CHECKING: + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + from .constant import ConstantVariable + + +def initialize_lazy_module( + tx: "InstructionTranslatorBase", + mod: torch.nn.Module, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> None: + """ + Fairly coupled helper used by NNModuleVariable and UnspecializedNNModuleVariable. + + Used to cause lazy module to be initialized (and delete its init hook) before tracing. Especially + useful now that 'allowed' modules graph-break on hooks, calling this first ensures there is no hook + by the time we trace __call__ and thus no graph-break for lazy allowed modules. + """ + if inspect.getattr_static(mod, "_initialize_hook", None) is not None: + + def convert_to_fake(x: Any) -> Any: + if is_namedtuple(x): + return type(x)(*(convert_to_fake(elem) for elem in x)) + elif isinstance(x, dict): + return {k: convert_to_fake(v) for k, v in x.items()} # type: ignore[misc] + elif isinstance(x, (list, tuple, set)): + return type(x)(convert_to_fake(elem) for elem in x) + elif isinstance(x, torch.fx.Proxy): + fake = get_fake_value(x.node, tx) + if isinstance(fake, torch.Tensor) and any( + isinstance(s, torch.SymInt) for s in fake.shape + ): + # _infer_parameters runs real ops on the module, so + # symbolic shapes must be concretized to their hints. + shape = [ + s.node.hint if isinstance(s, torch.SymInt) else s + for s in fake.shape + ] + if not all(isinstance(s, int) for s in shape): + raise AssertionError( + f"expected all shape entries to be int, got {shape}" + ) + return torch.empty( # pyrefly: ignore[no-matching-overload] + shape, dtype=fake.dtype, device=fake.device + ) + return fake + else: + return x + + proxy_args, proxy_kwargs = proxy_args_kwargs(args, kwargs) + fake_args = [convert_to_fake(arg) for arg in proxy_args] + fake_kwargs = {k: convert_to_fake(v) for k, v in proxy_kwargs.items()} + try: + mod._infer_parameters(mod, fake_args, fake_kwargs) # type: ignore[operator] + except AttributeError: + # Re-raise with the original error message from the AttributeError + raise_observed_exception( + AttributeError, + tx, + args=["AttributeError during lazy module initialization"], + ) + + +@contextmanager +def record_nn_module_stack( + module_key: str, + source: Source, + tx: "InstructionTranslatorBase", + mod: torch.nn.Module, +) -> Any: + fully_qualified_name = source.name + # Remove redundant namings + fully_qualified_name = re.sub( + r"\._(?:modules|parameters|buffers)\[(['\"])([^'\"\]]+)\1\]", + r".\2", + fully_qualified_name, + ) + num_calls = tx.num_calls.get(fully_qualified_name, 0) + module_key = f"{module_key}@{num_calls}" if num_calls > 0 else module_key + try: + tx.nn_module_stack[module_key] = (fully_qualified_name, mod.__class__) + tx.num_calls[fully_qualified_name] = num_calls + 1 + yield + finally: + del tx.nn_module_stack[module_key] + + +def guard_to_detect_forward_monkeypatching( + source: Source | None, mod: torch.nn.Module +) -> None: + # Users sometimes patch the forward method of a nn module instance to + # perform optimizations like quantization. Though this is not a good + # software practice, but python allows this and Dynamo needs to detect + # this patching. + # + # One way to do this is to add an ID_MATCH guard on every function + # getting inlined (https://github.com/pytorch/pytorch/pull/124975). But + # this increased guard overhead by around 20%. + # + # To keep the guard overhead down, we just guard on the `forward` being + # not present in the mod __dict__. The common case of patching forward + # method adds `forward` in the instance __dict__, whereas the unpatched + # `forward` sits in the type(mod).__dict__ + if source: + if "forward" in mod.__dict__ and callable(mod.__dict__["forward"]): + # Monkeypatched forward method, guard on call-relevant structure. + fwd = mod.__dict__["forward"] + forward_source = AttrSource(source, "forward") + if type(fwd) is types.MethodType: + forward_source = AttrSource(forward_source, "__func__") + install_guard(forward_source.make_guard(GuardBuilder.CLOSURE_MATCH)) + elif isinstance(fwd, functools.partial): + guard_to_detect_forward_partial_monkeypatching( + source, mod, forward_source, fwd + ) + else: + install_guard(forward_source.make_guard(GuardBuilder.CLOSURE_MATCH)) + else: + # Common case - check that the forward key is absent in mod __dict__ + install_guard( + source.make_guard( + functools.partial( + GuardBuilder.NOT_PRESENT_IN_GENERIC_DICT, attr="forward" + ) + ) + ) + + +def guard_to_detect_forward_partial_monkeypatching( + module_source: Source, + mod: torch.nn.Module, + partial_source: Source, + partial_obj: functools.partial[Any], +) -> None: + install_guard(partial_source.make_guard(GuardBuilder.TYPE_MATCH)) + + func_source = AttrSource(partial_source, "func") + if isinstance(partial_obj.func, functools.partial): + guard_to_detect_forward_partial_monkeypatching( + module_source, mod, func_source, partial_obj.func + ) + else: + install_guard(func_source.make_guard(GuardBuilder.CLOSURE_MATCH)) + + args_source = AttrSource(partial_source, "args") + install_guard(args_source.make_guard(GuardBuilder.SEQUENCE_LENGTH)) + for i, arg in enumerate(partial_obj.args): + guard_to_detect_forward_partial_value( + module_source, mod, GetItemSource(args_source, i), arg + ) + + keywords_source = AttrSource(partial_source, "keywords") + if partial_obj.keywords is None: + install_guard(keywords_source.make_guard(GuardBuilder.NONE_MATCH)) + return + + install_guard(keywords_source.make_guard(GuardBuilder.DICT_KEYS_MATCH)) + for key, value in partial_obj.keywords.items(): + guard_to_detect_forward_partial_value( + module_source, mod, DictGetItemSource(keywords_source, key), value + ) + + +def guard_to_detect_forward_partial_value( + module_source: Source, + mod: torch.nn.Module, + value_source: Source, + value: Any, +) -> None: + if value is mod: + dupe_guard = make_dupe_guard(value_source, module_source) + install_guard(value_source.make_guard(dupe_guard or GuardBuilder.ID_MATCH)) + elif isinstance(value, functools.partial): + guard_to_detect_forward_partial_monkeypatching( + module_source, mod, value_source, value + ) + elif type(value) is types.FunctionType: + install_guard(value_source.make_guard(GuardBuilder.CLOSURE_MATCH)) + elif is_safe_constant(value): + install_guard(value_source.make_guard(GuardBuilder.CONSTANT_MATCH)) + else: + install_guard(value_source.make_guard(GuardBuilder.ID_MATCH)) + + +class NNModuleVariable(VariableTracker): + _nonvar_fields = { + "module_type", + "module_key", + "value", + "nn_module_stack_source", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, module_type: type, module_key: str, value: torch.nn.Module, **kwargs: Any + ) -> None: + super().__init__(**kwargs) + self.module_type = module_type + self.module_key = module_key + self.value = value + # pyrefly: ignore[bad-override] + # NOTE: Don't remove this; better than adding suppressions + # everywhere else with asserts + self.source: Source = self.source + self.nn_module_stack_source = self.source + + def get_nn_module_stack_source(self) -> Source: + res = self.nn_module_stack_source or self.source + if not res: + raise AssertionError("nn_module_stack_source must not be None") + return res + + def set_nn_module_stack_source(self, source: Source) -> None: + self.nn_module_stack_source = source + + def python_type(self) -> type: + return self.module_type + + def get_id(self, tx: "InstructionTranslatorBase") -> int | None: + return id(tx.output.get_submodule(self.module_key)) + + def get_real_python_backed_value(self) -> object: + return self.value + + def nb_bool_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + """nb_bool for nn.Module. + + nn.Module itself has no __bool__ or __len__, so bare modules are always + truthy. Subclasses like ModuleList/ModuleDict define __len__, so + bool(module) calls PyObject_IsTrue which falls through nb_bool (NULL) + to sq_length/mp_length. We evaluate on the real module to capture this. + """ + from .constant import ConstantVariable + + mod = tx.output.get_submodule(self.module_key) + return ConstantVariable.create(bool(mod)) + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + mod = tx.output.get_submodule(self.module_key) + return VariableTracker.build(tx, repr(mod)) + + def _wrap_submodule( + self, + tx: "InstructionTranslatorBase", + source: Source, + submod: torch.nn.Module, + *key_extra: Any, + **options: Any, + ) -> None: + return + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase" + ) -> list[VariableTracker]: + # implement list/iter/tuple/etc calls + base = tx.output.get_submodule(self.module_key) + result: list[VariableTracker] = [] + if isinstance(base, torch.nn.ModuleDict): + for name, submod in base.items(): + name_var = VariableTracker.build(tx, name) + tx.output.register_attr_or_module( + submod, + self.module_key, + name, + source=NNModuleSource(GetItemSource(self.source, name)), # type: ignore[arg-type] + ) + result.append(name_var) + return result + + if not isinstance( + base, (torch.nn.ModuleList, torch.nn.ParameterList, torch.nn.Sequential) + ): + raise AssertionError( + f"Expected ModuleList, ParameterList, or Sequential, got {typestr(base)}" + ) + for idx, submod in enumerate(base): + result.append( + tx.output.register_attr_or_module( + submod, + self.module_key, + idx, + source=NNModuleSource(GetItemSource(self.source, idx)), + ) + ) + return result + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> "ConstantVariable": + mod = tx.output.get_submodule(self.module_key) + result = hasattr(mod, name) + install_guard( + self.source.make_guard(functools.partial(GuardBuilder.HASATTR, attr=name)) + ) + return VariableTracker.build(tx, result) + + def is_training(self, tx: "InstructionTranslatorBase") -> bool: + mod = tx.output.get_submodule(self.module_key) + return getattr(mod, "training", False) + + def convert_to_unspecialized(self, tx: "InstructionTranslatorBase") -> None: + """Restart analysis treating this module as an UnspecializedNNModuleVariable""" + mod = tx.output.get_submodule(self.module_key) + GenerationTracker.tag(mod) + + # Mark the class dynamic unless its module initialization + if tx.f_code.co_name != "__init__": + GenerationTracker.mark_class_dynamic(type(mod)) + raise UnspecializeRestartAnalysis + + def _custom_getattr_fallback( + self, + base: torch.nn.Module, + tx: "InstructionTranslatorBase", + name: str, + obj_source: Source, + ) -> VariableTracker | None: + """Check for a __getattr__ and handle it specially if it is implemented""" + if object_has_getattribute(base): + getattribute_fn = inspect.getattr_static(type(base), "__getattribute__") + new_source = ( + AttrSource(obj_source, "__getattribute__") if obj_source else None + ) + try: + return variables.UserMethodVariable( + getattribute_fn, + self, + source=new_source, + ).call_function(tx, [variables.ConstantVariable.create(name)], {}) + except ObservedAttributeError: + handle_observed_exception(tx) + except Unsupported: + unimplemented( + gb_type="Custom __getattribute__ in nn.Module attribute access", + context=f"tp_getattro_impl {self} {name}", + explanation="Dynamo could not trace through the custom " + "`__getattribute__` method on this `nn.Module`.", + hints=[ + "Simplify your `__getattribute__` implementation, " + "or replace it with a targeted `@property`.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + getattr_fn = get_custom_getattr(base, ignore_nn_module_getattr=True) + if getattr_fn is None: + return None + + if not isinstance(getattr_fn, types.FunctionType): + unimplemented( + gb_type="torch.nn.Module with a non-function custom __getattr__", + context=f"tp_getattro_impl {self} {name}", + explanation=( + "Dynamo detected a nn.Module object with a custom " + "`__getattr__` method, but this method is not a standard " + "Python function (e.g., it might be implemented in C/C++). " + "Dynamo cannot currently trace into such non-standard " + "`__getattr__` methods." + ), + hints=[ + "Avoid using objects with non-standard __getattr__ methods " + "within the compiled region. If possible, implement " + "__getattr__ as a standard Python function.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + options = {"source": AttrSource(obj_source, "__getattr__")} + + return variables.UserMethodVariable(getattr_fn, self, **options).call_function( + tx, [VariableTracker.build(tx, name)], {} + ) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + source = self.source and AttrSource(self.source, name) + + base = tx.output.get_submodule(self.module_key) + # NB: We look up attributes in __dict__ directly, bypassing any custom + # __getattribute__. Custom __getattribute__ is only traced through as a + # fallback (via _custom_getattr_fallback) for attributes not found here. + base_dict = object.__getattribute__(base, "__dict__") + object_member = True + all_class_attribute_names = set() + for x in inspect.getmro(base.__class__): + all_class_attribute_names.update(x.__dict__.keys()) + + if not self.source: + unimplemented( + gb_type="getattr with no source", + context=f"tp_getattro_impl {self} {name}", + explanation="Dynamo does not know how to access an attribute " + "on an `nn.Module` instance that lacks a source. This is " + "usually an internal error in Dynamo.", + hints=[*graph_break_hints.DYNAMO_BUG], + ) + + if name == "__dict__": + return self.get_dict_vt(tx) + + subobj = None + if name in base_dict: + subobj = base_dict[name] + elif ( + "_modules" in base_dict + and name in base_dict["_modules"] + and name not in all_class_attribute_names + ): + subobj = base_dict["_modules"][name] + elif "_parameters" in base_dict and name in base_dict["_parameters"]: + subobj = base_dict["_parameters"][name] + elif "_buffers" in base_dict and name in base_dict["_buffers"]: + subobj = base_dict["_buffers"][name] + else: + try: + subobj = inspect.getattr_static(base, name) + object_member = False + except AttributeError: + # see if we can fallback to __getattr__, which is not checked by getattr_static + result = self._custom_getattr_fallback( + base=base, tx=tx, name=name, obj_source=self.source + ) + if result is not None: + return result + # if we can't find a __getattr__, we can't parse this, raise attribute error + raise_observed_exception( + AttributeError, + tx, + args=[f"'{type(base).__name__}' object has no attribute '{name}'"], + ) + + if name == "forward": + guard_to_detect_forward_monkeypatching(self.source, base) + + if name == "__class__" and not object_member: + return VariableTracker.build(tx, base.__class__, source=source) + + if object_member: + out = VariableTracker.build(tx, subobj, NNModuleSource(source)) # type: ignore[arg-type] + + if isinstance(out, (NNModuleVariable, UnspecializedNNModuleVariable)): + # nn_module_stack source is BC surface area. Ensure that + # mod._modules["linear"] is reflected as mod.linear for + # nn_module_stack. + out.set_nn_module_stack_source( + AttrSource(self.get_nn_module_stack_source(), name) + ) + return out + + else: + if istype(subobj, property): + if self.source: + # Read the class attribute to reach the property + source = AttrSource(AttrSource(self.source, "__class__"), name) + # Get the getter function + source = AttrSource(source, "fget") + return variables.UserFunctionVariable( + subobj.fget, # pyrefly: ignore[bad-argument-type] + source=source, + ).call_function(tx, [(self)], {}) + elif istype(subobj, classmethod): + return variables.UserMethodVariable( + subobj.__func__, + variables.UserDefinedObjectVariable(type(base)), + source=source, + ) + elif istype(subobj, staticmethod): + return variables.UserFunctionVariable( + subobj.__get__(base), + source=source, + ) + elif istype(subobj, types.FunctionType): + return variables.UserMethodVariable(subobj, self, source=source) + elif is_safe_constant(subobj) or istensor(subobj): + # Support possibly common cases of class members + return VariableTracker.build(tx, subobj, NNModuleSource(source)) # type: ignore[arg-type] + else: + unimplemented( + gb_type="Unsupported nn.Module attribute type", + context=f"nn.Module subclass: {typestr(base)}, name: {name}, attribute type: {typestr(subobj)}", + explanation=f"Dynamo does not support tracing nn.Module attributes of type `{typestr(subobj)}`", + hints=[ + f"Refactor your code so that `{name}` (type `{typestr(subobj)}`) is not an attribute of `{typestr(base)}`", + "Currently supported attribute types are methods, classmethods, staticmethods, " + "properties, constants, and tensors.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + return super().tp_getattro_impl(tx, name) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + mod = tx.output.get_submodule(self.module_key) + + with record_nn_module_stack( + self.module_key, self.get_nn_module_stack_source(), tx, mod + ): + is_lazy = is_lazy_module(mod) + if ( + isinstance(mod, torch.nn.Sequential) + and mod.__class__.forward is torch.nn.Sequential.forward + ): + if nnmodule_has_hooks(mod): + # We do not want to unroll sequential if it has hooks, since evaporating it + # will cause hooks to not fire! + # This terminates and restart the tracing process + self.convert_to_unspecialized(tx) + + # Unroll sequential + if is_lazy: + raise AssertionError( + "Expected lazy sequential isn't a valid combination?" + ) + if kwargs: + raise_args_mismatch( + tx, + "torch.nn.Module.Sequential", + "0 kwargs", + f"{len(kwargs)} kwargs", + ) + (arg,) = args + # TODO: Use named_children when it supports remove_duplicate=False. + for child_name, submod in mod._modules.items(): + tx.call_function( + tx.output.register_attr_or_module( + submod, + self.module_key, + child_name, + source=NNModuleSource(AttrSource(self.source, child_name)), # type: ignore[arg-type] + ), + [arg], + {}, + ) + arg = tx.pop() + return arg + + if is_lazy: + # The module type will change after it is called + if mod.cls_to_become is not None: + self.module_type = mod.cls_to_become # type: ignore[assignment] + + # The pre-hook runs to initialize the module shapes, then deletes itself. After this, + # the module is more or less not lazy and can be treated as a normal module regardless of + # is_allowed or other variations. + initialize_lazy_module(tx, mod, args, kwargs) + + # If we are tracing the higher order op, we want Dynamo to step + # inside the module call so that Dynamo can see the underlying + # parameters and buffers and raise them as inputs to the graph. + # + # NB: torch.nn.utils.parametrize changes the class type of a + # parametrized module such that its __module__ points to + # "torch.nn.utils.parametrize". + if ( + tx.output.is_root_tracer() + and mod.__module__.startswith(("torch.nn.", "torch.ao.")) + and mod.__module__ != "torch.nn.utils.parametrize" + ): + if nnmodule_has_hooks( + mod, check_forward_hooks=True, check_backward_hooks=True + ): + # End of fn, this bubbles up and restarts tracing. + self.convert_to_unspecialized(tx) + + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_module", + self.module_key, + *proxy_args_kwargs(args, kwargs), + ), + ) + else: + if isinstance(mod, torch.fx.GraphModule): + # TODO: do we want to support __call__ for GM's? + # If so at least some changes are needed, we don't allow inlining + # the call_wrapped currently, and maybe other issues too + fn = mod.forward + fn_source = AttrSource(self.source, "forward") + else: + fn = mod._call_impl + fn_source = AttrSource(self.source, "_call_impl") + if istype(fn, types.MethodType): + fn = fn.__func__ + fn_source = AttrSource(fn_source, "__func__") + args = [self] + list(args) + else: + if not istype(fn, types.FunctionType): + raise AssertionError(f"Expected FunctionType, got {type(fn)}") + return tx.inline_user_function_return( + variables.UserFunctionVariable(fn, source=fn_source), + args, + kwargs, + allow_nested_graph_breaks=True, + ) + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: "VariableTracker", + ) -> "VariableTracker": + # nn.Module containers (ModuleList/Dict/Sequential/ParameterDict/ParameterList) + # These are Python-level __getitem__, not CPython C slots. + from .lists import SliceVariable + from .tensor import SymNodeVariable + + module = tx.output.get_submodule(self.module_key) + + builtin_supported = ( + torch.nn.ModuleDict.__getitem__, + torch.nn.ModuleList.__getitem__, + torch.nn.ParameterDict.__getitem__, + torch.nn.ParameterList.__getitem__, + torch.nn.Sequential.__getitem__, + ) + # pyrefly: ignore[missing-attribute] + if type(module).__getitem__ not in builtin_supported: + if not ( + key.is_python_constant() + and isinstance(key.as_python_constant(), (str, int)) + ): + unimplemented( + gb_type="Invalid or non-const argument in nn.Module __getitem__", + context=f"mp_subscript_impl: {self} {key}", + explanation="Dynamo does not support calling " + f"method `__getitem__` of ``nn.Module`` {module} with a non-constant or non-(str, int) key.", + hints=["Use constant arguments of type str or int for __getitem__"], + ) + fn = module.__getitem__.__func__ # pyrefly: ignore[missing-attribute] + + if not isinstance(fn, types.FunctionType): + raise AssertionError(f"Expected FunctionType, got {type(fn)}") + + src = AttrSource(AttrSource(self.source, "__getitem__"), "__func__") # type: ignore[arg-type] + return tx.inline_user_function_return( + variables.UserFunctionVariable(fn, source=src), + [self, key], + {}, + allow_nested_graph_breaks=True, + ) + + if isinstance(key, SliceVariable): + # TODO(anijain2305,export-team) - Remove this if condition when inlining of inbuilt nn modules is + # enabled for export. + if tx.output.export: + result = [] + keys = list(range(len(module)))[key.as_python_constant()] # type: ignore[arg-type] + for idx, submod in enumerate(module[key.as_python_constant()]): # type: ignore[arg-type] + k = keys[idx] + src = NNModuleSource(GetItemSource(self.source, k)) + result.append( + tx.output.register_attr_or_module( + submod, + k, + source=src, + ) + ) + + new_module = module[key.as_python_constant()] # type: ignore[index] + new_module_variable = tx.output.register_attr_or_module( + new_module, + f"{self}.__getitem__(slice)", + source=NNModuleSource( + GetItemSource(self.source, key.as_python_constant()) + ), + ) + return new_module_variable + else: + # slice on nn module results in a creation of new module instance, so we need to make it sourceless. + # Convert to unspecialized so that UnspecializedNNModule variable can take care of it. + self.convert_to_unspecialized(tx) + + key_value = 0 + if isinstance(key, SymNodeVariable): + key_value = key.evaluate_expr(tx.output) + elif key.is_python_constant(): + key_value = key.as_python_constant() + else: + unimplemented( + gb_type="Unsupported key type for nn.Module.__getitem__", + context=f"mp_subscript_impl: {self} {key}", + explanation="Dynamo does not support getitem on " + "`nn.Module` with non-constant key.", + hints=[], + ) + + submod = module[key_value] # type: ignore[index] + return tx.output.register_attr_or_module( + submod, + self.module_key, + key_value, + source=NNModuleSource(GetItemSource(self.source, key_value)), + ) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + from . import ListIteratorVariable + + return ListIteratorVariable( + self.unpack_var_sequence(tx), mutation_type=ValueMutationNew() + ) + + @staticmethod + def _gen_source(source: Source, name: str) -> Source: + name_split = name.split(".") + if name_split[0] == "": + return source + while len(name_split) > 0: + x = name_split.pop(0) + source = AttrSource(source, x) + return source + + def _generic_call_method_helper( + self, tx: "InstructionTranslatorBase", name: str, args: Any, kwargs: Any + ) -> VariableTracker: + # Put a `call_method` node in the FX graph, with the nn.Module as the + # first arg. + module = tx.output.get_submodule(self.module_key) + mod_proxy = tx.output.create_proxy("get_attr", self.module_key, (), {}) + set_example_value(mod_proxy.node, module) + proxy_args, proxy_kwargs = proxy_args_kwargs(args, kwargs) + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_method", name, args=(mod_proxy, *proxy_args), kwargs=proxy_kwargs + ), + ) + + def _assert_all_args_kwargs_const( + self, tx: "InstructionTranslatorBase", name: str, args: Any, kwargs: Any + ) -> None: + if not all( + x.is_python_constant() for x in itertools.chain(args, kwargs.values()) + ): + module = tx.output.get_submodule(self.module_key) + unimplemented( + gb_type="non-const argument in nn.Module method", + context=f"call_method: {self} {name} {args} {kwargs}", + explanation="Dynamo does not support calling " + f"method `{name}` of ``nn.Module`` {module} with non-constant arguments.", + hints=[], + ) + + def _get_kwargs( + self, + tx: "InstructionTranslatorBase", + name: str, + args: Any, + kwargs: Any, + *names: str, + ) -> dict[str, Any]: + self._assert_all_args_kwargs_const(tx, name, args, kwargs) + module = tx.output.get_submodule(self.module_key) + fn = getattr(module, name) + bound_args = inspect.signature(fn).bind( + *([x.as_python_constant() for x in args]), + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ) + bound_args.apply_defaults() + bound_args = bound_args.arguments + return {k: bound_args[k] for k in names} + + def _wrap_values( + self, tx: "InstructionTranslatorBase", items: Iterable[tuple[Any, Any]] + ) -> "variables.ListIteratorVariable": + result: list[VariableTracker] = [] + for name, submod in items: + result.append( + tx.output.register_attr_or_module( + submod, + self.module_key, + name, + source=NNModuleSource(self._gen_source(self.source, name)), + ) + ) + return variables.ListIteratorVariable(result, mutation_type=ValueMutationNew()) + + def _named_embed( + self, tx: "InstructionTranslatorBase", name: str, obj: Any + ) -> "variables.TupleVariable": + return variables.TupleVariable( + [ + VariableTracker.build(tx, name), + tx.output.register_attr_or_module( + obj, + self.module_key, + name, + source=NNModuleSource(self._gen_source(self.source, name)), + ), + ] + ) + + def _call_impl( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Example: `self.layer.__call__(x)`. Dynamo inlines `__call__`, + # including hooks. + return self.call_function(tx, args, kwargs) + + def forward( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Example: `self.layer.forward(x)`. Dynamo puts a `call_method` node in + # the FX graph and does not trigger hooks. + module = tx.output.get_submodule(self.module_key) + with record_nn_module_stack( + self.module_key, self.get_nn_module_stack_source(), tx, module + ): + return self._generic_call_method_helper(tx, "forward", args, kwargs) + + def _get_item_by_idx( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + if not args[1].is_python_constant(): + raise_type_error( + tx, + f"``nn.Module`` {module}'s call method _get_item_by_idx requires a constant index argument", + ) + if not isinstance(args[0], variables.TupleVariable): + raise_type_error( + tx, + f"``nn.Module`` {module}'s call method _get_item_by_idx requires a tuple as first argument", + ) + mod_var = args[0].items[args[1].as_python_constant()] + if isinstance(mod_var, UnspecializedNNModuleVariable): + return mod_var + key = mod_var.module_key + submod = tx.output.get_submodule(key) + return tx.output.register_attr_or_module( + submod, key, key, source=NNModuleSource(GetItemSource(self.source, key)) + ) + + def named_children( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + tx.output.guard_on_key_order.add(AttrSource(self.source, "_modules")) + if args or kwargs: + raise_args_mismatch( + tx, + "named_children", + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + result: list[VariableTracker] = [] + for n, submod in module.named_children(): + result.append(self._named_embed(tx, n, submod)) + return variables.ListIteratorVariable(result, mutation_type=ValueMutationNew()) + + def named_parameters( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + tx.output.guard_on_key_order.add(AttrSource(self.source, "_parameters")) + kw = self._get_kwargs(tx, "named_parameters", args, kwargs, "prefix", "recurse") + result: list[VariableTracker] = [] + for n, param in module.named_parameters(**kw): + result.append(self._named_embed(tx, n, param)) + return variables.ListIteratorVariable(result, mutation_type=ValueMutationNew()) + + def named_buffers( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + tx.output.guard_on_key_order.add(AttrSource(self.source, "_buffers")) + kw = self._get_kwargs( + tx, "named_buffers", args, kwargs, "prefix", "recurse", "remove_duplicate" + ) + result: list[VariableTracker] = [] + for n, buffer in module.named_buffers(**kw): + result.append(self._named_embed(tx, n, buffer)) + return variables.ListIteratorVariable(result, mutation_type=ValueMutationNew()) + + def named_modules( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + tx.output.guard_on_key_order.add(AttrSource(self.source, "_modules")) + kw = self._get_kwargs( + tx, "named_modules", args, kwargs, "memo", "prefix", "remove_duplicate" + ) + result: list[VariableTracker] = [] + for n, submod in module.named_modules(**kw): + result.append(self._named_embed(tx, n, submod)) + return variables.ListIteratorVariable(result, mutation_type=ValueMutationNew()) + + def children( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + tx.output.guard_on_key_order.add(AttrSource(self.source, "_modules")) + if args or kwargs: + raise_args_mismatch( + tx, + "children", + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + return self._wrap_values(tx, module.named_children()) + + def modules( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + tx.output.guard_on_key_order.add(AttrSource(self.source, "_modules")) + return self._wrap_values(tx, module.named_modules()) + + def parameters( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + tx.output.guard_on_key_order.add(AttrSource(self.source, "_parameters")) + kw = self._get_kwargs(tx, "parameters", args, kwargs, "recurse") + return self._wrap_values(tx, module.named_parameters(**kw)) + + def buffers( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + tx.output.guard_on_key_order.add(AttrSource(self.source, "_buffers")) + kw = self._get_kwargs(tx, "buffers", args, kwargs, "recurse") + return self._wrap_values(tx, module.named_buffers(**kw)) + + def keys( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + if args or kwargs: + raise_args_mismatch( + tx, + "keys", + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + result: list[VariableTracker] = [] + # pyrefly: ignore[not-iterable] + for tmp in module: + result.append(VariableTracker.build(tx, tmp)) + return variables.ListIteratorVariable(result, mutation_type=ValueMutationNew()) + + def values( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + if args or kwargs: + raise_args_mismatch( + tx, + "values", + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + return self._wrap_values(tx, module.items()) # type: ignore[operator] + + def items( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + module = tx.output.get_submodule(self.module_key) + if args or kwargs: + raise_args_mismatch( + tx, + "items", + "0 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + result: list[VariableTracker] = [] + for n, submod in module.items(): # type: ignore[operator] + result.append(self._named_embed(tx, n, submod)) + return variables.ListIteratorVariable(result, mutation_type=ValueMutationNew()) + + tp_methods = { + "_call_impl": Method(_call_impl), + "_wrapped_call_impl": Method(_call_impl), + "forward": Method(forward), + "_get_item_by_idx": Method(_get_item_by_idx), + "named_children": Method(named_children), + "named_parameters": Method(named_parameters), + "named_buffers": Method(named_buffers), + "named_modules": Method(named_modules), + "children": Method(children), + "modules": Method(modules), + "parameters": Method(parameters), + "buffers": Method(buffers), + "keys": Method(keys), + "values": Method(values), + "items": Method(items), + } + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + constant: bool = False, + ) -> VariableTracker: + from .constant import ConstantVariable + + module = tx.output.get_submodule(self.module_key) + + if name == "_check_input_dim" and trace_rules.is_torch_inline_allowed( + inspect.getfile(module.__class__._check_input_dim) # type: ignore[union-attr] + ): + return ConstantVariable.create(True) + + if constant: + fn = getattr(module, name) + const_name = f"{module.__class__.__name__}_{name}_result" + return invoke_and_store_as_constant(tx, fn, const_name, args, kwargs) + + if name == "__iter__": + return self.tp_iter_impl(tx) + elif ( + name == "__contains__" + and isinstance(module, (torch.nn.ModuleDict, torch.nn.ParameterDict)) + and args + and args[0].is_python_constant() + ): + return VariableTracker.build( + tx, args[0].as_python_constant() in module._modules + ) + elif ( + name == "_get_abs_string_index" + or ( + isinstance(module, torch.nn.modules.conv._ConvNd) + and name == "_conv_forward" + ) + or ( + isinstance(module, torch.nn.modules.conv._ConvTransposeNd) + and name == "_output_padding" + ) + ): + # Inline the function + fn = getattr(module, name).__func__ + fn_source = AttrSource(AttrSource(self.source, name), "__func__") # type: ignore[arg-type] + return tx.inline_user_function_return( + variables.UserFunctionVariable(fn, source=fn_source), + [self] + list(args), + kwargs, + ) + # A loose heuristic, but seems to be generally good before we drop into + # the manual handling of inputs. Skip tp_methods names so they reach the + # declarative dispatch in the base call_method. + elif ( + name not in self.tp_methods + and name in module.__class__.__dict__ + and callable(module.__class__.__dict__[name]) + and all(x.is_tensor() for x in itertools.chain(args, kwargs.values())) + ): + return self._generic_call_method_helper(tx, name, args, kwargs) + else: + return super().call_method(tx, name, list(args), kwargs) + + def sq_length_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + """Sequence length for container modules (e.g., nn.Sequential).""" + module = tx.output.get_submodule(self.module_key) + return VariableTracker.build(tx, len(module)) # type: ignore[arg-type] + + +class UnspecializedNNModuleVariable(UserDefinedObjectVariable): + _nonvar_fields = { + "value_type", + "is_state_mutated", + "nn_module_stack_source", + *UserDefinedObjectVariable._nonvar_fields, + } + + """ + The above class will specialize on the id() of a module and place + parameters on the torch.fx.GraphModule. Giving one graph per + module instance. This version treats nn.Modules() like other user + defined objects and will pass parameters into the FX graph as inputs. + Giving one graph per module class. + """ + + def __init__(self, value: torch.nn.Module, **kwargs: Any) -> None: + if "value_type" in kwargs: + lazy_value_to_become = getattr(kwargs["value_type"], "cls_to_become", None) + if type(value) is lazy_value_to_become: + # We may have cloned a variabletracker for a LazyModule earlier (e.g. tracking side-effects) + # and then later we called and mutated the LazyModule into a MaterializedModule. + # We do not do the mutation upon first seeing a LazyModule since we preserve eager semantics to only + # mutate upon first call, but this requires we update multiple copies of the VariableTracker post-mutation. + kwargs["value_type"] = type(value) + + super().__init__(value=value, **kwargs) + self.is_state_mutated = False + # nn_module_stack_source is used to ensure BC for nn_module_stack. + # Downstream users prefer mod.linear instead of mod._modules['linear'] + # as the module stack. When Dynamo inlines the __getattr__ method, we + # cannot use self.source for nn_module_stack because it will be similar + # to mod._modules['linear']. In these cases, we set the + # nn_module_stack_source appropriately to resemble mod.linear. + self.nn_module_stack_source = self.source + + def _wrap_source(self, attr_source: Source) -> Source: + # the vt is already wrapped with UnspecializedNNModuleSource + return attr_source + + def get_nn_module_stack_source(self) -> Source: + res = self.nn_module_stack_source or self.source + if not res: + raise AssertionError("nn_module_stack_source must not be None") + return res + + def set_nn_module_stack_source(self, source: Source) -> None: + self.nn_module_stack_source = source + + @staticmethod + @functools.cache + def _nn_module_method_ids() -> set[int]: + # Allow __setattr__ to fall through to base class handler + supported = { + torch.nn.Module.__setattr__, + torch.nn.Module.__init__, + torch.nn.Module.__delattr__, + } + return { + id(x.__code__) + for x in torch.nn.Module.__dict__.values() + if hasattr(x, "__code__") and x not in supported + } + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase" + ) -> list[VariableTracker]: + try: + fn = inspect.getattr_static(self.value_type, "__iter__") + except AttributeError as e: + raise NotImplementedError from e + + if fn in ( + torch.nn.ModuleList.__iter__, + torch.nn.ParameterList.__iter__, + torch.nn.Sequential.__iter__, + ): + # The program can mutate the nn module object but the saved `value` + # will not reflect the mutations. So, trace through the `__iter__` + # function to reflect any tracked mutations. + return tx.inline_user_function_return( + VariableTracker.build(tx, fn), + [ + self, + ], + {}, + ).unpack_var_sequence(tx) + + return super().unpack_var_sequence(tx) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + mod = self.value + # see comment on lazy module handling in NNModuleVariable.call_function for context + if is_lazy_module(mod): # type: ignore[arg-type] + if mod.cls_to_become is not None: # type: ignore[attr-defined] + self.value_type = mod.cls_to_become # type: ignore[attr-defined,assignment] + initialize_lazy_module(tx, mod, args, kwargs) # type: ignore[arg-type] + + if not isinstance(mod, torch.fx.GraphModule): + name = "__call__" + fn = getattr(self.value_type, name) + else: + name = "_call_impl" + fn = getattr(self.value_type, name) + + # Check if we can short circuit nn.Module._call_impl to the forward + # method. NB - This is done to reduce the compile time of Dynamo. + if ( + istype(mod.__call__, types.MethodType) # type: ignore[operator] + and istype(mod._call_impl, types.MethodType) # type: ignore[attr-defined] + and mod.__call__.__func__ is unpatched_nn_module_call # type: ignore[operator] + and mod._call_impl.__func__ is unpatched_nn_module_call_impl # type: ignore[attr-defined] + # Consult pending STORE_ATTR side effects too. During tracing the + # patched forward may not be visible in mod.__dict__ yet. + and not self.has_key_in_generic_dict(tx, "forward") + ): + forward_method = inspect.getattr_static(mod, "forward") + if isinstance(forward_method, types.FunctionType): + globals_vt = tx.nn_modules_globals_vt + + def _hooks_dict_len(obj: VariableTracker, attr: str) -> int: + vt = obj.tp_getattro_impl(tx, attr) + vt = vt.realize() if hasattr(vt, "realize") else vt + return vt.len() # type: ignore[union-attr] + + has_hooks = any( + _hooks_dict_len(self, attr) + for attr in ( + "_backward_hooks", + "_backward_pre_hooks", + "_forward_hooks", + "_forward_hooks_with_kwargs", + "_forward_pre_hooks", + "_forward_pre_hooks_with_kwargs", + ) + ) or any( + _hooks_dict_len(globals_vt, attr) + for attr in ( + "_global_backward_pre_hooks", + "_global_backward_hooks", + "_global_forward_hooks", + "_global_forward_pre_hooks", + ) + ) + + if not has_hooks: + name = "forward" + fn = self.value_type.forward # type: ignore[attr-defined] + + if self.source: + source = self.get_source_by_walking_mro(tx, name) + else: + source = None + + guard_to_detect_forward_monkeypatching(self.source, mod) # type: ignore[arg-type] + + ctx = ( + record_nn_module_stack( + str(id(mod)), + self.get_nn_module_stack_source(), + tx, + mod, # type: ignore[arg-type] + ) + if self.source + else nullcontext() + ) + with ctx: + if not isinstance(fn, (types.FunctionType, torch.jit.ScriptFunction)): + fn_vt = VariableTracker.build(tx, fn, source=source, realize=True) + return fn_vt.call_function(tx, [self] + list(args), kwargs) + else: + # Ideally we would have just used VariableTracker.build(tx, fn, + # source=source) but that introduces guard on the + # `forward.__code__` object. Given that we already guard on the + # forward not present in generic dict, we don't need this guard. + return variables.UserFunctionVariable(fn, source=source).call_function( + tx, [self] + list(args), kwargs + ) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name in ["_call_impl", "_wrapped_call_impl"]: + fn = getattr(self.value_type, name) + if self.source: + source = self.get_source_by_walking_mro(tx, name) + else: + source = None + + fn_vt = VariableTracker.build(tx, fn, source=source, realize=True) + return fn_vt.call_function(tx, [self] + list(args), kwargs) + + if not self.has_key_in_generic_dict(tx, name): + try: + method = inspect.getattr_static(type(self.value), name) + except AttributeError: + method = None + + if isinstance(method, staticmethod): + source = AttrSource( + self.get_source_by_walking_mro(tx, name), "__func__" + ) + fn_vt = VariableTracker.build( + tx, method.__func__, source=source, realize=True + ) + return fn_vt.call_function(tx, args, kwargs) + + if ( + hasattr(method, "__code__") + and id(method.__code__) in self._nn_module_method_ids() + ): + unimplemented( + gb_type="UnspecializedNNModuleVariable missing method", + context=f"call_method: {self} {name} {args} {kwargs}", + explanation=f"Dynamo does not support tracing method {name} of nn.Module {self.value}", + hints=[ + "Dynamo does not really define unspecialized nn.Module very well.", + *graph_break_hints.DIFFICULT, + ], + ) + + # "_parameters" in self.value.__dict__ checks that module is initialized + if name == "__setattr__" and "_parameters" in self.value.__dict__: + # Record if mutations happens on parameters/buffers/modules. The + # mutations on these are not tracked by base class + # UserDefinedObject vt. This will be used later to graph break + # on seeing a parameters() and family calls. + # TODO(anijain2305) - This might not be needed if we let Dynamo + # inline both getattr and setattr. In that case, it should see + # the lowest level dicts - _parameters and family and + # automatically track mutations on those. Investigate if that + # can be done. + attr_name = args[0].as_python_constant() + value = args[1] + + # This is reverse engineered by looking at nn module __setattr__ + # logic. + if ( + value.is_tensor() and value.python_type() is torch.nn.Parameter + ) or attr_name in self.value.__dict__["_parameters"]: + # Handle parameters + self.is_state_mutated = True + elif attr_name in self.value.__dict__["_buffers"]: + # Handle buffers + self.is_state_mutated = True + elif ( + isinstance( + value, + ( + variables.NNModuleVariable, + variables.UnspecializedNNModuleVariable, + ), + ) + or attr_name in self.value.__dict__["_modules"] + ): + # Handle submodules + self.is_state_mutated = True + + if ( + method is torch.nn.Module.__setattr__ + and isinstance(args[1], variables.DeletedVariable) + ) or method is torch.nn.Module.__delattr__: + # Trace through __delattr__ to track mutations on the module + # members like `_modules``. + fn_vt = VariableTracker.build(tx, torch.nn.Module.__delattr__) + return fn_vt.call_function(tx, [self, args[0]], kwargs) + + return super().call_method(tx, name, list(args), kwargs) + + def getattr_helper( + self, tx: "InstructionTranslatorBase", field: str, name_vt: VariableTracker + ) -> VariableTracker | None: + dict_vt = self.tp_getattro_impl(tx, field) + if isinstance(dict_vt, variables.UserDefinedDictVariable): + dict_vt = dict_vt._base_vt + if isinstance(dict_vt, variables.ConstDictVariable): + return dict_vt.maybe_getitem_const(name_vt) + return None + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if ( + tx.output.side_effects.is_attribute_mutation(self) + and name + in ( + "named_parameters", + "parameters", + "named_buffers", + "buffers", + "named_modules", + "modules", + ) + and self.is_state_mutated + and tx.output.side_effects.has_pending_mutation(self) + ): + unimplemented( + gb_type="getattr() on nn.Module with pending mutation", + context=f"getattr({self}, {name})", + explanation="Intentionally graph breaking on getattr() on a nn.Module " + "with a pending mutation", + hints=[], + ) + + # Allow skipping of empty hook dict guards on inbuilt nn modules + if name in ( + "_backward_hooks", + "_backward_pre_hooks", + "_forward_hooks_with_kwargs", + "_forward_hooks", + "_forward_pre_hooks_with_kwargs", + "_forward_pre_hooks", + ): + # For empty hooks, make an EMPTY_NN_MODULE_HOOKS_DICT. This allows us to control the installation of empty + # hooks guard via skip_nnmodule_hook_guards + if not tx.output.side_effects.has_pending_mutation_of_attr(self, name): + hooks_dict = getattr(self.value, name) + if isinstance(hooks_dict, dict) and len(hooks_dict) == 0: + hooks_source = ( + AttrSource(self.source, name) if self.source else None + ) + if hooks_source: + install_guard( + hooks_source.make_guard( + GuardBuilder.EMPTY_NN_MODULE_HOOKS_DICT + ) + ) + hooks_vt_cls = ( + variables.OrderedDictVariable + if isinstance(hooks_dict, collections.OrderedDict) + else variables.ConstDictVariable + ) + return hooks_vt_cls({}, source=hooks_source) + + # For non-empty hook dicts, one way is to just fallback to VariableTracker.build() and create a ConstDictVariable. + # However, ConstDictVariable guards on keys. This can cause recompiles when the same hook is installed for + # different nn module instances, because the key keeps changing (look more into RemovableHandle to understand why + # key changes - also related https://github.com/pytorch/pytorch/issues/125836). Here, we carefully craft a + # NNModuleHooksDictVariable (a subclass of ConstDictVariable) to avoid any guard on the keys. + if ( + self.source + and name + in ( + "_forward_pre_hooks_with_kwargs", + "_forward_pre_hooks", + "_forward_hooks_with_kwargs", + "_forward_hooks", + ) + and not tx.output.side_effects.has_pending_mutation_of_attr(self, name) + ): + hooks_dict = getattr(self.value, name) + hooks_dict_source = AttrSource(self.source, name) + install_guard(hooks_dict_source.make_guard(GuardBuilder.SEQUENCE_LENGTH)) + tx.output.guard_on_key_order.add(hooks_dict_source) + + def build_key_value( + i: int, k: Any, v: Any + ) -> tuple[VariableTracker, VariableTracker]: + # Make key sourceless to avoid any guard on it + key = VariableTracker.build(tx, k) + + # Instead of using dict[key] to access the value, use a dict[dict.keys()[index]] to access the + # value. This removes the reliance on the actual key value. + source_key = ConstDictKeySource(hooks_dict_source, i) + source_value = DictGetItemSource(hooks_dict_source, source_key) + value = LazyVariableTracker.create(v, source_value, tx=tx) + return key, value + + result = dict( + build_key_value(i, k, v) + for i, k, v in enumerate_items_with_dict_position(hooks_dict) + ) + + return variables.NNModuleHooksDictVariable(result, source=hooks_dict_source) + return super().tp_getattro_impl(tx, name) + + def manually_trace_nn_module_getattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + """ + Dynamo tracing of nn.Module __getattr__ can be expensive if the model + has deep submodule hierarchy. Since the __getattr__ is stable, we can + directly look into the underlying datastructures. This saves a lot of + compilation time. + """ + from .builder import SourcelessBuilder + + name_vt = SourcelessBuilder.create(tx, name) + out = self.getattr_helper(tx, "_parameters", name_vt) + if out is None: + out = self.getattr_helper(tx, "_modules", name_vt) + if out is None: + out = self.getattr_helper(tx, "_buffers", name_vt) + if out is None: + raise_observed_exception( + AttributeError, + tx, + args=[ + f"'{type(self.value).__name__}' object has no attribute '{name}'" + ], + ) + if out is None: + raise AssertionError( + f"manually_trace_nn_module_getattr failed to find attribute '{name}'" + ) + return out + + +class UnspecializedBuiltinNNModuleVariable(UnspecializedNNModuleVariable): + """ + Differentiates between builtin nn modules (e.g. torch.nn.Linear) and user defined nn modules. + """ + + def _wrap_source(self, attr_source: Source) -> Source: + # vt is already wrapped with the UnspecializedBuiltinNNModuleSource + return attr_source + + +class FSDPManagedNNModuleVariable(UnspecializedNNModuleVariable): + """ + Tracing behavior: trace into submodules and treat them as Unspecialized, do not + register parameters to the top-level, treat them as function inputs. + + Guards behavior: if 'skip_fsdp_guards', many guards that would be installed + by a vanilla UnspecializedNNModuleVariable are simply dropped, on the basis + that a user wrapping their model in FSDP(model) is already opting into a + requirement to not modify internal model state, which would already break FSDP without + compilation. + """ + + def __init__(self, value: torch.nn.Module, **kwargs: Any) -> None: + source = kwargs.get("source") + if source is None: + raise AssertionError( + "FSDPManagedNNModule depends on having an accurate source to control guarding." + ) + + super().__init__(value=value, **kwargs) + self.source = source + + def _wrap_source(self, attr_source: Any) -> Any: + if not isinstance( + attr_source, (FSDPNNModuleSource, UnspecializedNNModuleSource) + ): + if torch._dynamo.config.skip_fsdp_guards: + return FSDPNNModuleSource(attr_source) + else: + return UnspecializedNNModuleSource(attr_source) + return attr_source diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/object_protocol.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/object_protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..e9cde39513351a6959a614bf1ebee5a85b70324a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/object_protocol.py @@ -0,0 +1,2311 @@ +""" +Dynamo implementations of CPython's PyObject_* default slot algorithms. + +Analogous to CPython's Objects/object.c, this module holds the general +dispatch machinery that is independent of any specific type. +Per-type hook implementations (nb_bool_impl, tp_richcompare_impl, tp_getattro_impl, +etc.) live in their respective VT files. +""" + +import abc +import collections +import enum +import sys +import types +import typing +from functools import lru_cache, partial +from typing import NoReturn, TYPE_CHECKING + +import torch +from torch._C._dynamo import ( + get_type_slots, + has_slot, + PyMappingSlots, + PyNumberSlots, + PySequenceSlots, + PyTypeSlots, +) + +from .. import graph_break_hints, polyfills, variables +from ..exc import ( + handle_observed_exception, + ObservedTypeError, + raise_observed_exception, + raise_type_error, + UnhandledDescriptorError, + unimplemented, +) +from ..source import AttrSource, Source +from ..utils import istype +from .base import ( + AsPythonConstantNotImplementedError, + AttrMutationKind, + maybe_get_python_type, + NO_SUCH_SUBOBJ, + VariableTracker, +) +from .constant import ConstantVariable + + +if TYPE_CHECKING: + from ..symbolic_convert import InstructionTranslatorBase + + +def vt_identity_compare( + left: VariableTracker, + right: VariableTracker, +) -> "VariableTracker | None": + """Try to determine Python identity (left is right) at trace time. + + Returns ConstantVariable(True/False) if determinable, else None. + Mirrors the logic in BuiltinVariable's handle_is handler. + """ + if left is right: + return ConstantVariable.create(True) + + left_val = left.get_real_python_backed_value() + right_val = right.get_real_python_backed_value() + left_known = left_val is not NO_SUCH_SUBOBJ + right_known = right_val is not NO_SUCH_SUBOBJ + + if left_known and right_known: + return ( + ConstantVariable.create(True) + if left_val is right_val + else ConstantVariable.create(False) + ) + + # One side has a concrete backing object, the other doesn't — they can't + # be the same object. + if left_known != right_known: + return ConstantVariable.create(False) + + # Objects created during tracing: VT identity = Python identity. + from .dicts import ConstDictVariable + from .lists import ListVariable + from .misc import TracebackVariable + from .sets import SetVariable + + if isinstance( + left, (ConstDictVariable, ListVariable, SetVariable, TracebackVariable) + ): + return ConstantVariable.create(False) + + # Different Python types can never be the same object. + try: + if left.python_type() is not right.python_type(): + return ConstantVariable.create(False) + except NotImplementedError: + pass + + # Different exception types are never identical. + if ( + istype(left, variables.ExceptionVariable) + and istype(right, variables.ExceptionVariable) + and left.exc_type is not right.exc_type # type: ignore[attr-defined] + ): + return ConstantVariable.create(False) + + return None + + +def binop_type_error( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, + op_symbol: str, +) -> NoReturn: + raise_type_error( + tx, + f"unsupported operand type(s) for {op_symbol}: '{v.python_type_name()}' and '{w.python_type_name()}'", + ) + + +@lru_cache(maxsize=256) +def _get_cached_slots(obj_type: type) -> tuple[int, int, int, int]: + """Get all type slots for a type (cached).""" + return get_type_slots(obj_type) + + +def type_implements_sq_slot(obj_type: type, slot: int) -> bool: + """Check whether obj_type implements the given sq slot.""" + seq_slots, _, _, _ = _get_cached_slots(obj_type) + return has_slot(seq_slots, slot) + + +def type_implements_mp_slot(obj_type: type, slot: int) -> bool: + """Check whether obj_type implements the given mp slot.""" + _, map_slots, _, _ = _get_cached_slots(obj_type) + return has_slot(map_slots, slot) + + +# PySequenceSlots +type_implements_sq_item = partial(type_implements_sq_slot, slot=PySequenceSlots.SQ_ITEM) +type_implements_sq_length = partial( + type_implements_sq_slot, slot=PySequenceSlots.SQ_LENGTH +) +type_implements_sq_concat = partial( + type_implements_sq_slot, slot=PySequenceSlots.SQ_CONCAT +) +type_implements_sq_inplace_concat = partial( + type_implements_sq_slot, slot=PySequenceSlots.SQ_INPLACE_CONCAT +) +type_implements_sq_contains = partial( + type_implements_sq_slot, slot=PySequenceSlots.SQ_CONTAINS +) +type_implements_sq_ass_item = partial( + type_implements_sq_slot, slot=PySequenceSlots.SQ_ASS_ITEM +) +type_implements_sq_repeat = partial( + type_implements_sq_slot, slot=PySequenceSlots.SQ_REPEAT +) + +type_implements_sq_inplace_repeat = partial( + type_implements_sq_slot, slot=PySequenceSlots.SQ_INPLACE_REPEAT +) + +# PyMappingSlots +type_implements_mp_length = partial( + type_implements_mp_slot, slot=PyMappingSlots.MP_LENGTH +) +type_implements_mp_subscript = partial( + type_implements_mp_slot, slot=PyMappingSlots.MP_SUBSCRIPT +) +type_implements_mp_ass_subscript = partial( + type_implements_mp_slot, slot=PyMappingSlots.MP_ASS_SUBSCRIPT +) +type_implements_mp_length = partial( + type_implements_mp_slot, slot=PyMappingSlots.MP_LENGTH +) + + +def type_implements_nb_slot(obj_type: type, slot: int) -> bool: + """Check whether obj_type implements the nb slot.""" + _, _, number_slots, _ = _get_cached_slots(obj_type) + return has_slot(number_slots, slot) + + +type_implements_nb_add = partial(type_implements_nb_slot, slot=PyNumberSlots.NB_ADD) +type_implements_nb_subtract = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_SUBTRACT +) +type_implements_nb_multiply = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_MULTIPLY +) +type_implements_nb_remainder = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_REMAINDER +) +type_implements_nb_power = partial(type_implements_nb_slot, slot=PyNumberSlots.NB_POWER) +type_implements_nb_negative = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_NEGATIVE +) +type_implements_nb_positive = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_POSITIVE +) +type_implements_nb_absolute = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_ABSOLUTE +) +type_implements_nb_bool = partial(type_implements_nb_slot, slot=PyNumberSlots.NB_BOOL) +type_implements_nb_invert = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INVERT +) +type_implements_nb_lshift = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_LSHIFT +) +type_implements_nb_rshift = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_RSHIFT +) +type_implements_nb_and = partial(type_implements_nb_slot, slot=PyNumberSlots.NB_AND) +type_implements_nb_xor = partial(type_implements_nb_slot, slot=PyNumberSlots.NB_XOR) +type_implements_nb_or = partial(type_implements_nb_slot, slot=PyNumberSlots.NB_OR) +type_implements_nb_int = partial(type_implements_nb_slot, slot=PyNumberSlots.NB_INT) +type_implements_nb_float = partial(type_implements_nb_slot, slot=PyNumberSlots.NB_FLOAT) +type_implements_nb_inplace_add = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_ADD +) +type_implements_nb_inplace_subtract = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_SUBTRACT +) +type_implements_nb_inplace_multiply = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_MULTIPLY +) +type_implements_nb_inplace_remainder = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_REMAINDER +) +type_implements_nb_inplace_power = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_POWER +) +type_implements_nb_inplace_lshift = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_LSHIFT +) +type_implements_nb_inplace_rshift = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_RSHIFT +) +type_implements_nb_inplace_and = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_AND +) +type_implements_nb_inplace_xor = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_XOR +) +type_implements_nb_inplace_or = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_OR +) +type_implements_nb_floor_divide = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_FLOOR_DIVIDE +) +type_implements_nb_true_divide = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_TRUE_DIVIDE +) +type_implements_nb_inplace_floor_divide = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_FLOOR_DIVIDE +) +type_implements_nb_inplace_true_divide = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_TRUE_DIVIDE +) +type_implements_nb_index = partial(type_implements_nb_slot, slot=PyNumberSlots.NB_INDEX) +type_implements_nb_matrix_multiply = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_MATRIX_MULTIPLY +) +type_implements_nb_inplace_matrix_multiply = partial( + type_implements_nb_slot, slot=PyNumberSlots.NB_INPLACE_MATRIX_MULTIPLY +) + + +def type_implements_tp_iter(obj_type: type) -> bool: + _, _, _, type_slot = _get_cached_slots(obj_type) + return has_slot(type_slot, PyTypeSlots.TP_ITER) + + +def type_implements_tp_iternext(obj_type: type) -> bool: + _, _, _, type_slot = _get_cached_slots(obj_type) + return has_slot(type_slot, PyTypeSlots.TP_ITERNEXT) + + +def type_implements_tp_repr(obj_type: type) -> bool: + """Check whether obj_type implements the tp_repr slot.""" + _, _, _, type_slot = _get_cached_slots(obj_type) + return has_slot(type_slot, PyTypeSlots.TP_REPR) + + +def type_implements_tp_str(obj_type: type) -> bool: + """Check whether obj_type implements the tp_str slot.""" + _, _, _, type_slot = _get_cached_slots(obj_type) + return has_slot(type_slot, PyTypeSlots.TP_STR) + + +def type_implements_tp_call(obj_type: type) -> bool: + """Check whether obj_type implements the tp_call slot.""" + _, _, _, type_slot = _get_cached_slots(obj_type) + return has_slot(type_slot, PyTypeSlots.TP_CALL) + + +def pyiter_check(obj_type: type) -> bool: + # ref: https://github.com/python/cpython/blob/3.13/Objects/abstract.c#L2891-L2897 + # CPython checks if tp_iternext != _PyObject_NextNotImplemented + # Dynamo only sets the bit if __next__ is actually defined + return type_implements_tp_iternext(obj_type) + + +def pysequence_check(obj_type: type) -> bool: + """Implements PySequence_Check semantics for VariableTracker objects.""" + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1714-L1721 + if issubclass(obj_type, dict): + return False + return type_implements_sq_item(obj_type) + + +def pyindex_check(obj_type: type) -> bool: + """Implements _PyIndex_Check semantics for VariableTracker objects.""" + # ref: https://github.com/python/cpython/blob/3.13/Include/internal/pycore_abstract.h#L11-L17 + return type_implements_nb_index(obj_type) + + +def pycallable_check(obj_type: type) -> bool: + """Implements PyCallable_Check: type(x)->tp_call != NULL. + + obj_type is the object's Python type (Py_TYPE(x)); a non-NULL tp_call + slot on it means instances are callable. + + ref: https://github.com/python/cpython/blob/v3.13.0/Objects/call.c#L52-L57 + """ + return type_implements_tp_call(obj_type) + + +def pyiter_send( + tx: "InstructionTranslatorBase", iter_: VariableTracker, arg: VariableTracker +) -> VariableTracker: + """Implements PyIter_Send semantics for VariableTracker objects. + + ref: https://github.com/python/cpython/blob/51b511d7299f91a458e40d1ea997bd7e6cd3deef/Objects/abstract.c#L2930-L2953 + """ + + tp_iternext = iter_.tp_iternext + if arg.is_constant_none() and tp_iternext is not None: + return iter_.tp_iternext_impl(tx) + else: + return iter_.call_method(tx, "send", [arg], {}) + + +def pymapping_size( + tx: "InstructionTranslatorBase", obj: "VariableTracker" +) -> "VariableTracker": + # ref: https://github.com/python/cpython/blob/v3.13.3/Objects/abstract.c#L2308-L2330 + if obj.tp_as_mapping.mp_length: + return obj.mp_length_impl(tx) + + if obj.tp_as_sequence.sq_length is not None: + raise_type_error(tx, f"{obj.python_type_name()} is not a mapping") + + raise_type_error(tx, f"object of type {obj.python_type_name()} has no len()") + + +def generic_size( + tx: "InstructionTranslatorBase", obj: "VariableTracker" +) -> "VariableTracker": + # ref: https://github.com/python/cpython/blob/v3.13.3/Objects/abstract.c#L53-L69 + """ + Implements PyObject_Size/PyObject_Length semantics for VariableTracker objects. + Dispatches to sq_length (sequences) or mp_length (mappings) depending on the VT type. + """ + + if obj.tp_as_sequence.sq_length: + return obj.sq_length_impl(tx) + return pymapping_size(tx, obj) + + +def generic_is_true( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> VariableTracker: + """Mirrors PyObject_IsTrue. + + https://github.com/python/cpython/blob/c09ccd9c429/Objects/object.c#L2135-L2158 + + Resolution order: constants → nb_bool → mp_length/sq_length → truthy. + """ + from .constant import ConstantVariable + + if obj.is_python_constant(): + try: + return ConstantVariable.create(bool(obj.as_python_constant())) + except Exception as e: + raise_observed_exception(type(e), tx, args=[str(e)]) + + if obj.tp_as_number.nb_bool: + result = obj.nb_bool_impl(tx) + if result is not None: + return result + + try: + length = generic_size(tx, obj) + from .tensor import SymNodeVariable + + if isinstance(length, SymNodeVariable): + return SymNodeVariable.create(tx, length.as_proxy() > 0) + length_val = length.as_python_constant() + if length_val < 0: + raise_observed_exception( + ValueError, tx, args=["__len__() should return >= 0"] + ) + return ConstantVariable.create(length_val > 0) + except ObservedTypeError: + handle_observed_exception(tx) + + return ConstantVariable.create(True) + + +_repr_running: set[int] = set() + + +def generic_repr( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> VariableTracker: + """Mirrors PyObject_Repr with Py_ReprEnter/Py_ReprLeave cycle detection. + + https://github.com/python/cpython/blob/v3.13.3/Objects/object.c#L745-L778 + + Resolution order: tp_repr -> TypeError if the result is not str. + """ + obj_type = maybe_get_python_type(obj) + + tp_repr = obj.tp_repr + if tp_repr is not None: + obj_id = id(obj) + if obj_id in _repr_running: + sentinel = {list: "[...]", dict: "{...}", collections.deque: "[...]"} + return ConstantVariable.create(sentinel.get(obj_type, "...")) + _repr_running.add(obj_id) + try: + result = obj.tp_repr_impl(tx) + finally: + _repr_running.discard(obj_id) + result_type = maybe_get_python_type(result) + if not issubclass(result_type, str): + if sys.version_info >= (3, 15): + err_str = f"{obj.python_qualified_name()}.__repr__() must return a str, not int" + else: + err_str = f"__repr__ returned non-string (type {result_type.__name__})" + raise_type_error(tx, err_str) + return result + + raise_type_error(tx, f"object of type '{obj.python_type_name()}' has no repr") + + +def generic_str( + tx: "InstructionTranslatorBase", obj: "VariableTracker" +) -> "VariableTracker": + """Mirrors PyObject_Str semantics in Dynamo. + + https://github.com/python/cpython/blob/v3.13.3/Objects/object.c#L781-L829 + + Resolution order: str identity check -> tp_str (tp_str_impl) -> tp_repr fallback. + """ + from ..exc import TorchDynamoException + + if maybe_get_python_type(obj) is str: + return obj + + try: + if obj.tp_str and type(obj).tp_str_impl is not VariableTracker.tp_str_impl: + result = obj.tp_str_impl(tx) + else: + result = generic_repr(tx, obj) + except TorchDynamoException: + raise + except Exception as exc: + raise_observed_exception(type(exc), tx, args=list(exc.args)) + + result_type = maybe_get_python_type(result) + if not issubclass(result_type, str): + if sys.version_info >= (3, 15): + err_str = f"{obj.python_qualified_name()}.__str__() must return a str, not {result.python_qualified_name()}" + else: + err_str = f"__str__ returned non-string (type {result_type.__name__})" + raise_type_error(tx, err_str) + return result + + +def generic_getitem( + tx: "InstructionTranslatorBase", + obj: VariableTracker, + key: VariableTracker, +) -> VariableTracker: + """CPython's PyObject_GetItem — dispatch to the type's mp_subscript/sq_item. + + PyObject_GetItem: https://github.com/python/cpython/blob/62a6e898e01/Objects/abstract.c#L155-L206 + + CPython checks three branches in order: + 1. tp_as_mapping->mp_subscript (L161-166) + 2. tp_as_sequence->sq_item (L168-181) — only if key passes _PyIndex_Check + 3. PyType_Check(o) (L183-203) — type[int] → GenericAlias/__class_getitem__ + + Branch 1 is the common path (list, tuple, dict, range all have mp_subscript). + Branch 2 fires for types with only sq_item (e.g. deque). + Branch 3 delegates to mp_subscript_impl for type objects (__class_getitem__). + """ + obj_type = maybe_get_python_type(obj) + # Branch 1: mp_subscript + if obj.tp_as_mapping.mp_subscript: + return obj.mp_subscript_impl(tx, key) + # Branch 2: sq_item (only if mp_subscript is absent) + # CPython: abstract.c L168-181 — _PyIndex_Check(key) → PyNumber_AsSsize_t + # → PySequence_GetItem (wraps negative, calls sq_item) + if obj.tp_as_sequence.sq_item is not None: + key_type = maybe_get_python_type(key) + if pyindex_check(key_type): + key = pynumber_as_ssize_t(tx, key, IndexError) + return pysequence_getitem(tx, obj, key) + raise_type_error( + tx, + f"{obj_type.__name__} indices must be integers, not {key_type.__name__}", + ) + # Branch 3: PyType_Check → __class_getitem__ (abstract.c L183-203) + # In 3.10+ type.__getitem__ sets mp_subscript so this is normally caught + # by Branch 1, but we check explicitly for safety. + if issubclass(obj_type, type): + return obj.mp_subscript_impl(tx, key) + # CPython: abstract.c L205 + raise_type_error(tx, f"'{obj_type.__name__}' object is not subscriptable") + + +def pysequence_getitem( + tx: "InstructionTranslatorBase", + obj: VariableTracker, + index: VariableTracker, +) -> VariableTracker: + """CPython's PySequence_GetItem — always sq_item, never mp_subscript. + + ref: https://github.com/python/cpython/blob/v3.13.3/Objects/abstract.c#L1874-L1902 + + Called by PyObject_GetItem branch 2, reversed() fallback, and the old + iteration protocol. Wraps negative indices via sq_length before + dispatching to sq_item. + """ + sq_item = obj.tp_as_sequence.sq_item + if sq_item is not None: + # Negative index wrapping (abstract.c L2175-2183) + if isinstance(index, ConstantVariable): + index_val = index.as_python_constant() + if isinstance(index_val, int) and index_val < 0: + if obj.tp_as_sequence.sq_length is not None: + length = obj.sq_length_impl(tx) + index = ConstantVariable.create( + index_val + length.as_python_constant() + ) + return obj.sq_item_impl(tx, index) + + if obj.tp_as_mapping.mp_subscript is not None: + raise_type_error(tx, f"'{obj.python_type_name()}' is not a sequence") + + raise_type_error(tx, f"'{obj.python_type_name()}' object does not support indexing") + + +def pysequence_setitem( + tx: "InstructionTranslatorBase", + s: VariableTracker, + i: VariableTracker, + o: VariableTracker, +) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/abstract.c#L1926-L1957 (PySequence_SetItem) + sq_ass_item = s.tp_as_sequence.sq_ass_item + if sq_ass_item is not None: + # Negative index wrapping (abstract.c L1944-1952) + if isinstance(i, ConstantVariable): + index_val = i.as_python_constant() + if isinstance(index_val, int) and index_val < 0: + if s.tp_as_sequence.sq_length is not None: + length = s.sq_length_impl(tx) + i = ConstantVariable.create(index_val + length.as_python_constant()) + return s.sq_ass_item_impl(tx, i, o) + + if s.tp_as_mapping.mp_ass_subscript is not None: + raise_type_error(tx, f"'{s.python_type_name()}' is not a sequence") + + raise_type_error( + tx, f"'{s.python_type_name()}' object does not support item assignment" + ) + + +def generic_setitem( + tx: "InstructionTranslatorBase", + o: VariableTracker, + key: VariableTracker, + value: VariableTracker, +) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/abstract.c#L222-L254 + mp_ass_subscript = o.tp_as_mapping.mp_ass_subscript + if mp_ass_subscript is not None: + return o.mp_ass_subscript_impl(tx, key, value) + + if o.tp_as_sequence.sq_ass_item is not None: + key_type = maybe_get_python_type(key) + if pyindex_check(key_type): + key_value = pynumber_as_ssize_t(tx, key, err=IndexError) + return pysequence_setitem(tx, o, key_value, value) + raise_type_error( + tx, f"sequence index must be integer, not '{key.python_type_name()}'" + ) + raise_type_error( + tx, f"'{o.python_type_name()}' object does not support item assignment" + ) + + +def pysequence_delitem( + tx: "InstructionTranslatorBase", + s: VariableTracker, + i: VariableTracker, +) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/abstract.c#L1959-L1990 + + sq_ass_item = s.tp_as_sequence.sq_ass_item + if sq_ass_item is not None: + if isinstance(i, ConstantVariable): + idx = i.as_python_constant() + if idx < 0: + if s.tp_as_sequence.sq_length is not None: + length = s.sq_length_impl(tx) + i = pynumber_add(tx, i, length) + return s.sq_ass_item_impl(tx, i, None) + + if s.tp_as_mapping.mp_ass_subscript is not None: + raise_type_error(tx, f"'{s.python_type_name()}' is not a sequence") + + raise_type_error( + tx, f"'{s.python_type_name()}' object does not support item deletion" + ) + + +def generic_delitem( + tx: "InstructionTranslatorBase", + o: VariableTracker, + key: VariableTracker, +) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/abstract.c#L256-L288 + + mp_ass_subscript = o.tp_as_mapping.mp_ass_subscript + if mp_ass_subscript is not None: + return o.mp_ass_subscript_impl(tx, key, None) + + key_type = maybe_get_python_type(key) + if pyindex_check(key_type): + key_value = key.nb_index_impl(tx) + return pysequence_delitem(tx, o, key_value) + elif o.tp_as_sequence.sq_ass_item is not None: + raise_type_error( + tx, f"sequence index must be integer, not {key.python_type_name()}" + ) + + raise_type_error(tx, f"'{o.python_type_name()}' does not support item deletion") + + +def pynumber_int( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> VariableTracker: + """Mirrors PyNumber_Long (int(x) dispatch). + + https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1520-L1632 + + Resolution: nb_int → nb_index → str/bytes/bytearray parsing → TypeError. + """ + from .constant import ConstantVariable + + # Fast path for int (sub)class instances — mirrors PyLong_Check at the + # top of PyNumber_Long (abstract.c:1531). Avoids infinite recursion for + # int subclasses like IntEnum whose __int__ calls int() again. + if obj.is_python_constant() and isinstance(obj.as_python_constant(), int): + return ConstantVariable.create(int(obj.as_python_constant())) + + if obj.tp_as_number.nb_int is not None: + res = obj.nb_int_impl(tx) + if res.python_type() is not int: + raise_type_error( + tx, + f"__int__ returned non-int (type {res.python_type_name()})", + ) + return res + + if obj.tp_as_number.nb_index is not None: + return obj.nb_index_impl(tx) + + # String/bytes/bytearray parsing fallback. + # https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1598-L1612 + if obj.is_python_constant() and isinstance( + obj.as_python_constant(), (str, bytes, bytearray) + ): + try: + return ConstantVariable.create(int(obj.as_python_constant())) + except ValueError as e: + raise_observed_exception(ValueError, tx, args=[str(e)]) + + raise_type_error( + tx, + f"int() argument must be a string, a bytes-like object " + f"or a real number, not '{obj.python_type_name()}'", + ) + + +def pylong_from_base( + tx: "InstructionTranslatorBase", x: VariableTracker, obase: VariableTracker +) -> VariableTracker | None: + """Mirrors the explicit-base path of long_new_impl (int(x, base)). + + https://github.com/python/cpython/blob/v3.13.0/Objects/longobject.c#L5879-L5922 + + The base is resolved via PyNumber_AsSsize_t, which consults __index__, so + any __index__-able object is accepted. Returns None (graph break) when the + inputs cannot be resolved to Python constants. + """ + # base = PyNumber_AsSsize_t(obase, NULL) -> nb_index. + if obase.is_python_constant() and issubclass(obase.python_type(), int): + base_vt = obase + elif obase.tp_as_number.nb_index is not None: + base_vt = obase.nb_index_impl(tx) + else: + raise_type_error( + tx, + f"'{obase.python_type_name()}' object cannot be interpreted as an integer", + ) + if not (base_vt.is_python_constant() and issubclass(base_vt.python_type(), int)): + return None + base = base_vt.as_python_constant() + if (base != 0 and base < 2) or base > 36: + raise_observed_exception( + ValueError, tx, args=["int() base must be >= 2 and <= 36, or 0"] + ) + if not x.is_python_constant(): + return None + xval = x.as_python_constant() + if not isinstance(xval, (str, bytes, bytearray)): + raise_type_error(tx, "int() can't convert non-string with explicit base") + try: + return ConstantVariable.create(int(xval, base)) + except ValueError as e: + raise_observed_exception(ValueError, tx, args=list(e.args)) + + +def pynumber_float( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> VariableTracker: + """Mirrors PyNumber_Float (float(x) dispatch). + + https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1635-L1692 + + Resolution: nb_float → nb_index → str parsing → TypeError. + """ + from .constant import ConstantVariable + + # Fast path: if the value is already a float constant, return it directly. + # Mirrors PyFloat_CheckExact fast path at the top of PyNumber_Float + # (abstract.c:1641-1643). + if obj.is_python_constant() and isinstance(obj.as_python_constant(), float): + return ConstantVariable.create(float(obj.as_python_constant())) + + if obj.tp_as_number.nb_float is not None: + res = obj.nb_float_impl(tx) + if res.python_type() is not float: + raise_type_error( + tx, + f"__float__ returned non-float (type {res.python_type_name()})", + ) + return res + + # https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1674-L1685 + if obj.tp_as_number.nb_index is not None: + return obj.nb_index_impl(tx) + + # PyFloat_FromString fallback — handles str and bytes. + # https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1691 + if issubclass(obj.python_type(), (str, bytes)): + try: + return ConstantVariable.create(float(obj.as_python_constant())) + except ValueError as e: + raise_observed_exception(ValueError, tx, args=[str(e)]) + + raise_type_error( + tx, + f"float() argument must be a string or a real number, " + f"not '{obj.python_type_name()}'", + ) + + +def getindex( + tx: "InstructionTranslatorBase", + obj: VariableTracker, + arg: VariableTracker, +) -> VariableTracker: + """Mirrors typeobject.c::getindex: calls PyNumber_AsSsize_t then tp_as_sequence.sq_length""" + obj_type = maybe_get_python_type(obj) + + i = pynumber_as_ssize_t(tx, arg, err=OverflowError) + if i.as_python_constant() < 0: + if type_implements_sq_length(obj_type): + length = obj.sq_length_impl(tx) + i = pynumber_add(tx, i, length) + return i + + +def pylong_as_ssize_t(tx: "InstructionTranslatorBase", obj: VariableTracker) -> int: + """Mirrors PyLong_AsSsize_t: requires an int (or subclass). + values outside the Py_ssize_t range raise OverflowError. + + https://github.com/python/cpython/blob/60403a5409ff2c3f3b07dd2ca91a7a3e096839c7/Objects/longobject.c#L576 + """ + # Starting on Python 3.16, this will explicitly require an integer instance + # https://docs.python.org/3/deprecations/index.html#pending-removal-in-python-3-16 + if not issubclass(obj.python_type(), int): + raise_type_error(tx, "an integer is required") + val = obj.as_python_constant() + if not -sys.maxsize - 1 <= val <= sys.maxsize: + raise_observed_exception( + OverflowError, + tx, + args=["Python int too large to convert to C ssize_t"], + ) + return val + + +def pynumber_as_ssize_t( + tx: "InstructionTranslatorBase", + item: VariableTracker, + err: type[Exception] | None = IndexError, +) -> VariableTracker: + """Mirrors PyNumber_AsSsize_t: _PyNumber_Index(item) then PyLong_AsSsize_t. + + On overflow (value outside the Py_ssize_t range) CPython remaps the + OverflowError to `err`, or clips to the Py_ssize_t bounds when err is None. + + https://github.com/python/cpython/blob/60403a5409ff2c3f3b07dd2ca91a7a3e096839c7/Objects/abstract.c#L1469 + """ + from .tensor import SymNodeVariable + + value = pynumber_index(tx, item) + + # PyLong_AsSsize_t: a symbolic int must be specialized to a concrete + # ssize_t (with guard) to be usable as a C index. + if isinstance(value, SymNodeVariable): + val = value.evaluate_expr(tx.output) + else: + val = value.as_python_constant() + + if not isinstance(val, int): + raise AssertionError("pynumber_index did not return an int-like value") + + if -sys.maxsize - 1 <= val <= sys.maxsize: + return ConstantVariable.create(int(val)) + if err is None: + r = sys.maxsize if val > 0 else -sys.maxsize - 1 + return ConstantVariable.create(r) + raise_observed_exception( + err, + tx, + args=[f"cannot fit '{item.python_type_name()}' into an index-sized integer"], + ) + + +def pynumber_index( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> "VariableTracker": + """Mirrors PyNumber_Index (index(x) dispatch).""" + + if obj.tp_as_number.nb_index is None: + raise_type_error( + tx, + f"'{obj.python_type_name()}' object cannot be interpreted as an integer", + ) + + result = obj.nb_index_impl(tx) + + if not issubclass(result.python_type(), int): + raise_type_error( + tx, + f"__index__ returned non-int (type {result.python_type_name()})", + ) + + return result + + +def pynumber_tobase( + tx: "InstructionTranslatorBase", obj: VariableTracker, base: int +) -> VariableTracker | None: + """Mirrors PyNumber_ToBase (bin/oct/hex dispatch). + + https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1653-L1666 + + Resolves __index__ (raising TypeError if absent), then formats the + resulting int in the requested base. Returns None (graph break) when the + index result is not a Python constant. + """ + index = pynumber_index(tx, obj) + format_fn = {2: bin, 8: oct, 16: hex}[base] + return ConstantVariable.create(format_fn(index.as_python_constant())) + + +def pyiter_next( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> "VariableTracker": + """ + Implements PyIter_Next / tp_iternext semantics for VariableTracker objects. + + Calls obj.tp_iternext_impl(tx) if the object is an iterator, otherwise raises + TypeError. StopIteration propagation is left to the caller (mirrors + CPython's iternext contract where NULL return signals exhaustion). + """ + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L2865 + + tp_iternext = obj.tp_iternext + if tp_iternext is None: + raise_type_error(tx, f"expected an iterator, got '{obj.python_type_name()}'") + + return obj.tp_iternext_impl(tx) + + +def pynumber_negative( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> VariableTracker: + """Mirrors PyNumber_Negative. + + https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1375-L1392 + + Algorithm: + 1. If type has nb_negative slot, call obj.nb_negative_impl(tx) + 2. Otherwise, raise TypeError + """ + + nb_negative = obj.tp_as_number.nb_negative + if nb_negative is not None: + return obj.nb_negative_impl(tx) + + raise_type_error( + tx, + f"bad operand type for unary -: '{obj.python_type_name()}'", + ) + + +def pynumber_positive( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> VariableTracker: + """Mirrors PyNumber_Positive. + + https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1375-L1393 + + Algorithm: + 1. If type has nb_positive slot, call obj.nb_positive_impl(tx) + 2. Otherwise, raise TypeError + """ + + nb_positive = obj.tp_as_number.nb_positive + if nb_positive is not None: + return obj.nb_positive_impl(tx) + + raise_type_error( + tx, + f"bad operand type for unary +: '{obj.python_type_name()}'", + ) + + +def pynumber_absolute( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> VariableTracker: + """Mirrors PyNumber_Absolute. + + https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1375-L1395 + + Algorithm: + 1. If type has nb_absolute slot, call obj.nb_absolute_impl(tx) + 2. Otherwise, raise TypeError + """ + + nb_absolute = obj.tp_as_number.nb_absolute + if nb_absolute is not None: + return obj.nb_absolute_impl(tx) + + raise_type_error( + tx, + f"bad operand type for abs(): '{obj.python_type_name()}'", + ) + + +def vt_is_iterable(obj: VariableTracker) -> bool: + """Check if the object supports iteration (i.e. has tp_iter or sequence protocol).""" + T = maybe_get_python_type(obj) + return obj.tp_iter is not None or pysequence_check(T) + + +def pynumber_invert( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> VariableTracker: + """Mirrors PyNumber_Invert. + + https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1375-L1394 + + Algorithm: + 1. If type has nb_invert slot, call obj.nb_invert_impl(tx) + 2. Otherwise, raise TypeError + """ + + nb_invert = obj.tp_as_number.nb_invert + if nb_invert is not None: + return obj.nb_invert_impl(tx) + + raise_type_error( + tx, + f"bad operand type for unary ~: '{obj.python_type_name()}'", + ) + + +def generic_getiter( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> "VariableTracker": + """ + Implements PyObject_GetIter semantics for VariableTracker objects. + Routes to obj.tp_iter_impl(tx), the tp_iter slot on the object's type. + """ + + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L2847-L2870 + # The algorithm for PyObject_GetIter works as follows: Steps: + # 1. If the object has tp_iter slot, call it and return the result. The + # return object must be an iterator (it must have a tp_iternext slot) + # 2. If the object implements the sequence protocol - implements __getitem__ + # then create a sequence iterator for the object and return it + # 3. Otherwise, raise a TypeError + + T = maybe_get_python_type(obj) + tp_iter = obj.tp_iter + if tp_iter is not None: + res = obj.tp_iter_impl(tx) + res_T = maybe_get_python_type(res) + if not pyiter_check(res_T): + if sys.version_info >= (3, 15): + err_str = f"{obj.python_qualified_name()}.__iter__() must return an iterator, not {res.python_qualified_name()}" + else: + err_str = ( + f"iter() returned non-iterator of type '{res.python_type_name()}'" + ) + raise_type_error(tx, err_str) + return res + elif pysequence_check(T): + from .functions import UserFunctionVariable + + return UserFunctionVariable(polyfills.builtins.sequence_iterator).call_function( + tx, [obj], {} + ) + else: + raise_type_error(tx, f"'{obj.python_type_name()}' object is not iterable") + + +# --------------------------------------------------------------------------- +# Binary-op dispatch (CPython's abstract.c: binary_op1 / binary_op) +# https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L927 (binary_op1) +# --------------------------------------------------------------------------- + +NB_SLOT_MAPPING = { + "nb_lshift": PyNumberSlots.NB_LSHIFT, + "nb_inplace_lshift": PyNumberSlots.NB_INPLACE_LSHIFT, + "nb_inplace_rshift": PyNumberSlots.NB_INPLACE_RSHIFT, + "nb_rshift": PyNumberSlots.NB_RSHIFT, + "nb_or": PyNumberSlots.NB_OR, + "nb_inplace_or": PyNumberSlots.NB_INPLACE_OR, + "nb_subtract": PyNumberSlots.NB_SUBTRACT, + "nb_inplace_subtract": PyNumberSlots.NB_INPLACE_SUBTRACT, + "nb_add": PyNumberSlots.NB_ADD, + "nb_inplace_add": PyNumberSlots.NB_INPLACE_ADD, + "nb_multiply": PyNumberSlots.NB_MULTIPLY, + "nb_inplace_multiply": PyNumberSlots.NB_INPLACE_MULTIPLY, + "nb_matrix_multiply": PyNumberSlots.NB_MATRIX_MULTIPLY, + "nb_inplace_matrix_multiply": PyNumberSlots.NB_INPLACE_MATRIX_MULTIPLY, + "nb_and": PyNumberSlots.NB_AND, + "nb_inplace_and": PyNumberSlots.NB_INPLACE_AND, + "nb_xor": PyNumberSlots.NB_XOR, + "nb_inplace_xor": PyNumberSlots.NB_INPLACE_XOR, + "nb_floor_divide": PyNumberSlots.NB_FLOOR_DIVIDE, + "nb_inplace_floor_divide": PyNumberSlots.NB_INPLACE_FLOOR_DIVIDE, + "nb_true_divide": PyNumberSlots.NB_TRUE_DIVIDE, + "nb_inplace_true_divide": PyNumberSlots.NB_INPLACE_TRUE_DIVIDE, + "nb_remainder": PyNumberSlots.NB_REMAINDER, + "nb_inplace_remainder": PyNumberSlots.NB_INPLACE_REMAINDER, + "nb_divmod": PyNumberSlots.NB_DIVMOD, + "nb_power": PyNumberSlots.NB_POWER, + "nb_inplace_power": PyNumberSlots.NB_INPLACE_POWER, +} + + +def is_nb_not_implemented(result: VariableTracker) -> bool: + return result.is_constant_match(NotImplemented) + + +def is_python_subtype(w: VariableTracker, v: VariableTracker) -> bool: + """Check if w's underlying Python type is a proper subtype of v's.""" + try: + return issubclass(w.python_type(), v.python_type()) + except NotImplementedError: + return False + + +# Calling scheme used for binary operations: +# +# Order operations are tried until either a valid result or error: +# w.op(v,w)[*], v.op(v,w), w.op(v,w) +# +# [*] only when Py_TYPE(v) != Py_TYPE(w) && Py_TYPE(w) is a subclass of +# Py_TYPE(v) + + +def binary_op1( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, + op_slot: str, +) -> VariableTracker: + """CPython's binary_op1: try v's slot, then w's slot with subclass priority. + + Each VT that participates provides a ``_impl(self, tx, other, + reverse)`` method. ``reverse=False`` means "self is left operand" (forward, + e.g. ``__or__``), ``reverse=True`` means "self is right operand" (reverse, + e.g. ``__ror__``). For built-in types the flag is ignored because their + slots check both operands symmetrically. + + CPython splits the check into two steps: ``Py_TYPE(v)->tp_as_number != + NULL`` (does the type have a number-protocol struct), then read the + slot pointer (which may itself be NULL). We collapse both into a + single :func:`type_implements_nb_slot` query — its bit is set only + when the specific slot is non-NULL, which already implies + ``tp_as_number`` is non-NULL. Treating a missing slot as "no impl" + is what keeps the base ``VariableTracker.nb_*_impl`` graph-break + out of the path for types that genuinely lack the slot in C. + + https://github.com/python/cpython/blob/3.13/Objects/abstract.c#L926-L977 + """ + impl_attr = f"{op_slot}_impl" + nb_slot_bit = NB_SLOT_MAPPING[op_slot] + + v_type = maybe_get_python_type(v) + w_type = maybe_get_python_type(w) + + v_slot = ( + getattr(type(v), impl_attr, None) + if type_implements_nb_slot(v_type, nb_slot_bit) + else None + ) + w_slot = ( + getattr(type(w), impl_attr, None) + if type_implements_nb_slot(w_type, nb_slot_bit) + else None + ) + + # CPython skips slotw if Py_TYPE(w) == Py_TYPE(v) (one C type, one slot + # function). In Dynamo two VT subclasses can share a Python type — e.g. + # ConstantVariable(3) and SymNodeVariable both report ``int`` — yet have + # different ``nb_*_impl`` methods. Comparing the slots themselves + # captures both "literally the same function" (CPython's check) and + # "different VT subclasses sharing a python_type", so we drop the type + # equality check. + if v_slot is w_slot: + w_slot = None + + if v_slot is not None: + # Subclass priority: if w's Python type is a proper subtype of v's + # Python type and overrides the slot, try w first (CPython abstract.c:952-960). + if w_slot is not None and is_python_subtype(w, v): + # CPython ALWAYS calls the slot with (v, w), even for reverse slots. + # Since w_slot is a method call, we use reverse=True to indicate w + # is the right operand, matching CPython's semantics. + result = w_slot(w, tx, v, True) + if not is_nb_not_implemented(result): + return result + w_slot = None + result = v_slot(v, tx, w, False) + if not is_nb_not_implemented(result): + return result + if w_slot is not None: + result = w_slot(w, tx, v, True) + if not is_nb_not_implemented(result): + return result + return ConstantVariable.create(NotImplemented) + + +def binary_op( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, + op_slot: str, + op_symbol: str, +) -> VariableTracker: + """CPython's binary_op: binary_op1 + TypeError fallback. + https://github.com/python/cpython/blob/3.13/Objects/abstract.c#L997-L1020 + """ + + result = binary_op1(tx, v, w, op_slot) + if is_nb_not_implemented(result): + binop_type_error(tx, v, w, op_symbol) + return result + + +def ternary_op( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, + z: VariableTracker | None, + op_slot: str, + op_name: str, +) -> VariableTracker: + impl_attr = f"{op_slot}_impl" + nb_slot_bit = NB_SLOT_MAPPING[op_slot] + + v_type = maybe_get_python_type(v) + w_type = maybe_get_python_type(w) + + v_slot = ( + getattr(type(v), impl_attr, None) + if type_implements_nb_slot(v_type, nb_slot_bit) + else None + ) + + w_slot = ( + getattr(type(w), impl_attr, None) + if type_implements_nb_slot(w_type, nb_slot_bit) + else None + ) + + if v_slot is w_slot: + w_slot = None + + if v_slot: + if w_slot and is_python_subtype(w, v): + result = w_slot(w, tx, v, z, True) + if not is_nb_not_implemented(result): + return result + w_slot = None + result = v_slot(v, tx, w, z, False) + if not is_nb_not_implemented(result): + return result + if w_slot: + result = w_slot(w, tx, v, z, True) + if not is_nb_not_implemented(result): + return result + + if z: + z_type = maybe_get_python_type(z) + if type_implements_nb_slot(z_type, nb_slot_bit): + z_impl_attr = f"{op_slot}_z_impl" + z_slot = getattr(type(z), z_impl_attr, None) + if z_slot in (v_slot, w_slot): + z_slot = None + if z_slot: + result = z_slot(z, tx, v, w) + if not is_nb_not_implemented(result): + return result + + if z is None: + binop_type_error(tx, v, w, op_name) + else: + raise_type_error( + tx, + f"unsupported operand type(s) for {op_name}: " + f"'{v.python_type_name()}', '{w.python_type_name()}', '{z.python_type_name()}'", + ) + + +def ternary_iop( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, + z: VariableTracker | None, + iop_slot: str, + op_slot: str, + op_name: str, +) -> VariableTracker: + v_type = maybe_get_python_type(v) + if type_implements_nb_slot(v_type, NB_SLOT_MAPPING[iop_slot]): + impl_attr = f"{iop_slot}_impl" + slot = getattr(type(v), impl_attr) + result = slot(v, tx, w, z) + if not is_nb_not_implemented(result): + return result + + return ternary_op(tx, v, w, z, op_slot, op_name) + + +# Binary in-place operators +# +# The in-place operators are defined to fall back to the 'normal', non +# in-place operations, if the in-place methods are not in place. +# +# - If the left hand object has the appropriate struct members, and they are +# filled, call the appropriate function and return the result. No coercion +# is done on the arguments; the left-hand object is the one the operation +# is performed on, and it's up to the function to deal with the right-hand +# object. +# +# - Otherwise, in-place modification is not supported. Handle it exactly as a +# non in-place operation of the same kind. + + +def binary_iop1( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, + iop_slot: str, + op_slot: str, +) -> VariableTracker: + v_type = maybe_get_python_type(v) + + if type_implements_nb_slot(v_type, NB_SLOT_MAPPING[iop_slot]): + impl_attr = f"{iop_slot}_impl" + slot = getattr(type(v), impl_attr) + result = slot(v, tx, w) + if not is_nb_not_implemented(result): + return result + + return binary_op1(tx, v, w, op_slot) + + +def binary_iop( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, + iop_slot: str, + op_slot: str, + op_symbol: str, +) -> VariableTracker: + """CPython's binary_iop: try inplace slot, fallback to binary_op1. + + Combines binary_iop1 + TypeError fallback from binary_iop. + https://github.com/python/cpython/blob/3.13/Objects/abstract.c#L1229-L1270 (binary_iop1, binary_iop) + """ + result = binary_iop1(tx, v, w, iop_slot, op_slot) + if is_nb_not_implemented(result): + binop_type_error(tx, v, w, op_symbol) + return result + + +# add / inplace add needs special handling +def pynumber_add( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, +) -> VariableTracker: + """Implements addition via nb_add / nb_inplace_add with binary_op dispatch.""" + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1138-L1155 + result = binary_op1(tx, v, w, "nb_add") + if not is_nb_not_implemented(result): + return result + + sq_concat = v.tp_as_sequence.sq_concat + if sq_concat is not None: + return v.sq_concat_impl(tx, w) + binop_type_error(tx, v, w, "+") + + +def pynumber_inplace_add( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, +) -> VariableTracker: + """Implements in-place addition via nb_inplace_add with binary_iop dispatch.""" + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1307-L1328 + result = binary_iop1(tx, v, w, "nb_inplace_add", "nb_add") + if is_nb_not_implemented(result): + sq_inplace_concat = v.tp_as_sequence.sq_inplace_concat + sq_concat = v.tp_as_sequence.sq_concat + if sq_inplace_concat is not None: + return v.sq_inplace_concat_impl(tx, w) + elif sq_concat is not None: + return v.sq_concat_impl(tx, w) + else: + binop_type_error(tx, v, w, "+=") + return result + + +# --------------------------------------------------------------------------- +# Multiplication: PyNumber_Multiply / PyNumber_InPlaceMultiply +# +# Multiplication is special because numeric types implement nb_multiply but +# sequence types (list, tuple, str, bytes, bytearray) implement only sq_repeat. +# CPython's PyNumber_Multiply tries nb_multiply first (via binary_op1) and on +# NotImplemented falls back to sq_repeat on either operand. +# +# https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1156-L1193 +# --------------------------------------------------------------------------- + + +def pysequence_repeat( + tx: "InstructionTranslatorBase", + seq: VariableTracker, + n: VariableTracker, +) -> VariableTracker: + """Mirrors CPython's sequence_repeat helper. + + Validates that ``n`` is index-like, converts it to an int, and dispatches + to ``seq.sq_repeat_impl(tx, count)``. + + https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1156-L1174 + """ + n_type = maybe_get_python_type(n) + if not pyindex_check(n_type): + raise_type_error( + tx, + f"can't multiply sequence by non-int of type '{n.python_type_name()}'", + ) + count = n.nb_index_impl(tx) + validate_sequence_repeat_count(tx, count) + return seq.sq_repeat_impl(tx, count) + + +def pysequence_inplace_repeat( + tx: "InstructionTranslatorBase", + seq: VariableTracker, + n: VariableTracker, +) -> VariableTracker: + """pysequence_repeat using sq_inplace_repeat. + + The validation step is identical to ``pysequence_repeat``; only the + target slot differs. + """ + n_type = maybe_get_python_type(n) + if not pyindex_check(n_type): + raise_type_error( + tx, + f"can't multiply sequence by non-int of type '{n.python_type_name()}'", + ) + count = n.nb_index_impl(tx) + validate_sequence_repeat_count(tx, count) + return seq.sq_inplace_repeat_impl(tx, count) + + +def validate_sequence_repeat_count( + tx: "InstructionTranslatorBase", + count: VariableTracker, +) -> None: + n = count.as_python_constant() + if n < -sys.maxsize - 1 or n > sys.maxsize: + raise_observed_exception( + OverflowError, + tx, + args=["cannot fit 'int' into an index-sized integer"], + ) + + +def pynumber_multiply( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, +) -> VariableTracker: + """Mirrors CPython's PyNumber_Multiply. + + Try nb_multiply via binary_op1; on NotImplemented fall back to sq_repeat + on either operand. TypeError if no path works. + + https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1176-L1193 + """ + result = binary_op1(tx, v, w, "nb_multiply") + if not is_nb_not_implemented(result): + return result + + if v.tp_as_sequence.sq_repeat is not None: + return pysequence_repeat(tx, v, w) + if w.tp_as_sequence.sq_repeat is not None: + return pysequence_repeat(tx, w, v) + + raise_type_error( + tx, + f"unsupported operand type(s) for *: " + f"'{v.python_type_name()}' and '{w.python_type_name()}'", + ) + + +def pynumber_inplace_multiply( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, +) -> VariableTracker: + """Mirrors CPython's PyNumber_InPlaceMultiply. + + Try nb_inplace_multiply / nb_multiply via binary_iop1; on NotImplemented + fall back to sq_inplace_repeat (preferred), then sq_repeat. + + https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1330-L1357 + """ + result = binary_iop1(tx, v, w, "nb_inplace_multiply", "nb_multiply") + if not is_nb_not_implemented(result): + return result + + if v.tp_as_sequence.sq_inplace_repeat is not None: + return pysequence_inplace_repeat(tx, v, w) + if v.tp_as_sequence.sq_repeat is not None: + return pysequence_repeat(tx, v, w) + # Cannot mutate w in-place — abstract.c L1348-1352 explicitly avoids + # sq_inplace_repeat on the right-hand operand. + if w.tp_as_sequence.sq_repeat is not None: + return pysequence_repeat(tx, w, v) + + raise_type_error( + tx, + f"unsupported operand type(s) for *=: " + f"'{v.python_type_name()}' and '{w.python_type_name()}'", + ) + + +def pynumber_matrix_multiply( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, +) -> VariableTracker: + """Mirrors CPython's PyNumber_MatrixMultiply.""" + return binary_op(tx, v, w, "nb_matrix_multiply", "@") + + +def pynumber_inplace_matrix_multiply( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, +) -> VariableTracker: + """Mirrors CPython's PyNumber_InPlaceMatrixMultiply.""" + return binary_iop( + tx, + v, + w, + "nb_inplace_matrix_multiply", + "nb_matrix_multiply", + "@=", + ) + + +# --------------------------------------------------------------------------- +# Type-object slot wrappers for ``__mul__`` / ``__rmul__`` / ``__imul__`` +# +# These mirror the *type object*'s installation of ``__mul__`` etc. as a +# method, not the operator dispatch. In CPython the user-visible +# ``int.__mul__`` and ``list.__mul__`` are different functions, each +# generated at type-construction time from ``Objects/typeobject.c``'s +# ``slotdefs[]`` table: +# +# slotdefs[]: +# BINSLOT(__mul__, nb_multiply, slot_nb_multiply, "*") [L10323] +# SQSLOT (__mul__, sq_repeat, NULL, wrap_indexargfunc) [L10419] +# RBINSLOT(__rmul__, nb_multiply, slot_nb_multiply, "*") [L10325] +# SQSLOT (__rmul__, sq_repeat, NULL, wrap_indexargfunc) [L10421] +# IBSLOT (__imul__, nb_inplace_multiply, ...) [L10364] +# SQSLOT (__imul__, sq_inplace_repeat, NULL, ...) [L10434] +# +# https://github.com/python/cpython/blob/v3.13.13/Objects/typeobject.c#L10244 (slotdefs[]) +# https://github.com/python/cpython/blob/v3.13.13/Objects/typeobject.c#L10412-L10416 (rationale comment) +# +# ``add_operators`` walks ``slotdefs[]`` and inserts a method into the +# type's ``__dict__`` for whichever slot the type fills. As the comment +# at L10412 notes, types fill at most one of ``nb_multiply`` / +# ``sq_repeat`` per op; nb_* takes priority because its slotdef appears +# first. ``slot_wrapper_mul``/``slot_wrapper_imul`` reproduce that +# selection so that ``call_method`` routing for direct dunder calls +# (``[1, 2].__mul__(3)``) reaches the correct slot. +# +# Distinct from ``pynumber_multiply`` / ``pynumber_inplace_multiply``, which +# mirror the operator-level algorithm in ``Objects/abstract.c`` +# (``PyNumber_Multiply``) — cross-operand subclass priority and the +# ``sq_repeat`` fallback when ``nb_multiply`` returns ``NotImplemented``. +# --------------------------------------------------------------------------- + + +def slot_wrapper_mul( + tx: "InstructionTranslatorBase", + self: VariableTracker, + other: VariableTracker, + reverse: bool = False, +) -> VariableTracker: + """``self.__mul__(other)`` / ``self.__rmul__(other)`` slot wrapper.""" + nb_multiply = self.tp_as_number.nb_multiply + if nb_multiply is not None: + return self.nb_multiply_impl(tx, other, reverse=reverse) + if self.tp_as_sequence.sq_repeat is not None: + # SQSLOT for __mul__ and __rmul__ both use ``wrap_indexargfunc`` — + # the wrapper ignores the reverse flag because sq_repeat takes + # ``(seq, count)`` regardless of which side ``self`` is on. + return pysequence_repeat(tx, self, other) + raise_type_error( + tx, + f"unsupported operand type(s) for *: " + f"'{self.python_type_name()}' and '{other.python_type_name()}'", + ) + + +def slot_wrapper_imul( + tx: "InstructionTranslatorBase", + self: VariableTracker, + other: VariableTracker, +) -> VariableTracker: + """``self.__imul__(other)`` slot wrapper. + + When neither ``nb_inplace_multiply`` nor ``sq_inplace_repeat`` is + installed, the slotdef machinery doesn't generate ``__imul__`` at all + — but the operator-level fallback in ``slot_nb_inplace_multiply`` + (typeobject.c) does try the non-inplace slot. We mirror that here so + method lookups don't graph-break on (e.g.) tuple, even though tuple + has no ``__imul__`` attribute in standard CPython. + """ + nb_inplace_multiply = self.tp_as_number.nb_inplace_multiply + if nb_inplace_multiply is not None: + return self.nb_inplace_multiply_impl(tx, other) + if self.tp_as_sequence.sq_inplace_repeat is not None: + return pysequence_inplace_repeat(tx, self, other) + return slot_wrapper_mul(tx, self, other) + + +# --------------------------------------------------------------------------- +# Type-object slot wrappers for ``__add__`` / ``__radd__`` / ``__iadd__`` + +# BINSLOT (__add__, nb_add, slot_nb_add, "+") [typeobject.c L10915] +# RBINSLOT(__radd__, nb_add, slot_nb_add, "+") [L10917] +# SQSLOT (__add__, sq_concat, NULL, wrap_binaryfunc) [L11017] +# IBSLOT (__iadd__, nb_inplace_add, ...) [L10960] +# SQSLOT (__iadd__, sq_inplace_concat, NULL, ...) [L11031] +# +# Distinct from ``pynumber_add`` / ``pynumber_inplace_add``, which mirror the +# operator-level ``PyNumber_Add`` (cross-operand priority, sq_concat fallback). +# --------------------------------------------------------------------------- + + +def slot_wrapper_add( + tx: "InstructionTranslatorBase", + self: VariableTracker, + other: VariableTracker, + reverse: bool = False, +) -> VariableTracker: + """``self.__add__(other)`` / ``self.__radd__(other)`` slot wrapper.""" + nb_add = self.tp_as_number.nb_add + if nb_add is not None: + return self.nb_add_impl(tx, other, reverse=reverse) + # No SQSLOT(__radd__): sq_concat backs only the forward __add__. + sq_concat = self.tp_as_sequence.sq_concat + if not reverse and sq_concat is not None: + return self.sq_concat_impl(tx, other) + raise_type_error( + tx, + f"unsupported operand type(s) for +: " + f"'{self.python_type_name()}' and '{other.python_type_name()}'", + ) + + +def slot_wrapper_iadd( + tx: "InstructionTranslatorBase", + self: VariableTracker, + other: VariableTracker, +) -> VariableTracker: + """``self.__iadd__(other)`` slot wrapper. + + Mirrors ``slot_wrapper_imul``: when neither ``nb_inplace_add`` nor + ``sq_inplace_concat`` is installed, fall back to the non-inplace slot. + """ + nb_inplace_add = self.tp_as_number.nb_inplace_add + if nb_inplace_add is not None: + return self.nb_inplace_add_impl(tx, other) + sq_inplace_concat = self.tp_as_sequence.sq_inplace_concat + if sq_inplace_concat is not None: + return self.sq_inplace_concat_impl(tx, other) + return slot_wrapper_add(tx, self, other) + + +# --------------------------------------------------------------------------- +# tp_richcompare -- comparison dispatch +# +# CPython comparison architecture (Objects/object.c, Objects/typeobject.c): +# +# a == b (COMPARE_OP bytecode) +# -> PyObject_RichCompare(a, b, Py_EQ) +# -> do_richcompare(a, b, Py_EQ) # the 4-step algorithm +# -> type(a)->tp_richcompare(a, b, Py_EQ) # per-type slot +# +# a.__eq__(b) (attribute access) +# -> type(a)->tp_getattro(a, "__eq__") # descriptor protocol +# -> returns wrapper bound to tp_richcompare +# -> calling wrapper invokes tp_richcompare(a, b, Py_EQ) directly +# +# do_richcompare algorithm (Objects/object.c#L901-L955): +# 1. Subclass priority: if type(b) is a proper subclass of type(a), +# try type(b)->tp_richcompare(b, a, swapped_op) first +# 2. Forward: type(a)->tp_richcompare(a, b, op) +# 3. Reflected: type(b)->tp_richcompare(b, a, swapped_op) +# 4. Fallback: identity for eq/ne, TypeError for ordering +# +# Dynamo implementation: +# +# tp_richcompare_impl(self, tx, other, op) -- per-VT slot, analogous to +# tp_richcompare. Returns ConstantVariable(NotImplemented) when the +# type does not handle the comparison. +# +# generic_richcompare(tx, lhs, rhs, op) -- analogous to do_richcompare. +# Implements the 4-step algorithm directly using tp_richcompare_impl +# slots. If a user comparison method graph-breaks, the Unsupported +# exception propagates to COMPARE_OP (which has +# @break_graph_if_unsupported) and runs the comparison eagerly. +# UDOV.tp_richcompare_impl disables nested graph breaks on the resolved +# funcvar so the InliningInstructionTranslator does not try to split +# the inlined user method mid-function. +# +# Two entry points converge on tp_richcompare_impl: +# +# COMPARE_OP (a == b): +# -> BuiltinVariable dispatch -> generic_richcompare +# -> tp_richcompare_impl (4-step: subclass priority, forward, reflected, fallback) +# +# call_method("__eq__") (a.__eq__(b) in user code): +# -> base.py call_method -> tp_richcompare_impl directly +# +# The call_method path calls tp_richcompare_impl directly (not +# generic_richcompare) to match CPython semantics: a.__eq__(b) invokes +# the type's tp_richcompare slot without do_richcompare's reflected- +# operand protocol, and may return NotImplemented. +# --------------------------------------------------------------------------- + + +is_richcompare_not_implemented = is_nb_not_implemented + + +def object_richcompare( + self: VariableTracker, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, +) -> VariableTracker: + """object's tp_richcompare. + + https://github.com/python/cpython/blob/e76aa128fe/Objects/typeobject.c#L6263-L6305 + - __eq__: identity check, else NotImplemented + - __ne__: delegates to tp_richcompare(self, other, Py_EQ) and inverts + - ordering + """ + if op == "__eq__": + identity = vt_identity_compare(self, other) + if identity is not None and identity.as_python_constant(): + return ConstantVariable.create(True) + return ConstantVariable.create(NotImplemented) + elif op == "__ne__": + # https://github.com/python/cpython/blob/e76aa128fe/Objects/typeobject.c#L6279-L6298 + # Safe to call as_python_constant(): only identity-based types use + # object_richcompare, so eq_result is always True or NotImplemented. + eq_result = self.tp_richcompare_impl(tx, other, "__eq__") + if is_richcompare_not_implemented(eq_result): + return eq_result + return ConstantVariable.create(not eq_result.as_python_constant()) + else: + return ConstantVariable.create(NotImplemented) + + +def python_constant_richcompare_impl( + self: VariableTracker, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, +) -> VariableTracker: + """Constant-fold comparison for types with as_python_constant().""" + if not self.is_python_constant() or not other.is_python_constant(): + return ConstantVariable.create(NotImplemented) + self_val = self.as_python_constant() + other_val = other.as_python_constant() + try: + result = getattr(type(self_val), op)(self_val, other_val) + except TypeError as e: + raise_observed_exception(TypeError, tx, args=list(e.args)) + return ConstantVariable.create(result) + + +# _Py_SwappedOp: https://github.com/python/cpython/blob/e76aa128fe/Objects/object.c#L987 +_REFLECTED_OP: dict[str, str] = { + "__lt__": "__gt__", + "__gt__": "__lt__", + "__le__": "__ge__", + "__ge__": "__le__", + "__eq__": "__eq__", + "__ne__": "__ne__", +} + +_OP_STR: dict[str, str] = { + "__lt__": "<", + "__le__": "<=", + "__eq__": "==", + "__ne__": "!=", + "__gt__": ">", + "__ge__": ">=", +} + + +def generic_richcompare( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, + op: str, +) -> VariableTracker: + """Dynamo's do_richcompare. + + https://github.com/python/cpython/blob/e76aa128fe/Objects/object.c#L994-L1039 + + Implements the 4-step algorithm directly using tp_richcompare_impl slots. + Graph breaks inside user comparison methods propagate to COMPARE_OP + (which runs eagerly) because UDOV.tp_richcompare_impl disables nested + graph breaks on the resolved funcvar. + """ + reflected = _REFLECTED_OP[op] + + try: + v_type = v.python_type() + except NotImplementedError: + v_type = None + try: + w_type = w.python_type() + except NotImplementedError: + w_type = None + + checked_reverse = False + + # Step 1: subclass priority + if ( + v_type is not None + and w_type is not None + and v_type is not w_type + and issubclass(w_type, v_type) + ): + checked_reverse = True + result = w.tp_richcompare_impl(tx, v, reflected) + if not is_richcompare_not_implemented(result): + return result + + # Step 2: forward + result = v.tp_richcompare_impl(tx, w, op) + if not is_richcompare_not_implemented(result): + return result + + # Step 3: reflected (if not already tried) + if not checked_reverse: + result = w.tp_richcompare_impl(tx, v, reflected) + if not is_richcompare_not_implemented(result): + return result + + # Step 4: fallback + if op in ("__eq__", "__ne__"): + identity = vt_identity_compare(v, w) + if identity is not None: + if op == "__ne__": + return ConstantVariable.create(not identity.as_python_constant()) + return identity + unimplemented( + gb_type="richcompare identity fallback undetermined", + context=f"generic_richcompare({v}, {w}, {op})", + explanation="Cannot determine object identity for comparison fallback.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + else: + raise_type_error( + tx, + f"'{_OP_STR[op]}' not supported between instances of " + f"'{v.python_type_name()}' and '{w.python_type_name()}'", + ) + + +def generic_richcompare_bool( + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, + op: str, +) -> VariableTracker: + """Dynamo's PyObject_RichCompareBool for eq/ne. + + https://github.com/python/cpython/blob/e76aa128fe/Objects/object.c#L1046-L1080 + + Like generic_richcompare, but with an identity shortcut first: if v + and w are the same Python object, eq is True and ne is False. This + matters for NaN (nan is nan -> True, but nan == nan -> False). Used by + container comparisons (list_richcompare, tuplerichcompare) which call + PyObject_RichCompareBool per element in CPython. + """ + if op not in ("__eq__", "__ne__"): + raise AssertionError(f"generic_richcompare_bool only supports eq/ne, got {op}") + identity = vt_identity_compare(v, w) + if identity is not None and identity.as_python_constant(): + return ConstantVariable.create(op == "__eq__") + return generic_richcompare(tx, v, w, op) + + +def generic_hash_impl( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> tuple[int, bool]: + """Internal API: compute hash as (value, is_fake). + + Dispatches to the VT's hash_impl. Called by generic_hash (which wraps + the result in a VT), container hash_impls (which propagate is_fake), + and HashableTracker (which just needs the int). + """ + return obj.hash_impl(tx) + + +def generic_hash( + tx: "InstructionTranslatorBase", obj: VariableTracker +) -> VariableTracker: + """User-facing API: mirrors PyObject_Hash, returns a VariableTracker. + + https://github.com/python/cpython/blob/e76aa128fe/Objects/object.c#L1101-L1115 + + Wraps the result in ConstantVariable or FakeIdVariable depending on + whether the hash depends on a sourceless object's identity. + """ + from .constant import ConstantVariable, FakeIdVariable, FakeValueKind + + h, is_fake = generic_hash_impl(tx, obj) + if is_fake: + return FakeIdVariable(h, kind=FakeValueKind.HASH) + return ConstantVariable.create(h) + + +def pysequence_contains( + tx: "InstructionTranslatorBase", obj: "VariableTracker", item: "VariableTracker" +) -> "VariableTracker": + """ + Implements PySequence_Contains semantics for VariableTracker objects. + + If the object has sq_contains (i.e., __contains__), calls obj.sq_contains_impl(tx, item). + Otherwise falls back to iterating over obj and comparing each element. + """ + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L2272-L2283 + sq_contains = obj.tp_as_sequence.sq_contains + if sq_contains is not None: + return obj.sq_contains_impl(tx, item) + else: + # iter fallback handles both __iter__ and __getitem__ sequence protocol cases + it = generic_getiter(tx, obj) + return VariableTracker.build( + tx, polyfills.impl_CONTAINS_OP_fallback + ).call_function(tx, [item, it], {}) + + +# Metaclasses whose __subclasscheck__ Dynamo can't trace but whose +# behavior we're willing to observe at trace time via Python's issubclass. +# Each entry trades fidelity to the metaclass's side effects (e.g. ABC's +# subclass cache mutation) for coverage of the common case. +_CONSTANT_FOLD_SUBCLASSCHECK_METACLASSES: tuple[type, ...] = ( + abc.ABCMeta, + torch._C._TensorMeta, # actually just type.__subclasscheck__, but easier to list it here + enum.EnumMeta, +) + + +def generic_issubclass( + tx: "InstructionTranslatorBase", + derived: VariableTracker, + cls: VariableTracker, +) -> VariableTracker: + """Mirrors CPython's PyObject_IsSubclass / object_issubclass. + + https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L2766-L2823 + + This only attempts to replicate object_issubclass, otherwise we delegate to cpython + """ + derived_py = derived.get_real_python_backed_value() + cls_py = cls.get_real_python_backed_value() + if derived_py is NO_SUCH_SUBOBJ or cls_py is NO_SUCH_SUBOBJ: + unimplemented( + gb_type="issubclass() with unsupported arguments", + context=f"issubclass({derived}, {cls})", + explanation="Arguments to issubclass() must be backed by python values.", + hints=[ + "Make sure your arguments are types.", + *graph_break_hints.USER_ERROR, + *graph_break_hints.SUPPORTABLE, + ], + ) + cls_type = maybe_get_python_type(cls) + + # Step 1: PyType_CheckExact fast path — abstract.c L2772 + if cls_type is type: + try: + return ConstantVariable.create( + issubclass( + derived_py, # pyrefly: ignore [bad-argument-type] + cls_py, # pyrefly: ignore [invalid-argument] + ) + ) + except TypeError as e: + raise_observed_exception(TypeError, tx, args=list(e.args)) + + # Step 2: PEP 604 Union (e.g. ``int | str``) — abstract.c L2779-2781. + union_types = {types.UnionType} + if sys.version_info < (3, 14): + union_types.add( + typing._UnionGenericAlias # pyrefly: ignore [missing-attribute] + ) + if cls_type in union_types: + # TODO can trace this once TypingVariable is removed + args = typing.get_args(cls_py) + cls = VariableTracker.build(tx, args) + + # Step 3: tuple of classes — abstract.c L2783-2799. Check for + # TupleVariable instead of tuple to make the type checker happy. + from .lists import TupleVariable + + if isinstance(cls, TupleVariable): + for item in cls.items: + r = generic_issubclass(tx, derived, item) + if isinstance(r, ConstantVariable) and r.value: + return ConstantVariable.create(True) + return ConstantVariable.create(False) + + # Allowlist short-circuit for Step 4: constant-fold via Python's + # issubclass for metaclasses whose ``__subclasscheck__`` Dynamo can't + # trace (see _CONSTANT_FOLD_SUBCLASSCHECK_METACLASSES). Note that ABCMeta + # is problematic in particular since it caches registered subclasses. + # Ideally this should be traced or guarded + if isinstance(cls_py, type) and issubclass( + type(cls_py), _CONSTANT_FOLD_SUBCLASSCHECK_METACLASSES + ): + try: + return ConstantVariable.create( + issubclass( + derived_py, # pyrefly: ignore [bad-argument-type] + cls_py, + ) + ) + except TypeError as e: + raise_observed_exception(TypeError, tx, args=list(e.args)) + + # TypeError gate, mirroring abstract.c L2822 ``recursive_issubclass``: + # CPython reaches that fallback when ``_PyObject_LookupSpecial`` for + # ``__subclasscheck__`` returns NULL, and its first action is + # ``check_class(cls, ...)`` which raises this TypeError. We check + # eagerly because Dynamo's ``call_method`` below would graph-break + # rather than cleanly signal "no such method". + if not isinstance(cls_py, type): + raise_type_error( + tx, + "issubclass() arg 2 must be a class, a tuple of classes, or a union", + ) + + # Step 4: general case — call ``__subclasscheck__`` on cls's metaclass + # (abstract.c L2801-2815). Runs user code on a custom metaclass. + result = cls.call_method(tx, "__subclasscheck__", [derived], {}) + + # Coerce to bool (PyObject_IsTrue, abstract.c L2812). + return generic_is_true(tx, result) + + +# ── tp_getattro ────────────────────────────────────────────────────── +# +# Dynamo's PyObject_GetAttr / PyObject_GenericGetAttr. +# +# CPython references: +# PyObject_GetAttr: Objects/object.c#L1259-L1283 +# PyObject_GenericGetAttr: Objects/object.c#L1611-L1683 +# _PyType_LookupRef: Objects/typeobject.c#L5208-L5262 +# +# PyObject_GetAttr(obj, name): +# tp = Py_TYPE(obj) +# if tp->tp_getattro: +# return tp->tp_getattro(obj, name) +# ... +# raise AttributeError +# +# Dispatch path: +# LOAD_ATTR / getattr() -> GetAttrBuiltinVariable -> generic_getattr +# -> obj.tp_getattro_impl(tx, name) +# +# The base VariableTracker.tp_getattro_impl tries object_generic_getattr() +# first (MRO walk + descriptor protocol), falling back to const_getattr +# on _UnhandledDescriptorError. Callers of object_generic_getattr +# directly must handle _UnhandledDescriptorError at every step (2, 4, +# and 7), not just for unrecognized descriptor types. +# +# VTs with custom tp_getattro (TensorVariable, NNModuleVariable, +# UserDefinedClassVariable, SuperVariable) override tp_getattro_impl. + +_NO_DEFAULT = object() + + +_UnhandledDescriptorError = UnhandledDescriptorError + + +def mro_lookup(py_type: type, name: str) -> object: + """Walk py_type.__mro__ to find *name* in the class hierarchy. + + Mirrors CPython's _PyType_LookupRef (Objects/typeobject.c). + Searches only the class chain (py_type.__mro__), NOT the metaclass + chain. Returns the raw descriptor/value from the class __dict__, + or NO_SUCH_SUBOBJ if not found. + """ + for base in py_type.__mro__: + if name in base.__dict__: + return base.__dict__[name] + return NO_SUCH_SUBOBJ + + +def _resolve_descriptor_get( + tx: "InstructionTranslatorBase", + type_attr: object, + obj: VariableTracker, + class_vt: VariableTracker, + source: "Source | None", +) -> "VariableTracker | None": + """Invoke tp_descr_get on a type attribute if it's a descriptor. + + Handles all descriptor types that have dedicated VTs with + tp_descr_get_impl. Returns None if type_attr is not a recognized + descriptor type (plain class variable). + """ + import types as _types + + if isinstance(type_attr, property): + prop_vt = variables.PropertyVariable(type_attr, source=source) + return prop_vt.tp_descr_get_impl(tx, obj, class_vt) + if isinstance(type_attr, _types.MemberDescriptorType): + md_vt = variables.MemberDescriptorVariable(type_attr, source=source) + return md_vt.tp_descr_get_impl(tx, obj, class_vt) + if isinstance(type_attr, _types.GetSetDescriptorType): + gs_vt = variables.GetSetDescriptorVariable(type_attr, source=source) + return gs_vt.tp_descr_get_impl(tx, obj, class_vt) + _tuplegetter = collections._tuplegetter # pyrefly: ignore[missing-attribute] + if isinstance(type_attr, _tuplegetter): + tg_vt = variables.TupleGetterVariable(type_attr, source=source) + return tg_vt.tp_descr_get_impl(tx, obj, class_vt) + if isinstance(type_attr, staticmethod): + sm_vt = variables.StaticMethodVariable(type_attr, source=source) + return sm_vt.tp_descr_get_impl(tx, obj, class_vt) + if isinstance(type_attr, classmethod): + cm_vt = variables.ClassMethodVariable(type_attr, source=source) + return cm_vt.tp_descr_get_impl(tx, obj, class_vt) + if isinstance(type_attr, _types.ClassMethodDescriptorType): + cmd_vt = variables.ClassMethodDescriptorVariable(type_attr, source=source) + return cmd_vt.tp_descr_get_impl(tx, obj, class_vt) + if isinstance(type_attr, _types.WrapperDescriptorType): + wd_vt = variables.WrapperDescriptorVariable( + type_attr, owner=class_vt, source=source + ) + return wd_vt.tp_descr_get_impl(tx, obj, class_vt) + if isinstance(type_attr, _types.MethodDescriptorType): + md_vt = variables.MethodDescriptorVariable( + type_attr, owner=class_vt, source=source + ) + return md_vt.tp_descr_get_impl(tx, obj, class_vt) + if isinstance(type_attr, _types.FunctionType): + return variables.UserMethodVariable(type_attr, obj, source=source) + + return None + + +# BuiltinFunctionType is intentionally excluded: _resolve_descriptor_get +# does not handle it, so it falls through to _UnhandledDescriptorError +# and generic_getattr's GetAttrVariable fallback. +_METHOD_TYPES = ( + types.FunctionType, + types.MethodDescriptorType, + types.WrapperDescriptorType, +) + + +def _is_method_type(type_attr: object) -> bool: + return isinstance(type_attr, _METHOD_TYPES) + + +def _has_custom_call_method(obj: VariableTracker) -> bool: + for cls in type(obj).__mro__: + if cls is VariableTracker: + return False + if "call_method" in cls.__dict__: + return True + return False + + +def object_generic_getattr( + tx: "InstructionTranslatorBase", + obj: VariableTracker, + name: str, +) -> VariableTracker: + """Dynamo's PyObject_GenericGetAttr. + + https://github.com/python/cpython/blob/e76aa128fe/Objects/object.c#L1611-L1683 + + Implements the standard attribute lookup algorithm using the VT's + python_type() for MRO walking, and hooks on the VT for instance dict + and __getattr__ fallback. + + Steps: + 1. MRO walk on python_type() for type_attr + 2. Data descriptor -> invoke tp_descr_get + 3. Instance dict -> obj.lookup_instance_dict(tx, name) + 4. Non-data descriptor -> invoke tp_descr_get + 5. Plain class variable -> wrap in VT + 6. __getattr__ fallback -> obj.call_getattr_fallback(tx, name) + 7. AttributeError + """ + from .user_defined import is_data_descriptor + + py_type = obj.python_type() + source = obj.source and AttrSource(obj.source, name) + + # Step 1: MRO walk. + type_attr = mro_lookup(py_type, name) + + # Step 2: Data descriptor takes priority over instance dict. + if type_attr is not NO_SUCH_SUBOBJ and is_data_descriptor(type_attr): + class_vt = VariableTracker.build(tx, py_type) + result = _resolve_descriptor_get(tx, type_attr, obj, class_vt, source) + if result is not None: + return result + raise _UnhandledDescriptorError( + f"object_generic_getattr: unhandled data descriptor " + f"{type(type_attr)} for {name}" + ) + + # Step 3: Instance dict (tp_dictoffset). + instance_result = obj.lookup_instance_dict(tx, name) + if instance_result is not None: + return instance_result + + # Step 4: Non-data descriptor with __get__. + if type_attr is not NO_SUCH_SUBOBJ and hasattr(type(type_attr), "__get__"): + # If the VT dispatches this method through call_method (a hand-written + # override or a tp_methods entry), return a CallMethodVariable that + # dispatches through call_method instead of inlining the resolved + # method directly. This preserves custom tracing logic (side effects, + # graph nodes, suppression) that MRO-based resolution via + # UserMethodVariable would bypass. + if _is_method_type(type_attr) and ( + obj._lookup_tp_table(name, "tp_methods") is not None + or _has_custom_call_method(obj) + ): + return variables.CallMethodVariable(obj, name, source=source) + + class_vt = VariableTracker.build(tx, py_type) + result = _resolve_descriptor_get(tx, type_attr, obj, class_vt, source) + if result is not None: + return result + raise _UnhandledDescriptorError( + f"object_generic_getattr: unhandled non-data descriptor " + f"{type(type_attr)} for {name}" + ) + + # Step 5: Plain class variable (no __get__). + if type_attr is not NO_SUCH_SUBOBJ: + return VariableTracker.build(tx, type_attr, source) + + # Step 6: __getattr__ fallback. + getattr_result = obj.call_getattr_fallback(tx, name) + if getattr_result is not None: + return getattr_result + + # Step 7: Attribute not found -- signal to caller to fall back. + raise _UnhandledDescriptorError( + f"object_generic_getattr: '{py_type.__name__}' has no attribute '{name}'" + ) + + +def generic_getattr( + tx: "InstructionTranslatorBase", + obj: VariableTracker, + name: str, + default: "VariableTracker | object" = _NO_DEFAULT, +) -> VariableTracker: + """Dynamo's PyObject_GetAttr: attribute access dispatch. + + Checks side effects for pending attribute mutations, then dispatches + to obj.tp_getattro_impl(tx, name). On NotImplementedError, falls back + to GetAttrVariable (deferred resolution). + """ + from .user_defined import is_data_descriptor + + # NOTE [Tensor "grad" and "_grad" attr] + if obj.is_tensor() and name == "_grad": + name = "grad" + + # Side effects: check for pending attribute mutations. + if tx.output.side_effects.has_pending_mutation_of_attr(obj, name): + if not isinstance(obj, variables.UserDefinedObjectVariable): + return tx.output.side_effects.load_attr(obj, name) + if tx.output.side_effects.has_pending_mutation_of_attr( + obj, name, AttrMutationKind.INSTANCE_DICT + ): + value = tx.output.side_effects.load_attr(obj, name, deleted_ok=True) + type_attr = obj.lookup_class_mro_attr(name) + if not isinstance(value, variables.DeletedVariable) and ( + type_attr is NO_SUCH_SUBOBJ or not is_data_descriptor(type_attr) + ): + return value + + # Handle default for getattr(obj, name, default). + if default is not _NO_DEFAULT: + hasattr_var = obj.call_obj_hasattr(tx, name) + if not hasattr_var.is_constant_match(True, False): + raise AssertionError( + f"hasattr_var must be a constant True or False, got {hasattr_var}" + ) + if not hasattr_var.as_python_constant(): + return default # type: ignore[return-value] + + # tp_getset/tp_members are data descriptors: resolve ahead of the VT's + # tp_getattro so a tp_getattro_impl override need not repeat the consult. + getset = obj.lookup_tp_getset_member(name) + if getset is not None: + result = getset.getter(obj, tx) + if result is not None: + return result + + # Core dispatch: call the VT's tp_getattro_impl (tp_getattro). + source = obj.source and AttrSource(obj.source, name) + try: + return obj.tp_getattro_impl(tx, name) + except AsPythonConstantNotImplementedError: + raise + except NotImplementedError: + return variables.GetAttrVariable(obj, name, source=source) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/optimizer.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..eb88bab39d81358c40752acd7ad7a469f31e8fd2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/optimizer.py @@ -0,0 +1,434 @@ +""" +This module implements variable tracking for PyTorch optimizers during Dynamo tracing. + +The OptimizerVariable class provides specialized handling for optimizer instances by: +- Optimizing the tracing of expensive optimizer initialization +- Managing optimizer state and parameter group tracking +- Handling tensor sources and guards for optimizer state tensors +- Supporting CUDA graph execution through static tensor address management +- Providing special handling for parameter gradients and optimizer state tensors + +Key features include: +- Efficient initialization tracing via _init_group optimization +- Automatic marking of optimizer state tensors as static for CUDA graphs +- Proper source tracking for parameter groups, gradients, and state tensors +- Guard installation for optimizer state structure +- Support for both CPU and GPU tensor handling +- Cleanup of static tensor references via finalizers + +The module integrates with Dynamo's broader tracing system while providing +optimizer-specific optimizations and safety guarantees. +""" + +import logging +import weakref +from collections.abc import Iterable +from typing import Any, TYPE_CHECKING + +import torch +from torch._dynamo.variables.tensor import TensorVariable +from torch._guards import Source +from torch._logging import getArtifactLogger +from torch.utils._pytree import tree_map_only + +from ..guards import GuardBuilder, install_guard +from ..source import ( + AttrSource, + ConstDictKeySource, + DictGetItemSource, + GetItemSource, + GlobalWeakRefSource, + GradSource, +) +from ..utils import GLOBAL_KEY_PREFIX, unpack_iterable +from .base import GetSet, VariableTracker +from .constant import ConstantVariable +from .dicts import ConstDictVariable +from .hashable import HashableTracker +from .lists import ListVariable +from .misc import GetAttrVariable +from .user_defined import UserDefinedObjectVariable + + +if TYPE_CHECKING: + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + +class ArgMappingException(Exception): + pass + + +class GuardInstallException(Exception): + pass + + +perf_hint_log = getArtifactLogger(__name__, "perf_hints") + + +def _is_static_for_cudagraphs(x: torch.Tensor) -> bool: + from torch._inductor.cudagraph_trees import get_manager + + if x.is_cuda: + manager = get_manager(x.device.index, False) + is_static_address = torch._dynamo.utils.get_static_address_type(x) is not None + if manager: + if manager.current_node is None: + raise AssertionError("CUDA graph manager has no current node") + return ( + is_static_address + or manager.current_node._is_cuda_graph_recorded_tensor(x) + ) + else: + return is_static_address + else: + # Don't print a warning for non-cuda tensors + return True + + +class OptimizerVariable(UserDefinedObjectVariable): + _nonvar_fields = { + "grad_to_source", + "tensor_to_source", + "static_tensor_names", + *UserDefinedObjectVariable._nonvar_fields, + } + + def __init__( + self, + value: torch.optim.Optimizer, + grad_to_source: dict[Any, GradSource] | None = None, + static_tensor_names: set[str] | None = None, + tensor_to_source: dict[torch.Tensor, Source] | None = None, + **kwargs: Any, + ) -> None: + super().__init__(value, **kwargs) + # pyrefly: ignore [bad-override] + self.value: torch.optim.Optimizer = value + self.grad_to_source = grad_to_source or {} + self.tensor_to_source = tensor_to_source or {} + self.static_tensor_names = static_tensor_names or set() + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> "VariableTracker": + """This is an optimization to avoid tracing the very slow initialization of the optimizer""" + if name == "_init_group": + if not hasattr(self.value, "_init_group"): + # Fallback: if the optimizer does not have _init_group, trace normally + return super().call_method(tx, name, args, kwargs) + try: + self.graph_break_if_pending_mutation(tx) + self.move_step_if_cpu() + py_args, py_kwargs = self.get_python_args(*args, **kwargs) + ret_val = self.value._init_group(*py_args, **py_kwargs) + self.map_sources_and_install_guards(tx) + self.update_list_args(tx, args, kwargs, py_args, py_kwargs) + # stash a weak_ptr to optimizer to invalidate code + # if the optimizer object dies + mangled_name = f"__optimizer_{id(self.value)}" + tx.store_global_weakref_by_id(mangled_name, self.value) + self.create_finalizer(tx) + + # This is currently safe only because the only actual `ret_val`s returned + # by the `_init_group` of existing optimizers are properties that are invariant + # to the input tensors (e.g. dtype, layout). Changing these would trigger a + # recompilation and hence never result in the wrong specialization of `ret_val`. + return ConstantVariable.create(ret_val) + except (ArgMappingException, GuardInstallException) as _: + # trace normally if we can't map args or install guards correctly + pass + + return super().call_method(tx, name, args, kwargs) + + # _init_group resolves to a GetAttrVariable so the call is intercepted in + # call_method (in the typical case, a UserMethodVariable would inline it). + def _get_init_group(self, tx: "InstructionTranslatorBase") -> VariableTracker: + if not self.source: + raise AssertionError("OptimizerVariable requires a source for _init_group") + name = "_init_group" + py_type = type(getattr(self.value, name)) + return GetAttrVariable( + self, name, py_type=py_type, source=AttrSource(self.source, name) + ) + + # param_groups only runs setup side effects (static addresses, capturable + # guards) and declines, falling through to the generic protocol. + def _get_param_groups(self, tx: "InstructionTranslatorBase") -> None: + from ..decorators import mark_static_address + + for group in self.value.param_groups: + for p in group["params"]: + mark_static_address(p, guard=True) + + self._set_capturable(tx) + return None + + tp_getset = { + "_init_group": GetSet(_get_init_group), + "param_groups": GetSet(_get_param_groups), + } + + def graph_break_if_pending_mutation(self, tx: "InstructionTranslatorBase") -> None: + # If there are pending mutations on a parameter (due to using closure) + # then we need to graph break to allow the python version of the parameter + # to update, so that running _init_group will initialize the states with + # the correct values + for g in self.value.param_groups: + for p in g["params"]: + side_effects = tx.output.side_effects + variable = side_effects.id_to_variable.get(id(p), None) + if variable and side_effects.has_pending_mutation(variable): + from ..exc import unimplemented + + unimplemented( + gb_type="optimizer: pending mutation on parameter", + context=f"variable: {variable}, parameter: {p}", + explanation="Pending mutations on a parameter (e.g. due to using closure) require a graph break.", + hints=[], + ) + + def _set_capturable(self, tx: "InstructionTranslatorBase") -> None: + from . import LazyVariableTracker + + # We only set capturable if params are on cuda + # and the state is not initialized + def safe_to_set_capturable(group: dict[str, Any]) -> bool: + all_uninitialized = True + all_gpu = True + + for p in group.get("params", []): + all_gpu &= p.is_cuda or p.is_xpu + all_uninitialized &= p not in self.value.state + + return "capturable" in group and all_uninitialized and all_gpu + + # track indices to not set so we don't need to + # in the variable tracker realize the whole state + # we handle guarding the state specially + for group in self.value.param_groups: + if safe_to_set_capturable(group): + group["capturable"] = True + + source = self.source and AttrSource(self.source, "param_groups") + param_groups_vt = LazyVariableTracker.realize_all( + VariableTracker.build(tx, self.value.param_groups, source) + ) + for param_group_vt in param_groups_vt.items: + key = HashableTracker(ConstantVariable.create("capturable")) + param_group_vt.items[key] = ConstantVariable.create(True) + + def get_python_args( + self, *args: Any, **kwargs: Any + ) -> tuple[list[Any], dict[str, Any]]: + """Get python values equivalent to the variable tracker args""" + + def map_arg(arg: Any) -> Any: + if isinstance(arg, VariableTracker) and arg.is_python_constant(): + return arg.as_python_constant() + elif isinstance(arg, ListVariable) and not arg.items: + # pyrefly: ignore [implicit-any] + return [] + elif ( + isinstance(arg, ConstDictVariable) + and isinstance(arg.source, GetItemSource) + and isinstance(arg.source.base, AttrSource) + and arg.source.base.member == "param_groups" + ): + return self.value.param_groups[arg.source.index] + + raise ArgMappingException + + new_args = [map_arg(arg) for arg in args] + new_kwargs = {k: map_arg(v) for k, v in kwargs.items()} + + return new_args, new_kwargs + + # If users load an old state dictionary, + # it's possible that step could be on the cpu + # if this is the case, move it to the GPU + # corresponding to the parameter + # in most cases this is a no-op because the state is empty + def move_step_if_cpu(self) -> None: + for p, state in self.value.state.items(): + if "step" in state and state["step"].is_cpu: + state["step"] = state["step"].to(p.device) + + def map_sources_and_install_guards(self, tx: "InstructionTranslatorBase") -> None: + from ..decorators import mark_static_address + from .lazy import LazyVariableTracker + + self.grad_to_source = {} + self.tensor_to_source = {} + + def mark_static(x: Any) -> None: + mark_static_address(x, guard=True) + + tree_map_only(torch.Tensor, mark_static, self.value.state) + + # Recursively realize the variable trackers for optim.state and + # optim.param_groups, which recursively install the necessary guards. + params_groups_source = self.source and AttrSource(self.source, "param_groups") + param_groups_vt = LazyVariableTracker.realize_all( + VariableTracker.build(tx, self.value.param_groups, params_groups_source) + ) + + state_source = self.source and AttrSource(self.source, "state") + state_vt = VariableTracker.build(tx, self.value.state, state_source) + + # We need to realize the top level state dict to populate + # the guard locals + state_vt.realize() + if state_source is None: + raise AssertionError("state_source must not be None") + tx.output.guard_on_key_order.add(state_source) + + # Populate self.grad_to_source and self.tensor_to_source so that we can + # manually update_list_args + for group, group_vt in zip(self.value.param_groups, param_groups_vt.items): + # we assume here that all params within a param group + # are initialized similarly + if len(group["params"]) > 0: + for param in group["params"]: + if param.grad is not None: + key_index = None + for i, k in enumerate(self.value.state.keys()): + if k is param: + key_index = i + break + if key_index: + LazyVariableTracker.realize_all( + VariableTracker.build( + tx, + self.value.state[param], + DictGetItemSource( + state_source, + ConstDictKeySource(state_source, key_index), + ), + ) + ) + break + + params_vt = group_vt.getitem_const(tx, ConstantVariable.create("params")) + all_static = True + non_static_grads = [] + for p, p_vt in zip(group["params"], unpack_iterable(tx, params_vt)): + param_source = p_vt.source + if param_source is None: + raise AssertionError(f"param {p} does not have a source") + self.tensor_to_source[p] = param_source + grad_source = GradSource( + param_source, + "grad", + ) + + if p.grad is not None: + self.grad_to_source[p.grad] = grad_source + if not _is_static_for_cudagraphs(p.grad): + all_static = False + non_static_grads.append(grad_source) + else: + install_guard(grad_source.make_guard(GuardBuilder.CONSTANT_MATCH)) + + # Note: to avoid spam logs only warn if perf hint artifact is enabled + # (NB: artifacts are only enabled at the debug or warning level) + if not all_static and perf_hint_log.isEnabledFor(logging.DEBUG): + non_static_grad_names = [src.name for src in non_static_grads] + perf_hint_log.warning( + ( + "Grad tensors %s will be copied during cudagraphs execution." + "If using cudagraphs and the grad tensor addresses will be the same across runs," + " use torch._dynamo.decorators.mark_static_address to elide this copy.", + ), + non_static_grad_names, + ) + + # We have to again iterate over the state dict to collect the + # tensor_to_source dict. This is used for the finalizer. + for idx, value in enumerate(self.value.state.values()): + p_state_source = DictGetItemSource( + state_source, ConstDictKeySource(state_source, idx) + ) + tx.output.guard_on_key_order.add(p_state_source) + for inner_idx, v in enumerate(value.values()): + if ( + isinstance(v, torch.Tensor) + and v not in self.grad_to_source + and v not in self.tensor_to_source + ): + self.tensor_to_source[v] = DictGetItemSource( + p_state_source, ConstDictKeySource(p_state_source, inner_idx) + ) + + def wrap_tensor( + self, tx: "InstructionTranslatorBase", tensor_value: torch.Tensor + ) -> TensorVariable: + """Wrap state tensor in a TensorVariable""" + from ..decorators import mark_static_address + + # If we have a source for a tensor already use it, + # if we have not seen a tensor before, stash and use a + # global weak ref source, since it must be an optimizer tensor + # that we have missed + + if tensor_value in self.tensor_to_source: + # mark these tensors as static for cudagraphs + mark_static_address(tensor_value, guard=True) + source = self.tensor_to_source[tensor_value] + self.static_tensor_names.add(tx.output.module_key_name(source.name)) + elif tensor_value in self.grad_to_source: + source = self.grad_to_source[tensor_value] + else: + # mark these tensors as static for cudagraphs + mark_static_address(tensor_value, guard=True) + + global_name = tx.store_global_weakref_by_id(GLOBAL_KEY_PREFIX, tensor_value) + source = GlobalWeakRefSource(global_name) + self.static_tensor_names.add(tx.output.module_key_name(source.name)) + + return VariableTracker.build(tx, tensor_value, source) + + def update_list_args( + self, + tx: "InstructionTranslatorBase", + args: Iterable[VariableTracker], + kwargs: Any, + py_args: Iterable[Any], + py_kwargs: Any, + ) -> None: + """Update the args and kwargs to the traced optimizer call""" + for arg, py_arg in zip(args, py_args): + if isinstance(arg, ListVariable): + if not isinstance(py_arg, list): + raise AssertionError( + "py_arg should be a list in optimizer variable" + ) + for i, val in enumerate(py_arg): + tx.output.side_effects.mutation(arg) + if isinstance(val, torch.Tensor): + arg.items.append(self.wrap_tensor(tx, val)) + else: + source = arg.source and GetItemSource(arg.source, i) + arg.items.append(VariableTracker.build(tx, val, source)) + + def create_finalizer(self, tx: "InstructionTranslatorBase") -> None: + names_to_delete = self.static_tensor_names + value = self.value + tc = tx.output.tracing_context + + def init_finalizer(gm: torch.fx.GraphModule) -> None: + def clear_static_tensor_refs() -> None: + for name in names_to_delete: + gm._buffers.pop(name, None) + gm._parameters.pop(name, None) + if tc.params_flat: + tc.params_flat.clear() + if tc.params_flat_unwrap_subclasses: + tc.params_flat_unwrap_subclasses.clear() + + weakref.finalize(value, clear_static_tensor_refs) + + tx.output.add_graph_finalizer(init_finalizer) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/script_object.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/script_object.py new file mode 100644 index 0000000000000000000000000000000000000000..2630864cdae3b8b2565a20bf8a0561fdbdde0740 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/script_object.py @@ -0,0 +1,587 @@ +""" +This module implements variable tracking for TorchScript objects during Dynamo tracing. + +The CustomClassObjectVariable class provides specialized handling for TorchScript +objects with strong safety guarantees by: +- Enforcing method-call-only access to prevent unsafe attribute manipulation +- Converting graph breaks into hard errors via _raise_hard_error_if_graph_break +- Proper proxy and source tracking for TorchScript method calls +- Integration with higher-order operators for method call handling + +Key safety features: +- Strict validation that only method calls are allowed (no direct attribute access) +- Immediate error reporting for potentially unsafe operations +- Proper source tracking for debugging and guard installation +- Safe handling of TorchScript object method calls through torchbind + +The module ensures that TorchScript objects are handled safely during tracing +by limiting operations to known-safe patterns and failing fast for unsafe usage. +""" + +import enum +import functools +import inspect +import types +from collections.abc import Callable, Iterable +from typing import Any, TYPE_CHECKING, TypeVar +from typing_extensions import ParamSpec + +import torch +import torch.utils._pytree as pytree +from torch._guards import Source +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import ( + get_member_type, + is_custom_class, + is_opaque_constant_type, + is_opaque_symbolic_type, + MemberType, + should_hoist, +) +from torch.fx.proxy import Proxy + +from .. import graph_break_hints +from ..eval_frame import skip_code +from ..exc import ( + raise_observed_exception, + unimplemented, + UnsafeScriptObjectError, + Unsupported, +) +from ..source import AttrSource +from ..utils import proxy_args_kwargs +from .base import VariableTracker +from .constant import ConstantVariable +from .dicts import ConstDictVariable +from .lists import TupleVariable +from .misc import LambdaVariable +from .user_defined import UserDefinedObjectVariable, UserDefinedVariable + + +if TYPE_CHECKING: + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + +_P = ParamSpec("_P") +_T = TypeVar("_T") + + +def _raise_hard_error_if_graph_break( + reason: str, +) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: + def deco(fn: Callable[_P, _T]) -> Callable[_P, _T]: + @functools.wraps(fn) + def graph_break_as_hard_error(*args: _P.args, **kwargs: _P.kwargs) -> _T: + try: + return fn(*args, **kwargs) + except Unsupported as e: + raise UnsafeScriptObjectError(e.msg) from e + + return graph_break_as_hard_error + + return deco + + +class CustomClassVariable(UserDefinedVariable): + """ + A variable that represents an opaque object class (not instance). + Since UserDefinedClassVariable has some special handling for side effects, + we have a separate class here which will directly return the object when + __init__ is called. + """ + + def __init__(self, value: Any, **kwargs: Any) -> None: + if isinstance(value, type) and issubclass(value, enum.Enum): + raise AssertionError( + f"Enum class {value} should use UserDefinedClassVariable, " + "not CustomClassVariable" + ) + super().__init__(**kwargs) + self.value = value + + def as_python_constant(self) -> Any: + return self.value + + def is_python_constant(self) -> bool: + # prevents constant folding of attribute accesses on + # opaque classes. this ensures tp_getattro_impl is called, + # allowing for proper validation and error handling + return False + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # CustomClassVariable wraps the CLASS, not an instance. + # Classes are always hashable in CPython (type.__hash__ = object.__hash__). + return hash(self.value), False + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: "VariableTracker", + reverse: bool = False, + ) -> "VariableTracker": + try: + other_val = other.as_python_constant() + except NotImplementedError: + return VariableTracker.build(tx, NotImplemented) + # pyrefly: ignore[bad-argument-count] + result = type(self.value).__or__(self.value, other_val) + if result is NotImplemented: + return VariableTracker.build(tx, NotImplemented) + return VariableTracker.build(tx, result) + + def as_proxy(self) -> Any: + return self.value + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.value})" + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + obj = None + try: + obj = inspect.getattr_static(self.value, name) + except AttributeError: + unimplemented( + gb_type="Attribute not found on opaque class", + context=f"class={self.value}, attr={name}", + explanation=f"The attribute '{name}' does not exist on opaque class {self.value}.", + hints=[ + f"Ensure '{name}' is a valid attribute of {type(self.value)}.", + ], + ) + + if isinstance(obj, staticmethod): + obj = obj.__get__(self.value) + elif isinstance(obj, property): + obj = obj.__get__(None, self.value) # pyrefly: ignore[no-matching-overload] + elif hasattr(obj, "__get__"): + if not isinstance(type(obj).__dict__.get("__get__"), types.FunctionType): + # C-level descriptors are safe to resolve dynamically. + obj = getattr(self.value, name) + else: + type_name = type(obj).__name__ + unimplemented( + gb_type="Unsupported descriptor on opaque class", + context=f"class={self.value}, attr={name}, descriptor={type_name}", + explanation=f"The attribute '{name}' is a descriptor of type '{type_name}' which is not supported.", + hints=[ + "Only staticmethod, property, and pybind11_static_property are supported.", + "Consider accessing this attribute outside of the compiled region.", + ], + ) + + if ConstantVariable.is_literal(obj): + return VariableTracker.build(tx, obj) + + source = AttrSource(self.source, name) if self.source else None + return VariableTracker.build(tx, obj, source) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # disallow creating reference-type opaque objects in the middle of the + # program + if is_opaque_symbolic_type(self.value): + # Skip __init__ to prevent dynamo from tracing it during resume. + # C extension types (e.g. torch._C.Generator) have wrapper_descriptor + # __init__ without __code__, so guard the skip_code call. + if hasattr(self.value.__init__, "__code__"): + skip_code(self.value.__init__.__code__) + + unimplemented( + gb_type="An opaque object was created in the middle of the program.", + context=f"Opaque object type: {self.value}.", + explanation=( + "Opaque objects cannot be created inside the torch.compile region. " + "They must be created before entering the compiled function." + ), + hints=[ + "Please create the opaque object before calling torch.compile " + "and pass it in as an argument or as a global variable." + ], + ) + + var_args = TupleVariable(list(args)) + var_kwargs = ConstDictVariable( + {VariableTracker.build(tx, k): v for k, v in kwargs.items()} + ) + if should_hoist(self.value): + with tx.output.tracing_context.guards_context.skip_guard_install(): + constant_args = var_args.as_python_constant() + constant_kwargs = var_kwargs.as_python_constant() + else: + constant_args = var_args.as_python_constant() + constant_kwargs = var_kwargs.as_python_constant() + opaque_obj = self.value( # pyrefly: ignore[not-callable] + *constant_args, **constant_kwargs + ) + + # Capture sources from the VT args so subgraph reuse can apply + # source replacement to resolve new ctor arg values on stamp-out. + ctor_arg_sources = tuple(getattr(a, "source", None) for a in args) + + if is_opaque_constant_type(type(opaque_obj)): + fake_script_obj = opaque_obj + else: + fake_script_obj = torch._library.fake_class_registry.maybe_to_fake_obj( + tx.output.fake_mode, opaque_obj + ) + + return CustomClassObjectVariable.create( + opaque_obj, + fake_script_obj, + (constant_args, constant_kwargs), + ctor_arg_sources=ctor_arg_sources, + tx=tx, + ) + + +class CustomClassObjectVariable(UserDefinedObjectVariable): + _fake_script_object_cache: dict[int, "CustomClassObjectVariable"] = {} + + @classmethod + def is_matching_cls(cls, user_cls: type) -> bool: + return ( + issubclass(user_cls, torch.ScriptObject) + or is_custom_class(user_cls) + or issubclass(user_cls, FakeScriptObject) + ) + + @staticmethod + def create( + proxy: Proxy, + value: Any, + ctor_args_kwargs: Any = None, + ctor_arg_sources: tuple[Source | None, ...] | None = None, + *, + tx: "InstructionTranslatorBase | None" = None, + **options: Any, + ) -> "CustomClassObjectVariable": + if isinstance(value, enum.Enum): + raise AssertionError( + f"Enum {type(value)} should use UserDefinedObjectVariable, not CustomClassObjectVariable" + ) + out = CustomClassObjectVariable( + proxy, value, ctor_args_kwargs, ctor_arg_sources=ctor_arg_sources, **options + ) + if isinstance(proxy, torch.fx.Proxy) and proxy.node.op != "placeholder": + if tx is None: + raise AssertionError( + "tx must be provided to CustomClassObjectVariable.create " + "when proxy is a real Proxy" + ) + tx.output.current_tracer.record_proxyable_vt(out) + return out + + def __init__( + self, + proxy: Proxy, + value: Any, + ctor_args_kwargs: Any = None, + source: Source | None = None, + ctor_arg_sources: tuple[Source | None, ...] | None = None, + **kwargs: Any, + ) -> None: + super().__init__(value, **kwargs) + self.proxy = proxy + if isinstance(self.proxy, torch.fx.Proxy): + self.proxy.node.meta["example_value"] = value + self.source = source + # If the OpaqueObject is sourceless, then this is + # the constant (args, kwargs) that Dynamo used to construct it. + self.ctor_args_kwargs = ctor_args_kwargs + # Sources of the constructor args, used by subgraph reuse to + # resolve new values via source replacement on stamp-out. + self.ctor_arg_sources = ctor_arg_sources + + def as_proxy(self) -> Proxy: + if not isinstance(self.proxy, torch.fx.Proxy): + # If we have a hoisted value type, then lazily lift it to be a graph + # input when as_proxy() is called. + if not is_opaque_constant_type(type(self.proxy)): + raise AssertionError( + f"Expected opaque constant type, got {type(self.proxy)}" + ) + if should_hoist(type(self.proxy)): + from torch._dynamo.symbolic_convert import InstructionTranslator + + tx = InstructionTranslator.current_tx() + # if any kwargs (synthetic_graph_input doesn't support them yet) + # not a graph break because hard error more explicit here + # (and opaque objects are really just used for compile) + if self.ctor_args_kwargs[1]: + raise RuntimeError( + "NYI: hoisted opaque objects that accept kwargs, please pass as args" + ) + hoisted_vt = tx.output.synthetic_graph_input( + type(self.proxy), + self.ctor_args_kwargs[0], + ctor_arg_sources=self.ctor_arg_sources, + ) + self.proxy = hoisted_vt.as_proxy() + + return self.proxy + + def __str__(self) -> str: + value = ( + self.value.real_obj + if isinstance(self.value, FakeScriptObject) + else self.value + ) + return f"{self.__class__.__name__}({value})" + + __repr__ = __str__ + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: "VariableTracker", + op: str, + ) -> "VariableTracker": + from .constant import ConstantVariable + from .object_protocol import object_richcompare + + # Try value-based comparison first. CustomClassObjectVariable wraps + # pybind11 objects (e.g. Placement subclasses) whose C++ operator== + # does value comparison. Falling through to object_richcompare would + # use identity, returning wrong results (e.g. Shard(0) == Shard(0) + # would be False instead of True). + try: + self_val = self.as_python_constant() + except NotImplementedError: + return object_richcompare(self, tx, other, op) + try: + other_val = other.as_python_constant() + except NotImplementedError: + return ConstantVariable.create(NotImplemented) + try: + result = getattr(type(self_val), op)(self_val, other_val) + return ConstantVariable.create(result) + except Exception: + return ConstantVariable.create(NotImplemented) + + @_raise_hard_error_if_graph_break( + "Dynamo cannot safely trace script object due to graph break." + ) + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + from torch._higher_order_ops.torchbind import call_torchbind + + from .higher_order_ops import TorchHigherOrderOperatorVariable + + real_obj = self.as_python_constant() + real_obj_type = type(real_obj) + if is_custom_class(real_obj_type): + member_type = get_member_type(real_obj_type, name) + + if member_type == MemberType.USE_REAL: + value = getattr(real_obj, name) + if inspect.ismethod(value) or isinstance( + value, types.MethodWrapperType + ): + return LambdaVariable( + lambda *args, **kwargs: self.call_method(tx, name, args, kwargs) + ) + else: + return super().tp_getattro_impl(tx, name) + + elif member_type == MemberType.INLINED: + value = getattr(real_obj, name) + if ( + inspect.ismethod(value) + or isinstance(value, types.MethodWrapperType) + ) and self.source is None: + # When we don't have a source, fall back to call_method + # which creates a proxy node. + return LambdaVariable( + lambda *args, **kwargs: self.call_method(tx, name, args, kwargs) + ) + return super().tp_getattro_impl(tx, name) + + elif is_opaque_constant_type(real_obj_type): + return super().tp_getattro_impl(tx, name) + + elif name in ("__bool__", "__len__") and not hasattr(real_obj, name): + # Special case: __bool__ and __len__ are used for truthiness checks. + # If they're not registered and the real object doesn't have them, + # raise ObservedAttributeError so the caller can fall back to + # treating the object as truthy (Python default behavior + raise_observed_exception(AttributeError, tx) + + else: + unimplemented( + gb_type="Attempted to access unregistered member on an OpaqueObject", + context=f"value={real_obj}, attr={name}", + explanation=f"Member '{name}' is not registered for this opaque object type.", + hints=[ + f"Register '{name}' with a MemberType in register_custom_class(members=...).", + ], + ) + + method = getattr(self.value, name, None) + if method is None: + unimplemented( + gb_type="FakeScriptObject missing method implementation", + context=f"value={self.value}, method={name}", + explanation=f"TorchScript object {self.value} doesn't define the method {name}.", + hints=[ + f"Ensure the method {name} is implemented in {self.value}.", + *graph_break_hints.USER_ERROR, + ], + ) + + if not callable(method): + unimplemented( + gb_type="Attempted to access non-callable attribute of TorchScript object", + context=f"value={self.value}, method={name}", + explanation="Attribute accesses of TorchScript objects to non-callable attributes are not supported.", + hints=[ + "Use method calls instead of attribute access.", + ], + ) + + if self.source is None: + raise AssertionError( + "CustomClassObjectVariable requires a source for tp_getattro_impl" + ) + return TorchHigherOrderOperatorVariable.make( + call_torchbind, + source=AttrSource(self.source, name), + script_obj_var=self, + method_name=name, + ) + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: "VariableTracker", + ) -> "VariableTracker": + # Call call_method directly on this class to avoid the __getitem__ → + # mp_subscript_impl loop in VariableTracker.call_method. + return CustomClassObjectVariable.call_method(self, tx, "__getitem__", [key], {}) + + # We only support method calls on script objects. Interpreting the bytecodes + # should go through tp_getattro_impl then call_function instead of call_method. + + # However, it's possible for call_method to be used directly e.g. for __setattr__. + @_raise_hard_error_if_graph_break( + "Dynamo cannot safely trace script object due to graph break." + ) + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: Iterable[Any], + kwargs: dict[str, Any], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + real_obj = self.as_python_constant() + real_obj_type = type(real_obj) + if is_custom_class(real_obj_type): + member_type = get_member_type(real_obj_type, name) + + if member_type == MemberType.USE_REAL: + if ( + inspect.getattr_static(real_obj_type, "__getattr__", None) + is not None + ): + unimplemented( + gb_type="Opaque object with custom __getattr__ not supported", + context=f"{real_obj_type.__name__} with custom __getattr__", + explanation="Dynamo does not support opaque objects types with custom __getattr__ methods", + hints=[], + ) + + args_const = [x.as_python_constant() for x in args] + kwargs_const = {k: v.as_python_constant() for k, v in kwargs.items()} + + method = getattr(real_obj, name) + + if name == "__setattr__": + method(*args_const, **kwargs_const) + return real_obj # pyrefly: ignore[bad-return] + + constant_val = method(*args_const, **kwargs_const) + + if any( + is_opaque_symbolic_type(type(r)) + for r in pytree.tree_leaves(constant_val) + ): + unimplemented( + gb_type="Opaque object member with method-type USE_REAL returned a reference-type opaque object.", + context=f"Opaque object type: {real_obj_type}. Method name: '{name}'", + explanation=( + "To properly guard reference-type opaque objects, " + "we must lift them as inputs to the graph. In order " + "to do this, they must all have a source, meaning they " + "come from a global value or are an attribute of an input." + ), + hints=[ + f"Register member '{name}' with MemberType.INLINED in " + f"register_custom_class({real_obj_type}, members=...).", + ], + ) + + return VariableTracker.build(tx, constant_val) + + elif member_type == MemberType.INLINED or is_opaque_constant_type( + real_obj_type + ): + proxy_args, proxy_kwargs = proxy_args_kwargs(args, kwargs) + + proxy = tx.output.create_proxy( + "call_method", + name, + args=(self.proxy, *proxy_args), + kwargs=proxy_kwargs, + ) + + return wrap_fx_proxy(tx=tx, proxy=proxy) + + else: + unimplemented( + gb_type="Attempted to access unregistered member on an OpaqueObject", + context=f"value={real_obj}, attr={name}", + explanation=f"Member '{name}' is not registered for this opaque object type.", + hints=[ + f"Register '{name}' with a MemberType in register_custom_class(members=...).", + ], + ) + + unimplemented( + gb_type="Weird method call on TorchScript object", + context=f"value={self.value}, method={name}", + explanation=( + f"This particular method call ({name}) is not supported (e.g. calling `__setattr__`). " + "Most method calls to TorchScript objects should be supported." + ), + hints=[ + "Avoid calling this method.", + ], + ) + + def as_python_constant(self) -> Any: + if isinstance(self.value, FakeScriptObject): + return self.value.real_obj + elif is_opaque_constant_type(type(self.value)): + return self.value + elif isinstance(self.value, torch.ScriptObject): + return self.value + return super().as_python_constant() + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + from ..exc import raise_type_error + + real_obj = self.as_python_constant() + try: + return hash(real_obj), False + except TypeError: + raise_type_error(tx, f"unhashable type: '{type(real_obj).__name__}'") + + def get_real_value(self) -> Any: + return self.as_python_constant() diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/sdpa.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/sdpa.py new file mode 100644 index 0000000000000000000000000000000000000000..ef515365e5b360ef5628d915bac4f4a67fc900d3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/sdpa.py @@ -0,0 +1,103 @@ +from inspect import getattr_static +from typing import Any, TYPE_CHECKING, TypeGuard + +from torch._guards import Source +from torch.backends.cuda import SDPAParams +from torch.fx.proxy import Proxy + +from ..bytecode_transformation import create_call_function +from ..exc import unimplemented +from ..source import AttrSource +from .base import VariableTracker + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + +PARAM_NAMES = [ + "query", + "key", + "value", + "attn_mask", + "dropout", + "is_causal", + "enable_gqa", +] + + +class SDPAParamsVariable(VariableTracker): + """Represents the c++ params struct for scaled dot product attention. + This is a read-only container.""" + + @staticmethod + def create( + tx: "InstructionTranslatorBase", value: Any, source: Source + ) -> VariableTracker: + from .torch import TorchInGraphFunctionVariable + + params = [ + VariableTracker.build(tx, getattr(value, p), AttrSource(source, p)) + for p in PARAM_NAMES + ] + return TorchInGraphFunctionVariable(SDPAParams).call_function(tx, params, {}) + + def __init__( + self, proxy: Proxy, param_vars: list[VariableTracker], **kwargs: Any + ) -> None: + self.proxy = proxy + self.param_vars = param_vars + super().__init__(**kwargs) + + def python_type(self) -> type: + return SDPAParams + + def reconstruct(self, codegen: "PyCodegen") -> None: + if self.source is not None: + raise AssertionError( + "SDPAParamsVariable should not have a source during reconstruct" + ) + if self.param_vars is None: + raise AssertionError("SDPAParamsVariable.param_vars must not be None") + codegen.add_push_null( + lambda: codegen.load_import_from("torch._C", "_SDPAParams") + ) + codegen.foreach(self.param_vars) + codegen.extend_output(create_call_function(len(self.param_vars), False)) + + def as_proxy(self) -> Proxy: + return self.proxy + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + import torch._C + + from .builder import wrap_fx_proxy + from .misc import GetAttrVariable + + try: + getattr_static(torch._C._SDPAParams, name) + except AttributeError: + import torch._dynamo.graph_break_hints as graph_break_hints + + unimplemented( + gb_type="unsupported torch._C._SDPAParams attribute", + context=f"name: {name}", + explanation=f"Unable to fetch attribute {name} from torch._C._SDPAParams.", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + proxy = GetAttrVariable.create_getattr_proxy(self.as_proxy(), name) + if self.source is not None: + return wrap_fx_proxy( + tx=tx, proxy=proxy, source=AttrSource(self.source, name) + ) + else: + return wrap_fx_proxy(tx=tx, proxy=proxy) + + @staticmethod + def is_sdpa_params(value: Any) -> TypeGuard["SDPAParams"]: + return value is SDPAParams diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/sets.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/sets.py new file mode 100644 index 0000000000000000000000000000000000000000..e432240fe58eb7dbe8ba7bd6280a31bf80663307 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/sets.py @@ -0,0 +1,1072 @@ +""" +Set-related variable tracking classes for PyTorch Dynamo. + +This module implements variable tracking for different types of set-like objects: +- Regular Python sets (set) +- Frozen sets (frozenset) +- Ordered sets (torch.utils._ordered_set.OrderedSet) +- Dictionary key sets (dict_keys views used as sets) + +These classes are responsible for tracking set operations during graph compilation, +maintaining proper guards for set mutations and element existence checks. + +The implementation uses a special HashableTracker wrapper to handle set elements +while preserving proper aliasing semantics. Sets are modeled internally as +dictionaries with None values. +""" + +import functools +import operator +from collections.abc import Iterable, Iterator +from typing import Any, TYPE_CHECKING + +from torch.utils._ordered_set import OrderedSet + +from .. import variables +from ..bytecode_transformation import create_call_function, create_instruction +from ..exc import raise_observed_exception, raise_type_error +from ..guards import GuardBuilder, install_guard +from ..source import is_constant_source, is_from_local_source +from ..utils import ( + _item_debug_repr, + cmp_name_to_op_mapping, + istype, + lazily_unpack, + raise_args_mismatch, + set_methods, + tracked_repr, + unpack_iterable, +) +from .base import Member, Method, ValueMutationNew, VariableTracker +from .constant import ConstantVariable +from .hashable import HashableTracker, is_hashable + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + +# [Adding a new supported class within the keys of SetVariable] +# see steps outlined for ConstDictVariable + + +def pyanyset_check(obj: VariableTracker) -> bool: + return issubclass(obj.python_type(), (set, frozenset)) + + +def pyset_check(obj: VariableTracker) -> bool: + # ref: https://github.com/python/cpython/blob/v3.13.0/Include/setobject.h#L36-L38 + return issubclass(obj.python_type(), set) + + +def set_copy(obj: VariableTracker) -> VariableTracker: + """Mirrors CPython's internal `set_copy` (Objects/setobject.c). + + Always allocates a fresh set/frozenset with a shallow-copied items dict. + Distinct from the user-visible `.copy()` method, which preserves identity + for exact frozenset (`frozenset_copy`). Use this for binary-op scratch + storage so mutations don't bleed into the input. + """ + base = obj._base_vt if isinstance(obj, variables.UserDefinedSetVariable) else obj + if base is None: + raise AssertionError("_base_vt must not be None") + return base.clone( + items=base.items.copy(), # type: ignore[missing-attribute] + mutation_type=ValueMutationNew(), + source=None, + ) + + +class SetVariable(VariableTracker): + """Represents a Python set during symbolic execution.""" + + # PySet_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/setobject.c#L2436 + _cpython_type = set + + CONTAINS_GUARD = GuardBuilder.SET_CONTAINS + NOT_CONTAINS_GUARD = GuardBuilder.SET_NOT_CONTAINS + + def __init__( + self, + items: Iterable[VariableTracker | HashableTracker], + **kwargs: Any, + ) -> None: + # .clone() passes these arguments in kwargs but they're recreated below + if "original_items" in kwargs: + kwargs.pop("original_items") + if "should_reconstruct_all" in kwargs: + kwargs.pop("should_reconstruct_all") + + super().__init__(**kwargs) + + # Items can be either VariableTrackers or HashableTrackers (from set ops). + # For VariableTrackers, realize them to ensure aliasing guards are installed + # when the same object appears multiple times. + hashable_items = [] + for item in items: + if isinstance(item, HashableTracker): + # Already a HashableTracker from a set operation + hashable_items.append(item) + else: + # VariableTracker - realize to install guards, then wrap + # pyrefly: ignore [bad-argument-type] + hashable_items.append(HashableTracker(item.realize())) + # Internal representation as dict allows for simple integration with + # OrderedSet, notably polyfills. Using set moves complexity to OrderedSet + self.items = dict.fromkeys(hashable_items, SetVariable._default_value()) + self.should_reconstruct_all = ( + not is_from_local_source(self.source) if self.source else True + ) + self.original_items = dict.fromkeys( + hashable_items, SetVariable._default_value() + ) + + def debug_repr(self) -> str: + if not self.items: + return "set()" + else: + items: list[str] = [] + for v in self.items: + vt = v.vt if isinstance(v, HashableTracker) else v + val_str = _item_debug_repr(vt) + items.append(val_str) + return "{" + ", ".join(items) + "}" + + @property + def set_items(self) -> set["HashableTracker"]: + return set(self.items.keys()) + + @staticmethod + def _default_value() -> VariableTracker: + # Variable to fill in the keys of the dictionary + return ConstantVariable.create(None) + + def as_proxy(self) -> Any: + return {k.vt.as_proxy() for k in self.set_items} + + def python_type(self) -> type: + return set + + def is_python_constant(self) -> bool: + # Avoid the base implementation, which probes as_python_constant() and + # thus rebuilds a real set, re-hashing the elements (wrong for elements + # with a side-effecting __hash__). Check element constness directly. + return all(k.vt.is_python_constant() for k in self.set_items) + + def as_python_constant(self) -> Any: + return {k.vt.as_python_constant() for k in self.set_items} + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + # https://github.com/python/cpython/blob/3.13/Objects/setobject.c#L763-L822 + if not self.items: + return VariableTracker.build(tx, f"{self.python_type_name()}()") + items = ", ".join(tracked_repr(tx, item.vt) for item in self.set_items) + return VariableTracker.build(tx, "{" + items + "}") + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.foreach([x.vt for x in self.set_items]) + codegen.append_output(create_instruction("BUILD_SET", arg=len(self.set_items))) + + def __contains__(self, vt: VariableTracker) -> bool: + if not isinstance(vt, VariableTracker): + raise AssertionError(f"Expected VariableTracker, got {type(vt)}") + # Use is_hashable as a side-effect-free pre-check. We can't catch + # ObservedTypeError from HashableTracker because it modifies + # tx.exn_vt_stack as a side effect. + if not is_hashable(vt): + return False + key = HashableTracker(vt) + return key in self.items + + def has_new_items(self) -> bool: + return self.should_reconstruct_all or any( + # pyrefly: ignore [bad-argument-type] + self.is_new_item(self.original_items.get(key.vt), value) + for key, value in self.items.items() + ) + + def is_new_item( + self, value: VariableTracker | None, other: VariableTracker + ) -> bool: + if value and value.is_realized() and other.is_realized(): + return id(value.realize()) != id(other.realize()) + return id(value) != id(other) + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase" + ) -> list[VariableTracker]: + return [x.vt for x in self.items] + + def clone(self, **kwargs: Any) -> VariableTracker: + from torch._dynamo.variables.base import AttributeMutationNew, ValueMutationNew + + if isinstance( + kwargs.get("mutation_type"), (ValueMutationNew, AttributeMutationNew) + ): + kwargs["source"] = None + return super().clone(**kwargs) + + def is_hashable(self) -> bool: + return False + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + from ..exc import raise_type_error + + raise_type_error(tx, f"unhashable type: '{self.python_type_name()}'") + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + return VariableTracker.build(tx, hasattr(self.python_type(), name)) + + def install_set_contains_guard( + self, tx: "InstructionTranslatorBase", args: list[VariableTracker] + ) -> None: + if not self.source: + return + + if tx.output.side_effects.is_modified(self): + return + + contains = args[0] in self + if args[0].source is None and args[0].is_python_constant(): + guard_fn = ( + type(self).CONTAINS_GUARD if contains else type(self).NOT_CONTAINS_GUARD + ) + install_guard( + self.make_guard( + functools.partial( + guard_fn, + key=args[0].as_python_constant(), + ) + ) + ) + + def _fast_set_method( + self, + tx: "InstructionTranslatorBase", + fn: Any, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + try: + res = fn( + *[x.as_python_constant() for x in [self, *args]], + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ) + except Exception as exc: + raise_observed_exception(type(exc), tx, args=list(exc.args)) + return VariableTracker.build(tx, res) + + def _iter_operand_keys( + self, tx: "InstructionTranslatorBase", other: VariableTracker + ) -> "Iterator[HashableTracker]": + # Lazily yield HashableTracker keys for a set-operation operand, one + # element at a time so callers that short-circuit (isdisjoint) observe + # the same generator side effects as CPython. A set or dict operand's + # keys are reused directly (no re-hashing), mirroring CPython's + # set_update_internal fast path for set/frozenset/dict operands. + # HashableTracker raises ObservedTypeError for an unhashable element, + # matching CPython's hash-at-insert behavior. + from .dicts import ConstDictVariable + + if isinstance(other, (SetVariable, ConstDictVariable)): + yield from other.items.keys() + return + + yield from (HashableTracker(item) for item in lazily_unpack(tx, other)) + + def _operand_keys( + self, tx: "InstructionTranslatorBase", other: VariableTracker + ) -> list[HashableTracker]: + # Eager variant: unpack_iterable takes the fast unpack_var_sequence + # path for builtin iterables instead of the per-element iterator + # protocol. + from .dicts import ConstDictVariable + + if isinstance(other, (SetVariable, ConstDictVariable)): + return list(other.items.keys()) + return [HashableTracker(x) for x in unpack_iterable(tx, other)] + + def _new_set(self, items: "Iterable[HashableTracker]") -> "SetVariable": + # Build a fresh set of the same concrete type (set / frozenset / + # OrderedSet). list() preserves insertion order, which matters for + # OrderedSet. + return type(self)(list(items), mutation_type=ValueMutationNew()) + + def sq_contains_impl( + self, tx: "InstructionTranslatorBase", item: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/setobject.c#L2131-L2149 + if not is_hashable(item): + # Mirror CPython's set_contains: if hashing fails with TypeError due to + # an unhashable set, coerce the key to frozenset and retry. + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/setobject.c#L2151-L2159 + if not pyset_check(item): + raise_type_error(tx, f"unhashable type: '{item.python_type_name()}'") + # CPython NOTE: + # Note that 'key' could be a set() or frozenset() object. Unlike most + # container types, set allows membership testing with a set key, even + # though it is not hashable. + item = FrozensetVariable(item.items) # type: ignore[missing-attribute] + self.install_set_contains_guard(tx, [item]) + contains = item in self + return VariableTracker.build(tx, contains) + + def _try_fast_set_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> "VariableTracker | None": + from ..utils import check_constant_args + from .dicts import ConstDictVariable + + # Constant, exact-builtin fast path: materialize and call the real + # method. Set/dict operands take the slow VT path below so their keys + # are not re-hashed (CPython's do-not-rehash-dict-keys fast path); + # OrderedSet is excluded because as_python_constant() loses insertion + # order (it routes through the unordered set_items). + if ( + not any(isinstance(a, (SetVariable, ConstDictVariable)) for a in args) + and check_constant_args(args, kwargs) + and self.python_type() in (set, frozenset) + ): + py_type = self.python_type() + return self._fast_set_method(tx, getattr(py_type, name), args, kwargs) + return None + + def add( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Convert add to __setitem__ with None value + tx.output.side_effects.mutation(self) + self.items[HashableTracker(args[0])] = SetVariable._default_value() + return ConstantVariable.create(None) + + def pop( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Choose an item at random and pop it + try: + result: VariableTracker = self.set_items.pop().vt # type: ignore[assignment] + except KeyError as e: + raise_observed_exception(KeyError, tx, args=list(e.args)) + self.should_reconstruct_all = True + tx.output.side_effects.mutation(self) + self.items.pop(HashableTracker(result)) + return result + + def isdisjoint( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + fast = self._try_fast_set_method(tx, "isdisjoint", args, kwargs) + if fast is not None: + return fast + for key in self._iter_operand_keys(tx, args[0]): + if key in self.items: + return ConstantVariable.create(False) + return ConstantVariable.create(True) + + def intersection( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + fast = self._try_fast_set_method(tx, "intersection", args, kwargs) + if fast is not None: + return fast + out_items = dict(self.items) + for other in args: + other_keys = set(self._operand_keys(tx, other)) + out_items = {k: v for k, v in out_items.items() if k in other_keys} + return self._new_set(out_items) + + def intersection_update( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + kept = dict(self.items) + for other in args: + other_keys = set(self._operand_keys(tx, other)) + kept = {k: v for k, v in kept.items() if k in other_keys} + tx.output.side_effects.mutation(self) + self.should_reconstruct_all = True + self.items.clear() + self.items.update(kept) + return ConstantVariable.create(None) + + def union( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + fast = self._try_fast_set_method(tx, "union", args, kwargs) + if fast is not None: + return fast + out_items = dict(self.items) + for other in args: + for key in self._operand_keys(tx, other): + out_items.setdefault(key, SetVariable._default_value()) + return self._new_set(out_items) + + def difference( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + fast = self._try_fast_set_method(tx, "difference", args, kwargs) + if fast is not None: + return fast + out_items = dict(self.items) + for other in args: + for key in self._operand_keys(tx, other): + out_items.pop(key, None) + return self._new_set(out_items) + + def difference_update( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + tx.output.side_effects.mutation(self) + self.should_reconstruct_all = True + for other in args: + for key in self._operand_keys(tx, other): + self.items.pop(key, None) + return ConstantVariable.create(None) + + def symmetric_difference( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + fast = self._try_fast_set_method(tx, "symmetric_difference", args, kwargs) + if fast is not None: + return fast + other = dict.fromkeys( + self._operand_keys(tx, args[0]), SetVariable._default_value() + ) + out_items = {k: v for k, v in self.items.items() if k not in other} + out_items.update({k: v for k, v in other.items() if k not in self.items}) + return self._new_set(out_items) + + def symmetric_difference_update( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + other = dict.fromkeys( + self._operand_keys(tx, args[0]), SetVariable._default_value() + ) + new_items = {k: v for k, v in self.items.items() if k not in other} + new_items.update({k: v for k, v in other.items() if k not in self.items}) + tx.output.side_effects.mutation(self) + self.should_reconstruct_all = True + self.items.clear() + self.items.update(new_items) + return ConstantVariable.create(None) + + def update( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker | None: + if not self.is_mutable(): + return None + tx.output.side_effects.mutation(self) + for other in args: + for key in self._operand_keys(tx, other): + self.items.setdefault(key, SetVariable._default_value()) + return ConstantVariable.create(None) + + def remove( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if not self.sq_contains_impl(tx, args[0]).as_python_constant(): + raise_observed_exception(KeyError, tx, args=[args[0]]) + self.should_reconstruct_all = True + tx.output.side_effects.mutation(self) + # sq_contains validated/normalized args[0]; a set key was coerced to + # a frozenset, so pop that same normalized key. + key = args[0] if is_hashable(args[0]) else FrozensetVariable(args[0].items) # type: ignore[missing-attribute] + self.items.pop(HashableTracker(key)) + return ConstantVariable.create(None) + + def discard( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if self.sq_contains_impl(tx, args[0]).as_python_constant(): + self.should_reconstruct_all = True + tx.output.side_effects.mutation(self) + # sq_contains validated/normalized args[0]; a set key was coerced + # to a frozenset, so pop that same normalized key. + key = ( + args[0] if is_hashable(args[0]) else FrozensetVariable(args[0].items) # type: ignore[missing-attribute] + ) + self.items.pop(HashableTracker(key)) + return ConstantVariable.create(None) + + def _ordering_test(self, tx, args, op): + from .builder import SourcelessBuilder + + other = args[0].realize() + if not istype(other, SetVariable): + other = SourcelessBuilder.create(tx, set).call_function(tx, [other], {}) + return SourcelessBuilder.create(tx, op).call_function(tx, [self, other], {}) + + def issubset( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self._ordering_test(tx, args, operator.le) + + def issuperset( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return self._ordering_test(tx, args, operator.ge) + + def copy( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return set_copy(self) + + def clear( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + self.should_reconstruct_all = True + tx.output.side_effects.mutation(self) + self.items.clear() + return ConstantVariable.create(None) + + tp_methods = { + "add": Method(add), + "pop": Method(pop), + "isdisjoint": Method(isdisjoint), + "intersection": Method(intersection), + "intersection_update": Method(intersection_update), + "union": Method(union), + "difference": Method(difference), + "difference_update": Method(difference_update), + "symmetric_difference": Method(symmetric_difference), + "symmetric_difference_update": Method(symmetric_difference_update), + "update": Method(update), + "remove": Method(remove), + "discard": Method(discard), + "issubset": Method(issubset), + "issuperset": Method(issuperset), + "copy": Method(copy), + "clear": Method(clear), + } + + def getitem_const( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + raise RuntimeError("Illegal to getitem on a set") + + def tp_init_impl( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import SourcelessBuilder + + temp_set_vt = SourcelessBuilder.create(tx, set).call_set(tx, *args, **kwargs) + tx.output.side_effects.mutation(self) + self.items.clear() + self.items.update(temp_set_vt.items) # type: ignore[attr-defined] + return ConstantVariable.create(None) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + from .iter import SetIterator + + if self.source and not is_constant_source(self.source): + tx.output.guard_on_key_order.add(self.source) + return SetIterator(self.items) + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/setobject.c#L1318-L1338 + self_, other_ = (other, self) if reverse else (self, other) + + if not pyanyset_check(self_) or not pyanyset_check(other_): + return ConstantVariable.create(NotImplemented) + + result = set_copy(self_) + if self_ is other_: + return result + result.items.update(other_.items) # type: ignore[missing-attribute] + return result + + def nb_inplace_or_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/setobject.c#L1340-L1350 + if not pyanyset_check(other): + return ConstantVariable.create(NotImplemented) + + tx.output.side_effects.mutation(self) + self.items.update(other.items) # type: ignore[missing-attribute] + return self + + def nb_subtract_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/setobject.c#L1801-L1812 + self_, other_ = (other, self) if reverse else (self, other) + + if not pyanyset_check(self_) or not pyanyset_check(other_): + return ConstantVariable.create(NotImplemented) + + result = set_copy(self_) + for k in list(other_.items.keys()): # type: ignore[missing-attribute] + result.items.pop(k, None) # type: ignore[missing-attribute] + return result + + def nb_inplace_subtract_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/setobject.c#L1814-L1828 + if not pyanyset_check(other): + return ConstantVariable.create(NotImplemented) + + tx.output.side_effects.mutation(self) + for k in list(other.items.keys()): # type: ignore[missing-attribute] + self.items.pop(k, None) + return self + + def nb_and_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/setobject.c#L1506-L1518 (set_and) + self_, other_ = (other, self) if reverse else (self, other) + + if not pyanyset_check(self_) or not pyanyset_check(other_): + return ConstantVariable.create(NotImplemented) + + return self_.call_method(tx, "intersection", [other_], {}) + + def nb_inplace_and_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/setobject.c#L1520-L1536 (set_iand) + if not pyanyset_check(other): + return ConstantVariable.create(NotImplemented) + + self.call_method(tx, "intersection_update", [other], {}) + return self + + def nb_xor_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/setobject.c#L1984-L1990 (set_xor) + self_, other_ = (other, self) if reverse else (self, other) + + if not pyanyset_check(self_) or not pyanyset_check(other_): + return ConstantVariable.create(NotImplemented) + + return self_.call_method(tx, "symmetric_difference", [other_], {}) + + def nb_inplace_xor_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/setobject.c#L1992-L2004 (set_ixor) + if not pyanyset_check(other): + return ConstantVariable.create(NotImplemented) + + self.call_method(tx, "symmetric_difference_update", [other], {}) + return self + + def sq_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return VariableTracker.build(tx, len(self.set_items)) + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + """set_richcompare: subset/superset comparisons for all 6 ops. + + https://github.com/python/cpython/blob/e76aa128fe/Objects/setobject.c#L2097 + CPython uses PyAnySet_Check: only accepts set/frozenset (not dict views). + """ + if not isinstance(other, SetVariable): + try: + other_type = other.python_type() + except NotImplementedError: + return ConstantVariable.create(NotImplemented) + if not issubclass(other_type, (set, frozenset)): + return ConstantVariable.create(NotImplemented) + + # Accessing set_items directly is correct: CPython's set_richcompare + # operates on the internal C struct (PySet_GET_SIZE, set_next, + # set_contains_entry) -- it never calls __len__ or __contains__. + # https://github.com/python/cpython/blob/e76aa128fe/Objects/setobject.c#L2093-L2130 + self_items = self.set_items + other_items = other.set_items # type: ignore[attr-defined] + if op == "__eq__": + # len check + issubset: same length and subset implies equality. + if len(self_items) != len(other_items): + return ConstantVariable.create(False) + return VariableTracker.build(tx, self_items <= other_items) + elif op == "__ne__": + if len(self_items) != len(other_items): + return ConstantVariable.create(True) + return VariableTracker.build(tx, not (self_items <= other_items)) + else: + return VariableTracker.build( + tx, + cmp_name_to_op_mapping[op](self_items, other_items), + ) + + +class OrderedSetClassVariable(VariableTracker): + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + + def as_python_constant(self) -> type[OrderedSet[Any]]: + return OrderedSet + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if name == "__new__": + if len(args) != 2 or kwargs: + raise_args_mismatch( + tx, + name, + "OrderedSet.__new__ only accepts one arg" + f"{len(args)} args and {len(kwargs)} kwargs", + ) + + return variables.OrderedSetVariable([], mutation_type=ValueMutationNew()) + + resolved_fn = getattr(set, name) + if resolved_fn in set_methods and isinstance(args[0], variables.SetVariable): + return args[0].call_method(tx, name, args[1:], kwargs) + + return super().call_method(tx, name, args, kwargs) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> "OrderedSetVariable": + if len(args) > 1 or kwargs: + raise_args_mismatch( + tx, + "OrderedSet", + "OrderedSet only accepts one arg" + f"{len(args)} args and {len(kwargs)} kwargs", + ) + + if len(args) == 0: + # pyrefly: ignore [implicit-any] + items = [] + else: + items = unpack_iterable(tx, args[0]) + return variables.OrderedSetVariable(items, mutation_type=ValueMutationNew()) + + +class OrderedSetVariable(SetVariable): + _cpython_type = OrderedSet + + def method_flags_type(self) -> type: + # OrderedSet is pure-Python (no C ml_flags); its named methods mirror + # set's arities, so derive MethodFlags from set to enforce them. + return set + + def _get_internal_dict(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # OrderedSet is backed by a dict (self._dict). Expose it so inlined + # OrderedSet methods (e.g. __contains__ -> `elem in self._dict`) trace + # natively instead of graph-breaking on an unmodeled attribute. + from .dicts import ConstDictVariable + + return ConstDictVariable(self.items, mutation_type=ValueMutationNew()) # type: ignore[bad-argument-type] + + tp_members = {"_dict": Member(_get_internal_dict, None)} + + def debug_repr(self) -> str: + if not self.items: + return "OrderedSet([])" + else: + items: list[str] = [] + for k in self.items: + key_str = _item_debug_repr(k.vt) + items.append(key_str) + return "OrderedSet([" + ", ".join(items) + "])" + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + items = ", ".join(tracked_repr(tx, item.vt) for item in self.set_items) + return VariableTracker.build(tx, f"{self.python_type_name()}([{items}])") + + def as_python_constant(self) -> OrderedSet[Any]: + return OrderedSet([k.vt.as_python_constant() for k in self.set_items]) + + def python_type(self) -> type[OrderedSet[Any]]: + return OrderedSet + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from("torch.utils._ordered_set", "OrderedSet") + ) + codegen.foreach([x.vt for x in self.set_items]) + codegen.append_output(create_instruction("BUILD_LIST", arg=len(self.set_items))) + codegen.extend_output(create_call_function(1, False)) + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # OrderedSet does not inherit from Python set, so SetVariable.nb_or_impl + # won't work due to the PyAnySet_Check + return super().call_method(tx, "union", [other], {}) + + def nb_and_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # OrderedSet does not inherit from Python set, so SetVariable.nb_and_impl + # won't work due to the PyAnySet_Check + return super().call_method(tx, "intersection", [other], {}) + + def nb_xor_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # OrderedSet does not inherit from Python set, so SetVariable.nb_xor_impl + # won't work due to the PyAnySet_Check + return super().call_method(tx, "symmetric_difference", [other], {}) + + def nb_subtract_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + self_, other_ = (other, self) if reverse else (self, other) + return self_.call_method(tx, "difference", [other_], {}) + + def nb_inplace_subtract_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker + ) -> VariableTracker: + tx.output.side_effects.mutation(self) + self.call_method(tx, "difference_update", [other], {}) + return self + + +class FrozensetVariable(SetVariable): + # PyFrozenSet_Type: https://github.com/python/cpython/blob/v3.13.0/Objects/setobject.c#L2526 + _cpython_type = frozenset + + nb_inplace_subtract_impl = None # type: ignore[bad-override] + + def debug_repr(self) -> str: + if not self.items: + return "frozenset()" + else: + items: list[str] = [] + for k in self.items: + key_str = _item_debug_repr(k.vt) + items.append(key_str) + return "frozenset({" + ", ".join(items) + "})" + + @property + def set_items(self) -> set["HashableTracker"]: + return set(self.items.keys()) + + def python_type(self) -> type: + return frozenset + + def as_python_constant(self) -> Any: + return frozenset({k.vt.as_python_constant() for k in self.set_items}) + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + # https://github.com/python/cpython/blob/3.13/Objects/setobject.c#L763-L822 + if not self.items: + return VariableTracker.build(tx, f"{self.python_type_name()}()") + items = ", ".join(tracked_repr(tx, item.vt) for item in self.set_items) + return VariableTracker.build(tx, f"{self.python_type_name()}({{{items}}})") + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.extend_output( + [ + codegen.create_load_global("frozenset"), + ] + ) + ) + codegen.foreach([x.vt for x in self.set_items]) + codegen.extend_output( + [ + create_instruction("BUILD_LIST", arg=len(self.set_items)), + *create_call_function(1, False), + ] + ) + + def copy( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if type(self) is FrozensetVariable: + return self + return SetVariable.copy(self, tx, args, kwargs) + + def difference( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + r = SetVariable.difference(self, tx, args, kwargs) + return FrozensetVariable(r.items) # type: ignore[attr-defined] + + def intersection( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + r = SetVariable.intersection(self, tx, args, kwargs) + return FrozensetVariable(r.items) # type: ignore[attr-defined] + + def symmetric_difference( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + r = SetVariable.symmetric_difference(self, tx, args, kwargs) + return FrozensetVariable(r.items) # type: ignore[attr-defined] + + tp_methods = { + "copy": Method(copy), + "difference": Method(difference), + "intersection": Method(intersection), + "symmetric_difference": Method(symmetric_difference), + } + + def tp_init_impl( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # frozenset is immutable. Calling __init__ again shouldn't have any effect. + return ConstantVariable.create(None) + + def is_hashable(self) -> bool: + return True + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # Overrides SetVariable.hash_impl (which raises TypeError for mutable sets). + # CPython frozenset_hash: https://github.com/python/cpython/blob/e76aa128fe/Objects/setobject.c#L769 + from .hashable import RawHash + from .object_protocol import generic_hash_impl + + if self.is_python_constant(): + return hash(self.as_python_constant()), False + is_fake = False + raw_hashes = [] + for item in self.set_items: + h, fake = generic_hash_impl(tx, item.vt) + is_fake = is_fake or fake + raw_hashes.append(RawHash(h)) + return hash(frozenset(raw_hashes)), is_fake + + +class DictKeySetVariable(SetVariable): + def debug_repr(self) -> str: + if not self.items: + return "dict_keys([])" + else: + items: list[str] = [] + for k in self.items: + key_str = _item_debug_repr(k.vt) + items.append(key_str) + return "dict_keys([" + ", ".join(items) + "])" + + def install_set_contains_guard( + self, tx: "InstructionTranslatorBase", args: list[VariableTracker] + ) -> None: + # Already EQUALS_MATCH guarded + pass + + @property + def set_items(self) -> Any: + return self.items + + def python_type(self) -> type: + from ..utils import dict_keys + + return dict_keys + + def as_python_constant(self) -> Any: + return dict.fromkeys( + {k.vt.as_python_constant() for k in self.set_items}, None + ).keys() diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/streams.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/streams.py new file mode 100644 index 0000000000000000000000000000000000000000..f445d050e2f370c39ae98c7d7fb7bc34d5223288 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/streams.py @@ -0,0 +1,842 @@ +import collections +from collections.abc import Callable +from typing import Any, Optional + +import torch +from torch._dynamo.variables.dicts import ConstDictVariable +from torch._dynamo.variables.lists import TupleVariable +from torch.fx import has_side_effect, Proxy + +from .. import graph_break_hints +from ..bytecode_transformation import create_call_function +from ..exc import TYPE_CHECKING, unimplemented +from ..graph_bytecode_inputs import ( + CURRENT_STREAM_INDEX, + get_external_object_by_index, + register_graph_created_object, + register_user_object, + reset_user_object_tracking, +) +from ..source import CurrentStreamSource +from .base import GetSet, Method, VariableTracker +from .constant import ConstantVariable +from .ctx_manager import FxTracebackAnnotateVariable +from .lazy import LazyVariableTracker + + +if TYPE_CHECKING: + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + from ..codegen import PyCodegen + +from torch._library.custom_ops import custom_op + + +Tensor = torch.Tensor + + +def new_event(*args: Any, **kwargs: Any) -> int: + event = torch.Event(*args, **kwargs) + return register_graph_created_object( + event, + EventVariable.make_construct_in_graph_event_fn( + TupleVariable([]), ConstDictVariable({}) + ), + ) + + +def new_stream(*args: tuple[Any], **kwargs: Any) -> int: + stream = torch.Stream(*args, **kwargs) # type: ignore[no-matching-overload,call-overload] + return register_graph_created_object( + stream, + StreamVariable.make_construct_in_graph_stream_fn( + TupleVariable([]), ConstDictVariable({}) + ), + ) + + +def _codegen_current_stream(device: torch.device, cg: "PyCodegen") -> None: + cg.add_push_null( + lambda: cg.load_import_from( + torch._dynamo.graph_bytecode_inputs.__name__, # type: ignore[implicit-imports] + "stash_graph_created_object", + ) + ) + cg(CurrentStreamSource(device)) + cg.extend_output(create_call_function(1, False)) + + +def get_current_stream(device: torch.device) -> int: + stream = torch.accelerator.current_stream(device) + return register_graph_created_object( + stream, lambda _, cg: _codegen_current_stream(device, cg) + ) + + +def _get_stream_by_index(index: int) -> torch.Stream: + stream = get_external_object_by_index(index) + if not isinstance(stream, torch.Stream): + raise AssertionError( + f"Fork/join stream expected a stream object at index {index}" + ) + return stream + + +def _get_event_by_index(index: int) -> torch.Event: + event = get_external_object_by_index(index) + if not isinstance(event, torch.Event): + raise AssertionError( + f"Record/wait event expected an event object at index {index}" + ) + return event + + +@custom_op("streams::fork", mutates_args=()) +def fork_stream( + from_index: int, # kept to make stream transitions clearer + to_index: int, +) -> None: + torch.accelerator.set_stream(_get_stream_by_index(to_index)) + + +@fork_stream.register_fake +def _( + from_index: int, # kept to make stream transitions clearer + to_index: int, +) -> None: + pass + + +has_side_effect(torch.ops.streams.fork.default) + + +@custom_op("streams::join", mutates_args=()) +def join_stream(from_index: int, to_index: int) -> None: + torch.accelerator.set_stream(_get_stream_by_index(to_index)) + + +@join_stream.register_fake +def _( + from_index: int, + to_index: int, +) -> None: + pass + + +has_side_effect(torch.ops.streams.join.default) + + +@custom_op("streams::record_event", mutates_args=()) +def record_event(event_index: int, stream_index: int) -> None: + event = _get_event_by_index(event_index) + stream = _get_stream_by_index(stream_index) + event.record(stream) + + +@record_event.register_fake +def _( + event_index: int, + stream_index: int, +) -> None: + pass + + +has_side_effect(torch.ops.streams.record_event.default) + + +@custom_op("streams::wait_event", mutates_args=()) +def wait_event(event_index: int, stream_index: int) -> None: + event = _get_event_by_index(event_index) + stream = _get_stream_by_index(stream_index) + event.wait(stream) + + +@wait_event.register_fake +def _( + event_index: int, + stream_index: int, +) -> None: + pass + + +has_side_effect(torch.ops.streams.wait_event.default) + + +@custom_op("streams::synchronize_event", mutates_args=()) +def synchronize_event(event_index: int) -> None: + event = _get_event_by_index(event_index) + event.synchronize() + + +@synchronize_event.register_fake +def _(event_index: int) -> None: + pass + + +has_side_effect(torch.ops.streams.synchronize_event.default) + + +@custom_op("streams::synchronize_device", mutates_args=()) +def synchronize_device(device_type: str, device_index: int) -> None: + torch.accelerator.synchronize(torch.device(device_type, device_index)) + + +@synchronize_device.register_fake +def _(device_type: str, device_index: int) -> None: + pass + + +has_side_effect(torch.ops.streams.synchronize_device.default) + + +@custom_op("streams::synchronize_stream", mutates_args=()) +def synchronize_stream(stream_index: int) -> None: + stream = _get_stream_by_index(stream_index) + stream.synchronize() + + +@synchronize_stream.register_fake +def _(stream_index: int) -> None: + pass + + +has_side_effect(torch.ops.streams.synchronize_stream.default) + + +@custom_op("streams::wait_stream", mutates_args=()) +def wait_stream(waiting_stream_index: int, waited_on_stream_index: int) -> None: + waiting = _get_stream_by_index(waiting_stream_index) + waited_on = _get_stream_by_index(waited_on_stream_index) + waiting.wait_stream(waited_on) + + +@wait_stream.register_fake +def _( + event_index: int, + stream_index: int, +) -> None: + pass + + +has_side_effect(torch.ops.streams.wait_stream.default) + + +@custom_op("streams::sync_dealloc", mutates_args=()) +def sync_dealloc( + wait_event_index: int, src_stream_index: int, to_dealloc: torch.Tensor +) -> None: + """An op which waits on an event and moves the last usage of to_dealloc + after the wait, so that after the sync occurs, the deallocation or + subsequent reuse of the tensor's memory will be guaranteed to happen + after a side stream is finished using it. + See https://docs.pytorch.org/docs/stable/generated/torch.Tensor.record_stream.html#torch.Tensor.record_stream + for more details""" + torch.ops.streams.wait_event.default(wait_event_index, src_stream_index) + + +@sync_dealloc.register_fake +def _( + wait_event_index: int, + src_stream_index: int, + to_dealloc: torch.Tensor, +) -> None: + pass + + +has_side_effect(torch.ops.streams.sync_dealloc.default) + + +@custom_op("streams::record_stream", mutates_args=()) +def record_stream(tensor: torch.Tensor, stream_index: int) -> None: + tensor.record_stream(_get_stream_by_index(stream_index)) + + +@record_stream.register_fake +def _( + tensor: torch.Tensor, + stream_index: int, +) -> None: + pass + + +has_side_effect(torch.ops.streams.record_stream.default) + + +class SymbolicStreamState: + """Track the currently entered stream if any""" + + def __init__(self) -> None: + from ..source import CurrentStreamSource + + cur_stack: list[StreamVariable] = [] + if torch.accelerator.is_available(): + # Reset the registry so the current stream is guaranteed index 0. + reset_user_object_tracking() + stream = torch.accelerator.current_stream() + source = CurrentStreamSource(stream.device) + # Register the current stream so it gets index 0 (registry is + # fresh at tracing start). The inductor wrapper updates this + # entry at runtime so cudagraph capture uses the capture stream + # instead of this stale trace-time stream. + index = register_user_object(stream, source) + if index != CURRENT_STREAM_INDEX: + raise AssertionError( + f"Current stream must be registered at index {CURRENT_STREAM_INDEX}, " + f"got {index}" + ) + stream_var = LazyVariableTracker.create(stream, source=source) + # Set user_object_index as an instance attribute so accessing it + # does NOT trigger LazyVariableTracker realization. + stream_var.user_object_index = index # type: ignore[union-attr] + cur_stack = [stream_var] # type: ignore[list-item] + + self.cur_stream_stack: collections.deque[StreamVariable] = collections.deque( + cur_stack + ) + + def enter_stream(self, stream: "StreamVariable") -> None: + self.cur_stream_stack.append(stream) + + def exit_stream(self) -> None: + self.cur_stream_stack.pop() + + def cur_stream(self, device: torch.device | None = None) -> "StreamVariable": + if device is not None: + for stream in reversed(self.cur_stream_stack): + if stream.device == device: + return stream + + return self.cur_stream_stack[-1] + + def in_stream_context(self) -> bool: + return len(self.cur_stream_stack) > 0 + + def cur_stream_id(self) -> int: + """Get a Python object id for the current stream without realizing lazy variables.""" + stream = self.cur_stream_stack[-1] + if isinstance(stream, LazyVariableTracker) and not stream.is_realized(): + return id(stream.peek_value()) + return id(stream.value) + + +class StreamContextVariable(FxTracebackAnnotateVariable): + """This represents torch.cuda.StreamContext""" + + @staticmethod + def create( + tx: "InstructionTranslatorBase", + stream_to_enter: "StreamVariable", + **kwargs: dict[str, Any], + ) -> "StreamContextVariable": + return StreamContextVariable( + stream_to_enter, + **kwargs, + ) + + def __init__(self, stream: Optional["StreamVariable"], **kwargs: Any) -> None: + self.stream = stream + super().__init__( + annotation={"stream": self.get_stream().user_object_index}, + initial_values=None, + **kwargs, + ) + + def enter( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + # to stream, from stream is the order of the arguments + # we are entering the target, and leaving the initial stream + tx.symbolic_stream_state.enter_stream(self.get_stream()) + return super().enter(tx) + + def exit( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> VariableTracker: + # to stream, from stream is the order of the arguments + # we are leaving the target, and entering the initial stream + tx.symbolic_stream_state.exit_stream() + return super().exit(tx, *args) + + def python_type(self) -> type: + return torch.cuda.StreamContext + + def supports_graph_breaks(self) -> bool: + return True + + def get_stream(self) -> "StreamVariable": + if not self.stream: + raise AssertionError("Stream context should have a separate stream") + return self.stream + + +class StreamVariable(StreamContextVariable): + """Represents the device-agnostic torch.Stream class""" + + _cpython_type: type = torch.Stream # pyrefly: ignore [bad-override] + # Subclasses set this to the device-specific handle attribute name + # (e.g. "cuda_stream", "sycl_queue"). None means no special handling. + _device_handle_attr: str | None = None + + def __init__( + self, + proxy: Proxy, + value: torch.Stream, + user_object_index: int | None = None, + **kwargs: Any, + ) -> None: + # Index into the user object table + # used to pass arbitrary objects to the graph + if proxy is not None and "example_value" in proxy.node.meta: + if proxy.node.meta["example_value"] != value: + raise AssertionError( + f"proxy example_value {proxy.node.meta['example_value']} != {value}" + ) + + self.proxy = proxy + self.value = value + self.device = value.device + + self.user_object_index = user_object_index + super().__init__(None, **kwargs) + + def python_type(self) -> type: + return self._cpython_type + + def _stream_device_handle_get( + self: "StreamVariable", tx: "InstructionTranslatorBase" + ) -> "VariableTracker | None": + from ..guards import GuardBuilder, install_guard + + name = self._device_handle_attr + if name is None: + raise AssertionError( + "StreamVariable subclass must define _device_handle_attr" + ) + if self.source: + install_guard(self.source.make_guard(GuardBuilder.EQUALS_MATCH)) + if hasattr(self.value, name): + return ConstantVariable.create(getattr(self.value, name)) + if hasattr(self.value, "native_handle"): + return ConstantVariable.create(self.value.native_handle) + return None + + def get_real_python_backed_value(self) -> object: + return self.value + + def wait_event( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + event_arg = args[0] + if not isinstance(event_arg, EventVariable): + raise AssertionError(f"Expected EventVariable, got {type(event_arg)}") + tx.output.create_proxy( + "call_function", + torch.ops.streams.wait_event, + (event_arg.user_object_index, self.user_object_index), + {}, + ) + return ConstantVariable.create(None) + + def wait_stream( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + other_stream = args[0] + if not isinstance(other_stream, StreamVariable): + raise AssertionError(f"Expected StreamVariable, got {type(other_stream)}") + tx.output.create_proxy( + "call_function", + torch.ops.streams.wait_stream, + (self.user_object_index, other_stream.user_object_index), + {}, + ) + return ConstantVariable.create(None) + + def synchronize( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + tx.output.create_proxy( + "call_function", + torch.ops.streams.synchronize_stream, + (self.user_object_index,), + {}, + ) + return ConstantVariable.create(None) + + def query( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from ..utils import proxy_args_kwargs + from .builder import wrap_fx_proxy_cls + + return wrap_fx_proxy_cls( + target_cls=ConstantVariable, + tx=tx, + proxy=tx.output.create_proxy( + "call_method", "query", *proxy_args_kwargs([self] + args, kwargs) + ), + ) + + def record_event( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + tx.output.check_event_record_after_input_mutation(id(self.value)) + if args and isinstance(args[0], EventVariable): + event_var = args[0] + event = event_var.value + event_index = event_var.user_object_index + else: + event = self.value.record_event() + event_index = register_graph_created_object( + event, + EventVariable.make_construct_in_graph_event_fn( + TupleVariable([]), ConstDictVariable({}) + ), + ) + tx.output.create_proxy( + "call_function", + torch.ops.streams.record_event, + (event_index, self.user_object_index), + {}, + ) + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + get_external_object_by_index, + (event_index,), + {}, + ), + ) + + tp_methods = { + "wait_event": Method(wait_event), + "wait_stream": Method(wait_stream), + "synchronize": Method(synchronize), + "query": Method(query), + "record_event": Method(record_event), + } + + def tp_richcompare_impl(self, tx, other, op): + from ..guards import GuardBuilder, install_guard + from ..utils import cmp_name_to_op_mapping + from .constant import ConstantVariable + + if not isinstance(other, StreamVariable): + # Stream's tp_richcompare (THPStream_richcompare) compares + # stream_id/device and never returns NotImplemented. + return ConstantVariable.create(op == "__ne__") + if self.source: + install_guard(self.source.make_guard(GuardBuilder.EQUALS_MATCH)) + if other.source: + install_guard(other.source.make_guard(GuardBuilder.EQUALS_MATCH)) + op_fn = cmp_name_to_op_mapping[op] + return VariableTracker.build( + tx, + op_fn(self.value, other.value), # pyrefly: ignore[bad-argument-type] + ) + + def as_proxy(self) -> Proxy: + return self.proxy + + def module_name(self) -> str: + return "torch._C" + + def fn_name(self) -> str: + return "Stream" + + def reconstruct(self, codegen: "PyCodegen") -> None: + # If we got here, this stream is fully subsumed by the graph - this means it is + # not an input or global + if self.source: + raise AssertionError("Stream should not have a source during reconstruct") + if self.user_object_index is not None: + codegen.add_push_null( + lambda: codegen.load_import_from( + torch._dynamo.graph_bytecode_inputs.__name__, + "get_external_object_by_index", + ) + ) + codegen.append_output(codegen.create_load_const(self.user_object_index)) + codegen.extend_output(create_call_function(1, False)) + else: + # This will support the legacy behavior + prefix = f"_stream_{self.device}" + name = codegen.tx.output.install_global_by_id(prefix, self.value) + codegen.append_output(codegen.create_load_global(name, add=True)) + + def get_stream(self) -> "StreamVariable": + return self + + @staticmethod + def make_construct_in_graph_stream_fn( + args: TupleVariable, kwargs: ConstDictVariable + ) -> Callable[[int, "PyCodegen"], None]: + def fn(index: int, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from( + torch._dynamo.graph_bytecode_inputs.__name__, # type: ignore[implicit-imports] + "stash_graph_created_object", + ) + ) + codegen.add_push_null( + lambda: codegen.load_import_from( + torch._dynamo.utils.__name__, "build_stream" + ) + ) + codegen(args) + codegen(kwargs) + codegen.extend_output(create_call_function(2, False)) + codegen.extend_output(create_call_function(1, False)) + + return fn + + +class CudaStreamVariable(StreamVariable): + """Represents torch.cuda.Stream, preserving device-specific type and attributes.""" + + _cpython_type = torch.cuda.Stream + _device_handle_attr = "cuda_stream" + + tp_getset = { + "cuda_stream": GetSet(StreamVariable._stream_device_handle_get, None), + } + + +class XpuStreamVariable(StreamVariable): + """Represents torch.xpu.Stream, preserving device-specific type and attributes.""" + + _cpython_type = torch.xpu.Stream + _device_handle_attr = "sycl_queue" + + tp_getset = { + "sycl_queue": GetSet(StreamVariable._stream_device_handle_get, None), + } + + +_stream_fn_to_variable_cls: dict[object, type[StreamVariable]] = { + torch.cuda.current_stream: CudaStreamVariable, + torch.xpu.current_stream: XpuStreamVariable, +} + + +def _get_stream_variable_cls(stream_fn: object) -> type[StreamVariable] | None: + return _stream_fn_to_variable_cls.get(stream_fn) + + +class EventVariable(VariableTracker): + def __init__( + self, + proxy: Proxy, + value: torch.Event, + user_object_index: int | None, + **kwargs: Any, + ) -> None: + if proxy is not None and "example_value" in proxy.node.meta: + if proxy.node.meta["example_value"] != value: + raise AssertionError( + f"proxy example_value {proxy.node.meta['example_value']} != {value}" + ) + super().__init__(**kwargs) + self.proxy = proxy + self.value = value + self.user_object_index = user_object_index + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def python_type(self) -> type: + return type(self.value) + + def get_real_python_backed_value(self) -> object: + return self.value + + def wait( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + _, stream_index = EventVariable._get_stream_arg(tx, args, kwargs) + tx.output.create_proxy( + "call_function", + torch.ops.streams.wait_event, + ( + self.user_object_index, + stream_index, + ), + {}, + ) + return ConstantVariable.create(None) + + def record( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + stream_arg, stream_index = EventVariable._get_stream_arg(tx, args, kwargs) + tx.output.check_event_record_after_input_mutation(id(stream_arg.value)) + tx.output.create_proxy( + "call_function", + torch.ops.streams.record_event, + ( + self.user_object_index, + stream_index, + ), + {}, + ) + return ConstantVariable.create(None) + + def synchronize( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + tx.output.create_proxy( + "call_function", + torch.ops.streams.synchronize_event, + (self.user_object_index,), + {}, + ) + return ConstantVariable.create(None) + + def query( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from ..utils import proxy_args_kwargs + from .builder import wrap_fx_proxy_cls + + return wrap_fx_proxy_cls( + target_cls=ConstantVariable, + tx=tx, + proxy=tx.output.create_proxy( + "call_method", "query", *proxy_args_kwargs([self] + args, kwargs) + ), + ) + + tp_methods = { + "wait": Method(wait), + "record": Method(record), + "synchronize": Method(synchronize), + "query": Method(query), + } + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Event supports only the tp_methods above; every other name (including + # dunders) graph-breaks with an event-specific message rather than the + # generic "Unsupported method call". + if name in self.tp_methods: + return super().call_method(tx, name, args, kwargs) + method_name = ( + f"{type(self.value).__module__}.{type(self.value).__qualname__}.{name}" + ) + unimplemented( + gb_type="Unsupported event method", + context=str(name), + explanation=f"Dynamo doesn't support tracing the {method_name} method. " + f"We currently support wait, record, synchronize, and query.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + def as_proxy(self) -> Proxy: + return self.proxy + + @staticmethod + def _get_stream_arg( + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> tuple["StreamVariable", int]: + """Returns (stream_variable, stream_index_for_op). + + The ambient current stream is registered at index 0 in the external + object registry. The inductor wrapper updates index 0 at runtime so + that cudagraph capture sees the capture stream, not the stale + trace-time default stream. + """ + stream_arg = None + if args: + stream_arg = args[0] + elif kwargs: + stream_arg = kwargs.get("stream") + + if not stream_arg: + stream_var = tx.symbolic_stream_state.cur_stream() + return stream_var, stream_var.user_object_index # type: ignore[return-value] + + return stream_arg, stream_arg.user_object_index # type: ignore[return-value] + + @staticmethod + def make_construct_in_graph_event_fn( + args: TupleVariable, kwargs: ConstDictVariable + ) -> Callable[[int, "PyCodegen"], None]: + def fn(index: int, codegen: "PyCodegen") -> None: + codegen.add_push_null( + lambda: codegen.load_import_from( + torch._dynamo.graph_bytecode_inputs.__name__, # type: ignore[implicit-imports] + "stash_graph_created_object", + ) + ) + codegen.add_push_null( + lambda: codegen.load_import_from( + torch._dynamo.utils.__name__, "build_event" + ) + ) + codegen(args) + codegen(kwargs) + codegen.extend_output(create_call_function(2, False)) + codegen.extend_output(create_call_function(1, False)) + + return fn + + def reconstruct(self, codegen: "PyCodegen") -> None: + # If we got here, this event is fully subsumed by the graph - this means it is + # not an input or global + if self.source: + raise AssertionError("Event should not have a source during reconstruct") + if self.user_object_index is not None: + codegen.add_push_null( + lambda: codegen.load_import_from( + torch._dynamo.graph_bytecode_inputs.__name__, + "get_external_object_by_index", + ) + ) + codegen.append_output(codegen.create_load_const(self.user_object_index)) + codegen.extend_output(create_call_function(1, False)) + else: + prefix = "_event" + name = codegen.tx.output.install_global_by_id(prefix, self.value) + codegen.append_output(codegen.create_load_global(name, add=True)) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/tensor.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..c2bc10f2ef6a4489c137f86dd442f5eced999471 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/tensor.py @@ -0,0 +1,3667 @@ +""" +This module contains variable tracker classes for handling tensors and tensor-related operations in Dynamo. + +The main class is TensorVariable which represents torch.Tensor inputs and intermediate values in the FX graph. +It handles tensor operations, method calls, and maintains metadata about tensor properties like dtype, device, etc. + +Other key classes include: +- SymNodeVariable: Represents symbolic scalars (int/float/bool) used for size computation and unspecialized values +- NumpyNdarrayVariable: Handles numpy array interop through torch._numpy +- UnspecializedPythonVariable: Represents unspecialized Python numeric values as 1-element tensors +- TensorSubclassVariable: Handles tensor subclasses with __torch_function__ overrides +- UntypedStorageVariable: Represents tensor storage objects +- DataPtrVariable: Handles tensor data pointer operations + +These classes work together to track tensor operations and properties during Dynamo's tracing process. +""" + +import functools +import logging +import operator +import textwrap +import traceback +import types +from collections.abc import Iterable, Sequence +from contextlib import nullcontext +from itertools import chain +from types import NoneType +from typing import Any, NoReturn, Optional, TYPE_CHECKING +from typing_extensions import NotRequired, TypedDict + +import sympy + +import torch._numpy as tnp +import torch.fx +import torch.random +from torch import sym_float, sym_int +from torch._custom_class_base import CustomClassBase +from torch._dynamo import compiled_autograd +from torch._library.opaque_object import is_opaque_symbolic_type +from torch._subclasses.meta_utils import is_sparse_any +from torch.fx.experimental.symbolic_shapes import ( + guard_scalar, + GuardOnDataDependentSymNode, + has_free_symbols, + is_symbolic, + SymTypes, +) +from torch.utils._python_dispatch import is_traceable_wrapper_subclass + +from .. import config, graph_break_hints, variables +from .._trace_wrapped_higher_order_op import trace_wrapped +from ..exc import ( + ObservedAttributeError, + raise_observed_exception, + raise_type_error, + raise_value_error, + TorchRuntimeError, + unimplemented, + UnknownPropertiesDuringBackwardTrace, + UserError, + UserErrorType, +) +from ..external_utils import call_hook_from_backward_state +from ..guards import GuardBuilder, install_guard +from ..source import AttrSource, TypeSource +from ..utils import ( + cmp_name_to_op_mapping, + fqn, + get_custom_getattr, + get_fake_value, + get_real_value, + guard_if_dyn, + object_has_getattribute, + product, + proxy_args_kwargs, + set_example_value, + tensortype_to_dtype, +) +from .base import ( + _check_method_arity, + _derive_method_flags, + AttributeMutationNew, + GetSet, + Method, + ValueMutationNew, + VariableTracker, +) +from .constant import ConstantVariable +from .lists import ListIteratorVariable, SizeVariable +from .script_object import CustomClassObjectVariable +from .user_defined import UserDefinedClassVariable + + +try: + import numpy as np +except ModuleNotFoundError: + np = None # type: ignore[assignment] + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.output_graph import OutputGraph + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + from .functions import UserFunctionVariable + from .torch_function import TensorWithTFOverrideVariable + + +log = logging.getLogger(__name__) + +# Ops that allow tensor tensor +supported_tensor_comparison_ops = { + ">": operator.gt, + "<": operator.lt, + ">=": operator.ge, + "<=": operator.le, + "==": operator.eq, + "!=": operator.ne, + "is": operator.is_, + "is not": operator.is_not, +} +# Ops that allow tensor None +supported_const_comparison_ops = { + "is": operator.is_, + "is not": operator.is_not, + "==": operator.eq, + "!=": operator.ne, +} +supported_comparison_ops = { + **supported_tensor_comparison_ops, + **supported_const_comparison_ops, +} +supported_tensor_comparison_op_values = dict.fromkeys( + supported_tensor_comparison_ops.values() +) +supported_const_comparison_op_values = dict.fromkeys( + supported_const_comparison_ops.values() +) + + +def is_bound_tensor_method(value: object) -> bool: + return bool( + callable(value) + and not torch._dynamo.utils.object_has_getattribute(value) + and hasattr(value, "__self__") + and isinstance(value.__self__, torch.Tensor) + and getattr(value.__self__, value.__name__, None) + ) + + +# instead of using inspect.getattr_static, we directly lookup the appropriate +# dicts. It is necessary to keep the torch._C.TensorBase first in the or +# operation, because the second arg takes priority in or operation when there +# are common keys. +all_tensor_attrs = torch._C.TensorBase.__dict__ | torch.Tensor.__dict__ + +# Tensor attributes that are plain views of the tensor. Each maps to the aten op +# that the C++ getter dispatches to, see native_functions.yaml. +_VIEW_ATTR_TO_ATEN_OP = { + "T": torch.ops.aten.numpy_T, + "mT": torch.ops.aten.mT, + "H": torch.ops.aten.matrix_H, + "mH": torch.ops.aten.mH, +} + + +def _is_sym_arith_operand(vt: VariableTracker) -> bool: + """True if vt can be the other operand of a SymNode arithmetic op + (add/sub). Accepts SymNode-like values plus float ConstantVariable — + arithmetic with float promotes to SymFloat, unlike bitwise ops.""" + if vt.is_symnode_like(): + return True + + # mirror sym_node.py::binary_magic_impl + return isinstance(vt, ConstantVariable) and isinstance(vt.value, (float, int, bool)) + + +def _tensor_debug_repr(value: torch.Tensor, type_name: str = "Tensor") -> str: + if torch._C._functorch.is_batchedtensor(value): + level = torch._C._functorch.maybe_get_level(value) + bdim = torch._C._functorch.maybe_get_bdim(value) + unwrapped = torch._C._functorch.get_unwrapped(value) + return ( + "BatchedTensor(" + f"lvl={level}, bdim={bdim}, value={_tensor_debug_repr(unwrapped)}" + ")" + ) + if torch._C._functorch.is_gradtrackingtensor(value): + level = torch._C._functorch.maybe_get_level(value) + unwrapped = torch._C._functorch.get_unwrapped(value) + return f"GradTrackingTensor(lvl={level}, value={_tensor_debug_repr(unwrapped)})" + if torch._C._functorch.is_functionaltensor(value): + level = torch._C._functorch.maybe_get_level(value) + unwrapped = torch._C._functorch.get_unwrapped(value) + return f"FunctionalTensor(lvl={level}, value={_tensor_debug_repr(unwrapped)})" + return f"{type_name}(shape={tuple(value.shape)}, dtype={value.dtype})" + + +class TensorSpecializedProps(TypedDict): + """Static tensor metadata produced by TensorVariable.specialize; the keys + map 1:1 to the corresponding TensorVariable.__init__ kwargs. The size, + stride and contiguity keys are only populated for fully static shapes.""" + + dtype: torch.dtype + device: torch.device + layout: torch.layout + ndim: int + requires_grad: bool + is_nested: bool + is_quantized: bool + is_sparse: bool + class_type: type + has_grad_fn: bool + _size: NotRequired[tuple[Any, ...]] + stride: NotRequired[tuple[Any, ...]] + is_contiguous: NotRequired[tuple[torch.memory_format, ...] | None] + + +class TensorVariable(VariableTracker): + """A torch.Tensor input or an intermediate value in the FX graph""" + + _nonvar_fields = { + "proxy", + "dtype", + "device", + "layout", + "ndim", + "size", + "stride", + "requires_grad", + "is_quantized", + "is_contiguous", + "is_nested", + "is_sparse", + "class_type", + "specialized_value", + "_is_name_set", + *VariableTracker._nonvar_fields, + } + + def reconstruct_pycode(self, codegen) -> str: + if id(self.proxy) in codegen.graph_outputs: + return f"__graph_out[{codegen.graph_outputs[id(self.proxy)].index}]" + elif self.source: + return self.source.reconstruct_pycode(codegen) + else: + raise RuntimeError(f"Python codegen for {self} failed with unknown source.") + + def get_real_value(self) -> torch.Tensor: + """ + Get the actual value represented by this variable if computation is run + using the user-provided inputs. + NOTE: this runs actual tensor computation and may be + slow and memory-intensive. + """ + return get_real_value(self.proxy.node, self.proxy.tracer) + + def __init__( + self, + proxy: torch.fx.Proxy, + *, + dtype: torch.dtype, + device: torch.device, + layout: torch.layout, + ndim: int, + requires_grad: bool, + is_nested: bool, + is_quantized: bool, + is_sparse: bool, + class_type: type, + has_grad_fn: bool, + _size: tuple[Any, ...] | None = None, + stride: tuple[Any, ...] | None = None, + is_contiguous: tuple[torch.memory_format, ...] | None = None, + _is_name_set: bool | None = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.proxy = proxy + self.dtype = dtype + self.device = device + self.layout = layout + self.ndim = ndim + self._size = _size # this is accessed as a property for validation + self.stride = stride + self.requires_grad = requires_grad + self.is_quantized = is_quantized + self.is_contiguous = is_contiguous + self.is_nested = is_nested + self.is_sparse = is_sparse + self.class_type = class_type + self.has_grad_fn = has_grad_fn + if _is_name_set is None: + # no need to rename inputs + _is_name_set = self.proxy.node.op == "placeholder" + self._is_name_set: bool = _is_name_set + + def synchronize_attributes( + self, tx: "InstructionTranslatorBase", target_cls: type | None = None + ) -> None: + from .builder import get_specialized_props, infer_subclass_type + + if target_cls is None: + target_cls = type(self) + + example_value = self.proxy.node.meta.get("example_value") + specialized_props = get_specialized_props( + target_cls, tx, example_value, infer_subclass_type(example_value) + ) + # These fields match the conditionally specialized metadata in + # get_specialized_props(). If fake execution changes them to symbolic + # values, they are omitted and the old cache must be invalidated. + for k in ("_size", "stride", "is_contiguous"): + if k not in specialized_props: + setattr(self, k, None) + for k, v in specialized_props.items(): + setattr(self, k, v) + + def _get_fake_version(self) -> int | None: + """Get the current version of self's fake tensor, or None if unavailable.""" + self_fake = self.proxy.node.meta.get("example_value") + return self_fake._version if self_fake is not None else None + + def _sync_if_inplace_mutation( + self, + tx: "InstructionTranslatorBase", + version_before: int | None, + ) -> None: + """ + Sync attributes if self was mutated by an inplace operation. + + See Note [Inplace ops and VariableTracker metadata] + """ + version_after = self._get_fake_version() + if ( + version_before is not None + and version_after is not None + and version_after > version_before + ): + self.synchronize_attributes(tx) + tx.output.check_input_mutation_on_current_stream(tx) + + def debug_repr(self) -> str: + return _tensor_debug_repr( + self.proxy.node.meta["example_value"], self.python_type_name() + ) + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + unimplemented( + gb_type="repr() on tensor", + context=f"repr() on {self.python_type_name()}", + explanation="Tensor repr requires actual runtime values which are " + "not available during tracing.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + def as_proxy(self) -> torch.fx.Proxy: + return self.proxy + + def python_type(self) -> type: + return self.class_type + + def is_tensor(self) -> bool: + return True + + def nb_bool_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # THPVariable_bool calls at::Tensor::is_nonzero(), i.e. .item() != 0. + from .constant import ConstantVariable + + item = self.call_method(tx, "item", [], {}) + if isinstance(item, SymNodeVariable) and isinstance( + item.sym_num, torch.SymBool + ): + return item + if isinstance(item, ConstantVariable): + return VariableTracker.build(tx, bool(item.value)) + return SymNodeVariable.create(tx, item.as_proxy() != 0) + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + """Tensor tp_richcompare: element-wise comparison producing an FX proxy.""" + from .builder import wrap_fx_proxy_cls + + if not isinstance(other, (SymNodeVariable, ConstantVariable, TensorVariable)): + return ConstantVariable.create(NotImplemented) + op_fn = cmp_name_to_op_mapping[op] + proxy = tx.output.create_proxy( + "call_function", op_fn, (self.as_proxy(), other.as_proxy()), {} + ) + return wrap_fx_proxy_cls(type(self), tx, proxy) + + @staticmethod + def specialize(value: torch.Tensor) -> TensorSpecializedProps: + try: + has_grad_fn = value.grad_fn is not None + except Exception: + # Workaround for issues with create_parameter_op in Dynamo. Reading + # grad_fn should never cause an issue. + has_grad_fn = False + + props: TensorSpecializedProps = { + "dtype": value.dtype, + "device": value.device, + "layout": value.layout, + "ndim": int(value.ndim), + "requires_grad": value.requires_grad, + "is_nested": value.is_nested, + "is_quantized": value.is_quantized, + "is_sparse": value.is_sparse, + "class_type": type(value), + "has_grad_fn": has_grad_fn, + } + + if is_sparse_any(value) and not has_free_symbols(value): + props["_size"] = tuple( + int(s) if is_symbolic(s) else s for s in value.size() + ) + elif not has_free_symbols(value): + # this is a fully static shape, and the keys on props here inform specialization. + # We have to cast to int here, because these might get accessed as ConstantVariable, which has + # a strict no-symint policy. If we got here due to not having free symbols, this is a known constant + # already. We could remove the discrepancy here, by having ConstantVariable be more permissive for + # constant backed SymInts, but that assert being strict has led to some good signal in hunting bugs, and + # I'd like to keep it around for now. + props["_size"] = tuple( + # the non is_symbolic case applies to the jagged layout + # NestedTensor case as singleton ints are not symbolic + int(s) if is_symbolic(s) else s + for s in value.size() + ) + props["stride"] = tuple(value.stride()) + if torch._C._functorch.is_batchedtensor(value): + # Batched tensors does not support contiguity patterns, so + # we refrain from computing the `is_contiguous` property + props["is_contiguous"] = None + else: + props["is_contiguous"] = tuple( + x + for x in torch._prims_common._memory_formats + if value.is_contiguous(memory_format=x) + ) + return props + + def dynamic_getattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + fake_val = self.proxy.node.meta["example_value"] + # For getattrs on tensors without sources, + # we can do better than the default (creating a GetAttrVariable) + # if: + # (1) the tensor is a traceable tensor subclass + # (2) We are getattr'ing an inner tensor from that subclass + if not self.source and is_traceable_wrapper_subclass(fake_val): + attrs, _ctx = fake_val.__tensor_flatten__() + proxy = getattr(self.as_proxy(), name) + example_value = getattr(fake_val, name) + if name in attrs: + # attrs returned from tensor_flatten are always tensors or opaques + if not isinstance(example_value, (torch.Tensor, CustomClassBase)): + raise AssertionError( + f"Expected Tensor or CustomClassBase, got {type(example_value)}" + ) + from .builder import wrap_fx_proxy + + return wrap_fx_proxy(tx=tx, proxy=proxy, example_value=example_value) + elif is_opaque_symbolic_type(type(example_value)): + fake_script_obj = torch._library.fake_class_registry.maybe_to_fake_obj( + tx.output.fake_mode, example_value + ) + return CustomClassObjectVariable.create(proxy, fake_script_obj, tx=tx) + elif isinstance( + example_value, + torch._library.fake_class_registry.FakeScriptObject, + ): + return CustomClassObjectVariable.create(proxy, example_value, tx=tx) + # any other attributes on the subclass (that are not methods) + # are assumed to be constant metadata. + elif not callable(example_value): + return VariableTracker.build(tx, example_value) + + if not (self.source and self.source.subguards_allowed()): + raise NotImplementedError + + # For local source, we associate the real value. We use this real value + # for implementing getattr fallthrough on the variable tracker base class. + + # Note - this scope construction is mirrored in guards + # A subsequent PR will introduce a util. + scope = {"L": tx.output.local_scope, "G": tx.output.global_scope} + try: + # We raise in case we get a typerror bug w/ SuperSource. + # SuperSource has bugs in it atm, and can produce code like + # eval("super(L['mod'].model.model.encoder.embed_positions.forward__class__, + # L['mod'].model.model.encoder.embed_positions)", scope) + # Which is incorrect, and violates the invariant that all sources should be eval()-able against the scope. + _input_associated_real_value = eval(self.source.name, scope) + except Exception as exc: + raise NotImplementedError from exc + + if _input_associated_real_value is None: + raise NotImplementedError + + if object_has_getattribute(_input_associated_real_value): + raise NotImplementedError + + if get_custom_getattr(_input_associated_real_value): + raise NotImplementedError + + try: + real_value = getattr(_input_associated_real_value, name) + except AttributeError: + raise_observed_exception( + AttributeError, + tx, + args=[ + f"'{type(_input_associated_real_value).__name__}' object has no attribute '{name}'" + ], + ) + + attr_source = AttrSource(self.source, name) + + # Typically we'd want to use variable builder here + # but unfortunately id(real_value.__self__) is not id() + if is_bound_tensor_method(real_value): + # No need to install the guard because its a bound tensor method + from .misc import GetAttrVariable + + return GetAttrVariable( + self, name, source=attr_source, py_type=type(real_value) + ) + + install_guard( + self.source.make_guard(functools.partial(GuardBuilder.HASATTR, attr=name)) + ) + return VariableTracker.build(tx, real_value, attr_source) + + def _view_attr(self, tx: "InstructionTranslatorBase", name: str) -> VariableTracker: + """Trace a view attribute as a call to the aten op behind the C++ getter. + + Going through the op keeps the node on the current tracer. Reading the + attribute off the base proxy instead puts the node in whichever graph + owns the base, so inside a higher order op it lands in the parent graph + and then has to be lifted back in as a subgraph input. + """ + from .torch import TorchInGraphFunctionVariable + + return TorchInGraphFunctionVariable(_VIEW_ATTR_TO_ATEN_OP[name]).call_function( + tx, [self], {} + ) + + def method_attr_T(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self._view_attr(tx, "T") + + def method_attr_mT(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self._view_attr(tx, "mT") + + def method_attr_H(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self._view_attr(tx, "H") + + def method_attr_mH(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self._view_attr(tx, "mH") + + def method_attr_ndim(self, tx: "InstructionTranslatorBase") -> VariableTracker: + if self.ndim is not None: + return VariableTracker.build(tx, self.ndim) + else: + return self.call_method(tx, "dim", [], {}) + + def method_attr_dtype( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker | None: + if self.dtype is not None: + return VariableTracker.build(tx, self.dtype) + return None + + def method_attr_device( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker | None: + if self.device is not None: + return VariableTracker.build(tx, self.device) + return None + + def method_attr_layout( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker | None: + if self.layout is not None: + return VariableTracker.build(tx, self.layout) + return None + + def method_attr_is_cuda( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable | None: + if self.device is not None: + return VariableTracker.build(tx, self.device.type == "cuda") + return None + + def method_attr_shape(self, tx: "InstructionTranslatorBase") -> VariableTracker: + if self.valid_size(): + sizes: list[VariableTracker] = [ + VariableTracker.build(tx, x) for x in self.size + ] + return SizeVariable(sizes) + else: + return self.call_method(tx, "size", [], {}) + + def method_attr_requires_grad( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable | None: + if self.requires_grad is not None: + return VariableTracker.build(tx, self.requires_grad) + return None + + def method_attr_is_quantized( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable | None: + if self.is_quantized is not None: + return VariableTracker.build(tx, self.is_quantized) + return None + + def method_attr_is_sparse( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable | None: + if self.is_sparse is not None: + return VariableTracker.build(tx, self.is_sparse) + return None + + def method_attr_is_nested( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable | None: + if self.is_nested is not None: + return VariableTracker.build(tx, self.is_nested) + return None + + def method_attr_retain_grad(self, tx: "InstructionTranslatorBase") -> NoReturn: + unimplemented( + gb_type="Tensor.retain_grad() with AOTDispatcher", + context=f"tp_getattro_impl {self} retain_grad", + explanation="`Tensor.retain_grad()` does not work with AOTDispatcher.", + hints=[], + ) + + def method_attr_grad( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker | None: + if tx.output.side_effects.has_pending_mutation_of_attr(self, "grad"): + return tx.output.side_effects.load_attr(self, "grad") + if ( + isinstance(self.mutation_type, AttributeMutationNew) + and not self.has_grad_fn + ): + return ConstantVariable.create(None) + # None tells tp_getattro_impl to use default .grad handling + return None + + def method_attr_data(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return variables.TorchInGraphFunctionVariable( + torch._C._autograd._get_data_attr # type: ignore[attr-defined] + ).call_function(tx, [self], {}) + + def method_attr_grad_fn( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable | None: + if self.has_grad_fn: + unimplemented( + gb_type="Tensor with grad_fn()", + context=f"tp_getattro_impl {self} grad_fn", + explanation="Dynamo does not support tracing tensors with a grad_fn directly.", + hints=[], + ) + else: + return variables.ConstantVariable.create(None) + + def method_attr__version(self, tx: "InstructionTranslatorBase") -> VariableTracker: + from ..tensor_version_op import _tensor_version + + return variables.TorchInGraphFunctionVariable(_tensor_version).call_function( + tx, [self], {} + ) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + from . import GetAttrVariable + + # TODO - This is not a good solution but solves an accuracy issue. + # Today, tp_getattro_impl returns GetAttrVariable for both non-existent + # attributes and existing attributes. This is a bug and requires more + # deep dive. + if name in all_tensor_attrs: + return ConstantVariable.create(True) + + try: + var = VariableTracker.build(tx, getattr).call_function( + tx, [self, VariableTracker.build(tx, name)], {} + ) + # in the event that TensorVariable returns NotImplemented + # GetAttrBuiltinVariable.call_function returns GetAttrVariable + ret_val = not isinstance(var, GetAttrVariable) + except (AttributeError, ObservedAttributeError): + ret_val = False + + if self.source: + install_guard( + self.source.make_guard( + functools.partial(GuardBuilder.HASATTR, attr=name) + ) + ) + + return VariableTracker.build(tx, ret_val) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + fake_val = self.as_proxy().node.meta["example_value"] + if ( + isinstance(fake_val, torch.Tensor) + and is_sparse_any(fake_val) + and (not tx.export or not config.capture_sparse_compute) + ): + unimplemented( + gb_type="Attempted to wrap sparse Tensor", + context="", + explanation="torch.compile does not support sparse Tensors", + hints=[*graph_break_hints.SPARSE_TENSOR], + ) + + if self.is_strict_mode(tx): + if name in self._strict_mode_banned_ops(): + unimplemented( + gb_type="Strict mode banned op", + context=f"tp_getattro_impl {self} {name}", + explanation=f"Getattr invocation '{name}' in strict mode is not supported.", + hints=[ + f"Remove `{name}` from the list of banned ops by " + "setting `torch._dynamo.config._autograd_backward_strict_mode_banned_ops`.", + ], + ) + elif name in self._strict_mode_conditional_banned_ops(): + raise UnknownPropertiesDuringBackwardTrace( + f"Unknown property {name} during speculating backward, dynamo will insert contiguous call ahead and speculate it again" + ) + + if name == "__class__": + # Carry provenance on the class, mirroring BuiltinVariable.call_type. + # A sourced class self-guards when observed downstream (e.g. + # `w.__class__ is SomeType`), which keeps type observation sound even + # when the input's own class guard is relaxed (see + # VariableBuilder.wrap_tensor and ACT input polymorphism). + source = self.source and TypeSource(self.source) + return VariableTracker.build(tx, self.python_type(), source) + + handler = getattr(self, f"method_attr_{name}", None) + result = handler(tx) if handler is not None else None + + # Add a guard for type matching, these guards are checked before tensor guards + # In some cases, a . guard can be evaluated first, and break if + # is later changed to another type + if ( + result is not None + and self.source + and self.source.subguards_allowed() + # A view attribute is the output of an op we just traced, like any + # other view. An AttrSource would instead make Dynamo drop it from + # the graph outputs and rebuild it in bytecode from the base. + and name not in _VIEW_ATTR_TO_ATEN_OP + and not ( + name not in ("grad", "requires_grad") and result.is_python_constant() + ) + ): + install_guard(self.make_guard(GuardBuilder.TYPE_MATCH)) + result.source = AttrSource(self.source, name) + + # It's hard to get inplace view (metadata mutation) on graph input work properly across + # dynamo/aot/inductor, just fall back. + if self.source is not None and hasattr(torch.ops.aten, name): + fn = getattr(torch.ops.aten, name) + if ( + hasattr(fn, "overloads") + and hasattr(fn, fn.overloads()[0]) + and torch.Tag.inplace_view in getattr(fn, fn.overloads()[0]).tags + ): + # Delay the graph break to the actual call of unsqueeze_/resize_/resize_as_ etc. + return variables.misc.DelayGraphBreakVariable( + source=AttrSource(self.source, name), + msg="Getting an inplace view on a graph input is not supported", + hints=[ + "Avoid mutating a graph input's tensor metadata with in-place view ops. " + "If the mutation is only needed inside the compiled region, replace the in-place call " + "with an out-of-place view, for example `x = x.transpose(1, 2)` instead of " + "`x.transpose_(1, 2)`.", + "If you need to mutate the input tensor's metadata, move the in-place view call outside " + "`torch.compile`.", + ], + ) + + # For attributes (not methods) that were not caught in the special handling above, + # (e.g. tensor.real), we handle these generically, assuming that the output type is + # a tensor. + if result is None and name != "grad": + + def try_generic_attr_handling() -> VariableTracker | None: + from .builder import wrap_fx_proxy + + static_attr = all_tensor_attrs.get(name, None) + if static_attr is None: + return None + + # Make sure this is an attribute, not a method. + # type(torch.Tensor.H) should be "getset_descriptor" + # This is a because of CPython implementation, see THPVariableType: + # these attributes are implemented under tp_getset, which appear + # as `getset_descriptor`s, (compared to, say, methods which appear + # as `method_descriptor`s) + if type(static_attr) is not types.GetSetDescriptorType: + return None + + # Create the node on the current tracer, not on the tracer that + # owns the base proxy. Otherwise, inside a higher order op, the + # node lands in the parent graph and has to be lifted back in as + # a subgraph input. + proxy = tx.output.current_tracer.create_proxy( + "call_function", getattr, (self.as_proxy(), name), {} + ) + if self.source is not None: + return wrap_fx_proxy( + tx=tx, proxy=proxy, source=AttrSource(self.source, name) + ) + else: + return wrap_fx_proxy(tx=tx, proxy=proxy) + + result = try_generic_attr_handling() + + if result is None: + result = self.dynamic_getattr(tx, name) + + if result is None: + raise NotImplementedError + return result + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase", idxes: Sequence[int] | None = None + ) -> list[VariableTracker]: + from .builder import wrap_fx_proxy_cls + from .torch_function import TensorWithTFOverrideVariable + + if self.valid_size(): + size_len = len(self.size) + else: + size_var = self.call_method(tx, "size", [], {}) + if not isinstance(size_var, SizeVariable): + raise AssertionError(f"Expected SizeVariable, got {type(size_var)}") + size_len = len(size_var.items) + # Ensure we don't unpack a scalar tensor. + if size_len == 0: + raise AssertionError("Can't unpack scalar tensors.") + + if self.valid_size(): + length = self.size[0] + else: + dyn_length = self.call_method( + tx, "size", [VariableTracker.build(tx, 0)], {} + ) + # SymNodeVariable for symbolic sizes, ConstantVariable for constants OR values produced through + # symbolic_shapes, but that end up as int/sympy.Integer + if not ( + isinstance(dyn_length, SymNodeVariable) + or dyn_length.is_python_constant() + ): + raise AssertionError( + f"Expected SymNodeVariable or python constant, got {type(dyn_length)}" + ) + if isinstance(dyn_length, SymNodeVariable): + length = dyn_length.evaluate_expr(tx.output) + else: + length = dyn_length.as_python_constant() + + if idxes is None: + idxes = range(length) # type: ignore[arg-type] + else: + if len(idxes) != length: + raise AssertionError( + f"Can't unpack a tensor of {length} rows into a tuple of {len(idxes)} elements." + ) + + # preserve tensor subclass type when unpacking + if isinstance(self, TensorWithTFOverrideVariable): + base_vars = [ + wrap_fx_proxy_cls( + target_cls=TensorVariable, tx=tx, proxy=self.as_proxy()[i] + ) + for i in idxes + ] + return [ + TensorWithTFOverrideVariable.from_tensor_var( + tx, v, self.class_type, self.source + ) + for v in base_vars + ] + + return [ + wrap_fx_proxy_cls(target_cls=type(self), tx=tx, proxy=self.as_proxy()[i]) + for i in idxes + ] + + def call_tree_map( + self, + tx: "InstructionTranslatorBase", + tree_map_fn: "UserFunctionVariable", + map_fn: VariableTracker, + rest: list[VariableTracker], + tree_map_kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return map_fn.call_function(tx, [self, *rest], {}) + + def valid_size(self) -> bool: + return self._size is not None + + @property + def size(self) -> tuple[Any, ...]: + if self._size is None: + raise AssertionError("accessing None size in TensorVariable") + return self._size + + def _strict_mode_banned_ops(self) -> list[str]: + return torch._dynamo.config._autograd_backward_strict_mode_banned_ops + + def _strict_mode_conditional_banned_ops(self) -> list[str]: + return ( + torch._dynamo.config._autograd_backward_strict_mode_conditional_banned_ops + ) + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # Tensor.__getitem__ is a custom C slot, not CPython's mp_subscript. + from .builder import SourcelessBuilder, VariableBuilder + from .torch_function import can_dispatch_torch_function, dispatch_torch_function + + if self.is_strict_mode(tx) and "__getitem__" in self._strict_mode_banned_ops(): + unimplemented( + gb_type="Illegal __getitem__ invocation in strict mode", + context=f"mp_subscript_impl {self} {key}", + explanation="Dynamo currently does not support __getitem__ " + "invocation in strict mode.", + hints=[], + ) + + empty_kwargs: dict[str, VariableTracker] = {} + static_attr = all_tensor_attrs.get("__getitem__", None) + if static_attr is not None and can_dispatch_torch_function( + tx, (self, key), empty_kwargs + ): + if self.source: + func_var = VariableBuilder( + tx, + AttrSource(AttrSource(self.source, "__class__"), "__getitem__"), + )(static_attr) + else: + func_var = SourcelessBuilder.create(tx, torch.Tensor.__getitem__) + return dispatch_torch_function(tx, func_var, (self, key), empty_kwargs) + + return self.method___getitem__(tx, key) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: "dict[str, VariableTracker]", + ) -> VariableTracker: + from .builder import SourcelessBuilder, VariableBuilder + from .torch_function import can_dispatch_torch_function, dispatch_torch_function + + if self.is_strict_mode(tx) and name in self._strict_mode_banned_ops(): + unimplemented( + gb_type="Illegal method invocation in strict mode", + context=f"call_method {self} {name} {args} {kwargs}", + explanation="Dynamo currently does not support this method " + f"({name}) invocation in strict mode.", + hints=[], + ) + + if name == "__deepcopy__": + unimplemented( + gb_type="Attempted to copy.deepcopy a tensor", + context=f"copy.deepcopy({self})", + explanation="Dynamo does not support copy.deepcopy() on tensors.", + hints=[ + "Avoid calling copy.deepcopy() on tensors inside compiled regions.", + ], + ) + + # Only override builtin tensor methods + # The user can manually add override handling + # with a decorator for other methods (e.g. a dispatch subclass with other methods) + static_attr = all_tensor_attrs.get(name, None) + is_base_tensor_method = static_attr is not None + + if ( + can_dispatch_torch_function(tx, tuple([self] + list(args)), kwargs) + and is_base_tensor_method + ): + if self.source: + func_var = VariableBuilder( + tx, AttrSource(AttrSource(self.source, "__class__"), name) + )(static_attr) + else: + func_var = SourcelessBuilder.create(tx, getattr(torch.Tensor, name)) + + return dispatch_torch_function( + tx, func_var, tuple([self] + list(args)), kwargs + ) + + # Declarative named-method dispatch (tp_methods). Mirrors CPython's + # tp_methods table: arity (derived from CPython's ml_flags) is checked + # centrally via _check_method_arity, then the handler runs with its + # native Python signature. A handler returning None declines and falls + # through to the generic proxy path below, matching the old per-handler + # fall-through. + method = self.tp_methods.get(name) + if method is not None: + flags = _derive_method_flags(self, name) + _check_method_arity(self, tx, name, flags, args, kwargs) + # Realize any LazyVariableTracker in kwargs before calling handler. + realized_kwargs = {k: v.realize() for k, v in kwargs.items()} + try: + result = method.handler(self, tx, *args, **realized_kwargs) + except TypeError as e: + unimplemented( + gb_type="Unhandled args for method", + context=f"call_method {self} {name} {args} {kwargs}", + explanation="Dynamo encountered an error while calling " + f"the method `{name}`.", + hints=[], + from_exc=e, + ) + if result is not None: + return result + + # Guard against unknown methods reaching the generic proxy path. + # For traceable wrapper subclasses (DTensor, NestedTensor), class_type + # is torch.Tensor, so check the example_value's actual type instead. + example_value = self.proxy.node.meta.get("example_value") + check_type = ( + type(example_value) if example_value is not None else self.class_type + ) + if not hasattr(check_type, name): + unimplemented( + gb_type="Unhandled tensor method", + context=f"call_method {self} {name} {args} {kwargs}", + explanation=f"Tensor method `{name}` is not defined on " + f"{check_type.__name__} and does not have an explicit " + "handler in TensorVariable.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + from .builder import wrap_fx_proxy + + try: + proxy = tx.output.create_proxy( + "call_method", + name, + *proxy_args_kwargs([self, *args], kwargs), + ) + except NotImplementedError as e: + unimplemented( + gb_type="Unsupported argument type in tensor method call", + context=f"call_method {self} {name} {args} {kwargs}", + explanation=f"Dynamo could not create a proxy for an argument in the call " + f"to Tensor.{name}(). This usually means an unsupported type was passed " + f"as an argument to a tensor method.", + hints=[*graph_break_hints.SUPPORTABLE], + from_exc=e, + ) + + # [Note: Inplace ops and VariableTracker metadata] + # For inplace operations, we need to propagate tensor metadata from the + # arguments to self. For example: + # x.add_(y) where y.requires_grad=True => x.requires_grad becomes True + # We detect inplace ops by checking if self's fake tensor version changes + # after wrap_fx_proxy (which runs get_fake_value internally). + # Some inplace ops mutate metadata even without tensor arguments, e.g. + # as_strided_ mutates size/stride from integer/list arguments. + + # See ops_consuming_unbacked_scalars in torch.py for the full allowlist + # and reasoning. + from .torch import methods_consuming_unbacked_scalars + + ctx = ( + tx.fake_mode.shape_env.ignore_fresh_unbacked_symbols + if tx.fake_mode + and tx.fake_mode.shape_env + and name in methods_consuming_unbacked_scalars + and any( + isinstance(v, TensorVariable) and v.ndim == 0 + for v in chain(args, kwargs.values()) + ) + else nullcontext + ) + + version_before = self._get_fake_version() + with ctx(): + result = wrap_fx_proxy(tx, proxy) + self._sync_if_inplace_mutation(tx, version_before) + + return result + + def method_size( + self, tx: "InstructionTranslatorBase", *args: Any, **kwargs: Any + ) -> VariableTracker | None: + return self._method_size_stride("size", *args, **kwargs) + + def method_stride( + self, tx: "InstructionTranslatorBase", *args: Any, **kwargs: Any + ) -> VariableTracker | None: + return self._method_size_stride("stride", *args, **kwargs) + + def _method_size_stride( + self, name: str, dim: Any | None = None + ) -> VariableTracker | None: + dim = guard_if_dyn(dim) + + def make_const_size_variable(x: Sequence[Any], **options: Any) -> SizeVariable: + return SizeVariable( + [ConstantVariable.create(y, **options) for y in x], **options + ) + + RetVariable = ( + make_const_size_variable if name == "size" else ConstantVariable.create + ) + + # Technically, this should not be necessary, but I'm including it + # for enhanced BC, in case example_value is sometimes not set + # (it really should always be set though!) + if name != "size": + r = getattr(self, name) + elif name == "size" and self.valid_size(): + r = self.size + else: + r = None + + if r is not None: + if dim is None: + return RetVariable(r) + else: + return ConstantVariable.create(r[dim]) + + # It might still be constant! Consult the fake tensor and see + if (fake := self.proxy.node.meta.get("example_value")) is not None: + if dim is None: + fake_r = getattr(fake, name)() + if not has_free_symbols(fake_r): + # int conversion for safety, in case a SymInt refined + # to constant + return RetVariable(tuple(int(r) for r in fake_r)) + else: + fake_r = getattr(fake, name)(dim) + if not has_free_symbols(fake_r): + return ConstantVariable.create(int(fake_r)) + return None + + def method_numel(self, tx: "InstructionTranslatorBase") -> VariableTracker | None: + if self.valid_size(): + return VariableTracker.build(tx, product(self.size)) + + # It might still be constant! Consult the fake tensor and see + if (fake := self.proxy.node.meta.get("example_value")) is not None: + fake_r = fake.numel() + if not has_free_symbols(fake_r): + return VariableTracker.build(tx, int(fake_r)) + return None + + method_nelement = method_numel + + def method_dim(self, tx: "InstructionTranslatorBase") -> VariableTracker | None: + if self.ndim is not None: + return VariableTracker.build(tx, self.ndim) + return None + + method_ndimension = method_dim + + def method_is_floating_point( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable | None: + if self.dtype is not None: + return VariableTracker.build(tx, self.dtype.is_floating_point) + return None + + def method_is_inference( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable | None: + if config.fake_tensor_disable_inference_mode: + unimplemented( + gb_type="Encountered tensor.is_inference() during tracing", + context="", + explanation="tensor.is_inference() is not supported", + hints=[ + *graph_break_hints.FUNDAMENTAL, + *graph_break_hints.INFERENCE_MODE, + ], + ) + if (fake := self.proxy.node.meta.get("example_value")) is not None: + return VariableTracker.build(tx, fake.is_inference()) + return None + + def method_is_complex( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable | None: + if self.dtype is not None: + return VariableTracker.build(tx, self.dtype.is_complex) + return None + + def method_is_contiguous( + self, + tx: "InstructionTranslatorBase", + memory_format: VariableTracker | None = None, + ) -> ConstantVariable | None: + memory_format_const = ( + memory_format.as_python_constant() + if memory_format is not None + else torch.contiguous_format + ) + if self.is_contiguous is not None: + # pyrefly: ignore[not-iterable] + return VariableTracker.build(tx, memory_format_const in self.is_contiguous) + elif (fake := self.proxy.node.meta.get("example_value")) is not None: + return VariableTracker.build( + tx, fake.is_contiguous(memory_format=memory_format_const) + ) + return None + + def method_type( + self, + tx: "InstructionTranslatorBase", + dtype: Any | None = None, + non_blocking: bool = False, + **kwargs: Any, + ) -> VariableTracker | None: + if ( + dtype is None + and self.dtype is not None + and isinstance(self.device, torch.device) + ): + tensortype = next( + k for k, v in tensortype_to_dtype.items() if self.dtype in v + ) + if self.device.type == "cpu": + return VariableTracker.build(tx, f"torch.{tensortype.__name__}") + else: + return VariableTracker.build( + tx, f"torch.{self.device.type}.{tensortype.__name__}" + ) + elif ( + dtype is not None + and fqn(type(dtype.as_python_constant())) == "torch.tensortype" + ): + # torch.FloatTensor, etc. are all of type "torch.tensortype". + # torch.fx's tracer fails on these types, because it doesn't support arguments of torch.tensortype type. + # So, we pass it in as a string (which is also supported, see above implementation for .type() with 0 args) + tensor_type = dtype.as_python_constant() + tensor_type_const = VariableTracker.build(tx, fqn(tensor_type)) + + from .builder import wrap_fx_proxy + + if non_blocking: + kwargs = {"non_blocking": non_blocking, **kwargs} + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_method", + "type", + *proxy_args_kwargs([self, tensor_type_const], kwargs), + ), + ) + return None + + def method_as_subclass( + self, tx: "InstructionTranslatorBase", cls: VariableTracker + ) -> "TensorWithTFOverrideVariable": + if isinstance(cls, TensorSubclassVariable) and cls.source: + from .torch_function import TensorWithTFOverrideVariable + + py_cls = cls.as_python_constant() + var = TensorWithTFOverrideVariable.from_tensor_var( + tx, self, py_cls, cls.source + ) + # See NOTE [Side effect tracking for newly constructed tensor] + tx.output.side_effects._track_obj( + object(), var, mutation_type_cls=AttributeMutationNew + ) + return var + unimplemented( + gb_type="Argument of `as_subclass` must be a non-dispatcher-style tensor subclass", + context=f"{self}.as_subclass({cls})", + explanation="Currently not supported", + hints=[ + "Avoid this call or move it outside `torch.compile` region", + *graph_break_hints.SUPPORTABLE, + ], + ) + + def method_get_device( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker | None: + if isinstance(self.device, torch.device): + index = self.device.index if self.device.type != "cpu" else -1 + return VariableTracker.build(tx, index) + return None + + def method_element_size(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return VariableTracker.build(tx, self.dtype.itemsize) + + def method_numpy( + self, tx: "InstructionTranslatorBase", *, force: VariableTracker | bool = False + ) -> "NumpyNdarrayVariable": + if not config.trace_numpy: + unimplemented( + gb_type="Tensor.numpy() with trace_numpy=False", + context=f"call_method {self} numpy", + explanation="`Tensor.numpy()` was called, but the `trace_numpy` " + "configuration was manually disabled.", + hints=[ + "Set `torch._dynamo.config.trace_numpy = True` to allow " + "Dynamo to trace through NumPy.", + ], + ) + if not np: + unimplemented( + gb_type="Tensor.numpy() without NumPy installed", + context=f"call_method {self} numpy", + explanation="`Tensor.numpy()` was called, but the NumPy library " + "is not available in the current environment.", + hints=[ + "Ensure NumPy is installed in your Python environment.", + ], + ) + if self.layout != torch.strided: + raise TypeError( + f"can't convert {self.layout} layout tensor to numpy. Use Tensor.to_dense() first" + ) + + # We don't check that the tensor is on CPU when force is False, as this + # allows us to execute NumPy code on CUDA. Same for requires_grad=True + if force and force.as_python_constant(): # type: ignore[attr-defined] + # If the user set force=True we try to preserve the semantics (no gradients, move to CPU...) + t = self.call_method(tx, "detach", [], {}) + proxy = tx.output.create_proxy("call_method", "cpu", (t.as_proxy(),), {}) + else: + # Hacky way to create a view of self that will be marked as NumpyNdarrayVariable + proxy = tx.output.create_proxy( + "call_method", "view_as", *proxy_args_kwargs([self, self], {}) + ) + return NumpyNdarrayVariable.create(tx, proxy) + + def method_tolist(self, tx: "InstructionTranslatorBase") -> VariableTracker: + from .builder import wrap_fx_proxy + + def tolist(tensor: torch.Tensor, sub_proxy: torch.fx.Proxy) -> Any | list[Any]: + def wrap(i: Any, sub_proxy: torch.fx.Proxy) -> VariableTracker: + return wrap_fx_proxy( + tx, + sub_proxy.item(), + ) + + if tensor.dtype not in [ + torch.int8, + torch.int16, + torch.int32, + torch.int64, + ]: + unimplemented( + gb_type="Tensor.tolist() with non-integer tensor", + context=f"call_method {self} to_list", + explanation="Dynamo currently does not support tracing " + "`tolist()` on non-integer tensors.", + hints=[ + "Ensure the input tensor to `tolist()` is an integer " + "type (e.g., int8, int16, int32, int64)." + ], + ) + + if tensor.dim() == 0: + return wrap(tensor, sub_proxy) + + if tensor.dim() == 1: + return [wrap(val, sub_proxy[i]) for i, val in enumerate(tensor)] + + return [ + tolist(sub_tensor, sub_proxy=sub_proxy[i]) + for i, sub_tensor in enumerate(tensor) + ] + + tensor = self.as_proxy().node.meta["example_value"] + out = tolist(tensor, self.as_proxy()) + return VariableTracker.build(tx, out) + + def _collect_backward_inputs( + self, vars_iter: Iterable[VariableTracker], error_on_non_leaf: bool = False + ) -> list[VariableTracker] | None: + """ + Collect unique leaf tensors from vars_iter for backward. + + Only collects leaf tensors (no grad_fn). Non-leaf tensors are skipped + (or error if error_on_non_leaf=True) because when auto-detecting inputs, + we must not stop gradients at non-leafs - they are intermediates, and the + real leaf tensors (parameters) are further up the autograd graph. + + Deduplicates by proxy.node. + Returns list of unique leaf tensor variables. + """ + from ..source import SyntheticLocalSource + + result = [] + seen_nodes: set[torch.fx.Node] = set() + for var in vars_iter: + if isinstance(var, TensorVariable) and var.requires_grad: + # Non-leaf tensors (has_grad_fn=True) must be skipped because: + # 1. Semantically: they're intermediates, not the leaves we want gradients for + # 2. Implementation: the backward rewrite can't handle .grad on non-leafs + # (Dynamo creates GetAttrVariable instead of TensorVariable) + # + # In-graph created tensors without proper source also can't be handled + # when user explicitly passes them as inputs, because + # subguards_allowed() returns False for SyntheticLocalSource. + # However, in auto-detect mode (error_on_non_leaf=False), source-less + # leaves are valid backward targets — they gained requires_grad via + # requires_grad_() and accumulate_grad_ writes to .grad directly. + if var.has_grad_fn: + if error_on_non_leaf: + unimplemented( + gb_type="backward() with non-leaf tensor", + context=f"backward(inputs=[...]) with non-leaf tensor: {var}", + explanation="backward(inputs=[...]) with non-leaf tensors is not yet supported.", + hints=[ + "Only pass leaf tensors (parameters, graph inputs) to backward(inputs=...)", + ], + ) + elif error_on_non_leaf and ( + not var.source or isinstance(var.source, SyntheticLocalSource) + ): + unimplemented( + gb_type="backward() with in-graph created tensor", + context=f"backward(inputs=[...]) with in-graph created tensor: {var}", + explanation="backward(inputs=[...]) with tensors created inside the " + "compiled function is not yet supported.", + hints=[ + "Only pass tensors that are inputs to the compiled function or captured from outside", + ], + ) + else: + node = var.proxy.node + if node not in seen_nodes: + seen_nodes.add(node) + result.append(var) + # pyrefly: ignore [bad-return] + return result + + def method_backward( + self, + tx: "InstructionTranslatorBase", + gradient: VariableTracker | None = None, + retain_graph: VariableTracker | None = None, + create_graph: VariableTracker | None = None, + inputs: VariableTracker | None = None, + ) -> VariableTracker | None: + """ + Trace tensor.backward() by rewriting as autograd.grad() + accumulate_grad. + + Implementation: + 1. Collect leaf tensors to compute gradients for + 2. Call autograd.grad(loss, inputs) to compute gradients + 3. For each leaf tensor, call accumulate_grad to update .grad + + Non-leaf tensor handling: + - Auto-detect (inputs=None): Non-leaf tensors are silently skipped. + This matches eager where only leaves get .grad. + - User-provided (inputs=[...]): Errors if any non-leaf tensor is found. + While eager backward(inputs=[non_leaf]) works, Dynamo cannot trace it + because the backward rewrite accesses .grad, and Dynamo creates + a generic GetAttrVariable for .grad on non-leaf tensors (instead of a + TensorVariable), which cannot be used in tensor operations. + + TODO: Support non-leaf tensors by fixing .grad access on non-leaf in Dynamo. + """ + if not config.trace_autograd_ops: + unimplemented( + gb_type="Unsupported Tensor.backward() call", + context=f"call_method {self} backward {gradient} {retain_graph} {create_graph} {inputs}", + explanation="Dynamo currently does not support tracing `Tensor.backward()` when trace_autograd_ops is off.", + hints=["Set torch._dynamo.trace_autograd_ops=True"], + ) + + if not self.requires_grad and not self.has_grad_fn: + raise TorchRuntimeError( + "tensor does not require grad and does not have a grad_fn" + ) + + # Step 1: Collect leaf tensors to compute gradients for + # + # Note: We rely on the autograd.grad handler to validate that the generated + # autograd.grad call is legal (i.e., doesn't traverse external grad_fns). + # If the loss depends on leaves we don't know about, the autograd.grad + # handler will catch it via the external_grad_fns check. + auto_detect = inputs is None + if auto_detect: + # Sources can be either user inputs (params are included here) + # or parameters that are created in forward. + all_vars = chain( + tx.output.leaf_var_creation_order, + tx.output.input_source_to_var.values(), + ) + input_vars = self._collect_backward_inputs(all_vars) + if not input_vars: + # No leaf tensors found - nothing to accumulate gradients into. + # This matches eager behavior where backward() is a no-op if there + # are no leaves requiring grad. + return ConstantVariable.create(None) + else: + if isinstance(inputs, variables.BaseListVariable): + provided_vars = inputs.items + elif isinstance(inputs, variables.ConstDictVariable): + provided_vars = list(inputs.items.values()) + else: + provided_vars = [inputs] + input_vars = self._collect_backward_inputs( + provided_vars, error_on_non_leaf=True + ) + if not input_vars: + # User explicitly provided inputs but none were valid leaf tensors. + # This would cause "grad requires non-empty inputs" error at runtime. + unimplemented( + gb_type="backward() with empty inputs", + context="backward(inputs=[...]) resulted in no valid leaf tensors", + explanation="backward(inputs=[...]) requires at least one valid leaf tensor.", + hints=[ + "Ensure at least one tensor in inputs is a leaf (requires_grad=True, no grad_fn)", + ], + ) + + # Build autograd.grad call + grad_kwargs = {"allow_unused": VariableTracker.build(tx, auto_detect)} + if retain_graph is not None: + grad_kwargs["retain_graph"] = retain_graph + if create_graph is not None: + grad_kwargs["create_graph"] = create_graph + + inputs_var = VariableTracker.build(tx, input_vars) + grad_args = [self, inputs_var] + if gradient is not None: + grad_args.append(gradient) + + autograd_grad_fn = VariableTracker.build(tx, torch.autograd.grad) + grads_var = autograd_grad_fn.call_function(tx, grad_args, grad_kwargs) + + # Accumulate gradients for unique leaf tensors under no_grad context + # to replicate eager autograd engine. + from .ctx_manager import GradModeVariable + + grad_mode_var = GradModeVariable.create(tx, False, initialized=True) + grad_mode_var.enter(tx) + + accumulate_grad_fn = VariableTracker.build( + tx, torch.ops.inductor.accumulate_grad_.default + ) + if input_vars is None: + raise AssertionError("input_vars must not be None") + for idx, input_var in enumerate(input_vars): + grad_i = grads_var.call_method( + tx, "__getitem__", [VariableTracker.build(tx, idx)], {} + ) + accumulate_grad_fn.call_function(tx, [input_var, grad_i], {}) + + grad_mode_var.exit(tx) + + return ConstantVariable.create(None) + + def method_data_ptr( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> "DataPtrVariable": + return DataPtrVariable(self) + + def method_const_data_ptr( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> "DataPtrVariable": + return DataPtrVariable(self, method_name="const_data_ptr") + + def method_record_stream( + self, + tx: "InstructionTranslatorBase", + stream: VariableTracker, + ) -> VariableTracker: + from .streams import StreamVariable + + if not isinstance(stream, StreamVariable): + raise RuntimeError( + f"record_stream() expects a Stream argument, got {stream.python_type().__name__}" + ) + tx.output.create_proxy( + "call_function", + torch.ops.streams.record_stream, + (self.as_proxy(), stream.user_object_index), + {}, + ) + return ConstantVariable.create(None) + + def method_item( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> None: + # We enable capture_scalar_outputs when full_graph=True by default. + if not tx.one_graph and not config.capture_scalar_outputs: + self._warn_capture_scalar_outputs() + unimplemented( + gb_type="Unsupported Tensor.item() call with capture_scalar_outputs=False", + context=f"call_method {self} item {args} {kwargs}", + explanation="Dynamo does not support tracing `Tensor.item()` " + "with config.capture_scalar_outputs=False.", + hints=[ + "Set `torch._dynamo.config.capture_scalar_outputs = True` " + "or `export TORCHDYNAMO_CAPTURE_SCALAR_OUTPUTS=1` " + "to include these operations in the captured graph.", + ], + ) + return None + + def nb_index_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # CPython: only integer tensors of a single element can be converted + # to an index. Mirrors THPVariable_index_scalar in + # https://github.com/pytorch/pytorch/blob/7cfd054075b/tools/autograd/templates/python_variable_methods.cpp#L372-L385 + if self.dtype is not None and ( + not self.dtype.is_floating_point and not self.dtype.is_complex + ): + item = self.call_method(tx, "item", [], {}) + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + sym_int, + (item.as_proxy(),), + {}, + ), + ) + raise_observed_exception( + TypeError, + tx, + args=[ + "only integer tensors of a single element can be converted to an index" + ], + ) + + def nb_int_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # CPython: THPVariable_integral_scalar handles both integer and float + # tensors (floats are truncated to int). Complex tensors raise + # RuntimeError at runtime. + if self.dtype is not None and self.dtype.is_complex: + raise_observed_exception( + RuntimeError, + tx, + args=["value cannot be converted to type int64_t without overflow"], + ) + # For known non-complex dtypes and unknown dtype (None), emit the + # proxy and let it fail at runtime if the dtype is unsupported. + item = self.call_method(tx, "item", [], {}) + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + sym_int, + (item.as_proxy(),), + {}, + ), + ) + + def method___int__(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.nb_int_impl(tx) + + def nb_float_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # CPython: THPVariable_float_scalar dispatches to double. + # Complex tensors raise RuntimeError at runtime. + if self.dtype is not None and self.dtype.is_complex: + raise_observed_exception( + RuntimeError, + tx, + args=["value cannot be converted to type double without overflow"], + ) + item = self.call_method(tx, "item", [], {}) + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + sym_float, + (item.as_proxy(),), + {}, + ), + ) + + def method___float__(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.nb_float_impl(tx) + + def nb_negative_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", + operator.neg, + (self.as_proxy(),), + {}, + ), + ) + + def method___neg__(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.nb_negative_impl(tx) + + def nb_positive_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", + operator.pos, + (self.as_proxy(),), + {}, + ), + ) + + def method___pos__(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.nb_positive_impl(tx) + + def nb_absolute_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", + operator.abs, + (self.as_proxy(),), + {}, + ), + ) + + def method___abs__(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.nb_absolute_impl(tx) + + def nb_invert_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", + operator.invert, + (self.as_proxy(),), + {}, + ), + ) + + def method___invert__(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.nb_invert_impl(tx) + + def method___getitem__( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + if isinstance(args[0], SymNodeVariable): + # Standard indexing will force specialization due to + # __index__. Rewrite as a regular torch op which will + # trace fine + fn, args = ( # type: ignore[assignment] + torch.select, + [ + VariableTracker.build(tx, 0), + args[0], + ], + ) + else: + fn = operator.getitem + + proxy = tx.output.create_proxy( + "call_function", + fn, + *proxy_args_kwargs([self] + list(args), kwargs), + ) + + return wrap_fx_proxy(tx, proxy) + + @staticmethod + @functools.cache + def _warn_capture_scalar_outputs() -> None: + user_stack = torch._guards.TracingContext.extract_stack() + user_stack_formatted = "".join(traceback.format_list(user_stack)) + log.warning( + textwrap.dedent( + """\ + Graph break from `Tensor.item()`, consider setting: + torch._dynamo.config.capture_scalar_outputs = True + or: + env TORCHDYNAMO_CAPTURE_SCALAR_OUTPUTS=1 + to include these operations in the captured graph. + + Graph break: from user code at: + %s + """ + ), + user_stack_formatted, + ) + + def method___len__(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.sq_length_impl(tx) + + def sq_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + """Sequence length for tensors (size along first dimension).""" + return self.call_method(tx, "size", [VariableTracker.build(tx, 0)], {}) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return ListIteratorVariable( + self.unpack_var_sequence(tx), mutation_type=ValueMutationNew() + ) + + def method___iter__(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.tp_iter_impl(tx) + + def method_addcmul_( + self, + tx: "InstructionTranslatorBase", + tensor1: Any, + tensor2: Any, + *, + value: Any | None = None, + ) -> Any | None: + if value is not None and config.enable_dynamo_decompositions: + from torch._inductor import inductor_prims + + mul_var = variables.TorchInGraphFunctionVariable(torch.mul) + fma_var = variables.TorchInGraphFunctionVariable(inductor_prims.fma) + product = mul_var.call_function(tx, [tensor1, tensor2], {}) + result = fma_var.call_function(tx, [product, value, self], {}) + return self.call_method(tx, "copy_", [result], {}) + return None + + def mp_ass_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + if value is None: + raise_type_error(tx, "Tensor does not support deleting items") + return self.method___setitem__(tx, key, value) + + def method___setitem__( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + value: VariableTracker, + ) -> VariableTracker: + proxy = tx.output.create_proxy( + "call_function", + operator.setitem, + *proxy_args_kwargs([self, key, value], {}), + ) + + # See Note [Inplace ops and VariableTracker metadata] + # __setitem__ is always an inplace operation. We need to run fake execution + # and propagate metadata if self was mutated. + # The context managers handle saved tensor hooks and unbacked symbols. + version_before = self._get_fake_version() + + with ( + torch._dynamo.utils._disable_saved_tensors_hooks_during_tracing(), + tx.fake_mode.shape_env.ignore_fresh_unbacked_symbols() + if tx.fake_mode and tx.fake_mode.shape_env + else nullcontext(), + ): + get_fake_value(proxy.node, tx, allow_non_graph_fake=False) + + self._sync_if_inplace_mutation(tx, version_before) + + if config.use_graph_deduplication or config.track_nodes_for_deduplication: + tx.output.region_tracker.add_node_mutation(proxy.node, 0) + + return ConstantVariable.create(None) + + def method_resize_( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> NoReturn: + unimplemented( + gb_type="Unsupported Tensor.resize_() call", + context=f"call_method {self} resize_ {args} {kwargs}", + explanation="Dynamo currently does not support tracing `Tensor.resize_()`.", + hints=[], + ) + + def method_resize_as_( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> NoReturn: + unimplemented( + gb_type="Unsupported Tensor.resize_as_() call", + context=f"call_method {self} resize_as_ {args} {kwargs}", + explanation="Dynamo currently does not support tracing `Tensor.resize_as_()`.", + hints=[], + ) + + def method_sparse_resize_( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> NoReturn: + unimplemented( + gb_type="Unsupported Tensor.sparse_resize_() call", + context=f"call_method {self} sparse_resize_ {args} {kwargs}", + explanation="Dynamo currently does not support tracing `Tensor.sparse_resize_()`.", + hints=[], + ) + + def method_sparse_resize_and_clear_( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> NoReturn: + unimplemented( + gb_type="Unsupported Tensor.sparse_resize_and_clear_() call", + context=f"call_method {self} sparse_resize_and_clear_ {args} {kwargs}", + explanation="Dynamo currently does not support tracing `Tensor.sparse_resize_and_clear_()`.", + hints=[], + ) + + def method_set_( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> None: + if len(args) > 1: + # torch.Tensor.set_() has several overloads. + # aten::set_.source_Tensor(Tensor) gets special handling + # in AOTAutograd and functionalization, because it is the most common + # overload and is used by FSDP. + # graph-breaking on aten::set_source_Tensor_storage_offset for now, + # unless we find that we need to make it work. + unimplemented( + gb_type="Unsupported Tensor.set_() call", + context=f"call_method {self} set_ {args} {kwargs}", + explanation="Dynamo currently does not support tracing `Tensor.set_()` " + "overloads that include more than one argument.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + return None + + def method_add_( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + *, + alpha: VariableTracker | None = None, + ) -> VariableTracker | None: + # Tensor alpha: ATen would call .item() and fma internally. + # Use fma directly to avoid the item() graph break. + if ( + alpha is not None + and isinstance(alpha, TensorVariable) + and config.enable_dynamo_decompositions + ): + from torch._inductor import inductor_prims + + fma_var = variables.TorchInGraphFunctionVariable(inductor_prims.fma) + result = fma_var.call_function(tx, [other, alpha, self], {}) + return self.call_method(tx, "copy_", [result], {}) + return None + + def method_addcdiv_( + self, + tx: "InstructionTranslatorBase", + tensor1: "TensorVariable", + tensor2: "TensorVariable", + *, + value: VariableTracker | None = None, + ) -> VariableTracker | None: + if value is not None and config.enable_dynamo_decompositions: + result = variables.TorchInGraphFunctionVariable(torch.div).call_function( + tx, [tensor1, tensor2], {} + ) + from torch._inductor import inductor_prims + + fma_var = variables.TorchInGraphFunctionVariable(inductor_prims.fma) + fma_result = fma_var.call_function(tx, [result, value, self], {}) + return self.call_method(tx, "copy_", [fma_result], {}) + return None + + def sq_contains_impl( + self, tx: "InstructionTranslatorBase", item: VariableTracker + ) -> VariableTracker: + # Rewrite __contains__ here so that downstream passes can trace through + # without dealing with unbacked symbool. Roughly the code we translate is: + # def __contains__(self, x): + # return (x == self).any().item() + result = variables.TorchInGraphFunctionVariable(torch.eq).call_function( + tx, [self, item], {} + ) + result = variables.TorchInGraphFunctionVariable(torch.any).call_function( + tx, [result], {} + ) + return result.call_method(tx, "item", [], {}) + + def method___contains__( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + return self.sq_contains_impl(tx, arg) + + def method_register_hook( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + return self._method_register_hook(tx, "register_hook", *args, **kwargs) + + def method_register_post_accumulate_grad_hook( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + return self._method_register_hook( + tx, "register_post_accumulate_grad_hook", *args, **kwargs + ) + + def _method_register_hook( + self, tx: "InstructionTranslatorBase", name: str, hook: VariableTracker + ) -> VariableTracker: + # Note - do not arbitrarily add hooks here - make sure they match the same contract + # see [On tensor.register_hook] + + if not self.source: + # For intermediate tensors (those without a source), we have two approaches: + # 1. When compiled autograd is enabled: use BackwardState to defer hook execution + # 2. When compiled autograd is NOT enabled: use a custom autograd function + if compiled_autograd.compiled_autograd_enabled: + # Use the BackwardState approach for compiled autograd + hook_name, bw_state_proxy = tx.output.add_backward_state_hook(hook) + + def _register_hook_trampoline( + tensor: torch.Tensor, bw_state: compiled_autograd.BackwardState + ) -> None: + register_hook = getattr(tensor, name) + register_hook( + functools.partial( + trace_wrapped, + fn=call_hook_from_backward_state, + bw_state=bw_state, + hook_name=hook_name, + ) + ) + # TODO(jansel): returning None here is wrong, it should be + # RemovableHandle, but we need some extra work to support + # this properly. + return None + + from .builder import wrap_fx_proxy + + self_proxy = self.as_proxy() + self_proxy.node.meta["has_backward_hook"] = True + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", + _register_hook_trampoline, + (self_proxy, bw_state_proxy), + {}, + ), + ) + # Register the hook via a trampoline in the graph where the + # tensor's proxy lives. During AOTAutograd's make_fx, the + # trampoline calls tensor.register_hook(hook_fn). The hook + # fires on the accumulated gradient during backward + # tracing, matching eager semantics. When inside a subgraph + # (e.g. checkpoint), the node is created in the parent + # graph so the hook is not confined to the HOP scope. + from .higher_order_ops import speculate_subgraph + + tensor_proxy = self.as_proxy() + target_tracer = tensor_proxy.tracer + + # Trace the hook body with strict mode so stride-dependent + # operations (e.g. is_contiguous()) graph break instead of + # silently specializing on the FakeTensor's strides. + try: + with tx.strict_translation_mode(lambda v: v.is_tensor()): + (body_r, _), hook_graph, hook_freevars = speculate_subgraph( + tx, + hook, + [self], + {}, + "register_hook", + source_target=None, + enable_grad=None, + set_subgraph_inputs="automatic_with_forced_inputs", + restore_side_effects=True, + ) + except torch._dynamo.exc.UnknownPropertiesDuringBackwardTrace: + unimplemented( + gb_type="register_hook with stride-dependent code", + context="Hook accesses grad metadata (e.g. is_contiguous)", + explanation="register_hook callbacks that branch on " + "gradient metadata are not supported because grad " + "properties are unknown at trace time.", + hints=[], + ) + + hook_nn_modules = tx.output.tracing_context.module_context.copy_graphstate() + hook_name = tx.output.install_subgraph( + "hook_body", + torch.fx.GraphModule(hook_nn_modules.nn_modules, hook_graph), + ) + hook_node = target_tracer.create_proxy("get_attr", hook_name, (), {}) + + from torch._higher_order_ops.register_hook import register_hook_op + + p_args = (tensor_proxy, hook_node, *list(hook_freevars.keys())) + hooked_proxy = target_tracer.create_proxy( + "call_function", + register_hook_op, + tuple(p_args), + {}, + ) + hooked_proxy.node.meta["example_value"] = tensor_proxy.node.meta[ + "example_value" + ] + self.proxy = hooked_proxy + self.synchronize_attributes(tx) + return variables.RemovableHandleVariable( + mutation_type=variables.base.ValueMutationNew(), + ) + + handle_variable = variables.RemovableHandleVariable( + mutation_type=variables.base.ValueMutationNew(), + ) + tx.output.side_effects.register_hook(self, hook, handle_variable, name) + return handle_variable + + def method_requires_grad_( + self, + tx: "InstructionTranslatorBase", + requires_grad: bool | VariableTracker = True, + ) -> VariableTracker: + if requires_grad is not True: + requires_grad = requires_grad.as_python_constant() # type: ignore[attr-defined] + + node = self.as_proxy().node + example_value = node.meta["example_value"] + if example_value.requires_grad != requires_grad: + # For graph inputs (tensors with source), requires_grad_() is a + # metadata mutation that we can't trace — graph break as before. + if self.source: + unimplemented( + gb_type="Unsupported Tensor.requires_grad_() call", + context=f"call_method {self} requires_grad_", + explanation="Dynamo does not support changes to a Tensor's " + "`requires_grad` through calling `requires_grad_()`.", + hints=[], + ) + # On a previous attempt, we traced through requires_grad_() but + # discovered at compile time that the tainted intermediate leaked + # as a graph output. Graph break here to preserve partial + # acceleration for code before requires_grad_(). + if tx.speculation_log.graph_break_on_requires_grad_: + unimplemented( + gb_type="requires_grad_() intermediate leaked as output", + context=f"call_method {self} requires_grad_", + explanation="An intermediate tensor with requires_grad_() called " + "on it (or a tensor derived from it) is returned from the " + "compiled region. Graph breaking here to preserve partial " + "acceleration.", + hints=[ + "Call .detach() before returning if you only need values.", + "Consume the gradient inside the compiled function " + "(call backward() and use .grad), " + "or move requires_grad_() outside torch.compile.", + ], + ) + # AOTAutograd re-traces the FX graph under functorch transforms + # (functionalization). Functorch's checkSupportsInplaceRequiresGrad() + # rejects requires_grad_() when the dynamic layer stack is non-empty. + # We wrap the call with set_inplace_requires_grad_allowed(True) to + # bypass this check, matching GradInplaceRequiresGradCtxManagerVariable + # in ctx_manager.py (which handles the explicit context manager case). + # + # Lines below do two things in parallel: + # 1. Mutate trace-time state so example_value.requires_grad_() works + # 2. Emit FX nodes so the same toggle happens during AOTAutograd re-trace + prev_state = torch._C._functorch.get_inplace_requires_grad_allowed() + torch._C._functorch.set_inplace_requires_grad_allowed(True) + try: + tx.output.create_node( + "call_function", + torch._C._functorch.set_inplace_requires_grad_allowed, + (True,), + {}, + ) + tx.output.create_proxy( + "call_method", + "requires_grad_", + (self.as_proxy(),), + {}, + ) + tx.output.create_node( + "call_function", + torch._C._functorch.set_inplace_requires_grad_allowed, + (prev_state,), + {}, + ) + finally: + torch._C._functorch.set_inplace_requires_grad_allowed(prev_state) + example_value.requires_grad_(requires_grad) + self.requires_grad = requires_grad + if requires_grad: + tx.output.leaf_var_creation_order.append(self) + # For source-less intermediates, initialize .grad = None in + # side effects so the backward rewrite can read/write + # .grad naturally. Graph inputs don't need this — they handle + # .grad through their source. + if not self.source and tx.output.side_effects.is_attribute_mutation( + self + ): + tx.output.side_effects.store_attr( + self, "grad", variables.ConstantVariable.create(None) + ) + return self + + def method_detach_(self, tx: "InstructionTranslatorBase") -> "TensorVariable": + from .builder import wrap_fx_proxy + + proxy = tx.output.create_proxy( + "call_method", + "detach_", + (self.as_proxy(),), + {}, + ) + # Run the fake op so the proxy metadata reflects the detached tensor state. + wrap_fx_proxy(tx, proxy) + self.synchronize_attributes(tx) + return self + + def method_share_memory_(self, tx: "InstructionTranslatorBase") -> NoReturn: + unimplemented( + gb_type="Unsupported Tensor.share_memory_() call", + context=f"call_method {self} share_memory_", + explanation="Dynamo does not support Tensor.share_memory_() which modifies tensor storage for IPC", + hints=[ + "Move share_memory_() call outside the compiled region. ", + *graph_break_hints.SUPPORTABLE, + ], + ) + + def method_new( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + # Convert x.new(torch.Size) into x.new_empty(torch.Size), + # as Tensor.new acts differently with a Size input versus a tuple input. + if (len(args) == 1 and isinstance(args[0], SizeVariable)) or ( + len(args) >= 1 + and all( + a.is_python_constant() and isinstance(a.as_python_constant(), int) + for a in args + ) + ): + return self.call_method(tx, "new_empty", list(args), kwargs) + return None + + def method_new_tensor( + self: "TensorVariable", + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + if len(args) != 1: + return None + data_arg = args[0] + layout = kwargs.get("layout") + if layout is not None: + if not layout.is_python_constant(): + return None + if layout.as_python_constant() != torch.strided: + return None + fwd_kwargs = dict(kwargs) + fwd_kwargs.pop("layout", None) + fwd_kwargs.setdefault("dtype", self.tp_getattro_impl(tx, "dtype")) + fwd_kwargs.setdefault("device", self.tp_getattro_impl(tx, "device")) + return variables.TorchInGraphFunctionVariable(torch.tensor).call_function( + tx, + [data_arg], + fwd_kwargs, + ) + + def method_untyped_storage( + self, tx: "InstructionTranslatorBase" + ) -> "UntypedStorageVariable": + return UntypedStorageVariable( + self, self.as_proxy().node.meta["example_value"].untyped_storage() + ) + + def method_wait( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if args or kwargs: + raise torch._dynamo.exc.InternalTorchDynamoError( + "`wait` and `wait_tensor` do not take any arguments" + ) + from torch.distributed._functional_collectives import wait_tensor + + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", wait_tensor, (self.as_proxy(),), {} + ), + ) + + def method_random_( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> NoReturn: + # For historical reasons, these ops decompose down to syntactically + # invalid aten ops because they contain the python keyword `from`, see + # discussions in #151432 for more details. + # We graph break for now since this use case is uncommon. + unimplemented( + gb_type="Tensor.random_ op", + context=f"Tensor.random_({args=}, {kwargs=})", + explanation="This is currently not supported.", + hints=[ + "Use the out-of-place version of this op", + *graph_break_hints.SUPPORTABLE, + ], + ) + + def method_uniform_( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + if "from" in kwargs: + unimplemented( + gb_type="Tensor.uniform_ op called with `from` keyword", + context=f"Tensor.uniform_({args=}, {kwargs=})", + explanation="This is currently not supported.", + hints=[ + "Avoid using the `from` keyword.", + *graph_break_hints.SUPPORTABLE, + ], + ) + return None + + # Named-method dispatch table (see call_method). Each entry mirrors a + # CPython PyMethodDef: the handler keeps its native Python signature and + # `flags` (ml_flags) drive centralized arity checking. Tensor methods + # without an entry fall through to the generic FX-proxy path in call_method. + tp_methods = { + "size": Method(method_size), + "stride": Method(method_stride), + "numel": Method(method_numel), + "nelement": Method(method_nelement), + "dim": Method(method_dim), + "ndimension": Method(method_ndimension), + "is_floating_point": Method(method_is_floating_point), + "is_inference": Method(method_is_inference), + "is_complex": Method(method_is_complex), + "is_contiguous": Method(method_is_contiguous), + "type": Method(method_type), + "as_subclass": Method(method_as_subclass), + "get_device": Method(method_get_device), + "element_size": Method(method_element_size), + "numpy": Method(method_numpy), + "tolist": Method(method_tolist), + "backward": Method(method_backward), + "data_ptr": Method(method_data_ptr), + "const_data_ptr": Method(method_const_data_ptr), + "record_stream": Method(method_record_stream), + "item": Method(method_item), + "__int__": Method(method___int__), + "__float__": Method(method___float__), + "__neg__": Method(method___neg__), + "__pos__": Method(method___pos__), + "__abs__": Method(method___abs__), + "__invert__": Method(method___invert__), + "__getitem__": Method(method___getitem__), + "__len__": Method(method___len__), + "__iter__": Method(method___iter__), + "__setitem__": Method(method___setitem__), + "__contains__": Method(method___contains__), + "addcmul_": Method(method_addcmul_), + "addcdiv_": Method(method_addcdiv_), + "add_": Method(method_add_), + "resize_": Method(method_resize_), + "resize_as_": Method(method_resize_as_), + "sparse_resize_": Method(method_sparse_resize_), + "sparse_resize_and_clear_": Method(method_sparse_resize_and_clear_), + "set_": Method(method_set_), + "register_hook": Method(method_register_hook), + "register_post_accumulate_grad_hook": Method( + method_register_post_accumulate_grad_hook + ), + "requires_grad_": Method(method_requires_grad_), + "detach_": Method(method_detach_), + "share_memory_": Method(method_share_memory_), + "new": Method(method_new), + "new_tensor": Method(method_new_tensor), + "untyped_storage": Method(method_untyped_storage), + "wait": Method(method_wait), + "random_": Method(method_random_), + "uniform_": Method(method_uniform_), + } + + def set_name_hint(self, name: str) -> None: + if not self._is_name_set: + self.proxy.node._rename(name) + self._is_name_set = True + return None + + def nb_add_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1139 (PyNumber_Add) + from .builder import wrap_fx_proxy + + if not (isinstance(other, TensorVariable) or _is_sym_arith_operand(other)): + return VariableTracker.build(tx, NotImplemented) + args = [other, self] if reverse else [self, other] + proxy = tx.output.create_proxy( + "call_function", operator.add, *proxy_args_kwargs(args, {}) + ) + # Tensor dominates: any of Tensor+Tensor, Tensor+SymNode, Tensor+scalar + # produces a Tensor. + return wrap_fx_proxy(tx=tx, proxy=proxy) + + def nb_lshift_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + if not other.is_symnode_like(): + return VariableTracker.build(tx, NotImplemented) + lhs, rhs = (other, self) if reverse else (self, other) + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", operator.lshift, *proxy_args_kwargs([lhs, rhs], {}) + ), + ) + + def nb_rshift_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + if not other.is_symnode_like(): + return VariableTracker.build(tx, NotImplemented) + lhs, rhs = (other, self) if reverse else (self, other) + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", operator.rshift, *proxy_args_kwargs([lhs, rhs], {}) + ), + ) + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + if not other.is_symnode_like(): + return VariableTracker.build(tx, NotImplemented) + lhs, rhs = (other, self) if reverse else (self, other) + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", operator.or_, *proxy_args_kwargs([lhs, rhs], {}) + ), + ) + + def nb_and_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + if not other.is_symnode_like(): + return VariableTracker.build(tx, NotImplemented) + lhs, rhs = (other, self) if reverse else (self, other) + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", operator.and_, *proxy_args_kwargs([lhs, rhs], {}) + ), + ) + + def nb_xor_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + if not other.is_symnode_like(): + return VariableTracker.build(tx, NotImplemented) + lhs, rhs = (other, self) if reverse else (self, other) + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", operator.xor, *proxy_args_kwargs([lhs, rhs], {}) + ), + ) + + def nb_multiply_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # Reaches here only via direct ``tensor.__mul__(x)`` calls — the + # ``operator.mul`` path goes through ``_handle_insert_op_in_graph`` + # in ``BuiltinVariable``. Build the same FX proxy. + from .builder import wrap_fx_proxy + + lhs, rhs = (other, self) if reverse else (self, other) + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", operator.mul, *proxy_args_kwargs([lhs, rhs], {}) + ), + ) + + def nb_matrix_multiply_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # Reaches here only via direct ``tensor.__matmul__(x)`` calls. + from .builder import wrap_fx_proxy + + lhs, rhs = (other, self) if reverse else (self, other) + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", operator.matmul, *proxy_args_kwargs([lhs, rhs], {}) + ), + ) + + def nb_floor_divide_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # Reaches here only via direct ``tensor.__floordiv__(x)`` calls — the + # ``operator.floordiv`` path goes through ``_handle_insert_op_in_graph`` + # in ``BuiltinVariable``. Build the same FX proxy. + if not (isinstance(other, TensorVariable) or _is_sym_arith_operand(other)): + return VariableTracker.build(tx, NotImplemented) + from .builder import wrap_fx_proxy + + lhs, rhs = (other, self) if reverse else (self, other) + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", operator.floordiv, *proxy_args_kwargs([lhs, rhs], {}) + ), + ) + + def nb_true_divide_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # Reaches here only via direct ``tensor.__truediv__(x)`` calls — the + # ``operator.truediv`` path goes through ``_handle_insert_op_in_graph`` + # in ``BuiltinVariable``. Build the same FX proxy. + if not (isinstance(other, TensorVariable) or _is_sym_arith_operand(other)): + return VariableTracker.build(tx, NotImplemented) + from .builder import wrap_fx_proxy + + lhs, rhs = (other, self) if reverse else (self, other) + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", operator.truediv, *proxy_args_kwargs([lhs, rhs], {}) + ), + ) + + def nb_remainder_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # Reaches here only via direct ``tensor.__mod__(x)`` calls — the + # ``operator.mod`` path goes through ``_handle_insert_op_in_graph`` + # in ``BuiltinVariable``. Build the same FX proxy. + if not (isinstance(other, TensorVariable) or _is_sym_arith_operand(other)): + return VariableTracker.build(tx, NotImplemented) + from .builder import wrap_fx_proxy + + lhs, rhs = (other, self) if reverse else (self, other) + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", operator.mod, *proxy_args_kwargs([lhs, rhs], {}) + ), + ) + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # Tensor.__hash__ is `return id(self)`, so hash == id. + # Always use the FakeTensor identity so aliased tensors + # (e.g. y = x.add_(1)) hash consistently. + fake = self.as_proxy().node.meta["example_value"] + return id(fake), True + + def nb_subtract_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1135 (PyNumber_Subtract) + if not _is_sym_arith_operand(other): + return VariableTracker.build(tx, NotImplemented) + args = [other, self] if reverse else [self, other] + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.sub, *proxy_args_kwargs(args, {}) + ), + sym_num=None, + ) + + def nb_power_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + z: VariableTracker | None, + reverse: bool = False, + ) -> VariableTracker: + # Reaches here only via direct ``tensor.__pow__(x)`` calls — the + # ``operator.pow`` path goes through ``_handle_insert_op_in_graph`` + # in ``BuiltinVariable``. Build the same FX proxy. + if not (isinstance(other, TensorVariable) or _is_sym_arith_operand(other)) or z: + return VariableTracker.build(tx, NotImplemented) + from .builder import wrap_fx_proxy + + lhs, rhs = (other, self) if reverse else (self, other) + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", operator.pow, *proxy_args_kwargs([lhs, rhs], {}) + ), + ) + + +class SymNodeVariable(VariableTracker): + """ + Represents a symbolic scalar, either int, float or bool. This is most commonly used to + handle symbolic size computation, e.g., tensor.size(0), but it is also used to + handle logic like float_tensor.item() or unspecialized float inputs. + """ + + _nonvar_fields = { + "proxy", + "sym_num", + *VariableTracker._nonvar_fields, + } + + def debug_repr(self) -> str: + return repr(self.sym_num) + + @classmethod + def create( + cls, + tx: "InstructionTranslatorBase", + proxy: Any, + sym_num: Any | None = None, + **options: Any, + ) -> "VariableTracker": + if sym_num is None: + sym_num = get_fake_value(proxy.node, tx) + if "example_value" in proxy.node.meta: + if proxy.node.meta["example_value"] != sym_num: + raise AssertionError( + f"proxy example_value {proxy.node.meta['example_value']} != {sym_num}" + ) + set_example_value(proxy.node, sym_num) + + if isinstance(sym_num, (sympy.Integer, int, bool)): + sym_num = int(sym_num) if isinstance(sym_num, sympy.Integer) else sym_num + return VariableTracker.build(tx, sym_num) + + out = SymNodeVariable(proxy, sym_num, **options) + if proxy.node.op != "placeholder": + tx.output.current_tracer.record_proxyable_vt(out) + return out + + def __init__(self, proxy: Any, sym_num: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.proxy = proxy + # TODO: Should we allow non SymTypes here? Today it is allowed + self.sym_num = sym_num + self._tensor_var: TensorVariable | None = None + + def python_type(self) -> type: + if isinstance(self.sym_num, SymTypes): + return self.sym_num.node.pytype + else: + return type(self.sym_num) + + def is_symnode_like(self) -> bool: + return True + + def as_proxy(self) -> Any: + return self.proxy + + def nb_bool_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # long_bool / float_bool: non-zero check. SymBool is already boolean. + # https://github.com/python/cpython/blob/c09ccd9c429/Objects/longobject.c#L5200 + # https://github.com/python/cpython/blob/c09ccd9c429/Objects/floatobject.c#L853 + if isinstance(self.sym_num, torch.SymBool): + return self + if not isinstance(self.sym_num, (torch.SymInt, torch.SymFloat)): + raise AssertionError( + f"Expected SymInt or SymFloat, got {type(self.sym_num)}" + ) + return SymNodeVariable.create(tx, self.as_proxy() != 0) + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + """SymNode tp_richcompare: symbolic numeric comparison.""" + if not isinstance(other, (SymNodeVariable, ConstantVariable, TensorVariable)): + if op in ("__eq__", "__ne__"): + op_fn = cmp_name_to_op_mapping[op] + return VariableTracker.build(tx, op_fn(object(), None)) + return ConstantVariable.create(NotImplemented) + op_fn = cmp_name_to_op_mapping[op] + proxy = tx.output.create_proxy( + "call_function", op_fn, (self.as_proxy(), other.as_proxy()), {} + ) + return SymNodeVariable.create(tx, proxy, sym_num=None) + + def as_tensor(self, tx: "InstructionTranslatorBase", dtype: Any) -> TensorVariable: + if self._tensor_var is None: + self._tensor_var = VariableTracker.build( + tx, torch.scalar_tensor + ).call_function(tx, [self], {"dtype": VariableTracker.build(tx, dtype)}) + return self._tensor_var + + def evaluate_expr( + self, output_graph: Optional["OutputGraph"] = None + ) -> bool | int | float: + try: + return guard_scalar(self.sym_num) + except GuardOnDataDependentSymNode as e: + if torch.fx.experimental._config.no_data_dependent_graph_break: + raise + + raise UserError( # noqa: B904 + UserErrorType.ANTI_PATTERN, + f"Consider annotating your code using torch._check*(). {str(e)}", + case_name="constrain_as_size_example", + ) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_method", + name, + *proxy_args_kwargs([self, *args], kwargs), + ), + ) + + def nb_index_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # SymInt / SymBool define __index__ as `self.node.int_()`, which + # specializes the symbolic value to a concrete int (with guard). + # SymFloat has no __index__. + # ref: torch/__init__.py SymInt.__index__ / SymBool.__index__ + + pytype = self.python_type() + if pytype in (int, bool): + return variables.ConstantVariable.create(self.evaluate_expr()) + return super().nb_index_impl(tx) + + def nb_int_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # SymInt.__int__: https://github.com/pytorch/pytorch/blob/ee336ca5440939b8ad65e916d47421f849e56178/torch/__init__.py#L462 + # SymFloat.__int__: https://github.com/pytorch/pytorch/blob/ee336ca5440939b8ad65e916d47421f849e56178/torch/__init__.py#L682 + # SymBool.__int__: https://github.com/pytorch/pytorch/blob/ee336ca5440939b8ad65e916d47421f849e56178/torch/__init__.py#L784 + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + sym_int, + (self.as_proxy(),), + {}, + ), + ) + + def method___int__( + self, tx: "InstructionTranslatorBase", *args: Any, **kwargs: Any + ) -> VariableTracker: + return self.nb_int_impl(tx) + + def nb_add_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1139 (PyNumber_Add) + if not _is_sym_arith_operand(other): + return VariableTracker.build(tx, NotImplemented) + args = [other, self] if reverse else [self, other] + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.add, *proxy_args_kwargs(args, {}) + ), + sym_num=None, + ) + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + if not other.is_symnode_like(): + return VariableTracker.build(tx, NotImplemented) + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.or_, *proxy_args_kwargs([self, other], {}) + ), + sym_num=None, + ) + + def nb_and_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + if not other.is_symnode_like(): + return VariableTracker.build(tx, NotImplemented) + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.and_, *proxy_args_kwargs([self, other], {}) + ), + sym_num=None, + ) + + def nb_xor_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + if not other.is_symnode_like(): + return VariableTracker.build(tx, NotImplemented) + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.xor, *proxy_args_kwargs([self, other], {}) + ), + sym_num=None, + ) + + def nb_lshift_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + if not other.is_symnode_like(): + return VariableTracker.build(tx, NotImplemented) + args = [other, self] if reverse else [self, other] + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.lshift, *proxy_args_kwargs(args, {}) + ), + sym_num=None, + ) + + def nb_rshift_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + if not other.is_symnode_like(): + return VariableTracker.build(tx, NotImplemented) + args = [other, self] if reverse else [self, other] + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.rshift, *proxy_args_kwargs(args, {}) + ), + sym_num=None, + ) + + def nb_subtract_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1135 (PyNumber_Subtract) + if not _is_sym_arith_operand(other): + return VariableTracker.build(tx, NotImplemented) + args = [other, self] if reverse else [self, other] + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.sub, *proxy_args_kwargs(args, {}) + ), + sym_num=None, + ) + + def nb_multiply_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # sequence * sym_node must go through sq_repeat and not nb_multiply + if not _is_sym_arith_operand(other): + return VariableTracker.build(tx, NotImplemented) + lhs, rhs = (other, self) if reverse else (self, other) + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.mul, *proxy_args_kwargs([lhs, rhs], {}) + ), + sym_num=None, + ) + + def nb_floor_divide_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + if not _is_sym_arith_operand(other): + return VariableTracker.build(tx, NotImplemented) + lhs, rhs = (other, self) if reverse else (self, other) + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.floordiv, *proxy_args_kwargs([lhs, rhs], {}) + ), + sym_num=None, + ) + + def nb_true_divide_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + if not _is_sym_arith_operand(other): + return VariableTracker.build(tx, NotImplemented) + lhs, rhs = (other, self) if reverse else (self, other) + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.truediv, *proxy_args_kwargs([lhs, rhs], {}) + ), + sym_num=None, + ) + + def nb_remainder_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + if not _is_sym_arith_operand(other): + return VariableTracker.build(tx, NotImplemented) + lhs, rhs = (other, self) if reverse else (self, other) + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.mod, *proxy_args_kwargs([lhs, rhs], {}) + ), + sym_num=None, + ) + + def nb_float_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # SymFloat.__float__: https://github.com/pytorch/pytorch/blob/ee336ca5440939b8ad65e916d47421f849e56178/torch/__init__.py#L679 + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + sym_float, + (self.as_proxy(),), + {}, + ), + ) + + def method___float__( + self, tx: "InstructionTranslatorBase", *args: Any, **kwargs: Any + ) -> VariableTracker: + return self.nb_float_impl(tx) + + def nb_negative_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + return SymNodeVariable.create( + tx, + operator.neg(self.as_proxy()), + sym_num=None, + ) + + def method___neg__( + self, tx: "InstructionTranslatorBase", *args: Any, **kwargs: Any + ) -> VariableTracker: + return self.nb_negative_impl(tx) + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + return hash(self.evaluate_expr()), False + + def nb_positive_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + return SymNodeVariable.create( + tx, + operator.pos(self.as_proxy()), + sym_num=None, + ) + + def method___pos__( + self, tx: "InstructionTranslatorBase", *args: Any, **kwargs: Any + ) -> VariableTracker: + return self.nb_positive_impl(tx) + + def nb_absolute_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + return SymNodeVariable.create( + tx, + operator.abs(self.as_proxy()), + sym_num=None, + ) + + def nb_power_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + z: VariableTracker | None, + reverse: bool = False, + ) -> VariableTracker: + if z is not None: + return VariableTracker.build(tx, NotImplemented) + if not _is_sym_arith_operand(other): + return VariableTracker.build(tx, NotImplemented) + lhs, rhs = (other, self) if reverse else (self, other) + return SymNodeVariable.create( + tx, + tx.output.create_proxy( + "call_function", operator.pow, *proxy_args_kwargs([lhs, rhs], {}) + ), + sym_num=None, + ) + + def method___abs__( + self, tx: "InstructionTranslatorBase", *args: Any, **kwargs: Any + ) -> VariableTracker: + return self.nb_absolute_impl(tx) + + def is_python_hashable(self) -> bool: + return True + + def get_python_hash(self) -> int: + # Essentially convert the SymNode to a constant variable whenever its + # searched for a dict key. + return hash(self.evaluate_expr()) + + +class NumpyNdarrayVariable(TensorVariable): + """ + Represents a np.ndarray, but backed by torch Tensor via torch._numpy.ndarray. + Use this for Tensor.numpy() call. + """ + + @staticmethod + def create( + tx: "InstructionTranslatorBase", proxy: torch.fx.Proxy, **options: Any + ) -> "NumpyNdarrayVariable": + from .builder import wrap_fx_proxy_cls + + return wrap_fx_proxy_cls( + target_cls=NumpyNdarrayVariable, + tx=tx, + proxy=proxy, + **options, + ) + + def is_hashable(self) -> bool: + return False + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + from ..exc import raise_type_error + + raise_type_error(tx, "unhashable type: 'numpy.ndarray'") + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + """ndarray tp_richcompare: element-wise comparison via numpy_operator_wrapper.""" + from ..utils import numpy_operator_wrapper + + if not isinstance(other, (SymNodeVariable, ConstantVariable, TensorVariable)): + return ConstantVariable.create(NotImplemented) + op_fn = cmp_name_to_op_mapping[op] + proxy = tx.output.create_proxy( + "call_function", + numpy_operator_wrapper(op_fn), + (self.as_proxy(), other.as_proxy()), + {}, + ) + return NumpyNdarrayVariable.create(tx, proxy) + + # NB: ndim/itemsize are ALWAYS specialized constants (numpy exposes them via + # PyGetSetDef on ndarray), unlike size/shape which may carry free symbols. + def _get_ndim(self, tx: "InstructionTranslatorBase") -> VariableTracker: + example_value = self.as_proxy().node.meta["example_value"] + return VariableTracker.build(tx, tnp.ndarray(example_value).ndim) + + def _get_itemsize(self, tx: "InstructionTranslatorBase") -> VariableTracker: + example_value = self.as_proxy().node.meta["example_value"] + return VariableTracker.build(tx, tnp.ndarray(example_value).itemsize) + + def _get_numpy_attr( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + from ..utils import numpy_attr_wrapper + + proxy = tx.output.create_proxy( + "call_function", numpy_attr_wrapper, (self.as_proxy(), name), {} + ) + return NumpyNdarrayVariable.create(tx, proxy) + + tp_getset = { + "ndim": GetSet(_get_ndim, None), + "itemsize": GetSet(_get_itemsize, None), + "T": GetSet(lambda s, tx: s._get_numpy_attr(tx, "T")), + "real": GetSet(lambda s, tx: s._get_numpy_attr(tx, "real")), + "imag": GetSet(lambda s, tx: s._get_numpy_attr(tx, "imag")), + "flat": GetSet(lambda s, tx: s._get_numpy_attr(tx, "flat")), + } + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + # NB: This INTENTIONALLY does not call super(), because there is + # no intrinsic reason ndarray properties are related to Tensor + # properties. The inheritance here is for implementation sharing. + # tp_getset (ndim/itemsize/T/real/imag/flat) is resolved by + # generic_getattr before this method is reached, so it is not + # consulted here. + from ..utils import numpy_attr_wrapper + from .builder import wrap_fx_proxy + + example_value = self.as_proxy().node.meta["example_value"] + example_ndarray = tnp.ndarray(example_value) + + def insert_into_graph() -> VariableTracker: + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", numpy_attr_wrapper, (self.as_proxy(), name), {} + ), + ) + + # These are awkward to implement. The standard playbook for torch._numpy + # interop is to trace a call into the torch._numpy wrapper which works for + # Tensor operations. However, we don't want to do this for calls + # that don't return Tensors, because in those cases we may not want + # to trace the attribute access into the graph at all (it is sort + # of harmless to do so, because AOTAutograd will eliminate them, + # but it's best not to trace them in to begin with.) But in any + # case, tracing these into the graph is like trying to fit a square + # peg into a round hole; best not to do it. So instead we + # painstakingly implement these by hand + # + # NB: only ALWAYS specialized attributes can go here; notably, + # size/shape not allowed! + if name in ("shape", "stride"): + if not has_free_symbols(r := getattr(example_ndarray, name)): + return VariableTracker.build(tx, tuple(int(r) for r in r)) + return insert_into_graph() + elif name == "size": + if not has_free_symbols(r := example_ndarray.size): + return VariableTracker.build(tx, int(r)) + return insert_into_graph() + elif name in ["base", "flags", "dtype"]: + unimplemented( + gb_type="Unsupported ndarray attribute access", + context=f"tp_getattro_impl {self} {name}", + explanation=f"Dynamo currently does not support tracing `ndarray.{name}`.", + hints=[], + ) + elif name == "__version__": + unimplemented( + gb_type="Unsupported ndarray.__version__ access", + context=f"tp_getattro_impl {self} {name}", + explanation=f"Dynamo currently does not support tracing `ndarray.{name}`.", + hints=[], + ) + raise NotImplementedError + + @staticmethod + def patch_args( + name: str, args: list[VariableTracker], kwargs: dict[str, VariableTracker] + ) -> tuple[list[VariableTracker], dict[str, VariableTracker]]: + if name == "clip": + kwargs_rename = {"a_min": "min", "a_max": "max"} + kwargs = {kwargs_rename.get(k, k): v for k, v in kwargs.items()} + return args, kwargs + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from ..exc import unimplemented + from ..utils import numpy_method_wrapper + + args, kwargs = self.patch_args(name, args, kwargs) + + if name == "astype": + from .builtin import BuiltinVariable + + dtype_arg = None + if "dtype" in kwargs: + dtype_arg = kwargs["dtype"] + elif len(args) > 0: + dtype_arg = args[0] + is_object_str = dtype_arg is not None and dtype_arg.is_constant_match("O") + is_object_type = ( + isinstance(dtype_arg, BuiltinVariable) and dtype_arg.fn is object + ) + if is_object_str or is_object_type: + unimplemented( + gb_type="ndarray.astype(object)", + context=f"call_method {self} {name} {args} {kwargs}", + explanation=( + "`ndarray.astype('O')` or `ndarray.astype(object)` is not supported " + "by torch.compile, as there is no equivalent to object type in torch.Tensor. " + "This will be executed eagerly." + ), + hints=[*graph_break_hints.FUNDAMENTAL], + ) + if name in ["__len__", "size", "tolist", "__iter__"]: + # delegate back to TensorVariable + return super().call_method(tx, name, args, kwargs) + if name in ("tostring", "tobytes", "__delattr__"): + unimplemented( + gb_type="Unsupported ndarray method call", + context=f"call_method {self} {name} {args} {kwargs}", + explanation=f"`ndarray.{name}()` is not modelled in `torch._numpy`.", + hints=[], + ) + proxy = tx.output.create_proxy( + "call_function", + numpy_method_wrapper(name), + *proxy_args_kwargs([self] + list(args), kwargs), + ) + return NumpyNdarrayVariable.create(tx, proxy) + + def python_type(self) -> type: + if np is not None: + return np.ndarray + else: + return NoneType + + def mp_ass_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + if value is None: + raise_value_error(tx, "cannot delete array elements") + return self.call_method(tx, "__setitem__", [key, value], {}) + + +class UnspecializedPythonVariable(TensorVariable): + """ + This is a 1-element tensor represents unspecialized python float/int. + """ + + _nonvar_fields = { + "raw_value", + "need_unwrap", + *TensorVariable._nonvar_fields, + } + + def __init__( + self, + proxy: torch.fx.Proxy, + *, + raw_value: float | int | None = None, + need_unwrap: bool = True, + **kwargs: Any, + ) -> None: + super().__init__(proxy, **kwargs) + self.raw_value = raw_value + self.need_unwrap = need_unwrap + + @classmethod + def from_tensor_variable( + cls, + tensor_variable: TensorVariable, + raw_value: float | int | None, + need_unwrap: bool = True, + ) -> "UnspecializedPythonVariable": + # Convert a `TensorVariable` instance into an `UnspecializedPythonVariable` instance. + return UnspecializedPythonVariable( + **dict(tensor_variable.__dict__), + raw_value=raw_value, + need_unwrap=need_unwrap, + ) + + +class FakeItemVariable(TensorVariable): + """An unspecialized python variable which prevents access to the underlying raw value. + This is needed if item is called on a FakeTensor.""" + + _nonvar_fields = { + "need_unwrap", + *TensorVariable._nonvar_fields, + } + + def __init__(self, proxy: torch.fx.Proxy, **kwargs: Any) -> None: + need_unwrap = kwargs.pop("need_unwrap", False) + super().__init__(proxy, **kwargs) + self.need_unwrap = need_unwrap + + @classmethod + def from_tensor_variable( + cls, tensor_variable: TensorVariable + ) -> "FakeItemVariable": + return FakeItemVariable(**dict(tensor_variable.__dict__)) + + +class TensorSubclassVariable(UserDefinedClassVariable): + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Handle `Subclass(existing_tensor, ...)` calls. + from .torch_function import TensorWithTFOverrideVariable + + new_func = self.value.__new__ + if new_func is torch.Tensor.__new__: + var = None + if len(args) == 1 and args[0].is_tensor() and len(kwargs) == 0: + data = args[0] + # Simulate `torch.Tensor.__new__` as shallow-copying the input + # tensor data with a new type. TODO polyfill? + var = TensorWithTFOverrideVariable.from_tensor_var( + tx, data, self.value, self.source + ) + else: + unimplemented( + gb_type="Calling subclass default constructor with more than tensor argument", + context=f"{self.value}(args={args}, kwargs={kwargs})", + explanation="Currently not supported", + hints=[ + "Avoid this constructor call or move it outside " + "`torch.compile` region", + *graph_break_hints.SUPPORTABLE, + ], + ) + else: + # Let Dynamo trace through custom `__new__` + var = VariableTracker.build(tx, new_func).call_function( + tx, [self] + list(args), kwargs + ) + if var is None: + raise AssertionError("__new__ must return a non-None variable") + # Let Dynamo trace through custom `__init__` + init_func = self.value.__init__ + # TODO builder should be able to handle `torch.Tensor.__init__`, + # which is `object.__init__`, so that we can remove this check. + if init_func is not torch.Tensor.__init__: + VariableTracker.build(tx, init_func).call_function(tx, [var], kwargs) + + # See NOTE [Side effect tracking for newly constructed tensor] + tx.output.side_effects._track_obj( + object(), var, mutation_type_cls=AttributeMutationNew + ) + return var + + def as_python_constant(self) -> type: + return self.value + + +class UntypedStorageVariable(VariableTracker): + _nonvar_fields = { + "example_value", + *VariableTracker._nonvar_fields, + } + + def __init__( + self, + from_tensor: TensorVariable, + example_value: torch.UntypedStorage, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.from_tensor = from_tensor + # Example_value will always have device="meta" + self.example_value = example_value + + def python_type(self) -> type: + return torch.UntypedStorage + + def method_size( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + result = self.example_value.size() + if not has_free_symbols(result): + # avoid creating a node in the graph + return VariableTracker.build(tx, int(result)) + from ..external_utils import untyped_storage_size + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", + untyped_storage_size, + (self.from_tensor.as_proxy(),), + {}, + ), + ) + + def method_resize_( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + tx.output.create_proxy( + "call_function", + torch.ops.inductor.resize_storage_bytes_, + (self.from_tensor.as_proxy(), args[0].as_proxy()), + {}, + ) + return self + + tp_methods = { + "size": Method(method_size), + "resize_": Method(method_resize_), + } + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.from_tensor) + codegen.load_method("untyped_storage") + codegen.call_method(0) + + +class DataPtrVariable(VariableTracker): + _DATA_PTR_PRESERVING_TARGETS = { + ("call_method", "detach"), + ("call_function", torch.ops.aten.detach.default), + } + + def __init__( + self, + from_tensor: TensorVariable, + method_name: str = "data_ptr", + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.from_tensor = from_tensor + self.method_name = method_name + self.tensor_version = from_tensor._get_fake_version() + + def python_type(self) -> type: + return int + + @classmethod + def _strip_data_ptr_preserving_aliases(cls, node: torch.fx.Node) -> torch.fx.Node: + while ( + isinstance(node, torch.fx.Node) + and (node.op, node.target) in cls._DATA_PTR_PRESERVING_TARGETS + and len(node.args) == 1 + and isinstance(node.args[0], torch.fx.Node) + ): + node = node.args[0] + return node + + def _is_same_data_ptr(self, other: "VariableTracker") -> bool: + if not isinstance(other, DataPtrVariable): + return False + + if self.tensor_version is None or self.tensor_version != other.tensor_version: + return False + + self_root = self._strip_data_ptr_preserving_aliases( + self.from_tensor.as_proxy().node + ) + other_root = self._strip_data_ptr_preserving_aliases( + other.from_tensor.as_proxy().node + ) + return self_root is other_root + + def tp_richcompare_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + op: str, + ) -> VariableTracker: + """DataPtr tp_richcompare: identity-based eq/ne.""" + if op not in ("__eq__", "__ne__"): + return ConstantVariable.create(NotImplemented) + same_data_ptr = self._is_same_data_ptr(other) + if same_data_ptr: + return ConstantVariable.create(op == "__eq__") + unimplemented( + gb_type="Data pointer comparison", + context=f"tp_richcompare_impl {self} {op} {other}", + explanation="Dynamo can only trace data pointer comparisons " + "when it can prove both operands have the same data pointer.", + hints=[], + ) + + def reconstruct(self, codegen: "PyCodegen") -> None: + codegen(self.from_tensor) + codegen.load_method(self.method_name) + codegen.call_method(0) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/torch.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/torch.py new file mode 100644 index 0000000000000000000000000000000000000000..0953412d95c815720acd05ca2c70f2e415fdff61 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/torch.py @@ -0,0 +1,4368 @@ +""" +This module implements variable tracking for torch functions and operations during Dynamo tracing. + +It provides classes to handle different types of torch operations: + +TorchInGraphFunctionVariable: Handles torch.* functions that should be captured in the FX graph. +Provides special handling for constant folding, tensor methods, and torch function overrides. +Manages complex cases like out= variants and parameter construction. + +TorchCtxManagerClassVariable: Handles torch context managers like torch.no_grad(), autocast, etc. +Provides implementations for entering/exiting these contexts during tracing. + +DispatchKeySetVariable: Represents torch.DispatchKeySet for managing dispatch keys and +device-specific operations during tracing. + +The module includes special handling for: +- Constant folding of pure functions +- Tensor method calls +- torch.nn.Parameter construction +- __torch_function__ overrides +- Context manager state tracking +- Device and dtype management + +This is a core part of Dynamo's tracing system, translating torch operations into +traceable graph nodes while preserving correct semantics and handling edge cases. +""" + +import enum +import functools +import inspect +import logging +import math +import re +from collections.abc import Callable, Iterable +from contextlib import nullcontext +from typing import Any, cast, NoReturn, TYPE_CHECKING, TypeVar, Union +from typing_extensions import TypeIs + +import torch._C +import torch._refs +import torch.fx +import torch.nn +import torch.utils._pytree as _pytree +from torch._C import DispatchKeySet +from torch._dynamo.variables.constant import ConstantVariable +from torch._dynamo.variables.streams import StreamVariable +from torch._dynamo.variables.torch_function import TorchFunctionModeVariable +from torch._guards import Guard, Source, TracingContext +from torch._logging import warning_once +from torch._subclasses.fake_tensor import is_fake_tensor +from torch.autograd.graph import GradientEdge +from torch.utils._python_dispatch import is_traceable_wrapper_subclass_type + +from .. import config, graph_break_hints, polyfills, variables +from ..codegen import PyCodegen +from ..create_parameter_op import ( + can_convert_to_tracable_parameter, + new_parameter_placeholder, + tracable_create_parameter, +) +from ..device_interface import get_registered_device_interfaces +from ..exc import ( + raise_observed_exception, + raise_type_error, + unimplemented, + UserError, + UserErrorType, +) +from ..guards import ( + _COW_TENSOR_UNSUPPORTED, + _try_is_cow_tensor, + GuardBuilder, + install_guard, +) +from ..source import ( + AttrSource, + CallFunctionNoArgsSource, + GlobalStateSource, + ImportSource, + SyntheticLocalSource, +) +from ..utils import ( + _is_tensorify_enabled, + check_unspec_or_constant_args, + guard_if_dyn, + has_torch_function, + hashable, + is_wrapper_or_member_descriptor, + product, + proxy_args_kwargs, + unpack_iterable, + unwrap_if_wrapper, +) +from .base import typestr, VariableTracker +from .ctx_manager import ( + AutocastModeVariable, + ProfilerContextVariable, + ProfilerRecordFunctionContextVariable, + TorchFunctionDisableVariable, +) +from .distributed import DistributedVariable +from .functions import ( + bind_args_cached, + ClosureConversionError, + NestedUserFunctionVariable, + UserFunctionVariable, +) +from .lists import ListVariable, TupleVariable +from .object_protocol import vt_is_iterable +from .script_object import CustomClassObjectVariable +from .torch_function import ( + can_dispatch_torch_function, + dispatch_torch_function, + TensorWithTFOverrideVariable, + TorchFunctionModeStackVariable, +) +from .user_defined import UserDefinedTupleVariable + + +try: + import numpy as np +except ModuleNotFoundError: + np = None # type: ignore[assignment] + +try: + from torch.distributed.fsdp._fully_shard import _fsdp_param_group +except ModuleNotFoundError: + _fsdp_param_group = None # type: ignore[assignment] + + +if TYPE_CHECKING: + from torch._custom_class_base import CustomClassBase + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + from torch.utils._pytree import TreeSpec + + +V = TypeVar("V") +T = TypeVar("T") + +log = logging.getLogger(__name__) + + +def _is_supported_out_tensor_layout( + fake_out: torch.Tensor, *, false_if_dde: bool +) -> bool: + # Functionalization can preserve standard dense memory formats, but not + # arbitrary non-contiguous view strides. + return ( + torch._prims_common.is_contiguous(fake_out, false_if_dde=false_if_dde) + or torch._prims_common.is_contiguous_for_memory_format( + fake_out, + memory_format=torch.channels_last, + false_if_dde=false_if_dde, + ) + or torch._prims_common.is_contiguous_for_memory_format( + fake_out, + memory_format=torch.channels_last_3d, + false_if_dde=false_if_dde, + ) + ) + + +supported_ctx_manager_classes = dict.fromkeys( + [ + torch.profiler.profiler.profile, + torch.autograd.forward_ad._set_fwd_grad_enabled, + torch.autograd.forward_ad.dual_level, + torch.autograd.profiler.profile, + torch.autograd.profiler.record_function, + torch._C.DisableTorchFunctionSubclass, + torch._C.DisableTorchFunction, + torch._functorch.vmap.vmap_increment_nesting, + torch._functorch.eager_transforms.grad_increment_nesting, + torch._functorch.eager_transforms.jvp_increment_nesting, + torch._functorch.eager_transforms.enable_inplace_requires_grad, + torch.amp.autocast_mode.autocast, + torch.autograd.grad_mode.enable_grad, + torch.autograd.grad_mode.inference_mode, + torch.autograd.grad_mode.no_grad, + torch.autograd.grad_mode.set_grad_enabled, + torch.autograd.graph.disable_saved_tensors_hooks, + torch.cpu.amp.autocast_mode.autocast, + torch.cuda.amp.autocast_mode.autocast, + torch.cuda.use_mem_pool, + torch.cuda.use_mem_pool.__wrapped__, # type: ignore[attr-defined] + torch.fx.traceback.annotate, + torch.fx.traceback.annotate.__wrapped__, # type: ignore[attr-defined] + # We'll let Dynamo inline into the contextlib part of these context + # manager instances, all the way till it invokes the wrapped function + # itself (at which point we wrap it back to special context manager + # VTs). + # + # This allows us to support calling functions decorated with these + # context managers, without much extra effort or code dup. + torch.nn.attention.sdpa_kernel.__wrapped__, # type: ignore[attr-defined] + ] +) + + +REWRITE_OPS_TO_TENSOR_SIZE_METHOD = dict.fromkeys( + [ + torch._shape_as_tensor, + ] +) + +constant_fold_functions_need_guards = [ + torch._C._functorch.get_dynamic_layer_stack_depth, + torch.accelerator.current_device_index, + torch.accelerator.current_accelerator, + torch.cuda.current_device, + torch.cuda.is_initialized, + torch.xpu.current_device, + torch.xpu.is_initialized, + torch.__future__.get_overwrite_module_params_on_conversion, +] + +constant_fold_functions = [ + torch._assert, + torch._utils._get_device_index, + torch._C._get_cublas_allow_tf32, + torch._C._is_any_autocast_enabled, + torch.accelerator.is_available, + torch.backends.mps.is_available.__wrapped__, # type: ignore[attr-defined] + torch.backends.mps.is_built, + torch.cuda.get_device_properties, + torch.cuda.is_available, + torch.distributed.is_available, + torch.get_autocast_dtype, + torch.get_autocast_gpu_dtype, + torch.get_default_dtype, + torch.is_autocast_cache_enabled, + torch.is_autocast_cpu_enabled, + torch.is_autocast_enabled, + torch.is_complex, + torch.is_floating_point, + torch.nn.functional._Reduction.get_enum, # type: ignore[attr-defined] + torch.promote_types, + torch._C._get_privateuse1_backend_name, + torch.autograd._is_checkpoint_valid, + torch.mps.is_available, + torch.mtia.is_available, + torch.xpu.get_device_properties, + torch.xpu.is_available, +] + constant_fold_functions_need_guards +if torch.distributed.is_available(): + constant_fold_functions.extend( + [ + torch.distributed.is_initialized, + torch.distributed.get_rank, + torch.distributed.get_world_size, + ] + ) +# Convert to dict for O(1) access times +constant_fold_functions_need_guards = dict.fromkeys(constant_fold_functions_need_guards) +constant_fold_functions = dict.fromkeys(constant_fold_functions) + +# Ops that consume scalar values from 0-d tensors (via .item()) for computation +# only, not for output shapes. When capture_scalar_outputs is enabled, these ops +# create unbacked symbols that don't affect the outputs, causing +# PendingUnbackedSymbolNotFound errors. +# +# We use an explicit allowlist rather than generically suppressing for any 0-d +# tensor argument because an op could legitimately create unbacked symbols for +# data-dependent output shapes. Suppressing those would silently drop binding +# information. +ops_consuming_unbacked_scalars: frozenset[Callable[..., Any]] = frozenset( + { + # ops with Scalar alpha/beta/value arguments + torch.add, + torch.sub, + torch.addmm, + torch.addmv, + torch.addr, + torch.addbmm, + torch.baddbmm, + torch.addcmul, + torch.addcdiv, + # foreach ops with scalar/alpha arguments + torch._foreach_add, + torch._foreach_add_, + torch._foreach_sub, + torch._foreach_sub_, + torch._foreach_mul, + torch._foreach_mul_, + torch._foreach_div, + torch._foreach_div_, + torch._foreach_clamp_max, + torch._foreach_clamp_max_, + torch._foreach_clamp_min, + torch._foreach_clamp_min_, + torch._foreach_maximum, + torch._foreach_maximum_, + torch._foreach_minimum, + torch._foreach_minimum_, + torch._foreach_pow, + torch._foreach_pow_, + torch._foreach_lerp, + torch._foreach_lerp_, + torch._foreach_addcmul, + torch._foreach_addcmul_, + torch._foreach_addcdiv, + torch._foreach_addcdiv_, + } +) + +# Derived set of method names for TensorVariable.call_method. Includes inplace +# variants (e.g., "add_") since those are only callable as tensor methods. +# This is a set of strings (not function objects) because the call_method path +# only has the method name, whereas call_function has the actual function object. +methods_consuming_unbacked_scalars: frozenset[str] = frozenset( + name + for fn in ops_consuming_unbacked_scalars + for name in (fn.__name__, fn.__name__ + "_") + if hasattr(torch.Tensor, name) +) + + +@functools.cache +def tracing_state_functions() -> dict[Callable[[], Any], bool | None]: + # Defined as a function to avoid circular import like torch.onnx + return { + torch.jit.is_scripting: False, + torch.jit.is_tracing: False, + torch._C._get_tracing_state: None, + torch.fx._symbolic_trace.is_fx_tracing: False, + torch.fx._symbolic_trace.is_fx_symbolic_tracing: False, + torch.onnx.is_in_onnx_export: False, + # pyrefly: ignore [deprecated] + torch._dynamo.external_utils.is_compiling: True, + # pyrefly: ignore [deprecated] + torch._utils.is_compiling: True, + torch.compiler.is_compiling: True, + torch.compiler.is_dynamo_compiling: True, + torch.compiler.is_exporting: True, + torch._dynamo.eval_frame._is_in_optimized_module: True, + # Look into https://github.com/pytorch/pytorch/pull/164721 why this is + # turned to True for Dynamo. + torch.nn.modules.activation._is_make_fx_tracing: True, + } + + +bin_ops = dict.fromkeys(["add", "sub", "mul", "div", "sqrt"]) + +dispatch_key_set_functions = { + torch._C._dispatch_keys, + torch._C._dispatch_tls_local_include_set, + torch._C._dispatch_tls_local_exclude_set, +} + + +def _check_for_gradient_edge(var: VariableTracker, arg_name: str) -> None: + """Check if var contains a GradientEdge from outside the compiled region. + + Used by handle_autograd_grad to reject external GradientEdge objects that + cannot be traced through. + """ + from .dicts import ConstDictVariable + from .lists import BaseListVariable + + if isinstance(var, UserDefinedTupleVariable) and type(var.value) is GradientEdge: + # Try to get source info for context + source_info = var.source.name if var.source else None + context = f"GradientEdge in {arg_name}" + if source_info: + context += f": {source_info}" + + unimplemented( + gb_type="autograd.grad with external GradientEdge", + context=context, + explanation=( + "torch.autograd.grad() cannot be used with GradientEdge inputs " + "passed from outside the compiled region. The GradientEdge contains " + "a reference to an autograd node that was created before torch.compile " + "started tracing, so Dynamo cannot trace through its computation." + ), + hints=[ + "Move the autograd.grad() call outside the torch.compile region.", + "Or use tensor inputs directly instead of GradientEdge objects.", + *graph_break_hints.SUPPORTABLE, + ], + ) + elif isinstance(var, BaseListVariable): + for i, item in enumerate(var.items): + _check_for_gradient_edge(item, f"{arg_name}[{i}]") + elif isinstance(var, ConstDictVariable): + for hash_key, item in var.items.items(): + if not hash_key.vt.is_python_constant(): + unimplemented( + gb_type="autograd.grad with non-constant dict key", + context=f"non-constant key in {arg_name}", + explanation="autograd.grad/backward dict inputs must have constant keys.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + key_repr = hash_key.vt.as_python_constant() + _check_for_gradient_edge(item, f"{arg_name}[{key_repr!r}]") + + +def _collect_all_grad_fns(tensor: torch.Tensor) -> set[torch.autograd.graph.Node]: + from torch._subclasses.fake_tensor import get_plain_tensors + from torch.utils._python_dispatch import is_traceable_wrapper_subclass + + grad_fns: set[torch.autograd.graph.Node] = set() + + plain_tensors: list[torch.SymInt | torch.Tensor | int | CustomClassBase] = [] + # Get all plain tensors (handles nested subclasses) + if is_traceable_wrapper_subclass(tensor): + get_plain_tensors(tensor, out=plain_tensors) + else: + plain_tensors.append(tensor) + + for t in plain_tensors: + if not isinstance(t, torch.Tensor): + continue + + if t.grad_fn is not None: + grad_fns.add(t.grad_fn) + + # For views, also include the base tensor's grad_fn + if t._base is not None and t._base.grad_fn is not None: + grad_fns.add(t._base.grad_fn) + + return grad_fns + + +def _collect_tensors_with_sources( + var: VariableTracker, +) -> list[tuple[torch.Tensor, str | None]]: + """Extract (fake_tensor, source_name) pairs from a VariableTracker. + + Used by handle_autograd_grad to collect tensors from the outputs and inputs + arguments for grad_fn reachability analysis. + """ + from torch.utils._python_dispatch import is_traceable_wrapper_subclass + + from .dicts import ConstDictVariable + from .lazy import LazyVariableTracker + from .lists import BaseListVariable + from .tensor import TensorVariable + + results: list[tuple[torch.Tensor, str | None]] = [] + if isinstance(var, TensorVariable): + fake_tensor = var.as_proxy().node.meta.get("example_value") + if not isinstance(fake_tensor, torch.Tensor): + raise AssertionError( + f"Expected fake_tensor to be a torch.Tensor, got {type(fake_tensor)}" + ) + if is_fake_tensor(fake_tensor): + pass + elif is_traceable_wrapper_subclass(fake_tensor): + # For tensor subclasses (e.g. DTensor), verify the inner tensors + # are FakeTensors but keep the original subclass for grad_fn + # reachability analysis. + plain: list[object] = [] + torch._subclasses.fake_tensor.get_plain_tensors( + fake_tensor, # pyrefly: ignore[bad-argument-type] + out=plain, # pyrefly: ignore[bad-argument-type] + ) + if not all(is_fake_tensor(t) for t in plain if isinstance(t, torch.Tensor)): + raise AssertionError( + f"Expected all plain tensors to be FakeTensors, got {[type(t) for t in plain]}" + ) + else: + raise AssertionError( + f"Expected FakeTensor or subclass, got {type(fake_tensor)}" + ) + source_name = var.source.name if var.source else None + results.append((fake_tensor, source_name)) + elif isinstance(var, LazyVariableTracker): + # Realize the lazy var to get the actual TensorVariable + results.extend(_collect_tensors_with_sources(var.realize())) + elif isinstance(var, BaseListVariable): + for item in var.items: + results.extend(_collect_tensors_with_sources(item)) + elif isinstance(var, ConstDictVariable): + for item in var.items.values(): + results.extend(_collect_tensors_with_sources(item)) + else: + unimplemented( + gb_type="autograd.grad with unsupported argument type", + context=f"got {type(var).__name__}", + explanation=( + f"torch.autograd.grad() received an argument of type {type(var).__name__} " + "which is not supported. Expected tensor or sequence of tensors." + ), + hints=[ + "Ensure outputs and inputs arguments are tensors or sequences of tensors.", + ], + ) + return results + + +def _collect_placeholder_nodes(var: "VariableTracker") -> list[torch.fx.Node]: + """Recursively collect FX placeholder nodes from a VariableTracker. + + The returned placeholder nodes carry grapharg.example (real tensor) and + example_value (FakeTensor) metadata — comparing these reveals lost + autograd linkage (e.g., grad_fn dropped during tracing). + See NOTE [Detecting lost autograd linkage in closure-captured tensors]. + """ + from .lazy import LazyVariableTracker + from .lists import BaseListVariable + from .tensor import TensorVariable + + result: list[torch.fx.Node] = [] + if isinstance(var, TensorVariable): + node = var.as_proxy().node + if node.op == "placeholder": + result.append(node) + elif isinstance(var, LazyVariableTracker): + result.extend(_collect_placeholder_nodes(var.realize())) + elif isinstance(var, BaseListVariable): + for item in var.items: + result.extend(_collect_placeholder_nodes(item)) + else: + unimplemented( + gb_type="_autograd_grad with unsupported argument type", + context=f"got {type(var).__name__}", + explanation=( + f"_autograd_grad() received an argument of type {type(var).__name__} " + "which is not supported. Expected tensor or sequence of tensors." + ), + hints=[ + "Ensure outputs and inputs arguments are tensors or sequences of tensors.", + ], + ) + return result + + +@functools.cache +def get_overridable_functions() -> set[Callable[..., Any]]: + from itertools import chain + + from torch.overrides import get_overridable_functions as get_overridable_functions_ + from torch.utils._device import _device_constructors + + funcs = set(chain.from_iterable(get_overridable_functions_().values())) + funcs.update(_device_constructors()) + more: set[Callable[..., Any]] = { + torch.ones_like, + torch.zeros_like, + torch.empty_like, + torch.full_like, + } + funcs.update(more) + return funcs + + +class BaseTorchVariable(VariableTracker): + """common base for all torch.* functions, classes, modules and other things""" + + @classmethod + def create_with_source(cls, value: Any, source: Source) -> "BaseTorchVariable": + if inspect.isclass(value): + install_guard(source.make_guard(GuardBuilder.CLASS_MATCH)) + elif inspect.ismodule(value): + install_guard(source.make_guard(GuardBuilder.MODULE_MATCH)) + elif inspect.isfunction(value): + install_guard(source.make_guard(GuardBuilder.CLOSURE_MATCH)) + elif inspect.isbuiltin(value) or isinstance( + value, (torch._ops.OpOverload, torch._ops.OpOverloadPacket) + ): + install_guard(source.make_guard(GuardBuilder.BUILTIN_MATCH)) + elif is_wrapper_or_member_descriptor(value) or isinstance( + value, torch._dynamo.compiled_autograd.Op + ): + # Don't need to guard on wrappers + pass + else: + install_guard(source.make_guard(GuardBuilder.FUNCTION_MATCH)) + return cls(value, source=source) + + def __init__(self, value: Any, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + + def reconstruct(self, codegen: "PyCodegen") -> None: + try: + name = f"{self.value.__module__}.{self.value.__name__}" + except Exception: + name = f"torch_obj_{id(self.value)}" + unique_var_name = "__" + re.sub(r"[^a-zA-Z0-9_]+", "_", name) + codegen.extend_output( + codegen.setup_globally_cached(unique_var_name, self.value) + ) + + def as_proxy(self) -> Any: + return self.value + + def as_python_constant(self) -> Any: + return self.value + + def get_real_python_backed_value(self) -> Any: + return self.value + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + return self._nb_binop_impl(tx, other, "__or__", "__ror__", reverse) + + def nb_subtract_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + return self._nb_binop_impl(tx, other, "__sub__", "__rsub__", reverse) + + def _nb_binop_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + forward: str, + reverse_dunder: str, + reverse: bool, + ) -> VariableTracker: + dunder = reverse_dunder if reverse else forward + method = getattr(type(self.value), dunder, None) + if method is None: + return VariableTracker.build(tx, NotImplemented) + try: + other_val = other.as_python_constant() + except NotImplementedError: + return VariableTracker.build(tx, NotImplemented) + result = method(self.value, other_val) + if result is NotImplemented: + return VariableTracker.build(tx, NotImplemented) + return VariableTracker.build(tx, result) + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + return hash(self.value), False + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + from .object_protocol import object_richcompare + + return object_richcompare(self, tx, other, op) + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> ConstantVariable: + result = hasattr(self.value, name) + return VariableTracker.build(tx, result) + + def can_constant_fold_through(self) -> bool: + if self.value in constant_fold_functions: + return True + + if ( + self.value is torch.autograd._profiler_enabled + and config.constant_fold_autograd_profiler_enabled + ): + # The relevant flag is enabled only for export. One might wonder + # why? + # + # Actually we would like to not graph break even in the case of + # Dynamo. But there is a weird-unsolved bug with Kineto + Dynamo + # when there are distributed jobs that lead to NCCL timeouts. This + # bug is a rare edege case, but we have not been able to root cause + # it yet. See https://www.internalfb.com/sevmanager/view/560336 for + # more details. + # + # So is this safe for export? Yes, for export, we do not anticipate + # JIT tracing in distributed job training, and the weird edge-case + # interaction with Kineto is not a valid usecase. So, this is ok. + return True + + return getattr(self.value, "__module__", None) == "math" + + +class TorchCtxManagerClassVariable(BaseTorchVariable): + """Points to a context manager class in torch.* that dynamo has implementations""" + + def __repr__(self) -> str: + return f"TorchCtxManagerClassVariable({self.value})" + + @staticmethod + def is_matching_cls(value: Any) -> bool: + # Unwrap if it's a functools.lru_cache wrapper + value = unwrap_if_wrapper(value) + # We can't do isinstance(value, type) check because some ctx managers + # are implemented as a function decorated by contextlib.contextmanager, + # E.g., torch._functorch.vmap.vmap_increment_nesting. + return ( + # Context manager type or function with @contextmanager is callable + callable(value) + and ( + hashable(value) # accesses value.__hash__() + and value in supported_ctx_manager_classes + ) + ) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: "dict[str, VariableTracker]", + ) -> "VariableTracker": + from . import ( + CUDAMemPoolContextVariable, + DisabledSavedTensorsHooksVariable, + DualLevelContextManager, + FSDPParamGroupUseTrainingStateVariable, + FxTracebackAnnotateVariable, + GradIncrementNestingCtxManagerVariable, + GradInplaceRequiresGradCtxManagerVariable, + GradModeVariable, + InferenceModeVariable, + JvpIncrementNestingCtxManagerVariable, + SDPAKernelVariable, + SetFwdGradEnabledContextManager, + StreamVariable, + VmapIncrementNestingCtxManagerVariable, + ) + + if self.value is torch.no_grad: + if len(args) == 1 and isinstance( + args[0], variables.functions.BaseUserFunctionVariable + ): + ctx = GradModeVariable.create(tx, False) + return ctx.call_function(tx, args, kwargs) + else: + return GradModeVariable.create(tx, False) + elif self.value in ( + torch.cuda.use_mem_pool, + torch.cuda.use_mem_pool.__wrapped__, # type: ignore[attr-defined] + ): + unexpected_kwargs = [k for k in kwargs if k not in ("pool", "device")] + if unexpected_kwargs: + raise_type_error( + tx, + "use_mem_pool() got an unexpected keyword argument " + f"'{unexpected_kwargs[0]}'", + ) + if args and "pool" in kwargs: + raise_type_error( + tx, "use_mem_pool() got multiple values for argument 'pool'" + ) + if len(args) > 1 and "device" in kwargs: + raise_type_error( + tx, "use_mem_pool() got multiple values for argument 'device'" + ) + if len(args) > 2: + raise_type_error( + tx, + "use_mem_pool() takes from 1 to 2 positional arguments " + f"but {len(args)} were given", + ) + if not args and "pool" not in kwargs: + raise_type_error( + tx, + "use_mem_pool() missing 1 required positional argument: 'pool'", + ) + mempool = args[0] if args else kwargs["pool"] + device = args[1] if len(args) > 1 else kwargs.get("device") + return CUDAMemPoolContextVariable.create(tx, mempool, device) + elif self.value is torch.enable_grad: + if len(args) == 1 and isinstance( + args[0], variables.functions.BaseUserFunctionVariable + ): + ctx = GradModeVariable.create(tx, True) + return ctx.call_function(tx, args, kwargs) + return GradModeVariable.create(tx, True) + elif self.value is torch.set_grad_enabled and len(args) == 1: + return GradModeVariable.create( + tx, args[0].as_python_constant(), initialized=True + ) + elif self.value is torch.inference_mode: + if len(args) > 1: + raise AssertionError( + f"torch.inference_mode expects at most 1 arg, got {len(args)}" + ) + if len(kwargs) != 0: + raise AssertionError( + f"torch.inference_mode expects no kwargs, got {len(kwargs)}" + ) + inf_mode = args[0].as_python_constant() if len(args) == 1 else True + return InferenceModeVariable.create(tx, inf_mode) + elif self.value in ( + torch.fx.traceback.annotate, + torch.fx.traceback.annotate.__wrapped__, # type: ignore[attr-defined] + ): + if len(args) > 1: + raise AssertionError( + f"torch.fx.traceback.annotate expects at most 1 arg, got {len(args)}" + ) + if len(kwargs) != 0: + raise AssertionError( + f"torch.fx.traceback.annotate expects no kwargs, got {len(kwargs)}" + ) + return FxTracebackAnnotateVariable( + args[0].as_python_constant(), source=self.source + ) + elif inspect.isclass(self.value) and issubclass(self.value, torch.Stream): + from torch._dynamo.variables.builder import wrap_fx_proxy_cls + + return wrap_fx_proxy_cls( + StreamVariable, + tx, + tx.output.create_proxy( + "call_function", + self.value, + (), + {}, + ), + ) + elif self.value in ( + torch.amp.autocast_mode.autocast, + torch.cuda.amp.autocast, + torch.cpu.amp.autocast, + ): + # pyrefly: ignore [bad-argument-type] + return AutocastModeVariable.create(self.value, args, kwargs) + elif self.value in ( + torch.profiler.record_function, + torch.autograd.profiler.record_function, + ): + return ProfilerRecordFunctionContextVariable.create( + func=self.value, record_args=args, record_kwargs=kwargs + ) + elif self.value in ( + torch.profiler.profile, + torch.autograd.profiler.profile, + ): + warning_once(log, "Profiler function %s will be ignored", self.value) + return ProfilerContextVariable() + elif ( + self.value is torch._C.DisableTorchFunctionSubclass + or self.value is torch._C.DisableTorchFunction + ): + if args or kwargs: + raise AssertionError( + "DisableTorchFunctionSubclass/DisableTorchFunction expects no args or kwargs" + ) + return TorchFunctionDisableVariable.create( + tx, only_subclass=self.value is torch._C.DisableTorchFunctionSubclass + ) + elif self.value is torch._functorch.vmap.vmap_increment_nesting: + if len(args) != 2: + raise AssertionError( + f"vmap_increment_nesting expects 2 args, got {len(args)}" + ) + return VmapIncrementNestingCtxManagerVariable.create( + tx, + args, + ) + elif self.value is torch._functorch.eager_transforms.jvp_increment_nesting: + if len(args) != 0: + raise AssertionError( + f"jvp_increment_nesting expects 0 args, got {len(args)}" + ) + return JvpIncrementNestingCtxManagerVariable.create(tx) + elif self.value is torch.autograd.forward_ad._set_fwd_grad_enabled: + if len(args) != 1: + raise AssertionError( + f"_set_fwd_grad_enabled expects 1 arg, got {len(args)}" + ) + return SetFwdGradEnabledContextManager.create( + tx, + [guard_if_dyn(x) for x in args], + ) + elif self.value is torch.autograd.forward_ad.dual_level: + if len(args) != 0: + raise AssertionError(f"dual_level expects 0 args, got {len(args)}") + return DualLevelContextManager.create(tx) + elif self.value is torch._functorch.eager_transforms.grad_increment_nesting: + if len(args) != 0: + raise AssertionError( + f"grad_increment_nesting expects 0 args, got {len(args)}" + ) + return GradIncrementNestingCtxManagerVariable.create(tx) + elif ( + self.value is torch._functorch.eager_transforms.enable_inplace_requires_grad + ): + if len(args) != 1: + raise AssertionError( + f"enable_inplace_requires_grad expects 1 arg, got {len(args)}" + ) + return GradInplaceRequiresGradCtxManagerVariable.create( + tx, + [guard_if_dyn(x) for x in args], + ) + elif self.value is torch.autograd.graph.disable_saved_tensors_hooks: + if len(args) != 1: + raise AssertionError( + f"disable_saved_tensors_hooks expects 1 arg, got {len(args)}" + ) + return DisabledSavedTensorsHooksVariable.create( + tx, args[0].as_python_constant() + ) + elif ( + _fsdp_param_group is not None + and self.value is _fsdp_param_group.FSDPParamGroup.use_training_state + ): + if len(args) != 2: + raise AssertionError( + f"FSDPParamGroup.use_training_state expects 2 args, got {len(args)}" + ) + return FSDPParamGroupUseTrainingStateVariable.create( + tx, args[0], args[1].as_python_constant() + ) + elif self.value is torch.nn.attention.sdpa_kernel.__wrapped__: # type: ignore[attr-defined] + name_to_arg_map = bind_args_cached( + self.value, + tx, + self.source, + args, + kwargs, + ) + backends = name_to_arg_map["backends"].as_python_constant() + set_priority = name_to_arg_map["set_priority"].as_python_constant() + return SDPAKernelVariable.create(tx, backends, set_priority) + + return super().call_function(tx, args, kwargs) + + +class AllowInGraphKind(enum.Enum): + DEFAULT = "default" + NONSTRICT_TRACE = "nonstrict_trace" + LEAF_FUNCTION = "leaf_function" + + +class TorchInGraphFunctionVariable(BaseTorchVariable): + """Points to a torch function/method that should be put in FX graph""" + + def __init__( + self, + value: Callable[..., Any], + kind: AllowInGraphKind | None = None, + **kwargs: Any, + ) -> None: + super().__init__(value, **kwargs) + from ..trace_rules import is_leaf_function, is_nonstrict_trace_callable + + if kind is None: + if is_leaf_function(value): + kind = AllowInGraphKind.LEAF_FUNCTION + elif is_nonstrict_trace_callable(value): + kind = AllowInGraphKind.NONSTRICT_TRACE + else: + kind = AllowInGraphKind.DEFAULT + + self.kind = kind + + def __repr__(self) -> str: + return f"TorchInGraphFunctionVariable({self.value}, kind={self.kind})" + + def get_function(self) -> Callable[..., Any]: + return self.value + + @staticmethod + @functools.cache + def _get_handlers() -> dict[Callable[..., Any], Callable[..., Any]]: + """Build a dict from function -> method to handle it so that we are O(1) + in terms of the number of function with special handling.""" + # pyrefly: ignore [implicit-any] + handlers = {} + + def register( + *fns: Callable[..., Any], + ) -> Callable[[Callable[..., Any]], Callable[..., Any]]: + def _register(handler: Callable[..., Any]) -> Callable[..., Any]: + for fn in fns: + if fn in handlers: + raise AssertionError(f"Handler already registered for {fn}") + handlers[fn] = handler + return handler + + if not callable(fns[0]): + raise AssertionError( + f"Expected first argument to be callable, got {type(fns[0])}" + ) + return _register + + from torch.backends.cuda import SDPAParams + + from . import ( + ConstantVariable, + GradModeVariable, + InferenceModeVariable, + StreamContextVariable, + SymNodeVariable, + TensorVariable, + UserDefinedObjectVariable, + ) + from .builder import wrap_fx_proxy, wrap_fx_proxy_cls + + @register(*tracing_state_functions()) + def handle_tracing_state_functions( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if args: + raise AssertionError( + f"Tracing state functions expect no args, got {len(args)}" + ) + if kwargs: + raise AssertionError( + f"Tracing state functions expect no kwargs, got {len(kwargs)}" + ) + # See: https://github.com/pytorch/pytorch/issues/110765 + if self.value in ( + # pyrefly: ignore [deprecated] + torch._utils.is_compiling, + # pyrefly: ignore [deprecated] + torch._dynamo.external_utils.is_compiling, + torch.compiler.is_compiling, + torch.compiler.is_dynamo_compiling, + torch.compiler.is_exporting, + torch._dynamo.eval_frame._is_in_optimized_module, + ): + tx.mark_inconsistent_side_effects() + # Read dynamically: the cached dict always has True, but + # is_exporting() should only be True during torch.export. + if self.value is torch.compiler.is_exporting: + return VariableTracker.build(tx, torch.compiler._is_exporting_flag) + return VariableTracker.build(tx, tracing_state_functions()[self.value]) + + @register(*dispatch_key_set_functions) + def handle_dispatch_key_set_functions( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if kwargs: + raise AssertionError( + f"Dispatch key set functions expect no kwargs, got {len(kwargs)}" + ) + if self.value is torch._C._dispatch_keys: + if len(args) != 1: + raise AssertionError( + f"_dispatch_keys expects 1 arg, got {len(args)}" + ) + if not args[0].is_tensor(): + raise AssertionError( + "Expected first argument to _dispatch_keys to be a tensor" + ) + # pyrefly: ignore[missing-attribute] + example_value = args[0].proxy.node.meta["example_value"] + dks = self.value(example_value) + # Remove Python and PythonTLSSnapshot from the dispatch key set, + # as they originate from FakeTensor propagation. + # This should only be done if the example_value is a FakeTensor. + # However, if tensor subclasses are present, + # it is reasonable for Python to remain in the dispatch key set. + if torch._subclasses.fake_tensor.is_fake_tensor(example_value): + dks = ( + dks + - torch._C.DispatchKeySet(torch._C.DispatchKey.Python) + - torch._C.DispatchKeySet( + torch._C.DispatchKey.PythonTLSSnapshot + ) + ) + return DispatchKeySetVariable.create(dks) + else: + if args: + raise AssertionError( + f"Dispatch key set function expects no args, got {len(args)}" + ) + return DispatchKeySetVariable.create(self.value()) + + @register(torch.overrides.get_default_nowrap_functions.__wrapped__) + def handle_get_default_nowrap_functions( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + # [Note: __torch_function__] we return empty here because we restrict + # the set of functions that we trace __torch_function__ on to + # functions outside of the actual set. Implementing this properly will require implementing + # some variable types to track and compare tensor getset descriptors + return VariableTracker.build( + tx, torch.overrides.get_default_nowrap_functions() + ) + + @register(torch.ops.inductor.accumulate_grad_.default) + def handle_accumulate_grad_( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if len(args) == 2 and not kwargs: + variable, new_grad = args + if isinstance(variable, variables.LazyVariableTracker): + variable = variable.realize() + if not variable.is_tensor(): + raise AssertionError( + "Expected first argument to accumulate_grad_ to be a tensor" + ) + variable_grad = variable.tp_getattro_impl(tx, "grad") + updated_grad = tx.inline_user_function_return( + VariableTracker.build(tx, polyfills.accumulate_grad), + [variable, variable_grad, new_grad], + kwargs, + ) + updated_grad = updated_grad.clone(source=None, mutation_type=None) + tx.output.side_effects.store_attr(variable, "grad", updated_grad) + return ConstantVariable.create(None) + if len(args) == 3 and not kwargs: + variable, variable_grad, new_grad = args + if isinstance(variable, variables.LazyVariableTracker): + variable = variable.realize() + if not variable.is_tensor(): + raise AssertionError( + "Expected first argument to accumulate_grad_ to be a tensor" + ) + updated_grad = tx.inline_user_function_return( + VariableTracker.build(tx, polyfills.accumulate_grad_no_alias), + [variable, variable_grad, new_grad], + kwargs, + ) + tx.output.side_effects.store_attr( + variable, + "grad", + updated_grad.clone(source=None, mutation_type=None), + ) + return updated_grad + return tx.inline_user_function_return( + VariableTracker.build(tx, polyfills.accumulate_grad_no_alias), + list(args), + kwargs, + ) + + @register(math.radians) + def handle_radians( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + if not check_unspec_or_constant_args(args, kwargs): + # Use polyfill to convert math.radians(x) into math.pi * x / 180.0 + return tx.inline_user_function_return( + VariableTracker.build(tx, polyfills.radians), + list(args), + kwargs, + ) + + if hasattr(math, "fma"): # Python 3.13+ + + @register(math.fma) + def handle_fma( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + if len(args) != 3 or kwargs: + return None + + if all(arg.is_tensor() for arg in args): + x, y, z = args + addcmul_fn = TorchInGraphFunctionVariable(torch.addcmul) + return addcmul_fn.call_function(tx, [z, x, y], {}) + + # Use math.fma if constants + return None + + @register(torch.is_inference_mode_enabled) + def handle_is_inference_mode_enabled( + self, tx: "InstructionTranslatorBase" + ) -> NoReturn: + unimplemented( + gb_type="Encountered torch.is_inference_mode_enabled during tracing", + context="", + explanation="torch.is_inference_mode_enabled() is not supported", + hints=[ + *graph_break_hints.FUNDAMENTAL, + *graph_break_hints.INFERENCE_MODE, + ], + ) + + @register(torch.is_tensor, torch.overrides.is_tensor_like) + def handle_is_tensor( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> VariableTracker: + if arg.is_tensor() or ( + self.value is torch.overrides.is_tensor_like + and isinstance(arg, UserDefinedObjectVariable) + and hasattr(arg.value, "__torch_function__") + ): + return ConstantVariable.create(True) + else: + return ConstantVariable.create(False) + + @register( + torch.is_floating_point, + torch.is_complex, + ) + def handle_is_floating_point( + self, tx: "InstructionTranslatorBase", input: Any + ) -> VariableTracker | None: + input_arg = input + if input_arg.is_tensor() and input_arg.dtype is not None: + if self.value is torch.is_floating_point: + return VariableTracker.build(tx, input_arg.dtype.is_floating_point) + elif self.value is torch.is_complex: + return VariableTracker.build(tx, input_arg.dtype.is_complex) + else: + raise AssertionError(f"calling {self.value}") + return None + + @register(torch.numel) + def handle_numel( + self, tx: "InstructionTranslatorBase", input: Any + ) -> VariableTracker | None: + if input.is_tensor() and input.valid_size(): + return VariableTracker.build(tx, product(input.size)) + elif input.is_tensor(): + # Workaround dynamic shapes issue + return input.call_method(tx, "numel", [], {}) + return None + + @register(torch.compile) + def handle_torch_compile( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if len(args) == 1: + # torch.compile is a no-op in dynamo + return args[0] + + unimplemented( + gb_type="torch.compile call with > 1 args", + context=f"args={args}, kwargs={kwargs}", + explanation="Attempted to call `torch.compile` with > 1 args. Dynamo does not support this.", + hints=[ + "Remove the torch.compile call or its additional args.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + @register(torch.library.wrap_triton, torch._library.capture_triton) + def handle_wrap_triton( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if len(args) == 1: + # wrap_triton / capture_triton is a no-op in dynamo + return args[0] + + unimplemented( + gb_type="torch.library.wrap_triton call with > 1 args", + context=f"args={args}, kwargs={kwargs}", + explanation="Attempted to call `wrap_triton`/`capture_triton`" + " with > 1 args. Dynamo does not support this.", + hints=[ + "Remove the wrap_triton/capture_triton call or its additional args.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + @register(*REWRITE_OPS_TO_TENSOR_SIZE_METHOD) + def handle_tensor_size_rewrites( + self, tx: "InstructionTranslatorBase", input: VariableTracker + ) -> VariableTracker: + if not input.is_tensor(): + raise AssertionError( + "Expected input to tensor size rewrite to be a tensor" + ) + return input.call_method(tx, "size", [], {}) + + @register( + torch.nn.modules.utils._single, + torch.nn.modules.utils._pair, + torch.nn.modules.utils._triple, + torch.nn.modules.utils._quadruple, + torch.nn.modules.utils._ntuple, + ) + def handle_ntuple( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + return self._call_ntuple(tx, args, kwargs) + + @register(torch.is_grad_enabled) + def handle_is_grad_enabled( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable: + install_guard(GradModeVariable._guards_singleton) + return VariableTracker.build(tx, torch.is_grad_enabled()) + + @register(torch.autograd.grad_mode._enter_inference_mode) + def handle_enter_inference_mode( + self, tx: "InstructionTranslatorBase", mode: VariableTracker + ) -> InferenceModeVariable: + ctx = InferenceModeVariable.create(tx, mode.as_python_constant()) + ctx.enter(tx) + return ctx + + @register(torch.autograd.grad_mode._exit_inference_mode) + def handle_exit_inference_mode( + self, tx: "InstructionTranslatorBase", mode: InferenceModeVariable + ) -> VariableTracker: + return mode.exit(tx) + + @register(torch.use_deterministic_algorithms) + def handle_use_deterministic_algorithms( + self, + tx: "InstructionTranslatorBase", + mode: Any, + warn_only: VariableTracker | bool = False, + ) -> VariableTracker: + value = mode.as_python_constant() + warn_only_value = ( + warn_only.as_python_constant() + if isinstance(warn_only, VariableTracker) + else warn_only + ) + tx.output.create_node( + "call_function", + torch._C._set_deterministic_algorithms, + (value,), + {"warn_only": warn_only_value}, + ) + torch._C._set_deterministic_algorithms(value, warn_only=warn_only_value) + return ConstantVariable.create(None) + + @register(torch.autocast_increment_nesting) + def handle_autocast_increment_nesting( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker: + tx.output.create_node( + "call_function", torch.autocast_increment_nesting, (), {} + ) + prev = torch.autocast_increment_nesting() + tx.output.add_cleanup_hook(lambda: torch.autocast_decrement_nesting()) + return VariableTracker.build(tx, prev) + + @register(torch.autocast_decrement_nesting) + def handle_autocast_decrement_nesting( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker: + tx.output.create_node( + "call_function", torch.autocast_decrement_nesting, (), {} + ) + prev = torch.autocast_decrement_nesting() + tx.output.add_cleanup_hook(lambda: torch.autocast_increment_nesting()) + return VariableTracker.build(tx, prev) + + @register(torch.set_autocast_enabled) + def handle_set_autocast_enabled( + self, + tx: "InstructionTranslatorBase", + device_type: VariableTracker, + enabled: VariableTracker, + ) -> VariableTracker: + tx.output.create_node( + "call_function", + torch.set_autocast_enabled, + (device_type.as_proxy(), enabled.as_proxy()), + ) + dev_py_const = device_type.as_python_constant() + prev = torch.is_autocast_enabled(dev_py_const) + torch.set_autocast_enabled(dev_py_const, enabled.as_python_constant()) + tx.output.add_cleanup_hook( + lambda: torch.set_autocast_enabled(dev_py_const, prev) + ) + return ConstantVariable.create(None) + + @register(torch.set_autocast_dtype) + def handle_set_autocast_dtype( + self, + tx: "InstructionTranslatorBase", + device_type: VariableTracker, + dtype: VariableTracker, + ) -> VariableTracker: + tx.output.create_node( + "call_function", + torch.set_autocast_dtype, + (device_type.as_proxy(), dtype.as_proxy()), + ) + dev_py_const = device_type.as_python_constant() + prev = torch.get_autocast_dtype(dev_py_const) + torch.set_autocast_dtype(dev_py_const, dtype.as_python_constant()) + tx.output.add_cleanup_hook( + lambda: torch.set_autocast_dtype(dev_py_const, prev) + ) + return ConstantVariable.create(None) + + @register(torch.set_autocast_cache_enabled) + def handle_set_autocast_cache_enabled( + self, tx: "InstructionTranslatorBase", enabled: VariableTracker + ) -> VariableTracker: + tx.output.create_node( + "call_function", torch.set_autocast_cache_enabled, (enabled.as_proxy(),) + ) + prev = torch.is_autocast_cache_enabled() + torch.set_autocast_cache_enabled(enabled.as_python_constant()) + tx.output.add_cleanup_hook(lambda: torch.set_autocast_cache_enabled(prev)) + return ConstantVariable.create(None) + + @register(torch._functorch.predispatch._jvp_increment_nesting) + def handle_jvp_increment_nesting( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker: + tx.output.create_node( + "call_function", torch._functorch.predispatch._jvp_increment_nesting + ) + level = torch._functorch.predispatch._jvp_increment_nesting() + tx.output.add_cleanup_hook( + torch._functorch.predispatch._jvp_decrement_nesting + ) + return VariableTracker.build(tx, level) + + @register(torch._functorch.predispatch._jvp_decrement_nesting) + def handle_jvp_decrement_nesting( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker: + tx.output.create_node( + "call_function", torch._functorch.predispatch._jvp_decrement_nesting + ) + level = torch._functorch.predispatch._jvp_decrement_nesting() + tx.output.add_cleanup_hook( + torch._functorch.predispatch._jvp_increment_nesting + ) + return VariableTracker.build(tx, level) + + @register(torch._functorch.predispatch._enter_dual_level) + def handle_enter_dual_level( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker: + tx.output.create_node( + "call_function", torch._functorch.predispatch._enter_dual_level + ) + level = torch._functorch.predispatch._enter_dual_level() + tx.output.add_cleanup_hook( + lambda: torch._functorch.predispatch._exit_dual_level(level=level) + ) + return VariableTracker.build(tx, level) + + @register(torch._functorch.predispatch._exit_dual_level) + def handle_exit_dual_level( + self, tx: "InstructionTranslatorBase", level: VariableTracker + ) -> VariableTracker: + level_const = level.as_python_constant() + tx.output.create_node( + "call_function", + torch._functorch.predispatch._exit_dual_level, + (), + { + "level": level_const, + }, + ) + torch._functorch.predispatch._exit_dual_level(level=level_const) + + def cleanup(): + new_level = torch._functorch.predispatch._enter_dual_level() + if new_level != level_const: + raise AssertionError("Invalid _exit_dual_level") + + tx.output.add_cleanup_hook(cleanup) + return ConstantVariable.create(None) + + @register(torch._C._functorch._grad_increment_nesting) + def handle_grad_increment_nesting( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker: + tx.output.create_node( + "call_function", torch._C._functorch._grad_increment_nesting + ) + level = torch._C._functorch._grad_increment_nesting() + tx.output.add_cleanup_hook(torch._C._functorch._grad_decrement_nesting) + return VariableTracker.build(tx, level) + + @register(torch._C._functorch._grad_decrement_nesting) + def handle_grad_decrement_nesting( + self, tx: "InstructionTranslatorBase" + ) -> VariableTracker: + tx.output.create_node( + "call_function", torch._C._functorch._grad_decrement_nesting + ) + level = torch._C._functorch._grad_decrement_nesting() + tx.output.add_cleanup_hook(torch._C._functorch._grad_increment_nesting) + return VariableTracker.build(tx, level) + + @register(torch._C._functorch.set_inplace_requires_grad_allowed) + def handle_set_inplace_requires_grad_allowed( + self, tx: "InstructionTranslatorBase", allowed: VariableTracker + ) -> VariableTracker: + tx.output.create_node( + "call_function", + torch._C._functorch.set_inplace_requires_grad_allowed, + (allowed.as_proxy(),), + ) + prev = torch._C._functorch.get_inplace_requires_grad_allowed() + torch._C._functorch.set_inplace_requires_grad_allowed( + allowed.as_python_constant() + ) + tx.output.add_cleanup_hook( + lambda: torch._C._functorch.set_inplace_requires_grad_allowed(prev) + ) + return ConstantVariable.create(None) + + @register(torch.are_deterministic_algorithms_enabled) + def handle_are_deterministic_algorithms_enabled( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable: + guard = Guard( + GlobalStateSource(), + GuardBuilder.DETERMINISTIC_ALGORITHMS, # type: ignore[arg-type] + ) + install_guard(guard) + return VariableTracker.build( + tx, torch.are_deterministic_algorithms_enabled() + ) + + @register(torch._C._is_torch_function_enabled) + def handle_is_torch_function_enabled( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable: + install_guard(TorchFunctionDisableVariable._guards_singleton) + # see comment on SymbolicTorchFunctionState class as to why + # this is not a bug + return VariableTracker.build( + tx, tx.symbolic_torch_function_state.torch_function_subclass_enabled + ) + + @register(torch._C._is_cow_tensor) # pyrefly: ignore[missing-attribute] + def handle_is_cow_tensor( + self, tx: "InstructionTranslatorBase", arg: VariableTracker + ) -> ConstantVariable: + if not arg.is_tensor(): + raise AssertionError( + f"_is_cow_tensor expects a tensor, got {arg.python_type_name()}" + ) + + def has_prior_cow_state_changing_op() -> bool: + if not isinstance(arg, TensorVariable): + return False + graph = arg.as_proxy().node.graph + return any( + (node.op == "call_method" and node.target == "_lazy_clone") + or (node.op == "call_function" and node.target is torch._lazy_clone) + for node in graph.nodes + ) + + if arg.source is None: + unimplemented( + gb_type="source-less COW tensor check", + context="torch._C._is_cow_tensor on source-less tensor", + explanation=( + "Dynamo cannot safely guard COW state for an intermediate " + "tensor without a source." + ), + hints=[ + "Avoid checking COW state on intermediate tensors inside " + "torch.compile regions.", + ], + ) + if tx.output.current_tracer.is_export or torch.compiler._is_exporting_flag: + unimplemented( + gb_type="COW tensor check during export", + context="torch._C._is_cow_tensor during export", + explanation=( + "Dynamo cannot safely export COW-state-dependent " + "control flow because COW state is not represented in " + "the exported graph." + ), + hints=[ + "Avoid checking COW state inside torch.export regions.", + ], + ) + fake_version = arg._get_fake_version() # pyrefly: ignore[missing-attribute] + if fake_version is not None and fake_version > 0: + unimplemented( + gb_type="COW tensor check after mutation", + context="torch._C._is_cow_tensor after tensor mutation", + explanation=( + "Dynamo cannot safely fold a COW state check after " + "the tensor's state may have changed inside the " + "compiled frame." + ), + hints=[ + "Move the COW state check before tensor mutations or " + "outside the torch.compile region.", + ], + ) + if has_prior_cow_state_changing_op(): + unimplemented( + gb_type="COW tensor check after COW-state-changing op", + context="torch._C._is_cow_tensor after _lazy_clone", + explanation=( + "Dynamo cannot safely fold a COW state check after " + "an op in the current graph may have changed that " + "tensor's COW state." + ), + hints=[ + "Move the COW state check before _lazy_clone or outside " + "the torch.compile region.", + ], + ) + real_value = arg.get_real_value() # pyrefly: ignore[missing-attribute] + if is_fake_tensor(real_value): + unimplemented( + gb_type="COW tensor check on FakeTensor", + context="torch._C._is_cow_tensor on FakeTensor", + explanation=( + "Dynamo cannot safely evaluate COW state from a " + "FakeTensor because COW state is not represented in " + "FakeTensor metadata." + ), + hints=[ + "Avoid checking COW state on FakeTensors inside " + "torch.compile regions.", + ], + ) + cow_state = _try_is_cow_tensor(real_value) + if cow_state is _COW_TENSOR_UNSUPPORTED: + unimplemented( + gb_type="COW tensor check on Python tensor subclass", + context="torch._C._is_cow_tensor on Python tensor subclass", + explanation=( + "Dynamo cannot safely evaluate COW state for Python " + "tensor subclasses because their storage semantics are " + "controlled by __torch_dispatch__." + ), + hints=[ + "Avoid checking COW state on tensor subclasses inside " + "torch.compile regions.", + ], + ) + install_guard(arg.source.make_guard(GuardBuilder.COW_TENSOR_MATCH)) + return VariableTracker.build(tx, cast(bool, cow_state)) + + @register(torch._C._is_torch_function_all_disabled) + def handle_is_torch_function_all_disabled( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable: + install_guard(TorchFunctionDisableVariable._guards_singleton) + return VariableTracker.build( + tx, not tx.symbolic_torch_function_state.torch_function_mode_enabled + ) + + @register(torch._C._is_torch_function_mode_enabled) + def handle_is_torch_function_mode_enabled( + self, tx: "InstructionTranslatorBase" + ) -> ConstantVariable: + install_guard(TorchFunctionDisableVariable._guards_singleton) + # _is_torch_function_mode_enabled returns True only if: + # 1. Torch function modes are not disabled (DisableTorchFunction not entered) + # 2. There are actually modes on the stack + return VariableTracker.build( + tx, + tx.symbolic_torch_function_state.torch_function_mode_enabled + and tx.symbolic_torch_function_state.in_torch_function_mode(), + ) + + @register( + torch.overrides.has_torch_function, + torch.overrides.has_torch_function_variadic, + torch.overrides.has_torch_function_unary, + ) + def handle_has_torch_function( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> ConstantVariable: + tf_state = tx.symbolic_torch_function_state + if tf_state.skip_next: + tf_state.skip_next = False + return VariableTracker.build(tx, False) + elems = ( + unpack_iterable(tx, args[0]) + if len(args) == 1 and isinstance(args[0], TupleVariable) + else args + ) + return VariableTracker.build(tx, any(has_torch_function(x) for x in elems)) + + @register(torch._C._skip_one_hop_torch_function) + def handle_skip_one_hop_torch_function( + self, + tx: "InstructionTranslatorBase", + func: VariableTracker, + types: VariableTracker, + args: VariableTracker, + kwargs: VariableTracker, + ) -> VariableTracker: + tf_state = tx.symbolic_torch_function_state + if tf_state.skip_next: + from torch._dynamo.exc import raise_observed_exception + + raise_observed_exception( + RuntimeError, + tx, + args=[ + "you cannot skip two levels of __torch_function__, " + "you need to run one level of __torch_function__ " + "before being able to skip again." + ], + ) + tf_state.skip_next = True + tx.skip_one_hop_torch_function_depth += 1 + try: + return func.call_function( + tx, + unpack_iterable(tx, args), + kwargs.keys_as_python_constant(), # type: ignore[attr-defined] + ) + finally: + tx.skip_one_hop_torch_function_depth -= 1 + tf_state.skip_next = False + + @register( + *dict.fromkeys( # remove duplicates + device_interface.stream + for _, device_interface in get_registered_device_interfaces() + ) + ) + def handle_device_interface_stream( + self, tx: "InstructionTranslatorBase", stream: "StreamVariable" + ) -> StreamContextVariable: + return StreamContextVariable.create(tx, stream) + + @register(torch.from_numpy) + def handle_from_numpy( + self, tx: "InstructionTranslatorBase", *args: VariableTracker + ) -> TensorVariable: + if not config.trace_numpy: + unimplemented( + gb_type="call `torch.from_numpy` with `torch._dynamo.config.trace_numpy=False`", + context=f"trace_numpy={config.trace_numpy}", + explanation=( + "Attempted to call `torch.from_numpy` with config " + "`torch._dynamo.config.trace_numpy` set to `False`." + ), + hints=[ + "Change `torch._dynamo.config.trace_numpy` to `True`.", + ], + ) + if not np: + unimplemented( + gb_type="`torch.from_numpy` with NumPy unavailable", + context="", + explanation="Attempted to call `torch.numpy` but NumPy could not be imported.", + hints=[ + "Check NumPy version and installation in your environment.", + *graph_break_hints.USER_ERROR, + ], + ) + return wrap_fx_proxy_cls( + target_cls=TensorVariable, + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + torch.as_tensor, + *proxy_args_kwargs(args, {}), + ), + example_value=None, + ) + + @register(torch.jit.annotate) + def handle_jit_annotate( + self, tx: "InstructionTranslatorBase", the_type: Any, the_value: V + ) -> V: + return the_value + + @register(torch.backends.cudnn.is_acceptable) + def handle_cudnn_is_acceptable( + self, tx: "InstructionTranslatorBase", tensor: Any, *extra: Any + ) -> ConstantVariable: + # is_acceptable(tensor) returns true if + # (a) tensor dtype/device are supported by cudnn + # (b) cudnn is available + # (c) some initialization has completed + # technically, it depends on some global state from (c) (torch.backends.cudnn.__cudnn_version) + if extra: + raise AssertionError("Expect 1 input to cudnn.is_acceptable") + if not tensor.is_tensor(): + raise AssertionError( + "Expect input to cudnn.is_acceptable to be a tensor" + ) + tensor_inp = torch.tensor(0, dtype=tensor.dtype, device=tensor.device) + return VariableTracker.build( + tx, torch.backends.cudnn.is_acceptable(tensor_inp) + ) + + @register(torch.utils.hooks.BackwardHook) + def handle_backward_hook( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + return variables.BackwardHookVariable.create(tx, *args, **kwargs) + + @register(torch.nn.Parameter) + def handle_parameter( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + return self.call_nn_parameter(tx, *args, **kwargs) + + @register(torch.ops.aten.sym_size, torch.ops.aten.sym_size.int) + def handle_sym_size( + self_: Any, tx: "InstructionTranslatorBase", self, dim: Any | None = None + ) -> VariableTracker | None: + # we see this when retracing already traced code + if dim is not None: + return self.call_method(tx, "size", [dim], {}) + return None + + @register(torch.ops.aten.sym_stride, torch.ops.aten.sym_stride.int) + def handle_sym_stride( + self_: Any, tx: "InstructionTranslatorBase", self, dim: Any | None = None + ) -> VariableTracker | None: + if dim is not None: + return self.call_method(tx, "stride", [dim], {}) + return None + + @register(torch.addcdiv) + def handle_addcdiv( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + if len(args) == 3 and "value" in kwargs and len(kwargs) == 1: + # decompose addcdiv into constituent ops, prevents a graph break due to converting + # value to a scalar + result = TorchInGraphFunctionVariable(torch.div).call_function( + tx, [*args[1:]], {} + ) + result = TorchInGraphFunctionVariable(torch.mul).call_function( + tx, [result, kwargs["value"]], {} + ) + return TorchInGraphFunctionVariable(torch.add).call_function( + tx, [args[0], result], {} + ) + return None + + @register(torch.full) + def handle_full( + self, + tx: "InstructionTranslatorBase", + size: VariableTracker, + fill_value: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + if fill_value.is_tensor() and not issubclass( + fill_value.python_type(), torch.nn.Parameter + ): + # Decompose: create empty tensor and fill it + # This avoids the scalar extraction at compile time + empty_result = TorchInGraphFunctionVariable(torch.empty).call_function( + tx, [size], kwargs + ) + # Call fill_ method on the empty tensor + return empty_result.call_method(tx, "fill_", [fill_value], {}) + return None + + @register(torch.tensor_split) + def handle_tensor_split( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + indices_or_sections = ( + args[1] if len(args) >= 2 else kwargs.get("indices_or_sections") + ) + if not isinstance(indices_or_sections, TensorVariable): + return None + + example_value = indices_or_sections.as_proxy().node.meta.get( + "example_value" + ) + if ( + example_value is None + or example_value.dim() != 0 + or example_value.device.type != "cpu" + or example_value.dtype != torch.int64 + or (item_memo := example_value.item_memo) is None + ): + return None + + sections = torch.fx.experimental.symbolic_shapes.guard_scalar(item_memo) + if not isinstance(sections, int): + return None + + # tensor_split's scalar-tensor overload needs a concrete output + # arity. Guard the memoized value here so downstream AOT tracing + # does not re-read the 0-D tensor as a fresh unbacked scalar. + sections_vt = ConstantVariable.create(sections) + if len(args) >= 2: + args = (args[0], sections_vt, *args[2:]) + else: + kwargs["indices_or_sections"] = sections_vt + return TorchInGraphFunctionVariable(torch.tensor_split).call_function( + tx, list(args), kwargs + ) + + @register(torch._foreach_lerp_) + def handle_inplace_foreach_lerp_scalar( + _: Any, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + # Decompose via addcmul_ only when the weight is a tensor, so + # tensor weights (e.g. 0-dim tensor from tensor betas in Adam) stay + # in tensor arguments instead of hitting float() in the native + # lerp_scalar lowering. Python scalar weights can use the native + # foreach op directly, avoiding extra full-size weight tensors. + if ( + config.enable_dynamo_decompositions + and len(args) == 3 + and args[2].is_tensor() + and not kwargs + ): + return tx.inline_user_function_return( + VariableTracker.build(tx, polyfills.foreach_lerp_inplace), + list(args), + kwargs, + ) + return None + + @register(torch._foreach_pow) + def handle_foreach_pow_scalar( + _: Any, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + if not config.enable_dynamo_decompositions: + return None + + # In eager it's more performant to call item() from within the C op implementation + # in compile, it's more performant to not graph break. + if len(args) == 2 and args[0].is_tensor() and not kwargs: + return tx.inline_user_function_return( + VariableTracker.build(tx, polyfills.foreach_pow_scalar), + list(args), + kwargs, + ) + return None + + @register(torch._C._group_tensors_by_device_and_dtype) + def handle_group_tensors_by_device_and_dtype( + _: Any, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + return tx.inline_user_function_return( + VariableTracker.build(tx, polyfills.group_tensors_by_device_and_dtype), + list(args), + kwargs, + ) + + @register(torch._assert) + def handle_assert( + self, + tx: "InstructionTranslatorBase", + condition: VariableTracker, + message: VariableTracker, + ) -> VariableTracker | None: + if (condition.is_python_constant() and condition.as_python_constant()) or ( + isinstance(condition, variables.SymNodeVariable) + and condition.evaluate_expr() + ): + return ConstantVariable.create(None) + return None + + @register(SDPAParams) + def handle_sdpa_params( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + return wrap_fx_proxy( + tx, + proxy=tx.output.create_proxy( + "call_function", + torch._C._SDPAParams, + *proxy_args_kwargs(args, kwargs), + ), + param_vars=args, + ) + + if DistributedVariable.is_available(): + from torch.distributed.distributed_c10d import ( + _get_group_size_by_name, + _get_group_tag, + _rank_not_in_group, + _resolve_group_name_by_ranks_and_tag, + get_process_group_ranks, + get_rank, + get_world_size, + ) + + @register( + _get_group_size_by_name, + _get_group_tag, + _rank_not_in_group, + get_process_group_ranks, + _resolve_group_name_by_ranks_and_tag, + get_rank, + get_world_size, + ) + def handle_constant_processgroup_functions( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + # We desugar it at trace-time into ranks by directly calling util + # bake the result into the trace + if len(args) == 0 and len(kwargs) == 0: + # get_rank() or get_world_size() with no args (uses default group) + pass + elif len(args) == 1 and len(kwargs) == 0: + # group or group name + if not ( + args[0].is_python_constant() + or ( + isinstance(args[0], CustomClassObjectVariable) + and args[ # pyrefly: ignore[missing-attribute] + 0 + ].value.script_class_name # pyrefly: ignore[missing-attribute] + == "torch.distributed.distributed_c10d.ProcessGroup" + ) + ): + raise AssertionError( + f"Expected group arg to be a python constant or ProcessGroup, got {args[0]}" + ) + elif len(args) == 2 and len(kwargs) == 0: + # ranks + tag + if not isinstance(args[0], ListVariable): + raise AssertionError( + f"Expected first arg to be a ListVariable (ranks), got {type(args[0])}" + ) + if not args[1].is_python_constant(): + raise AssertionError( + "Expected second arg (tag) to be a python constant" + ) + elif len(args) == 0 and len(kwargs) > 0: + # All keyword arguments (e.g., get_world_size(group=...)) + pass + else: + raise AssertionError( + f"Invalid group value ({args}, {kwargs}) for constant pg " + f"function {self.value}" + ) + + def get_arg_value(arg: VariableTracker) -> Any: + # CustomClassObjectVariable for ProcessGroup doesn't support + # as_python_constant(), so extract real_obj directly + if isinstance(arg, CustomClassObjectVariable): + return arg.value.real_obj # pyrefly: ignore[missing-attribute] + return arg.as_python_constant() + + args_as_value = [get_arg_value(arg) for arg in args] + kwargs_as_value = {k: get_arg_value(v) for k, v in kwargs.items()} + invocation_result = self.value(*args_as_value, **kwargs_as_value) + + # Note - while we *could* cook up sources around invocations, like a FunctionSource + # the space of invoking functions in the middle of the guard chain is very iffy. As such, + # guard propagation via options is the best we can do. + return VariableTracker.build(tx, invocation_result) + + @register(torch.nested.nested_tensor) + def handle_nested_tensor( + self, + tx: "InstructionTranslatorBase", + tensor_list: VariableTracker | None = None, + *args: VariableTracker, + layout: Any | None = None, + **kwargs: VariableTracker, + ) -> None: + from .lists import BaseListVariable + + if layout and layout.is_constant_match(torch.strided): + unimplemented( + gb_type="Attempted to use strided NestedTensor", + context=f"layout={layout}", + explanation="Dynamo does not support this.", + hints=[ + "Change layout=torch.jagged.", + *graph_break_hints.SUPPORTABLE, + ], + ) + if not isinstance(tensor_list, BaseListVariable): + unimplemented( + gb_type="Attempted to use `nested_tensor` with non-list input", + context=f"tensor_list={tensor_list}", + explanation="Dynamo does not support this.", + hints=[ + "Change `nested_tensor` with list input.", + *graph_break_hints.USER_ERROR, + ], + ) + return None + + @register(torch.nn.functional.one_hot) + def handle_one_hot( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> None: + if len(args) + len(kwargs) == 1 or ( + len(args) == 2 and args[1].is_constant_match(-1) + ): + unimplemented( + gb_type="Attempted to use `torch.nn.functional.one_hot` with data-dependent output shape", + context=f"args={args}, kwargs={kwargs}", + explanation="Dynamo does not support this.", + hints=[ + "Explicitly set the `num_classes` param of the function call " + "`torch.nn.functional.one_hot` to something other than -1.", + ], + ) + return None + + @register(torch.fx.experimental.symbolic_shapes.guarding_hint_or_throw) + def handle_guarding_hint_or_throw( + self, + tx: "InstructionTranslatorBase", + expr: VariableTracker, + ) -> VariableTracker | None: + if isinstance(expr, SymNodeVariable): + return VariableTracker.build( + tx, + torch.fx.experimental.symbolic_shapes.guarding_hint_or_throw( + expr.sym_num + ), + ) + elif expr.is_python_constant(): + return expr + else: + return None + + @register(torch.fx.experimental.symbolic_shapes.optimization_hint) + def handle_optimization_hint( + self, + tx: "InstructionTranslatorBase", + expr: VariableTracker, + fallback: VariableTracker | None = None, + ) -> VariableTracker | None: + fallback_int = fallback.as_python_constant() if fallback else None + if isinstance(expr, SymNodeVariable): + return VariableTracker.build( + tx, + torch.fx.experimental.symbolic_shapes.optimization_hint( + expr.sym_num, fallback_int + ), + ) + elif expr.is_python_constant(): + return expr + else: + return None + + @register(torch.fx.experimental.symbolic_shapes.guard_size_oblivious) # type: ignore[deprecated] + def handle_guard_size_oblivious( + self, tx: "InstructionTranslatorBase", expr: VariableTracker + ) -> VariableTracker | None: + if isinstance(expr, SymNodeVariable): + # TODO: this probably should be folded somewhere else but I'm not sure where + # TODO: some of the other symbolic_shapes special tools can also get this treatment too + return VariableTracker.build( + tx, + torch.fx.experimental.symbolic_shapes.guard_size_oblivious( # type: ignore[deprecated] + expr.sym_num + ), + ) + elif expr.is_python_constant(): + return expr + else: + return None + + @register(torch.fx.experimental.symbolic_shapes.guard_or_true) + def handle_guard_or_true( + self, tx: "InstructionTranslatorBase", expr: VariableTracker + ) -> VariableTracker | None: + if isinstance(expr, SymNodeVariable): + # TODO: this probably should be folded somewhere else but I'm not sure where + # TODO: some of the other symbolic_shapes special tools can also get this treatment too + return VariableTracker.build( + tx, + torch.fx.experimental.symbolic_shapes.guard_or_true(expr.sym_num), + ) + elif expr.is_python_constant(): + return expr + else: + return None + + @register(torch.fx.experimental.symbolic_shapes.guard_or_false) + def handle_guard_or_false( + self, tx: "InstructionTranslatorBase", expr: VariableTracker + ) -> VariableTracker | None: + if isinstance(expr, SymNodeVariable): + # TODO: this probably should be folded somewhere else but I'm not sure where + # TODO: some of the other symbolic_shapes special tools can also get this treatment too + return VariableTracker.build( + tx, + torch.fx.experimental.symbolic_shapes.guard_or_false(expr.sym_num), + ) + elif expr.is_python_constant(): + return expr + else: + return None + + @register(torch.fx.experimental.symbolic_shapes.statically_known_false) + def handle_statically_known_false( + self, tx: "InstructionTranslatorBase", expr: VariableTracker + ) -> VariableTracker | None: + if isinstance(expr, SymNodeVariable): + return VariableTracker.build( + tx, + torch.fx.experimental.symbolic_shapes.statically_known_false( + expr.sym_num + ), + ) + elif expr.is_python_constant(): + return expr + else: + return None + + @register(torch.fx.experimental.symbolic_shapes.has_free_unbacked_symbols) + def handle_has_free_unbacked_symbols( + self, tx: "InstructionTranslatorBase", x: VariableTracker + ) -> VariableTracker | None: + from .tensor import TensorVariable + + if isinstance(x, TensorVariable): + example_value = x.as_proxy().node.meta.get("example_value") + if example_value is not None: + return variables.ConstantVariable.create( + torch.fx.experimental.symbolic_shapes.has_free_unbacked_symbols( + example_value + ) + ) + return None + + @register(torch.fx.experimental.symbolic_shapes.guard_scalar) + def guard_scalar( + self, tx: "InstructionTranslatorBase", expr: VariableTracker + ) -> VariableTracker: + if isinstance(expr, SymNodeVariable): + val = expr.sym_num + elif expr.is_python_constant(): + val = expr.as_python_constant() + else: + unimplemented( + gb_type="torch.fx.experimental.symbolic_shapes.guard_scalar branch not supported", + context=f"expr: {expr}", + explanation="Expected `expr` to be a symbolic variable or constant.", + hints=[], + ) + return VariableTracker.build( + tx, + # pyrefly: ignore [bad-argument-type, unbound-name] + torch.fx.experimental.symbolic_shapes.guard_scalar(val), + ) + + @register(torch.fx.experimental.symbolic_shapes.statically_known_true) + def handle_statically_known_true( + self, tx: "InstructionTranslatorBase", expr: VariableTracker + ) -> VariableTracker | None: + if isinstance(expr, SymNodeVariable): + return VariableTracker.build( + tx, + torch.fx.experimental.symbolic_shapes.statically_known_true( + expr.sym_num + ), + ) + elif expr.is_python_constant(): + return expr + else: + return None + + @register(torch.fx.experimental.symbolic_shapes.sym_and) + def handle_sym_and( + self, tx: "InstructionTranslatorBase", *terms: VariableTracker + ) -> VariableTracker | None: + if all(isinstance(x, SymNodeVariable) for x in terms): + return SymNodeVariable.create( + tx, + torch.fx.experimental.symbolic_shapes.sym_and( + *(x.as_proxy() for x in terms) + ), + sym_num=None, + ) + return None + + @register(torch.fx.experimental.symbolic_shapes.sym_or) + def handle_sym_or( + self, tx: "InstructionTranslatorBase", *terms: VariableTracker + ) -> VariableTracker | None: + if all(isinstance(x, SymNodeVariable) for x in terms): + return SymNodeVariable.create( + tx, + torch.fx.experimental.symbolic_shapes.sym_or( + *(x.as_proxy() for x in terms) + ), + sym_num=None, + ) + return None + + @register(torch.fx.experimental.symbolic_shapes.has_static_value) + def handle_has_static_value( + self, tx: "InstructionTranslatorBase", expr: VariableTracker + ) -> VariableTracker | None: + if isinstance(expr, SymNodeVariable): + val = expr.sym_num + elif expr.is_python_constant(): + val = expr.as_python_constant() + else: + return None + + return VariableTracker.build( + tx, torch.fx.experimental.symbolic_shapes.has_static_value(val) + ) + + @register(torch._C._autograd._unsafe_set_version_counter) + def handle_unsafe_set_version_counter( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + from ..tensor_version_op import _unsafe_set_version_counter + + return TorchInGraphFunctionVariable( + _unsafe_set_version_counter + ).call_function(tx, [*args], kwargs) + + @register(torch._C._functorch.peek_interpreter_stack) + def handle_functorch_peek_interpreter_stack( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> UserDefinedObjectVariable: + # Wrap C++ interpreter (torch._C._functorch.CInterpreter) as UserDefinedObjectVariable, + # but Python interpreter (torch._functorch.pyfunctorch.FuncTorchInterpreter) as FuncTorchInterpreterVariable. + return UserDefinedObjectVariable( + torch._C._functorch.peek_interpreter_stack() + ) + + @register(torch._functorch.pyfunctorch.coerce_cinterpreter) + def handle_functorch_pyfunctorch_coerce_cinterpreter( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> FuncTorchInterpreterVariable: + # pyrefly: ignore[missing-attribute] + cinterpreter = args[0].value + return FuncTorchInterpreterVariable( + torch._functorch.pyfunctorch.coerce_cinterpreter(cinterpreter) + ) + + @register(torch.tensor) + def handle_torch_tensor( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + def check_any_unspec(x: VariableTracker) -> bool: + # NB: This includes UnspecializedPythonVariable + if x.is_tensor() or isinstance(x, SymNodeVariable): + return True + elif isinstance(x, (ListVariable, TupleVariable)): + return any(check_any_unspec(y) for y in x.items) + # TODO: there maybe other recursive structures you need to + # check + else: + return False + + data_arg = None + if args: + data_arg = args[0] + elif "data" in kwargs: + data_arg = kwargs["data"] + + # NB: OK to pass torch.tensor(tensor), this will trace fine + if ( + data_arg is not None + and not data_arg.is_tensor() + and check_any_unspec(data_arg) + ): + # This is slower and less canonical, so only use it if we + # have to + return TorchInGraphFunctionVariable(torch._refs.tensor).call_function( + tx, [*args], kwargs + ) + else: + return None + + @register(torch._C._pop_torch_function_stack) + def handle_pop_torch_function( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> TorchFunctionModeVariable: + if args: + raise AssertionError( + f"_pop_torch_function_stack expects no args, got {len(args)}" + ) + if kwargs: + raise AssertionError( + f"_pop_torch_function_stack expects no kwargs, got {len(kwargs)}" + ) + if not tx.symbolic_torch_function_state.mode_stack: + unimplemented( + gb_type="Attempted to pop from empty torch function mode stack", + context="", + explanation="Called `torch._C._pop_torch_function_stack` when torch function mode stack is empty.", + hints=[ + "Do not pop from empty torch function mode stack.", + *graph_break_hints.USER_ERROR, + ], + ) + TorchFunctionModeStackVariable.register_mutation(tx) + return tx.symbolic_torch_function_state.pop_torch_function_mode() + + @register(torch._C._push_on_torch_function_stack) + def handle_push_torch_function( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if len(args) != 1 or kwargs: + raise_type_error( + tx, + f"push_torch_function takes exactly one argument ({len(args)} given)", + ) + TorchFunctionModeStackVariable.register_mutation(tx) + # type: ignore[arg-type] + tx.symbolic_torch_function_state.push_torch_function_mode(args[0]) + return ConstantVariable.create(None) + + @register(torch._C._len_torch_function_stack) + def handle_len_torch_function( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if args or kwargs: + raise_type_error(tx, "len_torch_function_stack takes no arguments") + return VariableTracker.build( + tx, len(tx.symbolic_torch_function_state.mode_stack) + ) + + @register(torch._C._get_function_stack_at) + def handle_get_stack_at( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> TorchFunctionModeVariable: + if len(args) != 1 or kwargs: + raise_type_error( + tx, + f"get_function_stack_at takes exactly one argument ({len(args)} given)", + ) + ind = args[0].as_python_constant() + if ind < 0: + raise AssertionError( + f"Expected non-negative index for get_function_stack_at, got {ind}" + ) + if ind >= len(tx.symbolic_torch_function_state.mode_stack): + raise AssertionError( + f"Index {ind} out of range for torch function mode stack " + f"of length {len(tx.symbolic_torch_function_state.mode_stack)}" + ) + return tx.symbolic_torch_function_state.mode_stack[ind] + + @register(torch.utils._python_dispatch._get_current_dispatch_mode_stack) + def handle_get_current_dispatch_mode_stack( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if args or kwargs: + raise_type_error( + tx, + "_get_current_dispatch_mode_stack() takes no arguments", + ) + # During tracing, Dynamo runs with dispatch modes removed, so + # the stack is always empty. Return [] as a constant instead + # of graph-breaking. + return VariableTracker.build(tx, []) + + @register(torch.get_device_module.__wrapped__) + def handle_get_device_module( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if len(args) + len(kwargs) > 1 or (kwargs and "device" not in kwargs): + unimplemented( + gb_type="improper torch.get_device_module arguments", + context=f"args={args}, kwargs={kwargs}", + explanation="torch.get_device_module accepts 1 optional argument `device`", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + try: + if kwargs: + device = kwargs["device"].as_python_constant() + elif args: + device = args[0].as_python_constant() + else: + device = None + module = torch.get_device_module(device) + except Exception as e: + unimplemented( + gb_type="bad device argument to torch.get_device_module", + context=f"args={args}, kwargs={kwargs}", + explanation="Expected valid string/torch.device argument ('cpu', 'cuda', etc.)", + hints=[*graph_break_hints.USER_ERROR], + from_exc=e, + ) + + # need to guard only on no-arg get_device_module + if device is None: + source = CallFunctionNoArgsSource(self.source) + install_guard(source.make_guard(GuardBuilder.ID_MATCH)) + # assumes `module` is in the form `torch.xyz` + torch_source = ImportSource("torch") + install_guard(torch_source.make_guard(GuardBuilder.ID_MATCH)) + new_source = AttrSource( + torch_source, + module.__name__.rsplit(".", maxsplit=1)[-1], + ) + return VariableTracker.build(tx, module, new_source) + + @register( + torch.accelerator.current_stream, + torch.cuda.current_stream, + torch.xpu.current_stream, + ) + def handle_current_stream( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> StreamVariable: + from .streams import _get_stream_variable_cls + + if len(args) + len(kwargs) > 1 or (kwargs and "device" not in kwargs): + unimplemented( + gb_type="unsupported arguments to torch.accelerator.current_stream", + context=f"args={args}, kwargs={kwargs}", + explanation="torch.accelerator.current_stream accepts one optional argument `device`", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + try: + if kwargs: + device = torch.device(kwargs["device"].as_python_constant()) + elif args: + device = torch.device(args[0].as_python_constant()) + else: + device = None + + stream_var = tx.symbolic_stream_state.cur_stream(device) + stream_variable_cls = _get_stream_variable_cls(self.value) + if stream_variable_cls is not None and not isinstance( + stream_var, stream_variable_cls + ): + stream_var = stream_variable_cls( + stream_var.proxy, + stream_var.value, + stream_var.user_object_index, + source=stream_var.source, + ) + return stream_var + except Exception as e: + unimplemented( + gb_type="bad device argument to torch.accelerator.current_stream", + context=f"args={args}, kwargs={kwargs}", + explanation="Expected valid string/torch.device argument ('cpu', 'cuda', etc.)", + hints=[*graph_break_hints.USER_ERROR], + from_exc=e, + ) + + _synchronize_fn_to_device_type = { + torch.cuda.synchronize: "cuda", + torch.xpu.synchronize: "xpu", + torch.mps.synchronize: "mps", + torch.cpu.synchronize: "cpu", + } + + @register( + torch.accelerator.synchronize, + torch.cuda.synchronize, + torch.xpu.synchronize, + torch.mps.synchronize, + torch.cpu.synchronize, + ) + def handle_synchronize( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + device = None + if kwargs and "device" in kwargs: + device = torch.device(kwargs["device"].as_python_constant()) + elif args: + device = torch.device(args[0].as_python_constant()) + + if device is None: + device_type = _synchronize_fn_to_device_type.get(self.value) + if device_type is None: + # torch.accelerator.synchronize with no args + accelerator = torch.accelerator.current_accelerator() + if accelerator is None: + raise AssertionError( + "No accelerator available for torch.accelerator.synchronize" + ) + device_type = accelerator.type + device = torch.device(device_type) + + # CPU synchronize is a no-op, skip emitting the op + if device.type == "cpu": + return ConstantVariable.create(None) + + tx.output.create_proxy( + "call_function", + torch.ops.streams.synchronize_device, + (device.type, device.index or 0), + {}, + ) + return ConstantVariable.create(None) + + @register(torch.set_default_device) + def handle_set_default_device( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + # Today this is inserted in the graph, once TF mode + # handling is complete, we can trace the device context + # like any other TF mode and remove this special handling + # Insert the TF mode representing the device context at + # the bottom of the stack to match the eager semantics + # Running the graph will ensure that the DeviceContext mode is + # at the correct position in the stack + TorchFunctionModeStackVariable.register_mutation(tx) + if args[0].is_constant_none(): + TorchFunctionModeStackVariable.clear_default_device(tx) + else: + TorchFunctionModeStackVariable.register_device_context_insertion(tx) + + return ConstantVariable.create(None) + + from torch._prims_common import elementwise_dtypes + + @register(elementwise_dtypes) + def handle_elementwise_dtypes( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + from .builder import SourcelessBuilder + + type_promotion_kind = kwargs["type_promotion_kind"].as_python_constant() + real_args = [] + for arg in args: + if isinstance(arg, TensorVariable): + real_args.append(arg.as_proxy().node.meta["example_value"]) + elif arg.is_python_constant(): + real_args.append(arg.as_python_constant()) + else: + unimplemented( + gb_type="elementwise_dtypes unsupported arg type", + context=str(arg), + explanation=( + "elementwise_dtypes requires tensor or constant arguments, " + f"got {type(arg).__name__}" + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + result = elementwise_dtypes( + *real_args, type_promotion_kind=type_promotion_kind + ) + return SourcelessBuilder.create(tx, result) + + def check_impl( + self, + tx: "InstructionTranslatorBase", + predicate_vt: VariableTracker | None, + message_vt: VariableTracker | None, + error_type: type[Exception] = RuntimeError, + ) -> VariableTracker: + if predicate_vt is None: + raise_type_error( + tx, + f"{self.value.__name__}() missing 1 required positional argument: 'cond'", + ) + + if predicate_vt.is_tensor(): + raise_type_error( + tx, + "cond must be a bool, but got a Tensor. " + "For tensor conditions, use torch._check_tensor_all() " + "to assert that all elements are true.", + ) + + message_eager = None + message_graph_arg = None + # Realize a possible LazyVariableTracker so the exact-type checks + # below see the underlying VariableTracker rather than the wrapper. + if message_vt is not None: + message_vt = message_vt.realize() + match message_vt: + case None: + pass + case NestedUserFunctionVariable() | UserFunctionVariable() if type( + message_vt + ) in (NestedUserFunctionVariable, UserFunctionVariable): + # These report is_python_constant() True (as_python_constant + # returns the underlying fn), so this arm must precede the + # constant arm below. Restrict to exact types: other + # function-VT subclasses (e.g. bound methods, whose + # get_function drops the receiver) cannot be faithfully + # reconstructed as a zero-arg message callable, so they fall + # through to the graph-break arm. + try: + message_eager = message_vt.get_function() + except ClosureConversionError: + unimplemented( + gb_type="Can't convert torch._check*() message closure", + context=str(message_vt), + explanation=( + "The message argument of torch._check*() must be a function " + "whose closure variables are Python constants." + ), + hints=[ + "Remove closure variables that reference non-constant values, e.g. " + "remove references to tensor `x` in `lambda: f'{x} failed check'`", + *graph_break_hints.SUPPORTABLE, + ], + ) + + message_graph_arg = tx.output.register_static_attr_and_return_proxy( + "_check_message", message_eager + ) + case _ if message_vt.is_python_constant(): + # Mirror eager torch._check, which accepts any constant and + # stringifies it; None means "use the default message". + message_eager = message_vt.as_python_constant() + if message_eager is not None: + message_graph_arg = str(message_eager) + case _: + unimplemented( + gb_type="Can't extract message from torch._check*()", + context=str(message_vt), + explanation=( + "The message argument of torch._check*() must be a string, None, " + "or a function." + ), + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + if predicate_vt.is_python_constant(): + if predicate_vt.as_python_constant(): + return ConstantVariable.create(None) + msg = ( + str(message_eager() if callable(message_eager) else message_eager) + if message_eager is not None + else ("Expected cond to be True, but got False.") + ) + raise_observed_exception(error_type, tx, args=[msg]) + + predicate_proxy = predicate_vt.as_proxy() + + proxy_args: tuple[Any, ...] + if message_graph_arg is None: + proxy_args = (predicate_proxy,) + else: + proxy_args = (predicate_proxy, message_graph_arg) + + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + torch._check, + proxy_args, + {}, + ), + ) + + @register(torch._check) + def handle_check( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + predicate_vt = args[0] if args else kwargs.get("cond") + rest_args = args[1:] if args else () + message_vt = rest_args[0] if rest_args else kwargs.get("message") + return check_impl(self, tx, predicate_vt, message_vt) + + @register( + torch._check_with, + torch._check_index, + torch._check_value, + torch._check_type, + torch._check_not_implemented, + ) + def handle_check_with( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if self.value is torch._check_with: + error_type_vt = args[0] if args else kwargs.get("error_type") + rest_args = args[1:] if args else () + else: + error_type_vt = None + rest_args = args + + _CHECK_ERROR_TYPES: dict[object, type[Exception]] = { + torch._check_index: IndexError, + torch._check_value: ValueError, + torch._check_type: TypeError, + torch._check_not_implemented: NotImplementedError, + } + + error_type = ( + error_type_vt.as_python_constant() + if error_type_vt is not None + else _CHECK_ERROR_TYPES.get(self.value, RuntimeError) + ) + + predicate_vt = rest_args[0] if rest_args else kwargs.get("cond") + rest_args = rest_args[1:] if rest_args else () + message_vt = rest_args[0] if rest_args else kwargs.get("message") + return check_impl(self, tx, predicate_vt, message_vt, error_type) + + @register( + torch._check_tensor_all_with, + torch._check_tensor_all, + ) + def handle_check_tensor_all( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + if self.value is torch._check_tensor_all_with: + error_type_vt = args[0] if args else kwargs.get("error_type") + rest_args = args[1:] if args else () + error_type = ( + error_type_vt.as_python_constant() + if error_type_vt is not None + else RuntimeError + ) + else: + rest_args = args + error_type = RuntimeError + + cond_vt = rest_args[0] if rest_args else kwargs.get("cond") + rest_args = rest_args[1:] if rest_args else () + message_vt = rest_args[0] if rest_args else kwargs.get("message") + + if cond_vt is None: + return check_impl(self, tx, None, message_vt, error_type) + + scalar_vt = cond_vt.call_method(tx, "_is_all_true", [], {}).call_method( + tx, "item", [], {} + ) + + return check_impl(self, tx, scalar_vt, message_vt, error_type) + + def exchange_device_helper( + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + fn: Callable[[int], int | None], + ) -> VariableTracker: + if len(args) != 1 or kwargs: + raise_type_error( + tx, + f"{fn.__name__} takes exactly one argument ({len(args)} given)", + ) + torch_source = ImportSource("torch") + install_guard(torch_source.make_guard(GuardBuilder.ID_MATCH)) + current_device_source = CallFunctionNoArgsSource( + AttrSource(AttrSource(torch_source, "cuda"), "current_device") + ) + install_guard(current_device_source.make_guard(GuardBuilder.EQUALS_MATCH)) + arg = args[0].as_python_constant() + prev = fn(arg) + tx.output.create_node( + "call_function", + fn, + (arg,), + {}, + ) + tx.output.add_cleanup_hook(lambda: torch.cuda.set_device(prev)) + return VariableTracker.build(tx, prev) + + @register(torch.cuda._exchange_device) + def handle_exchange_device( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + return exchange_device_helper( + tx, list(args), kwargs, torch.cuda._exchange_device + ) + + @register(torch.cuda._maybe_exchange_device) + def handle_maybe_exchange_device( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + return exchange_device_helper( + tx, list(args), kwargs, torch.cuda._maybe_exchange_device + ) + + @register(torch._dynamo.decorators.override_optimization_hint) + def handle_override_optimization_hint( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker: + from .constant import ConstantVariable + from .tensor import SymNodeVariable + + x_vt = args[0] + val_vt = args[1] + val = val_vt.as_python_constant() + + if x_vt.is_python_constant(): + torch._dynamo.decorators.override_optimization_hint( + x_vt.as_python_constant(), val + ) + return ConstantVariable.create(None) + + if isinstance(x_vt, SymNodeVariable): + torch._dynamo.decorators.override_optimization_hint(x_vt.sym_num, val) + return ConstantVariable.create(None) + + raise UserError( + UserErrorType.INVALID_INPUT, + "override_optimization_hint expects a SymInt or int argument, " + f"got {type(x_vt).__name__}", + ) + + @register(torch.autograd.grad) + def handle_autograd_grad( + self, tx: "InstructionTranslatorBase", *args, **kwargs + ): + """ + Handle torch.autograd.grad() calls within compiled regions. + + NOTE [Tracing autograd.grad in dynamo] + + We validate two things: + + 1. External grad_fns cannot be consumed: The grad_fn on external inputs + could change at runtime, so we would need to guard on it if we wanted + to trace through it. For now, we reject this case. + We compute "consumed" grad_fns (reachable from outputs, excluding + autograd.grad inputs parameter) and verify no graph input's grad_fn is in this set. + + 2. Returned tensors cannot have consumed grad_fns: If autograd.grad + consumes a grad_fn and we return a tensor connected to it, the user + would get "backward through graph a second time" error. We track + consumed grad_fns and check at output time. If violated, we retry + with a graph break at autograd.grad. + + Safe vs Unsafe Cases: + + Case 1 - Safe (external tensor is autograd.grad input): + x = torch.randn(4, requires_grad=True) + external = x * 2 # has external grad_fn + + @torch.compile + def fn(external_input): + loss = external_input.sum() + return torch.autograd.grad(loss, external_input) + + Safe because autograd.grad stops at external_input, never consuming + its external grad_fn. + + Case 2 - Unsafe (external grad_fn in path): + @torch.compile + def fn(external_input): + loss = mod(external_input).sum() + return torch.autograd.grad(loss, mod.weight) + + Unsafe because autograd.grad must traverse through external_input's + grad_fn to reach mod.weight. The external grad_fn could change at + runtime, so we would need to guard on it (like AOTAutograd does). + For now, we reject this case. + + Case 3 - Unsafe (returning tensor with consumed grad_fn): + @torch.compile + def fn(x): + y = x * 2 + grad = torch.autograd.grad(y.sum(), x) + return y, grad # y's grad_fn was consumed! + + Unsafe because y's grad_fn was consumed by autograd.grad. Trying to + backward through y later would error. + """ + from .. import compiled_autograd, config + from .builder import wrap_fx_proxy + from .constant import ConstantVariable + from .dicts import ConstDictVariable + from .lists import BaseListVariable + from .tensor import TensorVariable + + if not config.trace_autograd_ops: + unimplemented( + gb_type="using `torch.autograd.grad` with `torch._dynamo.config.trace_autograd_ops=False`", + context=f"trace_autograd_ops={config.trace_autograd_ops}", + explanation=( + "Attempted to call `torch.autograd.grad` with config " + "`torch._dynamo.config.trace_autograd_ops` set to `False`." + ), + hints=[ + "Change `torch._dynamo.config.trace_autograd_ops` to `True`.", + ], + ) + + # Graph break if we detected on a previous attempt that autograd.grad + # consumed grad_fns of returned tensors. This gives better compile + # coverage than failing the entire compile. + if tx.speculation_log.graph_break_on_autograd_grad: + leaked = tx.speculation_log.autograd_grad_leaked_tensors + leaked_str = ", ".join(leaked) if leaked else "unknown" + unimplemented( + gb_type="autograd.grad consumed returned tensor's grad_fn", + context=f"Leaked output tensors: {leaked_str}", + explanation=( + "torch.autograd.grad() consumes grad_fns that are needed by tensors " + "returned from this compiled function. This would cause 'backward " + "through graph a second time' errors.\n" + f" The following returned tensors have consumed grad_fns: {leaked_str}" + ), + hints=[ + f"Detach the problematic tensor(s) before returning: e.g. `{leaked[0]}.detach()`" + if leaked + else "Call .detach() on the tensor before returning.", + "If you need to backward through the returned tensor, use retain_graph=True in autograd.grad().", + ], + ) + + # Graph break if compiled_autograd is enabled. + # Compiled autograd has limitations (e.g., view_fn in CopySlices) + # that would cause errors during fake tensor execution. + if compiled_autograd.compiled_autograd_enabled: + unimplemented( + gb_type="autograd.grad with compiled autograd", + context="compiled_autograd is currently enabled", + explanation=( + "torch.autograd.grad() inside torch.compile is not supported when " + "compiled autograd is enabled. These two features have conflicting " + "requirements for how the autograd graph is traced." + ), + hints=[ + "Disable compiled autograd by removing the compiled_autograd context manager.", + "Or move the autograd.grad() call outside the torch.compile region.", + "Or restructure your code so autograd.grad() and compiled_autograd don't overlap.", + ], + ) + + # Check for external GradientEdge objects in outputs and inputs args + # if there is it will be a graph break + if len(args) >= 1: + _check_for_gradient_edge(args[0], "outputs") + if len(args) >= 2: + _check_for_gradient_edge(args[1], "inputs") + + # Collect external grad_fn objects from graph inputs, along with their sources. + # We need to collect ALL grad_fns associated with each input tensor: + # - Direct grad_fn, base tensor's grad_fn (for views) + # - Inner tensors (for subclasses) + external_grad_fns: set[torch.autograd.graph.Node] = set() + # Map grad_fn -> source name for better error messages + grad_fn_to_source: dict[torch.autograd.graph.Node, str] = {} + for var in tx.output.input_source_to_var.values(): + if isinstance(var, TensorVariable): + fake_tensor = var.as_proxy().node.meta.get("example_value") + if not isinstance(fake_tensor, torch.Tensor): + raise AssertionError( + f"Expected fake_tensor to be a torch.Tensor, got {type(fake_tensor)}" + ) + tensor_grad_fns = _collect_all_grad_fns(fake_tensor) + external_grad_fns.update(tensor_grad_fns) + # Track source name for error messages + if var.source is not None: + for gf in tensor_grad_fns: + grad_fn_to_source[gf] = var.source.name + + # Collect tensors from outputs and inputs args + from ..output_graph import collect_reachable_grad_fns + + outputs_with_sources = ( + _collect_tensors_with_sources(args[0]) if len(args) >= 1 else [] + ) + inputs_with_sources = ( + _collect_tensors_with_sources(args[1]) if len(args) >= 2 else [] + ) + + # Collect grad_fns from the autograd.grad inputs tensors to use as stop points. + # For non-leaf tensors: we stop at their grad_fn + # For leaf tensors (requires_grad=True, grad_fn=None): we don't add anything here, + # but this is fine because their AccumulateGrad is created during fake tensor + # tracing and is not in external_grad_fns, so it won't trigger a false positive. + inputs_grad_fns: set[torch.autograd.graph.Node] = set() + for tensor, _ in inputs_with_sources: + if isinstance(tensor, torch.Tensor) and tensor.grad_fn is not None: + inputs_grad_fns.add(tensor.grad_fn) + + # Collect all consumed grad_fns that are reachable from outputs, stopping at inputs. + # + # Note: Do not try to "optimize" by only checking inputs in the `inputs` arg. + # Without guarding on the autograd graph, we can't distinguish: + # Case 1: x, y are independent leaves -> OK, y's path not consumed + # Case 2: y = x * 2 (y.grad_fn external) -> BAD, we hit external grad_fn + # Since the same compiled code could be called with either, we must check + # ALL graph inputs for external grad_fns. + consumed_grad_fns = collect_reachable_grad_fns( + outputs_with_sources, stop_at=inputs_grad_fns + ) + + # Check if any graph input's grad_fn is in the consumed set. + # If so, autograd.grad would need to traverse through external autograd nodes, + # which we cannot trace. (If a graph input is also an autograd.grad input, + # its grad_fn is already excluded from consumed_grad_fns via stop_at.) + external_in_consumed = consumed_grad_fns & external_grad_fns + + if external_in_consumed: + sources = [ + grad_fn_to_source[gf] + for gf in external_in_consumed + if gf in grad_fn_to_source + ] + context = f"inputs with external grad_fn: {sources}" if sources else "" + unimplemented( + gb_type="autograd.grad with external grad_fn", + context=context, + explanation=( + "torch.autograd.grad() cannot trace through the autograd graph because " + "it's output depends on a tensor that was created outside " + "the compiled region and has a grad_fn attached. The autograd graph " + "extends beyond the compiled region boundary, which Dynamo cannot trace." + ), + hints=[ + "If you don't need gradients to flow back to the original tensor outside " + "the compiled region, detach the input: `tensor.detach().requires_grad_(True)`.", + "Otherwise, move the autograd.grad() call outside the compiled region.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + # Track consumed grad_fns for later validation + # (to detect returning tensors whose grad_fn was consumed by autograd.grad) + # Skip if retain_graph=True or create_graph=True since the graph is not + # consumed in those cases and can be traversed again. + retain_graph = kwargs.get("retain_graph") + create_graph = kwargs.get("create_graph") + graph_preserved = ( + isinstance(retain_graph, ConstantVariable) + and retain_graph.value is True + ) or ( + isinstance(create_graph, ConstantVariable) + and create_graph.value is True + ) + if not graph_preserved: + # Filter out AccumulateGrad nodes - they're never actually "consumed" + # by autograd. They just accumulate gradients into leaf.grad and can + # be traversed multiple times without issues. + non_leaf_consumed = { + gf + for gf in consumed_grad_fns + if type(gf).__name__ != "AccumulateGrad" + } + + # Check for double-consumption: if any grad_fn was already consumed + # by a previous autograd.grad, that's an error. + already_consumed = tx.output.autograd_grad_consumed_grad_fns + double_consumed = non_leaf_consumed & already_consumed + if double_consumed: + unimplemented( + gb_type="autograd.grad with already consumed grad_fn", + context=f"double consumed grad_fns: {len(double_consumed)}", + explanation=( + "torch.autograd.grad() is trying to consume grad_fns that were " + "already consumed by a previous autograd.grad() call. This would " + "cause 'backward through graph a second time' errors at runtime." + ), + hints=[ + "Use retain_graph=True in the first autograd.grad() call if you " + "need to compute gradients through the same graph multiple times.", + ], + ) + tx.output.autograd_grad_consumed_grad_fns.update(non_leaf_consumed) + + # Convert dict inputs to tuple for the FX graph. The engine + # always operates on flat tuples; we reconstruct the dict after. + inputs_var = args[1] if len(args) >= 2 else kwargs.get("inputs") + if isinstance(inputs_var, ConstDictVariable): + inputs_as_tuple = TupleVariable(list(inputs_var.items.values())) + if len(args) >= 2: + args = (args[0], inputs_as_tuple, *args[2:]) + else: + kwargs = {**kwargs, "inputs": inputs_as_tuple} + + with ( + torch.fx.traceback.preserve_node_meta(), + torch.fx.traceback._set_autograd_backward(), + ): + proxy = tx.output.create_proxy( + "call_function", + torch.autograd.grad, + *proxy_args_kwargs(args, kwargs), + ) + result = wrap_fx_proxy(tx=tx, proxy=proxy) + + if isinstance(inputs_var, ConstDictVariable): + if not isinstance(result, BaseListVariable): + raise AssertionError( + f"Expected BaseListVariable from autograd.grad with dict inputs, " + f"got {type(result)}" + ) + items: dict[VariableTracker, VariableTracker] = dict( + zip( + inputs_var.items.keys(), + result.items, + strict=True, + ) + ) + return ConstDictVariable(items) + return result + + @register(torch._functorch.eager_transforms._autograd_grad) + def handle_functorch_autograd_grad( + self, + tx: "InstructionTranslatorBase", + *args: VariableTracker, + **kwargs: VariableTracker, + ) -> VariableTracker | None: + """Graph-break when closure-captured tensors lose their grad_fn. + + NOTE [Detecting lost autograd linkage in closure-captured tensors] + + Functorch transforms (vjp, grad, jacrev) return closures that capture + tensors with grad_fn. When such a closure is compiled separately, those + tensors become graph placeholders whose FakeTensors lose grad_fn, + causing _autograd_grad to silently return zeros. + + _collect_placeholder_nodes gathers placeholder nodes from the + outputs/inputs args. For each, we compare grapharg.example (the real + tensor, retains grad_fn) against example_value (FakeTensor, grad_fn + is None). A mismatch means autograd linkage was lost, so we + graph-break. + + This is a pre-check only: kwargs (retain_graph, create_graph, + grad_outputs) don't affect linkage detection and are handled by + the default proxy path when this returns None. + """ + outputs_var = args[0] if len(args) >= 1 else None + inputs_var = args[1] if len(args) >= 2 else None + + if outputs_var is None or inputs_var is None: + return None + + output_placeholder_nodes = _collect_placeholder_nodes(outputs_var) + input_placeholder_nodes = _collect_placeholder_nodes(inputs_var) + + if output_placeholder_nodes and input_placeholder_nodes: + for node in output_placeholder_nodes: + fake = node.meta.get("example_value") + grapharg = node.meta.get("grapharg") + if ( + grapharg is not None + and isinstance(fake, torch.Tensor) + and fake.grad_fn is None + ): + real = grapharg.example + if isinstance(real, torch.Tensor) and real.grad_fn is not None: + unimplemented( + gb_type="_autograd_grad with lost grad_fn linkage", + context="outputs lost autograd linkage during tracing", + explanation=( + "_autograd_grad() received tensors whose grad_fn " + "was lost during tracing - this silently produces " + "zero gradients." + ), + hints=[ + "Compile the full transform instead of the returned " + "closure: torch.compile(lambda x: torch.func.vjp(f, x))", + *graph_break_hints.SUPPORTABLE, + ], + ) + return None + + return handlers + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> "VariableTracker": + source = self.source and AttrSource(self.source, name) + try: + member = getattr(self.value, name) + except AttributeError: + raise_observed_exception(AttributeError, tx) + raise + + if isinstance( + member, (torch._ops.OpOverloadPacket, torch._ops.OpOverload) + ) and torch._dynamo.trace_rules.is_aten_op_or_tensor_method(member): + return TorchInGraphFunctionVariable(member, source=source) + return variables.GetAttrVariable(self, name, source=source) + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: "dict[str, VariableTracker]", + ) -> "VariableTracker": + from . import SymNodeVariable + from .builder import wrap_fx_proxy + + if self.kind == AllowInGraphKind.NONSTRICT_TRACE: + return self._call_nonstrict_traceable_function(tx, args, kwargs) + + if self.kind == AllowInGraphKind.LEAF_FUNCTION: + return self._call_leaf_function(tx, args, kwargs) + + if self.torch_function_override_enabled(tx, args, kwargs): + return dispatch_torch_function(tx, self, args, kwargs) + + if self.can_constant_fold_through() and check_unspec_or_constant_args( + args, kwargs + ): + # constant fold functions need to be guarded. + if self.value in constant_fold_functions_need_guards: + if self.source is None: + raise AssertionError( + "Expected source to be set for constant fold function needing guards" + ) + source = CallFunctionNoArgsSource(self.source) + install_guard(source.make_guard(GuardBuilder.EQUALS_MATCH)) + # constant fold + try: + return VariableTracker.build( + tx, + self.as_python_constant()( + *[x.as_python_constant() for x in args], + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ), + ) + except (OverflowError, TypeError, ValueError) as exc: + raise_observed_exception( + type(exc), + tx, + args=list(exc.args), + ) + + if self.is_tensor_method(): + name = self.value.__name__ + # Guard against inplace view op on input tensor (not supported) + if args and args[0].is_tensor(): + tensor_var = args[0] + # Check if input tensor and inplace_view op specifically + if tensor_var.source is not None and hasattr(torch.ops.aten, name): + fn = getattr(torch.ops.aten, name) + if ( + hasattr(fn, "overloads") + and hasattr(fn, fn.overloads()[0]) + and torch.Tag.inplace_view + in getattr(fn, fn.overloads()[0]).tags + ): + unimplemented( + gb_type="Inplace op on input tensor", + context="", + explanation=f"Attempted to trace an inplace view op on input tensor {typestr(self.value)}.", + hints=[ + *graph_break_hints.SUPPORTABLE, + "Ensure you do not modify input tensor in place.", + ], + ) + return self.call_tensor_method(tx, list(args), kwargs) + + special_handler = self._get_handlers().get(self.value) + if special_handler: + result = special_handler(self, tx, *args, **kwargs) + if result: + return result + + any_symints_or_symfloats = any(isinstance(x, SymNodeVariable) for x in args) + + all_ints_or_floats = all( + isinstance(x, SymNodeVariable) or x.is_python_constant() for x in args + ) + # Intentional abstraction violation: when tensorify is enabled, + # skip this graph break. Scalar-only bin_ops on SymInt/SymFloat + # args are valid symbolic arithmetic that Dynamo can trace. + # The tensorify pass (in AOTAutograd) will convert SymFloat + # scalar ops to tensor ops downstream; SymInt ops flow through + # as symbolic expressions. + if ( + getattr(self.value, "__module__", "") == "torch" + and self.value.__name__ in bin_ops + and any_symints_or_symfloats + and all_ints_or_floats + and not _is_tensorify_enabled() + ): + msg = f"""\ +Calling {str(self.value)} on only torch.SymInt arguments is not yet supported. +To support this behavior, we need to allow const-propping tensors that store symint data. +For now, dynamo will explicitly graph break when it encounters user code with this behavior. +""" + log.warning(msg) + unimplemented( + gb_type="Attempted to call torch in-graph function on only torch.SymInt arguments", + context=f"fn={self.value}, args={args}, kwargs={kwargs}", + explanation=( + f"Attempted to call {str(self.value)} (that should be put in the FX graph) on only torch.SymInt arguments. " + "Dynamo does not support this." + ), + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + # TODO(voz): Replace w/ dynamic shape rewrite table. + # Ideally, we would be able to do this at ctor time, but alas we need a combination + # of value + args to determine this. + fn_ = self.value + if any_symints_or_symfloats: + torch_sym_op = f"_sym_{self.value.__name__}" + if getattr(self.value, "__module__", None) == "math" and hasattr( + torch, torch_sym_op + ): + fn_ = getattr(torch, torch_sym_op) + + # TODO for each of the following check on `out=` or `requires_grad=` + # variant torch ops, the original function could come from a user + # defined `@allow_in_graph` function as well, which doesn't have the + # same semantics as the torch ops. + + # Calling fake tensor propagation can mutate the out= tensor in + # tx.output.tracked_fakes. tracked_fakes are used to apply + # symbolic_shape guards. Mutating them destroys the information + # prior to tracing, which is essential for creating right + # guards. So save the shape now, and check later if it has + # changed. If it has, graph break. + saved_out_shapes = None + out_kwarg_vt = None + if "out" in kwargs: + out_kwarg_vt = kwargs["out"] + + # e.g., out=(t1, t2, ...) + if isinstance(out_kwarg_vt, (TupleVariable, ListVariable)): + saved_out_shapes = [] + for vt in out_kwarg_vt.items: + if vt.is_tensor(): + shape = vt.as_proxy().node.meta["example_value"].shape + else: + shape = None + saved_out_shapes.append(shape) + + # e.g., out=output_tensor + if out_kwarg_vt.is_tensor(): + saved_out_shapes = ( + out_kwarg_vt.as_proxy().node.meta["example_value"].shape + ) + + ctx = nullcontext + if fn_ in ops_consuming_unbacked_scalars: + if tx.fake_mode and tx.fake_mode.shape_env: + ctx = tx.fake_mode.shape_env.ignore_fresh_unbacked_symbols + + with ctx(): + tensor_variable = wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + fn_, + *proxy_args_kwargs(args, kwargs), + ), + ) + + # Handle e.g., `torch.ones(10, requires_grad=True)` + if ( + tensor_variable.is_tensor() + and "requires_grad" in kwargs + and kwargs["requires_grad"].as_python_constant() + ): + unimplemented( + gb_type="Attempted to use tensor creation function with requires_grad=True", + context=f"fn={self.value}, args={args}, kwargs={kwargs}", + explanation="Dynamo does not support this.", + hints=[ + "Create the tensor outside the compiled region.", + "Do not set `requires_grad=True`.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + # Handle e.g., `torch.add(a, b, out=result)` + if saved_out_shapes is not None: + # out variants of torch operators like torch.sort and torch.sigmoid + # mutate the tensors in the out field. + # + # However, it's non-trivial to update all references of the old + # `TensorVariable` to the new one returned (`result_var`), so we + # take the conservative approach to graph break on size changes, and + # assume other cases can fall through soundly. + # + # Note that although these tensor variables would hold different + # proxies, the in-place mutation semantics is preserved in the FX + # graph, so we won't have correctness issues. + if isinstance(saved_out_shapes, list): + for out_tensor_vt, saved_out_shape in zip( + out_kwarg_vt.items, # type: ignore[union-attr] + saved_out_shapes, + ): + if saved_out_shape is None: + # This should be extremely rare, but it's kept for now + # until we invest in enforcing the `out=` kwarg for only + # torch methods. + continue + + if not out_tensor_vt.is_tensor(): + raise AssertionError( + "Expected out= list element to be a tensor" + ) + fake_out = out_tensor_vt.proxy.node.meta["example_value"] + if saved_out_shape != fake_out.shape: + # It's hard to get out variants with resizing on graph inputs work + # properly across dynamo/aot/inductor, just fall back. + unimplemented( + gb_type="Shape mismatch with out= list of tensor variants", + context=f"fn={self.value}, args={args}, kwargs={kwargs}", + explanation=( + f"Shape mismatch when calling {self.value} with `out=`. " + f"Provided `out=` shape: {saved_out_shape}. Actual shape: {fake_out.shape}." + ), + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + if not _is_supported_out_tensor_layout( + fake_out, false_if_dde=False + ): + # It's difficult to handle strides correctly in functionalization + # when calling an out= op with a non-contiguous out argument + unimplemented( + gb_type="Attempted to call op with non-contiguous `out=` list of tensors", + context=f"self.value={self.value}, args={args}, kwargs={kwargs}", + explanation="Dynamo does not support this.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + else: + if out_kwarg_vt is None: + raise AssertionError("Expected out= kwarg to be set") + if not out_kwarg_vt.is_tensor(): + raise AssertionError("Expected out= kwarg to be a tensor") + if "example_value" not in out_kwarg_vt.as_proxy().node.meta: + raise AssertionError( + "Expected out= kwarg proxy node to have example_value metadata" + ) + fake_out = out_kwarg_vt.as_proxy().node.meta["example_value"] + if saved_out_shapes != fake_out.shape: + # It's hard to get out variants with resizing on graph inputs work + # properly across dynamo/aot/inductor, just fall back. + unimplemented( + gb_type="Shape mismatch with out= tensor variant", + context=f"fn={self.value}, args={args}, kwargs={kwargs}", + explanation=( + f"Shape mismatch when calling {self.value} with `out=`. " + f"Provided `out=` shape: {saved_out_shapes}. Actual shape: {fake_out.shape}." + ), + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + if not _is_supported_out_tensor_layout(fake_out, false_if_dde=True): + # It's difficult to handle strides correctly in functionalization + # when calling an out= op with a non-contiguous out argument + unimplemented( + gb_type="Attempted to call op with non-contiguous `out=` tensor", + context=f"self.value={self.value}, args={args}, kwargs={kwargs}", + explanation="Dynamo does not support this.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + return tensor_variable + + def _call_nonstrict_traceable_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: "dict[str, VariableTracker]", + ) -> VariableTracker: + from torch._dynamo.utils import _make_inlined + from torch._higher_order_ops.flat_apply import ( + flat_apply, + is_graphable_type, + is_valid_output, + to_graphable, + ) + from torch._higher_order_ops.invoke_leaf_function import _LeafCallable + from torch._subclasses.fake_tensor import fake_tensor_tls + from torch.utils._pytree import tree_flatten + + from .base import AsPythonConstantNotImplementedError + from .builder import SourcelessBuilder, wrap_fx_proxy + + # 1. Convert `args, kwargs` into pytree-flattened proxy forms. + # + # Rather than reconstructing `args, kwargs` into python objects and + # then tree_flatten them, we just let Dynamo symbolically interpret + # `tree_flatten((args, kwargs))`. This saves us from having to + # worry about the reconstruction logic, side effects, and guards. + args_with_states, kwargs_with_states = self._extract_nn_module_states( + tx, args, kwargs + ) + flat_args_vts, input_spec_vt = unpack_iterable( + tx, + _make_inlined(tx, tree_flatten)( + VariableTracker.build(tx, (args_with_states, kwargs_with_states)) + ), + ) + if not isinstance(flat_args_vts, ListVariable): + raise AssertionError( + f"Expected flat_args_vts to be a ListVariable, got {type(flat_args_vts)}" + ) + + # Handle the case when the input contains a non-graphable type. + for flat_arg_vt in flat_args_vts.items: + arg_type = flat_arg_vt.python_type() + if not is_graphable_type(arg_type): + type_name = flat_arg_vt.python_type().__qualname__ + unimplemented( + gb_type="Invalid input type for nonstrict_trace-ed function", + context=f"Encountered input of type <{type_name}>.", + explanation=( + "For `nonstrict_trace`-ed functions, only basic types (e.g., torch.Tensor, int, float) " + "or pytree containers of those are allowed as inputs. The provided argument contains " + "an unsupported type." + ), + hints=[ + "Use one of the following to register the type with pytree:\n" + "* `torch.utils._pytree.register_constant`\n" + "* `torch.utils._pytree.register_dataclass`\n" + "* `torch.utils._pytree.register_pytree_node`", + ], + ) + + # Since we checked with `is_graphable` above, `as_proxy` on the + # flat_arg VT should always work. + proxified_flat_args = [ + flat_arg_vt.as_proxy() for flat_arg_vt in flat_args_vts.items + ] + + # The downstream `flat_apply` call requires the input spec; however, + # the spec not a graphable type, so we still have to reconstruct it + # into a python object, and store it as a constant attribute on the + # fx graph. + try: + input_spec = input_spec_vt.as_python_constant() + except AsPythonConstantNotImplementedError as e: + typ = e.vt.python_type() + type_name = typ.__qualname__ + import torch.utils._pytree as pytree + + if pytree.is_constant_class(typ): + unimplemented( + gb_type="Input marked with `pytree.register_constant` constructed in the `torch.compile` region", + context=f"Input={input_spec_vt}, offending type <{type_name}>.", + explanation=( + "Calling a `nonstrict_trace`-ed function with an input that contains an object " + f"of type <{type_name}>, which was marked with `pytree.register_constant`. However, the object " + "was constructed _inside_ the `torch.compile` region. This is not supported." + ), + hints=[ + "Construct the object _outside_ the `torch.compile` region, or submit an issue to GitHub.", + *graph_break_hints.SUPPORTABLE, + ], + from_exc=e, + ) + else: + unimplemented( + gb_type="Invalid use of pytree_flatten with nonstrict_trace-ed function", + context=f"Input={input_spec_vt}, offending type <{type_name}>.", + explanation=( + "Calling a `nonstrict_trace`-ed function where one of the inputs has been registered " + f"with a `pytree_flatten` that places an object of type <{type_name}> into the context." + ), + hints=[ + "Modifying the `pytree_flatten` to avoid placing the object into the context.", + f"Apply one of the following to <{type_name}>:\n" + "* `torch.utils._pytree.register_constant`\n" + "* `torch.utils._pytree.register_dataclass`\n" + "* `torch.utils._pytree.register_pytree_node`", + *graph_break_hints.SUPPORTABLE, + ], + from_exc=e, + ) + + fn = self.value + + def patched_fn( + *args: VariableTracker, **kwargs: VariableTracker + ) -> VariableTracker: + # This enables reads to global/captured tensors, and we'll just + # treat them as constants in the graph. Note that after + # AOTDispatcher, this logic would disappear. + old_val = fake_tensor_tls.allow_non_fake_inputs_override + fake_tensor_tls.allow_non_fake_inputs_override = True + try: + res = fn(*args, **kwargs) + finally: # reset even when `fn` raises + fake_tensor_tls.allow_non_fake_inputs_override = old_val + return res + + f_callable = _LeafCallable(patched_fn) + + f_callable_proxy = tx.output.register_static_attr_and_return_proxy( + f"{fn.__name__}_callable", f_callable + ) + input_spec_proxy = tx.output.register_static_attr_and_return_proxy( + fn.__name__ + "_input_spec", + # pyrefly: ignore [unbound-name] + input_spec, + ) + f_callable_proxy.node.type = type(f_callable) + # pyrefly: ignore [unbound-name] + input_spec_proxy.node.type = type(input_spec) + all_args = (f_callable_proxy, input_spec_proxy, *proxified_flat_args) + + # 2. Create a proxy call to `flat_apply`, then fake-tensor propagate + # the call and wrap output into a VariableTracker. + + # What's going on here? The output of the nonstrict-traced function must + # be something we can put into the graph. This means it has to be Tuple, + # int, str, etc or lists/tuples of those (or lists of lists of those, + # etc). So by default we don't handle PyTree-able outputs. + + # To handle PyTree-able outputs we flatten the output to a flattened + # list of graph types and then trace the unflattening into the graph. + captured_spec: TreeSpec | None = None + + def flat_apply_capture(*args: Any) -> list[object]: + nonlocal captured_spec + out = flat_apply(*args, checked_output=False) + # Output is handled similar to flat_apply input but reverse by + # tree_flattening the output and trace the unflattening. Note that + # wrapped functions must return the same pytree structure every time + # they're called. + flat_out, spec = to_graphable(out) + if captured_spec is None: + captured_spec = spec + else: + if captured_spec != spec: + raise AssertionError( + "Error: nonstrict-traced functions must return the same " + f"output shape every time. got {spec!r} vs but expected {captured_spec!r}" + ) + if not is_valid_output(flat_out): + raise AssertionError( + "Nonstrict-traced function returned invalid output" + ) + return flat_out + + proxy = tx.output.create_proxy( + "call_function", flat_apply_capture, all_args, {} + ) + + # Instead of calling tree_unflatten at runtime, symbolically trace it + # just like we did for tree_flatten on inputs. This lets Dynamo + # capture the unflatten into the FX graph as well. + + # Build VTs representing (flat_output_list, out_spec) + try: + proxy_list_vt = wrap_fx_proxy(tx, proxy) + except ( + # From `handle_traced_output`. + torch._dynamo.exc.Unsupported, + # From `flat_apply` assert on output type. + torch._dynamo.exc.TorchRuntimeError, + # From fake tensor eval in _get_fake_value_impl. + torch._dynamo.exc.FakeTensorObservedException, + ): + unimplemented( + gb_type="Unsupported output type for nonstrict_trace-ed function", + context=f"Function: {fn.__name__}", + explanation=( + "For `nonstrict_trace`-ed functions, only basic types (e.g., torch.Tensor, int, list)" + " are allowed as output. The result of this call contains an unsupported type." + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + # pyrefly error: why doesn't it recognize unimplemented() as NoReturn? + raise AssertionError("unreachable") # noqa: B904 + + if captured_spec is None: + raise AssertionError("captured_spec was not set during nonstrict trace") + out_spec_vt = VariableTracker.build(tx, captured_spec) + + # Reuse the same pattern used above for tree_flatten: call the python + # function through Dynamo so it symbolically interprets it. + out_vt = SourcelessBuilder.create(tx, _pytree.tree_unflatten).call_function( + tx, [proxy_list_vt, out_spec_vt], {} + ) + + return out_vt + + def _extract_nn_module_states( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> tuple[VariableTracker, VariableTracker]: + """ + Extract nn.Module states from arguments for leaf function invocation. + + Replaces nn.Module arguments with LeafModuleState objects containing + the module's index (for later retrieval), parameters, and buffers. + """ + import torch.utils._pytree as pytree + from torch._dynamo.graph_bytecode_inputs import register_user_object + from torch._dynamo.utils import _make_inlined + from torch._higher_order_ops.invoke_leaf_function import ( + convert_modules_to_states, + ) + + from .nn_module import NNModuleVariable, UnspecializedNNModuleVariable + + def is_module_variable( + var: VariableTracker, + ) -> TypeIs[Union["NNModuleVariable", "UnspecializedNNModuleVariable"]]: + return isinstance(var, (NNModuleVariable, UnspecializedNNModuleVariable)) + + flat_args_var, tree_spec_var = unpack_iterable( + tx, + _make_inlined(tx, pytree.tree_flatten)( + VariableTracker.build(tx, (args, kwargs)) + ), + ) + + module_to_index: dict[int, int] = {} + for arg in unpack_iterable(tx, flat_args_var): + if is_module_variable(arg): + if arg.source is None: + unimplemented( + gb_type="leaf_function: nn.Module argument without source", + context=f"module type: {type(arg.value).__name__}", + explanation=( + "leaf_function received an nn.Module argument that cannot be " + "traced back to its origin. This typically happens when the " + "module is created dynamically inside the compiled region." + ), + hints=[ + "Ensure the nn.Module is created outside the compiled function " + "and passed as an argument.", + "If the module is a class attribute, access it via self.module_name.", + ], + ) + if arg.source is None: # make linter happy + raise AssertionError("Expected arg.source to be set") + module_to_index[id(arg.value)] = register_user_object( + arg.value, arg.source + ) + + if not module_to_index: + args_var = VariableTracker.build(tx, tuple(args)) + kwargs_var = VariableTracker.build(tx, kwargs) + return args_var, kwargs_var + + module_to_index_var = VariableTracker.build(tx, module_to_index) + + result_var = _make_inlined(tx, convert_modules_to_states)( + VariableTracker.build(tx, (args, kwargs)), module_to_index_var + ) + return unpack_iterable(tx, result_var) # pyrefly: ignore [bad-return] + + def _call_leaf_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + import torch.utils._pytree as pytree + from torch._dynamo.utils import _make_inlined + from torch._higher_order_ops.invoke_leaf_function import ( + _LeafCallable, + invoke_leaf_function, + make_leaf_function_wrappers, + ) + + from .builder import wrap_fx_proxy + + decorated_fn = self.value + real_impl = decorated_fn._torchdynamo_leaf_real_fn + fake_impl = decorated_fn._torchdynamo_leaf_fake_fn + mutates_args = decorated_fn._torchdynamo_leaf_mutates_args + + if fake_impl is None: + raise ValueError( + f"leaf_function '{getattr(decorated_fn, '__name__', decorated_fn)}' " + "requires a fake implementation. Please provide one using the @.register_fake " + "decorator. See the leaf_function docstring for details." + ) + + args_with_states, kwargs_with_states = self._extract_nn_module_states( + tx, args, kwargs + ) + + flat_args_var, input_spec_var = unpack_iterable( + tx, + _make_inlined(tx, pytree.tree_flatten)( + VariableTracker.build(tx, (args_with_states, kwargs_with_states)) + ), + ) + flat_arg_proxies = [ + arg.as_proxy() for arg in unpack_iterable(tx, flat_args_var) + ] + input_spec = input_spec_var.as_python_constant() + + mutated_flat_indices = "" + if mutates_args: + from torch._higher_order_ops.invoke_leaf_function import ( + _resolve_mutated_flat_indices, + ) + + try: + mutated_flat_indices = _resolve_mutated_flat_indices( + real_impl, mutates_args, len(flat_arg_proxies), input_spec + ) + except ValueError as e: + raise UserError(UserErrorType.INVALID_INPUT, str(e)) from e + + # Single-element mutable list so the wrappers can write back the output + # TreeSpec. Read captured_out_spec[0] after the wrappers have been called. + captured_out_spec: list[pytree.TreeSpec | None] = [None] + wrapped_real_impl, wrapped_fake_impl = make_leaf_function_wrappers( + real_impl, fake_impl, captured_out_spec + ) + + real_impl_callable = _LeafCallable(wrapped_real_impl) + fake_impl_callable = _LeafCallable(wrapped_fake_impl) + hook_fn = getattr(decorated_fn, "_torchdynamo_leaf_hook_fn", None) + if hook_fn is not None: + hook_fake_fn = getattr(decorated_fn, "_torchdynamo_leaf_hook_fake_fn", None) + real_impl_callable._leaf_hook_real_fn = hook_fn # type: ignore[attr-defined] + real_impl_callable._leaf_hook_fake_fn = hook_fake_fn # type: ignore[attr-defined] + + def make_callable_proxy(name: str, spec: Any) -> Any: + proxy = tx.output.register_static_attr_and_return_proxy(name, spec) + proxy.node.type = type(spec) + return proxy + + real_impl_proxy = make_callable_proxy("real_fn", real_impl_callable) + fake_impl_proxy = make_callable_proxy("fake_fn", fake_impl_callable) + input_spec_proxy = make_callable_proxy("input_spec", input_spec) + + invoke_args = ( + real_impl_proxy, + fake_impl_proxy, + input_spec_proxy, + mutated_flat_indices, + *flat_arg_proxies, + ) + result_proxy = tx.output.create_proxy( + "call_function", invoke_leaf_function, invoke_args, {} + ) + + flat_output_vt = wrap_fx_proxy(tx, result_proxy) + + if captured_out_spec[0] is None: + raise AssertionError( + "Output spec was not captured during fake tensor propagation. " + "This should not happen - please report a bug." + ) + out_spec_vt = VariableTracker.build(tx, captured_out_spec[0]) + return _make_inlined(tx, _pytree.tree_unflatten)(flat_output_vt, out_spec_vt) + + def _call_ntuple( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + """inline behavior of torch.nn.modules.utils._ntuple""" + if self.value is torch.nn.modules.utils._ntuple: + count = args[0].as_python_constant() + else: + count = self.value.__closure__[0].cell_contents + if not isinstance(count, int): + raise AssertionError( + f"Expected count to be an int in _ntuple, got {type(count)}" + ) + if kwargs: + raise AssertionError(f"_ntuple expects no kwargs, got {len(kwargs)}") + + def handle_ntuple(value: VariableTracker) -> VariableTracker: + if vt_is_iterable(value): + return variables.TupleVariable(unpack_iterable(tx, value)) + elif value.is_python_constant(): + # constant prop through it + return VariableTracker.build( + tx, + torch.nn.modules.utils._ntuple(count)(value.as_python_constant()), + ) + else: + unimplemented( + gb_type="Attempted to use `torch.nn.modules.utils._ntuple` with unsupported argument type", + context=f"value={value}", + explanation="Dynamo does not support this.", + hints=[ + "Change use of _ntuple with argument as constant or tensor.", + ], + ) + + if self.value is torch.nn.modules.utils._ntuple: + return variables.LambdaVariable(handle_ntuple) + else: + return handle_ntuple(args[0]) + + @classmethod + def call_nn_parameter( + cls, + tx: "InstructionTranslatorBase", + data: Any | None = None, + requires_grad: bool = True, + ) -> VariableTracker: + """A call to torch.nn.Parameter() gets lifted to before the graph""" + if tx.export: + unimplemented( + gb_type="Attempted to use `torch.nn.Parameter()` with export", + context="", + explanation="Dynamo does not support this.", + hints=[ + "Do not use `torch.nn.Parameter()` with export.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + if isinstance(requires_grad, variables.VariableTracker): + try: + requires_grad = requires_grad.as_python_constant() + except NotImplementedError: + unimplemented( + gb_type="non-constant `requires_grad` argument to `torch.nn.Parameter`", + context=f"requires_grad={requires_grad}", + explanation="Dynamo does not support this.", + hints=[ + "Change `requires_grad` to be a bool.", + *graph_break_hints.USER_ERROR, + ], + ) + + if data is None or not data.is_tensor(): + unimplemented( + gb_type="`torch.nn.Parameter()` with unsupported data type", + context=f"data={data}", + explanation="Called `torch.nn.Parameter()` with non-Tensor argument.", + hints=[ + "Ensure the argument to `torch.nn.Parameter()` is a `torch.Tensor`.", + *graph_break_hints.USER_ERROR, + ], + ) + + # this results in cleaner graphs, but only works for inputs + if data.source: + return cls._nn_param_via_prefix_insert(tx, data, requires_grad) + + if config.graph_break_on_nn_param_ctor: + # Need user to manually move since we cannot + unimplemented( + gb_type="Attempted to use `torch.nn.Parameter()` constructor with Dynamo", + context="", + explanation="Dynamo does not support this", + hints=[ + "Try to construct `torch.nn.Parameter()` outside the compiled region.", + "If this is not possible, turn `graph_break_on_nn_param_ctor` off", + *graph_break_hints.SUPPORTABLE, + ], + ) + + # TODO[@lucaskabela]: Remove the behavior below since it is deprecated + if isinstance( + data, + TensorWithTFOverrideVariable, + ) or is_traceable_wrapper_subclass_type(data.class_type): + unimplemented( + gb_type="Attempted to use torch.nn.Parameter constructor with tensor subclass", + context=str(data), + explanation="Dynamo does not support this.", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + + if not can_convert_to_tracable_parameter(): + unimplemented( + gb_type="`torch.nn.Parameter`: cannot convert to traceable tracable", + context="", + explanation="convert_tracable_parameter is set to False.", + hints=[ + "Check usage of context manager: do_not_convert_to_tracable_parameter", + *graph_break_hints.DIFFICULT, + ], + ) + + try: + shape = tuple(data.tp_getattro_impl(tx, "shape").as_python_constant()) + dtype = data.tp_getattro_impl(tx, "dtype").as_python_constant() + device = data.tp_getattro_impl(tx, "device").as_python_constant() + except NotImplementedError as e: + unimplemented( + gb_type="`torch.nn.Parameter` with non-constant Tensor attributes", + context=f"data={data}", + explanation="Dynamo does not support this.", + hints=[ + "Ensure the Tensor argument's shape, dtype, and device are correct.", + *graph_break_hints.USER_ERROR, + ], + from_exc=e, + ) + + placeholder = tx.output.synthetic_graph_input( + new_parameter_placeholder, + (shape, dtype, device, requires_grad), + ) + if data.requires_grad: + data = data.call_method(tx, "detach", [], {}) + + from .builder import wrap_fx_proxy + + result = wrap_fx_proxy( + tx, + tx.output.create_proxy( + "call_function", + tracable_create_parameter, + (data.as_proxy(), placeholder.as_proxy()), + {}, + ), + # In reconstruct() we should use the original parameter. The one + # returned by the graph will be an alias. + source=placeholder.source, + ) + if not result.is_tensor(): + raise AssertionError( + "Expected result of traceable_create_parameter to be a tensor" + ) + result.class_type = torch.nn.Parameter # type: ignore[union-attr] + + # TODO(jansel/bdhirsh) - There is some issue with + # tracable_create_parameter. It does not seem to use the right + # grad_enabled. Since this is parameter, we can just override the + # has_grad_fn field to False to workaround the issue. + result.has_grad_fn = False # type: ignore[union-attr] + + # Register this parameter as a leaf tensor for backward() auto-detection. + # When backward() is called without inputs, we need to find all leaf tensors, + # including those created in-graph like nn.Parameter. + tx.output.leaf_var_creation_order.append(result) + + # TODO(jansel): if the new param falls out of scope, currently it won't get freed until + # the end of the graph. We should fix this. + return result + + @staticmethod + def _nn_param_via_prefix_insert( + tx: "InstructionTranslatorBase", data: Any, requires_grad: bool + ) -> VariableTracker: + # Alternate version if we have a .source + varname = tx.output.new_var() + + # construct the nn.Parameter before the graph save it to varname + if tx.output.root_tx is None: + raise AssertionError("Expected tx.output.root_tx to be set") + cg = PyCodegen(tx.output.root_tx) + cg.add_push_null(lambda: cg.load_import_from("torch.nn", "Parameter")) + cg(data.source) + cg(VariableTracker.build(tx, requires_grad)) + cg.call_function(2, False) + cg.store(varname) + tx.output.pregraph_bytecode.extend(cg.get_instructions()) + + data_node = data.as_proxy().node + if data_node.op not in ("placeholder", "get_attr"): + unimplemented( + gb_type="Unexpected type of data placeholder op for parameter construction", + context=f"data_node.op={data_node.op}", + explanation="Data node op should be placeholder or get_attr.", + hints=[ + *graph_break_hints.DIFFICULT, + ], + ) + + # add the newly constructed nn.Parameter as a graph input + source = SyntheticLocalSource(varname) + example_value = torch.nn.Parameter( + tx.output.example_value_from_input_node(data.as_proxy().node), + requires_grad=requires_grad, + ) + result = VariableTracker.build(tx, example_value, source) + # Realize the VT because we will delete the guards on it in the next line. + result = result.realize() + # No need to guard on this since we already guarded on `data`. + # These guards would fail since varname doesn't exist until after the function starts + TracingContext.get().guards_context.dynamo_guards.remove_guards_with_source( + source + ) + return result + + def call_tensor_method( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + return args[0].call_method(tx, self.get_function().__name__, args[1:], kwargs) + + def is_tensor_method(self) -> bool: + from ..trace_rules import get_tensor_method + + return ( + inspect.ismethoddescriptor(self.get_function()) + and hasattr(self.get_function(), "__objclass__") + # pyrefly: ignore[missing-attribute] + and self.get_function().__objclass__ == torch._C.TensorBase + ) or self.get_function() in get_tensor_method() + + def torch_function_override_enabled( + self, + tx: "InstructionTranslatorBase", + args: Iterable[Any], + kwargs: dict[str, Any], + ) -> bool: + return ( + self.get_function() in get_overridable_functions() + or isinstance( + self.get_function(), + (torch._ops.OpOverload, torch._ops.OpOverloadPacket), + ) + ) and can_dispatch_torch_function(tx, args, kwargs) + + +class DispatchKeySetVariable(BaseTorchVariable): + """represents torch.DispatchKeySet""" + + @staticmethod + def create(value: DispatchKeySet, **kwargs: Any) -> "DispatchKeySetVariable": + return DispatchKeySetVariable(value, **kwargs) + + @classmethod + def create_with_source( + cls, value: DispatchKeySet, source: Source + ) -> "DispatchKeySetVariable": + install_guard(source.make_guard(GuardBuilder.DISPATCH_KEY_SET_MATCH)) + return cls(value, source=source) + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + from .object_protocol import python_constant_richcompare_impl + + return python_constant_richcompare_impl(self, tx, other, op) + + def is_constant_fold_method(self, name: str) -> bool: + return name == "has" + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> "VariableTracker": + if self.is_constant_fold_method(name) and check_unspec_or_constant_args( + args, kwargs + ): + method = getattr(self.value, name) + return VariableTracker.build( + tx, + method( + *[x.as_python_constant() for x in args], + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ), + ) + elif name == "highestPriorityTypeId": + return VariableTracker.build(tx, self.value.highestPriorityTypeId()) + return super().call_method(tx, name, args, kwargs) + + +class FuncTorchInterpreterVariable(BaseTorchVariable): + """represents torch._functorch.pyfunctorch.FuncTorchInterpreter""" + + @classmethod + def create_with_source( + cls, value: Any, source: Source + ) -> "FuncTorchInterpreterVariable": + install_guard(source.make_guard(GuardBuilder.ID_MATCH)) + return cls(value, source=source) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> "VariableTracker": + if name == "key": + return VariableTracker.build(tx, self.value.key()) + elif name == "process": + return tx.inline_user_function_return( + VariableTracker.build(tx, self.value.process.__func__), + [self] + args, + kwargs, + ) + elif name in ["level", "batch_size", "randomness"]: + return VariableTracker.build(tx, getattr(self.value, name)()) + elif name == "lower": + if args: + raise AssertionError(f"lower() expects no args, got {len(args)}") + if kwargs: + raise AssertionError(f"lower() expects no kwargs, got {len(kwargs)}") + return variables.TemporarilyPopInterpreterStackCtxManagerVariable.create( + tx, None + ) + return super().call_method(tx, name, args, kwargs) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/torch_function.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/torch_function.py new file mode 100644 index 0000000000000000000000000000000000000000..310866ff0725a8a5f196b18d700c43b218c9a557 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/torch_function.py @@ -0,0 +1,789 @@ +"""TorchDynamo support for __torch_function__ tensor subclasses. + +This module implements support for tensor subclasses with __torch_function__ overrides. +A tensor subclass instance is represented as a TensorWithTFOverrideVariable, which handles +dispatching __torch_function__ on attribute accesses, method calls, and torch API calls. + +Unsupported features: +- Triggering __torch_function__ on tensor subclass non-tensor custom attributes +- Graph breaking on mutating guardable tensor properties within a __torch_function__ context + (can cause excessive recompiles in certain cases) +- Matching exact eager behavior of ignoring __torch_function__ objects in non-tensor + argument positions of Torch API calls + +Supported features: +- Static method implementations of __torch_function__ on custom objects (triggers on torch + API calls with the object as any argument) +- Triggering __torch_function__ on torch API calls with tensor subclass arguments +- __torch_function__ calls on base tensor attribute access and method calls for tensor + subclass instances +- Matches dispatch ordering behavior of eager __torch_function__ with subclass/object + arguments in any position + +See https://docs.google.com/document/d/1WBxBSvW3NXhRp9ncmtokJloMLCtF4AYNhJaffvHe8Kw/edit#heading=h.vacn73lozd9w +for more information on the design. +""" + +import collections +import contextlib +import inspect +import operator +from collections.abc import Generator, Iterable +from types import TracebackType +from typing import Any, TYPE_CHECKING + +import torch._C +import torch.utils._pytree as pytree +from torch._guards import Source +from torch.overrides import ( + _get_overloaded_args, + get_default_nowrap_functions, + TorchFunctionMode, +) +from torch.utils._device import DeviceContext + +from .. import graph_break_hints +from ..exc import unimplemented +from ..guards import GuardBuilder, install_guard +from ..polyfills import NoEnterTorchFunctionMode +from ..source import AttrSource, GlobalSource, TorchFunctionModeStackSource, TypeSource +from ..utils import ( + class_has_getattribute, + clear_torch_function_mode_stack, + get_safe_global_name, + has_torch_function, + is_tensor_base_attr_getter, + set_torch_function_mode_stack, +) +from .base import VariableTracker +from .constant import ConstantVariable +from .ctx_manager import GenericContextWrappingVariable +from .functions import UserMethodVariable +from .lazy import LazyVariableTracker +from .lists import TupleVariable +from .tensor import TensorSubclassVariable, TensorVariable +from .user_defined import UserDefinedObjectVariable + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + + +bin_ops = [ + operator.pow, + operator.mul, + operator.matmul, + operator.floordiv, + operator.truediv, + operator.mod, + operator.add, + operator.lt, + operator.gt, + operator.ge, + operator.le, + operator.ne, + operator.eq, + operator.sub, + operator.ipow, + operator.imul, + operator.imatmul, + operator.ifloordiv, + operator.itruediv, + operator.imod, + operator.iadd, + operator.isub, +] + +bin_int_ops = [ + operator.and_, + operator.or_, + operator.xor, + operator.iand, + operator.ixor, + operator.ior, +] + +un_int_ops = [operator.invert] + +tensor_and_int_ops = [ + operator.lshift, + operator.rshift, + operator.ilshift, + operator.irshift, + operator.getitem, +] + +un_ops = [ + operator.abs, + operator.pos, + operator.neg, + operator.not_, # Note: this has a local scalar dense call + operator.length_hint, +] + + +banned_attrs = [ + fn.__self__.__name__ # type: ignore[attr-defined] + for fn in get_default_nowrap_functions() + if is_tensor_base_attr_getter(fn) +] + + +class TorchFunctionModeVariable(GenericContextWrappingVariable): + @staticmethod + def is_supported_torch_function_mode(ty: type[TorchFunctionMode]) -> bool: + # Supported in this sense means we can support graph breaks under the + # context. + # We are able to trace custom modes but if there are graph breaks under them + # and they have a custom __enter__/__exit__ we don't handle this for the + # same reason we don't handle generic context managers: there may be side effects + # that are now affected by executing the function across two frames instead of one + # Today we support the enter/exit of the default TorchFunctionMode as well as + # DeviceContext (which is used for set_default_device) + return issubclass(ty, (NoEnterTorchFunctionMode, DeviceContext)) or ( + not class_has_getattribute(ty) + and inspect.getattr_static(ty, "__enter__") is TorchFunctionMode.__enter__ + and inspect.getattr_static(ty, "__exit__") is TorchFunctionMode.__exit__ + ) + + def __init__( + self, + value: TorchFunctionMode | None, + source: Source | None = None, + **kwargs: Any, + ) -> None: + if value is not None: + super().__init__(value, **kwargs) + self.value = value + # needed for BC with calling enter from CM code + self.cm_obj = value # type: ignore[assignment] + self.source = source # type: ignore[assignment] + + def reconstruct(self, codegen: "PyCodegen") -> None: + # This shouldn't be called unless we have a source + if not self.source: + raise AssertionError( + "TorchFunctionModeVariable requires a source for reconstruct" + ) + self.source.reconstruct(codegen) + + def module_name(self) -> str: + return self.value.__module__ + + def fn_name(self) -> str: + return type(self.value).__name__ + + def python_type(self) -> type: + return type(self.value) + + def call_torch_function( + self, + tx: "InstructionTranslatorBase", + fn: VariableTracker, + types: TupleVariable, + args: Iterable[Any], + kwargs: dict[str, Any], + ) -> VariableTracker: + return call_torch_function( + tx, + get_torch_function_fn(tx, self), # type: ignore[arg-type] + fn, + types, + args, + kwargs, + ) + + def enter(self, tx: "InstructionTranslatorBase") -> VariableTracker: + from .torch import TorchInGraphFunctionVariable + + if isinstance(self.value, NoEnterTorchFunctionMode): + return ConstantVariable.create(None) + + TorchInGraphFunctionVariable( + torch._C._push_on_torch_function_stack + ).call_function(tx, [self], {}) + return ConstantVariable.create(None) + + def exit(self, tx: "InstructionTranslatorBase", *args: Any) -> VariableTracker: + from .torch import TorchInGraphFunctionVariable + + TorchInGraphFunctionVariable(torch._C._pop_torch_function_stack).call_function( + tx, [], {} + ) + return ConstantVariable.create(None) + + def reconstruct_type(self, codegen: "PyCodegen") -> None: + ty = NoEnterTorchFunctionMode + codegen( + AttrSource( + codegen.tx.import_source(ty.__module__), + ty.__name__, + ) + ) + + def supports_graph_breaks(self) -> bool: + return True + + def exit_on_graph_break(self) -> bool: + return False + + +# Used to clear/restore the python torch function mode stack and temporarily restore it as needed +class TorchFunctionModeStackStateManager: + def __init__(self) -> None: + self.stack: list[Any] = [] + + def __enter__(self) -> None: + self.stack = torch.overrides._get_current_function_mode_stack() + clear_torch_function_mode_stack() + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + set_torch_function_mode_stack(self.stack) + self.stack = [] + + @contextlib.contextmanager + def temp_restore_stack(self) -> Generator[None, None, None]: + prev = torch.overrides._get_current_function_mode_stack() + set_torch_function_mode_stack(self.stack) + try: + yield + finally: + set_torch_function_mode_stack(prev) + + +torch_function_mode_stack_state_mgr = TorchFunctionModeStackStateManager() + + +class SymbolicTorchFunctionState: + def __init__(self, py_stack: Iterable[Any], skip_next: bool) -> None: + # This is annoyingly complicated because of how the torch function subclass + mode C API was designed + # There are two exposed C knobs here as contexts: torch._C.DisableTorchFunction and torch._C.DisableTorchFunctionSubclass + # These are their definitions: + # 1) torch._C._is_torch_function_enabled indicates that neither of the above knobs have been entered + # (if either are entered, this will be False) + # 2) torch._C._is_torch_function_mode_enabled indicates that either the torch mode stack is empty OR + # torch._C.DisableTorchFunction has been entered + # To disambiguate these and keep myself sane I added a C API to check whether all torch function + # concepts (modes and subclasses) are enabled. + # This only returns true iff we have not entered torch._C.DisableTorchFunction and allows us to separate + # the stack length from the enablement state of torch function modes. + # This is important because now if a mode is pushed while dynamo is tracing, we know whether + # or not torch function modes are enabled and whether we should trace it. + self.torch_function_subclass_enabled = torch._C._is_torch_function_enabled() + + # Mirrors PythonTorchFunctionTLS::skip_next in C++. + # Set by _skip_one_hop_torch_function, consumed by has_torch_function. + # The real TLS flag is consumed by save_global_state in + # OutputGraph.__init__ (which runs before this) and passed in here. + # On tracing failure, restore_graphstate restores the real TLS. + self.skip_next = skip_next + + # This differs from the C API of the same name + # this will only be false iff we have entered torch._C.DisableTorchFunction + # and does not take into account the mode stack length, while the C API bundles these + # two concepts + self.torch_function_mode_enabled = ( + not torch._C._is_torch_function_all_disabled() + ) + + self.cur_mode = None + + TorchFunctionModeStackVariable.reset() + + self.mode_stack: collections.deque[TorchFunctionModeVariable] = ( + collections.deque() + ) + + for i, val in enumerate(py_stack): + self.mode_stack.append( + LazyVariableTracker.create(val, source=TorchFunctionModeStackSource(i)) # type: ignore[arg-type] + ) + + def in_torch_function_mode(self) -> bool: + return len(self.mode_stack) > 0 + + def pop_torch_function_mode(self) -> TorchFunctionModeVariable: + return self.mode_stack.pop() + + def push_torch_function_mode(self, mode_var: TorchFunctionModeVariable) -> None: + self.mode_stack.append(mode_var) + + def call_torch_function_mode( + self, + tx: "InstructionTranslatorBase", + fn: VariableTracker, + types: TupleVariable, + args: Iterable[Any], + kwargs: dict[str, Any], + ) -> Any: + with self._pop_mode_for_inlining() as cur_mode: + return cur_mode.call_torch_function(tx, fn, types, args, kwargs) + + @contextlib.contextmanager + def _pop_mode_for_inlining( + self, + ) -> Generator[TorchFunctionModeVariable, None, None]: + old_mode = self.cur_mode + self.cur_mode = self.pop_torch_function_mode() # type: ignore[assignment] + try: + yield self.cur_mode # type: ignore[misc] + finally: + mode = self.cur_mode + self.cur_mode = old_mode + self.push_torch_function_mode(mode) # type: ignore[arg-type] + + +class TorchFunctionModeStackVariable(VariableTracker): + """Fake VT to use as a dummy object, indicating the presence of torch function mode stack mutation""" + + # singleton value representing the global torch function mode stack + # singleton (it exists in C++) + stack_value_singleton = object() + + # offset is used to track if we have inserted/removed a + # device context which is always placed at the bottom of the stack + # if a device context is inserted, the graph will run this mutation + # so when we want to reconstruct any other modes on the stack + # their indices should be shifted right by 1 (+1) + # Conversely, if there was a device context on the stack, and the graph + # mutates the stack to remove that context (set default device to None) + # each of the indices of other modes should be shifted left by 1 (-1) + offset = 0 + + def __init__( + self, + source: Source, + symbolic_stack: collections.deque[TorchFunctionModeVariable], + ) -> None: + self.source = source + self.symbolic_stack = symbolic_stack + + @classmethod + def reset(cls) -> None: + cls.offset = 0 + + @classmethod + def register_mutation(cls, tx: "InstructionTranslatorBase") -> None: + if cls.stack_value_singleton not in tx.output.side_effects: + var = cls( + source=Source(), + symbolic_stack=tx.symbolic_torch_function_state.mode_stack, + ) + tx.output.side_effects.track_mutable(cls.stack_value_singleton, var) + tx.output.side_effects.mutation(var) + + @classmethod + def register_device_context_insertion(cls, tx: "InstructionTranslatorBase") -> None: + stack = tx.symbolic_torch_function_state.mode_stack + if stack and cls.is_device_context(stack[0]): + return + else: + cls.offset += 1 + stack.insert( + 0, + TorchFunctionModeVariable( + None, source=TorchFunctionModeStackSource(-cls.offset) + ), + ) + + @classmethod + def clear_default_device(cls, tx: "InstructionTranslatorBase") -> None: + stack = tx.symbolic_torch_function_state.mode_stack + if stack and cls.is_device_context(stack[0]): + stack.popleft() + cls.offset -= 1 + + @staticmethod + def is_device_context(var: TorchFunctionModeVariable) -> bool: + return isinstance(var.value, DeviceContext) or var.value is None + + @classmethod + def get_mode_index(cls, ind: int) -> int: + return ind + cls.offset + + +def _get_all_args( + args: Iterable[Any], kwargs: dict[str, Any] +) -> Iterable[VariableTracker]: + return _flatten_vts(pytree.arg_tree_leaves(*args, **kwargs)) + + +def _flatten_vts(vts: Iterable[VariableTracker]) -> list[VariableTracker]: + from collections import deque + + from .dicts import ConstDictVariable + from .lists import ListVariable + + vts = deque(vts) + output = [] + + while vts: + vt = vts.popleft() + + if not vt.is_realized() and vt.peek_type() in (dict, list, tuple): # type: ignore[attr-defined] + vt.realize() + + if vt.is_realized(): + if isinstance(vt, ListVariable): + vts.extend(vt.items) + continue + elif isinstance(vt, ConstDictVariable): + vts.extend(vt.items.values()) + continue + + output.append(vt) + + return output + + +def _get_subclass_type(var: VariableTracker) -> type: + if not isinstance(var, (TensorWithTFOverrideVariable, UserDefinedObjectVariable)): + raise AssertionError(f"Unexpected type {type(var)}") + return var.python_type() + + +def _get_subclass_type_var( + tx: "InstructionTranslatorBase", var: VariableTracker +) -> VariableTracker: + if isinstance(var, TensorWithTFOverrideVariable): + return var.class_type_var(tx) + elif isinstance(var, UserDefinedObjectVariable): + source = var.source and TypeSource(var.source) + return VariableTracker.build(tx, var.python_type(), source) + else: + raise AssertionError(f"Unexpected type {type(var)}") + + +def _is_attr_overridden( + tx: "InstructionTranslatorBase", var: VariableTracker, name: str +) -> bool: + if not isinstance(var, (TensorWithTFOverrideVariable, UserDefinedObjectVariable)): + return False + import torch + + overridden = False + try: + attr_val = inspect.getattr_static(var.python_type(), name) + overridden |= attr_val != getattr(torch.Tensor, name) + except AttributeError: + pass + + return overridden + + +def call_torch_function( + tx: "InstructionTranslatorBase", + torch_function_var: VariableTracker, + fn: VariableTracker, + types: TupleVariable, + args: Iterable[Any], + kwargs: dict[str, Any], + *, + is_subclass_dispatch: bool = False, +) -> Any: + # This emulates calling __torch_function__, which has a signature + # def __torch_function__(cls, func, types, args=(), kwargs=None): + # + # Also notice the `cls` is not explicitly passed in the reference + # implementations: + # 1. https://github.com/pytorch/pytorch/blob/8d81806211bc3c0ee6c2ef235017bacf1d775a85/torch/csrc/utils/python_arg_parser.cpp#L368-L374 + # 2. https://github.com/pytorch/pytorch/blob/8d81806211bc3c0ee6c2ef235017bacf1d775a85/torch/overrides.py#L1741-L1743 + tf_args = [ + fn, + types, + VariableTracker.build(tx, tuple(args)), + VariableTracker.build(tx, kwargs), + ] + # Mirror the C++ THPModule_disable_torch_function behavior: disable + # __torch_function__ subclass dispatch during the call to prevent + # re-entrant dispatch on operations inside __torch_function__. + # Only do this for subclass dispatch, not mode dispatch. Modes need + # subclass dispatch to remain enabled because the mode's + # __torch_function__ may re-dispatch to the subclass. + tf_state = tx.symbolic_torch_function_state + old_subclass_enabled = tf_state.torch_function_subclass_enabled + if is_subclass_dispatch and old_subclass_enabled: + tf_state.torch_function_subclass_enabled = False + try: + return torch_function_var.call_function(tx, tf_args, {}) + finally: + tf_state.torch_function_subclass_enabled = old_subclass_enabled + + +def get_torch_function_fn( + tx: "InstructionTranslatorBase", vt: VariableTracker +) -> VariableTracker: + # The underlying function could be a classmethod, staticmethod, regular + # function or a function with C-implementation. It doesn't matter as long as + # they satisfy the calling convention in `call_torch_function`. + + args = [vt, VariableTracker.build(tx, "__torch_function__")] + func_vt = VariableTracker.build(tx, getattr).call_function(tx, args, {}) + return func_vt + + +def can_dispatch_torch_function( + tx: "InstructionTranslatorBase", args: Iterable[Any], kwargs: dict[str, Any] +) -> bool: + has_overridden_args = any( + has_torch_function(arg) for arg in _get_all_args(args, kwargs) + ) + tf_state = tx.symbolic_torch_function_state + return (has_overridden_args and tf_state.torch_function_subclass_enabled) or ( + tf_state.torch_function_mode_enabled and tf_state.in_torch_function_mode() + ) + + +def dispatch_torch_function( + tx: "InstructionTranslatorBase", + fn: VariableTracker, + args: Iterable[Any], + kwargs: dict[str, Any], +) -> Any: + """Gathers all args that are TensorWithTFOverrideVariable and dispatches based on the ordering in _get_overloaded_args""" + + all_args = _get_all_args(args, kwargs) + overloaded_args = _get_overloaded_args( + [arg for arg in all_args if has_torch_function(arg)], + _get_subclass_type, + ) + + types = TupleVariable([_get_subclass_type_var(tx, arg) for arg in overloaded_args]) + + if tx.symbolic_torch_function_state.in_torch_function_mode(): + res = tx.symbolic_torch_function_state.call_torch_function_mode( + tx, fn, types, args, kwargs + ) + if not res.is_constant_match(NotImplemented): + return res + + for arg in overloaded_args: + res = arg.call_torch_function( + tx, + fn, + types, + args, + kwargs, + ) + + if not res.is_constant_match(NotImplemented): + tx.output.torch_function_subclass_inlined = True + return res + + unimplemented( + gb_type="All __torch_function__ overrides returned NotImplemented due to TypeError from user code", + context=f"{fn=}, {args=}, {kwargs=}", + explanation=f"All __torch_function__ overrides for function {fn} returned NotImplemented", + hints=[ + *graph_break_hints.USER_ERROR, + ], + ) + + +class TensorWithTFOverrideVariable(TensorVariable): + """ + Represents a tensor subclass instance with a __torch_function__ override. + """ + + @classmethod + def from_tensor_var( + cls, + tx: "InstructionTranslatorBase", + tensor_var: VariableTracker, + class_type: type, + cls_source: Source | None, + ) -> "TensorWithTFOverrideVariable": + # [Note: __torch_function__] coerce `tensor_var` into a + # TensorWithTFOverrideVariable. In eager, this is just a type change. + import torch + + tensor_var = tensor_var.realize() + # This simulates shallow-copying the tensor object. + kwargs = dict(tensor_var.__dict__) + input_tensor_type = kwargs.pop("class_type") + if not ( + input_tensor_type in (torch.Tensor, torch.nn.Parameter) + or issubclass(input_tensor_type, torch.Tensor) + ): + raise AssertionError( + f"invalid class type {input_tensor_type} in TensorWithTFOverrideVariable.from_tensor_var" + ) + var = cls(class_type=class_type, **kwargs) + var.install_global(tx) + return var + + def install_global(self, tx: "InstructionTranslatorBase") -> None: + # stash the subclass type to rewrap an output tensor if needed + # this is needed because the actual type needs to be available + # each time the compiled artifact is run and outputs a wrapped tensor. + if self.global_mangled_class_name(tx) not in tx.output.global_scope: + # Safe because global_mangled_class_name figures it out + tx.output.install_global_unsafe( + self.global_mangled_class_name(tx), self.class_type + ) + + def python_type(self) -> type: + return self.class_type + + def class_type_var(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return TensorSubclassVariable( + self.class_type, source=GlobalSource(self.global_mangled_class_name(tx)) + ) + + def global_mangled_class_name(self, tx: "InstructionTranslatorBase") -> str: + return get_safe_global_name( + tx, f"__subclass_{self.class_type.__name__}", self.class_type + ) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + # [Note: __torch_function__] We currently only support attributes that are defined on + # base tensors, custom attribute accesses will graph break. + import torch + + # I think only `_base` is breaking because we aren't modelling view + # relationship perfectly in some scenarios. + if name in banned_attrs: + unimplemented( + gb_type="Unsupported tensor subclass attribute access", + context=f"{name}", + explanation="`torch.compile` currently can't trace this", + hints=[ + f"Avoid accessing {name} of tensor subclass in torch.compile region", + *graph_break_hints.SUPPORTABLE, + ], + ) + + # Handle non-overridden attributes inherited from `torch.Tensor`. + attr_is_overridden = _is_attr_overridden(tx, self, name) + if ( + hasattr(torch.Tensor, name) + and not attr_is_overridden + and not inspect.ismethoddescriptor(getattr(torch.Tensor, name)) + ): + args = [self] + kwargs: dict[Any, Any] = {} + if can_dispatch_torch_function(tx, args, kwargs): + get_fn = VariableTracker.build(tx, getattr(torch.Tensor, name).__get__) + + return self.call_torch_function( + tx, + get_fn, + TupleVariable([self.class_type_var(tx)]), + args, + kwargs, + ) + else: + # `TensorVariable.tp_getattro_impl` doesn't handle user-defined + # function/attribute well, so we explicitly handle them here. + # + # TODO move this logic into `TensorVariable`, or try to merge it + # with similar logic in `UserDefinedObjectVariable`. + try: + attr = inspect.getattr_static(self.class_type, name) + except AttributeError: + pass + else: + import types + + cls_source = GlobalSource(self.global_mangled_class_name(tx)) + attr_source = AttrSource(cls_source, name) + if isinstance(attr, types.FunctionType): + install_guard(attr_source.make_guard(GuardBuilder.CLOSURE_MATCH)) + return UserMethodVariable(attr, self) + + elif isinstance(attr, property): + getter_source = AttrSource(attr_source, "fget") + getter = attr.fget + getter_var = VariableTracker.build( + tx, getter, source=getter_source, realize=True + ) + return getter_var.call_function(tx, [self], {}) + + elif isinstance(attr, classmethod): + return UserMethodVariable( + attr.__func__, self.class_type_var(tx), source=attr_source + ) + + elif attr_is_overridden: + unimplemented( + gb_type="Unsupported tensor subclass overridden attribute access", + context=f"{name}", + explanation="`torch.compile` only support tracing certain types of overridden tensor subclass attributes", + hints=[ + f"Avoid accessing {name} of tensor subclass in torch.compile region", + f"Renaming attribute `{name}` of type {self.class_type}", + *graph_break_hints.SUPPORTABLE, + ], + ) + + return super().tp_getattro_impl(tx, name) + + def call_torch_function( + self, + tx: "InstructionTranslatorBase", + fn: VariableTracker, + types: TupleVariable, + args: Iterable[Any], + kwargs: dict[str, Any], + ) -> Any: + # NOTE this assumes `__torch_function__` isn't modified during tracing. + if not hasattr(self, "torch_function_fn"): + self.torch_function_fn = get_torch_function_fn(tx, self) + + return call_torch_function( + tx, + self.torch_function_fn, + fn, + types, + args, + kwargs, + is_subclass_dispatch=True, + ) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: "dict[str, VariableTracker]", + ) -> "VariableTracker": + # This code block implements inlining the __torch_function__ override + # of `call_method`. + tf_args = [self] + list(args) + if can_dispatch_torch_function(tx, tf_args, kwargs): + import torch + + if _is_attr_overridden(tx, self, name): + unimplemented( + gb_type="Tensor subclass overridden method call", + context=f"{name}", + explanation="`torch.compile` currently can't trace this", + hints=[ + f"Avoid calling {name} of tensor subclass in torch.compile region", + f"Renaming method `{name}` of type {self.class_type}", + *graph_break_hints.SUPPORTABLE, + ], + ) + + # [Note: __torch_function__] Currently we only support methods that are defined on tensor + # we will graph break in other cases this will need a bigger overhaul of extracting methods/comparing them for equality + # We've established with the above check that the method is not overridden, so we guard that the method is the same + # as the impl defined on tensor and retrieve it + if self.source: + source = AttrSource(AttrSource(self.source, "__class__"), name) + value = inspect.getattr_static(self.python_type(), name) + else: + source = None + value = getattr(torch.Tensor, name) + func_var = VariableTracker.build(tx, value, source) + return dispatch_torch_function(tx, func_var, tf_args, kwargs) + else: + return super().call_method(tx, name, args, kwargs) diff --git a/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/user_defined.py b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/user_defined.py new file mode 100644 index 0000000000000000000000000000000000000000..dece28d92214ea56eef31ab4538d40cbcc589bd5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_dynamo/variables/user_defined.py @@ -0,0 +1,5488 @@ +""" +This module contains variable classes for handling user-defined objects in Dynamo's tracing system. + +The key classes are: +- UserDefinedVariable: Base class for representing custom Python objects +- UserDefinedClassVariable: Handles Python class objects/types +- UserDefinedObjectVariable: Fallback class for instance objects, with support for method calls, + attribute access, and other Python object behaviors. +- Specialized subclasses for common patterns: + - UserDefinedDictVariable: For dict subclasses + - UserDefinedSetVariable: For set subclasses + - UserDefinedTupleVariable: For tuple subclasses + - UserDefinedExceptionObjectVariable: For exception subclasses + - FrozenDataClassVariable: Special handling of frozen dataclasses + - MutableMappingVariable: For collections.abc.MutableMapping subclasses + +Dynamo specializes to VariableTracker subclasses like FrozenDataClassVariable if available; if no +subclass qualifies, it falls back to UserDefinedObjectVariable. + +These classes help Dynamo track and handle arbitrary Python objects during tracing, +maintaining proper semantics while enabling optimizations where possible. +""" + +import _collections # type: ignore[import-not-found] +import builtins +import collections +import contextlib +import dataclasses +import enum +import functools +import inspect +import random +import sys +import threading +import traceback +import types +import warnings +import weakref +from collections.abc import Callable, Iterable, Sequence +from typing import Any, cast, NoReturn, TYPE_CHECKING, Union +from typing_extensions import is_typeddict + +import torch._dynamo.config +import torch.nn +from torch._C._dynamo import PyNumberSlots +from torch._guards import Source, TracingContext +from torch.utils._ordered_set import OrderedSet +from torch.utils._python_dispatch import is_traceable_wrapper_subclass_type +from torch.utils._pytree import GetAttrKey, is_structseq_class + +from .. import config, graph_break_hints, polyfills, variables +from ..bytecode_transformation import create_call_function +from ..create_parameter_op import do_not_convert_to_tracable_parameter +from ..exc import ( + handle_observed_exception, + ObservedAttributeError, + ObservedKeyError, + raise_observed_exception, + raise_type_error, + unimplemented, +) +from ..graph_bytecode_inputs import get_external_object_by_index +from ..guards import GuardBuilder, install_guard +from ..source import ( + AttrSource, + CallFunctionNoArgsSource, + DictGetItemSource, + GetItemSource, + RandomValueSource, + TypeDictSource, + TypeMROSource, + TypeSource, + UnspecializedParamBufferSource, +) +from ..utils import ( + base_exception_methods, + check_constant_args, + cmp_name_to_op_mapping, + deque_iterator, + deque_methods, + deque_rev_iterator, + dict_methods, + exception_methods, + frozenset_methods, + get_custom_getattr, + has_torch_function, + is_lru_cache_wrapped_function, + is_namedtuple_cls, + is_pybind11_enum_member, + is_torch_class, + istype, + list_methods, + namedtuple_fields, + object_has_getattribute, + proxy_args_kwargs, + raise_args_mismatch, + set_methods, + tensortype_to_dtype, + tracked_repr, + tuple_methods, + unpack_iterable, + unpatched_nn_module_getattr, +) +from .base import ( + AsPythonConstantNotImplementedError, + AttrMutationKind, + GetSet, + getset_read, + Member, + Method, + MutationType, + NO_SUCH_SUBOBJ, + ValueMutationNew, + VariableTracker, +) +from .dicts import ConstDictVariable, OrderedDictVariable, pydict_check +from .hashable import HashableTracker +from .object_protocol import ( + _resolve_descriptor_get, + generic_is_true, + generic_repr, + is_nb_not_implemented, + mro_lookup, + pynumber_as_ssize_t, + pynumber_index, + type_implements_nb_slot, +) +from .sets import SetVariable + + +try: + import numpy as np +except ModuleNotFoundError: + np = None # type: ignore[assignment] + +try: + from torch.utils._cxx_pytree import PyTreeSpec +except ImportError: + PyTreeSpec = type(None) # type: ignore[misc, assignment] + + +_SAFE_C_SLOTS: OrderedSet[object] | None = None + + +def _safe_c_slots() -> OrderedSet[object]: + """C slot wrappers known to be safe to call at trace time. + + Covers tp_hash and tp_richcompare slots for C extension types. + Used by UDOV's hash_impl and tp_richcompare_impl MRO walks. + """ + global _SAFE_C_SLOTS + if _SAFE_C_SLOTS is None: + import datetime + import decimal + import re + + _SAFE_C_SLOTS = OrderedSet() + for tp in ( + datetime.datetime, + datetime.date, + datetime.time, + datetime.timedelta, + datetime.timezone, + decimal.Decimal, + re.Pattern, + ): + _SAFE_C_SLOTS.add(tp.__hash__) + for dunder in ("__eq__", "__ne__", "__lt__", "__le__", "__gt__", "__ge__"): + if hasattr(tp, dunder): + _SAFE_C_SLOTS.add(getattr(tp, dunder)) + return _SAFE_C_SLOTS + + +def _safe_c_tp_hash_funcs() -> OrderedSet[object]: + """Backward compat: returns the unified set (hash funcs are a subset).""" + return _safe_c_slots() + + +if TYPE_CHECKING: + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.side_effects import SideEffects + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + from torch._dynamo.variables.constant import ConstantVariable + + from .lists import ListVariable, TupleVariable + + +def is_standard_setattr(val: object) -> bool: + return val in (object.__setattr__, BaseException.__setattr__) + + +def is_standard_delattr(val: object) -> bool: + return val in (object.__delattr__, BaseException.__delattr__) + + +def is_forbidden_context_manager(ctx: object) -> bool: + f_ctxs: list[Any] = [] + + # pytest >= 8.4 moved RaisesContext into _pytest.raises and renamed it to RaisesExc, + # also adding RaisesGroup for ExceptionGroup matching. Keep both old and new names + # in independent try blocks so that one missing symbol doesn't drop the others. + try: + from _pytest.raises import RaisesExc, RaisesGroup # type: ignore[attr-defined] + + f_ctxs.append(RaisesExc) + f_ctxs.append(RaisesGroup) + except ImportError: + pass + + try: + from _pytest.python_api import RaisesContext # type: ignore[attr-defined] + + f_ctxs.append(RaisesContext) + except ImportError: + pass + + try: + from _pytest.recwarn import WarningsChecker # type: ignore[attr-defined] + + f_ctxs.append(WarningsChecker) + except ImportError: + pass + + if m := sys.modules.get("torch.testing._internal.jit_utils"): + f_ctxs.append(m._AssertRaisesRegexWithHighlightContext) + + return ctx in f_ctxs + + +def is_generic_ctx_manager_cls(cls: type) -> bool: + # A class is wrapped/entered as a GenericContextWrappingVariable only when + # its __enter__/__exit__ are plain Python-function methods: GCWV.enter/exit + # take `.__func__`, which only a regular bound method has. getattr_static + # (not getattr) inspects the raw descriptor, so staticmethod/classmethod + # descriptors and C-level slots (threading.Lock, file objects) are rejected + # -- those fall back to UserDefinedObjectVariable and cleanly graph-break on + # `with` instead of raising. Used at both wrap sites (VariableBuilder for + # sourced objects and SideEffects.get_variable_cls for in-trace ones) so a + # ctx manager wraps identically however it is encountered. + return ( + inspect.isfunction(inspect.getattr_static(cls, "__enter__", None)) + and inspect.isfunction(inspect.getattr_static(cls, "__exit__", None)) + and not is_forbidden_context_manager(cls) + ) + + +def is_cython_function(obj: object) -> bool: + return ( + callable(obj) + and hasattr(type(obj), "__name__") + and type(obj).__name__ == "cython_function_or_method" + ) + + +def is_pydantic_dataclass_cls(value: object) -> bool: + return ( + inspect.isclass(value) + and dataclasses.is_dataclass(value) + and "__is_pydantic_dataclass__" in getattr(value, "__dict__", {}) + ) + + +# Types whose instances are data descriptors (have __get__ + (__set__ or __delete__)). +# CPython invokes data descriptors found on the type MRO *before* checking +# the instance __dict__. This set is used by is_data_descriptor for a fast +# O(1) check before falling back to the generic hasattr probe. +KNOWN_DATA_DESCRIPTOR_TYPES: frozenset[type] = frozenset( + { + property, + _collections._tuplegetter, + types.MemberDescriptorType, + types.GetSetDescriptorType, + } +) + + +def is_data_descriptor(obj: object) -> bool: + """Return True if *obj* is a data descriptor (has __get__ and (__set__ or __delete__)).""" + tp = type(obj) + if tp in KNOWN_DATA_DESCRIPTOR_TYPES: + return True + return hasattr(tp, "__get__") and ( + hasattr(tp, "__set__") or hasattr(tp, "__delete__") + ) + + +def is_hashable(obj: object) -> bool: + try: + hash(obj) + return True + except TypeError: + return False + + +class UserDefinedVariable(VariableTracker): + value: object + + def _maybe_get_baseclass_method(self, name: str) -> Any: + """Get method from the base class if not overridden in value's __dict__.""" + if name not in getattr(self.value, "__dict__", {}): + try: + return inspect.getattr_static(type(self.value), name) + except AttributeError: + pass + return None + + +class UserDefinedClassVariable(UserDefinedVariable): + # pyrefly: ignore[bad-override] + value: type[object] + + def __init__(self, value: type[object], **kwargs: Any) -> None: + super().__init__(**kwargs) + self.value = value + # Used when we materialize class.__dict__ to a MappingProxyObject. In + # this case, we don't want to allow mutation in the class because there + # is no way to reflect it in the created MappingProxyVariable. + self.ban_mutation = False + + def get_value_for_setattr(self) -> object | None: + mod = getattr(self.value, "__module__", None) or "" + if mod == "torch" or mod.startswith(("torch.", "torch_")): + return None + return self.value + + def get_id_guard_type(self) -> Callable[..., Any] | None: + if self.source: + return GuardBuilder.CLASS_MATCH + return None + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + if self.source: + try: + install_guard(self.source.make_guard(GuardBuilder.CLASS_MATCH)) + return hash(self.value), False + except NotImplementedError: + pass + return hash(self.value), True + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + from .constant import ConstantVariable + + if not hasattr(other, "value"): + return ConstantVariable.create(NotImplemented) + if op in ("__eq__", "__ne__"): + try: + result = ( + (self.value == other.value) + if op == "__eq__" + else (self.value != other.value) + ) + return ConstantVariable.create(result) + except Exception: + return ConstantVariable.create(NotImplemented) + return ConstantVariable.create(NotImplemented) + + def as_python_constant(self) -> type[object]: + return self.value + + def as_proxy(self) -> object: + return self.value + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.value})" + + @staticmethod + @functools.cache + def _constant_fold_classes() -> set[type[object]]: + return { + torch.device, + torch.finfo, + torch.iinfo, + torch.Size, + } + + @staticmethod + @functools.cache + def _in_graph_classes() -> set[type[object]]: + _in_graph_class_list = { + torch.Tensor, + torch.cuda.FloatTensor, # type: ignore[attr-defined] + torch.cuda.DoubleTensor, # type: ignore[attr-defined] + torch.cuda.HalfTensor, # type: ignore[attr-defined] + torch.cuda.BFloat16Tensor, # type: ignore[attr-defined] + torch.cuda.ByteTensor, # type: ignore[attr-defined] + torch.cuda.CharTensor, # type: ignore[attr-defined] + torch.cuda.IntTensor, # type: ignore[attr-defined] + torch.cuda.ShortTensor, # type: ignore[attr-defined] + torch.cuda.LongTensor, # type: ignore[attr-defined] + torch.Stream, + torch.Event, + torch.cuda.Stream, + torch.cuda.Event, + torch.xpu.Stream, + torch.xpu.Event, + } + if hasattr(torch, "hpu"): + _in_graph_class_list.update( + { + torch.hpu.Stream, + torch.hpu.Event, + } + ) + + return set(tensortype_to_dtype.keys()) | _in_graph_class_list + + @staticmethod + @functools.cache + def supported_c_new_functions() -> set[Any]: + exceptions: set[Any] = { + getattr(builtins, name).__new__ + for name in dir(builtins) + if isinstance(getattr(builtins, name), type) + and issubclass(getattr(builtins, name), BaseException) + } + c_new_fns: set[Any] = { + object.__new__, + dict.__new__, + set.__new__, + frozenset.__new__, + tuple.__new__, + list.__new__, + int.__new__, + float.__new__, + str.__new__, + collections.deque.__new__, + } + return c_new_fns.union(exceptions) + + @staticmethod + def is_supported_new_method(value: object) -> bool: + if not is_hashable(value): + return False + if value in UserDefinedClassVariable.supported_c_new_functions(): + return True + # Structseq types each define their own C tp_new. + owner = getattr(value, "__self__", None) + return isinstance(owner, type) and is_structseq_class(owner) + + def can_constant_fold_through(self) -> bool: + if self.value in self._constant_fold_classes(): + return True + # Enum class calls (e.g., Color(1)) are value lookups that return + # existing singleton members, so they can always be constant-folded. + return isinstance(self.value, type) and issubclass(self.value, enum.Enum) + + def lookup_cls_mro_attr(self, name: str) -> object: + """Walk cls.__mro__ only (not the metaclass chain) to find *name*.""" + return mro_lookup(self.value, name) + + def get_source_by_walking_mro( + self, tx: "InstructionTranslatorBase", name: str + ) -> DictGetItemSource: + source = self.source + if source is None: + raise RuntimeError("get_source_by_walking_mro requires source") + + for idx, klass in enumerate(self.value.__mro__): + if name in klass.__dict__: + descriptor = klass.__dict__[name] + + for absent_idx in range(1, idx): + absent_klass = self.value.__mro__[absent_idx] + cache_key = (id(absent_klass), name) + if cache_key in tx.output.guarded_mro_absent_keys: + continue + tx.output.guarded_mro_absent_keys.add(cache_key) + mro_source = TypeMROSource(source) + klass_source: Source = GetItemSource(mro_source, absent_idx) + dict_source = TypeDictSource(klass_source) + install_guard( + dict_source.make_guard( + functools.partial(GuardBuilder.DICT_NOT_CONTAINS, key=name) + ) + ) + + cache_key = (id(descriptor), name) + cache = tx.output.mro_source_cache + if cache_key in cache: + return cache[cache_key] + + if idx != 0: + mro_source = TypeMROSource(source) + klass_source = GetItemSource(mro_source, idx) + else: + klass_source = source + dict_source = TypeDictSource(klass_source) + out_source = DictGetItemSource(dict_source, name) + cache[cache_key] = out_source + return out_source + + raise RuntimeError(f"Attribute {name} not found in MRO of {self.value}") + + def lookup_metaclass_attr(self, name: str) -> object: + """Walk type(cls).__mro__ (the metaclass chain) to find *name*.""" + return mro_lookup(type(self.value), name) + + def nb_bool_impl( + self, + tx: "InstructionTranslatorBase", + ) -> "VariableTracker": + from .constant import ConstantVariable + + # bool() on a class consults the metaclass __bool__. + # If the metaclass is the default `type`, all classes are truthy. + metaclass = type(self.value) + if hasattr(metaclass, "__bool__") and metaclass is not type: + return self.call_method(tx, "__bool__", [], {}) + return ConstantVariable.create(True) + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L2379-L2408 + metaclass = type(self.value) + if metaclass is type or metaclass.__repr__ is type.__repr__: + return VariableTracker.build(tx, repr(self.value)) + + type_attr = self.lookup_metaclass_attr("__repr__") + if type_attr is None: + raise_type_error(tx, "'NoneType' object is not callable") + return self.call_method(tx, "__repr__", [], {}) + + def tp_str_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + metaclass = type(self.value) + if metaclass is type or metaclass.__str__ is type.__str__: + return generic_repr(tx, self) + + type_attr = self.lookup_metaclass_attr("__str__") + if type_attr is None: + raise_type_error(tx, "'NoneType' object is not callable") + return self.call_method(tx, "__str__", [], {}) + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # CPython's type.__or__ implements _Py_union_type_or (type unions). + try: + other_val = other.as_python_constant() + except NotImplementedError: + return VariableTracker.build(tx, NotImplemented) + # pyrefly: ignore[bad-argument-count] + result = type(self.value).__or__(self.value, other_val) + if result is NotImplemented: + return VariableTracker.build(tx, NotImplemented) + return VariableTracker.build(tx, result) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + source = AttrSource(self.source, name) if self.source is not None else None + + # --- Dynamo-specific pre-checks --- + + # Custom metaclasses that override __getattribute__ replace the entire + # lookup algorithm; bail out for those. Standard metaclasses (ABCMeta, + # EnumType, etc.) that don't override __getattribute__ use + # type.__getattribute__ which is the algorithm we implement below. + metacls = type(self.value) + if metacls is not type and "__getattribute__" in metacls.__dict__: + unimplemented( + gb_type="Custom metaclass with __getattribute__", + context=f"type({self.value}) = {metacls}", + explanation="Dynamo does not trace attribute access on classes whose " + "metaclass overrides __getattribute__", + hints=graph_break_hints.SUPPORTABLE, + ) + + # ---- CPython type_getattro algorithm ---- + # https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L5417-L5505 + # 1. meta_attr = lookup name in type(cls).__mro__ (metaclass chain) + # 2. if meta_attr is a DATA descriptor → invoke + # 3. cls_attr = lookup name in cls.__mro__ (class chain) + # 4. if cls_attr has __get__ → invoke cls_attr.__get__(None, cls) + # 5. if cls_attr exists (plain) → return as-is + # 6. if meta_attr is a non-data descriptor or plain → return + # 7. raise AttributeError + + # Step 1-2: Metaclass data descriptors. + # For type(cls) is type, these are C-level getset/member descriptors + # for __dict__, __mro__, __name__, __qualname__, __doc__, etc. + meta_attr = self.lookup_metaclass_attr(name) + if meta_attr is not NO_SUCH_SUBOBJ and is_data_descriptor(meta_attr): + return self.resolve_meta_data_descriptor(tx, name, meta_attr, source) + + # Check for pending mutations from setattr on the class during tracing. + if tx.output.side_effects.has_pending_mutation_of_attr(self, name): + return tx.output.side_effects.load_attr(self, name) + + # Step 3-5: Class MRO lookup. + cls_attr = self.lookup_cls_mro_attr(name) + if cls_attr is not NO_SUCH_SUBOBJ: + if hasattr(type(cls_attr), "__get__"): + # Step 4: Descriptor — invoke __get__(None, cls). + return self.resolve_cls_descriptor(tx, name, cls_attr, source) + # Step 5: Plain attribute. + return self.resolve_cls_plain_attr(tx, name, cls_attr, source) + + # Step 6: Metaclass non-data descriptor or plain attr. + # For C-level descriptors with proper VTs, invoke tp_descr_get to + # produce a bound method. For everything else, defer to GetAttrVariable + # which routes call_function through call_method at runtime. + if meta_attr is not NO_SUCH_SUBOBJ: + metacls_source = TypeSource(self.source) if self.source else None + metacls_vt = VariableTracker.build(tx, type(self.value), metacls_source) + result = _resolve_descriptor_get(tx, meta_attr, self, metacls_vt, source) + if result is not None: + return result + return variables.GetAttrVariable(self, name, type(meta_attr), source=source) + + # __getattr__ on metaclass (not part of type_getattro proper — + # CPython handles this via slot_tp_getattr_hook). + metacls = type(self.value) + if metacls is not type: + meta_getattr = self.lookup_metaclass_attr("__getattr__") + if meta_getattr is not NO_SUCH_SUBOBJ and isinstance( + meta_getattr, types.FunctionType + ): + return variables.UserMethodVariable(meta_getattr, self).call_function( + tx, [variables.ConstantVariable.create(name)], {} + ) + + # Step 7: AttributeError. + raise_observed_exception( + AttributeError, + tx, + args=[f"type object '{self.value.__name__}' has no attribute '{name}'"], + ) + + def resolve_meta_data_descriptor( + self, + tx: "InstructionTranslatorBase", + name: str, + meta_attr: object, + source: Source | None, + ) -> VariableTracker: + """Handle data descriptors from the metaclass MRO (type.__dict__ slots).""" + if name == "__dict__": + return VariableTracker.build( + tx, + self.value.__dict__, + source=self.source and AttrSource(self.source, "__dict__"), + ) + if name == "__mro__": + if meta_attr is type.__dict__["__mro__"]: + attr_source = self.source and TypeMROSource(self.source) + else: + attr_source = source + return VariableTracker.build(tx, self.value.__mro__, attr_source) + if name == "__bases__": + bases = self.value.__bases__ + items = [ + VariableTracker.build(tx, b, source and GetItemSource(source, i)) + for i, b in enumerate(bases) + ] + return variables.TupleVariable(items, source=source) + if name == "__base__": + return VariableTracker.build(tx, self.value.__base__, source) + # __name__, __qualname__, __doc__, __module__, + # __abstractmethods__, etc. — all C-level getset descriptors on type. + resolved = type.__getattribute__(self.value, name) + if source: + return VariableTracker.build(tx, resolved, source) + from . import ConstantVariable + + if ConstantVariable.is_literal(resolved): + return VariableTracker.build(tx, resolved) + return variables.GetAttrVariable(self, name, type(resolved), source=source) + + def _descriptor_defining_class_vt( + self, + tx: "InstructionTranslatorBase", + descriptor: types.WrapperDescriptorType | types.MethodDescriptorType, + ) -> VariableTracker: + """VT for the class that actually implements an unbound C descriptor. + + Consider the following example: + + # Metaclass defines __neg__, so `-SomeClass` would call Meta.__neg__(cls). + class Meta(type): + def __neg__(cls): + return 999 + + + class Base(metaclass=Meta): + # Alias int's unary __neg__ slot wrapper into this class's dict under a + # different name. __objclass__ == int, __name__ == '__neg__', but looked + # up on Base, whose metaclass separately defines __neg__. + sneaky = int.__neg__ + + This helper function determines the correct owner of the descriptor based on the `__objclass__` attribute. + + class Foo(int): + ... + + assert Foo.__neg__ == int.__neg__ + assert Foo.__neg__.__objclass__ is int + """ + objclass = descriptor.__objclass__ + if objclass is self.value: + return self + return VariableTracker.build(tx, objclass) + + def resolve_cls_descriptor( + self, + tx: "InstructionTranslatorBase", + name: str, + cls_attr: object, + source: Source | None, + ) -> VariableTracker: + """Handle descriptors found in cls.__mro__.""" + if isinstance(cls_attr, staticmethod): + # Source points to the descriptor in the class __dict__ via MRO + # walk, not via AttrSource(cls, name) which would trigger the + # descriptor protocol and skip past the staticmethod wrapper. + descriptor_source = ( + self.get_source_by_walking_mro(tx, name) + if self.source is not None + else None + ) + sm_vt = variables.StaticMethodVariable(cls_attr, source=descriptor_source) + return sm_vt.tp_descr_get_impl(tx, self, self) + + if isinstance(cls_attr, classmethod): + if isinstance(cls_attr.__func__, property): + fget_vt = VariableTracker.build(tx, cls_attr.__func__.fget) + return fget_vt.call_function(tx, [self], {}) + # Source points to the descriptor in the class __dict__ via MRO + # walk, not via AttrSource(cls, name) which would trigger the + # descriptor protocol and skip past the classmethod wrapper. + descriptor_source = ( + self.get_source_by_walking_mro(tx, name) + if self.source is not None + else None + ) + cm_vt = variables.ClassMethodVariable(cls_attr, source=descriptor_source) + return cm_vt.tp_descr_get_impl(tx, self, self) + + if isinstance(cls_attr, types.ClassMethodDescriptorType): + cmd_vt = variables.ClassMethodDescriptorVariable(cls_attr, source=source) + return cmd_vt.tp_descr_get_impl(tx, self, self) + + # property_descr_get with obj=NULL returns self. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L1662-L1663 + if isinstance(cls_attr, property): + descriptor_source = ( + self.get_source_by_walking_mro(tx, name) + if self.source is not None + else None + ) + return variables.PropertyVariable(cls_attr, source=descriptor_source) + + # member_get with obj=NULL returns self. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L162-L164 + if isinstance(cls_attr, types.MemberDescriptorType): + descriptor_source = ( + self.get_source_by_walking_mro(tx, name) + if self.source is not None + else None + ) + return variables.MemberDescriptorVariable( + cls_attr, source=descriptor_source + ) + + if isinstance(cls_attr, _collections._tuplegetter): + descriptor_source = ( + self.get_source_by_walking_mro(tx, name) + if self.source is not None + else None + ) + tg_vt = variables.TupleGetterVariable(cls_attr, source=descriptor_source) + return tg_vt.tp_descr_get_impl(tx, None, self) + + # TODO(tp_descr_get) - Comparison dunders must be checked before + # WrapperDescriptor/MethodDescriptor to avoid VT type mismatches in + # identity checks. Revisit once we implement tp_richcompare slot. + if name in cmp_name_to_op_mapping and not isinstance( + cls_attr, types.FunctionType + ): + return variables.GetAttrVariable( + self, name, py_type=type(cls_attr), source=source + ) + + # wrapperdescr_get/method_get with obj=NULL returns the + # descriptor itself. + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L206-L207 + if ( + isinstance(cls_attr, types.WrapperDescriptorType) + and not is_torch_class(self.value) + and name not in ("__get__", "__set__", "__delete__") + ): + return variables.WrapperDescriptorVariable( + cls_attr, + owner=self._descriptor_defining_class_vt(tx, cls_attr), + source=source, + ) + + # https://github.com/python/cpython/blob/3.13/Objects/descrobject.c#L140-L141 + if ( + isinstance(cls_attr, types.MethodDescriptorType) + and not is_torch_class(self.value) + and name not in ("__get__", "__set__", "__delete__") + ): + return variables.MethodDescriptorVariable( + cls_attr, + owner=self._descriptor_defining_class_vt(tx, cls_attr), + source=source, + ) + + # User-defined descriptor with Python __get__. + # For torch-internal classes or attributes in the class's own __dict__, + # defer descriptor invocation to runtime via VariableTracker.build to + # avoid compile-time side effects (e.g. deprecation warnings from + # _ClassPropertyDescriptor on torch.FloatStorage.dtype). + get_fn = inspect.getattr_static(type(cls_attr), "__get__", None) + if isinstance(get_fn, types.FunctionType): + if source and ( + name in getattr(self.value, "__dict__", {}) + or self.value.__module__.startswith("torch.") + or self.value.__module__ == "torch" + ): + return VariableTracker.build(tx, cls_attr, source) + return self.invoke_cls_descriptor_get(tx, name, cls_attr, source) + + # TODO(tp_descr_get) - C-level descriptors not matched above (e.g. + # instancemethod, or wrapper/method descriptors on torch classes that + # need trace_rules). OrderedDict's C-level methods are handled at + # runtime. + if inspect.ismethoddescriptor(cls_attr): + if ( + source + and self.value is not collections.OrderedDict + and ( + name in getattr(self.value, "__dict__", {}) + or self.value.__module__.startswith("torch.") + or self.value.__module__ == "torch" + ) + ): + return VariableTracker.build(tx, cls_attr, source) + return variables.GetAttrVariable(self, name, type(cls_attr), source=source) + + # Everything else: FunctionType, etc. + return VariableTracker.build(tx, cls_attr, source) + + def resolve_cls_plain_attr( + self, + tx: "InstructionTranslatorBase", + name: str, + cls_attr: object, + source: Source | None, + ) -> VariableTracker: + """Handle non-descriptor attributes from cls.__mro__.""" + if name == "__new__" and UserDefinedClassVariable.is_supported_new_method( + cls_attr + ): + return variables.GetAttrVariable(self, name, source=source) + if self.value is collections.OrderedDict: + return variables.GetAttrVariable(self, name, py_type=type(cls_attr)) + return VariableTracker.build(tx, cls_attr, source) + + def invoke_cls_descriptor_get( + self, + tx: "InstructionTranslatorBase", + name: str, + descriptor: object, + source: Source | None, + ) -> VariableTracker: + """Trace a class-MRO descriptor's __get__(None, cls) call.""" + from .constant import ConstantVariable + + descriptor_source = None + descriptor_get_source = None + if self.source: + descriptor_source = AttrSource(self.source, name) + descriptor_get_source = AttrSource(TypeSource(descriptor_source), "__get__") + descriptor_var = VariableTracker.build(tx, descriptor, descriptor_source) + else: + descriptor_var = UserDefinedObjectVariable(descriptor) + + none_var = ConstantVariable.create(None) + return variables.UserMethodVariable( + descriptor.__get__.__func__, # type: ignore[union-attr] + descriptor_var, + source=descriptor_get_source, + ).call_function(tx, [none_var, self], {}) + + def len_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + m = self._maybe_get_baseclass_method("__len__") + if m: + source = self.source and AttrSource(self.source, "__len__") + return variables.UserMethodVariable( + m, self, source_fn=source + ).call_function(tx, [], {}) + raise_type_error(tx, f"object of type {self.python_type_name()} has no length") + + def sq_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.len_impl(tx) + + def mp_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + return self.len_impl(tx) + + def sq_contains_impl( + self, tx: "InstructionTranslatorBase", item: VariableTracker + ) -> VariableTracker: + m = self._maybe_get_baseclass_method("__contains__") + if m: + return self.call_method(tx, "__contains__", [item], {}) + return super().sq_contains_impl(tx, item) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + m = self._maybe_get_baseclass_method("__iter__") + if m: + source = self.source and AttrSource(self.source, "__iter__") + return variables.UserMethodVariable( + m, self, source_fn=source + ).call_function(tx, [], {}) + return super().tp_iter_impl(tx) + + def nb_negative_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + m = self._maybe_get_baseclass_method("__neg__") + if m: + source = self.source and AttrSource(self.source, "__neg__") + return variables.UserMethodVariable( + m, self, source_fn=source + ).call_function(tx, [], {}) + raise_type_error( + tx, f"bad operand type for unary -: '{self.python_type_name()}'" + ) + + def nb_positive_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + m = self._maybe_get_baseclass_method("__pos__") + if m: + source = self.source and AttrSource(self.source, "__pos__") + return variables.UserMethodVariable( + m, self, source_fn=source + ).call_function(tx, [], {}) + raise_type_error( + tx, f"bad operand type for unary +: '{self.python_type_name()}'" + ) + + def nb_absolute_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + m = self._maybe_get_baseclass_method("__abs__") + if m: + source = self.source and AttrSource(self.source, "__abs__") + return variables.UserMethodVariable( + m, self, source_fn=source + ).call_function(tx, [], {}) + raise_type_error( + tx, + f"bad operand type for abs(): '{self.python_type_name()}'", + ) + + def nb_invert_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + m = self._maybe_get_baseclass_method("__invert__") + if m: + source = self.source and AttrSource(self.source, "__invert__") + return variables.UserMethodVariable( + m, self, source_fn=source + ).call_function(tx, [], {}) + raise_type_error( + tx, + f"bad operand type for unary ~: '{self.python_type_name()}'", + ) + + def mp_ass_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + # Class-level __setitem__ / __delitem__: looked up on the metaclass. + # `cls[k] = v` invokes type(cls).__setitem__(cls, k, v); `del cls[k]` + # invokes __delitem__. value=None signals delete (CPython NULL). + is_delete = value is None + attr = "__delitem__" if is_delete else "__setitem__" + m = self._maybe_get_baseclass_method(attr) + if isinstance(m, types.FunctionType): + source = self.source and AttrSource(self.source, attr) + args = [key] if is_delete else [key, value] + variables.UserMethodVariable(m, self, source_fn=source).call_function( + tx, args, {} + ) + return variables.ConstantVariable.create(None) + return super().mp_ass_subscript_impl(tx, key, value) + + sq_ass_item_impl = mp_ass_subscript_impl + + def _call_cross_entropy_loss( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + """ + functional: input, target, weight=None, size_average=None, ignore_index=- 100, reduce=None, reduction='mean', + label_smoothing=0.0 + + non functional ctor: weight=None, size_average=None, ignore_index=- 100, reduce=None, reduction='mean', + label_smoothing=0.0 + + non functional loss call: input, target, optional_output + """ + from . import ConstantVariable + + def normalize_args( + weight: VariableTracker = ConstantVariable.create(None), + size_average: VariableTracker = ConstantVariable.create(None), + ignore_index: VariableTracker = ConstantVariable.create(-100), + reduce: VariableTracker = ConstantVariable.create(None), + reduction: VariableTracker = ConstantVariable.create("mean"), + label_smoothing: VariableTracker = ConstantVariable.create(0.0), + ) -> tuple[VariableTracker, ...]: + return ( + weight, + size_average, + ignore_index, + reduce, + reduction, + label_smoothing, + ) + + ( + weight, + size_average, + ignore_index, + reduce_arg, + reduction, + label_smoothing, + ) = normalize_args(*args, **kwargs) + + def fake_cross_entropy_loss( + input: VariableTracker, target: VariableTracker + ) -> VariableTracker: + from .builder import wrap_fx_proxy + + return wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + torch.nn.functional.cross_entropy, + *proxy_args_kwargs( + [ + input, + target, + weight, + size_average, + ignore_index, + reduce_arg, + reduction, + label_smoothing, + ], + {}, + ), + ), + ) + + return variables.LambdaVariable(fake_cross_entropy_loss) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import SourcelessBuilder + + if ( + name == "__subclasses__" + and len(args) == 0 + and not kwargs + and "__subclasses__" not in self.value.__dict__ + ): + source = self.source + if self.source: + source = AttrSource(self.source, "__subclasses__") + source = CallFunctionNoArgsSource(source) + return VariableTracker.build(tx, self.value.__subclasses__(), source) + elif ( + self.value in {collections.OrderedDict, collections.defaultdict} + and name == "fromkeys" + ): + return variables.DictBuiltinVariable.call_custom_dict_fromkeys( + tx, self.value, *args, **kwargs + ) + elif self.value is collections.OrderedDict and name == "move_to_end": + return args[0].call_method(tx, name, [*args[1:]], kwargs) + elif ( + self.value in {collections.defaultdict, collections.deque} + and name == "__copy__" + and len(args) == 1 + and not kwargs + ): + # copy.copy(x) resolves type(x).__copy__ and calls it with the + # instance as the sole argument; dispatch to the instance so the + # contents (and defaultdict default_factory / deque maxlen) are + # preserved. + return args[0].call_method(tx, name, [], kwargs) + elif name == "__len__" and len(args) == 1 and not kwargs: + from .object_protocol import generic_size + + return generic_size(tx, args[0]) + elif issubclass(self.value, dict) and name != "__new__": + # __new__ is handled below + return SourcelessBuilder.create(tx, dict).call_method( + tx, name, args, kwargs + ) + elif issubclass(self.value, (set, frozenset)) and name != "__new__": + # __new__ is handled below + return SourcelessBuilder.create(tx, set).call_method(tx, name, args, kwargs) + elif ( + len(args) == 1 + and isinstance(args[0], variables.GenericContextWrappingVariable) + and name == "__enter__" + ): + return args[0].enter(tx) + elif name == "__new__" and UserDefinedClassVariable.is_supported_new_method( + self.value.__new__ + ): + if self.value is collections.OrderedDict: + # Exact OrderedDict: represent as a bare OrderedDictVariable, + # mirroring dict.__new__(dict) -> ConstDictVariable. + return OrderedDictVariable({}, mutation_type=ValueMutationNew()) + # Some C-level tp_new functions (dict.__new__, set.__new__) ignore + # extra args — only the type arg matters. Pass init_args=[] for + # those so reconstruction emits base_cls.__new__(cls) without + # unreconstructable args (e.g. generators). Other tp_new functions + # (tuple.__new__, BaseException.__new__) use the extra args. + new_fn = self.value.__new__ + if new_fn in (dict.__new__, set.__new__, collections.deque.__new__): + init_args: list[VariableTracker] = [] + else: + init_args = list(args[1:]) + return tx.output.side_effects.track_new_user_defined_object( + self, + args[0], + init_args, + tx=tx, + ) + elif name == "__setattr__" and self.ban_mutation: + unimplemented( + gb_type="Class attribute mutation when the __dict__ was already materialized", + context=str(self.value), + explanation="Dynamo does not support tracing mutations on a class when its __dict__ is materialized", + hints=graph_break_hints.SUPPORTABLE, + ) + + # Dispatch dunder methods defined on the metaclass (e.g., EnumType.__contains__). + # In Python, `x in Color` calls `type(Color).__contains__(Color, x)`. + metaclass = type(self.value) + if metaclass is not type: + # Look up the method on the metaclass MRO, not the class MRO + for klass in metaclass.__mro__: + if name in klass.__dict__: + method = klass.__dict__[name] + if isinstance(method, types.FunctionType): + source = self.source and AttrSource(self.source, name) + return variables.UserMethodVariable( + method, self, source=source + ).call_function(tx, args, kwargs) + break + + return super().call_method(tx, name, args, kwargs) + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase" + ) -> list["VariableTracker"]: + if isinstance(self.value, type) and issubclass(self.value, enum.Enum): + return [VariableTracker.build(tx, item) for item in self.value] + raise NotImplementedError + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from ..side_effects import SideEffects + from .builder import SourcelessBuilder, wrap_fx_proxy + from .ctx_manager import ( + GenericContextWrappingVariable, + get_device_context_manager, + ) + + constant_args = check_constant_args(args, kwargs) + + if torch.distributed.is_available() and self.value is torch.distributed.P2POp: + if not config.enable_p2p_compilation: + unimplemented( + gb_type="P2P compilation disabled for P2POp construction", + context="torch.distributed.P2POp", + explanation="P2P compilation is disabled.", + hints=[ + "Set TORCHDYNAMO_ENABLE_P2P_COMPILATION=1 to enable.", + ], + ) + var = tx.output.side_effects.track_new_user_defined_object( + SourcelessBuilder.create(tx, object), + self, + [], + tx=tx, + ) + var.call_method(tx, "__init__", list(args), kwargs) # type: ignore[arg-type] + return var + + if self.can_constant_fold_through() and constant_args: + # constant fold + return VariableTracker.build( + tx, + self.as_python_constant()( # type: ignore[operator] + *[x.as_python_constant() for x in args], + **{k: v.as_python_constant() for k, v in kwargs.items()}, + ), + ) + elif self.value is torch.nn.CrossEntropyLoss: + return self._call_cross_entropy_loss(tx, args, kwargs) + elif self.value is contextlib.nullcontext: + # import here to avoid circular dependency + from .ctx_manager import NullContextVariable + + return NullContextVariable(*args, **kwargs) + elif self.value is collections.defaultdict: + # defaultdict construction — use track_new_user_defined_object + # which creates DefaultDictVariable. __init__ handler extracts + # default_factory and populates items. + from .builder import SourcelessBuilder + + result = tx.output.side_effects.track_new_user_defined_object( + SourcelessBuilder.create(tx, dict), + self, + [], + tx=tx, + ) + result.call_method(tx, "__init__", list(args), kwargs) + return result + elif is_typeddict(self.value): + if self.value.__optional_keys__: # type: ignore[attr-defined] + unimplemented( + gb_type="TypedDict with optional keys", + context=str(self.value), + explanation="Dynamo does not support tracing TypedDict with optional keys", + hints=[ + "Avoid using TypedDict with optional keys", + *graph_break_hints.SUPPORTABLE, + ], + ) + return variables.DictBuiltinVariable.call_custom_dict( + tx, dict, *args, **kwargs + ) + elif self.value is collections.deque: + maxlen = variables.ConstantVariable.create(None) + + def deque_signature( + iterable: Iterable[Any] | None = None, maxlen: int | None = None + ) -> Any: + pass + + bound_args = None + try: + bound_args = inspect.signature(deque_signature).bind(*args, **kwargs) + except TypeError as e: + unimplemented( + gb_type="collections.deque() with bad arguments", + context=f"args={args}, kwargs={kwargs}", + explanation="Detected call to collections.deque() with bad arguments.", + hints=[ + "Fix the call to collections.deque().", + *graph_break_hints.USER_ERROR, + ], + from_exc=e, + ) + if bound_args is None: + raise AssertionError("bound_args is None after signature binding") + if "iterable" in bound_args.arguments: + items = unpack_iterable(tx, bound_args.arguments["iterable"]) + else: + # pyrefly: ignore [implicit-any] + items = [] + + if "maxlen" in bound_args.arguments: + maxlen = bound_args.arguments["maxlen"] + + variables.lists.DequeVariable.validate_maxlen(tx, maxlen) + return variables.lists.DequeVariable( + items, maxlen=maxlen, mutation_type=ValueMutationNew() + ) + elif self.value in ( + deque_iterator, + deque_rev_iterator, + ): + # _deque_iterator(deque[, index]) / _deque_reverse_iterator(deque[, index]) + # ref: dequeiter_new in Modules/_collectionsmodule.c + name = self.value.__name__ + + def deque_iterator_sig(deque: Any, index: Any = 0, /) -> tuple[Any, Any]: + return deque, index + + try: + deque_arg, index = deque_iterator_sig(*args, **kwargs) + except TypeError: + raise_args_mismatch(tx, name) + if not isinstance(deque_arg, variables.lists.DequeVariable): + raise_type_error( + tx, + f"{name}() argument 1 must be collections.deque, " + f"not {deque_arg.python_type_name()}", + ) + if not isinstance(index, int): + index = index.as_python_constant() + if self.value is deque_rev_iterator: + cls = variables.lists.DequeReverseIteratorVariable + snapshot = list(reversed(deque_arg.items)) + else: + cls = variables.lists.DequeIteratorVariable + snapshot = list(deque_arg.items) + return cls( + snapshot, + deque_arg, + deque_arg.state, + index=index, + mutation_type=ValueMutationNew(), + ) + elif ( + # https://github.com/python/cpython/blob/33efd7178e269cbd04233856261fd0aabbf35447/Lib/contextlib.py#L475-L477 + self.value is types.MethodType + and len(args) == 2 + and isinstance(args[0], variables.UserFunctionVariable) + and isinstance(args[1], GenericContextWrappingVariable) + and args[0].get_name() in ("__enter__", "__exit__") + ): + cm_obj = args[1].cm_obj + fn = getattr(cm_obj, args[0].get_name()).__func__ + return variables.UserMethodVariable(fn, args[1], source=self.source) + elif self.value is weakref.ref: + if len(args) > 1: + callback = args[1] + else: + callback = variables.ConstantVariable.create(None) + return variables.WeakRefVariable(args[0], callback) + elif self.value is functools.partial: + if not args: + unimplemented( + gb_type="missing args to functools.partial", + context="", + explanation="functools.partial requires at least one argument", + hints=[ + "Fix the functools.partial call.", + *graph_break_hints.USER_ERROR, + ], + ) + # The first arg, a callable (the ctor below will assert on types) + fn = args[0] + rest_args = args[1:] + # guards for the produced FunctoolsPartialVariable are installed in FunctoolsPartialVariable ctor from the + # args and keywords + return variables.functions.FunctoolsPartialVariable( + fn, args=rest_args, keywords=kwargs + ) + elif self.value is warnings.catch_warnings and not args: + return variables.CatchWarningsCtxManagerVariable.create(tx, kwargs) + elif ( + not kwargs + and len(args) == 1 + and (variable_cls := get_device_context_manager(self.value)) is not None + ): + if not args[0].is_python_constant(): + raise_type_error( + tx, + f"{self.value.__module__}.{self.value.__qualname__} requires a constant argument", + ) + return variable_cls.create(tx, args[0].as_python_constant()) + elif ( + issubclass(type(self.value), type) + and hasattr( + self.value, "__enter__" + ) # TODO(voz): These can invoke user code! + and hasattr( + self.value, "__exit__" + ) # TODO(voz): These can invoke user code! + and self.is_standard_new() + and SideEffects.cls_supports_mutation_side_effects(self.value) + and self.source + and not is_forbidden_context_manager(self.value) + ): + from . import TorchCtxManagerClassVariable + from .functions import ( + BaseUserFunctionVariable, + FunctionDecoratedByContextlibContextManagerVariable, + ) + + # graph break on any contextlib.* that it is not contextlib.contextmanager + # Some of the APIs below are not supported because they rely on features + # that Dynamo doesn't play well today (i.e. contextlib.suppress) + if self.value in ( + contextlib._AsyncGeneratorContextManager, + contextlib.closing, + contextlib.redirect_stdout, + contextlib.redirect_stderr, + contextlib.AsyncExitStack, + ): + # We are not changing the behavior of Dynamo as these function were + # already ignored on trace_rules.py before #136033 landed + unimplemented( + gb_type="unsupported contextlib.* API", + context=f"{self.value}", + explanation=f"{self.value} not supported. This may be due to its use of " + "context-specific operations that are not supported in " + "Dynamo yet (i.e. Exception handling)", + hints=[ + *graph_break_hints.SUPPORTABLE, + ], + ) + arg_new = args + if self.value is contextlib._GeneratorContextManager and isinstance( + args[0], (BaseUserFunctionVariable, TorchCtxManagerClassVariable) + ): + if not torch._dynamo.config.enable_trace_contextlib: + unimplemented( + gb_type="attempted to trace contextlib.contextmanager", + context=f"args={args}", + explanation="Tracing contextlib.contextmanager is disabled.", + hints=[ + "Set torch._dynamo.config.enable_trace_contextlib = True", + ], + ) + + # Special treatments for certain context managers created via + # contextlib, because + # 1. we (pytorch) own their impls + # 2. it's tedious to trace through them, so we effectively + # "allow in graph" them without sacrificing soundness. + # + # We would typically reach here via either + # 1. the instance construction in `with ctx_manager(...):`: + # https://github.com/python/cpython/blob/3.12/Lib/contextlib.py#L301 + # 2. calling a function decorated with a context manager: + # https://github.com/python/cpython/blob/3.12/Lib/contextlib.py#L122 + # + # So we basically trace through the surface part of the + # contextlib code, and then special case the shared remaining + # logic (the actual context manager instance construction and + # usage later on). + if isinstance(args[0], TorchCtxManagerClassVariable): + fn_var = args[0] + args_list = args[1].items # type: ignore[union-attr,attr-defined] + kwargs_dict = args[2].keys_as_python_constant() # type: ignore[union-attr,attr-defined] + return fn_var.call_function(tx, args_list, kwargs_dict) + + # Wrap UserFunctionVariable in FunctionDecoratedByContextlibContextManagerVariable + # if the function is annotated with @contextlib.contextmanager + # This shouldn't be necessary once generator functions are fully + # supported in dynamo + # pyrefly: ignore[unsupported-operation] + arg_new = [ + FunctionDecoratedByContextlibContextManagerVariable( + args[0], source=args[0].source + ) + ] + args[1:] + + return tx.inline_user_function_return( + VariableTracker.build( + tx, polyfills.instantiate_user_defined_class_object + ), + [self, *arg_new], + kwargs, + ) + elif is_namedtuple_cls(self.value): + if is_structseq_class(self.value): + if kwargs or len(args) != 1: + raise_args_mismatch( + tx, + "torch.return_types", + "1 args and 0 kwargs", + f"{len(args)} args and {len(kwargs)} kwargs", + ) + # Structseq tp_new is a C function, so we can't trace into + # it like namedtuples. Use track_new_user_defined_object + # directly with self as both base_cls_vt and cls_vt. + return tx.output.side_effects.track_new_user_defined_object( + self, + self, + list(args), + tx=tx, + ) + else: + # Namedtuple __new__ is a Python function that calls + # tuple.__new__(cls, (field_values,)). Let Dynamo trace + # into it so default values and kwargs are handled by + # the generated __new__ itself. + return tx.inline_user_function_return( + VariableTracker.build( + tx, polyfills.instantiate_user_defined_class_object + ), + [self, *args], + kwargs, + ) + elif self.value is torch.Size: + # This simulates `THPSize_pynew`, the C impl for `Size.__new__`. + from .lists import SizeVariable + + tup = SourcelessBuilder.create(tx, tuple).call_function(tx, args, kwargs) + return SizeVariable(tup.items) # type: ignore[missing-attribute] + elif is_pydantic_dataclass_cls(self.value): + # Pydantic populates dataclass fields through an external validator, + # so tracing through the constructor misses the instance mutations. + unimplemented( + gb_type="Pydantic dataclass constructor", + context=f"{self.value}", + explanation="Dynamo graph breaks on pydantic dataclass constructors " + "because validation mutates the instance outside traced bytecode.", + hints=graph_break_hints.SUPPORTABLE, + ) + elif ( + self.value in self._in_graph_classes() + or is_traceable_wrapper_subclass_type(self.value) + ): + # torch.LongTensor cannot accept a list of FakeTensors. + # So we stack the list of FakeTensors instead. + from .lists import ListVariable + + if ( + np + and self.value in tensortype_to_dtype + and len(args) == 1 + and isinstance(args[0], ListVariable) + and len(args[0].items) > 1 + and all(x.is_tensor() for x in args[0].items) + ): + # Stack FakeTensor + stacked = wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + torch.stack, + *proxy_args_kwargs(args, kwargs), + ), + ) + args = [stacked] + + if issubclass(self.value, torch.Stream): + from .lists import TupleVariable + + var_kwargs = ConstDictVariable( + {VariableTracker.build(tx, k): v for k, v in kwargs.items()} + ) + var_args = TupleVariable(list(args)) + stream = self.value( + *(var_args.as_python_constant()), + **(var_kwargs.as_python_constant()), + ) + from ..graph_bytecode_inputs import register_graph_created_object + from .streams import StreamVariable + + ind = register_graph_created_object( + stream, + StreamVariable.make_construct_in_graph_stream_fn( + var_args, var_kwargs + ), + ) + tensor_variable = wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", get_external_object_by_index, (ind,), {} + ), + ) + elif issubclass(self.value, torch.Event): + from .lists import TupleVariable + + # Register newly created event for reconstruction + var_kwargs = ConstDictVariable( + {VariableTracker.build(tx, k): v for k, v in kwargs.items()} + ) + var_args = TupleVariable(list(args)) + event = self.value( + *(var_args.as_python_constant()), + **(var_kwargs.as_python_constant()), + ) + from ..graph_bytecode_inputs import register_graph_created_object + from .streams import EventVariable + + ind = register_graph_created_object( + event, + EventVariable.make_construct_in_graph_event_fn( + var_args, var_kwargs + ), + ) + tensor_variable = wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", get_external_object_by_index, (ind,), {} + ), + ) + else: + tensor_variable = wrap_fx_proxy( + tx=tx, + proxy=tx.output.create_proxy( + "call_function", + self.value, + *proxy_args_kwargs(args, kwargs), + ), + ) + + return tensor_variable + elif self.value is random.Random: + if len(args) == 1 and args[0].is_python_constant(): + seed = args[0].as_python_constant() + else: + seed = None + random_object = random.Random(seed) + return RandomVariable(random_object) + elif self.value is types.MappingProxyType and len(args) == 1: + # types.MappingProxyType is a read-only proxy of the dict. If the + # original dict changes, the changes are reflected in proxy as well. + dict_arg = args[0] + if isinstance(dict_arg, variables.UserDefinedDictVariable): + dict_arg = dict_arg._base_vt + if isinstance(dict_arg, ConstDictVariable): + return variables.MappingProxyVariable(dict_arg) + elif SideEffects.cls_supports_mutation_side_effects(self.value) and ( + self.source or torch._dynamo.config.enable_trace_load_build_class + ): + if self.value.__new__ is object.__new__: + # Graph-break before inlining the class-instantiation polyfill + # for extension types where object.__new__ cannot allocate an + # example object. SideEffects keeps a matching backstop for + # direct construction paths. This allocates one temporary + # instance for classes that pass the check. + try: + object.__new__(self.value) + except TypeError as exc: + unimplemented( + gb_type="Unsupported object.__new__ user-defined class construction", + context=f"class={self.value}, error={exc}", + explanation=( + "Dynamo could not construct an example object for " + "side-effect replay using object.__new__." + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + with do_not_convert_to_tracable_parameter(): + result = tx.inline_user_function_return( + VariableTracker.build( + tx, polyfills.instantiate_user_defined_class_object + ), + [self, *args], + kwargs, + ) + return result + + return super().call_function(tx, args, kwargs) + + def is_standard_new(self) -> bool: + """Check for __new__ being overridden""" + new_fn = inspect.getattr_static(self.value, "__new__", None) + if isinstance(new_fn, staticmethod): + new_fn = new_fn.__func__ + return new_fn is object.__new__ + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> "ConstantVariable": + se_result = self._hasattr_check_side_effects(tx, name) + if se_result is not None: + return se_result + if self.source: + install_guard( + self.source.make_guard( + functools.partial(GuardBuilder.HASATTR, attr=name) + ) + ) + return VariableTracker.build(tx, hasattr(self.value, name)) + + def const_getattr(self, tx: "InstructionTranslatorBase", name: str) -> Any: + if name == "__name__": + return self.value.__name__ + return super().const_getattr(tx, name) + + def reconstruct_pycode(self, codegen) -> str: + if self.source: + return self.source.reconstruct_pycode(codegen) + raise NotImplementedError( + "Python codegen not implemented yet for sourceless UserDefinedClassVariable." + ) + + def get_real_python_backed_value(self) -> object: + return self.value + + +class UserDefinedExceptionClassVariable(UserDefinedClassVariable): + @property + def fn(self) -> type[object]: + return self.value + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .builder import SourcelessBuilder + + if self.source is None: + # NB: If source is added via side effects, create the exception + # object through side_effects as well. See FrozenDataClass creation + var = tx.output.side_effects.track_new_user_defined_object( + SourcelessBuilder.create(tx, BaseException), + self, + list(args), + tx=tx, + ) + var.call_method(tx, "__init__", list(args), dict(kwargs)) + return var + return super().call_function(tx, args, kwargs) + + +class RemovableHandleClass: + # Dummy class to pass to python_type of + # RemovableHandleVariable + # Useful for isinstance check on hooks + pass + + +def call_random_fn( + tx: "InstructionTranslatorBase", + fn: Callable[..., Any], + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], +) -> VariableTracker: + from .builder import VariableBuilder + + args = [x.as_python_constant() for x in args] + kwargs = {k: v.as_python_constant() for k, v in kwargs.items()} + random_call_index = len(tx.output.random_calls) + # NB: it is probably not important for the example_value to be exactly correct, + # we just need the right type + example_value = fn(*args, **kwargs) + source = RandomValueSource(random_call_index) + tx.output.random_calls.append((fn, args, kwargs)) # type: ignore[arg-type] + # TODO: arguably, this should route to wrap_symint/wrap_symfloat + # (currently hypothetical), but I'm not going to poke my hand in + # this nest for now + return VariableBuilder(tx, source).wrap_unspecialized_primitive(example_value) + + +class UserDefinedObjectVariable(UserDefinedVariable): + """ + Mostly objects of defined type. Catch-all for something where we only know the type. + """ + + # VT representing the base built-in type's data for subclassed built-in types + # (e.g., ConstDictVariable for dict subclasses, ListVariable for list subclasses). + # None for plain user-defined objects that don't subclass a built-in container. + _base_vt: VariableTracker | None = None + + # Set of base class methods that can be delegated to _base_vt. + # Used to check whether a method is overridden before delegating. + _base_methods: set[Any] | None = None + + _nonvar_fields = { + "value", + "value_type", + *UserDefinedVariable._nonvar_fields, + } + + def __init__( + self, + value: object, + *, + value_type: type | None = None, + cls_source: TypeSource | None = None, + base_cls_vt: VariableTracker | None = None, + init_args: list[VariableTracker] | None = None, + **kwargs: Any, + ) -> None: + kwargs.pop("tx", None) + super().__init__(**kwargs) + self.value = value + self.value_type = value_type or type(value) + if type(value) is not self.value_type: + raise AssertionError(f"Expected type {self.value_type}, got {type(value)}") + # This is used with __new__, when the new object is sourceless but the user class can be sourceful. + self.cls_source = cls_source + if cls_source is None and self.source is not None: + self.cls_source = TypeSource(self.source) + + # These attributes are used to reconstruct the user defined object. The + # pseudo code looks like this. Builtin C __new__ do not support kwargs, + # so init_args is sufficient. + # obj = base_cls.__new__(user_cls, *args) + self.base_cls_vt = base_cls_vt + self.init_args = init_args + + # Cache inspect.getattr_static outputs for the same name. This is fine + # because if there is a mutation for the name, we use side-effects infra + # to early return the mutated value. + self._looked_up_attrs: dict[str, object] = {} + + # This is to avoid getattr_static calls to look up the subobj from the self.value.__class__ + self._subobj_from_class: dict[str, object] = {} + + import torch.utils._pytree as pytree + + self.is_pytree_constant_class = pytree.is_constant_class(self.value_type) + if pytree.is_constant_class(self.value_type) and self.source: + install_guard(self.source.make_guard(GuardBuilder.EQUALS_MATCH)) + + self._object_has_getattribute = object_has_getattribute(self.value) + + def __str__(self) -> str: + inner = self.value_type.__name__ + if inner in [ + "builtin_function_or_method", + "getset_descriptor", + "method_descriptor", + "method", + ]: + inner = str(getattr(self.value, "__name__", None)) + return f"{self.__class__.__name__}({inner})" + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.value_type.__name__})" + + def is_base_vt_modified(self, side_effects: "SideEffects") -> bool: + if self._base_vt is not None: + return side_effects.is_modified(self._base_vt) + return False + + def reconstruct_pycode(self, codegen): + if self.source: + return self.source.reconstruct_pycode(codegen) + raise NotImplementedError( + "Python codegen not implemented yet for sourceless UserDefinedObjectVariable" + ) + + def python_type(self) -> type: + return self.value_type # type: ignore[return-value] + + def get_real_python_backed_value(self) -> object: + return self.value + + def as_python_constant(self) -> object: + from ..utils import is_pybind11_enum_member + + if isinstance( + self.value, + (enum.Enum, torch.DispatchKey, torch._C._functorch.TransformType), + ) or is_pybind11_enum_member(self.value): + return self.value + + from torch.utils._triton import has_triton_package + + if has_triton_package(): + import triton.language as tl + + if isinstance(self.value, tl.constexpr): + return self.value.value + + if self.is_pytree_constant_class and self.source: + # NOTE pytree constants created in the torch.compile region will + # NOT be guarded (even though they have a source set) + return self.value + # TODO else try reconstructing the object by, e.g., leveraging side + # effects and `as_python_constant`. + + # Special case for _MaskModWrapper during legacy export: Dynamo creates + # objects via __new__ without calling __init__, so self.value.fn is unset. + # Reconstruct from the tracked side-effect attribute instead. + from torch.nn.attention.flex_attention import _MaskModWrapper + + if isinstance(self.value, _MaskModWrapper): + from torch._dynamo.symbolic_convert import InstructionTranslator + + tx = InstructionTranslator.current_tx() + if tx is not None and tx.export: + fn_vt = tx.output.side_effects.load_attr(self, "fn", deleted_ok=True) + if fn_vt is not None: + # Let as_python_constant() raise the proper exception + # (e.g., ClosureConversionError for non-constant closures) + fn = fn_vt.as_python_constant() + return _MaskModWrapper(fn) + + return super().as_python_constant() + + def as_proxy(self) -> object: + if isinstance(self.value, enum.Enum): + if isinstance(self.value, int): + return int(self.value) + return self.value + return super().as_proxy() + + def guard_as_python_constant(self) -> object: + if self.source: + install_guard(self.source.make_guard(GuardBuilder.ID_MATCH)) + return self.value + return super().guard_as_python_constant() + + def nb_bool_impl( + self, + tx: "InstructionTranslatorBase", + ) -> "VariableTracker | None": + # Mirrors slot_nb_bool: + # https://github.com/python/cpython/blob/c09ccd9c429/Objects/typeobject.c#L9408-L9458 + res = self._maybe_call_special(tx, "__bool__", []) + type_attr = self.lookup_class_mro_attr("__bool__") + using_len = False + + if type_attr is None: + raise_type_error( + tx, + f"'{self.python_type_name()}' cannot be interpreted as a boolean", + ) + elif res is None: + res = self._maybe_call_special(tx, "__len__", []) + using_len = True + + if res is None: + raise AssertionError("'res' should not be None") + + if using_len: + return generic_is_true(tx, res) + elif res.python_type() is bool: # pybool_check + return res + else: + if sys.version_info >= (3, 15): + err_str = f"{self.python_qualified_name()}.__bool__() must return a bool, not {res.python_qualified_name()}" + else: + err_str = ( + f"__bool__ should return bool, returned {res.python_type_name()}" + ) + + raise_type_error(tx, err_str) + + def tp_repr_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # ref: slot_tp_repr in https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10687-L10698 + if type(self.value).__repr__ is object.__repr__: + return VariableTracker.build(tx, repr(self.value)) + # A C-implemented __repr__ (e.g. `__repr__ = str.upper`) has no Python + # body to trace and graph breaks in _maybe_call_special. + res = self._maybe_call_special(tx, "__repr__", []) + if res is not None: + return res + unimplemented( + gb_type="untraceable user-defined __repr__", + context=f"Could not trace __repr__ override for {type(self.value).__name__}", + explanation="Dynamo could not safely trace this user-defined __repr__ override.", + hints=[*graph_break_hints.SUPPORTABLE], + skip_frame=True, + ) + + def tp_str_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/60403a5409ff2c3f3b07dd2ca91a7a3e096839c7/Objects/typeobject.c#L9475 + if type(self.value).__str__ is object.__str__: + return generic_repr(tx, self) + return self.SLOT0(tx, "__str__") + + def nb_index_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # CPython: PyNumber_Index checks tp_as_number->nb_index. + return self.SLOT0(tx, "__index__") + + def nb_int_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # CPython: slot_nb_int calls __int__(), PyNumber_Long validates the return type. + # https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1538-L1550 + return self.SLOT0(tx, "__int__") + + def nb_float_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # CPython: slot_nb_float calls __float__(), PyNumber_Float validates the return type. + # https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1647-L1658 + return self.SLOT0(tx, "__float__") + + def nb_negative_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # CPython: slot_nb_negative calls __neg__() via vectorcall_method. + # https://github.com/python/cpython/blob/v3.13.0/Objects/typeobject.c#L9361 + return self.SLOT0(tx, "__neg__") + + def nb_positive_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # CPython: slot_nb_positive calls __pos__() via vectorcall_method. + # https://github.com/python/cpython/blob/v3.13.0/Objects/typeobject.c#L9361 + return self.SLOT0(tx, "__pos__") + + def nb_absolute_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # CPython: slot_nb_absolute calls __abs__() via vectorcall_method. + # https://github.com/python/cpython/blob/v3.13.0/Objects/typeobject.c#L9406 + return self.SLOT0(tx, "__abs__") + + def nb_invert_impl( + self, + tx: "InstructionTranslatorBase", + ) -> VariableTracker: + # CPython: slot_nb_invert calls __invert__() via vectorcall_method. + # https://github.com/python/cpython/blob/v3.13.0/Objects/typeobject.c#L9426 + return self.SLOT0(tx, "__invert__") + + def torch_function_check(self) -> None: + if not has_torch_function(self): + raise AssertionError( + f"calling torch function on object without __torch_function__ {self}" + ) + + def get_torch_fn(self, tx: "InstructionTranslatorBase") -> VariableTracker: + self.torch_function_check() + from .torch_function import get_torch_function_fn + + return get_torch_function_fn(tx, self) + + def call_torch_function( + self, + tx: "InstructionTranslatorBase", + fn: VariableTracker, + types: "TupleVariable", + args: Sequence[Any], + kwargs: dict[str, Any], + ) -> VariableTracker: + self.torch_function_check() + + from .torch_function import call_torch_function + + return call_torch_function( + tx, + self.get_torch_fn(tx), + fn, + types, + args, + kwargs, + ) + + def sq_contains_impl( + self, tx: "InstructionTranslatorBase", item: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/4833e1cc666375454e4f86aff11b6587968b3333/Objects/typeobject.c#L9337 + type_attr = self.lookup_class_mro_attr("__contains__") + if type_attr is NO_SUCH_SUBOBJ: + raise_type_error( + tx, + f"'{self.python_type_name()}' object is not iterable", + ) + if type_attr is None: + raise_type_error(tx, f"{self.python_type_name()} is not a container") + + res = self._maybe_call_special(tx, "__contains__", [item]) + if res is None: + # PySequenceIterSearch + PySeqIterSearch = VariableTracker.build( + tx, polyfills.impl_CONTAINS_OP_fallback + ) + res = PySeqIterSearch.call_function(tx, [self, item], {}) + return generic_is_true(tx, res) + + def tp_iternext_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # https://github.com/python/cpython/blob/1ad0eef8ce8ec3db548be89c40fa427494e82814/Objects/typeobject.c#L10517 + return self._vectorcall_method(tx, "__next__", [], {}) + + def tp_iter_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # https://github.com/python/cpython/blob/1ad0eef8ce8ec3db548be89c40fa427494e82814/Objects/typeobject.c#L10496 + type_attr = self.lookup_class_mro_attr("__iter__") + if type_attr is None: + raise_type_error( + tx, + f"'{self.python_type_name()}' object is not iterable", + ) + + res = self._maybe_call_special(tx, "__iter__", []) + has_dunder_getitem = type_attr and type_attr is not NO_SUCH_SUBOBJ + + if res: + return res + + if not has_dunder_getitem: + raise_type_error( + tx, + f"'{self.python_type_name()}' object is not iterable", + ) + + SeqIter = VariableTracker.build(tx, polyfills.builtins.sequence_iterator) + return SeqIter.call_function(tx, [self], {}) + + @staticmethod + @functools.cache + def _supported_random_functions() -> set[Any]: + fns = { + random.random, + random.randint, + random.randrange, + random.uniform, + } + return fns + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/4833e1cc666375454e4f86aff11b6587968b3333/Objects/typeobject.c#L9370 + return self.SLOT1(tx, "__getitem__", key) + + def sq_repeat_impl( + self, + tx: "InstructionTranslatorBase", + count: VariableTracker, + ) -> VariableTracker: + method = self._maybe_get_baseclass_method("__mul__") + if ( + self._base_vt is not None + and self._base_methods is not None + and method in self._base_methods + ): + return self._base_vt.sq_repeat_impl(tx, count) + return super().sq_repeat_impl(tx, count) + + def sq_inplace_repeat_impl( + self, + tx: "InstructionTranslatorBase", + count: VariableTracker, + ) -> VariableTracker: + method = self._maybe_get_baseclass_method("__imul__") + if ( + self._base_vt is not None + and self._base_methods is not None + and method in self._base_methods + ): + self._base_vt.sq_inplace_repeat_impl(tx, count) + return self + return super().sq_inplace_repeat_impl(tx, count) + + def mp_ass_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + value: VariableTracker | None, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/4833e1cc666375454e4f86aff11b6587968b3333/Objects/typeobject.c#L9373 + if value is None: + return self._vectorcall_method(tx, "__delitem__", [key], {}) + else: + return self._vectorcall_method(tx, "__setitem__", [key, value], {}) + + sq_ass_item_impl = mp_ass_subscript_impl + + def _maybe_lookup_method( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker | None: + type_attr = self.lookup_class_mro_attr(name) + if type_attr is NO_SUCH_SUBOBJ: + # The method doesn't exist + return None + if type_attr is None: + # Method exists but it is set to None + return variables.ConstantVariable.create(None) + source = self.get_source_by_walking_mro(tx, name) if self.source else None + + # C slot wrapper / C method as a dunder: no Python body to trace. + # pybind11 exposes methods as CPython instancemethods wrapping a builtin + # function (e.g. ScriptDict.__repr__); those are equally untraceable, + # detected by a __func__ that is not a Python function. + is_c_special_method = isinstance( + type_attr, (types.WrapperDescriptorType, types.MethodDescriptorType) + ) or ( + torch._C._dynamo.utils.is_instancemethod(type_attr) # type: ignore[attr-defined] + and not isinstance(getattr(type_attr, "__func__", None), types.FunctionType) + ) + if is_c_special_method: + if not ( + self._base_vt is not None + and self._base_methods is not None + and type_attr in self._base_methods + ): + unimplemented( + gb_type="C-implemented special method without VariableTracker model", + context=f"name={name}, type={self.python_type_name()}, attr={type_attr}", + explanation=( + f"'{self.python_type_name()}' implements '{name}' in C " + f"and Dynamo has no model for it." + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + if isinstance(type_attr, types.WrapperDescriptorType): + # WrapperDescriptor.tp_descr_get -> MethodWrapper + return variables.MethodWrapperVariable( + type_attr, self._base_vt, source=source + ) + elif isinstance(type_attr, types.MethodDescriptorType): + # MethodDescriptor.tp_descr_get -> BuiltinMethod + return variables.BoundBuiltinMethodVariable( + type_attr, self._base_vt, source=source + ) + + if is_cython_function(type_attr): + raise AssertionError( + f"Cannot trace Cython function {name} on user-defined type {self.python_type_name()}" + ) + elif ( + torch._C._dynamo.utils.is_instancemethod(type_attr) # type: ignore[attr-defined] + or is_data_descriptor(type_attr) + ): + return self.resolve_data_descriptor(tx, name, type_attr, source) + else: + return self.resolve_type_attr(tx, name, type_attr, source) + + def _lookup_method( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + m = self._maybe_lookup_method(tx, name) + if m is None: + raise_type_error( + tx, f"'{self.python_type_name()}' object has no attribute '{name}'" + ) + return m + + def _vectorcall_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Mirror's CPython variant of vectorcall_method. + # NOTE: Dynamo does not IMPLEMENT the vectorcall protocol, but we keep + # the name for consistency with CPython's typeobject.c + m = self._lookup_method(tx, name) + return m.call_function(tx, args, kwargs) + + def _maybe_call_special( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + ) -> VariableTracker | None: + # Mirror's CPython variants of maybe_call_special_no_args and maybe_call_special_one_arg + m = self._maybe_lookup_method(tx, name) + if m is None: + return None + return m.call_function(tx, args, {}) + + def _vectorcall_maybe( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + ) -> VariableTracker: + # Mirrors CPython's vectorcall_maybe: lookup `name` on the type's MRO + # (NOT the instance), bind via the descriptor protocol, and call. + # Returns NotImplemented if the attribute is missing. + # + # Crucially, this must NOT route through `call_method`, since + # `call_method` re-dispatches dunders like __add__ back through + # nb__impl -> SLOT1BIN, causing infinite recursion when the + # type's ____ is a C-implemented slot wrapper that has no + # Python override. + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/typeobject.c#L2968-L2989 + + m = self._maybe_lookup_method(tx, name) + if m is None: + return variables.ConstantVariable.create(NotImplemented) + return m.call_function(tx, args, {}) + + def SLOT0( + self, + tx: "InstructionTranslatorBase", + dunder: str, + ) -> VariableTracker: + # Mirrors CPython's SLOT0 macro (Objects/typeobject.c). + return self._vectorcall_method(tx, dunder, [], {}) + + def SLOT1( + self, + tx: "InstructionTranslatorBase", + dunder: str, + other: VariableTracker, + ) -> VariableTracker: + # Mirrors CPython's SLOT1 macro (Objects/typeobject.c). + return self._vectorcall_method(tx, dunder, [other], {}) + + def SLOT1BIN( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + dunder: str, + rdunder: str, + nb_slot: int, # NB_OR, NB_AND, etc + reverse: bool, + ) -> VariableTracker: + # Implement SLOT1BIN semantics from CPython + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L9202-L9246 + # + # Direct translation of CPython's SLOT1BINFULL macro (Objects/typeobject.c). + # The logic is a bit convoluted, but the main idea remains the same. + # While implementing this I had some questions that might be worth + # answering here: + # + # Q1) What does SLOT1BIN do? + # + # It bridges a C nb_slot to the corresponding Python-level dunder + # methods, handling dispatch order (subclass priority, reflected calls) + # correctly. + # + # Q2) Why does this macro exist? + # + # For built-in types, CPython dispatches binary operations through + # C-level tp_as_number slots (e.g., nb_or). User-defined types don't + # have a native C slot implementation, so CPython installs a wrapper + # function (e.g., slot_nb_or) that maps the C slot interface to the + # Python-level dunder methods (e.g., __or__ / __ror__). SLOT1BINFULL is + # the body of that wrapper. + # + # Q3) Does SLOT1BIN implement the same logic as binary_op1? + # + # Not quite. binary_op1 (Objects/abstract.c) reads C slot pointers and + # dispatches based on pointer identity. SLOT1BINFULL runs *inside* a + # slot call and handles Python-level dispatch (MRO lookup, subclass + # priority, NotImplemented fallthrough). They are complementary layers. + # + # Q4) What types can self and other be? + # + # SLOT1BINFULL is installed as the C slot for Python-defined types, so + # at least one operand always has the slot wrapper (e.g., slot_nb_or). + # The do_other / TESTFUNC checks determine if the *other* operand also + # has a Python-defined slot: + # + # int do_other = !Py_IS_TYPE(self, Py_TYPE(other)) && + # Py_TYPE(other)->tp_as_number != NULL && + # Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; + # if (Py_TYPE(self)->tp_as_number != NULL && + # Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { ... } + # + # TESTFUNC == slot_nb_or (for the | operator), so this is basically + # asking "does this operand's type have a Python-defined dunder?" Native + # C types (e.g., int) fail the check and are skipped. + # + # Q5) Can this cause infinite recursion? + # + # Not if the dunder methods are called directly (MRO lookup + direct + # call), which is what CPython's vectorcall_maybe does. This is + # equivalent to calling a.__or__(b) directly, NOT a | b, which would + # re-enter the C slot layer and loop. + + def py_is_type(w_type: type, v_type: type) -> bool: + return w_type is v_type + + def py_is_subtype(w_type: type, v_type: type) -> bool: + return issubclass(w_type, v_type) + + self_, other_ = (other, self) if reverse else (self, other) + + s_type = self_.python_type() + o_type = other_.python_type() + + # Check if other is a different type and has the number slots + do_other = ( + not py_is_type(s_type, o_type) + and type_implements_nb_slot(o_type, nb_slot) + and isinstance(other_, UserDefinedObjectVariable) + ) + + if isinstance(self_, UserDefinedObjectVariable) and type_implements_nb_slot( + s_type, nb_slot + ): + if do_other and py_is_subtype(o_type, s_type): + # TODO: missing method_is_overloaded + method_is_overloaded = self_._maybe_get_baseclass_method( + rdunder + ) != other_._maybe_get_baseclass_method(rdunder) + if method_is_overloaded: + r = other_._vectorcall_maybe(tx, rdunder, [self_]) + if not is_nb_not_implemented(r): + return r + do_other = False + + r = self_._vectorcall_maybe(tx, dunder, [other_]) + if not is_nb_not_implemented(r) or py_is_type(o_type, s_type): + return r + + if do_other: + if not isinstance(other_, UserDefinedObjectVariable): + raise AssertionError( + f"Expected UserDefinedObjectVariable, got {type(other_)}" + ) + if other_._maybe_get_baseclass_method(rdunder): + r = other_._vectorcall_maybe(tx, rdunder, [self_]) + if not is_nb_not_implemented(r): + return r + + return variables.ConstantVariable.create(NotImplemented) + + def nb_multiply_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + return self.SLOT1BIN( + tx, + other, + "__mul__", + "__rmul__", + nb_slot=PyNumberSlots.NB_MULTIPLY, + reverse=reverse, + ) + + def nb_matrix_multiply_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + return self.SLOT1BIN( + tx, + other, + "__matmul__", + "__rmatmul__", + nb_slot=PyNumberSlots.NB_MATRIX_MULTIPLY, + reverse=reverse, + ) + + def nb_inplace_matrix_multiply_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + return self.SLOT1(tx, "__imatmul__", other) + + def nb_lshift_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10337-L10340 + return self.SLOT1BIN( + tx, + other, + "__lshift__", + "__rlshift__", + nb_slot=PyNumberSlots.NB_LSHIFT, + reverse=reverse, + ) + + def nb_inplace_lshift_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + return self.SLOT1(tx, "__ilshift__", other) + + def nb_rshift_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10341-L10344 + return self.SLOT1BIN( + tx, + other, + "__rshift__", + "__rrshift__", + nb_slot=PyNumberSlots.NB_RSHIFT, + reverse=reverse, + ) + + def nb_inplace_rshift_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + return self.SLOT1(tx, "__irshift__", other) + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10354-L10355 + return self.SLOT1BIN( + tx, + other, + "__or__", + "__ror__", + nb_slot=PyNumberSlots.NB_OR, + reverse=reverse, + ) + + def nb_inplace_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L9494 + return self.SLOT1(tx, "__ior__", other) + + def nb_and_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L9472 (slot_nb_and) + return self.SLOT1BIN( + tx, + other, + "__and__", + "__rand__", + nb_slot=PyNumberSlots.NB_AND, + reverse=reverse, + ) + + def nb_inplace_and_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + return self.SLOT1(tx, "__iand__", other) + + def nb_xor_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L9473 (slot_nb_xor) + return self.SLOT1BIN( + tx, + other, + "__xor__", + "__rxor__", + nb_slot=PyNumberSlots.NB_XOR, + reverse=reverse, + ) + + def nb_inplace_xor_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + return self.SLOT1(tx, "__ixor__", other) + + def nb_add_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10315-L10318 + return self.SLOT1BIN( + tx, + other, + "__add__", + "__radd__", + nb_slot=PyNumberSlots.NB_ADD, + reverse=reverse, + ) + + def nb_inplace_add_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L9494 + return self.SLOT1(tx, "__iadd__", other) + + def nb_subtract_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10319-L10322 + return self.SLOT1BIN( + tx, + other, + "__sub__", + "__rsub__", + nb_slot=PyNumberSlots.NB_SUBTRACT, + reverse=reverse, + ) + + def nb_inplace_subtract_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10362-L10363 + return self.SLOT1(tx, "__isub__", other) + + def nb_inplace_multiply_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + return self.SLOT1(tx, "__imul__", other) + + def nb_floor_divide_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10323-L10326 + return self.SLOT1BIN( + tx, + other, + "__floordiv__", + "__rfloordiv__", + nb_slot=PyNumberSlots.NB_FLOOR_DIVIDE, + reverse=reverse, + ) + + def nb_inplace_floor_divide_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + return self.SLOT1(tx, "__ifloordiv__", other) + + def nb_true_divide_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10327-L10330 + return self.SLOT1BIN( + tx, + other, + "__truediv__", + "__rtruediv__", + nb_slot=PyNumberSlots.NB_TRUE_DIVIDE, + reverse=reverse, + ) + + def nb_inplace_true_divide_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + return self.SLOT1(tx, "__itruediv__", other) + + def nb_remainder_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10331-L10334 + return self.SLOT1BIN( + tx, + other, + "__mod__", + "__rmod__", + nb_slot=PyNumberSlots.NB_REMAINDER, + reverse=reverse, + ) + + def nb_inplace_remainder_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + return self.SLOT1(tx, "__imod__", other) + + def nb_divmod_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10335-L10336 + return self.SLOT1BIN( + tx, + other, + "__divmod__", + "__rdivmod__", + nb_slot=PyNumberSlots.NB_DIVMOD, + reverse=reverse, + ) + + def nb_power_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + z: VariableTracker | None, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L10319-L10322 + if z is not None: + # Ternary pow(x, y, mod): __rpow__ is never called for 3-arg pow. + base, exp = (other, self) if reverse else (self, other) + return base.call_method(tx, "__pow__", [exp, z], {}) + return self.SLOT1BIN( + tx, + other, + "__pow__", + "__rpow__", + nb_slot=PyNumberSlots.NB_POWER, + reverse=reverse, + ) + + def nb_inplace_power_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + z: VariableTracker | None, + ) -> VariableTracker: + return self.SLOT1(tx, "__ipow__", other) + + def nb_power_z_impl( + self, + tx: "InstructionTranslatorBase", + v: VariableTracker, + w: VariableTracker, + ) -> VariableTracker: + # CPython: type(z)->nb_power(v, w, z) for a Python class calls v.__pow__(w, z). + return v.call_method(tx, "__pow__", [w, self], {}) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .. import trace_rules + from . import UserMethodVariable + from .constant import ConstantVariable + + method = self._maybe_get_baseclass_method(name) + if method is not None: + if method is object.__init__: + return ConstantVariable.create(None) + + if is_standard_setattr(method) or isinstance(self.value, threading.local): + return self.method_setattr_standard(tx, *args, **kwargs) + + if is_standard_delattr(method): + return self.method_setattr_standard( + tx, args[0], variables.DeletedVariable() + ) + + if isinstance(self.value, types.GeneratorType): + unimplemented( + gb_type="call_method on generator", + context=f"object={self.value}, method={name}, args={args}, kwargs={kwargs}", + explanation="Detected a method call to a user-defined generator object. " + "This is not fully supported.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + # torch.Generator methods like manual_seed(), get_state(), etc. + # are stateful RNG operations that cannot be soundly traced. + if ( + isinstance(self.value, torch._C.Generator) + and name in trace_rules._GENERATOR_METHODS_THAT_GRAPH_BREAK + ): + unimplemented( + gb_type="torch.Generator method", + context=f"torch.Generator.{name}", + explanation=f"torch.Generator.{name}() is a stateful RNG " + "operation that cannot be soundly traced in the FX graph.", + hints=[*graph_break_hints.FUNDAMENTAL], + ) + + tp_method = self.lookup_tp_method(name) + if tp_method is not None: + result = tp_method(self, tx, name, args, kwargs) + if result is not None: + return result + + # Delegate to _base_vt for non-overridden base-class methods. + # Skip comparison ops: they go through tp_richcompare_impl on the + # UserDefined*Variable subclass, which handles _base_vt + # unwrapping and avoids tracing tensor elements via list_cmp. + if ( + self._base_vt is not None + and self._base_methods is not None + and method in self._base_methods + and name not in self._slotdefs + ): + return self._base_vt.call_method(tx, name, args, kwargs) + + # check for methods implemented in C++ + if isinstance(method, types.FunctionType): + source = self.source + source_fn = None + if source: + source_fn = self.get_source_by_walking_mro(tx, name) + # TODO(jansel): add a guard to check for monkey patching? + from ..mutation_guard import unpatched_nn_module_init + + if method is torch.nn.Module.__init__: + method = unpatched_nn_module_init + return UserMethodVariable( + method, self, source_fn=source_fn, source=source + ).call_function(tx, args, kwargs) # type: ignore[arg-type] + + if method is list.__len__ and self.source and not (args or kwargs): + install_guard(self.source.make_guard(GuardBuilder.SEQUENCE_LENGTH)) + return VariableTracker.build(tx, len(self.value)) # type: ignore[arg-type] + + if trace_rules.is_polyfilled_callable(method): # type: ignore[arg-type] + from .functions import PolyfilledFunctionVariable + + polyfill_handlers = PolyfilledFunctionVariable._get_polyfill_handlers() + wrapped: Any = polyfill_handlers.get(method) # type: ignore[arg-type] + if wrapped is not None: + traceable_fn = wrapped.__torch_dynamo_polyfill__ + return variables.UserMethodVariable( + traceable_fn, self + ).call_function(tx, args, kwargs) + + if name == "__call__": + unimplemented( + gb_type="call to a callable object with no traceable __call__", + context=f"object={self.value}", + explanation="Dynamo could not trace a Python `__call__` method on " + "this object.", + hints=[*graph_break_hints.SUPPORTABLE], + ) + + return super().call_method(tx, name, args, kwargs) + + def sq_item_impl( + self, tx: "InstructionTranslatorBase", key: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/4833e1cc666375454e4f86aff11b6587968b3333/Objects/typeobject.c#L9294 + return self._vectorcall_method(tx, "__getitem__", [key], {}) + + def tp_init_impl( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + res = self._vectorcall_method(tx, "__init__", args, kwargs) + if not res.is_constant_none(): + raise_type_error( + tx, f"__init__() should return None, got {res.python_type_name()}" + ) + return res + + def sq_concat_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/typeobject.c#L10373-L10374 + method = self._maybe_get_baseclass_method("__add__") + if ( + self._base_vt is not None + and self._base_methods is not None + and method in self._base_methods + ): + return self._base_vt.sq_concat_impl(tx, other) + return super().sq_concat_impl(tx, other) + + def sq_inplace_concat_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Objects/typeobject.c#L10387-L10389 + method = self._maybe_get_baseclass_method("__iadd__") + if ( + self._base_vt is not None + and self._base_methods is not None + and method in self._base_methods + ): + self._base_vt.sq_inplace_concat_impl(tx, other) + return self + return super().sq_inplace_concat_impl(tx, other) + + def sq_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # ref: https://github.com/python/cpython/blob/4833e1cc666375454e4f86aff11b6587968b3333/Objects/typeobject.c#L9266 + res = self._vectorcall_method(tx, "__len__", [], {}) + + # A symbolic length must stay symbolic: coercing it via __index__ / + # PyNumber_AsSsize_t would specialize the shape to a constant and + # defeat dynamic shapes. The runtime non-negativity check is skipped. + if isinstance(res, variables.SymNodeVariable): + return res + + res = pynumber_index(tx, res) + if res.as_python_constant() < 0: + raise_observed_exception( + ValueError, + tx, + args=["__len__() should return >= 0"], + ) + + return pynumber_as_ssize_t(tx, res, OverflowError) + + # ref: https://github.com/python/cpython/blob/4833e1cc666375454e4f86aff11b6587968b3333/Objects/typeobject.c#L9368 + mp_length_impl = sq_length_impl + + def method_setattr_standard( + self, + tx: "InstructionTranslatorBase", + name: VariableTracker, + value: VariableTracker, + ) -> VariableTracker: + name_str = "" + try: + name_str = name.as_python_constant() + except NotImplementedError: + unimplemented( + gb_type="non-const setattr name on user-defined object", + context=f"object={self}, name={name}, value={value}", + explanation="Detected a call to `setattr` of a user-defined object with a non-constant name.", + hints=["Ensure that the name is a string."], + ) + if not tx.output.side_effects.is_attribute_mutation(self): + raise AssertionError( + "Attempted setattr on a user-defined object that does not have " + "an AttributeMutation mutation_type" + ) + + if ( + torch.distributed.is_available() + and type(self.value) is torch.distributed.P2POp + and ( + tx.output.side_effects.has_pending_mutation_of_attr(self, name_str) + or name_str in self.value.__dict__ + ) + ): + unimplemented( + gb_type="P2POp mutation", + context=f"object={self}, name={name}, value={value}", + explanation="Dynamo does not support mutating torch.distributed.P2POp instances.", + hints=[ + "Construct a new torch.distributed.P2POp instead of mutating an existing one inside torch.compile.", + ], + ) + + if name_str == "__class__": + unimplemented( + gb_type="__class__ assignment on user-defined object", + context=f"object={self}, value={value}", + explanation="Dynamo does not support reassigning __class__ on user-defined objects.", + hints=[ + "Move the __class__ assignment outside of the torch.compile region.", + ], + ) + + def raise_cannot_set_attr() -> NoReturn: + raise_observed_exception( + AttributeError, + tx, + args=[ + f"'{type(self.value).__name__}' object has no attribute '{name_str}'" + ], + ) + + def raise_readonly_attr() -> NoReturn: + raise_observed_exception( + AttributeError, + tx, + args=[ + f"'{type(self.value).__name__}' object attribute '{name_str}' is read-only" + ], + ) + + def raise_property_error(action: str) -> NoReturn: + raise_observed_exception( + AttributeError, + tx, + args=[ + f"property '{name_str}' of " + f"'{type(self.value).__name__}' object has no {action}" + ], + ) + + descriptor = self.lookup_class_mro_attr(name_str) + if descriptor is not NO_SUCH_SUBOBJ and ( + hasattr(type(descriptor), "__set__") + or hasattr(type(descriptor), "__delete__") + ): + desc_source = None + if self.cls_source: + desc_source = self.get_source_by_walking_mro(tx, name_str) + + if isinstance(descriptor, property): + if isinstance(value, variables.DeletedVariable): + if descriptor.fdel is None: + raise_property_error("deleter") + fdel_source = ( + AttrSource(desc_source, "fdel") if desc_source else None + ) + fdel_var = VariableTracker.build( + tx, descriptor.fdel, source=fdel_source + ) + return fdel_var.call_function(tx, [self], {}) + if descriptor.fset is None: + raise_property_error("setter") + fset_source = AttrSource(desc_source, "fset") if desc_source else None + fset_var = VariableTracker.build( + tx, descriptor.fset, source=fset_source + ) + return fset_var.call_function(tx, [self, value], {}) + + if isinstance(descriptor, types.MemberDescriptorType): + tx.output.side_effects.store_attr(self, name_str, value) + return variables.ConstantVariable.create(None) + + if isinstance(descriptor, types.GetSetDescriptorType): + if name_str == "__dict__": + self.dict_vt = None + # C get/set descriptors are applied by STORE_ATTR itself, so + # replay must stay descriptor-aware rather than using the + # descriptor-bypassing instance-dict or slot paths. + tx.output.side_effects.store_attr(self, name_str, value) + return variables.ConstantVariable.create(None) + + setter = inspect.getattr_static(type(descriptor), "__set__", None) + deleter = inspect.getattr_static(type(descriptor), "__delete__", None) + # collections._tuplegetter (namedtuple field accessor) is a C-level + # data descriptor whose __set__/__delete__ unconditionally raise + # AttributeError. Short-circuit so we don't need to model it. + _tuplegetter = getattr(collections, "_tuplegetter", None) + if _tuplegetter is not None and type(descriptor) is _tuplegetter: + raise_readonly_attr() + desc_var = VariableTracker.build(tx, descriptor, desc_source) + if isinstance(value, variables.DeletedVariable): + if isinstance(deleter, types.FunctionType): + del_source = ( + AttrSource(TypeSource(desc_source), "__delete__") + if desc_source + else None + ) + del_var = VariableTracker.build( + tx, deleter, del_source, realize=True + ) + return del_var.call_function(tx, [desc_var, self], {}) + if deleter is not None: + unimplemented( + gb_type="C-level descriptor delete on user-defined object", + context=f"object={self}, name={name_str}, descriptor={descriptor}", + explanation=( + "Dynamo does not yet model this C-level descriptor deleter " + "for user-defined objects." + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + raise_readonly_attr() + if isinstance(setter, types.FunctionType): + set_source = ( + AttrSource(TypeSource(desc_source), "__set__") + if desc_source + else None + ) + set_var = VariableTracker.build(tx, setter, set_source, realize=True) + return set_var.call_function(tx, [desc_var, self, value], {}) + + unimplemented( + gb_type="C-level descriptor setattr on user-defined object", + context=f"object={self}, name={name_str}, descriptor={descriptor}", + explanation=( + "Dynamo does not yet model this C-level descriptor setter " + "for user-defined objects." + ), + hints=[*graph_break_hints.SUPPORTABLE], + ) + + if hasattr(self.value, "__dict__"): + dict_vt = self.get_dict_vt(tx) + if isinstance(value, variables.DeletedVariable): + if not dict_vt.contains(name_str): + raise_cannot_set_attr() + dict_vt.delitem(name_str) + else: + dict_vt.setitem(name_str, value) + return variables.ConstantVariable.create(None) + + raise_cannot_set_attr() + + def needs_slow_setattr(self) -> bool: + return not is_standard_setattr( + inspect.getattr_static(self.value, "__setattr__", None) + ) and not isinstance(self.value, threading.local) + + def unpack_var_sequence( + self, tx: "InstructionTranslatorBase" + ) -> list[VariableTracker]: + return unpack_iterable(tx, self) + + def is_supported_random(self) -> bool: + try: + return self.value in self._supported_random_functions() + except (TypeError, AttributeError): + # TypeError: unhashable type + # AttributeError: backing object may not be fully initialized + return False + + def call_function( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if ( + self.is_supported_random() + and all(k.is_python_constant() for k in args) + and all(v.is_python_constant() for v in kwargs.values()) + ): + return call_random_fn(tx, self.value, args, kwargs) # type: ignore[arg-type] + elif istype(self.value, types.MethodType): + func = self.value.__func__ + obj = self.value.__self__ + if ( + func is torch.utils._contextlib._DecoratorContextManager.clone + and variables.TorchCtxManagerClassVariable.is_matching_cls( + obj.__class__ + ) + and not (args or kwargs) + ): + return variables.TorchCtxManagerClassVariable( + obj.__class__ + ).call_function(tx, args, kwargs) + + if ( + func is torch.autograd.grad_mode.inference_mode.clone + and obj.__class__ is torch.autograd.grad_mode.inference_mode + ): + # simulate the inference_mode.clone implementation + var = VariableTracker.build(tx, obj.mode) # type: ignore[attr-defined] + return variables.TorchCtxManagerClassVariable( + obj.__class__ + ).call_function(tx, [var], kwargs) + + if self.source is None: + unimplemented( + gb_type="attempted to call sourceless user-defined object as a method", + context=f"object={self.value}, function={func}, args={args}, kwargs={kwargs}", + explanation="Dynamo does not support this.", + hints=[ + f"Ensure the user-defined object {self.value} is constructed outside the compiled region.", + ], + ) + if self.source is None: + raise AssertionError("source must not be None for bound method call") + func_src = AttrSource(self.source, "__func__") + func_var = VariableTracker.build(tx, func, func_src, realize=True) + obj_src = AttrSource(self.source, "__self__") + obj_var = VariableTracker.build(tx, obj, obj_src) + return func_var.call_function(tx, [obj_var] + args, kwargs) # type: ignore[arg-type] + elif callable(self.value): + if self.source: + if self.cls_source is None: + raise AssertionError( + "cls_source must not be None for callable with source" + ) + source_attr = AttrSource(self.cls_source, "__call__") + install_guard(source_attr.make_guard(GuardBuilder.CLOSURE_MATCH)) + return self.call_method(tx, "__call__", args, kwargs) # type: ignore[arg-type] + + return super().call_function(tx, args, kwargs) + + def _check_for_getattr(self) -> object: + return get_custom_getattr(self.value) + + def _is_c_defined_property(self, subobj: object) -> bool: + if not isinstance(subobj, property): + return False + + # pybind def_readwrite is implemented via PyCFunction. At the python level, it is visible as a property whose + # fget is an instancemethod wrapper - https://docs.python.org/3/c-api/method.html#c.PyInstanceMethod_Check + + # If we have a PyCFunction, we make an assumption that there is no side effect. + return isinstance( + subobj.fget, types.BuiltinFunctionType + ) or torch._C._dynamo.utils.is_instancemethod(subobj.fget) # type: ignore[attr-defined] + + def _getattr_static(self, name: str) -> object: + if name in self._looked_up_attrs: + return self._looked_up_attrs[name] + + subobj = inspect.getattr_static(self.value, name, NO_SUCH_SUBOBJ) + + # In some cases, we have to do dynamic lookup because getattr_static is not enough. For example, threading.local + # has side-effect free __getattribute__ and the attribute is not visible without a dynamic lookup. + # NOTE we assume the following descriptors are side-effect-free as far + # as Dynamo tracing is concerned. + # + # C-level descriptors (getset_descriptor for __dict__, member_descriptor + # for __slots__) are always safe to resolve — their __get__ is + # implemented in C and doesn't run user code, so __getattribute__ + # overrides are irrelevant. The NO_SUCH_SUBOBJ and + # _is_c_defined_property cases DO require the absence of a custom + # __getattribute__ because they fall back to + # type(self.value).__getattribute__ which could be user-overridden. + if inspect.ismemberdescriptor(subobj) or inspect.isgetsetdescriptor(subobj): + subobj = type(self.value).__getattribute__(self.value, name) + elif not self._object_has_getattribute and ( + subobj is NO_SUCH_SUBOBJ # e.g., threading.local + or self._is_c_defined_property(subobj) + ): + # Call __getattribute__, we have already checked that this is not overridden and side-effect free. We don't + # want to call getattr because it can be user-overridden. + subobj = type(self.value).__getattribute__(self.value, name) + elif self._object_has_getattribute and subobj is NO_SUCH_SUBOBJ: + # If the object has an overridden getattribute method, Dynamo has + # already tried tracing it, and encountered an AttributeError. We + # call getattr_static only when the __getattribute__ tracing fails + # (check tp_getattro_impl impl). So, it is safe here to raise the + # AttributeError. + raise AttributeError + + self._looked_up_attrs[name] = subobj + return subobj + + def lookup_class_mro_attr(self, name: str) -> object: + """Walk type(obj).__mro__ to find *name* in the class hierarchy. + + Cached wrapper around mro_lookup() for UDOV. Only searches the + class chain (type(obj).__mro__), NOT the metaclass chain. + """ + if name in self._subobj_from_class: + return self._subobj_from_class[name] + + result = mro_lookup(type(self.value), name) + self._subobj_from_class[name] = result + return result + + def has_key_in_generic_dict( + self, tx: "InstructionTranslatorBase", key: str + ) -> bool: + if tx.output.side_effects.has_pending_mutation_of_attr( + self, key, AttrMutationKind.INSTANCE_DICT + ): + mutated_attr = tx.output.side_effects.load_attr(self, key, deleted_ok=True) + return not isinstance(mutated_attr, variables.DeletedVariable) + + # TODO(guilhermeleobas): This can trigger a side effect + return key in self.value.__dict__ + + def get_source_by_walking_mro( + self, tx: "InstructionTranslatorBase", name: str + ) -> DictGetItemSource: + if self.cls_source is None: + raise AssertionError("cls_source must not be None for MRO walk") + + for idx, klass in enumerate(type(self.value).__mro__): + if name in klass.__dict__: + descriptor = klass.__dict__[name] + + # Guard that intermediate MRO classes don't shadow this + # attribute, deduplicating by (id(klass), name) across + # subclasses that share the same intermediate MRO class. + # Safe because TYPE_MATCH guards fix the MRO, so the same + # id(klass) always refers to the same class object. + for absent_idx in range(1, idx): + absent_klass = type(self.value).__mro__[absent_idx] + cache_key = (id(absent_klass), name) + if cache_key in tx.output.guarded_mro_absent_keys: + continue + tx.output.guarded_mro_absent_keys.add(cache_key) + mro_source = TypeMROSource(self.cls_source) + klass_source: Source = GetItemSource(mro_source, absent_idx) + dict_source = TypeDictSource(klass_source) + install_guard( + dict_source.make_guard( + functools.partial(GuardBuilder.DICT_NOT_CONTAINS, key=name) + ) + ) + + # Guard that the instance __dict__ does not shadow the + # class attribute. Skipped for data descriptors (those + # with __set__, e.g. property) because Python gives data + # descriptors priority over instance __dict__ in attribute + # lookup — the instance dict can only be populated by + # directly writing to obj.__dict__, not via setattr. + if ( + self.source + and hasattr(self.value, "__dict__") + and name not in self.value.__dict__ + and not hasattr(descriptor, "__set__") + ): + install_guard( + self.source.make_guard( + functools.partial( + GuardBuilder.NOT_PRESENT_IN_GENERIC_DICT, attr=name + ) + ) + ) + + # Reuse the source if we've already resolved the same + # descriptor object for the same attribute name (e.g. same + # property reached via different subclasses) to avoid + # redundant ID_MATCH guards. We include name in the key + # because distinct attributes can point to the same object + # (e.g. a = b = some_obj, or interned small integers). + cache_key = (id(descriptor), name) + cache = tx.output.mro_source_cache + if cache_key in cache: + return cache[cache_key] + + if idx != 0: + mro_source = TypeMROSource(self.cls_source) + klass_source = GetItemSource(mro_source, idx) + else: + klass_source = self.cls_source + dict_source = TypeDictSource(klass_source) + out_source = DictGetItemSource(dict_source, name) + cache[cache_key] = out_source + return out_source + + unimplemented( + gb_type="could not find name in object's mro", + context=f"name={name}, object type={type(self.value)}, mro={type(self.value).__mro__}", + explanation=f"Could not find name `{name}` in mro {type(self.value).__mro__}", + hints=[ + f"Ensure the name `{name}` is defined somewhere in {self.value}'s type hierarchy.", + *graph_break_hints.USER_ERROR, + ], + ) + + def generic_getattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + """Dynamo implementation of CPython's PyObject_GenericGetAttr. + + This mirrors object.__getattribute__ and is called from: + - tp_getattro_impl (for objects without a custom __getattribute__) + - SuperVariable.call_method (when super().__getattribute__() resolves + to object.__getattribute__) + + The algorithm: MRO walk → data descriptor → instance __dict__ → + non-data descriptor / plain class attr → dynamic fallback → + __getattr__ → AttributeError. + """ + source: Source | None = AttrSource(self.source, name) if self.source else None + + if name == "__dict__": + if not hasattr(self.value, "__dict__"): + raise_observed_exception(AttributeError, tx) + return self.get_dict_vt(tx) + + # TODO(anijain2305) - Investigate if we need specialization for more + # dunder attrs. inspect.getattr_static does not return correct value for + # them. + if name == "__class__": + cls_source: Source | None = source + if source is None: + cls_source = self.cls_source + else: + cls_source = source + return VariableTracker.build(tx, type(self.value), cls_source) + + from ..mutation_guard import unpatched_nn_module_init + + # ---- CPython attribute lookup algorithm ---- + # Mirror object.__getattribute__ (PyObject_GenericGetAttr): + # 1. type_attr = lookup name in type(obj).__mro__ + # 2. if type_attr is a DATA descriptor → invoke it + # 3. if name in obj.__dict__ → return as-is (no descriptor invocation) + # 4. if type_attr is a non-data descriptor → invoke it + # 5. if type_attr is a plain class variable → return it + # 6. __getattr__ fallback + # 7. raise AttributeError + # + # Between steps 5 and 6, we also handle objects with custom storage + # that aren't visible via the MRO walk or instance __dict__ (step 5b). + # + # Step 1: Single MRO walk on the type (cached). + type_attr = self.lookup_class_mro_attr(name) + + # Dynamo patches nn.Module.__init__ at import time to inject tracing + # hooks. Undo that here so the unpatched original is traced instead. + if type_attr is torch.nn.Module.__init__: + type_attr = unpatched_nn_module_init + + # Step 2: Data descriptors on the type take priority over instance dict. + if type_attr is not NO_SUCH_SUBOBJ and is_data_descriptor(type_attr): + return self.resolve_data_descriptor(tx, name, type_attr, source) + + # Step 3: Instance __dict__ — return as-is, no descriptor invocation. + result = self.lookup_instance_dict(tx, name) + if result is not None: + return result + + # Step 4-5: Non-data descriptor or plain class attribute. + if type_attr is not NO_SUCH_SUBOBJ: + return self.resolve_type_attr(tx, name, type_attr, source) + + # Step 5b: Dynamic fallback for attributes that exist on the live + # object but aren't visible to the static MRO walk or instance + # __dict__ check above. This covers objects with custom storage + # backends (e.g. threading.local uses a per-thread dict not + # accessible via obj.__dict__) and C extensions that store data + # outside the normal Python object layout. + # + # This is NOT the same as the C-level data descriptor fallback in + # resolve_data_descriptor (step 2): that handles descriptors found + # on the type MRO (like member_descriptor for __slots__), while this + # handles attributes that aren't on the type MRO at all. + # + # Only safe when the class doesn't override __getattribute__, + # otherwise we'd run arbitrary user code. + # Skip if side effects have mutations that supersede the live object. + has_instance_mutations = tx.output.side_effects.has_pending_mutation_of_attr( + self, + name, + (AttrMutationKind.INSTANCE_DICT, AttrMutationKind.GENERIC_SETATTR), + ) or tx.output.side_effects.has_pending_mutation_of_attr( + self, "__dict__", AttrMutationKind.GENERIC_SETATTR + ) + if not self._object_has_getattribute and not has_instance_mutations: + try: + resolved = type(self.value).__getattribute__(self.value, name) + source = self.maybe_wrap_nn_module_source_for_instance(tx, name, source) + return VariableTracker.build(tx, resolved, source) + except AttributeError: + pass + + # Step 6: __getattr__ fallback. + result = self.call_getattr_fallback(tx, name) + if result is not None: + return result + + # Step 7: AttributeError. + raise_observed_exception( + AttributeError, + tx, + args=[f"'{type(self.value).__name__}' object has no attribute '{name}'"], + kwargs={"name": variables.ConstantVariable.create(name), "obj": self}, + ) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if self._object_has_getattribute: + getattribute_fn = inspect.getattr_static( + type(self.value), "__getattribute__" + ) + new_source: AttrSource | None = ( + AttrSource(self.source, "__getattribute__") if self.source else None + ) + + try: + return variables.UserMethodVariable( + getattribute_fn, + self, + source=new_source, + ).call_function(tx, [VariableTracker.build(tx, name)], {}) + except ObservedAttributeError: + # Pass through to __getattr__ if __getattribute__ fails + handle_observed_exception(tx) + + return self.generic_getattr(tx, name) + + def resolve_data_descriptor( + self, + tx: "InstructionTranslatorBase", + name: str, + type_attr: object, + source: Source | None, + ) -> VariableTracker: + """Handle data descriptors found on the type MRO (property, _tuplegetter, etc.).""" + # TODO - Check what is this _is_c_defined_property and if this handling should be moved inside the PropertyVariable. + if isinstance(type_attr, property) and not self._is_c_defined_property( + type_attr + ): + # Source points to the descriptor in the class __dict__ via MRO + # walk, not via AttrSource(cls, name) which would trigger the + # descriptor protocol and skip past the property wrapper. + if self.source: + source = self.get_source_by_walking_mro(tx, name) + prop_vt = variables.PropertyVariable(type_attr, source=source) + return prop_vt.tp_descr_get_impl( + tx, self, self.tp_getattro_impl(tx, "__class__") + ) + if isinstance(type_attr, types.MemberDescriptorType): + if tx.output.side_effects.has_pending_mutation_of_attr( + self, name, AttrMutationKind.GENERIC_SETATTR + ): + result = tx.output.side_effects.load_attr(self, name, deleted_ok=True) + if isinstance(result, variables.DeletedVariable): + raise_observed_exception( + AttributeError, + tx, + args=[ + f"'{type(self.value).__name__}' object has no attribute '{name}'" + ], + ) + return result + md_vt = variables.MemberDescriptorVariable(type_attr, source=source) + return md_vt.tp_descr_get_impl( + tx, self, self.tp_getattro_impl(tx, "__class__") + ) + + if isinstance(type_attr, types.GetSetDescriptorType): + if tx.output.side_effects.has_pending_mutation_of_attr( + self, name, AttrMutationKind.GENERIC_SETATTR + ): + result = tx.output.side_effects.load_attr(self, name, deleted_ok=True) + if isinstance(result, variables.DeletedVariable): + raise_observed_exception( + AttributeError, + tx, + args=[ + f"'{type(self.value).__name__}' object has no attribute '{name}'" + ], + ) + return result + gs_vt = variables.GetSetDescriptorVariable(type_attr, source=source) + return gs_vt.tp_descr_get_impl( + tx, self, self.tp_getattro_impl(tx, "__class__") + ) + + if isinstance(type_attr, _collections._tuplegetter): + tg_vt = variables.TupleGetterVariable(type_attr, source=source) + return tg_vt.tp_descr_get_impl( + tx, self, self.tp_getattro_impl(tx, "__class__") + ) + + get_fn = inspect.getattr_static(type(type_attr), "__get__", None) + if isinstance(get_fn, types.FunctionType): + # User-defined data descriptor with a Python __get__. + return self.invoke_descriptor_get(tx, name, type_attr, source) + + # TODO - Check when are these called - and if we need to create new VTs. + # Remaining C-level data descriptors (Cython attrs, etc.) + # -- resolve via __getattribute__. + try: + resolved = type(self.value).__getattribute__(self.value, name) + except AttributeError: + raise_observed_exception( + AttributeError, + tx, + args=[ + f"'{type(self.value).__name__}' object has no attribute '{name}'" + ], + ) + return VariableTracker.build(tx, resolved, source) + + def resolve_type_attr( + self, + tx: "InstructionTranslatorBase", + name: str, + type_attr: object, + source: Source | None, + ) -> VariableTracker: + """Handle non-data descriptors and plain class attributes from the type MRO.""" + from ..mutation_guard import unpatched_nn_module_init + + if ( + type_attr is unpatched_nn_module_init + or type_attr is torch.nn.Module.__init__ + ): + type_attr = unpatched_nn_module_init + + can_use_mro_source = self.cls_source is not None and self.source is not None + + if isinstance(type_attr, staticmethod): + # Source points to the descriptor in the class __dict__ via MRO + # walk, not via AttrSource(cls, name) which would trigger the + # descriptor protocol and skip past the staticmethod wrapper. + if can_use_mro_source: + source = self.get_source_by_walking_mro(tx, name) + sm_vt = variables.StaticMethodVariable(type_attr, source=source) + return sm_vt.tp_descr_get_impl( + tx, self, self.tp_getattro_impl(tx, "__class__") + ) + elif isinstance(type_attr, classmethod): + # Source points to the descriptor in the class __dict__ via MRO + # walk, not via AttrSource(cls, name) which would trigger the + # descriptor protocol and skip past the classmethod wrapper. + if can_use_mro_source: + source = self.get_source_by_walking_mro(tx, name) + cm_vt = variables.ClassMethodVariable(type_attr, source=source) + return cm_vt.tp_descr_get_impl( + tx, self, self.tp_getattro_impl(tx, "__class__") + ) + elif isinstance(type_attr, types.ClassMethodDescriptorType): + cmd_vt = variables.ClassMethodDescriptorVariable(type_attr, source=source) + return cmd_vt.tp_descr_get_impl( + tx, self, self.tp_getattro_impl(tx, "__class__") + ) + elif isinstance(type_attr, types.WrapperDescriptorType): + class_vt = self.tp_getattro_impl(tx, "__class__") + wd_vt = variables.WrapperDescriptorVariable( + type_attr, owner=class_vt, source=source + ) + return wd_vt.tp_descr_get_impl(tx, self, class_vt) + elif isinstance(type_attr, types.MethodDescriptorType): + class_vt = self.tp_getattro_impl(tx, "__class__") + md_vt = variables.MethodDescriptorVariable( + type_attr, owner=class_vt, source=source + ) + return md_vt.tp_descr_get_impl(tx, self, class_vt) + elif is_lru_cache_wrapped_function(type_attr): + return variables.WrapperUserMethodVariable( + type_attr, "__wrapped__", self, source=source + ) + elif isinstance(type_attr, types.FunctionType): + while hasattr(type_attr, "_torchdynamo_inline"): + type_attr = type_attr._torchdynamo_inline # type: ignore[union-attr] + source = AttrSource(source, "_torchdynamo_inline") if source else None + # Function on the type MRO + not in instance dict → bound method. + var_source = None + if can_use_mro_source: + var_source = self.get_source_by_walking_mro(tx, name) + return variables.UserMethodVariable( + type_attr, self, source_fn=var_source, source=source + ) + # Check for a Python-level __get__ (non-data descriptor with traceable __get__). + get_fn = inspect.getattr_static(type(type_attr), "__get__", None) + if isinstance(get_fn, types.FunctionType): + return self.invoke_descriptor_get(tx, name, type_attr, source) + + # TODO(tp_descr_get) - Investigate if we need a separate descriptor + # VT for instancemethod and cython functions. + if ( + torch._C._dynamo.utils.is_instancemethod(type_attr) # type: ignore[attr-defined] + or is_cython_function(type_attr) + ): + return variables.GetAttrVariable(self, name, type(type_attr), source=source) + + # Plain class variable (or MethodType, C-level non-data descriptor + # without __get__, etc.). + if can_use_mro_source: + source = self.get_source_by_walking_mro(tx, name) + elif not source and self.cls_source is not None: + source = AttrSource(self.cls_source, name) + return VariableTracker.build(tx, type_attr, source) + + def invoke_descriptor_get( + self, + tx: "InstructionTranslatorBase", + name: str, + descriptor: object, + source: Source | None, + ) -> VariableTracker: + """Trace a descriptor's __get__(instance, owner) call.""" + descriptor_source = None + descriptor_get_source = None + if self.cls_source: + descriptor_source = self.get_source_by_walking_mro(tx, name) + descriptor_get_source = AttrSource(TypeSource(descriptor_source), "__get__") + descriptor_var = VariableTracker.build(tx, descriptor, descriptor_source) + else: + descriptor_var = UserDefinedObjectVariable(descriptor) + + owner_var = UserDefinedClassVariable(type(self.value)) + return variables.UserMethodVariable( + descriptor.__get__.__func__, # type: ignore[union-attr] + descriptor_var, + source=descriptor_get_source, + ).call_function(tx, [self, owner_var], {}) + + def lookup_instance_dict( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker | None: + source: Source | None = AttrSource(self.source, name) if self.source else None + + if tx.output.side_effects.has_pending_mutation_of_attr( + self, + name, + (AttrMutationKind.INSTANCE_DICT, AttrMutationKind.GENERIC_SETATTR), + ): + result = tx.output.side_effects.load_attr(self, name, deleted_ok=True) + if not isinstance(result, variables.DeletedVariable): + return result + return None + + if tx.output.side_effects.has_pending_mutation_of_attr( + self, "__dict__", AttrMutationKind.GENERIC_SETATTR + ): + dict_vt = self.get_dict_vt(tx) + if dict_vt.contains(name): + return dict_vt.getitem(name) + return None + + if hasattr(self.value, "__dict__") and name in self.value.__dict__: + subobj = self.value.__dict__[name] + source = self.maybe_wrap_nn_module_source_for_instance(tx, name, source) + return VariableTracker.build(tx, subobj, source) + + return None + + def call_getattr_fallback( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker | None: + getattr_fn = self._check_for_getattr() + if isinstance(getattr_fn, types.FunctionType): + if ( + getattr_fn is unpatched_nn_module_getattr + and isinstance(self, variables.UnspecializedNNModuleVariable) + and istype(self.value._parameters, dict) # type: ignore[attr-defined] + and istype(self.value._buffers, dict) # type: ignore[attr-defined] + and istype(self.value._modules, dict) # type: ignore[attr-defined] + ): + out = self.manually_trace_nn_module_getattr(tx, name) + else: + new_source = None + if self.source: + new_source = AttrSource(self.source, "__getattr__") + out = variables.UserMethodVariable( + getattr_fn, self, source=new_source + ).call_function(tx, [variables.ConstantVariable.create(name)], {}) + + if self.source and getattr_fn is torch.nn.Module.__getattr__: + if isinstance( + out, + ( + variables.UnspecializedNNModuleVariable, + variables.NNModuleVariable, + ), + ): + out.set_nn_module_stack_source( # type: ignore[attr-defined] + AttrSource(self.get_nn_module_stack_source(), name) # type: ignore[attr-defined] + ) + return out + + elif getattr_fn is not None: + unimplemented( + gb_type="User-defined object with non-function __getattr__", + context=f"object={self.value}, name={name}, getattr_fn={getattr_fn}", + explanation=f"Found a non-function __getattr__ {getattr_fn} from a user-defined object {self.value} " + f" when attempting to getattr `{name}`", + hints=[ + "Ensure the object's __getattr__ is a function type.", + ], + ) + + return None + + def maybe_wrap_nn_module_source_for_instance( + self, + tx: "InstructionTranslatorBase", + name: str, + source: Source | None, + ) -> Source | None: + """Wrap source for nn.Module instance dict attribute access if needed.""" + if ( + source + and isinstance(self, variables.UnspecializedNNModuleVariable) + and (not tx.output.export or torch._dynamo.config.install_free_tensors) + ): + if name in ("_buffers", "_parameters"): + if self.source is None: + raise AssertionError( + "source must not be None for _buffers/_parameters access" + ) + source = UnspecializedParamBufferSource(self.source, name) + source = self._wrap_source(source) + return source + + def call_obj_hasattr( + self, tx: "InstructionTranslatorBase", name: str + ) -> "ConstantVariable": + if self.source: + install_guard( + self.source.make_guard( + functools.partial(GuardBuilder.HASATTR, attr=name) + ) + ) + + if not self._object_has_getattribute: + type_attr = self.lookup_class_mro_attr(name) + if ( + (type_attr is NO_SUCH_SUBOBJ or not is_data_descriptor(type_attr)) + and hasattr(self.value, "__dict__") + and not tx.output.side_effects.has_pending_mutation_of_attr( + self, + name, + (AttrMutationKind.INSTANCE_DICT, AttrMutationKind.GENERIC_SETATTR), + ) + and not tx.output.side_effects.has_pending_mutation_of_attr( + self, "__dict__", AttrMutationKind.GENERIC_SETATTR + ) + and self.has_key_in_generic_dict(tx, name) + ): + return variables.ConstantVariable.create(True) + + try: + var_vt = self.tp_getattro_impl(tx, name) + return VariableTracker.build( + tx, not isinstance(var_vt, variables.DeletedVariable) + ) + except ObservedAttributeError: + handle_observed_exception(tx) + return variables.ConstantVariable.create(False) + + def is_hashable(self) -> bool: + # Mirrors the __hash__ is None check in hash_impl's MRO walk. + # Returns "Is this hashable in CPython?", not "can Dynamo trace the hash?". + # Unknown C hashes are hashable but graph-break in hash_impl. + return type(self.value).__hash__ is not None + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # Mirrors CPython's slot_tp_hash which looks up __hash__ via the MRO: + # https://github.com/python/cpython/blob/e76aa128fe/Objects/typeobject.c#L9521-L9565 + # __hash__ = None → PyObject_HashNotImplemented: + # https://github.com/python/cpython/blob/e76aa128fe/Objects/typeobject.c#L8066-L8085 + + obj_type = type(self.value) + + # Walk the MRO to find the class that defines __hash__. + for cls in obj_type.__mro__: + if "__hash__" not in cls.__dict__: + continue + type_hash = cls.__dict__["__hash__"] + if type_hash is None: + raise_type_error(tx, f"unhashable type: '{obj_type.__name__}'") + if cls is object: + # object.__hash__ — identity hash, handled below + break + if isinstance(type_hash, types.FunctionType): + # Python __hash__: trace into it via resolve_type_attr. + method_var = self.resolve_type_attr( + tx, "__hash__", type_hash, source=None + ) + result = method_var.call_function(tx, [], {}) + from .constant import FakeIdVariable + + if isinstance(result, FakeIdVariable): + return result.as_python_constant(), True + if isinstance(result, variables.SymNodeVariable): + return int(result.evaluate_expr()), False + # CPython's slot_tp_hash validates PyLong_Check(res): + # https://github.com/python/cpython/blob/e76aa128fe/Objects/typeobject.c#L9543-L9548 + try: + result_type = result.python_type() + except NotImplementedError: + result_type = None + if result_type is not None and not issubclass(result_type, int): + raise_observed_exception( + TypeError, + tx, + args=[ + f"__hash__ method should return an integer, " + f"not '{result_type.__name__}'" + ], + ) + if not result.is_python_constant(): + unimplemented( + gb_type="Non-constant __hash__ return", + context=f"hash_impl {self}", + explanation=f"__hash__ returned a non-constant " + f"{type(result).__name__}.", + hints=[ + "Ensure that your custom __hash__ function returns an integer.", + *graph_break_hints.USER_ERROR, + ], + ) + return result.as_python_constant(), False + try: + in_allowlist = type_hash in _safe_c_tp_hash_funcs() + except TypeError: + in_allowlist = False + if ( + cls.__module__ == "builtins" + or in_allowlist + or is_pybind11_enum_member(self.value) + ): + # C hash we know is safe to call at trace time. + break + unimplemented( + gb_type="Untraceable C tp_hash", + context=f"hash_impl {self}", + explanation=f"{cls.__name__} defines a C __hash__ that " + f"Dynamo cannot trace into.", + hints=[ + f"Use torch._dynamo.allow_c_slot({cls.__name__}) to " + f"register it as safe if its slots are pure and " + f"deterministic.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + if self._base_vt is not None: + return self._base_vt.hash_impl(tx) + # hash(self.value) calls the real tp_hash — handles both + # object.__hash__ (identity) and builtin-inherited C hashes + # (e.g. IntEnum inheriting int.__hash__). + return hash(self.value), False + + def tp_richcompare_impl( + self, tx: "InstructionTranslatorBase", other: VariableTracker, op: str + ) -> VariableTracker: + """MRO walk for tp_richcompare, analogous to slot_tp_richcompare. + + https://github.com/python/cpython/blob/3.13/Objects/typeobject.c#L9421-L9468 + """ + from .constant import ConstantVariable + from .object_protocol import object_richcompare + + obj_type = type(self.value) + + for cls in obj_type.__mro__: + if op not in cls.__dict__: + continue + + if cls is object: + break + + method = cls.__dict__[op] + + if isinstance(method, types.FunctionType): + resolved = self.resolve_type_attr(tx, op, method, source=None) + if resolved is not None: + # Disable nested graph breaks so that if the user's + # comparison method graph-breaks, it propagates to + # COMPARE_OP (which runs eagerly) instead of splitting + # mid-method. Once PR #179844 lands (which defaults + # allow_nested_graph_breaks=False on + # inline_user_function_return), this override becomes + # unnecessary. + from unittest.mock import patch + + with patch.object( + resolved, "should_allow_nested_graph_breaks", lambda: False + ): + return resolved.call_function(tx, [other], {}) + break + + # C comparison method. If _base_vt exists, it already implements + # this type's C-level comparison (e.g. ConstDictVariable for dict, + # SetVariable for set). Delegate to it instead of constant-folding + # or graph-breaking. + if self._base_vt is not None: + break + + in_allowlist = False + try: + in_allowlist = method in _safe_c_slots() + except TypeError: + pass + if ( + cls.__module__ == "builtins" + or in_allowlist + or is_pybind11_enum_member(self.value) + ): + other_val = other.get_real_python_backed_value() + if other_val is not NO_SUCH_SUBOBJ: + try: + result = method(self.value, other_val) + return ConstantVariable.create(result) + except Exception: + pass + return ConstantVariable.create(NotImplemented) + unimplemented( + gb_type="Untraceable C tp_richcompare", + context=f"tp_richcompare_impl {self} {op}", + explanation=f"{cls.__name__} defines a C comparison method " + f"that Dynamo cannot trace into.", + hints=[ + f"Use torch._dynamo.allow_c_slot({cls.__name__}) to " + f"register it as safe if its comparison methods are pure " + f"and deterministic.", + *graph_break_hints.SUPPORTABLE, + ], + ) + + if self._base_vt is not None: + return self._base_vt.tp_richcompare_impl(tx, other, op) + + return object_richcompare(self, tx, other, op) + + def call_tree_map_branch( + self, + tx: "InstructionTranslatorBase", + tree_map_fn: "variables.functions.UserFunctionVariable", + map_fn: "VariableTracker", + rest: "list[VariableTracker]", + tree_map_kwargs: "dict[str, VariableTracker]", + ) -> "VariableTracker": + """Emulate tree_map behavior for user-defined objects. + + In pytree, a type is a leaf if it is NOT in SUPPORTED_NODES. + User-defined objects (that are not registered with register_pytree_node) + are always treated as leaves. This works for both torch.utils._pytree + and optree implementations. + """ + # Determine which tree_map implementation is being used + tree_map_module = getattr(getattr(tree_map_fn, "fn", None), "__module__", "") + is_optree = tree_map_module.startswith("optree") + + if is_optree: + # Check optree's registry - need to handle namespaces + # In optree, types can be registered globally (type in registry) + # or with a namespace ((namespace, type) in registry) + try: + import optree + from optree.registry import _NODETYPE_REGISTRY + + # Check if registered globally + # Namedtuples and structseqs are implicitly pytree nodes + is_registered = ( + self.value_type in _NODETYPE_REGISTRY + or optree.is_namedtuple_class(self.value_type) + or optree.is_structseq_class(self.value_type) + ) + + # Also check if registered with a namespace that's being used + if not is_registered: + namespace_var = tree_map_kwargs.get("namespace") + if namespace_var is not None: + try: + namespace = namespace_var.as_python_constant() + # Check for namespaced registration + is_registered = ( + namespace, + self.value_type, + ) in _NODETYPE_REGISTRY + except NotImplementedError: + # Can't determine namespace at compile time, fall back + return self._tree_map_fallback( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + ) + except ImportError: + # Can't import optree registry, fall back to tracing + import logging + + log = logging.getLogger(__name__) + log.warning( + "Failed to import optree.registry._NODETYPE_REGISTRY, " + "falling back to tracing for tree_map" + ) + return self._tree_map_fallback( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + ) + else: + # Check pytorch's pytree registry + import torch.utils._pytree as pytree + + # Namedtuples and structseqs are implicitly pytree nodes + is_registered = ( + self.value_type in pytree.SUPPORTED_NODES + or pytree.is_namedtuple_class(self.value_type) + or pytree.is_structseq_class(self.value_type) + ) + + # If not registered, it's a leaf and we should apply the map_fn directly + if not is_registered: + return map_fn.call_function(tx, [self, *rest], {}) + + # The type is registered in pytree - we need to fall back to tracing + # the actual tree_map implementation since we don't have the flattening + # logic implemented here + return self._tree_map_fallback( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + ) + + def call_tree_map_with_path_branch( + self, + tx: "InstructionTranslatorBase", + tree_map_fn: "variables.functions.UserFunctionVariable", + map_fn: "VariableTracker", + rest: "list[VariableTracker]", + tree_map_kwargs: "dict[str, VariableTracker]", + keypath: "tuple[Any, ...]", + ) -> "VariableTracker": + """Emulate tree_map_with_path behavior for user-defined objects. + + Same logic as call_tree_map_branch but passes keypath to the map function. + """ + tree_map_module = tree_map_fn.get_module() + is_optree = tree_map_module.startswith("optree") + + if is_optree: + try: + import optree + from optree.registry import _NODETYPE_REGISTRY + + is_registered = ( + self.value_type in _NODETYPE_REGISTRY + or optree.is_namedtuple_class(self.value_type) + or optree.is_structseq_class(self.value_type) + ) + + if not is_registered: + namespace_var = tree_map_kwargs.get("namespace") + if namespace_var is not None: + try: + namespace = namespace_var.as_python_constant() + is_registered = ( + namespace, + self.value_type, + ) in _NODETYPE_REGISTRY + except NotImplementedError: + return self._tree_map_with_path_fallback( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + keypath, + ) + except ImportError: + return self._tree_map_with_path_fallback( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + keypath, + ) + else: + import torch.utils._pytree as pytree + + is_registered = ( + self.value_type in pytree.SUPPORTED_NODES + or pytree.is_namedtuple_class(self.value_type) + or pytree.is_structseq_class(self.value_type) + ) + + if not is_registered: + keypath_var = variables.TupleVariable( + [VariableTracker.build(tx, k) for k in keypath] + ) + return map_fn.call_function(tx, [keypath_var, self, *rest], {}) + + return self._tree_map_with_path_fallback( + tx, + tree_map_fn, + map_fn, + rest, + tree_map_kwargs, + keypath, + ) + + +class FrozenDataClassVariable(UserDefinedObjectVariable): + """Frozen dataclass variable for as_proxy/as_python_constant/hashability. + + Construction is handled by the generic polyfill path (tracing through + the auto-generated __init__). Field values are retrieved dynamically + via tp_getattro_impl using InstructionTranslator.current_tx(). + """ + + def _get_field_vt(self, field_name: str) -> VariableTracker: + from torch._dynamo.symbolic_convert import InstructionTranslator + + tx = InstructionTranslator.current_tx() + return self.tp_getattro_impl(tx, field_name) + + def as_python_constant(self) -> object: + from dataclasses import fields + + import torch.utils._pytree as pytree + + if not istype( + self.value, (pytree.TreeSpec, pytree.LeafSpec, pytree.ConstantNode) + ): + raise NotImplementedError( + "currently can't reconstruct arbitrary frozen dataclass instances" + ) + + if istype(self.value, pytree.LeafSpec): + return pytree.treespec_leaf() + + args: list[object] = [] + kwargs: dict[str, object] = {} + for field in fields(self.value): # type: ignore[arg-type] + if field.init: + data = self._get_field_vt(field.name).as_python_constant() + if getattr(field, "kw_only", False): + kwargs[field.name] = data + else: + args.append(data) + + return self.python_type()(*args, **kwargs) + + def as_proxy(self) -> object: + from dataclasses import fields + + args: list[object] = [] + kwargs: dict[str, object] = {} + for field in fields(self.value): # type: ignore[arg-type] + proxy = self._get_field_vt(field.name).as_proxy() + if hasattr(field, "kw_only") and field.kw_only: + kwargs[field.name] = proxy + else: + args.append(proxy) + + return self.python_type()(*args, **kwargs) + + def reconstruct(self, codegen: "PyCodegen") -> None: + if self.source is not None: + codegen(self.source) + return + codegen.append_output( + codegen.create_load_const_unchecked(self.as_python_constant()) + ) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.value_type.__name__})" + + def hash_impl(self, tx: "InstructionTranslatorBase") -> tuple[int, bool]: + # The fast path below replicates CPython's *generated* frozen dataclass + # __hash__ (hash(tuple(field_values))). A frozen dataclass may instead + # define a custom __hash__ (e.g. the PyTreeSpec polyfill); dataclasses + # synthesizes the generated one via exec (co_filename ""), so a + # __hash__ from a real source file is custom -- defer to the general + # MRO-walking hash_impl, which traces it. + type_hash = type(self.value).__hash__ + if ( + isinstance(type_hash, types.FunctionType) + and type_hash.__code__.co_filename != "" + ): + return super().hash_impl(tx) + + # CPython's frozen dataclass __hash__ is generated by _hash_add: + # https://github.com/python/cpython/blob/e76aa128fe/Lib/dataclasses.py#L886-L892 + # It computes hash(tuple(field_values)), i.e. tuplehash applied to + # field values. Use RawHash to bypass int.__hash__'s modular reduction. + from dataclasses import fields as dc_fields + + from .hashable import RawHash + from .object_protocol import generic_hash_impl + + is_fake = False + raw_hashes = [] + for f in dc_fields(self.value): # type: ignore[arg-type] + h, fake = generic_hash_impl(tx, self._get_field_vt(f.name)) + is_fake = is_fake or fake + raw_hashes.append(RawHash(h)) + return hash(tuple(raw_hashes)), is_fake + + +class SourcelessGraphModuleVariable(UserDefinedObjectVariable): + def __init__( + self, + value: object, + **kwargs: Any, + ) -> None: + super().__init__(value, **kwargs) + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + fn_variable = VariableTracker.build(tx, self.value.forward.__func__) # type: ignore[attr-defined] + args = [self] + args + return tx.inline_user_function_return( + fn_variable, + args, + kwargs, + ) + + +class UserDefinedExceptionObjectVariable(UserDefinedObjectVariable): + def __init__(self, value: object, **kwargs: Any) -> None: + super().__init__(value, **kwargs) + init_args = kwargs.get("init_args", []) + self._base_vt = variables.ExceptionVariable(self.value_type, init_args) + self._base_methods = ( + base_exception_methods + if isinstance(value, BaseException) + else exception_methods + ) + + @property + def fn(self) -> Callable[..., object]: + return self.value_type + + @property + def exc_vt(self) -> "variables.ExceptionVariable": + if self._base_vt is None: + raise AssertionError("_base_vt must not be None for exception repr") + return cast(variables.ExceptionVariable, self._base_vt) + + def _with_traceback( + self, tx: "InstructionTranslatorBase", args: list[VariableTracker], kwargs + ) -> "VariableTracker": + return self._base_vt.call_method(tx, "with_traceback", args, kwargs) # type: ignore[missing-attribute] + + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # __setattr__ is the tp_setattro slot, not dispatched through tp_methods, + # so handle it here (mirroring ExceptionVariable.call_method) to route + # writes of __cause__/__context__/__suppress_context__/__traceback__ to + # the wrapped base exception VT. Without this, `raise X from Y` never + # records X.__cause__ (issue: contextlib exception-chaining repro). + if ( + name == "__setattr__" + and len(args) == 2 + and args[0].is_constant_match( + "__cause__", "__context__", "__suppress_context__", "__traceback__" + ) + ): + return self._base_vt.call_method(tx, "__setattr__", args, kwargs) # type: ignore[missing-attribute] + return super().call_method(tx, name, args, kwargs) + + def tp_init_impl( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Inherited C exception __init__ (BaseException.__init__, a method + # descriptor) is a no-op here; args are captured via __new__. Mirrors + # call_method's __init__ handling. + method = self._maybe_get_baseclass_method("__init__") + if method and inspect.ismethoddescriptor(method) and len(kwargs) == 0: + return variables.ConstantVariable.create(None) + return super().tp_init_impl(tx, args, kwargs) + + tp_methods = { + "with_traceback": Method(_with_traceback), + } + + # BaseException args/__cause__/__context__/__suppress_context__/__traceback__ + # are members/getsets; delegate each to the wrapped base exception VT. + tp_members = { + "args": Member(lambda s, tx: s._base_vt.tp_getattro_impl(tx, "args")), + "__cause__": Member(lambda s, tx: s._base_vt.tp_getattro_impl(tx, "__cause__")), + "__context__": Member( + lambda s, tx: s._base_vt.tp_getattro_impl(tx, "__context__") + ), + "__suppress_context__": Member( + lambda s, tx: s._base_vt.tp_getattro_impl(tx, "__suppress_context__") + ), + "__traceback__": Member( + lambda s, tx: s._base_vt.tp_getattro_impl(tx, "__traceback__") + ), + } + + @property + def __context__(self) -> "ConstantVariable": + return self._base_vt.__context__ # type: ignore[missing-attribute] + + @property + def args(self) -> list[VariableTracker]: + return self._base_vt.args # type: ignore[missing-attribute] + + def set_context(self, context: "variables.ExceptionVariable") -> None: + return self._base_vt.set_context(context) # type: ignore[missing-attribute] + + @property + def exc_type(self) -> type[BaseException]: + return self._base_vt.exc_type # type: ignore[missing-attribute] + + @property + def python_stack(self) -> traceback.StackSummary | None: + return self._base_vt.python_stack # type: ignore[missing-attribute] + + def debug_repr(self) -> str: + return self.exc_vt.debug_repr() + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + # ref: BaseException_repr in https://github.com/python/cpython/blob/3.13/Objects/exceptions.c#L135-L142 + if type(self.value).__repr__ is not BaseException.__repr__: + return super().tp_repr_impl(tx) + return self.exc_vt.tp_repr_impl(tx) + + def tp_str_impl(self, tx: "InstructionTranslatorBase") -> "VariableTracker": + # ref: BaseException_str in https://github.com/python/cpython/blob/3.13/Objects/exceptions.c#L118-L129 + if type(self.value).__str__ is not BaseException.__str__: + return super().tp_str_impl(tx) + return self.exc_vt.tp_str_impl(tx) + + @python_stack.setter + def python_stack(self, value: traceback.StackSummary) -> None: + self._base_vt.python_stack = value # type: ignore[missing-attribute] + + +class InspectVariable(UserDefinedObjectVariable): + """Handles inspect.Signature and inspect.Parameter objects. + + Short-circuits property accesses to avoid tracing property getters, + redirecting them to the underlying private attributes directly. + """ + + _PROPERTY_REDIRECTS: dict[type, dict[str, str]] = { + inspect.Signature: {"parameters": "_parameters"}, + inspect.Parameter: {"kind": "_kind", "name": "_name"}, + } + + @staticmethod + def is_matching_object(obj: object) -> bool: + return type(obj) in InspectVariable._PROPERTY_REDIRECTS + + @staticmethod + def is_matching_class(obj: object) -> bool: + return obj in InspectVariable._PROPERTY_REDIRECTS + + def _redirect( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker | None: + redirects = self._PROPERTY_REDIRECTS.get(type(self.value), {}) + if name in redirects: + return super().tp_getattro_impl(tx, redirects[name]) + return None + + def _parameters(self, tx: "InstructionTranslatorBase") -> VariableTracker | None: + return self._redirect(tx, "parameters") + + def _kind(self, tx: "InstructionTranslatorBase") -> VariableTracker | None: + return self._redirect(tx, "kind") + + def _name(self, tx: "InstructionTranslatorBase") -> VariableTracker | None: + return self._redirect(tx, "name") + + # inspect.Signature.parameters and inspect.Parameter.name/.kind are Python + # `property` objects (getset-like). Redirect to the private backing slots to + # avoid tracing the property getters. The redirect is per-type, so a getter + # declines (returns None) when the attribute doesn't apply to self.value. + tp_getset = { + "parameters": GetSet(_parameters, None), + "kind": GetSet(_kind, None), + "name": GetSet(_name, None), + } + + +class KeyedJaggedTensorVariable(UserDefinedObjectVariable): + @staticmethod + def is_matching_object(obj: object) -> bool: + mod = sys.modules.get("torchrec.sparse.jagged_tensor") + return mod is not None and type(obj) is mod.KeyedJaggedTensor + + def __init__(self, value: object, **kwargs: Any) -> None: + from torchrec.sparse.jagged_tensor import ( # type: ignore[import-not-found] + KeyedJaggedTensor, + ) + + if type(value) is not KeyedJaggedTensor: + raise AssertionError(f"Expected KeyedJaggedTensor, got {type(value)}") + super().__init__(value, **kwargs) + + def tp_getattro_impl( + self, tx: "InstructionTranslatorBase", name: str + ) -> VariableTracker: + if ( + torch._dynamo.config.force_unspec_int_unbacked_size_like_on_torchrec_kjt + and self.source is not None + and name in ("_length_per_key", "_offset_per_key") + ): + with TracingContext.patch(force_unspec_int_unbacked_size_like=True): + return super().tp_getattro_impl(tx, name) + return super().tp_getattro_impl(tx, name) + + +_CONSTANT_BASE_TYPES = (int, float, str) + +_constant_base_methods: dict[type, set[Any]] = { + t: {m for m in t.__dict__.values() if callable(m)} for t in _CONSTANT_BASE_TYPES +} + + +class UserDefinedConstantVariable(UserDefinedObjectVariable): + """ + Represents user-defined objects that subclass immutable constant types + (int, float, str). + + Uses a ConstantVariable as _base_vt for the underlying constant value. + """ + + def __init__(self, value: Any, **kwargs: Any) -> None: + from .constant import ConstantVariable + + super().__init__(value, **kwargs) + for base in type(value).__mro__: + if base in _CONSTANT_BASE_TYPES: + self._base_vt = ConstantVariable.create(base(value)) + self._base_methods = _constant_base_methods[base] + break + if self._base_vt is None: + raise AssertionError(f"No constant base type found in MRO of {type(value)}") + + def as_python_constant(self) -> Any: + return self.value + + def as_proxy(self) -> object: + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in as_proxy") + return self._base_vt.as_proxy() + + +class IntWrapperVariable(UserDefinedObjectVariable): + # Dummy class to check if the object is an IntWrapper, and turn it into a + # symint + @staticmethod + def is_matching_object(obj: object) -> bool: + mod = sys.modules.get("torch.export.dynamic_shapes") + return mod is not None and type(obj) is mod._IntWrapper + + +class RemovableHandleVariable(VariableTracker): + REMOVED = -1 + + def __init__( + self, + mutation_type: MutationType | None = None, + # index of the registration in the side_effects owned register_hook/handle list, used during removal. + idx: int | None = None, + **kwargs: Any, + ) -> None: + super().__init__(**kwargs) + self.mutation_type = mutation_type + self.idx = idx + + def remove( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + if self.idx != self.REMOVED: + if self.idx is None: + raise AssertionError("idx must not be None for hook removal") + tx.output.side_effects.remove_hook(self.idx) + self.idx = self.REMOVED + return variables.ConstantVariable.create(None) + + tp_methods = {"remove": Method(remove)} + + def reconstruct(self, codegen: "PyCodegen") -> None: + if self.idx == self.REMOVED: + # Hook has already been removed, return a dummy handle + codegen.add_push_null( + lambda: codegen.load_import_from( + "torch._dynamo.utils", "invalid_removeable_handle" + ) + ) + codegen.extend_output(create_call_function(0, False)) + return + # unreachable due to codegen.add_cache() when the hook is installed + super().reconstruct(codegen) + + def python_type(self) -> type[object]: + return RemovableHandleClass + + +class UserDefinedDictVariable(UserDefinedObjectVariable): + """ + Represents user defined objects that are subclasses of dict/OrderedDict. + + Internally, it uses a ConstDictVariable to represent the dict part of the + variable tracker. For everything else, it falls back to + UserDefinedObjectVariable. + """ + + def __init__( + self, + value: object, + dict_vt: ConstDictVariable | None = None, + **kwargs: Any, + ) -> None: + super().__init__(value, **kwargs) + if dict_vt is None: + if self.source is not None: + raise AssertionError( + "dict_vt must be constructed by builder.py when source is present" + ) + # OrderedDict subclasses need an OrderedDict-backed store so + # move_to_end / popitem(last=) delegate correctly. + base_cls = ( + OrderedDictVariable + if isinstance(value, collections.OrderedDict) + else ConstDictVariable + ) + self._base_vt = base_cls( + {}, + mutation_type=ValueMutationNew(), + ) + else: + self._base_vt = dict_vt + self._base_methods = dict_methods + if self._base_vt is None: + raise AssertionError("_base_vt must not be None after initialization") + + def len(self) -> int: + # Used by nn_module.py to short-circuit the nn.Module forward method + # when no hooks are registered. Calling .len() directly avoids the + # overhead of full call_method("__len__") dispatch during tracing. + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in len") + return self._base_vt.len() # type: ignore[union-attr] + + def sq_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # Dict implements __len__ via mp_length (mapping protocol), not + # sq_length (sequence protocol). Redirect so generic_size works. + return self.mp_length_impl(tx) + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: VariableTracker, + ) -> VariableTracker: + # dict_subscript: https://github.com/python/cpython/blob/62a6e898e01/Objects/dictobject.c#L3673-L3706 + # TODO(follow-up): add test for unhashable/invalid key type, Counter missing key + method = self._maybe_get_baseclass_method("__getitem__") + if method in self._base_methods: + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in mp_subscript_impl") + try: + return self._base_vt.mp_subscript_impl(tx, key) + except ObservedKeyError: + if issubclass( + self.python_type(), dict + ) and self._maybe_get_baseclass_method("__missing__"): + return self.call_method(tx, "__missing__", [key], {}) + else: + raise + return super().mp_subscript_impl(tx, key) + + def tp_init_impl( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # Inherited dict/OrderedDict __init__ populates the underlying storage + # (CPython dict_init == dict.update); route to _base_vt so content is + # not lost. defaultdict.__init__'s first arg is the default_factory and + # has its own path. Mirrors call_method's __init__ handling. + if self._maybe_get_baseclass_method("__init__") in ( + dict.__init__, + collections.OrderedDict.__init__, + ): + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in tp_init_impl") + self._base_vt.call_method(tx, "update", args, kwargs) + return variables.ConstantVariable.create(None) + return super().tp_init_impl(tx, args, kwargs) + + def debug_repr(self) -> str: + if self._base_vt is None: + raise AssertionError("_base_vt must not be None for dict repr") + base_vt = cast(ConstDictVariable, self._base_vt) + if type(self.value).__repr__ is collections.Counter.__repr__: + items = list(base_vt.items.items()) + try: + items = sorted( + items, + key=lambda item: item[1].as_python_constant(), + reverse=True, + ) + except (NotImplementedError, TypeError): + pass + if not items: + return f"{type(self.value).__name__}()" + contents = ", ".join( + f"{key.vt.debug_repr()}: {value.debug_repr()}" for key, value in items + ) + return f"{type(self.value).__name__}({{{contents}}})" + return base_vt.debug_repr() + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # https://github.com/python/cpython/blob/3.13/Lib/collections/__init__.py#L748-L757 + method = self._maybe_get_baseclass_method("__repr__") + if type(self.value).__repr__ is collections.Counter.__repr__: + if self._base_vt is None: + raise AssertionError("_base_vt must not be None for Counter repr") + base_vt = cast(ConstDictVariable, self._base_vt) + items = list(base_vt.items.items()) + try: + items = sorted( + items, + key=lambda item: item[1].as_python_constant(), + reverse=True, + ) + except (NotImplementedError, TypeError): + pass + if not items: + return VariableTracker.build(tx, f"{type(self.value).__name__}()") + contents = ", ".join( + f"{tracked_repr(tx, key.vt)}: {tracked_repr(tx, value)}" + for key, value in items + ) + return VariableTracker.build( + tx, f"{type(self.value).__name__}({{{contents}}})" + ) + if method in self._base_methods: + if self._base_vt is None: + raise AssertionError("_base_vt must not be None for dict repr") + return self._base_vt.tp_repr_impl(tx) + return super().tp_repr_impl(tx) + + +# TODO: move to dicts.py alongside ConstDictVariable. +# Currently blocked by circular imports (dicts.py ↔ user_defined.py). +class DefaultDictVariable(UserDefinedDictVariable): + """ + Represents collections.defaultdict instances. + + CPython's defaultdict is implemented in C: + https://github.com/python/cpython/blob/v3.13.3/Modules/_collectionsmodule.c#L2177-L2180 + + default_factory is a field on the C struct (defdictobject.default_factory), + not a Python instance attribute, so we model it as a field on the VT. + + Dict storage is delegated to _base_vt (a ConstDictVariable) via + UserDefinedDictVariable. + """ + + _cpython_type = collections.defaultdict + + def __init__( + self, + value: object, + default_factory: VariableTracker | None = None, + dict_vt: ConstDictVariable | None = None, + **kwargs: Any, + ) -> None: + if dict_vt is None: + from .dicts import ConstDictVariable + + dict_vt = ConstDictVariable( + {}, + mutation_type=ValueMutationNew(), + ) + super().__init__(value, dict_vt=dict_vt, **kwargs) + if default_factory is None: + from .constant import ConstantVariable + + default_factory = ConstantVariable.create(None) + self.default_factory = default_factory + + @staticmethod + def is_supported_factory(arg: VariableTracker) -> bool: + """Check if arg is a valid default_factory (callable or None). + + CPython's defaultdict.__init__ checks ``callable(factory)`` and + raises TypeError if not. We mirror this by checking the + underlying Python value when possible. + """ + val = arg.get_real_python_backed_value() + if val is not NO_SUCH_SUBOBJ: + return val is None or callable(val) + # Callables (functions, builtins, classes) are supported + return isinstance( + arg, + ( + variables.BaseBuiltinVariable, + variables.functions.BaseUserFunctionVariable, + variables.functions.PolyfilledFunctionVariable, + variables.UserDefinedClassVariable, + ), + ) + + def is_python_constant(self) -> bool: + if self._base_vt is None: + raise AssertionError("_base_vt must not be None for defaultdict const") + if not self.default_factory.is_python_constant(): + return False + return self._base_vt.is_python_constant() + + def as_python_constant(self) -> Any: + if self._base_vt is None: + raise AssertionError("_base_vt must not be None for defaultdict const") + if not self.default_factory.is_python_constant(): + raise AsPythonConstantNotImplementedError( + self, + "defaultdict default_factory is not a Python constant", + ) + factory = self.default_factory.as_python_constant() + return collections.defaultdict(factory, self._base_vt.as_python_constant()) + + def debug_repr(self) -> str: + if self.default_factory is None: + raise AssertionError("default_factory must not be None in debug_repr") + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in debug_repr") + return ( + f"defaultdict({self.default_factory.debug_repr()}, " + f"{self._base_vt.debug_repr()})" + ) + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + # https://github.com/python/cpython/blob/3.13/Modules/_collectionsmodule.c#L2373-L2405 + if self._base_vt is None: + raise AssertionError("_base_vt must not be None for defaultdict repr") + return VariableTracker.build( + tx, + f"{self.python_type_name()}({tracked_repr(tx, self.default_factory)}, " + f"{tracked_repr(tx, self._base_vt)})", + ) + + # ref: defdict_members[] in CPython Modules/_collectionsmodule.c + # {"default_factory", T_OBJECT, offsetof(defdictobject, default_factory)} + tp_members = { + "default_factory": Member(getset_read(lambda s: s.default_factory)), + } + + def _missing_impl( + self, + tx: "InstructionTranslatorBase", + key: "VariableTracker", + ) -> "VariableTracker": + """defaultdict.__missing__: auto-vivification via default_factory. + + https://github.com/python/cpython/blob/v3.13.3/Modules/_collectionsmodule.c#L2233-L2254 + """ + from .constant import ConstantVariable + + if ( + istype(self.default_factory, ConstantVariable) + and self.default_factory.value is None + ): + raise_observed_exception(KeyError, tx, args=[key]) + default_var = self.default_factory.call_function(tx, [], {}) + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in _missing_impl") + self._base_vt.call_method(tx, "__setitem__", [key, default_var], {}) + return default_var + + def mp_subscript_impl( + self, + tx: "InstructionTranslatorBase", + key: "VariableTracker", + ) -> "VariableTracker": + """defaultdict.__getitem__: dict lookup with __missing__ fallback.""" + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in mp_subscript_impl") + if key in self._base_vt: # type: ignore[operator] + return self._base_vt.getitem_const(tx, key) # type: ignore[union-attr] + return self._missing_impl(tx, key) + + def nb_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + reverse: bool = False, + ) -> VariableTracker: + # ref: https://github.com/python/cpython/blob/v3.13.0/Modules/_collectionsmodule.c#L2356-L2395 + # The C impl uses a naming convention of left/right for the two operands + # and swap self/other depending on some conditions. For simplicity, we + # will suffix the var names with "_" + + # new_defdict(self, left) calls type(self)(self.default_factory, left), + # then PyDict_Update(new, right). left/right are the original operands. + left, right = (other, self) if reverse else (self, other) + ret = issubclass(left.python_type(), collections.defaultdict) + self_, other_ = (left, right) if ret else (right, left) + if not isinstance(self_, DefaultDictVariable): + raise AssertionError(f"Expected DefaultDictVariable, got {type(self_)}") + + if not pydict_check(other_): + return variables.ConstantVariable.create(NotImplemented) + + if isinstance(left, ConstDictVariable): + items = left.items + else: + if not isinstance(left, UserDefinedDictVariable): + raise AssertionError( + f"Expected UserDefinedDictVariable, got {type(left)}: {left}" + ) + items = left._base_vt.items # type: ignore[missing-attribute] + + new = tx.output.side_effects.track_new_user_defined_object( + VariableTracker.build(tx, dict), + VariableTracker.build(tx, collections.defaultdict), + [], + tx=tx, + ) + new.default_factory = self.default_factory # type: ignore[missing-attribute] + new._base_vt = ConstDictVariable(items.copy(), mutation_type=ValueMutationNew()) # type: ignore[missing-attribute] + default_factory = new.default_factory # type: ignore[missing-attribute] + tx.output.side_effects.store_attr(new, "default_factory", default_factory) + new.call_method(tx, "update", [right], {}) + return new + + def nb_inplace_or_impl( + self, + tx: "InstructionTranslatorBase", + other: VariableTracker, + ) -> VariableTracker: + self.call_method(tx, "update", [other], {}) + return self + + def tp_init_impl( + self, + tx: "InstructionTranslatorBase", + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + # defaultdict.__init__(self, default_factory=None, *args, **kwargs) + # https://github.com/python/cpython/blob/v3.13.3/Modules/_collectionsmodule.c#L2072 + # Extract default_factory, delegate rest to dict.__init__ + if len(args) >= 1: + if self.is_supported_factory(args[0]): + self.default_factory = args[0] + tx.output.side_effects.store_attr( + self, + "default_factory", + self.default_factory, + ) + args = list(args[1:]) + else: + # CPython raises TypeError for non-callable first arg + raise_observed_exception( + TypeError, + tx, + args=["first argument must be callable or None"], + ) + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in __init__") + return self._base_vt.call_method(tx, "__init__", args, kwargs) + + def _getitem( + self, tx: "InstructionTranslatorBase", args: list[VariableTracker], kwargs + ) -> "VariableTracker": + if len(args) != 1: + raise_args_mismatch(tx, "__getitem__", "1 args", f"{len(args)} args") + return self.mp_subscript_impl(tx, args[0]) + + def _missing( + self, tx: "InstructionTranslatorBase", args: list[VariableTracker], kwargs + ) -> "VariableTracker": + if len(args) != 1: + raise_args_mismatch(tx, "__missing__", "1 args", f"{len(args)} args") + return self._missing_impl(tx, args[0]) + + def _copy( + self, tx: "InstructionTranslatorBase", args: list[VariableTracker], kwargs + ) -> "VariableTracker": + # defaultdict.copy() / copy.copy(dd) both create a new defaultdict + # https://github.com/python/cpython/blob/6280bb547840b609feedb78887c6491af75548e8/Modules/_collectionsmodule.c#L2290-L2293 + from .builder import SourcelessBuilder + + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in copy") + new_dd = tx.output.side_effects.track_new_user_defined_object( + SourcelessBuilder.create(tx, dict), + SourcelessBuilder.create(tx, collections.defaultdict), + [], + tx=tx, + ) + if not isinstance(new_dd, DefaultDictVariable): + raise AssertionError(f"Expected DefaultDictVariable, got {type(new_dd)}") + new_dd.default_factory = self.default_factory + new_dd._base_vt = self._base_vt.clone( + mutation_type=ValueMutationNew(), + source=None, + ) + tx.output.side_effects.store_attr( + new_dd, "default_factory", new_dd.default_factory + ) + return new_dd + + # __ior__ and __setattr__ are C-level slots (nb_inplace_or, tp_setattro), + # so they are handled in call_method rather than declared in tp_methods. + def call_method( + self, + tx: "InstructionTranslatorBase", + name: str, + args: list[VariableTracker], + kwargs: dict[str, VariableTracker], + ) -> VariableTracker: + from .constant import ConstantVariable + + if name == "__setattr__": + if len(args) != 2: + raise_args_mismatch(tx, name, "2 args", f"{len(args)} args") + if ( + istype(args[0], ConstantVariable) and args[0].value == "default_factory" + ) and self.is_supported_factory(args[1]): + self.default_factory = args[1] + tx.output.side_effects.store_attr( + self, "default_factory", self.default_factory + ) + return ConstantVariable.create(None) + return super().call_method(tx, name, args, kwargs) + + tp_methods = { + "__getitem__": Method(_getitem), + "__missing__": Method(_missing), + "copy": Method(_copy), + "__copy__": Method(_copy), + } + + +class UserDefinedSetVariable(UserDefinedObjectVariable): + """ + Represents user defined objects that are subclasses of set. + + Internally, it uses a SetVariable to represent the set part of the + variable tracker. For everything else, it falls back to + UserDefinedObjectVariable. + """ + + def __init__( + self, value: object, set_vt: SetVariable | None = None, **kwargs: Any + ) -> None: + from .builder import SourcelessBuilder + + tx = kwargs.pop("tx", None) + super().__init__(value, **kwargs) + + python_type = set if isinstance(value, set) else frozenset + self._base_methods = set_methods if python_type is set else frozenset_methods + + if set_vt is None: + if self.source is not None: + raise AssertionError( + "set_vt must be constructed by builder.py when source is present" + ) + if python_type is set: + # set is initialized later + self._base_vt = variables.SetVariable( + set(), + mutation_type=ValueMutationNew(), + ) + else: + init_args = kwargs.get("init_args", {}) + self._base_vt = SourcelessBuilder.create(tx, python_type).call_function( # type: ignore[assignment] + tx, init_args, {} + ) + else: + self._base_vt = set_vt + if self._base_vt is None: + raise AssertionError("_base_vt must not be None after initialization") + + def as_python_constant(self) -> object: + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in as_python_constant") + return self._base_vt.as_python_constant() + + @property + def set_items(self) -> set[Any]: + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in set_items") + return self._base_vt.set_items # pyrefly: ignore[missing-attribute] + + @property + def items(self) -> dict[HashableTracker, VariableTracker]: + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in items") + return self._base_vt.items # pyrefly: ignore[missing-attribute] + + +class UserDefinedListVariable(UserDefinedObjectVariable): + """ + Represents user defined objects that are subclasses of lists. + + Internally, it uses a ListVariable to represent the list part of the + variable tracker. For everything else, it falls back to + UserDefinedObjectVariable. + """ + + def __init__( + self, value: object, list_vt: Union["ListVariable", None] = None, **kwargs: Any + ) -> None: + from .lists import ListVariable + + super().__init__(value, **kwargs) + if list_vt is None: + if self.source is not None: + raise AssertionError( + "list_vt must be constructed by builder.py when source is present" + ) + self._base_vt = ListVariable([], mutation_type=ValueMutationNew()) + else: + self._base_vt = list_vt + self._base_methods = list_methods + if self._base_vt is None: + raise AssertionError("_base_vt must not be None after initialization") + + +class UserDefinedDequeVariable(UserDefinedObjectVariable): + """ + Represents user defined objects that are subclasses of collections.deque. + + Internally, it uses a DequeVariable to represent the deque part of the + variable tracker. For everything else, it falls back to + UserDefinedObjectVariable. + """ + + def __init__( + self, + value: object, + deque_vt: Union["variables.lists.DequeVariable", None] = None, + **kwargs: Any, + ) -> None: + from .lists import DequeVariable + + super().__init__(value, **kwargs) + if deque_vt is None: + if self.source is not None: + raise AssertionError( + "deque_vt must be constructed by builder.py when source is present" + ) + self._base_vt = DequeVariable([], mutation_type=ValueMutationNew()) + else: + self._base_vt = deque_vt + self._base_methods = deque_methods + if self._base_vt is None: + raise AssertionError("_base_vt must not be None after initialization") + + def _maxlen(self, tx: "InstructionTranslatorBase") -> VariableTracker | None: + # maxlen is a read-only getset on deque, not a method, so it is not + # covered by the _base_methods call_method delegation; route it to the + # DequeVariable which tracks maxlen on the base deque. + if self._base_vt is not None: + return self._base_vt.tp_getattro_impl(tx, "maxlen") + return None + + # ref: deque_getset[] in CPython Modules/_collectionsmodule.c; maxlen is a + # read-only getset (deque_get_maxlen, no setter). + tp_getset = { + "maxlen": GetSet(_maxlen, None), + } + + +class UserDefinedTupleVariable(UserDefinedObjectVariable): + """ + Represents user defined objects that are subclasses of tuple. + + Internally, it uses a TupleVariable to represent the tuple part of the + variable tracker. For everything else, it falls back to + UserDefinedObjectVariable. + + NamedTupleVariable and StructSequenceVariable are subclasses that handle + namedtuples and structseqs (torch.return_types.*) respectively. + """ + + _nonvar_fields = { + "tuple_cls", + *UserDefinedObjectVariable._nonvar_fields, + } + + @staticmethod + def get_vt_cls(cls: type) -> type["UserDefinedTupleVariable"]: + if is_structseq_class(cls): + return StructSequenceVariable + return NamedTupleVariable + + def __init__(self, value, tuple_vt=None, init_args=None, **kwargs): # type: ignore[all] + from .lists import TupleVariable + + tx = kwargs.pop("tx", None) + super().__init__(value, init_args=init_args, **kwargs) + if tuple_vt is None: + if self.source is not None: + raise AssertionError( + "tuple_vt must be constructed by builder.py when source is present" + ) + # Emulate `tuple.__new__`: `tuple.__new__(cls)` with no iterable + # arg builds an empty tuple, `tuple.__new__(cls, iterable)` builds + # a tuple from the iterable. + # https://github.com/python/cpython/blob/3.11/Objects/tupleobject.c#L697-L710 + # + # TODO this duplicates the logic in `BuiltinVariable(tuple)` + elems = unpack_iterable(tx, init_args[0]) if init_args else [] + self._base_vt = TupleVariable(elems, mutation_type=ValueMutationNew()) + else: + self._base_vt = tuple_vt + self.tuple_cls = type(value) + self._base_methods = tuple_methods + if self._base_vt is None: + raise AssertionError("_base_vt must not be None after initialization") + + @property + def items(self) -> list[VariableTracker]: + if self._base_vt is None: + raise AssertionError("_base_vt must not be None in items") + return self._base_vt.items # type: ignore[return-value] + + def resolve_data_descriptor( + self, + tx: "InstructionTranslatorBase", + name: str, + type_attr: object, + source: Source | None, + ) -> VariableTracker: + if isinstance(type_attr, _collections._tuplegetter): + # namedtuple fields are _tuplegetter descriptors implemented in C. + # Emulate _tuplegetter.__get__ via tracked tuple items because + # self.value may be a freshly-created empty tuple from + # SideEffects.get_example_value (tuple.__new__(cls) with no args) + # or otherwise underpopulated. Subclasses (NamedTupleVariable, + # StructSequenceVariable) may further override for their specific + # descriptor types. + _, (idx, _) = type_attr.__reduce__() + return self.items[idx] + return super().resolve_data_descriptor(tx, name, type_attr, source) + + def reconstruct(self, codegen: "PyCodegen") -> None: + # Sourceless namedtuples/structseqs (e.g. tensor subclass metadata from + # SourcelessBuilder) aren't in id_to_variable so codegen_save_tempvars + # never processes them. When they appear in return values, codegen falls + # through to call_reconstruct. This is the same pattern as other + # sourceless containers (ConstDictVariable, TupleVariable, etc.). + # UserDefinedDictVariable doesn't need this because it's never created + # sourceless — it only comes from VariableBuilder which always has a + # source. + if self.source is not None: + raise AssertionError( + "reconstruct should only be called on sourceless tuples" + ) + create_fn = self.get_construct_fn() + codegen.add_push_null( + lambda: codegen.append_output( + codegen.create_load_const_unchecked(create_fn) + ) + ) + codegen(self._base_vt) + codegen.extend_output(create_call_function(1, False)) + + def get_construct_fn(self) -> Callable[..., Any]: + raise NotImplementedError + + def _validate_rest_for_tree_map( + self, rest: "list[VariableTracker]" + ) -> list["UserDefinedTupleVariable"] | None: + """Validate that rest args are compatible for tree_map fast-path.""" + others: list[UserDefinedTupleVariable] = [] + n = len(self.items) + for candidate in rest: + if ( + not isinstance(candidate, UserDefinedTupleVariable) + or len(candidate.items) != n + or candidate.tuple_cls is not self.tuple_cls + ): + return None + others.append(candidate) + return others + + def _make_tree_map_result( + self, new_items: list[VariableTracker] + ) -> "UserDefinedTupleVariable": + from .lists import TupleVariable + + tuple_vt = TupleVariable(new_items, mutation_type=ValueMutationNew()) + return type(self)( + self.value, + tuple_vt=tuple_vt, + mutation_type=ValueMutationNew(), + ) + + def _is_pytree_node(self) -> bool: + from torch.utils._pytree import is_namedtuple_class + + return is_namedtuple_class(self.tuple_cls) or is_structseq_class(self.tuple_cls) + + def call_tree_map_branch( + self, + tx: "InstructionTranslatorBase", + tree_map_fn: "variables.functions.UserFunctionVariable", + map_fn: "VariableTracker", + rest: "list[VariableTracker]", + tree_map_kwargs: "dict[str, VariableTracker]", + ) -> "VariableTracker": + if not self._is_pytree_node(): + return super().call_tree_map_branch( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs + ) + others = self._validate_rest_for_tree_map(rest) + if others is None: + return self._tree_map_fallback( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs + ) + + new_items: list[VariableTracker] = [] + for idx, item in enumerate(self.items): + sibling_leaves = [o.items[idx] for o in others] + new_items.append( + item.call_tree_map( + tx, tree_map_fn, map_fn, sibling_leaves, tree_map_kwargs + ) + ) + + return self._make_tree_map_result(new_items) + + def call_tree_map_with_path_branch( + self, + tx: "InstructionTranslatorBase", + tree_map_fn: "variables.functions.UserFunctionVariable", + map_fn: "VariableTracker", + rest: "list[VariableTracker]", + tree_map_kwargs: "dict[str, VariableTracker]", + keypath: "tuple[Any, ...]", + ) -> "VariableTracker": + if not self._is_pytree_node(): + return super().call_tree_map_with_path_branch( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs, keypath + ) + others = self._validate_rest_for_tree_map(rest) + if others is None: + return self._tree_map_with_path_fallback( + tx, tree_map_fn, map_fn, rest, tree_map_kwargs, keypath + ) + + fields = namedtuple_fields(self.tuple_cls) + new_items: list[VariableTracker] = [] + for idx, item in enumerate(self.items): + sibling_leaves = [o.items[idx] for o in others] + child_keypath = keypath + (GetAttrKey(fields[idx]),) + new_items.append( + item.call_tree_map_with_path( + tx, + tree_map_fn, + map_fn, + sibling_leaves, + tree_map_kwargs, + child_keypath, + ) + ) + + return self._make_tree_map_result(new_items) + + +class NamedTupleVariable(UserDefinedTupleVariable): + """Represents Python namedtuples (created via collections.namedtuple). + + Namedtuples use _tuplegetter descriptors for field access and + Type(*args) / Type._make(iterable) for construction. + """ + + def resolve_data_descriptor( + self, + tx: "InstructionTranslatorBase", + name: str, + type_attr: object, + source: Source | None, + ) -> VariableTracker: + if isinstance(type_attr, _collections._tuplegetter): + # namedtuple fields are _tuplegetter descriptors implemented in C. + # We emulate _tuplegetter.__get__ by indexing into the tracked + # tuple items, because self.value may not hold actual runtime values. + _, (idx, _) = type_attr.__reduce__() + return self.items[idx] # type: ignore[union-attr] + return super().resolve_data_descriptor(tx, name, type_attr, source) + + def get_construct_fn(self) -> Callable[..., Any]: + return self.tuple_cls._make # type: ignore[attr-defined] + + def as_python_constant(self) -> Any: + items = [x.as_python_constant() for x in self.items] + return self.tuple_cls(*items) # type: ignore[arg-type] + + def as_proxy(self) -> Any: + items = [x.as_proxy() for x in self.items] + return self.tuple_cls(*items) # type: ignore[arg-type] + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + fields = namedtuple_fields(self.tuple_cls) + items = ", ".join( + f"{name}={tracked_repr(tx, item)}" for name, item in zip(fields, self.items) + ) + return VariableTracker.build(tx, f"{self.tuple_cls.__name__}({items})") + + +class StructSequenceVariable(UserDefinedTupleVariable): + """Represents C-implemented PyStructSequence types (torch.return_types.*). + + Structseqs use Type(iterable) calling convention and reject tuple.__new__. + """ + + def resolve_data_descriptor( + self, + tx: "InstructionTranslatorBase", + name: str, + type_attr: object, + source: Source | None, + ) -> VariableTracker: + if isinstance(type_attr, types.MemberDescriptorType): + # Structseq fields are member_descriptor objects. We emulate + # field access by looking up the field name in _fields and + # indexing into the tracked tuple items. + fields = namedtuple_fields(self.tuple_cls) + if name in fields: + return self.items[fields.index(name)] + return super().resolve_data_descriptor(tx, name, type_attr, source) + + def get_construct_fn(self) -> Callable[..., Any]: + return self.tuple_cls + + def as_python_constant(self) -> Any: + items = [x.as_python_constant() for x in self.items] + return self.tuple_cls(items) + + def as_proxy(self) -> Any: + items = [x.as_proxy() for x in self.items] + return self.tuple_cls(items) + + def debug_repr(self) -> str: + fields = namedtuple_fields(self.tuple_cls) + items = ", ".join( + f"{name}={item.debug_repr()}" for name, item in zip(fields, self.items) + ) + return f"{self.tuple_cls.__module__}.{self.tuple_cls.__qualname__}({items})" + + def tp_repr_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + fields = namedtuple_fields(self.tuple_cls) + items = ", ".join( + f"{name}={tracked_repr(tx, item)}" for name, item in zip(fields, self.items) + ) + return VariableTracker.build( + tx, + f"{self.tuple_cls.__module__}.{self.tuple_cls.__qualname__}({items})", + ) + + +class MutableMappingVariable(UserDefinedObjectVariable): + def __init__(self, value: object, **kwargs: Any) -> None: + super().__init__(value, **kwargs) + + def method_setattr_standard( + self, + tx: "InstructionTranslatorBase", + name: VariableTracker, + value: VariableTracker, + ) -> VariableTracker: + """Override to handle property setters on MutableMapping subclasses. + + This is needed because property.__set__ is a slot wrapper (C function), + but property.fset is a Python function we can trace. + + Without this, property setters on newly created MutableMapping objects fail + when accessing nested objects (which haven't been initialized yet on the + example value). By tracing the fset, we capture the setter logic in the graph + instead of running it on uninitialized example objects. + + TODO(compiler): This fix is scoped to MutableMapping only because tracing + property setters on ALL UserDefinedObjectVariable can cause failures when + the fset calls untraceable C++ functions (e.g., pybind functions). Ideally, + this should be extended to all user-defined classes with a graceful fallback + when tracing the fset hits an untraceable function. + See: https://github.com/pytorch/pytorch/issues/172000 + """ + if isinstance(name, variables.ConstantVariable) and isinstance(name.value, str): + name_str = name.value + descriptor = inspect.getattr_static(type(self.value), name_str, None) + if isinstance(descriptor, property) and descriptor.fset is not None: + fset_source = None + if self.cls_source: + desc_source = self.get_source_by_walking_mro(tx, name_str) + fset_source = AttrSource(desc_source, "fset") + fset_vt = VariableTracker.build(tx, descriptor.fset, fset_source) + return fset_vt.call_function(tx, [self, value], {}) + + return super().method_setattr_standard(tx, name, value) + + def _get(self, tx: "InstructionTranslatorBase") -> "VariableTracker | None": + # `.get` backed by the stdlib Mapping/dict implementation resolves to a + # traceable polyfill; anything else declines to the generic getattro. + if type(self.value).get in ( # type: ignore[attr-defined] + collections.abc.Mapping.get, + dict.get, + ): + return variables.UserMethodVariable(polyfills.mapping_get, self) + return None + + tp_getset = {"get": GetSet(_get, None)} + + def mp_length_impl(self, tx: "InstructionTranslatorBase") -> VariableTracker: + if self._maybe_get_baseclass_method("__len__") in dict_methods: + return VariableTracker.build(tx, len(self.value)) # type: ignore[bad-argument-type] + return super().mp_length_impl(tx) + + +class RandomVariable(UserDefinedObjectVariable): + pass diff --git a/.venv/lib/python3.12/site-packages/torch/_environment.py b/.venv/lib/python3.12/site-packages/torch/_environment.py new file mode 100644 index 0000000000000000000000000000000000000000..67e5784dfc1a5104f92b4d2144189976fcce43e8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_environment.py @@ -0,0 +1,9 @@ +from typing import Literal + + +def is_fbcode() -> Literal[False]: + return False + + +def is_prod() -> Literal[False]: + return False diff --git a/.venv/lib/python3.12/site-packages/torch/_export/__init__.py b/.venv/lib/python3.12/site-packages/torch/_export/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7a46a50c04b3ffe6aac78ca2978cdde293f2a17b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/__init__.py @@ -0,0 +1,189 @@ +# mypy: allow-untyped-defs +import copy +import dataclasses +import functools +import io +import json +import logging +import os +import re +import sys +import types +import warnings +import weakref +import zipfile +from collections import OrderedDict +from contextlib import contextmanager +from functools import lru_cache + +from typing import Any, Optional, TYPE_CHECKING, Union +from collections.abc import Callable +from unittest.mock import patch + +import torch +import torch.fx +import torch.utils._pytree as pytree + +from torch._dispatch.python import enable_python_dispatcher +from torch._guards import compile_context +from torch._utils_internal import log_export_usage +from torch.export._tree_utils import reorder_kwargs +from torch.export.graph_signature import ( + ArgumentSpec, + ConstantArgument, + ExportGraphSignature, + InputKind, + InputSpec, + OutputKind, + OutputSpec, + SymIntArgument, + SymBoolArgument, + SymFloatArgument, + TensorArgument, +) +from torch.fx import traceback as fx_traceback +from torch.fx._compatibility import compatibility +from torch.fx.experimental.proxy_tensor import make_fx +from torch.fx.graph import _PyTreeCodeGen, _PyTreeInfo + +from .wrappers import _wrap_submodules +from .utils import _materialize_cpp_cia_ops +from . import config + +if TYPE_CHECKING: + from torch._C._aoti import AOTIModelContainerRunner + +log = logging.getLogger(__name__) + +@dataclasses.dataclass +class ExportDynamoConfig: + """ + Manage Export-specific configurations of Dynamo. + """ + allow_rnn: bool = True + + +# We only want to print this once to avoid flooding logs in workflows where aot_compile_warning +# is called multiple times. +@lru_cache +def aot_compile_warning(): + + log.warning("+============================+") + log.warning("| !!! WARNING !!! |") + log.warning("+============================+") + log.warning( + "torch._export.aot_compile()/torch._export.aot_load() is being deprecated, please switch to " + "directly calling torch._inductor.aoti_compile_and_package(torch.export.export())/" + "torch._inductor.aoti_load_package() instead.") + + +def aot_compile( + f: Callable, + args: tuple[Any, ...], + kwargs: dict[str, Any] | None = None, + *, + dynamic_shapes: dict[str, Any] | None = None, + options: dict[str, Any] | None = None, + remove_runtime_assertions: bool = False, + disable_constraint_solver: bool = False, + same_signature: bool = True, +) -> list[Any] | str: + """ + Note: this function is not stable yet + + Traces either an nn.Module's forward function or just a callable with PyTorch + operations inside, generates executable cpp code from the program, and returns + the path to the generated shared library + + Args: + f: the `nn.Module` or callable to trace. + + args: example positional inputs. + + kwargs: optional example keyword inputs. + + dynamic_shapes: Should either be: + 1) a dict from argument names of ``f`` to their dynamic shape specifications, + 2) a tuple that specifies dynamic shape specifications for each input in original order. + If you are specifying dynamism on keyword args, you will need to pass them in the order that + is defined in the original function signature. + + The dynamic shape of a tensor argument can be specified as either + (1) a dict from dynamic dimension indices to :func:`Dim` types, where it is + not required to include static dimension indices in this dict, but when they are, + they should be mapped to None; or (2) a tuple / list of :func:`Dim` types or None, + where the :func:`Dim` types correspond to dynamic dimensions, and static dimensions + are denoted by None. Arguments that are dicts or tuples / lists of tensors are + recursively specified by using mappings or sequences of contained specifications. + + options: A dictionary of options to control inductor + + disable_constraint_solver: Whether the dim constraint solver must be disabled. + + Returns: + Path to the generated shared library + """ + from torch.export._trace import _export_to_torch_ir + from torch._inductor.decomposition import select_decomp_table + from torch._inductor import config as inductor_config + + aot_compile_warning() + + if inductor_config.is_predispatch: + gm = torch.export._trace._export(f, args, kwargs, dynamic_shapes, pre_dispatch=True).module() + else: + # We want to export to Torch IR here to utilize the pre_grad passes in + # inductor, which run on Torch IR. + with torch._export.config.patch(use_new_tracer_experimental=True): + gm = _export_to_torch_ir( + f, + args, + kwargs, + dynamic_shapes, + disable_constraint_solver=disable_constraint_solver, + same_signature=same_signature, + # Disabling this flag, because instead we can rely on the mapping + # dynamo_flat_name_to_original_fqn which is coming from Dynamo. + restore_fqn=False, + ) + + with torch.no_grad(): + so_path = torch._inductor.aot_compile(gm, args, kwargs, options=options) # type: ignore[arg-type] + + if not isinstance(so_path, (str, list)): + raise AssertionError(f"expected str or list, got {type(so_path)}") + return so_path + +def aot_load(so_path: str, device: str) -> Callable: + """ + Loads a shared library generated by aot_compile and returns a callable + + Args: + so_path: Path to the shared library + + Returns: + A callable + """ + aot_compile_warning() + + if device == "cpu": + runner: AOTIModelContainerRunner = torch._C._aoti.AOTIModelContainerRunnerCpu(so_path, 1) + elif device == "cuda" or device.startswith("cuda:"): + runner = torch._C._aoti.AOTIModelContainerRunnerCuda(so_path, 1, device) + elif device == "xpu" or device.startswith("xpu:"): + runner = torch._C._aoti.AOTIModelContainerRunnerXpu(so_path, 1, device) + elif device == "mps" or device.startswith("mps:"): + runner = torch._C._aoti.AOTIModelContainerRunnerMps(so_path, 1) + else: + raise RuntimeError("Unsupported device " + device) + + def optimized(*args, **kwargs): + call_spec = runner.get_call_spec() + in_spec = pytree.treespec_loads(call_spec[0]) + out_spec = pytree.treespec_loads(call_spec[1]) + flat_inputs = pytree.tree_flatten((args, reorder_kwargs(kwargs, in_spec)))[0] + flat_inputs = [x for x in flat_inputs if isinstance(x, torch.Tensor)] + flat_outputs = runner.run(flat_inputs) + return pytree.tree_unflatten(flat_outputs, out_spec) + + return optimized diff --git a/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7232eaba3319e444f77b314d1ac98ed8331c175 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/config.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4bd9899a7c5831109362361bab07cdb2ddb5887 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/config.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/converter.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/converter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34c1a765519f05741d135ec7a2111e85d42e7421 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/converter.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/error.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..331575310a2b86af7a4363cd4b1ede298ea175fc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/error.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/non_strict_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/non_strict_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a00f5d6bddcb886f6de25042519b6bb8d2cb13b1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/non_strict_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/pass_base.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/pass_base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8483d42d9ec7046fca6888a725b050310a737f8e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/pass_base.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/tools.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/tools.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1073dcdebe07e139bb26c3a26761a79c6f19c7f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/tools.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8776b9ab833e3b9b860497af5439ecea303666fb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/verifier.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/verifier.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8eb09d374a7d3b3081b9571c425acf5b6618da44 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/verifier.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/wrappers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/wrappers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba769f63259b295e0f05da7b3c64f804cac91fbb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/__pycache__/wrappers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/config.py b/.venv/lib/python3.12/site-packages/torch/_export/config.py new file mode 100644 index 0000000000000000000000000000000000000000..4f800487b2ab67ad88384d42bfb93f35f5e7b417 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/config.py @@ -0,0 +1,45 @@ +""" +Configuration module for torch.export.export. + +This module contains various configuration flags and settings that control torch.export's +behavior, including: +- Runtime behavior flags +- Debugging and development options +""" + +import sys +from typing import Any, TYPE_CHECKING + +from torch._environment import is_fbcode +from torch.utils._config_module import install_config_module + + +# this flag controls whether we use new functional tracer. It +# should be True in the long term. +use_new_tracer_experimental = True + +# this flag is used to control whether we want to instrument +# fake tensor creation to track potential leaks. It is off +# by default, but user can turn it on to debug leaks. +detect_non_strict_fake_tensor_leaks = False + +# error on potentially pre-dispatch/non-strict tracing limitation +# this type of error usually happens when we encounter an op +# that we don't know how to proxy, resulting in untracked fake tensors +error_on_lifted_constant_tensors = True + +# enable auto_functionalized_v2 in export +# We turn this off in fbcode due to downstream users not +# being ready to handle auto_functionalized_v2. +enable_auto_functionalized_v2_for_export = not is_fbcode() + +use_legacy_dynamo_graph_capture = True + + +if TYPE_CHECKING: + from torch.utils._config_typing import * # noqa: F403 + + def _make_closure_patcher(**changes: Any) -> Any: ... + + +install_config_module(sys.modules[__name__]) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/converter.py b/.venv/lib/python3.12/site-packages/torch/_export/converter.py new file mode 100644 index 0000000000000000000000000000000000000000..1cba606d093f715d6a6be9d683784461bfe1763c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/converter.py @@ -0,0 +1,1622 @@ +# mypy: allow-untyped-defs +import builtins +import logging +import operator +import typing +import warnings +from collections.abc import Callable, Sequence +from contextlib import contextmanager +from typing import Any + +import torch +import torch.export._trace +from torch import _C +from torch._export.passes.replace_quantized_ops_with_standard_ops_pass import ( + replace_quantized_ops_with_standard_ops, +) +from torch.export.dynamic_shapes import _tree_map_with_path, Dim +from torch.export.exported_program import ExportedProgram +from torch.export.graph_signature import ( + ConstantArgument, + CustomObjArgument, + InputKind, + InputSpec, + OutputKind, + OutputSpec, + TensorArgument, +) +from torch.fx import subgraph_rewriter + + +log = logging.getLogger(__name__) + + +def _get_param_count_list(method_graph, args_params): + param_count_list = [] + for input_, arg_params_ in zip(method_graph.inputs(), args_params): + if "PackedParams" in str(input_.type()): + in_vars, _ = torch.jit._flatten(arg_params_) + param_count_list.append(len(in_vars)) + else: + param_count_list.append(arg_params_ is not None) + + return param_count_list + + +def _trace_and_get_graph_from_model(model, args): + # A basic sanity check: make sure the state_dict keys are the same + # before and after running the model. Fail fast! + orig_state_dict_keys = torch.jit._unique_state_dict(model).keys() + + # Disable Autocast cache because it replaces kernel's weight and bias + # by (undesired) constants. + # No perf impact for when there are reused weights since https://github.com/pytorch/pytorch/pull/85665 + prev_autocast_cache_enabled = torch.is_autocast_cache_enabled() + torch.set_autocast_cache_enabled(False) + trace_graph, torch_out, _inputs_states = torch.jit._get_trace_graph( + model, + args, + strict=False, + _force_outplace=False, + _return_inputs_states=True, + ) + torch.set_autocast_cache_enabled(prev_autocast_cache_enabled) + + if orig_state_dict_keys != torch.jit._unique_state_dict(model).keys(): + raise RuntimeError( + "state_dict changed after running the tracer; " + "something weird is happening in your model!" + ) + + return trace_graph, torch_out + + +def _create_jit_graph( + model: torch.nn.Module | torch.jit.ScriptFunction, args: Sequence[Any] +) -> tuple[torch.Graph, list["_C.IValue"], Any, torch.ScriptModule | None]: + if isinstance(model, (torch.jit.ScriptFunction, torch.jit.ScriptModule)): + flattened_args = tuple(torch.jit._flatten(tuple(args))[0]) + torch_out = None + + if isinstance(model, torch.jit.ScriptModule): + try: + graph = model.forward.graph # type: ignore[attr-defined] + except AttributeError as e: + raise RuntimeError("'forward' method must be a script method") from e + _C._jit_pass_onnx_function_substitution(graph) + freezed_module = _C._freeze_module( + typing.cast(_C.ScriptModule, model._c), preserveParameters=True + ) + module, params = _C._jit_onnx_list_model_parameters(freezed_module) + method_graph = module._get_method("forward").graph + args_params = tuple(args) + tuple(params) + param_count_list = _get_param_count_list(method_graph, args_params) + in_vars, _ = torch.jit._flatten(args_params) + graph = _C._propagate_and_assign_input_shapes( + method_graph, tuple(in_vars), param_count_list, False, False + ) + return graph, params, torch_out, module + + # torch.jit.ScriptFunction + params = [] + graph = model.graph + _C._jit_pass_onnx_function_substitution(graph) + param_count_list = _get_param_count_list(graph, args) + graph = _C._propagate_and_assign_input_shapes( + graph, flattened_args, param_count_list, False, False + ) + return graph, params, torch_out, None + + graph, torch_out = _trace_and_get_graph_from_model(model, args) + _C._jit_pass_onnx_lint(graph) + state_dict = torch.jit._unique_state_dict(model) + params = list(state_dict.values()) + graph_inputs = list(graph.inputs()) + user_input_num = len(graph_inputs) - len(state_dict) + param_names = list(state_dict.keys()) + for i, inp in enumerate(graph_inputs): + if i >= user_input_num: + inp.setDebugName(param_names[i - user_input_num]) + _C._jit_pass_onnx_function_substitution(graph) + return graph, params, torch_out, None + + +def list_add(a, b): + return a + b + + +def list_append(container, element): + return container + [element] + + +def execute_subgraph_from_prim_loop( + subgraph, iter_idx, len_loop_local_arguments, *args, **kwargs +): + """ + subgraph: GraphModule from sub-block. + iter_idx: The index of interaction. + len_loop_local_arguments: The number of loop local arguments in args. + """ + + # Loop local variables. TS graph create those as inputs because their values + # are updated inside the loop. + loop_local_args = args[:len_loop_local_arguments] + # Global variables that are not passed in as inputs to the loop sub-blocks + # but are directly used. Most of time, their values are not updated, but + # the only exception is when there are some operations that perform inplace + # updates. + global_args = args[len_loop_local_arguments:] + return subgraph(*global_args, iter_idx, *loop_local_args, **kwargs) + + +def inplace_optimize_sym_size_div(gm: torch.fx.GraphModule): + def pattern(im, dim, scale): + sym_size_int = torch.ops.aten.sym_size.int(im, dim) + scalar_tensor = torch.ops.aten.scalar_tensor(sym_size_int) + div_scalar_mode = torch.ops.aten.div.Scalar_mode( + scalar_tensor, scale, rounding_mode="trunc" + ) + int_tensor = torch.ops.aten.Int.Tensor(div_scalar_mode) + return int_tensor + + def replacement(im, dim, scale): + sym_size_int = torch.ops.aten.sym_size.int(im, dim) + return sym_size_int // scale + + subgraph_rewriter.replace_pattern(gm, pattern, replacement) + + +def is_valid_for_codegen(name): + if len(name) == 0: + raise RuntimeError("Empty argument name for codegen") + if name[0].isdigit(): + return False + return True + + +def normalize_name(name: str, prefix: str = "rename") -> str: + name = name.replace(".", "_") + if is_valid_for_codegen(name): + return name + return f"{prefix}_{name}" + + +def ir_name_to_func_name(name: str) -> str: + """prim::If -> convert_prim_If""" + name_list = name.split("::") + return "convert_" + "_".join(name_list) + + +def get_node_as_placeholder_or_get_attr(fx_graph, name, is_top_level_graph): + if is_top_level_graph: + return fx_graph.get_attr(name) + return fx_graph.placeholder(name) + + +_TORCH_DTYPE_TO_ENUM = { + torch.uint8: 0, + torch.int8: 1, + torch.int16: 2, + torch.int32: 3, + torch.int64: 4, + torch.float16: 5, + torch.float32: 6, + torch.float64: 7, + torch.complex32: 8, + torch.complex64: 9, + torch.complex128: 10, + torch.bool: 11, + torch.qint8: 12, + torch.quint8: 13, + torch.bfloat16: 15, +} + +_TORCH_ENUM_TO_DTYPE = {value: key for key, value in _TORCH_DTYPE_TO_ENUM.items()} + + +def get_dtype_as_int(tensor): + """ + prim::dtype has the signature "Tensor a) -> int", where it gets the dtype of + the tensor and returns the integer corresponding to this dtype based on the + enum in ScalarType.h + """ + dtype = tensor.dtype + if dtype not in _TORCH_DTYPE_TO_ENUM: + raise RuntimeError(f"Unsupported dtype {dtype}") + return _TORCH_DTYPE_TO_ENUM[dtype] + + +# Those operators will be automatically populated to an instance method +# of TS2FXGraphConverter with name convert__(). +# Please check __init__ for method population implementations. +kind_to_standard_operators: dict[str, Callable[..., Any]] = { + "prim::max": builtins.max, + "prim::min": builtins.min, + "prim::TupleIndex": operator.getitem, + "aten::__is__": operator.is_, + "aten::__isnot__": operator.is_not, + "aten::__not__": operator.not_, + "aten::__contains__": operator.contains, + "prim::dtype": get_dtype_as_int, + "aten::len": len, + # Mapping from specialized op to its symbolic counterpart. + # They currently do not have any other overrides. + "aten::numel": torch.ops.aten.sym_numel, + "aten::size": torch.ops.aten.sym_size, + "aten::storage_offset": torch.ops.aten.sym_storage_offset, + "aten::stride": torch.ops.aten.sym_stride, +} + + +def get_ir_value_parent_name_and_attr_name(node): + irv_parent_name, irv_name = node.input().debugName(), node.output().debugName() + attr_name = node.s("name") + return irv_name, irv_parent_name, attr_name + + +def construct_fqn(ir, ref_map, name_map): + name_list = [] + while ir in ref_map: + name_list.append(name_map[ir]) + ir = ref_map[ir] + return ".".join(reversed(name_list)) + + +def get_block_to_lifted_attrs( + graph: torch._C.Graph, +) -> tuple[dict[torch._C.Block, set[str]], dict[str, str]]: + """ + Perform two passes to get a mapping of blocks to a set of FQNs of its lifted attributes. + When a graph has control flow, the graph will be divided into multiple blocks. We want to convert + each block to a graph which will be passed into torch.cond. A restriction for torch.cond is that model + parameters/buffers are expected to be lifted as inputs to the subgraphs. Before converting the model, + we will run this pass which will: + 1. Figure out which params/buffers are used within blocks through tracing the GetAttr calls. + 2. Process the graph bottom up to find the lifted attributes of each block by taking the union + of the attributes used in the current block, and the lifted attributes of all its child blocks. + + Returns: + A mapping of blocks to a set of FQNs of its lifted attributes, and a + mapping of node names to the FQNs of its lifted attributes. + """ + + # A map from a block to its expected to be lifted arguments. + blocks_to_lifted_attrs: dict[torch._C.Block, set[str]] = {} + + # Reference map stores the input (i.e., src) and output (i.e., dest) IR of a + # GetAttr node. By traversing this reference map, we can figure out the + # full IR aliasing pass and figure out the FQN of an attribute. + # E.g., %2 = GetAttr(linear)[%1] --> node_to_parent_map["%2"] = "%1" + node_to_parent_map: dict[str, str] = {} + + # Used for reconstructing the FQN of an attribute based on the reference map. + # In nutshell, for each GetAttr call, GetAttr(input IR, attribute name) -> output IR + # This name map stores which attribute name is called for a src IR --> dest IR action. + # E.g., %2 = GetAttr(linear)[%1] --> node_to_attr_name["%2"] = "linear" + node_to_attr_name: dict[str, str] = {} + + def _dfs_get_attr_dependency(entry): + """ + First DFS path to construct reference map and name map. + """ + for node in entry.nodes(): + if node.kind() == "prim::GetAttr": + ( + irv_name, + irv_parent_name, + attr_name, + ) = get_ir_value_parent_name_and_attr_name(node) + node_to_parent_map[irv_name] = irv_parent_name + node_to_attr_name[irv_name] = attr_name + for block in node.blocks(): + _dfs_get_attr_dependency(block) + + def _map_blocks_to_lifted_attrs(entry): + """ + Walk the graph in a bottom-up fashion to build the expected to be + lifted arguments for each block. + """ + arguments: set[str] = set() + for node in entry.nodes(): + for block in node.blocks(): + # Recursively build. + arguments = arguments.union(_map_blocks_to_lifted_attrs(block)) + if node.kind() == "prim::GetAttr": + irv_name = node.output().debugName() + # Skip for intermediate GetAttr, which will anyway not result a FQN. + # E.g., node_to_parent_name: {"%3": "%2", "%2": "%1"} + # node_to_attr_name: {"%3": "weight", "%2": "linear", "%1": "self"} + # There is only one FQN %3-->%2-->%1: self.linear.weight + # %2-->%1 is not a FQN: self.linear + if irv_name not in set(node_to_parent_map.values()): + arguments.add( + construct_fqn(irv_name, node_to_parent_map, node_to_attr_name) + ) + if not isinstance(entry, torch._C.Graph): # Skip the top level. + blocks_to_lifted_attrs[entry] = arguments + return arguments + + _dfs_get_attr_dependency(graph) + _map_blocks_to_lifted_attrs(graph) + + return blocks_to_lifted_attrs, node_to_attr_name + + +def get_attribute_fqn_from_ts_node( + name_to_attribute_fqn: dict[str, str], node: torch._C.Node +) -> str: + def get_attr(name: str): + if name in name_to_attribute_fqn: + return name_to_attribute_fqn[name] + else: + raise ValueError(f"Attribute {name} not found") + + if node.kind() == "prim::SetAttr": + input_name = next(node.inputs()).debugName() + elif node.kind() == "prim::GetAttr": + input_name = node.input().debugName() + else: + raise RuntimeError( + f"Unexpected node kind when getting attribute fqn. node: {node} " + ) + + attr_name = node.s("name") + root_attr_name = get_attr(input_name) + attr_fqn = f"{root_attr_name}.{attr_name}" if root_attr_name else attr_name + + return attr_fqn + + +def get_op_overload(node: torch._C.Node): + schema_str = node.schema() + if schema_str == "(no schema)": + raise AssertionError(f"got empty schema for {node}") + schema: torch._C.FunctionSchema = torch._C.parse_schema(schema_str) + ns, op_name = str(schema.name).split("::") + override = schema.overload_name + + try: + op_overload_mod = getattr(torch.ops, ns) + op_overload_packet = getattr(op_overload_mod, op_name) + if override: + op_overload = getattr(op_overload_packet, override) + else: + op_overload = op_overload_packet.default + except Exception as e: + raise RuntimeError( + f"Unable to find operator {node.kind()} with schema {node.schema()}" + ) from e + + return op_overload + + +class TS2FXGraphConverter: + def __init__( + self, + ts_graph: torch._C.Graph | torch._C.Block, + name_to_param: dict[str, torch.Tensor], + name_to_buffer: dict[str, torch.Tensor], + blocks_to_lifted_attrs: dict[torch._C.Block, set[str]], + name_to_non_tensor_attribute: dict[str, Any], + name_to_constant: dict[str, Any], + name_to_attribute_fqn: dict[str, str], + ): + self.ts_graph = ts_graph + # Mapping of parameter FQN to actual parameter value + self.name_to_param = name_to_param + # Mapping of buffer FQN to actual buffer value + self.name_to_buffer = name_to_buffer + + self.fx_graph: torch.fx.Graph = torch.fx.Graph() + self.input_specs: list[InputSpec] = [] + self.output_specs: list[OutputSpec] = [] + + # Mapping of TS node name to converted FX node + self.name_to_node: dict[ + str, torch.fx.Node | list[torch.fx.Node] | dict[Any, torch.fx.Node] + ] = {} + # Mapping of TS node name to constant value (int, str, TorchBind obj, + # tensor constants ...) + self.name_to_constant: dict[str, Any] = name_to_constant + + # Mapping from torchscript node output name to attribute fully qualified name + self.name_to_attribute_fqn: dict[str, str] = name_to_attribute_fqn + + # Mapping from fully qualified name to real values or a fx graph node + # During convert, this represents the current value of a non-tensor attribute + # One use case is: + # def forward(self, x): + # c1 = self.count + # self.count += 1 + # c2 = self.count + # return x + c1 + c2 + self.name_to_non_tensor_attribute_node: dict[str, Any] = {} + + # Mapping from fully qualified name to initial real values inputs + # We separate it from self.name_to_non_tensor_attribute_node since + # we need initial real value input when we construct fx.GraphModule + self.name_to_non_tensor_attribute: dict[str, Any] = name_to_non_tensor_attribute + + self.subgraphs: dict[str, torch.fx.GraphModule] = {} + + # Mapping of block to list of attributes that need to be lifted for each + # block + self.blocks_to_lifted_attrs = blocks_to_lifted_attrs + + # Populate methods for the standard operators. + for k in kind_to_standard_operators: + handler_func_name = ir_name_to_func_name(k) + # Create an indirect function call: + # convert__ --> lambda node: _convert_standard_operator(node) + setattr( + self, + handler_func_name, + lambda node: self._convert_standard_operators(node), + ) + + # This stores a list of return results that do not appear in the original TS + # graph's outputs. The reason we maintain this is because some operations in the sub-block + # might have inplace updates to the variable defined in the parent fx graph. After + # the execution of that sub-block, the variable defined in the parent fx graph also + # needs to be updated. + self.name_update_from_subblock_to_parent: set[str] = set() + + def _is_get_attr_node(self, fqn): + return ( + fqn in self.name_to_buffer + or fqn in self.name_to_param + or ( + fqn in self.name_to_constant + and isinstance(self.name_to_constant[fqn], torch.ScriptObject) + ) + ) + + def _convert_block_to_subgraph(self, node: torch._C.Node, arguments: list[str]): + subgraph_nodes, subgraph_converters = [], [] + for block in node.blocks(): + subgraph_converter = TS2FXGraphConverter( + block, + self.name_to_param, + self.name_to_buffer, + self.blocks_to_lifted_attrs, + {}, + self.name_to_constant, + self.name_to_attribute_fqn, + ) + + for block_arg in arguments: + normalized_block_arg_name = normalize_name(block_arg) + placeholder_node = subgraph_converter.fx_graph.placeholder( + normalized_block_arg_name + ) + subgraph_converter.name_to_node[block_arg] = placeholder_node + + subgraph = subgraph_converter.convert() + subgraph_name = self.add_subgraph(subgraph) + subgraph_nodes.append(self.fx_graph.get_attr(subgraph_name)) + subgraph_converters.append(subgraph_converter) + return subgraph_nodes, subgraph_converters + + def _identify_inputs_as_arguments(self, entry): + """ + Identify inputs from the innermost sub-block. This is needed + for nested sub-blocks when the input is hidden in the nested sub-block. + E.g., example IR of input is hidden in the nested sub-block. + Graph[x.1] + %1 = ... + Block[] + Block[x.1] + %2 = x.1 ... + """ + arguments: set[str] = set() + for block in entry.blocks(): + for block_node in block.nodes(): + for block_node_in in block_node.inputs(): + if ( + block_node_in.debugName() in self.name_to_node + and block_node_in.debugName() not in self.name_to_attribute_fqn + ): + arguments.add(block_node_in.debugName()) + arguments = arguments.union( + self._identify_inputs_as_arguments(block_node) + ) + return arguments + + def is_top_level_graph(self): + return isinstance(self.ts_graph, torch._C.Graph) + + def add_subgraph(self, subgraph) -> str: + name = f"subgraph_{len(self.subgraphs)}" + self.subgraphs[name] = subgraph + return name + + def get_args_kwargs(self, node: torch._C.Node, schema): + args = [] + kwargs = {} + for input, schema_arg in zip(node.inputs(), schema.arguments): + if schema_arg.kwarg_only: + kwargs[schema_arg.name] = self.get_fx_value_by_ir_value(input) + else: + args.append(self.get_fx_value_by_ir_value(input)) + + return tuple(args), kwargs + + def get_fx_value_by_ir_value(self, value: torch._C.Value): + value_name = value.debugName() + + if value_name in self.name_to_node: + input_node = self.name_to_node[value_name] + return input_node + elif value_name in self.name_to_constant: + if isinstance(self.name_to_constant[value_name], torch.ScriptObject): + return self.fx_graph.get_attr(value_name) + return self.name_to_constant[value_name] + elif value_name in self.name_to_attribute_fqn: + return self.get_fx_value_by_fqn(self.name_to_attribute_fqn[value_name]) + else: + raise ValueError(f"Input {value_name} not found") + + def get_fx_value_by_fqn(self, name): + if name in self.name_to_node: + fx_node = self.name_to_node[name] + elif name in self.name_to_constant: + fx_node = self.name_to_constant[name] + elif name in self.name_to_non_tensor_attribute_node: + fx_node = self.name_to_non_tensor_attribute_node[name] + elif name in self.name_to_non_tensor_attribute: + fx_node = self.name_to_non_tensor_attribute[name] + else: + raise ValueError(f"Attribute {name} not found") + return fx_node + + def convert(self) -> torch.fx.GraphModule: + self.convert_graph_inputs() + + for node in self.ts_graph.nodes(): + self.convert_node(node) + + self.convert_graph_outputs() + + # Pass parameter and buffer to the root for lookup. + gm = torch.fx.GraphModule( + { + **self.subgraphs, + **self.name_to_param, + **self.name_to_buffer, + **self.name_to_non_tensor_attribute, + **self.name_to_constant, + }, + self.fx_graph, + ) + + inplace_optimize_sym_size_div(gm) + + gm.graph.lint() + + return gm + + def convert_graph_inputs(self): + for graph_input in self.ts_graph.inputs(): + name = graph_input.debugName() + + if name in self.name_to_param: + normalized_name = normalize_name(name) + self.input_specs.append( + InputSpec( + InputKind.PARAMETER, + arg=TensorArgument(name=normalized_name), + target=name, + ) + ) + fx_node = get_node_as_placeholder_or_get_attr( + self.fx_graph, name, self.is_top_level_graph() + ) + elif name in self.name_to_buffer: + normalized_name = normalize_name(name) + self.input_specs.append( + InputSpec( + InputKind.BUFFER, + arg=TensorArgument(name=normalized_name), + target=name, + persistent=True, + ) + ) + fx_node = get_node_as_placeholder_or_get_attr( + self.fx_graph, name, self.is_top_level_graph() + ) + elif name in self.name_to_constant: + if not isinstance(self.name_to_constant[name], torch.ScriptObject): + raise AssertionError( + f"Input conversion only handles ScriptObject, got {type(self.name_to_constant[name])}" + ) + normalized_name = normalize_name(name) + self.input_specs.append( + InputSpec( + InputKind.CUSTOM_OBJ, + arg=CustomObjArgument( + name=normalized_name, class_fqn=normalized_name + ), + target=name, + persistent=False, + ) + ) + fx_node = get_node_as_placeholder_or_get_attr( + self.fx_graph, name, self.is_top_level_graph() + ) + elif isinstance(graph_input.type(), torch.ClassType): + # Directly skip inputs that are ScriptObject but not used in the graph. + continue + else: + normalized_name = normalize_name(name, prefix="input") + self.input_specs.append( + InputSpec( + InputKind.USER_INPUT, + arg=TensorArgument(name=normalized_name), + target=name, + ) + ) + fx_node = self.fx_graph.placeholder(normalized_name) + + self.name_to_node[name] = fx_node + + def convert_aten_Float(self, node: torch._C.Node): + def to_float_tensor(t): + return t.to(dtype=torch.float).item() + + inp_list = [self.get_fx_value_by_ir_value(inp) for inp in node.inputs()] + fx_node = self.fx_graph.call_function( + to_float_tensor, + tuple(inp_list), + ) + self.name_to_node[node.output().debugName()] = fx_node + + def convert_aten_tensor(self, node: torch._C.Node): + """aten::tensor creates a constant tensor ad-hoc --> GetAttr""" + args, kwargs = self.get_args_kwargs(node, torch.ops.aten.tensor.default._schema) + + for k in kwargs: + if k == "requires_grad": + kwargs[k] = bool(kwargs[k]) # 0 -> False, 1 -> True + + to_tensor = ( + torch.tensor + if all(isinstance(a, int) for a in args) + else torch._refs.tensor + ) + + def target(*args, **kwargs): + if "dtype" in kwargs and kwargs["dtype"] is not None: + kwargs["dtype"] = _TORCH_ENUM_TO_DTYPE[kwargs["dtype"]] + return to_tensor(*args, **kwargs) + + # def to_dynamic_tensor(*args, **kwargs): + # if "dtype" in kwargs and kwargs["dtype"] is not None: + # kwargs["dtype"] = _TORCH_ENUM_TO_DTYPE[kwargs["dtype"]] + # return torch._refs.tensor(*args, **kwargs) + + output_name = node.output().debugName() + fx_node = self.fx_graph.call_function(target, args, kwargs) + self.name_to_node[output_name] = fx_node + + def convert_aten_append(self, node: torch._C.Node): + # special handle python list append: "aten::append.t(t[](a!) self, t(c -> *) el) -> t[](a!)" + + # inplace append to the list!! This is kinda crazy, as we are inplace mutating the list + # This makes the converter "non-functional", and the result depends on the order of the nodes being converted + # In a sense, the converter now becomes a stateful interpreter + warnings.warn( + "Converting aten::append.t, which is an inplace mutation of the list. " + "This makes the converter non-functional: the result depends on the order of the append nodes being converted!", + stacklevel=2, + ) + + args = tuple(self.get_fx_value_by_ir_value(inp) for inp in node.inputs()) + fx_node = self.fx_graph.call_function(list_append, args) + self.name_to_node[node.output().debugName()] = fx_node + + # inplace mutate arg[0], which is the python list + self.name_to_node[node.inputsAt(0).debugName()] = fx_node + + # Variables that need to be updated to parent module. + if not self.is_top_level_graph() and args[0].op == "placeholder": + self.name_update_from_subblock_to_parent.add(node.inputsAt(0).debugName()) + + def convert_prim_Constant(self, node: torch._C.Node): + name = node.output().debugName() + + value: Any = None + if node.hasAttribute("value"): + constant_kind = node.kindOf("value") + if constant_kind == "i": + value = node.i("value") + elif constant_kind == "f": + value = node.f("value") + elif constant_kind == "s": + value = node.s("value") + elif constant_kind == "t": + alias_name = ( + f"lifted_tensor_{name}" # Follow naming convention from EP tracing. + ) + fx_node = self.fx_graph.get_attr(alias_name) + self.name_to_node[name] = fx_node + name, value = alias_name, node.t("value") + elif constant_kind == "ival": + value = node.ival("value") + else: + raise ValueError(f"Unsupported constant type: {node.kindOf('value')}") + else: + value = None + + self.name_to_constant[name] = value + + def convert_prim_CallMethod(self, node: torch._C.Node): + inp_list = [self.get_fx_value_by_ir_value(inp) for inp in node.inputs()] + fx_node = self.fx_graph.call_method( + node.s("name"), + tuple(inp_list), + ) + self.name_to_node[node.output().debugName()] = fx_node + + def convert_prim_device(self, node: torch._C.Node): + input_type = node.input().type() + if input_type.isSubtypeOf(torch._C.TensorType.get()): + device = input_type.device() # type: ignore[attr-defined] + output_name = node.output().debugName() + self.name_to_constant[output_name] = device + else: + raise ValueError(f"Unsupported JitType ({input_type}) when get device") + + def convert_prim_GetAttr(self, node: torch._C.Node): + # Build fully qualified name + attr_fqn = get_attribute_fqn_from_ts_node(self.name_to_attribute_fqn, node) + output_name = node.output().debugName() + self.name_to_attribute_fqn[output_name] = attr_fqn + + if self.is_top_level_graph(): + if self._is_get_attr_node(attr_fqn): + # We insert a get_attr node due to two reasons. + # First, ts graph does not lift tensor constants as input nodes. So + # tensor constants may be ignored by in convert_graph_inputs(). + # Second, attr_fqn may have been written to via SetAttr. Two + # GetAttr may give different values. + self.name_to_node[output_name] = self.fx_graph.get_attr(attr_fqn) + else: + if attr_fqn not in self.name_to_non_tensor_attribute_node: + self.name_to_non_tensor_attribute_node[attr_fqn] = ( + self.name_to_non_tensor_attribute[attr_fqn] + ) + self.name_to_node[output_name] = self.name_to_non_tensor_attribute_node[ + attr_fqn + ] + else: + # Special support for if blocks which do not allow SetAttr TorchScript + # node and get_attr FX Graph Node. + if self._is_get_attr_node(attr_fqn): + self.name_to_node[output_name] = self.name_to_node[attr_fqn] + + def convert_prim_SetAttr(self, node: torch._C.Node): + attr_fqn = get_attribute_fqn_from_ts_node(self.name_to_attribute_fqn, node) + attr_value = tuple(node.inputs())[1] + ts_graph_tensor_input = self.get_fx_value_by_ir_value(attr_value) + if self._is_get_attr_node(attr_fqn): + fx_attr_node = self.fx_graph.get_attr(attr_fqn) + self.fx_graph.call_function( + torch.Tensor.copy_, (fx_attr_node, ts_graph_tensor_input) + ) + else: + self.name_to_non_tensor_attribute_node[attr_fqn] = ts_graph_tensor_input + + def convert_call_function_op(self, node: torch._C.Node): + target = get_op_overload(node) + + args, kwargs = self.get_args_kwargs(node, target._schema) + + fx_node = self.fx_graph.call_function(target, args, kwargs) + + # TODO: convert sourceRange() into stack_trace + # fx_node.meta["stack_trace"] = node.sourceRange() + + if node.outputsSize() == 1: + output_name = node.output().debugName() + self.name_to_node[output_name] = fx_node + else: + for i, outp in enumerate(node.outputs()): + output_name = outp.debugName() + next_fx_node = self.fx_graph.call_function( + operator.getitem, (fx_node, i) + ) + self.name_to_node[output_name] = next_fx_node + + def convert_prim_TupleConstruct(self, node: torch._C.Node): + self._convert_prim_iterator(node) + + def convert_prim_ListConstruct(self, node: torch._C.Node): + self._convert_prim_iterator(node) + + def _convert_prim_iterator(self, node: torch._C.Node): + output_list = [self.get_fx_value_by_ir_value(inp) for inp in node.inputs()] + + output_name = node.output().debugName() + self.name_to_node[output_name] = output_list + + def convert_prim_DictConstruct(self, node: torch._C.Node): + output_dict = {} + k, v = None, None + for i, inp in enumerate(node.inputs()): + # We assume key value are stored in pair in the DictConstruct. + # The first element is the key and the following is the value. + if i % 2 == 0: + k = self.get_fx_value_by_ir_value(inp) + else: + v = self.get_fx_value_by_ir_value(inp) + if k is None or v is None: + raise AssertionError("DictConstruct has an empty key value pair.") + output_dict[k] = v + k, v = None, None + + if k is not None or v is not None: + raise AssertionError( + "DictConstruct has an odd number of elements (violating our assumption)." + ) + + output_name = node.output().debugName() + self.name_to_node[output_name] = output_dict + + def convert_prim_ListUnpack(self, node: torch._C.Node): + self._convert_prim_unpack_iterator(node) + + def convert_prim_TupleUnpack(self, node: torch._C.Node): + self._convert_prim_unpack_iterator(node) + + def _convert_prim_unpack_iterator(self, node: torch._C.Node): + # Single input and multiple outputs for unpacking. + for i, outp in enumerate(node.outputs()): + outp_name = outp.debugName() + inp = self.get_fx_value_by_ir_value(node.input()) + fx_node = self.fx_graph.call_function(operator.getitem, (inp, i)) + self.name_to_node[outp_name] = fx_node + + def convert_aten_Int(self, node: torch._C.Node): + # converts aten::Int as aten._to_copy + aten::_local_scalar_dense + target = torch.ops.aten._to_copy.default + args = tuple(self.get_fx_value_by_ir_value(input) for input in node.inputs()) + to_copy_node = self.fx_graph.call_function(target, args, {"dtype": torch.int32}) + + fx_node = self.fx_graph.call_function( + torch.ops.aten._local_scalar_dense.default, (to_copy_node,) + ) + + # TODO: convert sourceRange() into stack_trace + # fx_node.meta["stack_trace"] = node.sourceRange() + + output_name = node.output().debugName() + self.name_to_node[output_name] = fx_node + + def convert_prim_NumToTensor(self, node: torch._C.Node): + # Converts prim::NumToTensor as aten.scalar_tensor. + # prim::NumToTensor IRs are currently triggered by: + # .size() https://github.com/pytorch/pytorch/blob/main/torch/csrc/jit/frontend/tracer.cpp#L950 + # .numel() https://github.com/pytorch/pytorch/blob/main/torch/csrc/jit/frontend/tracer.cpp#L971 + # For both of those APIs, torch.jit.trace implicitly sets the output tensor type + # to be LongTensor. + target = torch.ops.aten.scalar_tensor + args = tuple(self.get_fx_value_by_ir_value(input) for input in node.inputs()) + + fx_node = self.fx_graph.call_function(target, args, {"dtype": torch.long}) + output_name = node.output().debugName() + self.name_to_node[output_name] = fx_node + + def convert_prim_CreateObject(self, node: torch._C.Node): + output_name = node.output().debugName() + self.name_to_attribute_fqn[output_name] = "" + + def convert_aten__convolution(self, node: torch._C.Node): + # converts aten::_convolution as aten.convolution, since aten::_convolution + # doesn't have a meta function + target = torch.ops.aten.convolution.default + args, kwargs = self.get_args_kwargs(node, target._schema) + + fx_node = self.fx_graph.call_function(target, args, kwargs) + + output_name = node.output().debugName() + self.name_to_node[output_name] = fx_node + + def convert_aten_div(self, node: torch._C.Node): + target = get_op_overload(node) + schema = target._schema + + args, kwargs = self.get_args_kwargs(node, schema) + + # converts aten::div.Tensor_mode(x, tensor_constant) + # as aten.div.Scalar_mode(x, tensor_constant.item()) + if schema.overload_name == "Tensor_mode": + arg1_name = args[1].name + if arg1_name in self.name_to_constant and isinstance( + self.name_to_constant[arg1_name], torch.Tensor + ): + tensor_constant = self.name_to_constant[arg1_name] + if tensor_constant.numel() == 1: + updated_args = list(args) + updated_args[1] = self.name_to_constant[arg1_name].item() + + fx_node = self.fx_graph.call_function( + torch.ops.aten.div.Scalar_mode, + tuple(updated_args), + kwargs, + ) + + # TODO: convert sourceRange() into stack_trace + # fx_node.meta["stack_trace"] = node.sourceRange() + + output_name = node.output().debugName() + self.name_to_node[output_name] = fx_node + return + + self.convert_call_function_op(node) + + def convert_aten___getitem__(self, node: torch._C.Node): + input_container, index = tuple( + self.get_fx_value_by_ir_value(input) for input in node.inputs() + ) + fx_node = self.fx_graph.call_function( + operator.getitem, (input_container, index) + ) + output_name = node.output().debugName() + self.name_to_node[output_name] = fx_node + + def convert_aten_to(self, node: torch._C.Node): + target = get_op_overload(node) + args, _kwargs = self.get_args_kwargs(node, target._schema) + + # special handle aten.to.dtype and aten.to.prim_dtype followed by inplace_mutation_op + # coz aten.to + inplace_mutation_op pattern would trigger + # "cannot mutate tensors with frozen storage" functionalization error. + # To work around the issue, we override the copy to be True, so that the output + # is for sure not an alias of input + if target is torch.ops.aten.to.dtype or target is torch.ops.aten.to.prim_dtype: + user_nodes = [use.user for use in node.output().uses()] + user_targets = [ + get_op_overload(user_node) + for user_node in user_nodes + if user_node.schema() != "(no schema)" + ] + has_mutable_target = any( + target._schema.is_mutable for target in user_targets + ) + + if has_mutable_target: + if len(args) < 4: + raise AssertionError(f"expected at least 4 args, got {len(args)}") + new_args = list(args) + new_args[3] = True # copy, override to True + fx_node = self.fx_graph.call_function( + torch.ops.aten.to.dtype, tuple(new_args) + ) + # temp hack to work around the issue https://github.com/pytorch/pytorch/issues/131679 + # When this issue is fixed, the clone node would be no longer needed + clone_node = self.fx_graph.call_function( + torch.ops.aten.clone.default, (fx_node,) + ) + output_name = node.output().debugName() + self.name_to_node[output_name] = clone_node + return + + self.convert_call_function_op(node) + + def convert_aten_add(self, node: torch._C.Node): + if node.schema() == "(no schema)": + if isinstance(node.inputsAt(0).type(), torch.ListType) and isinstance( + node.inputsAt(1).type(), torch.ListType + ): + target = torch.ops.aten.add.t + else: + raise RuntimeError(f"unable to determined the target for {node}") + else: + target = get_op_overload(node) + + if target is torch.ops.aten.add.t: + # special handle python list/tuple add: "aten::add.t(t[] a, t[] b) -> t[]" for + # RuntimeError: aten::add() Expected a value of type 'List[t]' for argument 'a' but instead found type 'immutable_list'. + args, _kwargs = self.get_args_kwargs(node, target._schema) + output_name = node.output().debugName() + self.name_to_node[output_name] = self.fx_graph.call_function(list_add, args) + else: + self.convert_call_function_op(node) + + def _check_prim_loop_support(self, node): + inputs = list(node.inputs()) + + # TODO: (1/N) stage. + if inputs[0].debugName() not in self.name_to_constant: + raise RuntimeError( + "prim::Loop currently cannot run with dynamic value of number of iterations." + ) + + # Make sure the condition is not updated in the subblock. + subblock = next(node.blocks()) + condition_output_name = next(subblock.outputs()).debugName() + for node in subblock.nodes(): + if ( + node.outputsSize() == 1 + and node.output().debugName() == condition_output_name + ): + raise RuntimeError( + "prim::Loop currently cannot run with dynamic value of condition." + ) + if node.outputsSize() >= 2: + for outp in node.outputs(): + if outp.debugName() == condition_output_name: + raise RuntimeError( + "prim::Loop currently cannot run with dynamic value of condition." + ) + + def convert_prim_Loop(self, node: torch._C.Node): + inputs = list(node.inputs()) + self._check_prim_loop_support(node) + + num_iterations = self.get_fx_value_by_ir_value(inputs[0]) + + # Find inputs. + loop_local_arguments = [inp.debugName() for inp in inputs[2:]] + + global_arguments = self._identify_inputs_as_arguments(node) + + # Lift parameters as inputs. + for block in node.blocks(): + global_arguments = global_arguments.union( + self.blocks_to_lifted_attrs[block] + ) + + global_arguments = list(global_arguments) + + subgraph_nodes, subgraph_converters = self._convert_block_to_subgraph( + node, global_arguments + ) + + if len(subgraph_nodes) != 1: + raise AssertionError(f"expected 1 subgraph node, got {len(subgraph_nodes)}") + subgraph_converter = subgraph_converters[0] + if not self.is_top_level_graph(): + self.name_update_from_subblock_to_parent = ( + self.name_update_from_subblock_to_parent.union( + subgraph_converter.name_update_from_subblock_to_parent + ) + ) + + fx_block_args = [ + self.get_fx_value_by_fqn(name) + for name in loop_local_arguments + global_arguments + ] + for iter_idx in range(num_iterations): + loop_node = self.fx_graph.call_function( + execute_subgraph_from_prim_loop, + # Check execute_node function for the expected arguments order. + ( + subgraph_nodes[0], + iter_idx, + len(loop_local_arguments), + *fx_block_args, + ), + {}, + ) + + # Update the value of loop local variables. + if node.outputsSize() >= 1: + for i, outp in enumerate(node.outputs()): + output_name = outp.debugName() + self.name_to_node[output_name] = self.fx_graph.call_function( + operator.getitem, + ( + loop_node, + i + 1, + ), # + 1 because the 0th element is the condition. + ) + fx_block_args[i] = self.name_to_node[output_name] + + # Update the value of global variables, whose values are modified inplace. + + for i, name in enumerate( + subgraph_converter.name_update_from_subblock_to_parent + ): + self.name_to_node[name] = self.fx_graph.call_function( + operator.getitem, + ( + loop_node, + i + node.outputsSize() + 1, + ), # + 1 because the 0th element is the condition. + ) + global_argument_index = global_arguments.index(name) + fx_block_args[i + node.outputsSize() + global_argument_index] = ( + self.name_to_node[name] + ) + + def _check_set_attr_in_if_block(self, if_node: torch._C.Node): + for block in if_node.blocks(): + for node in block.nodes(): + if node.kind() == "prim::SetAttr": + raise RuntimeError( + "During converting prim::If to torch.cond, found prim::SetAttr op" + " which is not supported yet. Please file an issue if you come " + "across this error." + ) + + def convert_prim_If(self, node: torch._C.Node): + self._check_set_attr_in_if_block(node) + + inputs = list(node.inputs()) + if len(inputs) != 1: + raise AssertionError(f"expected 1 input for prim::If, got {len(inputs)}") + predicate = self.get_fx_value_by_ir_value(inputs[0]) + + # Find inputs. + arguments = self._identify_inputs_as_arguments(node) + + # Lift parameters as inputs. + for block in node.blocks(): + arguments = arguments.union(self.blocks_to_lifted_attrs[block]) + + arguments = list(arguments) + subgraph_nodes, _ = self._convert_block_to_subgraph(node, arguments) + + if len(subgraph_nodes) != 2: + raise AssertionError( + f"expected 2 subgraph nodes, got {len(subgraph_nodes)}" + ) + + fx_block_args = [self.get_fx_value_by_fqn(name) for name in arguments] + + args = ( + predicate, + subgraph_nodes[0], + subgraph_nodes[1], + tuple(fx_block_args), + ) + + cond_node = self.fx_graph.call_function(torch.cond, args, {}) + + # prim::If can also have zero output. + if node.outputsSize() == 1: + output_name = node.output().debugName() + self.name_to_node[output_name] = cond_node + elif node.outputsSize() > 1: + for i, output in enumerate(node.outputs()): + output_name = output.debugName() + getitem = self.fx_graph.call_function(operator.getitem, (cond_node, i)) + self.name_to_node[output_name] = getitem + + def convert_aten_Bool(self, node: torch._C.Node): + self._convert_as_noop(node) + + def convert_prim_Enter(self, node: torch._C.Node): + # export generally treats prim::Enter as noop + # The only context manager export supports is aten::enable_grad. + # Unfortunately, TorchScript does not support aten::enable_grad yet. + # TODO: support aten::enable_grad in both TorchScript and Converter. + return + + def convert_prim_Exit(self, node: torch._C.Node): + # export treats prim::Exit as noop + return + + def _convert_as_noop(self, node: torch._C.Node): + # Converts the node as a no-op by mapping its output node as arg[0] + + target = get_op_overload(node) + schema = target._schema + + args, _kwargs = self.get_args_kwargs(node, schema) + + output_name = node.output().debugName() + self.name_to_node[output_name] = args[0] + + def convert_profiler__record_function_exit(self, node: torch._C.Node): + # _record_function_exit has side effect so we keep it in fx.graph + # currently, _record_function_enter_new and _record_function_exit are + # discarded during `retrace_as_exported_program`. + target = torch.ops.profiler._record_function_exit + args = tuple(self.get_fx_value_by_ir_value(input) for input in node.inputs()) + self.fx_graph.call_function(target, args) + + def convert_prim_tolist(self, node: torch._C.Node): + # prim::tolist cannot be supported by `_convert_standard_operators` + # since it requires call_method instead of call_function. + target = "tolist" + args = (self.get_fx_value_by_ir_value(next(node.inputs())),) + fx_node = self.fx_graph.call_method(target, args) + output_name = node.output().debugName() + self.name_to_node[output_name] = fx_node + + def convert_prim_Uninitialized(self, node: torch._C.Node): + # `prim::Uninitialized` is inserted by the compiler when it can prove + # the value will never be used. It can be introduced by exceptions, + # breaks, continues, and returns. + # So we add a dummy constant to the graph. + output_name = node.output().debugName() + self.name_to_constant[output_name] = torch.Tensor() + + def _convert_standard_operators(self, node: torch._C.Node): + target = kind_to_standard_operators[node.kind()] + args = tuple(self.get_fx_value_by_ir_value(input) for input in node.inputs()) + fx_node = self.fx_graph.call_function(target, args) + output_name = node.output().debugName() + self.name_to_node[output_name] = fx_node + + def convert_node(self, node: torch._C.Node): + node_kind = node.kind() + + # Get handler based on namespace and operator name. + # Provide a default node handler as well in case we don't find + # matching converter for that. + handler_func_name = ir_name_to_func_name(node_kind) + handler_func = getattr(self, handler_func_name, self.convert_call_function_op) + + # str calls print function implemented in CPP. To avoid repeating + # the entire logic here, we simply keep first line from node string (getting rid + # of sub-blocks IR prints). + node_str = "".join(str(node).split("\n")[:1]) + log.debug("[%s] converts [%s]", handler_func.__name__, node_str) + try: + handler_func(node) + except Exception as e: + raise RuntimeError(f"TS2EPConverter failed for node {node_kind}") from e + + def convert_graph_outputs(self): + args = [] + outp_name_list = [outp.debugName() for outp in self.ts_graph.outputs()] + list( + self.name_update_from_subblock_to_parent + ) + for output_name in outp_name_list: + if output_name in self.name_to_node: + fx_node = self.name_to_node[output_name] + # TODO: Revisit this later after HigherOrderOp design changes. + # Currently, we cannot directly return input as output. + if ( + not self.is_top_level_graph() + and isinstance(fx_node, torch.fx.Node) + and fx_node.op == "placeholder" + ): + fx_node = self.fx_graph.call_function(torch.clone, (fx_node,)) + args.append(fx_node) + self.output_specs.append( + OutputSpec( + OutputKind.USER_OUTPUT, + arg=TensorArgument(name=output_name), + target=output_name, + ) + ) + elif output_name in self.name_to_constant: + args.append(self.name_to_constant[output_name]) + self.output_specs.append( + OutputSpec( + OutputKind.USER_OUTPUT, + arg=ConstantArgument( + name=output_name, value=self.name_to_constant[output_name] + ), + target=output_name, + ) + ) + else: + raise ValueError(f"Output {output_name} not found") + + if len(args) == 0: + # Sub-block of prim::If can have zero output. + self.fx_graph.output([]) + elif len(args) == 1: + self.fx_graph.output( + args[0] + ) # Get rid of an extra list wrapped around final output. + elif len(args) > 1: + self.fx_graph.output( + args + ) # For prim::Loop and prim::If with multiple outputs. + else: + # Sub-block of prim::Loop can have multiple outputs. + self.fx_graph.output(args) + + +class ExplainTS2FXGraphConverter(TS2FXGraphConverter): + """ + Run TS2FXGraphConverter in an explain mode. It collects all failed operators conversions + and provide that information to users. In order to collect all failed conversions, it + also mocks some internal attributes (e.g., name_to_node). + """ + + class _DictMock(dict): + def __init__(self, dict_data, mock_value): + super().__init__(dict_data) + self.mock_value = mock_value + + def __getitem__(self, key): + # If the original dictionary has the key, return its value. + # Otherwise, return the mock value. + if not super().__contains__(key): + return self.mock_value + return super().__getitem__(key) + + def __contains__(self, key): + return True + + def __init__( + self, + ts_graph: torch._C.Graph | torch._C.Block, + name_to_param: dict[str, torch.Tensor], + name_to_buffer: dict[str, torch.Tensor], + blocks_to_lifted_attrs: dict[torch._C.Block, set[str]], + name_to_non_tensor_attribute: dict[str, Any], + name_to_constant: dict[str, Any], + name_to_attribute_fqn: dict[str, str], + ): + super().__init__( + ts_graph, + name_to_param, + name_to_buffer, + blocks_to_lifted_attrs, + name_to_non_tensor_attribute, + name_to_constant, + name_to_attribute_fqn, + ) + + # Data to keep track of unsupported nodes. + self.unsupported_node_list: list[torch._C.Node] = [] + + # Add mock to needed attributes. + self.name_to_node = ExplainTS2FXGraphConverter._DictMock( + self.name_to_node, + # Dummy node. + torch.fx.Node( + None, # type: ignore[arg-type] + "mock", + "call_function", + lambda: None, + (), + {}, + ), + ) + + def explain(self): + self.convert_graph_inputs() + for node in self.ts_graph.nodes(): + self.convert_node(node) + self.convert_graph_outputs() + + def convert_node(self, node): + try: + super().convert_node(node) + except Exception: + self.unsupported_node_list.append(node) + + +@contextmanager +def disable_logging(log): + disabled = log.disabled + log.disabled = True + try: + yield + finally: + log.disabled = disabled + + +class TS2EPConverter: + # TorchScript model to ExportedProgram converter + def __init__( + self, + ts_model: torch.jit.ScriptModule | torch.jit.ScriptFunction, + sample_args: tuple[Any, ...], + sample_kwargs: dict[str, Any] | None = None, + ): + self.ts_model = ts_model + self.ts_graph, self.params, _, _ = _create_jit_graph(ts_model, sample_args) + + self.sample_args = sample_args + self.sample_kwargs = sample_kwargs + + self.name_to_param: dict[str, torch.Tensor] = {} + self.name_to_buffer: dict[str, torch.Tensor] = {} + param_list = ( + list(self.ts_model.parameters()) + if not isinstance(self.ts_model, torch._C.ScriptFunction) + else [] + ) + if not isinstance(self.ts_model, torch._C.ScriptFunction): + for k, tensor in self.ts_model.state_dict().items(): # type: ignore[union-attr] + # Check if tensor belongs to any parameter. + if any( + (tensor == param).all() + for param in param_list + if tensor.shape == param.shape + ): + self.name_to_param[k] = tensor + else: + self.name_to_buffer[k] = tensor + + self.name_to_non_tensor_attributes: dict[str, Any] = {} + self.name_to_constant: dict[str, Any] = {} + + self.lift_get_attr() + + def convert(self) -> ExportedProgram: + log.info( + """ +TS2EPConverter logging starts from here. + +INFO: (TORCH_LOGS="export" ) + * Log TorchScript IR. + +DEBUG: (TORCH_LOGS="+export" ), additionally + * Log conversion IR by IR in a format of [] converts []. + """ + ) + log.info("TorchScript graph\n\n%s\n", self.ts_graph) + + blocks_to_lifted_attrs, name_to_attribute_fqn = get_block_to_lifted_attrs( + self.ts_graph + ) + + graph_converter = TS2FXGraphConverter( + self.ts_graph, + self.name_to_param, + self.name_to_buffer, + blocks_to_lifted_attrs, + self.name_to_non_tensor_attributes, + self.name_to_constant, + name_to_attribute_fqn, + ) + gm = graph_converter.convert() + + # Post-processing step to deal with quantized operators. + replace_quantized_ops_with_standard_ops(gm) + log.info("GraphModule: %s", gm.print_readable(print_output=False)) + + ep = self.retrace_as_exported_program( + gm, + graph_converter.name_to_constant, + ) + log.info("%s", ep) + + # Post-processing step to ensure ExportedProgram has the same state_dict as + # the original TorchScript model. Throw warnings for additionally populated + # state_dict entries. + if not isinstance(self.ts_model, torch._C.ScriptFunction): + for k, tensor in self.ts_model.state_dict().items(): # type: ignore[union-attr] + if k not in ep.state_dict: + warnings.warn( + f"Manually populate {k} into state_dict ExportedProgram, but it is never used by the ExportedProgram.", + stacklevel=2, + ) + ep.state_dict[k] = tensor + + return ep + + @disable_logging(log) + def explain(self, print_output=True): + blocks_to_lifted_attrs, name_to_attribute_fqn = get_block_to_lifted_attrs( + self.ts_graph + ) + + graph_converter = ExplainTS2FXGraphConverter( + self.ts_graph, + self.name_to_param, + self.name_to_buffer, + blocks_to_lifted_attrs, + self.name_to_non_tensor_attributes, + self.name_to_constant, + name_to_attribute_fqn, + ) + graph_converter.explain() + if len(graph_converter.unsupported_node_list) > 0: + explain_str = "Unsupported nodes are found in the following list:" + for i, n in enumerate(graph_converter.unsupported_node_list): + node_str = "".join(str(n).split("\n")[:1]) + explain_str += f"\n\n {i}. {n.kind()} [{node_str}]" + else: + explain_str = "Success!" + if print_output: + print(explain_str) + return explain_str + + def retrace_as_exported_program( + self, + gm: torch.fx.GraphModule, + name_to_constant: dict[str, Any], + ): + dynamic_shapes = _tree_map_with_path( + lambda path, x: ( + [Dim.AUTO] * x.dim() if isinstance(x, torch.Tensor) else None + ), + self.sample_args, + ) + + # TODO: adjust input orders to match GraphSignature convention + ep = torch.export._trace._export( + gm, + self.sample_args, + dynamic_shapes=dynamic_shapes, + strict=False, + pre_dispatch=True, + ) + + # Post-processing to make sure the ExportedProgram states are correct. + # Because during conversion, we set tensor constants as GetAttr, + # retracing cannot recognize them as tensor constants but instead + # treat them as buffers. We need to set them again here. + ep._constants.update( + { + k: v + for k, v in name_to_constant.items() + if isinstance(v, (torch.Tensor, torch.ScriptObject)) + } + ) + for k in name_to_constant: + ep.state_dict.pop(k, None) + + for spec in ep.graph_signature.input_specs: + # Mark as constant tensors for erroneously traced buffers. + if spec.kind == InputKind.BUFFER and spec.target in name_to_constant: + if not isinstance(name_to_constant[spec.target], torch.Tensor): + raise AssertionError( + f"{type(name_to_constant[spec.target])} has been erroneously marked as buffer" + ) + spec.kind = InputKind.CONSTANT_TENSOR + spec.persistent = None + ep.verifier().check(ep) + + return ep + + def lift_get_attr(self): + # This function lifts multiple data types. + + # 1. Tensor constants attributes (e.g., self.data = torch.tensor([2,3])) + # to buffers. Currently, when there are tensor constants, export + # would error and ask users to register tensor constants as buffers. + # Since it is hard to manually do so for TorchScript models + # (e.g., source code is missing), this function automatically + # lifts tensor constants to be buffers. + + # 2. ScriptObbject to constant. It will then be converted to getattr in + # in the fx graph. + # + # This function should happen in TS2EPConverter instead of + # TS2FXGraphConverter since it gets attributes from self.ts_model + # which is not accessible in TS2FXGraphConverter. It is similar to where + # we collect self.name_to_param and self.name_to_buffer. + name_to_attribute_fqn: dict[str, str] = {} + + def get_attr(fqn: str): + name = fqn.split(".") + v = self.ts_model + for n in name: + v = getattr(v, n) + return v + + def get_fqn(node: torch._C.Node): + attr_name = node.s("name") + input_name = node.input().debugName() + root_attr_name = name_to_attribute_fqn[input_name] + attr_fqn = f"{root_attr_name}.{attr_name}" if root_attr_name else attr_name + return attr_fqn + + def _dfs_get_attr(block): + for node in block.nodes(): + if node.kind() == "prim::CreateObject": + output_name = node.output().debugName() + name_to_attribute_fqn[output_name] = "" + + if node.kind() == "prim::GetAttr": + attr_fqn = get_fqn(node) + value = get_attr(attr_fqn) + output_name = node.output().debugName() + name_to_attribute_fqn[output_name] = attr_fqn + if isinstance(value, torch.Tensor): + if attr_fqn not in self.name_to_buffer: + # Lift tensor constants to be a buffer + self.name_to_buffer[attr_fqn] = value + elif isinstance(value, torch.ScriptObject): + if attr_fqn not in self.name_to_constant: + self.name_to_constant[attr_fqn] = value + else: + self.name_to_non_tensor_attributes[attr_fqn] = value + + for subblock in node.blocks(): + _dfs_get_attr(subblock) + + _dfs_get_attr(self.ts_graph) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/__init__.py b/.venv/lib/python3.12/site-packages/torch/_export/db/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10a55772ab58b21573a6eba0356ddd3080164ac7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/__init__.py @@ -0,0 +1,5 @@ +# 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. diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f3f86783f6df5ad23665eab3adc8fe2c9f18d34 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/case.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/case.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f5f00281eac327b547f758294be3ed2ba9d200b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/case.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/gen_example.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/gen_example.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..edf515e1b1524b0763d6741b22a8a575b4a0e155 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/gen_example.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/logging.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/logging.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea225412fa0566e46d2aad4bda0ab6f376fd9248 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/__pycache__/logging.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/case.py b/.venv/lib/python3.12/site-packages/torch/_export/db/case.py new file mode 100644 index 0000000000000000000000000000000000000000..476fe9793a55ca6cf91277da97a8c7c5c02223f1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/case.py @@ -0,0 +1,177 @@ +# mypy: allow-untyped-defs +import inspect +import re +import string +from dataclasses import dataclass, field +from enum import Enum +from typing import Any +from types import ModuleType + +import torch + +_TAGS: dict[str, dict[str, Any]] = { + "torch": { + "cond": {}, + "dynamic-shape": {}, + "escape-hatch": {}, + "map": {}, + "dynamic-value": {}, + "operator": {}, + "mutation": {}, + }, + "python": { + "assert": {}, + "builtin": {}, + "closure": {}, + "context-manager": {}, + "control-flow": {}, + "data-structure": {}, + "standard-library": {}, + "object-model": {}, + }, +} + + +class SupportLevel(Enum): + """ + Indicates at what stage the feature + used in the example is handled in export. + """ + + SUPPORTED = 1 + NOT_SUPPORTED_YET = 0 + + +ArgsType = tuple[Any, ...] + + +def check_inputs_type(args, kwargs): + if not isinstance(args, tuple): + raise ValueError( + f"Expecting args type to be a tuple, got: {type(args)}" + ) + if not isinstance(kwargs, dict): + raise ValueError( + f"Expecting kwargs type to be a dict, got: {type(kwargs)}" + ) + for key in kwargs: + if not isinstance(key, str): + raise ValueError( + f"Expecting kwargs keys to be a string, got: {type(key)}" + ) + +def _validate_tag(tag: str): + parts = tag.split(".") + t = _TAGS + for part in parts: + if not set(part) <= set(string.ascii_lowercase + "-"): + raise AssertionError(f"Tag contains invalid characters: {part}") + if part in t: + t = t[part] + else: + raise ValueError(f"Tag {tag} is not found in registered tags.") + + +@dataclass(frozen=True) +class ExportCase: + example_args: ArgsType + description: str # A description of the use case. + model: torch.nn.Module + name: str + example_kwargs: dict[str, Any] = field(default_factory=dict) + extra_args: ArgsType | None = None # For testing graph generalization. + # Tags associated with the use case. (e.g dynamic-shape, escape-hatch) + tags: set[str] = field(default_factory=set) + support_level: SupportLevel = SupportLevel.SUPPORTED + dynamic_shapes: dict[str, Any] | None = None + + def __post_init__(self): + check_inputs_type(self.example_args, self.example_kwargs) + if self.extra_args is not None: + check_inputs_type(self.extra_args, {}) + + for tag in self.tags: + _validate_tag(tag) + + if not isinstance(self.description, str) or len(self.description) == 0: + raise ValueError(f'Invalid description: "{self.description}"') + + +_EXAMPLE_CASES: dict[str, ExportCase] = {} +_MODULES: set[ModuleType] = set() +_EXAMPLE_CONFLICT_CASES: dict[str, list[ExportCase]] = {} +_EXAMPLE_REWRITE_CASES: dict[str, list[ExportCase]] = {} + + +def register_db_case(case: ExportCase) -> None: + """ + Registers a user provided ExportCase into example bank. + """ + if case.name in _EXAMPLE_CASES: + if case.name not in _EXAMPLE_CONFLICT_CASES: + _EXAMPLE_CONFLICT_CASES[case.name] = [_EXAMPLE_CASES[case.name]] + _EXAMPLE_CONFLICT_CASES[case.name].append(case) + return + + _EXAMPLE_CASES[case.name] = case + + +def to_snake_case(name): + name = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name) + return re.sub("([a-z0-9])([A-Z])", r"\1_\2", name).lower() + + +def _make_export_case(m, name, configs): + if not isinstance(m, torch.nn.Module): + raise TypeError("Export case class should be a torch.nn.Module.") + + if "description" not in configs: + # Fallback to docstring if description is missing. + if m.__doc__ is None: + raise AssertionError( + f"Could not find description or docstring for export case: {m}" + ) + configs = {**configs, "description": m.__doc__} + # pyrefly: ignore [bad-argument-type] + return ExportCase(**{**configs, "model": m, "name": name}) + + +def export_case(**kwargs): + """ + Decorator for registering a user provided case into example bank. + """ + + def wrapper(m): + configs = kwargs + module = inspect.getmodule(m) + if module in _MODULES: + raise RuntimeError("export_case should only be used once per example file.") + + if module is None: + raise AssertionError("module must not be None") + _MODULES.add(module) + module_name = module.__name__.split(".")[-1] + case = _make_export_case(m, module_name, configs) + register_db_case(case) + return case + + return wrapper + + +def export_rewrite_case(**kwargs): + def wrapper(m): + configs = kwargs + + parent = configs.pop("parent") + if not isinstance(parent, ExportCase): + raise AssertionError(f"expected ExportCase, got {type(parent)}") + key = parent.name + if key not in _EXAMPLE_REWRITE_CASES: + _EXAMPLE_REWRITE_CASES[key] = [] + + configs["example_args"] = parent.example_args + case = _make_export_case(m, to_snake_case(m.__name__), configs) + _EXAMPLE_REWRITE_CASES[key].append(case) + return case + + return wrapper diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__init__.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..834dbce32f10bfb339fd2182a2455b43914441c9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__init__.py @@ -0,0 +1,61 @@ +# mypy: allow-untyped-defs +import dataclasses +import glob +import inspect +from os.path import basename, dirname, isfile, join + +import torch +from torch._export.db.case import ( + _EXAMPLE_CASES, + _EXAMPLE_CONFLICT_CASES, + _EXAMPLE_REWRITE_CASES, + SupportLevel, + export_case, + ExportCase, +) + + +def _collect_examples(): + case_names = glob.glob(join(dirname(__file__), "*.py")) + case_names = [ + basename(f)[:-3] for f in case_names if isfile(f) and not f.endswith("__init__.py") + ] + + case_fields = {f.name for f in dataclasses.fields(ExportCase)} + for case_name in case_names: + case = __import__(case_name, globals(), locals(), [], 1) + variables = [name for name in dir(case) if name in case_fields] + export_case(**{v: getattr(case, v) for v in variables})(case.model) + +_collect_examples() + +def all_examples(): + return _EXAMPLE_CASES + + +if len(_EXAMPLE_CONFLICT_CASES) > 0: + + def get_name(case): + model = case.model + if isinstance(model, torch.nn.Module): + model = type(model) + return model.__name__ + + msg = "Error on conflict export case name.\n" + for case_name, cases in _EXAMPLE_CONFLICT_CASES.items(): + msg += f"Case name {case_name} is associated with multiple cases:\n " + msg += f"[{','.join(map(get_name, cases))}]\n" + + raise RuntimeError(msg) + + +def filter_examples_by_support_level(support_level: SupportLevel): + return { + key: val + for key, val in all_examples().items() + if val.support_level == support_level + } + + +def get_rewrite_cases(case): + return _EXAMPLE_REWRITE_CASES.get(case.name, []) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..46cb4cd7f3249e44331f0f3dbd67ae2e8a9d7b1a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/assume_constant_result.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/assume_constant_result.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff5cf018ab885925cbba6274a12d268e0706b037 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/assume_constant_result.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/autograd_function.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/autograd_function.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4246922e767e992cd50423e050081818645106e3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/autograd_function.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/class_method.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/class_method.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..852515d19969847c998477fa2e860178c82a2060 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/class_method.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_branch_class_method.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_branch_class_method.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f1b013c91358b1b6037eabdd9b5369004a75fd8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_branch_class_method.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_branch_nested_function.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_branch_nested_function.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1068490e888c002a08b39e7807f025720a3c214 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_branch_nested_function.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_branch_nonlocal_variables.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_branch_nonlocal_variables.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4e65f0aed3a5dec4eaffa7cf08a70a0d8409b8c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_branch_nonlocal_variables.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_closed_over_variable.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_closed_over_variable.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d35fadcec4dd40508cd7e60ab4dca8fa33d20496 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_closed_over_variable.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_operands.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_operands.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1220fa29573be247cc003477e03693b9a0a4395 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_operands.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_predicate.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_predicate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8d7be07e6888ba2c159fe5be7865681bfe96047 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/cond_predicate.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/constrain_as_size_example.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/constrain_as_size_example.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c59e609a066bbdfeea6ed9a790795c54572b1ab3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/constrain_as_size_example.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/constrain_as_value_example.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/constrain_as_value_example.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b7462aad83acfda21ee48caf15cbc41a2be7fdc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/constrain_as_value_example.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/decorator.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/decorator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f185552fb8c13f32b621e4b701e626d9026868f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/decorator.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dictionary.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dictionary.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f958d46f2a5fe93d3d12f8b4915273761b5bff43 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dictionary.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_assert.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_assert.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..162c7bff02cd89662c9a18778d6d424f6167a3e2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_assert.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_constructor.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_constructor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cec7cc7f5633233b9697142b4a7d43a85f48af25 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_constructor.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_if_guard.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_if_guard.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10e871bcea7f053132ff02cc5e3bbd6751f43061 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_if_guard.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_map.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_map.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08702b2c486eea377bd6bdfbefe8af4c22c1b881 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_map.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_round.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_round.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b29f375207cc044ea2873c7150092ad3eb462f4f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_round.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_slicing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_slicing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..166878dce89061b9e0376ae1d9865c98c05446b8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_slicing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_view.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_view.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09400082b59ce3eb9266025d0371daddceb90e52 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/dynamic_shape_view.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/fn_with_kwargs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/fn_with_kwargs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6bb2385550ec0717e352d8dd87524b5ca3d80da Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/fn_with_kwargs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/list_contains.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/list_contains.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d9779979def8587a5cb9bc4ef824367d8ab0fb8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/list_contains.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/list_unpack.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/list_unpack.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7fd05bca4d6aeb2dfe2d684a2a7561210320b73 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/list_unpack.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/model_attr_mutation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/model_attr_mutation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b34e35d572ccb6cce6ca288d38219b72009681f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/model_attr_mutation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/nested_function.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/nested_function.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2286b1ea65ac5a5757fad2cbcf133d71b912432f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/nested_function.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/null_context_manager.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/null_context_manager.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e539314149a92dad2d0f9e88d1116676994ca023 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/null_context_manager.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/optional_input.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/optional_input.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6b6f100ba36d857f4d75daf536f25164d646d8d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/optional_input.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/pytree_flatten.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/pytree_flatten.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..320a96c0e3b816ddb5ac49ca4c3768a54825fa78 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/pytree_flatten.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/scalar_output.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/scalar_output.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2ead47343b7bcc6352918077240c9afe8acc49f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/scalar_output.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/specialized_attribute.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/specialized_attribute.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eed7840364121d6454d3c388135c772bedd55ee7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/specialized_attribute.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/static_for_loop.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/static_for_loop.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35739d45fcf1362d29dbcf40ecfc4664eabfe51d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/static_for_loop.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/static_if.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/static_if.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce25b9f99fc7737ddfe618240e8bbac061df4b6c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/static_if.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/tensor_setattr.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/tensor_setattr.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3142719fac0137122f16d8d92e71f5fa7aeac048 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/tensor_setattr.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/type_reflection_method.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/type_reflection_method.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b995e6d5ccb007524f206ea92391c1cf86c9b02d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/type_reflection_method.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/unsupported_operator.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/unsupported_operator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e9b104fae57dc34b2dd659c9ca151a68e659100 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/unsupported_operator.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/user_input_mutation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/user_input_mutation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4cabbc012f13537ce1a2760a27bb0e34d7d376e2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/__pycache__/user_input_mutation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/assume_constant_result.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/assume_constant_result.py new file mode 100644 index 0000000000000000000000000000000000000000..ccd66f6c6f937004db4798a68719ce60fedc79c9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/assume_constant_result.py @@ -0,0 +1,20 @@ +# mypy: allow-untyped-defs +import torch +import torch._dynamo as torchdynamo + + +class AssumeConstantResult(torch.nn.Module): + """ + Applying `assume_constant_result` decorator to burn make non-traceable code as constant. + """ + + @torchdynamo.assume_constant_result + def get_item(self, y): + return y.int().item() + + def forward(self, x, y): + return x[: self.get_item(y)] + +example_args = (torch.randn(3, 2), torch.tensor(4)) +tags = {"torch.escape-hatch"} +model = AssumeConstantResult() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/autograd_function.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/autograd_function.py new file mode 100644 index 0000000000000000000000000000000000000000..efd645d13a7d5a13dc69d9ab3593772520b726c0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/autograd_function.py @@ -0,0 +1,25 @@ +# mypy: allow-untyped-defs +import torch + +class MyAutogradFunction(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward(ctx, x): + return x.clone() + + @staticmethod + # pyrefly: ignore [bad-override] + def backward(ctx, grad_output): + return grad_output + 1 + +class AutogradFunction(torch.nn.Module): + """ + TorchDynamo does not keep track of backward() on autograd functions. We recommend to + use `allow_in_graph` to mitigate this problem. + """ + + def forward(self, x): + return MyAutogradFunction.apply(x) + +example_args = (torch.randn(3, 2),) +model = AutogradFunction() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/class_method.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/class_method.py new file mode 100644 index 0000000000000000000000000000000000000000..f701f54d4f4ea1cb5816292cd60bb4df3d03c5e8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/class_method.py @@ -0,0 +1,22 @@ +# mypy: allow-untyped-defs +import torch + +class ClassMethod(torch.nn.Module): + """ + Class methods are inlined during tracing. + """ + + @classmethod + def method(cls, x): + return x + 1 + + def __init__(self) -> None: + super().__init__() + self.linear = torch.nn.Linear(4, 2) + + def forward(self, x): + x = self.linear(x) + return self.method(x) * self.__class__.method(x) * type(self).method(x) + +example_args = (torch.randn(3, 4),) +model = ClassMethod() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_branch_class_method.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_branch_class_method.py new file mode 100644 index 0000000000000000000000000000000000000000..1bf9b8de296e4f4b61cf0f2666c02fda25ae60f2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_branch_class_method.py @@ -0,0 +1,44 @@ +# mypy: allow-untyped-defs +import torch + +from functorch.experimental.control_flow import cond + +class MySubModule(torch.nn.Module): + def foo(self, x): + return x.cos() + + def forward(self, x): + return self.foo(x) + +class CondBranchClassMethod(torch.nn.Module): + """ + The branch functions (`true_fn` and `false_fn`) passed to cond() must follow these rules: + - both branches must take the same args, which must also match the branch args passed to cond. + - both branches must return a single tensor + - returned tensor must have the same tensor metadata, e.g. shape and dtype + - branch function can be free function, nested function, lambda, class methods + - branch function can not have closure variables + - no inplace mutations on inputs or global variables + + + This example demonstrates using class method in cond(). + + NOTE: If the `pred` is tested on a dim with batch size < 2, it will be specialized. + """ + + def __init__(self) -> None: + super().__init__() + self.subm = MySubModule() + + def bar(self, x): + return x.sin() + + def forward(self, x): + return cond(x.shape[0] <= 2, self.subm.forward, self.bar, [x]) + +example_args = (torch.randn(3),) +tags = { + "torch.cond", + "torch.dynamic-shape", +} +model = CondBranchClassMethod() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_branch_nested_function.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_branch_nested_function.py new file mode 100644 index 0000000000000000000000000000000000000000..ab52d8c8cde45d0855d6807df3081c72f9ab97da --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_branch_nested_function.py @@ -0,0 +1,41 @@ +# mypy: allow-untyped-defs +import torch + +from functorch.experimental.control_flow import cond + +class CondBranchNestedFunction(torch.nn.Module): + """ + The branch functions (`true_fn` and `false_fn`) passed to cond() must follow these rules: + - both branches must take the same args, which must also match the branch args passed to cond. + - both branches must return a single tensor + - returned tensor must have the same tensor metadata, e.g. shape and dtype + - branch function can be free function, nested function, lambda, class methods + - branch function can not have closure variables + - no inplace mutations on inputs or global variables + + This example demonstrates using nested function in cond(). + + NOTE: If the `pred` is tested on a dim with batch size < 2, it will be specialized. + """ + + def forward(self, x): + def true_fn(x): + def inner_true_fn(y): + return x + y + + return inner_true_fn(x) + + def false_fn(x): + def inner_false_fn(y): + return x - y + + return inner_false_fn(x) + + return cond(x.shape[0] < 10, true_fn, false_fn, [x]) + +example_args = (torch.randn(3),) +tags = { + "torch.cond", + "torch.dynamic-shape", +} +model = CondBranchNestedFunction() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_branch_nonlocal_variables.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_branch_nonlocal_variables.py new file mode 100644 index 0000000000000000000000000000000000000000..73df8add4703186bd3a0219b9e4eb845f35e0811 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_branch_nonlocal_variables.py @@ -0,0 +1,59 @@ +# mypy: allow-untyped-defs +import torch + +from functorch.experimental.control_flow import cond + +class CondBranchNonlocalVariables(torch.nn.Module): + """ + The branch functions (`true_fn` and `false_fn`) passed to cond() must follow these rules: + - both branches must take the same args, which must also match the branch args passed to cond. + - both branches must return a single tensor + - returned tensor must have the same tensor metadata, e.g. shape and dtype + - branch function can be free function, nested function, lambda, class methods + - branch function can not have closure variables + - no inplace mutations on inputs or global variables + + This example demonstrates how to rewrite code to avoid capturing closure variables in branch functions. + + The code below will not work because capturing closure variables is not supported. + ``` + my_tensor_var = x + 100 + my_primitive_var = 3.14 + + def true_fn(y): + nonlocal my_tensor_var, my_primitive_var + return y + my_tensor_var + my_primitive_var + + def false_fn(y): + nonlocal my_tensor_var, my_primitive_var + return y - my_tensor_var - my_primitive_var + + return cond(x.shape[0] > 5, true_fn, false_fn, [x]) + ``` + + NOTE: If the `pred` is tested on a dim with batch size < 2, it will be specialized. + """ + + def forward(self, x): + my_tensor_var = x + 100 + my_primitive_var = 3.14 + + def true_fn(x, y, z): + return x + y + z + + def false_fn(x, y, z): + return x - y - z + + return cond( + x.shape[0] > 5, + true_fn, + false_fn, + [x, my_tensor_var, torch.tensor(my_primitive_var)], + ) + +example_args = (torch.randn(6),) +tags = { + "torch.cond", + "torch.dynamic-shape", +} +model = CondBranchNonlocalVariables() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_closed_over_variable.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_closed_over_variable.py new file mode 100644 index 0000000000000000000000000000000000000000..183180ab4fc825385170fea2bec6af184374a67e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_closed_over_variable.py @@ -0,0 +1,22 @@ +# mypy: allow-untyped-defs +import torch + +from functorch.experimental.control_flow import cond + +class CondClosedOverVariable(torch.nn.Module): + """ + torch.cond() supports branches closed over arbitrary variables. + """ + + def forward(self, pred, x): + def true_fn(val): + return x * 2 + + def false_fn(val): + return x - 2 + + return cond(pred, true_fn, false_fn, [x + 1]) + +example_args = (torch.tensor(True), torch.randn(3, 2)) +tags = {"torch.cond", "python.closure"} +model = CondClosedOverVariable() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_operands.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_operands.py new file mode 100644 index 0000000000000000000000000000000000000000..d94e59c121788b6bba6dd52931e0048c04467ad2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_operands.py @@ -0,0 +1,35 @@ +# mypy: allow-untyped-defs +import torch + +from torch.export import Dim + +x = torch.randn(3, 2) +y = torch.randn(2) +dim0_x = Dim("dim0_x") + +class CondOperands(torch.nn.Module): + """ + The operands passed to cond() must be: + - a list of tensors + - match arguments of `true_fn` and `false_fn` + + NOTE: If the `pred` is tested on a dim with batch size < 2, it will be specialized. + """ + + def forward(self, x, y): + def true_fn(x, y): + return x + y + + def false_fn(x, y): + return x - y + + return torch.cond(x.shape[0] > 2, true_fn, false_fn, [x, y]) + +example_args = (x, y) +tags = { + "torch.cond", + "torch.dynamic-shape", +} +extra_inputs = (torch.randn(2, 2), torch.randn(2)) +dynamic_shapes = {"x": {0: dim0_x}, "y": None} +model = CondOperands() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_predicate.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_predicate.py new file mode 100644 index 0000000000000000000000000000000000000000..20ce1d6c8340b5462f5b1d13d0900706437d97d2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/cond_predicate.py @@ -0,0 +1,25 @@ +# mypy: allow-untyped-defs +import torch + +from functorch.experimental.control_flow import cond + +class CondPredicate(torch.nn.Module): + """ + The conditional statement (aka predicate) passed to cond() must be one of the following: + - torch.Tensor with a single element + - boolean expression + + NOTE: If the `pred` is tested on a dim with batch size < 2, it will be specialized. + """ + + def forward(self, x): + pred = x.dim() > 2 and x.shape[2] > 10 + + return cond(pred, lambda x: x.cos(), lambda y: y.sin(), [x]) + +example_args = (torch.randn(6, 4, 3),) +tags = { + "torch.cond", + "torch.dynamic-shape", +} +model = CondPredicate() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/constrain_as_size_example.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/constrain_as_size_example.py new file mode 100644 index 0000000000000000000000000000000000000000..934746aaf6739de7a37077d8ec3c2776586a5657 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/constrain_as_size_example.py @@ -0,0 +1,23 @@ +# mypy: allow-untyped-defs +import torch + + +class ConstrainAsSizeExample(torch.nn.Module): + """ + If the value is not known at tracing time, you can provide hint so that we + can trace further. Please look at torch._check APIs. + """ + + def forward(self, x): + a = x.item() + torch._check(a >= 0) + torch._check(a <= 5) + return torch.zeros((a, 5)) + + +example_args = (torch.tensor(4),) +tags = { + "torch.dynamic-value", + "torch.escape-hatch", +} +model = ConstrainAsSizeExample() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/constrain_as_value_example.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/constrain_as_value_example.py new file mode 100644 index 0000000000000000000000000000000000000000..22f791a3e80474257c27d927bad56cf4c2fbce78 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/constrain_as_value_example.py @@ -0,0 +1,26 @@ +# mypy: allow-untyped-defs +import torch + + +class ConstrainAsValueExample(torch.nn.Module): + """ + If the value is not known at tracing time, you can provide hint so that we + can trace further. Please look at torch._check API. + """ + + def forward(self, x, y): + a = x.item() + torch._check(a >= 0) + torch._check(a <= 5) + + if a < 6: + return y.sin() + return y.cos() + + +example_args = (torch.tensor(4), torch.randn(5, 5)) +tags = { + "torch.dynamic-value", + "torch.escape-hatch", +} +model = ConstrainAsValueExample() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/decorator.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/decorator.py new file mode 100644 index 0000000000000000000000000000000000000000..7d24cc681a6b62adf40bfd9a2e5283afb3515131 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/decorator.py @@ -0,0 +1,23 @@ +# mypy: allow-untyped-defs +import functools + +import torch + +def test_decorator(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + 1 + + return wrapper + +class Decorator(torch.nn.Module): + """ + Decorators calls are inlined into the exported function during tracing. + """ + + @test_decorator + def forward(self, x, y): + return x + y + +example_args = (torch.randn(3, 2), torch.randn(3, 2)) +model = Decorator() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dictionary.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dictionary.py new file mode 100644 index 0000000000000000000000000000000000000000..49e688bc0ac1f09567e3b877aaca29a1d02b4121 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dictionary.py @@ -0,0 +1,17 @@ +# mypy: allow-untyped-defs +import torch + +class Dictionary(torch.nn.Module): + """ + Dictionary structures are inlined and flattened along tracing. + """ + + def forward(self, x, y): + elements = {} + elements["x2"] = x * x + y = y * elements["x2"] + return {"y": y} + +example_args = (torch.randn(3, 2), torch.tensor(4)) +tags = {"python.data-structure"} +model = Dictionary() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_assert.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_assert.py new file mode 100644 index 0000000000000000000000000000000000000000..abf40db97dd459b24dad35a14d1576ae6d1c93a1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_assert.py @@ -0,0 +1,18 @@ +# mypy: allow-untyped-defs +import torch + +class DynamicShapeAssert(torch.nn.Module): + """ + A basic usage of python assertion. + """ + + def forward(self, x): + # assertion with error message + assert x.shape[0] > 2, f"{x.shape[0]} is greater than 2" # noqa: S101 + # assertion without error message + assert x.shape[0] > 1 # noqa: S101 + return x + +example_args = (torch.randn(3, 2),) +tags = {"python.assert"} +model = DynamicShapeAssert() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_constructor.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_constructor.py new file mode 100644 index 0000000000000000000000000000000000000000..157e460274ad58ba71c886b35364ddc0cd4d886a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_constructor.py @@ -0,0 +1,15 @@ +# mypy: allow-untyped-defs +import torch + +class DynamicShapeConstructor(torch.nn.Module): + """ + Tensor constructors should be captured with dynamic shape inputs rather + than being baked in with static shape. + """ + + def forward(self, x): + return torch.zeros(x.shape[0] * 2) + +example_args = (torch.randn(3, 2),) +tags = {"torch.dynamic-shape"} +model = DynamicShapeConstructor() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_if_guard.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_if_guard.py new file mode 100644 index 0000000000000000000000000000000000000000..90e336868ce4e784f2799d86c5887cec91e887e6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_if_guard.py @@ -0,0 +1,19 @@ +# mypy: allow-untyped-defs +import torch + +class DynamicShapeIfGuard(torch.nn.Module): + """ + `if` statement with backed dynamic shape predicate will be specialized into + one particular branch and generate a guard. However, export will fail if the + dimension is marked as dynamic shape from higher level API. + """ + + def forward(self, x): + if x.shape[0] == 3: + return x.cos() + + return x.sin() + +example_args = (torch.randn(3, 2, 2),) +tags = {"torch.dynamic-shape", "python.control-flow"} +model = DynamicShapeIfGuard() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_map.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_map.py new file mode 100644 index 0000000000000000000000000000000000000000..f8066aed556b9ee588b9744d17ba16c35d8fed6c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_map.py @@ -0,0 +1,19 @@ +# mypy: allow-untyped-defs +import torch + +from functorch.experimental.control_flow import map + +class DynamicShapeMap(torch.nn.Module): + """ + functorch map() maps a function over the first tensor dimension. + """ + + def forward(self, xs, y): + def body(x, y): + return x + y + + return map(body, xs, y) + +example_args = (torch.randn(3, 2), torch.randn(2)) +tags = {"torch.dynamic-shape", "torch.map"} +model = DynamicShapeMap() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_round.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_round.py new file mode 100644 index 0000000000000000000000000000000000000000..decbf036553cb76544a19e531e5aee98d792ae0b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_round.py @@ -0,0 +1,21 @@ +# mypy: allow-untyped-defs +import torch + +from torch._export.db.case import SupportLevel +from torch.export import Dim + +class DynamicShapeRound(torch.nn.Module): + """ + Calling round on dynamic shapes is not supported. + """ + + def forward(self, x): + return x[: round(x.shape[0] / 2)] + +x = torch.randn(3, 2) +dim0_x = Dim("dim0_x") +example_args = (x,) +tags = {"torch.dynamic-shape", "python.builtin"} +support_level = SupportLevel.NOT_SUPPORTED_YET +dynamic_shapes = {"x": {0: dim0_x}} +model = DynamicShapeRound() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_slicing.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_slicing.py new file mode 100644 index 0000000000000000000000000000000000000000..360fe15f6f98d9d735366bfa53371d79e0b00209 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_slicing.py @@ -0,0 +1,15 @@ +# mypy: allow-untyped-defs +import torch + +class DynamicShapeSlicing(torch.nn.Module): + """ + Slices with dynamic shape arguments should be captured into the graph + rather than being baked in. + """ + + def forward(self, x): + return x[: x.shape[0] - 2, x.shape[1] - 1 :: 2] + +example_args = (torch.randn(3, 2),) +tags = {"torch.dynamic-shape"} +model = DynamicShapeSlicing() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_view.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_view.py new file mode 100644 index 0000000000000000000000000000000000000000..c45d4aeebb0282a0f56c58a587b4bfe1655f50e3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/dynamic_shape_view.py @@ -0,0 +1,17 @@ +# mypy: allow-untyped-defs +import torch + +class DynamicShapeView(torch.nn.Module): + """ + Dynamic shapes should be propagated to view arguments instead of being + baked into the exported graph. + """ + + def forward(self, x): + new_x_shape = x.size()[:-1] + (2, 5) + x = x.view(*new_x_shape) + return x.permute(0, 2, 1) + +example_args = (torch.randn(10, 10),) +tags = {"torch.dynamic-shape"} +model = DynamicShapeView() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/fn_with_kwargs.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/fn_with_kwargs.py new file mode 100644 index 0000000000000000000000000000000000000000..46b2637b398c21bf9399d0a3fa2a964354beea3e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/fn_with_kwargs.py @@ -0,0 +1,30 @@ +# mypy: allow-untyped-defs +import torch + +class FnWithKwargs(torch.nn.Module): + """ + Keyword arguments are not supported at the moment. + """ + + def forward(self, pos0, tuple0, *myargs, mykw0, **mykwargs): + out = pos0 + for arg in tuple0: + out = out * arg + for arg in myargs: + out = out * arg + out = out * mykw0 + out = out * mykwargs["input0"] * mykwargs["input1"] + return out + +example_args = ( + torch.randn(4), + (torch.randn(4), torch.randn(4)), + *[torch.randn(4), torch.randn(4)] +) +example_kwargs = { + "mykw0": torch.randn(4), + "input0": torch.randn(4), + "input1": torch.randn(4), +} +tags = {"python.data-structure"} +model = FnWithKwargs() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/list_contains.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/list_contains.py new file mode 100644 index 0000000000000000000000000000000000000000..150070945cfa7f2ef7aca1f8c3dfece0f07cbecd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/list_contains.py @@ -0,0 +1,17 @@ +# mypy: allow-untyped-defs +import torch + +class ListContains(torch.nn.Module): + """ + List containment relation can be checked on a dynamic shape or constants. + """ + + def forward(self, x): + assert x.size(-1) in [6, 2] # noqa: S101 + assert x.size(0) not in [4, 5, 6] # noqa: S101 + assert "monkey" not in ["cow", "pig"] # noqa: S101 + return x + x + +example_args = (torch.randn(3, 2),) +tags = {"torch.dynamic-shape", "python.data-structure", "python.assert"} +model = ListContains() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/list_unpack.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/list_unpack.py new file mode 100644 index 0000000000000000000000000000000000000000..98533cfab5498934a61fbe693bb2497d5dbc9738 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/list_unpack.py @@ -0,0 +1,21 @@ +# mypy: allow-untyped-defs + +import torch + +class ListUnpack(torch.nn.Module): + """ + Lists are treated as static construct, therefore unpacking should be + erased after tracing. + """ + + def forward(self, args: list[torch.Tensor]): + """ + Lists are treated as static construct, therefore unpacking should be + erased after tracing. + """ + x, *y = args + return x + y[0] + +example_args = ([torch.randn(3, 2), torch.tensor(4), torch.tensor(5)],) +tags = {"python.control-flow", "python.data-structure"} +model = ListUnpack() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/model_attr_mutation.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/model_attr_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..122b0ddfc3429fb31415a146e8e1dcfddb2fe031 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/model_attr_mutation.py @@ -0,0 +1,24 @@ +# mypy: allow-untyped-defs +import torch + + +class ModelAttrMutation(torch.nn.Module): + """ + Attribute mutation raises a warning. Covered in the test_export.py test_detect_leak_strict test. + """ + + def __init__(self) -> None: + super().__init__() + self.attr_list = [torch.randn(3, 2), torch.randn(3, 2)] + + def recreate_list(self): + return [torch.zeros(3, 2), torch.zeros(3, 2)] + + def forward(self, x): + self.attr_list = self.recreate_list() + return x.sum() + self.attr_list[0].sum() + + +example_args = (torch.randn(3, 2),) +tags = {"python.object-model"} +model = ModelAttrMutation() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/nested_function.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/nested_function.py new file mode 100644 index 0000000000000000000000000000000000000000..e4076ac14dada40b4d78812666a9ec6b5e67045b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/nested_function.py @@ -0,0 +1,23 @@ +# mypy: allow-untyped-defs +import torch + +class NestedFunction(torch.nn.Module): + """ + Nested functions are traced through. Side effects on global captures + are not supported though. + """ + + def forward(self, a, b): + x = a + b + z = a - b + + def closure(y): + nonlocal x + x += 1 + return x * y + z + + return closure(x) + +example_args = (torch.randn(3, 2), torch.randn(2)) +tags = {"python.closure"} +model = NestedFunction() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/null_context_manager.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/null_context_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..80d09f68097edbe676077be183711dabe5cbc664 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/null_context_manager.py @@ -0,0 +1,21 @@ +# mypy: allow-untyped-defs +import contextlib + +import torch + +class NullContextManager(torch.nn.Module): + """ + Null context manager in Python will be traced out. + """ + + def forward(self, x): + """ + Null context manager in Python will be traced out. + """ + ctx = contextlib.nullcontext() + with ctx: + return x.sin() + x.cos() + +example_args = (torch.randn(3, 2),) +tags = {"python.context-manager"} +model = NullContextManager() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/optional_input.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/optional_input.py new file mode 100644 index 0000000000000000000000000000000000000000..41e66a7c977a83bf59116864c7f443387277f06e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/optional_input.py @@ -0,0 +1,20 @@ +# mypy: allow-untyped-defs +import torch +from torch._export.db.case import SupportLevel + + +class OptionalInput(torch.nn.Module): + """ + Tracing through optional input is not supported yet + """ + + def forward(self, x, y=torch.randn(2, 3)): + if y is not None: + return x + y + return x + + +example_args = (torch.randn(2, 3),) +tags = {"python.object-model"} +support_level = SupportLevel.SUPPORTED +model = OptionalInput() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/pytree_flatten.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/pytree_flatten.py new file mode 100644 index 0000000000000000000000000000000000000000..804e73c5a6d58ad5b5be179bf67a5d5bc38c2e2b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/pytree_flatten.py @@ -0,0 +1,16 @@ +# mypy: allow-untyped-defs +import torch + +from torch.utils import _pytree as pytree + +class PytreeFlatten(torch.nn.Module): + """ + Pytree from PyTorch can be captured by TorchDynamo. + """ + + def forward(self, x): + y, _spec = pytree.tree_flatten(x) + return y[0] + 1 + +example_args = ({1: torch.randn(3, 2), 2: torch.randn(3, 2)},), +model = PytreeFlatten() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/scalar_output.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/scalar_output.py new file mode 100644 index 0000000000000000000000000000000000000000..86d3b4645330c47c3625736b695d635f4ab58c70 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/scalar_output.py @@ -0,0 +1,23 @@ +# mypy: allow-untyped-defs +import torch + +from torch.export import Dim + +x = torch.randn(3, 2) +dim1_x = Dim("dim1_x") + +class ScalarOutput(torch.nn.Module): + """ + Returning scalar values from the graph is supported, in addition to Tensor + outputs. Symbolic shapes are captured and rank is specialized. + """ + def __init__(self) -> None: + super().__init__() + + def forward(self, x): + return x.shape[1] + 1 + +example_args = (x,) +tags = {"torch.dynamic-shape"} +dynamic_shapes = {"x": {1: dim1_x}} +model = ScalarOutput() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/specialized_attribute.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/specialized_attribute.py new file mode 100644 index 0000000000000000000000000000000000000000..f17092f9afc681b91a982a8a2479ac1dde4f455d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/specialized_attribute.py @@ -0,0 +1,26 @@ +# mypy: allow-untyped-defs +from enum import Enum + +import torch + +class Animal(Enum): + COW = "moo" + +class SpecializedAttribute(torch.nn.Module): + """ + Model attributes are specialized. + """ + + def __init__(self) -> None: + super().__init__() + self.a = "moo" + self.b = 4 + + def forward(self, x): + if self.a == Animal.COW.value: + return x * x + self.b + else: + raise ValueError("bad") + +example_args = (torch.randn(3, 2),) +model = SpecializedAttribute() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/static_for_loop.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/static_for_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..aa62b86d16d9b6a1c539976a891f58bd732ae30d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/static_for_loop.py @@ -0,0 +1,16 @@ +# mypy: allow-untyped-defs +import torch + +class StaticForLoop(torch.nn.Module): + """ + A for loop with constant number of iterations should be unrolled in the exported graph. + """ + + def forward(self, x): + # constant + ret = [i + x for i in range(10)] + return ret + +example_args = (torch.randn(3, 2),) +tags = {"python.control-flow"} +model = StaticForLoop() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/static_if.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/static_if.py new file mode 100644 index 0000000000000000000000000000000000000000..f169380159a45489142ce5ae3523b2e4504c6721 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/static_if.py @@ -0,0 +1,18 @@ +# mypy: allow-untyped-defs +import torch + +class StaticIf(torch.nn.Module): + """ + `if` statement with static predicate value should be traced through with the + taken branch. + """ + + def forward(self, x): + if len(x.shape) == 3: + return x + torch.ones(1, 1, 1) + + return x + +example_args = (torch.randn(3, 2, 2),) +tags = {"python.control-flow"} +model = StaticIf() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/tensor_setattr.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/tensor_setattr.py new file mode 100644 index 0000000000000000000000000000000000000000..8fbc263e7ff2240a3cf8618c56f152e744aa40e8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/tensor_setattr.py @@ -0,0 +1,15 @@ +# mypy: allow-untyped-defs +import torch + + +class TensorSetattr(torch.nn.Module): + """ + setattr() call onto tensors is not supported. + """ + def forward(self, x, attr): + setattr(x, attr, torch.randn(3, 2)) + return x + 4 + +example_args = (torch.randn(3, 2), "attr") +tags = {"python.builtin"} +model = TensorSetattr() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/type_reflection_method.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/type_reflection_method.py new file mode 100644 index 0000000000000000000000000000000000000000..99ad42a153c512d65aaae1bcac2377ee1e124f25 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/type_reflection_method.py @@ -0,0 +1,22 @@ +# mypy: allow-untyped-defs +import torch + +class A: + @classmethod + def func(cls, x): + return 1 + x + +class TypeReflectionMethod(torch.nn.Module): + """ + type() calls on custom objects followed by attribute accesses are not allowed + due to its overly dynamic nature. + """ + + def forward(self, x): + a = A() + return type(a).func(x) + + +example_args = (torch.randn(3, 4),) +tags = {"python.builtin"} +model = TypeReflectionMethod() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/unsupported_operator.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/unsupported_operator.py new file mode 100644 index 0000000000000000000000000000000000000000..ba5475c5f15fe35c9ba2be57f295f568602b82c5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/unsupported_operator.py @@ -0,0 +1,18 @@ +# mypy: allow-untyped-defs +import torch +from torch._export.db.case import SupportLevel + + +class TorchSymMin(torch.nn.Module): + """ + torch.sym_min operator is supported in export. + """ + + def forward(self, x): + return x.sum() + torch.sym_min(x.size(0), 100) + + +example_args = (torch.randn(3, 2),) +tags = {"torch.operator"} +support_level = SupportLevel.SUPPORTED +model = TorchSymMin() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/examples/user_input_mutation.py b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/user_input_mutation.py new file mode 100644 index 0000000000000000000000000000000000000000..3156b3a1bf2ec6f6361395de3dacb098ecf20c3a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/examples/user_input_mutation.py @@ -0,0 +1,17 @@ +# mypy: allow-untyped-defs +import torch + + +class UserInputMutation(torch.nn.Module): + """ + Directly mutate user input in forward + """ + + def forward(self, x): + x.mul_(2) + return x.cos() + + +example_args = (torch.randn(3, 2),) +tags = {"torch.mutation"} +model = UserInputMutation() diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/gen_example.py b/.venv/lib/python3.12/site-packages/torch/_export/db/gen_example.py new file mode 100644 index 0000000000000000000000000000000000000000..5c422f457bc3c7c1d7bc5d17dd4e93b8558a5de4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/gen_example.py @@ -0,0 +1,23 @@ +import os +import sys + +import torch._export.db.examples as examples + +TEMPLATE = '''import torch + +def {case_name}(x): + """ + """ + + return +''' + +if __name__ == "__main__": + if len(sys.argv) != 2: + raise AssertionError(f"expected 2 arguments, got {len(sys.argv)}") + root_dir = examples.__name__.replace(".", "/") + if not os.path.exists(root_dir): + raise AssertionError(f"root_dir does not exist: {root_dir}") + with open(os.path.join(root_dir, sys.argv[1] + ".py"), "w") as f: + print("Writing to", f.name, "...") + f.write(TEMPLATE.format(case_name=sys.argv[1])) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/db/logging.py b/.venv/lib/python3.12/site-packages/torch/_export/db/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..1416b1e99c2d163bcceced1ef827a5292bed0565 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/db/logging.py @@ -0,0 +1,46 @@ + +def exportdb_error_message(case_name: str) -> str: + from .examples import all_examples + from torch._utils_internal import log_export_usage + + ALL_EXAMPLES = all_examples() + # Detect whether case_name is really registered in exportdb. + if case_name in ALL_EXAMPLES: + url_case_name = case_name.replace("_", "-") + return f"See {case_name} in exportdb for unsupported case. \ + https://pytorch.org/docs/main/generated/exportdb/index.html#{url_case_name}" + else: + log_export_usage( + event="export.error.casenotregistered", + message=case_name, + ) + return f"{case_name} is unsupported." + + +def get_class_if_classified_error(e: Exception) -> str | None: + """ + Returns a string case name if the export error e is classified. + Returns None otherwise. + """ + + from torch._dynamo.exc import TorchRuntimeError, Unsupported, UserError + + ALWAYS_CLASSIFIED = "always_classified" + DEFAULT_CLASS_SIGIL = "case_name" + + # add error types that should be classified, along with any attribute name + # whose presence acts like a sigil to further distinguish which errors of + # that type should be classified. If the attribute name is None, then the + # error type is always classified. + _ALLOW_LIST = { + Unsupported: DEFAULT_CLASS_SIGIL, + UserError: DEFAULT_CLASS_SIGIL, + TorchRuntimeError: None, + } + if type(e) in _ALLOW_LIST: + # pyrefly: ignore [bad-index, index-error] + attr_name = _ALLOW_LIST[type(e)] + if attr_name is None: + return ALWAYS_CLASSIFIED + return getattr(e, attr_name, None) + return None diff --git a/.venv/lib/python3.12/site-packages/torch/_export/error.py b/.venv/lib/python3.12/site-packages/torch/_export/error.py new file mode 100644 index 0000000000000000000000000000000000000000..03b7f52fb9de435b9e58fa4a0bb141cc191e84c5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/error.py @@ -0,0 +1,56 @@ +from enum import Enum + + +class ExportErrorType(Enum): + # User providing invalid inputs to either tracer, or other public facing APIs + INVALID_INPUT_TYPE = 1 + + # User returning values from their models that we don't support. + INVALID_OUTPUT_TYPE = 2 + + # Generated IR does not conform to Export IR Specification. + VIOLATION_OF_SPEC = 3 + + # User's code contains types and functionalities we don't support. + NOT_SUPPORTED = 4 + + # User's code didn't provide necessary details for us to successfully trace and export. + # For example, we use a lot of decorators and ask users to annotate their model. + MISSING_PROPERTY = 5 + + # User is using an API without proper initialization step. + UNINITIALIZED = 6 + + +def internal_assert(pred: bool, assert_msg: str) -> None: + """ + This is exir's custom assert method. It internally just throws InternalError. + Note that the sole purpose is to throw our own error while maintaining similar syntax + as python assert. + """ + + if not pred: + raise InternalError(assert_msg) + + +class InternalError(Exception): + """ + Raised when an internal invariance is violated in EXIR stack. + Should hint users to report a bug to dev and expose the original + error message. + """ + + def __init__(self, message: str) -> None: + super().__init__(message) + + +class ExportError(Exception): + """ + This type of exception is raised for errors that are directly caused by the user + code. In general, user errors happen during model authoring, tracing, using our public + facing APIs, and writing graph passes. + """ + + def __init__(self, error_code: ExportErrorType, message: str) -> None: + prefix = f"[{error_code}]: " + super().__init__(prefix + message) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/non_strict_utils.py b/.venv/lib/python3.12/site-packages/torch/_export/non_strict_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3b7e444cd87f82ce1c13456a7f6635427ff6943c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/non_strict_utils.py @@ -0,0 +1,1384 @@ +import builtins +import contextlib +import functools +import inspect +import logging +import math +import sys +from collections import defaultdict +from collections.abc import Callable, Generator, Sequence +from contextlib import contextmanager +from typing import Any, cast, TYPE_CHECKING, TypeGuard, TypeVar + +import torch +import torch.utils._pytree as pytree +from torch._custom_class_base import CustomClassBase +from torch._dynamo.source import ( + AttrSource, + GetItemSource, + LocalSource, + TensorProperty, + TensorPropertySource, +) +from torch._dynamo.variables.builder import TrackedFake +from torch._export.passes.lift_constants_pass import ConstantAttrMap +from torch._export.utils import _fakify_params_buffers +from torch._guards import Source +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import is_custom_class_obj +from torch._subclasses.fake_tensor import FakeTensorMode +from torch.export import Constraint +from torch.export.dynamic_shapes import ( + _check_dynamic_shapes, + _combine_args, + _DimHint, + _DimHintType, + _IntWrapper, + _process_dynamic_shapes, + _RelaxedConstraint, + _tree_map_with_path, +) +from torch.export.graph_signature import CustomObjArgument +from torch.fx.experimental import _config as config +from torch.fx.experimental.symbolic_shapes import ( + _find_user_code_frame, + _suggest_fixes_for_data_dependent_error_non_strict, + ConstraintViolationError, + DimDynamic, + EqualityConstraint, + GuardOnDataDependentSymNode, + RelaxedUnspecConstraint, + ShapeEnv, + StatelessSymbolicContext, + SymIntSymbolicContext, + ValueRanges, +) +from torch.utils._pytree import ( + GetAttrKey, + KeyPath, + MappingKey, + SequenceKey, + tree_map_with_path, +) +from torch.utils._sympy.numbers import int_oo + + +if TYPE_CHECKING: + from sympy import Expr, Symbol + + from torch.fx.experimental.dynamic_spec import ParamsSpec, ShapesSpec + from torch.fx.experimental.symbolic_shapes import SymbolicContext + + +log = logging.getLogger(__name__) + + +_ModuleT = TypeVar("_ModuleT", bound=torch.nn.Module) + + +_DATA_PTR_ACCESS_ERROR = "Cannot access data pointer of Tensor" +_RAW_TRITON_KERNEL_NON_STRICT_EXPORT_ERROR = ( + "Raw Triton kernel calls are not supported by non-strict torch.export. " + "Wrap the kernel in a torch.library.triton_op and call it through " + "torch.library.wrap_triton (or torch._library.capture_triton) so export " + "records a stable custom operator instead of tracing into Triton's runtime." +) + + +def _is_raw_triton_kernel_data_ptr_error( + func: Callable[..., object], exc: RuntimeError +) -> bool: + if getattr(func, "__name__", None) != "data_ptr": + return False + if _DATA_PTR_ACCESS_ERROR not in str(exc): + return False + + for frame in inspect.stack(context=0): + filename = frame.filename.replace("\\", "/") + if "/triton/runtime/" in filename: + return True + return False + + +class _KeyPath: + """ + Wraps `KeyPath` to aid `isinstance` checks. + """ + + def __init__(self, kp: KeyPath) -> None: + self.kp = kp + + +class _KeyPathTrie: + """ + Builds a trie of `KeyPath` prefixes mapping to `Source` leaves. + """ + + def __init__(self) -> None: + self.root: dict[Any, Any] = {} + + def add(self, kp: KeyPath, src: Source) -> None: + if len(kp) == 0: + raise AssertionError("KeyPath must not be empty") + *path, leaf = kp + node = self.root + for k in path: + if k not in node: + node[k] = {} + node = node[k] + node[leaf] = src + + def get(self, kp: KeyPath) -> tuple[Source, KeyPath]: + node = self.root + # pyrefly: ignore [bad-assignment] + while not isinstance(node, Source): + if len(kp) == 0: + raise AssertionError("KeyPath exhausted before reaching Source") + k, *kp = kp # type: ignore[assignment] + node = node[k] + # pyrefly: ignore [bad-return] + return node, kp + + +def make_sourced_prefixes( + nn_module: torch.nn.Module, args: tuple[Any, ...], kwargs: dict[str, Any] +) -> _KeyPathTrie: + kp_args, kp_kwargs = tree_map_with_path( + lambda kp, _: _KeyPath(kp), + (tuple(None for _ in args), {k: None for k in kwargs}), # noqa: C420 + ) + kp_combined_args = _combine_args(nn_module, kp_args, kp_kwargs) + + sourced_prefixes = _KeyPathTrie() + for name, struct in kp_combined_args.items(): + src = LocalSource(name) + + if isinstance(struct, _KeyPath): + sourced_prefixes.add(struct.kp, src) + elif isinstance(struct, tuple): + for i, prefix in enumerate(struct): + if not isinstance(prefix, _KeyPath): + raise AssertionError(f"expected _KeyPath, got {type(prefix)}") + sourced_prefixes.add(prefix.kp, GetItemSource(src, i)) + elif isinstance(struct, dict): + for k, prefix in struct.items(): + if not isinstance(prefix, _KeyPath): + raise AssertionError(f"expected _KeyPath, got {type(prefix)}") + sourced_prefixes.add(prefix.kp, GetItemSource(src, k)) + + return sourced_prefixes + + +def key_path_to_source( + kp: KeyPath, sourced_prefixes: _KeyPathTrie | None = None +) -> Source: + """ + Given a key path, return the source for the key path. + """ + if sourced_prefixes is None: + source: Source = LocalSource("args") + else: + source, kp = sourced_prefixes.get(kp) + + for k in kp: + if isinstance(k, SequenceKey): + source = GetItemSource(source, k.idx) + elif isinstance(k, MappingKey): + source = GetItemSource(source, k.key) + elif isinstance(k, GetAttrKey): + source = AttrSource(source, k.name) + else: + raise ValueError(f"Unknown KeyEntry {k}") + + return source + + +def _is_constant_argument(t: object) -> bool: + return t is None or isinstance(t, (float, bool, str)) + + +def fakify( + mode: FakeTensorMode, + kp: KeyPath, + t: Any, + t_constraints: dict[int, dict[int, Constraint]], + sources: dict[tuple[int, int], list[Source]], + sourced_prefixes: _KeyPathTrie | None = None, +) -> Any: + source = key_path_to_source(kp, sourced_prefixes=sourced_prefixes) + if ( + _is_constant_argument(t) + or isinstance(t, (torch.ScriptObject, torch.nn.Module)) + or is_custom_class_obj(t) + ): + return t + + if isinstance(t, _IntWrapper): + if t.dynamism is not None and t.dynamism.type in ( # type: ignore[union-attr] + _DimHintType.DYNAMIC, + _DimHintType.AUTO, + ): + symint = mode.shape_env.create_unspecified_symint_and_symbol( # type: ignore[union-attr] + t.val, source, DimDynamic.DYNAMIC + ) + context = ( + SymIntSymbolicContext( + constraint=RelaxedUnspecConstraint(warn_only=False) + ) + if t.dynamism.type == _DimHintType.DYNAMIC # type: ignore[union-attr] + else None + ) + mode.shape_env.tracked_fakes.append( # type: ignore[union-attr] + TrackedFake(symint, source, context) + ) + return symint + else: + return t.val + + if not isinstance(t, torch.Tensor): + raise ValueError( + f"Unsupported input type {type(t)}. " + "Export only supports pytree containers of basic types (Tensor, int, float, ...) as input. " + "To register a custom dataclass, use torch.export.register_dataclass. " + "To register a custom container type, use torch.utils._pytree.register_pytree_node. " + "To register a constant input, use torch.utils._pytree.register_constant" + ) + + # Create symbolic context (handles subclass recursion internally) + symbolic_context = _create_symbolic_context_for_tensor( + t, source, t_constraints, sources, mode + ) + + fake = mode.from_tensor(t, source=source, symbolic_context=symbolic_context) + mode.shape_env.tracked_fakes.append(TrackedFake(fake, source, symbolic_context)) # type: ignore[union-attr] + return fake + + +def _create_symbolic_context_for_tensor( + t: torch.Tensor, + source: Source, + t_constraints: dict[int, dict[int, Constraint]], + sources: dict[tuple[int, int], list[Source]], + mode: FakeTensorMode, +) -> "SymbolicContext": + """Helper function to create symbolic context for a tensor.""" + from torch._dynamo.source import AttrSource + from torch.fx.experimental.symbolic_shapes import ( + DimDynamic, + RelaxedUnspecConstraint, + SubclassSymbolicContext, + ) + from torch.utils._python_dispatch import is_traceable_wrapper_subclass + + # Common dynamic dimension logic for both regular tensors and subclasses + n_dims = len(t.shape) + dynamic_sizes = [] + constraint_sizes = [None] * n_dims + + for i in range(n_dims): + if i in getattr(t, "_dynamo_weak_dynamic_indices", {}): + dynamic_sizes.append(DimDynamic.DYNAMIC) + elif i in getattr(t, "_dynamo_dynamic_indices", {}): + # bit annoying, but we need to replicate process in _dynamo/variables/builder.py + # where a RelaxedUnspecConstraint is created for Dim.DYNAMIC, so constraint violations + # are raised when specializing. + dynamic_sizes.append(DimDynamic.DYNAMIC) + constraint_sizes[i] = RelaxedUnspecConstraint(warn_only=False) # type: ignore[call-overload] + else: + dynamic_sizes.append(DimDynamic.STATIC) + + # Handle nested subclasses + if is_traceable_wrapper_subclass(t): + # Get inner contexts recursively + inner_contexts: dict[str, SymbolicContext] = {} + # pyrefly: ignore[missing-attribute] # TODO traceable wrapper subclasses define __tensor_flatten__ + attrs, _ = type(t).__tensor_flatten__(t) + + # Propagate outer tensor constraints to inner tensors if not already present + for attr in attrs: + match getattr(t, attr): + case torch.Tensor() as inner_value: + inner_source = AttrSource(source, attr) + inner_contexts[attr] = _create_symbolic_context_for_tensor( + inner_value, inner_source, t_constraints, sources, mode + ) + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + + symbolic_context = SubclassSymbolicContext( + dynamic_sizes=dynamic_sizes, + constraint_sizes=constraint_sizes, # type: ignore[arg-type] + view_base_context=None, + tensor_source=source, + shape_env_to_source_to_symbol_cache={}, + inner_contexts=inner_contexts, + ) + else: + symbolic_context: StatelessSymbolicContext = ( # type: ignore[no-redef] + StatelessSymbolicContext( + dynamic_sizes=dynamic_sizes, + constraint_sizes=constraint_sizes, # type: ignore[arg-type] + ) + ) + + # Apply constraints (common logic) + t_id = id(t) + if mode.shape_env is None: + raise AssertionError("mode.shape_env must not be None") + if t_id in t_constraints: + for i, constraint in t_constraints[t_id].items(): + src = TensorPropertySource(base=source, prop=TensorProperty.SIZE, idx=i) + sources[(t_id, i)].append(src) + if isinstance(constraint, _RelaxedConstraint): + continue + symbolic_context.constraint_sizes[i] = constraint.constraint_range + mode.shape_env.source_name_to_debug_name[src.name] = constraint.name # type: ignore[assignment] + + return symbolic_context + + +def _is_unbacked_symint(symbol: object) -> bool: + if not isinstance(symbol, torch.SymInt): + return False + + if symbol.node.shape_env is None: + raise AssertionError("shape_env should not be None") + return symbol.node.shape_env.is_unbacked_symint(symbol.node.expr) + + +def _tensor_min_max( + *args: Any, + real_callable: Callable[..., object], + tensor_callable: Callable[..., object], + **kwargs: Any, +) -> Any: + """ + This logic is replicated from dynamo/variables/builtin.py + """ + if len(args) == 2 and not kwargs: + arg1, arg2 = args + + # Case 1: Both are tensors + if isinstance(arg1, torch.Tensor) and isinstance(arg2, torch.Tensor): + return tensor_callable(arg1, arg2) + + # Case 2: One tensor, one scalar + elif isinstance(arg1, torch.Tensor) or isinstance(arg2, torch.Tensor): + if not isinstance(arg1, torch.Tensor): + arg1, arg2 = arg2, arg1 + + if isinstance(arg2, (int, float)): + kwarg = {"min" if tensor_callable is torch.maximum else "max": arg2} + return torch.clamp(arg1, **kwarg) # type: ignore[call-overload] + else: + return real_callable(arg1, arg2) + + # Case 3: SymInts + elif isinstance(arg1, torch.SymInt) or isinstance(arg2, torch.SymInt): + return ( + torch.sym_max(arg1, arg2) + if tensor_callable is torch.maximum + else torch.sym_min(arg1, arg2) + ) + + # Fallback + else: + return real_callable(arg1, arg2) + + # Single iterable argument handling + if len(args) == 1 and not kwargs: + iterable = args[0] + + if isinstance(iterable, torch.Tensor): + return tensor_callable(iterable) + try: + iterator = iter(iterable) + except TypeError: + pass + else: + items = list(iterator) + if not items: + raise ValueError(f"{real_callable.__name__}() arg is an empty sequence") + + return functools.reduce( + lambda a, b: _tensor_min_max( + a, b, real_callable=real_callable, tensor_callable=tensor_callable + ), + items, + ) + + # Fallback to original callable + return real_callable(*args, **kwargs) + + +@contextmanager +def _override_builtin_ops() -> Generator[None, None, None]: + original_max = builtins.max + original_min = builtins.min + original_pow = math.pow + + # pyrefly: ignore [bad-assignment] + builtins.max = functools.partial( + _tensor_min_max, real_callable=original_max, tensor_callable=torch.maximum + ) + + # pyrefly: ignore [bad-assignment] + builtins.min = functools.partial( + _tensor_min_max, real_callable=original_min, tensor_callable=torch.minimum + ) + + math.pow = lambda x, y: x**y # type: ignore[operator] + + try: + yield + finally: + builtins.max = original_max + builtins.min = original_min + math.pow = original_pow + + +def _make_fake_inputs_with_spec( + fake_mode: FakeTensorMode, + nn_module: Any, + args: Any, + kwargs: Any, + sourced_prefixes: Any, + dynamic_shapes: Any, + original_signature: inspect.Signature, +) -> tuple[FakeTensorMode, Any, Any, EqualityConstraint, inspect.Signature, Any]: + from torch.fx.experimental._spec_binding import _bind_spec_to_args + from torch.fx.experimental.dynamic_spec import ( + _coerce_to_shapes_spec, + IntVar, + ShapesSpec, + ) + from torch.fx.experimental.symbolic_shapes import ( + _finalize_spec_wiring, + _symbolic_context_from_shapes_spec, + _wire_spec_assumptions, + _wire_spec_slot, + _wire_tensor_spec_dims, + ) + + user_spec = cast(ShapesSpec, _coerce_to_shapes_spec(dynamic_shapes)) + shape_env = fake_mode.shape_env + if shape_env is None: + raise AssertionError("fake_mode.shape_env must not be None") + + def _fakify_one_leaf(x: Any, source: Source, leaf_spec: Any) -> Any: + """Fakify a single flat input leaf against its (already-bound) spec.""" + if isinstance(x, torch.Tensor): + if leaf_spec is None: + return fake_mode.from_tensor(x, static_shapes=True, source=source) + ctx = _symbolic_context_from_shapes_spec(x, source, leaf_spec, None, {}) + fake_x = fake_mode.from_tensor( + x, static_shapes=False, source=source, symbolic_context=ctx + ) + _wire_tensor_spec_dims(leaf_spec, fake_x) + return fake_x + # NB: don't match on bools. + if type(x) is int: + if isinstance(leaf_spec, int): + # Static int spec: verify the runtime value matches. + if x != leaf_spec: + raise ValueError( + f"shapes_spec declared {source.name} as static with " + f"value {leaf_spec}, but got {x} at trace time" + ) + return x + if isinstance(leaf_spec, (IntVar, torch.SymInt)): + sym_node = shape_env.create_unbacked_symint(source=source) + _wire_spec_slot(leaf_spec, sym_node) + return sym_node + return x + + # Wire assumptions BEFORE processing inputs so derived / assumption + # checks can drain as inputs bind. + if user_spec._assumptions: + _wire_spec_assumptions(shape_env, user_spec) + + leaf_specs, flat_args, in_spec = _bind_spec_to_args( + nn_module, args, kwargs, user_spec + ) + leaf_sources = [ + key_path_to_source(kp, sourced_prefixes=sourced_prefixes) + for kp, _ in pytree.tree_flatten_with_path((args, kwargs))[0] + ] + + with shape_env.ignore_fresh_unbacked_symbols(): + fake_leaves = [ + _fakify_one_leaf(x, leaf_sources[i], leaf_specs[i]) + for i, x in enumerate(flat_args) + ] + + # Verify every spec assumption / derived check that survived input + # processing has been emitted. + _finalize_spec_wiring(shape_env) + + fake_args, fake_kwargs = pytree.tree_unflatten(fake_leaves, in_spec) + equalities_inputs = EqualityConstraint( + source_pairs=[], + derived_equalities=[], + phantom_symbols=[], + relaxed_sources=set(), + warn_only=False, + ) + return ( + fake_mode, + fake_args, + fake_kwargs, + equalities_inputs, + original_signature, + dynamic_shapes, + ) + + +def make_fake_inputs( + nn_module: torch.nn.Module, + args: tuple[Any, ...], + kwargs: dict[str, Any], + dynamic_shapes: "dict[str, Any] | tuple[Any, ...] | list[Any] | ShapesSpec | ParamsSpec | None", + prefer_deferred_runtime_asserts_over_guards: bool = False, +) -> tuple[ + FakeTensorMode, + tuple[Any, ...], + dict[str, Any], + EqualityConstraint, + inspect.Signature, + dict[str, Any] | tuple[Any, ...] | list[Any] | None, +]: + """ + Given an nn module, example inputs, and constraints, return a new fake mode, + fake inputs created in that mode whose dynamic shape dimensions are constrained + by the given ranges, and sources for pairs of dynamic shape dimensions that are + constrained to be equal. + """ + # TODO(avik): refactor Dynamo to avoid duplication of the following code + # between non-strict and strict. + # Specifically, here (non-strict) we do the following pre-tracing steps: + # - Fakify inputs. + # - Process input shape equalities. + # In strict, these steps are spread across multiple files: + # - output_graph.py fakifies inputs. + # - [post-tracing] guards.py processes input shape equalities. + import torch._functorch.config as _config + from torch.fx.experimental.dynamic_spec import ParamsSpec, ShapesSpec + + # ShapesSpec/ParamsSpec drive dynamism via unbacked symbols (handled by the + # spec fakify branch below); skip the legacy constraint machinery for it. + is_shapes_spec = isinstance(dynamic_shapes, (ShapesSpec, ParamsSpec)) + + constraints: list[Constraint] = [] + t_constraints: dict[int, dict[int, Constraint]] = defaultdict(dict) + if not is_shapes_spec: + # Map ints to a wrapper structure to help us mark it as dynamic, if it is + # dynamic. We will unwrap ints in fakify later. + args, kwargs = pytree.tree_map_only( + int, lambda a: _IntWrapper(a), (args, kwargs) + ) + + combined_args = _combine_args(nn_module, args, kwargs) + _check_dynamic_shapes(combined_args, dynamic_shapes) + constraints = _process_dynamic_shapes(combined_args, dynamic_shapes) + for constraint in constraints: + t_constraints[constraint.t_id][constraint.dim] = constraint + + context = torch._guards.TracingContext.try_get() + if context is not None: + # This occurs when we are exporting within dynamo. There already exists + # a toplevel TracingContext with a fake mode, so we do not want to + # create another fake mode. + fake_mode = context.fake_mode + if fake_mode is None: + raise AssertionError("context.fake_mode must not be None") + else: + if isinstance(nn_module.forward, functools.partial): + # functools handles nesting by itself, no need to recurse + code = nn_module.forward.func.__code__ + elif ( + sys.version_info >= (3, 14) + and (fwd := getattr(nn_module.forward, "__func__", None)) + and isinstance(fwd, functools.partial) + ): + # functools.partial is now a method descriptor: + # https://docs.python.org/3/whatsnew/3.14.html#changes-in-the-python-api + code = fwd.func.__code__ + else: + code = nn_module.forward.__code__ + co_fields = { + "co_name": code.co_name, + "co_filename": code.co_filename, + "co_firstlineno": code.co_firstlineno, + } + with _config.patch(fake_tensor_allow_unsafe_data_ptr_access=False): + fake_mode = FakeTensorMode( + shape_env=ShapeEnv( + tracked_fakes=[], + co_fields=co_fields, + prefer_deferred_runtime_asserts_over_guards=prefer_deferred_runtime_asserts_over_guards, + trace_asserts=True, + ), + allow_non_fake_inputs=True, + export=True, + ) + if fake_mode.shape_env is None or fake_mode.shape_env.tracked_fakes is None: + raise ValueError( + "Detected fake_mode does not have a shape_env with tracked fakes. " + "If you constructed the module under a FakeTensorMode, " + "please initialize it like: FakeTensorMode(shape_env=ShapeEnv(tracked_fakes=[]))" + ) + + with fake_mode: + original_signature = inspect.signature(nn_module.forward) + sources: dict[tuple[int, int], list[Source]] = defaultdict(list) + sourced_prefixes = make_sourced_prefixes(nn_module, args, kwargs) + if is_shapes_spec: + return _make_fake_inputs_with_spec( + fake_mode, + nn_module, + args, + kwargs, + sourced_prefixes, + dynamic_shapes, + original_signature, + ) + fake_args, fake_kwargs = tree_map_with_path( + lambda kp, val: fakify( + fake_mode, + kp, + val, + t_constraints, + sources, + sourced_prefixes=sourced_prefixes, + ), + (args, kwargs), + ) + + names: dict[str, tuple[int, int]] = {} + source_pairs: list[tuple[Source, Source]] = [] + derived_equalities: list[ + tuple[Source, Source | Symbol, Callable[..., object]] + ] = [] + phantom_symbols: dict[str, Symbol] = {} + relaxed_sources: set[Source] = set() + for constraint in constraints: + torch.export.dynamic_shapes._process_equalities( + constraint, + lambda t_id, dim: sources[(t_id, dim)], + fake_mode.shape_env, + names, + source_pairs, + derived_equalities, + phantom_symbols, + relaxed_sources, + ) + + equalities_inputs = EqualityConstraint( + source_pairs=source_pairs, + derived_equalities=derived_equalities, + phantom_symbols=list(phantom_symbols.values()), + relaxed_sources=relaxed_sources, + warn_only=False, + ) + return ( + fake_mode, + fake_args, + fake_kwargs, + equalities_inputs, + original_signature, + dynamic_shapes, + ) + + +def _flatten_dynamic_shapes( + combined_args: dict[str, Any], + dynamic_shapes: dict[str, Any] | tuple[Any] | list[Any], +) -> list[Any]: + flat_shapes: list[Any] = [] + + def _tree_map_helper(path: KeyPath, t: Any, shape: Any) -> None: + nonlocal flat_shapes + flat_shapes.append(shape) + + _tree_map_with_path(_tree_map_helper, combined_args, dynamic_shapes) + return flat_shapes + + +def _clean_dynamic_markers(tensor: torch.Tensor) -> None: + for attr in ( + "_dynamo_weak_dynamic_indices", + "_dynamo_dynamic_indices", + "_dynamo_dynamic_range", + "_dynamo_static_indices", + "_dynamo_unbacked_indices", + "_dynamo_propagated_dynamic_indices", + "_has_dynamo_dim_marking", + ): + if hasattr(tensor, attr): + delattr(tensor, attr) + + +def produce_guards_and_solve_constraints( + fake_mode: FakeTensorMode, + gm: torch.fx.GraphModule, + dynamic_shapes: dict[str, Any] | tuple[Any] | list[Any] | None, + equalities_inputs: EqualityConstraint, + original_signature: inspect.Signature, +) -> None: + """ + Given a fake mode, sources pairs corresponding to equal dynamic shape dimensions, + and a graph module, produce guards on the fake mode's shape env (raising constraint + violations if any), solve (to suggest simplifications or fixes). + Dynamo already performs this, so this is for non-strict mode. + + Additional inputs: + equalities_inputs: the equality constraints to use for guards + original_signature: the signature of the forward method + """ + shape_env = fake_mode.shape_env + if shape_env is None: + raise AssertionError("fake_mode.shape_env must not be None") + if shape_env.tracked_fakes is None: + raise AssertionError("shape_env.tracked_fakes must not be None") + + placeholders = [tf.fake for tf in shape_env.tracked_fakes] + sources = [tf.source for tf in shape_env.tracked_fakes] + input_contexts = [tf.symbolic_context for tf in shape_env.tracked_fakes] + constraint_violation_error = None + try: + shape_env.produce_guards( + placeholders, + sources, + input_contexts=input_contexts, + equalities_inputs=equalities_inputs, + ignore_static=False, + ) + except ConstraintViolationError as e: + constraint_violation_error = e + + shape_env.frozen = True + dim_constraints = shape_env.dim_constraints + if dim_constraints is None: + # Expected when shape_env.produce_guards throws an early constraint violation error. + # There is nothing to solve for in this case. + # TODO(avik): Maybe record the constraint violation error instead and replay later? + if not constraint_violation_error: + raise AssertionError( + "expected constraint_violation_error when dim_constraints is None" + ) + raise constraint_violation_error + dim_constraints.solve() + forced_specializations = dim_constraints.forced_specializations() + + msg = dim_constraints.prettify_results( + original_signature, + dynamic_shapes, # type: ignore[arg-type] + constraint_violation_error, + forced_specializations, # type: ignore[arg-type] + ) + + if constraint_violation_error: + if constraint_violation_error.args: + constraint_violation_error.args = ( + constraint_violation_error.args[0] + msg, + ) + else: + constraint_violation_error.args = (msg,) + elif forced_specializations: + constraint_violation_error = ConstraintViolationError(msg) + if constraint_violation_error: + raise constraint_violation_error + + +def is_int(x: object) -> TypeGuard[int | torch.SymInt]: + return isinstance(x, int) or (isinstance(x, torch.SymInt) and x.node.expr.is_number) + + +def _constrain_user_specified_dimhint_range( + symint: torch.SymInt, + hint: int, + dim: _DimHint, + range_constraints: dict["Expr", "ValueRanges[Expr]"], + shape_env: ShapeEnv, + keypath: KeyPath, + i: int | None = None, +) -> str | None: + trace_vr = ( + range_constraints[symint.node.expr] + if not is_int(symint) + else ValueRanges(int(symint), int(symint)) + ) + + # warn on 0/1 specialization for Dim.AUTO; not an actual error + if dim.type == _DimHintType.AUTO and trace_vr.is_singleton() and hint in (0, 1): + pathstr = f"inputs{pytree.keystr(keypath)}" + if i is not None: + pathstr += f".shape[{i}]" + msg = ( + f"dimension {pathstr} 0/1 specialized; Dim.AUTO was specified along " + + f"with a sample input with hint = {hint}." + ) + log.warning(msg) + + try: + user_vr = ValueRanges( + lower=0 if dim.min is None else dim.min, + upper=int_oo if dim.max is None else dim.max, + ) + if is_int(symint): + out_vr = trace_vr & user_vr + else: + range_constraints[symint.node.expr] &= user_vr + shape_env.var_to_range[symint.node._expr] &= user_vr + out_vr = range_constraints[symint.node.expr] + + # check for Dim.DYNAMIC specializations; special case error message on 0/1 + if dim.type == _DimHintType.DYNAMIC and out_vr.is_singleton(): + path = f"inputs{pytree.keystr(keypath)}" + if i is not None: + path += f".shape[{i}]" + if ( + trace_vr.is_singleton() + and hint in (0, 1) + and not torch.fx.experimental._config.backed_size_oblivious + ): + msg = ( + f"- Received user-specified dim hint Dim.DYNAMIC(min={dim.min}, max={dim.max}), " + f"but export 0/1 specialized due to hint of {hint} for dimension {path}." + ) + else: + msg = ( + f"- Received user-specified dim hint Dim.DYNAMIC(min={dim.min}, max={dim.max}), " + f"but tracing inferred a static shape of {out_vr.lower} for dimension {path}." + ) + return msg + + except torch.utils._sympy.value_ranges.ValueRangeError: + path = f"inputs{pytree.keystr(keypath)}" + if i is not None: + path += f".shape[{i}]" + msg = ( + f"- Received user-specified min/max range of [{dim.min}, {dim.max}], " + f"conflicting with the inferred min/max range of [{trace_vr.lower}, {trace_vr.upper}], " + f"for {path}." + ) + return msg + + return None + + +def make_constraints( + fake_mode: FakeTensorMode, + gm: torch.fx.GraphModule, + combined_args: dict[str, Any], + dynamic_shapes: dict[str, Any] | tuple[Any] | list[Any] | None, + num_lifted_inputs: int, +) -> dict["Expr", "ValueRanges[Expr]"]: + """ + Given a fake mode's shape env and user-specified dynamic shapes, + return the resulting range constraints and equality constraints. + + Additional args: + num_lifted_inputs: the number of non-user-input placeholder nodes in the graph + (used only to enumerate the user-input nodes) + """ + + shape_env = fake_mode.shape_env + if shape_env is None: + raise AssertionError("fake_mode.shape_env must not be None") + inline_constraints = gm.meta.get("inline_constraints", []) + range_constraints = defaultdict(lambda: ValueRanges(0, int_oo)) | inline_constraints + if not dynamic_shapes: + return dict(range_constraints) + + # clean up dynamic markers from tensors + flat_paths, flat_args = zip(*pytree.tree_flatten_with_path(combined_args)[0]) + for arg in flat_args: + if isinstance(arg, torch.Tensor): + _clean_dynamic_markers(arg) + + # get individual dynamic shapes spec for each input + if not isinstance(dynamic_shapes, dict): + if not isinstance(dynamic_shapes, (tuple, list)): + raise AssertionError( + f"expected dict, tuple, or list for dynamic_shapes, got {type(dynamic_shapes)}" + ) + combined_args = type(dynamic_shapes)(combined_args.values()) # type: ignore[assignment, misc] + flat_dynamic_shapes = _flatten_dynamic_shapes(combined_args, dynamic_shapes) + + # check number of shapes vs. number of inputs + num_placeholders = [node.op == "placeholder" for node in gm.graph.nodes].count(True) + if len(flat_dynamic_shapes) != num_placeholders - num_lifted_inputs: + raise AssertionError( + f"expected {num_placeholders - num_lifted_inputs} shapes, got {len(flat_dynamic_shapes)}" + ) + + free_symbols = set() + range_violations: list[str] = [] + for input_index, node in enumerate(gm.graph.nodes): + meta_val = node.meta.get("val") + + if ( + input_index < num_lifted_inputs + or node.op != "placeholder" + or meta_val is None + ): + continue + + elif _is_constant_argument(meta_val) or isinstance(meta_val, CustomObjArgument): + continue + + shape_spec = flat_dynamic_shapes[input_index - num_lifted_inputs] + keypath = flat_paths[input_index - num_lifted_inputs] + flat_arg = flat_args[input_index - num_lifted_inputs] + + if isinstance(meta_val, int) or ( + isinstance(meta_val, torch.SymInt) and meta_val.node.expr.is_number + ): + pass + + elif isinstance(meta_val, torch.SymInt): + if shape_spec is not None and isinstance(shape_spec, _DimHint): + hint = flat_arg + range_constraints[meta_val.node.expr] &= shape_env.bound_sympy( + meta_val.node._expr + ) + violation = _constrain_user_specified_dimhint_range( + meta_val, + hint, + shape_spec, + range_constraints, + shape_env, + keypath, + None, + ) + if violation: + range_violations.append(violation) + else: + raise RuntimeError("nyi") + free_symbols.update(meta_val.node.expr.free_symbols) + + elif isinstance(meta_val, torch.Tensor): + for i, d in enumerate(node.meta["val"].shape): + dim = None + if isinstance(shape_spec, (list, tuple)): + dim = shape_spec[i] + elif isinstance(shape_spec, dict): + dim = shape_spec.get(i) + if not is_int(d): + # Compute the range constraint for the symbolic expression corresponding + # to this shape dimension and store it. + if dim is None or isinstance(dim, _DimHint): + range_constraints[d.node.expr] &= shape_env.bound_sympy( + d.node.expr + ) + else: + range_constraints[d.node.expr] &= ValueRanges( + lower=dim.min, upper=dim.max + ) + + free_symbols.update(d.node.expr.free_symbols) + + # check user-specified min/max range for DimHints; + # we might want to do this even if model tracing inferred a static dimension. + if isinstance(dim, _DimHint): + hint = flat_arg.shape[i] + violation = _constrain_user_specified_dimhint_range( + d, hint, dim, range_constraints, shape_env, keypath, i + ) + if violation: + range_violations.append(violation) + else: + raise RuntimeError(f"Unfamiliar meta val: {meta_val}") + + if range_violations: + prefix = "Found the following conflicts between user-specified ranges and inferred ranges from model tracing:\n" + raise ValueError(prefix + "\n".join(range_violations)) + + for symbol in free_symbols: + if symbol not in range_constraints: + # Placeholders can have symbolic shapes that are derived expressions. + # The above code will record direct range constraints for them + # so that we can do runtime assertions. In addition, for serde checks + # we want to record range constraints for their root symbols. + range_constraints[symbol] = shape_env.var_to_range[symbol] + + return dict(range_constraints) + + +def _gather_constant_attrs(m: torch.nn.Module) -> ConstantAttrMap: + """Search the module hierarchy, gathering up all tensor and ScriptObject constants. + + Returns a dictionary mapping hash(value) to the name of the constant. We + have to abuse `hash` here unfortunately, see: [ScriptObject hash]. + """ + constants = ConstantAttrMap() + buffers_parameters = set(m.buffers()) + buffers_parameters.update(m.parameters()) + + def inner( + m: torch.nn.Module, prefix_atoms: list[str], constants: ConstantAttrMap + ) -> None: + for k, v in m.__dict__.items(): + if isinstance( + v, + ( + torch.Tensor, + torch.ScriptObject, + FakeScriptObject, + ), + ): + if v in buffers_parameters: + # filter out buffers and parameters, leaving only constants + continue + + fqn = ".".join(prefix_atoms + [k]) + constants.add(v, fqn) + for k, v in m.named_children(): + inner(v, prefix_atoms + [k], constants) + + inner(m, [], constants) + return constants + + +def _get_graph_inputs_of_type_nn_module( + args: tuple[tuple[Any], dict[Any, Any]] | None, +) -> set[type[torch.nn.Module]]: + if args is None: + return set() + module_types = set() + for arg in pytree.tree_leaves(args): + if isinstance(arg, torch.nn.Module): + module_types.add(type(arg)) + return module_types + + +def _enter_enable_graph_inputs_of_type_nn_module( + module_types: set[type[torch.nn.Module]], +) -> None: + for t in module_types: + torch._export.utils.register_module_as_pytree_input_node(t) + + +def _exit_enable_graph_inputs_of_type_nn_module( + module_types: set[type[torch.nn.Module]], +) -> None: + for t in module_types: + torch._export.utils.deregister_module_as_pytree_input_node(t) + + +@contextlib.contextmanager +def _enable_graph_inputs_of_type_nn_module( + args: tuple[tuple[Any], dict[Any, Any]] | None, +) -> Generator[None, None, None]: + if args is None: + yield + return + + module_types = _get_graph_inputs_of_type_nn_module(args) + _enter_enable_graph_inputs_of_type_nn_module(module_types) + try: + yield + finally: + _exit_enable_graph_inputs_of_type_nn_module(module_types) + + +@contextlib.contextmanager +def _fakify_module_inputs( + args: tuple[Any], + kwargs: dict[Any, Any], + fake_mode: torch._subclasses.fake_tensor.FakeTensorMode, +) -> Generator[None, None, None]: + # This context manager is used to fakify module inputs. + # Inputs: + # args, kwargs: the args and kwargs containing module inputs that haven't been fakified. + # fake_mode: the fake mode to be used for fakifying script objects. It's the same mode that fakify input tensors. + + ctxs = [_enable_graph_inputs_of_type_nn_module((args, kwargs))] + for arg in pytree.tree_leaves((args, kwargs)): + if isinstance(arg, torch.nn.Module): + fake_params_buffers = _fakify_params_buffers(fake_mode, arg) + ctxs.append( + torch.nn.utils.stateless._reparametrize_module( + arg, + fake_params_buffers, + tie_weights=True, + strict=True, + stack_weights=True, + ) + ) + with contextlib.ExitStack() as stack: + for ctx in ctxs: + stack.enter_context(ctx) + yield + + +@contextlib.contextmanager +def _fakify_script_objects( + mod: _ModuleT, + args: Sequence[Any], + kwargs: dict[Any, Any], + fake_mode: torch._subclasses.fake_tensor.FakeTensorMode | None, +) -> Generator[tuple[_ModuleT, Any, Any, ConstantAttrMap, dict[Any, Any]], None, None]: + # This context manager is used to fakify script objects into FakeScriptObject. + # Inputs: + # mod: the module to be exported, it (and its recursive submodules)'s script object attrs haven't been fakified. + # args, kwargs: the args and kwargs inputs for mod, script object inputs haven't been fakified. + # fake_mode: the fake mode to be used for fakifying script objects. It's the same mode that fakify input tensors. + # + # Returns: + # mod: the patched module, its (and its recursive submodules) script object attrs have been fakified. + # fake_args, fake_kwargs: new fakified args and kwargs. + # Script object inputs have been fakified. Don't touch the tensors. + # fake_constant_attrs: a new map from FakeScriptObject to the fqn of the original script object. + # fake_to_real: a mapping between FakeScriptObject and the original script object in order to un-do the patching. + + constant_attrs: ConstantAttrMap = _gather_constant_attrs(mod) + if any(isinstance(obj, FakeScriptObject) for obj in constant_attrs.values()): + raise AssertionError("Mod shouldn't contain any FakeScriptObject.") + if pytree.tree_any(lambda obj: isinstance(obj, FakeScriptObject), (args, kwargs)): + raise AssertionError("args and kwargs shouldn't contain any FakeScriptObject.") + + patched_attr: dict[str, Any] = {} + fake_constant_attrs = ConstantAttrMap() + fake_to_real: dict[Any, Any] = {} + + def _maybe_fakify_obj(obj: object) -> FakeScriptObject | torch.ScriptObject: + fake_obj = torch._library.fake_class_registry.maybe_to_fake_obj(fake_mode, obj) + fake_to_real[fake_obj] = obj + return fake_obj + + def _leaf_mod_and_attr( + mod: torch.nn.Module, attr_fqn: str + ) -> tuple[torch.nn.Module, str]: + *prefix_attr, last_attr = attr_fqn.split(".") + cur_mod = mod + for attr in prefix_attr: + cur_mod = getattr(cur_mod, attr) + return cur_mod, last_attr + + try: + for obj, fqns in constant_attrs.items(): + if torch._library.fake_class_registry._is_script_object( + obj + ) or is_custom_class_obj(obj): + fake_script_obj = _maybe_fakify_obj(obj) + for fqn in fqns: + cur_mod, attr = _leaf_mod_and_attr(mod, fqn) + if obj is not getattr(cur_mod, attr): + raise AssertionError( + f"obj mismatch at {fqn}: expected {obj}, got {getattr(cur_mod, attr)}" + ) + setattr(cur_mod, attr, fake_script_obj) + fake_constant_attrs.add(fake_script_obj, fqn) + patched_attr[fqn] = obj + else: + for fqn in fqns: + fake_constant_attrs.add(obj, fqn) + + fake_args, fake_kwargs = pytree.tree_map_only( + torch.ScriptObject, _maybe_fakify_obj, (args, kwargs) + ) + yield (mod, fake_args, fake_kwargs, fake_constant_attrs, fake_to_real) + finally: + for fqn, orig_obj in patched_attr.items(): + cur_mod, attr = _leaf_mod_and_attr(mod, fqn) + setattr(cur_mod, attr, orig_obj) + + +class _NonStrictTorchFunctionHandler(torch.overrides.TorchFunctionMode): + """ + 1. Handles data-dependent errors raised by torch function calls in non-strict. + + Any data-dependent error is due to some condition on unbacked symints + that cannot be resolved. A mechanical way of fixing the error is to use + a torch._check() call to assert either that condition or its negation. + The handler suggests these options as code and points to the location + of the torch function call that raised the error as part of the error + message shown to the user, who can then simply select and copy-paste + a suggested fix at that location. + + NOTE: Not all data-dependent errors are raised by torch function calls. + In particular, conditions on unbacked symints can appear outside such + calls, and as such are not handled here. + + 2. Overrides torch functions that are known to cause problems in non-strict. + + Certain Python features, such as indexing/slicing, cannot be intercepted + in non-strict. Likewise, certain legacy ops, such as distributed collectives, + may need to be mapped to other ops. When there is special handling in Dynamo + for such things, tracing can fail in non-strict (while succeeding in strict). + Fortunately, redirecting to other torch functions can often fix such issues. + + 3. Handles line-of-code logging for each torch function call in non-strict. + + Usage: TORCHEXPORT_EXTENDED_DEBUG_CURRENT_LOC=1 TORCH_LOGS="+export" ... + """ + + def _override( + self, func: Callable[..., object], args: Sequence[Any], kwargs: dict[str, Any] + ) -> tuple[Callable[..., object], Sequence[Any], dict[str, Any]]: + if torch.distributed.is_available(): + from torch.distributed._functional_collectives import ( + _remap_traceable_collective, + ) + + # Redirect legacy collectives to functional collectives, following + # Dynamo. See torch/distributed/_functional_collectives.py for details. + remapped = _remap_traceable_collective(func, args, kwargs) + if remapped is not None: + return remapped + if func is torch.tensor: + # Redirect to Python implementation of torch.tensor for data with symints. + # NOTE(avik): We don't unconditionally redirect to this implementation + # because it has some known incompletenesses, e.g., it doesn't support + # empty data. See https://github.com/pytorch/pytorch/issues/143216 + if any( + isinstance(a, (torch.SymInt, torch.SymFloat, torch.SymBool)) + for a in pytree.tree_flatten(args[0])[0] + ): + return torch._refs.tensor, args, kwargs + if func.__name__ == "__getitem__" and isinstance(args[0], torch.Tensor): + + def is_scalar_tensor_index(item: object) -> TypeGuard[torch.Tensor]: + if not isinstance(item, torch.Tensor) or item.ndim != 0: + return False + # vmap BatchedTensor scalar indices must remain tensor indices; + # calling item() on them is unsupported. + if torch._C._functorch.is_batchedtensor(item): + return False + + from torch._prims_common import is_integer_dtype + + return is_integer_dtype(item.dtype) + + def maybe_tensor_index_item(item: object) -> Any: + if is_scalar_tensor_index(item): + return item.item() + return item + + def rewrite( + dim: int, item: Any + ) -> tuple[int, tuple[Callable[..., object], list[Any]]] | None: + # Redirect to torch.select for indexing. + if item is None: + return dim + 1, (torch.unsqueeze, [dim]) + if isinstance(item, (int, torch.SymInt)): + return dim, (torch.select, [dim, item]) + if is_scalar_tensor_index(item): + return dim, ( + lambda t, dim, item: torch.select( + t, dim, maybe_tensor_index_item(item) + ), + [dim, item], + ) + # Redirect to torch.ops.aten.slice for slicing. + if isinstance(item, slice): + step = 1 if item.step is None else item.step + if ( + item.start is None + and item.stop is None + and isinstance(step, int) + and step == 1 + ): + # no-op + return dim + 1, (lambda t: t, []) + return dim + 1, ( + lambda t, dim, start, stop, step: torch.ops.aten.slice( + t, + dim, + maybe_tensor_index_item(start), + maybe_tensor_index_item(stop), + maybe_tensor_index_item(step), + ), + [dim, item.start, item.stop, step], + ) + # Otherwise do nothing. + + items = list(args[1]) if isinstance(args[1], tuple) else [args[1]] + + has_symint = False + index_ellipsis = None + t = args[0] + n_none_slices = t.ndim + 1 + for i, item in enumerate(items): + if ( + isinstance(item, torch.SymInt) + or ( + isinstance(item, slice) + and any( + isinstance(s, torch.SymInt) or is_scalar_tensor_index(s) + for s in (item.start, item.stop, item.step) + ) + ) + or is_scalar_tensor_index(item) + ): + has_symint = True + if item is Ellipsis: + index_ellipsis = i + if item is not None: + n_none_slices -= 1 + + # only rewrite when there are symints + if has_symint: + if index_ellipsis is not None: + none_slices = [slice(None)] * n_none_slices + items[index_ellipsis : index_ellipsis + 1] = none_slices + + dim = 0 + # Sequence rewrites. + sequence: list[tuple[Callable[..., object], list[Any]]] = [] + for item in items: + if (r := rewrite(dim, item)) is None: + return func, args, kwargs + dim, call_spec = r + sequence.append(call_spec) + + def run() -> Any: + # Run sequence. + # pyrefly: ignore [bad-index, index-error] + t = args[0] + for _method, _args in sequence: + t = _method(t, *_args) + return t + + return run, [], {} + + return func, args, kwargs + + def __torch_function__( + self, + func: Callable[..., object], + types: Sequence[type], + args: Sequence[Any] = (), + kwargs: dict[str, Any] | None = None, + ) -> Any: + kwargs = kwargs or {} + if torch.compiler.is_dynamo_compiling(): + return func(*args, **kwargs) + + if log.isEnabledFor(logging.DEBUG) and config.extended_debug_current_loc: + frame = _find_user_code_frame() + if frame is not None: + log.debug( + "%s called at %s:%s in %s", + func.__qualname__, + frame.f_code.co_filename, + frame.f_lineno, + frame.f_code.co_name, + ) + + func, args, kwargs = self._override(func, args, kwargs) + try: + return func(*args, **kwargs) + except GuardOnDataDependentSymNode as e: + _suggest_fixes_for_data_dependent_error_non_strict(e) + raise + except RuntimeError as e: + if _is_raw_triton_kernel_data_ptr_error(func, e): + raise RuntimeError(_RAW_TRITON_KERNEL_NON_STRICT_EXPORT_ERROR) from e + raise diff --git a/.venv/lib/python3.12/site-packages/torch/_export/pass_base.py b/.venv/lib/python3.12/site-packages/torch/_export/pass_base.py new file mode 100644 index 0000000000000000000000000000000000000000..a9e5826f057aa2d068da8bf24f82185d538a9b51 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/pass_base.py @@ -0,0 +1,505 @@ +# mypy: allow-untyped-defs +import operator +import traceback +from collections.abc import Callable +from contextlib import nullcontext +from typing import Any + +import torch +from torch import fx +from torch._dispatch.python import enable_python_dispatcher +from torch._export.pass_infra.node_metadata import NodeMetadata +from torch._export.pass_infra.proxy_value import ProxyValue +from torch._higher_order_ops.map import _unstack_pytree +from torch._subclasses import FakeTensor, UnsupportedFakeTensorException +from torch._subclasses.fake_tensor import ( + FakeTensorMode, + is_fake_tensor, + maybe_get_fake_constant, + maybe_get_fake_mode, +) +from torch.fx import traceback as fx_traceback +from torch.fx.experimental.proxy_tensor import PythonKeyTracer +from torch.fx.experimental.symbolic_shapes import ( + compute_unbacked_bindings, + PropagateUnbackedSymInts, +) +from torch.fx.graph import CodeGen +from torch.fx.passes.infra.pass_base import PassBase, PassResult +from torch.fx.passes.shape_prop import _extract_tensor_metadata, TensorMetadata +from torch.utils import _pytree as pytree + + +__all__ = ["_ExportPassBaseDeprecatedDoNotUse"] + + +Argument = Any +Value = Any +Fn = Callable[..., Any] +PassType = Callable[[torch.fx.GraphModule], PassResult | None] + + +_TORCH_SYM_OPS: set[Callable] = { + torch.sym_int, + torch.sym_float, + torch.sym_ite, + torch.sym_max, + torch.sym_min, + torch.sym_not, + torch.sym_sqrt, +} + + +class ExportPassBaseError(RuntimeError): + pass + + +class _ExportPassBaseDeprecatedDoNotUse(PassBase): + """ + Interpreter-based pass class to help users maintain the IR spec while writing + transformations. + """ + + @staticmethod + def _create_dummy_node_metadata(): + return NodeMetadata({"stack_trace": "".join(traceback.format_stack(limit=1))}) + + class ExportTracer(PythonKeyTracer): + def __init__( + self, callback: "_ExportPassBaseDeprecatedDoNotUse", codegen: CodeGen + ) -> None: + super().__init__() + self.callback = callback + self.root = torch.nn.Module() + self.graph = torch.fx.Graph() + self.graph.set_codegen(codegen) + self.tensor_attrs: dict[str, torch.Tensor] = {} # type: ignore[assignment] + self.fake_tensor_mode: FakeTensorMode | None = None + self.submodules: dict[torch.nn.Module, str] = {} + + def trace(self) -> None: # type: ignore[override] + raise ExportPassBaseError("ExportTracer doesn't support trace().") + + def create_arg(self, a: Argument) -> torch.fx.Node: + if isinstance(a, torch.nn.Module): + if a not in self.submodules: + name_submodule = f"submodule_{len(self.submodules)}" + self.root.add_module(name_submodule, a) + self.submodules[a] = name_submodule + elif is_fake_tensor(a): + if maybe_get_fake_constant(a) is None: + raise ExportPassBaseError(f"Cannot add {a} to graph.") + a = maybe_get_fake_constant(a) + node = super().create_arg(a) + if ( + isinstance(a, torch.Tensor) + and isinstance(node, torch.fx.Node) + and node.op == "get_attr" + ): + self.set_metadata(node, a) + self.callback.on_attr(ProxyValue(a, node)) + return node + + def set_metadata( + self, + node: torch.fx.Node, + value: Argument, + ) -> None: + # propagate the fake tensor or sym nodes + def make_val( + x: Argument, + ) -> ( + FakeTensor + | torch.SymInt + | torch.SymFloat + | torch.SymBool + | int + | float + | bool + | str + | None + ): + if isinstance(x, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR + return x + elif isinstance(x, torch.Tensor): + if x.is_quantized: + # TODO (tmanlaibaatar) properly support Quantized FakeTensor + x = torch.dequantize(x) + + try: + if self.fake_tensor_mode is None: + raise AssertionError("fake_tensor_mode must not be None") + # TODO we should allocate static shapes + # for param/buffer values + if isinstance(x, torch.nn.Parameter): + fake_tensor = self.fake_tensor_mode.from_tensor( + x, static_shapes=True + ) + else: + fake_tensor = self.fake_tensor_mode.from_tensor(x) + except UnsupportedFakeTensorException: + # TODO: This is just a workaround to get over the + # x.as_subclass error + print( + "Fakeifying a Tensor subclass is not supported \ + right now. Instead a TensorMetadata is used." + ) + fake_tensor = None + return fake_tensor + elif isinstance( + x, + ( + torch.SymInt, + torch.SymFloat, + torch.SymBool, + int, + float, + bool, + str, + ), + ): + return x + else: + return None + + node.meta["val"] = pytree.tree_map(make_val, value) + + # Set the tensor_metadata for values that do not have a corresponding FakeTensor + def make_tensor_meta(x: Argument) -> TensorMetadata | None: + if not is_fake_tensor(x) and isinstance(x, torch.Tensor): + if x.is_quantized: + # TODO (tmanlaibaatar) properly support Quantized FakeTensor + x = torch.dequantize(x) + + try: + if self.fake_tensor_mode is None: + raise AssertionError("fake_tensor_mode must not be None") + _ = self.fake_tensor_mode.from_tensor(x) + tensor_meta = None + except UnsupportedFakeTensorException: + # TODO: This is just a workaround to get over the + # x.as_subclass error + tensor_meta = _extract_tensor_metadata(x) + return tensor_meta + else: + return None + + node.meta["tensor_meta"] = pytree.tree_map(make_tensor_meta, value) + + class ExportInterpreter(fx.Interpreter): + def __init__( + self, callback: "_ExportPassBaseDeprecatedDoNotUse", gm: fx.GraphModule + ) -> None: + super().__init__(gm) + self.callback = callback + self.node: torch.fx.Node = next(iter(gm.graph.nodes)) + + # pyrefly: ignore [bad-override] + def placeholder( + self, + target: str, # type: ignore[override] + args: tuple[Argument, ...], + kwargs: dict[str, Argument], + ) -> ProxyValue: + arg = super().placeholder(target, args, kwargs) + return self.callback.placeholder(target, arg, NodeMetadata(self.node.meta)) + + def output( + self, + target: torch.fx.node.Target, + args: tuple[Argument, ...], + kwargs: dict[str, Argument], + ) -> ProxyValue: + return self.callback.output(args[0], NodeMetadata(self.node.meta)).data # type: ignore[return-value] + + def call_function( + self, + target: torch.fx.node.Target, + args: tuple[Argument, ...], + kwargs: dict[str, Argument], + ) -> ProxyValue: + meta = NodeMetadata(self.node.meta) + + if target is operator.getitem: + value, key = args + return self.callback.call_getitem(value, key, meta) + elif getattr(target, "__module__", None) in { + "_operator", + "builtins", + "math", + }: + if not callable(target): + raise AssertionError(f"expected callable target, got {target}") + return self.callback.call_sym(target, args, meta) + elif target in _TORCH_SYM_OPS: + if not callable(target): + raise AssertionError(f"expected callable target, got {target}") + return self.callback.call_sym(target, args, meta) + elif isinstance( + target, (torch._ops.OpOverload, torch._ops.OpOverloadPacket) + ): + return self.callback.call_operator( + target, + args, + kwargs, + meta, + ) + elif target is torch.ops.higher_order.cond: + pred, true_fn, false_fn, inputs = args + return self.callback.call_cond(pred, true_fn, false_fn, inputs, meta) + elif target is torch.ops.higher_order.map_impl: + f, mapped_args, operands = args # type: ignore[assignment] + return self.callback.call_map(f, mapped_args, operands, meta) + # For other unregistered HigherOrderOps, just interpret them blindly + elif isinstance(target, torch._ops.HigherOrderOperator): + return self.callback._fx( + "call_function", + target, + args, + kwargs, + meta, + ) + else: + raise ExportPassBaseError(f"Unsupported target type: {target}") + + def get_attr( # type: ignore[override] + self, + target: str, + args: tuple[Argument, ...], + kwargs: dict[str, Argument], + ) -> Argument: + return super().get_attr(target, args, kwargs) + + def call_module( + self, + target: torch.fx.node.Target, + args: tuple[Argument, ...], + kwargs: dict[str, Argument], + ) -> None: + raise ExportPassBaseError("call_module is not supported.") + + def call_method( # type: ignore[override] + self, + target: str, + args: tuple[Argument, ...], + kwargs: dict[str, Argument], + ) -> None: + raise ExportPassBaseError("call_method is not supported.") + + def run_node(self, n: torch.fx.Node) -> Argument: + self.node = n + self.callback.node_debug_str = n.format_node() + return super().run_node(n) + + def __init__(self) -> None: + self.interpreter = PropagateUnbackedSymInts( + torch.fx.GraphModule(torch.nn.Module(), torch.fx.Graph()) + ) + self.tracer = self.ExportTracer(self, CodeGen()) + self.fake_tensor_mode: FakeTensorMode | None = None + self._initialized = True + self.node_debug_str: str | None = None + + def _fx( + self, + kind: str, + target: torch.fx.node.Target, + args: tuple[Argument, ...], + kwargs: dict[str, Argument], + meta: NodeMetadata, + ) -> ProxyValue: + args_data, kwargs_data = pytree.tree_map_only( + ProxyValue, lambda x: x.data, (args, kwargs) + ) + res_data = getattr(self.interpreter, kind)(target, args_data, kwargs_data) + args_proxy, kwargs_proxy = pytree.tree_map_only( + ProxyValue, lambda x: x.proxy, (args, kwargs) + ) + + name = None + if isinstance(target, torch._ops.OpOverload): + name = self.tracer.graph._target_to_str(target.overloadpacket.__name__) + + res_proxy = self.tracer.create_proxy( + kind, target, args_proxy, kwargs_proxy, name=name + ) + res_proxy.node.meta.update(meta.data) + if self.fake_tensor_mode and (shape_env := self.fake_tensor_mode.shape_env): + if symbol_to_path := compute_unbacked_bindings(shape_env, res_data): + res_proxy.node.meta["unbacked_bindings"] = symbol_to_path + self.tracer.set_metadata(res_proxy.node, res_data) + return ProxyValue(res_data, res_proxy) + + def inputs(self, graph_module: torch.fx.GraphModule) -> list[Argument]: + # TODO(angelayi): Update this with what we decide to do for metadata in + # the exported graph module + if (args := graph_module.meta.get("args", None)) is not None: + return list(args) + + def extract_input(node: torch.fx.Node) -> FakeTensor | None: + if "val" in node.meta: + fake = node.meta["val"] + if hasattr(fake, "constant") and fake.constant is not None: + return fake.constant + return fake + elif tensor_meta := node.meta.get("tensor_meta"): + if self.fake_tensor_mode is None: + raise AssertionError("fake_tensor_mode must not be None") + return FakeTensor( + self.fake_tensor_mode, + torch.empty( + tensor_meta.shape, + dtype=tensor_meta.dtype, + device="meta", + requires_grad=tensor_meta.requires_grad, + memory_format=tensor_meta.memory_format, + ), + torch.device("cpu"), + ) + elif len(node.users) == 0: + return None + raise ExportPassBaseError( + f"Cannot construct an input for graph module: {graph_module}.", + ) + + return [ + extract_input(node) + for node in graph_module.graph.nodes + if node.op == "placeholder" + ] + + def on_attr(self, attr: ProxyValue) -> None: + pass + + def placeholder(self, name: str, arg: Argument, meta: NodeMetadata) -> ProxyValue: + arg_proxy = self.tracer.create_proxy("placeholder", name, (), {}) + arg_proxy.node.meta = meta.data + self.tracer.set_metadata(arg_proxy.node, arg) + return ProxyValue(arg, arg_proxy) + + def call_operator( + self, + op, + args: tuple[Argument, ...], + kwargs: dict[str, Argument], + meta: NodeMetadata, + ) -> ProxyValue: + return self._fx("call_function", op, args, kwargs, meta) + + def call_sym( + self, + target: Fn, + args: tuple[Argument, ...], + meta: NodeMetadata, + ) -> ProxyValue: + return self._fx("call_function", target, args, {}, meta) + + def call_cond( + self, + pred: ProxyValue, + true_fn: torch.fx.GraphModule, + false_fn: torch.fx.GraphModule, + inputs: list[Argument], + meta: NodeMetadata, + ) -> ProxyValue: + true_branch = self.call_submodule(true_fn, tuple(inputs)) + false_branch = self.call_submodule(false_fn, tuple(inputs)) + if true_branch is None: + raise AssertionError("true_branch must not be None") + if false_branch is None: + raise AssertionError("false_branch must not be None") + return self._fx( + "call_function", + torch.ops.higher_order.cond, + (pred, true_branch.graph_module, false_branch.graph_module, list(inputs)), + {}, + meta, + ) + + def call_map( + self, + f: torch.fx.GraphModule, + mapped_args: list[ProxyValue], + operands: list[ProxyValue], + meta: NodeMetadata, + ) -> ProxyValue: + xs = _unstack_pytree([arg.data for arg in mapped_args])[0] + f_branch = self.call_submodule(f, tuple(xs + [arg.data for arg in operands])) + if f_branch is None: + raise AssertionError("f_branch must not be None") + return self._fx( + "call_function", + torch.ops.higher_order.map_impl, + (f_branch.graph_module, mapped_args, operands), + {}, + meta, + ) + + def call_getitem( + self, value: ProxyValue, key: int, meta: NodeMetadata + ) -> ProxyValue: + return self._fx("call_function", operator.getitem, (value, key), {}, meta) + + def output(self, results: list[Argument], meta: NodeMetadata) -> ProxyValue: + return self._fx("output", "output", (results,), {}, meta) + + def call_submodule( + self, graph_module: fx.GraphModule, inputs: tuple[Argument, ...] + ) -> PassResult: + prev_tracer, self.tracer = ( + self.tracer, + self.ExportTracer(self, graph_module.graph._codegen), + ) + self.tracer.fake_tensor_mode = prev_tracer.fake_tensor_mode + interpreter = self.ExportInterpreter(self, graph_module) + # pyrefly: ignore [bad-assignment] + prev_interpreter, self.interpreter = ( + self.interpreter, + torch.fx.Interpreter( # type: ignore[assignment] + torch.fx.GraphModule(torch.nn.Module(), torch.fx.Graph()) + ), + ) + inputs_data = pytree.tree_map_only(ProxyValue, lambda x: x.data, inputs) + with fx_traceback.preserve_node_meta(): + interpreter.run(*inputs_data) + + new_graph_module = torch.fx.GraphModule(self.tracer.root, self.tracer.graph) + + self.tracer = prev_tracer + self.interpreter = prev_interpreter + return PassResult( + new_graph_module, + True, + ) + + def call(self, graph_module: fx.GraphModule) -> PassResult: + if not getattr(self, "_initialized", False): + raise ExportPassBaseError( + "ExportPass is not initialized with __init__().", + ) + + inputs = self.inputs(graph_module) + + fake_tensor_mode = None + for i in inputs: + if is_fake_tensor(i): + if ( + fake_tensor_mode is not None + and fake_tensor_mode is not maybe_get_fake_mode(i) + ): + raise AssertionError("Multiple fake tensor mode detected.") + fake_tensor_mode = maybe_get_fake_mode(i) + if fake_tensor_mode is None: + self.tracer.fake_tensor_mode = FakeTensorMode(allow_non_fake_inputs=True) + fake_tensor_mode = nullcontext() # type: ignore[assignment] + dispatcher_mode = nullcontext() # type: ignore[assignment] + else: + fake_tensor_mode.allow_non_fake_inputs = True + self.tracer.fake_tensor_mode = fake_tensor_mode + dispatcher_mode = enable_python_dispatcher() # type: ignore[assignment] + self.fake_tensor_mode = self.tracer.fake_tensor_mode + + with fake_tensor_mode, dispatcher_mode: # type: ignore[assignment, union-attr] + result = self.call_submodule(graph_module, tuple(inputs)) + + return result diff --git a/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/__init__.py b/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b60dd6d7a34f3a90f44710b2a347edec8e95a75e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/__pycache__/node_metadata.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/__pycache__/node_metadata.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..187c19c182be9a3f4145c4026bd563d8a4179999 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/__pycache__/node_metadata.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/__pycache__/proxy_value.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/__pycache__/proxy_value.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8d6f59a73d51d7d609f28fd9b902c6240e12934 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/__pycache__/proxy_value.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/node_metadata.py b/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/node_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..9874dc1520fdbd6f4adc061dd7bccee031710797 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/node_metadata.py @@ -0,0 +1,32 @@ +from typing import Any + + +NodeMetadataValue = Any + + +PROTECTED_KEYS: set[str] = { + "val", + "stack_trace", + "nn_module_stack", + "debug_handle", + "tensor_meta", +} + + +class NodeMetadata: + def __init__(self, data: dict[str, Any]) -> None: + self.data: dict[str, Any] = data.copy() + + def __getitem__(self, key: str) -> NodeMetadataValue: + return self.data[key] + + def __setitem__(self, key: str, value: NodeMetadataValue) -> NodeMetadataValue: + if key in PROTECTED_KEYS: + raise RuntimeError(f"Could not override node key: {key}") + self.data[key] = value + + def __contains__(self, key: str) -> bool: + return key in self.data + + def copy(self) -> "NodeMetadata": + return NodeMetadata(self.data.copy()) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/proxy_value.py b/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/proxy_value.py new file mode 100644 index 0000000000000000000000000000000000000000..d4a3e1cc4a63c8e26cda39346507a3b9f96b1efa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/pass_infra/proxy_value.py @@ -0,0 +1,49 @@ +# pyre-strict +from collections.abc import Iterable, Iterator +from typing import Generic, TypeVar + +import torch + + +_T = TypeVar("_T") + + +class ProxyValue(Generic[_T]): + # pyre-ignore + def __init__(self, data: Iterable[_T], proxy: torch.fx.Proxy | torch.fx.Node): + # pyre-ignore + self.data = data + self.proxy_or_node = proxy + + @property + def node(self) -> torch.fx.Node: + if isinstance(self.proxy_or_node, torch.fx.Node): + return self.proxy_or_node + if not isinstance(self.proxy_or_node, torch.fx.Proxy): + raise AssertionError( + f"expected Node or Proxy, got {type(self.proxy_or_node)}" + ) + return self.proxy_or_node.node + + @property + def proxy(self) -> torch.fx.Proxy: + if not isinstance(self.proxy_or_node, torch.fx.Proxy): + raise RuntimeError( + f"ProxyValue doesn't have attached Proxy object. Node: {self.proxy_or_node.format_node()}" + ) + return self.proxy_or_node + + def to_tensor(self) -> torch.Tensor: + if not isinstance(self.data, torch.Tensor): + raise AssertionError(f"expected Tensor, got {type(self.data)}") + return self.data + + def is_tensor(self) -> bool: + return isinstance(self.data, torch.Tensor) + + # pyre-ignore + def __iter__(self) -> Iterator[_T]: + yield from self.data + + def __bool__(self) -> bool: + return bool(self.data) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__init__.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..aa9ce2ac03c23600c86ff02e38a2a4bfeefef9e2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/__init__.py @@ -0,0 +1 @@ +from .replace_view_ops_with_view_copy_ops_pass import ReplaceViewOpsWithViewCopyOpsPass diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb4246797bf0e624279f00dec20256d2066836ba Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/_node_metadata_hook.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/_node_metadata_hook.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba4c56b84a27188fd804a40db51e7151e5c2428a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/_node_metadata_hook.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/add_runtime_assertions_for_constraints_pass.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/add_runtime_assertions_for_constraints_pass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a87757d3385eb22f394d28bb61378775eaff462 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/add_runtime_assertions_for_constraints_pass.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/collect_tracepoints_pass.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/collect_tracepoints_pass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6dcb43d3a7e67110781bddb29ed2a29069bd84bd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/collect_tracepoints_pass.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/constant_folding.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/constant_folding.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0be07b3294e3c3b03c4195106104e6d974ce3215 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/constant_folding.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/functionalize_side_effectful_ops_pass.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/functionalize_side_effectful_ops_pass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d2b0162e11ef89ebdd48bfb0083845e60186285 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/functionalize_side_effectful_ops_pass.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/insert_custom_op_guards.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/insert_custom_op_guards.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac1fb18274dfed616634c9833d7541efbbdf170c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/insert_custom_op_guards.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/lift_constants_pass.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/lift_constants_pass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa0afff5026319b90512b97583589f6d92b30bd2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/lift_constants_pass.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/remove_runtime_assertions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/remove_runtime_assertions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16a5dd8be9f703a2d3cd2d7099730bf73fadcbd6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/remove_runtime_assertions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_autocast_with_hop_pass.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_autocast_with_hop_pass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3732e2ef2ac915bd4e1baefd7f9ba667e3a69644 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_autocast_with_hop_pass.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_quantized_ops_with_standard_ops_pass.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_quantized_ops_with_standard_ops_pass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ecccf05a3277d32b8985f06ea271b64e1b3838a2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_quantized_ops_with_standard_ops_pass.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_set_grad_with_hop_pass.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_set_grad_with_hop_pass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1b0dcb2b7643fcb66dda0b292202e8d387b1cd5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_set_grad_with_hop_pass.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_view_ops_with_view_copy_ops_pass.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_view_ops_with_view_copy_ops_pass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbe0dd169688df448d733982165dfa35af826289 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_view_ops_with_view_copy_ops_pass.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_with_hop_pass_util.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_with_hop_pass_util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4adeae9a3f301b54f86c8d48dd105e59cd22d5ac Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/passes/__pycache__/replace_with_hop_pass_util.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/_node_metadata_hook.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/_node_metadata_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..414bc04d1bad980fde10dd7e9dd3148445240da7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/_node_metadata_hook.py @@ -0,0 +1,112 @@ +# mypy: allow-untyped-defs +import contextlib +from typing import Any + +import torch +import torch.utils._pytree as pytree +from torch._dispatch.python import enable_python_dispatcher +from torch._subclasses.fake_tensor import FakeTensorMode +from torch.fx.graph_module import GraphModule + + +_EMPTY_NN_MODULE_STACK_KEY = "_empty_nn_module_stack_from_metadata_hook" + + +def _node_metadata_hook( + node: torch.fx.Node, + metadata: dict[str, Any] | None = None, + fake_mode: FakeTensorMode | None = None, +) -> None: + """ + Hook for adding the appropriate metadata to nodes that are created during a + pass using graph.create_node. An example of how to use it: + + ``` + with _set_node_metadata_hook(gm, + functools.partial(_node_metadata_hook, metadata={"stack_trace": "file"}) + ): + pass(gm) + ``` + + This hook should not work for all generic cases -- specifically it assumes + that nodes being added are only call_function nodes, and copies over the + first argument node's nn_module_stack. + """ + # pyrefly: ignore [bad-assignment] + fake_mode = fake_mode or contextlib.nullcontext() + + if node.op != "call_function" or not callable(node.target): + raise AssertionError(f"node: {node}, target: {node.target}") + + if ( + isinstance(node.target, torch._ops.OpOverload) + and len(node.target._schema.returns) == 0 + ): + node.meta["val"] = None + else: + fake_args, fake_kwargs = pytree.tree_map_only( + torch.fx.Node, lambda arg: arg.meta["val"], (node.args, node.kwargs) + ) + # pyrefly: ignore [bad-context-manager] + with fake_mode, enable_python_dispatcher(): + fake_res = node.target(*fake_args, **fake_kwargs) + node.meta["val"] = fake_res + + if metadata is not None: + for k, v in metadata.items(): + node.meta[k] = v + + # Copy over metadata from argument nodes + arg_meta = [ + arg.meta + for arg in pytree.tree_flatten((node.args, node.kwargs))[0] + if isinstance(arg, torch.fx.Node) + ] + if len(arg_meta) == 0: + return + arg_meta = arg_meta[0] + + node.meta["nn_module_stack"] = node.meta.get( + "nn_module_stack", + arg_meta.get( + "nn_module_stack", + { + _EMPTY_NN_MODULE_STACK_KEY: ( + _EMPTY_NN_MODULE_STACK_KEY, + _EMPTY_NN_MODULE_STACK_KEY, + ) + }, + ), + ) + + node.meta["torch_fn"] = node.meta.get( + "torch_fn", + ( + f"{node.target.__name__}_0", + f"{node.target.__class__.__name__}.{node.target.__name__}", + ), + ) + + node.meta["custom"] = node.meta.get("custom", arg_meta.get("custom", {})) + + +@contextlib.contextmanager +def _set_node_metadata_hook(gm: torch.fx.GraphModule, f): + """ + Takes a callable which will be called after we create a new node. The + callable takes the newly created node as input and returns None. + """ + if not callable(f): + raise AssertionError("node_metadata_hook must be a callable.") + + # Add the hook to all submodules + for m in gm.modules(): + if isinstance(m, GraphModule): + m._register_create_node_hook(f) + try: + yield + finally: + # Restore hook for all submodules + for m in gm.modules(): + if isinstance(m, GraphModule): + m._unregister_create_node_hook(f) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/add_runtime_assertions_for_constraints_pass.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/add_runtime_assertions_for_constraints_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..2a49de497f81c0106708a3246ec3846a49002fdf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/add_runtime_assertions_for_constraints_pass.py @@ -0,0 +1,253 @@ +# mypy: allow-untyped-defs +import math +import operator +import traceback +from functools import partial +from typing import NamedTuple, TYPE_CHECKING + +import sympy + +import torch +import torch.fx +from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols +from torch.fx.passes.infra.pass_base import PassBase, PassResult +from torch.utils._sympy.numbers import int_oo +from torch.utils._sympy.value_ranges import ValueRanges + + +if TYPE_CHECKING: + from collections.abc import Callable + + +__all__ = ["InputDim"] + + +class InputDim(NamedTuple): + input_name: str + dim: int + + +def _convert_to_int(val): + # Convert simple sympy Integers into concrete int + if val in (sympy.oo, int_oo): + return math.inf + if val in (-sympy.oo, -int_oo): + return -math.inf + if isinstance(val, sympy.Integer): + return int(val) + raise RuntimeError("Export constraints cannot be non-integer expressions") + + +def _convert_range_to_int(range: ValueRanges): + if not isinstance(range, ValueRanges): + raise AssertionError(f"expected ValueRanges, got {type(range)}") + min_val = _convert_to_int(range.lower) + max_val = _convert_to_int(range.upper) + return min_val, max_val + + +class _AddRuntimeAssertionsForInlineConstraintsPass(PassBase): + def __init__( + self, + range_constraints: dict[sympy.Symbol, ValueRanges], + ): + super().__init__() + self.range_constraints: dict[sympy.Symbol, ValueRanges] = range_constraints + self._asserts_generated_unbacked_symbols: set[sympy.Symbol] = set() + self.counter = 0 + + def _assert_range_constraint(self, node, lower, upper, assert_msg): + last_node = node + if lower > -math.inf: + last_node = self._insert_assert_async( + last_node, operator.ge, node, lower, assert_msg + ) + + if upper < math.inf: + last_node = self._insert_assert_async( + last_node, operator.le, node, upper, assert_msg + ) + + def _insert_assert_async(self, last_node, op, lower, upper, assert_msg): + """ + Inserts assert_async call_function nodes in the graph. This function is + called **during** the interpreter-based pass. + """ + self.counter += 1 + graph = last_node.graph + with graph.inserting_after(last_node): + cmp = graph.call_function(op, (lower, upper), {}) + with graph.inserting_after(cmp): + cmp_tensor = graph.call_function( + torch.ops.aten.scalar_tensor.default, (cmp,), {} + ) + with graph.inserting_after(cmp_tensor): + assert_async = graph.call_function( + torch.ops.aten._assert_async.msg, + (cmp_tensor, assert_msg), + {}, + ) + return assert_async + + def call(self, graph_module) -> PassResult: + self.existing_inline_assertions = _get_existing_inline_assertions( + graph_module, self.range_constraints + ) + + for module in graph_module.modules(): + if not isinstance(module, torch.fx.GraphModule): + continue + for node in module.graph.nodes: + if node.op != "call_function": + continue + if "val" not in node.meta: + continue + + val = node.meta["val"] + # In general, we may have to deal the case such as: ret[1].shape[0]. + # We need first find out what symbols require assertion, then we need to follow the path + # from ret to the symbol, construct the proxies along the way and construct the messages + # piece-wise at the same time. + # + # We use post-order traversal to collect all the proxies callbacks needed, construct + # the error message callbacks, and at the top-level traversal tree we execute all the callbacks. + # We need the callbacks because, in order to call the function to create a proxy for shape[0], we + # need the proxy for shape, which further requires the proxy for ret[1], etc. + + def add_assertions(val): + call_backs: list[Callable] = [] + messages: list[str] = [] + if isinstance(val, (torch.SymInt, torch.SymFloat, torch.SymBool)): + symbol = val.node.expr + if symbol in self.existing_inline_assertions: + return call_backs, messages + if isinstance(symbol, sympy.Symbol) and free_unbacked_symbols( + symbol + ): + if symbol in self._asserts_generated_unbacked_symbols: + return call_backs, messages + # We only care about unbacked symints for these inline + # constraints, which are prefixed with 'u' + constraint = self.range_constraints[symbol] + min_val, max_val = _convert_range_to_int(constraint) + assert_msg = f" is outside of inline constraint [{min_val}, {max_val}]." + call_backs.append( + partial( + self._assert_range_constraint, + lower=min_val, + upper=max_val, + ) + ) + messages.append(assert_msg) + self._asserts_generated_unbacked_symbols.add(symbol) + + elif isinstance(val, torch.Tensor): + for i, sym in enumerate(val.shape): + cbs, msgs = add_assertions(sym) + for cb, msg in zip(cbs, msgs): + + def sym_size_cb(node, assert_msg, dim): + with node.graph.inserting_after(node): + dim_node = module.graph.create_size_node( # type: ignore[union-attr] + node, dim + ) + cb(node=dim_node, assert_msg=assert_msg) + + call_backs.append(partial(sym_size_cb, dim=i)) + messages.append(f".shape[{i}]" + msg) + return call_backs, messages + + callbacks, messages = add_assertions(val) + for cb, msg in zip(callbacks, messages): + cb(node=node, assert_msg=f"{node}" + msg) + + module.recompile() + + # Sometimes this pass would return a wrong graph where we have mismatched + # node names in signature. Before we fix it, let's just skip it. + if ( + self.counter == 0 + and type(self) is _AddRuntimeAssertionsForInlineConstraintsPass + ): + return PassResult(graph_module, False) + + # Populate the stack trace with dummy vals to respect IR + for node in graph_module.graph.nodes: + if not node.meta.get("stack_trace", None) and node.op not in [ + "placeholder", + "output", + ]: + node.meta["stack_trace"] = "".join(traceback.format_stack(limit=1)) + return PassResult(graph_module, True) + + +def _get_existing_inline_assertions( + graph_module: torch.fx.GraphModule, + range_constraints: dict[sympy.Symbol, ValueRanges], +) -> dict[sympy.Symbol, ValueRanges]: + existing_inline_assertions: dict[sympy.Symbol, ValueRanges] = {} + + for module in graph_module.modules(): + if not isinstance(module, torch.fx.GraphModule): + continue + + # Find all the existing inline assertions. They will look something like: + # %_local_scalar_dense = call_function[target=torch.ops.aten._local_scalar_dense.default](args = (%arg1_1,), kwargs = {}) + # %ge = call_function[target=operator.ge](args = (%_local_scalar_dense, 0), kwargs = {}) + # %_assert_scalar = call_function[target=torch.ops.aten._assert_scalar.default](args = (%scalar_tensor, "..."), kwargs = {}) + for node in module.graph.nodes: + if node.target != torch.ops.aten._assert_scalar.default: + continue + + compare_arg = node.args[0] + if not ( + isinstance(compare_arg, torch.fx.Node) + and compare_arg.op == "call_function" + and compare_arg.target in (operator.le, operator.ge) + and len(compare_arg.args) == 2 + ): + continue + + compare_op = compare_arg.target + lhs, rhs = compare_arg.args + + def maybe_get_symint(x): + if ( + isinstance(x, torch.fx.Node) + and "val" in x.meta + and isinstance(x.meta["val"], torch.SymInt) + ): + return x.meta["val"].node.expr + return x + + lhs = maybe_get_symint(lhs) + rhs = maybe_get_symint(rhs) + + if compare_op is operator.ge: + lhs, rhs = rhs, lhs + + if isinstance(lhs, sympy.Symbol) and isinstance(rhs, int): + symint = lhs + scalar = rhs + elif isinstance(rhs, sympy.Symbol) and isinstance(lhs, int): + symint = rhs + scalar = lhs + else: + continue + + if symint not in range_constraints: + raise RuntimeError( + f"Unable to find symint {symint} in {range_constraints}" + ) + + previous_range = existing_inline_assertions.get( + symint, ValueRanges(-math.inf, math.inf) + ) + + if symint is lhs: + bounds = ValueRanges(-math.inf, scalar) + else: + bounds = ValueRanges(scalar, math.inf) + existing_inline_assertions[symint] = previous_range & bounds + + return existing_inline_assertions diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/collect_tracepoints_pass.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/collect_tracepoints_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..ed43e3319ce79f80a9754231ad16d0751023851a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/collect_tracepoints_pass.py @@ -0,0 +1,158 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import operator +from typing import TYPE_CHECKING + +import torch +from torch.export.exported_program import ConstantArgument, TensorArgument +from torch.fx.passes.infra.pass_base import PassBase, PassResult + + +if TYPE_CHECKING: + from torch.export.exported_program import ModuleCallSignature + from torch.export.graph_signature import ExportGraphSignature + + +__all__ = ["CollectTracepointsPass"] + + +class CollectTracepointsPass(PassBase): + """ + Performs constant folding and constant propagation. + """ + + def __init__( + self, specs: dict[str, ModuleCallSignature], sig: ExportGraphSignature + ) -> None: + super().__init__() + self.specs = specs + self.sig = sig + + def call(self, gm: torch.fx.GraphModule) -> PassResult | None: + def get_arg_spec(arg) -> TensorArgument | ConstantArgument: + if isinstance(arg, torch.fx.Node): + if isinstance(arg.meta.get("val"), torch.Tensor): + return TensorArgument(name=arg.name) + else: + raise AssertionError( + "Symint input is not implemented yet for submodule call signature." + ) + else: + return ConstantArgument(name="", value=arg) + + for module in gm.modules(): + if not isinstance(module, torch.fx.GraphModule): + continue + nn_module_stack = None + for node in module.graph.nodes: + if node.op != "call_function": + continue + if node.target is torch.ops.higher_order._export_tracepoint: + kind = node.kwargs["kind"] + if kind == "module_call_outputs": + nn_module_stack = node.meta["nn_module_stack"] + elif kind == "module_call_inputs": + nn_module_stack = None + else: + raise AssertionError(f"Unknown tracepoint kind: {kind}") + elif node.meta["nn_module_stack"] == nn_module_stack: + node.meta["nn_module_stack"].popitem() + else: + nn_module_stack = None + nn_module_stack = None + for node in reversed(module.graph.nodes): + if node.op != "call_function": + continue + if node.target is torch.ops.higher_order._export_tracepoint: + kind = node.kwargs["kind"] + if kind == "module_call_inputs": + nn_module_stack = node.meta["nn_module_stack"] + elif kind == "module_call_outputs": + nn_module_stack = None + else: + raise AssertionError(f"Unknown tracepoint kind: {kind}") + elif node.meta["nn_module_stack"] == nn_module_stack: + node.meta["nn_module_stack"].popitem() + else: + nn_module_stack = None + + def copy_sig(sig) -> ModuleCallSignature: + from torch.export.exported_program import ModuleCallSignature + + return ModuleCallSignature( + inputs=[], + outputs=[], + in_spec=sig.in_spec, + out_spec=sig.out_spec, + forward_arg_names=None, + ) + + for module in gm.modules(): + if not isinstance(module, torch.fx.GraphModule): + continue + for node in module.graph.nodes: + if node.op != "call_function": + continue + if node.target is torch.ops.higher_order._export_tracepoint: + # There's some subtlety worth noting. Here fqn corresponds to + # the call name, whereas path corresponds to the module name. + # They are not necessarily the same! When a submodule is shared + # through different aliases, there are as many _export_tracepoint + # markers as there are aliases, since the shared submodule is + # wrapped once for each alias. + path = node.kwargs["path"] + fqn, _ = next(reversed(node.meta["nn_module_stack"].values())) + + module_key = next(reversed(node.meta["nn_module_stack"])) + if "@" in module_key: + suffix = module_key.split("@")[-1] + path = f"{path}@{suffix}" + + call_fqn = f"{fqn}@{suffix}" + if call_fqn not in self.specs: + self.specs[call_fqn] = copy_sig(self.specs[fqn]) + fqn = call_fqn + + kind = node.kwargs["kind"] + for i, arg in enumerate(node.args): + # We only update the signature of the alias used to call + # the submodule. Otherwise the signatures of all aliases + # would get conflated; the inputs/outputs of every call + # would be recorded in every other call as well. + if fqn == path: + if kind == "module_call_inputs": + self.specs[path].inputs.append(get_arg_spec(arg)) + elif kind == "module_call_outputs": + self.specs[path].outputs.append(get_arg_spec(arg)) + else: + raise AssertionError(f"Unknown tracepoint kind: {kind}") + if isinstance(arg, torch.fx.Node): + for user in node.users: + if user.op != "call_function": + raise AssertionError( + f"expected call_function, got {user.op}" + ) + if user.target is not operator.getitem: + raise AssertionError( + f"expected getitem target, got {user.target}" + ) + if not isinstance(user.args[1], int): + raise AssertionError( + f"expected int arg, got {type(user.args[1])}" + ) + if user.args[1] == i: + user.replace_all_uses_with(arg) + self.sig.replace_all_uses(user.name, arg.name) + break + users = list(node.users) + for user in users: + if len(user.users) != 0: + raise AssertionError( + f"expected no users, got {len(user.users)}" + ) + gm.graph.erase_node(user) + gm.graph.erase_node(node) + return PassResult(gm, True) + + return None diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/constant_folding.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/constant_folding.py new file mode 100644 index 0000000000000000000000000000000000000000..3e6fc281b85b9e967416fb2c2cff489ce02cc3bd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/constant_folding.py @@ -0,0 +1,304 @@ +# mypy: allow-untyped-defs +import collections +from collections import defaultdict +from collections.abc import Callable +from typing import Any + +import torch +import torch.utils._pytree as pytree + + +aten = torch.ops.aten + +# We would like to split modules into two subgraphs for runtime weight updates to work correctly. +# The use case and more information could be found at: +# https://docs.google.com/document/d/1inZC-8KarJ6gKB7G9egmYLx1V_dKX_apxon0w4zPC0Q/edit?usp=sharing +META_TAG = "MODULE_TYPE" +MODULE_TAG = "_MAIN_MODULE" +CONST_MODULE_TAG = "_CONST_MODULE" + + +def replace_node_with_constant(gm, node, constant, name=None): + g = gm.graph + + if name: + qualname = name + else: + if not hasattr(gm, "_frozen_param_count"): + gm._frozen_param_count = 0 + i = gm._frozen_param_count + + while True: + qualname = f"_frozen_param{i}" + if not hasattr(gm, qualname): + break + i += 1 + + gm._frozen_param_count = i + 1 + + with g.inserting_before(node): + new_input_node = g.create_node("get_attr", qualname, (), {}) + node.replace_all_uses_with(new_input_node) + new_input_node.meta.update(node.meta) + g.erase_node(node) + + # needed to suppress `does not reference an nn.Module, nn.Parameter, or buffer` warning + gm.register_buffer(qualname, constant) + setattr(gm, qualname, constant) + + +class ConstantFolder(torch.fx.Interpreter): + def __init__( + self, + gm: torch.fx.GraphModule, + skip_constructors: bool = False, + ): + super().__init__(gm) + self.node_replacements: dict[torch.fx.Node, Any] = {} + self.replaced_uses: dict[torch.fx.Node, int] = collections.Counter() + self.unknown_value = object() + self.skip_constructors: bool = skip_constructors + + # overwrite this to deallocate env values if their only remaining use + # is the output + self.user_to_last_uses = self.node_to_last_non_output_use() + + def is_impure(self, node: torch.fx.Node) -> bool: + if ( + node.target is torch.ops.prims.convert_element_type.default + and node.args[0].op == "get_attr" # type: ignore[union-attr] + and node.args[0].meta["val"].dtype == torch.int8 # type: ignore[union-attr] + and node.args[1] == torch.bfloat16 + ): + # For int8_weight -> dq -> bf16_weight + return True + if node.target in [ + torch.ops.quantized_decomposed.dequantize_per_channel.default, + torch.ops.quantized_decomposed.dequantize_per_tensor.default, + torch.ops.quantized_decomposed.dequantize_per_tensor.tensor, + torch.ops.pt2e_quant.dequantize_affine, + ]: + # For the pattern fp32_weight -> q -> dq + # We only folding fp32_weight -> q + # int8_weight and leave dq in graph to be fused + return True + return False + + def node_to_last_non_output_use(self): + last_non_output_use = collections.defaultdict(list) + seen_uses = set() + output_node = next(iter(reversed(self.module.graph.nodes))) # type: ignore[arg-type, union-attr] + + for node in reversed(self.module.graph.nodes): # type: ignore[arg-type, union-attr] + if node.target == "output": + continue + + def add_use(inp): + if inp in seen_uses: + return + + seen_uses.add(inp) + last_non_output_use[node].append(inp) + + # In-place is fine since we don't mutate + pytree.tree_map_only_(torch.fx.Node, add_use, (node.args, node.kwargs)) + + # if this node is only used in output, we want to gc it right away + if len(node.users) == 1 and output_node in node.users: + last_non_output_use[node].append(node) + + return last_non_output_use + + def run_node(self, node): + if node.target == "output": + # because we remove nodes from env on last non output use, + # re-define them now or we'll get error in interpreter + def set_env(arg): + self.env[arg] = self.unknown_value + + # In-place is fine since we don't mutate + pytree.tree_map_only_(torch.fx.Node, set_env, node.args) + return super().run_node(node) + + args, kwargs = self.fetch_args_kwargs_from_env(node) + flattened_inputs = pytree.arg_tree_leaves(*args, **kwargs) + + # We need to do this weird thing because in cases where flattened_inputs + # contains a ScriptObject, equality checking results in a type error if + # the types are different. + if any( + type(self.unknown_value) is type(input_) and self.unknown_value == input_ + for input_ in flattened_inputs + ): + return self.unknown_value + + # TODO - fix errors with this + if ( + node.op == "call_function" + and node.target is aten._efficientzerotensor.default + ): + return self.unknown_value + + # TODO - constant folding triton kernel returns the inputs -- fix this + if ( + node.op == "call_function" + and node.name == "triton_kernel_wrapper_functional_proxy" + ): + return self.unknown_value + + # skip constructors, since inductor generates optimal code for them already + # and turning into tensor would result in an additional global memory read + # TODO - more complicated strategy + if ( + self.skip_constructors + and node.op != "get_attr" + and not any(isinstance(e, torch.Tensor) for e in flattened_inputs) + ): + return self.unknown_value + + # All mutations should either be removed or on inputs which we did not make constant + if ( + isinstance(node.target, torch._ops.OpOverload) + and torch.Tag.nondeterministic_seeded in node.target.tags + ): + return self.unknown_value + + out = super().run_node(node) + + if node.op != "get_attr" and isinstance(out, torch.Tensor): + if out.device.type == "meta": + return out + + if not self.insertable_tensor_check(out): + return out + + if self.is_impure(node): + return self.unknown_value + + self.add_node_replacement(node, out) + + flattened_node_inps = pytree.arg_tree_leaves(*node.args, **node.kwargs) + + for n in flattened_node_inps: + if not isinstance(n, torch.fx.Node): + continue + + self.replaced_uses[n] += 1 + + for to_delete in self.user_to_last_uses.get(node, []): + if self.replaced_uses[to_delete] == len(to_delete.users): + self.node_replacements.pop(to_delete, None) + + return out + + def insertable_tensor_check(self, tensor: torch.Tensor) -> bool: + return True + + def add_node_replacement(self, node: torch.fx.Node, tensor: torch.Tensor) -> None: + self.node_replacements[node] = tensor + + def run(self): # type: ignore[override] + env = {} + for n in self.module.graph.find_nodes(op="placeholder"): # type: ignore[operator, union-attr] + env[n] = self.unknown_value + return super().run(initial_env=env) + + +def constant_fold( + gm: torch.fx.GraphModule, + constraint_fn: Callable[[torch.fx.Node], bool] | None = None, +): + with torch.utils._python_dispatch._disable_current_modes(): + cf = ConstantFolder(gm, skip_constructors=True) + cf.run() + + for node, constant in cf.node_replacements.items(): + if constraint_fn is not None and not constraint_fn(node): + continue + replace_node_with_constant(gm, node, constant) + + erased_params = [] + # Get all attr users by looking up the graph instead from node.users, because in this case + # _tensor_constant0 and _tensor_constant0_1 are actually referring to the same tensor. + + # opcode name target args kwargs + # ------------- ------------------- ---------------- --------------------------- -------- + # placeholder arg0_1 arg0 () {} + # get_attr _tensor_constant0 state () {} + # call_function add aten.add.Tensor (arg0_1, _tensor_constant0) {} + # get_attr _tensor_constant0_1 state () {} + # call_function add_ aten.add_.Tensor (_tensor_constant0_1, 1) {} + # output output output ([add],) {} + + get_attr_node_users = defaultdict(list) + for node in gm.graph.nodes: + if node.op == "get_attr": + get_attr_node_users[node.target].extend(node.users.keys()) + for node in gm.graph.find_nodes(op="get_attr"): + if node.op == "get_attr" and len(get_attr_node_users[node.target]) == 0: + if hasattr(gm, node.target): + delattr(gm, node.target) + erased_params.append(node) + for node in erased_params: + gm.graph.erase_node(node) + + gm.graph.eliminate_dead_code() + gm.graph.lint() + gm.recompile() + + +def constant_graph_tag(gm: torch.fx.GraphModule) -> None: + with torch.utils._python_dispatch._disable_current_modes(): + cf = ConstantFolder(gm, skip_constructors=True) + cf.run() + + for node in gm.graph.nodes: + if ( + node.op == "get_attr" + or node in cf.node_replacements + or node in cf.replaced_uses + ): + node.meta[META_TAG] = CONST_MODULE_TAG + else: + node.meta[META_TAG] = MODULE_TAG + + +def run_and_get_constant_graph(gm: torch.fx.GraphModule) -> torch.fx.GraphModule: + """ + Construct a GraphModule which corresponds to the part which could be + constant folded in provided gm. + """ + + constant_graph_tag(gm) + # We rewrite the tags, if it's a constant being directly consumed, without + # any folding opportunity, we keep it in main gm. + for node in gm.graph.find_nodes(op="get_attr"): + used_to_fold = False + for u in node.users: + if u.meta[META_TAG] == CONST_MODULE_TAG: + used_to_fold = True + break + if not used_to_fold: + node.meta[META_TAG] = MODULE_TAG + + new_graph = torch.fx.Graph() + + node_remapping: dict[torch.fx.Node, torch.fx.Node] = {} + output_nodes = [] + for node in gm.graph.nodes: + if node.meta[META_TAG] == MODULE_TAG: + continue + + new_node = new_graph.node_copy(node, lambda x: node_remapping[x]) + node_remapping[node] = new_node + + for user in node.users: + if user.meta[META_TAG] == MODULE_TAG: + output_nodes.append(new_node) + break + + new_graph.output(tuple(output_nodes)) + new_graph.lint() + new_gm = torch.fx.GraphModule(gm, new_graph) + + return new_gm diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/functionalize_side_effectful_ops_pass.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/functionalize_side_effectful_ops_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..c612aaf34888793b0953779c67e656d98eb6316f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/functionalize_side_effectful_ops_pass.py @@ -0,0 +1,100 @@ +import copy + +import torch +from torch._export.pass_base import ( + _ExportPassBaseDeprecatedDoNotUse, + Argument, + PassResult, +) +from torch._export.pass_infra.node_metadata import NodeMetadata +from torch._export.pass_infra.proxy_value import ProxyValue +from torch._ops import OpOverload + + +aten = torch.ops.aten + +_NON_FUNCTIONAL_TO_FUNCTIONAL_SIDE_EFFECTFUL_FUNCS: dict[OpOverload, OpOverload] = { + aten.sym_constrain_range.default: aten._functional_sym_constrain_range.default, + aten._assert_async.msg: aten._functional_assert_async.msg, +} + + +class _FunctionalizeSideEffectfulOpsPass(_ExportPassBaseDeprecatedDoNotUse): + """ + Functionalize ops with side effect in graph module by replacing the op with + functional version of it. A new dependency token (`dep_token`) will be + created and propagated through functional ops to output. + For example: + ``` + def f(x): + sym_constrain_range(x.shape[0], min=1, max=3) + return x.add(3) + ``` + Will be transformed to: + ``` + def f(x): + dep_token0 = _make_dep_token() + dep_token1 = _functional_sym_constrain_range( + x.shape[0], min=1, max=3, dep_token=dep_token0 + ) + + return x.add(3), dep_token1 + ``` + """ + + def __init__(self) -> None: + super().__init__() + self._dep_token: ProxyValue | None = None + self._next_dep_token_index: int | None = None + + def call(self, graph_module: torch.fx.GraphModule) -> PassResult: + # Early return if no non-functional assertions. + if not any( + n.target in _NON_FUNCTIONAL_TO_FUNCTIONAL_SIDE_EFFECTFUL_FUNCS + for n in graph_module.graph.nodes + ): + return PassResult(graph_module=graph_module, modified=False) + + gm = copy.deepcopy(graph_module) + self._dep_token = None + self._next_dep_token_index = None + return super().call(gm) + + def call_operator( + self, + op: OpOverload, + args: tuple[Argument, ...], + kwargs: dict[str, Argument], + meta: NodeMetadata, + ) -> ProxyValue: + if op not in _NON_FUNCTIONAL_TO_FUNCTIONAL_SIDE_EFFECTFUL_FUNCS: + return super().call_operator(op, args, kwargs, meta) + + if self._dep_token is None: + self._dep_token = super().call_operator( + aten._make_dep_token, + args=(), + kwargs={}, + meta=self._create_dummy_node_metadata(), + ) + self._dep_token.node.name = "dep_token0" + self._next_dep_token_index = 1 + + self._dep_token = super().call_operator( + _NON_FUNCTIONAL_TO_FUNCTIONAL_SIDE_EFFECTFUL_FUNCS[op], + args=args, + kwargs={**kwargs, "dep_token": self._dep_token}, + meta=meta, + ) + if self._next_dep_token_index is None: + raise AssertionError("_next_dep_token_index must not be None") + self._dep_token.node.name = f"dep_token{self._next_dep_token_index}" + self._next_dep_token_index += 1 + + return self._dep_token + + def output(self, results: list[Argument], meta: NodeMetadata) -> ProxyValue: + if self._dep_token is None: + raise AssertionError("_dep_token must not be None") + + return super().output(results=(*results, self._dep_token), meta=meta) # type: ignore[arg-type] diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/insert_custom_op_guards.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/insert_custom_op_guards.py new file mode 100644 index 0000000000000000000000000000000000000000..8bbca86cf58908ffe31f976f3fa3fce152ade694 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/insert_custom_op_guards.py @@ -0,0 +1,84 @@ +import functools +from collections import defaultdict + +import torch +from torch._export.passes._node_metadata_hook import ( + _node_metadata_hook, + _set_node_metadata_hook, +) +from torch._library.fake_profile import OpProfile, TensorMetadata + + +def insert_custom_op_guards(gm: torch.fx.GraphModule, ops_to_guard: set[str]) -> None: + """ + This is used by draft_export to insert guards in front of calls to custom + operators which have a generated fake kernel. + """ + for node in gm.graph.nodes: + if node.op == "call_function" and str(node.target) in ops_to_guard: + with ( + _set_node_metadata_hook( + gm, + functools.partial( + _node_metadata_hook, + metadata={"stack_trace": node.meta.get("stack_trace")}, + ), + ), + gm.graph.inserting_before(node), + ): + for arg in (*node.args, *node.kwargs.values()): + if isinstance(arg, torch.fx.Node) and isinstance( + arg.meta.get("val"), torch.Tensor + ): + val = arg.meta["val"] + gm.graph.call_function( + torch.ops.aten._assert_tensor_metadata.default, + args=(arg,), + kwargs={ + "dtype": val.dtype, + "device": val.device, + "layout": val.layout, + }, + ) + + gm.recompile() + + +def get_op_profiles( + gm: torch.fx.GraphModule, ops_to_guard: set[str] +) -> dict[str, set[OpProfile]]: + """ + This is used by draft_export to get a list of custom operator profiles so + that we can generate fake kernels. + """ + + def _get_op_profile(node: torch.fx.Node) -> OpProfile: + args_profile = tuple( + TensorMetadata.maybe_from_tensor(arg.meta.get("val")) + if isinstance(arg, torch.fx.Node) + else None + for arg in (*node.args, *node.kwargs.values()) + ) + + out_profile = None + meta = node.meta.get("val") + if meta is None: + raise AssertionError("node.meta['val'] must not be None") + if isinstance(meta, torch.Tensor): + out_profile = TensorMetadata.maybe_from_tensor(meta) + elif isinstance(meta, (list, tuple)): + out_profile = tuple(TensorMetadata.maybe_from_tensor(m) for m in meta) # type: ignore[assignment] + if out_profile is None: + raise AssertionError( + f"out_profile must not be None for meta type {type(meta)}" + ) + + return OpProfile(args_profile, out_profile) # type: ignore[arg-type] + + op_profiles: dict[str, set[OpProfile]] = defaultdict(set) + + for node in gm.graph.nodes: + if node.op == "call_function" and str(node.target) in ops_to_guard: + op_profiles[str(node.target)].add(_get_op_profile(node)) + + return op_profiles diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/lift_constants_pass.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/lift_constants_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..e57a5569233e27d8efa117a41a1b9e96f4daf793 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/lift_constants_pass.py @@ -0,0 +1,449 @@ +# mypy: allow-untyped-defs +import collections +import logging +from typing import Any + +import torch +from torch._export.verifier import SpecViolationError +from torch._guards import detect_fake_mode +from torch._library.fake_class_registry import FakeScriptObject, maybe_to_fake_obj +from torch._library.opaque_object import ( + get_opaque_type_name, + is_custom_class, + is_opaque_symbolic_type, +) +from torch._subclasses.fake_tensor import unset_fake_temporarily +from torch.export.exported_program import ( + ArgumentSpec, + CustomObjArgument, + ExportGraphSignature, + InputKind, + InputSpec, + TensorArgument, +) +from torch.fx._symbolic_trace import _ConstantAttributeType +from torch.fx.graph_module import _get_attr + + +log = logging.getLogger(__name__) + + +class ConstantAttrMap(collections.abc.MutableMapping): + """A mapping class that understands how to use module constants (tensors, + ScriptObjects, FakeScriptObjects, opaque objects) as keys. We store tensors, + FakeScriptObjects, and opaque objects normally, but ScriptObjects are stored + by hash, because different torch.ScriptObjects can point to the same + underlying value (but we guarantee that they will `hash()` to the same value + if that's the case). + """ + + def __init__(self) -> None: + # Underlying dict that we use to implement this mapping. + self._constant_attrs: dict[ + int | torch.Tensor | FakeScriptObject | torch.utils._pytree.TreeSpec, + list[Any], + ] = {} + # Map from the hash(ScriptObject) to the ScriptObject itself. Used for + # APIs like `__iter__` that should look like they're returning the + # original ScriptObjects. + self._script_object_map: dict[int, torch.ScriptObject] = {} + + def __getitem__(self, key: _ConstantAttributeType) -> Any: + real_key = hash(key) if isinstance(key, torch.ScriptObject) else key + if not isinstance( + real_key, (int, torch.Tensor, FakeScriptObject) + ) and not is_custom_class(type(real_key)): + raise AssertionError( + f"expected int, Tensor, FakeScriptObject, or opaque type key, got {type(real_key)}" + ) + return self._constant_attrs[real_key] + + def __setitem__(self, key: _ConstantAttributeType, value): + # we shouldn't actually call this, should go to add() instead to handle aliasing + raise NotImplementedError( + """Directly setting values for ConstantAttrMap is not supported, please use add(key, value) instead. +The same key can be mapped to multiple values, for handling constant aliasing.""" + ) + + def add(self, key: _ConstantAttributeType, value: Any) -> None: + if isinstance(key, torch.ScriptObject): + if hash(key) not in self._constant_attrs: + self._constant_attrs[hash(key)] = [] + self._constant_attrs[hash(key)].append(value) + self._script_object_map[hash(key)] = key + elif isinstance(key, (torch.Tensor, FakeScriptObject)) or is_custom_class( + type(key) + ): + if key not in self._constant_attrs: + self._constant_attrs[key] = [] + self._constant_attrs[key].append(value) + else: + raise TypeError( + f"Expected key to be a tensor or ScriptObject, got {type(key)}" + ) + + def __delitem__(self, key: _ConstantAttributeType): + real_key = hash(key) if isinstance(key, torch.ScriptObject) else key + + del self._constant_attrs[real_key] + + def __iter__(self): + for key in self._constant_attrs: + if isinstance(key, int): + yield self._script_object_map[key] + else: + yield key + + def __len__(self): + return len(self._constant_attrs) + + def __contains__(self, key: object) -> bool: + real_key = hash(key) if isinstance(key, torch.ScriptObject) else key + return real_key in self._constant_attrs + + +def get_constant_fqn(node: torch.fx.Node, constant_name: str) -> str: + # The FQN of the constant tensor in the state dict should + # correspond to the module where the constant tensor was + # originally used. + if len(node.meta["nn_module_stack"]) == 0: + return constant_name + parent_fqn = list(node.meta["nn_module_stack"].values())[-1][0] + if len(parent_fqn) > 0: + return f"{parent_fqn}.{constant_name}" + else: + return constant_name + + +def _get_first_fqn( + const_attrs: ConstantAttrMap, + key: _ConstantAttributeType, +) -> Any: + fqns = const_attrs.get(key) + return fqns[0] if fqns else None + + +def _unused_constant(node: torch.fx.Node) -> list[torch.fx.Node] | None: + """ + If there is a tensor constant created while tracing, here is how the graph + looks like: + + %_tensor_constant0 : [num_users=1] = get_attr[target=_tensor_constant0] + %lift_fresh_copy : [num_users=1] = call_function[target=torch.ops.aten.lift_fresh_copy.default](args = (%_tensor_constant0,)) + %detach_ : [num_users=?] = call_function[target=torch.ops.aten.detach_.default](args = (%lift_fresh_copy,)) + + To check to see if the tensor constant is being used, we want to traverse to + the detach node to see if it's actually being used. + + This function returns None if this constant is being used, otherwise it returns the + lift_fresh and detach node to be removed later. + """ + if len(node.users) > 1: + return None + + lift_fresh_node = next(iter(node.users.keys())) + if not ( + lift_fresh_node.op == "call_function" + and lift_fresh_node.target + in ( + torch.ops.aten.lift_fresh.default, + torch.ops.aten.lift_fresh_copy.default, + ) + ): + return None + + if len(lift_fresh_node.users) > 1: + return None + + # Case 1: lift node is not used anywhere + if len(lift_fresh_node.users) == 0: + return [lift_fresh_node, node] + + detach_node = next(iter(lift_fresh_node.users.keys())) + if not ( + detach_node.op == "call_function" + and detach_node.target + in ( + torch.ops.aten.detach_.default, + torch.ops.aten.detach.default, + ) + ): + return None + + if len(detach_node.users) > 0: + return None + else: + # Case 2: Lift node's child is not used anywhere + return [detach_node, lift_fresh_node, node] + + +def lift_constants_pass( + gm: torch.fx.GraphModule, + graph_signature: ExportGraphSignature, + constant_attrs: ConstantAttrMap, +) -> dict[str, _ConstantAttributeType]: + """ + Takes a graph module, graph signature, and modifies them inplace to lift any + constants (tensors or custom classes) as inputs to the graph. Returns a + dictionary of names to constants. + + Arguments: + gm (torch.fx.GraphModule): The graph module containing the graph and constants to lift. + graph_signature (ExportGraphSignature): This graph signature will be + mutated to add additional CONSTANT_TENSOR and CUSTOM_OBJ inputs. + constant_attrs (ConstantAttr): A mapping from a constant value to its + fully-qualified path in `gm`. This is used to maintain consistent + location of constants between the original module and the exported + version. + + Returns: + A dictionary of fqn => constant value. + """ + all_constants: dict[str, _ConstantAttributeType] = {} + + input_specs = graph_signature.input_specs + num_custom_obj = sum( + input_spec.kind == InputKind.CUSTOM_OBJ for input_spec in input_specs + ) + num_tensor_constants = sum( + input_spec.kind == InputKind.CONSTANT_TENSOR for input_spec in input_specs + ) + + fake_mode = detect_fake_mode( + tuple(node.meta["val"] for node in gm.graph.nodes if node.op == "placeholder") + ) + + first_user_input_loc, first_user_input = 0, next(iter(gm.graph.nodes)) + used_target_names = set() + + input_nodes = [node for node in gm.graph.nodes if node.op == "placeholder"] + if len(input_nodes) != len(input_specs): + raise AssertionError( + f"input nodes count {len(input_nodes)} != input specs count {len(input_specs)}" + ) + for i, (node, input_spec) in enumerate(zip(input_nodes, input_specs)): + used_target_names.add(input_spec.target) + if input_spec.kind == InputKind.USER_INPUT: + first_user_input = node + first_user_input_loc = i + break + + lifted_objs = ConstantAttrMap() + renamed_targets = {} + for node in list(gm.graph.nodes): + if node.op == "get_attr": + if nodes_to_remove := _unused_constant(node): + # Remove the node if it's not being used + for node_rm in nodes_to_remove: + gm.graph.erase_node(node_rm) + continue + + constant_val = _get_attr(gm, node.target) + # These are not hashable and not gonna be lifted + # so we can skip them earlier + if isinstance(constant_val, torch.fx.GraphModule): + continue + if "LoweredBackendModule" in type(constant_val).__name__: + continue + if "AOTInductorRunnerWrapper" in type(constant_val).__name__: + continue + if isinstance(constant_val, torch.utils._pytree.TreeSpec): + continue + + if constant_val in lifted_objs: + # We already lifted this constant elsewhere. Just rewrite uses + # of this get_attr to point to the already-existing placeholder + # node. + const_placeholder_node = _get_first_fqn(lifted_objs, constant_val) + node.replace_all_uses_with(const_placeholder_node) + gm.graph.erase_node(node) + renamed_targets[node.name] = const_placeholder_node.name + continue + + # For ScriptObject, Tensor and FakeScriptObject constants: + # First check if the constant was an attribute on some module by + # consulting `constant_attrs` map. If it is, use the fqn that keeps + # its location consistent with the eager module. + # + # If it's not in the `constant_attrs` map, that means it's an inline + # constant (e.g. x + torch.tensor(0)), and thus did not have a + # specific location in the eager module. In that case, just generate + # some name and attach it to the module in which it was used. + if isinstance( + constant_val, (torch.ScriptObject, FakeScriptObject) + ) or is_opaque_symbolic_type(type(constant_val)): + constant_kind = InputKind.CUSTOM_OBJ + constant_fqn = _get_first_fqn(constant_attrs, constant_val) + if constant_fqn is not None: + constant_name = constant_fqn.replace(".", "_") + else: + constant_name = f"lifted_custom_{num_custom_obj}" + constant_fqn = get_constant_fqn(node, constant_name) + while constant_fqn in used_target_names: + num_custom_obj += 1 + constant_name = f"lifted_custom_{num_custom_obj}" + constant_fqn = get_constant_fqn(node, constant_name) + num_custom_obj += 1 + elif isinstance(constant_val, torch.Tensor): + # Remove the parameterness of constant_val + if isinstance(constant_val, torch.nn.Parameter): + log.debug( + "%s created when tracing %s is a parameter. But " + "it's not registered with register_parameter(). export will treat it as a constant tensor", + str(node.target), + str(node.meta.get("stack_trace", "")), + ) + # We get the real data out of the parameter by disabling the surrounding fake mode. + with unset_fake_temporarily(): + constant_val = constant_val.data + constant_kind = InputKind.CONSTANT_TENSOR + constant_fqn = _get_first_fqn(constant_attrs, constant_val) + if constant_fqn is not None: + constant_name = constant_fqn.replace(".", "_") + else: + constant_name = f"lifted_tensor_{num_tensor_constants}" + constant_fqn = get_constant_fqn(node, constant_name) + while constant_fqn in used_target_names: + num_tensor_constants += 1 + constant_name = f"lifted_tensor_{num_tensor_constants}" + constant_fqn = get_constant_fqn(node, constant_name) + num_tensor_constants += 1 + else: + raise SpecViolationError( + f"getattr node {node} referencing unsupported type {type(constant_val)}" + ) + + with gm.graph.inserting_before(first_user_input): + # Insert the constant node before the first user input + const_placeholder_node = gm.graph.placeholder(constant_name) + # match target name with its node name in case there is name collision + # and suffix is added to node name in fx + const_placeholder_node.target = const_placeholder_node.name + + for k, v in node.meta.items(): + const_placeholder_node.meta[k] = v + + # Once the FQN has been used, remove nn_module_stack, stack_trace + const_placeholder_node.meta.pop("nn_module_stack") + const_placeholder_node.meta.pop("stack_trace", None) + + input_spec_arg: ArgumentSpec + if isinstance(constant_val, torch.Tensor): + if fake_mode is not None: + const_placeholder_node.meta["val"] = fake_mode.from_tensor( + constant_val, static_shapes=True + ) + const_placeholder_node.meta["val"].constant = constant_val + else: + const_placeholder_node.meta["val"] = constant_val + input_spec_arg = TensorArgument(name=const_placeholder_node.name) + elif isinstance(constant_val, torch._C.ScriptObject): + class_fqn = constant_val._type().qualified_name() # type: ignore[attr-defined] + const_placeholder_node.meta["val"] = CustomObjArgument( + constant_fqn, class_fqn + ) + input_spec_arg = CustomObjArgument( + name=const_placeholder_node.name, class_fqn=class_fqn + ) + elif isinstance(constant_val, FakeScriptObject): + class_fqn = constant_val.script_class_name + const_placeholder_node.meta["val"] = CustomObjArgument( + constant_fqn, class_fqn, constant_val + ) + input_spec_arg = CustomObjArgument( + name=const_placeholder_node.name, + class_fqn=class_fqn, + fake_val=constant_val, + ) + elif is_custom_class(type(constant_val)): + class_fqn = get_opaque_type_name(type(constant_val)) + fake_val = ( + maybe_to_fake_obj(fake_mode, constant_val) + if fake_mode + else None + ) + const_placeholder_node.meta["val"] = CustomObjArgument( + constant_fqn, + class_fqn, + fake_val, # pyrefly: ignore[bad-argument-type] + ) + input_spec_arg = CustomObjArgument( + name=const_placeholder_node.name, + class_fqn=class_fqn, + fake_val=fake_val, # pyrefly: ignore[bad-argument-type] + ) + else: + raise SpecViolationError( + f"tried to lift unsupported type {type(constant_val)} from node {node.format_node()}" + ) + + lifted_objs.add(constant_val, const_placeholder_node) + node.replace_all_uses_with(const_placeholder_node) + gm.graph.erase_node(node) + + renamed_targets[node.name] = const_placeholder_node.name + + # Add the constant as a buffer to the graph signature + graph_signature.input_specs.insert( + first_user_input_loc, + InputSpec( + kind=constant_kind, + arg=input_spec_arg, + target=constant_fqn, + ), + ) + if constant_val in constant_attrs: + for fqn in constant_attrs[constant_val]: + all_constants[fqn] = constant_val + else: + all_constants[constant_fqn] = constant_val + first_user_input_loc += 1 + + for spec in graph_signature.output_specs: + if spec.arg.name in renamed_targets: + spec.arg.name = renamed_targets[spec.arg.name] + + return all_constants + + +def rewrite_script_object_meta( + gm: torch.fx.GraphModule, +) -> dict[str, _ConstantAttributeType]: + """When tracing, we produce a graph with FakeScriptObject in the + meta["val"]. + + For now, we rewrite meta["val"] to be a placeholder CustomObjArgument + """ + constants: dict[ + str, + _ConstantAttributeType, + ] = {} + for node in gm.graph.nodes: + if "val" not in node.meta: + continue + + old_meta = node.meta["val"] + + if isinstance(old_meta, torch.ScriptObject): + class_fqn = old_meta._type().qualified_name() # type: ignore[attr-defined] + new_meta = CustomObjArgument(node.name, class_fqn) + constants[node.name] = old_meta + node.meta["val"] = new_meta + + elif isinstance(old_meta, FakeScriptObject): + class_fqn = old_meta.script_class_name # type: ignore[attr-defined] + new_meta = CustomObjArgument(node.name, class_fqn, old_meta) + constants[node.name] = old_meta + node.meta["val"] = new_meta + + return constants + + +def _materialize_and_lift_constants( + gm: torch.fx.GraphModule, + export_graph_signature: ExportGraphSignature, + constant_attrs: ConstantAttrMap, +) -> dict[str, _ConstantAttributeType]: + constants = rewrite_script_object_meta(gm) + constants.update(lift_constants_pass(gm, export_graph_signature, constant_attrs)) + return constants diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/remove_runtime_assertions.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/remove_runtime_assertions.py new file mode 100644 index 0000000000000000000000000000000000000000..ceed7cd23aa0e953b99586052629668cc53c4bdd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/remove_runtime_assertions.py @@ -0,0 +1,36 @@ +import torch +from torch.fx.passes.infra.pass_base import PassBase, PassResult + + +class _RemoveRuntimeAssertionsPass(PassBase): + """ + Remove runtime assertions inserted by the + _AddRuntimeAssertionsForInlineConstraintsPass. + """ + + def call(self, graph_module: torch.fx.GraphModule) -> PassResult: + modified = False + for module in graph_module.modules(): + if not isinstance(module, torch.fx.GraphModule): + continue + for node in module.graph.nodes: + if node.target in [ + torch.ops.aten._assert_async.msg, + torch.ops.aten._assert_scalar.default, + torch.ops.aten.sym_constrain_range_for_size.default, + torch.ops.aten.sym_constrain_range.default, + torch.ops.aten._assert_tensor_metadata.default, + ]: + assert_async_node = node + if len(assert_async_node.users) > 0: + continue + module.graph.erase_node(assert_async_node) + # the upstream scalar_tensor <- {le, ge} <- sym_size + # linear chain of nodes of nodes is removed by the + # downstream dead code elimination + modified = True + + # We don't necessarily want to run DCE here because it could affect + # nodes that are in the module_call_graph attribute of the exported + # program. We will leave it to the pass caller to call DCE. + return PassResult(graph_module, modified) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_autocast_with_hop_pass.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_autocast_with_hop_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..a603565f502f83eff2bdaed145a850987a7eceda --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_autocast_with_hop_pass.py @@ -0,0 +1,212 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch +from torch._higher_order_ops.wrap import wrap_with_autocast + +from ..utils import node_inline_, nodes_filter, nodes_first, sequential_split +from .replace_with_hop_pass_util import ( + _replace_with_hop_helper, + _replace_with_hop_pass_helper, + _sequential_split_and_maybe_inline_subgraphs_helper, +) + + +if TYPE_CHECKING: + from torch.export.graph_signature import ExportGraphSignature + + +def _is_autocast_node(node: torch.fx.Node) -> torch.fx.Node | bool: + return ( + node + and node.op == "call_function" + and node.target + in [ + torch.amp.autocast_mode._enter_autocast, + torch.amp.autocast_mode._exit_autocast, + ] + ) + + +def _is_enter_autocast_node(node: torch.fx.Node) -> torch.fx.Node | bool: + return ( + node + and node.op == "call_function" + and node.target is torch.amp.autocast_mode._enter_autocast + ) + + +def _is_exit_autocast_node(node: torch.fx.Node) -> torch.fx.Node | bool: + return ( + node + and node.op == "call_function" + and node.target is torch.amp.autocast_mode._exit_autocast + ) + + +def _is_autocast_sub_mod(node: torch.fx.Node) -> bool: + """ + Check if the first non-placeholder node is `torch.amp.autocast_mode._enter_autocast`. + """ + if node.op == "call_module": + if not isinstance(node.target, str): + raise AssertionError(f"expected str target, got {type(node.target)}") + subgm = getattr(node.graph.owning_module, node.target) + first_non_ph = nodes_first( + subgm.graph.nodes, lambda node: node.op != "placeholder" + ) + if ( + first_non_ph + and first_non_ph.op == "call_function" + and first_non_ph.target is torch.amp.autocast_mode._enter_autocast + ): + # TODO: check if current auto-cast type is the same as the args of + # _enter_autocast. If so, return False, i.e. do not create a submodule. + return True + return False + + +def _check_valid_autocast_block( + enter_autocast_node: torch.fx.Node, exit_autocast_node: torch.fx.Node +) -> None: + if not _is_enter_autocast_node(enter_autocast_node): + raise AssertionError( + f"expected enter_autocast node, got {enter_autocast_node.target}" + ) + if not _is_exit_autocast_node(exit_autocast_node): + raise AssertionError( + f"expected exit_autocast node, got {exit_autocast_node.target}" + ) + if exit_autocast_node.args[0] != enter_autocast_node: + raise AssertionError( + "exit_autocast_node.args[0] must match enter_autocast_node" + ) + + +def _replace_with_hop(node: torch.fx.Node) -> None: + if node.op != "call_module": + raise AssertionError(f"expected call_module op, got {node.op}") + graph: torch.fx.Graph = node.graph + if graph.owning_module is None: + raise AssertionError("graph.owning_module must not be None") + gm: torch.fx.GraphModule = graph.owning_module + if not isinstance(node.target, str): + raise AssertionError(f"expected str target, got {type(node.target)}") + sub_gm = getattr(gm, node.target) + sub_graph = sub_gm.graph + autocast_nodes = nodes_filter(sub_graph.nodes, _is_autocast_node) + if len(autocast_nodes) > 0: + if len(autocast_nodes) <= 1: + raise AssertionError( + f"need at least an enter node and an exit node, got {len(autocast_nodes)}" + ) + enter_autocast_node = autocast_nodes[0] + exit_autocast_node = autocast_nodes[-1] + _check_valid_autocast_block(enter_autocast_node, exit_autocast_node) + + _replace_with_hop_helper(node, enter_autocast_node, wrap_with_autocast) + sub_graph.erase_node(exit_autocast_node) + sub_graph.erase_node(enter_autocast_node) + + +def _split_autocast(gm: torch.fx.GraphModule) -> torch.fx.GraphModule: + """ + split_autocast creates a new graph module that splits the input graph module into multiple submodules + based on the `_enter_autocast` and `_exit_autocast` nodes. It doesn't mutate the input graph module. + + Nodes between the **outer-most** `_enter_autocast` and `_exit_autocast(_enter_autocast)` are split + into a submodule. Nested autocast regions are not split. + `_enter_autocast` and `_exit_autocast(_enter_autocast)` nodes are in the submodule as well. + + Below is an example of splitting. A, B, C, D, E are blocks of non-autocast nodes in the original graph + module. Nodes marked with the same number are grouped into the same submodule. + A # 0 + enter_autocast # 1 + B # 1 + exit_autocast # 1 + C # 2 + enter_autocast # 3 + D # 3 + exit_autocast # 3 + E # 4 + """ + enter_autocast_node_stack: list[torch.fx.Node] = [] + first_node_after_outer_most_exit: bool = False + + def node_call_back(node: torch.fx.Node) -> bool: + nonlocal enter_autocast_node_stack, first_node_after_outer_most_exit + increment_id = False + if first_node_after_outer_most_exit or ( + len(enter_autocast_node_stack) == 0 and _is_enter_autocast_node(node) + ): + if len(enter_autocast_node_stack) != 0: + raise AssertionError( + f"expected empty stack, got {len(enter_autocast_node_stack)} items" + ) + first_node_after_outer_most_exit = False + increment_id = True + if _is_enter_autocast_node(node): + enter_autocast_node_stack.append(node) + elif _is_exit_autocast_node(node): + if len(enter_autocast_node_stack) == 0: + raise AssertionError("enter_autocast_node_stack must not be empty") + last_enter_autocast_node = enter_autocast_node_stack.pop() + if node.args[0] != last_enter_autocast_node: + raise AssertionError("exit node args[0] must match last enter node") + if len(enter_autocast_node_stack) == 0: + # next node should be in the next submodule since + # autocast block ends + first_node_after_outer_most_exit = True + return increment_id + + return sequential_split(gm, node_call_back) + + +def _sequential_split_and_maybe_inline_subgraphs( + gm: torch.fx.GraphModule, graph_signature: ExportGraphSignature | None +) -> tuple[torch.fx.GraphModule, ExportGraphSignature | None]: + """ + Helper function for replace_autocast_with_hop_pass(). + Split the graph module into multiple subgraphs based on the autocast nodes. + For each subgraph, decides whether to construct a HOO subgraph, or inline the calls + back into the parent graph module. + Nodes between `_enter_autocast` and `_exit_autocast(_enter_autocast)` are considered + as a subgraph. + """ + need_replacing = any(_is_autocast_node(node) for node in gm.graph.nodes) + if not need_replacing: + return gm, graph_signature + + # split_autocast returns a new graph module that could have different output + # args names. We need to fix the graph signature in `_sequential_split_and_maybe_inline_subgraphs_helper`. + new_gm = _split_autocast(gm) + + def _maybe_inline_or_replace_with_hop(node: torch.fx.Node) -> None: + if _is_autocast_sub_mod(node): + _replace_with_hop(node) + else: + if node.op != "call_module": + raise AssertionError(f"expected call_module op, got {node.op}") + if not isinstance(node.target, str): + raise AssertionError(f"expected str target, got {type(node.target)}") + node_inline_(node) + + return _sequential_split_and_maybe_inline_subgraphs_helper( + new_gm, graph_signature, _maybe_inline_or_replace_with_hop + ) + + +def replace_autocast_with_hop_pass( + gm: torch.fx.GraphModule, graph_signature: ExportGraphSignature | None +) -> tuple[torch.fx.GraphModule, ExportGraphSignature | None]: + """ + Split gm into sub-graph-modules using `sequential_split_and_maybe_inline_subgraphs`, and + then recursively call itself on each of the submodules. + """ + return _replace_with_hop_pass_helper( + gm, + graph_signature, + _sequential_split_and_maybe_inline_subgraphs, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_quantized_ops_with_standard_ops_pass.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_quantized_ops_with_standard_ops_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..8016708026b2ef71b04062b3aec2151ec6ee7fba --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_quantized_ops_with_standard_ops_pass.py @@ -0,0 +1,700 @@ +# mypy: allow-untyped-defs +import logging +import operator + +import torch +import torch.export._trace +from torch._ops import OpOverload +from torch.ao.quantization.fx._decomposed import ( + dequantize_per_channel, + dequantize_per_tensor, + quantize_per_tensor, +) +from torch.ao.quantization.utils import calculate_qmin_qmax +from torch.fx.graph_module import _assign_attr + + +log = logging.getLogger(__name__) + +# Those values will need to be carried over multiple operators. +_INPUT_Q_DTYPE: torch.dtype | torch.fx.Node | None = None +_SCALE: float | torch.fx.Node | None = None +_ZERO_POINT: float | torch.fx.Node | None = None + + +def int_to_valid_dtype(val: int) -> torch.dtype: + from torch._export.converter import _TORCH_ENUM_TO_DTYPE # No circular import. + + if isinstance(val, torch.dtype): + return val + dtype = _TORCH_ENUM_TO_DTYPE[val] + if dtype == torch.quint8: + return torch.uint8 + elif dtype == torch.qint8: + return torch.int8 + return dtype + + +def fx_enum_to_dtype(gm: torch.fx.GraphModule, val: int) -> torch.fx.Node: + return gm.graph.call_function(int_to_valid_dtype, (val,)) + + +def insert_quantized_node( + gm: torch.fx.GraphModule, + val_node: torch.fx.Node, + scale_node: float | torch.fx.Node, + zero_point_node: float | torch.fx.Node, + qmin_node: float | int | torch.fx.Node, + qmax_node: float | int | torch.fx.Node, + dtype_node: torch.dtype | torch.fx.Node, + qscheme: torch.qscheme | None, +) -> torch.fx.Node: + return gm.graph.call_function( + quantize_per_tensor, + ( + val_node, + scale_node, + zero_point_node, + qmin_node, + qmax_node, + dtype_node, + ), + ) + + +def get_dequantized( + val: torch.Tensor, + scale: float | torch.Tensor, + zero_point: float | torch.Tensor, + qmin: float | int, + qmax: float | int, + dtype: torch.dtype, + axis: int | None, + qscheme: torch.qscheme | None, +) -> torch.Tensor: + if qscheme is torch.per_tensor_affine: + return dequantize_per_tensor( + val, + scale, # type: ignore[arg-type] + zero_point, # type: ignore[arg-type] + qmin, # type: ignore[arg-type] + qmax, # type: ignore[arg-type] + dtype, + ) + elif qscheme is torch.per_channel_affine: + return dequantize_per_channel( + val, + scale, # type: ignore[arg-type] + zero_point, # type: ignore[arg-type] + axis, # type: ignore[arg-type] + qmin, # type: ignore[arg-type] + qmax, # type: ignore[arg-type] + dtype, + ) + else: + raise RuntimeError(f"Unsupported dequantization scheme: {qscheme}") + + +def insert_dequantized_node( + gm: torch.fx.GraphModule, + val_node: torch.fx.Node, + scale_node: float | torch.fx.Node, + zero_point_node: float | torch.fx.Node, + qmin_node: float | int | torch.fx.Node, + qmax_node: float | int | torch.fx.Node, + dtype_node: torch.dtype | torch.fx.Node, + axis_node: int | torch.fx.Node | None, + qscheme: torch.qscheme | None, +) -> torch.fx.Node: + if qscheme is torch.per_tensor_affine: + return gm.graph.call_function( + dequantize_per_tensor, + ( + val_node, + scale_node, + zero_point_node, + qmin_node, + qmax_node, + dtype_node, + ), + ) + elif qscheme is torch.per_channel_affine: + return gm.graph.call_function( + dequantize_per_channel, + ( + val_node, + scale_node, + zero_point_node, + axis_node, + qmin_node, + qmax_node, + dtype_node, + ), + ) + else: + raise RuntimeError(f"Unsupported dequantization scheme: {qscheme}") + + +def get_qmin_qmax(dtype: torch.dtype) -> tuple[int | float, int | float]: + return calculate_qmin_qmax(None, None, False, dtype, False) # type: ignore[arg-type] + + +def insert_qmin_qmax_node( + gm: torch.fx.GraphModule, dtype_node: torch.dtype | torch.fx.Node +) -> tuple[torch.fx.Node, torch.fx.Node]: + q_min_max_node = gm.graph.call_function( + calculate_qmin_qmax, (None, None, False, dtype_node, False) + ) + qmin_node = gm.graph.call_function(operator.getitem, (q_min_max_node, 0)) + qmax_node = gm.graph.call_function(operator.getitem, (q_min_max_node, 1)) + return qmin_node, qmax_node + + +def get_script_object( + gm: torch.nn.Module, node: torch.fx.Node +) -> torch._C.ScriptObject: + if not isinstance(node, torch.fx.Node): + raise AssertionError(f"expected fx.Node, got {type(node).__name__}") + if node.op != "get_attr": + raise AssertionError(f"expected get_attr op, got {node.op}") + attr_name = node.target + if not isinstance(attr_name, str): + raise AssertionError(f"expected str target, got {type(attr_name).__name__}") + + mod = gm + for attr in attr_name.split("."): + mod = getattr(mod, attr) + if not isinstance(mod, torch._C.ScriptObject): + raise AssertionError(f"expected ScriptObject, got {type(mod).__name__}") + return mod + + +def insert_weight_and_bias_get_attr_node_from_get_attr_to_scriptobject( + gm: torch.fx.GraphModule, + param_node: torch.fx.Node, +) -> tuple[torch.fx.Node, torch.fx.Node | None]: + """Directly inline tensor from a get_attr fx node.""" + mod = get_script_object(gm, param_node) + w_qtensor, b_qtensor = mod.unpack() # type: ignore[attr-defined] + w_attr_name, b_attr_name = ( + f"dequantized_{param_node.target}_w", + f"dequantized_{param_node.target}_b", + ) + return insert_weight_and_bias_get_attr_node( + gm, w_qtensor, b_qtensor, w_attr_name, b_attr_name + ) + + +def insert_weight_and_bias_get_attr_node_from_get_attr_to_qtensor( + gm: torch.fx.GraphModule, + get_attr_to_weight_node: torch.fx.Node, + get_attr_to_bias_node: torch.fx.Node | None, +) -> tuple[torch.fx.Node, torch.fx.Node | None]: + if not isinstance(get_attr_to_weight_node.target, str): + raise AssertionError( + f"expected str target, got {type(get_attr_to_weight_node.target).__name__}" + ) + w_qtensor = getattr(gm, get_attr_to_weight_node.target) + w_attr_name = f"dequantized_{get_attr_to_weight_node.target}_w" + + if get_attr_to_bias_node is not None: + if not isinstance(get_attr_to_bias_node.target, str): + raise AssertionError( + f"expected str target, got {type(get_attr_to_bias_node.target).__name__}" + ) + b_qtensor = getattr(gm, get_attr_to_bias_node.target) + b_attr_name = f"dequantized_{get_attr_to_bias_node.target}_b" + else: + b_qtensor, b_attr_name = None, "" + + return insert_weight_and_bias_get_attr_node( + gm, w_qtensor, b_qtensor, w_attr_name, b_attr_name + ) + + +def insert_weight_and_bias_get_attr_node( + gm: torch.fx.GraphModule, + w_qtensor: torch.Tensor, + b_qtensor: torch.Tensor | None, + w_attr_name: str, + b_attr_name: str, +) -> tuple[torch.fx.Node, torch.fx.Node | None]: + w_tensor = get_tensor_from_qtensor(w_qtensor) + _assign_attr(w_tensor, gm, w_attr_name) + w_tensor_attr = gm.graph.get_attr(w_attr_name) + + if b_qtensor is not None: + b_tensor = get_tensor_from_qtensor(b_qtensor, dequant=False) + _assign_attr(b_tensor, gm, b_attr_name) + b_tensor_attr = gm.graph.get_attr(b_attr_name) + else: + b_tensor_attr = None + + return w_tensor_attr, b_tensor_attr + + +def get_tensor_from_qtensor( + qtensor: torch.Tensor, dequant: bool = True +) -> torch.Tensor: + # Manual conversion because qint8 is not used anymore. + if qtensor.dtype in [torch.qint8, torch.quint8]: + tensor = qtensor.int_repr() + else: + tensor = qtensor + + # Weights need dequantization with scaling and zero_point adjustment, but + # bias does not need that. + if dequant: + qscheme = qtensor.qscheme() + if qscheme == torch.per_channel_affine: + scale, zero_point, axis = ( + qtensor.q_per_channel_scales(), + qtensor.q_per_channel_zero_points(), + qtensor.q_per_channel_axis(), + ) + else: + scale, zero_point, axis = ( + qtensor.q_scale(), # type: ignore[assignment] + qtensor.q_zero_point(), # type: ignore[assignment] + None, + ) + dtype = tensor.dtype + qmin, qmax = get_qmin_qmax(dtype) + return get_dequantized( + tensor, scale, zero_point, qmin, qmax, dtype, axis, qscheme + ) + return tensor + + +def insert_fused_activation_node( + gm: torch.fx.GraphModule, opname: str, fx_node: torch.fx.Node +) -> torch.fx.Node: + if opname in ["conv1d_relu", "conv2d_relu", "linear_relu", "add_relu", "mul_relu"]: + fx_node = gm.graph.call_function(torch.ops.aten.relu, (fx_node,)) + return fx_node + + +def _conv1d_op_with_squeeze( + inp: torch.Tensor, + weight: torch.Tensor, + bias: torch.Tensor | None, + stride: list[int], + padding: list[int], + dilation: list[int], + groups: int, +) -> torch.Tensor: + # In quantized version, conv1d is emulated using conv2d with squeeze and unsqueeze + # operations before and after the conv2d operation to match the dimension of weights. + # Reference: https://github.com/pytorch/pytorch/blob/eca0cb0fbe84bb0a34fa94afe261bceecd52c436/aten/src/ATen/native/quantized/cpu/qconv.cpp#L1827 + s_inp = torch.ops.aten.unsqueeze(inp, 2) + conv1d_res = torch.ops.aten.conv2d( + s_inp, + weight, + bias, + stride, + padding, + dilation, + groups, + ) + uns_conv1d_res = torch.ops.aten.squeeze(conv1d_res, 2) + return uns_conv1d_res + + +def _transform_conv_with_packedparam(gm: torch.fx.GraphModule, node: torch.fx.Node): + """Conv specific transformation function.""" + if not isinstance(node.target, torch._ops.OpOverload): + raise AssertionError(f"expected OpOverload, got {type(node.target).__name__}") + opname = node.target._opname + scale_node, zero_point_node = node.args[2], node.args[3] + + op_f = ( + torch.ops.aten.conv2d + if opname in ["conv2d", "conv2d_relu"] + else _conv1d_op_with_squeeze + ) + + inp_node, param_node = node.args[0], node.args[1] + if not isinstance(inp_node, torch.fx.Node): + raise AssertionError(f"expected fx.Node for inp, got {type(inp_node)}") + if not isinstance(param_node, torch.fx.Node): + raise AssertionError(f"expected fx.Node for param, got {type(param_node)}") + + if param_node.op == "call_function": + # Using Conv2dPrepackParam from conv_prepack. + # We directly skip the packing call and inline weights and bias. + w_node, b_node = param_node.args[0], param_node.args[1] + if not isinstance(w_node, torch.fx.Node): + raise AssertionError(f"expected fx.Node for w, got {type(w_node)}") + if b_node is not None and not isinstance(b_node, torch.fx.Node): + raise AssertionError(f"expected fx.Node for b, got {type(b_node)}") + ( + param_0, + param_1, + ) = insert_weight_and_bias_get_attr_node_from_get_attr_to_qtensor( + gm, w_node, b_node + ) + op_res_node = gm.graph.call_function( + op_f, (inp_node, param_0, param_1, *param_node.args[2:]) + ) + else: + # Using ConvPrepackedParam. + param = get_script_object(gm, param_node) + ( + param_0, + param_1, + ) = insert_weight_and_bias_get_attr_node_from_get_attr_to_scriptobject( + gm, param_node + ) # type: ignore[assignment] + op_res_node = gm.graph.call_function( + op_f, + ( + inp_node, + param_0, + param_1, + param.stride(), # type: ignore[attr-defined] + param.padding(), # type: ignore[attr-defined] + param.dilation(), # type: ignore[attr-defined] + param.groups(), # type: ignore[attr-defined] + ), + ) + return op_res_node, scale_node, zero_point_node + + +def _transform_linear_with_packedparam(gm: torch.fx.GraphModule, node: torch.fx.Node): + """Linear specific transformation function.""" + scale_node, zero_point_node = node.args[2], node.args[3] + + inp_node, param_node = node.args[0], node.args[1] + if not isinstance(inp_node, torch.fx.Node): + raise AssertionError(f"expected fx.Node for inp, got {type(inp_node)}") + if not isinstance(param_node, torch.fx.Node): + raise AssertionError(f"expected fx.Node for param, got {type(param_node)}") + + if param_node.op == "call_function": + # Using LinearPrepackParam from linear_prepack. + # We directly skip the packing call and inline weights and bias. + w_node, b_node = param_node.args[0], param_node.args[1] + if not isinstance(w_node, torch.fx.Node): + raise AssertionError(f"expected fx.Node for w, got {type(w_node)}") + if b_node is not None and not isinstance(b_node, torch.fx.Node): + raise AssertionError(f"expected fx.Node for b, got {type(b_node)}") + ( + param_0, + param_1, + ) = insert_weight_and_bias_get_attr_node_from_get_attr_to_qtensor( + gm, w_node, b_node + ) + op_res_node = gm.graph.call_function( + torch.ops.aten.linear, (inp_node, param_0, param_1, *param_node.args[2:]) + ) + else: + # Using LinearPackedParams. + ( + param_0, + param_1, + ) = insert_weight_and_bias_get_attr_node_from_get_attr_to_scriptobject( + gm, param_node + ) # type: ignore[assignment] + op_res_node = gm.graph.call_function( + torch.ops.aten.linear, (inp_node, param_0, param_1) + ) + return op_res_node, scale_node, zero_point_node + + +def _transform_op_where_last_two_arguments_are_scale_and_zero_point( + gm: torch.fx.GraphModule, node: torch.fx.Node +): + """ + This transformation function can be used for function where the last two + parameters are scale and zero point. Additionally, the function's parameters + do not need any unpacking. + """ + to_standard_op = { + "mul": torch.ops.aten.mul, + "mul_relu": torch.ops.aten.mul, + "add": torch.ops.aten.add, + "add_relu": torch.ops.aten.add, + "softmax": torch.ops.aten.softmax, + "cat": torch.ops.aten.cat, + "hardswish": torch.ops.aten.hardswish, + } + + if not isinstance(node.target, torch._ops.OpOverload): + raise AssertionError(f"expected OpOverload, got {type(node.target).__name__}") + opname, args = node.target._opname, node.args + scale_node, zero_point_node = args[-2], args[-1] + op_res_node = gm.graph.call_function(to_standard_op[opname], tuple(args[:-2])) + return op_res_node, scale_node, zero_point_node + + +def _transform_scalar_arithmetic(gm: torch.fx.GraphModule, node: torch.fx.Node): + """Transform scalar overload for basic arithmetic.""" + to_standard_op = { + "mul": torch.ops.aten.mul.Scalar, + "add": torch.ops.aten.add.Scalar, + } + if not isinstance(node.target, torch._ops.OpOverload): + raise AssertionError(f"expected OpOverload, got {type(node.target).__name__}") + opname, args = node.target._opname, node.args + op_res_node = gm.graph.call_function(to_standard_op[opname], args) + return op_res_node, _SCALE, _ZERO_POINT + + +def _transform_prepacked_op(gm: torch.fx.GraphModule, node: torch.fx.Node): + """ + Transformation for functions under prepacked namespace, where they share + the same handling logic that [...]OpContext contains all parameters. + """ + if not isinstance(node.target, torch._ops.OpOverload): + raise AssertionError(f"expected OpOverload, got {type(node.target).__name__}") + opname, args = node.target._opname, node.args + op_f = None + if opname == "conv2d_clamp_run": + op_f = torch.ops.aten.conv2d + elif opname == "linear_clamp_run": + op_f = torch.ops.aten.linear + else: + raise RuntimeError(f"Invalid operator {opname}") + + if not isinstance(args[1], torch.fx.Node): + raise AssertionError(f"expected fx.Node for args[1], got {type(args[1])}") + so = get_script_object(gm, args[1]) + + func_args = [] + func_args += [args[0]] + func_args += so.unpack()[:2] # type: ignore[attr-defined] + if opname == "conv2d_clamp_run": + func_args += torch.ops.prepacked.unpack_prepacked_sizes_conv2d(so)[2:] + + op_res_node = gm.graph.call_function(op_f, tuple(func_args)) + return op_res_node + + +def _transform_batch_norm(gm: torch.fx.GraphModule, node: torch.fx.Node): + args = node.args + scale_node, zero_point_node = args[-2], args[-1] + op_res_node = gm.graph.call_function( + torch.ops.aten.native_batch_norm, (*args[:-3], False, 0.1, args[-3]) + ) + op_res_node = gm.graph.call_function(operator.getitem, (op_res_node, 0)) + return op_res_node, scale_node, zero_point_node + + +def fx_transform_quantized_op_to_standard_op( + gm: torch.fx.GraphModule, node: torch.fx.Node +) -> torch.fx.Node: + global _SCALE, _ZERO_POINT, _INPUT_Q_DTYPE + + if not isinstance(node.target, torch._ops.OpOverload): + raise AssertionError(f"expected OpOverload, got {type(node.target).__name__}") + opname, overload = node.target._opname, node.target._overloadname + + key = f"{opname}.{overload}" + opname_to_transform_f = { + "conv1d.new": _transform_conv_with_packedparam, + "conv1d_relu.new": _transform_conv_with_packedparam, + "conv1d.default": _transform_conv_with_packedparam, + "conv1d_relu.default": _transform_conv_with_packedparam, + "conv2d.new": _transform_conv_with_packedparam, + "conv2d_relu.new": _transform_conv_with_packedparam, + "conv2d.default": _transform_conv_with_packedparam, + "conv2d_relu.default": _transform_conv_with_packedparam, + "linear.default": _transform_linear_with_packedparam, + "linear_relu.default": _transform_linear_with_packedparam, + "add.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point, + "add_relu.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point, + "mul.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point, + "mul_relu.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point, + "softmax.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point, + "cat.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point, + "hardswish.default": _transform_op_where_last_two_arguments_are_scale_and_zero_point, + "batch_norm2d.default": _transform_batch_norm, + "mul.Scalar": _transform_scalar_arithmetic, + "add.Scalar": _transform_scalar_arithmetic, + } + + if f"{key}" not in opname_to_transform_f: + raise RuntimeError(f"Unsupported quantized op during transformation: {key}") + + op_res_node, scale_node, zero_point_node = opname_to_transform_f[f"{key}"](gm, node) + + # Add fused activation layer. + op_res_node = insert_fused_activation_node(gm, opname, op_res_node) + _SCALE, _ZERO_POINT = scale_node, zero_point_node + + if _INPUT_Q_DTYPE is None: + raise AssertionError("_INPUT_Q_DTYPE should not be None") + qmin_node, qmax_node = insert_qmin_qmax_node(gm, _INPUT_Q_DTYPE) + q_fx_node = insert_quantized_node( + gm, + op_res_node, + scale_node, + zero_point_node, + qmin_node, + qmax_node, + _INPUT_Q_DTYPE, + torch.per_tensor_affine, + ) + dq_fx_node = insert_dequantized_node( + gm, + q_fx_node, + scale_node, + zero_point_node, + qmin_node, + qmax_node, + _INPUT_Q_DTYPE, + None, + torch.per_tensor_affine, + ) + return dq_fx_node + + +def replace_quantized_ops_with_standard_ops(gm: torch.fx.GraphModule): + """ + Replace legacy quantized ops (aten.quantize_per_tensor, quantized.conv) with + PT2 ops (quantize_decomposed.quantize_per_tensor, aten.conv). + + Before: x || -> aten.q || -> quantized.conv2d || -> quantized.linear || -> aten.dq || -> y + + After: x || -> qd.q -> qd.dq || -> aten.conv2d -> qd.q -> qd.dq || aten.linear -> qd.q -> qd.dq || -> y + + (qd == quantized_decomposed library, q = quantize, dq = dequantize) + ^ + | + getattr(w), getattr(b) from Conv2dParamPrepack + + During each iteration, the transformation spits out the transformed operator, its quantized output, + and its dequantized value together. We did this because dequantization need to use the + scale and zero point parameters from the quantization to recover the approximate original value. After each + iteration, the new dequantization node will be used as the input to the next node (e.g., dq2 -> linear). + + For operators like conv2d and linear, their weights and bias are packed in a quantized format in the ScriptObject. + During the transformation, we unpack those objects, get their dequantized tensor, populate those + as attributes to the module, and use getattr to access them. + + One exception in the transformation is conv_prepack and linear_prepack. Those calls pack + weight and bias constant tensors into ScriptObject, which are then used by subsequent conv2d or linear calls. + During transformation, we directly skip transforming conv_prepack or linear_prepack. We check whether ScriptObject to the + quantized::conv2d or linear is from conv_prepack or linear_prepack. If it is, we then inline those parameters + to the operator by converting them to a getattr fx.node. + + For prepacked::conv2d_clamp_run and prepacked::linear_clamp_run, we directly convert them to aten.conv2d and aten.linear + without the need of doing de/quantization. + + Three global variables defined are _INPUT_Q_DTYPE, _SCALE, _ZERO_POINT. _INPUT_Q_DTYPE determines the de/quantization + data type, which is the same across the entire program, but it only shows up in the very first quantization + call. _SCALE and _ZERO_POINT are used only when operators do not have those specified. E.g., mul.Scalar. + """ + + global _INPUT_Q_DTYPE + + quantized = False + + last_quantized_node = None + # pyrefly: ignore [bad-assignment] + for node in gm.graph.nodes: + if isinstance(node.target, OpOverload): + with gm.graph.inserting_before(node): + namespace, opname = node.target.namespace, node.target._opname + if namespace == "quantized" and opname not in [ + "conv_prepack", + "linear_prepack", + ]: + quantized = True + fx_node = fx_transform_quantized_op_to_standard_op(gm, node) + node.replace_all_uses_with(fx_node) + last_quantized_node = fx_node + elif namespace == "prepacked": + quantized = True + fx_node = _transform_prepacked_op(gm, node) + node.replace_all_uses_with(fx_node) + last_quantized_node = fx_node + elif namespace == "aten" and opname == "quantize_per_tensor": + inp_node, scale_node, zero_point_node, dtype_node = node.args + dtype_node = fx_enum_to_dtype(gm, dtype_node) + _INPUT_Q_DTYPE = dtype_node + qmin_node, qmax_node = insert_qmin_qmax_node(gm, dtype_node) + q_fx_node = insert_quantized_node( + gm, + inp_node, + scale_node, + zero_point_node, + qmin_node, + qmax_node, + dtype_node, + torch.per_tensor_affine, + ) + dq_fx_node = insert_dequantized_node( + gm, + q_fx_node, + scale_node, + zero_point_node, + qmin_node, + qmax_node, + dtype_node, + None, + torch.per_tensor_affine, + ) + node.replace_all_uses_with(dq_fx_node) + last_quantized_node = dq_fx_node + elif namespace == "aten" and opname == "dequantize": + if last_quantized_node is None: + raise AssertionError("last_quantized_node should not be None") + node.replace_all_uses_with(last_quantized_node) + else: + last_quantized_node = node + + # Post-processing again to remove legacy ScriptObjects and quantized tensors + # stored as attributes or in the buffer. This is used to clean up the GraphModule + # to not trigger tracing errors like missing __obj_flatten__ functions. + def _clean_attr(mod: torch.nn.Module): + for submod in mod.modules(): + attr_names_to_clean = set() + for k, v in submod.__dict__.items(): + if isinstance(v, torch.ScriptObject): + attr_names_to_clean.add(k) + if k == "_buffers": + buffer_name_to_clean = set() + + for b_name, b_value in v.items(): + if isinstance(b_value, torch.Tensor) and b_value.dtype in [ + torch.qint8, + torch.quint8, + ]: + buffer_name_to_clean.add(b_name) + for b_name in buffer_name_to_clean: + v.pop(b_name, None) + for attr_name in attr_names_to_clean: + delattr(submod, attr_name) + + if quantized: + """ + TODO: SetAttr + quantized ops will result incorrect program. This flag is used to temporarily + bypass test cases. + + The deadcode elimination pass is needed to remove legacy quantized ops. Otherwise, retracing + will throw errors. However, the current way of SetAttr does inplace update to attributes, so + this pass regard them as dead code and remove them. Below is an example of GraphModule before + and after the dead code elimination pass. + + class GraphModule(torch.nn.Module): + def forward(self, x_1): + # No stacktrace found for following nodes + data = self.data; data = None + data_1 = self.data + add_tensor = torch.ops.aten.add.Tensor(data_1, x_1, alpha = 1); data_1 = None + data_2 = self.data + copy_ = torch_Tensor_copy_(data_2, add_tensor); data_2 = add_tensor = copy_ = None + data_3 = self.data + add_tensor_1 = torch.ops.aten.add.Tensor(x_1, data_3, alpha = 1); x_1 = data_3 = None + return add_tensor_1 + + class GraphModule(torch.nn.Module): + def forward(self, x_1): + # No stacktrace found for following nodes + data_3 = self.data + add_tensor_1 = torch.ops.aten.add.Tensor(x_1, data_3, alpha = 1); x_1 = data_3 = None + return add_tensor_1 + """ + gm.graph.eliminate_dead_code() + _clean_attr(gm) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_set_grad_with_hop_pass.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_set_grad_with_hop_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..100c88397828f42b340174f02f9cc2327338be0f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_set_grad_with_hop_pass.py @@ -0,0 +1,131 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch +from torch._higher_order_ops.wrap import wrap_with_set_grad_enabled + +from ..utils import node_inline_, nodes_filter, nodes_first, nodes_map, sequential_split +from .replace_with_hop_pass_util import ( + _replace_with_hop_helper, + _replace_with_hop_pass_helper, + _sequential_split_and_maybe_inline_subgraphs_helper, +) + + +if TYPE_CHECKING: + from torch.export.graph_signature import ExportGraphSignature + + +def _is_set_grad_enabled_node(node: torch.fx.Node) -> torch.fx.Node | bool: + return ( + node + and node.op == "call_function" + and node.target is torch._C._set_grad_enabled + ) + + +def _is_set_grad_enabled_sub_mod( + node: torch.fx.Node, omit_if_same_with_ambient: bool = False +) -> bool | torch.Tensor: + if node.op == "call_module": + if not isinstance(node.target, str): + raise AssertionError(f"expected str target, got {type(node.target)}") + subgm = getattr(node.graph.owning_module, node.target) + first_non_ph = nodes_first( + subgm.graph.nodes, lambda node: node.op != "placeholder" + ) + if ( + first_non_ph + and first_non_ph.op == "call_function" + and first_non_ph.target is torch._C._set_grad_enabled + ): + return ( + first_non_ph.args[0] != torch.is_grad_enabled() # type: ignore[bad-return] + if omit_if_same_with_ambient + else True + ) + return False + + +def _replace_with_hop(node: torch.fx.Node) -> None: + if node.op != "call_module": + raise AssertionError(f"expected call_module op, got {node.op}") + graph: torch.fx.Graph = node.graph + if graph.owning_module is None: + raise AssertionError("graph.owning_module must not be None") + gm: torch.fx.GraphModule = graph.owning_module + if not isinstance(node.target, str): + raise AssertionError(f"expected str target, got {type(node.target)}") + sub_gm = getattr(gm, node.target) + sub_graph = sub_gm.graph + set_grad_nodes = nodes_filter(sub_graph.nodes, _is_set_grad_enabled_node) + if len(set_grad_nodes) > 0: + if len(set_grad_nodes) != 1: + raise AssertionError( + f"expected exactly 1 set_grad node, got {len(set_grad_nodes)}" + ) + set_grad_node = set_grad_nodes[0] + _replace_with_hop_helper(node, set_grad_node, wrap_with_set_grad_enabled) + sub_graph.erase_node(set_grad_node) + + +def _remove_set_grad_and_inline(node: torch.fx.Node) -> None: + if node.op != "call_module": + raise AssertionError(f"expected call_module op, got {node.op}") + graph: torch.fx.Graph = node.graph + if graph.owning_module is None: + raise AssertionError("graph.owning_module must not be None") + gm: torch.fx.GraphModule = graph.owning_module + if not isinstance(node.target, str): + raise AssertionError(f"expected str target, got {type(node.target)}") + sub_gm = getattr(gm, node.target) + sub_graph = sub_gm.graph + nodes_map( + sub_graph.nodes, + lambda n: sub_graph.erase_node(n) if _is_set_grad_enabled_node(n) else n, + ) + node_inline_(node) + + +def _sequential_split_and_maybe_inline_subgraphs( + gm: torch.fx.GraphModule, graph_signature: ExportGraphSignature | None +) -> tuple[torch.fx.GraphModule, ExportGraphSignature | None]: + """ + Helper function for replace_set_grad_with_hop_pass(). + Split the graph module into multiple subgraphs based on the set_grad_enabled nodes. + For each subgraph, decides whether to construct a HOO subgraph, or inline the calls + back into the parent graph module. + """ + need_replacing = any(_is_set_grad_enabled_node(node) for node in gm.graph.nodes) + if not need_replacing: + return gm, graph_signature + + # sequential_split returns a new graph module that could have different output + # args names. We need to fix the graph signature. + new_gm = sequential_split(gm, _is_set_grad_enabled_node) + + def _maybe_inline_or_replace_with_hop(node: torch.fx.Node): + if _is_set_grad_enabled_sub_mod(node, omit_if_same_with_ambient=True): + _replace_with_hop(node) + else: + _remove_set_grad_and_inline(node) + + return _sequential_split_and_maybe_inline_subgraphs_helper( + new_gm, graph_signature, _maybe_inline_or_replace_with_hop + ) + + +def replace_set_grad_with_hop_pass( + gm: torch.fx.GraphModule, graph_signature: ExportGraphSignature | None +) -> tuple[torch.fx.GraphModule, ExportGraphSignature | None]: + """ + Split gm into sub-graph-modules using `sequential_split_and_maybe_inline_subgraphs`, and + then recursively call itself on each of the submodules. + """ + return _replace_with_hop_pass_helper( + gm, + graph_signature, + _sequential_split_and_maybe_inline_subgraphs, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_view_ops_with_view_copy_ops_pass.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_view_ops_with_view_copy_ops_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..98d93e16559b77e9fc812096a010261cdaf05fde --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_view_ops_with_view_copy_ops_pass.py @@ -0,0 +1,64 @@ +# mypy: allow-untyped-defs + +import torch +from torch._export.error import InternalError +from torch._export.pass_base import _ExportPassBaseDeprecatedDoNotUse +from torch._ops import HigherOrderOperator, OpOverload + + +__all__ = ["ReplaceViewOpsWithViewCopyOpsPass"] + + +_NON_FUNCTIONAL_OPS_TO_FUNCTIONAL_OPS: dict[OpOverload, OpOverload] = { + torch.ops.aten._unsafe_view.default: torch.ops.aten.view_copy.default, +} + + +def is_view_op(schema: torch._C.FunctionSchema) -> bool: + if len(schema.arguments) == 0: + return False + alias_info = schema.arguments[0].alias_info + return (alias_info is not None) and (not alias_info.is_write) + + +def get_view_copy_of_view_op(schema: torch._C.FunctionSchema) -> OpOverload | None: + if is_view_op(schema) and schema.name.startswith("aten::"): + view_op_name = schema.name.split("::")[1] + view_op_overload = ( + schema.overload_name if schema.overload_name != "" else "default" + ) + view_copy_op_name = view_op_name + "_copy" + if not hasattr(torch.ops.aten, view_copy_op_name): + raise InternalError(f"{schema.name} is missing a view_copy variant") + + view_copy_op_overload_packet = getattr(torch.ops.aten, view_copy_op_name) + + if not hasattr(view_copy_op_overload_packet, view_op_overload): + raise InternalError(f"{schema.name} is missing a view_copy variant") + + return getattr(view_copy_op_overload_packet, view_op_overload) + + return None + + +class ReplaceViewOpsWithViewCopyOpsPass(_ExportPassBaseDeprecatedDoNotUse): + """ + Our backend expects pure functional operators. For efficiency + purposes, we keep view ops around while functionalizing the exported + program. This pass replaces view ops with view copy ops for backends that + need AOT memory planning. + """ + + def call_operator(self, op, args, kwargs, meta): + if op in _NON_FUNCTIONAL_OPS_TO_FUNCTIONAL_OPS: + return super().call_operator( + (_NON_FUNCTIONAL_OPS_TO_FUNCTIONAL_OPS[op]), args, kwargs, meta + ) + + if isinstance(op, HigherOrderOperator): + return super().call_operator(op, args, kwargs, meta) + + if view_copy_op := get_view_copy_of_view_op(op._schema): + return super().call_operator(view_copy_op, args, kwargs, meta) + + return super().call_operator(op, args, kwargs, meta) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_with_hop_pass_util.py b/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_with_hop_pass_util.py new file mode 100644 index 0000000000000000000000000000000000000000..b095d2c6e07609fd603477011b29de1a326769d5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/passes/replace_with_hop_pass_util.py @@ -0,0 +1,202 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import contextlib +import copy +import operator +from typing import TYPE_CHECKING + +import torch + +from ..utils import node_replace_, nodes_map + + +if TYPE_CHECKING: + from collections.abc import Callable + + from torch._ops import HigherOrderOperator + from torch.export.graph_signature import ExportGraphSignature + + +def _replace_with_hop_helper( + node: torch.fx.Node, + enter_block_node: torch.fx.Node, + wrap_hoo: HigherOrderOperator, +) -> None: + graph: torch.fx.Graph = node.graph + if graph.owning_module is None: + raise AssertionError("graph.owning_module must not be None") + gm: torch.fx.GraphModule = graph.owning_module + if not isinstance(node.target, str): + raise AssertionError(f"expected str target, got {type(node.target)}") + sub_gm = getattr(gm, node.target) + + def set_hoo_node_meta(call_func_node): + call_func_node.meta["nn_module_stack"] = copy.copy( + enter_block_node.meta.get("nn_module_stack", {}) + ) + call_func_node.meta["torch_fn"] = ( + f"{wrap_hoo.__name__}", + # pyrefly: ignore [missing-attribute] + f"{wrap_hoo.__class__.__name__}.{wrap_hoo.__name__}", + ) + if isinstance(output_args, (tuple, list)): + call_func_node.meta["val"] = tuple(arg.meta["val"] for arg in output_args) + elif isinstance(output_args, torch.fx.Node): + call_func_node.meta["val"] = (output_args.meta["val"],) + + with graph.inserting_before(node): + get_attr_node = graph.get_attr(node.target) + get_attr_node.meta["nn_module_stack"] = copy.copy( + enter_block_node.meta.get("nn_module_stack", {}) + ) + output_node = next(iter(reversed(sub_gm.graph.nodes)), None) + # Split_module pass intentionally doesn't add output node + # if the graph doesn't return anything. + # TODO (tmanlaibaatar) Figure out if this is right behaviour + # for split_module + if isinstance(output_node, torch.fx.Node) and output_node.op != "output": + output_node = None + if output_node is not None: + if len(output_node.args) != 1: + raise AssertionError( + f"expected 1 output arg, got {len(output_node.args)}" + ) + output_args = output_node.args[0] + enter_block_node_args = enter_block_node.args + if isinstance(output_args, (tuple, list)): + call_func_node = graph.call_function( + wrap_hoo, + (*enter_block_node_args, get_attr_node, *node.args), + {}, + ) + # Create the metadata + set_hoo_node_meta(call_func_node) + node_replace_(node, call_func_node) + + # Rename the name of getitem nodes to the actual name of its contents + # for passing verifier and better readability, also propagate metadata + for get_item_node in call_func_node.users: + idx: int = get_item_node.args[1] # type: ignore[assignment] + output_node = output_args[idx] + get_item_node._rename(output_node.name) + get_item_node.meta = output_node.meta + + elif isinstance(output_args, torch.fx.Node): + call_func_node = graph.create_node( + "call_function", + wrap_hoo, + (*enter_block_node_args, get_attr_node, *node.args), + {}, + output_args.name, + ) + # Modify the subgraph to output a singleton list. + output_node.args = ((output_args,),) + # Add in an extra `getitem(wrap_hoo, 0)` node to the toplevel graph. + get_item_node = graph.create_node( + "call_function", + operator.getitem, + (call_func_node, 0), + {}, + ) + # Create the metadata + get_item_node.meta = output_args.meta + set_hoo_node_meta(call_func_node) + node_replace_(node, get_item_node) + else: + raise NotImplementedError( + f"replace_with_hop_pass doesn't support output type {type(output_args)}" + ) + else: + # TODO (shangdiy): remove this line, since the export graph can be non-functional + node.graph.erase_node(node) + + +def _sequential_split_and_maybe_inline_subgraphs_helper( + new_gm: torch.fx.GraphModule, + graph_signature: ExportGraphSignature | None, + maybe_inline_or_replace_with_hop: Callable[[torch.fx.Node], None], +) -> tuple[torch.fx.GraphModule, ExportGraphSignature | None]: + """ + Helper function for replacing graph nodes with higher order nodes. + For each subgraph in `new_gm`, decides whether to construct a HOO subgraph, or inline the calls + back into the parent graph module, depending on `maybe_inline_or_replace_with_hop`. + """ + # new_gm is a new graph module that could have different output args names. + # We need to fix the graph signature. + replace_ctx = contextlib.nullcontext() + new_signature = None + if graph_signature is not None: + # Cannot deep copy a real ScriptObject, which is referenced + # in the FakeScriptObject. Copy should be good enough to guard + # against accidental mutation to original graph_signature. + new_signature = copy.copy(graph_signature) + new_gm_out_node = next(reversed(new_gm.graph.find_nodes(op="output"))) + if new_gm_out_node.op != "output" or len(new_gm_out_node.args[0]) != len( + new_signature.output_specs + ): + raise AssertionError( + f"output node mismatch: {new_gm_out_node.op}, " + f"{len(new_gm_out_node.args[0])} vs {len(new_signature.output_specs)}" + ) + for arg_node, out_spec in zip( + new_gm_out_node.args[0], new_signature.output_specs + ): + if arg_node is None: + if out_spec.arg.value is not None: # type: ignore[union-attr] + raise AssertionError( + f"expected None out_spec.arg.value, got {out_spec.arg.value}" # type: ignore[union-attr] + ) + elif ( + isinstance(arg_node, torch.fx.Node) + and out_spec.arg.name != arg_node.name + ): + out_spec.arg.name = arg_node.name + + replace_ctx = new_gm._set_replace_hook(new_signature.get_replace_hook()) # type: ignore[assignment] + + with replace_ctx: + nodes_map( + list(new_gm.graph.nodes), + lambda node: ( + maybe_inline_or_replace_with_hop(node) + if node.op == "call_module" + else node + ), + ) + new_gm.recompile() + new_gm.graph.lint() + return new_gm, new_signature + + +def _replace_with_hop_pass_helper( + gm: torch.fx.GraphModule, + graph_signature: ExportGraphSignature | None, + sequential_split_and_maybe_inline_subgraphs: Callable[ + [torch.fx.GraphModule, ExportGraphSignature | None], + tuple[torch.fx.GraphModule, ExportGraphSignature | None], + ], +) -> tuple[torch.fx.GraphModule, ExportGraphSignature | None]: + """ + Split gm into sub-graph-modules using `sequential_split_and_maybe_inline_subgraphs`, and + then recursively call itself on each of the submodules. + """ + new_gm, new_signature = sequential_split_and_maybe_inline_subgraphs( + gm, graph_signature + ) + # recursively call + for node in new_gm.graph.nodes: + if node.op == "get_attr": + subgm = getattr(new_gm, node.target) + if not isinstance(subgm, torch.fx.GraphModule): + continue + new_subgm, _ = _replace_with_hop_pass_helper( + subgm, + None, + sequential_split_and_maybe_inline_subgraphs, + ) + setattr(new_gm, node.target, new_subgm) + + new_gm.recompile() + new_gm.graph.lint() + return new_gm, new_signature diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/__init__.py b/.venv/lib/python3.12/site-packages/torch/_export/serde/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af8ea412709f7bb16052cb25795597469ad61c60 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/dynamic_shapes.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/dynamic_shapes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..148984c99057c6e68ef1a48bb34e8ff64bd574f8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/dynamic_shapes.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/schema.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/schema.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf91411fb64da2b309bc413ce875142e3e51fe2f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/schema.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/schema_check.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/schema_check.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c19289f9fa80ca96440085acab5d2cce2ce8946 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/schema_check.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/serialize.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/serialize.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eaa4ab8f58b380161bc85736a5e8b4dbdd319c7b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/serialize.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:945bc7008c47b8da653b3aeefba9cb943119de745389967fa268a8d0b0a606e6 +size 225350 diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/union.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/union.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..adfd8141a0d889ebb7a697d19c3f469e818bdb9d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/union.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/dynamic_shapes.py b/.venv/lib/python3.12/site-packages/torch/_export/serde/dynamic_shapes.py new file mode 100644 index 0000000000000000000000000000000000000000..32fe6014b04447ebe8f51ce8e855a737fbddd5d6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/serde/dynamic_shapes.py @@ -0,0 +1,327 @@ +import dataclasses +from typing import Any + +import torch +from torch._dynamo.exc import UserError, UserErrorType +from torch.export.dynamic_shapes import ( + _check_dynamic_shapes, + _DerivedDim, + _DimHint, + _tree_map_with_path, + Dim, +) +from torch.utils._pytree import tree_map + +from .serialize import _dataclass_to_dict + + +@dataclasses.dataclass +class RootDim: + """ + This represents a Dim object. + """ + + min: int + max: int | None + derived: list[str] + + +@dataclasses.dataclass +class DynamicShapesSpec: + """ + This stores a dynamic_shapes spec for de/serialization. + """ + + dynamic_shapes: dict[str, Any] | tuple[Any] | list[Any] | None + dims: dict[str, RootDim] + + +def _postprocess_serialized_shapes( + dynamic_shapes: dict[str, Any] | tuple[Any] | list[Any] | None, + dims: dict[str, dict[str, int | list[str] | None]], + to_dict: bool | None = False, +) -> DynamicShapesSpec | dict[str, Any]: + """ + Sorts dims and dumps to dictionary format. + """ + from torch.utils._sympy.numbers import int_oo + + # pyrefly: ignore [bad-assignment] + dims = { + k: RootDim( + min=v["min"], # type: ignore[arg-type] + max=None if v["max"] is int_oo else v["max"], # type: ignore[arg-type] + derived=sorted(v["derived"]), # type: ignore[arg-type] + ) + for k, v in sorted(dims.items()) + } + # pyrefly: ignore [bad-argument-type] + spec = DynamicShapesSpec(dynamic_shapes=dynamic_shapes, dims=dims) + if to_dict: + return _dataclass_to_dict(spec) + else: + return spec + + +def _dump_dynamic_shapes( + dynamic_shapes: dict[str, Any] | tuple[Any] | list[Any] | None, + args: tuple[Any], + kwargs: dict[str, Any] | None = None, + to_dict: bool | None = False, +) -> DynamicShapesSpec | dict[str, Any]: + """ + Utility function for dynamic shapes serialization, serializing a dynamic_shapes spec. + Returns a DynamicShapesSpec dataclass containing 2 fields, "dynamic_shapes" and "dims". + Uses args & kwargs to distinguish between tensor-level and dim-level specs (only for Nones). + + dynamic_shapes: A pytree structure mirroring the dynamic_shapes input to export(): + - Each tensor input is represented with a list of values, non-tensor inputs with None. + - dynamic dimensions (i.e. symbols) in tensors and Dim enums are represented with strings. + - static dimensions are represented with ints. + + dims: A dictionary mapping each symbol name to the min/max range and derived dim names. + + For example: + ``` + dx = Dim("dx", min=4, max=16) + dy = dx + 1 + + inputs = ( + [ + torch.randn(4, 4), + torch.randn(5, 4), + ], + torch.randn(4), + torch.randn(4, 4), + "hello", + ) + dynamic_shapes = { + "a": [ + (dx, 4), + (dy, 4), + ], + "b": (Dim.STATIC,), + "c": None, + "d": None, + } + out = _dump_dynamic_shapes(dynamic_shapes, inputs, to_dict=True) + ``` + would generate the following output: + ``` + { + "dynamic_shapes": ( + [ + ["dx", 4], + ["dx + 1", 4], + ], + ["_DimHint.STATIC"], + ["_DimHint.STATIC", "_DimHint.STATIC"], + None, + ), + "dims": { + "dx": { + "min": 4, + "max": 16, + "derived": ["dx + 1"], + }, + }, + } + ``` + """ + dims: dict[str, dict[str, Any]] = {} + + def _standardize_shapes(path, tensor, shape): # type: ignore[no-untyped-def] + """ + Helps standardize the dynamic_shapes tree structure we serialize, + returning lists for each tensor shape, handling tensor-level Nones. + """ + if not isinstance(tensor, torch.Tensor): + return None + if shape is None: + return [Dim.STATIC] * len(tensor.shape) + + out = [] + if isinstance(shape, dict): + for i, s in enumerate(tensor.shape): + out.append(s if shape.get(i) is None else shape.get(i)) + else: + if not isinstance(shape, (tuple, list)): + raise AssertionError(f"expected tuple or list, got {type(shape)}") + for i, s in enumerate(tensor.shape): + out.append(s if shape[i] is None else shape[i]) + return out + + def _track_dim_from_dims( + val: None | int | _DimHint | Dim, + ) -> None | int | str: + """ + Tracks dims, ranges, derived dims from the standardized dynamic_shapes spec. + """ + if val is None or isinstance(val, int): # non-tensor input or static + return val + if isinstance(val, _DimHint): # store enum as string + return val.__class__.__name__ + "." + val.type.name + + if not isinstance(val, Dim): + raise AssertionError(f"expected Dim, got {type(val)}") + + # track root dim + root = val.root if isinstance(val, _DerivedDim) else val # type: ignore[attr-defined] + if root.__name__ not in dims: + dims[root.__name__] = { + "min": root.min, # type: ignore[attr-defined,union-attr] + "max": root.max, # type: ignore[attr-defined,union-attr] + "derived": set(), + } + + # track derived dims + if isinstance(val, _DerivedDim): + dims[root.__name__]["derived"].add(val.__name__) + + return val.__name__ + + if dynamic_shapes is None: + return {"dynamic_shapes": None, "dims": {}} + + # convert to tuple of specs, for each arg/kwarg + kwargs = kwargs or {} + if isinstance(dynamic_shapes, dict): + dynamic_shapes = dynamic_shapes.values() # type: ignore[assignment] + # pyrefly: ignore [bad-assignment, bad-argument-type] + dynamic_shapes = tuple(dynamic_shapes) + combined_args = tuple(args) + tuple(kwargs.values()) + + # run same check when we're processing shapes for export - is this too lazy? + _check_dynamic_shapes(dict(enumerate(combined_args)), dynamic_shapes) # type: ignore[arg-type] + + tree_shapes = _tree_map_with_path( + _standardize_shapes, combined_args, dynamic_shapes, tree_name="inputs" + ) + serialized_shapes = tree_map(_track_dim_from_dims, tree_shapes) + return _postprocess_serialized_shapes(serialized_shapes, dims, to_dict=to_dict) + + +def _load_dynamic_shapes( + spec: DynamicShapesSpec | dict[str, Any], + from_dict: bool | None = False, +) -> dict[str, Any] | tuple[Any] | list[Any] | None: + """ + Utility function for dynamic shapes serialization. + Deserializes a DynamicShapesSpec or corresponding dictionary into a dynamic_shapes input to export(). + """ + import sympy + + from torch.fx.experimental.symbolic_shapes import _is_supported_equivalence + + if from_dict: + if not isinstance(spec, dict): + raise UserError( + UserErrorType.INVALID_INPUT, + f"With from_dict=True, expected `spec` to be a dict, got {type(spec)}", + ) + if sorted(spec.keys()) != ["dims", "dynamic_shapes"]: + raise UserError( + UserErrorType.INVALID_INPUT, + "With from_dict=True, expected `spec` to have keys `dims` and `dynamic_shapes`, " + f"instead found {spec.keys()}", + ) + dims = {} + for k, v in spec["dims"].items(): + if not isinstance(k, str): + raise UserError( + UserErrorType.INVALID_INPUT, + f"Expected `spec['dims']` keys to be strings for symbols, got key {type(k)}", + ) + if sorted(v.keys()) != ["derived", "max", "min"]: + raise UserError( + UserErrorType.INVALID_INPUT, + f"Expected `spec['dims']` values to have keys `derived`, `max`, and `min`, " + f"instead found {v.keys()}", + ) + if not isinstance(v["min"], int): + raise UserError( + UserErrorType.INVALID_INPUT, + f"Expected dims in `spec['dims']` to map `min` to an int, got {k}: {v['min']}", + ) + if not isinstance(v["max"], int) or v["max"] is None: + raise UserError( + UserErrorType.INVALID_INPUT, + f"Expected dims in `spec['dims']` to map `max` to an int or None, got {k}: {v['max']}", + ) + if not isinstance(v["derived"], list) or any( + not isinstance(d, str) for d in v["derived"] + ): + raise UserError( + UserErrorType.INVALID_INPUT, + "Expected dims in `spec['dims']` to map `derived` to a list of derived expressions, " + f"got {k}: {v['derived']}", + ) + dims[k] = RootDim(**v) + dynamic_shapes = spec["dynamic_shapes"] + else: + if not isinstance(spec, DynamicShapesSpec): + raise UserError( + UserErrorType.INVALID_INPUT, + f"Expected `spec` to be a DynamicShapesSpec, got {type(spec)}", + ) + dims = spec.dims + dynamic_shapes = spec.dynamic_shapes + + if dynamic_shapes is None: + return None + + dim_cache = {} + for name, info in dims.items(): + symbol = sympy.sympify(name) + if not isinstance(symbol, sympy.Symbol): + raise UserError( + UserErrorType.INVALID_INPUT, + f"Expected `spec['dims']` keys to be symbols, got {name}", + ) + dim_cache[name] = Dim(name, min=info.min, max=info.max) # cache root dim + for _expr in info.derived: + expr = sympy.sympify(_expr) + if len(expr.free_symbols) != 1 or symbol not in expr.free_symbols: + raise UserError( + UserErrorType.INVALID_INPUT, + f"Expected derived expressions in to have {name} as the only free symbol, got {expr}", + ) + if not _is_supported_equivalence(expr): + raise UserError( + UserErrorType.INVALID_INPUT, + f"Expected derived expressions to be linear expressions, got {expr}", + ) + modulus, remainder = sympy.polys.polytools.div(expr, symbol) + ddim = dim_cache[name] + if modulus != 1: + ddim = int(modulus) * ddim # type: ignore[assignment, operator] + if remainder != 0: + ddim = ddim + int(remainder) # type: ignore[assignment, operator] + dim_cache[_expr] = ddim # cache derived dims + + def deserialize_shape( + val: None | int | str, + ) -> None | int | Dim | _DimHint: + if val is None or isinstance(val, int): + return val + elif val == "_DimHint.AUTO": + return _DimHint.AUTO() + elif val == "_DimHint.DYNAMIC": + return _DimHint.DYNAMIC() + elif val == "_DimHint.STATIC": + return _DimHint.STATIC() + if not isinstance(val, str): + raise UserError( + UserErrorType.INVALID_INPUT, + "Expected leaves in `spec['dynamic_shapes']` to be ints, None, Dim.AUTO/STATIC, symbols, " + f" or derived expressions, got {val}", + ) + if val not in dim_cache: + raise UserError( + UserErrorType.INVALID_INPUT, + "Expected dims in `spec['dynamic_shapes']` to be tracked in `spec['dims']`, " + f"got {val} which is not in {dims.keys()}", + ) + return dim_cache[val] # type: ignore[return-value] + + return tree_map(deserialize_shape, dynamic_shapes) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/export_schema.thrift b/.venv/lib/python3.12/site-packages/torch/_export/serde/export_schema.thrift new file mode 100644 index 0000000000000000000000000000000000000000..5268efc883809b1b70c229e311ff90a5de7f50b5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/serde/export_schema.thrift @@ -0,0 +1,383 @@ +// @generated by update_schema.py +// checksum<> + +namespace py3 torch._export +namespace cpp2 torch._export.schema + +enum ArgumentKind { + UNKNOWN = 0, + POSITIONAL = 1, + KEYWORD = 2, +} + + +enum Layout { + Unknown = 0, + SparseCoo = 1, + SparseCsr = 2, + SparseCsc = 3, + SparseBsr = 4, + SparseBsc = 5, + _mkldnn = 6, + Strided = 7, +} + + +enum MemoryFormat { + Unknown = 0, + ContiguousFormat = 1, + ChannelsLast = 2, + ChannelsLast3d = 3, + PreserveFormat = 4, +} + + +enum ScalarType { + UNKNOWN = 0, + BYTE = 1, + CHAR = 2, + SHORT = 3, + INT = 4, + LONG = 5, + HALF = 6, + FLOAT = 7, + DOUBLE = 8, + COMPLEXHALF = 9, + COMPLEXFLOAT = 10, + COMPLEXDOUBLE = 11, + BOOL = 12, + BFLOAT16 = 13, + UINT16 = 28, + FLOAT8E4M3FN = 29, + FLOAT8E5M2 = 30, + FLOAT8E4M3FNUZ = 31, + FLOAT8E5M2FNUZ = 32, + FLOAT8E8M0FNU = 33, + UINT32 = 34, + UINT64 = 35, +} + + +struct Device { + 10: string type; + 20: optional i64 index; +} + +union SymExprHint { + 10: i64 as_int; + 20: bool as_bool; + 30: double as_float; +} + +struct SymExpr { + 10: string expr_str; + 20: optional SymExprHint hint; +} + +union SymInt { + 10: SymExpr as_expr; + 20: i64 as_int; +} + +union SymFloat { + 10: SymExpr as_expr; + 20: double as_float; +} + +union SymBool { + 10: SymExpr as_expr; + 20: bool as_bool; +} + +struct TensorMeta { + 10: ScalarType dtype; + 20: list sizes; + 30: bool requires_grad; + 40: Device device; + 50: list strides; + 60: SymInt storage_offset; + 70: Layout layout; +} + +union SymIntArgument { + 10: string as_name; + 20: i64 as_int; +} + +union SymFloatArgument { + 10: string as_name; + 20: double as_float; +} + +union SymBoolArgument { + 10: string as_name; + 20: bool as_bool; +} + +struct TensorArgument { + 10: string name; +} + +struct TokenArgument { + 10: string name; +} + +union OptionalTensorArgument { + 20: TensorArgument as_tensor; + 10: bool as_none; +} + +struct GraphArgument { + 10: string name; + 20: Graph graph; +} + +struct CustomObjArgument { + 10: string name; + 20: string class_fqn; +} + +struct ComplexValue { + 10: double real; + 20: double imag; +} + +union Argument { + 10: bool as_none; + 20: TensorArgument as_tensor; + 30: list as_tensors; + 50: i64 as_int; + 70: list as_ints; + 80: double as_float; + 90: list as_floats; + 100: string as_string; + 101: list as_strings; + 110: SymIntArgument as_sym_int; + 120: list as_sym_ints; + 130: ScalarType as_scalar_type; + 140: MemoryFormat as_memory_format; + 150: Layout as_layout; + 160: Device as_device; + 170: bool as_bool; + 180: list as_bools; + 182: SymBoolArgument as_sym_bool; + 184: list as_sym_bools; + 200: GraphArgument as_graph; + 190: list as_optional_tensors; + 210: CustomObjArgument as_custom_obj; + 220: string as_operator; + 230: SymFloatArgument as_sym_float; + 240: list as_sym_floats; + 250: OptionalTensorArgument as_optional_tensor; + 260: ComplexValue as_complex; + 270: list> as_nested_tensors; + 280: list> as_int_lists; + 290: map as_string_to_argument; + 300: list> as_float_lists; +} + +struct NamedArgument { + 10: string name; + 20: Argument arg; + 30: optional ArgumentKind kind; +} + +struct Node { + 10: string target; + 20: list inputs; + 30: list outputs; + 40: map metadata; + 50: optional bool is_hop_single_tensor_return; + 60: optional string name; +} + +struct Graph { + 10: list inputs; + 20: list outputs; + 30: list nodes; + 40: map tensor_values; + 50: map sym_int_values; + 60: map sym_bool_values; + 70: bool is_single_tensor_return; + 80: map custom_obj_values; + 90: map sym_float_values; +} + +struct UserInputSpec { + 10: Argument arg; +} + +union ConstantValue { + 10: bool as_none; + 20: i64 as_int; + 30: double as_float; + 40: string as_string; + 50: bool as_bool; +} + +struct InputToConstantInputSpec { + 10: string name; + 20: ConstantValue value; +} + +struct InputToParameterSpec { + 10: TensorArgument arg; + 20: string parameter_name; +} + +struct InputToBufferSpec { + 10: TensorArgument arg; + 20: string buffer_name; + 30: bool persistent; +} + +struct InputToTensorConstantSpec { + 10: TensorArgument arg; + 20: string tensor_constant_name; +} + +struct InputToCustomObjSpec { + 10: CustomObjArgument arg; + 20: string custom_obj_name; +} + +struct InputTokenSpec { + 10: TokenArgument arg; +} + +union InputSpec { + 10: UserInputSpec user_input; + 20: InputToParameterSpec parameter; + 30: InputToBufferSpec buffer; + 40: InputToTensorConstantSpec tensor_constant; + 50: InputToCustomObjSpec custom_obj; + 70: InputTokenSpec token; + 60: InputToConstantInputSpec constant_input; +} + +struct UserOutputSpec { + 10: Argument arg; +} + +struct LossOutputSpec { + 10: TensorArgument arg; +} + +struct BufferMutationSpec { + 10: TensorArgument arg; + 20: string buffer_name; +} + +struct ParameterMutationSpec { + 10: TensorArgument arg; + 20: string parameter_name; +} + +struct GradientToParameterSpec { + 10: TensorArgument arg; + 20: string parameter_name; +} + +struct GradientToUserInputSpec { + 10: TensorArgument arg; + 20: string user_input_name; +} + +struct UserInputMutationSpec { + 10: TensorArgument arg; + 20: string user_input_name; +} + +struct OutputTokenSpec { + 10: TokenArgument arg; +} + +union OutputSpec { + 10: UserOutputSpec user_output; + 20: LossOutputSpec loss_output; + 30: BufferMutationSpec buffer_mutation; + 40: GradientToParameterSpec gradient_to_parameter; + 50: GradientToUserInputSpec gradient_to_user_input; + 60: UserInputMutationSpec user_input_mutation; + 70: OutputTokenSpec token; + 80: ParameterMutationSpec parameter_mutation; +} + +struct GraphSignature { + 10: list input_specs; + 20: list output_specs; +} + +struct RangeConstraint { + 10: optional i64 min_val; + 20: optional i64 max_val; +} + +struct ModuleCallSignature { + 10: list inputs; + 20: list outputs; + 30: string in_spec; + 40: string out_spec; + 50: optional list forward_arg_names; +} + +struct ModuleCallEntry { + 10: string fqn; + 30: optional ModuleCallSignature signature; +} + +struct NamedTupleDef { + 10: list field_names; +} + +struct GraphModule { + 10: Graph graph; + 50: GraphSignature signature; + 60: list module_call_graph; + 40: map metadata; + 70: map treespec_namedtuple_fields; +} + +struct SchemaVersion { + 10: i64 major; + 20: i64 minor; +} + +struct ExportedProgram { + 10: GraphModule graph_module; + 20: map opset_version; + 30: map range_constraints; + 60: SchemaVersion schema_version; + 70: list verifiers; + 80: string torch_version; + 90: list guards_code; +} + +struct PayloadMeta { + 10: string path_name; + 20: bool is_param; + 30: bool use_pickle; + 40: optional TensorMeta tensor_meta; +} + +struct PayloadConfig { + 10: map config; +} + +struct AOTInductorModelPickleData { + 1: string library_basename; + 2: list input_names; + 3: list output_names; + 4: optional i64 floating_point_input_dtype; + 5: optional i64 floating_point_output_dtype; + 6: optional bool aot_inductor_model_is_cpu; +} + +struct ExternKernelNode { + 10: string name; + 20: Node node; +} + +struct ExternKernelNodes { + 10: list nodes; +} diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/schema.py b/.venv/lib/python3.12/site-packages/torch/_export/serde/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..1715a72511bb2d6140ca2ae3b7972e1d0f6a6ad0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/serde/schema.py @@ -0,0 +1,574 @@ +# NOTE: This is a placeholder for iterating on export serialization schema design. +# Anything is subject to change and no guarantee is provided at this point. + +from dataclasses import dataclass, field +from enum import IntEnum +from typing import Annotated + +from torch._export.serde.union import _Union, _union_dataclass + + +# NOTE: Please update this value if any modifications are made to the schema +SCHEMA_VERSION = (8, 20) +TREESPEC_VERSION = 1 + + +# NOTE: If you updated the schema, please run `scripts/export/update_schema.py` +# to update the auto generated files. +# +# There are also mappings from serialized enum values to c10 enum member names. +# These are used by scripts/export/update_schema.py to generate C++ conversion +# functions for oss_proxy_executor.cpp. +# When adding new enum values, update both the enum AND the mapping. +class ScalarType(IntEnum): + UNKNOWN = 0 + BYTE = 1 + CHAR = 2 + SHORT = 3 + INT = 4 + LONG = 5 + HALF = 6 + FLOAT = 7 + DOUBLE = 8 + COMPLEXHALF = 9 + COMPLEXFLOAT = 10 + COMPLEXDOUBLE = 11 + BOOL = 12 + BFLOAT16 = 13 + UINT16 = 28 + FLOAT8E4M3FN = 29 + FLOAT8E5M2 = 30 + FLOAT8E4M3FNUZ = 31 + FLOAT8E5M2FNUZ = 32 + FLOAT8E8M0FNU = 33 + UINT32 = 34 + UINT64 = 35 + + +class Layout(IntEnum): + Unknown = 0 + SparseCoo = 1 + SparseCsr = 2 + SparseCsc = 3 + SparseBsr = 4 + SparseBsc = 5 + _mkldnn = 6 + Strided = 7 + + +class MemoryFormat(IntEnum): + Unknown = 0 + ContiguousFormat = 1 + ChannelsLast = 2 + ChannelsLast3d = 3 + PreserveFormat = 4 + + +SCALAR_TYPE_TO_C10: dict[int, str] = { + ScalarType.BYTE: "Byte", + ScalarType.CHAR: "Char", + ScalarType.SHORT: "Short", + ScalarType.INT: "Int", + ScalarType.LONG: "Long", + ScalarType.HALF: "Half", + ScalarType.FLOAT: "Float", + ScalarType.DOUBLE: "Double", + ScalarType.COMPLEXHALF: "ComplexHalf", + ScalarType.COMPLEXFLOAT: "ComplexFloat", + ScalarType.COMPLEXDOUBLE: "ComplexDouble", + ScalarType.BOOL: "Bool", + ScalarType.BFLOAT16: "BFloat16", + ScalarType.UINT16: "UInt16", + ScalarType.FLOAT8E4M3FN: "Float8_e4m3fn", + ScalarType.FLOAT8E5M2: "Float8_e5m2", + ScalarType.FLOAT8E4M3FNUZ: "Float8_e4m3fnuz", + ScalarType.FLOAT8E5M2FNUZ: "Float8_e5m2fnuz", + ScalarType.FLOAT8E8M0FNU: "Float8_e8m0fnu", + ScalarType.UINT32: "UInt32", + ScalarType.UINT64: "UInt64", +} + +LAYOUT_TO_C10: dict[int, str] = { + Layout.SparseCoo: "Sparse", + Layout.SparseCsr: "SparseCsr", + Layout.SparseCsc: "SparseCsc", + Layout.SparseBsr: "SparseBsr", + Layout.SparseBsc: "SparseBsc", + Layout._mkldnn: "Mkldnn", + Layout.Strided: "Strided", +} + +MEMORY_FORMAT_TO_C10: dict[int, str] = { + MemoryFormat.ContiguousFormat: "Contiguous", + MemoryFormat.ChannelsLast: "ChannelsLast", + MemoryFormat.ChannelsLast3d: "ChannelsLast3d", + MemoryFormat.PreserveFormat: "Preserve", +} + + +@dataclass +class Device: + type: Annotated[str, 10] + index: Annotated[int | None, 20] = None + + +@_union_dataclass +class SymExprHint(_Union): + as_int: Annotated[int, 10] + as_bool: Annotated[bool, 20] + as_float: Annotated[float, 30] + + +# This is for storing the symbolic expressions behind symints/symfloats/symbools +# For example, we can get something like +# SymExpr(expr_str="s0 + s1", hint=SymExprHint(as_int=4) +# if we also have the hint that s0 and s1 are both 2. +@dataclass +class SymExpr: + expr_str: Annotated[str, 10] + hint: Annotated[SymExprHint | None, 20] = None + + +@_union_dataclass +class SymInt(_Union): + as_expr: Annotated[SymExpr, 10] + as_int: Annotated[int, 20] + + +@_union_dataclass +class SymFloat(_Union): + as_expr: Annotated[SymExpr, 10] + as_float: Annotated[float, 20] + + +@_union_dataclass +class SymBool(_Union): + as_expr: Annotated[SymExpr, 10] + as_bool: Annotated[bool, 20] + + +@dataclass +class TensorMeta: + dtype: Annotated[ScalarType, 10] + sizes: Annotated[list[SymInt], 20] + requires_grad: Annotated[bool, 30] + device: Annotated[Device, 40] + strides: Annotated[list[SymInt], 50] + storage_offset: Annotated[SymInt, 60] + layout: Annotated[Layout, 70] + + +# In most cases we will use the "as_name" field to store arguments which are +# SymInts. +# The "as_int" field is used in the case where we have a list containing a mix +# of SymInt and ints (ex. [1, s0, ...]). We will serialize this type of list to +# be List[SymIntArgument] and map the SymInts to the "as_name" field, and ints +# to the "as_int" field. +@_union_dataclass +class SymIntArgument(_Union): + as_name: Annotated[str, 10] + as_int: Annotated[int, 20] + + +# In most cases we will use the "as_name" field to store arguments which are +# SymFloats. +# The "as_float" field is used in the case where we have a list containing a mix +# of SymFloat and float (ex. [1.0, s0, ...]). We will serialize this type of list to +# be List[SymFloatArgument] and map the SymFloats to the "as_name" field, and ints +# to the "as_float" field. +@_union_dataclass +class SymFloatArgument(_Union): + as_name: Annotated[str, 10] + as_float: Annotated[float, 20] + + +# In most cases we will use the "as_name" field to store arguments which are +# SymBools. +# The "as_bool" field is used in the case where we have a list containing a mix +# of SymBool and bools (ex. [True, i0, ...]). We will serialize this type of list to +# be List[SymBoolArgument] and map the SymBools to the "as_name" field, and bools +# to the "as_bool" field. +@_union_dataclass +class SymBoolArgument(_Union): + as_name: Annotated[str, 10] + as_bool: Annotated[bool, 20] + + +@dataclass +class TensorArgument: + name: Annotated[str, 10] + + +@dataclass +class TokenArgument: + name: Annotated[str, 10] + + +# This is use for storing the contents of a list which contain optional tensors +# (Tensor?[], ex. [Tensor, None, ...]), where the list will be serialized to the +# type List[OptionalTensorArgument], with tensor values serialized to the +# "as_tensor" field, and None values serialized to the "as_none" field. +@_union_dataclass +class OptionalTensorArgument(_Union): + as_tensor: Annotated[TensorArgument, 20] + as_none: Annotated[bool, 10] + + +@dataclass +class GraphArgument: + name: Annotated[str, 10] + graph: Annotated["Graph", 20] + + +@dataclass +class CustomObjArgument: + name: Annotated[str, 10] + class_fqn: Annotated[str, 20] + + +@dataclass +class ComplexValue: + real: Annotated[float, 10] + imag: Annotated[float, 20] + + +# This is actually a union type +@_union_dataclass +class Argument(_Union): + as_none: Annotated[bool, 10] + as_tensor: Annotated[TensorArgument, 20] + as_tensors: Annotated[list[TensorArgument], 30] + as_int: Annotated[int, 50] + as_ints: Annotated[list[int], 70] + as_float: Annotated[float, 80] + as_floats: Annotated[list[float], 90] + as_string: Annotated[str, 100] + as_strings: Annotated[list[str], 101] + as_sym_int: Annotated[SymIntArgument, 110] + as_sym_ints: Annotated[list[SymIntArgument], 120] + as_scalar_type: Annotated[ScalarType, 130] + as_memory_format: Annotated[MemoryFormat, 140] + as_layout: Annotated[Layout, 150] + as_device: Annotated[Device, 160] + as_bool: Annotated[bool, 170] + as_bools: Annotated[list[bool], 180] + as_sym_bool: Annotated[SymBoolArgument, 182] + as_sym_bools: Annotated[list[SymBoolArgument], 184] + as_graph: Annotated[GraphArgument, 200] + as_optional_tensors: Annotated[list[OptionalTensorArgument], 190] + as_custom_obj: Annotated[CustomObjArgument, 210] + as_operator: Annotated[str, 220] + as_sym_float: Annotated[SymFloatArgument, 230] + as_sym_floats: Annotated[list[SymFloatArgument], 240] + as_optional_tensor: Annotated[OptionalTensorArgument, 250] + as_complex: Annotated[ComplexValue, 260] + as_nested_tensors: Annotated[list[list[TensorArgument]], 270] + as_int_lists: Annotated[list[list[int]], 280] + as_string_to_argument: Annotated[dict[str, "Argument"], 290] + as_float_lists: Annotated[list[list[float]], 300] + + +class ArgumentKind(IntEnum): + UNKNOWN = 0 + POSITIONAL = 1 + KEYWORD = 2 + + +@dataclass +class NamedArgument: + # Argument name from the operator schema + name: Annotated[str, 10] + arg: Annotated[Argument, 20] + kind: Annotated[ArgumentKind | None, 30] = None + + +@dataclass +class Node: + target: Annotated[str, 10] + inputs: Annotated[list[NamedArgument], 20] + outputs: Annotated[list[Argument], 30] + metadata: Annotated[dict[str, str], 40] + is_hop_single_tensor_return: Annotated[bool | None, 50] = None + # For BC, default is None so older serialized models without 'name' can be loaded. + name: Annotated[str | None, 60] = None + + +@dataclass +class Graph: + inputs: Annotated[list[Argument], 10] + outputs: Annotated[list[Argument], 20] + nodes: Annotated[list[Node], 30] + tensor_values: Annotated[dict[str, TensorMeta], 40] + sym_int_values: Annotated[dict[str, SymInt], 50] + sym_bool_values: Annotated[dict[str, SymBool], 60] + # This is for deserializing the submodule graphs from higher order ops + # (ex. cond, map) where single tensor returns will just return a single + # tensor, rather than following export schema and returning a singleton + # list. + is_single_tensor_return: Annotated[bool, 70] = False + custom_obj_values: Annotated[dict[str, CustomObjArgument], 80] = field( + default_factory=dict + ) + sym_float_values: Annotated[dict[str, SymFloat], 90] = field(default_factory=dict) + + +@dataclass +class UserInputSpec: + # Actually, only tensors and SymInts are allowed here + arg: Annotated[Argument, 10] + + +@_union_dataclass +class ConstantValue(_Union): + as_none: Annotated[bool, 10] + as_int: Annotated[int, 20] + as_float: Annotated[float, 30] + as_string: Annotated[str, 40] + as_bool: Annotated[bool, 50] + + +@dataclass +class InputToConstantInputSpec: + name: Annotated[str, 10] + value: Annotated[ConstantValue, 20] + + +@dataclass +class InputToParameterSpec: + arg: Annotated[TensorArgument, 10] + parameter_name: Annotated[str, 20] + + +@dataclass +class InputToBufferSpec: + arg: Annotated[TensorArgument, 10] + buffer_name: Annotated[str, 20] + persistent: Annotated[bool, 30] + + +@dataclass +class InputToTensorConstantSpec: + arg: Annotated[TensorArgument, 10] + tensor_constant_name: Annotated[str, 20] + + +@dataclass +class InputToCustomObjSpec: + arg: Annotated[CustomObjArgument, 10] + custom_obj_name: Annotated[str, 20] + + +@dataclass +class InputTokenSpec: + arg: Annotated[TokenArgument, 10] + + +@_union_dataclass +class InputSpec(_Union): + user_input: Annotated[UserInputSpec, 10] + parameter: Annotated[InputToParameterSpec, 20] + buffer: Annotated[InputToBufferSpec, 30] + tensor_constant: Annotated[InputToTensorConstantSpec, 40] + custom_obj: Annotated[InputToCustomObjSpec, 50] + token: Annotated[InputTokenSpec, 70] + constant_input: Annotated[InputToConstantInputSpec, 60] + + +@dataclass +class UserOutputSpec: + arg: Annotated[Argument, 10] + + +@dataclass +class LossOutputSpec: + arg: Annotated[TensorArgument, 10] + + +@dataclass +class BufferMutationSpec: + arg: Annotated[TensorArgument, 10] + buffer_name: Annotated[str, 20] + + +@dataclass +class ParameterMutationSpec: + arg: Annotated[TensorArgument, 10] + parameter_name: Annotated[str, 20] + + +@dataclass +class GradientToParameterSpec: + arg: Annotated[TensorArgument, 10] + parameter_name: Annotated[str, 20] + + +@dataclass +class GradientToUserInputSpec: + arg: Annotated[TensorArgument, 10] + user_input_name: Annotated[str, 20] + + +@dataclass +class UserInputMutationSpec: + arg: Annotated[TensorArgument, 10] + user_input_name: Annotated[str, 20] + + +@dataclass +class OutputTokenSpec: + arg: Annotated[TokenArgument, 10] + + +@_union_dataclass +class OutputSpec(_Union): + user_output: Annotated[UserOutputSpec, 10] + loss_output: Annotated[LossOutputSpec, 20] + buffer_mutation: Annotated[BufferMutationSpec, 30] + gradient_to_parameter: Annotated[GradientToParameterSpec, 40] + gradient_to_user_input: Annotated[GradientToUserInputSpec, 50] + user_input_mutation: Annotated[UserInputMutationSpec, 60] + token: Annotated[OutputTokenSpec, 70] + parameter_mutation: Annotated[ParameterMutationSpec, 80] + + +@dataclass +class GraphSignature: + input_specs: Annotated[list[InputSpec], 10] + output_specs: Annotated[list[OutputSpec], 20] + + +@dataclass +class RangeConstraint: + min_val: Annotated[int | None, 10] + max_val: Annotated[int | None, 20] + + +@dataclass +class ModuleCallSignature: + inputs: Annotated[list[Argument], 10] + outputs: Annotated[list[Argument], 20] + + # These are serialized by calling pytree.treespec_loads + # And deserialized by calling pytree.treespec_dumps + in_spec: Annotated[str, 30] + out_spec: Annotated[str, 40] + + # This field is used to prettify the graph placeholders + # after we Ser/Der and retrace + forward_arg_names: Annotated[list[str] | None, 50] = None + + +@dataclass +class ModuleCallEntry: + fqn: Annotated[str, 10] + signature: Annotated[ModuleCallSignature | None, 30] = None + + +@dataclass +class NamedTupleDef: + field_names: Annotated[list[str], 10] + + +@dataclass +class GraphModule: + graph: Annotated[Graph, 10] + signature: Annotated[GraphSignature, 50] + # This is used for unflattening, by tracking the calling structure of all of + # the modules in order to unflatten the modules back to the eager calling + # conventions. + module_call_graph: Annotated[list[ModuleCallEntry], 60] + metadata: Annotated[dict[str, str], 40] = field(default_factory=dict) + # Mapping of namedtuple types to namedtuple field names, used for BC + treespec_namedtuple_fields: Annotated[dict[str, NamedTupleDef], 70] = field( + default_factory=dict + ) + + +# Invariant: Every time a change is made to the schema, one of the versions +# should be updated. +@dataclass +class SchemaVersion: + major: Annotated[ + int, 10 + ] # Major version number is bumped every time a breaking change is made. + minor: Annotated[ + int, 20 + ] # Minor version number is bumped when a compatible change is made. + + +@dataclass +class ExportedProgram: + graph_module: Annotated[GraphModule, 10] + # Key is the opset namespace (ex. aten), and value is the version number + opset_version: Annotated[dict[str, int], 20] + range_constraints: Annotated[dict[str, RangeConstraint], 30] + schema_version: Annotated[SchemaVersion, 60] + verifiers: Annotated[list[str], 70] = field(default_factory=list) + torch_version: Annotated[str, 80] = "<=2.4" + guards_code: Annotated[list[str], 90] = field(default_factory=list) + + +######################################################################### +# Container types for inference tasks, not being used directly for export. +######################################################################### + + +# The metadata for payload saved in PT2 archive. +# payload includes params, buffers, tensor constants, and custom objects. +@dataclass +class PayloadMeta: + # the path of the payload in the archive file, e.g. "weight_0" + path_name: Annotated[str, 10] + is_param: Annotated[bool, 20] + # whether the payload is serialized using pickle. + # Only custom objects and tensor subclasses that are not fake tensors + # are serialized using pickle. + use_pickle: Annotated[bool, 30] + # Custom Objects don't have tensor_meta and will be serialized using pickle + tensor_meta: Annotated[TensorMeta | None, 40] + + +# The mapping from payload FQN to its metadata. +@dataclass +class PayloadConfig: + config: Annotated[dict[str, PayloadMeta], 10] + + +# +# The structure is used to serialize instances of AOTInductorModel to pass +# them from the publishing pipeline to the predictor. +# +# All new fields should be marked as optional. +# +@dataclass +class AOTInductorModelPickleData: + # Base name of an associated .so AOTInductor library. Typically looks like: + # "abc.so". + library_basename: Annotated[str, 1] + + # AOTInductor engine input names. + input_names: Annotated[list[str], 2] + + # AOTInductor engine output names. + output_names: Annotated[list[str], 3] + + # These fields tell whether floating point inputs/outputs should be converted to + # a certain type. If None, the dtypes that the AOTInductor engine inferred from the sample + # inputs are used. + floating_point_input_dtype: Annotated[int | None, 4] = None + floating_point_output_dtype: Annotated[int | None, 5] = None + + # Whether AOTInductor runtime is for CPU. + aot_inductor_model_is_cpu: Annotated[bool | None, 6] = None + + +@dataclass +class ExternKernelNode: + # name is not the unique identifier of the node + name: Annotated[str, 10] + node: Annotated[Node, 20] + + +@dataclass +class ExternKernelNodes: + nodes: Annotated[list[ExternKernelNode], 10] diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/schema.yaml b/.venv/lib/python3.12/site-packages/torch/_export/serde/schema.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3b9c4d3051a8779f77627b3e187c57e31fbf58be --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/serde/schema.yaml @@ -0,0 +1,569 @@ +# @generated by update_schema.py +# checksum<> +AOTInductorModelPickleData: + kind: struct + fields: + library_basename: + type: str + input_names: + type: List[str] + output_names: + type: List[str] + floating_point_input_dtype: + type: Optional[int] + default: None + floating_point_output_dtype: + type: Optional[int] + default: None + aot_inductor_model_is_cpu: + type: Optional[bool] + default: None +Argument: + kind: union + fields: + as_none: + type: bool + as_tensor: + type: TensorArgument + as_tensors: + type: List[TensorArgument] + as_int: + type: int + as_ints: + type: List[int] + as_float: + type: float + as_floats: + type: List[float] + as_string: + type: str + as_strings: + type: List[str] + as_sym_int: + type: SymIntArgument + as_sym_ints: + type: List[SymIntArgument] + as_scalar_type: + type: ScalarType + as_memory_format: + type: MemoryFormat + as_layout: + type: Layout + as_device: + type: Device + as_bool: + type: bool + as_bools: + type: List[bool] + as_sym_bool: + type: SymBoolArgument + as_sym_bools: + type: List[SymBoolArgument] + as_graph: + type: GraphArgument + as_optional_tensors: + type: List[OptionalTensorArgument] + as_custom_obj: + type: CustomObjArgument + as_operator: + type: str + as_sym_float: + type: SymFloatArgument + as_sym_floats: + type: List[SymFloatArgument] + as_optional_tensor: + type: OptionalTensorArgument + as_complex: + type: ComplexValue + as_nested_tensors: + type: List[List[TensorArgument]] + as_int_lists: + type: List[List[int]] + as_string_to_argument: + type: Dict[str, Argument] + as_float_lists: + type: List[List[float]] +ArgumentKind: + kind: enum + fields: + UNKNOWN: 0 + POSITIONAL: 1 + KEYWORD: 2 +BufferMutationSpec: + kind: struct + fields: + arg: + type: TensorArgument + buffer_name: + type: str +ComplexValue: + kind: struct + fields: + real: + type: float + imag: + type: float +ConstantValue: + kind: union + fields: + as_none: + type: bool + as_int: + type: int + as_float: + type: float + as_string: + type: str + as_bool: + type: bool +CustomObjArgument: + kind: struct + fields: + name: + type: str + class_fqn: + type: str +Device: + kind: struct + fields: + type: + type: str + index: + type: Optional[int] + default: None +ExportedProgram: + kind: struct + fields: + graph_module: + type: GraphModule + opset_version: + type: Dict[str, int] + range_constraints: + type: Dict[str, RangeConstraint] + schema_version: + type: SchemaVersion + verifiers: + type: List[str] + default: '[]' + torch_version: + type: str + default: <=2.4 + guards_code: + type: List[str] + default: '[]' +ExternKernelNode: + kind: struct + fields: + name: + type: str + node: + type: Node +ExternKernelNodes: + kind: struct + fields: + nodes: + type: List[ExternKernelNode] +GradientToParameterSpec: + kind: struct + fields: + arg: + type: TensorArgument + parameter_name: + type: str +GradientToUserInputSpec: + kind: struct + fields: + arg: + type: TensorArgument + user_input_name: + type: str +Graph: + kind: struct + fields: + inputs: + type: List[Argument] + outputs: + type: List[Argument] + nodes: + type: List[Node] + tensor_values: + type: Dict[str, TensorMeta] + sym_int_values: + type: Dict[str, SymInt] + sym_bool_values: + type: Dict[str, SymBool] + is_single_tensor_return: + type: bool + default: 'False' + custom_obj_values: + type: Dict[str, CustomObjArgument] + default: '{}' + sym_float_values: + type: Dict[str, SymFloat] + default: '{}' +GraphArgument: + kind: struct + fields: + name: + type: str + graph: + type: Graph +GraphModule: + kind: struct + fields: + graph: + type: Graph + signature: + type: GraphSignature + module_call_graph: + type: List[ModuleCallEntry] + metadata: + type: Dict[str, str] + default: '{}' + treespec_namedtuple_fields: + type: Dict[str, NamedTupleDef] + default: '{}' +GraphSignature: + kind: struct + fields: + input_specs: + type: List[InputSpec] + output_specs: + type: List[OutputSpec] +InputSpec: + kind: union + fields: + user_input: + type: UserInputSpec + parameter: + type: InputToParameterSpec + buffer: + type: InputToBufferSpec + tensor_constant: + type: InputToTensorConstantSpec + custom_obj: + type: InputToCustomObjSpec + token: + type: InputTokenSpec + constant_input: + type: InputToConstantInputSpec +InputToBufferSpec: + kind: struct + fields: + arg: + type: TensorArgument + buffer_name: + type: str + persistent: + type: bool +InputToConstantInputSpec: + kind: struct + fields: + name: + type: str + value: + type: ConstantValue +InputToCustomObjSpec: + kind: struct + fields: + arg: + type: CustomObjArgument + custom_obj_name: + type: str +InputToParameterSpec: + kind: struct + fields: + arg: + type: TensorArgument + parameter_name: + type: str +InputToTensorConstantSpec: + kind: struct + fields: + arg: + type: TensorArgument + tensor_constant_name: + type: str +InputTokenSpec: + kind: struct + fields: + arg: + type: TokenArgument +Layout: + kind: enum + fields: + Unknown: 0 + SparseCoo: 1 + SparseCsr: 2 + SparseCsc: 3 + SparseBsr: 4 + SparseBsc: 5 + _mkldnn: 6 + Strided: 7 +LossOutputSpec: + kind: struct + fields: + arg: + type: TensorArgument +MemoryFormat: + kind: enum + fields: + Unknown: 0 + ContiguousFormat: 1 + ChannelsLast: 2 + ChannelsLast3d: 3 + PreserveFormat: 4 +ModuleCallEntry: + kind: struct + fields: + fqn: + type: str + signature: + type: Optional[ModuleCallSignature] + default: None +ModuleCallSignature: + kind: struct + fields: + inputs: + type: List[Argument] + outputs: + type: List[Argument] + in_spec: + type: str + out_spec: + type: str + forward_arg_names: + type: Optional[List[str]] + default: None +NamedArgument: + kind: struct + fields: + name: + type: str + arg: + type: Argument + kind: + type: Optional[ArgumentKind] + default: None +NamedTupleDef: + kind: struct + fields: + field_names: + type: List[str] +Node: + kind: struct + fields: + target: + type: str + inputs: + type: List[NamedArgument] + outputs: + type: List[Argument] + metadata: + type: Dict[str, str] + is_hop_single_tensor_return: + type: Optional[bool] + default: None + name: + type: Optional[str] + default: None +OptionalTensorArgument: + kind: union + fields: + as_tensor: + type: TensorArgument + as_none: + type: bool +OutputSpec: + kind: union + fields: + user_output: + type: UserOutputSpec + loss_output: + type: LossOutputSpec + buffer_mutation: + type: BufferMutationSpec + gradient_to_parameter: + type: GradientToParameterSpec + gradient_to_user_input: + type: GradientToUserInputSpec + user_input_mutation: + type: UserInputMutationSpec + token: + type: OutputTokenSpec + parameter_mutation: + type: ParameterMutationSpec +OutputTokenSpec: + kind: struct + fields: + arg: + type: TokenArgument +ParameterMutationSpec: + kind: struct + fields: + arg: + type: TensorArgument + parameter_name: + type: str +PayloadConfig: + kind: struct + fields: + config: + type: Dict[str, PayloadMeta] +PayloadMeta: + kind: struct + fields: + path_name: + type: str + is_param: + type: bool + use_pickle: + type: bool + tensor_meta: + type: Optional[TensorMeta] +RangeConstraint: + kind: struct + fields: + min_val: + type: Optional[int] + max_val: + type: Optional[int] +ScalarType: + kind: enum + fields: + UNKNOWN: 0 + BYTE: 1 + CHAR: 2 + SHORT: 3 + INT: 4 + LONG: 5 + HALF: 6 + FLOAT: 7 + DOUBLE: 8 + COMPLEXHALF: 9 + COMPLEXFLOAT: 10 + COMPLEXDOUBLE: 11 + BOOL: 12 + BFLOAT16: 13 + UINT16: 28 + FLOAT8E4M3FN: 29 + FLOAT8E5M2: 30 + FLOAT8E4M3FNUZ: 31 + FLOAT8E5M2FNUZ: 32 + FLOAT8E8M0FNU: 33 + UINT32: 34 + UINT64: 35 +SchemaVersion: + kind: struct + fields: + major: + type: int + minor: + type: int +SymBool: + kind: union + fields: + as_expr: + type: SymExpr + as_bool: + type: bool +SymBoolArgument: + kind: union + fields: + as_name: + type: str + as_bool: + type: bool +SymExpr: + kind: struct + fields: + expr_str: + type: str + hint: + type: Optional[SymExprHint] + default: None +SymExprHint: + kind: union + fields: + as_int: + type: int + as_bool: + type: bool + as_float: + type: float +SymFloat: + kind: union + fields: + as_expr: + type: SymExpr + as_float: + type: float +SymFloatArgument: + kind: union + fields: + as_name: + type: str + as_float: + type: float +SymInt: + kind: union + fields: + as_expr: + type: SymExpr + as_int: + type: int +SymIntArgument: + kind: union + fields: + as_name: + type: str + as_int: + type: int +TensorArgument: + kind: struct + fields: + name: + type: str +TensorMeta: + kind: struct + fields: + dtype: + type: ScalarType + sizes: + type: List[SymInt] + requires_grad: + type: bool + device: + type: Device + strides: + type: List[SymInt] + storage_offset: + type: SymInt + layout: + type: Layout +TokenArgument: + kind: struct + fields: + name: + type: str +UserInputMutationSpec: + kind: struct + fields: + arg: + type: TensorArgument + user_input_name: + type: str +UserInputSpec: + kind: struct + fields: + arg: + type: Argument +UserOutputSpec: + kind: struct + fields: + arg: + type: Argument +SCHEMA_VERSION: +- 8 +- 20 +TREESPEC_VERSION: 1 diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/schema_check.py b/.venv/lib/python3.12/site-packages/torch/_export/serde/schema_check.py new file mode 100644 index 0000000000000000000000000000000000000000..2b9d94b876f1873549c1a7699ed9e59a3ddd2573 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/serde/schema_check.py @@ -0,0 +1,927 @@ +import dataclasses +import hashlib +import inspect +import re +import types +import typing +from enum import IntEnum +from typing import Annotated, Any, ForwardRef, Union + +from torch._export.serde import schema +from torch._export.serde.union import _Union + + +class SchemaUpdateError(Exception): + pass + + +def _check(x: object, msg: str) -> None: + if not x: + raise SchemaUpdateError(msg) + + +_CPP_TYPE_MAP = { + str: "std::string", + int: "int64_t", + float: "F64", + bool: "bool", +} + +_THRIFT_TYPE_MAP = { + str: "string", + int: "i64", + float: "double", + bool: "bool", +} + + +def _staged_schema() -> tuple[dict[str, Any], str, str]: + yaml_ret: dict[str, Any] = {} + defs: dict[str, Any] = {} + cpp_enum_defs: dict[str, str] = {} + cpp_class_defs: dict[str, str] = {} + cpp_type_decls: list[str] = [] + cpp_json_defs: list[str] = [] + thrift_enum_defs: list[str] = [] + thrift_type_defs: dict[str, str] = {} + + def _handle_aggregate( + ty: type[Any], + ) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]: + def dump_type(t: Any, level: int) -> tuple[str, str, str]: + if getattr(t, "__name__", None) in cpp_enum_defs: + return t.__name__, "int64_t", t.__name__ + elif t in _CPP_TYPE_MAP: + return (t.__name__, _CPP_TYPE_MAP[t], _THRIFT_TYPE_MAP[t]) + elif isinstance(t, str): + if t not in defs: + raise AssertionError(f"type {t} not in defs") + if t in cpp_enum_defs: + raise AssertionError(f"type {t} unexpectedly in cpp_enum_defs") + if "[" in t: + raise AssertionError(f"type {t} contains '[' which is not allowed") + return t, f"ForwardRef<{t}>", t + elif isinstance(t, ForwardRef): + return ( + t.__forward_arg__, + f"ForwardRef<{t.__forward_arg__}>", + t.__forward_arg__, + ) + elif o := typing.get_origin(t): + # Lemme know if there's a better way to do this. + if o is list: + yaml_head, cpp_head, thrift_head, thrift_tail = ( + "List", + "std::vector", + "list<", + ">", + ) + elif o is dict: + yaml_head, cpp_head, thrift_head, thrift_tail = ( + "Dict", + "std::unordered_map", + "map<", + ">", + ) + elif o is Union or o is types.UnionType: + if level != 0: + raise AssertionError( + f"Optional is only supported at the top level, got level={level}" + ) + args = typing.get_args(t) + if len(args) != 2 or args[1] is not type(None): + raise AssertionError( + f"expected Optional type with 2 args ending in None, got {args}" + ) + yaml_type, cpp_type, thrift_type = dump_type(args[0], level + 1) + return ( + f"Optional[{yaml_type}]", + f"std::optional<{cpp_type}>", + f"optional {thrift_type}", + ) + elif o is Annotated: + return dump_type(t.__origin__, level) + else: + raise AssertionError(f"Type {t} is not supported in export schema.") + yaml_arg_types, cpp_arg_types, thrift_arg_types = zip( + *[dump_type(x, level + 1) for x in typing.get_args(t)] + ) + return ( + (f"{yaml_head}[{', '.join(yaml_arg_types)}]"), + (f"{cpp_head}<{', '.join(cpp_arg_types)}>"), + f"{thrift_head}{', '.join(thrift_arg_types)}{thrift_tail}", + ) + elif isinstance(t, type): + return (t.__name__, t.__name__, t.__name__) + else: + raise AssertionError(f"Type {t} is not supported in export schema.") + + def dump_cpp_value(v: object) -> str: + if v is None: + return "std::nullopt" + elif v is True: + return "true" + elif v is False: + return "false" + elif v == {}: + return "{}" + elif v == []: + return "{}" + elif v == (): + return "{}" + elif isinstance(v, str): + return f'"{v}"' + else: + raise AssertionError( + f"Default value {v} is not supported yet in export schema." + ) + + def dump_field( + f: dataclasses.Field[Any], + ) -> tuple[dict[str, Any], str, str | None, str, int]: + t, cpp_type, thrift_type = dump_type(f.type, 0) + ret = {"type": t} + cpp_default: str | None = None + if typing.get_origin(f.type) is not Annotated: + raise AssertionError( + f"Field {f.name} must be annotated with an integer id." + ) + # pyrefly: ignore[missing-attribute] # TODO f.type is an Annotated alias at runtime, not str + thrift_id = f.type.__metadata__[0] + if type(thrift_id) is not int: + raise AssertionError( + f"Field {f.name} must be annotated with an integer id, got {type(thrift_id)}" + ) + + value = dataclasses.MISSING + if f.default is not dataclasses.MISSING: + value = f.default + elif f.default_factory is not dataclasses.MISSING: + value = f.default_factory() + + if value is not dataclasses.MISSING: + default = str(value) + ret["default"] = default + cpp_default = dump_cpp_value(value) + + if t.startswith("Optional[") and value is not None: + raise AssertionError( + f"Optional field {ty.__name__}.{f.name} must have default value to be None." + ) + + # Skip emitting "= {}" for non-primitive types whose + # default-construction already yields the same empty value + # (containers, strings, classes). Emitting it would trigger + # readability-redundant-member-init. Keep it for primitives + # (int64_t, bool, F64) which require explicit value-init. + if cpp_default == "{}" and cpp_type not in ("int64_t", "bool", "F64"): + cpp_default = None + elif cpp_type in ("int64_t", "bool", "F64"): + # Value-initialize primitive/enum members (enums map to int64_t) + # to satisfy cppcoreguidelines-pro-type-member-init. Non-primitive + # types (std::string, containers, classes) default-construct + # themselves; emitting "= {}" for those would trigger + # readability-redundant-member-init. + cpp_default = "{}" + + return ret, cpp_type, cpp_default, thrift_type, thrift_id + + yaml_ret = {} + cpp_ret = {} + thrift_ret = {} + thrift_ids = set() + for f in dataclasses.fields(ty): + yaml_res, cpp_type, cpp_default, thrift_type, thrift_id = dump_field(f) + yaml_ret[f.name] = yaml_res + cpp_ret[f.name] = {"cpp_type": cpp_type, "cpp_default": cpp_default} + thrift_ret[f.name] = {"thrift_type": thrift_type, "thrift_id": thrift_id} + if thrift_id in thrift_ids: + raise AssertionError( + f"Duplicate thrift id {thrift_id} for field {f.name} in {ty.__name__}." + ) + thrift_ids.add(thrift_id) + return yaml_ret, cpp_ret, thrift_ret + + def _handle_int_enum(name: str, ty: type[IntEnum]) -> None: + yaml_ret[name] = {"kind": "enum", "fields": {x.name: x.value for x in ty}} + cpp_enum_defs[name] = f""" +enum class {name} {{ +{chr(10).join([f" {x.name} = {x.value}," for x in ty])} +}}; + +inline std::string_view printEnum(const {name}& e) {{ + switch (e) {{ +{chr(10).join([f" case {name}::{x.name}: return {chr(34)}{x.name}{chr(34)};" for x in ty])} + default: + throw std::runtime_error("Unknown enum value"); + }} +}} + +inline void parseEnum(std::string_view s, {name}& t) {{ +{chr(10).join([f" if (s == {chr(34)}{x.name}{chr(34)}) {{ t = {name}::{x.name}; return; }}" for x in ty])} + throw std::runtime_error("Unknown enum value: " + std::string{{s}}); +}} +""" + thrift_enum_defs.append( + f""" +enum {name} {{ +{chr(10).join([f" {x.name} = {x.value}," for x in ty])} +}} +""" + ) + + def _handle_struct(name: str, ty: type[Any]) -> None: + fields, cpp_fields, thrift_fields = _handle_aggregate(ty) + yaml_ret[name] = {"kind": "struct", "fields": fields} + field_decls = "\n".join( + f" {f['cpp_type']} {name}{' = ' + f['cpp_default'] if f['cpp_default'] is not None else ''};" + for name, f in cpp_fields.items() + ) + + def accessor(name: str, ty: str) -> str: + type_name = fields[name]["type"] + if type_name in cpp_enum_defs: + return f""" + {type_name} get_{name}() const {{ + return static_cast<{type_name}>({name}); + }} + + void set_{name}({type_name} def) {{ + {name} = static_cast(def); + }} +""" + return f""" + const {ty}& get_{name}() const {{ + return {name}; + }} + + template + void set_{name}(U&& def) {{ + {name} = std::forward(def); + }} +""" + + to_json_decl = f"void to_json(nlohmann::json& nlohmann_json_j, const {name}& nlohmann_json_t)" + to_json_def = f"""{{ +{chr(10).join([f' nlohmann_json_j["{name}"] = nlohmann_json_t.{name};' for name in cpp_fields])} +}} +""" + from_json_decl = f"void from_json(const nlohmann::json& nlohmann_json_j, {name}& nlohmann_json_t)" + + from_json_def = f"""{{ + {name} nlohmann_json_default_obj; +{ + chr(10).join( + [ + f' nlohmann_json_t.{name} = nlohmann_json_j.value("{name}", nlohmann_json_default_obj.{name});' + for name in cpp_fields + ] + ) + } +}} +""" + cpp_class_defs[name] = f""" +class {name} {{ + private: +{field_decls} + + public: +{"".join([accessor(name, f["cpp_type"]) for name, f in cpp_fields.items()])} + friend {to_json_decl}; + friend {from_json_decl}; +}}; +""" + cpp_json_defs.append(f"inline {to_json_decl} {to_json_def}") + cpp_json_defs.append(f"inline {from_json_decl} {from_json_def}") + cpp_type_decls.append(f"class {name};") + + thrift_type_defs[name] = f""" +struct {name} {{ +{chr(10).join(f" {f['thrift_id']}: {f['thrift_type']} {n};" for n, f in thrift_fields.items())} +}}""" + + def _handle_union(name: str, ty: type[Any]) -> None: + fields, cpp_fields, thrift_fields = _handle_aggregate(ty) + yaml_ret[name] = {"kind": "union", "fields": fields} + + def accessor(name: str, ty: str, idx: int) -> str: + return f""" + const {ty}& get_{name}() const {{ + return std::get<{idx + 1}>(variant_); + }} + + template + void set_{name}(U&& def) {{ + variant_.emplace<{idx + 1}>(std::forward(def)); + tag_ = Tag::{name.upper()}; + }} +""" + + to_json_branches = "".join( + [ + f""" + if (nlohmann_json_t.tag_ == Tag::{name.upper()}) {{ + nlohmann_json_j["{name}"] = nlohmann_json_t.get_{name}(); + return; + }}""" + for idx, (name, f) in enumerate(cpp_fields.items()) + ] + ) + from_json_branches = "".join( + [ + f""" + if (nlohmann_json_j.contains("{name}")) {{ + nlohmann_json_t.variant_.emplace<{idx + 1}>(nlohmann_json_j.at("{name}").template get<{f["cpp_type"]}>()); + nlohmann_json_t.tag_ = Tag::{name.upper()}; + return; + }}""" + for idx, (name, f) in enumerate(cpp_fields.items()) + ] + ) + + cpp_class_defs[name] = f""" +class {name} {{ + struct Void {{}}; + + public: + enum class Tag {{ + {", ".join([name.upper() for name in cpp_fields])} + }}; + + private: + std::variant variant_; + Tag tag_{{}}; + + public: + Tag tag() const {{ + return tag_; + }} +{"".join([accessor(name, f["cpp_type"], idx) for idx, (name, f) in enumerate(cpp_fields.items())])} + friend void to_json(nlohmann::json& nlohmann_json_j, const {name}& nlohmann_json_t) {{ +{to_json_branches} + }} + + friend void from_json(const nlohmann::json& nlohmann_json_j, {name}& nlohmann_json_t) {{ +{from_json_branches} + }} +}}; + +inline std::string_view printEnum(const {name}::Tag& e) {{ + switch (e) {{ +{chr(10).join([f" case {name}::Tag::{x.upper()}: return {chr(34)}{x.upper()}{chr(34)};" for x in cpp_fields])} + default: + throw std::runtime_error("Unknown enum value"); + }} +}} + +inline void parseEnum(std::string_view s, {name}::Tag& t) {{ +{chr(10).join([f" if (s == {chr(34)}{x.upper()}{chr(34)}) {{ t = {name}::Tag::{x.upper()}; return; }}" for x in cpp_fields])} + throw std::runtime_error("Unknown enum value: " + std::string{{s}}); +}} + +""" + cpp_type_decls.append(f"class {name};") + + thrift_type_defs[name] = f""" +union {name} {{ +{chr(10).join(f" {f['thrift_id']}: {f['thrift_type']} {n};" for n, f in thrift_fields.items())} +}}""" + + for name in dir(schema): + if name.startswith("_"): + continue + + value = getattr(schema, name) + + if hasattr(value, "__module__") and value.__module__ != schema.__name__: + continue + + defs[name] = value + + class_ordering = {} + for name, value in defs.items(): + if isinstance(value, type): + if issubclass(value, IntEnum): + _handle_int_enum(name, value) + elif dataclasses.is_dataclass(value): + class_ordering[name] = inspect.findsource(value)[1] + if issubclass(value, _Union): + _handle_union(name, value) + else: + _handle_struct(name, value) + else: + raise AssertionError(f"Unknown schema type {name}: {value}") + elif isinstance(value, (int, tuple)): + if name not in ("SCHEMA_VERSION", "TREESPEC_VERSION"): + raise AssertionError( + f"expected SCHEMA_VERSION or TREESPEC_VERSION, got {name}" + ) + elif isinstance(value, dict): + # Skip mapping dictionaries used for codegen + pass + else: + raise AssertionError(f"Unknown variable {name}: {value}") + + yaml_ret["SCHEMA_VERSION"] = list(defs["SCHEMA_VERSION"]) + if not all(x > 0 for x in yaml_ret["SCHEMA_VERSION"]): + raise AssertionError( + f"all SCHEMA_VERSION values must be > 0, got {yaml_ret['SCHEMA_VERSION']}" + ) + yaml_ret["TREESPEC_VERSION"] = defs["TREESPEC_VERSION"] + if yaml_ret["TREESPEC_VERSION"] <= 0: + raise AssertionError( + f"TREESPEC_VERSION must be > 0, got {yaml_ret['TREESPEC_VERSION']}" + ) + + cpp_header = f""" +#pragma once + +#include +#include +#include +#include +#include +#include + +#include + +#ifndef NLOHMANN_JSON_NAMESPACE_BEGIN +#define NLOHMANN_JSON_NAMESPACE_BEGIN namespace nlohmann {{ +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_END +#define NLOHMANN_JSON_NAMESPACE_END }} +#endif + +// https://github.com/nlohmann/json/pull/2117 +NLOHMANN_JSON_NAMESPACE_BEGIN +template +struct adl_serializer> {{ + static void to_json(json& j, const std::optional& opt) {{ + if (opt == std::nullopt) {{ + j = nullptr; + }} else {{ + j = *opt; // this will call adl_serializer::to_json which will + // find the free function to_json in T's namespace! + }} + }} + + static void from_json(const json& j, std::optional& opt) {{ + if (j.is_null()) {{ + opt = std::nullopt; + }} else {{ + opt = j.template get(); // same as above, but with + // adl_serializer::from_json + }} + }} +}}; +NLOHMANN_JSON_NAMESPACE_END + +namespace torch::_export {{ + +template +class ForwardRef {{ + static_assert(!std::is_reference_v, "ForwardRef cannot be a reference type"); + + public: + ForwardRef(): ptr_(std::make_unique()) {{}} + ForwardRef(ForwardRef&&) noexcept; + ForwardRef(const ForwardRef& other): ptr_(std::make_unique(*other.ptr_)) {{}} + ForwardRef& operator=(ForwardRef&&) noexcept; + ForwardRef& operator=(const ForwardRef& other) {{ + ptr_ = std::make_unique(*other.ptr_); + return *this; + }} + ~ForwardRef(); + const T& operator*() const {{ + return *ptr_; + }} + + const T* operator->() const {{ + return ptr_.get(); + }} + + void emplace(T&& t) {{ + ptr_ = std::make_unique(std::move(t)); + }} + + private: + std::unique_ptr ptr_; +}}; + +template +void to_json(nlohmann::json& j, const ForwardRef& p) {{ + j = *p; +}} + +template +void from_json(const nlohmann::json& j, ForwardRef& p) {{ + p.emplace(j.template get()); +}} + +class F64 {{ + public: + double get() const {{ + return value_; + }} + + void set(double value) {{ + value_ = value; + }} + + private: + double value_{{}}; +}}; + +inline void to_json(nlohmann::json& j, const F64& f) {{ + if (std::isinf(f.get())) {{ + j = "Infinity"; + }} else if (std::isinf(-f.get())) {{ + j = "-Infinity"; + }} else if (std::isnan(f.get())) {{ + j = "NaN"; + }} else {{ + j = f.get(); + }} +}} + +inline void from_json(const nlohmann::json& j, F64& f) {{ + if (j == "Infinity") {{ + f.set(std::numeric_limits::infinity()); + }} else if (j == "-Infinity") {{ + f.set(-std::numeric_limits::infinity()); + }} else if (j == "NaN") {{ + f.set(std::numeric_limits::quiet_NaN()); + }} else {{ + f.set(j.get()); + }} +}} + +{chr(10).join(cpp_type_decls)} +{"".join(cpp_enum_defs.values())} +{"".join(dict(sorted(cpp_class_defs.items(), key=lambda x: class_ordering[x[0]])).values())} +{chr(10).join(cpp_json_defs)} + +template ForwardRef::ForwardRef(ForwardRef&&) noexcept = default; +template ForwardRef& ForwardRef::operator=(ForwardRef&&) noexcept = default; +template ForwardRef::~ForwardRef() = default; +}} // namespace torch::_export +""" + thrift_schema = f""" +namespace py3 torch._export +namespace cpp2 torch._export.schema +{chr(10).join(thrift_enum_defs)} +{chr(10).join(dict(sorted(thrift_type_defs.items(), key=lambda x: class_ordering[x[0]])).values())} +""" + return yaml_ret, cpp_header, thrift_schema + + +def _diff_schema( + dst: dict[str, Any], src: dict[str, Any] +) -> tuple[dict[str, Any], dict[str, Any]]: + additions = {key: src[key] for key in src.keys() - dst.keys()} + subtractions = {key: dst[key] for key in dst.keys() - src.keys()} + + common_keys = src.keys() & dst.keys() + + versions = {"SCHEMA_VERSION", "TREESPEC_VERSION"} + common_keys -= versions + + for key in common_keys: + src_kind = src[key]["kind"] + src_fields = src[key]["fields"] + dst_kind = dst[key]["kind"] + dst_fields = dst[key]["fields"] + _check( + src_kind == dst_kind, + f"Type {key} changed kind from {dst_kind} to {src_kind}", + ) + if not isinstance(src_fields, dict) or not isinstance(dst_fields, dict): + raise AssertionError( + f"expected dict fields, got src={type(src_fields)}, dst={type(dst_fields)}" + ) + added_fields = { + key: src_fields[key] for key in src_fields.keys() - dst_fields.keys() + } + subtracted_fields = { + key: dst_fields[key] for key in dst_fields.keys() - src_fields.keys() + } + common_fields = src_fields.keys() & dst_fields.keys() + + for field in common_fields: + src_field = src_fields[field] + dst_field = dst_fields[field] + if src_kind == "struct": + _check( + src_field["type"] == dst_field["type"], + f"Type of the field {key}.{field} changed from {dst_field['type']} to {src_field['type']}", + ) + if "default" in src_field and "default" not in dst_field: + added_fields[field] = {} + added_fields[field]["default"] = src_field["default"] + if "default" not in src_field and "default" in dst_field: + subtracted_fields[field] = {} + subtracted_fields[field]["default"] = dst_field["default"] + elif src_kind == "enum": + _check( + src_field == dst_field, + f"Value of the enum field {key}.{field} changed from {dst_field} to {src_field}", + ) + elif src_kind == "union": + _check( + src_field["type"] == dst_field["type"], + f"Type of the field {key}.{field} changed from {dst_field['type']} to {src_field['type']}", + ) + else: + raise AssertionError(f"Unknown kind {src_kind}: {key}") + if len(added_fields) > 0: + if key in additions: + raise AssertionError(f"key {key} already in additions") + additions[key] = {} + additions[key]["fields"] = added_fields + if len(subtracted_fields) > 0: + if key in subtractions: + raise AssertionError(f"key {key} already in subtractions") + subtractions[key] = {} + subtractions[key]["fields"] = subtracted_fields + + return additions, subtractions + + +def _hash_content(s: str) -> str: + return hashlib.sha256(s.strip().encode("utf-8")).hexdigest() + + +def _generate_enum_converters() -> str: + """Generate C++ converter functions from serialized enum values to c10 enums.""" + + def validate_mapping( + enum_class: type[IntEnum], + mapping: dict[int, str], + enum_name: str, + skip_values: set[int], + ) -> None: + """Validate that all enum values have corresponding c10 mappings.""" + for member in enum_class: + if member.value in skip_values: + continue + if member.value not in mapping: + raise SchemaUpdateError( + f"{enum_name}.{member.name} (value={member.value}) is missing " + f"from {enum_name.upper()}_TO_C10 mapping in schema.py. " + f"Please add the mapping to the c10 enum name." + ) + + # Validate that all enum values have mappings (except UNKNOWN values) + validate_mapping( + schema.ScalarType, + schema.SCALAR_TYPE_TO_C10, + "ScalarType", + {schema.ScalarType.UNKNOWN}, + ) + validate_mapping( + schema.Layout, + schema.LAYOUT_TO_C10, + "Layout", + {schema.Layout.Unknown}, + ) + validate_mapping( + schema.MemoryFormat, + schema.MEMORY_FORMAT_TO_C10, + "MemoryFormat", + {schema.MemoryFormat.Unknown}, + ) + + def generate_converter( + name: str, + c10_type: str, + mapping: dict[int, str], + max_value: int, + ) -> str: + lines: list[str] = [] + for i in range(max_value + 1): + if i in mapping: + lines.append( + f" static_cast(c10::{c10_type}::{mapping[i]}), // {i}" + ) + else: + lines.append(f" kInvalid, // {i}") + + return f""" +inline c10::{c10_type} convertSerialized{name}(int serialized_value) {{ + constexpr int kInvalid = -1; + constexpr int k{name}Map[] = {{ +{chr(10).join(lines)} + }}; + constexpr int kMapSize = sizeof(k{name}Map) / sizeof(k{name}Map[0]); + + TORCH_CHECK( + serialized_value >= 0 && serialized_value < kMapSize, + "Serialized {name} value out of range: ", + serialized_value); + int result = k{name}Map[serialized_value]; + TORCH_CHECK( + result != kInvalid, + "Invalid serialized {name} value: ", + serialized_value); + return static_cast(result); +}} +""" + + scalar_type_converter = generate_converter( + "ScalarType", + "ScalarType", + schema.SCALAR_TYPE_TO_C10, + max(schema.SCALAR_TYPE_TO_C10.keys()), + ) + layout_converter = generate_converter( + "Layout", + "Layout", + schema.LAYOUT_TO_C10, + max(schema.LAYOUT_TO_C10.keys()), + ) + memory_format_converter = generate_converter( + "MemoryFormat", + "MemoryFormat", + schema.MEMORY_FORMAT_TO_C10, + max(schema.MEMORY_FORMAT_TO_C10.keys()), + ) + + return f""" +#pragma once + +#include +#include +#include +#include + +// Converter functions from serialized enum values (torch._export.serde.schema) +// to c10 enums. The serialized format has different enum values than c10. + +namespace torch::aot_inductor {{ +{scalar_type_converter} +{layout_converter} +{memory_format_converter} +}} // namespace torch::aot_inductor +""" + + +@dataclasses.dataclass +class _Commit: + result: dict[str, Any] + checksum_next: str + yaml_path: str + additions: dict[str, Any] + subtractions: dict[str, Any] + base: dict[str, Any] + checksum_head: str | None + cpp_header: str + cpp_header_path: str + enum_converter_header: str + enum_converter_header_path: str + thrift_checksum_head: str | None + thrift_checksum_real: str | None + thrift_checksum_next: str + thrift_schema: str + thrift_schema_path: str + + +def update_schema() -> _Commit: + import importlib.resources + + dst: dict[str, Any] + # pyrefly: ignore [bad-argument-type] + if importlib.resources.is_resource(__package__, "schema.yaml"): + # pyrefly: ignore [bad-argument-type] + content = importlib.resources.read_text(__package__, "schema.yaml") + match = re.search("checksum<<([A-Fa-f0-9]{64})>>", content) + _check(match is not None, "checksum not found in schema.yaml") + if match is None: + raise AssertionError("checksum not found in schema.yaml") + checksum_head = match.group(1) + + thrift_content = importlib.resources.read_text( + # pyrefly: ignore [bad-argument-type] + __package__, + "export_schema.thrift", + ) + match = re.search("checksum<<([A-Fa-f0-9]{64})>>", thrift_content) + _check(match is not None, "checksum not found in export_schema.thrift") + if match is None: + raise AssertionError("checksum not found in export_schema.thrift") + thrift_checksum_head = match.group(1) + thrift_content = thrift_content.splitlines() + if not thrift_content[0].startswith("// @" + "generated"): + raise AssertionError( + f"expected first line to start with '// @generated', got {thrift_content[0]!r}" + ) + if not thrift_content[1].startswith("// checksum<<"): + raise AssertionError( + f"expected second line to start with '// checksum<<', got {thrift_content[1]!r}" + ) + thrift_checksum_real = _hash_content("\n".join(thrift_content[2:])) + + from yaml import load, Loader + + dst = load(content, Loader=Loader) + if not isinstance(dst, dict): + raise AssertionError(f"expected dict from yaml, got {type(dst)}") + else: + checksum_head = None + thrift_checksum_head = None + thrift_checksum_real = None + dst = {"SCHEMA_VERSION": None, "TREESPEC_VERSION": None} + + src, cpp_header, thrift_schema = _staged_schema() + enum_converter_header = _generate_enum_converters() + additions, subtractions = _diff_schema(dst, src) + # pyrefly: ignore [missing-attribute] + yaml_path = __package__.replace(".", "/") + "/schema.yaml" + # pyrefly: ignore [missing-attribute] + thrift_schema_path = __package__.replace(".", "/") + "/export_schema.thrift" + torch_prefix = "torch/" + if not yaml_path.startswith(torch_prefix): + raise AssertionError( + f"yaml_path must start with {torch_prefix}, got {yaml_path}" + ) + if not thrift_schema_path.startswith(torch_prefix): + raise AssertionError( + f"thrift_schema_path must start with {torch_prefix}, got {thrift_schema_path}" + ) + + return _Commit( + result=src, + checksum_next=_hash_content(repr(src)), + yaml_path=yaml_path, + additions=additions, + subtractions=subtractions, + base=dst, + checksum_head=checksum_head, + cpp_header=cpp_header, + cpp_header_path=torch_prefix + "csrc/utils/generated_serialization_types.h", + enum_converter_header=enum_converter_header, + enum_converter_header_path=torch_prefix + + "csrc/inductor/aoti_torch/generated_enum_converters.h", + thrift_checksum_head=thrift_checksum_head, + thrift_checksum_real=thrift_checksum_real, + thrift_checksum_next=_hash_content(thrift_schema), + thrift_schema=thrift_schema, + thrift_schema_path=thrift_schema_path, + ) + + +def check(commit: _Commit, force_unsafe: bool = False) -> tuple[list[int] | None, str]: + next_version: list[int] | None = None + reason = "" + # Step 1: Detect major schema updates. + if len(commit.additions) > 0: + for k, v in commit.additions.items(): + if k not in commit.base: + continue + kind = commit.result[k]["kind"] + fields = v["fields"] + for f, d in fields.items(): + if kind == "struct" and "default" not in d: + reason += ( + f"Field {k}.{f} is added to schema.py without a default value as an incompatible change " + + "which requires major version bump.\n" + ) + next_version = [commit.base["SCHEMA_VERSION"][0] + 1, 1] + + if len(commit.subtractions) > 0: + for k, v in commit.subtractions.items(): + if k not in commit.result: + continue + for f in v["fields"]: + reason = f"Field {k}.{f} is removed from schema.py as an incompatible change which requires major version bump.\n" + next_version = [commit.base["SCHEMA_VERSION"][0] + 1, 1] + + if force_unsafe: + reason += "--force-unsafe is used." + next_version = commit.result["SCHEMA_VERSION"] + else: + # Step 2: Detect minor schema updates. + if next_version is None and len(commit.additions) > 0: + for k, v in commit.additions.items(): + for f in v["fields"]: + reason += ( + f"Field {k}.{f} is added to schema.py as a compatible change " + + "which still requires minor version bump.\n" + ) + next_version = [ + commit.base["SCHEMA_VERSION"][0], + commit.base["SCHEMA_VERSION"][1] + 1, + ] + if next_version is None and len(commit.subtractions) > 0: + for k, v in commit.subtractions.items(): + for f in v["fields"]: + reason += ( + f"Field {k}.{f} is removed from schema.py as a compatible change " + + "which still requires minor version bump.\n" + ) + next_version = [ + commit.base["SCHEMA_VERSION"][0], + commit.base["SCHEMA_VERSION"][1] + 1, + ] + + return next_version, reason diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/serialize.py b/.venv/lib/python3.12/site-packages/torch/_export/serde/serialize.py new file mode 100644 index 0000000000000000000000000000000000000000..4b9e761513cc372e2d722f961e5f8bd319f52e7a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/serde/serialize.py @@ -0,0 +1,4431 @@ +# mypy: allow-untyped-defs +import base64 +import copy +import copyreg +import dataclasses +import heapq +import inspect +import io +import json +import keyword +import logging +import math +import operator +import re +import traceback +import types +import typing +from collections import namedtuple, OrderedDict +from collections.abc import Callable, Iterable, Iterator, Sequence +from contextlib import contextmanager +from dataclasses import dataclass, field +from enum import Enum +from typing import Annotated, Any, cast, final, Optional + +import sympy + +import torch +import torch.export.exported_program as ep +from torch._export.non_strict_utils import _enable_graph_inputs_of_type_nn_module +from torch._export.verifier import load_verifier +from torch._library.opaque_object import get_opaque_type_name, is_custom_class_obj +from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode +from torch.fx._symbolic_trace import _ConstantAttributeType +from torch.fx.experimental import symbolic_shapes +from torch.fx.traceback import NodeSource +from torch.utils import _pytree as pytree +from torch.utils._pytree import treespec_dumps, treespec_loads +from torch.utils._sympy.numbers import int_oo +from torch.utils._sympy.symbol import prefix_str, SymT +from torch.utils._sympy.value_ranges import ValueRanges +from torch.utils._traceback import CapturedTraceback +from torch.utils._triton import has_triton + +from ..utils import remove_proxy_from_state_dict +from . import schema +from .schema import ( # type: ignore[attr-defined] + Argument, + ArgumentKind, + BufferMutationSpec, + ComplexValue, + ConstantValue, + CustomObjArgument, + Device, + ExportedProgram, + GradientToParameterSpec, + GradientToUserInputSpec, + Graph, + GraphArgument, + GraphModule, + GraphSignature, + InputSpec, + InputToBufferSpec, + InputToConstantInputSpec, + InputToCustomObjSpec, + InputTokenSpec, + InputToParameterSpec, + InputToTensorConstantSpec, + Layout, + LossOutputSpec, + MemoryFormat, + ModuleCallEntry, + ModuleCallSignature, + NamedArgument, + NamedTupleDef, + Node, + OptionalTensorArgument, + OutputSpec, + OutputTokenSpec, + ParameterMutationSpec, + RangeConstraint, + ScalarType, + SCHEMA_VERSION, + SchemaVersion, + SymBool, + SymBoolArgument, + SymExpr, + SymExprHint, + SymFloat, + SymFloatArgument, + SymInt, + SymIntArgument, + TensorArgument, + TensorMeta, + TokenArgument, + TREESPEC_VERSION, + UserInputMutationSpec, + UserInputSpec, + UserOutputSpec, +) +from .union import _Union + + +__all__ = [ + "serialize", + "GraphModuleSerializer", + "ExportedProgramSerializer", + "GraphModuleDeserializer", + "ExportedProgramDeserializer", +] + +log = logging.getLogger(__name__) + + +class SerializeError(RuntimeError): + pass + + +def _reverse_map(d: dict[Any, Enum]): + return {v.value: k for k, v in d.items()} + + +MetaType = ( + FakeTensor + | int + | torch.SymInt + | float + | torch.SymFloat + | bool + | torch.SymBool + | ep.CustomObjArgument +) + +DEFAULT_PICKLE_PROTOCOL = 2 + +ST_DELIMITER = ";" + +_TORCH_TO_SERIALIZE_DTYPE = { + torch.uint8: ScalarType.BYTE, + torch.int8: ScalarType.CHAR, + torch.uint16: ScalarType.UINT16, + torch.int16: ScalarType.SHORT, + torch.int32: ScalarType.INT, + torch.int64: ScalarType.LONG, + torch.float16: ScalarType.HALF, + torch.float32: ScalarType.FLOAT, + torch.float64: ScalarType.DOUBLE, + torch.complex32: ScalarType.COMPLEXHALF, + torch.complex64: ScalarType.COMPLEXFLOAT, + torch.complex128: ScalarType.COMPLEXDOUBLE, + torch.bool: ScalarType.BOOL, + torch.bfloat16: ScalarType.BFLOAT16, + torch.float8_e4m3fn: ScalarType.FLOAT8E4M3FN, + torch.float8_e5m2: ScalarType.FLOAT8E5M2, + torch.float8_e4m3fnuz: ScalarType.FLOAT8E4M3FNUZ, + torch.float8_e5m2fnuz: ScalarType.FLOAT8E5M2FNUZ, + torch.float8_e8m0fnu: ScalarType.FLOAT8E8M0FNU, + torch.uint32: ScalarType.UINT32, + torch.uint64: ScalarType.UINT64, +} + + +_SERIALIZE_TO_TORCH_DTYPE = _reverse_map(_TORCH_TO_SERIALIZE_DTYPE) # type: ignore[arg-type] + + +_TORCH_TO_SERIALIZE_LAYOUT = { + torch.sparse_coo: Layout.SparseCoo, + torch.sparse_csr: Layout.SparseCsr, + torch.sparse_csc: Layout.SparseCsc, + torch.sparse_bsr: Layout.SparseBsr, + torch.sparse_bsc: Layout.SparseBsc, + torch._mkldnn: Layout._mkldnn, # type: ignore[attr-defined] + torch.strided: Layout.Strided, +} + + +_SERIALIZE_TO_TORCH_LAYOUT = _reverse_map(_TORCH_TO_SERIALIZE_LAYOUT) # type: ignore[arg-type] + + +_TORCH_TO_SERIALIZE_MEMORY_FORMAT = { + torch.contiguous_format: MemoryFormat.ContiguousFormat, + torch.channels_last: MemoryFormat.ChannelsLast, + torch.channels_last_3d: MemoryFormat.ChannelsLast3d, + torch.preserve_format: MemoryFormat.PreserveFormat, +} + + +_SERIALIZE_TO_TORCH_MEMORY_FORMAT = _reverse_map(_TORCH_TO_SERIALIZE_MEMORY_FORMAT) # type: ignore[arg-type] + +_SYM_OPS = { + operator.eq, + operator.ne, + operator.le, + operator.ge, + operator.lt, + operator.gt, + operator.neg, + operator.pos, + math.trunc, + torch.sym_not, + operator.mul, + operator.add, + operator.sub, + operator.floordiv, + operator.mod, + operator.pow, + torch.sym_int, + torch.sym_float, + torch.sym_ite, + torch.sym_max, + torch.sym_min, + torch.sym_sqrt, + operator.truediv, + operator.and_, + operator.or_, + operator.lshift, + operator.rshift, +} + + +if any(isinstance(op, torch._ops.OpOverload) for op in _SYM_OPS): + raise AssertionError("_SYM_OPS should not contain OpOverload instances") + + +@dataclass +class SerializedArtifact: + exported_program: bytes + state_dict: bytes + constants: bytes + example_inputs: bytes + + +@dataclass +class _SerializedProgram: + exported_program: ExportedProgram + state_dict: bytes + constants: bytes + example_inputs: bytes + + +class LazyMap(dict): + """ + Dictionary class for deferred instantiation of node metadata values. + Purpose is to avoid creation of symbolic-shape tensors before relevant shape guards are parsed. + """ + + def __init__(self): + self.map = {} + self.evaluated = set() + + def __setitem__(self, k, v): + self.map[k] = v + + def __getitem__(self, k): + out = self.map[k] + if k in self.evaluated: + return out + self.evaluated.add(k) + self.map[k] = out() + return self.map[k] + + def __repr__(self): + return self.map.__repr__() + + +def deserialize_device(d: Device) -> torch.device: + if d.index is None: + return torch.device(type=d.type) # type: ignore[call-overload] + return torch.device(type=d.type, index=d.index) + + +def deserialize_size(sizes: Sequence[SymInt]) -> tuple[int, ...]: + for sym_int_size in sizes: + if sym_int_size.type != "as_int": + raise AssertionError(f"Only as_int is supported, got {sym_int_size.type}") + return tuple(sym_int_size.as_int for sym_int_size in sizes) + + +def deserialize_stride(strides: Sequence[SymInt]) -> tuple[int, ...]: + for sym_int_stride in strides: + if sym_int_stride.type != "as_int": + raise AssertionError(f"Only as_int is supported, got {sym_int_stride.type}") + return tuple(sym_int_stride.as_int for sym_int_stride in strides) + + +def deserialize_scalar_type(st: ScalarType) -> torch.dtype: + return _SERIALIZE_TO_TORCH_DTYPE[st] + + +def deserialize_storage_offset(offset: SymInt) -> int: + if offset.type != "as_int": + raise AssertionError(f"Only as_int is supported, got {offset.type}") + return offset.as_int + + +def _print_sympy(s: torch.SymInt | torch.SymBool | torch.SymFloat | sympy.Expr): + if isinstance(s, (torch.SymInt, torch.SymBool, torch.SymFloat)): + s = s.node.expr + return sympy.printing.repr.srepr(s) + + +def serialize_sym_int(s: int | torch.SymInt) -> SymInt: + if isinstance(s, (torch.SymInt, sympy.Symbol, int)): + if symbolic_shapes.is_concrete_int(s): + return SymInt.create(as_int=int(s)) + else: + if not isinstance(s, (torch.SymInt, sympy.Symbol)): + raise AssertionError( + f"expected SymInt or Symbol, got {type(s).__name__}" + ) + if s.node.hint is None: + return SymInt.create(as_expr=SymExpr(_print_sympy(s))) + else: + return SymInt.create( + as_expr=SymExpr( + _print_sympy(s), + hint=SymExprHint.create(as_int=s.node.hint), + ) + ) + else: + raise SerializeError( + f"SymInt should be either symbol or int, got `{s}` of type `{type(s)}`" + ) + + +def serialize_sym_float(s: float | torch.SymFloat) -> SymFloat: + if isinstance(s, (torch.SymFloat, sympy.Symbol, float)): + if symbolic_shapes.is_concrete_float(s): + return SymFloat.create(as_float=float(s)) + else: + if not isinstance(s, (torch.SymFloat, sympy.Symbol)): + raise AssertionError( + f"expected SymFloat or Symbol, got {type(s).__name__}" + ) + if s.node.hint is None: + return SymFloat.create(as_expr=SymExpr(_print_sympy(s))) + else: + return SymFloat.create( + as_expr=SymExpr( + _print_sympy(s), + hint=SymExprHint.create(as_float=s.node.hint), + ) + ) + else: + raise SerializeError( + f"SymFloat should be either symbol or float, got `{s}` of type `{type(s)}`" + ) + + +def serialize_sym_bool(s: bool | torch.SymBool) -> SymBool: + if isinstance(s, (torch.SymBool, bool)): + if symbolic_shapes.is_concrete_bool(s): + return SymBool.create(as_bool=bool(s)) + else: + return SymBool.create(as_expr=SymExpr(expr_str=_print_sympy(s))) + else: + raise SerializeError( + f"SymBool should be either symbol or bool, got `{s}` of type `{type(s)}`" + ) + + +def serialize_tensor_meta(t: torch.Tensor) -> TensorMeta: + """ + Extract a TensorMeta describing `t`. + """ + return TensorMeta( + dtype=_TORCH_TO_SERIALIZE_DTYPE[t.dtype], + sizes=[serialize_sym_int(s) for s in t.shape], + requires_grad=t.requires_grad, + device=Device(type=t.device.type, index=t.device.index), + strides=[serialize_sym_int(s) for s in t.stride()], + storage_offset=serialize_sym_int(t.storage_offset()), + layout=_TORCH_TO_SERIALIZE_LAYOUT[t.layout], + ) + + +_CURRENT_DESERIALIZER: Optional["GraphModuleDeserializer"] = None + + +def _reduce_fake_tensor(fake_tensor: FakeTensor): + is_parameter = isinstance(fake_tensor, torch.nn.Parameter) + tensor_meta = serialize_tensor_meta(fake_tensor) + tensor_meta_bytes = json.dumps( + _dataclass_to_dict(tensor_meta), cls=EnumEncoder + ).encode("utf-8") + return _reconstruct_fake_tensor, (tensor_meta_bytes, is_parameter) + + +def _reconstruct_fake_tensor( + serialized_tensor_meta: bytes, is_parameter: bool +) -> FakeTensor: + # Deserialize the bytes into a TensorMeta + json_tensor_meta = json.loads(serialized_tensor_meta.decode("utf-8")) + tensor_meta = _dict_to_dataclass(TensorMeta, json_tensor_meta) + # Find the current fake mode + if _CURRENT_DESERIALIZER is None: + raise AssertionError("Need access to current deserializer state") + fake_tensor = _CURRENT_DESERIALIZER.deserialize_tensor_meta(tensor_meta) + if is_parameter: + fake_tensor = torch.nn.Parameter(fake_tensor) # type: ignore[assignment] + # pyrefly: ignore [bad-return] + return fake_tensor + + +def serialize_torch_artifact( + artifact: Any | None, pickle_protocol: int = DEFAULT_PICKLE_PROTOCOL +) -> bytes: + if artifact is None: + return b"" + + if FakeTensor in copyreg.dispatch_table: + raise AssertionError("Refusing to stomp on existing FakeTensor reducer") + try: + copyreg.pickle(FakeTensor, _reduce_fake_tensor) + buffer = io.BytesIO() + # This is a workaround for backend's tensor deserialization problem: + # unpickleTensor() always create a tensor on the device where it was originally saved + # This behavior is bad for multi-gpu training, as we wish to directly load the tensor + # on the designated device. + # For now, we simply move the tensor to cpu before saving. + # TODO: this should be fixed by deserialization instead. + torch.save(artifact, buffer, pickle_protocol=pickle_protocol) + return buffer.getvalue() + finally: + del copyreg.dispatch_table[FakeTensor] + + +def deserialize_torch_artifact( + serialized: dict[str, Any] | tuple[Any, ...] | bytes, +): + if isinstance(serialized, (dict, tuple)): + return serialized + if len(serialized) == 0: + return {} + buffer = io.BytesIO(serialized) + buffer.seek(0) + # weights_only=False as we want to load custom objects here (e.g. ScriptObject) + try: + artifact = torch.load(buffer, weights_only=True) + except Exception as e: + buffer.seek(0) + artifact = torch.load(buffer, weights_only=False) + log.warning( + "Fallback to weights_only=False succeeded. " + "Loaded object of type %s after initial failure: %s", + type(artifact), + exc_info=e, + ) + if not isinstance(artifact, (tuple, dict)): + raise AssertionError(f"expected tuple or dict, got {type(artifact).__name__}") + return artifact + + +def _sympy_int_to_int(val: sympy.Expr, adjust: str) -> int | None: + # Convert simple sympy Integers into concrete int + if val in (sympy.oo, int_oo): + return None + if val in (-sympy.oo, -int_oo): + return None + if isinstance(val, sympy.Integer): + return int(val) + + # TODO: Remove this adjustment when Ed gets rid of fractional ranges + log.warning( + "Export constraints cannot be non-integer expressions. Found " + "type %s, and value %s. We will attempt to %s " + "this value.", + type(val), + val, + adjust, + ) + + if adjust == "floor": + return math.floor(val) + elif adjust == "ceil": + return math.ceil(val) + else: + raise RuntimeError(f"Got invalid adjustment {adjust}") + + +def _int_to_sympy_int(val: int | None, default) -> sympy.Expr: + # Convert concrete int into simple sympy Integers + if val is None: + return default + if val in [-int_oo, int_oo]: + return val + if val == math.inf: + return int_oo + if val == -math.inf: + return -int_oo + return sympy.Integer(val) + + +def _symbol_index(sym: sympy.Symbol, sym_type: SymT): + return int(str(sym)[len(prefix_str[sym_type]) :]) + + +def serialize_range_constraints( + range_constraints: dict[sympy.Symbol, ValueRanges], +) -> dict[str, RangeConstraint]: + return { + str(k): RangeConstraint( + _sympy_int_to_int(v.lower, "ceil"), # type: ignore[arg-type] + _sympy_int_to_int(v.upper, "floor"), # type: ignore[arg-type] + ) + for k, v in range_constraints.items() + } + + +def _get_schema_from_target(target): + if isinstance(target, torch._ops.OpOverload): + return target._schema + elif type(target) in _serialization_registry: + return _serialization_registry[type(target)].op_schema(target) + raise RuntimeError(f"Cannot find schema for {type(target)}") + + +@dataclass +class GraphState: + inputs: list[Argument] = field(default_factory=list) + outputs: list[Argument] = field(default_factory=list) + nodes: list[Node] = field(default_factory=list) + tensor_values: dict[str, TensorMeta] = field(default_factory=dict) + sym_int_values: dict[str, SymInt] = field(default_factory=dict) + sym_bool_values: dict[str, SymBool] = field(default_factory=dict) + sym_float_values: dict[str, SymFloat] = field(default_factory=dict) + is_single_tensor_return: bool = False + custom_obj_values: dict[str, CustomObjArgument] = field(default_factory=dict) + + +class Final(type): + def __new__(metacls, name, bases, classdict): + for b in bases: + if isinstance(b, Final): + raise TypeError(f"type '{b.__name__}' is not an acceptable base type") + return type.__new__(metacls, name, bases, dict(classdict)) + + +def is_metadata_matched(config, entry_metadata): + metadata_attrs = ["num_cpu_threads", "num_warps", "num_stages", "num_ctas"] + for attr in metadata_attrs: + if hasattr(config, attr) and hasattr(entry_metadata, attr): + if getattr(config, attr) != getattr(entry_metadata, attr): + return False + return True + + +def get_triton_kernel_and_cache_entry(node: torch.fx.Node): + if ( + node.target + is not torch._higher_order_ops.triton_kernel_wrap.triton_kernel_wrapper_functional + ): + raise AssertionError( + f"expected triton_kernel_wrapper_functional, got {node.target}" + ) + + if not has_triton(): + raise AssertionError("triton required to serialize triton kernels") + from triton.runtime.autotuner import Autotuner + from triton.runtime.jit import JITFunction + + if not isinstance(node.kwargs["kernel_idx"], int): + raise AssertionError( + f"expected kernel_idx to be int, got {type(node.kwargs['kernel_idx'])}" + ) + kernel = torch._higher_order_ops.triton_kernel_wrap.kernel_side_table.get_kernel( + node.kwargs["kernel_idx"] + ) + + # For Autotuner, we need to look at the underlying JITFunction's cache + # since the Autotuner itself doesn't have a cache + is_autotuner = isinstance(kernel, Autotuner) + # pyrefly: ignore [missing-attribute] + actual_kernel = kernel.fn if is_autotuner else kernel + + if hasattr(actual_kernel, "device_caches"): + caches = actual_kernel.device_caches + if len(caches.keys()) != 1: + raise AssertionError( + f"expected exactly 1 device cache, got {len(caches.keys())}" + ) + cache = next(iter(caches.values()))[0] + elif hasattr(actual_kernel, "cache"): + # old path, still used for cpu triton builds + caches = actual_kernel.cache + if len(caches.keys()) != 1: + raise AssertionError( + f"expected exactly 1 cache key, got {len(caches.keys())}" + ) + cache = next(iter(caches.values())) + else: + raise AssertionError( + # pyrefly: ignore [missing-attribute] + f"kernel caches not found for kernel {actual_kernel.__name__}" + ) + + if len(cache.keys()) == 1: + return actual_kernel, next(iter(cache.values())) + + has_constexprs = ( + isinstance(actual_kernel, JITFunction) + and hasattr(actual_kernel, "constexprs") + and len(actual_kernel.constexprs) > 0 + ) + + if has_constexprs: + constexpr_vals = {} + # pyrefly: ignore [missing-attribute] + for constexpr_idx in actual_kernel.constexprs: + # pyrefly: ignore [missing-attribute] + if constexpr_idx < len(actual_kernel.arg_names): + # pyrefly: ignore [missing-attribute] + param_name = actual_kernel.arg_names[constexpr_idx] + kwargs_dict = node.kwargs.get("kwargs", {}) + if isinstance(kwargs_dict, dict): + if param_name in kwargs_dict: + constexpr_vals[param_name] = kwargs_dict[param_name] + + expected_values = [ + # pyrefly: ignore [missing-attribute] + constexpr_vals[actual_kernel.arg_names[idx]] + # pyrefly: ignore [missing-attribute] + for idx in actual_kernel.constexprs + # pyrefly: ignore [missing-attribute] + if actual_kernel.arg_names[idx] in constexpr_vals + ] + + # Normalize expected values for comparison with parsed constexpr values. + # The kernel signature key stores constexprs as strings (e.g., "True", "1.5", "42"), + # which we parse back to Python types. To ensure proper comparison, we normalize + # the expected values: booleans, ints, and floats are kept as-is since they can + # be compared directly with parsed values. Other types (like dtype or string + # constants) are converted to strings to match the parsed format. + normalized_expected = [] + for val in expected_values: + if isinstance(val, (bool, int, float)): + normalized_expected.append(val) + else: + # pyrefly: ignore [bad-argument-type] + normalized_expected.append(str(val)) + + matching_entries = [] + for sig_key, cache_entry in cache.items(): + constexpr_matches = re.findall(r"\('constexpr',\s*([^)]+)\)", sig_key) + if constexpr_matches: + # Parse constexpr string values back to Python types for comparison. + # Booleans are stored as "True"/"False" strings, numbers as their string + # representation. Values that can't be parsed as numbers are kept as strings + # (e.g., dtype names like "torch.float32"). + constexpr_values = [] + for match in constexpr_matches: + if match in ("True", "False"): + constexpr_values.append(match == "True") + else: + try: + constexpr_values.append(float(match)) + except ValueError: + try: + constexpr_values.append(int(match)) + except ValueError: + constexpr_values.append(match) + + if constexpr_values == normalized_expected: + matching_entries.append((sig_key, cache_entry)) + else: + matching_entries = list(cache.items()) + + if len(matching_entries) == 0: + raise AssertionError( + # pyrefly: ignore [missing-attribute] + f"couldn't find a kernel cache entry with metadata matching the autotuner configs for kernel {actual_kernel.__name__}. " + f"Available cache keys: {list(cache.keys())}" + ) + + if len(matching_entries) == 1: + return actual_kernel, matching_entries[0][1] + + if is_autotuner: + for _sig_key, cache_entry in matching_entries: + entry_metadata = cache_entry.metadata + # pyrefly: ignore [missing-attribute] + for config in kernel.configs: + if is_metadata_matched(config, entry_metadata): + return actual_kernel, cache_entry + + raise AssertionError( + # pyrefly: ignore [missing-attribute] + f"Multiple cache entries found for autotuned kernel {actual_kernel.__name__} " + f"{'with same constexpr values' if has_constexprs else 'with no constexpr'} " + f"and couldn't disambiguate using configs. " + ) + + raise AssertionError( + # pyrefly: ignore [missing-attribute] + f"Multiple cache entries found for non-autotuned kernel {actual_kernel.__name__} " + f"{'with same constexpr values' if has_constexprs else 'with no constexpr'}. " + f"This should not happen. Available cache keys: {[key for key, _ in matching_entries]}" + ) + + +@final +class GraphModuleSerializer(metaclass=Final): + def __init__( + self, + graph_signature: ep.ExportGraphSignature, + module_call_graph: list[ep.ModuleCallEntry], + ): + self.graph_state = GraphState() + self.graph_signature = graph_signature + self.module_call_graph = module_call_graph + self.custom_objs: dict[str, Any] = {} + self.duplicate_getitem_nodes: dict[str, str] = {} + self.treespec_namedtuple_fields: dict[str, NamedTupleDef] = {} + + @contextmanager + def save_graph_state(self): + saved = self.graph_state + self.graph_state = GraphState() + try: + yield + finally: + self.graph_state = saved + + def handle_placeholder(self, node: torch.fx.Node): + if node.op != "placeholder": + raise AssertionError(f"expected placeholder op, got {node.op}") + val = node.meta["val"] + log.debug("[handle_placeholder] %s: %s", node.name, val) + if isinstance(val, torch.Tensor): + graph_input = Argument.create( + as_tensor=self.serialize_tensor_output(node.name, val) + ) + elif isinstance(val, torch.SymInt): + graph_input = Argument.create( + as_sym_int=self.serialize_sym_int_output(node.name, val) + ) + elif isinstance(val, torch.SymFloat): + raise AssertionError("SymFloat graph input is not implemented yet.") + elif isinstance(val, (int, bool, str, float, type(None))): + graph_input = self.serialize_input(val) + elif isinstance(val, ep.CustomObjArgument): + class_fqn = val.class_fqn + graph_input = Argument.create( + as_custom_obj=CustomObjArgument(name=node.name, class_fqn=class_fqn) + ) + self.graph_state.custom_obj_values[node.name] = ( + self.serialize_script_obj_meta(val) + ) + else: + raise AssertionError(f"Unimplemented graph input type: {node.meta['val']}") + self.graph_state.inputs.append(graph_input) + + def handle_output(self, node: torch.fx.Node): + if node.op != "output": + raise AssertionError(f"expected output op, got {node.op}") + if len(node.args) != 1: + raise AssertionError( + f"FX.Node's args should have one arg, got {len(node.args)}" + ) + node_args = node.args[0] + log.debug("[handle_output] %s: %s", node.name, node_args) + if isinstance(node_args, torch.fx.Node): + # For singleton tensor returns + self.graph_state.is_single_tensor_return = True + self.graph_state.outputs = [self.serialize_input(node_args)] + else: + if not isinstance(node_args, (tuple, list)): + raise AssertionError(f"expected tuple or list, got {type(node_args)}") + self.graph_state.outputs = [self.serialize_input(arg) for arg in node_args] + + def serialize_operator(self, target) -> str: + if isinstance(target, str): + return target + elif target.__module__.startswith("torch._ops"): + # TODO(zhxchen17) Maybe provide a function name helper in FX. + # From torch.fx.node._get_qualified_name + module = target.__module__.replace("torch._ops", "torch.ops") + return f"{module}.{target.__name__}" + else: # TODO(zhxchen17) Don't catch all here. + return f"{target.__module__}.{target.__name__}" + + def handle_call_function(self, node: torch.fx.Node): + if node.op != "call_function": + raise AssertionError(f"expected call_function op, got {node.op}") + meta_val = node.meta.get("val") + log.debug( + "[handle_call_function] %s: %s(%s, {%s}) -> %s", + node.name, + node.target, + node.args, + node.kwargs, + meta_val, + ) + + # getitem has been handled in the producer node, skip it here + if node.target is operator.getitem: + return + + if node.target in _SYM_OPS or ( + meta_val is not None + and isinstance(meta_val, (torch.SymInt, torch.SymBool, torch.SymFloat)) + ): + if len(node.kwargs) != 0: + raise AssertionError( + f"expected no kwargs for sym op, got {len(node.kwargs)}" + ) + ex_node = Node( + name=node.name, + target=self.serialize_operator(node.target), + inputs=self.serialize_sym_op_inputs(node.target, node.args), + outputs=[self.serialize_output(node.name, meta_val)], + metadata=self.serialize_metadata(node), + ) + elif isinstance(node.target, torch._ops.OpOverload): + ex_node = Node( + name=node.name, + target=self.serialize_operator(node.target), + inputs=self.serialize_inputs(node.target, node.args, node.kwargs), + outputs=self.serialize_outputs(node), + # TODO: create a new tensor_values here, meta might have faketensor info + metadata=self.serialize_metadata(node), + ) + elif isinstance(node.target, torch._ops.HigherOrderOperator): + + def _is_hop_single_tensor_return(node) -> bool: + if not isinstance(node.target, torch._ops.HigherOrderOperator): + raise AssertionError( + f"expected HigherOrderOperator, got {type(node.target).__name__}" + ) + # HOP schema is not always available, so we look at node.meta["val"] + meta_val = node.meta.get("val", None) + return meta_val is not None and isinstance(meta_val, torch.Tensor) + + # Special handle serialization for aoti_call_delegate + if node.target is torch._higher_order_ops.aoti_call_delegate: + serializable_args = list(node.args) + + # AOTI lowered module is not serializable, serialize the aoti_path instead + lowered_module_name: str = node.args[0].name # type: ignore[assignment, no-untyped-def, union-attr] + if not hasattr(node.graph.owning_module, lowered_module_name): + raise AssertionError( + f"owning_module does not have attribute {lowered_module_name}" + ) + lowered_module = getattr(node.graph.owning_module, lowered_module_name) # type: ignore[no-untyped-def] + serializable_args[0] = lowered_module.aoti_path + + # AOTI compiled graph module in node.args[0] is stateful, and will fail the verifier check + # Skip serializing original_gm as a workaround + serializable_args[1] = None + + serializable_weight_nodes = [] + if serializable_args[2] is not None and isinstance( + serializable_args[2], Iterable + ): + for weight_node in serializable_args[2]: + # skip passing custom obj into the weight arg as an hack + # The schema of weight input is a list of Tensors. + # Downstream runtime is not actively consuming the weighs arg for anything meaningful. + if isinstance(weight_node, torch.fx.Node) and isinstance( + weight_node.meta.get("val", None), ep.CustomObjArgument + ): + continue + serializable_weight_nodes.append(weight_node) + serializable_args[2] = serializable_weight_nodes + + def serialize_tensor_list_output(node): + meta_val = node.meta.get("val", None) + tensor_args = [] + for idx, meta in enumerate(meta_val): + name = self._output_node_name_at_index(node, idx) + tensor_args.append(self.serialize_tensor_output(name, meta)) + return [Argument.create(as_tensors=tensor_args)] + + ex_node = Node( + name=node.name, + target=self.serialize_operator(node.target), + inputs=self.serialize_hoo_inputs(serializable_args, node.kwargs), + outputs=serialize_tensor_list_output(node), + metadata=self.serialize_metadata(node), + is_hop_single_tensor_return=False, + ) + elif ( + node.target + is torch._higher_order_ops.triton_kernel_wrap.triton_kernel_wrapper_functional + ): + kernel, kernel_cache_entry = get_triton_kernel_and_cache_entry(node) + kernel_cache_metadata = kernel_cache_entry.metadata + + meta_val = node.meta["val"] + if not isinstance(meta_val, dict): + raise AssertionError( + f"expected meta_val to be dict, got {type(meta_val).__name__}" + ) + + output_keys = meta_val.keys() + output_indices = [] + + constexpr_keys = {p.name for p in kernel.params if p.is_constexpr} + found_constexpr = False + inputs_new = [] + i = 0 + + if not isinstance(node.kwargs["kwargs"], dict): + raise AssertionError( + f"expected kwargs['kwargs'] to be dict, got {type(node.kwargs['kwargs'])}" + ) + for k, v in node.kwargs["kwargs"].items(): + # don't serialize constexpr since they will + # be embedded into the binary and don't + # need to be passed around as attributes + if k in constexpr_keys: + found_constexpr = True + continue + + if found_constexpr: + raise AssertionError( + "non-constexpr args found after constexpr arg(s)" + ) + + if k in output_keys: + output_indices.append(i) + inputs_new.append( + NamedArgument( + name=k, + arg=self.serialize_input(v), + kind=ArgumentKind.POSITIONAL, + ) + ) + i += 1 + + if not isinstance(node.kwargs["grid"], list): + raise AssertionError( + f"expected grid to be list, got {type(node.kwargs['grid'])}" + ) + + kernel_name_with_hash = ( + f"{kernel.fn.__name__}_{kernel_cache_metadata.hash}" + ) + kwargs_new = { + "name": kernel_name_with_hash, + "grid": node.kwargs["grid"][0], + "output_indices": output_indices, + "num_warps": kernel_cache_metadata.num_warps, + } + if hasattr(kernel_cache_metadata, "num_cpu_threads"): + kwargs_new["num_cpu_threads"] = ( + kernel_cache_metadata.num_cpu_threads + ) + + if hasattr(kernel_cache_metadata, "shared"): + if isinstance(kernel_cache_metadata.shared, bool): + kwargs_new["shared_memory_bytes"] = int( + kernel_cache_metadata.shared + ) + else: + kwargs_new["shared_memory_bytes"] = kernel_cache_metadata.shared + + # MTIA-specific parameters for triton kernel compilation + if hasattr(kernel_cache_metadata, "tile_width"): + kwargs_new["tile_width"] = kernel_cache_metadata.tile_width + if hasattr(kernel_cache_metadata, "tile_height"): + kwargs_new["tile_height"] = kernel_cache_metadata.tile_height + if hasattr(kernel_cache_metadata, "base_pe"): + kwargs_new["base_pe"] = kernel_cache_metadata.base_pe + + # Kernel parameter metadata for MTIA fatbin compilation + kwargs_new["kernel_param_names"] = [ + p.name for p in kernel.params if not p.is_constexpr + ] + # Use inferred signature types from the compiled kernel's ASTSource + # when available. The signature is populated at runtime with actual + # types like "i32", "*fp32" based on the values passed to the kernel + # (see specialize_impl in jit.py). Fall back to static annotations + # for architectures that don't rely on precise type information. + compiled_signature = getattr( + getattr(kernel_cache_entry, "src", None), "signature", None + ) + if compiled_signature is not None: + kwargs_new["kernel_param_types"] = [ + str(compiled_signature.get(p.name, p.annotation)) + for p in kernel.params + if not p.is_constexpr + ] + else: + # Default behavior: use static annotations (may be empty) + kwargs_new["kernel_param_types"] = [ + str(p.annotation) for p in kernel.params if not p.is_constexpr + ] + + ex_node = Node( + name=node.name, + target=self.serialize_operator(node.target), + inputs=inputs_new + + [ + NamedArgument( + name=name, + arg=self.serialize_input(a), + kind=ArgumentKind.KEYWORD, + ) + for name, a in kwargs_new.items() + ], + outputs=self.serialize_hoo_outputs(node), + metadata=self.serialize_metadata(node), + is_hop_single_tensor_return=_is_hop_single_tensor_return(node), + ) + else: + ex_node = Node( + name=node.name, + target=self.serialize_operator(node.target), + inputs=self.serialize_hoo_inputs(node.args, node.kwargs), + outputs=self.serialize_hoo_outputs(node), + metadata=self.serialize_metadata(node), + is_hop_single_tensor_return=_is_hop_single_tensor_return(node), + ) + elif type(node.target) in _serialization_registry: + # Sanity check for unhandled serialization. + if type(node.target) not in _serialization_registry: + raise AssertionError( + f"{type(node.target)} is not supported in export serialization." + ) + + handler = _serialization_registry[type(node.target)] + namespace = handler.namespace() + op_name = handler.to_op_name(node.target) + if not isinstance(namespace, str) or not isinstance(op_name, str): + raise AssertionError( + f"expected namespace and op_name to be str, got {type(namespace).__name__} and {type(op_name).__name__}" + ) + if ":" in namespace or ":" in op_name: + raise AssertionError( + f"namespace and op_name should not contain ':', got {namespace!r} and {op_name!r}" + ) + ex_node = Node( + name=node.name, + target=f"#{namespace}:{op_name}", + inputs=self.serialize_inputs(node.target, node.args, node.kwargs), + outputs=self.serialize_outputs(node), + metadata=self.serialize_metadata(node), + ) + elif callable(node.target): + # Handle predispatch wrapper functions (vmap, JVP, etc.) that appear + # as plain Python function call_function nodes in pre_dispatch graphs. + ex_node = Node( + name=node.name, + target=self.serialize_operator(node.target), + inputs=self.serialize_hoo_inputs(node.args, node.kwargs), + outputs=self.serialize_hoo_outputs(node), + metadata=self.serialize_metadata(node), + ) + else: + raise SerializeError(f"Serializing {node.target} is not supported") + + self.graph_state.nodes.append(ex_node) + + def handle_get_attr(self, node): + log.debug("[handle_get_attr] %s", node.name) + + def _output_node_at_index(self, node, index) -> torch.fx.Node | None: + user_node = None + for user in node.users: + if user.target is not operator.getitem: + raise AssertionError(f"{user} is not a getitem node") + if index == user.args[1]: + if user_node is None: + user_node = user + else: + # We want to deduplicate getitem nodes that are trying to + # index to the same index + self.duplicate_getitem_nodes[user.name] = user_node.name + return user_node + + def _output_node_name_at_index(self, node, index) -> str: + user_node = self._output_node_at_index(node, index) + if user_node is None: + return f"{node.name}_unused_{index}" + else: + return user_node.name + + def serialize_metadata(self, node: torch.fx.Node) -> dict[str, str]: + ret = {} + + if stack_trace := node.meta.get("stack_trace"): + ret["stack_trace"] = stack_trace + + if nn_module_stack := node.meta.get("nn_module_stack"): + + def export_nn_module_stack(val): + if not isinstance(val, tuple) or len(val) != 2: + val_len = len(val) if isinstance(val, tuple) else "N/A" + raise AssertionError( + f"expected tuple of length 2, got {type(val).__name__} of length {val_len}" + ) + path, ty = val + + if not isinstance(path, str): + raise AssertionError( + f"expected path to be str, got {type(path).__name__}" + ) + if not isinstance(ty, str): + raise AssertionError( + f"expected ty to be str, got {type(ty).__name__}" + ) + + return path + "," + ty + + # Serialize to "key,orig_path,type_str" + nn_module_list = [ + f"{k},{export_nn_module_stack(v)}" for k, v in nn_module_stack.items() + ] + ret["nn_module_stack"] = ST_DELIMITER.join(nn_module_list) + + if source_fn_st := node.meta.get("source_fn_stack"): + source_fn_list = [ + f"{source_fn[0]},{self.serialize_operator(source_fn[1])}" + for source_fn in source_fn_st + ] + ret["source_fn_stack"] = ST_DELIMITER.join(source_fn_list) + + if torch_fn := node.meta.get("torch_fn"): + ret["torch_fn"] = ST_DELIMITER.join(list(torch_fn)) + + if custom := node.meta.get("custom"): + try: + ret["custom"] = json.dumps(custom) + except Exception as e: + raise SerializeError( + f"Failed to serialize custom metadata for node {node.name} with error {e}" + ) from e + + if "from_node" in node.meta: + from_node = node.meta["from_node"] + # Serialize from_node as JSON since it's a complex nested structure + ret["from_node"] = json.dumps(self._serialize_from_node(from_node)) + + return ret + + def _serialize_from_node( + self, from_node: list[NodeSource] | None + ) -> list[dict[str, Any]] | None: + """ + Serialize from_node metadata from a list of NodeSource objects to a list of dictionaries. + """ + if from_node is None: + return None + + return [ + node_source.to_dict() + for node_source in from_node + if isinstance(node_source, NodeSource) + ] + + def serialize_script_obj_meta( + self, script_obj_meta: ep.CustomObjArgument + ) -> CustomObjArgument: + log.debug("[serialize_script_obj_meta] %s", script_obj_meta) + return CustomObjArgument( + name=script_obj_meta.name, + class_fqn=script_obj_meta.class_fqn, + ) + + def serialize_sym_op_inputs(self, op, args) -> list[NamedArgument]: + if isinstance(op, torch._ops.OpOverload): + args_names = [arg.name for arg in op._schema.arguments] + else: + if op not in _SYM_OPS: + raise AssertionError(f"op {op} is not in _SYM_OPS") + args_names = list(inspect.signature(op).parameters.keys()) + serialized_args = [] + for args_name, arg in zip(args_names, args): + serialized_args.append( + NamedArgument( + name=args_name, + arg=self.serialize_input(arg), + kind=ArgumentKind.POSITIONAL, + ) + ) + return serialized_args + + def serialize_inputs( + self, + target: Any, # torch._ops.OpOverload and other custom operator types. + args, + kwargs=None, + ) -> list[NamedArgument]: + schema = None + serialized_args = [] + + if isinstance(target, torch._higher_order_ops.torchbind.CallTorchBind): + obj = args[0] + method = args[1] + schema = target.schema(obj, method) + else: + if not isinstance( + target, (torch._ops.OpOverload, *_registered_extension_types()) + ): + raise AssertionError( + f"expected OpOverload or registered extension type, got {type(target).__name__}" + ) + schema = _get_schema_from_target(target) + if schema is None: + raise AssertionError("schema should not be None") + kwargs = kwargs or {} + + for i, schema_arg in enumerate(schema.arguments): + if schema_arg.name in kwargs: + serialized_args.append( + NamedArgument( + name=schema_arg.name, + arg=self.serialize_input( + kwargs[schema_arg.name], schema_arg.type + ), + kind=ArgumentKind.KEYWORD, + ) + ) + elif not schema_arg.kwarg_only and i < len(args): + serialized_args.append( + NamedArgument( + name=schema_arg.name, + arg=self.serialize_input(args[i], schema_arg.type), + kind=ArgumentKind.POSITIONAL, + ) + ) + else: + # We intentionally don't serialize the missing arguments + # with default values + pass + + return serialized_args + + def serialize_hoo_inputs(self, args, kwargs) -> list[NamedArgument]: + """ + For serializing HOO inputs since HOOs do not have a schema. + """ + inputs = [ + NamedArgument( + name="", arg=self.serialize_input(a), kind=ArgumentKind.POSITIONAL + ) + for a in args + ] + inputs.extend( + [ + NamedArgument( + name=name, + arg=self.serialize_input(a), + kind=ArgumentKind.KEYWORD, + ) + for name, a in kwargs.items() + ] + ) + return inputs + + def is_inductor_sym_int_arg(self, arg) -> bool: + # This is a special branch for handling SymInt args in inductor's + # ExternalFallbackNode. + # For regular FX graph, SymInt arg should be a fx.Node and should be + # verified with is_sym_int_arg() + return type(arg) is int or isinstance(arg, torch.SymInt) + + def is_sym_int_arg(self, arg) -> bool: + return type(arg) is int or ( + isinstance(arg, torch.fx.Node) + and arg.name in self.graph_state.sym_int_values + ) + + def is_sym_float_arg(self, arg) -> bool: + return isinstance(arg, float) or ( + isinstance(arg, torch.fx.Node) + and arg.name in self.graph_state.sym_float_values + ) + + def is_sym_bool_arg(self, arg) -> bool: + return isinstance(arg, bool) or ( + isinstance(arg, torch.fx.Node) + and arg.name in self.graph_state.sym_bool_values + ) + + # should be torch._C.JitType but that annotation is busted + def serialize_input(self, arg, arg_type: Any | None = None) -> Argument: + import torch._inductor.ir as inductor_ir + + inductor_tensor_buffers = ( + inductor_ir.Buffer, + inductor_ir.ReinterpretView, + ) + + if isinstance(arg, torch.fx.Node): + if arg.op == "get_attr": + if not isinstance(arg.target, str): + raise AssertionError( + f"expected arg.target to be str, got {type(arg.target).__name__}" + ) + attr = getattr(arg.graph.owning_module, arg.target) + + if isinstance(attr, torch.Tensor): + raise SerializeError( + "getattr nodes containing tensors should not appear in the graph" + ) + elif isinstance(attr, torch.fx.GraphModule): + with self.save_graph_state(): + graph = self.serialize_graph(attr) + return Argument.create( + as_graph=GraphArgument(name=arg.target, graph=graph) + ) + elif type(attr).__name__ == "LoweredBackendModule": + # Special handling for executorch_call_delegate HOP + # Its first argument is a LoweredBackendModule, for which we + # serialize name and backend id of the lowered module + module_name = getattr(attr, "module_name", None) + backend_id = getattr(attr, "backend_id", None) + if module_name is None: + raise AssertionError("module_name should not be None") + if backend_id is None: + raise AssertionError("backend_id should not be None") + return Argument.create(as_string=f"{module_name}-{backend_id}") + else: + raise SerializeError( + f"Unsupported getattr attribute {arg.target} with type: {type(attr)}" + ) + elif self.is_sym_int_arg(arg): + return Argument.create( + as_sym_int=SymIntArgument.create(as_name=arg.name) + ) + elif self.is_sym_float_arg(arg): + return Argument.create( + as_sym_float=SymFloatArgument.create(as_name=arg.name) + ) + elif self.is_sym_bool_arg(arg): + return Argument.create( + as_sym_bool=SymBoolArgument.create(as_name=arg.name) + ) + elif isinstance(arg.meta["val"], ep.CustomObjArgument): + return Argument.create( + as_custom_obj=CustomObjArgument( + name=arg.name, class_fqn=arg.meta["val"].class_fqn + ) + ) + elif arg.name in self.duplicate_getitem_nodes: + dedup_name = self.duplicate_getitem_nodes[arg.name] + return Argument.create(as_tensor=TensorArgument(name=dedup_name)) + else: + return Argument.create(as_tensor=TensorArgument(name=arg.name)) + elif isinstance(arg, inductor_tensor_buffers): + # Other branches are for arguments in fx node. + # This is a special branch for handling buffers (representing tensor arguments) + # for inductor's ExternalFallbackNode + # export_extern_kernel_node() is using this function to serialize arguments + arg_name = arg.get_name() + if arg_name is None: + raise AssertionError("Buffer must have valid name") + return Argument.create(as_tensor=TensorArgument(name=arg_name)) + elif isinstance(arg, inductor_ir.TorchBindObject): + # This is a special branch for handling TorchBindObject + # for inductor's ExternalFallbackNode + # export_extern_kernel_node() is using this function to serialize arguments + arg_name = arg.get_name() + if arg_name is None: + raise AssertionError("Buffer must have valid name") + arg_val = arg.get_real_obj() + class_fqn = arg_val._type().qualified_name() + self.custom_objs[arg_name] = arg_val + return Argument.create(as_custom_obj=CustomObjArgument(arg_name, class_fqn)) + elif isinstance(arg, torch.SymInt): + # This is a special branch for handling SymInt args in inductor's + # ExternalFallbackNode. + # For regular FX graph, SymInt arg should be a fx.Node with + # self.is_sym_int_arg(arg) being true + return Argument.create(as_sym_int=SymIntArgument.create(as_name=str(arg))) + elif isinstance(arg, torch.SymFloat): + # This is a special branch for handling SymFloat args in inductor's + # ExternalFallbackNode. + # For regular FX graph, SymInt arg should be a fx.Node with + # self.is_sym_float_arg(arg) being true + return Argument.create( + as_sym_float=SymFloatArgument.create(as_name=str(arg)) + ) + elif type(arg) is bool: + return Argument.create(as_bool=arg) + elif type(arg) is str: + return Argument.create(as_string=arg) + elif type(arg) is int: + return Argument.create(as_int=arg) + elif type(arg) is float: + return Argument.create(as_float=arg) + elif type(arg) is complex: + return Argument.create( + as_complex=ComplexValue(real=arg.real, imag=arg.imag) + ) + elif arg is None: + return Argument.create(as_none=True) + elif isinstance(arg, dict): + serialized_dict = {} + for key, value in arg.items(): + if not isinstance(key, str): + raise SerializeError(f"Dict keys must be strings, got {type(key)}") + serialized_dict[key] = self.serialize_input(value) + return Argument.create(as_string_to_argument=serialized_dict) + elif isinstance(arg, (list, tuple)): + if len(arg) == 0: + if arg_type is not None: + if isinstance(arg_type, torch.OptionalType): + arg_type = arg_type.getElementType() # type: ignore[assignment] + if not isinstance(arg_type, torch.ListType): + raise AssertionError( + f"expected ListType, got {type(arg_type).__name__}" + ) + elem_type = arg_type.getElementType() + if isinstance(elem_type, torch.OptionalType): + elem_type = elem_type.getElementType() + + if isinstance(elem_type, torch.BoolType): + return Argument.create(as_bools=[]) + elif isinstance(elem_type, torch.IntType): + return Argument.create(as_ints=[]) + elif isinstance(elem_type, torch.FloatType): + return Argument.create(as_floats=[]) + elif isinstance(elem_type, torch.StringType): + return Argument.create(as_strings=[]) + elif isinstance(elem_type, torch.TensorType): + return Argument.create(as_tensors=[]) + elif isinstance(elem_type, torch.ListType): + inner_elem_type = elem_type.getElementType() + if isinstance(inner_elem_type, torch.IntType): + return Argument.create(as_int_lists=[]) + elif isinstance(inner_elem_type, torch.FloatType): + return Argument.create(as_float_lists=[]) + else: + raise SerializeError( + f"Empty list with nested type {elem_type} nyi." + ) + else: + # I believe empty symint lists default to ints, but + # please file an issue if this is not the case + raise SerializeError(f"Empty list with type {elem_type} nyi.") + else: + # We could serialize this by default to a tensor list. This + # is needed in the HOO case + log.warning( + "Unsure how to serialize the given empty list, " + "as we don't know what is the type of this argument. " + "Serializing it as a tensor list by default." + ) + return Argument.create(as_tensors=[]) + + if all(type(a) is bool for a in arg): + return Argument.create(as_bools=list(arg)) + elif all(type(a) is int for a in arg): + return Argument.create(as_ints=list(arg)) + elif all(type(a) is float for a in arg): + return Argument.create(as_floats=list(arg)) + elif all(type(a) is str for a in arg): + return Argument.create(as_strings=list(arg)) + elif all(self.is_inductor_sym_int_arg(a) for a in arg): + # This is a special branch for handling SymInt args in inductor's + # ExternalFallbackNode. + # For regular FX graph, SymInt arg should be a fx.Node + values = [] + for a in arg: + if isinstance(a, torch.SymInt): + values.append(SymIntArgument.create(as_name=str(a))) + elif type(a) is int: + values.append(SymIntArgument.create(as_int=a)) + return Argument.create(as_sym_ints=values) + elif all(isinstance(a, torch.SymFloat) for a in arg): + return Argument.create( + as_sym_floats=[SymFloatArgument.create(as_name=str(a)) for a in arg] + ) + elif all(self.is_sym_int_arg(a) for a in arg): + # list of sym_ints + values = [] + for a in arg: + if isinstance(a, torch.fx.Node): + values.append(SymIntArgument.create(as_name=a.name)) + elif type(a) is int: + values.append(SymIntArgument.create(as_int=a)) + return Argument.create(as_sym_ints=values) + elif all(self.is_sym_float_arg(a) for a in arg): + # list of sym_float + values = [] + for a in arg: + if isinstance(a, torch.fx.Node): + values.append(SymFloatArgument.create(as_name=a.name)) + elif isinstance(a, float): + values.append(SymFloatArgument.create(as_float=a)) + return Argument.create(as_sym_floats=values) + elif all(self.is_sym_bool_arg(a) for a in arg): + # list of sym_bools + values = [] + for a in arg: + if isinstance(a, torch.fx.Node): + values.append(SymBoolArgument.create(as_name=a.name)) + elif isinstance(a, bool): + values.append(SymBoolArgument.create(as_bool=a)) + return Argument.create(as_sym_bools=values) + elif all(isinstance(a, torch.fx.Node) for a in arg): + # list of tensors + arguments = [] + for a in arg: + if a.op == "get_attr": + raise SerializeError( + "getattr nodes containing tensors should not appear in the graph" + ) + arguments.append(TensorArgument(name=a.name)) + return Argument.create(as_tensors=arguments) + elif all(isinstance(a, (list, tuple)) for a in arg) and all( + all(isinstance(t, torch.fx.Node) for t in inner) for inner in arg + ): + # nested list of tensors (List[List[Tensor]]) + nested_arguments = [] + for inner_list in arg: + inner_arguments = [] + for node in inner_list: + if node.op == "get_attr": + raise SerializeError( + "getattr nodes containing tensors should not appear in the graph" + ) + inner_arguments.append(TensorArgument(name=node.name)) + nested_arguments.append(inner_arguments) + return Argument.create(as_nested_tensors=nested_arguments) + elif all(isinstance(a, (torch.fx.Node, type(None))) for a in arg): + # list of optional tensors + def serialize_optional_tensor_args(a): + if a is None: + return OptionalTensorArgument.create(as_none=True) + elif isinstance(a, torch.fx.Node): + return OptionalTensorArgument.create( + as_tensor=TensorArgument(name=a.name) + ) + else: + raise SerializeError(f"Unsupported list/tuple argument: {a}") + + return Argument.create( + as_optional_tensors=list(map(serialize_optional_tensor_args, arg)) + ) + elif all(isinstance(a, inductor_tensor_buffers) for a in arg): + # list of inductor buffers + return Argument.create( + as_tensors=[TensorArgument(name=a.get_name()) for a in arg], + ) + elif all( + isinstance(a, (*inductor_tensor_buffers, type(None))) for a in arg + ): + # list of inductor buffers as optional tensors + def serialize_optional_tensor_args(a): + if a is None: + return OptionalTensorArgument.create(as_none=True) + elif isinstance(a, inductor_tensor_buffers): + return OptionalTensorArgument.create( + as_tensor=TensorArgument(name=a.get_name()) + ) + else: + raise SerializeError(f"Unsupported list/tuple argument: {a}") + + return Argument.create( + as_optional_tensors=list(map(serialize_optional_tensor_args, arg)) + ) + elif all( + isinstance(a, (list, tuple)) and all(type(x) is int for x in a) + for a in arg + ): + # list of int lists (List[List[int]]) + return Argument.create(as_int_lists=[list(t) for t in arg]) + elif all( + isinstance(a, (list, tuple)) and all(isinstance(x, float) for x in a) + for a in arg + ): + # list of float lists (List[List[float]]) + return Argument.create(as_float_lists=[list(t) for t in arg]) + else: + raise SerializeError( + f"Unsupported list/tuple argument type: {[type(a) for a in arg]}" + ) + elif isinstance(arg, torch.dtype): + return Argument.create(as_scalar_type=_TORCH_TO_SERIALIZE_DTYPE[arg]) + elif isinstance(arg, torch.device): + return Argument.create(as_device=Device(type=arg.type, index=arg.index)) + elif isinstance(arg, torch.memory_format): + return Argument.create( + as_memory_format=_TORCH_TO_SERIALIZE_MEMORY_FORMAT[arg] + ) + elif isinstance(arg, torch.layout): + return Argument.create(as_layout=_TORCH_TO_SERIALIZE_LAYOUT[arg]) + elif isinstance(arg, torch._C.ScriptObject): + if not ( + arg._has_method("__getstate__") # type: ignore[attr-defined] + and arg._has_method("__setstate__") # type: ignore[attr-defined] + ): + raise SerializeError( + f"Unable to serialize custom class {arg}. Please define " + "serialization methods via def_pickle()." + ) + # Custom objects through torchind are serializable with pickle, + # through implementing the .def_pickle function. This should result + # in the object containing a __getstate__ and __setstate__ + # serialize/deserialize function. + custom_obj_name = f"_custom_obj_{len(self.custom_objs)}" + self.custom_objs[custom_obj_name] = arg + class_fqn = arg._type().qualified_name() # type: ignore[attr-defined] + return Argument.create( + as_custom_obj=CustomObjArgument(custom_obj_name, class_fqn) + ) + elif is_custom_class_obj(arg): + custom_obj_name = f"_custom_obj_{len(self.custom_objs)}" + self.custom_objs[custom_obj_name] = arg + class_fqn = get_opaque_type_name(type(arg)) + return Argument.create( + as_custom_obj=CustomObjArgument(custom_obj_name, class_fqn) + ) + elif isinstance(arg, (torch._ops.OpOverload, torch._ops.HigherOrderOperator)): + return Argument.create(as_operator=self.serialize_operator(arg)) + else: + raise SerializeError( + f"Unsupported argument type: {type(arg)} with schema arg_type {arg_type}" + ) + + def serialize_tensor_output(self, name, meta_val) -> TensorArgument: + if name in self.graph_state.tensor_values: + raise AssertionError(f"name {name!r} already in tensor_values") + self.graph_state.tensor_values[name] = serialize_tensor_meta(meta_val) + return TensorArgument(name=name) + + def serialize_sym_int_output(self, name, meta_val) -> SymIntArgument: + if name in self.graph_state.sym_int_values: + raise AssertionError(f"name {name!r} already in sym_int_values") + self.graph_state.sym_int_values[name] = serialize_sym_int(meta_val) + return SymIntArgument.create(as_name=name) + + def serialize_sym_float_output(self, name, meta_val) -> SymFloatArgument: + if name in self.graph_state.sym_float_values: + raise AssertionError(f"name {name!r} already in sym_float_values") + self.graph_state.sym_float_values[name] = serialize_sym_float(meta_val) + return SymFloatArgument.create(as_name=name) + + def serialize_sym_bool_output(self, name, meta_val) -> SymBoolArgument: + if name in self.graph_state.sym_bool_values: + raise AssertionError(f"name {name!r} already in sym_bool_values") + self.graph_state.sym_bool_values[name] = serialize_sym_bool(meta_val) + return SymBoolArgument.create(as_name=name) + + def serialize_input_spec(self, spec: ep.InputSpec) -> InputSpec: + log.debug("[serialize_input_spec] %s", spec) + if spec.kind == ep.InputKind.USER_INPUT: + if isinstance(spec.arg, ep.ConstantArgument): + if type(spec.arg.value) is int: + constant_spec = ConstantValue.create(as_int=spec.arg.value) + elif type(spec.arg.value) is bool: + constant_spec = ConstantValue.create(as_bool=spec.arg.value) + elif type(spec.arg.value) is str: + constant_spec = ConstantValue.create(as_string=spec.arg.value) + elif type(spec.arg.value) is float: + constant_spec = ConstantValue.create(as_float=spec.arg.value) + elif spec.arg.value is None: + constant_spec = ConstantValue.create(as_none=True) + else: + raise SerializeError( + f"Unhandled constant input {spec.arg.value} to serialize" + ) + return InputSpec.create( + constant_input=InputToConstantInputSpec( + name=spec.arg.name, value=constant_spec + ) + ) + else: + return InputSpec.create( + user_input=UserInputSpec(arg=self.serialize_argument_spec(spec.arg)) + ) + elif spec.kind == ep.InputKind.PARAMETER: + if spec.target is None: + raise AssertionError("spec.target should not be None for PARAMETER") + if not isinstance(spec.arg, ep.TensorArgument): + raise AssertionError( + f"expected TensorArgument, got {type(spec.arg).__name__}" + ) + return InputSpec.create( + parameter=InputToParameterSpec( + arg=TensorArgument(name=spec.arg.name), + parameter_name=spec.target, + ) + ) + elif spec.kind == ep.InputKind.BUFFER: + if spec.target is None: + raise AssertionError("spec.target should not be None for BUFFER") + if not isinstance(spec.arg, ep.TensorArgument): + raise AssertionError( + f"expected TensorArgument, got {type(spec.arg).__name__}" + ) + if spec.persistent is None: + raise AssertionError("spec.persistent should not be None for BUFFER") + return InputSpec.create( + buffer=InputToBufferSpec( + arg=TensorArgument(name=spec.arg.name), + buffer_name=spec.target, + persistent=spec.persistent, + ) + ) + elif spec.kind == ep.InputKind.CONSTANT_TENSOR: + if spec.target is None: + raise AssertionError( + "spec.target should not be None for CONSTANT_TENSOR" + ) + if not isinstance(spec.arg, ep.TensorArgument): + raise AssertionError( + f"expected TensorArgument, got {type(spec.arg).__name__}" + ) + return InputSpec.create( + tensor_constant=InputToTensorConstantSpec( + arg=TensorArgument(name=spec.arg.name), + tensor_constant_name=spec.target, + ) + ) + elif spec.kind == ep.InputKind.CUSTOM_OBJ: + if spec.target is None: + raise AssertionError("spec.target should not be None for CUSTOM_OBJ") + if not isinstance(spec.arg, ep.CustomObjArgument): + raise AssertionError( + f"expected CustomObjArgument, got {type(spec.arg).__name__}" + ) + return InputSpec.create( + custom_obj=InputToCustomObjSpec( + arg=CustomObjArgument( + name=spec.arg.name, class_fqn=spec.arg.class_fqn + ), + custom_obj_name=spec.target, + ) + ) + elif spec.kind == ep.InputKind.TOKEN: + if not isinstance(spec.arg, ep.TokenArgument): + raise AssertionError( + f"expected TokenArgument, got {type(spec.arg).__name__}" + ) + return InputSpec.create( + token=InputTokenSpec( + arg=TokenArgument(name=spec.arg.name), + ) + ) + else: + raise AssertionError(f"Unknown argument kind: {spec}") + + def serialize_output_spec(self, spec: ep.OutputSpec) -> OutputSpec: + log.debug("[serialize_output_spec] %s", spec) + if spec.kind == ep.OutputKind.USER_OUTPUT: + return OutputSpec.create( + user_output=UserOutputSpec(arg=self.serialize_argument_spec(spec.arg)) + ) + elif spec.kind == ep.OutputKind.LOSS_OUTPUT: + if not isinstance(spec.arg, ep.TensorArgument): + raise AssertionError( + f"expected TensorArgument, got {type(spec.arg).__name__}" + ) + return OutputSpec.create( + loss_output=LossOutputSpec(arg=TensorArgument(name=spec.arg.name)) + ) + elif spec.kind == ep.OutputKind.BUFFER_MUTATION: + if spec.target is None: + raise AssertionError( + "spec.target should not be None for BUFFER_MUTATION" + ) + if not isinstance(spec.arg, ep.TensorArgument): + raise AssertionError( + f"expected TensorArgument, got {type(spec.arg).__name__}" + ) + return OutputSpec.create( + buffer_mutation=BufferMutationSpec( + arg=TensorArgument(name=spec.arg.name), + buffer_name=spec.target, + ) + ) + elif spec.kind == ep.OutputKind.PARAMETER_MUTATION: + if spec.target is None: + raise AssertionError( + "spec.target should not be None for PARAMETER_MUTATION" + ) + if not isinstance(spec.arg, ep.TensorArgument): + raise AssertionError( + f"expected TensorArgument, got {type(spec.arg).__name__}" + ) + return OutputSpec.create( + parameter_mutation=ParameterMutationSpec( + arg=TensorArgument(name=spec.arg.name), + parameter_name=spec.target, + ) + ) + elif spec.kind == ep.OutputKind.GRADIENT_TO_PARAMETER: + if spec.target is None: + raise AssertionError( + "spec.target should not be None for GRADIENT_TO_PARAMETER" + ) + if not isinstance(spec.arg, ep.TensorArgument): + raise AssertionError( + f"expected TensorArgument, got {type(spec.arg).__name__}" + ) + return OutputSpec.create( + gradient_to_parameter=GradientToParameterSpec( + arg=TensorArgument(name=spec.arg.name), + parameter_name=spec.target, + ) + ) + elif spec.kind == ep.OutputKind.GRADIENT_TO_USER_INPUT: + if spec.target is None: + raise AssertionError( + "spec.target should not be None for GRADIENT_TO_USER_INPUT" + ) + if not isinstance(spec.arg, ep.TensorArgument): + raise AssertionError( + f"expected TensorArgument, got {type(spec.arg).__name__}" + ) + return OutputSpec.create( + gradient_to_user_input=GradientToUserInputSpec( + arg=TensorArgument(name=spec.arg.name), + user_input_name=spec.target, + ) + ) + elif spec.kind == ep.OutputKind.USER_INPUT_MUTATION: + if spec.target is None: + raise AssertionError( + "spec.target should not be None for USER_INPUT_MUTATION" + ) + if not isinstance(spec.arg, ep.TensorArgument): + raise AssertionError( + f"expected TensorArgument, got {type(spec.arg).__name__}" + ) + return OutputSpec.create( + user_input_mutation=UserInputMutationSpec( + arg=TensorArgument(name=spec.arg.name), + user_input_name=spec.target, + ) + ) + elif spec.kind == ep.OutputKind.TOKEN: + if not isinstance(spec.arg, ep.TokenArgument): + raise AssertionError( + f"expected TokenArgument, got {type(spec.arg).__name__}" + ) + return OutputSpec.create( + token=OutputTokenSpec( + arg=TokenArgument(name=spec.arg.name), + ) + ) + else: + raise AssertionError(f"Unknown argument kind: {spec}") + + def serialize_signature(self, sig: ep.ExportGraphSignature) -> GraphSignature: + log.debug("\n[serialize_signature]") + return GraphSignature( + input_specs=[self.serialize_input_spec(s) for s in sig.input_specs], + output_specs=[self.serialize_output_spec(s) for s in sig.output_specs], + ) + + def serialize_argument_spec(self, x: ep.ArgumentSpec) -> Argument: + if isinstance(x, ep.TensorArgument): + return Argument.create(as_tensor=TensorArgument(name=x.name)) + elif isinstance(x, ep.SymIntArgument): + return Argument.create(as_sym_int=SymIntArgument.create(as_name=x.name)) + elif isinstance(x, ep.SymFloatArgument): + return Argument.create(as_sym_float=SymFloatArgument.create(as_name=x.name)) + elif isinstance(x, ep.ConstantArgument): + return self.serialize_input(x.value) + elif isinstance(x, ep.CustomObjArgument): + return Argument.create( + as_custom_obj=CustomObjArgument(name=x.name, class_fqn=x.class_fqn) + ) + else: + raise AssertionError("TODO") + + def serialize_treespec(self, treespec: pytree.TreeSpec) -> str: + # We want to additionally save all the field names of the namedtuples in + # case users want to check that the treespec types are equivalent + def store_namedtuple_fields(ts: pytree.TreeSpec) -> None: + if ts.type is None: + return + if ts.type is namedtuple or pytree.is_namedtuple_class(ts.type): + serialized_type_name = pytree.SUPPORTED_SERIALIZED_TYPES[ + ts.context + ].serialized_type_name + if serialized_type_name in self.treespec_namedtuple_fields: + field_names = self.treespec_namedtuple_fields[ + serialized_type_name + ].field_names + if field_names != ts.context._fields: + raise SerializeError( + f"The given TreeSpec's namedtuple type {ts.context} " + f"was found to have field names {ts.context._fields} " + f"but somehow previously was found to have field names {field_names}." + ) + else: + self.treespec_namedtuple_fields[serialized_type_name] = ( + NamedTupleDef(field_names=ts.context._fields) + ) + + for child in ts.children(): + store_namedtuple_fields(child) + + serialized_treespec = treespec_dumps(treespec, TREESPEC_VERSION) + store_namedtuple_fields(treespec) + return serialized_treespec + + def serialize_module_call_signature( + self, module_call_signature: ep.ModuleCallSignature + ) -> ModuleCallSignature: + log.debug("[serialize_module_call_signature] %s", module_call_signature) + return ModuleCallSignature( + inputs=[ + self.serialize_argument_spec(x) for x in module_call_signature.inputs + ], + outputs=[ + self.serialize_argument_spec(x) for x in module_call_signature.outputs + ], + in_spec=self.serialize_treespec(module_call_signature.in_spec), + out_spec=self.serialize_treespec(module_call_signature.out_spec), + forward_arg_names=( + names if (names := module_call_signature.forward_arg_names) else None + ), + ) + + def serialize_module_call_graph( + self, module_call_graph: list[ep.ModuleCallEntry] + ) -> list[ModuleCallEntry]: + log.debug("\n[serialize_module_call_graph]") + return [ + ModuleCallEntry( + fqn=entry.fqn, + signature=( + self.serialize_module_call_signature(entry.signature) + if entry.signature + else None + ), + ) + for entry in module_call_graph + ] + + def serialize_outputs(self, node: torch.fx.Node) -> list[Argument]: + """For a given node, return the dataclass representing its output values. + + [NOTE: Multiple outputs] We handle aggregates differently than FX. For + FX, it looks like: + + x = call_function("multiple_return", ...) + element0 = call_function(getitem, x, 0) + foo = call_function("use_output", element0) + + We do not want the intermediate `getitem` call, so our serialized thing looks like: + + element0, element1, element2 = call_function("multiple_return", ...) + foo = call_function("use_output", element0) + + We want names to be consistent across these two schemes, so that we can + mostly reuse the names coming from FX. This function computes a mapping from + the FX representation to our representation, preserving the names. + """ + + def _is_single_tensor_list_return(target: Any) -> bool: + schema = _get_schema_from_target(target) + returns = schema.returns + + if len(returns) != 1: + return False + return_type = returns[0].real_type + return isinstance(return_type, torch.ListType) and isinstance( + return_type.getElementType(), torch.TensorType + ) + + if not ( + node.op == "call_function" + and isinstance( + node.target, (torch._ops.OpOverload, *_registered_extension_types()) + ) + ): + raise AssertionError( + f"expected call_function with OpOverload or registered extension type, " + f"got {node.op} with {type(node.target).__name__}" + ) + + schema = _get_schema_from_target(node.target) + returns = schema.returns + + if len(returns) == 0: + return [] + + meta_val = node.meta["val"] + + # Check single value return + if _is_single_tensor_list_return(node.target): + # e.g "-> Tensor[]" + tensor_args = [] + for idx, meta in enumerate(meta_val): + name = self._output_node_name_at_index(node, idx) + tensor_args.append(self.serialize_tensor_output(name, meta)) + return [Argument.create(as_tensors=tensor_args)] + elif len(returns) == 1: + return [self.serialize_output(node.name, meta_val)] + + # There are a two possibilities at this point: + # - This operator returns a tuple of Tensors, e.g. "-> (Tensor, Tensor)" + # - This operator returns a tuple of mixed of Tensor and Tensors, e.g. "-> (Tensor, Tensor[])" + # + # Either way, start by gathering a list of TensorArguments with the correct names. + # For consistent naming with FX, consult the downstream `getitem` node and + # make sure our outputs have the same name. + + output_arguments = [] + for idx, (meta, return_schema) in enumerate(zip(meta_val, returns)): + if meta is None: + if not isinstance( + return_schema.real_type, (torch.OptionalType, torch.TensorType) + ): + raise AssertionError( + f"expected OptionalType or TensorType, got {type(return_schema.real_type).__name__}" + ) + # When the return type is annotated as Tensor type, the op can also return an + # undefined Tensor which will be implicitly converted to None in Python. + output_arguments.append(Argument.create(as_none=True)) + elif isinstance(meta, torch.Tensor): + if not isinstance( + return_schema.real_type, (torch.OptionalType, torch.TensorType) + ): + raise AssertionError( + f"expected OptionalType or TensorType, got {type(return_schema.real_type).__name__}" + ) + name = self._output_node_name_at_index(node, idx) + output_arguments.append(self.serialize_output(name, meta)) + elif isinstance(meta, list): + # for List[Tensor] return type + if not ( + isinstance(return_schema.real_type, torch.ListType) + and isinstance( + return_schema.real_type.getElementType(), torch.TensorType + ) + ): + raise AssertionError( + f"expected ListType with TensorType element, got {type(return_schema.real_type).__name__}" + ) + user_node = self._output_node_at_index(node, idx) + args = [] + for i, m in enumerate(meta): + if m is None: + continue + if user_node is None: + name = f"{node.name}_unused_{idx}_{i}" + else: + name = self._output_node_name_at_index(user_node, i) + args.append(self.serialize_tensor_output(name, m)) + output_arguments.append(Argument.create(as_tensors=args)) + elif isinstance(meta, (int, SymInt, float, SymFloat)): + user_node_name = self._output_node_name_at_index(node, idx) + output_arguments.append(self.serialize_output(user_node_name, meta)) + else: + raise ValueError( + f"Unhandled output type {type(meta)} from node {node.format_node()}" + ) + + return output_arguments + + def serialize_hoo_outputs(self, node: torch.fx.Node) -> list[Argument]: + """ + For serializing HOO outputs since HOOs do not have a schema. + """ + meta_val = node.meta["val"] + + if isinstance(meta_val, tuple): + outputs = [] + for i, element_meta_val in enumerate(meta_val): + user_node = self._output_node_at_index(node, i) + if isinstance(element_meta_val, list): + # e.g "-> Tensor[]" + tensors = [] + for j, m in enumerate(element_meta_val): + if not isinstance(m, torch.Tensor): + raise SerializeError( + f"Serialize list output with type {type(m)} nyi" + ) + + if user_node is None: + name = f"{node.name}_unused_{i}_{j}" + else: + name = self._output_node_name_at_index(user_node, j) + tensors.append(self.serialize_tensor_output(name, m)) + outputs.append(Argument.create(as_tensors=tensors)) + + else: + name = ( + user_node.name + if user_node is not None + else f"{node.name}_unused_{i}" + ) + + outputs.append(self.serialize_output(name, element_meta_val)) + + return outputs + elif isinstance(meta_val, dict): + tensor_args = [] + # use the dict key as the idx + for idx, meta in meta_val.items(): + if not isinstance(meta, torch.Tensor): + raise SerializeError( + f"Serialize list output with type {type(meta)} nyi" + ) + name = self._output_node_name_at_index(node, idx) + tensor_args.append(self.serialize_tensor_output(name, meta)) + return [Argument.create(as_tensors=tensor_args)] + else: + return [self.serialize_output(node.name, meta_val)] + + def serialize_output(self, name: str, meta_val: Any) -> Argument: + # Check single value return + if meta_val is None: + return Argument.create(as_none=True) + if isinstance(meta_val, torch.Tensor): + # e.g "-> Tensor" + return Argument.create( + as_tensor=self.serialize_tensor_output(name, meta_val) + ) + elif isinstance(meta_val, (bool, torch.SymBool)): + # e.g "-> SymBool" + return Argument.create( + as_sym_bool=self.serialize_sym_bool_output(name, meta_val) + ) + elif isinstance(meta_val, (int, torch.SymInt)): + # e.g "-> SymInt" + if isinstance(meta_val, bool): + raise AssertionError( + "meta_val should not be bool when returning SymInt" + ) + return Argument.create( + as_sym_int=self.serialize_sym_int_output(name, meta_val) + ) + elif isinstance(meta_val, (float, torch.SymFloat)): + # e.g "-> SymFloat" + return Argument.create( + as_sym_float=self.serialize_sym_float_output(name, meta_val) + ) + + # list outputs should've been handled earlier + raise SerializeError(f"Unable to serialize output {meta_val}") + + def _handle_getitem_users(self, node: torch.fx.Node) -> list[TensorArgument]: + meta_val = node.meta["val"] + + idx_to_name = {} + for user in node.users: + if user.target is not operator.getitem: + raise AssertionError(f"User node {user} of {node} is incorrect") + # pyrefly: ignore [unsupported-operation] + idx_to_name[user.args[1]] = user.name + + for idx, _ in enumerate(meta_val): + # FX does not emit a getitem node for any outputs that are unused. + # However, we need a name for them so that the number of outputs will + # correctly match the schema. Just assign a dummy name. + if idx not in idx_to_name: + # pyrefly: ignore [unsupported-operation] + idx_to_name[idx] = f"{node.name}_unused_{idx}" + + arg_list = [] + for i, element_meta_val in enumerate(meta_val): + arg_list.append( + # pyrefly: ignore [bad-index] + self.serialize_tensor_output(idx_to_name[i], element_meta_val) + ) + + return arg_list + + def serialize_graph(self, graph_module: torch.fx.GraphModule) -> Graph: + if not isinstance(graph_module, torch.fx.GraphModule): + raise AssertionError( + f"expected GraphModule, got {type(graph_module).__name__}" + ) + log.debug( + "[serialize_graph]\n\n%s", graph_module.print_readable(print_output=False) + ) + + for node in graph_module.graph.nodes: + try: + getattr(self, f"handle_{node.op}")(node) + except Exception as e: + raise SerializeError( + f"Failed serializing node {node} in graph: {node.format_node()}\n Original exception {traceback.format_exc()}" + ) from e + + return Graph( + inputs=self.graph_state.inputs, + nodes=self.graph_state.nodes, + tensor_values=self.graph_state.tensor_values, + sym_int_values=self.graph_state.sym_int_values, + sym_float_values=self.graph_state.sym_float_values, + sym_bool_values=self.graph_state.sym_bool_values, + custom_obj_values=self.graph_state.custom_obj_values, + outputs=self.graph_state.outputs, + is_single_tensor_return=self.graph_state.is_single_tensor_return, + ) + + def serialize_graph_module_metadata(self, meta: dict[str, Any]): + ret = {} + if custom := meta.get("custom"): + log.debug("\n[serialize_graph_module_metadata] %s", custom) + try: + ret["custom"] = json.dumps(custom) + except Exception as e: + raise SerializeError( + f"Failed to serialize custom metadata for graph with error {e}" + ) from e + + return ret + + def serialize(self, graph_module: torch.fx.GraphModule) -> GraphModule: + log.debug("\n[serialize]") + graph = self.serialize_graph(graph_module) + + return GraphModule( + graph=graph, + signature=self.serialize_signature(self.graph_signature), + module_call_graph=self.serialize_module_call_graph(self.module_call_graph), + metadata=self.serialize_graph_module_metadata(graph_module.meta), + treespec_namedtuple_fields=self.treespec_namedtuple_fields, + ) + + +@final +class ExportedProgramSerializer(metaclass=Final): + def __init__( + self, + opset_version: dict[str, int] | None = None, + pickle_protocol: int = DEFAULT_PICKLE_PROTOCOL, + ): + self.opset_version: dict[str, int] = {} + if opset_version: + self.opset_version.update(opset_version) + if "aten" not in self.opset_version: + self.opset_version["aten"] = torch._C._get_max_operator_version() + + self.pickle_protocol = pickle_protocol + + def serialize( + self, + exported_program: ep.ExportedProgram, + *, + serialize_state_dict: bool = True, + serialize_constants: bool = True, + serialize_example_inputs: bool = True, + ) -> _SerializedProgram: + """ + Args: + exported_program: Exported Program to serialize + """ + exported_program.validate() + + gm_serializer = GraphModuleSerializer( + exported_program.graph_signature, exported_program.module_call_graph + ) + serialized_graph_module = gm_serializer.serialize(exported_program.graph_module) + serialized_range_constraints = serialize_range_constraints( + exported_program.range_constraints + ) + + # TODO: Directly serialize exported_program.constants once + # CustomClassHolders get stored in the ExportedProgram rather than in + # the graph + constants: dict[str, Any] = gm_serializer.custom_objs.copy() + for n, t in exported_program.constants.items(): + if n in constants: + raise AssertionError(f"constant name {n!r} already exists in constants") + constants[n] = t + + serialized_ep = ExportedProgram( + graph_module=serialized_graph_module, + opset_version=self.opset_version, + range_constraints=serialized_range_constraints, + schema_version=SchemaVersion( + major=SCHEMA_VERSION[0], + minor=SCHEMA_VERSION[1], + ), + verifiers=[v.dialect for v in exported_program.verifiers], + torch_version=torch.__version__, + guards_code=exported_program._guards_code, + ) + + # Test canonical form is well defined. + canonicalize(serialized_ep, set(constants.keys())) + + # Proxy cannot be dumped, so we remove them. + new_state_dict = remove_proxy_from_state_dict( + exported_program.state_dict, in_place=False + ) + serialized_state_dict = b"" + if serialize_state_dict: + serialized_state_dict = serialize_torch_artifact( + new_state_dict, self.pickle_protocol + ) + + serialized_constants = b"" + if serialize_constants: + serialized_constants = serialize_torch_artifact( + constants, self.pickle_protocol + ) + + serialized_example_inputs = b"" + if serialize_example_inputs: + serialized_example_inputs = serialize_torch_artifact( + exported_program.example_inputs, self.pickle_protocol + ) + + return _SerializedProgram( + serialized_ep, + serialized_state_dict, + serialized_constants, + serialized_example_inputs, + ) + + +@final +class GraphModuleDeserializer(metaclass=Final): + @dataclasses.dataclass + class Result: + graph_module: torch.fx.GraphModule + signature: ep.ExportGraphSignature + module_call_graph: list[ep.ModuleCallEntry] + names_to_symbols: dict[str, sympy.Symbol] + state_dict: dict[str, torch.Tensor | torch.nn.Parameter] + constants: dict[str, _ConstantAttributeType] + example_inputs: tuple[tuple[torch.Tensor, ...], dict[str, Any]] | None + + def __init__(self) -> None: + self.serialized_name_to_node: dict[str, torch.fx.Node] = {} + self.serialized_name_to_meta: LazyMap = LazyMap() # str -> MetaType + self.graph = torch.fx.Graph() + self.module = torch.nn.Module() + + @contextmanager + def save_graph_module(self) -> Iterator[None]: + saved = ( + self.graph, + self.module, + self.serialized_name_to_node, + self.serialized_name_to_meta, + self.unbacked_symbols, + ) + self.graph = torch.fx.Graph() + self.module = torch.nn.Module() + self.serialized_name_to_node = {} + self.serialized_name_to_meta = LazyMap() + self.unbacked_symbols: set[sympy.Symbol] = set() + try: + yield + finally: + ( + self.graph, + self.module, + self.serialized_name_to_node, + self.serialized_name_to_meta, + self.unbacked_symbols, + ) = saved + + def deserialize_extension_operator(self, serialized_target: str): + namespace, op_name = serialized_target.split(":") + namespace = namespace[1:] # starting with # + handler = _deserialization_registry[namespace] + return handler.from_op_name(op_name) + + def deserialize_operator(self, serialized_target: str): + if serialized_target.startswith( + "_operator" + ): # TODO(zhxchen17) Follow up on this. + module = operator + serialized_target_names = serialized_target.split(".")[1:] + elif serialized_target.startswith("torch"): + module = torch # type: ignore[misc] + serialized_target_names = serialized_target.split(".")[1:] + elif serialized_target.startswith("math"): + module = math # type: ignore[misc] + serialized_target_names = serialized_target.split(".")[1:] + elif serialized_target.startswith("#"): + return self.deserialize_extension_operator(serialized_target) + else: # TODO(zhxchen17) Don't catch all here. + return serialized_target + + target = module + for name in serialized_target_names: + if not hasattr(target, name): + return serialized_target + else: + target = getattr(target, name) + return target + + def _parse_sym_expr( + self, expr_str: str, hint: int | bool | float | None = None + ) -> sympy.Expr: + """ + Parses and does bottom-up processing of sympy.Expr nodes, + populating ShapeEnv & caching symbols as needed. + """ + + def _process_sym_expr( + sym: sympy.Expr, hint: int | bool | float | None = None + ) -> sympy.Expr: + if sym.is_Integer or sym.is_Float or sym.is_Boolean: # base case + return sym + else: # recursive case + # important to use str(expr) and not _print_sympy(), + # str(expr) is key for self.symbol_name_to_range + expr_str = str(sym) + for arg in sym.args: + self._parse_sym_expr(arg) + # symbol caching + if expr_str in self.symbol_name_to_symbol: + sym = self.symbol_name_to_symbol[expr_str] + else: + self.symbol_name_to_symbol[expr_str] = sym + if isinstance(sym, sympy.Symbol) and symbolic_shapes.symbol_is_type( + sym, (SymT.UNBACKED_INT, SymT.UNBACKED_FLOAT) + ): + self.unbacked_symbols.add(sym) + # hints + if hint is not None and sym not in self.shape_env.backed_var_to_val: + self.shape_env.add_backed_var_to_val(sym, hint) # type: ignore[arg-type] + # ValueRanges + if vr := self.symbol_name_to_range.get(expr_str): + self.shape_env.constrain_symbol_range( + sym, + compiler_min=vr.lower, # type: ignore[arg-type] + compiler_max=vr.upper, # type: ignore[arg-type] + ) + # ShapeEnv meta + if isinstance(sym, sympy.Symbol): + self.shape_env.var_to_stack[sym] = CapturedTraceback.extract(skip=1) + return sym + + expr = sympy.sympify( + expr_str, + locals={**self.sympy_functions, **self.symbol_name_to_symbol}, + ) + return _process_sym_expr(expr, hint) + + def deserialize_sym_int(self, s: SymInt) -> int | torch.SymInt: + val = s.value + if s.type == "as_expr": + if val.hint is None: + hint = None + else: + if val.hint.type != "as_int": + raise AssertionError( + f"expected hint type 'as_int', got {val.hint.type!r}" + ) + hint = val.hint.value + + sym = self._parse_sym_expr(val.expr_str, hint) + return self.shape_env.create_symintnode(sym, hint=hint) + elif s.type == "as_int": + if type(val) is not int: + raise AssertionError(f"expected int, got {type(val).__name__}") + return val + else: + raise SerializeError( + f"SymInt has invalid field type {s.type} with value {s.value}" + ) + + def deserialize_sym_float(self, s: SymFloat) -> float | torch.SymFloat: + val = s.value + if s.type == "as_expr": + hint = val.hint.as_float if val.hint else None + sym = self._parse_sym_expr(val.expr_str, hint) + return self.shape_env.create_symfloatnode(sym, hint=hint) + elif s.type == "as_float": + if not isinstance(val, float): + raise AssertionError(f"expected float, got {type(val).__name__}") + return val + else: + raise SerializeError( + f"SymFloat has invalid field type {s.type} with value {s.value}" + ) + + def deserialize_sym_bool(self, s: SymBool) -> bool | torch.SymBool: + val = s.value + if s.type == "as_expr": + expr = self._parse_sym_expr(val.expr_str) + return self.shape_env.create_symboolnode(expr) + elif s.type == "as_bool": + if not isinstance(val, bool): + raise AssertionError(f"expected bool, got {type(val).__name__}") + return val + else: + raise SerializeError( + f"SymBool has invalid field type {s.type} with value {s.value}" + ) + + def deserialize_tensor_meta( + self, + tensor_meta: TensorMeta, + ) -> FakeTensor: + with self.fake_tensor_mode: + return cast( + FakeTensor, + torch.empty_strided( + tuple(self.deserialize_sym_int(val) for val in tensor_meta.sizes), # type: ignore[misc] + tuple(self.deserialize_sym_int(val) for val in tensor_meta.strides), # type: ignore[misc] + device=deserialize_device(tensor_meta.device), + dtype=_SERIALIZE_TO_TORCH_DTYPE[tensor_meta.dtype], + requires_grad=tensor_meta.requires_grad, + ), + ) + + def deserialize_script_obj_meta( + self, script_obj_meta: CustomObjArgument + ) -> ep.CustomObjArgument: + return ep.CustomObjArgument( + name=script_obj_meta.name, + class_fqn=script_obj_meta.class_fqn, + ) + + def deserialize_graph_output(self, output) -> torch.fx.Node | int | None: + if output.type == "as_tensor": + return self.serialized_name_to_node[output.as_tensor.name] + elif output.type == "as_sym_int": + return self.serialized_name_to_node[output.as_sym_int.as_name] + elif output.type == "as_sym_bool": + return self.serialized_name_to_node[output.as_sym_bool.as_name] + elif output.type == "as_sym_float": + return self.serialized_name_to_node[output.as_sym_float.as_name] + elif output.type == "as_int": + return output.as_int + elif output.type == "as_float": + return output.as_float + elif output.type == "as_bool": + return output.as_bool + elif output.type == "as_none": + return None + else: + raise SerializeError(f"Unable to deserialize output node {output}") + + def deserialize_graph(self, serialized_graph: Graph) -> torch.fx.Graph: + log.debug("\n[deserialize_graph]") + + # Handle the tensor metas. + for name, tensor_value in serialized_graph.tensor_values.items(): + log.debug("[deserialize_tensor_meta] %s (input): %s", name, tensor_value) + self.serialized_name_to_meta[name] = ( + lambda v=tensor_value: self.deserialize_tensor_meta(v) + ) + + for name, sym_int_value in serialized_graph.sym_int_values.items(): + log.debug("[deserialize_sym_int] %s (input): %s", name, sym_int_value) + self.serialized_name_to_meta[name] = ( + lambda v=sym_int_value: self.deserialize_sym_int(v) + ) + + for name, sym_float_value in serialized_graph.sym_float_values.items(): + log.debug("[deserialize_sym_float] %s (input): %s", name, sym_float_value) + self.serialized_name_to_meta[name] = ( + lambda v=sym_float_value: self.deserialize_sym_float(v) + ) + + for name, sym_bool_value in serialized_graph.sym_bool_values.items(): + log.debug("[deserialize_sym_bool] %s (input): %s", name, sym_bool_value) + self.serialized_name_to_meta[name] = ( + lambda v=sym_bool_value: self.deserialize_sym_bool(v) + ) + + for name, script_obj_meta in serialized_graph.custom_obj_values.items(): + log.debug("[deserialize_script_obj_meta] %s", script_obj_meta) + self.serialized_name_to_meta[name] = ( + lambda v=script_obj_meta: self.deserialize_script_obj_meta(v) + ) + + log.debug("\n[deserialize graph nodes]") + # Inputs: convert to placeholder nodes in FX. + for i, input_ in enumerate(serialized_graph.inputs): + log.debug("[deserialize input] %s", input_) + if input_.type in ("as_tensor", "as_custom_obj"): + node_name = input_.value.name + placeholder_node = self.graph.placeholder(node_name) + # FX might declare a name illegal (e.g. some nn.Modules use "input" as forward() arguments) + # we will overwrite it + placeholder_node.name = node_name + self.sync_fx_node(node_name, placeholder_node) + elif input_.type == "as_sym_int": + if input_.value.type == "as_name": + node_name = input_.value.as_name + placeholder_node = self.graph.placeholder(node_name) + # FX might declare a name illegal (e.g. some nn.Modules use "input" as forward() arguments) + # we will overwrite it + placeholder_node.name = node_name + self.sync_fx_node(node_name, placeholder_node) + else: + raise SerializeError( + f"Deserializing a constant symint {input_.value} as an input" + ) + elif input_.type in ( + "as_int", + "as_float", + "as_bool", + "as_none", + "as_string", + ): + node_name = self.signature.input_specs[i].arg.name or f"arg{i}" + placeholder_node = self.graph.placeholder(node_name) + placeholder_node.meta["val"] = self.deserialize_input(input_) + else: + raise SerializeError(f"Invalid input type {input_}") + + # Nodes: convert to call_function nodes. + for serialized_node in serialized_graph.nodes: + try: + target = self.deserialize_operator(serialized_node.target) + self.deserialize_node(serialized_node, target) + + except Exception as e: + raise SerializeError( + f"Failed deserializing node {serialized_node}\n Original exception {traceback.format_exc()}" + ) from e + + # Outputs: convert to a single `output` node. + outputs = [] + for output in serialized_graph.outputs: + log.debug("[deserialize output] %s", output) + outputs.append(self.deserialize_graph_output(output)) + + if serialized_graph.is_single_tensor_return: + if len(outputs) != 1: + raise AssertionError( + f"expected single output for single_tensor_return, got {len(outputs)}" + ) + outputs = outputs[0] # type: ignore[assignment] + else: + outputs = tuple(outputs) # type: ignore[assignment] + + output_node = self.graph.output(outputs) + + if serialized_graph.is_single_tensor_return: + first_arg = output_node.args[0] + if not isinstance(first_arg, torch.fx.Node): + raise AssertionError( + f"Expected Node for single tensor return, got {type(first_arg)}" + ) + output_node.meta["val"] = first_arg.meta["val"] + else: + first_arg = output_node.args[0] + if not isinstance(first_arg, (tuple, list)): + raise AssertionError( + f"Expected tuple/list for multi tensor return, got {type(first_arg)}" + ) + output_node.meta["val"] = tuple( + arg.meta["val"] if isinstance(arg, torch.fx.Node) else arg + for arg in first_arg + ) + + # recompute unbacked bindings + for node in self.graph.nodes: + if (val := node.meta.get("val")) is not None and ( + unbacked_bindings := symbolic_shapes._free_unbacked_symbols_with_path( + val, + (), + shape_env=self.shape_env, + pending=self.unbacked_symbols, + simplify=True, + ) + ): + node.meta["unbacked_bindings"] = unbacked_bindings + + if len(self.unbacked_symbols) != 0: + raise AssertionError( + f"expected no unbacked symbols, got {len(self.unbacked_symbols)}: {self.unbacked_symbols}" + ) + return self.graph + + def deserialize_node(self, serialized_node: Node, target: Callable) -> None: + def _is_single_tensor_return(target) -> bool: + schema = _get_schema_from_target(target) + returns = schema.returns + return len(returns) == 1 and isinstance( + returns[0].real_type, torch.TensorType + ) + + if ( + target in _SYM_OPS + or target + == torch.ops.aten.item.default # this can produce either SymInt or SymBool + ): + # BC: use serialized_node.name if available, otherwise fallback to original logic + name = ( + serialized_node.name + if serialized_node.name + else serialized_node.outputs[0].value.as_name + ) + args = self.deserialize_sym_op_inputs(serialized_node.inputs) + + fx_node = self.graph.create_node("call_function", target, args, {}, name) + self.deserialize_sym_op_outputs(serialized_node, fx_node) + elif ( + target + is torch._higher_order_ops.triton_kernel_wrap.triton_kernel_wrapper_functional + ): + raise SerializeError( + "deserialize nyi for torch._higher_order_ops.triton_kernel_wrap.triton_kernel_wrapper_functional" + ) + elif isinstance(target, torch._ops.HigherOrderOperator): + args, kwargs = self.deserialize_hoo_inputs(serialized_node.inputs) + metadata = self.deserialize_metadata(serialized_node.metadata) + for x in (*args, *kwargs.values()): + if isinstance(x, torch.fx.Node) and x.op == "get_attr": + # this means that we have deserialized a graph argument, but + # unfortunately the schema for it does not include metadata; + # so we reuse the metadata of the HOP call for such arguments + x.meta.update(metadata) + # If a serialized HOP node has a length=1 outputs of type `as_tensor``. + # There could be two cases: + # (1) The HOP node returns a single tensor + # (2) The HOP node returns a tuple containing a single tensor + # We distinguish (1) and (2) by the `is_single_tensor_return` + # field in the schema of Node + # For BC, getattr() will return True if `is_single_tensor_return` doesn't + # exist. This is because prior to adding `is_single_tensor_return`, + # only (1) could happen as we handle (2) with type `as_tensors` + # BC: use serialized_node.name if available, otherwise fallback to original logic + if serialized_node.name: + name = serialized_node.name + else: + name = ( + serialized_node.outputs[0].as_tensor.name + if len(serialized_node.outputs) == 1 + and hasattr(serialized_node.outputs[0], "as_tensor") + and getattr(serialized_node, "is_hop_single_tensor_return", True) + else None + ) + fx_node = self.graph.create_node( + "call_function", target, args, kwargs, name + ) + self.deserialize_outputs(serialized_node, fx_node) + fx_node.meta.update(metadata) + + elif isinstance( + target, (torch._ops.OpOverload, *_registered_extension_types()) + ): + # For convenience: if this node returns a single tensor, name the + # newly-created node after it. This ensures that these tensor values + # have names that are consistent with serialized. + # BC: use serialized_node.name if available, otherwise fallback to original logic + if serialized_node.name: + name = serialized_node.name + else: + name = ( + serialized_node.outputs[0].as_tensor.name + if _is_single_tensor_return(target) + else None # FX will generate a name for us. + ) + + args, kwargs = self.deserialize_inputs(target, serialized_node) + fx_node = self.graph.create_node( + "call_function", target, args, kwargs, name + ) + self.deserialize_outputs(serialized_node, fx_node) + elif callable(target): + # Handle predispatch wrapper functions (vmap, JVP, etc.) + args, kwargs = self.deserialize_hoo_inputs(serialized_node.inputs) + name = serialized_node.name if serialized_node.name else None + fx_node = self.graph.create_node( + "call_function", target, args, kwargs, name + ) + self.deserialize_outputs(serialized_node, fx_node) + else: + _additional_msg = ( + ( + f"We failed to resolve {target} to an operator. " + + "If it's a custom op/custom triton op, this is usually because the custom op is not registered" + + " when deserializing. Please import the custom op to register it before deserializing." + + " Otherwise, please file an issue on github." + ) + if isinstance(target, str) + else "" + ) + raise SerializeError( + _additional_msg + + f" Unsupported target type for node {serialized_node}: {type(target)}." + ) + + fx_node.meta.update(self.deserialize_metadata(serialized_node.metadata)) + log.debug( + "[deserialize_node] %s: %s(%s, {%s}) -> %s", + fx_node.name, + fx_node.target, + fx_node.args, + fx_node.kwargs, + fx_node.meta.get("val"), + ) + + # handle ShapeEnv asserts + if target is torch.ops.aten._assert_scalar.default: + if not isinstance((arg := fx_node.args[0]), bool): + expr = arg.meta["val"] # type: ignore[union-attr] + if isinstance(expr, torch.SymBool): + self.shape_env.guard_or_defer_runtime_assert( + expr.node.expr, "", fx_node + ) + elif target is torch.ops.aten.sym_constrain_range_for_size.default: + sym = fx_node.args[0].meta["val"] # type: ignore[union-attr] + if isinstance(sym, torch.SymInt): + self.shape_env._constrain_range_for_size(sym.node.expr) + + # handle nn_module_stack; serialization throws away empty dicts + if ( + fx_node.op not in ["placeholder", "output"] + and "nn_module_stack" not in fx_node.meta + ): + fx_node.meta["nn_module_stack"] = {} + + def deserialize_input_spec(self, i: InputSpec) -> ep.InputSpec: + log.debug("[deserialize_input_spec] %s", i) + if i.type == "user_input": + return ep.InputSpec( + kind=ep.InputKind.USER_INPUT, + arg=self.deserialize_argument_spec(i.user_input.arg), + target=None, + ) + elif i.type == "parameter": + return ep.InputSpec( + kind=ep.InputKind.PARAMETER, + arg=ep.TensorArgument(name=i.parameter.arg.name), + target=i.parameter.parameter_name, + ) + elif i.type == "buffer": + return ep.InputSpec( + kind=ep.InputKind.BUFFER, + arg=ep.TensorArgument(name=i.buffer.arg.name), + target=i.buffer.buffer_name, + persistent=i.buffer.persistent, + ) + elif i.type == "tensor_constant": + return ep.InputSpec( + kind=ep.InputKind.CONSTANT_TENSOR, + arg=ep.TensorArgument(name=i.tensor_constant.arg.name), + target=i.tensor_constant.tensor_constant_name, + ) + elif i.type == "custom_obj": + return ep.InputSpec( + kind=ep.InputKind.CUSTOM_OBJ, + arg=ep.CustomObjArgument( + name=i.custom_obj.arg.name, class_fqn=i.custom_obj.arg.class_fqn + ), + target=i.custom_obj.custom_obj_name, + ) + elif i.type == "token": + return ep.InputSpec( + kind=ep.InputKind.TOKEN, + arg=ep.TokenArgument(name=i.token.arg.name), + target=None, + ) + elif i.type == "constant_input": + return ep.InputSpec( + kind=ep.InputKind.USER_INPUT, + arg=ep.ConstantArgument( + name=i.constant_input.name, + value=self.deserialize_constant_input(i.constant_input.value), + ), + target=None, + ) + else: + raise AssertionError(f"Unknown input spec {i}") + + def deserialize_output_spec(self, o: OutputSpec) -> ep.OutputSpec: + log.debug("[deserialize_output_spec] %s", o) + if o.type == "user_output": + return ep.OutputSpec( + kind=ep.OutputKind.USER_OUTPUT, + arg=self.deserialize_argument_spec(o.user_output.arg), + target=None, + ) + elif o.type == "loss_output": + return ep.OutputSpec( + kind=ep.OutputKind.LOSS_OUTPUT, + arg=ep.TensorArgument(name=o.loss_output.arg.name), + target=None, + ) + elif o.type == "buffer_mutation": + return ep.OutputSpec( + kind=ep.OutputKind.BUFFER_MUTATION, + arg=ep.TensorArgument(name=o.buffer_mutation.arg.name), + target=o.buffer_mutation.buffer_name, + ) + elif o.type == "parameter_mutation": + return ep.OutputSpec( + kind=ep.OutputKind.PARAMETER_MUTATION, + arg=ep.TensorArgument(name=o.parameter_mutation.arg.name), + target=o.parameter_mutation.parameter_name, + ) + elif o.type == "gradient_to_parameter": + return ep.OutputSpec( + kind=ep.OutputKind.GRADIENT_TO_PARAMETER, + arg=ep.TensorArgument(name=o.gradient_to_parameter.arg.name), + target=o.gradient_to_parameter.parameter_name, + ) + elif o.type == "gradient_to_user_input": + return ep.OutputSpec( + kind=ep.OutputKind.GRADIENT_TO_USER_INPUT, + arg=ep.TensorArgument(name=o.gradient_to_user_input.arg.name), + target=o.gradient_to_user_input.user_input_name, + ) + elif o.type == "user_input_mutation": + return ep.OutputSpec( + kind=ep.OutputKind.USER_INPUT_MUTATION, + arg=ep.TensorArgument(name=o.user_input_mutation.arg.name), + target=o.user_input_mutation.user_input_name, + ) + elif o.type == "token": + return ep.OutputSpec( + kind=ep.OutputKind.TOKEN, + arg=ep.TokenArgument(name=o.token.arg.name), + target=None, + ) + else: + raise AssertionError(f"Unknown output spec {o}") + + def deserialize_signature(self, sig: GraphSignature) -> ep.ExportGraphSignature: + log.debug("\n[deserialize_signature]") + return ep.ExportGraphSignature( + input_specs=[self.deserialize_input_spec(i) for i in sig.input_specs], + output_specs=[self.deserialize_output_spec(o) for o in sig.output_specs], + ) + + def deserialize( + self, + serialized_graph_module: GraphModule, + serialized_state_dict: dict[str, torch.Tensor] | bytes, + constants: dict[str, Any] | bytes, + example_inputs: tuple[tuple[torch.Tensor, ...], dict[str, Any]] + | bytes + | None = None, + symbol_name_to_range: dict[str, symbolic_shapes.ValueRanges] | None = None, + ) -> Result: + global _CURRENT_DESERIALIZER + if _CURRENT_DESERIALIZER is not None: + raise AssertionError("_CURRENT_DESERIALIZER is already set") + _CURRENT_DESERIALIZER = self + try: + log.debug("\n[deserialize]") + self.shape_env = symbolic_shapes.ShapeEnv(assume_static_by_default=True) + self.fake_tensor_mode = FakeTensorMode( + allow_fallback_kernels=False, + allow_non_fake_inputs=True, + shape_env=self.shape_env, + ) + self.sympy_functions = { + # all torch.utils._sympy.functions should go here + # TODO(avik): find a better way to keep this collection in sync; + # e.g.., `exec('from torch.utils._sympy.functions import *', ...)` + # would work as long as the public API of that module is complete + "FloorDiv": torch.utils._sympy.functions.FloorDiv, + "ModularIndexing": torch.utils._sympy.functions.ModularIndexing, + "Where": torch.utils._sympy.functions.Where, + "PythonMod": torch.utils._sympy.functions.PythonMod, + "Mod": torch.utils._sympy.functions.Mod, + "CleanDiv": torch.utils._sympy.functions.CleanDiv, + "CeilToInt": torch.utils._sympy.functions.CeilToInt, + "FloorToInt": torch.utils._sympy.functions.FloorToInt, + "CeilDiv": torch.utils._sympy.functions.CeilDiv, + "LShift": torch.utils._sympy.functions.LShift, + "RShift": torch.utils._sympy.functions.RShift, + "PowByNatural": torch.utils._sympy.functions.PowByNatural, + "FloatPow": torch.utils._sympy.functions.FloatPow, + "FloatTrueDiv": torch.utils._sympy.functions.FloatTrueDiv, + "IntTrueDiv": torch.utils._sympy.functions.IntTrueDiv, + "IsNonOverlappingAndDenseIndicator": torch.utils._sympy.functions.IsNonOverlappingAndDenseIndicator, + "TruncToFloat": torch.utils._sympy.functions.TruncToFloat, + "TruncToInt": torch.utils._sympy.functions.TruncToInt, + "RoundToInt": torch.utils._sympy.functions.RoundToInt, + "RoundDecimal": torch.utils._sympy.functions.RoundDecimal, + "ToFloat": torch.utils._sympy.functions.ToFloat, + "Identity": torch.utils._sympy.functions.Identity, + } + self.symbol_name_to_symbol: dict[str, sympy.Symbol] = {} + self.constants = deserialize_torch_artifact(constants) + self.signature = self.deserialize_signature( + serialized_graph_module.signature + ) + + # deserialization does analysis with checks on 0/1, so we create fake range constraints and + # restore the original range constraints afterwards + self.symbol_name_to_range = {} + # we also need to bump unbacked sym[float,int] counters in the + # shape env to accommodate unbacked symbols in the exported program + self.unbacked_symbols = set() + count_unbacked_symfloat, count_unbacked_symint = -1, -1 + unbacked_symfloat_prefix, unbacked_symint_prefix = ( + prefix_str[t] for t in [SymT.UNBACKED_FLOAT, SymT.UNBACKED_INT] + ) + if symbol_name_to_range: + for k, vr in symbol_name_to_range.items(): + lower = vr.lower + self.symbol_name_to_range[k] = symbolic_shapes.ValueRanges( + _int_to_sympy_int(lower, -int_oo), vr.upper + ) + if k.startswith(unbacked_symfloat_prefix): + i = int(k[len(unbacked_symfloat_prefix) :]) + count_unbacked_symfloat = max(count_unbacked_symfloat, i) + elif k.startswith(unbacked_symint_prefix): + i = int(k[len(unbacked_symint_prefix) :]) + count_unbacked_symint = max(count_unbacked_symint, i) + + # TODO(pianpwk): if we can clean up unused symbols in range_constraints, + # then this logic can just be handled with self.unbacked_symbols alone + for _ in range(count_unbacked_symfloat + 1): + self.shape_env.unbacked_symfloat_counter += 1 + for _ in range(count_unbacked_symint + 1): + self.shape_env.unbacked_symint_counter += 1 + + if example_inputs is not None and len(example_inputs) > 0: + self.example_inputs = deserialize_torch_artifact(example_inputs) + else: + self.example_inputs = None + self.deserialize_graph(serialized_graph_module.graph) + + with _enable_graph_inputs_of_type_nn_module(self.example_inputs): + module_call_graph = self.deserialize_module_call_graph( + serialized_graph_module.module_call_graph + ) + graph_module = ep._create_graph_module_for_export(self.module, self.graph) + meta = {} + if custom := serialized_graph_module.metadata.get("custom"): + meta["custom"] = json.loads(custom) + if hasattr(serialized_graph_module, "treespec_namedtuple_fields"): + meta["treespec_namedtuple_fields"] = {} + for ( + type_, + fields, + ) in serialized_graph_module.treespec_namedtuple_fields.items(): + meta["treespec_namedtuple_fields"][type_] = fields.field_names + graph_module.meta = meta + return GraphModuleDeserializer.Result( + graph_module=graph_module, + signature=self.signature, + module_call_graph=module_call_graph, + names_to_symbols=self.symbol_name_to_symbol, + state_dict=deserialize_torch_artifact(serialized_state_dict), + constants=self.constants, + example_inputs=self.example_inputs, + ) + finally: + _CURRENT_DESERIALIZER = None + + def sync_fx_node(self, name: str, fx_node: torch.fx.Node): + if name in self.serialized_name_to_node: + raise SerializeError(f"Node {name} has already been deserialized before.") + # overwrite name + fx_node.name = name + self.serialized_name_to_node[name] = fx_node + if "val" in fx_node.meta: + raise AssertionError(f"fx_node {name} already has 'val' in meta") + fx_node.meta["val"] = self.serialized_name_to_meta[name] + + def deserialize_sym_op_inputs(self, inputs): + return tuple(self.deserialize_input(input.arg) for input in inputs) + + def deserialize_inputs(self, target, serialized_node: Node): + schema_args = _get_schema_from_target(target).arguments + argument_kinds = {input.name: input.kind for input in serialized_node.inputs} + actual_args = { + input.name: self.deserialize_input(input.arg) + for input in serialized_node.inputs + } + args = [] + kwargs: OrderedDict[str, Any] = OrderedDict() + for schema_arg in schema_args: + if schema_arg.name in actual_args: + arg = actual_args[schema_arg.name] + kind = argument_kinds[schema_arg.name] + if kind == ArgumentKind.POSITIONAL: + args.append(arg) + continue + elif kind == ArgumentKind.KEYWORD and not keyword.iskeyword( + schema_arg.name + ): + kwargs[schema_arg.name] = arg + continue + + # If there's no ArgumentKind found, fallback to the old cases. + is_positional = ( + not schema_arg.has_default_value() and not schema_arg.kwarg_only + ) + if is_positional: + args.append(actual_args[schema_arg.name]) + elif keyword.iskeyword(schema_arg.name): + if schema_arg.kwarg_only: + raise AssertionError( + f"schema_arg {schema_arg.name} should not be kwarg_only" + ) + if len(kwargs) > 0: + kwargs = OrderedDict() + args.extend(list(kwargs.values())) + args.append(actual_args[schema_arg.name]) + else: + if schema_arg.name in actual_args: + kwargs[schema_arg.name] = actual_args[schema_arg.name] + return tuple(args), kwargs + + def deserialize_hoo_inputs(self, inputs: list[NamedArgument]): + """ + For deserializing HOO inputs since HOOs do not have a schema. + """ + args = [] + kwargs = {} + for input_ in inputs: + if input_.kind == ArgumentKind.POSITIONAL or input_.name == "": + args.append(self.deserialize_input(input_.arg)) + else: + kwargs[input_.name] = self.deserialize_input(input_.arg) + return (tuple(args), kwargs) + + def deserialize_input(self, inp: Argument) -> Any: + value = inp.value + typ_ = inp.type + if typ_ == "as_none": + # None should converted as None, but is encoded as bool in serialized + # Convert serialized object to torch equivalent + return None + elif typ_ == "as_tensor": + return self.serialized_name_to_node[inp.as_tensor.name] + elif typ_ == "as_scalar_type": + return _SERIALIZE_TO_TORCH_DTYPE[inp.as_scalar_type] + elif typ_ == "as_memory_format": + return _SERIALIZE_TO_TORCH_MEMORY_FORMAT[inp.as_memory_format] + elif typ_ == "as_layout": + return _SERIALIZE_TO_TORCH_LAYOUT[inp.as_layout] + elif typ_ == "as_graph": + if not isinstance(value, GraphArgument): + raise AssertionError( + f"expected GraphArgument, got {type(value).__name__}" + ) + with self.save_graph_module(): + self.deserialize_graph(value.graph) + submodule = ep._create_graph_module_for_export(self.module, self.graph) + self.module.register_module(value.name, submodule) + return self.graph.create_node( + "get_attr", + value.name, + name=value.name, + ) + elif typ_ == "as_device": + return deserialize_device(inp.as_device) + elif typ_ == "as_int": + return inp.as_int + elif typ_ == "as_float": + return inp.as_float + elif typ_ == "as_bool": + return inp.as_bool + elif typ_ == "as_string": + return inp.as_string + elif typ_ == "as_complex": + return complex(inp.as_complex.real, inp.as_complex.imag) + elif typ_ == "as_sym_int": + return self.deserialize_sym_argument(inp.as_sym_int) + elif typ_ == "as_sym_float": + return self.deserialize_sym_argument(inp.as_sym_float) + elif typ_ == "as_sym_bool": + return self.deserialize_sym_argument(inp.as_sym_bool) + elif isinstance(value, dict): + if typ_ == "as_string_to_argument": + # Deserialize dict[str, Argument] recursively + return {k: self.deserialize_input(v) for k, v in value.items()} + else: + raise SerializeError(f"Unknown dict type: {typ_}") + elif isinstance(value, list): + if len(value) == 0: + return [] + elif typ_ == "as_tensors": + result = [self.serialized_name_to_node[arg.name] for arg in value] + return result + elif typ_ in ("as_ints", "as_floats", "as_bools", "as_strings"): + # convert from serialized.python.types.List to python list + return list(value) + elif typ_ == "as_int_lists": + # Convert list of lists back to list of tuples for Triton grids + return [tuple(dims) for dims in value] + elif typ_ == "as_float_lists": + return [list(floats) for floats in value] + elif typ_ == "as_nested_tensors": + # nested list of tensors (List[List[Tensor]]) + return [ + [self.serialized_name_to_node[arg.name] for arg in inner_list] + for inner_list in value + ] + elif typ_ in ("as_sym_ints", "as_sym_bools", "as_sym_floats"): + return [self.deserialize_sym_argument(arg) for arg in value] + elif typ_ == "as_optional_tensors": + + def deserialize_optional_tensor_args(a): + if a.type == "as_none": + return None + elif a.type == "as_tensor": + return self.serialized_name_to_node[a.value.name] + else: + raise SerializeError(f"Unhandled argument {inp}") + + return list(map(deserialize_optional_tensor_args, value)) + else: + raise SerializeError(f"Unhandled argument {inp}") + elif typ_ == "as_custom_obj": + if inp.as_custom_obj.name in self.serialized_name_to_node: + # Custom object has been lifted as an input + return self.serialized_name_to_node[inp.as_custom_obj.name] + return self.constants[inp.as_custom_obj.name] + elif typ_ == "as_operator": + return self.deserialize_operator(inp.as_operator) + else: + raise SerializeError(f"Unhandled argument {inp}") + + def deserialize_constant_input(self, inp: ConstantValue) -> Any: + if inp.type == "as_int": + return int(inp.as_int) + elif inp.type == "as_float": + return float(inp.as_float) + elif inp.type == "as_string": + return str(inp.as_string) + elif inp.type == "as_bool": + return bool(inp.as_bool) + elif inp.type == "as_none": + return None + else: + raise SerializeError(f"Unhandled constant argument {inp} to deserialize") + + def deserialize_sym_argument(self, sym_arg): + if isinstance(sym_arg, SymIntArgument): + if sym_arg.type == "as_int": + return sym_arg.as_int + elif sym_arg.type == "as_name": + return self.serialized_name_to_node[sym_arg.as_name] + elif isinstance(sym_arg, SymFloatArgument): + if sym_arg.type == "as_float": + return sym_arg.as_float + elif sym_arg.type == "as_name": + return self.serialized_name_to_node[sym_arg.as_name] + elif isinstance(sym_arg, SymBoolArgument): + if sym_arg.type == "as_bool": + return sym_arg.as_bool + elif sym_arg.type == "as_name": + return self.serialized_name_to_node[sym_arg.as_name] + raise SerializeError(f"Unknown symbolic argument type: {sym_arg}") + + def deserialize_sym_op_outputs(self, serialized_node: Node, fx_node: torch.fx.Node): + self.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node) + + def deserialize_outputs(self, serialized_node: Node, fx_node: torch.fx.Node): + # Check single value return + if len(serialized_node.outputs) == 0: + return + + if ( + len(serialized_node.outputs) == 1 + and "torch.ops.higher_order" in serialized_node.target + and not getattr(serialized_node, "is_hop_single_tensor_return", True) + and serialized_node.outputs[0].type != "as_none" + ): + + def _deserialize_hop_with_single_return(serialized_node, fx_node): + meta_val: list[Any] = [] + arg = None + if serialized_node.outputs[0].type == "as_tensor": + arg = serialized_node.outputs[0].as_tensor + elif isinstance( + serialized_node.outputs[0].value, + (SymIntArgument, SymBoolArgument, SymFloatArgument), + ): + arg = serialized_node.outputs[0].value + deserialized_metadata = self.deserialize_metadata( + serialized_node.metadata + ) + if arg is None: + raise AssertionError("arg should not be None") + # pyrefly: ignore [bad-argument-type] + self.generate_getitem(meta_val, fx_node, arg, 0, deserialized_metadata) + fx_node.meta["val"] = tuple(meta_val) + self.serialized_name_to_node[fx_node.name] = fx_node + return + + return _deserialize_hop_with_single_return(serialized_node, fx_node) + + if ( + len(serialized_node.outputs) == 1 + and serialized_node.outputs[0].type == "as_tensor" + ): + self.sync_fx_node(serialized_node.outputs[0].as_tensor.name, fx_node) + return + elif len(serialized_node.outputs) == 1 and isinstance( + serialized_node.outputs[0].value, + (SymIntArgument, SymBoolArgument, SymFloatArgument), + ): + self.sync_fx_node(serialized_node.outputs[0].value.as_name, fx_node) + return + elif ( + len(serialized_node.outputs) == 1 + and serialized_node.outputs[0].type == "as_none" + ): + # manually rename the node to a unused name to avoid naming conflicts + fx_node.meta["val"] = None + fx_node._rename(f"{self.graph._target_to_str(fx_node.target)}_unused") + return + + self.deserialize_multiple_outputs(serialized_node, fx_node) + + def generate_getitem( + self, + meta_val, + fx_node: torch.fx.Node, + arg: TensorArgument | SymIntArgument | SymFloatArgument, + idx: int, + deserialized_metadata: dict[str, Any], + ): + if isinstance(arg, TensorArgument): + name = arg.name + elif isinstance(arg, SymIntArgument): + name = arg.as_name + elif isinstance(arg, SymFloatArgument): + name = arg.as_name + else: + raise AssertionError( + f"generate_getitem got unknown argument type {type(arg)}" + ) + individual_output = self.graph.create_node( + "call_function", + operator.getitem, + (fx_node, idx), + name=name, + ) + self.sync_fx_node(name, individual_output) + meta_val.append(self.serialized_name_to_meta[name]) + # The derived `getitem` nodes should have the same stacktrace as the + # original `fx_node` + individual_output.meta.update(deserialized_metadata) + + def generate_getitems( + self, + meta_val, + fx_node: torch.fx.Node, + args, + deserialized_metadata: dict[str, Any], + ): + for idx, arg in enumerate(args): + if isinstance(arg, (TensorArgument, SymIntArgument, SymFloatArgument)): + self.generate_getitem( + meta_val, fx_node, arg, idx, deserialized_metadata + ) + continue + + if not isinstance(arg, Argument): + raise AssertionError(f"expected Argument, got {type(arg).__name__}") + if arg.type in ("as_tensor", "as_sym_int", "as_sym_float"): + self.generate_getitem( + meta_val, fx_node, arg.value, idx, deserialized_metadata + ) + elif arg.type in ( + "as_tensors", + "as_sym_ints", + "as_sym_floats", + "as_ints", + "as_floats", + "as_strings", + "as_bools", + "as_sym_bools", + ): + list_output = self.graph.create_node( + "call_function", + operator.getitem, + (fx_node, idx), + ) + meta_val.append([]) + self.generate_getitems( + meta_val[-1], list_output, arg.value, deserialized_metadata + ) + list_output.meta.update(deserialized_metadata) + list_output.meta["val"] = meta_val[-1] + elif arg.type == "as_none": + individual_output = self.graph.create_node( + "call_function", + operator.getitem, + (fx_node, idx), + name="as_none", + ) + meta_val.append(None) + individual_output.meta["val"] = None + individual_output.meta.update(deserialized_metadata) + else: + raise NotImplementedError(f"Unimplemented node output type: {arg}") + + def deserialize_multiple_outputs( + self, serialized_node: Node, fx_node: torch.fx.Node + ) -> None: + deserialized_metadata = self.deserialize_metadata(serialized_node.metadata) + + # Convert multiple return types to FX format. + # In FX, each node only returns one value. So in order to represent + # multiple return values, we have to emit a `getitem` node for each + # return value. + # This performs the inverse mapping of the `serialize_outputs` call in + # serialization, see [NOTE: Multiple outputs] + meta_val: list[Any] = [] + if len(serialized_node.outputs) == 1: + if not isinstance(serialized_node.outputs[0].value, list): + raise AssertionError( + f"expected list, got {type(serialized_node.outputs[0].value).__name__}" + ) + if not isinstance(serialized_node.outputs[0].value[0], TensorArgument): + raise AssertionError( + f"expected TensorArgument, got {type(serialized_node.outputs[0].value[0]).__name__}" + ) + self.generate_getitems( + meta_val, + fx_node, + serialized_node.outputs[0].as_tensors, + deserialized_metadata, + ) + else: + self.generate_getitems( + meta_val, fx_node, serialized_node.outputs, deserialized_metadata + ) + + # also update the metaval for `fx_node` to be a list(meta) + fx_node.meta["val"] = tuple(meta_val) + self.serialized_name_to_node[fx_node.name] = fx_node + + def deserialize_metadata(self, metadata: dict[str, str]) -> dict[str, Any]: + ret: dict[str, Any] = {} + if stack_trace := metadata.get("stack_trace"): + ret["stack_trace"] = stack_trace + + def deserialize_meta_func(serialized_target: str): + module = None + if serialized_target.startswith("torch.nn"): + module = torch.nn + serialized_target_names = serialized_target.split(".")[2:] + elif serialized_target.startswith("torch"): + module = torch + serialized_target_names = serialized_target.split(".")[1:] + else: + return self.deserialize_operator(serialized_target) + + target = module + for name in serialized_target_names: + if not hasattr(target, name): + return serialized_target + else: + target = getattr(target, name) + return target + + if nn_module_stack_str := metadata.get("nn_module_stack"): + # Originally serialized to "key,orig_path,type_str" + def import_nn_module_stack(key, path, ty): + return key, (path, ty) + + # Helper function to split string by commas, accounting for nested parentheses/brackets + def metadata_split(metadata): + out = [] + start, n = 0, 0 + a, b = "[(", ")]" + for end, c in enumerate(metadata): + if c in a: + n += 1 + elif c in b: + n -= 1 + elif c == "," and n == 0: + out.append(metadata[start:end]) + start = end + 1 + out.append(metadata[start:]) + if len(out) != 3: + raise AssertionError( + f"expected metadata_split to return 3 parts, got {len(out)}" + ) + return out + + nn_module_stack = dict( + import_nn_module_stack(*metadata_split(item)) + for item in nn_module_stack_str.split(ST_DELIMITER) + ) + ret["nn_module_stack"] = nn_module_stack + + if source_fn_st_str := metadata.get("source_fn_stack"): + # Originally serializes to "fx_node_name,op_str" + source_fn_st = [] + for source_fn_str in source_fn_st_str.split(ST_DELIMITER): + name, target_str = source_fn_str.split(",") + source_fn_st.append((name, deserialize_meta_func(target_str))) + ret["source_fn_stack"] = source_fn_st + + if torch_fn_str := metadata.get("torch_fn"): + ret["torch_fn"] = tuple(torch_fn_str.split(ST_DELIMITER)) + + if custom_str := metadata.get("custom"): + ret["custom"] = json.loads(custom_str) + + if from_node_str := metadata.get("from_node"): + ret["from_node"] = self._deserialize_from_node(json.loads(from_node_str)) + + return ret + + def _deserialize_from_node( + self, from_node_data: list[dict[str, Any]] | None + ) -> list[NodeSource] | None: + """ + Deserialize from_node metadata from JSON data. + """ + if from_node_data is None: + return None + + if not isinstance(from_node_data, list): + raise AssertionError(f"expected list, got {type(from_node_data).__name__}") + + return [ + node_source + for fn_dict in from_node_data + if (node_source := NodeSource._from_dict(fn_dict)) is not None + ] + + def deserialize_argument_spec(self, x: Argument) -> ep.ArgumentSpec: + log.debug("[deserialize_argument_spec] %s", x) + if x.type == "as_tensor": + return ep.TensorArgument(name=x.as_tensor.name) + elif x.type == "as_sym_int": + return ep.SymIntArgument(name=x.as_sym_int.as_name) + elif x.type == "as_sym_float": + return ep.SymFloatArgument(name=x.as_sym_float.as_name) + elif x.type == "as_custom_obj": + return ep.ConstantArgument( + name=x.as_custom_obj.name, value=self.deserialize_input(x) + ) + else: + return ep.ConstantArgument(name="", value=self.deserialize_input(x)) + + def deserialize_module_call_signature( + self, module_call_signature: ModuleCallSignature + ) -> ep.ModuleCallSignature: + return ep.ModuleCallSignature( + inputs=[ + self.deserialize_argument_spec(x) for x in module_call_signature.inputs + ], + outputs=[ + self.deserialize_argument_spec(x) for x in module_call_signature.outputs + ], + in_spec=treespec_loads(module_call_signature.in_spec), + out_spec=treespec_loads(module_call_signature.out_spec), + forward_arg_names=( + names if (names := module_call_signature.forward_arg_names) else None + ), + ) + + def deserialize_module_call_graph( + self, module_call_graph: list[ModuleCallEntry] + ) -> list[ep.ModuleCallEntry]: + log.debug("\n[deserialize_module_call_graph]") + return [ + ep.ModuleCallEntry( + fqn=entry.fqn, + signature=( + self.deserialize_module_call_signature(entry.signature) + if entry.signature + else None + ), + ) + for entry in module_call_graph + ] + + +@final +class ExportedProgramDeserializer(metaclass=Final): + def __init__(self, expected_opset_version: dict[str, int] | None = None): + self.expected_opset_version: dict[str, int] = {} + if expected_opset_version: + self.expected_opset_version.update(expected_opset_version) + if "aten" not in self.expected_opset_version: + self.expected_opset_version["aten"] = torch._C._get_max_operator_version() + + def deserialize_range_constraints( + self, + symbol_name_to_range: dict[str, symbolic_shapes.ValueRanges], + symbol_name_to_symbol: dict[str, sympy.Symbol], + ) -> dict[sympy.Symbol, ValueRanges]: + log.debug("\n[deserialize_range_constraints]") + range_constraints = {} + for k, v in symbol_name_to_range.items(): + if symbol := symbol_name_to_symbol.get(k): + log.debug("[deserialize_range_constraints] %s -> %s", k, v) + range_constraints[symbol] = v # type: ignore[arg-type] + else: + log.warning( + "Symbol %s did not appear in the graph that was deserialized", k + ) + return range_constraints + + def deserialize( + self, + exported_program: ExportedProgram, + state_dict: dict[str, torch.Tensor] | bytes, + constants: dict[str, torch.Tensor] | bytes, + example_inputs: tuple[tuple[torch.Tensor, ...], dict[str, Any]] + | bytes + | None = None, + *, + _unsafe_skip_version_check=False, + ) -> ep.ExportedProgram: + if not isinstance(exported_program, ExportedProgram): + raise AssertionError( + f"expected ExportedProgram, got {type(exported_program).__name__}" + ) + version = exported_program.schema_version + + # TODO(zhxchen17) blocked on thrift schema refactor + if version.major != SCHEMA_VERSION[0] and not ( + version.major == 0 and version.minor == 0 + ): + if not _unsafe_skip_version_check: + raise SerializeError( + f"Serialized schema version {exported_program.schema_version} " + f"does not match our current schema version {SCHEMA_VERSION}." + ) + + symbol_name_to_range = { + k: symbolic_shapes.ValueRanges( + _int_to_sympy_int(v.min_val, -int_oo), + _int_to_sympy_int(v.max_val, int_oo), + ) + for k, v in exported_program.range_constraints.items() + } + res = GraphModuleDeserializer().deserialize( + exported_program.graph_module, + state_dict, + constants, + example_inputs, + symbol_name_to_range, + ) + range_constraints = self.deserialize_range_constraints( + symbol_name_to_range, + res.names_to_symbols, + ) + + result = ep.ExportedProgram( + root=res.graph_module, + graph=res.graph_module.graph, + graph_signature=res.signature, + state_dict=res.state_dict, # type: ignore[arg-type] + range_constraints=range_constraints, + module_call_graph=res.module_call_graph, + example_inputs=res.example_inputs, + constants=res.constants, + verifiers=[load_verifier(v) for v in exported_program.verifiers], + ) + result._guards_code = exported_program.guards_code + log.debug("\n[deserialize]: %s", result) + return result + + +class EnumEncoder(json.JSONEncoder): + def default(self, obj): + if isinstance(obj, Enum): + return obj.value + if isinstance(obj, bytes): + return base64.b64encode(obj).decode("utf-8") + return super().default(obj) + + +def _dataclass_to_dict(obj): + if isinstance(obj, _Union): + return {obj.type: _dataclass_to_dict(obj.value)} + elif dataclasses.is_dataclass(obj): + return { + f.name: _dataclass_to_dict(getattr(obj, f.name)) + for f in dataclasses.fields(obj) + } + elif isinstance(obj, list): + return [_dataclass_to_dict(x) for x in obj] + elif isinstance(obj, tuple): + return tuple(_dataclass_to_dict(x) for x in obj) + elif isinstance(obj, dict): + return {k: _dataclass_to_dict(v) for k, v in obj.items()} + elif isinstance(obj, float): + if obj == math.inf: + return "Infinity" + elif obj == -math.inf: + return "-Infinity" + elif math.isnan(obj): + return "NaN" + else: + return obj + else: + return obj + + +def _to_json_bytes(obj: Any) -> bytes: + return json.dumps(_dataclass_to_dict(obj), cls=EnumEncoder, allow_nan=False).encode( + "utf-8" + ) + + +def serialize( + exported_program: ep.ExportedProgram, + opset_version: dict[str, int] | None = None, + pickle_protocol: int = DEFAULT_PICKLE_PROTOCOL, + *, + serialize_state_dict: bool = True, + serialize_constants: bool = True, + serialize_example_inputs: bool = True, +) -> SerializedArtifact: + with _enable_graph_inputs_of_type_nn_module(exported_program.example_inputs): + serialized_program = ExportedProgramSerializer( + opset_version, pickle_protocol + ).serialize( + exported_program, + serialize_state_dict=serialize_state_dict, + serialize_constants=serialize_constants, + serialize_example_inputs=serialize_example_inputs, + ) + if not isinstance(serialized_program.exported_program, ExportedProgram): + raise AssertionError( + f"expected ExportedProgram, got {type(serialized_program.exported_program).__name__}" + ) + + json_bytes = _to_json_bytes(serialized_program.exported_program) + artifact = SerializedArtifact( + json_bytes, + serialized_program.state_dict, + serialized_program.constants, + serialized_program.example_inputs, + ) + return artifact + + +def _resolve_schema_cls(cls): + if isinstance(cls, str): + resolved = getattr(schema, cls, None) + if resolved is not None: + return resolved + if isinstance(cls, typing.ForwardRef): + return _resolve_schema_cls(cls.__forward_arg__) + return cls + + +def _dict_to_dataclass(cls, data): + cls = _resolve_schema_cls(cls) + if isinstance(cls, str): + raise AssertionError(f"Unresolved class type: '{cls}'.") + if typing.get_origin(cls) is Annotated: + return _dict_to_dataclass(cls.__origin__, data) + if typing.get_origin(cls) in (typing.Union, types.UnionType) and type( + None + ) in typing.get_args(cls): + if data is None: + return None + ty_args = typing.get_args(cls) + if len(ty_args) != 2: + raise AssertionError(f"expected 2 type args, got {len(ty_args)}") + return _dict_to_dataclass(ty_args[0], data) + elif isinstance(cls, type) and issubclass(cls, _Union): + if not isinstance(data, dict): + raise AssertionError(f"expected dict, got {type(data).__name__}") + if len(data) != 1: + raise AssertionError(f"expected dict with 1 key, got {len(data)}") + _type = next(iter(data.keys())) + _value = next(iter(data.values())) + if not isinstance(_type, str): + raise AssertionError(f"expected str key, got {type(_type).__name__}") + type_hints = typing.get_type_hints(cls, globalns=vars(schema)) + field_type = type_hints[_type] + # pyrefly: ignore [missing-attribute] + return cls.create(**{_type: _dict_to_dataclass(field_type, _value)}) + elif dataclasses.is_dataclass(cls): + fields = {} + type_hints = typing.get_type_hints(cls, globalns=vars(schema)) + # For forward compatibility consideration, we ignore all the keys + # that are not showing up in the dataclass definition. + for f in dataclasses.fields(cls): + name = f.name + if name not in data: + continue + new_field_obj = _dict_to_dataclass(type_hints[name], data[name]) + fields[name] = new_field_obj + return cls(**fields) # type: ignore[operator] + elif isinstance(data, list): + if len(data) == 0: + return data + d_type = typing.get_args(cls)[0] + return [_dict_to_dataclass(d_type, d) for d in data] + elif isinstance(data, dict): + v_type = typing.get_args(cls)[1] + return {k: _dict_to_dataclass(v_type, v) for k, v in data.items()} + elif cls is float: + return float(data) + return data + + +def _bytes_to_dataclass(cls: Any, artifact_bytes: bytes) -> Any: + artifact_str = artifact_bytes.decode("utf-8") + artifact_dict = json.loads(artifact_str) + artifact_dataclass = _dict_to_dataclass(cls, artifact_dict) + return artifact_dataclass + + +def deserialize( + artifact: SerializedArtifact, + expected_opset_version: dict[str, int] | None = None, + *, + _unsafe_skip_version_check=False, +) -> ep.ExportedProgram: + if not isinstance(artifact.exported_program, bytes): + raise AssertionError( + f"expected bytes, got {type(artifact.exported_program).__name__}" + ) + serialized_exported_program = _bytes_to_dataclass( + ExportedProgram, artifact.exported_program + ) + return ExportedProgramDeserializer(expected_opset_version).deserialize( + serialized_exported_program, + artifact.state_dict, + artifact.constants, + artifact.example_inputs, + _unsafe_skip_version_check=_unsafe_skip_version_check, + ) + + +def _canonicalize_graph( + sorted_inputs, sorted_outputs, graph, constants +) -> tuple[Graph, dict[str, str]]: + def _get_argument(a: Argument): + if a.type == "as_none": + return None + elif a.type == "as_tensor": + return a.as_tensor + elif a.type == "as_tensors": + return a.as_tensors + elif a.type == "as_int": + return None + elif a.type == "as_ints": + return None + elif a.type == "as_float": + return None + elif a.type == "as_floats": + return None + elif a.type == "as_string": + return None + elif a.type == "as_strings": + return None + elif a.type == "as_complex": + return None + elif a.type == "as_sym_int": + return a.as_sym_int + elif a.type == "as_sym_ints": + return a.as_sym_ints + elif a.type == "as_sym_float": + return a.as_sym_float + elif a.type == "as_sym_floats": + return a.as_sym_floats + elif a.type == "as_scalar_type": + return None + elif a.type == "as_memory_format": + return None + elif a.type == "as_layout": + return None + elif a.type == "as_device": + return None + elif a.type == "as_bool": + return None + elif a.type == "as_bools": + return None + elif a.type == "as_sym_bool": + return a.as_sym_bool + elif a.type == "as_sym_bools": + return a.as_sym_bools + elif a.type == "as_graph": + return None + elif a.type == "as_optional_tensors": + return a.as_optional_tensors + elif a.type == "as_custom_obj": + return a.as_custom_obj + elif a.type == "as_operator": + return None + elif a.type == "as_int_lists": + return None + elif a.type == "as_float_lists": + return None + elif a.type == "as_string_to_argument": + return None + elif a.type == "as_nested_tensors": + return a.as_nested_tensors + else: + raise AssertionError(f"Unknown input type to the ExportedProgram: {a}") + + # Stage 1: Reorder named items. + def for_args(f, a): + if not isinstance(a, Argument): + raise AssertionError(f"expected Argument, got {type(a).__name__}") + pytree.tree_map(f, _get_argument(a)) + + def sort_nodes(nodes): + @dataclass + class Edges: + outs: list[int] + ins: int + + graph_inputs: set[str] = set() + def_table: dict[str, int] = {} + edges: dict[int, Edges] = {} + candidates: list[tuple[str, list[tuple[str, list[int]]], int]] = [] + rank: dict[str, int] = {} + ret: list[Node] = [] + + def get_name(a) -> str | None: + if a is None: + return None + if isinstance(a, TensorArgument): + return a.name + elif isinstance(a, (SymIntArgument, SymBoolArgument, SymFloatArgument)): + if a.type == "as_name": + return a.as_name + elif a.type in ("as_int", "as_bool", "as_float"): + return None + else: + raise AssertionError(f"Unknown argument type: {a}") + elif isinstance(a, OptionalTensorArgument): + if a.type == "as_tensor": + return a.as_tensor.name + elif a.type == "as_none": + return None + else: + raise AssertionError(f"Unknown optional tensor type: {a}") + elif isinstance(a, CustomObjArgument): + return a.name + else: + raise AssertionError(f"Unknown argument type: {a}") + + for i in sorted_inputs: + + def add_input(a): + if s := get_name(a): + graph_inputs.add(s) + + for_args(add_input, i) + + for idx, node in enumerate(nodes): + + def add_def(a): + if s := get_name(a): + if s in def_table: + raise AssertionError(f"symbol {s!r} already in def_table") + def_table[s] = idx + + for o in node.outputs: + for_args(add_def, o) + + edges[idx] = Edges([], 0) + + for idx, user in enumerate(nodes): + + def add_edge(a): + if s := get_name(a): + if s in constants: + return + if s not in def_table: + if s not in graph_inputs: + raise AssertionError( + f"symbol {s!r} not in def_table or graph_inputs" + ) + return + src = def_table[s] + edges[src].outs.append(idx) + edges[idx].ins += 1 + + for i in user.inputs: + for_args(add_edge, i.arg) + + def add_rank(a): + if s := get_name(a): + if s in rank: + raise AssertionError(f"symbol {s!r} already in rank") + rank[s] = len(rank) + + def get_rank(a): + s = get_name(a) + if s and s not in constants: + return rank[s] + else: + return -1 + + for i in sorted_inputs: + for_args(add_rank, i) + + def add_candidate(idx: int): + def get_ranks(i): + ranks = [] + for_args(lambda x: ranks.append(get_rank(x)), i) + return ranks + + node = nodes[idx] + args_rank = [(a.name, get_ranks(a.arg)) for a in node.inputs] + heapq.heappush(candidates, (node.target, args_rank, idx)) + + for idx, e in edges.items(): + if e.ins == 0: + add_candidate(idx) + + while len(candidates) > 0: + _, _, idx = heapq.heappop(candidates) + node = nodes[idx] + for o in node.outputs: + for_args(add_rank, o) + ret.append(node) + if idx not in edges: + raise AssertionError(f"idx {idx} not in edges") + for user in edges[idx].outs: + e = edges[user] + if e.ins <= 0: + raise AssertionError(f"e.ins should be > 0, got {e.ins}") + e.ins -= 1 + if e.ins == 0: + add_candidate(user) + edges[idx].outs.clear() + + return ret + + sorted_nodes = sort_nodes(graph.nodes) + if len(sorted_nodes) != len(graph.nodes): + raise AssertionError( + f"expected {len(graph.nodes)} sorted nodes, got {len(sorted_nodes)}" + ) + + # Stage 2: Rename nodes. + name_table: dict[str, str] = {} + + def rename_def(a): + def _rename(arg_name, values): + new_name = f"_{len(name_table)}" + if arg_name in name_table: + raise AssertionError(f"arg_name {arg_name!r} already in name_table") + name_table[arg_name] = new_name + if arg_name not in values: + raise AssertionError(f"arg_name {arg_name!r} not in values") + values[new_name] = values.pop(arg_name) + return new_name + + if a is None: + return + if isinstance(a, TensorArgument): + a.name = _rename(a.name, graph.tensor_values) + elif isinstance(a, SymIntArgument): + if a.type == "as_name": + a.as_name = _rename(a.as_name, graph.sym_int_values) + elif isinstance(a, SymFloatArgument): + if a.type == "as_name": + a.as_name = _rename(a.as_name, graph.sym_float_values) + elif isinstance(a, SymBoolArgument): + if a.type == "as_name": + a.as_name = _rename(a.as_name, graph.sym_bool_values) + elif isinstance(a, CustomObjArgument): + a.name = _rename(a.name, graph.custom_obj_values) + else: + raise AssertionError(f"Unknown argument type: {a}") + + def replace_use(a): + if a is None: + return + if isinstance(a, TensorArgument): + a.name = name_table.get(a.name, a.name) + elif isinstance(a, (SymIntArgument, SymFloatArgument)): + if a.type == "as_name": + a.as_name = name_table.get(a.as_name, a.as_name) + elif isinstance(a, SymBoolArgument): + if a.type == "as_name": + a.as_name = name_table.get(a.as_name, a.as_name) + elif isinstance(a, OptionalTensorArgument): + if a.type == "as_tensor": + a.as_tensor.name = name_table.get(a.as_tensor.name, a.as_tensor.name) + elif isinstance(a, CustomObjArgument): + a.name = name_table.get(a.name, a.name) + else: + raise AssertionError(f"Unknown argument type: {a}") + + for i in sorted_inputs: + for_args(rename_def, i) + + for n in sorted_nodes: + for o in n.outputs: + for_args(rename_def, o) + + for n in sorted_nodes: + for i in n.inputs: + for_args(replace_use, i.arg) + + for o in sorted_outputs: + for_args(replace_use, o) + + # Stage 3: Remove unstable fields. + for n in sorted_nodes: + n.metadata.clear() + + # Stage 4: Aggregate values. + # pyrefly: ignore [no-matching-overload] + sorted_tensor_values = dict( + sorted(graph.tensor_values.items(), key=operator.itemgetter(0)) + ) + # pyrefly: ignore [no-matching-overload] + sorted_sym_int_values = dict( + sorted(graph.sym_int_values.items(), key=operator.itemgetter(0)) + ) + # pyrefly: ignore [no-matching-overload] + sorted_sym_float_values = dict( + sorted(graph.sym_float_values.items(), key=operator.itemgetter(0)) + ) + # pyrefly: ignore [no-matching-overload] + sorted_sym_bool_values = dict( + sorted(graph.sym_bool_values.items(), key=operator.itemgetter(0)) + ) + # pyrefly: ignore [no-matching-overload] + sorted_custom_obj_values = dict( + sorted(graph.custom_obj_values.items(), key=operator.itemgetter(0)) + ) + + # Stage 5: Recurse in subgraphs. + counter = 0 + for node in sorted_nodes: + for i in node.inputs: + a = i.arg + if a.type == "as_graph": + a.as_graph.graph, _ = _canonicalize_graph( + a.as_graph.graph.inputs, + a.as_graph.graph.outputs, + a.as_graph.graph, + constants, + ) + a.as_graph.name = f"_g{counter}" + counter += 1 + + graph = Graph( + inputs=sorted_inputs, + outputs=sorted_outputs, + nodes=sorted_nodes, + tensor_values=sorted_tensor_values, + sym_int_values=sorted_sym_int_values, + sym_float_values=sorted_sym_float_values, + sym_bool_values=sorted_sym_bool_values, + is_single_tensor_return=graph.is_single_tensor_return, + custom_obj_values=sorted_custom_obj_values, + ) + return graph, name_table + + +def canonicalize( + ep: ExportedProgram, constants: set[str] | None = None +) -> ExportedProgram: + """ + Normalize a serialized ExportedProgram, so that different eager program which + shares the same semantics can get a single representation on disk. + + This function canonicalizes an ExportedProgram by: + + 1. Sorting nodes in topological order. + 2. Rename nodes to have unique names. + 3. Remove unstable fields. + 4. Aggregate the above program fields. + 5. Recurse in subgraphs. + + Args: + ep (ExportedProgram): The ExportedProgram to canonicalize. + constants (Optional[set[str]]): Set of constants names + + Returns: + ExportedProgram: The canonicalized exported program. + """ + ep = copy.deepcopy(ep) + # pyrefly: ignore [annotation-mismatch, redefinition] + constants: set[str] = constants or set() + + opset_version = dict(sorted(ep.opset_version.items(), key=operator.itemgetter(0))) + range_constraints = dict( + sorted(ep.range_constraints.items(), key=operator.itemgetter(0)) + ) + guards_code = sorted(ep.guards_code) + module_call_graph = sorted(ep.graph_module.module_call_graph, key=lambda x: x.fqn) + signature = ep.graph_module.signature + graph = ep.graph_module.graph + + if len(graph.inputs) != len(signature.input_specs): + raise AssertionError( + f"graph.inputs length {len(graph.inputs)} != signature.input_specs length {len(signature.input_specs)}" + ) + if len(graph.outputs) != len(signature.output_specs): + raise AssertionError( + f"graph.outputs length {len(graph.outputs)} != signature.output_specs length {len(signature.output_specs)}" + ) + + def rank_input(inp) -> tuple[int, str | None, int]: + idx, (_arg, spec) = inp + if not isinstance(spec, InputSpec): + raise AssertionError(f"expected InputSpec, got {type(spec).__name__}") + if spec.type == "user_input": + return 5, None, idx + elif spec.type == "parameter": + return 1, spec.parameter.parameter_name, idx + elif spec.type == "buffer": + return 2, spec.buffer.buffer_name, idx + elif spec.type == "tensor_constant": + return 3, spec.tensor_constant.tensor_constant_name, idx + elif spec.type == "custom_obj": + return 4, spec.custom_obj.custom_obj_name, idx + elif spec.type == "token": + return 0, None, idx + elif spec.type == "constant_input": + return 6, spec.constant_input.name, idx + else: + raise AssertionError(f"Unknown input type: {spec}") + + def rank_output(out) -> tuple[int, str | None, int]: + idx, (_arg, spec) = out + if not isinstance(spec, OutputSpec): + raise AssertionError(f"expected OutputSpec, got {type(spec).__name__}") + if spec.type == "user_output": + return 4, None, idx + elif spec.type == "loss_output": + return 4, None, idx + elif spec.type == "parameter_mutation": + return 1, spec.parameter_mutation.parameter_name, idx + elif spec.type == "buffer_mutation": + return 2, spec.buffer_mutation.buffer_name, idx + elif spec.type == "gradient_to_parameter": + return 5, spec.gradient_to_parameter.parameter_name, idx + elif spec.type == "gradient_to_user_input": + return 6, None, idx + elif spec.type == "user_input_mutation": + return 3, None, idx + elif spec.type == "token": + return 0, None, idx + else: + raise AssertionError(f"Unknown output type: {spec}") + + sorted_ins = sorted( + enumerate(zip(graph.inputs, signature.input_specs)), key=rank_input + ) + + if len(sorted_ins) > 0: + sorted_inputs, input_specs = zip(*(i for idx, i in sorted_ins)) # type: ignore[assignment] + else: + sorted_inputs = () + input_specs = () + + sorted_outs = sorted( + enumerate(zip(graph.outputs, signature.output_specs)), key=rank_output + ) + sorted_outputs, output_specs = zip(*(i for idx, i in sorted_outs)) # type: ignore[assignment] + + sorted_graph, replace_table = _canonicalize_graph( + sorted_inputs, sorted_outputs, graph, constants + ) + + def replace_input(spec): + if not isinstance(spec, InputSpec): + raise AssertionError(f"expected InputSpec, got {type(spec).__name__}") + if spec.type == "user_input": + arg = spec.user_input.arg + if arg.type == "as_tensor": + t = arg.as_tensor + t.name = replace_table[t.name] + elif arg.type == "as_sym_int": + s = arg.as_sym_int + if s.type == "as_name": + s.as_name = replace_table[s.as_name] + elif s.type == "as_int": + pass + else: + raise AssertionError(f"Unknown sym_int type: {s}") + elif arg.type == "as_sym_float": + f = arg.as_sym_float + if f.type == "as_name": + f.as_name = replace_table[f.as_name] + elif f.type == "as_float": + pass + else: + raise AssertionError(f"Unknown sym_float type: {f}") + elif arg.type in ( + "as_none", + "as_bool", + "as_int", + "as_float", + "as_string", + "as_custom_obj", + ): + return + else: + raise AssertionError(f"Unknown input type: {arg}") + elif spec.type == "parameter": + t = spec.parameter.arg + t.name = replace_table[t.name] + elif spec.type == "buffer": + t = spec.buffer.arg + t.name = replace_table[t.name] + elif spec.type == "tensor_constant": + t = spec.tensor_constant.arg + t.name = replace_table[t.name] + elif spec.type == "custom_obj": + t_custom_obj = spec.custom_obj.arg + t_custom_obj.name = replace_table[t_custom_obj.name] + return + elif spec.type == "token": + tok = spec.token.arg + tok.name = replace_table[tok.name] + elif spec.type == "constant_input": + return + else: + raise AssertionError(f"Unknown input type: {spec}") + + def replace_output(out): + if not isinstance(spec, OutputSpec): + raise AssertionError(f"expected OutputSpec, got {type(spec).__name__}") + if spec.type == "user_output": + arg = spec.user_output.arg + if arg.type == "as_tensor": + t = arg.as_tensor + t.name = replace_table[t.name] + elif arg.type == "as_sym_int": + s = arg.as_sym_int + if s.type == "as_name": + s.as_name = replace_table[s.as_name] + elif s.type == "as_int": + pass + else: + raise AssertionError(f"Unknown sym_int type: {s}") + elif arg.type == "as_sym_float": + f = arg.as_sym_float + if f.type == "as_name": + f.as_name = replace_table[f.as_name] + elif f.type == "as_float": + pass + else: + raise AssertionError(f"Unknown sym_float type: {f}") + elif arg.type in ("as_none", "as_bool", "as_int", "as_float", "as_string"): + return + else: + raise AssertionError(f"Unknown input type: {arg}") + elif spec.type == "loss_output": + t = spec.loss_output.arg + t.name = replace_table[t.name] + elif spec.type == "buffer_mutation": + t = spec.buffer_mutation.arg + t.name = replace_table[t.name] + elif spec.type == "parameter_mutation": + t = spec.parameter_mutation.arg + t.name = replace_table[t.name] + elif spec.type == "gradient_to_parameter": + t = spec.gradient_to_parameter.arg + t.name = replace_table[t.name] + elif spec.type == "gradient_to_user_input": + g = spec.gradient_to_user_input + g.arg.name = replace_table[g.arg.name] + g.user_input_name = replace_table[g.user_input_name] + elif spec.type == "user_input_mutation": + u = spec.user_input_mutation + u.arg.name = replace_table[u.arg.name] + u.user_input_name = replace_table[u.user_input_name] + elif spec.type == "token": + tok = spec.token.arg + tok.name = replace_table[tok.name] + else: + raise AssertionError(f"Unknown output type: {spec}") + + for spec in input_specs: + replace_input(spec) + + for spec in output_specs: + replace_output(spec) + + return ExportedProgram( + graph_module=GraphModule( + graph=sorted_graph, + signature=GraphSignature( + input_specs=list(input_specs), + output_specs=list(output_specs), + ), + module_call_graph=module_call_graph, + ), + opset_version=opset_version, + range_constraints=range_constraints, + schema_version=ep.schema_version, + verifiers=ep.verifiers, + torch_version=ep.torch_version, + guards_code=guards_code, + ) + + +class ExtensionHandler: + """ + Base class for handling extension operators. + """ + + @classmethod + def namespace(cls) -> str: + raise NotImplementedError(f"{cls.__class__} namespace() must be implemented") + + @classmethod + def to_op_name(cls, op) -> str: + raise NotImplementedError(f"{cls.__class__} op_name() must be implemented") + + @classmethod + def from_op_name(cls, name: str): + raise NotImplementedError(f"{cls.__class__} op_name() must be implemented") + + @classmethod + def op_schema(cls, op) -> torch.FunctionSchema: + raise NotImplementedError(f"{cls.__class__} op_schema() must be implemented") + + +def register_extension( + op_type: type[Any], + extension_handler: type[ExtensionHandler], +): + """Register custom de/serialization method for a node with non-standard type.""" + if not issubclass(extension_handler, ExtensionHandler): + raise AssertionError(f"Expected ExtensionHandler, got {extension_handler}.") + if op_type in _serialization_registry: + raise AssertionError(f"{op_type} is already registered.") + if not isinstance(op_type, type): + raise AssertionError(f"op_type must be a type, got {type(op_type).__name__}") + if op_type.__module__.startswith("torch") or op_type.__module__.startswith( + "builtins" + ): + raise AssertionError( + f"op_type module {op_type.__module__} should not start with 'torch' or 'builtins'" + ) + if extension_handler.namespace() in _deserialization_registry: + raise AssertionError( + f"namespace {extension_handler.namespace()!r} is already registered" + ) + _serialization_registry[op_type] = extension_handler + _deserialization_registry[extension_handler.namespace()] = extension_handler + + +def _registered_extension_types(): + return tuple(_serialization_registry.keys()) + + +# Registry to store all custom serialization implementations. +# The registry maps an operation to its serialization function (a callable), in their own +# namespace to avoid conflicts. +# Serialization: Op type --> custom handler. +# De-serialization: Namespace --> custom handler. +_serialization_registry: dict[type[Any], type[ExtensionHandler]] = {} +_deserialization_registry: dict[str, type[ExtensionHandler]] = {} diff --git a/.venv/lib/python3.12/site-packages/torch/_export/serde/union.py b/.venv/lib/python3.12/site-packages/torch/_export/serde/union.py new file mode 100644 index 0000000000000000000000000000000000000000..6610c4d74ee9f63ddc8e5d21f64e37bc2ba543ed --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/serde/union.py @@ -0,0 +1,104 @@ +import functools +from collections.abc import Hashable +from dataclasses import dataclass, fields +from typing import Any, TypeVar +from typing_extensions import dataclass_transform + + +T = TypeVar("T", bound="_Union") + + +class _UnionTag(str): + __slots__ = ("_cls",) + _cls: Hashable + + @staticmethod + def create(t: str, cls: type["_Union"]) -> "_UnionTag": + tag = _UnionTag(t) + if hasattr(tag, "_cls"): + raise AssertionError("tag already has _cls attribute") + tag._cls = cls + return tag + + def __eq__(self, cmp: object) -> bool: + if not isinstance(cmp, str): + raise AssertionError(f"expected str, got {type(cmp)}") + other = str(cmp) + if other not in _get_field_names(self._cls): + raise AssertionError( + f"{other} is not a valid tag for {self._cls}. Available tags: {_get_field_names(self._cls)}" + ) + return str(self) == other + + def __hash__(self) -> int: + return hash(str(self)) + + +@functools.cache +def _get_field_names(cls: type["_Union"]) -> set[str]: + # pyrefly: ignore[bad-argument-type] # TODO _Union subclasses are dataclasses at runtime via _union_dataclass + return {f.name for f in fields(cls)} + + +# If you turn a schema class that inherits from union into a dataclass, please use +# this decorator to configure it. It's safe, faster and allows code sharing. +# +# For example, _union_dataclass customizes the __eq__ method to only check the type +# and value property instead of default implementation of dataclass which goes +# through every field in the dataclass. +@dataclass_transform(eq_default=False) +def _union_dataclass(cls: type[T]) -> type[T]: + if not issubclass(cls, _Union): + raise AssertionError(f"{cls} must inherit from {_Union}.") + return dataclass(repr=False, eq=False)(cls) + + +class _Union: + _type: _UnionTag + + @classmethod + def create(cls: type[T], **kwargs: object) -> T: + if len(kwargs) != 1: + raise AssertionError(f"expected exactly 1 kwarg, got {len(kwargs)}") + obj = cls(**{**{f.name: None for f in fields(cls)}, **kwargs}) # type: ignore[arg-type] + obj._type = _UnionTag.create(next(iter(kwargs.keys())), cls) + return obj + + def __post_init__(self) -> None: + if any( + f.name in ("type", "_type", "create", "value") + for f in fields(self) # type: ignore[arg-type, misc] + ): + raise AssertionError( + "field names 'type', '_type', 'create', 'value' are reserved" + ) + + @property + def type(self) -> str: + try: + return self._type + except AttributeError as e: + raise RuntimeError( + f"Please use {type(self).__name__}.create to instantiate the union type." + ) from e + + @property + def value(self) -> Any: + return getattr(self, self.type) + + def __getattribute__(self, name: str) -> Any: + attr = super().__getattribute__(name) + if attr is None and name in _get_field_names(type(self)) and name != self.type: + raise AttributeError(f"Field {name} is not set.") + return attr + + def __eq__(self, other: object) -> bool: + if not isinstance(other, _Union): + return False + return self.type == other.type and self.value == other.value + + def __str__(self) -> str: + return self.__repr__() + + def __repr__(self) -> str: + return f"{type(self).__name__}({self.type}={getattr(self, self.type)})" diff --git a/.venv/lib/python3.12/site-packages/torch/_export/tools.py b/.venv/lib/python3.12/site-packages/torch/_export/tools.py new file mode 100644 index 0000000000000000000000000000000000000000..94f5168930b1c0d4177830d72563305961672e71 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/tools.py @@ -0,0 +1,148 @@ +# mypy: allow-untyped-defs +import logging +import warnings +from collections.abc import Iterable +from typing import Any + +import torch +import torch.export +import torch.export._trace +from torch._utils_internal import log_export_usage + + +log = logging.getLogger(__name__) + +__all__ = ["report_exportability"] + + +def _generate_inputs_for_submodules( + model: torch.nn.Module, + target_submodules: Iterable[str], + args: tuple[Any, ...], + kwargs: dict[str, Any] | None = None, +) -> dict[str, tuple[Any, Any]]: + """ + Generate inputs for targeting submodules in the given model. Note that if two submodules refer to the same obj, this + function doesn't work. + + Args: + model: root model. + inputs: inputs to the root model. + target_submodules: submodules that we want to generate inputs for. + + Returns: + A dict that maps from submodule name to its inputs. + """ + kwargs = kwargs or {} + + handles = [] + results = {} + submodule_to_names = {mod: name for name, mod in model.named_modules()} + + def pre_forward(module, module_args, module_kwargs): + results[submodule_to_names[module]] = (module_args, module_kwargs) + + try: + for name, mod in model.named_modules(): + if name in target_submodules: + handles.append( + mod.register_forward_pre_hook(pre_forward, with_kwargs=True) + ) + model(*args, **kwargs) + except Exception as e: + warnings.warn( + f"Failed to generate submodule inputs because of the following error:\n{e}", + stacklevel=2, + ) + finally: + for h in handles: + h.remove() + return results + + +def report_exportability( + mod: torch.nn.Module, + args: tuple[Any, ...], + kwargs: dict[str, Any] | None = None, + *, + strict: bool = True, + pre_dispatch: bool = False, +) -> dict[str, Exception | None]: + """ + Report exportability issues for a module in one-shot. + + Args: + mod: root module. + args: args to the root module. + kwargs: kwargs to the root module. + Returns: + A dict that maps from submodule name to the exception that was raised when trying to export it. + `None` means the module is exportable without issue. + Sample output: + { + '': UnsupportedOperatorException(func=), + 'submod_1': UnsupportedOperatorException(func=), + 'submod_2': None + } + """ + + log_export_usage(event="export.report_exportability") + + kwargs = kwargs or {} + + all_submod_names = [name for name, _ in mod.named_modules() if name != ""] + submod_inputs = _generate_inputs_for_submodules(mod, all_submod_names, args, kwargs) + + tried_module_types = set() + report: dict[str, Exception | None] = {} + + def try_export(module, module_name, args, kwargs): + nonlocal submod_inputs, report, strict, pre_dispatch, tried_module_types + + if type(module) in tried_module_types: + return + tried_module_types.add(type(module)) + + if args is not None or kwargs is not None: + try: + torch.export._trace._export( + module, + args, + kwargs, + strict=strict, + pre_dispatch=pre_dispatch, + ) + report[module_name] = None + log.info("Successfully exported `%s`", module_name) + return + except Exception as e: + short_msg = repr(e).split("\n")[0] + log.warning( + "Failed exporting `%s` with exception: %s", module_name, short_msg + ) + report[module_name] = e + + for name, submod in module.named_children(): + sub_module_name = name if module_name == "" else f"{module_name}.{name}" + + submod_args, submod_kwargs = submod_inputs.get( + sub_module_name, (None, None) + ) + + try_export(submod, sub_module_name, submod_args, submod_kwargs) + + return + + try_export(mod, "", args, kwargs) + + unique_issues = set() + for exception in report.values(): + if exception is not None: + key = repr(exception).split("\\n")[0] + unique_issues.add(key) + + log.warning("Found %d export issues:", len(unique_issues)) + for issue in unique_issues: + log.warning(issue) + + return report diff --git a/.venv/lib/python3.12/site-packages/torch/_export/utils.py b/.venv/lib/python3.12/site-packages/torch/_export/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3f51d0efb3b2dd4cf8c8376f180fd1463a95165d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/utils.py @@ -0,0 +1,1693 @@ +import ast +import copy +import dataclasses +import functools +import inspect +import json +import math +import operator +import re +from collections import defaultdict +from collections.abc import Callable, Collection, Generator, Iterable, Sequence +from contextlib import contextmanager +from inspect import ismethod, Parameter +from typing import Any, TYPE_CHECKING + +import torch +from torch._guards import detect_fake_mode +from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode, is_fake_tensor +from torch._subclasses.functional_tensor import FunctionalTensor +from torch.fx._utils import first_call_function_nn_module_stack +from torch.fx.experimental.proxy_tensor import PreDispatchTorchFunctionMode +from torch.fx.passes.runtime_assert import insert_deferred_runtime_asserts + + +if TYPE_CHECKING: + import sympy + + from torch._export.passes.lift_constants_pass import ConstantAttrMap + from torch._functorch._aot_autograd.schemas import GraphSignature + from torch._ops import OperatorBase + from torch.export import ExportedProgram + from torch.export.graph_signature import ExportGraphSignature + from torch.fx.experimental.symbolic_shapes import ShapeEnv + from torch.utils._pytree import TreeSpec + +from torch.export.graph_signature import CustomObjArgument, InputKind, OutputKind +from torch.fx._pytree import ( + _deregister_pytree_flatten_spec, + register_pytree_flatten_spec, +) +from torch.utils._pytree import ( + _deregister_pytree_node, + _register_pytree_node, + Context, + FlattenFn, + FromDumpableContextFn, + GetAttrKey, + KeyPath, + keystr, + MappingKey, + SequenceKey, + ToDumpableContextFn, + tree_flatten_with_path, + UnflattenFn, +) + + +placeholder_prefixes = { + InputKind.USER_INPUT: "", + InputKind.PARAMETER: "p_", + InputKind.BUFFER: "b_", + InputKind.CONSTANT_TENSOR: "c_", + InputKind.CUSTOM_OBJ: "obj_", + InputKind.TOKEN: "token", +} + +_DISABLE_ATEN_TO_ASSERTION_PASS = False + + +def _collect_and_set_constant_attrs( + graph_signature: "ExportGraphSignature", + constants: dict[str, Any], + mod: torch.nn.Module, +) -> "ConstantAttrMap": + # the exported module will store constants & non-persistent buffers such that + # retracing treats them as persistent buffers, so we inform the constants lifting pass + # and overwrite the new graph signature using the previous program. This is intended to only be used + # in run_decompositions where we still have access to original EP. + from torch._export.passes.lift_constants_pass import ConstantAttrMap + + constant_attrs = ConstantAttrMap() + non_persistent_buffers = { + spec.target + for spec in graph_signature.input_specs + if spec.kind == InputKind.BUFFER and not spec.persistent + } + for name, value in constants.items(): + if name in non_persistent_buffers: + continue + # recursive getattr + _mod = mod + *atoms, attr = name.split(".") + for atom in atoms: + _mod = getattr(_mod, atom) + # remove as buffer, reassign as constant/non-persistent buffer + _mod._buffers.pop(attr, None) + setattr(_mod, attr, value) + constant_attrs.add(value, name) + return constant_attrs + + +def _register_constants_as_buffers( + mod: torch.fx.GraphModule, + state_dict: dict[str, Any], + non_persistent_buffers: Collection[str], +) -> set[str]: + # TODO some annoying circular dependency issue + from torch.export.unflatten import _assign_attr, _AttrKind + + temp_registered_constants = set() + + for node in mod.graph.nodes: + if node.op == "get_attr": + target = torch.fx.graph_module._get_attr(mod, node.target) + if isinstance(target, torch.Tensor): + # Make sure we also check if the original buffer is + # non persistent as well. + if (node.target not in state_dict) and ( + node.target not in non_persistent_buffers + ): + torch.fx.graph_module._del_attr(mod, node.target) + _assign_attr(target, mod, node.target, _AttrKind.BUFFER, False) + temp_registered_constants.add(node.target) + + mod.recompile() + + return temp_registered_constants + + +def _override_graph_signature_for_temp_registered_constants( + sig: "ExportGraphSignature", temp_registered_constants: set[str] +) -> "ExportGraphSignature": + for spec in sig.input_specs: + if spec.target in temp_registered_constants: + spec.kind = InputKind.CONSTANT_TENSOR + spec.persistent = None + + for spec in sig.output_specs: + if ( + spec.kind == OutputKind.BUFFER_MUTATION + and spec.target in temp_registered_constants + ): + raise RuntimeError( + f"Constant {spec.target} is mutated in the forward method. Pls register it as buffer" + ) + + return sig + + +def _overwrite_signature_for_non_persistent_buffers( + old_sig: "ExportGraphSignature", new_sig: "ExportGraphSignature" +) -> "ExportGraphSignature": + # overwrite signature for non-persistent buffers + non_persistent_buffers = { + spec.target + for spec in old_sig.input_specs + if spec.kind == InputKind.BUFFER and not spec.persistent + } + + for spec in new_sig.input_specs: + if spec.kind == InputKind.BUFFER and spec.target in non_persistent_buffers: + spec.persistent = False + return new_sig + + +def _collect_param_buffer_metadata(mod: torch.fx.GraphModule) -> dict[str, Any]: + """ + Param/buffer metadata needs to be saved before lowering to aten IR + because aten IR lifts them, as a result, automatic preservation doesn't work. + This is intended to be called on the strict mode tracing right before lowering to + aten IR OR run_decomposition pass. + """ + params_buffers_to_node_meta = {} + + def _getattr(model: torch.fx.GraphModule, attr_name: str) -> Any: + *prefix, field = attr_name.split(".") + t = model + for item in prefix: + t = getattr(t, item, None) # type: ignore[assignment] + if t is None: + raise AssertionError(f"attribute {item!r} not found in path") + + return getattr(t, field) + + for node in mod.graph.nodes: + target = node.target + meta = node.meta + if node.op == "call_module": + submodule = _getattr(mod, target) + if isinstance(submodule, torch.nn.Module): + for name, _ in submodule.named_parameters( + recurse=True, remove_duplicate=False + ): + params_buffers_to_node_meta[target + "." + name] = meta + + for name, _ in submodule.named_buffers( + recurse=True, remove_duplicate=False + ): + params_buffers_to_node_meta[target + "." + name] = meta + + if node.op == "get_attr": + submodule = _getattr(mod, target) + if not isinstance(submodule, torch.fx.GraphModule): + params_buffers_to_node_meta[target] = meta + + # If the call_function uses param as input, we also need to update params' meta + # with this call_function node's meta. + # This is basically the same flow as torch.fx.traceback.preserve_meta() + if node.op == "call_function" and not isinstance( + node.target, torch._ops.HigherOrderOperator + ): + for arg in node._input_nodes: + if arg.op == "get_attr": + for entry in torch.fx.proxy._COPY_META_FIELDS: + # the custom field should not be copied + if entry == "custom": + continue + if entry in meta: + params_buffers_to_node_meta[arg.target][entry] = meta[entry] + + return params_buffers_to_node_meta + + +def _maybe_find_pre_dispatch_tf_mode_for_export() -> ( + PreDispatchTorchFunctionMode | None +): + if not torch.compiler.is_exporting(): + return None + + if not torch._C._is_torch_function_mode_enabled(): + return None + + torch_function_mode_stack = torch.overrides._get_current_function_mode_stack() + + pre_dispatch_tf_modes = [ + mode + for mode in torch_function_mode_stack + if isinstance(mode, PreDispatchTorchFunctionMode) + ] + + if len(pre_dispatch_tf_modes) > 1: + raise AssertionError( + f"Expected only one PreDispatchTorchFunctionMode, found {len(pre_dispatch_tf_modes)}" + ) + + if len(pre_dispatch_tf_modes) == 0: + return None + + mode = pre_dispatch_tf_modes[0] + return mode + + +def _populate_param_buffer_metadata_to_new_gm( + params_buffers_to_node_meta: dict[str, Any], + gm: torch.fx.GraphModule, + new_sig: "ExportGraphSignature", +) -> None: + """ + Given that we collected param'buffer metadata before, we put them back in + newly traced graph module + """ + # Don't copy over nn_module_stack, stack_trace metadata for params/buffers nodes + for metadata in params_buffers_to_node_meta.values(): + metadata.pop("nn_module_stack", None) + metadata.pop("stack_trace", None) + + inputs_to_parameters = new_sig.inputs_to_parameters + inputs_to_buffers = new_sig.inputs_to_buffers + for node in gm.graph.nodes: + if node.op == "placeholder": + if node.target in inputs_to_parameters: + param_name = inputs_to_parameters[node.target] + if param_name in params_buffers_to_node_meta: + for k, v in params_buffers_to_node_meta[param_name].items(): + node.meta[k] = v + if node.target in inputs_to_buffers: + buffer_name = inputs_to_buffers[node.target] + if buffer_name in params_buffers_to_node_meta: + for k, v in params_buffers_to_node_meta[buffer_name].items(): + node.meta[k] = v + + +def _get_shape_env_from_gm(gm: torch.fx.GraphModule) -> "ShapeEnv | None": + vals = [ + node.meta["val"] + for node in gm.graph.nodes + if node.meta.get("val", None) is not None + ] + + fake_mode = _detect_fake_mode_from_gm(gm) + if fake_mode is not None: + return fake_mode.shape_env + for v in vals: + if isinstance(v, torch.SymInt): + return v.node.shape_env + + +def _rename_without_collisions( + name_map: dict[str, str], + find_available: dict[str, int], + used_names: set[str], + orig_name: str, + name: str, + is_placeholder: bool = False, +) -> str: + """ + Renames nodes to avoid name collisions, with suffixing. + name_map: map from original name to new name + find_available: map prefix to available suffix + used_names: cache of used names + orig_name: mapping key + name: candidate name (potentially suffixed, e.g. mul_2) + is_placeholder: if the node is a placeholder, avoid detecting suffix + """ + match = re.match(r"(.*)_(\d+)", name) + key = name + + if match and not is_placeholder: + prefix, n = match.group(1), match.group(2) + key = prefix + + new_name = name + if new_name in used_names: + new_name = f"{key}_{find_available[key] + 1}" + + match = re.match(r"(.*)_(\d+)", new_name) + if match: + prefix, n = match.group(1), match.group(2) + if int(n) > find_available[prefix]: + find_available[prefix] = int(n) + + name_map[orig_name] = new_name + used_names.add(new_name) + + return name_map[orig_name] + + +def get_keystr(key_path: KeyPath) -> str: + """For a given index into the flat_args, return a human readable string + describing how to access it, e.g. "*args["foo"][0].bar" + """ + # Prefix the keypath with "*args" or "**kwargs" to make it clearer where + # the arguments come from. Ultimately we ought to serialize the + # original arg names for the best error message here. + args_kwargs_key_path = key_path[0] + if not isinstance(args_kwargs_key_path, SequenceKey): + raise AssertionError( + f"expected SequenceKey, got {type(args_kwargs_key_path).__name__}" + ) + if args_kwargs_key_path.idx == 0: + return f"*args{keystr(key_path[1:])}" + else: + kwarg_key = key_path[1] + if not isinstance(kwarg_key, (GetAttrKey, MappingKey)): + raise AssertionError( + f"expected GetAttrKey or MappingKey, got {type(kwarg_key).__name__}" + ) + name = str(kwarg_key)[1:-1] # get rid of the enclosed [] + return f"{name}{keystr(key_path[2:])}" + + +def _check_symint( + symint: int | torch.SymInt, + arg: int, + range_constraints: dict["sympy.Expr", Any], + unification_map: dict["sympy.Symbol", Any], + keypath: KeyPath, + i: int | None = None, +) -> None: + from torch.export.dynamic_shapes import _IntWrapper + + if ( + isinstance(arg, torch.SymInt) + and not arg.node.expr.is_number + or isinstance(arg, _IntWrapper) + ): + # This can happen when, say, arg is a fake tensor. + # We do not run checks on symbolic shapes of fake inputs as + # such checks can affect the shape env. + return + + import sympy + + from torch._export.passes.add_runtime_assertions_for_constraints_pass import ( + _convert_range_to_int, + ) + from torch.utils._sympy.solve import try_solve + + if isinstance(symint, torch.SymInt) and len(symint.node.expr.free_symbols) == 1: + symbol = next(iter(symint.node.expr.free_symbols)) + if symbol in unification_map: + existing_dim = symint.node.expr.subs(unification_map) + if arg != existing_dim: + path = get_keystr(keypath) + if i is not None: + path += f".shape[{i}]" + raise RuntimeError( + f"Expected input at {path} to be equal to {existing_dim}, but got {arg}", + ) + else: + if isinstance(symint.node.expr, sympy.Symbol): + # Short cut for try_solve below. Also useful in cases where + # sympy.Eq(symint.node.expr, arg) would evaluate to False + # purely because symbol is constrained to be size-like, + # e.g., when symint.node.expr = symbol and arg = 0. + unification_map[symbol] = int(arg) + else: + solution = try_solve(sympy.Eq(symint.node.expr, arg), symbol) + if solution is None: + path = get_keystr(keypath) + if i is not None: + path += f".shape[{i}]" + raise RuntimeError( + f"Expected input {path} = {arg} to be " + f"of the form {symint.node.expr}, where {symbol} is an integer" + ) + else: + unification_map[symbol] = int(solution[1]) + + if symint.node.expr in range_constraints: + min_val, max_val = _convert_range_to_int( + range_constraints[symint.node.expr] + ) + # NOTE: we allow dimensions to be 0/1 at runtime + if min_val > 2: + if arg < min_val: + path = get_keystr(keypath) + if i is not None: + path += f".shape[{i}]" + raise RuntimeError( + f"Expected input at {path} to be >= {min_val}, but got {arg}", + ) + if max_val < math.inf: + if arg > max_val: + path = get_keystr(keypath) + if i is not None: + path += f".shape[{i}]" + raise RuntimeError( + f"Expected input at {path} to be <= {max_val}, but got {arg}", + ) + elif isinstance(symint, torch.SymInt) and not symint.node.expr.is_number: + # this means we deferred a guard from export analysis to runtime, let this pass + # we'll add a runtime assert checking equality to this replacement expression + pass + elif arg != int(symint): + path = get_keystr(keypath) + if i is not None: + path += f".shape[{i}]" + raise RuntimeError( + f"Expected input at {path} to be equal to {symint}, but got {arg}. " + "If you meant for this dimension to be dynamic, please re-export and specify dynamic_shapes " + "(e.g. with Dim.DYNAMIC)" + ) + + +def _check_input_constraints_for_graph( + input_placeholders: list[torch.fx.Node], + flat_args_with_path: Sequence[tuple[tuple[Any, ...], Any]], + range_constraints: dict["sympy.Expr", Any], +) -> None: + if len(flat_args_with_path) != len(input_placeholders): + raise RuntimeError( + "Unexpected number of inputs " + f"(expected {len(input_placeholders)}, got {len(flat_args_with_path)})" + ) + # NOTE: export already guarantees that the same symbol is used in metadata + # for all InputDims related by equality constraints, so we can just unify + # symbols with given input dimension values to check equality constraints. + unification_map: dict[sympy.Symbol, Any] = {} + for (key_path, arg), node in zip(flat_args_with_path, input_placeholders): + node_val = node.meta.get("val") + if is_fake_tensor(node_val): + if not isinstance(arg, torch.Tensor): + raise RuntimeError( + f"Expected input at {get_keystr(key_path)} to be a tensor, but got {type(arg)}", + ) + + if len(node_val.shape) != len(arg.shape): + raise RuntimeError( + f"Unexpected number of dimensions in input at {get_keystr(key_path)}.shape " + f"(expected {node_val.shape}, got {arg.shape})" + ) + + for j, (arg_dim, node_dim) in enumerate(zip(arg.shape, node_val.shape)): + _check_symint( + node_dim, arg_dim, range_constraints, unification_map, key_path, j + ) + + elif isinstance(node_val, (int, float, str)): + if type(arg) is not type(node_val): + raise RuntimeError( + f"Expected input at {get_keystr(key_path)} to be equal to {node_val}, but got {arg}", + ) + # NaN != NaN in Python, so use math.isnan for NaN-to-NaN comparison + if isinstance(node_val, float) and math.isnan(node_val): + if not isinstance(arg, float) or not math.isnan(arg): + raise RuntimeError( + f"Expected input at {get_keystr(key_path)} to be nan, but got {arg}", + ) + elif arg != node_val: + raise RuntimeError( + f"Expected input at {get_keystr(key_path)} to be equal to {node_val}, but got {arg}", + ) + elif isinstance(node_val, torch.SymInt): + _check_symint( + node_val, + arg, + range_constraints, + unification_map, + key_path, + None, + ) + + +def register_dataclass_as_pytree_node( + cls: type[Any], + flatten_fn: FlattenFn | None = None, + unflatten_fn: UnflattenFn | None = None, + *, + serialized_type_name: str | None = None, + to_dumpable_context: ToDumpableContextFn | None = None, + from_dumpable_context: FromDumpableContextFn | None = None, + return_none_fields: bool = False, +) -> None: + if not dataclasses.is_dataclass(cls): + raise AssertionError( + f"Only dataclasses can be registered with this function: {cls}" + ) + + @torch._dynamo.dont_skip_tracing + def default_flatten_fn(obj: Any) -> tuple[list[Any], Context]: + flattened = [] + flat_names = [] + none_names = [] + for f in dataclasses.fields(obj): + name, val = f.name, getattr(obj, f.name) + if val is not None or return_none_fields: + flattened.append(val) + flat_names.append(name) + else: + none_names.append(name) + return flattened, [flat_names, none_names] + + @torch._dynamo.dont_skip_tracing + def default_unflatten_fn(values: Iterable[Any], context: Context) -> Any: + flat_names, none_names = context + return cls(**dict(zip(flat_names, values)), **dict.fromkeys(none_names)) + + @torch._dynamo.dont_skip_tracing + def default_flatten_fn_with_keys(obj: Any) -> tuple[list[Any], Context]: + flattened, (flat_names, _none_names) = flatten_fn(obj) # type: ignore[misc] + return [(MappingKey(k), v) for k, v in zip(flat_names, flattened)], flat_names + + flatten_fn = flatten_fn if flatten_fn is not None else default_flatten_fn + unflatten_fn = unflatten_fn if unflatten_fn is not None else default_unflatten_fn + + if (to_dumpable_context is None) ^ (from_dumpable_context is None): + raise ValueError( + f"Both to_dumpable_context and from_dumpable_context for {cls} must " + "be None or registered." + ) + + _register_pytree_node( + cls, + flatten_fn, + unflatten_fn, + serialized_type_name=serialized_type_name, + flatten_with_keys_fn=default_flatten_fn_with_keys, + to_dumpable_context=to_dumpable_context, + from_dumpable_context=from_dumpable_context, + ) + + +def is_param(program: "ExportedProgram", node: torch.fx.Node) -> bool: + """ + Checks if the given node is a parameter within the exported program + """ + + return node.name in program.graph_signature.inputs_to_parameters + + +def get_param( + program: "ExportedProgram", + node: torch.fx.Node, +) -> torch.nn.Parameter | None: + """ + Returns the parameter associated with the given node in the exported program. + Returns None if the node is not a parameter within the exported program + """ + + if is_param(program, node): + parameter_name = program.graph_signature.inputs_to_parameters[node.name] + return program.state_dict[parameter_name] + + return None + + +def is_buffer(program: "ExportedProgram", node: torch.fx.Node) -> bool: + """ + Checks if the given node is a buffer within the exported program + """ + + return node.name in program.graph_signature.inputs_to_buffers + + +def get_buffer( + program: "ExportedProgram", + node: torch.fx.Node, +) -> torch.Tensor | None: + """ + Returns the buffer associated with the given node in the exported program. + Returns None if the node is not a buffer within the exported program + """ + + if is_buffer(program, node): + buffer_name = program.graph_signature.inputs_to_buffers[node.name] + if buffer_name in program.graph_signature.non_persistent_buffers: + return program.constants[buffer_name] + else: + return program.state_dict[buffer_name] + + return None + + +def is_lifted_tensor_constant( + program: "ExportedProgram", + node: torch.fx.Node, +) -> bool: + """ + Checks if the given node is a lifted tensor constant within the exported program + """ + + return node.name in program.graph_signature.inputs_to_lifted_tensor_constants + + +def get_lifted_tensor_constant( + program: "ExportedProgram", + node: torch.fx.Node, +) -> torch.Tensor | None: + """ + Returns the lifted tensor constant associated with the given node in the exported program. + Returns None if the node is not a lifted tensor constant within the exported program + """ + + if is_lifted_tensor_constant(program, node): + lifted_tensor_name = program.graph_signature.inputs_to_lifted_tensor_constants[ + node.name + ] + return program.constants[lifted_tensor_name] + + return None + + +def sequential_split( + gm: torch.fx.GraphModule, + node_call_back: Callable[[torch.fx.Node], torch.fx.Node | bool], +) -> torch.fx.GraphModule: + """ + sequential_split creates a new graph module that splits the input graph module into multiple submodules + based on the node_call_back. It doesn't mutate the input graph module. The node_call_back should return + True if the node is a delimiter. Delimiter will be the first node in the next submodule. + """ + from torch.fx.passes.split_module import split_module + + split_map = {} + split_id = 0 + for node in gm.graph.nodes: + if node_call_back(node): + split_id += 1 + split_map[node] = split_id + + new_gm = split_module( + gm, + gm, + lambda node: split_map[node], + keep_original_order=True, + keep_original_node_name=True, + ) + # Keep the codegen from original graph module to preserve e.g. pytree info. + new_gm.graph._codegen = gm.graph._codegen + new_gm.recompile() + return new_gm + + +def nodes_filter( + nodes: list[torch.fx.Node], node_call_back: Callable[[torch.fx.Node], object] +) -> list[torch.fx.Node]: + """Returns the nodes that match the node_call_back as a list.""" + return [node for node in nodes if node_call_back(node)] + + +@contextmanager +def _disable_aten_to_metadata_assertions() -> Generator[None, None, None]: + global _DISABLE_ATEN_TO_ASSERTION_PASS + orig_val = _DISABLE_ATEN_TO_ASSERTION_PASS + _DISABLE_ATEN_TO_ASSERTION_PASS = True + try: + yield + finally: + _DISABLE_ATEN_TO_ASSERTION_PASS = orig_val + + +def _insert_aten_to_metadata_assert_pass(gm: torch.fx.GraphModule) -> None: + from torch._export.passes._node_metadata_hook import ( + _node_metadata_hook, + _set_node_metadata_hook, + ) + + if _DISABLE_ATEN_TO_ASSERTION_PASS: + return + + aten_to_variants = [ + torch.ops.aten.to.device, + torch.ops.aten.to.dtype, + torch.ops.aten.to.dtype_layout, + ] + for node in gm.graph.nodes: + if node.target in aten_to_variants: + if ( + node.prev.target is torch.ops.aten._assert_tensor_metadata.default + and node.args[0] == node.prev.args[0] + ): + # skip if already guarded + continue + + if (tensor_val := node.args[0].meta.get("val")) is not None: + with ( + gm.graph.inserting_before(node), + _set_node_metadata_hook( + gm, + functools.partial( + _node_metadata_hook, + metadata={ + "stack_trace": node.meta.get("stack_trace"), + "nn_module_stack": node.meta.get("nn_module_stack"), + }, + ), + ), + ): + gm.graph.call_function( + torch.ops.aten._assert_tensor_metadata.default, + args=(node.args[0],), + kwargs={ + "dtype": tensor_val.dtype, + "device": tensor_val.device, + "layout": tensor_val.layout, + }, + ) + + +def apply_runtime_assertion_pass( + gm: torch.fx.GraphModule, graph_signature: "GraphSignature" +) -> tuple[torch.fx.GraphModule, "GraphSignature"]: + from torch._export.passes._node_metadata_hook import ( + _node_metadata_hook, + _set_node_metadata_hook, + ) + from torch._functorch._aot_autograd.input_output_analysis import _graph_output_names + + if not torch._dynamo.config.do_not_emit_runtime_asserts: + stack_trace = ( + 'File "torch/fx/passes/runtime_assert.py", line 24, ' + "in insert_deferred_runtime_asserts" + ) + with _set_node_metadata_hook( + gm, + functools.partial( + _node_metadata_hook, metadata={"stack_trace": stack_trace} + ), + ): + shape_env = _get_shape_env_from_gm(gm) + if shape_env: + insert_deferred_runtime_asserts( + gm, + shape_env, + f"exported program: {first_call_function_nn_module_stack(gm.graph)}", + export=True, + ) + + # insert runtime assertions for aten.to nodes + _insert_aten_to_metadata_assert_pass(gm) + + # update output specs + gm.recompile() + graph_signature.user_outputs = _graph_output_names(gm) + return gm, graph_signature + + +def nodes_first( + nodes: list[torch.fx.Node], + node_call_back: Callable[[torch.fx.Node], object] | None = None, +) -> torch.fx.Node | None: + """ + Returns the first node that matches the node_call_back. If no node matches, returns None. + When node_call_back is None, returns the first node in the node list. + """ + ret = nodes_filter(nodes, node_call_back if node_call_back else lambda node: True) + if len(ret) > 0: + return ret[0] + return None + + +def nodes_count( + nodes: list[torch.fx.Node], node_call_back: Callable[[torch.fx.Node], object] +) -> int: + """Returns the number of nodes that match the node_call_back.""" + return len(nodes_filter(nodes, node_call_back)) + + +def nodes_map( + nodes: list[torch.fx.Node], node_call_back: Callable[[torch.fx.Node], object] +) -> list[torch.fx.Node]: + """ + Sequentially visit the nodes list and invoke node_call_back on each element. + Returns the nodes list after the node_call_back is invoked on each element. + """ + for node in nodes: + node_call_back(node) + return nodes + + +def node_replace_(old_node: torch.fx.Node, new_node: torch.fx.Node) -> None: + """ + Replace all uses of old_node with new_node. + """ + old_node.replace_all_uses_with(new_node) + old_node.users.clear() + old_node.graph.erase_node(old_node) + + +def _update_gm_meta_if_possible(gm: torch.fx.GraphModule, mod: torch.nn.Module) -> None: + if ( + isinstance(mod, torch.fx.GraphModule) + and hasattr(mod, "meta") + and "custom" in mod.meta + ): + gm.meta.update({"custom": mod.meta["custom"]}) + + +def node_inline_(call_mod_node: torch.fx.Node) -> torch.fx.GraphModule | None: + """ + Inline the submodule of the given node into the parent module. + Note: we only support the case where submodule takes tensors inputs. + """ + if call_mod_node.op != "call_module": + raise AssertionError(f"expected call_module op, got {call_mod_node.op}") + gm = call_mod_node.graph.owning_module + if gm is None: + raise AssertionError("owning_module should not be None") + + if not isinstance(call_mod_node.target, str): + raise AssertionError( + f"expected target to be str, got {type(call_mod_node.target).__name__}" + ) + sub_gm = getattr(gm, call_mod_node.target) + + phs = (node for node in sub_gm.graph.nodes if node.op == "placeholder") + body = ( + node for node in sub_gm.graph.nodes if node.op not in ("placeholder", "output") + ) + output = [node for node in sub_gm.graph.nodes if node.op == "output"] + + for ph, arg in zip(phs, call_mod_node.args): + if not isinstance(arg, torch.fx.Node): + raise AssertionError(f"expected fx.Node, got {type(arg)}") + node_replace_(ph, arg) + + with gm.graph.inserting_before(call_mod_node): + for node in body: + new_node = gm.graph.node_copy(node) + if node.op == "get_attr": + if not isinstance(new_node.target, str): + raise AssertionError( + f"Expected str target for get_attr, got {type(new_node.target)}" + ) + if not isinstance(node.target, str): + raise AssertionError( + f"Expected str target for get_attr, got {type(node.target)}" + ) + new_target_name = new_node.target + if hasattr(gm, new_target_name): + # Loop through and find the "submod_{i}" that have no name collision + i = 1 + new_target_name = f"submod_{i}" + while hasattr(gm, new_target_name): + i += 1 + new_target_name = f"submod_{i}" + new_node.target = new_target_name + setattr(gm, new_node.target, getattr(sub_gm, node.target)) + node_replace_(node, new_node) + + if len(output) > 0: + if len(output) != 1 or len(output[0].args) != 1: + raise AssertionError( + f"expected exactly 1 output with 1 arg, got {len(output)} outputs" + ) + new_output = output[0].args[0] + + if isinstance(new_output, torch.fx.Node): + # Clear the users of the output node and set + # the users to be the users of original call_module node. + new_output.users.clear() + node_replace_(call_mod_node, new_output) + elif isinstance(new_output, (list, tuple)): + # Pop subgraph output node from users. + for node in new_output: + node.users.pop(output[0]) + + # Inline the get_item calls for the output node. + get_item_users = nodes_filter( + list(call_mod_node.users.keys()), + lambda node: node.op == "call_function" + and node.target is operator.getitem, + ) + # get_item_node.args[1] is the idx referring to new_output[idx] + nodes_map( + get_item_users, + lambda get_item_node: node_replace_( + get_item_node, + # pyrefly: ignore[bad-index] # TODO getitem idx is an int FX arg + new_output[get_item_node.args[1]], + ), + ) + call_mod_node.graph.erase_node(call_mod_node) + else: + raise NotImplementedError( + f"Unsupported output type {type(new_output)}. Expect it to be a Node or a list/tuple of Nodes." + ) + else: + call_mod_node.graph.erase_node(call_mod_node) + + gm.delete_all_unused_submodules() + gm.recompile() + return gm + + +def _get_torch_jit_trace_forward_signature(mod: torch.nn.Module) -> inspect.Signature: + """ + Get source code and parse argument names using AST. The function returns + a signature of the forward() function. + + # TODO: Directly provide inspect.signature compatible TS-d module. + """ + ast_mod = ast.parse(mod.code) # type: ignore[call-overload] + ast_func_def: ast.FunctionDef = ast_mod.body[0] + + # FIXME(jiashenc): TorchScript should only allow positional or keywords arguments. + arg_type_map = {"args": Parameter.POSITIONAL_OR_KEYWORD} + + # Traverse all argument types in AST tree and create associated parameters. + param_list = [] + for arg_type, param_type in arg_type_map.items(): + arg_name_list = [a.arg for a in getattr(ast_func_def.args, arg_type)] + for arg_name in arg_name_list: + if arg_name == "self": + continue # Skip self argument. + param_list.append(inspect.Parameter(arg_name, param_type)) + + return inspect.Signature(parameters=param_list) + + +def _bind_signature_to_inputs( + mod: torch.nn.Module, fake_args: tuple[Any, ...], fake_kwargs: dict[str, Any] +) -> dict[str, Any]: + if isinstance(mod, (torch.jit.ScriptModule, torch.jit.TracedModule)): + sig = _get_torch_jit_trace_forward_signature(mod) + + # Sanity check for placeholder names coming from TorchScript. + if len(sig.parameters) != len(fake_args) + len(fake_kwargs): + raise AssertionError( + "Arguments other than POSITIONAL_OR_KEYWORD kinds in forward() " + "are not supported in _get_torch_jit_trace_forward_signature" + ) + else: + sig = inspect.signature(mod.forward) + + # Rather than binding both fake_args and fake_kwargs to sig names, we + # (partially) bind only fake_args, while reusing fake_kwarg names. This + # ensures that fake_kwargs do not get reordered, which is important to + # match flattened user inputs. + return {**sig.bind_partial(*fake_args).arguments, **fake_kwargs} + + +def _build_cache( + name: str, find_available: dict[str, int], used_names: set[str] +) -> None: + used_names.add(name) + match = re.match(r"(.*)_(\d+)", name) + if match: + prefix, n = match.group(1), match.group(2) + if int(n) > find_available[prefix]: + find_available[prefix] = int(n) + + +def _name_hoo_subgraph_placeholders(gm: torch.fx.GraphModule) -> None: + """ + Propagate placeholder names from the top-level graph into HigherOrderOp subgraphs, + and handle collisions with non-placeholders by count suffixing. + Different HOO subgraph types have different input schemas, so we first enumerate them + and gather the top-level named placeholder nodes. + """ + + # gather all HOO subgraphs and their top-level named placeholder nodes + subgraph_ph_tuples: list[tuple[torch.fx.GraphModule, list[torch.fx.Node]]] = [] + for node in gm.graph.nodes: + if node.op == "call_function" and isinstance( + node.target, torch._ops.HigherOrderOperator + ): + # HOO subgraphs have varying input schemas, so we enumerate them there + if node.target._name == "cond": + _, true_graph, false_graph, cond_args = node._args + subgraph_ph_tuples.append((getattr(gm, true_graph.target), cond_args)) + subgraph_ph_tuples.append((getattr(gm, false_graph.target), cond_args)) + elif node.target._name == "wrap_with_set_grad_enabled": + subgraph, phs = node._args[1], node._args[2:] + subgraph_ph_tuples.append((getattr(gm, subgraph.target), phs)) + elif node.target._name == "map_impl": + body_graph, array, args = node._args + subgraph_ph_tuples.append( + (getattr(gm, body_graph.target), array + args) + ) + + # propagate names + for subgraph, hoo_phs in subgraph_ph_tuples: + name_map: dict[str, str] = {} + find_available: dict[str, int] = defaultdict(int) + used_names: set[str] = set() + for i, node in enumerate(subgraph.graph.nodes): + if i < len(hoo_phs): # placeholder, retain name + name_map[node.name] = hoo_phs[i].name + node.name = node.target = hoo_phs[i].name + _build_cache(node.name, find_available, used_names) + else: # non-placeholder, check for collisions + node.name = _rename_without_collisions( + name_map, find_available, used_names, node.name, node.name + ) + + # recurse and recompile + _name_hoo_subgraph_placeholders(subgraph) + subgraph.recompile() + + +def _assign_new_node_names( + gm: torch.fx.GraphModule, + name_map: dict[str, str], + custom_meta: dict[str, Any], +) -> None: + """ + Assign new names to all nodes, in the graph module, from name map. + """ + for node in gm.graph.nodes: + if node.op == "placeholder": + if node.name not in name_map: + raise AssertionError(f"placeholder node {node.name!r} not in name_map") + node.name = node.target = name_map[node.name] + if node.name in custom_meta: + if node.meta.get("custom") is None: + empty_custom: dict[str, Any] = {} + node.meta["custom"] = empty_custom + else: + # Assert if any existing key has different value + for k, v in node.meta["custom"].items(): + if ( + k in custom_meta[node.name] + and v != custom_meta[node.name][k] + ): + raise AssertionError( + f"Mismatch in custom metadata for key {k}. Value in " + f"node.meta is {v} and value in custom_meta is {custom_meta[node.name][k]}." + ) + node.meta["custom"].update(custom_meta[node.name]) + # if the constant obj is an input, we also need to update meta["val"] + # because this is created before the placeholder naming pass + if isinstance(node.meta["val"], CustomObjArgument): + node.meta["val"].name = node.name + elif node.name in name_map: + node.name = name_map[node.name] + + +def placeholder_naming_pass( + gm: torch.fx.GraphModule, + export_graph_signature: "ExportGraphSignature", + mod: torch.nn.Module, + fake_args: tuple[Any, ...], + fake_kwargs: dict[str, Any], + fake_params_buffers: dict[str, torch.Tensor | torch.nn.Parameter], + constants: dict[str, Any], +) -> None: + """ + This pass is run at the end of _export_non_strict() to assign better placeholder node names: + - User inputs: + These follow the signature of mod.forward(), e.g. forward(x, y) produces nodes x, y. + For nested inputs from dictionaries, lists, tuples, or dataclasses, + the names are a concatenation of the path to the tensor. + e.g. x = { + 'a': torch.randn(), + 'b': [torch.randn(), torch.randn()] + } + produces nodes x_a, x_b_0, x_b_1. + - Parameters/buffers/constants/custom objects: + These follow the FQN of the object, prefixed by "p", "b", "c", "obj" respectively. + e.g. self.bar.l0.weight produces "p_bar_l0_weight". + - Effect tokens: + These are named token, token_1, ... + """ + + custom_meta: dict[str, Any] = {} + if isinstance(mod, torch.fx.GraphModule): + for node in mod.graph.nodes: + if "custom" in node.meta: + custom_meta[node.name] = node.meta["custom"] + + def _strip_name(x: str) -> str: + if x.startswith("L__self___"): + x = x[len("L__self___") :] + elif x.startswith("self_"): + x = x[len("self_") :] + x = re.sub(r"[^a-zA-Z0-9]", "_", x) + return x + + def _extract_pytree_key(x: object) -> str: + if isinstance(x, MappingKey): + x = re.sub(r"[^a-zA-Z0-9]", "_", str(x.key)) + return x + elif isinstance(x, SequenceKey): + return str(x.idx) + elif isinstance(x, GetAttrKey): + return x.name + else: + raise RuntimeError(f"Pytree key of type {type(x)} not handled for {x}") + + name_map: dict[str, str] = {} + find_available: dict[str, int] = defaultdict(int) + used_names: set[str] = set() + + # map user input names with mod.forward() signature + combined_args = _bind_signature_to_inputs(mod, fake_args, fake_kwargs) + + flat_args_with_path, _ = tree_flatten_with_path(combined_args) + user_input_names = [ + spec.arg.name + for spec in export_graph_signature.input_specs + if spec.kind == InputKind.USER_INPUT + ] + + # use pytree path to name nested user inputs + for (arg_path, _arg), user_input_name in zip(flat_args_with_path, user_input_names): + if user_input_name: + _rename_without_collisions( + name_map, + find_available, + used_names, + user_input_name, + placeholder_prefixes[InputKind.USER_INPUT] + + "_".join(_extract_pytree_key(x).lower() for x in arg_path), + is_placeholder=True, + ) + + # use graph signature input specs to map param/buffer/constant names + # name effect tokens as token, token_1, ... (these aren't visible to user) + for spec in export_graph_signature.input_specs: + if spec.kind == InputKind.USER_INPUT: + continue + if spec.kind == InputKind.TOKEN: + base_name = "" + else: + # pyrefly: ignore[bad-argument-type] # TODO non-token specs always have a str target + base_name = _strip_name(spec.target).lower() + base_name = re.sub(r"[^a-zA-Z0-9]", "_", base_name) + + _rename_without_collisions( + name_map, + find_available, + used_names, + spec.arg.name, + placeholder_prefixes[spec.kind] + base_name, + is_placeholder=True, + ) + if base_name in custom_meta: + # the keys in custom_meta are node names from `mod`, + # which is the base_name here. + # we need the re-mapped name for lookup later + custom_meta[name_map[spec.arg.name]] = custom_meta[base_name] + del custom_meta[base_name] + + # handle naming collisions with call_function/get_attr inputs. + # here, we want to prioritize user input names over call_function names + # e.g. not have forward(self, mul): lead to a placeholder node called mul_13, + # so we increment the suffix of call_function nodes as needed + for node in gm.graph.nodes: + if node.op == "placeholder": + continue + _rename_without_collisions( + name_map, find_available, used_names, node.name, node.name + ) + + # assign new node names + _assign_new_node_names(gm, name_map, custom_meta) + + # propagate names to higher order op subgraphs + _name_hoo_subgraph_placeholders(gm) + + # re-generate graph module code + gm.recompile() + + # modify graph signature (input specs, output specs, user input mutations) + for spec in export_graph_signature.input_specs: + if spec.arg.name not in name_map: + raise AssertionError(f"input spec arg {spec.arg.name!r} not in name_map") + spec.arg.name = name_map[spec.arg.name] + if ( # handle targets for custom objects + spec.kind == InputKind.CUSTOM_OBJ and spec.target in name_map + ): + # pyrefly: ignore [bad-index, index-error] + spec.target = name_map[spec.target][4:] # strip obj_ prefix + + for spec in export_graph_signature.output_specs: + if spec.arg.name in name_map: + spec.arg.name = name_map[spec.arg.name] + if spec.kind == OutputKind.USER_INPUT_MUTATION and spec.target in name_map: + # pyrefly: ignore [bad-index, index-error] + spec.target = name_map[spec.target] + + # rename keys in constants dict for custom objects + for name in list(constants.keys()): + constant = constants[name] + if name in name_map and not isinstance( + constant, torch.Tensor + ): # rename custom objects with generic names + new_name = name_map[name] + if ( + new_name != name + and re.match(r"arg(\d+)_1", name) + and new_name != placeholder_prefixes[InputKind.CUSTOM_OBJ] + name + ): + constants[new_name] = constant + del constants[name] + + +def remove_proxy_from_state_dict( + state_dict: dict[str, Any], in_place: bool +) -> dict[str, Any]: + """ + If `in_place` is false, return a new copy of `state_dict` with "proxy" removed from `v.__dict__`. + `v` is the values in the dictionary. + If `in_place` is true, modify `state_dict` in place. + """ + if in_place: + for k, v in state_dict.items(): + if hasattr(v, "proxy"): + delattr(state_dict[k], "proxy") + return state_dict + else: + new_state_dict = {} + for k, v in state_dict.items(): + if hasattr(v, "proxy"): + new_state_dict[k] = v.detach().clone() + else: + new_state_dict[k] = v + return new_state_dict + + +def _detect_fake_mode_from_gm( + gm: torch.fx.GraphModule, +) -> torch._subclasses.fake_tensor.FakeTensorMode | None: + """ + For a given graph module, we look at the "val" of placeholder nodes to find the fake inputs. + Additionally, if gm doesn't have placeholders, we further look at the "example_value" or "val" of other nodes. + If no fake mode is found, we return None for fake_mode. + """ + + fake_inps: list[torch.Tensor] = [] + fake_vals: list[torch.Tensor] = [] + for node in gm.graph.nodes: + if node.op == "placeholder" and "val" in node.meta: + fake_val = node.meta["val"] + if fake_val is not None and isinstance(fake_val, torch.Tensor): + fake_inps.append(fake_val) + elif len(fake_inps) == 0 and ( + "example_value" in node.meta or "val" in node.meta + ): + fake_val = None + if "example_value" in node.meta: + fake_val = node.meta["example_value"] + elif "val" in node.meta: + fake_val = node.meta["val"] + if fake_val is not None and isinstance(fake_val, torch.Tensor): + fake_vals.append(fake_val) + + return detect_fake_mode(fake_inps + fake_vals) + + +@contextmanager +def _disable_load_state_dict_hooks( + mod: torch.nn.Module, +) -> Generator[None, None, None]: + state_dict_hooks: dict[int, Callable[..., object]] = dict(mod._state_dict_hooks) + state_dict_pre_hooks: dict[int, Callable[..., object]] = dict( + mod._state_dict_pre_hooks + ) + mod._state_dict_hooks.clear() + mod._state_dict_pre_hooks.clear() + try: + yield + finally: + mod._state_dict_hooks = state_dict_hooks + mod._state_dict_pre_hooks = state_dict_pre_hooks + + +def _is_cia_op(op: "OperatorBase") -> bool: + return ( + torch._C._dispatch_has_kernel_for_dispatch_key( + op.name(), torch._C.DispatchKey.CompositeImplicitAutograd + ) + or torch._C.DispatchKey.CompositeImplicitAutograd in op.py_kernels + ) + + +def _is_preservable_cia_op(op: "OperatorBase") -> bool: + return _check_valid_to_preserve(op) and _is_cia_op(op) + + +def _is_aten_op(op: "OperatorBase") -> bool: + return op.name().split("::")[0] == "aten" + + +def _is_custom_op(op: "OperatorBase") -> bool: + return not _is_aten_op(op) + + +# We can't cache this because custom op registry API in python can still +# add entries to the C++ dispatcher. +def _materialize_cpp_cia_ops() -> None: + """ + Utility function to query C++ dispatcher to get the all + possible CIA ops and populate them into torch.ops namespace + """ + cia_ops = torch._C._dispatch_get_registrations_for_dispatch_key( + "CompositeImplicitAutograd" + ) + + # Materialize all CIA ops + for op in cia_ops: + namespace, op_name = tuple(op.split("::")) + split_list = op_name.split(".") + # Sometime overload could be missing + if len(split_list) not in (1, 2): + raise AssertionError(f"expected 1 or 2 parts, got {len(split_list)}") + op_name = split_list[0] + op_overload_name = "default" + if len(split_list) == 2: + op_overload_name = split_list[1] + + _ = getattr(getattr(getattr(torch.ops, namespace), op_name), op_overload_name) + + +def _special_op_to_preserve_cia(*args: Any, **kwargs: Any) -> Any: + """ + This is a special marker that tells our infra that we shouldn't decompose this op. + """ + return NotImplemented + + +# Our strategy for deciding if we can preserve a op is following: +# 1. The op should be known statically that it is functional +# 2. If it is maybe aliasing, we decompose because we must know if an op +# is mutating or aliasing. +def _check_valid_to_preserve(op_overload: "OperatorBase") -> bool: + from torch._decomp import _should_decompose_because_unsafe_op + + if _should_decompose_because_unsafe_op(op_overload): + return False + if op_overload in FunctionalTensor.metadata_fns: + return False + + if not hasattr(op_overload, "_schema"): + return False + + alias_info = len( + [i for i in op_overload._schema.arguments if i.alias_info is not None] + ) + + is_mutating_or_aliasing = alias_info != 0 or op_overload._schema.is_mutable + + if is_mutating_or_aliasing: + return False + + if not torch._C._dispatch_has_kernel(op_overload.name()): + return False + + return True + + +@functools.lru_cache(maxsize=1) +def _collect_all_valid_cia_ops_for_aten_namespace() -> set["OperatorBase"]: + return _collect_all_valid_cia_ops_for_namespace(torch.ops.aten) + + +def _collect_all_valid_cia_ops_for_namespace( + op_namespace: torch._ops._OpNamespace, +) -> set["OperatorBase"]: + # Step 1: Materialize all ops from C++ dispatcher + _materialize_cpp_cia_ops() + + # Step 2: Query all ops from python dispatcher + cia_ops = set() + for op in op_namespace: + op_packet = getattr(op_namespace, op) + for op_overload in op_packet.op_overloads(): + if _is_preservable_cia_op(op_overload): + cia_ops.add(op_overload) + return cia_ops + + +def _collect_all_valid_cia_ops() -> set["OperatorBase"]: + """ + This is an util function that gets the all CIA functional ops. + + The algorithm is in 2 steps: + 1. We first query C++ dispatcher to get the list of CIA ops + and then we call getattr on torch.ops.aten to lazily populate + them. + + 2. Sometimes, handful of ops have CIA registered in python dispatcher + but not on the C++ side, these can't be caught at the first step. + So we walk again to get the final list. + + Note that the output of this function should never be modified + """ + cia_ops = set() + for op_namespace_name in torch.ops._dir: + # The reason we split here is because aten ops are safe to cache. + if op_namespace_name != "aten": + if not hasattr(torch.ops, op_namespace_name): + raise AssertionError( + f"torch.ops does not have attribute {op_namespace_name!r}" + ) + op_namespace = getattr(torch.ops, op_namespace_name) + if isinstance(op_namespace, torch._ops._OpNamespace): + cia_ops |= _collect_all_valid_cia_ops_for_namespace(op_namespace) + else: + cia_ops |= _collect_all_valid_cia_ops_for_aten_namespace() + return cia_ops + + +def _get_decomp_for_cia(op: "OperatorBase") -> Callable[..., object]: + # [NOTE] Separating out func.decompose + # Ideally we should be able to just register func.decompose but + # we can't as this decomp is gonna be registered to the py_impl. + # As a result it will infinitely recurse. So we first check if the op + # has py_impl entry for CIA and if it is we use that first. If not, + # we register C++ query to py_impl. + dk = torch._C.DispatchKey.CompositeImplicitAutograd + if dk in op.py_kernels and not isinstance(op.py_kernels[dk], torch._C.DispatchKey): + return op.py_kernels[dk] + + def _special_op_to_decompose_cia(*args: Any, **kwargs: Any) -> Any: + kernel = kwargs["kernel"] + del kwargs["kernel"] + # Can't call kernel.decompose due to infinite recursion as + # we register this kernel to py_impl directly + dk = torch._C.DispatchKey.CompositeImplicitAutograd + if torch._C._dispatch_has_kernel_for_dispatch_key( + kernel.name(), torch._C.DispatchKey.CompositeImplicitAutograd + ): + return kernel._op_dk(dk, *args, **kwargs) + else: + raise AssertionError( + f"Expected {kernel} to have CompositeImplicitAutograd kernel" + ) + + return functools.partial(_special_op_to_decompose_cia, kernel=op) + + +@contextmanager +def _compiling_state_context() -> Generator[None, None, None]: + old_compiling_flag = torch.compiler._is_compiling_flag + old_exporting_flag = torch.compiler._is_exporting_flag + try: + torch.compiler._is_compiling_flag = True + torch.compiler._is_exporting_flag = True + yield + finally: + torch.compiler._is_compiling_flag = old_compiling_flag + torch.compiler._is_exporting_flag = old_exporting_flag + + +def _fakify_params_buffers( + fake_mode: FakeTensorMode, + mod: torch.nn.Module, +) -> dict[str, torch.Tensor | torch.nn.Parameter]: + params_buffers = { + **dict(mod.named_parameters(remove_duplicate=False)), + **dict(mod.named_buffers(remove_duplicate=False)), + } + + faked_params_buffers = {} + memo: dict[int, FakeTensor] = {} + for key, value in params_buffers.items(): + if id(value) in memo: + fake_tensor = memo[id(value)] + else: + fake_tensor = fake_mode.from_tensor(value, static_shapes=True) + memo[id(value)] = fake_tensor + faked_params_buffers[key] = fake_tensor + return faked_params_buffers # type: ignore[return-value] + + +def register_module_as_pytree_input_node(cls: type[torch.nn.Module]) -> None: + """ + Registers a module as a valid input type for :func:`torch.export.export`. + + Args: + mod: the module instance + serialized_type_name: The serialized name for the module. This is + required if you want to serialize the pytree TreeSpec containing this + module. + + Example:: + + import torch + + + class Module(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear = torch.nn.Linear(3, 3) + + def forward(self, x): + return self.linear(x) + + + torch._export.utils.register_module_as_pytree_node(InputDataClass) + + + class Mod(torch.nn.Module): + def forward(self, x, m): + return m(x) + x + + + ep = torch.export.export(Mod(), (torch.randn(3), Module())) + print(ep) + + """ + if not issubclass(cls, torch.nn.Module): + raise AssertionError(f"expected nn.Module subclass, got {cls}") + + import weakref + + class PrototypeModule(weakref.ref[torch.nn.Module]): + def __init__(self, m: torch.nn.Module, *args: Any, **kwargs: Any) -> None: + super().__init__(m, *args, **kwargs) # type: ignore[call-arg] + if not isinstance(m, torch.nn.Module): + raise AssertionError(f"expected nn.Module, got {type(m).__name__}") + if hasattr(self, "_proto_cls"): + raise AssertionError("_proto_cls should not be set") + self._proto_cls = cls + + def __eq__(self, other: object) -> bool: + return self._proto_cls == other._proto_cls # type: ignore[attr-defined] + + def __deepcopy__(self, memo: dict[Any, Any]) -> "PrototypeModule": + # pyrefly: ignore[bad-argument-type] # TODO referent is alive during deepcopy + return PrototypeModule(self()) + + def default_flatten_fn(obj: Any) -> tuple[list[Any], Context]: + named_parameters = dict(obj.named_parameters()) + named_buffers = dict(obj.named_buffers()) + params_buffers = {**named_parameters, **named_buffers} + return list(params_buffers.values()), [ + list(params_buffers.keys()), + PrototypeModule(obj), + ] + + def default_unflatten_fn(values: Iterable[Any], context: Context) -> Any: + flat_names, ref = context + if ref is None or ref() is None: + raise RuntimeError("Module has been garbage collected") + obj = ref() + if flatten_fn is None: + raise AssertionError("flatten_fn should not be None") + flattened, _ = flatten_fn(obj) + + # NOTE: This helper function will replicate an nn.Module in the exactly same + # structure to be used together with _reparameterize_module. This will + # create a clone of the module with the new parameters and buffers without + # affecting the original module. + def copy_module(mod: torch.nn.Module) -> torch.nn.Module: + ret = copy.copy(mod) + ret.__dict__ = {copy.copy(k): copy.copy(v) for k, v in mod.__dict__.items()} + for name, child in ret.named_children(): + setattr(ret, name, copy_module(child)) + return ret + + if any(v is not o for v, o in zip(values, flattened)): + with torch.nn.utils.stateless._reparametrize_module( + obj, dict(zip(flat_names, values)), tie_weights=True, strict=True + ): + ret = copy_module(obj) + else: + ret = obj + return ret + + def default_flatten_fn_with_keys(obj: Any) -> tuple[list[Any], Context]: + flattened, [flat_names, *args] = flatten_fn(obj) # type: ignore[misc] + return [(MappingKey(k), v) for k, v in zip(flat_names, flattened)], [ + flat_names, + *args, + ] + + flatten_fn = default_flatten_fn + unflatten_fn = default_unflatten_fn + + serialized_type_name = cls.__module__ + "." + cls.__qualname__ + + def to_dumpable_context(context: Context) -> str: + keys, *_ = context + return json.dumps([keys, *([None] * len(_))]) + + def from_dumpable_context(dumpable: str) -> Any: + s = json.loads(dumpable) + s[1] = PrototypeModule(torch.nn.Module()) + return s + + _register_pytree_node( + cls, + flatten_fn, + unflatten_fn, + serialized_type_name=serialized_type_name, + flatten_with_keys_fn=default_flatten_fn_with_keys, + to_dumpable_context=to_dumpable_context, + from_dumpable_context=from_dumpable_context, + ) + + def default_flatten_fn_spec(obj: Any, spec: "TreeSpec") -> list[Any]: + flats, context = flatten_fn(obj) + if context != spec.context: + raise AssertionError(f"context mismatch: {context} != {spec.context}") + return flats + + register_pytree_flatten_spec( + cls, + default_flatten_fn_spec, + ) + + +def deregister_module_as_pytree_input_node(cls: type[torch.nn.Module]) -> None: + _deregister_pytree_node(cls) + _deregister_pytree_flatten_spec(cls) + + +def _sync_state(src: torch.nn.Module, dst: torch.nn.Module) -> None: + if not isinstance(src, torch.nn.Module): + raise AssertionError(f"Expected {src} to be a nn.Module") + if not isinstance(dst, torch.nn.Module): + raise AssertionError(f"Expected {dst} to be a nn.Module") + # Share state (params, buffers) between modules. + # This ensures that state mutations are visible across them. + # Since tensor constants are not mutable, copying (without sharing) is OK. + # Also, primitive constants are specialized, so copying (without sharing) is OK. + dst._parameters = src._parameters + dst._buffers = src._buffers + + +def sync_state(*wrapped_method_modules: torch.nn.Module) -> None: + """ + Sync state between exported modules corresponding to wrapped methods. + This might be necessary after serializing/deserializing due to copying. + """ + if wrapped_method_modules: + m, *other_ms = wrapped_method_modules + for other_m in other_ms: + _sync_state(m, other_m) + + +class _WrappedMethod(torch.nn.Module): + def __init__(self, method: Callable[..., object]) -> None: + super().__init__() + # share state of method's self module + _sync_state(method.__self__, self) # type: ignore[attr-defined] + # redirect forward to method + self.forward = method + + +def wrap_method(method: Callable[..., object]) -> _WrappedMethod: + """ + Wrap a method as a module so that it can be exported. + The wrapped module's forward points to the method, and + the method's original module state is shared. + """ + if not ismethod(method): + raise AssertionError(f"Expected {method} to be a method") + return _WrappedMethod(method) diff --git a/.venv/lib/python3.12/site-packages/torch/_export/verifier.py b/.venv/lib/python3.12/site-packages/torch/_export/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..00a9c9e106f1bedf5acd89b63c84d939c4ad3932 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/verifier.py @@ -0,0 +1,584 @@ +# mypy: allow-untyped-defs +import inspect +import math +import operator +from collections.abc import Iterable +from typing import Any, final, TYPE_CHECKING + +import torch +from torch._library.opaque_object import is_custom_class +from torch._ops import HigherOrderOperator, OpOverload +from torch._subclasses.fake_tensor import FakeTensor +from torch.export.graph_signature import ( + CustomObjArgument, + InputKind, + SymBoolArgument, + SymFloatArgument, + SymIntArgument, + TensorArgument, + TokenArgument, +) +from torch.fx import GraphModule + + +if TYPE_CHECKING: + from torch.export.exported_program import ExportedProgram + + +class SpecViolationError(Exception): + pass + + +def is_functional(op: OpOverload) -> bool: + return not op._schema.is_mutable + + +def _check_has_fake_tensor(node: torch.fx.Node) -> None: + # TODO(angelayi): remove this in favor of _check_val + return _check_val(node) + + +def _check_val(node: torch.fx.Node) -> None: + from torch.fx.experimental.symbolic_shapes import SymBool, SymFloat, SymInt + + def _check_correct_val(val): + if val is None: + return True + elif isinstance(val, (int, bool, str, float)): + return True + elif isinstance( + val, (torch.memory_format, torch.dtype, torch.device, torch.layout) + ): + return True + elif isinstance( + val, (FakeTensor, torch.Tensor) + ): # TODO(zhxchen17) Remove Tensor. + return True + elif isinstance(val, (SymInt, SymFloat, SymBool)): + return True + elif isinstance(val, CustomObjArgument): + return True + elif isinstance(val, Iterable): + return all(_check_correct_val(x) for x in val) + elif is_custom_class(type(val)): + return True + return False + + def _no_returns(op): + if not isinstance(op, OpOverload): + return False + return len(op._schema.returns) == 0 + + if "val" not in node.meta: + if node.op == "call_function" and _no_returns(node.target): + return + raise SpecViolationError(f"Node.meta {node.name} is missing val field.") + + val = node.meta["val"] + if not _check_correct_val(val): + raise SpecViolationError(f"Node.meta {node.name} has invalid val field {val}") + + +def _check_torch_fn(node: torch.fx.Node) -> None: + torch_fn = node.meta.get("torch_fn") + if torch_fn is None: + raise SpecViolationError( + f"Unable to find torch_fn metadata for node {node.name}" + ) + if ( + not isinstance(torch_fn, tuple) + and isinstance(torch_fn[0], str) + and isinstance(torch_fn[1], str) + ): + raise SpecViolationError( + f"Node.meta {node.name} has invalid torch_fn field {torch_fn}" + ) + + +class _VerifierMeta(type): + _registry: dict[str, type["Verifier"]] = {} + + def __new__(metacls, name, bases, attrs): + if bases: + if "check" in attrs or "_check_graph_module" in attrs: + raise SyntaxError("Overriding method check is not allowed.") + if "dialect" not in attrs or attrs["dialect"] == "ATEN": + raise AssertionError( + f"subclass must define dialect != 'ATEN', got {attrs.get('dialect')}" + ) + else: + if "check" not in attrs: + raise AssertionError("base class must define 'check' method") + if "_check_graph_module" not in attrs: + raise AssertionError( + "base class must define '_check_graph_module' method" + ) + if attrs["dialect"] != "ATEN": + raise AssertionError( + f"base class dialect must be 'ATEN', got {attrs['dialect']}" + ) + + if not isinstance(attrs["dialect"], str): + raise AssertionError(f"dialect must be str, got {type(attrs['dialect'])}") + ret = type.__new__(metacls, name, bases, attrs) + metacls._registry[attrs["dialect"]] = ret # type: ignore[assignment] + return ret + + +def getattr_recursive(obj: Any, target: str) -> Any: + target_atoms = target.split(".") + attr_itr = obj + for i, atom in enumerate(target_atoms): + if not hasattr(attr_itr, atom): + raise RuntimeError( + f"Node referenced nonexistent target {'.'.join(target_atoms[:i])}" + ) + attr_itr = getattr(attr_itr, atom) + return attr_itr + + +class Verifier(metaclass=_VerifierMeta): + dialect = "ATEN" + + def allowed_builtin_ops(self) -> list: + return [ + operator.getitem, + operator.add, + operator.mul, + operator.sub, + operator.truediv, + operator.ge, + operator.le, + operator.gt, + operator.lt, + operator.eq, + operator.ne, + operator.floordiv, + operator.mod, + operator.and_, + operator.or_, + operator.not_, + operator.pow, + operator.neg, + operator.abs, + operator.lshift, + operator.rshift, + math.ceil, + math.floor, + math.trunc, + round, + ] + + def allowed_op_types(self) -> tuple[type[Any], ...]: + return (OpOverload, HigherOrderOperator) + + def allowed_getattr_types(self) -> tuple[type[Any], ...]: + return (torch.fx.GraphModule, torch.utils._pytree.TreeSpec) + + def allowed_getattr_types_for_subgm(self) -> tuple[type[Any], ...]: + # subgm in HOP's argument could have getattr(weight) nodes, thus stateful + return ( + torch.fx.GraphModule, + torch.nn.parameter.Parameter, + torch.Tensor, # for buffer and constant tensor + torch.utils._pytree.TreeSpec, + ) + + def check_valid_op(self, op): + pass + + def check_additional(self, gm: GraphModule) -> None: + """ + Additional checks that are specific to some dialects. + """ + + @final + def check(self, ep: "ExportedProgram") -> None: + self._check_graph_module(ep.graph_module) + _verify_exported_program_module_call_graph(ep) + _verify_exported_program_signature(ep) + + @final + def _check_graph_module(self, gm: torch.fx.GraphModule) -> None: + def _allowed_getattr_types(is_toplevel_gm) -> tuple[type[Any], ...]: + if is_toplevel_gm: + ret = self.allowed_getattr_types() + else: + ret = self.allowed_getattr_types_for_subgm() + if any(t is object for t in ret): + raise AssertionError("allowed_getattr_types must not contain 'object'") + return ret + + def _check_valid_op(op) -> None: + def _allowed_builtin_ops() -> list: + ret = self.allowed_builtin_ops() + if not all(inspect.isbuiltin(op) for op in ret): + raise AssertionError("allowed_builtin_ops must all be builtins") + return ret + + def _allowed_op_types() -> tuple[type[Any], ...]: + ret = self.allowed_op_types() + if any(t is object for t in ret): + raise AssertionError("allowed_op_types must not contain 'object'") + return ret + + # TODO Remove this allowlist. + _allowed_torch_functions = ( + torch.autograd.grad_mode.set_grad_enabled, + torch.sym_int, + torch.sym_float, + torch.sym_ite, + torch.sym_max, + torch.sym_min, + torch.sym_not, + torch.sym_sqrt, + torch.sym_sum, + torch.export.custom_ops._call_custom_autograd_function_in_pre_dispatch, + # TODO (tmanlaibaatar) + # Predispatch export is able to contain autograd ops. + # These will be modeled as HOO later + torch._C._set_grad_enabled, + torch.amp.autocast_mode._enter_autocast, + torch.amp.autocast_mode._exit_autocast, + torch.fx.experimental.symbolic_shapes.cast_symbool_to_symint_guardless, + torch._functorch.predispatch._add_batch_dim, + torch._functorch.predispatch._remove_batch_dim, + torch._functorch.predispatch._vmap_increment_nesting, + torch._functorch.predispatch._vmap_decrement_nesting, + torch._functorch.predispatch.lazy_load_decompositions, + torch._functorch.predispatch._make_dual, + torch._functorch.predispatch._unpack_dual, + torch._functorch.predispatch._jvp_increment_nesting, + torch._functorch.predispatch._jvp_decrement_nesting, + torch._functorch.predispatch._unwrap_for_grad, + torch._functorch.predispatch._enter_dual_level, + torch._functorch.predispatch._exit_dual_level, + ) + + if not isinstance(op, _allowed_op_types()): + if ( + op not in _allowed_builtin_ops() + and op not in _allowed_torch_functions + ): + raise SpecViolationError( + f"Operator '{op}' is not an allowed operator type: {_allowed_op_types()}\n" + f"Valid builtin ops: {_allowed_builtin_ops()}" + f"Valid torch functions: {_allowed_torch_functions}" + ) + + if isinstance(op, OpOverload): + # All ops functional + # TODO (tmanlaibaatar) more proper way is needed here + if self.dialect != "TRAINING" and not is_functional(op): + raise SpecViolationError(f"operator '{op}' is not functional") + self.check_valid_op(op) + + for mod in gm.modules(): + is_toplevel_gm = mod is gm + + if not isinstance(mod, torch.fx.GraphModule): + continue + + mod.graph.lint() + for node in mod.graph.nodes: + # TODO(T140410192): should have fake tensor for all dialects + if node.op in {"call_module", "call_method"}: + raise SpecViolationError( + f"call_module is not valid: got a class '{node.target}' ", + ) + + elif node.op == "call_function": + _check_val(node) + + _check_valid_op(node.target) + + elif node.op == "get_attr": + if not isinstance(node.target, str): + raise SpecViolationError( + f"Expected get_attr target to be string, but got {type(node.target)}" + ) + + attr = getattr_recursive(mod, node.target) + if isinstance(attr, torch.nn.Module): + + def _is_type(name, ty): + return isinstance(getattr(attr, name, None), ty) + + if type(attr).__name__ == "LoweredBackendModule": + if ( + _is_type("backend_id", str) + and hasattr(attr, "original_module") + and hasattr(attr, "module_name") + and getattr(attr, "backend_id", None) == "aoti" + ): + continue + if ( + _is_type("backend_id", str) + and _is_type("processed_bytes", bytes) + and _is_type("compile_specs", list) + and hasattr(attr, "original_module") + ): + continue + else: + backend_id = getattr(attr, "backend_id", None) + processed_bytes = getattr(attr, "processed_bytes", None) + compile_specs = getattr(attr, "compile_specs", None) + raise SpecViolationError( + f"Invalid get_attr type {type(attr)}. \n" + f"LoweredBackendModule fields: " + f"backend_id(str) : {type(backend_id)}, " + f"processed_bytes(bytes) : {type(processed_bytes)}, " + f"compile_specs(list) : {type(compile_specs)}" + ) + elif type(attr).__name__ == "AOTInductorEPModule": + continue + + elif type(attr).__name__ == "AOTInductorRunnerWrapper": + continue + + if not isinstance(attr, _allowed_getattr_types(is_toplevel_gm)): + raise SpecViolationError( + f"Invalid get_attr type {type(attr)} on target {node.target}. \n" + f"Valid get_attr types: {_allowed_getattr_types(is_toplevel_gm)}" + ) + + elif node.op == "placeholder": + _check_val(node) + # TODO(zhxchen17) + # elif node.op == "output": + # _check_flattened_outputs() + + self.check_additional(gm) + + +class TrainingIRVerifier(Verifier): + dialect = "TRAINING" + + +def _verify_exported_program_module_call_graph(exported_program) -> None: + module_call_graph = exported_program.module_call_graph + nodes = {node.name for node in exported_program.graph.nodes} + for entry in module_call_graph: + if entry.signature is not None: + for arg in entry.signature.inputs: + if arg.name and arg.name not in nodes: + raise SpecViolationError( + f"Input {arg.name} does not exist in the graph." + ) + for arg in entry.signature.outputs: + if arg.name and arg.name not in nodes: + raise SpecViolationError( + f"Output {arg.name} does not exist in the graph." + ) + + +def _verify_exported_program_signature(exported_program) -> None: + # Check ExportedProgram signature matches + gs = exported_program.graph_signature + + # Lazily computed on first use; avoids calling graph_module.state_dict() + # unless at least one buffer is missing from the top-level state_dict. + _gm_state_dict: dict | None = None + + # Check every node in the signature exists in the graph + input_node_names = [ + node.name for node in exported_program.graph.nodes if node.op == "placeholder" + ] + + if len(input_node_names) != len(gs.input_specs): + input_spec_names = [ + spec.arg.name for spec in gs.input_specs if hasattr(spec.arg, "name") + ] + missing_in_specs = set(input_node_names) - set(input_spec_names) + missing_in_graph = set(input_spec_names) - set(input_node_names) + raise SpecViolationError( + f"Number of graph inputs ({len(input_node_names)}) " + f"does not match number of inputs in the graph signature ({len(gs.input_specs)})\n" + f"Placeholders missing input_specs: {missing_in_specs}\n" + f"Input_specs missing placeholders: {missing_in_graph}" + ) + + for input_spec, node in zip(gs.input_specs, input_node_names): + if isinstance( + input_spec.arg, + (TensorArgument, SymIntArgument, SymFloatArgument, SymBoolArgument), + ): + if input_spec.arg.name != node: + raise SpecViolationError( + f"Input spec name {input_spec.arg.name} does not match node name {node}" + ) + + if input_spec.kind == InputKind.USER_INPUT: + continue + + elif input_spec.kind == InputKind.PARAMETER: + if not isinstance(input_spec.arg, TensorArgument): + raise SpecViolationError( + f"Parameter {input_spec.name} is not a tensor argument. Found {input_spec.arg} instead." + ) + if input_spec.target is None: + raise SpecViolationError( + f"InputSpec for {input_spec.name} has no target." + ) + + param = input_spec.target + if param not in exported_program.state_dict: + raise SpecViolationError(f"Parameter {param} is not in the state dict.") + + if not isinstance(exported_program.state_dict[param], torch.nn.Parameter): + raise SpecViolationError( + f"State dict entry for parameter {param} is not an instance of torch.nn.Parameter." + ) + + elif input_spec.kind == InputKind.BUFFER: + if not isinstance(input_spec.arg, TensorArgument): + raise SpecViolationError( + f"Buffer {input_spec.name} is not a tensor argument. Found {input_spec.arg} instead." + ) + if input_spec.target is None: + raise SpecViolationError( + f"InputSpec for {input_spec.name} has no target." + ) + + buffer = input_spec.target + if input_spec.persistent is None: + raise SpecViolationError( + f"Buffer {buffer} is missing a persistence flag" + ) + + if ( + input_spec.persistent is True + and buffer not in exported_program.state_dict + ): + # Allow buffers that live in constants or in a subgraph + # submodule (e.g. lifted tensor constants from + # invoke_subgraph tracing stored under repeated_subgraph0). + # Use a lazy copy of the graph module state to avoid the + # cost of state_dict() when no fallback is needed. + if buffer not in exported_program.constants: + if _gm_state_dict is None: + _gm_state_dict = exported_program.graph_module.state_dict() + if buffer not in _gm_state_dict: + raise SpecViolationError( + f"Buffer {buffer} is not in the state dict." + ) + + if input_spec.persistent is False and buffer in exported_program.state_dict: + raise SpecViolationError( + f"Non-persistent buffer {buffer} is in the state dict, it should not be." + ) + elif input_spec.kind == InputKind.CONSTANT_TENSOR: + if not isinstance(input_spec.arg, TensorArgument): + raise SpecViolationError( + f"Constant tensor {input_spec.name} is not a tensor argument. Found {input_spec.arg} instead." + ) + if input_spec.target is None: + raise SpecViolationError( + f"InputSpec for {input_spec.name} has no target." + ) + + tensor_const = input_spec.target + if tensor_const not in exported_program.constants: + raise SpecViolationError( + f"Constant tensor {tensor_const} is not in the constants dictionary." + ) + elif input_spec.kind == InputKind.CUSTOM_OBJ: + if not isinstance(input_spec.arg, CustomObjArgument): + raise SpecViolationError( + f"Custom object {input_spec.name} is not a custom object argument. Found {input_spec.arg} instead." + ) + if input_spec.target is None: + raise SpecViolationError( + f"InputSpec for {input_spec.name} has no target." + ) + + custom_obj = input_spec.target + if custom_obj not in exported_program.constants: + raise SpecViolationError( + f"Custom object {custom_obj} is not in the constants dictionary." + ) + elif input_spec.kind == InputKind.TOKEN: + if not isinstance(input_spec.arg, TokenArgument): + raise SpecViolationError( + f"Constant tensor {input_spec.name} is not a tensor argument. Found {input_spec.arg} instead." + ) + else: + raise SpecViolationError(f"Unknown InputKind {input_spec.kind}.") + + # Check outputs + output_node = list(exported_program.graph.nodes)[-1] + if output_node.op != "output": + raise AssertionError(f"last node must be output, got {output_node.op}") + output_nodes = [ + arg.name if isinstance(arg, torch.fx.Node) else arg + for arg in output_node.args[0] + ] + + if len(output_nodes) != len(gs.output_specs): + output_spec_names = [ + spec.arg.name if hasattr(spec.arg, "name") else str(spec.arg) + for spec in gs.output_specs + ] + missing_out_specs = set(output_nodes) - set(output_spec_names) + missing_out_graph = set(output_spec_names) - set(output_nodes) + raise SpecViolationError( + f"Number of output nodes {len(output_nodes)} is different " + f"Than the number of outputs specified by the graph signature: {len(gs.output_specs)}\n" + f"Nodes missing output_specs: {missing_out_specs}\n" + f"Output_specs missing nodes: {missing_out_graph}" + ) + + num_tokens = len(gs.output_tokens) + buffers_to_mutate = gs.buffers_to_mutate + parameters_to_mutate = gs.parameters_to_mutate + user_inputs_to_mutate = gs.user_inputs_to_mutate + end = ( + len(buffers_to_mutate) + + len(parameters_to_mutate) + + len(user_inputs_to_mutate) + + num_tokens + ) + mutate_nodes: list[str] = output_nodes[num_tokens:end] + user_output_nodes = output_nodes[end : end + len(gs.user_outputs)] + + for mutation_node in mutate_nodes: + if mutation_node in buffers_to_mutate: + if buffers_to_mutate[mutation_node] not in gs.buffers: + raise SpecViolationError( + f"Buffer output {mutation_node} does not point to a buffer that exists. \n" + f"Dict of buffers that are mutated, in order: {buffers_to_mutate} \n" + f"Buffer nodes available: {gs.buffers} \n" + ) + elif mutation_node in parameters_to_mutate: + if parameters_to_mutate[mutation_node] not in gs.parameters: + raise SpecViolationError( + f"Parameter output {mutation_node} does not point to a parameter that exists. \n" + f"Dict of parameters that are mutated, in order: {parameters_to_mutate} \n" + f"Parameter nodes available: {gs.parameters} \n" + ) + elif mutation_node in user_inputs_to_mutate: + if user_inputs_to_mutate[mutation_node] not in gs.user_inputs: + raise SpecViolationError( + f"User input output {mutation_node} does not point to a user input that exists. \n" + f"Dict of user inputs that are mutated, in order: {user_inputs_to_mutate} \n" + f"User input nodes available: {gs.user_inputs} \n" + ) + else: + raise SpecViolationError( + f"Mutation node {mutation_node} is neither a buffer nor a user input. " + f"Buffers to mutate: {buffers_to_mutate}, User inputs to mutate: {user_inputs_to_mutate}" + ) + + for user_output_node, user_output_name in zip(user_output_nodes, gs.user_outputs): + if user_output_node != user_output_name: + raise SpecViolationError( + f"User output {user_output_node} is not in the correct " + "order or is not found in the " + f"exported program's user_output list: {gs.user_outputs}. " + ) + + +def load_verifier(dialect: str) -> type[Verifier]: + if dialect == "ATEN" or dialect == "": + return _VerifierMeta._registry.get(dialect, Verifier) + return _VerifierMeta._registry[dialect] diff --git a/.venv/lib/python3.12/site-packages/torch/_export/wrappers.py b/.venv/lib/python3.12/site-packages/torch/_export/wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..28418576aac4f773e2b217a2ec86108a83222668 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_export/wrappers.py @@ -0,0 +1,399 @@ +import inspect +from collections.abc import Callable, Generator, Iterable +from contextlib import contextmanager +from functools import wraps +from typing import Any, TYPE_CHECKING, TypeVar +from typing_extensions import ParamSpec + +import torch +import torch._custom_ops +from torch._C import DispatchKey +from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export +from torch._higher_order_ops.flat_apply import ( + _ConstantFunction, + flat_apply, + to_graphable, +) +from torch._higher_order_ops.strict_mode import strict_mode +from torch._higher_order_ops.utils import autograd_not_implemented, register_fake +from torch._ops import HigherOrderOperator +from torch.fx.experimental.proxy_tensor import ( + PreDispatchTorchFunctionMode, + ProxyTorchDispatchMode, + track_tensor_tree, +) +from torch.utils import _pytree as pytree +from torch.utils._python_dispatch import is_traceable_wrapper_subclass_type + + +if TYPE_CHECKING: + from torch._subclasses.functional_tensor import BaseFunctionalizeAPI + from torch.fx.experimental.proxy_tensor import _ProxyTracer + from torch.fx.proxy import Proxy + from torch.utils.hooks import RemovableHandle + + +_P = ParamSpec("_P") +_R = TypeVar("_R") + + +class ExportTracepoint(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("_export_tracepoint") + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + # pyrefly: ignore [missing-attribute] + return super().__call__(*args, **kwargs) + + +_export_tracepoint = ExportTracepoint() + + +@_export_tracepoint.py_impl(ProxyTorchDispatchMode) +def export_tracepoint_dispatch_mode( + mode: ProxyTorchDispatchMode, *args: Any, **kwargs: Any +) -> Any: + # pyrefly: ignore[missing-attribute] # TODO tracer is PythonKeyTracer here, not _GraphAppendingTracerEx + p_args, p_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, (args, kwargs)) + proxy = mode.tracer.create_proxy( + "call_function", _export_tracepoint, p_args, p_kwargs + ) + return track_tensor_tree(args, proxy, constant=None, tracer=mode.tracer) + + +@register_fake(_export_tracepoint, skip_cache=True) +def export_tracepoint_fake_tensor_mode(*args: Any, **kwargs: Any) -> tuple[Any, ...]: + return args + + +@_export_tracepoint.py_functionalize_impl +def export_tracepoint_functional( + ctx: "BaseFunctionalizeAPI", *args: Any, **kwargs: Any +) -> tuple[Any, ...]: + unwrapped_args = ctx.unwrap_tensors(args) + # pyrefly: ignore[bad-argument-type] # TODO unwrap_tensors accepts pytrees at runtime + unwrapped_kwargs = ctx.unwrap_tensors(kwargs) + + with ctx.redispatch_to_next(): + _export_tracepoint(*unwrapped_args, **unwrapped_kwargs) + return args + + +_export_tracepoint.py_impl(DispatchKey.Autograd)( + autograd_not_implemented(_export_tracepoint, deferred_error=True) +) + + +@_export_tracepoint.py_impl(DispatchKey.CPU) +def export_tracepoint_cpu(*args: Any, **kwargs: Any) -> tuple[Any, ...]: + return args + + +def _wrap_submodule( + mod: torch.nn.Module, + path: str, + module_call_specs: dict[str, dict[str, pytree.TreeSpec]], +) -> tuple["RemovableHandle", "RemovableHandle"]: + if not isinstance(mod, torch.nn.Module): + raise AssertionError(f"expected torch.nn.Module, got {type(mod)}") + if path == "": + raise AssertionError("path must not be empty") + submodule = torch.fx.graph_module._get_attr(mod, path) + + def update_module_call_signatures( + path: str, in_spec: pytree.TreeSpec, out_spec: pytree.TreeSpec + ) -> None: + if path in module_call_specs: + if module_call_specs[path]["in_spec"] != in_spec: + raise AssertionError( + f"in_spec mismatch for {path}: {module_call_specs[path]['in_spec']} != {in_spec}" + ) + if module_call_specs[path]["out_spec"] != out_spec: + raise AssertionError( + f"out_spec mismatch for {path}: {module_call_specs[path]['out_spec']} != {out_spec}" + ) + module_call_specs[path] = {"in_spec": in_spec, "out_spec": out_spec} + + def check_flattened(flat_args: list[Any]) -> None: + for a in flat_args: + if not (isinstance(a, (torch.Tensor, str, int, float, bool)) or a is None): + raise AssertionError( + f"Only Tensors or scalars are supported as pytree flattened inputs, got: {a}" + ) + + def pre_hook( + module: torch.nn.Module, args: tuple[Any, ...], kwargs: dict[str, Any] + ) -> tuple[tuple[Any, ...], dict[str, Any]]: + flat_args, in_spec = pytree.tree_flatten((args, kwargs)) + check_flattened(flat_args) + flat_args = _export_tracepoint(*flat_args, kind="module_call_inputs", path=path) + args, kwargs = pytree.tree_unflatten(flat_args, in_spec) + return args, kwargs + + def post_hook( + module: torch.nn.Module, + args: tuple[Any, ...], + kwargs: dict[str, Any], + res: Any, + ) -> Any: + _, in_spec = pytree.tree_flatten((args, kwargs)) + flat_res, out_spec = pytree.tree_flatten(res) + check_flattened(flat_res) + flat_res = _export_tracepoint(*flat_res, kind="module_call_outputs", path=path) + update_module_call_signatures(path, in_spec, out_spec) + return pytree.tree_unflatten(flat_res, out_spec) + + pre_handle = submodule.register_forward_pre_hook(pre_hook, with_kwargs=True) + post_handle = submodule.register_forward_hook(post_hook, with_kwargs=True) + return pre_handle, post_handle + + +@contextmanager +def _wrap_submodules( + f: torch.nn.Module | Callable[..., object], + preserve_signature: Iterable[str], + module_call_signatures: dict[str, dict[str, pytree.TreeSpec]], +) -> Generator[None, None, None]: + handles: list[RemovableHandle] = [] + + try: + for path in preserve_signature: + # pyrefly: ignore[bad-argument-type] # TODO f is an nn.Module at runtime (asserted in _wrap_submodule) + handles.extend(_wrap_submodule(f, path, module_call_signatures)) + yield + finally: + for handle in handles: + handle.remove() + + +def _mark_strict_experimental(cls: type[_R]) -> type[_R]: + def call(self: Any, *args: Any) -> Any: + return strict_mode(self, args) + + cls.__call__ = call # type: ignore[attr-defined] + return cls + + +def _register_func_spec_proxy_in_tracer( + tracer: "_ProxyTracer", name: str, spec: pytree.TreeSpec +) -> "Proxy": + """ + This is a wrapper utility method on top of tracer to cache the + already registered subclass spec attribute. This is useful because + Subclass.__init__ will be same for each subclass. By default, fx will + create multiple attributes/proxies for given attribute. + """ + fx_name = name + "0" + # pyrefly: ignore[missing-attribute] # TODO tracer is PythonKeyTracer here, not _GraphAppendingTracerEx + if hasattr(tracer.root, fx_name): + # pyrefly: ignore[missing-attribute] # TODO tracer is PythonKeyTracer here, not _GraphAppendingTracerEx + if getattr(tracer.root, fx_name) != spec: + raise AssertionError(f"spec mismatch for {fx_name}") + return tracer.create_proxy("get_attr", fx_name, (), {}) + + # pyrefly: ignore[missing-attribute] # TODO tracer is PythonKeyTracer here, not _GraphAppendingTracerEx + qualname = tracer.get_fresh_qualname(name) + # pyrefly: ignore[missing-attribute] # TODO tracer is PythonKeyTracer here, not _GraphAppendingTracerEx + setattr(tracer.root, qualname, spec) + return tracer.create_proxy("get_attr", qualname, (), {}) + + +def _emit_flat_apply_call( + *, + tracer: "_ProxyTracer", + spec_name: str, + const_target_for_apply: Callable[..., object], + graphable_args: pytree.PyTree, + track_value: object, + call_spec_cache_key: str, +) -> None: + # Flatten to graphable form and record the spec on the FX root + flat_args, in_spec = to_graphable(graphable_args) + qualname = tracer.get_fresh_qualname(spec_name) # type: ignore[union-attr] + setattr(tracer.root, qualname, in_spec) # type: ignore[union-attr] + spec_proxy = tracer.create_proxy("get_attr", qualname, (), {}) + + # Reuse/cached ConstantFunction spec on the root + _, func_spec = pytree.tree_flatten(_ConstantFunction(const_target_for_apply)) + func_spec_proxy = _register_func_spec_proxy_in_tracer( + tracer, f"{call_spec_cache_key}_const_func_spec", func_spec + ) + + # Map runtime args -> proxies (always via tracer.unwrap_proxy now) + # pyrefly: ignore[missing-attribute] # TODO tracer is PythonKeyTracer here, not _GraphAppendingTracerEx + flat_proxy_args = pytree.tree_map(tracer.unwrap_proxy, flat_args) + + # Emit flat_apply and track result structure + out_proxy = tracer.create_proxy( + "call_function", flat_apply, (func_spec_proxy, spec_proxy, *flat_proxy_args), {} + ) + track_tensor_tree(track_value, out_proxy, constant=None, tracer=tracer) + + +def _is_init(fn: object) -> bool: + return callable(fn) and fn.__name__ == "__init__" + + +def mark_subclass_constructor_exportable_experimental( + constructor_subclass: Callable[_P, None], +) -> Callable[_P, None]: + """ + Experimental decorator that makes subclass to be traceable in export + with pre-dispatch IR. To make your subclass traceable in export, you need to: + 1. Implement __init__ method for your subclass (Look at DTensor implementation) + 2. Decorate your __init__ method with _mark_constructor_exportable_experimental + 3. Put torch._dynamo_disable decorator to prevent dynamo from peeking into its' impl + + Example: + + class FooTensor(torch.Tensor): + @staticmethod + def __new__(cls, elem, *, requires_grad=False): + # ... + return torch.Tensor._make_subclass(cls, elem, requires_grad=requires_grad) + + @torch._dynamo_disable + @mark_subclass_constructor_exportable_experimental + def __init__(self, elem, ...): + # ... + """ + if not _is_init(constructor_subclass): + raise RuntimeError( + f"torch._export.wrappers.mark_constructor_exportable_experimental can only be applied on subclass tensor.__init__" + f"But, you are adding it on {constructor_subclass.__name__} which is not supported. " + f"If __init__ doesn't exist on your subclass, please add it. Look at DTensor.__init__ implementation for example" + ) + + def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> None: + constructor_subclass(*args, **kwargs) + + if not torch.compiler.is_exporting(): + return + + if not is_traceable_wrapper_subclass_type(type(args[0])): + if not constructor_subclass.__qualname__.endswith("__init__"): + raise AssertionError( + f"expected __qualname__ to end with '__init__', got {constructor_subclass.__qualname__}" + ) + obj_name = constructor_subclass.__qualname__[: -len("__init__")] + raise RuntimeError( + f"Can't intercept {obj_name} in export because this object is not a traceable " + f"tensor subclass. Please look at DTensor.__init__ implementation as an example of proper usage of this API." + ) + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + if mode is None: + return + + if not isinstance(mode, PreDispatchTorchFunctionMode): + raise AssertionError( + f"expected PreDispatchTorchFunctionMode, got {type(mode)}" + ) + + tracer = mode.tracer + subclass = args[0] + graphable = (tuple(args[1:]), kwargs) + + spec_name = "_".join(constructor_subclass.__qualname__.lower().split(".")) + call_spec_cache_key = type(subclass).__name__.lower() + + _emit_flat_apply_call( + tracer=tracer, + spec_name=spec_name, + const_target_for_apply=type(subclass), + graphable_args=graphable, + track_value=subclass, # track the constructed subclass instance + call_spec_cache_key=call_spec_cache_key, + ) + return + + return wrapper + + +def allow_in_pre_dispatch_graph(func: Callable[_P, _R]) -> Callable[_P, _R]: + """ + Experimental decorator that adds user function to export pre-dispatch graph. Note that + we only support custom autograd function/subclass constructors today. To use this function: + 1. For subclasses: + 1. refer to instructions in mark_subclass_constructor_exportable_experimental + 2. Define apply method on your custom autograd function and apply this decorator. + + Example: + + class MyCoolCustomAutogradFunc(autograd.Function): + @classmethod + @torch._export.wrappers.allow_in_pre_dispatch_graph + def apply(cls, *args, **kwargs): + return super(MyCoolCustomAutogradFunc, cls).apply(*args, **kwargs) + + """ + if _is_init(func): + # pyrefly: ignore[bad-return, bad-argument-type] # TODO _is_init(func) implies func returns None + return mark_subclass_constructor_exportable_experimental(func) + + if not (_is_init(func) or func.__name__ == "apply"): + raise RuntimeError( + f"torch._export.wrappers.allow_in_pre_dispatch_graph can only be applied on subclass tensor.__init_ " + f"or custom_autograd_function.apply. " + f"But, you are adding it on {func.__name__} which is not supported. " + f"If __init__ doesn't exist on your subclass, please add it. Look at DTensor.__init__ implementation for example. " + f"If you are adding it on custom autograd function, please add it on apply method. " + f"If anything else, file an issue on github and we may consider extending our support. " + ) + + @wraps(func) + def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R: + if not torch.compiler.is_exporting(): + return func(*args, **kwargs) + + if not inspect.isclass(args[0]): + return func(*args, **kwargs) + + if not issubclass(args[0], torch.autograd.Function): + return func(*args, **kwargs) + + from torch._ops import _get_dispatch_mode_pre_dispatch + + mode = _get_dispatch_mode_pre_dispatch(torch._C._TorchDispatchModeKey.PROXY) + if mode is None: + return func(*args, **kwargs) + + # Sometimes custom autograd functions can call into HOPs that don't have proxy impl + # at PreDispatch level, so we just dispatch it below to get the concrete result. + include_to_set = torch._C._dispatch_tls_local_include_set().remove( + torch._C.DispatchKey.PreDispatch + ) + exclude_to_set = ( + torch._C._dispatch_tls_local_exclude_set() + | torch._C.DispatchKeySet(torch._C.DispatchKey.PreDispatch) + ) + + with torch._C._ForceDispatchKeyGuard(include_to_set, exclude_to_set): + out = func(*args, **kwargs) + + if not mode.pre_dispatch: + raise AssertionError("Should only do this in predispatch") + tracer = mode.tracer + + function_cls_name = f"{args[0].__module__}.{args[0].__qualname__}" + graphable = ((function_cls_name, *args[1:]), kwargs) + + from torch.export.custom_ops import ( + _call_custom_autograd_function_in_pre_dispatch, + ) + + spec_name = "_".join(function_cls_name.split(".")) + call_spec_cache_key = type( + _call_custom_autograd_function_in_pre_dispatch + ).__name__.lower() + _emit_flat_apply_call( + tracer=tracer, + spec_name=spec_name, + const_target_for_apply=_call_custom_autograd_function_in_pre_dispatch, + graphable_args=graphable, + track_value=out, + call_spec_cache_key=call_spec_cache_key, + ) + return out + + return wrapper diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__init__.py b/.venv/lib/python3.12/site-packages/torch/_functorch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10a55772ab58b21573a6eba0356ddd3080164ac7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/__init__.py @@ -0,0 +1,5 @@ +# 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. diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02a4cad3ca14e06883a283ee4bada5379fed9073 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/aot_autograd.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/aot_autograd.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94ff5379b74d85cd6af551b335dee33b471aad55 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/aot_autograd.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/apis.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/apis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d090e2802d2b80706c42bdd3b0951058c479dde3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/apis.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/autograd_function.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/autograd_function.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ff8d16447c3cbccbd20d869d29018bdee800541 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/autograd_function.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/batch_norm_replacement.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/batch_norm_replacement.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2f632e5d77aa860b8a64b82cf3ee427e2f09581 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/batch_norm_replacement.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/benchmark_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/benchmark_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5b1fa896050fff57d3c61dcb1b653264dd5a390 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/benchmark_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/compile_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/compile_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bed43310a3113bfb306319f818318a0a48f0a23a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/compile_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/compilers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/compilers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f313ae9305540a76b83d30c3f226810e00aa217 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/compilers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/config.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a9c5d656ba16d50cf7efd4b9c5dd9ec14ed1d39 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/config.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/deprecated.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/deprecated.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e769ad6ae0d76e100c4c34bcf94f73d781a28060 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/deprecated.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/eager_transforms.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/eager_transforms.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..570dde28e4eca2eff6b4b871f9e620b7e2eac7ec Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/eager_transforms.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/einops.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/einops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fca6ffe067c69ddb260b90f490ac5a04cce6641 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/einops.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/functional_call.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/functional_call.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52d54b8b508b29c82eff261cd1d03cf7b7879aea Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/functional_call.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/fx_minifier.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/fx_minifier.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b304be2f77fc9e2ffa114292db6f1e2e4ebbe40 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/fx_minifier.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/make_functional.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/make_functional.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..828b21cfca98757e1ff49596f5b4968059995c0a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/make_functional.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/partitioners.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/partitioners.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bebcc2277722f026b65690bd046e90d3be0a53ae --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/partitioners.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:166a63fbe903d78c104caa25e82acf6539fe2e558519895016e7a48f75ec0c78 +size 191712 diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/predispatch.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/predispatch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e7406737ef91366d1b6d2bf375a4b87831eb2c3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/predispatch.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/pyfunctorch.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/pyfunctorch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffcfcd15bec9f5590ef2c516ac5d665e1e5da13a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/pyfunctorch.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/python_key.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/python_key.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b0ae16ca2a417ec09a1ae0d30db47408cb5bed3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/python_key.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/pytree_hacks.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/pytree_hacks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8303fcf25ef78cccbfc039018aac48ba1445d3c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/pytree_hacks.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/top_operators_github_usage.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/top_operators_github_usage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd3dec5343c6c3797e8c7159a7a4f0bda4aca5e0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/top_operators_github_usage.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19f163bc0e9d3d08a9e8cc5b97389091e8439a82 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/vmap.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/vmap.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8eb79f6eaadd1a424e2d54e20a37791a86c0200 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/vmap.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__init__.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10a55772ab58b21573a6eba0356ddd3080164ac7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__init__.py @@ -0,0 +1,5 @@ +# 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. diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb3afecc4499723a1adc32bb7f72450f9005d253 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/ac_logging_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/ac_logging_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f35db80b7745e4b4450eafc0754306c4ccf5a80 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/ac_logging_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/graph_info_provider.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/graph_info_provider.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..293617cc3062705eccf275d5b7a39bc04c3e3738 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/graph_info_provider.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/knapsack.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/knapsack.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de994026758f73022598104e4edab130092c1c16 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/knapsack.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/knapsack_evaluator.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/knapsack_evaluator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8bd4de8594e1054959ff888747f8663fb843436e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/knapsack_evaluator.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/remat_using_tags_for_fwd_loss_bwd_graph_pass.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/remat_using_tags_for_fwd_loss_bwd_graph_pass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c876336779006ec47f68bf692cf1b615a4beec2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/__pycache__/remat_using_tags_for_fwd_loss_bwd_graph_pass.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/ac_logging_utils.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/ac_logging_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f456804d8bf66ceec62081439fd1da47c21df3e8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/ac_logging_utils.py @@ -0,0 +1,228 @@ +import json +import logging +from typing import Any + +from torch._logging import trace_structured +from torch.fx import Graph, Node + + +log: logging.Logger = logging.getLogger(__name__) + + +def create_joint_graph_node_information( + joint_graph: Graph, + recomputable_node_info: dict[str, int], +) -> dict[str, Any]: + joint_graph_node_information: dict[str, Any] = {} + + for i, joint_graph_node in enumerate(joint_graph.nodes): + is_recomputable_candidate: bool = ( + joint_graph_node.name in recomputable_node_info + ) + tensor_meta = joint_graph_node.meta.get("tensor_meta") + # pyrefly: ignore [implicit-any] + shape = getattr(tensor_meta, "shape", []) if tensor_meta else [] + + node_info: dict[str, Any] = { + "index": i, + "name": joint_graph_node.name, + "is_recomputable_candidate": is_recomputable_candidate, + "target": str(joint_graph_node.target), + "shape": str(shape), + "input_arguments": [inp.name for inp in joint_graph_node.all_input_nodes], + "stack_trace": joint_graph_node.meta.get("stack_trace", ""), + } + + if is_recomputable_candidate: + idx: int = recomputable_node_info[joint_graph_node.name] + node_info["recomputable_candidate_info"] = { + "recomputable_node_idx": idx, + } + + joint_graph_node_information[joint_graph_node.name] = node_info + + return joint_graph_node_information + + +def create_joint_graph_edges(joint_graph: Graph) -> list[tuple[str, str]]: + joint_graph_edges: list[tuple[str, str]] = [ + (inp.name, node.name) + for node in joint_graph.nodes + for inp in node.all_input_nodes + ] + return joint_graph_edges + + +def create_activation_checkpointing_logging_structure_payload( + joint_graph: Graph, + joint_graph_node_information: dict[str, Any], + joint_graph_edges: list[tuple[str, str]], + all_recomputable_banned_nodes: list[Node], + expected_runtime: float, + saved_node_idxs: list[int], + recomputable_node_idxs: list[int], + memories_banned_nodes: list[int], + normalized_memories_banned_nodes: list[float], + runtimes_banned_nodes: list[float], + min_cut_saved_values: list[Node], + memory_budget: float, + min_act_size: float, + max_act_size: float, + saved_values_act_size: float, + more_aggressive_saved_values_mem_ratio: float, + aggressive_recomputation_saved_values_mem_ratio: float, +) -> dict[str, Any]: + """ + Creates a structured payload for logging activation checkpointing information. + + Args: + joint_graph: The computational graph representing operations. + joint_graph_node_information: Dictionary containing information about nodes in the joint graph. + joint_graph_edges: List of edges in the joint graph represented as tuples of node names. + all_recomputable_banned_nodes: List of nodes that are banned from recomputation. + expected_runtime: Expected runtime of the computation. + saved_node_idxs: Indices of nodes that are saved (not recomputed). + recomputable_node_idxs: Indices of nodes that can be recomputed. + memories_banned_nodes: Memory usage values (in absolute units) for banned nodes. + normalized_memories_banned_nodes: Normalized memory usage values for banned nodes, + used as input to the knapsack algorithm. + runtimes_banned_nodes: Runtime values for banned nodes, used as input to the + knapsack algorithm. + min_cut_saved_values: List of nodes saved by the min-cut algorithm. + memory_budget: The memory budget ratio (0 to 1) used for activation checkpointing. + min_act_size: Minimum activation size in GB (size when saving only inputs). + max_act_size: Maximum activation size in GB (size when saving all runtime-optimized values). + saved_values_act_size: Estimated activation size in GB for the saved values. + more_aggressive_saved_values_mem_ratio: Memory ratio for more aggressive recomputation strategy. + aggressive_recomputation_saved_values_mem_ratio: Memory ratio for fully aggressive recomputation strategy. + + Returns: + A dictionary containing structured logging information for activation checkpointing. + """ + activation_checkpointing_logging_structure_payload: dict[str, Any] = { + "Joint Graph Size": len(joint_graph.nodes), + "Joint Graph Edges": { + "Total": len(joint_graph_edges), + "Edges": joint_graph_edges, + }, + "Joint Graph Node Information": joint_graph_node_information, + "Recomputable Banned Nodes Order": [ + node.name for node in all_recomputable_banned_nodes + ], + "Expected Runtime": expected_runtime, + "Knapsack Saved Nodes": saved_node_idxs, + "Knapsack Recomputed Nodes": recomputable_node_idxs, + "Absolute Memories": memories_banned_nodes, + "Knapsack Input Memories": normalized_memories_banned_nodes, + "Knapsack Input Runtimes": runtimes_banned_nodes, + "Min Cut Solution Saved Values": [node.name for node in min_cut_saved_values], + "Memory Budget": memory_budget, + "Min Activation Size (GB)": min_act_size, + "Max Activation Size (GB)": max_act_size, + "Saved Values Activation Size (GB)": saved_values_act_size, + "More Aggressive Saved Values Mem Ratio": more_aggressive_saved_values_mem_ratio, + "Aggressive Recomputation Saved Values Mem Ratio": aggressive_recomputation_saved_values_mem_ratio, + } + return activation_checkpointing_logging_structure_payload + + +def create_structured_trace_for_min_cut_info( + joint_graph: Graph, + all_recomputable_banned_nodes: list[Node], + saved_node_idxs: list[int], + recomputable_node_idxs: list[int], + expected_runtime: float, + memories_banned_nodes: list[int], + normalized_memories_banned_nodes: list[float], + runtimes_banned_nodes: list[float], + min_cut_saved_values: list[Node], + memory_budget: float, + min_act_size: float, + max_act_size: float, + saved_values_act_size: float, + more_aggressive_saved_values_mem_ratio: float, + aggressive_recomputation_saved_values_mem_ratio: float, +) -> None: + """ + Creates a structured trace for minimum cut information in the graph. + + Args: + joint_graph: The computational graph representation. + all_recomputable_banned_nodes: List of nodes that can be recomputed. + saved_node_idxs: Indices of nodes that are saved in memory. + recomputable_node_idxs: Indices of nodes that are recomputed. + expected_runtime: Expected runtime for the computation. + memories_banned_nodes: Memory requirements for each banned node in bytes. + normalized_memories_banned_nodes: Normalized memory requirements for each banned node + (typically scaled between 0 and 1 for relative comparison). + runtimes_banned_nodes: Runtime costs associated with each banned node. + min_cut_saved_values: Nodes that are saved as part of the minimum cut solution. + memory_budget: The memory budget ratio (0 to 1) used for activation checkpointing. + min_act_size: Minimum activation size in GB (size when saving only inputs). + max_act_size: Maximum activation size in GB (size when saving all runtime-optimized values). + saved_values_act_size: Estimated activation size in GB for the saved values. + more_aggressive_saved_values_mem_ratio: Memory ratio for more aggressive recomputation strategy. + aggressive_recomputation_saved_values_mem_ratio: Memory ratio for fully aggressive recomputation strategy. + """ + # Create a dictionary to store recomputable node information + recomputable_node_info: dict[str, int] = { + node.name: idx for idx, node in enumerate(all_recomputable_banned_nodes) + } + + # Create joint graph node information + joint_graph_node_information = create_joint_graph_node_information( + joint_graph, recomputable_node_info + ) + + # Update node information with recomputable candidate details + for node_name, node_info in joint_graph_node_information.items(): + if node_info["is_recomputable_candidate"]: + idx = recomputable_node_info[node_name] + node_info["recomputable_candidate_info"]["memory"] = memories_banned_nodes[ + idx + ] + node_info["recomputable_candidate_info"]["runtime"] = runtimes_banned_nodes[ + idx + ] + node_info["recomputable_candidate_info"]["is_saved"] = ( + idx in saved_node_idxs + ) + node_info["recomputable_candidate_info"]["is_recomputed"] = ( + idx in recomputable_node_idxs + ) + + # Create joint graph edges + joint_graph_edges = create_joint_graph_edges(joint_graph) + + # Create activation checkpointing logging structure payload + activation_checkpointing_logging_structure_payload = create_activation_checkpointing_logging_structure_payload( + joint_graph=joint_graph, + joint_graph_node_information=joint_graph_node_information, + joint_graph_edges=joint_graph_edges, + all_recomputable_banned_nodes=all_recomputable_banned_nodes, + expected_runtime=expected_runtime, + saved_node_idxs=saved_node_idxs, + recomputable_node_idxs=recomputable_node_idxs, + memories_banned_nodes=memories_banned_nodes, + normalized_memories_banned_nodes=normalized_memories_banned_nodes, + runtimes_banned_nodes=runtimes_banned_nodes, + min_cut_saved_values=min_cut_saved_values, + memory_budget=memory_budget, + min_act_size=min_act_size, + max_act_size=max_act_size, + saved_values_act_size=saved_values_act_size, + more_aggressive_saved_values_mem_ratio=more_aggressive_saved_values_mem_ratio, + aggressive_recomputation_saved_values_mem_ratio=aggressive_recomputation_saved_values_mem_ratio, + ) + + # Create structured trace + payload_str = json.dumps(activation_checkpointing_logging_structure_payload) + + # Store on graph for AOTAutograd cache replay + joint_graph._min_cut_info_str = payload_str # type: ignore[attr-defined] + + trace_structured( + "artifact", + metadata_fn=lambda: {"name": "min_cut_information", "encoding": "json"}, + payload_fn=lambda: payload_str, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/graph_info_provider.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/graph_info_provider.py new file mode 100644 index 0000000000000000000000000000000000000000..0294e32f292e5f9fe00eb6a1227c7c948757171b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/graph_info_provider.py @@ -0,0 +1,319 @@ +from typing import Any + +import networkx as nx + +from torch.fx import Graph, Node + + +class GraphInfoProvider: + """ + This class provides information about the graph, such as the nodes, edges, and their runtime and memory requirements. + It also provides methods to create graphs from the information provided. + """ + + __RECOMPUTABLE_NODE_ONLY_GRAPH = "recomputable_node_only_graph" + __RECOMPUTABLE_NODE_ONLY_GRAPH_WITH_LARGER_GRAPH_CONTEXT = ( + "recomputable_node_only_graph_with_larger_graph_context" + ) + __FULL_NX_JOINT_GRAPH = "full_nx_joint_graph" + __SIMPLIFIED_FX_JOINT_GRAPH = "fx_joint_graph" + + def __init__( + self, + graph_nodes_in_order: list[str], + graph_edges: list[tuple[str, str]], + all_recomputable_banned_nodes: list[str], + all_node_runtimes: dict[str, float] | None = None, + all_node_memories: dict[str, float] | None = None, + recorded_knapsack_input_memories: list[float] | None = None, + recorded_knapsack_input_runtimes: list[float] | None = None, + joint_graph: Graph | None = None, + ) -> None: + self.graph_nodes_in_order = graph_nodes_in_order + self.graph_edges = graph_edges + self.all_node_runtimes: dict[str, float] = dict() + if all_node_runtimes is None: + if recorded_knapsack_input_runtimes is None: + raise ValueError( + "Either all_node_runtimes or recorded_knapsack_input_runtimes must be provided." + ) + self.all_node_runtimes = { + node: recorded_knapsack_input_runtimes[i] + for i, node in enumerate(all_recomputable_banned_nodes) + } + else: + self.all_node_runtimes.update(all_node_runtimes) + self.all_node_memories: dict[str, float] = dict() + if all_node_memories is None: + if recorded_knapsack_input_memories is None: + raise ValueError( + "Either all_node_memories or recorded_knapsack_input_memories must be provided." + ) + self.all_node_memories = { + node: recorded_knapsack_input_memories[i] + for i, node in enumerate(all_recomputable_banned_nodes) + } + else: + self.all_node_memories.update(all_node_memories) + self.all_recomputable_banned_nodes = all_recomputable_banned_nodes + self.all_recomputable_banned_nodes_set = set(all_recomputable_banned_nodes) + self.recorded_knapsack_input_memories = recorded_knapsack_input_memories + self.recorded_knapsack_input_runtimes = recorded_knapsack_input_runtimes + self._lazily_initialized_graphs: dict[str, Any] = { + self.__RECOMPUTABLE_NODE_ONLY_GRAPH: None, + self.__RECOMPUTABLE_NODE_ONLY_GRAPH_WITH_LARGER_GRAPH_CONTEXT: None, + self.__FULL_NX_JOINT_GRAPH: None, + self.__SIMPLIFIED_FX_JOINT_GRAPH: None, + } + + @classmethod + def inialize_from_graph( + cls, + joint_graph: Graph, + all_recomputable_banned_nodes: list[Node], + recorded_knapsack_input_memories: list[float], + recorded_knapsack_input_runtimes: list[float], + ) -> "GraphInfoProvider": + """ + Enables initialization from a joint graph. + """ + graph_nodes_in_order = [node.name for node in joint_graph.nodes] + graph_edges = [ + (node.name, user.name) for node in joint_graph.nodes for user in node.users + ] + all_recomputable_banned_node_names = [ + node.name for node in all_recomputable_banned_nodes + ] + return cls( + graph_nodes_in_order=graph_nodes_in_order, + graph_edges=graph_edges, + all_recomputable_banned_nodes=all_recomputable_banned_node_names, + recorded_knapsack_input_memories=recorded_knapsack_input_memories, + recorded_knapsack_input_runtimes=recorded_knapsack_input_runtimes, + joint_graph=joint_graph, + ) + + @property + def recomputable_node_only_graph(self) -> nx.DiGraph: + if self._lazily_initialized_graphs[self.__RECOMPUTABLE_NODE_ONLY_GRAPH] is None: + self._lazily_initialized_graphs[self.__RECOMPUTABLE_NODE_ONLY_GRAPH] = ( + self._create_recomputable_node_only_graph() + ) + return self._lazily_initialized_graphs[self.__RECOMPUTABLE_NODE_ONLY_GRAPH] + + @property + def recomputable_node_only_graph_with_larger_graph_context(self) -> nx.DiGraph: + if ( + self._lazily_initialized_graphs[ + self.__RECOMPUTABLE_NODE_ONLY_GRAPH_WITH_LARGER_GRAPH_CONTEXT + ] + is None + ): + self._lazily_initialized_graphs[ + self.__RECOMPUTABLE_NODE_ONLY_GRAPH_WITH_LARGER_GRAPH_CONTEXT + ] = self._create_recomputable_node_only_graph_with_larger_graph_context() + return self._lazily_initialized_graphs[ + self.__RECOMPUTABLE_NODE_ONLY_GRAPH_WITH_LARGER_GRAPH_CONTEXT + ] + + @property + def full_joint_nx_graph(self) -> nx.DiGraph: + if self._lazily_initialized_graphs[self.__FULL_NX_JOINT_GRAPH] is None: + self._lazily_initialized_graphs[self.__FULL_NX_JOINT_GRAPH] = ( + self._create_full_joint_graph() + ) + return self._lazily_initialized_graphs[self.__FULL_NX_JOINT_GRAPH] + + @property + def simplified_fx_joint_graph(self) -> Graph: + if self._lazily_initialized_graphs[self.__SIMPLIFIED_FX_JOINT_GRAPH] is None: + self._lazily_initialized_graphs[self.__SIMPLIFIED_FX_JOINT_GRAPH] = ( + self._recreate_psuedo_joint_graph() + ) + return self._lazily_initialized_graphs[self.__SIMPLIFIED_FX_JOINT_GRAPH] + + def get_non_ac_peak_memory(self) -> float: + return sum( + self.all_node_memories[node_name] + for node_name in self.all_recomputable_banned_nodes_set + ) + + def get_theoretical_max_runtime(self) -> float: + return sum( + self.all_node_runtimes[node_name] + for node_name in self.all_recomputable_banned_nodes_set + ) + + def get_knapsack_memory_input(self) -> list[float]: + return ( + self.recorded_knapsack_input_memories + if self.recorded_knapsack_input_memories + else [ + self.all_node_memories[node_name] + for node_name in self.all_recomputable_banned_nodes + ] + ) + + def get_knapsack_runtime_input(self) -> list[float]: + return ( + self.recorded_knapsack_input_runtimes + if self.recorded_knapsack_input_runtimes + else [ + self.all_node_runtimes[node_name] + for node_name in self.all_recomputable_banned_nodes + ] + ) + + def _create_recomputable_node_only_graph(self) -> nx.DiGraph: + graph = nx.DiGraph() + for recomputable_node in self.all_recomputable_banned_nodes: + graph.add_node(recomputable_node) + + for a, b in self.graph_edges: + if ( + a in self.all_recomputable_banned_nodes_set + and b in self.all_recomputable_banned_nodes_set + ): + graph.add_edge(a, b) + return graph + + def _create_recomputable_node_only_graph_with_larger_graph_context( + self, + ) -> nx.DiGraph: + # Create a dictionary to store the reachable nodes for each node + all_recomputable_banned_nodes_set = set(self.all_recomputable_banned_nodes) + + reachable_nodes = {} + for node in all_recomputable_banned_nodes_set: + # Use BFS to find all reachable nodes + predecessors = dict(nx.bfs_predecessors(self.full_joint_nx_graph, node)) + reachable_recomputable_nodes = set(predecessors.keys()).intersection( + all_recomputable_banned_nodes_set + ) + reachable_nodes[node] = reachable_recomputable_nodes + # Create the candidate graph + candidate_graph = nx.DiGraph() + candidate_graph.add_nodes_from(all_recomputable_banned_nodes_set) + for node1 in all_recomputable_banned_nodes_set: + for node2 in reachable_nodes[node1]: + # Check if there is an overlapping path + overlapping_path = False + for intermediate_node in reachable_nodes[node1]: + if ( + intermediate_node != node2 + and node2 in reachable_nodes[intermediate_node] + ): + overlapping_path = True + break + if not overlapping_path: + candidate_graph.add_edge(node1, node2) + return candidate_graph + + def _create_full_joint_graph(self) -> nx.DiGraph: + graph = nx.DiGraph() + for node in self.graph_nodes_in_order: + if node == "output": + continue + graph.add_node(node) + + for a, b in self.graph_edges: + if a == "output" or b == "output": + continue + graph.add_edge(a, b) + return graph + + def _recreate_psuedo_joint_graph(self) -> Graph: + # Create a dictionary to store the dependencies of each node + node_dependencies: dict[str, list[str]] = { + node: [] for node in self.graph_nodes_in_order + } + for a, b in self.graph_edges: + if a not in node_dependencies or b not in node_dependencies: + raise ValueError(f"Edge ({a}, {b}) references a non-existent node.") + node_dependencies[b].append(a) + + joint_graph = Graph() + # Create nodes in the graph + nodes: dict[str, Node] = {} + for node_name in self.graph_nodes_in_order: + input_nodes = [nodes[dep] for dep in node_dependencies[node_name]] + if input_nodes: + node = joint_graph.call_function(lambda *x: x, tuple(input_nodes)) + node.name = node_name + else: + node = joint_graph.placeholder(node_name) + nodes[node_name] = node + return joint_graph + + def _visualize_recomputable_candidate_graph_with_larger_context( + self, + layout_k: float = 0.5, + layout_iterations: int = 30, + ) -> None: + """ + Visualize the recomputable candidate graph with larger context. + """ + from matplotlib import cm, colors as mcolors, pyplot as plt + + pos = nx.spring_layout( + self.recomputable_node_only_graph_with_larger_graph_context, + k=layout_k, + iterations=layout_iterations, + ) + # pos = nx.spectral_layout(graph_with_indirect_edges) + plt.figure(figsize=(20, 15)) + + # Create a dictionary for node labels using the index + labels = { + node: self.recomputable_node_only_graph_with_larger_graph_context.nodes[ + node + ].get("index", node) + for node in self.recomputable_node_only_graph_with_larger_graph_context.nodes + } + + # Extract memory values and normalize them + norm = mcolors.Normalize( + vmin=min(self.get_knapsack_memory_input()), + vmax=max(self.get_knapsack_memory_input()), + ) + cmap = cm.viridis # type: ignore[attr-defined] + + # Assign colors based on memory + node_colors = [ + cmap( + norm( + float( + self.recomputable_node_only_graph_with_larger_graph_context.nodes[ + node + ]["memory"] + ) + ) + ) + for node in self.recomputable_node_only_graph_with_larger_graph_context.nodes + ] + + # Draw the graph with parsed nodes only + nx.draw_networkx_nodes( + self.recomputable_node_only_graph_with_larger_graph_context, + pos, + node_color=node_colors, + node_size=300, + label="Parsed Nodes", + ) + nx.draw_networkx_edges( + self.recomputable_node_only_graph_with_larger_graph_context, + pos, + arrows=True, + arrowsize=10, + ) + nx.draw_networkx_labels( + self.recomputable_node_only_graph_with_larger_graph_context, + pos, + labels=labels, + font_size=8, + font_weight="bold", + ) + + plt.title("Memory Colour Coded Dependency Graph for Recomputable Nodes") + plt.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), label="Memory") + plt.show() diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/knapsack.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/knapsack.py new file mode 100644 index 0000000000000000000000000000000000000000..b2f0a124c64c1ec7ec6651aa79ff62ebec557949 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/knapsack.py @@ -0,0 +1,267 @@ +import torch + + +def greedy_knapsack( + memory: list[float], runtimes: list[float], max_memory: float +) -> tuple[float, list[int], list[int]]: + n = len(runtimes) + items = list(range(n)) + + # Sort items based on the ratio of runtime to memory in descending order + items = sorted(items, key=lambda i: runtimes[i] / memory[i], reverse=True) + + total_memory = 0.0 + total_runtime = 0.0 + items_to_save = [] + items_to_allow_recomputing = [] + + for i in items: + if total_memory + memory[i] <= max_memory: + total_memory += memory[i] + total_runtime += runtimes[i] + items_to_save.append(i) + else: + items_to_allow_recomputing.append(i) + return total_runtime, items_to_save, items_to_allow_recomputing + + +def ilp_knapsack( + memory: list[float], runtimes: list[float], max_memory: float +) -> tuple[float, list[int], list[int]]: + import numpy as np + + try: + from scipy.optimize import Bounds, LinearConstraint, milp + except ImportError: + raise RuntimeError( + "To use the ILP for memory budget checkpointing you need to install scipy" + ) from None + + np_memory = np.array(memory) + np_runtimes = np.array(runtimes) + c = -np_runtimes # type: ignore[operator] + + memory_constraint = LinearConstraint(A=np_memory, ub=np.array(max_memory)) + constraints = [memory_constraint] + + integrality = np.ones_like(c) + res = milp( + c=c, constraints=constraints, integrality=integrality, bounds=Bounds(0, 1) + ) + if not res.success: + raise RuntimeError("Somehow scipy solving failed") + + items_to_save = [] + items_to_allow_recomputing = [] + for idx, i in enumerate(res.x): + if i == 1: + items_to_save.append(idx) + else: + items_to_allow_recomputing.append(idx) + return -res.fun, items_to_save, items_to_allow_recomputing + + +def dp_knapsack( + memory: list[float], runtime: list[float], max_memory: float +) -> tuple[float, list[int], list[int]]: + # Scaling factor to convert floating point weights to integers + S = 10000 + + # Quantize the memory weights + quantized_memory = torch.tensor( + [round(m * S) for m in memory], dtype=torch.long, device="cpu" + ) + runtimes = torch.tensor(runtime, dtype=torch.float32, device="cpu") + + # Quantized pseudopolynomial DP for 0-1 Knapsack + quantized_max_memory = round(max_memory * S) + + n = len(memory) + + # Initialize the DP table + # TODO(chilli): I think if needed, this memory can be optimized with sliding + # window trick + Hirschberg trick: + # https://codeforces.com/blog/entry/47247?#comment-316200 + dp = torch.zeros( + (n + 1, quantized_max_memory + 1), dtype=torch.float32, device="cpu" + ) + + for i in range(1, n + 1): + current_memory = quantized_memory[i - 1] + current_runtime = runtimes[i - 1] + + # Copy the previous row + dp[i, :] = dp[i - 1, :] + + # Update dp[i, j] for all j >= current_memory + if current_memory == 0: + dp[i, :] = dp[i - 1, :] + current_runtime + else: + dp[i, current_memory:] = torch.maximum( + dp[i - 1, current_memory:], + dp[i - 1, :-current_memory] + current_runtime, + ) + + # Backtrack to find the items included in the knapsack + saved_items = [] + recomputable_items = [] + j: int = quantized_max_memory + for i in range(n, 0, -1): + if dp[i][j] != dp[i - 1][j]: + saved_items.append(i - 1) # Include this item (indexing from 0) + j -= int(quantized_memory[i - 1].item()) + else: + recomputable_items.append(i - 1) + + saved_items.reverse() # To get items in the order they were added + + # The maximum runtime that can be achieved within the max_memory constraint + max_runtime = dp[n][quantized_max_memory].item() + + return max_runtime, saved_items, recomputable_items + + +def dp_knapsack_sliding_hirschberg( + memory: list[float], runtime: list[float], max_memory: float +) -> tuple[float, list[int], list[int]]: + # Scaling factor to convert floating point weights to integers + S = 10000 + + # q_ prefix stands for quantized + q_memory = [int(round(m * S)) for m in memory] + runtimes = [float(v) for v in runtime] + + q_max_memory = int(round(max_memory * S)) + + q_memory_length = len(q_memory) + if q_memory_length == 0: + return 0.0, [], [] + + item_indices = list(range(q_memory_length)) + dp_profile_size = q_max_memory + 1 + + # Current DP profile (row) + dp_profile = torch.zeros(dp_profile_size, dtype=torch.float32, device="cpu") + # Store a candidate for next dp_profile - current dp row + item + candidate_profile = torch.empty(dp_profile_size, dtype=torch.float32, device="cpu") + left_profile = torch.empty(dp_profile_size, dtype=torch.float32, device="cpu") + right_profile = torch.empty(dp_profile_size, dtype=torch.float32, device="cpu") + + saved_items: list[int] = [] + recomputable_items: list[int] = [] + + # Explicit stack to optimize memory and avoid recursion + # Stack stores segments as (start index, end index, capacity for segment) + stack: list[tuple[int, int, int]] = [(0, q_memory_length, q_max_memory)] + + # LIFO + while stack: + start, end, capacity = stack.pop() + length = end - start + if length == 0: + continue + + # Leaf + if length == 1: + index = item_indices[start] + memory_item = q_memory[index] + runtime_item = runtimes[index] + if memory_item <= capacity and runtime_item > 0.0: + saved_items.append(index) + else: + recomputable_items.append(index) + continue + + # Split the segment into two halves + middle = start + (length // 2) + left_start, left_end = middle, end + right_start, right_end = start, middle + + # Assign items to both halves + left_items = item_indices[left_start:left_end] + right_items = item_indices[right_start:right_end] + + # Working only on items allowed by segment's capacity + capacity = capacity + 1 + dp_view = dp_profile[:capacity] + candidate_view = candidate_profile[:capacity] + left_dp_local = left_profile[:capacity] + right_dp_local = right_profile[:capacity] + + # Left part + dp_view.zero_() + for index in left_items: + memory_item = q_memory[index] + runtime_item = runtimes[index] + + if memory_item == 0: + # Weight is 0, so add it to all capacities; a "free lunch", essentially + dp_view.add_(runtime_item) + continue + + # If item is too heavy, we skip it + if memory_item >= capacity: + continue + + # Add the current item so we can then pick the highest value + dp_view_candidate = candidate_view[: capacity - memory_item] + torch.add(dp_view[:-memory_item], runtime_item, out=dp_view_candidate) + # Take the highest - either previous (without current) or with current + torch.maximum( + dp_view[memory_item:], dp_view_candidate, out=dp_view[memory_item:] + ) + + # Store the left profile + left_dp_local.copy_(dp_view) + + # Right part + dp_view.zero_() + for index in right_items: + memory_item = q_memory[index] + runtime_item = runtimes[index] + + if memory_item == 0: + dp_view.add_(runtime_item) + continue + + if memory_item >= capacity: + continue + + dp_view_candidate = candidate_view[: capacity - memory_item] + torch.add(dp_view[:-memory_item], runtime_item, out=dp_view_candidate) + torch.maximum( + dp_view[memory_item:], dp_view_candidate, out=dp_view[memory_item:] + ) + + # Store the reversed right profile + right_dp_local.copy_(dp_view.flip(-1)) + + # In-place compute item-wise sum of left and right to pick the split point where the sum is highest + left_dp_local.add_(right_dp_local) + + # Pick the index of highest value of a pair, which we then use as a split point + best_split = int(torch.argmax(left_dp_local).item()) + + left_capacity = best_split + right_capacity = capacity - best_split + + # Clamp (might be removed if we're 100% sure that there is no edge case that will mess up the indices math) + if left_capacity < 0: + left_capacity = 0 + if right_capacity < 0: + right_capacity = 0 + if left_capacity > q_max_memory: + left_capacity = q_max_memory + if right_capacity > q_max_memory: + right_capacity = q_max_memory + + # Push right then left, so left is processed next + stack.append((right_start, right_end, right_capacity)) + stack.append((left_start, left_end, left_capacity)) + + saved_items = sorted(saved_items) + recomputable_items = sorted(recomputable_items) + + max_runtime = sum(runtime[i] for i in saved_items) + recomputable_items.reverse() + return max_runtime, saved_items, recomputable_items diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/knapsack_evaluator.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/knapsack_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..75e35571a1d5b14da2fab08e2c5d5fc92e8da112 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/knapsack_evaluator.py @@ -0,0 +1,282 @@ +import operator +from collections import deque +from collections.abc import Callable + +import networkx as nx + +from torch._functorch._activation_checkpointing.graph_info_provider import ( + GraphInfoProvider, +) + + +class KnapsackEvaluator: + """ + This class evaluates the theoretical runtime and peak memory usage of a given checkpointing strategy. + It takes in a graph and a list of nodes that are saved and recomputed, and then simulates the + backward pass to calculate the peak memory usage. + """ + + def __init__( + self, + graph_info_provider: GraphInfoProvider, + ) -> None: + self._graph_info_provider = graph_info_provider + + def _get_backward_memory_from_topologically_sorted_graph( + self, + node_graph: nx.DiGraph, + node_memories: dict[str, float], + saved_nodes_set: set[str], + peak_memory_after_forward_pass: float, + ) -> list[tuple[float, str]]: + """ + Simulates the backward pass and keeps track of the peak memory usage. + + High Level Steps: + 1. Set Initial Peak/Current Memory + Allows you to set the peak memory after the forward pass, but typically this is + the sum of the estimated memory of the saved nodes. + 2. Perform a reverse topological sort of the node_graph. + If full graph is defined then will sort the full graph and only process the subset + of nodes in the node_graph. + 3. Iterate through the sorted graph nodes. + If the node is saved then just drop its memory from current memory. + If the node is not saved then add its memory to current memory and then traverse its + predecessors to simulate recomputation chain. Will check if new peak memory after all + predecessors are processed. + + Args: + node_graph (nx.DiGraph): A directed graph representing the recomputable forward nodes. + saved_nodes_set (Set[str]): A set of node names that are saved. + peak_memory_after_forward_pass (float): The peak memory usage after the forward pass. + """ + current_memory = [ + (peak_memory_after_forward_pass, "Initial Peak/Current Memory") + ] + already_computed = set() + sorted_nodes = list(reversed(list(nx.topological_sort(node_graph)))) + dependencies_computed = set() + + for node in sorted_nodes: + if node in saved_nodes_set or node in already_computed: + current_memory.append( + ( + current_memory[-1][0] - node_memories[node], + f"Dropping Node(already saved): {node}", + ) + ) + continue + + already_computed.add(node) + current_memory.append( + ( + current_memory[-1][0] + node_memories[node], + f"Recomputing Node: {node}", + ) + ) + # Create a queue of dependencies required for recomputation + predecessor_queue = deque( + [ + dependency + # pyrefly: ignore [bad-unpacking] + for dependency, v in node_graph.in_edges(node) + if dependency not in already_computed + ] + ) + while predecessor_queue: + dep = predecessor_queue.popleft() + already_computed.add(dep) + dependencies_computed.add(dep) + current_memory.append( + ( + current_memory[-1][0] + node_memories[dep], + f"Recomputing Predecessor of {node}: {dep}", + ) + ) + # Add predecessors of the predecessor to the queue if they haven't been recomputed yet + # pyrefly: ignore [bad-unpacking] + for dependency_of_dependency, _ in node_graph.in_edges(dep): + if ( + dependency_of_dependency in already_computed + or dependency_of_dependency in saved_nodes_set + or dependency_of_dependency in predecessor_queue + ): + continue + predecessor_queue.append(dependency_of_dependency) + dependencies_computed.clear() + current_memory.append( + (current_memory[-1][0] - node_memories[node], f"Dropping Node: {node}") + ) + return current_memory + + def _validate_all_indexes_accounted_for_in_provided_output( + self, saved_nodes_idxs: list[int], recomputable_node_idxs: list[int] + ) -> None: + """ + Validate that all indexes are accounted for in the provided output. + This function checks that the union of saved nodes and recomputable nodes + covers all candidate nodes without any overlaps. + """ + recomputable_node_idxs_set = set(recomputable_node_idxs) + saved_nodes_idxs_set = set(saved_nodes_idxs) + all_candidate_nodes_idxs = set( + range(len(self._graph_info_provider.all_recomputable_banned_nodes)) + ) + # Check that there are no overlaps between saved nodes and recomputable nodes + if len(recomputable_node_idxs_set.intersection(saved_nodes_idxs_set)) != 0: + raise AssertionError( + f"Saved nodes and recomputable nodes cannot have any overlaps, " + f"but found overlap: {recomputable_node_idxs_set.intersection(saved_nodes_idxs_set)}" + ) + # Check that all candidate nodes are accounted for + if ( + recomputable_node_idxs_set.union(saved_nodes_idxs_set) + != all_candidate_nodes_idxs + ): + raise AssertionError( + f"All candidate nodes must be accounted for in the provided output, " + f"got union={recomputable_node_idxs_set.union(saved_nodes_idxs_set)}, " + f"expected={all_candidate_nodes_idxs}" + ) + + def evaluate_knapsack_output( + self, + saved_nodes_idxs: list[int], + recomputable_node_idxs: list[int], + account_for_backward_pass: bool = False, + ) -> dict[str, float]: + """ + Evaluate the theoretical runtime and peak memory usage of a given checkpointing strategy. + Args: + - saved_nodes_idxs (List[int]): The indices of nodes that are saved. + - recomputable_node_idxs (List[int]): The indices of nodes that need to be recomputed. + """ + self._validate_all_indexes_accounted_for_in_provided_output( + saved_nodes_idxs, recomputable_node_idxs + ) + recomputation_runtime = sum( + self._graph_info_provider.all_node_runtimes[ + self._graph_info_provider.all_recomputable_banned_nodes[node] + ] + for node in recomputable_node_idxs + ) + if account_for_backward_pass: + memory_list = self._get_backward_memory_from_topologically_sorted_graph( + node_graph=self._graph_info_provider.recomputable_node_only_graph_with_larger_graph_context, + saved_nodes_set={ + self._graph_info_provider.all_recomputable_banned_nodes[i] + for i in saved_nodes_idxs + }, + node_memories=self._graph_info_provider.all_node_memories, + peak_memory_after_forward_pass=sum( + self._graph_info_provider.all_node_memories[ + self._graph_info_provider.all_recomputable_banned_nodes[i] + ] + for i in saved_nodes_idxs + ), + ) + peak_memory = max(memory_list, key=operator.itemgetter(0))[0] + else: + peak_memory = sum( + self._graph_info_provider.all_node_memories[ + self._graph_info_provider.all_recomputable_banned_nodes[node] + ] + for node in saved_nodes_idxs + ) + return { + "peak_memory": peak_memory, + "recomputation_runtime": recomputation_runtime, + "non_ac_peak_memory": self._graph_info_provider.get_non_ac_peak_memory(), + "theoretical_max_runtime": self._graph_info_provider.get_theoretical_max_runtime(), + "percentage_of_theoretical_peak_memory": peak_memory + / self._graph_info_provider.get_non_ac_peak_memory(), + "percentage_of_theoretical_peak_runtime": recomputation_runtime + / self._graph_info_provider.get_theoretical_max_runtime(), + } + + def evaluate_distribution_of_results_for_knapsack_algo( + self, + knapsack_algo: Callable[ + [list[float], list[float], float], tuple[float, list[int], list[int]] + ], + memory_budget_values: list[float], + ) -> list[dict[str, float]]: + """ + Evaluates the distribution of results for a given knapsack algorithm. + Args: + knapsack_algo (Callable): The knapsack algorithm to use for evaluation. + memory_budget_values (List[float]): A list of memory budgets to evaluate. + """ + results = [] + for memory_budget in memory_budget_values: + _, saved_nodes, recomputed_nodes = knapsack_algo( + self._graph_info_provider.get_knapsack_memory_input(), + self._graph_info_provider.get_knapsack_runtime_input(), + memory_budget, + ) + result = self.evaluate_knapsack_output( + saved_nodes_idxs=saved_nodes, + recomputable_node_idxs=recomputed_nodes, + ) + result["memory_budget"] = memory_budget + results.append(result) + return results + + def get_knee_point_memory_budget( + self, + knapsack_algo: Callable[ + [list[float], list[float], float], tuple[float, list[int], list[int]] + ], + max_mem_budget: float = 0.1, + min_mem_budget: float = 0.001, + iterations: int = 100, + ) -> float: + """ + Finds the memory budget at the knee point in the Pareto frontier. + + The knee point is defined as the point where the trade-off between + runtime and memory usage is optimal. + + Args: + knapsack_algo (callable): Knapsack algorithm to use for evaluation. + max_mem_budget (float, optional): Maximum memory budget. Defaults to 0.1. + min_mem_budget (float, optional): Minimum memory budget. Defaults to 0.001. + iterations (int, optional): Number of memory budgets to evaluate. Defaults to 100. + + Returns: + float: Memory budget at the knee point. + """ + results = self.evaluate_distribution_of_results_for_knapsack_algo( + knapsack_algo=knapsack_algo, + memory_budget_values=[ + min_mem_budget + + i * (max_mem_budget - min_mem_budget) / (iterations - 1) + for i in range(iterations) + ], + ) + runtime_values = [ + result["percentage_of_theoretical_peak_runtime"] for result in results + ] + memory_values = [ + result["percentage_of_theoretical_peak_memory"] for result in results + ] + runtime_range = max(runtime_values) - min(runtime_values) + memory_range = max(memory_values) - min(memory_values) + if runtime_range == 0 or memory_range == 0: + return max_mem_budget + + # Normalize values + runtime_min = min(runtime_values) + memory_min = min(memory_values) + runtime_norm = [ + (value - runtime_min) / runtime_range for value in runtime_values + ] + memory_norm = [(value - memory_min) / memory_range for value in memory_values] + # Calculate Euclidean distance + distances = [ + (runtime_norm[i] ** 2 + memory_norm[i] ** 2) ** 0.5 + for i in range(len(runtime_norm)) + ] + # Find the knee point(shortest distance from the origin) + knee_index = distances.index(min(distances)) + return results[knee_index]["memory_budget"] diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/remat_using_tags_for_fwd_loss_bwd_graph_pass.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/remat_using_tags_for_fwd_loss_bwd_graph_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..a8826183675a8d169746aca181da469ecb1bb61b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_checkpointing/remat_using_tags_for_fwd_loss_bwd_graph_pass.py @@ -0,0 +1,246 @@ +"""AC rematerialize pass: Duplicates recompute nodes for backward, then DCE removes unused forward versions.""" + +import itertools +import logging +from typing import Any, overload + +import torch +import torch.fx as fx +from torch._functorch.compile_utils import raise_getitems +from torch._functorch.partitioners import ( + cleanup_recompute_tags, + force_save_bw_mutation_src, + has_recomputable_ops, + has_recomputable_rng_ops, + is_not_collective, + must_recompute, +) + + +log = logging.getLogger(__name__) +_EMPTY_CUSTOM_META: dict[str, object] = {} + + +def is_impure_node_for_dce(node: fx.Node) -> bool: + # Check for special collectives that should be treated as pure + if not is_not_collective(node): + # It's a collective (wait_tensor, all_gather_into_tensor, etc.) + # Treat as pure - can be eliminated if unused + return False + + # For everything else, fall back to the DEFAULT logic + # This is what eliminate_dead_code() calls when is_impure_node=None + impure_random = True + if torch._guards.TracingContext.try_get(): + impure_random = torch._inductor.config.fallback_random + return node.is_impure(impure_random) + + +def _is_backward_node(node: fx.Node, use_phase: bool = False) -> bool: + """Check if node is in backward region. + + If use_phase is True, only checks custom["phase"] == "backward" + (user annotation). Otherwise falls back to node.meta["autograd_backward"], + which Dynamo adds when tracing torch.autograd.grad. + """ + custom = node.meta.get("custom", _EMPTY_CUSTOM_META) + if use_phase: + return custom.get("phase") == "backward" + return node.meta.get("autograd_backward", False) + + +def _has_user_phase_annotation(gm: fx.GraphModule) -> bool: + """Check if any node has the user-level phase: backward annotation.""" + return any( + node.meta.get("custom", _EMPTY_CUSTOM_META).get("phase") == "backward" + for node in gm.graph.nodes + ) + + +def _collect_backward_regions( + gm: fx.GraphModule, use_phase: bool +) -> list[tuple[int, int, bool]]: + """Returns (bwd_start, bwd_end, needs_remat) for each backward region. + + Regions are maximal contiguous runs of backward nodes, as [start, end) + indices into the graph node list. + """ + regions: list[tuple[int, int, bool]] = [] + bwd_start: int | None = None + needs_remat = False + + for idx, node in enumerate(gm.graph.nodes): + if _is_backward_node(node, use_phase=use_phase): + if bwd_start is None: + bwd_start = idx + needs_remat = False + if not needs_remat and any( + must_recompute(inp) for inp in node.all_input_nodes + ): + needs_remat = True + elif bwd_start is not None: + regions.append((bwd_start, idx, needs_remat)) + bwd_start = None + + if bwd_start is not None: + regions.append((bwd_start, idx + 1, needs_remat)) + + return regions + + +def remat_using_tags_for_fwd_loss_bwd_graph(gm: fx.GraphModule) -> fx.GraphModule: + """ + Duplicate recompute nodes for backward use. DCE removes unused forward versions. + + Backward regions are identified by custom["phase"] == "backward" (user + annotation) or node.meta["autograd_backward"] == True (set automatically when + Dynamo traces torch.autograd.grad). When the user provides phase + annotations, only those annotated regions are used. + + The graph may contain multiple disjoint backward regions (e.g. chunked + loss). Regions that do not depend on recomputable forward nodes are + skipped. Only one region may require remat; if multiple do, we error + and ask the user to annotate which region to rematerialize. + """ + if not has_recomputable_ops(gm): + return gm + + if has_recomputable_rng_ops(gm): + raise RuntimeError( + "Activation checkpoint rematerialization in `forward-loss-backward` graph does not support RNG ops " + "in recompute regions. Please move RNG operations outside " + "of recompute regions, or use joint graph mode (where partitioner handles RNG)." + ) + + # Use partitioner pass to normalize AC node tags. + gm = cleanup_recompute_tags(gm, is_default_partition=True) + + force_save_bw_mutation_src(gm) + + # must_recompute (used inside _collect_backward_regions) requires + # cleanup_recompute_tags to have run first. + use_phase = _has_user_phase_annotation(gm) + regions = _collect_backward_regions(gm, use_phase) + if not regions: + return gm + + # User-annotated phase regions: multiple annotations is always an error. + if use_phase and len(regions) > 1: + raise RuntimeError( + f"Detected {len(regions)} disjoint backward regions annotated with " + 'phase: "backward" but remat only supports a single backward region. ' + "Please ensure only one contiguous region is annotated." + ) + + remat_regions = [(s, e) for s, e, needs in regions if needs] + + if len(remat_regions) > 1: + raise RuntimeError( + f"Detected {len(remat_regions)} disjoint backward regions that require recomputation, " + "but remat only supports one such region in a forward-loss-backward graph." + ) + + if not remat_regions: + return gm + + bwd_start, bwd_end = remat_regions[0] + + order = {node: idx for idx, node in enumerate(gm.graph.nodes)} + new_graph = fx.Graph() + env: dict[fx.Node, fx.Node] = {} + recomputed_nodes: dict[fx.Node, fx.Node] = {} + + # Insert forward nodes + for node in itertools.islice(gm.graph.nodes, 0, bwd_start): + env[node] = new_graph.node_copy(node, lambda x: env[x]) + + def _ensure_in_env(node: fx.Node) -> fx.Node: + """Eagerly copy a backward node and its dependencies into the new graph. + + The CPU offloading pass must run before remat. Offloaded forward nodes + carry ``cpu_offload_reload_node`` metadata pointing to their backward + reload chain (ao.reload -> ao.wait_tensor). Recomputed nodes need the + reloaded tensor, but the reload chain may not have been copied into + ``env`` yet (e.g. layer-boundary nodes whose reload is in a later + backward region). This helper copies the chain on demand. + """ + if node in env: + return env[node] + for dep in node.all_input_nodes: + _ensure_in_env(dep) + env[node] = new_graph.node_copy(node, lambda x: env[x]) + return env[node] + + @overload + def remat_input(x: fx.Node) -> fx.Node: ... + @overload + def remat_input(x: Any) -> Any: ... + + def remat_input(x: object) -> object: + if not isinstance(x, fx.Node): + return x + if x in recomputed_nodes: + return recomputed_nodes[x] + reload_node = x.meta.get("cpu_offload_reload_node") + if reload_node is not None: + return _ensure_in_env(reload_node) + return env[x] + + def gather_recompute_deps(node: fx.Node) -> set[fx.Node]: + deps: set[fx.Node] = set() + + def _gather(n: fx.Node) -> None: + if n in deps or n in recomputed_nodes or not must_recompute(n): + return + deps.add(n) + for inp in n.all_input_nodes: + _gather(inp) + + # Can't call _gather(node) directly: node itself may not be must_recompute + # (e.g. backward nodes), so _gather would return early without visiting inputs. + for inp in node.all_input_nodes: + _gather(inp) + return deps + + # Insert backward nodes + for node in itertools.islice(gm.graph.nodes, bwd_start, bwd_end): + # Gather all deps that need to be recomputed for this node + deps = gather_recompute_deps(node) + + # Insert deps in forward order (guaranteed disjoint from already-inserted) + # This is not as inefficient as it looks, because we only add fresh dependencies + # when they are not yet processed as recomputed nodes. + new_deps = sorted(deps, key=lambda n: order[n]) + if new_deps: + log.debug( + "To compute backward node %s, recomputing [%s]", + node.name, + ", ".join(dep.name for dep in new_deps), + ) + for dep in new_deps: + dup = new_graph.node_copy(dep, remat_input) + dup.name = dep.name + "_recomputed" + dup.meta["autograd_backward"] = True + recomputed_nodes[dep] = dup + + # Skip nodes already copied by _ensure_in_env (offload reload chains) + # to avoid duplicating H2D transfers. + if node not in env: + env[node] = new_graph.node_copy(node, remat_input) + + for node in itertools.islice(gm.graph.nodes, bwd_end, None): + if node not in env: + env[node] = new_graph.node_copy(node, lambda x: env[x]) + + new_gm = torch.fx.GraphModule(gm, new_graph) + + # DCE with custom is_impure_node (like default_partition) + # Treats certain collectives as pure while delegating to default impurity logic + new_gm.graph.eliminate_dead_code(is_impure_node=is_impure_node_for_dce) + + # raise_getitems pass for better memory (like default_partition) + new_gm = raise_getitems(new_gm) + + new_gm.recompile() + + return new_gm diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__init__.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10a55772ab58b21573a6eba0356ddd3080164ac7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__init__.py @@ -0,0 +1,5 @@ +# 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. diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80ad878f7a054c3c9b66d9155413b3be3ee1ae4a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__pycache__/activation_offloading.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__pycache__/activation_offloading.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..630773a1a9b1b85a87e6579a59c67336f755246c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__pycache__/activation_offloading.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__pycache__/offload_ops.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__pycache__/offload_ops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78276c0e463695bdb9314138d1a692c89df21f87 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/__pycache__/offload_ops.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/activation_offloading.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/activation_offloading.py new file mode 100644 index 0000000000000000000000000000000000000000..943ec2cf75cac70857bc959e6533c43d381b127f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/activation_offloading.py @@ -0,0 +1,828 @@ +"""Activation offloading for memory optimization during compilation. + +This module provides functionality to offload activations to CPU during the forward +pass and reload them during the backward pass, reducing GPU memory usage. It can be +applied to graphs produced by both AOT Autograd partitioners and make_fx-based tracing. +""" + +import logging +import operator +from dataclasses import dataclass + +import torch +import torch.fx as fx +from torch._functorch._activation_offloading.offload_ops import ( # noqa: F401 -- registers ao::offload, ao::reload, ao::wait_tensor ops + offload, + reload, + wait_tensor, +) +from torch._inductor.fx_passes.overlap_scheduling import benchmark_node, is_compute_node +from torch._subclasses.fake_tensor import extract_tensor_metadata +from torch.utils._ordered_set import OrderedSet + +from .. import config +from ..partitioners import _size_of, get_default_op_list, OpTypes + + +log: logging.Logger = logging.getLogger(__name__) + + +# Node name prefixes for offload/reload operations +# NOTE: right now we are using these prefixes as identifiers for offload/reload +CPU_OFFLOAD_PREFIX = "cpu_offload_" +GPU_RELOAD_PREFIX = "gpu_reload_" + + +def _find_all_effective_users(node: fx.Node, op_types: OpTypes) -> OrderedSet[fx.Node]: + """Find all effective users of a node, where view ops extend the lifetime + of the original node. If a user is a view op, recursively find users of + the view.""" + effective_users: OrderedSet[fx.Node] = OrderedSet() + for user in node.users: + if user.op == "output": + continue + effective_users.add(user) + if op_types.is_view(user): + effective_users.update(_find_all_effective_users(user, op_types)) + return effective_users + + +@dataclass +class ReloadNodeInfo: + """ + Information about backward reload related nodes for each reload operation. + + Pattern: ao.reload → ao.wait_tensor + + - Reload group (ao.reload): Performs the actual asynchronous data transfer. + Can be moved earlier in the graph to overlap with computation. + - Wait node (ao.wait_tensor): Synchronization point that blocks until the data + transfer completes. Must remain at the point where the data is first needed. + """ + + reload_group_nodes: list[fx.Node] + wait_event_node: fx.Node + transfer_size_bytes: int + transfer_time_ms: float + + +@dataclass +class ReloadQueueEntry: + """ + Entry in the reload queue for prefetch scheduling. + + Attributes: + pattern: The reload pattern information + remaining_time_ms: Remaining overlap time needed in milliseconds + """ + + pattern: ReloadNodeInfo + remaining_time_ms: float + + +def offload_activation_fw(graph: fx.Graph) -> None: + """ + Insert CPU offload operations in the forward pass graph. + + Offload operations are placed after the last effective use of each tensor marked + for offloading. This ensures the tensor is no longer needed on the GPU before + transferring it to CPU memory. + + NOTE: An alternative approach would offload tensors immediately after generation + to maximize compute-communication overlap. However, this requires additional + synchronization to ensure tensor deletion (which occurs on the default stream) + waits for the asynchronous offload operation to complete. This would necessitate + more complex tracking to separate operation scheduling from memory cleanup. + + Args: + graph: The forward graph to modify + """ + + op_types: OpTypes = get_default_op_list() + + output_node: fx.Node = graph.find_nodes(op="output")[0] + # pyrefly: ignore [bad-assignment] + fwd_outputs: tuple[fx.Node, ...] = output_node.args[ + 0 + ] # pyrefly: ignore [bad-assignment] + node_to_offload: dict[fx.Node, fx.Node] = dict() + node_to_index: dict[fx.Node, int] = { + node: idx for idx, node in enumerate(graph.nodes) + } + + for node in fwd_outputs: + if node.meta.get("saved_for_offloading", False) is False: + continue + + # Find insertion point, which is the last use + if all_effective_users := _find_all_effective_users(node, op_types): + last_user = max(all_effective_users, key=lambda n: node_to_index[n]) + else: + last_user: fx.Node = node + + # Insert the CPU offload operation after the last user + with graph.inserting_after(last_user): + cpu_node: fx.Node = graph.call_function( + torch.ops.prims.device_put.default, + args=(node, torch.device("cpu")), + kwargs={"non_blocking": True}, + name=CPU_OFFLOAD_PREFIX + str(node.name), + ) + cpu_node.meta["val"] = node.meta["val"].to(torch.device("cpu")) + cpu_node.meta["tensor_meta"] = extract_tensor_metadata(cpu_node.meta["val"]) + + node_to_offload[node] = cpu_node + + # Update the return node args + output_node.update_arg( + 0, tuple(node_to_offload.get(node, node) for node in fwd_outputs) + ) + + +def reload_activation_bw(graph: fx.Graph) -> None: + """ + Insert GPU reload operations in the backward pass graph. + + Reload operations are placed before the first use of each offloaded tensor, + transferring it from CPU back to GPU memory before it's needed for computation. + + Args: + graph: The backward graph to modify + """ + + node_to_index: dict[fx.Node, int] = { + node: idx for idx, node in enumerate(graph.nodes) + } + output_node: fx.Node = graph.find_nodes(op="output")[0] + + for node in graph.find_nodes(op="placeholder"): + if node.meta.get("saved_for_offloading", False) is False: + continue + + # Find insertion point, which is the first use or output node if no users + # The later should not happen, but inserting before output node is safe + insert_point: fx.Node = ( + min(node.users.keys(), key=lambda n: node_to_index[n]) + if node.users + else output_node + ) + + # Insert the GPU reload operation before the first user + original_device: torch.Device = node.meta["original_device"] + with graph.inserting_before(insert_point): + gpu_node: fx.Node = graph.call_function( + torch.ops.prims.device_put.default, + args=(node, original_device), + kwargs={"non_blocking": True}, + name=str(node.name).replace(CPU_OFFLOAD_PREFIX, GPU_RELOAD_PREFIX), + ) + gpu_node.meta["val"] = node.meta["val"].to(original_device) + gpu_node.meta["tensor_meta"] = extract_tensor_metadata(gpu_node.meta["val"]) + + # Replace all uses of the CPU tensor with the GPU tensor + for user in list(node.users.keys()): + if user != gpu_node: + user.replace_input_with(node, gpu_node) + + +def offload_activation_fw_async(graph: fx.Graph) -> None: + """Insert async CPU offload operations in the forward pass graph. + + Uses ao.offload + ao.wait_tensor ops which encapsulate stream management + internally, producing a clean 2-node IR per offloaded tensor. + """ + + op_types: OpTypes = get_default_op_list() + + output_node: fx.Node = graph.find_nodes(op="output")[0] + # pyrefly: ignore [bad-assignment] + fwd_outputs: tuple[fx.Node, ...] = output_node.args[ + 0 + ] # pyrefly: ignore [bad-assignment] + node_to_offload: dict[fx.Node, fx.Node] = dict() + node_to_index: dict[fx.Node, int] = { + node: idx for idx, node in enumerate(graph.nodes) + } + + if not any(n.meta.get("saved_for_offloading", False) for n in fwd_outputs): + return + + for node in fwd_outputs: + if node.meta.get("saved_for_offloading", False) is False: + continue + + if all_effective_users := _find_all_effective_users(node, op_types): + last_user = max(all_effective_users, key=lambda n: node_to_index[n]) + else: + last_user: fx.Node = node + + with graph.inserting_after(last_user): + offload_node: fx.Node = graph.call_function( + torch.ops.ao.offload.default, + args=(node,), + name=f"async_{CPU_OFFLOAD_PREFIX}{node.name}", + ) + offload_node.meta["val"] = node.meta["val"].to(torch.device("cpu")) + offload_node.meta["tensor_meta"] = extract_tensor_metadata( + offload_node.meta["val"] + ) + # The keepalive=node arg extends the GPU tensor's lifetime in the + # graph so the allocator doesn't reclaim it before the async D2H + # copy completes. + with graph.inserting_after(offload_node): + wait_node: fx.Node = graph.call_function( + torch.ops.ao.wait_tensor.default, + args=(offload_node, node), + name=CPU_OFFLOAD_PREFIX + str(node.name), + ) + wait_node.meta["val"] = offload_node.meta["val"] + wait_node.meta["tensor_meta"] = offload_node.meta["tensor_meta"] + + node_to_offload[node] = wait_node + + output_node.update_arg( + 0, tuple(node_to_offload.get(node, node) for node in fwd_outputs) + ) + + +def reload_activation_bw_async(graph: fx.Graph) -> None: + """Insert async GPU reload operations in the backward pass graph. + + Uses ao.reload + ao.wait_tensor ops which encapsulate stream management internally, + producing a clean 2-node IR per reloaded tensor. + """ + + node_to_index: dict[fx.Node, int] = { + node: idx for idx, node in enumerate(graph.nodes) + } + + nodes_to_reload = [ + n + for n in graph.find_nodes(op="placeholder") + if n.meta.get("saved_for_offloading", False) + ] + if not nodes_to_reload: + return + + for node in nodes_to_reload: + if not node.users: + raise RuntimeError( + f"Offloaded tensor {node.name} has no users in the backward graph" + ) + insert_point: fx.Node = min(node.users.keys(), key=lambda n: node_to_index[n]) + + original_device: torch.device = node.meta["original_device"] + original_size: tuple[int, ...] = node.meta["original_size"] + original_stride: tuple[int, ...] = node.meta["original_stride"] + with graph.inserting_before(insert_point): + reload_node: fx.Node = graph.call_function( + torch.ops.ao.reload.default, + args=( + node, + original_device, + list(original_size), + list(original_stride), + ), + name=f"async_{str(node.name).replace(CPU_OFFLOAD_PREFIX, GPU_RELOAD_PREFIX)}", + ) + reload_node.meta["val"] = torch.empty_strided( + original_size, + original_stride, + dtype=node.meta["val"].dtype, + device=original_device, + ) + reload_node.meta["tensor_meta"] = extract_tensor_metadata( + reload_node.meta["val"] + ) + wait_node: fx.Node = graph.call_function( + torch.ops.ao.wait_tensor.default, + args=(reload_node, node), + name=str(node.name).replace(CPU_OFFLOAD_PREFIX, GPU_RELOAD_PREFIX), + ) + wait_node.meta["val"] = reload_node.meta["val"] + wait_node.meta["tensor_meta"] = reload_node.meta["tensor_meta"] + + for user in list(node.users.keys()): + if user != reload_node and user != wait_node: + user.replace_input_with(node, wait_node) + + +def can_offload( + node: fx.Node, + fwd_outputs: OrderedSet[fx.Node], + model_outputs: OrderedSet[fx.Node], + static_lifetime_input_nodes: OrderedSet[fx.Node], +) -> bool: + """ + Determine if a node can be offloaded to CPU. + + Args: + node: The node to check + fwd_outputs: Forward module outputs, including model outputs and activations + model_outputs: Model outputs + + NOTE: Additional context for the logic behind these offloading checks: + + * fwd_outputs: Only saved intermediate tensors should be offloaded. + + * model_outputs / static_lifetime_input_nodes: Tensors that may be accessed outside + the compiled region (e.g., model outputs, static inputs) cannot be offloaded as + they must remain accessible beyond the scope of the compiled graph. + + * views / getitems: Offloading such nodes can lead to segmentation faults. + + * contiguous: Offloading non-contiguous tensors causes CPU-side stride changes + during both forward and backward passes when using the Inductor backend. While + these stride changes cancel each other out, they introduce significant compute + overhead. This is due to the contiguity check in ir.py (see link below). + TODO: This restriction could potentially be bypassed in the future. + Reference: https://github.com/pytorch/pytorch/blob/44ac69388a4a5eb463dbd2a13f00d1e3b924566c/torch/_inductor/ir.py#L3214 + + Additional criteria to consider for offloading optimization: + + * Tensor size: Small tensors may not fully utilize available bandwidth, reducing the + efficiency gains from offloading. + + * Position in forward/backward graph: Activations generated near the end of the forward + pass are typically consumed near the beginning of the backward pass. Offloading such + tensors may be counterproductive since they are quickly reloaded, not having sufficient + time to overlap the transfer with computation. + """ + + log.debug(f"Checking node {node.name} for offloading...") # noqa: G004 + + op_types: OpTypes = get_default_op_list() + + if node not in fwd_outputs: + log.debug("\tSkipped! Can only offload nodes in fwd_module_outputs.") + return False + if node in model_outputs: + log.debug("\tSkipped! Cannot offload model outputs.") + return False + if node in static_lifetime_input_nodes: + log.debug("\tSkipped! Cannot offload static input nodes.") + return False + if op_types.is_view(node): + log.debug("\tSkipped! Cannot offload views.") + return False + if node.target == operator.getitem: + log.debug("\tSkipped! Cannot offload getitems.") + return False + if hasattr(node, "meta") and "val" in node.meta: + if ( + isinstance(val := node.meta["val"], torch.Tensor) + and not val.is_contiguous() + ): + log.debug("\tSkipped! Cannot offload non-contiguous tensors.") + return False + + log.debug("\tGood!") + return True + + +def choose_offload_sets( + fwd_module: fx.GraphModule, + num_fwd_outputs: int, + static_lifetime_input_nodes: OrderedSet[fx.Node], +) -> bool: + """ + Decide which nodes will be offloaded based on the marked nodes and feasibility. + Marks nodes with "saved_for_offloading" if they should and can be offloaded. + + Args: + fwd_module: Forward graph module + bwd_module: Backward graph module + num_fwd_outputs: Number of forward outputs + + Returns: + bool: Whether activation offloading should be performed + """ + + fwd_outputs: OrderedSet[fx.Node] = OrderedSet( + fwd_module.graph.find_nodes(op="output")[0].args[0] + ) + model_outputs: OrderedSet[fx.Node] = OrderedSet( + fwd_module.graph.find_nodes(op="output")[0].args[0][:num_fwd_outputs] + ) + + should_perform_offloading = False + for node in fwd_module.graph.nodes: + if node.meta.get("should_offload", False) and can_offload( + node, fwd_outputs, model_outputs, static_lifetime_input_nodes + ): + node.meta["saved_for_offloading"] = True + should_perform_offloading = True + + return should_perform_offloading + + +def offload_chosen_sets( + fwd_module: fx.GraphModule, + bwd_module: fx.GraphModule, +) -> None: + """ + Add offload and reload nodes to the forward and backward graphs. + This function adds device_put operations without any stream handling. + + Args: + fwd_module: Forward module graph + bwd_module: Backward module graph + """ + + # Add offload nodes in forward graph + offload_activation_fw(fwd_module.graph) + + # Update backward graph inputs to be offloaded tensors + bwd_inputs: dict[str, fx.Node] = { + node.name: node for node in bwd_module.graph.find_nodes(op="placeholder") + } + for fwd_node in fwd_module.graph.find_nodes(op="output")[0].args[0]: + if CPU_OFFLOAD_PREFIX not in fwd_node.name: + continue + + bwd_node: fx.Node = bwd_inputs[fwd_node.name.replace(CPU_OFFLOAD_PREFIX, "")] + with bwd_module.graph.inserting_after(bwd_node): + bwd_offload_node: fx.Node = bwd_module.graph.placeholder(name=fwd_node.name) + + bwd_offload_node.meta.update(fwd_node.meta) + bwd_offload_node.meta["saved_for_offloading"] = True + bwd_offload_node.meta["original_device"] = bwd_node.meta["val"].device + bwd_offload_node.meta["original_size"] = tuple(bwd_node.meta["val"].size()) + bwd_offload_node.meta["original_stride"] = tuple(bwd_node.meta["val"].stride()) + bwd_node.replace_all_uses_with(bwd_offload_node) + bwd_module.graph.erase_node(bwd_node) + + # Add reload nodes in backward graph + reload_activation_bw(bwd_module.graph) + + +def offload_chosen_sets_async( + fwd_module: fx.GraphModule, + bwd_module: fx.GraphModule, +) -> None: + """ + Add async offload and reload nodes using ao ops. + + Uses ao.offload/ao.reload + ao.wait_tensor which encapsulate stream management, + instead of device_put + explicit stream operations. Can be applied to + partitioned forward/backward graphs or to a joint graph produced by make_fx. + """ + + offload_activation_fw_async(fwd_module.graph) + + # Replace backward graph placeholders with their offloaded (CPU) counterparts. + # For each offloaded forward output, find the matching backward input and swap + # it with a new placeholder carrying the CPU tensor's metadata, then mark it + # for reloading. + bwd_inputs: dict[str, fx.Node] = { + node.name: node for node in bwd_module.graph.find_nodes(op="placeholder") + } + for fwd_node in fwd_module.graph.find_nodes(op="output")[0].args[0]: + if CPU_OFFLOAD_PREFIX not in fwd_node.name: + continue + + bwd_node: fx.Node = bwd_inputs[fwd_node.name.replace(CPU_OFFLOAD_PREFIX, "")] + with bwd_module.graph.inserting_after(bwd_node): + bwd_offload_node: fx.Node = bwd_module.graph.placeholder(name=fwd_node.name) + + bwd_offload_node.meta.update(fwd_node.meta) + bwd_offload_node.meta["saved_for_offloading"] = True + bwd_offload_node.meta["original_device"] = bwd_node.meta["val"].device + bwd_offload_node.meta["original_size"] = tuple(bwd_node.meta["val"].size()) + bwd_offload_node.meta["original_stride"] = tuple(bwd_node.meta["val"].stride()) + bwd_node.replace_all_uses_with(bwd_offload_node) + bwd_module.graph.erase_node(bwd_node) + + reload_activation_bw_async(bwd_module.graph) + + +def activation_offload_sink_wait_async(fwd_module: fx.GraphModule) -> None: + """Sink ao.wait_tensor operations for offload completion to the end of the graph. + + This allows computation to overlap with offload operations. + + NOTE: Sinking waits to the end delays GPU memory release of the source + tensor (kept alive via the wait's keepalive arg) until the end of the + compiled graph. For per-layer compile this is fine (one layer's worth of + memory), but for full-model compile this means offloaded GPU tensors are + not freed until the entire forward pass completes. + """ + graph: fx.Graph = fwd_module.graph + output_node: fx.Node = graph.find_nodes(op="output")[0] + + wait_nodes_to_sink: list[fx.Node] = [ + node + for node in graph.nodes + if node.op == "call_function" + and node.target == torch.ops.ao.wait_tensor.default + and isinstance(node.args[0], fx.Node) + and node.args[0].op == "call_function" + and node.args[0].target == torch.ops.ao.offload.default + ] + + # prepend moves the node from its current position (no manual removal needed) + for wait_node in wait_nodes_to_sink: + output_node.prepend(wait_node) + + +def activation_reload_prefetch_async(bwd_module: fx.GraphModule) -> None: + """ + Prefetch backward reload operations by moving ao.reload nodes earlier + in the graph to overlap data transfer with computation, while keeping + ao.wait_tensor at its original position. + """ + graph: fx.Graph = bwd_module.graph + nodes_list: list[fx.Node] = list(graph.nodes) + + # Identify reload + wait pairs + reload_patterns: dict[fx.Node, ReloadNodeInfo] = {} + for node in graph.nodes: + if not ( + node.op == "call_function" and node.target == torch.ops.ao.reload.default + ): + continue + wait_node = next( + (u for u in node.users if u.target == torch.ops.ao.wait_tensor.default), + None, + ) + if wait_node is None: + continue + transfer_size_bytes: int = _calculate_transfer_size(node) + transfer_time_ms: float = _estimate_transfer_time_in_ms(transfer_size_bytes) + reload_patterns[node] = ReloadNodeInfo( + reload_group_nodes=[node], + wait_event_node=wait_node, + transfer_size_bytes=transfer_size_bytes, + transfer_time_ms=transfer_time_ms, + ) + + reorder_for_prefetch(nodes_list, reload_patterns) + + +def _calculate_transfer_size(device_put_node: fx.Node) -> int: + """Calculate the size in bytes of data being transferred.""" + + # ao.offload(tensor) -> tensor at args[0] + # ao.reload(tensor, device) -> tensor at args[0] + if device_put_node.target in ( + torch.ops.ao.offload.default, + torch.ops.ao.reload.default, + ): + return _size_of(device_put_node.args[0]) # pyrefly: ignore [bad-argument-type] + raise ValueError(f"Unexpected transfer op: {device_put_node.target}") + + +def _estimate_transfer_time_in_ms(transfer_size_bytes: int) -> float: + """Estimate transfer time in milliseconds based on size and bandwidth. + + Uses config.activation_offload_cpu_gpu_bw (GB/s) which should be set by + the user to match their hardware. + """ + return ( + transfer_size_bytes / (1024**3) * 1_000 / config.activation_offload_cpu_gpu_bw + ) + + +def identify_reload_patterns( + graph: fx.Graph, nodes_list: list[fx.Node], node_to_idx: dict[fx.Node, int] +) -> dict[fx.Node, ReloadNodeInfo]: + """ + Identify backward reload patterns in the graph. + + Pattern: fork → wait_stream → device_put → record_event → join → wait_event + + This uses position-based matching since these nodes are inserted together in + add_backward_reload_stream_ops() in a specific order. Since stream operations + do not have data dependencies between them, they are unsuitable for subgroup + pattern matching type of checks. + + Returns a dict mapping device_put node to ReloadNodeInfo containing: + - reload_group_nodes: fork → wait_stream → device_put → record_event → join + - wait_event_node: the wait_event node + - transfer_size_bytes: size of data being transferred + - transfer_time_ms: estimated transfer time in milliseconds + """ + patterns: dict[fx.Node, ReloadNodeInfo] = {} + + # Find all GPU reload device_put nodes whose inputs are placeholder nodes + reload_nodes: list[fx.Node] = [ + node + for node in graph.find_nodes( + op="call_function", target=torch.ops.prims.device_put.default + ) + if GPU_RELOAD_PREFIX in node.name + and ( + node.args + and isinstance(node.args[0], fx.Node) + and node.args[0].op == "placeholder" + ) + ] + + # Extract patterns for each reload device_put node + for reload_node in reload_nodes: + reload_node_idx: int = node_to_idx[reload_node] + + fork_node: fx.Node = nodes_list[reload_node_idx - 2] + wait_stream_node: fx.Node = nodes_list[reload_node_idx - 1] + record_event_node: fx.Node = nodes_list[reload_node_idx + 1] + join_node: fx.Node = nodes_list[reload_node_idx + 2] + wait_event_node: fx.Node = nodes_list[reload_node_idx + 3] + + # Validate the nodes are what we expect + # Removed in follow-up commit + _validate_pattern_nodes( # noqa: F821 # pyrefly: ignore [unknown-name] + fork_node, + wait_stream_node, + record_event_node, + join_node, + wait_event_node, + ) + + # Calculate transfer size and time + transfer_size_bytes: int = _calculate_transfer_size(reload_node) + transfer_time_ms: float = _estimate_transfer_time_in_ms(transfer_size_bytes) + + patterns[reload_node] = ReloadNodeInfo( + reload_group_nodes=[ + fork_node, + wait_stream_node, + reload_node, + record_event_node, + join_node, + ], + wait_event_node=wait_event_node, + transfer_size_bytes=transfer_size_bytes, + transfer_time_ms=transfer_time_ms, + ) + + return patterns + + +def reorder_for_prefetch( + nodes_list: list[fx.Node], + reload_patterns: dict[fx.Node, ReloadNodeInfo], +) -> None: + """ + Reorder nodes to prefetch reload operations by directly manipulating the graph. + + This follows the algorithm as follows: + - Go through nodes in reverse order + - When encountering a reload pattern, add it to a queue with its transfer time + - When encountering a compute node, use its runtime to satisfy overlap requirements + - Place reload patterns when their overlap requirement is satisfied + - When encountering placeholder nodes, flush queue as reloads cannot move before inputs + """ + + # Build a set of all nodes in reload groups for quick lookup + reload_group_nodes_set: set[fx.Node] = set() + for pattern in reload_patterns.values(): + reload_group_nodes_set.update(pattern.reload_group_nodes) + + # Queue to hold reload group nodes waiting to be placed (FIFO) + reload_queue: list[ReloadQueueEntry] = [] + + # Loop through nodes in reverse + for node in reversed(nodes_list): + if node.op == "output": + continue + elif node.op == "placeholder": + # Flush queue - place all remaining reloads after the last placeholder + while reload_queue: + entry: ReloadQueueEntry = reload_queue.pop(0) + for reload_group_node in reversed(entry.pattern.reload_group_nodes): + node.append(reload_group_node) + break + elif node in reload_patterns: + pattern: ReloadNodeInfo = reload_patterns[node] + reload_queue.append( + ReloadQueueEntry( + pattern=pattern, remaining_time_ms=pattern.transfer_time_ms + ) + ) + elif node in reload_group_nodes_set: + continue + else: + if not reload_queue: + continue + compute_runtime_ms: float = ( + benchmark_node(node) if is_compute_node(node) else 0 + ) + reload_queue[0].remaining_time_ms -= compute_runtime_ms + + # Pop and place reload if its remaining time is satisfied (<= 0) + if reload_queue[0].remaining_time_ms <= 0: + entry: ReloadQueueEntry = reload_queue.pop(0) + for reload_group_node in entry.pattern.reload_group_nodes: + node.prepend(reload_group_node) + + +def activation_offload_sink_wait(fwd_module: fx.GraphModule) -> None: + """ + Sink wait_event operations for offload completion to the end of the graph. + + This function identifies wait_event nodes for offload completion and moves them + to the end of the graph, allowing computation to overlap with offload operations. + + Args: + fwd_module: Forward module graph + """ + graph: fx.Graph = fwd_module.graph + nodes_list: list[fx.Node] = list(graph.nodes) + node_to_idx: dict[fx.Node, int] = {node: idx for idx, node in enumerate(nodes_list)} + + # Find all CPU offload device_put nodes + offload_nodes: list[fx.Node] = [ + node + for node in graph.find_nodes( + op="call_function", target=torch.ops.prims.device_put.default + ) + if CPU_OFFLOAD_PREFIX in node.name + ] + + # Collect all wait_event nodes that need to be moved + wait_nodes_to_sink: list[fx.Node] = [] + for offload_node in offload_nodes: + offload_idx: int = node_to_idx[offload_node] + wait_event_node: fx.Node = nodes_list[offload_idx + 3] + + # Validate it's actually a wait_event node + if not ( + wait_event_node.op == "call_function" + and wait_event_node.target == torch.ops.streams.wait_event.default + ): + raise ValueError( + f"Expected wait_event node three positions after {offload_node.name}" + ) + + wait_nodes_to_sink.append(wait_event_node) + + # Find the output node, and move all wait_event nodes to just before the output node + output_node: fx.Node = graph.find_nodes(op="output")[0] + for wait_node in wait_nodes_to_sink: + output_node.prepend(wait_node) + + +def activation_reload_prefetch(bwd_module: fx.GraphModule) -> None: + """ + Prefetch backward reload operations by moving them earlier in the graph + to overlap communication with computation. + + This function identifies backward reload patterns (fork → wait_stream → device_put → + record_event → join) and moves them earlier in the execution order to overlap + the data transfer with computation, while keeping the wait_event at its original + position. + + Args: + bwd_module: Backward module graph + """ + graph: fx.Graph = bwd_module.graph + nodes_list: list[fx.Node] = list(graph.nodes) + node_to_idx: dict[fx.Node, int] = {node: idx for idx, node in enumerate(nodes_list)} + + # Step 1: Identify reload patterns + reload_patterns: dict[fx.Node, ReloadNodeInfo] = identify_reload_patterns( + graph, nodes_list, node_to_idx + ) + + # Step 2: Reorder nodes by directly manipulating the graph + reorder_for_prefetch(nodes_list, reload_patterns) + + +def enable_activation_offloading( + fwd_module: fx.GraphModule, + bwd_module: fx.GraphModule, + num_fwd_outputs: int, + static_lifetime_input_nodes: OrderedSet[fx.Node], +) -> None: + """ + Main entry point for activation offloading. + + Args: + fwd_module: Forward module graph + bwd_module: Backward module graph + num_fwd_outputs: Number of forward outputs + """ + + # Step 1: Decide which nodes to offload and mark them + should_perform_offloading: bool = choose_offload_sets( + fwd_module, + num_fwd_outputs, + static_lifetime_input_nodes, + ) + if not should_perform_offloading: + return + + # Step 2: Add offload and reload nodes to the graphs + if config.activation_offload_separate_stream: + # Use async ao ops (2 nodes each: offload/reload + wait_tensor) + offload_chosen_sets_async(fwd_module, bwd_module) + if config.activation_offload_sink_wait: + activation_offload_sink_wait_async(fwd_module) + if config.activation_reload_prefetch: + activation_reload_prefetch_async(bwd_module) + else: + # Use synchronous device_put (1 node each) + offload_chosen_sets(fwd_module, bwd_module) + + fwd_module.graph.lint() + bwd_module.graph.lint() diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/offload_ops.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/offload_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..88b663b59aadb8b3433aebaf4aedb0a65f9e5f06 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_activation_offloading/offload_ops.py @@ -0,0 +1,296 @@ +"""Custom ops for async activation offloading between GPU and CPU. + +These ops encapsulate stream management internally, producing a clean 2-node +IR pattern (offload/reload + wait_tensor) similar to c10d functional collectives. + +A single dedicated transfer stream handles all D2H/H2D copies. +Completion events are keyed by output tensor data_ptr() and stored in a +module-level registry, so ``ao.wait_tensor`` takes only the tensor itself +(plus optional ``keepalive`` and ``last_use_of_storage`` args). + +Offload pattern: + cpu_tensor = ao.offload(gpu_tensor) + cpu_tensor = ao.wait_tensor(cpu_tensor, keepalive=gpu_tensor) + keepalive frees the GPU tensor's storage after the D2H copy completes. + +Reload pattern: + gpu_tensor = ao.reload(cpu_tensor, device) + gpu_tensor = ao.wait_tensor(gpu_tensor, keepalive=cpu_tensor) + keepalive frees the CPU tensor's storage after the H2D copy completes. + +The optional ``last_use_of_storage`` arg creates a dependency on a tensor whose +storage must outlive the async transfer but is not otherwise connected by a +data-flow edge in the graph. +""" + +import torch +from torch._library.custom_ops import custom_op +from torch.fx import has_side_effect + + +# --- Global transfer stream (one per device, lazily created) --- +_transfer_streams: dict[torch.device, torch.Stream] = {} + + +def _get_or_create_transfer_stream(device: torch.device) -> torch.Stream: + if device not in _transfer_streams: + _transfer_streams[device] = torch.Stream(device=device) + return _transfer_streams[device] + + +# --- Pinned memory pool (avoids per-offload cudaHostAlloc overhead) --- +# Keyed by (numel, dtype) to prevent cross-dtype reuse. +# Not keyed by device: pinned CPU memory is host-side and accessible from +# any GPU. Cross-device reuse is safe because wait_tensor synchronizes the +# transfer (via wait_event) before _pool_free returns the buffer — the +# buffer is never in-flight when reused. +_pinned_pool: dict[tuple[int, torch.dtype], list[torch.Tensor]] = {} +_pool_enabled: bool = False +_pool_managed_ptrs: set[int] = set() + + +def _maybe_pool_alloc(numel: int, dtype: torch.dtype) -> torch.Tensor: + """Get a pinned CPU buffer from the pool (if enabled), or allocate fresh.""" + if _pool_enabled: + key = (numel, dtype) + bucket = _pinned_pool.get(key) + if bucket: + buf = bucket.pop() + _pool_managed_ptrs.add(buf.data_ptr()) + return buf + buf = torch.empty(numel, dtype=dtype, device="cpu", pin_memory=True) + _pool_managed_ptrs.add(buf.data_ptr()) + return buf + return torch.empty(numel, dtype=dtype, device="cpu", pin_memory=True) + + +def _pool_free(buf: torch.Tensor) -> None: + """Return a pinned buffer to the pool, or free its storage if pool disabled.""" + ptr = buf.data_ptr() + if ptr in _pool_managed_ptrs: + key = (buf.nelement(), buf.dtype) + _pinned_pool.setdefault(key, []).append(buf) + else: + storage = buf.untyped_storage() + if storage.size() > 0: + storage.resize_(0) + + +def _pool_clear() -> None: + """Free all cached pinned buffers.""" + _pinned_pool.clear() + _pool_managed_ptrs.clear() + + +import contextlib + + +@contextlib.contextmanager +def pinned_memory_pool(enabled: bool = True): + """Context manager that controls pinned memory pooling for offload ops. + + Without this context manager, ``ao.offload`` allocates a fresh pinned + buffer every call and ``ao.wait_tensor`` does not cache freed buffers. + Inside the context with ``enabled=True``, buffers are reused across + calls, avoiding the ~3 ms per-tensor ``cudaHostAlloc`` overhead:: + + with pinned_memory_pool(): + for step in range(num_steps): + train_step() # ao.offload/reload reuse pooled buffers + # pinned buffers freed here + + Nestable: inner contexts save and restore the outer state. + Pass ``enabled=False`` to temporarily disable pooling. + """ + global _pool_enabled + saved = _pool_enabled + _pool_enabled = enabled + try: + yield + finally: + if not saved: + _pool_clear() + _pool_enabled = saved + + +# --- Wait registry: maps data_ptr() -> (completion_event, device) --- +# Created by ao.offload / ao.reload, consumed (popped) by ao.wait_tensor. +# Not thread-safe — graph execution is single-threaded Python. +_wait_registry: dict[int, tuple[torch.Event, torch.device]] = {} + + +def _register_wait(tensor: torch.Tensor, device: torch.device) -> torch.Event: + """Create an event for an async transfer and register it for wait_tensor.""" + event = torch.Event() + _wait_registry[tensor.data_ptr()] = (event, device) + return event + + +def _pop_wait(tensor: torch.Tensor) -> tuple[torch.Event, torch.device]: + key = tensor.data_ptr() + try: + return _wait_registry.pop(key) + except KeyError: + raise RuntimeError( + f"ao.wait_tensor: no pending transfer for tensor with data_ptr={key}. " + "Every ao.wait_tensor must be paired with a preceding ao.offload or ao.reload." + ) from None + + +def _clear_wait_registry() -> None: + _wait_registry.clear() + + +@custom_op("ao::offload", mutates_args=()) +def offload(tensor: torch.Tensor) -> torch.Tensor: + """Async offload a GPU tensor to CPU on the dedicated transfer stream. + + Callers MUST pair this with an ``ao.wait_tensor`` that passes the source GPU + tensor as ``keepalive`` to extend its lifetime past the async D2H copy. + Do NOT use ``record_stream`` — it causes memory fragmentation and + unbounded memory growth. + + Uses pinned-memory allocation + copy_ so the transfer is compatible + with CUDA graph capture. + """ + device = tensor.device + transfer_stream = _get_or_create_transfer_stream(device) + current_stream = torch.accelerator.current_stream(device) + + transfer_stream.wait_stream(current_stream) + + torch.accelerator.set_stream(transfer_stream) + result = _maybe_pool_alloc(tensor.nelement(), tensor.dtype).view(tensor.shape) + completion_event = _register_wait(result, device) + result.copy_(tensor, non_blocking=True) + transfer_stream.record_event(completion_event) + torch.accelerator.set_stream(current_stream) + + return result + + +@offload.register_fake +def _(tensor: torch.Tensor) -> torch.Tensor: + return torch.empty(tensor.shape, dtype=tensor.dtype, device="cpu") + + +@custom_op("ao::reload", mutates_args=()) +def reload( + tensor: torch.Tensor, + device: torch.device, + original_size: list[int] | None = None, + original_stride: list[int] | None = None, +) -> torch.Tensor: + """Async reload a CPU tensor to GPU on the dedicated transfer stream. + + The GPU tensor is allocated on the compute stream to avoid cross-stream + allocator ownership issues. The H2D copy runs on the transfer stream. + The completion event is keyed by the output tensor's data_ptr. + + ``original_size`` and ``original_stride`` restore the GPU tensor's + original layout (which may be non-contiguous, e.g. from transpose). + When None, the tensor's own size/stride are used. + """ + size = original_size if original_size is not None else list(tensor.shape) + stride = original_stride if original_stride is not None else list(tensor.stride()) + transfer_stream = _get_or_create_transfer_stream(device) + current_stream = torch.accelerator.current_stream(device) + + result = torch.empty_strided(size, stride, dtype=tensor.dtype, device=device) + completion_event = _register_wait(result, device) + + transfer_stream.wait_stream(current_stream) + + torch.accelerator.set_stream(transfer_stream) + result.copy_(tensor, non_blocking=True) + transfer_stream.record_event(completion_event) + torch.accelerator.set_stream(current_stream) + + return result + + +@reload.register_fake +def _( + tensor: torch.Tensor, + device: torch.device, + original_size: list[int] | None = None, + original_stride: list[int] | None = None, +) -> torch.Tensor: + size = original_size if original_size is not None else list(tensor.shape) + stride = original_stride if original_stride is not None else list(tensor.stride()) + return torch.empty_strided(size, stride, dtype=tensor.dtype, device=device) + + +# ao::wait_tensor is defined via torch.library with an aliasing schema so the +# output can alias the input (custom_op forbids this). +# +# Uses CompositeExplicitAutograd (single impl for all devices) because the +# offload case has mixed-device args: ``tensor`` is CPU (the offload result) +# while ``keepalive`` is CUDA (the source GPU tensor). A single impl avoids +# relying on device-priority dispatch ordering. +# +# Synchronization details (completion event, device) are looked up from +# ``_wait_registry`` keyed on ``tensor.data_ptr()``. +# +# ``keepalive`` is the source tensor of the async transfer. It creates a +# graph dependency that extends the source tensor's lifetime until the +# compute stream has waited on the transfer completion event. After the +# wait, the op frees the source tensor's storage via ``resize_(0)`` since +# it is no longer needed: +# - Offload (D2H): keepalive is the GPU tensor; freed after the D2H copy. +# - Reload (H2D): keepalive is the CPU tensor; freed after the H2D copy. +# +# ``last_use_of_storage`` is an optional tensor whose storage is shared with +# other live tensors (views/aliases). Passing it here tells the scheduler +# that this wait_tensor call is the last consumer of that storage, creating +# a data dependency edge that prevents the storage from being freed or +# reused before the async transfer completes. This is needed when the +# storage is not otherwise kept alive by a direct data-flow edge in the +# graph -- without it, a compiler pass could schedule a storage-freeing op +# before the transfer finishes. +_lib = torch.library.Library("ao", "DEF") +_lib.define( + "wait_tensor(Tensor(a) tensor, Tensor? keepalive=None, Tensor? last_use_of_storage=None) -> Tensor(a)" +) + + +@torch.library.impl("ao::wait_tensor", "CompositeExplicitAutograd") +def _ao_wait_tensor( + tensor: torch.Tensor, + keepalive: torch.Tensor | None = None, + last_use_of_storage: torch.Tensor | None = None, +) -> torch.Tensor: + completion_event, device = _pop_wait(tensor) + current_stream = torch.accelerator.current_stream(device) + + current_stream.wait_event(completion_event) + if keepalive is not None: + if keepalive.is_pinned(): + # Return CPU pinned buffer to pool for reuse + _pool_free(keepalive.view(-1)) + else: + storage = keepalive.untyped_storage() + if storage.size() > 0: + storage.resize_(0) + return tensor + + +@torch.library.register_fake("ao::wait_tensor") +def _ao_wait_tensor_fake( + tensor: torch.Tensor, + keepalive: torch.Tensor | None = None, + last_use_of_storage: torch.Tensor | None = None, +) -> torch.Tensor: + return tensor + + +has_side_effect(torch.ops.ao.wait_tensor.default) + + +def wait_tensor( + tensor: torch.Tensor, + keepalive: torch.Tensor | None = None, + last_use_of_storage: torch.Tensor | None = None, +) -> torch.Tensor: + """Callable wrapper so ``wait_tensor`` can be imported by name for op registration.""" + return torch.ops.ao.wait_tensor.default(tensor, keepalive, last_use_of_storage) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__init__.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10a55772ab58b21573a6eba0356ddd3080164ac7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__init__.py @@ -0,0 +1,5 @@ +# 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. diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..618e33bb59fa701fe124eae0cd2d498ad3f7ce89 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/aot_autograd_result.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/aot_autograd_result.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..496248921fbfc60c9f363277d4a1f964d9d9a672 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/aot_autograd_result.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/autograd_cache.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/autograd_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d5be85ca58dea2212ab37e89eb9a0f9361f978b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/autograd_cache.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/codegen.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/codegen.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e1381a5514e8383ae3c183f82c4ffc2e45e7ca7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/codegen.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/collect_metadata_analysis.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/collect_metadata_analysis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..583ac728f1da15197b18c9960c3dd90a9f7e7744 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/collect_metadata_analysis.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/complex_decomposition.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/complex_decomposition.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c78d58fe686d89324961efafd520e36193f01ba Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/complex_decomposition.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/descriptors.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/descriptors.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c78c3e2520bf4c5b57fadd225e6c40d60d41b4c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/descriptors.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/frontend_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/frontend_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2fc9a399e2612bbaa16abc0e9e80ae3120950333 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/frontend_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/functional_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/functional_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56f3db9a739743228298aec87ba6813be1649ee2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/functional_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/fx_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/fx_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..374ecee0a1305388eb06ecf37c47c4049f0661f6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/fx_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/graph_capture.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/graph_capture.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..243500d21fffa15830a29365e30fd42ca6eb0ff2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/graph_capture.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/graph_capture_wrappers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/graph_capture_wrappers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3bb923dc47c8b89db08057c6da8a42006468bcf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/graph_capture_wrappers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/graph_compile.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/graph_compile.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cef8cd8fd7d39fe270c61bbf19e3b26f99a11055 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/graph_compile.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/indexed_dict.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/indexed_dict.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3d32130dc0b0c065820b8d66167fcaab86df3e0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/indexed_dict.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/input_output_analysis.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/input_output_analysis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be33fa2be50b092d4cc315a18ded2971d362e9df Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/input_output_analysis.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/logging_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/logging_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a37a34f6a2bb1a0ea261b73574247279fb72fdc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/logging_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/runtime_wrappers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/runtime_wrappers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce6b7e0de5cb7d7bdc8c5b37c39086e25675381c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/runtime_wrappers.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77e31e07a704815bcd165b9bdcb11cb5c2a4ba4c528f64ff091fc342a28649c6 +size 156248 diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/schemas.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/schemas.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a080a59dd19946b746e9eebcc42913f55b406be Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/schemas.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/source_emit.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/source_emit.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5a1e7234d2c753e97d52c4e07ede235fa2e3679 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/source_emit.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/standalone_runtime.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/standalone_runtime.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d91f76b5dcb7c461e968b5f38d96389e2969ef8c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/standalone_runtime.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/streams.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/streams.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41783d24802700eb21ed6f657de8d651d8a1e8b9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/streams.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/subclass_codegen.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/subclass_codegen.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43aea8bf9c692aaf15af8cc70aaeff844dcf4ecb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/subclass_codegen.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/subclass_parametrization.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/subclass_parametrization.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9bf987de106dcb9dfb237364dd2fae033ad9022 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/subclass_parametrization.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/subclass_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/subclass_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2f727aab9b99c70a7fb461864a998cfb871b817 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/subclass_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/to_standalone_python.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/to_standalone_python.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..222854567a21cc402cb6ad87ee44e07260e2c49c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/to_standalone_python.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd00971e473b55c95a778d3c8859f0f118b39137 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/aot_autograd_result.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/aot_autograd_result.py new file mode 100644 index 0000000000000000000000000000000000000000..eeff74fc596fef55dcaf2a28d769a67dcc0212a9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/aot_autograd_result.py @@ -0,0 +1,756 @@ +""" +This module provides result classes for AOT Autograd compilation. + +Similar to how torch._inductor.output_code provides OutputCode classes for inductor +compilation results, this module provides AOTAutogradResult classes that represent +the compiled artifacts produced by AOT Autograd. + +These results are: +- Serializable: can be saved/loaded from disk without recompilation +- Addressable: can be stored in caches with keys for later retrieval +- Reusable: can be used for both caching and ahead-of-time compilation (precompile) + +The main result types are: +- GenericAOTAutogradResult: Abstract base for all AOT Autograd results +- AOTAutogradResult: Regular result that references FxGraphCache entries +- BundledAOTAutogradResult: Result that bundles the entire compiled code directly +""" + +from __future__ import annotations + +import json +import logging +from abc import ABC, abstractmethod +from collections.abc import Callable, Sequence +from copy import copy +from dataclasses import dataclass +from typing import Any, cast, Generic, TYPE_CHECKING, TypeVar + +import torch +from torch._dynamo.precompile_context import BackendCacheArtifact +from torch._inductor.codecache import FxGraphCache +from torch._inductor.output_code import ( + CompiledFxGraph, + CompiledFxGraphConstants, + OutputCode, +) +from torch._inductor.utils import should_use_remote_fx_graph_cache +from torch._logging import getArtifactLogger + +from .runtime_wrappers import ( + AOTDispatchAutograd, + AOTDispatchAutogradCompileSpec, + AOTDispatchSubclassWrapper, + CachedAutogradLazyBackwardCompileInfo, + CompilerWrapper, + FunctionalizedRngRuntimeWrapper, + post_compile, + RuntimeWrapper, + SerializableCompiledFunction, + SubclassMeta, +) +from .schemas import AOTAutogradCacheInfo, AOTConfig # noqa: F401 +from .utils import simple_wraps + + +if TYPE_CHECKING: + from torch._inductor.compile_fx import _CompileFxKwargs + + from .schemas import CacheableAOTConfig, ViewAndMutationMeta + +log = logging.getLogger(__name__) +aot_graphs_log = getArtifactLogger(__name__, "aot_graphs") + + +TOut = TypeVar("TOut", bound=OutputCode) + + +class InductorOutput(ABC, Generic[TOut]): + """ + Class representing a single inductor output + """ + + @abstractmethod + def pre_save(self) -> None: ... + + @abstractmethod + def load(self, example_inputs: Sequence[Any]) -> TOut: ... + + @abstractmethod + def post_compile(self, result: TOut, fx_config: _CompileFxKwargs) -> TOut: ... + + +TOutputCode = TypeVar("TOutputCode", bound=OutputCode) + + +@dataclass +class BundledOutputCodeLoadable(InductorOutput[TOutputCode], Generic[TOutputCode]): + """ + A generic wrapper for OutputCode objects that are bundled directly in the cache + (rather than looked up via FxGraphCache). + + This works for any OutputCode subclass (CompiledFxGraph, RegionalOutputCode, etc.) + """ + + result: TOutputCode + + def pre_save(self) -> None: + disk_result = copy(self.result) + disk_result.prepare_for_serialization() + self.result = disk_result + return + + def load(self, example_inputs: Sequence[Any]) -> TOutputCode: + self.example_inputs = example_inputs + return self.result + + def post_compile( + self, result: TOutputCode, fx_config: _CompileFxKwargs + ) -> TOutputCode: + constants = CompiledFxGraphConstants() + + # Special handling for CompiledFxGraph - needs FxGraphCache.cache_hit_post_compile + if isinstance(result, CompiledFxGraph): + graph, cache_info = FxGraphCache.cache_hit_post_compile( + result, {}, constants + ) + if graph is None: + raise RuntimeError("Failed to reload cache entry from disk") + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "fx_graph_bundled_cache_hit", # always a hit + "encoding": "json", + }, + payload_fn=lambda: json.dumps(cache_info), + ) + result = graph # type: ignore[assignment] + result.compile_region_name = ( # pyrefly: ignore[missing-attribute] + fx_config.get("compile_region_name") + ) + + # Run normal post compile + result.post_compile(self.example_inputs, constants, fx_config) + + # Let the CUDAGraph policy do outer-level wrapping (e.g. wrapping + # an entire RegionalOutputCode as a single CUDA graph instead of + # per-inner-region). + import torch._inductor.config as _inductor_config + + policy = _inductor_config.cudagraph_policy + if policy is not None: + result = policy.wrap_output(result) + + return result + + +# Backwards compatibility alias +CompiledFxGraphLoadable: type[BundledOutputCodeLoadable[CompiledFxGraph]] = ( + BundledOutputCodeLoadable[CompiledFxGraph] +) + + +@dataclass +class FxGraphCacheLoadable(InductorOutput[CompiledFxGraph]): + fx_graph_cache_info: tuple[str, list[str]] + fx_graph_guard_expr: str | None + + def pre_save(self) -> None: + return + + def _is_backward(self) -> bool: + return False + + def load(self, example_inputs: Sequence[Any]) -> CompiledFxGraph: + from .autograd_cache import FXGraphCacheMiss + + # [Note: AOTAutogradCache and FXGraphCache Guard interactions] + # As mentioned, AOTAutograd takes in the symint inputs from dynamo's list of arguments. + # FXGraphCache serializes guards that are needed in the shape_env based on these symint inputs to the graph. + # The invariant that AOTAutograd uses here is that the sources for symints given to it by dynamo are exactly + # the same as the ones it passes to inductor, for both the forward and backward passes. + # (This does not mean that the tensor values passed in are the same: only that their symints are). + # That is, AOTAutograd and Inductor never create new guards based on symints with different sources + # than those passed to it by inductor. + # We pass the post compile function, which sets various fx_config boxed values, + # so we can call it only after we're sure both forward and backward have + # Clear CompiledTritonKernels before loading from FXGraphCache + torch._inductor.async_compile.CompiledTritonKernels.cache_clear() + remote_cache = None + constants = CompiledFxGraphConstants() + if should_use_remote_fx_graph_cache(): + remote_cache = FxGraphCache.get_remote_cache() + (cache_key, debug_lines) = self.fx_graph_cache_info + + def check_exact_guard_match(guard_expr: str, _hints: Any) -> bool: + """ + AOTAutogradCache tracks its own guards, so we just need to treat these guard expressions as a second + cache key of sorts: we just check for equality, i.e. the FXGraphCache entry with + the exact same guards as we originally saved into the cache. + """ + return guard_expr == self.fx_graph_guard_expr + + result, cache_info = FxGraphCache.load_with_key( + cache_key, + debug_lines, + example_inputs, + local=True, + remote_cache=remote_cache, + is_backward=self._is_backward(), + constants=constants, + evaluate_guards=check_exact_guard_match, + ) + if result is None: + log.info("FXGraphCache cache miss for key %s", self.fx_graph_cache_info) + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "fx_graph_cache_miss", # always a hit + "encoding": "json", + }, + payload_fn=lambda: json.dumps(cache_info), + ) + + raise FXGraphCacheMiss + + # No need to log chromium event because AOTAutograd will log that immediately for us + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "fx_graph_cache_hit", # always a hit + "encoding": "json", + }, + payload_fn=lambda: json.dumps(cache_info), + ) + self.example_inputs = example_inputs + self.constants = constants + return result + + def post_compile( + self, result: CompiledFxGraph, fx_config: _CompileFxKwargs + ) -> CompiledFxGraph: + """ + Called after FXGraphCacheLoadable.load, mutates fx_config + """ + result.compile_region_name = fx_config.get( # pyrefly: ignore[bad-assignment] + "compile_region_name" + ) + result.post_compile(self.example_inputs, self.constants, fx_config) + + import torch._inductor.config as _inductor_config + + policy = _inductor_config.cudagraph_policy + if policy is not None: + result = policy.wrap_output(result) + + return result + + +@dataclass +class CompiledForward(FxGraphCacheLoadable): + """ + Cacheable entry for a forward function + """ + + def _is_backward(self) -> bool: + return False + + +@dataclass +class GenericCompiledBackward(InductorOutput[TOut]): + # Used by AOTDispatchAutograd.post_compile + backward_state_indices: list[int] + num_symints_saved_for_bw_: int + + def post_compile(self, result: TOut, fx_config: _CompileFxKwargs) -> TOut: + # The concrete post_compile comes from the loadable mixin in each subclass MRO. + compiled_bw = super().post_compile( # pyrefly: ignore[missing-attribute] + result, fx_config + ) + # See note [Wrapping bw_compiler in disable] + # This is done by _wrapped_bw_compiler in torch/_dynamo/backends/common.py + # But since on cache hit we do not call the bw_compiler, we need to reapply the disable + return torch._dynamo.disable( # type: ignore[return-value] + compiled_bw, reason="do not trace generated backwards pass" + ) + + +@dataclass +class CompiledBackward(GenericCompiledBackward[CompiledFxGraph], FxGraphCacheLoadable): + """ + Cacheable entry for a backward function + """ + + def _is_backward(self) -> bool: + return True + + +# Generic bundled forward/backward classes that work with any OutputCode type +@dataclass +class BundledCompiledForward( + BundledOutputCodeLoadable[TOutputCode], Generic[TOutputCode] +): + """ + Generic forward function for bundled compilation. + Works with any OutputCode type (CompiledFxGraph, RegionalOutputCode, etc.) + """ + + +@dataclass +class BundledCompiledBackward( + GenericCompiledBackward[TOutputCode], + BundledOutputCodeLoadable[TOutputCode], + Generic[TOutputCode], +): + """ + Generic backward function for bundled compilation. + Works with any OutputCode type (CompiledFxGraph, RegionalOutputCode, etc.) + """ + + +@dataclass +class SerializedGraphModule: + fn: Callable[[dict[Any, Any], str], torch.nn.Module] + args: tuple[Any, ...] + + def __init__(self, gm: torch.fx.GraphModule) -> None: + self.fn, self.args = gm.__reduce__() + + def deserialize(self) -> torch.fx.GraphModule: + gm = self.fn(*self.args) + if not isinstance(gm, torch.fx.GraphModule): + raise AssertionError(f"expected fx.GraphModule, got {type(gm)}") + return gm + + +def serialize_graph_module(gm: torch.fx.GraphModule) -> SerializedGraphModule: + # NOTE: mutates the graph module + gm.meta = {} + for node in gm.graph.nodes: + # pyrefly: ignore [implicit-any] + node.meta = {} + return SerializedGraphModule(gm) + + +TForward = TypeVar("TForward", bound="InductorOutput[Any]") +TBackward = TypeVar("TBackward", bound="GenericCompiledBackward[Any]") + + +@dataclass +class GenericAOTAutogradResult(Generic[TForward, TBackward]): + """A single result from AOT Autograd compilation, genericized by Forward and Backward types. + + A TForward is always an InductorOutput of some sort, which represents the + forward graph of the compile. + A TBackward is an InductorOutput + metadata about the backward, useful for specific + backward-only wrappers. This type is encapsulated by GenericCompiledBackward. + + Each AOTAutogradResult is essentially parameterized by 1. the method of loading + from the cache (either Bundled or UnBundled), and 2. The type of the output. For now, + the only type of output we support is Python Wrapper output, i.e. OutputCode.CompiledFxGraph, + but the same technique works for C++ wrapper code; we'd just add an extra InductorOutput type. + """ + + # Forward and Backward info + compiled_fw: TForward + compiled_bw: TBackward | None + + # Code of the joint graph using print_readable() + # Used for logging purposes + aot_joint_graph_str: str | None + aot_forward_graph_str: str | None + aot_backward_graph_str: str | None + min_cut_info_str: str | None + + # Runtime_metadata saved right before compilation + runtime_metadata: ViewAndMutationMeta + + # Wrappers that run after each aot_dispatch_* function + dispatch_wrappers: list[CompilerWrapper] + + # Used by AOTSubclassWrapper + maybe_subclass_meta: SubclassMeta | None + num_fw_outs_saved_for_bw: int | None + + # Used by RuntimeWrapper + indices_of_inps_to_detach: list[int] + + # Time taken to trace/compile the forward + # forward_time_taken includes AOTAutograd tracing time + inductor compilation time + # backward_time_taken is essentially just the time inductor took to compile + forward_time_taken_ns: int + backward_time_taken_ns: int + + # Used by standalone_compile + sanitized_aot_config: CacheableAOTConfig + + guards_expr: str | None + + # Used by Compiled Autograd + serialized_bw_module: SerializedGraphModule | None + + def pre_save(self) -> None: + """ + Perform any preparations to make the result ready for serialization. + """ + self.compiled_fw.pre_save() + if self.compiled_bw is not None: + self.compiled_bw.pre_save() + + def _log_cached_graphs(self, aot_config: AOTConfig | CacheableAOTConfig) -> None: + if not aot_config.enable_log: + return + + if self.aot_joint_graph_str is not None: + torch._logging.trace_structured( + "aot_joint_graph", payload_fn=lambda: self.aot_joint_graph_str + ) + aot_graphs_log.info( + "Joint graph (from cache)\n\n%s", self.aot_joint_graph_str + ) + + if self.aot_forward_graph_str is not None: + from torchgen.utils import dataclass_repr + + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "aot_forward_graph_fw_metadata", + "encoding": "string", + }, + payload_fn=lambda: dataclass_repr(self.runtime_metadata), + ) + if self.maybe_subclass_meta is not None: + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "aot_forward_graph_fw_subclass_metadata", + "encoding": "string", + }, + payload_fn=lambda: dataclass_repr(self.maybe_subclass_meta), + ) + + # It's called an inference graph if not running with autograd + has_backward = self.aot_backward_graph_str is not None + torch._logging.trace_structured( + "aot_forward_graph" if has_backward else "aot_inference_graph", + payload_fn=lambda: self.aot_forward_graph_str, + ) + aot_graphs_log.info( + "Forward graph (from cache)\n\n%s", + self.aot_forward_graph_str, + ) + + if self.aot_backward_graph_str is not None: + torch._logging.trace_structured( + "aot_backward_graph", payload_fn=lambda: self.aot_backward_graph_str + ) + aot_graphs_log.info( + "Backward graph (from cache)\n\n%s", + self.aot_backward_graph_str, + ) + + if self.min_cut_info_str is not None: + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "min_cut_information", + "encoding": "json", + }, + payload_fn=lambda: self.min_cut_info_str, + ) + + def _load_and_post_compile( + self, + args: list[torch.Tensor], + fx_config: _CompileFxKwargs, + ) -> tuple[Callable[..., Any], Callable[..., Any] | None, bool]: + from torch._dynamo.utils import CompileEventLogger + + compiled_fw_func = self.compiled_fw.load(args) + if self.compiled_bw is not None: + compiled_bw_func = self.compiled_bw.load(args) + needs_autograd = True + CompileEventLogger.try_add_pt2_compile( + "backend_compile", dispatch_mode="autograd" + ) + # Now that we've loaded forward and backward, call post compile on both + # This avoids setting things like BoxedBools in fx_config until + # after both forward and backward cache hit + fw_fx_config: _CompileFxKwargs = { + **fx_config, + "is_backward": False, + } + bw_fx_config: _CompileFxKwargs = { + **fx_config, + "is_backward": True, + } + compiled_fw_func = self.compiled_fw.post_compile( + compiled_fw_func, fw_fx_config + ) + compiled_bw_func = self.compiled_bw.post_compile( + compiled_bw_func, bw_fx_config + ) + return compiled_fw_func, compiled_bw_func, needs_autograd + + inference_fx_config: _CompileFxKwargs = { + **fx_config, + "is_backward": False, + } + + needs_autograd = False + CompileEventLogger.try_add_pt2_compile( + "backend_compile", dispatch_mode="inference" + ) + compiled_fw_func = self.compiled_fw.post_compile( + compiled_fw_func, inference_fx_config + ) + return compiled_fw_func, None, needs_autograd + + def _apply_runtime_wrappers( + self, + compiled_fw_func: Callable[..., Any], + compiled_bw_func: Callable[..., Any] | None, + needs_autograd: bool, + aot_config: AOTConfig, + ) -> Callable[..., Any]: + from torch._dynamo.utils import CompileEventLogger + + compiled_fw_func = AOTDispatchSubclassWrapper( + trace_joint=needs_autograd, + fw_only=None, + maybe_subclass_meta=self.maybe_subclass_meta, + num_fw_outs_saved_for_bw=self.num_fw_outs_saved_for_bw, + ).post_compile( + compiled_fw_func, aot_config, runtime_metadata=self.runtime_metadata + ) + + req_subclass_dispatch = self.maybe_subclass_meta is not None + CompileEventLogger.try_add_pt2_compile( + "backend_compile", requires_subclass_dispatch=req_subclass_dispatch + ) + + # In autograd case, functionalizedRngWrapper should not modify outs + return_new_outs = not needs_autograd + compiled_fw_func = FunctionalizedRngRuntimeWrapper( + return_new_outs=return_new_outs + ).post_compile( + compiled_fw_func, aot_config, runtime_metadata=self.runtime_metadata + ) + # pyrefly: ignore [missing-attribute] + compiled_fw_func._boxed_call = True + disable_amp = torch._C._is_any_autocast_enabled() + + if needs_autograd: + if self.compiled_bw is None: + raise AssertionError("compiled_bw must not be None when needs_autograd") + + cached_lazy_backward = None + if self.serialized_bw_module is not None: + cached_lazy_backward = CachedAutogradLazyBackwardCompileInfo( + self.serialized_bw_module.deserialize + ) + # This function is run on both cache miss and cache hit, either here + # or in aot_dispatch_autograd. On a cache hit, + # 1. the bw is already compiled + # 2. we don't need to save to the cache again + # so those corresponding arguments are set to None. + compile_spec = AOTDispatchAutogradCompileSpec( + compiled_fw_func=compiled_fw_func, + compiled_bw_func=compiled_bw_func, + maybe_subclass_meta=self.maybe_subclass_meta, + num_symints_saved_for_bw=self.compiled_bw.num_symints_saved_for_bw_, + backward_state_indices=self.compiled_bw.backward_state_indices, + disable_amp=disable_amp, + indices_of_inps_to_detach=self.indices_of_inps_to_detach, + lazy_backward_info=cached_lazy_backward, + bw_compiler=None, + aot_config=aot_config, + fw_metadata=self.runtime_metadata, + try_save_cache_entry=None, + ) + compiled_function = AOTDispatchAutograd.post_compile(compile_spec) + + else: + compiled_function = RuntimeWrapper( + indices_of_inps_to_detach=self.indices_of_inps_to_detach, + trace_joint=False, + disable_amp=disable_amp, + ).post_compile( + compiled_fw_func, aot_config, runtime_metadata=self.runtime_metadata + ) + + # Add serialization function back onto object + compiled_function, _ = post_compile( + self.dispatch_wrappers, + compiled_function, + aot_config, + runtime_metadata=self.runtime_metadata, + ) + return compiled_function + + def _check_guards(self, args: list[torch.Tensor]) -> None: + if self.guards_expr: + from .autograd_cache import AOTAutogradCache + + symints = AOTAutogradCache._filter_backed_symints(args) + check = bool(AOTAutogradCache.evaluate_guards(self.guards_expr, symints)) + if check is not True: + raise AssertionError(f"guards check failed: {check}") + + # Turn result into the original callable + def wrap_post_compile( + self, + args: list[torch.Tensor], + aot_config: AOTConfig | CacheableAOTConfig, + fx_config: _CompileFxKwargs, + ) -> Callable[..., Any]: + """ + This function takes a result and carefully reconstructs the original callable + that AOTAutograd returned the first time it was run. It does this by running the various + post compile steps that AOTAutograd runs on its compiled artifact after running the fw/bw compilers. + + In the inference path, this consists of the Subclass, FunctionalzedRngRuntime, and RuntimeWrappers. + In the autograd path, this consists of AOTAutogradDispatch.post_compile. + + The steps here should match exactly the steps that are run in aot_dispatch_base and aot_dispatch_autograd. + + Notably absent from the cached path are: + - DebugAssertWrapper + - FakifiedOutWrapper + + Which we'll handle separately later on, if necessary. + """ + from torch._dynamo.utils import dynamo_timed + + self._log_cached_graphs(aot_config) + # Cache hits only retain the cacheable subset of AOTConfig. Narrow once + # here so the existing post-compile wrapper stack can keep its compile-time + # AOTConfig annotations. + runtime_aot_config = cast(AOTConfig, aot_config) + with dynamo_timed("AOTAutogradCache.inductor_load"): + compiled_fw_func, compiled_bw_func, needs_autograd = ( + self._load_and_post_compile(args, fx_config) + ) + + compiled_function = self._apply_runtime_wrappers( + compiled_fw_func, + compiled_bw_func, + needs_autograd, + runtime_aot_config, + ) + # Now that we're pretty sure it's a successful load, add guards + # to the existing shape environment from the cache. + self._check_guards(args) + return compiled_function + + +class AOTAutogradResult(GenericAOTAutogradResult[CompiledForward, CompiledBackward]): + """ + Regular AOTAutogradResult: saves the forward/backward FxGraphCache keys + and looks them up in FxGraphCache on load + """ + + +class BundledAOTAutogradResult( + GenericAOTAutogradResult[ + BundledCompiledForward[TOutputCode], BundledCompiledBackward[TOutputCode] + ], + Generic[TOutputCode], +): + """ + Generic AOTAutogradResult where we bundle the entire OutputCode directly + (rather than looking it up via FxGraphCache). + + This works with any OutputCode type: + - CompiledFxGraph: Traditional inductor compilation + - RegionalOutputCode: Regional inductor compilation with GraphPickler serialization + - Any future OutputCode subclasses + + Type parameter: + TOutputCode: The OutputCode subclass (e.g., CompiledFxGraph, RegionalOutputCode) + + Usage with CompiledFxGraph: + entry = BundledAOTAutogradResult[CompiledFxGraph]( + compiled_fw=BundledCompiledForward(result=CompiledFxGraph(...)), + compiled_bw=BundledCompiledBackward( + result=CompiledFxGraph(...), + backward_state_indices=[...], + num_symints_saved_for_bw_=..., + ), + ... + ) + + Usage with RegionalOutputCode: + entry = BundledAOTAutogradResult[RegionalOutputCode]( + compiled_fw=BundledCompiledForward(result=RegionalOutputCode(gm)), + compiled_bw=BundledCompiledBackward( + result=RegionalOutputCode(gm), + backward_state_indices=[...], + num_symints_saved_for_bw_=..., + ), + ... + ) + """ + + +def deserialize_bundled_cache_entry( + entry: BundledAOTAutogradResult[Any], +) -> Callable[..., Any]: + from copy import deepcopy + + from torch._inductor.cudagraph_utils import BoxedDeviceIndex + from torch._inductor.utils import BoxedBool + + # In the precompile use case, guards are already serialized + # by dynamo, so we don't need to add them to the environment + entry.guards_expr = None + # TODO: this isn't exactly right, because cudagraphs needs to be a shared config + # which is set by compile_fx. But in precompile, we never actually call compile_fx + # so we don't have a place to track cudagraphs here. + cudagraphs = BoxedBool(torch._inductor.config.triton.cudagraphs) + boxed_forward_device_index = BoxedDeviceIndex(None) + # We need to make a clean copy of the cache entry + # in case it needs to be serialized again + serializable_copy = deepcopy(entry) + + from torch._subclasses import FakeTensorMode + from torch.fx.experimental.symbolic_shapes import ShapeEnv + + context = torch._guards.TracingContext.try_get() + if context is None: + # Create a clean environment when running fx graph post compile + # if one is not available + context = torch._guards.TracingContext(FakeTensorMode(shape_env=ShapeEnv())) + with torch._guards.tracing(context): + compiled_fn = entry.wrap_post_compile( + [], + entry.sanitized_aot_config, + { + "cudagraphs": cudagraphs, + "boxed_forward_device_index": boxed_forward_device_index, + }, + ) + # Ensure the deserialized cache entry is still serializable + + compiled_fn = SerializableCompiledFunction(compiled_fn, lambda: serializable_copy) + + # TODO: this ignores flat_params, which can exist + # if inline_builtin_nn_modules=False + @simple_wraps(compiled_fn) + def forward(*runtime_args: Any) -> Any: + return compiled_fn(list(runtime_args)) + + if not hasattr(compiled_fn, "serialize"): + raise AssertionError("compiled_fn must have serialize attribute") + forward.serialize = compiled_fn.serialize # type: ignore[attr-defined] + + return forward + + +@dataclass +# pyrefly: ignore [implicit-any] +class BundledAOTAutogradCacheArtifact(BackendCacheArtifact[Callable]): + # pyrefly: ignore [implicit-any] + def after_deserialization(self) -> Callable: + return deserialize_bundled_cache_entry(self.content) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/autograd_cache.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/autograd_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..652fa39cb453c0fe828b539669a4041b630717f4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/autograd_cache.py @@ -0,0 +1,1584 @@ +""" +Utils for caching the outputs of AOTAutograd +""" + +from __future__ import annotations + +import base64 +import contextlib +import dataclasses +import functools +import hashlib +import json +import logging +import os +import pickle +import random +import shutil +import time +import traceback +from copy import copy +from typing import Any, TYPE_CHECKING +from typing_extensions import override + +import torch +from torch._dynamo.precompile_context import PrecompileContext +from torch._dynamo.trace_rules import torch_non_c_binding_in_graph_functions +from torch._dynamo.utils import ( + chromium_event_log_active, + CompileEventLogger, + counters, + is_safe_numpy_wrapper, + numpy_wrapper_cache_key, + warn_once, +) +from torch._functorch import config +from torch._inductor.codecache import ( + _ident, + add_ephemeral_timeout_increase_for_distributed, + AOTAUTOGRAD_CACHE_PREFIX, + BypassFxGraphCache, + create_cache, + extract_tensor_metadata_for_cache_key, + FxGraphCache, + FxGraphCachePickler, + FxGraphHashDetails, + GuardedCache, + sha256_hash, + write_atomic, +) +from torch._inductor.custom_graph_pass import ( + CustomKnapsackSolver, + CustomRuntimeEstimator, +) +from torch._inductor.output_code import OutputCode +from torch._inductor.remote_cache import cache_stats +from torch._inductor.runtime.runtime_utils import cache_dir +from torch._inductor.utils import BoxedBool, should_use_remote_fx_graph_cache +from torch._library.fake_class_registry import FakeScriptObject +from torch._logging import LazyString +from torch._utils_internal import log_cache_bypass +from torch.compiler._cache import ( + CacheArtifact, + CacheArtifactFactory, + CacheArtifactRecorder, +) +from torch.fx.experimental.symbolic_shapes import guarding_hint_or_throw +from torch.fx.node import Node +from torch.fx.traceback import _get_memory_budget_annotation +from torch.utils._triton import has_triton_package + +from .aot_autograd_result import ( + AOTAutogradResult, + BundledAOTAutogradCacheArtifact, + BundledAOTAutogradResult, + BundledCompiledBackward, + BundledCompiledForward, + CompiledBackward, + CompiledForward, + GenericAOTAutogradResult, + SerializedGraphModule, +) +from .runtime_wrappers import ( + CompilerWrapper, + SerializableCompiledFunction, + SubclassMeta, +) +from .schemas import ( + ActInputPaths, + AOTAutogradCacheInfo, + AOTConfig, + CacheableAOTConfig, + ViewAndMutationMeta, +) + + +if TYPE_CHECKING: + from collections.abc import Callable, Generator, Sequence + + from torch._inductor.compile_fx import _CompileFxKwargs, CompilerConfigExtra + from torch._inductor.remote_cache import JsonDataTy, RemoteCache + + +log = logging.getLogger(__name__) + + +class BypassAOTAutogradCache(Exception): + pass + + +# Used to signify when FXGraphCache missed when AOTAutogradCache uses it +class FXGraphCacheMiss(BypassAOTAutogradCache): + pass + + +def should_use_remote_autograd_cache() -> bool: + if torch.compiler.config.force_disable_caches: + return False + if config.enable_remote_autograd_cache is not None: + return config.enable_remote_autograd_cache + if not config.is_fbcode(): + return False + + if torch._utils_internal.is_fb_unit_test(): + return False + + try: + from torch._inductor.fb.remote_cache import REMOTE_CACHE_VERSION + except ModuleNotFoundError: + return False + + jk_name = "pytorch/remote_cache:aot_autograd_cache_version" + + return REMOTE_CACHE_VERSION >= torch._utils_internal.justknobs_getval_int(jk_name) + + +def should_use_local_autograd_cache() -> bool: + if torch.compiler.config.force_disable_caches: + return False + return config.enable_autograd_cache + + +def should_bundle_autograd_cache() -> bool: + return config.bundled_autograd_cache or torch._dynamo.config.caching_precompile + + +def check_node_safe(node: Node) -> None: + """ + Checks that the node only uses supported operators. We are starting with very + conservative cacheability constraints, and incrementally adding more support as we expand. + + [Note: AOTAutograd Cacheability checks] + - Our cache key is computed from the FX graph produced by Dynamo and the input example values + - A node is "safe" if the same cache key results in a compiled artifact that has the same behavior + (i.e, the set of inputs that go into our cache key is sufficient to distinguish its behavior) + + To accomplish this safety check, we consider the following functions to be safe: + - Public functions under modules torch, torch.functional, and torch.nn.functional: these are + allowed in the graph by dynamo, so we can assume they are safe to cache. + - method calls on base tensor types + - Any call_module that dynamo deemed safe to allow AOTAutograd to trace + - Non callable nodes, such as placeholder, output, get_attr + + The test suite test_aot_autograd_cache.py::AOTAutogradCachePicklerTests tries its best to fully cover/specify this behavior. + """ + SAFE_TORCH_MODULES = ("torch.functional", "torch.nn.functional") + SAFE_TORCH_FUNCTIONS = ( + "torch.Size", + "torch.Tensor", + "torch.sym_int", + "torch._sym_sqrt", + "torch.sym_float", + "torch.sym_sum", + "torch.autograd.grad", + "torch.distributed.tensor._api.from_local", + # An autocast context manager *inside* a compiled region is traced into + # these calls. What they do is fully determined by their arguments + # (device type, dtype, enabled, cache_enabled), which are constants in + # the graph and therefore part of the cache key, so a graph compiled + # under one autocast setting can never be reused for another. + "torch.amp.autocast_mode._enter_autocast", + "torch.amp.autocast_mode._exit_autocast", + ) + SAFE_NON_TORCH_FUNCTIONS = ( + "einops.einops.rearrange", + "einops.einops.repeat", + ) + + def is_public_torch_api(target: Callable[..., Any]) -> bool: + # Don't blindly allow private functions in the torch namespace + is_private = target.__name__.startswith("_") + + return ( + getattr(target, "__module__", None) in SAFE_TORCH_MODULES and not is_private + ) + + def is_safe_torch_function(target: Callable[..., Any]) -> bool: + """Allowlisted torch functions""" + function_name = f"{target.__module__}.{target.__name__}" + # Allow torch.autograd.function.FunctionCtx if custom autograd functions are allowed + if function_name == "torch.autograd.function.FunctionCtx": + return ( + torch._functorch.config.autograd_cache_allow_custom_autograd_functions + ) + + # Functions in torch_non_c_binding_in_graph_functions + # are guaranteed to be cache safe. + # See NOTE: [Cacheability of in-graph torch functions] + return ( + function_name in torch_non_c_binding_in_graph_functions + or function_name in SAFE_TORCH_FUNCTIONS + or function_name in torch._inductor.config.unsafe_marked_cacheable_functions + ) + + def is_cacheable_function(target: Callable[..., Any]) -> bool: + if isinstance(target, (torch._ops.OpOverload, torch._ops.OpOverloadPacket)): + return True + if is_safe_numpy_wrapper(target): + return True + if is_public_torch_api(target): + return True + # Technically, FXGraphCache._check_for_hop already checks this, + # but better to error earlier anyway + if isinstance(target, torch._ops.HigherOrderOperator): + return target.cacheable() + is_builtin_fun_or_type = type(target).__name__ == "builtin_function_or_method" + if is_builtin_fun_or_type: + return True + if is_safe_torch_function(target): + return True + function_name = f"{target.__module__}.{target.__name__}" + if function_name in SAFE_NON_TORCH_FUNCTIONS: + return True + return False + + def is_tensor(target: Node) -> bool: + # Tensors always have example values in meta field + return "example_value" in target.meta + + # I'd love to use a match statement here, but it wasn't introduced until py3.10 + if node.op == "call_function": + if node.meta and node.meta.get("is_wrapped", False): + # This is fx.wrap function + # By default we BypassAOTAutogradCache for unknown functions, + # But if user explicitly specified cache hash - allow to cache it. + if node.meta.get("user_cache_hash", None): + return + if isinstance(node.target, str): + raise AssertionError( + f"expected node.target to not be a string, got {node.target}" + ) + if not is_cacheable_function(node.target): + module = getattr(node.target, "__module__", None) + name = getattr(node.target, "__name__", None) + raise BypassAOTAutogradCache( + f"Unsupported call_function target {node.target}. \n Function module: {module}, \nFunction name: {name}" + ) + elif node.op == "call_method": + method_name = node.target + method_target = node.args[0] + # Only support method calls on base tensors + if not isinstance(method_target, Node): + raise AssertionError( + f"expected method_target to be Node, got {type(method_target)}" + ) + if not is_tensor(method_target): + module = getattr(method_target, "__module__", None) + name = getattr(method_target, "__name__", None) + raise BypassAOTAutogradCache( + f"Unsupported call_method target {method_target}. \nMethod module: {module}, \nMethod name: {name}" + ) + if ( + type(method_name) is not str + and type(method_name).__name__ != "method_descriptor" + ): + raise BypassAOTAutogradCache( + f"Unsupported call_method method {node.target}: {method_name}" + ) + # Cache safe + elif node.op in ("placeholder", "get_attr", "call_module", "output"): + # Assumption today for call_module being a safe op: + # (1) today the only call_module ops that can show up in a graph come from "built-in-nn-modules" + # that dynamo assumes are safe to trace. If dynamo assumes they are safely to blindly trace, then + # they should be safe to cache as well. + # (2) in the steady-state (some time in H2?) we shouldn't see these anymore, once inline builtin nn modules by default + # (3) We do not allow user made nn modules in the graph today, only function calls. + pass + else: + raise BypassAOTAutogradCache(f"Unsupported node op {node.op}") + + +def check_cacheable(gm: torch.fx.GraphModule) -> None: + """ + Checks that the graph module only uses supported operators + """ + nodes = gm.graph.nodes + if torch._inductor.config.freezing: + raise BypassAOTAutogradCache("Cannot cache a graph with freezing enabled") + + if not ( + torch._inductor.config.fx_graph_cache or should_use_remote_fx_graph_cache() + ): + raise BypassAOTAutogradCache("FX graph cache is not enabled") + + tracing_context = torch._guards.TracingContext.try_get() + if tracing_context and tracing_context.fakify_first_call: + raise BypassAOTAutogradCache( + "Won't cache a graph with fakify_first_call enabled" + ) + for node in nodes: + check_node_safe(node) + + # Saved tensors hooks are globally set subgraphs, + # that are not used explicitly in the main graph. + # They are inlined in aot_autograd graphs. + # Subgraphs are only used for caching logic. + if hasattr(gm, "saved_tensors_hooks_pack_0"): + check_cacheable(gm.saved_tensors_hooks_pack_0) # type: ignore[arg-type] + # We have guarantee of unpack subgraph existence if pack subgraph exists + check_cacheable(gm.saved_tensors_hooks_unpack_0) # type: ignore[arg-type] + + +def _get_context_fn_cache_hash(context_fn: Callable[..., Any]) -> str | None: + """ + Extract a cache hash from a context_fn used for selective activation checkpointing (SAC). + + The context_fn determines which ops are saved vs recomputed in the SAC region. + Since context_fn can be an arbitrary Python function, we cannot reliably pickle + it for cache key generation (pickle only captures the function name, not the code). + + Users must provide a stable hash by setting a `cache_hash` attribute on the context_fn. + For functools.partial objects, set the cache_hash on the partial object itself, not on + the underlying function. + + Returns: + The cache hash if found + None: If no hash is provided (caller should bypass caching) + """ + if hasattr(context_fn, "cache_hash"): + return context_fn.cache_hash + + return None + + +def _iter_graph_modules( + gm: torch.fx.GraphModule, +) -> Generator[torch.fx.GraphModule, None, None]: + for module in gm.modules(): + if isinstance(module, torch.fx.GraphModule): + yield module + + +def _collect_context_fn_hashes(gm: torch.fx.GraphModule) -> list[str]: + """ + Collect cache hashes from all context_fn used in SAC HOPs within the graph module. + + Returns a list of hashes. Raises BypassAOTAutogradCache if any context_fn + lacks a cache_hash attribute. + """ + hashes = [] + for module in _iter_graph_modules(gm): + context_fn = module.meta.get("_checkpoint_context_fn") + if context_fn is not None: + cache_hash = _get_context_fn_cache_hash(context_fn) + if cache_hash is None: + raise BypassAOTAutogradCache( + "SAC context_fn does not have a cache_hash attribute. " + "To enable caching with selective activation checkpointing, " + "add a 'cache_hash' attribute to your context_fn. This can be " + "a string or any hashable value that uniquely identifies the checkpointing " + "behavior (e.g., based on source code hash and closed-over globals). " + "For functools.partial objects, set cache_hash on the partial itself." + ) + hashes.append(cache_hash) + return hashes + + +def _collect_wrapped_user_cache_hashes(gm: torch.fx.GraphModule) -> list[str]: + wrapped_user_cache_hashes = [] + for node in gm.graph.nodes: + if node.meta and node.meta.get("is_wrapped", False): + wrapped_user_cache_hashes.append(node.meta["user_cache_hash"]) + return wrapped_user_cache_hashes + + +def _collect_saved_tensors_hooks_fx_wrap_cache_hashes( + gm: torch.fx.GraphModule, +) -> tuple[list[str], list[str]]: + if not hasattr(gm, "saved_tensors_hooks_pack_0"): + return ([], []) + + return ( + _collect_wrapped_user_cache_hashes( + # pyrefly: ignore[bad-argument-type] + gm.saved_tensors_hooks_pack_0 + ), + _collect_wrapped_user_cache_hashes( + # pyrefly: ignore[bad-argument-type] + gm.saved_tensors_hooks_unpack_0 + ), + ) + + +def _get_custom_estimator_solver_uuids( + autograd_config: Any, +) -> tuple[object | None, object | None]: + """ + Extract uuid values from custom runtime estimator and solver configs if they have uuid() methods. + + Returns a tuple of (runtime_estimator_uuid, solver_uuid). + + Returns None for each component if: + - The config field value is None + - The config field value is a string (built-in option like "flops", "greedy") + + Raises BypassAOTAutogradCache if: + - The config field value is a raw callable without uuid() method (caching not supported) + - The CustomRuntimeEstimator/CustomKnapsackSolver's uuid() method returns None + (caching explicitly disabled by implementation) + """ + + runtime_estimator = getattr( + autograd_config, "activation_memory_budget_runtime_estimator", None + ) + solver = getattr(autograd_config, "activation_memory_budget_solver", None) + + runtime_estimator_uuid = None + solver_uuid = None + + if isinstance(runtime_estimator, CustomRuntimeEstimator): + runtime_estimator_uuid = runtime_estimator.uuid() + if runtime_estimator_uuid is None: + raise BypassAOTAutogradCache( + "CustomRuntimeEstimator.uuid() returned None, bypassing cache" + ) + elif callable(runtime_estimator) and not isinstance(runtime_estimator, str): + raise BypassAOTAutogradCache( + "activation_memory_budget_runtime_estimator is a raw callable without uuid() method, " + "bypassing cache. Use CustomRuntimeEstimator for cache support." + ) + + if isinstance(solver, CustomKnapsackSolver): + solver_uuid = solver.uuid() + if solver_uuid is None: + raise BypassAOTAutogradCache( + "CustomKnapsackSolver.uuid() returned None, bypassing cache" + ) + elif callable(solver) and not isinstance(solver, str): + raise BypassAOTAutogradCache( + "activation_memory_budget_solver is a raw callable without uuid() method, " + "bypassing cache. Use CustomKnapsackSolver for cache support." + ) + + return runtime_estimator_uuid, solver_uuid + + +class AOTAutogradCacheDetails(FxGraphHashDetails): + """ + Object to capture all the details for a dynamo graph module relevant to computing + a safe and stable cache key for AOTAutograd. + """ + + def _iter_triton_kernels_from_node(self, node: Node) -> Generator[Any, None, None]: + if isinstance(node.target, torch._ops.OpOverloadPacket): + for attr in node.target._dir: + custom_op = getattr(node.target, attr, None) + if custom_op is not None: + yield from torch._library.triton.get_triton_kernels_for_op( + custom_op._name + ) + return + if isinstance(node.target, torch._ops.OpOverload): + yield from torch._library.triton.get_triton_kernels_for_op( + node.target._name + ) + + def get_triton_source_codes_from_gm( + self, + gm: torch.fx.GraphModule, + ) -> list[str]: + if not has_triton_package(): + raise AssertionError("Triton is not available") + + triton_kernels = [] + for module in _iter_graph_modules(gm): + for node in module.graph.nodes: + triton_kernels.extend(self._iter_triton_kernels_from_node(node)) + + triton_kernel_source_codes = [] + from torch._inductor.codegen.wrapper import ( + user_defined_triton_kernel_transitive_closure_source_code, + ) + + for kernel in triton_kernels: + from triton.runtime.autotuner import Autotuner + + if isinstance(kernel, Autotuner): + # Grab the Inner JITFunction + kernel = kernel.fn + source_codes = user_defined_triton_kernel_transitive_closure_source_code( + kernel + ) + triton_kernel_source_codes.append(source_codes) + + return triton_kernel_source_codes + + def __init__( + self, + gm: torch.fx.GraphModule, + example_inputs: Sequence[Any], + aot_config: AOTConfig, + fx_config: _CompileFxKwargs, + act_input_paths: ActInputPaths = (), + ) -> None: + # FxGraphHashDetails contains all the keys related to inductor. Also + # includes some system info. + self.aot_config = aot_config + self.act_input_paths = tuple(act_input_paths) + self._record_runtime_state(gm) + self.saved_tensors_hooks_fx_wrap_cache_hashes = ( + _collect_saved_tensors_hooks_fx_wrap_cache_hashes(gm) + ) + self.sac_context_fn_hashes = _collect_context_fn_hashes(gm) + + # region_activation_memory_budget is graph-wide (the partitioner enforces + # a single value across the graph) and propagates to every node, so the + # cache key only needs the value off the first node. node.meta is stripped + # by GraphModule.__reduce__, so without recording it here a budget change + # would not invalidate the cache. + first_node = next(iter(gm.graph.nodes), None) + self.region_activation_memory_budget: float | None = ( + _get_memory_budget_annotation(first_node) + if first_node is not None + else None + ) + + # Note: We use the live config module, not self.autograd_config (the + # saved config), because activation_memory_budget_runtime_estimator and + # activation_memory_budget_solver are excluded from save_config (in + # _save_config_ignore) since they're not serializable. We must access the + # config module directly to get the patched runtime values. + self.custom_estimator_solver_uuids = _get_custom_estimator_solver_uuids(config) + self._init_fx_graph_hash_details(gm, example_inputs, fx_config) + + def _record_runtime_state(self, gm: torch.fx.GraphModule) -> None: + self.grad_enabled = torch.is_grad_enabled() + # Include per-device autocast dtype in cache key to avoid reusing + # a graph compiled for one autocast dtype (e.g. bfloat16) when + # running under a different autocast dtype (e.g. float16). + self.autocast_state: dict[str, torch.dtype] = {} + for device_type in torch._C._autocast_supported_devices(): + if torch.is_autocast_enabled(device_type): + self.autocast_state[device_type] = torch.get_autocast_dtype(device_type) + self.deterministic_algorithms = torch.are_deterministic_algorithms_enabled() + self.autograd_config = config.save_config() + if has_triton_package(): + self.triton_kernel_source_codes = self.get_triton_source_codes_from_gm(gm) + + def _init_fx_graph_hash_details( + self, + gm: torch.fx.GraphModule, + example_inputs: Sequence[Any], + fx_config: _CompileFxKwargs, + ) -> None: + try: + # FXGraphCache has constraints on what can be pickled in its inductor + # config. Check that the gm is cacheable by inductor first, + # and if it raises an exception, also bypass on our end. + FxGraphCache._check_can_cache(gm, example_inputs, fx_config) + super().__init__(gm, example_inputs, fx_config, []) + except BypassFxGraphCache as e: + # Sometimes inductor configs are unpickleable and can fail + raise BypassAOTAutogradCache(str(e)) from e + + +class AOTAutogradCachePickler(FxGraphCachePickler): + def __init__( + self, + gm: torch.fx.GraphModule, + symint_name_map: dict[str, str] | None = None, + graph_symint_names: set[str] | None = None, + ) -> None: + super().__init__(gm) + self._symint_name_map: dict[str, str] = symint_name_map or {} + self._graph_symint_names: set[str] = graph_symint_names or set() + # pyrefly: ignore[missing-attribute] + self.dispatch_table.update( + { + AOTConfig: functools.partial(self._reduce_aot_config), + torch.Tensor: functools.partial(self._reduce_tensor), + FakeScriptObject: functools.partial(self._reduce_fake_script_object), + } + ) + + def _reduce_symint( + self, s: torch.SymInt + ) -> tuple[Callable[..., Any], tuple[Any, ...]]: + name = str(s) + normalized = self._symint_name_map.get(name) + if normalized is not None: + if name in self._graph_symint_names: + return (_ident, (normalized,)) + # Non-graph SymInt with non-deterministic name (from MetaConverter). + # Include the hint to distinguish different specializations. + hint = s.node.hint + if hint is not None: + return (_ident, (normalized, hint)) + return (_ident, (name,)) + + # pyrefly: ignore [bad-override] + def reducer_override(self, obj: Any) -> Any: + """ + Override to handle tensor subclasses (like DTensor) that aren't caught + by the dispatch_table's exact type matching. + + The dispatch_table only matches exact types, so subclasses like DTensor + fall through to the default __reduce_ex__ which includes non-deterministic + storage addresses. This method catches those cases using isinstance checks. + """ + if isinstance(obj, torch.fx.GraphModule): + return self._reduce_graph_module_for_cache_key(obj) + if (numpy_key := numpy_wrapper_cache_key(obj)) is not None: + return (_ident, (numpy_key,)) + # Handle tensor subclasses that aren't exactly torch.Tensor + # dispatch_table already handles torch.Tensor exactly + if isinstance(obj, torch.Tensor) and type(obj) is not torch.Tensor: + return self._reduce_tensor_subclass(obj) + # Fall back to parent class reducer which handles unpicklable types + return super().reducer_override(obj) + + @staticmethod + def _format_global_for_cache_key(name: str, obj: Any) -> str: + if (numpy_key := numpy_wrapper_cache_key(obj)) is not None: + return f"# cache_key_numpy_wrapper {name}: {numpy_key!r}" + + from torch.fx.graph_module import _format_import_statement + from torch.package import sys_importer + + return _format_import_statement(name, obj, sys_importer) + + def _reduce_graph_module_for_cache_key( + self, gm: torch.fx.GraphModule + ) -> tuple[Callable[..., Any], tuple[Any, ...]]: + recompile = getattr(gm, "_real_recompile", gm.recompile) + python_code = recompile() + # FxGraphCache strips user-defined Triton side-table indices from + # Inductor wrapper code. This reducer handles arbitrary AOT GraphModule + # code, so keep the generated code exact and let AOTAutogradCacheDetails + # carry Triton source/constant-arg metadata separately. + dict_without_graph = gm.__dict__.copy() + dict_without_graph.pop("_graph", None) + + import_block = "\n".join( + sorted( + self._format_global_for_cache_key(name, obj) + for name, obj in python_code.globals.items() + ) + ) + return (_ident, ((dict_without_graph, import_block),)) + + # [NOTE] Tensor subclass stable hashing for AOT autograd cache + # Python's hash() varies with PYTHONHASHSEED, making cache keys unstable + # across processes. We use blake2b for cross-process determinism. + # + # EXTENSION POINT: Traceable wrapper subclasses can override cache key + # generation by implementing _stable_hash_for_caching(self) -> str. + # This method should return a deterministic string that uniquely identifies + # the tensor's metadata for caching purposes. See DTensor for an example. + # + # We can't define a default method on subclasses because there is no abstract + # base subclass, and we don't want to pollute torch.Tensor. Instead, we provide + # a default implementation here that uses __tensor_flatten__ to recursively + # hash inner tensors and metadata. + + def _hash_bytes_for_cache(self, data: bytes) -> str: + return hashlib.blake2b(data, digest_size=16).hexdigest() + + def _hash_pickled_value_for_cache(self, value: Any) -> str: + return self._hash_bytes_for_cache(pickle.dumps(value)) + + def _stable_hash_for_cache_value(self, obj: Any) -> str: + """Get a stable hash for an object used inside tensor subclass metadata.""" + from torch._custom_class_base import CustomClassBase + from torch.utils._python_dispatch import is_traceable_wrapper_subclass + + if hasattr(obj, "_stable_hash_for_caching"): + return obj._stable_hash_for_caching() + if isinstance(obj, torch.Tensor) and is_traceable_wrapper_subclass(obj): + return self._default_stable_hash_for_caching(obj) + if isinstance(obj, CustomClassBase): + # Opaque objects are runtime pass-throughs; only the type matters + # for cache key purposes, not the instance identity or value. + return self._hash_bytes_for_cache(type(obj).__qualname__.encode()) + if isinstance(obj, torch.Tensor): + return self._hash_pickled_value_for_cache( + extract_tensor_metadata_for_cache_key(obj) + ) + return self._hash_pickled_value_for_cache(obj) + + def _reduce_tensor_subclass( + self, tensor: torch.Tensor + ) -> tuple[Callable[..., Any], tuple[Any]]: + from torch.utils._python_dispatch import is_traceable_wrapper_subclass + + if hasattr(tensor, "_stable_hash_for_caching"): + return (_ident, (tensor._stable_hash_for_caching(),)) + if is_traceable_wrapper_subclass(tensor): + warn_once( + f"{type(tensor).__name__} does not implement _stable_hash_for_caching. " + "For PT2-compatible tensor subclasses, it is recommended to implement " + "_stable_hash_for_caching(self) -> str for stable AOT autograd caching." + ) + return (_ident, (self._default_stable_hash_for_caching(tensor),)) + return self._reduce_tensor(tensor) + + def _collect_inner_tensor_hashes( + self, tensor: torch.Tensor, inner_tensor_names: Sequence[str] + ) -> dict[str, str]: + inner_hashes = {} + for name in inner_tensor_names: + inner_hashes[name] = self._stable_hash_for_cache_value( + getattr(tensor, name) + ) + return inner_hashes + + def _stabilize_tensor_subclass_metadata(self, obj: Any) -> Any: + from torch._custom_class_base import CustomClassBase + + if isinstance(obj, CustomClassBase): + return type(obj).__qualname__ + if isinstance(obj, tuple): + return tuple(self._stabilize_tensor_subclass_metadata(x) for x in obj) + if isinstance(obj, list): + return [self._stabilize_tensor_subclass_metadata(x) for x in obj] + if isinstance(obj, dict): + return { + k: self._stabilize_tensor_subclass_metadata(v) for k, v in obj.items() + } + return obj + + def _default_stable_hash_for_caching(self, tensor: torch.Tensor) -> str: + """ + Default stable hash implementation for traceable wrapper subclasses. + """ + inner_tensor_names, subclass_metadata = tensor.__tensor_flatten__() # type: ignore[attr-defined] + cache_payload = ( + tensor.shape, + tensor.requires_grad, + self._stabilize_tensor_subclass_metadata(subclass_metadata), + self._collect_inner_tensor_hashes(tensor, inner_tensor_names), + ) + return self._hash_pickled_value_for_cache(cache_payload) + + def _reduce_aot_config( + self, aot_config: AOTConfig + ) -> tuple[Callable[..., Any], tuple[Any, ...]]: + """ + Reduce the config to a stable key for caching. + """ + cacheable = aot_config.to_cacheable() + return ( + # Cache entries persist the full CacheableAOTConfig, but cache keys + # intentionally ignore the debug-only aot_id so equivalent graphs can hit. + _ident, + ( + cacheable.num_params_buffers, + cacheable.keep_inference_input_mutations, + cacheable.is_export, + cacheable.no_tangents, + cacheable.dynamic_shapes, + cacheable.aot_autograd_arg_pos_to_source, + cacheable.static_input_indices, + cacheable.enable_log, + cacheable.pre_dispatch, + cacheable.precompile_backend_id, + ), + ) + + def _reduce_tensor(self, t: torch.Tensor) -> tuple[Callable[..., Any], tuple[Any]]: + """ + Reduce the tensor to a stable key for caching. + """ + metadata = extract_tensor_metadata_for_cache_key(t) + return (_ident, (metadata,)) + + +@contextlib.contextmanager +def normalize_placeholder_names( + gm: torch.fx.GraphModule, +) -> Generator[None, None, None]: + """ + Context manager that normalizes the placeholder names in the graph module. + This is used while generating a cache key for AOTAutogradCache, so that two graphs + that are isomorphic when normalizing names can hit the same cache entry. + This is safe because nothing underneath AOTAutograd uses the node names on the + original dynamo graph: AOTAutograd re-traces with its own nodes, and guards are + in terms of original sources rather than placeholder names. + """ + # Standalone inductor: we're bypassing AOTAutogradCache anyway, so return the graph + # as-is + if not config.autograd_cache_normalize_inputs or not hasattr(gm, "graph"): + yield + return + + # Track all the old state of placeholders + old_placeholder_names = [] + old_symint_names = [] + old_used_names = copy(gm.graph._graph_namespace._used_names) + i = 0 + j = 0 + for n in gm.graph.find_nodes(op="placeholder", sort=True): + if n.type == torch.SymInt: + new_name = f"s_{j}" + old_symint_names.append((n.name, n.target)) + n.target = new_name + n._rename(new_name) + j += 1 + else: + # _rename renames the node in the body of the function, + # but it doesn't change the raw name from node.target + # So we also set the raw_name of node.target to a new placeholder name + new_placeholder_name = f"p_{i}" + old_placeholder_names.append((n.name, n.target)) + n.target = new_placeholder_name + n._rename(new_placeholder_name) + i += 1 + gm.recompile() + try: + yield + finally: + # Used_names contains all our old placeholder names, + # so we clear it temporarily when we put them back + gm.graph._graph_namespace._used_names = set() + # Restore the placeholder names + i = 0 + j = 0 + for n in gm.graph.find_nodes(op="placeholder", sort=True): + if n.type == torch.SymInt: + (name, target) = old_symint_names[j] + n.target = target + n._rename(name) + j += 1 + else: + (name, target) = old_placeholder_names[i] + n.target = target + n._rename(name) + i += 1 + if i != len(old_placeholder_names): + raise AssertionError( + f"i={i} != len(old_placeholder_names)={len(old_placeholder_names)}" + ) + if j != len(old_symint_names): + raise AssertionError( + f"j={j} != len(old_symint_names)={len(old_symint_names)}" + ) + # Now restore the old namespace's used names + gm.graph._graph_namespace._used_names = old_used_names + gm.recompile() + + +def create_fx_config( + compiler_config_extra: CompilerConfigExtra | None = None, + compile_region_name: str | None = None, +) -> _CompileFxKwargs: + if compiler_config_extra is None: + cudagraphs = BoxedBool(torch._inductor.config.triton.cudagraphs) + boxed_forward_device_index = None + else: + cudagraphs = compiler_config_extra.cudagraphs + boxed_forward_device_index = compiler_config_extra.forward_device + return { + "cudagraphs": cudagraphs, + "boxed_forward_device_index": boxed_forward_device_index, + "compile_region_name": compile_region_name, # pyrefly: ignore[bad-typed-dict-key] + } + + +def _check_triton_cache_version() -> None: + if not has_triton_package(): + return + + # Due to https://github.com/triton-lang/triton/issues/3729, if triton is < + # 3.2.0, AOTAutogradCache may cause us to attempt to load a cache entry + # without initializing the CUDA context on the autograd thread. + # + # Without caching, we naturally do this initialization when tracing through + # the graph with the autograd engine. + import triton + + if triton.__version__ < "3.2.0": + raise BypassAOTAutogradCache("AOTAutogradCache requires triton 3.2.0") + + +def _get_debug_lines_for_cache_key( + pickler: AOTAutogradCachePickler, + details: AOTAutogradCacheDetails, + key: str, +) -> list[str]: + # debug_lines re-hashes every attribute individually and is expensive. Only + # compute when debug logging is enabled. + if not log.isEnabledFor(logging.DEBUG): + return [] + + debug_lines = pickler.debug_lines(details) + log.debug( + "Autograd graph cache hash details for key %s:\n%s", + key, + LazyString(lambda: "\n".join(debug_lines)), + ) + return debug_lines + + +def autograd_cache_key( + mod: torch.fx.GraphModule | torch._dynamo.utils.GmWrapper, + example_inputs: Sequence[Any], + config: AOTConfig, + compiler_config_extra: CompilerConfigExtra | None = None, + act_input_paths: ActInputPaths = (), + # TODO: add args and parameters +) -> tuple[str, list[str]]: + """ + Generate a unique hash of the FX graph for caching. + """ + + gm = mod.gm if isinstance(mod, torch._dynamo.utils.GmWrapper) else mod + try: + # Capture graph SymInt placeholder names before normalization so the + # pickler can distinguish graph-native SymInts (deterministic names) + # from MetaConverter-generated SymInts (non-deterministic names). + graph_symint_names: set[str] = set() + symint_name_map: dict[str, str] = {} + if torch._functorch.config.autograd_cache_normalize_inputs: + for n in gm.graph.find_nodes(op="placeholder", sort=True): + if n.type == torch.SymInt: + graph_symint_names.add(n.target) + j = 0 + for inp in example_inputs: + if isinstance(inp, torch.SymInt): + symint_name_map[str(inp)] = f"s_{j}" + j += 1 + with sanitize_gm_for_cache(gm): + check_cacheable(gm) + _check_triton_cache_version() + details = AOTAutogradCacheDetails( + gm, + example_inputs, + config, + create_fx_config(compiler_config_extra), + act_input_paths, + ) + pickler = AOTAutogradCachePickler(gm, symint_name_map, graph_symint_names) + # The prefix distinguishes among the other kinds of objects we cache + key = AOTAUTOGRAD_CACHE_PREFIX + pickler.get_hash(details) + debug_lines = _get_debug_lines_for_cache_key(pickler, details, key) + return key, debug_lines + except Exception: + # If enable_aot_compile is set, we're in AOT precompile mode where we always + # want to use fallback nonce keys. Unlike caching, it's fine if we can't generate + # a proper key because we are guaranteed in an AOT precompile world users are in + # complete control of distributing and loading artifacts. + if torch._functorch.config.bypass_autograd_cache_key: + log.info( + "Failed to generate AOTAutograd cache key; falling back to nonce due to enable_aot_compile", + exc_info=True, + ) + return str(random.random()), [] + else: + raise + + +@contextlib.contextmanager +def sanitize_gm_for_cache( + gm: torch.fx.GraphModule, +) -> Generator[None, None, None]: + """ + Clears a few fields in a dynamo supplied Graph Module that are not stable between graph inputs, but don't + affect inductor or aotdispatch correctness. + + These fields **can** be used by code calling into aotdispatch (namely, dynamo), so we can't null them out completely. + + To ensure that these fields are not accessed by inductor or aotdispatch, we clear them during AOTAutogradCache.load, + and then put them back before returning. This way, we generate a cache key based off of a canonical graph + without these fields, and also guarantee they aren't used to affect the cache's output. + """ + # Mapping from each field to a default value + IGNORED_FIELDS: dict[str, Any] = { + # pyrefly: ignore [implicit-any] + "meta": {}, # metadata used by export + "compile_subgraph_reason": None, # Used by dynamo only for logging, no change in inductor/autograd behavior + "_param_name_to_source": None, # Encapsulated by aot_config.aot_autograd_arg_pos_to_source + "_backend_id": None, + } + saved_fields = {} + for field, default_value in IGNORED_FIELDS.items(): + saved_fields[field] = getattr(gm, field, None) + # Clear the field + setattr(gm, field, default_value) + try: + with normalize_placeholder_names(gm): + yield + finally: + for field, value in saved_fields.items(): + setattr(gm, field, value) + + +@CacheArtifactFactory.register +class AOTAutogradCacheArtifact(CacheArtifact): + @override + def populate_cache(self) -> None: + AOTAutogradCache._write_to_local_cache(self.key, self.content) + + @override + @staticmethod + def type() -> str: + return "aot_autograd" + + +class AOTAutogradCache(GuardedCache[GenericAOTAutogradResult[Any, Any]]): + """ + Caches the results of running AOTAutograd. This class mostly handles the save and load logic, whereas + AOTAutogradResult handles the wrapping/unwrapping logic. + + Cache Inputs (AOTAutogradCacheDetails) + - AOTAutogradCache takes in the following inputs, which are analogous to inputs given + to AOTAutograd by dynamo: + - A fx graph module generated by dynamo + - A list of args, which consists of: + - Symint inputs to the graph, generated by dynamo + - The **real tensor** inputs, which inductor uses for cudagraphs + - Notably, the real tensor inputs don't have symints in their metadata. + AOTAutograd then retraces those real tensor arguments into FakeTensors later during execution. + - A set of global configurations that affect AOTAutograd or Inductor behavior. + + It then generates a cache key given these values. Notably, this means AOTAutogradCache currently + specializes on the sizes and strides of the real tensor inputs when dynamic shapes are turned on. + In a later PR, we'll likely generate the cache key based on the FakeTensors AOTAutograd generates + based on the real tensor inputs, which can contain symints. + + # Cache Outputs (AOTAutogradResult) + - AOTAutogradCache caches the following values: + - The compiled forward and backward functions from inductor, via keys to the FXGraphCache + - Metadata to reconstruct the AOTModule from the compiled inductor artifacts + - See AOTAutogradResult for more info + + [Note: Caching guards generated by AOTAutograd and Inductor] + AOTAutograd and inductor both can introduce new guards to the shape environment. FXGraphCache saves guards with each + compiled graph inductor generates. On a cache hit, AOTAutograd reloads the compiled forward and backward functions + from FXGraphCache, giving it new symint arguments from the input args. + FXGraphCache uses those symints and its saved guards to repopulate the ShapeEnv with guards. + **No new guards are generated into the shape env after inductor finishes compiling**, so the guards + saved by inductor are sufficient for correctness for both AOTAutograd and Inductor's caches. + """ + + @staticmethod + def clear() -> None: + """Clear the cache""" + shutil.rmtree(AOTAutogradCache._get_tmp_dir(), ignore_errors=True) + + @staticmethod + def try_load( + mod: torch.fx.GraphModule | torch._dynamo.utils.GmWrapper, + args: list[Any], + aot_config: AOTConfig, + compiler_config_extra: CompilerConfigExtra | None, + local: bool, + remote: bool, + act_input_paths: ActInputPaths = (), + compile_region_name: str | None = None, + ) -> tuple[Callable[..., Any] | None, AOTConfig]: + """ + Load a result from the cache, and reconstruct a runtime wrapper around + the object. On a cache miss, return an updated config carrying the + cache metadata needed to save the eventual compile result. + """ + compiled_fn = None + cache_info: dict[str, Any] = {} + cache_key = None + debug_lines: list[str] = [] + cache_event_time = time.time_ns() + cache_state = None + try: + cache_key, debug_lines = autograd_cache_key( + mod, args, aot_config, compiler_config_extra, act_input_paths + ) + result: tuple[GenericAOTAutogradResult[Any, Any], bytes] | None = ( + AOTAutogradCache._lookup( + cache_key, local, remote, args, cache_info, aot_config + ) + ) + if result is not None: + (entry, pickled_content) = result + fx_config = create_fx_config(compiler_config_extra, compile_region_name) + compiled_fn = entry.wrap_post_compile(args, aot_config, fx_config) + # Make the compiled_fn serializable, where the serialize function just + # makes a copy of the original entry before post compile via the pickled content + compiled_fn = SerializableCompiledFunction( + compiled_fn, lambda: pickle.loads(pickled_content) + ) + log.info("AOTAutograd cache hit for key %s", cache_key) + + counters["aot_autograd"]["autograd_cache_hit"] += 1 + cache_state = "hit" + cache_event_time = time.time_ns() + forward_time_saved = entry.forward_time_taken_ns // 1e6 + backward_time_saved = entry.backward_time_taken_ns // 1e6 + cache_info.update( + { + "forward_time_saved_ms": forward_time_saved, + "backward_time_saved_ms": backward_time_saved, + "time_saved_ms": forward_time_saved + backward_time_saved, + } + ) + time_saved_ns = ( + entry.forward_time_taken_ns + entry.backward_time_taken_ns + ) + # TODO: should we use the same field for remote cache time saved for both + # FXGraphCache and AOTAutogradCache? + # get_metrics_context().increment(...) + if ( + ephemeral_increase + := add_ephemeral_timeout_increase_for_distributed(time_saved_ns) + ) != 0: + cache_info["ephemeral_timeout_increase"] = ephemeral_increase + + if compiled_fn is None: + log.info("AOTAutograd cache miss for key %s", cache_key) + counters["aot_autograd"]["autograd_cache_miss"] += 1 + cache_state = "miss" + cache_event_time = time.time_ns() + # Count missing the FXGraphCache as a miss not a bypass + except FXGraphCacheMiss as e: + counters["aot_autograd"]["autograd_cache_miss"] += 1 + cache_state = "miss" + if config.strict_autograd_cache or torch._dynamo.config.strict_precompile: + raise e + # Most often this is BypassAOTAutogradCache, but + # if there's ever different reason we can't cache, + # we still never want to hard throw an exception, since + # we can always fallback to a cache bypass. + # As an example, if the user calls autograd via + # standalone inductor, we will sometimes get a GraphModule + # that doesn't actually have a `.graph` on it. Instead + # of checking every single case, we safely catch the exception + # in those cases. + except Exception as e: + cache_key = None + counters["aot_autograd"]["autograd_cache_bypass"] += 1 + log.info("Bypassing autograd cache due to: %s", e) + cache_state = "bypass" + cache_event_time = time.time_ns() + cache_info["cache_bypass_reason"] = str(e) + cache_info["cache_bypass_exception_type"] = type(e).__name__ + cache_info["cache_bypass_traceback"] = traceback.format_exc().split("\n") + # TODO: this gets logged implicitly by cache_bypass_reason, + # and here we explicitly log it into tlparse. + # We may want to log this as an extra column in Scuba, though. + cache_info["cache_bypass_hard_exception"] = not isinstance( + e, BypassAOTAutogradCache + ) + if remote: + log_cache_bypass("bypass_aot_autograd", str(e)) + if config.strict_autograd_cache or torch._dynamo.config.strict_precompile: + raise e + if compiled_fn is None: + # Set the cache key so we can save a cache result later + symints = AOTAutogradCache._filter_backed_symints(args) + if cache_key is not None: + aot_config = dataclasses.replace( + aot_config, + cache_info=AOTAutogradCacheInfo( + cache_key, + time.time_ns(), + forward_symints=symints, + ), + ) + + cache_info.update( + { + "key": cache_key, + "cache_state": cache_state, + "components": debug_lines, + } + ) + if chromium_event_log_active(): + CompileEventLogger.instant( + f"autograd_cache_{cache_state}", + metadata=cache_info, + time_ns=cache_event_time, + ) + CompileEventLogger.try_add_pt2_compile( + "backend_compile", + cache_state=cache_state, + cache_event_time=cache_event_time, + key=cache_info.get("key"), + components=cache_info.get("components"), + cache_bypass_reason=cache_info.get("cache_bypass_reason"), + remote_cache_enabled=remote, + local_cache_enabled=local, + ) + + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": f"aotautograd_cache_{cache_state}", + "encoding": "json", + }, + payload_fn=lambda: json.dumps(cache_info), + ) + + return compiled_fn, aot_config + + @classmethod + def generate_guards_expression( + cls: type[AOTAutogradCache], cache_info: AOTAutogradCacheInfo + ) -> str | None: + shape_env = cls._get_shape_env() + + if shape_env is None: + return None + + symints = cache_info.forward_symints + guards = shape_env.get_pruned_guards(symints) + return shape_env.produce_guards_expression(placeholders=symints, guards=guards) + + @classmethod + def _get_tmp_dir(cls: type[AOTAutogradCache]) -> str: + """ + Get the toplevel temporary directory for storing compiled graphs. + """ + return os.path.join(cache_dir(), "aotautograd") + + @classmethod + def _get_tmp_dir_for_key(cls: type[AOTAutogradCache], _key: str) -> str: + """ + Get the toplevel temporary directory for storing compiled graphs. + """ + return os.path.join(cls._get_tmp_dir(), _key) + + @classmethod + def _record_result( + cls: type[AOTAutogradCache], + key: str, + local_hit: bool, + local_miss: bool, + remote_hit: bool, + remote_miss: bool, + ) -> None: + """ + Called by GuardedCache to record hit/miss statistics. + """ + if local_hit: + cache_stats.hit("LocalAOTAutogradCache") + CompileEventLogger.try_( + CompileEventLogger.increment_toplevel, + "aotautograd_local_cache_hit_count", + ) + if remote_hit: + CompileEventLogger.try_( + CompileEventLogger.increment_toplevel, + "aotautograd_remote_cache_hit_count", + ) + if local_miss: + cache_stats.miss("LocalAOTAutogradCache") + CompileEventLogger.try_( + CompileEventLogger.increment_toplevel, + "aotautograd_local_cache_miss_count", + ) + if remote_miss: + CompileEventLogger.try_( + CompileEventLogger.increment_toplevel, + "aotautograd_remote_cache_miss_count", + ) + + @staticmethod + def evaluate_guards(guard_expr: str, hints: list[int] | list[torch.SymInt]) -> bool: + if torch._inductor.config.unsafe_skip_cache_dynamic_shape_guards: + return True + shape_env = AOTAutogradCache._get_shape_env() + if shape_env is None: + raise AssertionError("shape_env must not be None") + result = shape_env.evaluate_guards_expression(guard_expr, hints) + return result + + @staticmethod + def _lookup( + key: str, + local: bool, + remote: bool, + args: list[Any], + cache_info: dict[str, Any], + aot_config: AOTConfig | None, + ) -> tuple[GenericAOTAutogradResult[Any, Any], bytes] | None: + """Given a key generated by AOTAutogradCachePickler, look up its location in the cache.""" + remote_cache: RemoteCache[JsonDataTy] | None = None + if remote: + remote_cache = AOTAutogradCache.get_remote_cache() + + symints = AOTAutogradCache._filter_backed_symints(args) + hints = [guarding_hint_or_throw(s) for s in symints] + entry = None + pickled_content = None + try: + ( + entry, + pickled_content, + guard_info, + ) = AOTAutogradCache.find_guarded_entry( + key, local, remote_cache, AOTAutogradCache.evaluate_guards, hints + ) + + if entry is None and guard_info["cache_status_detailed"] == "guard_miss": + counters["aot_autograd"]["autograd_cache_guard_miss"] += 1 + cache_info.update(guard_info) + CacheArtifactRecorder( + AOTAutogradCacheArtifact.type(), key + ).record_if_present(pickled_content) + if pickled_content is not None: + if ( + should_bundle_autograd_cache() + and aot_config is not None + and aot_config.precompile_backend_id is not None + ): + # NB: We don't want to use the cached aot_config.precompile_backend_id + # 1. because we set it to None on save 2. even if we didn't, this new run + # that cache hit has a *new* backend id associated with it. + PrecompileContext.record_artifact( + BundledAOTAutogradCacheArtifact( + aot_config.precompile_backend_id, entry + ), + ) + except Exception as e: + log.info("AOTAutograd cache unable to load compiled graph: %s", e) + if config.strict_autograd_cache: + raise e + if entry is not None: + if pickled_content is None: + raise AssertionError( + "pickled_content must not be None when entry is not None" + ) + return (entry, pickled_content) + else: + return None + + @staticmethod + def _write_to_local_cache(key: str, content: bytes) -> None: + """Write an entry to the local cache.""" + subdir = AOTAutogradCache._get_tmp_dir_for_key(key) + if not os.path.exists(subdir): + os.makedirs(subdir, exist_ok=True) + + # Use a hash of the serialized entry to get a unique file + # name. The specific name doesn't matter since a lookup involves + # iterating over all entries in the parent subdir. + path = os.path.join(subdir, sha256_hash(content)) + log.info("Writing AOTAutograd cache entry to %s", path) + write_atomic(path, content) + + @staticmethod + def _find_unpicklable_field( + entry: GenericAOTAutogradResult[Any, Any], + ) -> str | None: + """Find which field of entry is causing pickle to fail.""" + # pyrefly: ignore [implicit-any] + fields = [] + if hasattr(entry, "__dataclass_fields__"): + fields = list(entry.__dataclass_fields__.keys()) + elif hasattr(entry, "__dict__"): + fields = list(entry.__dict__.keys()) + + for name in fields: + try: + pickle.dumps(getattr(entry, name)) + except Exception: + return name + return None + + @staticmethod + def _pickle_entry( + entry: GenericAOTAutogradResult[Any, Any], remote: bool + ) -> bytes | None: + """Pickle entry, returning None on failure.""" + try: + with torch.utils._python_dispatch._disable_current_modes(): + return pickle.dumps(entry) + except (pickle.PicklingError, TypeError, AttributeError) as e: + bad_field = AOTAutogradCache._find_unpicklable_field(entry) + error_str = str(e) + log.warning("AOTAutograd cache unable to serialize compiled graph: %s", e) + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "aotautograd_cache_pickle_failure", + "encoding": "json", + }, + payload_fn=lambda: json.dumps({"error": error_str, "field": bad_field}), + ) + if remote: + log_cache_bypass( + "bypass_aot_autograd", "Unable to serialize: " + str(e) + ) + if config.strict_autograd_cache: + raise + return None + + @staticmethod + def _handle_save_error(e: Exception, remote: bool, is_bypass: bool) -> None: + """Handle exceptions during save, re-raising if strict mode is enabled.""" + if is_bypass: + counters["aot_autograd"]["autograd_cache_bypass"] += 1 + log.info("Bypassing autograd cache due to: %s", e) + bypass_reason = str(e) + else: + log.warning("AOTAutograd cache unable to serialize compiled graph: %s", e) + bypass_reason = "Unable to serialize: " + str(e) + if remote: + log_cache_bypass("bypass_aot_autograd", bypass_reason) + if config.strict_autograd_cache: + raise e + + @staticmethod + def save(key: str, entry: GenericAOTAutogradResult[Any, Any], remote: bool) -> None: + """Save a single entry into the cache.""" + content: bytes | None = None + try: + entry.pre_save() + content = AOTAutogradCache._pickle_entry(entry, remote) + if content is None: + return None + CacheArtifactRecorder(AOTAutogradCacheArtifact.type(), key).record(content) + if ( + should_bundle_autograd_cache() + and entry.sanitized_aot_config.precompile_backend_id is not None + ): + precompile_key = entry.sanitized_aot_config.precompile_backend_id + artifact = BundledAOTAutogradCacheArtifact(precompile_key, entry) + entry.sanitized_aot_config.precompile_backend_id = None + PrecompileContext.record_artifact(artifact) + AOTAutogradCache._write_to_local_cache(key, content) + counters["aot_autograd"]["autograd_cache_saved"] += 1 + cache_stats.put("LocalAOTAutogradCache") + except BypassAOTAutogradCache as e: + AOTAutogradCache._handle_save_error(e, remote, is_bypass=True) + return None + except Exception as e: + AOTAutogradCache._handle_save_error(e, remote, is_bypass=False) + return None + + if remote: + remote_cache = AOTAutogradCache.get_remote_cache() + if remote_cache is not None: + time_taken_ms = int( + (entry.forward_time_taken_ns + entry.backward_time_taken_ns) // 1e6 + ) + cache_data: JsonDataTy = { + "data": base64.b64encode(content).decode("ascii"), + "time_taken_ms": time_taken_ms, + } + remote_cache.put(key, cache_data) + + @staticmethod + @functools.cache + def get_remote_cache() -> RemoteCache[JsonDataTy] | None: + """ + Attempts to load the remote cache, returns None on error. + """ + cache_id = "autograd-experimental" + return create_cache( + cache_id, + config.is_fbcode(), + "FbRemoteAOTAutogradCache", + "RemoteAOTAutogradCache", + ) + + @staticmethod + def make_entry( + compiled_fw_func: OutputCode, + compiled_bw_func: OutputCode | None, + aot_joint_graph_str: str | None, + aot_forward_graph_str: str | None, + aot_backward_graph_str: str | None, + runtime_metadata: ViewAndMutationMeta, + dispatch_wrappers: list[CompilerWrapper], + maybe_subclass_meta: SubclassMeta | None, + num_fw_outs_saved_for_bw: int | None, + indices_of_inps_to_detach: list[int], + forward_time_taken_ns: int, + backward_time_taken_ns: int, + sanitized_aot_config: CacheableAOTConfig, + guards_expr: str | None, + backward_state_indices: list[int] | None, + num_symints_saved_for_bw: int | None, + serialized_bw_module: SerializedGraphModule | None, + min_cut_info_str: str | None, + ) -> GenericAOTAutogradResult[Any, Any]: + if should_bundle_autograd_cache(): + # Helper function to unwrap all the wrappers we added during aotdispatch + # They get reapplied on cache load + def unwrap_output_code(obj: object) -> OutputCode: + while hasattr(obj, "__wrapped__"): + obj = obj.__wrapped__ + if not isinstance(obj, OutputCode): + raise AssertionError(f"expected OutputCode, got {type(obj)}") + return obj + + compiled_fw_graph = unwrap_output_code(compiled_fw_func) + bundled_compiled_forward = BundledCompiledForward(compiled_fw_graph) + bundled_compiled_backward = None + if compiled_bw_func is not None: + if backward_state_indices is None: + raise AssertionError("backward_state_indices must not be None") + if num_symints_saved_for_bw is None: + raise AssertionError("num_symints_saved_for_bw must not be None") + compiled_bw_graph = unwrap_output_code(compiled_bw_func) + bundled_compiled_backward = BundledCompiledBackward( + compiled_bw_graph, backward_state_indices, num_symints_saved_for_bw + ) + + return BundledAOTAutogradResult( + compiled_fw=bundled_compiled_forward, + compiled_bw=bundled_compiled_backward, + aot_joint_graph_str=aot_joint_graph_str, + aot_forward_graph_str=aot_forward_graph_str, + aot_backward_graph_str=aot_backward_graph_str, + min_cut_info_str=min_cut_info_str, + runtime_metadata=runtime_metadata, + dispatch_wrappers=dispatch_wrappers, + maybe_subclass_meta=maybe_subclass_meta, + num_fw_outs_saved_for_bw=num_fw_outs_saved_for_bw, + indices_of_inps_to_detach=indices_of_inps_to_detach, + forward_time_taken_ns=forward_time_taken_ns, + backward_time_taken_ns=backward_time_taken_ns, + sanitized_aot_config=sanitized_aot_config, + guards_expr=guards_expr, + serialized_bw_module=serialized_bw_module, + ) + + else: + fw_key = getattr(compiled_fw_func, "_fx_graph_cache_key", None) + fw_debug_lines = getattr( + compiled_fw_func, "_fx_graph_cache_debug_lines", [] + ) + + if fw_key is None: + raise AssertionError("fw_key must not be None") + compiled_forward = CompiledForward( + fx_graph_cache_info=(fw_key, fw_debug_lines), + fx_graph_guard_expr=getattr(compiled_fw_func, "guards_expr", None), + ) + compiled_backward = None + if compiled_bw_func is not None: + bw_key = getattr(compiled_bw_func, "_fx_graph_cache_key", None) + bw_debug_lines = getattr( + compiled_bw_func, "_fx_graph_cache_debug_lines", [] + ) + if bw_key is None: + raise AssertionError("bw_key must not be None") + if backward_state_indices is None: + raise AssertionError("backward_state_indices must not be None") + if num_symints_saved_for_bw is None: + raise AssertionError("num_symints_saved_for_bw must not be None") + compiled_backward = CompiledBackward( + fx_graph_cache_info=(bw_key, bw_debug_lines), + fx_graph_guard_expr=getattr(compiled_bw_func, "guards_expr", None), + backward_state_indices=backward_state_indices, + num_symints_saved_for_bw_=num_symints_saved_for_bw, + ) + + return AOTAutogradResult( + compiled_fw=compiled_forward, + compiled_bw=compiled_backward, + aot_joint_graph_str=aot_joint_graph_str, + aot_forward_graph_str=aot_forward_graph_str, + aot_backward_graph_str=aot_backward_graph_str, + min_cut_info_str=min_cut_info_str, + runtime_metadata=runtime_metadata, + dispatch_wrappers=dispatch_wrappers, + maybe_subclass_meta=maybe_subclass_meta, + num_fw_outs_saved_for_bw=num_fw_outs_saved_for_bw, + indices_of_inps_to_detach=indices_of_inps_to_detach, + forward_time_taken_ns=forward_time_taken_ns, + backward_time_taken_ns=backward_time_taken_ns, + sanitized_aot_config=sanitized_aot_config, + guards_expr=guards_expr, + serialized_bw_module=serialized_bw_module, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/codegen.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/codegen.py new file mode 100644 index 0000000000000000000000000000000000000000..d35f98523c50c23487a06cfe47cbbfcbcaf21a63 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/codegen.py @@ -0,0 +1,240 @@ +""" +Generic codegen for AOTAutograd runtime wrappers. + +PySourceBuilder accumulates indented Python source together with the globals the +generated code closes over and a fresh-name counter; _compile_and_exec_source is +the single chokepoint that turns generated source into a live function (logging it +as a structured-trace artifact for tlparse and giving it a stable traceback +filename). Every runtime-wrapper codegen routes through it -- the subclass wrappers +in subclass_codegen.py and the orchestration / alias / mutation epilogues in +runtime_wrappers.py -- so it knows nothing about any particular wrapper kind. This +module also hosts the optional thread-local capture sink that records each codegen'd +wrapper's source, which AOT-to-Python lowering (to_standalone_python.py) uses to +compose the wrappers into one standalone module. Kept as a leaf module (stdlib + +torch only) so it is safe to import anywhere. +""" + +import contextlib +import functools +import logging +import threading +from collections.abc import Callable, Iterator + +import torch +from torch.utils._indented_buffer import IndentedBuffer + + +log = logging.getLogger(__name__) + + +class PySourceBuilder(IndentedBuffer): + """Builds indented Python source for compile/exec, along with the globals + the generated code closes over and a monotonic fresh-name counter. + + Inherits the indentation primitive (``writeline``/``indent()``) from + IndentedBuffer: body lines are written WITHOUT leading whitespace and + indentation is managed by the ``indent()`` context manager so call sites + read as plain code. This subclass adds the exec layer (globals binding, + fresh-name generation, and ``build()`` via _compile_and_exec_source). Pass + ``fn_name``/``artifact_name`` to emit a ``def`` header and enable + ``build()``. + """ + + def __init__( + self, + fn_name: str | None = None, + *, + args: str = "args", + artifact_name: str | None = None, + ) -> None: + super().__init__() + self.globals: dict[str, object] = {} + self._name_counter: int = 0 + self._fn_name = fn_name + self._artifact_name = artifact_name + if fn_name is not None: + self.writeline(f"def {fn_name}({args}):") + + def emit(self, line: str, indent: int = 1) -> None: + """Append one line at an explicit absolute indent level. + + Convenient for recursive generators that thread an indent depth instead + of nesting indent() context managers. + """ + saved, self._indent = self._indent, indent + try: + self.writeline(line) + finally: + self._indent = saved + + def fresh_name(self, prefix: str) -> str: + name = f"{prefix}_{self._name_counter}" + self._name_counter += 1 + return name + + def add_global(self, name: str, value: object) -> str: + """Bind a live object into the exec globals under ``name``, by reference.""" + self.globals[name] = value + return name + + def bind(self, **values: object) -> None: + """Bind live objects into the exec globals by keyword, by reference.""" + self.globals.update(values) + + def bind_value(self, prefix: str, value: object) -> str: + """Bind a value under a fresh unique name and return that name.""" + return self.add_global(self.fresh_name(prefix), value) + + def getvalue(self) -> str: + # Join without a trailing newline (unlike IndentedBuffer.getvalue). + if not all(isinstance(li, str) for li in self._lines): + raise AssertionError(f"expected all lines to be str, got {self._lines}") + return "\n".join(self._lines) # type: ignore[arg-type] + + def build( + self, *, wrapped_fn: Callable[..., object] | None = None + ) -> Callable[..., object]: + if self._fn_name is None or self._artifact_name is None: + raise AssertionError("build() requires fn_name and artifact_name") + return _compile_and_exec_source( + self.getvalue(), + self.globals, + self._fn_name, + self._artifact_name, + wrapped_fn=wrapped_fn, + ) + + +# Optional sink for the source of every runtime-wrapper function codegen'd via +# ``_compile_and_exec_source``. When a sink is installed (see +# ``capture_generated_sources``), each codegen'd wrapper appends a +# ``GeneratedSource`` to it; this lets AOT-to-Python lowering compose the wrappers +# into one standalone module. Thread-local (NOT a process global) so a concurrent +# compile on another thread cannot splice its wrappers into this capture -- and, +# conversely, so an unrelated concurrent compile on another thread is never mistaken for +# offloaded capture work and aborted (``_compile_and_exec_source`` runs on EVERY +# AOTAutograd compile, not just this one). Absent (zero overhead, no behavior change) +# during ordinary compilation. Mirrors the threading.local used by +# _saved_tensor_hook_context in graph_compile.py. +_capture_tls = threading.local() + + +def _current_capture_sink() -> "list[GeneratedSource] | None": + return getattr(_capture_tls, "sink", None) + + +class GeneratedSource: + """One codegen'd runtime-wrapper function: its source, the exec'd function + object, and the globals it closes over (which include the inner ``compiled_fn`` + it chains to, plus any baked metadata). The function object lets a composer wire + cross-wrapper references by identity. Recorded by ``_compile_and_exec_source`` + when capture is active. + + ``globals_dict`` is a PRE-EXEC snapshot of the declared closure globals: it does + NOT contain the interpreter ``__builtins__`` that exec() would otherwise inject, + so the standalone composer can reconstruct every entry as source without having + to special-case ``__builtins__``.""" + + def __init__( + self, + artifact_name: str, + fn_name: str, + source: str, + globals_dict: dict[str, object], + fn: object, + origin_id: int | None = None, + ) -> None: + self.artifact_name = artifact_name + self.fn_name = fn_name + self.source = source + self.globals_dict = globals_dict + self.fn = fn + # Identity of the TracingContext this wrapper was codegen'd under. The capture + # sink is duration-scoped over one inductor compile, so a re-entrant on-thread + # lowering that codegen's into THIS sink during that window would append its + # wrappers too; the composer filters by this id, which separates such a foreign + # lowering when it ran under a DISTINCT TracingContext. A same-context re-entrant + # lowering shares this id and is caught instead by the composer's + # orchestration-count guard. + self.origin_id = origin_id + + +@contextlib.contextmanager +def capture_generated_sources(into: "list[GeneratedSource]") -> "Iterator[None]": + """Within this context, record every codegen'd runtime-wrapper function's source + into ``into`` (in codegen order). A no-op when not entered. + + THREADING: the sink is thread-local, so every wrapper captured into ``into`` must be + codegen'd ON THIS THREAD. There is deliberately NO cross-thread tripwire here: a + process-global owner check would abort an unrelated concurrent compile on another + thread, since ``_compile_and_exec_source`` runs on every AOTAutograd compile and is not + serialized against this capture. If a future change offloads wrapper codegen to a + worker thread, those wrappers are simply not captured; a forward that loses its + orchestration wrapper this way is rejected by the composer (it requires exactly one), + so the common case fails loudly rather than emitting an empty module. + """ + prev = _current_capture_sink() + _capture_tls.sink = into + try: + yield + finally: + _capture_tls.sink = prev + + +def _compile_and_exec_source( + source: str, + globals_dict: dict[str, object], + fn_name: str, + artifact_name: str, + wrapped_fn: Callable[..., object] | None = None, +) -> Callable[..., object]: + """Compile generated source, exec it, and return the named function. + + If wrapped_fn is provided, applies functools.update_wrapper so that + __wrapped__ and __dict__ (e.g. _fx_graph_cache_key) propagate to the + generated function. + """ + if log.isEnabledFor(logging.DEBUG): + log.debug("Generated %s:\n%s", artifact_name, source) + + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": artifact_name, + "encoding": "string", + }, + payload_fn=lambda: source, + ) + + # Use a path under torch/_functorch/ so the code object is recognized by + # dynamo's MOD_SKIPLIST. The eval frame hook stays active during the entire + # torch.compile(fn)(*args) call (to handle graph breaks and resume functions), + # so codegen'd functions called during backward get intercepted even though + # no tracing is active. A real path makes them skip automatically. + code = compile(source, f"{__file__}:codegen({artifact_name})", "exec") + local_dict: dict[str, object] = {} + # exec() mutates ``globals_dict`` in place, injecting ``__builtins__`` (and any + # name the source binds at module scope). When capturing, snapshot the declared + # closed-over names BEFORE that happens so the captured GeneratedSource holds only + # the intended closure globals -- not the post-exec dict with the interpreter's + # ``__builtins__`` -- which is what the standalone composer reconstructs as source. + sink = _current_capture_sink() + captured_globals = dict(globals_dict) if sink is not None else globals_dict + exec(code, globals_dict, local_dict) + fn = local_dict[fn_name] + if wrapped_fn is not None: + functools.update_wrapper(fn, wrapped_fn) # type: ignore[arg-type] + + if sink is not None: + # Tag with the current TracingContext identity so the composer can drop any + # wrapper a re-entrant lowering appended during the capture window (see the + # origin_id note on GeneratedSource). + ctx = torch._guards.TracingContext.try_get() + origin_id = id(ctx) if ctx is not None else None + sink.append( + GeneratedSource( + artifact_name, fn_name, source, captured_globals, fn, origin_id + ) + ) + + return fn # type: ignore[return-value] diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/collect_metadata_analysis.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/collect_metadata_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..d7c298170cec45ace0e5597a87763fa90e396430 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/collect_metadata_analysis.py @@ -0,0 +1,880 @@ +from __future__ import annotations + + +""" +This module is one of the analysis modules - it takes as input a function or graph +and some preexisting properties, and returns some data that is useful for deciding +how to further proceed with compilation or construct runtime wrappers. + +In particular, the analysis here constructs view and mutation metadata from running +a functionalized version of the graph under compilation. +""" + +import collections +import contextlib +import logging +from typing import Any, TYPE_CHECKING + +import torch +import torch.utils._pytree as pytree +from torch import Tensor +from torch._guards import detect_fake_mode +from torch._library.opaque_object import is_custom_class +from torch._logging import getArtifactLogger +from torch._subclasses.functional_tensor import FunctionalTensor, FunctionalTensorMode +from torch._subclasses.meta_utils import safe_is_leaf +from torch.fx.experimental.proxy_tensor import disable_autocast_cache +from torch.fx.experimental.symbolic_shapes import is_concrete_int +from torch.multiprocessing.reductions import StorageWeakRef +from torch.utils._python_dispatch import ( + is_traceable_wrapper_subclass, + transform_subclass, +) + +from .descriptors import ( + AOTInput, + AOTOutput, + InputMutationAOTOutput, + IntermediateBaseAOTOutput, + PlainAOTOutput, + TangentAOTInput, +) +from .functional_utils import ( + are_all_mutations_hidden_from_autograd, + are_all_mutations_under_no_grad_or_inference_mode, + from_fun, + has_data_mutation, + has_metadata_mutation, + MetadataKey, + to_fun, + ViewMetaSequence, + was_inductor_storage_resized, + was_shallow_copy_data, +) +from .schemas import ( + InputAliasInfo, + MemoryFormatMeta, + MutationType, + OutputAliasInfo, + OutputType, + ViewAndMutationMeta, +) +from .subclass_utils import create_subclass_meta +from .utils import _get_autocast_states, KNOWN_TYPES, simple_wraps, strict_zip + + +if TYPE_CHECKING: + from collections.abc import Callable + +zip = strict_zip + +log = logging.getLogger(__name__) +static_input_logger = getArtifactLogger("torch._dynamo", "cudagraph_static_inputs") + + +# Note [Tangents memory format] +# We assume tangents memory format to be similar to corresponding output's memory_format. +# The idea is that we are technically making a guess about the strides of our tangents, +# while we trace out the joint. +# If runtime specified tangents will not have the same memory format as predicted traced tangents, +# we coerce them at runtime to traced tangents memory format. + + +# Coercing and collecting traced tangents memory format in one recursive traversal +def coerce_tangent_and_suggest_memory_format( + x: Tensor, +) -> tuple[Any, MemoryFormatMeta | list[Any] | None, bool]: + updated = False + if not isinstance(x, Tensor): + return x, None, updated + + out = x.detach() + + is_subclass = is_traceable_wrapper_subclass(out) + + memory_format = MemoryFormatMeta.from_tensor(out) + + # pyrefly: ignore [missing-attribute] + if memory_format.memory_format is not None: + was = out + # pyrefly: ignore [bad-argument-type] + out = out.contiguous(memory_format=memory_format.memory_format) + updated = was is not out + + # For subclass we keep memory format of outer strides at the beginning of the list + out_memory_format = [memory_format] if is_subclass else memory_format + + # Note [Tangents memory format, Part 2] + # In the same way that "what strides do we assigns to our tangents" is a question + # that we can not answer (and therefore have to guess) as we trace the backward ahead-of-time, + # The same applies to any tensor subclass metadata, when we have tangents that are subclasses. + # To handle this situation, we have two new methods that a tensor subclass can implement: + # (1) __coerce_tangent_metadata__(self) + # Given a subclass with "non-standard" metadata, turn it into a new subclass with "normal" metadata. + # The main example here is a DTensor with the "_Partial" placement. + # If we have a forward output with a _Partial placement, and corresponding tangent + # with a Replicate/Shard placement, we have no way to convert the tangent "back" to a _Partial placement. + # This method lets us avoid the problem entirely by allowing subclasses to ensure that we can never + # have a tangent with "problematic" metadata, that we cannot convert to. + # (1) __coerce_same_metadata_as_tangent__(self, metadata) + # Given a subclass, and a target differing metadata, + # convert self to have the same metadata as the target. + # With DTensor being the main example, we can use this to convert a DTensor with a Replicate() + # placement into one with a Shard() placement, in the case that we "guessed wrong", + # and traced tangents with a Shard() placement at compile time. + # + if is_subclass and hasattr(out, "__coerce_tangent_metadata__"): + out = out.__coerce_tangent_metadata__() # type: ignore[attr-defined] + + if is_subclass: + # pyrefly: ignore [missing-attribute] + attrs = out.__tensor_flatten__()[0] + + for attr in attrs: + elem = getattr(out, attr) + ( + new_elem, + new_elem_memory_format, + elem_updated, + ) = coerce_tangent_and_suggest_memory_format(elem) + # pyrefly: ignore [missing-attribute] + out_memory_format.append(new_elem_memory_format) + if elem_updated: + setattr(out, attr, new_elem) + + return out, out_memory_format, updated + + +# This is a version of functionalization that is specifically designed +# for the AOTAutograd use case. +# +# Unlike functorch's variant, this doesn't use the functorch level system, +# instead it directly uses PyTorch's conventional dispatcher to hit the +# functionalization key. In particular, this means that FunctionalTensorWrapper +# can have autograd data stored directly on it. +# +# In typical AOTAutograd usage, the dispatch key order will look like: +# +# Autograd - Functionalization ~~~~> Proxy Mode - Fake Tensor +# outer tensor inner tensor +# +# Returns: +# - ViewAndMutationMeta, telling us metadata about the inputs and outputs, and +# The list of outputs from the forward, but **only** the outputs that we need +# to pass in as tangents into the backward. +# Specifically, aliased outputs from the forward get regenerated, and don't participate +# in the compiled backward function. +def run_functionalized_fw_and_collect_metadata( + f: Callable[..., Any], + *, + flat_args_descs: list[AOTInput], + keep_input_mutations: bool, + # Note: this is guaranteed to be set when running under dynamo + static_input_indices: list[int] | None = None, + pre_dispatch: bool = False, +) -> Callable[..., ViewAndMutationMeta]: + memo: dict[Tensor, Tensor] = {} + + # TODO: see if we can rewrite this to be more accurate using + # overload + def _to_fun(t: object) -> object: + if isinstance(t, Tensor): + if t in memo: + return memo[t] + r = to_fun(t) + memo[t] = r + return r + else: + return t + + @simple_wraps(f) + def inner(*flat_args: Any) -> ViewAndMutationMeta: + # This function is meant to be run with the forward, which expects a flat list of tensor/symint/other args. + if not all( + isinstance(a, tuple(KNOWN_TYPES)) or is_custom_class(type(a)) + for a in flat_args + ): + raise AssertionError("all flat_args must be KNOWN_TYPES or opaque types") + + input_info: list[InputAliasInfo] = [] + output_info: list[OutputAliasInfo] = [] + + prior_grad_enabled = torch.is_grad_enabled() + prior_autocast_states = _get_autocast_states() + + # See Note [Disabling Functionalize TLS Above Python Functionalization] + disable_above = torch._C._ExcludeDispatchKeyGuard( + torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize) + ) + + # It doesn't matter if we run this under predispatch or not because it is + # only for figuring out metadata + mode = FunctionalTensorMode( + _allow_token_discovery=True, + _keep_input_mutations=keep_input_mutations, + ) + suppress_pending = contextlib.nullcontext() + fake_mode = detect_fake_mode() + if fake_mode and (shape_env := fake_mode.shape_env): + suppress_pending = shape_env.ignore_fresh_unbacked_symbols() + with disable_above, mode, suppress_pending, disable_autocast_cache(): + # precondition: The passed in function already handles unflattening inputs + flattening outputs + flat_f_args = pytree.tree_map(_to_fun, flat_args) + flat_f_args_descs = flat_args_descs + flat_f_outs = f(*flat_f_args) + + # Assert that f does NOT have an AOTOutputs in it, easy mistake to + # make! You need to drop the second output before calling this + # function + if pytree.tree_any(lambda x: isinstance(x, AOTOutput), flat_f_outs): + raise AssertionError( + f"{f} returned AOTOutput when it shouldn't. Did you remember to wrap the " + "function with without_output_descs before passing it here?" + ) + + # NB: this is just to setup the input descriptors, we will + # recreate these descriptors (with the same convention!) when we + # actually do the trace + flat_f_outs_descs = [PlainAOTOutput(i) for i in range(len(flat_f_outs))] + + # We didn't do any tracing, so we don't need to process the + # unbacked symbols, they will just disappear into the ether. + # Also, prevent memoization from applying. + if fake_mode: + fake_mode.epoch += 1 + fake_mode.reset_nt_tensor_id_counter() + + if prior_autocast_states != _get_autocast_states(): + raise RuntimeError( + "AOTAutograd does not support tracing graphs that mutate the autocast state. " + "Dynamo will only insert autocast context managers (e.g. with torch.autocast(..)) into the graph, " + "which will unwind all of their mutations to autocast state before the graph exits. " + "If you encounter this error while using torch.compile, please file a bug." + ) + + # Inspect the state of the input tensor functional wrapper to detect input mutation info + # If inp[i] has a metadata-only mutation, then maybe_inputs_with_mutated_metadata[i] contains the updated version + for arg, f_arg in zip(flat_args, flat_f_args): + mutates_data = has_data_mutation(f_arg) + mutates_metadata = has_metadata_mutation( + f_arg, arg, check_only_storage_mutation=False + ) + mutates_storage_metadata = has_metadata_mutation( + f_arg, arg, check_only_storage_mutation=True + ) + mutations_hidden_from_autograd = are_all_mutations_hidden_from_autograd( + f_arg + ) + mutations_under_no_grad_or_inference_mode = ( + mutates_data + and are_all_mutations_under_no_grad_or_inference_mode(f_arg) + ) + mutation_inductor_storage_resize = was_inductor_storage_resized(f_arg) + + if mutates_storage_metadata: + mutates_data = False + + requires_grad = isinstance(f_arg, torch.Tensor) and f_arg.requires_grad + + input_info.append( + InputAliasInfo( + is_leaf=isinstance(arg, Tensor) and safe_is_leaf(arg), + mutates_data=mutates_data, + mutates_metadata=mutates_metadata, + mutations_hidden_from_autograd=mutations_hidden_from_autograd, + mutates_storage_metadata=mutates_storage_metadata, + mutation_is_shallow_copy_data=was_shallow_copy_data(f_arg), + mutations_under_no_grad_or_inference_mode=mutations_under_no_grad_or_inference_mode, + mutation_inductor_storage_resize=mutation_inductor_storage_resize, + requires_grad=requires_grad, + keep_input_mutations=keep_input_mutations, + ) + ) + + # If a function involves creating a tensor, and returning a view of it, such that its _base is the intermediate, + # We need to make sure our graph returns the _base as a graph output, and we manually recreate the view + # to return to the user. Why? The backend compiler is free to (incorrectly) not set requires_grad + # on the base tensor, but we are obligated to properly set requires-gradness on the real output. + + inp_storage_refs = { + StorageWeakRef(inpt.untyped_storage()): idx + for idx, inpt in enumerate(flat_f_args) + if isinstance(inpt, Tensor) + } + + # We need inp tensor id's to be able to tell if an outputs **are** inputs. + inp_tensor_ids = {id(inpt) for inpt in flat_f_args if isinstance(inpt, Tensor)} + # We need output tensor id's to tell if any output._base` attributes **are** other outputs. + # (This is also a dict because we need to know that output's index, so we can regenerate + # the alias from it). + out_tensor_ids = {id(o): i for i, o in enumerate(flat_f_outs)} + + # Keep track of which outputs alias other outputs + out_tensor_alias_counts: collections.defaultdict[StorageWeakRef | None, int] = ( + collections.defaultdict(int) + ) + # This tells us, for a given group of outputs that alias each other, + # whether they e.g. all came from an unbind call + num_aliased_tensors_that_are_multi_output_views: collections.defaultdict[ + StorageWeakRef | None, int + ] = collections.defaultdict(int) + + out_storage_to_metadata_key_to_tensors: collections.defaultdict[ + StorageWeakRef | None, + collections.defaultdict[MetadataKey, set[torch.Tensor]], + ] = collections.defaultdict(lambda: collections.defaultdict(set)) + + curr_storage = None + for o in flat_f_outs: + if isinstance(o, torch.Tensor): + curr_storage = StorageWeakRef(o.untyped_storage()) + out_tensor_alias_counts[curr_storage] += 1 + # Note: [AOTAutograd: differentiable outputs that alias each other from a multi-output view call] + # This is an optimization on top of the "alias of intermediates" logic, + # which you can read more about under Note [AOT Autograd: outputs aliasing inputs or intermediates!] + # + # Before describing the optimization: this is important for AOTAutograd to have good + # perf around, multi-output views. HOWEVER: + # - There is a more generic change to AOTAutograd that we'd like to make, that subsumes this case, + # around using pre-dispatch tracing to partition out a graph so we can faithfully replay all + # views without having to regenerate them at runtime. + # - It's loosely described in this doc (more details will be added soon): + # https://docs.google.com/document/d/1DlfFq8TKbuAn2zyJxLfoW-X1qkkm5PLdHFtySo03QAk/edit + # - Once that change lands, we should just rip out this "optimization", since: + # (1) It will be fully unnecessary + # (2) Although it is only a few lines of code, it is a bit difficult to reason about + # its correctness with the autograd engine in all cases. + # + # + # What is this optimization? Consider the below case: + # def f(x): + # intermediate = x.mul(2) + # # x and intermediate here require grad + # o1, o2, ... o10 = intermediate.unbind(-1) + # return intermediate, o1, o2, ... o10 + # Now, the "intermediate base" handling in AOTAutograd implies that we must do the following: + # (1) return "intermediate as an extra output of the compiled graph + # (2) regenerate each aliased output off of "intermediate", **outside** of the autograd.Function. + # The reason AOTAutograd ordinarily does this is for safety: the autograd engine needs to know + # that o1 through o10 are all aliased, and if we blindly return o1 through o10 from the autograd.Function, + # this information will be hidden. + # In particular, mutating one alias might require autograd to update autograd metadata on the other aliases + # (like their grad_fn, for example, when the autograd engine needs to do view-replay). + # + # However, intermediate_base logic can be bad for backward performance (we sometimes generate + # as_strided calls during the intermediate base logic, which can have a slow backward formula). + # Is it possible to find a set of conditions where it is **safe** to hide the output aliasing from autograd? + # + # For a set of outputs of the graph that alias each other, o_1...o_k, consider: + # (1) They came from the same multi-output view op, e.g. o_1, ..., o_k = intermediate.unbind(0) + # (2) If there are any other aliases of o_1 through o_k (in the example above, intermediate), + # **at most** 1 can escape from the graph (e.g. there is not some other graph input/output + # o_other, that aliases these outputs) + # (3) o_1...o_k all require_grad, they all share the same ._base, and their ._base requires grad. + # This condition is important because it's what causes slowness in the intermediate_base + # codepath of aot_autograd. Ordinarily, o_1...o_k would all get a grad_fn, and + # aot_autograd's view-replay might give each output an AsStridedBackward as its grad_fn. + # "K" AsStridedBackward calls will be *much* slower than a single UnbindBackward. + # In this setup, is it possible to mutate one of the outputs o_i in a way that would affect the autograd meta + # of the other aliases? + # + # Claim: No! Consider a few example (which I'm pretty sure cover all cases of mutation w.r.t. autograd): + # (a) What happens if we mutate any of o_1 through o_k directly? + # Autograd raises an error: + # "RuntimeError: Output 0 of UnbindBackward0 is a view and is being modified inplace. This view is + # the output of a function that returns multiple views. Such functions do not allow the output + # views to be modified inplace. You should replace the inplace operation by an out-of-place one." + # (b) What if we take a view of o_k and mutate it, o_k.view(o_k.shape).mul_(2)? + # Autograd raises the same error- the "multi-output-view"ness of an alias propagates to future views. + # (c) What if we mutate o_k under no_grad? + # Autograd raises the same error + # (d) What if we detach and mutate, e.g. o_k.detach().mul_(2)? + # Autograd allows this, *but* autograd updates all alias's grad_fn's to be error functions when accessed. + # Autograd raises the same error + # (e) What if we try to mutate another alias of o_1...o_k, that was **not** created from a multi-output view? + # We promised that there is at most **one** such alias, e.g. intermediate in the example above. + # You can mutate intermediate, but in eager mode this will change the grad_fn of o_1...o_k + # to be error fn's. + # Since intermediate was the *only* non-multi-output-alias, there are no other aliases + # of `intermediate` around that were produced by the compiled fn and have a valid grad_fn. + # + # Coming back to this optimization: + # Given that it is not possible for mutating one of these aliases to affect the autograd metadata of another alias + # without causing an error in eager mode, we will simple hide the aliasing from autograd during torch.compile + # if all of the above conditions are met. + # This has the slight downside that it's possible to write some "bad" code that autograd will raise an error on + # in eager but fail to during torch.compile, but it has the benefit that this code has much better performance. + # NOTE: if and when we eventually update AOTAutograd to do the "view graph slicing" defined here: + # https://docs.google.com/document/d/1DlfFq8TKbuAn2zyJxLfoW-X1qkkm5PLdHFtySo03QAk/edit, + # then this optimization will probably matter less and might be ok to remove. + is_cur_tensor_multi_out_view = isinstance( + o, FunctionalTensor + ) and torch._functionalize_is_multi_output_view( # type: ignore[attr-defined] + o.elem + ) + if is_cur_tensor_multi_out_view: + num_aliased_tensors_that_are_multi_output_views[curr_storage] += 1 + if o.requires_grad: + out_storage_to_metadata_key_to_tensors[curr_storage][ + MetadataKey.make(o) + ].add(o) + + # maps the id of an intermediate base to its index in the output of the compiled forward + intermediate_base_tensor_id_to_output_idx: dict[int, int] = {} + intermediate_bases: list[torch.Tensor] = [] + intermediate_bases_descs: list[AOTInput] = [] + # Why Do We Care If Storage Changed? + # It's important to understand the implications of storage changes in complex scenarios. Take this example: + # + # def f(x): + # x_storage = x.untyped_storage() + # non_leaf_tensor = torch.ones(4, requires_grad=True).clone() + # + # # Using no_grad() and _unsafe_preserve_version_counter to simulate the .data = operation + # with torch.no_grad(), torch.autograd._unsafe_preserve_version_counter(x): + # x.set_(non_leaf_tensor.untyped_storage()) + # + # out = x.view(-1) + # + # # Restoring x to its original storage, again simulating .data = operation + # with torch.no_grad(), torch.autograd._unsafe_preserve_version_counter(x): + # x.set_(x_storage) + # + # return out + # + # In this scenario, 'x' and 'out' have different shapes and are stored at different memory addresses, aka no aliasing. + # However, due to how set_() and more specifically, set is functionalized, is defined to preserve eager semantics, + # the autograd engine mistakenly assumes that 'x' and 'out' are aliased, treating 'x' as 'out._base'. + # This misinterpretation leads to an 'alias_of_input' flag, causing an unnecessary as_strided() call to be generated, + # which could lead to issues later in the code. + for o, desc in zip(flat_f_outs, flat_f_outs_descs): + functional_tensor_storage_changed = isinstance( + o, FunctionalTensor + ) and torch._functionalize_was_storage_changed( # type: ignore[attr-defined] + o.elem + ) + curr_storage = ( + None + if not isinstance(o, torch.Tensor) + else StorageWeakRef(o.untyped_storage()) + ) + outs_with_identical_metadata_that_require_grad: list[torch.Tensor] = ( + [] + if not isinstance(o, Tensor) + else [ + curr + for curr in out_storage_to_metadata_key_to_tensors[curr_storage][ + MetadataKey.make(o) + ] + if o is not curr + ] + ) + + # See Note [Accessing .grad_fn on FunctionalTensor] + # In-place operations on views will trigger a lazy rebase of the autograd graph; + # this runs during access to the .grad_fn. The rebase logic will invoke view ops + # on FunctionalTensors, so we must enable a FunctionalTensorMode here to ensure + # these op calls succeed. + grad_fn = None + if isinstance(o, Tensor): + with FunctionalTensorMode(): + grad_fn = o.grad_fn + + is_result_of_custom_autograd_fn = False + # Need to check for both custom cpp (CppFunction) and python (BackwardCFunction) + # autograd fns + if type(grad_fn).__name__ == "CppFunction": + is_result_of_custom_autograd_fn = True + if isinstance(grad_fn, torch.autograd.function.BackwardCFunction): + is_result_of_custom_autograd_fn = True + + if not isinstance(o, Tensor): + output_type = OutputType.non_alias + base_idx = None + elif ( + curr_storage in inp_storage_refs + and grad_fn is not None + and is_result_of_custom_autograd_fn + ): + output_type = OutputType.custom_function_view + base_idx = None + elif ( + curr_storage in inp_storage_refs + and not functional_tensor_storage_changed + ): + # pyrefly: ignore [bad-index, index-error] + base_idx = inp_storage_refs[curr_storage] + is_input_tensor = id(o) in inp_tensor_ids + num_aliased_outs = out_tensor_alias_counts[curr_storage] + num_multi_output_view_outs = ( + num_aliased_tensors_that_are_multi_output_views[curr_storage] + ) + num_aliased_outs_that_are_not_multi_output_views = ( + num_aliased_outs - num_multi_output_view_outs + ) + if ( + grad_fn is not None + and num_aliased_outs_that_are_not_multi_output_views == 0 + ): + # See Note: [AOTAutograd: differentiable outputs that alias each other from a multi-output view call] + # In particular, given: + # def f(x): + # return list(x.unbind(0)) + # The main reason we ordinarily try to regenerate these output aliases outside of the + # compiled autograd.Function is because if any of the outputs are later mutated, + # autograd needs to perform view-replay to regenerate them. + # However, autograd does not allow users to mutate multi-output views + # in any way that can change the autograd metadata of other aliases. + # So we hide this aliasing from autograd here. + log.debug( + "Encountered AOTAutograd case: differentiable outputs that \ +alias each other from a multi-output view call" + ) + output_type = OutputType.non_alias + elif is_input_tensor: + output_type = OutputType.is_input + else: + output_type = OutputType.alias_of_input + elif functional_tensor_storage_changed and id(o) in inp_tensor_ids: + # When there is a set_() on an input, we cannot rely on checking storages + # to detect if we are returning an input (since the inputs storage is different) + if curr_storage is None: + raise AssertionError("curr_storage must not be None") + base_idx = inp_storage_refs[curr_storage] + output_type = OutputType.is_input + + # We only need to handle the intermediate base case when both + # the intermediate base and the output require gradients. + # See Note [AOT Autograd: outputs aliasing inputs or intermediates!] + elif o._base is not None and o.requires_grad and o._base.requires_grad: + num_aliased_outs = out_tensor_alias_counts[curr_storage] + num_multi_output_view_outs = ( + num_aliased_tensors_that_are_multi_output_views[curr_storage] + ) + num_aliased_outs_that_are_not_multi_output_views = ( + num_aliased_outs - num_multi_output_view_outs + ) + # Note: [AOTAutograd: differentiable outputs that alias each other from a multi-output view call] + if ( + out_tensor_alias_counts[curr_storage] == 1 + or num_aliased_outs_that_are_not_multi_output_views <= 1 + ): + # Note [Intermediate Bases Optimization] + # Normally if we have an output that aliases an intermediate, + # we need to add the extra "intermediate base" logic further down + # to prevent autograd from yelling at us if the user later tries to + # mutate that output. + # However, the common case here is if we have an output that aliases an intermediate, + # but doesn't alias any other outputs. + # In that case, autograd shouldn't have to worry about the aliasing at all + # (if that output is mutated, there are no other live aliases for autograd to worry about). + # The "intermediate bases" can hurt inductor perf by forcing more variables to become outputs. + # So as an optimization, we won't do intermediate base handling in this case. + # Instead, we'll hide the aliasing from autograd using aten._unsafe_view(). + if ( + out_tensor_alias_counts[curr_storage] != 1 + and num_aliased_outs_that_are_not_multi_output_views <= 1 + ): + log.debug( + "Encountered AOTAutograd case: differentiable outputs that alias each other \ +from a multi-output view call" + ) + output_type = OutputType.unsafe_view_alias + base_idx = None + else: + # First, check if o's ._base is an existing output + maybe_existing_out_idx = out_tensor_ids.get(id(o._base)) + if maybe_existing_out_idx is not None: + # Special case where the output is an alias of a graph intermediate, but that intermediate + # is itself also a user output. + output_type = ( + OutputType.alias_of_intermediate_base_is_user_output + ) + base_idx = maybe_existing_out_idx + else: + # Next, check if o's ._base is an intermediate base that we already returned + maybe_existing_base_output_idx = ( + intermediate_base_tensor_id_to_output_idx.get(id(o._base)) + ) + if maybe_existing_base_output_idx is not None: + output_type = OutputType.alias_of_intermediate + base_idx = maybe_existing_base_output_idx + else: + # Otherwise, take o._base and explicitly return it as an output in the compiled graph + new_out_idx = len(intermediate_bases) + base_idx = new_out_idx + # Indicate to the logic later on (when we trace the joint) + # that this particular output should get it's ._base appended to the forward graph outputs + output_type = ( + OutputType.alias_of_intermediate_save_as_output + ) + intermediate_base_tensor_id_to_output_idx[id(o._base)] = ( + new_out_idx + ) + intermediate_bases.append(o._base) + # NB: The desc we picked here is guaranteed to be + # synchronized with the one in + # graph_capture_wrappers.py because we + # SPECIFICALLY notated this output as + # alias_of_intermediate_save_as_output + intermediate_bases_descs.append( + TangentAOTInput(IntermediateBaseAOTOutput(desc)) + ) + elif ( + # See https://github.com/pytorch/pytorch/issues/100348 for this case. + # This protects against the specific case where a user fn returns (output, output.detach()) + out_tensor_alias_counts[curr_storage] > 1 + and len(outs_with_identical_metadata_that_require_grad) > 0 + and not o.requires_grad + ): + # In theory we could use any of these tensors to regenerate the aliased outputs from, + # since they all alias each other and have identical metadata + out_alias = outs_with_identical_metadata_that_require_grad[0] + existing_out_idx = out_tensor_ids[id(out_alias)] + output_type = OutputType.alias_of_intermediate_base_is_user_output + base_idx = existing_out_idx + else: + output_type = OutputType.non_alias + base_idx = None + + if isinstance(o, torch.Tensor): + dynamic_dims = { + i for i, s in enumerate(o.shape) if not is_concrete_int(s) + } + else: + dynamic_dims = None + + # Save the current FunctionalTensor output. + # + # This will be used at runtime for reconstructing output views from + # their respective base tensors. + # + # The FunctionalTensor will be saved if one of the 2 conditions below + # is true: + view_meta_sequence = None + if ( + # 1. If the output_type is either of: + # (i) alias_of_intermediate; + # (ii) alias_of_intermediate_save_as_output; or + # (iii) alias_of_intermediate_base_is_user_output. + # + # No need to worry about in-place view operations here, since + # this functionalization step eliminates mutations. + # + # i.e. we have access to the actual base tensor, before the + # in-place operation was applied. + output_type + in ( + OutputType.alias_of_intermediate, + OutputType.alias_of_intermediate_save_as_output, + OutputType.alias_of_intermediate_base_is_user_output, + ) + ) or ( + # 2. If the output_type is alias_of_input, and no in-place view + # operation was run on the input (base tensor). + # + # In this case, we need to check for metadata mutation because + # the runtime explicitly reconstructs the inputs, before actually + # reconstructing the outputs. Due to in-place view operations, the + # fully reconstructed input may not be this output base tensor + # anymore. + output_type == OutputType.alias_of_input + and base_idx is not None + and not input_info[base_idx].mutates_metadata + ): + if isinstance(o, FunctionalTensor): + view_meta_sequence = ViewMetaSequence(o) + + requires_grad = isinstance(o, torch.Tensor) and o.requires_grad + out_info = OutputAliasInfo( + output_type=output_type, + raw_type=type(o), + base_idx=base_idx, + dynamic_dims=dynamic_dims, + requires_grad=requires_grad, + # A view created under no_grad() inherits requires_grad from + # its base but has no grad_fn and does not participate in + # differentiation. + requires_grad_for_backward=requires_grad + and (o._base is None or grad_fn is not None), + view_meta_sequence=view_meta_sequence, + ) + output_info.append(out_info) + + # See Note [AOT Autograd: Views to avoid tangents aliasing inputs] + def view_avoid_dupes_with_primals(t: object) -> object: + if isinstance(t, Tensor) and is_traceable_wrapper_subclass(t): + return transform_subclass( + t, lambda _, inner_t: view_avoid_dupes_with_primals(inner_t) + ) + if isinstance(t, Tensor): + return t.view(t.shape) + return t + + # This analysis function returns *only* the outputs that are meant to be tangents to the backwards. + # Anything that aliases (inputs returned in the fw due to metadata mutations, or outputs that alias inputs/intermediates) + # are *regenerated* later, and not used directly in the autograd graph + def _plain_fake_tensor_like_subclass(x: Any) -> torch.Tensor: + # pyrefly: ignore [bad-context-manager] + with detect_fake_mode(): + return torch.empty( + x.shape, dtype=x.dtype, device=x.device, layout=x.layout + ) + + def _is_subclass_mutated_input_tangent_always_subclass(inp: object) -> bool: + return ( + isinstance(inp, torch.nested._internal.nested_tensor.NestedTensor) + or torch._functorch.config.disable_guess_zero_tangent_for_mutated_input_subclass + ) + + f_input_tangents_pairs = [ + # Note: [AOTAutograd Tangent Subclassness for mutated inputs] + # Generally when creating tangents to trace with, we assume that tangents will have + # the same subclass-ness as their forward outs + # however: for tangents that correspond to input mutations, in practice it is more likely + # that these tangents will be plain tensors of zeros at runtime, so we tweak our guess + # to assume that these tangents should always be plaint tensors. + # Example: + # def f(x): + # x.mul_(2) + # return x + 1 + # out = f(x) + # out.sum().backward() + # In the above code, we will have a tangent "x_updated_tangent", + # which will be a plain tensor of zeros, *unless* x is used in some compute after executing f + # + # However, there are exceptions to this logic. If a view is created from mutated input and is used in backward, + # The tangent for this subclass input will be a subclass tensor. + # Example: + # def f(a, b): + # a.mul_(2) + # b.mul_(3) + # return b.view(b.shape), a + b + # a_out, b_out = f(..., Subclass) + # (a * b).sum().backward() + # + # We can not deduce it easily now, so introducing a debug config to be able to turn off this for specific cases. + # NJT guarantees to have its tangent as NJT, because it has dedicated integration in Autograd + # See torch/csrc/autograd/python_function.cpp, use_zeros_like. + ( + ( + _plain_fake_tensor_like_subclass(inp) + if is_traceable_wrapper_subclass(inp) + and not _is_subclass_mutated_input_tangent_always_subclass(inp) + else inp + ), + TangentAOTInput(InputMutationAOTOutput(inp_desc)), + ) + for inp, inp_desc, info in zip(flat_f_args, flat_f_args_descs, input_info) + if info.mutation_type == MutationType.MUTATED_OUT_GRAPH + and info.mutates_data + and info.requires_grad + ] + f_input_tangents, f_input_tangents_descs = ( + [x[0] for x in f_input_tangents_pairs], + [x[1] for x in f_input_tangents_pairs], + ) + + f_output_tangents_pairs = [ + (o, TangentAOTInput(desc)) + for o, info, desc in zip(flat_f_outs, output_info, flat_f_outs_descs) + if info.output_type + in [ + OutputType.non_alias, + OutputType.unsafe_view_alias, + OutputType.custom_function_view, + ] + and issubclass(info.raw_type, torch.Tensor) + and info.requires_grad_for_backward + ] + f_output_tangents, f_output_tangents_descs = ( + [x[0] for x in f_output_tangents_pairs], + [x[1] for x in f_output_tangents_pairs], + ) + + # intermediate bases are also included in the backward graph + f_tangents = f_input_tangents + f_output_tangents + intermediate_bases + f_tangents_descs = ( + f_input_tangents_descs + f_output_tangents_descs + intermediate_bases_descs + ) + + # TODO: I'm pretty sure you don't need a tree_map here + traced_tangents = pytree.tree_map(from_fun, f_tangents) + traced_tangents = pytree.tree_map( + view_avoid_dupes_with_primals, traced_tangents + ) + traced_tangents = [ + coerce_tangent_and_suggest_memory_format(tt)[0] + for i, tt in enumerate(traced_tangents) + ] + # NB: update this if the maps above ever change structure. + # Also, it might be helpful to add coercion information to the tangent desc! + traced_tangents_descs = f_tangents_descs + + nonlocal static_input_indices + static_input_indices = static_input_indices or [] + if torch._dynamo.compiled_autograd.in_compiled_autograd_region: + passed_indices = set(static_input_indices) + static_input_indices = [ + i + for i, arg in enumerate(flat_args) + if (isinstance(arg, torch.nn.Parameter) or i in passed_indices) + ] + + static_input_logger.debug( + "static input indices metadata analysis: %s", static_input_indices + ) + + f_mutated_inputs = [ + inp + for inp, info in zip(flat_f_args, input_info) + if info.mutation_type == MutationType.MUTATED_OUT_GRAPH + ] + # Build the full list of forward graph outputs so the subclass wrapping + # code knows exactly which graph outputs to wrap back into subclasses. + # Including intermediate_bases unconditionally is safe: they are only + # populated when outputs require grad (line ~539), so they are naturally + # empty during pure inference. In the "downgrade from training to + # inference" path, num_intermediate_bases > 0 is already gated behind + # `assert not req_subclass_dispatch` (aot_autograd.py), so the subclass + # wrapping code that consumes subclass_fw_graph_out_meta never sees them. + f_fw_graph_outs = [*f_mutated_inputs, *flat_f_outs, *intermediate_bases] + fw_graph_outs = pytree.tree_map(from_fun, f_fw_graph_outs) + + grad_enabled_mutation = None + if torch.is_grad_enabled() != prior_grad_enabled: + grad_enabled_mutation = torch.is_grad_enabled() + torch.set_grad_enabled( + prior_grad_enabled + ) # Restore the prior state after tracing it + log.debug( + ( + "grad_mode mutation encountered in graph. " + "Will emit mutation epilogue, to set grad_mode=%s" + ), + grad_enabled_mutation, + ) + + subclass_inp_meta = create_subclass_meta(flat_args) + subclass_fw_graph_out_meta = create_subclass_meta(fw_graph_outs) + subclass_tangent_meta = create_subclass_meta( + traced_tangents, count_symints=False, with_memory_format=True + ) + + metadata = ViewAndMutationMeta( + input_info=input_info, + output_info=output_info, + num_intermediate_bases=len(intermediate_bases), + keep_input_mutations=keep_input_mutations, + traced_tangents=traced_tangents, + traced_tangents_descs=traced_tangents_descs, + subclass_inp_meta=subclass_inp_meta, + subclass_fw_graph_out_meta=subclass_fw_graph_out_meta, + subclass_tangent_meta=subclass_tangent_meta, + grad_enabled_mutation=grad_enabled_mutation, + static_input_indices=static_input_indices, + tokens=mode._tokens, + ) + return metadata + + return inner diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/complex_decomposition.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/complex_decomposition.py new file mode 100644 index 0000000000000000000000000000000000000000..583e0addb15aac48ab5790861ef097f3523d982d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/complex_decomposition.py @@ -0,0 +1,147 @@ +""" +Graph pass to decompose complex-valued operations into real-valued operations. + +This pass runs AFTER functionalization, so the graph is purely functional (no +mutations, no aliasing). It retraces the graph with ComplexTensor dispatch active, +which decomposes each complex op into real-valued sub-ops. The graph signature +(input/output count and dtypes) is preserved: complex inputs get unpacked via +aten.real/aten.imag at the top, and complex outputs get repacked via aten.complex +at the bottom. +""" + +from __future__ import annotations + +from typing import Any, TYPE_CHECKING + +import torch +import torch.fx as fx +import torch.fx.traceback as fx_traceback +import torch.utils._pytree as pytree +from torch import Tensor +from torch._subclasses.complex_tensor import ComplexTensor, WrapComplexMode +from torch.fx.experimental.proxy_tensor import make_fx + + +if TYPE_CHECKING: + from collections.abc import Callable, Mapping + + from torch._ops import OpOverload + + +def _can_wrap(value: Any) -> bool: + return ( + isinstance(value, Tensor) + and value.dtype.is_complex + and not isinstance(value, ComplexTensor) + ) + + +def _maybe_wrap(value: Any) -> Any: + if _can_wrap(value): + return ComplexTensor(torch.real(value), torch.imag(value)) + return value + + +def _maybe_unwrap(value: Any) -> Any: + if isinstance(value, ComplexTensor): + return value.as_interleaved() + return value + + +def _has_complex(gm: fx.GraphModule, flat_args: list[Any]) -> bool: + for arg in flat_args: + if _can_wrap(arg): + return True + for node in gm.graph.nodes: + if node.op == "call_function": + val = node.meta.get("val") + if _can_wrap(val): + return True + return False + + +def _aliased_input_indices(op: torch._ops.OpOverload) -> list[int]: + schema = op._schema + ret_aliases = set() + idxs = [] + + for ret in schema.returns: + ret_alias = ret.alias_info + if ret_alias is None: + continue + ret_aliases.update(ret_alias.before_set) + + if len(ret_aliases) == 0: + return idxs + + for i, arg in enumerate(schema.arguments): + if arg.alias_info is None: + continue + if not arg.alias_info.before_set.isdisjoint(ret_aliases): + idxs.append(i) + + return idxs + + +def _collect_storage_aliases(node: fx.Node) -> set[fx.Node]: + seen: set[fx.Node] = set() + stack: list[fx.Node] = [node] + while stack: + n = stack.pop() + if n in seen: + continue + seen.add(n) + if not isinstance(n.target, torch._ops.OpOverload): + continue + idxs = _aliased_input_indices(n.target) + for idx in idxs: + src = n.args[idx] + if isinstance(src, fx.Node): + stack.append(src) + return seen + + +def _assert_no_incorrect_aliasing_mutation(gm: fx.GraphModule) -> None: + """ + In this function, we check that the compiled graph respects aliasing semantics. + + There are three cases in which this check fires: + 1. A complex tensor is mutated in place via an incorrect alias. + The ops that produce incorrect aliases are listed in `INCORRECT_ALIASING_OPS`. + 2. A complex input is mutated in place. This is not allowed because complex inputs + decompose to real and imaginary parts, which are made contiguous for performance. + Therefore, any complex input passed in does not alias the original tensor. + 3. A complex input aliases an output. This is not allowed as the input and output + tensors can't alias each other because of 2. + + In all three cases, we raise an error if possible incorrectness is detected. + """ + for n in gm.graph.nodes: + if ( + isinstance(n.target, torch._ops.OpOverload) + and n.target.overloadpacket == torch.ops.aten.copy_ + and n.args[0].meta["val"].dtype.is_complex + ): + raise RuntimeError( + "Mutating a complex tensor in place is not allowed in a `torch.compile` region." + ) + + +def decompose_complex_in_graph( + gm: fx.GraphModule, + flat_args: list[Any], + decompositions: Mapping[OpOverload, Callable[..., Any]] | None = None, +) -> fx.GraphModule: + if not _has_complex(gm, flat_args): + return gm + + _assert_no_incorrect_aliasing_mutation(gm) + + def wrapper(*args: Any) -> Any: + wrapped = tuple(_maybe_wrap(a) for a in args) + with WrapComplexMode(): + result = fx.Interpreter(gm).run(*wrapped) + return pytree.tree_map(_maybe_unwrap, result) + + with fx_traceback.preserve_node_meta(): + return make_fx(wrapper, decomposition_table=decompositions)(*flat_args) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/descriptors.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/descriptors.py new file mode 100644 index 0000000000000000000000000000000000000000..d1c47f64dacf1b8f4a96551637e9b9bebf3606e5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/descriptors.py @@ -0,0 +1,782 @@ +""" +AOTAutograd descriptors are a path-like data structure (similar to pytree +paths and sources) that describe the semantic meaning of an input/output to FX +graphs. Although you may know the input/output meaning at the top level of +the original function you traced, because we have many graph capture wrappers +that change the calling convention, it can be difficult to tell how these +correspond to the actual FX graph you get back, to say nothing about the extra +arguments/outputs for tangents, gradients, etc. Descriptors describe the meaning +of arguments. + +Examples +-------- + +Before we talk about the precise semantics, it's helpful to look at some +examples to get some intuition for the meaning of descriptors. Here are some +input descriptors you might find on the joint FX graph: + +* PlainAOTInput(idx=0) - the first input from the original callable, as is + +* ParamAOTInput(target="mod.weight") - the parameter with FQN mod.weight + +* TangentAOTInput(output=PlainAOTOutput(idx=1)) - the input tangent + corresponding to the gradients for the second output in the forward graph + +* ViewBaseAOTInput(base_of=PlainAOTInput(idx=0)) - it turned out the first + input was actually a (differentiable) view of a tensor which aliased with + another input tensor. We replaced this input with a single input for the + base of all of these inputs, replacing the original inputs (one of which is + mentioned in base_of). We would generate a GradAOTOutput for *this* input + (and not the original PlainAOTInputs!) If you have a joint graph where a + view base like this is undesirable, you can eliminate this by cloning + the views outside of the compiled region (assuming you aren't mutating this + tensor). + +* SubclassGetAttrAOTInput(base=AOTInput(idx=0), attr="inner") - this tensor + corresponds to the "inner" tensor from the tensor subclass that is at the + first index. In general, joint graphs from AOTAutograd never take tensor + subclasses as inputs; they are always unpacked into their constituent plain + tensor pieces; use the descriptors to identify the parts of the tensor that + are related. Note that this can be nested (if you have nested tensor + subclasses!) + +Here are some output descriptors you might find on the Joint FX graph: + +* PlainAOTOutput(idx=0) - the first output from the original forward function, + as is + +* GradAOTOutput(grad_of=PlainAOTInput(idx=1)) - the computed gradient for the + second input to the graph, an output of the backward graph + +* InputMutationAOTOutput(mutated_input=PlainAOTInput(idx=0)) - when the first + input is mutated, the new value to be copied into the first input of the + graph. Sometimes, these outputs can be elided and the ``copy_`` is done directly + in the graph (controlled by keep_input_mutations), but if the input + mutation must be differentiated through we always generate an output like this + +* IntermediateBaseAOTOutput(base_of=PlainAOTOutput(idx=0)) - if we return + multiple outputs which alias each other, we instead replace them with a single + output tensor representing the base of all the aliases. This output indicates + it is the base for /one/ of those original outputs. If this is undesirable in + the joint graph, clone all outputs before returning from the graph. + +* SubclassGetAttrAOTOutput(base=PlainAOTOutput(idx=0), idx="inner") - this + tensor corresponds to the inner tensor of the first original output which + is a tensor subclass. This and other subclass components of that output will + get repacked into a tensor subclass. + +High level semantics +-------------------- + +OK, let's formally define a descriptor. Intuitively, suppose we have:: + + def wrapped_graph(*args): + ret = graph(*in_transform(args)) + return out_transform(ret) + +Then the descriptor for input[i] to graph describes a function fin_i such that:: + + fin_i(args) == in_transform(args)[i] + +and the descriptor for output[j] from graph describes a function fout_j such that:: + + fout_j(out_transform(ret)) == ret[j] + +AKA input descriptors tell you how to get from outer inputs to inner inputs, +while output descriptors tell you how to get from outer outputs to inner +outputs (inverse data flow!) + +We haven't said anything about what these transformations actually do. There +are three major transformations AOTAutograd does (performed in this order): + +* View/mutation handling +* Autograd +* Subclasses + +So intuitively, descriptors are built like this: + +1. **PlainAOTInput, PlainAOTOutput.** + + We start off descriptors describing the exact inputs/outputs of the + original flattened user function. This user function is assumed to already + be flattened; you would chain on pytree KeyPaths to further describe where + in the pytree each input/output lived if you needed to deal with + unflattened functions: this can be done from userland on top of + descriptors, so the main descriptors mechanism doesn't handle it. + +2. **SyntheticBaseAOTInput, ViewBaseAOTInput, MetadataMutationAOTOutput, + InputMutationAOTOutput, IntermediateBaseAOTOutput** + + We deal with mutations and aliasing by removing duplicate PlainAOTInputs + and introduce some new artificial inputs/outputs. These inputs do not + have a straightforward correspondence to the original user inputs, but if + you are implementing a pass that doesn't care about the exact semantics of + inputs, you should handle all of these uniformly in the same way as regular + inputs. + +3. **TangentAOTInput, GradAOTOutput** + + We deal with autograd by introducing a tangent input for every + differentiable AOTOutput (including the new ones introduced above), and a + gradient output for every differentiable AOTInput (also including new ones + introduced above.) The arguments to these AOTInput/AOTOutput can ONLY be + the ones we already have above (from steps 1-2). As AOTAutograd does not + currently support double backwards, you never have tangents of grads or + vice versa (but in the future we could!) + +4. **SubclassGetAttrAOTInput, SubclassGetAttrAOTOutput, et al.** + + We deal with subclasses by introducing flattened inputs/outputs (including + potentially symbolic sizes/strides) for every AOTInput/AOTOutput that was a + subclass. As above, the arguments to these AOTInput/AOTOutput can ONLY be + the ones we have above (from steps 1-3). Recursive subclasses are + supported, so these descriptors can nest with each other (so descriptors + from step 4 are fair game as well.) + +5. **ForwardTokenAOTInput, ForwardTokenAOTOutput, BackwardTokenAOTInput, BackwardTokenAOTOutput.** + + Some extra token inputs/outputs get added, these are synthetic and are just here to + prevent DCE/reordering. + +The important thing about the pipeline is that descriptors can ONLY be +created from top-to-bottom. So for example, you can have:: + + SubclassGetAttrAOTInput(TangentAOTInput(PlainAOTOutput(...))) # OK + +As you can see that PlainAOTOutput -> TangentAOTInput -> +SubclassGetAttrAOTInput is consistent with the pipeline ordering), but you can +NEVER have:: + + TangentAOTInput(SubclassGetAttrAOTOutput(PlainAOTOutput(...)) # BAD + +This is inconsistent; we always do autograd BEFORE we process subclasses! + +Similarly, for example, this is illegal:: + + GradAOTOutput(SubclassGetAttrAOTInput(PlainAOTInput(...))) # BAD + +It is illegal because subclasses are handled *after* create joint during +wrapper construction. Instead, you would have:: + + SubclassGetAttrAOTOutput(GradAOTOutput(PlainAOTInput(...))) # OK + +This intuitively captures the fact that we always to autograd directly on the +subclass, rather than after desugaring the subclass into its inner tensors. + +Descriptor index +---------------- + +Here is a list of all AOTInput/AOTOutput, organized by how likely you need to +handle them: + +* AOTInput + + * Important: + + * PlainAOTInput (the primals!) + * ParamAOTInput + * TangentAOTInput + * SubclassGetAttrAOTInput et al. (if you use subclasses) + + * View related (can be eliminated by cloning inputs to graph; if you don't + eliminate them, make sure to handle pairing them with GradAOTOutput): + + * ViewBaseAOTInput + * SyntheticBaseAOTInput + + * Non-tensor, mostly just ignore them: + + * DummyAOTInput + * PhiloxForwardSeedAOTInput + * PhiloxForwardBaseOffsetAOTInput + * PhiloxBackwardSeedAOTInput + * PhiloxBackwardBaseOffsetAOTInput + * ForwardTokenAOTInput + * BackwardTokenAOTInput + +* AOTOutput + + * Important: + + * PlainAOTOutput + * GradAOTOutput + * SubclassGetAttrAOTOutput et al. (if you use subclasses) + + * More obscure (if not eliminated, make sure you handle pairing them with + TangentAOTInput): + + * InputMutationAOTOutput (can be eliminated if mutations are non-differentiable) + * IntermediateBaseAOTOutput (can be eliminated by cloning outputs of graph) + * MetadataMutationAOTOutput (uhh, just don't mutate metadata?) + + * Non-tensor, mostly just ignore them: + + * PhiloxUpdatedForwardOffsetAOTOutput + * PhiloxUpdatedBackwardOffsetAOTOutput + * ForwardTokenAOTOutput + * BackwardTokenAOTOutput + * DummyAOTOutput + +For convenience, we also have DifferentiableAOTInput and +DifferentiableAOTOutput to help you classify which inputs/outputs can be +wrapped by GradAOTOutput/TangentAOTInput (respectively), which are essentially +all tensor AOTInput/AOTOutput excluding the subclass descriptors. + +Implementation details +---------------------- + +The stylized view above is good for understanding how to interpret +descriptors, but the way that descriptors are generated in code is a bit more +complicated. Specifically, AOTAutograd is structured as a series of wrappers +on the original user function, which are composed together to form the final +function to trace. As a result of this, AOTAutograd ends up first building +the full AOTInputs for a function to be traced (as it builds the wrappers and +modifies the flat arguments to be compatible with the new input signature of +the wrapper), and then in reverse builds up the AOTOutput as it is tracing. + +There is one major exception to this general idea of "build AOTInput first", +and then "build AOTOutput second": when we create TangentAOTInput, we need to +reference AOTOutputs (which output we are the tangents of) which we generally +haven't created yet. There's two ways we deal with this: + +- After the precompile steps (dedup and synthetic base handling), we do an + initial pass to collect forward metadata that produces the initial set of + PlainAOTOutputs which we use to create the tangent inputs. + +- We also sometimes just violate causality and predict that an AOTOutput will + be created in a particular way at some later point in time when we build an + AOTInput. + +As of July 2025, here is an exhaustive description of how inputs/outputs +traverse the wrappers from AOTAutograd, and what descriptors can be introduced +at these phases. + +:: + + Build wrappers (FLOWS DOWN) Run trace (FLOWS UP) + ------------------------------------------------------------------------------------------------- + Begin PlainAOTInput (n/a) + ParamAOTInput + + Precompile dedupe (remove dupes) (nothing) + + Precompile synthetic base SyntheticBaseAOTInput MetadataMutationAOTOutput + ViewBaseAOTInput + + Forward metadata trace PlainAOTOutput (n/a) + MetadataMutationAOTOutput + + Prepare for autograd (nothing) InputMutationAOTOutput + IntermediateBaseAOTOutput + + Create joint TangentAOTInput GradAOTOutput + w/ InputMutationAOTOutput + w/ IntermediateBaseAOTOutput + + Precompile subclass SubclassGetAttrAOTInput et al. SubclassGetAttrAOTOutput et al. + + Effect tokens ForwardTokenAOTInput ForwardTokenAOTOutput + BackwardTokenAOTInput BackwardTokenAOTOutput + + End (n/a) PlainAOTOutput + +It can be helpful to separately write down the input flow and the output flow +for ease of understanding the data flow: + +* Input desc propagation (happens as we build wrappers) + + * [IN] Begin with original calling convention (PlainAOTInput, ParamAOTInput) + * [IN] Precompile dedupe: (removes duplicate AOTInputs) + * [IN] Precompile synthetic base: SyntheticBaseAOTInput, ViewBaseAOTInput + * Forward metadata trace (mini output desc propagation) + + * [OUT] Original output convention: PlainAOTOutput + * [OUT] Precompile synthetic base: MetadataMutationAOTOutput + + * [IN] Prepare for autograd: (nothing) + * [IN] Create joint: TangentAOTInput (potentially w/ + IntermediateBaseAOTOutput, InputMutationAOTOutput) + * [IN] Precompile subclass: SubclassGetAttrAOTInput et al. + * [IN] Effect tokens: ForwardTokenAOTInput, BackwardTokenAOTInput + (Note: BackwardTokenAOTInput is technically generated not by a wrapper but + actually done by token_discovery which implicitly adds extra arguments + to the FX trace on-the-fly.) + +* Trigger a trace with the modified inputs on the wrapper +* Output desc propagation (happens as we unwind from the user function call in trace) + + * [OUT] Begin with original calling convention: PlainAOTOutput + * [OUT] Effect tokens: ForwardTokenAOTOutput, BackwardTokenAOTOutput + * [OUT] Precompile subclass: SubclassGetAttrAOTOutput et al. + * [OUT] Create joint: GradAOTOutput + * [OUT] Prepare for autograd: InputMutationAOTOutput, IntermediateBaseAOTOutput + * [OUT] Precompile synthetic base: MetadataMutationAOTOutput + * [OUT] Precompile dedupe: (nothing) +""" + +import dataclasses + + +# TODO: the is_* predicates are a little suspicious because (1) they're not +# used by anything and (2) they always report False even when a parameter got +# swizzled into a view base or deduped with a non-parameter. It is pretty +# difficult to exercise these cases but it's not clear if you will write code +# that works correctly in those cases. + + +@dataclasses.dataclass(frozen=True) +class AOTInput: + """Describes where an input from an AOTAutograd produced FX graph comes from""" + + def expr(self) -> str: + raise NotImplementedError("Subclasses must implement expr()") + + def is_param(self) -> bool: + """True if this input is a parameter or derived from a parameter (e.g., subclass attr)""" + return False + + def is_buffer(self) -> bool: + """True if this input is a buffer or derived from a buffer (e.g., subclass attr)""" + return False + + def is_tangent(self) -> bool: + """True if this input is a tangent or derived from a tangent (e.g., subclass attr)""" + return False + + +# Note: Currently, our typing discipline for differentiable versus not is not +# very good, so feel free to rely on runtime tests instead. + + +@dataclasses.dataclass(frozen=True) +class DifferentiableAOTInput(AOTInput): + """A subclass that classifies AOTInput that can be wrapped by GradAOTOutput""" + + +@dataclasses.dataclass(frozen=True) +class AOTOutput: + """Describes where an output from an AOTAutograd produced FX graph will + eventually be bundled into the final output""" + + def expr(self) -> str: + raise NotImplementedError("Subclasses must implement expr()") + + def is_grad(self) -> bool: + """True if this output is a grad or derived from a grad (e.g., subclass attr)""" + return False + + +@dataclasses.dataclass(frozen=True) +class DifferentiableAOTOutput(AOTOutput): + """A subclass that classifies AOTOutput that can be wrapped by TangentAOTInput""" + + +# ------------ + +# AOTInput + +# ------------ + + +@dataclasses.dataclass(frozen=True) +class ParamAOTInput(DifferentiableAOTInput): + """The input is a parameter, whose FQN is target""" + + target: str + + def expr(self) -> str: + return f"self.get_parameter({self.target!r})" + + def is_param(self) -> bool: + return True + + def is_buffer(self) -> bool: + return False + + +@dataclasses.dataclass(frozen=True) +class BufferAOTInput(DifferentiableAOTInput): + """The input is a buffer, whose FQN is target""" + + target: str + + def expr(self) -> str: + return f"self.get_buffer({self.target!r})" + + def is_param(self) -> bool: + return False + + def is_buffer(self) -> bool: + return True + + +@dataclasses.dataclass(frozen=True) +class DummyAOTInput(AOTInput): + """In some circumstances, we want to call into a function that expects AOTInput, but + we don't actually care about that logic (most typically, because some code is being used + for both compile-time and run-time; AOTInput processing is not needed in this situation. + Pass a dummy in this situation; but it is better to just have a version of the function + that doesn't have this at all.""" + + idx: int + + def expr(self) -> str: + return f"__dummy{self.idx}" + + +@dataclasses.dataclass(frozen=True) +class PlainAOTInput(DifferentiableAOTInput): + """The input is a plain input, corresponding to a particular positional index. + + Note that AOTInput is always relative to a function with a *flat* calling convention, + e.g., as accepted by `aot_module_simplified`. There are some AOTAutograd APIs that + flatten pytrees, and we don't record PyTree key paths from the flattening (but we + could and should!) + """ + + idx: int + + def expr(self) -> str: + return f"args[{self.idx}]" + + +@dataclasses.dataclass(frozen=True) +class SubclassGetAttrAOTInput(AOTInput): + """Subclass inputs get unpacked into their constituent pieces before going into an FX + graph. This tells you which particular attribute of the subclass this particular + input corresponds to (of the 'base' originally subclass argument.) + """ + + base: AOTInput + attr: str + + def expr(self) -> str: + return f"{self.base.expr()}.{self.attr}" + + def is_param(self) -> bool: + return self.base.is_param() + + def is_buffer(self) -> bool: + return self.base.is_buffer() + + def is_tangent(self) -> bool: + return self.base.is_tangent() + + +@dataclasses.dataclass(frozen=True) +class SubclassSizeAOTInput(AOTInput): + """Which subclass this particular outer size SymInt input (at dim idx) came from.""" + + base: AOTInput + idx: int + + def expr(self) -> str: + return f"{self.base.expr()}.size({self.idx})" + + +@dataclasses.dataclass(frozen=True) +class SubclassStrideAOTInput(AOTInput): + """Which subclass this particular outer stride SymInt input (at dim idx) came from.""" + + base: AOTInput + idx: int + + def expr(self) -> str: + return f"{self.base.expr()}.stride({self.idx})" + + +@dataclasses.dataclass(frozen=True) +class ViewBaseAOTInput(DifferentiableAOTInput): + """ + When multiple differentiable inputs are views of the same input, AOTAutograd will replace all of these + views with a single input representing the base. If this is undesirable, you can clone the views + example inputs before passing them into AOTAutograd. + + TODO: In principle we could report ALL of the inputs who this is a base of. + """ + + base_of: AOTInput + + def expr(self) -> str: + return f"{self.base_of.expr()}._base" + + +@dataclasses.dataclass(frozen=True) +class SyntheticBaseAOTInput(DifferentiableAOTInput): + """This is similar to ViewBaseAOTInput, but this happens when none of the views were differentiable, so + we weren't able to get our hands on the true original view and constructed a synthetic one instead + for the sake of autograd. + """ + + base_of: AOTInput + + def expr(self) -> str: + return f"__make_synthetic_base({self.base_of.expr()})" + + +@dataclasses.dataclass(frozen=True) +class PhiloxForwardSeedAOTInput(AOTInput): + """The seed for functionalized Philox RNG calls, specifically for forward graph.""" + + def expr(self) -> str: + return "__philox_forward_seed" + + +@dataclasses.dataclass(frozen=True) +class PhiloxForwardBaseOffsetAOTInput(AOTInput): + """The offset for functionalized Philox RNG calls, specifically for forward graph.""" + + def expr(self) -> str: + return "__philox_forward_base_offset" + + +@dataclasses.dataclass(frozen=True) +class PhiloxBackwardSeedAOTInput(AOTInput): + """The seed for functionalized Philox RNG calls, specifically for backward graph.""" + + def expr(self) -> str: + return "__philox_backward_seed" + + +@dataclasses.dataclass(frozen=True) +class PhiloxBackwardBaseOffsetAOTInput(AOTInput): + """The offset for functionalized Philox RNG calls, specifically for backward graph.""" + + def expr(self) -> str: + return "__philox_backward_base_offset" + + +@dataclasses.dataclass(frozen=True) +class ForwardTokenAOTInput(AOTInput): + """The world token which is threaded through side-effectful operations""" + + idx: int + + def expr(self) -> str: + return f"__forward_token{self.idx}" + + +@dataclasses.dataclass(frozen=True) +class BackwardTokenAOTInput(AOTInput): + """The world token which is threaded through side-effectful operations, for backwards""" + + idx: int + + def expr(self) -> str: + return f"__backward_token{self.idx}" + + +# Technically the "output" here is redundant, tangents always correspond to +# outputs +# NB: this is marked differentiable as it /would/ be differentiable if we +# support double backwards, but we never generate this today because we +# don't support double backwards. +@dataclasses.dataclass(frozen=True) +class TangentAOTInput(DifferentiableAOTInput): + """An input to the joint graph representing the tangent of an output.""" + + output: DifferentiableAOTOutput + + def __post_init__(self) -> None: + if not isinstance(self.output, DifferentiableAOTOutput): + raise AssertionError( + f"expected output to be DifferentiableAOTOutput, got {type(self.output)}" + ) + + def expr(self) -> str: + return f"__output_tangent({self.output.expr()})" + + def is_tangent(self) -> bool: + return True + + +# ------------ + +# AOTOutput + +# ------------ + + +@dataclasses.dataclass(frozen=True) +class PlainAOTOutput(DifferentiableAOTOutput): + """A plain tensor output at position idx of the output tuple""" + + idx: int + + def expr(self) -> str: + return f"output[{self.idx}]" + + +@dataclasses.dataclass(frozen=True) +class InputMutationAOTOutput(DifferentiableAOTOutput): + """The mutated value of an input tensor, returned so we can appropriately propagate autograd.""" + + mutated_input: AOTInput + + def expr(self) -> str: + return f"__input_mutation({self.mutated_input.expr()})" + + +@dataclasses.dataclass(frozen=True) +class IntermediateBaseAOTOutput(DifferentiableAOTOutput): + """An intermediate base of multiple outputs which alias each other. We only report ONE of + the outputs that contributed to this base""" + + base_of: "AOTOutput" + + def expr(self) -> str: + return f"__intermediate_base({self.base_of.expr()})" + + +# TODO: it's a little dodgy this is differentiable lol, but we do generate +# these BEFORE autograd is handled +@dataclasses.dataclass(frozen=True) +class MetadataMutationAOTOutput(DifferentiableAOTOutput): + idx: int + + def expr(self) -> str: + return f"__aliased_arg_with_metadata_mutation{self.idx}" + + +# NB: this is marked differentiable as it /would/ be differentiable if we +# support double backwards, but we never generate this today because we +# don't support double backwards. +@dataclasses.dataclass(frozen=True) +class GradAOTOutput(DifferentiableAOTOutput): + """An output representing the computed gradient for a differentiable input, in the joint graph""" + + grad_of: DifferentiableAOTInput + + def __post_init__(self) -> None: + if not isinstance(self.grad_of, DifferentiableAOTInput): + raise AssertionError( + f"expected grad_of to be DifferentiableAOTInput, got {type(self.grad_of)}" + ) + + def expr(self) -> str: + return f"__grad({self.grad_of.expr()})" + + def is_grad(self) -> bool: + return True + + +@dataclasses.dataclass(frozen=True) +class PhiloxUpdatedForwardOffsetAOTOutput(AOTOutput): + """The final offset from the functionalized RNG calls, forward only""" + + def expr(self) -> str: + return "__philox_updated_forward_offset" + + +@dataclasses.dataclass(frozen=True) +class PhiloxUpdatedBackwardOffsetAOTOutput(AOTOutput): + """The final offset from the functionalized RNG calls, backward only""" + + def expr(self) -> str: + return "__philox_updated_backward_offset" + + +@dataclasses.dataclass(frozen=True) +class ForwardTokenAOTOutput(AOTOutput): + """The world token output for side-effectful calls, returned so we cannot DCE it, forward only""" + + idx: int + + def expr(self) -> str: + return f"__forward_token{self.idx}" + + +@dataclasses.dataclass(frozen=True) +class BackwardTokenAOTOutput(AOTOutput): + """The world token output for side-effectful calls, returned so we cannot DCE it, backward only""" + + idx: int + + def expr(self) -> str: + return f"__backward_token{self.idx}" + + +# These are seemingly symmetric with their AOTInput counterparts. The way to +# think about it is that a subclass could be an input or an output, and they +# get exploded into plain tensors on the way in and out. So we need +# descriptors for both. +@dataclasses.dataclass(frozen=True) +class SubclassGetAttrAOTOutput(AOTOutput): + """This output will be bundled into a subclass at this location""" + + base: AOTOutput + attr: str + + def expr(self) -> str: + return f"{self.base.expr()}.{self.attr}" + + def is_grad(self) -> bool: + return self.base.is_grad() + + +@dataclasses.dataclass(frozen=True) +class SubclassSizeAOTOutput(AOTOutput): + """This output size will be bundled into a subclass at this location""" + + base: AOTOutput + idx: int + + def expr(self) -> str: + return f"{self.base.expr()}.size({self.idx})" + + +@dataclasses.dataclass(frozen=True) +class SubclassStrideAOTOutput(AOTOutput): + """This output stride will be bundled into a subclass at this location""" + + base: AOTOutput + idx: int + + def expr(self) -> str: + return f"{self.base.expr()}.stride({self.idx})" + + +@dataclasses.dataclass(frozen=True) +class DummyAOTOutput(AOTOutput): + """For cases when you don't actually care about descriptor propagation, do not use under normal + circumstances.""" + + idx: int + + def expr(self) -> str: + return f"__dummy{self.idx}" + + +@dataclasses.dataclass(frozen=True) +class SavedForBackwardsAOTOutput(AOTOutput): + idx: int + + def expr(self) -> str: + return f"__saved_for_backwards_{self.idx}" + + +# Note [Activations with no version counter checks in eager] +# In eager, when a tensor is saved for backward, the autograd engine +# generally performs version counter checks when grabbing the activation +# at backward time. +# One exception is in a custom autograd.Function: if the user stashes a tensor +# for use in the backward using `ctx.foo = foo`, rather than +# `ctx.save_for_backward(foo)`, then the autograd engine will not know +# to perform any checks. +# In torch.compile, we handle autograd by tracing through it ahead of time, +# and wrapping the fw + bw graphs into a custom autograd.Function. +# In order to provide parity with eager around VC checks, though, we need +# to know which activations had gotten this "no VC checks" treatment in eager, +# so we can plumb this info into the AOTAutograd runtime, +# and avoid calling ctx.save_for_backward on these tensors. +# +# This dataclass tells us that a given AOTOutput corresponds to: +# - An activation output from the forward graph +# - that should *not* have its version counter checked at runtime in the backward. +# This is done by stashing this activation on the ctx object directly +@dataclasses.dataclass(frozen=True) +class SavedForBackwardsNoVcCheckAOTOutput(AOTOutput): + idx: int + + def expr(self) -> str: + return f"__saved_for_backwards_no_vc_check_{self.idx}" diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/frontend_utils.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/frontend_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8aef1c8f7740c1f4b054d50561a9ff16a1581094 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/frontend_utils.py @@ -0,0 +1,478 @@ +from __future__ import annotations + +import warnings +from contextlib import contextmanager +from typing import Any, cast, TYPE_CHECKING + +import torch +import torch.utils._pytree as pytree +from torch._custom_class_base import CustomClassBase +from torch._guards import detect_fake_mode +from torch._library.opaque_object import is_custom_class +from torch._subclasses import FakeTensor, FakeTensorMode +from torch._subclasses.fake_tensor import is_fake_tensor, maybe_get_fake_mode +from torch.fx.experimental.proxy_tensor import _pytree_subclasses_that_lose_info +from torch.fx.experimental.symbolic_shapes import ShapeEnv +from torch.utils._python_dispatch import is_traceable_wrapper_subclass + +from .. import config +from .descriptors import BufferAOTInput, DifferentiableAOTInput, ParamAOTInput +from .schemas import ActInputPath, AOTConfig, FakifiedFlatArgs +from .utils import get_loaded_async_collective_tensor_type + + +if TYPE_CHECKING: + from collections.abc import Generator, KeysView + + from torch.distributed._functional_collectives import AsyncCollectiveTensor + + +static_inputs_log = torch._logging.getArtifactLogger( + __name__, "cudagraph_static_inputs" +) + + +def process_inputs( + flat_args: list[Any], + aot_config: AOTConfig, + fake_mode: FakeTensorMode, + shape_env: ShapeEnv | None, + ignore_shape_env: bool = False, +) -> tuple[FakifiedFlatArgs, list[ActInputPath]]: + """Convert real tensor inputs into fake tensors for AOT autograd tracing. + + Called at compile time (not runtime) to produce the fake inputs that AOT + autograd traces through. Each real tensor is converted to a FakeTensor + via ``fake_mode.from_tensor``, preserving shape, dtype, device, and + symbolic shape information from the ShapeEnv. Non-tensor inputs (ints, + SymInts, ScriptObjects) are converted or passed through as appropriate. + + Tensor subclass inputs (DTensor, etc.) are fakified recursively by walking + their ``__tensor_flatten__`` attrs. AsyncCollectiveTensors are resolved via + ``trigger_wait()`` before fakification so they don't appear in the traced + metadata (see below). + + Called from ``aot_function``, ``aot_module_simplified``, and + ``aot_export_module`` — anywhere AOT autograd needs fake inputs before + graph capture. + + Returns: + A tuple of (fakified_args, act_input_paths) where act_input_paths records + which input paths held AsyncCollectiveTensors. The paths are stored on + ViewAndMutationMeta so the runtime wrapper can re-wait those positions. + """ + # Resolve AsyncCollectiveTensors before tracing. ACTs are transient + # eager-mode wrappers for async collective overlap; if they leak into the + # traced graph as input types, AOT autograd records them in + # SubclassCreationMeta for output tangent metadata. At runtime, autograd + # produces plain tensor tangents, causing a type mismatch. Unwrapping + # here prevents ACT from appearing in the traced metadata. + AsyncCollectiveTensor = get_loaded_async_collective_tensor_type() + act_input_paths: list[ActInputPath] = [] + if AsyncCollectiveTensor is not None: + tracing_context = torch._guards.TracingContext.try_get() + for i, a in enumerate(flat_args): + resolved_arg = _resolve_input_async_collectives( + a, i, (), act_input_paths, AsyncCollectiveTensor + ) + # Rebuilt wrapper inputs must keep Dynamo's symbolic context so + # fakeification does not allocate source-less shape symbols. + if resolved_arg is not a and isinstance(resolved_arg, torch.Tensor): + if tracing_context is not None: + if a in tracing_context.tensor_to_context: + tracing_context.tensor_to_context[resolved_arg] = ( + tracing_context.tensor_to_context[a] + ) + flat_args[i] = resolved_arg + + with fake_mode: + + def convert(idx: int, x: Any) -> Any: + nonlocal ignore_shape_env + if shape_env is not None and not ignore_shape_env: + from torch._dynamo.source import ConstantSource + + if isinstance(x, int): + # We always specialize on scalar values in export. + if aot_config.is_export: + return x + source = ConstantSource(f"sym_{idx}") + return shape_env.create_symintnode( + shape_env.create_symbol(x, source, positive=x >= 0), + hint=x, + source=source, + ) + if isinstance(x, torch.ScriptObject) or is_custom_class(type(x)): + return torch._library.fake_class_registry.maybe_to_fake_obj( + fake_mode, x + ) + if not isinstance(x, torch.Tensor): + return x + if is_fake_tensor(x): + # In the case of cross compilation we will have example inputs + # with a different fake mode than our tracing fake mode. + # In these cases we want to clone the fake tensor into our + # inner fake mode. + if maybe_get_fake_mode(x) is not fake_mode: + return fake_mode.from_tensor(x) + return x + if is_traceable_wrapper_subclass(x): + attrs, _ = x.__tensor_flatten__() + # See if all inner tensors are FakeTensors from this mode + all_this_fake = True + for a in attrs: + match getattr(x, a): + case FakeTensor() as v: + if v.fake_mode is not fake_mode: + # FakeTensor subclass from a different mode. + # Fall through to refakify. + all_this_fake = False + break + case torch.Tensor(): + all_this_fake = False + break + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + + if all_this_fake: + return x + + # see note [Tensor Fakification and Symbol Caching] + symbolic_context = None + source = None + trace = True + if tracing_context := torch._guards.TracingContext.try_get(): + if x in tracing_context.tensor_to_context: + symbolic_context = tracing_context.tensor_to_context[x] + source = symbolic_context.tensor_source + # We already fakeified this tensor in Dynamo, don't + # dump the trace for it again + trace = False + if ( + idx < aot_config.num_params_buffers + and config.static_weight_shapes + and not symbolic_context + ): + # TODO: Ensure that this codepath is never exercised from + # Dynamo + return fake_mode.from_tensor(x, static_shapes=True) + + result = fake_mode.from_tensor( + x, + static_shapes=ignore_shape_env, + symbolic_context=symbolic_context, + source=source, + trace=trace, + ) + return result + + return FakifiedFlatArgs( + [convert(idx, x) for idx, x in enumerate(flat_args)] + ), act_input_paths + + +def _resolve_input_async_collectives( + x: object, + idx: int, + attr_path: tuple[str, ...], + act_input_paths: list[ActInputPath], + AsyncCollectiveTensor: type[AsyncCollectiveTensor], +) -> object: + """Wait on ACT inputs, recording each top-level or wrapper-subclass path.""" + if isinstance(x, AsyncCollectiveTensor): + act_input_paths.append((idx, attr_path)) + return x.trigger_wait() + + if not is_traceable_wrapper_subclass(x): + return x + + attrs, meta = x.__tensor_flatten__() + inner_tensors: dict[str, Any] | None = None + for attr in attrs: + inner = getattr(x, attr) + match inner: + case CustomClassBase(): + continue + case torch.Tensor(): + resolved_inner = _resolve_input_async_collectives( + inner, + idx, + (*attr_path, attr), + act_input_paths, + AsyncCollectiveTensor, + ) + case _: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(inner)}" + ) + + if resolved_inner is not inner: + if inner_tensors is None: + inner_tensors = {a: getattr(x, a) for a in attrs} + inner_tensors[attr] = resolved_inner + + if inner_tensors is None: + return x + + return type(x).__tensor_unflatten__( # type: ignore[attr-defined] + inner_tensors, meta, x.size(), x.stride() + ) + + +def construct_fake_mode( + flat_args: list[Any], aot_config: AOTConfig +) -> tuple[FakeTensorMode, ShapeEnv | None]: + fake_mode = detect_fake_mode(flat_args) + if fake_mode is None: + shape_env = ShapeEnv() if aot_config.dynamic_shapes else None + fake_mode = FakeTensorMode(shape_env=shape_env) + else: + shape_env = fake_mode.shape_env + return (fake_mode, shape_env) + + +def _try_get_metadata_from_dynamo( + mod: torch.nn.Module, + param_keys: KeysView[str], + full_args_num: int, + full_args_descs: list[DifferentiableAOTInput], +) -> tuple[list[torch._guards.Source | None] | None, list[int]]: + """ + Metadata is forwarded from Dynamo to AOTDispatch via special fields on GraphModule. + We first verify that `mod` does come from Dynamo, then we handle cases where + metadata might be missing. + + Returns: + aot_autograd_arg_pos_to_source: used to dedup params and their guards + static_input_indices: used to identify static inputs for cudagraphs + """ + # Note [Assumption on Dynamo Metadata] + # This function assumes a graph module from dynamo provides `dynamo_compiled_id`, + # _param_name_to_source, and every placeholder node has `_dynamo_source` attributes. + # When gm is modified (e.g., DDPOptimizer via split_module), metadata needs to + # be propagated in order to be recognized as a dynamo graph + + if not (isinstance(mod, torch.fx.GraphModule) and "dynamo_compile_id" in mod.meta): + # graph was not captured by dynamo + return None, [] + + if not hasattr(mod, "_param_name_to_source"): + # is from export + static_input_indices = [ + i + for i, node in enumerate(full_args_descs) + if isinstance(node, (ParamAOTInput, BufferAOTInput)) + ] + return None, static_input_indices + + # We now know this came from dynamo, and (1) we care about guards, + # so setting up aot_autograd_arg_pos_to_source for downstream dedup guards + # can now be done safely. (2) Dynamo logic protects the 1:1 sizing below. + # Additionally, we mark static indices for cudagraphs. + param_name_to_source = cast( + dict[str, torch._guards.Source], mod._param_name_to_source + ) + seen_sources = set() + + aot_autograd_arg_pos_to_source: list[torch._guards.Source | None] = [] + static_input_indices = [] + # Collect the new inputs lifted by aotdispatch + for i, name in enumerate(param_keys): + if name not in param_name_to_source: + raise AssertionError(f"{name} not found in param_name_to_source") + source = param_name_to_source[name] + if source in seen_sources: + raise AssertionError(f"source {source} already in seen_sources") + if source is None: + raise AssertionError(f"source must not be None for {name}") + seen_sources.add(source) + aot_autograd_arg_pos_to_source.append(source) + + static_input_indices.append(i) + + # Collect the dynamo graph inputs + # TODO(mlazos): Revisit if this is still needed. With Dynamo install ID + # matched tensors back into the Fx graph, this might not be necessary. + for pos, node in enumerate(mod.graph.find_nodes(op="placeholder")): + if not hasattr(node, "_dynamo_source"): + raise AssertionError(f"node {node} must have _dynamo_source attribute") + source = node._dynamo_source + # `source`` specifies the source from user code. ddp optimizer may have + # intermediate values becoming submodule placeholders which does not + # have a source + if source is not None and source in seen_sources: + raise AssertionError(f"source {source} already in seen_sources") + seen_sources.add(source) + aot_autograd_arg_pos_to_source.append(source) + source_name = source.name if source else str(source) + + # input[i] in dynamo is now: + # input[i + len(extra_params)] in AOT, + # where extra_params are the params/buffers that dynamo baked into the + # OutputGraph + actual_pos = pos + len(param_keys) + + if "tensor_dict" in node.meta and node.meta["tensor_dict"].get( + "_dynamo_static_input_type", None + ): + static_inputs_log.debug( + "Adding static input pos %s for source %s", actual_pos, source_name + ) + static_input_indices.append(actual_pos) + else: + static_inputs_log.debug( + "Non-static input pos %s for source %s", actual_pos, source_name + ) + + if full_args_num != len(aot_autograd_arg_pos_to_source): + raise AssertionError( + f"full_args_num={full_args_num} != len(aot_autograd_arg_pos_to_source)={len(aot_autograd_arg_pos_to_source)}" + ) + return aot_autograd_arg_pos_to_source, static_input_indices + + +@contextmanager +def _detect_attribute_assignment(mod: torch.nn.Module) -> Generator[None, None, None]: + # Do not allow assignment of tensor attributes during export unless + # the attribute is registered as a buffer. + + NN_MODULE_STD_ATTRS = [ + "_backward_hooks", + "_backward_pre_hooks", + "_buffers", + "_forward_hooks", + "_forward_hooks_always_called", + "_forward_hooks_with_kwargs", + "_forward_pre_hooks", + "_forward_pre_hooks_with_kwargs", + "_is_full_backward_hook", + "_load_state_dict_post_hooks", + "_load_state_dict_pre_hooks", + "_modules", + "_non_persistent_buffers_set", + "_parameters", + "_state_dict_hooks", + "_state_dict_pre_hooks", + "training", + ] + NN_MODULE_LAZY_STD_ATTRS = [ + "_initialize_hook", + "_load_hook", + ] + STD_ATTRS = { + *NN_MODULE_STD_ATTRS, + *NN_MODULE_LAZY_STD_ATTRS, + } + + def _get_attributes(mod: torch.nn.Module) -> dict[str, Any]: + # return any attributes of a module that are not standard attributes + return {k: v for k, v in mod.__dict__.items() if k not in STD_ATTRS} + + def _get_all_module_attributes(mod: torch.nn.Module) -> dict[str, dict[str, Any]]: + # return attributes from all modules and submodules + result = {} + for name, submodule in mod.named_modules(): + result[name] = _get_attributes(submodule) + return result + + def _restore_all_module_attributes( + mod: torch.nn.Module, snapshot: dict[str, dict[str, Any]] + ) -> None: + # restore attributes to all modules and submodules + for name, submodule in mod.named_modules(): + if name in snapshot: + submodule.__dict__.update(snapshot[name]) + + # save state of attributes before enter + snapshot = pytree.tree_map( + lambda x: x, + _get_all_module_attributes(mod), + is_leaf=lambda x: type(x) in _pytree_subclasses_that_lose_info, + ) + try: + yield + finally: + # after exit, compare state of attributes with snapshot + # to detect which tensor attributes were assigned + + def _collect_assigned_tensor_attributes( + snapshot: dict[str, dict[str, Any]], new_attrs: dict[str, dict[str, Any]] + ) -> list[str]: + assigned_tensor_attributes = [] + + def _compare_values(path: str, old_val: Any, new_val: Any) -> None: + """Recursively compare values, handling containers.""" + # Same object, no change + if old_val is new_val: + return + + if old_val is None or new_val is None: + if isinstance(new_val, torch.Tensor): + assigned_tensor_attributes.append(path) + return + + # Check if it's a tensor that was reassigned + if isinstance(new_val, torch.Tensor): + assigned_tensor_attributes.append(path) + return + + # Handle dict containers + if isinstance(old_val, dict) and isinstance(new_val, dict): + all_keys = set(old_val.keys()) | set(new_val.keys()) + for key in all_keys: + old_item = old_val.get(key) + new_item = new_val.get(key) + _compare_values(f"{path}[{key!r}]", old_item, new_item) + return + + # Handle list/tuple containers + if isinstance(old_val, (list, tuple)) and isinstance( + new_val, (list, tuple) + ): + # Different lengths = mutation happened + max_len = max(len(old_val), len(new_val)) + for i in range(max_len): + old_item = old_val[i] if i < len(old_val) else None + new_item = new_val[i] if i < len(new_val) else None + _compare_values(f"{path}[{i}]", old_item, new_item) + return + + # For other types, just check if they're different objects + # (we don't care about non-tensor mutations) + + for module_name in snapshot.keys() | new_attrs.keys(): + old_module_attrs = snapshot.get(module_name, {}) + new_module_attrs = new_attrs.get(module_name, {}) + + for attr_name in old_module_attrs.keys() | new_module_attrs.keys(): + module_prefix = f"self.{module_name}." if module_name else "self." + full_path = f"{module_prefix}{attr_name}" + + old_val = old_module_attrs.get(attr_name) + new_val = new_module_attrs.get(attr_name) + _compare_values(full_path, old_val, new_val) + + return assigned_tensor_attributes + + new_attrs = _get_all_module_attributes(mod) + assigned_tensor_attributes = _collect_assigned_tensor_attributes( + snapshot, new_attrs + ) + # restore state of all attributes (including, e.g., of primitive types) + _restore_all_module_attributes(mod, snapshot) + + if assigned_tensor_attributes: + if len(assigned_tensor_attributes) > 1: + noun, verb = "attributes", "were" + else: + noun, verb = "attribute", "was" + warnings.warn( + f"The tensor {noun} {', '.join(assigned_tensor_attributes)} {verb} assigned during export. " + "Such attributes must be registered as buffers using the `register_buffer` API " + "(https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.register_buffer).", + stacklevel=2, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/functional_utils.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/functional_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cd26a80fb560660332887169ee1feb841f08bd7c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/functional_utils.py @@ -0,0 +1,700 @@ +""" +This file contains utilities related to functionalization in AOTAutograd: +1. converting to/from functional tensors +2. detecting Tensor mutations - both metadata and Tensor value +3. regenerating/replaying views from their base +4. checking if a graph is functional i.e. whether it contains any mutation ops +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, TypeGuard + +import torch +from torch import Tensor +from torch._C import _functionalization +from torch._custom_class_base import CustomClassBase +from torch._logging import getArtifactLogger +from torch._subclasses.fake_tensor import is_fake_tensor +from torch._subclasses.functional_tensor import FunctionalTensor +from torch._subclasses.meta_utils import is_sparse_any +from torch.fx.experimental.symbolic_shapes import guard_or_false, sym_eq, SymIntEqByExpr +from torch.multiprocessing.reductions import StorageWeakRef +from torch.utils._python_dispatch import ( + is_traceable_wrapper_subclass, + transform_subclass, +) + + +aot_joint_log = getArtifactLogger(__name__, "aot_joint_graph") + + +def to_fun(t: object) -> Any: + if isinstance(t, Tensor): + if is_traceable_wrapper_subclass(t): + # See Note [Functionalization always runs last] + # This means that if we want to "functionalize" a subclass, we need to ensure that the functional wrapper + # goes at the bottom. + # recurse here, so we can support nested wrapper subclasses + out = transform_subclass(t, lambda _, inner_t: to_fun(inner_t)) + torch._mirror_autograd_meta_to(t, out) # type: ignore[attr-defined] + return out + else: + return FunctionalTensor.to_functional(t) + else: + return t + + +def sync_functional_tensor(t: torch.Tensor) -> None: + if is_traceable_wrapper_subclass(t): + attrs, _ctx = t.__tensor_flatten__() # type: ignore[attr-defined] + for attr in attrs: + match getattr(t, attr): + case Tensor() as inner: + sync_functional_tensor(inner) + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + else: + torch._sync(t) + + +# When subclasses are involved, t here will usually look something like: +# SubclassA(SubclassB(FunctionalTensor(_to_fun_tensor(FakeTensor)))) +def from_fun(t: object) -> object: + if isinstance(t, Tensor) and is_traceable_wrapper_subclass(t): + # See Note [Functionalization always runs last] + # This means that if we want to "functionalize" a subclass, we need to ensure that the functional wrapper + # goes at the bottom. + # recurse here, so we can support nested wrapper subclasses + out = transform_subclass(t, lambda _, inner_t: from_fun(inner_t)) + torch._mirror_autograd_meta_to(t, out) # type: ignore[attr-defined] + return out + + if not isinstance(t, FunctionalTensor): + # quick sanity assert + if isinstance(t, torch.Tensor): + if torch._is_functional_tensor(t): # type: ignore[attr-defined] + raise AssertionError("expected non-functional tensor") + return t + sync_functional_tensor(t) + return torch._from_functional_tensor(t.elem) + + +def is_fun(t: object) -> TypeGuard[FunctionalTensor | Tensor]: + if isinstance(t, Tensor) and is_traceable_wrapper_subclass(t): + # See Note [Functionalization always runs last] + # This means that if we want to "functionalize" a subclass, we need to ensure that the functional wrapper + # goes at the bottom. + # recurse here, so we can support nested wrapper subclasses + t_attrs, _ = t.__tensor_flatten__() # type: ignore[attr-defined] + got_fun: bool | None = None + for attr in t_attrs: + match getattr(t, attr): + case Tensor() as v: + fun = is_fun(v) + if got_fun is None: + got_fun = fun + elif got_fun != fun: + raise AssertionError( + "mixed functional/non-functional inner tensors" + ) + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + return got_fun or False + + return isinstance(t, FunctionalTensor) + + +# t here is either +# (1) A FunctionalTensor(_to_functional_tensor(FakeTensor)) +# (2) A traceable tensor subclass that holds a FunctionalTensor +# (3) Not a tensor +def has_data_mutation(t: object) -> bool: + if is_traceable_wrapper_subclass(t): + attrs, _ = t.__tensor_flatten__() + # A tensor subclass was updated if any of its inner elements were updated + for attr in attrs: + match getattr(t, attr): + case Tensor() as v: + if has_data_mutation(v): + return True + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + return False + else: + if isinstance(t, torch.Tensor): + if not isinstance(t, FunctionalTensor): + raise AssertionError(f"expected FunctionalTensor, got {type(t)}") + return torch._functionalize_has_data_mutation(t.elem) # type: ignore[attr-defined] + return False + + +def are_all_mutations_hidden_from_autograd(t: object) -> bool: + if is_traceable_wrapper_subclass(t): + attrs, _ = t.__tensor_flatten__() + # If all inner elements are mutations hidden from autograd, then it is a mutation hidden from autograd. + for attr in attrs: + match getattr(t, attr): + case Tensor() as v: + if not are_all_mutations_hidden_from_autograd(v): + return False + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + return True + elif isinstance(t, torch.Tensor): + if not isinstance(t, FunctionalTensor): + raise AssertionError(f"expected FunctionalTensor, got {type(t)}") + return torch._functionalize_are_all_mutations_hidden_from_autograd(t.elem) + else: + return False + + +def are_all_mutations_under_no_grad_or_inference_mode(t: torch.Tensor) -> bool: + if is_traceable_wrapper_subclass(t): + attrs, _ = t.__tensor_flatten__() + for attr in attrs: + match getattr(t, attr): + case Tensor() as v: + if not are_all_mutations_under_no_grad_or_inference_mode(v): + return False + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + return True + else: + if not isinstance(t, FunctionalTensor): + raise AssertionError(f"expected FunctionalTensor, got {type(t)}") + return torch._functionalize_are_all_mutations_under_no_grad_or_inference_mode( + t.elem + ) + + +def was_inductor_storage_resized(t: object) -> bool: + if is_traceable_wrapper_subclass(t): + attrs, _ = t.__tensor_flatten__() + for attr in attrs: + match getattr(t, attr): + case Tensor() as v: + if was_inductor_storage_resized(v): + raise RuntimeError( + f"storage resizing is not supported on tensor subclass: {type(t)}" + ) + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + return False + elif not isinstance(t, torch.Tensor): + return False + else: + if not isinstance(t, FunctionalTensor): + raise AssertionError(f"expected FunctionalTensor, got {type(t)}") + return torch._functionalize_was_inductor_storage_resized(t.elem) + + +def was_shallow_copy_data(t: object) -> bool: + if is_traceable_wrapper_subclass(t): + return False + if not isinstance(t, torch.Tensor): + return False + if not isinstance(t, FunctionalTensor): + raise AssertionError(f"expected FunctionalTensor, got {type(t)}") + return torch._functionalize_was_shallow_copy_data(t.elem) # type: ignore[attr-defined] + + +# f_arg here is either +# (1) A FunctionalTensor(_to_functional_tensor(FakeTensor)) +# (2) A traceable tensor subclass that holds a FunctionalTensor +# (3) Not a tensor +# Assumption: arg promises to be the "original" tensor wrapped by f_arg +# Note: "storage mutations" coming from set_() are a type of metadata mutation. So: +# - check_only_storage_mutation=True: only return true if there was a storage mutation +# - check_only_storage_mutation=False: return true if there was any metadata mutation (including a storage mutation) +def has_metadata_mutation( + f_arg: object, arg: object, *, check_only_storage_mutation: bool +) -> bool: + if is_traceable_wrapper_subclass(f_arg): + attrs, _ = f_arg.__tensor_flatten__() + # A tensor subclass was updated if any of its inner elements were updated + for attr in attrs: + match getattr(f_arg, attr): + case Tensor(): + f_inner_t = getattr(f_arg, attr) + inner_t = getattr(arg, attr) + if has_metadata_mutation( + f_inner_t, + inner_t, + check_only_storage_mutation=check_only_storage_mutation, + ): + return True + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + return False + else: + if not isinstance(f_arg, torch.Tensor): + if isinstance(arg, torch.Tensor): + raise AssertionError( + f"f_arg is not a Tensor but arg is: {type(f_arg)} vs {type(arg)}" + ) + return False + if not isinstance(f_arg, FunctionalTensor): + raise AssertionError( + f"expected FunctionalTensor for f_arg, got {type(f_arg)}" + ) + if not is_fake_tensor(arg): + raise AssertionError(f"expected FakeTensor for arg, got {type(arg)}") + + arg_after = torch._from_functional_tensor(f_arg.elem) + # This is true if the current tensor experienced at least one set_() call + maybe_storage_changed = torch._functionalize_was_storage_changed(f_arg.elem) # type: ignore[attr-defined] + # However, multiple set_() calls can cancel out. So we also check whether the + # storage of the tensor has changed. + # Note: if an input experienced two set_() calls that cancel out, **and** + # it experiences a data mutation, we pessimistically think that the set_() + # call is necessary here. We could in theory fix this, but this will + # hopefully never happen in user code, and is not needed for fsdp. + if is_sparse_any(arg): + # TODO:add sparse tensors support to functionalization + same_storages = False + else: + same_storages = StorageWeakRef(arg.untyped_storage()) == StorageWeakRef( + arg_after.untyped_storage() + ) + has_storage_metadata_mutation = maybe_storage_changed and not same_storages + if check_only_storage_mutation: + return has_storage_metadata_mutation + + # storage metadata mutation is a type of metadata mutation, so return true if we saw one + if has_storage_metadata_mutation: + return True + + maybe_metadata_mutated = torch._functionalize_has_metadata_mutation(f_arg.elem) # type: ignore[attr-defined] + # This is true if the current tensor experienced at least one metadata mutation. + # So if false, we know there was no metadata mutation + if not maybe_metadata_mutated: + return False + + # However, multi metadata mutations can cancel out. + # So we also check if the concrete sizes/strides on the tensor have changed. + same_sizes = arg.shape == arg_after.shape + same_strides = arg.stride() == arg_after.stride() + same_offsets = arg.storage_offset() == arg_after.storage_offset() + has_metadata_mutation_ = maybe_metadata_mutated and not ( + same_sizes and same_strides and same_offsets + ) + # We consider a tensor to have been metadata mutated if its storage was mutated through a set_() call. + return has_metadata_mutation_ + + +def gen_alias_from_base( + aliased_base_tensor: Tensor, + target_meta_tensor: Tensor, + target_requires_grad: bool, + target_view_meta_sequence: ViewMetaSequence | None = None, + *, + replay_views: bool, +) -> Tensor: + # Patch the correct requires_grad field of the output tensor, depending on whether: + # (i) the reconstructed output (out) was came from a tensor that requires grad or not; + # and (ii) the concrete returned output does require grad or not. + def patch_requires_grad(out: Tensor) -> Tensor: + if aliased_base_tensor.requires_grad and not target_requires_grad: + out = out.detach() + elif not aliased_base_tensor.requires_grad and target_requires_grad: + out.requires_grad_(True) + return out + + # If provided, use the target functional tensor for replaying the views. + # + # In summary, we use the fact that FunctionalTensorWrapper saves the view + # functions applied to itself (collected during functionalization) so as + # to replay them (view functions) on the aliased_base_tensor. + if ( + replay_views + and target_view_meta_sequence is not None + and not any(vm.has_symbolic_inputs for vm in target_view_meta_sequence.sequence) + ): + out = _functionalization.apply_view_meta_sequence( + aliased_base_tensor, target_view_meta_sequence.sequence + ) + # If re-applying the ViewMeta sequence succeeded, there should be no more + # problems going forward. We just check we got to the target shape and + # patch requires_grad flag. + if out.shape != target_meta_tensor.shape: + raise AssertionError( + "incorrect out shape after application of ViewMeta sequence: " + f"{tuple(out.shape)} (actual) vs {tuple(target_meta_tensor.shape)} (expected)" + ) + return patch_requires_grad(out) + + # Try to do view-replay if possible. + # fall back to .as_strided() if we can't. + if target_meta_tensor._base is not None: + # The base that we want to replay our view off of might have a different shape than the view's original base. + b = target_meta_tensor._base + abt = aliased_base_tensor + # Don't unnecessarily call as_strided if nothing changed; as_strided's + # backward is poorly implemented and slow + if abt is not b and ( + abt.size() != b.size() + or abt.stride() != b.stride() + or abt.storage_offset() != b.storage_offset() + ): + reshaped_base_tensor = aliased_base_tensor.as_strided( + b.size(), b.stride(), b.storage_offset() + ) + else: + reshaped_base_tensor = aliased_base_tensor + out = target_meta_tensor._view_func(reshaped_base_tensor) # type: ignore[attr-defined] + # This shape mismatch can happen due to a bug in inplace/view handling in autograd. + # Try putting a breakpoint here and running + # `test/functorch/test_aotdispatch TestAOTAutograd.test_output_all_alias_types` + # Also, https://github.com/pytorch/pytorch/issues/49825 + # + # As a stopgap, we'll fall back to as_strided. + if out is not None and out.shape == target_meta_tensor.shape: + return patch_requires_grad(out) + + size = target_meta_tensor.size() + stride = target_meta_tensor.stride() + storage_offset = target_meta_tensor.storage_offset() + # If the target lives on a different storage than the aliased base + # (e.g. because inductor's copy_misaligned_inputs cloned the input to + # obtain an aligned buffer), ``target.storage_offset()`` is expressed in + # the cloned storage and would pick the wrong slice when applied via + # ``as_strided()`` on the original aliased base tensor. Translate the + # offset: the traced FakeTensor's storage_offset equals the trace-time + # RELATIVE offset from the input, so add back the runtime input's + # ``storage_offset`` to keep the alias anchored to the correct slice. + # Compare storages via ``_cdata`` (raw c10::Storage handle) rather than + # ``.data_ptr()`` so this is safe on fake/meta storages that would raise + # from ``.data_ptr()`` during AOT tracing. + if ( + aliased_base_tensor.untyped_storage()._cdata + != target_meta_tensor.untyped_storage()._cdata + ): + storage_offset = aliased_base_tensor.storage_offset() + storage_offset + if aliased_base_tensor.is_complex() and not target_meta_tensor.is_complex(): + aliased_out = torch.view_as_real(aliased_base_tensor).as_strided( + size, stride, storage_offset + ) + elif not aliased_base_tensor.is_complex() and target_meta_tensor.is_complex(): + aliased_out = torch.view_as_complex(aliased_base_tensor).as_strided( + size, stride, storage_offset + ) + else: + aliased_out = aliased_base_tensor.as_strided(size, stride, storage_offset) + # For outputs aliasing inputs, we need to check if the requires-gradness has changed. + aliased_out = patch_requires_grad(aliased_out) + # For outputs aliasing inputs, we need to check if the dtype has changed. + # as_strided() is the "most generic" view, but it does not cover cross-dtype views + if aliased_out.dtype != target_meta_tensor.dtype: + aliased_out = aliased_out.view(target_meta_tensor.dtype) + return aliased_out + + +def has_same_metadata(t1: Tensor, t2: Tensor) -> bool: + return ( + guard_or_false(sym_eq(t1.size(), t2.size())) + and guard_or_false(t1.layout == t2.layout) + and ( + is_sparse_any(t1) + or ( + guard_or_false(sym_eq(t1.stride(), t2.stride())) + and guard_or_false(t1.storage_offset() == t2.storage_offset()) + ) + ) + and t1.is_conj() == t2.is_conj() + and t1.is_neg() == t2.is_neg() + ) + + +@dataclass(frozen=True) +class MetadataKey: + """ + This should be equal whenever has_same_metadata would return True + """ + + size: tuple[SymIntEqByExpr, ...] + layout: torch.layout + is_sparse: bool + # these are empty when is_sparse + stride: tuple[SymIntEqByExpr, ...] | None + storage_offset: SymIntEqByExpr | None + is_conj: bool + is_neg: bool + + @staticmethod + def make(t: Tensor) -> MetadataKey: + is_sparse = is_sparse_any(t) + return MetadataKey( + size=tuple(SymIntEqByExpr(s) for s in t.size()), + layout=t.layout, + is_sparse=is_sparse, + stride=None if is_sparse else tuple(SymIntEqByExpr(s) for s in t.stride()), + storage_offset=None if is_sparse else SymIntEqByExpr(t.storage_offset()), + is_conj=t.is_conj(), + is_neg=t.is_neg(), + ) + + +# ViewMeta sequence wrapper for equality comparisons. +# +# Even though we can compare each ViewMeta instance, we compare the resulting +# tensor metadata, instead. That's because the creation of synthetic bases + the +# re-generation of input views might end-up creating a different sequence of +# ViewMeta that is semantically equivalent. i.e. gets to a tensor with the same +# metadata. +# +# Therefore, we store what the end result should look like as serializable +# metadata. +# +# When logging, this class should look like: +# +# ViewMetaSequence(view, select_int, slice_Tensor) +# +# i.e. a parenthesized list of view operations within that ViewMeta sequence. +class ViewMetaSequence: + def __init__(self, tensor: FunctionalTensor) -> None: + if not torch._is_functional_tensor(tensor.elem): + raise AssertionError("expected tensor.elem to be a functional tensor") + self.sequence = _functionalization.get_view_meta_sequence(tensor.elem) + self.metadata = MetadataKey.make(tensor) + + def __repr__(self) -> str: + suffix = len("_ViewMeta") + types = ", ".join(type(vm).__name__[:-suffix] for vm in self.sequence) + return f"ViewMetaSequence({types})" + + def __eq__(self, other: object) -> bool: + # If other is None, then it probably means that we weren't able to recreate + # the ViewMeta sequence. One example is when we update the view metadata by + # calling: create_synthetic_base_metadata. + if other is None: + return True + + # Comparison against any other type is not implemented. + if not isinstance(other, ViewMetaSequence): + return NotImplemented + + return self.metadata == other.metadata + + @classmethod + def _from_parts( + cls, sequence: list[_functionalization.ViewMeta], metadata: MetadataKey + ) -> ViewMetaSequence: + # Rebuild a ViewMetaSequence directly from its parts, bypassing the + # FunctionalTensor-based __init__. This lets the recipe be reconstructed from + # plain values rather than from a live FunctionalTensor or an embedded pickle. + # Sole caller: torch._functorch._aot_autograd.source_emit, when baking a + # ViewMetaSequence into standalone source; keep the attributes set here in sync + # with __init__ (sequence, metadata) or the reconstructed object diverges. + self = cls.__new__(cls) + self.sequence = sequence + self.metadata = metadata + return self + + +# new_arg and arg here are either: +# (1) both a FakeTensor +# (2) both a traceable tensor subclass that holds a FakeTensor +# Pre-condition: the two args are the "old" and "new" inputs from running functionalization. +# When we run functionalization and wrap our inputs into FunctionalTensors, +# we can detect whether or not an input was mutated by checking to see if the inner tensor has changed +# +# Normally it would be enough just to check if arg is new_arg, which is normally enough for functionalization +# to confirm that inputs were not mutated when running the user's model with functionalization on. +# But when we have subclass inputs, we can't rely on that: +# `from_fun(to_fun(x)) is x` will return False, because the call to `from_fun` constructs +# a brand new subclass instance: we are calling __tensor_unflatten__, and going +# from Subclass(FakeTensor) to Subclass(FunctionalTensor(FakeTensor)) +def was_tensor_updated(arg: torch.Tensor, new_arg: torch.Tensor) -> bool: + if is_traceable_wrapper_subclass(arg): + if not is_traceable_wrapper_subclass(new_arg): + raise AssertionError( + f"expected new_arg to be traceable wrapper subclass, got {type(new_arg)}" + ) + attrs, _ = arg.__tensor_flatten__() + new_attrs, _ = new_arg.__tensor_flatten__() + if attrs != new_attrs: + raise AssertionError(f"attrs mismatch: {attrs} != {new_attrs}") + # A tensor subclass was updated if any of its inner elements were updated + for attr in attrs: + match getattr(arg, attr): + case Tensor() as v: + if was_tensor_updated(v, getattr(new_arg, attr)): + return True + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + return False + else: + return arg is not new_arg + + +# new_arg and arg here are either: +# (1) both a FakeTensor +# (2) both a traceable tensor subclass that holds a FakeTensor +# Pre-condition: the two args are the "old" and "new" inputs from running functionalization. +# When we run functionalization and wrap our inputs into FunctionalTensors, +# we can detect whether or not an input was mutated by checking to see if the inner tensor has changed, +# but shares storage with the old input +def was_tensor_metadata_updated(arg: Any, new_arg: Any) -> bool: + if is_traceable_wrapper_subclass(arg): + if not is_traceable_wrapper_subclass(new_arg): + raise AssertionError( + f"expected new_arg to be traceable wrapper subclass, got {type(new_arg)}" + ) + attrs, _ = arg.__tensor_flatten__() + new_attrs, _ = new_arg.__tensor_flatten__() + if attrs != new_attrs: + raise AssertionError(f"attrs mismatch: {attrs} != {new_attrs}") + # A tensor subclass was updated if any of its inner elements were updated + for attr in attrs: + match getattr(arg, attr): + case Tensor() as v: + if was_tensor_metadata_updated(v, getattr(new_arg, attr)): + return True + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + return False + else: + return arg is not new_arg and StorageWeakRef( + arg.untyped_storage() + ) == StorageWeakRef(new_arg.untyped_storage()) + + +# Returns the number of detected copy_ +def _is_functional_graph(fx_g: torch.fx.Graph) -> tuple[str | None, int]: + allowed_mutation_ops = [ + torch.ops.aten.copy_.default, + torch.ops.aten.set_.source_Tensor, + torch.ops.aten.shallow_copy_data_.default, + ] + if hasattr(torch.ops.fsdp, "copy_"): + allowed_mutation_ops.append(torch.ops.fsdp.copy_.default) + + placeholders = set() + mutation_count = 0 + # NB: It would also be nice to verify that the mutations all happen at the + # end, but we also do some administrative views after mutations so this + # isn't actually true. (TODO: Could this cause problems for Inductor?) + error = None + for n in fx_g.nodes: + if n.op == "placeholder": + placeholders.add(n) + if isinstance(n.target, torch._ops.OpOverload): + if n.target in allowed_mutation_ops: + # Can only copy_/set_ into an input + # this is mostly a hack to avoid failing XLA tests. + # See https://github.com/pytorch/pytorch/pull/122434#issuecomment-2101012113 + if "set_buffer_donor_" not in str(n.args[0]): + if n.args[0] not in placeholders: + error = f"n={str(n)}, n.args[0]={str(n.args[0])}, placeholders={str(placeholders)}, graph={str(fx_g)}" + mutation_count += 1 + else: + if n.target._schema.is_mutable: + error = f"aot_autograd expected to have an entirely functional graph, but found {n.format_node()}" + return error, mutation_count + + +def assert_functional_graph(fx_g: torch.fx.Graph) -> int: + error, mutation_count = _is_functional_graph(fx_g) + if error is not None: + raise AssertionError(error) + return mutation_count + + +def propagate_input_mutation_stacktraces(fx_g: torch.fx.Graph) -> None: + placeholders = set() + for n in fx_g.nodes: + if n.op == "placeholder": + placeholders.add(n) + if isinstance(n.target, torch._ops.OpOverload): + if n.target is torch.ops.aten.copy_.default: + # Can only copy_ into an input, and can only do so once + if "set_buffer_donor_" not in str(n.args[0]): + if n.args[0] not in placeholders: + raise AssertionError( + f"n={str(n)}, n.args[0]={str(n.args[0])}, placeholders={str(placeholders)}, graph={str(fx_g)}" + ) + placeholders.remove(n.args[0]) + copy_from_node = n.args[1] + # Pre-condition: every node has a "stack_trace" field in its meta, + # but copy_() nodes do not (since we manually added them during functionalization). + # Instead, we manually propagate here. + if "stack_trace" in copy_from_node.meta: + n.meta["stack_trace"] = copy_from_node.meta["stack_trace"] + + +def _check_if_mutation_can_be_in_graph( + keep_input_mutations: bool, + mutates_data: bool, + mutates_metadata: bool, + mutations_hidden_from_autograd: bool, + mutations_under_no_grad_or_inference_mode: bool, + mutates_storage_metadata: bool, + mutation_inductor_storage_resize: bool, + requires_grad: bool, +) -> bool: + if keep_input_mutations: + in_graph = ( + mutates_data or mutates_storage_metadata or mutation_inductor_storage_resize + ) and ( + (not mutates_metadata and not requires_grad) + or mutations_hidden_from_autograd + or mutations_under_no_grad_or_inference_mode + ) + else: + in_graph = False + # See Note [set_() Input Mutations in AOTAutograd] + # If there was a `set_()`, we require that all mutations were under no_grad, + # so we can (safely) emit the set_() in the graph at runtime + # resize_() gets the same treatment + if mutation_inductor_storage_resize or mutates_storage_metadata: + op_name = "resize_" if mutation_inductor_storage_resize else "set_" + if not in_graph: + raise AssertionError(f"""\ +Encountered a {op_name} on a graph input, but the input has other mutations that we cannot +keep in the graph. This is not supported today. Current state: + keep_input_mutations={keep_input_mutations} + mutates_data={mutates_data} + mutates_metadata={mutates_metadata} + mutations_hidden_from_autograd={mutations_hidden_from_autograd} + mutations_under_no_grad_or_inference_mode={mutations_under_no_grad_or_inference_mode} + mutation_inductor_storage_resize={mutation_inductor_storage_resize} + requires_grad={requires_grad}""") + return in_graph diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/fx_utils.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/fx_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9446b9c4943b6f6f2336419085a20b7738d4a8ee --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/fx_utils.py @@ -0,0 +1,324 @@ +""" +This module contains utility functions for working with joint FX graphs with descriptors +that are produced by AOTAutograd. They will NOT work on generic FX graphs. See also +:func:`torch._functorch.aot_autograd.aot_export_joint_with_descriptors`. We also +recommend reading :mod:torch._functorch._aot_autograd.descriptors`. +""" + +from typing import NoReturn + +import torch.fx as fx + +from .descriptors import ( + AOTInput, + AOTOutput, + BufferAOTInput, + DifferentiableAOTInput, + DifferentiableAOTOutput, + GradAOTOutput, + ParamAOTInput, + PlainAOTInput, + PlainAOTOutput, + SubclassGetAttrAOTInput, + SubclassGetAttrAOTOutput, + TangentAOTInput, +) + + +def _raise_autograd_subclass_not_implemented( + n: fx.Node, desc: AOTInput | AOTOutput +) -> NoReturn: + raise RuntimeError( + "Subclasses are currently not supported by this function, but a desugared subclass input " + f"was found at {n} ({desc}). The problem is " + "that there may not necessarily be a 1-1 correspondence between primals/tangents/outputs/grads " + "when subclasses are involved: for example, the primal might be a plain tensor " + "but the tangent a tensor subclass that desugared into multiple plain tensors. " + "It is not clear what exactly you would like this function to do in this case " + "(Collect all nodes for the subclass together? Match up the inner nodes if " + "subclasses match exactly?) If you have a concrete use case, please file an " + "issue so we can understand it and design an API that works for your case." + ) + + +def get_all_input_and_grad_nodes( + g: fx.Graph, +) -> dict[DifferentiableAOTInput, tuple[fx.Node, fx.Node | None]]: + """ + Given a joint graph with descriptors (meta['desc'] on placeholders and + output), returns the node for every input and its corresponding grad + output node if it exists. These tuples are in a dict that is indexed by + the AOTInput descriptor that describes the input. + + NB: *all* forward tensor inputs are returned, including non-differentiable + inputs (which simply have a None grad), so it is safe to use this function + to perform operations on all inputs. (Non-tensor inputs like symbolic + integers, tokens or RNG state are NOT traversed by this function.) + + Args: + g: The FX joint graph with descriptors + + Returns: + A dictionary mapping each DifferentiableAOTInput descriptor to a tuple + containing: + - The input node itself + - The grad (output) node if it exists, None otherwise + + Raises: + RuntimeError: If the joint graph has subclass tensor inputs/outputs; this + is not supported by API as there is not necessarily a 1-1 correspondence + between inputs and grads when subclasses are involved. + """ + input_index: dict[DifferentiableAOTInput, tuple[fx.Node, fx.Node | None]] = {} + for n in g.nodes: + if n.op == "placeholder": + desc = n.meta["desc"] + # Skip inputs that cannot possibly be differentiable + if not isinstance(desc, DifferentiableAOTInput): + continue + if isinstance(desc, SubclassGetAttrAOTInput): + _raise_autograd_subclass_not_implemented(n, desc) + + input_index[desc] = (n, None) + elif n.op == "output": + if "desc" not in n.meta: + raise AssertionError(f"'desc' not in n.meta for {n}: {n.meta}") + desc = n.meta["desc"] + for sub_n, sub_desc in zip(n.args[0], desc): + if isinstance(sub_desc, SubclassGetAttrAOTOutput): + _raise_autograd_subclass_not_implemented(sub_n, sub_desc) + if isinstance(sub_desc, GradAOTOutput): + inp, grad = input_index[sub_desc.grad_of] + if grad is not None: + raise AssertionError( + f"grad already set for {sub_n}, {sub_desc}, {input_index}" + ) + input_index[sub_desc.grad_of] = (inp, sub_n) + return input_index + + +def get_all_output_and_tangent_nodes( + g: fx.Graph, +) -> dict[DifferentiableAOTOutput, tuple[fx.Node, fx.Node | None]]: + """Get all output nodes and their corresponding tangent nodes from a joint graph. + + Similar to get_all_input_and_grad_nodes, but returns output nodes paired with + their tangent nodes (if they exist). This function traverses the graph to find + all differentiable outputs and matches them with their corresponding tangent + inputs used in forward-mode autodiff. + + NB: *all* forward tensor outputs are returned, including non-differentiable outputs, + so you can use this function to perform operations on all outputs. + + Args: + g: The FX joint graph with descriptors + + Returns: + A dictionary mapping each DifferentiableAOTOutput descriptor to a tuple + containing: + - The output node itself + - The tangent (input) node if it exists, None otherwise + + Raises: + RuntimeError: If the joint graph has subclass tensor inputs/outputs; this + is not supported by API as there is not necessarily a 1-1 correspondence + between outputs and tangents when subclasses are involved. + """ + output_index: dict[DifferentiableAOTOutput, tuple[fx.Node, fx.Node | None]] = {} + for n in g.nodes: + if n.op == "output": + desc = n.meta["desc"] + for sub_n, sub_d in zip(n.args[0], desc): + # Skip outputs that cannot possibly be differentiable + if not isinstance(sub_d, DifferentiableAOTOutput): + continue + if isinstance(sub_d, SubclassGetAttrAOTOutput): + _raise_autograd_subclass_not_implemented(sub_n, sub_d) + + output_index[sub_d] = (sub_n, None) + for n in g.nodes: + if n.op == "placeholder": + desc = n.meta["desc"] + if isinstance(desc, SubclassGetAttrAOTInput): + _raise_autograd_subclass_not_implemented(n, desc) + if isinstance(desc, TangentAOTInput): + out, tangent = output_index[desc.output] + if tangent is not None: + raise AssertionError( + f"tangent already set for {n}, {desc}, {output_index}" + ) + output_index[desc.output] = (out, n) + return output_index + + +def get_param_and_grad_nodes( + graph: fx.Graph, +) -> dict[ParamAOTInput, tuple[fx.Node, fx.Node | None]]: + """Get parameter nodes and their corresponding gradient nodes from a joint graph. + + Args: + graph: The FX joint graph with descriptors + + Returns: + A dictionary mapping each ParamAOTInput descriptor to a tuple containing: + - The parameter input node + - The gradient (output) node if it exists, None otherwise + """ + return { + desc: (n, g) + for desc, (n, g) in get_all_input_and_grad_nodes(graph).items() + if isinstance(desc, ParamAOTInput) + } + + +def get_plain_input_and_grad_nodes( + graph: fx.Graph, +) -> dict[PlainAOTInput, tuple[fx.Node, fx.Node | None]]: + """Get plain input nodes and their corresponding gradient nodes from a joint graph. + + Args: + graph: The FX joint graph with descriptors + + Returns: + A dictionary mapping each PlainAOTInput descriptor to a tuple containing: + - The plain input node + - The gradient (output) node if it exists, None otherwise + """ + return { + desc: (n, g) + for desc, (n, g) in get_all_input_and_grad_nodes(graph).items() + if isinstance(desc, PlainAOTInput) + } + + +def get_plain_output_and_tangent_nodes( + graph: fx.Graph, +) -> dict[PlainAOTOutput, tuple[fx.Node, fx.Node | None]]: + """Get plain output nodes and their corresponding tangent nodes from a joint graph. + + Args: + graph: The FX joint graph with descriptors + + Returns: + A dictionary mapping each PlainAOTOutput descriptor to a tuple containing: + - The plain output node + - The tangent (input) node if it exists, None otherwise + """ + return { + desc: (n, g) + for desc, (n, g) in get_all_output_and_tangent_nodes(graph).items() + if isinstance(desc, PlainAOTOutput) + } + + +def _raise_fqn_subclass_not_implemented( + n: fx.Node, desc: AOTInput | AOTOutput +) -> NoReturn: + raise RuntimeError( + "Subclasses are currently not supported by this function, but a desugared subclass input " + f"was found at {n} ({desc}). The problem is " + "that there may not necessarily be a 1-1 correspondence between a FQN and a plain tensor " + "when subclasses are involved: for example, a parameter that is a subclass " + "would desugar into multiple plain tensors, which we can't uniquely assign the " + "FQN to. It's not clear what you want the API to do in this case: do you want to " + "instead return a struct of nodes showing how to assemble the subclass? But you " + "don't (directly) have the metadata for the subclass? If you have a concrete use " + "case, please file an issue so we can understand it and design an API that works for your case." + ) + + +def get_named_param_nodes(graph: fx.Graph) -> dict[str, fx.Node]: + """Get parameter nodes mapped by their fully qualified names. + + This function traverses the graph to find all parameter input nodes and + returns them in a dictionary where keys are the parameter names (FQNs) + and values are the corresponding FX nodes. + + Args: + graph: The FX joint graph with descriptors + + Returns: + A dictionary mapping parameter names (str) to their corresponding FX nodes. + + Raises: + RuntimeError: If subclass tensors are encountered (not yet supported), as + with subclasses a FQN does not necessarily map to a single plain tensor. + """ + r = {} + for n in graph.nodes: + if n.op == "placeholder": + desc = n.meta["desc"] + if isinstance(desc, SubclassGetAttrAOTInput): + _raise_fqn_subclass_not_implemented(n, desc) + elif isinstance(desc, ParamAOTInput): + r[desc.target] = n + return r + + +def get_named_buffer_nodes(graph: fx.Graph) -> dict[str, fx.Node]: + """Get buffer nodes mapped by their fully qualified names. + + This function traverses the graph to find all buffer input nodes and + returns them in a dictionary where keys are the buffer names (FQNs) + and values are the corresponding FX nodes. + + Args: + graph: The FX joint graph with descriptors + + Returns: + A dictionary mapping buffer names (str) to their corresponding FX nodes. + + Raises: + RuntimeError: If subclass tensors are encountered (not yet supported), as + with subclasses a FQN does not necessarily map to a single plain tensor. + """ + r = {} + for n in graph.nodes: + if n.op == "placeholder": + desc = n.meta["desc"] + if isinstance(desc, SubclassGetAttrAOTInput): + _raise_fqn_subclass_not_implemented(n, desc) + elif isinstance(desc, BufferAOTInput): + r[desc.target] = n + return r + + +def get_param_nodes(graph: fx.Graph) -> list[fx.Node]: + """Get all parameter nodes from a graph as a list. + + You can rely on this providing the correct order of parameters you need + to feed into the joint graph (at the very beginning of the argument list, + before buffers). + + Args: + graph: The FX joint graph with descriptors + + Returns: + A list of FX nodes representing all parameters in the graph. + + Raises: + RuntimeError: If subclass tensors are encountered (not yet supported), as + it is not clear if you wanted each individual constituent piece of the + subclasses, or have them grouped up in some way. + """ + return list(get_named_param_nodes(graph).values()) + + +def get_buffer_nodes(graph: fx.Graph) -> list[fx.Node]: + """Get all buffer nodes from a graph as a list. + + You can rely on this providing the correct order of buffers you need + to feed into the joint graph (after parameters). + + Args: + graph: The FX joint graph with descriptors + + Returns: + A list of FX nodes representing all buffers in the graph. + + Raises: + RuntimeError: If subclass tensors are encountered (not yet supported), as + it is not clear if you wanted each individual constituent piece of the + subclasses, or have them grouped up in some way. + """ + return list(get_named_buffer_nodes(graph).values()) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/graph_capture.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/graph_capture.py new file mode 100644 index 0000000000000000000000000000000000000000..a511ce7d91d0edfff9a0d467a35b91e10f51313a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/graph_capture.py @@ -0,0 +1,590 @@ +""" +This module dispatches the graphs to either the forward-only or joint compilation +pathways, taking into account the AOTConfig and the collected ViewAndMutationMetadata. +""" + +import contextlib +import dataclasses +from collections.abc import Callable +from typing import Any + +import torch +import torch.utils._pytree as pytree +import torch.utils.dlpack +from torch._dispatch.python import enable_python_dispatcher +from torch._dynamo.utils import detect_fake_mode, lazy_format_graph_code +from torch._logging import getArtifactLogger, trace_structured +from torch._subclasses.functional_tensor import FunctionalTensorMode +from torch.fx.experimental.proxy_tensor import make_fx +from torchgen.utils import dataclass_repr + +from .. import config +from .descriptors import AOTInput, BackwardTokenAOTInput +from .functional_utils import ( + assert_functional_graph, + propagate_input_mutation_stacktraces, +) +from .graph_capture_wrappers import ( + aot_dispatch_subclass, + create_functionalized_fn, + create_joint, + fn_input_mutations_to_outputs, + fn_prepped_for_autograd, + handle_effect_tokens_fn, +) +from .schemas import AOTConfig, FxValue, SubclassMeta, TraceFn, ViewAndMutationMeta +from .streams import ( + assign_backward_streams, + assign_epilogue_copy_streams, + insert_backward_syncs, + populate_fw_metadata_with_stream_indices, + sync_deallocations, + wrap_all_sync_nodes_with_control_deps, +) +from .utils import ( + call_and_expect_output_descs, + copy_fwd_metadata_to_bw_nodes, + fn_wrappers, + register_buffer_assignment_hook, + root_module_when_exporting_non_strict, + simple_wraps, + unlift_tokens, +) + + +aot_graphs_log = getArtifactLogger(__name__, "aot_graphs") + + +def _extract_tangent_source_stack_traces( + fx_g: torch.fx.GraphModule, + fw_metadata: ViewAndMutationMeta, +) -> None: + from .descriptors import PlainAOTOutput, TangentAOTInput + + if not fw_metadata.traced_tangents_descs: + return + + output_node = list(fx_g.graph.nodes)[-1] + all_outputs = output_node.args[0] + + stack_traces: list[str | None] = [] + got_one = False + + for desc in fw_metadata.traced_tangents_descs: + stack_trace = None + + if isinstance(desc, TangentAOTInput): + output_desc = desc.output + if isinstance(output_desc, PlainAOTOutput) and output_desc.idx < len( + all_outputs + ): + output_arg = all_outputs[output_desc.idx] + if isinstance(output_arg, torch.fx.Node): + stack_trace = output_arg.meta.get("stack_trace", None) + got_one = True + + stack_traces.append(stack_trace) + + if got_one: + fw_metadata.tangent_source_stack_traces = stack_traces + + +def _create_graph( + f: Callable[..., Any], + args: list[torch.Tensor], + args_descs: list[AOTInput] + | None = None, # keep compat with old clients; maybe we should split into two impls + *, + aot_config: AOTConfig, +) -> torch.fx.GraphModule: + # FunctionalTensorMode must be enabled here. + # See Note [Accessing .grad_fn on FunctionalTensor] + out_descs = None + + if args_descs is None: + inner_f = f + else: + + @simple_wraps(f) + def inner_f(*args: Any) -> Any: + nonlocal out_descs + if out_descs is not None: + raise AssertionError("out_descs must be None") + out, out_descs = call_and_expect_output_descs(f, args) + return out + + if aot_config.disable_functionalization: + ctx = contextlib.nullcontext() + else: + ctx = FunctionalTensorMode( # type: ignore[assignment] + pre_dispatch=aot_config.pre_dispatch, + export=aot_config.is_export, + # Allow token discovery for joint fn tracing as tokens can be used in backward. + _allow_token_discovery=True, + _keep_input_mutations=aot_config.keep_inference_input_mutations, + ) + + with ( + enable_python_dispatcher(), + ctx, + torch._dynamo.eval_frame._use_eager_on_nested_compile(), + ): + fx_g = make_fx( + inner_f, + decomposition_table=aot_config.decompositions, + record_module_stack=True, + pre_dispatch=aot_config.pre_dispatch, + _disable_torch_fn_metadata_mode=aot_config._disable_torch_fn_metadata_mode, + )(*args) + + if args_descs is not None: + flat_args_descs, _ = pytree.tree_flatten(args_descs) + flat_out_descs, _ = pytree.tree_flatten(out_descs) + + # Unfortunately, flat_args_descs is not guaranteed to match the + # number of actual arguments that show up on the FX graph. + # Specifically, allow_token_discovery=True means that we will + # silently add extra token arguments to the backwards graph. + # + # Although there are a few ways to detect what these tokens are, + # we are going to settle for something dodgy but simple to + # implement: match tangents_token placeholders specifically, + # as these are the only placeholders that are created by token + # discovery (NB: there is NO other code that treats this name + # as load bearing, so this is a bit naughty!) + # + # I originally wanted to detect tokens in exactly the same way + # that they are detected at normal runtime, but to be honest + # the normal runtime detection is pretty strange: it seems the + # backward tokens are not reliably at the end of the argument list + # but *precede* the RNG arguments (I don't understand why this is + # the case). And in unlift_tokens, token arguments are detected + # by seeing if they feed into an effects call! Dastardly. Why + # didn't we just introduce a new type. + + i = 0 + j = 0 + for n in fx_g.graph.nodes: + if n.op == "placeholder": + if n.name.startswith("tangents_token"): + n.meta["desc"] = BackwardTokenAOTInput(j) + j += 1 + else: + if i >= len(flat_args_descs): + raise AssertionError( + f"i={i} >= len(flat_args_descs)={len(flat_args_descs)}: " + f"fn_wrappers={fn_wrappers(inner_f)}, " + f"placeholders={[n for n in fx_g.graph.nodes if n.op == 'placeholder']}" + ) + n.meta["desc"] = flat_args_descs[i] + i += 1 + elif n.op == "output": + n.meta["desc"] = flat_out_descs + + return fx_g + + +# TODO: Refactor the following code so detach() persists item_memo +def _detach_and_copy_item_memo(t: torch.Tensor) -> torch.Tensor: + detached_t = t.detach() + if hasattr(t, "item_memo"): + # pyrefly: ignore[missing-attribute] + detached_t.item_memo = t.item_memo + return detached_t + + +@dataclasses.dataclass +class _GraphCaptureTracingResult: + fn_to_trace: Callable[..., Any] + flat_args: Any + flat_args_descs: Any + maybe_subclass_meta: SubclassMeta | None + + +def _detach_traced_inputs(flat_args: Any) -> Any: + if detect_fake_mode(): + detach_tensor = _detach_and_copy_item_memo + else: + + def detach_tensor(t: torch.Tensor) -> torch.Tensor: + return t.detach() + + return pytree.tree_map_only(torch.Tensor, detach_tensor, flat_args) + + +def _prepare_graph_capture_tracing( + fn_to_trace: Callable[..., Any], + flat_args: Any, + flat_args_descs: Any, + flat_fn: TraceFn, + *, + fw_metadata: ViewAndMutationMeta, + aot_config: AOTConfig, + trace_joint: bool, + joint_fn_handle: Any | None = None, +) -> _GraphCaptureTracingResult: + if aot_config.disable_functionalization: + updated_flat_args, updated_flat_args_descs = flat_args, flat_args_descs + else: + fn_to_trace, updated_flat_args, updated_flat_args_descs = ( + create_functionalized_fn( + fn_to_trace, + flat_args, + flat_args_descs, + meta=fw_metadata, + aot_config=aot_config, + trace_joint=trace_joint, + joint_fn_handle=joint_fn_handle, + ) + ) + + subclass_tracing_info = aot_dispatch_subclass( + fn_to_trace, + updated_flat_args, + updated_flat_args_descs, + is_joint_structure=trace_joint, + meta=fw_metadata, + fw_only=flat_fn, + ) + fn_to_trace = subclass_tracing_info.plain_tensor_trace_fn + updated_flat_args = subclass_tracing_info.plain_tensor_args + updated_flat_args_descs = subclass_tracing_info.plain_tensor_args_descs + + if not aot_config.disable_functionalization: + fn_to_trace, updated_flat_args, updated_flat_args_descs = ( + handle_effect_tokens_fn( + fn_to_trace, + updated_flat_args, + updated_flat_args_descs, + meta=fw_metadata, + trace_joint=trace_joint, + ) + ) + return _GraphCaptureTracingResult( + fn_to_trace=fn_to_trace, + flat_args=updated_flat_args, + flat_args_descs=updated_flat_args_descs, + maybe_subclass_meta=subclass_tracing_info.maybe_subclass_meta, + ) + + +def _create_graph_and_save_traced_inputs( + fn_to_trace: Callable[..., Any], + flat_args: Any, + flat_args_descs: Any, + *, + aot_config: AOTConfig, +) -> tuple[torch.fx.GraphModule, Any]: + saved_flat_args = _detach_traced_inputs(flat_args) + return ( + _create_graph(fn_to_trace, flat_args, flat_args_descs, aot_config=aot_config), + saved_flat_args, + ) + + +def aot_dispatch_base_graph( + flat_fn: TraceFn, + flat_args: list[FxValue], + flat_args_descs: list[AOTInput], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, +) -> tuple[torch.fx.GraphModule, list[FxValue], list[AOTInput], SubclassMeta | None]: + # aot_dispatch_base requires functionalization, but doesn't need to handle as many cases as the autograd case. + # The cases that aot_dispatch_base doesn't need to handle include: + # - outputs that are aliases of graph intermediates + # - outputs that are aliases of graph inputs + # While cases that it does need to handle include: + # - input mutations (including when inputs are aliases of each other) + # - input metadata mutations + fn_to_trace = fn_input_mutations_to_outputs( + flat_fn, + flat_args_descs, + fw_metadata, + keep_data_input_mutations=aot_config.keep_inference_input_mutations, + ) + # TODO: replace with AOTDispatchSubclassWrapper once we refactor + # fn_input_mutations_to_outputs and create_functionalized_fn + # into CompilerWrappers. + tracing_state = _prepare_graph_capture_tracing( + fn_to_trace, + flat_args, + flat_args_descs, + flat_fn, + fw_metadata=fw_metadata, + aot_config=aot_config, + trace_joint=False, + ) + fn_to_trace = tracing_state.fn_to_trace + updated_flat_args_subclasses_desugared = tracing_state.flat_args + updated_flat_args_subclasses_desugared_descs = tracing_state.flat_args_descs + maybe_subclass_meta = tracing_state.maybe_subclass_meta + + aot_graphs_log.debug( + "aot_config id: %s, fw_metadata=%s,subclass_metadata=%s", + aot_config.aot_id, + fw_metadata, + maybe_subclass_meta, + ) + + # We track buffer assignments when exporting in non-strict mode. + # (In contrast, strict mode errors on any attribute assignment.) + mod_when_exporting_non_strict = root_module_when_exporting_non_strict(flat_fn) + assigned_buffers: dict[str, str] = {} + hook = None + if aot_config.is_export and mod_when_exporting_non_strict is not None: + # For any buffer that is assigned, we want to associate it to the final proxy node + # that it is assigned to. This node can then be added as a buffer mutation output. + hook = register_buffer_assignment_hook( + mod_when_exporting_non_strict, assigned_buffers + ) + + try: + ( + fw_module, + saved_updated_flat_args_subclasses_desugared, + ) = _create_graph_and_save_traced_inputs( + fn_to_trace, + updated_flat_args_subclasses_desugared, + updated_flat_args_subclasses_desugared_descs, + aot_config=aot_config, + ) + finally: + if hook is not None: + hook.remove() + hook = None + saved_updated_flat_args_subclasses_desugared_descs = ( + updated_flat_args_subclasses_desugared_descs + ) + + if aot_config.is_export and mod_when_exporting_non_strict is not None: + # We update metadata to consider any assigned buffers as buffer mutations. + i = len(dict(mod_when_exporting_non_strict.named_parameters())) + for name, _ in mod_when_exporting_non_strict.named_buffers(): + if name in assigned_buffers and not fw_metadata.input_info[i].mutates_data: + fw_metadata.input_info[i] = dataclasses.replace( + fw_metadata.input_info[i], mutates_data=True + ) + fw_metadata.num_mutated_inp_runtime_indices += 1 + i += 1 + + # We add nodes corresponding to buffer assignments as output nodes in the graph. + add_nodes = [] + output_node = list(fw_module.graph.nodes)[-1] + for name in assigned_buffers.values(): + for node in fw_module.graph.nodes: + if node.name == name: + add_nodes.append(node) + node.users[output_node] = None + output_node.args = ((*add_nodes, *output_node.args[0]),) + + # As long as we opted to remove input mutations, then + # there should be *NO* mutating ops in the graph at this point. + if not aot_config.disable_functionalization: + copy_count = assert_functional_graph(fw_module.graph) + assign_epilogue_copy_streams(fw_module) + # Wrap sync nodes with control_deps to prevent reordering + wrap_all_sync_nodes_with_control_deps(fw_module) + # Populate fw_metadata with stream indices from the compiled graph + populate_fw_metadata_with_stream_indices(fw_module, fw_metadata) + fw_module.graph.eliminate_dead_code() + fw_module.recompile() + copy_count2 = assert_functional_graph(fw_module.graph) + propagate_input_mutation_stacktraces(fw_module.graph) + if copy_count != copy_count2: + raise AssertionError( + f"copy_count={copy_count} != copy_count2={copy_count2}" + ) + else: + fw_module.graph.eliminate_dead_code() + + # See Note [Side-Effectful Tokens in AOTAutograd] + num_tokens = len(fw_metadata.tokens) + if num_tokens != 0 and config.unlift_effect_tokens: + unlift_tokens(fw_module, fw_metadata, aot_config) + saved_updated_flat_args_subclasses_desugared = ( + saved_updated_flat_args_subclasses_desugared[num_tokens:] + ) + saved_updated_flat_args_subclasses_desugared_descs = ( + saved_updated_flat_args_subclasses_desugared_descs[num_tokens:] + ) + + if aot_config.enable_log: + aot_graphs_log.info( + "%s", + lazy_format_graph_code( + "Forward graph", + fw_module, + aot_config.aot_id, + include_stride=True, + include_device=True, + colored=True, + # For more expanded output set this to True (but can't default + # to this because it affects tests): + expanded_def=False, + ), + ) + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "aot_forward_graph_fw_metadata", + "encoding": "string", + }, + payload_fn=lambda: dataclass_repr(fw_metadata), + ) + if maybe_subclass_meta is not None: + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "aot_forward_graph_fw_subclass_metadata", + "encoding": "string", + }, + payload_fn=lambda: dataclass_repr(maybe_subclass_meta), + ) + + trace_structured( + "aot_inference_graph", + payload_fn=lambda: fw_module.print_readable( + print_output=False, + include_stride=True, + include_device=True, + expanded_def=True, + ), + ) + + # TODO: should factor this into a separate function for export that always only returns just the graph. + if aot_config.is_export and maybe_subclass_meta is not None: + raise AssertionError( + "aot_export_module does not support tensor subclass inputs for now." + ) + return ( + fw_module, + saved_updated_flat_args_subclasses_desugared, + saved_updated_flat_args_subclasses_desugared_descs, + maybe_subclass_meta, + ) + + +# Has the precondition that there +# are no duplicate arguments in flat_args (e.g., the same Tensor +# object never shows up twice. However, two tensor inputs MAY alias +# the same storage, so long as they have separate TensorImpls.) +def aot_dispatch_autograd_graph( + flat_fn: TraceFn, + flat_args: list[Any], + flat_args_descs: list[AOTInput], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, +) -> tuple[ + torch.fx.GraphModule, + tuple[list[Any], list[Any]], + tuple[list[AOTInput], list[AOTInput]], + SubclassMeta | None, +]: + # NB: flat_fn here is the original user function (as far as + # aot_module_simplified is concerned) + + # traced_tangents corresponds to the set of outputs in the traced forward that should get grad_outputs in the traced backward. + # It includes outputs of the original forward, *and* any updated inputs due to input mutations. + # However, it does *not* include any outputs that are aliases of inputs or intermediates, or any metadata-only input mutations. + joint_inputs = (flat_args, fw_metadata.traced_tangents) + joint_inputs_descs = (flat_args_descs, fw_metadata.traced_tangents_descs) + + fn_prepared_for_autograd = fn_prepped_for_autograd( + flat_fn, + flat_args_descs, + fw_metadata, + aot_config, + ) + joint_fn_to_trace = create_joint( + fn_prepared_for_autograd, flat_args_descs, aot_config=aot_config + ) + # pyrefly: ignore[missing-attribute] + joint_fn_handle = joint_fn_to_trace.handle + # TODO: replace with AOTDispatchSubclassWrapper once we refactor + # fn_input_mutations_to_outputs and create_functionalized_fn + # into CompilerWrappers. + tracing_state = _prepare_graph_capture_tracing( + joint_fn_to_trace, + joint_inputs, + joint_inputs_descs, + flat_fn, + fw_metadata=fw_metadata, + aot_config=aot_config, + trace_joint=True, + joint_fn_handle=joint_fn_handle, + ) + joint_fn_to_trace = tracing_state.fn_to_trace + updated_joint_inputs = tracing_state.flat_args + updated_joint_inputs_descs = tracing_state.flat_args_descs + maybe_subclass_meta = tracing_state.maybe_subclass_meta + + # When we call _create_graph, this may mutate the metadata of joint + # inputs. But callers are expecting to get the original joint inputs. So + # we make aliases of all the inputs to make sure we have a copy that + # doesn't get modified. + # + # This destroys requires_grad/grad_fn information. However, backends + # beneath AOTAutograd are indifferent to this information, so it doesn't + # matter. + fx_g, saved_updated_joint_inputs = _create_graph_and_save_traced_inputs( + joint_fn_to_trace, + updated_joint_inputs, + updated_joint_inputs_descs, + aot_config=aot_config, + ) + + # Redundant with the check above, but worth having in case tracing introduced + # a fake tensor. Unlikely. + # See Note: [Fake Modules and AOTAutograd] + torch._dynamo.utils.assert_no_fake_params_or_buffers(fx_g) + + # Have to copy before eliminate_dead_code otherwise the + # fw node match might be erased + copy_fwd_metadata_to_bw_nodes(fx_g) + + # After copying metadata, assign streams to gradient accumulation nodes + assign_backward_streams(fx_g) + + assign_epilogue_copy_streams(fx_g) + + # Insert syncs for newly assigned backward streams + insert_backward_syncs(fx_g) + + # Sync deallocations for tensors where the stream w/ their last usage + # is distinct from their allocation stream + sync_deallocations(fx_g) + + # Wrap sync nodes with control_deps to prevent reordering + # (must be after sync_deallocations which inserts additional sync nodes) + wrap_all_sync_nodes_with_control_deps(fx_g) + + # Populate fw_metadata with stream indices from the compiled graph + # NB: This needs to be done after the above stream assignments + populate_fw_metadata_with_stream_indices(fx_g, fw_metadata) + + # this helps users identify which forward output to call .detach() on. + _extract_tangent_source_stack_traces(fx_g, fw_metadata) + + fx_g.graph.eliminate_dead_code() + if not aot_config.disable_functionalization: + # There should be *NO* mutating ops in the graph at this point. + assert_functional_graph(fx_g.graph) + + fx_g.recompile() + + # TODO: in AOTAutograd, we create metadata like _indices_of_inps_to_detach to detect + # when we need to manually detach() some inputs in the forward. + # Higher order ops might eventually need to do the same. + if aot_config.is_export and maybe_subclass_meta is not None: + raise AssertionError( + "aot_export_module does not support tensor subclass inputs for now." + ) + return ( + fx_g, + saved_updated_joint_inputs, + updated_joint_inputs_descs, + maybe_subclass_meta, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/graph_capture_wrappers.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/graph_capture_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..5b3ee4992d30dfcf96339b88554f97e24814522c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/graph_capture_wrappers.py @@ -0,0 +1,1557 @@ +""" +This module is responsible for transforming functions to be traced into a form +that is easier for the downstream infra (e.g. Autograd, FX, AOTAutograd analysis) +to handle. + +It does so by: +1. functionalization (including RNG functionalzation) +2. creating a joint graph when required +3. transforming mutations into extra outputs +4. dispatching subclasses +""" + +import typing +import warnings +from collections.abc import Callable, Generator +from contextlib import AbstractContextManager, contextmanager, ExitStack, nullcontext +from dataclasses import dataclass +from typing import Any, TypeVar +from unittest.mock import patch + +import torch +import torch.fx.traceback as fx_traceback +import torch.utils._pytree as pytree +from torch import Tensor +from torch._custom_class_base import CustomClassBase +from torch._decomp.decompositions_for_rng import PhiloxStateTracker +from torch._guards import detect_fake_mode +from torch._prims_common import CUDARngStateHelper +from torch.fx.experimental.proxy_tensor import ( + _proxy_tensor_disable_update_tensor_tracker, + get_proxy_mode, + maybe_disable_thunkify, + maybe_enable_thunkify, +) +from torch.fx.experimental.symbolic_shapes import ( + guard_or_true, + PropagateUnbackedSymInts, + sym_eq, +) +from torch.nn.utils import stateless +from torch.utils._python_dispatch import is_traceable_wrapper_subclass +from torch.utils._pytree import TreeSpec + +from .. import config +from .collect_metadata_analysis import run_functionalized_fw_and_collect_metadata +from .descriptors import ( + AOTInput, + AOTOutput, + BackwardTokenAOTOutput, + ForwardTokenAOTInput, + ForwardTokenAOTOutput, + GradAOTOutput, + InputMutationAOTOutput, + IntermediateBaseAOTOutput, + PhiloxBackwardBaseOffsetAOTInput, + PhiloxBackwardSeedAOTInput, + PhiloxForwardBaseOffsetAOTInput, + PhiloxForwardSeedAOTInput, + PhiloxUpdatedBackwardOffsetAOTOutput, + PhiloxUpdatedForwardOffsetAOTOutput, +) +from .functional_utils import ( + _check_if_mutation_can_be_in_graph, + are_all_mutations_hidden_from_autograd, + are_all_mutations_under_no_grad_or_inference_mode, + from_fun, + has_data_mutation, + has_metadata_mutation, + is_fun, + sync_functional_tensor, + to_fun, + was_inductor_storage_resized, +) +from .logging_utils import setup_stacktrace_preservation_hooks +from .schemas import ( + AOTConfig, + FxValue, + InputAliasInfo, + JointTraceFn, + MutationType, + OutputType, + PreppedForAutogradTraceFn, + SubclassMeta, + SubclassTracingInfo, + TraceFn, + ViewAndMutationMeta, +) +from .subclass_utils import ( + create_subclass_meta, + remap_unwrapped_subclass_arg_indices, + requires_subclass_dispatch, + unwrap_tensor_subclasses, + wrap_tensor_subclasses_maybe_joint, +) +from .utils import ( + _is_tangent, + call_and_expect_output_descs, + maybe_to_fresh_input, + simple_wraps, + without_output_descs, +) + + +# This function returns a new function that returns mutated inputs as outputs. +# if keep_data_input_mutations is set, then we assume that data-only mutations +# will be left in the graph, and we only return metadata-mutated inputs as outputs. +def fn_input_mutations_to_outputs( + fn: Callable[..., Any], + args_descs: list[AOTInput], + meta: ViewAndMutationMeta, + keep_data_input_mutations: bool, +) -> Any: + @simple_wraps(fn) + def inner_fn(*args: FxValue) -> tuple[tuple[Any, ...], tuple[Any, ...]]: + outs, outs_descs = call_and_expect_output_descs(fn, args) + if len(meta.output_info) != len(outs): + raise AssertionError( + f"output_info length ({len(meta.output_info)}) != outs length ({len(outs)})" + ) + # The compiled fw will return mutated input tensors, *including* metadata-only mutation. + # However, if keep_data_input_mutations is set, the compiled fw only needs to return metadata-mutated inputs. + # (because data-only input mutations are handled directly in the compiled graph) + mutated_input_pairs = [ + (x, InputMutationAOTOutput(src)) + for (i, (x, src)) in enumerate(zip(args, args_descs)) + if i in meta.mutated_inp_runtime_indices + ] + if mutated_input_pairs: + mutated_inputs_to_return, mutated_inputs_to_return_descs = zip( + *mutated_input_pairs + ) + else: + mutated_inputs_to_return, mutated_inputs_to_return_descs = (), () + return ( + (*mutated_inputs_to_return, *outs), + (*mutated_inputs_to_return_descs, *outs_descs), + ) + + return inner_fn + + +@contextmanager +def disable_autocast() -> Generator[None, None, None]: + with ExitStack() as stack: + autocast_enabled_devices = torch._C._autocast_supported_devices() + for device_type in autocast_enabled_devices: + if hasattr(torch, device_type): + stack.enter_context(torch.amp.autocast(device_type, enabled=False)) + yield + + +# This function takes in a fn with external aliasing and mutation, +# and returns a new fn with no external aliasing and mutation, +# as needed for autograd. +# The main transformations are: +# - Return mutated inputs as extra outputs +# - Clone mutated inputs that require gradients, +# because autograd will require us to pass the pre-mutated inputs into autograd.grad +# - Return intermediate bases of outputs as additional outputs, +# needed to appease autograd.Function +# The new function returns: +# (1) The updated outputs +# (2) A boolean mask of len(new_fn_outputs), +# that can be used to tell autograd.grad which outputs should get tangents +# if we trace the backward. +def fn_prepped_for_autograd( + fn: TraceFn, + args_descs: list[AOTInput], + meta: ViewAndMutationMeta, + aot_config: AOTConfig, +) -> PreppedForAutogradTraceFn: + @simple_wraps(fn) + def inner_fn( + *args: FxValue, + ) -> tuple[tuple[list[FxValue], list[bool]], list[AOTOutput]]: + args_maybe_cloned = [ + maybe_to_fresh_input(i, t, meta) for i, t in enumerate(args) + ] + + outs, outs_descs = call_and_expect_output_descs(fn, args_maybe_cloned) # type: ignore[arg-type] + if not isinstance(outs, (tuple, list)): + raise AssertionError(f"expected outs to be tuple or list, got {type(outs)}") + outs = list(outs) + if len(meta.output_info) != len(outs): + raise AssertionError( + f"output_info length ({len(meta.output_info)}) != outs length ({len(outs)})" + ) + + mutated_input_pairs = [ + (x, InputMutationAOTOutput(src)) + for (i, (x, src)) in enumerate(zip(args_maybe_cloned, args_descs)) + if i in meta.mutated_inp_runtime_indices + ] + if mutated_input_pairs: + mutated_inputs_to_return, mutated_inputs_to_return_descs = zip( + *mutated_input_pairs + ) + else: + mutated_inputs_to_return, mutated_inputs_to_return_descs = (), () + + intermediate_bases = [] + intermediate_bases_descs = [] + for o, info, o_desc in zip(outs, meta.output_info, outs_descs): + if info.output_type == OutputType.alias_of_intermediate_save_as_output: + if not isinstance(o, torch.Tensor): + raise AssertionError( + f"Expected tensor for intermediate base, got {type(o)}" + ) + intermediate_bases.append(o._base) + intermediate_bases_descs.append(IntermediateBaseAOTOutput(o_desc)) + + if meta.num_intermediate_bases != len(intermediate_bases): + raise AssertionError( + f"num_intermediate_bases ({meta.num_intermediate_bases}) != len(intermediate_bases) ({len(intermediate_bases)})" + ) + + # the compiled forward should return (mutated_inputs, user_outs, intermediate_bases) + fw_outs_to_return = *mutated_inputs_to_return, *outs, *intermediate_bases + fw_outs_to_return_descs = ( + *mutated_inputs_to_return_descs, + *outs_descs, + *intermediate_bases_descs, + ) + + # Also return a boolean mask specifying which outputs to this function will be used as tangents + mutated_inputs_grad_mask = [ + meta.input_info[meta.mutated_inp_runtime_indices[i]].mutates_data + and meta.input_info[meta.mutated_inp_runtime_indices[i]].requires_grad + for (i, x) in enumerate(mutated_inputs_to_return) + ] + + # Pass any (non-aliased) outputs in as tangents, since they'll be returned as outputs in the fw + # For outputs that are aliases of intermediates, we will have returned the output's _base as an output in the graph instead, + # which we *should* send to grad() + output_grad_mask = [ + meta.output_info[i].output_type + in [ + OutputType.non_alias, + OutputType.unsafe_view_alias, + OutputType.custom_function_view, + ] + # Also, only tensor outputs should participate in the backward + # (in particular, Symint outputs in the forward graph shouldn't get tangents) + and issubclass(meta.output_info[i].raw_type, Tensor) + and meta.output_info[i].requires_grad_for_backward + for (i, x) in enumerate(outs) + ] + + intermediate_base_grad_mask = [True for _ in range(len(intermediate_bases))] + + out_grad_mask = ( + mutated_inputs_grad_mask + output_grad_mask + intermediate_base_grad_mask + ) + if len(out_grad_mask) != len(fw_outs_to_return): + raise AssertionError( + f"out_grad_mask length ({len(out_grad_mask)}) != fw_outs_to_return length ({len(fw_outs_to_return)})" + ) + + # Take care to grab and sync the updated inputs from primals_after_cloning (the inputs we actually mutate!) + # and not primals (the preserved inputs, pre-mutation, that we pass to grad()) + # This is annoying: our joint function needs to be aware of functionalization + # (syncing mutated inputs before calling autograd.grad()) + # In theory, we could make the autograd engine do this automatically, although that probably isn't any cleaner. + if not aot_config.disable_functionalization: + for arg in args_maybe_cloned: + if not isinstance(arg, Tensor): + continue + sync_functional_tensor(arg) + + # pyrefly: ignore[bad-return] + return (fw_outs_to_return, out_grad_mask), ( + fw_outs_to_return_descs, + out_grad_mask, + ) + + return inner_fn + + +@dataclass +class JointFnHandle: + post_forward: Callable[..., Any] | None = None + + +# Given a fn, computes the joint. +# NOTE: fn is expects the following behavior: +# (1) fn() needs to return a tuple of (outs, mask), +# where `mask` tells us which outputs are meant to have tangents. +# we don't know this info automatically, because we don't actually want to blindly +# compute tangents for every output that requires grad. +# Specifically, outputs that alias inputs won't participate in the backward and get tangents. +# (2) fn() cannot mutate any inputs that require gradient. +# otherwise, when we compute autograd.grad(), we will not take those input mutations into account +# (the way this is handled is that we ensure any inputs that normally get mutated are cloned first) +def create_joint( + fn: Callable[..., Any], + primals_descs: list[AOTInput] | None = None, + *, + aot_config: AOTConfig, +) -> Callable[..., Any]: + joint_fn_handle = JointFnHandle() + + # post_forward + # NB: this type is inaccurate when primals_descs is None + @simple_wraps(fn) + def inner_fn( + primals: list[FxValue], tangents: list[FxValue] + ) -> tuple[ + tuple[list[FxValue], list[Tensor | None]], + tuple[list[AOTOutput], list[AOTOutput | None]], + ]: + outs_descs = None + if primals_descs is None: + outs, tangent_mask = fn(*primals) + if pytree.tree_any(lambda x: isinstance(x, AOTOutput), tangent_mask): + raise AssertionError( + "tangent_mask should not contain AOTOutput instances" + ) + else: + (outs, tangent_mask), (outs_descs, _) = call_and_expect_output_descs( + fn, + primals, # type: ignore[arg-type] + ) + mode = get_proxy_mode() + if mode is None: + raise AssertionError("Expected non-None proxy mode") + for node in mode.tracer.graph.nodes: + if _is_tangent(node): + node.meta["partitioner_tag"] = "is_backward" + else: + node.meta["partitioner_tag"] = "is_forward" + + # TODO: I think this hook can also be eliminated now + if joint_fn_handle and joint_fn_handle.post_forward: + joint_fn_handle.post_forward(primals) + + if len(tangent_mask) != len(outs): + raise AssertionError( + f"tangent_mask length ({len(tangent_mask)}) != outs length ({len(outs)})" + ) + outs_to_grad = [ + o for needs_tangent, o in zip(tangent_mask, outs) if needs_tangent + ] + if len(outs_to_grad) != len(tangents): + raise AssertionError( + f"outs_to_grad length ({len(outs_to_grad)}) != tangents length ({len(tangents)})" + ) + + # Get the inputs that need gradients + grad_primals: list[torch.Tensor] = [] + inputs_needs_grads = [] + # Note that we're not using primals here, + # being carefully not to pass any mutated inputs into autograd.grad() + for p in primals: + if isinstance(p, Tensor) and p.requires_grad: + inputs_needs_grads.append(True) + if not isinstance(p, torch.Tensor): # Help mypy understand the type + raise AssertionError(f"expected Tensor, got {type(p)}") + grad_primals.append(p) + else: + inputs_needs_grads.append(False) + + # Get the outputs that need gradients + needed_outs: list[Tensor] = [] + needed_tangents: list[Tensor] = [] + for out, tangent in zip(outs_to_grad, tangents): + if isinstance(out, Tensor) and out.requires_grad: + # A bit sketchy, but fixes e.g. test_aot_autograd_exhaustive_matmul_cpu_float32 + # The issue is that we are sensitive to decomps that don't accurately maintain + # their output's _base.shape compared to eager mode, and this helps mitigate a bit. + # The guard_or_true also sketchy; if unbacked + # symints are involved, we're just going to assume that the + # decomps setup the base shape correctly + + # Return out if the result of out.shape==tangent.shape is unknown or known to be true. + # otherwise if its a known false return out.view(tangent.shape). + # tangent should also be a tensor since it corresponds to a tensor output + if not isinstance(tangent, torch.Tensor): + raise AssertionError( + f"Expected tensor tangent, got {type(tangent)}" + ) + needed_outs.append( + out + if guard_or_true(sym_eq(out.shape, tangent.shape)) + else out.view(tangent.shape) + ) + needed_tangents.append(tangent) + + setup_stacktrace_preservation_hooks( + [out.grad_fn for out in needed_outs if out.grad_fn is not None] + ) + + if config.functionalize_rng_ops: + PhiloxStateTracker.mark_beginning_of_backward() + backward_out: tuple[Tensor, ...] = () + # Call the backwards pass + if grad_primals: + functional_tensor_mode = torch.utils._python_dispatch._detect_infra_mode( + torch._C._TorchDispatchModeKey.FUNCTIONAL + ) + if functional_tensor_mode is not None: + # Side-Effect Tokens: + # We want to have independent chains of tokens for forward and backward. + # functional_tensor_mode._tokens is used by both. + # We memoize the result tokens of forward in functional_tensor_mode._tokens_forward_output, + # to return them as joint graph outputs. + # We clean functional_tensor_mode._tokens before backward, to prevent reuse of forward tokens in backward. + # Joint graph tracing allows tokens discovery, + # So all the tokens in backward will be created and added as a graph inputs during tracing. + functional_tensor_mode._tokens_forward_output = ( + functional_tensor_mode._tokens + ) + functional_tensor_mode._tokens = {} # pyrefly: ignore[implicit-any] + + with ( + set_partitioner_tag_is_backward(), + fx_traceback.preserve_node_meta(), + ExitStack() as stack, + ): + backward_pass_autocast = torch._functorch.config.backward_pass_autocast + if backward_pass_autocast == "same_as_forward": + # Use the ambient autocast mode(s) + pass + elif backward_pass_autocast == "off": + stack.enter_context(disable_autocast()) + else: + # Disable autocast, then enable anything in `backward_pass_autocast`. + stack.enter_context(disable_autocast()) + if not isinstance(backward_pass_autocast, list): + raise AssertionError( + f"expected backward_pass_autocast to be a list, got {type(backward_pass_autocast)}" + ) + for kwargs in backward_pass_autocast: + if not isinstance(kwargs, dict): + raise AssertionError( + f"expected kwargs to be a dict, got {type(kwargs)}" + ) + stack.enter_context(torch.amp.autocast(**kwargs)) + + # for full graph export, we always export a joint graph where we assume no tangents are needed. + if aot_config.no_tangents: + if not ( + len(needed_tangents) == 1 and needed_tangents[0].numel() == 1 + ): + raise AssertionError( + f"expected single scalar tangent for no_tangents mode, got {len(needed_tangents)} tangents" + ) + backward_out = torch.autograd.grad( + needed_outs, + grad_primals, + allow_unused=True, + ) + else: + backward_out = torch.autograd.grad( + needed_outs, + grad_primals, + grad_outputs=needed_tangents, + allow_unused=True, + ) + backward_out_iter = iter(backward_out) + final_outs = ( + outs, + [next(backward_out_iter) if i else None for i in inputs_needs_grads], + ) + if primals_descs is None: + return final_outs # type: ignore[return-value] + if outs_descs is None: + raise AssertionError("outs_descs must not be None") + # pyrefly: ignore[bad-return] + return final_outs, ( + outs_descs, + [ + # TODO: ideally we do know this is DifferentiableAOTInput + # but this is quite an involved refactor + GradAOTOutput(desc) if i else None # type: ignore[arg-type] + for i, desc in zip(inputs_needs_grads, primals_descs) + ], + ) + + @simple_wraps(inner_fn) + def inner_fn_with_anomaly( + primals: list[FxValue], tangents: list[FxValue] + ) -> tuple[ + tuple[list[FxValue], list[Tensor | None]], + tuple[list[AOTOutput], list[AOTOutput | None]], + ]: + with fx_traceback.preserve_node_meta(), warnings.catch_warnings(): + warnings.filterwarnings("ignore", "Anomaly Detection has been enabled.") + with torch.autograd.detect_anomaly(check_nan=False): + return inner_fn(primals, tangents) + + def joint_helper( + primals: list[FxValue], tangents: list[FxValue] + ) -> tuple[ + tuple[list[FxValue], list[Tensor | None]], + tuple[list[AOTOutput], list[AOTOutput | None]], + ]: + return inner_fn_with_anomaly(primals, tangents) + + joint_helper.handle = joint_fn_handle # type: ignore[attr-defined] + + # pyrefly: ignore[bad-return] + return joint_helper + + +def create_functionalized_rng_ops_wrapper( + func: Callable[..., Any], + args: Any, + args_descs: list[AOTInput], + trace_joint: bool = True, +) -> Any: + # Functionalization of rng ops changes the calling convention of the joint graph. + # It goes from (primals, tangents) to (seed, offset, primals, tangents) + # At runtime, we pass on the current seed and offset. This is hidden from + # the user. + fake_mode_det = detect_fake_mode() + fake_mode: AbstractContextManager[Any] = nullcontext() + if fake_mode_det is not None: + fake_mode = fake_mode_det + + def override_get_rng_state( + device: int | str | torch.device = "cuda", + ) -> Tensor: + out = PhiloxStateTracker.get_state_as_tensor() + return out + + def override_set_rng_state( + x: Tensor, device: int | str | torch.device = "cuda" + ) -> None: + PhiloxStateTracker.set_state_from_tensor(x) + + def append_rng_offsets(outs: Any, outs_descs: Any) -> Any: + if trace_joint: + # outs signature before: Tuple(fwd_outputs), Tuple(bwd_outputs) + # outs signature after: Tuple(fwd_outputs, new_fwd_rng_offset), Tuple(bwd_offset, new_bwd_rng_offset) + return ( + ( + (*outs[0], PhiloxStateTracker.get_updated_fwd_offset()), + (*outs[1], PhiloxStateTracker.get_updated_bwd_offset()), + ), + ( + (*outs_descs[0], PhiloxUpdatedForwardOffsetAOTOutput()), + (*outs_descs[1], PhiloxUpdatedBackwardOffsetAOTOutput()), + ), + ) + else: + # outs signature before: Tuple(fwd_outputs) + # outs signature after: Tuple(fwd_outputs, new_fwd_rng_offset) + return ( + (*outs, PhiloxStateTracker.get_updated_fwd_offset()), + (*outs_descs, PhiloxUpdatedForwardOffsetAOTOutput()), + ) + + def traced_joint( + primals: list[FxValue], + tangents: list[FxValue], + fwd_seed: Tensor, + fwd_base_offset: Tensor, + bwd_seed: Tensor, + bwd_base_offset: Tensor, + ) -> tuple[ + tuple[tuple[FxValue, ...], tuple[FxValue, ...]], + tuple[tuple[AOTOutput, ...], tuple[AOTOutput, ...]], + ]: + with ( + patch("torch.cuda.get_rng_state", override_get_rng_state), + patch("torch.cuda.set_rng_state", override_set_rng_state), + ): + return append_rng_offsets(*func(primals, tangents)) + + def traced_forward(*primals_fwd_seed_fwd_base_offset: Any) -> Any: + # The signature is (*primals, seed, offset) + with ( + patch("torch.cuda.get_rng_state", override_get_rng_state), + patch("torch.cuda.set_rng_state", override_set_rng_state), + ): + return append_rng_offsets(*func(*primals_fwd_seed_fwd_base_offset[:-2])) + + if trace_joint: + # Get the current seed and offset to setup tracing. + fwd_seed, fwd_base_offset = CUDARngStateHelper.get_torch_state_as_tuple( + fake_mode + ) + bwd_seed, bwd_base_offset = CUDARngStateHelper.get_torch_state_as_tuple( + fake_mode + ) + PhiloxStateTracker.record_state(fwd_seed, fwd_base_offset, "forward") + PhiloxStateTracker.record_state(bwd_seed, bwd_base_offset, "backward") + return ( + traced_joint, + ( + *args, + fwd_seed, + fwd_base_offset, + bwd_seed, + bwd_base_offset, + ), + ( + *args_descs, + PhiloxForwardSeedAOTInput(), + PhiloxForwardBaseOffsetAOTInput(), + PhiloxBackwardSeedAOTInput(), + PhiloxBackwardBaseOffsetAOTInput(), + ), + ) + else: + # Get the current seed and offset to setup tracing. + fwd_seed, fwd_base_offset = CUDARngStateHelper.get_torch_state_as_tuple( + fake_mode + ) + PhiloxStateTracker.record_state(fwd_seed, fwd_base_offset, "forward") + return ( + traced_forward, + (*args, fwd_seed, fwd_base_offset), + ( + *args_descs, + PhiloxForwardSeedAOTInput(), + PhiloxForwardBaseOffsetAOTInput(), + ), + ) + + +@contextmanager +def set_partitioner_tag(tag: str) -> Generator[None, None, None]: + meta_key = "partitioner_tag" + if not fx_traceback.has_preserved_node_meta(): + raise AssertionError("expected preserved node meta") + + original_val = fx_traceback.current_meta.get(meta_key, None) + fx_traceback.current_meta[meta_key] = tag + try: + yield + finally: + fx_traceback.current_meta[meta_key] = original_val + + +def set_partitioner_tag_is_backward() -> AbstractContextManager[None]: + return set_partitioner_tag("is_backward") + + +def set_partitioner_tag_must_be_in_backward() -> AbstractContextManager[None]: + return set_partitioner_tag("must_be_in_backward") + + +def set_partitioner_tag_must_be_in_forward() -> AbstractContextManager[None]: + return set_partitioner_tag("must_be_in_forward") + + +@dataclass +class MutationCounters: + mc_data: int + mc_storage: int + mc_inductor_storage_resized: int + + +T = TypeVar("T") + + +def sc_visit( + t: torch.Tensor, + fn: Callable[[Tensor], T], + reduce_fn: Callable[[T, T], T], + accum_init: T, +) -> T: + if not is_traceable_wrapper_subclass(t): + return fn(t) + + accum = accum_init + + def visit(e: Any) -> None: + if not is_traceable_wrapper_subclass(e): + nonlocal accum + accum = reduce_fn(accum, fn(e)) + return + + for a in e.__tensor_flatten__()[0]: + match getattr(e, a): + case torch.Tensor() as inner: + visit(inner) + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + + visit(t) + return accum + + +def _get_mutation_counter(t: torch.Tensor) -> int: + return sc_visit( + t, + lambda t: torch._functionalize_mutation_counter(t.elem), # type: ignore[attr-defined] + lambda l, r: max(l, r), + -1, + ) + + +def _get_storage_changed_counter(t: torch.Tensor) -> int: + return sc_visit( + t, + lambda t: torch._functionalize_storage_changed_counter(t.elem), # type: ignore[attr-defined] + lambda l, r: max(l, r), + -1, + ) + + +def _get_inductor_storage_resized_counter(t: torch.Tensor) -> int: + return sc_visit( + t, + lambda t: torch._functionalize_inductor_storage_resized_counter(t.elem), # type: ignore[attr-defined] + lambda l, r: max(l, r), + -1, + ) + + +def _get_mutation_counters(t: torch.Tensor) -> MutationCounters: + return MutationCounters( + _get_mutation_counter(t), + _get_storage_changed_counter(t), + _get_inductor_storage_resized_counter(t), + ) + + +def apply_in_graph_mutations( + input_info: InputAliasInfo, + inpt_old: Tensor, + inpt_new: Tensor, + f_inpt: Tensor, + input_idx: int, + mcs: MutationCounters | None = None, + applied_mcs: MutationCounters | None = None, +) -> None: + if input_info.mutation_type != MutationType.MUTATED_IN_GRAPH: + raise AssertionError( + f"expected mutation_type MUTATED_IN_GRAPH, got {input_info.mutation_type}" + ) + # See Note [set_() Input Mutations in AOTAutograd] + # all mutations on the input must be under no_grad, so it is safe to put in the graph + # Here, we're saying that if an input experienced a set call, inp.set_(other), + # then we can effectively not have to worry about whether its data was mutated. + # There are 3 cases: + # (1) We mutate inp *after* the set_() call. other is a graph intermediate. + # In this case, we're not really mutating the input storage of "inp"; + # we're mutating the storage of an intermediate value (other), + # and slamming that storage into the input tensor. So no data mutation is necessary. + # (2) We mutate inp *after* the set_() call. other is a graph *input*. + # In this case, the data mutation will be properly handled in the runtime + # epilogue during the processing of "other" + # (3) We mutate inp *before* the set_() call. + # This case is *not* currently handled. + if input_info.mutates_storage_metadata: + if mcs is None or mcs.mc_storage > applied_mcs.mc_storage: # type: ignore[union-attr] + with torch.no_grad(): + if input_info.mutation_is_shallow_copy_data: + torch.ops.aten.shallow_copy_data_(inpt_old, inpt_new) + else: + # pyrefly: ignore [bad-argument-type, no-matching-overload] + inpt_old.set_(inpt_new) + + # Note [Ordering of resize_() and set_()] + # Importantly: the common usage in FSDP is that we have a dummy parameter + # that sees a set_() and **Then** a resize_(). + # We must put those mutations into the graph in the same order, + # Since running them in the opposite order will have different behavior. + # We fully ban resize_() followed by set_() for now, although in principal + # we could support this + if input_info.mutation_inductor_storage_resize: + if ( + mcs is None + or mcs.mc_inductor_storage_resized > applied_mcs.mc_inductor_storage_resized # type: ignore[union-attr] + ): + # resizing is not supported on subclasses (we error earlier if this happens) + from torch._subclasses.functional_tensor import FunctionalTensor + + if not isinstance(f_inpt, FunctionalTensor): + raise AssertionError(f"expected FunctionalTensor, got {type(f_inpt)}") + old_storage_size = torch._functionalize_get_storage_size( # type: ignore[attr-defined] + f_inpt.elem, before=True + ) + new_storage_size = torch._functionalize_get_storage_size( # type: ignore[attr-defined] + f_inpt.elem, before=False + ) + if old_storage_size != new_storage_size: + if not (old_storage_size == 0 or new_storage_size == 0): + raise AssertionError(f"""\ + Encosize during tracing on input {input_idx}. Old nbytes={old_storage_size}, new nbytes={new_storage_size} + We oresizing on graph inputs as long as the input either starts or ends with a storage size of 0 + (thee for FSDP)""") + torch.ops.inductor.resize_storage_bytes_(inpt_old, new_storage_size) + if new_storage_size == 0: + # Even if we marked the input as having a data mutation (thus needing a copy_()), + # We should **ignore** it if our input has no storage + # (this can happen if, e.g. we temporarily resize our input, copy data into it, + # and resize it back down to zero) + return + + # Optimization: if the copy_() is a no-op then don't include it in the graph. + # In theory inductor could optimize this away, however in fsdp, we end up with + # param.copy_(param), where param is a zero-storage-size tensor, + # and running this op in eager mode (using the aot_eager backend) will result in a segfault. + # So we may as well optimize it away here. + if inpt_old is inpt_new: + # (This check needs to be done after putting resize_() in the graph, + # since a resize_(0) doesn't actually change the FunctionalTensor's inner tensor) + return + # We found an input that had a (data-only) mutation. + # Since keep_input_mutations is set, we need to faithfully apply a copy_() + # so the compiler will see the input mutation in the graph. + + if not input_info.mutates_data: + return + + if mcs is not None and mcs.mc_data <= applied_mcs.mc_data: # type: ignore[union-attr] + return + + if input_info.mutations_hidden_from_autograd: + # Hidden from autograd = run under no_grad, **and** don't bump VC + # (although if the tensor was created in inference mode, it has no VC) + if inpt_old.is_inference(): + maybe_preserve_vc = nullcontext() + else: + maybe_preserve_vc = torch.autograd._unsafe_preserve_version_counter( + inpt_old # type: ignore[assignment] + ) + with torch.no_grad(), maybe_preserve_vc: + inpt_old.copy_(inpt_new) + elif input_info.mutations_under_no_grad_or_inference_mode: + # Under no_grad = run under no_grad (we still bump the VC though) + # (inference_mode will also bump the VC, as long as the tensor in question + # was created outside of inference_mode) + + with torch.no_grad(): + inpt_old.copy_(inpt_new) + else: + inpt_old.copy_(inpt_new) + + +# This creates the final function that we want to trace using make_fx(), +# in both aot_dispatch_autograd and aot_dispatch_base. +# Preconditions: +# - fn corresponds to the user's fw function +# - fn arguments have been flattened, duplicate arguments have been handled +# - In the returned function, the "primals" arguments *includes* synthetic bases. +# This function does the work of functionalizing the input function, +# and performing copy_() calls at the end of the function if `keep_input_mutations` is set. +# The function returned has signature that is either: +# (1) "traced_fn(primals: List[Any])" if trace_joint is False +# (2) "traced_fn(primals: List[Any], tangents: List[Any])" if trace_joint is True +# Returns a new (functionalized) function, and updated arguments to call it with. +def create_functionalized_fn( + fn: Callable[..., Any], + args: Any, + args_descs: Any, + *, + meta: ViewAndMutationMeta, + aot_config: AOTConfig, + trace_joint: bool, + joint_fn_handle: JointFnHandle | None = None, +) -> Any: + primals_after_forward = None + f_args_after_forward = None + f_args_mutation_counters_after_forward: list[MutationCounters] | None = None + inputs_mutated_in_graph = [ + info.mutation_type == MutationType.MUTATED_IN_GRAPH for info in meta.input_info + ] + has_input_mutated_in_graph = any(inputs_mutated_in_graph) + + @simple_wraps(fn) + def _functionalized_f_helper( + *args: list[FxValue], + ) -> tuple[tuple[list[FxValue], list[Tensor]], list[AOTOutput | None]]: + with maybe_enable_thunkify(): + # See Note [Disabling Functionalize TLS Above Python Functionalization] + disable_above = torch._C._ExcludeDispatchKeyGuard( + torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize) + ) + + with disable_above: + # The functionalization code here can potentially trigger traces + # into the graph, but we'd prefer to NOT do this, because if we + # trace them now, we will end up with FX nodes that don't have + # module stack annotations, which makes unflattener unhappy. + # Wrap inputs into functional wrappers + f_args = pytree.tree_map(to_fun, args) + + if trace_joint and has_input_mutated_in_graph and joint_fn_handle: + # TODO(ivankobzarev): Support fw and bw mutations for subclasses + def _post_forward(primals: Any) -> None: + nonlocal primals_after_forward + primals_after_forward = pytree.tree_map(from_fun, primals) + nonlocal f_args_after_forward + f_args_after_forward = f_args[0] + nonlocal f_args_mutation_counters_after_forward + f_args_mutation_counters_after_forward = [ + MutationCounters(-1, -1, -1) + if not inputs_mutated_in_graph[i] + else _get_mutation_counters(f_arg) + for i, f_arg in enumerate(f_args_after_forward) + ] + + joint_fn_handle.post_forward = _post_forward + + # Run the joint + f_outs, f_outs_descs = call_and_expect_output_descs(fn, f_args) + + if trace_joint: + # We support a limited amount of mutation of graph inputs during the backward pass. + # (This is used e.g. by Float8, which needs to update buffers during the backward pass) + # Here, we perform extra checks for primals that were mutated in the **backward** + # We're doing the checks here instead of doing them with the rest of the input mutation handling because: + # - We need to detect inputs that were mutated in the backward **separately** from mutations that happened + # during the forward, because the handling is different: some input mutations from the forward + # can be only handled in a fw-only runtime epilogue, and in theory if we wanted to handle those same + # types of mutations in the backward we would need a bw-only runtime epilogue. + # - We could in theory have our analysis pass differentiate mutations in the fw from mutations in + # the bw by running our analysis first on the fw-only graph, and then on the joint graph. This would + # require an extra round of tracing though, so it's more efficient to do in-line here. + if not ( + isinstance(args, tuple) + and len(args) == 2 + and isinstance(args[0], (list, tuple)) + ): + raise AssertionError( + f"expected args to be tuple of (list/tuple, ...), got {type(args)}" + ) + # Only look at mutations that happened to forward inputs (e.g. fw buffers that were saved for bw) + primals_before = args[0] + primals_after = pytree.tree_map(from_fun, f_args[0]) + for idx, (f_inpt, before, after, inpt_info) in enumerate( + zip(f_args[0], primals_before, primals_after, meta.input_info) + ): + # Store information about mutations in joint(for backward analysis) + joint_mutates_data = has_data_mutation(f_inpt) + + joint_mutates_metadata = has_metadata_mutation( + f_inpt, before, check_only_storage_mutation=False + ) + + # Ban metadata mutations on fw inputs during the bw + if not inpt_info.mutates_metadata: + if joint_mutates_metadata: + raise AssertionError( + "Found a graph input that had its metadata mutated in the backward. This is not supported" + ) + + # Ban storage resizing on fw inputs during the bw + if not inpt_info.mutation_inductor_storage_resize: + if was_inductor_storage_resized(f_inpt): + raise AssertionError( + "Found a graph input that had storage resizing in the backward. This is not supported" + ) + + # Allow data mutations on fw inputs during the bw, but only if they do not require grad + # So we can guarantee that we can keep the mutations in the graph + if ( + joint_mutates_data + and not inpt_info.mutates_data + and not inpt_info.mutates_storage_metadata + ): + # Not banning here mutations on inpt_info.requires_grad - + # we'll check at runtime and fail only when backward is under torch.is_grad_enabled (create_graph) + # Add node meta for copy_ for partitioner that this node should be in backward graph. + with ( + torch.fx.traceback.preserve_node_meta(), + set_partitioner_tag_must_be_in_backward(), + ): + # before and after should be tensors if we're calling copy_ on them + if not ( + isinstance(before, torch.Tensor) + and isinstance(after, torch.Tensor) + ): + raise AssertionError( + f"expected both before and after to be Tensors, got {type(before)} and {type(after)}" + ) + # no_grad prevents the FakeTensor's requires_grad from + # triggering check_inplace during tracing. The + # requires_grad case is checked at runtime instead + with torch.no_grad(): + before.copy_(after) + meta.indices_of_inputs_that_requires_grad_with_mutations_in_bw.append( + idx + ) + # Now that we covered mutations to *forward* inputs during the backward, + # we also need to cover mutations to *backward-only* inputs during the backward (e.g. mutation to a grad_out). + # Today, we will just error in all cases of this happening unless someone needs us to support it. + tangents_before = args[1] + tangents_after = pytree.tree_map(from_fun, f_args[1]) + for f_inpt, before, after in zip( + f_args[1], tangents_before, tangents_after + ): + if has_metadata_mutation( + f_inpt, before, check_only_storage_mutation=False + ): + raise AssertionError( + "Found an input to the backward that had metadata mutated " + "during the backward pass. This is not supported" + ) + if has_data_mutation(f_inpt): + can_be_in_graph = _check_if_mutation_can_be_in_graph( + keep_input_mutations=True, + mutates_data=True, + mutates_metadata=False, + mutations_hidden_from_autograd=are_all_mutations_hidden_from_autograd( + f_inpt + ), + mutations_under_no_grad_or_inference_mode=are_all_mutations_under_no_grad_or_inference_mode( + f_inpt + ), + mutates_storage_metadata=False, + mutation_inductor_storage_resize=was_inductor_storage_resized( + f_inpt + ), + requires_grad=f_inpt.requires_grad, + ) + if not can_be_in_graph: + raise AssertionError( + "a backward input that had data mutated in an autograd-aware way. This is not supported" + ) + # Perform the input mutation + with torch.fx.traceback.preserve_node_meta(): + # before and after should be tensors if we're calling copy_ on them + if not ( + isinstance(before, torch.Tensor) + and isinstance(after, torch.Tensor) + ): + raise AssertionError( + f"expected both before and after to be Tensors, got {type(before)} and {type(after)}" + ) + before.copy_(after) + + if aot_config.keep_inference_input_mutations: + # Note: This is a bit annoying. There's a layering issue here, where: + # (1) functionalization needs to operate on **synthetic base** inputs, before unpacking them into the "real" inputs. + # (2) For keep_input_mutations, we support tracing a call to copy_() directly on mutated inputs. + # However, we **only** want to support this for inputs that have data-only (and no metadata) mutations, + # because inductor (and backends in generally) would prefer not to see these (e.g. as_strided_(), resize_()). + # This makes it pretty difficult for this logic to operate on synthetic bases. + # (3) In addition, there are cases where it's significantly cheaper to perform the copy on the individual + # (unpacked) input aliases, instead of the synthetic base. + # Example case where (3) could be important: + # + # def f(x, y): + # x.mul_(2) + # y.mul_(3) + # return x, y + # a = torch.ones(1'000'000) + # x, y = out(a[0:9], a[1:10]) + # + # It would be much better to add copy_() calls into the graph for the two tiny slices, instead of materializing + # a giant "updated synthetic base" and copying into a's entire storage. + # + # For now, we are pessimistically not performing the optimization from (3); + # we will materialize an "updated" synthetic base, and copy it back to the synthetic input base. + # This allows us to factor aot autograd much more nicely, since only one area of the code needs to worry + # about synthetic bases. + + # Apply in graph forward mutations only in joint case. + # Note: Mutations of primals in forward AND backward. + # If we have mutations of the same input in forward and in backward, + # we can not fuse them into one copy_ node. As in this case partitioner will put it + # either in forward or in backward. This will lead to incorrect state + # after forward and before backward. + # We have to emit two copy_ nodes, marking with additional meta each node, + # if it must be in forward or backward. + # We memorize mutation counter of the inputs after forward. + # Based on this after joint graph we check if backward also mutated input or not. + # We emit copy_ only in the end of joint tracing, to provide invariant for joint + # graph passes, that our graph is functional, except only some number of copy_ nodes + # in the end. + mcs_applied: list[MutationCounters] = [MutationCounters(0, 0, 0)] * len( + meta.input_info + ) + if f_args_mutation_counters_after_forward is not None: + primals_before = args[0] + for idx, (f_inpt, before, after, inpt_info) in enumerate( + # pyrefly: ignore [no-matching-overload] + zip( + f_args_after_forward, # type: ignore[arg-type] + primals_before, # type: ignore[arg-type] + primals_after_forward, # type: ignore[arg-type] + meta.input_info, + ) + ): + if inpt_info.mutation_type != MutationType.MUTATED_IN_GRAPH: + continue + + mcs_after_forward = f_args_mutation_counters_after_forward[idx] + with ( + torch.fx.traceback.preserve_node_meta(), + set_partitioner_tag_must_be_in_forward(), + _proxy_tensor_disable_update_tensor_tracker(), + ): + apply_in_graph_mutations( + inpt_info, + # pyrefly: ignore [bad-argument-type] + before, + after, + f_inpt, + idx, + mcs_after_forward, + mcs_applied[idx], + ) + mcs_applied[idx] = mcs_after_forward + + for idx, (inpt_old, f_inpt) in enumerate( + zip(args, f_args) if not trace_joint else zip(args[0], f_args[0]) # type: ignore[arg-type] + ): + if not isinstance(f_inpt, torch.Tensor): + continue + if not is_fun(f_inpt): + raise AssertionError( + f"expected functional tensor, got {type(f_inpt)}" + ) + inpt_new = from_fun(f_inpt) + if ( + meta.input_info[idx].mutation_type + != MutationType.MUTATED_IN_GRAPH + ): + continue + mcs: MutationCounters | None = None + if f_args_mutation_counters_after_forward is not None: + # This could happen for subclasses tracing + # Subclasses support for mutations in fw and bw is TBD. + mcs = _get_mutation_counters(f_inpt) + if mcs == mcs_applied[idx]: + # No mutation in backward; mutation was already applied. + continue + + with ( + torch.fx.traceback.preserve_node_meta(), + set_partitioner_tag_must_be_in_backward(), + ): + apply_in_graph_mutations( + meta.input_info[idx], + # pyrefly: ignore[bad-argument-type] + inpt_old, + # pyrefly: ignore[bad-argument-type] + inpt_new, + f_inpt, + idx, + mcs, + mcs_applied[idx], + ) + + # When an output tensor is a functionalized mutated input, and we + # were able to move the mutation in to the graph then we can return + # the mutated input directly. This prevents duplicating the + # tensors contents. + flat_outs, outs_spec = pytree.tree_flatten(f_outs) + flat_outs = [from_fun(o) for o in flat_outs] + num_outs = len(meta.output_info) + + for i in range(num_outs): + info = meta.output_info[i] + if info.output_type != OutputType.is_input: + continue + + if info.base_idx is None: + raise AssertionError("info.base_idx must not be None") + if ( + meta.input_info[info.base_idx].mutation_type + == MutationType.MUTATED_IN_GRAPH + ): + fw_args = args[0] if trace_joint else args + flat_outs[i] = fw_args[info.base_idx] + return pytree.tree_unflatten(flat_outs, outs_spec), f_outs_descs + + return pytree.tree_map(from_fun, f_outs), f_outs_descs + + # Kinda annoying, but needed to make sure that the fx graph we trace out has "primals" + # and "tangents" as its input names (which are special-cased by the partitioner) + # TODO (tmanlaibaatar) revisit this if we ever need to turn on non-strict joint graph export + def joint_helper(primals: list[FxValue], tangents: list[FxValue]) -> Any: + return _functionalized_f_helper(primals, tangents) + + helper = joint_helper if trace_joint else _functionalized_f_helper + if config.functionalize_rng_ops: + # Setup the wrapper for functionalization of rng ops + helper, args, args_descs = create_functionalized_rng_ops_wrapper( + helper, args, args_descs, trace_joint + ) + + return helper, args, args_descs + + +def handle_effect_tokens_fn( + fn: Callable[..., Any], + args: Any, + args_descs: list[AOTInput], + *, + meta: ViewAndMutationMeta, + trace_joint: bool, +) -> Any: + num_tokens = len(meta.tokens) + + @simple_wraps(fn) + def inner_fn(*args: Any) -> Any: + # See Note [Disabling Functionalize TLS Above Python Functionalization] + disable_above = torch._C._ExcludeDispatchKeyGuard( + torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize) + ) + + with disable_above: + # See Note [Side-Effectful Tokens in AOTAutograd] + if trace_joint: + if not (isinstance(args, tuple) and isinstance(args[0], (list, tuple))): + raise AssertionError( + f"expected args to be tuple with first element as list/tuple, got {type(args)}" + ) + tokens = args[0][:num_tokens] + if not all(token.numel() == 0 for token in tokens): + raise AssertionError("all tokens must have numel() == 0") + args = (args[0][num_tokens:], *args[1:]) + else: + tokens = args[:num_tokens] + if not all(token.numel() == 0 for token in tokens): + raise AssertionError("all tokens must have numel() == 0") + args = args[num_tokens:] + + # Populate the current FunctionalTensorMode with the tokens per + # operator. See Note [FunctionalTensorMode is Stateful] + functional_tensor_mode = torch.utils._python_dispatch._detect_infra_mode( + torch._C._TorchDispatchModeKey.FUNCTIONAL + ) + if functional_tensor_mode is None: + raise AssertionError("functional_tensor_mode must not be None") + f_tokens = pytree.tree_map(to_fun, tokens) + for i, k in enumerate(meta.tokens.keys()): + functional_tensor_mode._tokens[k] = f_tokens[i] + + # Run the joint + outs, outs_descs = call_and_expect_output_descs(fn, args) + + # Return both the tokens and the outputs + # See Note [Side-Effectful Tokens in AOTAutograd] + if trace_joint: + if len(outs) != 2: + raise AssertionError( + f"expected len(outs) == 2 for joint trace, got {len(outs)}" + ) + if len(functional_tensor_mode._tokens_forward_output) != num_tokens: + raise AssertionError( + f"expected {num_tokens} forward output tokens, got {len(functional_tensor_mode._tokens_forward_output)}" + ) + fwd_out_tokens = functional_tensor_mode._tokens_forward_output.values() + + bwd_out_tokens = functional_tensor_mode._tokens.values() + + f_fwd_out_tokens = [from_fun(t) for t in fwd_out_tokens] + f_bwd_out_tokens = [from_fun(t) for t in bwd_out_tokens] + f_fwd_out_tokens_descs = [ + ForwardTokenAOTOutput(i) for i in range(len(fwd_out_tokens)) + ] + f_bwd_out_tokens_descs = [ + BackwardTokenAOTOutput(i) for i in range(len(bwd_out_tokens)) + ] + + meta.num_backward_tokens = len(bwd_out_tokens) + return ( + ((*f_fwd_out_tokens, *outs[0]), (*outs[1], *f_bwd_out_tokens)), + ( + (*f_fwd_out_tokens_descs, *outs_descs[0]), + (*outs_descs[1], *f_bwd_out_tokens_descs), + ), + ) + + out_tokens = [from_fun(t) for t in functional_tensor_mode._tokens.values()] + # TODO: can probably do a little more resolution here + out_tokens_descs = [ + ForwardTokenAOTOutput(i) + for i in range(len(functional_tensor_mode._tokens.values())) + ] + return ((*out_tokens, *outs), (*out_tokens_descs, *outs_descs)) + + # Additionally pass in tokens as inputs + # See Note [Side-Effectful Tokens in AOTAutograd] + additional_fwd_token_inputs = [torch.tensor([])] * num_tokens + additional_fwd_token_inputs_descs = [ + ForwardTokenAOTInput(i) for i in range(num_tokens) + ] + + if trace_joint: + args = ([*additional_fwd_token_inputs, *args[0]], *args[1:]) + args_descs = ( # type: ignore[assignment] + [*additional_fwd_token_inputs_descs, *args_descs[0]], # type: ignore[misc] + *args_descs[1:], + ) + else: + args = [*additional_fwd_token_inputs, *args] + args_descs = [*additional_fwd_token_inputs_descs, *args_descs] + + if num_tokens > 0: + meta.static_input_indices = [ + idx + num_tokens for idx in meta.static_input_indices + ] + return inner_fn, args, args_descs + + +# Given a function operating on Subclass -> Subclass, returns a function that operates on Tensor -> Tensor +# Also returns: +# - the new set of arguments to pass into this function (now that tensor subclasses have been eliminated) +# - the updated ViewAndMutationMeta for this dense -> dense function. +# The other important arguments are: +# - flat_fn_maybe_joint: when is_joint_structure=True, this is the joint fw-bw function. +# when is_joint_structure=False, this is just the forward function. +# - fw_only: this is *always* the forward-only function. +# Why do we need this? We need to collect updated ViewAndMutationMeta on our new dense -> dense functions. +# In particular, we need this to tell the partitioner how many dense forward outputs there are. +def aot_dispatch_subclass( + flat_fn_maybe_joint: JointTraceFn | TraceFn, + args: list[FxValue] | tuple[list[FxValue], list[FxValue]], + args_descs: list[AOTInput] | tuple[list[AOTInput], list[AOTInput]], + *, + is_joint_structure: bool, + meta: ViewAndMutationMeta, + fw_only: Callable[..., Any], +) -> SubclassTracingInfo: + # Skip logic if we don't need to trace through any subclasses + req_subclass_dispatch = requires_subclass_dispatch(args, meta) # type: ignore[arg-type] + if not req_subclass_dispatch: + return SubclassTracingInfo( + plain_tensor_trace_fn=flat_fn_maybe_joint, + plain_tensor_args=args, + plain_tensor_args_descs=args_descs, + maybe_subclass_meta=None, + ) + + # TODO: add subclass guards (later PR). + + # What's going on here? We need to compute subclass metadata about the outputs of the joint (grad_inputs). + # Annoying: we don't know the grad input metas until we're in the middle of tracing the joint, + # so we set it later, while we're tracing the joint (see inner_fn() below). + # Another option would be to run our run_functionalized_fw_and_collect_metadata() function + # directly on the joint, but this would hurt compile time (adding yet another pass through the joint). + subclass_meta = SubclassMeta() + + # NB: doesn't take descs, this is going from the NEW flat_args to the + # subclasses, we don't need to do bookkeeping here + def inner_fn(fn: Callable[..., Any], args: Any, *, use_trace_joint: bool) -> Any: + # Step 1: wrap tensor inputs into subclasses if necessary + all_args = wrap_tensor_subclasses_maybe_joint( + args, is_joint_structure=use_trace_joint, meta=meta + ) + + # Step 2: call the inner function, with our (maybe subclass) inputs + wrapped_outs, wrapped_outs_descs = call_and_expect_output_descs(fn, all_args) # type: ignore[arg-type] + + if use_trace_joint: + # See Note: [Computing Subclass Metadata about grad_inputs] + # We also stash subclass info on our grad_inputs, if we're tracing the joint. + nonlocal subclass_meta + if not (isinstance(wrapped_outs, tuple) and len(wrapped_outs) == 2): + raise AssertionError( + f"expected wrapped_outs to be tuple of length 2, got {type(wrapped_outs)}, {wrapped_outs_descs}" + ) + # Don't need fw outs since we already have subclass metadata on them + grad_inputs = wrapped_outs[1] + subclass_meta.grad_input_metas = create_subclass_meta(grad_inputs) + + # Add extra symints as outputs to the forward/backward graphs + # ignore nested ints here + forward_outs, forward_outs_descs = unwrap_tensor_subclasses( + wrapped_outs[0], + wrapped_outs_descs[0], + append_symints=True, + ) + # ignore nested ints here + backward_outs, backward_outs_descs = unwrap_tensor_subclasses( + wrapped_outs[1], + wrapped_outs_descs[1], + append_symints=True, + ) + return ( + (forward_outs, backward_outs), + (forward_outs_descs, backward_outs_descs), + ) + + # Step 3: Unwrap any subclass outputs back into dense tensors + return unwrap_tensor_subclasses( + wrapped_outs, wrapped_outs_descs, append_symints=True + ) + + def joint_fn( + primals: list[FxValue], tangents: list[FxValue] + ) -> tuple[ + tuple[list[FxValue], list[FxValue]], tuple[list[AOTOutput], list[AOTOutput]] + ]: + with maybe_enable_thunkify(): + return inner_fn( + flat_fn_maybe_joint, (primals, tangents), use_trace_joint=True + ) + + def fw_fn(*primals: FxValue) -> tuple[list[FxValue], list[AOTOutput]]: + with maybe_enable_thunkify(): + return inner_fn(flat_fn_maybe_joint, primals, use_trace_joint=False) + + def metadata_fn(*primals: FxValue) -> tuple[list[FxValue], list[AOTOutput]]: + @simple_wraps(fw_only) + def inner_fw_only(*args: Any) -> Any: + return call_and_expect_output_descs(fw_only, args) + + return inner_fn(inner_fw_only, primals, use_trace_joint=False) + + if is_joint_structure: + primals_wrapped: list[FxValue] = typing.cast(list[FxValue], args[0]) + primals_wrapped_descs: list[AOTInput] = typing.cast( + list[AOTInput], args_descs[0] + ) + tangents_wrapped: list[FxValue] = typing.cast(list[FxValue], args[1]) + tangents_wrapped_descs: list[AOTInput] = typing.cast( + list[AOTInput], args_descs[1] + ) + + # Add extra symints (size/strides) as input to the forward graph + primals_unwrapped_pair = unwrap_tensor_subclasses( + primals_wrapped, + primals_wrapped_descs, + append_symints=True, + ) + # We pass append_symints=False here because the partitioner will + # capture and add any extra argument. + tangents_unwrapped_pair = unwrap_tensor_subclasses( + tangents_wrapped, + tangents_wrapped_descs, + append_symints=False, + ) + + args_unwrapped = (primals_unwrapped_pair[0], tangents_unwrapped_pair[0]) + args_descs_unwrapped = (primals_unwrapped_pair[1], tangents_unwrapped_pair[1]) + remapped_static_indices = remap_unwrapped_subclass_arg_indices( + primals_wrapped, + meta.static_input_indices, # type: ignore[arg-type] + ) + + primals_unwrapped = args_unwrapped[0] # type: ignore[assignment] + primals_unwrapped_descs = args_descs_unwrapped[0] # type: ignore[assignment] + fn_to_trace = joint_fn # type: ignore[assignment] + else: + primals_wrapped: list[FxValue] = typing.cast(list[FxValue], args) + primals_wrapped_descs: list[AOTInput] = typing.cast(list[AOTInput], args_descs) + + args_unwrapped, args_descs_unwrapped = unwrap_tensor_subclasses( # type: ignore[assignment] + primals_wrapped, + primals_wrapped_descs, + append_symints=True, + ) + remapped_static_indices = remap_unwrapped_subclass_arg_indices( + primals_wrapped, + meta.static_input_indices, # type: ignore[arg-type] + ) + + primals_unwrapped = args_unwrapped # type: ignore[assignment] + primals_unwrapped_descs = args_descs_unwrapped # type: ignore[assignment] + fn_to_trace = fw_fn # type: ignore[assignment] + + # Note: [Partitioner handling for Subclasses, Part 1] + # The way the partitioner works is that: + # (1) we pass is a single graph containing the joint fw/bw, + # where the # of graph outputs corresponds to # fw_outputs + # grad_inputs + # (2) The partitioner accepts an arguments, num_fwd_outputs, + # and assumes that the first "num_fwd_outputs" graph outputs correspond + # to outputs of the forward graph. + # How do tensor subclasses enter the picture? + # the num_fwd_outputs in the final graph is actually non-trivial to compute, + # because it can be influenced by input mutations and intermediate bases. + # So we compute it by inspecting the current ViewAndMutationMeta object. + # However, the original ViewAndMutationMeta that we computed was created + # on the subclass -> subclass graph, + # which can have a different number of outputs than the dense -> dense graph. + # That's why we created a fresh metadata object on the dense -> dense function here, + # and plumb it back up to the partitioner. + # See Note: [Partitioner handling for Subclasses, Part 2] for more info. + with torch._dynamo.eval_frame._use_eager_on_nested_compile(): + meta_updated = run_functionalized_fw_and_collect_metadata( + without_output_descs(metadata_fn), + # pyrefly: ignore [bad-argument-type] + flat_args_descs=primals_unwrapped_descs, + static_input_indices=remapped_static_indices, + keep_input_mutations=meta.keep_input_mutations, + # pyrefly: ignore [not-iterable] + )(*primals_unwrapped) + + subclass_meta.fw_metadata = meta_updated + + return SubclassTracingInfo( + plain_tensor_trace_fn=fn_to_trace, + plain_tensor_args=args_unwrapped, + plain_tensor_args_descs=args_descs_unwrapped, + maybe_subclass_meta=subclass_meta, + ) + + +def create_functional_call( + mod: Any, + params_spec: Any, + params_len: int, + store_orig_mod: bool = False, + strict_out_tuple: bool = True, +) -> Callable[..., Any]: + # Redundant with dynamo, but worth having in case this gets invoked elsewhere. + + @simple_wraps(mod) + def functional_call(*args: Any, **kwargs: Any) -> Any: + flat_params = args[:params_len] + if isinstance(params_spec, TreeSpec): + params = pytree.tree_unflatten(flat_params, params_spec) + else: + if not isinstance(params_spec, list): + raise AssertionError( + f"expected params_spec to be a list, got {type(params_spec)}" + ) + params = dict(zip(params_spec, flat_params)) + with ( + stateless._reparametrize_module(mod, params), + maybe_disable_thunkify(), + ): + if isinstance(mod, torch.fx.GraphModule): + if kwargs: + # Handle **kwargs. FX only natively supports positional + # arguments (through placeholders). + arg_list = list(args[params_len:]) + arg_list.extend(list(kwargs.values())) + args = tuple(arg_list) + else: + args = args[params_len:] + + with fx_traceback.preserve_node_meta(), warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", "Anomaly Detection has been enabled." + ) + with torch.autograd.detect_anomaly(check_nan=False): + fake_mode = detect_fake_mode() + if fake_mode is None: + raise AssertionError("fake_mode must not be None") + fake_mode.epoch += 1 + out = PropagateUnbackedSymInts(mod).run(*args) + else: + out = mod(*args[params_len:], **kwargs) + + if strict_out_tuple and not isinstance(out, (tuple, list)): + raise RuntimeError( + "Graph output must be a (). This is so that we can avoid " + "pytree processing of the outputs. Please change the module to " + "have tuple outputs or use aot_module instead." + ) + return out + + # Note [Preserving the nn module stack metadata during export non-strict mode] + # This path is currently only used by the non-strict export flow, + # where we cannot rely on dynamo to preserve nn stack metadata in our captured graph. + # Instead, we stash the original user nn module here, and rely on `make_fx` to grab + # this stashed module and use it to track nn module stack metadata + if store_orig_mod and not hasattr(functional_call, "_orig_mod"): + functional_call._orig_mod = mod # type: ignore[attr-defined] + + return functional_call diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/graph_compile.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/graph_compile.py new file mode 100644 index 0000000000000000000000000000000000000000..d27c3d2889bcc1599e12d1f935a96fe86fb07605 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/graph_compile.py @@ -0,0 +1,2881 @@ +""" +Functions in this module do most of the "work" of AOTAutograd. +An aot_dispatch_* function: +- Takes in the input flat_fn, flat_args, and some metadata +- Runs a set of pre compile wrappers (e.g. argument deduping) +- Runs the actual compiler +- Wraps the returned callable in a set of post compile wrappers +- Returns the wrapped callable and metadata. +""" + +import copy +import dataclasses +import functools +import itertools +import logging +import operator +import threading +import time +import traceback +from collections import defaultdict +from collections.abc import Callable, Generator +from contextlib import contextmanager, nullcontext +from typing import Any + +import torch +import torch.utils._pytree as pytree +import torch.utils.dlpack +from torch import Tensor +from torch._custom_class_base import CustomClassBase +from torch._dynamo.utils import ( + CompileEventLogger, + detect_fake_mode, + dynamo_timed, + lazy_format_graph_code, +) +from torch._guards import CompileContext, TracingContext +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import is_custom_class_obj +from torch._logging import getArtifactLogger, trace_structured +from torch._subclasses import FakeTensor +from torch._subclasses.fake_tensor import is_fake_tensor +from torch._subclasses.meta_utils import is_sparse_any +from torch.fx.experimental._backward_state import BackwardState +from torch.fx.experimental.proxy_tensor import is_sym_node +from torch.fx.experimental.symbolic_shapes import fx_placeholder_vals, guard_or_true +from torch.fx.graph_module import GraphModule +from torch.fx.passes._tensorify_python_scalars import tensorify_python_scalars +from torch.multiprocessing.reductions import StorageWeakRef +from torch.types import py_sym_types +from torch.utils._python_dispatch import is_traceable_wrapper_subclass +from torchgen.utils import dataclass_repr + +from .. import config +from .aot_autograd_result import GenericAOTAutogradResult, serialize_graph_module +from .autograd_cache import ( + AOTAutogradCache, + should_bundle_autograd_cache, + should_use_remote_autograd_cache, +) +from .descriptors import AOTOutput, PlainAOTOutput +from .graph_capture import aot_dispatch_autograd_graph, aot_dispatch_base_graph +from .logging_utils import track_graph_compiling +from .runtime_wrappers import ( + AOTDedupeWrapper, + AOTDispatchAutograd, + AOTDispatchAutogradCompileSpec, + AOTDispatchSubclassWrapper, + AOTSyntheticBaseWrapper, + AutogradLazyBackwardCompileInfo, + CompilerWrapper, + DebugAssertWrapper, + EffectTokensWrapper, + FakifiedOutWrapper, + FunctionalizedRngRuntimeWrapper, + make_runtime_safe, + post_compile, + pre_compile, + RuntimeWrapper, + SerializableCompiledFunction, +) +from .schemas import ( + AOTConfig, + AOTGraphCapture, + AOTState, + FlatFn, + FxValue, + MutationType, + SubclassMeta, + ViewAndMutationMeta, +) +from .subclass_utils import compute_inner_mutated_inp_indices_from_subclass_meta +from .utils import ( + contain_metadata_mutation_ops, + get_default_generator, + make_boxed_func, + simple_wraps, + strict_zip, + unlift_tokens, +) + + +def is_opaque_node(node: Any) -> bool: + """Check if a node contains an opaque or non-tensor value (e.g., ProcessGroup).""" + from torch._library.fake_class_registry import FakeScriptObject + + if not isinstance(node, torch.fx.Node): + return False + if "val" not in getattr(node, "meta", {}): + return False + val = node.meta["val"] + if is_custom_class_obj(val): + return True + if isinstance(val, (torch.ScriptObject, FakeScriptObject)): + return True + return False + + +_thread_local = threading.local() + + +def _should_save_cache(*compiled_fns: Callable[..., Any]) -> bool: + if should_bundle_autograd_cache(): + return True + return all( + getattr(fn, "_fx_graph_cache_key", None) is not None for fn in compiled_fns + ) + + +@contextmanager +def maybe_skip_decompose(aot_config: AOTConfig) -> Generator[AOTConfig, None, None]: + if config.selective_decompose: + yield dataclasses.replace(aot_config, decompositions={}) + else: + yield aot_config + + +# Saved tensor hooks context +# Compiled saved tensor hooks are convenient way to inline some logic in the graphs +# for saved nodes from forward to backward. (E.g. activations quantization) +# In base implementation user does not have any additional information about saved value +# in the hook, except FakeTensor shape, dtype, device etc. +# _get_saved_tensor_hook_context gives additional graph information about that saved value, +# that can be used to make a decisions which pack/unpack to apply for particular saved value. +# This allows user to reuse saved tensors hooks api to apply selective pack/unpack in +# graph aware way. +# Alternative to this will be making user to write a custom pass that mucks with forward outputs, +# backward input metadata, which requires significantly more effort. +# +# As for now in context we expose forward graph, backward graph and current saved node, +# which contains node.meta with additional information about that fx.Node. +# Warning: This API may change without backward compatibility. +@contextmanager +def _saved_tensor_hook_context(state: dict[str, Any]) -> Generator[None, None, None]: + previous_state = getattr(_thread_local, "state", None) + try: + _thread_local.state = state + yield + finally: + # Clean up: restore previous state or remove attribute + if previous_state is not None: + _thread_local.state = previous_state + else: + if hasattr(_thread_local, "state"): + delattr(_thread_local, "state") + + +def _get_saved_tensor_hook_context() -> dict[str, Any] | None: + return getattr(_thread_local, "state", None) + + +zip = strict_zip + +log = logging.getLogger(__name__) +aot_joint_log = getArtifactLogger(__name__, "aot_joint_graph") +aot_graphs_log = getArtifactLogger(__name__, "aot_graphs") + +aten = torch.ops.aten + +# Returns a Callable and a ViewAndMutationMeta. +# Currently, only export needs the ViewAndMutationMeta after this function. +# TODO: Refactor this +DispatchReturn = tuple[Callable[..., Any], ViewAndMutationMeta] + + +def _create_wrappers_for_dispatch(needs_autograd: bool) -> list[CompilerWrapper]: + """ + Wrappers that run on every dispatch function + """ + return [AOTDedupeWrapper(), AOTSyntheticBaseWrapper(trace_joint=needs_autograd)] + + +def aot_stage1_graph_capture( + aot_state: AOTState, + orig_flat_fn: FlatFn, +) -> AOTGraphCapture: + # NB: flat_fn at this point coincides with the initial info from forward + # metadata collection returning a list[Tensor]. We are now going to + # augment the output to return a tuple[list[Tensor], list[AOTOutput]] and + # then preserve this convention through the rest of the passes. + + # TODO: We could test for consistency with fw_metadata, but this is not a + # big deal + @simple_wraps(orig_flat_fn) + def orig_flat_fn2(*args: FxValue) -> tuple[list[FxValue], list[AOTOutput]]: + out = orig_flat_fn(*args) + out_descs: list[AOTOutput] = type(out)( # type: ignore[assignment] + PlainAOTOutput(i) # type: ignore[misc] + for i in range(len(out)) # type: ignore[misc] + ) + return out, out_descs + + aot_config = aot_state.aot_config + + wrappers = _create_wrappers_for_dispatch(aot_state.needs_autograd) + flat_fn, aot_state.flat_args, aot_state.flat_args_descs, aot_state.fw_metadata = ( + pre_compile( + wrappers, + orig_flat_fn2, + aot_state.flat_args, + aot_state.flat_args_descs, + aot_config, + fw_metadata=aot_state.fw_metadata, + ) + ) + if aot_config.disable_functionalization: + # Effect tokens are introduced by FunctionalTensorMode. The + # disable_functionalization path intentionally traces without the + # effect-token wrapper, so metadata-discovered tokens must not affect + # graph signatures or forward/backward output partitioning. + aot_state.fw_metadata.tokens = {} + aot_state.fw_metadata.num_backward_tokens = 0 + + # NB: This is currently only used for backwards, where fwd/bwd + # deterministic TLS can be different + aot_state.fw_metadata.deterministic = torch.are_deterministic_algorithms_enabled() + updated_flat_args: list[Any] | tuple[list[Any], list[Any]] + + with maybe_skip_decompose(aot_config) as graph_capture_aot_config: + # if config.selective_decompose, skip decomposition and apply selective_decompose + # after we get the joint graph. See [Note: Selective Decomposition] for details. + if aot_state.needs_autograd and not aot_config.pre_dispatch: + # FYI: this being moved to trigger in export is new, seems fine! + with dynamo_timed("aot_trace_joint_graph", log_pt2_compile_event=True): + ( + graph, + updated_flat_args, + updated_flat_args_descs, + maybe_subclass_meta, + ) = aot_dispatch_autograd_graph( + flat_fn, + aot_state.flat_args, + aot_state.flat_args_descs, + graph_capture_aot_config, + fw_metadata=aot_state.fw_metadata, + ) + else: + graph, updated_flat_args, updated_flat_args_descs, maybe_subclass_meta = ( + aot_dispatch_base_graph( + flat_fn, + aot_state.flat_args, + aot_state.flat_args_descs, + graph_capture_aot_config, + fw_metadata=aot_state.fw_metadata, + ) + ) + if config.selective_decompose: + from torch.fx.experimental.proxy_tensor import selective_decompose + from torch.fx.passes.regional_inductor import _needs_inductor_compile + + graph = selective_decompose( + graph, + *updated_flat_args, + decomposition=aot_config.decompositions, + should_decompose=_needs_inductor_compile, + trace_joint_graph=aot_state.needs_autograd and not aot_config.pre_dispatch, + ) + + return AOTGraphCapture( + wrappers=wrappers, + graph_module=graph, + updated_flat_args=updated_flat_args, + updated_flat_args_descs=updated_flat_args_descs, + maybe_subclass_meta=maybe_subclass_meta, + ) + + +def aot_stage2_export( + aot_state: AOTState, aot_graph_capture: AOTGraphCapture +) -> DispatchReturn: + graph = aot_graph_capture.graph_module + aot_config = aot_state.aot_config + wrappers = aot_graph_capture.wrappers + + CompileEventLogger.try_add_pt2_compile("backend_compile", dispatch_mode="export") + + # NB: the wrappers that run in pre_compile for export are + # either a no-op, because they're not needed, or will raise a runtime error, + # since they don't support export. + # We still run these wrappers to make sure that they're not needed pre compile, + # but we technically don't need to run them post compile at all here. + compiled_fn, aot_state.fw_metadata = post_compile( + wrappers, + graph, # pyrefly: ignore [bad-argument-type] + aot_config, + runtime_metadata=aot_state.fw_metadata, + ) + + # Therefore, since no wrapperes run, we don't get back a callable - we get back the raw fx graph + # (either a joint or an inference-only graph) + if not isinstance(compiled_fn, torch.fx.GraphModule): + raise AssertionError( + f"expected compiled_fn to be GraphModule, got {type(compiled_fn)}" + ) + return compiled_fn, aot_state.fw_metadata + + +def _get_inner_meta( + maybe_subclass_meta: SubclassMeta | None, + fw_metadata: ViewAndMutationMeta, +) -> ViewAndMutationMeta: + """ + Util to get view and mutation metadata. + """ + return ( + fw_metadata if maybe_subclass_meta is None else maybe_subclass_meta.fw_metadata + ) + + +def _apply_tensorify_python_scalars(module: torch.fx.GraphModule) -> None: + """ + Util to apply tensorify_python_scalars. + """ + # TODO(anijain2305) - Add tensorify_python_scalars to the HOP graph passes. + fake_mode = detect_fake_mode() + if fake_mode is not None and fake_mode.shape_env is not None: + tensorify_python_scalars(module, fake_mode.shape_env, fake_mode) + + +def aot_stage2_compile( + aot_state: AOTState, + aot_graph_capture: AOTGraphCapture, + # pyrefly: ignore [implicit-any] + partition_fn: Callable, + # pyrefly: ignore [implicit-any] + fw_compiler: Callable, + # pyrefly: ignore [implicit-any] + bw_compiler: Callable | None = None, + # pyrefly: ignore [implicit-any] + inference_compiler: Callable | None = None, +) -> DispatchReturn: + if bw_compiler is None: + bw_compiler = fw_compiler + if inference_compiler is None: + inference_compiler = fw_compiler + + if aot_state.needs_autograd and not aot_state.aot_config.pre_dispatch: + return aot_stage2_autograd( + aot_state, + aot_graph_capture, + partition_fn, + fw_compiler, + bw_compiler, + ) + else: + return aot_stage2_inference( + aot_state, + aot_graph_capture, + partition_fn, + inference_compiler, + ) + + +def _log_inference_graph( + fw_module: torch.fx.GraphModule, + aot_config: AOTConfig, +) -> str | None: + """ + Log the inference graph to the structured logger. + Return a str representation of the graph. + """ + if aot_config.enable_log: + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "torch._functorch.config", + "encoding": "string", + }, + payload_fn=lambda: torch._functorch.config.get_serializable_config_copy(), + ) + + # Save the forward_graph_str right after aot_dispatch_base_graph, + # to save in the cache + aot_forward_graph_str = None + if aot_config.cache_info is not None: + aot_forward_graph_str = fw_module.print_readable( + print_output=False, + include_stride=True, + include_device=True, + fast_sympy_print=True, + expanded_def=True, + ) + + return aot_forward_graph_str + + +def _aot_stage2b_inference_compile( + fw_module: torch.fx.GraphModule, + updated_flat_args: list[Any], + maybe_subclass_meta: SubclassMeta | None, + fw_metadata: ViewAndMutationMeta, + aot_config: AOTConfig, + # pyrefly: ignore [implicit-any] + inference_compiler: Callable, + # pyrefly: ignore [implicit-any] +) -> Callable: + return _aot_stage2b_compile_forward_or_inference( + fw_module, + updated_flat_args, # type: ignore[arg-type] + maybe_subclass_meta, + fw_metadata, + aot_config, + inference_compiler, + is_inference=True, + )[1] + + +def aot_stage2_inference( + aot_state: AOTState, + aot_graph_capture: AOTGraphCapture, + # pyrefly: ignore [implicit-any] + partition_fn: Callable, + # pyrefly: ignore [implicit-any] + inference_compiler: Callable, +) -> DispatchReturn: + """ + Handles functions that don't need autograd. Runs wrappers and compiles with + the stage-2 inference compiler. + """ + + aot_config = aot_state.aot_config + fw_metadata = aot_state.fw_metadata + fw_module = aot_graph_capture.graph_module + wrappers = aot_graph_capture.wrappers + updated_flat_args = aot_graph_capture.updated_flat_args + maybe_subclass_meta = aot_graph_capture.maybe_subclass_meta + + CompileEventLogger.try_add_pt2_compile("backend_compile", dispatch_mode="inference") + aot_forward_graph_str = _log_inference_graph(fw_module, aot_config) + + if not isinstance(fw_module, GraphModule): + raise AssertionError( + f"expected fw_module to be GraphModule, got {type(fw_module)}" + ) + _apply_tensorify_python_scalars(fw_module) + + # When trace_autograd_ops=True, the inference graph may contain fw/bw + # invoke_subgraph pairs from traced torch.autograd.grad/backward calls. + # Partition them before the remat pass so that remat duplicates the + # already-partitioned fw subgraphs (which produce saved tensors for bw). + fw_module = run_joint_graph_passes_on_hops( + fw_module, None, aot_config, default_partition_fn=partition_fn + ) + + # Apply AC rematerialization after HOP partitioning. This must happen + # after partitioning so remat duplicates the partitioned fw subgraphs + # (not the original unpartitioned ones). + if torch._functorch.config.remat_using_tags_for_fwd_loss_bwd_graph: + from torch._functorch._activation_checkpointing.remat_using_tags_for_fwd_loss_bwd_graph_pass import ( + remat_using_tags_for_fwd_loss_bwd_graph, + ) + + fw_module = remat_using_tags_for_fwd_loss_bwd_graph(fw_module) + + if _has_invoke_subgraph_node(fw_module): + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "aot_inference_graph_after_hop_passes", + "encoding": "string", + }, + payload_fn=lambda: fw_module.print_readable( + print_output=False, + include_stride=True, + include_device=True, + expanded_def=True, + ), + ) + + compiled_fw = _aot_stage2b_inference_compile( + fw_module, + updated_flat_args, # type: ignore[arg-type] + maybe_subclass_meta, + fw_metadata, + aot_config, + inference_compiler, + ) + + entry = _cache_inference_info( + aot_config, + fw_metadata, + maybe_subclass_meta, + compiled_fw, + aot_forward_graph_str, + wrappers, + ) + + return _aot_stage2c_make_inference_function( + aot_config, + fw_metadata, + compiled_fw, + wrappers, + entry, + ) + + +def _cache_inference_info( + aot_config: AOTConfig, + fw_metadata: ViewAndMutationMeta, + maybe_subclass_meta: SubclassMeta | None, + compiled_fw: Callable[..., Any], + aot_forward_graph_str: str | None, + wrappers: list[CompilerWrapper], +) -> GenericAOTAutogradResult[Any, Any] | None: + make_runtime_safe(fw_metadata, maybe_subclass_meta) + + cache_info = aot_config.cache_info + + entry: GenericAOTAutogradResult[Any, Any] | None = None + if cache_info is not None and _should_save_cache(compiled_fw): + time_taken_ns = time.time_ns() - cache_info.start_time_ns + guards_expr = AOTAutogradCache.generate_guards_expression(cache_info) + entry = AOTAutogradCache.make_entry( + compiled_fw_func=compiled_fw, # type: ignore[arg-type] + compiled_bw_func=None, + aot_joint_graph_str=None, + aot_forward_graph_str=aot_forward_graph_str, + aot_backward_graph_str=None, + runtime_metadata=fw_metadata, + dispatch_wrappers=wrappers, + maybe_subclass_meta=maybe_subclass_meta, + num_fw_outs_saved_for_bw=None, + indices_of_inps_to_detach=[], + forward_time_taken_ns=time_taken_ns, + backward_time_taken_ns=0, + sanitized_aot_config=aot_config.to_cacheable(), + guards_expr=guards_expr, + backward_state_indices=None, + num_symints_saved_for_bw=None, + serialized_bw_module=None, + min_cut_info_str=None, + ) + AOTAutogradCache.save( + cache_info.cache_key, + entry, + remote=should_use_remote_autograd_cache(), + ) + + return entry + + +def _aot_stage2c_make_inference_function( + aot_config: AOTConfig, + fw_metadata: ViewAndMutationMeta, + compiled_fw: Callable[..., Any], + wrappers: list[CompilerWrapper], + entry: GenericAOTAutogradResult[Any, Any] | None, +) -> DispatchReturn: + if entry is not None: + compiled_fw = SerializableCompiledFunction(compiled_fw, lambda: entry) + + disable_amp = torch._C._is_any_autocast_enabled() + compiled_fn = RuntimeWrapper( + indices_of_inps_to_detach=[], + trace_joint=False, + disable_amp=disable_amp, + ).post_compile( + compiled_fw, + aot_config, + runtime_metadata=fw_metadata, + ) + + compiled_fn = post_compile( + wrappers, compiled_fn, aot_config, runtime_metadata=fw_metadata + ) + return compiled_fn + + +def collect_fw_donated_buffer_idxs( + fw_ins: list[FakeTensor | None], + user_fw_outs: list[FakeTensor | None], + bw_outs: list[FakeTensor | None], + saved_tensors: list[FakeTensor | None], +) -> list[int]: + """ + Checks if the saved tensors are donated buffers, which means a saved tensor is not + an alias of any tensors in fw_ins, user_fw_outs, and bw_outs. + """ + + storage_refs = set() + + for t in itertools.chain(fw_ins, user_fw_outs, bw_outs): + # Only access storage if a tensor has storage (not sparse) + if t is not None and is_fake_tensor(t) and not is_sparse_any(t): + storage_refs.add(StorageWeakRef(t.untyped_storage())) + + num_saved_tensor = len(saved_tensors) + donated_buffer_idxs = [] + for i in range(num_saved_tensor): + t = saved_tensors[i] + if ( + t is not None + and is_fake_tensor(t) + and not is_sparse_any(t) + and StorageWeakRef(t.untyped_storage()) not in storage_refs + ): + donated_buffer_idxs.append(i) + + return donated_buffer_idxs + + +def collect_bw_donated_buffer_idxs( + fw_module: torch.fx.GraphModule, + bw_module: torch.fx.GraphModule, + fw_metadata: ViewAndMutationMeta, +) -> list[int]: + """ + Collects backward donated buffer indexes from fw_module and bw_module. + """ + + # [Note: Metadata mutation in proxy tracing] + # node.meta["val"] is a snapshot of the tensor value when tracing a graph, + # instead of the final state after the graph has run. node.meta["val"] is + # not updated even if later there is a metadata mutation op. + # See: https://github.com/pytorch/pytorch/pull/141308#issuecomment-2495798947 + # + # Currently, metadata mutation op happens only for sacrificial parameter + # specifically the `set_` op. This motivates banning metadata mutation from + # proxy tracing. + # + # Since node.meta["val"] is used to detect donated buffer, we return an empty + # list if there exists metadata mutation op. + if contain_metadata_mutation_ops(fw_module) or contain_metadata_mutation_ops( + bw_module + ): + return [] + + fw_ins = fw_module.graph.find_nodes(op="placeholder") + bw_outs = next(reversed(bw_module.graph.find_nodes(op="output"))).args[0] + fw_outs = next(reversed(fw_module.graph.find_nodes(op="output"))).args[0] + + fw_ins = [ + n.meta["val"] if (hasattr(n, "meta") and "val" in n.meta) else None + for n in fw_ins + ] + fw_outs = [ + n.meta["val"] if (hasattr(n, "meta") and "val" in n.meta) else None + for n in fw_outs + ] + bw_outs = [ + n.meta["val"] if (hasattr(n, "meta") and "val" in n.meta) else None + for n in bw_outs + ] + + user_fw_outs = fw_outs[: fw_metadata.num_forward] + saved_tensors = fw_outs[fw_metadata.tensors_saved_for_backwards_slice] + + fw_donated_buffer = collect_fw_donated_buffer_idxs( + fw_ins, + user_fw_outs, + bw_outs, + saved_tensors, + ) + + if fw_metadata.num_symints_saved_for_bw is None: + raise AssertionError("fw_metadata.num_symints_saved_for_bw must not be None") + return [fw_metadata.num_symints_saved_for_bw + i for i in fw_donated_buffer] + + +@dataclasses.dataclass +class InvokeSubgraphHopGraphs: + """ + A data structure to hold all the information needed to partition the + `joint_hop_gm` and joint graph and the restitch the `new_fw_hop_gm` and + `new_bw_hop_gm` into the bigger `joint_gm`. + """ + + # To avoid re-partitioning subgraphs + partitioning_done: bool = False + old_num_fw_outputs: int | None = None + old_num_fw_inputs: int | None = None + + new_fw_hop_gm: torch.fx.GraphModule | None = None + new_bw_hop_gm: torch.fx.GraphModule | None = None + new_num_sym_nodes: int | None = None + new_num_saved_nodes: int | None = None + + +def prepare_for_partitioner( + mod: torch.fx.GraphModule, num_primals: int, num_fw_outputs: int +) -> torch.fx.GraphModule: + # min-cut partitioner requires the placeholders to have primals and + # tangents string in the node.name. The signature of the joint graph is + # (*primals, *tangents) + + # We also have to update the output signature which is right now + # (*grads, *fw_outs) and we have to change to (*fw_outs, *grads) for the + # partitioner to work. + new_graph = torch.fx.Graph() + env = {} + + primals_counter = itertools.count(0) + tangents_counter = itertools.count(0) + + for idx, node in enumerate(mod.graph.nodes): + if node.op == "placeholder": + if idx < num_primals: + env[node] = new_graph.placeholder(f"primals_{next(primals_counter)}") + else: + env[node] = new_graph.placeholder(f"tangents_{next(tangents_counter)}") + env[node].meta = copy.copy(node.meta) + elif node.op == "output": + # Reverse the (*grads, *fw_outs) to (*fw_outs, *grads) + # The reason for having the reversed signature in the first + # place is to simplify step 3. + old_outputs = node.args[0] + new_outputs = ( + *old_outputs[-num_fw_outputs:], + *old_outputs[:-num_fw_outputs], + ) + new_outputs = [env[n] if n else None for n in new_outputs] + new_graph.output(tuple(new_outputs)) + else: + env[node] = new_graph.node_copy(node, lambda n: env[n]) + env[node].meta = copy.copy(node.meta) + + new_graph.lint() + + out = torch.fx.GraphModule(mod, new_graph) + return out + + +def _get_partition_fn( + fw_hop_node: torch.fx.Node, + aot_config: AOTConfig, + default_partition_fn: Callable[ + ..., tuple[torch.fx.GraphModule, torch.fx.GraphModule] + ] + | None, +) -> tuple[bool, Callable[..., tuple[torch.fx.GraphModule, torch.fx.GraphModule]]]: + """ + Return either `default_partition_fn` or a HOP specific partition function. + + If a HOP specific partition function is returned, used_hop_custom_partition is True. + + See Note [InvokeSubgraphHOP Partitioner] + """ + used_hop_custom_partition = False + + # Check for HOP-specific partition function first. This is needed because + # run_joint_graph_passes_on_hops can be called without an outer stage-2 + # partition function (e.g., in aot_stage1_graph_capture before the remat + # pass). + if ( + fw_hop_node.target == torch._higher_order_ops.invoke_subgraph + and "custom" in fw_hop_node.meta + and "nested_region_config" in fw_hop_node.meta["custom"] + ): + hop_partition_fn = fw_hop_node.meta["custom"][ + "nested_region_config" + ].partitioner + if hop_partition_fn is not None: + if callable(hop_partition_fn): + raw_partitioner = hop_partition_fn + elif not isinstance(hop_partition_fn, str): + raise AssertionError( + f"expected hop_partition_fn to be str, got {type(hop_partition_fn)}" + ) + else: + match hop_partition_fn: + case "default_partition": + raw_partitioner = ( + torch._functorch.partitioners.default_partition + ) + case "min_cut_rematerialization_partition": + raw_partitioner = torch._functorch.partitioners.min_cut_rematerialization_partition + case _: + raise ValueError( + f"Unknown HOP partitioner config: {hop_partition_fn}" + ) + + # Route through Inductor's `partition_fn` so joint-graph passes + # (e.g. scatter_upon_const_tensor) run on the HOP subgraph before + # the user-selected raw partitioner. + from torch._inductor.compile_fx import ( + partition_fn as _inductor_partition_fn, + ) + + return True, functools.partial( + _inductor_partition_fn, partitioner_fn_override=raw_partitioner + ) + + # Fall back to the parent partitioner from aot_config. When the outer + # compile is Inductor this is already `compile_fx.partition_fn` so + # joint-graph passes run there too. + if default_partition_fn is None: + raise AssertionError("default_partition_fn must not be None") + return used_hop_custom_partition, default_partition_fn + + +def _has_invoke_subgraph_node(gm: torch.fx.GraphModule): + from torch._higher_order_ops import invoke_subgraph + + for node in gm.graph.nodes: + if node.op == "call_function" and node.target is invoke_subgraph: + return True + return False + + +def run_joint_graph_passes_on_hops( + joint_gm: torch.fx.GraphModule, + joint_inputs: Any, + aot_config: AOTConfig, + *, + default_partition_fn: Callable[ + ..., tuple[torch.fx.GraphModule, torch.fx.GraphModule] + ] + | None = None, +) -> torch.fx.GraphModule: + """ + This pass runs the joint graph passes on the HOP graph. In torch.compile, we + typically have many passes which work on the joint graph and then end with a + partitioner. + + + The partitioner part is quite mechanical to handle. HOP have their own + forward and backward graph. The process can be broken into following steps + + 1) Get a `joint_hop_gm` from the `fw_hop_gm` and `bw_hop_gm` + 2) Run joint graph passes on the `joint_hop_gm` to get `new_fw_hop_gm` and `new_bw_hop_gm` + 3) Stitch the `new_fw_hop_gm` and `new_bw_hop_gm` back into the `joint_gm`. + + The terminology used in the code is + `joint_graph/joint_gm` : Refers to the main graph. This may contain many HOPs which have their own `hop_graph` + `fw_hop_graph/fw_hop_gm` : Refers to the forward graph associated with a HOP. + `bw_hop_graph/bw_hop_gm` : Refers to the backward graph associated with a HOP. + `joint_hop_graph/joint_hop_gm` : Refers to the subgraph associated with the HOP like invoke_subgraph. + `new_fw_hop_graph/new_fw_hop_gm` : Refers to the forward graph after partitioning is applied to `joint_hop_gm`. + `new_bw_hop_graph/new_bw_hop_gm` : Refers to the backward graph after partitioning is applied to `joint_hop_gm`. + + NB: This pass works for invoke_subgraph today because we took extra care in + the Autograd.Dispatch key of invoke_subgraph to vastly simplify Step 1. + + NB: This pass only matches **top-level** invoke_subgraph HOP nodes in + `joint_gm`. It does not recurse into subgraph modules, so when one + `nested_compile_region` is invoked from inside another, the inner + invoke_subgraph HOPs live inside the outer's subgraph module and are not + paired here. Top-level HOPs are still paired correctly via `call_id`; + recursive partitioning of nested regions is left to downstream passes. + """ + from torch._higher_order_ops import invoke_subgraph + from torch._higher_order_ops.invoke_subgraph import ( + get_backward_nested_region_config, + ) + + def num_outputs(mod: torch.fx.GraphModule) -> int: + return len(mod.graph.find_nodes(op="output")[0].args[0]) + + def num_inputs(mod: torch.fx.GraphModule) -> int: + return len(mod.graph.find_nodes(op="placeholder")) + + new_hop_graphs: dict[str, InvokeSubgraphHopGraphs] = defaultdict( + lambda: InvokeSubgraphHopGraphs() + ) + + # Step 1 - Get a `joint_hop_gm` from the `fw_hop_gm` and `bw_hop_gm` This is + # easy to do for `invoke_subgraph` HOP. During the Autograd dispatch key + # tracing, we have put the joint_hop_graph in the backward hop graph itself. + # So to recover the joint_hop_gm, we just have to look at the backward + # HOP graphs. + # So we will merge step 1 and step 2 in this next section + + # Save the fw and bwd hop nodes. We will later in-place modify the graph + # using these nodes. + # pyrefly: ignore [implicit-any] + fw_hop_nodes = [] + # pyrefly: ignore [implicit-any] + bw_hop_nodes = [] + for node in joint_gm.graph.nodes: + if ( + node.op == "call_function" + and node.target is invoke_subgraph + and isinstance(node.args[1], str) + ): + if node.args[1].startswith("fw"): + fw_hop_nodes.append(node) + elif node.args[1].startswith("bw"): + bw_hop_nodes.append(node) + + if not bw_hop_nodes: + return joint_gm + + # The fw and bw HOP counts are not necessarily equal. A fw HOP can have no + # corresponding bw HOP when autograd never runs backward through that call + # — e.g. the user does `x_d = x.detach().requires_grad_()` between two + # regions, or some outputs are not used in the loss. Likewise, multiple fw + # calls in the same compile region can share a single bw if autograd dedups + # or DCEs intermediate bws. + # + # Pair fw and bw HOPs by `call_id` — a per-call counter stamped by + # InvokeSubgraphAutogradOp's fw/bw on each FX node. This is unambiguous + # regardless of how autograd dispatched the backward (single outer + # `.backward()`, per-iter `.backward()` in a loop, interleaved regions). + fws_by_call_id: dict[int, torch.fx.Node] = {} + for fw in fw_hop_nodes: + cid = fw.meta.get("custom", {}).get("call_id") + if cid is None: + continue + if cid in fws_by_call_id: + raise AssertionError( + f"duplicate call_id={cid} on fw HOPs " + f"{fws_by_call_id[cid].name!r} and {fw.name!r}" + ) + fws_by_call_id[cid] = fw + + bw_to_fw_hop_node: dict[torch.fx.Node, torch.fx.Node] = {} + paired_fws: set[torch.fx.Node] = set() + for bw in bw_hop_nodes: + cid = bw.meta.get("custom", {}).get("call_id") + if cid is None: + raise AssertionError( + f"bw HOP {bw.args[1]!r} has no call_id in meta['custom']" + ) + fw = fws_by_call_id.get(cid) + if fw is None: + raise AssertionError( + f"could not find matching fw HOP for bw {bw.args[1]!r} " + f"with call_id={cid} (fw call_ids: {sorted(fws_by_call_id)})" + ) + bw_to_fw_hop_node[bw] = fw + paired_fws.add(fw) + + # Extra fws share a compile region with a paired bw but have no bw of + # their own (autograd may dedup or DCE the bw). They still must be + # rewritten to call the new partitioned fw subgraph, otherwise the output + # signatures diverge from the rewritten paired fws. Key by the bw + # identifier so the key matches `new_hop_graphs`. + fw_args_to_bw_identifier: dict[str, str] = {} + for bw, fw in bw_to_fw_hop_node.items(): + fw_arg = fw.args[1] + bw_arg = bw.args[1] + if not (isinstance(fw_arg, str) and isinstance(bw_arg, str)): + raise AssertionError( + f"expected fw/bw invoke_subgraph HOP args[1] to be str identifiers, " + f"got fw={type(fw_arg)}, bw={type(bw_arg)}" + ) + fw_args_to_bw_identifier.setdefault(fw_arg, bw_arg.removeprefix("bw")) + extra_fws_by_id: dict[str, list[torch.fx.Node]] = defaultdict(list) + for fw in fw_hop_nodes: + if fw in paired_fws: + continue + bw_ident_key = fw_args_to_bw_identifier.get(fw.args[1]) + if bw_ident_key is None: + continue + extra_fws_by_id[bw_ident_key].append(fw) + + for node in bw_hop_nodes: + identifier = node.args[1].removeprefix("bw") + + # If partitioning already done for this identifier, skip. This saves + # redundant joint graph passes for same subgraphs. + if new_hop_graphs[identifier].partitioning_done: + continue + + # Collect some information from the forward hop graph + fw_hop_node = bw_to_fw_hop_node[node] + fw_subgraph_attr = fw_hop_node.args[0] + if not isinstance(fw_subgraph_attr, torch.fx.Node): + raise AssertionError( + f"expected fw invoke_subgraph HOP args[0] to be torch.fx.Node, " + f"got {type(fw_subgraph_attr)}" + ) + fw_subgraph_attr_target = fw_subgraph_attr.target + if not isinstance(fw_subgraph_attr_target, str): + raise AssertionError( + f"expected fw invoke_subgraph HOP args[0].target to be str, " + f"got {type(fw_subgraph_attr_target)}" + ) + fw_hop_gm = getattr(joint_gm, fw_subgraph_attr_target) + if not isinstance(fw_hop_gm, torch.fx.GraphModule): + raise AssertionError( + f"expected fw_hop_gm to be GraphModule, got {type(fw_hop_gm)}" + ) + num_fw_inputs = num_inputs(fw_hop_gm) + num_fw_outputs = num_outputs(fw_hop_gm) + new_hop_graphs[identifier].old_num_fw_inputs = num_fw_inputs + new_hop_graphs[identifier].old_num_fw_outputs = num_fw_outputs + + # Step 1) - Get the `joint_hop_gm`. As mentioned earlier, the + # backward graph is the joint graph. + joint_hop_gm = getattr(joint_gm, node.args[0].target) + if not isinstance(joint_hop_gm, torch.fx.GraphModule): + raise AssertionError( + f"expected joint_hop_gm to be GraphModule, got {type(joint_hop_gm)}" + ) + + # Prepare the graph for the partitioner + joint_hop_gm = prepare_for_partitioner( + joint_hop_gm, num_fw_inputs, num_fw_outputs + ) + + # TODO: invoke_subgraph should track which of its inputs static indices + # so it can propagate them to the partitioner (and use in cudagraphs) + static_lifetime_input_indices: list[int] = [] + + used_hop_custom_partition, partition_fn = _get_partition_fn( + fw_hop_node, aot_config, default_partition_fn + ) + + # Step 2) and 3) - Run joint graph passes and partitioner + try: + new_fw_hop_gm, new_bw_hop_gm = partition_fn( + joint_hop_gm, + [], + num_fwd_outputs=num_fw_outputs, + static_lifetime_input_indices=static_lifetime_input_indices, + ) + except Exception as e: + if used_hop_custom_partition: + raise RuntimeError( + f"Error in custom partition function for invoke_subgraph node {fw_hop_node.name}: {e}" + ) from e + else: + raise + + # Save the new forward and backward graph modules + new_hop_graphs[identifier].new_fw_hop_gm = new_fw_hop_gm + new_hop_graphs[identifier].new_bw_hop_gm = new_bw_hop_gm + + # Save the number of symints and saved tensors + new_fw_out_nodes = new_fw_hop_gm.graph.find_nodes(op="output")[0].args[0] + extra_outputs = new_fw_out_nodes[num_fw_outputs:] + symint_outputs = [n for n in extra_outputs if is_sym_node(n)] + + new_hop_graphs[identifier].new_num_sym_nodes = len(symint_outputs) + new_hop_graphs[identifier].new_num_saved_nodes = len(extra_outputs) - len( + symint_outputs + ) + + new_hop_graphs[identifier].partitioning_done = True + + # Step 3) Restitch the new fw and bw graphs back into the main graph. + # + # This is a very mechanical process. There are a quite a few pieces that we + # need to connect together to make it work. Lets try to understand the + # problem statement first. + # + # For the forward graph, the signature of the old_fw_hop_gm is + # inputs - (*primals) + # outputs - (*fw_outs) + # Now the signature of the new_fw_hop_gm is + # inputs - (*primals) -- This is same + # outputs - (*fw_outs, *saved_tensors) - This is different + # At a high level, this is an easy transformation, in the new graph we just + # have to replace the old_fw_hop_gm with the new_fw_hop_gm. Everything else + # falls into place, because the input signature (i.e. args) is same. And + # even though output signature is different, fw_outs are still at the same + # indexes as before. So the forward of the `joint_gm` works nicely. + # + # Now, lets look at the backward hop graph. Old signature + # inputs - (*primals, *tangents) + # outputs - (*grad_outs, *fw_outs) + # New signature + # inputs - (*saved_tensors, *tangents) -- Different + # outputs - (*grad_outs) -- Different + # Here both input and output signature change. The output signature handling + # is quite easy because the grads_out are sitting at the right place, so we + # don't have to do anything. + # + # For the input signature, we have to collect the saved tensors from the + # corresponding forward graph output. We collect all saved_tensors when we + # see the forward graph, and save it into a map and then later use it during + # the backward. + + # The stack of fw_nodes for invoke_subgraph HOP. There is an implicit + # assumption about the graph structure, i.e., if we have hop1, hop2, hop3, + # ... in the forward part of the joint graph, we will have .., hop3, hop2, + # hop1 order for the backward. This structure allows us to just use a stack + # to collect all the information that we need to pass from the forward hop + # node to the corresponding backward node. + + already_added_new_hop_mods = set() + + def add_new_hop_gm(new_subgraph_mod: torch.fx.GraphModule, name: str) -> str: + new_subgraph_attr_name = f"partitioned_{name}" + if new_subgraph_attr_name in already_added_new_hop_mods: + return new_subgraph_attr_name + + joint_gm.register_module(new_subgraph_attr_name, new_subgraph_mod) + already_added_new_hop_mods.add(new_subgraph_attr_name) + return new_subgraph_attr_name + + def propagate_meta_info( + new_hop_gm: torch.fx.GraphModule, + new_call_function_node: torch.fx.Node, + old_call_function_node: torch.fx.Node, + ) -> None: + # Copy all the fields from the old call_function node. And then override + # the `val` meta field with the outputs of new_hop_gm. + new_call_function_node.meta = copy.copy(old_call_function_node.meta) + + output = new_hop_gm.graph.find_nodes(op="output")[0] + out_example_vals = [n.meta["val"] if n else None for n in output.args[0]] + new_call_function_node.meta["val"] = tuple(out_example_vals) + + for bw_node in reversed(bw_hop_nodes): + identifier = bw_node.args[1].removeprefix("bw") + + # Make changes to the corresponding fw and bw node pair simultaneously. + # The removes the need of any bookkeeping. + + # Fw node changes + # Insert the new_fw_hop_gm. This is straightforward. Get the + # new_fw_hop_gm, insert the hop_gm as a get_attr fw_node, and then + # add a call_function fw_node. Additionally, also use getitem + # call_functions to collect the saved_tensor nodes + + fw_node = bw_to_fw_hop_node[bw_node] + new_fw_hop_gm = new_hop_graphs[identifier].new_fw_hop_gm + if new_fw_hop_gm is None: + raise AssertionError( + f"new_fw_hop_gm for identifier {identifier} must not be None" + ) + + old_num_fw_outputs = new_hop_graphs[identifier].old_num_fw_outputs + new_num_sym_nodes = new_hop_graphs[identifier].new_num_sym_nodes + new_num_saved_nodes = new_hop_graphs[identifier].new_num_saved_nodes + if old_num_fw_outputs is None: + raise AssertionError( + f"old_num_fw_outputs for identifier {identifier} must not be None" + ) + if new_num_sym_nodes is None: + raise AssertionError( + f"new_num_sym_nodes for identifier {identifier} must not be None" + ) + if new_num_saved_nodes is None: + raise AssertionError( + f"new_num_saved_nodes for identifier {identifier} must not be None" + ) + total_outputs = old_num_fw_outputs + new_num_saved_nodes + new_num_sym_nodes + + extra_fw_outputs = [] + + # Insert the new_fw_hop_gm into the joint_gm + fw_subgraph_attr = fw_node.args[0] + if not isinstance(fw_subgraph_attr, torch.fx.Node): + raise AssertionError( + f"expected fw invoke_subgraph HOP args[0] to be torch.fx.Node, " + f"got {type(fw_subgraph_attr)}" + ) + with joint_gm.graph.inserting_after(fw_node): + new_fw_mod_attr_name = add_new_hop_gm(new_fw_hop_gm, f"fw{identifier}") + new_fw_mod_attr = joint_gm.graph.get_attr(new_fw_mod_attr_name) + new_fw_mod_attr.meta = copy.copy(fw_subgraph_attr.meta) + + # new_hop_fw_gm output signature is (*fw_outs, *saved_tensors) + with joint_gm.graph.inserting_after(new_fw_mod_attr): + new_fw_node = joint_gm.graph.call_function( + the_function=invoke_subgraph, + args=( + new_fw_mod_attr, + new_fw_mod_attr_name, + *fw_node.args[2:], + ), + ) + propagate_meta_info(new_fw_hop_gm, new_fw_node, fw_node) + + # old_num_fw_outputs = (*fw_outs) + # new_num_fw_outputs = (*fw_outs, *saved_tensors, *sym_nodes) + with joint_gm.graph.inserting_after(new_fw_node): + for fw_out_idx in range(old_num_fw_outputs, total_outputs): + saved_tensor_node = joint_gm.graph.call_function( + the_function=operator.getitem, args=(new_fw_node, fw_out_idx) + ) + saved_tensor_node.meta = copy.copy(new_fw_node.meta) + saved_tensor_node.meta["val"] = new_fw_node.meta["val"][fw_out_idx] + extra_fw_outputs.append(saved_tensor_node) + + fw_node.replace_all_uses_with(new_fw_node) + joint_gm.graph.erase_node(fw_node) + + # Bw node changes + # Prepare the operands for the bwd graph + # Old bw graph signature : (*primals, *tangents) + # New signature will be : (*sym_nodes, *saved_tensors, *tangents) + # We have already collected the saved_tensors in the forward hop processing. + + # extra_fw_outputs are in the order (*saved_nodes, *sym_nodes). + # Partitioner has this quirk where the backward wants sym_nodes + # first. So extract the sym and saved nodes. + + new_bw_hop_gm = new_hop_graphs[identifier].new_bw_hop_gm + if new_bw_hop_gm is None: + raise AssertionError( + f"new_bw_hop_gm for identifier {identifier} must not be None" + ) + + saved_tensor_nodes = extra_fw_outputs[:new_num_saved_nodes] + sym_nodes = extra_fw_outputs[new_num_saved_nodes:] + + num_primals = new_hop_graphs[identifier].old_num_fw_inputs + if num_primals is None: + raise AssertionError( + f"num_primals for identifier {identifier} must not be None" + ) + tangents = list(bw_node.args[2 + num_primals :]) + operands = sym_nodes + saved_tensor_nodes + tangents + + # Insert the new_bw_hop_gm into the joint_gm + with joint_gm.graph.inserting_after(bw_node): + new_bw_mod_attr_name = add_new_hop_gm(new_bw_hop_gm, bw_node.args[1]) + new_bw_mod_attr = joint_gm.graph.get_attr(new_bw_mod_attr_name) + new_bw_mod_attr.meta = copy.copy(bw_node.args[0].meta) + + with joint_gm.graph.inserting_after(new_bw_mod_attr): + new_bw_node = joint_gm.graph.call_function( + the_function=invoke_subgraph, + args=( + new_bw_mod_attr, + new_bw_mod_attr_name, + *operands, + ), + ) + propagate_meta_info(new_bw_hop_gm, new_bw_node, bw_node) + # Since the partitioner is run after the graph passes, we have lost + # the eager information and cannot faithfully extract the eager + # inputs for the new partitioned backward graph. For the forward + # graph, it was fine because the input signature remains same. + new_bw_node.meta.pop("eager_input_vals", None) + + # When the region sets backward-specific inductor config, compile the + # partitioned backward under it; the forward keeps its own config. + fw_region_config = fw_node.meta.get("custom", {}).get( + "nested_region_config" + ) + # get_backward_nested_region_config returns fw_config unchanged when + # the region has no distinct backward config, so identity tells us + # whether to stamp. + bw_region_config = get_backward_nested_region_config(fw_region_config) + if bw_region_config is not fw_region_config: + # Re-stamp on the fresh backward node's meta["custom"] (the source + # of truth: unlike a GraphModule's meta it survives FX transforms). + # Lowering picks it up via the subgraph-module mirror (_propagate_*) + # or the ir.py node fallback. + new_bw_node.meta["custom"] = { + **new_bw_node.meta.get("custom", {}), + "nested_region_config": bw_region_config, + } + + bw_node.replace_all_uses_with(new_bw_node) + joint_gm.graph.erase_node(bw_node) + + # Rewrite extra (unpaired) fws to call the new partitioned fw subgraph. + # Their additional saved-tensor outputs become dead and are pruned by + # eliminate_dead_code. + for identifier, extras in extra_fws_by_id.items(): + if not new_hop_graphs[identifier].partitioning_done: + continue + new_fw_hop_gm = new_hop_graphs[identifier].new_fw_hop_gm + if new_fw_hop_gm is None: + continue + for fw_node in extras: + fw_subgraph_attr = fw_node.args[0] + if not isinstance(fw_subgraph_attr, torch.fx.Node): + raise AssertionError( + f"expected fw invoke_subgraph HOP args[0] to be torch.fx.Node, " + f"got {type(fw_subgraph_attr)}" + ) + with joint_gm.graph.inserting_after(fw_node): + new_attr_name = add_new_hop_gm(new_fw_hop_gm, f"fw{identifier}") + new_attr = joint_gm.graph.get_attr(new_attr_name) + new_attr.meta = copy.copy(fw_subgraph_attr.meta) + with joint_gm.graph.inserting_after(new_attr): + new_fw_node = joint_gm.graph.call_function( + the_function=invoke_subgraph, + args=(new_attr, new_attr_name, *fw_node.args[2:]), + ) + propagate_meta_info(new_fw_hop_gm, new_fw_node, fw_node) + fw_node.replace_all_uses_with(new_fw_node) + joint_gm.graph.erase_node(fw_node) + + joint_gm.graph.eliminate_dead_code() + joint_gm.graph.lint() + joint_gm.recompile() + return joint_gm + + +def maybe_log_graph( + gm: torch.fx.GraphModule, + graph_name: str, + aot_config: AOTConfig, + structured_log_prefix_fn: Callable[[], str], + out_structured_logs: list[str] | None = None, +) -> None: + if not aot_config.enable_log: + return + aot_graphs_log.debug( + "%s", + lazy_format_graph_code( + f"{graph_name}", + gm, + aot_config.aot_id, + include_stride=True, + include_device=True, + colored=True, + ), + ) + + def gm_str_fn() -> str: + return gm.print_readable( + print_output=False, + include_stride=True, + include_device=True, + expanded_def=True, + ) + + if out_structured_logs is not None: + out_structured_logs.append(f"{structured_log_prefix_fn()}:{gm_str_fn()}") + else: + trace_structured( + f"{structured_log_prefix_fn()}", + payload_fn=lambda: gm_str_fn(), + ) + + +def create_wrap_fn( + fn: Callable[..., Any], args: tuple[Any, ...] +) -> tuple[Callable[..., Any], tuple[Any, ...]]: + from torch.fx.experimental.proxy_tensor import maybe_enable_thunkify + + from .functional_utils import from_fun, has_data_mutation, to_fun + + def assert_no_mutation(t: Any) -> None: + if has_data_mutation(t): + raise AssertionError( + "Saved tensors hooks with inputs mutations are not allowed" + ) + + @simple_wraps(fn) + def _wrapper(*args: Any) -> Any: + with maybe_enable_thunkify(): + disable_above = torch._C._ExcludeDispatchKeyGuard( + torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize) + ) + + with disable_above: + f_args = pytree.tree_map(to_fun, args) + f_outs = fn(*f_args) + pytree.tree_map(assert_no_mutation, f_args) + return pytree.tree_map(from_fun, f_outs) + + return _wrapper, args + + +def prepare_hook_gm( + aot_config: AOTConfig, fn: Callable[..., Any], args: tuple[Any, ...] +) -> torch.fx.GraphModule: + from torch._functorch._aot_autograd.graph_capture import _create_graph + + fn, args = create_wrap_fn(fn, args) + gm = _create_graph(fn, args, aot_config=aot_config) # type: ignore[arg-type] + return gm + + +# Inline Autograd saved_tensors_hooks into epilogue of forward graph +# and prologue of backward graph. +# This changes forward graph outputs and inputs. +# Pack hook can return tensors, sym scalars, constants. +# All tensors to save for backward will be grouped together at front. +# Sym scalars grouped on another end. Constants are inlined in the graph. +def maybe_inline_graph_saved_tensors_hooks( + fw_module: torch.fx.GraphModule, + bw_module: torch.fx.GraphModule, + num_inner_fwd_outputs: int, + inner_meta: ViewAndMutationMeta, + aot_config: AOTConfig, + static_input_indices: list[int], +) -> None: + if torch._dynamo.compiled_autograd.in_compiled_autograd_region: + return + + get_hooks = torch._functorch._aot_autograd.utils.top_saved_tensors_hooks + are_inline_hooks = ( + torch._functorch._aot_autograd.utils.saved_tensors_hooks_are_inlineable + ) + + hooks = get_hooks() + if not are_inline_hooks(hooks): + return + + pack_hook_gm, unpack_hook_gm = hooks + + structured_logs: list[str] = [] + maybe_log_graph( + fw_module, + "Forward graph pre saved_tensors_hooks inlining", + aot_config, + lambda: "aot_forward_graph_pre_saved_tensors_hooks", + structured_logs, + ) + maybe_log_graph( + bw_module, + "Backward graph pre saved_tensors_hooks inlining", + aot_config, + lambda: "aot_backward_graph_pre_saved_tensors_hooks", + structured_logs, + ) + fw_g = fw_module.graph + bw_g = bw_module.graph + + fw_g_names = {node.name for node in fw_g.nodes} + bw_g_names = {node.name for node in bw_g.nodes} + + def _gen_unused_name(candidate: str) -> str: + c = candidate + i = 0 + while c in fw_g_names or c in bw_g_names: + c = f"{candidate}_{i}" + i = i + 1 + return c + + bw_g_inputs = bw_g.find_nodes(op="placeholder") + + fw_out_n = fw_g.output_node() + fw_outs = fw_out_n.args[0] # type: ignore[var-annotated] + fw_outs_inner_set = set(fw_outs[:num_inner_fwd_outputs]) # type: ignore[index] + fw_outs_saved_for_bw = fw_outs[num_inner_fwd_outputs:] # type: ignore[index] + fw_outs_packed_tensors = [] # type: ignore[var-annotated] + fw_outs_packed_syms = [] # type: ignore[var-annotated] + + # The main use case for saved_tensors_hooks is activation quantization, + # for memory usage optimization. + # Desired behavior is to quantize saved activations to free the original saved tensor. + # Saved nodes may include forward inputs, outputs, parameters. + # They may be held by something else and will not be deallocated after quantization. + # Donated buffers are intermediates in the graph invisible for the user, + # this guarantees that they can be deallocated. + # Using this as a default behavior to select saved nodes to apply hooks. + # There is also a config to apply hooks for all saved nodes without any filtering. + # The plan is to propagate meta about the source of the saved node to the user hook function. + mode = torch._functorch.config.saved_tensors_hooks_filtering_mode + allow_set = None + exclude_set = None + + if mode == "donated": + # collect_bw_donated_buffer_idxs requires inner_meta to have num_symints_saved_for_bw + inner_meta.num_symints_saved_for_bw = len( + [n for n in fw_outs_saved_for_bw if is_sym_node(n)] # type: ignore[arg-type] + ) + # Count tensors with no version counter check (used in tensors_saved_for_backwards_slice) + inner_meta.num_tensors_saved_with_no_vc_check = len( + [ + n + # pyrefly: ignore [not-iterable] + for n in fw_outs_saved_for_bw + if isinstance(n, torch.fx.Node) + and n.meta.get("saved_tensor_with_no_vc_check", False) + ] + ) + bw_donated_idxs = collect_bw_donated_buffer_idxs( + fw_module, + bw_module, + inner_meta, + ) + fw_donated_idxs = [ + i - inner_meta.num_symints_saved_for_bw for i in bw_donated_idxs + ] + allow_set = {fw_outs_saved_for_bw[i].name for i in fw_donated_idxs} # type: ignore[union-attr] + elif mode == "no_static": + fw_g_inputs = fw_g.find_nodes(op="placeholder") + exclude_set = {fw_g_inputs[i].name for i in static_input_indices} + + if (allow_set is not None) and (not allow_set): + # This means we have empty whitelist, + # No donated (intermediate) saved. + # Do not do anything in this case + return + + if aot_config.enable_log: + structured_logs.append(f"fw_outs_saved_for_bw:{fw_outs_saved_for_bw}") + structured_logs.append(f"mode:{mode}") + structured_logs.append(f"allow_set:{allow_set}") + structured_logs.append(f"exclude_set:{exclude_set}") + + # pyrefly: ignore [not-iterable] + for saved in fw_outs_saved_for_bw: + if ((allow_set is not None) and (saved.name not in allow_set)) or ( # type: ignore[union-attr] + (exclude_set is not None) and (saved.name in exclude_set) # type: ignore[union-attr] + ): + if isinstance(saved.meta["val"], torch.Tensor): # type: ignore[union-attr] + fw_outs_packed_tensors.append(saved) + continue + + val = saved.meta["val"] # type: ignore[union-attr] + if not isinstance(val, torch.Tensor): + continue + + def _get_extra_info() -> dict[str, Any]: + return {"_fw_graph": fw_g, "_bw_graph": bw_g, "_node": saved} + + with _saved_tensor_hook_context(_get_extra_info()): + pack_out_val = pack_hook_gm(val) + + requires_sc_handling = any( + is_traceable_wrapper_subclass(x) for x in pytree.tree_leaves(pack_out_val) + ) + if requires_sc_handling: + raise NotImplementedError( + "Tensor subclasses in GraphModule saved tensors hooks are not supported" + "You can workaround it by manually returning subclass's inner tensors" + " in the pack hook, and reconstructing the subclass in the unpack hook" + ) + + with _saved_tensor_hook_context(_get_extra_info()): + pack_gm = prepare_hook_gm(aot_config, pack_hook_gm, (val,)) + pack_g = pack_gm.graph + maybe_log_graph( + pack_gm, + f"saved_tensors_pack_hook {saved.name}", # type: ignore[union-attr] + aot_config, + lambda: f"aot_saved_tensors_hooks_pack {saved.name}", # type: ignore[union-attr] + structured_logs, + ) + pack_out_val = pack_gm(val) + + # Install pack hook graph as eiplogue of fw_module. + # Saved tensor output becomes input of pack hook graph. + # Replace saved tensor output with pack hook graph output. + # Outputs symbolic scalars, tensors are accumulated separately. + # Then in forward outputs and backward inputs installed in order + # sym_scalars, packed_saved_tensors. + # Keeping all tensors together allows to preserve + # the same identification at runtime, + # updating only number of saved sym_scalars and tensors. + pack_g_inputs = pack_g.find_nodes(op="placeholder") + if len(pack_g_inputs) != 1: + raise AssertionError( + f"expected exactly 1 pack_g_input, got {len(pack_g_inputs)}" + ) + env = {pack_g_inputs[0]: saved} + fw_pack_out_args = None + with fw_g.inserting_before(fw_out_n): + for node in pack_g.nodes: + if node.op == "placeholder": + continue + new_n = fw_g.node_copy(node, lambda n: env[n]) + fw_g_names.add(new_n.name) + env[node] = new_n + # Output node is temporarily copied to have remapped arguments. + # Removed in the end. + if node.op == "output": + fw_pack_out_args = new_n.args[0] + fw_g.erase_node(new_n) + + env.clear() + if not fw_pack_out_args: + raise AssertionError("fw_pack_out_args must not be empty") + fw_outs_bw_ins_node_names = [] + for out_idx, _n in enumerate(pytree.tree_leaves(fw_pack_out_args)): + if not isinstance(_n, torch.fx.Node): + fw_outs_bw_ins_node_names.append("") + continue + + # This happens when hook is noop and it is either user input or user output. + # Do not do anything with this node. + if _n.op == "placeholder" or _n in fw_outs_inner_set: + # This means the hook returned input primals unchanged + # Do not rename in this case. + n = _n + new_node_name = _n.name + fw_outs_bw_ins_node_names.append(new_node_name) + else: + # We can not specify desired name in node_copy. + # Copying node manually to set specific name, + # to have matching fw_outs, bw_inputs names. + new_node_name = _gen_unused_name(f"{saved.name}_hook_{out_idx}") # type: ignore[union-attr] + with fw_g.inserting_before(_n): + n = fw_g.create_node( + _n.op, + _n.target, + _n.args, + _n.kwargs, + name=new_node_name, + ) + if n.name != new_node_name: + raise AssertionError( + f"expected n.name == {new_node_name}, got {n.name}" + ) + fw_outs_bw_ins_node_names.append(new_node_name) + n.meta = copy.copy(_n.meta) + _n.replace_all_uses_with(n) + fw_g.erase_node(_n) + if isinstance(n.meta["val"], torch.Tensor): + fw_outs_packed_tensors.append(n) + elif is_sym_node(n): + fw_outs_packed_syms.append(n) + + # Install unpack hook graph as a prologue of backward graph + # Saved tensors inputs are replaced with packed tensors and packed sym scalars. + # The saved tensors inputs usages in the graph are replaced with unpack hook graph outputs. + with _saved_tensor_hook_context(_get_extra_info()): + unpack_gm = prepare_hook_gm(aot_config, unpack_hook_gm, (pack_out_val,)) + unpack_g = unpack_gm.graph + maybe_log_graph( + unpack_gm, + f"saved_tensors_unpack_hook {saved.name}", # type: ignore[union-attr] + aot_config, + lambda: f"aot_saved_tensors_hooks_unpack {saved.name}", # type: ignore[union-attr] + structured_logs, + ) + + def find_saved_in_bw_inputs( + bw_inputs: list[torch.fx.Node], + ) -> torch.fx.Node | None: + for n in bw_inputs: + if n.name == saved.name: # type: ignore[union-attr] + return n + + bw_g_input = find_saved_in_bw_inputs(bw_g_inputs) + if not bw_g_input: + raise AssertionError( + f"could not find saved tensor {saved.name} in bw_g_inputs" # type: ignore[union-attr] + ) + original_bw_g_input_users = list(bw_g_input.users.keys()) + bw_g_input_used_directly = False + + # Replace backward graph saved tensor input with copy of pack graph outputs + # All non-Tensor, non-symscalars outputs are constanted. + + unpack_g_inputs = unpack_g.find_nodes(op="placeholder") + env = {} + for out_idx, (unp_in_n, out_n, val) in enumerate( + zip( + unpack_g_inputs, + pytree.tree_leaves(fw_pack_out_args), + pytree.tree_leaves(pack_out_val), + ) + ): + is_sym = isinstance(val, py_sym_types) + if isinstance(val, torch.Tensor) or is_sym: + # We want forward_outputs names to match backward_inputs, + # Potentially backward may already have "{saved.name}_hook_{idx}", + # In this case fx.Graph will add suffix. + new_node_name = fw_outs_bw_ins_node_names[out_idx] + if bw_g_input.name == new_node_name: + env[unp_in_n] = bw_g_input + bw_g_input_used_directly = True + else: + # Backward calling convention: ctx_symints,ctx_saved_tensors + # Inserting packed sym scalars before first saved tensor input. + # Inserting packed tensors before last saved tensor input. + # Saved tensor inputs between them will be removed. + with ( + bw_g.inserting_before(bw_g_inputs[0]) + if is_sym + else bw_g.inserting_before(bw_g_input) + ): + new_n = bw_g.placeholder(new_node_name) + if new_n.name != new_node_name: + raise AssertionError( + f"expected new_n.name == {new_node_name}, got {new_n.name}" + ) + new_n.meta = copy.copy(out_n.meta) + env[unp_in_n] = new_n + else: + # Inline values of non-Tensor, non-SymScalars + env[unp_in_n] = val + + # Inserting unpack hook after placeholders. + bw_unpack_out_n = None + with bw_g.inserting_before(bw_g_inputs[-1].next): + for node in unpack_g.nodes: + if node.op == "placeholder": + continue + new_n = bw_g.node_copy(node, lambda n: env[n]) + bw_g_names.add(new_n.name) + env[node] = new_n + # Temporary insert output, to have remapped by node_copy args. + # Removed in the end. + if node.op == "output": + bw_unpack_out_n = new_n + + if not bw_unpack_out_n: + raise AssertionError("bw_unpack_out_n must not be None") + _leaves = pytree.tree_leaves(bw_unpack_out_n.args) + if len(_leaves) != 1: + raise AssertionError(f"expected exactly 1 leaf, got {len(_leaves)}") + unpack_saved_tensor_n = _leaves[0] + + if not bw_g_input_used_directly: + bw_g_input.replace_all_uses_with(unpack_saved_tensor_n) + bw_g.erase_node(bw_g_input) + else: + # Keep usages of bw_g_input in inserted unpacked hook graph. + # Replace other usages of bw_g_input with unpack_saved_tensor_n. + for use_node in original_bw_g_input_users: + use_node._replace_input_with(bw_g_input, unpack_saved_tensor_n) + bw_g.erase_node(bw_unpack_out_n) + + # Changing forward graph outputs, + # Inserting packed_tensors and packed_syms on the place of saved tensors. + # Packed sym_scalars are together with saved symints + symint_outs_saved_for_bw = [n for n in fw_outs_saved_for_bw if is_sym_node(n)] # type: ignore[arg-type] + fw_new_outs = pytree.tree_leaves( + ( + fw_outs[:num_inner_fwd_outputs], # type: ignore[index] + fw_outs_packed_tensors, + fw_outs_packed_syms, + symint_outs_saved_for_bw, + ) + ) + fw_out_n.args = (tuple(fw_new_outs),) + + # Assert that saved tensors and symints in forward outputs are aligned with backward inputs + _fw_n = num_inner_fwd_outputs + _fw_num_t = len(fw_outs_packed_tensors) + _fw_num_s = len(fw_outs_packed_syms) + len(symint_outs_saved_for_bw) + fw_outs_saved_tensors = fw_new_outs[_fw_n : _fw_n + _fw_num_t] + fw_outs_saved_syms = fw_new_outs[_fw_n + _fw_num_t :] + bw_new_ins = list(bw_g.find_nodes(op="placeholder")) + bw_ins_saved_syms = bw_new_ins[:_fw_num_s] + bw_ins_saved_tensors = bw_new_ins[_fw_num_s : _fw_num_s + _fw_num_t] + + fw_t_names = [n.name for n in fw_outs_saved_tensors] + bw_t_names = [n.name for n in bw_ins_saved_tensors] + fw_s_names = [n.name for n in fw_outs_saved_syms] + bw_s_names = [n.name for n in bw_ins_saved_syms] + + def _log_structured_logs() -> None: + if not aot_config.enable_log: + return + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "aot_saved_tensors_hooks_graphs", + "encoding": "string", + }, + payload_fn=lambda: "\n".join(structured_logs), + ) + + if aot_config.enable_log: + structured_logs.append( + f"fw_outs[:num_inner_fwd_outputs]:{fw_outs[:num_inner_fwd_outputs]}" # type: ignore[index] + ) + structured_logs.append(f"fw_outs_packed_tensors:{fw_outs_packed_tensors}") + structured_logs.append(f"fw_t_names:{fw_t_names}") + structured_logs.append(f"bw_t_names:{bw_t_names}") + structured_logs.append(f"fw_s_names:{fw_s_names}") + structured_logs.append(f"bw_s_names:{bw_s_names}") + structured_logs.append(f"\nfw_g_pre_assert:{fw_g}") + structured_logs.append(f"\nbw_g_pre_assert:{bw_g}") + maybe_log_graph( + fw_module, + "Forward graph after transform pre-assert", + aot_config, + lambda: "aot_forward_graph_pre_assert_saved_tensors_hooks", + structured_logs, + ) + maybe_log_graph( + bw_module, + "Backward graph after transform pre-assert", + aot_config, + lambda: "aot_backward_graph_pre_assert_saved_tensors_hooks", + structured_logs, + ) + _log_structured_logs() + + if fw_t_names != bw_t_names: + raise AssertionError( + f"expected fw_t_names == bw_t_names, got {fw_t_names} != {bw_t_names}" + ) + if fw_s_names != bw_s_names: + raise AssertionError( + f"expected fw_s_names == bw_s_names, got {fw_s_names} != {bw_s_names}" + ) + + fw_g.lint() + bw_g.lint() + fw_module.recompile() + bw_module.recompile() + + +def _log_joint_graph( + fx_g: torch.fx.GraphModule, + aot_config: AOTConfig, +) -> str | None: + """ + Log the joint graph to the structured logger. + Return a str representation of the graph. + """ + joint_graph_str = None + if aot_config.enable_log: + aot_joint_log.info( + "%s", + lazy_format_graph_code( + "Joint graph", + fx_g, + aot_config.aot_id, + include_stride=True, + include_device=True, + colored=True, + ), + ) + joint_graph_str = fx_g.print_readable( + print_output=False, + include_stride=True, + include_device=True, + expanded_def=True, + ) + trace_structured( + "aot_joint_graph", + payload_fn=lambda: joint_graph_str, + ) + return joint_graph_str + + +def _log_fw_bw_graphs( + fw_module: torch.fx.GraphModule, + bw_module: torch.fx.GraphModule, + maybe_subclass_meta: SubclassMeta | None, + fw_metadata: ViewAndMutationMeta, + aot_config: AOTConfig, +) -> tuple[str | None, str | None]: + """ + Log the fw and bw graphs to the structured logger. + Return str representations of the graphs. + """ + fw_module_str = None + bw_module_str = None + if aot_config.enable_log: + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "torch._functorch.config", + "encoding": "string", + }, + payload_fn=lambda: torch._functorch.config.get_serializable_config_copy(), + ) + aot_graphs_log.info( + "aot_config id: %s, fw_metadata=%s, inner_meta=%s", + aot_config.aot_id, + fw_metadata, + _get_inner_meta(maybe_subclass_meta, fw_metadata), + ) + + aot_graphs_log.info( + "%s", + lazy_format_graph_code( + "Forward graph", + fw_module, + aot_config.aot_id, + include_stride=True, + include_device=True, + colored=True, + ), + ) + aot_graphs_log.info( + "%s", + lazy_format_graph_code( + "Backward graph", + bw_module, + aot_config.aot_id, + include_stride=True, + include_device=True, + colored=True, + ), + ) + fw_module_str = fw_module.print_readable( + print_output=False, + include_stride=True, + include_device=True, + expanded_def=True, + ) + bw_module_str = bw_module.print_readable( + print_output=False, + include_stride=True, + include_device=True, + expanded_def=True, + ) + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "aot_forward_graph_fw_metadata", + "encoding": "string", + }, + payload_fn=lambda: dataclass_repr(fw_metadata), + ) + if maybe_subclass_meta is not None: + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "aot_forward_graph_fw_subclass_metadata", + "encoding": "string", + }, + payload_fn=lambda: dataclass_repr(maybe_subclass_meta), + ) + + trace_structured( + "aot_forward_graph", + payload_fn=lambda: fw_module_str, + ) + trace_structured( + "aot_backward_graph", + payload_fn=lambda: bw_module_str, + ) + return fw_module_str, bw_module_str + + +def _partition_joint_graph_into_fw_bw( + fx_g: torch.fx.GraphModule, + joint_inputs: list[Any] | tuple[list[Any], list[Any]], + inner_meta: ViewAndMutationMeta, + fw_metadata: ViewAndMutationMeta, + aot_config: AOTConfig, + # pyrefly: ignore [implicit-any] + partition_fn: Callable, +) -> tuple[torch.fx.GraphModule, torch.fx.GraphModule, int]: + # See Note: [Partitioner handling for Subclasses, Part 1] + # See Note: [Recomputing subclass mutation handling] + mutated_inp_runtime_indices = compute_inner_mutated_inp_indices_from_subclass_meta( + fw_metadata, inner_meta + ) + num_tokens = len(fw_metadata.tokens) + num_inner_fwd_outputs = ( + len(mutated_inp_runtime_indices) + + inner_meta.num_outputs + + inner_meta.num_intermediate_bases + + inner_meta.num_outputs_rng_offset + + num_tokens # See Note [Side-Effectful Tokens in AOTAutograd] + ) + + fx_g = run_joint_graph_passes_on_hops( + fx_g, joint_inputs, aot_config, default_partition_fn=partition_fn + ) + + # apply joint_gm callback here + if callable(torch._functorch.config.joint_custom_pass): + # pyrefly: ignore [bad-assignment] + fx_g = torch._functorch.config.joint_custom_pass(fx_g, joint_inputs) + + fw_module, bw_module = partition_fn( + fx_g, + joint_inputs, + num_fwd_outputs=num_inner_fwd_outputs, + static_lifetime_input_indices=fw_metadata.static_input_indices, + ) + + rng_states = [ + n + for n in fw_module.graph.find_nodes(op="placeholder") + if "fwd_rng_state" in n.name + ] + fw_metadata.num_graphsafe_rng_states = len(rng_states) + if rng_states: + rng_device = rng_states[0].meta["val"].device + fw_metadata.graphsafe_rng_state_index = rng_device.index + fw_metadata.graphsafe_rng_device = rng_device + + return fw_module, bw_module, num_inner_fwd_outputs + + +def _joint_inputs_for_forward( + joint_inputs: list[Any] | tuple[list[Any], list[Any]], +) -> list[Any]: + return joint_inputs[0] if isinstance(joint_inputs, tuple) else joint_inputs + + +def _maybe_unlift_partitioned_effect_tokens( + fw_module: torch.fx.GraphModule, + bw_module: torch.fx.GraphModule, + joint_inputs: list[Any] | tuple[list[Any], list[Any]], + fw_metadata: ViewAndMutationMeta, + aot_config: AOTConfig, + num_inner_fwd_outputs: int, +) -> tuple[int, list[Any] | tuple[list[Any], list[Any]]]: + num_tokens = len(fw_metadata.tokens) + + # See Note [Side-Effectful Tokens in AOTAutograd] + if config.unlift_effect_tokens and ( + num_tokens > 0 or fw_metadata.num_backward_tokens > 0 + ): + unlift_tokens(fw_module, fw_metadata, aot_config, bw_module) + num_inner_fwd_outputs -= num_tokens + if isinstance(joint_inputs, tuple): + joint_inputs = ( + _joint_inputs_for_forward(joint_inputs)[num_tokens:], + joint_inputs[1], + ) + else: + joint_inputs = joint_inputs[num_tokens:] + + return num_inner_fwd_outputs, joint_inputs + + +def _categorize_saved_tensors_for_backward( + fw_module: torch.fx.GraphModule, + bw_module: torch.fx.GraphModule, + inner_meta: ViewAndMutationMeta, + fw_metadata: ViewAndMutationMeta, + num_inner_fwd_outputs: int, +) -> tuple[int, int]: + fw_outs = next(iter(fw_module.graph.find_nodes(op="output"))).args[0] + # we only need to bookkeep the symints that are saved for bw, not any symints + # the user forward might have returned in its own output + fw_outs_saved_for_bw = fw_outs[num_inner_fwd_outputs:] + num_fw_outs_saved_for_bw = len(fw_outs_saved_for_bw) + + num_symints_saved_for_bw = 0 + num_opaque_objects_saved_for_bw = 0 + saved_tensor_is_graph_input: list[bool] = [] + for idx, node in enumerate(fw_outs_saved_for_bw): + if is_sym_node(node): + num_symints_saved_for_bw += 1 + elif is_opaque_node(node): + num_opaque_objects_saved_for_bw += 1 + elif isinstance(node, torch.fx.Node) and "val" in getattr(node, "meta", {}): + if is_fake_tensor(node.meta["val"]): + # If the saved_tensor is a view, a graph intermediate, + # and returned from the autograd.Function output, we need to + # detach() it to prevent a reference cycle. Record + # if the saved_tensor is a graph input here to help. + saved_tensor_is_graph_input.append(node.op == "placeholder") + # record dynamic tensor activations + dynamic_dims: set[int] = { + dim + for dim, size in enumerate(node.meta["val"].shape) + if not isinstance(size, int) + } + if dynamic_dims: + fw_metadata.dynamic_saved_tensors_idxs[idx] = dynamic_dims + elif isinstance(node.meta["val"], (FakeScriptObject, CustomClassBase)): + num_opaque_objects_saved_for_bw += 1 + else: + saved_tensor_is_graph_input.append(False) + + fw_metadata.num_symints_saved_for_bw = num_symints_saved_for_bw + fw_metadata.num_opaque_objects_saved_for_bw = num_opaque_objects_saved_for_bw + num_tensors_saved_for_bw = ( + num_fw_outs_saved_for_bw + - num_symints_saved_for_bw + - num_opaque_objects_saved_for_bw + ) + if len(saved_tensor_is_graph_input) != num_tensors_saved_for_bw: + raise AssertionError( + "expected one saved_tensor_is_graph_input entry per saved tensor, " + f"got {len(saved_tensor_is_graph_input)} != {num_tensors_saved_for_bw}" + ) + fw_metadata.saved_tensor_is_graph_input = saved_tensor_is_graph_input + inner_meta.num_symints_saved_for_bw = num_symints_saved_for_bw + inner_meta.num_opaque_objects_saved_for_bw = num_opaque_objects_saved_for_bw + inner_meta.saved_tensor_is_graph_input = saved_tensor_is_graph_input + + # See Note [Activations with no version counter checks in eager] + # Count tensors saved with no version counter check. + # These are tensors that were stashed on ctx (e.g., ctx.x = x) rather than + # via save_for_backward in an autograd.Function. + # The partitioner sorts these to be at the end of saved_values. + num_tensors_saved_with_no_vc_check = sum( + 1 + for node in fw_outs_saved_for_bw + if isinstance(node, torch.fx.Node) + and node.meta.get("saved_tensor_with_no_vc_check", False) + ) + fw_metadata.num_tensors_saved_with_no_vc_check = num_tensors_saved_with_no_vc_check + inner_meta.num_tensors_saved_with_no_vc_check = num_tensors_saved_with_no_vc_check + + if torch._functorch.config.donated_buffer: + fw_metadata.bw_donated_idxs = collect_bw_donated_buffer_idxs( + fw_module, + bw_module, + inner_meta, + ) + inner_meta.bw_donated_idxs = fw_metadata.bw_donated_idxs + + return num_fw_outs_saved_for_bw, num_symints_saved_for_bw + + +# Note [Detaching inputs that never need gradients] +# See https://github.com/pytorch/pytorch/issues/97745 +# Suppose we have a function like this that we want to compile: +# +# def f(x, y): +# return torch.mul(x, y.detach()) +# +# What gradients should we compute for x and y? +# By default, AOTAutograd will compute a gradient for **every** input that requires gradients, +# and so we'll compute: +# x_grad_input = y +# y_grad_input = None +# Does this preserve the semantics of eager mode? +# Unfortunately, no. +# Doing the above will cause autograd to **continue** to backprop the autograd tape +# that was generated from constructing y. +# +# This is **different** from what would have happened in eager mode. +# In eager mode, if we backprop through the output of this function, autograd will only traverse +# the bit of the autograd tape corresponding to "x". +# In particular, if a user had previously backpropped through y's autograd tape, +# And then they try to backprop through the output of the above function, +# then we'll hit the dreaded "Trying to backward through the graph a second time" error. +# +# You might think: If autograd sees that a gradient is None, shouldn't it stop early, +# instead of continuing the backprop through the ancestors of that node in the graph? +# +# Autograd has two passes: +# (1) a first pass that traverses the autograd graph and figures out which nodes need to be executed +# (2) a second pass that actually goes ahead and executes each node when it becomes ready, +# propagating gradients +# By the time we're executing a node and we see that it produces a None, the set of nodes to execute +# is already locked-in. +# +# The fix: instead, we can recognize statically that the graph we're compiling will never contribute +# gradients to y, and prevent autograd from trying to traverse y's autograd tape at all. +# We can do this by manually detach'ing y before sending it through the `CompiledFunction`. +# +# Note that this solution is not bulletproof. +# It's possible to construct a case where eager may or may not have tried to autograd through y, +# depending on the actual grad_outputs that were passed in during the backward. +# There is no easy fix for this: the simplest fix would be to run with `retain_graph=True`, +# allowing autograd to reuse the graph. +# +# An example of this case is: +# def f(x): +# return x.detach() * 2, x * 3 +# If we were to only backprop through outs[0], in eager, we would stop +# If we backward only on the first output, we shouldn't send a grad through x. +# But the custom autograd function doesn't know that: it will materialize zero grads for x * 3 +# and we will end up with a zero grad at x. +# If we later backprop through the second output, this will also require backprop'ing through x. +# Meaning we'll need to use `retain_graph=True` to be able to backprop through x the second time. +def _compute_indices_of_inps_to_detach( + bw_module: torch.fx.GraphModule, + maybe_subclass_meta: SubclassMeta | None, + inner_meta: ViewAndMutationMeta, + fw_metadata: ViewAndMutationMeta, +) -> list[int]: + # TODO: we should apply the below "detach inputs if their gradients are statically known to be None" + # optimization even if we have subclass inputs/outputs (we do not handle this today). + # Computing which our our inputs get None gradients is a bit more complicated, + # if any of our inputs are subclasses. Why? + # (a) we need to make sure that we call .detach() on the input subclasses, since autograd sees subclasses. + # (b) The grad_outputs that we AOT computed in our backward graph are the desugared tensor tensors, + # so we need to figure out which subclass fw inputs they map to. + if maybe_subclass_meta is not None: + return [] + + indices_of_inps_to_detach: list[int] = [] + + # reversed() since we expect output at end of graph + bw_output = next(reversed(bw_module.graph.find_nodes(op="output"))) + bw_outs = bw_output.args[0] + + num_backward_tokens = inner_meta.num_backward_tokens + expected_bw_outs = ( + len(fw_metadata.input_info) + + inner_meta.num_outputs_rng_offset + + num_backward_tokens + ) + if len(bw_outs) != expected_bw_outs: + raise AssertionError( + f"expected len(bw_outs) == {expected_bw_outs}, got {len(bw_outs)}" + ) + + bw_outs_no_rng_no_tokens = bw_outs + if (inner_meta.num_outputs_rng_offset + num_backward_tokens) > 0: + bw_outs_no_rng_no_tokens = bw_outs[ + : -(inner_meta.num_outputs_rng_offset + num_backward_tokens) + ] + if len(bw_outs_no_rng_no_tokens) != len(fw_metadata.input_info): + raise AssertionError( + f"expected len(bw_outs_no_rng_no_tokens) == {len(fw_metadata.input_info)}, " + f"got {len(bw_outs_no_rng_no_tokens)}" + ) + + for i, bw_out in enumerate(bw_outs_no_rng_no_tokens): + # If our input experiences a metadata mutation inside the graph (e.g. set_()), + # we *must* not detach, otherwise it will be the detach'd input that gets the metadata mutation + metadata_mutation_in_graph = ( + fw_metadata.input_info[i].mutation_type == MutationType.MUTATED_IN_GRAPH + and fw_metadata.input_info[i].mutates_storage_metadata + ) + is_non_leaf = ( + fw_metadata.input_info[i].requires_grad + and not fw_metadata.input_info[i].is_leaf + ) + if bw_out is None and not metadata_mutation_in_graph and is_non_leaf: + indices_of_inps_to_detach.append(i) + + return indices_of_inps_to_detach + + +def _aot_stage2a_partition( + fx_g: torch.fx.GraphModule, + joint_inputs: list[Any] | tuple[list[Any], list[Any]], + maybe_subclass_meta: SubclassMeta | None, + fw_metadata: ViewAndMutationMeta, + aot_config: AOTConfig, + # pyrefly: ignore [implicit-any] + partition_fn: Callable, +) -> tuple[torch.fx.GraphModule, torch.fx.GraphModule, int, int, list[int], list[Any]]: + """ + Partition the joint graph into a forward graph and a backward graph. Returns: + - the forward and backward graphs + - the number of forward outputs and the number of symints saved for backward + - indices of inputs to detach + - adjusted inputs to forward + """ + disable_amp = torch._C._is_any_autocast_enabled() + inner_meta = _get_inner_meta(maybe_subclass_meta, fw_metadata) + + with torch.no_grad(): + context = torch._C._DisableAutocast if disable_amp else nullcontext + with context(), track_graph_compiling(aot_config, "joint"): + fw_module, bw_module, num_inner_fwd_outputs = ( + _partition_joint_graph_into_fw_bw( + fx_g, + joint_inputs, + inner_meta, + fw_metadata, + aot_config, + partition_fn, + ) + ) + num_inner_fwd_outputs, joint_inputs = ( + _maybe_unlift_partitioned_effect_tokens( + fw_module, + bw_module, + joint_inputs, + fw_metadata, + aot_config, + num_inner_fwd_outputs, + ) + ) + + maybe_inline_graph_saved_tensors_hooks( + fw_module, + bw_module, + num_inner_fwd_outputs, + inner_meta, + aot_config, + fw_metadata.static_input_indices, + ) + num_fw_outs_saved_for_bw, num_symints_saved_for_bw = ( + _categorize_saved_tensors_for_backward( + fw_module, + bw_module, + inner_meta, + fw_metadata, + num_inner_fwd_outputs, + ) + ) + + _indices_of_inps_to_detach = _compute_indices_of_inps_to_detach( + bw_module, + maybe_subclass_meta, + inner_meta, + fw_metadata, + ) + + return ( + fw_module, + bw_module, + num_fw_outs_saved_for_bw, + num_symints_saved_for_bw, + _indices_of_inps_to_detach, + _joint_inputs_for_forward(joint_inputs), + ) + + +def _aot_stage2b_fw_compile( + fw_module: torch.fx.GraphModule, + adjusted_flat_args: list[Any], + maybe_subclass_meta: SubclassMeta | None, + fw_metadata: ViewAndMutationMeta, + num_fw_outs_saved_for_bw: int, + aot_config: AOTConfig, + # pyrefly: ignore [implicit-any] + fw_compiler: Callable, + # pyrefly: ignore [implicit-any] +) -> tuple[list[tuple[int, ...] | None] | None, Callable]: + return _aot_stage2b_compile_forward_or_inference( + fw_module, + adjusted_flat_args, + maybe_subclass_meta, + fw_metadata, + aot_config, + fw_compiler, + is_inference=False, + num_fw_outs_saved_for_bw=num_fw_outs_saved_for_bw, + ) + + +def _aot_stage2b_bw_compile( + bw_module: torch.fx.GraphModule, + maybe_subclass_meta: SubclassMeta | None, + fw_metadata: ViewAndMutationMeta, + fwd_output_strides: list[tuple[int, ...] | None] | None, + num_symints_saved_for_bw: int, + aot_config: AOTConfig, + # pyrefly: ignore [implicit-any] + bw_compiler: Callable, + # pyrefly: ignore [implicit-any] +) -> tuple[AutogradLazyBackwardCompileInfo, Callable | None]: + """ + Compile the backward graph. Returns: + - the placeholder list for the backward graph + - the compiled backward function + """ + with torch.no_grad(): + # NB: It's important to compile backwards ahead of time, as this may + # add extra guards which we need to apply to the Dynamo cache at + # forwards + with track_graph_compiling(aot_config, "backward"), torch._C._DisableAutocast(): + placeholder_list = fx_placeholder_vals(bw_module) + + forward_saved_for_backwards_strides = None + if fwd_output_strides is not None: + inner_meta = _get_inner_meta(maybe_subclass_meta, fw_metadata) + forward_saved_for_backwards_strides = fwd_output_strides[ + inner_meta.tensors_saved_for_backwards_slice + ] + + # saved activations can have different stride to eager if + # the compiler does layout optimization. We should restride the + # tensor passed in for compiling the backward graph using the + # saved tensor's stride. + for i in range(len(placeholder_list)): + ph_arg = placeholder_list[i] + if not isinstance(ph_arg, torch.Tensor): + continue + + if forward_saved_for_backwards_strides is None: + continue + + real_stride = None + # Per all_args calling convention + j = i - num_symints_saved_for_bw + if 0 <= j < len(forward_saved_for_backwards_strides): + real_stride = forward_saved_for_backwards_strides[j] + if real_stride is None: + continue + + # Comparing ph_arg.stride() with real_stride directly may + # cause dynamic dimensions in ph_arg being specialized to static + # value. Using suppress_guards and guard_or_true to avoid that. + + stride_different = False + fake_mode = detect_fake_mode() + suppress_ctx = ( + fake_mode.shape_env.suppress_guards() + if fake_mode is not None and fake_mode.shape_env is not None + else nullcontext() + ) + + # Inductor can choose different strides for activations than + # what backward graph has. if we can't statically tell that + # strides are the same, we assume they are not. + with suppress_ctx: + for k in range(len(ph_arg.stride())): + # real_stride can't be symbolic. + + if guard_or_true(ph_arg.stride()[k] != int(real_stride[k])): + stride_different = True + break + + if stride_different: + # Note that here we use the stride of the real tensor to + # restride a FakeTensor. This does not cause trouble + # for dynamic shape since this code path only get + # executed if layout optimization is enabled. And we + # disable layout optimization for dynamic shape right + # now. + # + # A solution that decide stride order based on real + # tensor's stride and then apply that stride order to + # the FakeTensor does not work smoothly since some + # tensor's layout is not 'dense'. E.g. mixnet_l has a + # tensor with size [8, 64, 112, 112] and strides + # (2408448, 1, 21504, 192). The solution mentioned will + # decide a stride of (802816, 1, 7168, 64) for this + # tensor which is wrong. + + ph_size = ph_arg.size() + + placeholder_list[i] = ph_arg.as_strided(ph_size, real_stride) + compiled_bw_func = None + if ( + num_symints_saved_for_bw > 0 + or aot_config.force_non_lazy_backward_lowering + ): + try: + # See Note: [Backward graph lazy lowering] + with torch._subclasses.fake_tensor.unset_fake_temporarily(): + # If bw_module contains lifted constants, they will be real tensors stored as + # GraphModule. Deepcopying tensors under fake mode is not supported and will + # raise when attempting to set storage. + bw_module_copy = copy.deepcopy(bw_module) + compiled_bw_func = bw_compiler(bw_module_copy, placeholder_list) + del bw_module_copy + except Exception as e: + if aot_config.force_non_lazy_backward_lowering: + raise + exc = e + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "eager_compile_backwards_failure", + "encoding": "string", + }, + payload_fn=lambda: "\n".join( + traceback.format_exception( + type(exc), exc, exc.__traceback__ + ) + ), + ) + log.warning( + "failed to eagerly compile backwards for dynamic, suppressing in case backwards not needed", + exc_info=True, + ) + # Compiled autograd will run the bw_module in the backward pass, + # so recompilation need happen anyway if the backward pass is ever + # called. + # + # The reason we do the GraphModule recompilation here is because + # the lazy recompilation will cause issue in the backward pass + # with compiled autograd. + # + # Do the _LazyGraphModule.force_recompile here rather than when + # bw_module is first generated by the partitioner because the bw_module.recompile + # may be called in some code path later and cause the _LazyGraphModule.forward + # becomes the lazy version again. One example is when dynamic shape is enabled + # upfront, the bw_compiler will be called above which can cause extra + # graph module recompilation on bw_module. + if torch._dynamo.compiled_autograd.in_compiled_autograd_region: + from torch.fx._lazy_graph_module import _LazyGraphModule + + _LazyGraphModule.force_recompile(bw_module) + + saved_context = TracingContext.try_get() + saved_compile_context = CompileContext.try_get() + + lazy_backward_info = AutogradLazyBackwardCompileInfo( + # pyrefly: ignore [bad-argument-type] + bw_module, + placeholder_list, + saved_context, + saved_compile_context, + ) + + return lazy_backward_info, compiled_bw_func + + +def aot_stage2_autograd( + aot_state: AOTState, + aot_graph_capture: AOTGraphCapture, + # pyrefly: ignore [implicit-any] + partition_fn: Callable, + # pyrefly: ignore [implicit-any] + fw_compiler: Callable, + # pyrefly: ignore [implicit-any] + bw_compiler: Callable, +) -> DispatchReturn: + """ + Autograd logic. Generates a joint graph, partitions it, manipulates the input with various wrappers, + and returns a wrapped torch.autograd.Function with a forward and backward. + """ + + fx_g = aot_graph_capture.graph_module + maybe_subclass_meta = aot_graph_capture.maybe_subclass_meta + fw_metadata = aot_state.fw_metadata + aot_config = aot_state.aot_config + + CompileEventLogger.try_add_pt2_compile("backend_compile", dispatch_mode="autograd") + joint_graph_str = _log_joint_graph(fx_g, aot_config) + + _apply_tensorify_python_scalars(fx_g) + + ( + fw_module, + bw_module, + num_fw_outs_saved_for_bw, + num_symints_saved_for_bw, + _indices_of_inps_to_detach, + adjusted_flat_args, + ) = _aot_stage2a_partition( + fx_g, + aot_graph_capture.updated_flat_args, + maybe_subclass_meta, + fw_metadata, + aot_config, + partition_fn, + ) + + min_cut_info_str = getattr(fx_g.graph, "_min_cut_info_str", None) + + fw_module_str, bw_module_str = _log_fw_bw_graphs( + fw_module, bw_module, maybe_subclass_meta, fw_metadata, aot_config + ) + + fwd_output_strides, compiled_fw_func = _aot_stage2b_fw_compile( + fw_module, + adjusted_flat_args, + maybe_subclass_meta, + fw_metadata, + num_fw_outs_saved_for_bw, + aot_config, + fw_compiler, + ) + + lazy_backward_info, compiled_bw_func = _aot_stage2b_bw_compile( + bw_module, + maybe_subclass_meta, + fw_metadata, + fwd_output_strides, + num_symints_saved_for_bw, + aot_config, + bw_compiler, + ) + + try_save_cache_entry, entry = _cache_autograd_info( + aot_config, + aot_state.flat_args, + compiled_fw_func, + compiled_bw_func, + fw_module_str, + bw_module_str, + joint_graph_str, + aot_graph_capture.wrappers, + maybe_subclass_meta, + fw_metadata, + num_fw_outs_saved_for_bw, + _indices_of_inps_to_detach, + num_symints_saved_for_bw, + bw_module, + min_cut_info_str, + ) + + return _aot_stage2c_make_autograd_function( + aot_config, + aot_state.flat_args, + fw_metadata, + maybe_subclass_meta, + aot_graph_capture.wrappers, + compiled_fw_func, + compiled_bw_func, + bw_compiler, + lazy_backward_info, + try_save_cache_entry, # type: ignore[arg-type] + entry, # type: ignore[arg-type] + _indices_of_inps_to_detach, + num_symints_saved_for_bw, + ) + + +def _aot_stage2c_make_autograd_function( + aot_config: AOTConfig, + flat_args: list[Any], + fw_metadata: ViewAndMutationMeta, + maybe_subclass_meta: SubclassMeta | None, + wrappers: list[CompilerWrapper], + compiled_fw_func: Callable[..., Any], + compiled_bw_func: Callable[..., Any] | None, + # pyrefly: ignore [implicit-any] + bw_compiler: Callable, + lazy_backward_info: AutogradLazyBackwardCompileInfo | None, + try_save_cache_entry: Callable[..., Any], + entry: GenericAOTAutogradResult[Any, Any] | None, + _indices_of_inps_to_detach: list[int], + num_symints_saved_for_bw: int, +) -> DispatchReturn: + backward_state_indices = [ + idx for idx, x in enumerate(flat_args) if isinstance(x, BackwardState) + ] + if len(backward_state_indices) > 1: + raise AssertionError( + f"expected at most 1 backward_state_index, got {len(backward_state_indices)}" + ) + + disable_amp = torch._C._is_any_autocast_enabled() + compile_spec = AOTDispatchAutogradCompileSpec( + compiled_fw_func=compiled_fw_func, + compiled_bw_func=compiled_bw_func, + maybe_subclass_meta=maybe_subclass_meta, + num_symints_saved_for_bw=num_symints_saved_for_bw, + backward_state_indices=backward_state_indices, + disable_amp=disable_amp, + indices_of_inps_to_detach=_indices_of_inps_to_detach, + lazy_backward_info=lazy_backward_info, + bw_compiler=bw_compiler, + aot_config=aot_config, + fw_metadata=fw_metadata, + try_save_cache_entry=try_save_cache_entry, + ) + compiled_fn = AOTDispatchAutograd.post_compile(compile_spec) + + if entry is not None: + compiled_fn = SerializableCompiledFunction(compiled_fn, lambda: entry) + + if config.debug_assert: + flat_requires_grad: list[bool | None] = [ + a.requires_grad if isinstance(a, Tensor) else None for a in flat_args + ] + compiled_fn = DebugAssertWrapper( + flat_requires_grad=flat_requires_grad + ).post_compile(compiled_fn, aot_config, runtime_metadata=fw_metadata) + + compiled_fn = post_compile( + wrappers, + compiled_fn, + aot_config, + runtime_metadata=fw_metadata, + ) + return compiled_fn + + +def _cache_autograd_info( + aot_config: AOTConfig, + flat_args: list[Any], + compiled_fw_func: Callable[..., Any], + compiled_bw_func: Callable[..., Any] | None, + fw_module_str: str | None, + bw_module_str: str | None, + joint_graph_str: str | None, + wrappers: list[CompilerWrapper], + maybe_subclass_meta: SubclassMeta | None, + fw_metadata: ViewAndMutationMeta, + num_fw_outs_saved_for_bw: int, + _indices_of_inps_to_detach: list[int], + num_symints_saved_for_bw: int, + bw_module: torch.fx.GraphModule | None, + min_cut_info_str: str | None, +) -> tuple[ + GenericAOTAutogradResult[Any, Any] | None, + Callable[..., Any], +]: + backward_state_indices = [ + idx for idx, x in enumerate(flat_args) if isinstance(x, BackwardState) + ] + if len(backward_state_indices) > 1: + raise AssertionError( + f"expected at most 1 backward_state_index, got {len(backward_state_indices)}" + ) + + make_runtime_safe(fw_metadata, maybe_subclass_meta) + + try_save_cache_entry: Callable[..., Any] | None = None + entry: GenericAOTAutogradResult[Any, Any] | None = None + + if aot_config.cache_info is not None: + forward_time_taken_ns = time.time_ns() - aot_config.cache_info.start_time_ns + + # NB: aot_config here is technically not needed as an argument: we could just + # close over aot_config.cache_info, since aot_config never changes. + # But closing over random variables is confusing IMO, so I'm leaving it. + def try_save_cache_entry( + compiled_bw_func: Callable[..., Any], + bw_module: torch.fx.GraphModule, + _fw_metadata: ViewAndMutationMeta, + aot_config: AOTConfig, + ) -> GenericAOTAutogradResult[Any, Any] | None: + cache_info = aot_config.cache_info + + if cache_info is not None and _should_save_cache( + compiled_fw_func, compiled_bw_func + ): + if forward_time_taken_ns is None: + raise AssertionError("forward_time_taken_ns must not be None") + # TODO: technically, AOTAutograd does a *little* bit of post processing work + # in the backward that isn't measured here. But it's small enough that it's not worth + # the complexity of threading a bunch of times through the code, so we + # use the compiled_bw_func's inductor compile time instead. + # It's possible this changes in the future, in which case we should + # update backward_time_taken_ns to be more inclusive + backward_time_taken_ns = getattr(compiled_bw_func, "_time_taken_ns", 0) + + aot_forward_graph_str: str | None = fw_module_str + aot_backward_graph_str: str | None = bw_module_str + aot_joint_graph_str: str | None = joint_graph_str + guards_expr = AOTAutogradCache.generate_guards_expression(cache_info) + + entry = AOTAutogradCache.make_entry( + compiled_fw_func, # type: ignore[arg-type] + compiled_bw_func, # type: ignore[arg-type] + aot_joint_graph_str, + aot_forward_graph_str, + aot_backward_graph_str, + _fw_metadata, + wrappers, + maybe_subclass_meta, + num_fw_outs_saved_for_bw, + _indices_of_inps_to_detach, + forward_time_taken_ns, + backward_time_taken_ns, + sanitized_aot_config=aot_config.to_cacheable(), + guards_expr=guards_expr, + backward_state_indices=backward_state_indices, + num_symints_saved_for_bw=num_symints_saved_for_bw, + serialized_bw_module=serialize_graph_module(bw_module), + min_cut_info_str=min_cut_info_str, + ) + AOTAutogradCache.save( + cache_info.cache_key, + entry, + remote=should_use_remote_autograd_cache(), + ) + return entry + return None + + if compiled_bw_func is not None: + # If we already compiled the backward, we save its cache entry now + if bw_module is None: + raise AssertionError( + "bw_module must not be None when compiled_bw_func is not None" + ) + entry = try_save_cache_entry( + compiled_bw_func, + bw_module, + fw_metadata, + aot_config, # type: ignore[arg-type] + ) + try_save_cache_entry = None + + return try_save_cache_entry, entry # type: ignore[return-value] + + +def _aot_stage2b_compile_forward_or_inference( + fw_module: torch.fx.GraphModule, + adjusted_flat_args: list[Any], + maybe_subclass_meta: SubclassMeta | None, + fw_metadata: ViewAndMutationMeta, + aot_config: AOTConfig, + # pyrefly: ignore [implicit-any] + compiler: Callable, + *, + is_inference: bool, + num_fw_outs_saved_for_bw: int | None = None, + # pyrefly: ignore [implicit-any] +) -> tuple[list[tuple[int, ...] | None] | None, Callable]: + """ + Compile the forward or inference graph. Returns: + - the output strides of the forward graph + - the compiled forward/inference function + + Args: + fw_module: The forward graph module to compile + adjusted_flat_args: Flattened arguments after adjustments + maybe_subclass_meta: Metadata for tensor subclasses + fw_metadata: View and mutation metadata + aot_config: AOT configuration + is_inference: If True, compile for inference; if False, compile for forward (autograd) + num_fw_outs_saved_for_bw: Number of forward outputs saved for backward (required if not is_inference) + + Before compiling, we run pre_compile for the following wrappers: + - FakifiedOutWrapper + - FunctionalizedRngRuntimeWrapper + After compiling, we run post_compile for the following wrappers: + - EffectTokensWrapper + - AOTDispatchSubclassWrapper + - FunctionalizedRngRuntimeWrapper + - FakifiedOutWrapper + """ + + # Validation + if not is_inference and num_fw_outs_saved_for_bw is None: + raise ValueError( + "num_fw_outs_saved_for_bw must be provided when is_inference=False" + ) + + # Determine grad context, autocast context, and tracking mode. + if is_inference: + grad_ctx: Any = nullcontext + autocast_ctx: Any = ( + torch._C._DisableAutocast + if torch._C._is_any_autocast_enabled() + else nullcontext + ) + tracking_mode: str = "inference" + else: + grad_ctx = torch.no_grad + autocast_ctx = torch._C._DisableAutocast + tracking_mode = "forward" + + with grad_ctx(), autocast_ctx(), track_graph_compiling(aot_config, tracking_mode): + # Setup wrappers + fakified_out_wrapper = FakifiedOutWrapper() + fakified_out_wrapper.pre_compile( + fw_module, adjusted_flat_args, aot_config, fw_metadata=fw_metadata + ) + + # Initialize RNG wrapper based on mode + functionalized_rng_wrapper = FunctionalizedRngRuntimeWrapper( + return_new_outs=is_inference + ) + + # Add RNG states for forward mode only + if not is_inference and fw_metadata.num_graphsafe_rng_states > 0: + index = fw_metadata.graphsafe_rng_state_index + if index is None: + raise AssertionError( + "fw_metadata.graphsafe_rng_state_index must not be None when num_graphsafe_rng_states > 0" + ) + device = fw_metadata.graphsafe_rng_device + if device is None: + raise AssertionError( + "fw_metadata.graphsafe_rng_device must not be None when num_graphsafe_rng_states > 0" + ) + rng_states = [ + get_default_generator(device).clone_state() + for _ in range(fw_metadata.num_graphsafe_rng_states) + ] + adjusted_flat_args.extend(rng_states) # type: ignore[arg-type] + + functionalized_rng_wrapper.pre_compile( + fw_module, adjusted_flat_args, aot_config, fw_metadata=fw_metadata + ) + + # Set tracing context + if tracing_context := torch._guards.TracingContext.try_get(): + tracing_context.fw_metadata = _get_inner_meta( + maybe_subclass_meta, fw_metadata + ) + + if config.enable_complex_wrapper: + from .complex_decomposition import decompose_complex_in_graph + + fw_module = decompose_complex_in_graph( + fw_module, adjusted_flat_args, aot_config.decompositions + ) + + with TracingContext.report_output_strides() as fwd_output_strides: + # pyrefly: ignore[not-callable] + compiled_fw_func = compiler(fw_module, adjusted_flat_args) + + # Make boxed if needed + if not getattr(compiled_fw_func, "_boxed_call", False): + compiled_fw_func = make_boxed_func(compiled_fw_func) + + # Set forward output strides if needed + if fakified_out_wrapper.needs_post_compile: + fakified_out_wrapper.set_fwd_output_strides(fwd_output_strides) # type: ignore[arg-type] + + # Apply post-compile wrappers + compiled_fw_func = EffectTokensWrapper().post_compile( + compiled_fw_func, + aot_config, + runtime_metadata=fw_metadata, + ) + + compiled_fw_func = AOTDispatchSubclassWrapper( + fw_only=None, + trace_joint=False, + maybe_subclass_meta=maybe_subclass_meta, + num_fw_outs_saved_for_bw=num_fw_outs_saved_for_bw, + ).post_compile( + compiled_fw_func, + aot_config, + runtime_metadata=fw_metadata, + ) + + compiled_fw_func = functionalized_rng_wrapper.post_compile( + compiled_fw_func, aot_config, runtime_metadata=fw_metadata + ) + + compiled_fw_func = fakified_out_wrapper.post_compile( + compiled_fw_func, + aot_config, + runtime_metadata=fw_metadata, + ) + + return fwd_output_strides, compiled_fw_func diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/indexed_dict.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/indexed_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..748818ff4b16ccf6651a9bdfe7b8064e67ff922e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/indexed_dict.py @@ -0,0 +1,54 @@ +from collections.abc import Iterator, MutableMapping +from typing import Generic, TypeVar + + +K = TypeVar("K") +V = TypeVar("V") + + +# Used for fast next key access (using the fact that the dict is ordered) +# Note: doesn't support deletion but we don't need it! +class IndexedDict(MutableMapping[K, V], Generic[K, V]): + """A dict that maintains insertion order with O(1) index access.""" + + __slots__ = ("_dict", "_keys", "_key_to_index") + + def __init__(self) -> None: + self._dict: dict[K, V] = {} + self._keys: list[K] = [] # typing: ignore[bad-override] + self._key_to_index: dict[K, int] = {} + + def __setitem__(self, key: K, value: V) -> None: + if key not in self._dict: + self._key_to_index[key] = len(self._keys) + self._keys.append(key) + self._dict[key] = value + + def __getitem__(self, key: K) -> V: + return self._dict[key] + + def __delitem__(self, key: K) -> None: + raise NotImplementedError("Deletion not supported for IndexedDict") + + def __len__(self) -> int: + return len(self._dict) + + def __iter__(self) -> Iterator[K]: + return iter(self._keys) + + def __contains__(self, key: object) -> bool: + return key in self._dict + + def next_key(self, key: K) -> K | None: + """Get the next key in insertion order. O(1).""" + idx = self._key_to_index.get(key) + if idx is not None and idx + 1 < len(self._keys): + return self._keys[idx + 1] + return None + + def prev_key(self, key: K) -> K | None: + """Get the previous key in insertion order. O(1).""" + idx = self._key_to_index.get(key) + if idx is not None and idx > 0: + return self._keys[idx - 1] + return None diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/input_output_analysis.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/input_output_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..9fb2c49d1fc9871741c524316d04a1e6a76f4aeb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/input_output_analysis.py @@ -0,0 +1,508 @@ +""" +This module is one of the analysis modules - it takes as input a function or graph +and some preexisting properties, and returns some data that is useful for deciding +how to further proceed with compilation or construct runtime wrappers. + +In particular, the following analyses are provided: +1. Refine the view and mutation metadata collected previously - removing duplicate + inputs or mapping views to their bases. +2. We also analyze the function signature for export graphs. +""" + +import contextlib +import itertools +from typing import Any + +import torch +import torch.utils._pytree as pytree +from torch import Tensor +from torch._C._dynamo.guards import compute_overlapping_tensors +from torch._functorch._aot_autograd.schemas import PlainTensorMeta +from torch._guards import StorageOverlap +from torch._subclasses.functional_tensor import FunctionalTensor +from torch.fx.experimental.symbolic_shapes import is_concrete_int + +from .collect_metadata_analysis import coerce_tangent_and_suggest_memory_format +from .descriptors import AOTInput, InputMutationAOTOutput, TangentAOTInput +from .schemas import ( + AOTConfig, + BackwardSignature, + GraphSignature, + InputAliasInfo, + MemoryFormatMeta, + OutputAliasInfo, + OutputType, + ViewAndMutationMeta, +) +from .utils import strict_zip + + +zip = strict_zip + + +def remove_dupe_metadata( + m: ViewAndMutationMeta, + keep_arg_mask: list[bool], + add_dupe_map: list[int], +) -> ViewAndMutationMeta: + if len(m.input_info) != len(keep_arg_mask): + raise AssertionError( + f"len(m.input_info)={len(m.input_info)} != len(keep_arg_mask)={len(keep_arg_mask)}" + ) + # Easy invariant: the first argument should never be a dupe (it will be kept) + if len(keep_arg_mask) == 0 or not keep_arg_mask[0]: + raise AssertionError( + "keep_arg_mask must be non-empty and keep_arg_mask[0] must be True" + ) + + # Filter dupe'd mutated inputs out of traced_tangents + num_data_mutations = len([x for x in m.input_info if x.mutates_data]) + other_traced_tangents = m.traced_tangents[num_data_mutations:] + inp_traced_tangents = m.traced_tangents[:num_data_mutations] + other_traced_tangents_descs = m.traced_tangents_descs[num_data_mutations:] + inp_traced_tangents_descs = m.traced_tangents_descs[:num_data_mutations] + filtered_inp_traced_tangents = [ + # See Note [Tangents memory format] + x + for i, x in enumerate(inp_traced_tangents) + if keep_arg_mask[m.mutated_inp_runtime_indices[i]] + ] + filtered_inp_traced_tangents_descs = [ + x_desc + for i, x_desc in enumerate(inp_traced_tangents_descs) + if keep_arg_mask[m.mutated_inp_runtime_indices[i]] + ] + traced_tangents = filtered_inp_traced_tangents + other_traced_tangents + traced_tangents_descs = ( + filtered_inp_traced_tangents_descs + other_traced_tangents_descs + ) + + if m.subclass_tangent_meta is None: + raise AssertionError("m.subclass_tangent_meta must not be None") + subclass_tangent_meta = [ + PlainTensorMeta( + 0, memory_format=MemoryFormatMeta(memory_format=torch.contiguous_format) + ) + ] * len(filtered_inp_traced_tangents) + m.subclass_tangent_meta[num_data_mutations:] + + return ViewAndMutationMeta( + input_info=[x for i, x in enumerate(m.input_info) if keep_arg_mask[i]], + # For outputs that are views of inputs, we store the index of the input that the output + # was generated from. Need to update that index to account for removed dupes. + output_info=[ + OutputAliasInfo( + output_type=o.output_type, + raw_type=o.raw_type, + dynamic_dims=o.dynamic_dims, + base_idx=None if o.base_idx is None else add_dupe_map[o.base_idx], + requires_grad=o.requires_grad, + requires_grad_for_backward=o.requires_grad_for_backward, + view_meta_sequence=o.view_meta_sequence, + ) + for o in m.output_info + ], + num_intermediate_bases=m.num_intermediate_bases, + keep_input_mutations=m.keep_input_mutations, + traced_tangents=traced_tangents, + traced_tangents_descs=traced_tangents_descs, + # We are guaranteed not to get here, since dupes are not supported today with subclass inputs. + subclass_inp_meta=[], + subclass_fw_graph_out_meta=[], + subclass_tangent_meta=subclass_tangent_meta, + ) + + +# Given our ViewAndMutation metadata, this fn constructs a new set of metadata, +# after adding synthetic base arguments to the function. +# Most of the work in this fn is slogging through all of the metadata corresponding to inputs, +# and updating it with our synthetic base calling convention. +# +# When config.debug_assert is set, we automatically regenerate the metadata +# and compare it to this output for sanity. +# +# In addition to the updated metadata, also return the list of input indices +# that will need to be updated in the synthetic base epilogue +def create_synthetic_base_metadata( + m: ViewAndMutationMeta, + # Maps each outer argument idx to its inner idx (or, if this outer arg is generated from a + # synthetic base, you get a tuple of (i, TensorMeta), telling you the base tensor idx, and view metadata) + synthetic_base_info: list[int | tuple[int, torch.Tensor]], + outer_args: list[Any], + inner_args: list[Any], + inner_args_desc: list[AOTInput], +) -> tuple[ViewAndMutationMeta, list[int]]: + # maps inner arg indices to outer arg indices + synthetic_base_to_indices: dict[int, list[int]] = {} + for inner_idx in range(len(inner_args)): + outer_aliased_indices_of_current_base_arg = [ + outer_idx + for outer_idx, inner_idx_or_tuple in enumerate(synthetic_base_info) + if (isinstance(inner_idx_or_tuple, int) and inner_idx_or_tuple == inner_idx) + or ( + isinstance(inner_idx_or_tuple, tuple) + and inner_idx_or_tuple[0] == inner_idx + ) + ] + synthetic_base_to_indices[inner_idx] = outer_aliased_indices_of_current_base_arg + + # given the requires_grad info on mutated inputs, + # generate the requires_grad info on those same mutated inputs, but after constructing synthetic bases. + # pyrefly: ignore [implicit-any] + input_infos = [] + for outer_indices in synthetic_base_to_indices.values(): + # leaf-ness should be all-or-nothing for aliased tensor. + # (aka if "a" and "b" are views, then a.is_leaf == b.is_leaf) + any_leaf = any(m.input_info[x].is_leaf for x in outer_indices) + all_leaf = all(m.input_info[x].is_leaf for x in outer_indices) + if any_leaf != all_leaf: + raise AssertionError( + f"any_leaf={any_leaf} != all_leaf={all_leaf} for outer_indices={outer_indices}" + ) + + mutates_data = ( + True + if len(outer_indices) > 1 + else m.input_info[outer_indices[0]].mutates_data + ) + mutates_metadata = ( + False + if len(outer_indices) > 1 + else m.input_info[outer_indices[0]].mutates_metadata + ) + requires_grad = any(m.input_info[x].requires_grad for x in outer_indices) + mutations_under_no_grad_or_inference_mode = all( + m.input_info[x].mutations_under_no_grad_or_inference_mode + for x in outer_indices + ) + + mutation_inductor_storage_resize = all( + m.input_info[x].mutation_inductor_storage_resize for x in outer_indices + ) + + inpt_info = InputAliasInfo( + # If len(outer_indices) > 1, then this input is a synthetic base. + # The invariant is that to the rest of aot autograd, synthetic bases only show up if + # one of their aliases gets a data mutation. And if any of their aliases get metadata + # mutations, they will be hidden from the rest of aot autograd. + mutates_data=mutates_data, + mutates_metadata=mutates_metadata, + mutations_hidden_from_autograd=all( + m.input_info[x].mutations_hidden_from_autograd for x in outer_indices + ), + mutates_storage_metadata=( + False + if len(outer_indices) > 1 + else m.input_info[outer_indices[0]].mutates_storage_metadata + ), + mutation_is_shallow_copy_data=( + False + if len(outer_indices) > 1 + else m.input_info[outer_indices[0]].mutation_is_shallow_copy_data + ), + mutations_under_no_grad_or_inference_mode=mutations_under_no_grad_or_inference_mode, + mutation_inductor_storage_resize=mutation_inductor_storage_resize, + is_leaf=any_leaf, + requires_grad=requires_grad, + keep_input_mutations=m.keep_input_mutations, + ) + input_infos.append(inpt_info) + + # Find any inputs that fulfill the following criteria: + # (1) They are part of a synthetic base (because they alias another input, + # and at least one input experiences a data mutation) + # (2) They experience a metadata mutation + outer_aliased_arg_idx_with_metadata_mutations = [ + outer_idx + for outer_idx, inpt_info in enumerate(m.input_info) + if inpt_info.mutates_metadata + and not isinstance(synthetic_base_info[outer_idx], int) + ] + + # grab the original requires grad info on the outputs, except the ones from the mutated inputs + input_metadata_output_info = [ + OutputAliasInfo( + output_type=OutputType.alias_of_input, + raw_type=FunctionalTensor, + dynamic_dims={ + i + for i, s in enumerate(outer_args[outer_idx].shape) + if not is_concrete_int(s) + }, + base_idx=synthetic_base_info[outer_idx][0], # type: ignore[index] + requires_grad=(requires_grad := outer_args[outer_idx].requires_grad), + requires_grad_for_backward=requires_grad, + ) + for outer_idx in outer_aliased_arg_idx_with_metadata_mutations + ] + existing_output_infos = [] + for o in m.output_info: + synthetic_base_info_for_output = ( + None if o.base_idx is None else synthetic_base_info[o.base_idx] + ) + new_base_idx = ( + None + if o.base_idx is None + else ( + synthetic_base_info_for_output + if isinstance(synthetic_base_info_for_output, int) + else synthetic_base_info_for_output[0] # type: ignore[index] + ) + ) + # If the original input was merged into a synthetic base, then an + # output that was literally that input is now a view of the base. + input_merged = o.base_idx is not None and isinstance( + synthetic_base_info[o.base_idx], tuple + ) + new_output_type = ( + OutputType.alias_of_input + if o.output_type == OutputType.is_input and input_merged + else o.output_type + ) + existing_output_infos.append( + OutputAliasInfo( + output_type=new_output_type, + raw_type=o.raw_type, + dynamic_dims=o.dynamic_dims, + # Map the input idx pre-synthetic-bases to the new idx post-synthetic-bases + base_idx=new_base_idx, # type: ignore[arg-type] + requires_grad=o.requires_grad, + requires_grad_for_backward=o.requires_grad_for_backward, + view_meta_sequence=o.view_meta_sequence, + ) + ) + + inner_mutated_tangents_and_memory_formats = [ + # See Note [Tangents memory format] + ( + coerce_tangent_and_suggest_memory_format(x), + TangentAOTInput(InputMutationAOTOutput(x_desc)), + ) + for inner_idx, (x, x_desc) in enumerate(zip(inner_args, inner_args_desc)) + if input_infos[inner_idx].mutates_data and input_infos[inner_idx].requires_grad + ] + inner_mutated_tangents = [ + x[0][0] for x in inner_mutated_tangents_and_memory_formats + ] + inner_mutated_tangents_descs = [ + x[1] for x in inner_mutated_tangents_and_memory_formats + ] + inner_mutated_tangents_memory_formats = [ + x[0][1] for x in inner_mutated_tangents_and_memory_formats + ] + + output_info = existing_output_infos + input_metadata_output_info + # Regenerate traced tangents to include mutated inputs including synthetic bases + traced_tangents = ( + inner_mutated_tangents + m.traced_tangents[len(inner_mutated_tangents) :] + ) + traced_tangents_descs = ( + inner_mutated_tangents_descs + + m.traced_tangents_descs[len(inner_mutated_tangents) :] + ) + if m.subclass_tangent_meta is None: + raise AssertionError("m.subclass_tangent_meta must not be None") + subclass_tangent_meta = [ + # pyrefly: ignore[bad-argument-type] + PlainTensorMeta(0, memory_format=x) + for x in inner_mutated_tangents_memory_formats + ] + m.subclass_tangent_meta[len(inner_mutated_tangents) :] + + return ( + ViewAndMutationMeta( + input_info=input_infos, + output_info=output_info, + num_intermediate_bases=m.num_intermediate_bases, + keep_input_mutations=m.keep_input_mutations, + traced_tangents=traced_tangents, + traced_tangents_descs=traced_tangents_descs, + # We are guaranteed not to get here, since synthetic_base codepaths are not supported today with subclass inputs. + subclass_inp_meta=[], + subclass_fw_graph_out_meta=[], + subclass_tangent_meta=subclass_tangent_meta, + ), + outer_aliased_arg_idx_with_metadata_mutations, + ) + + +def compute_overlapping_inputs( + aot_config: AOTConfig, fwd_inputs: list[Any], aliased_input_indices: list[int] +) -> set[int]: + num_aliases = len(aliased_input_indices) + + shape_env = None + maybe_suppress_guards = contextlib.nullcontext + tracing_context = torch._guards.TracingContext.try_get() + + if tracing_context is not None: + if tracing_context.fake_mode is None: + raise AssertionError("tracing_context.fake_mode must not be None") + shape_env = tracing_context.fake_mode.shape_env + + # Check whether we can actually get the dynamo sources from within AOTAutograd. + if aot_config.aot_autograd_arg_pos_to_source and shape_env is not None: + maybe_suppress_guards = shape_env.suppress_guards # type: ignore[assignment] + + # Check whether there are any symbolic values being used. + # We do this for 2 reasons: + # 1. StorageOverlap guard is only issued whenever dynamic shapes is turned on + # 2. Triggers the fast-path for computing storage overlapping + symbolic = any( + isinstance(x, torch.SymInt) + for i in aliased_input_indices + for x in [ + *fwd_inputs[i].shape, + *fwd_inputs[i].stride(), + fwd_inputs[i].storage_offset(), + ] + ) + + if torch._inductor.config.is_fbcode(): + if symbolic and num_aliases > 400: + from torch._subclasses.fake_tensor import ( + UnsupportedMutationAliasingException, + ) + from torch._utils_internal import justknobs_check + + msg = f"Encountered {num_aliases} dynamic, aliased/mutated inputs, consider setting dynamic=False" + + if justknobs_check( + "pytorch/compiler:aliased_inputs_with_mutation_and_dyn_shapes_killswitch", + False, + ): + raise UnsupportedMutationAliasingException(msg) + + with maybe_suppress_guards(): + aliased_fwd_inputs = [fwd_inputs[i] for i in aliased_input_indices] + actual_aliased_indices = { + aliased_input_indices[i] + for i in compute_overlapping_tensors(aliased_fwd_inputs, symbolic=symbolic) + } + + # Add the StorageOverlap AOTAutograd guard only if we are actually keeping track of + # dynamo sources inside AOTAutograd. + if ( + tracing_context is not None + # Make sure dynamic shapes is currently being used. + and symbolic + # We check that we have more than 1 aliased tensor, which should be true at + # this point, anyway. + and num_aliases > 1 + and aot_config.aot_autograd_arg_pos_to_source + ): + no_overlap_indices = list(set(aliased_input_indices) - actual_aliased_indices) + + overlapping_sources = [ + aot_config.aot_autograd_arg_pos_to_source[i] for i in actual_aliased_indices + ] + non_overlapping_sources = [ + aot_config.aot_autograd_arg_pos_to_source[i] for i in no_overlap_indices + ] + + tracing_context.guards_context.aotautograd_guards.append( + StorageOverlap(overlapping_sources, non_overlapping_sources) + ) + + return actual_aliased_indices + + +def _graph_input_names(gm: torch.fx.GraphModule) -> list[str]: + return [node.name for node in gm.graph.find_nodes(op="placeholder")] + + +def _graph_output_names(gm: torch.fx.GraphModule) -> list[Any]: + output_node = next(iter(reversed(gm.graph.nodes))) + if output_node.op != "output" or len(output_node.args) != 1: + raise AssertionError( + f"expected output node with 1 arg, got op={output_node.op}, args={len(output_node.args)}" + ) + return_args = output_node.args[0] + return [getattr(return_arg, "name", None) for return_arg in return_args] + + +def create_graph_signature( + fx_g: torch.fx.GraphModule, + fw_metadata: ViewAndMutationMeta, + in_spec: pytree.TreeSpec, + out_spec: pytree.TreeSpec, + *, + user_args_flat: list[Tensor], + params_and_buffers_flat: list[Tensor], + param_names: list[str], + buffer_names: list[str], + trace_joint: bool, + num_user_fw_outs: int | None, + loss_index: int | None, +) -> GraphSignature: + # Retrieve graph input names + graph_input_names = _graph_input_names(fx_g) + # Retrieve graph output names + graph_output_names = _graph_output_names(fx_g) + + num_params_buffers = len(param_names) + len(buffer_names) + num_tokens = len(fw_metadata.tokens) + # We have enough restrictions on the graph (no de-duping, synthetic bases, etc), + # Such that # graph inps = # user inps + # params + # buffers + num_user_args = len(graph_input_names) - num_params_buffers - num_tokens + + if trace_joint: + if num_user_fw_outs is None: + raise AssertionError( + "num_user_fw_outs must not be None when trace_joint=True" + ) + num_fw_outs = num_user_fw_outs + fw_metadata.num_mutated_inp_runtime_indices + backward_output_names = graph_output_names[num_fw_outs:] + + grad_index = itertools.count(0) + gradients_to_parameters = { + backward_output_names[next(grad_index)]: param_names[i] + for i, param in enumerate(params_and_buffers_flat) + if param.requires_grad + } + + gradients_to_user_inputs = { + backward_output_names[next(grad_index)]: graph_input_names[ + i + len(params_and_buffers_flat) + ] + for i, user_input in enumerate(user_args_flat) + if user_input.requires_grad + } + + if len(gradients_to_parameters) + len(gradients_to_user_inputs) != len( + backward_output_names + ): + raise AssertionError( + f"len(gradients_to_parameters)={len(gradients_to_parameters)} + " + f"len(gradients_to_user_inputs)={len(gradients_to_user_inputs)} != " + f"len(backward_output_names)={len(backward_output_names)}" + ) + + # Check that we have fully accounted for all graph outputs + if loss_index is None: + raise AssertionError("loss_index must not be None") + backward_signature = BackwardSignature( + gradients_to_parameters, + gradients_to_user_inputs, + graph_output_names[loss_index], + ) + else: + backward_signature = None + num_user_fw_outs = ( + len(graph_output_names) + - fw_metadata.num_mutated_inp_runtime_indices + - num_tokens + ) + + return GraphSignature.from_tracing_metadata( + in_spec=in_spec, + out_spec=out_spec, + graph_input_names=graph_input_names, + graph_output_names=graph_output_names, + view_mutation_metadata=fw_metadata, + named_parameters=param_names, + named_buffers=buffer_names, + num_user_inputs=num_user_args, + num_user_outputs=num_user_fw_outs, + trace_joint=trace_joint, + loss_index=loss_index, + backward_signature=backward_signature, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/logging_utils.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/logging_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a5dda6c67dfa7804170374e7c737b3bc3ec5eb2e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/logging_utils.py @@ -0,0 +1,166 @@ +""" +Contains utils for logging in AOTAutograd, including managing the names of the graphs under +compilation, capturing user-friendly tracebacks, and debug messages. +""" + +import collections +from collections.abc import Callable, Generator, Iterator +from contextlib import contextmanager +from typing import Any + +import torch +import torch.fx.traceback as fx_traceback + +from .schemas import AOTConfig + + +# This is a list since looking forward, we can have this arbitrarily nested. +graph_being_compiled: list[str] = [] +# TODO: It would be nice to reset the numbering every time aot_id goes +# up, but this is annoying to do right now (because we don't know if +# an aot_id will come back from the dead), so right now this also happens +# to be a globally unique number too (at the cost of wobbling if you change +# how the graphs compile) +nth_graph: int = 0 +model_name: str = "model" + + +def set_model_name(name: str) -> None: + global model_name + model_name = name + + +def get_aot_compilation_context() -> tuple[list[str], str, int]: + return list(graph_being_compiled), model_name, nth_graph + + +def get_aot_graph_name() -> str: + """ + Returns the name of the graph being compiled. + """ + global model_name, graph_being_compiled, nth_graph + return f"{model_name}__{'_'.join(graph_being_compiled)}_{nth_graph}" + + +get_graph_being_compiled = get_aot_graph_name + + +@contextmanager +def track_graph_compiling( + aot_config: AOTConfig, graph_name: str +) -> Generator[None, None, None]: + global graph_being_compiled + # TODO: Don't shove the aot_id in here; set it in the context + graph_being_compiled = [f"{aot_config.aot_id}_{graph_name}"] + old_name = None + if tracing_context := torch._guards.TracingContext.try_get(): + old_name = tracing_context.aot_graph_name + tracing_context.aot_graph_name = graph_being_compiled + has_tracing_context = True + else: + has_tracing_context = False + try: + yield + finally: + global nth_graph + nth_graph += 1 + graph_being_compiled = [] + if has_tracing_context: + if tracing_context := torch._guards.TracingContext.try_get(): + tracing_context.aot_graph_name = old_name + + +# Set up hooks so that during backward the fx's stack_trace is properly set +callback_set = False + + +def setup_stacktrace_preservation_hooks(roots: list[torch.autograd.graph.Node]) -> None: + def iter_graph( + roots: list[torch.autograd.graph.Node], + ) -> Iterator[torch.autograd.graph.Node]: + if not roots: + return + seen = set() + q = collections.deque() + for node in roots: + if node is not None and node not in seen: + seen.add(node) + q.append(node) + + while q: + node = q.popleft() + for fn, _idx in node.next_functions: + if fn in seen or fn is None: + continue + seen.add(fn) + q.append(fn) + + yield node + + def get_callback(saved_stack_: list[str]) -> Callable[[], None]: + def callback() -> None: + global callback_set + fx_traceback.set_stack_trace(saved_stack_) + callback_set = False + + return callback + + def get_prehook(stack_: list[str], seq_nr: int) -> Callable[[Any], None]: + def prehook(grad_output: Any) -> None: + global callback_set + + if not callback_set: + torch.autograd.variable.Variable._execution_engine.queue_callback( # type: ignore[attr-defined] + get_callback(fx_traceback.format_stack()) + ) + callback_set = True + + fx_traceback.set_stack_trace(stack_) + fx_traceback.set_grad_fn_seq_nr(seq_nr) + fx_traceback._mark_autograd_backward() + + return prehook + + def get_posthook( + special_stack_: list[str], seq_nr: int + ) -> Callable[[Any, Any], None]: + def posthook(grad_input: Any, grad_output: Any) -> None: + fx_traceback.set_stack_trace(special_stack_) + fx_traceback.reset_grad_fn_seq_nr() + fx_traceback._reset_autograd_backward() + + return posthook + + for node in iter_graph(roots): + # pyrefly: ignore[missing-attribute] + forward_node_stack = node.metadata.get("traceback_", []) + node.register_prehook(get_prehook(forward_node_stack, node._sequence_nr())) + + special_stack = forward_node_stack.copy() + special_stack.append(fx_traceback.GRADIENT_ACC_SPECIAL_STACK) + node.register_hook(get_posthook(special_stack, node._sequence_nr())) + + +def setup_stacktrace_preservation_hooks_from_tensors(outputs: Any) -> None: + roots = [ + t.grad_fn + for t in (outputs if isinstance(outputs, (list, tuple)) else (outputs,)) + if isinstance(t, torch.Tensor) and t.grad_fn is not None + ] + if roots: + setup_stacktrace_preservation_hooks(roots) + + +def describe_input(i: int, aot_config: AOTConfig) -> str: + if i < aot_config.num_params_buffers: + return f"parameter/buffer {i}" + else: + return f"input {i - aot_config.num_params_buffers}" + + +def format_guard_bug_msg(aot_config: AOTConfig, expected: str) -> str: + return ( + f"At compilation time, graph {aot_config.aot_id} was compiled under the " + f"assumption that {expected}, but at runtime this was not the case. " + "This indicates a guard bug in AOTAutograd or Dynamo, please file a bug to PyTorch." + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..2fcc5a964c3f1dbadd302c0429101abe5e76246d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py @@ -0,0 +1,3915 @@ +""" +This module defines runtime wrappers, which, based on previous analysis attempts to: +1. process the inputs and outputs +2. apply mutations +3. handle functionalized randomness +4. deduplicate inputs and consolidate views into their bases (see input_output_analysis) +""" + +import collections +import contextlib +import copy +import functools +import itertools +import pprint +import typing +import warnings +import weakref +from collections.abc import Callable, Generator, Sequence +from contextlib import AbstractContextManager, nullcontext +from dataclasses import dataclass, field +from functools import wraps +from typing import Any + +import torch +import torch.fx as fx +from torch import Tensor +from torch._custom_class_base import CustomClassBase +from torch._dynamo import config as dynamo_config +from torch._dynamo.callback import callback_handler, CallbackTrigger +from torch._dynamo.graph_bytecode_inputs import index_to_external_object_weakref +from torch._dynamo.utils import CompileEventLogger, dynamo_timed, get_metrics_context +from torch._guards import ( + compile_context, + CompileContext, + detect_fake_mode, + DuplicateInputs, + tracing, + TracingContext, +) +from torch._library.opaque_object import is_custom_class +from torch._library.utils import is_builtin +from torch._logging import getArtifactLogger +from torch._ops import OpOverload +from torch._prims_common import CUDARngStateHelper +from torch._subclasses.fake_tensor import is_fake_tensor +from torch.fx.experimental._backward_state import BackwardState +from torch.fx.experimental.proxy_tensor import HANDLED_TYPES +from torch.multiprocessing.reductions import StorageWeakRef +from torch.utils._python_dispatch import ( + is_traceable_wrapper_subclass, + TorchDispatchMode, +) +from torch.utils._pytree import tree_flatten + +from .. import config +from .collect_metadata_analysis import run_functionalized_fw_and_collect_metadata +from .descriptors import ( + AOTInput, + AOTOutput, + DummyAOTInput, + MetadataMutationAOTOutput, + SyntheticBaseAOTInput, + ViewBaseAOTInput, +) +from .functional_utils import gen_alias_from_base +from .graph_capture_wrappers import aot_dispatch_subclass +from .input_output_analysis import ( + compute_overlapping_inputs, + create_synthetic_base_metadata, + remove_dupe_metadata, +) +from .logging_utils import describe_input, format_guard_bug_msg, track_graph_compiling +from .schemas import ( + AOTConfig, + CompilerWrapper, + FxValue, + InductorWrapper, + InputAliasInfo, + MemoryFormatMeta, + MutationType, + OpaqueMeta, + OutputAliasInfo, + OutputType, + PlainTensorMeta, + SubclassCreationMeta, + SubclassMeta, + TensorAlias, + TraceFn, + ViewAndMutationMeta, +) +from .subclass_utils import ( + requires_subclass_dispatch, + runtime_unwrap_tensor_subclasses, + wrap_tensor_subclasses, +) +from .utils import ( + call_and_expect_output_descs, + call_func_at_runtime_with_args, + make_boxed_func, + partial_flatten_asdict, + simple_wraps, + strict_zip, + without_output_descs, +) + + +if typing.TYPE_CHECKING: + from .codegen import PySourceBuilder + + +def _snapshot_external_objects(ctx: Any) -> None: + """Snapshot the external object registry onto ctx for backward restore.""" + ctx._external_objects = { + k: ref() + for k, ref in index_to_external_object_weakref.items() + if ref() is not None + } + + +def _unwrap_tensor_subclasses_no_symints( + args: list[Any], +) -> list[Any]: + return runtime_unwrap_tensor_subclasses(args, append_symints=False) # type: ignore[arg-type] + + +zip = strict_zip + +aot_graphs_log = getArtifactLogger(__name__, "aot_graphs") + + +def _unwrap_no_symints(args: list[Any]) -> list[Any]: + return runtime_unwrap_tensor_subclasses(args, append_symints=False) + + +def _describe_arg_for_logging(arg: object) -> str: + from torch._library import opaque_object + + try: + is_dtensor = isinstance(arg, torch.distributed.tensor.DTensor) + except AttributeError: + is_dtensor = False + + if is_dtensor: + arg = typing.cast(torch.distributed.tensor.DTensor, arg) + mesh = arg.device_mesh + return ( + f"DTensor(shape={arg.shape}, dtype={arg.dtype}, " + f"device={arg.device}, mesh_shape={mesh.shape}, " + f"placements={arg.placements})" + ) + elif isinstance(arg, torch.Tensor): + return f"Tensor(shape={arg.shape}, dtype={arg.dtype}, device={arg.device})" + elif opaque_object.is_custom_class(type(arg)): + return f"Opaque: {type(arg).__name__}" + else: + return f"{type(arg).__name__}: {arg}" + + +def _log_input_metadata(runtime_metadata: ViewAndMutationMeta) -> None: + aot_graphs_log.debug( + "Expected input metadata (count=%s):", len(runtime_metadata.subclass_inp_meta) + ) + for i, meta in enumerate(runtime_metadata.subclass_inp_meta): + aot_graphs_log.debug(" [%s] %s", i, meta) + + +def _log_args_list(args: Sequence[object], label: str) -> None: + aot_graphs_log.debug("%s (count=%s):", label, len(args)) + for i, arg in enumerate(args): + aot_graphs_log.debug(" [%s] %s", i, _describe_arg_for_logging(arg)) + + +def _log_args_maybe_list(arg: object, label: str) -> None: + if isinstance(arg, (list, tuple)): + _log_args_list(arg, label) + else: + aot_graphs_log.debug("%s: %s", label, _describe_arg_for_logging(arg)) + + +# The wrapper created by this function handles all of the runtime aliasing and mutation "epilogue" logic +# that needs to run after the compiled function. +# +# This function accepts a trace_joint flag, indicating whether or not we're generating the runtime +# epilogue for a forward-only inference graph, or for an autograd.Function.apply function. +# This is because there are some minor differences in how we treat these cases at runtime: +# - resize_() is currently handled in the inference case, but not fully handled in the autograd case. +# - the autograd cases inserts TensorAlias wrapper objects for outputs that alias inputs +@dataclass +class RuntimeWrapper(CompilerWrapper): + indices_of_inps_to_detach: list[int] + trace_joint: bool + disable_amp: bool + + def post_compile( + self, + compiled_fn: Callable[..., Any], + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ) -> Callable[..., Any]: + return _create_runtime_wrapper( + compiled_fn, + runtime_metadata=runtime_metadata, + indices_of_inps_to_detach=self.indices_of_inps_to_detach, + trace_joint=self.trace_joint, + keep_input_mutations=aot_config.keep_inference_input_mutations, + disable_amp=self.disable_amp, + ) + + +class NoopAliasHandler: + def __init__( + self, + info: OutputAliasInfo, + runtime_metadata: ViewAndMutationMeta, + trace_joint: bool, + ) -> None: + pass + + def __call__( + self, orig_inputs: dict[int, Tensor], fw_outs: list[Any], out: Any + ) -> Any: + return out + + +def _unwrap_tensoralias(x: TensorAlias) -> torch.Tensor: + if not isinstance(x, TensorAlias): + raise AssertionError(f"expected TensorAlias, got {type(x)}") + return x.alias + + +def _identity(x: Any) -> Any: + return x + + +class AliasOfInputHandler: + def __init__( + self, + info: OutputAliasInfo, + runtime_metadata: ViewAndMutationMeta, + trace_joint: bool, + ) -> None: + if info.base_idx is None: + raise AssertionError("expected info.base_idx to be set") + self.base_idx = info.base_idx + self.unwrap_out = _unwrap_tensoralias if trace_joint else _identity + self.requires_grad = info.requires_grad + self.view_meta_sequence = info.view_meta_sequence + self.replay_views = config.view_replay_for_aliased_outputs + + def __call__( + self, orig_inputs: dict[int, Tensor], fw_outs: list[Any], out: Any + ) -> torch.Tensor: + aliased_base_tensor = orig_inputs[self.base_idx] + return gen_alias_from_base( + aliased_base_tensor, + self.unwrap_out(out), + self.requires_grad, + self.view_meta_sequence, + replay_views=self.replay_views, + ) + + +class IsInputHandler: + def __init__( + self, + info: OutputAliasInfo, + runtime_metadata: ViewAndMutationMeta, + trace_joint: bool, + ) -> None: + if info.base_idx is None: + raise AssertionError("expected info.base_idx to be set") + self.base_idx = info.base_idx + + def __call__( + self, orig_inputs: dict[int, Tensor], fw_outs: list[Any], out: Any + ) -> torch.Tensor: + aliased_base_tensor = orig_inputs[self.base_idx] + return aliased_base_tensor + + +class AliasOfIntermediateHandler: + def __init__( + self, + info: OutputAliasInfo, + runtime_metadata: ViewAndMutationMeta, + trace_joint: bool, + ) -> None: + if info.base_idx is None: + raise AssertionError("expected info.base_idx to be set") + self._unwrap_aliased_base_tensor = _identity + if info.output_type in ( + OutputType.alias_of_intermediate, + OutputType.alias_of_intermediate_save_as_output, + ): + num_user_outputs = len(runtime_metadata.output_info) + self.base_idx = info.base_idx + num_user_outputs + else: + self.base_idx = info.base_idx + if self.base_idx in runtime_metadata.aliased_out_indices: + self._unwrap_aliased_base_tensor = _unwrap_tensoralias + + self.unwrap_out = _unwrap_tensoralias if trace_joint else _identity + self.requires_grad = info.requires_grad + self.view_meta_sequence = info.view_meta_sequence + self.replay_views = config.view_replay_for_aliased_outputs + + def __call__( + self, orig_inputs: dict[int, Tensor], fw_outs: list[Any], out: Any + ) -> torch.Tensor: + aliased_base_tensor = fw_outs[self.base_idx] + return gen_alias_from_base( + self._unwrap_aliased_base_tensor(aliased_base_tensor), + self.unwrap_out(out), + self.requires_grad, + self.view_meta_sequence, + replay_views=self.replay_views, + ) + + +_HANDLER_MAP: dict[ + OutputType, + type[ + NoopAliasHandler + | AliasOfInputHandler + | IsInputHandler + | AliasOfIntermediateHandler + ], +] = { + OutputType.non_alias: NoopAliasHandler, + OutputType.unsafe_view_alias: NoopAliasHandler, + OutputType.custom_function_view: NoopAliasHandler, + OutputType.alias_of_input: AliasOfInputHandler, + OutputType.is_input: IsInputHandler, + OutputType.alias_of_intermediate: AliasOfIntermediateHandler, + OutputType.alias_of_intermediate_save_as_output: AliasOfIntermediateHandler, + OutputType.alias_of_intermediate_base_is_user_output: AliasOfIntermediateHandler, +} + + +def make_output_handler( + info: OutputAliasInfo, runtime_metadata: ViewAndMutationMeta, trace_joint: bool +) -> ( + NoopAliasHandler | AliasOfInputHandler | IsInputHandler | AliasOfIntermediateHandler +): + handler_type = _HANDLER_MAP[info.output_type] + return handler_type(info, runtime_metadata, trace_joint) + + +# _dynamo_propagated_dynamic_indices: A guardless attribute for cross-graph-break +# dynamism propagation. When AOTAutograd traces a graph and discovers that output +# dimensions are symbolic (dynamic), it stamps this attribute on the output tensors +# at runtime. This tells Dynamo to treat those dims as weakly dynamic when the tensor +# appears as input to a subsequent graph (e.g., after a graph break), avoiding +# unnecessary specialization and recompilation. +# +# Unlike _dynamo_weak_dynamic_indices (which is user-facing, set via maybe_mark_dynamic(), +# and guarded on), this attribute is compiler-internal and NOT guarded on. This avoids +# the problem where the compiler mutating an input tensor's attributes (through an +# input-aliased output) would cause a spurious guard failure and recompilation. +# +# Note: this is best-effort. Eager code does not propagate +# _dynamo_propagated_dynamic_indices, so there is no guarantee that the next graph +# will have proper dynamism information. It only helps when the output of one compiled +# graph feeds directly into the next. +def mark_dynamo_propagated_dynamic_indices(t: torch.Tensor, dims: set[int]) -> None: + if hasattr(t, "_dynamo_propagated_dynamic_indices"): + # pyrefly: ignore [missing-attribute] + t._dynamo_propagated_dynamic_indices |= dims + else: + t._dynamo_propagated_dynamic_indices = dims.copy() # type: ignore[attr-defined] + + +def _should_disable_saved_tensors_hooks() -> bool: + # Compiled autograd is not supported yet, to be added in future. + if torch._dynamo.compiled_autograd.in_compiled_autograd_region: + return False + + get_hooks = torch._functorch._aot_autograd.utils.top_saved_tensors_hooks + are_inline_hooks = ( + torch._functorch._aot_autograd.utils.saved_tensors_hooks_are_inlineable + ) + + hooks = get_hooks() + if are_inline_hooks(hooks): + return True + + return False + + +def _schema_allows_aliasing(func: Any) -> bool: + schema = func._schema + # View ops have non-write aliases declared in arguments + if schema._is_view_op(): + return True + # Handles cases like mkldnn::_convolution_pointwise_.binary + # where the schema is Tensor(a!) other -> Tensor(a!) Y + for ret in schema.returns: + if ret.alias_info is not None: + return True + return False + + +def _check_custom_op_aliasing( + name: str, args: tuple[Any, ...], kwargs: dict[str, Any], result: Any +) -> None: + """ + Check if custom op outputs alias inputs or other outputs. + If config.error_on_custom_op_aliasing is True, raises RuntimeError. + Otherwise, emits a warning. + """ + try: + torch._library.utils._c_check_aliasing_constraint( + name, + args, + kwargs, + result, + ) + except RuntimeError as e: + if config.error_on_custom_op_aliasing: + raise + else: + msg = f"{e} This is deprecated and will become an error in a future version of PyTorch." + warnings.warn(msg, UserWarning, stacklevel=3) + + +@functools.lru_cache(None) +def _is_fsdp_all_gather_copy_in(func: Any) -> bool: + """ + Check if func is torch.ops.fsdp.all_gather_copy_in.default by comparing + namespace and name strings. This avoids accessing torch.ops.fsdp directly, + which would fail on platforms where FSDP ops aren't registered (e.g., macOS + builds with USE_DISTRIBUTED=0). + """ + return ( + hasattr(func, "namespace") + and func.namespace == "fsdp" + and hasattr(func, "__name__") + and func.__name__ == "all_gather_copy_in.default" + ) + + +class _AnalyzeCustomOpInputOutputMode(TorchDispatchMode): + """ + Checks if inp/out of custom ops alias each other. + If config.error_on_custom_op_aliasing is True, violations raise errors. + Otherwise, violations emit warnings. + """ + + def __init__(self) -> None: + super().__init__() + self.supports_higher_order_operators = True + + def __torch_dispatch__( + self, + func: OpOverload, + types: Any, + args: tuple[Any, ...] = (), + kwargs: dict[str, Any] | None = None, + ) -> Any: + if not kwargs: + kwargs = {} + + flat_tensor_args = filter( + lambda x: isinstance(x, torch.Tensor), tree_flatten((args, kwargs))[0] + ) + + # Defer this to subclass torchdispatch modes (probably shouldn't have fake tensor here tho) + # For Parameters, we need to check the underlying tensor type, not the Parameter itself + for tensor in flat_tensor_args: + underlying_tensor = tensor + if isinstance(tensor, torch.nn.Parameter): + underlying_tensor = tensor.data + if type(underlying_tensor) not in HANDLED_TYPES: + return NotImplemented + + res = func(*args, **kwargs) + # Only check aliasing for custom ops (non-aten/prim/prims/_c10d_functional/c10d) + # that claim to be functional + # Skip ops whose schema declares aliasing is allowed + if ( + not isinstance(func, torch._ops.HigherOrderOperator) + and not is_builtin(func) + # TODO (https://github.com/pytorch/pytorch/issues/170986) + and func.namespace not in ("_c10d_functional", "c10d", "onednn") + # This op is quite important but has wrong schema, so lets skip for now + and not _is_fsdp_all_gather_copy_in(func) + and not _schema_allows_aliasing(func) + ): + _check_custom_op_aliasing( + func.name(), + args, + kwargs, + res, + ) + return res + + @classmethod + def ignore_compile_internals(cls) -> bool: + return True + + +class _FirstInvocationContext: + """ + Context manager that tracks first invocation and conditionally enables _AnalyzeCustomOpInputOutputMode. + This is useful when we have a custom op where we want to analyze its input + and output during cold start. + """ + + def __init__(self) -> None: + self._is_first = True + + def __call__(self) -> AbstractContextManager[Any]: + """ + Returns a context manager: _AnalyzeCustomOpInputOutputMode on first invocation, nullcontext thereafter. + Automatically updates state after first use. + """ + # NB: Don't run the analyzer when you're forcing compile during FX + # tracing, as the analyzer doesn't play nicely when it's being + # make_fx'ed through + if ( + self._is_first + and config.check_custom_op_aliasing + and not torch._dynamo.config.force_compile_during_fx_trace + ): + self._is_first = False + return _AnalyzeCustomOpInputOutputMode() + return nullcontext() + + +# Note [RuntimeWrapper codegen specification methods] +# The run() method on _RuntimeCompiledFnInvoker and the capture_orig_inputs(), +# increment_mutation_versions(), and finalize() methods on _RuntimeForwardEpilogue +# are the readable reference implementations for the codegen'd _runtime_wrapper +# generated in _create_runtime_wrapper(). They are not called on the hot path; +# the codegen inlines their logic with all branches resolved at compile time. +# +# WARNING: Any semantic change to the runtime wrapper must be reflected in both +# the reference methods here and the codegen in _create_runtime_wrapper(). +@dataclass +class _RuntimeCompiledFnInvoker: + compiled_fn: Callable[..., Any] + indices_of_inps_to_detach: list[int] + trace_joint: bool + disable_amp: bool + first_invocation_ctx: _FirstInvocationContext = field( + default_factory=_FirstInvocationContext + ) + + def __post_init__(self) -> None: + if not getattr(self.compiled_fn, "_boxed_call", False): + self.compiled_fn = make_boxed_func(self.compiled_fn) + + # WARNING: this is a reference implementation; the hot path uses codegen'd + # code from _create_runtime_wrapper(). Keep both in sync. + # See Note [RuntimeWrapper codegen specification methods] + def run(self, args: list[Any], *, on_before_call: Callable[[], None]) -> list[Any]: + with self.first_invocation_ctx(): + if self.trace_joint: + args_ = list(args) + # See Note [Detaching inputs that never need gradients] + for idx in self.indices_of_inps_to_detach: + if isinstance(args_[idx], torch.Tensor): + args_[idx] = args_[idx].detach() + + # It's possible to have trace_joint inside user specified with no_grad() region, + # if there is a nested with enable_grad(), that forces some outputs to require gradients. + # Therefore, we unconditionally turn on enable_grad() for compiled_fn execution. + prev_view_replay_enabled = torch._C._is_view_replay_enabled() + try: + if not prev_view_replay_enabled: + torch._C._set_view_replay_enabled(True) + with torch.enable_grad(): + on_before_call() + return call_func_at_runtime_with_args( + self.compiled_fn, + args_, + disable_amp=self.disable_amp, + steal_args=True, + ) + finally: + if torch._C._is_view_replay_enabled() != prev_view_replay_enabled: + torch._C._set_view_replay_enabled(prev_view_replay_enabled) + + # When we have an inference graph, we run with grad disabled. + # It's possible to get an inference graph with inputs that require grad, + # in which case we want to make sure autograd is disabled + # (since e.g., inductor will generate aten.addmm.out calls which autograd will complain on) + # NOTE: We use _set_grad_enabled directly to reduce runtime overhead + grad_enabled = torch.is_grad_enabled() + try: + if grad_enabled: + torch._C._set_grad_enabled(False) + on_before_call() + return call_func_at_runtime_with_args( + self.compiled_fn, + args, + disable_amp=self.disable_amp, + steal_args=True, + ) + finally: + if grad_enabled: + torch._C._set_grad_enabled(True) + + +@dataclass +class _RuntimeForwardEpilogue: + runtime_metadata: ViewAndMutationMeta + trace_joint: bool + keep_input_mutations: bool + epilogue_args_idx: tuple[int, ...] = field(init=False) + output_handlers: tuple[ + NoopAliasHandler + | AliasOfInputHandler + | IsInputHandler + | AliasOfIntermediateHandler, + ..., + ] = field(init=False) + + def __post_init__(self) -> None: + epilogue_args_idx = list(self.runtime_metadata.mutated_inp_runtime_indices) + for info in self.runtime_metadata.output_info: + if ( + info.output_type == OutputType.alias_of_input + or info.output_type == OutputType.is_input + ): + if not isinstance(info.base_idx, int): + raise AssertionError( + f"expected info.base_idx to be int, got {type(info.base_idx)}" + ) + epilogue_args_idx.append(info.base_idx) + self.epilogue_args_idx = tuple(epilogue_args_idx) + + if config.unlift_effect_tokens: + if len(self.runtime_metadata.tokens) != 0: + raise AssertionError( + "expected no tokens when unlift_effect_tokens is True, " + f"got {len(self.runtime_metadata.tokens)}" + ) + + if self.runtime_metadata.num_outputs_aliased > 0: + self.output_handlers = tuple( + make_output_handler(info, self.runtime_metadata, self.trace_joint) + for info in self.runtime_metadata.output_info + ) + else: + self.output_handlers = () + + # WARNING: this is a reference implementation; the hot path uses codegen'd + # code from _create_runtime_wrapper(). Keep both in sync. + # See Note [RuntimeWrapper codegen specification methods] + def capture_orig_inputs(self, args: list[Any]) -> dict[int, Tensor]: + return {i: typing.cast(Tensor, args[i]) for i in self.epilogue_args_idx} + + # WARNING: this is a reference implementation; the hot path uses codegen'd + # code from _create_runtime_wrapper(). Keep both in sync. + # See Note [RuntimeWrapper codegen specification methods] + def increment_mutation_versions(self, args: list[Any]) -> None: + if self.keep_input_mutations: + mutated_args = ( + args[i] + for i in self.runtime_metadata.mutated_graph_handled_indices_seen_by_autograd + ) + torch.autograd.graph.increment_version(mutated_args) + + # WARNING: this is a reference implementation; the hot path uses codegen'd + # code from _create_runtime_wrapper(). Keep both in sync. + # See Note [RuntimeWrapper codegen specification methods] + def finalize(self, orig_inputs: dict[int, Tensor], all_outs: list[Any]) -> Any: + self._validate_compiled_output_arity(all_outs) + updated_inputs, fw_outs = self._split_mutated_inputs(all_outs) + if updated_inputs is not None: + self._apply_input_mutations(orig_inputs, updated_inputs) + + ret_outs = self._replay_output_aliases(orig_inputs, fw_outs) + if self.runtime_metadata.dynamic_outputs: + for t, o in zip(ret_outs, self.runtime_metadata.output_info): + if o.dynamic_dims is None: + continue + mark_dynamo_propagated_dynamic_indices(t, o.dynamic_dims) + if self.runtime_metadata.grad_enabled_mutation is not None: + torch._C._set_grad_enabled(self.runtime_metadata.grad_enabled_mutation) + return ret_outs + + def _validate_compiled_output_arity(self, all_outs: list[Any]) -> None: + expected_outs = ( + self.runtime_metadata.num_mutated_inp_runtime_indices + + self.runtime_metadata.num_outputs + + self.runtime_metadata.num_intermediate_bases + ) + if len(all_outs) != expected_outs: + raise AssertionError( + f"expected {expected_outs} outputs, got {len(all_outs)}" + ) + + def _split_mutated_inputs( + self, all_outs: list[Any] + ) -> tuple[list[Any] | None, list[Any]]: + num_mutated_runtime_inps = self.runtime_metadata.num_mutated_inp_runtime_indices + if num_mutated_runtime_inps == 0: + return None, all_outs + return ( + all_outs[:num_mutated_runtime_inps], + all_outs[num_mutated_runtime_inps:], + ) + + def _apply_input_mutations( + self, orig_inputs: dict[int, Tensor], updated_inputs: list[Any] + ) -> None: + for i, inpt_idx in enumerate(self.runtime_metadata.mutated_inp_runtime_indices): + meta = self.runtime_metadata.input_info[inpt_idx] + if not meta.mutates_data and not meta.mutates_metadata: + continue + original_inpt = orig_inputs[inpt_idx] + updated_inpt = updated_inputs[i] + if meta.mutates_storage_metadata: + # See Note [set_() Input Mutations in AOTAutograd] + # mutates_storage_metadata means our input saw a x.set_(y) call. + # What if x **also** saw a data and/or a metadata mutation? + # (1) If the [meta]data mutation occurred after the set_(), + # then there is no need to copy_() the data. + # When we perform x.set_(x_updated), we are guaranteed that + # x_updated already has the final version of the data/metadata + # (2) If a data mutation occurred before the set_(). + # This case seems very difficult to support. + # TODO: discuss on the PR and decide if we want to tr to + # either support it, or detect and ban it. + if self.trace_joint: + if not isinstance(updated_inpt, TensorAlias): + raise AssertionError( + f"expected TensorAlias for updated_inpt, got {type(updated_inpt)}" + ) + updated_inpt = updated_inpt.alias + with torch.no_grad(): + if meta.mutation_is_shallow_copy_data: + torch.ops.aten.shallow_copy_data_(original_inpt, updated_inpt) + else: + original_inpt.set_(updated_inpt) + continue + if meta.mutates_metadata and not meta.mutates_data: + if self.trace_joint: + if not isinstance(updated_inpt, TensorAlias): + raise AssertionError( + f"expected TensorAlias for updated_inpt, got {type(updated_inpt)}" + ) + updated_inpt = updated_inpt.alias + # We need to grab the size/stride/storage_offset from the compiled forward, + # and use that to mutate the metadata of the input + original_inpt.as_strided_( + updated_inpt.size(), + updated_inpt.stride(), + updated_inpt.storage_offset(), + ) + else: + if meta.mutates_data and meta.mutates_metadata: + original_inpt.as_strided_( + updated_inpt.size(), + updated_inpt.stride(), + updated_inpt.storage_offset(), + ) + else: + if not meta.mutates_data: + raise AssertionError("expected meta.mutates_data to be True") + if meta.is_leaf and original_inpt.requires_grad: + # We can hit this situation in this case: + # def f(x): + # x.detach().mul_(2) + # return x + 1 + # AOTAutograd will see a mutation in the above case, and try to + # apply a copy_() here, in the epilogue. + # But if x required gradients, and is a leaf, then autograd + # will yell at us for trying to mutate it. + # However, it's only possible to end up in this scenario (like the above) + # if all of the mutations to the leaf input were non-autograd-tracking mutations + # (aka mutations under no_grad(), or on detached views). + # In that case, we fully want to hide the mutation from autograd, so detaching is ok. + original_inpt.detach().copy_(updated_inpt) + else: + # Check if we have stream index information for this mutated input + if ( + self.runtime_metadata.mutated_inp_stream_indices is not None + and i < len(self.runtime_metadata.mutated_inp_stream_indices) + and self.runtime_metadata.mutated_inp_stream_indices[i] + is not None + ): + raise RuntimeError( + "Mutations on inputs with user-specified streams are not yet supported. " + "See: https://github.com/pytorch/pytorch/issues/172522" + ) + original_inpt.copy_(updated_inpt) + + def _replay_output_aliases( + self, orig_inputs: dict[int, Tensor], fw_outs: list[Any] + ) -> Any: + if self.runtime_metadata.num_outputs_aliased == 0: + return fw_outs + + # The compiled forward also returned intermediate bases. We don't want to return them to the user. + expect_num_outputs = ( + len(self.output_handlers) + self.runtime_metadata.num_intermediate_bases + ) + if len(fw_outs) != expect_num_outputs: + raise AssertionError( + f"expected {expect_num_outputs} fw_outs, got {len(fw_outs)}" + ) + return [ + handler(orig_inputs, fw_outs, out) + for out, handler in zip(fw_outs, self.output_handlers) + ] + + +def _codegen_capture_orig_inputs( + buf: "PySourceBuilder", + epilogue_args_idx: tuple[int, ...], +) -> None: + if epilogue_args_idx: + idx_str = ", ".join(f"{i}: args[{i}]" for i in epilogue_args_idx) + buf.emit(f"orig_inputs = {{{idx_str}}}", indent=1) + else: + buf.emit("orig_inputs = {}", indent=1) + + +def _codegen_increment_mutation_versions( + buf: "PySourceBuilder", + keep_input_mutations: bool, + runtime_metadata: ViewAndMutationMeta, +) -> None: + if ( + keep_input_mutations + and runtime_metadata.mutated_graph_handled_indices_seen_by_autograd + ): + buf.add_global("_increment_version_", torch.autograd.graph.increment_version) + mut_idx = tuple(runtime_metadata.mutated_graph_handled_indices_seen_by_autograd) + gen_expr = ", ".join(f"args[{i}]" for i in mut_idx) + buf.emit(f"_increment_version_(({gen_expr},))", indent=1) + + +def _codegen_normalize_as_list( + buf: "PySourceBuilder", var_name: str, *, indent_level: int +) -> None: + buf.emit(f"if isinstance({var_name}, tuple):", indent=indent_level) + buf.emit(f"{var_name} = list({var_name})", indent=indent_level + 1) + buf.emit(f"elif not isinstance({var_name}, list):", indent=indent_level) + buf.emit(f"{var_name} = [{var_name}]", indent=indent_level + 1) + + +def _codegen_compiled_fn_invocation( + buf: "PySourceBuilder", + trace_joint: bool, + indices_of_inps_to_detach: list[int], + disable_amp: bool, +) -> None: + buf.emit("with _first_ctx_():", indent=1) + # trace_joint is known at codegen time. Only the joint/training path needs + # forced view replay; inference wrappers should not touch this TLS state. + if trace_joint: + buf.emit("args_ = list(args)", indent=2) + for idx in indices_of_inps_to_detach: + buf.emit( + f"if isinstance(args_[{idx}], torch.Tensor): " + f"args_[{idx}] = args_[{idx}].detach()", + indent=2, + ) + buf.emit( + "prev_view_replay_enabled = torch._C._is_view_replay_enabled()", indent=2 + ) + buf.emit("try:", indent=2) + buf.emit("if not prev_view_replay_enabled:", indent=3) + buf.emit("torch._C._set_view_replay_enabled(True)", indent=4) + buf.emit("with torch.enable_grad():", indent=3) + buf.emit("_on_before_call_()", indent=4) + if disable_amp: + buf.add_global("_DisableAutocast_", torch._C._DisableAutocast) + buf.emit("with _DisableAutocast_():", indent=4) + buf.emit("all_outs = _compiled_fn_(args_)", indent=5) + _codegen_normalize_as_list(buf, "all_outs", indent_level=5) + else: + buf.emit("all_outs = _compiled_fn_(args_)", indent=4) + _codegen_normalize_as_list(buf, "all_outs", indent_level=4) + buf.emit("finally:", indent=2) + buf.emit( + "if torch._C._is_view_replay_enabled() != prev_view_replay_enabled:", + indent=3, + ) + buf.emit( + "torch._C._set_view_replay_enabled(prev_view_replay_enabled)", indent=4 + ) + else: + buf.emit("grad_enabled = torch.is_grad_enabled()", indent=2) + buf.emit("try:", indent=2) + buf.emit("if grad_enabled: torch._C._set_grad_enabled(False)", indent=3) + buf.emit("_on_before_call_()", indent=3) + if disable_amp: + buf.add_global("_DisableAutocast_", torch._C._DisableAutocast) + buf.emit("with _DisableAutocast_():", indent=3) + buf.emit("all_outs = _compiled_fn_(args)", indent=4) + _codegen_normalize_as_list(buf, "all_outs", indent_level=4) + else: + buf.emit("all_outs = _compiled_fn_(args)", indent=3) + _codegen_normalize_as_list(buf, "all_outs", indent_level=3) + buf.emit("finally:", indent=2) + buf.emit("if grad_enabled: torch._C._set_grad_enabled(True)", indent=3) + buf.emit("del args", indent=1) + + +# signatures mirror the _RuntimeForwardEpilogue reference methods +# (_apply_input_mutations / _replay_output_aliases). The codegen'd _alias_fn +# always builds and returns a list, so list[Any] is tighter than the reference's +# -> Any (the early `return fw_outs` path does not exist in the codegen'd fn). +_EpilogueApplyMutationsFn = Callable[[dict[int, Tensor], list[Any]], None] +_EpilogueReplayAliasesFn = Callable[[dict[int, Tensor], list[Any]], list[Any]] + + +def _codegen_epilogue( + buf: "PySourceBuilder", + runtime_metadata: ViewAndMutationMeta, + apply_mutations_fn: _EpilogueApplyMutationsFn | None, + replay_aliases_fn: _EpilogueReplayAliasesFn | None, + num_mutated_runtime_inps: int, + expected_outs: int, +) -> None: + buf.emit(f"if len(all_outs) != {expected_outs}:", indent=1) + buf.emit( + f'raise AssertionError(f"expected {expected_outs} outputs, ' + f'got {{len(all_outs)}}")', + indent=2, + ) + + if num_mutated_runtime_inps > 0: + buf.emit(f"updated_inputs = all_outs[:{num_mutated_runtime_inps}]", indent=1) + buf.emit(f"fw_outs = all_outs[{num_mutated_runtime_inps}:]", indent=1) + buf.emit("_apply_mutations_(orig_inputs, updated_inputs)", indent=1) + buf.add_global("_apply_mutations_", apply_mutations_fn) + else: + buf.emit("fw_outs = all_outs", indent=1) + + if runtime_metadata.num_outputs_aliased > 0: + buf.add_global("_replay_aliases_", replay_aliases_fn) + buf.emit("ret_outs = _replay_aliases_(orig_inputs, fw_outs)", indent=1) + else: + buf.emit("ret_outs = fw_outs", indent=1) + + if runtime_metadata.dynamic_outputs: + buf.add_global("_mark_dynamic_", mark_dynamo_propagated_dynamic_indices) + for i, o in enumerate(runtime_metadata.output_info): + if o.dynamic_dims is not None: + dims_name = f"_dyn_dims_{i}" + buf.add_global(dims_name, o.dynamic_dims) + buf.emit(f"_mark_dynamic_(ret_outs[{i}], {dims_name})", indent=1) + + if runtime_metadata.grad_enabled_mutation is not None: + buf.emit( + f"torch._C._set_grad_enabled({runtime_metadata.grad_enabled_mutation!r})", + indent=1, + ) + + buf.emit("return ret_outs", indent=1) + + +def _create_runtime_wrapper( + compiled_fn: Callable[..., Any], + *, + runtime_metadata: ViewAndMutationMeta, + indices_of_inps_to_detach: list[int], + trace_joint: bool, + keep_input_mutations: bool, + disable_amp: bool, +) -> Callable[..., Any]: + compiled_invoker = _RuntimeCompiledFnInvoker( + compiled_fn=compiled_fn, + indices_of_inps_to_detach=indices_of_inps_to_detach, + trace_joint=trace_joint, + disable_amp=disable_amp, + ) + runtime_epilogue = _RuntimeForwardEpilogue( + runtime_metadata=runtime_metadata, + trace_joint=trace_joint, + keep_input_mutations=keep_input_mutations, + ) + + # The orchestration closes over these two codegen'd epilogue functions directly + # (bound into rw_globals as _apply_mutations_ / _replay_aliases_ in _codegen_epilogue). + # Each stays None when its epilogue step is absent for this graph. + codegen_apply_mutations: _EpilogueApplyMutationsFn | None = None + codegen_alias_fn: _EpilogueReplayAliasesFn | None = None + + # Codegen output alias regeneration: emit straight-line code per output + # with all handler branches resolved at compile time. + if runtime_metadata.num_outputs_aliased > 0: + output_handlers = runtime_epilogue.output_handlers + from .codegen import PySourceBuilder + + buf = PySourceBuilder( + "_alias_fn", + args="orig_inputs, fw_outs", + artifact_name="output_alias_wrapper", + ) + buf.bind( + gen_alias_from_base=gen_alias_from_base, + _unwrap_tensoralias=_unwrap_tensoralias, + ) + with buf.indent(): + buf.writeline("ret_outs = []") + for i, handler in enumerate(output_handlers): + if isinstance(handler, NoopAliasHandler): + buf.writeline(f"ret_outs.append(fw_outs[{i}])") + elif isinstance(handler, IsInputHandler): + buf.writeline(f"ret_outs.append(orig_inputs[{handler.base_idx}])") + elif isinstance(handler, AliasOfInputHandler): + vms_name = buf.bind_value("_vms", handler.view_meta_sequence) + out_expr = ( + f"_unwrap_tensoralias(fw_outs[{i}])" + if trace_joint + else f"fw_outs[{i}]" + ) + buf.writeline( + f"ret_outs.append(gen_alias_from_base(" + f"orig_inputs[{handler.base_idx}], {out_expr}, " + f"{handler.requires_grad!r}, {vms_name}, " + f"replay_views={handler.replay_views!r}))" + ) + elif isinstance(handler, AliasOfIntermediateHandler): + vms_name = buf.bind_value("_vms", handler.view_meta_sequence) + out_expr = ( + f"_unwrap_tensoralias(fw_outs[{i}])" + if trace_joint + else f"fw_outs[{i}]" + ) + base_unwrap = ( + handler._unwrap_aliased_base_tensor is _unwrap_tensoralias + ) + base_expr = ( + f"_unwrap_tensoralias(fw_outs[{handler.base_idx}])" + if base_unwrap + else f"fw_outs[{handler.base_idx}]" + ) + buf.writeline( + f"ret_outs.append(gen_alias_from_base(" + f"{base_expr}, {out_expr}, " + f"{handler.requires_grad!r}, {vms_name}, " + f"replay_views={handler.replay_views!r}))" + ) + else: + raise AssertionError( + f"unhandled output handler type: {type(handler).__name__}" + ) + buf.writeline("return ret_outs") + + codegen_alias_fn = typing.cast(_EpilogueReplayAliasesFn, buf.build()) + + def record_runtime_wrapper_prologue_enter() -> AbstractContextManager[None] | None: + if ( + torch.autograd.profiler._is_profiler_enabled + and dynamo_config.record_runtime_overhead + ): + cm = torch._C._profiler._RecordFunctionFast( + "AOTDispatcher Runtime Wrapper Prologue" + ) + cm.__enter__() + return cm + return None + + def record_runtime_wrapper_prologue_exit( + cm: AbstractContextManager[None] | None, + ) -> None: + if cm is not None: + cm.__exit__(None, None, None) + + # Codegen mutation epilogue: emit straight-line code per mutated input + # with all branches resolved at compile time. + if runtime_metadata.num_mutated_inp_runtime_indices > 0: + from .codegen import PySourceBuilder + + buf = PySourceBuilder( + "_apply_mutations", + args="orig_inputs, updated_inputs", + artifact_name="mutation_epilogue", + ) + buf.bind(torch=torch, _unwrap_tensoralias=_unwrap_tensoralias) + wrote_body = False + with buf.indent(): + for i, inpt_idx in enumerate(runtime_metadata.mutated_inp_runtime_indices): + meta = runtime_metadata.input_info[inpt_idx] + if not meta.mutates_data and not meta.mutates_metadata: + continue + wrote_body = True + oi = f"orig_inputs[{inpt_idx}]" + ui = f"updated_inputs[{i}]" + if meta.mutates_storage_metadata: + u = buf.fresh_name("_u") + if trace_joint: + buf.writeline(f"{u} = _unwrap_tensoralias({ui})") + else: + buf.writeline(f"{u} = {ui}") + buf.writeline(f"with torch.no_grad(): {oi}.set_({u})") + elif meta.mutates_metadata and not meta.mutates_data: + u = buf.fresh_name("_u") + if trace_joint: + buf.writeline(f"{u} = _unwrap_tensoralias({ui})") + else: + buf.writeline(f"{u} = {ui}") + buf.writeline( + f"{oi}.as_strided_({u}.size(), {u}.stride(), {u}.storage_offset())" + ) + else: + if meta.mutates_data and meta.mutates_metadata: + buf.writeline( + f"{oi}.as_strided_({ui}.size(), {ui}.stride(), {ui}.storage_offset())" + ) + else: + if not meta.mutates_data: + raise AssertionError( + f"expected mutates_data for input {inpt_idx}" + ) + if meta.is_leaf: + buf.writeline( + f"if {oi}.requires_grad: {oi}.detach().copy_({ui})" + ) + buf.writeline(f"else: {oi}.copy_({ui})") + else: + has_stream = ( + runtime_metadata.mutated_inp_stream_indices is not None + and i < len(runtime_metadata.mutated_inp_stream_indices) + and runtime_metadata.mutated_inp_stream_indices[i] + is not None + ) + if has_stream: + msg_name = buf.bind_value( + "_stream_err", + "Mutations on inputs with user-specified streams are not yet supported. " + "See: https://github.com/pytorch/pytorch/issues/172522", + ) + buf.writeline(f"raise RuntimeError({msg_name})") + else: + buf.writeline(f"{oi}.copy_({ui})") + if not wrote_body: + buf.writeline("pass") + + codegen_apply_mutations = typing.cast(_EpilogueApplyMutationsFn, buf.build()) + + from .codegen import PySourceBuilder + + epilogue_args_idx = runtime_epilogue.epilogue_args_idx + num_mutated_runtime_inps = runtime_metadata.num_mutated_inp_runtime_indices + expected_outs = ( + num_mutated_runtime_inps + + runtime_metadata.num_outputs + + runtime_metadata.num_intermediate_bases + ) + + buf = PySourceBuilder( + "_runtime_wrapper", + args="_compiled_fn_, _first_ctx_, _on_before_call_, args", + artifact_name="runtime_wrapper_orchestration", + ) + buf.bind(torch=torch) + + _codegen_capture_orig_inputs(buf, epilogue_args_idx) + _codegen_increment_mutation_versions(buf, keep_input_mutations, runtime_metadata) + _codegen_compiled_fn_invocation( + buf, trace_joint, indices_of_inps_to_detach, disable_amp + ) + _codegen_epilogue( + buf, + runtime_metadata, + codegen_apply_mutations, + codegen_alias_fn, + num_mutated_runtime_inps, + expected_outs, + ) + + _codegen_runtime_wrapper = buf.build() + + _inner_compiled_fn = compiled_invoker.compiled_fn + _first_invocation_ctx = compiled_invoker.first_invocation_ctx + + @simple_wraps(_inner_compiled_fn) + def runtime_wrapper(args: list[Any]) -> Any: + cm = record_runtime_wrapper_prologue_enter() + prologue_exited = False + + def exit_prologue() -> None: + nonlocal prologue_exited + if not prologue_exited: + record_runtime_wrapper_prologue_exit(cm) + prologue_exited = True + + try: + result = _codegen_runtime_wrapper( + _inner_compiled_fn, + _first_invocation_ctx, + exit_prologue, + args, + ) + finally: + exit_prologue() + del args + return result + + if not (trace_joint and _should_disable_saved_tensors_hooks()): + return runtime_wrapper + + @simple_wraps(runtime_wrapper) + def _runtime_wrapper(*args: Any, **kwargs: Any) -> Any: + with _disable_saved_tensors_hooks(): + return runtime_wrapper(*args, **kwargs) + + return _runtime_wrapper + + +# WARNING: this does NOT operate on TraceFn +@dataclass +class FunctionalizedRngRuntimeWrapper(InductorWrapper): + # TODO: I would love to get rid of this argument, but it's + # Wrapped pretty tightly around our aot_dispatch_autograd logic. + # Specifically, tensors_saved_for_backwards_slice's value is both used for calculating indices + # for setting placeholder strides(which is done before runtime, before this wrapper runs) + # and for saving tensors for backward (which is done during runtime, after this wrapper runs) + # So in aot_dispatch_autograd, this wrapper can't edit the set of outs without making one + # of those two indices incorrect. + return_new_outs: bool = True + + def pre_compile( + self, + fw_module: torch.fx.GraphModule, + flat_args: list[Any], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, + ) -> None: + if config.functionalize_rng_ops: + # Update example inputs for the fw_compiler + fake_mode = detect_fake_mode() + if fake_mode is None: + raise AssertionError( + "fake_mode must not be None when functionalize_rng_ops is True" + ) + seed, offset = CUDARngStateHelper.get_torch_state_as_tuple(fake_mode) + flat_args.extend([seed, offset]) + # We are not clearing flat_args here because + # 1) There is a check in the debug compiler at the end + # 2) It does not matter as these are fake tensors + + def post_compile( + self, + compiled_fn: Callable[..., Any], + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ) -> Callable[..., Any]: + if not runtime_metadata.is_rng_op_functionalized: + return compiled_fn + + if runtime_metadata.num_outputs_rng_offset != 1: + raise AssertionError( + f"expected num_outputs_rng_offset == 1, got {runtime_metadata.num_outputs_rng_offset}" + ) + + from .codegen import PySourceBuilder + + offset_index = runtime_metadata.num_forward_returns + buf = PySourceBuilder( + "_functionalized_rng_wrapper", + args="runtime_args", + artifact_name="functionalized_rng_wrapper", + ) + buf.bind( + _compiled_fn_=compiled_fn, + _get_rng_state_=CUDARngStateHelper.get_torch_state_as_tuple, + _set_offset_=CUDARngStateHelper.set_new_offset, + ) + with buf.indent(): + buf.writeline("seed, offset = _get_rng_state_()") + buf.writeline("runtime_args.extend([seed, offset])") + buf.writeline("outs = _compiled_fn_(runtime_args)") + buf.writeline(f"_set_offset_(outs[{offset_index}])") + if self.return_new_outs: + buf.writeline( + f"return outs[:{offset_index}] + outs[{offset_index + 1}:]" + ) + else: + buf.writeline("return outs") + + inner_fn = buf.build(wrapped_fn=compiled_fn) + inner_fn._boxed_call = True # type: ignore[attr-defined] + return inner_fn + + # Calling convention: If we are running functionalized RNG, then outs consists + # of (user_outs, rng_offset) + def _functionalized_rng_runtime_epilogue( + self, + metadata: ViewAndMutationMeta, + outs: Any, + offset_index: int, + ) -> Any: + if metadata.is_rng_op_functionalized: + if metadata.num_outputs_rng_offset != 1: + raise AssertionError( + f"expected num_outputs_rng_offset == 1, got {metadata.num_outputs_rng_offset}" + ) + new_rng_offset = outs[offset_index] + CUDARngStateHelper.set_new_offset(new_rng_offset) + if self.return_new_outs: + user_outs = outs[:offset_index] + outs[offset_index + 1 :] + return user_outs + else: + return outs + + return outs + + +# WARNING: this does NOT operate on TraceFn +@dataclass +class FakifiedOutWrapper(InductorWrapper): + out_metas: list[torch.Tensor] = field(default_factory=list) + # TracingContext.fwd_output_strides + # Generated from actually doing compile + # NB: an entry is None if it's not a Tensor + fwd_output_strides: list[list[int] | None] | None = None + needs_post_compile: bool = True + + def pre_compile( + self, + fw_module: fx.GraphModule, # Must be fw_module from aot_dispatch_*_graph + flat_args: list[Any], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, + ) -> None: + tracing_context = torch._guards.TracingContext.try_get() + if tracing_context and tracing_context.fakify_first_call: + self.out_metas = [ + n.meta["val"] for n in (list(fw_module.graph.nodes)[-1].args[0]) + ] + else: + self.needs_post_compile = False + + def _compute_output_meta_with_inductor_strides(self) -> list[torch.Tensor]: + out = self.out_metas + fwd_output_strides = self.fwd_output_strides + if not fwd_output_strides: + return out + + from torch.fx.experimental.symbolic_shapes import statically_known_true + + for i in range(len(out)): + if not isinstance(out[i], Tensor): + continue + strides = fwd_output_strides[i] + # fwd_output_strides is best effort by Inductor. When an output + # Tensor has unbacked SymInts, Inductor may sometimes be unable + # to compute what the output stride would be. If Inductor doesn't + # have any clear direction on the layout, we don't have to run + # as_strided. To repro without this, run: + # + # python test/distributed/test_dynamo_distributed.py + # TestFakeDistributedSingleProc.test_unbacked_symbol_splitting_no_binding + if strides is None: + continue + if all( + statically_known_true(s1 == s2) + for s1, s2 in zip(out[i].stride(), strides) + ): + continue + out[i] = out[i].as_strided(out[i].shape, strides) + return out + + # To be called post compile + def set_fwd_output_strides( + self, fwd_output_strides: list[list[int] | None] + ) -> None: + self.fwd_output_strides = fwd_output_strides + + def post_compile( + self, + compiled_fn: Callable[..., Any], + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ) -> Callable[..., Any]: + if self.needs_post_compile: + if self.fwd_output_strides is None: + raise AssertionError( + "fwd_output_strides must not be None when needs_post_compile is True" + ) + fakified_out = self._compute_output_meta_with_inductor_strides() + + @wraps(compiled_fn) + def wrapper(runtime_args: list[Any]) -> Any: + nonlocal fakified_out + if fakified_out is not None: + out = fakified_out + fakified_out = None + return out + return compiled_fn(runtime_args) + + return wrapper + # If we don't need to fakify, we can just return the original compiled function + return compiled_fn + + +# This wrapper handles the AOTDispatch runtime logic for tensor subclasses. +# At runtime, we have a compiled function that knows how to operate on the domain of DenseTensor -> DenseTensor, +# But the user might have passed us some tensor subclass inputs (or expect some subclass tensor outputs). +# This function handles the wrapping and unwrapping of tensor subclasses at runtime. +@dataclass +class AOTDispatchSubclassWrapper(CompilerWrapper): + trace_joint: bool + fw_only: Callable[..., Any] | None # Not cached, only used in pre_compile + maybe_subclass_meta: SubclassMeta | None + num_fw_outs_saved_for_bw: int | None + + def pre_compile( + self, + flat_fn: TraceFn, + flat_args: list[FxValue], + flat_args_descs: list[AOTInput], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, + ) -> tuple[TraceFn, list[FxValue], list[AOTInput], ViewAndMutationMeta]: + (new_flat_fn, new_flat_args, new_flat_args_descs, subclass_meta) = ( + aot_dispatch_subclass( + flat_fn, + flat_args, + flat_args_descs, + is_joint_structure=self.trace_joint, + meta=fw_metadata, + fw_only=self.fw_only, # type: ignore[arg-type] + ) + ) + self.maybe_subclass_meta = subclass_meta + return new_flat_fn, new_flat_args, new_flat_args_descs, fw_metadata + + @staticmethod + def _get_frozen_inp_indices() -> frozenset[int]: + # fw_compiler_freezing (compile_fx.py) bakes frozen params into the + # graph and sets their TracingContext.params_flat entries to None + # before post_compile runs. We pass these indices to codegen so it + # can emit straight-line code instead of a runtime None check. + tc = TracingContext.try_get() + if tc is None or tc.params_flat is None: + return frozenset() + return frozenset(i for i, p in enumerate(tc.params_flat) if p is None) + + def post_compile( + self, + compiled_fn: Callable[..., Any], + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ) -> Callable[..., Any]: + if self.maybe_subclass_meta is None and not runtime_metadata.act_input_paths: + return compiled_fn + + from .subclass_codegen import codegen_subclass_wrapper + + inner_fn = codegen_subclass_wrapper( + compiled_fn=compiled_fn, + inp_metas=runtime_metadata.subclass_inp_meta, + out_metas=runtime_metadata.subclass_fw_graph_out_meta, + num_fw_outs_saved_for_bw=self.num_fw_outs_saved_for_bw, + frozen_inp_indices=self._get_frozen_inp_indices(), + act_input_paths=runtime_metadata.act_input_paths, + ) + inner_fn._boxed_call = True # type: ignore[attr-defined] + return inner_fn + + +@dataclass +class EffectTokensWrapper(CompilerWrapper): + def post_compile( + self, + compiled_fn: Callable[..., Any], + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ) -> Callable[..., Any]: + num_tokens = len(runtime_metadata.tokens) + if num_tokens == 0: + return compiled_fn + + from .codegen import PySourceBuilder + + buf = PySourceBuilder( + "_effect_tokens_wrapper", + args="args", + artifact_name="effect_tokens_wrapper", + ) + buf.bind(_compiled_fn_=compiled_fn) + with buf.indent(): + buf.writeline(f"new_args = [{', '.join(['None'] * num_tokens)}, *args]") + buf.writeline("args.clear()") + buf.writeline("outs = _compiled_fn_(new_args)") + buf.writeline("if outs is None:") + with buf.indent(): + buf.writeline("return None") + buf.writeline(f"return outs[{num_tokens}:]") + + inner_fn = buf.build(wrapped_fn=compiled_fn) + inner_fn._boxed_call = True # type: ignore[attr-defined] + return inner_fn + + +# MOTIVATION: +# +# When tracing functions for future execution, one must be careful not to pass +# in the same input tensor multiple times (e.g., f(x, x), as this can result +# in graphs that are ONLY valid if you later pass a new tensor in exactly the +# same way (e.g., f(y, y)). (NB: we really mean duplicate; two distinct +# tensors that alias each other is a different situation that is covered by +# aot_dispatch_deduplicated_autograd). Here are two examples: +# +# (1) Suppose you have a function: +# +# def f(x, y): +# return x + y +# +# If you make_fx(f)(x, x), you will trace out: +# +# def f(x, y): +# return y + y +# +# Oops! +# +# (2) For most tensors x and y, you can compute f's gradient with respect to +# these to inputs by saying torch.autograd.grad(f(x, y), (x, y)). However, +# if x is y, you will trace out a program that gets incorrect gradients: +# +# >>> x = torch.randn(1, requires_grad=True) +# >>> torch.autograd.grad(x + x, (x, x)) +# (tensor([2.]), tensor([2.])) +# +# In other words, the gradient is double-counted. Deduplicating the arguments +# gives you an appropriate gradient: +# +# >>> y = torch.randn(1, requires_grad=True) +# >>> torch.autograd.grad(x + y, (x, y)) +# (tensor([1.]), tensor([1.])) +# +# HOW TO DEDUPLICATE: +# +# There are a few strategies, in order of preference: +# +# 1. For every duplicate argument to the function, detach it into +# a separate leaf tensor, so that it is no longer duplicated. +# +# PRO: The resulting compiled graph works for any configuration +# of duplicated arguments. +# +# CON: It does not (naively) work if you mutate the metadata of inputs: +# +# def f(x, y): +# x.transpose_(0, 1) +# y.transpose_(0, 2) +# +# x = torch.randn(2, 3, 4) +# f(x, x) +# +# The ordering of the transposes inside f dictates whether or not +# you get [4, 2, 3] or [3, 4, 2]. This means that you cannot precompute +# what metadata mutations should get applied to each input; you need to +# assume they aren't duplicates (what we do today) or preserve +# the original metadata mutations exactly in order, so that they work +# for any duplicate configuration. +# +# CON: It does not (naively) work if you mutate the data of inputs. +# In particular, leaf tensors that require grad cannot be mutated, +# this makes it impossible to differentiate with respect to the original +# base. +# +# 2. For every duplicate argument to the function, remove it, so it is +# no longer part of the "true" signature: +# +# PRO: Implemented naively, it still works for metadata/data mutation. +# +# CON: The resulting compiled graph is duplicate-specialized: it only +# works if future calls duplicate arguments in exactly the same way. +# Horribly, Dynamo doesn't guard on this at the moment. But even if +# it did, you could still end up recompiling a bunch of each duplicate. +# +# Our strategy is to do (1) if we can, and do (2) otherwise, erroring if +# Dynamo's guards are not enough. In practice, this seems to cover +# everything. +# +@dataclass +class AOTDedupeWrapper(CompilerWrapper): + keep_arg_mask: list[bool] = field(default_factory=list) + add_dupe_map: list[int] = field(default_factory=list) + old_input_metadata: list[InputAliasInfo] = field(default_factory=list) + needs_post_compile: bool = True + + # NB: Hot path, avoid set lookups here + # TODO: Can avoid the zip here too, probably + def remove_dupe_args(self, args: list[Any]) -> list[Any]: + return [t for t, keep in zip(args, self.keep_arg_mask) if keep] + + def add_dupe_args(self, args: list[Any]) -> list[Any]: + return [args[i] for i in self.add_dupe_map] + + def pre_compile( + self, + flat_fn: TraceFn, + flat_args: list[FxValue], + flat_args_descs: list[AOTInput], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, + ) -> tuple[TraceFn, list[FxValue], list[AOTInput], ViewAndMutationMeta]: + # Use information about whether or not flat_fn mutates its arguments + # or not to handle dupe args + + # Strategy 1: For any input that is not mutated, we can leafify it if we + # need to remove a duplicate. + leaf_flat_args: list[FxValue] = [] + leaf_flat_args_descs: list[AOTInput] = [] + args_set = set() + ok = True + + for i, (a, a_desc) in enumerate(zip(flat_args, flat_args_descs)): + if not isinstance(a, torch.Tensor): + leaf_flat_args.append(a) + leaf_flat_args_descs.append(a_desc) + elif a not in args_set: + args_set.add(a) + leaf_flat_args.append(a) + leaf_flat_args_descs.append(a_desc) + elif ( + not fw_metadata.input_info[i].mutates_data + and not fw_metadata.input_info[i].mutates_metadata + ): + leaf_flat_args.append(a.detach().requires_grad_(a.requires_grad)) + leaf_flat_args_descs.append(a_desc) + else: + ok = False + break + + if ok: + self.needs_post_compile = False + return flat_fn, leaf_flat_args, leaf_flat_args_descs, fw_metadata + + if requires_subclass_dispatch(leaf_flat_args, fw_metadata): # type: ignore[arg-type] + raise RuntimeError( + """\ + Encountered duplicate inputs that are mutated in the graph, but at least one input/output + to the graph is a tensor subclass. This is not supported today. You can try to + remove the aliasing yourself as a workaround, or otherwise file an issue on github.""" + ) + + # export path: ban duplicate inputs for now, add later if requested. + if aot_config.is_export: + raise RuntimeError( + f"""\ + Encountered duplicated inputs that are mutated in the graph you are trying to export. + This functionality is currently not supported. If needed, please file a github issue. + + fw_metadata={str(fw_metadata)} + """ + ) + + # Strategy 2: Duplicate specialization + # + # When we have duplicate arguments in a function call, we need to handle them specially. + # For example, if we have a function call f(a, b, a, c), we need to: + # + # 1. Remove duplicates to get a deduplicated list [a, b, c] + # 2. Compile our function to work with this deduplicated list + # 3. At runtime, convert incoming arguments with duplicates to the deduplicated form + # 4. Pass the deduplicated arguments to our compiled function + # + # To do this, we need two helper functions: + # + # - remove_dupe_args: Converts [a, b, a, c] -> [a, b, c] + # - add_dupe_args: Converts [a, b, c] -> [a, b, a, c] + # + # For our example [a, b, a, c], we track: + # + # - seen_args = {a: 0, b: 1, c: 2} (maps each unique arg to its first position) + # - add_dupe_map = [0, 1, 0, 2] (tells us how to reconstruct the original list) + # - keep_arg_mask = [True, True, False, True] (tells us which args to keep when deduplicating) + + seen_args: dict[Tensor, int] = {} + # Implicitly map duped arg position (list index) to de-duped arg position + keep_arg_mask: list[bool] = [] + add_dupe_map: list[int] = [] + duped_arg_len = len(flat_args) + + j = 0 # index into deduped_flat_args + for t in flat_args: + if isinstance(t, torch.Tensor): + if t in seen_args: + keep_arg_mask.append(False) + add_dupe_map.append(seen_args[t]) + continue + seen_args[t] = j + + keep_arg_mask.append(True) + add_dupe_map.append(j) + j += 1 + if len(add_dupe_map) != duped_arg_len: + raise AssertionError( + f"Expects add_dupe_map to have length {duped_arg_len} but got {len(add_dupe_map)}" + ) + + self.keep_arg_mask = keep_arg_mask + self.add_dupe_map = add_dupe_map + + deduped_flat_args = self.remove_dupe_args(flat_args) + # TODO: instead of arbitrarily removing args, it might be useful to + # have a record that these were duped, perhaps as a mutable attribute + # on the kept arg? Do this if someone needs it + deduped_flat_args_descs = self.remove_dupe_args(flat_args_descs) + + # Update our input metadata to remove duped input metadata. + updated_fw_metadata = remove_dupe_metadata( + fw_metadata, keep_arg_mask, add_dupe_map + ) + + if ( + tracing_context := TracingContext.try_get() + and aot_config.aot_autograd_arg_pos_to_source + ): + # TODO(voz): This structure is 1:1, we could consider an alternate structure like + # kept_pos:[dupe_arg_pos], however, add_dupe_map is 1:1 so we would need a new structure there, + # which feels like needless complexity for a tiny bit of efficiency at this point. + for dupe_arg_pos, (kept_pos, keep_arg) in enumerate( + zip(add_dupe_map, keep_arg_mask) + ): + if not keep_arg: + dupe_arg_source = aot_config.aot_autograd_arg_pos_to_source[ + dupe_arg_pos + ] + kept_arg_source = aot_config.aot_autograd_arg_pos_to_source[ + kept_pos + ] + tracing_context.guards_context.aotautograd_guards.append( # type: ignore[attr-defined] + DuplicateInputs(kept_arg_source, dupe_arg_source) + ) + + @simple_wraps(flat_fn) + def wrapped_flat_fn( + *args: FxValue, + ) -> tuple[list[FxValue], list[AOTOutput]]: + outs, out_descs = call_and_expect_output_descs( + flat_fn, + self.add_dupe_args(args), # type: ignore[arg-type] + ) + return outs, out_descs + + if config.debug_assert: + ref_fw_metadata = run_functionalized_fw_and_collect_metadata( + without_output_descs(wrapped_flat_fn), + flat_args_descs=deduped_flat_args_descs, + static_input_indices=aot_config.static_input_indices, + keep_input_mutations=fw_metadata.keep_input_mutations, + )(*deduped_flat_args) + if ref_fw_metadata != updated_fw_metadata: + raise AssertionError( + f"ref_metadata={str(ref_fw_metadata)}, actual_metadata={str(updated_fw_metadata)}" + ) + + return ( + wrapped_flat_fn, + deduped_flat_args, + deduped_flat_args_descs, + updated_fw_metadata, + ) + + def post_compile( + self, + compiled_fn: Callable[..., Any], + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ) -> Callable[..., Any]: + if not self.needs_post_compile: + return compiled_fn + + keep_indices = [i for i, keep in enumerate(self.keep_arg_mask) if keep] + idx_list = ", ".join(f"args[{i}]" for i in keep_indices) + from .codegen import PySourceBuilder + + buf = PySourceBuilder("inner_fn", args="args", artifact_name="dedup_wrapper") + buf.bind(compiled_fn=compiled_fn) + with buf.indent(): + buf.writeline(f"deduped_args = [{idx_list}]") + buf.writeline("args.clear()") + buf.writeline("return compiled_fn(deduped_args)") + + wrapped_compiled_fn: Callable[..., Any] = buf.build( # type: ignore[assignment] + wrapped_fn=compiled_fn + ) + + wrapped_compiled_fn._boxed_call = True # type: ignore[attr-defined] + + # This can be uncommented when we properly guard for duplicates, + # but right now we must not do it. + # if not config.debug_assert: + # return wrapped_compiled_fn + + @wraps(wrapped_compiled_fn) + def debugged_compiled_fn(args: list[Any]) -> Any: + # Test that the computed remove/add arg functions are an inverse + new_args = self.add_dupe_args(self.remove_dupe_args(args)) + seen: dict[Any, None] = {} + for i, (x, y) in enumerate(zip(new_args, args)): + seen[y] = None + if x is not y: + raise AssertionError( + format_guard_bug_msg( + aot_config, + f"{describe_input(i, aot_config)} would be a duplicate of " + f"{describe_input(self.add_dupe_map[i], aot_config)}", + ) + ) + # This is only an error if there is metadata mutation on both of + # the duped arguments; in this case, we need to know what order + # the metadata mutation applies in. You'll get the correct result + # otherwise, because a graph that assumes distinct inputs works if + # you dupe the inputs (the gradient contributions from each input + # will get summed up appropriately.) + # + # TODO: work out how to setup this assert correctly + """ + assert len(seen) == unique_args, format_guard_bug_msg(aot_config, + f"there would be {unique_args} distinct arguments" + ) + """ + return wrapped_compiled_fn(args) + + debugged_compiled_fn._boxed_call = True # type: ignore[attr-defined] + + return debugged_compiled_fn + + +# This layer handles the situation where you have two inputs that alias each other, +# and one of the inputs is mutated. +# We need to take special care to ensure that the mutation is applied to the other aliases in the graph. +# +# pre-condition: AOTDedupWrapper has already run. +# (This function will in theory work if there are duplicate args. +# However, the synthetic base code path is a bit sub-optimal, and running with dupe'd inputs +# would cause us to hit that path more frequently). +@dataclass +class AOTSyntheticBaseWrapper(CompilerWrapper): + # Currently, the only reason we need to plumb this bool is because + # the synthetic base code prohibits more cases in the autograd case than the inference case. + trace_joint: bool # TODO: refactor trace_joint + needs_post_compile: bool = True + aliased_arg_idx_with_metadata_mutations: list[int] = field(default_factory=list) + base_groups: dict[int, list[int]] = field( + default_factory=lambda: collections.defaultdict(list) + ) + other_arg_indices: list[int] = field(default_factory=list) + + def pre_compile( + self, + flat_fn: TraceFn, + flat_args: list[FxValue], + flat_args_descs: list[AOTInput], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, + ) -> tuple[Callable[..., Any], list[FxValue], list[AOTInput], ViewAndMutationMeta]: + is_inference = not self.trace_joint + ( + flat_args_with_synthetic_bases, + flat_args_descs_with_synthetic_bases, + synthetic_base_info, + ) = merge_view_inputs( + aot_config, + flat_args, + flat_args_descs, + fw_metadata.input_info, + is_inference=is_inference, + ) + + # Happy path: we don't need synthetic bases + if synthetic_base_info is None: + self.needs_post_compile = False + return flat_fn, flat_args, flat_args_descs, fw_metadata + + # export path: ban synthetic bases for now, add later if requested. + if requires_subclass_dispatch(flat_args, fw_metadata): # type: ignore[arg-type] + raise RuntimeError( + """\ + Encountered aliased inputs that are mutated in the graph, but at least one input/output + to the graph is a tensor subclass. This is not supported today. You can try to + remove the aliasing yourself as a workaround, or otherwise file an issue on github.""" + ) + + if aot_config.is_export: + raise RuntimeError( + f"""\ + Encountered aliased inputs that are mutated in the graph you are trying to export. + This functionality is currently not supported. If needed, please file a github issue. + + synthetic_base_info={str(synthetic_base_info)} + + fw_metadata={str(fw_metadata)} + """ + ) + + if len(fw_metadata.input_info) != len(synthetic_base_info): + raise AssertionError( + f"expected len(fw_metadata.input_info) == len(synthetic_base_info), " + f"got {len(fw_metadata.input_info)} != {len(synthetic_base_info)}" + ) + + # Update our forward metadata to take synthetic bases into account + ( + fw_metadata_updated, + aliased_arg_idx_with_metadata_mutations, + ) = create_synthetic_base_metadata( + fw_metadata, + synthetic_base_info, + flat_args, + flat_args_with_synthetic_bases, + flat_args_descs_with_synthetic_bases, + ) + # Pre-compute base_groups and other_arg_map from + # synthetic_base_info so the post_compile codegen can emit a + # wrapper without calling merge_view_inputs at runtime. + # + # other_arg_entries collects (new_idx, orig_idx) pairs so we can + # sort by new_idx -- the position in the post-merge calling + # convention (bases ++ others). merge_view_inputs puts + # non-tensor args before non-aliased tensor args, so iterating + # by orig_idx alone would produce a wrong order when non-tensors + # are interleaved with tensors. + other_arg_entries: list[tuple[int, int]] = [] + for orig_idx, entry in enumerate(synthetic_base_info): + if isinstance(entry, int): + other_arg_entries.append((entry, orig_idx)) + else: + base_idx, _ = entry + self.base_groups[base_idx].append(orig_idx) + other_arg_entries.sort() + self.other_arg_indices = [orig_idx for _, orig_idx in other_arg_entries] + + self.aliased_arg_idx_with_metadata_mutations = ( + aliased_arg_idx_with_metadata_mutations + ) + replay_views = config.view_replay_for_aliased_outputs + + def _unpack_synthetic_bases(primals: tuple[Any, ...]) -> list[Any]: + f_args_inner = [] + # pyrefly: ignore [not-iterable] + for inner_idx_or_tuple in synthetic_base_info: + if isinstance(inner_idx_or_tuple, int): + f_args_inner.append(primals[inner_idx_or_tuple]) + else: + inner_base_idx, view_tensor = inner_idx_or_tuple + base = primals[inner_base_idx] + view_arg = gen_alias_from_base( + base, + view_tensor, + view_tensor.requires_grad, + replay_views=replay_views, + ) + f_args_inner.append(view_arg) + return f_args_inner + + @simple_wraps(flat_fn) + def wrapped_flat_fn(*args: Any) -> Any: + unpacked_args = _unpack_synthetic_bases(args) + # This is a bit subtle. The goal of this entire function (aot_dispatch_synthetic_bases) + # is to relieve the downstream logic from having to reason about mutations on inputs that alias + # each other, by replacing aliased inputs with a synthetic base. + # One area where this breaks down a bit however is if one of those aliased inputs + # experienced a metadata mutation. + # We are now obligated to reapply the metadata mutation directly to the user's input; + # it isn't enough to apply mutations back to the synthetic base in the downstream logic. + # + # The way we handle this is by pretending that those aliased inputs that experience metadata mutations + # are additional outputs in the user's forward function. + # The downstream logic will just treat these as "user outputs that alias inputs". + # However, we will manually grab them at runtime here, use them to reapply the metadata mutation + # to the user inputs, and not return them to the user. + aliased_args_with_metadata_mutations = [ + x + for i, x in enumerate(unpacked_args) + if i in self.aliased_arg_idx_with_metadata_mutations + ] + out, out_descs = call_and_expect_output_descs(flat_fn, unpacked_args) # type: ignore[arg-type] + if len(aliased_args_with_metadata_mutations) > 0: + # TODO: record more detailed desc information here + return (*out, *aliased_args_with_metadata_mutations), ( + *out_descs, + *( + [ + MetadataMutationAOTOutput(i) + for i in range( + len(self.aliased_arg_idx_with_metadata_mutations) + ) + ] + ), + ) + else: + return out, out_descs + + if config.debug_assert: + ref_fw_metadata = run_functionalized_fw_and_collect_metadata( + without_output_descs(wrapped_flat_fn), + flat_args_descs=flat_args_descs_with_synthetic_bases, + static_input_indices=aot_config.static_input_indices, + keep_input_mutations=fw_metadata.keep_input_mutations, + )(*flat_args_with_synthetic_bases) + if ref_fw_metadata != fw_metadata_updated: + raise AssertionError( + f"ref_metadata={pprint.pformat(partial_flatten_asdict(ref_fw_metadata))}, " + f"\nactual_metadata={pprint.pformat(partial_flatten_asdict(fw_metadata_updated))}" + ) + return ( + wrapped_flat_fn, + flat_args_with_synthetic_bases, + flat_args_descs_with_synthetic_bases, + fw_metadata_updated, + ) + + def post_compile( + self, + compiled_fn: Callable[..., Any], + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ) -> Callable[..., Any]: + if not self.needs_post_compile: + return compiled_fn + + from .codegen import PySourceBuilder + + base_groups = self.base_groups + other_indices = self.other_arg_indices + + num_bases = len(base_groups) + aliased_meta_mut_indices = self.aliased_arg_idx_with_metadata_mutations + num_meta_mut = len(aliased_meta_mut_indices) + + buf = PySourceBuilder( + "_synthetic_base_wrapper", + args="args", + artifact_name="synthetic_base_wrapper", + ) + buf.bind(torch=torch, _compiled_fn_=compiled_fn) + + with buf.indent(): + buf.writeline(f"_bases = [None] * {num_bases}") + for base_idx in sorted(base_groups): + group = base_groups[base_idx] + first_orig = group[0] + if len(group) == 1: + indices_check = f"args[{first_orig}]._base is not None" + base_expr = f"args[{first_orig}]._base" + else: + indices_str = ", ".join(str(i) for i in group) + indices_check = ( + f"any(args[_i]._base is not None for _i in [{indices_str}])" + ) + base_expr = f"next(args[_i]._base for _i in [{indices_str}] if args[_i]._base is not None)" + buf.writeline(f"if {indices_check}:") + with buf.indent(): + buf.writeline(f"_bases[{base_idx}] = {base_expr}") + buf.writeline("else:") + with buf.indent(): + buf.writeline( + f"_b = torch.empty((0,), dtype=args[{first_orig}].dtype, device=args[{first_orig}].device)" + ) + buf.writeline(f"_b.set_(args[{first_orig}].untyped_storage())") + buf.writeline(f"_bases[{base_idx}] = _b") + + other_items = ", ".join(f"args[{orig}]" for orig in other_indices) + buf.writeline(f"_new_args = _bases + [{other_items}]") + + if num_meta_mut > 0: + meta_items = ", ".join(f"args[{i}]" for i in aliased_meta_mut_indices) + buf.writeline(f"_meta_mut = [{meta_items}]") + + buf.writeline("args.clear()") + buf.writeline("_outs = _compiled_fn_(_new_args)") + + if num_meta_mut > 0: + # Handles metadata mutations on inputs that were merged into + # synthetic bases (create_synthetic_base_metadata hides these + # from the normal tracking by forcing mutates_metadata=False + # on the base). Metadata mutations on non-aliased inputs are + # handled separately by _apply_input_mutations in the runtime + # epilogue. + buf.writeline(f"_mut_inps = _outs[-{num_meta_mut}:]") + buf.writeline(f"_user_outs = _outs[:-{num_meta_mut}]") + buf.writeline("for _inp, _mi in zip(_meta_mut, _mut_inps):") + with buf.indent(): + buf.writeline( + "_inp.as_strided_(_mi.size(), _mi.stride(), _mi.storage_offset())" + ) + buf.writeline("return _user_outs") + else: + buf.writeline("return _outs") + + inner_fn = buf.build(wrapped_fn=compiled_fn) + inner_fn._boxed_call = True # type: ignore[attr-defined] + return inner_fn + + +# Note [Handling mutations on an input that aliases other inputs] +# The easiest example to show-case this edge case is here: +# +# def f(a, b): +# a.mul_(2) +# out = a + b +# return out +# b = torch.ones(...) +# a = b.view(-1) +# f(a, b) +# +# In this situation, if a and b happened to be aliased, we need to trace something different! +# Suppose we had b = a.view(-1) +# (In this case, that means that `a._base is b`) +# +# We need to ensure that the aliasing relationship between a and b is preserved. +# We do that detecting the specific situation above (mutate an input that aliases another input), +# and when we do that, we create a synthetic base argument. Then inside of the traced forward, +# we regenerate a and b off of that base. +# The complete example of the transformed function looks like this: +# +# // The traced forward takes in a synthetic base, and regenerates the aliased inputs as views +# // We could consider getting view-replay support here to minimize as_strided_scatter ops in the graph +# def traced_forward(base): +# a = base.as_strided(...) +# b = base.as_strided(...) +# a_updated = a.mul(2) +# base_updated = torch.as_strided_scatter(base, a_updated, ...) +# b_updated = base_updated.as_strided(...) +# out = a_updated + b_updated +# return a_updated, out +# +# def compiled_fn(a, b): +# // we detect that a is the "differentiable base" here +# base = a +# // In other situations, we might do either: +# // (1) a and b are both views off of some larger differentiable base +# // assert a._base is b._base and a._base is not None +# // base = a._base +# // (2) a and b both don't require gradients. Create a base from the storage +# // assert a._base is None and b._base is None +# // base = torch.Tensor(a.storage()) +# a_updated, out = traced_forward(base) +# a.copy_(a_updated) +# return out +# +# This function: +# (1) Merges input views into a synthetic base argument, when any of those input views are mutated +# (2) Returns metadata telling the autograd.Function how to modify their arguments properly, +# to respect the new calling convention. +# +# The calling convention is as follows. +# Any inputs that were originally views of one another get yanked, and replaced with a synthetic base. +# The argument list ordering goes [base1, ..., baseN], [arg1, ..., argN], +# Where the ordering of the bases is determined from the ordering of the original view args. +# baseA will come before baseB if the earliest original argument coming from baseA +# showed up earlier in the argument list than the earliest original argument coming from baseB. +# +# Example, given some tensors a, b, c, d +# call site: +# f(a, c.view(-1), b.view(-1), b, c, d) +# Modified argument list: +# c_base comes first because the first c view came earlier in arg list than the first b view +# a and d still show up in the modified arg list, but b and c don't- they're regenerated from their bases +# b_base = torch.Tensor(b.storage()) +# c_base = torch.Tensor(c.storage()) +# f(c_base, b_base, a, d) +def merge_view_inputs( + aot_config: AOTConfig, + fwd_inputs: list[Any], + # This is None when called at runtime from post_compile closure + fwd_inputs_descs: list[AOTInput] | None, + mutated_input_info: list[InputAliasInfo], + *, + # The autograd case currently has more restrictions than the inference case. + is_inference: bool, +) -> tuple[list[Any], list[AOTInput], list[int | tuple[int, torch.Tensor]] | None]: + if fwd_inputs_descs is None: + fwd_inputs_descs = [DummyAOTInput(i) for i in range(len(fwd_inputs))] + + def _are_differentiable_views(view1: torch.Tensor, view2: torch.Tensor) -> bool: + if view1 is view2: + return True + if view1._base is None and view2._base is None: + return False + if view1._base is view2._base or view1._base is view2 or view1 is view2._base: + return True + return False + + def _same_dtype_views(view1: torch.Tensor, view2: torch.Tensor) -> bool: + if view1.dtype != view2.dtype: + return False + if view1._base is not None and view1.dtype != view1._base.dtype: + return False + if view2._base is not None and view2.dtype != view2._base.dtype: + return False + return True + + def _format_input(idx: int) -> str: + if ( + aot_config.aot_autograd_arg_pos_to_source is not None + and idx < len(aot_config.aot_autograd_arg_pos_to_source) + and aot_config.aot_autograd_arg_pos_to_source[idx] is not None + ): + source = aot_config.aot_autograd_arg_pos_to_source[idx] + name = getattr(source, "local_name", source.name) + else: + name = fwd_inputs_descs[idx].expr() + return f"input {idx} ({name})" + + if len(fwd_inputs) != len(mutated_input_info): + raise AssertionError( + f"expected len(fwd_inputs) == len(mutated_input_info), " + f"got {len(fwd_inputs)} != {len(mutated_input_info)}" + ) + if not [info for info in mutated_input_info if info.mutates_data]: + # Return early when there are no mutations. + return fwd_inputs, fwd_inputs_descs, None + + storage_ref_to_idx: dict[StorageWeakRef, list[int]] = collections.defaultdict(list) + # pyrefly: ignore [implicit-any] + base_args = [] + # pyrefly: ignore [implicit-any] + other_args = [] + base_args_descs = [] + other_args_descs = [] + for i, (inpt, source) in enumerate(zip(fwd_inputs, fwd_inputs_descs)): + if isinstance(inpt, Tensor): + storage_ref = StorageWeakRef(inpt.untyped_storage()) + storage_ref_to_idx[storage_ref].append(i) + else: + other_args.append(inpt) + other_args_descs.append(source) + # Note [Synthetic Base Info Metadata] + # This list contains metadata that tells you what the i'th argument in the inner calling convention should be. + # It's either: + # - another int (corresponding to the index in the argument list of the element from the outer calling convention) + # - idx, view_tensor, where we can generate the new output with view_tensor._view_func(old_args[idx]) + # idx corresponds to which synthetic base from the outer calling context to view + inner_calling_convention_meta: dict[int, int | tuple[int, torch.Tensor]] = {} + for aliased_input_indices in storage_ref_to_idx.values(): + if len(aliased_input_indices) <= 1 or not any( + # We only care about mutations that affect all aliases, + # so metadata mutations on an input doesn't require us to do synthetic base handling. + mutated_input_info[inpt_idx].mutates_data + for inpt_idx in aliased_input_indices + ): + other_args.extend( + fwd_inputs[curr_idx] for curr_idx in aliased_input_indices + ) + other_args_descs.extend( + fwd_inputs_descs[curr_idx] for curr_idx in aliased_input_indices + ) + continue + + # Here, we attempt to do a more complicated check to detect false aliasing + # (e.g. if all the tensors have the same storage, but don't actually overlap) + # In theory, we could have a large group of tensors that all share storages, where only *some* of them + # have overlapping memory. + # I don't bother with that case for now: here, we only bail out earlier if we detect that **every** pair + # of tensors in the current group that shares a storage is non-overlapping. + aliased_input_indices_no_false_sharing = compute_overlapping_inputs( + aot_config, fwd_inputs, aliased_input_indices + ) + if len(aliased_input_indices_no_false_sharing) <= 1: + other_args.extend( + fwd_inputs[curr_idx] for curr_idx in aliased_input_indices + ) + other_args_descs.extend( + fwd_inputs_descs[curr_idx] for curr_idx in aliased_input_indices + ) + continue + + # We detected an input that was mutated, AND aliases with another input. + # we need to replace this set of aliased inputs with a single synthetic base. + # For now, I'm banning a bunch of cases. We expect dynamo to properly detect these cases + # and error out. We can fix them later. + # These checks are transitive, so we don't need to check every pair. + for idx1, idx2 in zip( + aliased_input_indices, aliased_input_indices[1:], strict=False + ): + view1 = fwd_inputs[idx1] + view2 = fwd_inputs[idx2] + # The "inputs that are aliased but have different differentiable bases" case + # is more complicated and hopefully pretty rare. Not currently handled. + if not is_inference: + if not _are_differentiable_views(view1, view2): + raise AssertionError( + f"aot_autograd() does not yet handle non-differentiable view input mutations. " + f"{_format_input(idx1)} and {_format_input(idx2)} share storage but are " + f"not differentiable views of each other." + ) + # Regenerating views when reinterpreting complex / real tensors seems non-trivial, + # not handling for now + if not _same_dtype_views(view1, view2): + raise AssertionError( + "aot_autograd() does not yet handle input mutations on views with different dtypes." + ) + non_none_bases = [ + (i, fwd_inputs[i]._base) + for i in aliased_input_indices + if fwd_inputs[i]._base is not None + ] + aliases_with_none_bases = [ + fwd_inputs[i] for i in aliased_input_indices if fwd_inputs[i]._base is None + ] + synthetic_base_desc: AOTInput + if len(non_none_bases) == 0: + # Case where none of the aliases have a ._base + # we generate a synthetic base without gradients, and generate views off of it + # We hit this case when we have input tensors to the graph that share a storage, + # but do not have a ._base field. + # Wondering when we hit this case? + # The _base field simply says that autograd knows about the aliasing relationship, + # but sometimes we create tensors which are aliased out of the same storage but guaranteed + # to be disjoint. In these cases, we will skip setting up the _base relationship + # for performance reasons (because the fact that the tensors share the same storage + # is unobservable unless you (1) do naughty things with resize_/as_strided + # or (2) look at the storage--as we are doing here.) + # One particular example of this is optimizer steps on the LSTM module: + # LSTM parameters are packed into a contiguous storage for efficiency reasons when + # calling cuDNN kernels, so when these parameters get passed to the optimizer we will + # find they share the same storage, but do not have _base set since they are all disjoint. + # + # NOTE: There is one case where this is unsafe: + # torch.Tensor(storage) will ALWAYS create a 1D tensor, which is not necessarily + # the same shape as the "actual" base that the tensor came from. + # For the most part this is fine, because we always use as_strided() + # to generate the original aliased inputs again. + # If we were to use view-replay though, this could cause the aliased views + # to have incorrect sizes. + example_idx = aliased_input_indices[0] + example_alias = fwd_inputs[example_idx] + # Note that this function is reused at both trace time and runtime. + # At trace time, we're under a FakeMode so synthetic_base becomes a FakeTensor. + synthetic_base = torch.empty( + (0,), dtype=example_alias.dtype, device=example_alias.device + ) + # We don't actually have a convenient way of going from storage -> tensor, + # So using set_() here (we suffer some minor overhead, but this case is rare). + synthetic_base.set_(example_alias.untyped_storage()) + synthetic_base_desc = SyntheticBaseAOTInput(fwd_inputs_descs[example_idx]) + else: + # Case where all of the aliases require gradients, and have the same _base. + i, synthetic_base = non_none_bases[0] + synthetic_base_desc = ViewBaseAOTInput(fwd_inputs_descs[i]) + for j, other_base in non_none_bases[1:]: + if other_base is not synthetic_base: + raise AssertionError( + f"aot_autograd() does not yet handle non-differentiable view input mutations. " + f"Aliased inputs share storage but have different autograd ._base tensors: " + f"{_format_input(i)} and {_format_input(j)} have ._base fields that point to different tensors." + ) + for alias in aliases_with_none_bases: + if alias is not synthetic_base: + none_base_indices = [ + _format_input(k) + for k in aliased_input_indices + if fwd_inputs[k]._base is None + ] + has_base_indices = [ + _format_input(k) + for k in aliased_input_indices + if fwd_inputs[k]._base is not None + ] + raise AssertionError( + f"aot_autograd() does not yet handle non-differentiable view input mutations. " + f"Aliased inputs share storage but have mixed autograd ._base states: " + f"{has_base_indices} have ._base set, while " + f"{none_base_indices} have ._base=None (and are not the synthetic base)." + ) + base_args.append(synthetic_base) + base_args_descs.append(synthetic_base_desc) + for curr_view_idx in aliased_input_indices: + curr_view = fwd_inputs[curr_view_idx] + base_idx = len(base_args) - 1 + # We store just enough info here so that we can regenerate the view later. + # Regeneration: curr_view._view_func(args[base_idx]) + inner_calling_convention_meta[curr_view_idx] = (base_idx, curr_view) + if len(base_args) == 0: + if len(other_args) != len(fwd_inputs): + raise AssertionError( + f"expected len(other_args) == len(fwd_inputs), " + f"got {len(other_args)} != {len(fwd_inputs)}" + ) + # If no synthetic bases are necessary, just return the original inputs. + return fwd_inputs, fwd_inputs_descs, None + else: + from torch.fx.experimental.symbolic_shapes import SymIntEqByExpr + + def make_hashable(arg: Any) -> Any: + if isinstance(arg, torch.SymInt): + # Since only nested SymInt objects can be hashed, we wrap them with + # SymIntEqByExpr, which is a hashable wrapper of SymInts. + return SymIntEqByExpr(arg) + return arg + + # Otherwise, return: + # (1) The new args according to the updated calling convention: (synthetic_bases, other_args) + # (2) Metadata telling functionalization how to generate the inner argument list given the outer calling convention. + # We post-process it into a list, where meta[i] tells you info about the i'th argument in the inner calling convention. + args_to_functionalization = base_args + other_args + args_to_functionalization_descs = base_args_descs + other_args_descs + + # Map each argument into its old index. + # There may be some repeated arguments, so we collect their indices in a list. + arg_to_old_idx_map = collections.defaultdict(list) + for i, arg in enumerate(fwd_inputs): + arg_to_old_idx_map[make_hashable(arg)].append(i) + # Reverse the list of each argument, so that we can easily pop them one-after-the-other in order. + for hashable_arg in arg_to_old_idx_map: + arg_to_old_idx_map[hashable_arg] = list( + reversed(arg_to_old_idx_map[hashable_arg]) + ) + + for i, other_arg in enumerate(other_args): + new_idx = len(base_args) + i + old_idx = arg_to_old_idx_map[make_hashable(other_arg)].pop() + inner_calling_convention_meta[old_idx] = new_idx + + # post process into a list + post_processed_calling_convention_meta: list[int | tuple[int, torch.Tensor]] = [ + -1 for _ in range(len(inner_calling_convention_meta)) + ] + for k, v in inner_calling_convention_meta.items(): + post_processed_calling_convention_meta[k] = v + # Quick assert: every argument in the inner calling convention should be accounted for. + for x in post_processed_calling_convention_meta: + if x == -1: + raise AssertionError( + "every argument in the inner calling convention should be accounted for" + ) + # pyrefly: ignore [bad-return] + return ( + args_to_functionalization, + args_to_functionalization_descs, + post_processed_calling_convention_meta, + ) + + +# Note: [Backward graph lazy lowering] +# After AOTDispatch traces the backward for graphs requiring autograd, we will lower the graph lazily, +# unless we suspect that inductor might specialize and insert additional guards. When we do lazy +# lowering, we stash the AOT backward graph (bw_module) in this class. +# +# Lowering passes are performed on a deepcopy of this bw_module due to compatibility +# with compiled autograd. See: https://github.com/pytorch/pytorch/pull/149229#discussion_r2002122645. +@dataclass +class AutogradLazyBackwardCompileInfo: + bw_module: Callable[..., Any] + placeholder_list: list[Any] + saved_context: TracingContext | None + saved_compile_context: CompileContext | None + + +# On an AOT Autograd cache hit, we already have a lowered backward, so there is usually +# no need to keep information around for a new lazy compilation. Except for compiled autograd, +# which wants to retrace this backward into a larger graph, and it needs the graph module to do so. +@dataclass +class CachedAutogradLazyBackwardCompileInfo: + bw_module_fn: Callable[..., Any] + + +def initialize_rng_states( + num_rng: int, + graphsafe_idx: int, + fwd_rng_states: list[torch.Generator], + bwd_rng_states: list[torch.Generator], + *, + device: torch.device, +) -> None: + """ + Initialize the graphsafe rng states. + + Initialization of rng states should have a few properties: + - the initialization for each rng state should be independent + - the initialization should be deterministic + - the initialization should be based off current rng state, so that independent graphs do not + have equal rng behavior + + We defer initialization of rng states until runtime because compilation is wrapped + with preserve_rng_states. Seed initialization should advance the rng states so consecutive compilations + do not give equal randomness. + """ + from .utils import get_default_generator + + with torch.utils._python_dispatch._disable_current_modes(): + seeds = torch.randint(0, torch.iinfo(torch.int64).max, (num_rng,), device="cpu") + generator = get_default_generator(device) + fwd_rng_states.extend( + [generator.clone_state().manual_seed(int(seeds[i])) for i in range(num_rng)] + ) + bwd_rng_states.extend( + [generator.clone_state().manual_seed(int(seeds[i])) for i in range(num_rng)] + ) + + +def coerce_to_expected_memory_format( + x: torch.Tensor, memory_format: MemoryFormatMeta +) -> torch.Tensor: + if memory_format.memory_format is not None: + # Coerce to torch.memory_format + if not x.is_contiguous(memory_format=memory_format.memory_format): + x = x.contiguous(memory_format=memory_format.memory_format) + return x + + expected_size = memory_format.size + if expected_size is None: + raise AssertionError("memory_format.size must not be None") + expected_stride = memory_format.stride + if expected_stride is None: + raise AssertionError("memory_format.stride must not be None") + # Expected size and stride are static ints + # ok to use == to compare runtime tensor strides and shapes + + if x.shape == expected_size and x.stride() == expected_stride: + # Runtime tangent size and stride are the same as expected, no need to coerce + return x + + # Empty_strided creates a raw Tensor. + # We are guaranteed that only raw Tensors has expected size and stride. + # Subclasses have only expected memory_format. + restrided = torch.empty_strided( + size=expected_size, + stride=expected_stride, + dtype=x.dtype, + device=x.device, + layout=x.layout, + requires_grad=x.requires_grad, + ) + restrided.copy_(x) + return restrided + + +@contextlib.contextmanager +def _disable_saved_tensors_hooks() -> Generator[None, None, None]: + error_message = ( + "Saved tensors hooks were specialized as GraphModules." + "In this case aot_autograd inlines them in forward and backward graph " + "and disables them during runtime of aot_autograd compiled region." + "If you see this error, that means that there is some unexpected push or pop manipulation " + "during aot_autograd compiled region runtime." + "Compilation with different hooks must result in recompilation." + ) + fail_if_non_empty = False + maybe_prev_message = None + try: + maybe_prev_message = ( + torch._C._autograd._saved_tensors_hooks_get_disabled_error_message() + ) + torch._C._autograd._saved_tensors_hooks_disable( + error_message, fail_if_non_empty + ) + yield + finally: + if maybe_prev_message is None: + torch._C._autograd._saved_tensors_hooks_enable() + else: + torch._C._autograd._saved_tensors_hooks_disable( + maybe_prev_message, fail_if_non_empty + ) + + +@dataclass +class SerializableCompiledFunction: + """ + Represents a result of AOTDispatch after calling the inner compiler + that can be serialized + """ + + compiled_fn: Callable[..., Any] + serialize_fn: Callable[[], Any] + + def __init__( + self, compiled_fn: Callable[..., Any], serialize_fn: Callable[[], Any] + ) -> None: + self.compiled_fn = compiled_fn + self.serialize_fn = serialize_fn + # Equivalent to functools.wraps + functools.update_wrapper( + self, + compiled_fn, + assigned=("__doc__", "__annotations__", "__type_params__"), + ) + + def serialize(self) -> Any: + return self.serialize_fn() + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + return self.compiled_fn(*args, **kwargs) + + +@dataclass +class AOTDispatchAutogradCompileSpec: + compiled_fw_func: Callable[..., Any] + compiled_bw_func: Callable[..., Any] | None + maybe_subclass_meta: SubclassMeta | None + num_symints_saved_for_bw: int + backward_state_indices: list[int] + disable_amp: bool + indices_of_inps_to_detach: list[int] + lazy_backward_info: ( + AutogradLazyBackwardCompileInfo | CachedAutogradLazyBackwardCompileInfo | None + ) + bw_compiler: Callable[..., Any] | None + aot_config: AOTConfig + fw_metadata: ViewAndMutationMeta + try_save_cache_entry: Callable[..., Any] | None + + +@dataclass +class _AutogradSavedState: + metadata: ViewAndMutationMeta + + def save_from_forward(self, ctx: Any, fw_outs: Sequence[Any]) -> None: + tensors_saved_with_vc_check = fw_outs[ + self.metadata.tensors_saved_for_backwards_with_vc_check_slice + ] + tensors_saved_no_vc_check = fw_outs[ + self.metadata.tensors_saved_for_backwards_no_vc_check_slice + ] + if not all(isinstance(x, torch.Tensor) for x in tensors_saved_with_vc_check): + raise AssertionError( + "expected all tensors_saved_with_vc_check to be Tensors, " + f"got types: {[type(x) for x in tensors_saved_with_vc_check]}" + ) + if not all(isinstance(x, torch.Tensor) for x in tensors_saved_no_vc_check): + raise AssertionError( + "expected all tensors_saved_no_vc_check to be Tensors, " + f"got types: {[type(x) for x in tensors_saved_no_vc_check]}" + ) + + # See Note [Detaching saved tensors in AOTAutograd] + num_vc_check = len(tensors_saved_with_vc_check) + is_graph_input = self.metadata.saved_tensor_is_graph_input + tensors_to_save = [ + x if is_graph_input[i] or not x._is_view() else x.detach() + for i, x in enumerate(tensors_saved_with_vc_check) + ] + tensors_no_vc_check = [ + x if is_graph_input[num_vc_check + i] or not x._is_view() else x.detach() + for i, x in enumerate(tensors_saved_no_vc_check) + ] + + # dynamic_saved_tensors_idxs has indices relative to all saved tensors + # (vc_check + no_vc_check combined). Mark dynamics on the detached tensors. + for idx, dims in self.metadata.dynamic_saved_tensors_idxs.items(): + if idx < num_vc_check: + mark_dynamo_propagated_dynamic_indices(tensors_to_save[idx], dims) + else: + mark_dynamo_propagated_dynamic_indices( + tensors_no_vc_check[idx - num_vc_check], dims + ) + + ctx.save_for_backward(*tensors_to_save) + ctx._tensors_no_vc_check = tensors_no_vc_check + + symint_outs = fw_outs[self.metadata.symints_saved_for_backwards_slice] + if not all( + isinstance(x, (int, float, torch.SymInt, torch.SymFloat)) + for x in symint_outs + ): + raise AssertionError( + "expected all symint_outs to be int/float/SymInt/SymFloat, " + f"got types: {[type(x) for x in symint_outs]}" + ) + ctx.symints = symint_outs + + opaque_object_outs = fw_outs[ + self.metadata.opaque_objects_saved_for_backwards_slice + ] + if not all( + is_custom_class(type(obj)) or isinstance(obj, CustomClassBase) + for obj in opaque_object_outs + ): + raise AssertionError( + "expected all opaque_object_outs to be opaque types, " + f"got types: {[type(obj) for obj in opaque_object_outs]}" + ) + ctx.opaque_objects = opaque_object_outs + + +@dataclass +class _AutogradForwardEpilogue: + metadata: ViewAndMutationMeta + + def finalize(self, ctx: Any, fw_outs: Sequence[Any]) -> tuple[Any, ...]: + num_outputs = self.metadata.num_outputs + num_outputs_aliased = self.metadata.num_outputs_aliased + num_mutated_runtime_inps = self.metadata.num_mutated_inp_runtime_indices + num_forward_returns = self.metadata.num_forward_returns + + raw_returns = list(fw_outs[:num_forward_returns]) + + # Wrap all autograd.Function.forward() outputs that are aliases + # so that autograd.Function doesn't treat them as tensors + if num_mutated_runtime_inps > 0: + for i, idx in enumerate(self.metadata.mutated_inp_runtime_indices): + # We could make this faster by only looping over inputs with metadata-only mutations + # (instead of looping over inputs with either data or metadata mutations), but there shouldn't be many. + info = self.metadata.input_info[idx] + if info.mutates_metadata and not info.mutates_data: + raw_returns[i] = TensorAlias(raw_returns[i]) + + if config.debug_assert: + user_mutated_inputs_raw = raw_returns[0:num_mutated_runtime_inps] + mut_inp_infos = [ + x + for x in self.metadata.input_info + if x.mutates_data or x.mutates_metadata + ] + if len(user_mutated_inputs_raw) != len(mut_inp_infos): + raise AssertionError( + "expected len(user_mutated_inputs_raw) == len(mut_inp_infos), " + f"got {len(user_mutated_inputs_raw)} != {len(mut_inp_infos)}" + ) + + if self.metadata.num_unsafe_view_outputs > 0: + for idx in self.metadata.unsafe_view_out_indices: + raw_return_idx = num_mutated_runtime_inps + idx + o = raw_returns[raw_return_idx] + raw_returns[raw_return_idx] = torch.ops.aten._unsafe_view(o, o.shape) + + if num_outputs_aliased > 0: + for idx in self.metadata.aliased_out_indices: + raw_return_idx = num_mutated_runtime_inps + idx + raw_returns[raw_return_idx] = TensorAlias(raw_returns[raw_return_idx]) + + if config.debug_assert: + intermediates_raw = raw_returns[ + num_mutated_runtime_inps + num_outputs : + ] + if any(isinstance(x, TensorAlias) for x in intermediates_raw): + raise AssertionError("expected no TensorAlias in intermediates_raw") + + # invariant: intermediate bases always require gradients, so we don't have to + # consider marking them as non-differentiable. + raw_returns_not_including_intermediate_bases = raw_returns[ + : num_mutated_runtime_inps + num_outputs + ] + raw_returns_meta = [ + x + for x in self.metadata.input_info + if x.mutation_type == MutationType.MUTATED_OUT_GRAPH + ] + self.metadata.output_info + + fw_outs_not_requiring_grad = [ + x + for (i, x) in enumerate(raw_returns_not_including_intermediate_bases) + if isinstance(x, torch.Tensor) and not raw_returns_meta[i].requires_grad + ] + ctx.mark_non_differentiable(*fw_outs_not_requiring_grad) + ctx._materialize_non_diff_grads = False + _snapshot_external_objects(ctx) + + return tuple(raw_returns) + + +@dataclass +class _AutogradRngStateTracker: + num_rng: int + graphsafe_idx: int | None + device: torch.device | None = None + fwd_rng_states: list[torch.Generator] = field(default_factory=list) + bwd_rng_states: list[torch.Generator] = field(default_factory=list) + curr_fwd_iter: Any = field(default_factory=lambda: itertools.count(0)) + backward_state_position: int = 0 + pending_forwards: set[int] = field(default_factory=set) + saved_backward_tensor_states: dict[int, list[torch.Tensor]] = field( + default_factory=dict + ) + + def add_forward_args(self, ctx: Any, args: tuple[Any, ...]) -> tuple[Any, ...]: + if self.num_rng == 0: + return args + + if len(self.fwd_rng_states) == 0: + if self.graphsafe_idx is None: + raise AssertionError("graphsafe_idx must not be None when num_rng > 0") + if self.device is None: + raise AssertionError("device must not be None when num_rng > 0") + initialize_rng_states( + self.num_rng, + self.graphsafe_idx, + self.fwd_rng_states, + self.bwd_rng_states, + device=self.device, + ) + + curr_iter = next(self.curr_fwd_iter) + ctx._curr_iter = curr_iter + + # if this state is not contained in the backward, + # we need to save it for when its backward pass happens + if curr_iter != self.backward_state_position: + self.saved_backward_tensor_states[curr_iter] = [ + rng_state.get_state() for rng_state in self.fwd_rng_states + ] + + self.pending_forwards.add(curr_iter) + return (*args, *self.fwd_rng_states) + + def add_backward_args(self, ctx: Any, all_args: list[Any]) -> None: + if self.num_rng == 0: + return + + curr_backward_iter = ctx._curr_iter + retain_graph = torch._C._autograd._get_current_graph_task_keep_graph() + + # Save current state if we have a pending forward that needs this state + # or this state may be needed again because of retain graph + if ( + self.backward_state_position in self.pending_forwards + and self.backward_state_position not in self.saved_backward_tensor_states + and (self.backward_state_position != curr_backward_iter or retain_graph) + ): + self.saved_backward_tensor_states[self.backward_state_position] = [ + rng_state.get_state() for rng_state in self.bwd_rng_states + ] + + # Restore saved states if needed + if curr_backward_iter in self.saved_backward_tensor_states: + if self.backward_state_position != curr_backward_iter: + for bwd_state, saved_state in zip( + self.bwd_rng_states, + self.saved_backward_tensor_states[curr_backward_iter], + ): + bwd_state.set_state(saved_state) + if not retain_graph: + del self.saved_backward_tensor_states[curr_backward_iter] + else: + if self.backward_state_position != curr_backward_iter: + raise AssertionError( + "expected backward_state_position == curr_backward_iter, " + f"got {self.backward_state_position} != {curr_backward_iter}" + ) + + self.backward_state_position = curr_backward_iter + 1 + if not retain_graph: + self.pending_forwards.remove(curr_backward_iter) + all_args.extend(self.bwd_rng_states) + + +@dataclass +class _AutogradBackwardCompiler: + compiled_bw: Callable[..., Any] | None + lazy_backward_info: ( + AutogradLazyBackwardCompileInfo | CachedAutogradLazyBackwardCompileInfo | None + ) + disable_amp: bool + bw_compiler: Callable[..., Any] | None + aot_config: AOTConfig + fw_metadata: ViewAndMutationMeta + try_save_cache_entry: Callable[..., Any] | None + + def get_or_compile(self, *, saved_tensors_use_once: bool) -> Callable[..., Any]: + if self.compiled_bw is not None: + return self.compiled_bw + + if self.lazy_backward_info is None: + raise AssertionError("lazy_backward_info must not be None") + if not isinstance(self.lazy_backward_info, AutogradLazyBackwardCompileInfo): + raise AssertionError( + "expected AutogradLazyBackwardCompileInfo, " + f"got {type(self.lazy_backward_info)}" + ) + + self._prepare_lazy_backward_context(saved_tensors_use_once) + + bw_module = self.lazy_backward_info.bw_module + placeholder_list = self.lazy_backward_info.placeholder_list + saved_context = self.lazy_backward_info.saved_context + saved_compile_context = self.lazy_backward_info.saved_compile_context + + context = torch._C._DisableAutocast if self.disable_amp else nullcontext + metrics_context = get_metrics_context() + with ( + tracing(saved_context), + compile_context(saved_compile_context), + context(), + track_graph_compiling(self.aot_config, "backward"), + metrics_context, + dynamo_timed( + "backward._backward_impl", + phase_name="entire_backward_compile", + log_pt2_compile_event=True, + dynamo_compile_column_us="backward_cumulative_compile_time_us", + log_waitcounter=True, + waitcounter_name_override="entire_backward_compile", + ), + callback_handler.install_callbacks( + CallbackTrigger.LAZY_BACKWARD, + str(CompileContext.current_compile_id()), + ), + ): + CompileEventLogger.compilation_metric(is_forward=False) + # See Note: [Backward graph lazy lowering] + if self.bw_compiler is None: + raise AssertionError("bw_compiler must not be None") + self.compiled_bw = self.bw_compiler( + copy.deepcopy(bw_module), placeholder_list + ) + # Maybe save cache entry + if self.try_save_cache_entry is not None: + self.try_save_cache_entry( + self.compiled_bw, + bw_module, + self.fw_metadata, + self.aot_config, + ) + + return self.compiled_bw + + def _prepare_lazy_backward_context(self, saved_tensors_use_once: bool) -> None: + if self.lazy_backward_info is None: + raise AssertionError("lazy_backward_info must not be None") + if not isinstance(self.lazy_backward_info, AutogradLazyBackwardCompileInfo): + raise AssertionError( + "expected AutogradLazyBackwardCompileInfo, " + f"got {type(self.lazy_backward_info)}" + ) + + if ( + hasattr(self.lazy_backward_info, "saved_context") + and self.lazy_backward_info.saved_context is not None + ): + if not isinstance(self.lazy_backward_info.saved_context, TracingContext): + raise AssertionError( + f"expected TracingContext, got {type(self.lazy_backward_info.saved_context)}" + ) + ddp_ctx = self.lazy_backward_info.saved_context.ddp_optimizer_ctx + if ddp_ctx is not None: + if ddp_ctx.curr_bucket < 0: + raise AssertionError( + "expected same # of fw and bw compiles, " + f"but found bucket {ddp_ctx.curr_bucket}" + ) + curr_fw_meta = ddp_ctx.metadata_per_bucket[ddp_ctx.curr_bucket] + # Note [DDPOptimizer and fw_metadata] + # When using the DDPOptimizer, we have a single dynamo graph (and TracingContext), + # but multiple AOTDispatcher graph. + # + # One consequence is that there will be **multiple** fw_metadata objects, one per AOT graph, + # which we stash the fw_metadata on the TracingContext. + # + # Normally what happens is that as we compile AOT graphs 1...N, we clobber the fw_metadata + # for graph i-1 when we start running AOT for graph i. + # Ordinarily this is fine, because inductor no longer needs the metadata from graph i-1. + # + # However, this is a problem for lazy compilation of the backward. During backward compilation, + # we compile the backward lazily at backward runtime, meaning that we will first compile + # backward graph N, N-1, ..., 1. + # We need to ensure that at the time inductor compiles bw graph N-1, it can access + # the corresponding fw_metadata for graph N-1. + # + # We do this by stashing a DDPOptimizerContext, which tracks: + # - the metadata of all N graphs + # - the graph we are currently compiling in our DDPOptimizer region. + ddp_ctx.curr_bucket -= 1 + self.lazy_backward_info.saved_context.fw_metadata = curr_fw_meta + + if not saved_tensors_use_once: + self.fw_metadata.bw_donated_idxs = [] + # Update bw_donated_idxs if using lazy_backward_info from `aot_dispatch_autograd` + if ( + hasattr(self.lazy_backward_info, "saved_context") + and hasattr(self.lazy_backward_info.saved_context, "fw_metadata") + and hasattr( + self.lazy_backward_info.saved_context.fw_metadata, # type: ignore[union-attr] + "bw_donated_idxs", + ) + ): + self.lazy_backward_info.saved_context.fw_metadata.bw_donated_idxs = ( # type: ignore[union-attr] + # pyrefly: ignore [implicit-any] + [] + ) + + +def _codegen_backward_prologue( + fw_metadata: ViewAndMutationMeta, + maybe_subclass_meta: SubclassMeta | None, + codegen_unwrap_fn: Callable[..., Any] | None, +) -> Callable[..., Any]: + from .codegen import PySourceBuilder + + num_mutated_runtime_inps = fw_metadata.num_mutated_inp_runtime_indices + num_outputs = fw_metadata.num_outputs + num_intermediate_bases = fw_metadata.num_intermediate_bases + expected_grad_outs = num_outputs + num_mutated_runtime_inps + num_intermediate_bases + deterministic = fw_metadata.deterministic + num_backward_tokens = fw_metadata.num_backward_tokens + is_rng_op_functionalized = fw_metadata.is_rng_op_functionalized + has_subclass = maybe_subclass_meta is not None + has_mutations_in_bw = bool( + fw_metadata.indices_of_inputs_that_requires_grad_with_mutations_in_bw + ) + input_info = fw_metadata.input_info + + inp_surviving: list[int] = [] + for i, info_idx in enumerate(fw_metadata.mutated_inp_runtime_indices): + if input_info[info_idx].mutates_data and input_info[info_idx].requires_grad: + inp_surviving.append(i) + + out_surviving: list[int] = [] + for i, info in enumerate(fw_metadata.output_info): + if ( + info.output_type + in [ + OutputType.non_alias, + OutputType.unsafe_view_alias, + OutputType.custom_function_view, + ] + and issubclass(info.raw_type, torch.Tensor) + and info.requires_grad_for_backward + ): + out_surviving.append(num_mutated_runtime_inps + i) + + intermediate_start = num_mutated_runtime_inps + num_outputs + all_surviving = ( + inp_surviving + + out_surviving + + list(range(intermediate_start, expected_grad_outs)) + ) + num_flat_bw_args_with_grads = len(all_surviving) + + buf = PySourceBuilder( + "_backward_prologue", + args="ctx_saved_tensors, ctx_symints, ctx_opaque_objects, flat_args", + artifact_name="backward_prologue", + ) + buf.bind(torch=torch) + + with buf.indent(): + buf.writeline("stack = torch._C._functorch.peek_interpreter_stack()") + buf.writeline( + "torch._check(stack is None, lambda: (" + "\"It looks like you're trying to call a compiled backward " + 'function within vmap/grad/vjp, "' + " \"which isn't supported. Try wrapping vmap inside " + 'torch.compile, or skip compiling the "' + ' "backward function."),)' + ) + + if deterministic is not None and not deterministic: + buf.writeline("_gd = torch.are_deterministic_algorithms_enabled()") + buf.writeline( + "torch._check(not _gd, lambda: (" + "'This compiled backward function is being run with '" + " 'torch.use_deterministic_algorithms(True), '" + " 'but it was previously generated during the forward function" + " while '" + " 'torch.use_deterministic_algorithms(False) was set.'))" + ) + + buf.writeline(f"if len(flat_args) != {expected_grad_outs}:") + with buf.indent(): + buf.writeline( + f"raise AssertionError(" + f"f'expected {expected_grad_outs} grad_outs, " + f"got {{len(flat_args)}}')" + ) + + if all_surviving: + items = ", ".join(f"flat_args[{i}]" for i in all_surviving) + buf.writeline(f"_bw_grads = [{items}]") + else: + buf.writeline("_bw_grads = []") + + buf.writeline("if isinstance(flat_args, list):") + with buf.indent(): + buf.writeline("flat_args.clear()") + + buf.writeline("_n_saved = len(ctx_saved_tensors)") + + parts = [ + "*ctx_symints", + "*ctx_saved_tensors", + "*ctx_opaque_objects", + "*_bw_grads", + ] + if num_backward_tokens > 0: + parts.append(f"*([None] * {num_backward_tokens})") + if is_rng_op_functionalized: + buf.bind(_get_rng_state_=CUDARngStateHelper.get_torch_state_as_tuple) + parts.append("*_get_rng_state_()") + buf.writeline(f"all_args = [{', '.join(parts)}]") + buf.writeline("del ctx_saved_tensors") + + buf.writeline("_ts = len(ctx_symints) + _n_saved + len(ctx_opaque_objects)") + buf.writeline(f"_te = _ts + {num_flat_bw_args_with_grads}") + + buf.bind( + _process_tangent_=AOTDispatchAutograd.process_runtime_tangent, + _tangent_metas_=fw_metadata.subclass_tangent_meta, + _tangent_descs_=fw_metadata.traced_tangents_descs, + _compile_id_=fw_metadata.compile_id_str, + _stack_traces_=fw_metadata.tangent_source_stack_traces or (), + ) + + if has_subclass: + buf.bind(_chain_=itertools.chain.from_iterable) + + buf.writeline("_tangents = all_args[_ts:_te]") + buf.writeline( + f"if len(_tangents) != {len(fw_metadata.subclass_tangent_meta)}:" + ) + with buf.indent(): + buf.writeline( + "raise RuntimeError(" + "'The grad inputs should be same number as forward output tangents')" + ) + buf.writeline( + "_fpt = list(_chain_(" + "_process_tangent_(t, m, idx, desc, _compile_id_, " + "_stack_traces_[idx] if _stack_traces_ else None)[1] " + "for idx, (t, m, desc) in enumerate(" + "zip(_tangents, _tangent_metas_, _tangent_descs_))))" + ) + + if codegen_unwrap_fn is not None: + buf.bind(_unwrap_=codegen_unwrap_fn) + else: + buf.bind(_unwrap_=_unwrap_no_symints) + buf.writeline( + "all_args = _unwrap_(all_args[:_ts]) + _fpt + _unwrap_(all_args[_te:])" + ) + elif num_flat_bw_args_with_grads > 0: + buf.writeline(f"for j in range({num_flat_bw_args_with_grads}):") + with buf.indent(): + buf.writeline("_i = _ts + j") + buf.writeline( + "all_args[_i] = _process_tangent_(all_args[_i], " + "_tangent_metas_[j], j, _tangent_descs_[j], _compile_id_, " + "_stack_traces_[j] if _stack_traces_ else None)[0]" + ) + + if has_mutations_in_bw: + buf.writeline("if torch.is_grad_enabled():") + with buf.indent(): + buf.writeline( + "raise RuntimeError(" + "'aot_autograd does not support input mutations with " + "requires_grad in backward for create_graph=True')" + ) + + buf.writeline("return all_args") + + return buf.build() + + +def _codegen_backward_epilogue( + fw_metadata: ViewAndMutationMeta, + maybe_subclass_meta: SubclassMeta | None, + codegen_wrap_fn: Callable[..., Any] | None, +) -> Callable[..., Any]: + from .codegen import PySourceBuilder + + num_bw_tokens = fw_metadata.num_backward_tokens + is_rng = fw_metadata.is_rng_op_functionalized + has_subclass = maybe_subclass_meta is not None + + if has_subclass: + args = "out, make_subclass_override=None" + else: + args = "out" + buf = PySourceBuilder( + "_backward_epilogue", args=args, artifact_name="backward_epilogue" + ) + + with buf.indent(): + if num_bw_tokens > 0: + buf.writeline(f"out = out[:-{num_bw_tokens}]") + + if is_rng: + if fw_metadata.num_outputs_rng_offset != 1: + raise AssertionError( + f"expected num_outputs_rng_offset == 1, got {fw_metadata.num_outputs_rng_offset}" + ) + buf.bind(_set_offset_=CUDARngStateHelper.set_new_offset) + buf.writeline("_oi = len(out) - 1") + buf.writeline("_set_offset_(out[_oi])") + buf.writeline("out = out[:_oi] + out[_oi + 1:]") + + buf.writeline("out = tuple(out)") + + if has_subclass: + buf.bind(_wrap_subclasses_=wrap_tensor_subclasses) + if ( + maybe_subclass_meta.grad_input_metas is None + ): # pyrefly: ignore [missing-attribute] + raise AssertionError("grad_input_metas must not be None") + buf.bind( + _grad_input_metas_=maybe_subclass_meta.grad_input_metas + ) # pyrefly: ignore [missing-attribute] + if codegen_wrap_fn is not None: + buf.bind(_wrap_=codegen_wrap_fn) + buf.writeline("if make_subclass_override is None:") + with buf.indent(): + buf.writeline("return _wrap_(out)") + buf.writeline( + "return _wrap_subclasses_(out, " + "subclass_metas=_grad_input_metas_, " + "included_subclass_symints=True, is_runtime=True, " + "make_subclass_override=make_subclass_override)" + ) + else: + buf.writeline("return out") + + return buf.build() + + +def _codegen_compiled_forward( + fw_metadata: ViewAndMutationMeta, + backward_state_indices: list[int], + disable_amp: bool, + num_rng: int, +) -> Callable[..., Any]: + from .codegen import PySourceBuilder + + buf = PySourceBuilder( + "_compiled_forward", + args="ctx, args, _rng_add_, _save_, _finalize_, _compiled_fw_", + artifact_name="compiled_function_forward", + ) + buf.bind(torch=torch, BackwardState=BackwardState) + + with buf.indent(): + if backward_state_indices: + idx = backward_state_indices[0] + buf.writeline(f"_bw_state = args[{idx}]") + buf.writeline("if not isinstance(_bw_state, BackwardState):") + with buf.indent(): + buf.writeline( + "raise AssertionError(" + "f'expected BackwardState, got {type(_bw_state)}')" + ) + buf.writeline("ctx._compiled_autograd_backward_state = _bw_state") + + if num_rng > 0: + buf.writeline("args = _rng_add_(ctx, args)") + + if disable_amp: + buf.bind(_DisableAutocast_=torch._C._DisableAutocast) + buf.writeline("with _DisableAutocast_():") + with buf.indent(): + buf.writeline("fw_outs = _compiled_fw_(list(args))") + _codegen_normalize_as_list(buf, "fw_outs", indent_level=2) + else: + buf.writeline("fw_outs = _compiled_fw_(list(args))") + _codegen_normalize_as_list(buf, "fw_outs", indent_level=1) + + buf.writeline("_save_(ctx, fw_outs)") + buf.writeline("return _finalize_(ctx, fw_outs)") + + return buf.build() + + +def _codegen_compiled_backward( + num_rng: int, + num_tensors_no_vc_check: int | None, + inputs_require_grad: bool, +) -> Callable[..., Any]: + from .codegen import PySourceBuilder + + buf = PySourceBuilder( + "_compiled_backward", + args="_flat_args_, _ctx_, _prologue_," + " _rng_add_, _impl_, _epilogue_, _double_bw_", + artifact_name="compiled_function_backward", + ) + buf.bind(torch=torch, functools=functools) + + with buf.indent(): + buf.writeline( + "if len(_flat_args_) != 1 or not isinstance(_flat_args_[0], list):" + ) + with buf.indent(): + buf.writeline( + "raise AssertionError(" + "'Compiled backward expects grads as a single mutable list '" + " f'argument, but got {len(_flat_args_)} args. '" + " 'Grads must be passed as [grad0, grad1, ...] to allow '" + " 'freeing individual grads mid-backward.')" + ) + buf.writeline("grad_args = _flat_args_[0]") + buf.writeline("del _flat_args_") + + if num_tensors_no_vc_check is not None and num_tensors_no_vc_check > 0: + buf.writeline( + "_saved = (*_ctx_.saved_tensors, *_ctx_._tensors_no_vc_check)" + ) + else: + buf.writeline("_saved = _ctx_.saved_tensors") + + buf.writeline( + "all_args = _prologue_(_saved, _ctx_.symints," + " _ctx_.opaque_objects, grad_args)" + ) + buf.writeline("del _saved") + + if num_rng > 0: + buf.writeline("_rng_add_(_ctx_, all_args)") + + buf.writeline("def impl_fn(double_ctx=None):") + with buf.indent(): + buf.writeline("out = _impl_(_ctx_, all_args)") + buf.writeline("return _epilogue_(out)") + + buf.writeline( + "if (torch._C._is_key_in_tls('context')" + " and (_cc := torch._C._get_obj_in_tls('context')) is not None):" + ) + with buf.indent(): + buf.writeline("impl_fn = functools.partial(_cc.copy().run, impl_fn)") + + if inputs_require_grad: + buf.writeline("if torch.is_grad_enabled():") + else: + buf.writeline( + "_ng = torch.is_grad_enabled() and any(" + "t.requires_grad for t in all_args if isinstance(t, torch.Tensor))" + ) + buf.writeline("if _ng:") + with buf.indent(): + buf.writeline("return _double_bw_(_ctx_, impl_fn, all_args)") + buf.writeline("return impl_fn()") + + return buf.build() + + +@dataclass +class _AOTDispatchAutogradFunctionFactory: + spec: AOTDispatchAutogradCompileSpec + + def build(self) -> type[torch.autograd.Function]: + compile_id = CompileContext.current_compile_id() + compile_id_str = str(compile_id) if compile_id is not None else None + self.spec.fw_metadata.compile_id_str = compile_id_str + + saved_state = _AutogradSavedState(self.spec.fw_metadata) + forward_epilogue = _AutogradForwardEpilogue(self.spec.fw_metadata) + rng_state = _AutogradRngStateTracker( + num_rng=self.spec.fw_metadata.num_graphsafe_rng_states, + graphsafe_idx=self.spec.fw_metadata.graphsafe_rng_state_index, + device=self.spec.fw_metadata.graphsafe_rng_device, + ) + backward_compiler = _AutogradBackwardCompiler( + compiled_bw=self.spec.compiled_bw_func, + lazy_backward_info=self.spec.lazy_backward_info, + disable_amp=self.spec.disable_amp, + bw_compiler=self.spec.bw_compiler, + aot_config=self.spec.aot_config, + fw_metadata=self.spec.fw_metadata, + try_save_cache_entry=self.spec.try_save_cache_entry, + ) + + compiled_fw_func = self.spec.compiled_fw_func + compiled_bw_func = self.spec.compiled_bw_func + maybe_subclass_meta = self.spec.maybe_subclass_meta + num_symints_saved_for_bw_ = self.spec.num_symints_saved_for_bw + backward_state_indices = self.spec.backward_state_indices + disable_amp = self.spec.disable_amp + lazy_backward_info = self.spec.lazy_backward_info + aot_config = self.spec.aot_config + fw_metadata = self.spec.fw_metadata + + _codegen_bw_unwrap_fn = None + _codegen_bw_wrap_fn = None + if maybe_subclass_meta is not None: + from .subclass_codegen import codegen_backward_subclass_fns + + _codegen_bw_unwrap_fn, _codegen_bw_wrap_fn = codegen_backward_subclass_fns( + grad_input_metas=maybe_subclass_meta.grad_input_metas, + ) + + _codegen_bw_prologue = _codegen_backward_prologue( + fw_metadata, + maybe_subclass_meta, + _codegen_bw_unwrap_fn, + ) + + _codegen_bw_epilogue = _codegen_backward_epilogue( + fw_metadata, + maybe_subclass_meta, + _codegen_bw_wrap_fn, + ) + + _codegen_fwd = _codegen_compiled_forward( + fw_metadata, + backward_state_indices, + disable_amp, + rng_state.num_rng, + ) + + _codegen_bwd = _codegen_compiled_backward( + rng_state.num_rng, + fw_metadata.num_tensors_saved_with_no_vc_check, + any(inp.requires_grad for inp in fw_metadata.input_info), + ) + + # Codegen for CompiledFunction.forward: emit straight-line TensorAlias + # wrapping, _unsafe_view, and non-differentiable output collection with + # all indices resolved at compile time. + num_mutated_runtime_inps = fw_metadata.num_mutated_inp_runtime_indices + num_outputs = fw_metadata.num_outputs + num_outputs_aliased = fw_metadata.num_outputs_aliased + + from .codegen import PySourceBuilder + + buf = PySourceBuilder( + "_transform_raw_returns", + args="raw_returns", + artifact_name="compiled_fn_wrapper", + ) + buf.bind(TensorAlias=TensorAlias, torch=torch, Tensor=Tensor) + + with buf.indent(): + for i, idx in enumerate(fw_metadata.mutated_inp_runtime_indices): + info = fw_metadata.input_info[idx] + if info.mutates_metadata and not info.mutates_data: + buf.writeline(f"raw_returns[{i}] = TensorAlias(raw_returns[{i}])") + + if fw_metadata.num_unsafe_view_outputs > 0: + for idx in fw_metadata.unsafe_view_out_indices: + ri = num_mutated_runtime_inps + idx + buf.writeline(f"_o = raw_returns[{ri}]") + buf.writeline( + f"raw_returns[{ri}] = torch.ops.aten._unsafe_view(_o, _o.shape)" + ) + + if num_outputs_aliased > 0: + for idx in fw_metadata.aliased_out_indices: + ri = num_mutated_runtime_inps + idx + buf.writeline(f"raw_returns[{ri}] = TensorAlias(raw_returns[{ri}])") + + # Non-differentiable output collection: build a list of specific indices + # at compile time rather than iterating at runtime. + _non_diff_indices: list[int] = [] + _returns_meta = [ + x + for x in fw_metadata.input_info + if x.mutation_type == MutationType.MUTATED_OUT_GRAPH + ] + list(fw_metadata.output_info) + for i, meta in enumerate(_returns_meta): + if ( + i < num_mutated_runtime_inps + num_outputs + and not meta.requires_grad + ): + _non_diff_indices.append(i) + if _non_diff_indices: + checks = " + ".join( + f"([raw_returns[{i}]] if isinstance(raw_returns[{i}], Tensor) else [])" + for i in _non_diff_indices + ) + buf.writeline(f"non_diff = {checks}") + else: + buf.writeline("non_diff = []") + buf.writeline("return non_diff") + + _codegen_transform_raw_returns: Callable[..., list[Any]] = buf.build() # type: ignore[assignment] + + # Monkey-patch forward_epilogue.finalize to use codegen'd transform + def _codegen_finalize(ctx: Any, fw_outs: Any) -> tuple[Any, ...]: + num_forward_returns = fw_metadata.num_forward_returns + raw_returns = list(fw_outs[:num_forward_returns]) + fw_outs_not_requiring_grad = _codegen_transform_raw_returns(raw_returns) + if config.debug_assert: + if num_mutated_runtime_inps > 0: + user_mutated_inputs_raw = raw_returns[0:num_mutated_runtime_inps] + mut_inp_infos = [ + x + for x in fw_metadata.input_info + if x.mutates_data or x.mutates_metadata + ] + if len(user_mutated_inputs_raw) != len(mut_inp_infos): + raise AssertionError( + f"expected len(user_mutated_inputs_raw) == len(mut_inp_infos), " + f"got {len(user_mutated_inputs_raw)} != {len(mut_inp_infos)}" + ) + if num_outputs_aliased > 0: + intermediates_raw = raw_returns[ + num_mutated_runtime_inps + num_outputs : + ] + if any(isinstance(x, TensorAlias) for x in intermediates_raw): + raise AssertionError( + "expected no TensorAlias in intermediates_raw" + ) + ctx.mark_non_differentiable(*fw_outs_not_requiring_grad) + ctx._materialize_non_diff_grads = False + _snapshot_external_objects(ctx) + + return tuple(raw_returns) + + forward_epilogue.finalize = _codegen_finalize # type: ignore[method-assign] + + class CompiledFunction(torch.autograd.Function): + compiled_fw = compiled_fw_func + compiled_bw = compiled_bw_func + metadata: ViewAndMutationMeta = fw_metadata # type: ignore[assignment] + maybe_subclass_metadata: SubclassMeta | None = maybe_subclass_meta + num_symints_saved_for_bw = num_symints_saved_for_bw_ + _aot_id = aot_config.aot_id + _lazy_backward_info = lazy_backward_info + _bw_prologue_fn = _codegen_bw_prologue + _bw_epilogue_fn = _codegen_bw_epilogue + _fwd_fn = _codegen_fwd + _bwd_fn = _codegen_bwd + boxed_grads_call = True + + @staticmethod + def _compiled_autograd_key(ctx: Any) -> tuple[Any, ...]: + return (ctx._autograd_function_id, *ctx.symints) + + @staticmethod + # pyrefly: ignore [bad-override] + def forward(ctx: Any, *deduped_flat_tensor_args: Any) -> Any: + return CompiledFunction._fwd_fn( + ctx, + deduped_flat_tensor_args, + rng_state.add_forward_args, + saved_state.save_from_forward, + forward_epilogue.finalize, + CompiledFunction.compiled_fw, + ) + + @staticmethod + def backward(ctx: Any, *flat_args: Any) -> tuple[Any, ...]: + return CompiledFunction._bwd_fn( + flat_args, + ctx, + CompiledFunction._bw_prologue_fn, + rng_state.add_backward_args, + CompiledFunction._backward_impl, + CompiledFunction._bw_epilogue_fn, + CompiledFunction._double_backward, + ) + + @staticmethod + def _double_backward( + ctx: Any, impl_fn: Callable[..., Any], all_args: list[Any] + ) -> Any: + # Ensure that the graph is connected, and error if double backward is performed. + # See comment for why once_differentiable is not sufficient: + # https://github.com/pytorch/pytorch/pull/92348/files#r1072962107 + class CompiledFunctionBackward(torch.autograd.Function): + # CompiledFunctionBackward is not yet supported in dynamo skipfiles + _aot_id = aot_config.aot_id + + @staticmethod + # pyrefly: ignore [bad-override] + def forward(double_ctx: Any, *unused_args: Any) -> Any: + return impl_fn(double_ctx) + + @staticmethod + def backward(ctx: Any, *args: Any) -> None: + raise RuntimeError( + "torch.compile with aot_autograd does not currently support double backward" + ) + + CompiledFunctionBackward._compiled_autograd_key = ( # type: ignore[method-assign] + CompiledFunction._compiled_autograd_key + ) + + # Saved tensors are detached (forward runs under no-grad), so no + # real arg requires grad. Prepend a dummy requires_grad=True + # input so CompiledFunctionBackward.apply attaches a grad_fn and + # gradient outputs report requires_grad=True for create_graph=True. + if not any( + t.requires_grad for t in all_args if isinstance(t, torch.Tensor) + ): + all_args = [torch.empty(0, requires_grad=True)] + all_args + return CompiledFunctionBackward.apply(*all_args) + + @staticmethod + def _backward_impl(ctx: Any, all_args: list[Any]) -> Any: + # compiled autograd reimplements this function at proxy_call_aot_backward + if backward_state_indices: + raise AssertionError("BackwardState requires CompiledAutograd") + ctx.maybe_clear_saved_tensors() + + saved_tensors_use_once = ( + not torch._C._autograd._get_current_graph_task_keep_graph() + ) + compiled_bw = backward_compiler.get_or_compile( + saved_tensors_use_once=saved_tensors_use_once + ) + CompiledFunction.compiled_bw = compiled_bw + + if ( + torch._functorch.config.donated_buffer + and not saved_tensors_use_once + and fw_metadata.bw_donated_idxs != [] + ): + torch._check( + False, + lambda: ( + "This backward function was compiled with non-empty donated " + "buffers which requires create_graph=False and retain_graph=False. " + "Please keep backward(create_graph=False, retain_graph=False) " + "across all backward() function calls, or set " + "torch._functorch.config.donated_buffer=False to disable " + "donated buffer." + ), + ) + + for idx, obj in getattr(ctx, "_external_objects", {}).items(): + index_to_external_object_weakref[idx] = weakref.ref(obj) + + return call_func_at_runtime_with_args( + compiled_bw, + all_args, + steal_args=True, + disable_amp=disable_amp, + ) + + return CompiledFunction + + +# This is wrapped in a class just for namespacing purposes +# No need to make it into an actual CompilerWrapper because it doesn't fit the abstract as cleanly +class AOTDispatchAutograd: + @staticmethod + def _raise_tangent_metadata_error( + expected_type: type | None, + expected_meta: Any, + runtime_type: type, + runtime_meta: Any, + orig_x: torch.Tensor, + tangent_idx: int | None, + tangent_desc: Any | None, + compile_id_str: str | None, + tangent_stack_trace: str | None, + ) -> RuntimeError: + expected_subclass_got_plain_tensor = ( + expected_type is not None + and expected_type is not torch.Tensor + and runtime_type is torch.Tensor + ) + if expected_subclass_got_plain_tensor: + tangent_msg = "" + if tangent_idx is not None: + tangent_msg = f" (tangent index: {tangent_idx})" + + output_hint = "" + if tangent_desc is not None: + from .descriptors import PlainAOTOutput, TangentAOTInput + + if isinstance(tangent_desc, TangentAOTInput) and isinstance( + tangent_desc.output, PlainAOTOutput + ): + idx = tangent_desc.output.idx + output_hint = f"\n\nThe problematic output is: forward output at index {idx} (0-indexed)" + else: + output_hint = ( + f"\n\nThe problematic output is: {tangent_desc.expr()}" + ) + + graph_hint = "" + if compile_id_str is not None: + graph_hint = ( + f"\n\nThis error occurred in compiled graph [{compile_id_str}]." + ) + + stack_trace_hint = "" + if tangent_stack_trace is not None: + stack_trace_hint = ( + f"\n\nThe forward output was created here:\n{tangent_stack_trace}" + ) + + return RuntimeError( + f""" +During the backward, we encountered a tensor subclass where we guessed its +metadata incorrectly. +Expected a {expected_type.__name__} tangent but got a plain Tensor{tangent_msg}. +This happens when a compiled function returns multiple outputs that +require gradients, but .backward() is only called on some of them. +To fix: call .detach() on forward outputs you don't need gradients for.{output_hint}{graph_hint}{stack_trace_hint} + +This error is also more likely to occur if your compiled model is suffering +from a large number of graph breaks. For more advice on finding and fixing +graph breaks, see: +https://docs.pytorch.org/docs/stable/user_guide/torch_compiler/compile/programming_model.graph_breaks_index.html + +For more info about this error, see: +https://github.com/pytorch/pytorch/issues/172556""" + ) + else: + return RuntimeError( + f""" +During the backward, we encountered a tensor subclass where we guessed its +metadata incorrectly. +Expected: {expected_meta} (type {expected_type}), +got: {runtime_meta} (type {runtime_type}), shape: {orig_x.shape}. +Your tensor subclass must implement __coerce_same_metadata_as_tangent__.""" + ) + + @staticmethod + def process_runtime_tangent( + x: Any, + meta: PlainTensorMeta | SubclassCreationMeta, + tangent_idx: int | None = None, + tangent_desc: Any | None = None, + compile_id_str: str | None = None, + tangent_stack_trace: str | None = None, + ) -> tuple[Any, list[Any]]: + if not isinstance(x, torch.Tensor): + return x, [x] + + if is_fake_tensor(x): + if not meta.memory_format: + raise AssertionError( + "meta.memory_format must not be None for FakeTensor" + ) + x = coerce_to_expected_memory_format(x, meta.memory_format) + return x, [x] + + expected_type: type | None = torch.Tensor + expected_meta = None + if isinstance(meta, SubclassCreationMeta): + expected_type = meta.original_subclass_type + expected_meta = meta.meta + + runtime_type = type(x) + # When we're inside compiled autograd's AOTDispatcher step, + # regular Tensors look like FunctionalTensors. + # Tensor subclasses still look like Tensor subclasses though. + if isinstance(x, torch._subclasses.functional_tensor.FunctionalTensor): + runtime_type = torch.Tensor + + runtime_meta = None + runtime_subclass_keys: Sequence[str] = [] + + if is_traceable_wrapper_subclass(x): + runtime_subclass_keys, runtime_meta = x.__tensor_flatten__() + + def maybe_coerce(x: torch.Tensor) -> torch.Tensor | None: + same_type: bool = expected_type == runtime_type + same_meta: bool = expected_meta == runtime_meta + + if same_type and same_meta: + return x + + if not hasattr(x, "__coerce_same_metadata_as_tangent__"): + return None + + if same_type: + # Backward Compatibility, as some Subclass impls can have original 1-arg function. + return x.__coerce_same_metadata_as_tangent__(expected_meta) + + return x.__coerce_same_metadata_as_tangent__(expected_meta, expected_type) + + # Coerce to expected type and metadata + orig_x = x + x = maybe_coerce(x) + if x is None: + raise AOTDispatchAutograd._raise_tangent_metadata_error( + expected_type, + expected_meta, + runtime_type, + runtime_meta, + orig_x, + tangent_idx, + tangent_desc, + compile_id_str, + tangent_stack_trace, + ) + + # Coerce to expected memory format + if not meta.memory_format: + raise AssertionError("meta.memory_format must not be None") + x = coerce_to_expected_memory_format(x, meta.memory_format) + + if not is_traceable_wrapper_subclass(x): + return x, [x] + + if not isinstance(meta, SubclassCreationMeta): + raise AssertionError(f"expected SubclassCreationMeta, got {type(meta)}") + if orig_x is not x: + runtime_subclass_keys = x.__tensor_flatten__()[0] + + if len(meta.attrs) != len(runtime_subclass_keys): + raise AssertionError( + f"expected len(meta.attrs) == len(runtime_subclass_keys), " + f"got {len(meta.attrs)} != {len(runtime_subclass_keys)}" + ) + leaves = [] + for attr, attr_meta in meta.attrs.items(): + if isinstance(attr_meta, OpaqueMeta): + # Opaques aren't differentiable but occupy a flat arg slot. + leaves.append(getattr(x, attr)) + continue + elem = getattr(x, attr) + new_elem, elem_leaves = AOTDispatchAutograd.process_runtime_tangent( + elem, attr_meta + ) + if new_elem is not elem: + setattr(x, attr, new_elem) + leaves.extend(elem_leaves) + + return x, leaves + + @staticmethod + def post_compile(spec: AOTDispatchAutogradCompileSpec) -> Callable[..., Any]: + compiled_function_cls = _AOTDispatchAutogradFunctionFactory(spec).build() + return RuntimeWrapper( + indices_of_inps_to_detach=spec.indices_of_inps_to_detach, + trace_joint=True, + disable_amp=spec.disable_amp, + ).post_compile( + compiled_function_cls.apply, + spec.aot_config, + runtime_metadata=spec.fw_metadata, + ) + + +@dataclass +class DebugAssertWrapper(CompilerWrapper): + flat_requires_grad: list[bool | None] = field(default_factory=list) + + def post_compile( + self, + compiled_fn: Callable[..., Any], + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ) -> Callable[..., Any]: + from .codegen import PySourceBuilder + + buf = PySourceBuilder( + "inner_fn", args="args", artifact_name="debug_assert_wrapper" + ) + buf.bind(compiled_fn=compiled_fn) + with buf.indent(): + for i, can_require_grad in enumerate(self.flat_requires_grad): + if can_require_grad is None: + buf.writeline( + f"if isinstance(args[{i}], Tensor):" + f" raise AssertionError(" + f"'expected non-Tensor for arg {i}, got Tensor')" + ) + elif not can_require_grad: + msg_name = buf.bind_value( + "_msg", + format_guard_bug_msg( + aot_config, + f"{describe_input(i, aot_config)} would not require grad", + ), + ) + buf.writeline( + f"if args[{i}].requires_grad: raise AssertionError({msg_name})" + ) + buf.writeline("return compiled_fn(args)") + + buf.bind(Tensor=Tensor) + + return buf.build(wrapped_fn=compiled_fn) + + +def pre_compile( + wrappers: list[CompilerWrapper], + flat_fn: TraceFn, + flat_args: list[FxValue], + flat_args_descs: list[AOTInput], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, +) -> tuple[TraceFn, list[FxValue], list[AOTInput], ViewAndMutationMeta]: + """ + Runs a sequence of wrappers on the given function and arguments. + Mutates wrappers in place. + """ + for wrapper in wrappers: + flat_fn, flat_args, flat_args_descs, fw_metadata = wrapper.pre_compile( + flat_fn, flat_args, flat_args_descs, aot_config, fw_metadata=fw_metadata + ) + return flat_fn, flat_args, flat_args_descs, fw_metadata + + +def post_compile( + wrappers: list[CompilerWrapper], + compiled_fn: Callable[..., Any], + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, +) -> tuple[Callable[..., Any], ViewAndMutationMeta]: + """ + Runs a sequence of wrappers on the given function. Should be called after pre_compile() + """ + for wrapper in reversed(wrappers): + compiled_fn = wrapper.post_compile( + compiled_fn, aot_config, runtime_metadata=runtime_metadata + ) + return compiled_fn, runtime_metadata + + +def make_runtime_safe( + fw_metadata: ViewAndMutationMeta, + maybe_subclass_meta: SubclassMeta | None, +) -> None: + """ + Calls make_runtime_safe on all ViewAndMutationMetas. + Modifies both arguments. Allows ViewAndMutationMetas to + be safely cached in AOTAutogradCache. + """ + fw_metadata.make_runtime_safe() + if maybe_subclass_meta is not None: + maybe_subclass_meta.fw_metadata.make_runtime_safe() + if maybe_subclass_meta.grad_input_metas: + for meta in maybe_subclass_meta.grad_input_metas: + if isinstance(meta, SubclassCreationMeta): + meta.make_runtime_safe() diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/schemas.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..c3b7013b4a21754cca829498a2a21a61fa70065b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/schemas.py @@ -0,0 +1,1567 @@ +""" +The various dataclasses, Enums, namedtuples etc used in AOTAutograd. This includes +input/output types, metadata, config, function signatures etc. +""" + +from __future__ import annotations + +import collections +import functools +from collections.abc import Sequence +from dataclasses import dataclass, field, replace +from enum import Enum +from typing import Any, NewType, Protocol, TYPE_CHECKING, TypeAlias, TypeVar +from typing_extensions import ParamSpec + +import torch +import torch.utils._pytree as pytree +from torch import SymInt, Tensor +from torch._custom_class_base import CustomClassBase +from torch._subclasses.fake_tensor import is_fake, is_fake_tensor +from torch.fx.experimental._backward_state import BackwardState +from torch.utils._python_dispatch import is_traceable_wrapper_subclass + +from .. import config +from .functional_utils import _check_if_mutation_can_be_in_graph, ViewMetaSequence +from .utils import strict_zip + + +if TYPE_CHECKING: + import contextlib + from collections.abc import Callable, Iterable + + from torch._guards import Source + from torch._inductor.output_code import OutputCode + from torch._inductor.utils import InputType + from torch._ops import OpOverload + from torch._subclasses import FakeTensorMode + from torch.types import IntLikeType + + from .descriptors import AOTInput, AOTOutput + from .graph_capture_wrappers import JointFnHandle + +_P = ParamSpec("_P") +_R = TypeVar("_R") +zip = strict_zip + +ActInputPath: TypeAlias = tuple[int, tuple[str, ...]] +ActInputPaths: TypeAlias = Sequence[ActInputPath] + + +OutputType = Enum( + "OutputType", + ( + # output is not an alias + "non_alias", + # output aliases an input + "alias_of_input", + # output **is** an input tensor + "is_input", + # output has a ._base tensor, which is a graph intermediate. + # We need to return its ._base as a graph output, + # so its requires_grad info is populated correctly. + # Instructs the runtime code to regenerate the current output + # from a base tensor, graph_intermediates[base_idx] + "alias_of_intermediate_save_as_output", + # Same as above; but we don't need to explicitly add its ._base + # as a graph output, because it already **is** a graph output. + "alias_of_intermediate", + # Same as above; but the output's ._base is **already** a user output. + # Instructs the runtime code to regenerate the current output from + # a base tensor, user_outputs[base_idx] + "alias_of_intermediate_base_is_user_output", + # See Note [Intermediate Bases Optimization] + "unsafe_view_alias", + # output is an alias, but has a custom autograd.Function backward. + # In this case, we don't want to do view-replay, since we won't be able to replay the custom function. + # Instead, we'll treat this output "normally", and trace its backward into the graph. + "custom_function_view", + ), +) + + +# This class stores info about every user output. +@dataclass(frozen=True) +class OutputAliasInfo: + # Tells us if this output is: + # (1) a regular (non-aliased) output + # (2) an alias of a forward input + # (3) **is** a forward input (special case of "alias_of_input") + # (4) an alias of an intermediate (aka an alias of an output of the inner traced forward) + # (5) an alias of an intermediate, that explicitly requires returning the intermediate + # as a graph output + # (6) an alias of an intermediate, where that intermediate is also a user output + output_type: OutputType + # The raw type of the output (torch.Tensor, SymInt, etc) + raw_type: type + # If (1) above, then + # - base_idx is None + # If (2) or (3) above, then + # - Tells us that the base of this alias is user_fwd_input[base_idx] + # (This is an index into the inputs *before* we make synthetic bases) + # If (4) or (5) above, then + # - Tells us that the base of this alias is output_graph_intermediates[base_idx] + # here, this refers to the index of the *direct* traced + # If (6) above, then: + # - Tells us that the base of this alias is output_user_fwds[base_idx] + # here, this refers to the index of the *direct* traced + base_idx: int | None + # If it is a Tensor, what the dynamic dims are (otherwise is None) + dynamic_dims: set[int] | None + # Whether the output tensor has requires_grad=True. Use for + # preserving output properties (mark_non_differentiable, alias reconstruction). + requires_grad: bool + # Whether this output participates in backward as + # a tangent. Normally the same as requires_grad, but False for views created + # under no_grad() that inherit requires_grad from their base without having a + # grad_fn. Use when constructing tangent lists for torch.autograd.grad(). + requires_grad_for_backward: bool + # Sequence of ViewMeta objects. + # + # Provides us the means to re-run view functions on other tensors. + # + # We need to wrap the actual list of ViewMeta with this class so that + # we compare the ViewMeta elements appropriately, i.e. their type and + # the elements returned by the `as_tuple()` call. + view_meta_sequence: ViewMetaSequence | None = None + + +class MutationType(Enum): + NOT_MUTATED = 1 + MUTATED_IN_GRAPH = 2 + MUTATED_OUT_GRAPH = 3 + + +# This class tells us info about user inputs. +@dataclass(frozen=True) +class InputAliasInfo: + is_leaf: bool + mutates_data: bool + mutates_metadata: bool + mutations_hidden_from_autograd: bool + mutations_under_no_grad_or_inference_mode: bool + mutation_inductor_storage_resize: bool + mutates_storage_metadata: bool + mutation_is_shallow_copy_data: bool + requires_grad: bool + keep_input_mutations: bool + + def __post_init__(self) -> None: + if self.mutates_storage_metadata: + # For convenience, we guarantee that this is always true. + # In practice, If we call .set_(), then at runtime there is no need + # to additionally fix up the tensor metadata, since our runtime + # call to inp.set_(updated_inp) will already have the right metadata + if not self.mutates_metadata: + raise AssertionError( + "mutates_storage_metadata requires mutates_metadata to be True" + ) + + @functools.cached_property + def mutation_type(self) -> MutationType: + if ( + (not self.mutates_data) + and (not self.mutates_metadata) + and not (self.mutation_inductor_storage_resize) + ): + return MutationType.NOT_MUTATED + + if _check_if_mutation_can_be_in_graph( + self.keep_input_mutations, + self.mutates_data, + self.mutates_metadata, + self.mutations_hidden_from_autograd, + self.mutations_under_no_grad_or_inference_mode, + self.mutates_storage_metadata, + self.mutation_inductor_storage_resize, + self.requires_grad, + ): + return MutationType.MUTATED_IN_GRAPH + + return MutationType.MUTATED_OUT_GRAPH + + +@dataclass +class MemoryFormatMeta: + # For static shapes we assume tangents have the same strideness as outputs + size: Sequence[int] | None = None + stride: Sequence[int] | None = None + + # For dynamic shapes we assume the same memory format: contiguous, channels_last etc. + memory_format: torch.memory_format | None = None + + @staticmethod + def from_tensor( + t: torch.Tensor, force_use_memory_format: bool = False + ) -> MemoryFormatMeta | None: + # We only memorize expected memory format for + # 1. Traceable wrapper subclasses + # We can not create restrided subclass tensor, as torch.empty_strided works only with dense tensors. + # 2. Dynamic shape tensors + # Support for symbolic shapes is not implemented yet. + # 3. force_use_memory_format=True (e.g., local_map where shapes change) + use_memory_format: bool = ( + force_use_memory_format + or not torch._functorch.config.guess_tangent_strides_as_outputs + or is_traceable_wrapper_subclass(t) + ) + if not use_memory_format: + use_memory_format = t._has_symbolic_sizes_strides + + if ( + not use_memory_format + and t.layout == torch.strided + and torch._debug_has_internal_overlap(t) == 1 + ): + # An internally overlapping output, e.g. from expand(), cannot + # represent arbitrary incoming gradients with its own strides. + use_memory_format = True + + if use_memory_format: + return MemoryFormatMeta( + # pyrefly: ignore [unbound-name] + memory_format=torch._prims_common.suggest_memory_format(t), + ) + + return MemoryFormatMeta( + size=t.size(), + stride=t.stride(), + ) + + +@dataclass +class PlainTensorMeta: + unwrapped_idx: int + memory_format: MemoryFormatMeta | None = None + size_symbol_placeholders: tuple[bool, ...] = () + stride_symbol_placeholders: tuple[bool, ...] = () + + @property + def arg_count(self) -> int: + return ( + 1 + + sum(self.size_symbol_placeholders) + + sum(self.stride_symbol_placeholders) + ) + + +@dataclass +class OpaqueMeta: + pass + + +@dataclass +class SubclassCreationMeta: + """ + Used for AOTDispatch. + This dataclass gives us the information we need to reconstruct a tensor subclass + from our flat inputs. + Why is this important? The graph that we'd like to trace out contains flat tensor inputs, + But the user's original model may have subclass inputs and outputs. + So we need to wrap/unwrap subclasses as necessary to translate between the user's + view (subclass inps/outs), and the backend compiler's view (graph with no subclass args). + + Complications arise mostly from the fact that a subclass can hold more than one inner tensor; + So for a given subclass input/output, we need to carefully track which indices map + to the subclass tensor in the corresponding "dense-tensor-only" graph. + """ + + # In the inner graph that only takes in dense tensor inputs, + # this maps to the first index of "tensors that should go in this subclass wrapper" + flat_tensor_start_idx: int + # arg_count is inclusive of the arg_counts of any + # inner tensor subclasses: If I have a TwoTensor and + # both of its inner elements are TwoTensors, then the + # arg_count of the outer-most subclass will be 4 + arg_count: int + # Mark where or not symints were included. This flag is only used in one assertion + # in "wrap_tensor_subclasses" + included_subclass_symints: bool + # meta and attrs are produced by the subclass's __tensor_flatten__. + # We need to keep them around along with outer_size / outer_stride to plumb them + # into __tensor_unflatten__ + attrs: dict[str, SubclassCreationMeta | PlainTensorMeta | OpaqueMeta] + outer_size: Iterable[IntLikeType | None] + outer_stride: Iterable[IntLikeType | None] + meta: Any + # Stores the original subclass itself. + # This is needed because we need the autograd metadata on the original subclass + # (this is guaranteed to be a wrapper subclass that holds a fake tensor, + # so holding onto this at runtime shouldn't leak memory) + # This field is nulled out after calling make_runtime_safe() + original_subclass: torch.Tensor | None + + # Used at runtime to determine the subclass type, so we don't need to save the original subclass + original_subclass_type: type | None = None + memory_format: MemoryFormatMeta | None = None + outer_size_from_attr: str | None = None + outer_stride_from_attr: str | None = None + + def compute_outer_size_and_stride( + self, + all_args: Sequence[torch.Tensor | IntLikeType | CustomClassBase], + *, + curr_start_idx: int, + ) -> tuple[ + Iterable[IntLikeType | None], + Iterable[IntLikeType | None], + ]: + from .subclass_utils import compute_symint_placeholders + + def compute( + outer: Iterable[IntLikeType | None], start_idx: int + ) -> tuple[Any, int | Any]: + placeholders = compute_symint_placeholders(outer) + has_symbolic = any(placeholders) + + if has_symbolic: + end = start_idx + sum(placeholders) + it_args = iter(all_args[start_idx:end]) + it_placeholders = iter(placeholders) + return pytree.tree_map_only( + lambda _: next(it_placeholders), lambda _: next(it_args), outer + ), end + else: + return outer, start_idx + + outer_size, next_idx = compute(self.outer_size, curr_start_idx) + outer_stride, _ = compute(self.outer_stride, next_idx) + return outer_size, outer_stride + + def creation_fn( + self, + all_args: Sequence[torch.Tensor | IntLikeType | CustomClassBase], + *, + is_runtime: bool, + ) -> torch.Tensor: + inner_tensors: dict[str, torch.Tensor | CustomClassBase] = {} + + curr_start_idx = self.flat_tensor_start_idx + for attr, creation_meta in self.attrs.items(): + if isinstance(creation_meta, OpaqueMeta): + opaque = all_args[curr_start_idx] + if not isinstance(opaque, CustomClassBase): + raise AssertionError( + f"CustomClassBase expected, got {type(opaque)}" + ) + inner_tensors[attr] = opaque + curr_start_idx += 1 + continue + if isinstance(creation_meta, PlainTensorMeta): + subclass = all_args[curr_start_idx] + if not isinstance(subclass, Tensor): + raise AssertionError("Tensor expected") + curr_start_idx += creation_meta.arg_count + else: + subclass = creation_meta.creation_fn( + all_args, + is_runtime=is_runtime, + ) + curr_start_idx += creation_meta.arg_count + inner_tensors[attr] = subclass + + if is_runtime: + if self.original_subclass_type is None: + raise AssertionError( + "original_subclass_type must not be None at runtime" + ) + original_subclass_type = self.original_subclass_type + else: + original_subclass_type = type(self.original_subclass) + + if is_runtime: + outer_size, outer_stride = self.compute_outer_size_and_stride( + all_args, + curr_start_idx=curr_start_idx, + ) + if self.outer_size_from_attr is not None: + size_attr = inner_tensors[self.outer_size_from_attr] + if not isinstance(size_attr, Tensor): + raise AssertionError("Tensor expected") + outer_size = size_attr.size() + if self.outer_stride_from_attr is not None: + stride_attr = inner_tensors[self.outer_stride_from_attr] + if not isinstance(stride_attr, Tensor): + raise AssertionError("Tensor expected") + outer_stride = stride_attr.stride() + else: + outer_size, outer_stride = self.outer_size, self.outer_stride + + rebuilt = original_subclass_type.__tensor_unflatten__( # type: ignore[attr-defined] + inner_tensors, self.meta, outer_size, outer_stride + ) + + if not is_runtime: + # After wrapping up the inner dense tensors into a subclass, we need to make sure that our new wrapper + # has correct autograd metadata, since we'll be tracing through the autograd engine with the subclass. + # We don't trace through the autograd engine at runtime though, so no need + # to compute this extra metadata then! + torch._mirror_autograd_meta_to(self.original_subclass, rebuilt) # type: ignore[attr-defined] + + return rebuilt + + def make_runtime_safe(self) -> None: + def _make_size_runtime_safe(x: None | int | torch.SymInt) -> int | None: + dummy = -1 + if isinstance(x, torch.SymInt): + # Replace nested ints by a dummy value (-1) as NJT ignores + # the outer_size/outer_stride at runtime. + return dummy if x.node.is_nested_int() else None + return x + + if self.original_subclass is None: + raise AssertionError( + "original_subclass must not be None before calling make_runtime_safe" + ) + self.original_subclass_type = type(self.original_subclass) + self.original_subclass = None + + # Note: NJT outer_size in AOTDispatcher + # `_make_size_runtime_safe` replaces any nested int with a dummy value (-1) + # to prevent serializing a SymInt at runtime. Internally, nested tensor __tensor_unflatten__ + # is designed to safely ignore this dummy value. + # For more details, see: https://github.com/pytorch/pytorch/blob/5141ade8e30c64e873e14dcc8de233da45d15025/torch/nested/_internal/nested_tensor.py#L266-L299 + self.outer_size = tuple(map(_make_size_runtime_safe, self.outer_size)) + self.outer_stride = tuple(map(_make_size_runtime_safe, self.outer_stride)) + + # Recurse on nested subclass info + for creation_meta in self.attrs.values(): + if isinstance(creation_meta, SubclassCreationMeta): + creation_meta.make_runtime_safe() + + def __post_init__(self) -> None: + # sanity assert to make sure we don't leak memory + if not is_fake(self.original_subclass): + raise AssertionError( + f"original_subclass must be a fake tensor to avoid memory leaks, got {type(self.original_subclass)}" + ) + + +# This class encapsulates all aliasing + mutation info we need about the forward graph +# See a more detailed overview of the edge case handling at +# https://docs.google.com/document/d/19UoIh_SVrMy_b2Sx5ZaeOJttm6P0Qmyss2rdBuyfoic/edit +# NOTE: This class is saved in AOTAutogradCache, If you are adding elements, make sure +# they are covered by warm cache tests. +@dataclass(eq=False) +class ViewAndMutationMeta: + # length = # user inputs + # This gives us info about every input, and what sort of mutation happened to it (if any) + input_info: list[InputAliasInfo] + + # length = # user outputs + # This gives us info about every output (mostly around whether it aliases other tensors) + output_info: list[OutputAliasInfo] + + # length = the number of intermediate bases appended as outputs to the end of the forward graph. + # Note: this is not necessarily the same thing as: + # len([x for x in output_info if x.output_type == OutputType.alias_of_intermediate]) + # Because outputs might share a ._base, or an output's ._base might itself be + # another user output (in both cases, we won't redundantly append bases to the end of the graph) + num_intermediate_bases: int + + # For inference only: instructs us to keep data-only input mutations directly in the graph + keep_input_mutations: bool + + # length = (# inputs w data mutations) + (# user outputs that are non_aliasing tensors) + # + (# intermediate bases) + # These are the FakeTensor (or potential SymInt) outputs that we traced from our + # metadata pass of the user's forward function. + # Their only use today is to pass them as a best-guess for tangents when tracing the joint. + # Stashing them as part of our "metadata" makes it simpler if we want to run our analysis + # pass once, and reuse the output throughout AOTAutograd + traced_tangents: list[Any] + + # TODO doc + traced_tangents_descs: list[AOTInput] + + # Each of these is a list telling us about subclasses for the inputs/outputs/grad_outs + # They are used throughout AOTDispatch to tell us how to generate a list of subclass tensors, + # Given a (potentially larger) list of plain torch tensors. + + # Taking subclass_inp_meta as an example: + # subclass_inp_meta[i] = j (an int) tells us: + # "The i'th user input is not a subclass, and corresponds to inputs[j] of the plain-tensor graph." + # subclass_inp_meta[i] = SubclassCreationMeta(flat_tensor_start_idx=3, arg_count=2) + # "The i'th user input is subclass holding two inner tensors, which are + # inputs[3] and inputs[4] of the plain-tensor graph". + + # length = # user inputs + subclass_inp_meta: list[PlainTensorMeta | SubclassCreationMeta] + # So, the full set of outputs to the forward graph looks something like: + # (*mutated_inps, *user_outs, *intermediate_bases, *saved_for_bw_tensors) + # where the first 3 of those 4 can be subclasses + # (but not saved_for_bw tensors, since these are internal to the compiler + # and not user visible, so there's no point in wrapping/unwrapping them at runtime). + # This list contains subclass information on all of the fw graph outputs + # except for saved_for_bw_tensors. + subclass_fw_graph_out_meta: list[PlainTensorMeta | SubclassCreationMeta] + # length = # backward graph inputs + subclass_tangent_meta: list[PlainTensorMeta | SubclassCreationMeta] + + # length = (# inputs w data mutations) + (# user outputs that are non_aliasing tensors) + # + (# intermediate bases) + # At runtime, we don't keep the traced_tangents around since they're not serializable. + # Instead, we keep any necessary subclass metadata necessary about each traced_tangent. + # This list is generated after calling make_runtime_safe(). + traced_tangent_metas: list[Any] | None = None + + num_symints_saved_for_bw: int | None = None + + # See Note [Activations with no version counter checks in eager] + # Number of tensors saved for backward that were stashed on ctx (e.g., ctx.x = x) + # rather than via save_for_backward in an autograd.Function. + # These tensors are placed at the end of the saved tensors and should skip + # version counter checks at runtime. + num_tensors_saved_with_no_vc_check: int | None = None + + # Number of opaque objects saved for backward + num_opaque_objects_saved_for_bw: int | None = None + + # Whether each saved tensor is also a graph input. + saved_tensor_is_graph_input: list[bool] = field(default_factory=list) + # The grad_enabled mutation that will be emitted in the runtime_wrapper epilogue + # NOTE: AOTAutograd will assume that the ambient `is_grad_enabled` is the grad mode + # that is intended to be in effect prior to running the graph, in keeping with + # equivalence to eager mode. It is the responsibility of upstream graph acquisition + # to reset the grad mode to its pre-graph value prior to calling aot_autograd. + grad_enabled_mutation: bool | None = None + + # Keeps track of whether `torch.use_deterministic_algorithms` was turned on + # when the forward was run. If deterministic mode was turned off during the + # forward, but is turned on during the backward call, then an error is + # raised + deterministic: bool | None = None + + # Keeps track of which input indices store parameters (which we will treat as static) + static_input_indices: list[int] = field(default_factory=list) + + # Input paths that held AsyncCollectiveTensors at compile time. A path is + # (input_index, attr_path), where an empty attr_path means the top-level + # input. Used to emit direct trigger_wait() calls at runtime instead of + # scanning every arg on every graph invocation. + act_input_paths: list[ActInputPath] = field(default_factory=list) + + # Map of effect type (ex. _EffectType.ORDERED) to token. If there are + # side-effectful operators, FunctionalTensorMode will populate this + # dictionary telling us how many tokens we will need during tracing. + tokens: dict[Any, torch.Tensor] = field(default_factory=dict) + + # Only filled in if/when we trace the joint function + # If an input requires grad and is mutated in the backward, it is only safe to keep the mutation + # in the graph if gradients are disabled while the backward runs + # (grad mode is disabled by default when users run the backward, but can be turned on with create_graph=True) + # At runtime during the backward, we use this list of indices to error properly if we find out + # that it was not safe to include a backward mutation in the graph. + indices_of_inputs_that_requires_grad_with_mutations_in_bw: list[int] = field( + default_factory=list + ) + + # Indexes of saved tensors which are donated buffer. + # Donated buffer means the tensor is not alias of any forward user input, forward user output, + # and backward output. + bw_donated_idxs: list[int] | None = None + + # Number of tokens used in backward, appended at the end of backward outputs. + # Filled after tracing joint function. + num_backward_tokens: int = 0 + + # Number of rng states that will get thread into the forward and backward for + # cudagraph compatible run_and_save_rng + num_graphsafe_rng_states: int = 0 + + graphsafe_rng_state_index: int | None = None + + # Device for graphsafe RNG states (supports CUDA, TPU, etc.) + graphsafe_rng_device: torch.device | None = None + + # Stream indices for mutated inputs in the epilogue + # Maps from index in mutated_inp_runtime_indices to the stream index that last touched + # the storage of the tensor that will be copied back into the original input + # None means use the current/default stream + # This is populated during graph compilation when stream assignments are made + mutated_inp_stream_indices: list[int | None] | None = None + + # compile ID string (e.g., "1/0") for error messages + compile_id_str: str | None = None + + # help users identify where to add .detach() in their code + tangent_source_stack_traces: list[str | None] | None = None + + def __post_init__(self) -> None: + # pre-compute the indices of the inputs that are mutated. + # When keep_input_mutations is set, we don't need to worry about our epilogue + # handling data-only mutations, because we keep them directly in the graph. + mutated_inp_runtime_indices = [ + i + for i, m in enumerate(self.input_info) + if (m.mutation_type == MutationType.MUTATED_OUT_GRAPH) + ] + + mutated_graph_handled_indices = [ + i + for i, m in enumerate(self.input_info) + if m.mutation_type == MutationType.MUTATED_IN_GRAPH + ] + self.mutated_graph_handled_indices = mutated_graph_handled_indices + self.num_mutated_graph_handled_indices = len(self.mutated_graph_handled_indices) + + mutated_graph_handled_indices_seen_by_autograd = [ + i + for i in mutated_graph_handled_indices + if not self.input_info[i].mutations_hidden_from_autograd + ] + + self.mutated_graph_handled_indices_seen_by_autograd = ( + mutated_graph_handled_indices_seen_by_autograd + ) + self.num_mutated_graph_handled_indices_seen_by_autograd = len( + self.mutated_graph_handled_indices_seen_by_autograd + ) + + aliased_out_indices = [ + i + for i, m in enumerate(self.output_info) + if m.output_type + not in [ + OutputType.non_alias, + OutputType.unsafe_view_alias, + OutputType.custom_function_view, + ] + ] + unsafe_view_out_indices = [ + i + for i, m in enumerate(self.output_info) + if m.output_type is OutputType.unsafe_view_alias + ] + + # This is pre-computed in post_init for perf. + # It contains the index of every element + # of input_info that corresponds to a mutation (data or metadata or both) + self.mutated_inp_runtime_indices = mutated_inp_runtime_indices + self.num_mutated_inp_runtime_indices = len(self.mutated_inp_runtime_indices) + + # This is pre-computed for perf. + # It contains the index of every element + # of output_info that corresponds to an alias (either of an input or intermediate) + self.aliased_out_indices = aliased_out_indices + self.unsafe_view_out_indices = unsafe_view_out_indices + self.num_outputs = len(self.output_info) + self.num_outputs_non_aliased = len( + [ + x + for x in self.output_info + if x.output_type + in [ + OutputType.non_alias, + OutputType.unsafe_view_alias, + OutputType.custom_function_view, + ] + ] + ) + self.num_outputs_aliased_to_inputs = len( + [ + x + for x in self.output_info + if x.output_type + in [ + OutputType.alias_of_input, + OutputType.is_input, + ] + ] + ) + self.num_unsafe_view_outputs = len(self.unsafe_view_out_indices) + self.num_outputs_aliased_to_intermediates = len( + [ + x + for x in self.output_info + if x.output_type + in [ + OutputType.alias_of_intermediate, + OutputType.alias_of_intermediate_save_as_output, + OutputType.alias_of_intermediate_base_is_user_output, + ] + ] + ) + self.num_outputs_aliased = ( + self.num_outputs_aliased_to_inputs + + self.num_outputs_aliased_to_intermediates + ) + + # Record dynamic outputs of the Dynamo traced forward graph + # Mark them as dynamic at the end of the runtime wrapper + self.dynamic_outputs = any(o.dynamic_dims for o in self.output_info) + + # Record the indices of dynamic outputs in the partitioned forward graph + # Mark them as dynamic in the runtime wrapper + # activation index -> dynamic dims indices + self.dynamic_saved_tensors_idxs: dict[int, set[int]] = {} + + # See Note: [AOTAutograd Backward Guards] + # This is pre-computed for fast asserts on the types of our grad_outputs in the backward. + # Eventually, we should kill this and replace with real backward guards. + # (we want to precompute the "runtime" types, so replace FakeTensor with torch.Tensor) + self.output_types = [ + torch.Tensor if is_fake_tensor(x) else type(x) for x in self.traced_tangents + ] + + self.is_rng_op_functionalized = config.functionalize_rng_ops + # All of the above metadata is collected by tracing the fw function. + # However, extra outputs for rng offsets behave differently. Both fwd + # and bwd graphs have their own outputs for the total consumed offsets. + # Unlike mutated inputs, we don't have to worry about sending the right + # set of tensors between fwd and bwd. Fwd and bwd offsets are + # independent and simpler to handle. Therefore, we track them + # separately. + self.num_outputs_rng_offset = 1 if self.is_rng_op_functionalized else 0 + + # Our forward() returns both (tokens, mutated_inputs, outputs, output_intermediate_bases, saved_tensors, saved_symints) + # Tokens will be split out before mutations/view handling and we do not count them here. + self.num_forward_returns = ( + self.num_mutated_inp_runtime_indices + + self.num_outputs + + self.num_intermediate_bases + ) + # In case of functionalization of rng ops, the fw_module returns one + # additional output for rng offset. This rng offset is used right + # away to advance the rng state, and is not passed on to the raw + # outputs. However, we need to know the exact boundary to identify + # which tensors to be saved for the bwd graph. num_forward captures + # this information. + self.num_forward = self.num_forward_returns + self.num_outputs_rng_offset + + def make_runtime_safe(self) -> None: + """ + There are various fields in ViewAndMutationMeta that aren't serializable. This function is called after all tracing + is completed to simplify certain fields in the metadata so that they can be safely cached. + + Doing so may lose information (in the case of traced_tangents), but none of the information is needed at runtime. + """ + # TODO: This function is only a best effort: there are other fields that may not be cache safe + # (i.e., there's no guarantee that tensor_flatten() returns a serializable result), or that + # SubclassCreationMeta is cache safe. + if self.traced_tangent_metas is not None: + raise AssertionError( + "traced_tangent_metas should be None before calling make_runtime_safe" + ) + + def extract_metadata(t: object) -> tuple[Sequence[str], object] | None: + if isinstance(t, torch.Tensor) and is_traceable_wrapper_subclass(t): + (inner_tensors, flatten_spec) = t.__tensor_flatten__() # type: ignore[attr-defined] + # Technically, we only need the flatten_spec, not the inner tensors. + # However, some Tensor subclasses (like TwoTensor) may have flatten_spec = None. + # And we want to be able to assert that this metadata is non-None, + # to distinguish between "this was a tensor subclass with no metadata" vs. + # "this wasn't a tensor subclass at all". + return (inner_tensors, flatten_spec) + else: + return None + + self.traced_tangent_metas = [extract_metadata(t) for t in self.traced_tangents] + # Clear traced tangents at runtime + self.traced_tangents = [] + for inp_meta in self.subclass_inp_meta: + if isinstance(inp_meta, SubclassCreationMeta): + inp_meta.make_runtime_safe() + for inp_meta in self.subclass_fw_graph_out_meta: + if isinstance(inp_meta, SubclassCreationMeta): + inp_meta.make_runtime_safe() + for inp_meta in self.subclass_tangent_meta: + if isinstance(inp_meta, SubclassCreationMeta): + inp_meta.make_runtime_safe() + + # Clear view_meta_sequence when it has symbolic inputs, since it won't + # be used at runtime anyway (gen_alias_from_base skips view replay for + # symbolic inputs) and the SymInt references make it unpicklable. + for i, out_info in enumerate(self.output_info): + if out_info.view_meta_sequence is not None and any( + vm.has_symbolic_inputs for vm in out_info.view_meta_sequence.sequence + ): + self.output_info[i] = replace(out_info, view_meta_sequence=None) + + @property + def tensors_saved_for_backwards_slice(self) -> slice: + if self.num_symints_saved_for_bw is None: + raise AssertionError("num_symints_saved_for_bw must not be None") + if self.num_tensors_saved_with_no_vc_check is None: + raise AssertionError("num_tensors_saved_with_no_vc_check must not be None") + # Fast-path: if no tensors without VC check, just return the VC check slice + if self.num_tensors_saved_with_no_vc_check == 0: + return self.tensors_saved_for_backwards_with_vc_check_slice + # Invariant: total tensors activations = (acts_with_vc_check, acts_no_vc_check) + vc_slice = self.tensors_saved_for_backwards_with_vc_check_slice + no_vc_slice = self.tensors_saved_for_backwards_no_vc_check_slice + # Start should be the same (self.num_forward) + if vc_slice.start != self.num_forward: + raise AssertionError( + f"vc_slice.start ({vc_slice.start}) != self.num_forward ({self.num_forward})" + ) + # End is the end of the no_vc_check slice + return slice(vc_slice.start, no_vc_slice.stop) + + @property + def tensors_saved_for_backwards_with_vc_check_slice(self) -> slice: + """ + Slice of forward outputs that are tensors saved for backward that + require version counter checks (i.e., were saved via save_for_backward). + """ + # See Note [Activations with no version counter checks in eager] + if self.num_symints_saved_for_bw is None: + raise AssertionError("num_symints_saved_for_bw must not be None") + if self.num_tensors_saved_with_no_vc_check is None: + raise AssertionError("num_tensors_saved_with_no_vc_check must not be None") + # The tensors with VC check come first, followed by tensors without VC check + num_no_vc_check = self.num_tensors_saved_with_no_vc_check + num_opaque = self.num_opaque_objects_saved_for_bw or 0 + num_symints = self.num_symints_saved_for_bw + num_trailing = num_no_vc_check + num_opaque + num_symints + if num_trailing > 0: + return slice(self.num_forward, -num_trailing if num_trailing != 0 else None) + else: + return slice(self.num_forward, None) + + @property + def tensors_saved_for_backwards_no_vc_check_slice(self) -> slice: + """ + Slice of forward outputs that are tensors saved for backward that + do NOT require version counter checks (i.e., were stashed on ctx + rather than via save_for_backward in an autograd.Function). + """ + if self.num_symints_saved_for_bw is None: + raise AssertionError("num_symints_saved_for_bw must not be None") + if self.num_tensors_saved_with_no_vc_check is None: + raise AssertionError("num_tensors_saved_with_no_vc_check must not be None") + num_no_vc_check = self.num_tensors_saved_with_no_vc_check + num_opaque = self.num_opaque_objects_saved_for_bw or 0 + num_symints = self.num_symints_saved_for_bw + if num_no_vc_check == 0: + return slice(0, 0) # empty slice + num_trailing = num_opaque + num_symints + if num_trailing > 0: + return slice(-num_no_vc_check - num_trailing, -num_trailing) + else: + return slice(-num_no_vc_check, None) + + @property + def opaque_objects_saved_for_backwards_slice(self) -> slice: + num_opaque = self.num_opaque_objects_saved_for_bw or 0 + num_symints = self.num_symints_saved_for_bw or 0 + if num_opaque > 0: + if num_symints > 0: + return slice(-num_opaque - num_symints, -num_symints) + else: + return slice(-num_opaque, None) + else: + return slice(0, 0) # empty slice + + @property + def symints_saved_for_backwards_slice(self) -> slice: + if self.num_symints_saved_for_bw is None: + raise AssertionError("num_symints_saved_for_bw must not be None") + if self.num_symints_saved_for_bw > 0: + return slice(-self.num_symints_saved_for_bw, None) + else: + return slice(0, 0) # empty slice + + def __eq__(self, other: object) -> bool: + if not isinstance(other, ViewAndMutationMeta): + return NotImplemented + return ( + self.input_info == other.input_info + and self.output_info == other.output_info + and self.num_intermediate_bases == other.num_intermediate_bases + and self.keep_input_mutations == other.keep_input_mutations + and self.is_rng_op_functionalized == other.is_rng_op_functionalized + and self.num_outputs_rng_offset == other.num_outputs_rng_offset + and len(self.traced_tangents) == len(other.traced_tangents) + and all( + x.shape == y.shape and x.dtype == y.dtype + for x, y in zip(self.traced_tangents, other.traced_tangents) + ) + and self.num_backward_tokens == other.num_backward_tokens + ) + + +@dataclass(eq=False) +class SubclassMeta: + # A copy of all forward metadata, but computed on the *dense* tensor forward (after desugaring subclasses) + # So for example, if the user had a model containing two `TwoTensor` inputs, + # Then `SubclassMeta.fw_metadata.input_infos` would have length 4 here. + fw_metadata: ViewAndMutationMeta + + # Note: [Computing Subclass Metadata about grad_inputs] + # Given a list of flattened, plain tensor grad_inputs, this tells us how to reconstruct the grad_input subclasses + # + # You might think: why not just assume that all grad_inputs will have the same subclass-ness as the original inputs? + # (AOTAutograd generally assumes other properties, e.g. that grad_outputs are contiguous) + # + # This doesn't really work though. take this example: + # + # def f(DoubleTensor, DenseTensor): + # return DoubleTensor * DenseTensor + # + # In the above example, the .grad field of *both* DoubleTensor and DenseTensor will be a DoubleTensor. + # When we trace out a joint fw-bw graph, we'll end up returning two subclasses for the two grad_inputs. + # This means that our backward graph will return 4 outputs (two dense tensors for each DoubleTensor grad_input) + # and we need to properly store the metadata that tells us how to turn these 4 outputs back into DoubleTensors. + # + # Note that this info **cannot** easily be figured out from ViewAndMutationMeta. + # We can only compute this info by tracing the entire joint and examining the grad_inputs that we computed. + # + # See Note: [AOTAutograd Backward Guards] + # This will also eventually require us to install backward guards, + # in case we made incorrect assumptions about the subclass-ness of our grad_outputs + # + # Optional field because we don't compute for inference graphs + grad_input_metas: list[PlainTensorMeta | SubclassCreationMeta] | None = None + + def __init__(self) -> None: + # The fields in this class get set after its construction. + pass + + +# This class exists because: +# - the autograd.Function.forward() in aot autograd returns outputs that might alias inputs +# - we only care about the metadata on those aliases, so we can regenerate them. +# We do not want them to participate in the autograd.Function. +# We do that by wrapping them in an opaque class, so the autograd.Function +# does not know to treat them as tensors. +@dataclass(frozen=True) +class TensorAlias: + alias: torch.Tensor + + +@dataclass +class BackwardSignature: + """ + Provides information about the backward section of an exported + joint forward-backward graph. + For a particular fx GraphModule, this class contains information on: + (1) A mapping from each gradient (backwards output) to the parameter + it corresponds to (forward input) + (2) A mapping from each gradient (backwards output) to the user input + it corresponds to (forward input) + (3) Which of the forward outputs corresponds to the loss, that we backprop on. + + Each string name is the `node.name` of the corresponding node in the fx graph. + """ + + gradients_to_parameters: dict[str, str] + gradients_to_user_inputs: dict[str, str] + loss_output: str + + +GraphOutputName = NewType("GraphOutputName", str) +GraphInputName = NewType("GraphInputName", str) +FQN = NewType("FQN", str) + + +@dataclass +class GraphSignature: + """ + Provides information about an exported module. + For a particular fx GraphModule, this class contains information on: + (1) Which graph inputs are parameters, buffers, or user inputs + (2) (for params/buffers) a mapping from the name of each graph argument + to its parameter/buffer FQN in the original nn.Module. + (3) If there are input mutations, these are represented as extra outputs + in the fx GraphModule. We provide a mapping from these + extra output names to the names of the actual inputs. + (4) The pytree metadata on how to flatten/unflatten inputs and outputs. + The corresponding FX GraphModule only accepts and returns + pytree-flattened inputs/outputs. + (5) (Optionally) if the FX is a joint forward-backward graph, we provide + a signature on the backward section of the joint graph. + """ + + parameters: list[FQN] + buffers: list[FQN] + + user_inputs: list[GraphInputName] + user_outputs: list[GraphOutputName] + inputs_to_parameters: dict[GraphInputName, FQN] + inputs_to_buffers: dict[GraphInputName, FQN] + + # If the user's module mutates a buffer, + # it's represented in the graph as an extra graph output. + # This dict is a mapping from + # "graph outputs that correspond to updated buffers" + # to the FQN names of those mutated buffers. + buffers_to_mutate: dict[GraphOutputName, FQN] + parameters_to_mutate: dict[GraphOutputName, FQN] + user_inputs_to_mutate: dict[GraphOutputName, GraphInputName] + + in_spec: pytree.TreeSpec + out_spec: pytree.TreeSpec + + backward_signature: BackwardSignature | None + + input_tokens: list[GraphInputName] + output_tokens: list[GraphOutputName] + + @classmethod + def from_tracing_metadata( + cls, + *, + in_spec: pytree.TreeSpec, + out_spec: pytree.TreeSpec, + graph_input_names: list[str], + graph_output_names: list[str], + view_mutation_metadata: ViewAndMutationMeta, + named_parameters: list[str], + named_buffers: list[str], + num_user_inputs: int, + num_user_outputs: int, + trace_joint: bool, + loss_index: int | None, + backward_signature: BackwardSignature | None, + ) -> GraphSignature: + graph_inputs = graph_input_names + graph_outputs = graph_output_names + parameters = list(named_parameters) + buffers = list(named_buffers) + num_tokens = len(view_mutation_metadata.tokens) + + # Calling convention assumptions: + # (1) graph inputs = (input_tokens, params, buffers, user_inputs) + # (2) graph outputs = (output_tokens, mutated_inputs, user_outs, param_gradients) + # (If we are capturing an inference graph, this convention is identical + # except that param_gradients is empty) + # See Note [Side-Effectful Tokens in AOTAutograd] for information on tokens + + # Address input calling conventions: + start, stop = 0, num_tokens + input_tokens = graph_inputs[start:stop] + + start, stop = stop, stop + len(parameters) + inputs_to_parameters = dict(zip(graph_inputs[start:stop], parameters)) + + start, stop = stop, stop + len(buffers) + inputs_to_buffers = dict( + zip( + graph_inputs[start:stop], + buffers, + ) + ) + + start, stop = stop, stop + num_user_inputs + user_inputs = graph_inputs[start:stop] + + # We should've gone through all the inputs now + if len(graph_inputs) - stop != 0: + raise AssertionError( + f"expected all graph_inputs consumed, but {len(graph_inputs) - stop} remain" + ) + + # Address output calling conventions: + start, stop = 0, num_tokens + output_tokens = graph_outputs[start:stop] + + names = [*input_tokens, *parameters, *buffers, *user_inputs] + mutations: list[str] = [] + for idx, input_info in enumerate(view_mutation_metadata.input_info): + if input_info.mutates_data: + if trace_joint: + # Only buffers can be mutated, not parameters + if idx < len(parameters): + raise AssertionError( + f"expected idx ({idx}) >= len(parameters) ({len(parameters)}) when tracing joint" + ) + mutations.append(names[idx + num_tokens]) + + if len(mutations) != view_mutation_metadata.num_mutated_inp_runtime_indices: + raise AssertionError( + f"len(mutations) ({len(mutations)}) != " + f"num_mutated_inp_runtime_indices ({view_mutation_metadata.num_mutated_inp_runtime_indices})" + ) + + start, stop = ( + stop, + stop + view_mutation_metadata.num_mutated_inp_runtime_indices, + ) + outputs_to_mutations = dict(zip(graph_outputs[start:stop], mutations)) + + user_inputs_to_mutate: dict[GraphOutputName, GraphInputName] = {} + buffers_to_mutate: dict[GraphOutputName, FQN] = {} + parameters_to_mutate: dict[GraphOutputName, FQN] = {} + for output_name, mutation_name in outputs_to_mutations.items(): + if mutation_name in user_inputs: + # pyrefly: ignore [unsupported-operation] + user_inputs_to_mutate[output_name] = mutation_name + else: + if mutation_name not in buffers and mutation_name not in parameters: + raise AssertionError( + f"mutation_name '{mutation_name}' not found in buffers or parameters" + ) + if mutation_name in buffers: + # pyrefly: ignore [unsupported-operation] + buffers_to_mutate[output_name] = mutation_name + else: + # pyrefly: ignore [unsupported-operation] + parameters_to_mutate[output_name] = mutation_name + + start, stop = stop, stop + num_user_outputs + user_outputs = graph_outputs[start:stop] + + unused_outputs = len(graph_outputs) - stop + if backward_signature is not None: + unused_outputs -= len(backward_signature.gradients_to_parameters) + len( + backward_signature.gradients_to_user_inputs + ) + if unused_outputs != 0: + raise AssertionError(f"expected unused_outputs == 0, got {unused_outputs}") + + return GraphSignature( + parameters=parameters, # type: ignore[arg-type] + buffers=buffers, # type: ignore[arg-type] + user_inputs=user_inputs, # type: ignore[arg-type] + user_outputs=user_outputs, # type: ignore[arg-type] + inputs_to_buffers=inputs_to_buffers, # type: ignore[arg-type] + inputs_to_parameters=inputs_to_parameters, # type: ignore[arg-type] + user_inputs_to_mutate=user_inputs_to_mutate, + buffers_to_mutate=buffers_to_mutate, # type: ignore[arg-type] + parameters_to_mutate=parameters_to_mutate, # type: ignore[arg-type] + in_spec=in_spec, + out_spec=out_spec, + backward_signature=backward_signature, + input_tokens=input_tokens, # type: ignore[arg-type] + output_tokens=output_tokens, # type: ignore[arg-type] + ) + + +@dataclass +class AOTAutogradCacheInfo: + cache_key: str + start_time_ns: int + forward_symints: list[torch.SymInt] + + +@dataclass +class CacheableAOTConfig: + """ + Serializable subset of AOTConfig used by cache keys and cached entries. + """ + + num_params_buffers: int + aot_id: int + keep_inference_input_mutations: bool + is_export: bool = False + no_tangents: bool = False + dynamic_shapes: bool = False + aot_autograd_arg_pos_to_source: list[Source] | None = None + static_input_indices: list[int] | None = None + enable_log: bool = True + # this is always false outside of export. + pre_dispatch: bool = False + precompile_backend_id: str | None = None + + def __post_init__(self) -> None: + if self.pre_dispatch and not self.is_export: + raise AssertionError("Can only have pre_dispatch IR for export.") + + +@dataclass(frozen=True) +class AOTConfig: + """ + Configuration for AOTDispatcher + """ + + fw_compiler: Callable[..., Any] | None + bw_compiler: Callable[..., Any] | None + partition_fn: Callable[..., Any] | None + decompositions: dict[OpOverload, Callable[..., Any]] | None + num_params_buffers: int + aot_id: int + keep_inference_input_mutations: bool + is_export: bool = False + no_tangents: bool = False + dynamic_shapes: bool = False + aot_autograd_arg_pos_to_source: list[Source] | None = None + static_input_indices: list[int] | None = None + inference_compiler: Callable[..., Any] | None = None + enable_log: bool = True + # this is always false outside of export. + pre_dispatch: bool = False + # Key to use for AOTAutogradCache + cache_info: AOTAutogradCacheInfo | None = None + # If we should ignore the shape_env in the ambient tracing_context. + # The net effect is that if dynamic shapes are on, we end up + # specializing on example_inputs. + # Used only by standalone_compile. + ignore_shape_env: bool = False + precompile_backend_id: str | None = None + force_non_lazy_backward_lowering: bool = False + # This config makes sure to check certain things like + # mutating input with req_grad in export joint tracing. + export_trace_joint: bool = False + disable_functionalization: bool = False + # If True, disable TorchFunctionMetadataMode during make_fx tracing. + # This mode is used to track torch_fn metadata but can interfere with + # certain tracing scenarios. + _disable_torch_fn_metadata_mode: bool = False + + def to_cacheable(self) -> CacheableAOTConfig: + return CacheableAOTConfig( + num_params_buffers=self.num_params_buffers, + aot_id=self.aot_id, + keep_inference_input_mutations=self.keep_inference_input_mutations, + is_export=self.is_export, + no_tangents=self.no_tangents, + dynamic_shapes=self.dynamic_shapes, + aot_autograd_arg_pos_to_source=self.aot_autograd_arg_pos_to_source, + static_input_indices=self.static_input_indices, + enable_log=self.enable_log, + pre_dispatch=self.pre_dispatch, + precompile_backend_id=self.precompile_backend_id, + ) + + def __post_init__(self) -> None: + if self.pre_dispatch: + if not self.is_export: + raise AssertionError("Can only have pre_dispatch IR for export.") + + +# TODO: types here +# plain_tensor_trace_fn, when it is joint, has tuple structure on the trace +# info too! +# TODO: this needs to be generic, parameterized on AOTDescriptor +SubclassTracingInfo = collections.namedtuple( + "SubclassTracingInfo", + [ + "plain_tensor_trace_fn", + "plain_tensor_args", + "plain_tensor_args_descs", + "maybe_subclass_meta", + ], +) + + +@dataclass +class AOTState: + """ + When we run AOTAutograd, this class encapsulates the state in the compiler which + must be preserved across stages. This is state in the traditional sense (not an + environment) because some values in this structure change as we progress through + pipelines in AOTAutograd. + """ + + # Whether or not we need to handle autograd when doing graph capture and + # compilation. Although the calling convention for non-autograd graph + # capture in AOTAutograd is simple and can be relied upon, the autograd + # capture calling convention is quite complicated and in general you are + # only expected to pass to aot_stage2_compile to process. + needs_autograd: bool + + # The FAKE flat arguments which we will do tracing with. Although you + # might naively expect this to be immutable, it's not: when we perform + # tracing, we may execute code that modifies the metadata of inputs, + # causing the args to become "invalid". It's also nontrivial to have a + # "golden" set of fake values and deepcopy them just in time when you + # might destructively mutate them (Voz and I tried very hard to do this). + # So we just periodically renew this field. Don't worry too much about + # this unless you're specifically trying to track down an input metadata + # mutation bug. + # + # (By the way, this is NEVER the joint inputs! Those only ever go in + # AOTGraphCapture) + flat_args: list[FxValue] + + # The descriptor for each argument in flat_args. + flat_args_descs: list[AOTInput] + + # This contains view and mutation information about the function, which we + # detected by doing an initial trace when we created this state. + fw_metadata: ViewAndMutationMeta + + # Top-level configuration. Stage-local compiler choices are threaded + # explicitly rather than mutating this object in place. + aot_config: AOTConfig + + # When performing AOTAutograd traces and other passes, we typically + # require a lot of active context managers; most typically these either + # (1) ensure we are faithfully replicating the original PyTorch context + # managers or (2) toggle some behaviors in PyTorch to make it more + # suitable for tracing. When you use AOTState, you're expected to have + # created an ExitStack, entered it; then while we are running AOTAutograd + # we will add things onto the stack as necessary. When you're all done + # with processing AOTAutograd, you can exit this stack. All functions + # that take AOTState expect the ExitStack to not have been exited yet. + # + # TODO: We potentially could offer a resumable context manager, where you + # can cancel it and reenable it later when you need it. + stack: contextlib.ExitStack + + # The fake tensor mode used during tracing. This is useful for later + # operations that need to create new fake tensors consistent with the + # original trace. + fake_mode: FakeTensorMode + + +FxValue = Tensor | int | SymInt | BackwardState | CustomClassBase + + +class CompilerWrapper: + """ + AOTAutograd needs to do many transformations to the calling convention of the user function + it is tracing, e.g., deduplicating inputs, unpacking subclasses, etc. CompilerWrapper lets + us factor these into compositional stages so we can handle each transformation incrementally + instead of having to do it all at once. + + Since there is a calling convention change, there are two parts to the wrapper: + + 1. The prologue, which is about compile-time behavior: given this original function, what + is the new function with modified calling convention that we should trace with AOTAutograd + to get the FX graph we will do joint passes, partitioning and ultimate Inductor compilation on? + We get (flat_fn, flat_args), the original function under trace and inputs we were + going to feed it, and produce a new function and new inputs to feed it. + + 2. The epilogue, which is about run-time behavior: we have now compiled the modified calling + convention function, we need to wrap it so that we have a new function that has the + original calling convention of the original function, so that our users can call it + at the old signature they expected. We get (compiled_fn, real arguments), the newly + compiled function we need to wrap. + + Note about caching: we do NOT directly serialize the runtime wrappers; instead, they + are reapplied to compiled_fn after we have finished deserializing the compiled_fn. + + Extra metadata that is needed to compute pre or post compile can be passed in via attributes. + """ + + def pre_compile( + self, + flat_fn: TraceFn, + flat_args: list[FxValue], + flat_args_descs: list[AOTInput], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, + ) -> tuple[TraceFn, list[FxValue], list[AOTInput], ViewAndMutationMeta]: + """ + Process the inputs to the compiler_fn. You can pass in extra metadata via kwargs. + Args: + flat_fn: The function to compile + flat_args: Metadata from example inputs of the function to compile + aot_config: AOTConfig passed in at compile time + fw_metadata: ViewAndMutationMeta generated from flat_fn and flat_args + """ + return flat_fn, flat_args, flat_args_descs, fw_metadata + + def post_compile( + self, + compiled_fn: Callable[_P, _R], + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ) -> Callable[_P, _R]: + """ + Given an output of the compiler, wrap it with information received from prologue. + Args: + compiled_fn: Callable after calling compiler_fn + aot_config: AOTConfig after calling prologue + runtime_metadata: ViewAndMutationMeta after calling all wrappers's pre_compile steps. + Example: + + def wrapped_compiled_fn(args): + # do something with args, aot_config, fw_metadata + return compiled_fn(args) + + return wrapped_compiled_fn + """ + return compiled_fn + + +class InductorWrapper: + """ + This is sort of like CompilerWrapper, but it happens at a different part of the lifecycle: + it talks about transformations we do to the traced and partitioned FX graph before we + send it to the Inductor compiler. + + Once again, there are two parts: + + 1. The prologue, which "modifies" the FX graph before we send it to + Inductor. I say "modifies" because... we don't really actually do + anything nontrivial in either of our two implementations. + 2. The epilogue, which modifies the compiled function produced by Inductor + + Although hypothetically these wrappers could be used compositionally in a centralized + wrappers list, in practice they seem to just be invoked manually when needed. + + NB: The flat_args input is sometimes mutated. This is probably naughty but whatever. + """ + + def pre_compile( + self, + fw_module: torch.fx.GraphModule, + flat_args: list[Tensor], + aot_config: AOTConfig, + *, + fw_metadata: ViewAndMutationMeta, + ) -> None: + """ + Process the inputs to the compiler_fn. You can pass in extra metadata via kwargs. + Args: + flat_fn: The function to compile + flat_args: Metadata from example inputs of the function to compile + aot_config: AOTConfig passed in at compile time + fw_metadata: ViewAndMutationMeta generated from flat_fn and flat_args + """ + return + + def post_compile( + self, + compiled_fn: Callable[_P, _R], + aot_config: AOTConfig, + *, + runtime_metadata: ViewAndMutationMeta, + ) -> Callable[_P, _R]: + """ + Given an output of the compiler, wrap it with information received from prologue. + Args: + compiled_fn: Callable after calling compiler_fn + aot_config: AOTConfig after calling prologue + runtime_metadata: ViewAndMutationMeta after calling all wrappers's pre_compile steps. + Example: + + def wrapped_compiled_fn(args): + # do something with args, aot_config, fw_metadata + return compiled_fn(args) + + return wrapped_compiled_fn + """ + return compiled_fn + + +@dataclass +class AOTGraphCapture: # Produced by aot_stage1_graph_capture + # AOTAutograd typically operates by taking complicated graphs and + # desugaring them into simpler graphs that use PyTorch features. These + # wrappers establish invariants so that when we actually do tracing we can + # assume these invariants hold, leading to a simpler tracing + # implementation. However, this means that we have to keep track of how + # to enter/exit these wrappers when passing inputs into the compiled + # graph, among other things! + wrappers: list[CompilerWrapper] + + # The actual captured graph module. In some circumstances (export) this + # graph has a specific calling convention that can be relied upon by + # external callers. In other situations, the calling convention is + # unspecified and only aot_stage2_compile knows how to deal with them. + graph_module: torch.fx.GraphModule + + # When compiling with autograd support, this is the joint_inputs, which is + # larger than the original flat_args as all tangents get inputs. The + # tuple organizes into primals and tangents. When not autograd it's just + # a plain list. + updated_flat_args: list[Any] | tuple[list[Any], list[Any]] + + updated_flat_args_descs: list[AOTInput] | tuple[list[AOTInput], list[AOTInput]] + + # Metadata about subclass inputs/outputs in the graph trace. + maybe_subclass_meta: Any + + +FakifiedFlatArgs = NewType("FakifiedFlatArgs", list[Any]) + + +TOutputCode = TypeVar("TOutputCode", bound="OutputCode") + + +class AOTDispatchCompiler(Protocol): + """ + Represents a fw or bw_compiler passed to AOTAutograd. + """ + + def __call__( + self, + gm: torch.fx.GraphModule, + example_inputs: Sequence[InputType], + ) -> Any: ... + + +# TODO: bikeshed on this name +class SerializableAOTDispatchCompiler(AOTDispatchCompiler): + """ + Represents an AOTDispatchCompiler that returns an OutputCode, and is + therefore cacheable. SerializableAOTDispatchCompiler always return an OutputCode. + A _CompileFxCallable usually gets converted into an AOTDispatchCompiler after binding all of + the kwargs in _CompileFxKwargs. + """ + + def __init__( + self, + output_code_ty: type[TOutputCode], + compiler_fn: Callable[[torch.fx.GraphModule, Sequence[InputType]], TOutputCode], + ) -> None: + # pyrefly: ignore [invalid-type-var] + self.output_code_ty = output_code_ty + # pyrefly: ignore [invalid-type-var] + self.compiler_fn = compiler_fn + + def __call__( + self, + gm: torch.fx.GraphModule, + example_inputs: Sequence[InputType], + ) -> OutputCode: + output_code = self.compiler_fn(gm, example_inputs) + return output_code + + +class FlatFn(Protocol): + def __call__(self, *args: FxValue) -> list[FxValue]: ... + + +class TraceFn(Protocol): + def __call__(self, *args: FxValue) -> tuple[list[FxValue], list[AOTOutput]]: ... + + +class PreppedForAutogradTraceFn(Protocol): + def __call__( + self, + *args: FxValue, + ) -> tuple[tuple[list[FxValue], list[bool]], list[AOTOutput]]: ... + + +class JointTraceFn(Protocol): + handle: JointFnHandle + + def __call__( + self, primals: list[FxValue], tangents: list[FxValue] + ) -> tuple[ + tuple[list[FxValue], list[Tensor | None]], + tuple[list[AOTOutput], list[AOTOutput | None]], + ]: ... + + +@dataclass +class JointWithDescriptors: + _aot_state: AOTState + _aot_graph_capture: AOTGraphCapture + + # The exact order parameters and buffers are expected to be passed into + # the final compiled function. Parameters before buffers. + params_spec: list[str] + buffers_spec: list[str] + + in_spec: pytree.TreeSpec + out_spec: pytree.TreeSpec + + @property + def graph_module(self) -> torch.fx.GraphModule: + return self._aot_graph_capture.graph_module + + @graph_module.setter + def graph_module(self, value: torch.fx.GraphModule) -> None: + self._aot_graph_capture.graph_module = value + + @property + def fake_mode(self) -> FakeTensorMode: + return self._aot_state.fake_mode + + def cache_hash(self) -> str: + """ + Return a hash string suitable for use as a cache key. This method + exists to decouple cache key generation from __str__/__repr__, so + that display-oriented changes don't accidentally affect caching. + """ + from hashlib import sha256 + + return sha256(str(self).encode("utf-8")).hexdigest() diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/source_emit.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/source_emit.py new file mode 100644 index 0000000000000000000000000000000000000000..23799fb6522c2690ae284173e47e8940a8b0c681 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/source_emit.py @@ -0,0 +1,537 @@ +"""Reconstruct live Python values as standalone, auditable source. + +The composer (to_standalone_python.py) inlines AOTAutograd's runtime wrappers, which +close over baked metadata objects (view-replay recipes, tensor-subclass specs, ...). +This module turns such a live object into a Python expression that reconstructs an +EQUAL value -- emitted as readable source, never a pickle / base64 blob -- or raises +NotImplementedError if it cannot be expressed. ``emit_value`` is the public entry +point; ``_emit_value`` is the internal recursion (it threads the traversal state); +``_emit_via_reduce`` is the pickle-reduce-as-source fallback and ``_REBUILD_HELPER`` is +the ``_rebuild`` function it references in generated code. Kept as a leaf module so it +is safe to import anywhere in the package. +""" + +from __future__ import annotations + +import inspect +from typing import Any, NewType, TYPE_CHECKING + + +# id() returns an object identity used here only as a recursion/alias key, not an +# arbitrary int. Shadowing the builtin under TYPE_CHECKING tags every ``id(obj)`` as +# ``_ObjId`` so ``set[_ObjId]`` propagates without wrapping each call site; the real +# builtin runs at runtime (NewType is identity), so behavior is unchanged. +_ObjId = NewType("_ObjId", int) + +if TYPE_CHECKING: + + def id(obj: object, /) -> _ObjId: ... + + +# The runtime helper for reduce-based metadata reconstruction (see _emit_via_reduce). +# Emitted only when some baked value actually needs it -- many graphs (e.g. a plain +# module with no tensor-subclass metadata) reference none, so it would just be dead +# code. Includes its own trailing blank lines so the splice stays clean. +_REBUILD_HELPER: list[str] = [ + "def _rebuild(obj, state):", + " # Apply pickle-style reduce state to a freshly __new__'d object, emitted as", + " # readable source instead of an opaque blob (no pickle.loads). Used for the", + " # opaque value leaves of baked metadata -- e.g. tensor-subclass placement", + " # objects -- mirroring pickle's load_build: prefer __setstate__, else update", + " # __dict__ (and slot state for the (dict, slots) 2-tuple form).", + " if state is None:", + " return obj", + " if hasattr(obj, '__setstate__'):", + " obj.__setstate__(state)", + " return obj", + " slotstate = None", + " if isinstance(state, tuple) and len(state) == 2:", + " state, slotstate = state", + " if state:", + " obj.__dict__.update(state)", + " if slotstate:", + " for _k, _v in slotstate.items():", + " setattr(obj, _k, _v)", + " return obj", + "", + "", +] + + +def _emit_importable(obj: Any, imports: set[str]) -> str: + """Return an expression referencing ``obj`` via its defining module (recording the + import). Works for classes, functions, and modules. Raises if ``obj`` is not + reachable as ``module.qualname`` (e.g. a local or lambda), since then it cannot be + reproduced in the standalone module without embedding it.""" + import importlib + + module = getattr(obj, "__module__", None) + qualname = getattr(obj, "__qualname__", None) + if not module or not qualname or "<" in qualname: + raise NotImplementedError( + f"compile_to_python cannot reference {obj!r} by import: it has no " + "module/qualname or is a local definition." + ) + target: Any = importlib.import_module(module) + for part in qualname.split("."): + target = getattr(target, part, None) + if target is not obj: + raise NotImplementedError( + f"compile_to_python cannot reference {qualname} from {module}: it does " + "not round-trip to the same object." + ) + imports.add(f"import {module}") + return f"{module}.{qualname}" + + +def _reject_shared_mutable(obj: Any, _seen: set[_ObjId]) -> None: + """Fail loud when a mutable object is reached more than once in a single traversal: + it would be emitted as two independent source literals, silently dropping the + shared-identity aliasing (mutating one copy would no longer affect the other), which + is not expressible as a source literal today. Routed here are the kinds reconstructed + as fresh MUTABLE copies whose aliasing a flat literal cannot preserve: list / dict / + set, bytearray, non-frozen dataclasses, and the opaque _emit_via_reduce value objects. + Kinds treated as immutable value objects are exempt -- scalars, tuple / frozenset, frozen + dataclasses, and the recipe-like value objects emitted by their own branches + (functools.partial, ViewMeta, ViewMetaSequence), which are never mutated after + reconstruction -- so a shared one of those still emits fine. ``_seen`` is threaded in + place across the whole traversal (unlike the per-level in-progress cycle set), so it + catches shared siblings, not just self-referential ancestors.""" + if id(obj) in _seen: + raise NotImplementedError( + f"compile_to_python cannot bake a shared mutable {type(obj).__qualname__}: " + "it is reached more than once in the value being baked, so emitting it as " + "independent source literals would silently drop the shared-identity " + "aliasing." + ) + _seen.add(id(obj)) + + +def emit_value(obj: Any, imports: set[str]) -> str: + """Emit a Python expression (valid in the generated module) that rebuilds ``obj`` + from source -- the pickle-free replacement for embedding a base64 blob. + + Public entry point: recurses through containers and metadata so the artifact stays + auditable and exec'ing it never runs ``pickle.loads``. Bottoms out for opaque value + objects (e.g. tensor-subclass placement objects) at the pickle reduce protocol, but + EMITTED AS SOURCE via ``_rebuild`` (see ``_emit_via_reduce``). Raises + NotImplementedError at any leaf that cannot be expressed as source (a live tensor, a + lambda, a still-symbolic Sym*), for a self-referential structure, or for a shared + mutable object whose aliasing a flat source literal cannot preserve. + + Any import needed by the emitted expression is recorded into ``imports`` (as ``import + module`` statements).""" + return _emit_value(obj, imports, set(), set()) + + +def _emit_value( + obj: Any, + imports: set[str], + _in_progress: set[_ObjId], + _seen: set[_ObjId], +) -> str: + """Internal recursion behind ``emit_value``; requires the traversal state its guards + thread. Call ``emit_value`` from outside this module. + + ``_in_progress`` is an identity-keyed set of the objects currently being emitted on + this recursion PATH (copied per level, like a call stack): revisiting one means the + metadata is self-referential and cannot be a source literal, so we raise rather than + recurse forever. ``_seen`` is an identity-keyed set of every MUTABLE object already + emitted anywhere in this traversal (threaded in place, like ``imports``): revisiting + one means the same mutable object is shared across positions, whose aliasing a flat + literal cannot preserve, so we raise (see ``_reject_shared_mutable``).""" + import dataclasses + import enum + import functools + import math + import types + + import torch + from torch._C import _functionalization as _F + from torch.fx.experimental.symbolic_shapes import SymIntEqByExpr + + from .functional_utils import ViewMetaSequence + + # Live tensors / storages must never be baked: their reduce form is a + # ``torch.storage._load_from_bytes(b'...')`` pickle blob, which both embeds the + # raw weight bytes and invokes ``pickle.loads`` at exec time -- violating the + # module's no-weights-baked / never-pickle.loads / fully-auditable guarantees. + # Reject them explicitly here, before they can fall through to _emit_via_reduce. + # A non-Tensor object whose reduce IS ``_load_from_bytes`` (a wrapper that + # delegates pickling to a storage's bytes) is caught at the reduce callable in + # _emit_via_reduce, where that callable is actually visible. + if isinstance( + obj, (torch.Tensor, torch.storage.TypedStorage, torch.UntypedStorage) + ): + raise NotImplementedError( + f"compile_to_python cannot bake a live {type(obj).__qualname__} into " + "standalone source: that would embed raw tensor bytes and require " + "pickle.loads at exec time. The standalone artifact bakes no weights." + ) + + # Primitives first, before any cycle / alias bookkeeping: those guards never matter + # for immutable scalars, and returning here skips the per-level in-progress copy and + # the mutable-alias check for the (very common) scalar leaves. + # + # Non-finite floats: repr() gives bare ``inf`` / ``-inf`` / ``nan``, which are + # NameErrors in the generated module (it imports no such names). Emit a + # self-contained constructor instead. Likewise for a complex with a non-finite + # component (repr would be e.g. ``(inf+0j)``). + if isinstance(obj, float) and not math.isfinite(obj): + if math.isnan(obj): + return "float('nan')" + return "float('inf')" if obj > 0 else "float('-inf')" + if isinstance(obj, complex) and not ( + math.isfinite(obj.real) and math.isfinite(obj.imag) + ): + # Use the module-level recursion directly (the in-body shadow is not defined until + # after the guards below); the components are floats, so they bottom out above. + real = _emit_value_recurse(obj.real, imports, _in_progress, _seen) + imag = _emit_value_recurse(obj.imag, imports, _in_progress, _seen) + return f"complex({real}, {imag})" + # Plain constants reproduce via repr (but not IntEnum/StrEnum members, whose repr + # is not valid source -- those fall through to the enum handler below). Match EXACT + # builtin types only: a subclass of a builtin scalar (e.g. a ``str`` subclass, or an + # ``int`` subclass with a constructor-style ``__repr__``) would mis-bake under repr + # -- losing its type or emitting a NameError -- so it must fall through to the + # importable/reduce path, which reconstructs it faithfully or raises. + if obj is None or ( + not isinstance(obj, enum.Enum) + and type(obj) in (bool, int, float, complex, str, bytes) + ): + return repr(obj) + # bytearray is the one mutable builtin whose repr round-trips, so it is emitted as a + # repr literal like the immutable scalars above -- but being mutable it needs the same + # shared-alias guard the containers get (reached twice it would become two independent + # literals, silently dropping the aliasing). It cannot be self-referential, so it needs + # only the alias check and no cycle guard. + if type(obj) is bytearray: + _reject_shared_mutable(obj, _seen) + return repr(obj) + + # Cycle guard: thread an identity-keyed in-progress set down the recursion so a + # self-referential metadata object raises NotImplementedError naming the offending + # type instead of recursing until RecursionError. Primitives already returned above, + # so no immutable-scalar exemption is needed here. + if id(obj) in _in_progress: + raise NotImplementedError( + f"compile_to_python cannot bake {type(obj).__qualname__}: it is " + "self-referential, which is not expressible as source." + ) + # Alias guard: a mutable container reached twice anywhere in the traversal would be + # emitted as two independent literals, silently dropping the shared-identity aliasing. + # Match EXACT list/dict/set only -- those are the types the container branches below + # emit; a subclass falls through to _emit_via_reduce, which tracks it there (matching + # here too would double-count the same object and falsely reject a single subclass). + if type(obj) in (list, dict, set): + _reject_shared_mutable(obj, _seen) + + _child = _in_progress | {id(obj)} + + def _emit_value(obj: Any, imports: set[str]) -> str: + # Shadow the module-level recursion entry point so every recursive call in + # this function body automatically threads the current in-progress set (with + # the parent ``obj`` added) plus the traversal-wide seen set, without touching + # each call site. + return _emit_value_recurse(obj, imports, _child, _seen) + + # torch scalar singletons whose repr round-trips, plus device/Size/SymInt. + if isinstance(obj, (torch.dtype, torch.layout, torch.memory_format)): + imports.add("import torch") + return repr(obj) + if isinstance(obj, torch.device): + imports.add("import torch") + return f"torch.device({str(obj)!r})" + if isinstance(obj, torch.Size): + imports.add("import torch") + return f"torch.Size([{', '.join(_emit_value(x, imports) for x in obj)}])" + if isinstance(obj, torch.SymInt): + concrete = obj.node.maybe_as_int() + if concrete is None: + raise NotImplementedError( + "compile_to_python cannot bake a symbolic SymInt; precompile " + "specializes to static shapes." + ) + return repr(concrete) + # SymBool / SymFloat get the same treatment as SymInt (bake the concrete value, reject + # a still-symbolic one with the static-shapes message) so all sym scalar types are + # handled consistently instead of falling into the reduce path with an opaque error. + if isinstance(obj, torch.SymBool): + concrete_bool = obj.node.maybe_as_bool() + if concrete_bool is None: + raise NotImplementedError( + "compile_to_python cannot bake a symbolic SymBool; precompile " + "specializes to static shapes." + ) + return repr(concrete_bool) + if isinstance(obj, torch.SymFloat): + concrete_float = obj.node.maybe_as_float() + if concrete_float is None: + raise NotImplementedError( + "compile_to_python cannot bake a symbolic SymFloat; precompile " + "specializes to static shapes." + ) + return repr(concrete_float) + + # Importable definitions: classes, functions, modules. + if isinstance(obj, type) or inspect.isfunction(obj) or inspect.isbuiltin(obj): + return _emit_importable(obj, imports) + if isinstance(obj, types.ModuleType): + imports.add(f"import {obj.__name__}") + return obj.__name__ + + # Python enums and pybind11 enums (e.g. InverseReturnMode) both reference a member + # by name off the importable type. pybind enum members are not singletons (as_tuple + # hands back fresh copies), so match by value via the type's __members__ map. + members = getattr(type(obj), "__members__", None) + name = getattr(obj, "name", None) + is_enum_like = isinstance(obj, enum.Enum) or ( + members is not None and name in members and members[name] == obj + ) + if is_enum_like: + if name is not None and members is not None and name in members: + return f"{_emit_importable(type(obj), imports)}.{name}" + # A combined Flag/IntFlag member (A | B) has no single member name, so emit by + # value -- ``Type(value)`` reproduces the same combined member. A non-Flag enum + # with no resolvable name is not source-expressible, so reject it rather than + # emit ``Type.None`` (a SyntaxError that would break the whole module). + if isinstance(obj, enum.Flag): + cls = _emit_importable(type(obj), imports) + return f"{cls}({_emit_value(obj.value, imports)})" + # Defensive backstop, effectively unreachable for constructible inputs: a + # pure-Python non-Flag enum.Enum always resolves a name in __members__ (it rejects + # unregistered values with ValueError) and so returns by-name above, and a pybind + # enum-like value only reaches here via the ``name in members`` arm that already + # returned. Kept so any future name-less enum-like type fails loudly, not silently. + raise NotImplementedError( + f"compile_to_python cannot bake enum member {obj!r}: it has no resolvable " + "member name and is not a Flag." + ) + + if isinstance(obj, functools.partial): + parts = [_emit_value(obj.func, imports)] + parts += [_emit_value(a, imports) for a in obj.args] + parts += [ + f"{k}={_emit_value(v, imports)}" for k, v in (obj.keywords or {}).items() + ] + imports.add("import functools") + return f"functools.partial({', '.join(parts)})" + + # AOT view-replay recipes: ViewMeta C++ objects round-trip through as_tuple(); + # ViewMetaSequence has no public constructor so use its _from_parts factory; + # SymIntEqByExpr wraps a sympy expr that must be a concrete integer here. + if isinstance(obj, _F.ViewMeta): + # as_tuple lives on the ViewMeta subclass bindings (create_binding_with_pickle), + # not on the base ViewMeta stub, so pyrefly cannot see it on the isinstance type. + tup = obj.as_tuple() # pyrefly: ignore[missing-attribute] + return f"{_emit_importable(type(obj), imports)}({_emit_value(tuple(tup), imports)})" + if isinstance(obj, ViewMetaSequence): + cls = _emit_importable(ViewMetaSequence, imports) + seq = _emit_value(list(obj.sequence), imports) + return f"{cls}._from_parts({seq}, {_emit_value(obj.metadata, imports)})" + if isinstance(obj, SymIntEqByExpr): + if not getattr(obj.val, "is_Integer", False): + raise NotImplementedError( + "compile_to_python cannot bake symbolic view metadata; precompile " + "specializes to static shapes." + ) + return f"{_emit_importable(SymIntEqByExpr, imports)}({int(obj.val)})" + + # namedtuple before plain tuple (it has a richer, by-name constructor). The plain + # container branches match EXACT builtin types only (like the scalar branch above): a + # container SUBCLASS (e.g. a ``list`` subclass carrying extra state) would otherwise be + # silently downcast to its base type, dropping the subclass and its state. Subclasses + # fall through to _emit_via_reduce, which reconstructs them faithfully or rejects them + # (its listitems/dictitems guard fires for list/dict subclasses). + if isinstance(obj, tuple) and hasattr(obj, "_fields"): + cls = _emit_importable(type(obj), imports) + return f"{cls}({', '.join(_emit_value(x, imports) for x in obj)})" + if type(obj) is tuple: + items = [_emit_value(x, imports) for x in obj] + return f"({items[0]},)" if len(items) == 1 else f"({', '.join(items)})" + if type(obj) is list: + return f"[{', '.join(_emit_value(x, imports) for x in obj)}]" + if type(obj) is set or type(obj) is frozenset: + ctor = "frozenset" if isinstance(obj, frozenset) else "set" + # Iteration order of a set is not byte-stable across processes, so emit the + # elements in a canonical order: sort them by their EMITTED SOURCE EXPRESSION -- + # the exact text that lands in the artifact, so it is the only key guaranteed to + # be byte-stable across processes. A ``repr``-keyed sort would silently admit a + # custom-but-nondeterministic ``__repr__`` (e.g. one embedding ``id(self)``), + # making the emitted source differ run to run, and a numeric sort would raise on a + # ``nan`` element (``sorted`` does not) and does not exist for mixed types. Each + # element is emitted exactly once (into the real ``imports``, since every element + # emitted is one that lands in the output) and then the resulting expressions are + # sorted -- which forces each element through the same source-expressibility gate, + # so a non-source-expressible element raises here exactly as at final emit. + exprs = sorted(_emit_value(x, imports) for x in obj) + return f"{ctor}([{', '.join(exprs)}])" + if type(obj) is dict: + items = [ + f"{_emit_value(k, imports)}: {_emit_value(v, imports)}" + for k, v in obj.items() + ] + return f"{{{', '.join(items)}}}" + + # Dataclasses (e.g. MetadataKey, SubclassViewMetaSequence) reproduce field-by-field + # through their generated constructor, passing only the init fields. That path is + # faithful ONLY when the object carries no state outside those init fields: a + # non-init field (init=False) holding state, or a __post_init__ that derives state + # the constructor call would not reproduce, would be silently dropped. Guard it the + # same way the rest of this module guards opaque leaves -- reject rather than emit a + # subtly-wrong artifact -- by round-tripping through the constructor and requiring + # the rebuilt instance to compare equal to the original. The in-scope metadata + # types (e.g. MetadataKey) are plain value dataclasses, so they round-trip and keep + # working; a type with hidden/derived state does not and raises NotImplementedError + # naming itself. This strategy needs value equality: a dataclass declared eq=False + # inherits object.__eq__ (identity), so rebuilt == obj is ALWAYS False even for a + # pure value object -- detect that and fall through to _emit_via_reduce (which has its + # own source-expressibility rejects) rather than spuriously rejecting it. + if ( + dataclasses.is_dataclass(obj) + and not isinstance(obj, type) + and type(obj).__eq__ is not object.__eq__ + ): + # A non-frozen dataclass is mutable, so it gets the same shared-alias guard as the + # containers: reached twice it would be emitted as two independent constructor + # calls, silently dropping the shared-identity aliasing. A frozen dataclass is + # immutable and stays exempt, like a tuple. + if not obj.__dataclass_params__.frozen: + _reject_shared_mutable(obj, _seen) + cls = _emit_importable(type(obj), imports) + fields = dataclasses.fields(obj) + init_kwargs = {f.name: getattr(obj, f.name) for f in fields if f.init} + try: + # type(obj) is the concrete dataclass at runtime, not the protocol pyrefly + # infers from the is_dataclass narrowing; the call is correct. + rebuilt = type(obj)(**init_kwargs) # pyrefly: ignore[bad-instantiation] + round_trips = rebuilt == obj + except Exception: + round_trips = False + if not round_trips: + raise NotImplementedError( + f"compile_to_python cannot bake dataclass {type(obj).__qualname__}: it " + "does not round-trip through its constructor from its init fields alone " + "(it likely has a stateful non-init field or a __post_init__ deriving " + "state the constructor call would not reproduce), so emitting only the " + "init fields would silently drop that state." + ) + kw = [f"{k}={_emit_value(v, imports)}" for k, v in init_kwargs.items()] + return f"{cls}({', '.join(kw)})" + + return _emit_via_reduce(obj, imports, _child, _seen) + + +# The recursion entry point used by the in-body shadow of ``_emit_value`` and by +# ``_emit_via_reduce`` to thread the identity-keyed in-progress + seen traversal sets. +_emit_value_recurse = _emit_value + + +def _emit_via_reduce( + obj: Any, + imports: set[str], + _in_progress: set[_ObjId], + _seen: set[_ObjId], +) -> str: + """Last resort for opaque value objects (e.g. DTensor placements, which are C++ + objects with no source-friendly constructor): reconstruct from the pickle reduce + protocol, but EMITTED AS SOURCE -- ``cls.__new__(cls)`` plus ``_rebuild`` applying + the reduce state -- so there is no ``pickle.loads`` at exec time and the bytes + are readable. The reduce state recurses back through ``_emit_value``, so any + non-source-expressible leaf inside it still raises.""" + import copyreg + + import torch + + # These reduce value objects are mutable, so the same guard the containers get in + # _emit_value applies: an object reached twice would be emitted as two independent + # reconstructions, silently dropping the shared-identity aliasing. + _reject_shared_mutable(obj, _seen) + + def _emit_value(obj: Any, imports: set[str]) -> str: + # Continue threading the cycle guard + seen set through the reduce-state recursion. + return _emit_value_recurse(obj, imports, _in_progress, _seen) + + try: + reduced = obj.__reduce_ex__(2) + except Exception as e: + raise NotImplementedError( + f"compile_to_python cannot make {type(obj).__module__}." + f"{type(obj).__qualname__} self-contained: it is not source-expressible " + f"and has no usable reduce ({type(e).__name__})." + ) from e + if not isinstance(reduced, tuple) or len(reduced) < 2: + raise NotImplementedError( + f"compile_to_python cannot reconstruct {type(obj).__qualname__}: " + "unsupported __reduce__ form." + ) + func, args = reduced[0], reduced[1] + # The reduce protocol requires the second element to be a tuple of constructor args; + # validate once here so all three func branches below normalize a malformed reduce + # into the uniform NotImplementedError contract rather than leaking a bare TypeError. + if not isinstance(args, tuple): + raise NotImplementedError( + f"compile_to_python cannot reconstruct {type(obj).__qualname__}: reduce " + "args field is not a tuple." + ) + state = reduced[2] if len(reduced) > 2 else None + listitems = reduced[3] if len(reduced) > 3 else None + dictitems = reduced[4] if len(reduced) > 4 else None + # A reduce whose callable is ``torch.storage._load_from_bytes`` would embed raw + # bytes and require a pickle.loads-equivalent at exec time. This is the ONLY place + # that callable is visible (it is the reduce result's func, not the object's + # __reduce_ex__ method), so reject it here to uphold the no-bytes / fully-auditable + # guarantee for any non-Tensor wrapper that delegates pickling to storage bytes. + if func is getattr(torch.storage, "_load_from_bytes", None): + raise NotImplementedError( + f"compile_to_python cannot bake {type(obj).__qualname__} into standalone " + "source: its reduce is torch.storage._load_from_bytes, which would embed " + "raw bytes and require pickle.loads at exec time." + ) + if listitems is not None or dictitems is not None: + raise NotImplementedError( + f"compile_to_python cannot reconstruct {type(obj).__qualname__}: reduce " + "produced list/dict items (container subclass)." + ) + # A non-None 6th element is a protocol-5 ``state_setter``: the object opted out of + # the default __setstate__/__dict__ install that ``_rebuild`` implements, so applying + # state via _rebuild would silently use the wrong mechanism. Reject rather than emit + # a subtly-wrong object. + state_setter = reduced[5] if len(reduced) > 5 else None + if state_setter is not None: + raise NotImplementedError( + f"compile_to_python cannot reconstruct {type(obj).__qualname__}: reduce " + "produced a state_setter (protocol-5 form) that _rebuild cannot apply." + ) + if func is getattr(copyreg, "__newobj__", None): + if not args: + raise NotImplementedError( + f"compile_to_python cannot reconstruct {type(obj).__qualname__}: " + "__newobj__ reduce produced no class argument." + ) + cls = _emit_value(args[0], imports) + extra = ", ".join(_emit_value(a, imports) for a in args[1:]) + base = f"{cls}.__new__({cls}{', ' + extra if extra else ''})" + elif func is getattr(copyreg, "__newobj_ex__", None): + if not ( + isinstance(args, tuple) + and len(args) == 3 + and isinstance(args[1], tuple) + and isinstance(args[2], dict) + ): + raise NotImplementedError( + f"compile_to_python cannot reconstruct {type(obj).__qualname__}: " + "__newobj_ex__ reduce did not produce a (cls, args, kwargs) triple." + ) + cls_obj, new_args, new_kwargs = args + cls = _emit_value(cls_obj, imports) + pos = ", ".join(_emit_value(a, imports) for a in new_args) + kw = ", ".join(f"{k}={_emit_value(v, imports)}" for k, v in new_kwargs.items()) + joined = ", ".join(p for p in (pos, kw) if p) + base = f"{cls}.__new__({cls}{', ' + joined if joined else ''})" + else: + func_expr = _emit_value(func, imports) + base = f"{func_expr}({', '.join(_emit_value(a, imports) for a in args)})" + if state is None: + return base + return f"_rebuild({base}, {_emit_value(state, imports)})" diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/standalone_runtime.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/standalone_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..9c02774b31ff745648edfdf839518df334a8d256 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/standalone_runtime.py @@ -0,0 +1,43 @@ +"""Runtime-support surface for standalone artifacts. + +Modules emitted by ``torch._functorch.aot_autograd.compile_to_python`` inline +AOTAutograd's codegen'd prelude/epilogue, which closes over a few small runtime +helpers (output-alias regeneration, etc.). Rather than have the generated code +reach into scattered AOTAutograd internals -- whose exact locations are not a +stable contract -- it imports those helpers from this one module. This is the +intentional, single dependency surface of a standalone artifact: keep it small and +stable, and update generated-artifact compatibility deliberately if it changes. +""" + +# Importing ``runtime_wrappers`` directly in a fresh process pulls in a name +# (e.g. AutogradLazyBackwardCompileInfo) that is only bound once the dynamo init +# chain has run, so importing it first triggers a circular ImportError. Force the +# dynamo/aot chain to fully initialize before the ``from .runtime_wrappers`` +# import below so a bare ``import torch`` artifact stays self-contained. +import torch._dynamo # noqa: F401 +from torch._prims_common import CUDARngStateHelper + +# IDENTITY CONTRACT: these names MUST be plain re-exports that preserve the original +# object identity -- never wrap, decorate, or alias them (e.g. functools.wraps, a thin +# forwarding lambda, a partial). to_standalone_python._known_helper_table keys on +# id() of these exact objects to recognize a global the codegen'd wrappers close over. +# A wrapper would change id(), so the table lookup would silently miss and that global +# would route to its internal AOTAutograd location instead of this stable surface. +# The same contract covers ``CUDARngStateHelper`` (imported above for circular-import +# ordering): the table keys on id() of its ``get_torch_state_as_tuple`` / +# ``set_new_offset`` staticmethods, so it too must not be wrapped or aliased. +from .functional_utils import gen_alias_from_base +from .runtime_wrappers import ( + _unwrap_tensoralias, + mark_dynamo_propagated_dynamic_indices, +) +from .utils import normalize_as_list + + +__all__ = [ + "gen_alias_from_base", + "_unwrap_tensoralias", + "mark_dynamo_propagated_dynamic_indices", + "normalize_as_list", + "CUDARngStateHelper", +]